diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow-2.15.1.dist-info/INSTALLER b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow-2.15.1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow-2.15.1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow-2.15.1.dist-info/LICENSE b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow-2.15.1.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..12d255f8e0f049d3c3127e71788e219b86cdf55b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow-2.15.1.dist-info/LICENSE @@ -0,0 +1,251 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +## Some of TensorFlow's code is derived from Caffe, which is subject to the following copyright notice: + +COPYRIGHT + +All contributions by the University of California: + +Copyright (c) 2014, The Regents of the University of California (Regents) +All rights reserved. + +All other contributions: + +Copyright (c) 2014, the respective contributors +All rights reserved. + +Caffe uses a shared copyright model: each contributor holds copyright over +their contributions to Caffe. The project versioning records all such +contribution and copyright details. If a contributor wants to further mark +their specific copyright on a particular contribution, they should indicate +their copyright solely in the commit message of the change when it is +committed. + +LICENSE + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +CONTRIBUTION AGREEMENT + +By contributing to the BVLC/caffe repository through pull-request, comment, +or otherwise, the contributor releases their content to the +license and copyright terms herein. \ No newline at end of file diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow-2.15.1.dist-info/METADATA b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow-2.15.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..1c5a038e6c0eb70673b5b7c167c9a8c7b312b771 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow-2.15.1.dist-info/METADATA @@ -0,0 +1,81 @@ +Metadata-Version: 2.1 +Name: tensorflow +Version: 2.15.1 +Summary: TensorFlow is an open source machine learning framework for everyone. +Home-page: https://www.tensorflow.org/ +Download-URL: https://github.com/tensorflow/tensorflow/tags +Author: Google Inc. +Author-email: packages@tensorflow.org +License: Apache 2.0 +Keywords: tensorflow tensor machine learning +Classifier: Development Status :: 5 - Production/Stable +Classifier: Environment :: GPU :: NVIDIA CUDA :: 11.8 +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: Education +Classifier: Intended Audience :: Science/Research +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Topic :: Scientific/Engineering +Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence +Classifier: Topic :: Scientific/Engineering :: Mathematics +Classifier: Topic :: Software Development +Classifier: Topic :: Software Development :: Libraries +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Requires-Python: >=3.9 +Description-Content-Type: text/markdown +License-File: LICENSE +Requires-Dist: absl-py (>=1.0.0) +Requires-Dist: astunparse (>=1.6.0) +Requires-Dist: flatbuffers (>=23.5.26) +Requires-Dist: gast (!=0.5.0,!=0.5.1,!=0.5.2,>=0.2.1) +Requires-Dist: google-pasta (>=0.1.1) +Requires-Dist: h5py (>=2.9.0) +Requires-Dist: libclang (>=13.0.0) +Requires-Dist: ml-dtypes (~=0.3.1) +Requires-Dist: numpy (<2.0.0,>=1.23.5) +Requires-Dist: opt-einsum (>=2.3.2) +Requires-Dist: packaging +Requires-Dist: protobuf (!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5,<5.0.0dev,>=3.20.3) +Requires-Dist: setuptools +Requires-Dist: six (>=1.12.0) +Requires-Dist: termcolor (>=1.1.0) +Requires-Dist: typing-extensions (>=3.6.6) +Requires-Dist: wrapt (<1.15,>=1.11.0) +Requires-Dist: tensorflow-io-gcs-filesystem (>=0.23.1) +Requires-Dist: grpcio (<2.0,>=1.24.3) +Requires-Dist: tensorboard (<2.16,>=2.15) +Requires-Dist: tensorflow-estimator (<2.16,>=2.15.0) +Requires-Dist: keras (<2.16,>=2.15.0) +Requires-Dist: tensorflow-cpu-aws (==2.15.1) ; platform_system == "Linux" and (platform_machine == "arm64" or platform_machine == "aarch64") +Requires-Dist: tensorflow-intel (==2.15.1) ; platform_system == "Windows" +Provides-Extra: and-cuda +Requires-Dist: nvidia-cublas-cu12 (==12.2.5.6) ; extra == 'and-cuda' +Requires-Dist: nvidia-cuda-cupti-cu12 (==12.2.142) ; extra == 'and-cuda' +Requires-Dist: nvidia-cuda-nvcc-cu12 (==12.2.140) ; extra == 'and-cuda' +Requires-Dist: nvidia-cuda-nvrtc-cu12 (==12.2.140) ; extra == 'and-cuda' +Requires-Dist: nvidia-cuda-runtime-cu12 (==12.2.140) ; extra == 'and-cuda' +Requires-Dist: nvidia-cudnn-cu12 (==8.9.4.25) ; extra == 'and-cuda' +Requires-Dist: nvidia-cufft-cu12 (==11.0.8.103) ; extra == 'and-cuda' +Requires-Dist: nvidia-curand-cu12 (==10.3.3.141) ; extra == 'and-cuda' +Requires-Dist: nvidia-cusolver-cu12 (==11.5.2.141) ; extra == 'and-cuda' +Requires-Dist: nvidia-cusparse-cu12 (==12.1.2.141) ; extra == 'and-cuda' +Requires-Dist: nvidia-nccl-cu12 (==2.16.5) ; extra == 'and-cuda' +Requires-Dist: nvidia-nvjitlink-cu12 (==12.2.140) ; extra == 'and-cuda' + +[![Python](https://img.shields.io/pypi/pyversions/tensorflow.svg?style=plastic)](https://badge.fury.io/py/tensorflow) +[![PyPI](https://badge.fury.io/py/tensorflow.svg)](https://badge.fury.io/py/tensorflow) + +TensorFlow is an open source software library for high performance numerical +computation. Its flexible architecture allows easy deployment of computation +across a variety of platforms (CPUs, GPUs, TPUs), and from desktops to clusters +of servers to mobile and edge devices. + +Originally developed by researchers and engineers from the Google Brain team +within Google's AI organization, it comes with strong support for machine +learning and deep learning and the flexible numerical computation core is used +across many other scientific domains. TensorFlow is licensed under [Apache +2.0](https://github.com/tensorflow/tensorflow/blob/master/LICENSE). diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow-2.15.1.dist-info/RECORD b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow-2.15.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..3578bfb72a7924d096be56e1c796eaf935ef279b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow-2.15.1.dist-info/RECORD @@ -0,0 +1,14714 @@ +../../../bin/estimator_ckpt_converter,sha256=-_I-98wkL2Pb-TvUmB5a-gQbDEV58CcF7VgutLjxyik,272 +../../../bin/import_pb_to_tensorboard,sha256=zrhwgtNSblP1Fcr07vJ789d-NrjUu9736CW881fFawA,256 +../../../bin/saved_model_cli,sha256=Xdg6L-M05Adt8Nhz3WRTO16avv6LDiei_gTgM12Tfdo,247 +../../../bin/tensorboard,sha256=OYT8DN140qDWkgahFSsFGWahVm5hlBHgcx6NIh7x0gg,232 +../../../bin/tf_upgrade_v2,sha256=PqatVsx2YQE_Yge3sbmGyt6ghpLUXuU2YmGZMyCMD2g,257 +../../../bin/tflite_convert,sha256=PO5JLSs1YpdHv5AkLhJ6kCt4u3NkJaAFZcBQLppSmu8,245 +../../../bin/toco,sha256=PO5JLSs1YpdHv5AkLhJ6kCt4u3NkJaAFZcBQLppSmu8,245 +../../../bin/toco_from_protos,sha256=TJ8KFWeWiphbGVOAFVdjBCNgFYejYb2C0M2qPyRf52c,252 +tensorflow-2.15.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +tensorflow-2.15.1.dist-info/LICENSE,sha256=ccaRXQQmV3KgM5vtRydpQsZ4tFzAFTQhDr5phP0a7GU,13575 +tensorflow-2.15.1.dist-info/METADATA,sha256=VRL0s_bnF0OcKcl3AxzQh8Ak4ZpYwyhaGSRMF6YHElY,4197 +tensorflow-2.15.1.dist-info/RECORD,, +tensorflow-2.15.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow-2.15.1.dist-info/WHEEL,sha256=nKSwEH5fkxvG0Vdj1Hx7vbuU-SGQ9Nxl4yFFsCilvhs,152 +tensorflow-2.15.1.dist-info/entry_points.txt,sha256=nqYpYvE6eeeaoTWpO0GTgDf_CvggrQKGMzi9-M3RR0M,549 +tensorflow-2.15.1.dist-info/top_level.txt,sha256=-I2lqWdVdXElk2-uuqVf_fe9SUdeNTSKZsS9W1IKiUo,23 +tensorflow/THIRD_PARTY_NOTICES.txt,sha256=-77cYZ0gwmteSGv4Ks2x7-r_8DL7XIVENWUZJK_sDLg,476563 +tensorflow/__init__.py,sha256=sE61V9_NkW5B6sWNH2J5mHnZtiFHh6WlEGnpdE-RNcQ,29449 +tensorflow/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/_api/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/_api/v2/__internal__/__init__.py,sha256=6um6Jq5ED4Ju8dSglM9mewzkGA8_cFdBfhWmXd2AZxs,2518 +tensorflow/_api/v2/__internal__/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/__internal__/autograph/__init__.py,sha256=lS3dqn1D4kpefRtfAEh1wVeZtDso4hyj0Xc9CCxxLPA,374 +tensorflow/_api/v2/__internal__/autograph/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/__internal__/decorator/__init__.py,sha256=SWznSTRgIg5Y8yB44TEuut9brkbVo7BW_7y-IM06hlA,374 +tensorflow/_api/v2/__internal__/decorator/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/__internal__/dispatch/__init__.py,sha256=rCiZMvp1LrrXMp4-VJy8yOINaCXzcnJNgqhFF-LC2ck,440 +tensorflow/_api/v2/__internal__/dispatch/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/__internal__/distribute/__init__.py,sha256=E6CcR7j71mXzPSZ8iAe2BMPovjjpzZS6EDeUIdcduRU,715 +tensorflow/_api/v2/__internal__/distribute/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/__internal__/distribute/combinations/__init__.py,sha256=vr_MhCj9cAI8Y1wJ6j45m6THSLNDR1WDlLiCclxF9GQ,3140 +tensorflow/_api/v2/__internal__/distribute/combinations/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/__internal__/distribute/interim/__init__.py,sha256=1Y0gGfMGfjIixKdQzM0K2JhRTAnvS-ch87V__Df1QEQ,317 +tensorflow/_api/v2/__internal__/distribute/interim/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/__internal__/distribute/multi_process_runner/__init__.py,sha256=NksTCGT3_qeJtD3NJ7ghwlSSsStEibtxf1a1mlXZtCg,887 +tensorflow/_api/v2/__internal__/distribute/multi_process_runner/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/__internal__/eager_context/__init__.py,sha256=_1qgzLfZM31UPgb0PaJZiENxC6YHYu-tYXFCxshpF5M,586 +tensorflow/_api/v2/__internal__/eager_context/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/__internal__/feature_column/__init__.py,sha256=KbkMxcwg22FWEsbnGW9VlIeqa6dMQZJDSrsu7HMmhgA,907 +tensorflow/_api/v2/__internal__/feature_column/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/__internal__/function/__init__.py,sha256=HddbB1puuuGtVhBwe6UdhzBMKqFC67BXJcilyHX25nA,318 +tensorflow/_api/v2/__internal__/function/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/__internal__/graph_util/__init__.py,sha256=KiqDI09z69WtWKyHctALT4Vv2HQr0SWyqjdEEnANYNU,306 +tensorflow/_api/v2/__internal__/graph_util/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/__internal__/mixed_precision/__init__.py,sha256=EHs3Rm2dC6CfMQmh-iy-vAjWPxdcDI-0dlpXCZHhABQ,333 +tensorflow/_api/v2/__internal__/mixed_precision/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/__internal__/monitoring/__init__.py,sha256=_3AhWJV0JkBlXzklkHyC0vMfypNjCtVr1PgGgZl9EzU,290 +tensorflow/_api/v2/__internal__/monitoring/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/__internal__/nest/__init__.py,sha256=e76G5bIM8mVQkv5_l11cMvcdaap_JdaJBU048pmMQ-Y,782 +tensorflow/_api/v2/__internal__/nest/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/__internal__/ops/__init__.py,sha256=UBm872zzroFdTqxXbGax0aK2_yVfzomY-Nhrp_D25-s,390 +tensorflow/_api/v2/__internal__/ops/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/__internal__/saved_model/__init__.py,sha256=FZDSOm-bq80DOPCg8jsmLnzvNMpU-l1Ccr0I8F4RQ04,727 +tensorflow/_api/v2/__internal__/saved_model/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/__internal__/saved_model/load/__init__.py,sha256=ffaGqyWr9ep_8zQqI7Kr0-W0u3_wPNCt_UztWIgRgvE,580 +tensorflow/_api/v2/__internal__/saved_model/load/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/__internal__/smart_cond/__init__.py,sha256=DPMllQMAvtiQwIWjVS3ihYTOoF2BBXTJtUdnZoSwnKM,294 +tensorflow/_api/v2/__internal__/smart_cond/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/__internal__/test/__init__.py,sha256=Ny7nvhrrUkQ1zsLW-x8tkeFABDk04tN_4Pm6naS6DfE,361 +tensorflow/_api/v2/__internal__/test/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/__internal__/test/combinations/__init__.py,sha256=qHHhOXr2YuQMRZQyYzrxRmtVtKJvIa9vjrbFdAOQF1A,798 +tensorflow/_api/v2/__internal__/test/combinations/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/__internal__/tf2/__init__.py,sha256=hQfIdhecDdU40nBY4ry--NiPv5ZV8ZhdrB9KVt8oyCU,267 +tensorflow/_api/v2/__internal__/tf2/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/__internal__/tracking/__init__.py,sha256=r6bxddeSsQY5jPU5fVd2ao5Ap4o9MsrLGyrZMq4p5Ic,1425 +tensorflow/_api/v2/__internal__/tracking/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/__internal__/train/__init__.py,sha256=oC3WhlUk2gMvULzlFh5IBAXSEgclsv1RuCvK5_C3pOg,697 +tensorflow/_api/v2/__internal__/train/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/__internal__/types/__init__.py,sha256=K9-_9-UWsZudnM6855tI9eBKYwsi7OZMEHHuybDnn54,330 +tensorflow/_api/v2/__internal__/types/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/__internal__/types/data/__init__.py,sha256=Pj2MK4HDyAFy2LEiHynWcphuA8BiBZTeB7VpDvlroYI,294 +tensorflow/_api/v2/__internal__/types/data/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/__operators__/__init__.py,sha256=zCh6ZF7hNr6BHpv9vRp1IU9la6jVNaSzHkVaZCDjFqo,632 +tensorflow/_api/v2/__operators__/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/__pycache__/v2.cpython-310.pyc,, +tensorflow/_api/v2/api_packages.txt,sha256=t1jWGLBv_-Z_OnCpf6UpAjX5OwwkyP7_MX3go7XJITw,13699 +tensorflow/_api/v2/audio/__init__.py,sha256=2W1la6sIGCunRNRgFmyd6zECqNCKX_SJ_gS2M-4rtpM,345 +tensorflow/_api/v2/audio/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/autodiff/__init__.py,sha256=jc4f7St5w7Uf6QW9vm4jfoub2gYg_LqZZde8Y1IbqIc,355 +tensorflow/_api/v2/autodiff/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/autograph/__init__.py,sha256=PciqSIT_LZdof3aaT03492cD5ST0SvSMoiPvCsSOgq4,556 +tensorflow/_api/v2/autograph/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/autograph/experimental/__init__.py,sha256=LX430SLxhMs-vU9A8l35sG2gF2IOzFjrMzMbmywCMmU,454 +tensorflow/_api/v2/autograph/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/bitwise/__init__.py,sha256=UVfp0fx-PR2LbmJ_-TM4G1IlwwJ-rwbdJ3DA-_4-5-Q,641 +tensorflow/_api/v2/bitwise/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/__init__.py,sha256=qwjSKkXIg5WGFMUd5Zw27viRPZUStAytO0205Tn4l2M,1204 +tensorflow/_api/v2/compat/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/__init__.py,sha256=PfmTayxy6DTqvXw9Yazh9JkJlIq0mPOieOmCW8V6lTI,51114 +tensorflow/_api/v2/compat/v1/__internal__/__init__.py,sha256=YuVeqPKQI0hfObpOdfcC4bBa0En6Wm1sWiD1FTjhZlc,653 +tensorflow/_api/v2/compat/v1/__internal__/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/__internal__/types/__init__.py,sha256=dFBo6dsnCGlAL0ienxotDC2zei4nboCgDcDJZKC3BJY,599 +tensorflow/_api/v2/compat/v1/__internal__/types/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/__internal__/types/data/__init__.py,sha256=rdhgaZ16ea_HOC7sfEjw6fZ-C1_oIF554ssgUfhnVBI,617 +tensorflow/_api/v2/compat/v1/__internal__/types/data/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/app/__init__.py,sha256=bRa_9Pjhd1IZKzvcyUWrdItbJkafm7q4LRCDmuXtk3I,562 +tensorflow/_api/v2/compat/v1/app/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/audio/__init__.py,sha256=XAZ29qxTe-QplrkVomPc_aglxwR1EwOg_lES4UMYIZw,650 +tensorflow/_api/v2/compat/v1/audio/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/autograph/__init__.py,sha256=WJC0jEJUyMeYQXsoMlXI_kdi20c6pcfsXR8KnzWUCPE,904 +tensorflow/_api/v2/compat/v1/autograph/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/autograph/experimental/__init__.py,sha256=T51WzGAKFknGG0aXwPmeUJ-HL-1RmQ3_p-3BVUXi1fY,776 +tensorflow/_api/v2/compat/v1/autograph/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/bitwise/__init__.py,sha256=D3myoEIms5B5vpQZ6iBKQ5KMcl5aPCfEI6ziFgjJ3yg,948 +tensorflow/_api/v2/compat/v1/bitwise/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/compat/__init__.py,sha256=-VQPnMx9B_iFVvam7uHggk7RABfkvvGykmWxualfOR0,1530 +tensorflow/_api/v2/compat/v1/compat/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/compat/v1/__init__.py,sha256=PfmTayxy6DTqvXw9Yazh9JkJlIq0mPOieOmCW8V6lTI,51114 +tensorflow/_api/v2/compat/v1/compat/v1/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/compat/v1/compat/__init__.py,sha256=-VQPnMx9B_iFVvam7uHggk7RABfkvvGykmWxualfOR0,1530 +tensorflow/_api/v2/compat/v1/compat/v1/compat/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/compat/v2/__init__.py,sha256=DSM0mo8-ZLqve8dzURwuZ1J6-Pm2RL7draHK4GULlew,25315 +tensorflow/_api/v2/compat/v1/compat/v2/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/compat/v2/compat/__init__.py,sha256=tGMChPCisK3f5ML27IehDXI1AtDxIANNpN3i2YNuVJE,1224 +tensorflow/_api/v2/compat/v1/compat/v2/compat/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/config/__init__.py,sha256=aK8ykYQX2t_NOvseJF7QsJeBzDMrm-8Qg1RhW74f6n4,2264 +tensorflow/_api/v2/compat/v1/config/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/config/experimental/__init__.py,sha256=lA2ogO7xOKpE0hYnq-Gzj8qIGNjaEndraH3sshrI1n0,2432 +tensorflow/_api/v2/compat/v1/config/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/config/optimizer/__init__.py,sha256=OQXvxmNDuiGp_dtFwUk8VjyIQkHMx19i-6kc6FdXbMI,950 +tensorflow/_api/v2/compat/v1/config/optimizer/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/config/threading/__init__.py,sha256=Tzr9dnpN9Q7dgnAWEsxxMI0NtHh8wjUS_4vDUUITCyM,898 +tensorflow/_api/v2/compat/v1/config/threading/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/data/__init__.py,sha256=PmKDOgmggcledU0vgroO3Rq3OoCK-9iMvXRO6wWnbHA,2096 +tensorflow/_api/v2/compat/v1/data/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/data/experimental/__init__.py,sha256=S-WNARjssSlju92M8kNj1JHcJDNyrpycEUJLh9JQGR8,6525 +tensorflow/_api/v2/compat/v1/data/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/data/experimental/service/__init__.py,sha256=zfkjpHMbL36H1UtWU2PVD3Gtm70j7nR027Hw9QO5NrM,1217 +tensorflow/_api/v2/compat/v1/data/experimental/service/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/debugging/__init__.py,sha256=t6Pe6p3RtX-jGZcyLV5bR9MPVuuLHdXqGPYrB3W_c34,3354 +tensorflow/_api/v2/compat/v1/debugging/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/debugging/experimental/__init__.py,sha256=EhOK9E7FWsWem61KvbBvMfL60SHV6Iagq47DtmpJAJo,727 +tensorflow/_api/v2/compat/v1/debugging/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/distribute/__init__.py,sha256=KPXj6OQGuax9Ct2gHNOGiIQPAE11Ar1LnQE_iJe2Z4w,2451 +tensorflow/_api/v2/compat/v1/distribute/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/distribute/cluster_resolver/__init__.py,sha256=BFuLs5JwIbzBHtRJOHxHLbyo_9wuJQtQ9IHoviweoms,1462 +tensorflow/_api/v2/compat/v1/distribute/cluster_resolver/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/distribute/experimental/__init__.py,sha256=WHe1RnMEAScK1tL9krtqMWreUtv5J5zdUnGBIy2tAlw,1466 +tensorflow/_api/v2/compat/v1/distribute/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/distributions/__init__.py,sha256=WYzJNuicufLoSW2Jc45y2bK8PGasTxPeXloUTqX6ILw,2022 +tensorflow/_api/v2/compat/v1/distributions/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/dtypes/__init__.py,sha256=kY8LxFvFQi-uqgWrrxmHMsiSXFGAHKkBxUSTpacDWMU,2697 +tensorflow/_api/v2/compat/v1/dtypes/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/dtypes/experimental/__init__.py,sha256=W1Yw7v2Fh-Ph88P35a1rnP2MvEngUbi9RkH3CPM-v70,809 +tensorflow/_api/v2/compat/v1/dtypes/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/errors/__init__.py,sha256=04pt759xg7KAb2m50NlxbkCgjamMiljbrdxwSF7wEGA,3487 +tensorflow/_api/v2/compat/v1/errors/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/experimental/__init__.py,sha256=sl6bv-fgO-fm6tUwzJFdgzS6zMkfAaBIyBLTn5ZU-EU,2477 +tensorflow/_api/v2/compat/v1/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/experimental/extension_type/__init__.py,sha256=ystCyFVmKeaxosZgEB3se9OOv2eVUmye0yYIM9Q5E6s,627 +tensorflow/_api/v2/compat/v1/experimental/extension_type/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/feature_column/__init__.py,sha256=WKvbeh4fuhbjFynOdt27p_4G8Qg_-cbLbj93Hl0t3IU,2523 +tensorflow/_api/v2/compat/v1/feature_column/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/gfile/__init__.py,sha256=ZBK6P83k_SdsoB73t5STxPSdye_Esq2eRpre5bivQH4,1671 +tensorflow/_api/v2/compat/v1/gfile/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/graph_util/__init__.py,sha256=kqcSz8jj2ZF5hTIYXDqgzdzhc9LYHZhHtm6HcnsAaQs,1061 +tensorflow/_api/v2/compat/v1/graph_util/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/image/__init__.py,sha256=gh2yF98pAPvvXG6_mP6VKSak-qDrH9w9pxRDqPcBT6A,6183 +tensorflow/_api/v2/compat/v1/image/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/initializers/__init__.py,sha256=gBVN0q0SKBpFPE9_Rm3cm1A6zxAsvcsfBWgyFu3J5Kw,2167 +tensorflow/_api/v2/compat/v1/initializers/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/io/__init__.py,sha256=PTd1qf5lpGNrn_ulOLVKRiCxooxs3jf4aIerkcCsz_U,3991 +tensorflow/_api/v2/compat/v1/io/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/io/gfile/__init__.py,sha256=Sxvq4bmyiFeoCWKuUH4ioe_VUGGbjVnA3iv0dzxzc74,1695 +tensorflow/_api/v2/compat/v1/io/gfile/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/layers/__init__.py,sha256=xX5GJYDK4IBZ8U70bFt61rgwOHne7U77BLrUBOWbsio,585 +tensorflow/_api/v2/compat/v1/layers/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/linalg/__init__.py,sha256=K2B6LPXf4-bKIoiIu9nG-nmz2Epp4Ljrp-hd5omYe8s,6155 +tensorflow/_api/v2/compat/v1/linalg/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/linalg/experimental/__init__.py,sha256=4gSiniE-eSNTXGF3hQEMnOohwcWV5Ov8DJnQRhbYuxM,633 +tensorflow/_api/v2/compat/v1/linalg/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/lite/__init__.py,sha256=LZ641HAHq_URxMg3Dh1EeTSAYT8MDgIje2jSnt9mZLI,1218 +tensorflow/_api/v2/compat/v1/lite/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/lite/constants/__init__.py,sha256=-O9i5B0IHM_BaYs3PemO6UUG167PC5qcnASeEpRDFxk,1216 +tensorflow/_api/v2/compat/v1/lite/constants/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/lite/experimental/__init__.py,sha256=l0VDXdbNm8QUI61IO7ZYRvvxpA8nVFR_GKe0QgQP-H0,1118 +tensorflow/_api/v2/compat/v1/lite/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/lite/experimental/authoring/__init__.py,sha256=mV8cPwfBjjNU4NJv-wZnnsabwtC04IwH4vS1y0KlOr0,630 +tensorflow/_api/v2/compat/v1/lite/experimental/authoring/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/logging/__init__.py,sha256=ArVscOLVg98MwCSZHY09_0V9zlGoW_RN3Y99XfjwLVg,1913 +tensorflow/_api/v2/compat/v1/logging/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/lookup/__init__.py,sha256=2WyxuKANa9SB6RM4oXsdaai_VqJadGfAzD0_OcpR1Sg,1003 +tensorflow/_api/v2/compat/v1/lookup/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/lookup/experimental/__init__.py,sha256=cr1KFJUiRzqcXWPjcpTSViS6RBU9xszBzwO4UwQugbE,684 +tensorflow/_api/v2/compat/v1/lookup/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/losses/__init__.py,sha256=GpZzgecJSY6IozyMinz-MnLoyozmtaxcYTAnn_nrMyk,1884 +tensorflow/_api/v2/compat/v1/losses/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/manip/__init__.py,sha256=GrT49Eel0gjwkXbXyru4zvvt2WHkQnTITEcW4YKsdyA,1078 +tensorflow/_api/v2/compat/v1/manip/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/math/__init__.py,sha256=iVd-vPVQbHGXI3tsIHUzAL7vscg0CDtDsWOPnScc-f0,9662 +tensorflow/_api/v2/compat/v1/math/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/math/special/__init__.py,sha256=fWHssrel4uuZ19IZbM_oWjNBjupfFA7ho6pa2Y8xz0Y,1761 +tensorflow/_api/v2/compat/v1/math/special/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/metrics/__init__.py,sha256=h3_CJCQif4khPAm2HbOEglJ35ktDvDdckoCPr72PN70,3106 +tensorflow/_api/v2/compat/v1/metrics/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/mixed_precision/__init__.py,sha256=WeMvqgXGpY0CV8hDz7MMp8HaFrN1UnDyKxbLnE4HrWc,1302 +tensorflow/_api/v2/compat/v1/mixed_precision/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/mixed_precision/experimental/__init__.py,sha256=6x7E0njo2ay8eGdjQnFxsnF_dngOTqVc45O8e4I1hjw,820 +tensorflow/_api/v2/compat/v1/mixed_precision/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/mlir/__init__.py,sha256=9yAkYLit01YEF6vGV7vUCgFNX2BbUT68kYFTsn_LihM,565 +tensorflow/_api/v2/compat/v1/mlir/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/mlir/experimental/__init__.py,sha256=-UPN3Gu6XN-1sTK9qYDgROn__1QkVHLLiqAWl45Gmik,1122 +tensorflow/_api/v2/compat/v1/mlir/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/nest/__init__.py,sha256=W06sb9VnK0fn2zmoxrd2QSBVDP8ekqtP4KS21ZjTsqY,837 +tensorflow/_api/v2/compat/v1/nest/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/nn/__init__.py,sha256=0V9muqoIWN8uP2tHjwT0eTC9Wgfn7vS1z9j-Xm1880M,8919 +tensorflow/_api/v2/compat/v1/nn/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/nn/experimental/__init__.py,sha256=ff_qYJepyY7TYyY_hFX9SMszqH3sQJLNkMgSBAmVQ-Y,670 +tensorflow/_api/v2/compat/v1/nn/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/nn/rnn_cell/__init__.py,sha256=NtyYwysgrcdvpklA6ejwr8vzmx-acxwkXo-pdd6tRQE,1449 +tensorflow/_api/v2/compat/v1/nn/rnn_cell/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/profiler/__init__.py,sha256=P3suit2Ssc1XpCieSRRWySREi3t47Hd0R00rjmRmdhk,1194 +tensorflow/_api/v2/compat/v1/profiler/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/python_io/__init__.py,sha256=oSxWchKy757XU5a-gfwUFJyZ0BzY7fntmDlejJLrSPQ,824 +tensorflow/_api/v2/compat/v1/python_io/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/quantization/__init__.py,sha256=yOJj3gF9KurUI3pf9j_E1hk9zVZLadTXfFU1kLgr6-E,1557 +tensorflow/_api/v2/compat/v1/quantization/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/quantization/experimental/__init__.py,sha256=hOPf9a7q7HkQ07gE2uuoP-nYfSWV0ZGe6CnhBVvIlJE,1386 +tensorflow/_api/v2/compat/v1/quantization/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/queue/__init__.py,sha256=UHcwGpsQu4m7XRgkL79_NMJuFl12foza0d87uK94_vA,878 +tensorflow/_api/v2/compat/v1/queue/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/ragged/__init__.py,sha256=zWrP1HA0izXVZVbWCZGl6rxI2PHRjqtF2HhGZwl4CbI,1612 +tensorflow/_api/v2/compat/v1/ragged/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/random/__init__.py,sha256=BaiqJTL4mvj-lb4CqfFPMeZXSqsZ_xvPrVvchz9lVlU,3322 +tensorflow/_api/v2/compat/v1/random/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/random/experimental/__init__.py,sha256=MVQhMliUG8syVNex5KVIjlg7QffXcV6vL72F1a4uQV4,1293 +tensorflow/_api/v2/compat/v1/random/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/raw_ops/__init__.py,sha256=JGUF5pX6rtP_eFGbhcTYJnx20JS7N7V8Gelt-GNR8YQ,115715 +tensorflow/_api/v2/compat/v1/raw_ops/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/resource_loader/__init__.py,sha256=Z62NIYET_oN84SGppOMualLkjN05uXLG8cYuOGRNKdQ,966 +tensorflow/_api/v2/compat/v1/resource_loader/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/saved_model/__init__.py,sha256=q7nyZZf1VORuS1qHBv7qMP1uM6mBRndjw3FDqrQZGP8,4840 +tensorflow/_api/v2/compat/v1/saved_model/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/saved_model/builder/__init__.py,sha256=iuNAureTbprUlWVsP7LzsZMANpM_KwQpSQA3rdeQuq0,621 +tensorflow/_api/v2/compat/v1/saved_model/builder/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/saved_model/constants/__init__.py,sha256=0XFXIVU6wF4yfZ1YlofpEI6M3fW4zXbIfn1dGuY_1gw,1451 +tensorflow/_api/v2/compat/v1/saved_model/constants/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/saved_model/experimental/__init__.py,sha256=4nih0IXfb4Yfm9br3p8B91qYpBRNKt-J9P6GJynylEE,771 +tensorflow/_api/v2/compat/v1/saved_model/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/saved_model/loader/__init__.py,sha256=UeVUMwrzW2OLhPrzduu4zUUZk-3bDcGtMjeD1oNyRVQ,699 +tensorflow/_api/v2/compat/v1/saved_model/loader/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/saved_model/main_op/__init__.py,sha256=JuxU-Fxe3SQXihGFbmcTNkSOk--u-VOIFqllEB9Jwv4,697 +tensorflow/_api/v2/compat/v1/saved_model/main_op/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/saved_model/signature_constants/__init__.py,sha256=CYXJEgtBRPrFf47U8O3b0-6b0urBHy9_NW3418LeSbA,1586 +tensorflow/_api/v2/compat/v1/saved_model/signature_constants/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/saved_model/signature_def_utils/__init__.py,sha256=wCMdBkmV3iimGYVwrLSrnqbDpW9kLGzCStx8Iu3pUZQ,1159 +tensorflow/_api/v2/compat/v1/saved_model/signature_def_utils/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/saved_model/tag_constants/__init__.py,sha256=pLj55End2-QRhYFFUR-YCxJqE-XcpABQIJOVHJjMko4,841 +tensorflow/_api/v2/compat/v1/saved_model/tag_constants/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/saved_model/utils/__init__.py,sha256=ZnojUaFa0oNDQUGPIYmCwxeSGnagyj9Ue_9S8KNnaGc,707 +tensorflow/_api/v2/compat/v1/saved_model/utils/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/sets/__init__.py,sha256=eBUBR0vvG5p1nXqXUpGQin8mFXzmU_aVmOqvNJuAZgk,1101 +tensorflow/_api/v2/compat/v1/sets/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/signal/__init__.py,sha256=D1sBwnFLodhPkzHHPK0CetDzbtCYzBkk-4pEGpXsnTI,2998 +tensorflow/_api/v2/compat/v1/signal/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/sparse/__init__.py,sha256=8gLKub1AUK8NmDfL32VcshFDwacSyzeL5AMeEjQtXOM,3569 +tensorflow/_api/v2/compat/v1/sparse/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/spectral/__init__.py,sha256=o0hTx0oEK6CyNyrlhvvC8iisLGVLrwm8kvKFmHQVllk,1464 +tensorflow/_api/v2/compat/v1/spectral/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/strings/__init__.py,sha256=yPZ7-O03_nGwpObOXUfJhV804P9ntNPYjnlLQSh8SSQ,2735 +tensorflow/_api/v2/compat/v1/strings/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/summary/__init__.py,sha256=WZ51Ezaok_zjoRUtL_ZydmYIdi8-RSxZ414BQtfMfs4,1771 +tensorflow/_api/v2/compat/v1/summary/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/sysconfig/__init__.py,sha256=G4xyuIf6n6O0dw8SEfR9ONcl-9fVr0cFefR06grxAKk,1109 +tensorflow/_api/v2/compat/v1/sysconfig/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/test/__init__.py,sha256=Vgnxld0TMJtikg4FdCTWvkaCYDIhawotOyTRX09O1T8,2167 +tensorflow/_api/v2/compat/v1/test/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/test/experimental/__init__.py,sha256=Cj3y0YSzVoZxMF0FnGZ3CFkzXsEOSkDQuLMVAQi50mk,608 +tensorflow/_api/v2/compat/v1/test/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/tpu/__init__.py,sha256=rr8qhX6HLaOVphXkk0kvUtJPdVkMZFZH5iulZsCP5hw,1429 +tensorflow/_api/v2/compat/v1/tpu/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/tpu/experimental/__init__.py,sha256=UZj3M2ZfOjbxWhX49pO2F5jHgwxARpIRz8FLiEJEvew,1755 +tensorflow/_api/v2/compat/v1/tpu/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/tpu/experimental/embedding/__init__.py,sha256=0D_82zhTuMmHmYspcejr11K9yeeVE70LiUs13Ij_wxk,1553 +tensorflow/_api/v2/compat/v1/tpu/experimental/embedding/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/train/__init__.py,sha256=TZKNva1IDiTdGjC2CyvoufscR9_Mq1EU-m4UzEkgyi8,10503 +tensorflow/_api/v2/compat/v1/train/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/train/experimental/__init__.py,sha256=XxNIeks-HcM_l4D4Q16gRAYfG8tdAvqhNdtgf0xjurw,1314 +tensorflow/_api/v2/compat/v1/train/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/train/queue_runner/__init__.py,sha256=GaW1MXT_SW2EZsf-StSh7z9_dLPSjcva-VM-Ja3wK_Y,789 +tensorflow/_api/v2/compat/v1/train/queue_runner/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/types/__init__.py,sha256=E6c6bn8ES8zcsdgL21WugNxA4AJKc5YgrJbQsvDVzC0,568 +tensorflow/_api/v2/compat/v1/types/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/types/experimental/__init__.py,sha256=qvewKMcofKetnYAVUlWvJIlB2g7BtJhGOQuQmhMSF2s,663 +tensorflow/_api/v2/compat/v1/types/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/user_ops/__init__.py,sha256=ddbGDqW4jTSfGvMGqQs6V5X4Gl26Znifjz00SOjKmb0,581 +tensorflow/_api/v2/compat/v1/user_ops/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/version/__init__.py,sha256=9iyJABzpgqu6jQOqZlDxClpP83gwMVNazwGHHmGK-m4,989 +tensorflow/_api/v2/compat/v1/version/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/xla/__init__.py,sha256=YhdqBBgIvTyNGOj9lz4rbiBICXon7Gw1xTLm4yWaezc,562 +tensorflow/_api/v2/compat/v1/xla/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v1/xla/experimental/__init__.py,sha256=sRyJlyhuwaoTwH-zSzr1O_FEAA-kBbznX8mVlA22-Ts,690 +tensorflow/_api/v2/compat/v1/xla/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/__init__.py,sha256=DSM0mo8-ZLqve8dzURwuZ1J6-Pm2RL7draHK4GULlew,25315 +tensorflow/_api/v2/compat/v2/__internal__/__init__.py,sha256=8F_z_Q4Q93MQcniZVw8o_rx59nq5sf-MmQd3r2ZyQzA,2708 +tensorflow/_api/v2/compat/v2/__internal__/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/__internal__/autograph/__init__.py,sha256=lS3dqn1D4kpefRtfAEh1wVeZtDso4hyj0Xc9CCxxLPA,374 +tensorflow/_api/v2/compat/v2/__internal__/autograph/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/__internal__/decorator/__init__.py,sha256=SWznSTRgIg5Y8yB44TEuut9brkbVo7BW_7y-IM06hlA,374 +tensorflow/_api/v2/compat/v2/__internal__/decorator/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/__internal__/dispatch/__init__.py,sha256=rCiZMvp1LrrXMp4-VJy8yOINaCXzcnJNgqhFF-LC2ck,440 +tensorflow/_api/v2/compat/v2/__internal__/dispatch/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/__internal__/distribute/__init__.py,sha256=2XFJzTfi3w0Z5-03jBDmpcL4QOnIpuKtF8xGaxxtS-0,745 +tensorflow/_api/v2/compat/v2/__internal__/distribute/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/__internal__/distribute/combinations/__init__.py,sha256=vr_MhCj9cAI8Y1wJ6j45m6THSLNDR1WDlLiCclxF9GQ,3140 +tensorflow/_api/v2/compat/v2/__internal__/distribute/combinations/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/__internal__/distribute/interim/__init__.py,sha256=1Y0gGfMGfjIixKdQzM0K2JhRTAnvS-ch87V__Df1QEQ,317 +tensorflow/_api/v2/compat/v2/__internal__/distribute/interim/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/__internal__/distribute/multi_process_runner/__init__.py,sha256=NksTCGT3_qeJtD3NJ7ghwlSSsStEibtxf1a1mlXZtCg,887 +tensorflow/_api/v2/compat/v2/__internal__/distribute/multi_process_runner/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/__internal__/eager_context/__init__.py,sha256=_1qgzLfZM31UPgb0PaJZiENxC6YHYu-tYXFCxshpF5M,586 +tensorflow/_api/v2/compat/v2/__internal__/eager_context/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/__internal__/feature_column/__init__.py,sha256=KbkMxcwg22FWEsbnGW9VlIeqa6dMQZJDSrsu7HMmhgA,907 +tensorflow/_api/v2/compat/v2/__internal__/feature_column/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/__internal__/function/__init__.py,sha256=HddbB1puuuGtVhBwe6UdhzBMKqFC67BXJcilyHX25nA,318 +tensorflow/_api/v2/compat/v2/__internal__/function/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/__internal__/graph_util/__init__.py,sha256=KiqDI09z69WtWKyHctALT4Vv2HQr0SWyqjdEEnANYNU,306 +tensorflow/_api/v2/compat/v2/__internal__/graph_util/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/__internal__/mixed_precision/__init__.py,sha256=EHs3Rm2dC6CfMQmh-iy-vAjWPxdcDI-0dlpXCZHhABQ,333 +tensorflow/_api/v2/compat/v2/__internal__/mixed_precision/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/__internal__/monitoring/__init__.py,sha256=_3AhWJV0JkBlXzklkHyC0vMfypNjCtVr1PgGgZl9EzU,290 +tensorflow/_api/v2/compat/v2/__internal__/monitoring/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/__internal__/nest/__init__.py,sha256=e76G5bIM8mVQkv5_l11cMvcdaap_JdaJBU048pmMQ-Y,782 +tensorflow/_api/v2/compat/v2/__internal__/nest/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/__internal__/ops/__init__.py,sha256=UBm872zzroFdTqxXbGax0aK2_yVfzomY-Nhrp_D25-s,390 +tensorflow/_api/v2/compat/v2/__internal__/ops/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/__internal__/saved_model/__init__.py,sha256=HhbXQzVmYQ6PXzwyJ6mNF9bHhF0hJE1LS4rCg99g3Xg,737 +tensorflow/_api/v2/compat/v2/__internal__/saved_model/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/__internal__/saved_model/load/__init__.py,sha256=ffaGqyWr9ep_8zQqI7Kr0-W0u3_wPNCt_UztWIgRgvE,580 +tensorflow/_api/v2/compat/v2/__internal__/saved_model/load/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/__internal__/smart_cond/__init__.py,sha256=DPMllQMAvtiQwIWjVS3ihYTOoF2BBXTJtUdnZoSwnKM,294 +tensorflow/_api/v2/compat/v2/__internal__/smart_cond/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/__internal__/test/__init__.py,sha256=wpcXPe7Ja3J2bocUv4JZmQIiGxymTqSxNlunVPYlfBI,371 +tensorflow/_api/v2/compat/v2/__internal__/test/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/__internal__/test/combinations/__init__.py,sha256=qHHhOXr2YuQMRZQyYzrxRmtVtKJvIa9vjrbFdAOQF1A,798 +tensorflow/_api/v2/compat/v2/__internal__/test/combinations/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/__internal__/tf2/__init__.py,sha256=hQfIdhecDdU40nBY4ry--NiPv5ZV8ZhdrB9KVt8oyCU,267 +tensorflow/_api/v2/compat/v2/__internal__/tf2/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/__internal__/tracking/__init__.py,sha256=r6bxddeSsQY5jPU5fVd2ao5Ap4o9MsrLGyrZMq4p5Ic,1425 +tensorflow/_api/v2/compat/v2/__internal__/tracking/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/__internal__/train/__init__.py,sha256=oC3WhlUk2gMvULzlFh5IBAXSEgclsv1RuCvK5_C3pOg,697 +tensorflow/_api/v2/compat/v2/__internal__/train/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/__internal__/types/__init__.py,sha256=k2Bha5VSoQog4gzrBKhim5cWTR54b9nr3J-NEbYxfhs,340 +tensorflow/_api/v2/compat/v2/__internal__/types/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/__internal__/types/data/__init__.py,sha256=Pj2MK4HDyAFy2LEiHynWcphuA8BiBZTeB7VpDvlroYI,294 +tensorflow/_api/v2/compat/v2/__internal__/types/data/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/__operators__/__init__.py,sha256=zCh6ZF7hNr6BHpv9vRp1IU9la6jVNaSzHkVaZCDjFqo,632 +tensorflow/_api/v2/compat/v2/__operators__/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/audio/__init__.py,sha256=2W1la6sIGCunRNRgFmyd6zECqNCKX_SJ_gS2M-4rtpM,345 +tensorflow/_api/v2/compat/v2/audio/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/autodiff/__init__.py,sha256=jc4f7St5w7Uf6QW9vm4jfoub2gYg_LqZZde8Y1IbqIc,355 +tensorflow/_api/v2/compat/v2/autodiff/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/autograph/__init__.py,sha256=3KKFQk1JvKd4eIEs83S9CRoFHzFykdwkFkQ71lW8wGM,566 +tensorflow/_api/v2/compat/v2/autograph/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/autograph/experimental/__init__.py,sha256=LX430SLxhMs-vU9A8l35sG2gF2IOzFjrMzMbmywCMmU,454 +tensorflow/_api/v2/compat/v2/autograph/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/bitwise/__init__.py,sha256=UVfp0fx-PR2LbmJ_-TM4G1IlwwJ-rwbdJ3DA-_4-5-Q,641 +tensorflow/_api/v2/compat/v2/bitwise/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/compat/__init__.py,sha256=tGMChPCisK3f5ML27IehDXI1AtDxIANNpN3i2YNuVJE,1224 +tensorflow/_api/v2/compat/v2/compat/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/compat/v1/__init__.py,sha256=PfmTayxy6DTqvXw9Yazh9JkJlIq0mPOieOmCW8V6lTI,51114 +tensorflow/_api/v2/compat/v2/compat/v1/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/compat/v1/compat/__init__.py,sha256=-VQPnMx9B_iFVvam7uHggk7RABfkvvGykmWxualfOR0,1530 +tensorflow/_api/v2/compat/v2/compat/v1/compat/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/compat/v2/__init__.py,sha256=DSM0mo8-ZLqve8dzURwuZ1J6-Pm2RL7draHK4GULlew,25315 +tensorflow/_api/v2/compat/v2/compat/v2/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/compat/v2/compat/__init__.py,sha256=tGMChPCisK3f5ML27IehDXI1AtDxIANNpN3i2YNuVJE,1224 +tensorflow/_api/v2/compat/v2/compat/v2/compat/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/config/__init__.py,sha256=ezYO8lpe3cwZcpuwKwx_tBeOX3f3U9a0wlVTB-suNhQ,1958 +tensorflow/_api/v2/compat/v2/config/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/config/experimental/__init__.py,sha256=zD1evBgdSgnRbnNoRUqIUQ_ReVSBClzZnqTd_ZLFfwE,2194 +tensorflow/_api/v2/compat/v2/config/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/config/optimizer/__init__.py,sha256=Xm1tvQ4n0JY-f3g5zg4Qzd8Z_IVGe5arSioFa2JDU2g,634 +tensorflow/_api/v2/compat/v2/config/optimizer/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/config/threading/__init__.py,sha256=MytvNqIgcB4QOzCPtALvhRjzqWNtVyyQooLJk2JkSAY,582 +tensorflow/_api/v2/compat/v2/config/threading/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/data/__init__.py,sha256=E7gSspgD_ICZDYA5NLoH_pZoMFnTrQ6Qt9aAqEYnkvU,1376 +tensorflow/_api/v2/compat/v2/data/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/data/experimental/__init__.py,sha256=htcliwTahuAfjxz1M1FIIp0mB-jPUO8qHnC66mlqguE,5622 +tensorflow/_api/v2/compat/v2/data/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/data/experimental/service/__init__.py,sha256=8d4lsegpD8ODIKm-xUZmjn4DxltS6dp0O4EMOuLEC6o,1078 +tensorflow/_api/v2/compat/v2/data/experimental/service/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/debugging/__init__.py,sha256=jaVQ06eVCuWDLF8Xqa3c1skZ8s7lUQ2gekLgWB63rFk,3080 +tensorflow/_api/v2/compat/v2/debugging/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/debugging/experimental/__init__.py,sha256=buFlNlokJCfiYa8g4oeY-7LDzxuSvzL_b-DHL4uMx2Q,405 +tensorflow/_api/v2/compat/v2/debugging/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/distribute/__init__.py,sha256=w-hkVrJgxZpSarW0fQSEb7aAqGa1JznsoXsAv1fgIyc,2786 +tensorflow/_api/v2/compat/v2/distribute/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/distribute/cluster_resolver/__init__.py,sha256=-6xKP5suDV6HS1nirLiOmdpKJvjn0nzEyzYjCMEO-nw,1135 +tensorflow/_api/v2/compat/v2/distribute/cluster_resolver/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/distribute/coordinator/__init__.py,sha256=vCIXtxHvuHBfEPTXX4OqWDejjm1riZ8ZhpNgo6sCAKU,670 +tensorflow/_api/v2/compat/v2/distribute/coordinator/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/distribute/experimental/__init__.py,sha256=eY5CmJ1A3gkVx6dxO43A4B-mJ3b5Ygm6Ds5m2Ub-b90,1741 +tensorflow/_api/v2/compat/v2/distribute/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/distribute/experimental/coordinator/__init__.py,sha256=ZcBKq5vPHen735z-mkeMRkTUa5sX0LcEuUAkukw5sk0,515 +tensorflow/_api/v2/compat/v2/distribute/experimental/coordinator/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/distribute/experimental/partitioners/__init__.py,sha256=HTcNh2Zi3xTvjceFYGncZ1iLFe1IVL3kkL8M29XV_MY,585 +tensorflow/_api/v2/compat/v2/distribute/experimental/partitioners/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/distribute/experimental/rpc/__init__.py,sha256=yREf0ghX3_Ac2ONQE87Qh1M6JtufnWNcEFu2gVsMZ_s,394 +tensorflow/_api/v2/compat/v2/distribute/experimental/rpc/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/dtypes/__init__.py,sha256=isjjMfYJ8x0AFgyiexnYEPPzsS5PxuHH5hudMOCiwyA,2321 +tensorflow/_api/v2/compat/v2/dtypes/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/dtypes/experimental/__init__.py,sha256=CSeaJaF0yxZYSF6objNz4OlEYqZ8naa3PkCY2YxGgoo,490 +tensorflow/_api/v2/compat/v2/dtypes/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/errors/__init__.py,sha256=9uMWHyAb-S1pDr-YimWCvSgUBP0sad7zyCYefq-WjTI,2988 +tensorflow/_api/v2/compat/v2/errors/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/experimental/__init__.py,sha256=aFf7HruNeiBzp-EVxZEa09j9Nl6R6diBMDM1nRi1zv8,2317 +tensorflow/_api/v2/compat/v2/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/experimental/dlpack/__init__.py,sha256=yswQu62pJwRthG5v2l17cPUnZSS2k3-frPbhjaIjzRY,349 +tensorflow/_api/v2/compat/v2/experimental/dlpack/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/experimental/dtensor/__init__.py,sha256=w48tqFW_-wGbILYp7e2EmiT8bxagk2cMFOkIbgda-p8,3528 +tensorflow/_api/v2/compat/v2/experimental/dtensor/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/experimental/extension_type/__init__.py,sha256=cEAJIgp3LIeh3QzPiNX8d7HahQutjBCHDYvRY0RhcM8,300 +tensorflow/_api/v2/compat/v2/experimental/extension_type/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/experimental/numpy/__init__.py,sha256=4OAchfG6_NeIEHVvpvfvtt5QTK_lUO6YLoKPHbDGy6Y,17611 +tensorflow/_api/v2/compat/v2/experimental/numpy/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/experimental/numpy/random/__init__.py,sha256=gYqwwfyYA8ZEYkUEquhyi07-L8ReEgSNneQONNIuN_8,809 +tensorflow/_api/v2/compat/v2/experimental/numpy/random/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/experimental/tensorrt/__init__.py,sha256=rCq4t3h14nBI4AE03jtJKaVIyOQ44jMBJ3Brk8R_hIU,437 +tensorflow/_api/v2/compat/v2/experimental/tensorrt/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/feature_column/__init__.py,sha256=yw6wWR2g7s4FPmTLNwmKLuLIt7JJhLHJc7l8K3vKFMk,2143 +tensorflow/_api/v2/compat/v2/feature_column/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/graph_util/__init__.py,sha256=zpnMmHiP_2hg9maz43RdJ8kVHPr7Xr9tp9m8hWI7PsM,286 +tensorflow/_api/v2/compat/v2/graph_util/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/image/__init__.py,sha256=5ECUjECT5LQBb8cEiZ5-TQ-YqepqzcNEP0wLMqRN6jE,6102 +tensorflow/_api/v2/compat/v2/image/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/io/__init__.py,sha256=yZPAFvVQ3lY5LBCZd1sUoN4pPfdsIAFKSaC0RmcvFLI,3326 +tensorflow/_api/v2/compat/v2/io/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/io/gfile/__init__.py,sha256=8r0drYwnfRWsMUrDJLpVVOkCuRBZYu-kyf_dToTg274,1387 +tensorflow/_api/v2/compat/v2/io/gfile/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/linalg/__init__.py,sha256=IcufAfwnqRFWHWlFyfGALgDu2htyW2t9sBQD-Bg7O5k,5988 +tensorflow/_api/v2/compat/v2/linalg/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/linalg/experimental/__init__.py,sha256=i1PbArX-DzveKw_a2CLJfPjM4-cTrT8zqBnGlc0JMs4,314 +tensorflow/_api/v2/compat/v2/linalg/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/lite/__init__.py,sha256=bSaiV3J2oGlGdBOTDpEjnlG-mdi9ozqU5SJqLBg0VLY,682 +tensorflow/_api/v2/compat/v2/lite/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/lite/experimental/__init__.py,sha256=zfjiQpcEtW0CZ1XQ49XLtVHrT8R8qr9nw2UWrSHJoD4,719 +tensorflow/_api/v2/compat/v2/lite/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/lite/experimental/authoring/__init__.py,sha256=dR2DMoQyERUXD30NabSLhkFrU4b8FkW-lldgJWkQAUc,303 +tensorflow/_api/v2/compat/v2/lite/experimental/authoring/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/lookup/__init__.py,sha256=4aWvxZJ-OnS1jOxf6b2bJX2sQbKn8Ajr5FjYsksCtHM,649 +tensorflow/_api/v2/compat/v2/lookup/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/lookup/experimental/__init__.py,sha256=6i68sJ8ldei1NaaJvjA8kYNK3vp7ZtylJK8sciOFkXs,365 +tensorflow/_api/v2/compat/v2/lookup/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/math/__init__.py,sha256=1UuaDfGhNudxvCGYccmc5WuW_BHoCMRMMdXLefz_Mrk,9284 +tensorflow/_api/v2/compat/v2/math/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/math/special/__init__.py,sha256=RCQ1NxuzgdSSGPG4tIqKEfY689lzx8arktwpBYb-J6k,1449 +tensorflow/_api/v2/compat/v2/math/special/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/mlir/__init__.py,sha256=AqL3MNn9vlVNJkr32itwGpGl6vReo55SNq-8ldY65Is,261 +tensorflow/_api/v2/compat/v2/mlir/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/mlir/experimental/__init__.py,sha256=994zzXW-QLGLJgYtXQNyYjiZC9_I5gVeK01qrEWa0iE,805 +tensorflow/_api/v2/compat/v2/mlir/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/nest/__init__.py,sha256=gjKeiD0HT9iwKnhHrKvcqllyeCSZBeWF0nWRLgKZFak,533 +tensorflow/_api/v2/compat/v2/nest/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/nn/__init__.py,sha256=nSYjigtax995z8O0Zi8yGvsUgKrEC7NPKrpO6TDRC2g,7743 +tensorflow/_api/v2/compat/v2/nn/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/nn/experimental/__init__.py,sha256=wLwONSQFFVjTXOurhlUqXDmXoL4bBjovTIo-3a8yIAE,355 +tensorflow/_api/v2/compat/v2/nn/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/profiler/__init__.py,sha256=Z7Zyk9Gt4bmaOmME-qFhGvxwCot0sBxzgfzbb7EJHuM,269 +tensorflow/_api/v2/compat/v2/profiler/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/profiler/experimental/__init__.py,sha256=VezzYmis-WLX_AP_9VoYm2M6uusJTH4VSTLilScsmo8,706 +tensorflow/_api/v2/compat/v2/profiler/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/profiler/experimental/client/__init__.py,sha256=2YMvdxYF_qvps6jWuGTwtUoQrIpEigQLUx_U8Nf-IHE,373 +tensorflow/_api/v2/compat/v2/profiler/experimental/client/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/profiler/experimental/server/__init__.py,sha256=Utk9HePyvdgtAh7jhAJ2TZjf0rI_KUtZvSPBlDqLO8U,311 +tensorflow/_api/v2/compat/v2/profiler/experimental/server/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/quantization/__init__.py,sha256=ShiyvB0VEC-VOtwCHN-c0-fEYghiicnBgLq4MF9-erI,1245 +tensorflow/_api/v2/compat/v2/quantization/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/quantization/experimental/__init__.py,sha256=BcHQDMQ6HXADeE1JTiexp6aXm8AXxIzFmcTCw-g0y7s,1061 +tensorflow/_api/v2/compat/v2/quantization/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/queue/__init__.py,sha256=WXfj4fuCnQQSxRYmL2WrVbM7Fg8zf8sVvZ_EHJs5o8c,573 +tensorflow/_api/v2/compat/v2/queue/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/ragged/__init__.py,sha256=qVV5uqAPyvoRRG7mCtVyPRVTGwpUYr3Une372gFSE6Q,1046 +tensorflow/_api/v2/compat/v2/ragged/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/random/__init__.py,sha256=iOtnjJUy-zYak0YidR1cPNF5xPUlwfF_hybZDxtWzhQ,2783 +tensorflow/_api/v2/compat/v2/random/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/random/experimental/__init__.py,sha256=BcwR5KqTOMK4qo7abELzsvaaD8PSJSUAuZG9IhxdgRY,974 +tensorflow/_api/v2/compat/v2/random/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/raw_ops/__init__.py,sha256=hd9jHJ0pPg_Tmo3a1rTqCBW-iKSrK-f-buSBg4Br1gY,115408 +tensorflow/_api/v2/compat/v2/raw_ops/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/saved_model/__init__.py,sha256=BjNFHWdSvqa8kcqURrNKMRzTKtHC3kjypwBwZ16pgDM,2783 +tensorflow/_api/v2/compat/v2/saved_model/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/saved_model/experimental/__init__.py,sha256=f7IJQ8Y4KdZfsRfRR-1DL1d700X81YooAM5nWZh0LKY,548 +tensorflow/_api/v2/compat/v2/saved_model/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/sets/__init__.py,sha256=nxmv-C-N1j9xfPbguqN0YYsHCPQ6o0sczuWlFRMvjeE,523 +tensorflow/_api/v2/compat/v2/sets/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/signal/__init__.py,sha256=xSoQEa4rJmviavjjhK0LjBOZ2y8gfa1_EfrAlS1DiNg,2692 +tensorflow/_api/v2/compat/v2/signal/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/sparse/__init__.py,sha256=y_q9iwFD3bplZir8wqz85ZDl5F4K-oWfbhSZLGwnNJY,2793 +tensorflow/_api/v2/compat/v2/sparse/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/strings/__init__.py,sha256=IY-RLHmFxBnXajvqltYdGT9D1h4nimNFZkyq3QZZF3w,2455 +tensorflow/_api/v2/compat/v2/strings/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/summary/__init__.py,sha256=ivm3flvMz3SWXE9ZUSP25TtzEXGTz2kGY3Uvfea9zJY,1104 +tensorflow/_api/v2/compat/v2/summary/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/summary/experimental/__init__.py,sha256=SAkuK54N6Uqk3gpQYT0mtdmUirienAN9uqrf-BcO5Uk,507 +tensorflow/_api/v2/compat/v2/summary/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/sysconfig/__init__.py,sha256=1UyALZE_P2X9d7_i_XZ5pKxBe5iiDlx3R3_L6_e5oEA,800 +tensorflow/_api/v2/compat/v2/sysconfig/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/test/__init__.py,sha256=YP1yWwEOXSZIZ9i18vZ7SFHY49fHaZY6b2k8GhLx4Fo,1499 +tensorflow/_api/v2/compat/v2/test/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/test/experimental/__init__.py,sha256=kM0VxmV4U0EePaKpJK-ZZ7hgzjL7KHUGvFLJmwp3uRQ,291 +tensorflow/_api/v2/compat/v2/test/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/tpu/__init__.py,sha256=S18G2xRY-hPJneiVx4ArAgk1PUgOrsPuFvx2osgNRx4,320 +tensorflow/_api/v2/compat/v2/tpu/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/tpu/experimental/__init__.py,sha256=ZV80AqSxyv3tVjlBLw5Su4ZyG3Ko8efb4Dmt3dqPdP0,891 +tensorflow/_api/v2/compat/v2/tpu/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/tpu/experimental/embedding/__init__.py,sha256=zjX7XfPsBTByfm5qMR9vhxIQCpNR3sxgxB6Tcp5OTWY,1227 +tensorflow/_api/v2/compat/v2/tpu/experimental/embedding/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/train/__init__.py,sha256=SVBxj9-_47aIN3A9CgfLshp_Cmd_fbCVOoCz5aLiTNQ,2294 +tensorflow/_api/v2/compat/v2/train/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/train/experimental/__init__.py,sha256=bk6LGwFmrBEA_1Fxt8-XTvNWz42FsOE4qejchgDHX1M,292 +tensorflow/_api/v2/compat/v2/train/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/types/__init__.py,sha256=wWiieggGnbgANv4yJpHpTEeSM9ccy2I7vNyU7DmddQY,263 +tensorflow/_api/v2/compat/v2/types/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/types/experimental/__init__.py,sha256=JRWps2iZCQN1klJ5LLfilgSxGuHRoNlOI3Izl26zszE,923 +tensorflow/_api/v2/compat/v2/types/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/types/experimental/distributed/__init__.py,sha256=r-vPOaEfo43G81zOnCVYbsDZ5jljczv-n-pHZFy0RTE,366 +tensorflow/_api/v2/compat/v2/types/experimental/distributed/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/version/__init__.py,sha256=xflJsSX3x0iUIhQ6s4R0k1CDmefE68yy5Z4BEofeam0,682 +tensorflow/_api/v2/compat/v2/version/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/xla/__init__.py,sha256=44Dd6pCSumzL8nZaglmDfrPX5L1ibOxq3s_D-pPwqPw,259 +tensorflow/_api/v2/compat/v2/xla/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/compat/v2/xla/experimental/__init__.py,sha256=HkZSM_5wBJ1kbvgLfCyLAfFfvh-_TaJTyoGb7TTw39U,374 +tensorflow/_api/v2/compat/v2/xla/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/config/__init__.py,sha256=yr3p4S70FmNtHDM0zJgkMV5wwU4a0HoT6w9L98OC8DE,1928 +tensorflow/_api/v2/config/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/config/experimental/__init__.py,sha256=zD1evBgdSgnRbnNoRUqIUQ_ReVSBClzZnqTd_ZLFfwE,2194 +tensorflow/_api/v2/config/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/config/optimizer/__init__.py,sha256=Xm1tvQ4n0JY-f3g5zg4Qzd8Z_IVGe5arSioFa2JDU2g,634 +tensorflow/_api/v2/config/optimizer/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/config/threading/__init__.py,sha256=MytvNqIgcB4QOzCPtALvhRjzqWNtVyyQooLJk2JkSAY,582 +tensorflow/_api/v2/config/threading/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/data/__init__.py,sha256=dDWMHdsTNeYJa_3Szu_Oophrwea3gzEshLh-tpWCv24,1366 +tensorflow/_api/v2/data/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/data/experimental/__init__.py,sha256=2rNvqU16-HF6Wyo_kPt-3-os221Rlenl_r6ZEnmkzeA,5612 +tensorflow/_api/v2/data/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/data/experimental/service/__init__.py,sha256=8d4lsegpD8ODIKm-xUZmjn4DxltS6dp0O4EMOuLEC6o,1078 +tensorflow/_api/v2/data/experimental/service/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/debugging/__init__.py,sha256=VZlGeAtAMw8HrEawr_3JzIxTYfx73ekwm_UoonK-Vkw,3070 +tensorflow/_api/v2/debugging/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/debugging/experimental/__init__.py,sha256=buFlNlokJCfiYa8g4oeY-7LDzxuSvzL_b-DHL4uMx2Q,405 +tensorflow/_api/v2/debugging/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/distribute/__init__.py,sha256=i3DKF-m_T0uaSuxBDxDjUB2jI3sY2Z_X_eNiuTp3VIk,2756 +tensorflow/_api/v2/distribute/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/distribute/cluster_resolver/__init__.py,sha256=-6xKP5suDV6HS1nirLiOmdpKJvjn0nzEyzYjCMEO-nw,1135 +tensorflow/_api/v2/distribute/cluster_resolver/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/distribute/coordinator/__init__.py,sha256=vCIXtxHvuHBfEPTXX4OqWDejjm1riZ8ZhpNgo6sCAKU,670 +tensorflow/_api/v2/distribute/coordinator/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/distribute/experimental/__init__.py,sha256=pfmmkLGH4680gkJ2PPXsiwsx_GKSICf3kp5OZIDpB5o,1711 +tensorflow/_api/v2/distribute/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/distribute/experimental/coordinator/__init__.py,sha256=ZcBKq5vPHen735z-mkeMRkTUa5sX0LcEuUAkukw5sk0,515 +tensorflow/_api/v2/distribute/experimental/coordinator/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/distribute/experimental/partitioners/__init__.py,sha256=HTcNh2Zi3xTvjceFYGncZ1iLFe1IVL3kkL8M29XV_MY,585 +tensorflow/_api/v2/distribute/experimental/partitioners/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/distribute/experimental/rpc/__init__.py,sha256=yREf0ghX3_Ac2ONQE87Qh1M6JtufnWNcEFu2gVsMZ_s,394 +tensorflow/_api/v2/distribute/experimental/rpc/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/dtypes/__init__.py,sha256=Vm1u3B_3GN-bg7jDG1nkhKA9GWqSvi5F9ZXdkZV2VDA,2311 +tensorflow/_api/v2/dtypes/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/dtypes/experimental/__init__.py,sha256=CSeaJaF0yxZYSF6objNz4OlEYqZ8naa3PkCY2YxGgoo,490 +tensorflow/_api/v2/dtypes/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/errors/__init__.py,sha256=9uMWHyAb-S1pDr-YimWCvSgUBP0sad7zyCYefq-WjTI,2988 +tensorflow/_api/v2/errors/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/experimental/__init__.py,sha256=_Q4O9XsNV9JJW2BonCebROeOc2lzzbDrXBzOvJskIzA,2267 +tensorflow/_api/v2/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/experimental/dlpack/__init__.py,sha256=yswQu62pJwRthG5v2l17cPUnZSS2k3-frPbhjaIjzRY,349 +tensorflow/_api/v2/experimental/dlpack/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/experimental/dtensor/__init__.py,sha256=w48tqFW_-wGbILYp7e2EmiT8bxagk2cMFOkIbgda-p8,3528 +tensorflow/_api/v2/experimental/dtensor/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/experimental/extension_type/__init__.py,sha256=cEAJIgp3LIeh3QzPiNX8d7HahQutjBCHDYvRY0RhcM8,300 +tensorflow/_api/v2/experimental/extension_type/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/experimental/numpy/__init__.py,sha256=z2RR5-Y3w913I31BvAO26i4JA7yBnbwAqz_UCfMOBFg,17601 +tensorflow/_api/v2/experimental/numpy/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/experimental/numpy/random/__init__.py,sha256=gYqwwfyYA8ZEYkUEquhyi07-L8ReEgSNneQONNIuN_8,809 +tensorflow/_api/v2/experimental/numpy/random/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/experimental/tensorrt/__init__.py,sha256=rCq4t3h14nBI4AE03jtJKaVIyOQ44jMBJ3Brk8R_hIU,437 +tensorflow/_api/v2/experimental/tensorrt/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/feature_column/__init__.py,sha256=yw6wWR2g7s4FPmTLNwmKLuLIt7JJhLHJc7l8K3vKFMk,2143 +tensorflow/_api/v2/feature_column/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/graph_util/__init__.py,sha256=zpnMmHiP_2hg9maz43RdJ8kVHPr7Xr9tp9m8hWI7PsM,286 +tensorflow/_api/v2/graph_util/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/image/__init__.py,sha256=5ECUjECT5LQBb8cEiZ5-TQ-YqepqzcNEP0wLMqRN6jE,6102 +tensorflow/_api/v2/image/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/io/__init__.py,sha256=40nlw1j5bfKd9sKpd_OKvvhvFFOHNl4azOWJq__pX9w,3316 +tensorflow/_api/v2/io/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/io/gfile/__init__.py,sha256=8r0drYwnfRWsMUrDJLpVVOkCuRBZYu-kyf_dToTg274,1387 +tensorflow/_api/v2/io/gfile/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/linalg/__init__.py,sha256=xRX1G6Es4LpbcJp1nn0fxiCDkNWEfhiGFHc5K_CSshs,5978 +tensorflow/_api/v2/linalg/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/linalg/experimental/__init__.py,sha256=i1PbArX-DzveKw_a2CLJfPjM4-cTrT8zqBnGlc0JMs4,314 +tensorflow/_api/v2/linalg/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/lite/__init__.py,sha256=D3IvvitLcxjdyzolDqR3hrSo1QSHcZbuPvPVz-mMyNI,672 +tensorflow/_api/v2/lite/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/lite/experimental/__init__.py,sha256=nEs3FNxzhU4onsgdsyTGqhdV-k35IgZUqpC34jbqnkY,709 +tensorflow/_api/v2/lite/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/lite/experimental/authoring/__init__.py,sha256=dR2DMoQyERUXD30NabSLhkFrU4b8FkW-lldgJWkQAUc,303 +tensorflow/_api/v2/lite/experimental/authoring/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/lookup/__init__.py,sha256=0hbU1oPKHb1vUKQFrQPR5d7xp16E33P5ORUZs62_gNc,639 +tensorflow/_api/v2/lookup/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/lookup/experimental/__init__.py,sha256=6i68sJ8ldei1NaaJvjA8kYNK3vp7ZtylJK8sciOFkXs,365 +tensorflow/_api/v2/lookup/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/math/__init__.py,sha256=L4x9w8YIejIuG4qOozD5tAM-o5fRKSaJws06MXZe0l4,9274 +tensorflow/_api/v2/math/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/math/special/__init__.py,sha256=RCQ1NxuzgdSSGPG4tIqKEfY689lzx8arktwpBYb-J6k,1449 +tensorflow/_api/v2/math/special/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/mlir/__init__.py,sha256=AhG_gTzhnNaK58YqabeiKw8NCOYIgxho5Lfdm0MZRNc,251 +tensorflow/_api/v2/mlir/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/mlir/experimental/__init__.py,sha256=994zzXW-QLGLJgYtXQNyYjiZC9_I5gVeK01qrEWa0iE,805 +tensorflow/_api/v2/mlir/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/nest/__init__.py,sha256=gjKeiD0HT9iwKnhHrKvcqllyeCSZBeWF0nWRLgKZFak,533 +tensorflow/_api/v2/nest/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/nn/__init__.py,sha256=6QV7itsxByZHwhAs9QrCTIrkeT2HlDjEnW7p4FKhJQg,7733 +tensorflow/_api/v2/nn/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/nn/experimental/__init__.py,sha256=wLwONSQFFVjTXOurhlUqXDmXoL4bBjovTIo-3a8yIAE,355 +tensorflow/_api/v2/nn/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/profiler/__init__.py,sha256=7KHwigqRjK19axoGobCRsI3f-PJFafXRSJ0OzYeFyF8,259 +tensorflow/_api/v2/profiler/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/profiler/experimental/__init__.py,sha256=LqwMmKVkU075yqVnq_7-M1cbjLsZhQG0V6jeUUKQM6A,686 +tensorflow/_api/v2/profiler/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/profiler/experimental/client/__init__.py,sha256=2YMvdxYF_qvps6jWuGTwtUoQrIpEigQLUx_U8Nf-IHE,373 +tensorflow/_api/v2/profiler/experimental/client/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/profiler/experimental/server/__init__.py,sha256=Utk9HePyvdgtAh7jhAJ2TZjf0rI_KUtZvSPBlDqLO8U,311 +tensorflow/_api/v2/profiler/experimental/server/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/quantization/__init__.py,sha256=TxTsozbDOOtPNh7KlsAKz8oBK-p7u1x8HIM4PAG104E,1235 +tensorflow/_api/v2/quantization/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/quantization/experimental/__init__.py,sha256=BcHQDMQ6HXADeE1JTiexp6aXm8AXxIzFmcTCw-g0y7s,1061 +tensorflow/_api/v2/quantization/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/queue/__init__.py,sha256=WXfj4fuCnQQSxRYmL2WrVbM7Fg8zf8sVvZ_EHJs5o8c,573 +tensorflow/_api/v2/queue/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/ragged/__init__.py,sha256=qVV5uqAPyvoRRG7mCtVyPRVTGwpUYr3Une372gFSE6Q,1046 +tensorflow/_api/v2/ragged/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/random/__init__.py,sha256=Fj6zLpmqCDK0dJt4FQcovISaDaoTdUMOCtH18bxlTlU,2773 +tensorflow/_api/v2/random/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/random/experimental/__init__.py,sha256=BcwR5KqTOMK4qo7abELzsvaaD8PSJSUAuZG9IhxdgRY,974 +tensorflow/_api/v2/random/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/raw_ops/__init__.py,sha256=hd9jHJ0pPg_Tmo3a1rTqCBW-iKSrK-f-buSBg4Br1gY,115408 +tensorflow/_api/v2/raw_ops/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/saved_model/__init__.py,sha256=EP1GaBuRGIGrMRyse0r_cUbtGtd8sNELID-tzWhm9WQ,2773 +tensorflow/_api/v2/saved_model/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/saved_model/experimental/__init__.py,sha256=f7IJQ8Y4KdZfsRfRR-1DL1d700X81YooAM5nWZh0LKY,548 +tensorflow/_api/v2/saved_model/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/sets/__init__.py,sha256=nxmv-C-N1j9xfPbguqN0YYsHCPQ6o0sczuWlFRMvjeE,523 +tensorflow/_api/v2/sets/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/signal/__init__.py,sha256=xSoQEa4rJmviavjjhK0LjBOZ2y8gfa1_EfrAlS1DiNg,2692 +tensorflow/_api/v2/signal/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/sparse/__init__.py,sha256=y_q9iwFD3bplZir8wqz85ZDl5F4K-oWfbhSZLGwnNJY,2793 +tensorflow/_api/v2/sparse/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/strings/__init__.py,sha256=IY-RLHmFxBnXajvqltYdGT9D1h4nimNFZkyq3QZZF3w,2455 +tensorflow/_api/v2/strings/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/summary/__init__.py,sha256=y1QojM4Sh2-mX_G-Pn0xdb_LqvMWXEb55kQEyR8bRTM,1094 +tensorflow/_api/v2/summary/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/summary/experimental/__init__.py,sha256=SAkuK54N6Uqk3gpQYT0mtdmUirienAN9uqrf-BcO5Uk,507 +tensorflow/_api/v2/summary/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/sysconfig/__init__.py,sha256=1UyALZE_P2X9d7_i_XZ5pKxBe5iiDlx3R3_L6_e5oEA,800 +tensorflow/_api/v2/sysconfig/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/test/__init__.py,sha256=3NhYaNhEyx8ULrjKZV0S922nMylgxn0wP1ptW75Q8Hw,1489 +tensorflow/_api/v2/test/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/test/experimental/__init__.py,sha256=kM0VxmV4U0EePaKpJK-ZZ7hgzjL7KHUGvFLJmwp3uRQ,291 +tensorflow/_api/v2/test/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/tpu/__init__.py,sha256=jbc-iRY46yKp6RqALdRoL8I4Kt_o5-TciZvew3ybtAg,310 +tensorflow/_api/v2/tpu/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/tpu/experimental/__init__.py,sha256=FoxoSl763AEfdw0pFA_Xy1a1O4S8VnnT9UIPmCdtUZw,881 +tensorflow/_api/v2/tpu/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/tpu/experimental/embedding/__init__.py,sha256=zjX7XfPsBTByfm5qMR9vhxIQCpNR3sxgxB6Tcp5OTWY,1227 +tensorflow/_api/v2/tpu/experimental/embedding/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/train/__init__.py,sha256=pyvK_mZz_aEQSVLPQ7dFxgzsnxwg3jIfoP35IOrJ4Yc,2284 +tensorflow/_api/v2/train/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/train/experimental/__init__.py,sha256=bk6LGwFmrBEA_1Fxt8-XTvNWz42FsOE4qejchgDHX1M,292 +tensorflow/_api/v2/train/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/types/__init__.py,sha256=ALUQlvLUdkAhEJdHPZn45G4qkkbYwTI7gEL-p0E67Ng,253 +tensorflow/_api/v2/types/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/types/experimental/__init__.py,sha256=q6xHs-5ddcfbeTyJ4pYDZv44qKCS1cSjn7XjIQenRV8,913 +tensorflow/_api/v2/types/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/types/experimental/distributed/__init__.py,sha256=r-vPOaEfo43G81zOnCVYbsDZ5jljczv-n-pHZFy0RTE,366 +tensorflow/_api/v2/types/experimental/distributed/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/v2.py,sha256=sE61V9_NkW5B6sWNH2J5mHnZtiFHh6WlEGnpdE-RNcQ,29449 +tensorflow/_api/v2/version/__init__.py,sha256=xflJsSX3x0iUIhQ6s4R0k1CDmefE68yy5Z4BEofeam0,682 +tensorflow/_api/v2/version/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/xla/__init__.py,sha256=5kiServFjl_vfoLO7wQbCFh4LwW98Z2HqMKsmUM-o8E,249 +tensorflow/_api/v2/xla/__pycache__/__init__.cpython-310.pyc,, +tensorflow/_api/v2/xla/experimental/__init__.py,sha256=HkZSM_5wBJ1kbvgLfCyLAfFfvh-_TaJTyoGb7TTw39U,374 +tensorflow/_api/v2/xla/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/compiler/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/compiler/__pycache__/__init__.cpython-310.pyc,, +tensorflow/compiler/jit/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/compiler/jit/__pycache__/__init__.cpython-310.pyc,, +tensorflow/compiler/jit/ops/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/compiler/jit/ops/__pycache__/__init__.cpython-310.pyc,, +tensorflow/compiler/jit/ops/__pycache__/xla_ops.cpython-310.pyc,, +tensorflow/compiler/jit/ops/__pycache__/xla_ops_grad.cpython-310.pyc,, +tensorflow/compiler/jit/ops/xla_ops.py,sha256=IJW0DxWiqrzCyk5nUxZlPnqnzC5039krC_lPsBwEMJ4,14749 +tensorflow/compiler/jit/ops/xla_ops_grad.py,sha256=rf0MBQECSg9SGTG-OUhwVpFqCq7jNdNaEQdmjFcP-DM,1097 +tensorflow/compiler/mlir/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/compiler/mlir/__pycache__/__init__.cpython-310.pyc,, +tensorflow/compiler/mlir/lite/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/compiler/mlir/lite/__pycache__/__init__.cpython-310.pyc,, +tensorflow/compiler/mlir/lite/debug/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/compiler/mlir/lite/debug/__pycache__/__init__.cpython-310.pyc,, +tensorflow/compiler/mlir/lite/debug/__pycache__/debug_options_pb2.cpython-310.pyc,, +tensorflow/compiler/mlir/lite/debug/debug_options_pb2.py,sha256=Q3i6V9nLlk7zRMBnyQ7NGa8fgmzqGqBp7kY8kvw3PWw,1513 +tensorflow/compiler/mlir/quantization/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/compiler/mlir/quantization/__pycache__/__init__.cpython-310.pyc,, +tensorflow/compiler/mlir/quantization/stablehlo/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/compiler/mlir/quantization/stablehlo/__pycache__/__init__.cpython-310.pyc,, +tensorflow/compiler/mlir/quantization/stablehlo/__pycache__/quantization_options_pb2.cpython-310.pyc,, +tensorflow/compiler/mlir/quantization/stablehlo/quantization_options_pb2.py,sha256=_MlSkXAcPugExPGxAau1qMRlHsWJJ-xQ8E6ZSt8joaU,4174 +tensorflow/compiler/mlir/quantization/tensorflow/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/compiler/mlir/quantization/tensorflow/__pycache__/__init__.cpython-310.pyc,, +tensorflow/compiler/mlir/quantization/tensorflow/__pycache__/exported_model_pb2.cpython-310.pyc,, +tensorflow/compiler/mlir/quantization/tensorflow/__pycache__/quantization_options_pb2.cpython-310.pyc,, +tensorflow/compiler/mlir/quantization/tensorflow/calibrator/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/compiler/mlir/quantization/tensorflow/calibrator/__pycache__/__init__.cpython-310.pyc,, +tensorflow/compiler/mlir/quantization/tensorflow/calibrator/__pycache__/calibration_algorithm.cpython-310.pyc,, +tensorflow/compiler/mlir/quantization/tensorflow/calibrator/__pycache__/calibration_statistics_pb2.cpython-310.pyc,, +tensorflow/compiler/mlir/quantization/tensorflow/calibrator/calibration_algorithm.py,sha256=Y0f3zkmvauKmdEM9H9kRudbWCvgqR7rfw2oNHjfpepU,15024 +tensorflow/compiler/mlir/quantization/tensorflow/calibrator/calibration_statistics_pb2.py,sha256=MCj8TomsQSe9AQhGeKA-XCCPvHQV-PnXwyfX9yKv7y0,2451 +tensorflow/compiler/mlir/quantization/tensorflow/exported_model_pb2.py,sha256=jOTUZpfNauHheWRmHL4xoDZOYX-vZKZlhOGCrv9gmgM,2566 +tensorflow/compiler/mlir/quantization/tensorflow/python/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/compiler/mlir/quantization/tensorflow/python/__pycache__/__init__.cpython-310.pyc,, +tensorflow/compiler/mlir/quantization/tensorflow/python/__pycache__/quantize_model.cpython-310.pyc,, +tensorflow/compiler/mlir/quantization/tensorflow/python/__pycache__/representative_dataset.cpython-310.pyc,, +tensorflow/compiler/mlir/quantization/tensorflow/python/__pycache__/save_model.cpython-310.pyc,, +tensorflow/compiler/mlir/quantization/tensorflow/python/pywrap_quantize_model.so,sha256=_1xkqrHeaBl-4NIr_wex76gNFATbGp-tmnoXMqTxaK0,2088321 +tensorflow/compiler/mlir/quantization/tensorflow/python/quantize_model.py,sha256=9baX_rdKqo3wAp_vKpewu4L6t6v1ADtghEPczFRyCE0,58405 +tensorflow/compiler/mlir/quantization/tensorflow/python/representative_dataset.py,sha256=racCVFsjH3STSj6EVW49EUzoMXvEKH8lhEOca0z25Zg,10989 +tensorflow/compiler/mlir/quantization/tensorflow/python/save_model.py,sha256=KXtUFrkNOPeKb4aN1_41J0loLudpNnEJRf1GwY2BhRk,12510 +tensorflow/compiler/mlir/quantization/tensorflow/quantization_options_pb2.py,sha256=dHEBS8hY_4odWdt_s0BKx755ZnjMqDMf1ai1x3A__lc,8428 +tensorflow/compiler/mlir/stablehlo/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/compiler/mlir/stablehlo/__pycache__/__init__.cpython-310.pyc,, +tensorflow/compiler/mlir/stablehlo/__pycache__/stablehlo.cpython-310.pyc,, +tensorflow/compiler/mlir/stablehlo/stablehlo.py,sha256=DAMP4rMC-Smy7BZNu3iMRFbP9CbV3Xl-NxdkhdvgPOk,1074 +tensorflow/compiler/mlir/stablehlo/stablehlo_extension.so,sha256=fDnDVAZN7MC9lxSwYUNcLPENjSs8RqJKIHTsgM0yHTA,19664088 +tensorflow/compiler/mlir/tensorflow/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/compiler/mlir/tensorflow/__pycache__/__init__.cpython-310.pyc,, +tensorflow/compiler/mlir/tensorflow/__pycache__/gen_mlir_passthrough_op.cpython-310.pyc,, +tensorflow/compiler/mlir/tensorflow/gen_mlir_passthrough_op.py,sha256=mLozkfKsG8Nztuu7PACmYIWT9GKEcEmCnihzWKaUQkI,5096 +tensorflow/compiler/tf2tensorrt/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/compiler/tf2tensorrt/__pycache__/__init__.cpython-310.pyc,, +tensorflow/compiler/tf2tensorrt/_pywrap_py_utils.pyi,sha256=6tDYAm2P_roiFAZbb2i1iJsSwzzW4-QtA15Aov8653U,904 +tensorflow/compiler/tf2tensorrt/_pywrap_py_utils.so,sha256=dq076Ohdux1x7T1TaKN_euLulD2q3h8gv120-jD4QDU,325824 +tensorflow/compiler/tf2tensorrt/ops/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/compiler/tf2tensorrt/ops/__pycache__/__init__.cpython-310.pyc,, +tensorflow/compiler/tf2tensorrt/ops/__pycache__/gen_trt_ops.cpython-310.pyc,, +tensorflow/compiler/tf2tensorrt/ops/gen_trt_ops.py,sha256=z9UUmVBD2PStVyR0OhDgs42LSbKwhYpmf3s6s1rn5oo,34106 +tensorflow/compiler/tf2xla/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/compiler/tf2xla/__pycache__/__init__.cpython-310.pyc,, +tensorflow/compiler/tf2xla/__pycache__/tf2xla_pb2.cpython-310.pyc,, +tensorflow/compiler/tf2xla/ops/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/compiler/tf2xla/ops/__pycache__/__init__.cpython-310.pyc,, +tensorflow/compiler/tf2xla/ops/__pycache__/gen_xla_ops.cpython-310.pyc,, +tensorflow/compiler/tf2xla/ops/_xla_ops.so,sha256=sU_coXV6h5AAWhPQLLdufqiKG6BFVS30-ZkFRehNEEw,1240144 +tensorflow/compiler/tf2xla/ops/gen_xla_ops.py,sha256=ldKBjzb8dxznmCYGxn9M8QYQLVNXjMK3XOXvSmCxub4,238472 +tensorflow/compiler/tf2xla/python/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/compiler/tf2xla/python/__pycache__/__init__.cpython-310.pyc,, +tensorflow/compiler/tf2xla/python/__pycache__/xla.cpython-310.pyc,, +tensorflow/compiler/tf2xla/python/xla.py,sha256=yZGanBfljK4ZXdxiCUbF7_tXb85IGB9gajBQwR-tThM,23354 +tensorflow/compiler/tf2xla/tf2xla_pb2.py,sha256=ZxLMtIXia8T4UaIK_eBPd0YngBCwYZRvwe5hFjxokOM,2833 +tensorflow/compiler/xla/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/compiler/xla/__pycache__/__init__.cpython-310.pyc,, +tensorflow/compiler/xla/__pycache__/xla_data_pb2.cpython-310.pyc,, +tensorflow/compiler/xla/service/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/compiler/xla/service/__pycache__/__init__.cpython-310.pyc,, +tensorflow/compiler/xla/service/__pycache__/hlo_pb2.cpython-310.pyc,, +tensorflow/compiler/xla/service/hlo_pb2.py,sha256=zU-V-D5qdIfaSH3RNMsi-_DqSmQ9NHs_57pb4TmtqNo,19125 +tensorflow/compiler/xla/xla_data_pb2.py,sha256=Xa5arvn3XHPFUMW_R1wTrQTeCpIrd4P1LUgZOfYurJg,17253 +tensorflow/core/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/core/__pycache__/__init__.cpython-310.pyc,, +tensorflow/core/config/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/core/config/__pycache__/__init__.cpython-310.pyc,, +tensorflow/core/config/__pycache__/flags.cpython-310.pyc,, +tensorflow/core/config/flags.py,sha256=0eKeOYfHDyniHdVMhUJBNjpKGqcW8-iCJ5OXOSJeLfE,1013 +tensorflow/core/debug/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/core/debug/__pycache__/__init__.cpython-310.pyc,, +tensorflow/core/debug/__pycache__/debug_service_pb2.cpython-310.pyc,, +tensorflow/core/debug/__pycache__/debug_service_pb2_grpc.cpython-310.pyc,, +tensorflow/core/debug/__pycache__/debugger_event_metadata_pb2.cpython-310.pyc,, +tensorflow/core/debug/debug_service_pb2.py,sha256=HlfV_jHw-ZbkTMbYl4qtARE5e7LKiVDXDTr6Iqwx8xY,3872 +tensorflow/core/debug/debug_service_pb2_grpc.py,sha256=S8xDxr7_Xrdz1u2n5wf1TI7xzyl2RtEkNUL4zcnjY4o,4141 +tensorflow/core/debug/debugger_event_metadata_pb2.py,sha256=emK_6CThvt74zhdYL6Km-9XCmurarde1RXHErnKClAg,1265 +tensorflow/core/distributed_runtime/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/core/distributed_runtime/__pycache__/__init__.cpython-310.pyc,, +tensorflow/core/distributed_runtime/preemption/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/core/distributed_runtime/preemption/__pycache__/__init__.cpython-310.pyc,, +tensorflow/core/distributed_runtime/preemption/__pycache__/gen_check_preemption_op.cpython-310.pyc,, +tensorflow/core/distributed_runtime/preemption/gen_check_preemption_op.py,sha256=bjkNdbxG6i0OZMfg2RQzqMNsN4wsrMQ6srtaBsXyuhg,3883 +tensorflow/core/example/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/core/example/__pycache__/__init__.cpython-310.pyc,, +tensorflow/core/example/__pycache__/example_parser_configuration_pb2.cpython-310.pyc,, +tensorflow/core/example/__pycache__/example_pb2.cpython-310.pyc,, +tensorflow/core/example/__pycache__/feature_pb2.cpython-310.pyc,, +tensorflow/core/example/example_parser_configuration_pb2.py,sha256=wBl70oWiAqyro0Z_olMXvlr7XK0bCKwo8WeD0ooIIug,3573 +tensorflow/core/example/example_pb2.py,sha256=F5KRmhxjMNKbOCUnKEhZK4KnQ9ALJYfxN6bTo0NsoNc,1781 +tensorflow/core/example/feature_pb2.py,sha256=aaHIuRkZO2tQf9YIzrBELjdTZ9QEUX7mgRlkRkSzGww,3482 +tensorflow/core/framework/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/core/framework/__pycache__/__init__.cpython-310.pyc,, +tensorflow/core/framework/__pycache__/allocation_description_pb2.cpython-310.pyc,, +tensorflow/core/framework/__pycache__/api_def_pb2.cpython-310.pyc,, +tensorflow/core/framework/__pycache__/attr_value_pb2.cpython-310.pyc,, +tensorflow/core/framework/__pycache__/cost_graph_pb2.cpython-310.pyc,, +tensorflow/core/framework/__pycache__/cpp_shape_inference_pb2.cpython-310.pyc,, +tensorflow/core/framework/__pycache__/dataset_metadata_pb2.cpython-310.pyc,, +tensorflow/core/framework/__pycache__/dataset_options_pb2.cpython-310.pyc,, +tensorflow/core/framework/__pycache__/dataset_pb2.cpython-310.pyc,, +tensorflow/core/framework/__pycache__/device_attributes_pb2.cpython-310.pyc,, +tensorflow/core/framework/__pycache__/full_type_pb2.cpython-310.pyc,, +tensorflow/core/framework/__pycache__/function_pb2.cpython-310.pyc,, +tensorflow/core/framework/__pycache__/graph_debug_info_pb2.cpython-310.pyc,, +tensorflow/core/framework/__pycache__/graph_pb2.cpython-310.pyc,, +tensorflow/core/framework/__pycache__/graph_transfer_info_pb2.cpython-310.pyc,, +tensorflow/core/framework/__pycache__/kernel_def_pb2.cpython-310.pyc,, +tensorflow/core/framework/__pycache__/log_memory_pb2.cpython-310.pyc,, +tensorflow/core/framework/__pycache__/model_pb2.cpython-310.pyc,, +tensorflow/core/framework/__pycache__/node_def_pb2.cpython-310.pyc,, +tensorflow/core/framework/__pycache__/op_def_pb2.cpython-310.pyc,, +tensorflow/core/framework/__pycache__/optimized_function_graph_pb2.cpython-310.pyc,, +tensorflow/core/framework/__pycache__/reader_base_pb2.cpython-310.pyc,, +tensorflow/core/framework/__pycache__/resource_handle_pb2.cpython-310.pyc,, +tensorflow/core/framework/__pycache__/step_stats_pb2.cpython-310.pyc,, +tensorflow/core/framework/__pycache__/summary_pb2.cpython-310.pyc,, +tensorflow/core/framework/__pycache__/tensor_description_pb2.cpython-310.pyc,, +tensorflow/core/framework/__pycache__/tensor_pb2.cpython-310.pyc,, +tensorflow/core/framework/__pycache__/tensor_shape_pb2.cpython-310.pyc,, +tensorflow/core/framework/__pycache__/tensor_slice_pb2.cpython-310.pyc,, +tensorflow/core/framework/__pycache__/types_pb2.cpython-310.pyc,, +tensorflow/core/framework/__pycache__/variable_pb2.cpython-310.pyc,, +tensorflow/core/framework/__pycache__/versions_pb2.cpython-310.pyc,, +tensorflow/core/framework/allocation_description_pb2.py,sha256=2hJ5k9tltcu7ZS48ldmpy9bYqTOMDbmuW8xlsTt3ako,1758 +tensorflow/core/framework/api_def_pb2.py,sha256=S-N0VZv9mGIRoWBrAGUo9mYSHxso_6mNrxIK-i8qjlI,3303 +tensorflow/core/framework/attr_value_pb2.py,sha256=WCYI-jjEjhyEDrJ6BBEWOGX6CbMlehjgJqTuLM10wYA,4045 +tensorflow/core/framework/cost_graph_pb2.py,sha256=DPf2MU5o46yYmNF05TRqaX64Ny5RUtTCe9GfibCr19s,4110 +tensorflow/core/framework/cpp_shape_inference_pb2.py,sha256=r6VjzwNemAD8RwTlVPxEcWNU9RHHGFVbhQCg9ycixs4,2952 +tensorflow/core/framework/dataset_metadata_pb2.py,sha256=RB1pV649V29CIbwQSibHNHHDKkO5V7kIVINiPJdE0nM,1279 +tensorflow/core/framework/dataset_options_pb2.py,sha256=RlDMTtuBQ8yRdVUrD7eKwCbZS059a_ycHSXOev_anXo,5603 +tensorflow/core/framework/dataset_pb2.py,sha256=Ye9i5Dhwb_duQdxkmEs1Z_EGAWLreZK2wNfQ3AxzUeI,2276 +tensorflow/core/framework/device_attributes_pb2.py,sha256=pa1ekGVbO6yCfEDj8Wan46OLv7I_ZuB2f87y4ypMoI4,2399 +tensorflow/core/framework/full_type_pb2.py,sha256=aiQrGZ9_-NSdAmVIokrFchwOi12LTIv5mSJeY8NPdW4,2836 +tensorflow/core/framework/function_pb2.py,sha256=V1chTlZWh31Plz3oH_I51DJd5jJ-W8EltKZ5gM3GLL8,5310 +tensorflow/core/framework/graph_debug_info_pb2.py,sha256=c3k7mNa4rPO-wUATR5aXNv1pVV5smnk0N9rUlYgtL1M,3999 +tensorflow/core/framework/graph_pb2.py,sha256=xLUQjoVqZQU5M-6X9fKO0LXDoDEJnf1Wz-sl0lPppKI,2400 +tensorflow/core/framework/graph_transfer_info_pb2.py,sha256=3-xE5qiiR4Tyk7v70KUMAV1r-FMk8Gvg2TQ10jt6LRE,4426 +tensorflow/core/framework/kernel_def_pb2.py,sha256=Cg8RSklmQnuGhysiZ3r4PMKhC0xPzPcVVeF_DZYqGhs,2174 +tensorflow/core/framework/log_memory_pb2.py,sha256=RMHjdw8bLRo3WEMDs3tdC9g3PpXsd3qP9qSLsyy29pE,3171 +tensorflow/core/framework/model_pb2.py,sha256=bkZHbImx5-ZECj8omfgujw2c8uC_sdDa4t6SxeFHOcg,4179 +tensorflow/core/framework/node_def_pb2.py,sha256=VoMPjfYoLEdydEMSJDi-FdAGo_ndwUwds2795h9ey3o,2570 +tensorflow/core/framework/op_def_pb2.py,sha256=8hE2MzMRoqCxOFHloakv3yHU8lF1nX9617UiCkJqZ_I,3989 +tensorflow/core/framework/optimized_function_graph_pb2.py,sha256=z-DAROiudMQOSvjLHdMAsHOs_u2NogNLmMM-llecPrE,2631 +tensorflow/core/framework/reader_base_pb2.py,sha256=_AWWumBf8PEGhUuDcBHNShvMlOqKZueJeeFMKudAicM,1562 +tensorflow/core/framework/resource_handle_pb2.py,sha256=VUnCPOFrgYuVanr5BFyR5qLYUY1-61vUqvHj3uaF0N4,2311 +tensorflow/core/framework/step_stats_pb2.py,sha256=n_mgXYntM6x86t2mgG72OuPQagJ_n1FodidqOCjBGao,5349 +tensorflow/core/framework/summary_pb2.py,sha256=z9vclVvURBIO4N80CdLoG3zxSUHlsuY0mh0tFLP5EIw,3950 +tensorflow/core/framework/tensor_description_pb2.py,sha256=lPLgO6uE3MiDv___ZwVv6zNn1BhZmobb4Juny-Zb_UI,2169 +tensorflow/core/framework/tensor_pb2.py,sha256=0J7jJZbCIKqKLU14piPdDM-4-2oqpt7ervnIikjmINM,4497 +tensorflow/core/framework/tensor_shape_pb2.py,sha256=t_iOsH7tSQx0vcmIhaGT6QApsk7N23u3MklPSMH1kVk,1676 +tensorflow/core/framework/tensor_slice_pb2.py,sha256=v-P-YAbodI9jOmAHIy6P1S733BABrRpNF7ZbFh46U8c,1690 +tensorflow/core/framework/types_pb2.py,sha256=RGvp761xWNo8c9hR-3PP0dTOAlMqhxPVzijRaiuuHoA,3312 +tensorflow/core/framework/variable_pb2.py,sha256=Y1VGLuK8eVltNOZ-WpnjbnR7K5LinNW6eolU6vVJxfk,2772 +tensorflow/core/framework/versions_pb2.py,sha256=R6b4_RzE1jX8lJ5fE3ycjVrpP9Ctpy64gE2wlmBB-Ls,1467 +tensorflow/core/function/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/core/function/__pycache__/__init__.cpython-310.pyc,, +tensorflow/core/function/capture/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/core/function/capture/__pycache__/__init__.cpython-310.pyc,, +tensorflow/core/function/capture/__pycache__/capture_container.cpython-310.pyc,, +tensorflow/core/function/capture/__pycache__/restore_captures.cpython-310.pyc,, +tensorflow/core/function/capture/capture_container.py,sha256=zYyHKaaHuft4d14G4d20oKZn8zod-HgPVs2tXi22Ngc,12184 +tensorflow/core/function/capture/restore_captures.py,sha256=dqWbst7igQVOfvyorjgQfPUB7ALXucvCvcWUD3ox0zw,5840 +tensorflow/core/function/polymorphism/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/core/function/polymorphism/__pycache__/__init__.cpython-310.pyc,, +tensorflow/core/function/polymorphism/__pycache__/function_cache.cpython-310.pyc,, +tensorflow/core/function/polymorphism/__pycache__/function_type.cpython-310.pyc,, +tensorflow/core/function/polymorphism/__pycache__/function_type_pb2.cpython-310.pyc,, +tensorflow/core/function/polymorphism/__pycache__/type_dispatch.cpython-310.pyc,, +tensorflow/core/function/polymorphism/function_cache.py,sha256=R-l_CjBocNB12Ows6xnft0ee7KzEOJpd9W9d7pRjTfA,3692 +tensorflow/core/function/polymorphism/function_type.py,sha256=i6NWHyWXOHRMkAYKPChutmkmuQjcOdL-9_fGR-I9Bv8,26771 +tensorflow/core/function/polymorphism/function_type_pb2.py,sha256=UMpUyCYs44Jvx29nZ1Zzhudz6HXBT-xnlAkIkfABWOs,2451 +tensorflow/core/function/polymorphism/type_dispatch.py,sha256=QRc_0Ash8RP4eq04-Ul_rTFGKzvGHeSC1melxNSjUz0,5178 +tensorflow/core/function/trace_type/__init__.py,sha256=r3ysLAFR_cKJfX4-juaNMRKsL7NJQg7DGVxiyApBcDw,2038 +tensorflow/core/function/trace_type/__pycache__/__init__.cpython-310.pyc,, +tensorflow/core/function/trace_type/__pycache__/custom_nest_trace_type.cpython-310.pyc,, +tensorflow/core/function/trace_type/__pycache__/default_types.cpython-310.pyc,, +tensorflow/core/function/trace_type/__pycache__/default_types_pb2.cpython-310.pyc,, +tensorflow/core/function/trace_type/__pycache__/serialization.cpython-310.pyc,, +tensorflow/core/function/trace_type/__pycache__/serialization_pb2.cpython-310.pyc,, +tensorflow/core/function/trace_type/__pycache__/serialization_test_pb2.cpython-310.pyc,, +tensorflow/core/function/trace_type/__pycache__/trace_type_builder.cpython-310.pyc,, +tensorflow/core/function/trace_type/__pycache__/util.cpython-310.pyc,, +tensorflow/core/function/trace_type/custom_nest_trace_type.py,sha256=uK1saVahk7xuzHiKWj17d8GbbtZ1WKHIGJDO0a5gWEY,5425 +tensorflow/core/function/trace_type/default_types.py,sha256=RsZh-jRraelEuSmo9SAqh8daSsKI9BqXNzIA9UVT3pw,27836 +tensorflow/core/function/trace_type/default_types_pb2.py,sha256=i19RpDlfu8Khf04ssPAYVwsSDNF0jgJ8TVvdG865cAM,3077 +tensorflow/core/function/trace_type/serialization.py,sha256=UB28Ts0n6uJ7n8VDqTB6kmN2YkilqmmRvndci3r-524,3717 +tensorflow/core/function/trace_type/serialization_pb2.py,sha256=pjavgiYRtQoRSVKeRhEe5CuQy7Fel94USx0re5WbUtw,1273 +tensorflow/core/function/trace_type/serialization_test_pb2.py,sha256=OBKTJDsfvOB7kA7uFA--2jdcqcueBOvFGCUBFwNuv5s,1820 +tensorflow/core/function/trace_type/trace_type_builder.py,sha256=VpGjoSHej5-X8f8TByww53j9WS1PXITjnqPSA98_V4U,7512 +tensorflow/core/function/trace_type/util.py,sha256=zdo--MG1F8hryt6yszTmzcYI3tR7P3vDb0ATvkjvZrk,1792 +tensorflow/core/grappler/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/core/grappler/__pycache__/__init__.cpython-310.pyc,, +tensorflow/core/grappler/costs/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/core/grappler/costs/__pycache__/__init__.cpython-310.pyc,, +tensorflow/core/grappler/costs/__pycache__/op_performance_data_pb2.cpython-310.pyc,, +tensorflow/core/grappler/costs/op_performance_data_pb2.py,sha256=wsEfj3wDIt-gyuAJPhsWj3GdDa0dTp1BbidSX7KffXw,5435 +tensorflow/core/kernels/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/core/kernels/__pycache__/__init__.cpython-310.pyc,, +tensorflow/core/kernels/libtfkernel_sobol_op.so,sha256=aWSQJ2NmGxf7HV7ynav73CvHqTNiGD9Cee129BxQGJk,5859600 +tensorflow/core/lib/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/core/lib/__pycache__/__init__.cpython-310.pyc,, +tensorflow/core/lib/core/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/core/lib/core/__pycache__/__init__.cpython-310.pyc,, +tensorflow/core/lib/core/__pycache__/error_codes_pb2.cpython-310.pyc,, +tensorflow/core/lib/core/error_codes_pb2.py,sha256=C1PYZDoNuR8-ecVWTOIlgkPLZePD1W4deXB0V0qd0gM,1090 +tensorflow/core/profiler/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/core/profiler/__pycache__/__init__.cpython-310.pyc,, +tensorflow/core/profiler/__pycache__/profile_pb2.cpython-310.pyc,, +tensorflow/core/profiler/__pycache__/profiler_options_pb2.cpython-310.pyc,, +tensorflow/core/profiler/__pycache__/tfprof_log_pb2.cpython-310.pyc,, +tensorflow/core/profiler/__pycache__/tfprof_options_pb2.cpython-310.pyc,, +tensorflow/core/profiler/__pycache__/tfprof_output_pb2.cpython-310.pyc,, +tensorflow/core/profiler/profile_pb2.py,sha256=oOJcuqxuzB7zqzMkMD8HTFiUsmwi273jTcc0KXKQbKc,1135 +tensorflow/core/profiler/profiler_options_pb2.py,sha256=RYYEMgvSrCT7IgklI4XCU4LyZRShQdqb03qVosBBSO0,1186 +tensorflow/core/profiler/protobuf/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/core/profiler/protobuf/__pycache__/__init__.cpython-310.pyc,, +tensorflow/core/profiler/protobuf/__pycache__/xplane_pb2.cpython-310.pyc,, +tensorflow/core/profiler/protobuf/xplane_pb2.py,sha256=8CIizTafxKDq6Dn4uzeMQ-Wd1T7QFGDSiORNPkO_keQ,1152 +tensorflow/core/profiler/tfprof_log_pb2.py,sha256=BVb6nbElEtu3ywUC0CuRBmSg9JfiymuI1tl_mjkVDvg,10728 +tensorflow/core/profiler/tfprof_options_pb2.py,sha256=bZc5mkfG0_rEHoImku0sIYTkYB1zkM4Me9wBgrgKYBY,3303 +tensorflow/core/profiler/tfprof_output_pb2.py,sha256=Dn57qqJ3Vu14HaxEyxPEOVtcxeGBSY5Hwp8vvo_RYEI,5339 +tensorflow/core/protobuf/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/core/protobuf/__pycache__/__init__.cpython-310.pyc,, +tensorflow/core/protobuf/__pycache__/bfc_memory_map_pb2.cpython-310.pyc,, +tensorflow/core/protobuf/__pycache__/cluster_pb2.cpython-310.pyc,, +tensorflow/core/protobuf/__pycache__/composite_tensor_variant_pb2.cpython-310.pyc,, +tensorflow/core/protobuf/__pycache__/config_pb2.cpython-310.pyc,, +tensorflow/core/protobuf/__pycache__/control_flow_pb2.cpython-310.pyc,, +tensorflow/core/protobuf/__pycache__/core_platform_payloads_pb2.cpython-310.pyc,, +tensorflow/core/protobuf/__pycache__/data_service_pb2.cpython-310.pyc,, +tensorflow/core/protobuf/__pycache__/debug_event_pb2.cpython-310.pyc,, +tensorflow/core/protobuf/__pycache__/debug_pb2.cpython-310.pyc,, +tensorflow/core/protobuf/__pycache__/device_filters_pb2.cpython-310.pyc,, +tensorflow/core/protobuf/__pycache__/device_properties_pb2.cpython-310.pyc,, +tensorflow/core/protobuf/__pycache__/error_codes_pb2.cpython-310.pyc,, +tensorflow/core/protobuf/__pycache__/fingerprint_pb2.cpython-310.pyc,, +tensorflow/core/protobuf/__pycache__/meta_graph_pb2.cpython-310.pyc,, +tensorflow/core/protobuf/__pycache__/named_tensor_pb2.cpython-310.pyc,, +tensorflow/core/protobuf/__pycache__/queue_runner_pb2.cpython-310.pyc,, +tensorflow/core/protobuf/__pycache__/remote_tensor_handle_pb2.cpython-310.pyc,, +tensorflow/core/protobuf/__pycache__/rewriter_config_pb2.cpython-310.pyc,, +tensorflow/core/protobuf/__pycache__/rpc_options_pb2.cpython-310.pyc,, +tensorflow/core/protobuf/__pycache__/saved_model_pb2.cpython-310.pyc,, +tensorflow/core/protobuf/__pycache__/saved_object_graph_pb2.cpython-310.pyc,, +tensorflow/core/protobuf/__pycache__/saver_pb2.cpython-310.pyc,, +tensorflow/core/protobuf/__pycache__/service_config_pb2.cpython-310.pyc,, +tensorflow/core/protobuf/__pycache__/snapshot_pb2.cpython-310.pyc,, +tensorflow/core/protobuf/__pycache__/status_pb2.cpython-310.pyc,, +tensorflow/core/protobuf/__pycache__/struct_pb2.cpython-310.pyc,, +tensorflow/core/protobuf/__pycache__/tensor_bundle_pb2.cpython-310.pyc,, +tensorflow/core/protobuf/__pycache__/tensorflow_server_pb2.cpython-310.pyc,, +tensorflow/core/protobuf/__pycache__/trackable_object_graph_pb2.cpython-310.pyc,, +tensorflow/core/protobuf/__pycache__/transport_options_pb2.cpython-310.pyc,, +tensorflow/core/protobuf/__pycache__/verifier_config_pb2.cpython-310.pyc,, +tensorflow/core/protobuf/bfc_memory_map_pb2.py,sha256=toN1gAESm9cjM9__-to4PLz7AdKJomeiINB7hJb18Ws,1348 +tensorflow/core/protobuf/cluster_pb2.py,sha256=1nafgOIWUBKL_VxBmtvBCwKS9BYWD7SQPaGFr9qan1g,1857 +tensorflow/core/protobuf/composite_tensor_variant_pb2.py,sha256=EqRpaulep9pFzOkRHSwU0g8GRMIk5Zw4j3zlUKiIRLA,1540 +tensorflow/core/protobuf/config_pb2.py,sha256=TfXLBAtIFAjDIdyIw6kWuXSD6ST-PfxkAcOccaE5tpM,14169 +tensorflow/core/protobuf/control_flow_pb2.py,sha256=k69r2I_nn4SpvQsjOKUK0viTiHkvBehyF9fPw-J-5Zk,3280 +tensorflow/core/protobuf/core_platform_payloads_pb2.py,sha256=2sNuPK7xp3wY2pcPFBBbz3NBGT1--86AaEqnZPvaerw,1788 +tensorflow/core/protobuf/data_service_pb2.py,sha256=5QZp0Ifl_QA6IQagVmvyjoiqAMMpD8xO_w6p2JZcAiM,3009 +tensorflow/core/protobuf/debug_event_pb2.py,sha256=hpsjhVumf_IJtHmQ5z0EPJd7nZmbTuCQvY776Utezng,5901 +tensorflow/core/protobuf/debug_pb2.py,sha256=BfQxjFM_4FMeiCJ4OPPGPePEMwoeOtlXh2UBsVoVgBc,2408 +tensorflow/core/protobuf/device_filters_pb2.py,sha256=_ifWVAc6z_aBTA4h_dnrmNs5EqQ2q1KVkOx7_dzphVw,2229 +tensorflow/core/protobuf/device_properties_pb2.py,sha256=k3rm77qfR-O3YGOYLUzizRbg0azhHsLT4-dkiGNRnuo,2490 +tensorflow/core/protobuf/error_codes_pb2.py,sha256=M6jlmOt7AOb6qD0ztpFoXJeRu69l_QMIXvsuLSsW5RY,1335 +tensorflow/core/protobuf/fingerprint_pb2.py,sha256=KcafAry-DL_S6wCGY1X7qePwRZMNpGVel4BDzkPQKfI,1868 +tensorflow/core/protobuf/meta_graph_pb2.py,sha256=s0LO_aEhmw1vfWSNlDXxxAFoFoAKxECr6ty9fe9UOnU,9335 +tensorflow/core/protobuf/named_tensor_pb2.py,sha256=hQtLasQqAichTwOfFPIIyEdPuiT1o9qcISvyZN59WnE,1630 +tensorflow/core/protobuf/queue_runner_pb2.py,sha256=f2s0bnC8siBRZ_mhpycHua3XLuedaf7YSccik_utpP8,2100 +tensorflow/core/protobuf/remote_tensor_handle_pb2.py,sha256=PS9qw3u2ibtReKlKyaZyrrntvwGF6HtwK9DLuUznJOc,2326 +tensorflow/core/protobuf/rewriter_config_pb2.py,sha256=xmwpD5NmBj1kiDBRHIlT3X2iwl42s7VhF2hpOxG4Nlo,7137 +tensorflow/core/protobuf/rpc_options_pb2.py,sha256=k3QaQ6uVfwGDFB9JWC9skw1k0VqKz6b9JHd4sT4ETqg,1329 +tensorflow/core/protobuf/saved_model_pb2.py,sha256=BV8yS57OMnYJ7IesO7vocCSi8T6oC1SlbeWDGsXTwUU,1643 +tensorflow/core/protobuf/saved_object_graph_pb2.py,sha256=HfEOaBwTDvhhX0SUET33WCT4EPtthN6PuTDoFaZwaAw,8178 +tensorflow/core/protobuf/saver_pb2.py,sha256=svykA5Amt3_wdfWfxVyrMmVlXRz3kEk34_pp2U7h99U,1912 +tensorflow/core/protobuf/service_config_pb2.py,sha256=Ojg0NyvE0gjgafO7U-AevOqeonQVazAhmfq1yBpmpTs,2762 +tensorflow/core/protobuf/snapshot_pb2.py,sha256=ZhJq8LbgtYCTdiYomfEeghuLahahj6F5hsgSzpx2dqs,2893 +tensorflow/core/protobuf/status_pb2.py,sha256=N6mvkJ-GGM258iXTj-B-1G_iTES8vCKJQNaMvKAvstk,1293 +tensorflow/core/protobuf/struct_pb2.py,sha256=M9EZvxsYy9jb2oAhPKnIwmaFKc1XfaXIhlWu58fNvow,5884 +tensorflow/core/protobuf/tensor_bundle_pb2.py,sha256=-7uGGiBM7rLT6xsGOZ0pU0CRs1baHL8uHBRpRV-JFBo,2858 +tensorflow/core/protobuf/tensorflow_server_pb2.py,sha256=Hc1-zCFP7RRXMfBdXdDHqInfIwVjOh9jOZbk0NMR-Og,2281 +tensorflow/core/protobuf/tpu/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/core/protobuf/tpu/__pycache__/__init__.cpython-310.pyc,, +tensorflow/core/protobuf/tpu/__pycache__/compilation_result_pb2.cpython-310.pyc,, +tensorflow/core/protobuf/tpu/__pycache__/dynamic_padding_pb2.cpython-310.pyc,, +tensorflow/core/protobuf/tpu/__pycache__/optimization_parameters_pb2.cpython-310.pyc,, +tensorflow/core/protobuf/tpu/__pycache__/topology_pb2.cpython-310.pyc,, +tensorflow/core/protobuf/tpu/__pycache__/tpu_embedding_configuration_pb2.cpython-310.pyc,, +tensorflow/core/protobuf/tpu/compilation_result_pb2.py,sha256=frjngNw16H4IKVGz00Hqo1GivKviS9QOERPu1QRvxdc,2187 +tensorflow/core/protobuf/tpu/dynamic_padding_pb2.py,sha256=gRszmyBWR_zC8hMqbHZtF3S-nTrAxnF8MiuROtZOCmI,1233 +tensorflow/core/protobuf/tpu/optimization_parameters_pb2.py,sha256=Hy3fDH2rbekizGbkBlM_IS3pE2Rxs5F7Gc5ktvaOj5k,12725 +tensorflow/core/protobuf/tpu/topology_pb2.py,sha256=cZMPUnv9e2TgAGG1WwjrmaPppyFzG7Syk5r8BloWa9Q,1887 +tensorflow/core/protobuf/tpu/tpu_embedding_configuration_pb2.py,sha256=kd3OhO4Ce7BRhehHLq07vpAlr6a_Ob5PgiDbInB2JZA,3708 +tensorflow/core/protobuf/trackable_object_graph_pb2.py,sha256=FPB5Va97OLpmSH-yIA7KEpkkNL60QMyGiyvI4WfubqE,3315 +tensorflow/core/protobuf/transport_options_pb2.py,sha256=PlouQ9u3OpAHC0QI5_LFtwgvnfQK3GznhBtGQg3AdVk,1300 +tensorflow/core/protobuf/verifier_config_pb2.py,sha256=bJF0kdthbi2WxJYiY4Ws8mMiva7Qi2TtPzSqqxvkpQw,1741 +tensorflow/core/util/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/core/util/__pycache__/__init__.cpython-310.pyc,, +tensorflow/core/util/__pycache__/event_pb2.cpython-310.pyc,, +tensorflow/core/util/__pycache__/memmapped_file_system_pb2.cpython-310.pyc,, +tensorflow/core/util/__pycache__/saved_tensor_slice_pb2.cpython-310.pyc,, +tensorflow/core/util/__pycache__/test_log_pb2.cpython-310.pyc,, +tensorflow/core/util/event_pb2.py,sha256=z_6SF0DC2e2zlgS2z7oHGRfaYZIp0kGvhMYdAHS1Ut0,5418 +tensorflow/core/util/memmapped_file_system_pb2.py,sha256=-U5l-uFNJrbS8M-TP8vO2h0fySlRvzUsXfeM8GcmXKs,1505 +tensorflow/core/util/quantization/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/core/util/quantization/__pycache__/__init__.cpython-310.pyc,, +tensorflow/core/util/quantization/__pycache__/uniform_quant_ops_attr_pb2.cpython-310.pyc,, +tensorflow/core/util/quantization/uniform_quant_ops_attr_pb2.py,sha256=RHglEOg-gWnA4XmiNH4XGEMLufx_KmBdpGrxKcZNS_U,1887 +tensorflow/core/util/saved_tensor_slice_pb2.py,sha256=bEaWbLvmWO3gtHqocLQYcis7hQL2NMxTLVDBCfr-sP0,2978 +tensorflow/core/util/test_log_pb2.py,sha256=GXW7emqth1c8PlqtdGmvCCrZiFH-hwzpDbx2nczv1Hw,1081 +tensorflow/distribute/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/distribute/__pycache__/__init__.cpython-310.pyc,, +tensorflow/distribute/experimental/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/distribute/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/distribute/experimental/rpc/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/distribute/experimental/rpc/__pycache__/__init__.cpython-310.pyc,, +tensorflow/distribute/experimental/rpc/kernels/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/distribute/experimental/rpc/kernels/__pycache__/__init__.cpython-310.pyc,, +tensorflow/distribute/experimental/rpc/kernels/__pycache__/gen_rpc_ops.cpython-310.pyc,, +tensorflow/distribute/experimental/rpc/kernels/gen_rpc_ops.py,sha256=KzF8SKLbONvuxHd7F-_YBHFBZSCKNts9pIMlcz82nQs,29268 +tensorflow/distribute/experimental/rpc/proto/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/distribute/experimental/rpc/proto/__pycache__/__init__.cpython-310.pyc,, +tensorflow/distribute/experimental/rpc/proto/__pycache__/tf_rpc_service_pb2.cpython-310.pyc,, +tensorflow/distribute/experimental/rpc/proto/__pycache__/tf_rpc_service_pb2_grpc.cpython-310.pyc,, +tensorflow/distribute/experimental/rpc/proto/tf_rpc_service_pb2.py,sha256=mZvoAMgm2obxVhra8ib6Yi0SM-KDZhwhIBtk6z4A_0c,2525 +tensorflow/distribute/experimental/rpc/proto/tf_rpc_service_pb2_grpc.py,sha256=gSFJEBBV29aXkzV-d6FPui42TJQMVKMtAEzrON3CjaE,2843 +tensorflow/dtensor/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/dtensor/__pycache__/__init__.cpython-310.pyc,, +tensorflow/dtensor/proto/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/dtensor/proto/__pycache__/__init__.cpython-310.pyc,, +tensorflow/dtensor/proto/__pycache__/layout_pb2.cpython-310.pyc,, +tensorflow/dtensor/proto/layout_pb2.py,sha256=BDNBCjSH936zc49e15KUo4oJ36-UpBelymV-lRcvoXE,2295 +tensorflow/dtensor/python/__init__.py,sha256=7YC5pYdt9ltRbDblbSvqbD5iHj-yyEl17nO-nOJ0nY0,757 +tensorflow/dtensor/python/__pycache__/__init__.cpython-310.pyc,, +tensorflow/dtensor/python/__pycache__/accelerator_util.cpython-310.pyc,, +tensorflow/dtensor/python/__pycache__/api.cpython-310.pyc,, +tensorflow/dtensor/python/__pycache__/config.cpython-310.pyc,, +tensorflow/dtensor/python/__pycache__/d_checkpoint.cpython-310.pyc,, +tensorflow/dtensor/python/__pycache__/d_variable.cpython-310.pyc,, +tensorflow/dtensor/python/__pycache__/dtensor_device.cpython-310.pyc,, +tensorflow/dtensor/python/__pycache__/gen_dtensor_ops.cpython-310.pyc,, +tensorflow/dtensor/python/__pycache__/input_util.cpython-310.pyc,, +tensorflow/dtensor/python/__pycache__/layout.cpython-310.pyc,, +tensorflow/dtensor/python/__pycache__/mesh_util.cpython-310.pyc,, +tensorflow/dtensor/python/__pycache__/numpy_util.cpython-310.pyc,, +tensorflow/dtensor/python/__pycache__/save_restore.cpython-310.pyc,, +tensorflow/dtensor/python/__pycache__/tpu_util.cpython-310.pyc,, +tensorflow/dtensor/python/accelerator_util.py,sha256=SiiM8fixtX3J3clyH7z6mzRSH7lGHumXHZK3-1YEOVI,12500 +tensorflow/dtensor/python/api.py,sha256=aoEdLqf4b0ntMEM7w_pKRj1ia5vL4yn0VEIeNH6peDI,18200 +tensorflow/dtensor/python/config.py,sha256=zMQZq1gwkNONJ97s_cXhP5lBKI8KLgd4y-ubaHmzMh4,7986 +tensorflow/dtensor/python/d_checkpoint.py,sha256=pbG6Ce-bSk-pZtUZ-XVFEIotKE16vNFtflPgbtZ6pYY,20687 +tensorflow/dtensor/python/d_variable.py,sha256=9H0WYIhMT993RQEV7E5wdiyKjlOCmEe0Krvk2Yddo7s,10576 +tensorflow/dtensor/python/dtensor_device.py,sha256=KLAn6mUDO4vS2W9PTrTt3H8Qxb-xr-uNmKKZkQmthoU,16006 +tensorflow/dtensor/python/gen_dtensor_ops.py,sha256=nFHgyBRMGJ-RfNCu-Yr94GDKTMOQqEm_nDKhx8MsTfk,31892 +tensorflow/dtensor/python/input_util.py,sha256=LWJnzvy_LYFbsdg8FtZ-uEFlUcRhc6iEV0b6zDrewwY,27727 +tensorflow/dtensor/python/layout.py,sha256=Wzj9LI0cc14KB83K8cMIZ30qy11XFskF5x-ps72ekyo,20343 +tensorflow/dtensor/python/mesh_util.py,sha256=eSyMthVyfqb5lZwt2gJruPrT3LgXaiRSEVegCczklko,12157 +tensorflow/dtensor/python/numpy_util.py,sha256=QdPsuynohVibPRIZLGcfRMvpXmDiuN7klTt_hXjVMX0,4392 +tensorflow/dtensor/python/save_restore.py,sha256=x9mHZ5GzMs1GhUUxwvzIZet3s6Qr_7wDjihwkMUYxCg,9179 +tensorflow/dtensor/python/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/dtensor/python/tests/__pycache__/__init__.cpython-310.pyc,, +tensorflow/dtensor/python/tests/__pycache__/multi_client_test_util.cpython-310.pyc,, +tensorflow/dtensor/python/tests/__pycache__/test_backend_name.cpython-310.pyc,, +tensorflow/dtensor/python/tests/__pycache__/test_backend_util.cpython-310.pyc,, +tensorflow/dtensor/python/tests/__pycache__/test_util.cpython-310.pyc,, +tensorflow/dtensor/python/tests/__pycache__/test_util_ops.cpython-310.pyc,, +tensorflow/dtensor/python/tests/multi_client_test_util.py,sha256=Q8Uukvc0kbuc6oeXaXHHi674AcgrVOI1bHPsr1DxCRM,4893 +tensorflow/dtensor/python/tests/test_backend_name.py,sha256=NSGYTE57MVn79nGUiwp-O3dhhlbEV6pa6VcbO7dcfIU,1283 +tensorflow/dtensor/python/tests/test_backend_util.py,sha256=yfd-xod5_l247kfDxB6jdoHTDmZDwJZTlEwUKSKYqSE,2805 +tensorflow/dtensor/python/tests/test_util.py,sha256=A-ZumuZDYkiDET5gqjDW0Ig8tEhAn_0Hs2xn33Iq25g,14626 +tensorflow/dtensor/python/tests/test_util_ops.py,sha256=XV9sbFUkAM1kTCYwCopgJEjfTIfFHtTMuyTxbdPP-nA,15798 +tensorflow/dtensor/python/tpu_util.py,sha256=zHSgykfmc1QhL-dxBoXqq3WHCmmKPNoc9rbwNkEX1kw,32532 +tensorflow/include/Eigen/AccelerateSupport,sha256=o8OjMr5XLesbNMMc1i8vXiDx7hliYFm9l1oKhfDxPow,2116 +tensorflow/include/Eigen/Cholesky,sha256=VPdSkfvtQVkKZ0fxPlUaLWDF89Ew85Oaf69veHbWsz8,1168 +tensorflow/include/Eigen/CholmodSupport,sha256=lBtCJbr1IaStipxadftKgCAPDiuPBZ7vMndJCAfOrrQ,1958 +tensorflow/include/Eigen/Core,sha256=9VJ29w0mKpBl5EvGlvJJ9Di_bJJsaY1Ds3f8pakXU8c,13596 +tensorflow/include/Eigen/Dense,sha256=UyXJ1NaT5QTuASxSda1LELE1pwHL2HwURm0uoh6iLuU,122 +tensorflow/include/Eigen/Eigen,sha256=sEc7XXwM2TEdSpBUgWLozxYJBEdocff7dJ6WJOmz39E,35 +tensorflow/include/Eigen/Eigenvalues,sha256=jTZcEf6E26zS8cJBiRmCdgUHFB9qNVi-7fe2dmEiZlE,1836 +tensorflow/include/Eigen/Geometry,sha256=JGqKT_Hj87OIsvrdiKpT3JwCizZxjo-ChSZfl2644b4,1997 +tensorflow/include/Eigen/Householder,sha256=__vXdVk7ZqWHOGK7cINK864qH6iPyWwO2KQ3SDmUZVY,887 +tensorflow/include/Eigen/IterativeLinearSolvers,sha256=6eq9Fz4mMMgAl7iH3KRP5I8Sm1V9HkkXhZ7ZOq_XKVg,2160 +tensorflow/include/Eigen/Jacobi,sha256=i72UjwD31up57bRRwG16qz6IEZMwlFUl8D5PQpVF7i8,952 +tensorflow/include/Eigen/KLUSupport,sha256=l5WfXMnpQow8gCyWQHVDb519cxL-3UDKCEpCp65b4Dc,1429 +tensorflow/include/Eigen/LU,sha256=mIwgzncMRYOKXQQUX4kK6fDHVoP8vphM-xPJA_WKIGo,1276 +tensorflow/include/Eigen/MetisSupport,sha256=_dHevgSQxC_Zn4uqU6yGArw_NJc6uHeuguj2LD6usSE,1048 +tensorflow/include/Eigen/OrderingMethods,sha256=yeROxXU6pM-AaSHRxvGw7mDNcyJuekm_X6p_8LNv-9I,2510 +tensorflow/include/Eigen/PaStiXSupport,sha256=PZVxX5sDNbH2H-gkJvgGugD-bfKULpTD_MwkilqlnjA,1809 +tensorflow/include/Eigen/PardisoSupport,sha256=1A2UgWvbMe_UUYS2UEnY377cyBdmGySPU4B_5aeUQ7k,1174 +tensorflow/include/Eigen/QR,sha256=rGHXJX8p7ezjQFzXrUbBNYp4w3K69zbgztQ5FYAifXQ,1279 +tensorflow/include/Eigen/QtAlignedMalloc,sha256=xGYpHG59Iw6Ldrclza0e2Cwkm_AfXsO8tvP2UB7Q_5c,900 +tensorflow/include/Eigen/SPQRSupport,sha256=0pen5fTc87sTzzerugoAGPUNMbwbHTn80F1EuWJn22I,1251 +tensorflow/include/Eigen/SVD,sha256=iD_hFgG1mswSsYTx1D6XH5T9X8daWUkLH8LhMovteTA,1674 +tensorflow/include/Eigen/Sparse,sha256=vjUbbuZSp6IOOVPQ6uIW1NAcLCa6e2pGS_kI2zRJkHs,888 +tensorflow/include/Eigen/SparseCholesky,sha256=N4ib7KY18onfEzRZLmg2ZG78H3_2Fgcpz-RvrcvlvoU,1294 +tensorflow/include/Eigen/SparseCore,sha256=tlemE5YM4TxptVgsHwTeuGjI34Fc5KTKedzr70ymTAg,2270 +tensorflow/include/Eigen/SparseLU,sha256=DVHYc2hGes0ZfjcDnYPzaYeuuOaQZHONiISTuZOBJ80,1824 +tensorflow/include/Eigen/SparseQR,sha256=t-nDDdPfjnr-re2beY-W1T0Irq84gGDVT3HfNjy8THo,1253 +tensorflow/include/Eigen/StdDeque,sha256=ZjMm6PN7tq38fyv4aGSJQWKTFh8g7A2MAfZoPbe9-eI,855 +tensorflow/include/Eigen/StdList,sha256=iJiURtuqBPyCCtgJtGKAOzAAN6HPMsuSfEZmX3056z0,784 +tensorflow/include/Eigen/StdVector,sha256=2X7Uwc_tN3uiyy8zWbYc27Da8bUo96nite9CWXVffKI,861 +tensorflow/include/Eigen/SuperLUSupport,sha256=KA7OobxOpmIWSImlqfHWM7VFZAm6SKoWb_2vbAk7ENA,2301 +tensorflow/include/Eigen/ThreadPool,sha256=iDKUFtVzDsG1mhUsQfCOG2vw5HvTEIYw_XUIpvo8O7c,2137 +tensorflow/include/Eigen/UmfPackSupport,sha256=efbpXfXF-2XPCnH_e8xBpJ4C_Odytoog17aqfle60Ls,1439 +tensorflow/include/Eigen/src/AccelerateSupport/AccelerateSupport.h,sha256=PasHzAVswMNCJJe4FP_OHTCE2Ye11f0sWhmxbsziQXY,15135 +tensorflow/include/Eigen/src/AccelerateSupport/InternalHeaderCheck.h,sha256=m8BsKoCFQ-HMxv2YKhMcLn8_p9LYQ3qCi06nuY1F3lo,160 +tensorflow/include/Eigen/src/Cholesky/InternalHeaderCheck.h,sha256=can-V-H517aW6XC8NNE8ZXhR09eShzKsEUxr9aHZV8Q,142 +tensorflow/include/Eigen/src/Cholesky/LDLT.h,sha256=Qxsi1utnn5hLGRXiAL0Pce2SN4QtdEiJ-JJis1QDmVE,24900 +tensorflow/include/Eigen/src/Cholesky/LLT.h,sha256=QXvDL5PbNL04TPYrj0fn_kfhtK3W7uYw8WCfOR_Ap8M,18713 +tensorflow/include/Eigen/src/Cholesky/LLT_LAPACKE.h,sha256=5aUCsnWeopIgI5OuBzNo79or7TEd4XDpJpA7asoOnP4,5126 +tensorflow/include/Eigen/src/CholmodSupport/CholmodSupport.h,sha256=pU2LgckQS7MKbQbyHpaev1BqHKzx8jKNH_l8JtBr7CA,25476 +tensorflow/include/Eigen/src/CholmodSupport/InternalHeaderCheck.h,sha256=AZpXyx5BI1BVIfSVr1PQ69LZMV-9RWy6zSbU7wFS_ss,154 +tensorflow/include/Eigen/src/Core/ArithmeticSequence.h,sha256=cXcSHgqAua942_uPE6ZaA2TaPJWxAElrielOOotvnTY,10790 +tensorflow/include/Eigen/src/Core/Array.h,sha256=b0e701x6BTEFQjzwoXssoU24IUFNbs3qMByJ_QvvuiM,16400 +tensorflow/include/Eigen/src/Core/ArrayBase.h,sha256=ocO5tm_e6yBU6GTlXRzAey-M8SInxTAZ3fUZ2qgozyo,8252 +tensorflow/include/Eigen/src/Core/ArrayWrapper.h,sha256=-QEkgeDcBYH1rzerqx6jBdx5jnFwNOiaBPH480zyENU,6878 +tensorflow/include/Eigen/src/Core/Assign.h,sha256=yufTeE3SuRmcrglmVRkkulyYnc41L2A3OW5ATqU7U6M,2774 +tensorflow/include/Eigen/src/Core/AssignEvaluator.h,sha256=yj5cctLHf8diYWD2VNi-g-oMM0AcI6g4WcIZPgXs7aA,42924 +tensorflow/include/Eigen/src/Core/Assign_MKL.h,sha256=AdTscJ6Fa_Fx9g3vxycPC6ETWULnWS0TPp3b1FTjc_8,12508 +tensorflow/include/Eigen/src/Core/BandMatrix.h,sha256=UgisqqtnTbhRD8yvzLTRHBR5kr_a2Mxd55qzPYudjnU,14072 +tensorflow/include/Eigen/src/Core/Block.h,sha256=kE7JBbe9VtgL3B_zzL9kjICCD8qF30dJRz_MTuERra4,19387 +tensorflow/include/Eigen/src/Core/CommaInitializer.h,sha256=qDwrJ2xF7Q1q7b2DzaOWS1DAviFZ7wHiCmVcSLYvdZo,6092 +tensorflow/include/Eigen/src/Core/ConditionEstimator.h,sha256=2773aJu8N9EecM8o29wLI7vfXPt-y6MLo90e0UthNMI,7070 +tensorflow/include/Eigen/src/Core/CoreEvaluators.h,sha256=UooNDwfpGFFLVfWtuS0W6z4lk3qCAVFZkhJF9APLqUs,75628 +tensorflow/include/Eigen/src/Core/CoreIterators.h,sha256=gPgoAjff4zrlj9K1AMg5ru_7HIYBiNv4VjMoadK-G48,4781 +tensorflow/include/Eigen/src/Core/CwiseBinaryOp.h,sha256=seQ9MIXKLxaHspdG_bUX1LcbJaJ8pLJnb8Cy-cKBwHg,7756 +tensorflow/include/Eigen/src/Core/CwiseNullaryOp.h,sha256=-MKv5n4rj-CiXrKIY7-yi4s3ZfVXY0T4H3lQwNPXL2Y,37759 +tensorflow/include/Eigen/src/Core/CwiseTernaryOp.h,sha256=rVWJwaPWb9GmYcLtoBlZDQ42ayoC24kTLwD6TzD912c,8034 +tensorflow/include/Eigen/src/Core/CwiseUnaryOp.h,sha256=s3nV0TCP3sRmEvg137-D_8lW1XFEfsrAj3ORVeR92ys,3926 +tensorflow/include/Eigen/src/Core/CwiseUnaryView.h,sha256=Q_qUd6FUDS81DDmOE3pZMK3FdMhpQ5QgQbUQVHYuXZA,6274 +tensorflow/include/Eigen/src/Core/DenseBase.h,sha256=9-aJtUk8jcAx3GsSf4YMFve3yxlQyjiwY3Fl3tpYcC4,31897 +tensorflow/include/Eigen/src/Core/DenseCoeffsBase.h,sha256=hDh6M2H37I_rgACvRsY-7Z6T0CTle1GaDNDizU1L_z0,24436 +tensorflow/include/Eigen/src/Core/DenseStorage.h,sha256=KPcUPUZ_bzXYL16TLMdb7v52jHHHDESRsRgEz_x8RS8,28934 +tensorflow/include/Eigen/src/Core/Diagonal.h,sha256=eQ4I3uWdGc9aeaLLWp1MW7NxCmF6glM-_N8M6LNmojc,9601 +tensorflow/include/Eigen/src/Core/DiagonalMatrix.h,sha256=ikL2a-gJk8zC2I_ewCzNA6Q41gBaJnbmu6eFl7pUhxE,18129 +tensorflow/include/Eigen/src/Core/DiagonalProduct.h,sha256=ulSTg91sf4ApufsbQK6Lh0I7i84nCFXqBuOY-7-UQj4,1024 +tensorflow/include/Eigen/src/Core/Dot.h,sha256=fnOScZI7nstIVWcjo5pVFW-lam6pv693h6HHGbts--4,11427 +tensorflow/include/Eigen/src/Core/EigenBase.h,sha256=fwAzd2ERhKKtKkv2fIc5YME2v9coe0Q7xZAVLTuKo4A,5877 +tensorflow/include/Eigen/src/Core/ForceAlignedAccess.h,sha256=iSPUYReDECsJ51QrXfR8qJc_b9Ow-v15LjjmNxE7IKE,4886 +tensorflow/include/Eigen/src/Core/Fuzzy.h,sha256=BBuirxqw49G6XLzTNEkyKt4bt-opgL_YRq2LS7aRT8E,5813 +tensorflow/include/Eigen/src/Core/GeneralProduct.h,sha256=M763u-x_uU0Db4mfCkaXROoZbhue_USXhbNs0vk0IEQ,21622 +tensorflow/include/Eigen/src/Core/GenericPacketMath.h,sha256=EBsvL_mpDd2z-ij7i_4l9tj7rUQ3-pjaR412QpgYoS0,54436 +tensorflow/include/Eigen/src/Core/GlobalFunctions.h,sha256=ZFSwNjJCcFEuUvyDt_btV8gcn6USi_qawShb6ylDZ8k,12188 +tensorflow/include/Eigen/src/Core/IO.h,sha256=otmam46ZHp_fIokhDMi4v_8wWqUhYKX7sP6lALo7tnc,8364 +tensorflow/include/Eigen/src/Core/IndexedView.h,sha256=lS59ZDxquRnVitswkg_Z7WnuK-8kGgDDGvJWr574nuw,10668 +tensorflow/include/Eigen/src/Core/InternalHeaderCheck.h,sha256=R-f0eq5P5r53YNY1vUMKtfYHSE_FPv12vvcud20eQsk,134 +tensorflow/include/Eigen/src/Core/Inverse.h,sha256=6JVyY7TGl3d9aRHD8Qmh6CuwLzTqoE89QCo6Uhxi_yQ,3510 +tensorflow/include/Eigen/src/Core/Map.h,sha256=Q-CvrXylhTWTH-MlCUdszgf30Y2V4rJl9KahGJprABs,7127 +tensorflow/include/Eigen/src/Core/MapBase.h,sha256=8gBQNsiqhKMHMBEduTS8ocxSt10vvrKolpkPVHe4P24,11206 +tensorflow/include/Eigen/src/Core/MathFunctions.h,sha256=j7YyaY8yk5-lMJXXMRrhEo7H2KBof2DiSwytLKnLEmQ,59455 +tensorflow/include/Eigen/src/Core/MathFunctionsImpl.h,sha256=9Yzvvxbh0TS-ulUPIUGmEP8eQPlrBnb3q39tvimOo2c,13219 +tensorflow/include/Eigen/src/Core/Matrix.h,sha256=IeRbpd7-_jDL6fr54TYME45ZvYplzh35-SLVnLUT-QE,24419 +tensorflow/include/Eigen/src/Core/MatrixBase.h,sha256=yh4j1dmL3yos1sJ_24WvvV_tNCgb590FYkXnWDgB8WU,24111 +tensorflow/include/Eigen/src/Core/NestByValue.h,sha256=UOJGh_WHOJRSUsNnSvZZppmjJQTGuvoAmOEeR8xTOZs,3095 +tensorflow/include/Eigen/src/Core/NoAlias.h,sha256=-yGw4pBdPrCBF9VwlWUR6f_0f4AHGgWSnnPRLlmc3ZU,3656 +tensorflow/include/Eigen/src/Core/NumTraits.h,sha256=RWbIQeC0NtLIO_YJLBYQmpCxgIzgAtOW9nKIlSqlEB8,15069 +tensorflow/include/Eigen/src/Core/PartialReduxEvaluator.h,sha256=Ru8zvd-gQ8dmfm48BqyhgrGrtRt9haN_L1Wonr3GARg,9283 +tensorflow/include/Eigen/src/Core/PermutationMatrix.h,sha256=JmB5IhDeSK8xPgaU6Ual209jR9IlQEB5pQmV4x701zc,20771 +tensorflow/include/Eigen/src/Core/PlainObjectBase.h,sha256=BHJEYsXZVP4jGMxc8HVHaDlqaA4Jq4-8mlWsw-CEkqQ,49410 +tensorflow/include/Eigen/src/Core/Product.h,sha256=KTh5UYcrwWIanJtiYgtcYt1vkcw6qj8XUf40XPWXngs,7314 +tensorflow/include/Eigen/src/Core/ProductEvaluators.h,sha256=b-OKHg4Ti_xXTPnyc-rUONsMXfKGi5GP4zHn43aV9Nc,55121 +tensorflow/include/Eigen/src/Core/Random.h,sha256=9jIZYE4mUbBSxdJYl0V-S-hCvcY2Ui9pYe5xUbN0B54,7748 +tensorflow/include/Eigen/src/Core/Redux.h,sha256=Gt3OcIOZiOi4y-8AV3jJ9c0jvWsQ8KC_paQKcYvWqsA,22864 +tensorflow/include/Eigen/src/Core/Ref.h,sha256=VvQhgsBp_6o3-gLtx1-mhdShgzNtvl_GGvLIRrZ8JqA,19104 +tensorflow/include/Eigen/src/Core/Replicate.h,sha256=MDZ4toaJTBp6tfg9DZhqeFqDfoJGbPx3H5WxIhZK_20,5635 +tensorflow/include/Eigen/src/Core/Reshaped.h,sha256=blDP6GzQY4MqMS_wB0yErY129F6mlrChN6NZosuVrSM,16980 +tensorflow/include/Eigen/src/Core/ReturnByValue.h,sha256=ML4jXV86R_hH2XzjQNMOFG11k4psaOzqSROvp9Bni3c,4317 +tensorflow/include/Eigen/src/Core/Reverse.h,sha256=1xzSkzD_B7RMH5AnGIsUYyXfn70sH316ymEi9qAuWm0,7552 +tensorflow/include/Eigen/src/Core/Select.h,sha256=96370Bozm7ZOpRy5V3yAw9Oquz0seEZFlj_q7jbYouM,7716 +tensorflow/include/Eigen/src/Core/SelfAdjointView.h,sha256=aIg45g1fe0CP_J_ikCCOBHfbvf5N2rAwMCYJMlSqTm8,14908 +tensorflow/include/Eigen/src/Core/SelfCwiseBinaryOp.h,sha256=zG0SGRRogOVoLCqdQIz9XH_aMnJGcdJ5wGwtfWcXGp4,1733 +tensorflow/include/Eigen/src/Core/SkewSymmetricMatrix3.h,sha256=nbfOFCw4rncVYG3rqya1ueuFcLhOKu4H889PUeJ5uX4,16006 +tensorflow/include/Eigen/src/Core/Solve.h,sha256=JN3FJlfeLysYcTMBoun9NFWpOYgDcNMHj_NCIke7Ces,6902 +tensorflow/include/Eigen/src/Core/SolveTriangular.h,sha256=Btd-ML_PL0XX-Xav3X7GW8uRO7Q_U1_kjVZdRClTWKs,9430 +tensorflow/include/Eigen/src/Core/SolverBase.h,sha256=BIkk7OJo_f2AQJmUYX2j-IOnV00CM3ZuKNdvtA47d9I,5967 +tensorflow/include/Eigen/src/Core/StableNorm.h,sha256=S7ZLZFaJ6jBQGTp_-3lVt1LZpG9mNdlQd_GPXMaSgPY,8689 +tensorflow/include/Eigen/src/Core/StlIterators.h,sha256=vbwB4QjsyOHBOZ7kAUWDCoA7T-c2hY9dessnRAJ8WI8,21245 +tensorflow/include/Eigen/src/Core/Stride.h,sha256=n5qy-ZBrLn-kT_B7opDf7nSga2RaX7o-E-2c0ggeDHc,4450 +tensorflow/include/Eigen/src/Core/Swap.h,sha256=7KSQTshBLUR3jYTu0VENCpeb2gHvSFz-6oFlmKH2t6o,2801 +tensorflow/include/Eigen/src/Core/Transpose.h,sha256=NRnpFbQQ0gU5kA44nQvT8zRLHgyiSLJL1h9OjelP60w,17669 +tensorflow/include/Eigen/src/Core/Transpositions.h,sha256=8v7a6nxbehtspNIeyS-dv-nudkW9e4O9m52WttpXOVk,13603 +tensorflow/include/Eigen/src/Core/TriangularMatrix.h,sha256=HIq5BhDtjz3fw13BiN6PV9I-TXqNYyYcCROY0n4rOF4,38143 +tensorflow/include/Eigen/src/Core/VectorBlock.h,sha256=w-OSHHjIBHseztSjPPAtQzIZkIFjjoA7ooiNfkezJWw,3485 +tensorflow/include/Eigen/src/Core/VectorwiseOp.h,sha256=rqqFvZ64n2jsXiTxeO9T3DrETUgmZR9Chxe7fHBN838,35183 +tensorflow/include/Eigen/src/Core/Visitor.h,sha256=apYAta7llbH9zdZcaYG1eCLan6pH40HRlgP9EbYyCPs,35589 +tensorflow/include/Eigen/src/Core/arch/AVX/Complex.h,sha256=YPsKdFWkoFtoKO4kSH_DaTzTz25LTZpweAvqDxPYKc4,14929 +tensorflow/include/Eigen/src/Core/arch/AVX/MathFunctions.h,sha256=6EtCJw36C5dT4VZt7dBLT4mykkzzGggaC7_BsUtLlz4,4141 +tensorflow/include/Eigen/src/Core/arch/AVX/PacketMath.h,sha256=gKFYgxsHBdjtR2AeDxvgPyLHBGr6rYSTgAai7x3bi4g,100192 +tensorflow/include/Eigen/src/Core/arch/AVX/TypeCasting.h,sha256=zx5qZ5jXFVRHJfVrGbzKRaPDTbMgcV_XDT2jid1_Lp8,8269 +tensorflow/include/Eigen/src/Core/arch/AVX512/Complex.h,sha256=vveTUWOJJsSli3AVbda4mq3ZtkbImYgPPYd6f5Dvgd8,15751 +tensorflow/include/Eigen/src/Core/arch/AVX512/GemmKernel.h,sha256=XVJ9XUMl9guFyrfNrg3xss_FPIfmsjAg855nvhdDkKI,48316 +tensorflow/include/Eigen/src/Core/arch/AVX512/MathFunctions.h,sha256=dl7mh8KgW_Zg8tlIkY7KbPLnjaMZz_b4jKDL7u6aZyk,4645 +tensorflow/include/Eigen/src/Core/arch/AVX512/PacketMath.h,sha256=qybMs4B0NJBfMHQfXsUKNSiQL2xOtgoYwCx_a_7vVBM,112031 +tensorflow/include/Eigen/src/Core/arch/AVX512/PacketMathFP16.h,sha256=feJLeyWdUokyxrspPz4Ups7rM3GSgVNRbfOr-mYSSY0,26473 +tensorflow/include/Eigen/src/Core/arch/AVX512/TrsmKernel.h,sha256=Bs60UHgV75_SLoOiCol84e44LaJGY8S93OJLflOstcE,55565 +tensorflow/include/Eigen/src/Core/arch/AVX512/TrsmUnrolls.inc,sha256=ySQ28JDvuQFP3zWRpR2iLVvrs-ZTQtLhKCt4AthFah4,56496 +tensorflow/include/Eigen/src/Core/arch/AVX512/TypeCasting.h,sha256=NSzyH5HA8yxw5oAKK7BHrCdNbcCC9qMonmPQhbEPP-w,8620 +tensorflow/include/Eigen/src/Core/arch/AltiVec/Complex.h,sha256=GY4XE0jt2c4HRaOupr9ilixkXMv90Yfu0Wf8nOm72HA,20628 +tensorflow/include/Eigen/src/Core/arch/AltiVec/MathFunctions.h,sha256=QldfGKsAVqYnddH7FioBHG0xwP5rCGoQ3Jl6TE0FOUU,2252 +tensorflow/include/Eigen/src/Core/arch/AltiVec/MatrixProduct.h,sha256=i9h6JaIoX05rUx_6wpy0wqoHbzA4xCC-SqEBITo4tIw,148589 +tensorflow/include/Eigen/src/Core/arch/AltiVec/MatrixProductCommon.h,sha256=RuUcWZDRWnig_VCUq-XN1XIlmhnTbJljDzOV8_JR0yA,7888 +tensorflow/include/Eigen/src/Core/arch/AltiVec/MatrixProductMMA.h,sha256=MVOAFFG5fVHAYGSWUOb8gwz2ijy4Ubt8kiejBBKQyMY,28090 +tensorflow/include/Eigen/src/Core/arch/AltiVec/MatrixProductMMAbfloat16.h,sha256=HaWBEuk711Y-TD9XdjLKdv4AO5HgYrU3YFGzji9Kkqc,28242 +tensorflow/include/Eigen/src/Core/arch/AltiVec/MatrixVectorProduct.h,sha256=srpaZxXfnaggSEI83N-aX1DFAtBhoTOFDGbvzkc6grE,111974 +tensorflow/include/Eigen/src/Core/arch/AltiVec/PacketMath.h,sha256=UH82ZILpEk6ADYWUbT196c0GdWT2VLmKeHPL2VWNzEY,121674 +tensorflow/include/Eigen/src/Core/arch/AltiVec/TypeCasting.h,sha256=ICAQWXS7kTVeKaDMm1sf1-MQtN32WeRqO-f9VZ25eAc,5236 +tensorflow/include/Eigen/src/Core/arch/Default/BFloat16.h,sha256=E33GdLteuPA32p_UbgIHXpWm0EgDR7vcD1gSIw4lYUE,34597 +tensorflow/include/Eigen/src/Core/arch/Default/ConjHelper.h,sha256=uelkIQFnG5qOBxPGm7cNa17Kz8NR9zKuBvBrYXdv5i4,5291 +tensorflow/include/Eigen/src/Core/arch/Default/GenericPacketMathFunctions.h,sha256=CnYxnvX2FQ_1jYHwArj5_f2X06S3WItVSwd6TztuaVQ,93550 +tensorflow/include/Eigen/src/Core/arch/Default/GenericPacketMathFunctionsFwd.h,sha256=YmYNN9yux_H5Te-b25PrJtxR-EJ75YIMLsyPIhYRT_8,7777 +tensorflow/include/Eigen/src/Core/arch/Default/Half.h,sha256=szFYor0Pz5FEQaky7YRI319KQ3BYnG-h18w8EnWdI-w,40711 +tensorflow/include/Eigen/src/Core/arch/Default/Settings.h,sha256=Qbh6le3EAOdUX3JzxZdCq8ld765sp82F-WLVGnqPt5A,1746 +tensorflow/include/Eigen/src/Core/arch/GPU/Complex.h,sha256=EmPd2JM1BW9e-cETa5LlTNN5uW6xeS5d3_t7qT6k3No,17981 +tensorflow/include/Eigen/src/Core/arch/GPU/MathFunctions.h,sha256=yZOLNLrdPkQ_iAIo_Xg0tKfLF1cgVqmqXnuk32-pU1c,2735 +tensorflow/include/Eigen/src/Core/arch/GPU/PacketMath.h,sha256=Ym1knDDIDXJ19mgTv94pmTOSy9H0V2N8md37eZh4nno,58218 +tensorflow/include/Eigen/src/Core/arch/GPU/Tuple.h,sha256=ISGURebu8ssFrwwCmI6AwRNjnp71rGWYjMoZvbCDGTg,9694 +tensorflow/include/Eigen/src/Core/arch/GPU/TypeCasting.h,sha256=BJWvPHFFnFCAfMbZNKbRuHCkEY7w2kpP7txzbfFHJZI,2297 +tensorflow/include/Eigen/src/Core/arch/HIP/hcc/math_constants.h,sha256=TYakFU7yBjjXKrL1hexh9sCIGQjZhqK0_7RO-pf5ckY,691 +tensorflow/include/Eigen/src/Core/arch/HVX/GeneralBlockPanelKernel.h,sha256=iLCU4U9ka714aBnfkGdIsPJlHRdj4FNgr-n2j9UFZSs,1596 +tensorflow/include/Eigen/src/Core/arch/HVX/PacketMath.h,sha256=4mU7MQ6nar0OT3R3KeQa-TMWCbjDJhK_xrVUumqh9P0,23921 +tensorflow/include/Eigen/src/Core/arch/MSA/Complex.h,sha256=kbtnfxzQf8f0nad-UtyD18wIWGeBITtfx7HhNPT43lg,17402 +tensorflow/include/Eigen/src/Core/arch/MSA/MathFunctions.h,sha256=z5Yesl36k_eGMryg96_UmWqCraV8JmqDdJ1LL6DmSdI,16053 +tensorflow/include/Eigen/src/Core/arch/MSA/PacketMath.h,sha256=IUf81EnQxQJBfVQAcMu_fpmB2uWZWa7YreFpIWltjbU,33492 +tensorflow/include/Eigen/src/Core/arch/NEON/Complex.h,sha256=7AI7lIPTAB60TVOGxQYKkxXeRO1JOVZJMAmzehcEDW8,21988 +tensorflow/include/Eigen/src/Core/arch/NEON/GeneralBlockPanelKernel.h,sha256=3kgifrI0UdmT-8rzwzf8dV1nEauXE_g-EMR3uYtwUCs,9906 +tensorflow/include/Eigen/src/Core/arch/NEON/MathFunctions.h,sha256=pc38LvCW9nL3CyIlH1Ctv6qwP0UgYXP7NKTYgjoJsgU,2106 +tensorflow/include/Eigen/src/Core/arch/NEON/PacketMath.h,sha256=82tf_yoUIQc9k3rVIeYo86G2gcqfTZlwIY3s1gQr6OE,194208 +tensorflow/include/Eigen/src/Core/arch/NEON/TypeCasting.h,sha256=RujVrkwYtnHgTCxedTqIdrobkvMmZZn8F1weqU78M0Y,60825 +tensorflow/include/Eigen/src/Core/arch/NEON/UnaryFunctors.h,sha256=BaDUiPwlK-10223tHYtFZ1r2Y2q1HXu6Ivl698hD0yc,1886 +tensorflow/include/Eigen/src/Core/arch/SSE/Complex.h,sha256=KlNW_zwmRmRBWXJHUuhDhKlbpToORfitLtodfwnxQ64,13504 +tensorflow/include/Eigen/src/Core/arch/SSE/MathFunctions.h,sha256=Nykh5TYr2RtQkIR0cz3Jum-ubG5ATRP2s3ksoj9Qc2A,2845 +tensorflow/include/Eigen/src/Core/arch/SSE/PacketMath.h,sha256=7KuLWHOQV40NCkimTn2GBmlE90ktRXrEQZBrtvjJcTw,83165 +tensorflow/include/Eigen/src/Core/arch/SSE/TypeCasting.h,sha256=1UJ4KllC7XBbMTPX5bjYz8NO-IdKfhEUsdL2Kd3y-g8,6380 +tensorflow/include/Eigen/src/Core/arch/SVE/MathFunctions.h,sha256=hMx8TMcvaa-cXvYiPLOoMxG18anSO3wH8-nyjC2drks,1169 +tensorflow/include/Eigen/src/Core/arch/SVE/PacketMath.h,sha256=w_AVx4CyRFDruxxfb7hmj7nXIK2IJj4zSKYEYVtyIOg,21138 +tensorflow/include/Eigen/src/Core/arch/SVE/TypeCasting.h,sha256=DSidGWo_id-eRxWTRHBgLENmefbJP6jaXWE5xmfFOck,1391 +tensorflow/include/Eigen/src/Core/arch/SYCL/InteropHeaders.h,sha256=jpepN__YAps7rwvQisJEfAUZ2dlWQK4RyfRHGEYobOc,7445 +tensorflow/include/Eigen/src/Core/arch/SYCL/MathFunctions.h,sha256=4JSJie5fcOv3naIJ12_wPB_xEVZEaNDlfdFl346JyNM,12579 +tensorflow/include/Eigen/src/Core/arch/SYCL/PacketMath.h,sha256=SRTsYLWaEDP-Ui3EkfUt1Xd9-ciKNZiYZX2Li_dskzM,13577 +tensorflow/include/Eigen/src/Core/arch/SYCL/TypeCasting.h,sha256=A_1wmtC1DxR4uXcw0XI8WFJ7FczCykdRijqdU0SANRM,2669 +tensorflow/include/Eigen/src/Core/arch/ZVector/Complex.h,sha256=EVMehDx1nuObb6vqsfZYoRfNGjyZzsFBCqFc9Wm5Wu4,16327 +tensorflow/include/Eigen/src/Core/arch/ZVector/MathFunctions.h,sha256=yGvN-DDLsGL-xiJ6e7FJYp9X7inb_kKXgpGebS1WZI0,7927 +tensorflow/include/Eigen/src/Core/arch/ZVector/PacketMath.h,sha256=gU-b29Aegf_cyxh6-5qULl6omKxK2VNOER5Q2sUxajo,36847 +tensorflow/include/Eigen/src/Core/functors/AssignmentFunctors.h,sha256=f5GkxAd8q6uv1m7NnOr8Qyx8GGXYeWaAlSI8wocOVpw,6454 +tensorflow/include/Eigen/src/Core/functors/BinaryFunctors.h,sha256=5puftq5fo9PAfkidkx2psFILbZj7WpizrO7kOV8vJhU,31940 +tensorflow/include/Eigen/src/Core/functors/NullaryFunctors.h,sha256=YTJFYL7yM4tU_A_XuI6v61NOslri9RtFQBKA2P6o-A8,9534 +tensorflow/include/Eigen/src/Core/functors/StlFunctors.h,sha256=cJcQxzIXAPv-KzR0qJ6riKZWHLzp9Lb9L1kLYENG8ms,4009 +tensorflow/include/Eigen/src/Core/functors/TernaryFunctors.h,sha256=NevLvWniBmlcxJGJZXG07NlmLzSu2WEnt2jalkaUBXw,1736 +tensorflow/include/Eigen/src/Core/functors/UnaryFunctors.h,sha256=4UV7MtMorcEx4W2RGaLqk5Xt9QKFOTdugWPRC98ElE0,46996 +tensorflow/include/Eigen/src/Core/products/GeneralBlockPanelKernel.h,sha256=JN7dZQY1Z1QDiSHL_Kc642jkS4zsMijkAxeTmanXMvM,140899 +tensorflow/include/Eigen/src/Core/products/GeneralMatrixMatrix.h,sha256=P3uBe4Ix1kUuBUDVlqALLTYtcZu_z88YIGPYOfH6HtY,19826 +tensorflow/include/Eigen/src/Core/products/GeneralMatrixMatrixTriangular.h,sha256=HrjGZ6Cmp2zzQZIlhKYfEvNdRtV-eatfNg7DKqgubEM,15819 +tensorflow/include/Eigen/src/Core/products/GeneralMatrixMatrixTriangular_BLAS.h,sha256=GJnaCYmbHSNkCF_2CyItQoHeSHCoaahyruLl139-UdY,6973 +tensorflow/include/Eigen/src/Core/products/GeneralMatrixMatrix_BLAS.h,sha256=MxhVs7RZOZSeabG5R-fJP1wDo5OmCQuoTX2WTpaao3o,5143 +tensorflow/include/Eigen/src/Core/products/GeneralMatrixVector.h,sha256=l9CTJWD4HyWz5k9nMvRjOSgwAqDnTebF8e2RflbRhX0,22136 +tensorflow/include/Eigen/src/Core/products/GeneralMatrixVector_BLAS.h,sha256=OLrpYiosUkE_yXBlo961ucuBz2695vos-kFYoPThlBA,6405 +tensorflow/include/Eigen/src/Core/products/Parallelizer.h,sha256=fHBWLJIggNRGiQ0VEcsF9FE_EAsxd3456RZmsagbAX0,5252 +tensorflow/include/Eigen/src/Core/products/SelfadjointMatrixMatrix.h,sha256=Iut4nZf5DxPDbJ2kB_OgL-DZwL_FV2TRCXPkk7Oqg8Y,21343 +tensorflow/include/Eigen/src/Core/products/SelfadjointMatrixMatrix_BLAS.h,sha256=Q4WBTm0j6Cu49VdgTpI87RpTKhkFQeVcq5ZGxxS4jVg,11607 +tensorflow/include/Eigen/src/Core/products/SelfadjointMatrixVector.h,sha256=5PkZWei6aeFRupWG-YxRXsSusGV8qP1rIlqPy6My9kc,9893 +tensorflow/include/Eigen/src/Core/products/SelfadjointMatrixVector_BLAS.h,sha256=SP-22RdvsR4h6KOmz5OlsPr_7oRhZ16R_0YSwf477qE,5246 +tensorflow/include/Eigen/src/Core/products/SelfadjointProduct.h,sha256=dRjZMj7kTtU6rRgoBm0E9U_E7pbzCYJ0GCnohnQUxsg,6131 +tensorflow/include/Eigen/src/Core/products/SelfadjointRank2Update.h,sha256=fy6qg-8YXt09KLFtwzn6_CZjj-slOaI_xTmtJTHGGvQ,4077 +tensorflow/include/Eigen/src/Core/products/TriangularMatrixMatrix.h,sha256=9BoIPFBS6U5YriVT-UJ5wOUYRWUc25B9oRoVGzWoHUo,21173 +tensorflow/include/Eigen/src/Core/products/TriangularMatrixMatrix_BLAS.h,sha256=1O3GvxpWMp5ngkLnHAWiIOx5mzLOSAh6ajmaclB2io4,13904 +tensorflow/include/Eigen/src/Core/products/TriangularMatrixVector.h,sha256=Z7ufuCLrzvdwTTuVTadRyKRj3xvurPsCHqlW5GufhwQ,14886 +tensorflow/include/Eigen/src/Core/products/TriangularMatrixVector_BLAS.h,sha256=Hop8vISKN0gw48jcc0wucWsQ4Gy02cyL5mFz2DEW8K4,10608 +tensorflow/include/Eigen/src/Core/products/TriangularSolverMatrix.h,sha256=VNSEPi4fKlpwFPxVAfnCmvyHmoaSbMTk1vbqULl7_EU,19276 +tensorflow/include/Eigen/src/Core/products/TriangularSolverMatrix_BLAS.h,sha256=l40rTvK1IsQw_JvB-Ose_kB9BzzBzFnlUoUJKRTEJbo,6744 +tensorflow/include/Eigen/src/Core/products/TriangularSolverVector.h,sha256=vITfbwZZwmMBeoNB6sxzZrfNpxlWEtvwQo4WEyOwRDo,5779 +tensorflow/include/Eigen/src/Core/util/Assert.h,sha256=jNXcKNe38pRMIjLXUvWBxJy3FSzDdNQwJeXlEbQjn7w,6211 +tensorflow/include/Eigen/src/Core/util/BlasUtil.h,sha256=Ytep496UgMN88TIRvdLXKauI9CQ4R3g1ahbTuagYRgw,26286 +tensorflow/include/Eigen/src/Core/util/ConfigureVectorization.h,sha256=wB-8vZjHFY5ZUW32gENpgm7zrakoM6Flo0hPUIJ_UK0,19583 +tensorflow/include/Eigen/src/Core/util/Constants.h,sha256=VS0moMdEkVUUA9Mg1IePRGVEoyw2CuusnnM7jLMJF3c,22279 +tensorflow/include/Eigen/src/Core/util/DisableStupidWarnings.h,sha256=0tSnX4Q4auJIKMcX-fzw5kr2KroM8YvwIuOvcxNKfYk,6264 +tensorflow/include/Eigen/src/Core/util/EmulateArray.h,sha256=0YUn1cZ3yvoMZetzJpZO_WstmBFcGepP7972cvjOI1w,8899 +tensorflow/include/Eigen/src/Core/util/ForwardDeclarations.h,sha256=T7JCkFjE8xqB85xp2hr8vl3fHaKUViqJV-moq7cFgvY,15929 +tensorflow/include/Eigen/src/Core/util/IndexedViewHelper.h,sha256=xnl9Un5FC1lhzenT3xkG46LewjofqoRVJFnRKvbYxPs,6273 +tensorflow/include/Eigen/src/Core/util/IntegralConstant.h,sha256=AD-6VOK2ijxvz5GkEf85v66-4JgKMv_vEwhX4ld41iA,9567 +tensorflow/include/Eigen/src/Core/util/MKL_support.h,sha256=6CG9H8BnI2VtQf2nP2uzmqpSF6UhGP9bSYIxhh6xxJw,4305 +tensorflow/include/Eigen/src/Core/util/Macros.h,sha256=HCNgZiVMYsOXAkpRQwwnuyXUPSOKvAkRhhjSPaOwExo,48587 +tensorflow/include/Eigen/src/Core/util/MaxSizeVector.h,sha256=EuF1mZRH4vkqjvlccCWQjqBH9Z1YAAS_IInj0XcFA8Y,4178 +tensorflow/include/Eigen/src/Core/util/Memory.h,sha256=ETU-9T9A1USRSWGHVDf3vCIO1tRJ_VXtkPksU8kR_hs,50310 +tensorflow/include/Eigen/src/Core/util/Meta.h,sha256=qrVcVMWgV8BBH3qQ-7TfN5gInX4SIZa8xnCOkByeRgY,21000 +tensorflow/include/Eigen/src/Core/util/MoreMeta.h,sha256=sDh1Fe415NHlkeONH-lfiyE3TIC4Yb6pIKXy-xO7K6I,22551 +tensorflow/include/Eigen/src/Core/util/ReenableStupidWarnings.h,sha256=z9ZjZfiqVdB4E9K2YfXtuwFtlNYMM9pFhopRr7KaDqM,1387 +tensorflow/include/Eigen/src/Core/util/ReshapedHelper.h,sha256=cbXYGTy7hX2-f9d6AT5cvzhomEP-Ra9Q4_tLumqE-H0,1463 +tensorflow/include/Eigen/src/Core/util/Serializer.h,sha256=YmmNlLI9a8DVNnT-C56RoX1BA0V9Wp7x5qVYY98nfgY,7810 +tensorflow/include/Eigen/src/Core/util/StaticAssert.h,sha256=YccxgMaJpcyG_Tc68DdTKkEsjZvMxK7GWIbUxMxODTM,5496 +tensorflow/include/Eigen/src/Core/util/SymbolicIndex.h,sha256=BZHbmNznhRgCokB4Uov4_-sIOFHY5kQZ654eKCaZ9H4,9854 +tensorflow/include/Eigen/src/Core/util/XprHelper.h,sha256=KO9UWGlyZT7y-7fAH6oDgJReQRMfcwiPTRT-ZDZRvNw,38260 +tensorflow/include/Eigen/src/Eigenvalues/ComplexEigenSolver.h,sha256=FGVS70svIn2RJ7hVnR20kgh0Pkb2qmIrVFDxVCmVR2o,12494 +tensorflow/include/Eigen/src/Eigenvalues/ComplexSchur.h,sha256=_raNL9aHDvylCV5R1PHSfAhMGh_5YUHCFeIyFZnEbCo,17320 +tensorflow/include/Eigen/src/Eigenvalues/ComplexSchur_LAPACKE.h,sha256=NiGfqLtmQZ7oCCiMUQv3gQ7DTY3TZNDO99Kts_IC_Ac,4214 +tensorflow/include/Eigen/src/Eigenvalues/EigenSolver.h,sha256=ophf--Vdgm-C6Kxz5deBdIVk39-CObEBySTPIHXMGjc,23006 +tensorflow/include/Eigen/src/Eigenvalues/GeneralizedEigenSolver.h,sha256=8lzwLYrqOJ4FTH3jZvDBDhqwNte5EaGRdQUrq_hUqbI,17277 +tensorflow/include/Eigen/src/Eigenvalues/GeneralizedSelfAdjointEigenSolver.h,sha256=j_DIBO9T_DGNE1nEta1POA4QoF4mQWG6v-8fQ0Acvc4,9752 +tensorflow/include/Eigen/src/Eigenvalues/HessenbergDecomposition.h,sha256=jBFQ_ONwFqcq-pOpEIScNabpUsaulXIAR06nu79txm0,14372 +tensorflow/include/Eigen/src/Eigenvalues/InternalHeaderCheck.h,sha256=byzL-Pjcn2aRz3PKcwa2ifUAfS8F5P40zeXEsCKpkcQ,148 +tensorflow/include/Eigen/src/Eigenvalues/MatrixBaseEigenvalues.h,sha256=DAAQo4KzXDaDxGKtcaSL1X0NiaIESHxrG3eUwujpebk,5611 +tensorflow/include/Eigen/src/Eigenvalues/RealQZ.h,sha256=_rkY2hrM46di7VNe6KnevHNpfi1-8qAm3qa0KGVnw6Q,23758 +tensorflow/include/Eigen/src/Eigenvalues/RealSchur.h,sha256=921Zgg8adSzcKHkrOgN7LUSaAhw_VJnVoU587DY0qxA,21155 +tensorflow/include/Eigen/src/Eigenvalues/RealSchur_LAPACKE.h,sha256=BVaNwMgBtJXtzfVOpW4U9IswxCXYViFYBRtKFvJUMYg,3686 +tensorflow/include/Eigen/src/Eigenvalues/SelfAdjointEigenSolver.h,sha256=OsbNEj6uo0DAVkwBNiJm3VqsFvP7dIUGb9MpDvTNgTE,35395 +tensorflow/include/Eigen/src/Eigenvalues/SelfAdjointEigenSolver_LAPACKE.h,sha256=rqvPfQZS9rFB-cyk82yS2MPTjViDdXvz0s0GRMuYb3o,4140 +tensorflow/include/Eigen/src/Eigenvalues/Tridiagonalization.h,sha256=MjSgrbsnBnJcbLlTcQLTA_j6CkiVLAGapJkVwHHaLng,22878 +tensorflow/include/Eigen/src/Geometry/AlignedBox.h,sha256=CkeyWExZuh8AYnTOOg68FFHqpLimTAGLosuU0svOy3Q,18975 +tensorflow/include/Eigen/src/Geometry/AngleAxis.h,sha256=8THcy0fylT7dHFu31F6cOByCWJ4wkW0I5N1EQuOvt10,8439 +tensorflow/include/Eigen/src/Geometry/EulerAngles.h,sha256=0tyff33PN-WunoL-TRpP_uOnQuxsF22GeC0D3bqpryo,8420 +tensorflow/include/Eigen/src/Geometry/Homogeneous.h,sha256=nMXspb1Mbnpp373YzXIyFKkBMlWkLYqDQEhgkq9VrDM,20652 +tensorflow/include/Eigen/src/Geometry/Hyperplane.h,sha256=SZPkRu9WXSE5FHcDzJ3vmpz65M1_k3j4Q65xsYLOR-U,11997 +tensorflow/include/Eigen/src/Geometry/InternalHeaderCheck.h,sha256=qivX0LlQdh23h-EJU-3SOdk_KEn915LbswOEIYV5Al0,142 +tensorflow/include/Eigen/src/Geometry/OrthoMethods.h,sha256=hHAyWdqjIUFrUzE4Pk5TSQqRYPhyFokzqrh6MZNT0sc,11304 +tensorflow/include/Eigen/src/Geometry/ParametrizedLine.h,sha256=EV97kbKM49tgEbkUyJDMe2rQ1AHp3h7j-T3hXG-gn8E,9845 +tensorflow/include/Eigen/src/Geometry/Quaternion.h,sha256=N4Yivfu9LCRP1g8WTE5yWnO_-i9fnmuZYCyt9Yx3qI4,34657 +tensorflow/include/Eigen/src/Geometry/Rotation2D.h,sha256=aAdPrKLMgJvcD0TiEHEEv1ODuLzSD5WsrC7nAIvEaXE,6898 +tensorflow/include/Eigen/src/Geometry/RotationBase.h,sha256=Nv2sTkK_1e3PODwNmkHFHjHL75MVzz1VyCH4RXhXOgg,8099 +tensorflow/include/Eigen/src/Geometry/Scaling.h,sha256=QVUt1Aj9pOAmyNga5vxIAQrzStmPhCFd3n_t9fDkckg,7090 +tensorflow/include/Eigen/src/Geometry/Transform.h,sha256=qHDr3tl1Ki3irBcs12jw6tzsBkH0ctcUFF777t2qY3g,62294 +tensorflow/include/Eigen/src/Geometry/Translation.h,sha256=U77hRwsa1FFOJ8gaAnen8ok_Wy6R9q1Rxza6SNOrW7Q,7682 +tensorflow/include/Eigen/src/Geometry/Umeyama.h,sha256=T7Yfax55N6GFZZKNvsXQaJDlbJVyO2Q3NLAKnCMKJmU,6263 +tensorflow/include/Eigen/src/Geometry/arch/Geometry_SIMD.h,sha256=QLe8KChngpHWjn8NaN3LXHlLe6CbwkSp70-S-PqN4QY,5982 +tensorflow/include/Eigen/src/Householder/BlockHouseholder.h,sha256=JtoidxNGUz21MbCncj_oMxcFGwEiJFCnA5yMrfC9y8o,4821 +tensorflow/include/Eigen/src/Householder/Householder.h,sha256=CUI6AXQwnDAzrn02qSBfTNwn5RqXWwZ3fDAkjX00Syc,5434 +tensorflow/include/Eigen/src/Householder/HouseholderSequence.h,sha256=LSGV2kd1iV9o3KdeXlFPPCJYQHMu0wehBZPP2XvwNmk,23665 +tensorflow/include/Eigen/src/Householder/InternalHeaderCheck.h,sha256=DNTEipbt8ZK8xBESDKRwueu5PL9JTE9296oNwNDWA4I,148 +tensorflow/include/Eigen/src/IterativeLinearSolvers/BasicPreconditioners.h,sha256=x1W6O_MPNeuxl8F7qBZU3xioGN25wdYBV8Aq6lPH9cE,6807 +tensorflow/include/Eigen/src/IterativeLinearSolvers/BiCGSTAB.h,sha256=OjuuiiK2TmDyGZhztdrRYzmduSxcr-Uz_ksYYVmAOgQ,6886 +tensorflow/include/Eigen/src/IterativeLinearSolvers/ConjugateGradient.h,sha256=QwavuU74C-XrJrj5TlET2Q-L5mEMABN0JjoqFEOUFiM,8859 +tensorflow/include/Eigen/src/IterativeLinearSolvers/IncompleteCholesky.h,sha256=65OJLqvJFwbT6KTb4zYhG5WuTqp5FhuPjNlv4UMsc1s,15079 +tensorflow/include/Eigen/src/IterativeLinearSolvers/IncompleteLUT.h,sha256=XNUoxzxW_I1XiXvtDvGa_M0tLsllG57iuGAq7VV0qFw,14976 +tensorflow/include/Eigen/src/IterativeLinearSolvers/InternalHeaderCheck.h,sha256=Qf-w9OmfdOqSoS37D_pSZ0XPDyEK2gnCSfbUzUMbYGE,170 +tensorflow/include/Eigen/src/IterativeLinearSolvers/IterativeSolverBase.h,sha256=Jhli3PC4fCDivJNzsBWhgO6YK10oiiW58bwLBkNx-gM,13412 +tensorflow/include/Eigen/src/IterativeLinearSolvers/LeastSquareConjugateGradient.h,sha256=GBDK2JunVFwL6EzH3HvSyRoJJ-xYqZagWvWU30c25as,7400 +tensorflow/include/Eigen/src/IterativeLinearSolvers/SolveWithGuess.h,sha256=4rbB3HmHi-D9A6S31_BjuGf4jboYhANV2WlIUKufN5M,4245 +tensorflow/include/Eigen/src/Jacobi/InternalHeaderCheck.h,sha256=W7aaUNcfezh8iXoWUmTzJrng4rOI2TiKyGF6M5nabGw,138 +tensorflow/include/Eigen/src/Jacobi/Jacobi.h,sha256=_owUT1AGlpxKCYCk84MWJAvB6ygH-eoOeo3VNm0NTTY,16571 +tensorflow/include/Eigen/src/KLUSupport/InternalHeaderCheck.h,sha256=A3APIm8JE9rGFrt1SCFLjASKck3dUvd0qnafz4wduJ8,146 +tensorflow/include/Eigen/src/KLUSupport/KLUSupport.h,sha256=FNERN8FQSHoDzFAuaLXlnX3jRR2gs34pE3FGLM50bgA,11611 +tensorflow/include/Eigen/src/LU/Determinant.h,sha256=wT2znBCmIfPIdAPwka_Zpv7b55OwfaVsPrU-I_zGIzI,3588 +tensorflow/include/Eigen/src/LU/FullPivLU.h,sha256=KQcld7Er2VzWe6mu2nIXQerJfEu1aQNXnRm_mM4hFaM,33322 +tensorflow/include/Eigen/src/LU/InternalHeaderCheck.h,sha256=9QfZim1IzgSP89QmHkxjvTTXoiv5YMCZ8VQj6qFF2KM,130 +tensorflow/include/Eigen/src/LU/InverseImpl.h,sha256=pPQt8OG7oXfSIEby17dsD_3A6liLx7_SeDnBgmSfWgk,15714 +tensorflow/include/Eigen/src/LU/PartialPivLU.h,sha256=h3hITHosJmlnI6g4ZIWqXbQI_9mTR-U5e9-14fJW4BQ,22758 +tensorflow/include/Eigen/src/LU/PartialPivLU_LAPACKE.h,sha256=l1j8o4rk-rRxq0aX4jGIywgBPnzrcjia5NtMRlJBnCA,4164 +tensorflow/include/Eigen/src/LU/arch/InverseSize4.h,sha256=oMPi8OQqsHoNHtMzggmEbiL0V7zDhjZ506PczOQlYFU,13820 +tensorflow/include/Eigen/src/MetisSupport/InternalHeaderCheck.h,sha256=Hh-EAbq8lM4Ib_SOA_Og34gWQUNsURsi_1zhnV_lOe0,150 +tensorflow/include/Eigen/src/MetisSupport/MetisSupport.h,sha256=MJTmmh03OCepGTLCFsdQAO1NYLqxbzeTTQLrD5htfjA,4624 +tensorflow/include/Eigen/src/OrderingMethods/Amd.h,sha256=UzWDBj7OPpFfs53L74CjI_Zgk_inXvdng-GKru_tmpw,16141 +tensorflow/include/Eigen/src/OrderingMethods/Eigen_Colamd.h,sha256=aGVdr2uuSAuOnywk06Ox5iRwLxWsHoxIHuOpuiYJgOs,61681 +tensorflow/include/Eigen/src/OrderingMethods/InternalHeaderCheck.h,sha256=aSO8OmRxjTm7pNapq_sHmxnRZVTF0hOJppN3Abz6Er4,156 +tensorflow/include/Eigen/src/OrderingMethods/Ordering.h,sha256=9O8eYpyWE6BChfRwY2_iEP-9k6nnblLQaxPk1a-qSrM,5284 +tensorflow/include/Eigen/src/PaStiXSupport/InternalHeaderCheck.h,sha256=Bm_ENYSgScNXJiOWQWMg-_Eht5T7xsB5sXPpLYWnBVk,152 +tensorflow/include/Eigen/src/PaStiXSupport/PaStiXSupport.h,sha256=4ek3nCkbZFae7VL6YTMK4Ivsv74fjALiN3CnZnKfBgY,22284 +tensorflow/include/Eigen/src/PardisoSupport/InternalHeaderCheck.h,sha256=96bO5iakpNjej8QLxr8YNeTsFZF6WK1BaRJkQ7yVQnM,154 +tensorflow/include/Eigen/src/PardisoSupport/PardisoSupport.h,sha256=x7V-dLpPM5bS-3idxo2b6YB7DcSAMCwV0LC9b-ZzOG8,20124 +tensorflow/include/Eigen/src/QR/ColPivHouseholderQR.h,sha256=JN7tFvQoJ4nSh9CHSY5jIfoR-beM0EXfbMgwNDoUCvc,26754 +tensorflow/include/Eigen/src/QR/ColPivHouseholderQR_LAPACKE.h,sha256=NEYAzADDnCKy22d3hGrrqMI6iV7lDA4-PHkzD9hRfpM,8080 +tensorflow/include/Eigen/src/QR/CompleteOrthogonalDecomposition.h,sha256=sji6RfmpNo24UQb8Aki8wPIYXJ_-_100r5P2XcTOA1I,24917 +tensorflow/include/Eigen/src/QR/FullPivHouseholderQR.h,sha256=byX0BBIFSlXhAwmjkjpEAAnW-OI141Xmsi52tooIIrA,28893 +tensorflow/include/Eigen/src/QR/HouseholderQR.h,sha256=sVQMl1GoX1CGnY_JSai7zQK6Gi5Bqb4ySS7MubL8FAo,18625 +tensorflow/include/Eigen/src/QR/HouseholderQR_LAPACKE.h,sha256=mtoB53x0N-3SQgQpGb_0karG5DQlygQrgLawyhzTgGw,3012 +tensorflow/include/Eigen/src/QR/InternalHeaderCheck.h,sha256=1GQg_Yeb1TilTa66YfhA67YyKtdy6GofQv9y1QXlJ6g,130 +tensorflow/include/Eigen/src/SPQRSupport/InternalHeaderCheck.h,sha256=oGseXOD_aNQIGoCUHVXcdLmer-4pMDZJFiEFykmnmB8,148 +tensorflow/include/Eigen/src/SPQRSupport/SuiteSparseQRSupport.h,sha256=ocflkJ2OesZRy_3OA2vrh3vpBp0KVitlUNEOJw2E3Zs,11922 +tensorflow/include/Eigen/src/SVD/BDCSVD.h,sha256=ZVF8g_rMVvjR5lIei-nw1IMSrn-7Fs0SNl7FuutX1l0,62184 +tensorflow/include/Eigen/src/SVD/BDCSVD_LAPACKE.h,sha256=4u0_sctBcNJpXsOTC-6427JYxgImYgMEkenfiqvlj1c,6899 +tensorflow/include/Eigen/src/SVD/InternalHeaderCheck.h,sha256=dH80qOuBaJzc90FU_gFfOEbl4T-agrmV_-oQQ97a_Xo,132 +tensorflow/include/Eigen/src/SVD/JacobiSVD.h,sha256=grO42i9FQPWMUVO_XwD9vFadPgNAgt6wbriHmv2ljSs,35263 +tensorflow/include/Eigen/src/SVD/JacobiSVD_LAPACKE.h,sha256=x3J3iJp_R-tahWJRzg-tvp4couavtMxEyV9V_ZUlwaE,5993 +tensorflow/include/Eigen/src/SVD/SVDBase.h,sha256=6UJ_kWCrkBKU-ismpTQ9KtMHmuFjfQi85z3z5XBDdZg,19816 +tensorflow/include/Eigen/src/SVD/UpperBidiagonalization.h,sha256=F7fKlVMy-rQJ-FWdj0LFPA8oJ7Ea4GfBKAPTbJB0qTQ,16304 +tensorflow/include/Eigen/src/SparseCholesky/InternalHeaderCheck.h,sha256=gS0ORWY8VmW6hPesvqw2IlHAUpcNmHB1b_jjRJ3jc2I,154 +tensorflow/include/Eigen/src/SparseCholesky/SimplicialCholesky.h,sha256=IFQWAVxEnS9oJRqWRFN792OF6ixjO91I0hIZUNPAMNE,24252 +tensorflow/include/Eigen/src/SparseCholesky/SimplicialCholesky_impl.h,sha256=vM4CW8KmXdNt0jE5vnC1KNDGh-BbzAdh8oAjQyRxSZc,5866 +tensorflow/include/Eigen/src/SparseCore/AmbiVector.h,sha256=ZmSH7vRh2QfHmGICVmEo7OhJugSlBwQLZKHd0_D4XiY,10706 +tensorflow/include/Eigen/src/SparseCore/CompressedStorage.h,sha256=ovebDAwrKWpNTExQ-SvWpP9lbZHHoEdQC9-VmB431JI,7588 +tensorflow/include/Eigen/src/SparseCore/ConservativeSparseSparseProduct.h,sha256=eQ-y0lAvsXqaVLQ5PuI4KHADhIo94c20RM7I8D3OiFc,12582 +tensorflow/include/Eigen/src/SparseCore/InternalHeaderCheck.h,sha256=uMHTeZtzrLs4c8mVK1JyK-2R7s919F46-qAa3xQH1oc,146 +tensorflow/include/Eigen/src/SparseCore/SparseAssign.h,sha256=N4z4SxziT94T9eDuPPUNRXdsU_sRCQZr0iX2Mj7s7w8,11403 +tensorflow/include/Eigen/src/SparseCore/SparseBlock.h,sha256=5KDyXPx8G7eP_10oQG4iP_GIEoq67Nx9TB5rWX_nEQ0,24134 +tensorflow/include/Eigen/src/SparseCore/SparseColEtree.h,sha256=012R3ckCb_6hAHiiWOwKJV9oxA5A0SJz-epu43qeeDo,6521 +tensorflow/include/Eigen/src/SparseCore/SparseCompressedBase.h,sha256=r11tLqRLfwXkr--XZYn-BvbBhOthyD9h3D7MIXxYyWU,23226 +tensorflow/include/Eigen/src/SparseCore/SparseCwiseBinaryOp.h,sha256=FqszPMqkiEYtIGPNrG0esyeoKCw_np_-Cy2ACmOSqzs,36258 +tensorflow/include/Eigen/src/SparseCore/SparseCwiseUnaryOp.h,sha256=Fxdj1fpk5pQsGL7VGxkk1DiG9i_AGjrmm6iS7p6ybOg,4793 +tensorflow/include/Eigen/src/SparseCore/SparseDenseProduct.h,sha256=5pOvfFVay2QaL7THZywNCYf2Z1_ssmo8Nxn0fWkjtWo,13411 +tensorflow/include/Eigen/src/SparseCore/SparseDiagonalProduct.h,sha256=s-mjsPThrYbnVm4P8WaxMUodv76cRoGKJqSQEUdu1M8,5844 +tensorflow/include/Eigen/src/SparseCore/SparseDot.h,sha256=76ui7m8X2hPjJt0LP13dzgrPM4vAEDBN2oEPotD5pNE,3116 +tensorflow/include/Eigen/src/SparseCore/SparseFuzzy.h,sha256=Y519lcpwUBoXlSnux-jLCVPYNsQ2CNa-03fDz7sSolA,1125 +tensorflow/include/Eigen/src/SparseCore/SparseMap.h,sha256=c0t2QB4WyesB8zoiZQH-u5tioixJ6itREA2Nc-YoJCg,12613 +tensorflow/include/Eigen/src/SparseCore/SparseMatrix.h,sha256=cUg9FWu8hW-QY2c3S7cpW-fAzA-nfShZ1x6xbrjbsqc,80753 +tensorflow/include/Eigen/src/SparseCore/SparseMatrixBase.h,sha256=gieTLqlRLP0QqfNOegMLUm4y5WyZT0q7BTdGHvzlEVI,17281 +tensorflow/include/Eigen/src/SparseCore/SparsePermutation.h,sha256=pZTVp_KDlo-XqyxgDPRKG_QiNSyJ1noMKwFGI3vGKvI,11408 +tensorflow/include/Eigen/src/SparseCore/SparseProduct.h,sha256=7iOR6Pa4lY-dAAXYZoPpAvUJkDrt44DTM3bIPCRzJOI,7532 +tensorflow/include/Eigen/src/SparseCore/SparseRedux.h,sha256=pIy4-ZADAB5wgsiEsB5uYvnDpVv8eJH8tezAVnEv2v4,1735 +tensorflow/include/Eigen/src/SparseCore/SparseRef.h,sha256=h1lmS2EbZnm1cqsf3OKhWHZngcLgzVV1WEMXQYQWEsQ,15471 +tensorflow/include/Eigen/src/SparseCore/SparseSelfAdjointView.h,sha256=naPVeM630N-DkYM38j9hUX-oUjJlu6Vg_q3nqt-JRjo,25481 +tensorflow/include/Eigen/src/SparseCore/SparseSolverBase.h,sha256=2d5X8-p7KYM58RJQJiDXReUphRJJh-kW-n5TC9TL4ZI,4561 +tensorflow/include/Eigen/src/SparseCore/SparseSparseProductWithPruning.h,sha256=0SMWqGB2eH2FJJi6CkVHMpeMSu1cAa2qIiB-i-Tjz7g,8702 +tensorflow/include/Eigen/src/SparseCore/SparseTranspose.h,sha256=CgDDzAQ4XT6wEqoC_i22p4dBsuEmgjQzFCqMDx_UoF4,3211 +tensorflow/include/Eigen/src/SparseCore/SparseTriangularView.h,sha256=HP5Of8_9NoPk5miuZC5j8p6F5EPD0sk4d3DRaPAS8ho,6442 +tensorflow/include/Eigen/src/SparseCore/SparseUtil.h,sha256=zyjA2Trn5V7-dw_a67sEbthV7jhG4pp6PqFLsdGPGqI,6672 +tensorflow/include/Eigen/src/SparseCore/SparseVector.h,sha256=a9adSfdw-gosEnR7Vsvz4gfRCIdj7vnvagDvsl88n30,17978 +tensorflow/include/Eigen/src/SparseCore/SparseView.h,sha256=QmxYdRU5nUHBBtef5mG1QWR-zL5XQ5KyxvvqCUt7s7Q,8124 +tensorflow/include/Eigen/src/SparseCore/TriangularSolver.h,sha256=3Ux1inbqmCo-ovnsfhBGUQr096E4E5_G0WHAnggvcyA,9690 +tensorflow/include/Eigen/src/SparseLU/InternalHeaderCheck.h,sha256=1KfOf2LCyHnKLLpoApnOChQ-xbVv5cSbo9jY8ntUHNM,142 +tensorflow/include/Eigen/src/SparseLU/SparseLU.h,sha256=T0oLh9RwQcRZHn4cUfNqGR6iHUSczlaoJPbbVFxeva0,34855 +tensorflow/include/Eigen/src/SparseLU/SparseLUImpl.h,sha256=eki3Fr3TtyrtnDEZxt1PIshf3DAE97ajXmkHEZsn9zE,4339 +tensorflow/include/Eigen/src/SparseLU/SparseLU_Memory.h,sha256=FsJs7E-vY1iScRglEbV5j3hCg1NU_rIC8oott4OnDLA,7638 +tensorflow/include/Eigen/src/SparseLU/SparseLU_Structs.h,sha256=OpFl1WKVbZaOiKf2g3Akdx3fILl6ugeCiPwJf7E85rc,4999 +tensorflow/include/Eigen/src/SparseLU/SparseLU_SupernodalMatrix.h,sha256=1ey8HIMRzhPjMzz931LccWmNbijTce4gphA7fZ9unPI,12744 +tensorflow/include/Eigen/src/SparseLU/SparseLU_Utils.h,sha256=BPLbBAJShjSDYQU205ophUnQIT673yAigiFphdkViz0,2085 +tensorflow/include/Eigen/src/SparseLU/SparseLU_column_bmod.h,sha256=bt_zHpa84_amHh8rVdaMqGs3D2MTOTxTaIgb62Bi0DA,6748 +tensorflow/include/Eigen/src/SparseLU/SparseLU_column_dfs.h,sha256=JOpufBzUjdqhAo6drryF8LIEJno_v7Vj1ZiVLX0kuOs,6620 +tensorflow/include/Eigen/src/SparseLU/SparseLU_copy_to_ucol.h,sha256=gtA5yX371k3fwmrw_0mkLFt-scLPvuOO0cpJ9lpTTtE,3717 +tensorflow/include/Eigen/src/SparseLU/SparseLU_heap_relax_snode.h,sha256=dSOevuRcGUHSC9dco3SsZvusPcazUjubGs_s7JQY4SI,4000 +tensorflow/include/Eigen/src/SparseLU/SparseLU_kernel_bmod.h,sha256=SEWWJR3BGbUKWT2RP7_24o4P8dH9-zNAOBYNeElC63s,5621 +tensorflow/include/Eigen/src/SparseLU/SparseLU_panel_bmod.h,sha256=t4oD6sWZj4a5qptPV-J77uvwCNSbwmvRALyzUBAh_qM,8379 +tensorflow/include/Eigen/src/SparseLU/SparseLU_panel_dfs.h,sha256=ZK_u-CGjNdeKWZk0RbCskYwDAgoC0NfgpxF9AzGv5ME,9064 +tensorflow/include/Eigen/src/SparseLU/SparseLU_pivotL.h,sha256=ieAhsHTuAgrf6UtC87Ip_t7ZXLpSp7M5Z8FW95VbuZc,5015 +tensorflow/include/Eigen/src/SparseLU/SparseLU_pruneL.h,sha256=UR1GHY76Lkt4kmkNNexHTtxmxbvEETHUhCUazPO3tWU,4581 +tensorflow/include/Eigen/src/SparseLU/SparseLU_relax_snode.h,sha256=fjzVkV7e5p1hhZMXtraukX8u1SeQPl9nrx1oSaZf_-c,2925 +tensorflow/include/Eigen/src/SparseQR/InternalHeaderCheck.h,sha256=7SWb5IxAUT1bFYSx8UDafBxd_d8xxlAaX0MgFvV8la4,142 +tensorflow/include/Eigen/src/SparseQR/SparseQR.h,sha256=5HoMSMoaK7uwVwB_OP7Oki3KOeCP9_xCd3H6Bpj23ts,29184 +tensorflow/include/Eigen/src/StlSupport/StdDeque.h,sha256=kSFlCoJhqhesEOuR2_3mvu-2FpAyAiz2ZnzWLEpM2UY,1963 +tensorflow/include/Eigen/src/StlSupport/StdList.h,sha256=hKxOkT2sgZMEJ8jE7kvT6KKludcaJVFPG0801qAfqu8,1870 +tensorflow/include/Eigen/src/StlSupport/StdVector.h,sha256=XhKfKkUkXFD50Ys73H3swcIyEUABK5cetaQoAN0YvXs,1982 +tensorflow/include/Eigen/src/StlSupport/details.h,sha256=zH64Cae0Lf6V1Wpxlwpv_-E6lFGvzdHl7pGcO7QECRg,2761 +tensorflow/include/Eigen/src/SuperLUSupport/InternalHeaderCheck.h,sha256=T9ukAuBm7BYj3bZap_l_qLyqcLYX2xqhMCZ1Ub3hxoA,154 +tensorflow/include/Eigen/src/SuperLUSupport/SuperLUSupport.h,sha256=cgl__4I6l02tFWqgVRocgf646fno7pp0MXoahhwZnJQ,34360 +tensorflow/include/Eigen/src/ThreadPool/Barrier.h,sha256=OmKNGjJoccq4tfHIJO4ObPDH46gaFXDKYzsV9GLJSnE,2116 +tensorflow/include/Eigen/src/ThreadPool/EventCount.h,sha256=KPkK242iGBFKn5QngMxMk9sV0pYjj_1AeCMJSBKVvyc,9155 +tensorflow/include/Eigen/src/ThreadPool/InternalHeaderCheck.h,sha256=k7Zmgz5GzRtCQsrl7-49aPh4KIbTRnvGFpAJFDN-1UM,164 +tensorflow/include/Eigen/src/ThreadPool/NonBlockingThreadPool.h,sha256=rxy7KjPKugcGL2n7KRfKEXVv4A9PztRMr1PS4FCMOic,17112 +tensorflow/include/Eigen/src/ThreadPool/RunQueue.h,sha256=wznOTqBzu9CfjSd1j4qPaHn1F-9VUL8vyixr5MLZtJk,9364 +tensorflow/include/Eigen/src/ThreadPool/ThreadCancel.h,sha256=7IPJUGtaaS24TND4IOFoq2vf8nkj_q9_MC34dwtAmKM,774 +tensorflow/include/Eigen/src/ThreadPool/ThreadEnvironment.h,sha256=dMVfV8GFHqUi6VCA-ndTlGh9r34AAB3Pv1Ubvsissl4,1245 +tensorflow/include/Eigen/src/ThreadPool/ThreadLocal.h,sha256=UG1njdAc-zbXvK2-o4MxBDArgmAGSwojLm_Lx20qsxc,11335 +tensorflow/include/Eigen/src/ThreadPool/ThreadPoolInterface.h,sha256=c_nQyNJMgg6qLSIkOgpsZ3ZdnKsj0scB02M0grrLyf0,1716 +tensorflow/include/Eigen/src/ThreadPool/ThreadYield.h,sha256=qPtB8q2nHHSgVabCXDNawca84FUl4-GEh9fw5SK_39s,611 +tensorflow/include/Eigen/src/UmfPackSupport/InternalHeaderCheck.h,sha256=UO2sgJCKQFEVSGWAv-M6RwyZjQNXhs_GsNvVcBVyiAE,154 +tensorflow/include/Eigen/src/UmfPackSupport/UmfPackSupport.h,sha256=auSRri-zXDJcgGIavH8UEzEfM06GNQZOq5bdUTgYsTk,24496 +tensorflow/include/Eigen/src/misc/Image.h,sha256=qsKOvJvlLkTknRIAlvHTf9A6kTU-M5uaVFxiruK--B8,2949 +tensorflow/include/Eigen/src/misc/InternalHeaderCheck.h,sha256=R-f0eq5P5r53YNY1vUMKtfYHSE_FPv12vvcud20eQsk,134 +tensorflow/include/Eigen/src/misc/Kernel.h,sha256=Ejj2JaI3XJXQZ6PO6luGb8BQHjfHc19aeVBbO8FT4xM,2778 +tensorflow/include/Eigen/src/misc/RealSvd2x2.h,sha256=Jy6--Qn8LPeTc1tg6XudW6kWdhF9570qbfZAcSeDaog,1784 +tensorflow/include/Eigen/src/misc/blas.h,sha256=qkgMDdnkRoMPfd96yd-ernsbYZcu6ff7HlEL-IgEKWg,6030 +tensorflow/include/Eigen/src/misc/lapacke.h,sha256=BD1o_l6e7yVAP_KiXaRcfWsEZJquU_Wpek7csJVgQ4E,1058402 +tensorflow/include/Eigen/src/misc/lapacke_helpers.h,sha256=ncbj0uysSGsdza8ASmKO1BepgofVLTmkmH-iF0nvJLc,6572 +tensorflow/include/Eigen/src/misc/lapacke_mangling.h,sha256=fXH97lOh4M0BVoq6LxUvLh5Pu4SehNdA47Ax6Bn7-iI,474 +tensorflow/include/Eigen/src/plugins/ArrayCwiseBinaryOps.h,sha256=C6GgMUakapwY2hFqYJyTDt9qJN1Wu-LD953Krpb_GOk,13721 +tensorflow/include/Eigen/src/plugins/ArrayCwiseUnaryOps.h,sha256=cXKD75t5XzHdGn5OyPcabKeFC7laR7k0Y2C9_v8tTI4,22938 +tensorflow/include/Eigen/src/plugins/BlockMethods.h,sha256=CXoW_vYXomuOBubE23I3ZMi4iuZtNa4os5NhIRsszbk,58948 +tensorflow/include/Eigen/src/plugins/CommonCwiseBinaryOps.h,sha256=FaUr8Ron2XgzWpjIo4RQF98az0AfWzQ1kRQYhLoNHSc,6282 +tensorflow/include/Eigen/src/plugins/CommonCwiseUnaryOps.h,sha256=chYCU6dN6opvHii6TVq70qfe1xGoT6sglaWzl4IVWV0,5925 +tensorflow/include/Eigen/src/plugins/IndexedViewMethods.h,sha256=20WuCDIuxuh26IFr_CgzpaH7EICMzgJnx2y7wxxNMuw,17673 +tensorflow/include/Eigen/src/plugins/InternalHeaderCheck.h,sha256=nQ_rK_jxElgTKUiV20zTQWN6tgLnEm0WqUz9sTj3SVQ,137 +tensorflow/include/Eigen/src/plugins/MatrixCwiseBinaryOps.h,sha256=KluMR3LZ_hfFjeuV5O6Nj_RpFJRturUrJRxfLV6maiM,16882 +tensorflow/include/Eigen/src/plugins/MatrixCwiseUnaryOps.h,sha256=HrTaMUJFF71PqnqTq7Do5z2vRh_VpNsqrSV19SvsJbU,4105 +tensorflow/include/Eigen/src/plugins/ReshapedMethods.h,sha256=FckG8N0LFSwvIOKkUUTNWBjo8XmSy3rHiCUhaJQ4Rxg,6891 +tensorflow/include/absl/algorithm/algorithm.h,sha256=1KdNCyumvWEx-wGST-j6HnlglI2LV2Kny2S0AVBAWqA,6293 +tensorflow/include/absl/algorithm/container.h,sha256=JSnZBbyLohWYVCt0gX9fgRu6xCJNI-d7Ief30W9TN0w,78119 +tensorflow/include/absl/base/attributes.h,sha256=BBeM6o6eBYXNDRqOwEhnhlmPdvwoUpabCV_9ZBFaogs,31332 +tensorflow/include/absl/base/call_once.h,sha256=SE1E14-SR23R8Qr-5ZPFo9boN0_aa5Wx9OX-ZaXq5Dw,8150 +tensorflow/include/absl/base/casts.h,sha256=Y9zXe50U4XpDDy8f0E_-XFd4bR2yirAuHWTpZ3Xsnwo,7064 +tensorflow/include/absl/base/config.h,sha256=f-pej4y-9uFwsKe52_TNLO0F11hM7rrt5i29E1Sqs6E,37508 +tensorflow/include/absl/base/const_init.h,sha256=VwoAS6-Llle7TW6qPKO3Ei0MA-CGp6UqWOc5MZaUZ5o,3431 +tensorflow/include/absl/base/dynamic_annotations.h,sha256=oZyI2FIofrNrTte9SGP6BSqF0XwzCIMhvZT9Bj_7-Mg,19172 +tensorflow/include/absl/base/internal/atomic_hook.h,sha256=Sf27Yb5WivSLpMtGDcOLUI51EZdnRJX1j1jqJpPK8pM,7511 +tensorflow/include/absl/base/internal/cycleclock.h,sha256=LAbFxIB9fg2itSpVSkMbYnALU8JgPY6SWVig0DKjaZo,4983 +tensorflow/include/absl/base/internal/cycleclock_config.h,sha256=d6cb0NiwRJTB8EIlV2IN4qTAJNVNahaM5viNsQ2BeJE,2020 +tensorflow/include/absl/base/internal/direct_mmap.h,sha256=cVyLSDqQMapMUGL_uMn6MdVu5MZVlu2MBuapKBdVuRE,5851 +tensorflow/include/absl/base/internal/dynamic_annotations.h,sha256=59E3QLXoNNq-kU8v10oJxq1W-bN9yxmAAn2PXD2iZ78,15874 +tensorflow/include/absl/base/internal/endian.h,sha256=RjihlUXHtJikjMFRLsvUe8lcoHsTRZ3hFg_APmpjZJo,9261 +tensorflow/include/absl/base/internal/errno_saver.h,sha256=AdaELNuQbphCbAO3--JPDe_1PJfEScmu9TrOZgecIPs,1321 +tensorflow/include/absl/base/internal/fast_type_id.h,sha256=hRjto0LIj5I3n0IzfQHV9HaXVkDrnO3ums-JJj2ieqs,1458 +tensorflow/include/absl/base/internal/hide_ptr.h,sha256=yIPb4_DEqiaIpgKT8INm0Io7jRm0NUdlLNAKaUKJrSg,1677 +tensorflow/include/absl/base/internal/identity.h,sha256=hMh2YDZxJXC2uU71KL6Dhv-0VXDYt66Hi_xbN-Vw8gs,1012 +tensorflow/include/absl/base/internal/inline_variable.h,sha256=KT3f0ACHTX9cjdbtJfIqKEn0lvAi5XI0BkdnFZsQ0Ns,4679 +tensorflow/include/absl/base/internal/invoke.h,sha256=dpFmaiday7TIYSazUoiBzsabgFf0icp5OaMuJ1Apzv8,9405 +tensorflow/include/absl/base/internal/low_level_alloc.h,sha256=vl4-IosrTkGxCJ2CMQ-g8L_fw_NdZHkbdGu_9P5VfSs,4688 +tensorflow/include/absl/base/internal/low_level_scheduling.h,sha256=gcKRvs79_fpVrceCpLU7seEz5d7uHc8iwnWeConjA8Y,4827 +tensorflow/include/absl/base/internal/per_thread_tls.h,sha256=4i0ERllD9gUR4ZV_tH5XDdX_U-seM4XwhAR9OIHc86M,1758 +tensorflow/include/absl/base/internal/prefetch.h,sha256=uatYm0IGvlN_Z0C5-3pESZdAk7dElFDsFUzFPIkVafM,4358 +tensorflow/include/absl/base/internal/raw_logging.h,sha256=JSYVi5pnYI-Yi0mDGBMf8qDbIoLSGxkiAH3gb8Bqo3U,9407 +tensorflow/include/absl/base/internal/scheduling_mode.h,sha256=3TDxBOtnahx13ekQ2ZF5K4UWpNyDpvAI6PL_E6ZGB3s,2410 +tensorflow/include/absl/base/internal/spinlock.h,sha256=J9io82lbM6px6BL6ahNt_O0SHO3rL-p-rs6iARdHjGs,9721 +tensorflow/include/absl/base/internal/spinlock_akaros.inc,sha256=i_y22R5PfUylk4NcvHCj63_f0j5Mauccw8f7jFOA95I,1359 +tensorflow/include/absl/base/internal/spinlock_linux.inc,sha256=fDEGOnGfFEUpdJV3U3rVD8MOdtwdQBxYhVhIu15W1kk,2387 +tensorflow/include/absl/base/internal/spinlock_posix.inc,sha256=sqWyqa5205tB53FBpLxiKYA6LZctAYl-HUpOUbdvsZ8,1484 +tensorflow/include/absl/base/internal/spinlock_wait.h,sha256=DjAT6doRYCaig_iBWD92fa6cyFR-jL58tXrMnyplkEg,3850 +tensorflow/include/absl/base/internal/spinlock_win32.inc,sha256=seAG2HHin1KZ9EBGQFSbQsnz1QBMCgJMOc11lUMRieg,1369 +tensorflow/include/absl/base/internal/strerror.h,sha256=TXRXoKkM-uQ3aacDyY7jZmaS1TTUevjkR90OKunRtxY,1386 +tensorflow/include/absl/base/internal/sysinfo.h,sha256=HE2T42-E31bUskhx4OEjKIZFaGaBdJbvtSeCt1BQz_8,2702 +tensorflow/include/absl/base/internal/thread_annotations.h,sha256=rIwx3Trgl_jv5ClwCvYPpnVwblCx6b8AzRQ6LruKG5k,10851 +tensorflow/include/absl/base/internal/thread_identity.h,sha256=iQFf1_gC7oafAmdlix3mFeXno0kHn3zuiGCJYCGvDvs,11113 +tensorflow/include/absl/base/internal/throw_delegate.h,sha256=JiOH7AJB7hzKuvfHfi3TxCBDXkDiw7VXO8CeqC2sW6s,3331 +tensorflow/include/absl/base/internal/tsan_mutex_interface.h,sha256=manu8qVZ32lyl9uWgv2HP6jBjWwnwwn0nQga8aVQ6qk,2521 +tensorflow/include/absl/base/internal/unaligned_access.h,sha256=Mc8qkZ1fB_-wviJEcLYeY_1_WSr8W9Q1kwepTc4SbtI,2424 +tensorflow/include/absl/base/internal/unscaledcycleclock.h,sha256=qqlsUhzBV3V8PqnuJvgPQLJJTi98yNAQyfUGpBZiPxk,3131 +tensorflow/include/absl/base/internal/unscaledcycleclock_config.h,sha256=Y-d7SMwaPfF4EbKZQaW0gW5-H3qTgvZf-pKD3csKgMA,2575 +tensorflow/include/absl/base/log_severity.h,sha256=mZUFdrUNg-ESxg_uUQwoqgKDwIRRRnCvntH9kvL982U,6603 +tensorflow/include/absl/base/macros.h,sha256=R-AjYL5t8bF-RJ0AKzR3x7e6vhwNen17l4JXttx3LUc,5162 +tensorflow/include/absl/base/optimization.h,sha256=cSqCSjhvCh8n38SOIHXHAcLkU0ihVUP0pbDjBGQCXAw,11790 +tensorflow/include/absl/base/options.h,sha256=p2a9X7Q907hKzdxJiK2oDo3_u6lehnOExwaBzOpLKho,11409 +tensorflow/include/absl/base/policy_checks.h,sha256=l_QyDgHvKlH5PdFq1SY58wCX8MfYiTz9pRrvsDbnp1U,4284 +tensorflow/include/absl/base/port.h,sha256=bSowyBoLZezojOFghtlAKRPF7Ry45C4o9Qj80bqVTZM,896 +tensorflow/include/absl/base/thread_annotations.h,sha256=bh13Ou-AZRFjj_7c9j9n34xrvQaFEPSCdrnzQQQeOe4,12060 +tensorflow/include/absl/cleanup/cleanup.h,sha256=kvPN9KvuoXZ6IfdwTkTt4Yi2aCcaBwIkSJIJTfxGPqM,4642 +tensorflow/include/absl/cleanup/internal/cleanup.h,sha256=8dPDgRGeqxboqRlWPGDep0b0ILpC2QKsgkqXknFNErM,2763 +tensorflow/include/absl/container/btree_map.h,sha256=ld6AnT6WzzYxgrOo-nNpnuAmLqbTXmHH9bE46ZSJaw0,32904 +tensorflow/include/absl/container/btree_set.h,sha256=t9bKXT8dhiOiczhPGAIHfJkfbJNRG3G7dpGP0fIv98c,29278 +tensorflow/include/absl/container/fixed_array.h,sha256=ZXvmEKswf9AfbzUKpkQPuFIELdbwrXjTWRLc4SuweEg,19407 +tensorflow/include/absl/container/flat_hash_map.h,sha256=X5GoNyVNUBdZINg3kW3g_PoYbpD6EiYftT01iJKpgIw,23874 +tensorflow/include/absl/container/flat_hash_set.h,sha256=7rGTwlNK_7SN0hw7PDsk3MRcvafFRD_Tm7jTf7S0-to,18790 +tensorflow/include/absl/container/inlined_vector.h,sha256=817ZddUGRN641CVvZK3CoUd1XFS87V8-3MmIdk7wwAM,35221 +tensorflow/include/absl/container/internal/btree.h,sha256=cJC3c92yoOhA1qpoJNRn0L42LtL8u_kNTrrocxKsDZ4,113096 +tensorflow/include/absl/container/internal/btree_container.h,sha256=WcjYzd9ZGbPQ9hiFFj1C721Xuopdcpgcuy0Z-EGu_LY,27787 +tensorflow/include/absl/container/internal/common.h,sha256=Im5oNdmfCVS5rvkKp_RNssxgY7r-v_3bURKDFEePhOg,5639 +tensorflow/include/absl/container/internal/common_policy_traits.h,sha256=mErtDTFi9ZbEAEUIpQFPgmesNfMkFCDifZIRRxzyq3I,4839 +tensorflow/include/absl/container/internal/compressed_tuple.h,sha256=OOR31Ek2szkkP14frWyO3evVtNolTLzd9SoqiLlOnHE,10632 +tensorflow/include/absl/container/internal/container_memory.h,sha256=K4sTlmYRZDq8vn9xrjDYE6axpIPIgBv7Sv4_4WsyHms,17088 +tensorflow/include/absl/container/internal/hash_function_defaults.h,sha256=1jTZTM8oMZt1CArpG2J_ObBPPWkhYSzf0oI7qCtceJU,5494 +tensorflow/include/absl/container/internal/hash_policy_traits.h,sha256=SJW3gpndCmq1mIAaTeyzJ5_ysfasQa522FnCTnum6dg,6323 +tensorflow/include/absl/container/internal/hashtable_debug_hooks.h,sha256=UFd3innmZ1kZqhFlKi3nH_dmdPD-C9Ju5DvocEa5dyo,2976 +tensorflow/include/absl/container/internal/hashtablez_sampler.h,sha256=JrOo1p7pghKps_L0uFhWCblyLd0ECVxCHQmrVoN7Ffo,9792 +tensorflow/include/absl/container/internal/inlined_vector.h,sha256=sDy5q4vX5LkoG9Bmnz0A7la8cwMN0inlXjT4VVYKQBE,35541 +tensorflow/include/absl/container/internal/layout.h,sha256=gzh8tCWBVviaebBYYNsCRHrT-n7E7U97JA1aBOPuYyA,27200 +tensorflow/include/absl/container/internal/node_slot_policy.h,sha256=_UOZx9ADh5CkFeFW0Q0rUnNMC5Q2ZQVwabYbcgeEhgI,2858 +tensorflow/include/absl/container/internal/raw_hash_map.h,sha256=nAvaFSiL6x_mcv75sICW_Z1Kd3wPtVr8d3BlYSfUqQA,7640 +tensorflow/include/absl/container/internal/raw_hash_set.h,sha256=tK_cCkXc3wpX31DIy31OXyaKQ1CaRH9Jm-Pwnj6mu3g,106334 +tensorflow/include/absl/container/node_hash_map.h,sha256=hImzdWnBw8ur4kqNPNQqYFXfxmZk8UvF1WLMy9D3kcU,23615 +tensorflow/include/absl/container/node_hash_set.h,sha256=87E5jnwJz95sLVZqEmbDtMtN_CQkHmZOaeyLjaeYGZA,18831 +tensorflow/include/absl/crc/crc32c.h,sha256=eAEn0-EDALrczMto4q5SZRhUr99B-qRDPEpr9LQ9NnQ,7043 +tensorflow/include/absl/crc/internal/cpu_detect.h,sha256=naCHS4kCyYpJOzsICbdYz1-s2RtQZ9myORioNaE8csk,1758 +tensorflow/include/absl/crc/internal/crc.h,sha256=eEZLgsxZaix8WA6Hblt0pdYwHtUKRKVeBknL1703VdQ,3443 +tensorflow/include/absl/crc/internal/crc32_x86_arm_combined_simd.h,sha256=w9BZH_lWMSCHvbATDLNPj91dUrS6LV2SrZn_cvtL7UI,8167 +tensorflow/include/absl/crc/internal/crc32c.h,sha256=ELDWbEULoE57SmKWrsob1ha1jc8ZBsIg4nlmiN1jNqs,1263 +tensorflow/include/absl/crc/internal/crc32c_inline.h,sha256=XGtYlxzNJep2Al_RmsskWPlvJZyXEhNxkRxhqRpk24Q,2108 +tensorflow/include/absl/crc/internal/crc_cord_state.h,sha256=gm3kCDmz_r34tzfuazvbeKmcoyasIK_jXeyND68SF7g,5873 +tensorflow/include/absl/crc/internal/crc_internal.h,sha256=NnnPYT0oLfyvtH6piU5K5ghxZgHlX55QOkMX9_YCCC8,7071 +tensorflow/include/absl/crc/internal/crc_memcpy.h,sha256=f4q5RjAtWS9BJ6tqpXjfnyAar5KtTg3XVvXhHggED94,4298 +tensorflow/include/absl/crc/internal/non_temporal_arm_intrinsics.h,sha256=ciYRXYpZPh0g3SRhkdlBhjHPMWzN_Awq7nW5EZg43sg,3255 +tensorflow/include/absl/crc/internal/non_temporal_memcpy.h,sha256=dLs47JyhghIUqjYxdwf4VKIdMNvsx5__cDzc2Hbbn10,5850 +tensorflow/include/absl/debugging/internal/address_is_readable.h,sha256=Tqm9PUPhLJ-_qeDhce_Dma6rbBEyArlVf1sFzBUU22g,1083 +tensorflow/include/absl/debugging/internal/demangle.h,sha256=7M7rokO1gr09hvwn6PQYmyFuy2tc2lVXNCW0j5sUNLA,2741 +tensorflow/include/absl/debugging/internal/elf_mem_image.h,sha256=BwBCHnDzkEbi_OdnnNMBYxx6aLberm9zsShN3ljEqmo,4813 +tensorflow/include/absl/debugging/internal/examine_stack.h,sha256=XJafSs3joqOvSTAL5DAPaYewcEzVwg0CtW_-e8mazZk,2567 +tensorflow/include/absl/debugging/internal/stacktrace_aarch64-inl.inc,sha256=aF5HD6cA1mpkPW5bgGugCk1wnhGG8eSebchmdjRvtk8,7873 +tensorflow/include/absl/debugging/internal/stacktrace_arm-inl.inc,sha256=WFQwPPJlh7B2pWrruYlP_KiVywNVqsrQYPprWw8Pn34,5162 +tensorflow/include/absl/debugging/internal/stacktrace_config.h,sha256=LPKIBLSlLynYdxyeEWSFnVwT54DRFgp1WJC4U8ILH4k,3398 +tensorflow/include/absl/debugging/internal/stacktrace_emscripten-inl.inc,sha256=qR5BVxxlDoP_hLcMGPaZCc9cRH4sDMmJ-RMMHSN5J-I,3852 +tensorflow/include/absl/debugging/internal/stacktrace_generic-inl.inc,sha256=i50eZZSAv2lfMj_MWrSQdIpCoE-8mL1dkcALbEjFTxs,3976 +tensorflow/include/absl/debugging/internal/stacktrace_powerpc-inl.inc,sha256=-j0gejbVJtGPwvCCm3DMgMgtOIH9rOhXqxHygdffFo0,10361 +tensorflow/include/absl/debugging/internal/stacktrace_riscv-inl.inc,sha256=FKc11jAo-I6rYqkBQQjVwcuUFW9TuOBrsBtEIjcYgqk,6871 +tensorflow/include/absl/debugging/internal/stacktrace_unimplemented-inl.inc,sha256=dP1mkZ-0IVUT_QXH9OzcyIfN6Wpy5XaxEhbTHPswwAI,730 +tensorflow/include/absl/debugging/internal/stacktrace_win32-inl.inc,sha256=filoFok1uUCl66BlDUDL7vqPhgcbreYVewHbAbaHirw,3901 +tensorflow/include/absl/debugging/internal/stacktrace_x86-inl.inc,sha256=fmNCvtlOwMDoUAVGAuUmQVDQWUSfyBtTsFUOeAorqbE,15531 +tensorflow/include/absl/debugging/internal/symbolize.h,sha256=ZCWgWU3ymYX-S2WLQFHQ8rEam6_Hf2mUrSRMAABqSXQ,5326 +tensorflow/include/absl/debugging/internal/vdso_support.h,sha256=HbITpq4A07yQLJi9nm4LelkFTr9rlrt3Ed0BEUdagTI,5823 +tensorflow/include/absl/debugging/leak_check.h,sha256=2dQJEN51tVyDHtEL1wiYeBfXwJOo1vdDuGP-SvDhGjo,5517 +tensorflow/include/absl/debugging/stacktrace.h,sha256=1KcJmPut_M1c5U4xZbKYyu7EcUrzCF8U08v53TZjUAY,10329 +tensorflow/include/absl/debugging/symbolize.h,sha256=Bkp8cyY1koauugDgnShw_G33DTi1v8lVWqKd2ZLniv8,3633 +tensorflow/include/absl/debugging/symbolize_darwin.inc,sha256=5mv5-CAt6ohy1yY6Y2W6YKrFOHYdiPwqfWWyT6TuFUw,3293 +tensorflow/include/absl/debugging/symbolize_elf.inc,sha256=W_wjoiZPDhqs_eO1fBrN0TpAi7VmGx0RmHvRFrElYNk,57194 +tensorflow/include/absl/debugging/symbolize_emscripten.inc,sha256=w1dcx52woXSrXIREfXL6Oti9MpoGO2OpcT87yGJMslk,2119 +tensorflow/include/absl/debugging/symbolize_unimplemented.inc,sha256=rwku2ifl_zTLj93J9qDoW7QIQ1JtPcY8-X5PQIQ9J4U,1288 +tensorflow/include/absl/debugging/symbolize_win32.inc,sha256=3uYZTYYo6bhjmwIItbj07ZSuBwcim6g-c7KC5qgAZn4,2769 +tensorflow/include/absl/flags/commandlineflag.h,sha256=HVev_hoaqjgobaNY-JS-miOjG1MQwj4Cz6W2M_iKfFE,7060 +tensorflow/include/absl/flags/config.h,sha256=tfYSsGaVKewMHIFzvMqjv3gvSK_nKxz5t74lVaZpjEY,2387 +tensorflow/include/absl/flags/declare.h,sha256=Rd0HhOfmBVUuJdT4x9WvN039lRi-EemLjoGhRh8kJaU,2516 +tensorflow/include/absl/flags/flag.h,sha256=ZP6n0ME8GU_tPteWH_1ZXtrb3RNo7PZ4n3yE7oomulY,13484 +tensorflow/include/absl/flags/internal/commandlineflag.h,sha256=hMFxuo1QDAuWn112FHnub-tB_wXRiDEtTOZSJXpOs70,2501 +tensorflow/include/absl/flags/internal/flag.h,sha256=ujgk5gdmSefA4-PZA-XxFvdgxNOl_dG-v8_mQaDlo_w,28304 +tensorflow/include/absl/flags/internal/flag_msvc.inc,sha256=cJ4LI3SOVNSPIDwca14puHiUdg-MkuKb1KObWl2qduo,4740 +tensorflow/include/absl/flags/internal/path_util.h,sha256=CoAaEkx8x8KRHxCN-6GPxLboUL1-VW4hw0WZcUgLCiE,2117 +tensorflow/include/absl/flags/internal/private_handle_accessor.h,sha256=ENJ--cuOkzTT13MHqOeyydWaolr7Z5M2rMAZ13Icf58,2225 +tensorflow/include/absl/flags/internal/program_name.h,sha256=FTNIgjkD8I68woRGrfHvpz-SvQppLfuo77A9qDUV4WI,1692 +tensorflow/include/absl/flags/internal/registry.h,sha256=aQQmoWmQnrkR7NvckT2diR27pvn1J0llqsTazbyGljE,3655 +tensorflow/include/absl/flags/internal/sequence_lock.h,sha256=IhohuAlz1TKPYOuazQE6C4woQtrri-CH7bD0f_EDYRg,7692 +tensorflow/include/absl/flags/marshalling.h,sha256=9nGLLQhAd8o4Q_2UKGixNkZvZ32-tGgvLMz3pV3HI_Q,13514 +tensorflow/include/absl/flags/reflection.h,sha256=YurCRb9S5YsPZHdJ27MPeb0iXjTqX47JD7u7W8TtRZY,2883 +tensorflow/include/absl/flags/usage_config.h,sha256=EBebTM8yKCMQd7WqVhQHddWGcda-jPI8adCaz0Ci0JI,5173 +tensorflow/include/absl/functional/any_invocable.h,sha256=-joYPkPxj53amISZ5k538avOLgh-KHQ7fOamR0KVOoQ,12220 +tensorflow/include/absl/functional/bind_front.h,sha256=Ik5M0r1qnEfIAsN_AiajmXsKFcTtG57obIOvdxidVmw,7424 +tensorflow/include/absl/functional/function_ref.h,sha256=My-PG4MY-sZSr_BvxSkSzKbUlf68AhpEC4P09wlNPk4,5805 +tensorflow/include/absl/functional/internal/any_invocable.h,sha256=HX1UCkJzVXPFUQHM-3Om5d1FPtZbZ6XMzwWXW9vv7ZQ,39494 +tensorflow/include/absl/functional/internal/front_binder.h,sha256=HEQhFggWbvQQfipRSrtgIIEjZO_ywBzE4j1vaz0kMyA,3685 +tensorflow/include/absl/functional/internal/function_ref.h,sha256=_HXOmowfVKQOy_nyJ87ks9vwiFT4JIGBcs_66KuB2jQ,3656 +tensorflow/include/absl/hash/hash.h,sha256=1s4fK0ZZjfoTiCFrvm6ZvdILC7lLiSelvi88bTjF8n8,16609 +tensorflow/include/absl/hash/internal/city.h,sha256=4stOY2T1lNqgJkUQmJodeCfgryR7mlvmTcan-RgNi-I,3060 +tensorflow/include/absl/hash/internal/hash.h,sha256=jFUrDsHnekU9aW5CO8OYySwD2IqgllaqivxMKvMn39Q,50618 +tensorflow/include/absl/hash/internal/low_level_hash.h,sha256=-JwwFFYiG01iTkYUejY1Pq7S-ehmvWQeLLTBnFU3A2Q,1794 +tensorflow/include/absl/log/check.h,sha256=zJIz9YnB5br4qm0zxX1m8dx4TXFevsuMLfiXYVZGjq4,7908 +tensorflow/include/absl/log/globals.h,sha256=1S_tDHZG4pHyiShvrHn3QzU2-gpTwTV7ndbisc7F-vY,5787 +tensorflow/include/absl/log/internal/append_truncated.h,sha256=yqU_nCcOesHcrzFAhgxkJI4Xtfr4QqZs-qaR9J_UVas,1623 +tensorflow/include/absl/log/internal/check_impl.h,sha256=x7lEJpRk3gNKycWpGwJi8ZM23padmvyljIAhKox64GU,7478 +tensorflow/include/absl/log/internal/check_op.h,sha256=F5MxlClMwsVph0g5OJ-ajWv4GAXPeAsPifv1SJ7_HCI,19920 +tensorflow/include/absl/log/internal/conditions.h,sha256=UhN05zlhjDbMQBOk2mcowUFLTgC46XI4wNAAkPkdfuI,10212 +tensorflow/include/absl/log/internal/config.h,sha256=5eBqaBh2x9QtE089PlJTE9MjCbzOH4MaRwVlK0rZilI,1214 +tensorflow/include/absl/log/internal/globals.h,sha256=bydiafiIdCEWBfzcxZZxhDGOPdAI9Nfx4SaWmwi_3-c,4030 +tensorflow/include/absl/log/internal/log_format.h,sha256=_ko6bUs1DpWhZ1tGGZ0CF78neBnEAidSFGdvOBV1KsE,3033 +tensorflow/include/absl/log/internal/log_impl.h,sha256=UjF_NOtv5W6gzPPPXloNfh64hETpMSOEoygl8H7l5iA,9723 +tensorflow/include/absl/log/internal/log_message.h,sha256=-RkW1oC-1gI-LEsz6jfg7ZhP60T-GgohK7-TV4MoWs4,14781 +tensorflow/include/absl/log/internal/log_sink_set.h,sha256=jAFtHWGfDiOQEisrOnlsA367ZXkF94mKiViTpI2ITXE,1977 +tensorflow/include/absl/log/internal/nullguard.h,sha256=YtUffYVsMa0foADKLO2Bh8TqcenIot5_SApYgdgSfuI,2846 +tensorflow/include/absl/log/internal/nullstream.h,sha256=UbFyEQ6TKqih0JuSZWAJgIf5hRR29BOMLCKSfiKE3BM,4312 +tensorflow/include/absl/log/internal/proto.h,sha256=AYhFwnNoqA-1OIaDZMslwhS3gBrMPDeptRbzCjF0gTo,13147 +tensorflow/include/absl/log/internal/strip.h,sha256=XbI5EZKeTotrKUSNVjLu-Q8dAc6bSnmxMRi8ftkECRQ,3747 +tensorflow/include/absl/log/internal/voidify.h,sha256=iqj6A1EiY4NPBn6SsEV7EPHNSQMPv3nly-bXEYeJ7AY,1451 +tensorflow/include/absl/log/log.h,sha256=3B0g0MoXbCtXZifhvDDff5jUe5zNf0IwZbBPEvatzAU,13958 +tensorflow/include/absl/log/log_entry.h,sha256=GXOTEBrYl7hiszFBXVgwf71qZ6S16IDyNiB0B28RvwQ,8228 +tensorflow/include/absl/log/log_sink.h,sha256=BD3lofYCXUN9YyG9WGb-9MvBywZV9yz5kWHPH57Iuuo,2147 +tensorflow/include/absl/log/log_sink_registry.h,sha256=6wu_RhG5PInkrJR_RDXepMltpZnYYM_hvXWUM1Z7gog,2134 +tensorflow/include/absl/memory/memory.h,sha256=kumsmbTbDtRLBLef9QklXJ_qMhvaZl-F4m_SwTEw7w0,11324 +tensorflow/include/absl/meta/type_traits.h,sha256=L7gKGQSPxZTFpfeV4Yxs7W7ArxgfGWzKCQhGHNqd32c,34471 +tensorflow/include/absl/numeric/bits.h,sha256=6qD2fPD2zQjXBMUxk34iuhfHUzWtZZNKUW0Vv9heXdA,5692 +tensorflow/include/absl/numeric/int128.h,sha256=FYQyINz1CZUaqeQgcJrmxdmgcs6rhsCixKVqRRwqUrY,38422 +tensorflow/include/absl/numeric/int128_have_intrinsic.inc,sha256=vgnppxeknCSUDiDaEdrOqku31TiAZlC9b140In4BmPs,9380 +tensorflow/include/absl/numeric/int128_no_intrinsic.inc,sha256=szrFDw3qWiALtoaJ3nWch-4Z0l6HG5ixLigQ7sbad1s,10808 +tensorflow/include/absl/numeric/internal/bits.h,sha256=ZHuJya58Ak4MWm35hBEtsHR2pKrOluLSJt4mP6Bd43w,12570 +tensorflow/include/absl/numeric/internal/representation.h,sha256=Mm3P1kEmEAmM5cTxdMCD1PNhsDKaaqu9OU_5q-6XLc0,2076 +tensorflow/include/absl/profiling/internal/exponential_biased.h,sha256=3XaqRRabbMPtEh8_15Ce6xBuHjrLbMqOIYZ409iPXOg,4915 +tensorflow/include/absl/profiling/internal/sample_recorder.h,sha256=xavDPYAvinKfvyWfch6dAVXbAmKZwxkXwy443qFGDGo,8276 +tensorflow/include/absl/random/bernoulli_distribution.h,sha256=FXJq-250fyibkHzaNkf28_u9_KFVfOkq3oOO1zFo5LE,7582 +tensorflow/include/absl/random/beta_distribution.h,sha256=X13PrbIBcMB7jaE-1F0fl_Z3l1v1iifLEABhbSKBGvY,14648 +tensorflow/include/absl/random/discrete_distribution.h,sha256=5o5tqumf4h7XmILV3yDuIjNefl4Hol4EMcnZx_eudT4,7942 +tensorflow/include/absl/random/distributions.h,sha256=VboRjs2ph7U8Zb74gGoUX7BqJya62IVE_cw5brc1xak,18630 +tensorflow/include/absl/random/exponential_distribution.h,sha256=QVl6M7FNROWfCwDKYvf6St3Ocqv8Oxb6k3KQPsvYkaY,5421 +tensorflow/include/absl/random/gaussian_distribution.h,sha256=HpvLZETNboLm_ZWczaBwb7jU3HmbPS7apYOKk2poFA4,9478 +tensorflow/include/absl/random/internal/distribution_caller.h,sha256=5wCQhbEQTsv6ZqDSWYXzAqd7jdNqruK6ZUZST1blDhM,3590 +tensorflow/include/absl/random/internal/fast_uniform_bits.h,sha256=obX4uz0sKcaVqi4m6ViMR5uaHw0yyVFbL5hhK1O9uRY,10572 +tensorflow/include/absl/random/internal/fastmath.h,sha256=57bd15-qaQWxQzb83dfUi6DFIJEiU_G6v-QI0mmtBmU,1956 +tensorflow/include/absl/random/internal/generate_real.h,sha256=6tTwmmSHc3DWnBNJujLNcfSiYu8gkvCmGyt5nEbgcC0,5647 +tensorflow/include/absl/random/internal/iostream_state_saver.h,sha256=s5Xsb8q1W4ecpQEilkfPdyOg4jQWoLR22kPN_5FP-9U,8063 +tensorflow/include/absl/random/internal/nonsecure_base.h,sha256=J-ZZcXdD73BP0sH-PWaJyDUhFg-CaPXNYpONNIHOFVI,5499 +tensorflow/include/absl/random/internal/pcg_engine.h,sha256=bwjv5nHeBAqKC-ke0KYndR4qL_1QBkm-HuxNKvCKmY8,10067 +tensorflow/include/absl/random/internal/platform.h,sha256=G9Oq2rdbg01qTFtWOPYmSgBMNvA25tQgR4upZJlEROw,6509 +tensorflow/include/absl/random/internal/pool_urbg.h,sha256=vEZhXt85XfgoA2yFDyqA0FjJRBuyL6vYH1yRhDlvVr0,4070 +tensorflow/include/absl/random/internal/randen.h,sha256=5-jBDWXitVMi4jUrH8qr9CnczBYHqCJr1yUFZY6dBg4,3006 +tensorflow/include/absl/random/internal/randen_detect.h,sha256=J0U5eQEbQx93Bi_rgWyQP28Q7UNzkDPKAxz3YqbOPaA,1126 +tensorflow/include/absl/random/internal/randen_engine.h,sha256=2BFYzHobd3hxl-fkKvsjvqtz9dcjZqHAU0rHzXUS2Bo,9768 +tensorflow/include/absl/random/internal/randen_hwaes.h,sha256=WPNsgLFUFmc-UOiIJZwkOg6y2dvOFkdNRCcO5z_oOJs,1891 +tensorflow/include/absl/random/internal/randen_slow.h,sha256=TKPS4Ls_nR-V0ICxsBRM-U1Lo9AHXEH-M0k-Sme5-qk,1306 +tensorflow/include/absl/random/internal/randen_traits.h,sha256=13iTW8EU5fGSp5dnt99-_m7VlX9cmk2zcF5v4YP6J9w,3779 +tensorflow/include/absl/random/internal/salted_seed_seq.h,sha256=iNEhZWr4ASLCy7CRLhg4fipRUmr0sxaKfpPSW_T4LHQ,6049 +tensorflow/include/absl/random/internal/seed_material.h,sha256=bQhUw-WwTlKrZXrQ8XQ8od3esx1-k3tdfl3XkcjM_ZI,3668 +tensorflow/include/absl/random/internal/traits.h,sha256=6nX7Sm0Qf0cWnQoT5OwGxwW56sYvw6HlLhMWIdG258E,3996 +tensorflow/include/absl/random/internal/uniform_helper.h,sha256=19E_FQtJHAqfBx_MqfanjJ_FqjpOqUPWTByWL8t6ybA,9198 +tensorflow/include/absl/random/internal/wide_multiply.h,sha256=O5sKWziL8XjhH3v_YKztzheHNgm6EPpkd6pA8TADo3Q,3009 +tensorflow/include/absl/random/log_uniform_int_distribution.h,sha256=_tnaI5_YAmCqnUVk8KMVYZTo6s3h1mQNVio91REkpyg,8958 +tensorflow/include/absl/random/poisson_distribution.h,sha256=Nkp389F0TLE6CCfJxagR2p0jC2ZFEVeJafzwlGpX-Q8,8875 +tensorflow/include/absl/random/random.h,sha256=Hu06qoiFCY1Y5pgmbxSj91Sqkn0Oafdwci8JIZEqayM,7719 +tensorflow/include/absl/random/seed_gen_exception.h,sha256=4MeCBOIDhmWOpSOhAMWs06TKuve_wVKg_FGnT6yaAc4,1894 +tensorflow/include/absl/random/seed_sequences.h,sha256=It6xc5Ve9MZFsuNiDtNeZd8L6ZDQ1WbAbuk-CLbP5PI,4210 +tensorflow/include/absl/random/uniform_int_distribution.h,sha256=N2YEb0r6PtYohsfIeUf5HKnHg2WzFVXIZfsgM-THwNw,10411 +tensorflow/include/absl/random/uniform_real_distribution.h,sha256=iiI2bjr6qV6He1tBSuUMODqotcwwVsIhur9G7N0HxsQ,7299 +tensorflow/include/absl/random/zipf_distribution.h,sha256=xKrpz2AaFBiST1IEUcgexdOFxbalMIe4_LZ5bpttQa4,9161 +tensorflow/include/absl/status/internal/status_internal.h,sha256=yx6WjTWF1FeS3PX-Q43WQMdxftcQBuzsQBBUhIxk68U,2691 +tensorflow/include/absl/status/internal/statusor_internal.h,sha256=uIbMZO86-HpQ1crlorelTzGjWfK462Skzg5LdRY758g,13574 +tensorflow/include/absl/status/status.h,sha256=NOII6RvJ6qh5lCyFMzurEBjGoOhn6NRhSaCRt32c78I,34412 +tensorflow/include/absl/status/status_payload_printer.h,sha256=SB1I_NIvFoL1mCDgkW0i-SNMNZDo1yzQlpiq8JyH2Io,2221 +tensorflow/include/absl/status/statusor.h,sha256=KU8nAbmCrAjOhbqIZ8_jAM8Q3t_yYawykBYcERMFZZc,27938 +tensorflow/include/absl/strings/ascii.h,sha256=f9q2YBmebb0iFj-MmiozwzyplJD-qlQnB6ctoJuOajg,8591 +tensorflow/include/absl/strings/charconv.h,sha256=FZiEv4BpMtGMt23r4RwGCB2ddc3eQ9pxIlt-IoOAzGM,4963 +tensorflow/include/absl/strings/cord.h,sha256=bDGQ-M3lM-bL9eStYO7LhVJdg9tVmO5fV8OItru0Jfw,60247 +tensorflow/include/absl/strings/cord_analysis.h,sha256=45HDsHIwOXnrGeTWxRx5FZzkoXvpFNJmLukg-Kjxe5A,1623 +tensorflow/include/absl/strings/cord_buffer.h,sha256=-iZDPWUceE7XDqf3IDn7rGNiCmnCY91yVlIdmtJOQ1Q,22875 +tensorflow/include/absl/strings/escaping.h,sha256=G65Se3tkNPmg_hLZ87lGZ0LulzN3o_yiR1DNK1kUIaE,6636 +tensorflow/include/absl/strings/internal/char_map.h,sha256=rPwD6lzATQDZoKNvyWR9AbrLdhrvaAb1xHLm3lCkSfs,5444 +tensorflow/include/absl/strings/internal/charconv_bigint.h,sha256=fJ3AZwltzj48ctzhZDKbVCsBOdU9NjGptd8BEHV1Ohk,14774 +tensorflow/include/absl/strings/internal/charconv_parse.h,sha256=hu9Y0vK8Au8_0d5-3yb_oas9M6ElXr7aBqa7FQU_Wm0,4326 +tensorflow/include/absl/strings/internal/cord_data_edge.h,sha256=pwJCjAJN6gkX39dEp0QoJxbHKhdDJBjxp-XW7YkQ7Ag,2274 +tensorflow/include/absl/strings/internal/cord_internal.h,sha256=2SG_ZUlvWFHpeXv6S-sxyuqR3KInEe31v10ODA5LSnc,32613 +tensorflow/include/absl/strings/internal/cord_rep_btree.h,sha256=Xn2H7BAfT-cGBQPX_uD_EXrC3O5BHnxbigrx5yQ2Z9U,40842 +tensorflow/include/absl/strings/internal/cord_rep_btree_navigator.h,sha256=3Bt5p7So3FwhxGtEJHOvTjWJgBbigipqflpzhgHQv8E,10173 +tensorflow/include/absl/strings/internal/cord_rep_btree_reader.h,sha256=kTJl1Q7f50vW_zIC1z-sTZPcgTqMOhJi1gZGJs2LmMQ,8620 +tensorflow/include/absl/strings/internal/cord_rep_consume.h,sha256=aVQZ6J_AShvJPyNJRlLIRVZ4-4T57DaDH1EzN8CrdnI,2213 +tensorflow/include/absl/strings/internal/cord_rep_crc.h,sha256=q_UgEPLiPKC6JFGlJYfJx3gvVsjPy2vEfMp45zeWMus,3349 +tensorflow/include/absl/strings/internal/cord_rep_flat.h,sha256=-uqUnk485DkiR4p8v1w72swKazYztOYzLfiPBQKk45s,7445 +tensorflow/include/absl/strings/internal/cord_rep_ring.h,sha256=2pBBEcZCEJaueR7dTD_OVuq_mNgFuxauUZQ8QxPtDCY,26183 +tensorflow/include/absl/strings/internal/cord_rep_ring_reader.h,sha256=SxqwVFw_Lu7tfT0yJRMd2IHZq_l6h9z9PePhglP8MPI,4268 +tensorflow/include/absl/strings/internal/cordz_functions.h,sha256=kaweVQsscrl_km9PEbQUmhPJhNvqKa4kgFuWlGc46hY,2611 +tensorflow/include/absl/strings/internal/cordz_handle.h,sha256=hQY9p5zDVelQT6SWpg5fnOvkCfwsobful1gJhDTqMs4,5514 +tensorflow/include/absl/strings/internal/cordz_info.h,sha256=8R1cR0c0MsYct4HdiTGZskKfZcUMSqsFkzlbDP81cg4,12620 +tensorflow/include/absl/strings/internal/cordz_statistics.h,sha256=QQj8Vbg9zOHVJeETWpRtRIimvk0jmcAfONoFqA7PzSE,3451 +tensorflow/include/absl/strings/internal/cordz_update_scope.h,sha256=ZUOdp94Mo8eeie6y6JDksS25cDfWBZc40FUzzKaPq74,2307 +tensorflow/include/absl/strings/internal/cordz_update_tracker.h,sha256=lFYu00muHUjg60ItZGLNoyp4K9NV_LFZRFPE_YTWmvM,3857 +tensorflow/include/absl/strings/internal/damerau_levenshtein_distance.h,sha256=epTH4huzOpXW8PrRFGixWG6hXS_bxCw-DJMyctHSjGM,1271 +tensorflow/include/absl/strings/internal/escaping.h,sha256=QVZzK5KRE-NPPK65GI2ZZQZ4vtiSlA9Fq0kFNBFM3kA,2277 +tensorflow/include/absl/strings/internal/has_absl_stringify.h,sha256=qutUXEBiypFSonuKtPxlQ-wAM7Q1jDiveS3-uac1ROQ,1746 +tensorflow/include/absl/strings/internal/memutil.h,sha256=GC7tieZ7CkOxQ7mGzXGi7AG8g1cqGpCRB0HPvg8qwZk,5753 +tensorflow/include/absl/strings/internal/ostringstream.h,sha256=odTKBVOU6eV7abenCabWvz20rTWAdHrD3Jz02vaDVpQ,3563 +tensorflow/include/absl/strings/internal/resize_uninitialized.h,sha256=j0kIb_ODS9FJMcKqRCHvcPX6V-XkwwbTfy2Gni1xWDY,4426 +tensorflow/include/absl/strings/internal/stl_type_traits.h,sha256=fmjsE1zDLV3Z1UtSn8URH5bv1MRzX_V0bzgWC-y8rCk,11213 +tensorflow/include/absl/strings/internal/str_format/arg.h,sha256=10lpR5OeI4UmcCzbv2nP01FBwJJ9s0fvrXz9oVycAlc,25425 +tensorflow/include/absl/strings/internal/str_format/bind.h,sha256=Wvqd469xyVPr3mSnH0BWlMfdWnZybuTW8LyJMkPit5M,8469 +tensorflow/include/absl/strings/internal/str_format/checker.h,sha256=UhJzHAe9d1fV8q4dO5xZBDDsrXVVvZeK1PTnmgaDoBQ,3175 +tensorflow/include/absl/strings/internal/str_format/constexpr_parser.h,sha256=9oampzql_tiHVUwjgdSjyy-xMHGHPxMTe7bcRkThXWk,13381 +tensorflow/include/absl/strings/internal/str_format/extension.h,sha256=Y5lD2BCUoBBrzvbEcfnOc5mIxmGGyHN2Q3RiVu35f_I,14070 +tensorflow/include/absl/strings/internal/str_format/float_conversion.h,sha256=FG_EFGTpWsx6zk9zwBUCsXXNvj690-GeZjSvRmS1LLA,1343 +tensorflow/include/absl/strings/internal/str_format/output.h,sha256=qMcgBKIoBYXWltvVpfYJVP17IBuHuQcj6TAYiTb7Rlw,2916 +tensorflow/include/absl/strings/internal/str_format/parser.h,sha256=AuDbx-F5uWUxSe9zkZpzR3jA1ppyC0kX0o-f7e2ZRqQ,9842 +tensorflow/include/absl/strings/internal/str_join_internal.h,sha256=JP1Z4pw2gRw36PLSb0Eoz2PEdjOFMeUfykD9Z694-IA,10421 +tensorflow/include/absl/strings/internal/str_split_internal.h,sha256=kK7bmZtILUMU0Z-7B7yelf-1rabP-RjE5nzmMRlpoeI,16087 +tensorflow/include/absl/strings/internal/string_constant.h,sha256=ypy0U0V744PwSwTjTPD-FGL4NUMxsfqhHb9AW9y_1iY,2574 +tensorflow/include/absl/strings/internal/stringify_sink.h,sha256=WFv43IgHm6u3rsqHPfjGHLvVnd1bxeyDVNih_vRFaW8,1526 +tensorflow/include/absl/strings/internal/utf8.h,sha256=Mhg0oPTFBcja_r51QHzil_s8LR5CNjeYLAg1iJaA5DQ,1707 +tensorflow/include/absl/strings/match.h,sha256=QF4di_TCGqXFGke92S-pxWZ6ORbM8VTAqg5KbXPNyVk,3408 +tensorflow/include/absl/strings/numbers.h,sha256=nwG3ZYkbFrlTCqmJXZ1tS2DGPUuV6wnMpfgDhafjhvA,12450 +tensorflow/include/absl/strings/str_cat.h,sha256=76E_FYO3U4w4VVM8V8wJ_AOyrlG-2UQHIMq4D1LVHOs,17641 +tensorflow/include/absl/strings/str_format.h,sha256=66HJbZEyWJUZGoEBEaFrF4QPaYimZQDEPTVaXTNeK8s,35385 +tensorflow/include/absl/strings/str_join.h,sha256=nTV3DX7sNMRZ60Be8ml6SOhKpqwwxQk-hb3nqfa_T74,11209 +tensorflow/include/absl/strings/str_replace.h,sha256=VLaIBjWG3xuKNzqygD4V02gc2r2iCLWb4n13YArfJYU,8368 +tensorflow/include/absl/strings/str_split.h,sha256=YCDIHBuP7HoyXsruJrktd5UhLvfSbNmDjP5exX-IpH0,20339 +tensorflow/include/absl/strings/string_view.h,sha256=Re9Xg1RrNYlN_Xo9EtprKRGA8YNsdaY9M305TUODhho,26895 +tensorflow/include/absl/strings/strip.h,sha256=LUPDSqPrFyCptJkC7mJdU1iyg8BXlSiP_Zy4JjQpxfI,3146 +tensorflow/include/absl/strings/substitute.h,sha256=kgg_j5HTLXm3bWaTtSQk2b-iqCm9ivm7SFXIWG3RO5Y,35356 +tensorflow/include/absl/synchronization/barrier.h,sha256=sutWXd7B6hduXwzSNdqr5PGpYdMGRsht9JOpMyI0sPM,2866 +tensorflow/include/absl/synchronization/blocking_counter.h,sha256=uiCI73jS1Oci6LbZmWHQdaj5oiIgudq7QmbspEHQRYU,3836 +tensorflow/include/absl/synchronization/internal/create_thread_identity.h,sha256=l9S1jcL8Z_-zOIOASZ9CG7vqBw0dn5LCin1g_bUYJ7M,2160 +tensorflow/include/absl/synchronization/internal/futex.h,sha256=VqqnNhtjBFM0SJ9igJ1OtA1ncQHSHOhH_B7prmTahok,4781 +tensorflow/include/absl/synchronization/internal/graphcycles.h,sha256=_x7yq_Sgul-6FL8dKULeI2b8iE-6G0Vy7tnplgIn0hU,5262 +tensorflow/include/absl/synchronization/internal/kernel_timeout.h,sha256=xCp_UEoHuQKmhjNx_91x433ptZ7woDJ0rq-LeU5U9Og,6038 +tensorflow/include/absl/synchronization/internal/per_thread_sem.h,sha256=Gq5n5zywWiExxdVKtcOw0lGBkLpKi86D1KH2hRxhQYU,4489 +tensorflow/include/absl/synchronization/internal/waiter.h,sha256=xgW7xtCdl6ieQHLzfBYIUTgj7opwbJ_HUKrHwoLnonI,5311 +tensorflow/include/absl/synchronization/mutex.h,sha256=hw2-FBq2YO54JzDmO8ZyuBWkX8mhJotS1jHKXGmo6Zw,45258 +tensorflow/include/absl/synchronization/notification.h,sha256=j-HJSenBiZy8kR7badSsrlBOTcRLK5257DFQZYv9mxw,5098 +tensorflow/include/absl/time/civil_time.h,sha256=Ti3GV5WPhWhV5JnUpAWtocQQH8oI2XAu-JcGYSbjpcA,22043 +tensorflow/include/absl/time/clock.h,sha256=OQLXCJJrCnkVsCOsBEu6HgOJ4U93Kaqh6p7dBuSDsZs,2714 +tensorflow/include/absl/time/internal/cctz/include/cctz/civil_time.h,sha256=aPkXnCDUmv8aHn94R2uDFR6SfCpsoRkf3wpINFoVb-I,13616 +tensorflow/include/absl/time/internal/cctz/include/cctz/civil_time_detail.h,sha256=eW6QksBpqNO4jzyqhSqExEk9ejc7K9sSMQ4ecGg_T1E,21679 +tensorflow/include/absl/time/internal/cctz/include/cctz/time_zone.h,sha256=fjlKgkq8sWQbz7v0luMiZSFn5knCNcJN-E6F54h79RU,19669 +tensorflow/include/absl/time/internal/cctz/include/cctz/zone_info_source.h,sha256=fM57fINt6PZmee6wW5ZTd_de1YwbHZN66hl_LlPYTTw,3756 +tensorflow/include/absl/time/internal/cctz/src/time_zone_fixed.h,sha256=SGp3FNYDS4kyxP6v_WoD3FwFtFjuMqku5ii1L6YzGGY,2091 +tensorflow/include/absl/time/internal/cctz/src/time_zone_if.h,sha256=WeJJDEt5g1cwnD1vWJB8EL2g64Eu5RYYowuZAMgBQ7k,2770 +tensorflow/include/absl/time/internal/cctz/src/time_zone_impl.h,sha256=wrYlmCwLwHBRuxWA1pRx5_VimjE9wb2BJguoptmliKA,3344 +tensorflow/include/absl/time/internal/cctz/src/time_zone_info.h,sha256=nBSKv49Tvxmov31TMDgiU1xyXF4-L62tWieWzRJX6xI,5542 +tensorflow/include/absl/time/internal/cctz/src/time_zone_libc.h,sha256=SdK4KRPcyFgmPODlfYMzo9i6VkpFBb04dXVhaL9LLlc,1904 +tensorflow/include/absl/time/internal/cctz/src/time_zone_posix.h,sha256=1tPa6L1DVH6RoWV_eLL3pElbdRFtZgm0B_UFZE1f1xg,4022 +tensorflow/include/absl/time/internal/cctz/src/tzfile.h,sha256=VFB_-uiON7pByBbMve-3T2NLX4rihME_S2DIVNGII10,4118 +tensorflow/include/absl/time/internal/get_current_time_chrono.inc,sha256=QSNcrx8MDGXZfJGmXrY21CiUr8Z0LaqY7hTbgGUGZwY,1007 +tensorflow/include/absl/time/internal/get_current_time_posix.inc,sha256=s1q3YkAY6cQaaRaLwyVO6cuxYWSgYP9MCLx_QaoBEsQ,589 +tensorflow/include/absl/time/time.h,sha256=s1EPb8mtgCK8MMtR7ry8uURVC2BdjeMlIKaYdeGexr4,68122 +tensorflow/include/absl/types/bad_optional_access.h,sha256=mGynl8bC6e1oY3HNcy0J05XJ4OtBIzYq2goD_odBh8c,2237 +tensorflow/include/absl/types/bad_variant_access.h,sha256=uorWuKE9sSrYv1U-vgq-_Ig1hLDPO1c-z4ZwNtTL_tQ,2454 +tensorflow/include/absl/types/compare.h,sha256=yH95Rg38fustH2jL9qgDHib9Tg06aZd4NQHzfgd2O4o,23469 +tensorflow/include/absl/types/internal/optional.h,sha256=bPOi2QkexwLojhx4f6t_Y0f35AUSArj_WrwuLIYgPjY,13772 +tensorflow/include/absl/types/internal/span.h,sha256=VUecum5u09tgAfDPG_znR1T58SrpeA21-nH1RMNAp1Q,4570 +tensorflow/include/absl/types/internal/variant.h,sha256=RcAVPBWsK0Ma5epyKsAJL-H7dIBckmewDovl1PuT8Qs,56218 +tensorflow/include/absl/types/optional.h,sha256=iAjvVMeVoQQSDCy5JZ4_7BXnQhXk2LAWc5yzR6gWc7w,28748 +tensorflow/include/absl/types/span.h,sha256=sLnJPhBP6mgisUsXr4OovBegE8Ogdrnainhb6XR_4zI,26976 +tensorflow/include/absl/types/variant.h,sha256=DYmz9S0PHiKjMedO7ZsGCTIdvvxX5swa7B0zdF6l_Pw,34055 +tensorflow/include/absl/utility/utility.h,sha256=4KrL0ZgquTBAZNlW5pYOpe5VsWKru98MAno_OzI_ApI,11643 +tensorflow/include/external/absl_py/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358 +tensorflow/include/external/boringssl/src/crypto/asn1/internal.h,sha256=oRYSjUweU0arfvO3GiJeBUXH5_3QODHd9rKhczkiWso,11811 +tensorflow/include/external/boringssl/src/crypto/bio/internal.h,sha256=BPyNjIxHnSoXZCRYs_DW86wAuGvnsDnoiJVgdQEee90,4821 +tensorflow/include/external/boringssl/src/crypto/bytestring/internal.h,sha256=rESXvbraKs2Ncfj0T6eNAB60X0B-VMHb18TO3_uAcyE,4429 +tensorflow/include/external/boringssl/src/crypto/chacha/internal.h,sha256=k1hjPjXKagHTYKSZlwm4Vmu-aJkkunhniZzJebCWZ0Q,1619 +tensorflow/include/external/boringssl/src/crypto/cipher_extra/internal.h,sha256=PFrcdXxfTOnng16m_Pv_M6j6fGBN0Pzge5TZeM9tQHY,10170 +tensorflow/include/external/boringssl/src/crypto/conf/conf_def.h,sha256=QaD1yD_OVaouJFT2gAJ91sauMOvWrhSt2IkwAVezXrc,6426 +tensorflow/include/external/boringssl/src/crypto/conf/internal.h,sha256=GK_KZhB90irbiPxfWHezYNyotzS-9c2m-BntMIpkOYE,1728 +tensorflow/include/external/boringssl/src/crypto/cpu_arm_linux.h,sha256=868IeShqHS1Dhmly5XEDMBTNhrodSFB0MBkTOdFEGH8,6177 +tensorflow/include/external/boringssl/src/crypto/curve25519/curve25519_tables.h,sha256=qrwSgetiLUM-8YaaJVDW81orI0fF-2e6FRKwwXvMk7E,276080 +tensorflow/include/external/boringssl/src/crypto/curve25519/internal.h,sha256=DT1QNel34W9O2316yPqkbVei8GXPreoBn-GN3tKhho4,4444 +tensorflow/include/external/boringssl/src/crypto/des/internal.h,sha256=0bhBRGgXmnA3Qy-kBtXJMenfKRypwbyIQ6YP_5wxS74,10740 +tensorflow/include/external/boringssl/src/crypto/dsa/internal.h,sha256=aAERQEd_wbdp_zqGTYWWTEDFmewXg7_KANTGZw4rFBk,1174 +tensorflow/include/external/boringssl/src/crypto/ec_extra/internal.h,sha256=HskXQ_M3IK0UY9Gke6j76x4Sgpzhx_tulL3JMw7Cmd8,3111 +tensorflow/include/external/boringssl/src/crypto/err/internal.h,sha256=GiKbIQCK3AyOk610hZY_V5PX8l7rjq7lBXwIJ2hxI90,1981 +tensorflow/include/external/boringssl/src/crypto/evp/internal.h,sha256=oC99cNFlLKU0V_hO2Wm6Qu2kmXk35puS316VRzrCbJA,12242 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/aes/aes.c,sha256=6SvgS2liQqSJrSUi81DmE7GiJDxf35XE2A1Qw-evvzI,4118 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/aes/aes_nohw.c,sha256=aUTMHK2F4ejppW2n9nwiOZ0FZddgYeGtJwNNkNHhGJ0,50855 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/aes/internal.h,sha256=Z9jrqI1UAdGa2TQQMNBpQI2uNJw6E-UKvlMqgxdo6ys,8087 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/aes/key_wrap.c,sha256=ay33mWdBeKs8XTbZ3lk0IPrbpr0ak-auUS_n1rpmgXA,7980 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/aes/mode_wrappers.c,sha256=J1gHqqLhpY8QswVXlGhamttzWHTLhHK0HTZ17IMYS6Y,5095 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/bn/add.c,sha256=vhVDuN1AkEejn5lPSg8tcm0Hpc4a9HoktYBTIHiNyzs,7655 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/bn/asm/x86_64-gcc.c,sha256=mwpF1u2Wgdzka0cD7bzmNM3VJVMvpk01wrnYjARQNyI,16088 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/bn/bn.c,sha256=OQrp9cyk4V4PX1QH1aM289pido-zE2u6T7F2L5taPHk,10913 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/bn/bytes.c,sha256=PxBGvb1ddXt1KfhXPFyycWx1St7FRLIJCgttR3PkFuM,8192 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/bn/cmp.c,sha256=lngAoP1pcZE9LSbckIEuI6JQnrO9P_a-9NcF-VbDK-c,6699 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/bn/ctx.c,sha256=0lsbyhwn0r02NbOkGvZVt7DLujALC-XXBdcdGaxpgFs,7208 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/bn/div.c,sha256=C_OmFit3rbOtczvzky1C5rjRkyuF1tOpIQQxo0sQd2w,26466 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/bn/div_extra.c,sha256=MkCJ_OeHvKrsetHG_DhKR3jBUp_DxNAmzs3tkl-Z860,3187 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/bn/exponentiation.c,sha256=x9ygSFLwZWhbC_RrttDtaHHvRbdXclZ9ksZ_k4-KmQw,37489 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/bn/gcd.c,sha256=xgJ5B17ItFIbmhF26px3SRbgpU3atP5TlERANcc3VZs,12050 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/bn/gcd_extra.c,sha256=d-SWezv7m0_P1P_MymDKVvfZhdCfBx2PFRr0tmmdtsg,11361 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/bn/generic.c,sha256=reCr4qTMvs84cDedJKUveumAs0KHQOWBn51RAISJxcc,18787 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/bn/internal.h,sha256=KMVlfcxm418hWF3UDqueopfambfcDAgHAyVvTmLGehc,36646 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/bn/jacobi.c,sha256=vIKVDeBJQPzlBh8p54KY1fqCVfd3FaX9glevBPM43s4,4618 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/bn/montgomery.c,sha256=tJUc3fK9_MOE20nqdBhTFgCt_gkZYUE_owRyeCPc55Y,16682 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/bn/montgomery_inv.c,sha256=brWvYNGuuuGppZlXc_BTNiIO3KJQRMRrrdk2RpIb_N8,7075 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/bn/mul.c,sha256=kaRSAfnJr4seypGVcm77AM-si6_FbkT7aZ5DK4mU9Io,23683 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/bn/prime.c,sha256=tytC2_wT2ecRXkOBYseoBLaDKlcqGP007qVc-ZzNJb8,37559 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/bn/random.c,sha256=LVVMEROBTK0IouEXELNg6sKlk89jqPKsLp8lAc-IHP8,13108 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/bn/rsaz_exp.c,sha256=UkOyb8q9vw9LKyU9IvQlAxJhBsYG00v3l7e0ZzeX-TU,4842 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/bn/rsaz_exp.h,sha256=nP27AwdwZLPnVHp_t7k86WfajG1nj3QL4UTKIXZk9C4,4351 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/bn/shift.c,sha256=EHqU0bECSTaqdzidJHMtATzHLjVsKDMoFUAd_ih3TSc,10149 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/bn/sqrt.c,sha256=oOu70jkCZDokTNq2cw89l3_woTHy1w44zPGpRcDW3Jg,12753 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/cipher/aead.c,sha256=u0aFqgSSKfRqN6QDFwnhTUnZFxwGfXjdjPi5K0JOkPE,9055 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/cipher/cipher.c,sha256=SFWTnninX8LsoYty3VE_FLgrAz8z8wP4osQIC_AZoAU,19644 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/cipher/e_aes.c,sha256=gpb1srVxDbmqHbmonGN-l1mD5Hubcf5LLueeaoQua9w,45321 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/cipher/e_aesccm.c,sha256=46xGW1qYW4yImKyTCopJjo_Arzc5UC8lyYVKSBGTzCY,15575 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/cipher/internal.h,sha256=GKY5501ImcwMSzaVkPaqUTA-YzBxuhtAg51qF7DO-Aw,7127 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/cmac/cmac.c,sha256=wWRgavisLswLOFdATtlVf3G9MRNLiq-LKwEltuoVKfw,10167 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/delocate.h,sha256=A4nI8IvpPkiqLMZMH95I6wWckueLoPscAgA_vVmx85I,4433 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/dh/check.c,sha256=CHCR7vXruGClaB4BGIR3UozZDXDHCgUr6aJDwHMg02o,6734 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/dh/dh.c,sha256=EnI1WBXuH6sBYf_S4rtv3cUJx01ANMeN9UN5hLyg3IE,13229 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/dh/internal.h,sha256=AIzh9u-0kB3oAWxJqCc9n4riO6nwhLAPmWtC44kliaA,1805 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/digest/digest.c,sha256=qRZg8H506j4b1YjtrqVk4WU6ILdelgAnHClm_VTez0s,8632 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/digest/digests.c,sha256=sCWs10Cg68-WNHSgdnepH0TkP07jQDVNRjPrQJ-VERc,9186 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/digest/internal.h,sha256=VPTmwIMWxkls2A3PEnj_88QFBrz62jo5mAEghkIDSuk,4701 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/digest/md32_common.h,sha256=w9PXFF4mYTcH4eoeczQTR5OLGSQxwmcmehcn_5mcReI,7259 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/digestsign/digestsign.c,sha256=f-KYX1ssHfK8wyCnwXQl42xsjKl1nk7xRU3KG9aq7EE,8326 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/ec/ec.c,sha256=tiVPsi1GJfCGA81_UTbcTYA-gIrD9qmY86VBaaEbmtc,43437 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/ec/ec_key.c,sha256=fsWPJdJ1KasqQb6nsNt8U1mryAFeidFlLssbYU2ElmA,15284 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/ec/ec_montgomery.c,sha256=DUSJshzomnadUNI-C8WHD2T59NkQPyt97mlYI7gfw_Q,19605 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/ec/felem.c,sha256=0p2ih8tzfZAg7ZQrAO4jzE799q8__F4VtEuV14HcrPU,3510 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/ec/internal.h,sha256=uH5yWBCX_fmrDf73L40JJ-yZ4cYEK4HRWYW06ZNt60M,37131 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/ec/oct.c,sha256=fjXbo4S4EC9NuNTWU90VoKF6ssGjQjlePWAvo5fxrnc,11487 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/ec/p224-64.c,sha256=KC49ZqKFif_G9gkE257jYiw3rSxxgAp45Lf1mHLiyTc,43399 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/ec/p256-nistz-table.h,sha256=BN5wqssbB5q-NoEl-9aD5NrjLDyHfzMYd0KtQGiBClI,643054 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/ec/p256-nistz.c,sha256=W34eWGa_xRwptjE0rHtR3rfSy1VzlOZcUa10ca0-4Ek,23343 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/ec/p256-nistz.h,sha256=9EH1rl4PI8vu5Bn8piIjIsTs34tm0Lk-SE-eQJ0wYcc,5295 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/ec/p256.c,sha256=tp0Hbkr7_qzoC3yKDIkRmKjcq57VTddZKaIJONly9bc,27634 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/ec/p256_table.h,sha256=3VfQnhWDPY5gsn3sg5O_oo-cImpRgjr5KfPwyOQh_oc,14857 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/ec/scalar.c,sha256=3r0_FEF0SfxSdZUmRDq2weulk01K5EaBL76rla8elKU,6365 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/ec/simple.c,sha256=HFptdH2bbJdoAD8TnzGyXSUTSjxcd7_fXj4mzdDGW3k,13307 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/ec/simple_mul.c,sha256=VlanQRxs2wHKT1KLHAqFD6cieImcDBbN7oWpVOxLxio,10462 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/ec/util.c,sha256=8pzdxkcOcyLK-QT0GV9Y0k9cTvMfRJs-08nZimbWGdg,11411 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/ec/wnaf.c,sha256=RQSK_AY4jDOuorTrGxbXQS0ntcsaU1jZRUk3nm8sd3Y,9774 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/ecdh/ecdh.c,sha256=dFxdEbXzOb48XGyAA6ZCfAgW9K_pN0tS3Cvx-3SXbZ8,4892 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/ecdsa/ecdsa.c,sha256=C1pSZ4FIjprYMLREeP5FcflmUrnMIshaVata1fAFmXQ,11993 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/ecdsa/internal.h,sha256=xyM1DNEAXbyXQFF5126ZUju0c_-R-pj6pYqIvSnqYxU,1964 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/hmac/hmac.c,sha256=TIx6VsE-DKmSeaNbYzph0JmTED41AwA0Pn15FDmEO6g,8627 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/md4/md4.c,sha256=EmnUPC6hVvn65uFyRTTfIR42wqeAErLENT88cBn68Ps,8517 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/md5/internal.h,sha256=kx0xrwZmoVca4FFBZZF-9LmzBDURxmVO2dgPJuZ2WBs,1251 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/md5/md5.c,sha256=TbjZDmVebz94RRjLR_xYMKerZI2neCzMuUvYhJgquDs,10174 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/modes/cbc.c,sha256=PAwVDNQPPLMEQ1V1m-_CJZfmwWEG7qzX8V8XOrHH_Gw,5734 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/modes/cfb.c,sha256=_Z4omnDq5rklWsrVAasTk__pMDvWLr59VmZ9ePML6Xo,6628 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/modes/ctr.c,sha256=bSePCcedSaY9wGgipAkUBCj1BPE-mIgtrDsm_IH-x3k,6610 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/modes/gcm.c,sha256=IvuSiDyWPmXEfFoZKDhBSZ130Q3A2Zkj9Q6O_HZeNaE,21858 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/modes/gcm_nohw.c,sha256=rUivP1alLmKf2HSieVWT7iD1azBQfHBWKhAQs64GgTQ,11181 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/modes/internal.h,sha256=UayLHySdrIQC35bDXxZp6AltfsRkijIjdWfJoOE6GX4,18306 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/modes/ofb.c,sha256=f-f7cZ2FqK_VCgGB2O_QA-Q1G5uDQX_kymUFxnQu2HM,3510 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/modes/polyval.c,sha256=HY96K9ARIrdI8f0Yz2QUmHT-Hv-T-c0WC7srgu69MaY,2948 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/rand/ctrdrbg.c,sha256=7rS8IAdXxEVCtXfSZXk_TxGWJYPbg68orcm0hO0f3zs,6936 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/rand/fork_detect.c,sha256=TKHql1tpcX5ZnowzM648C6xncbfzvNeFyc6nX6vaVJ8,4482 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/rand/fork_detect.h,sha256=sLt1bKt6ukvPRK17vGX8oXChdLww12ff59v2Qre2AD0,2115 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/rand/getrandom_fillin.h,sha256=Zon03p25QvbdhhwNrE6Lb5jehgaQemT9qJbyfTmNXX4,1826 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/rand/internal.h,sha256=8zxDCRv_3HVrv3m6Oh1UVG3n4rEb58afENjy6GpDpuc,5827 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/rand/rand.c,sha256=BqpMdoTNWtgqPuZFdyj6jXaLjb6Ys0-K7uFTgZS5FwQ,17184 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/rand/urandom.c,sha256=3k8aRXm7ao4dfNGbjV25_8VlViTnA_1wtPpVRYz8p7o,10622 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/rsa/blinding.c,sha256=VsPKL5fJQOi2q4OATmFjBN9KDlMG-4455jx7gNdqypo,9775 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/rsa/internal.h,sha256=Y18GmVgZ1-antQ24o-crr4UyQwCkeecen1y2OMn8jmg,6970 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/rsa/padding.c,sha256=wxLTtnNP-E_Dv-pW7v4n265lvHuhq8NNB144QasFJBw,20235 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/rsa/rsa.c,sha256=jMnGx7sr7lP9weT0zf_hcLsLDaFauuz3gX7u_ev97YE,29031 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/rsa/rsa_impl.c,sha256=djGLwP0ZNLkcXQ_7MZcQ7R-FCIHq5TV8DGkKd0lpRQU,47219 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/self_check/fips.c,sha256=4O6APpo91pbNJ2QpPBARbWcfKLoWk2Vq-FT-0pwor1I,3027 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/self_check/self_check.c,sha256=qvRTc_sVYdYsCbshBe1Nwd9sq_ISgtoaRb4nAoyN6Mo,41644 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/service_indicator/internal.h,sha256=Fae4XUDSS_xAKfc5XjbHU75vTCwgs6rAYTzNaXYZ6E0,3811 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/service_indicator/service_indicator.c,sha256=j1FzYkEVEdRTVtnT642cYd2K_G5kiZ_toMi1qFf6KKs,10645 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/sha/internal.h,sha256=vL1n1zzLA_-He48N9jdXH98ioqD1TFR_xL4B-t_9j5c,1586 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/sha/sha1.c,sha256=57VzBJlcoaJdFGlW2ijfYawfsJvdMNYy9d5VMUQxZSE,15123 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/sha/sha256.c,sha256=RQXHyOgBBj9qF_8d1sKVvhP9iwiPuGyZx0CkX1yqyu0,12030 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/sha/sha512.c,sha256=MRzbnj33tBwx2o9SHH_Q1gSSZV5EZZHbXQWW-kfgDXQ,17776 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/tls/internal.h,sha256=gGqHvD9caZMGAyRN5R2t7YK4EQBcY74sXjEiDBFjE4A,1621 +tensorflow/include/external/boringssl/src/crypto/fipsmodule/tls/kdf.c,sha256=ecT0O7lsQmQlzU7KAGYXUXFIlzj69dPLgJy3P7c_UVA,6385 +tensorflow/include/external/boringssl/src/crypto/hrss/internal.h,sha256=5jySe2Uu5dNnp0QCltpCg_F5ka0oPR5E634UQS6lH_0,2458 +tensorflow/include/external/boringssl/src/crypto/internal.h,sha256=NBhtydOoXjcGO-_6xE61NkXzORqpNZ9tdTNeHX9ary0,45835 +tensorflow/include/external/boringssl/src/crypto/lhash/internal.h,sha256=eh-intprFNlE046apMYRf_s9yIH3s_joPa_7-vglrVM,16009 +tensorflow/include/external/boringssl/src/crypto/obj/obj_dat.h,sha256=TTn06dz78lM8bIR8TYG320LCcQu0ogE0xiYhDwCYxLA,295919 +tensorflow/include/external/boringssl/src/crypto/pkcs7/internal.h,sha256=Wfwgglk79c8jbEqRvUSzArU_TMlrWATpKj3nSvyctWk,2555 +tensorflow/include/external/boringssl/src/crypto/pkcs8/internal.h,sha256=BWJ1WlSGTfCOvaBGjCYcmA5gVfwDqUE53fnHdDqb9Kw,5918 +tensorflow/include/external/boringssl/src/crypto/poly1305/internal.h,sha256=v13NarOjYf5lmAg8RHTytTy6xgiaNEmQyVfnIHC0bXI,1453 +tensorflow/include/external/boringssl/src/crypto/pool/internal.h,sha256=3OhsrW_ca73JOBNdApNUJe-kd7z9oZ4Z0VUuMSeg6_o,1371 +tensorflow/include/external/boringssl/src/crypto/trust_token/internal.h,sha256=xU_Vf_-Y1OFjUxL20qYToex5pxzlMPf64HaH13hlETA,14673 +tensorflow/include/external/boringssl/src/crypto/x509/internal.h,sha256=It0SCJKfaswGdSL6kKQdNxtgjaIj0mfElOs99EKWCt4,14807 +tensorflow/include/external/boringssl/src/crypto/x509v3/ext_dat.h,sha256=d3RWqxIMqzLiNz_gJXpg5bcUHwGEsAx3rlaeDbhR_qk,4814 +tensorflow/include/external/boringssl/src/crypto/x509v3/internal.h,sha256=J7_Z6jS3Uz2ZLAQt2QWV3JrVPeHQ68YFYzDjkvoKjFA,8886 +tensorflow/include/external/boringssl/src/include/openssl/aead.h,sha256=V70Exp8y2Y_ZP8XPcV8UW3ZdpVWLOSKTdKqO6yKRxiU,22464 +tensorflow/include/external/boringssl/src/include/openssl/aes.h,sha256=69l9NSOQ6PUZmFNDBGng_awWAfTqwzpJRgIBxtohay4,9801 +tensorflow/include/external/boringssl/src/include/openssl/arm_arch.h,sha256=x1WechDPLbAvD7RzNuCc8W0ZVPS0pg4JLm_of7rl10M,8806 +tensorflow/include/external/boringssl/src/include/openssl/asn1.h,sha256=D4TuiUeV8gj08RKtTolsxirLH0CTB3u6MsOs7tP9w-8,99609 +tensorflow/include/external/boringssl/src/include/openssl/asn1_mac.h,sha256=NN9sITgTEHrsf0tocv6m8YErYI6B7V6fO842gmF41-g,892 +tensorflow/include/external/boringssl/src/include/openssl/asn1t.h,sha256=nU78YojQeRRx1K8ltJAykkEerUCeouRY06T-Em2fTY4,21018 +tensorflow/include/external/boringssl/src/include/openssl/base.h,sha256=OHp0zrQ3t0Vtv8rYsXk8T7JW_0VN8DwN5zFBWHzzCSo,22314 +tensorflow/include/external/boringssl/src/include/openssl/base64.h,sha256=6nhnqwA6p8hKGregU3XiUfOfSnrsqFvsKUcT_tgOT3s,8979 +tensorflow/include/external/boringssl/src/include/openssl/bio.h,sha256=n3VPtIHwr6lD8aoZUwyP9UU1a1R8ubcXEQp4Q84wjEc,39011 +tensorflow/include/external/boringssl/src/include/openssl/blake2.h,sha256=yo5SXih3gNy56odN134fgWTOO4zV7YnxH9sV10OslgU,2150 +tensorflow/include/external/boringssl/src/include/openssl/blowfish.h,sha256=906WLzdpLezu59kZz4bfvWFMgssncOSxhwbgsoERSZY,4091 +tensorflow/include/external/boringssl/src/include/openssl/bn.h,sha256=cqreUDdPRMq2BLr3UFTiuxuxM4G6Xc8koaKIF1PjEa4,49417 +tensorflow/include/external/boringssl/src/include/openssl/buf.h,sha256=bj4y2RuX7LwgS70O1MQO-NO6roKdf361Fud6ks7xehg,5483 +tensorflow/include/external/boringssl/src/include/openssl/buffer.h,sha256=nT6msu860Z3QOUsOj4yrQ1RFWcyVY91cXq3xgxAkBho,891 +tensorflow/include/external/boringssl/src/include/openssl/bytestring.h,sha256=Kvo630_x3r20r71QpxE379pGUYQzFzXoPcycln5cioo,30875 +tensorflow/include/external/boringssl/src/include/openssl/cast.h,sha256=qNWiolj6ql-eNzs_J2yzCI5VPTtQV-OvO6y1CzbZKU8,4394 +tensorflow/include/external/boringssl/src/include/openssl/chacha.h,sha256=Pc60Z_a6RzF-ar1y6C-R-pMWdkm9D-VsnhUsJ0rI50I,1530 +tensorflow/include/external/boringssl/src/include/openssl/cipher.h,sha256=LU7P5aGvbcsP6_0TJI0p1CrG5Q-EJCwqeMzbh3F-tDQ,28413 +tensorflow/include/external/boringssl/src/include/openssl/cmac.h,sha256=rgHJcDpSANtzxQ61OXv2R_fnMg5gB0_KOiF0EDAbeqI,3150 +tensorflow/include/external/boringssl/src/include/openssl/conf.h,sha256=yQIaV5LWc0A1TIKnFW_lomqfC39xZvZgJBKH-Efoicc,6465 +tensorflow/include/external/boringssl/src/include/openssl/cpu.h,sha256=kufcct2aloGLTEFI5X2F1HyyvHmFbN_YPd2ssgAs-FQ,911 +tensorflow/include/external/boringssl/src/include/openssl/crypto.h,sha256=Phq1yWFSIbIwR4Nztl66lDMUO-q8SfSpjntVf9QlE6k,7676 +tensorflow/include/external/boringssl/src/include/openssl/ctrdrbg.h,sha256=tf_dq7asYppopqOkD1f_etkFhMYoTY0fvFjuW604YLM,3067 +tensorflow/include/external/boringssl/src/include/openssl/curve25519.h,sha256=XA-50MIu7LHZmoSJ_qhXSIH_Z8hwUF42ze9irLxVbNA,8428 +tensorflow/include/external/boringssl/src/include/openssl/des.h,sha256=oJ7PP955zXBD4z77U4RcNlKSmFMoVdYe-VcyRWnUkZs,8363 +tensorflow/include/external/boringssl/src/include/openssl/dh.h,sha256=ldYierLDqRFv5yVvaplbGJEqgHmKKit_UhcE0D16btg,15670 +tensorflow/include/external/boringssl/src/include/openssl/digest.h,sha256=FwUQ_3L6bOh3LgCdFAE9RNzFvPsYrnlhtXTlUgVdDAg,14760 +tensorflow/include/external/boringssl/src/include/openssl/dsa.h,sha256=5LMIN8WYNCUATnnh-Dk-T6SU8WbixhUC4bqfsH6--5g,18406 +tensorflow/include/external/boringssl/src/include/openssl/dtls1.h,sha256=_1qmtQAe6YiG2bX-HeQdKrTOYgLBxP5N6Xej2wAvKys,873 +tensorflow/include/external/boringssl/src/include/openssl/e_os2.h,sha256=1gdA_lVIZ1SU-rT7vfvAENBav2zfFz01ZRNPVOh-h-o,900 +tensorflow/include/external/boringssl/src/include/openssl/ec.h,sha256=4IsGQkAnSSneWZWyxeNzrJPZlJiDOE7bkYKMRiYw-B4,21718 +tensorflow/include/external/boringssl/src/include/openssl/ec_key.h,sha256=4oonCNDub3ecx0QYMAXU2hEKFxw_77sLvt2NPC2Ce74,17027 +tensorflow/include/external/boringssl/src/include/openssl/ecdh.h,sha256=CQBrYNhRy310agK2NCSfcUeQQmgVhJ_xA_6p4ObMxys,5063 +tensorflow/include/external/boringssl/src/include/openssl/ecdsa.h,sha256=TzKzI4T4xfFSFHI8Usz87gOGsmPEtXg_bRAOasAX4r0,9897 +tensorflow/include/external/boringssl/src/include/openssl/engine.h,sha256=JBLnt7Rs_2SjDYopANr0Oy6ZlDoNnriPx09aEF4GaBk,3737 +tensorflow/include/external/boringssl/src/include/openssl/err.h,sha256=Z5T6ATn_6z-_gYBwfc-TmUgdmBuk0Su8vwS2M-NC4gQ,20564 +tensorflow/include/external/boringssl/src/include/openssl/evp.h,sha256=sDFSokAGsNiLYUbJSVBP0kP4D_36MWwO6Bj5qhGZ7to,50636 +tensorflow/include/external/boringssl/src/include/openssl/evp_errors.h,sha256=0lQ3XpBwcVYFERWCTh4NzzaxLrq-c1fIzqHTxSS3-S0,4719 +tensorflow/include/external/boringssl/src/include/openssl/ex_data.h,sha256=Jju-2jKO6meiijIvKFwF6yVGF3mEkVfmYY32X_znwXU,9143 +tensorflow/include/external/boringssl/src/include/openssl/hkdf.h,sha256=DKvVs4wH05g8fLIgS0j7DOSS6pOQJVX93VwTGoECD0c,2886 +tensorflow/include/external/boringssl/src/include/openssl/hmac.h,sha256=hc5zbGaEvGVHJ6na0n_-5YuSGvvdo_yXGOHFO4Jr5yc,7977 +tensorflow/include/external/boringssl/src/include/openssl/hpke.h,sha256=NZAUW1GC8m6YIWzzAUl8tY4B-5xw1wWhkf67j9oCZFg,16833 +tensorflow/include/external/boringssl/src/include/openssl/hrss.h,sha256=lMdp8La5zjyfTBCsxExOVLpgt6iFWW9dSIbULnuFosA,4488 +tensorflow/include/external/boringssl/src/include/openssl/is_boringssl.h,sha256=d2LyQCI9kw6zNyr--2vN7bpRgVRwYmKeNyAbok-r_LM,863 +tensorflow/include/external/boringssl/src/include/openssl/kdf.h,sha256=F0Acu_yumJUwH75YJcolqHHr8mKz7CEo4K-bkM8nc38,4164 +tensorflow/include/external/boringssl/src/include/openssl/lhash.h,sha256=hgXN79sa1RLeITmUguYooLOS58v_-F0LqjL7b9hqcbE,3778 +tensorflow/include/external/boringssl/src/include/openssl/md4.h,sha256=AybMt9aI1uG4HyM8OX3CuowXuWayjuTXX0VhZcoZnrI,4659 +tensorflow/include/external/boringssl/src/include/openssl/md5.h,sha256=WHGtAjwZepR9LPjRzWcMycXb4TytZDgotdGP4Qb0a-M,4660 +tensorflow/include/external/boringssl/src/include/openssl/mem.h,sha256=RlelzKpv0dplY08I-gfHOnS-bPmA3LkzT1CrWtZEU4Y,11053 +tensorflow/include/external/boringssl/src/include/openssl/nid.h,sha256=AoI00YmvS72pnvQVODyClgdbVn7uvlM8-mIYpTXHPiw,148873 +tensorflow/include/external/boringssl/src/include/openssl/obj.h,sha256=GvGrpZkdElJBLyMHQ3D7B_aIScTuEQRUrZ-I43Ukwlk,11324 +tensorflow/include/external/boringssl/src/include/openssl/obj_mac.h,sha256=dWeYM8pENFG8ZkDpx-wea1RHDTd2V1CHpGYCUul_ChM,891 +tensorflow/include/external/boringssl/src/include/openssl/objects.h,sha256=4Pmik-8i6-IL3iWs1LwAjgzg8Cz6sN4CojBX2mu1G5U,891 +tensorflow/include/external/boringssl/src/include/openssl/opensslconf.h,sha256=8ZLeyW44qZel2F1wSIfebULuIX6L69efGkVb9bN9wM4,2197 +tensorflow/include/external/boringssl/src/include/openssl/opensslv.h,sha256=i2EpstyNKKty9KnWMss25ms1Z2c9kT4dM4gYm8gSUIE,894 +tensorflow/include/external/boringssl/src/include/openssl/ossl_typ.h,sha256=F4-9CPGY0XNfJTru7jVSefkeQW2Wnni0Sfn50_w5PJc,892 +tensorflow/include/external/boringssl/src/include/openssl/pem.h,sha256=rjHq2XDp1IYSX_Y9IYTHQHURwear61zFTZ8VOkCkVS4,23132 +tensorflow/include/external/boringssl/src/include/openssl/pkcs12.h,sha256=BDLw3_mr0rN__I9fwElAy7WIrw5DEhLWppWFOwv7ED0,893 +tensorflow/include/external/boringssl/src/include/openssl/pkcs7.h,sha256=ptmHi0SmdPA4aduHs2vThzGGq7-3THE828YpgxAv-Cs,9225 +tensorflow/include/external/boringssl/src/include/openssl/pkcs8.h,sha256=JZ5rVNkIy2U364tjhml_fy775YxAQjTeEBXzS9iaIwE,13730 +tensorflow/include/external/boringssl/src/include/openssl/poly1305.h,sha256=WnmpA4wpdteoLxo-bhjuMjmInxpqo6Rj4XWkVkWn68Y,1965 +tensorflow/include/external/boringssl/src/include/openssl/pool.h,sha256=sKmxh_rAJNGBa_mfFoIcFz0w9mLdB1zOTDDhvwavgjQ,4225 +tensorflow/include/external/boringssl/src/include/openssl/rand.h,sha256=GGIFdEO9Nl5vBS5LegPKfwpE1URbtWAjLBsa64AEK10,4598 +tensorflow/include/external/boringssl/src/include/openssl/rc4.h,sha256=-dXOiNWrYH8-JPexbQnpzyJYBqKAqS6A2BYB2MbrAuI,4020 +tensorflow/include/external/boringssl/src/include/openssl/ripemd.h,sha256=EOaPMBO9NCe1UM3Z0Lm7KuFh_CqpDH562JDKJMxHAzo,4854 +tensorflow/include/external/boringssl/src/include/openssl/rsa.h,sha256=OJ5tDpRzXX1TSEY8QFrtp0rgvXNba4-vwKq_4k-_f_U,38921 +tensorflow/include/external/boringssl/src/include/openssl/safestack.h,sha256=UOJIKx_0YtdmoFNpUoYn8ZB-bZ-tgVp5YJNnM1k0DQo,873 +tensorflow/include/external/boringssl/src/include/openssl/service_indicator.h,sha256=eG56OQYR1gpTFE0mO6YTDuxYc0ThFCbjf-4Wg95wXuc,3569 +tensorflow/include/external/boringssl/src/include/openssl/sha.h,sha256=_-uAg0wYELf5PTLzC-fB1IVfLFcADHAUnZLD8MkKVUU,11659 +tensorflow/include/external/boringssl/src/include/openssl/siphash.h,sha256=eze9mXjAMzVPC4AHOzCoJR_oW_3Nm-3Id7w6vkEapL8,1284 +tensorflow/include/external/boringssl/src/include/openssl/span.h,sha256=QXDD342aH5WI4AKuCCOTXXbyTlEZdxgJsZyzpy4dm9k,6474 +tensorflow/include/external/boringssl/src/include/openssl/srtp.h,sha256=fgcbjBm68uI1g4HoNSSoLbbb59xGGrdurqznJ5xl4HQ,891 +tensorflow/include/external/boringssl/src/include/openssl/ssl.h,sha256=-tGNdn0pf_hfFho3wBQ3_44t8QL7Ln6_byzCyaZ01_0,278385 +tensorflow/include/external/boringssl/src/include/openssl/ssl3.h,sha256=9c-xkX3F4tRmJNT5nHjgs0bp3zhwt3k6Qpt-TtWNGfQ,13944 +tensorflow/include/external/boringssl/src/include/openssl/stack.h,sha256=MRLMcD7IZQka8OsLdJp4fPjzicXY2eZfHOjgW--DB3s,32316 +tensorflow/include/external/boringssl/src/include/openssl/thread.h,sha256=GPg-9D0fsR83O6Dz_FO2qhUpsWC0krBsUBm9egAPI_w,8188 +tensorflow/include/external/boringssl/src/include/openssl/time.h,sha256=dTwq9O4D5EFsgXVmg4TocvAdWZn6QWgd1LH74OKTXZU,1593 +tensorflow/include/external/boringssl/src/include/openssl/tls1.h,sha256=y649nQgn1t3fwHssoSfM_MLOQ7xrsrAia8ZmHrXtxcM,30443 +tensorflow/include/external/boringssl/src/include/openssl/trust_token.h,sha256=4Vvdx-LlAx_38LsJKf3FHPG1LZg7FYfeCs90UlroJzE,16939 +tensorflow/include/external/boringssl/src/include/openssl/type_check.h,sha256=ljFcuMxhZQ0VYdqINmdpBKOxnKxhHpbCI8JbzzGUaEQ,3708 +tensorflow/include/external/boringssl/src/include/openssl/x509.h,sha256=-7ziZ2AQ_jbrPdtlyos2j942PIgTZSQEU_-wJ6mCliI,140808 +tensorflow/include/external/boringssl/src/include/openssl/x509_vfy.h,sha256=xis-Ngxvb4Btl0vkE20ZGkuII24Zwg_JhXiZQTiLHmY,892 +tensorflow/include/external/boringssl/src/include/openssl/x509v3.h,sha256=Gn1-AV2lzsObMcDHqwvCNbEQ2jGwns4aJMhYXWI_TQs,41383 +tensorflow/include/external/boringssl/src/ssl/internal.h,sha256=Xa6MZl8uIzeewMBPVm9Frd_fCUr81FXHsRZyx2XU-Nc,163793 +tensorflow/include/external/boringssl/src/third_party/fiat/curve25519_32.h,sha256=tSYK4p7NJZaViPoVewIXPZjiG2Nzm-okOSrMksiQ2vw,45726 +tensorflow/include/external/boringssl/src/third_party/fiat/curve25519_64.h,sha256=AKcW_FztqdkLkBlIGo_YHKPa72Qewexta5__tgPE5xw,29399 +tensorflow/include/external/boringssl/src/third_party/fiat/p256_32.h,sha256=SPs3ceX-v03EY3F2NUJ2px0keiN3jQZKBi63HR_h5jQ,153853 +tensorflow/include/external/boringssl/src/third_party/fiat/p256_64.h,sha256=CHt5oAsDojMYn_XLF_SXVBG_QiVzsn_Dq99AVVedNTo,65364 +tensorflow/include/external/com_github_googlecloudplatform_google_cloud_cpp/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/alarm.h,sha256=GYlbw-aGeDyPaSK30ORvfg1jPUAPFyyK7MK33YgjqxE,879 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/channel.h,sha256=-Fhp3md4CfYbw2fICJpsEw8W-NrkgljFKbn6lxNMl34,887 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/client_context.h,sha256=W5Z8o4g7E9y0kxfrh54K78FQJEh4qjEyBJt-RFXQBAg,915 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/completion_queue.h,sha256=Ek6pI7gbI3RhaJb6pszeaDd1wmlBA7BtOxQqD0LsPfA,923 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/create_channel.h,sha256=DkJRKvPEukL7rhFSpz6bfBktbj7oNRYiv3Ei4CEyDbw,915 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/create_channel_posix.h,sha256=MCPsaIa6gfkC7qQbrhUwhGa4gXd1Tkg7yG09eceMIxM,939 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/ext/health_check_service_server_builder_option.h,sha256=RqwxP16Fl1wMvr-4Zi5W1Rnwix5-zYINBn47E6wMvzA,1043 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/generic/async_generic_service.h,sha256=eJ3-XIi1Uj-2ZejCfoKTid4ur0Gi5hb9mnFWdm3ZuMs,975 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/generic/generic_stub.h,sha256=7Q4cjSoRwKdr7xIMsNlAsMyUlt9YrTpw94F0ylYHpyM,939 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/grpc++.h,sha256=7h-XU3ND9Q554QW2up-LRfeWSZa6aZwaB0d0MuX04s8,883 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/health_check_service_interface.h,sha256=hYshjOaITsSXV_LqrSvgscQ5KLaswYmRc1Siq1hOmCQ,979 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/impl/call.h,sha256=u3NGi942GdMEQRLbv9lGH7-NC39MT9E07Yh5DgEj2Cw,895 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/impl/channel_argument_option.h,sha256=jCjFH6EzIDFyoobPT2j8WhtEPrmSTcANIveXPlLCXvw,971 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/impl/client_unary_call.h,sha256=PX5nIRZjpcm0KqB_7H_lBJoIsIQ-gvTEvsIUd3d2ppo,947 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/impl/codegen/async_stream.h,sha256=TcKIUJhBJh8LfrVxqT5nbCrr4Y2T8M9YcFYrIfqauug,959 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/impl/codegen/async_unary_call.h,sha256=tVwJu1tMPfHmFFnADjgBFskBYx1qD9XRguBai9M-8AU,975 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/impl/codegen/byte_buffer.h,sha256=JOGm2WEDVLcIaTVfC2HiH7TqXxkSm0MkGAfMYgc2Dxk,955 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/impl/codegen/call.h,sha256=lSg4R3iQjhCehH76SQxZOYY4bZzNgZP2h5INA3psybk,927 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/impl/codegen/call_hook.h,sha256=032QZZUHG7QpKhZGh4zDUqnHFbrAEUqNMNSrv5kwH1E,947 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/impl/codegen/channel_interface.h,sha256=uSD5JDJ9BFeFUupa5vzKOWPKRnTG3Buja2vVVHHY09g,979 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/impl/codegen/client_context.h,sha256=U_Ye8C-0xOFIiU9oWUle8nbvs_EUfXggjWahn0Ok_Mk,967 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/impl/codegen/client_unary_call.h,sha256=iJ-UP6gIA3VdN7-VeHm1tZsI842cQNRreHkLXC5MXf4,979 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/impl/codegen/completion_queue.h,sha256=_nM0mKkwpoIS8UbPS4IOBOS0KfxkWkx6n5T8uJVrc2k,975 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/impl/codegen/completion_queue_tag.h,sha256=YXpUSzOc4M4-cKZgO1M_ZhCJ-jE1finJmpStW0irXJs,991 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/impl/codegen/config.h,sha256=7tL8RHoS4_Zn39YtgTglHNeYzUR7W30tncNYCPTK0v8,935 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/impl/codegen/config_protobuf.h,sha256=iIDkuJShcGyTFc2yAYonAvkLWYu85AEOdLbxQlNlYaU,971 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/impl/codegen/core_codegen.h,sha256=0CQ_2fp7U8-5qjr94VlT-sarHDZ42yiDBHCWUQnVeoI,959 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/impl/codegen/core_codegen_interface.h,sha256=HF_XNmgtd1jPbHO_IMOKLvKT9xa3zumGRIeQrpf4wS8,999 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/impl/codegen/create_auth_context.h,sha256=DtZQEni0v_lK4RFPc-1p_TQaUJeQa9SZBTd4vdQBYpg,987 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/impl/codegen/grpc_library.h,sha256=jUPW0Ih_zIaRXleuzUepBkfrKEkv8z8WIBX7hpMCxa8,959 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/impl/codegen/metadata_map.h,sha256=jluCSTDdZYAcT6vxUG-BnOSjVufz_NNoTp7oBKJoTrg,959 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/impl/codegen/method_handler_impl.h,sha256=FzXGarr75HHbssL9PTRGeWn3t5ZCOBSR4dyOyE4iUtw,987 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/impl/codegen/proto_utils.h,sha256=TbrHqKX5cLfzyarzB6TLwDzvp-cM_dq9po1d039ZLTA,955 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/impl/codegen/rpc_method.h,sha256=oRiqQPTNqVlJsQ0p1KXLgvj0PZARSs4ARItlMoSY3tM,951 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/impl/codegen/rpc_service_method.h,sha256=VEx39kYBpmT8-OS4C9hC1ui-NbCSSMvvBtu6M46Tg_8,983 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/impl/codegen/security/auth_context.h,sha256=GNvLeBdWnifnBOaH-r_XvWoNknyFcjItOxcyxcXIZtQ,995 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/impl/codegen/serialization_traits.h,sha256=PUfu6QPY06n7sJJLcctv0it6uO2WwVKpWv-hbUJNJHU,991 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/impl/codegen/server_context.h,sha256=FOH8j5bRlW7NH791M89gYPME14YbyEdUvofCDFkHCoY,967 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/impl/codegen/server_interface.h,sha256=H0cy0Ab0bGCs0aTCNoG9RpSyCVXzuFE3CiIsQOmNghU,975 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/impl/codegen/service_type.h,sha256=6sITlAXY7alh2KQktQkakfpT7fObqXNlPMh5j-cBo4M,959 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/impl/codegen/slice.h,sha256=ZCw01BNFwN86OtZT_5euODIdk_utKoJMrOCAmpPymys,931 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/impl/codegen/status.h,sha256=dJatK6Ve06Kx_sXeFS9u_FoQQgvs-dPoBoaf3vdvanE,935 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/impl/codegen/status_code_enum.h,sha256=vyuk_hE-C-g9AEXPWSIctjPR2CZTMCPSq-zpVT3ymIs,975 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/impl/codegen/string_ref.h,sha256=GG3fo2qhgthCRCaiDYlA-c23z9FJlekyMDJxnl6tFck,951 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/impl/codegen/stub_options.h,sha256=zb5PQ0kcXrDkZfz0ZG1UgUXzVqWcpvUqhknltcoIa7w,959 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/impl/codegen/sync_stream.h,sha256=oMtJmqgIgSQau6fmLDRMgU6TRCPq3oG4u2Kop31Y5J8,955 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/impl/codegen/time.h,sha256=bdD7M9ux-Ae37DRI3shHQ4rhiTFTeiySPicawJRHfdA,927 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/impl/grpc_library.h,sha256=elPJgh08WyjTS_b9KrtNcTb5V7IbGFNO1of63mA_wCk,927 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/impl/method_handler_impl.h,sha256=I5GC8iPqkknCbbGtn5fPAwBCKm4hV8lTz09Jy_td2Nk,955 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/impl/rpc_method.h,sha256=In1tNLoTWDo70vxxUjshQvVD3Nc0q3_GX0tHg-mJRwM,919 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/impl/rpc_service_method.h,sha256=XX0vjJkTUZFTbuATv4q10juk-sjuEzH_u73ItHKOP2E,951 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/impl/serialization_traits.h,sha256=BxkHP47jkv39iwG6AVjcVJuc1yoSRFnJ2Vr816i-amw,959 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/impl/server_builder_option.h,sha256=o_NeWXRoV3HQ18RAysjnD1frGfLt161LXLOtBnV0iNA,963 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/impl/server_builder_plugin.h,sha256=DgnL9K-dO6R3Yy2_1q_1q2UVpc9GcjGXsfhfAeV48aM,963 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/impl/server_initializer.h,sha256=08eA-kSImvov0rT-Ck4icKc8vpFnIlPS6ZOidUOaXRg,951 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/impl/service_type.h,sha256=bWcUJAvR7u7wyNOOm2j_2AIWDR3s5DmkeLj57U1ttOo,927 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/impl/sync_cxx11.h,sha256=KQ4qjZTjnYc-Xih-3bC8vjSL1sSctIEXgz9R7qPdxBQ,919 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/impl/sync_no_cxx11.h,sha256=VVhiXqxKFVdj9sJ1x6WzxHbeEstIJJO2pnBtbe2PylM,931 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/resource_quota.h,sha256=uToIe0CFkaGsAKD8BfNeDriBiyWgRVVeC0bjXp6eDTc,915 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/security/auth_context.h,sha256=RFTmaqKE8eiD1Q8ep7gp4qk-_thIGZcKoiPRHtuAdF8,943 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/security/auth_metadata_processor.h,sha256=NnZfXAwmq5TEJ3h5ZPAP-8c7_shVnwZqAcnRwsV1EY4,987 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/security/credentials.h,sha256=E8cI1bI_ybpO6AIQDFyc3amFtnudlutsK6P8I8Tpty4,939 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/security/server_credentials.h,sha256=-Q-x9Ku-XPT7fglJJGytWCvJUW1S54T4wKqV3hoSfaI,967 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/server.h,sha256=MHWkODgNsCwZhpJ6UUEVprc31obPkYXmJ5n-lNEhGAM,883 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/server_builder.h,sha256=kbkm2IFUjZPqZLrzbg7EsXIds586pVUqwYEim60QLZc,915 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/server_context.h,sha256=azQSgIEFBiMvZB1Kah6Rs4U2xlM4myRnQ3k1aio4768,915 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/server_posix.h,sha256=gEedX4boESwSVLQ3avoZk08eQFG2Qmaydziz3O2v8IU,907 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/support/async_stream.h,sha256=v-MBHQQW0-yet3hCrM6a3l3Q_ygMBMbu4BA7pp7FPcc,939 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/support/async_unary_call.h,sha256=wJPTO4Z536BjZSDl79oCq73TnF7Yy36Mwf6MbGG74YM,955 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/support/byte_buffer.h,sha256=XOGOR1mu2QmKQRumlibj937xawpNfi4Eq_t7hIr56E0,935 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/support/channel_arguments.h,sha256=TzLiv0IYudUIwp2TXGnO9SSheakKHNvd27p8FD44srk,959 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/support/config.h,sha256=xs4nsdrn_K3zHg1sj64ApA3izmSm23AfyclM-yRHE3Q,915 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/support/slice.h,sha256=IpaKNFugO2plufe7SckHTLU-539GI2yzvfQekD1Bb50,911 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/support/status.h,sha256=vONo4dDDdQo57iGjBDmp-j2QwesZChd1mz_bhsOXf1g,915 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/support/status_code_enum.h,sha256=oDOosXfK9aWzC_FWR72zvwY0zw9U7ghKNG--RPAw7ow,955 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/support/string_ref.h,sha256=4e6rB5Xo_yOvaNZH2TEhW6ayyD9l5Yy8fpGT62LP9QE,931 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/support/stub_options.h,sha256=bSpHkbKM3RtIUjWYIsOsxlzVuS4oNb3DzJ6liB9OGu4,939 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/support/sync_stream.h,sha256=uMaedEoGt0478wBk_pBQb9sFtFoArl7BWKWMedbhNiM,935 +tensorflow/include/external/com_github_grpc_grpc/include/grpc++/support/time.h,sha256=gM6EpPHmU0xAmjqnVWeAVPNHA0B7-YTyhDzZsMsb4BY,907 +tensorflow/include/external/com_github_grpc_grpc/include/grpc/byte_buffer.h,sha256=XKOwx5XOCaYhSewGTlGpInwBT96YGEVBpIupFp8WeMk,807 +tensorflow/include/external/com_github_grpc_grpc/include/grpc/byte_buffer_reader.h,sha256=UVHPePwM_wH6_xrhqIKFh8IaPG8Ricob5HM7FFaOX_U,804 +tensorflow/include/external/com_github_grpc_grpc/include/grpc/census.h,sha256=2LSF59hzO4rqG9PTnylwSt5KU45hOuq66WoG8Lo2mFI,1083 +tensorflow/include/external/com_github_grpc_grpc/include/grpc/compression.h,sha256=J5CStjbOc9dCc1-sNzyIc_AZZB7a0EPsodvVO0bSsw8,2696 +tensorflow/include/external/com_github_grpc_grpc/include/grpc/fork.h,sha256=pMlv96jGp9mjTsXj0ogpeLWe6ys4zOr7bxllSR1VVP4,748 +tensorflow/include/external/com_github_grpc_grpc/include/grpc/grpc.h,sha256=kXOc2hARnspS14KJ1BPGOpKMkSq_oAHOYW_w6z6WVB4,24846 +tensorflow/include/external/com_github_grpc_grpc/include/grpc/grpc_posix.h,sha256=y3NDpLaftHlDgKeKzbbG0Qkla-GaknOBUyHhItuz1Bg,1926 +tensorflow/include/external/com_github_grpc_grpc/include/grpc/grpc_security.h,sha256=FcQG0YVumEsCMoBfAIRHCMwD-hsDwOYUqS7B2FLfMt8,47298 +tensorflow/include/external/com_github_grpc_grpc/include/grpc/grpc_security_constants.h,sha256=IP2ky9HcEeyE76M_YVbKn6jxL-VPaHtwlxaG_iznzWg,6065 +tensorflow/include/external/com_github_grpc_grpc/include/grpc/impl/codegen/atm.h,sha256=t0lq7p86vxy1QrlfLjhvO2A55g5Qmios3C3O42TycnA,3390 +tensorflow/include/external/com_github_grpc_grpc/include/grpc/impl/codegen/atm_gcc_atomic.h,sha256=pneCHIiPr41a_wdMPlsZ9LpbRal2gHbCq1hLFD37iY8,3122 +tensorflow/include/external/com_github_grpc_grpc/include/grpc/impl/codegen/atm_gcc_sync.h,sha256=RypdjM_2QUujO2X7D3H4MothLQ-sRjjdJ73xjZy4vrA,2588 +tensorflow/include/external/com_github_grpc_grpc/include/grpc/impl/codegen/atm_windows.h,sha256=ExOOsEZDVuYgjqz5rnMrmQInYhgSiDr7YM_uvQAQcJ8,4317 +tensorflow/include/external/com_github_grpc_grpc/include/grpc/impl/codegen/byte_buffer.h,sha256=DVanc8vjyiBKwi87td-jjTWGUEIHs_XB4DVyVZ2zwWw,4161 +tensorflow/include/external/com_github_grpc_grpc/include/grpc/impl/codegen/byte_buffer_reader.h,sha256=J6b1JlbEUdQUTf_qdcjd4MxnbrBM8nN4ZAUkLMDM8DE,1171 +tensorflow/include/external/com_github_grpc_grpc/include/grpc/impl/codegen/compression_types.h,sha256=6Ct8W7_SJ06cvAekpGddcbR0af-mZfA8ndodD10bZL0,3984 +tensorflow/include/external/com_github_grpc_grpc/include/grpc/impl/codegen/connectivity_state.h,sha256=S41S8jBPWozyA_wlFSAKMm3m1aHI5NowCQlFrnbdnJ0,1245 +tensorflow/include/external/com_github_grpc_grpc/include/grpc/impl/codegen/fork.h,sha256=bhzuK0_YCSei3q10ClZwZyf31iA8_CjoK3qbPBdkzgw,1248 +tensorflow/include/external/com_github_grpc_grpc/include/grpc/impl/codegen/gpr_slice.h,sha256=I7piDER4YnCkG2IRcsFKQSXgqn9Qtwe7EAe5nVzOP00,2905 +tensorflow/include/external/com_github_grpc_grpc/include/grpc/impl/codegen/gpr_types.h,sha256=o63ciWb_7r8c89_T5YbDIzqXe4-b7ARMuBEJMG3XEWk,1780 +tensorflow/include/external/com_github_grpc_grpc/include/grpc/impl/codegen/grpc_types.h,sha256=lLKUML2dbWPE5WBnmyto3uwdEuzOAhaVCRHqfW4Nghw,36851 +tensorflow/include/external/com_github_grpc_grpc/include/grpc/impl/codegen/log.h,sha256=RiXw4BzR7c8nmWfxpsczWvPiB035rfBDf1TzMEaWzuM,3534 +tensorflow/include/external/com_github_grpc_grpc/include/grpc/impl/codegen/port_platform.h,sha256=uDy2IleRCy_cd6eu3IlSFDX6eMgw5K39AadIC9Jq9-M,19985 +tensorflow/include/external/com_github_grpc_grpc/include/grpc/impl/codegen/propagation_bits.h,sha256=LA8JpFP_zLBE6U0-_dqXDfzeba-g0G8VRUXtxYX2uNw,1918 +tensorflow/include/external/com_github_grpc_grpc/include/grpc/impl/codegen/slice.h,sha256=ndmC4T6BpRhXdbFIOCQm79rv6ZJiUQjZksA-cFrfcAw,4792 +tensorflow/include/external/com_github_grpc_grpc/include/grpc/impl/codegen/status.h,sha256=vk5sZsnHJ1v_XyJLYA_Ofc29gT6gbKNTxUMrpWrY88g,6256 +tensorflow/include/external/com_github_grpc_grpc/include/grpc/impl/codegen/sync.h,sha256=D3T627nocfmZZPAnEUsVwQ19QFb2_VqPosQBS4WjIiw,1947 +tensorflow/include/external/com_github_grpc_grpc/include/grpc/impl/codegen/sync_custom.h,sha256=a7FBUQbNAfovWb4LjqGc5VP8MiYa4sRwS635Wlemy-U,1082 +tensorflow/include/external/com_github_grpc_grpc/include/grpc/impl/codegen/sync_generic.h,sha256=J-_5pzsz-mFatEdW7v5eAhB1D_Nu9W1zfg5TubICItM,1142 +tensorflow/include/external/com_github_grpc_grpc/include/grpc/impl/codegen/sync_posix.h,sha256=i7gcgBJHz4q56subAQn4pHcT-pn0srAfGLGQ3rMYhYA,1486 +tensorflow/include/external/com_github_grpc_grpc/include/grpc/impl/codegen/sync_windows.h,sha256=FjpCb-QXRtmb_ZKgIEffe3MR8BEaX6hkzQ9hh4PfPfs,1046 +tensorflow/include/external/com_github_grpc_grpc/include/grpc/load_reporting.h,sha256=TR4keLs2tf_X_F4b-R8LGaszUSnZKsPjUc11nab0c2M,1511 +tensorflow/include/external/com_github_grpc_grpc/include/grpc/slice.h,sha256=Xj3EgwPe1GrSGbKxDjZN6ukq-ZBeu5w0XPjntduhJ1A,6958 +tensorflow/include/external/com_github_grpc_grpc/include/grpc/slice_buffer.h,sha256=EmpQTYaeIApOwh7WqQzJrz1iRHo1gClcld6bNVQh2J8,3911 +tensorflow/include/external/com_github_grpc_grpc/include/grpc/status.h,sha256=HYo25GxDFSTkJd9oWRH7xoGyx9RnbvBitWjGlkqr3kA,756 +tensorflow/include/external/com_github_grpc_grpc/include/grpc/support/alloc.h,sha256=ZlBObOAweqxrpBmWzLKgQgnBCDnGp-Gw_Q6CMiMN3IM,1535 +tensorflow/include/external/com_github_grpc_grpc/include/grpc/support/atm.h,sha256=p7Y9rOxkb7T6J4j8DOxiTyq--ZTURr25ScUi02Y050U,768 +tensorflow/include/external/com_github_grpc_grpc/include/grpc/support/atm_gcc_atomic.h,sha256=js7aVQ3-TXP8XZziJfQ5gHE2wBxxWP0dyhYxulmgSCc,812 +tensorflow/include/external/com_github_grpc_grpc/include/grpc/support/atm_gcc_sync.h,sha256=WLmw10dZ9BMZyrfQc8OHC1Jk8KYwjqsPU8VStnCug1c,804 +tensorflow/include/external/com_github_grpc_grpc/include/grpc/support/atm_windows.h,sha256=0TzT-4x6cv5LpifknEm9nx7rGPCsQAERllMDHYxSInY,800 +tensorflow/include/external/com_github_grpc_grpc/include/grpc/support/cpu.h,sha256=EgX86o3-bM3YmF_uWUfxFWW5_fAgxiCSPLUB6qwsuKU,1339 +tensorflow/include/external/com_github_grpc_grpc/include/grpc/support/log.h,sha256=dD0c0yQ4EjFyozv0mns27dt4VnCr9YYmt_Y2yRcfBVw,768 +tensorflow/include/external/com_github_grpc_grpc/include/grpc/support/log_windows.h,sha256=v3Sq7R-tE_IeUigbHsUVpDDRFz3lL4nZqhqAcCF7NI0,1067 +tensorflow/include/external/com_github_grpc_grpc/include/grpc/support/port_platform.h,sha256=N2o44COA53CvcSFzdbZTpB1yM8pMe3Pe4rBs4fPdank,767 +tensorflow/include/external/com_github_grpc_grpc/include/grpc/support/string_util.h,sha256=i4lajDrVI4-zCWUxHMDExS99N0-KfD7V0d7zcfvcQ50,1528 +tensorflow/include/external/com_github_grpc_grpc/include/grpc/support/sync.h,sha256=Q71wR7y3OcyGq57fufP3z3yU6YAWrXe56_a-jekad14,10994 +tensorflow/include/external/com_github_grpc_grpc/include/grpc/support/sync_custom.h,sha256=UrMObrEfTSG6X0U1wK5-sXJ5LE-piW0_8IzqR19o_PY,800 +tensorflow/include/external/com_github_grpc_grpc/include/grpc/support/sync_generic.h,sha256=DmOEvlNY8bU72AaztJsfLXJnqlN57czfE1_7cl7P1UI,804 +tensorflow/include/external/com_github_grpc_grpc/include/grpc/support/sync_posix.h,sha256=EE6V6ATz4lRwLTRlNX6ymM-PwNPGiFymExCExXrxrzA,796 +tensorflow/include/external/com_github_grpc_grpc/include/grpc/support/sync_windows.h,sha256=cF-XchJqoG1fTbxS-Rk9CrZ9IOBKbrPksLkLjnJ-yrw,804 +tensorflow/include/external/com_github_grpc_grpc/include/grpc/support/thd_id.h,sha256=7D_QJG6dhDDJfiQpAtw0XmFDPVEKCaW5mAt9LDsEeog,1109 +tensorflow/include/external/com_github_grpc_grpc/include/grpc/support/time.h,sha256=MiH9WU0puB2XMGEcYP1pYsyBlCSbvrVZZ4yVJVcUfJU,3239 +tensorflow/include/external/com_github_grpc_grpc/include/grpc/support/workaround_list.h,sha256=C3KHHxXvb90R41RQg1qXY6gkTKAinyWa5OqGAovI1MU,1000 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/alarm.h,sha256=8k2Bt_MoFa7Ica9hmcRVPQbxGjBkM9vNgqZfxQoCmYw,764 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/alarm_impl.h,sha256=qRflgGYYmR9tped9SWOo-xEZwBx9owpR2rpN6MB8Cns,4464 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/channel.h,sha256=jf3DwckPs979mu8tbHPw8U6cI_7LzdlkGvTiHgUWUv8,1098 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/channel_impl.h,sha256=IYAiQ-iVw-JSVGtDRM0oN691FnR-dUhUs2oF5OjEZvw,4939 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/client_context.h,sha256=e0NFd0O7xyPyD0n5-K9KYpSlV_fQ9IgvtHkTT8AnAx8,1439 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/completion_queue.h,sha256=zst9gpFFk2nkMplkxQVWQqwRXf_zJuk5eBEA76_BZlg,761 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/completion_queue_impl.h,sha256=faQX8Oh3UetYqy4XQxAs9BitD84o7alKJwwToH4rNt8,781 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/create_channel.h,sha256=4AbIHeqWS8r8NjBClsEX1fRS1J01qJ0bBmQB0uMTFJM,1820 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/create_channel_impl.h,sha256=Ai3b-26A8fe29Ctbcrf5SUZZMz67Y9h44PZSmogsFzY,2969 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/create_channel_posix.h,sha256=9RFgDLFoz3PTUfMWdSi27TK21EsHL0As767UMjxXx8g,1802 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/create_channel_posix_impl.h,sha256=dKvrsntYQkazeNA6LnmPLURRqmlfC4TqdxdbVByxDqI,2359 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/ext/health_check_service_server_builder_option.h,sha256=5slvjjeTJj9V5ACJvoZFmL0QcDB8IxxO59B8qARwYEM,1603 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/generic/async_generic_service.h,sha256=PMmjPr6nKXL_NzTZS0fCsXN691FuxFHHy5cVvarWE9o,805 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/generic/generic_stub.h,sha256=eMVtJHt3I6PF8ZSJeckfZRXD70MJnDE2woCXFM1U23w,856 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/generic/generic_stub_impl.h,sha256=1rYV1iurFOjF9pqwVAbG1UcmYKzj2G7-KPNOAntPAgY,7882 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/grpcpp.h,sha256=1St6NLiqtb8mO_-Jt6VMt_PfBoaiSIsCWSXjktrUk-8,2331 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/health_check_service_interface.h,sha256=nQaopvVaAFOwjDYoDIN5TbgGVYDZ0MMtm7WxPYbkKw8,1261 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/health_check_service_interface_impl.h,sha256=8pTOjz91jXElOTC0pKzbrWSCZTntlnXcEuaQWHYIh00,1879 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/call.h,sha256=HcsKQE6Ywm42NhGBSG2iGuio53kl-bKsAYjupyVvrRg,728 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/channel_argument_option.h,sha256=OTxXpo3_TV2Z-THc1HVhW_ca3BkVoiVfHmKqT2h5e78,1143 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/client_unary_call.h,sha256=lMOjivhbn-NsQvVD0gcFztEDcaoyIqK5wLayxjFFWxA,780 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/async_generic_service.h,sha256=FFDJIbzCemhJXdKqRvtEXXtzCNiN-RRegAP7mATJZYA,5279 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/async_stream.h,sha256=94jY7zEGfiQ4TaMA9CgOosfETv8jdNnOMyy1EKhpKz0,2778 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/async_stream_impl.h,sha256=gyk7nmfaW90D6hp2aLDz6F1vEXLs2KVhzhnbZDTZbBI,46580 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/async_unary_call.h,sha256=bEeiS3bjqASaa4MmfsdUd4mvFPAMLYN1_D4d7A6YgM8,1327 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/async_unary_call_impl.h,sha256=-AligQ9IOFXJoJFqhTw9D3Gj4_Yejo7mBw1a8IRBPDQ,12543 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/byte_buffer.h,sha256=saSIxg5QBwChDveRrvAWVnoEE16LRgXeLL27YgmT6_g,7878 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/call.h,sha256=rCnGeiqaZJqJhuVZJN0t8LRY9rW9Oet-Tumn8OXG1j4,2800 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/call_hook.h,sha256=Ymxrbd2x9vg1tP3GEvrlYQD6cVNUwbvpFBJSnIR7-pY,1083 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/call_op_set.h,sha256=V4TEUzMqRODxlTlbu9z8ntweADM6gFtbIT8ExWgKtTY,33988 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/call_op_set_interface.h,sha256=JrAB7KlYlbB3FEBbsXdKO5TgSQQzzt6EDkW3tO7s5yY,2080 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/callback_common.h,sha256=dY3PVefLtMF3hbeFPdnLBUpFFN1Y35IaIOlQRF2xoyQ,7961 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/channel_interface.h,sha256=G2HwiDxID9CDWOthCTG--kLDYIxIgPA0kibadTtqrck,6737 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/client_callback.h,sha256=QJOYpoEhRj0q9X4NfuuI2D5nbb7RGirLwKM7c5NLmYA,2444 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/client_callback_impl.h,sha256=tUxCDgz0FBUf-cn-ZtTOrjlCUhdw1_iaYns91Ub_dlE,41230 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/client_context.h,sha256=75GoauUUmm3D5sQ5fGtfwgSwN7kDCCoDO0ksMOhw2NY,948 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/client_context_impl.h,sha256=WECB7gJ4W9BuPpc6nFx-KPPelZXkhkOcgaxh24UV9Mo,19367 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/client_interceptor.h,sha256=9wjSZKe6i9GLYYy5CJrjaKsoFOTtwvvBMj7Dlv1CuLI,7099 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/client_unary_call.h,sha256=duWn0XrUcL46aJZIVxtLCH7bD9iGHulOeWkFM_UUsj4,3550 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/completion_queue.h,sha256=gQCU8n9qEVIEPFBSyqMyAilWs9-qC41ELz23y1UwivI,971 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/completion_queue_impl.h,sha256=E7kA_Gm1ji5F9d9n470vYIA7usqYtzpCzn-O-qTD0zw,17182 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/completion_queue_tag.h,sha256=BvZ8Ezi0jKU1LOQBGZpzixZK55fffF7ZcLQkGWIN8l8,2087 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/config.h,sha256=fcQkryCX2oc6ueX0hakfVxBKrKFeMp7sP7NG1rSTrbE,1163 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/config_protobuf.h,sha256=-SLFEsado9t6hZC4N9MeF2HatSv5K_i44uCyx7UYBr0,3795 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/core_codegen.h,sha256=4e-Kmxj2oEW1K9RL0DXhgVlnE-GZSk70fCco7WqaWSQ,5778 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/core_codegen_interface.h,sha256=f3VTbrps6VISMbXmpL1NQhwtwr68GvSJph0ClyoW6u8,7718 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/create_auth_context.h,sha256=UBlKo0pYNmOdI6Yg5qsta6BVXLSunnqK4uGedDNvzC8,987 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/delegating_channel.h,sha256=bv2ToJOTfsFRVC_kn0bStUNZucPHwlrhN-nNnPmbhb4,3035 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/grpc_library.h,sha256=Keimp3LBbOgDNKdopMiSaqZzOWOWWnFBae6EqJvRH48,1862 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/intercepted_channel.h,sha256=mhTXOoQZ163oN2cc_SUVUx1qLHwTEmOy9xAyjSLg0F4,2898 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/interceptor.h,sha256=PHs7ngwEudZybLDvOFHK6S7gzYmTTqU1CdV9Ghjfen8,10932 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/interceptor_common.h,sha256=Cvp5zbO0amAIP_HMmgBMIYWnnXFTDtY-Kwn2x9iL8D0,18340 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/message_allocator.h,sha256=UdoBWNtXkojCue9YJkGmHjMWt2FFjlHwg6WDh5OO3CE,3150 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/metadata_map.h,sha256=-kpJ6Y8TLg8bKvtM1x1vrjSiNghSsWHXDdrF4blK9t4,2983 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/method_handler.h,sha256=vOv_iuvEERP_51X_WFJgG5WPsYkwlXujOHZfHja1Kmw,2634 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/method_handler_impl.h,sha256=ZDU_JHn1UFTsSdF1YLLibN3bc-evizg9pzH2I9s24Ks,15097 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/proto_buffer_reader.h,sha256=g8O0Ma9nmoJweIq6faSI-f78SSOgnqY0xBMrasKTB7c,5843 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/proto_buffer_writer.h,sha256=NFhwRhg9Zqm8FSyEl3NiQq6HgiACP-jgat3-8dCOe-A,7176 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/proto_utils.h,sha256=J-8EVMPJ-Ew_CUioK-8bMicnwOIe47coKwB8mEfnH5c,4550 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/rpc_method.h,sha256=YIpUxH4pymgpetrotlfUJiw4IvYir9zqANVQaQI2Q00,1723 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/rpc_service_method.h,sha256=dyv40Uxkd78ZfQNwLgw4vUNpC7XUpvhQeNTS96l9zNc,5454 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/security/auth_context.h,sha256=6GNDtelahoZ2-oAPKwEbcNgAMWvx_UH1E_tIajBV4zw,3050 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/serialization_traits.h,sha256=iocmSkL3vl4spFdDj41OBeNTNqPvWhGXUncguxsoE5E,2362 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/server_callback.h,sha256=QXl0hhOqm0khin_OcygLjjKRxrQbvhblWNuY2R_HrJU,1762 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/server_callback_handlers.h,sha256=B6xyY4KZljQP09AQ9ZvZeZiQz4Tlerzh2MOg-c1Nu28,31894 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/server_callback_impl.h,sha256=3ZbsZjpL00YnoeNkH_6GhMS3Bugr6K_chVgcsVLGWnA,26912 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/server_context.h,sha256=PExlQ78tI8A1J6s5fuQ0lN2eeLMES4lOGJitWShAtsg,1319 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/server_context_impl.h,sha256=icXHkqlzJbuMT0sfrj8WX0GMvXebLvhZ_EJGhodX_xo,23050 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/server_interceptor.h,sha256=ZxbLX-8LYgFYKjfcfiQeraBpG1kOfwrwiimPKAfgJxg,5079 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/server_interface.h,sha256=zCouiWfoE8l45a_YBXpj0v1RXsbrWBFeBe2ZPd_7zkk,16670 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/service_type.h,sha256=otuRpu9s-EhFDd_meZRq9uFafGWmmntcSX0IrzUNJpM,10273 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/slice.h,sha256=wiL7Eok7FnfpEyIiw4b7ZvozJBoCZBwB7siM9R97q-U,5268 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/status.h,sha256=uHJY0m-KpMCIJcSCcrxAp3ISrOeN6XklyuRhtUFmvZI,5459 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/status_code_enum.h,sha256=lJ1YxdP4JhZ6nlYmhARPCV5ShLQX9bgxBujMmjVjvvk,6012 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/string_ref.h,sha256=6n5_7_y1nZc6-9QBKkmyXPmNwjSj7pK9dtvLYI8J4jg,4544 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/stub_options.h,sha256=CE0pu96eLNxwNr9ErIuPVZr8VIbGfD4AAb41mnB7-tc,841 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/sync.h,sha256=ZPHPZUN1MNy5pCkPvqE6OsP0-FSLELFgbciIfmsPhHI,4035 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/sync_stream.h,sha256=pNt4ocZy_C5ofshV-kJZQJwg_VgHVlX6cC5d32ZbNRM,2884 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/sync_stream_impl.h,sha256=GblOMuks7zD30yUklXjtQtTZBkTPBHSQNdvU09ojxUc,36820 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/codegen/time.h,sha256=Kt7BfxvTIT0Joam7z28SEPM2kHkKnezWQSQd9xrq8P0,2510 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/grpc_library.h,sha256=iRRrZGvOUV52Tq2sLuflHkugfB1s5ecSVUpKpCNAlpk,1759 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/method_handler_impl.h,sha256=Lm5opHzLmcdAR-xNAKLvMgdRVTbDWrld7br-6et_0gg,788 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/rpc_method.h,sha256=rYBsdFjNkLyhLjQ2q5YEn006BtGsXKJZcaM5xZ6qaZs,752 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/rpc_service_method.h,sha256=xFlxwVOtx5VhEJGhLIpuffPPjIX5UXBB3NIFFpocxiM,784 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/serialization_traits.h,sha256=p53PwL9NU6Kb1fR3zjhyP87duuMww2rS4xSp7IE1bN4,792 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/server_builder_option.h,sha256=CPC5Rvf0eL15j_Cg2vSCX2R_ICONP6nYt4NN0h2rhdw,896 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/server_builder_option_impl.h,sha256=GoTb74lXYitqoUsvxAypLp16rXA03sLNLVA0l37g5hA,1385 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/server_builder_plugin.h,sha256=RQNhfJeZbF_Z61j8AJ1K2KR59uSx8tvlfZULvPiNW6w,2330 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/server_initializer.h,sha256=MBt_WDaNif0p1zYMQnLJ-KeyrSi3bXMIEeoh-QrbzUU,880 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/server_initializer_impl.h,sha256=t7vhOHsMgMETHMv7uoaFMqyPIcKbEbr30e7rTOABKjo,1440 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/service_type.h,sha256=eDuks3_MfF4cB5YyEYG7vth8Xy6q3jDBAW8F8oj_1Yo,760 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/sync_cxx11.h,sha256=a6AFvWj5SyAbF5OcNd3w8SSjiBH1ykEcn5e8BinGI-c,752 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/impl/sync_no_cxx11.h,sha256=3q1NYHQsTlE2WVgJerWfDVU9m-bf9MUp99MrKyOnRGU,764 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/resource_quota.h,sha256=W6ByQc5PTdY811lPmMx1OueHKiH-VL4jr_IlPjRHbSc,835 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/resource_quota_impl.h,sha256=aGfRAIM0nHhxn_Z96rsp7pzYM2GMtz1-gdVw9LGF2XQ,2434 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/security/auth_context.h,sha256=nOK8CoUtKr_d7l0TE0-k8owyZJlElBRA1D8LRyY8qgI,781 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/security/auth_metadata_processor.h,sha256=UBkB-L5HDzfRjRlKEDztWKgt9S9qnB3JDQ_w4SXaiH0,924 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/security/auth_metadata_processor_impl.h,sha256=ElYQy0Y2MFE0NM6YdKKKTsZbqPClwG5o7ulPL2koZsI,2411 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/security/credentials.h,sha256=h8Qyp_-ovL9mbiKP3LgFXitPhj9FwWp-CcKKRcj25bA,5213 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/security/credentials_impl.h,sha256=A2e1L7WcEoVLr26_SSsEOUsxjTlTC4TaWpfOGRct8xE,13437 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/security/server_credentials.h,sha256=asD9iceVs-Zyf_CDgz7Zm6N4nsIxceXZXANz_Ww1uMI,3001 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/security/server_credentials_impl.h,sha256=yLeZCXXiDXNp6H3yn2R_LpVkYglj9_nXmtvrwmnZtkI,2840 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/security/tls_credentials_options.h,sha256=Ib-svYresJpXSw73j1NAFCR4HVjLBzHZ2Vh68428aRE,13882 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/server.h,sha256=wEJuFMQjr6S-J49sn3IdJO3IUceOLKe6kBBD_OZCxKo,790 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/server_builder.h,sha256=xlQUsRjTQ3KlCSaNq9HuETQpLKW1oC0qqBdSAdR-pJw,836 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/server_builder_impl.h,sha256=9ituYGBNd20MvKEgBQ06eWF2V6Z22Uzt_3q86iQ2JQ8,15045 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/server_context.h,sha256=6g6tCVkV92MEQhjfdoFoXyyEnxkXDLYmk8xsB8bw5ew,753 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/server_impl.h,sha256=DdNpWqGrhAhnviHz7EgA4YJ6uOSxP1zVw9NcsR5wCHs,15336 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/server_posix.h,sha256=-aF0zP92kbkfwfr4ZaAm2sVJM46AZjbShG0FDfz5a0g,981 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/server_posix_impl.h,sha256=WCE0Uvc8CSEuoWYrzrPhU4LERUJP7r1w_gBPBGhnqXA,1183 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/support/async_stream.h,sha256=fd0QK6bGJdMjxjNQb9yuOSCEmmFBcX673F6cqd9Ri90,769 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/support/async_stream_impl.h,sha256=WlAdjaFhpyvBOgVingURv6LTDm2OdCPD5-1UKJv1pQ8,789 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/support/async_unary_call.h,sha256=3JrEPsQbEJoxniQRUeNyCmeDubrKz9sfLitnGs5o61k,785 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/support/async_unary_call_impl.h,sha256=u9dlTbHz9MgJVYgQVAgMZ-IEP-JP9dlwtXm1Xcsdimw,805 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/support/byte_buffer.h,sha256=Ihzz0D1mMZIfailaLS7knQLxRPP59YwyHHD-5rwl4f8,998 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/support/channel_arguments.h,sha256=QyHS6Z4JHcrCvjK76IhXqlqTKWXgxiWwXFS4QPfWTpg,989 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/support/channel_arguments_impl.h,sha256=8id6NDT4SNXimHaeQNGZ1wXJB4kuvxaU08pz6EiZUTw,5343 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/support/client_callback.h,sha256=pgQu-9jWYrkRV-mlj-op2w88Xjp0Hpp0E4buHPkGPPE,781 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/support/client_callback_impl.h,sha256=ZgRV-spWed5qo4bzeXWKxPqFbTW-r3aIi0oyo8Rk1Tc,801 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/support/client_interceptor.h,sha256=8tAjLfMI7O_CkqqZ7SIi2Kt2A4phHHEXEdPApJB-XUU,793 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/support/config.h,sha256=SiUGfoyEMc9gtETYXvb4UaMjRmJ1I73QOZdfeKgJh1w,745 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/support/interceptor.h,sha256=BSPItXTdD2mDvtB9czEtwX01iTj8A3Lpvg-BB71O6Og,765 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/support/message_allocator.h,sha256=OMtEiBMkXypf00ewVsrWMjkACmqvvrUaV9lfVETgJxc,789 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/support/method_handler.h,sha256=-PvT6bOuudLwwixnMMQIz3Pei22mX5tzRLRCmA4edaM,777 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/support/proto_buffer_reader.h,sha256=LYdQlEob_MZZmFHd-lP6fWDMziZHNyT1dBpdkuyMfSM,797 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/support/proto_buffer_writer.h,sha256=iUp4GsUUDQhYUFYaGb4_m6Zv4VB-9Imvn5AZzD_6AMI,797 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/support/server_callback.h,sha256=aYYmeDuHvZjiGY5cD86GnNGPMtYsrpvn4WLjsU0seWo,781 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/support/server_callback_impl.h,sha256=GojCNubOneWzS5uve6imneGyHhR6GGW1Lo3BBatWWEE,801 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/support/server_interceptor.h,sha256=7zfg-511Gqqe8hGcyR1n4bt1TsJeKtxuRU5yqbhbbk8,793 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/support/slice.h,sha256=UjlY09ZEp6jrz9UM-Uc1MJd2wQPJPoRX1y8aGSni7co,800 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/support/status.h,sha256=KQS867LeXtPcSbRhHB2iSKtDtqkf0ehsG2xz259zTsQ,745 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/support/status_code_enum.h,sha256=mpCkmrbq_4j-LK_ZepYr1gxwq24r76PsRqI5ZtajDQ4,785 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/support/string_ref.h,sha256=Twc4lj-vnDnvGA4TSNNDeLTXUpMTL96_5ERBNtTK_L4,761 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/support/stub_options.h,sha256=DApj0o6hwoVR88ibZYZ9tEDgxf2DhMPwNFJ_ARWf48c,769 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/support/sync_stream.h,sha256=q8NA6LivmTf81DoirWE9dL97Bssx5r1bM1MIsT6Qgd0,765 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/support/sync_stream_impl.h,sha256=FIfSsj2ADIaeFVw9SChkB1jYotSdX_vaEq83QLEM5Oo,785 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/support/time.h,sha256=wbLnR53xtUmjRTSMchuHOYCptQ8KsLK088I5qSBx0xI,737 +tensorflow/include/external/com_github_grpc_grpc/include/grpcpp/support/validate_service_config.h,sha256=oAb8aTOUpT5eC2hM_nqRfq9YDRZPatkptX0co4lMKkU,1189 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/filters/client_channel/backend_metric.h,sha256=a6THMtwMHy0Ez-HYSGHswm4KnFKf_cRkJp87uFOscHg,1230 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/filters/client_channel/backup_poller.h,sha256=ePzqLZzMznQda6qcQcY8wVT7lGdbM9H0W5Cc2PqOuoc,1422 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/filters/client_channel/client_channel.h,sha256=tjbCoHFzKJwzqmPT5PgvIzVMGc6AobThFmg3YpBveCw,3501 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/filters/client_channel/client_channel_channelz.h,sha256=nyidK0pZW-HdAWnczBWmMCMrKtUZArtw-gSMQZljFKQ,2748 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/filters/client_channel/client_channel_factory.h,sha256=4wySEpvEIjpsdmZ9Apa3PZb-zOsEGAP8-tqjSmGaOxU,1506 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/filters/client_channel/connector.h,sha256=RKv5Qotndkza9WuDMsavGAmljc4q20RlqweOClZpqQw,2577 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/filters/client_channel/global_subchannel_pool.h,sha256=eqmkn0SBfZHSwcmzuW5epgOO3HbAH1tVbAN-VHkeB6o,2470 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/filters/client_channel/health/health_check_client.h,sha256=3xIihGw0XcrzKWtSka63HKUkIdNjq9UsTqTnA8qvpt8,6071 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/filters/client_channel/http_connect_handshaker.h,sha256=7eHNnfyq40z_JfQ0BlciaJRiuF1z6aLThmllSyXOZ9o,1331 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/filters/client_channel/http_proxy.h,sha256=f6SpZI22kW30ZeOCNCFvE-7Bb4W3Xfp0fhArKpADQ58,867 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/filters/client_channel/lb_policy.h,sha256=0PEEUT5l6FcTLACbegBIoInfz7Vd-5s1QXDnsv1ujNk,16417 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/client_load_reporting_filter.h,sha256=EIvGlIQxCj70FzS_S3j7tYCQfonjqTnwnJf7u6Pbc2A,1058 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb.h,sha256=ROU-TsVoQH5074WSdZl4qw0mouUmU8SAwPEvX1-8GK4,1593 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_channel.h,sha256=8Uh_ZXJQA5K30jad5mmUTHnviPrQz17sKhe4q5SpKRQ,1498 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_client_stats.h,sha256=BzN6n1QikQaG6gB1wySU1KZvrkw4rZTgCu46u8HbN34,2460 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/load_balancer_api.h,sha256=qT3fDjyurj7F6asOKe7QGmWCKjLRYkbmDCcUjLsBzTM,2495 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/filters/client_channel/lb_policy/subchannel_list.h,sha256=35pBOR4zdt__Kew14tP3XZoySgYPZIUq-SgAWXdRsR8,17393 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/filters/client_channel/lb_policy/xds/xds.h,sha256=k84Q26wSKbe0InYjiZIST3CaKN0eoRKe7X5lm_MX_Ts,1262 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/filters/client_channel/lb_policy_factory.h,sha256=ui6Gg3N508zxTAlVUB_3_H7CdEQ3FFtXNUhZxe8qHCY,1537 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/filters/client_channel/lb_policy_registry.h,sha256=kbHfBK-tE9bJieXstRF1tOwkRLMAaOmg3vvwYIuynHI,2435 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/filters/client_channel/local_subchannel_pool.h,sha256=a5aL7XJPKrclZlr2O1KktE_EV5xfgf2n7PoPEiuaahE,2125 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/filters/client_channel/parse_address.h,sha256=hBbsN2AFNt2f8LRRDl5Uw2BAtegasyKkYMICu4eB5ZA,2176 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/filters/client_channel/proxy_mapper.h,sha256=PRSoqpBgvtUtZH6P36QD3riBw-nXS3fvUBcM4eeKY9A,1891 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/filters/client_channel/proxy_mapper_registry.h,sha256=A5E_MQYbpyk2u3_lmVk5MVREPtxbyC8g5rynkb4tnEo,1728 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/filters/client_channel/resolver.h,sha256=zVaSoJec29WAAiznHySK6dLRTZ_e_yVG5hz-8QhXwzY,5234 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.h,sha256=vcMMOeSQoDZ-Y3xFMkUSarcGyAns_U7dAlYqEtJ7Cyk,4433 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h,sha256=Rt7BNZfSU9rcwo7P7oxProceH_IkVuJYDCV1X5NdDZc,4421 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/filters/client_channel/resolver/dns/dns_resolver_selection.h,sha256=xAfcJTXJFwQDTQGNNYZ2Ca3UqyZPMRMs-raYgT6qiag,1011 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/filters/client_channel/resolver/fake/fake_resolver.h,sha256=rhrmvje_IzZv0VxKcf3b-s9WH4Gr6Iq0lukJL92MS9A,3823 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/filters/client_channel/resolver_factory.h,sha256=oVFVaCxDBOKhj8Ne1PNcn5MeB5aWMzxXYCdwlwVzY1c,2432 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/filters/client_channel/resolver_registry.h,sha256=PcDAkUo6d96IMokMY5tVWwQxjgaVz0rQnjJimc2exPk,3636 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/filters/client_channel/resolver_result_parsing.h,sha256=4vK7QDNh3l4BEn7z7nV-rtKthA8dO9GVWGrV_qr_xGc,4245 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/filters/client_channel/resolving_lb_policy.h,sha256=JfVV4lxLW4sQ8uvX0h5VmDnWqOyDZm7l_xd-Rq_m2RI,5087 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/filters/client_channel/retry_throttle.h,sha256=DsjRi4ZMsZ3JCGiWIG9BSSDHjuzq4VgZhTqrvwwyYxU,2576 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/filters/client_channel/server_address.h,sha256=0Y24b6rYy-3lO2j0MEszcAfpRmzF3yAgI26g1SX_Go8,2919 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/filters/client_channel/service_config.h,sha256=0DG67tLSnqyLrpeAUdFPrE5-LJrN9ub8_pjoH4lmdEo,7580 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/filters/client_channel/subchannel.h,sha256=vsPWxDaYd3oqHDN735ccKe8RCoZuTNuxjBsMNJZyuEs,15718 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/filters/client_channel/subchannel_interface.h,sha256=70lJxbaZ2m6IoMMqR55KpFVPJx7D1C6koUT1JqGMIPY,3817 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/filters/client_channel/subchannel_pool_interface.h,sha256=Ow772hehbpDgqewAM-anL7lmv7zTBP2vd3wv2nl5F4U,3252 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/filters/client_channel/xds/xds_api.h,sha256=ppYY27PEWtJjj2bXPx084OlSEGbSsDhvgRQKKgxDA7M,6070 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/filters/client_channel/xds/xds_bootstrap.h,sha256=cw1ogQNp7MzqsTLDByKZbUcF4HHxu_W5Nm4X1y2Gso4,3474 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/filters/client_channel/xds/xds_channel.h,sha256=WDEc793gR90SGBdPUY8tpzdkw1f_tUbXFQpvVreuryI,1383 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/filters/client_channel/xds/xds_channel_args.h,sha256=dlqU5BMCLXuW28iWQsVBsf1QXNZrgC5BGOO-IzpmsFI,1059 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/filters/client_channel/xds/xds_client.h,sha256=smn3hwe4DintJ1Lucljh32_RoblqrSu1yKMMECzCswk,8025 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/filters/client_channel/xds/xds_client_stats.h,sha256=LzDA7xNFTAVzpWKb2p9fTzBKO3pFFAiQEniUCOACDco,9346 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/filters/deadline/deadline_filter.h,sha256=nJx1NpWh6bLcA7EASxpL70YiHIA4lUPtZ3oY85gHbMs,3562 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/filters/http/client/http_client_filter.h,sha256=OtO1VSD-ItWTHENz1Q1725Zon2a1ajHYQwspXgRfgGs,1165 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/filters/http/client_authority_filter.h,sha256=5PS2Bpjp2vC30SLgyZxMkZxzTlLeTkY2lRabw-w33IY,1215 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/filters/http/message_compress/message_compress_filter.h,sha256=Mh3_gB--NsPW-snWBTiTWedMLiwltlZe_qkrsYFHvUc,2063 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/filters/http/server/http_server_filter.h,sha256=2eNFF8KX0NCNMVwIQ2Vk9bmGOLjKagLeRU-W8_q-Heo,1013 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/filters/max_age/max_age_filter.h,sha256=2cL6CVbC5ApsGZsAAMIT-1l5AS-RXugAhuCA4MrSczw,913 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/filters/message_size/message_size_filter.h,sha256=fX9PaAryqoHcY8ay0Sq_9N2GfZbMWQfYLOshEKTQwQo,1747 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/filters/workarounds/workaround_cronet_compression_filter.h,sha256=anMwsoRbRfCxkjH6VvSqcQQJ9k3qrd6Td0Yh21TEcs4,1023 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/filters/workarounds/workaround_utils.h,sha256=mfx-A-O9Jh25UrHDRbEPPol0RP0uj4YliJDyR-bdZmc,1325 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/transport/chttp2/alpn/alpn.h,sha256=lbbuFmQlt6fivBPg1VdwmRIoF0OmRmQVmDWaMcs5tfg,1216 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/transport/chttp2/client/authority.h,sha256=PDbL4CpS7TjFw3xQEii1NG-KZAOThidvSlTKiHe_zVo,1273 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/transport/chttp2/client/chttp2_connector.h,sha256=jY8f4v64pKCBdrvNgANSnCak4rZMIB8M_ESuCQ6h3hE,1808 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/transport/chttp2/server/chttp2_server.h,sha256=6TxnNyFPDcWS4Mr3Y9chNd22TWQ8K6gBXxqRYn0LnFQ,1180 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/transport/chttp2/transport/bin_decoder.h,sha256=2-Tkltjqvjla0RQO-ayj9JYv7HLDXGdo97aKznsxUJc,2186 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/transport/chttp2/transport/bin_encoder.h,sha256=pvS3x9WntlRwlSa14qswkPbPdf3ShRzV1zVtSYC5Mjk,1495 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/transport/chttp2/transport/chttp2_transport.h,sha256=25p46Kg_i-biJ5rVvN1Pco4Df9CnWRkuFjseopN832k,2016 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/transport/chttp2/transport/context_list.h,sha256=-jQnJPF7iGCUDTAGafZpSSupNzpVgdsGpCZZ-HI8ygo,1904 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/transport/chttp2/transport/flow_control.h,sha256=2D6rPrer6fVahNnzE-klUUa9Ab2Mt9Rit7uG786qlwE,17144 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/transport/chttp2/transport/frame.h,sha256=pnHiXGJd-2E-D0XH4E3nDQkH11uFYht_Rbv0FQ_W6Xo,1526 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/transport/chttp2/transport/frame_data.h,sha256=OF4LBVEhx8lG3W1OxeKQt5L5BSDx63bVYQKvG87_ZII,2927 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/transport/chttp2/transport/frame_goaway.h,sha256=AD4G3b_FTenQ91lv1bo4WdzRE2koLnl2bid9Qc0SJ1w,2242 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/transport/chttp2/transport/frame_ping.h,sha256=pmas_8Qm1pbbBpgQD8d-VDqWANrevllbQ8x3bOr_4qI,1637 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/transport/chttp2/transport/frame_rst_stream.h,sha256=SadtgCrfMSoRyHwxKArXj0UZs4K90GFMuVyH_lyQi1A,2021 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/transport/chttp2/transport/frame_settings.h,sha256=GDWL5-Z5hGYn62zoE3H1rq4raG43HrQit3_xFuBNOlc,2223 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/transport/chttp2/transport/frame_window_update.h,sha256=kN9ByFrhpOrGehtTuOi5qetSmN9qFgwWov_dtuw_WMU,1734 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/transport/chttp2/transport/hpack_encoder.h,sha256=1_tM8SKVD82pQEZcRDg3MT20i3V9EZc_AB1l_VlavUs,4290 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/transport/chttp2/transport/hpack_parser.h,sha256=gjVNBoQyJZz2SM4zRYlgt0aC6udomybt-GatP9prbmg,4218 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/transport/chttp2/transport/hpack_table.h,sha256=Fhd0AsjerYlL_b0eboeox324oEJoZffVOsgqJVbQD5o,6040 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/transport/chttp2/transport/http2_settings.h,sha256=7HPqe8IIfYwJuemq9AVm4xJPlu_jZ564LHiTHOh8Brw,2176 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/transport/chttp2/transport/huffsyms.h,sha256=P2JFfNvvbSiW0zMhxoxObyTrYt1yW5TaqN8r76GktFY,1021 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/transport/chttp2/transport/incoming_metadata.h,sha256=3qAk9D6L80nIvy1RjAgajhUstxsqyEIGNCm2uau88Nw,2171 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/transport/chttp2/transport/internal.h,sha256=3v0NB-jDAmRgp-M45Ah3sxke6_9aTHhx5vRqx1YFJrk,33829 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/transport/chttp2/transport/stream_map.h,sha256=68Hxs6YsqpVOrtghz4OCFdr0l9Lftyy402xhIFB3_2k,2554 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/transport/chttp2/transport/varint.h,sha256=ekiPbYtXz2yzi7NIG237V_RCiQ7oTBIpbwAzU3ERHTo,2662 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/transport/inproc/inproc_transport.h,sha256=jI672hLVLV-lbgwsDHPkHJ0ozraCt0m1LCO4FyiN-Ec,1195 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/upb-generated/envoy/api/v2/auth/cert.upb.h,sha256=jY0wF1FEtrKJFwQHQJVseW9HaD_kUctv8qJ0LeKr6HY,64574 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/upb-generated/envoy/api/v2/cds.upb.h,sha256=sC8h-gldM9DgjEVnkYXRnH6mDIVV4-MlKO5nAT7oyrk,101512 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/upb-generated/envoy/api/v2/cluster/circuit_breaker.upb.h,sha256=OOc6pWMKvVMGTwq1dGDRaGNCBsnsT9-WAqXUxe_eZPY,11095 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/upb-generated/envoy/api/v2/cluster/filter.upb.h,sha256=cnFKXlCH7yWXaT9W0q9nB2TM4jXXPpc2ohsVkCJPigE,2850 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/upb-generated/envoy/api/v2/cluster/outlier_detection.upb.h,sha256=yLVM985lXuwip0GNVli8rLOaon9xAckvc1gte0gBChU,23575 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/upb-generated/envoy/api/v2/core/address.upb.h,sha256=ANpJh7Jw9ji3zNOx1S5qDGQr-jJISj8MuNMNynIYCeE,20239 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/upb-generated/envoy/api/v2/core/base.upb.h,sha256=D4rWojUgqza3IHPjxUf1sPhu0HKfEM-2D0y7nSzsyyk,45131 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/upb-generated/envoy/api/v2/core/config_source.upb.h,sha256=FdXLXM88wsPbCY6UE8QGPiiJf5TXT1mfrVy3relTysY,20722 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/upb-generated/envoy/api/v2/core/grpc_service.upb.h,sha256=a8j42dNd7MezCKpQoiTe1LkHl5rkNk7pUMe3Nn6BFxI,53743 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/upb-generated/envoy/api/v2/core/health_check.upb.h,sha256=OoSwyUmJMmexTOw06eivNyUxoKItE_sHxLcpwm_HlNA,46286 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/upb-generated/envoy/api/v2/core/http_uri.upb.h,sha256=kWbxjMVJZFbZyFk0O7-cwtbk4YfnL4_CVDgwwaxUDWo,3835 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/upb-generated/envoy/api/v2/core/protocol.upb.h,sha256=w1_6EQTSWLS7JfsRhUfzAIXKm-W3hg4b6MFDU8EM8wI,22947 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/upb-generated/envoy/api/v2/discovery.upb.h,sha256=Aj-hEsTFfvh2RNz-DbKYcKJhvMykeX5ZSfFC1rvPW8c,27642 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/upb-generated/envoy/api/v2/eds.upb.h,sha256=vVfMxzNwT3rWfFf9iSN2bbAFpQl53thLKNc5g6X3hkY,18047 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/upb-generated/envoy/api/v2/endpoint/endpoint.upb.h,sha256=D3wVtk0tx9D0Ymu93A8n9sXzocsFFvilU9bgo-u2664,17750 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/upb-generated/envoy/api/v2/endpoint/load_report.upb.h,sha256=Sv1roHWj6Ilis0owUk7-LxUykUnyuBV0q_Hq4p0_dQo,25844 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/upb-generated/envoy/service/discovery/v2/ads.upb.h,sha256=74c27V4ps0ObhUtSOiFmJU-7CtfMSJPZas8ls1uwH9Y,1703 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/upb-generated/envoy/service/load_stats/v2/lrs.upb.h,sha256=yvMLhudwbB2ej-uvlAGq8Pi81GDGAtrl3UAw_hEXMUw,8463 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/upb-generated/envoy/type/http.upb.h,sha256=uUG-pQ1alzsGpoPieIAvDKjja8KWLnek09E1ihi9NlA,684 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/upb-generated/envoy/type/percent.upb.h,sha256=sQhGTVRrV8rm-lpQn9XtCNstYnLgatN-jLjyJgKXMrw,3441 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/upb-generated/envoy/type/range.upb.h,sha256=vMukF9pDpO1j8fmJGlV2zP5YYU1OS_KR5QOLrG4LTMs,3395 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/upb-generated/gogoproto/gogo.upb.h,sha256=9x7vRjF2W7NcqvBdiLwCUYPUuL9QXY5o1_4BeG4cUmY,563 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/upb-generated/google/api/annotations.upb.h,sha256=2H_YNJbfTGO3zP8GvWsLZJpQz1VDwUlVE0xIypDy71w,595 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/upb-generated/google/api/http.upb.h,sha256=Tk8ZxSr2NNyTTc4s1cuFGeYR214GRIZ_XWZs8bjX-dY,11196 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/upb-generated/google/protobuf/any.upb.h,sha256=sA_A8A4ef6P6pAFzgzyLb9Ggq3B2N_UAF7ocQyf_G94,1981 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/upb-generated/google/protobuf/descriptor.upb.h,sha256=69sQiYsmIwZamV11ogqxetaxuXAVEI2F0HvmMv_J-qg,130645 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/upb-generated/google/protobuf/duration.upb.h,sha256=atf_BnLnezPDPz-cd6qkHtGBJGThw5sUkUq2IoFLjGo,2090 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/upb-generated/google/protobuf/empty.upb.h,sha256=ecrjq1z6qMVFenx6dudrMJl6lC7Pd_6aWbRxgglFfKM,1429 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/upb-generated/google/protobuf/struct.upb.h,sha256=KWkVsbgMJDIeUk--VitALD0pzrVv2TNkxTcBe_IZxUE,12601 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/upb-generated/google/protobuf/timestamp.upb.h,sha256=06tBkLYHxXWCqnB6JbsSRH5OIzRBNw5SMuCcct-Jrks,2119 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/upb-generated/google/protobuf/wrappers.upb.h,sha256=PTo68sRfR5CXkpuN84Z1Y5_0YvLO_BBi4LlRg-NadIE,11726 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/upb-generated/google/rpc/status.upb.h,sha256=1H1iyW3YGryqJ54ZHB_z73ZCSSy5XzjbJdt0HsQm7y8,3071 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/upb-generated/src/proto/grpc/gcp/altscontext.upb.h,sha256=ITyUQgKrzwgzcQbOqY7Oug63SzINt9frSy3XoKMGXoQ,7323 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/upb-generated/src/proto/grpc/gcp/handshaker.upb.h,sha256=sUijpk3LRfxr55ykj6MjcfGu5DcFOkJ4VTX6fKaFv0A,45118 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/upb-generated/src/proto/grpc/gcp/transport_security_common.upb.h,sha256=mrBf9pBSZKtYqEvKNDItDWvE5i0GdoVx56HPloUpXG8,5638 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/upb-generated/src/proto/grpc/health/v1/health.upb.h,sha256=IJcXQuPBze2tNmkeXtJpKTqnEEOvbyXG_l-4aYs-rGQ,3702 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/upb-generated/src/proto/grpc/lb/v1/load_balancer.upb.h,sha256=dz7cDgLxpsZnuEGolblC2RXy_aifqStYU96txi_TTrs,24887 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/upb-generated/udpa/data/orca/v1/orca_load_report.upb.h,sha256=qbY8l99yLTvnM5Dw4Ix-wnIZSJcnxNeslJ3c5ikn3eg,9885 +tensorflow/include/external/com_github_grpc_grpc/src/core/ext/upb-generated/validate/validate.upb.h,sha256=r4OwVhXPydKWez9CJCDymB0T9hF0l9bfPJlYcu35r3Y,129449 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/avl/avl.h,sha256=RU1AMbhUoFEmipjHGResVeFmC4juHIla33av1GcRsSs,3600 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/backoff/backoff.h,sha256=hHiceqi3mJH-dVLLW05T8SayVvIhLJa9d7QWcrdKcKU,2604 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/channel/channel_args.h,sha256=h_zSe76D4nSiHTtpM6OP6bNLmzgM6UDcvO6-ReQ385k,5928 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/channel/channel_stack.h,sha256=JWZl5yL3mVtWWc9Or04Z9c6xJYLtU4ITKjhntU7pSoo,12486 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/channel/channel_stack_builder.h,sha256=ez1v2bM_8sByMS9JwvfBS6CnMWXpWC4s-7kYBKLKc2A,6739 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/channel/channel_trace.h,sha256=-cRP1e6UYBPMwr-uUC7JopARPDdX4P355CpztDF3-Fw,4450 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/channel/channelz.h,sha256=hcBtimvCp86UNkIPR9tCmUPsg604Kto5zi0MsldLswM,11384 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/channel/channelz_registry.h,sha256=pFv1GZ_iJXOi4oMvjjgTWglul6ZqzXvtETkUt6Ao9yc,3197 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/channel/connected_channel.h,sha256=kqqZ_THHK_YLhHnec-XyjcCipgVwJr6ZpCZgmzJwJLU,1183 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/channel/context.h,sha256=Z8zKUAvWnLTzjV_gs3erVC3PYDubh49w7-yYHJIR-gk,1488 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/channel/handshaker.h,sha256=ynmeIDhFz3ClhZ8nX5vsGYw7k5Gw4ui6fU5hLTfkNng,6721 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/channel/handshaker_factory.h,sha256=a4EQdaLHXCSJ0DBbkKlOqE4-a4CYzJvh1oxBRwvfrNI,1277 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/channel/handshaker_registry.h,sha256=qLwXBGByVG9dCrw4WCEWbzXLVWpwSKJbKOLoK0kgaJc,1754 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/channel/status_util.h,sha256=isdxYqzQ4FlkjMEHssruo7V7ecR0_t-E1A7JATvHD6c,1707 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/compression/algorithm_metadata.h,sha256=9Ll3PeKYHz-dz8Hz8waoexNOOwyNyVkuNWcWtY5vVhI,2304 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/compression/compression_args.h,sha256=2krxY3uin-llPHlkLeQy2MfBOdMd-ji3ErIr7FFf_sk,2258 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/compression/compression_internal.h,sha256=Va1AT4WlmujwJ9GUkFSV-hP2MgC3QPGTIVP5GEhCRk8,3069 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/compression/message_compress.h,sha256=Y19v114O5JvFZd0-UUk5U5w6-T_D9Usqx3Ld1QbI9a0,1546 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/compression/stream_compression.h,sha256=iQZwPRiDg_WAWuk_9-HH-aE8tynAMOyJckUMpg2s7Ds,4664 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/compression/stream_compression_gzip.h,sha256=ue7PptthAuzZJKxjNGHautSy7ejrvjQ5VNh244P0wEo,913 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/compression/stream_compression_identity.h,sha256=BsLl2M9BjNLmPQ9oGZx-pGEMyXq1-bdN1qbEteQ-ov4,929 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/debug/stats.h,sha256=s5iaYH2ONmI-MvO0cqJ75RmOYqPMGbHSjBm47mlMexE,2600 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/debug/stats_data.h,sha256=a6pF6jibb6U5WArBGx7dv8v0ubFFmpkjA5KctEGgAaY,31007 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/debug/trace.h,sha256=c7ygIp0EnqqtFR8CT11Z1kZsViUFEwFqbKVL9-NoV9w,3568 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/gpr/alloc.h,sha256=UTm2XPYsDrDvMdumMWa0SzsuCBeaBREsH8OFjLO_gK0,927 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/gpr/arena.h,sha256=FdnMzkKRzLf-LImhJJU-u05Nc0K7QdNrJIZ7Z8q9YrQ,1752 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/gpr/env.h,sha256=9QPHk7OI3Vp4a6zZnhprGG9Rl7eGI2AD8GSMYS68w2A,1297 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/gpr/murmur_hash.h,sha256=mcPy9GByo06rW_dOdmkH9PqmtvLtUUx3KDRL7T5IvUo,907 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/gpr/spinlock.h,sha256=hP-HirEzNmsUtZ_AGrZpj0WePhq_lfdE2YwxFd6lJaQ,1392 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/gpr/string.h,sha256=eo5Vqn7wMUxAsG76Jl3nVaJx1YjXiHS3yx6xUCSY6Jc,4821 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/gpr/string_windows.h,sha256=rNG9nvgvDOtY38b95Mup_Pfh8hUhjLUSpCxUIa4LyPE,987 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/gpr/time_precise.h,sha256=RT-BbG6f1UKBxgTmKrvm4wkkbAMMenwJkZ_1-Q_8mGY,2113 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/gpr/tls.h,sha256=RP0dCfyT4_HdFaMj4dmD2SdQIP1RkKr3svTB_ReU_qY,1797 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/gpr/tls_gcc.h,sha256=ZxiRCC5J_MLVx_iVkwz8Jaxc0hWNS1m-YCy4sT--Us0,1504 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/gpr/tls_msvc.h,sha256=slQecdUZiFDUabgOlMaH_kzs8efEq2ePDypMejzfWOY,1717 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/gpr/tls_pthread.h,sha256=s86bbR6NNoPacgQXFu8xo4Nr3ISKyuTa1cQFZ-2ZODM,1979 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/gpr/tmpfile.h,sha256=-4GMuTEfNOAvBaJHyNW33pVnAtuTaMLVm6xcQrapauQ,1098 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/gpr/useful.h,sha256=r8YUgQkMnQEswyQdWBxFMwc1HzA1GKzQsieo_l3g5xY,2269 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/gprpp/arena.h,sha256=Az27csV4qMRRvW-F2Hfij8dAgInNDmzoTPA3HfpyrY8,4288 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/gprpp/atomic.h,sha256=n2q5XFb6d2hnUOO0LEMYEAP3shUm0M1q6Paq0DUEKeA,3350 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/gprpp/debug_location.h,sha256=yNUDlDGlDiSfmspr21MSleh5FNvJuhuQBJhuy93LF7c,1668 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/gprpp/fork.h,sha256=rZWkGfol_r49VoKkpmu9B_P9y8gwH2jhgukz-bUvXME,2992 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/gprpp/global_config.h,sha256=wg6Kxpt36tHzNZFrXC_d6Iv4EH8VAY1WTTh4vOfLjEw,3474 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/gprpp/global_config_custom.h,sha256=IAVivSILqu_Umi30_cyC_XPpEgA9RfNPOz3VHeYDTxU,1011 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/gprpp/global_config_env.h,sha256=SIYxwrbT37-SG29hQj9FqB1WVQQXuzw4S846GkMrjuQ,4627 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/gprpp/global_config_generic.h,sha256=OPR6dYR0mt0DqW_POjVxHdLx73Jovl4mfB30F93ABpI,1532 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/gprpp/host_port.h,sha256=kdhbdQ5acsdQfvaUz0X6DCGkG13JUaDMg2W10CHIedA,2221 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/gprpp/inlined_vector.h,sha256=lYeqaRZL1rEWgHHJ-Kcq5f8UeF3PtFCnnl6HwH9hkUw,6175 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/gprpp/manual_constructor.h,sha256=mPMf2UY1nXtKOECL3prVsMSIR0WGTREcYgjKT95ll9Q,6609 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/gprpp/map.h,sha256=szUrB7M5kWvj44CJDKpmd4-Uk4Ozjrzq7D_YVAS6374,1641 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/gprpp/memory.h,sha256=DX9GVwElVmqblvzdCZ05_BtMagCWU2tMmL_vL27MYDs,1563 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/gprpp/mpscq.h,sha256=kzlJehYiMqgk-0I7InNs0t9-N8zpkP2Z0d5TsJrGd3o,3073 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/gprpp/optional.h,sha256=mqL4rNSFW5rMs0V1iJgiWqFp61DHeopbiDYx2ySGaPE,1602 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/gprpp/orphanable.h,sha256=K-SqienB9EfKPfLG_Hs22pDSPCT54AZFcJWOb1J8_GA,3937 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/gprpp/ref_counted.h,sha256=93ao_1nD90o3ZnD65_Ufm5C0SuzIUOUG7DzSB6jUUVA,10225 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/gprpp/ref_counted_ptr.h,sha256=jLp6ptKEU77ySK-8aM-hsLqD796h70N3tCs-AeyI7UI,5524 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/gprpp/string_view.h,sha256=G-0410-hn1iAtIe1BtvrvShfYENiJ_U6MeIvQDUqfPE,5183 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/gprpp/sync.h,sha256=f502wM1AbE9yAjShHNX_IdNVCNvHsh5aZLqrPBne9wQ,3341 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/gprpp/thd.h,sha256=bO20bgIesn8nqCNQQ-3lUK1y2nMciqRXEoiuezCZ-AE,5965 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/http/format_request.h,sha256=6wPupbApH9lrLzeau7_zbbXCmZtdZqF179YAZST3jT8,1231 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/http/httpcli.h,sha256=FC2rM5PAKdxPBfD65DE6S4UPeORs5HUXwQQccUqZboc,5452 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/http/parser.h,sha256=e53MNISLaIQZdG3lXPXkpwLuWoBjVLsepaZ83iJi2tQ,3211 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/block_annotate.h,sha256=Jg6Q461F1IZK0B-83R5Mh6F13zzP91YDMkKva5tKGlQ,2035 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/buffer_list.h,sha256=oIucBiJ9eY1VJxvCQm2yXv1t_vwAVqoafHAvbtkKWsE,6172 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/call_combiner.h,sha256=4TWiJM1nqWG9JrVBz4nsXK-Zm1LWu3eb_t2rU4o4-N4,8868 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/cfstream_handle.h,sha256=4CbN5N3gIXVNv8V2c5RUdrElG8JQGaJiBkg49qf2-tI,3037 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/closure.h,sha256=4ghyIq-UcNQ7XdIdF-h8kW-0H2TWfNxKNHPgUqXzSJg,7612 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/combiner.h,sha256=qPZaxdDjT-uHD5QZODxTLU5NFbQiy1IqkLI8hbLHkrQ,3157 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/dynamic_annotations.h,sha256=kN5gj9Aiah25eW34FiL3UviCmLuNqUZho33ctoBvWFA,2507 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/endpoint.h,sha256=-VK0YiM7zEwsn-KlHEUP9dm6pqqbj_Afl454kadz_9Y,4266 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/endpoint_cfstream.h,sha256=gdDGd2DBz5w0Id4PCp1BjO_zUnKMO4uqP79-ZPso23Y,1536 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/endpoint_pair.h,sha256=Fb2gtRxkjs7zkgaoGcZ_W7WfApIJ8g9prxiH86JktOc,1062 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/error.h,sha256=N1yObtKhZV4z12G8FLTwEcwL_uHr9b4LPChQuN1RGQI,11173 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/error_cfstream.h,sha256=rV50g1vETYf_Z772EedeQFThvFHkKbX6ugQdpWUwqo8,1179 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/error_internal.h,sha256=3z2k9xVk7uJ-ZU2VD-8IKt_uBS-_SvpMOK6j1vO-6q4,1945 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/ev_epoll1_linux.h,sha256=N2BgpmMNhyvOgIN4t-21ubDwlWVILHjS2I8oCVf2XZo,1027 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/ev_epollex_linux.h,sha256=U9Sy6kd7Wn-QEdFqiCWYIO9eJPSb1pIg78wtZVQfsIE,961 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/ev_poll_posix.h,sha256=VV8tJ4dIn0Y72J_rdA0z16AF6YjA_t-xh97L3uefNdc,988 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/ev_posix.h,sha256=xF17wojlFzKthJg9ngikalDbU762gCQBIVtis3Ra3EQ,8603 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/exec_ctx.h,sha256=4RRbtbU-KAuMxh3h3DlOk_d-0cCtzjCGrYwhhtPfzTQ,13369 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/executor.h,sha256=NDfmfVUk7pu_EtRkWfYx2HF8lHltIOqiyYeLdqq7XWA,3598 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/executor/mpmcqueue.h,sha256=7WiMiyRYJ1cEQM5fzIhgpeVYTOyzUesH5OEaIjKC608,6397 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/executor/threadpool.h,sha256=tSrsNTzWMehk2ROwB5cp66hCcqj1xda3F9uPJjFNm8c,5657 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/gethostname.h,sha256=62l53UBJpDOzWb0zFtkdECurD_GynTyR5eXzWzuGyD0,846 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/grpc_if_nametoindex.h,sha256=udRncvKuIujQP-7QKxkLiqfFrD_d35ZvZ4zobdvFjwE,1004 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/internal_errqueue.h,sha256=ve5_Ikvs0mrHH2EeJEWwNcoxyovVHUIctR_Z9OvD7iY,6950 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/iocp_windows.h,sha256=MKSsZZ6uuJj0FuOORiFJWV4cQ-4hesfRpTAjYqi9-rY,1305 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/iomgr.h,sha256=m8sdLexlT1SMr0BCQ8CqpXyokrsF3teMeXwGvpUnwdM,1989 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/iomgr_custom.h,sha256=CpcoBWGfiLUNW6nJmQ2rDGr-dYUrsUhqy7QUGvS9z8U,1710 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/iomgr_internal.h,sha256=1za368Q7pjD4mUhOG5EOHhh_EJyg5XVDJrihgdits68,2557 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/iomgr_posix.h,sha256=2pFAzzeVe7ZSTZHWG4qJR3jHx36bKWcN4S5X1Ao-PIw,825 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/is_epollexclusive_available.h,sha256=LQaf7WCjLj6xc_BBK0xkNmG7FzpfzWm5Eb2oFO--cuM,962 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/load_file.h,sha256=bOF44QBpFMPqZF3kuXOji417F9pzBhxQBv9briegpRc,1088 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/lockfree_event.h,sha256=XalBUVyVyU2yjDmZAcIAPPH08OxGk0rfSDKgWnAuSeo,2282 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/logical_thread.h,sha256=bKxxg1H8vdGnr2EuRRQnoP3Gat04ycDx91rA8kveWw0,1668 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/nameser.h,sha256=UMNr9nfI5EN5aRDHM_Jxj_wGIg7nwoHBeGpEXtXpK-o,4198 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/polling_entity.h,sha256=ttAEEUaO81nYRTaTlmbctMgJW7Y6g7FZNHTFOQSgveU,2431 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/pollset.h,sha256=scrIPcE1cxR6o6izyE2EgMrrUs7Q0DLZ79jEV21W1kM,3914 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/pollset_custom.h,sha256=HIV_y5y_bqbtWmw14IicgrFqLQ2y0i1fx5TCc_T-iHw,1040 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/pollset_set.h,sha256=LfDpJB5Oh71wePcEIpc_p_W7QJoLGikai9TNHZuumCQ,2285 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/pollset_set_custom.h,sha256=BKccD_1jY-a0dt9mB28zShcgBaU2zmnTyMm48SlVBLw,836 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/pollset_set_windows.h,sha256=DdmBTk-8DrcPZFK0en9Nb0PWfIOXRfKWimno_T14Pio,846 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/pollset_uv.h,sha256=r4ZrEkeKtTSggEU2E34UeKjB4kpMXxDj1jIDB9GA7_g,1024 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/pollset_windows.h,sha256=UfPsuk_lqV7GmBH9bCzjsKZ65i8qWbQcpj9Kv3NWoko,2010 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/port.h,sha256=4b2lE7IUt1sS0YHaBRZ_gek7gQ09E_RtHLCUNTxGSL4,7724 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/python_util.h,sha256=M23jauO9aKyIcqwR4KaTjN8NMsqGikUdGZYWTv_CuXA,1471 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/resolve_address.h,sha256=FPd5B2KQUHQLcKLpBQu2W0SqD7lfKkaQbF9pWULfgEk,2751 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/resolve_address_custom.h,sha256=NbwjMyznr4Gdimhbkr5ELqIyfhrVDkMgtRMCvSls1zs,1512 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/resource_quota.h,sha256=zp4JFjSu3evlOmBNJcWna72qp_z8INZIfBdDjy45qtE,8401 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/sockaddr.h,sha256=98oOASOTGj2-yc0sKuZX2ZEkV-kzItdNgAwTdtF2myc,1102 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/sockaddr_custom.h,sha256=iOhWd63YKXpDRrDZmJ_Egj0_UxjAMqUJjl3f-UNeruM,1531 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/sockaddr_posix.h,sha256=_fOpzeaf22TBx7kmOKVmJvdztBz2uV1M8pbG9jzu2Fc,1533 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/sockaddr_utils.h,sha256=JZ3Eip7MVB492sP-NIdPy1BtWe7UVNAaWCXzQPuGdNg,3406 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/sockaddr_windows.h,sha256=SyVeVJ6oAEjLkNejg2IEQs-yz8SzeMQUkjWTRrdUtlY,1502 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/socket_factory_posix.h,sha256=pqfLfNl3BrstUx0Zn9ydSyD6U1stqE3ZBFjFN-042uc,2689 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/socket_mutator.h,sha256=Rxe5wzgRs5FGxXR934l4t00U3Hzk9M9tJMx6LONUa1M,2219 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/socket_utils.h,sha256=8sbUs8s2K_1VzbkBxdc8PzxrqtgNj15E65Lu-_Exnjc,1563 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/socket_utils_posix.h,sha256=dGatWyIzdeEagPBRaeM4v7g4WUd9shuPRVbUbxyq9R8,6287 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/socket_windows.h,sha256=ocsfJUtyjhH0Mejz986tqLl7OwmZlKkzXvJ_Z9hqoqk,4900 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/sys_epoll_wrapper.h,sha256=Ox629jmer8Q8mmQMVnKejm8X4xkXsi-f3BP6H2Ht-lg,883 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/tcp_client.h,sha256=MDu3ohi1xGpBkC52jl7Qs6oI2GZXn9f99TaQFI1wE5Q,2068 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/tcp_client_posix.h,sha256=ud_wiZseY0Gegj1ddRdHwvxVPNIbs7um_zUwXNTogTU,2796 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/tcp_custom.h,sha256=8MQ5RLnP5eaaIhqY9sJLZ2bByACz2HQyYdJYVfvnd0o,3457 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/tcp_posix.h,sha256=es9SP7dHXZOP-SbrR-cNoIlwkZ6Ax9sdY-FgMn8OP58,2053 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/tcp_server.h,sha256=L-afxQsDGYtnDoLi2ktsB0VNMdnLLp2PTzassTdjAHQ,6076 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/tcp_server_utils_posix.h,sha256=GJzjdLXZvgLCXQszJVLZCyPZHLHP2mZdkFyEfJLk4dc,4567 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/tcp_windows.h,sha256=FLAe6Xuwskt10tpiTV92BnHolhA_T88MzvqtlgsB5u8,1613 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/time_averaged_stats.h,sha256=UwdzlTkWnIP-YjQ1bsbWZpi2Y_mxUX6QIn0JiyOf7qE,3513 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/timer.h,sha256=Qg7A4YZJbeUnH9wXME_Lj47DdaBHvxL4WyvjH791a-I,4720 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/timer_custom.h,sha256=KqUGW6VTpO1t-i7hyDFXDFD2jVs0xlAvfp3rIzMTktk,1252 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/timer_generic.h,sha256=TBTNu_fQuySvwknl6BJ0WUE-CFdC1wk6LcZgMMKUXHM,1118 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/timer_heap.h,sha256=A6U5fUqMIbLcwBVq8jO3FJPYaJEenDWFjUIL6w9IsCc,1395 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/timer_manager.h,sha256=dHIyUXiyl9VXygWqiXrCjjimTrCaEnuPzOhte1IFu0w,1447 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/udp_server.h,sha256=IceLzfDM1OMbvleOelTCTYbtdLYvajTEv1aAZovig-g,4152 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/unix_sockets_posix.h,sha256=43OUHLj8FbTx1rC-eTC-F-sGmVqw1S2fo8pc4KZ1gFg,1335 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/wakeup_fd_pipe.h,sha256=unh5ttRQqZ0SFgWeEvr_jx8qnUPbRiEOKG9OQHRDyys,899 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/iomgr/wakeup_fd_posix.h,sha256=yw2Zm68_2aNgQpK0LpeYbRg-L-f1ZwU8bShb1zsTeWY,3568 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/json/json.h,sha256=DpqpMCHV6zbazYDpl_8sLrzI0zqnuyV3IXTjTJlR88w,3846 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/profiling/timers.h,sha256=nDXBOBJyzzLTIW0IE8XjRLOhOf_zuILU9AiA1vvYXv8,3144 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/security/context/security_context.h,sha256=fWtsQkUEupcy74cvoB_iSdKCF4S0SkQDbSrPM2EZMmU,4970 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/security/credentials/alts/alts_credentials.h,sha256=C8ne0FiBNt4ZC6-qwxPE2I5dUGU0Zei998spxDAtGWw,4385 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/security/credentials/alts/check_gcp_environment.h,sha256=cpmb0ikGq5-Mr6d5Xzgmo25nAwAFQtFSxF8K4N-31PU,1781 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/security/credentials/alts/grpc_alts_credentials_options.h,sha256=ZJeJj1hohQ1Btvl823BoP_w2q2thRXce8Bn_mA-dEXo,2575 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/security/credentials/composite/composite_credentials.h,sha256=nMk1od8iS9sPSq3tMWxxWJhDie6OHYuuSGEEN2qLUDo,3781 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/security/credentials/credentials.h,sha256=bbEk6OsXGkmwL0iOWfDt1iQBnfWjIbzxvpROMeBC8ZU,12828 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/security/credentials/fake/fake_credentials.h,sha256=T5L9wOKWUxW5m1thBeXwaB4gHpFLRKjw52Sdf8PhVL4,3239 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/security/credentials/google_default/google_default_credentials.h,sha256=IE34hMSi7XusBaWEgXA1eRamQeoElzYu8uxu87XKr5Q,3096 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/security/credentials/iam/iam_credentials.h,sha256=dzFTvQNLdO3K_0xuYFt-O_CoC9drAnIEL7j9mlUZxZ8,1649 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/security/credentials/jwt/json_token.h,sha256=g8Ga3wYMqkg3l3x_-gBuWfmHsYigRM6hrNe5batDLKo,2627 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/security/credentials/jwt/jwt_credentials.h,sha256=oXnAI0SMwxsxnxAoEGO1s6KPDFrsnWq2lankI9GekDI,2511 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/security/credentials/jwt/jwt_verifier.h,sha256=OCeQnW6lF0_Ri30-FAMSoQKd0id4-vQGyzq7pCrw01U,4937 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/security/credentials/local/local_credentials.h,sha256=IS9O9nP1zZrdBQOUYN4qtz8wvoxBYHW0V1irdSqJw0Q,2112 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/security/credentials/oauth2/oauth2_credentials.h,sha256=8P5_rj4mzUNzmwx1LFa4-i37rcwiznLKaR7eaIoauuc,6056 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/security/credentials/plugin/plugin_credentials.h,sha256=JVAHyjXWc6Jc7QV_0kssnvyxe2pXZ-zUrbKEW4WS4Cc,2627 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/security/credentials/ssl/ssl_credentials.h,sha256=V_kAZrsCoWsmfBpIH3AEejYmLrmXXdXFP41_MFVr81U,3519 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/security/credentials/tls/grpc_tls_credentials_options.h,sha256=nUBoDsj780qqGcPpoVMQAhetIrAY_0wktgn8GkNh3eU,11163 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/security/credentials/tls/tls_credentials.h,sha256=4LcFrcu9_6GBJKY9mi3HUhleCZ7Vad7AdNCsPhUpUtU,2118 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/security/security_connector/alts/alts_security_connector.h,sha256=Zy4ltkLSQuwdj0bphehZ8qaKYQNE2Heo2lmpnCaiABk,2647 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/security/security_connector/fake/fake_security_connector.h,sha256=8DsYmCjhtcEgRbSbgew077khfSrBBm1fOLnz4X8Yh9A,1778 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/security/security_connector/load_system_roots.h,sha256=b073OyT05Xtoclekk9veEc7ABW2pF3s_jPNwj7lCBiI,965 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/security/security_connector/load_system_roots_linux.h,sha256=qHzFW14OySizKMoPtz2v1qQXDn8Y28Q0niUFvJ25hBA,1491 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/security/security_connector/local/local_security_connector.h,sha256=DUW31P4cq5ibyWVKxdywzWeBo1Ep509h94kS2LVemRU,2208 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/security/security_connector/security_connector.h,sha256=EM_Y7H0STTlr0UuvLGOk6Nvq9ic3hncBIYkTG1iQrME,6674 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/security/security_connector/ssl/ssl_security_connector.h,sha256=yIwnYR3RbpWn7Zim3xM-TWYhF-PNdWw88zzDHuADZlE,3249 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/security/security_connector/ssl_utils.h,sha256=0GFi56eIB5Ar0Ln9yt2UUewdqxhQJxi4vw8bJMM_KYw,6921 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/security/security_connector/ssl_utils_config.h,sha256=pHrYa1BM1hWDZplJOc87nj7CVT9FFd9Pw92LSlouURw,1047 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/security/security_connector/tls/tls_security_connector.h,sha256=y4nj4Bo4NjqRIPgee6kl70jmMWYNlw1v_3iN0MCtob8,6339 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/security/transport/auth_filters.h,sha256=Q_Wd9FcqP8lRB0Z0g4bvJEptBC7iTLRRtoE9GCpj4LE,1451 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/security/transport/secure_endpoint.h,sha256=yiMrICSXOLMVTjiYFytpn2BIRIy4qxwgJchdYBI59pg,1422 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/security/transport/security_handshaker.h,sha256=zrsWqLBhngDwUQ5zaNbHEzbum0eoMlrXfHlHBzDPKiI,1588 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/security/transport/target_authority_table.h,sha256=wpeSsckBv9Pl0e_fE8MqG0FY09_KlLVSgJ1BmAWttpo,1365 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/security/transport/tsi_error.h,sha256=UMOcKBJyqn44KwlF5Ppx2bpHupCsbs35gB4fWUh4Y2o,982 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/security/util/json_util.h,sha256=xB7LWGvhjDhA-l0eJpAJ2xHDuEtiFjNQENE1VWgLVRk,1574 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/slice/b64.h,sha256=e8Y9jkRpevfH9qkukUTAsxZPunWZFNwfD1qQVzjQ9eg,2000 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/slice/percent_encoding.h,sha256=AXJEz_hF0vRsQZlSFAwAt3oQ7f9cF57T6J_P3t27SC8,2936 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/slice/slice_hash_table.h,sha256=5ZyWuETeBcktDd8oemjiZhEJ8ZQfZXyP9RxWksFeSeo,6856 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/slice/slice_internal.h,sha256=bsg_pQxBW6gf4XtL_GxZZtuW21rn0gfFGstXmT7Fo9o,13048 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/slice/slice_string_helpers.h,sha256=qQInFVzBIO4H1_xhHFvd-h61e38c0azJBwU8_IK3l8s,1787 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/slice/slice_utils.h,sha256=3N759NdqSXNS4F1n_mkbRRUAEb3bmGDy5jsVPpJ0XNQ,7626 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/slice/slice_weak_hash_table.h,sha256=oauWwBKB-k53lAOwQeHUd45ZphFl7GCq9XPaKwianuo,3193 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/surface/api_trace.h,sha256=3F26UC9AB8hDtskaRrr3FFvTFOfHGpirgBoqlO1j0iA,2001 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/surface/call.h,sha256=CAzU55PeyhXmDJwLZDIUGOOGqiuvpQWgTuhlQvsbD74,4533 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/surface/call_test_only.h,sha256=KnQVUrQAxWLwiEDg6RqXE9Ty6tPUDJz-O7YgJoiO7SY,1460 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/surface/channel.h,sha256=mTPOeqnI6Hm6zUztoLNj9E_sppTbQ6RtiVwc3cH5lfU,4954 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/surface/channel_init.h,sha256=IfnVMI7J58tzpuPPa6S47-oTVA3rwDl8prADBupa69w,3460 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/surface/channel_stack_type.h,sha256=xS-I2aYH6oo7nrRcGaFOJwc07FUk4MT97XvKDdT-PIw,1560 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/surface/completion_queue.h,sha256=MQN0PsLpDgsvZPyh1J_kZea3ONElx_sXvDchsgv1-N8,3789 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/surface/completion_queue_factory.h,sha256=GvS_a7xid1htPHr22FlVYzf8CNShXFfs6_8NGtlofok,1295 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/surface/event_string.h,sha256=d_4GPplgUNSQvyLKSMaYAiAn9oGFkvsB5X6mu82pEJA,932 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/surface/init.h,sha256=poJ_Q4vPPTEPvY9tfrvSRO9UDyn_JrAVGKv1zxoIjVE,878 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/surface/lame_client.h,sha256=oM_fYljkutbPpJLCtCa6J4RtR816bFePa-5fQWmyiAY,884 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/surface/server.h,sha256=3mFreRbUodSylrfpVqWIw1aiDDvcY_I7UPDYKz1mwaE,2560 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/surface/validate_metadata.h,sha256=ywy-J6nLDSHQme3kApIDjHZMazYwk_r6csqsntsdLak,1491 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/transport/bdp_estimator.h,sha256=6c8jHnClSMdUsCPB64ecEPoADoSQ5AvIV1Uuw_GfoWE,2815 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/transport/byte_stream.h,sha256=wjuL-Uuzr5P0-QG4xUpKeIsVsiBZvkDv3CyszH5Udv8,4815 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/transport/connectivity_state.h,sha256=yHdiQzj5jqnb7fdyRxQBS4bW5blVbJmFEOMOc1XfWK0,4438 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/transport/error_utils.h,sha256=Npw_QbmuzVe2LBvCU5CS5kNuB8b4xuo9Cz3WMjwgTd4,1943 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/transport/http2_errors.h,sha256=eHyq2F4ygRDh78m5vAHcCX0Ct0OeqaWaTj9wvrRosmY,1387 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/transport/metadata.h,sha256=0qrrdBjupazLo2_Ly-6aStihVze9FeSECOWCJ5d6tXo,17341 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/transport/metadata_batch.h,sha256=VWDasHu3-10JCgaFhGJZZc5NV1jNeXEaS3KIjb8SYWk,7498 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/transport/pid_controller.h,sha256=t9pIs_TmsqjxbALiMNuHDNyyc73FhqSwHoati7-zfHs,3619 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/transport/static_metadata.h,sha256=q_Q8YOMNMhaWiTqa5iLi1pKGFy1oPZSOeEzug58df6A,25741 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/transport/status_conversion.h,sha256=x0ITyLMPka9H7v9cy438vEdMjojMWesUcyNIMSvABZg,1415 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/transport/status_metadata.h,sha256=Yr7yMwf6Pf2kyVIHSzCwi5MtPRBFOOlaP7ZFHY1NWx0,1515 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/transport/timeout_encoding.h,sha256=OHDHkZML8TE_MsRWbNBnm5pCFJ5jgMGMedHnpE8FAYY,1343 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/transport/transport.h,sha256=_SJg9TCh8ANoPwCy_Q5AedaFryXjo_I0kR8SqHKr2g4,18797 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/transport/transport_impl.h,sha256=IAjHhci2ImILw-itg8GLWw9D72zhP-xeY1hsmuo9Tls,2626 +tensorflow/include/external/com_github_grpc_grpc/src/core/lib/uri/uri_parser.h,sha256=uSz48hyuDcPKWyzuNg6zkMjFQwLDD_1MJMniRuKhM5c,1509 +tensorflow/include/external/com_github_grpc_grpc/src/core/tsi/alts/crypt/gsec.h,sha256=3a_D85xMGhKpGL_HqPrDl31EehHiGNcLz3hntFhp7E0,21873 +tensorflow/include/external/com_github_grpc_grpc/src/core/tsi/alts/frame_protector/alts_counter.h,sha256=GpinSUlO-gjYng-BcZX4kPy1bJlgVb3iy2BKXAGeq7I,3715 +tensorflow/include/external/com_github_grpc_grpc/src/core/tsi/alts/frame_protector/alts_crypter.h,sha256=B4WUPcEBu2Vsmm0ANkPgNrCEXbZvHQpNU9PFOBulYeU,11383 +tensorflow/include/external/com_github_grpc_grpc/src/core/tsi/alts/frame_protector/alts_frame_protector.h,sha256=BeNdK6R22kyDiJ3va5erYT5FuJomxPuRC0WolKbsl-g,2213 +tensorflow/include/external/com_github_grpc_grpc/src/core/tsi/alts/frame_protector/alts_record_protocol_crypter_common.h,sha256=RdkmFScw9d29uW0xxq54WPYfOy0JTDs4_qBlhcOQv5A,4508 +tensorflow/include/external/com_github_grpc_grpc/src/core/tsi/alts/frame_protector/frame_handler.h,sha256=cg8USJF2dIGovYRIlZUEIUOlv-b6r3RYFvz6AQXd0QQ,7993 +tensorflow/include/external/com_github_grpc_grpc/src/core/tsi/alts/handshaker/alts_handshaker_client.h,sha256=XGAWAYdsfsVMyPZrJ_T4GpLVsegpuq-2DtePAwguuAU,6305 +tensorflow/include/external/com_github_grpc_grpc/src/core/tsi/alts/handshaker/alts_shared_resource.h,sha256=qydE5WcvGz--9t6WLJWPRWXNf3XZh-y4rlUUcglCRHA,2473 +tensorflow/include/external/com_github_grpc_grpc/src/core/tsi/alts/handshaker/alts_tsi_handshaker.h,sha256=rSpUgysRrh7DgxKzD7kaFbenjsWh0OYcYNGcY_ySSgI,3833 +tensorflow/include/external/com_github_grpc_grpc/src/core/tsi/alts/handshaker/alts_tsi_handshaker_private.h,sha256=bhSI7InSZi6gH8D4Pt3AMWL8lLsLaxLkpm1IPqfERys,3185 +tensorflow/include/external/com_github_grpc_grpc/src/core/tsi/alts/handshaker/alts_tsi_utils.h,sha256=hUWHG5dp9IEtrBUhJTqd7Z7UvbUsN_lq3C2iMWRa3fs,1624 +tensorflow/include/external/com_github_grpc_grpc/src/core/tsi/alts/handshaker/transport_security_common_api.h,sha256=en3Fw5UR0jm7sXI4l79vGN4Z1FgQl4ean9_R-8skQJs,5822 +tensorflow/include/external/com_github_grpc_grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_integrity_only_record_protocol.h,sha256=kQSxb51lSE13AIl6OuKmEX5688y5pgV-12LI5mbEugM,2290 +tensorflow/include/external/com_github_grpc_grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_privacy_integrity_record_protocol.h,sha256=c7YXsMqqbC4hA1SvAXnFfugldQZBLNvCakV_0FcE-8E,1980 +tensorflow/include/external/com_github_grpc_grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_record_protocol.h,sha256=c3pzJUMcq1qhC8wMGRAcNfeuLU_ebxuWccPI25R0NV8,3608 +tensorflow/include/external/com_github_grpc_grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_record_protocol_common.h,sha256=HYut7Z8xA-L6w5TCIsgzzo3cHQ4XrsK13bJkdInD_jw,4286 +tensorflow/include/external/com_github_grpc_grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_iovec_record_protocol.h,sha256=T78cIygIZngsJjvbV8Q6015v-KNoPok6p9xlngJYDwU,8752 +tensorflow/include/external/com_github_grpc_grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_zero_copy_grpc_protector.h,sha256=kU4bSB_t9TtPIGkd63RKaPozBg7DzIWOSjEVI8zR4Ps,2474 +tensorflow/include/external/com_github_grpc_grpc/src/core/tsi/fake_transport_security.h,sha256=aHJca4b8ef56MqkwZn8mYGkXepnAiZw0Xieo-CgcuqQ,1803 +tensorflow/include/external/com_github_grpc_grpc/src/core/tsi/grpc_shadow_boringssl.h,sha256=D_LLxFjGBgKS9lG3YMOf2VEQuBdpvSrHwE4WTppQvX0,196265 +tensorflow/include/external/com_github_grpc_grpc/src/core/tsi/local_transport_security.h,sha256=uU40CAjOO_NXOOl62aIbvlUs4MqFctcKMOGz8N-Vuds,1679 +tensorflow/include/external/com_github_grpc_grpc/src/core/tsi/ssl/session_cache/ssl_session.h,sha256=P2rak5y6knT0oqSd5KiWGjlVEcopCc6NoCQI6aONCPo,2361 +tensorflow/include/external/com_github_grpc_grpc/src/core/tsi/ssl/session_cache/ssl_session_cache.h,sha256=1Gnn6S-Xxky0NOfL4IVl6a7ag3OXrZ7C17dIsQvwQ2w,2825 +tensorflow/include/external/com_github_grpc_grpc/src/core/tsi/ssl_transport_security.h,sha256=vgRH9CiMgpVpYmWWVOL60J7h0cr2fTzcaj2yYN5TKlU,15573 +tensorflow/include/external/com_github_grpc_grpc/src/core/tsi/ssl_types.h,sha256=SJE1z_Zso_J59SKrvLYClbH5FNMGlo6FB6YvLl-Jxdg,1365 +tensorflow/include/external/com_github_grpc_grpc/src/core/tsi/transport_security.h,sha256=Nb3hAxqBKiAFYuWOYY-ZnDkLK1YYL4bfX_ImwzH1jmE,5923 +tensorflow/include/external/com_github_grpc_grpc/src/core/tsi/transport_security_grpc.h,sha256=MKaBkHNY-E2cSSNJ0oxoNO4mA33hmjbsn1hBmoS62lU,3372 +tensorflow/include/external/com_github_grpc_grpc/src/core/tsi/transport_security_interface.h,sha256=HmyiLfJ6LR2lsn6t4W9caoA0Vku9w8bg6O7-9GG1-cE,21263 +tensorflow/include/external/com_github_grpc_grpc/src/cpp/client/create_channel_internal.h,sha256=8IiBhAbJN7j0OPaYIcGkUA2xuZ7z6UMNA7N98QHxbN0,1216 +tensorflow/include/external/com_github_grpc_grpc/src/cpp/client/secure_credentials.h,sha256=Esyi_s7QOpYqWo1lESKntSYv9oXvbGO8KKPXBL3qksg,3810 +tensorflow/include/external/com_github_grpc_grpc/src/cpp/common/channel_filter.h,sha256=nrnr8weOvJBg35tGNDgh0s1FpEIX0x6HIR2QMoOswj8,14624 +tensorflow/include/external/com_github_grpc_grpc/src/cpp/common/secure_auth_context.h,sha256=1PQ83r0Ln20DPD8rlNNzcmEhBorF-QYK6KuhKKYxb8c,1801 +tensorflow/include/external/com_github_grpc_grpc/src/cpp/common/tls_credentials_options_util.h,sha256=GSb8QgmXChqE1c-Y1kOLmb3qNdp-xvI78n0GVVj66Ck,2212 +tensorflow/include/external/com_github_grpc_grpc/src/cpp/server/dynamic_thread_pool.h,sha256=ZILgBDSu6tsHqsk-BsFTiv3FFMe3D5aQrE5FloyJQ6Y,1767 +tensorflow/include/external/com_github_grpc_grpc/src/cpp/server/external_connection_acceptor_impl.h,sha256=3MZAQqyF7x3u-jR_YJunEdfqlB8jLwE88oLYSgrv0ZI,2186 +tensorflow/include/external/com_github_grpc_grpc/src/cpp/server/health/default_health_check_service.h,sha256=hkIjcYNyE1GZBxoChz2j_vIilw00lMJp6t31RXoS6J0,10756 +tensorflow/include/external/com_github_grpc_grpc/src/cpp/server/secure_server_credentials.h,sha256=WT4N1fdWkOf6VCy-eW4UTU9xjiRa89WBS2nVurHkdn4,2665 +tensorflow/include/external/com_github_grpc_grpc/src/cpp/server/thread_pool_interface.h,sha256=TpL_zgo1vKvixTkptUK3ds3e60Maou4A0kLjTp64T0A,1288 +tensorflow/include/external/com_github_grpc_grpc/src/cpp/thread_manager/thread_manager.h,sha256=k_7L5eOs8XcrEs3876Bn31U1LuSrdQZefeW7mlOcnHU,6704 +tensorflow/include/external/com_github_grpc_grpc/third_party/address_sorting/address_sorting_internal.h,sha256=fQ0wwflfwUUvzAFED7O5shw4pfqdezaAR2faQs0Ates,2804 +tensorflow/include/external/com_github_grpc_grpc/third_party/address_sorting/include/address_sorting/address_sorting.h,sha256=fWYwfI1yPPGfeBqfQc5s7VsRwoXB6ftA5W3sHd83AOI,4503 +tensorflow/include/external/com_google_absl/LICENSE,sha256=x5p_6g48rATNQ_IOe2SOWg_4-lNE5kSw7gnKEWK2J0c,11361 +tensorflow/include/external/com_google_protobuf/LICENSE,sha256=bl4RcySv2UTc9n82zzKYQ7wakiKajNm7Vz16gxMP6n0,1732 +tensorflow/include/external/com_googlesource_code_re2/re2/bitmap256.h,sha256=ftNfAEj87fQu2QCDeCXisGuXa0eAmPx6y_ayM9l0nlk,1837 +tensorflow/include/external/com_googlesource_code_re2/re2/filtered_re2.h,sha256=HqIQSZ7LY3zQyOvF8g0MO-Aml-SqD2FOvIMYEnCSJ_U,4281 +tensorflow/include/external/com_googlesource_code_re2/re2/pod_array.h,sha256=Gbv_xWHxBfBbglQXaZMKcUbNs7B8cQD6m94uMyFkknM,1052 +tensorflow/include/external/com_googlesource_code_re2/re2/prefilter.h,sha256=xqV53cSEWdI9Rdotfu3LUuFc9yEW6oUF-_IZAOPX3aQ,3881 +tensorflow/include/external/com_googlesource_code_re2/re2/prefilter_tree.h,sha256=GypKEiyanXeOio-4t_nLP0Yqm093hf_rikVjMq-0yno,5294 +tensorflow/include/external/com_googlesource_code_re2/re2/prog.h,sha256=NaL_Rvz1VsCQExYhUlkhvMwdYttmVLqBzUhgA3VjcXA,19420 +tensorflow/include/external/com_googlesource_code_re2/re2/re2.h,sha256=njiSFzDwKIPeeUWTtJNCjq9r85TtLEhFJgSAUSbYmFs,41787 +tensorflow/include/external/com_googlesource_code_re2/re2/regexp.h,sha256=mmMIzGNdIZ3soEp70KWAFW7LdB4jMIMeeYwYuSZ_N-s,24163 +tensorflow/include/external/com_googlesource_code_re2/re2/set.h,sha256=HKVpBQkUwWXFrxbzEYxduukpJd5OXhcrj7-mmn__VII,2518 +tensorflow/include/external/com_googlesource_code_re2/re2/sparse_array.h,sha256=L8v_On7cyieoZbAX-1Z31Huq8CCR_STy6k2TTnqsA0Q,11974 +tensorflow/include/external/com_googlesource_code_re2/re2/sparse_set.h,sha256=Zp-SWVzIRSbf4fAAALCeDJ-_yxJyrZbMpp5wfmyLzK8,7140 +tensorflow/include/external/com_googlesource_code_re2/re2/stringpiece.h,sha256=Yq0Eq86gFnwrSOab55RQZPGxn5OvKmrF6WgWBjxZmXE,1004 +tensorflow/include/external/com_googlesource_code_re2/re2/unicode_casefold.h,sha256=0lZTndE8cNaUcmH6TNdjuABo71Hpzzz1NDmtdgHsagk,2539 +tensorflow/include/external/com_googlesource_code_re2/re2/unicode_groups.h,sha256=Qv14UhdNQ1cGhPkExezW8Ia_gazYnS16uXsVNYOAucU,1525 +tensorflow/include/external/com_googlesource_code_re2/re2/walker-inl.h,sha256=RmxiMWTEgIrVUCasEBP_WNDe8jEyP9BjPdyR_-2QO6s,7803 +tensorflow/include/external/com_googlesource_code_re2/util/logging.h,sha256=8U-3d-ujMBuE9h7lH9IBqv0yA1VCS7XGo90L0aa7R5s,2898 +tensorflow/include/external/com_googlesource_code_re2/util/strutil.h,sha256=JHu2WlXWx1JBvv0dvPkoKnOOF6aZ7YTKB9YFZaICFRw,339 +tensorflow/include/external/com_googlesource_code_re2/util/utf.h,sha256=0GOePuPS0OkC4TPmYBTzHA40t5WZUvLeU0yTfJlg5Us,1516 +tensorflow/include/external/cub_archive/LICENSE.TXT,sha256=_xsrMOa_IulVKNtn06_05D4XybrA4Oj6YbLMYvYNUmI,1600 +tensorflow/include/external/cudnn_frontend_archive/_virtual_includes/cudnn_frontend/third_party/cudnn_frontend/include/contrib/nlohmann/json/LICENSE.txt,sha256=yYPWlSM3eBnbPDd7OQ1WRPXsU77Jt8Sg8e2JO7dD0EU,1076 +tensorflow/include/external/cudnn_frontend_archive/_virtual_includes/cudnn_frontend/third_party/cudnn_frontend/include/contrib/nlohmann/json/json.hpp,sha256=KYrZBr1miU9fWvbMJmf72v0SC1uJBIJdRyRKF8ZeDMo,957790 +tensorflow/include/external/cudnn_frontend_archive/_virtual_includes/cudnn_frontend/third_party/cudnn_frontend/include/cudnn_backend_base.h,sha256=qqftxKRsBks0n1R3xl5DSnJyHeFUc3m7Af5tFYAUsiQ,5651 +tensorflow/include/external/cudnn_frontend_archive/_virtual_includes/cudnn_frontend/third_party/cudnn_frontend/include/cudnn_frontend.h,sha256=5clr8uqRZcV6llEfmhd-_xqV7qp_PwaPZINd1__-xVo,6992 +tensorflow/include/external/cudnn_frontend_archive/_virtual_includes/cudnn_frontend/third_party/cudnn_frontend/include/cudnn_frontend_ConvDesc.h,sha256=RqFQqgYEVo_qAy3i3xAMHI0yrP60Ouwome7rEqBCaR0,13996 +tensorflow/include/external/cudnn_frontend_archive/_virtual_includes/cudnn_frontend/third_party/cudnn_frontend/include/cudnn_frontend_Engine.h,sha256=JXGAZfTjjhZQIBq_aGV7Q91VLIxulHBJ4ZULKx9OFzU,13089 +tensorflow/include/external/cudnn_frontend_archive/_virtual_includes/cudnn_frontend/third_party/cudnn_frontend/include/cudnn_frontend_EngineConfig.h,sha256=zw_QnajlRJ53V8mzlj9_NgbdrumQGOW0zMX-9ixTU8Y,10543 +tensorflow/include/external/cudnn_frontend_archive/_virtual_includes/cudnn_frontend/third_party/cudnn_frontend/include/cudnn_frontend_EngineConfigGenerator.h,sha256=us5yw8UQoTB-JbhPM_xQWrv_TEGQWd6b-i_vm0wYJWw,5524 +tensorflow/include/external/cudnn_frontend_archive/_virtual_includes/cudnn_frontend/third_party/cudnn_frontend/include/cudnn_frontend_EngineFallbackList.h,sha256=5Wfq7E0ScKqtwrq4_3TYdsyuPdiQZF51GfkT29B2nH8,8052 +tensorflow/include/external/cudnn_frontend_archive/_virtual_includes/cudnn_frontend/third_party/cudnn_frontend/include/cudnn_frontend_Errata.h,sha256=ucIs980R9au4Bd1jGez4lCOQHeaYP3kpLfqaQPhVPds,12823 +tensorflow/include/external/cudnn_frontend_archive/_virtual_includes/cudnn_frontend/third_party/cudnn_frontend/include/cudnn_frontend_ExecutionPlan.h,sha256=HY1xUun_78jyUl1gdk4I3-TZ4l-WYjF16_KWb88jkT8,28121 +tensorflow/include/external/cudnn_frontend_archive/_virtual_includes/cudnn_frontend/third_party/cudnn_frontend/include/cudnn_frontend_ExecutionPlanCache.h,sha256=zdgBZjn39x2pw_LTXWRRChsT7fte0JBCwpuL2J4omm4,7620 +tensorflow/include/external/cudnn_frontend_archive/_virtual_includes/cudnn_frontend/third_party/cudnn_frontend/include/cudnn_frontend_Filters.h,sha256=Ld1mmf1if5Pd9WneXHk9H9gD11wdrw56Nh2dvgsXawc,4742 +tensorflow/include/external/cudnn_frontend_archive/_virtual_includes/cudnn_frontend/third_party/cudnn_frontend/include/cudnn_frontend_Heuristics.h,sha256=lflUt7mCQqI3QjaILmdU-C2lc3EXWXwY2bssbLAtZPc,17711 +tensorflow/include/external/cudnn_frontend_archive/_virtual_includes/cudnn_frontend/third_party/cudnn_frontend/include/cudnn_frontend_Logging.h,sha256=CnSCH7SWyQrBXMS-yhd9SLvaj6Y99JO7f-9SIJW6pZk,3232 +tensorflow/include/external/cudnn_frontend_archive/_virtual_includes/cudnn_frontend/third_party/cudnn_frontend/include/cudnn_frontend_MatMulDesc.h,sha256=Kh36sF0ffg0UZ_mhnUxuTub3Uhq9MHCyKFug30v0G18,6371 +tensorflow/include/external/cudnn_frontend_archive/_virtual_includes/cudnn_frontend/third_party/cudnn_frontend/include/cudnn_frontend_Operation.h,sha256=UlLaBzeXJX5e7r6BkfOYNrkAbFEY1uUApx2H8RgoqWQ,134612 +tensorflow/include/external/cudnn_frontend_archive/_virtual_includes/cudnn_frontend/third_party/cudnn_frontend/include/cudnn_frontend_OperationGraph.h,sha256=maz4v_4vAt7ksl634SEhJkE9qEvR2R7pBlpk7-BsrEE,10325 +tensorflow/include/external/cudnn_frontend_archive/_virtual_includes/cudnn_frontend/third_party/cudnn_frontend/include/cudnn_frontend_PointWiseDesc.h,sha256=M1WQpLoF89HO_Ik3CHGiqK6F19qF-ppTqzOEH4S6sHs,18680 +tensorflow/include/external/cudnn_frontend_archive/_virtual_includes/cudnn_frontend/third_party/cudnn_frontend/include/cudnn_frontend_ReductionDesc.h,sha256=vNABAVj3wumUYHV_1PsxEbmOnMgYjlDS8oqnsXOpf0o,6361 +tensorflow/include/external/cudnn_frontend_archive/_virtual_includes/cudnn_frontend/third_party/cudnn_frontend/include/cudnn_frontend_Reorder_Tensor.h,sha256=cNbqB1g3cH5s50uC0k-rX4jsaglOjukGFbKG7H96vEo,3607 +tensorflow/include/external/cudnn_frontend_archive/_virtual_includes/cudnn_frontend/third_party/cudnn_frontend/include/cudnn_frontend_Resample.h,sha256=9pyMDtnFv-QQkSOwBvjWKCl1hJnwhn86OD4prjvfsLE,20494 +tensorflow/include/external/cudnn_frontend_archive/_virtual_includes/cudnn_frontend/third_party/cudnn_frontend/include/cudnn_frontend_Rng.h,sha256=7bFfz0xZeGUSynL0T01lHIwF8L-JOOA3-orNEl-puQo,11700 +tensorflow/include/external/cudnn_frontend_archive/_virtual_includes/cudnn_frontend/third_party/cudnn_frontend/include/cudnn_frontend_Tensor.h,sha256=2TZYjSC7HVU3jJo6go8id0xInLMVSsNVGlAyMDOjlSI,20313 +tensorflow/include/external/cudnn_frontend_archive/_virtual_includes/cudnn_frontend/third_party/cudnn_frontend/include/cudnn_frontend_VariantPack.h,sha256=SR33YMJKdwh8Du8I55RUfgQnHPZW6Nit5i74Po1XaCk,7973 +tensorflow/include/external/cudnn_frontend_archive/_virtual_includes/cudnn_frontend/third_party/cudnn_frontend/include/cudnn_frontend_find_plan.h,sha256=_bQzUu1RKVhFpLnTd5YAj7cV9Ipo870aSijdGpXpZTk,6784 +tensorflow/include/external/cudnn_frontend_archive/_virtual_includes/cudnn_frontend/third_party/cudnn_frontend/include/cudnn_frontend_get_plan.h,sha256=XrnTse6PrHKMGemtXhMSD482MNwnEqTCKKZ2hxfYuiA,2318 +tensorflow/include/external/cudnn_frontend_archive/_virtual_includes/cudnn_frontend/third_party/cudnn_frontend/include/cudnn_frontend_utils.h,sha256=Zk-aXoHHes2OzCKp2WnphXqkFmhF_-6djHtC5rjJvnk,24731 +tensorflow/include/external/cudnn_frontend_archive/include/contrib/nlohmann/json/LICENSE.txt,sha256=yYPWlSM3eBnbPDd7OQ1WRPXsU77Jt8Sg8e2JO7dD0EU,1076 +tensorflow/include/external/cudnn_frontend_archive/include/contrib/nlohmann/json/json.hpp,sha256=KYrZBr1miU9fWvbMJmf72v0SC1uJBIJdRyRKF8ZeDMo,957790 +tensorflow/include/external/cudnn_frontend_archive/include/cudnn_backend_base.h,sha256=qqftxKRsBks0n1R3xl5DSnJyHeFUc3m7Af5tFYAUsiQ,5651 +tensorflow/include/external/cudnn_frontend_archive/include/cudnn_frontend.h,sha256=5clr8uqRZcV6llEfmhd-_xqV7qp_PwaPZINd1__-xVo,6992 +tensorflow/include/external/cudnn_frontend_archive/include/cudnn_frontend_ConvDesc.h,sha256=RqFQqgYEVo_qAy3i3xAMHI0yrP60Ouwome7rEqBCaR0,13996 +tensorflow/include/external/cudnn_frontend_archive/include/cudnn_frontend_Engine.h,sha256=JXGAZfTjjhZQIBq_aGV7Q91VLIxulHBJ4ZULKx9OFzU,13089 +tensorflow/include/external/cudnn_frontend_archive/include/cudnn_frontend_EngineConfig.h,sha256=zw_QnajlRJ53V8mzlj9_NgbdrumQGOW0zMX-9ixTU8Y,10543 +tensorflow/include/external/cudnn_frontend_archive/include/cudnn_frontend_EngineConfigGenerator.h,sha256=us5yw8UQoTB-JbhPM_xQWrv_TEGQWd6b-i_vm0wYJWw,5524 +tensorflow/include/external/cudnn_frontend_archive/include/cudnn_frontend_EngineFallbackList.h,sha256=5Wfq7E0ScKqtwrq4_3TYdsyuPdiQZF51GfkT29B2nH8,8052 +tensorflow/include/external/cudnn_frontend_archive/include/cudnn_frontend_Errata.h,sha256=ucIs980R9au4Bd1jGez4lCOQHeaYP3kpLfqaQPhVPds,12823 +tensorflow/include/external/cudnn_frontend_archive/include/cudnn_frontend_ExecutionPlan.h,sha256=HY1xUun_78jyUl1gdk4I3-TZ4l-WYjF16_KWb88jkT8,28121 +tensorflow/include/external/cudnn_frontend_archive/include/cudnn_frontend_ExecutionPlanCache.h,sha256=zdgBZjn39x2pw_LTXWRRChsT7fte0JBCwpuL2J4omm4,7620 +tensorflow/include/external/cudnn_frontend_archive/include/cudnn_frontend_Filters.h,sha256=Ld1mmf1if5Pd9WneXHk9H9gD11wdrw56Nh2dvgsXawc,4742 +tensorflow/include/external/cudnn_frontend_archive/include/cudnn_frontend_Heuristics.h,sha256=lflUt7mCQqI3QjaILmdU-C2lc3EXWXwY2bssbLAtZPc,17711 +tensorflow/include/external/cudnn_frontend_archive/include/cudnn_frontend_Logging.h,sha256=CnSCH7SWyQrBXMS-yhd9SLvaj6Y99JO7f-9SIJW6pZk,3232 +tensorflow/include/external/cudnn_frontend_archive/include/cudnn_frontend_MatMulDesc.h,sha256=Kh36sF0ffg0UZ_mhnUxuTub3Uhq9MHCyKFug30v0G18,6371 +tensorflow/include/external/cudnn_frontend_archive/include/cudnn_frontend_Operation.h,sha256=UlLaBzeXJX5e7r6BkfOYNrkAbFEY1uUApx2H8RgoqWQ,134612 +tensorflow/include/external/cudnn_frontend_archive/include/cudnn_frontend_OperationGraph.h,sha256=maz4v_4vAt7ksl634SEhJkE9qEvR2R7pBlpk7-BsrEE,10325 +tensorflow/include/external/cudnn_frontend_archive/include/cudnn_frontend_PointWiseDesc.h,sha256=M1WQpLoF89HO_Ik3CHGiqK6F19qF-ppTqzOEH4S6sHs,18680 +tensorflow/include/external/cudnn_frontend_archive/include/cudnn_frontend_ReductionDesc.h,sha256=vNABAVj3wumUYHV_1PsxEbmOnMgYjlDS8oqnsXOpf0o,6361 +tensorflow/include/external/cudnn_frontend_archive/include/cudnn_frontend_Reorder_Tensor.h,sha256=cNbqB1g3cH5s50uC0k-rX4jsaglOjukGFbKG7H96vEo,3607 +tensorflow/include/external/cudnn_frontend_archive/include/cudnn_frontend_Resample.h,sha256=9pyMDtnFv-QQkSOwBvjWKCl1hJnwhn86OD4prjvfsLE,20494 +tensorflow/include/external/cudnn_frontend_archive/include/cudnn_frontend_Rng.h,sha256=7bFfz0xZeGUSynL0T01lHIwF8L-JOOA3-orNEl-puQo,11700 +tensorflow/include/external/cudnn_frontend_archive/include/cudnn_frontend_Tensor.h,sha256=2TZYjSC7HVU3jJo6go8id0xInLMVSsNVGlAyMDOjlSI,20313 +tensorflow/include/external/cudnn_frontend_archive/include/cudnn_frontend_VariantPack.h,sha256=SR33YMJKdwh8Du8I55RUfgQnHPZW6Nit5i74Po1XaCk,7973 +tensorflow/include/external/cudnn_frontend_archive/include/cudnn_frontend_find_plan.h,sha256=_bQzUu1RKVhFpLnTd5YAj7cV9Ipo870aSijdGpXpZTk,6784 +tensorflow/include/external/cudnn_frontend_archive/include/cudnn_frontend_get_plan.h,sha256=XrnTse6PrHKMGemtXhMSD482MNwnEqTCKKZ2hxfYuiA,2318 +tensorflow/include/external/cudnn_frontend_archive/include/cudnn_frontend_utils.h,sha256=Zk-aXoHHes2OzCKp2WnphXqkFmhF_-6djHtC5rjJvnk,24731 +tensorflow/include/external/curl/COPYING,sha256=sdf-uUnqUCNVICn74L9dtPI8L4XpuOUeGFNvDsv5xSQ,1088 +tensorflow/include/external/curl/include/curl/curl.h,sha256=z7KDXzNwVTrP12DrQCI9rBaSKCC6gG6RfSTdWUs_X9c,128982 +tensorflow/include/external/curl/include/curl/curlver.h,sha256=olmAI6X-XK3rGavpNUaFoOpWLR9ZtkDv-8Y0QtS36VI,3044 +tensorflow/include/external/curl/include/curl/easy.h,sha256=CJDgY9K-qLqBXXR9T2ZZlOJj4QQ_DhSoVzPJRFy4Om0,4013 +tensorflow/include/external/curl/include/curl/header.h,sha256=YUvkiob05dMExapA7xyFJF4luXcykhw2MYQBRmadmS8,2910 +tensorflow/include/external/curl/include/curl/mprintf.h,sha256=a9CEOfQMKepUxrj16XMbDjGj7YzG0XrBhGKjKauIbMI,2704 +tensorflow/include/external/curl/include/curl/multi.h,sha256=Sk3X7TGICNzquKt7EFNXghuQMrptBYmMFLT8iRiB_1c,17769 +tensorflow/include/external/curl/include/curl/options.h,sha256=VxYBjSfngyg4Jb7SqKBRGQSHci_etkt6otA6mX6ZuNE,2401 +tensorflow/include/external/curl/include/curl/stdcheaders.h,sha256=11iLhoFKNf_Ddm_2JC5vZwXgRAH8nCCKGVyv81A6-Bw,1362 +tensorflow/include/external/curl/include/curl/system.h,sha256=tSDLx4VbKEqYARi7ZS6jngZU03LDzVCChUGDh9NrTgE,19611 +tensorflow/include/external/curl/include/curl/typecheck-gcc.h,sha256=G29ygxfEUcDevfDyRMnoW9mFVmcX4yxEQXqfq-cWmfc,43548 +tensorflow/include/external/curl/include/curl/urlapi.h,sha256=2WPSFhRoBuO3kzzjEklFMEt8zIlABvvPUQJh4khAmyg,5480 +tensorflow/include/external/curl/include/curl/websockets.h,sha256=tYux1-2j_SNy_rTYVsJWiX2DAG3-eTPWm-VLxKK6Wj8,2741 +tensorflow/include/external/curl/include/curl_config.h,sha256=cmIQxnOAx5ptigeWM47BZCrelW0Ix5gWcMe-qCtECWE,7380 +tensorflow/include/external/curl/lib/altsvc.h,sha256=md-G3_y9s4c4e68AmZeCmv267zt0MYZjJeQsYa_u0zk,2799 +tensorflow/include/external/curl/lib/amigaos.h,sha256=JIEraBD7rWPD1KakJ2zfL0hzdzO5MS1a7khP-ukIsCQ,1436 +tensorflow/include/external/curl/lib/arpa_telnet.h,sha256=OAcbLUNfw7rHnB-g3jAnjd5cyXDrQOPIWouL7Q5mjcc,4099 +tensorflow/include/external/curl/lib/asyn.h,sha256=Qad5KnXDHM6xVuUF8WQnC3Iro87P26Z3fOQDINQTTSE,6704 +tensorflow/include/external/curl/lib/bufq.h,sha256=gomKHJiypXZ8NzU-7hLDSMLPu_ybEeHnejjNpjHXhHc,10151 +tensorflow/include/external/curl/lib/bufref.h,sha256=3Bf0EsQiCUlLZCLnZQJ-crDd4KuwQPCGjb9i-U4cCXU,1827 +tensorflow/include/external/curl/lib/c-hyper.h,sha256=LEYPEtC0H29HqCXN9Nyf3_qxoyu_3Mr4CpCXqNUN-hg,2169 +tensorflow/include/external/curl/lib/cf-h1-proxy.h,sha256=lgR2t9fx4mDW59XvIvVB_-5uxZoWl3IC30QQ7Q0FKsg,1465 +tensorflow/include/external/curl/lib/cf-h2-proxy.h,sha256=QHycahrttOYRmggRa_xGAjddUZz5BRF9n40YaMadYa8,1469 +tensorflow/include/external/curl/lib/cf-haproxy.h,sha256=N9m7o-0mF3UOjPr0TI1VBbqkrSHdJvlrLk3187_XPE4,1438 +tensorflow/include/external/curl/lib/cf-https-connect.h,sha256=ELMn8BxiBxQaSdt9_BHHWokx9YOsVIRKxqH9eYBPiS8,2235 +tensorflow/include/external/curl/lib/cf-socket.h,sha256=_wrSXdYHh34Wch07CKwvlUbzv4XnsPVOnpFpWRvlE58,6843 +tensorflow/include/external/curl/lib/cfilters.h,sha256=2cyhJWDb-y7LiePD0IUHYjNz6DE-1wZyRKdYbNC90Dk,21898 +tensorflow/include/external/curl/lib/config-amigaos.h,sha256=Pc-3ArCRMkH4cnRECV5HXYJt2kIZNpZc0RIsoV_-3Xg,3453 +tensorflow/include/external/curl/lib/config-dos.h,sha256=ltCkhc2mMdc7nHV-qMNFZ8sEm7PZc3FCNTHgm4kVIv4,3948 +tensorflow/include/external/curl/lib/config-mac.h,sha256=wjDsuZ_basrQXHK-Ueqg652tdpS5LIs6NlLPjI-SQjs,3209 +tensorflow/include/external/curl/lib/config-os400.h,sha256=rtYUQJ8MdO4CkRVX1kATj_oheaSVQygKSL9w6ORX6EY,9988 +tensorflow/include/external/curl/lib/config-plan9.h,sha256=_TOG7WrhOJXtDbBpT7CgQEhBzk10sRqLfLWhXxN21j0,3909 +tensorflow/include/external/curl/lib/config-riscos.h,sha256=yyjEoQJBNyYBEalnvzidHzwBrilhsNeKDc_UTiIVBr4,7749 +tensorflow/include/external/curl/lib/config-win32.h,sha256=v8vTHuVpyMdmKCL3UIybDTssTMnPARjdN2ZDqXcgbUY,19779 +tensorflow/include/external/curl/lib/config-win32ce.h,sha256=nmc0dxQafU1yUNFeA9lvNpHmfMggUjxq9dquo-NEFi8,9752 +tensorflow/include/external/curl/lib/conncache.h,sha256=7SVvgBZ56Tpsxl5woBgzHJbUFftwHjiEGsgHLnWplCs,5225 +tensorflow/include/external/curl/lib/connect.h,sha256=8MPQSo7utCGsgeUm7PPhL-m_kLmWkDbfgJFegTTAAMc,5226 +tensorflow/include/external/curl/lib/content_encoding.h,sha256=Jqxf9C7FBLMimzeo98FU1qhscR6sklc1kUAZCasnxpo,1621 +tensorflow/include/external/curl/lib/cookie.h,sha256=PoEjkbg1WWnf6ZO7Brr9pxziB00nyBx4mU2Jx4t1DnA,5672 +tensorflow/include/external/curl/lib/curl_addrinfo.h,sha256=6lI_sv2OmA3rZhvGeflfELxf_2CZnG7N7WDO31-H5dU,3305 +tensorflow/include/external/curl/lib/curl_base64.h,sha256=kfUU0Oc--tqy2mXFWwpIlvntaKWvbPWCE5pes46mywY,1849 +tensorflow/include/external/curl/lib/curl_ctype.h,sha256=5ToCjlyPRU2ksXAGXXdVGa9HZVOfOxuHzG-qC4WAcnY,2185 +tensorflow/include/external/curl/lib/curl_des.h,sha256=1dqhjrAUYJi9997LxJLBxIuumkte8c6g-eQpFJgtFOk,1571 +tensorflow/include/external/curl/lib/curl_endian.h,sha256=R9yvH--y6hd2b_SH0OR_3WnRz93zG7uOzIygiDJ_3aA,1459 +tensorflow/include/external/curl/lib/curl_fnmatch.h,sha256=HdHbn0_RILv6k0kkj-O944Tr4j2U1QpUaXyoJK7OLVo,1801 +tensorflow/include/external/curl/lib/curl_get_line.h,sha256=qi5Ly87_2bGPmPCWpnG5UQafNpiduSRlawOiz6x_RkU,1313 +tensorflow/include/external/curl/lib/curl_gethostname.h,sha256=Jpo-TAzrWZoF2ON1HJSOVVqp7C7nEdTiqT_tegZtuRs,1340 +tensorflow/include/external/curl/lib/curl_gssapi.h,sha256=mxbeFCtKMMiwFOPCnOz6HMmZrdN95PyfD6ng9bfT7DI,2162 +tensorflow/include/external/curl/lib/curl_hmac.h,sha256=MxhYrD3S5A6bWx-JmHkGQudRA4xr6Zm241RaVciqLTM,3065 +tensorflow/include/external/curl/lib/curl_krb5.h,sha256=suaFBuyw-WFME9lanMxLc2R7INIETotuBAcuE5UB-7U,1914 +tensorflow/include/external/curl/lib/curl_ldap.h,sha256=mz3xSSYQWXtlOXIz9dgJ6KsdwId_9M_oPCXPM1Iz8-Q,1426 +tensorflow/include/external/curl/lib/curl_md4.h,sha256=AwQUSGw0ccrWaUL4gmBE9aBYBud9q49uHYmrAXiIk9I,1392 +tensorflow/include/external/curl/lib/curl_md5.h,sha256=oesXplAsp9Gn_iNxebzTO2JHj3osqtBYzl7ZjZwR-xI,2667 +tensorflow/include/external/curl/lib/curl_memory.h,sha256=ou8EZ3qIV5E1dfd8jec6Q-of5v871SgTF1AMaTsTC5I,5410 +tensorflow/include/external/curl/lib/curl_memrchr.h,sha256=IH-jZPltfmU_vNxiiTOORtT2wk7OuuqrO_2IoWWSVCc,1415 +tensorflow/include/external/curl/lib/curl_multibyte.h,sha256=d7YjTOL65bAal6IyA2facdCFwIbhrfaXmoayOwUSkf0,3408 +tensorflow/include/external/curl/lib/curl_ntlm_core.h,sha256=YJzqd6dYPAmTFyVQ56lOvqCJ2lsXaigwkRjx_2DKKhw,3241 +tensorflow/include/external/curl/lib/curl_ntlm_wb.h,sha256=iRYHphsFp4AWhu7_iNRrsFUYcuUInt41uX58KMvaYQs,1753 +tensorflow/include/external/curl/lib/curl_path.h,sha256=7aSf5S0KnUnfP9KYmNZrFajI_xSLznNYOeG-5pvHPaw,1692 +tensorflow/include/external/curl/lib/curl_printf.h,sha256=hoXiFcR6un_eKvsph1lAPODvX4fkpO7C-QhJDhI2mEo,1676 +tensorflow/include/external/curl/lib/curl_range.h,sha256=UEaCGtUZjjq4AaCxJUZUFrIDG93whQpT-YV-5PiIdjA,1225 +tensorflow/include/external/curl/lib/curl_rtmp.h,sha256=L6dhV4qDZvOHvcS_gTY9edpQ4sFEqskou6ue3pD1kXs,1468 +tensorflow/include/external/curl/lib/curl_sasl.h,sha256=IWH4oytcKilukS3Uh4jARKxkG4AezflxDPdbgffk2mw,6441 +tensorflow/include/external/curl/lib/curl_setup.h,sha256=4L6jdvZ0doyJ06OuM6N9apytXrC-4H0ZzlO9zDyiaS4,23459 +tensorflow/include/external/curl/lib/curl_setup_once.h,sha256=x6REhe9UoJvEMWROdc7T-V--5fy6DMoBt5GaIcIJyPI,11713 +tensorflow/include/external/curl/lib/curl_sha256.h,sha256=AVnbFB8Yf9NQW4g8imap5Kva0ohRXvjQ4AnZfCvlfvA,1741 +tensorflow/include/external/curl/lib/curl_sspi.h,sha256=EpF3ROLD_0moZUWscrt8CiyJSfhtqUBdegiA2HN4IV0,3552 +tensorflow/include/external/curl/lib/curl_threads.h,sha256=4adRVXHvFOs5eWAMm6uLEb2cwsK9vr8thu4DZnBW47A,2608 +tensorflow/include/external/curl/lib/curl_trc.h,sha256=sQkFHYxTmKsjvZ6eB7pGa5PYbGc_SKxLFejS0Y0UQDc,5261 +tensorflow/include/external/curl/lib/curlx.h,sha256=-CgrAnk8P_BCq4b4MV49x3wKBOZmagKgb1_qNeR9TOY,3687 +tensorflow/include/external/curl/lib/dict.h,sha256=bACiXb9mQ2vktz0UOabTEHPiTE_oll7_x3Fp_mGh5F0,1217 +tensorflow/include/external/curl/lib/doh.h,sha256=z_jf6Z4CEGWTN1Ag9JruehMYYaG7-m28_1Mw1fS4jFk,3669 +tensorflow/include/external/curl/lib/dynbuf.h,sha256=m7uB-ZOj8BW42j33rOE1uqo5kse-1OoLvlKXXB1G5xA,3664 +tensorflow/include/external/curl/lib/dynhds.h,sha256=nHgUBYsM61h_t2thd5TR3qfeDv3xW8jG-leXprRohmI,5648 +tensorflow/include/external/curl/lib/easy_lock.h,sha256=K7gmJmou6_RLoJa66msJaukfkS2seI9VzVUaHESziEE,2940 +tensorflow/include/external/curl/lib/easyif.h,sha256=cZsHNlVB3h4rjTuKaHIlDBYOkeKRY-z1uAjgshLbLTQ,1504 +tensorflow/include/external/curl/lib/easyoptions.h,sha256=afNQthsYxAeqaWCiTe1mFgdAFQWMsAoUmgJI6eHjuok,1341 +tensorflow/include/external/curl/lib/escape.h,sha256=l4vQikmf3qmXfwU8K3y54a6y9D5jOzgjvOpT0MZQG-4,1677 +tensorflow/include/external/curl/lib/file.h,sha256=ljlnr_N-Bcz9AkhbJzilPqdCqu5SsE10iMu5fLX7hPU,1648 +tensorflow/include/external/curl/lib/fileinfo.h,sha256=LWbo3tOdHa_Pehlw7j1K9YSH18ui9jam4vd9cFnyZQE,1409 +tensorflow/include/external/curl/lib/fopen.h,sha256=rtZqHpZkL02779vpH3wCVdY9wlCZKORxbPLDp2_JqaI,1224 +tensorflow/include/external/curl/lib/formdata.h,sha256=yF3tAIjp3oGXs6ng-c996Z-NZx4oMEI320fyNGGyFsM,2052 +tensorflow/include/external/curl/lib/ftp.h,sha256=BCOUHXQsIY22-uUbtIDTxlZMgpRcLM6839TakI1G2uk,6868 +tensorflow/include/external/curl/lib/ftplistparser.h,sha256=6V9PvTa3_iFH-koeON1PCvb9bF0Ob902giKcAiJLP6U,2790 +tensorflow/include/external/curl/lib/functypes.h,sha256=zO0gORdLxqL3Z6BH3qx2khLsG3nyyxWUrYbTN5jHBdw,2876 +tensorflow/include/external/curl/lib/getinfo.h,sha256=i2ogoRLYiKF3mNZcc3YWeyEscNNXkyRAcrk5lSs38hg,1255 +tensorflow/include/external/curl/lib/gopher.h,sha256=eQ2G4kSRC3spqB1PMCo78tqs27BChQwEuLE7bqoS5XU,1304 +tensorflow/include/external/curl/lib/hash.h,sha256=A7MLGFwic8gtyO4hdwnkRXFtEOgr2LPQRBrIZXuN8Fw,3468 +tensorflow/include/external/curl/lib/headers.h,sha256=ukitkuQoNwHVFXV2jsGXQAWjZCBwx7ipALl5bE2Y1lk,1958 +tensorflow/include/external/curl/lib/hostip.h,sha256=SjK-0JYzA90BKS15Ao2iRBXGuBbUqglDTjCOFvEvov0,7645 +tensorflow/include/external/curl/lib/hsts.h,sha256=rqr5o22ZP_xPdKvu6mZ_YOin86zCoSJPvlpdhSqcV4k,2471 +tensorflow/include/external/curl/lib/http.h,sha256=tO6TPRbw7_zIEzRL1H-yuFWcS-uC3mw6c-N746kuQ3U,12135 +tensorflow/include/external/curl/lib/http1.h,sha256=pSS8YcN0szsnR_MX9PZSJxEh0U1xssw4Hj3LEEQ7X-Y,2177 +tensorflow/include/external/curl/lib/http2.h,sha256=qVV3d6CQ-F0cr3zo51Lnyw-UIZzEYi1g6YvBJJBi0jI,2789 +tensorflow/include/external/curl/lib/http_aws_sigv4.h,sha256=04nJUqdTXMDK2J35pPpMeiLD6BWNanRxL65unq8dAPI,1310 +tensorflow/include/external/curl/lib/http_chunks.h,sha256=t6yIzfX1qi5AUckRnwv4kTWB4CrnhfjtUYPGX2pRaxQ,3503 +tensorflow/include/external/curl/lib/http_digest.h,sha256=LlESmUQjhXkLGjrRA8K0NVq-Dtu9sc6tyjeMFzkL0ys,1778 +tensorflow/include/external/curl/lib/http_negotiate.h,sha256=O0-TuDYO3FL0FzgQHLRi00hu9OB29nAulyj9VhLX20k,1742 +tensorflow/include/external/curl/lib/http_ntlm.h,sha256=bEdUhHyd169nv3dZCobVziUuZCTo2NKgv3wDVQhXBKU,1630 +tensorflow/include/external/curl/lib/http_proxy.h,sha256=Rzbo8aVRwAhlbeVESwOjWyX8Fh2Tnmssi2oTuuF0XOc,2430 +tensorflow/include/external/curl/lib/idn.h,sha256=a-O1EirQobSdCWo22j9F_-DrPle0KRQyafVRMmKm1AY,1673 +tensorflow/include/external/curl/lib/if2ip.h,sha256=Y6LX9ejf_gi46YOAd6wCUWuHSLY3-hefHHwXexFytko,3161 +tensorflow/include/external/curl/lib/imap.h,sha256=5FYodYJpxU00rBFc7nxvZODgO-dcOKE6LBGBZXiQGgk,4050 +tensorflow/include/external/curl/lib/inet_ntop.h,sha256=iVuvmR4Ny8RdARAlblqkCAY6FIt4uZDeYFJXc2pHhU4,1426 +tensorflow/include/external/curl/lib/inet_pton.h,sha256=ofSVvC5JN46XQHtVFeHN7gvdOqzRq_QIO2JKFUH3790,1446 +tensorflow/include/external/curl/lib/llist.h,sha256=prBv2P-jQE5ASKW3aXVMMeM9j_v304JtxyNXSKjAHD0,1896 +tensorflow/include/external/curl/lib/macos.h,sha256=4m0BAvm6sv9TCjXGVQ9ML0AvaaVF5WZ1TimsRdPAQzc,1279 +tensorflow/include/external/curl/lib/memdebug.h,sha256=aInZtnHLhPtk6hAbqgahKhVxOV4fOiAgWH4WmXuEgzU,7992 +tensorflow/include/external/curl/lib/mime.h,sha256=FQQwr2A6FbMUtiGGBQSJQbD4X4mmpeXugGgs7XiabaY,7345 +tensorflow/include/external/curl/lib/mqtt.h,sha256=vdbNXOMLcaDgqRutGTiN1d44Kl4YAbA0xxviHWTbS9E,2043 +tensorflow/include/external/curl/lib/multihandle.h,sha256=3dzpoAEFDjdy9xReKIMMRvldvltsvsT_nkj6CMTS52Q,6657 +tensorflow/include/external/curl/lib/multiif.h,sha256=Ty4GpRHyUySpwUdxWvQ5BcAPUh_1z2hanZGFIojhfHs,3979 +tensorflow/include/external/curl/lib/netrc.h,sha256=qESR3586n4RooxbTFu8Emfp1-g3Mzg8gnDcdY_QTcss,1666 +tensorflow/include/external/curl/lib/nonblock.h,sha256=rLGTo8NNuGKLcBUPupS7IW7G3dIz_LI-CDbSKbWYRQs,1314 +tensorflow/include/external/curl/lib/noproxy.h,sha256=hx0Pom4LzBk1pYJJ-g8CTwXb8y3ljpaH2Uf_CcDyrYE,1684 +tensorflow/include/external/curl/lib/parsedate.h,sha256=L55b6vd9wObGJbDYn5nhdfa-9Di_rev8DtoQFmPHgvY,1493 +tensorflow/include/external/curl/lib/pingpong.h,sha256=080k3vagV5B1aSldd-0RZYNwf2LcgewmK2RF8ZCtOvg,6099 +tensorflow/include/external/curl/lib/pop3.h,sha256=QMUxRbzA0gt6EGc6GXpK-J3XGJrR11_NwKuUppK9JXU,3731 +tensorflow/include/external/curl/lib/progress.h,sha256=hnS-3l5YBYtDpZZ6pnO8X_R4VaZUK1XLYpDY4SI2j5M,2901 +tensorflow/include/external/curl/lib/psl.h,sha256=RLfnLaYMaySOxwN_kc_umCKAWIuj2hzrJ-zDSlLotnQ,1690 +tensorflow/include/external/curl/lib/rand.h,sha256=3MRM41SM0mTtcapCzWgN69GpZngs4s7KaGa6OOtnkGc,1906 +tensorflow/include/external/curl/lib/rename.h,sha256=3tB7Vat4C1wO0Q9XXBZc4yzGDC20lwByJ3voi07eZRk,1197 +tensorflow/include/external/curl/lib/rtsp.h,sha256=pFoJPP_wwk7fxyk0LjxM-Vl3C4WyI-T-XbL4WI_n8S8,2316 +tensorflow/include/external/curl/lib/select.h,sha256=uticNvEkyVLN13fgFzqmfZvIkmVNGFsKiz_jvx4NpFw,3311 +tensorflow/include/external/curl/lib/sendf.h,sha256=AOiK5vh0-nKCDvEGf7oHVtpveJf45cWWi9P8Mz3DRhk,4650 +tensorflow/include/external/curl/lib/setopt.h,sha256=gkKTPpTI_mucR95F7USdUmqs9SkMYfxuGUnUn4hReWw,1378 +tensorflow/include/external/curl/lib/setup-os400.h,sha256=vnix5tMSaERXkeakaY4zUC1C4qcjFoDxNJB_DH3O43U,6288 +tensorflow/include/external/curl/lib/setup-vms.h,sha256=DXc3LMvaljBU3vZzZIxlBPXmg7YcP8wo8_CWbbXQ2Xc,14735 +tensorflow/include/external/curl/lib/share.h,sha256=fgRdmfSrYr9IYFod865aOIrY-QyRM7HlEentAWt5BvQ,2349 +tensorflow/include/external/curl/lib/sigpipe.h,sha256=CInFKuzWhnDg_p131PdwbzygCPtJES9VyyffLPfTJ-Q,2667 +tensorflow/include/external/curl/lib/slist.h,sha256=YU0y1hcSnma1gNiXPaIp-nFzyjkpkZFPZPydGQyTUbg,1626 +tensorflow/include/external/curl/lib/smb.h,sha256=b-9psOFUGanRw1u7XaDp-EgotOI7F8cITSTwpnqvN5I,1865 +tensorflow/include/external/curl/lib/smtp.h,sha256=wNBBPv8K_SRRqxCWAwx7KP9wYuaF28tHbco2qglaIMQ,4078 +tensorflow/include/external/curl/lib/sockaddr.h,sha256=vWC-2MqJwIlUsKaPs-r4NXMrY5S7yBUG2iLRS_mlTtI,1490 +tensorflow/include/external/curl/lib/socketpair.h,sha256=wtfjrjSgkME-i2URZlm-uKl-m4eH2SRsn53mfSbc3mk,1389 +tensorflow/include/external/curl/lib/socks.h,sha256=i2w2Si-Fgs2aY-gKOf2d5_HfnVH8Xg9-rc8hz6P-qMg,2228 +tensorflow/include/external/curl/lib/speedcheck.h,sha256=LQF8E32KV5rda84ZoNAnEpmnGdRbo4heImriVF-H3x4,1338 +tensorflow/include/external/curl/lib/splay.h,sha256=qBmX8LARt_GP-vgjNUYs-Zs16-r7qOWXuq3yt8t_QPA,2485 +tensorflow/include/external/curl/lib/strcase.h,sha256=94J-pG5SgpPtGyP9BaJtkNLnu4QGKGM3a0tzl1eOR2Y,1979 +tensorflow/include/external/curl/lib/strdup.h,sha256=gHv45qysSSP9Dfcwv88klrBE7YBHbgkDn_buoSUc0WY,1393 +tensorflow/include/external/curl/lib/strerror.h,sha256=ddXL9WJCd9UFd05Wd_q4c1RSAVFvvDIMNmj5WEU1NHI,1496 +tensorflow/include/external/curl/lib/strtok.h,sha256=Lccarvzq70LEffnpohXCgdEEbf8ji72TQL__KV4LsxY,1330 +tensorflow/include/external/curl/lib/strtoofft.h,sha256=z3zwTh7X0syp71H7aI1DDQZncatgaNJkYFPmUZ2b9yQ,2139 +tensorflow/include/external/curl/lib/system_win32.h,sha256=jTJU6i3MhCaOFEglw3GUZYhTf5_9QRJxSJzwFBGwGLw,1761 +tensorflow/include/external/curl/lib/telnet.h,sha256=VWB409bnDG9u6LnUu8ClYNhIF90NiWQsFuWJfSYRfy8,1226 +tensorflow/include/external/curl/lib/tftp.h,sha256=RTzWGyE8dTEAruSb-uqFIhEW0KtYzp3sGzFoy6Kwgmw,1216 +tensorflow/include/external/curl/lib/timediff.h,sha256=APVVorVt24xET4v-49M_FzX7Oc_YUxvWGDO1VU5O02E,1932 +tensorflow/include/external/curl/lib/timeval.h,sha256=7kR-hSdpD1tZI5J5yDBNAntssNBvNFBdWTA1jm_X-8I,2227 +tensorflow/include/external/curl/lib/transfer.h,sha256=SzHOMvCrWNIiezw217S0HU0hrT8mWHND7wI_zQG378w,3178 +tensorflow/include/external/curl/lib/url.h,sha256=wrzH5ks1YMsutqnmuPjL4m0wKqXxeOKBPSUVg9UmnFU,3108 +tensorflow/include/external/curl/lib/urlapi-int.h,sha256=LzSVbVneLavxjoaJKEdTbT4QWg9ew0rqeMUm1TAyo8c,1551 +tensorflow/include/external/curl/lib/urldata.h,sha256=ygUp_UaXNFhx1J9aVGIB573tAT6b3ofM9dWoQAQj0pY,82115 +tensorflow/include/external/curl/lib/vauth/digest.h,sha256=yeIV4ivuy9u45xnMCvbalMVOoMSkrZ4u8xc3mHe31G4,1492 +tensorflow/include/external/curl/lib/vauth/ntlm.h,sha256=Ub5A8n8NptNW5Jc7dk05q8MB8rTkqbLABLQlFf_6E84,5484 +tensorflow/include/external/curl/lib/vauth/vauth.h,sha256=X8PLp8nro4XM0jprpJKftyM1zYPNFn310bSWGNJANOo,10266 +tensorflow/include/external/curl/lib/version_win32.h,sha256=aSohLQApCqqTTYffxX1xCP3CjsYA5W2QHSze0nQBLY8,1939 +tensorflow/include/external/curl/lib/vquic/curl_msh3.h,sha256=Iq-QrzQtsmvKZwIeBkEVFryy3EsuyBKyWgMd81f2gMo,1667 +tensorflow/include/external/curl/lib/vquic/curl_ngtcp2.h,sha256=U2b_ZaLkIpc2LcigBNxpp94usawmhmGA1HfcrnZjgDM,2003 +tensorflow/include/external/curl/lib/vquic/curl_quiche.h,sha256=cxhaq3ATpoFlKBk9LbkT1MSy16Sfu7bjEm65yCbwvPI,1741 +tensorflow/include/external/curl/lib/vquic/vquic.h,sha256=rX2zS4xfYYkz7oYJiDRay2A5vcIFgma9K8aiT7w8ngI,2159 +tensorflow/include/external/curl/lib/vquic/vquic_int.h,sha256=YBpD0pRJgH7gqt1_nCYLAs6susWAK-8y03MY06bff7M,3411 +tensorflow/include/external/curl/lib/vssh/ssh.h,sha256=Zq34aflj64VpfRYEWZnOSGtQT0qOFQ8mhZNWCL7QuVU,8784 +tensorflow/include/external/curl/lib/vtls/bearssl.h,sha256=9my4GKV2ARuilJPbOw6DlTq0E1RK4pZpmX2BXAtIvKU,1254 +tensorflow/include/external/curl/lib/vtls/gtls.h,sha256=AaY4oQplhnyUQu-M1ZaUcw3i70sbRjKgymko261-SjE,2350 +tensorflow/include/external/curl/lib/vtls/hostcheck.h,sha256=U6iDQVI9xeUzRW_gjHOl9ja92B_hnbVCEExrI6bIcPU,1342 +tensorflow/include/external/curl/lib/vtls/keylog.h,sha256=OGHN30eEuXaPbVUY8TBEGOPna4rM6RbsJBjSdBhDW3o,2043 +tensorflow/include/external/curl/lib/vtls/mbedtls.h,sha256=NprZNVkue9UtLSnVB6gheLialDnLDBY7dyKSChQlBh4,1310 +tensorflow/include/external/curl/lib/vtls/mbedtls_threadlock.h,sha256=dzXoCrlTvBrDMUzm19i7mFCDYBfXeaOKLxd4is3Pmck,1852 +tensorflow/include/external/curl/lib/vtls/openssl.h,sha256=sHT-fi3XXZd6HquoKb2ytYilaJAchoP-fqIceDPAdoI,2712 +tensorflow/include/external/curl/lib/vtls/rustls.h,sha256=1iwSVUhtIUrK0DzLJ34LcHoT4j1j4kWNwX-KLA1TRBo,1265 +tensorflow/include/external/curl/lib/vtls/schannel.h,sha256=nN5YLnGbezhqML8-aDGtZauOzZBu0Tyuy4r-CM9M2ds,2694 +tensorflow/include/external/curl/lib/vtls/schannel_int.h,sha256=1c9RCoj9cwFY6CQK2-VHrsCz_hi6h9WIJLLaqlW7yhM,4880 +tensorflow/include/external/curl/lib/vtls/sectransp.h,sha256=Gs6k-zDZezlE9QD73_Ow355pXUNmTybEXVFYFDPnGvo,1323 +tensorflow/include/external/curl/lib/vtls/vtls.h,sha256=d0vkBMADa2Gt6Zbh5LQNM4SwvqHOVGhHON-Gg5kgv5I,8800 +tensorflow/include/external/curl/lib/vtls/vtls_int.h,sha256=VBqO-iUOdKiOzs7hgbyXcEO6mVQAIg-Y6RObuvugM6s,9013 +tensorflow/include/external/curl/lib/vtls/wolfssl.h,sha256=c_HYbzUhcasmNLv2AL0hpRG4MwSM1YnGAV_ZliOBths,1257 +tensorflow/include/external/curl/lib/vtls/x509asn1.h,sha256=2GFzLJnci9U48VCDpr2PPCa_dryTxKvEGSqFVIavX_A,2903 +tensorflow/include/external/curl/lib/warnless.h,sha256=RqrOCTXRR4U6hv8PG3o7mO7sCjEH8p_72DRx62ZZ-pk,2633 +tensorflow/include/external/curl/lib/ws.h,sha256=v5soaUiax3h-P3fd2pkVAHp8mQJPRZFVnRj6JdiCLTI,3289 +tensorflow/include/external/dlpack/include/dlpack/dlpack.h,sha256=1j93krmZFayE4eeJUH1r5AZ9qEC8Lw8h8ESjQMDcl9Y,6660 +tensorflow/include/external/double_conversion/double-conversion/bignum-dtoa.h,sha256=0RUX67aRB8UVxbRdgg4aL_ZlrGQYL2L90lusgErPHR8,4300 +tensorflow/include/external/double_conversion/double-conversion/bignum.h,sha256=a2P66hPzb2AmtWhVqo0oMpuhqRxWS5q8lLIWCMpCy_s,5891 +tensorflow/include/external/double_conversion/double-conversion/cached-powers.h,sha256=HakTJP_UIAs8tB0fBwcncXXN0o_L_6ExBOFN9DHwB0Q,3021 +tensorflow/include/external/double_conversion/double-conversion/diy-fp.h,sha256=-PXWa-VoSsVH9ouZfUH9xX6Nwsoe8u8uOxDGp2ycW3U,5030 +tensorflow/include/external/double_conversion/double-conversion/double-conversion.h,sha256=J1Tl5-8aFY0A9SnaA9z5Q90jnMxw55illPIuE-jdD5Q,1804 +tensorflow/include/external/double_conversion/double-conversion/double-to-string.h,sha256=V3zY8tUZTbLhLj1_dsA8nhA7O2A9nDJPEYJwjs-20Yw,22349 +tensorflow/include/external/double_conversion/double-conversion/fast-dtoa.h,sha256=Uj13iTWZXepdIeWfVWKbpA6vaN7f6Z6Ctx79SudfTkA,4064 +tensorflow/include/external/double_conversion/double-conversion/fixed-dtoa.h,sha256=XCIHfT0zOZi4fFeKoaAVUD0WKJXiDl8u6SchyDR0juE,2770 +tensorflow/include/external/double_conversion/double-conversion/ieee.h,sha256=vJpK2uSS9pLhnbnCeerFLUkz3fhyr_QwVrzu5C1lqPU,15223 +tensorflow/include/external/double_conversion/double-conversion/string-to-double.h,sha256=GXYxD90E47w1DF-PS0Q7oCh6u0AEsxjwSKxBYRJ45Mk,10848 +tensorflow/include/external/double_conversion/double-conversion/strtod.h,sha256=CMOo-YUrbjOZtpTq11EeDsrclqamFDH8H53wA_L_Qdg,3038 +tensorflow/include/external/double_conversion/double-conversion/utils.h,sha256=-lgDSwYn5Xda74c1O0nuDwBlIf6vhyAgNEcdrwumrVw,15340 +tensorflow/include/external/ducc/LICENSE,sha256=wOgoMEgJ7O1TrH6N31LezSU7JAv5puq8OWfojOdXfLQ,15188 +tensorflow/include/external/ducc/_virtual_includes/fft/ducc/google/threading.h,sha256=BDFgszFjFLUfx_q6j9XhM_ReGuTA1OityDgLmfF3VJE,2069 +tensorflow/include/external/ducc/_virtual_includes/fft/ducc/src/ducc0/fft/fft.h,sha256=oGCyuOO1Ll3j1oDGRbxM_BUJ89ZdkGZ8hHIltIGdaZo,32463 +tensorflow/include/external/ducc/_virtual_includes/fft/ducc/src/ducc0/fft/fft1d_impl.h,sha256=P6fHXOd_lhuiU9jYhVjbpOkoXdVxYUr-QZthrvvfaV8,103114 +tensorflow/include/external/ducc/_virtual_includes/fft/ducc/src/ducc0/fft/fftnd_impl.h,sha256=WLq-cfumBTt9mQGnxcg-T5r7roi3UQ3apgkItrIqjDc,64987 +tensorflow/include/external/ducc/_virtual_includes/fft/ducc/src/ducc0/infra/mav.h,sha256=Q9EEn4ZMM4VmfZQpeRmvFxwYogJA7ekavj6QA7DvkuA,48173 +tensorflow/include/external/ducc/_virtual_includes/fft/ducc/src/ducc0/infra/threading.h,sha256=gJZyPMvnixsbxZ99Fz1GJ5VS9wTDYxZ99IgiICnNOsM,11497 +tensorflow/include/external/ducc/google/ducc0_custom_lowlevel_threading.h,sha256=IKCEyXR76RetZ7LpOBfAIGic-lFk_fmVwFTDwXojqis,1252 +tensorflow/include/external/ducc/google/threading.h,sha256=BDFgszFjFLUfx_q6j9XhM_ReGuTA1OityDgLmfF3VJE,2069 +tensorflow/include/external/ducc/src/ducc0/fft/fft.h,sha256=oGCyuOO1Ll3j1oDGRbxM_BUJ89ZdkGZ8hHIltIGdaZo,32463 +tensorflow/include/external/ducc/src/ducc0/fft/fft1d_impl.h,sha256=P6fHXOd_lhuiU9jYhVjbpOkoXdVxYUr-QZthrvvfaV8,103114 +tensorflow/include/external/ducc/src/ducc0/fft/fftnd_impl.h,sha256=WLq-cfumBTt9mQGnxcg-T5r7roi3UQ3apgkItrIqjDc,64987 +tensorflow/include/external/ducc/src/ducc0/infra/aligned_array.h,sha256=NPimzq30rSZ_qFGx2q4KAel5kmgLDt4xe9jH9Qnispc,6053 +tensorflow/include/external/ducc/src/ducc0/infra/error_handling.h,sha256=RTzKyOC1spUazMmBmHF4msDnxilS4PgvEW2WjHnpYxc,4283 +tensorflow/include/external/ducc/src/ducc0/infra/mav.h,sha256=Q9EEn4ZMM4VmfZQpeRmvFxwYogJA7ekavj6QA7DvkuA,48173 +tensorflow/include/external/ducc/src/ducc0/infra/misc_utils.h,sha256=Dy2kGWC7mlUqksZQIADM63Y6zVgmksO8EhtUzSdEqDY,4334 +tensorflow/include/external/ducc/src/ducc0/infra/simd.h,sha256=Pv1cgoC1dYxwd8PcQ9NMjIDyEVBtxAECcDNhf_40ntA,29854 +tensorflow/include/external/ducc/src/ducc0/infra/threading.h,sha256=gJZyPMvnixsbxZ99Fz1GJ5VS9wTDYxZ99IgiICnNOsM,11497 +tensorflow/include/external/ducc/src/ducc0/infra/useful_macros.h,sha256=emCkE7aji2cdjTfhN3PzVJvaBSqnKxx6bUJ3rp_zEuo,2935 +tensorflow/include/external/ducc/src/ducc0/math/cmplx.h,sha256=bQm1xOEg0xH2ZMY16KDg7RkhgrXFXaOqdkQ1wcyrIiY,4449 +tensorflow/include/external/ducc/src/ducc0/math/unity_roots.h,sha256=qkxgOb0kmNSCA9JnM75ViHkG7pLQsY1UiQ5efbUmm-8,7288 +tensorflow/include/external/farmhash_archive/src/farmhash.h,sha256=98Vp-FwDX3NwWkuQJagOuxxHcvtjBf1EaffgYpqJjc0,11649 +tensorflow/include/external/farmhash_gpu_archive/_virtual_includes/farmhash_gpu/third_party/farmhash_gpu/src/farmhash_gpu.h,sha256=Bj1ZKxJivasXm3t5Xr1Slc0sXyRF07ApvONOMIlEJO0,284386 +tensorflow/include/external/farmhash_gpu_archive/src/farmhash_gpu.h,sha256=Bj1ZKxJivasXm3t5Xr1Slc0sXyRF07ApvONOMIlEJO0,284386 +tensorflow/include/external/flatbuffers/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358 +tensorflow/include/external/gemmlowp/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358 +tensorflow/include/external/gemmlowp/fixedpoint/fixedpoint.h,sha256=8bEedWuhOLQqvS85CV_U10CiaxD_GoxoLC600nNljPY,35769 +tensorflow/include/external/gemmlowp/fixedpoint/fixedpoint_avx.h,sha256=5qb6Kl_PUgfhUusK_0WQA4kNljLpdDN34pHVejtDecM,11184 +tensorflow/include/external/gemmlowp/fixedpoint/fixedpoint_msa.h,sha256=cZhRIN3urPyLPu2B8ITH_DW1xHvStiJBUFuyg0-RQC8,12541 +tensorflow/include/external/gemmlowp/fixedpoint/fixedpoint_neon.h,sha256=g_ZK9lVdbFm5FvWe4qg3sc1BQMC3wmeRrD8LNpdfCtA,9073 +tensorflow/include/external/gemmlowp/fixedpoint/fixedpoint_sse.h,sha256=xynXq-jFKCm-Y7wLUd73rueitwCqrtvNm8NgVgXZzi4,11142 +tensorflow/include/external/gemmlowp/fixedpoint/fixedpoint_wasmsimd.h,sha256=F1Ur5YvxAIYPWhMUkdEm55XSIlr0qfRn1b8XNaqibWI,11257 +tensorflow/include/external/gemmlowp/internal/allocator.h,sha256=kNWIWE2wrpUE39YimGTMA6kt2Vc2V1S0GoPGqHB9CXs,6328 +tensorflow/include/external/gemmlowp/internal/block_params.h,sha256=ofkXFrhMyeJbCbify7LZaH8T0_Gk4LLXS8U1KALnYW0,6768 +tensorflow/include/external/gemmlowp/internal/common.h,sha256=uwczkaYnYS6PLPMU0ucVVozwXsnQNmKpN_bnEjCVAVE,6676 +tensorflow/include/external/gemmlowp/internal/compute.h,sha256=vTJQiIv-wLm6dXSI_eg2h5uON8h6tXnHM4FE6sFI7xU,4299 +tensorflow/include/external/gemmlowp/internal/detect_platform.h,sha256=v6YdSHFWxoyxH9KxFOCqaKwEjsFbTkRjHaK8awM6PxA,4996 +tensorflow/include/external/gemmlowp/internal/dispatch_gemm_shape.h,sha256=C-x0pr2Hpyh21KDvLzeRtRDxyfDb6Kot03COFUrjjIU,8036 +tensorflow/include/external/gemmlowp/internal/kernel.h,sha256=8ZTquwZu-wxqLmmZrGJ9W9A2X341361WmnoQDPdwCyk,9218 +tensorflow/include/external/gemmlowp/internal/kernel_avx.h,sha256=4wGkmAkeMhSpP6ywaaBBUxMQ7MBNn8s7A3rvtRRn7eM,19165 +tensorflow/include/external/gemmlowp/internal/kernel_default.h,sha256=lZeIzQMZj4FC04-DcsNe2pYxQzviWDFozHippUo8IKg,4847 +tensorflow/include/external/gemmlowp/internal/kernel_msa.h,sha256=6g6aqOdqFH17dcBjFUGHC2T7qOm9nJf8mK-lNqxHUpc,23748 +tensorflow/include/external/gemmlowp/internal/kernel_neon.h,sha256=Fqguydj-XzArBaDk-5DSU88tJ2USdOIEjNQT41-F1bo,75739 +tensorflow/include/external/gemmlowp/internal/kernel_reference.h,sha256=O1E5Psu6CA039eWMI_pTkujNHZapCetjraMKd-Xty94,4837 +tensorflow/include/external/gemmlowp/internal/kernel_sse.h,sha256=cZj5WBjm8u22daoWfuxi_AU6d77WU8OeKf9JS2iMEBQ,18968 +tensorflow/include/external/gemmlowp/internal/multi_thread_gemm.h,sha256=WqiOAHH5H3vCIlMCa5Pqe-Qkr9nhEKaL-paOKEZVYuU,28223 +tensorflow/include/external/gemmlowp/internal/output.h,sha256=DQbM4MPeN6juxZWoh2CjmJ3fcUZ5Dj0mhgp1v0YMPUo,22604 +tensorflow/include/external/gemmlowp/internal/output_avx.h,sha256=CGAhtuHGJ8lN6uxnghvnqayz980FMnqv0IC3Drt7GdI,763 +tensorflow/include/external/gemmlowp/internal/output_msa.h,sha256=ziNJF-WXEWdgxukPFg7k6L6ukafHlRfAsf9T25CIKSo,44686 +tensorflow/include/external/gemmlowp/internal/output_neon.h,sha256=7DLS3x9e8cbvk5FagrI_4LN8_UJF575E0xoHRd5fG1U,35994 +tensorflow/include/external/gemmlowp/internal/output_sse.h,sha256=JHn8NNL3vlmPiBCua9X4ZQXE_rzdxDZg8YLClv29adI,20105 +tensorflow/include/external/gemmlowp/internal/pack.h,sha256=BEUBjpB4aNSMZsr4gf2JRmoq8ihX7BjXc2BZKEI54_I,17975 +tensorflow/include/external/gemmlowp/internal/pack_avx.h,sha256=KbWVnUM8d3ueWVilcK-c-DOhBezirq2dGd4YfP2mp2E,11519 +tensorflow/include/external/gemmlowp/internal/pack_msa.h,sha256=TIqKMKJDxiHf0P-Ufa7WDioLb0dA70eGhcr_g1Swlz0,18939 +tensorflow/include/external/gemmlowp/internal/pack_neon.h,sha256=ZpYmc80UyMiNj5nFWFRMzrpLMTtcHLbI1g3VjPV4kxM,15055 +tensorflow/include/external/gemmlowp/internal/pack_sse.h,sha256=uOsHrbuWwiNM6uxVVK5zOWOzSqM3RIsipBgAv9HL8mY,4972 +tensorflow/include/external/gemmlowp/internal/platform.h,sha256=ruPon6YMMmbQY2xo6Q8HcBatqfRfoytb0OdqhlE4c8M,2977 +tensorflow/include/external/gemmlowp/internal/simd_wrappers.h,sha256=9XmA-lJRZcmLmZoWXFgWIWW42QSYm4nAXmAxlGHQBe4,25588 +tensorflow/include/external/gemmlowp/internal/simd_wrappers_common_neon_sse.h,sha256=kWtEFcVvWq5THs7Mp3UrZMrK690b4-pwMti75_3pfac,31387 +tensorflow/include/external/gemmlowp/internal/simd_wrappers_msa.h,sha256=xH9pnPyD1OZWMog7KFgA2ugyNVkHD_DVxvAqoU9oBEg,5642 +tensorflow/include/external/gemmlowp/internal/simd_wrappers_neon.h,sha256=3lAiPbyH3vYXq1fAEunGursEZvpCt-d6ay8oK7knGyA,19188 +tensorflow/include/external/gemmlowp/internal/simd_wrappers_sse.h,sha256=IwrYgKmGyIuyq53rC0qXMGsVsdSTnxbzeh3oT68cLyw,4257 +tensorflow/include/external/gemmlowp/internal/single_thread_gemm.h,sha256=jgd2Sj65O12jbz8-WTzcKwWnRhM1ev8APxmub4bnbEc,5586 +tensorflow/include/external/gemmlowp/internal/unpack.h,sha256=vI46hHDqA4jKAHihwzl1tBsopIP4JtKp8zQKDuCnMwQ,12594 +tensorflow/include/external/gemmlowp/meta/base.h,sha256=Y4YFAc3VVu4D6bw1KeN6WkjwL5c1nW47QL7X6XUcbI0,3960 +tensorflow/include/external/gemmlowp/meta/legacy_multi_thread_common.h,sha256=lh-oJ1kR97oreNV45I1Vpbbm_4vEZSw1k96RIxa3xu0,5384 +tensorflow/include/external/gemmlowp/meta/legacy_multi_thread_gemm.h,sha256=KKZc3ze7vEIv2C9tDsmUyhZQXbKwYmDwY3WNLf6GJ88,11396 +tensorflow/include/external/gemmlowp/meta/legacy_multi_thread_gemv.h,sha256=688LRgRfkNAKv8UtuDLV3bhI26l0B2_lMH0CLT2EsrA,6992 +tensorflow/include/external/gemmlowp/meta/legacy_operations_common.h,sha256=Kwq79GUAvJTuR8SzqxH_OkEO1QIz0iHr38WlMUFkD60,1850 +tensorflow/include/external/gemmlowp/meta/legacy_single_thread_gemm.h,sha256=uHJwHPaAUbgRY2ITxcLvXgBhMyTbO9B13L7JWBLKFO8,9600 +tensorflow/include/external/gemmlowp/meta/multi_thread_common.h,sha256=XFv_3cnHnrlnzhSQml9tl8fVun-xkO3E0kTs9pcNGHQ,1593 +tensorflow/include/external/gemmlowp/meta/multi_thread_gemm.h,sha256=TVTvfj027CD1kmSECmolOyvXPHOvmn9RFPijR3b_gwI,5253 +tensorflow/include/external/gemmlowp/meta/multi_thread_transform.h,sha256=fllEE11LpGsq_rHkTo9_gNQYHBcDllC_yqGZZOsSNsg,3519 +tensorflow/include/external/gemmlowp/meta/quantized_mul_kernels.h,sha256=FIMI-Rkd9O-FYpDIrizI8T787hV2TyQid8RinkMkvDw,5759 +tensorflow/include/external/gemmlowp/meta/quantized_mul_kernels_arm_32.h,sha256=VfbwHgmiXN_0fjCBVpnNe6yX3X1BPa68QYypXcirUNo,131368 +tensorflow/include/external/gemmlowp/meta/quantized_mul_kernels_arm_64.h,sha256=XTA39e5_yE9WlfnoDG5GggZNsuVa5_gW93fp14GIvFw,130137 +tensorflow/include/external/gemmlowp/meta/single_thread_gemm.h,sha256=YzrQs4DC2J7kwyOs6997OB3WlFDddIHtJxyzgVbJkQE,25668 +tensorflow/include/external/gemmlowp/meta/single_thread_transform.h,sha256=c3AC9qXXCcnxZ7nNFJ-wDmUKolwomuHQQopJwBYqLgE,2957 +tensorflow/include/external/gemmlowp/meta/streams.h,sha256=K6qFqkySXRANslLqBXaHUJPQeoGTIfjqAdH_YVkk5Tc,11049 +tensorflow/include/external/gemmlowp/meta/streams_arm_32.h,sha256=lib_XPr_n_Zj-3WDFR1WzcdjfMgLlGr1zxc4vpuLdlw,390785 +tensorflow/include/external/gemmlowp/meta/streams_arm_64.h,sha256=DvX2PHcaNe6Pjj6apbvxASVAmrO9FULsJ0T6pfx9Ry0,410715 +tensorflow/include/external/gemmlowp/meta/transform_kernels.h,sha256=aImCzua12JOSQkawV15UNF7Tz9vg3A8RgQxLys2Gv9k,7317 +tensorflow/include/external/gemmlowp/meta/transform_kernels_arm_32.h,sha256=MEH6qO3OtR-Be1UrnPZldvaha9FeXYMed_B9DvG2UxI,247365 +tensorflow/include/external/gemmlowp/meta/transform_kernels_arm_64.h,sha256=1rBzW5WoJZfcm9NM8nCElNsgvBJV-oyv0cGPhtR8RmI,260838 +tensorflow/include/external/gemmlowp/profiling/instrumentation.h,sha256=ZQ21M0MlojxqHY6_geY-_LZs7CCQJ74JvHzUSn1n6vI,6543 +tensorflow/include/external/gemmlowp/profiling/profiler.h,sha256=fIJs2m6h5wMNlqNrEmKbRCoqX5718R-jv8rHjvcjfKU,11853 +tensorflow/include/external/gemmlowp/profiling/pthread_everywhere.h,sha256=8LZSpqne_oPRCZsKUa1Y17BVuL_mGpE6qd3UQI4y-MA,3313 +tensorflow/include/external/gemmlowp/public/bit_depth.h,sha256=G1RvFveTIzil41g7LJBlp_1nhed0clC3w48tM1LRits,2616 +tensorflow/include/external/gemmlowp/public/gemmlowp.h,sha256=qrgHAcAqQMwIrdcOnT4Iyd2Tn3KQQFpyBFOR8JI_tYM,4314 +tensorflow/include/external/gemmlowp/public/map.h,sha256=LdGBeE86xIzAviw-K17mmtKvVAyKtu5gZ-o3ykUEEvU,4422 +tensorflow/include/external/gemmlowp/public/output_stages.h,sha256=B6tjIe_hNzfeAJQIOyFnzoUbt2fez7Y9AyPGUR7-cC4,11283 +tensorflow/include/external/gif/gif_hash.h,sha256=VxqmGj8u6SZiRplya8XBHCl69D5yx6hJAxQ52YhmKtE,1425 +tensorflow/include/external/gif/gif_lib.h,sha256=fHOFTi175PxQ5HXAmM_NpdcE1aEEFNtmjJPDYtDJLbg,12986 +tensorflow/include/external/gif/gif_lib_private.h,sha256=D-DYcLfN7VZNwEzlLe5onoEj8I3ghvZCegQOzP5gPug,2706 +tensorflow/include/external/highwayhash/highwayhash/arch_specific.h,sha256=WIqTVDtjsIs10zbM1r1OfS6EWY_syc62MEmCu_cI_Vc,6521 +tensorflow/include/external/highwayhash/highwayhash/compiler_specific.h,sha256=Cyu4L6zQz5AyZb4Iif0qjtQqtG4Pq50uPF0aMjr68ls,2638 +tensorflow/include/external/highwayhash/highwayhash/endianess.h,sha256=ace5Rlsi1j5_C2h71MbbQu5YxlypGcrElsv346goa6E,3437 +tensorflow/include/external/highwayhash/highwayhash/sip_hash.h,sha256=X6GYDGxcbcz6PwRO-vO5Lc2iKncGc5iZ48x6vvrbyU4,5569 +tensorflow/include/external/highwayhash/highwayhash/state_helpers.h,sha256=u9effW7__KEqARwMuvFzJwDZ8aBCVAZxHzhz6MmcpfQ,4816 +tensorflow/include/external/icu/icu4c/source/common/bmpset.h,sha256=VkpbNjJyxWhq_FpNBTVdwMoq3W_RYHzXYrH6EIkfdEk,5788 +tensorflow/include/external/icu/icu4c/source/common/brkeng.h,sha256=AV5l6NKOTmwOKLheAShmgTkiUz2fkMWn54bmoowP2ds,8083 +tensorflow/include/external/icu/icu4c/source/common/bytesinkutil.h,sha256=xsPFhVxX6AD1klCBNI6c2zP-BXBnaqwLiA9Pux2cofo,3088 +tensorflow/include/external/icu/icu4c/source/common/capi_helper.h,sha256=JIfN2oF7tmku1LKVAvk_ZPEHDZ6qQtJDHdGQroyLyQA,2647 +tensorflow/include/external/icu/icu4c/source/common/charstr.h,sha256=0t60XcYJDNNmLQeHRBCqMLAHgVuoVRZiQgLE10Lmads,7561 +tensorflow/include/external/icu/icu4c/source/common/charstrmap.h,sha256=yfnfzFibSHR23BJyHETyqP6h5zZR8sb1nH7N3GAyabw,1568 +tensorflow/include/external/icu/icu4c/source/common/cmemory.h,sha256=5uByQHvqHKX01WSlsCD--npa8bgjf2pno6NdCUr4BF8,30670 +tensorflow/include/external/icu/icu4c/source/common/cpputils.h,sha256=mYJ9TOxX4ty-SLag7TMh9iggyW_7GyUwYwvnRzgvdmQ,3267 +tensorflow/include/external/icu/icu4c/source/common/cstr.h,sha256=czz3Bk0sfkkhKiarIPRBDMAHVaiXuEvWDdCzss2QHYM,1788 +tensorflow/include/external/icu/icu4c/source/common/cstring.h,sha256=0HojqEH8fq11ckYGjaz-XWOWaeHR-3xFW-tWbZv1yyk,4013 +tensorflow/include/external/icu/icu4c/source/common/cwchar.h,sha256=uUWg9lfU47ZGLr3P5E8Mf_0G1BrZvBZO4uqGEM_oHBw,1890 +tensorflow/include/external/icu/icu4c/source/common/dictbe.h,sha256=bVMEOauosVLI1ovYKtkZmKlN7vQzM0BdKF4cYgEEJF4,12109 +tensorflow/include/external/icu/icu4c/source/common/dictionarydata.h,sha256=KSFh8BYIZAzOynrlbWY6womPokc-QfbxyoKjsbj2uw4,7957 +tensorflow/include/external/icu/icu4c/source/common/hash.h,sha256=Dr-tPgY97kFKxWIWjeIW0hIsWEqkN6nK768jJMgS_fk,8216 +tensorflow/include/external/icu/icu4c/source/common/icuplugimp.h,sha256=n3No-WTo46_XffNv8-Hziten7C0i-rcsKPan9D7zUEY,2102 +tensorflow/include/external/icu/icu4c/source/common/localeprioritylist.h,sha256=PcUsZd7LkonZQU8Mw5d9JcBqP8nHcMLqMMkFHsuX5kc,3612 +tensorflow/include/external/icu/icu4c/source/common/localsvc.h,sha256=zv5cZd83DUMji4Rs9Q6lsYRU04hAhbGEPCbGDtcPk64,947 +tensorflow/include/external/icu/icu4c/source/common/locbased.h,sha256=Pa8kB1VDUgbUlB8pzs_bmh45jYvB78cHOuhk0sqwRgE,3413 +tensorflow/include/external/icu/icu4c/source/common/locdistance.h,sha256=NtmFY7Mg60QAQXe21wqfJq_mFceFo35sHbtMrAL-weM,5312 +tensorflow/include/external/icu/icu4c/source/common/loclikelysubtags.h,sha256=X-CcKIAyBhsAyRnYsw5NKWnQvN7hKyuIxZ8bYK6o1C8,4069 +tensorflow/include/external/icu/icu4c/source/common/locmap.h,sha256=0vo6MdM-n_504gy0fuFz3dQ9EVrhi-XnQbkkNOTfRhA,1361 +tensorflow/include/external/icu/icu4c/source/common/locutil.h,sha256=hTiPhV9kcfRyR693cP1JtVFMJhRUU1y8wnnr3orhZLY,1304 +tensorflow/include/external/icu/icu4c/source/common/lsr.h,sha256=xR7W_rpHuZnMh3kGWco5AGgn_xhe9bU_uib5Lw4iUSk,2432 +tensorflow/include/external/icu/icu4c/source/common/messageimpl.h,sha256=r2cT2QoRy8Q82RnE6c_x4OgAXhRZLeLmZhEmb9-n2ow,2062 +tensorflow/include/external/icu/icu4c/source/common/msvcres.h,sha256=Ob13jd42QzmT-TTQ5Tbg1Z1Vz1LMOIshoKRNORnzOTc,910 +tensorflow/include/external/icu/icu4c/source/common/mutex.h,sha256=Aj4dIkDm87mQVEDm7Ad3bK_cePymnzd54lJ0VAQEVaY,2291 +tensorflow/include/external/icu/icu4c/source/common/norm2_nfc_data.h,sha256=x0vJ70D8q8itZdcNHvtUAgJ4GcQHLK_Lzw8RXGrlIzg,90545 +tensorflow/include/external/icu/icu4c/source/common/norm2allmodes.h,sha256=RYWBThiKHKfkaGStGSQgUQV0sb2Xs6B541K12dUlfjE,15276 +tensorflow/include/external/icu/icu4c/source/common/normalizer2impl.h,sha256=ZJ9Hbv5KM0NJVbsNp09QD4RQ-px9zdSRdkk7_r7ERto,41737 +tensorflow/include/external/icu/icu4c/source/common/patternprops.h,sha256=QSUo04V3faipBnV2ytzzmeplk1y_iiSSgx_0evfzSeA,3326 +tensorflow/include/external/icu/icu4c/source/common/pluralmap.h,sha256=2Y1QcTLLnBNKc1SUfxmE3YOo-qmgJkRpJkN75Krq5e8,8653 +tensorflow/include/external/icu/icu4c/source/common/propname.h,sha256=wwkXmdKlUQ7_SJ6XuNjYT1D5XVP_BMt8LSr0spG0sYE,8169 +tensorflow/include/external/icu/icu4c/source/common/propname_data.h,sha256=XGrdkremmtdzmbyh5IWjRfKhrWHtk3KoxEh0gBqka4o,166318 +tensorflow/include/external/icu/icu4c/source/common/propsvec.h,sha256=OkMx7JeaOVs0NE5ftcsjo-NZkpncF2KZEBXLlz98nSQ,5902 +tensorflow/include/external/icu/icu4c/source/common/punycode.h,sha256=3KtyxQqp6GTnKh2cLkWfNdHb633jonvBflJXRDdyCgk,4368 +tensorflow/include/external/icu/icu4c/source/common/putilimp.h,sha256=0PwK4cG3aMQXn3g2z9r88z9jJWgxNPkE4Q4O0mr4UJk,19385 +tensorflow/include/external/icu/icu4c/source/common/rbbi_cache.h,sha256=3qrfm4Z3lZWvBdz8JvDqyfydBU9wumTVCrO2rMa8cwI,7953 +tensorflow/include/external/icu/icu4c/source/common/rbbidata.h,sha256=9t6LrfNByoTUdTta5NfC1aE3h1YCbyDkqR0O95dPfUA,9554 +tensorflow/include/external/icu/icu4c/source/common/rbbinode.h,sha256=V4RierufYHpF9q0a4bzr2tmYj5howWC8RVIZBnCYNVE,4393 +tensorflow/include/external/icu/icu4c/source/common/rbbirb.h,sha256=bgAOX9jJOUtS7LwmfBMAyh_77dznoco7952nNXtCnW4,9181 +tensorflow/include/external/icu/icu4c/source/common/rbbirpt.h,sha256=1F08FBloQiWgmQXcEsEy7hsgj3ads4hZHp3tRiaklVY,9851 +tensorflow/include/external/icu/icu4c/source/common/rbbiscan.h,sha256=rZn9X9PSVwFVgUPfciqo_bNT7SLE32PuSpiL4z8F87g,7493 +tensorflow/include/external/icu/icu4c/source/common/rbbisetb.h,sha256=L3l5gVsWsX0fozTkyTy7k1X4nr6yJYK3NWqkMCcHQ9M,6068 +tensorflow/include/external/icu/icu4c/source/common/rbbitblb.h,sha256=Nw0-oJWxGCxKgjQTWXYgkwC8ZjJqFN8Xt1W5x0n_Gws,8698 +tensorflow/include/external/icu/icu4c/source/common/resource.h,sha256=OSN1HK1SrX0lBE4iyrOqWszOct-F20_GckBAhZhKuAE,9422 +tensorflow/include/external/icu/icu4c/source/common/restrace.h,sha256=55HtGOSFDFoKSWmpNDV1ir4lXp5tdCAx2dqKzCJNSro,3479 +tensorflow/include/external/icu/icu4c/source/common/ruleiter.h,sha256=0wlLZLNAYA-AoobS3uAPT4OIr1EG1-vHGXMrqoNn19M,7809 +tensorflow/include/external/icu/icu4c/source/common/serv.h,sha256=O-kA7d3EuiW5ApMFUVNgTpV0FCybSs0aV_Qkir2ADic,37016 +tensorflow/include/external/icu/icu4c/source/common/servloc.h,sha256=lBm2TnY11gM09n6aIbN21TNBGdSp09Glr0WiqB_TSUk,16405 +tensorflow/include/external/icu/icu4c/source/common/servnotf.h,sha256=bkDJGMz_ARU0y4CuVpqHAVcYnppmm06buLUpopZ3xgM,3648 +tensorflow/include/external/icu/icu4c/source/common/sharedobject.h,sha256=sCQEVauIl6alEfq2vbyuI_tD-PJWzSlShYXJ-2EAx1A,5645 +tensorflow/include/external/icu/icu4c/source/common/sprpimpl.h,sha256=ddQJvCYGxJU4xFNS6ty-SCkLXoI9D1qz_tJaQeWbAuk,3604 +tensorflow/include/external/icu/icu4c/source/common/static_unicode_sets.h,sha256=ZXURsiDsoewhg8O7mVTXYP2b5VIrU7lL8xAQtIIetZA,3832 +tensorflow/include/external/icu/icu4c/source/common/uarrsort.h,sha256=1AbP7YSpid5JPy8PkFqsBWPOETP5Ua52Ty0TYg9YjUI,3362 +tensorflow/include/external/icu/icu4c/source/common/uassert.h,sha256=C926oUx9WpkTycc-jb1rNIh4B6AnLdb219VgXEwHvoc,1370 +tensorflow/include/external/icu/icu4c/source/common/ubidi_props.h,sha256=AOrQ8vk_-G-UBi3RN9M_63AT7DeT23jshIkVKbpV72g,3798 +tensorflow/include/external/icu/icu4c/source/common/ubidi_props_data.h,sha256=9J2yY1rEaPNx5qoOGc_Zxy4d3effEp_qH-r51taKqNA,57445 +tensorflow/include/external/icu/icu4c/source/common/ubidiimp.h,sha256=K0MsRkjTEyt6EpoAf4gMiWTRlK0LsrRJTmVssqjDhYY,18232 +tensorflow/include/external/icu/icu4c/source/common/ubrkimpl.h,sha256=Z5uZYfxLiOYyr6y8st8jmSr40kWIsYxJZKXTeCg73II,503 +tensorflow/include/external/icu/icu4c/source/common/ucase.h,sha256=4WrQknkX7iXCOwt2cUYxBoRJdIWvctuhVDd6u_nhUq0,13206 +tensorflow/include/external/icu/icu4c/source/common/ucase_props_data.h,sha256=I3CrYFkgos4_SK8tO0hfhlhLBwtZwg6piNo5zcL6H0k,64544 +tensorflow/include/external/icu/icu4c/source/common/ucasemap_imp.h,sha256=9Umi8mLA_ncKvm_lAPoAP3TXm5c82ps5bMm67dZj2bY,9842 +tensorflow/include/external/icu/icu4c/source/common/uchar_props_data.h,sha256=nm5B3xLktps17jr9bllSgaSu9yEKAZHDJDl91DIldDs,349970 +tensorflow/include/external/icu/icu4c/source/common/ucln.h,sha256=bSS8z9ZllBNz_bsdLfPNy-Ht8lUNUrQ4_iOeYobNZSU,3205 +tensorflow/include/external/icu/icu4c/source/common/ucln_cmn.h,sha256=ULKiHGVpQLAsRLJ0pNgd-jF_dwrXa3ue_P65-1FgyI4,2458 +tensorflow/include/external/icu/icu4c/source/common/ucln_imp.h,sha256=XCjMT5qRQbZP1Y8tqrLJilLR4W4oGNAtcSw5uA9Rmtc,5217 +tensorflow/include/external/icu/icu4c/source/common/ucmndata.h,sha256=7L-yUnJISKPwIk8wewbPgIqvPYXiT4aMvYymGvS-qhk,3314 +tensorflow/include/external/icu/icu4c/source/common/ucnv_bld.h,sha256=U891Y1Ivv2M067HH9yqx9jknOO5GmNO0aJSd6o3nbbA,11454 +tensorflow/include/external/icu/icu4c/source/common/ucnv_cnv.h,sha256=w1y96ahqo7jaMtRbRc1SC8-YJy4nIXzpQvFPPVmtMF4,12977 +tensorflow/include/external/icu/icu4c/source/common/ucnv_ext.h,sha256=2QczmVGzsCilcFWN8cc6zyMyz_KSSh6mQEXVYJ0zXog,19116 +tensorflow/include/external/icu/icu4c/source/common/ucnv_imp.h,sha256=mjfHKr7lJmuRLaOdUD3JnAxw95Nr-fPmhAFDDXC5Lwo,4795 +tensorflow/include/external/icu/icu4c/source/common/ucnv_io.h,sha256=4qhfW6QnkdM-GPoiGHgQ5UOkoxuytbZThcROhg3CFk0,3702 +tensorflow/include/external/icu/icu4c/source/common/ucnvmbcs.h,sha256=-NY0IY43Y0TYPV89eRTweWyeZiK6UT_6oEJOOx-BRlk,23835 +tensorflow/include/external/icu/icu4c/source/common/ucol_data.h,sha256=Xq5dKIhCNwcEBLPjwK8bDPFdGqDJmz43X4DG7vg_XAg,4482 +tensorflow/include/external/icu/icu4c/source/common/ucol_swp.h,sha256=ffZd47Fneg7lSQRI6yDKt3eZvVu3y_G4PwRodEjVw7w,1479 +tensorflow/include/external/icu/icu4c/source/common/ucptrie_impl.h,sha256=dHzSVX-TiTgOwirhgIQF68cgoSUT1i7Nvh1qZX6vk4U,11176 +tensorflow/include/external/icu/icu4c/source/common/ucurrimp.h,sha256=qLhEw7sVUPLr3eAMKmA_dzhSrEL2MRYK60pVuMN7hFw,2801 +tensorflow/include/external/icu/icu4c/source/common/udatamem.h,sha256=OCOzd-EJWhXbLyYYlDGK_lLRo9Ct-spNbqXE63MI_t8,2937 +tensorflow/include/external/icu/icu4c/source/common/udataswp.h,sha256=f_uST4rC7_Uxrmq1yijHo9eT3FsA_787ZHWRbuwTMms,12850 +tensorflow/include/external/icu/icu4c/source/common/uelement.h,sha256=DnGYft4Vn13rn4PWRLxQxVOmem5gnf3wLuS6p-2m_C8,3048 +tensorflow/include/external/icu/icu4c/source/common/uenumimp.h,sha256=G016GIcsdzIFxZ37cgk1YfaabfTV29-871uwWXgp9ho,4239 +tensorflow/include/external/icu/icu4c/source/common/uhash.h,sha256=U2Fk69fvRtMSC5Oi37hkRpWAiSgs-1QW0psY4ogLwNc,28393 +tensorflow/include/external/icu/icu4c/source/common/uinvchar.h,sha256=GhV70aHpv_bhB1sGwwZcDWupckq_xRg6bipCYG1ghr8,5853 +tensorflow/include/external/icu/icu4c/source/common/ulayout_props.h,sha256=FUIyXFyiYrA9U-RPKvQosNWR3SlWzbErvNtDWzK53GQ,1261 +tensorflow/include/external/icu/icu4c/source/common/ulist.h,sha256=rW8H49wqqIcoLKlxPHz2FWHr04jp8MyxjFmHbHb1IvE,1766 +tensorflow/include/external/icu/icu4c/source/common/ulocimp.h,sha256=4S-dw0RB-LAObIVZ9sHPyen5c54tK5-ZsSe-9pph95A,10510 +tensorflow/include/external/icu/icu4c/source/common/umapfile.h,sha256=nfwFwciQu767LGglYaqxqYba3qHDczYC3q_zBJnCLAM,2139 +tensorflow/include/external/icu/icu4c/source/common/umutex.h,sha256=uBqBsxCaykT-5wnJIKuXrwsTyBFpIUsQF2IsB7AzUoM,9197 +tensorflow/include/external/icu/icu4c/source/common/unicode/appendable.h,sha256=jta1WyeOd_IjHlY3gt6WRkUOziFeHdrqie10-LN195E,8694 +tensorflow/include/external/icu/icu4c/source/common/unicode/brkiter.h,sha256=rp1xTk1uDIn7F5UzMjC6QJZb26SCCwk5qRIQ_bxflEI,28464 +tensorflow/include/external/icu/icu4c/source/common/unicode/bytestream.h,sha256=kcGKktk3IwiPiburDmhp7D22xCfQrmrVQKDTGyCFtDM,10986 +tensorflow/include/external/icu/icu4c/source/common/unicode/bytestrie.h,sha256=qdKDMX1m2ypBAP_ZmBn1LA0VSZ3Xpqhar0JCuu7wKuA,21268 +tensorflow/include/external/icu/icu4c/source/common/unicode/bytestriebuilder.h,sha256=eDFRAlxSqhdVkDQy19_fQpoWeXiF9uQ7GP8OwRzNYow,7470 +tensorflow/include/external/icu/icu4c/source/common/unicode/caniter.h,sha256=3RaPiMYzLHEgfi8hAUETRG59R6oje-9j0324gmvyrsU,7611 +tensorflow/include/external/icu/icu4c/source/common/unicode/casemap.h,sha256=VwkMk3qIMroJYgTlyiubFKN0g4uCMKUXll2lAl1-Vo4,25933 +tensorflow/include/external/icu/icu4c/source/common/unicode/char16ptr.h,sha256=-LgRjWpsfTA_D_avIfxpHgoVbOOwFLgS-eZYlBAM95o,7393 +tensorflow/include/external/icu/icu4c/source/common/unicode/chariter.h,sha256=NaV05aa5_MfWqKoaJcgDfq0K1gMcSVzNevrwvtHAD2U,24632 +tensorflow/include/external/icu/icu4c/source/common/unicode/dbbi.h,sha256=5YFpXiXl6zbSlETWfv4SWlxZuW2Atp_FkGc6TtvJDYI,1223 +tensorflow/include/external/icu/icu4c/source/common/unicode/docmain.h,sha256=FREKukdGFXtgh7Wnx3AyxuTdZuUMp9gZYReObj6Het0,7384 +tensorflow/include/external/icu/icu4c/source/common/unicode/dtintrv.h,sha256=gtZQeBXeyZ7JwEJY4K2NXCpwX7R2mnrv-4vkCflBx3c,3930 +tensorflow/include/external/icu/icu4c/source/common/unicode/edits.h,sha256=TRkYZoQDkPfl2G1pwf5awLzTq32-cfnonJG9h5URzfY,21237 +tensorflow/include/external/icu/icu4c/source/common/unicode/enumset.h,sha256=cU5SNo-MIEoRhEDARYfG7ZU6MADiJDAEYx7FUiv67wQ,2130 +tensorflow/include/external/icu/icu4c/source/common/unicode/errorcode.h,sha256=4pnpfi8R-OrZw-fP4kp4Wpi6uU74ZQCpfwsd9V78XR0,4956 +tensorflow/include/external/icu/icu4c/source/common/unicode/filteredbrk.h,sha256=lFpDZuWhH9F_93pMMl3SbfT7AutMO3HWe0aIQycZOPw,5501 +tensorflow/include/external/icu/icu4c/source/common/unicode/icudataver.h,sha256=WxJ-4MCLKXzJfbFNoG-fUqsRnlTG_MhzLIn_UNDmmug,1049 +tensorflow/include/external/icu/icu4c/source/common/unicode/icuplug.h,sha256=YLP_ahGJtUvEoSkyVZh4tEg1RU42PQ6ekzfSmzto9zM,12109 +tensorflow/include/external/icu/icu4c/source/common/unicode/idna.h,sha256=MfS_9gzeqtknOloS4Fd37Qg7dhRtaJLlkW0GMOkCuVg,13000 +tensorflow/include/external/icu/icu4c/source/common/unicode/localebuilder.h,sha256=FL8KXX1iG9t_Fpba2RtKqlZgoGpqhlDjW0B4xPjnn2A,11495 +tensorflow/include/external/icu/icu4c/source/common/unicode/localematcher.h,sha256=Iv6ZjNrJizpCK87xAANx9Hh6clRVhHEc_NiwK56DcSw,27623 +tensorflow/include/external/icu/icu4c/source/common/unicode/localpointer.h,sha256=xKgr2ryyGPxNx2_hdHPDtAL5iByyx_WTQhyQ2q5s5sE,19829 +tensorflow/include/external/icu/icu4c/source/common/unicode/locdspnm.h,sha256=gj3evq6mIpudnPhejPPO16-1NHbIu8zVvPPBXA2Wfiw,7292 +tensorflow/include/external/icu/icu4c/source/common/unicode/locid.h,sha256=8nY09GMPphb-IHdGqvZxEWrxIgcqtAx8HJqu0h1tTwM,48796 +tensorflow/include/external/icu/icu4c/source/common/unicode/messagepattern.h,sha256=KdCHiGSSkKikuM9Ow2f1WD3T257Q8S_V9-j7lq1wukI,34521 +tensorflow/include/external/icu/icu4c/source/common/unicode/normalizer2.h,sha256=seYcErfEJ6lOq3Zd0RdjomZjNomK4opNIa1kR4eWuAI,34466 +tensorflow/include/external/icu/icu4c/source/common/unicode/normlzr.h,sha256=0Au5T9F8apP-ckZsitKrqmiN5RPJg1XAx6sByy8A6hQ,31682 +tensorflow/include/external/icu/icu4c/source/common/unicode/parseerr.h,sha256=hTNtYUSXQK6QoMLDbP1nHgqjIAyS2U4Hr8PoKqyxmzU,3155 +tensorflow/include/external/icu/icu4c/source/common/unicode/parsepos.h,sha256=KagcKVVTitggEg0q4x7R-W2qRGhgi6AX3NrHwuLaA2I,5692 +tensorflow/include/external/icu/icu4c/source/common/unicode/platform.h,sha256=j-W2y14JMifP9mUaJY4yzR1ZifXGmLzJP5-fwsbQbo8,28752 +tensorflow/include/external/icu/icu4c/source/common/unicode/ptypes.h,sha256=COoa_Ogm2o2uMBm91zNoLsc-0bO7O70P5zDrrgBrv7Q,3577 +tensorflow/include/external/icu/icu4c/source/common/unicode/putil.h,sha256=JYP06oYTa-g2ZSfHkSFyHU-RftSyETdmczMkn_g7H60,6471 +tensorflow/include/external/icu/icu4c/source/common/unicode/rbbi.h,sha256=Qh4hCvcrG-HlxfcfICyBbN45Ic5JuQa9FG9fQMIDsLU,28227 +tensorflow/include/external/icu/icu4c/source/common/unicode/rep.h,sha256=TF3fHEaQKej3P1a3exY_Vf1P1NFWg4R-Asc36ssBKhI,9599 +tensorflow/include/external/icu/icu4c/source/common/unicode/resbund.h,sha256=wUfmipESYy9g7G02bhHlijcBVvLXb71-ZedGGxicn_Y,18503 +tensorflow/include/external/icu/icu4c/source/common/unicode/schriter.h,sha256=ukMxGGLZN1LGrDnPk6XYbSweB3KoHDbJWyL4S6dmBs4,6475 +tensorflow/include/external/icu/icu4c/source/common/unicode/simpleformatter.h,sha256=A4MOFPsj0QncUYyMLgUW7jDcZHLLOol6AwlRC1h0Tso,12888 +tensorflow/include/external/icu/icu4c/source/common/unicode/std_string.h,sha256=L1GXs-ZUkls67drlIKNi8lRN2VJCwUDTzzK2fKg_ZIk,1076 +tensorflow/include/external/icu/icu4c/source/common/unicode/strenum.h,sha256=lKVKwM_Gpn_hf3NFcbqAxs_6lKORAng79IOBsDybqOA,10158 +tensorflow/include/external/icu/icu4c/source/common/unicode/stringoptions.h,sha256=kxUzqEmAHrsH4yT4d_nl1lwWt4LXCNZ49JGL9_ogaQg,5926 +tensorflow/include/external/icu/icu4c/source/common/unicode/stringpiece.h,sha256=-7SZHJIqbnc2K5U4i1DpzQbsLYJJPfcBJNmwovG02MA,10288 +tensorflow/include/external/icu/icu4c/source/common/unicode/stringtriebuilder.h,sha256=kO9pHHGzZB6JeSEhxfw6fexNdh1vO7FCRyA62lUBFEg,15698 +tensorflow/include/external/icu/icu4c/source/common/unicode/symtable.h,sha256=DsyQ6iKQ6tfuwau3E648l_1PLJ5WGyLPNCinV1C1Qe0,4374 +tensorflow/include/external/icu/icu4c/source/common/unicode/ubidi.h,sha256=7lcdURzKI9mKQA2K7w6RTOftZV08QVLVpmEcRGJrqaQ,91688 +tensorflow/include/external/icu/icu4c/source/common/unicode/ubiditransform.h,sha256=NXBQ9x5ucdA4KczNvQBodhqwluB-2fGTlwOiANwVI3Q,13003 +tensorflow/include/external/icu/icu4c/source/common/unicode/ubrk.h,sha256=8QQ3HEd1Htvptm0jF3SHYm1gN3LOB3g6KzkvbWdXBcc,25036 +tensorflow/include/external/icu/icu4c/source/common/unicode/ucasemap.h,sha256=Xd9STuiUnsA5cCZ9YLsurR7P-ypl073U1VnCEKHfC6w,15579 +tensorflow/include/external/icu/icu4c/source/common/unicode/ucat.h,sha256=ChmQ5WpzhPrTEU_gq8iFYQh6UWrKvb_pow7UwWGdTsY,5478 +tensorflow/include/external/icu/icu4c/source/common/unicode/uchar.h,sha256=ym08Z3WoFQpR-vxVxKlB78Yb6VT2ZOGmlDNMqtIbNVQ,144516 +tensorflow/include/external/icu/icu4c/source/common/unicode/ucharstrie.h,sha256=IL4Csx9Gigz7R0tWbSGtfE4oE1ghw4Bp88nqUU4jUQg,23066 +tensorflow/include/external/icu/icu4c/source/common/unicode/ucharstriebuilder.h,sha256=AwnhUe9hMhm8gTyH-uuMNO1-Gb5RUoTOFBwlVc0ahdw,7475 +tensorflow/include/external/icu/icu4c/source/common/unicode/uchriter.h,sha256=Zj--ZquOEF7r4_Yp9VC9M7Rans8PdrhucqZucIlQ_hQ,13521 +tensorflow/include/external/icu/icu4c/source/common/unicode/uclean.h,sha256=reAf7HgSllWP98n0ntFnNlFRYfQkrIJqpSq96cRHNz0,11468 +tensorflow/include/external/icu/icu4c/source/common/unicode/ucnv.h,sha256=KSi5_jwKBNE4h0Cm499s2PPqxSC-0kkeHtOXGkX1nDs,85029 +tensorflow/include/external/icu/icu4c/source/common/unicode/ucnv_cb.h,sha256=bbIDCj5DVNVVkUPLRPTZOjjV29dseYpnuPBY1BveFbg,6738 +tensorflow/include/external/icu/icu4c/source/common/unicode/ucnv_err.h,sha256=6U6Fb-kXtLVeS8uxxU9V-WR1O5qo0HZGUu5W6Om5RLg,21476 +tensorflow/include/external/icu/icu4c/source/common/unicode/ucnvsel.h,sha256=70hTo_gdQA1ibxGunG6AKbToDFbPCaKP9mC5NX1yihI,6339 +tensorflow/include/external/icu/icu4c/source/common/unicode/uconfig.h,sha256=UAl-T9KvD_if8NgCz2YTuDrt9O3yyQLj3aHSUr60Axg,12481 +tensorflow/include/external/icu/icu4c/source/common/unicode/ucpmap.h,sha256=UtKQ8faw2b4IOS33g-d_oQgLbgyOsVhoPf9iA7FSaL8,5663 +tensorflow/include/external/icu/icu4c/source/common/unicode/ucptrie.h,sha256=aYQnBZOXN17mv-xfcKrmZi-py-kVZVKGMBiORYcH7nk,23048 +tensorflow/include/external/icu/icu4c/source/common/unicode/ucurr.h,sha256=MGvf-pD2H1E3_S72Gbw3gmpMCZpsZsdBiQnvjDq9OtI,17173 +tensorflow/include/external/icu/icu4c/source/common/unicode/udata.h,sha256=y9tizaFYYJuk2yw3ZzEwXWexgZYIQ7BeZPf-IvgmzVw,15995 +tensorflow/include/external/icu/icu4c/source/common/unicode/udisplaycontext.h,sha256=6TywdT46c-DDEVqpQwKsJGOdKri-NYmCPcr-t74RiaY,6084 +tensorflow/include/external/icu/icu4c/source/common/unicode/uenum.h,sha256=ono7y6D-aV2WZHvbCYLhXozKDVXfAdVE-7KH5JRAKeI,7981 +tensorflow/include/external/icu/icu4c/source/common/unicode/uidna.h,sha256=Dat55fpcjq7BFh71Qm8ID0XRzyYekJ_mSL1agJowmZM,34229 +tensorflow/include/external/icu/icu4c/source/common/unicode/uiter.h,sha256=eRd0BpB6tezYYc9ykjjR2ohPhPDbDj4-pItOC4YB6QE,23299 +tensorflow/include/external/icu/icu4c/source/common/unicode/uldnames.h,sha256=Mq4YqGoUJ8pKrAHsE8ltKPfNe4_QK9m70r_oOjspOfo,10733 +tensorflow/include/external/icu/icu4c/source/common/unicode/uloc.h,sha256=JNWlDJmwrZFLN9TmdxV2hUsV5SI0wI-PiA1bTDtLY_c,55909 +tensorflow/include/external/icu/icu4c/source/common/unicode/umachine.h,sha256=bXn7r1cY7Rofge_kZkYooHkcESTXOjGhckS1VU6C50M,16439 +tensorflow/include/external/icu/icu4c/source/common/unicode/umisc.h,sha256=4cCu8lzE_kz4vLqIV4NRL9iTCG_uhv1kvwP4yz0RAIA,1365 +tensorflow/include/external/icu/icu4c/source/common/unicode/umutablecptrie.h,sha256=JkT0_NU-fneKgepaHs8I51PufnwIWh6LYnWj4xn1fKE,8494 +tensorflow/include/external/icu/icu4c/source/common/unicode/unifilt.h,sha256=Q2QUmFIR1GwJaL6ORudS-Lyi6H2H5AJa3w5gXllD-D0,4055 +tensorflow/include/external/icu/icu4c/source/common/unicode/unifunct.h,sha256=Z2Lhf1zOUhKk3ejNkiE2S5koqgdTQjGvUzr-dYFQ-JE,4141 +tensorflow/include/external/icu/icu4c/source/common/unicode/unimatch.h,sha256=_Hlav6C6-gKMwU6--x9nJt3-y68oeG_JQWpWDS3XoEA,6244 +tensorflow/include/external/icu/icu4c/source/common/unicode/uniset.h,sha256=axkCF7lD9fi-LU2JoOg_ptB3jQkJ4f5B2FiY29kPT6Q,66601 +tensorflow/include/external/icu/icu4c/source/common/unicode/unistr.h,sha256=kx-e_zjswsy2G3OoxtLCujA7gkU5WxWWiQvicJ-s054,174550 +tensorflow/include/external/icu/icu4c/source/common/unicode/unorm.h,sha256=3-7KMzMkVvWl1H58YLHdLQiVmumSNFWrgXI95utIc8k,21015 +tensorflow/include/external/icu/icu4c/source/common/unicode/unorm2.h,sha256=2nkwpzeX-NE2PChNL8UmnlHFy0MbRHVs6ac-6BlyTQU,25269 +tensorflow/include/external/icu/icu4c/source/common/unicode/uobject.h,sha256=JzDILmYWHdnnDs4mqsWX6rSMO62N4i5_haukc-YyqaU,10936 +tensorflow/include/external/icu/icu4c/source/common/unicode/urename.h,sha256=WffsApyglGz7P_qtwGvpXRk9b44rTKhXAD14ht6JKgo,137183 +tensorflow/include/external/icu/icu4c/source/common/unicode/urep.h,sha256=RTJ1JamgisBE9AHX7c9gx1dKfNvCnSkw1TOYfWohSkg,5507 +tensorflow/include/external/icu/icu4c/source/common/unicode/ures.h,sha256=DdcYlPta62pxLzkPb6Z8ouikGcbj3DxRLCRPaaZaKfo,37418 +tensorflow/include/external/icu/icu4c/source/common/unicode/uscript.h,sha256=ZvzNGqs5tGYIM3PTbP0lg7Bn9bbIPByuxr1_qknmU5E,27845 +tensorflow/include/external/icu/icu4c/source/common/unicode/uset.h,sha256=gwaDE_IbooZSL1hWVFff6vXFSmROIcr33MUxvc4HTCg,43616 +tensorflow/include/external/icu/icu4c/source/common/unicode/usetiter.h,sha256=zZdwLg2oaMcX9PyAonNHWjKgOgh5mOtJm93UyhZznDQ,9781 +tensorflow/include/external/icu/icu4c/source/common/unicode/ushape.h,sha256=-BuxHSCKXdD0SSWtCyIg6LwK1czQMoXp1Z4Nh0M8QJw,18430 +tensorflow/include/external/icu/icu4c/source/common/unicode/usprep.h,sha256=mZJCxwSPP8Xaj3tVLfGAGCurSCy98RhVQZB6Kmwpxic,8382 +tensorflow/include/external/icu/icu4c/source/common/unicode/ustring.h,sha256=lZ-2LYzGLGsrc1ACxhctWWmitbTACcnf-H4ysQtHLFE,74089 +tensorflow/include/external/icu/icu4c/source/common/unicode/ustringtrie.h,sha256=XJyqza0qdKcokOJAcfprGpbNDrt3RFKvunnh0f96pOs,3224 +tensorflow/include/external/icu/icu4c/source/common/unicode/utext.h,sha256=3LBoz4fyLOFsf5F03_Jr7ZZIBFswQFX6hqskq0I4isE,59471 +tensorflow/include/external/icu/icu4c/source/common/unicode/utf.h,sha256=ko41HXEqvNCXAUEgAhxMFxkaTADAQeak9ZxzublpUWA,8057 +tensorflow/include/external/icu/icu4c/source/common/unicode/utf16.h,sha256=AgCDSUurR8tdHP2bYmvWIUpEXT0S-gdCrjiIn6rSeXI,23910 +tensorflow/include/external/icu/icu4c/source/common/unicode/utf32.h,sha256=XQEbCBYaStPL4NMb_rDHb_-2xv6DLrnHb00v3h4AscY,763 +tensorflow/include/external/icu/icu4c/source/common/unicode/utf8.h,sha256=1_OplTfeSjFYFQGr_5V2LSF2uek84xqEltq_jtVvb9Q,31572 +tensorflow/include/external/icu/icu4c/source/common/unicode/utf_old.h,sha256=QEMlb-YOmo08kDH4XWkrvIFaDthYdXnVabhfzJklzXs,46929 +tensorflow/include/external/icu/icu4c/source/common/unicode/utrace.h,sha256=eWH8ObfMjfrNQI4ckC6DZ-dqeez1UlFITESk2lHneZE,17595 +tensorflow/include/external/icu/icu4c/source/common/unicode/utypes.h,sha256=0YkqOUiePsy0P8vFeofkkKwUWRkCj4hFg_mwFnTmwcY,31809 +tensorflow/include/external/icu/icu4c/source/common/unicode/uvernum.h,sha256=9wn1TqPvmlbgt1MxrOnjZc5w7uXUeUjLr28QUgFfMWg,6839 +tensorflow/include/external/icu/icu4c/source/common/unicode/uversion.h,sha256=Uc2dCVUv1PCfDDbXYVpJx9Z8TIV8XpiJNVQLOvrxFQA,6137 +tensorflow/include/external/icu/icu4c/source/common/unifiedcache.h,sha256=V4nfOsNBZso59-gJhqAEtahqng2c5mdH5N6nLsaD2Vs,19617 +tensorflow/include/external/icu/icu4c/source/common/uniquecharstr.h,sha256=YNG68U1MU2d66ZsuwENPAP85tpBzy5qpid2bdH4hHMU,3323 +tensorflow/include/external/icu/icu4c/source/common/unisetspan.h,sha256=Ccv8r0MQR_CZ0B-Uc_HPeZP__kxbJq7Lzb3256boLTg,5085 +tensorflow/include/external/icu/icu4c/source/common/unistrappender.h,sha256=fWy5AWfSZwlDI8YA1b9KuMT9J7fuF7ivhR1OSKxLkh8,2431 +tensorflow/include/external/icu/icu4c/source/common/unormimp.h,sha256=OWRE73lAWGeSXdjQGrWhLHNZLIruYknX1yoLR7D0qgQ,21224 +tensorflow/include/external/icu/icu4c/source/common/uposixdefs.h,sha256=AAVuibXIHIVP3yoEBO_Q1LYVRJnTnDjwDrvO1IOhxgw,2654 +tensorflow/include/external/icu/icu4c/source/common/uprops.h,sha256=3RVGTjvtJP-J5Z8b_TaPGT6QM7xqCWj2vc2ASf9kcl0,13162 +tensorflow/include/external/icu/icu4c/source/common/uresdata.h,sha256=B5L0LsrK2XTpBuZpCYYC14U6_YLSiinHB4N-42BwhOs,23799 +tensorflow/include/external/icu/icu4c/source/common/uresimp.h,sha256=-7CMbri_q5MPfHuVvI2vBZLNOna1r6OvefiVvjp88q4,15484 +tensorflow/include/external/icu/icu4c/source/common/ureslocs.h,sha256=1r_WW0cs0j0tNomToUHjqa_NiTH0HRblx3lUHe7in1E,861 +tensorflow/include/external/icu/icu4c/source/common/usc_impl.h,sha256=oDPrp1FN0HTJZYVwlSM_ImwIHyyQmb1Uuj_EUvFQAD0,5560 +tensorflow/include/external/icu/icu4c/source/common/uset_imp.h,sha256=BgkNmsa0v_GK49LNZnLRugL78BM-uzSCoft5LkD1IQA,1465 +tensorflow/include/external/icu/icu4c/source/common/ustr_cnv.h,sha256=FGkwOl1e5tVM0b0MKYBouyJqRK1DQ4zWKgVbvXwHpUs,1226 +tensorflow/include/external/icu/icu4c/source/common/ustr_imp.h,sha256=StiNJ7dPDor-GRErFsExI9BKO-c7NrvROTJvspeqC6M,5068 +tensorflow/include/external/icu/icu4c/source/common/ustrenum.h,sha256=lISmxhfyNwVDC3Dr4aVw3Qcr2fAfKjShgWqUkw_e32M,2554 +tensorflow/include/external/icu/icu4c/source/common/ustrfmt.h,sha256=YdxFAWz0tpERxuDoh2lCcGUMlEJFVX9AyDoNoZBhTHo,565 +tensorflow/include/external/icu/icu4c/source/common/util.h,sha256=hqxE7ilqTRI6U_yKwlBHuURE-Srui0qSXSjJulA674s,11212 +tensorflow/include/external/icu/icu4c/source/common/utracimp.h,sha256=j3eCDbw1Tsa_4tG_8atq_ClorpeGBR7X1egaAF8lcTA,14377 +tensorflow/include/external/icu/icu4c/source/common/utrie.h,sha256=b6QS70I2U8WPnstjXGf5GtaOPD6OfTcrvsxSwmlzFzU,31117 +tensorflow/include/external/icu/icu4c/source/common/utrie2.h,sha256=r6nIdjf_tHj7b1ekAx4Ho3wJT_AwK_WQeu7NEGGARMg,37430 +tensorflow/include/external/icu/icu4c/source/common/utrie2_impl.h,sha256=g-yj5aIUGjf56C40qxPLIO5HBoS-boV69iuKzDHaSMc,5388 +tensorflow/include/external/icu/icu4c/source/common/utypeinfo.h,sha256=rMQZ05a3giAI6K12Y-wYvZaHDqXP85F-uZuaGXYxjvo,1229 +tensorflow/include/external/icu/icu4c/source/common/uvector.h,sha256=oaOlaVqwW8fFjVAcmH4UoioXyPEPIsh8MGmSDHMnSws,12606 +tensorflow/include/external/icu/icu4c/source/common/uvectr32.h,sha256=Irjyh34fL2_IPobGSgWncOjoIYuFUsuhBicAwNYdI14,8588 +tensorflow/include/external/icu/icu4c/source/common/uvectr64.h,sha256=Z2NyEOT691mhMMHua3USV_4bOS-_uBJdl3ST223nEtY,7911 +tensorflow/include/external/icu/icu4c/source/common/wintz.h,sha256=g386KMp7KSIT--29yxcH65wpfCs5GOob9O5F5Hqy2dU,935 +tensorflow/include/external/libjpeg_turbo/LICENSE.md,sha256=7h6vGU1ZJLY2CvimumpOFVQDcJH3UFlDMAze7GXxrrs,5213 +tensorflow/include/external/libjpeg_turbo/jccolext.c,sha256=1G-IoeJxHavqZ5tzjGsdtzTJNUwIGlJOmsvfZoAgKRY,4521 +tensorflow/include/external/libjpeg_turbo/jchuff.h,sha256=L5mQNEQeoLKHBqRmL-OnkL3lfVgHhh3lmRq7bsmRRog,1514 +tensorflow/include/external/libjpeg_turbo/jconfig.h,sha256=dogBt_pfoTKmTSgwLmB3f8AQPDEzdnCA605GaeyQiho,1053 +tensorflow/include/external/libjpeg_turbo/jconfigint.h,sha256=7XAk97lHglebitmyE1zL-odzlSdmE0-fui4pC1LnmEI,1112 +tensorflow/include/external/libjpeg_turbo/jdcoefct.h,sha256=Y-Ss8s7rs0BjDr4DNKcbi5ApWPgP6DVBrQwSKhIuPEc,2704 +tensorflow/include/external/libjpeg_turbo/jdcol565.c,sha256=mV2Smwc0W2qd4v4F06Ld32gtnghJlfTR8V9M-vpCams,11665 +tensorflow/include/external/libjpeg_turbo/jdcolext.c,sha256=AMWJh-tJfbmWiPEzZ8k_MD3pbJZkzVQEKSnqwJXtjWY,4355 +tensorflow/include/external/libjpeg_turbo/jdct.h,sha256=34NIyW7d9Vem3PLp2UmFmJ4swdpc3XlD0MdenhscGxw,9708 +tensorflow/include/external/libjpeg_turbo/jdhuff.h,sha256=FmrtRSVIR7x5bjFL9Ukpd4RkyZ2g5C_tsDMOQIFE324,9795 +tensorflow/include/external/libjpeg_turbo/jdmainct.h,sha256=ikBVcmakbIJE4_pMPwJFZlElKwW3lptIJeSsqak8DxY,2448 +tensorflow/include/external/libjpeg_turbo/jdmaster.h,sha256=KtdonWEnPkZIZr5ra5rSJ-cHBjef17cltcRTUoX6KaQ,788 +tensorflow/include/external/libjpeg_turbo/jdmerge.h,sha256=NtA9opqTEmf_qTLYRgtP0tbtieHQ9kdZvpOU1oFzEKk,1630 +tensorflow/include/external/libjpeg_turbo/jdmrg565.c,sha256=Qy7vJ4Z0hdzJMW6acKJDMYxmvhfgZqqyv6s4KaGaOvc,11030 +tensorflow/include/external/libjpeg_turbo/jdmrgext.c,sha256=nHX96nQIn0AAjPgABr9sMkkKppSkk8ZsjlQ35I2hZiA,5787 +tensorflow/include/external/libjpeg_turbo/jdsample.h,sha256=gY2_kN6iATT82M-ads-0atl-jYRTtqt2NJmmF_LwZcs,1725 +tensorflow/include/external/libjpeg_turbo/jerror.h,sha256=ysfSo2MCdBL8wGqZNiMTX7ZExwwlCh-Pxb8HQSVSEuQ,15864 +tensorflow/include/external/libjpeg_turbo/jinclude.h,sha256=8YuevRlKfnXvDRZff9yXASmx5a9gNT8ek_ag6yRs2D8,3163 +tensorflow/include/external/libjpeg_turbo/jmemsys.h,sha256=ZT5AVIOdc4ew0AsSi2SyxLaQuSxAdkG2ZYqD3MKfHas,7788 +tensorflow/include/external/libjpeg_turbo/jmorecfg.h,sha256=_OOhgOSLtJpfj1llqECzR3Tn8ZSos7qRWcfV05s0eDU,14192 +tensorflow/include/external/libjpeg_turbo/jpeg_nbits_table.h,sha256=Ljo56I4yWSg9UbzcgFpsCSVEDUnYMwsyFE2erVgSiSc,270393 +tensorflow/include/external/libjpeg_turbo/jpegcomp.h,sha256=cbwnpzvLDG352rQvym7RDVlLN3kIZeEerSFcBlPSkgo,1130 +tensorflow/include/external/libjpeg_turbo/jpegint.h,sha256=QBMVmPPI1LvnsCok3hBPFq0-3wnRPaVdp7qdAWA__s8,15782 +tensorflow/include/external/libjpeg_turbo/jpeglib.h,sha256=tRzAy1rAgkZQBNyJQi69pDmwU_3_vPa6-KYzajKIdZ8,50281 +tensorflow/include/external/libjpeg_turbo/jsimd.h,sha256=ncw9SF-HWikU0uy62MEV47C1D0IU_jXbecKzXL__B0E,5853 +tensorflow/include/external/libjpeg_turbo/jsimddct.h,sha256=7WYADbf4QdN5GdqJ_4hwJi5xn-zDAH1y4c_Lkehsg5M,3085 +tensorflow/include/external/libjpeg_turbo/jstdhuff.c,sha256=TK6IpUvNfHVglDsx0ee0iMMbdnUKLQwXW8QHHlWDnK0,5321 +tensorflow/include/external/libjpeg_turbo/jversion.h,sha256=jmo92wxD0aQT22RHG_2bShZeCahbhFO2vBEYZ1tFlX0,1754 +tensorflow/include/external/libjpeg_turbo/simd/jsimd.h,sha256=vrMhq5UvKCn8rkQ436YhW40eE7KSi6YDjrc9AEXew-w,56939 +tensorflow/include/external/llvm-project/mlir/LICENSE.TXT,sha256=lLMBu2Uq41H1lBZVv1M_GhNjAK0Tlr50UsigT_LJE3Q,13151 +tensorflow/include/external/llvm-project/mlir/_virtual_includes/ArithCanonicalizationIncGen/ArithCanonicalization.inc,sha256=D1nRzerq1RKQrbpncJiLRKe4vgriOI5ISIeRIyUUSDc,162942 +tensorflow/include/external/llvm-project/mlir/_virtual_includes/AsmParserTokenKinds/TokenKinds.def,sha256=CwMHUPuS-9h8uV_R5NT1zLVxt5ewyfFuZU94JrR7_zs,3463 +tensorflow/include/external/llvm-project/mlir/_virtual_includes/GPUToNVVMGen/GPUToNVVM.cpp.inc,sha256=Fn9djodc8RRC9VNMSacrxSJfzLHybIjniI_ueUiU2YI,2060 +tensorflow/include/external/llvm-project/mlir/_virtual_includes/GPUToROCDLTGen/GPUToROCDL.cpp.inc,sha256=tEOeuLmnfXafp5WKd9cJggNrvwd_NhsUx4QYPAKXQok,2060 +tensorflow/include/external/llvm-project/mlir/_virtual_includes/MLIRShapeCanonicalizationIncGen/ShapeCanonicalization.inc,sha256=P6P1GIjQrH4hUvWS-tmy2-Antq6z6MkKK2xnxPqpFTY,16235 +tensorflow/include/external/llvm-project/mlir/_virtual_includes/ShapeToStandardGen/ShapeToStandard.cpp.inc,sha256=cSxWYR-ppFRiVNw3R6fH060SEonHVF5PpBgLYm30hno,5712 +tensorflow/include/external/llvm-project/mlir/include/mlir/Analysis/AliasAnalysis.h,sha256=g86WuccrnOJJY3tAPedpLJWYNDbmjbf3-H4nMBNHCWg,11225 +tensorflow/include/external/llvm-project/mlir/include/mlir/Analysis/AliasAnalysis/LocalAliasAnalysis.h,sha256=vVX-aPor0YeEgJe4lF66hDEW6QEjWV6xF5YvFvOM7z8,1512 +tensorflow/include/external/llvm-project/mlir/include/mlir/Analysis/CFGLoopInfo.h,sha256=7ehNIeJj-od3x1kPBBLEAlsExnHmTclT5fGuosuA3No,1853 +tensorflow/include/external/llvm-project/mlir/include/mlir/Analysis/CallGraph.h,sha256=NdIy6j8KM92X-mY_Wc_4lw8fpYBCVCiC-2U1Kw-w8zE,9899 +tensorflow/include/external/llvm-project/mlir/include/mlir/Analysis/DataFlow/ConstantPropagationAnalysis.h,sha256=eK1dFQ2b7VJQ7vOsRIQNfNndh7yEoiPpEwiCaQ9ku8M,4164 +tensorflow/include/external/llvm-project/mlir/include/mlir/Analysis/DataFlow/DeadCodeAnalysis.h,sha256=SDQOOeofYbJwS9bHVQVJb2-42wp1dU47I-6Q15fFzlE,9365 +tensorflow/include/external/llvm-project/mlir/include/mlir/Analysis/DataFlow/DenseAnalysis.h,sha256=JLglmZxy9TNG-G0BvF3jrwJJoNituivMEZUWiaRqnPw,26480 +tensorflow/include/external/llvm-project/mlir/include/mlir/Analysis/DataFlow/IntegerRangeAnalysis.h,sha256=HvSZQcoWsFTtvtsSt_65cdWEzPgLs-dGDb9sT6Zhb3U,4527 +tensorflow/include/external/llvm-project/mlir/include/mlir/Analysis/DataFlow/LivenessAnalysis.h,sha256=e5No19fp3Po_LyYPB_5KFIksiz-C98EjsKHXIdBfvcA,4431 +tensorflow/include/external/llvm-project/mlir/include/mlir/Analysis/DataFlow/SparseAnalysis.h,sha256=1ETlopYRuJeN0JC4xOkzrIhVjlDCIi8zhiAagz0i6lA,20906 +tensorflow/include/external/llvm-project/mlir/include/mlir/Analysis/DataFlowFramework.h,sha256=o3rI8HGDuiLPuBQTpKQTZQaE4S3CZdcLWPnOB7fJAC0,19727 +tensorflow/include/external/llvm-project/mlir/include/mlir/Analysis/DataLayoutAnalysis.h,sha256=Q1PFmxq1KDb211v-cykAaNKn39E2eY5YH9eWcXA7KPw,1567 +tensorflow/include/external/llvm-project/mlir/include/mlir/Analysis/FlatLinearValueConstraints.h,sha256=1CJ3Ue_dF_ZWoWs48rGZP_7bFmRMB2p5T3G-Q71oU6g,26017 +tensorflow/include/external/llvm-project/mlir/include/mlir/Analysis/Liveness.h,sha256=JKPtsJRLtzNhHWN6HBiEt0aZ0iFNMdZgjinITtQJ2g0,5724 +tensorflow/include/external/llvm-project/mlir/include/mlir/Analysis/Presburger/Fraction.h,sha256=7nie8u6_2kU4mY4_QZyvHRAkP_N0EN6NKs3qjBFsxO0,4609 +tensorflow/include/external/llvm-project/mlir/include/mlir/Analysis/Presburger/IntegerRelation.h,sha256=Rp24iJTVxYXLOREzDvDEbncxDy3g7BRjUdfUHxHcwII,40435 +tensorflow/include/external/llvm-project/mlir/include/mlir/Analysis/Presburger/LinearTransform.h,sha256=Tgug5zsfftBFfWXwuknPPi2cjkrRLf7J-NMrjc3hIyE,2351 +tensorflow/include/external/llvm-project/mlir/include/mlir/Analysis/Presburger/MPInt.h,sha256=Hhhx3imRAamYzwngNEFuR1SogwYvEnMyA26XX-_NAmo,24066 +tensorflow/include/external/llvm-project/mlir/include/mlir/Analysis/Presburger/Matrix.h,sha256=WWAfudtOdMJmrrAHeht1e-9uumD96d__8JcXQ6_qngs,10299 +tensorflow/include/external/llvm-project/mlir/include/mlir/Analysis/Presburger/PWMAFunction.h,sha256=Oa5iAN4J70WqeAq-gQ728dTCwMDDztQKvv6iOZHQdTI,10592 +tensorflow/include/external/llvm-project/mlir/include/mlir/Analysis/Presburger/PresburgerRelation.h,sha256=iyM0GMHdfxnWHKCj7ZfHReM5vcJDyQGt1NsVE-xvAg0,11353 +tensorflow/include/external/llvm-project/mlir/include/mlir/Analysis/Presburger/PresburgerSpace.h,sha256=-MRASAEadGBVhJdlrt_Rlypf6ytZKIbIUQRmpJfRPVc,13222 +tensorflow/include/external/llvm-project/mlir/include/mlir/Analysis/Presburger/Simplex.h,sha256=YKjcdh1elCZ5_8Hu5r2Q3Swo2ejnICHT2JJof3_ffSM,42773 +tensorflow/include/external/llvm-project/mlir/include/mlir/Analysis/Presburger/SlowMPInt.h,sha256=ZTwphZZfS1cm1PMM3q4S2HDRfybzOcbabTgD8qCy7BE,5409 +tensorflow/include/external/llvm-project/mlir/include/mlir/Analysis/Presburger/Utils.h,sha256=1jFSk-2fSwRovoR-faHAZAWxsL0X96soT87iCzMKWLY,12320 +tensorflow/include/external/llvm-project/mlir/include/mlir/Analysis/SliceAnalysis.h,sha256=ZX80rb0230YjKgx_53t9Ovmp8eo8O9akVzNCrF-lflo,10946 +tensorflow/include/external/llvm-project/mlir/include/mlir/Analysis/SymbolTableAnalysis.h,sha256=dr9-YKbKxPfdOVbZ2Sapi8akjOON2UMhxviLnaTtYoE,1997 +tensorflow/include/external/llvm-project/mlir/include/mlir/AsmParser/AsmParser.h,sha256=VWW2ukWnW1SJK5fw6aZRZEyQbNZHEowzlBCK_y2G05c,3735 +tensorflow/include/external/llvm-project/mlir/include/mlir/AsmParser/AsmParserState.h,sha256=6ZU6TZZHUA3jgcXx1cOraXR7UpDMFXfbmzECMm2uHew,8807 +tensorflow/include/external/llvm-project/mlir/include/mlir/AsmParser/CodeComplete.h,sha256=LQOxUOUj2s8V0k_c-3R7mEh-zkerEAEoeF-Fs88E3CA,2939 +tensorflow/include/external/llvm-project/mlir/include/mlir/Bytecode/BytecodeImplementation.h,sha256=8KSG-Xlcz3nciv0pyQXVvNtc4nNVuJlxsVqiAifVank,20446 +tensorflow/include/external/llvm-project/mlir/include/mlir/Bytecode/BytecodeOpInterface.cpp.inc,sha256=_7oa4Xokvs5y0MH3_OvQkjlQQ_PAHv224P63wVQmfnE,1073 +tensorflow/include/external/llvm-project/mlir/include/mlir/Bytecode/BytecodeOpInterface.h,sha256=IhzKrQzbkFz8cMfs6lq6spKzfgcDf4QNQtgt-tpurj4,1008 +tensorflow/include/external/llvm-project/mlir/include/mlir/Bytecode/BytecodeOpInterface.h.inc,sha256=B95AK1lEEKQLD3SBHqB9qK2EVuyw7zks35Ys-Bv4xnY,4200 +tensorflow/include/external/llvm-project/mlir/include/mlir/Bytecode/BytecodeReader.h,sha256=tnPwqbEJwRldeD1g8UBJeXoeuoTLctpFKgm-gmuruIo,4052 +tensorflow/include/external/llvm-project/mlir/include/mlir/Bytecode/BytecodeReaderConfig.h,sha256=o6OBwb1FtOfmYlWyA90mbu9AW1mVnOONFnhtMgUspBo,4418 +tensorflow/include/external/llvm-project/mlir/include/mlir/Bytecode/BytecodeWriter.h,sha256=Pq1emeKE9gYZbYwgNJVM3myB-Qc6Xf4LrZu4vayMIZA,7523 +tensorflow/include/external/llvm-project/mlir/include/mlir/Bytecode/Encoding.h,sha256=AA8cYrAIHtoH2cJMfka-kxraEN1H1GMtaZZ0qUr1llk,4562 +tensorflow/include/external/llvm-project/mlir/include/mlir/Config/mlir-config.h,sha256=gRHZFLe_W9tg6s4LaY2sQI-Yoq0jRR134U4KXqOYnHY,1381 +tensorflow/include/external/llvm-project/mlir/include/mlir/Conversion/AMDGPUToROCDL/AMDGPUToROCDL.h,sha256=GuIismYCAyP-muz0EOLQndjdEKa2o2Wt5J0r2ER2npQ,1245 +tensorflow/include/external/llvm-project/mlir/include/mlir/Conversion/AffineToStandard/AffineToStandard.h,sha256=Gm9ybmktyXhM0ouEY1oug65rhGQ9D7v6oFa8_bJbqKU,1940 +tensorflow/include/external/llvm-project/mlir/include/mlir/Conversion/ArithCommon/AttrToLLVMConverter.h,sha256=Pev1SAChnb3LHAa9pTODPohheZSHIiOitBzjLy7KRQ8,2309 +tensorflow/include/external/llvm-project/mlir/include/mlir/Conversion/ArithToLLVM/ArithToLLVM.h,sha256=SwbSF94DUjmhN5kRHq5jVe-ZO85kT5CYkL-b5iPWrIg,1006 +tensorflow/include/external/llvm-project/mlir/include/mlir/Conversion/AsyncToLLVM/AsyncToLLVM.h,sha256=B03a0RuGiMx0rMHbU2op8Zy8-JFD99rOE9nIsuMakrA,1386 +tensorflow/include/external/llvm-project/mlir/include/mlir/Conversion/BufferizationToMemRef/BufferizationToMemRef.h,sha256=zrzLdQbL6EKn4VYT_69OVzEPxjEfVQFU3Ghrc0GaQ60,834 +tensorflow/include/external/llvm-project/mlir/include/mlir/Conversion/ComplexToLLVM/ComplexToLLVM.h,sha256=eAixtOYSnDY2mbpPERp9YM2q_u7GJ2SfUxvfndg-An4,1987 +tensorflow/include/external/llvm-project/mlir/include/mlir/Conversion/ComplexToStandard/ComplexToStandard.h,sha256=2C_jhF7rmGSCZRizZh7USL92uwucHej5wm4FkEc0kW4,1039 +tensorflow/include/external/llvm-project/mlir/include/mlir/Conversion/ControlFlowToLLVM/ControlFlowToLLVM.h,sha256=vLc1kdWZkjd5O5HuP5nirjSfFy15ZzKnbqf5_jKyzDo,1837 +tensorflow/include/external/llvm-project/mlir/include/mlir/Conversion/ConvertToLLVM/ToLLVMInterface.h,sha256=5J9NejcZkb3gvmzssUDZdq9cVjshKOzoZwpwBhUUqcc,2438 +tensorflow/include/external/llvm-project/mlir/include/mlir/Conversion/ConvertToLLVM/ToLLVMPass.h,sha256=BgzrlF1Rx4SRJVNT5AChQuEk79ZAMMenlZ20OpBPsQw,874 +tensorflow/include/external/llvm-project/mlir/include/mlir/Conversion/FuncToLLVM/ConvertFuncToLLVM.h,sha256=9HZKv0UJE_CcI1hIwkLIVgR0jrOVC2fWaIkgD0rvXzc,2317 +tensorflow/include/external/llvm-project/mlir/include/mlir/Conversion/FuncToLLVM/ConvertFuncToLLVMPass.h,sha256=KkUB-aXpdbOmt3uJ26b3-LqgQTmpzECXCseCko99Nf0,776 +tensorflow/include/external/llvm-project/mlir/include/mlir/Conversion/GPUCommon/GPUCommonPass.h,sha256=wYuotq6gLe2fyv4t0feBVdL066cPDqJ6r0F---7-m6Y,2711 +tensorflow/include/external/llvm-project/mlir/include/mlir/Conversion/GPUToNVVM/GPUToNVVMPass.h,sha256=nHnX8ITZYo6-admOiPQlzOI5eVsBCE5n_OWlddgGms4,1848 +tensorflow/include/external/llvm-project/mlir/include/mlir/Conversion/GPUToROCDL/GPUToROCDLPass.h,sha256=MHE32eC5IemeJ7kGsSAuPDfHHC-pVeBtXqdy3CnhIKM,1971 +tensorflow/include/external/llvm-project/mlir/include/mlir/Conversion/GPUToROCDL/Runtimes.h,sha256=H9Ts-cHRYvsRXWTheyR_YVIOLv89grmBBs_QqOlt_8w,720 +tensorflow/include/external/llvm-project/mlir/include/mlir/Conversion/IndexToLLVM/IndexToLLVM.h,sha256=OFtgmq2ebVNMD8-zoNUNlORzKLoAyzR4PkubSBCHRJk,1008 +tensorflow/include/external/llvm-project/mlir/include/mlir/Conversion/LLVMCommon/ConversionTarget.h,sha256=2AdzIxdXksgOr7BIuJa1RcWouGMdZ6CPwzoVI0soyZk,838 +tensorflow/include/external/llvm-project/mlir/include/mlir/Conversion/LLVMCommon/LoweringOptions.h,sha256=OqwULCBIzvngl_-vBDcAXyiS7nrWQiHSjtHEXN5zAKw,2411 +tensorflow/include/external/llvm-project/mlir/include/mlir/Conversion/LLVMCommon/MemRefBuilder.h,sha256=S2a1WHEBxu1lA9INS0qxqDOE-pV799EXXGXV4shJJMU,12575 +tensorflow/include/external/llvm-project/mlir/include/mlir/Conversion/LLVMCommon/Pattern.h,sha256=YgQoBm5QBrlpXUdAVSVbr7aV9UwOOkdOGnPJyRn9EJw,9397 +tensorflow/include/external/llvm-project/mlir/include/mlir/Conversion/LLVMCommon/StructBuilder.h,sha256=aXNe1DG6onFFI-XI9MTBveKiTgoUnREplWdwi689MUo,1663 +tensorflow/include/external/llvm-project/mlir/include/mlir/Conversion/LLVMCommon/TypeConverter.h,sha256=XXALjNrVbAgw1nrO3atzIP-Gq8NeX2Xaeo5cFe6C2Zs,12567 +tensorflow/include/external/llvm-project/mlir/include/mlir/Conversion/LLVMCommon/VectorPattern.h,sha256=6r_EKFY-CQ4WiIlYcckoj9awLpEzRdqry7jpalLlqeA,4504 +tensorflow/include/external/llvm-project/mlir/include/mlir/Conversion/MathToLLVM/MathToLLVM.h,sha256=kLI4ixCDuWzr2Ixh3_XjgdqjpcYl_iWe-rGf-3k6hhM,1032 +tensorflow/include/external/llvm-project/mlir/include/mlir/Conversion/MathToLibm/MathToLibm.h,sha256=y9Zw7w2PAQzbbjBHYsU8tGCPqVjOPzPzNuFR5tlaFGs,1076 +tensorflow/include/external/llvm-project/mlir/include/mlir/Conversion/MemRefToLLVM/AllocLikeConversion.h,sha256=heZ_Kb3KwtgBwCxv5nblLv0429QgSwBbs2Rs_TwURws,6926 +tensorflow/include/external/llvm-project/mlir/include/mlir/Conversion/MemRefToLLVM/MemRefToLLVM.h,sha256=oy4D50_4n-u-99KOh3mSCPp3FpkKy5SW-A_J3XbJT2Q,1075 +tensorflow/include/external/llvm-project/mlir/include/mlir/Conversion/PDLToPDLInterp/PDLToPDLInterp.h,sha256=DNLotWjjBlhSIvUyyCxVtozw_Fc6rRWreKVcrNgY6GQ,1400 +tensorflow/include/external/llvm-project/mlir/include/mlir/Conversion/Passes.capi.cpp.inc,sha256=zx5i-rsqv12Nubo01JfHsBkmbH8ZWuZuHcCNZWu94U4,14557 +tensorflow/include/external/llvm-project/mlir/include/mlir/Conversion/Passes.capi.h.inc,sha256=HAfUjHDJ1JQyZJ4w4CI4m1UQLTIxSQgR3LfNVS6jIVo,12251 +tensorflow/include/external/llvm-project/mlir/include/mlir/Conversion/Passes.h.inc,sha256=wjSXRZ6BK3JB5AQ0pbQhwoQMurzmm2dHvqFREtBBkZo,379990 +tensorflow/include/external/llvm-project/mlir/include/mlir/Conversion/ReconcileUnrealizedCasts/ReconcileUnrealizedCasts.h,sha256=jcvHy9Wk20LvLMXupbLcT4waNDPfGzHcS8aob1U_w-s,1139 +tensorflow/include/external/llvm-project/mlir/include/mlir/Conversion/SCFToControlFlow/SCFToControlFlow.h,sha256=ZBLcEB1iV9aAq4wuRmF1DEuolsg5KwfvTpoWnnUl40c,1091 +tensorflow/include/external/llvm-project/mlir/include/mlir/Conversion/SCFToGPU/SCFToGPU.h,sha256=D_rSqlTc5lOLJPXd_N_ZmFrF1D5JNM1dJoRfD-qfvmc,2276 +tensorflow/include/external/llvm-project/mlir/include/mlir/Conversion/SCFToGPU/SCFToGPUPass.h,sha256=y7e4xL8Z1D_00RHpABPQsO88EWNILr-pPG3_QGkMyqk,1833 +tensorflow/include/external/llvm-project/mlir/include/mlir/Conversion/ShapeToStandard/ShapeToStandard.h,sha256=P_wNnbJgp8e_RuwgthpBMbJCuHqESBKF4S-gtJfZvwg,1144 +tensorflow/include/external/llvm-project/mlir/include/mlir/Conversion/TensorToLinalg/TensorToLinalg.h,sha256=c4IaZBOQnMHcRjfYg2PoQH9qOQvRSOHGleS1Bm7OEu0,944 +tensorflow/include/external/llvm-project/mlir/include/mlir/Conversion/TensorToLinalg/TensorToLinalgPass.h,sha256=bOrbAL2lvD_Q2-3v5Nu8EARuP8XNjymfRxFQabWWnlk,1003 +tensorflow/include/external/llvm-project/mlir/include/mlir/Conversion/VectorToLLVM/ConvertVectorToLLVM.h,sha256=iPK24OXsK74f7ZldxI78gizEz7TUG31gRCpKJgdovCU,1286 +tensorflow/include/external/llvm-project/mlir/include/mlir/Conversion/VectorToLLVM/ConvertVectorToLLVMPass.h,sha256=_Oh2KvO4KzDe0oYX071IeP21Qly_QEvZbpo5JiOSeDM,756 +tensorflow/include/external/llvm-project/mlir/include/mlir/Conversion/VectorToSCF/VectorToSCF.h,sha256=e3K2J-EH1KBjLLSyQYlt5J_rNW2ni6kZ-IzH_yncm5w,3185 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/AMDGPU/IR/AMDGPU.cpp.inc,sha256=dbIclVLQ3vUI4pMpH3vqcD4QZQqK4dgLCS0YlNKVf6o,358614 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/AMDGPU/IR/AMDGPU.h.inc,sha256=m42g-Su-5sH_iq8qPo-MPwE0TjJjt9ulaaWCUerYg0U,138552 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/AMDGPU/IR/AMDGPUAttributes.cpp.inc,sha256=pBai8nKLXSKoj4a-1Vu4S2gmc0G9PqZT2MV03CNH4-k,5472 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/AMDGPU/IR/AMDGPUAttributes.h.inc,sha256=00pSExqwkz2woZVVL2x1y6BwpILpMmMjRjv00eIRWR8,1478 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/AMDGPU/IR/AMDGPUDialect.cpp.inc,sha256=SvrvlplIu3fCl8tEcqTYwKahOO9bQa-6X7WfXOe_IXM,1113 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/AMDGPU/IR/AMDGPUDialect.h,sha256=_9Iq2NObk-1jPfzOwUdeuf5L4Sn-3ZsrNdrr9PWS1rM,1191 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/AMDGPU/IR/AMDGPUDialect.h.inc,sha256=iX_JwE-xWoeWevh7YRiaFNgvF66F6vA-gDW3rS3v0Ms,1465 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/AMDGPU/IR/AMDGPUEnums.cpp.inc,sha256=NUcOHR6JhbWGnX9tup_yRPE80IVncJJReylrguI7uuM,2377 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/AMDGPU/IR/AMDGPUEnums.h.inc,sha256=F6zywUELkW8_0EUHDQ4h6q5DNen8kjGySDZALq-OHGc,3415 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/AMDGPU/Utils/Chipset.h,sha256=YO1dN5YeNGNjAh2zkWTsLfyDMdFOtg5xDeSKXJsPVnA,864 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/AMX/AMX.cpp.inc,sha256=oFRQLfUc7IvkEUkQbOB_CThQFXxqhNL1mUpuogUic_c,105251 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/AMX/AMX.h.inc,sha256=IizbZVvCDc8xBFtZh5FC-DkYJWUoNmLvRg5niMkzNK0,68492 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/AMX/AMXConversions.inc,sha256=W4j7ES83-Lv2fdL2w_FJ-NLPA3tDk9L6J6fBh9-Q2gk,3825 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/AMX/AMXDialect.cpp.inc,sha256=LkouucExwuxL-kqp5hsLE4JmE5WmWk9OxCa40e1hV3E,980 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/AMX/AMXDialect.h,sha256=8P7mtiC9q3v6KkVncjZYeWxBIY9Jno6Fbd8M3dn0660,938 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/AMX/AMXDialect.h.inc,sha256=cda5H5Ozkc1n2EQRVOCUnqHpV0JxBUuYCK3qnx0GfcY,1079 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/AMX/Transforms.h,sha256=msg41iuQHXG-PX31cPZHqrI5YfnoiakRuwF3A88igLc,1011 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Affine/Analysis/AffineAnalysis.h,sha256=sy2cyR524Sv2jnusP71AbxhbjJoAPcJwKz85Z3MdhjI,8305 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Affine/Analysis/AffineStructures.h,sha256=JhQ1L5K7zJ-IMQM0BhtADxYBHptgtt3m4HG5X69C1ZM,12328 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Affine/Analysis/LoopAnalysis.h,sha256=86zEWNcOjiuQxIEQ1rA_-WN1NsiTAIrEMAVR8Ocz0zE,3892 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Affine/Analysis/NestedMatcher.h,sha256=DOQ-cYpe-tSGFxS2DX_Ly3Ia6xHBeMLr-iop_5-7UfU,7694 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Affine/Analysis/Utils.h,sha256=5SMWorAj4zCpeZWSes9AK8jKl4z725zIlUq-DSsTDm0,27024 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Affine/IR/AffineMemoryOpInterfaces.cpp.inc,sha256=hBRGLMgRfNmad9TxoxEb8zI4iht2nRpPZp-tU_UhMrE,2721 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Affine/IR/AffineMemoryOpInterfaces.h,sha256=EXn7ZaPAE1ZanGQyuOdpAD-3xpdMioJVY0J7xjaBSh8,865 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Affine/IR/AffineMemoryOpInterfaces.h.inc,sha256=p6Uj8tWhXKIxF5jQ3IFjv15O8eUBm8jXdiCTFaCKnQ4,23530 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Affine/IR/AffineOps.cpp.inc,sha256=7RA1eGdUqxE1Ks-bi34nzuwKcHk7PCb5MSvPJyu24S4,187829 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Affine/IR/AffineOps.h,sha256=MmhN_FnbdiqT4L73CYlgdwfrHtuDB87QRobBIWWqg30,23232 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Affine/IR/AffineOps.h.inc,sha256=ZJSgW5Zr_dhx3BtciUSg7wie7ebAJ0ytAzIeQyzOYoU,122146 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Affine/IR/AffineOpsDialect.cpp.inc,sha256=aS0AuOoccN_0x8EZzHNXUkEpplNF5MNK-0hyqq1YQOg,1062 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Affine/IR/AffineOpsDialect.h.inc,sha256=4vKECDCsXbeADfBJZae60KzUUwUiqbnMKjngQa5htTw,1486 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Affine/IR/AffineValueMap.h,sha256=P1_DRLomSDmhKgo2CdP9bWnJPKxDRgxRwGFnloD60j0,3948 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Affine/IR/ValueBoundsOpInterfaceImpl.h,sha256=TQmI3SAFZgE57QmZLIfvVIqWMwmdGWRY8xllkfAHoCk,734 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Affine/LoopFusionUtils.h,sha256=mTnGnUQjncZ8EZruPn7CtktL6M80LZIl3THCBk-co_U,7873 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Affine/LoopUtils.h,sha256=FRvE96nQn848zZ65AcyLWQ1pmR0L8NZIBO4PhoFeRA4,16239 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Affine/Passes.h,sha256=qsKBS5bTAP4wiZfrGtRjiThG0XHk_PWj_faG-iLKEmE,5501 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Affine/Passes.h.inc,sha256=xrWPgWTh-DYTOrjlEmbhKP5TgfwqvSPcTf-QNI9anJs,84257 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Affine/Transforms/Transforms.h,sha256=7euHakRodgZmhAHuZAHOugtX5ozfBYRoRO5DODs3-nQ,4349 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Affine/Utils.h,sha256=OFtareClKwPUNOA0Kmtb5EjkhDCbdOhZh6-SSS9nppM,17121 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Affine/ViewLikeInterfaceUtils.h,sha256=4OEfcphgVnE1xvx3So2PuB1A1BRS6BofsUaG-gnKq48,4811 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Arith/IR/Arith.h,sha256=jgSgfdZQQe8n9j0LCaWVIDFOzDxfZVPiZBPnVodkZTg,6114 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Arith/IR/ArithCanonicalization.inc,sha256=D1nRzerq1RKQrbpncJiLRKe4vgriOI5ISIeRIyUUSDc,162942 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Arith/IR/ArithOps.cpp.inc,sha256=bhYpkL7IkcGNOeMM3p-sb9H4qfwiHobYwpl-FyqfXnM,527438 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Arith/IR/ArithOps.h.inc,sha256=0B4ZSFmZ6bLRLcBVMe9Q9f6okZv9ChrLDiV0ERsha9E,331757 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Arith/IR/ArithOpsAttributes.cpp.inc,sha256=DOXwPi0-2nzX-8lIuRm6WI0VTNXGacarix_3GPINd8A,5842 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Arith/IR/ArithOpsAttributes.h.inc,sha256=h1nQ9tgHKo2fT88a--P97rAk_hXoFDX7WLW1iLTckAo,1506 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Arith/IR/ArithOpsDialect.cpp.inc,sha256=n8ovCbHPl9mJ7aF9mrAxQ1lNgIvAtr3F-o2sXpk2iKk,998 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Arith/IR/ArithOpsDialect.h.inc,sha256=EKMb-Dl71QEcFaDnL-3MF_mtjcLgvWBSFHv_v1XmIPs,1840 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Arith/IR/ArithOpsEnums.cpp.inc,sha256=K3XvzeQQ5l3753Uu2JGfVwYpYgKxcQgiUjS1Oi3Omw4,13518 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Arith/IR/ArithOpsEnums.h.inc,sha256=QE_IGBc1GpDcyyM8FpAS673ljfPbNoE7sFuExdUCvOY,14452 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Arith/IR/ArithOpsInterfaces.cpp.inc,sha256=e-oNdulCznlObkWrX1sScf47ub6YcC3jNHjiHoXeKIA,1010 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Arith/IR/ArithOpsInterfaces.h.inc,sha256=8CWgBzwfqp7JJdjLzmTZOtRDsy40wFXY8TD34ByWp4A,4901 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Arith/Transforms/BufferDeallocationOpInterfaceImpl.h,sha256=Wv7-xfQ1u3l9uRUU_ZBap65CPKAIHq8tRFqJBc-xI7U,787 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Arith/Transforms/BufferizableOpInterfaceImpl.h,sha256=OCLoeaekBXJ0yRxwSwg7WbSW86eEVywT7gExAH2G9hs,725 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Arith/Transforms/NarrowTypeEmulationConverter.h,sha256=aN9IosX6cZil2VLRNNHjJ8Y_xLs4p5HL9YyPMl4S7nY,1155 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Arith/Transforms/Passes.h,sha256=BQerBMjfEUcnX3SmOmJfiOehpMzMFdqnhYE0OvAsMKw,3778 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Arith/Transforms/Passes.h.inc,sha256=Hes9dn8-Zxm0XyuoBJktswo6uF4UIpyy-8h-zkepVq0,42661 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Arith/Transforms/Transforms.h,sha256=48igQ5KZ658SCZ_SamWPMWlip79d1pxjMk5QO-5zwx8,2421 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Arith/Transforms/WideIntEmulationConverter.h,sha256=k3wwrHt0u1fR2kvF1NTBCWD4FkKT5f1aK2LWBaNbCEA,1453 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Arith/Utils/Utils.h,sha256=5pwLsb0EnyRtD-II973HxI1Kurlms3mJ0IcNuXN-A-4,2942 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/ArmNeon/ArmNeon.cpp.inc,sha256=PoSPv5MjonkeXEyRMol2iq1zSObihbAMrloalfvcMms,33913 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/ArmNeon/ArmNeon.h.inc,sha256=LbRiwxTEb2mRSczUIfmmSfUvFXbJLX0F4ayVAkul02c,16300 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/ArmNeon/ArmNeonConversions.inc,sha256=OaDAZZIbVubMoGXyTBdlbT21fJKqW_VQ5WOY8yfQfO4,1133 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/ArmNeon/ArmNeonDialect.cpp.inc,sha256=ksKlAbdZtEblcrNHpGaIfgWIRPpgv6adUyV_E7haUHk,1019 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/ArmNeon/ArmNeonDialect.h,sha256=jZC62VErdNfquwpzuswuT8-94KCtYU6MBuoQEFkYTAk,982 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/ArmNeon/ArmNeonDialect.h.inc,sha256=__DRSZVNadFrVShu4kbR8WM2zxrJunyM6b9IqL6r6i0,1115 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/ArmSME/IR/ArmSME.cpp.inc,sha256=PKtWoVO1d81CQT7-BLL7P_IyvtZhaVeSGoR8G7UQGv0,786 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/ArmSME/IR/ArmSME.h,sha256=9ZkwA_xid9CQ0laiuJ97mdu7j2A0QaijIFIHOPWIjQE,1268 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/ArmSME/IR/ArmSME.h.inc,sha256=XYfe_30vhIgEkLmnJLVDvXgZOmzTeRj7fw2cGvSpUvo,815 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/ArmSME/IR/ArmSMEAttrDefs.cpp.inc,sha256=ZWfv7qnZ7P-HFQeWwTl2EaJHzWNXyZR0Sh5JlozkRII,5651 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/ArmSME/IR/ArmSMEAttrDefs.h.inc,sha256=lqLyTuW_hU7cKRwWzLYS1AWMgYlAOWj9z9MBaYExd0M,1532 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/ArmSME/IR/ArmSMEDialect.cpp.inc,sha256=SUknCuvynQjKrAe2Hp1ca_9fPTbw3iuTgsd_smUXnjo,1175 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/ArmSME/IR/ArmSMEDialect.h.inc,sha256=vAGl8DnW12S7FFeYU_1K2W-ROUnzStcavungm6_OZ2E,1469 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/ArmSME/IR/ArmSMEEnums.cpp.inc,sha256=MfleWFSW_3Mm_62QZ2Nwhi1tkaUOF7d4QpcY_Ne_fR0,1465 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/ArmSME/IR/ArmSMEEnums.h.inc,sha256=TxOs0-hSOiET1xYeqI4ub7AdpxKY9aX0O-xE4tgJmnk,3317 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/ArmSME/IR/ArmSMEIntrinsicConversions.inc,sha256=gwSRqvbeXOmiJ4yNT3S_AkIM7m0oZDksRYT-UqH4DS0,18880 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/ArmSME/IR/ArmSMEIntrinsicOps.cpp.inc,sha256=cRxhHSVPnHTi9GMIGCuv6ttX-iuEQ4ehO69YnYWeK3Q,212759 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/ArmSME/IR/ArmSMEIntrinsicOps.h.inc,sha256=5FScSJqzUIo8cJ0t-xJxv4XYnZCB7coD_buj5kSoKfg,189310 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/ArmSME/IR/ArmSMEOps.cpp.inc,sha256=Xf-HFUCGwZebWsP2TTdsmdr8xT26q0XC9MV-3Qui7p8,138870 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/ArmSME/IR/ArmSMEOps.h.inc,sha256=_tHzBJlyQo5kzMutwADxxQ8dU3xO37ldIVR-JjNGmbk,70179 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/ArmSME/IR/ArmSMEOpsConversions.inc,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/ArmSME/IR/ArmSMETypes.cpp.inc,sha256=IjAB-myhldXS6RW2gjpCVBpCZkUDP8w81p2NTsiVIiA,568 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/ArmSME/IR/ArmSMETypes.h.inc,sha256=64LZAuTQPiNIhz_gKBODV-E28z7OD16fC0C18aRvUc8,729 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/ArmSME/Transforms/Passes.h,sha256=UeaNvykpq0Jm9zsDej_Kq6FXL4DtpKd7X5kSTdMV1u4,2274 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/ArmSME/Transforms/Passes.h.inc,sha256=bc7B9xw5kQ595fxVzACEyiLO0f0bSD-lKAozfxAUuWQ,12014 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/ArmSME/Transforms/Transforms.h,sha256=7Wdxm2VOGJBQeljw2BTycD0ykUbkAbOCrwCT9DZV3hE,1227 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/ArmSME/Utils/Utils.h,sha256=IJ0-y1sVeRwSNyiYvETRibXm_KMkUi7zGwFpnRsHWyU,1771 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/ArmSVE/IR/ArmSVE.cpp.inc,sha256=xpE05vCPzovbT_i-skSQ9v9MpAP8h3aBHXZLC6dFIyw,210972 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/ArmSVE/IR/ArmSVE.h.inc,sha256=FaiHUw40hYffUxu0rVkVkGZEJBiMIOU_zPJ3r7UOxrY,139143 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/ArmSVE/IR/ArmSVEConversions.inc,sha256=nypt02ye88jK1_lV9JkPf03q23WkuxkCea61mtE75Cs,8222 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/ArmSVE/IR/ArmSVEDialect.cpp.inc,sha256=rvmh-3aQBHdhIu9cbrV0_UxhnovqQl5fMqj_XpUHWs0,1010 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/ArmSVE/IR/ArmSVEDialect.h,sha256=T9OhJDhjHDEGOpebT7W-mIdnHc5P8PDSpl7DW6ED1YA,974 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/ArmSVE/IR/ArmSVEDialect.h.inc,sha256=PbHUpeokLPEaEOgh2Gq51_t4R1CTz6BriVxqfrJ5hX8,1107 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/ArmSVE/IR/ArmSVETypes.cpp.inc,sha256=IjAB-myhldXS6RW2gjpCVBpCZkUDP8w81p2NTsiVIiA,568 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/ArmSVE/IR/ArmSVETypes.h.inc,sha256=64LZAuTQPiNIhz_gKBODV-E28z7OD16fC0C18aRvUc8,729 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/ArmSVE/Transforms/Transforms.h,sha256=mSDxudMjL0nw4l42p52wSehsASejEdnZ1EMYW7h4Wmw,1035 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Async/IR/Async.h,sha256=iXdWixTsm1jPP0YoiGkM047OKLfQwSSXEJrWUqoneIk,2609 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Async/IR/AsyncOps.cpp.inc,sha256=WywEUtzRD4MjgM4uCtcbxipxRNajqCxobJuujteNpc0,246834 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Async/IR/AsyncOps.h.inc,sha256=Y4PKwuG7jsezfQe0yNcFju-jNIFmwcoDd2XaFkqbgS8,165351 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Async/IR/AsyncOpsDialect.cpp.inc,sha256=cWkc7mE7y2OAmivS9kF7_XkT-ysRBsEbnqzWNO-PHxM,998 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Async/IR/AsyncOpsDialect.h.inc,sha256=5m1GZBj1om4uyPYiK8-GlONGggKvEkIDFg4LdZz7jhk,1673 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Async/IR/AsyncOpsTypes.cpp.inc,sha256=yPPVqJVutEbD-Sr2FPy9YobNB-8HMMeVh8zGRlf7ViY,6120 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Async/IR/AsyncOpsTypes.h.inc,sha256=T-bBC2uHTKRpADn0kjye9iWce3HABGJRcwDvhlRL5hA,2813 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Async/IR/AsyncTypes.h,sha256=l9qvdIzBa9_l9bFtT6nkAYIcGrxv7wjP-Ahnh6mN_f4,942 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Async/Passes.capi.cpp.inc,sha256=MIKD-a4HocnrGd2pq0ovzNttpxJfBsvIIvzwi6yIoiE,1650 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Async/Passes.capi.h.inc,sha256=zS3Y_q2LvSwLEtTuFKgOh4MWZMn5NEkGDEUw9oWKZZ0,1292 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Async/Passes.h,sha256=aVQ9SYcAkfVCW7gfypBW8_9EfZXpRgd4e6DZTarKQ8o,1848 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Async/Passes.h.inc,sha256=LttjMZcaYpgrvBlmBvshUR6KiW8Xy60mBPCQ9-Xm9NQ,33198 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Async/Transforms.h,sha256=Aj-1bvDPkr56BCqp28Abb7N_EoStYcqkuiFZmo-i44E,1510 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Bufferization/IR/AllocationOpInterface.cpp.inc,sha256=V5mwfcngkcx68JZC89D4EiRJ3v-BmMJ4tdB2BOv_RzM,2444 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Bufferization/IR/AllocationOpInterface.h,sha256=I64Yzrd0UxcELQrLhOwzGHYwEjPgdNJZTHZixi3a7ig,1193 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Bufferization/IR/AllocationOpInterface.h.inc,sha256=TQuOmxrvUWYqhE4E0SXOS9tp08XkzY2qd4oLx6Kwljw,9898 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Bufferization/IR/BufferDeallocationOpInterface.cpp.inc,sha256=RWqJ21AE4KnGcw3NLmzgHkR-Rc-HA1AGutixj8r8MEY,2771 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Bufferization/IR/BufferDeallocationOpInterface.h,sha256=4Kf4qHZYRqfOETwO0DHjgKOf5j2n8bV2Mvl0Cp5RHAk,10878 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Bufferization/IR/BufferDeallocationOpInterface.h.inc,sha256=oA52bsS8dllC44XOYTbgE5GqvZUGSi0gVG3_8VnmBTk,8895 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Bufferization/IR/BufferizableOpInterface.cpp.inc,sha256=M9kbH4JLWBjy4u5tQ5I7xqTYeo6lDU881W_iVY8jE5E,20575 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Bufferization/IR/BufferizableOpInterface.h,sha256=-cOv_XyIxdlqam0lN08HomMkWllOdRJN2S1oDi6-epU,27957 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Bufferization/IR/BufferizableOpInterface.h.inc,sha256=5jmKjxJVBuM_Wk65S5mzc8MJAHkoEK4T9J7I-XlSn_c,74660 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Bufferization/IR/Bufferization.h,sha256=DcJY6HZWqyZaGpxf9UMSb8p3qEN1IUTv735kANKO2I8,3394 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Bufferization/IR/BufferizationEnums.cpp.inc,sha256=p0udicyMuTpqXG4Nf1Y_eXyxU2rqEs4cDNfdkC_d8Pg,2587 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Bufferization/IR/BufferizationEnums.h.inc,sha256=z8B5aZU14AQ2ruU6kHMbLh577wrcbsW6I6uDKqueCQc,3774 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Bufferization/IR/BufferizationOps.cpp.inc,sha256=omQFyoxTR1Xl5IYW3mF04qQKTGGdC32S7-psBmOHNrU,107122 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Bufferization/IR/BufferizationOps.h.inc,sha256=CODLbch7e0iyqAAX_ppzlhASSL9iF5RbK7iGJMStiaM,63468 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Bufferization/IR/BufferizationOpsDialect.cpp.inc,sha256=5v6-zNX1pnsPDADJ43ue0rmuMfTXFH7FrGeG7TML-3Q,1296 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Bufferization/IR/BufferizationOpsDialect.h.inc,sha256=vRb4bQohJekODolbYOlMMEF9Fu1udELVXmqolEIhat0,2900 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Bufferization/IR/DstBufferizableOpInterfaceImpl.h,sha256=UNPCbtlC5j08H3QyW3I1Q8wtmpXGF5ILUprVLtlMW7A,2215 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Bufferization/IR/SubsetInsertionOpInterface.cpp.inc,sha256=fy0WGFrqCX_bmu3n6gXXwLKSW7smc_SXIldwpq8PjtA,3710 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Bufferization/IR/SubsetInsertionOpInterface.h,sha256=F9LtH40KuTXyHapqR2QR1zjqfyFMOiBmNtzGR0c-1zk,1045 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Bufferization/IR/SubsetInsertionOpInterface.h.inc,sha256=-rKkCjUeD2F6qM_5r92q01UnniqjA4e5Y_JT-t3XvTM,11567 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Bufferization/IR/UnstructuredControlFlow.h,sha256=hv_skHRumjE1S_WGFv2_DdiMouQNI-tY445rxoKGtXc,7640 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Bufferization/Transforms/BufferUtils.h,sha256=zCoTdxSkj1bSzKxHthiPKfHDPSPJDF4uHMPgKCTFUsM,5207 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Bufferization/Transforms/BufferViewFlowAnalysis.h,sha256=SiqZcUtZktAFhosc3F70JMHcHNDR_Xk0KtjzDLL1fUM,3067 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Bufferization/Transforms/Bufferize.h,sha256=TIsvFNmdJjEL07JRLSq1XD9RXpNPS-ILoryX-QmJcVc,4346 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Bufferization/Transforms/FuncBufferizableOpInterfaceImpl.h,sha256=3Lxuvdlo91wtm1e7fsG1w5f2GDG6BZ-xVw7pi1n_IQk,2957 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Bufferization/Transforms/OneShotAnalysis.h,sha256=4IZc68gWKS6dS8-3eWW2pwLjKMn7m5i9EoZ3T-MLMNY,11146 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Bufferization/Transforms/OneShotModuleBufferize.h,sha256=15_Sj9sZ7fLbyHstdEQk-Ubd_wDlGf5AWku0nW4Q2rc,2330 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Bufferization/Transforms/Passes.h,sha256=rQG2xKmrQ5G4iv2ParClDLCf3m3GZ4CG9tggLzTiD_c,9741 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Bufferization/Transforms/Passes.h.inc,sha256=piKuchrWbnBGA-oJtS1rVPWR-Av644fCuuyRq0CEyok,80591 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Bufferization/Transforms/Transforms.h,sha256=KSgZuIFIMq_oq3QuVd4X7XYDAQ-GvWkpl3_0ckdA6hs,2957 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/CommonFolders.h,sha256=3R2yp2sB-NRkK2dGeajntyYdqJW4ybiQJt0fLInvhAM,12658 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Complex/IR/Complex.h,sha256=q7D5MXicsBFUOsgnIAHlb4uUZMnH8WKRM1kfsRpgyMM,1362 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Complex/IR/ComplexAttributes.cpp.inc,sha256=eD_QRC2I1QdMEXC7-rrkYMTtCO3dYWGB87H4wGnr9L0,5374 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Complex/IR/ComplexAttributes.h.inc,sha256=7ueXOBz_TDzq3t1ACwdR5K4C4eCA0IKHI0vrVTQLocw,1955 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Complex/IR/ComplexOps.cpp.inc,sha256=c-oAmZHN5ZWukbx_CALHus2a8bdai3iqdqbc3SjzMVw,428826 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Complex/IR/ComplexOps.h.inc,sha256=6yYs0CvQvVzXvwU_WUWnLXM8XWMdzXb-i3dKC3fpPpU,242373 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Complex/IR/ComplexOpsDialect.cpp.inc,sha256=6xKSmzc1W0F9ctTnjfor1Yl7bFjNRvJ1kvxsO_y43Ck,1071 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Complex/IR/ComplexOpsDialect.h.inc,sha256=poS-cxDQDSoBK6L41r-llRNXQBa2XyH7XVLGOyNT660,1856 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/ControlFlow/IR/ControlFlow.h,sha256=O9sRnLBI7aMI4OciYvqf4K6tWrZfOCPsBBwhwmSr--Q,795 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/ControlFlow/IR/ControlFlowOps.cpp.inc,sha256=aNtcePHIIbNj09SYBKr0xhEl3bTyNCP8u7AVBY2qNVY,63620 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/ControlFlow/IR/ControlFlowOps.h,sha256=NWcf5Pqi7J36UrZugvMgY7byx0mKDbAI7z_MQ2S5APU,1132 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/ControlFlow/IR/ControlFlowOps.h.inc,sha256=RusXcsNrE0iHj8ihgKv6YHxWKKhliiRwmh2uR1le4_s,36593 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/ControlFlow/IR/ControlFlowOpsDialect.cpp.inc,sha256=itaL-Bh9gOGfzanbZtPEnXbX7B_8PSiDrvvo65mIYfw,1080 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/ControlFlow/IR/ControlFlowOpsDialect.h.inc,sha256=mZMP37qV8O4Vhoa4wxxZPgiaApCZ8VlZl2CT3dLR-QE,1107 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/ControlFlow/IR/ControlFlowOpsEnums.cpp.inc,sha256=brNEETQWwyiIHU4RKMBkksJOv-U3RGrNp7Pn2sUHxkA,649 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/ControlFlow/IR/ControlFlowOpsEnums.h.inc,sha256=gEY882Osff_DP9NEbvEM0DXtKBAd_D84WNg2WJ4Yitk,649 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/DLTI/DLTI.h,sha256=qh76II4PC9vJS59nyat4Ug4NOpKiA32amas4Z7C4AiY,4594 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/DLTI/DLTIDialect.cpp.inc,sha256=5R3IP9oQei_56lPFlv4WT_YocHJFnlSVR-nvCo99gv8,946 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/DLTI/DLTIDialect.h.inc,sha256=4rMhYvWrITLVjfS_x6jM95EfLT5MoUYI0V8BqIHu7Zs,2293 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/DLTI/Traits.h,sha256=ivdTWzA4yzAYz_0xBZQUJogERNJcT2EOhyeR2As3knE,1562 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Func/Extensions/AllExtensions.h,sha256=rO9y6rsyI_x6wNoxDyKNpwKM2KMWnn5dTPZgDSNP4CQ,1157 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Func/Extensions/InlinerExtension.h,sha256=Ayy-TPr_b0yK-9aSBl-DAFjSJt79gsPXRcoAWbT0kK8,976 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Func/IR/FuncOps.cpp.inc,sha256=4Eh-nTtmM3KnWaYcUy-RcH9hGqCPWVrnwEKyLPbLXs4,71530 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Func/IR/FuncOps.h,sha256=ojG46dYT9h29SJTmH1CS82gLPzrFpn6wlgu0tuWcNdQ,1565 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Func/IR/FuncOps.h.inc,sha256=usflTSkiHjONCwJxET2uWA_CpM_ep0xlKrdRl5AmHZY,42902 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Func/IR/FuncOpsDialect.cpp.inc,sha256=Kw4jt6qmnW3RddCC5rRWIaNJp_Rum0dgoMPWqtzDXCk,989 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Func/IR/FuncOpsDialect.h.inc,sha256=HhouZUqaDvGG5U_5sDX5aNbugCXT0kqO8LWjEUn6X4Y,1470 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Func/IR/FuncOpsEnums.cpp.inc,sha256=zPa4zJN5Oc0zLETu9NrpGfLIXIggXChG7_mM_Ar8fbU,649 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Func/IR/FuncOpsEnums.h.inc,sha256=7i81vNQEPGtUeAm37Pw6Tn0OQWQP7tCcqnroTJfaZ2g,649 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Func/Transforms/DecomposeCallGraphTypes.h,sha256=wXMGHbXuPjWd_DSoYS9zBCni2HavPUqW5svMOGyZpo4,4324 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Func/Transforms/FuncConversions.h,sha256=RCDambHLiTdRyehBWAvj6ZXTblLE1rSai1b2mzuMZ74,3210 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Func/Transforms/OneToNFuncConversions.h,sha256=RS5NRtLz_LCcKlAs5leX7RTAZMJO4K2VVXjHmWjlUhw,977 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Func/Transforms/Passes.h,sha256=FABUn4KmbXk_9_DlheH0WvDy5TJbIZCez5siQTqE0dU,1542 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Func/Transforms/Passes.h.inc,sha256=S0zh4oRmB210w-zpjYq_TuIpmIgxU8XAD1ixsZjdeaU,10512 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/GPU/IR/CompilationAttrInterfaces.cpp.inc,sha256=wdL2nDMu_LYhGxiOHkN2uYbvfOoF27eaBrkSMb9qJkg,3043 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/GPU/IR/CompilationAttrInterfaces.h.inc,sha256=RoiUqAAe0VN1MRD7UQHHI-2s0gU05YsuibQKkQ1pVdo,11428 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/GPU/IR/CompilationInterfaces.h,sha256=V9p9OPxSBWQuTCTtsZbBew2NXn9fkao0h_Cm3On4CLA,4386 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/GPU/IR/GPUDialect.h,sha256=UWc0tikWhNbVOsaJO0RAeMqIRvXXoaZP2Q4_YWRZFJY,7612 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/GPU/IR/GPUOpInterfaces.cpp.inc,sha256=y_Ywh-RyAio1hJbmGPpWtHryFt5PXa3LtumV68K0UQQ,1198 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/GPU/IR/GPUOpInterfaces.h.inc,sha256=8ODIz_LZGIypsaPzPt9E18Ns682KC8IZJpRubmW0cIU,6327 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/GPU/IR/GPUOps.cpp.inc,sha256=l5kd0mdXLWS-ZWYLli3PDTh3k3yd_VlNLnuco1mN99M,914405 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/GPU/IR/GPUOps.h.inc,sha256=lNt8_o2K8-gIW08UrIrjys-ZSZ3N9xf7w3Q85Ye1tSE,437885 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/GPU/IR/GPUOpsAttributes.cpp.inc,sha256=FjKsGMrzJYfad3rHPXdMU7r_Txs2_LgsGAR5zIJoH2A,62299 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/GPU/IR/GPUOpsAttributes.h.inc,sha256=bI5cgbEsA4Hs-x-rVkWYmJRswSczz4aHZqmEjlyrHl4,14057 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/GPU/IR/GPUOpsDialect.cpp.inc,sha256=2_9BLMF1I3FR7IFkhQ4wyngv-ZfjljthXAhyXZ5p1f8,1035 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/GPU/IR/GPUOpsDialect.h.inc,sha256=a7ZEn5bsWgENirPYzUV2wikOYWfnXJ_GuOVJwy41kjY,3015 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/GPU/IR/GPUOpsEnums.cpp.inc,sha256=aqGEMd9XFpzJzRln2cxQFpUwtqdwuVCBnA05BtKVPhI,17265 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/GPU/IR/GPUOpsEnums.h.inc,sha256=wGDhBIN-4r5mgnicbQieXqL5On8sLi3JtLjKtDhSAvI,30983 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/GPU/Transforms/BufferDeallocationOpInterfaceImpl.h,sha256=Fh4Wiys_vY6cixm0FzENmQKZ3cOB-YSNck6jY4kQ76s,777 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/GPU/Transforms/MemoryPromotion.h,sha256=rFcL98mEdnevlW6KvkXcRUTx_3pTXgh1S7qh4kNSHP8,1070 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/GPU/Transforms/ParallelLoopMapper.h,sha256=n3-oLjUEGaULApvhLvx9pJCfQ-9omra7DRhUkV9lgj8,1575 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/GPU/Transforms/Passes.capi.cpp.inc,sha256=4tcTPkFoK-C9m7hX5gRvK9Pdgn_U_cEuzFQM1CxvbtY,1951 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/GPU/Transforms/Passes.capi.h.inc,sha256=wjF0dWFWpnMdMcC0Jo9tq46HiR4Y-fPTX2wZyNiiuow,1558 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/GPU/Transforms/Passes.h,sha256=cnXTuQtNW6m6KLc3s1eADlEAeCru5dWCbEvhFE1cFKQ,7037 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/GPU/Transforms/Passes.h.inc,sha256=J-wGlTfu3764QeD0NU4ClUvZJ2c2aPmv_ThMTqRSDSc,51983 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/GPU/Transforms/Utils.h,sha256=hK-gisEmYZE05X0-mApZHr9xVcFY6BpZ-n00dtxbbB4,1971 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Index/IR/IndexAttrs.cpp.inc,sha256=3SPSYkjAIUP3U80oGlBmAm0_eNcepv4x_Z-uZuW1fZg,5632 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Index/IR/IndexAttrs.h,sha256=kLA9JRimIhS31ZxMCLqwqZwMeF5zKaOvMtaSJzVxfl0,858 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Index/IR/IndexAttrs.h.inc,sha256=ceEbcOQDFES5KXmiwrpofWhLxAxotdlqY2s_fzz3kQY,1547 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Index/IR/IndexDialect.h,sha256=rjN5Hjd6dKnP-XqQmzVH6VcRkDhLHshZAutd_nY-smA,787 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Index/IR/IndexEnums.cpp.inc,sha256=qFUWMl0VFKhVzl9D6hZ-t0jZh317C2BWECTsxLZKxQQ,2465 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Index/IR/IndexEnums.h.inc,sha256=o9Mf8ddaNlv5KzL5k62ozzxx8mq_rysbDXJW3qtDfNw,3438 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Index/IR/IndexOps.cpp.inc,sha256=5E6WuUV0uWPNEtP4VUc7Tz5MzBqvii_Y1nNCFatTINE,238659 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Index/IR/IndexOps.h,sha256=eiriSzvTDqtQjUurkkHM1WTQNdzaxAAfYBM6JIcUOwk,1514 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Index/IR/IndexOps.h.inc,sha256=hLgAbjaOoNVOycWpuPp4l0pUasex4mzHkzrmudHNfIw,158791 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Index/IR/IndexOpsAttrDefs.cpp.inc,sha256=3SPSYkjAIUP3U80oGlBmAm0_eNcepv4x_Z-uZuW1fZg,5632 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Index/IR/IndexOpsAttrDefs.h.inc,sha256=ceEbcOQDFES5KXmiwrpofWhLxAxotdlqY2s_fzz3kQY,1547 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Index/IR/IndexOpsDialect.cpp.inc,sha256=zm2aj4Oekz18Z0M5us_msrhrGlHrseRyYH6va6dEC8k,998 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Index/IR/IndexOpsDialect.h.inc,sha256=IoHyx19kYvgNdfZjO1DyW2STE5Ufl09PY_RpLwstuEM,1987 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/LLVMIR/FunctionCallUtils.h,sha256=Tg2RXJVzIQEGNKLRAJnup-kt3l0gRDRUbTRUCIm3wL4,3317 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/LLVMIR/LLVMAttrs.h,sha256=iEWWK5WbC-vJHcWScF5HO16H3khRAlfVj8rH8mUfyqA,2695 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/LLVMIR/LLVMConversionEnumsFromLLVM.inc,sha256=eXPeLv16e1STSTLU_zeG8TfPhYsId5DbGnsWFOPijkM,18985 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/LLVMIR/LLVMConversionEnumsToLLVM.inc,sha256=ukOeBWh7vXUlKY0TldVxEeC-KO8lW9taKfd1l_IjojM,14854 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/LLVMIR/LLVMConversions.inc,sha256=uUx4J_NeE9Cpm9m4k40Kp2imGqt4nwg-KM9LVFgro-U,18030 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/LLVMIR/LLVMConvertibleLLVMIRIntrinsics.inc,sha256=_QPrZricuq3i5AmJIWAoI92_bCTAIfCUu3412E9FKzI,5007 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/LLVMIR/LLVMDialect.h,sha256=lRPv4EY4asGutwzimMD2G86bvjYKlvabtPgIbdkLoHI,9100 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/LLVMIR/LLVMInterfaces.cpp.inc,sha256=vHwtlMCNonSlNmHuaXbuUUISt-TOOFxSew4tH_kwfAQ,3630 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/LLVMIR/LLVMInterfaces.h,sha256=tp9HD7egNayQ2QLvFQ6cHxbctgKdHlQ26w2-AK7vQHE,1221 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/LLVMIR/LLVMInterfaces.h.inc,sha256=9Xn-_eNfdwEINpxVXESDC-qr5mqz6UaZ-Y_deVXMaeM,29890 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/LLVMIR/LLVMIntrinsicConversions.inc,sha256=RqpdYuCRpqiu2U2Bj-EL2Lwl7EMqpGvqmyO_eIz-534,90673 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/LLVMIR/LLVMIntrinsicFromLLVMIRConversions.inc,sha256=3_fWEmu_ZT2Bm9POvgmb5qwkQZu03g44OA7A9t5Eol4,87472 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/LLVMIR/LLVMIntrinsicOps.cpp.inc,sha256=3hQdylHieabNE90W_t2Xd8oX3Wj_uAxKX-8KK4ns4h8,1620783 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/LLVMIR/LLVMIntrinsicOps.h.inc,sha256=iv2fsR2pwPK4aoIrlPYBcmldWa-aN5rWD3bbIJjGdqA,1108559 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/LLVMIR/LLVMOpFromLLVMIRConversions.inc,sha256=p_tv9jQ5Ez-I4JVIXi76-kh1oZJ-fBKTz-Z0HE8pVbM,27570 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/LLVMIR/LLVMOps.cpp.inc,sha256=ZJ4B5iaS8OjG1mbN0ybdPlod3ecWKQMD6EPNniZHxlM,1174270 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/LLVMIR/LLVMOps.h.inc,sha256=7qOsVysTdMOJD1r1jYXwjjIMlQhnH_1O7Ei_0yBLAAA,599541 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/LLVMIR/LLVMOpsAttrDefs.cpp.inc,sha256=gfKuLzgcAVpAmoD_-wS-2_K57nviyoUzSwGCPxCwjaQ,279445 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/LLVMIR/LLVMOpsAttrDefs.h.inc,sha256=DQyWMzZrbx583ZibiFf5aA-8OwXHhR21ZMJsjRGHzhY,33574 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/LLVMIR/LLVMOpsDialect.cpp.inc,sha256=qIdky4dea-umlovWIPPi7AIWVuAfevBHMcpIO4tg4l0,989 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/LLVMIR/LLVMOpsDialect.h.inc,sha256=Ak33TRZBD0ZEEuGeO9eKdtpGu_bQy-ijWm_yELz9jB8,6483 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/LLVMIR/LLVMOpsEnums.cpp.inc,sha256=lA40hvIaVExldqoFOkfQ_zGs3UxIOuJ-gcBnAaIgHMs,48769 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/LLVMIR/LLVMOpsEnums.h.inc,sha256=WHoBArLM-PBz7Jj9Bo0IjF6MkFHMORiBiVc6MyL5yoI,50205 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/LLVMIR/LLVMTypeInterfaces.cpp.inc,sha256=8SN7bpvHi_ecdjuUW2yN9WSKqPePzle6Po4L5ov-prI,789 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/LLVMIR/LLVMTypeInterfaces.h.inc,sha256=a4T-fHv3SFzhPJE2tON7sUCt3PNzGWS5kdgEmppN8fA,3941 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/LLVMIR/LLVMTypes.cpp.inc,sha256=F_l6dTdsKmREhSGFZojmFg23MEFtbpqQxtoJRfId70g,27731 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/LLVMIR/LLVMTypes.h,sha256=LQs_MmAGCiFglUUtCQXjhNINa9W5wJIzY1A1P3pH4D8,12745 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/LLVMIR/LLVMTypes.h.inc,sha256=aMyRVY8V9dMcggIEAPPJGUyjPUkTwa6kLvmzZqSdqvk,11295 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/LLVMIR/NVVMConversions.inc,sha256=t2aZjYCz6e0cyC2e9ejnAsOyt47Nhz46b2ODlnpVUtc,22853 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/LLVMIR/NVVMDialect.h,sha256=erU_dO2YKqCNtCukVb6SdCXFt5grnGKD0wSi7Eeg4s8,2023 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/LLVMIR/NVVMOps.cpp.inc,sha256=j1OvXmT-lSQWxLOGlwfF61D47Z1rs2I78z6dgiI-NEc,592031 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/LLVMIR/NVVMOps.h.inc,sha256=Z0V04V6RrEweLg87KrtEwIjMMmhUAnp6727JNq6iJtM,439739 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/LLVMIR/NVVMOpsAttributes.cpp.inc,sha256=bYQExYgLXn9lkHLIXpXSoWRqFJcfi9dMnd18oebtN6s,53259 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/LLVMIR/NVVMOpsAttributes.h.inc,sha256=zfYHjbkpA5tLFm_7MjulVqczsYuLEsn4n3N5uRuXGGY,10585 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/LLVMIR/NVVMOpsDialect.cpp.inc,sha256=Pbfig60-nXzCp3gHtqs_ls7LWYap-U33KMkz8HXQvmE,1042 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/LLVMIR/NVVMOpsDialect.h.inc,sha256=shGzwUE6jsqyq67IzjWKEY9JKL7TUNwIEF2q1gvHnys,3069 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/LLVMIR/NVVMOpsEnums.cpp.inc,sha256=iRpHc1wAAzZOY1Uut_6apJMZ7wnYbziRXIfpomCoSlo,12945 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/LLVMIR/NVVMOpsEnums.h.inc,sha256=-of6DwOAtADJxtQbqPfiDpsH4jsD6XwPkZ49s3ou1ng,31166 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/LLVMIR/NVVMOpsInterface.cpp.inc,sha256=UQ8Zrcq6BVwMfmKPoJjZPtaVlXSALfP30QubsUUmEA4,1701 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/LLVMIR/NVVMOpsInterface.h.inc,sha256=2WNTgKIVY5w4pvjCMlkgg_KCma_gaTl1rz2OywRJrXI,11331 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/LLVMIR/ROCDLConversions.inc,sha256=pdfDC4icspFq2UC10iGX-WAydAnoqcQzkiPKBtixLFc,40010 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/LLVMIR/ROCDLDialect.h,sha256=ujUgoaGGCHqNn-NPY4N3qLggLEGxsRQG6CxaV_qQvNU,1571 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/LLVMIR/ROCDLOps.cpp.inc,sha256=DwoMCz_u3Ze42kw-Uz0hL2x6zpErcRqBext-H8Vhm_k,702342 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/LLVMIR/ROCDLOps.h.inc,sha256=4_YR1Je6dFndsPriPN_EoeHbQJ1717oz5hWt31gr_uQ,454482 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/LLVMIR/ROCDLOpsAttributes.cpp.inc,sha256=nLDVknhpRpOUKgfEg7ij6RtLLbs_oawzy-p5nfNgJ5I,14595 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/LLVMIR/ROCDLOpsAttributes.h.inc,sha256=lkaH-6K7XzgR1rfAB8hVrq6UtJDMygUeU7QOBioZsko,2668 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/LLVMIR/ROCDLOpsDialect.cpp.inc,sha256=0e5LBTc5F27D9BV3JFDn9XdVqgKj0u3kR3MxN2w0Vjc,1051 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/LLVMIR/ROCDLOpsDialect.h.inc,sha256=rYce0KLlz2OgDIkHR7UkdJAjUuJodLHmHLaZL8ugiuo,2512 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/LLVMIR/Transforms/AddComdats.h,sha256=w1y1qi6CHo3DfPbNNh_26DYHtYn6GHXgShoTc9F-a5w,731 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/LLVMIR/Transforms/LegalizeForExport.h,sha256=LDWLtr-ubF-Et8z7vwqrTE61RHOLnH5t2ZG1U_P6Dqc,1363 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/LLVMIR/Transforms/OptimizeForNVVM.h,sha256=3bjRsaOoSB9Kn3-Vs9gFLWifiH5GeR6a1RNopsNiBZw,849 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/LLVMIR/Transforms/Passes.h,sha256=rqmgNxlChy2NCGQIAbDXAB0UV26RawfjiXUj8prmDLQ,1189 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/LLVMIR/Transforms/Passes.h.inc,sha256=eg6GpczKEitYyrQSlD28VJNVwgtrAUBUHflBoaZ-oyE,30721 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/LLVMIR/Transforms/RequestCWrappers.h,sha256=YwxPV48l8w8SLhTXIxovJzH-cxlExdMtE91nLtbx9VQ,806 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/LLVMIR/Transforms/TypeConsistency.h,sha256=Ka4GXftnpRIK4J7hqBpEu2cjtCvtQsH9foeT5dDfqsI,3691 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Linalg/IR/Linalg.h,sha256=LYI97fy5CZWyEtKrn4GRrp0l0c1u5LUJAGlgpgZmR6A,5101 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Linalg/IR/LinalgInterfaces.cpp.inc,sha256=iyqkghQP5V6AsefBQ50koSQy_WjOVvDMmDL1Ta-gO9U,14176 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Linalg/IR/LinalgInterfaces.h,sha256=jNZ1ZC33t-RrhoSacMUcskS7b7iOiGePVLNEYwlzzNU,8115 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Linalg/IR/LinalgInterfaces.h.inc,sha256=hJU6OAb0QCdp0OKj6Qv0FOJQ6oo-d6SmRjw9pG0r0wY,101919 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Linalg/IR/LinalgNamedStructuredOps.yamlgen.cpp.inc,sha256=DeszWe94xpVpNEvXzMyEcmtTZf8gaMyHhz_EcWMwt8U,330771 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Linalg/IR/LinalgNamedStructuredOps.yamlgen.td,sha256=h-cDMG5i_lS822ePYd6hv_TBJTMcMymQoikvJR3Pcx0,235044 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Linalg/IR/LinalgOps.cpp.inc,sha256=xuWgH5LHZKdhv_k68GTH_6vRrCO1tQDe7LkXbRBZdD4,38914 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Linalg/IR/LinalgOps.h.inc,sha256=jOtQxrQ2Rc5uomsbVfKiV0NX6fRlhw58bko174amw2k,23070 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Linalg/IR/LinalgOpsAttrDefs.cpp.inc,sha256=kCzV5gsyTdjKvR7Rppn8oSfSKXa0GnrJ9-k2AqcBluI,15095 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Linalg/IR/LinalgOpsAttrDefs.h.inc,sha256=Lx4RDPx5rO9t0hPshv0hzYWZNe-nxG_qdOV7WfqxhJw,3455 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Linalg/IR/LinalgOpsDialect.cpp.inc,sha256=z4WOnnNk-mk3yJFzPDRSZKWva9nO_VeSzlUnN-2P7-s,1286 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Linalg/IR/LinalgOpsDialect.h.inc,sha256=3Pc0EdleOPujwzvRWQwvltwPU-l_Br_LulA4QLiyw_8,2739 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Linalg/IR/LinalgOpsEnums.cpp.inc,sha256=foD1561NFoFibFgtTDuYJWTiaao-lv8PW2aYqoDwWFs,4046 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Linalg/IR/LinalgOpsEnums.h.inc,sha256=kVmMCNV6fCUEftCwFFLa7_pWQFgbuoZFETxXyDgjKL8,8390 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Linalg/IR/LinalgStructuredOps.cpp.inc,sha256=RLLi2TvPOnFUZNBjNTMw2n4Q1QLyKR-0ZxHuEFzJ8UY,1302315 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Linalg/IR/LinalgStructuredOps.h.inc,sha256=5vAUTVL5bY3MIlSnGDAr3-SZ4lFG-f6HFesxQWEZxs0,827921 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Linalg/IR/ValueBoundsOpInterfaceImpl.h,sha256=VJc1OmUZZAuppGvXKr9vcR1UR-DNlKj3EYWs-lKpXfU,734 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Linalg/Passes.capi.cpp.inc,sha256=ooG3rpdHZA7dS5yu04d0lZPM2XvHYyHcEsxDTH26ZfE,2738 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Linalg/Passes.capi.h.inc,sha256=f4c3syLc2RPu5FrTN9nAWZYv4v43aaTCoP-DfIGhRwU,2167 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Linalg/Passes.h,sha256=KEnD1mHG2TOMtUDEV2EM0DR6zB_fEe3I4JK00BYGS6o,2714 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Linalg/Passes.h.inc,sha256=n1Dbrb_z-NIzoOPwmP6z81rgAWjYceMBqNIOUXUEYOE,57604 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Linalg/Transforms/BufferizableOpInterfaceImpl.h,sha256=lKcYMUtaQaZfyzhN0QuDcuWglND9WpZhSiWCeh21oj8,729 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Linalg/Transforms/Hoisting.h,sha256=M-ymK_vNVTg_Uehi_g8I3eo8uXm1pzHjdUA1gHOFy5I,6612 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Linalg/Transforms/SubsetInsertionOpInterfaceImpl.h,sha256=n6YOhkYcF-SKQFCtmO0yOe6BRmgkhyQ__wKdCUZ-Pg8,746 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Linalg/Transforms/TilingInterfaceImpl.h,sha256=HQEHmGDUyW7guG85G44_sqtR4TLTi6wqNjqdbic_qZw,697 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Linalg/Transforms/Transforms.h,sha256=pWXK7R1P80P27NmsSnBsr-Tuc_zcnNooTaQxvBeDLrU,68897 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Linalg/Utils/Utils.h,sha256=2JKv8w_8PM_z8Pc9c0mOjAdy2ZkZQg5ZeW8g0nyxUz4,16688 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/MLProgram/IR/MLProgram.h,sha256=lr_-ieKI5O-X-BPQk5jfcQP1wwTaiOl44ApUtR3fmUg,1564 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/MLProgram/IR/MLProgramAttributes.cpp.inc,sha256=62lMigFKCTLi2ch_zPW4sp3RuwnWSOATnDFiS7qtE2I,4550 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/MLProgram/IR/MLProgramAttributes.h,sha256=39eUWODXP6PUJSPh58qhtEI3Q7CW0nQ7UcjgsYkfkEc,915 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/MLProgram/IR/MLProgramAttributes.h.inc,sha256=u8DI1LgHsGZn62Pqf_b82RKD7DUEJckz4pL8HZCa3Us,1462 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/MLProgram/IR/MLProgramOps.cpp.inc,sha256=BSF79aNe505hXrIpDblC2W-7GqmzoVXAYgmF7oV8xc4,160911 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/MLProgram/IR/MLProgramOps.h.inc,sha256=ippv4-QW09YKJY4vNWzyK98YSow-hssepsS5RYY27FI,92019 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/MLProgram/IR/MLProgramOpsDialect.cpp.inc,sha256=X86_I8bgmGxkyF4wCwn-DNYYbvdHFkj_lS8Ko6VJr4g,1037 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/MLProgram/IR/MLProgramOpsDialect.h.inc,sha256=ohRH2RMcRYENIXyUKIX7ipo1E5VULXSELaRJMsp3ymY,1764 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/MLProgram/IR/MLProgramTypes.cpp.inc,sha256=QJSj2nKEc3Or0ev6e_LmUjptzf2s5kbAH1U8aN9QRyo,2653 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/MLProgram/IR/MLProgramTypes.h,sha256=THwkjAaL-IHQRf2xsIl4dxnPAs6TZY1_xddzQLmVdYw,837 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/MLProgram/IR/MLProgramTypes.h.inc,sha256=8kGKk-n5yAaa29ggt7vEI56b1xImiK4EJjV8yzaHkmE,1104 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Math/IR/Math.h,sha256=Wk03OzLmTCv3whs4xLBY6AfJRkDnfUJ7Xi5CTmdKO7g,1347 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Math/IR/MathOps.cpp.inc,sha256=QHPal-08SF6C2OzxtSDxjFZzAEs_x464fggPHZiVkGY,484398 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Math/IR/MathOps.h.inc,sha256=ceAPbwM_LPtC0wJm1H2bWtikdbqYipp48e3NV7JcBYA,281215 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Math/IR/MathOpsDialect.cpp.inc,sha256=Hl8R-Qo6Tc0ZMpYKRYq3z1MdxWS0szaHUnKOr1ttjhs,1052 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Math/IR/MathOpsDialect.h.inc,sha256=Hrxru0TgAD5xfy2txklErruEpdM1bmIm4i9PzNw18XE,1470 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Math/Transforms/Approximation.h,sha256=9i_CzsapNlGmZWi0JvwDvC17MXA6SSemI-JNDN4NXKk,934 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Math/Transforms/Passes.h,sha256=EBfpk4MraB01Hdp7qiVCc3lQt0GhErhFqtWrI4KvJRk,1949 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Math/Transforms/Passes.h.inc,sha256=KB3QAqcCI-ykh33_SybQyuNIeNPoXxXtgu4AV2ZgqbM,5585 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/MemRef/IR/MemRef.h,sha256=Let2-vg5WvfrNvH8nUWV5SBDTcceEgaBHzFmQkxF1oo,3595 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/MemRef/IR/MemRefMemorySlot.h,sha256=IKgDGzTLtbXSTqvQK9P-o0OmliMQPrQz3zUul5xHoA8,692 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/MemRef/IR/MemRefOps.cpp.inc,sha256=23o_DsicIHs-6muzTKgST2ONHBm42ISh2Jfo1NhX8DM,436733 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/MemRef/IR/MemRefOps.h.inc,sha256=sfDT_rRwsDrYMNYj3YYBQhaGA34qSvW8BhExI9YPlf8,257040 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/MemRef/IR/MemRefOpsDialect.cpp.inc,sha256=i7CR6aMSm9CYWxq8UO_ucIhTu0eaaZDv02hPm_mmFjg,1062 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/MemRef/IR/MemRefOpsDialect.h.inc,sha256=kAlZc9h9pUEEq88wRDUeHTrn6CPZHR3yyOrpBiPWxVI,1486 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/MemRef/IR/ValueBoundsOpInterfaceImpl.h,sha256=ATDiXMbFKhnv72tpciDG60lFRSaMtN4UUgFtYteoPQY,734 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/MemRef/Transforms/AllocationOpInterfaceImpl.h,sha256=_emQPwVepoSOkP5nwMEB9w839P7h60Y7-yVpWhUdXT0,721 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/MemRef/Transforms/BufferizableOpInterfaceImpl.h,sha256=Fzv_c8SaxY3vHXegoT9t_QqAsmBmNDE0e9nYtdPIwPM,730 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/MemRef/Transforms/ComposeSubView.h,sha256=D-xMLCXD2gkNK-y_lNLKx5U5YLk8pR0htLC-Pd82uP8,929 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/MemRef/Transforms/Passes.h,sha256=6Tft5nCAxCt3aZNfhOZu0POFm138w4SpOstd5_3R6Ok,3143 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/MemRef/Transforms/Passes.h.inc,sha256=AFfW79u1t5t22Ld1zkRU6hj3NmicRLZf5EsvQFxYYfc,42130 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/MemRef/Transforms/RuntimeOpVerification.h,sha256=169V6uqdFhNAr-2s_cmd4Yq0A9LqX_uP-jOTl0yVpZo,721 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/MemRef/Transforms/Transforms.h,sha256=xoMTKfU9s9SqRYvMXGAxDcKIONfE7KqZ8av1cfvnHDw,8701 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/MemRef/Utils/MemRefUtils.h,sha256=tffVqf6oPfZ3AosdURhemCAlcCdSBZnYfwEGdf6V_Vc,3105 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/NVGPU/IR/NVGPU.cpp.inc,sha256=0NbUqrP3TypxNnDfPqrOt2m1WZ7DKxUbSRJoBFkVcQs,252229 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/NVGPU/IR/NVGPU.h.inc,sha256=dEkXI0Mjb91lFtqypg9HwDaNA3IYpcLGw_FvZ2jP6AM,123217 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/NVGPU/IR/NVGPUAttrDefs.cpp.inc,sha256=gdyI0fyHT-sfBHaDs0Nz1EOpYO5cNrKFrnaoPpHEAdk,15691 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/NVGPU/IR/NVGPUAttrDefs.h.inc,sha256=FxWQsHLVmzuOLhhXTMbSSMCv1JGEHJIu96Kob64jRpA,3847 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/NVGPU/IR/NVGPUDialect.cpp.inc,sha256=UNBlB1yZ28cQ4RunVq1TO7eduvr5tDHsE1bRAVtRixo,998 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/NVGPU/IR/NVGPUDialect.h,sha256=xkj_h3aPTq5K_mHwe6jLaNN_vdlv76dIAu3mMBULHu4,1209 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/NVGPU/IR/NVGPUDialect.h.inc,sha256=fRFPjafNU-gvU_0wqzoef3pRt1EXfjM4WymHm-JehOo,2750 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/NVGPU/IR/NVGPUEnums.cpp.inc,sha256=AkrNFSU5T-5prZRupzMB--RvTaX3fFGUXO1Bt_oDLi8,5103 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/NVGPU/IR/NVGPUEnums.h.inc,sha256=VDz_dn7GR6qaOoeQ9ui_65wxJY8fE0623PmVcgz9wTs,11982 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/NVGPU/IR/NVGPUTypes.cpp.inc,sha256=XnUpyagno53P0O93f88jriDM-jtDYRPL2gCEr6TrX34,27921 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/NVGPU/IR/NVGPUTypes.h.inc,sha256=64Ukl-Wl42EZicJGYbafqZoj4nej0UycrFmNIJrB4sc,4776 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/OpenACC/OpenACC.h,sha256=lIDz1s8eYJvaJlpgY_cQFf8mr-aMzYBGLn7teCCYzQg,4145 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/OpenACC/OpenACCInterfaces.h,sha256=dpPXU36ER4b0i1uNgEZs273Wckh-3ZgGmsBUBeXo7V4,786 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/OpenACC/OpenACCOps.cpp.inc,sha256=0B_GpxRVIGkFePEnpC0hREuH_F_FgeASDkr4tiZxOmQ,1369463 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/OpenACC/OpenACCOps.h.inc,sha256=IwpND9r1l0nHgT2xhWT27Cu6Un9wsf9wBtGXGJFZPrk,509247 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/OpenACC/OpenACCOpsAttributes.cpp.inc,sha256=hlKv5ZxnTYu1BY_x_1NfMb3OZ2eFm5sf1ZC_Al_YVgE,28790 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/OpenACC/OpenACCOpsAttributes.h.inc,sha256=jcuI8CJAalPyYoxR7sT5R5E4Rul0ME0JINVFL6ELl2I,5304 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/OpenACC/OpenACCOpsDialect.cpp.inc,sha256=Xmq66GO3CsX_n9erYTlybHm3rtfKj7dSzcKINHBHVpQ,1130 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/OpenACC/OpenACCOpsDialect.h.inc,sha256=NBPU8sEg0ZCMv-TDyjjAlpUwOcbXB4A0OxmvQD-DGHA,1728 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/OpenACC/OpenACCOpsEnums.cpp.inc,sha256=TAsVa7kN6CVFrYeUH5JYPfGg5MucGzEsr4pLeuKTZ1s,8098 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/OpenACC/OpenACCOpsEnums.h.inc,sha256=HYz44H2wxtMc6IXRPG5nN4dfEIou4uq5IPamHzuoECM,9201 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/OpenACC/OpenACCOpsInterfaces.cpp.inc,sha256=urRhxNgjzlZt1cFAVfcrlYtv7ZDmrnRVO4EWOxHmsUQ,935 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/OpenACC/OpenACCOpsInterfaces.h.inc,sha256=6aDnpxsN9JCjIghBH03arxxxFhbgoSApTaSXgizuJfI,3936 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/OpenACC/OpenACCOpsTypes.cpp.inc,sha256=uEkCuodsKlFlDOUOETk9rHuNQ6b2PJUb9ephd49ALNo,2609 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/OpenACC/OpenACCOpsTypes.h.inc,sha256=sR5D2D76IfhQwjx697HeK7OD8R6CjYlSSLiK8GC08TI,1112 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/OpenACC/OpenACCTypeInterfaces.cpp.inc,sha256=RrGm5M1HC8E2PxldTMYtbHvgtOHzdNIke_v9u2_dJAc,768 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/OpenACC/OpenACCTypeInterfaces.h.inc,sha256=N7W-V775ODK25wJT85AoRfPtnzm8hs9q9YrN2L6Owm4,2969 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/OpenACCMPCommon/Interfaces/AtomicInterfaces.cpp.inc,sha256=f14o_s2ek4GN-q9W8eCxEFsf62nhoF6AdWoA62Sw0rQ,3888 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/OpenACCMPCommon/Interfaces/AtomicInterfaces.h,sha256=KiDtENXNhLIuTjjf29DISv9ilL_M0mmSB3M_uNq9DpM,893 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/OpenACCMPCommon/Interfaces/AtomicInterfaces.h.inc,sha256=DC6wEm4jph-c0J3Qamzx5znB8uJVvtiDcV1Vc4GSTgs,35713 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/OpenMP/OpenMPDialect.h,sha256=uBx5Vpv75ofgDWWOqdUhgPkIdYi3cTJiiDWmMQWljfY,1446 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/OpenMP/OpenMPInterfaces.h,sha256=-mKDGQti6FmpO0posNVFsAK32uiFCZstG259Z2ZPKEo,1802 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/OpenMP/OpenMPOps.cpp.inc,sha256=_Ic7NZWhnTzrwxVE9u2toUyhKo6_Z92XKAWAutn1hCw,772464 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/OpenMP/OpenMPOps.h.inc,sha256=ZhagB6YqVm2KgPpwo2Q2o9R43KvlGOQEz_mdSDSvhQM,319648 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/OpenMP/OpenMPOpsAttributes.cpp.inc,sha256=iox9U_vXTTUZyjrFZX-upHhnWX43eEnseG-3hfIlW7k,75721 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/OpenMP/OpenMPOpsAttributes.h.inc,sha256=VMtjsI1VIv6A_Av5zpN-hI-ug_2VDwcY24qHAOCELEY,14532 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/OpenMP/OpenMPOpsDialect.cpp.inc,sha256=UPEDxHW8_4JDMB0zB0wtn3gfLGofiHOlDVc6lvVq7ls,1086 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/OpenMP/OpenMPOpsDialect.h.inc,sha256=XbX3fQ9eYmv3D7621Y5kGDdJSteZF2UghM9RNQf9Sgw,1724 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/OpenMP/OpenMPOpsEnums.cpp.inc,sha256=jSOo_11x5-s3mMraF0c9vJ6TkHSUjevktBPyQILDe4Y,15348 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/OpenMP/OpenMPOpsEnums.h.inc,sha256=wiUSIgZAWl-Uas_uwYCB0ky-XNmjIsMlI6wRMPRx-6s,40094 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/OpenMP/OpenMPOpsInterfaces.cpp.inc,sha256=6cqWapKbFkL1L2mb862psZ2ocXO3nioHK9m8M8vI6gU,6707 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/OpenMP/OpenMPOpsInterfaces.h.inc,sha256=Ko7Zo2Qe6RzWpSlV3sA0rkvIDcYCFHQnm10Y57ZfF_o,53079 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/OpenMP/OpenMPOpsTypes.cpp.inc,sha256=Qw-XUR0LhskHkMpKGw2AQ1PvhcElzb9bR_oYYoPKe_4,2607 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/OpenMP/OpenMPOpsTypes.h.inc,sha256=oonNrSqIozy45dLlDKhSHeR8ZnB3R9UlseRxvVSTytw,1112 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/OpenMP/OpenMPTypeInterfaces.cpp.inc,sha256=kSyPGWOY_okn69xwo373T-dzClPeGclCPG9-tZ6dkiU,768 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/OpenMP/OpenMPTypeInterfaces.h.inc,sha256=yXckKn4VMKnsiOmcjcriDDdn00-la4lurCOMHnFHuY4,2969 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/PDL/IR/PDL.h,sha256=pV9zG7uPYs2FDjMtVEkZ6UxVROVqNcng6jrvvddGP6k,895 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/PDL/IR/PDLOps.cpp.inc,sha256=QtZ04xZzSBnO6T42P3URYdIReiXEjDwTRb61ucsBfLo,201694 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/PDL/IR/PDLOps.h,sha256=XhukXUmgnxLXp9MI1dcqPczOqUBnpY6Mp5tUyBNIw8M,1153 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/PDL/IR/PDLOps.h.inc,sha256=0gJHVfjVOpKYjxxFosLdFXMBkAGJmrSBjbbzY8iHZ-A,109899 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/PDL/IR/PDLOpsDialect.cpp.inc,sha256=TpRDZH9R9buYpMHOp1eZ6Qzm8wydaVjhJTdcE4PWHxk,980 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/PDL/IR/PDLOpsDialect.h.inc,sha256=8ZRWiLftN73JOoeQBxh7PAXfGS0hEre1iOKAolFEA5I,1379 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/PDL/IR/PDLOpsTypes.cpp.inc,sha256=tWFQPXUJBByr0gJ8R5hT4UPZcaca0PgsOdz2jLNxcow,5731 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/PDL/IR/PDLOpsTypes.h.inc,sha256=UmEkibHT996t-meoMfmcv7Y-glrrWT_aeYUGIhxixpE,2797 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/PDL/IR/PDLTypes.h,sha256=HwiqBjxMMrgDGPM_iavtvuq80ukpIfcHp01Y8ycRHis,1316 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/PDLInterp/IR/PDLInterp.h,sha256=N0g-qf0BLv3cGrN0eOnKEj84LGNL-q3_fZoL7cPqvZs,1522 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/PDLInterp/IR/PDLInterpOps.cpp.inc,sha256=b4BLGsuc4wDSYlkcZDoTF3LXZAX4KONJAemV1iABc9k,480252 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/PDLInterp/IR/PDLInterpOps.h.inc,sha256=n6-2nhNx252U9eE8joq8UgBQ-tJYOckyo3kDq-rpA_0,284852 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/PDLInterp/IR/PDLInterpOpsDialect.cpp.inc,sha256=lGpSMNxuGDk5DSf1fy3VTWQtxhuKoQMrWvj6KyC9VT8,1088 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/PDLInterp/IR/PDLInterpOpsDialect.h.inc,sha256=1juSQE9OhHv5Xg3uebaVoMGEJ566eKjXp4QF_VcZPwU,1631 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Quant/FakeQuantSupport.h,sha256=ghaI7TO9BZOR_YQHzicZTyrqsISAUckSOlun6wP2158,3294 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Quant/QuantDialectBytecode.cpp.inc,sha256=EHHoLuHHYKGBYiykPObTCnqU6Gj0JKYf_aVsKL78LO8,7465 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Quant/QuantOps.cpp.inc,sha256=xnT8WLGJnBrgtYO7CDxVsx2JhyzAsZXCrW46BDXee6Y,17003 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Quant/QuantOps.h,sha256=kE8OURxy9V_XNpOl5ZFutAFyZakMlivpv04UqCk7bwg,936 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Quant/QuantOps.h.inc,sha256=rI_6nPH-x3yI7VW-p7gikK9TV745a1VX3DiIm8C7cD4,15290 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Quant/QuantOpsDialect.cpp.inc,sha256=RyGGfUtRrffrDVR-gthflpAgixqN9vZSfIYylcOMpTo,1040 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Quant/QuantOpsDialect.h.inc,sha256=6rddFYHoh1eujy9WpgbkbMPzih6yFzbmqWioTudZVYc,1394 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Quant/QuantTypes.h,sha256=SWr0PpFi_BVu0UXYUg0Rgy6BKKp_bk6MTwKcrNQhKuo,17131 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Quant/UniformSupport.h,sha256=4WywY59oJhokOVzBvHkug18zouhBoaVei92Ia4w9xVI,8916 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/SCF/IR/DeviceMappingAttrInterface.cpp.inc,sha256=F0LApKcz52L2GqSJlgKvQFNqfhg3yu2kiXTiIj6fNzE,1200 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/SCF/IR/DeviceMappingAttrInterface.h.inc,sha256=fgrWP26xOp6ivg4TbIS1IOu-tvl25RfLIO2AZq0gAtY,5044 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/SCF/IR/DeviceMappingAttributes.cpp.inc,sha256=LqGHns8mlRGIn6JQ0G8rWhwXzWSEj0akMFP3Q5ypOjo,568 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/SCF/IR/DeviceMappingAttributes.h.inc,sha256=2TV6O_65Bp7tfXTLSgXUyavC3Mz0orC9feIuY5xG3eM,729 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/SCF/IR/DeviceMappingInterface.h,sha256=sAmmY3PJHFBEtACCFnIStN6ndC0xCiwHGklGUonBm4Q,837 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/SCF/IR/SCF.h,sha256=CFhZpGLdWI9J6siEqSmrdbA20L-XOL68hOR43TffHB0,5082 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/SCF/IR/SCFOps.cpp.inc,sha256=f3UT2cmSwMfAtSlxvx2dS7mBlcQvoT_5Psdn9cxKfTE,108291 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/SCF/IR/SCFOps.h.inc,sha256=NuuKNMpN5AjfrcRvAJme0qu5Db8lys6gXyRTjWrSJlw,85543 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/SCF/IR/SCFOpsDialect.cpp.inc,sha256=_DEyaH3VQJWHcpG0m5AVfRb2RX5ROOD9LZWPsFQZOOI,1035 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/SCF/IR/SCFOpsDialect.h.inc,sha256=65TtNBRVYFlPBPpqkb904bgq32E7uWpPVjdaJErDIqQ,1079 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/SCF/IR/ValueBoundsOpInterfaceImpl.h,sha256=pCx2MAmTFOYcbKPrvMmU3-97yWH_DGM0fHj8nfJpAws,719 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/SCF/Transforms/BufferDeallocationOpInterfaceImpl.h,sha256=zLBjC1lzuaSuOqiklUoFpS9mSfmICQk9cFwmwA_kNEU,777 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/SCF/Transforms/BufferizableOpInterfaceImpl.h,sha256=nMNkXvUogtGi4ANlo01X1ryZ14KC4GLaioTaraN4k_I,736 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/SCF/Transforms/Passes.h,sha256=N5LKA7g6XsSjkFqnI91w3ATGMWns45_7N_E8HVCF7VU,2848 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/SCF/Transforms/Passes.h.inc,sha256=v2ncZUKauGRg6RlNRZUetXqzFPIVI3N7Nw0kM8f6LR0,52325 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/SCF/Transforms/Patterns.h,sha256=AnPHjtTGuJkOWoVPvhpQiFAfQhK0cYg0cyCY43Utx2Q,3575 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/SCF/Transforms/TileUsingInterface.h,sha256=HqNQ_piD4Kotpe9E6WP_tvw70RqvAy89qFq3ONqeTZM,9665 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/SCF/Transforms/Transforms.h,sha256=4m6jpGyXIXSo2XztzPHX4k7dIdXqqakuzefYptCfnN4,7234 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/SCF/Utils/AffineCanonicalizationUtils.h,sha256=AV5u_WBRxW0Y2NHu1ysGxoGAj2KcMqlkehj1tYnKrRA,3296 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/SCF/Utils/Utils.h,sha256=Sc2XTmEhH8fOj9VEwv8BPEjVpvSX-QFaWXv7z9_-ylU,8264 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Shape/Analysis/ShapeMappingAnalysis.h,sha256=lxJcNQMSSbgyYe64pxK0BPwKDQoDAbhqTYShPK5z5CI,2033 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Shape/IR/Shape.h,sha256=4O4B-z_M0OEhw4AeewAgeugw35FkalI524PSQIkBxxQ,1923 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Shape/IR/ShapeCanonicalization.inc,sha256=P6P1GIjQrH4hUvWS-tmy2-Antq6z6MkKK2xnxPqpFTY,16235 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Shape/IR/ShapeOps.cpp.inc,sha256=ULRF-iXte1yFm9_qy7WT_HlUHZYOIU8ZTjQ8W8LpAIg,392295 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Shape/IR/ShapeOps.h.inc,sha256=-0oENdM5yiJyQQe9W6HOsx-ivQDJatQzCTvhIkn6gOo,249816 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Shape/IR/ShapeOpsDialect.cpp.inc,sha256=pBKTNUf4SzwzpI7rQ-diXGgMCBQopcZHWmIIkBBlv8c,1110 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Shape/IR/ShapeOpsDialect.h.inc,sha256=VAqBwWyrqQosdc3aGoJU_6wy-mRojIa7fjw3IRPsZm0,1968 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Shape/IR/ShapeOpsTypes.cpp.inc,sha256=Vt3ZItLaH0Ax3uOyiCiBLLsvpzbAbcaBEfakYllZHxg,4140 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Shape/IR/ShapeOpsTypes.h.inc,sha256=5rs7kIDXgb9cFl9EgnZW7jyzCEEnzKZxt5aq1ifW7-0,1972 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Shape/Transforms/BufferizableOpInterfaceImpl.h,sha256=RQQCiaP5NhC5BjSTkgU1x5RXdFjh5KcDzPrvMnidj8I,724 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Shape/Transforms/Passes.h,sha256=_KFOvPwmWiR6XMopWi9-genqnlP7-8eo_h3aq2Q078s,2701 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Shape/Transforms/Passes.h.inc,sha256=d5tfmv1xXXObEdOeHm1N9_j51RhOcnSMGF_2XsajDr0,20124 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/SparseTensor/IR/Enums.h,sha256=sZWhEgSF2nOPJFfUDvGq65ocEVCS8gx47QNHglyCjuU,20365 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/SparseTensor/IR/SparseTensor.h,sha256=wn6GL9Mofe9EAk5VXxbUdGp42HXmRrqdICCEZ23eprw,7577 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/SparseTensor/IR/SparseTensorAttrDefs.cpp.inc,sha256=SszBtThndPVfFzlJBfUkYFFxsYKQrzY_vKHfas3sY-Y,17984 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/SparseTensor/IR/SparseTensorAttrDefs.h.inc,sha256=PjPatLhvapHlx3GhV4tr9vdoL4Yt4_dmF8Ldl8p7cik,11854 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/SparseTensor/IR/SparseTensorAttrEnums.cpp.inc,sha256=PflXE8wYwNTpEN18fE-BLi0jZxWnb2qyfZjQl9dbHmU,3549 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/SparseTensor/IR/SparseTensorAttrEnums.h.inc,sha256=yGJ9nry6I-04uz-HQFAXpJMbZeZyaUVEJNXCPdUF_oE,6637 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/SparseTensor/IR/SparseTensorOps.cpp.inc,sha256=Ln1vUwGJUDzvbRKrOGG5YuhoSQ7PMq99o9P_BeGvjMw,392495 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/SparseTensor/IR/SparseTensorOps.h.inc,sha256=-sf0XCZ4nJ1Gnp6_h1-Y5qXA9bcG05Cj-JCzzqLyIqw,196915 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/SparseTensor/IR/SparseTensorOpsDialect.cpp.inc,sha256=rQ1gRoEce6CTLIiG7UxWNN4SAeLCPyTw_rhQqTX-whU,1064 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/SparseTensor/IR/SparseTensorOpsDialect.h.inc,sha256=HKmFX2zLJ0Cj0I71A3hvln5Yk36qj8uVnWevNzS2u3Q,1788 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/SparseTensor/IR/SparseTensorStorageLayout.h,sha256=7mTIgF2KEmUuwQ3W2LjQhigSkdyMhrRWvUyoAb8Imds,7570 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/SparseTensor/IR/SparseTensorType.h,sha256=7ox7OIfRWK0KC8iCBFYUfHID7abZZOH8AE_yJhANHdo,13834 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/SparseTensor/IR/SparseTensorTypes.cpp.inc,sha256=CTqs7VeIqIXCwmqb4OsnUygLmPyQw_d-4rdIIGZ9xIc,5427 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/SparseTensor/IR/SparseTensorTypes.h.inc,sha256=PSL9XBp5Su9F7tLKsfb3cLf5KMcePcuWtVSjG4XO0gE,1709 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/SparseTensor/Transforms/BufferizableOpInterfaceImpl.h,sha256=1Z1O2r6HCT8iY0NG78VdGy3jcCkoq8NIlOCkmA4ayLY,797 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/SparseTensor/Transforms/Passes.capi.cpp.inc,sha256=8ixGFWqlqHjP8zyo6DUYNvDUdTIx-Tz7zNWILXtMe0Y,2854 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/SparseTensor/Transforms/Passes.capi.h.inc,sha256=b1Q483g_cIwYoj6_Iplcie-Yor_LV0BzW1CJ6fOqzkg,2361 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/SparseTensor/Transforms/Passes.h,sha256=FQuwsx2lAtj0SUtIsjp-L-rfgOKKrV8iITdv5npk_-c,10877 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/SparseTensor/Transforms/Passes.h.inc,sha256=AknGi2SDgOebTEkxdNMvBG8TeDd6zDUvkAbR3Y_tsxc,72528 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/SparseTensor/Utils/Merger.h,sha256=1stp3ZYN-bsKbq3zGoFr-7LzNAyEHSs8nfB2sAAATv8,29230 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Tensor/IR/Tensor.h,sha256=h9qhjmxEZF4MSq-zlvaQY2yPUKol-_hxegG0RgukDJs,7390 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Tensor/IR/TensorInferTypeOpInterfaceImpl.h,sha256=7EOPLaUmhviE3EdAanYOlfgcWll847dxz7NZKEAZmUA,1539 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Tensor/IR/TensorOps.cpp.inc,sha256=ID9UROlbvx1j5CRQK7YC716wNacTpq5bZ8H3gecsykg,372574 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Tensor/IR/TensorOps.h.inc,sha256=FGte-he7wLBnROxfiVmtffcviX2JBw-jgVR2WuHSIkk,203583 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Tensor/IR/TensorOpsDialect.cpp.inc,sha256=6ryW0hJQUFGcY2ebAxu9xtRJbZsIaWGNTMeqwpPT3kw,1178 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Tensor/IR/TensorOpsDialect.h.inc,sha256=JMFe5Yib5m23I-JfOGcd__cFlHC6GW5FKJQmZqAPzCs,1623 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Tensor/IR/TensorTilingInterfaceImpl.h,sha256=J0dd9EV95yo2i5VJxB9hZOChivfpLBPUjYB3aH49EvU,2781 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Tensor/IR/ValueBoundsOpInterfaceImpl.h,sha256=2SAxVxECKlzL2x8TJDAlGTwadC-LIT-dwfjpzPbQsOw,734 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Tensor/Transforms/BufferizableOpInterfaceImpl.h,sha256=bO6zJUUCnTjUWzAK6jnyGVjrBHq9XD58OmGL4o94puA,729 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Tensor/Transforms/Passes.h,sha256=k3tGT5yYfatO7Uma6N2qnYUPA7FHat8qXXzsdoc-Xdg,1350 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Tensor/Transforms/Passes.h.inc,sha256=fVA26sXuLaKdao3HmE7OxnPr41rvkPJTq8iD8Ta-XTs,10272 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Tensor/Transforms/SubsetInsertionOpInterfaceImpl.h,sha256=qUIIWIBP4B9iklPQuFxC-7fc07kHiJGiiuiFicnhUx4,746 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Tensor/Transforms/TransformUtils.h,sha256=dMwkH9DPAkmWlmma4r9DquCG5HIfcL_YSenNLSL2cLM,12051 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Tensor/Transforms/Transforms.h,sha256=Cptl7bQ37CwRq0mIlj6QFM7zItrqWRHyVFREYPu-LHA,5242 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Tensor/Utils/Utils.h,sha256=zG2iCAd_wgfSIS_qE4ka27vybH4l6P3OBr6V4laqO-U,2049 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Traits.h,sha256=tzY6hM9WcwRVvPIWEQtCEPxAloY2sDgG53uiRhkjLiQ,4600 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Transform/IR/MatchInterfaces.cpp.inc,sha256=lQLqpZl95hChEVif6fKLIx3Hx8DnI9-LFxcJiqaRFq4,1988 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Transform/IR/MatchInterfaces.h,sha256=YQ506b8OIcoqlEFcp9_j-ljGjP4BfLvMITI_dY9Fy3A,7198 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Transform/IR/MatchInterfaces.h.inc,sha256=FeO1JvIZk-m7RUnne0zF2T2MvRJxUYNzTDFC9Wa_Uvs,5992 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Transform/IR/TransformAttrs.h,sha256=FSlhNwVM__DMovdM3dJq37_TWdFIotNykL0rPwQxn2U,704 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Transform/IR/TransformDialect.cpp.inc,sha256=SfVOF3NNoUeVloWJBsaUxhVhHUirp5Tt4g5zoba5gqE,1034 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Transform/IR/TransformDialect.h,sha256=4UrGW05goFjXuGXpbzNZMmYd_fIAkyCaY5eBXj6zkcg,13022 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Transform/IR/TransformDialect.h.inc,sha256=P_JS50YQMLFt7sWmdGi8f7-05ikXu5caDhfxYuzsZB0,6972 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Transform/IR/TransformDialectEnums.cpp.inc,sha256=fdQXgceGnCJgrRl_cQrTCSLLrIVttXf58HSzdYpCeMU,4722 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Transform/IR/TransformDialectEnums.h.inc,sha256=x0VscH5xc9q_ncJNZJTSpUHz718FuXgA9DXg0Ch_x4M,7171 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Transform/IR/TransformInterfaces.cpp.inc,sha256=AUc1XGxTMLk8ble_BUIuCYOcrLN68_2y1JsVmRlg7TE,5078 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Transform/IR/TransformInterfaces.h,sha256=Hr0aJ-5gikrebpCluy7A4ASaxaTYq0W0xXveeQZGuew,74340 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Transform/IR/TransformInterfaces.h.inc,sha256=0AAOGZlKWD-SQi17NKQnvvTHVwEFiHAukgMS5JoTqwY,33231 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Transform/IR/TransformOps.cpp.inc,sha256=DrWuw_bY7R-PWpkyn5RANaLVXii4jHQ1VXe8g-8hwvw,437423 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Transform/IR/TransformOps.h,sha256=K0clszom1QiUPob679ynIJ_YzsuyuNIFhEs_lAMIdKw,1834 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Transform/IR/TransformOps.h.inc,sha256=7RHquIO1-DJK6SQnvk5ko2pWUTdaVDdDSRhS3cMvX7I,258920 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Transform/IR/TransformTypeInterfaces.cpp.inc,sha256=_X8BiE6m4ERw3RL__hVUHDDiyHcNwJmZRt4cex04uzE,1899 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Transform/IR/TransformTypeInterfaces.h.inc,sha256=LAcb42WsoNLPDRXIQGxfXBt-iPbyWrssT3SdA5FfxE4,11846 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Transform/IR/TransformTypes.cpp.inc,sha256=J0CUQM6TuQ5Oy1O9Gae53YiOM8QHi13sqEskeVJlCxw,11485 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Transform/IR/TransformTypes.h,sha256=ZQfVa75Rl_p_e5_nNwU75dXASsEFG4FuvWPdRVbubQQ,911 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Transform/IR/TransformTypes.h.inc,sha256=FPAAcA_vPblalCo2HuMJ8moTBkeru_bC0v6uEhsrjn8,5657 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Transform/Transforms/Passes.h,sha256=gy2Y2vJqAlQJy8FjnOEPfcvJz4Z7KfOexdQ_bE967lw,840 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Transform/Transforms/Passes.h.inc,sha256=WVIGm0XAZp9QeUkICR3pglTL8oXhGITsdDFsPOCiDdA,10523 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Transform/Transforms/TransformInterpreterPassBase.h,sha256=8GN2LVS360yxNC5tUHbiMuCLh2CmL0J_1lqQetKdX4E,9727 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Transform/Transforms/TransformInterpreterUtils.h,sha256=29Tpr_HPFAUPMEhcCghLBiWJWL1HvQXhw895dCdluas,4160 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Transform/Utils/DiagnosedSilenceableFailure.h,sha256=fuw7MRFxgeIQHF0sQ8X1_jgtaHv8X_6POhsIBv_kc9g,10565 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Transform/Utils/RaggedArray.h,sha256=Muj1DQw6KP3MpjmeJYurHtZi4hYgspm_zM2d9qIBNVc,6273 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Transform/Utils/Utils.h,sha256=qLDReS59bb_qY0YCSG922xNgrTHT8dr784bwZZ3kPYA,2233 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/UB/IR/UBOps.cpp.inc,sha256=B0FtlGQPXjpa6irTccjH54U05109_VVlKRhWPRPnE2I,12567 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/UB/IR/UBOps.h,sha256=JEH-_xgloSNovCx8kkuYvLt1BcWD_uJ9mE-cmddufkQ,887 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/UB/IR/UBOps.h.inc,sha256=U3tE0yza6mbBBD2JMpNW1gq20lPXQZ3MqkHu330R3zA,8507 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/UB/IR/UBOpsAttributes.cpp.inc,sha256=mhi93DjDawZucLWZ0Y7OIdrdcjz4H173-Uq5RerB_aM,2732 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/UB/IR/UBOpsAttributes.h.inc,sha256=9sgvc_CHWf8y_5lkYAhbtOQqXeHpiM9Itg65e60oB9I,1140 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/UB/IR/UBOpsDialect.cpp.inc,sha256=Ks-F7yXRBOMLkv8Hw21QiV6D5aDYFqbfxC54Oj5bq24,971 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/UB/IR/UBOpsDialect.h.inc,sha256=AtFiepLBDGpLwst9MX0jLTPYc_Gr3n3T0yK6v1reCCY,1816 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/UB/IR/UBOpsInterfaces.cpp.inc,sha256=RDDM26gjMzU1CRBs-NKUCrOUcCw2zV5oioY1HpEdWyk,568 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/UB/IR/UBOpsInterfaces.h.inc,sha256=XZvaL1MIrg968Lg0n8QP5D6g733Fhtk17QfXYuZoIcs,2090 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Utils/DialectUtilsEnums.cpp.inc,sha256=wD6LchTYGb0LEaqvpO4SmZPCHUXdTGMiIMx5i6yjmOI,1417 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Utils/DialectUtilsEnums.h.inc,sha256=xnLt9kNinUWpI_oD1SOzk45mLiqWTYNvyPhmEWvAV68,3174 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Utils/IndexingUtils.h,sha256=jG-4joXACPqxoXgWD7-I09qE9lKZC-bCcCr_gwiHgHw,15993 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Utils/ReshapeOpsUtils.h,sha256=raFFu10XTJz5iZeT98ZnZPHjYSA99WJZXBPB6gZd0Ak,24099 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Utils/StaticValueUtils.h,sha256=VwPmgiywycuLRI_fs4LlvFyrioIHXYe_Oh3AvE9wkjo,6867 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Utils/StructuredOpsUtils.h,sha256=rY7R694VbZA1GcPSgJi4G81lg4Gg4s1twqMMr6rMUGg,5220 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Vector/IR/VectorAttributes.cpp.inc,sha256=gW49XJ-hgfEIkGm9ADsUspo5wYD-_uLtsG9oNFvdaYg,12679 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Vector/IR/VectorAttributes.h.inc,sha256=swuRnMkxyMYDyXthGY7dyELXCcLoEegpGGA_1NvG-G0,2941 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Vector/IR/VectorDialect.cpp.inc,sha256=gq3deTi5gmXSDboQxLrNAcD646kclF3bAQFajewnVWo,1062 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Vector/IR/VectorDialect.h.inc,sha256=pW0mAOFtcOMnsriXb4IuX10kTJL-1qpZraVrKEpOk_U,1848 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Vector/IR/VectorEnums.cpp.inc,sha256=dQrqu6JWQzrRU1znMV-L6wXPANXiEkOis1SoJF4_Mg8,4673 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Vector/IR/VectorEnums.h.inc,sha256=gkIYenQLTRMJt0ChwN9cP8OPYev9UpBTqBUjXMs-Dr0,10256 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Vector/IR/VectorOps.cpp.inc,sha256=QNqXKs_4CjgaXhZR23VjQrlu7ljpP0-_v4T9xIW8Fho,601993 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Vector/IR/VectorOps.h,sha256=TD31MRWTOmdXOd5eWcu9UVMghdIgkDPBYq1w152NBQA,7549 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Vector/IR/VectorOps.h.inc,sha256=C8h3z07LzcI8XkaYyv3tYcJU31C96AdqZ0m_UO3f2ro,325417 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Vector/Interfaces/MaskableOpInterface.cpp.inc,sha256=9fg3muPWcWUSho8nzxssYCH5rD5mOQH-_VnxD5h57e4,1461 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Vector/Interfaces/MaskableOpInterface.h,sha256=D-0nhxzakFnWIHCyCC3MDAO5GqzrDEfmCEfOTAaIuKw,945 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Vector/Interfaces/MaskableOpInterface.h.inc,sha256=u2QHZNu-T-fcsJ3YFYTCgfWtGILDr8t1F9ka1Owf0U0,7880 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Vector/Interfaces/MaskingOpInterface.cpp.inc,sha256=zkUySkfhd0zWlkJE75UPQdGuI9RVevMAnSU1LTxYue4,1312 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Vector/Interfaces/MaskingOpInterface.h,sha256=yk-uqUHH-w_ZrsQqt2wMGLzaLpr00_R7PernKIbTzNs,877 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Vector/Interfaces/MaskingOpInterface.h.inc,sha256=IQ3NfkHnJer4eAkf7ArI2eKNBVgRtYrkwKOJEks6S0o,5662 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Vector/Transforms/BufferizableOpInterfaceImpl.h,sha256=lhgMtPZ-s_5qdMUWeXq_RoTRDpvxNe86l6RWcaoWF6E,730 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Vector/Transforms/LoweringPatterns.h,sha256=_giEzvsuoU9LPU6488Tg3-J1pjpM6c7WwO473AiBNKk,11183 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Vector/Transforms/Passes.h,sha256=oPno1Y0zbvWIwqbQuBP4EAuRFw1sKZPLi3ZqdBx6taU,1248 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Vector/Transforms/Passes.h.inc,sha256=xMXWlF3A1zyczApPsQsBM8ci5p2-nNvZEze53iebqeM,10004 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Vector/Transforms/VectorDistribution.h,sha256=o6I0-ZaV-2WMJ67x1tlrOhEVNKXBGYHdJfDZhzR02RY,3850 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Vector/Transforms/VectorRewritePatterns.h,sha256=dGFlYReV8gBcHtx0UUs-lHr9VhZ_8AjjqqD8pqoizVg,15202 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Vector/Transforms/VectorTransforms.h,sha256=9fY922VOD62J2wH_lHC1LULiPSzHET0stXAnatEpnik,4805 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Vector/Transforms/VectorTransformsEnums.cpp.inc,sha256=QnjOeR-swfl9ZNIuMqliOtS2yqsqD9UR2NgDxdTTfUk,9155 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Vector/Transforms/VectorTransformsEnums.h.inc,sha256=OEilKiomVwtd8RDchFZppGZbGoyLBnmZ56P-lL124ck,14278 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/Vector/Utils/VectorUtils.h,sha256=DTZM1XQg9PpLvvSiTCivWN6ob27e254SFYHumJqSJms,4789 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/X86Vector/Transforms.h,sha256=K8XWPeA9yJZrrMUXmUYp4OWC4hTZjdg2svyHWaFtZ0o,7670 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/X86Vector/X86Vector.cpp.inc,sha256=fjd0-CZqnlklXmBIemBbBPET_J1KNzFrjbw86d8jKyc,165203 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/X86Vector/X86Vector.h.inc,sha256=D2BgaTmE3sWbNGys5I0IXmzoeSaTZ-vs8skLw3DCSB4,92793 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/X86Vector/X86VectorConversions.inc,sha256=hmZFLbMrv6KSeDt7priqUywO7k-u2ITydYfGv7NBSz4,4519 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/X86Vector/X86VectorDialect.cpp.inc,sha256=qWxkbW0IPkKKRFIJX2TJ5f-slyc5QsQeTKbRkwbjT8E,1034 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/X86Vector/X86VectorDialect.h,sha256=YKFqziypFO2xLE7QS6NhNCotaPlz4m0sBWjlGsJeqt0,1092 +tensorflow/include/external/llvm-project/mlir/include/mlir/Dialect/X86Vector/X86VectorDialect.h.inc,sha256=sTJqPDs6BF4cI6gMZ6nYqNO9KMHhspOd1DNaRAloOUk,1127 +tensorflow/include/external/llvm-project/mlir/include/mlir/ExecutionEngine/AsyncRuntime.h,sha256=Y4NLTwbYv221ImhY0jeON2Wx1bkrPvWjMweR_hMBiAc,6607 +tensorflow/include/external/llvm-project/mlir/include/mlir/ExecutionEngine/CRunnerUtils.h,sha256=QxLLj1LU0tNHNbjnugjWp-2zkwOmZ_dSCt79rEftUF0,16636 +tensorflow/include/external/llvm-project/mlir/include/mlir/ExecutionEngine/ExecutionEngine.h,sha256=4nL_vEw3S4QGjttv_HUKwhGx_4W9_6EO60JN1myMr6w,10293 +tensorflow/include/external/llvm-project/mlir/include/mlir/ExecutionEngine/Float16bits.h,sha256=YDdOZtj1r1qYtOdX6yZLnw5DdurfgZpPqCsVutDhWWo,1897 +tensorflow/include/external/llvm-project/mlir/include/mlir/ExecutionEngine/MemRefUtils.h,sha256=ECSOyaJnNojAgeAUD6MMocwFvCaoXwmefbeGnYk2G88,8494 +tensorflow/include/external/llvm-project/mlir/include/mlir/ExecutionEngine/Msan.h,sha256=NKo-oznw7BfFlxgabVlWIjIip05JPFdacSkpkRsZ1nQ,1246 +tensorflow/include/external/llvm-project/mlir/include/mlir/ExecutionEngine/OptUtils.h,sha256=3ud5K6Q6RLGZTg0aJTzxZd2uCCcq0_1xnvoafrYyymo,1390 +tensorflow/include/external/llvm-project/mlir/include/mlir/ExecutionEngine/RunnerUtils.h,sha256=4bdSNedo_EQuzLzRcYtaibvL_YR4qFubIZ55dSPJjAg,18343 +tensorflow/include/external/llvm-project/mlir/include/mlir/ExecutionEngine/SparseTensor/ArithmeticUtils.h,sha256=l7QndiKy-k24bBLy3rhx5jS9mcdnHFjKIoXpYAeYOUg,4902 +tensorflow/include/external/llvm-project/mlir/include/mlir/ExecutionEngine/SparseTensor/COO.h,sha256=5reUkqhtB8RSRYbMbVwdn9TTY7BnjzWavqS_WzRbix8,6431 +tensorflow/include/external/llvm-project/mlir/include/mlir/ExecutionEngine/SparseTensor/ErrorHandling.h,sha256=3_aJdAZqaDtmpIMwIoVTxiEu559njvZMMKY2KKFORhw,1745 +tensorflow/include/external/llvm-project/mlir/include/mlir/ExecutionEngine/SparseTensor/File.h,sha256=ymOzaC45CU5LErO1_dUOIQMbo_HyVQpvoiRnA-hzgrU,14737 +tensorflow/include/external/llvm-project/mlir/include/mlir/ExecutionEngine/SparseTensor/MapRef.h,sha256=FW-znwhQBPTcq6XJloj0O2j1Wds90ac9tu_xF9X7XmY,2213 +tensorflow/include/external/llvm-project/mlir/include/mlir/ExecutionEngine/SparseTensor/Storage.h,sha256=5GbzTMn5zozAX8iTQU0DJb99xvnctBBYY3SR2eZm-fg,55510 +tensorflow/include/external/llvm-project/mlir/include/mlir/ExecutionEngine/SparseTensorRuntime.h,sha256=63_jJq-qgEGgiuh0RxfCydDdYgTw1cWl-znLmryZd-0,12284 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/Action.h,sha256=mPqHelhLeKhc32IkxuOr_fDBWeNBaxU7SjxokNnbk94,3298 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/AffineExpr.h,sha256=rYBOla4LmxnefySWq4t7znGIcFCslQBfAvJScfx19xk,13717 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/AffineExprVisitor.h,sha256=rn4rntl6pHHjijn3Te55jhbDsPreWdMmeN9O7m0Danc,16362 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/AffineMap.h,sha256=qE8Que-IztC3O5hM1_T4ohVCPsBsSo67emM_-GaUZys,26975 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/AsmState.h,sha256=dhmNWFvmH9RGlCB3qO0M4VVJqzdEksQM6M127m46kLc,24701 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/AttrTypeSubElements.h,sha256=P3-4r1oJjboUtRHhWSF0XXLw6NGWE7w3kpfB6bvBgSU,19922 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/AttributeSupport.h,sha256=c_Qzi-sjJYqBSwx5lB-HE6Z9xrwmJ1J3t18VsVHKStE,12917 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/Attributes.h,sha256=Z_z8XrtCe-94DCpm29mMMQ7cmeaIsUPgXNdUnDEZXVc,15891 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/Block.h,sha256=HCK0kvaQaP3jioSrPe9LvPx4jgX0-5hOnSMF4uuJq_o,15834 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/BlockSupport.h,sha256=EXotbJ3XaFH5cgS9igrLLr8GjJhS-q7s0Bn_Pt_SLeI,10084 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/Builders.h,sha256=cFTmGbPoKZ_K-PRm3pYOoj0qXZevnqazwDGSn-V7oJ0,22164 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/BuiltinAttributeInterfaces.cpp.inc,sha256=m4_H0udIvS7yBtDfaNDTz_esb86OJ_2FPPSCBTz4nTs,2396 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/BuiltinAttributeInterfaces.h,sha256=Ynp7FPTvLCwyJbO-w-tqmCTvz231LPLygV6FZW5mcxA,11805 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/BuiltinAttributeInterfaces.h.inc,sha256=H33ry3MKDZNMsfbmRTa1IJIwrBby6hp5HKKmX1q-v_o,29166 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/BuiltinAttributes.cpp.inc,sha256=-G0Qf2ibShHwoKNPHTtbSCi031VTbeRd8XwUq7PecYQ,25807 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/BuiltinAttributes.h,sha256=30q_ulofkpdxAWScTjMy_xbnK84qx0afrNj0n3xkCjU,47538 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/BuiltinAttributes.h.inc,sha256=tyjYBWFDaCCdCelkhncm6THWNSt_nspdmu8MSPweBIU,28928 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/BuiltinDialect.cpp.inc,sha256=zqZJX2UrhMQZHN_R2Gmt8hiXDAIRUE67WNPdaKTbXIk,964 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/BuiltinDialect.h,sha256=1Jr9wS44b95v5btRkPP8aEI80fuUuqAQKXuYiKFUmf0,958 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/BuiltinDialect.h.inc,sha256=AzpHWssFYxbvV9fBxlXri581Q1Xfr06EGUhcTEDqjVU,1304 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/BuiltinDialectBytecode.cpp.inc,sha256=V6lghEGZmvlWVB9qDycYZJ8IrekkJhuNFozPqLrI3wk,30210 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/BuiltinLocationAttributes.cpp.inc,sha256=S0RwPq2XAXF1BJL1IQjPL5eX6kHfLzm9hE-emoFB7wo,9419 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/BuiltinLocationAttributes.h.inc,sha256=m0Bl__mcL57fTqkDIId_lrosDAA5nHDLXuPWJfTAdtM,5414 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/BuiltinOps.cpp.inc,sha256=etDDyf28HKPCZmNA1Wvn4fVQ_ETxwmIqpCa_gw5pLwY,23355 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/BuiltinOps.h,sha256=G1jgzBVsiuSSOY3__1XmeN_8GLbuZyRHER5NmUJNgaA,1632 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/BuiltinOps.h.inc,sha256=myp3TeLjcr5pXZZLQQp4K__bXa-IqMSYVCM3eQrikjY,15237 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/BuiltinTypeInterfaces.cpp.inc,sha256=-Y-n4vklH8c_KhvUFalwTAheM4uypM8pquS0621nOiA,1621 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/BuiltinTypeInterfaces.h,sha256=UsFj3vzupzARhdjNsX79DH-oGEv3nJJ0BPiLFThSyzM,569 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/BuiltinTypeInterfaces.h.inc,sha256=gCBUGRIh-TGbMgQ2L2mi4vdfzA83U2eGcYZNH0Bvk4k,14924 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/BuiltinTypes.cpp.inc,sha256=fghaiBcXGcYCdec-jd8p3zAphn0vRDMJGAJXsjhzJRA,17343 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/BuiltinTypes.h,sha256=_qtTTznF8Kuy3FzQGG5m0tkbwHXJZ82lHYHqzFFmwoc,19678 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/BuiltinTypes.h.inc,sha256=dyR39Yvss_BQeMIQmvkGdmE8YHIG7PbvR-NM8PeZVLA,20027 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/Diagnostics.h,sha256=xEV6qXzxoZsY-BC2RSjhBO-6TQFfWyNuQMCgv7s9SpU,24526 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/Dialect.h,sha256=dT0KAMQD4ql4ILqlUVG7cS3RMKbUUGRswDR0vCVxgU8,17019 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/DialectImplementation.h,sha256=wUJDtnX-YfS2T6CafkSxYOjNquRlp2GyYqL2DjN15Jw,5791 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/DialectInterface.h,sha256=ArJ2AYOozLyMMOSY1rUV0B4vwje07I9FDgQmzx9YZjg,6818 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/DialectRegistry.h,sha256=o_iFhjvY9lw_hzVB3p_Ry0clNTUHFn-m3FOlsoJtUlE,10691 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/DialectResourceBlobManager.h,sha256=62tjjuOgP-g-qo7lgdiHtaxJIAuHkKqx3MGSamH-nUg,8869 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/Dominance.h,sha256=AUwrnoXIFwfoDTTftMeC-CQhdT_qvQxX9LEb2pO_Zmk,9367 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/ExtensibleDialect.h,sha256=5AQAFN5VW7p1kpXSMxZ5QRnlR20gJ37hK0WLsQf4Hmg,27847 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/IRMapping.h,sha256=lgTj8hm9nq2nLKjfS2NHFFH96O3gTKsr5vnh3tGui-o,4154 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/ImplicitLocOpBuilder.h,sha256=SSRAwd3wnU1qSSOiEguIrHWWDaDLFPfyxjDl3bi3vxw,4429 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/IntegerSet.h,sha256=0UAncHzLlOWyZhxHC72m5mu9HTNNY4HTEajv-pu-RFY,5629 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/Iterators.h,sha256=TjPdHpnXm31w55BmAp-O2sA37aRrxpg8Wea144jjb44,4481 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/Location.h,sha256=8gHwDSv5rm7pVlFubTa-bVk742Sm4onOC3ICjpbfBlc,8947 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/MLIRContext.h,sha256=ZjG6Smi38zr5H4_uRzUxduXXx5dTrB_ZkoMcNFcHIvs,12641 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/Matchers.h,sha256=K8Wpe_MW54X8D_EQ54sPVXaZiHUnBD57_Yf9r88DAN4,15068 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/ODSSupport.h,sha256=t4dLLa7BSEDZmgCyjnPgygPwCi3vOzL4pK_ANYusKjA,2471 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/OpAsmInterface.cpp.inc,sha256=IVF0EJ8-UkC2a0-kh-3C4zZY47cTZrh48IDFJ-eSb8I,3051 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/OpAsmInterface.h.inc,sha256=IiBO5-zJ4VpzrsbiiFRrZRnceUhCHiLXwzDQbiUS3YE,11773 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/OpDefinition.h,sha256=zXBCDVQ86FKvlBRpjQEKostugESX2YZYATxv7ZDx3W8,82955 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/OpImplementation.h,sha256=TuHCVj3bV_cVEJV5YUzrGo15DJ2v2XLHbdsijjcvstM,70604 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/Operation.h,sha256=qcRRA-oQPKnUoSiIwiw3cqkG1YzOH2Ow8v6dZ2WzM-4,47290 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/OperationSupport.h,sha256=Ez2hv3i6qYk7_532GkflkAsEcBfG-lhQtTi6uhiw9z0,54901 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/OwningOpRef.h,sha256=2UjoaxdV6Xs0LFtb7bQB9XL42T-rccquuuos7w1hFBY,2179 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/PatternMatch.h,sha256=d_yUZZAHN7XLM5PTxgyW5U6mSyeKOklh5Ak7XmWx22w,77732 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/Region.h,sha256=qDyqzUSgRdtTPN7JzBWIH0E7gMQx-QEo2Cz_vb91EZs,15291 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/RegionGraphTraits.h,sha256=Agca-AP-Y-NBHOGxX4lkIu2h5WvsWhkRSLO_R0Prvuo,3649 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/RegionKindInterface.cpp.inc,sha256=X6CtmKM75payA8G5OSp8gV54sTc82ieBG3vtQ69px3E,976 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/RegionKindInterface.h,sha256=w5XamwyzWMFFvgall3DEwc5bKHFHaEOO4RwNbSbZizI,2083 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/RegionKindInterface.h.inc,sha256=zEEL_UMSqkW8dLc2jl0ezxpYQHI1rrUEmpdZcSFGp8Q,3394 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/StorageUniquerSupport.h,sha256=UKCXvd4bvzGl4elQkPpDCMKfXFqo6YQQCP6pC2b2Uz0,11027 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/SymbolInterfaces.cpp.inc,sha256=givjwaW8DaQVHiO3iiB00r9_xvcF8GCIkIhehYTU0kk,4328 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/SymbolInterfaces.h.inc,sha256=-Xaqv0uYGjFphlzGPSbkfkhJiv_2iAZpuSDicBEvFSQ,32772 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/SymbolTable.h,sha256=ezRmLKyIotSU1OUAOfHMN9FF-ppkMkUnS4YSd7fEeew,21081 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/TensorEncInterfaces.cpp.inc,sha256=_QaicV1ocV_TkYH8KsUcYevTjtOJJCUZ1VnrXEo6mrY,1006 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/TensorEncInterfaces.h.inc,sha256=_qv8QnTNBUeJxZ7Q7NhxaCzqtIvv5GA1168Bj0RFVeo,3887 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/TensorEncoding.h,sha256=gJTbZtM0e9uXgUZQ8Wy9sRN5w-ClPHuO0Vj9zD00GFY,777 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/Threading.h,sha256=6lu7yzy5ms0JW1cpkafcSrDyhhOsId4wApPuBp7WOkE,6799 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/TypeRange.h,sha256=UCWKL_DARVp3stc-9sX829QxuSa4A9nltF8pMnAQnbQ,8490 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/TypeSupport.h,sha256=2AwTORd9mbDiVnBm_uDIgpA9pOrGOtoufMZCN8o1nAg,11283 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/TypeUtilities.h,sha256=WxBchHtJX1q0QrqgRwWqCVn0ef6eaGQCJEzIfmNvQHk,4639 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/Types.h,sha256=T9nhB54iY3RVIueVNgQQGqb1ybn6ojDvlOXPTdUfQnA,16285 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/Unit.h,sha256=P2TdhwERVtc4xjQuOK3aPqXxDQQoMq0lBhuGu460Lio,1573 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/UseDefLists.h,sha256=MzK4Ta39b1AXfLqGSvIgjzXN00jxfLzgSbRpOVzwr7E,11756 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/Value.h,sha256=09ycTxdispXuA8hI0peLXT-3XTSoqGNZstOGXMHK_UM,21637 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/ValueRange.h,sha256=xyAEWlmJWO1miWKtxY0MCkdhryx6-nc2TFucj7Kk2oo,16024 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/Verifier.h,sha256=SLjva7XVhVnk6JNnED8tDMs2kROAIyGHqje5vykkdQ4,983 +tensorflow/include/external/llvm-project/mlir/include/mlir/IR/Visitors.h,sha256=IMtr7pgkK5-B_OxE67oCBRfDS63zky6IbgCyE3KOACk,19979 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/CallInterfaces.cpp.inc,sha256=KhoTf2Mu5ILb-thOcwD04AfilWSFvuOGQcx8RBzWF2Q,4811 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/CallInterfaces.h,sha256=6M2WjasKxPlWpW0dBA7t1iEZIwH9XD86oIJRyQk_5jU,1547 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/CallInterfaces.h.inc,sha256=YxvEhO2zfwX0f0_TovDmw8AHKVaLJZ_E8ctkHt4yEcs,22686 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/CastInterfaces.cpp.inc,sha256=Q12SF83yuvbCI-mdTZdUf1Zsw0b4EjuzM0fvoTkSvlM,847 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/CastInterfaces.h,sha256=gtXLH3CFY30DHwV3Y4uiBtej8XOlIEmaeZxvhQa5MU4,1370 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/CastInterfaces.h.inc,sha256=-5feNUVc2p51zgnIzjEuNrcQdmQj6aNbLkFanQko1Uk,3266 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/ControlFlowInterfaces.cpp.inc,sha256=SWk4c5MLQemaXvYhtzvfwjzdpu2AbdDEWTrBx7fdbXQ,8434 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/ControlFlowInterfaces.h,sha256=_avIFgbNAQ4r0lhIO8cZPVfBNYhadWYTRWwO3izpqf0,13633 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/ControlFlowInterfaces.h.inc,sha256=TwD3MWyi7T_QYzHoVC8JsbhIORhdJs_po1NDcUxbpnI,36519 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/CopyOpInterface.cpp.inc,sha256=LG_Qjj7UFPoPAs4KT1Ml4d94YQqr-gJzU25zRCEa_Q4,908 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/CopyOpInterface.h,sha256=6DYEbpfvw8txAXHohAPk0qv0T3aAs-pbo7IjradxofA,798 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/CopyOpInterface.h.inc,sha256=PzjSAHXxqzNj71V_wkh3qFsrnYtHk3eDuWREuOJD8FQ,3710 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/DataLayoutAttrInterface.cpp.inc,sha256=du5dstIse9fqhIXSWB7TVsMkTwCWe7WHYU_vaQn25mk,2985 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/DataLayoutAttrInterface.h.inc,sha256=Cm1r56bVzM_YTag0T7FR1oOV6kcUePIJy-XJ2gPRffY,19448 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/DataLayoutInterfaces.h,sha256=3fGepaNLvNTCZHiMrD-AmUX6phlcLhTl6arH_M6ErFU,8842 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/DataLayoutOpInterface.cpp.inc,sha256=h-0gl_raaAz4ybh-R--1RydUPSLl-LoGZTRb7h_hMeg,2916 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/DataLayoutOpInterface.h.inc,sha256=p4g0xrS9RTsXc2S9jGxxLXMG6898GXAUI-dB2tZsrts,15477 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/DataLayoutTypeInterface.cpp.inc,sha256=63N4w4-aSixz6P0TUoDJ3UEp-bEDhkWPkCDBlzwqssY,2346 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/DataLayoutTypeInterface.h.inc,sha256=XA2mKPuf-V7CqFtxklhqHQUmhqhYuJEYS-WjcM-i8rk,13013 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/DerivedAttributeOpInterface.cpp.inc,sha256=vfZEkzHppACUhtS3Pc6qy7pGYXA4Xl34gY0RQSKWq8U,1074 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/DerivedAttributeOpInterface.h,sha256=-jBHtdFu-wqmo0GM9uLp14T-InLOzp6F0UEdfo625Rw,850 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/DerivedAttributeOpInterface.h.inc,sha256=DsilzzmDGl06ax0iViP6twNgKww3HDpC124OLHrzP1A,4072 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/DestinationStyleOpInterface.cpp.inc,sha256=xE7XBkqJ0mWb0OZNpJkQFgDg5b5ZwI2Ufpx87eWry2E,790 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/DestinationStyleOpInterface.h,sha256=TkiBAvd6UnUDfS4CsQL31K9mfn0ED4TaB2F_fiQa-Gg,1063 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/DestinationStyleOpInterface.h.inc,sha256=u2sYKRslVmS5R546c0UJ-Yz3d4c9Ba9wR2G4JYcL-s4,15122 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/FoldInterfaces.h,sha256=NMFZZUqiFCTrshc0t8izreWbraKO7b4km31B1zHQlKI,2091 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/FunctionImplementation.h,sha256=sncjbXVPi_6dJSpSn-9dE2WwTRK4rflp5jAHF5JSpWE,5053 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/FunctionInterfaces.cpp.inc,sha256=Ch6PCHusDjA1Hu7IX_vE02YK8TeDplnESgFfIHltMMY,9641 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/FunctionInterfaces.h,sha256=j9zwLIZToZQT46lVyfUSTWtkoQElYvjtN_2LSjEOTn0,10529 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/FunctionInterfaces.h.inc,sha256=SPST3JZSBbftTU8T0NwcyVUnn_Uc4NJCC7hXTbn057s,57966 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/InferIntRangeInterface.cpp.inc,sha256=TpeDQgtpOJMJlNU3XXgsVi6TZxNvfkEue2BAuM8AFCQ,1856 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/InferIntRangeInterface.h,sha256=a_FT9dco5YuFM4c5TKisp3sCzQVEd262E3RA9n53UuE,5182 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/InferIntRangeInterface.h.inc,sha256=-LhptaXp0kMAPtgVWMy7rzq8XKutqP_7u-akFEkXoeY,4556 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/InferTypeOpInterface.cpp.inc,sha256=ZafhNesJLx0p5iaKSrbi2uon6XahODGQxXABpS_9VI8,6645 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/InferTypeOpInterface.h,sha256=z2psv2T6AGUsg0VPgsmKY-8aOYxHs5ekTFzb7A9eInk,10102 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/InferTypeOpInterface.h.inc,sha256=qu7-J9jJdpYCNp3CdbTgEuxhPohyv5HlEJUeIc24xLU,28767 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/LoopLikeInterface.cpp.inc,sha256=O59GVm5QAiNGmvcZc-lCWOqzvI-vVP07uXNTq6GXr1w,4620 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/LoopLikeInterface.h,sha256=x6yVdQrypXz-JtIF7ydAbZ9F-21wH66zWNiibHru0Ik,1239 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/LoopLikeInterface.h.inc,sha256=o1GM4gLqb7ddPPoCtLZXQyDtepac2y4vDjwuyQtWUI0,26565 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/MemorySlotInterfaces.h,sha256=Z_qvUlOcosHS2c5IXSYMJWOUFeXzLDvRWX42IdphEGY,1570 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/MemorySlotOpInterfaces.cpp.inc,sha256=T95zMQbB14N1vd-9oihNZCCIBvcHrAlNKbnSgq8UzIQ,13368 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/MemorySlotOpInterfaces.h.inc,sha256=z8MPQWNX3InDb74EDCznW42g_iXwkc64zntmczf1lqA,44696 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/MemorySlotTypeInterfaces.cpp.inc,sha256=4BQiGVAhrz9hy8j6bZs5GDnrKL4S47BMbbH7i_EsTBc,1387 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/MemorySlotTypeInterfaces.h.inc,sha256=KXHc8hmHm9s_hrag0ooyqvT3vTnGvZofVWtmrq9Ia8U,4921 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/ParallelCombiningOpInterface.cpp.inc,sha256=2Zx4WI6eDJ3mH04wTooPVIyAVYXxy80hPfINuzTUizI,1047 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/ParallelCombiningOpInterface.h,sha256=l3z3APAjQV2j8BIyblWwHjCH0nmNrI7yBKLcFtfV_7w,1077 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/ParallelCombiningOpInterface.h.inc,sha256=FPtOBpIGIMa-VfJhBeOmmUnfEtf-xD81DJgCZcQl_mk,4485 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/RuntimeVerifiableOpInterface.cpp.inc,sha256=gqd8ceP-L42Kun0dQqZsXHErAdTDfbYptdrNAty7YoU,888 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/RuntimeVerifiableOpInterface.h,sha256=kwCxBazty-SOK3vJDI6daaBSOxjiKLn2OSM_mcPL2yw,689 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/RuntimeVerifiableOpInterface.h.inc,sha256=v-eUgjq7o7MnUSNySnL8rlnK4WMlL5xwSPFH5d2lrnc,3511 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/ShapedOpInterfaces.cpp.inc,sha256=G2O38mqYACVH6YGONHz-ePNdOs8hqjtP9Hq-asGlZRI,1002 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/ShapedOpInterfaces.h,sha256=y5wqqwZCSsBFaRCDooWCgL45fx2Zswzgg6Z5wQdy_v8,1025 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/ShapedOpInterfaces.h.inc,sha256=p6KGi1YhFpfB8D2UHZnLlr_n_XYdlTq56kNgPQ05xLo,4106 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/SideEffectInterfaces.cpp.inc,sha256=UGNPg-lVByiWqYT6lolU1USDs8vNFJvmDLa-4I4Q83U,1236 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/SideEffectInterfaces.h,sha256=nWOXPHhtdzMwPqlS-RryV4IICmmz-N3GhcZxH3tF-Tw,17153 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/SideEffectInterfaces.h.inc,sha256=57eoVafd5VStL9qMKBgJ3t-f-2mjIaKrh4w5RzP4R5Q,9952 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/TilingInterface.cpp.inc,sha256=WFTpobTuZ45m56mGiWaHVX5jMFujf1Yu78vlWc4J9sQ,6316 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/TilingInterface.h,sha256=5tmDyib6Hm0fxOjvrND4NViZctUEJ-K-QOccR15Pv7g,1436 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/TilingInterface.h.inc,sha256=vA7KjyIsXaLB6lZfDZnCOZtbcj0gdWImYBXjWzuqTH8,30408 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/Utils/InferIntRangeCommon.h,sha256=bpUJDQfxIQNG9Y_bHHA7XnMLnKD-rR2YZcJ4YmlXXzQ,4940 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/ValueBoundsOpInterface.cpp.inc,sha256=ce8stlw_ID2MpU32NXaPX6Ficc-lYNafGzFf9ek9wr8,1572 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/ValueBoundsOpInterface.h,sha256=homIufByfrk-aeLb8au8iNOLmFjufq4f9QacwLWREGQ,12155 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/ValueBoundsOpInterface.h.inc,sha256=gY2ro_HKzv-hUS8BF5sieydu256D2IvBirSLCilmC0U,7289 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/VectorInterfaces.cpp.inc,sha256=JTSvZlTN5uYgGhNCoVRBQeRm9k5qdBMQ6gLirJxQxEU,5556 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/VectorInterfaces.h,sha256=OMYByWFWvo8ks9s1mMV_jk-qZiw8Rq13T751fssBurI,855 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/VectorInterfaces.h.inc,sha256=jIlnrROOyW21O-kGuu4vOaufdNC5rY2N-szHZENbZK0,38571 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/ViewLikeInterface.cpp.inc,sha256=nTzQf9fF4Mxz-2pBiDG9vqwWsoywa5olp0i5Heu9tlI,6687 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/ViewLikeInterface.h,sha256=380v-4q7w3-TXuZGJ1ZlBMAztT7DSmnUEG3BxMEyRg4,7757 +tensorflow/include/external/llvm-project/mlir/include/mlir/Interfaces/ViewLikeInterface.h.inc,sha256=VMV5gvKzUzBRnP4r4FP60bpgVnIDaVHQv7a8QRIACyI,51306 +tensorflow/include/external/llvm-project/mlir/include/mlir/Parser/Parser.h,sha256=TwBnao1KIbjEcwJZpFF4eo11HF7UP3EVcJD_jrDOyY4,13765 +tensorflow/include/external/llvm-project/mlir/include/mlir/Pass/AnalysisManager.h,sha256=Uu2Y-DxijruuMUkDOwcdypeY9sQ_LLopKYPGHsZDfFo,15520 +tensorflow/include/external/llvm-project/mlir/include/mlir/Pass/Pass.h,sha256=5TkX23rTsIjxMD8FFd43Gv6btcq2ecbKHIFGYIYElIs,18138 +tensorflow/include/external/llvm-project/mlir/include/mlir/Pass/PassInstrumentation.h,sha256=Bu9ICPHH9WYm3waaRhVVE5MyoYoKgvAKC5JaUflZXZE,5880 +tensorflow/include/external/llvm-project/mlir/include/mlir/Pass/PassManager.h,sha256=y9nuTPMdXYxBsS7Iwj85mQsYkWAva_SXlFWrHBLlcDM,19853 +tensorflow/include/external/llvm-project/mlir/include/mlir/Pass/PassOptions.h,sha256=YcPZifWbyXk4vKfz8jo5ACsz5_TiQqaLNaEAgsjrcNo,18479 +tensorflow/include/external/llvm-project/mlir/include/mlir/Pass/PassRegistry.h,sha256=irJQx_MyfhifR-DESZKjgOvjDDb3G48ve6ycSpfLZQ0,12235 +tensorflow/include/external/llvm-project/mlir/include/mlir/Rewrite/FrozenRewritePatternSet.h,sha256=IevsxnNS3BoavYA2JRlREDVz3thAZJRSsACaSKWrv_g,4200 +tensorflow/include/external/llvm-project/mlir/include/mlir/Rewrite/PatternApplicator.h,sha256=84-3eJAXpPT3n9BL0SOP86mwoR0AAPK5xlTxG-RsF7I,4030 +tensorflow/include/external/llvm-project/mlir/include/mlir/Support/DebugStringHelper.h,sha256=aNa0pnKHSNEw0VwRerk4CgrQt23ldkYrasZj-_A-sRA,1291 +tensorflow/include/external/llvm-project/mlir/include/mlir/Support/FileUtilities.h,sha256=-ntgDcw7CpGTPj-7LAgFiM6TufB0AAPbxuswHgtusBQ,1732 +tensorflow/include/external/llvm-project/mlir/include/mlir/Support/IndentedOstream.h,sha256=UP0xLMLNWS8jR5RR71H8Wmf-Kb7Bq6LxjfT39Brl4aM,5684 +tensorflow/include/external/llvm-project/mlir/include/mlir/Support/InterfaceSupport.h,sha256=RE7cJ2UBaNcgwn0lXs_qxYQ9qRmwW8OZWKzyhIcfkiE,11787 +tensorflow/include/external/llvm-project/mlir/include/mlir/Support/LLVM.h,sha256=N_TKIlG3KQPuVsD1ecJRAm0hVTxTJ2aIsbyEBceR2wg,4436 +tensorflow/include/external/llvm-project/mlir/include/mlir/Support/LogicalResult.h,sha256=7WM-TZI1nSVCO5cyOIjrCeqLi1Jk5oFcXqHv_Rv1Yz4,5305 +tensorflow/include/external/llvm-project/mlir/include/mlir/Support/MathExtras.h,sha256=qKPNq-jGmrqpRbMh4RaR5IxJ3X3Lccx97cdNrJQpfGQ,1908 +tensorflow/include/external/llvm-project/mlir/include/mlir/Support/RawOstreamExtras.h,sha256=VbtMZrEydp9J1Asm2icYXwoDSeKUoaUe3bhJbuFyY4c,626 +tensorflow/include/external/llvm-project/mlir/include/mlir/Support/StorageUniquer.h,sha256=rwLkEMohSP9j4H0mnJ0SEZLybcJ3U-31bVndODtQLYc,13845 +tensorflow/include/external/llvm-project/mlir/include/mlir/Support/ThreadLocalCache.h,sha256=zFL_AtL_HMXi_XEIS1qCeoUAzPF6ocPvjNEg6wBHlQQ,5158 +tensorflow/include/external/llvm-project/mlir/include/mlir/Support/Timing.h,sha256=KOaprM9dxVwpoK14EzaUGD9cvvV95XQesEVNODbvmjU,15265 +tensorflow/include/external/llvm-project/mlir/include/mlir/Support/ToolUtilities.h,sha256=xvFTSUFUpkSMxcz2AuE-yJGXDMwxE2N-1bUKV5sRgaA,1795 +tensorflow/include/external/llvm-project/mlir/include/mlir/Support/TypeID.h,sha256=UEq1JJBLaXZS0NpcpzNfN3flq7sBVspnaC8kHhZTmhg,15347 +tensorflow/include/external/llvm-project/mlir/include/mlir/Target/LLVM/ModuleToObject.h,sha256=013_uXf2HxRKMQiwlfV4IYer1eRWyBKbdtrw5BEbHPo,4282 +tensorflow/include/external/llvm-project/mlir/include/mlir/Target/LLVM/NVVM/Target.h,sha256=eiyDWQx6EAUwHD0h-gYQStx3yzW80XFxNhnOukBJPDA,1145 +tensorflow/include/external/llvm-project/mlir/include/mlir/Target/LLVM/NVVM/Utils.h,sha256=FKYr9UpFvRwp0QTVtkeCw1BCpgttEldQWhuVmKtja6M,2602 +tensorflow/include/external/llvm-project/mlir/include/mlir/Target/LLVM/ROCDL/Target.h,sha256=GFvrsF8e9jCZILotXZ22iN4dHgmF21MHW4wxi0BgKTY,1155 +tensorflow/include/external/llvm-project/mlir/include/mlir/Target/LLVM/ROCDL/Utils.h,sha256=tb2NhKXHGDf0J50D8r9Jc3AiXt2P1xgVmkxLP1gsNJA,3588 +tensorflow/include/external/llvm-project/mlir/include/mlir/Target/LLVMIR/Dialect/AMX/AMXToLLVMIRTranslation.h,sha256=Ug3d0kCCAvyPD0iZQbdbvjFe52y36p1sZCMfW0jsfZA,1144 +tensorflow/include/external/llvm-project/mlir/include/mlir/Target/LLVMIR/Dialect/All.h,sha256=ixe7Qz7_TWM_RagVOrNYbPU4hkGH51tBgwopAGapXis,3429 +tensorflow/include/external/llvm-project/mlir/include/mlir/Target/LLVMIR/Dialect/ArmNeon/ArmNeonToLLVMIRTranslation.h,sha256=iCCFzE6IJ24_0vLLT5Ue7Whrdc9OJaZpX1thq5e1ooA,1188 +tensorflow/include/external/llvm-project/mlir/include/mlir/Target/LLVMIR/Dialect/ArmSME/ArmSMEToLLVMIRTranslation.h,sha256=71ugun9z7_bnRi6GKd8gv5z-4UxodkFrfJNq1FLDoAk,1177 +tensorflow/include/external/llvm-project/mlir/include/mlir/Target/LLVMIR/Dialect/ArmSVE/ArmSVEToLLVMIRTranslation.h,sha256=_-PYEutnut4ylFFzz-rU_1A9UtgTW5ZyRnMZNWcAWrQ,1177 +tensorflow/include/external/llvm-project/mlir/include/mlir/Target/LLVMIR/Dialect/Builtin/BuiltinToLLVMIRTranslation.h,sha256=mGA606-N8Jx90IQCqGWzLGZ3VmblLxSXS7ksrRmWhMQ,1173 +tensorflow/include/external/llvm-project/mlir/include/mlir/Target/LLVMIR/Dialect/GPU/GPUToLLVMIRTranslation.h,sha256=pPTg7RN0aaVwypVw2vfTHOUYhGaCQuFjLIGpYpv9dVE,1367 +tensorflow/include/external/llvm-project/mlir/include/mlir/Target/LLVMIR/Dialect/LLVMIR/LLVMIRToLLVMTranslation.h,sha256=0MEjRi84o_EhHWncuElbquQEjw0YdwPrSOV0AHeet3c,1111 +tensorflow/include/external/llvm-project/mlir/include/mlir/Target/LLVMIR/Dialect/LLVMIR/LLVMToLLVMIRTranslation.h,sha256=TRmGYLi2Ap4PDE8KjwHcxoc1pfuUtlm4_Mdlaac6I-0,1161 +tensorflow/include/external/llvm-project/mlir/include/mlir/Target/LLVMIR/Dialect/NVVM/NVVMToLLVMIRTranslation.h,sha256=adrR9vzPL8bJU6_nFwCs2EU_bV2MnTJMEaHvevJE0PI,1155 +tensorflow/include/external/llvm-project/mlir/include/mlir/Target/LLVMIR/Dialect/OpenACC/OpenACCToLLVMIRTranslation.h,sha256=bpfhdEylq2ga_mpqmDVbIFHhhSIYw0kOAlzrEweX9uI,1172 +tensorflow/include/external/llvm-project/mlir/include/mlir/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.h,sha256=MT-xeW6ibu71nAYT7lqW502OijPKjyN_wdIkGzbuM0o,1177 +tensorflow/include/external/llvm-project/mlir/include/mlir/Target/LLVMIR/Dialect/OpenMPCommon.h,sha256=OG7fxv3LWBX9e5_MtEZgDJNG1oAVp5GC6-hs8J-G9zA,1537 +tensorflow/include/external/llvm-project/mlir/include/mlir/Target/LLVMIR/Dialect/ROCDL/ROCDLToLLVMIRTranslation.h,sha256=piM5w_q5DhWtR_WPz3K_Hmxht7R8ypSWcKjBlpnh3WI,1166 +tensorflow/include/external/llvm-project/mlir/include/mlir/Target/LLVMIR/Dialect/X86Vector/X86VectorToLLVMIRTranslation.h,sha256=7ZN71s1qFaR-DoChdbrXzUw3qMDc_5muvIDZ_42lUjA,1213 +tensorflow/include/external/llvm-project/mlir/include/mlir/Target/LLVMIR/Export.h,sha256=VUQ2gqRoUW8qYn8U01OZwDAzSu0DqqQKVYjNbLLdqMQ,1087 +tensorflow/include/external/llvm-project/mlir/include/mlir/Target/LLVMIR/Import.h,sha256=3ndDDGKPNVCxXCKyS2YS3JNU5quHPagFEceVXOfT9D8,1851 +tensorflow/include/external/llvm-project/mlir/include/mlir/Target/LLVMIR/LLVMImportInterface.h,sha256=JX99meUNqgl8vMD-epLQzz-cyUsalHCuZEN0TJQLqrw,7137 +tensorflow/include/external/llvm-project/mlir/include/mlir/Target/LLVMIR/LLVMTranslationInterface.h,sha256=EPD2Uiy1MVFZJ6Es-Cb26JoLedZU1Vno3O2ahXe6ifM,3710 +tensorflow/include/external/llvm-project/mlir/include/mlir/Target/LLVMIR/ModuleImport.h,sha256=2tqYWQ3q71jTZQEdN9kaSFxYTsxUGgiF1yKhop2jwF0,18046 +tensorflow/include/external/llvm-project/mlir/include/mlir/Target/LLVMIR/ModuleTranslation.h,sha256=0k64FXVMKysMVlIIUIYCNnU8H98YOtfZNbWxFmu8m6M,16245 +tensorflow/include/external/llvm-project/mlir/include/mlir/Target/LLVMIR/TypeFromLLVM.h,sha256=TQHCjMIC8ol_Y8VX37Is2tdcAJSO_REoGKWrO8KrGRU,1505 +tensorflow/include/external/llvm-project/mlir/include/mlir/Target/LLVMIR/TypeToLLVM.h,sha256=nIeuPnWh1hIYpsMNW6qEMtDxIDy7wf4LbG5AEmlbeIM,1806 +tensorflow/include/external/llvm-project/mlir/include/mlir/Tools/ParseUtilities.h,sha256=v68s_1EVf5yCTBoIe5e1_5opagnbm5vWkUIv2FsM4ro,1529 +tensorflow/include/external/llvm-project/mlir/include/mlir/Tools/mlir-translate/MlirTranslateMain.h,sha256=9iawBpI1zVVw8c3meNST1crbPvmiI_8NJztkEUz7M90,1217 +tensorflow/include/external/llvm-project/mlir/include/mlir/Tools/mlir-translate/Translation.h,sha256=3MEMfsikgzP2IGBNLdppGONPQznGX-mtnZhpBRpVVOw,7259 +tensorflow/include/external/llvm-project/mlir/include/mlir/Transforms/CFGToSCF.h,sha256=UKv7Tsm-TUFJUZN95TOYrq2aQf7jJE85PnkD33CI194,8149 +tensorflow/include/external/llvm-project/mlir/include/mlir/Transforms/CSE.h,sha256=1eeWZLWKRBoMMmNl7R2FYNTiDHqr9OiLS9E9ZHf7qyE,1112 +tensorflow/include/external/llvm-project/mlir/include/mlir/Transforms/CommutativityUtils.h,sha256=NkGzEI-Vja3MGtkiZVFCImKxMbKnOUpJR2zPmlRYIxE,1037 +tensorflow/include/external/llvm-project/mlir/include/mlir/Transforms/ControlFlowSinkUtils.h,sha256=4PzTWM13V8DL4DE_rmb9-Cve4J11_vk9k1-YatrODzQ,2747 +tensorflow/include/external/llvm-project/mlir/include/mlir/Transforms/DialectConversion.h,sha256=UxsfaCNyCXLMKakQJcnTdr2GQMi2y2wNSoVxK3rcZo8,49837 +tensorflow/include/external/llvm-project/mlir/include/mlir/Transforms/FoldUtils.h,sha256=9om5WefMJejdR5A0kd4W8WuIrVwsXiRGMQhipJhXHyc,5048 +tensorflow/include/external/llvm-project/mlir/include/mlir/Transforms/GreedyPatternRewriteDriver.h,sha256=yfbSywWm249_OtcPMAvcOltOYJYGdp-Vxzzg34iMTvc,6862 +tensorflow/include/external/llvm-project/mlir/include/mlir/Transforms/InliningUtils.h,sha256=K7rYpnw7mftWohy7Zg3d5xBH-7EBN63nG8NrxYgJAvQ,14661 +tensorflow/include/external/llvm-project/mlir/include/mlir/Transforms/LocationSnapshot.h,sha256=H5VHXXVupthqHCbBJ57wwBuoUjxi9yofwMUwkHOo_2E,3280 +tensorflow/include/external/llvm-project/mlir/include/mlir/Transforms/LoopInvariantCodeMotionUtils.h,sha256=VBiSycObitiTcCg5bF2-l22qpNW9VswWlF4tNGy_Edw,2561 +tensorflow/include/external/llvm-project/mlir/include/mlir/Transforms/Mem2Reg.h,sha256=aDKrSPMtcyQtBZgIdmuZW3dkIxC7SwvNG7MYaVfZnqU,1954 +tensorflow/include/external/llvm-project/mlir/include/mlir/Transforms/OneToNTypeConversion.h,sha256=ch4QMNJXGUjCmUgwxHg0VZjqQuoSueWuCVuKPguHYmQ,14818 +tensorflow/include/external/llvm-project/mlir/include/mlir/Transforms/Passes.h,sha256=Kiv8EeifiL8hWz-MXTofiWdpGAYDwTNSzh-rK1SMS44,5884 +tensorflow/include/external/llvm-project/mlir/include/mlir/Transforms/Passes.h.inc,sha256=amsbBPYD952WXrD6piSndJO0kDf8PhNDGYLoI8XmQ_0,93723 +tensorflow/include/external/llvm-project/mlir/include/mlir/Transforms/RegionUtils.h,sha256=8GxC69AyfBz4Nw2PpStIJ4SZWoGIlbzEfaDRlnB7WN0,4175 +tensorflow/include/external/llvm-project/mlir/include/mlir/Transforms/SROA.h,sha256=nKB1S3thbIIfdBWUQU61tZW-b38h5pinDf9zApomapQ,2106 +tensorflow/include/external/llvm-project/mlir/include/mlir/Transforms/TopologicalSortUtils.h,sha256=y1IOHkTA_l3hTPDGgLOW9cGfrZ14kE2GBaZeFnnQViM,3332 +tensorflow/include/external/llvm-project/mlir/include/mlir/Transforms/Transforms.capi.cpp.inc,sha256=l-Xrv2w42M0loj_izSdUETCx7b_YoaO1HpODuU6vR8k,3696 +tensorflow/include/external/llvm-project/mlir/include/mlir/Transforms/Transforms.capi.h.inc,sha256=6Ek5JCPt17l_uGX4_vqcB67U2-o855UY8ixlyRkqZqs,3253 +tensorflow/include/external/llvm-project/mlir/include/mlir/Transforms/ViewOpGraph.h,sha256=sVHIrRF2c0vgjnaUhGiMwR2qDkKTQJeG0_dGCKnfEbU,965 +tensorflow/include/external/llvm-project/mlir/lib/AsmParser/AsmParserImpl.h,sha256=l-jCWKS6I0P2k02dqySBlzvuHEolD2XKZq0K7A_xCes,20882 +tensorflow/include/external/llvm-project/mlir/lib/AsmParser/Lexer.h,sha256=aWliUK8yl5dCJcWTycMzHHKGogPVjNHBMJL5lI5jPSY,2615 +tensorflow/include/external/llvm-project/mlir/lib/AsmParser/Parser.h,sha256=mvGhW3r4f0AOU26TO20lL2Spc8X_pFC0MkJDCkQ9z2c,14101 +tensorflow/include/external/llvm-project/mlir/lib/AsmParser/ParserState.h,sha256=-JUg7iKitStaZ7HwfNcd6gVTgntBsc6Z-VVdGZokimY,3511 +tensorflow/include/external/llvm-project/mlir/lib/AsmParser/Token.h,sha256=BJ2a_eBAROjvjXbmkaW9w9zcXcScLFyGTMCO3lKCu70,4882 +tensorflow/include/external/llvm-project/mlir/lib/AsmParser/TokenKinds.def,sha256=CwMHUPuS-9h8uV_R5NT1zLVxt5ewyfFuZU94JrR7_zs,3463 +tensorflow/include/external/llvm-project/mlir/lib/Bytecode/Writer/IRNumbering.h,sha256=8aHkr5HfakIgx0j_D-0sXzAB5VhSR36HBDRXbO9eTCA,10017 +tensorflow/include/external/llvm-project/mlir/lib/Conversion/GPUCommon/GPUOpsLowering.h,sha256=uX7csjfpR7PBVUShBfkaUo2BRsoZTMD-d_g5aYXgmBo,4696 +tensorflow/include/external/llvm-project/mlir/lib/Conversion/GPUCommon/IndexIntrinsicsOpLowering.h,sha256=w190P8sAuxVCbiqb-Y9eJiWUvCEsPeQQETO3lmHyeZU,3491 +tensorflow/include/external/llvm-project/mlir/lib/Conversion/GPUCommon/OpToFuncCallLowering.h,sha256=IwcqXuZm7JUhZm7FoeAl46lnrbCT3djViiZq3YIMfj0,4284 +tensorflow/include/external/llvm-project/mlir/lib/Conversion/GPUToNVVM/GPUToNVVM.cpp.inc,sha256=Fn9djodc8RRC9VNMSacrxSJfzLHybIjniI_ueUiU2YI,2060 +tensorflow/include/external/llvm-project/mlir/lib/Conversion/GPUToROCDL/GPUToROCDL.cpp.inc,sha256=tEOeuLmnfXafp5WKd9cJggNrvwd_NhsUx4QYPAKXQok,2060 +tensorflow/include/external/llvm-project/mlir/lib/Conversion/LLVMCommon/MemRefDescriptor.h,sha256=hwlinmEOtsgoSLvEXkjG6HtSl26j5lMbZizC0gS1mpE,1148 +tensorflow/include/external/llvm-project/mlir/lib/Conversion/PDLToPDLInterp/Predicate.h,sha256=WtJNinRTm2LF5JE8iYRwr2Ej4c3zDrRjLc7MIqfOA7Y,28047 +tensorflow/include/external/llvm-project/mlir/lib/Conversion/PDLToPDLInterp/PredicateTree.h,sha256=1PPPnLXMMA-26GiW0QoguSi8tPvqb_tS-1RrSlxyXi4,7748 +tensorflow/include/external/llvm-project/mlir/lib/Conversion/PDLToPDLInterp/RootOrdering.h,sha256=GTXcVyFBrwu1ouPY8snl01rDESpkCFWKqQNDab2oAow,6718 +tensorflow/include/external/llvm-project/mlir/lib/Conversion/ShapeToStandard/ShapeToStandard.cpp.inc,sha256=cSxWYR-ppFRiVNw3R6fH060SEonHVF5PpBgLYm30hno,5712 +tensorflow/include/external/llvm-project/mlir/lib/Dialect/Async/Transforms/PassDetail.h,sha256=dFrCZIECU8bc-Uj1MC_JmFcoMFbikZRPMdJyTUhB5K0,1520 +tensorflow/include/external/llvm-project/mlir/lib/Dialect/LLVMIR/IR/LLVMInlining.h,sha256=VzHCUJmcy78hOh2HPDToQzCw-mTHAYjVtAxQceBwJx8,989 +tensorflow/include/external/llvm-project/mlir/lib/Dialect/LLVMIR/IR/TypeDetail.h,sha256=tr7OYgSv_tHbI2BjoyvO5mlColAcAVycIhq59ZAtSCU,15456 +tensorflow/include/external/llvm-project/mlir/lib/Dialect/Quant/IR/QuantDialectBytecode.h,sha256=svCQ7cm5cRmKBRVup8afnQpd_HxEAOG4QzUkxjUqxfw,994 +tensorflow/include/external/llvm-project/mlir/lib/Dialect/Quant/IR/TypeDetail.h,sha256=6PPPydjszcCyR2r2lvm0cdykhrTSyc0sxxpwlSV3btc,11174 +tensorflow/include/external/llvm-project/mlir/lib/Dialect/SparseTensor/IR/Detail/DimLvlMap.h,sha256=1syNqctLDLlOb2HqIcNccXw_v7mWTFwD4tbnofEi3D4,14443 +tensorflow/include/external/llvm-project/mlir/lib/Dialect/SparseTensor/IR/Detail/DimLvlMapParser.h,sha256=hOXnITzhD615vj5Fsl7i0jaLMRm6K9OU1J6vEVI6WlE,4132 +tensorflow/include/external/llvm-project/mlir/lib/Dialect/SparseTensor/IR/Detail/LvlTypeParser.h,sha256=uZ7aOCm8g6M5InYS_qcR8sKo180y9V9_pHPRJnCbDJY,941 +tensorflow/include/external/llvm-project/mlir/lib/Dialect/SparseTensor/IR/Detail/TemplateExtras.h,sha256=8G1aS4CEkDvwPjAmxh-Bnv9jt6YwCLJy3PWnVm5TFeI,4173 +tensorflow/include/external/llvm-project/mlir/lib/Dialect/SparseTensor/IR/Detail/Var.h,sha256=TGTB_pZSNKjOc9cLBAvrTuLCwsnTAkigAj6VS4axE4o,21360 +tensorflow/include/external/llvm-project/mlir/lib/Dialect/SparseTensor/Transforms/CodegenEnv.h,sha256=ep-gSdePKBdtLIYmUIzQfYQVMW9VNFNf6USZcZ_0Voc,8247 +tensorflow/include/external/llvm-project/mlir/lib/Dialect/SparseTensor/Transforms/CodegenUtils.h,sha256=G8Sar71yWqGDaHgRVkOt_ZuCvDrQBZVU79ra5H__3DU,20700 +tensorflow/include/external/llvm-project/mlir/lib/Dialect/SparseTensor/Transforms/LoopEmitter.h,sha256=j_PsOQOm3pEzWxND2noXacOP3m6yE-wNe29Yqmwp4VU,32925 +tensorflow/include/external/llvm-project/mlir/lib/Dialect/SparseTensor/Transforms/SparseTensorDescriptor.h,sha256=EIsIGgw7ecix6bgiUrTAbatPxTNtWpuYnLWyVFNC0HU,10443 +tensorflow/include/external/llvm-project/mlir/lib/IR/AffineExprDetail.h,sha256=tlI8aQgtCkl_NW8yR3wtGBSARBJRyGk-RbAtwNfSNgY,3193 +tensorflow/include/external/llvm-project/mlir/lib/IR/AffineMapDetail.h,sha256=pgVwr5ZfYgdp_ZcYua4wcRCdnkzgWWGePqVAvJs2YiM,2243 +tensorflow/include/external/llvm-project/mlir/lib/IR/AttributeDetail.h,sha256=DLu4y6bhtxRhPYyZqqZda2tVxS5ygqwm8MkM8j10oNY,16414 +tensorflow/include/external/llvm-project/mlir/lib/IR/BuiltinDialectBytecode.h,sha256=LzHgcCGJS1kMGZFdMmMHMIteUaISnOZ96-mfSUppdmY,954 +tensorflow/include/external/llvm-project/mlir/lib/IR/IntegerSetDetail.h,sha256=_eglsmXUhgTa45RDdRCXSuChcZzeZMS4rgYNk0ziTyM,1910 +tensorflow/include/external/llvm-project/mlir/lib/IR/TypeDetail.h,sha256=LCZV-Ppim73sCuCbtI44JJPYmNlCpZGqP7G5oLqRFi0,5254 +tensorflow/include/external/llvm-project/mlir/lib/Pass/PassDetail.h,sha256=Pmh0b9E1Z5HKeH4woFcH9IKV7QXaloPLOHhFxVG4n24,6242 +tensorflow/include/external/llvm-project/mlir/lib/Rewrite/ByteCode.h,sha256=W34pfPHSlGvkqO841L_G9sky9nUIyRMzQ-lFL9_BHHU,9548 +tensorflow/include/external/llvm-project/mlir/lib/Target/LLVMIR/AttrKindDetail.h,sha256=_pYFAlFEQbT2ns5eVMLYQ8MYeNzUPamrPxyStlUUacY,3161 +tensorflow/include/external/llvm-project/mlir/lib/Target/LLVMIR/DataLayoutImporter.h,sha256=lQr5WcKYgStzB_Bue_4xENhc9CEHNtAk3_-7VTJrqCM,4503 +tensorflow/include/external/llvm-project/mlir/lib/Target/LLVMIR/DebugImporter.h,sha256=HrpQnv_RviKRVi0EpPWmEaStdcitqUDF-3sVKNUPquY,3506 +tensorflow/include/external/llvm-project/mlir/lib/Target/LLVMIR/DebugTranslation.h,sha256=pvEBC7CveIhJZ_sAM3RINUIgZ4Ktck1wHsylDXgjTWs,4510 +tensorflow/include/external/llvm-project/mlir/lib/Target/LLVMIR/LoopAnnotationImporter.h,sha256=IroHwZcsILcHRI8xNQd4S8lygnXmja-4bmlkMypDm9I,2883 +tensorflow/include/external/llvm-project/mlir/lib/Target/LLVMIR/LoopAnnotationTranslation.h,sha256=4yCUu_V5iT7JG8vWt_wtPQDPFUj_vKyxwRAmLfAl5y4,2877 +tensorflow/include/external/local_config_cuda/cuda/cuda/cuda_config.h,sha256=Agt2pQ3WM9tRvpI9kWBSCzOe4BYPhyflDzAcniDB0N4,1148 +tensorflow/include/external/local_config_python/numpy_include/numpy/.doxyfile,sha256=goOZR7LcINt3snuBGH8Me-_aVTGm5f4u4wEaSpjM_W4,58 +tensorflow/include/external/local_config_python/numpy_include/numpy/__multiarray_api.h,sha256=g07fWp9Fe-CBg5QPEKAxdAgysVpylHC27SMwHIZyOwo,62314 +tensorflow/include/external/local_config_python/numpy_include/numpy/__ufunc_api.h,sha256=kOT0I320xLGHnuE8XSaomEiCmFaup8fTOTied514XiM,12614 +tensorflow/include/external/local_config_python/numpy_include/numpy/_neighborhood_iterator_imp.h,sha256=A6YPpQihUwscZYxz0oODrBjRSYZdJM2dG0vcdtJtY64,1877 +tensorflow/include/external/local_config_python/numpy_include/numpy/_numpyconfig.h,sha256=DYhvMSbnzi1OVUxC_e4qjpjq0PKGZdqiMwu8B3I43kI,971 +tensorflow/include/external/local_config_python/numpy_include/numpy/arrayobject.h,sha256=-BlWQ7kfVbzCqzHn0qaeMe0_08AbwliuG98XWG57lT8,282 +tensorflow/include/external/local_config_python/numpy_include/numpy/arrayscalars.h,sha256=h6MKjFHzguTZ5CQd7HATAVWHoZ7mkC-86R1uMHeLT04,3818 +tensorflow/include/external/local_config_python/numpy_include/numpy/experimental_dtype_api.h,sha256=U4gGFiivVt-975AVhEWtF7aGzufOJQivX1FmBarM2os,19915 +tensorflow/include/external/local_config_python/numpy_include/numpy/halffloat.h,sha256=TRZfXgipa-dFppX2uNgkrjrPli-1BfJtadWjAembJ4s,1959 +tensorflow/include/external/local_config_python/numpy_include/numpy/libdivide/LICENSE.txt,sha256=-8U59H0M-DvGE3gID7hz1cFGMBJsrL_nVANcOSbapew,1018 +tensorflow/include/external/local_config_python/numpy_include/numpy/libdivide/libdivide.h,sha256=ew9MNhPQd1LsCZiWiFmj9IZ7yOnA3HKOXffDeR9X1jw,80138 +tensorflow/include/external/local_config_python/numpy_include/numpy/multiarray_api.txt,sha256=lUu3-kmIThRGDbEyhz7avfa7gM6OwUuQhqt4JHa1gmE,57008 +tensorflow/include/external/local_config_python/numpy_include/numpy/ndarrayobject.h,sha256=Lvr0ljFumbLtDgepidCtA1V3fHoTRpL432B-t7sWVh0,10191 +tensorflow/include/external/local_config_python/numpy_include/numpy/ndarraytypes.h,sha256=BNnFGzO8_pnEA3T47ORSlGABK4MqfODvyb0P-IO_AwE,69078 +tensorflow/include/external/local_config_python/numpy_include/numpy/noprefix.h,sha256=d83l1QpCCVqMV2k29NMkL3Ld1qNjiC6hzOPWZAivEjQ,6830 +tensorflow/include/external/local_config_python/numpy_include/numpy/npy_1_7_deprecated_api.h,sha256=y0MJ8Qw7Bkt4H_4VxIzHzpkw5JqAdj5ECgtn08fZFrI,4327 +tensorflow/include/external/local_config_python/numpy_include/numpy/npy_3kcompat.h,sha256=kkHpOP0HozJwzKj6h7A2MLJLdJGDUL_pJjYbC1aq6Kc,15990 +tensorflow/include/external/local_config_python/numpy_include/numpy/npy_common.h,sha256=_INzM3hdWejf7egw0_FnzYl_wxf1PBfxifXI5X2wG8Y,39015 +tensorflow/include/external/local_config_python/numpy_include/numpy/npy_cpu.h,sha256=s5wuxe4hDuxffIlhstEd5k5bZtNdrGWwjUo0haegE0E,4603 +tensorflow/include/external/local_config_python/numpy_include/numpy/npy_endian.h,sha256=we7X9fPeWzNpo_YTh09MPGDwdE0Rw_WDM4c9y4nBj5I,2786 +tensorflow/include/external/local_config_python/numpy_include/numpy/npy_interrupt.h,sha256=DQZIxi6FycLXD8drdHn2SSmLoRhIpo6osvPv13vowUA,1948 +tensorflow/include/external/local_config_python/numpy_include/numpy/npy_math.h,sha256=QfDcaqAczDkH4AmK3OHSshmsTFpNb1FwueyGt5X61NM,21370 +tensorflow/include/external/local_config_python/numpy_include/numpy/npy_no_deprecated_api.h,sha256=0yZrJcQEJ6MCHJInQk5TP9_qZ4t7EfBuoLOJ34IlJd4,678 +tensorflow/include/external/local_config_python/numpy_include/numpy/npy_os.h,sha256=l4OlIIc0snxwIZqJ4V7iKbIcTSk-aubsTSs0E2ZKvjM,1070 +tensorflow/include/external/local_config_python/numpy_include/numpy/numpyconfig.h,sha256=GxgJxPKS1gcG4vqp9BB_KpL_v4HwB7ZpMsHWWxZPLqw,2284 +tensorflow/include/external/local_config_python/numpy_include/numpy/old_defines.h,sha256=xuYQDDlMywu0Zsqm57hkgGwLsOFx6IvxzN2eiNF-gJY,6405 +tensorflow/include/external/local_config_python/numpy_include/numpy/oldnumeric.h,sha256=laP57STtFtJSs_fjRRDlrk34hqfqCwxP-BFEytR6lTM,899 +tensorflow/include/external/local_config_python/numpy_include/numpy/random/bitgen.h,sha256=49AwKOR552r-NkhuSOF1usb_URiMSRMvD22JF5pKIng,488 +tensorflow/include/external/local_config_python/numpy_include/numpy/random/distributions.h,sha256=uJVR8qB0LXdvRg7VZakVrZ8qDPRS9FWkxtLFfXzj-Jc,9865 +tensorflow/include/external/local_config_python/numpy_include/numpy/ufunc_api.txt,sha256=CMYRT5Wl36VufbEnjRR_yLg1vf0R3ydcNODyJY3WPCw,7198 +tensorflow/include/external/local_config_python/numpy_include/numpy/ufuncobject.h,sha256=PDpFN5loASykuAgmCEt2t38yt5RiNP54tDyQB33yT98,11895 +tensorflow/include/external/local_config_python/numpy_include/numpy/utils.h,sha256=wMNomSH3Dfj0q78PrjLVtFtN-FPo7UJ4o0ifCUO-6Es,1185 +tensorflow/include/external/local_config_python/python_include/Python.h,sha256=cLBMQIM7383XKw03ca_mfHQ0D_JoO30msNyOlSiSY6c,3224 +tensorflow/include/external/local_config_python/python_include/abstract.h,sha256=j6KR5ezggbPL9kP8RR8_yWIFcdmEcUE_yimus47YtyE,31405 +tensorflow/include/external/local_config_python/python_include/bltinmodule.h,sha256=G1EBtLhUCf2RADJxOQaAC7uDWAUDA2RpwqYKyOgLj3I,264 +tensorflow/include/external/local_config_python/python_include/boolobject.h,sha256=OwQqXWnx65JkgAehuYhJCnqRd8isNTqtBdeGNWoxOp8,1224 +tensorflow/include/external/local_config_python/python_include/bytearrayobject.h,sha256=pvMy7ceW81KDyep1vFm1Jcgr5SEpzqMuM3GXTeCNbuE,1484 +tensorflow/include/external/local_config_python/python_include/bytesobject.h,sha256=vYYxyQw3Jq98JDgAJqvBafdkBOFJYiIaO1OxlOB2tQQ,2593 +tensorflow/include/external/local_config_python/python_include/cellobject.h,sha256=amjB8NRNZo-AgOQJ0XR2PP51rhH4xMZnuOh0mlrgQl0,720 +tensorflow/include/external/local_config_python/python_include/ceval.h,sha256=6ni-nUWhe3Wx3Ym2ZhMApybcQbzhQNY9A7tOK0SuVko,5703 +tensorflow/include/external/local_config_python/python_include/classobject.h,sha256=CmRKiXkJkkma0XTUksjSl3jZWWZJjuVprYxtkNpUwFQ,1657 +tensorflow/include/external/local_config_python/python_include/code.h,sha256=3iHus65_ExTilnJ71tthz-SW4XeiMO11Bx569bAtiLU,318 +tensorflow/include/external/local_config_python/python_include/codecs.h,sha256=DKPG5V5_9ihytHrutzedeEsD6_xhu9AptnSF_ng7qsU,7071 +tensorflow/include/external/local_config_python/python_include/compile.h,sha256=KGdub_Y4SMfoEsNLt5zYHfzLwKn_xW1bFDmzBN83ceo,520 +tensorflow/include/external/local_config_python/python_include/complexobject.h,sha256=fCJOYp49JXbMvwRXc4Y9y-9Wb4m3jSp45hQYyunCgsw,1806 +tensorflow/include/external/local_config_python/python_include/context.h,sha256=AS73epaDoBXmhyjE9DAUkhoE2wYmwdyfvMSKh9ThAS8,1962 +tensorflow/include/external/local_config_python/python_include/cpython/abstract.h,sha256=sT1kGY6Z-EvqUBK5Ixt3WoBsM6WOnkH41K4YwfdYB7Q,14054 +tensorflow/include/external/local_config_python/python_include/cpython/bytearrayobject.h,sha256=bA_1U03tL7Aa3gcfrQbhVh6j7LVZcMSnm4b9Rx-pvXE,769 +tensorflow/include/external/local_config_python/python_include/cpython/bytesobject.h,sha256=TRFUKzC8AZLC2oXeUBq84e_EIHkllfgYa2tjf51kD4E,4119 +tensorflow/include/external/local_config_python/python_include/cpython/ceval.h,sha256=RK0wD3NBFqLXpFT3YhVfIOPRXpL0rnylj296Q7AaevI,1468 +tensorflow/include/external/local_config_python/python_include/cpython/code.h,sha256=ahyV-Vssa_x2TUMx9lRV0rNpF27tbpobkWSj0KLM7mg,7570 +tensorflow/include/external/local_config_python/python_include/cpython/compile.h,sha256=h8yD4Oi4nLDbdRIi6BBM4FrmlOkK_8gsRqeKHzO1lWA,2218 +tensorflow/include/external/local_config_python/python_include/cpython/dictobject.h,sha256=SlGHMYlMQuaAAvnoaEqPKJIqH1rsaRyLPCawVZvuRqc,3734 +tensorflow/include/external/local_config_python/python_include/cpython/fileobject.h,sha256=_WvJQQcyZPz9XURHJH8vLNFg-qZ99mXshyWXcxNCcL4,723 +tensorflow/include/external/local_config_python/python_include/cpython/fileutils.h,sha256=Tn-Hqt3h3lIqZXLtQOfkNAOHRJn1gzINbZYVLgMs8Vo,4267 +tensorflow/include/external/local_config_python/python_include/cpython/frameobject.h,sha256=V8Du7qUuwSOcBLlj4ch9N_gzAMF_OZ-QCF2YDZJQoNQ,3152 +tensorflow/include/external/local_config_python/python_include/cpython/import.h,sha256=3A4Plr3ejfvFVJyrwhmjcmjob2KJ4lSsw0m-IgJgvCg,1630 +tensorflow/include/external/local_config_python/python_include/cpython/initconfig.h,sha256=DxP3TOtG0yWdjr3QvmHP6NBQiC_AP9SCsmQqDIH3yto,7597 +tensorflow/include/external/local_config_python/python_include/cpython/interpreteridobject.h,sha256=j8eXhNVWJF17fzggY-83l-OuvQprN1qVAn3WOl36MLY,387 +tensorflow/include/external/local_config_python/python_include/cpython/listobject.h,sha256=VKjDKclcX_k2KE54nJvbuKAj0yWktJKQsl8Va0v0_Vo,1243 +tensorflow/include/external/local_config_python/python_include/cpython/methodobject.h,sha256=0DVuBFYaFFsIrrXEV9aUQ_1Dh1QVhEy6V6rj9ex3xr4,1399 +tensorflow/include/external/local_config_python/python_include/cpython/object.h,sha256=Ytye5IChaIpktGRYum1XUpRqQcjJjF6Rxkb3UasGpZ0,19613 +tensorflow/include/external/local_config_python/python_include/cpython/objimpl.h,sha256=qctYb30BtDDCZ_VMPDGjqww1aC8BQJo2aksf0V04RKI,3356 +tensorflow/include/external/local_config_python/python_include/cpython/odictobject.h,sha256=_ysNd66occHt1vYyCUif5wx8EdTanD4vbvaFjNsASg0,1299 +tensorflow/include/external/local_config_python/python_include/cpython/picklebufobject.h,sha256=2j3VYmFQqk4ApKAZm6pYK025uTYkEqRPmsIMqAsAhso,846 +tensorflow/include/external/local_config_python/python_include/cpython/pyctype.h,sha256=ELXMvCEP0oMunDSEmjlS6Nt18AFq3YkYg1ix2mqPPbs,1387 +tensorflow/include/external/local_config_python/python_include/cpython/pydebug.h,sha256=hy-ZqL1NA9nt86LVOaE3gQdJwE7jbaUxCI04I_dOjgE,1093 +tensorflow/include/external/local_config_python/python_include/cpython/pyerrors.h,sha256=as1mLSUvRDGV6ukr0DTW4xitwPzYzTx1iu0mJsdyaKk,5476 +tensorflow/include/external/local_config_python/python_include/cpython/pyfpe.h,sha256=6nv6fYkaC1Ny2LQKV9G0ZreCQpblw_jVCxp83ghEKbc,444 +tensorflow/include/external/local_config_python/python_include/cpython/pylifecycle.h,sha256=F_TEGYshUQqJ_veC7O-quK_oxkgSZ0zK9N9WP88xoiI,2095 +tensorflow/include/external/local_config_python/python_include/cpython/pymem.h,sha256=ijeVqTULEFSOitbTfa1pviq9OHCnUeZ_qjKhmgkGCNs,3379 +tensorflow/include/external/local_config_python/python_include/cpython/pystate.h,sha256=hzgesd4aIHUUSWsdfHoO1HfI3C9WnCLa_ne6i8qVP5s,11914 +tensorflow/include/external/local_config_python/python_include/cpython/pythonrun.h,sha256=2prI7CrlrJcMpgehd5wMtRmy-meZKnAXFokZH_pL_Iw,4811 +tensorflow/include/external/local_config_python/python_include/cpython/pytime.h,sha256=R7kjjZjCY0reb5p9k9Pmvno2NPeDwLWxkYwk6qclDQ0,9196 +tensorflow/include/external/local_config_python/python_include/cpython/sysmodule.h,sha256=_TGScAG4zDI-gujSUm1fAigjqrrjiFNoKI4fWepHH0A,506 +tensorflow/include/external/local_config_python/python_include/cpython/traceback.h,sha256=DguJzE6HM_I9B8Pkboe1PkrMx8J0ce1_mXyTs7ObhPw,404 +tensorflow/include/external/local_config_python/python_include/cpython/tupleobject.h,sha256=y9C2biA0zI0uXTrKshvXM5yOakBG6pfWc2Em_xos9SE,975 +tensorflow/include/external/local_config_python/python_include/cpython/unicodeobject.h,sha256=IRtuBeOKmV2bti3plWZgeg0qNrM2V6lHdlYODdxNb6k,44284 +tensorflow/include/external/local_config_python/python_include/datetime.h,sha256=fNc3EjUQ9d3DNMwlUMgyvR7MG-c7R-RvTEpcPMuawfU,9635 +tensorflow/include/external/local_config_python/python_include/descrobject.h,sha256=RLTr6br1syX7eZRvm60wgMdzhjWbES8DR28dGFT3sA8,3002 +tensorflow/include/external/local_config_python/python_include/dictobject.h,sha256=TOGCj-_jlHDfAfVPOrG8pnnM1ywZ6_7Oa1U2j7qWrC0,3853 +tensorflow/include/external/local_config_python/python_include/dynamic_annotations.h,sha256=PkNm99CCg1BJcwNY0nelrXpg4W0WAfViLwoEWjfBUqw,22471 +tensorflow/include/external/local_config_python/python_include/enumobject.h,sha256=IkT-JQ25mVBo_nTc4OI_1wwSsD_ZR1HZi3c76PZIlrY,253 +tensorflow/include/external/local_config_python/python_include/errcode.h,sha256=aFeGdx_MQWy6fzxR5NXkKvCIsp0o_mZhpLesZ9sn2bQ,1700 +tensorflow/include/external/local_config_python/python_include/eval.h,sha256=iucAD_KwgB6L4a83TNt66n_OQlF8l91-_0CGHMcHxMo,831 +tensorflow/include/external/local_config_python/python_include/exports.h,sha256=-SQt6PcxhGFk1ERnRd0qc3zN-D91QJkBjtyQSFsc1EU,1098 +tensorflow/include/external/local_config_python/python_include/fileobject.h,sha256=TImTdybmww1iw2G0hWei3hwFM-fciuj4BdmTmELQCnw,1571 +tensorflow/include/external/local_config_python/python_include/fileutils.h,sha256=lcZa-CONLe3AP9_FW_MNsEQtuOfCHm2icFSMAzZeAnQ,508 +tensorflow/include/external/local_config_python/python_include/floatobject.h,sha256=IL9QfPh_KzV08b0f_Yc-P8Z0HMCJG5T9vPQje9NLP2s,4360 +tensorflow/include/external/local_config_python/python_include/frameobject.h,sha256=tp7-ZjbwXnnlC1ofRuPtJgKsXV7an7V6LVjUzcme37c,337 +tensorflow/include/external/local_config_python/python_include/funcobject.h,sha256=9vCPUP2DoNLQ0vftS4VZkOEBgTMx-dKooq7is-WfqrE,4257 +tensorflow/include/external/local_config_python/python_include/genericaliasobject.h,sha256=DlOgsYwRS-aOzOqf_R3Vd-IEsfCtpNOu3I5-4MgPx_g,334 +tensorflow/include/external/local_config_python/python_include/genobject.h,sha256=B48w3EKSlEZiXG6LyZU5LFgiSJc3epRQYPslJ3BFdq0,3347 +tensorflow/include/external/local_config_python/python_include/import.h,sha256=8ypNQWz1WNSdeX-NZ9kHiRcljtWvHapzR1XIviyMdrI,3026 +tensorflow/include/external/local_config_python/python_include/internal/pycore_abstract.h,sha256=rEdNvA5SKltZz_JcUPAut1sIv2C5BW2Evf0G1yAumvM,479 +tensorflow/include/external/local_config_python/python_include/internal/pycore_accu.h,sha256=CvXPBI9RVkbWhWa9h4bpc8RaUB8jeC2Alh45CxFq2ys,1126 +tensorflow/include/external/local_config_python/python_include/internal/pycore_asdl.h,sha256=CbsyPgpGWP_Vt-4fnv7HTE7BjK3Ol6dshj310fsuJVk,2971 +tensorflow/include/external/local_config_python/python_include/internal/pycore_ast.h,sha256=PcxGdxBluzIscbPhMyZ1YWwl4R3NGf12YGuFZDZx0WE,28828 +tensorflow/include/external/local_config_python/python_include/internal/pycore_ast_state.h,sha256=VKcLOa0zKSmDuytigX6h2bnSNXOCucbg8-dOiELlTJo,6457 +tensorflow/include/external/local_config_python/python_include/internal/pycore_atomic.h,sha256=lecRjnma0_qvyOWKKbLR8aS7lOGqwyc-BC83n44S1OY,16979 +tensorflow/include/external/local_config_python/python_include/internal/pycore_atomic_funcs.h,sha256=nVz6E62GOgzBsKsGhhwfjPvcfXMLnEYD5Xd6YIJj05k,2438 +tensorflow/include/external/local_config_python/python_include/internal/pycore_bitutils.h,sha256=ieTeeQfZSdydSMSpGb_aqrQp6euCyDKe3kGxmBJdvfM,5271 +tensorflow/include/external/local_config_python/python_include/internal/pycore_blocks_output_buffer.h,sha256=A_7VBU0NeONxHnOZXkhP77gUlcBjpbnvVVwDldf8Hrw,8688 +tensorflow/include/external/local_config_python/python_include/internal/pycore_bytes_methods.h,sha256=FTQybb8Cfpu0cr5cz4uC-rSPMoLMf2phYpuAH8gK_AA,3384 +tensorflow/include/external/local_config_python/python_include/internal/pycore_call.h,sha256=mcoZ7iZ7E47TQSUFQT08JSzaiwScQsx_b3OV0rQ4uuY,870 +tensorflow/include/external/local_config_python/python_include/internal/pycore_ceval.h,sha256=pKGPXnIfZQvPgTvVkw8ezBT8gBSIu1A5wlDhAeiVGwE,3484 +tensorflow/include/external/local_config_python/python_include/internal/pycore_code.h,sha256=RhBk4WbdJ4_VJ-C9YhXNBNKKv50sosnSPKCYQl_4BqE,696 +tensorflow/include/external/local_config_python/python_include/internal/pycore_compile.h,sha256=IVBrwAywSolhgUHHbjG4McD6_a3kI8PlJzuYVg4KbXI,1045 +tensorflow/include/external/local_config_python/python_include/internal/pycore_condvar.h,sha256=PTfhc5BSAiqNEgCW_8hSHimkqTDDOacOMV2t4_rdYvU,2809 +tensorflow/include/external/local_config_python/python_include/internal/pycore_context.h,sha256=2LE45o4JZ4Fn3Z5hXwNoZdo4gNbkI-oIf3uH5pqCjL0,822 +tensorflow/include/external/local_config_python/python_include/internal/pycore_dtoa.h,sha256=-5RYSETcgaf4CTEZzIEZeQ0xxXxT57pGLWyeR8zebYY,646 +tensorflow/include/external/local_config_python/python_include/internal/pycore_fileutils.h,sha256=9Scz2YlhVW3pGQ3_LI9UU7zRbLAROzuTol4b-Z5olh8,1704 +tensorflow/include/external/local_config_python/python_include/internal/pycore_format.h,sha256=JTzHfm0RuiDSl4E-BkZQ-pZbNlPxUL2F-AW5TbXzqY0,480 +tensorflow/include/external/local_config_python/python_include/internal/pycore_gc.h,sha256=zTgKiiZJ1pgKW9kS06zD2U7ry6XRNQrK4mFn5DxgZis,6859 +tensorflow/include/external/local_config_python/python_include/internal/pycore_getopt.h,sha256=6TOTBntmtVewMA4FwQ7pBNS-VMrfshTFMoqSJa0ZlFI,490 +tensorflow/include/external/local_config_python/python_include/internal/pycore_gil.h,sha256=z0VarNVlHltDVH6-absyTquEI42SZl31PB3zJDS9DZs,1565 +tensorflow/include/external/local_config_python/python_include/internal/pycore_hamt.h,sha256=pWUJcrdrBaQxlCGlEiSTMQ8KY73O56BooMV_eavdVfQ,3697 +tensorflow/include/external/local_config_python/python_include/internal/pycore_hashtable.h,sha256=dekDSG1rbgRodwprw4ldi5QjwbZGFOOLKaHWWh1b_fc,4197 +tensorflow/include/external/local_config_python/python_include/internal/pycore_import.h,sha256=H4T-8cMTfysSJIXPKl98U-skeVziZjG2Pr0jnCOa9gs,346 +tensorflow/include/external/local_config_python/python_include/internal/pycore_initconfig.h,sha256=d_bP7G01ojGAsKV5SJPkl5Dxcectl8bXnAV55OoRFV8,5625 +tensorflow/include/external/local_config_python/python_include/internal/pycore_interp.h,sha256=-p7bHh3qWwU20TLQN50-rW9D1cG-jPIQXbqtO6SmewQ,9289 +tensorflow/include/external/local_config_python/python_include/internal/pycore_list.h,sha256=-VMdZQPbdxFmU47FPGmyZfD-Chbo9-4akJANa82X4eI,350 +tensorflow/include/external/local_config_python/python_include/internal/pycore_long.h,sha256=udYcflXKdSn44-iCVzCs8sHJzDPM-5c8HEQOkhWutFQ,2589 +tensorflow/include/external/local_config_python/python_include/internal/pycore_moduleobject.h,sha256=v9ydYPeSwYD93BjgGQbEQqidRkLnltuXiJYNhjmoIgU,1047 +tensorflow/include/external/local_config_python/python_include/internal/pycore_object.h,sha256=VefprmaMfTjPbn3OtMZBEGt6-YaLvctdy8ROxoFfuio,5989 +tensorflow/include/external/local_config_python/python_include/internal/pycore_parser.h,sha256=BSYFVus5dKhD70Uo8LLSh_4CcSYNQKkBE5_KWEBYVAk,626 +tensorflow/include/external/local_config_python/python_include/internal/pycore_pathconfig.h,sha256=tJHkDeDDwbe0GJDuUj3gQKYrcRSud2YEF6qOzPwCID8,1981 +tensorflow/include/external/local_config_python/python_include/internal/pycore_pyarena.h,sha256=1PTlE7rnj_mF9Rykj7fRpNVwVcWTk6HrZh5V5uw7ph8,2733 +tensorflow/include/external/local_config_python/python_include/internal/pycore_pyerrors.h,sha256=a0mfqFI3qtb9NQtCpy__8IcN4j5bE2URPKtJU4FZLfk,2314 +tensorflow/include/external/local_config_python/python_include/internal/pycore_pyhash.h,sha256=bp250-fXJFsQ4zWYuZX8m1GzlSzhciWDDQJIxvpi3VE,206 +tensorflow/include/external/local_config_python/python_include/internal/pycore_pylifecycle.h,sha256=bg-He9MvuT74gmtWl0yeAbVEY_tPOmHGiH4_lNILXHQ,4940 +tensorflow/include/external/local_config_python/python_include/internal/pycore_pymem.h,sha256=xbW0uDebj6a3uar5OK_ISNcOQk8B6u-P4PzUk_gG-us,3211 +tensorflow/include/external/local_config_python/python_include/internal/pycore_pystate.h,sha256=MsG3RjiigJ0_3BiJuSehXRP3HIfhQoAjtI8NxoTvIr4,3938 +tensorflow/include/external/local_config_python/python_include/internal/pycore_runtime.h,sha256=FCrjnVt0iK6Kv0gDb5gXkUta_0OSTHAmQFSngA0TNbw,4902 +tensorflow/include/external/local_config_python/python_include/internal/pycore_structseq.h,sha256=IZmvx54Te-NRUPTgb6L42fQsy-pWvNaNXz7MaioUZg4,386 +tensorflow/include/external/local_config_python/python_include/internal/pycore_symtable.h,sha256=UUwwDFznMrto9yB-UConJtRw1LfVJlrvC8sj9p3aWwY,5578 +tensorflow/include/external/local_config_python/python_include/internal/pycore_sysmodule.h,sha256=CRcwgo1rYCk3VvntX3ALt35_JBn2sFyfwPLgJwhhf7U,548 +tensorflow/include/external/local_config_python/python_include/internal/pycore_traceback.h,sha256=1cdlebiEcIae5ba_M4xdq7P3yuh0H88_XA4eBe79nio,2970 +tensorflow/include/external/local_config_python/python_include/internal/pycore_tuple.h,sha256=f0TRfQ2VAChMcWfJRV5ZfzxbfXEronzo62ltgv1dis0,425 +tensorflow/include/external/local_config_python/python_include/internal/pycore_ucnhash.h,sha256=bZB36HVwPl232vKTpsfqPUPR7oTewTepUPF6Juk0jrU,898 +tensorflow/include/external/local_config_python/python_include/internal/pycore_unionobject.h,sha256=jsVYaj_6xYwwBtInrk6YaKXor9XNvry4SyZXDKAJfdY,629 +tensorflow/include/external/local_config_python/python_include/internal/pycore_warnings.h,sha256=u5dxeyMEf1eIcIrvcis8j3Yaj_GRpRR2gdrBjvZgRZU,633 +tensorflow/include/external/local_config_python/python_include/interpreteridobject.h,sha256=YtBgeU90iPNlQC24He09WIttd1nrDekZQyn9Aak3TPY,334 +tensorflow/include/external/local_config_python/python_include/intrcheck.h,sha256=aW_hdhjFeajLqtm4YXX2DUPqC56KqqHWWtJW1T3BY8E,772 +tensorflow/include/external/local_config_python/python_include/iterobject.h,sha256=-rdODyos0YX4Rq3jJHseNIue1bcvh1zsf_b5Do8WfcM,593 +tensorflow/include/external/local_config_python/python_include/listobject.h,sha256=_qJaw6XY8LhnjNd-unPPnDeXSQokweZYW_JVmCq0jCM,1781 +tensorflow/include/external/local_config_python/python_include/longintrepr.h,sha256=KN3cny1ds-OD0ekhp3Mb3_aD7DlLj9M09suhQkHV0kQ,3799 +tensorflow/include/external/local_config_python/python_include/longobject.h,sha256=cVkng4miorydJ92N70SADG-_lmWC0RICHBnVxCeLA6o,8606 +tensorflow/include/external/local_config_python/python_include/marshal.h,sha256=BrpqaBVPhZUXlFKUZaB-B0RPuFJEAFmjmMmDRABKJ_U,803 +tensorflow/include/external/local_config_python/python_include/memoryobject.h,sha256=WolJHNh5_ZC6IFJccQx04njSQy2nic5sYI7kxlkgzUg,2764 +tensorflow/include/external/local_config_python/python_include/methodobject.h,sha256=9LdPmXChB33yW3k0nK6QziZJlzanyulhL-MmFeOFLG8,4147 +tensorflow/include/external/local_config_python/python_include/modsupport.h,sha256=cYwDSRKvh_dCpYeGPxzzhKPGvGmn2AKIsySsxM3-qQE,10333 +tensorflow/include/external/local_config_python/python_include/moduleobject.h,sha256=HFO9ZiCZwBUkJYGhwclnhEVab1vg5nP1aadzSphBpi4,2458 +tensorflow/include/external/local_config_python/python_include/namespaceobject.h,sha256=0oLW0MZJP1aSHAOb-iP9OLxKZD67ms4HEI2bFwkA-8g,349 +tensorflow/include/external/local_config_python/python_include/object.h,sha256=zPnOkmHSj7u7y1w2XhDkZ8Op3wvfQI-USdcTOJxx4Ks,28344 +tensorflow/include/external/local_config_python/python_include/objimpl.h,sha256=I18oU8chv6lSqYRSlhyhrVIA2hCy12sCaifkX7EVk8I,8445 +tensorflow/include/external/local_config_python/python_include/opcode.h,sha256=gxp4F28eKFpPN70RJTun4ohwlW2Pxd8y0oHy3_iMXgc,5509 +tensorflow/include/external/local_config_python/python_include/osdefs.h,sha256=g3LpxQeUmojtPK1f0KgwGQ1goWVemj9Z700IMsBqBBw,737 +tensorflow/include/external/local_config_python/python_include/osmodule.h,sha256=wBOTW0j0jKjOJJpNSCxV4_tvHP54bFoypXlpu3Snedk,291 +tensorflow/include/external/local_config_python/python_include/patchlevel.h,sha256=3F5kNaF3yabb8rO_a3xn1ec8iBvP-2Gpz5bbIjLKgOY,1301 +tensorflow/include/external/local_config_python/python_include/py_curses.h,sha256=GEmK4D7V-4GBWpjh3eiIyeDqHDj-rWx7NpjSWDU4x_Y,2474 +tensorflow/include/external/local_config_python/python_include/pycapsule.h,sha256=j-1064HoNyDKrjRgEd1t7tsUf9Riv5TmeerFBl36kqo,1725 +tensorflow/include/external/local_config_python/python_include/pyconfig.h,sha256=Xyt0siZTsEj0rtjPp4_VKELsHv0P5_D7agaNUKKGAhw,48747 +tensorflow/include/external/local_config_python/python_include/pydtrace.h,sha256=00KUg3LkbLASS6ExHOW6mUGDesihN6drWlMrygPGlug,2413 +tensorflow/include/external/local_config_python/python_include/pyerrors.h,sha256=KuZMVj5rAg73DcKa142rejK2B0yl0yTWC-_JKwknMNU,12426 +tensorflow/include/external/local_config_python/python_include/pyexpat.h,sha256=S94Fs7fW2_9bdWW3HvWaTOHnlqVJ0o7bTHWlyr0A_pY,2450 +tensorflow/include/external/local_config_python/python_include/pyframe.h,sha256=kvo5YjkinNUj43NJ-a5ujZkAYWmMXX4HcKRzzhWzkwQ,466 +tensorflow/include/external/local_config_python/python_include/pyhash.h,sha256=9nRoM0At7LomDZ2D-YERoAiN4_AL1E7iBbiRQAJ_YuM,4223 +tensorflow/include/external/local_config_python/python_include/pylifecycle.h,sha256=CzsZI0R9bhIk6ImU_gC2PuUHhtJTgyve6jMj25hfqZs,2080 +tensorflow/include/external/local_config_python/python_include/pymacconfig.h,sha256=BqKEzSzMy6whxaos5eodBdBKS15QOOXVXH-rJgqzDiw,2989 +tensorflow/include/external/local_config_python/python_include/pymacro.h,sha256=S-1JjwJVgwMb9x9f3ly1ieOvB0TnMUO2sHSEX_9R9-8,4920 +tensorflow/include/external/local_config_python/python_include/pymath.h,sha256=OULV7Zf8y2k9SzQv_j2_HOsBknpFZvtU87dI-5LjSKo,8313 +tensorflow/include/external/local_config_python/python_include/pymem.h,sha256=PiVswYnWjD_ApwSW4izzzZs0vpJbFXJAaZ-eOXycvTo,3891 +tensorflow/include/external/local_config_python/python_include/pyport.h,sha256=f4Zo116oPky7PBhzg7wDKruZpYXu1fZ3kaQYuccGU3c,31684 +tensorflow/include/external/local_config_python/python_include/pystate.h,sha256=aar-S0nby5adVq15WqyLl_TtSOojNnXYPgupNCMlQZc,5250 +tensorflow/include/external/local_config_python/python_include/pystrcmp.h,sha256=9AHYM4-27PXxJ2julc0JwmL4gLLuUiyjRLiQ29zeTIg,436 +tensorflow/include/external/local_config_python/python_include/pystrhex.h,sha256=IkL5Cpor8Toy8AFrsFaGkZPfBCMKzkaLRpsYAI9WoPk,849 +tensorflow/include/external/local_config_python/python_include/pystrtod.h,sha256=35ikkgRPVc8BbACP7zGB130T8YKLhGJbXLH0YOX17S8,1483 +tensorflow/include/external/local_config_python/python_include/pythonrun.h,sha256=Ck2-h5Ha5D-sq8KeiymNlb0NHaYV1szzFYtasDPwj7Q,1110 +tensorflow/include/external/local_config_python/python_include/pythread.h,sha256=9XjS0wBRuUdPNpFpCTCGZdUdPpZT9id0pijmWblp-NQ,5938 +tensorflow/include/external/local_config_python/python_include/rangeobject.h,sha256=65u7Mc9ij_qMRFKqfRNpQbPpPkPgTUS1HGi6CxbVY4E,628 +tensorflow/include/external/local_config_python/python_include/setobject.h,sha256=gi801iFKg4-dFf_rR7S7rksHJsuaoosakqsyEXXCYWE,3381 +tensorflow/include/external/local_config_python/python_include/sliceobject.h,sha256=MhWgLeWWc6lQuJQaAiRHTPC8ti9hfZr8QC8eF3E_nCg,2516 +tensorflow/include/external/local_config_python/python_include/structmember.h,sha256=inZmy8RArvsFIGFd1Qp3bDS5h71ngd1MLUCVDOtgOVA,2074 +tensorflow/include/external/local_config_python/python_include/structseq.h,sha256=0IyERmZGZgWZwvbQOvkL4G7o-fgTgKiR2eKoyOJ-Qwg,1390 +tensorflow/include/external/local_config_python/python_include/sysmodule.h,sha256=LBwh21yHBN4j0VgCUKMCQ8o6kk8U8R5LVDdqP__Y128,1242 +tensorflow/include/external/local_config_python/python_include/token.h,sha256=dUufU3gMAw9ysdCsEPE7idDaGtlVwHxOs7y8NAY0ewI,2669 +tensorflow/include/external/local_config_python/python_include/traceback.h,sha256=xtsoHZaGzxtolfdXSgUpEmO4Gqo_Nc0MqaLjIZpmm0U,584 +tensorflow/include/external/local_config_python/python_include/tracemalloc.h,sha256=Dl5TX7teZkALTcs9QE_1Mpca6WS0oRrEq7bXOZGtJP4,1114 +tensorflow/include/external/local_config_python/python_include/tupleobject.h,sha256=oGWa3Jvf_RmA_KA2s7nqvBqZVAQ1tuhX8HFxEFTrs-0,1614 +tensorflow/include/external/local_config_python/python_include/typeslots.h,sha256=pjh-PhSIHobhtxQzp2250O2Ks6Z74_r8ee28xE3Md-E,2460 +tensorflow/include/external/local_config_python/python_include/unicodeobject.h,sha256=maBpRFBngZHBEFxb_dU8qv16m_lq8MiU-sC3JRlJcuc,36148 +tensorflow/include/external/local_config_python/python_include/warnings.h,sha256=0HxbPUtfOwxlHh1CRM_nSU4xJ5Ls41aKUTTdgWm2HrI,1776 +tensorflow/include/external/local_config_python/python_include/weakrefobject.h,sha256=1kkgd50L35sWIOsZr6g30NdN8uB2gZuQqpWjqgo1wAk,2863 +tensorflow/include/external/local_config_rocm/rocm/rocm/rocm_config.h,sha256=wmuylasUCfCsNjRN2frz6vPRUOa1pFb2a1RXFKKfuLk,981 +tensorflow/include/external/ml_dtypes/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358 +tensorflow/include/external/ml_dtypes/_ml_dtypes_ext.so,sha256=QBV6ReZ1yQ9c_357cMLD9K9goaDQ89E0_freQ0HSIAU,3282120 +tensorflow/include/external/ml_dtypes/_virtual_includes/float8/ml_dtypes/include/float8.h,sha256=0nmPrU5kN1tWax3x17xEAxPksQJMoI8Szq0-qktz_3I,51353 +tensorflow/include/external/ml_dtypes/_virtual_includes/int4/ml_dtypes/include/int4.h,sha256=s6mXDDxrFpxBrC_UN19mjT_RtJLUi5EtiUFfoVIqj1A,8784 +tensorflow/include/external/ml_dtypes/include/float8.h,sha256=0nmPrU5kN1tWax3x17xEAxPksQJMoI8Szq0-qktz_3I,51353 +tensorflow/include/external/ml_dtypes/include/int4.h,sha256=s6mXDDxrFpxBrC_UN19mjT_RtJLUi5EtiUFfoVIqj1A,8784 +tensorflow/include/external/nccl_archive/LICENSE.txt,sha256=DwF0prTgszrCY3W_cpUzB1sy9MUaW2gCo9dC19zcmnY,1895 +tensorflow/include/external/nccl_archive/_virtual_includes/enqueue_clang/third_party/nccl/nccl.h,sha256=NN0gCA6nSgRhgTXVYMF7EJTT2TAj0ORZISB_06KVeYA,16583 +tensorflow/include/external/nccl_archive/_virtual_includes/include_hdrs/align.h,sha256=yTtynhe20dh1FMIImxSJfgz0Epdu0zQ-4RrSFrM5KhI,1100 +tensorflow/include/external/nccl_archive/_virtual_includes/include_hdrs/alloc.h,sha256=Tdk2Gp-FXQHqrzOzTfFFz1OMe2GkyZ1sA9nMHjteuUo,7371 +tensorflow/include/external/nccl_archive/_virtual_includes/include_hdrs/argcheck.h,sha256=m3BngCIewNGBarATsirLpXw1jixexoua6cSfSF0dX80,479 +tensorflow/include/external/nccl_archive/_virtual_includes/include_hdrs/bootstrap.h,sha256=-lyR6J-xwOpDmhvRtg08TA_FIctcNgJEdK242BxMdXk,1408 +tensorflow/include/external/nccl_archive/_virtual_includes/include_hdrs/channel.h,sha256=yFKzofQ-kXuTzd5by56FIT0gYSyW-NjABJDsBkwusgg,1865 +tensorflow/include/external/nccl_archive/_virtual_includes/include_hdrs/checks.h,sha256=WkMnkL6B3CYyCt3HSKyHzidjj_ZIUcWkEnJ0aNfSZRM,5566 +tensorflow/include/external/nccl_archive/_virtual_includes/include_hdrs/coll_net.h,sha256=ndd4nQpViLR1RrIrffNfhuoWHcb1mKDeULwiDfZgcqg,3364 +tensorflow/include/external/nccl_archive/_virtual_includes/include_hdrs/collectives.h,sha256=nVdTG1x9hjj5mW22Ivtv75GuKtRmtCpVf4bheWDlVxY,5144 +tensorflow/include/external/nccl_archive/_virtual_includes/include_hdrs/comm.h,sha256=edKKZTj1TBaSgnGwBEeZZh9QiH6HI_EQu53GDKDkGbc,12131 +tensorflow/include/external/nccl_archive/_virtual_includes/include_hdrs/core.h,sha256=cmlFsQRdJCQzBrJnKrKZSfGA6PGb8X5L3MqqqaVJFVk,1595 +tensorflow/include/external/nccl_archive/_virtual_includes/include_hdrs/cpuset.h,sha256=EoSa9oqNyOpjg4LmIhNWlsDrLAa7ur3mJfP8IlLenhs,1508 +tensorflow/include/external/nccl_archive/_virtual_includes/include_hdrs/cudawrap.h,sha256=zV0dJ1VpPbuB3SDXIE3iXX79VNXh2tt9pwTWPa8VxO8,3493 +tensorflow/include/external/nccl_archive/_virtual_includes/include_hdrs/debug.h,sha256=J_yCBIR4UuZGLG9q1ZknUneI6b5E5EjMWVMquJtFrxA,1572 +tensorflow/include/external/nccl_archive/_virtual_includes/include_hdrs/devcomm.h,sha256=ZwtHxY_-mvyC2KiOtF_oUV8q77eKxz7ojDTaAZY_PB8,8662 +tensorflow/include/external/nccl_archive/_virtual_includes/include_hdrs/enqueue.h,sha256=fXPu5TKUTi7sbccJuUHBjgRWjG4dc6ce7FIwzkPt9bU,1130 +tensorflow/include/external/nccl_archive/_virtual_includes/include_hdrs/gdrwrap.h,sha256=pLXbbAafDYFmdNKCisYgvdcc6yvYn-hBcbEf2ZsKRKM,8726 +tensorflow/include/external/nccl_archive/_virtual_includes/include_hdrs/graph.h,sha256=VxfSZDPlm_rQEp9F32VsScQs9pFvRsNSjcby_yI7rVQ,5050 +tensorflow/include/external/nccl_archive/_virtual_includes/include_hdrs/group.h,sha256=97jOv9tb_xnpXEwgrmQOB524-u96dVq2L0k6ONyxcAI,3807 +tensorflow/include/external/nccl_archive/_virtual_includes/include_hdrs/ibvwrap.h,sha256=0aRpmoM4YAvxMJyp7mgq0YjKi2cb2yryTgpYZdAaQ6k,29711 +tensorflow/include/external/nccl_archive/_virtual_includes/include_hdrs/info.h,sha256=p2TxNE8Bqpo8YsM8EGebaa6Nzu66HxLTWqeOyEoA7FM,3281 +tensorflow/include/external/nccl_archive/_virtual_includes/include_hdrs/nccl_net.h,sha256=3jkTzjKwbKhq_jZwuEARl4NH0HO1BUIYJY_Ork94Myw,17126 +tensorflow/include/external/nccl_archive/_virtual_includes/include_hdrs/net.h,sha256=jTIb0yDigpMMel6DaC9eTXe7inJKUbn5Suv3Vt7n9xQ,3755 +tensorflow/include/external/nccl_archive/_virtual_includes/include_hdrs/nvmlwrap.h,sha256=kN7BGs9YuxAR16aemKt6a9B9dd286B2A_35W3kOUhwA,9400 +tensorflow/include/external/nccl_archive/_virtual_includes/include_hdrs/nvtx.h,sha256=32Y_6Bw1_l7IcTg6Zq9C7i1Aq1_idrgo8aHKA-lAHoQ,3150 +tensorflow/include/external/nccl_archive/_virtual_includes/include_hdrs/nvtx3.hpp,sha256=ocxoI1Qlxs35zT0MFyWhGU3VdJ-L9r9ZBC_VKI4fK3w,79942 +tensorflow/include/external/nccl_archive/_virtual_includes/include_hdrs/nvtx3/nvToolsExt.h,sha256=s85H0xuXias4U6UNvGCXehu5ZpomCE62KVraWXx4TAU,50660 +tensorflow/include/external/nccl_archive/_virtual_includes/include_hdrs/nvtx3/nvToolsExtCuda.h,sha256=PmYhPyd2wa6pJWXs6MK8lVsCVawRo04qrCSCMrF9gQ8,4617 +tensorflow/include/external/nccl_archive/_virtual_includes/include_hdrs/nvtx3/nvToolsExtCudaRt.h,sha256=XuIwHOiob8dEkiCAU8174cNi57O_sTo_LgOn3juGmtw,3806 +tensorflow/include/external/nccl_archive/_virtual_includes/include_hdrs/nvtx3/nvToolsExtOpenCL.h,sha256=8VwxO0SLbM_E9G80DZCUQNRjgeAR3omWBFbXFQXzP4M,6976 +tensorflow/include/external/nccl_archive/_virtual_includes/include_hdrs/nvtx3/nvToolsExtPayload.h,sha256=BYckphedBb92MtxG0C8p9R0pPNXSnZEDPB94CdH_eI4,26557 +tensorflow/include/external/nccl_archive/_virtual_includes/include_hdrs/nvtx3/nvToolsExtSync.h,sha256=qJOvuyng1PP1DhMAU-pghapzpMVXEqMi92frrjVWEAE,13169 +tensorflow/include/external/nccl_archive/_virtual_includes/include_hdrs/nvtx3/nvtxDetail/nvtxImpl.h,sha256=vANH5NyFnL-n7UQJVPV61XAy53bfEOpVWHs5vZsqvKA,21666 +tensorflow/include/external/nccl_archive/_virtual_includes/include_hdrs/nvtx3/nvtxDetail/nvtxImplCore.h,sha256=ofvo55SG9BCiIZMoL9ZU0YPp3CEeQ5sfPWc1oUesCyA,10011 +tensorflow/include/external/nccl_archive/_virtual_includes/include_hdrs/nvtx3/nvtxDetail/nvtxImplCudaRt_v3.h,sha256=xez577NoDKNeJichQThuOnaCwqf5VTF5DVCfq6aNiWM,3104 +tensorflow/include/external/nccl_archive/_virtual_includes/include_hdrs/nvtx3/nvtxDetail/nvtxImplCuda_v3.h,sha256=WmIizt4Z4CGBmjx46_pWsrW423O3i-4OyncTohjBfXg,3883 +tensorflow/include/external/nccl_archive/_virtual_includes/include_hdrs/nvtx3/nvtxDetail/nvtxImplOpenCL_v3.h,sha256=O65tDmFq7IWiFx1qxRVIip0p92EhcW4g2sTvmYxe51M,6608 +tensorflow/include/external/nccl_archive/_virtual_includes/include_hdrs/nvtx3/nvtxDetail/nvtxImplSync_v3.h,sha256=CMjKNf5sOTBwj59xpKbR9eWvEscDgGnUsVzg-4OBFeI,3355 +tensorflow/include/external/nccl_archive/_virtual_includes/include_hdrs/nvtx3/nvtxDetail/nvtxInit.h,sha256=RVo7LXO7Z5-oD41lGBdmydJ0xTCCYOkBvzwXmmiALE8,13049 +tensorflow/include/external/nccl_archive/_virtual_includes/include_hdrs/nvtx3/nvtxDetail/nvtxInitDecls.h,sha256=z7jF8oqQ0x-qmgwKjBNz5uz7MZHf84FrSgfKOTKVQHo,9616 +tensorflow/include/external/nccl_archive/_virtual_includes/include_hdrs/nvtx3/nvtxDetail/nvtxInitDefs.h,sha256=TpF8B6oW86PQzyDVp8RPT_nv01t1xCFK_QV71MgltnY,35687 +tensorflow/include/external/nccl_archive/_virtual_includes/include_hdrs/nvtx3/nvtxDetail/nvtxLinkOnce.h,sha256=b_pwTw-sSxuSnlH7hxwjZVWe_XJlypqtjoyu1ApE0W4,4118 +tensorflow/include/external/nccl_archive/_virtual_includes/include_hdrs/nvtx3/nvtxDetail/nvtxTypes.h,sha256=D0q101AnuosTf5VAGiUOmjtC3I1KGMJKLM-fJ--Fa7U,15765 +tensorflow/include/external/nccl_archive/_virtual_includes/include_hdrs/nvtx3/nvtxExtDetail/nvtxExtImpl.h,sha256=ruPxzv_JPIKGJCfZ7uEEOUBQEMEMYd9Fi7lb0xZMwHc,2184 +tensorflow/include/external/nccl_archive/_virtual_includes/include_hdrs/nvtx3/nvtxExtDetail/nvtxExtImplPayload_v1.h,sha256=3RG6_-_SMjarVxiyByLwJFy5LMN7NSEKoMeIUjziIio,3209 +tensorflow/include/external/nccl_archive/_virtual_includes/include_hdrs/nvtx3/nvtxExtDetail/nvtxExtInit.h,sha256=lFYrlAroaXOgcwyD-i3PpZz4zWcMZfdM8pk9RImrrVg,14867 +tensorflow/include/external/nccl_archive/_virtual_includes/include_hdrs/nvtx3/nvtxExtDetail/nvtxExtPayloadTypeInfo.h,sha256=o1wZU2-9vPHhMEOw4hyhQvK9yLilT1GRm-MCaLHKwoQ,5228 +tensorflow/include/external/nccl_archive/_virtual_includes/include_hdrs/nvtx3/nvtxExtDetail/nvtxExtTypes.h,sha256=CgMIUrFRId-RFiywH1Fjt0rVcZqqNIUNWNYHQvBjQQ0,1337 +tensorflow/include/external/nccl_archive/_virtual_includes/include_hdrs/p2p.h,sha256=AMQYA_O8JyDv5F6OSYkJAqP-BrVwG7o0mvfxAM3eWNM,335 +tensorflow/include/external/nccl_archive/_virtual_includes/include_hdrs/param.h,sha256=Any4z5EEzGBf035UL6ty1fcpLTchzQikrrx_RIeIWfI,981 +tensorflow/include/external/nccl_archive/_virtual_includes/include_hdrs/profiler.h,sha256=PMusc7JNQxkuNQmeACI6t9jKLuanns3jqbWcecZZ5T0,907 +tensorflow/include/external/nccl_archive/_virtual_includes/include_hdrs/proxy.h,sha256=zxHO_xJQrHV33-j9oe0z5FVH45ef0kI00hZA9USl05I,6089 +tensorflow/include/external/nccl_archive/_virtual_includes/include_hdrs/shm.h,sha256=BQnqLlkZReerCJm_Mf8sjvHfq0u_mzgnFD3qiYP5rAE,597 +tensorflow/include/external/nccl_archive/_virtual_includes/include_hdrs/socket.h,sha256=ZLE9yO-fScl_B-IOB6zIOENIWoMVh-WXyy6SgwlOfKg,3966 +tensorflow/include/external/nccl_archive/_virtual_includes/include_hdrs/strongstream.h,sha256=itEF_hTTAodZxy4zJAVpZf19aPB3YxkTJ6inKCVCg8I,5080 +tensorflow/include/external/nccl_archive/_virtual_includes/include_hdrs/timer.h,sha256=MZ8Y46zWkpV24ixN_6_KU7_v3N4FLmXgOxSnu8wqoGA,1611 +tensorflow/include/external/nccl_archive/_virtual_includes/include_hdrs/transport.h,sha256=IfkL7BjCiSscgjOFb7PZ1G3PqU36mdCShv8KiicNRC0,3037 +tensorflow/include/external/nccl_archive/_virtual_includes/include_hdrs/trees.h,sha256=jWvihShyxOo3a91fO6YIJG4buvMkwxxPSoiT5_QL4jY,574 +tensorflow/include/external/nccl_archive/_virtual_includes/include_hdrs/utils.h,sha256=g4WZDjTe1huPox9ce6TldnpMOtg4w9G9eShGroIH-FE,16631 +tensorflow/include/external/nccl_archive/_virtual_includes/nccl/third_party/nccl/nccl.h,sha256=NN0gCA6nSgRhgTXVYMF7EJTT2TAj0ORZISB_06KVeYA,16583 +tensorflow/include/external/nccl_archive/_virtual_includes/nccl_config/third_party/nccl/nccl_config.h,sha256=yvKgfkHqRL85Y7TgcRFo4xJiYvXZaiu1nvLj1Bs5AJQ,27 +tensorflow/include/external/nccl_archive/_virtual_includes/src_hdrs/include/collectives.h,sha256=nVdTG1x9hjj5mW22Ivtv75GuKtRmtCpVf4bheWDlVxY,5144 +tensorflow/include/external/nccl_archive/_virtual_includes/src_hdrs/nccl.h,sha256=NN0gCA6nSgRhgTXVYMF7EJTT2TAj0ORZISB_06KVeYA,16583 +tensorflow/include/external/nccl_archive/nccl_config.h,sha256=yvKgfkHqRL85Y7TgcRFo4xJiYvXZaiu1nvLj1Bs5AJQ,27 +tensorflow/include/external/nccl_archive/src/graph/rings.h,sha256=R8sdjIuMcVSpzJ9KJXZCEkfPmGqBZP61_hCWQxn8f8Y,358 +tensorflow/include/external/nccl_archive/src/graph/topo.h,sha256=luwZ9O7aoShXFFFVBT1mblJXo6i2Np8NYju53dJhbos,5832 +tensorflow/include/external/nccl_archive/src/graph/xml.h,sha256=sfdw3UgVGJXx2QlAQL26w_EGYPZzE95f5kc2PTQMm7M,9437 +tensorflow/include/external/nccl_archive/src/include/align.h,sha256=yTtynhe20dh1FMIImxSJfgz0Epdu0zQ-4RrSFrM5KhI,1100 +tensorflow/include/external/nccl_archive/src/include/alloc.h,sha256=Tdk2Gp-FXQHqrzOzTfFFz1OMe2GkyZ1sA9nMHjteuUo,7371 +tensorflow/include/external/nccl_archive/src/include/argcheck.h,sha256=m3BngCIewNGBarATsirLpXw1jixexoua6cSfSF0dX80,479 +tensorflow/include/external/nccl_archive/src/include/bootstrap.h,sha256=-lyR6J-xwOpDmhvRtg08TA_FIctcNgJEdK242BxMdXk,1408 +tensorflow/include/external/nccl_archive/src/include/channel.h,sha256=yFKzofQ-kXuTzd5by56FIT0gYSyW-NjABJDsBkwusgg,1865 +tensorflow/include/external/nccl_archive/src/include/checks.h,sha256=WkMnkL6B3CYyCt3HSKyHzidjj_ZIUcWkEnJ0aNfSZRM,5566 +tensorflow/include/external/nccl_archive/src/include/coll_net.h,sha256=ndd4nQpViLR1RrIrffNfhuoWHcb1mKDeULwiDfZgcqg,3364 +tensorflow/include/external/nccl_archive/src/include/collectives.h,sha256=nVdTG1x9hjj5mW22Ivtv75GuKtRmtCpVf4bheWDlVxY,5144 +tensorflow/include/external/nccl_archive/src/include/comm.h,sha256=edKKZTj1TBaSgnGwBEeZZh9QiH6HI_EQu53GDKDkGbc,12131 +tensorflow/include/external/nccl_archive/src/include/core.h,sha256=cmlFsQRdJCQzBrJnKrKZSfGA6PGb8X5L3MqqqaVJFVk,1595 +tensorflow/include/external/nccl_archive/src/include/cpuset.h,sha256=EoSa9oqNyOpjg4LmIhNWlsDrLAa7ur3mJfP8IlLenhs,1508 +tensorflow/include/external/nccl_archive/src/include/cudawrap.h,sha256=zV0dJ1VpPbuB3SDXIE3iXX79VNXh2tt9pwTWPa8VxO8,3493 +tensorflow/include/external/nccl_archive/src/include/debug.h,sha256=J_yCBIR4UuZGLG9q1ZknUneI6b5E5EjMWVMquJtFrxA,1572 +tensorflow/include/external/nccl_archive/src/include/devcomm.h,sha256=ZwtHxY_-mvyC2KiOtF_oUV8q77eKxz7ojDTaAZY_PB8,8662 +tensorflow/include/external/nccl_archive/src/include/enqueue.h,sha256=fXPu5TKUTi7sbccJuUHBjgRWjG4dc6ce7FIwzkPt9bU,1130 +tensorflow/include/external/nccl_archive/src/include/gdrwrap.h,sha256=pLXbbAafDYFmdNKCisYgvdcc6yvYn-hBcbEf2ZsKRKM,8726 +tensorflow/include/external/nccl_archive/src/include/graph.h,sha256=VxfSZDPlm_rQEp9F32VsScQs9pFvRsNSjcby_yI7rVQ,5050 +tensorflow/include/external/nccl_archive/src/include/group.h,sha256=97jOv9tb_xnpXEwgrmQOB524-u96dVq2L0k6ONyxcAI,3807 +tensorflow/include/external/nccl_archive/src/include/ibvwrap.h,sha256=0aRpmoM4YAvxMJyp7mgq0YjKi2cb2yryTgpYZdAaQ6k,29711 +tensorflow/include/external/nccl_archive/src/include/info.h,sha256=p2TxNE8Bqpo8YsM8EGebaa6Nzu66HxLTWqeOyEoA7FM,3281 +tensorflow/include/external/nccl_archive/src/include/nccl_net.h,sha256=3jkTzjKwbKhq_jZwuEARl4NH0HO1BUIYJY_Ork94Myw,17126 +tensorflow/include/external/nccl_archive/src/include/net.h,sha256=jTIb0yDigpMMel6DaC9eTXe7inJKUbn5Suv3Vt7n9xQ,3755 +tensorflow/include/external/nccl_archive/src/include/nvmlwrap.h,sha256=kN7BGs9YuxAR16aemKt6a9B9dd286B2A_35W3kOUhwA,9400 +tensorflow/include/external/nccl_archive/src/include/nvtx.h,sha256=32Y_6Bw1_l7IcTg6Zq9C7i1Aq1_idrgo8aHKA-lAHoQ,3150 +tensorflow/include/external/nccl_archive/src/include/nvtx3.hpp,sha256=ocxoI1Qlxs35zT0MFyWhGU3VdJ-L9r9ZBC_VKI4fK3w,79942 +tensorflow/include/external/nccl_archive/src/include/nvtx3/nvToolsExt.h,sha256=s85H0xuXias4U6UNvGCXehu5ZpomCE62KVraWXx4TAU,50660 +tensorflow/include/external/nccl_archive/src/include/nvtx3/nvToolsExtCuda.h,sha256=PmYhPyd2wa6pJWXs6MK8lVsCVawRo04qrCSCMrF9gQ8,4617 +tensorflow/include/external/nccl_archive/src/include/nvtx3/nvToolsExtCudaRt.h,sha256=XuIwHOiob8dEkiCAU8174cNi57O_sTo_LgOn3juGmtw,3806 +tensorflow/include/external/nccl_archive/src/include/nvtx3/nvToolsExtOpenCL.h,sha256=8VwxO0SLbM_E9G80DZCUQNRjgeAR3omWBFbXFQXzP4M,6976 +tensorflow/include/external/nccl_archive/src/include/nvtx3/nvToolsExtPayload.h,sha256=BYckphedBb92MtxG0C8p9R0pPNXSnZEDPB94CdH_eI4,26557 +tensorflow/include/external/nccl_archive/src/include/nvtx3/nvToolsExtSync.h,sha256=qJOvuyng1PP1DhMAU-pghapzpMVXEqMi92frrjVWEAE,13169 +tensorflow/include/external/nccl_archive/src/include/nvtx3/nvtxDetail/nvtxImpl.h,sha256=vANH5NyFnL-n7UQJVPV61XAy53bfEOpVWHs5vZsqvKA,21666 +tensorflow/include/external/nccl_archive/src/include/nvtx3/nvtxDetail/nvtxImplCore.h,sha256=ofvo55SG9BCiIZMoL9ZU0YPp3CEeQ5sfPWc1oUesCyA,10011 +tensorflow/include/external/nccl_archive/src/include/nvtx3/nvtxDetail/nvtxImplCudaRt_v3.h,sha256=xez577NoDKNeJichQThuOnaCwqf5VTF5DVCfq6aNiWM,3104 +tensorflow/include/external/nccl_archive/src/include/nvtx3/nvtxDetail/nvtxImplCuda_v3.h,sha256=WmIizt4Z4CGBmjx46_pWsrW423O3i-4OyncTohjBfXg,3883 +tensorflow/include/external/nccl_archive/src/include/nvtx3/nvtxDetail/nvtxImplOpenCL_v3.h,sha256=O65tDmFq7IWiFx1qxRVIip0p92EhcW4g2sTvmYxe51M,6608 +tensorflow/include/external/nccl_archive/src/include/nvtx3/nvtxDetail/nvtxImplSync_v3.h,sha256=CMjKNf5sOTBwj59xpKbR9eWvEscDgGnUsVzg-4OBFeI,3355 +tensorflow/include/external/nccl_archive/src/include/nvtx3/nvtxDetail/nvtxInit.h,sha256=RVo7LXO7Z5-oD41lGBdmydJ0xTCCYOkBvzwXmmiALE8,13049 +tensorflow/include/external/nccl_archive/src/include/nvtx3/nvtxDetail/nvtxInitDecls.h,sha256=z7jF8oqQ0x-qmgwKjBNz5uz7MZHf84FrSgfKOTKVQHo,9616 +tensorflow/include/external/nccl_archive/src/include/nvtx3/nvtxDetail/nvtxInitDefs.h,sha256=TpF8B6oW86PQzyDVp8RPT_nv01t1xCFK_QV71MgltnY,35687 +tensorflow/include/external/nccl_archive/src/include/nvtx3/nvtxDetail/nvtxLinkOnce.h,sha256=b_pwTw-sSxuSnlH7hxwjZVWe_XJlypqtjoyu1ApE0W4,4118 +tensorflow/include/external/nccl_archive/src/include/nvtx3/nvtxDetail/nvtxTypes.h,sha256=D0q101AnuosTf5VAGiUOmjtC3I1KGMJKLM-fJ--Fa7U,15765 +tensorflow/include/external/nccl_archive/src/include/nvtx3/nvtxExtDetail/nvtxExtImpl.h,sha256=ruPxzv_JPIKGJCfZ7uEEOUBQEMEMYd9Fi7lb0xZMwHc,2184 +tensorflow/include/external/nccl_archive/src/include/nvtx3/nvtxExtDetail/nvtxExtImplPayload_v1.h,sha256=3RG6_-_SMjarVxiyByLwJFy5LMN7NSEKoMeIUjziIio,3209 +tensorflow/include/external/nccl_archive/src/include/nvtx3/nvtxExtDetail/nvtxExtInit.h,sha256=lFYrlAroaXOgcwyD-i3PpZz4zWcMZfdM8pk9RImrrVg,14867 +tensorflow/include/external/nccl_archive/src/include/nvtx3/nvtxExtDetail/nvtxExtPayloadTypeInfo.h,sha256=o1wZU2-9vPHhMEOw4hyhQvK9yLilT1GRm-MCaLHKwoQ,5228 +tensorflow/include/external/nccl_archive/src/include/nvtx3/nvtxExtDetail/nvtxExtTypes.h,sha256=CgMIUrFRId-RFiywH1Fjt0rVcZqqNIUNWNYHQvBjQQ0,1337 +tensorflow/include/external/nccl_archive/src/include/p2p.h,sha256=AMQYA_O8JyDv5F6OSYkJAqP-BrVwG7o0mvfxAM3eWNM,335 +tensorflow/include/external/nccl_archive/src/include/param.h,sha256=Any4z5EEzGBf035UL6ty1fcpLTchzQikrrx_RIeIWfI,981 +tensorflow/include/external/nccl_archive/src/include/profiler.h,sha256=PMusc7JNQxkuNQmeACI6t9jKLuanns3jqbWcecZZ5T0,907 +tensorflow/include/external/nccl_archive/src/include/proxy.h,sha256=zxHO_xJQrHV33-j9oe0z5FVH45ef0kI00hZA9USl05I,6089 +tensorflow/include/external/nccl_archive/src/include/shm.h,sha256=BQnqLlkZReerCJm_Mf8sjvHfq0u_mzgnFD3qiYP5rAE,597 +tensorflow/include/external/nccl_archive/src/include/socket.h,sha256=ZLE9yO-fScl_B-IOB6zIOENIWoMVh-WXyy6SgwlOfKg,3966 +tensorflow/include/external/nccl_archive/src/include/strongstream.h,sha256=itEF_hTTAodZxy4zJAVpZf19aPB3YxkTJ6inKCVCg8I,5080 +tensorflow/include/external/nccl_archive/src/include/timer.h,sha256=MZ8Y46zWkpV24ixN_6_KU7_v3N4FLmXgOxSnu8wqoGA,1611 +tensorflow/include/external/nccl_archive/src/include/transport.h,sha256=IfkL7BjCiSscgjOFb7PZ1G3PqU36mdCShv8KiicNRC0,3037 +tensorflow/include/external/nccl_archive/src/include/trees.h,sha256=jWvihShyxOo3a91fO6YIJG4buvMkwxxPSoiT5_QL4jY,574 +tensorflow/include/external/nccl_archive/src/include/utils.h,sha256=g4WZDjTe1huPox9ce6TldnpMOtg4w9G9eShGroIH-FE,16631 +tensorflow/include/external/nccl_archive/src/nccl.h,sha256=NN0gCA6nSgRhgTXVYMF7EJTT2TAj0ORZISB_06KVeYA,16583 +tensorflow/include/external/nsync/internal/common.h,sha256=vDJu4ki9wqeJFvdKEvgTd5nvQ0fhVQe2Ax8tWesE694,12944 +tensorflow/include/external/nsync/internal/dll.h,sha256=tHrkiyW3pbCXWjHWiXDwZ4jNZFW6CWoGI-BdmYWJyAg,3243 +tensorflow/include/external/nsync/internal/headers.h,sha256=HQlukrkbixi3ihDKpNgDEqc6MasOIqAVYlcQeZD3fLQ,826 +tensorflow/include/external/nsync/internal/sem.h,sha256=Rl3rBLBwLctjLvtrCvyXIid98-8LCOr9Wkxioy3QE8M,1477 +tensorflow/include/external/nsync/internal/wait_internal.h,sha256=cfM92QWCfP8qX4m_KwmLqeFRh3FMv5EdSTF26fXb0VQ,1445 +tensorflow/include/external/nsync/platform/aarch64/cputype.h,sha256=1ucwLXHmght2g_MsFoMm4-3nL8eEnLV8NUiMiRsFjZ4,741 +tensorflow/include/external/nsync/platform/alpha/cputype.h,sha256=WwG8u28uYVoq1bt6P4jeIPiTYqmdvdxCgPCuhYUfd_A,735 +tensorflow/include/external/nsync/platform/arm/cputype.h,sha256=LHv447-W8sWIF-EABlDfgR8GPRdeEsfTMjiCTuhzxeE,729 +tensorflow/include/external/nsync/platform/atomic_ind/atomic.h,sha256=SEDEih7GJfhRyxRMAiA232CCo0AGhR-Zjc_CRzreGVg,3595 +tensorflow/include/external/nsync/platform/c++11.futex/platform.h,sha256=GqsDJ_lS7pYzp1Cs3qBnNDhwceUL2AHbZ2jLT5X5Juo,993 +tensorflow/include/external/nsync/platform/c++11/atomic.h,sha256=XgvaSfvIYCvtpK_b7itb7S7CWsj1vB_4cdTPyi_yZKA,4523 +tensorflow/include/external/nsync/platform/c++11/platform.h,sha256=-uFXm6B6HhG-8tXJMGlyNI88MTdPOgYqA3GdoWciJ1Q,5842 +tensorflow/include/external/nsync/platform/c11/atomic.h,sha256=rdyYRtiYlGSBxVgHRmVc3gQfewvhFiaY9-DnEkdOmmY,4513 +tensorflow/include/external/nsync/platform/clang/atomic.h,sha256=LxqfNXy7eRM6FlKZ-G6ir3EQOBGL5V63g7Jp1ZEBRL8,722 +tensorflow/include/external/nsync/platform/clang/compiler.h,sha256=IbiAhRbDtMfjq8m1UEMXFsakNUCVbcTYQ9ioQPH9P3Y,824 +tensorflow/include/external/nsync/platform/cygwin/platform.h,sha256=NxzVwUjB69WiY1i9w_ss3qoYKEoHjJUY3YugTn3ifs0,961 +tensorflow/include/external/nsync/platform/decc/compiler.h,sha256=ClovlKSBXA7lcdIJowPAOY_vaGpR5DOs2b9Q00W6t6g,807 +tensorflow/include/external/nsync/platform/freebsd/platform.h,sha256=KAj4ZBy6MwQHlrnyqNsQPTgR-9lxR44cL7yb45nIuJ8,952 +tensorflow/include/external/nsync/platform/gcc/atomic.h,sha256=eanUMqs-WX6DK5RgPnAQbu4vrqlIlg_BDlx2ELRtvQg,2832 +tensorflow/include/external/nsync/platform/gcc/compiler.h,sha256=_bS1sJBZx2trI2Gd0qbx2lo0KL-AI-S2cwvKT5L-Qto,818 +tensorflow/include/external/nsync/platform/gcc_new/atomic.h,sha256=78qD8RAV8q93tE3yEe3pSjeCUC-8ktOiKJnAKAfgfZI,4373 +tensorflow/include/external/nsync/platform/gcc_new_debug/atomic.h,sha256=NZEhQki34Xm-cCbLMjP_nUq1C8hwVPOGswbdQF4xD14,5108 +tensorflow/include/external/nsync/platform/gcc_no_tls/compiler.h,sha256=piJfVrLeuK4xZKSUThAG4Q6TErRumfl_PUL0LFOTako,830 +tensorflow/include/external/nsync/platform/gcc_old/atomic.h,sha256=XwooLL2Cey1LVPSU5z_pPSGgAkUSPozyXBVe4614gOE,3880 +tensorflow/include/external/nsync/platform/lcc/compiler.h,sha256=CRkWwJpM74wtjCrsPA9glKSo_2IjbjJo2d-Sp43NRuw,776 +tensorflow/include/external/nsync/platform/lcc/nsync_time_init.h,sha256=sxrGy-aUZ_urIlyKvatsEjIdbF83xGfPR5BRbgEJ3nQ,900 +tensorflow/include/external/nsync/platform/linux/platform.h,sha256=sawyRtkZSRpHOXEwBFaQ_blpjHdW5pSwXD1xzYVeAJk,1068 +tensorflow/include/external/nsync/platform/macos/atomic.h,sha256=EKeLrqddslYT0fd6vYugJcXA2DZEu_GIo42sTsZ7Lcc,4077 +tensorflow/include/external/nsync/platform/macos/platform.h,sha256=XPpsMAs6kJn_usfkQw89UqdNMVlXwQs5-Sh37g9AYEc,1223 +tensorflow/include/external/nsync/platform/macos/platform_c++11_os.h,sha256=Wxae6f0fMregaBeNDEMPDM-YF-mOiRxoZFn-72a5Ysk,1032 +tensorflow/include/external/nsync/platform/msvc/compiler.h,sha256=bvvnxylRxSEIny_S74qsAjnoyxd_OPTmnknfoCu2sE8,807 +tensorflow/include/external/nsync/platform/netbsd/atomic.h,sha256=HwPDAoAR5GfX1YYv2cztQ92EIATIrmC5YA9a5U_hjuw,4301 +tensorflow/include/external/nsync/platform/netbsd/platform.h,sha256=dXxyj1UIoQjwo3FdukphjAU_5jciy8iEs7A_3Z3-04M,1031 +tensorflow/include/external/nsync/platform/openbsd/platform.h,sha256=H_PLp7hpSXuLXZRJ8EVIuoD4Iz6kygUdRCmu50P8wMI,1032 +tensorflow/include/external/nsync/platform/osf1/platform.h,sha256=-rus-p16PeFKBTUa8O6ZEebX_hY6O62ORrZ327AOs88,900 +tensorflow/include/external/nsync/platform/pmax/cputype.h,sha256=Op5g3WZNjnz35uopAy7C6w3fdNgyC0rdwC8pZqa6b_A,732 +tensorflow/include/external/nsync/platform/posix/cputype.h,sha256=KU2jwJx6cxJS72qBvW1DBLFoMGCEjpBakqm-Oco_DXM,735 +tensorflow/include/external/nsync/platform/posix/nsync_time_init.h,sha256=7olscDFSZT77qbpwRT6C-gOYOd-jnQRT_VSLquDV7tc,775 +tensorflow/include/external/nsync/platform/posix/platform_c++11_os.h,sha256=-8Iq-y8pRotcijFiPFwbk8dUIg27_w-Ziz1s4JpcGaE,574 +tensorflow/include/external/nsync/platform/ppc32/cputype.h,sha256=vbKOGI0-sK3Fc9GtEoKE8ozpwdm7mvNOj6kni32BosE,735 +tensorflow/include/external/nsync/platform/ppc64/cputype.h,sha256=dy0H5Y3MPpNcNQIhDrx8REQMXSkVVIKvkxlFs8C1rp0,735 +tensorflow/include/external/nsync/platform/s390x/cputype.h,sha256=F25Cr6HqPxKW_2_dNT_30JeU4oJqcB4Edy87IULlj1Y,735 +tensorflow/include/external/nsync/platform/shark/cputype.h,sha256=tjU-j35n2syib-9umEFeXoucqLLUAQ0Tn2cy2akpg0k,735 +tensorflow/include/external/nsync/platform/tcc/compiler.h,sha256=_yTgUKwC0GYXooOO3SxB5OpdoTY-LIfcXb3466wZteg,810 +tensorflow/include/external/nsync/platform/win32/atomic.h,sha256=mlcwnV6TEFB-0Y1vu0EB-Blag1t_ghWOl1JU1JrLhBo,4407 +tensorflow/include/external/nsync/platform/win32/platform.h,sha256=GlJ2SLSdyOgna7ZUwdhs3iFYWltqUD4cUZg6sTMvyR4,3959 +tensorflow/include/external/nsync/platform/win32/platform_c++11_os.h,sha256=D4PS7ST042lucbJG7NbiWA9fcSKeZAOssWSJzBevkQQ,2152 +tensorflow/include/external/nsync/platform/x86_32/cputype.h,sha256=luTzJKeEZe_cBM2g2aE1uLJk5iD_HH6E-hsPPr-mHuk,738 +tensorflow/include/external/nsync/platform/x86_64/cputype.h,sha256=AKAtwvHRg6u05CX1C-WJjznCVX0VK6HnCp7SypPw1bg,738 +tensorflow/include/external/nsync/public/nsync.h,sha256=shCVSvuuIfGlIXhzu7QaTqU9H1dMRudvElpm4NxQ3oA,867 +tensorflow/include/external/nsync/public/nsync_atomic.h,sha256=bBpczTLY5vs-f_VVY1D0qrjAOfQJNe1ujlRb_XxcdJk,2163 +tensorflow/include/external/nsync/public/nsync_counter.h,sha256=5TkZFAiFCO2G-cms1GPqCc13JWiOj0N8HXY-WG4NOTA,2236 +tensorflow/include/external/nsync/public/nsync_cpp.h,sha256=U5JyD8W3ANhXcKW27dwGRt5tNdiHaPEVqOQwNq9zo0w,1565 +tensorflow/include/external/nsync/public/nsync_cv.h,sha256=CMeNFkcRPYktSWrZ4CrY78c7iOjjuEvJaum-vTgSojM,6840 +tensorflow/include/external/nsync/public/nsync_debug.h,sha256=WEuIbKz3ZeoDmKXhu109dXMS_MODezt3irPsFeutn0o,2328 +tensorflow/include/external/nsync/public/nsync_mu.h,sha256=6nw8RD1HECcqSCcZAqr63sBck3-5OfTDcvNuRznTv1w,4281 +tensorflow/include/external/nsync/public/nsync_mu_wait.h,sha256=YSXHvNc_Xdwa0Qy08y-wWmqg41EH66qzHmyfCiDDnn4,5582 +tensorflow/include/external/nsync/public/nsync_note.h,sha256=GPEYpHMq72jYbNqs-lUikSC5P7gQopKGzA7jeHlEfg8,2639 +tensorflow/include/external/nsync/public/nsync_once.h,sha256=dxa7-rQwLgT3fF3y3E5GepWA0jg0tsWMw6DcIFJQFuY,2061 +tensorflow/include/external/nsync/public/nsync_time.h,sha256=xUPPQOhj7wndPY9qmGnriyRJcnDVXmEkkxjuW0jZS1o,2255 +tensorflow/include/external/nsync/public/nsync_time_internal.h,sha256=f20-LZmZYJisPTxBy6nEH_DXtctpHF2L6JZL_HqBjJw,7466 +tensorflow/include/external/nsync/public/nsync_waiter.h,sha256=1mKbfZjtIuhE3JVKhXwErYnxNK5e848DwtVyWMEYEr4,5849 +tensorflow/include/external/onednn/include/dnnl.h,sha256=I-QBhgaQhsKI9ws5dIWiC1mo_tzjMZTqcOEH2R_dquQ,826 +tensorflow/include/external/onednn/include/dnnl.hpp,sha256=7EzmLtny7m_4pRVphyYiPvrsnwF6k4fScSQ6t_vOBrA,834 +tensorflow/include/external/onednn/include/dnnl_config.h,sha256=4gxE_VLSQRh1ZjNU0b813RVsIqLRf1g97y8E7yYt6SE,854 +tensorflow/include/external/onednn/include/dnnl_debug.h,sha256=54dhupUgTYXVDXGNKkIHZa_CIs5rNdGaB4jzaKOmsV8,850 +tensorflow/include/external/onednn/include/dnnl_ocl.h,sha256=zEhZqSx-AMUh-leUn1DUIKre4POhBRoclUX204x0Ynw,842 +tensorflow/include/external/onednn/include/dnnl_ocl.hpp,sha256=AtN-4Y8wmrv_Fe7DkOMq2-lZHNH3cZK97K6g3ZbkEzU,850 +tensorflow/include/external/onednn/include/dnnl_sycl.h,sha256=hP8wUN2leTYsOSH0zxGhYCowrWL6y1qzEMJx82cMOLE,846 +tensorflow/include/external/onednn/include/dnnl_sycl.hpp,sha256=qVdl2cYsFcyCF4NpURATOVd2ZsY9c2QWNSuwA-laDbk,854 +tensorflow/include/external/onednn/include/dnnl_sycl_types.h,sha256=wx0L7FacMUW1yLGkQdl633awv1WIiMyjPit8VR0MxRw,870 +tensorflow/include/external/onednn/include/dnnl_threadpool.h,sha256=pXtNzHokkJu8cOj1YHKPswQ2lHyfnlWmahZ6xSFUONk,870 +tensorflow/include/external/onednn/include/dnnl_threadpool.hpp,sha256=Ma26PaVZ1D_dIKKuSC68LN7Ak0SYjJRnR9TCmvOhC1c,878 +tensorflow/include/external/onednn/include/dnnl_threadpool_iface.hpp,sha256=6c4hFR5SOjW5ke4BfdrklzYSuFQH9av-3qYIstHvyfE,902 +tensorflow/include/external/onednn/include/dnnl_types.h,sha256=mj-E92o3tq2jYmf4m5ApwxF5ZUpOHSW2Tcx1Ye2-CXE,850 +tensorflow/include/external/onednn/include/dnnl_version.h,sha256=TMnzInMTsAACwnwp4ICpkZmiGXNhA4PHNkrHME_E8_8,858 +tensorflow/include/external/onednn/include/oneapi/dnnl/dnnl.h,sha256=7v1gE2lLsYUtg7OS5sl4s4RBURtv_odMPPjUy6xyV7o,164771 +tensorflow/include/external/onednn/include/oneapi/dnnl/dnnl.hpp,sha256=tWHMr4F76wrHBAmXFDMPIIk6uKobehn6h6whnjifCJ0,595247 +tensorflow/include/external/onednn/include/oneapi/dnnl/dnnl_common.h,sha256=mKAdlEHdgFZVHfU0AsuQv8ALksoRpRxFZJx2zhdd32U,5619 +tensorflow/include/external/onednn/include/oneapi/dnnl/dnnl_common.hpp,sha256=T0QUWUPmkp-GgcRWCB7iGuQ8NXwuJl7GYJZxThl2AtU,14548 +tensorflow/include/external/onednn/include/oneapi/dnnl/dnnl_common_types.h,sha256=KfouiVp69E4EGKG_kmdbevmgLVW2Mpa9eRl6RK3Cr90,5976 +tensorflow/include/external/onednn/include/oneapi/dnnl/dnnl_config.h,sha256=d7uYRD9t3K_T4GCnZOxDXKk8FYHBHLZlQ1_pbnMtzDY,5199 +tensorflow/include/external/onednn/include/oneapi/dnnl/dnnl_config.h.in,sha256=UnO7GZSaoTGOVrXd-L1m92CGP_A8nO-jgD2ZVlObAp4,5487 +tensorflow/include/external/onednn/include/oneapi/dnnl/dnnl_debug.h,sha256=JEUA9w6V3sIOd8HjfLJyUXjHX4A-8lJ2yfCiqcqSnRU,2164 +tensorflow/include/external/onednn/include/oneapi/dnnl/dnnl_graph.h,sha256=HICFFDnstAL9eql8kFSGIjbitiYgFbX5Rv6nPgwHIR8,29128 +tensorflow/include/external/onednn/include/oneapi/dnnl/dnnl_graph.hpp,sha256=6xxomf7-aqB_dU5EQI78kIvTbpSoALhUUTIDQUAq-pQ,59473 +tensorflow/include/external/onednn/include/oneapi/dnnl/dnnl_graph_sycl.h,sha256=bxaJTCx7ZlVlF1z9icL7f2miV_0h_30ed9Swf6xVmhg,3603 +tensorflow/include/external/onednn/include/oneapi/dnnl/dnnl_graph_sycl.hpp,sha256=XjlESo-adGpXoJKu_sb-ZJKdXt56J5NOh3yxODPjZAs,4309 +tensorflow/include/external/onednn/include/oneapi/dnnl/dnnl_graph_types.h,sha256=2IwspZaiMuiIhvE1RRBmChwKg424teKLY3K7HBUV354,16444 +tensorflow/include/external/onednn/include/oneapi/dnnl/dnnl_ocl.h,sha256=_PkVtWANTJny5_8ubUjxyXY3EbgskQwXt0cen_YpgRw,10412 +tensorflow/include/external/onednn/include/oneapi/dnnl/dnnl_ocl.hpp,sha256=JtN6Np4li9BYJcP1WTDR-1yHeSGS3J3Cq-ljpm-PuRw,12962 +tensorflow/include/external/onednn/include/oneapi/dnnl/dnnl_ocl_types.h,sha256=J3rW6OBG7OgDXOJqLMLxjsNCUhPvOtWNA9hC7Rs3fhw,1338 +tensorflow/include/external/onednn/include/oneapi/dnnl/dnnl_sycl.h,sha256=9dE7pfEr6V0pt4QrxpJfek1HpeKLPdfWipYfdCKyh3Q,6792 +tensorflow/include/external/onednn/include/oneapi/dnnl/dnnl_sycl.hpp,sha256=ZCOBBX-z7MEPT1f527wQP7bTTO6y3pjqAftnI3Ny2Os,11141 +tensorflow/include/external/onednn/include/oneapi/dnnl/dnnl_sycl_types.h,sha256=pdRCsKfL2oiE6dXeGQCOSuKEgMXkO5GT9RuzkH9Uqfk,1350 +tensorflow/include/external/onednn/include/oneapi/dnnl/dnnl_threadpool.h,sha256=MRxtU6ucvrZgFMCsU5JBrYfaT9USXmj1d_EI4eDeTSo,4524 +tensorflow/include/external/onednn/include/oneapi/dnnl/dnnl_threadpool.hpp,sha256=2Zgcg34OQPC7Tf-D5U3_6CxCI5fxlPfMsD-AvMl50nA,4327 +tensorflow/include/external/onednn/include/oneapi/dnnl/dnnl_threadpool_iface.hpp,sha256=0_62P7fK_DH-fc4ny1CvywVCVDoaaFe86SYUOBT1Q5g,2182 +tensorflow/include/external/onednn/include/oneapi/dnnl/dnnl_types.h,sha256=hq8NOVgZi_NFevq-3xpY5HbyFb5wU-TrM1B1s5roFk0,92666 +tensorflow/include/external/onednn/include/oneapi/dnnl/dnnl_version.h,sha256=3g7OV9MCtq_r3e2wIRRbR5Nugk2A4v5l4GYfPyO-cjo,1066 +tensorflow/include/external/onednn/include/oneapi/dnnl/dnnl_version.h.in,sha256=iSmiNsZyGSP694hy5AWq1bKjQzzYdfQVjbi0bI5BnSM,1139 +tensorflow/include/external/onednn/src/common/batch_normalization_pd.hpp,sha256=mOrcdYuN6wAbJH8w5WBp9nukSJVTtt2olm8d_EUAW9o,13772 +tensorflow/include/external/onednn/src/common/bfloat16.hpp,sha256=45nWeehpnUUZQWCGEI7SvOEkLEOfm4g6nd8n7--qGuo,3141 +tensorflow/include/external/onednn/src/common/binary_pd.hpp,sha256=72ijr15HlPCdwo5ajXQFcxqlI7U5MnUz6dmKOfzMeRk,5619 +tensorflow/include/external/onednn/src/common/bit_cast.hpp,sha256=szk4Xspjj9U5JXEoBq2jJ6exJ-s2jrasSb29l3y4tGI,1972 +tensorflow/include/external/onednn/src/common/broadcast_strategy.hpp,sha256=mvEDzq0rh6bi6fJHRTbGUSdIx5A_1KLz6CvK4IyrMZA,2321 +tensorflow/include/external/onednn/src/common/c_types_map.hpp,sha256=ZVyQOHyz6LMjSYMIAPf0f9gnQQ8Jyrh3yfB3YUfEutU,88478 +tensorflow/include/external/onednn/src/common/cache_blob.hpp,sha256=del0bkTumOuyg3wLDjVv3BIhX9wmkQ-8vIB0FNAwP7c,3719 +tensorflow/include/external/onednn/src/common/cache_blob_id.hpp,sha256=IHV9l_Uswuxplzj1_ExOLSW4UuAEuhNBRJhV5mfr_h0,2042 +tensorflow/include/external/onednn/src/common/cache_utils.hpp,sha256=YK92wTDxqPDH7SYajEukUviDiN9fPebXu91Ovo4q6C0,15379 +tensorflow/include/external/onednn/src/common/compiler_workarounds.hpp,sha256=4RchvtqPs47jcoG6IbbU75HVVlpw3yMkVZEpfdm11Fw,2870 +tensorflow/include/external/onednn/src/common/concat.hpp,sha256=wbpda8GDvko0KA9x55QIJq7jk4t13CRJuGmeSSkevss,1168 +tensorflow/include/external/onednn/src/common/concat_pd.hpp,sha256=b5DDi0Ra5sPU3mMHf0B2_tRtEBoSnYOJjM4kwBzHNiQ,10583 +tensorflow/include/external/onednn/src/common/convolution_pd.hpp,sha256=lxIhkhLDydYA8rDEPgQZVEwindwmpsyPx71M0Vcezn4,17668 +tensorflow/include/external/onednn/src/common/counting_barrier.hpp,sha256=Wc_I6DTgcS7WbkrZAaMUaxvzAvFoy_kerDoRtZOY954,2022 +tensorflow/include/external/onednn/src/common/cpp_compat.hpp,sha256=jBzQG9d4RX8tUlmFBOADmvdLwThhj0YZ559LdkwK1-E,1708 +tensorflow/include/external/onednn/src/common/deconvolution_pd.hpp,sha256=oJdZ1SyN3Rd4rA2ohQyQ__uIOtU_Y7N7qRhx81NsbQ4,13280 +tensorflow/include/external/onednn/src/common/dnnl_thread.hpp,sha256=wSzdb7cfL2yzXa_Yqqv6XMqOug3XHwQWV97SClnVOnI,26030 +tensorflow/include/external/onednn/src/common/dnnl_traits.hpp,sha256=hocSL-zGstHLyerfL2TYmedwoITjR17rps_122xbBoY,3757 +tensorflow/include/external/onednn/src/common/eltwise_pd.hpp,sha256=aZUtlg3ryVlAv-r4uFIX92lSxoMEqD2c95z7F1Ji0uE,11191 +tensorflow/include/external/onednn/src/common/engine.hpp,sha256=rPmGJfgS2_1uMs4XT7m309JO99G7qwqzp8N4-2esDq8,7137 +tensorflow/include/external/onednn/src/common/engine_id.hpp,sha256=TtPTqcLPo98PuC_ECqzgVapebBeMdKcdU92vjF9P4cI,3584 +tensorflow/include/external/onednn/src/common/experimental.hpp,sha256=PviF6ndajMjA5RhTvN1CjhH48GmcMD6FzyJ28ZXLPDM,963 +tensorflow/include/external/onednn/src/common/float16.hpp,sha256=UPxLNyomDf-JZ_Fs5VOwpHBZf2xFYUo30UT_2dxsRLI,3706 +tensorflow/include/external/onednn/src/common/gemm_pd.hpp,sha256=MriXjUsjCIn-jG94PVjiDfr23WQMzAWTyNLgTLjX2qo,3846 +tensorflow/include/external/onednn/src/common/gemm_types.hpp,sha256=W34viX-occ2YDfKqfO-VPIexBr1eCsY30IPSHA3QbEI,6075 +tensorflow/include/external/onednn/src/common/gemm_utils.hpp,sha256=B7og7eNINeh7GGk11TvUYxsrlVpbdmmmnjQR2MVc5uk,6379 +tensorflow/include/external/onednn/src/common/guard_manager.hpp,sha256=uoz0NoDeZSz8H4GkgBofBTRds4nE2xTyO-R19mo9Ya4,2057 +tensorflow/include/external/onednn/src/common/impl_list_item.hpp,sha256=p6Sp2N8m767YO70yrpqrc2KfIYMIAd7dqoN9vdkufEI,8078 +tensorflow/include/external/onednn/src/common/impl_registration.hpp,sha256=4xIeTftlgaSRBMdzyi35qbAZczHQUdz74TZBl2EkzCA,5151 +tensorflow/include/external/onednn/src/common/inner_product_pd.hpp,sha256=H8paLRiJ-h3aEAoVcisz_6hEcJerYiLtPlRNoROjn7Y,14746 +tensorflow/include/external/onednn/src/common/internal_defs.hpp,sha256=m0sc7iljuu6ZMkZRMpgx8ZBDPAWRhvR_eBh5_ZvEde8,1109 +tensorflow/include/external/onednn/src/common/ittnotify.hpp,sha256=fWppfAELBtPh8yackWdPuFRvyw0f_-ZMNWCex50DLC4,1406 +tensorflow/include/external/onednn/src/common/ittnotify/disable_warnings.h,sha256=_3pDBCgqCUkDgh7eEo-25LbJec178zJNLEEInWgMB2Y,1069 +tensorflow/include/external/onednn/src/common/ittnotify/ittnotify.h,sha256=-HCPw-E9wCt-VUhuSCcaU8o2ATJL8O2CFp2uqPruqO8,187448 +tensorflow/include/external/onednn/src/common/ittnotify/ittnotify_config.h,sha256=efLL28lweJRjCXiF0SS9x1S-8Pf9G_7-kA638u4_RpQ,23065 +tensorflow/include/external/onednn/src/common/ittnotify/ittnotify_static.h,sha256=nLxlvgNNRAZOUBnr4HZ1dU5wirQkM23ZIUJ4buU60r4,41145 +tensorflow/include/external/onednn/src/common/ittnotify/ittnotify_types.h,sha256=86EuGhyKr_K6h8dVnd4AQ-y3V4xKAitWAVmyJl6THEg,2053 +tensorflow/include/external/onednn/src/common/ittnotify/jitprofiling.h,sha256=PyNEdPe1RXZ5cCw6AM0m9-vfAeVGwk0Hq1lr2TgT_00,29637 +tensorflow/include/external/onednn/src/common/ittnotify/legacy/ittnotify.h,sha256=J7280tIG-kE7pluDE7NtEjU9sYSjOKNcG9MTx_T82XU,37090 +tensorflow/include/external/onednn/src/common/kernel_cache.hpp,sha256=IvS4Pikvg5Zw9vRereX4KuOCHKS6bgPV-W4rkF6RXj4,4308 +tensorflow/include/external/onednn/src/common/layer_normalization_pd.hpp,sha256=ffqxoJTCJr67uRptnhxPFqf3iPfUgy0bR3vcBt6oxu8,13290 +tensorflow/include/external/onednn/src/common/lrn_pd.hpp,sha256=dXqVk680DHGFrCyI6XLIyxcvmcLu5wf0RwhtEoJHW24,8112 +tensorflow/include/external/onednn/src/common/math_utils.hpp,sha256=_o7t5n5SIZrBFEw3XIx_XArOKeub7aRSrMUAwkl3AYo,14559 +tensorflow/include/external/onednn/src/common/matmul_pd.hpp,sha256=IWJqtVwjcNI7pPw-WhZHsoKQFWSwsvS2SRX-OJZHBlk,6417 +tensorflow/include/external/onednn/src/common/memory.hpp,sha256=cvNjOjHGCHyyQyfRvYIo4XhHk1qnkAwGbOfEsF1YKFU,3599 +tensorflow/include/external/onednn/src/common/memory_debug.hpp,sha256=j6A4xJ-WlO8lfQDU5XJflmbF6IYDeEj22vr40RPLbXY,2391 +tensorflow/include/external/onednn/src/common/memory_desc.hpp,sha256=-qv73c-iwrQem4Cls7eZ5VEPl84qH3F9nxAp2Tlekho,9188 +tensorflow/include/external/onednn/src/common/memory_desc_wrapper.hpp,sha256=0hdBkztia8Bw2JQ07JM-PMveaV1WLNz1yicjp_lkTME,21783 +tensorflow/include/external/onednn/src/common/memory_storage.hpp,sha256=zKKUZ6Ippxdp8JOYIZRk9M-RXS2VF3rLpBW9fOFnm_k,4756 +tensorflow/include/external/onednn/src/common/memory_tracking.hpp,sha256=lm_YLhE250xibmEEbMx_An6lt3jHtNOtrHBRZNxRlg0,19285 +tensorflow/include/external/onednn/src/common/nstl.hpp,sha256=Dmv1DdBvHAbk1iK1-j_-aNuNajjioZySgGD5t06b-Zs,9593 +tensorflow/include/external/onednn/src/common/opdesc.hpp,sha256=PL9GdtSK_I9Yxhfs-23XB08Aa8xPv2gt_cENGIA-1AI,24811 +tensorflow/include/external/onednn/src/common/optional.hpp,sha256=mJr36SY-IGF6oRcm8j12iaFckfgMq4rVE2ByO8qKdgo,3937 +tensorflow/include/external/onednn/src/common/pooling_pd.hpp,sha256=vV2XOEeb1Bllx6e4b9oOQrOU8_VVunkVWZ-j_wrBySw,11617 +tensorflow/include/external/onednn/src/common/prelu_pd.hpp,sha256=8AA1OQopQePwoCjfgVNBEHUNuKsnRby2mk00VQ5CE4k,8993 +tensorflow/include/external/onednn/src/common/primitive.hpp,sha256=F1bIEK1bf9K3j6mFkI9QRZmipdgUepe_ldldY3MEUWE,6025 +tensorflow/include/external/onednn/src/common/primitive_attr.hpp,sha256=kAvjLvRo3A01pHrG5VrrvsycTd9zsfClb8w4qWZdPp4,27850 +tensorflow/include/external/onednn/src/common/primitive_cache.hpp,sha256=l-JgxaylpHrJVZHAcshcAaHVDpF0h1DabRvIze1Il7s,2448 +tensorflow/include/external/onednn/src/common/primitive_desc.hpp,sha256=27Zz15dc2CXjmxqppiRraSTrqGFB4dd5rKAPgIwb1_E,16562 +tensorflow/include/external/onednn/src/common/primitive_desc_iface.hpp,sha256=EcQ3QGqkX8pqje4Un9m4G9ELX1VcldyM5gTuijAIXzQ,3158 +tensorflow/include/external/onednn/src/common/primitive_desc_iterator.hpp,sha256=Ypd8RbsExqHLY8rBmMDHP86QXKRenhpxCKhTXQ_r0hU,4708 +tensorflow/include/external/onednn/src/common/primitive_exec_types.hpp,sha256=MtsjwSnd_n79zCE0OVxuq02_74aygWZFeLjvVH5Y6fg,5145 +tensorflow/include/external/onednn/src/common/primitive_hashing.hpp,sha256=xc3XXqkXXGraO87VrKLtcVGvB-ko-xEUPLmaRaiiGC0,6587 +tensorflow/include/external/onednn/src/common/primitive_iface.hpp,sha256=_U4LQMqeUMG8F9p0ty122-V4ByQtHDn-dNQIp6hbA7k,3200 +tensorflow/include/external/onednn/src/common/profiler.hpp,sha256=edd4cMuPW7MUQj1H-hsNOA4dMFQAjlWa_BLyh0DAjvw,6840 +tensorflow/include/external/onednn/src/common/reduction_pd.hpp,sha256=hJzjeS9GWaM8Hc-BD3GXhIU35mMP3dVBdKyg7aCrnt8,5341 +tensorflow/include/external/onednn/src/common/reorder.hpp,sha256=9VwvnqgWqaGSAqIziNrpjmBocHR1ORqZH5C_j1MFsHw,1147 +tensorflow/include/external/onednn/src/common/reorder_pd.hpp,sha256=AiZM3EB8Yf5k0IOml4tsHjCTgf-qHQVR1IDfh5wyvvM,6118 +tensorflow/include/external/onednn/src/common/resampling_pd.hpp,sha256=N2zEA1mCnXVzNNEji92dEs8n-QwZepcCO1wj5-dNSo0,8037 +tensorflow/include/external/onednn/src/common/resource.hpp,sha256=b92dHI_Dt01FBL2VoPztQez4uXJQW1063UmoWL36yA8,3485 +tensorflow/include/external/onednn/src/common/rnn.hpp,sha256=jRAJBfwaXc094hnWmnhfXP-gnUz6QA_weacN2wNhA9A,993 +tensorflow/include/external/onednn/src/common/rnn_pd.hpp,sha256=oLGcON5V4pZdSxOgXAevKf6wUSEIScDdb2rAMQO85I4,18946 +tensorflow/include/external/onednn/src/common/rw_mutex.hpp,sha256=IZSBlbNc4VItQfcqzBTYkozCMuFZdZblSIKQjRtTgFo,1756 +tensorflow/include/external/onednn/src/common/scratchpad.hpp,sha256=v3ST3pRsIDMMwILhsSmg-v-Z0paoGx0XNXmeKYa-unc,1282 +tensorflow/include/external/onednn/src/common/scratchpad_debug.hpp,sha256=kVked22CPWzai_vUM0ZadZzshYDshm5ciiSWzP0w3TY,1730 +tensorflow/include/external/onednn/src/common/serialization.hpp,sha256=eA_8A5AHwiRJSvP6UsjZkh4y3VUYE1E_QXMad3-6aSo,3168 +tensorflow/include/external/onednn/src/common/serialization_stream.hpp,sha256=zzqHc2Mwnyf-Huu_d0tVCEBjC263gIKoShdVrKWjjVs,2132 +tensorflow/include/external/onednn/src/common/shuffle_pd.hpp,sha256=46gSLUcKnQnsyFM6HlrAJmruAOVKOql28Br7cJAkKrw,6437 +tensorflow/include/external/onednn/src/common/softmax_pd.hpp,sha256=C0DAf8u5F6JAc6i83GmkXcBw_piL_RUikZnqiemWUAQ,8901 +tensorflow/include/external/onednn/src/common/stack_checker.hpp,sha256=ylojHFco9JxZSWAEoBVrhkGIGVWiOsnDkmZYK8p3sEM,12392 +tensorflow/include/external/onednn/src/common/stream.hpp,sha256=vHU-y2vUKJh9C4j0q-HWR86mo6i4wQcTz8VnufYUitg,3324 +tensorflow/include/external/onednn/src/common/sum_pd.hpp,sha256=9A2al6WosABG7zYB5tytf-lDAE46viymbYZrOJhuxWQ,7249 +tensorflow/include/external/onednn/src/common/tag_traits.hpp,sha256=XvFKSZH8QQhfZdqOKEwtvEhDga60Wwwc9dFtOctQPEk,32792 +tensorflow/include/external/onednn/src/common/thread_local_storage.hpp,sha256=BW2Sqs_xTYFo77uIXOKI0LxIdXvtKdsq3oTHOn6eykI,2220 +tensorflow/include/external/onednn/src/common/type_helpers.hpp,sha256=TljllaAWwWZ0hSBNzmFwGPyBnaQuErI84e8WZsWpb9w,36055 +tensorflow/include/external/onednn/src/common/utils.hpp,sha256=0_6LbIwyO4Fkd1cLoZjjncXLqVICpjoe6VK4YWIqsaw,24627 +tensorflow/include/external/onednn/src/common/verbose.hpp,sha256=3ec7qEbOiFqQFeo_AlaMROjI_BIg9_Op3xq9XIANcDo,6556 +tensorflow/include/external/onednn/src/common/verbose_msg.hpp,sha256=zIWu9g_HLj6jaG6UbxXPSeNLB-YniKXXcjWkNIkib-o,3590 +tensorflow/include/external/onednn/src/common/z_magic.hpp,sha256=Qy7cJ1wiehP6cOkHw39jSgUDTQ5SmqEmlYX4eVb3hF8,1605 +tensorflow/include/external/onednn/src/cpu/aarch64/acl_batch_normalization.hpp,sha256=vFkT5l-no0EyfeGenyqRSnNe4GC0OhM687-ndRM48as,11862 +tensorflow/include/external/onednn/src/cpu/aarch64/acl_benchmark_scheduler.hpp,sha256=78PnzVzMEr0HZp4Ga-tR9n1MBza0yO_U-OaoXznsOH0,2365 +tensorflow/include/external/onednn/src/cpu/aarch64/acl_binary.hpp,sha256=rIXRDh-DWDQH6TbKnp41fKXTBIMRQwoFbbiSrGIfE7U,11351 +tensorflow/include/external/onednn/src/cpu/aarch64/acl_convolution_utils.hpp,sha256=QvMzn0PBi5JYq2HfEB4LFtUijB26divpUeDjuvR-KhU,4689 +tensorflow/include/external/onednn/src/cpu/aarch64/acl_deconvolution.hpp,sha256=iM_-0UzZPtc_JG7QBeDM52C6_3kIf1uiCga_NZBoLW4,13307 +tensorflow/include/external/onednn/src/cpu/aarch64/acl_depthwise_convolution.hpp,sha256=Hjb25ebnUAcUNrtdbYCO4BZvoyHJFDweEJYEyGRpuDE,5002 +tensorflow/include/external/onednn/src/cpu/aarch64/acl_eltwise.hpp,sha256=KwiKlh_ZNr1qyx8PxFXb_jKjvLWewEEr9ffJwB7WJNk,5961 +tensorflow/include/external/onednn/src/cpu/aarch64/acl_gemm_convolution.hpp,sha256=8dalEB_yBjLPVGn_bwg2_BdyeomCCVyTkqBs9Xho4gQ,5819 +tensorflow/include/external/onednn/src/cpu/aarch64/acl_indirect_gemm_convolution.hpp,sha256=gm8KzaJtnvt1VwFRYdNqXmnH1nvgtgR3G7WB_BroWn4,5421 +tensorflow/include/external/onednn/src/cpu/aarch64/acl_inner_product.hpp,sha256=mbP_ggIs0m7iw8djQdV38gKn-De6U5PXwzXfQP17AjY,13056 +tensorflow/include/external/onednn/src/cpu/aarch64/acl_layer_normalization.hpp,sha256=18ecVUEzK6gb1Oxm9opfGkphqUeX-yunoGaIzsGizD8,9982 +tensorflow/include/external/onednn/src/cpu/aarch64/acl_pooling.hpp,sha256=e_2InoV71V2mYhngI1mVpe5EUvi7jCwuCZIqhy2CFBI,9311 +tensorflow/include/external/onednn/src/cpu/aarch64/acl_post_ops.hpp,sha256=DRlIKeNqOIVn6xZf7oMXdajpJxSv54qn2zXN-PJJfN8,7937 +tensorflow/include/external/onednn/src/cpu/aarch64/acl_prelu.hpp,sha256=Cd_xLSRuO1jOgxLpTKnfO6Diu7OvJxaxW1-9h3dHiRQ,5787 +tensorflow/include/external/onednn/src/cpu/aarch64/acl_softmax.hpp,sha256=pXrUCaKJiiet0sxxkdPNS9dLuMaLnQ0pSCWGDG2sg5Q,9387 +tensorflow/include/external/onednn/src/cpu/aarch64/acl_thread.hpp,sha256=IiAV5yYBcQcPcaZ5ov4U4aL2MngVok8a0cXTXzKmkxc,2010 +tensorflow/include/external/onednn/src/cpu/aarch64/acl_threadpool_scheduler.hpp,sha256=IBMh7Mbv6YtNQ9TJPxHu2l-1DaWuNZziNbG1v9yr8Wo,2383 +tensorflow/include/external/onednn/src/cpu/aarch64/acl_utils.hpp,sha256=AZAkdDtz3sHi-bXhh4FfwLKa7MEgLomJ3es-iJf19ew,5635 +tensorflow/include/external/onednn/src/cpu/aarch64/cpu_barrier.hpp,sha256=yRGFJSbu65iDmSDxPq-47_mxjKe4yZStO0ZlXzLfbWU,2873 +tensorflow/include/external/onednn/src/cpu/aarch64/cpu_isa_traits.hpp,sha256=AlXhBblQLQ7dkTVYa_8066Zjul7dL9HSQHEvvnj3rUo,7567 +tensorflow/include/external/onednn/src/cpu/aarch64/cpu_reducer.hpp,sha256=dg7LcFrFGAMLThCDm1c9k4NT7hxPdZNOKYq5wDR7Efk,13380 +tensorflow/include/external/onednn/src/cpu/aarch64/injectors/injector_utils.hpp,sha256=sGoRWSKAeVCpAQZ7npIgvvd9Yt7KWQfphoTmiJfAWMc,3739 +tensorflow/include/external/onednn/src/cpu/aarch64/injectors/jit_uni_binary_injector.hpp,sha256=D1RuLCGi_ocAIyC6NiQMRyEHAkOEOe001Mr_vT3YoMo,29818 +tensorflow/include/external/onednn/src/cpu/aarch64/injectors/jit_uni_eltwise_injector.hpp,sha256=OGg_fhb3gqrzXsyWSWq_EthLW9NmUu__8kGx9JAbTtU,14280 +tensorflow/include/external/onednn/src/cpu/aarch64/injectors/jit_uni_postops_injector.hpp,sha256=APJbhF7GCOI3t87hxp-I_ibxEzYZO94dNIVCe5tMb8w,6676 +tensorflow/include/external/onednn/src/cpu/aarch64/jit_generator.hpp,sha256=4f1gJqQ844HNq6WrowgVX0Bi6YvXvmFq9K9DiT_n7vU,25560 +tensorflow/include/external/onednn/src/cpu/aarch64/jit_op_imm_check.hpp,sha256=NGWHSXR8NVag7YLMAdh1qGfDYK3mrSbnKlMd4BNATe8,3302 +tensorflow/include/external/onednn/src/cpu/aarch64/jit_primitive_conf.hpp,sha256=Jhqe3LHdZ8ut_GDN5-PVURFyLIz189scD6XhprGfIpI,15996 +tensorflow/include/external/onednn/src/cpu/aarch64/jit_sve_512_1x1_conv_kernel.hpp,sha256=yfSevlIU1MVvOTBxB_SNXKpSW-mBDQ-lXtTTwQRPNsA,7351 +tensorflow/include/external/onednn/src/cpu/aarch64/jit_sve_512_1x1_convolution.hpp,sha256=EzF_2od6dZfaHxej7zYi-OD-rn47ZZEMAD91ttl7NMQ,23008 +tensorflow/include/external/onednn/src/cpu/aarch64/jit_sve_512_conv_kernel.hpp,sha256=y_ySnHbv73UdWwQF0TVqPc3odRp82GjUM8UBHcEeuvc,21309 +tensorflow/include/external/onednn/src/cpu/aarch64/jit_sve_512_convolution.hpp,sha256=NCIP7DPHxpZWnDcVjr2izl-XEjXKZSX8AgXJ-ppKcbc,10873 +tensorflow/include/external/onednn/src/cpu/aarch64/jit_sve_512_core_x8s8s32x_deconvolution.hpp,sha256=Ay78KXkVs7xwgxNnGNQtkIMQ-5jCSnOJiR2WEbLYBgU,12822 +tensorflow/include/external/onednn/src/cpu/aarch64/jit_sve_512_x8s8s32x_conv_kernel.hpp,sha256=nxqsNtmLMuOsgucTXb-C7pVARbeDl-Iulv1B1C55dRw,8666 +tensorflow/include/external/onednn/src/cpu/aarch64/jit_sve_512_x8s8s32x_convolution.hpp,sha256=HZzlGI55d7rMGfxKJShJsRJzMhAaOqMmP1qOirH2G14,4677 +tensorflow/include/external/onednn/src/cpu/aarch64/jit_uni_1x1_conv_utils.hpp,sha256=LYKyNUz7KrSNpnMfTwoEIiqAaEK_fe687J81G0mCenI,24533 +tensorflow/include/external/onednn/src/cpu/aarch64/jit_uni_batch_normalization.hpp,sha256=oKXQZcRry7X0jHkJxZRSg8kHZ088RO7uIfqp4Bo2Xtk,3377 +tensorflow/include/external/onednn/src/cpu/aarch64/jit_uni_batch_normalization_s8.hpp,sha256=ZStMxzYGphV3sFnptpLtuPOKzvTo65dV1-DxB0qBNic,2363 +tensorflow/include/external/onednn/src/cpu/aarch64/jit_uni_binary.hpp,sha256=TDay1ZKdfyRwFIucSBe0If1nis4VJQlH6LaVWp1eMMU,4459 +tensorflow/include/external/onednn/src/cpu/aarch64/jit_uni_binary_kernel.hpp,sha256=hZ7DWZUex1G0gCF1umaAL2EZiCT3L9-91TuGaNhvisw,5484 +tensorflow/include/external/onednn/src/cpu/aarch64/jit_uni_deconv_zp_pad_str_kernel.hpp,sha256=arSoqsI4DNeJWjVc3snzkV2Va2j3lImDP10ThdF5EpI,3711 +tensorflow/include/external/onednn/src/cpu/aarch64/jit_uni_dw_conv_kernel_f32.hpp,sha256=Ntj-wz6tj8ms25I0ylsGUHtJ-sBXG_x90IL97WCRoq4,8702 +tensorflow/include/external/onednn/src/cpu/aarch64/jit_uni_dw_conv_kernel_utils.hpp,sha256=xBzHF60HVGDjhl1LKZY6TjhTwAcPNHNHllPeeCFUvR8,22348 +tensorflow/include/external/onednn/src/cpu/aarch64/jit_uni_dw_convolution.hpp,sha256=jTlWX5alhHBul9MciVERREpWikJGjiFTJlAgWDuvnfE,10974 +tensorflow/include/external/onednn/src/cpu/aarch64/jit_uni_eltwise.hpp,sha256=3lCxXIqLblF657sNdmPiA4M8OiDHR8qOZPSuL5GH8qw,2801 +tensorflow/include/external/onednn/src/cpu/aarch64/jit_uni_eltwise_int.hpp,sha256=rAuvDkGWk9Mlt3BSyvV1PZ7YuHd35jXWVHok0FqNnxs,2163 +tensorflow/include/external/onednn/src/cpu/aarch64/jit_uni_i8i8_pooling.hpp,sha256=c5N_BVX962ZfwH6gD_O9OSeTTf3BCkJiB2Ud-jmIooQ,3542 +tensorflow/include/external/onednn/src/cpu/aarch64/jit_uni_pool_kernel.hpp,sha256=BerHt08JB_O0C2UV4GkYbxSl52KxYJsi5XXJkz950-g,5547 +tensorflow/include/external/onednn/src/cpu/aarch64/jit_uni_pooling.hpp,sha256=pn8G9TLNgotdGTCwlTcraEme6NP8yF3FqliPxAXs1Gg,6729 +tensorflow/include/external/onednn/src/cpu/aarch64/jit_uni_reorder.hpp,sha256=-SADp0wGLGEtsIR8RWO22E_v5bJXih_Gi20Foao7i7w,10356 +tensorflow/include/external/onednn/src/cpu/aarch64/jit_uni_softmax.hpp,sha256=oVxzxjK2_6U2-F5ES23GBLwNH9SIhsT0YoCDw34XtR0,7209 +tensorflow/include/external/onednn/src/cpu/aarch64/matmul/acl_matmul.hpp,sha256=FFrdXOGuuPu4EdNPfvxOrsc3ZC_ofAO_GJeoh5Tkhb8,5771 +tensorflow/include/external/onednn/src/cpu/aarch64/matmul/acl_matmul_utils.hpp,sha256=oU_F5Anlj17rznS1zvmOeE2EvNGMZ7Kniye26GR_mPY,2072 +tensorflow/include/external/onednn/src/cpu/aarch64/shuffle/jit_uni_shuffle.hpp,sha256=ipg_m1q7AqtOtuuUXY5juP5ov7-1FdoW0iuHJ_wqcqM,2160 +tensorflow/include/external/onednn/src/cpu/aarch64/shuffle/jit_uni_shuffle_kernel.hpp,sha256=N9OjjM-wvzNPzCB0c5Jm-R_lIRVPSlJ13eNpQFZyaw4,3641 +tensorflow/include/external/onednn/src/cpu/aarch64/utils/jit_io_helper.hpp,sha256=wWbfvh13CbPOY1RuCjylYASKTZbSHcKzcv-WKwUgVPo,8004 +tensorflow/include/external/onednn/src/cpu/binary_injector_utils.hpp,sha256=xTf1xipAY1mNXWEn30Zo5e4OIkb2-m4soNPl_sFZQAo,2950 +tensorflow/include/external/onednn/src/cpu/cpu_batch_normalization_pd.hpp,sha256=T_yEYWmcK6_sTfQpgTpOodbCmZitnRJW9dwvTlV0qNc,1385 +tensorflow/include/external/onednn/src/cpu/cpu_batch_normalization_utils.hpp,sha256=DgCJyfP4QbemJIHiXdoyL6ZVx6QgJE3uAIz48MaB8nk,1617 +tensorflow/include/external/onednn/src/cpu/cpu_binary_pd.hpp,sha256=uCr3B01JttW0ViZXUmQ8puzAnb9Yhvr_j8MNqxk9JCo,1220 +tensorflow/include/external/onednn/src/cpu/cpu_concat_pd.hpp,sha256=pICgpGffjZSpv5Ts_PJ_RL-3wXsoOQIp8K8JxOAPzPM,1242 +tensorflow/include/external/onednn/src/cpu/cpu_convolution_pd.hpp,sha256=42-ulQ50uTUZ2aOZiwbRgIK8TGjZ_yIwGklCRxkZlUg,2660 +tensorflow/include/external/onednn/src/cpu/cpu_deconvolution_pd.hpp,sha256=EJqxUJi4C7UHhxJcnwcI82oma5rBngYkdvrzMuIzg6c,1526 +tensorflow/include/external/onednn/src/cpu/cpu_eltwise_pd.hpp,sha256=VMw0hGnp4jEUn5RutnCiLyoavIqVcf6S0PrQksKTblc,1371 +tensorflow/include/external/onednn/src/cpu/cpu_engine.hpp,sha256=h90tOHhNO8Cdnv3sONxQA5QHB-FevW1RLwnhF55bypw,5947 +tensorflow/include/external/onednn/src/cpu/cpu_inner_product_pd.hpp,sha256=hkki-9x_6ojXYeEUB10Au9pfWkz-dpJFQe_N4QW_5bE,12493 +tensorflow/include/external/onednn/src/cpu/cpu_layer_normalization_pd.hpp,sha256=cNAsCHhzcrjFz-ap4ZToYoO5x9oO8JA8O9-8hLmwj-I,1385 +tensorflow/include/external/onednn/src/cpu/cpu_lrn_pd.hpp,sha256=xtYL4XVoWnpp0O2Xc8brZ7ZM77EUvX4YuINu3cMjcT4,1230 +tensorflow/include/external/onednn/src/cpu/cpu_memory_storage.hpp,sha256=a7YD2fAC6sWSxxCXwuwjYS40dAwgtWO7YoiMLoHNW9A,3785 +tensorflow/include/external/onednn/src/cpu/cpu_pooling_pd.hpp,sha256=RW0vufWH2muOKY-zrse2vDdVyk2aXIMv_vTBDUvqhx8,1253 +tensorflow/include/external/onednn/src/cpu/cpu_prelu_pd.hpp,sha256=6p1MwMwkgQRDsgNojQtEH-S87BQGE0b3UNR4ZzOurhY,1247 +tensorflow/include/external/onednn/src/cpu/cpu_primitive.hpp,sha256=NacCnhAiIadCSYkAmeKgc0uZwyQDIMCZGlK26k--mUY,5841 +tensorflow/include/external/onednn/src/cpu/cpu_reduction_pd.hpp,sha256=NXWqZAMn52Xfd_JXl4ahWV4ctHTV87R8b8Ahkf3eLk0,1055 +tensorflow/include/external/onednn/src/cpu/cpu_resampling_pd.hpp,sha256=tO6EOjWQMUCTb0tH5Rn14R9g2KOmDzpgQ7tgLAHTZEI,1286 +tensorflow/include/external/onednn/src/cpu/cpu_shuffle_pd.hpp,sha256=0tCSxgSHrEUOn2F_E9YRsNR07wdlWUpIxQTnzND-sEw,1249 +tensorflow/include/external/onednn/src/cpu/cpu_softmax_pd.hpp,sha256=d4JNZ9lUU3wQeC6uSoRZMMGoi7cZy82im-B3sL0PU2I,1371 +tensorflow/include/external/onednn/src/cpu/cpu_stream.hpp,sha256=G7JOmKwS7LI4h6GNOfIMHtnDheM_R1_k3WrtJmy-CDA,2004 +tensorflow/include/external/onednn/src/cpu/cpu_sum_pd.hpp,sha256=xDBVwHl33rIR8GoF9xtVy4J2R7BCkBPweTI_2Ucw_l8,1200 +tensorflow/include/external/onednn/src/cpu/dw_convolution_utils.hpp,sha256=WCYbDgWwjOIqW8QvRl44Yn8OVNxb-C_1ekAv_PlJzl8,5015 +tensorflow/include/external/onednn/src/cpu/gemm/f32/gemm_utils_f32.hpp,sha256=nBJLAGNJFNk721VI0nfccXmiWKEvCezwq-Qn76MxIxw,2383 +tensorflow/include/external/onednn/src/cpu/gemm/f32/ref_gemm_f32.hpp,sha256=tPi_cgZABHoMOKb95gnzghtKuHqnlA9NH0hycyphO8o,1355 +tensorflow/include/external/onednn/src/cpu/gemm/gemm.hpp,sha256=hzLH68TFt4v80G4JVfHMfS3NRENdnL2UYEYxK6Wr8Ew,3157 +tensorflow/include/external/onednn/src/cpu/gemm/gemm_msan_unpoison.hpp,sha256=xm_M62zloc2xVQBZx0gSCxyLBAnQimJrFU-SvHA7K60,1428 +tensorflow/include/external/onednn/src/cpu/gemm/gemm_pack.hpp,sha256=QL7zNYeMP87BBWWXsAVbd4eW236x-RP1PriPvyHRa7g,4348 +tensorflow/include/external/onednn/src/cpu/gemm/os_blas.hpp,sha256=fQQ8POIIp1e0PZ1NY9TWBF_oZ9GF5ii3-C1ij6c56ss,1909 +tensorflow/include/external/onednn/src/cpu/gemm/s8x8s32/ref_gemm_s8x8s32.hpp,sha256=VY9z-l1Bn8VHduTYZ9ZALVkabV8BXrtnhgXP7GDL450,1463 +tensorflow/include/external/onednn/src/cpu/gemm/s8x8s32/simple_gemm_s8s8s32.hpp,sha256=RcGQyJ5DzksHbU5HOOzPkFfFszaRm-F6D4VF_Hcrb88,1455 +tensorflow/include/external/onednn/src/cpu/gemm_convolution.hpp,sha256=Zt5UaKafRaba59p7ZpnRc5ItEdIdLf1POFMUNKGrx2s,9276 +tensorflow/include/external/onednn/src/cpu/gemm_convolution_utils.hpp,sha256=5tKIGseruIP9Ne4qPlqEzrfPFMQRbRdhsBMSTpKIW8w,4620 +tensorflow/include/external/onednn/src/cpu/gemm_inner_product.hpp,sha256=jIx1RzaxTkcVNWjKevKmbJh-pLK_fMomsbfVfUiF8E4,7731 +tensorflow/include/external/onednn/src/cpu/gemm_inner_product_utils.hpp,sha256=rTNuoFFG0tjXFigknwZG7NpOfBuJP_Z-xx8OYittumQ,4325 +tensorflow/include/external/onednn/src/cpu/gemm_x8s8s32x_conv_zp_src_pad_comp.hpp,sha256=wymM2KbTG3rR9N1oWPmMZqOTGgq_gaORNrMCVxmHShU,1564 +tensorflow/include/external/onednn/src/cpu/gemm_x8s8s32x_convolution.hpp,sha256=dPdNuWrB53-3IenEkjbe9Bcgfgk6i2JxazUd25pKK9k,7445 +tensorflow/include/external/onednn/src/cpu/gemm_x8s8s32x_convolution_utils.hpp,sha256=86lZ-DAlM71nDoKKB3c0ynyBT7uUHi1DRnCU5aQdjDk,2268 +tensorflow/include/external/onednn/src/cpu/gemm_x8s8s32x_inner_product.hpp,sha256=YgTWfsLeppowx7lvyjqSmPFVHnlMs96phyhsBsRn0VU,4537 +tensorflow/include/external/onednn/src/cpu/jit_utils/jit_utils.hpp,sha256=hsXcqpFBH96K4875-WbvL9L6-LxtCq8z2JzusNfyZgc,1105 +tensorflow/include/external/onednn/src/cpu/jit_utils/linux_perf/linux_perf.hpp,sha256=Y9ujWdF8i2NFQaUActi6VY4LRvVtGfZ5DqDEBk80JZg,1276 +tensorflow/include/external/onednn/src/cpu/matmul/cpu_matmul_pd.hpp,sha256=e-2FBhBuab_ljWna9yM73NOhJ0fMVuy5yfC33-05tvs,1133 +tensorflow/include/external/onednn/src/cpu/matmul/gemm_based_common.hpp,sha256=cY6Sq0AZJKPZlzar3rnSIlBM4-5qOzfutu2n8q9_Fbo,5811 +tensorflow/include/external/onednn/src/cpu/matmul/gemm_bf16_matmul.hpp,sha256=nYPeZA5EjpHYjx3Lkr5PNnNHSe0ueX2dKscOZ8XOVkQ,4113 +tensorflow/include/external/onednn/src/cpu/matmul/gemm_f32_matmul.hpp,sha256=OzgBLcjQFWWwDcoxkqLYyPtD1oTbFGx9DXY6baPHnG4,4170 +tensorflow/include/external/onednn/src/cpu/matmul/gemm_x8s8s32x_matmul.hpp,sha256=K6-t5FCCh66qDzpDI1je6j3VGXTUpYvJYd7Hn596Svg,3428 +tensorflow/include/external/onednn/src/cpu/matmul/matmul_utils.hpp,sha256=ErNvMOMRPhWnPZObbY8AgJLmrhLOA9o4PQGOj3zKdVw,6569 +tensorflow/include/external/onednn/src/cpu/matmul/ref_matmul.hpp,sha256=58BN8QC9G51_tHFHVEn7eF6F3zdDThHNRFVzHIczkpg,4126 +tensorflow/include/external/onednn/src/cpu/matmul/ref_matmul_int8.hpp,sha256=girXH_esME2L_gpzJAyeHwCWJMoeUE3lxgU7fs0rFR4,3851 +tensorflow/include/external/onednn/src/cpu/matmul/ref_sparse_matmul.hpp,sha256=5PfdOyMhOE1pNc5umIeHqU8Yl_QObqlafd61jgg0bHg,3386 +tensorflow/include/external/onednn/src/cpu/nchw_pooling.hpp,sha256=2T3Zjqbn-POSUGJqYdqAmOlNFsz-0_YuPhDg__jtmCY,7456 +tensorflow/include/external/onednn/src/cpu/ncsp_batch_normalization.hpp,sha256=Jlv0g9wpj5EA6e18xTai3AydtC6f-UveSe3xA9F5t1s,7877 +tensorflow/include/external/onednn/src/cpu/nhwc_pooling.hpp,sha256=_to5mWe2eW_eOdMHVJCaxYxn-vRtGEhdvCoFxDD3pPk,7499 +tensorflow/include/external/onednn/src/cpu/nspc_batch_normalization.hpp,sha256=8hixGmcn_uspYEO4WB5-NY0oX7IU7RkXmLWd_ymFDW0,7888 +tensorflow/include/external/onednn/src/cpu/platform.hpp,sha256=Tm9mScN7Aa3-4SbTonEZJQKK0DPEjz9GrWuHPb4JOzM,6052 +tensorflow/include/external/onednn/src/cpu/ppc64/ppc64_gemm_driver.hpp,sha256=rad0ashevhyS95sboV-RkdYbjL3brv-MpEiTsCOqJIQ,1239 +tensorflow/include/external/onednn/src/cpu/ppc64/ppc64_gemm_s8x8s32.hpp,sha256=mQnJNAvdF60r7GnqEhLqaye_39MbXwAi4wtIyNsuxMk,125193 +tensorflow/include/external/onednn/src/cpu/primitive_attr_postops.hpp,sha256=uz6WbT_LYZKxNEuo50y1iUFKynXo4hrXfOxqJ9kVQ3Q,2682 +tensorflow/include/external/onednn/src/cpu/ref_batch_normalization.hpp,sha256=36qe9uG6FmD-vzXy24bNsG50kIpUgI-FeNfrrPjSLaQ,5164 +tensorflow/include/external/onednn/src/cpu/ref_binary.hpp,sha256=v19KwOFDtfL5WCcp_Z1eyY0okXJyl1i65pI-uLIS4to,3063 +tensorflow/include/external/onednn/src/cpu/ref_concat.hpp,sha256=zxfygiyTdL6K7Lj0qfwT6qC44iaq-f6l5qsOCE0pxkI,7767 +tensorflow/include/external/onednn/src/cpu/ref_convolution.hpp,sha256=g8dKa0ksuB5CLYdmrwCqID_vNPSIltQPeZUseYXMy4Y,8088 +tensorflow/include/external/onednn/src/cpu/ref_convolution_int8.hpp,sha256=xbKCHW-63IOSXivSnrT8NQyfCd6UBvUzVfqls0h_tDo,6359 +tensorflow/include/external/onednn/src/cpu/ref_convolution_utils.hpp,sha256=QefZSfAQIJ9bkDvhTxu-HmL80u-Yrsl_7chG6xos9yM,2262 +tensorflow/include/external/onednn/src/cpu/ref_deconvolution.hpp,sha256=Ew5SNJ0ePRv2MLrkviWAjryc0z0ztD9dXFr3BUXrS1g,22832 +tensorflow/include/external/onednn/src/cpu/ref_eltwise.hpp,sha256=fBj3v_OWeBILbyFEBdpoKBFWum8ZwoIFlMPrwcwkUlo,6508 +tensorflow/include/external/onednn/src/cpu/ref_fused_convolution.hpp,sha256=GwTO7MaYtMZMDbd61OC-Zgu6rrDHs2WvSJqijOLYn5U,18121 +tensorflow/include/external/onednn/src/cpu/ref_inner_product.hpp,sha256=jdH_62MEroIM9IW7XhxYHFGCk67RsCdDo7709xY9Pmk,7011 +tensorflow/include/external/onednn/src/cpu/ref_inner_product_int8.hpp,sha256=UJdcChgkDJyx4zj2zgw2aRJrN3QXfNQVRe1LGO2_jow,3579 +tensorflow/include/external/onednn/src/cpu/ref_inner_product_utils.hpp,sha256=PC9NlIXR8hRIitEkYBSjg_H3JwKCjiBQNW40Twu-fxk,2006 +tensorflow/include/external/onednn/src/cpu/ref_io_helper.hpp,sha256=GkzJWopZUMSg3KsGoW7jF5U0atVeW_NUSTfMqv7GjRU,2639 +tensorflow/include/external/onednn/src/cpu/ref_layer_normalization.hpp,sha256=PxnhA46l795itUrcD1U6BFxymDLRyJMsq6UPXgxI2MI,4274 +tensorflow/include/external/onednn/src/cpu/ref_lrn.hpp,sha256=KzdieOQdbBno5KcquV-g2t1Ou09CQDBxhoLo-wcpYO0,4947 +tensorflow/include/external/onednn/src/cpu/ref_pooling.hpp,sha256=XvPS1Rwq7EL2twHIMEL7nW6NGIA0XEe8cyLt1IWhYpQ,5142 +tensorflow/include/external/onednn/src/cpu/ref_prelu.hpp,sha256=AeNY1dnMZwBw9Vc2gkh4_fWeXHg0h57Sialklwj-Yr8,6968 +tensorflow/include/external/onednn/src/cpu/ref_reduction.hpp,sha256=Rkwh-etUVuXQo5vTjEe3ZptTsOwSIAYS6Rq0JNw7T0o,3205 +tensorflow/include/external/onednn/src/cpu/ref_resampling.hpp,sha256=3hOacYlv1g8gwgYaRTb6k4yg-M6nBiDGuV2qfvNpgtA,3567 +tensorflow/include/external/onednn/src/cpu/ref_shuffle.hpp,sha256=YyRXmSR6LdsDjH3LD1-su7aW08BfI1Kbz5vfFoCHCv0,4171 +tensorflow/include/external/onednn/src/cpu/ref_softmax.hpp,sha256=22ugkl2BPogv5k37Vw9JhBBTK5fVuQa1uBPRBTT5-mw,7776 +tensorflow/include/external/onednn/src/cpu/ref_sum.hpp,sha256=g4FWMDh9r_s4BSrfihgyMedaej6gkxlO4iDYBRW84GE,5857 +tensorflow/include/external/onednn/src/cpu/reorder/cpu_reorder.hpp,sha256=kyRUShYLr7ZBlD-qvLnglGSmhXZpaQ7gvL6Ul0zo2MQ,4361 +tensorflow/include/external/onednn/src/cpu/reorder/cpu_reorder_pd.hpp,sha256=xm9M3U-mrEq7PZgc8wDLr1w4QKHl0DVwftAFV1TNVc0,4303 +tensorflow/include/external/onednn/src/cpu/reorder/simple_reorder.hpp,sha256=TS8jP4XyW0PBuL04cejL0eym2pCa_aH-B4cpUT2QHSc,96938 +tensorflow/include/external/onednn/src/cpu/resampling_utils.hpp,sha256=wwhutEGVylNn1gKnUdqXLDMkXwHPLtCpOM2NIl5z7sY,3333 +tensorflow/include/external/onednn/src/cpu/rnn/cpu_rnn_pd.hpp,sha256=G_YfRQqus_YFgfA2C_SBIODRwEw4Dso4OttFfRQUbOU,14263 +tensorflow/include/external/onednn/src/cpu/rnn/postgemm_dispatcher.hpp,sha256=U8aBnWXESArLrmeF5cyB_IKMR32NJ6KP3M65zu_R1tg,14264 +tensorflow/include/external/onednn/src/cpu/rnn/ref_rnn.hpp,sha256=n4QEm9dBCvxtN3pxDpmJzc8uCKeC5_vcrEsuoEvpAeM,33939 +tensorflow/include/external/onednn/src/cpu/rnn/rnn_reorders.hpp,sha256=ueCe0qhnL4kh_bv6BYUtBGUjN_JTRB8zyvmATInhjCQ,40229 +tensorflow/include/external/onednn/src/cpu/rnn/rnn_utils.hpp,sha256=6bBeC6dMipaghqmn1o3xyzV55JP8CrRrDOUS71cuohg,57584 +tensorflow/include/external/onednn/src/cpu/rv64/rvv_nchw_pooling.hpp,sha256=-3Sl6jRP7HWi-TC9NGbvzC_QMpOpj3Rd_Xa5qLSUSAc,3216 +tensorflow/include/external/onednn/src/cpu/s390x/kernel_s16s16s32.hpp,sha256=kcJPDaIZu5Mb_PouOTrB2bws0pyqdbAe60ks8LGS5Zg,8723 +tensorflow/include/external/onednn/src/cpu/s390x/pack.hpp,sha256=wDUf0BrsVisV6Xm0JW7R1ULwjyhUUFyZ9zEBdEByRlU,3980 +tensorflow/include/external/onednn/src/cpu/scale_utils.hpp,sha256=RK_mPgNWbTwUZdRsJq5yJ7b7GPEZfjnS31Tp-upULAY,1865 +tensorflow/include/external/onednn/src/cpu/simple_concat.hpp,sha256=LXw5UAQ5WEYGdN-9U3dHQJFTNzLgpJ0i0qXyEiELOXU,6270 +tensorflow/include/external/onednn/src/cpu/simple_layer_normalization.hpp,sha256=RsHoIJRDdHrHgAlOBTLQ68ppdWI4tnVA4EBuxHDjZgc,8633 +tensorflow/include/external/onednn/src/cpu/simple_q10n.hpp,sha256=OGQZIrr1Lb8p4hwXJcMDdGpy9q440iCmrLZlXj4PfoI,5219 +tensorflow/include/external/onednn/src/cpu/simple_resampling.hpp,sha256=net8R3W_jn1WMGRvlicijux8r1B6xop5nQqpiV_DRx8,5164 +tensorflow/include/external/onednn/src/cpu/simple_sum.hpp,sha256=XlPfdTy-iEReC8RmJHNV78htVS7xT19l9qaqbE_IS2U,5069 +tensorflow/include/external/onednn/src/cpu/x64/amx_tile_configure.hpp,sha256=6Wja3FWxJ181s6wxin8PijwTJuRlDcEJyfwyTFMq4xY,1179 +tensorflow/include/external/onednn/src/cpu/x64/brgemm/brgemm.hpp,sha256=mWxOQ_Y3cCCe5IuONB288hl216TXsieIIZDvrTQP9yU,11724 +tensorflow/include/external/onednn/src/cpu/x64/brgemm/brgemm_containers.hpp,sha256=_a0epVQF8Q_Ksp9N64APDz-rP1EzLCOZfXBIkVMhJGw,4244 +tensorflow/include/external/onednn/src/cpu/x64/brgemm/brgemm_types.hpp,sha256=DseY6SGfBqNa0zp3Ut1QBw9M_yr04T0ZjaN2c2md8fs,18436 +tensorflow/include/external/onednn/src/cpu/x64/brgemm/brgemm_utils.hpp,sha256=JrhkuzdOu366kuxzNXts8Pbv5iVeP_yoM2xdnbPVUxc,2646 +tensorflow/include/external/onednn/src/cpu/x64/brgemm/jit_brdgmm_kernel.hpp,sha256=nkmKougRnoVhQJk5BznM7U6ISVWHbD-gBta2Mo-Ow2c,9362 +tensorflow/include/external/onednn/src/cpu/x64/cpu_barrier.hpp,sha256=z78k7BQk7tbFFSvfiNAlM-mX_lIPHyrupbIsmVyez74,2817 +tensorflow/include/external/onednn/src/cpu/x64/cpu_isa_traits.hpp,sha256=LZjIsh0pyvWJ9kEe_kHbWrNAVFN7gMp9-v4K14rC5kg,16232 +tensorflow/include/external/onednn/src/cpu/x64/cpu_reducer.hpp,sha256=Z0L0Do5RQq3vuYwQme9M1UxE9eNEOShLOiohtRezhHM,13334 +tensorflow/include/external/onednn/src/cpu/x64/gemm/amx/jit_avx512_core_amx_copy_kern.hpp,sha256=QB9uSBzCXAC9zEHfEk0uNt3sZk6KaR5yc1QOCc2l8z0,3770 +tensorflow/include/external/onednn/src/cpu/x64/gemm/amx/jit_avx512_core_amx_gemm_kern.hpp,sha256=gBdog8VVNy3oBEVFx5h1VfTJd-al89UlD4gGjiLxLtA,1497 +tensorflow/include/external/onednn/src/cpu/x64/gemm/bf16/common_s16.hpp,sha256=ack9MNO1zSmiVT95oVEA4wQu6tbLrkhqMDtx8mulcrk,3105 +tensorflow/include/external/onednn/src/cpu/x64/gemm/bf16/jit_avx512_core_gemm_bf16bf16f32_kern.hpp,sha256=50C7VZo4idNPcMybvj_lp_PQVnaU-Stn6j_nlfwIdH0,3651 +tensorflow/include/external/onednn/src/cpu/x64/gemm/bf16/jit_avx512_core_gemv_bf16bf16f32_kern.hpp,sha256=HtHKBKHvTFo-5ZLQzQvm4aOkW3GELBkeYXrs8VtxECg,3597 +tensorflow/include/external/onednn/src/cpu/x64/gemm/f32/common_f32.hpp,sha256=lCSZpIB4NOHIXTpwa7vf7JstX_a-BCcMNvSV9Gzfr7c,6285 +tensorflow/include/external/onednn/src/cpu/x64/gemm/f32/jit_avx2_kernel_sgemm_kern.hpp,sha256=pATr45gdUxgs0gqqxBNcH7FR8xpHW48x4ZS6mk-H_Yk,27254 +tensorflow/include/external/onednn/src/cpu/x64/gemm/f32/jit_avx512_common_gemm_f32.hpp,sha256=D4OUfBQ-IR3HzUne18aE1zwUzrBUzRsuLbgnaS7dEpQ,1783 +tensorflow/include/external/onednn/src/cpu/x64/gemm/f32/jit_avx512_core_f32_copy_at_kern_autogen.hpp,sha256=665fomxWWfC41i0TvnyfqDjdJSglAo-Q13zgmPgl-eE,1301 +tensorflow/include/external/onednn/src/cpu/x64/gemm/f32/jit_avx512_core_gemm_smalln_tn_f32_kern.hpp,sha256=fQN4GV9iByo6Y7DMUPUVrN-MG_kB1oga0ucHX3B-nOw,1661 +tensorflow/include/external/onednn/src/cpu/x64/gemm/f32/jit_avx_gemm_f32.hpp,sha256=IeBFnnmk8OX1OxFK9fLaZOPhndaLujpRAuO5tiH_u3o,1733 +tensorflow/include/external/onednn/src/cpu/x64/gemm/f32/jit_avx_gemv_t_f32_kern.hpp,sha256=2yE4OydiPjD4CTGuzx2W5GbYbhMq95LUYBOO7-iFKT4,2329 +tensorflow/include/external/onednn/src/cpu/x64/gemm/f32/jit_avx_kernel_b0_sgemm_kern_autogen.hpp,sha256=bt19twfwbqFOfuALiFYwPdqpJBDTcUXWfAoQU65q2l8,1576 +tensorflow/include/external/onednn/src/cpu/x64/gemm/f32/jit_avx_kernel_sgemm_kern_autogen.hpp,sha256=BXZhiCpK8Y8jG8QPoIX_pL-gJFvu1jzfMlQmNAnFCic,1564 +tensorflow/include/external/onednn/src/cpu/x64/gemm/f32/jit_sse41_gemv_n_f32_kern.hpp,sha256=AERNRKhwXuKrZ04N99_DEZSGLvNOtmeDwV1zUPj5pPU,3206 +tensorflow/include/external/onednn/src/cpu/x64/gemm/f32/jit_sse41_gemv_t_f32_kern.hpp,sha256=7bCVM6P5bpkuzxCihogz1a7O-IpsQaHW1pgaxpFMuYY,2320 +tensorflow/include/external/onednn/src/cpu/x64/gemm/gemm_driver.hpp,sha256=BkbcHccAi8xWbGIIevvrP5TD55Y0pEeK-IvDgoG-sKw,1992 +tensorflow/include/external/onednn/src/cpu/x64/gemm/gemm_info.hpp,sha256=bwrWRQUqwk7PlcGobS-Y8snJOMCLJmn-7fvC0XhSygM,7163 +tensorflow/include/external/onednn/src/cpu/x64/gemm/gemm_pack.hpp,sha256=c5Bf7VqOTEAVks9f1Jqg_wWWE9-ILvv0TwQejjfRPTs,4207 +tensorflow/include/external/onednn/src/cpu/x64/gemm/gemm_pack_storage.hpp,sha256=oRCpZJ7geRiAGJJCr7a9VgI5IIHZRw8pcfciLttARjU,12472 +tensorflow/include/external/onednn/src/cpu/x64/gemm/gemm_partition.hpp,sha256=riv9AUf90MmCoMRLeLjce8pUsqQvEdhfzl08WoAfd5o,9235 +tensorflow/include/external/onednn/src/cpu/x64/gemm/gemm_threading.hpp,sha256=6xa1BI3PCpSHXLskAdmyTyiLEKNNFLlMuoV40d8sypc,3808 +tensorflow/include/external/onednn/src/cpu/x64/gemm/gemm_utils.hpp,sha256=He_-euwC3q4rJdaTmUzrvBCrPs8ABeP2NOW1oe8yAkY,6400 +tensorflow/include/external/onednn/src/cpu/x64/gemm/gemv_driver.hpp,sha256=4Qrpv9hSLcOj5liUgWJsAX0CSSiMSEqaf4buri5x5Do,1205 +tensorflow/include/external/onednn/src/cpu/x64/gemm/s8x8s32/common_u8.hpp,sha256=6ENSY3YRCz74rf14tp7MNN8TRaQT4bMBCrQrLPkDlUc,14413 +tensorflow/include/external/onednn/src/cpu/x64/gemm/s8x8s32/jit_avx2_gemm_s8u8s32_kern.hpp,sha256=AxNFIo0adEFkU3pueccKrlKbYw2Va9b7US-r5QPzb9c,3300 +tensorflow/include/external/onednn/src/cpu/x64/gemm/s8x8s32/jit_avx512_core_gemm_s8u8s32_kern.hpp,sha256=boovvAat5xHUFuwyniPGiPrjvIg8dyA5hLRoc_xCg9Q,3303 +tensorflow/include/external/onednn/src/cpu/x64/gemm/s8x8s32/jit_avx512_core_gemv_s8x8s32.hpp,sha256=UJTuh9VBff-uiPp5qu6ZvfRPQvknXn0QvfxLpwWtMt0,1200 +tensorflow/include/external/onednn/src/cpu/x64/gemm/s8x8s32/jit_avx512_core_kernel_gemv_s8x8s32_kern.hpp,sha256=NzPpwJk8QnCrF8V-RCztKaarSGd8iPw0P9XxvQiRm30,3150 +tensorflow/include/external/onednn/src/cpu/x64/gemm_bf16_convolution.hpp,sha256=KabYmngLBFkR7mOoS5TmydCsVkPz0kocAIJV7oQCHJg,15028 +tensorflow/include/external/onednn/src/cpu/x64/gemm_bf16_inner_product.hpp,sha256=XM0Zs30jCdI3VBIuXpd_HwsNYNNj0I80-lyprKDbXvQ,11543 +tensorflow/include/external/onednn/src/cpu/x64/injectors/injector_utils.hpp,sha256=jQHeTeDRQ299GryOvmmQTjRHZF5rUSrYqujWbfSSnMo,3056 +tensorflow/include/external/onednn/src/cpu/x64/injectors/jit_uni_binary_injector.hpp,sha256=l3Fx1rLx8N6GqtrWqzPKgBVDo3Lw5v5GYLge7U0R_pU,25359 +tensorflow/include/external/onednn/src/cpu/x64/injectors/jit_uni_eltwise_injector.hpp,sha256=HiYGnYpW1jV4J7dMRIper52idBRMCQl5VgipHvHkd0Y,14009 +tensorflow/include/external/onednn/src/cpu/x64/injectors/jit_uni_postops_injector.hpp,sha256=EOYjXJ3lNrdi2iPar2ecWnL8PQoVV-DquPhUDPuFEoE,6685 +tensorflow/include/external/onednn/src/cpu/x64/ip_convolution.hpp,sha256=3m-Zx7yu0xaPwH5iqQZCt4CFB0ybzNCziTA43SyPOYM,16396 +tensorflow/include/external/onednn/src/cpu/x64/jit_avx2_1x1_conv_kernel_f32.hpp,sha256=dU18v4hLOee_XAPtQ72T_01xLB_GpHX9CilpO9P0rsc,3814 +tensorflow/include/external/onednn/src/cpu/x64/jit_avx2_1x1_convolution.hpp,sha256=jAYDMAmhQfFwXKaQRNd_apOuQIb1TE1zIQlpb4AO2jE,25404 +tensorflow/include/external/onednn/src/cpu/x64/jit_avx2_conv_kernel_f32.hpp,sha256=lT4xnG0T0taGL-WeFzsxrWLf94qmOfkhU55c-GwUK_8,13017 +tensorflow/include/external/onednn/src/cpu/x64/jit_avx2_convolution.hpp,sha256=-pkbtSLcOYSt3SilXyF153gWJy85o2NJq41unRR0af4,14745 +tensorflow/include/external/onednn/src/cpu/x64/jit_avx512_common_1x1_conv_kernel.hpp,sha256=MOuUHclxGmcFE0d-bMOoJvShSOUVSg_fkipUvr7SS4E,4535 +tensorflow/include/external/onednn/src/cpu/x64/jit_avx512_common_1x1_convolution.hpp,sha256=HkL8hoBUwjHSBFufzC6DTBDwt47rGwxIZSaET0Ux5Uk,23478 +tensorflow/include/external/onednn/src/cpu/x64/jit_avx512_common_conv_kernel.hpp,sha256=SzP2fLxvVoMqKjHf38WbHXWSutprwZnuHeVhGwfim_4,16953 +tensorflow/include/external/onednn/src/cpu/x64/jit_avx512_common_convolution.hpp,sha256=3kHLp0bu_eqGvCZqVeq6Sjh1U5njgYpQnMU4sapP9aw,11201 +tensorflow/include/external/onednn/src/cpu/x64/jit_avx512_core_amx_1x1_conv_kernel.hpp,sha256=b4horovNRdFxjKwGJQKAhnWnCGkQ1Ij3ii0kcmYr3MY,6409 +tensorflow/include/external/onednn/src/cpu/x64/jit_avx512_core_amx_1x1_convolution.hpp,sha256=xsByPNHWajY7kJmUSqZHgiA2yeDGtWUFhMeA-fk4yY0,5471 +tensorflow/include/external/onednn/src/cpu/x64/jit_avx512_core_amx_conv_kernel.hpp,sha256=hgO7yEnM9O0Fnj75YSLNa9tRRIDmkKLfml6y4ArkYWo,29130 +tensorflow/include/external/onednn/src/cpu/x64/jit_avx512_core_amx_conv_utils.hpp,sha256=R-ZUmVYqz0MJqhyQyFT0cPGC4a-OUVzTNfpHmRYKs3Q,13397 +tensorflow/include/external/onednn/src/cpu/x64/jit_avx512_core_amx_convolution.hpp,sha256=ST8Wd_ARBM7XoZHjVGlg2EaqPRS9Js--lGzv302PQBw,13783 +tensorflow/include/external/onednn/src/cpu/x64/jit_avx512_core_amx_deconvolution.hpp,sha256=N7yosG4uyzy6N3Wv2XQsI7uPM4BX2YEU5M5bw3g9ff0,4802 +tensorflow/include/external/onednn/src/cpu/x64/jit_avx512_core_bf16_1x1_conv_kernel.hpp,sha256=ZGuzuzz81rc1BkB_qMwWBGNPvyMRa9_ElfXZf7afq18,8220 +tensorflow/include/external/onednn/src/cpu/x64/jit_avx512_core_bf16_1x1_convolution.hpp,sha256=sIkLjpeozee7eMu1hK6IH9FzG81XO988h7FouGRAqG4,24910 +tensorflow/include/external/onednn/src/cpu/x64/jit_avx512_core_bf16_conv_kernel.hpp,sha256=PobDMpTOHBdgYSSbpmQDXXkpm5mFde72LWdfXBuFaVE,27078 +tensorflow/include/external/onednn/src/cpu/x64/jit_avx512_core_bf16_convolution.hpp,sha256=Xq_3AnfKsicB-MUKfbW9x9SYv9BlBlfm-pj9PwKKwaw,11179 +tensorflow/include/external/onednn/src/cpu/x64/jit_avx512_core_bf16_dw_conv_kernel.hpp,sha256=pvsJvJLsPsMpnrINsXtCaLSXKcqBBzFTCNldex6GdWI,11579 +tensorflow/include/external/onednn/src/cpu/x64/jit_avx512_core_bf16cvt.hpp,sha256=DaYA6PLwzsiEQHvNgAURoH2BRBi0dQslX9S3xq1jnU0,13538 +tensorflow/include/external/onednn/src/cpu/x64/jit_avx512_core_fp16cvt.hpp,sha256=WOkyduogK0CpjI1h31pKaPlPh0eD9IAt-HLbjAnbnxw,2610 +tensorflow/include/external/onednn/src/cpu/x64/jit_avx512_core_resampling.hpp,sha256=a6qL7Vc6ljSRM2TcBrb877wd1U6q8DE_DjF0RQX5COI,2322 +tensorflow/include/external/onednn/src/cpu/x64/jit_avx512_core_x8s8s32x_1x1_conv_kernel.hpp,sha256=aZjcer_ma7knx_fmKaQjm36MTLfr2PnlhyFYHpoE5yQ,8421 +tensorflow/include/external/onednn/src/cpu/x64/jit_avx512_core_x8s8s32x_1x1_convolution.hpp,sha256=c7oAOoTqIr1_DYH8n283qBXubkMy9ft4XPwO2fb8qYY,14368 +tensorflow/include/external/onednn/src/cpu/x64/jit_avx512_core_x8s8s32x_1x1_deconvolution.hpp,sha256=icHj0sZY5qRROvxKzF721-triGi-cq6tMwvsQ9Rali8,6053 +tensorflow/include/external/onednn/src/cpu/x64/jit_avx512_core_x8s8s32x_conv_kernel.hpp,sha256=fKC-6DgXEHGdL32yj0--pa35_HNxjLU43aCP_bETZfw,11196 +tensorflow/include/external/onednn/src/cpu/x64/jit_avx512_core_x8s8s32x_convolution.hpp,sha256=36kS6hQaz3kMkB6sLi54j6HVIR2ydOGGLFq4ZW9CsCc,5456 +tensorflow/include/external/onednn/src/cpu/x64/jit_avx512_core_x8s8s32x_deconvolution.hpp,sha256=0rnd7zaZvKEraAguBM2r00Sms9GY0QAxcfToSICJ7Bo,12816 +tensorflow/include/external/onednn/src/cpu/x64/jit_brdgmm_dw_conv.hpp,sha256=vi0m4sNS5YH5PwCxBcu-I9jsoYiGXKgJboQHetCzGks,2183 +tensorflow/include/external/onednn/src/cpu/x64/jit_brgemm_1x1_conv.hpp,sha256=lUjJ8pSBYP29nB3uyxTGRD-SRyRc2XV29xTuRoHU_aE,6273 +tensorflow/include/external/onednn/src/cpu/x64/jit_brgemm_conv.hpp,sha256=7uZe6MsZk3Rqyd2YalTPpisC9AtyZ7LYeiv-bi9GIX8,12069 +tensorflow/include/external/onednn/src/cpu/x64/jit_brgemm_conv_bwd.hpp,sha256=OdODv1PuQ1pLcM6x7y38an0_n1nK4QoIyVdFreTxPoc,2427 +tensorflow/include/external/onednn/src/cpu/x64/jit_brgemm_conv_bwd_strided.hpp,sha256=uATywFJ3kcC_h1PlzeHQbjZ-3vZLqp58soFu9OGQsR4,8516 +tensorflow/include/external/onednn/src/cpu/x64/jit_brgemm_conv_bwd_trans_kernel.hpp,sha256=yRblbzqUSgfL9sMB1bq5Wn-TsHHaT_U2bQhsgCmST2c,3077 +tensorflow/include/external/onednn/src/cpu/x64/jit_brgemm_conv_bwd_utils.hpp,sha256=3Lb46SeVoJzDpzHTwBEzhhutjv3EoPU7PLEEx62NBqc,2535 +tensorflow/include/external/onednn/src/cpu/x64/jit_brgemm_conv_bwd_w.hpp,sha256=CcKnpR-v0a4K6C9Qu-LqAPYuxpMoPmK7YznJ1C_bTJY,8326 +tensorflow/include/external/onednn/src/cpu/x64/jit_brgemm_conv_comp_pad_kernel.hpp,sha256=GrmLhHiSuUVwaWx_yjRPzoZQJuMqsTvX17TmvMH_zRY,4169 +tensorflow/include/external/onednn/src/cpu/x64/jit_brgemm_conv_trans_kernel.hpp,sha256=9oI_glxOo8egNuAs77Dbq--MhUckPTjeactUHqQE8wc,3466 +tensorflow/include/external/onednn/src/cpu/x64/jit_brgemm_conv_utils.hpp,sha256=W86PtgqPyJh1qxj8SpgY3WiTyo8LH4T4X0IZW5_sUFQ,2657 +tensorflow/include/external/onednn/src/cpu/x64/jit_brgemm_deconv.hpp,sha256=fRBe7ceq8Ak4EWrXU8fhbAZYJ-OAPmE3Y-a8k2xsGHQ,3466 +tensorflow/include/external/onednn/src/cpu/x64/jit_brgemm_inner_product.hpp,sha256=pB59yI0qQ_Z1cdwHDkPgBsrC3qeUu0U8i77VdNGTDoE,26799 +tensorflow/include/external/onednn/src/cpu/x64/jit_brgemm_inner_product_utils.hpp,sha256=dT4FnM_skBvD3UbAElPWZOnRHeAVAlqL1styUAfYVQg,4746 +tensorflow/include/external/onednn/src/cpu/x64/jit_brgemm_post_ops.hpp,sha256=YzpgcTSOuAcU9Y1QvB7cX9IM0pNGQn9UyPLOH9ZNM20,41713 +tensorflow/include/external/onednn/src/cpu/x64/jit_brgemm_primitive_conf.hpp,sha256=7bZeipuexMxnSika-qmcbuK2cqg3nbhFlNHzCA0KVYw,2646 +tensorflow/include/external/onednn/src/cpu/x64/jit_brgemm_transpose_utils.hpp,sha256=-heZSDL4ObsHmocLgE_cKIAS3srHi56kJU8MaY-KCjg,7206 +tensorflow/include/external/onednn/src/cpu/x64/jit_gemm_inner_product_utils.hpp,sha256=T2_FMNLK8VkpQSgv8oC0JxqVmU80wGyu1WvheMH9fQY,1605 +tensorflow/include/external/onednn/src/cpu/x64/jit_gemm_x8s8s32x_conv_zp_src_pad_comp.hpp,sha256=KA8tIO2d_93lHNe3jfpWAAlH8j3H6-D74FM6GjwSoyI,4846 +tensorflow/include/external/onednn/src/cpu/x64/jit_gemm_x8s8s32x_convolution_utils.hpp,sha256=ML1G-LIla_O4CJdsM8gJr65WocW9tGM43rVlhjT0I5A,1477 +tensorflow/include/external/onednn/src/cpu/x64/jit_generator.hpp,sha256=cRntXjHU1dtVu2QOAO9lO3Znk1riBKm6Y7PeYVycMMI,91372 +tensorflow/include/external/onednn/src/cpu/x64/jit_primitive_conf.hpp,sha256=9hZYWTGOIgoN014OW-9t9RjVl8Z64Dyca5RlOp3MwcY,25457 +tensorflow/include/external/onednn/src/cpu/x64/jit_sse41_1x1_conv_kernel_f32.hpp,sha256=OXZHaVARqJRUXcS4sO-Hfw3QlkQOcUoU4IHF6loNLpA,3488 +tensorflow/include/external/onednn/src/cpu/x64/jit_sse41_1x1_convolution.hpp,sha256=u9w2ThMt6qm567I2kprsa2vqp6NrhhO69CgIFD3F4yE,12361 +tensorflow/include/external/onednn/src/cpu/x64/jit_sse41_conv_kernel_f32.hpp,sha256=iQGbn6nXDV1ps_17m1ADIjmR9VlG0oVIk2oEaut4W_E,4523 +tensorflow/include/external/onednn/src/cpu/x64/jit_sse41_convolution.hpp,sha256=h2aCaF-MWNt-gWDobB8UCJZ9NLFfSVRH67HzERG-GvQ,5098 +tensorflow/include/external/onednn/src/cpu/x64/jit_transpose_utils.hpp,sha256=QlJr2Bc0mqfxjOzvRM57GT4z2lM-fd8pDoynRYKgFzA,4181 +tensorflow/include/external/onednn/src/cpu/x64/jit_uni_1x1_conv_utils.hpp,sha256=r6e71AQtpWkT7byMCXEdlcMsnz18vyl5_uQO-NPeAxg,25787 +tensorflow/include/external/onednn/src/cpu/x64/jit_uni_batch_normalization.hpp,sha256=2L6KK9q_4n8bLzh9aCTVVtyQkrLH59ClIZprDkxMTDs,4499 +tensorflow/include/external/onednn/src/cpu/x64/jit_uni_batch_normalization_s8.hpp,sha256=IEhL386HPL8mpnKB1RCPJchZI0bBVcoUZt5VWNfMvZc,2315 +tensorflow/include/external/onednn/src/cpu/x64/jit_uni_binary.hpp,sha256=8cmkQVnWqrQhticymnVfNIN7O-ShK2svP5uMe_sqNRg,4400 +tensorflow/include/external/onednn/src/cpu/x64/jit_uni_binary_kernel.hpp,sha256=L00sSRBxA4rBb-aRv7U1E0hqOz9V5Uz5LarvOhyy8dk,5781 +tensorflow/include/external/onednn/src/cpu/x64/jit_uni_convert_xf16.hpp,sha256=euOxTmlkLdD4UwjGHSmvPgJ1qAKZq1nSCl0ekW1mEiI,8798 +tensorflow/include/external/onednn/src/cpu/x64/jit_uni_deconv_zp_pad_str_kernel.hpp,sha256=FXAAZPTjWkcczR6HhqcLzsbbfV64zogwpSsyXE3PgpI,3605 +tensorflow/include/external/onednn/src/cpu/x64/jit_uni_dw_conv_kernel_f32.hpp,sha256=HWMQNROOKz9sr0WkEtBbGIMM1GS0Bk1OxiVe3I3hl8E,12437 +tensorflow/include/external/onednn/src/cpu/x64/jit_uni_dw_conv_kernel_utils.hpp,sha256=uXfS8R8nKMv8d05P2st49NlgCSyJmKUFPMzdQ_AyStc,5044 +tensorflow/include/external/onednn/src/cpu/x64/jit_uni_dw_convolution.hpp,sha256=saLVzsLsDOeqaTC7tyxh0cwU2RJ1UwAN294YZfBKR4U,11528 +tensorflow/include/external/onednn/src/cpu/x64/jit_uni_eltwise.hpp,sha256=qQVLsoJ72Xx8Z3fAvWpyTChqavPFz4jiD9BQeiDj3Is,3314 +tensorflow/include/external/onednn/src/cpu/x64/jit_uni_eltwise_int.hpp,sha256=J02mg78rta_r-ak3bMqyFR9-5dea3E8GNBZZg09nR0Y,2115 +tensorflow/include/external/onednn/src/cpu/x64/jit_uni_i8i8_pooling.hpp,sha256=9AIe5NQBsWSOTYI3YeuPpKVJ8lne0FgHvgdU2cXPnuE,3501 +tensorflow/include/external/onednn/src/cpu/x64/jit_uni_layer_normalization.hpp,sha256=GqblGF-av_lpzof9QyFoF5D-WY5ayswTW2IXer1ZcCc,14956 +tensorflow/include/external/onednn/src/cpu/x64/jit_uni_pool_kernel.hpp,sha256=b4_rduWy13dUG4GnLyP5sOTrUEjcmRP3PfAcCkIVUZ4,8882 +tensorflow/include/external/onednn/src/cpu/x64/jit_uni_pooling.hpp,sha256=_KiTlvU9u9eikjOiz8ZEOh5iXETKbv7NsXtInTw0-Z0,6747 +tensorflow/include/external/onednn/src/cpu/x64/jit_uni_reduction.hpp,sha256=F245I-SWHoSJyXBmUqZIAj16c27EY9HUqnxXNcuRM4g,2174 +tensorflow/include/external/onednn/src/cpu/x64/jit_uni_reduction_kernel.hpp,sha256=QxuRXlyG8-UymuaqVUWw-O1lZeZM9cMWq4BIeWb1ZMU,5678 +tensorflow/include/external/onednn/src/cpu/x64/jit_uni_reorder.hpp,sha256=WQowWaR11EVB6epgJbwCybAUrNbAFk3F5N8q3Nys6CY,10261 +tensorflow/include/external/onednn/src/cpu/x64/jit_uni_resampling.hpp,sha256=srBiI9qN3_Ob1KvLztG1FaO7-0HRndJl0KAzhobYQoI,6083 +tensorflow/include/external/onednn/src/cpu/x64/jit_uni_resampling_kernel.hpp,sha256=hoSqcEmU-7TbK-CRxjgYk7pnsr__d4KEjs-uwwQuGHI,8101 +tensorflow/include/external/onednn/src/cpu/x64/jit_uni_softmax.hpp,sha256=SDOINRUkjfZ7q3dN8NcFLu0h7B-28gwkS3pCnILvRd8,12000 +tensorflow/include/external/onednn/src/cpu/x64/jit_uni_tbb_batch_normalization.hpp,sha256=t7Yblbeafy_x6gRGmbN8we_jFA4lcEuzN3_W45_ydL0,4493 +tensorflow/include/external/onednn/src/cpu/x64/jit_uni_x8s8s32x_1x1_conv_kernel.hpp,sha256=Xb-i9xmgyt92WfkYyJautlKY-fjeJ8enynvwyRsrQaw,7269 +tensorflow/include/external/onednn/src/cpu/x64/jit_uni_x8s8s32x_1x1_convolution.hpp,sha256=SibciLDJm9d9Df8OY9fAGo3KPWA0OcV7tJkG-BashBw,16822 +tensorflow/include/external/onednn/src/cpu/x64/jit_uni_x8s8s32x_1x1_deconvolution.hpp,sha256=LCj7fycKjyL9BKjnzaCJrevHpssubZWn6KdqDTfuUJU,6013 +tensorflow/include/external/onednn/src/cpu/x64/jit_uni_x8s8s32x_conv_kernel.hpp,sha256=EyJqtju0MK07OLAFvsNd1LmOGI5tpEWPhWw8A56Yhdc,9074 +tensorflow/include/external/onednn/src/cpu/x64/jit_uni_x8s8s32x_convolution.hpp,sha256=GctZbRfzso3Rsk9JywUFtaWrd9cYAeEDdAJ8bNN6tgk,5408 +tensorflow/include/external/onednn/src/cpu/x64/jit_uni_x8s8s32x_deconvolution.hpp,sha256=tCiLH0oHn7Fj3ypsNgRt1Js_3OTlp1rQ6dTu77Msoi0,8024 +tensorflow/include/external/onednn/src/cpu/x64/jit_uni_xf16_sum.hpp,sha256=FNXaRkk44Lr149mzb17M2yo6J1bqsguT4SdZdxiPb6U,11959 +tensorflow/include/external/onednn/src/cpu/x64/lrn/jit_avx512_common_lrn.hpp,sha256=vbQsXKPTeZTOv1-ZXMgyA4Ik-gKNJ63Ec0TElp5su3A,4060 +tensorflow/include/external/onednn/src/cpu/x64/lrn/jit_avx512_common_lrn_bwd_base.hpp,sha256=Xb4_8MUMpF179LDLa9SiRT9kAHf2N65WbwvXsQUD5lI,3631 +tensorflow/include/external/onednn/src/cpu/x64/lrn/jit_avx512_common_lrn_bwd_blocked.hpp,sha256=-53i3PW26Z4-WqQAGf-MI8LRnj_1sBqgq_QnseazU4s,2412 +tensorflow/include/external/onednn/src/cpu/x64/lrn/jit_avx512_common_lrn_bwd_nhwc.hpp,sha256=os8MXXUzwhXWk86wvLcCelhUCGDEDRHIjxXsnbayRvo,3002 +tensorflow/include/external/onednn/src/cpu/x64/lrn/jit_avx512_common_lrn_fwd_base.hpp,sha256=DzQG4DlUGHWrDDSegrzzExe7cXeK_oK3Cs7Bp53JCfA,3783 +tensorflow/include/external/onednn/src/cpu/x64/lrn/jit_avx512_common_lrn_fwd_blocked.hpp,sha256=0-hCGxUUfhZUQE2noTTjbbl0O7G_0o4kDnZijlo7lZM,2145 +tensorflow/include/external/onednn/src/cpu/x64/lrn/jit_avx512_common_lrn_fwd_nhwc.hpp,sha256=d5QMGc0QY8MY3Kb1LqPndbmBunW_qP319BXc8C0cDaI,2810 +tensorflow/include/external/onednn/src/cpu/x64/lrn/jit_avx512_common_lrn_utils.hpp,sha256=IqDtyQ8JB8tlBRcatlCn8ux6cZY12Kc4wZFzEE4768g,1489 +tensorflow/include/external/onednn/src/cpu/x64/lrn/jit_uni_lrn.hpp,sha256=0FtS2rCoD7YrqFUNmXcdVzNuAV2pD1CNXe6E40d-hZ8,3299 +tensorflow/include/external/onednn/src/cpu/x64/lrn/jit_uni_lrn_kernel.hpp,sha256=WQCKIGOHvJHikE4YL3GM3GZ2EYKVokl26T0tac3tlgs,9879 +tensorflow/include/external/onednn/src/cpu/x64/lrn/lrn_avx512_blocked_executor.hpp,sha256=DD6tA-wRTmwy9NVnBof00rvrvNHrILHLw9fC39bkG9k,12880 +tensorflow/include/external/onednn/src/cpu/x64/lrn/lrn_avx512_nhwc_executor.hpp,sha256=hx1HJMK_0i6EuTQrxiZ4laxAimy9nNM63SJZAOlZboI,5087 +tensorflow/include/external/onednn/src/cpu/x64/lrn/lrn_executor.hpp,sha256=XYO29Lr5L5Cp6gYEbO8-7aSVong_GaiTzen_6p8X_dQ,1258 +tensorflow/include/external/onednn/src/cpu/x64/lrn/lrn_executor_factory.hpp,sha256=ZeAvLJgGP4bGsZgfN_xBRQkZigbq5bvOH1FkHcNFo7Q,2692 +tensorflow/include/external/onednn/src/cpu/x64/matmul/brgemm_matmul.hpp,sha256=lfHaZdCotuxasSO448RX7r9MJzFjglaFrofpCog79so,5569 +tensorflow/include/external/onednn/src/cpu/x64/matmul/brgemm_matmul_copy_utils.hpp,sha256=G7mNGA7NfsZ1MNlIvK28tIatj7ACeGdy9f0RKPPicZI,2664 +tensorflow/include/external/onednn/src/cpu/x64/matmul/brgemm_matmul_reorders.hpp,sha256=rWJ3KzaMpTpoiI1Y5uplYmtVh4gDndHRnvrCfkGp37w,2544 +tensorflow/include/external/onednn/src/cpu/x64/matmul/brgemm_matmul_utils.hpp,sha256=r2xHmp5N9Ba0Xnqj49TkVcb4QmUjXoGkAaAmMf0EB7M,10654 +tensorflow/include/external/onednn/src/cpu/x64/matmul/jit_uni_sparse_matmul.hpp,sha256=HU8FtQ9nYOSWnSibUyKE08cNdEPTb6oa0VL_Dmy-f10,3145 +tensorflow/include/external/onednn/src/cpu/x64/prelu/jit_prelu_backward.hpp,sha256=-gF6h5jC98hB5FPe-XpQLn0rTrAvED-m9WdpUuuoU9Q,2524 +tensorflow/include/external/onednn/src/cpu/x64/prelu/jit_prelu_base_kernel.hpp,sha256=oqcBPebsCuZFPYPbPn2bgJ8egpnu0yYHNm6bmWRB5fM,2390 +tensorflow/include/external/onednn/src/cpu/x64/prelu/jit_prelu_forward.hpp,sha256=z_SVcToNvxtP_Uj_K7jv6dmqkoZG_a0V6yTMswM0BfM,1851 +tensorflow/include/external/onednn/src/cpu/x64/prelu/jit_prelu_reduction_kernel.hpp,sha256=Hs52pmA0LyoSVVughJ9vsYNvZwRcHi_lv9nXtI7exJQ,3626 +tensorflow/include/external/onednn/src/cpu/x64/prelu/jit_prelu_utils.hpp,sha256=3_yvCZGRmwn4zMTtGERfQeVpEUDgIokXDPYhC1pAlIA,2001 +tensorflow/include/external/onednn/src/cpu/x64/prelu/jit_uni_prelu_backward_kernel.hpp,sha256=nDWoQjPDdMi79ZzeqXoGuR4sWEdHLHe2vUNYkuOmVns,3885 +tensorflow/include/external/onednn/src/cpu/x64/prelu/jit_uni_prelu_forward_kernel.hpp,sha256=VTmKQlhR-p9_IPCmylhTlxj3sgyE3NZ1reKUaBmwMQs,3675 +tensorflow/include/external/onednn/src/cpu/x64/rnn/brgemm_cell_common_bwd.hpp,sha256=aIe7b-7OHb8Wfvkj2HPFyJJDauNTKLy4jnbk9fb84m8,9562 +tensorflow/include/external/onednn/src/cpu/x64/rnn/brgemm_cell_common_fwd.hpp,sha256=YWTDoLFmTqI_qK2PsonyC12CZhGwdsZGqvU7XbQcVxs,10425 +tensorflow/include/external/onednn/src/cpu/x64/rnn/brgemm_cell_common_reorders.hpp,sha256=oZ2UYesdbFUHfKBxvbh1Usfi8sAiwlO_kNjLOoGRfNo,1607 +tensorflow/include/external/onednn/src/cpu/x64/rnn/brgemm_cell_common_utils.hpp,sha256=k3CMdgLEEfViftw50oKViVEK5C85_Bs07BBzoyjxMOs,1504 +tensorflow/include/external/onednn/src/cpu/x64/rnn/jit_brgemm_transpose_single_row.hpp,sha256=eN1QDQUcmYHA-bE9Jpr_U9Pjr5BOSUO37rEJJCRxx5M,2458 +tensorflow/include/external/onednn/src/cpu/x64/rnn/jit_diff_weights_peephole.hpp,sha256=Whp5M0zhUqpaNe7sWbtTt97K0kyXvSwB6-xvumLo_aA,2500 +tensorflow/include/external/onednn/src/cpu/x64/rnn/jit_gates_reduction.hpp,sha256=J5Q9itZ4Dvkvu2z656KduIliIU4uirx5MJTm46Josjg,2764 +tensorflow/include/external/onednn/src/cpu/x64/rnn/jit_uni_gru_cell_postgemm_1_bwd.hpp,sha256=BPmnzlmuyJN8f5R9h5caAkW2Eb9_j3JSIXyju2_dSrg,12436 +tensorflow/include/external/onednn/src/cpu/x64/rnn/jit_uni_gru_cell_postgemm_1_fwd.hpp,sha256=ybUIQMmZopvuCvaOJw0o2NqQQNuG01zQ6PTh-viG5_s,13202 +tensorflow/include/external/onednn/src/cpu/x64/rnn/jit_uni_gru_cell_postgemm_2_bwd.hpp,sha256=8lBayHef_UypLs3Bd2MLbw7WioXDMfdf5aijwyZQoUU,8549 +tensorflow/include/external/onednn/src/cpu/x64/rnn/jit_uni_gru_cell_postgemm_2_fwd.hpp,sha256=j1EXTq9zxxwg6IE_7OmocYeBOaiKBOdqLHbnA2_du4o,14785 +tensorflow/include/external/onednn/src/cpu/x64/rnn/jit_uni_gru_lbr_cell_postgemm_bwd.hpp,sha256=N3lY3bO06GBNxqvT-MFDgJMpZS3w3BA0Gn1UHVg0LVw,15689 +tensorflow/include/external/onednn/src/cpu/x64/rnn/jit_uni_gru_lbr_cell_postgemm_fwd.hpp,sha256=9YRiAji2_k9SZAC6iPge2Kwc2mZQ5btDgFSCAQ3ZsDE,12881 +tensorflow/include/external/onednn/src/cpu/x64/rnn/jit_uni_lstm_cell_postgemm.hpp,sha256=YKhmmVBAQXa6_bxIoe2vzv5RwS63yHEmZ9APnuzLCWo,5917 +tensorflow/include/external/onednn/src/cpu/x64/rnn/jit_uni_lstm_cell_postgemm_bwd.hpp,sha256=FUrGlpK5wvE4j8PhCq_FLsRWjvmSXuoGYMfvBGMjfXw,16492 +tensorflow/include/external/onednn/src/cpu/x64/rnn/jit_uni_lstm_cell_postgemm_fwd.hpp,sha256=pwRoVBVk29QdlMMGc-mquCLYXwHbyqLYuNweCjMj5YU,21538 +tensorflow/include/external/onednn/src/cpu/x64/rnn/jit_uni_lstm_cell_projection_postgemm_fwd.hpp,sha256=sc0yhDzCx2Y63rQInbv8_NoMNcMiHXDZoO6lVcpmrLA,6516 +tensorflow/include/external/onednn/src/cpu/x64/rnn/jit_uni_rnn_cell_postgemm_bwd.hpp,sha256=aWlvBFXxJBcVCHII6BY-1UbUOGd4HdogKtA-bpOUfs0,9299 +tensorflow/include/external/onednn/src/cpu/x64/rnn/jit_uni_rnn_cell_postgemm_fwd.hpp,sha256=kwu8NGmY__XytC5MNwCVN4gdladTvQ5bJycG-AJMy7k,9194 +tensorflow/include/external/onednn/src/cpu/x64/rnn/jit_uni_rnn_common_postgemm.hpp,sha256=AN5fRvfUmB1xbZJ35uullhEvuaNdBuLlKCCkCoIsHu4,38212 +tensorflow/include/external/onednn/src/cpu/x64/rnn/rnn_brgemm_utils.hpp,sha256=JFZZds9V8B0V8odDjAtY13UbuQAv6EQu9ephmhFxJhA,11004 +tensorflow/include/external/onednn/src/cpu/x64/shuffle/jit_uni_shuffle.hpp,sha256=kwQG9uDacWHRwIEgsqJbyHhZ5iUS51aPpxNakBobaNQ,2103 +tensorflow/include/external/onednn/src/cpu/x64/shuffle/jit_uni_shuffle_kernel.hpp,sha256=Y75EO9C3jqh5jw44Cz48BaPkLHra_Q7lJWtiK0_GXxg,3682 +tensorflow/include/external/onednn/src/cpu/x64/utils/jit_io_helper.hpp,sha256=EQHnFklOUpKza5cILk_PA532iN-3linwoWYS6B39D_4,10030 +tensorflow/include/external/onednn/src/cpu/x64/xbyak/xbyak.h,sha256=gdPF1vfQoiBYlulYldrg5MCkr1Y-MPWxFCJef7le6-A,102227 +tensorflow/include/external/onednn/src/cpu/x64/xbyak/xbyak_bin2hex.h,sha256=wBbczf7V0IGwn9-_Z-vj2VpDmCjf6e_rhnf3fJU2ypQ,6685 +tensorflow/include/external/onednn/src/cpu/x64/xbyak/xbyak_mnemonic.h,sha256=9S3t58b78b-EdseofQoj_mxis0A26KKTpdp9mJO-5Y8,255849 +tensorflow/include/external/onednn/src/cpu/x64/xbyak/xbyak_util.h,sha256=cwx8pYUmBK-9SOmZb6bc64iVhxlbbcqKOj3QYfTz5Eo,34966 +tensorflow/include/external/onednn/src/cpu/zero_point_utils.hpp,sha256=jAKS1SEHovFGZ59UNd3lWDNjIubaYqzmTLSlhXNBQCI,3541 +tensorflow/include/external/org_brotli/LICENSE,sha256=PRgACONpIqTo2uwRw0x68mT-1ZYtB5JK6pKMOOhmPJQ,1084 +tensorflow/include/external/org_sqlite/sqlite3.h,sha256=ZekyJxvJsDf7VgRTWBlbPJC5Ea0Ska4u-Yr4JuoTf3A,628463 +tensorflow/include/external/org_sqlite/sqlite3ext.h,sha256=UaUesXYS1_g31QeR8qdXS5Czq0N0bBqykI3GFTyoERM,37831 +tensorflow/include/external/pasta/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357 +tensorflow/include/external/png/LICENSE,sha256=3-WlNrDlpTH4RPucEBowiaymB3KlA4k7jhX5RX42mWA,5345 +tensorflow/include/external/png/png.h,sha256=IldlIS87WR-Lruik5mim7e6ixPf2Jo6InhDABIg1x6U,142869 +tensorflow/include/external/png/pngconf.h,sha256=__EY47xbo7ukE5LETv9v2vlnUMDYdRsOpPtsWPzDnAE,22806 +tensorflow/include/external/png/pngdebug.h,sha256=WJQaEdru5DZUGxloT3Ee_IQ1Tpw2o74nQxWkEr4hnkU,5319 +tensorflow/include/external/png/pnginfo.h,sha256=h8s-_E3PIrRvKgEiXVxu6ncidT2Fy05vacxIu2G3aHw,12514 +tensorflow/include/external/png/pnglibconf.h,sha256=96Xlsm6d_etzWZd4nzxcv72jTPaszjOz_yGk4KL8Qb4,7753 +tensorflow/include/external/png/pngpriv.h,sha256=efMSOXe3M9KrAGFlJG2aKSsIAGFRWmsCDUYBvUZsyoA,89568 +tensorflow/include/external/png/pngstruct.h,sha256=T0HhxpIMZTLQaaCvWGGJBvU2gbLN3X37UdgcY4KsOVA,19901 +tensorflow/include/external/pybind11/_virtual_includes/pybind11/pybind11/attr.h,sha256=L-eXgUNPe4JAnCvvP2ZzdhewnHFJ83cLM1hZwS8LE3Q,23959 +tensorflow/include/external/pybind11/_virtual_includes/pybind11/pybind11/buffer_info.h,sha256=S4Qkm4F3XqEJjMPvK_TIjXlu-sFxWHJBOL-ZkA9dDgU,7069 +tensorflow/include/external/pybind11/_virtual_includes/pybind11/pybind11/cast.h,sha256=wyemwF3uN3g6V8K6aF5CDFyH-8xpAPYzOxWG2no7Ayk,65660 +tensorflow/include/external/pybind11/_virtual_includes/pybind11/pybind11/chrono.h,sha256=A23naeloqn-1NKVAABOsJtHU9Vz8lfvrAICuLk-7qBM,8458 +tensorflow/include/external/pybind11/_virtual_includes/pybind11/pybind11/complex.h,sha256=AaDZ-rEmK4tFaue-K9P5y3TxxnaQF6JwZ_6LAzkdLQI,2096 +tensorflow/include/external/pybind11/_virtual_includes/pybind11/pybind11/detail/class.h,sha256=Y2IzTplhE5KiMiBlzWSAovCQaI_1M0dlsoDYCTpB5Hg,28518 +tensorflow/include/external/pybind11/_virtual_includes/pybind11/pybind11/detail/common.h,sha256=YsM08qNvETm0rrvL_dvH0cdUWyU1FGASTOn9cx3Ych0,52930 +tensorflow/include/external/pybind11/_virtual_includes/pybind11/pybind11/detail/descr.h,sha256=UXUS9hff2pMepjPYoY4u5NPn2PJ6XM1LaoRdYNCmf2U,5491 +tensorflow/include/external/pybind11/_virtual_includes/pybind11/pybind11/detail/init.h,sha256=PyB7LRhsO5oyJfhbqClnDa_MB0DFPXgpDWMoZWUoFks,17869 +tensorflow/include/external/pybind11/_virtual_includes/pybind11/pybind11/detail/internals.h,sha256=9SDZmmPUTcm6rX4jApZv0apyxm1IzgbysCBoYJEo-_s,26305 +tensorflow/include/external/pybind11/_virtual_includes/pybind11/pybind11/detail/type_caster_base.h,sha256=grpMpc5A4Qqw45GKDGOkphJEVD63cdaH74oR887NSu8,42613 +tensorflow/include/external/pybind11/_virtual_includes/pybind11/pybind11/detail/typeid.h,sha256=jw5pr9m72vkDsloT8vxl9wj17VJGcEdXDyziBlt89Js,1625 +tensorflow/include/external/pybind11/_virtual_includes/pybind11/pybind11/embed.h,sha256=HhdzT5ez7Pzk5i1jAU8hM0E_2D75JD8nurF-51oAbGE,13471 +tensorflow/include/external/pybind11/_virtual_includes/pybind11/pybind11/eval.h,sha256=7re-O2Eor1yD0Q_KgFkHIjKD17ejzII687Yszl9_KfE,4731 +tensorflow/include/external/pybind11/_virtual_includes/pybind11/pybind11/functional.h,sha256=cXDJUS0Y_1GBbOK4Nn13exhkZsAQWx408HZ-PFBmbJo,5002 +tensorflow/include/external/pybind11/_virtual_includes/pybind11/pybind11/gil.h,sha256=RZkkMm0E9PQlHXW6xkBIhM7VBeCvmyJlPVQNaSJMUQQ,8262 +tensorflow/include/external/pybind11/_virtual_includes/pybind11/pybind11/iostream.h,sha256=K5rPXoCYN325r1PptcJCIhPhgtRtTJQjMr7bvUIOwxk,8862 +tensorflow/include/external/pybind11/_virtual_includes/pybind11/pybind11/numpy.h,sha256=ZsfSGJAbzOoLeuBC9-d80a8LRBrxO7V4FQ3fPPDULwg,79416 +tensorflow/include/external/pybind11/_virtual_includes/pybind11/pybind11/operators.h,sha256=224RoAXcv1la4NNY9rQ3aD_AeC8S9ZKx3HVK1O8B4MU,9103 +tensorflow/include/external/pybind11/_virtual_includes/pybind11/pybind11/options.h,sha256=qXvmnj--9fZSp56NYefnB3W5V17ppHlY1Srgo3DNBpw,2734 +tensorflow/include/external/pybind11/_virtual_includes/pybind11/pybind11/pybind11.h,sha256=n1Cdu7DIs_xAPEc28JOjSReLs0JimGFveOb25GuiDlU,126420 +tensorflow/include/external/pybind11/_virtual_includes/pybind11/pybind11/pytypes.h,sha256=Z3Gl9YCNjH1nnRF1WD0SYkMnsHWfTrPWug9HuzFrybM,94641 +tensorflow/include/external/pybind11/_virtual_includes/pybind11/pybind11/stl.h,sha256=DpTs39hXdAcYJ6Lf66ys-bz5FzFZFHcD_tMAywnc4O0,15337 +tensorflow/include/external/pybind11/_virtual_includes/pybind11/pybind11/stl_bind.h,sha256=DVSwtVqj5-ShkMCV1dWmwKQWcQ7P1LxBKo-8ja2742w,29747 +tensorflow/include/external/pybind11/include/pybind11/attr.h,sha256=L-eXgUNPe4JAnCvvP2ZzdhewnHFJ83cLM1hZwS8LE3Q,23959 +tensorflow/include/external/pybind11/include/pybind11/buffer_info.h,sha256=S4Qkm4F3XqEJjMPvK_TIjXlu-sFxWHJBOL-ZkA9dDgU,7069 +tensorflow/include/external/pybind11/include/pybind11/cast.h,sha256=wyemwF3uN3g6V8K6aF5CDFyH-8xpAPYzOxWG2no7Ayk,65660 +tensorflow/include/external/pybind11/include/pybind11/chrono.h,sha256=A23naeloqn-1NKVAABOsJtHU9Vz8lfvrAICuLk-7qBM,8458 +tensorflow/include/external/pybind11/include/pybind11/complex.h,sha256=AaDZ-rEmK4tFaue-K9P5y3TxxnaQF6JwZ_6LAzkdLQI,2096 +tensorflow/include/external/pybind11/include/pybind11/detail/class.h,sha256=Y2IzTplhE5KiMiBlzWSAovCQaI_1M0dlsoDYCTpB5Hg,28518 +tensorflow/include/external/pybind11/include/pybind11/detail/common.h,sha256=YsM08qNvETm0rrvL_dvH0cdUWyU1FGASTOn9cx3Ych0,52930 +tensorflow/include/external/pybind11/include/pybind11/detail/descr.h,sha256=UXUS9hff2pMepjPYoY4u5NPn2PJ6XM1LaoRdYNCmf2U,5491 +tensorflow/include/external/pybind11/include/pybind11/detail/init.h,sha256=PyB7LRhsO5oyJfhbqClnDa_MB0DFPXgpDWMoZWUoFks,17869 +tensorflow/include/external/pybind11/include/pybind11/detail/internals.h,sha256=9SDZmmPUTcm6rX4jApZv0apyxm1IzgbysCBoYJEo-_s,26305 +tensorflow/include/external/pybind11/include/pybind11/detail/type_caster_base.h,sha256=grpMpc5A4Qqw45GKDGOkphJEVD63cdaH74oR887NSu8,42613 +tensorflow/include/external/pybind11/include/pybind11/detail/typeid.h,sha256=jw5pr9m72vkDsloT8vxl9wj17VJGcEdXDyziBlt89Js,1625 +tensorflow/include/external/pybind11/include/pybind11/embed.h,sha256=HhdzT5ez7Pzk5i1jAU8hM0E_2D75JD8nurF-51oAbGE,13471 +tensorflow/include/external/pybind11/include/pybind11/eval.h,sha256=7re-O2Eor1yD0Q_KgFkHIjKD17ejzII687Yszl9_KfE,4731 +tensorflow/include/external/pybind11/include/pybind11/functional.h,sha256=cXDJUS0Y_1GBbOK4Nn13exhkZsAQWx408HZ-PFBmbJo,5002 +tensorflow/include/external/pybind11/include/pybind11/gil.h,sha256=RZkkMm0E9PQlHXW6xkBIhM7VBeCvmyJlPVQNaSJMUQQ,8262 +tensorflow/include/external/pybind11/include/pybind11/iostream.h,sha256=K5rPXoCYN325r1PptcJCIhPhgtRtTJQjMr7bvUIOwxk,8862 +tensorflow/include/external/pybind11/include/pybind11/numpy.h,sha256=ZsfSGJAbzOoLeuBC9-d80a8LRBrxO7V4FQ3fPPDULwg,79416 +tensorflow/include/external/pybind11/include/pybind11/operators.h,sha256=224RoAXcv1la4NNY9rQ3aD_AeC8S9ZKx3HVK1O8B4MU,9103 +tensorflow/include/external/pybind11/include/pybind11/options.h,sha256=qXvmnj--9fZSp56NYefnB3W5V17ppHlY1Srgo3DNBpw,2734 +tensorflow/include/external/pybind11/include/pybind11/pybind11.h,sha256=n1Cdu7DIs_xAPEc28JOjSReLs0JimGFveOb25GuiDlU,126420 +tensorflow/include/external/pybind11/include/pybind11/pytypes.h,sha256=Z3Gl9YCNjH1nnRF1WD0SYkMnsHWfTrPWug9HuzFrybM,94641 +tensorflow/include/external/pybind11/include/pybind11/stl.h,sha256=DpTs39hXdAcYJ6Lf66ys-bz5FzFZFHcD_tMAywnc4O0,15337 +tensorflow/include/external/pybind11/include/pybind11/stl_bind.h,sha256=DVSwtVqj5-ShkMCV1dWmwKQWcQ7P1LxBKo-8ja2742w,29747 +tensorflow/include/external/ruy/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358 +tensorflow/include/external/six_archive/LICENSE,sha256=i7hQxWWqOJ_cFvOkaWWtI9gq3_YPI5P8J2K2MYXo5sk,1066 +tensorflow/include/external/snappy/COPYING,sha256=VRcgRPfiQSBxF0SKTZ1rodCSXIrWa11MCMcK36nMPeY,2645 +tensorflow/include/external/snappy/config.h,sha256=IoIcgMv7Vjxv6H9rU7q_TFBKKkkCh9vfCIfn51aP0bw,1298 +tensorflow/include/external/snappy/snappy-internal.h,sha256=3r4gbxz_hEJjj66SgI8IeveB5c_El6OnDJPMwEYAgYk,15994 +tensorflow/include/external/snappy/snappy-sinksource.h,sha256=umMI-NZNZw-7BoKECW4vRoXjkZ7SE6beGhhao2gCA7s,7265 +tensorflow/include/external/snappy/snappy-stubs-internal.h,sha256=zj3xmvtfIv9WxTOpM8DuYS4N5uLDw4Fnn2c0ivULqLM,16112 +tensorflow/include/external/snappy/snappy-stubs-public.h,sha256=qQhiSMQRenVIYk7qjcTD1UuAzGUHT9YeYp4DZPipULg,2674 +tensorflow/include/external/snappy/snappy.h,sha256=IeJ0fGRq2MoKWYKLbNTm19Lqth3IbTa8HLJxteVEIsQ,10656 +tensorflow/include/external/stablehlo/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357 +tensorflow/include/external/stablehlo/_virtual_includes/base/stablehlo/dialect/Base.h,sha256=JWXMzP8Cu9GYNf1rThn20_VgbjUKkhvwSwkfQaCJU4Y,15979 +tensorflow/include/external/stablehlo/_virtual_includes/base_attr_interfaces_inc_gen/stablehlo/dialect/BaseAttrInterfaces.cpp.inc,sha256=fFr5uXHysoL85Rq4SKttJzwwLpl8eqfkW2XG5msXdGg,735 +tensorflow/include/external/stablehlo/_virtual_includes/base_attr_interfaces_inc_gen/stablehlo/dialect/BaseAttrInterfaces.h.inc,sha256=_cNwf6G_HEpB1xlmo4RsUkVH45ejhP1dQ5wBCo0jYjc,3081 +tensorflow/include/external/stablehlo/_virtual_includes/broadcast_utils/stablehlo/dialect/BroadcastUtils.h,sha256=sO-A2uHh3HfpTVzCGeibHFUSHU0olIgkboM5w5Bsuis,2403 +tensorflow/include/external/stablehlo/_virtual_includes/chlo_attrs_inc_gen/stablehlo/dialect/ChloAttrs.cpp.inc,sha256=L61nBgz5IdwnKRNWf-OfiZFM8JvUyFCC0CNy25G7nvE,7891 +tensorflow/include/external/stablehlo/_virtual_includes/chlo_attrs_inc_gen/stablehlo/dialect/ChloAttrs.h.inc,sha256=k1pld886sY7nxV1VIh4B8DS4HdTVJrxZ8N6ws6hK4-8,2281 +tensorflow/include/external/stablehlo/_virtual_includes/chlo_enums_inc_gen/stablehlo/dialect/ChloEnums.cpp.inc,sha256=tOBEojWmCUf4kjbIrD21QxbpC4AbWQ0UFst-qdxASPU,3172 +tensorflow/include/external/stablehlo/_virtual_includes/chlo_enums_inc_gen/stablehlo/dialect/ChloEnums.h.inc,sha256=442j5unWk34XNx3x9DjBPK7-QegXnJctCu-PfHaAy74,6100 +tensorflow/include/external/stablehlo/_virtual_includes/chlo_ops/stablehlo/dialect/ChloBytecode.h,sha256=_Q63v519iDDgw0z7CyaGZzI9X-QI4Js8gfeBd9RZPBE,1019 +tensorflow/include/external/stablehlo/_virtual_includes/chlo_ops/stablehlo/dialect/ChloOps.h,sha256=1hoexrUGVTQDwLSk7RD8AhpfRU2-Nh5CVeJoUknJUyI,2539 +tensorflow/include/external/stablehlo/_virtual_includes/chlo_ops_inc_gen/stablehlo/dialect/ChloOps.cpp.inc,sha256=xQfdBaS55t9DHG7-MfOjpBmXqqfA18OpjECn9T7gLuE,563803 +tensorflow/include/external/stablehlo/_virtual_includes/chlo_ops_inc_gen/stablehlo/dialect/ChloOps.h.inc,sha256=0nKx8lbDGYYcxNKzxNf6m-JQ3hfB-dvyJkNYNKgxRsw,346134 +tensorflow/include/external/stablehlo/_virtual_includes/experimental_ops/stablehlo/dialect/ExperimentalOps.h,sha256=I0aCz7p1X5V_V47ccQHKIL7KZMzPZ5zMM5BPtcii4wU,9200 +tensorflow/include/external/stablehlo/_virtual_includes/interpreter_ops/stablehlo/reference/InterpreterOps.h,sha256=viEvXyN4DQWl8NzDs79BRu9hkqOZGIdPXFQ-kVu1Y84,1541 +tensorflow/include/external/stablehlo/_virtual_includes/interpreter_ops_inc_gen/stablehlo/reference/InterpreterOps.cpp.inc,sha256=4i0WAiKdukP0kpVg1LrMRe0zoyyzj0_3AJIyyb36wAY,19846 +tensorflow/include/external/stablehlo/_virtual_includes/interpreter_ops_inc_gen/stablehlo/reference/InterpreterOps.h.inc,sha256=4Uv83KZm0fq46bxsHQHHrueB4q1qw4udsyg17UYKZBw,7075 +tensorflow/include/external/stablehlo/_virtual_includes/reference_axes/stablehlo/reference/Axes.h,sha256=W_I4vjq4OmV1u8Zkk68pMywzP9iWI39Uq9jsUww0iAs,1546 +tensorflow/include/external/stablehlo/_virtual_includes/reference_element/stablehlo/reference/Element.h,sha256=naARnGb7kJELLSLSUplZZhvWF3BrDKJA8ubpBHY279o,10739 +tensorflow/include/external/stablehlo/_virtual_includes/reference_errors/stablehlo/reference/Errors.h,sha256=Zos7bU3hKsli3YHp5vNmxpBiGFrr7bjYGJRm7QON5xY,1260 +tensorflow/include/external/stablehlo/_virtual_includes/reference_index/stablehlo/reference/Index.h,sha256=6GH_-FrbxbJcu4r2SDs1HknOCnTbx7XemMIBPNqU79o,6145 +tensorflow/include/external/stablehlo/_virtual_includes/reference_interpretervalue/stablehlo/reference/InterpreterValue.h,sha256=byJH0Jd3D0YBftUm8seHqFSHUy5Z7Idyt5IZNPldMU8,2471 +tensorflow/include/external/stablehlo/_virtual_includes/reference_ops/stablehlo/reference/Ops.h,sha256=BZa92Ei0i8BI4t9V8J0lmigjbHb0P28XXhyrywH0UxU,12651 +tensorflow/include/external/stablehlo/_virtual_includes/reference_process/stablehlo/reference/Process.h,sha256=wfOlDqzgzKv1afXvseXaeLbJsssz5H1F7SOqGFsd6tM,2487 +tensorflow/include/external/stablehlo/_virtual_includes/reference_process_grid/stablehlo/reference/ProcessGrid.h,sha256=3D5_IEKRvtBjumBzGNjFAEsZxRkQJL-VyjDkSjsTefs,10959 +tensorflow/include/external/stablehlo/_virtual_includes/reference_scope/stablehlo/reference/Scope.h,sha256=mMo5ck4uoNPzHu8M41S2NxLSM42yuVkXD4cdSA0W0N0,4334 +tensorflow/include/external/stablehlo/_virtual_includes/reference_tensor/stablehlo/reference/Tensor.h,sha256=unRi-CEVpSsNXFJlti3cSfhlwWyBMHoDQLXwzO5Hw5M,4410 +tensorflow/include/external/stablehlo/_virtual_includes/reference_token/stablehlo/reference/Token.h,sha256=Bs318lKWaRkVNJrfotgVh6mffDLxVF8VPmqcaNQF0JI,1421 +tensorflow/include/external/stablehlo/_virtual_includes/reference_types/stablehlo/reference/Types.h,sha256=-gM3IdI9tKwGBgG-cltEYfObmemGOqSZH3P_BTty50U,2385 +tensorflow/include/external/stablehlo/_virtual_includes/register/stablehlo/dialect/Register.h,sha256=_JhTeyPrqR-W3_MlkeBv7KeeI63vQOqO10JBkmIwW3s,1067 +tensorflow/include/external/stablehlo/_virtual_includes/stablehlo_assembly_format/stablehlo/dialect/AssemblyFormat.h,sha256=Xqj3WY2ic-qaQ1nPRI7jPSpOcGkU2MzO4vKrbovGUtk,13147 +tensorflow/include/external/stablehlo/_virtual_includes/stablehlo_attrs_inc_gen/stablehlo/dialect/StablehloAttrs.cpp.inc,sha256=ZA9KW2b4QGnCFspsgpGcqFcMWThGXbEMesufn12BQ3s,56355 +tensorflow/include/external/stablehlo/_virtual_includes/stablehlo_attrs_inc_gen/stablehlo/dialect/StablehloAttrs.h.inc,sha256=HO6wL1OmGlYZrB5yPUiH25-zz3BXd552dCFWK28p2aw,13078 +tensorflow/include/external/stablehlo/_virtual_includes/stablehlo_enums_inc_gen/stablehlo/dialect/StablehloEnums.cpp.inc,sha256=uTLvTUG4Ra_P8OmPDGi0pD1mhQsDygGmqkLEl8LXZXk,10173 +tensorflow/include/external/stablehlo/_virtual_includes/stablehlo_enums_inc_gen/stablehlo/dialect/StablehloEnums.h.inc,sha256=3zUpTjIagdmkXfKb3ldn1leAQDwuu83_gi_cICcdRRg,22700 +tensorflow/include/external/stablehlo/_virtual_includes/stablehlo_ops/stablehlo/dialect/StablehloBytecode.h,sha256=zNnuHGYB5-AkLkpUU3cC1AH6vYjlxnexK3Pl67hCsC4,1060 +tensorflow/include/external/stablehlo/_virtual_includes/stablehlo_ops/stablehlo/dialect/StablehloOps.h,sha256=zgAVKwGw952l2Ta0XHRKI0chz48CFm2Hbzz6lnE7yMc,4772 +tensorflow/include/external/stablehlo/_virtual_includes/stablehlo_ops_inc_gen/stablehlo/dialect/StablehloOps.cpp.inc,sha256=gnLsgarwiv8Whj1gHd_ckIQuxcr_dIc24VvbRzY-hIg,1433082 +tensorflow/include/external/stablehlo/_virtual_includes/stablehlo_ops_inc_gen/stablehlo/dialect/StablehloOps.h.inc,sha256=BjslTeX61Et4LatSpR8MC1FdQzGThPwofXcZWRcIaMc,814185 +tensorflow/include/external/stablehlo/_virtual_includes/stablehlo_pass_inc_gen/stablehlo/transforms/Passes.h.inc,sha256=LLRRs-LxQQ5k4J_inI5qSw9mfdiSqZFhs_uOqimw_DQ,29101 +tensorflow/include/external/stablehlo/_virtual_includes/stablehlo_passes/stablehlo/transforms/MapStablehloToVhlo.h,sha256=HhZADTd2Jr7ttfxAiXrjRb0Ss7BRzhNpEHjmLwmZfy8,7319 +tensorflow/include/external/stablehlo/_virtual_includes/stablehlo_passes/stablehlo/transforms/Passes.h,sha256=8IH8pQrR_gYX8PwVbE1EkMMCpcEm9FevoOe4evsRtdQ,2682 +tensorflow/include/external/stablehlo/_virtual_includes/stablehlo_portable_api/stablehlo/api/PortableApi.h,sha256=xPs_qBzG3diX-5cnTq_qLkQUz_wcoZlpSuJAm5GaOT4,3358 +tensorflow/include/external/stablehlo/_virtual_includes/stablehlo_type_inference/stablehlo/dialect/TypeInference.h,sha256=FfcYwOg82N2neIEPI_h246DAYWWvl7lrdoNQqDh2Kjg,24362 +tensorflow/include/external/stablehlo/_virtual_includes/version/stablehlo/dialect/Version.h,sha256=qQyeFiSR27pWLBzEzm7xthjCwNzTf7JV0vYJz6sGtlI,2905 +tensorflow/include/external/stablehlo/_virtual_includes/vhlo_attr_interfaces_inc_gen/stablehlo/dialect/VhloAttrInterfaces.cpp.inc,sha256=K5w1hE_XIzBMQxPDKyCBF5e-1xlXMmBqPRWZtd_rrWk,1026 +tensorflow/include/external/stablehlo/_virtual_includes/vhlo_attr_interfaces_inc_gen/stablehlo/dialect/VhloAttrInterfaces.h.inc,sha256=478C2U1efDbbhw05oCnadapr-wSAAwwuApAEZ7B24AE,4220 +tensorflow/include/external/stablehlo/_virtual_includes/vhlo_attrs_inc_gen/stablehlo/dialect/VhloAttrs.cpp.inc,sha256=nokWwoH7rnhjrcKVyep9SqeXAVjF99kt_xaEau_D2aE,62263 +tensorflow/include/external/stablehlo/_virtual_includes/vhlo_attrs_inc_gen/stablehlo/dialect/VhloAttrs.h.inc,sha256=3PCnQeezJ6X-sSjBJlAtbYoPXM2oL6Saah4TcIvuXOQ,19781 +tensorflow/include/external/stablehlo/_virtual_includes/vhlo_enums_inc_gen/stablehlo/dialect/VhloEnums.cpp.inc,sha256=RB3orEYeGkU2CUzxl-gr76iobu8VO0Z7ZRdlVoZbPDc,9460 +tensorflow/include/external/stablehlo/_virtual_includes/vhlo_enums_inc_gen/stablehlo/dialect/VhloEnums.h.inc,sha256=2r8jUdWpdiBR6KxWtmRLBaACXEhWb9zth2U02ioK1Lk,21691 +tensorflow/include/external/stablehlo/_virtual_includes/vhlo_op_interfaces_inc_gen/stablehlo/dialect/VhloOpInterfaces.cpp.inc,sha256=ZopNRVGPF4os43WM9RiwhI95nUf3GzHtAjP20IW5ZuA,1014 +tensorflow/include/external/stablehlo/_virtual_includes/vhlo_op_interfaces_inc_gen/stablehlo/dialect/VhloOpInterfaces.h.inc,sha256=GEs8xLnDytxI-KIBGLwZn5WOeKllXOVqRcV5PD1AVDc,4094 +tensorflow/include/external/stablehlo/_virtual_includes/vhlo_ops/stablehlo/dialect/VhloBytecode.h,sha256=XC85vjdAVP_uKaOWXTcblOMxVYWZiMaRLLsgHl6jgDw,1020 +tensorflow/include/external/stablehlo/_virtual_includes/vhlo_ops/stablehlo/dialect/VhloOps.h,sha256=I2oeO4QZ3V4NP89aM3-E2y6KCXyynr_Ra9DTe1oqK8o,2577 +tensorflow/include/external/stablehlo/_virtual_includes/vhlo_ops_inc_gen/stablehlo/dialect/VhloOps.cpp.inc,sha256=lkRcOTaEh1YEponIXUQjNA7NZwTAG0yz0oqjEYTVqlA,953988 +tensorflow/include/external/stablehlo/_virtual_includes/vhlo_ops_inc_gen/stablehlo/dialect/VhloOps.h.inc,sha256=yu-uDdksAw5SJtWGXQ29GyDOcs1FNUxfxUBkkYFWBVU,662902 +tensorflow/include/external/stablehlo/_virtual_includes/vhlo_type_interfaces_inc_gen/stablehlo/dialect/VhloTypeInterfaces.cpp.inc,sha256=hrrAnhaQgskp8-bilL5Sm97slAk5LkbvWnkviZ_OrII,1026 +tensorflow/include/external/stablehlo/_virtual_includes/vhlo_type_interfaces_inc_gen/stablehlo/dialect/VhloTypeInterfaces.h.inc,sha256=0X1cIQHQnocq1A4NLjclPQpRKe99juDlqfaaH88ETEg,4150 +tensorflow/include/external/stablehlo/_virtual_includes/vhlo_types/stablehlo/dialect/VhloTypes.h,sha256=axigK8fPbLkBsVN9pGLkw07kqq9z50tKMMhQKm0U1bg,2889 +tensorflow/include/external/stablehlo/_virtual_includes/vhlo_types_inc_gen/stablehlo/dialect/VhloTypeDefs.cpp.inc,sha256=UONFkz2VcdtY-RGR7No6SNIP22L02AvatYoxLf9H0mM,43263 +tensorflow/include/external/stablehlo/_virtual_includes/vhlo_types_inc_gen/stablehlo/dialect/VhloTypeDefs.h.inc,sha256=A0795I_v5YRnpgelfi94TEaXiV0-RDPV_tAH93aHhWE,21501 +tensorflow/include/external/stablehlo/stablehlo/api/PortableApi.h,sha256=xPs_qBzG3diX-5cnTq_qLkQUz_wcoZlpSuJAm5GaOT4,3358 +tensorflow/include/external/stablehlo/stablehlo/dialect/AssemblyFormat.h,sha256=Xqj3WY2ic-qaQ1nPRI7jPSpOcGkU2MzO4vKrbovGUtk,13147 +tensorflow/include/external/stablehlo/stablehlo/dialect/Base.h,sha256=JWXMzP8Cu9GYNf1rThn20_VgbjUKkhvwSwkfQaCJU4Y,15979 +tensorflow/include/external/stablehlo/stablehlo/dialect/BaseAttrInterfaces.cpp.inc,sha256=fFr5uXHysoL85Rq4SKttJzwwLpl8eqfkW2XG5msXdGg,735 +tensorflow/include/external/stablehlo/stablehlo/dialect/BaseAttrInterfaces.h.inc,sha256=_cNwf6G_HEpB1xlmo4RsUkVH45ejhP1dQ5wBCo0jYjc,3081 +tensorflow/include/external/stablehlo/stablehlo/dialect/BroadcastUtils.h,sha256=sO-A2uHh3HfpTVzCGeibHFUSHU0olIgkboM5w5Bsuis,2403 +tensorflow/include/external/stablehlo/stablehlo/dialect/ChloAttrs.cpp.inc,sha256=L61nBgz5IdwnKRNWf-OfiZFM8JvUyFCC0CNy25G7nvE,7891 +tensorflow/include/external/stablehlo/stablehlo/dialect/ChloAttrs.h.inc,sha256=k1pld886sY7nxV1VIh4B8DS4HdTVJrxZ8N6ws6hK4-8,2281 +tensorflow/include/external/stablehlo/stablehlo/dialect/ChloBytecode.h,sha256=_Q63v519iDDgw0z7CyaGZzI9X-QI4Js8gfeBd9RZPBE,1019 +tensorflow/include/external/stablehlo/stablehlo/dialect/ChloEnums.cpp.inc,sha256=tOBEojWmCUf4kjbIrD21QxbpC4AbWQ0UFst-qdxASPU,3172 +tensorflow/include/external/stablehlo/stablehlo/dialect/ChloEnums.h.inc,sha256=442j5unWk34XNx3x9DjBPK7-QegXnJctCu-PfHaAy74,6100 +tensorflow/include/external/stablehlo/stablehlo/dialect/ChloOps.cpp.inc,sha256=xQfdBaS55t9DHG7-MfOjpBmXqqfA18OpjECn9T7gLuE,563803 +tensorflow/include/external/stablehlo/stablehlo/dialect/ChloOps.h,sha256=1hoexrUGVTQDwLSk7RD8AhpfRU2-Nh5CVeJoUknJUyI,2539 +tensorflow/include/external/stablehlo/stablehlo/dialect/ChloOps.h.inc,sha256=0nKx8lbDGYYcxNKzxNf6m-JQ3hfB-dvyJkNYNKgxRsw,346134 +tensorflow/include/external/stablehlo/stablehlo/dialect/ExperimentalOps.h,sha256=I0aCz7p1X5V_V47ccQHKIL7KZMzPZ5zMM5BPtcii4wU,9200 +tensorflow/include/external/stablehlo/stablehlo/dialect/Register.h,sha256=_JhTeyPrqR-W3_MlkeBv7KeeI63vQOqO10JBkmIwW3s,1067 +tensorflow/include/external/stablehlo/stablehlo/dialect/Serialization.h,sha256=lhh-CLJ5Wrsh0u9hdO37FEwiHuQFE7OU3w49eoAj4A4,1957 +tensorflow/include/external/stablehlo/stablehlo/dialect/StablehloAttrs.cpp.inc,sha256=ZA9KW2b4QGnCFspsgpGcqFcMWThGXbEMesufn12BQ3s,56355 +tensorflow/include/external/stablehlo/stablehlo/dialect/StablehloAttrs.h.inc,sha256=HO6wL1OmGlYZrB5yPUiH25-zz3BXd552dCFWK28p2aw,13078 +tensorflow/include/external/stablehlo/stablehlo/dialect/StablehloBytecode.h,sha256=zNnuHGYB5-AkLkpUU3cC1AH6vYjlxnexK3Pl67hCsC4,1060 +tensorflow/include/external/stablehlo/stablehlo/dialect/StablehloEnums.cpp.inc,sha256=uTLvTUG4Ra_P8OmPDGi0pD1mhQsDygGmqkLEl8LXZXk,10173 +tensorflow/include/external/stablehlo/stablehlo/dialect/StablehloEnums.h.inc,sha256=3zUpTjIagdmkXfKb3ldn1leAQDwuu83_gi_cICcdRRg,22700 +tensorflow/include/external/stablehlo/stablehlo/dialect/StablehloOps.cpp.inc,sha256=gnLsgarwiv8Whj1gHd_ckIQuxcr_dIc24VvbRzY-hIg,1433082 +tensorflow/include/external/stablehlo/stablehlo/dialect/StablehloOps.h,sha256=zgAVKwGw952l2Ta0XHRKI0chz48CFm2Hbzz6lnE7yMc,4772 +tensorflow/include/external/stablehlo/stablehlo/dialect/StablehloOps.h.inc,sha256=BjslTeX61Et4LatSpR8MC1FdQzGThPwofXcZWRcIaMc,814185 +tensorflow/include/external/stablehlo/stablehlo/dialect/TypeInference.h,sha256=FfcYwOg82N2neIEPI_h246DAYWWvl7lrdoNQqDh2Kjg,24362 +tensorflow/include/external/stablehlo/stablehlo/dialect/Version.h,sha256=qQyeFiSR27pWLBzEzm7xthjCwNzTf7JV0vYJz6sGtlI,2905 +tensorflow/include/external/stablehlo/stablehlo/dialect/VhloAttrInterfaces.cpp.inc,sha256=K5w1hE_XIzBMQxPDKyCBF5e-1xlXMmBqPRWZtd_rrWk,1026 +tensorflow/include/external/stablehlo/stablehlo/dialect/VhloAttrInterfaces.h.inc,sha256=478C2U1efDbbhw05oCnadapr-wSAAwwuApAEZ7B24AE,4220 +tensorflow/include/external/stablehlo/stablehlo/dialect/VhloAttrs.cpp.inc,sha256=nokWwoH7rnhjrcKVyep9SqeXAVjF99kt_xaEau_D2aE,62263 +tensorflow/include/external/stablehlo/stablehlo/dialect/VhloAttrs.h.inc,sha256=3PCnQeezJ6X-sSjBJlAtbYoPXM2oL6Saah4TcIvuXOQ,19781 +tensorflow/include/external/stablehlo/stablehlo/dialect/VhloBytecode.h,sha256=XC85vjdAVP_uKaOWXTcblOMxVYWZiMaRLLsgHl6jgDw,1020 +tensorflow/include/external/stablehlo/stablehlo/dialect/VhloEnums.cpp.inc,sha256=RB3orEYeGkU2CUzxl-gr76iobu8VO0Z7ZRdlVoZbPDc,9460 +tensorflow/include/external/stablehlo/stablehlo/dialect/VhloEnums.h.inc,sha256=2r8jUdWpdiBR6KxWtmRLBaACXEhWb9zth2U02ioK1Lk,21691 +tensorflow/include/external/stablehlo/stablehlo/dialect/VhloOpInterfaces.cpp.inc,sha256=ZopNRVGPF4os43WM9RiwhI95nUf3GzHtAjP20IW5ZuA,1014 +tensorflow/include/external/stablehlo/stablehlo/dialect/VhloOpInterfaces.h.inc,sha256=GEs8xLnDytxI-KIBGLwZn5WOeKllXOVqRcV5PD1AVDc,4094 +tensorflow/include/external/stablehlo/stablehlo/dialect/VhloOps.cpp.inc,sha256=lkRcOTaEh1YEponIXUQjNA7NZwTAG0yz0oqjEYTVqlA,953988 +tensorflow/include/external/stablehlo/stablehlo/dialect/VhloOps.h,sha256=I2oeO4QZ3V4NP89aM3-E2y6KCXyynr_Ra9DTe1oqK8o,2577 +tensorflow/include/external/stablehlo/stablehlo/dialect/VhloOps.h.inc,sha256=yu-uDdksAw5SJtWGXQ29GyDOcs1FNUxfxUBkkYFWBVU,662902 +tensorflow/include/external/stablehlo/stablehlo/dialect/VhloTypeDefs.cpp.inc,sha256=UONFkz2VcdtY-RGR7No6SNIP22L02AvatYoxLf9H0mM,43263 +tensorflow/include/external/stablehlo/stablehlo/dialect/VhloTypeDefs.h.inc,sha256=A0795I_v5YRnpgelfi94TEaXiV0-RDPV_tAH93aHhWE,21501 +tensorflow/include/external/stablehlo/stablehlo/dialect/VhloTypeInterfaces.cpp.inc,sha256=hrrAnhaQgskp8-bilL5Sm97slAk5LkbvWnkviZ_OrII,1026 +tensorflow/include/external/stablehlo/stablehlo/dialect/VhloTypeInterfaces.h.inc,sha256=0X1cIQHQnocq1A4NLjclPQpRKe99juDlqfaaH88ETEg,4150 +tensorflow/include/external/stablehlo/stablehlo/dialect/VhloTypes.h,sha256=axigK8fPbLkBsVN9pGLkw07kqq9z50tKMMhQKm0U1bg,2889 +tensorflow/include/external/stablehlo/stablehlo/reference/Axes.h,sha256=W_I4vjq4OmV1u8Zkk68pMywzP9iWI39Uq9jsUww0iAs,1546 +tensorflow/include/external/stablehlo/stablehlo/reference/Element.h,sha256=naARnGb7kJELLSLSUplZZhvWF3BrDKJA8ubpBHY279o,10739 +tensorflow/include/external/stablehlo/stablehlo/reference/Errors.h,sha256=Zos7bU3hKsli3YHp5vNmxpBiGFrr7bjYGJRm7QON5xY,1260 +tensorflow/include/external/stablehlo/stablehlo/reference/Index.h,sha256=6GH_-FrbxbJcu4r2SDs1HknOCnTbx7XemMIBPNqU79o,6145 +tensorflow/include/external/stablehlo/stablehlo/reference/InterpreterOps.cpp.inc,sha256=4i0WAiKdukP0kpVg1LrMRe0zoyyzj0_3AJIyyb36wAY,19846 +tensorflow/include/external/stablehlo/stablehlo/reference/InterpreterOps.h,sha256=viEvXyN4DQWl8NzDs79BRu9hkqOZGIdPXFQ-kVu1Y84,1541 +tensorflow/include/external/stablehlo/stablehlo/reference/InterpreterOps.h.inc,sha256=4Uv83KZm0fq46bxsHQHHrueB4q1qw4udsyg17UYKZBw,7075 +tensorflow/include/external/stablehlo/stablehlo/reference/InterpreterValue.h,sha256=byJH0Jd3D0YBftUm8seHqFSHUy5Z7Idyt5IZNPldMU8,2471 +tensorflow/include/external/stablehlo/stablehlo/reference/Ops.h,sha256=BZa92Ei0i8BI4t9V8J0lmigjbHb0P28XXhyrywH0UxU,12651 +tensorflow/include/external/stablehlo/stablehlo/reference/Process.h,sha256=wfOlDqzgzKv1afXvseXaeLbJsssz5H1F7SOqGFsd6tM,2487 +tensorflow/include/external/stablehlo/stablehlo/reference/ProcessGrid.h,sha256=3D5_IEKRvtBjumBzGNjFAEsZxRkQJL-VyjDkSjsTefs,10959 +tensorflow/include/external/stablehlo/stablehlo/reference/Scope.h,sha256=mMo5ck4uoNPzHu8M41S2NxLSM42yuVkXD4cdSA0W0N0,4334 +tensorflow/include/external/stablehlo/stablehlo/reference/Tensor.h,sha256=unRi-CEVpSsNXFJlti3cSfhlwWyBMHoDQLXwzO5Hw5M,4410 +tensorflow/include/external/stablehlo/stablehlo/reference/Token.h,sha256=Bs318lKWaRkVNJrfotgVh6mffDLxVF8VPmqcaNQF0JI,1421 +tensorflow/include/external/stablehlo/stablehlo/reference/Types.h,sha256=-gM3IdI9tKwGBgG-cltEYfObmemGOqSZH3P_BTty50U,2385 +tensorflow/include/external/stablehlo/stablehlo/transforms/MapStablehloToVhlo.h,sha256=HhZADTd2Jr7ttfxAiXrjRb0Ss7BRzhNpEHjmLwmZfy8,7319 +tensorflow/include/external/stablehlo/stablehlo/transforms/Passes.h,sha256=8IH8pQrR_gYX8PwVbE1EkMMCpcEm9FevoOe4evsRtdQ,2682 +tensorflow/include/external/stablehlo/stablehlo/transforms/Passes.h.inc,sha256=LLRRs-LxQQ5k4J_inI5qSw9mfdiSqZFhs_uOqimw_DQ,29101 +tensorflow/include/external/tf_runtime/LICENSE,sha256=wFqPwu_qDy_JGoV9qvJ27mefqyZTydLH2QA6l4fGAeE,14049 +tensorflow/include/external/tf_runtime/include/tfrt/bef/bef.h,sha256=VV7-idRvuorwBUAUpJ-wVcI51TdlVbbZ8MHOeTr7xm8,13571 +tensorflow/include/external/tf_runtime/include/tfrt/bef/bef_buffer.h,sha256=GoHlCzRZYXRANYiNyK75PHt3j2VebIxZilMVldOJ8YU,1155 +tensorflow/include/external/tf_runtime/include/tfrt/bef/bef_encoding.h,sha256=HpuUNK1F_WkFukJ8436SY2IYQZUpiEqKq04t_S1w3fg,11173 +tensorflow/include/external/tf_runtime/include/tfrt/bef/bef_reader.h,sha256=AkNlc99WfWTS1HYyDKT-GgKrFDMicLbu6cihfbkgOYo,6363 +tensorflow/include/external/tf_runtime/include/tfrt/bef/kernel.h,sha256=gZbK0hbHaWaANhaMxidhpzoT41GVk63T2hYqnmOur7o,5425 +tensorflow/include/external/tf_runtime/include/tfrt/bef/span.h,sha256=4evCiQRHv2ujlp-XR-XvKs_GWJ77aMDO5Q53IqMTuFk,1897 +tensorflow/include/external/tf_runtime/include/tfrt/concurrency/async_value.h,sha256=z8oU3cMCil4fRtgu5Wsd-4tAEeneyN0E94qflboVLlA,35100 +tensorflow/include/external/tf_runtime/include/tfrt/concurrency/async_value_ref.h,sha256=u80EMmEttgnOxfIBqPahs9bnWuFQYI-H2Eb9kZJKwnE,16774 +tensorflow/include/external/tf_runtime/include/tfrt/concurrency/chain.h,sha256=cgA_tBJnO19reMS81GvK3ZrGFcyBCm8Ix9rUa7iy7NU,816 +tensorflow/include/external/tf_runtime/include/tfrt/concurrency/concurrent_vector.h,sha256=e7-vfI1k9DFIxmGXcsFDPFD2YFYxCrcNAWlAYEFE9rI,6758 +tensorflow/include/external/tf_runtime/include/tfrt/concurrency/ref_count.h,sha256=doLICsEExlWWSCgcnsIijlOPIUQrUXa15ihxF2inxMA,7832 +tensorflow/include/external/tf_runtime/include/tfrt/dtype/dtype.def,sha256=HyXkD4RdUVDE5prpJCXjWhMDKwj2P_3ZPD3VnRWCSgM,3644 +tensorflow/include/external/tf_runtime/include/tfrt/dtype/dtype.h,sha256=2-uSFgs_qlg81UC-LgcwEBFUyGtFU365J_Fwx3W4l64,6880 +tensorflow/include/external/tf_runtime/include/tfrt/dtype/dtype_formatter.h,sha256=waVuk3TDH7W1m926zwLsiqxJZBsmKiHnKOq8_XW9l0M,3700 +tensorflow/include/external/tf_runtime/include/tfrt/dtype/quantized_types.h,sha256=9TghoCYbmOcxSvYnev_pMmqjlbxnN9cWZkn2iFnmU_M,1811 +tensorflow/include/external/tf_runtime/include/tfrt/host_context/async_dispatch.h,sha256=9GJgl8JJz0d5RN1Ttr1vb9fSZ85ySDO2ONapvpV51RQ,9231 +tensorflow/include/external/tf_runtime/include/tfrt/host_context/async_value.h,sha256=cPRMeYzTn4VNCzPytt-ciR48eujUKiLqsDyQyfsJNVk,1568 +tensorflow/include/external/tf_runtime/include/tfrt/host_context/async_value_ref.h,sha256=z34t_AQH_D6LRQdQUrDdZRldo9SGIdK2fhdZIEsTtdo,2011 +tensorflow/include/external/tf_runtime/include/tfrt/host_context/attribute_utils.h,sha256=URLrCEF3y-5Ic1g1TBeJ7MwECF_7nVph2UK78z5aQGo,15313 +tensorflow/include/external/tf_runtime/include/tfrt/host_context/chain.h,sha256=5yOX_SHWiRG63XSGGoX1rnpAXzke7cPRligwyAS7eOI,1353 +tensorflow/include/external/tf_runtime/include/tfrt/host_context/concurrent_work_queue.h,sha256=V8uONFDdYKkvsCWOR5jDJkINbLwVbVbhqHti9IP3PkQ,7443 +tensorflow/include/external/tf_runtime/include/tfrt/host_context/device.h,sha256=bR2uG3LkQsB9nbU2eBt32Ayz_PihHyzrZQIvW2ZHAmI,7110 +tensorflow/include/external/tf_runtime/include/tfrt/host_context/diagnostic.h,sha256=6oPeiH2r8kOtBZCqSAtFtCGZbapSd-S6GbOcXe-ZerM,2952 +tensorflow/include/external/tf_runtime/include/tfrt/host_context/execution_context.h,sha256=OzvIimhrRPiRftLhfqVf6fNewkNUtpy3rfiXcRiRFdc,8123 +tensorflow/include/external/tf_runtime/include/tfrt/host_context/function.h,sha256=zXN-pOK7NCrd7mv8p_8GXIO7-Nu6FOKMnjmo8gTwZTQ,4120 +tensorflow/include/external/tf_runtime/include/tfrt/host_context/host_allocator.h,sha256=ekKn7Uj010NlZBCLWVFLbzDAAi4XLLwxDvEMEg-FOQM,4217 +tensorflow/include/external/tf_runtime/include/tfrt/host_context/host_buffer.h,sha256=h-IWG0TtBETC_uwjyuGnj76CJnt22WLr2k6Bk3xBRWs,5827 +tensorflow/include/external/tf_runtime/include/tfrt/host_context/host_context.h,sha256=MohxM1q591mAm0hUD1AkduvL3HwFHeobHRiVYjmvDPU,8643 +tensorflow/include/external/tf_runtime/include/tfrt/host_context/host_context_ptr.h,sha256=aaflHiDf-TOAFGX7oqcMGLdClQcOo9DgWd43YbPYsR0,2576 +tensorflow/include/external/tf_runtime/include/tfrt/host_context/kernel_frame.h,sha256=5HD18OMPwlSDCdLuL8xKjomQgFaub_Z6Fgpl_JY8Ehs,12687 +tensorflow/include/external/tf_runtime/include/tfrt/host_context/kernel_registry.h,sha256=fAlr6ozCd-OEGuejQio2lVfWlpOib4lQK1w5QZNOMuY,3682 +tensorflow/include/external/tf_runtime/include/tfrt/host_context/kernel_utils.h,sha256=AKp_eaTRd6tVlRkuQe8tDPQ4Qap79H6dLrVaRikFJIU,43888 +tensorflow/include/external/tf_runtime/include/tfrt/host_context/location.h,sha256=q2cn7o1vNFZhieogb0b9BEECN7Xqxu8O4V11Dhe_hLI,3017 +tensorflow/include/external/tf_runtime/include/tfrt/host_context/native_function.h,sha256=EsXKnvVBL_8n2aFsSKkCI7Mg7xYTOAox4gHvrEngTuw,3205 +tensorflow/include/external/tf_runtime/include/tfrt/host_context/parallel_for.h,sha256=g4ZSw0N8YXyoC2JoXbNirgs4oEe3LaVhUzckKPvJy2k,8601 +tensorflow/include/external/tf_runtime/include/tfrt/host_context/request_deadline_tracker.h,sha256=XUNIYnBC1iXxf4C4CKy7PZaBemw53Ff6P8X1BqCvRqY,1611 +tensorflow/include/external/tf_runtime/include/tfrt/host_context/resource_context.h,sha256=iO1Xp6ZBav-TAe-C873msJSLJlpuEi1YdPeWmWiQ95c,5213 +tensorflow/include/external/tf_runtime/include/tfrt/host_context/shared_context.h,sha256=v0yTOm2P23Nbxr9oG-tIw_mq_Cmyr-i-6CGl_mNTq-0,1676 +tensorflow/include/external/tf_runtime/include/tfrt/host_context/sync_kernel_frame.h,sha256=R5A_Etsd-iT3TeMjZOKF4hKCR-XevHVI2M113M_aNs8,6510 +tensorflow/include/external/tf_runtime/include/tfrt/host_context/sync_kernel_utils.h,sha256=T6Q0GuWVQbqaGPtLBx0dNES7HWySaajvDXUj2DTQc_U,19113 +tensorflow/include/external/tf_runtime/include/tfrt/host_context/task_function.h,sha256=Q1zcsQH4SIJKiCAx6FApvDpHuV2UqvC0zRvWwF6LSfs,992 +tensorflow/include/external/tf_runtime/include/tfrt/host_context/timer_queue.h,sha256=ljpyuzvVl8r4d2WSjRtBMhoccbZHP24aJYZ3das6WcE,3490 +tensorflow/include/external/tf_runtime/include/tfrt/host_context/type_name.h,sha256=_Q4pa41awnSSMwevqAUOLaim42sI9FECYfY0o6pEmfs,1509 +tensorflow/include/external/tf_runtime/include/tfrt/host_context/value.h,sha256=6_s4Hb604rwxt1kvhwmb-fbSbWBk_XkEyPVeb6udIx4,12665 +tensorflow/include/external/tf_runtime/include/tfrt/support/aligned_buffer.h,sha256=LU_YqDIhNxMfi4zcwgbixuIafqUnpwGuAVQrqF7WkiI,2376 +tensorflow/include/external/tf_runtime/include/tfrt/support/alloc.h,sha256=4HPyptyy6Y2OaP-Q_r74HAO9ACXlDhH2Rv9_rE9yhXE,1120 +tensorflow/include/external/tf_runtime/include/tfrt/support/bf16.h,sha256=GwM1wU28PTIAZT29Zwwd3sSS7CgBurTBuSkoovfwJfw,1348 +tensorflow/include/external/tf_runtime/include/tfrt/support/byte_order.h,sha256=BGHSRDUHKsSaw03EbvVI_IO-QnIjnOFkDf1A10tkAMo,1491 +tensorflow/include/external/tf_runtime/include/tfrt/support/concurrent_vector.h,sha256=rymM6KuUTmoIcCNegFp81K-EPN6GReNxBlgRBdtObvw,951 +tensorflow/include/external/tf_runtime/include/tfrt/support/crc32c.h,sha256=8XduPd6ux5svyjhgZgbhLIf6TE2oqZB-jaFMcKagVuc,1892 +tensorflow/include/external/tf_runtime/include/tfrt/support/error_type.def,sha256=_v_9X9kg3muZgq-23kFaCnJBvg2sxTi2rQ58njfRZ8I,1866 +tensorflow/include/external/tf_runtime/include/tfrt/support/error_util.h,sha256=RwV7kDxMqVIzmX3II1MgWhbJNU3AEXu5OMigIfyJtfI,8768 +tensorflow/include/external/tf_runtime/include/tfrt/support/forward_decls.h,sha256=ghmTlWZNL9GzoGG4i2mqVZWeR6MYqB6lwy1oZei73Ak,2996 +tensorflow/include/external/tf_runtime/include/tfrt/support/fp16.h,sha256=qxTbv8nppd02odx-vyRnut0gso3L7WFIM2z44lzpfJ0,1277 +tensorflow/include/external/tf_runtime/include/tfrt/support/hash_util.h,sha256=QfM0MsLmnhClzw6Eeq3q2dDpIUxYOQAIv63ijJjg-Kg,1427 +tensorflow/include/external/tf_runtime/include/tfrt/support/latch.h,sha256=UgJPj_efK-fm0mHmdkB2SfKSwsg3pguT3KQt6G2Z_ac,3246 +tensorflow/include/external/tf_runtime/include/tfrt/support/logging.h,sha256=58otsy2JmqjkvsZoFr9GY2nP540bEhftHZdVBsu6ZYg,3959 +tensorflow/include/external/tf_runtime/include/tfrt/support/map_by_type.h,sha256=-6UBAE2MLRrYBYVLMFFlDsjEOoyKy6xhJXfY4F3l0Mg,5634 +tensorflow/include/external/tf_runtime/include/tfrt/support/msan.h,sha256=8jIh2u9bzBuclBvM9VK3cfJ1s4MUwlWlMIeuTwBIoik,1563 +tensorflow/include/external/tf_runtime/include/tfrt/support/mutex.h,sha256=HwRGVKQdNC8gv_pJk2Bl0Y8vo2XUTX4TkM544FqFPew,3293 +tensorflow/include/external/tf_runtime/include/tfrt/support/op_registry_impl.h,sha256=NtCWPRtPY3rZncEz5hDw9HQeJk3PdBIMH3K9RN_izGA,2290 +tensorflow/include/external/tf_runtime/include/tfrt/support/philox_random.h,sha256=kjXVyXCh9yaZeK-YtGyeDwI3pmnng7MMhCZZZF4cRn8,5327 +tensorflow/include/external/tf_runtime/include/tfrt/support/pointer_util.h,sha256=bSS5HnpYhjAL9bLNsu8rT0ry6s4_JrHLrz3OT-kREVs,2329 +tensorflow/include/external/tf_runtime/include/tfrt/support/random_util.h,sha256=tNw-4v_7g3uW6qBg2AXeV8KTb5rB0_cY-mnGHsV8BSk,976 +tensorflow/include/external/tf_runtime/include/tfrt/support/ranges.h,sha256=pGJEvJSzCWrbVaGh24VUqkxHRjvm2PgDA7afS1rx5Sk,2347 +tensorflow/include/external/tf_runtime/include/tfrt/support/ranges_util.h,sha256=uiSSk98GOTzlu4RIpSrVBke2tga5Kig40pTcBndZh_U,2087 +tensorflow/include/external/tf_runtime/include/tfrt/support/raw_coding.h,sha256=tqn5oX8sv8ebTz58Q0UNcO5N84TcWOSNJ8rtXQWrdrs,2467 +tensorflow/include/external/tf_runtime/include/tfrt/support/rc_array.h,sha256=M7T7aLJm3RDlsi5I6rhQQ3rcZo9WvI2-5BvBjGCoZvg,2186 +tensorflow/include/external/tf_runtime/include/tfrt/support/ref_count.h,sha256=sgo-dIRSDv0-5A2uoHbCioOTuTH5wyxBisZoAl_ZbuM,1373 +tensorflow/include/external/tf_runtime/include/tfrt/support/refcounted_callback.h,sha256=5HoIpRyF07ucX4nlfDAjJVJkR2Pd3rsnuIL-ns-PAOA,2394 +tensorflow/include/external/tf_runtime/include/tfrt/support/string_util.h,sha256=c8S1RKr6rzKzFnQlmPTWeKjah2mOop8-qHSTHw4efkg,3102 +tensorflow/include/external/tf_runtime/include/tfrt/support/template_util.h,sha256=ok6VUjntXnfu4go52276sK-JO6jOUZoFH82QWn9IkM0,1577 +tensorflow/include/external/tf_runtime/include/tfrt/support/thread_annotations.h,sha256=9BvAZ3cAzl8edB774lMX-RiRK_LsmKfVzpgeqB9FEH0,3290 +tensorflow/include/external/tf_runtime/include/tfrt/support/thread_environment.h,sha256=bmarjrt6Us6FhQmVJSuUiFL6dXX8BJAaLlnOGFqWPFo,1807 +tensorflow/include/external/tf_runtime/include/tfrt/support/thread_local.h,sha256=C5B3MhMXC1myi7OaiGIu4CbHTLHn_-7h92wQ8wg5Sdc,9431 +tensorflow/include/external/tf_runtime/include/tfrt/support/type_id.h,sha256=3jbcWxl3rwodUrk6gosSFoixBje1igwnhNWdJaeSNOQ,3831 +tensorflow/include/external/tf_runtime/include/tfrt/support/type_traits.h,sha256=wwnaPsf92aa52vaGbikjidADMJJRJBtyBbJ6zYdm-6w,5777 +tensorflow/include/external/tf_runtime/include/tfrt/support/variant.h,sha256=kMkLBhOqLB9PTlnYeQV3BTXoskZl5r5rQlTRlVoRBt8,6127 +tensorflow/include/external/tf_runtime/third_party/concurrent_work_queue/lib/blocking_work_queue.h,sha256=6b78n84y887Woqh8eT-JT0l8pYGiOJiSwkTukllZrAU,12912 +tensorflow/include/external/tf_runtime/third_party/concurrent_work_queue/lib/event_count.h,sha256=RGo0ggQzI0X7dh4o7oA9VOF-9kKpx3XFwIdTvp1JE5Y,10106 +tensorflow/include/external/tf_runtime/third_party/concurrent_work_queue/lib/non_blocking_work_queue.h,sha256=ySFa-hFRkztay1xrCkze5vi94cUAljOvAaiqLc_GCi4,5894 +tensorflow/include/external/tf_runtime/third_party/concurrent_work_queue/lib/task_deque.h,sha256=GRsFhuUkFe5XP32V3bYEuepIYfhzdr4lfIINMdjpxQg,10832 +tensorflow/include/external/tf_runtime/third_party/concurrent_work_queue/lib/task_priority_deque.h,sha256=dOgDWv54JNgPopjfVsRCoN44lGA6cwJsH2l9agEDQ7E,18567 +tensorflow/include/external/tf_runtime/third_party/concurrent_work_queue/lib/task_queue.h,sha256=oVq8Ka8_dFqpHedqewIfV8YqyNUDkd5TYrjz_2zuEo0,5927 +tensorflow/include/external/tf_runtime/third_party/concurrent_work_queue/lib/work_queue_base.h,sha256=Q1kAHZtcDTbOopzXAloNN9NpOCb9LfCc1G_hNmBCYuE,27531 +tensorflow/include/external/tf_runtime/third_party/llvm_derived/include/llvm_derived/Support/in_place.h,sha256=bTOVQ8O4PuFkKUCS9B64vvfSHmMcNJDkquz3LDToAYk,2096 +tensorflow/include/external/tf_runtime/third_party/llvm_derived/include/llvm_derived/Support/unique_any.h,sha256=qEhxAk7Fe0C0D-zqqtjrwt5ebwG-WJU-DC0texiJkgo,8081 +tensorflow/include/external/triton/_virtual_includes/triton_combine_inc_gen/TritonCombine.inc,sha256=xWrMTN6giMvEKePRcU1EAZNdWI94pKzutZlOLB4VZ3o,17445 +tensorflow/include/external/triton/include/triton/Analysis/Alias.h,sha256=6nMCwYctLbLm5h1lkFTVP-0pHSeUIlGX9kUeRytr2Ic,3115 +tensorflow/include/external/triton/include/triton/Analysis/Allocation.h,sha256=lkwg0Y03Jz_JA6jnDkJo9MSlT3RbvBAlErFCt7G3wA0,8246 +tensorflow/include/external/triton/include/triton/Analysis/AxisInfo.h,sha256=SlpnFUf1idJEkfwYJ4GjPy8kGVl3ZYfGTaqzmuwRnvQ,11886 +tensorflow/include/external/triton/include/triton/Analysis/Membar.h,sha256=KSB_QFiI3nh7oa9P0H1quOyEL-e34j7uijpFVAarxwk,5272 +tensorflow/include/external/triton/include/triton/Analysis/Utility.h,sha256=3QyeSKni46SROiPiHRCsGtHsi2AQg3mEhyx3AQeoWLI,10221 +tensorflow/include/external/triton/include/triton/Conversion/MLIRTypes.h,sha256=Tk0e-YVsedIveE2Jj8pqXI6PBd9d0IyyjbxWv_06pyY,1320 +tensorflow/include/external/triton/include/triton/Conversion/TritonGPUToLLVM/AsmFormat.h,sha256=xnEkp4ue_IZLwxJaM6EcqkjOWZj6wQeYKgJMBypzQ1s,722 +tensorflow/include/external/triton/include/triton/Conversion/TritonGPUToLLVM/GCNAsmFormat.h,sha256=FD3KuKIlkeq2qjrRYvkXUG58-FZLQdNBNbmnbLDPX0M,10971 +tensorflow/include/external/triton/include/triton/Conversion/TritonGPUToLLVM/PTXAsmFormat.h,sha256=ngJ-L-Nu4IT2iA5fPbIr159JqX4EPzRqJUmzInYS9kk,11439 +tensorflow/include/external/triton/include/triton/Conversion/TritonGPUToLLVM/Passes.h,sha256=LnTlBJfJTynpd6rGSB8Rnf2XOJ0tEeCYRy4Yl6l4tO4,366 +tensorflow/include/external/triton/include/triton/Conversion/TritonGPUToLLVM/Passes.h.inc,sha256=xXw5wH67Jmz7iPGolnmjMoAMck7e545G-wefxML9d88,7356 +tensorflow/include/external/triton/include/triton/Conversion/TritonGPUToLLVM/TritonGPUToLLVMPass.h,sha256=jmBVw3Bn-MCOYWfjFCPQc8CVzhE6iuEK24Rxaqg9z9I,530 +tensorflow/include/external/triton/include/triton/Conversion/TritonToTritonGPU/Passes.h,sha256=-PVDNaJx3ehzXePfqf95Ne9CP2IF5ymr4OW65QCUZRQ,321 +tensorflow/include/external/triton/include/triton/Conversion/TritonToTritonGPU/Passes.h.inc,sha256=rNQ9-hy-qLUtNgvyaC8tlB7QBWDDw92lPdoVUhGIGxM,6918 +tensorflow/include/external/triton/include/triton/Conversion/TritonToTritonGPU/TritonToTritonGPUPass.h,sha256=IjOhzepPLXikDbL7RVwm-g1Ig_EVB0jnzZ9fS-k2LpA,752 +tensorflow/include/external/triton/include/triton/Dialect/Triton/IR/AttrInterfaces.cpp.inc,sha256=RDDM26gjMzU1CRBs-NKUCrOUcCw2zV5oioY1HpEdWyk,568 +tensorflow/include/external/triton/include/triton/Dialect/Triton/IR/AttrInterfaces.h.inc,sha256=TXTD0FbCDYx5gXyhLuONaStUQGDK949FzLaB3HJfUUM,568 +tensorflow/include/external/triton/include/triton/Dialect/Triton/IR/Dialect.cpp.inc,sha256=ySYkgGCYhsnLtdZqI6wLPDO5_7IrbyrvdPd-Wvlntso,1224 +tensorflow/include/external/triton/include/triton/Dialect/Triton/IR/Dialect.h,sha256=5jJlf72zpxqqPNc7dM76yIuYi_M0csOOK2cdIM7uVaY,2078 +tensorflow/include/external/triton/include/triton/Dialect/Triton/IR/Dialect.h.inc,sha256=FznMPSWNeD9vCEUdmkmf5Q5dJpuVrT_kq0M7EyKLpf0,1782 +tensorflow/include/external/triton/include/triton/Dialect/Triton/IR/Interfaces.h,sha256=phT5V8kE8c5DY4_b-HcK2txprADxTNvjFb6vYNnkzB4,215 +tensorflow/include/external/triton/include/triton/Dialect/Triton/IR/Ops.cpp.inc,sha256=p1RQExmVAFs2oBYbt1ftp-pItx-RXhvmsdYwQ_uLpvM,448887 +tensorflow/include/external/triton/include/triton/Dialect/Triton/IR/Ops.h.inc,sha256=W28xd0SuOjP4JI0CTBhNyyN6BNFbxvAhYgz7TuCoBOY,245553 +tensorflow/include/external/triton/include/triton/Dialect/Triton/IR/OpsEnums.cpp.inc,sha256=rX9QUpqfgGV_PAaxsK0dftPz-TR9h8_cORSAa_W65LY,12203 +tensorflow/include/external/triton/include/triton/Dialect/Triton/IR/OpsEnums.h.inc,sha256=34m06kaFZyFDoSe3gNrKKKDtCbfHnSgykNheaUsJwYg,18422 +tensorflow/include/external/triton/include/triton/Dialect/Triton/IR/Traits.h,sha256=ToTuEt9kqjsQUgEYNPmxZCiP1172k3NrekcIdi2K0LE,3375 +tensorflow/include/external/triton/include/triton/Dialect/Triton/IR/Types.cpp.inc,sha256=UaCko-UlV_ZMD3BBWkRElIyFEyyzR6LeW2Xtx8RZLM0,3971 +tensorflow/include/external/triton/include/triton/Dialect/Triton/IR/Types.h,sha256=8DHkvlzJ4BAYCMToMi08IPFv0yqCBdoW_Yd3Co7JVH0,644 +tensorflow/include/external/triton/include/triton/Dialect/Triton/IR/Types.h.inc,sha256=dtUbuSec7kk3kECwJG7ZrBnblS-jZuqVsdBp3_DDHyg,1408 +tensorflow/include/external/triton/include/triton/Dialect/Triton/Transforms/Passes.h,sha256=QvR-dq6HC0ugIcA-JkvBfEkq0cj43dTuSmAFIxCDGsE,491 +tensorflow/include/external/triton/include/triton/Dialect/Triton/Transforms/Passes.h.inc,sha256=tMFe8LMe276emeSI7o7Z7zXtiG6S4GZE5aGb4PE7JCY,16114 +tensorflow/include/external/triton/include/triton/Dialect/TritonGPU/IR/Attributes.h,sha256=cWcdW6sIjLZp2gi1rISA4cFF1q-4gOKq3Q1cHdf_p6c,245 +tensorflow/include/external/triton/include/triton/Dialect/TritonGPU/IR/Dialect.cpp.inc,sha256=wtsi8kSz34n9TGkQ-fd8NZNcl5cz7xRHStuyggDshcg,1236 +tensorflow/include/external/triton/include/triton/Dialect/TritonGPU/IR/Dialect.h,sha256=-qtLGDLMr13Q_JHBCLb8nDk1NqeEJS2sQM20h14wqA0,3658 +tensorflow/include/external/triton/include/triton/Dialect/TritonGPU/IR/Dialect.h.inc,sha256=5HNynaS-2SMaWlTGXvgwTaOFQKhywQWWeuSeQ_jIGLw,2487 +tensorflow/include/external/triton/include/triton/Dialect/TritonGPU/IR/Ops.cpp.inc,sha256=ZzustrmpMnwOHwSloq2ma6hHV-XYtIFLRYpw267ltiU,127171 +tensorflow/include/external/triton/include/triton/Dialect/TritonGPU/IR/Ops.h.inc,sha256=gX4P52BUGj-A8DiumG-OlFl5oD_KH8qGQaDnXGTTg1E,71741 +tensorflow/include/external/triton/include/triton/Dialect/TritonGPU/IR/Traits.h,sha256=q5HqsLyHCZBqwUy5mtwMD2rB_wjScIuC1XOke76RT-Y,779 +tensorflow/include/external/triton/include/triton/Dialect/TritonGPU/IR/TritonGPUAttrDefs.cpp.inc,sha256=Dw4BY-bKfkKpS50GgnerjO13qVWWw5qcWTePNFPMToI,21911 +tensorflow/include/external/triton/include/triton/Dialect/TritonGPU/IR/TritonGPUAttrDefs.h.inc,sha256=eNmedoibHGh5BO6ksCOEniVTmYvdolXhANrRVnQXzE8,8157 +tensorflow/include/external/triton/include/triton/Dialect/TritonGPU/Transforms/Passes.h,sha256=cKH40Z0xRbZ__94lQla1_yg5zsd-0h_Zt84ilx_uE5Q,964 +tensorflow/include/external/triton/include/triton/Dialect/TritonGPU/Transforms/Passes.h.inc,sha256=uddApVjd8S94a8MUQudW9w2aXuXHAINifKG5pOBrUyY,43013 +tensorflow/include/external/triton/include/triton/Dialect/TritonGPU/Transforms/TritonGPUConversion.h,sha256=j-8UWvFfZ3YMSOY3GFqT98ebN0TeUPOzGGgmryFD8fU,1087 +tensorflow/include/external/triton/include/triton/Dialect/TritonGPU/Transforms/Utility.h,sha256=PZFXvbh-BgNgexOu38Aq8oUqHsT2wP4scz0YaC0KlYI,1453 +tensorflow/include/external/triton/include/triton/Target/LLVMIR/LLVMIRTranslation.h,sha256=ZiBcFNoryrL4YRhydn_nXIcTA-t99BeXau7ZzoEnA-Q,1116 +tensorflow/include/external/triton/include/triton/Target/LLVMIR/Passes.h,sha256=HqlhI9l8wlUcx25DHCkkbYo7IOxvOmWiMnzhf90Tu_U,402 +tensorflow/include/external/triton/include/triton/Target/LLVMIR/Passes.h.inc,sha256=30oU5Mvllzp-UOyWcjRBtRGyGJFPU5mIQDQq2hCSl4Q,5129 +tensorflow/include/external/triton/include/triton/Tools/Sys/GetEnv.hpp,sha256=2wUiy5TiApOH3OLbAa2wxuthYaIRJAHkt4y3odaouuw,1524 +tensorflow/include/external/triton/include/triton/Tools/Sys/GetPlatform.hpp,sha256=iuZAhvBecAjZLakcQ0HMF5QECQtDvz6pCuaAuyFj2d0,1160 +tensorflow/include/external/triton/lib/Conversion/TritonGPUToLLVM/ConvertLayoutOpToLLVM.h,sha256=_83f3VmslEWNnEk-t2RhjR4JhIYKrVIjA4CM1xHtctY,534 +tensorflow/include/external/triton/lib/Conversion/TritonGPUToLLVM/DotOpToLLVM.h,sha256=iBIVdHWZaPIrtQ5mxGDnoi-HG176HgAB7lgdUbIgSh8,463 +tensorflow/include/external/triton/lib/Conversion/TritonGPUToLLVM/ElementwiseOpToLLVM.h,sha256=fA3CaHGVanuI3k5T8D89X7xOSLbpAcPBuT9hLRYsv7A,400 +tensorflow/include/external/triton/lib/Conversion/TritonGPUToLLVM/LoadStoreOpToLLVM.h,sha256=K44zo9o9WJwYArJoa1-NTGJx770oSiJnHNQhvJFeVrc,512 +tensorflow/include/external/triton/lib/Conversion/TritonGPUToLLVM/ReduceOpToLLVM.h,sha256=T3J71HQOa4C1d7zVMwVmGIXggqKQrOQJMwOTNRbPJis,459 +tensorflow/include/external/triton/lib/Conversion/TritonGPUToLLVM/ScanOpToLLVM.h,sha256=WBYgBSYmV4PPineK84q47HslVYAXtiEclk7jy4OYDC0,453 +tensorflow/include/external/triton/lib/Conversion/TritonGPUToLLVM/TritonGPUToLLVM.h,sha256=Bkd6jt--XRmB6pR6BnyaDvUx4xSzaxKREEKg5DsT0MU,440 +tensorflow/include/external/triton/lib/Conversion/TritonGPUToLLVM/TritonGPUToLLVMBase.h,sha256=8NxDcFpQxx8vbddD8dcWYT6afIbhKzv9VYRiC8MJ-kg,42996 +tensorflow/include/external/triton/lib/Conversion/TritonGPUToLLVM/TypeConverter.h,sha256=HwErF7nnMjR1jtpFKe6XxBqjgV46uB9L8Q9qIvmEldk,1090 +tensorflow/include/external/triton/lib/Conversion/TritonGPUToLLVM/Utility.h,sha256=Hjku1BxSu-6vQIP-6CPyW-HCOVH7YfGWWfJAXHYaBtc,13814 +tensorflow/include/external/triton/lib/Conversion/TritonGPUToLLVM/ViewOpToLLVM.h,sha256=Jml_Qa5vgQFIIZuOH3u7JzqlStiv5jrK3JcIyaZ0EB0,405 +tensorflow/include/external/triton/lib/Dialect/Triton/Transforms/TritonCombine.inc,sha256=xWrMTN6giMvEKePRcU1EAZNdWI94pKzutZlOLB4VZ3o,17445 +tensorflow/include/external/upb/upb/decode.h,sha256=R3DWE--fhe_sJx3BDreCkO8k6cyP12oP-iZLRbqnYGA,370 +tensorflow/include/external/upb/upb/encode.h,sha256=OQRpSilJkdiHfigwqepOZa6K4qywnsB8RNMvQf5-BKc,359 +tensorflow/include/external/upb/upb/generated_util.h,sha256=GGtghYdsIQhxZ3rxVUGYL43uCtqUTV-xe732GQ0j91k,3131 +tensorflow/include/external/upb/upb/msg.h,sha256=wZtGeyZQn8tWDuLF3rY9rpeR8WJdDFfwvC9F6ZPqTJg,2054 +tensorflow/include/external/upb/upb/port_def.inc,sha256=tmaLPs74gZ0fgB34SsP1gGIeQCWpkVrq6Jfa178Y94Q,4564 +tensorflow/include/external/upb/upb/port_undef.inc,sha256=jBFciF49f_yEX0Ltou9GaMFOWPw6zyo-pwElox6tlGM,459 +tensorflow/include/external/upb/upb/table.int.h,sha256=RnDGnOLuOtXIPwPpbpc1afJeErv6r5kapbH3-LHRCtw,17900 +tensorflow/include/external/upb/upb/upb.h,sha256=ZqmrQRmiOSrclQIFGkWrcvxp0pofZ2q4uZpPGmKWhgo,10883 +tensorflow/include/external/zlib/crc32.h,sha256=miIjV1GDrC7ookfyC_OsBm6L0BQDaVVr29_8d3Q1dJ4,591749 +tensorflow/include/external/zlib/deflate.h,sha256=DbG173nKa6D1CLe4vaoRr0XF6-LImrTxCG3CK5Y6Uvo,13125 +tensorflow/include/external/zlib/gzguts.h,sha256=-oXJ2r4k5CupXHAocEFv9n7MWJBjIfjnS3KlDf199AA,6843 +tensorflow/include/external/zlib/inffast.h,sha256=fYwchzzpvDRq1gBbuddczlxjUqr3OVOFviFqlFKjSQg,427 +tensorflow/include/external/zlib/inffixed.h,sha256=I3unEPCQ5DK2Lr-WO-6LMChn6WkUBrLT-O6J7nv--bA,6332 +tensorflow/include/external/zlib/inflate.h,sha256=6NSlGwdpS_SMuRl5wZl0z2pasLignSbsDRTfNJIwZz4,6683 +tensorflow/include/external/zlib/inftrees.h,sha256=RAhKk2czhttigty2HXOchFGOEN_2bRxoUHFRN8gnRkw,2927 +tensorflow/include/external/zlib/trees.h,sha256=uwqdPKiO4AyBrbfGNuc7lwhfbvG1LW1Y7b4rbcOt600,8472 +tensorflow/include/external/zlib/zconf.h,sha256=gOCjGkwObyDRutDfmScbnVNaqffE5i8aVPZDrbTG36I,16625 +tensorflow/include/external/zlib/zlib.h,sha256=qYCg0QQZilPMIgxRq1hW5b6QG-yKLQLg7nmodUIZ3-0,97323 +tensorflow/include/external/zlib/zutil.h,sha256=z5TYZeOpFiwFccun90yPAe-9yia5gdbMnFRdTDmR48I,7297 +tensorflow/include/google/protobuf/any.h,sha256=9ECkWaLZNzU9XeKE34bqHaHXptq1o3D51AbRLbbklSI,6547 +tensorflow/include/google/protobuf/any.pb.h,sha256=6xuXp4edsK2qJueeWTf1WlLrVyQiCmdB8xoZBE_sM_4,13792 +tensorflow/include/google/protobuf/api.pb.h,sha256=OG5IP3v68EL-OOL5K4tvrnzEo4uD0WixXKH1XIUYljI,51911 +tensorflow/include/google/protobuf/arena.h,sha256=sRN9GnTvQvlZZAFqySegYRYY4omrJP0TZgcsTztKkY0,35781 +tensorflow/include/google/protobuf/arena_impl.h,sha256=UOsIQ2LjnLuZ9XizYguNUAUIpy3ASgjTXKRmmCwFl0E,25433 +tensorflow/include/google/protobuf/arena_test_util.h,sha256=pqnQBMUAlgmgXDH-sUGxIvKMwMdYt1GSk9py879NzMk,4564 +tensorflow/include/google/protobuf/arenastring.h,sha256=IxpVe9wB3bdfRTBKbqirK7t9NJBch1Cby-MJpcxNmOc,19008 +tensorflow/include/google/protobuf/arenaz_sampler.h,sha256=CO9PXWo9JHKyqB-LUwjeI3LPhU3grIxPYfAjmq9uQNc,7642 +tensorflow/include/google/protobuf/compiler/annotation_test_util.h,sha256=HQt00ZQUafg9v6eTPpkWqjz-sKGFqnfgGcPak8F6Qmo,5377 +tensorflow/include/google/protobuf/compiler/code_generator.h,sha256=yVmFU45UeKfBlR926gPgsNJJ_hg97-9lXd3xIjoEko4,8592 +tensorflow/include/google/protobuf/compiler/command_line_interface.h,sha256=8huWkeBkAa2NQuJtYV0HIN-nm7q9QnU-BKNOIrl4sgo,20307 +tensorflow/include/google/protobuf/compiler/cpp/cpp_generator.h,sha256=2TVBK0_aCZ7WJ2iAGj392b1KCVQKb-Dz-82bhOY8eF0,219 +tensorflow/include/google/protobuf/compiler/cpp/enum.h,sha256=KiQu8AHtMTf5YHH8sbD_jbrGsdDFo5xFrwgAXiZc8_k,3982 +tensorflow/include/google/protobuf/compiler/cpp/enum_field.h,sha256=hbDTaORwVnJEas26dP3IwbWHvH9CCeUEMeU6gTrXGHU,5608 +tensorflow/include/google/protobuf/compiler/cpp/extension.h,sha256=ptbFzl6bAXX3k2xI6afVehC8ggkekx6KvMUBubjCvuU,3402 +tensorflow/include/google/protobuf/compiler/cpp/field.h,sha256=fuVrrRLDPDjTDmx3wdt6F1L6yk5phy-sJiVj6AcG_Rk,11821 +tensorflow/include/google/protobuf/compiler/cpp/file.h,sha256=E7rDWSfMglBLVLRo0--RRZPTx_SBQFe8Ii0z_mkDB_A,8637 +tensorflow/include/google/protobuf/compiler/cpp/generator.h,sha256=m_uebIxp5kBLhAgouE0G2TEsITySX5vKSdVOsHcvOB8,4204 +tensorflow/include/google/protobuf/compiler/cpp/helpers.h,sha256=_Hl_e4GeYEFlRrFVWiMR0Qa0VeXaGc_V82bQCdTbYwM,42667 +tensorflow/include/google/protobuf/compiler/cpp/map_field.h,sha256=SCigZcvT9WJUw8nT3Mj6miaPOhWfGFz8w4ZbA-M07TY,3757 +tensorflow/include/google/protobuf/compiler/cpp/message.h,sha256=FzwYLCwBvLw2j_Ap3zm1hd5o7x4iQze8SdCOe-B-ALQ,9768 +tensorflow/include/google/protobuf/compiler/cpp/message_field.h,sha256=jBSgw_T06ahjUplQVjhn4XWl4d8GrQ376k-yfra6dwc,6710 +tensorflow/include/google/protobuf/compiler/cpp/message_layout_helper.h,sha256=TCg0nHcE7eHpq-lNRnWzDFXcZAOFWHLg_J75ivABD2w,2665 +tensorflow/include/google/protobuf/compiler/cpp/names.h,sha256=mqJ7yKrC7cJIibTWhwQOd_Msd70cAolQud4_G0XohC8,3792 +tensorflow/include/google/protobuf/compiler/cpp/options.h,sha256=ToOMIVPAQLvepjKQotzuSgEWpsrWX2tjbenRYEXffrI,3784 +tensorflow/include/google/protobuf/compiler/cpp/padding_optimizer.h,sha256=E04CDU2ARbf5xVlhKkXGah2Yc645Eu4kRpOsg4wham0,2779 +tensorflow/include/google/protobuf/compiler/cpp/parse_function_generator.h,sha256=VGi8NG6-xQTNTKd36Wtm0dOkwpfyMGqXovUcqRPR5Ko,7158 +tensorflow/include/google/protobuf/compiler/cpp/primitive_field.h,sha256=7ybPJYtNkkcqhXVx5EYiHN4vdANx4Hbtfep4sNycIBY,5726 +tensorflow/include/google/protobuf/compiler/cpp/service.h,sha256=fe7y_hgxcuJM6ys972qlmCj-60myrCJKBnIn4dHI8r4,4285 +tensorflow/include/google/protobuf/compiler/cpp/string_field.h,sha256=kIjZUGsvU9WjiE0Hj94_5P0XJq9MqHvschXCEcUxfyo,6178 +tensorflow/include/google/protobuf/compiler/cpp/unittest.h,sha256=QRuzQXJnP2mMT1x5It5WcZaJYRPHZCDLTigWtzYTVL0,2512 +tensorflow/include/google/protobuf/compiler/cpp/unittest.inc,sha256=5doWWelWK2j_jvOI05OYtqtwW2TEIpBHXApiMLm5HI4,78211 +tensorflow/include/google/protobuf/compiler/csharp/csharp_doc_comment.h,sha256=Xj-nTW1tX7-sKN6FdWdHBs3Ze-4LeVXAVXwIAC5U5Xc,2525 +tensorflow/include/google/protobuf/compiler/csharp/csharp_enum.h,sha256=ySV3MkoYJC0YTNI-lHRzdeg2jreq9fCXtM30ham9MNo,2572 +tensorflow/include/google/protobuf/compiler/csharp/csharp_enum_field.h,sha256=wGyozemPyb3E7AnE0RwhPieHEpsQNDguWCQ7B-tcogA,3547 +tensorflow/include/google/protobuf/compiler/csharp/csharp_field_base.h,sha256=WSqgxjg0GDquZeY4mKsMhF3bv5C3WkIBsDKoEYLoV7s,4704 +tensorflow/include/google/protobuf/compiler/csharp/csharp_generator.h,sha256=WD6_wa6xUPtWoPj_m2hhdiwcaLmKPCzmEwOVm-0QsLw,2812 +tensorflow/include/google/protobuf/compiler/csharp/csharp_helpers.h,sha256=LRp3S1Gy2Ms_okIu4qVG3mn3Shf6JsezclWhC0OnjYs,7778 +tensorflow/include/google/protobuf/compiler/csharp/csharp_map_field.h,sha256=CfhXwxbw6iEkpAdBUFmtApUDANL57sRdpOTbTU1Mj7g,3322 +tensorflow/include/google/protobuf/compiler/csharp/csharp_message.h,sha256=ySOGmL_3Nxhtkg8jwwC3fwhBYWXToOZzC7ZXEqMFOS0,3637 +tensorflow/include/google/protobuf/compiler/csharp/csharp_message_field.h,sha256=XCBqXENJibH-G59hZja0i4zNas9tMQYg7aBKKMMvA0g,4086 +tensorflow/include/google/protobuf/compiler/csharp/csharp_names.h,sha256=eVr2HX4BBr8Cggy-FCl7g8QvNbPRTyv_cSD9z8gju-s,4180 +tensorflow/include/google/protobuf/compiler/csharp/csharp_options.h,sha256=MThiH0VIrjimwMVtKbpW997YTWU_znEJ5YvOonmAEyo,3591 +tensorflow/include/google/protobuf/compiler/csharp/csharp_primitive_field.h,sha256=k_lxNvPzQoqF6DWHWPEcKMiNTR6-UHJJOYgRVX_zK0w,4114 +tensorflow/include/google/protobuf/compiler/csharp/csharp_reflection_class.h,sha256=Dh3c4J18TdnCIgBiLR0PXAT6RF5b9nh51twF4zhfphM,3019 +tensorflow/include/google/protobuf/compiler/csharp/csharp_repeated_enum_field.h,sha256=nDS07mAAb7D-11xonh4bgoSuTr3hA0GxdzSMhejve2c,3663 +tensorflow/include/google/protobuf/compiler/csharp/csharp_repeated_message_field.h,sha256=4666PjTbtyp05qa5iSfw-ky4N127nJe9E_yKxtf8tWY,3562 +tensorflow/include/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.h,sha256=BywYs9sILkYR8Wpi-b2JaBcWFJarK6VyiP4CZcWIGCg,3528 +tensorflow/include/google/protobuf/compiler/csharp/csharp_source_generator_base.h,sha256=TJqRTjEKGPKZsfBDZ_IQidJJuO4cyhKGKyaw8o-VBWg,2730 +tensorflow/include/google/protobuf/compiler/csharp/csharp_wrapper_field.h,sha256=PnDwkwO881yMvrpIbk0pVVYInuxAdLb31DlLktuUHf8,4506 +tensorflow/include/google/protobuf/compiler/importer.h,sha256=xjsLnhkHm-dhwX5Ubgf-MkxJtLnp_JUT6ubG2WBfLZs,14334 +tensorflow/include/google/protobuf/compiler/java/context.h,sha256=KIvTc_KW1kJEwyUuqKwVzGyP6sL-SDez6RBdzz5WSdI,4135 +tensorflow/include/google/protobuf/compiler/java/doc_comment.h,sha256=TcNTz3fxWAOtdnVBv-zSYcAeMmw8tZvWFJLYyvq32sE,4108 +tensorflow/include/google/protobuf/compiler/java/enum.h,sha256=ax_bT1FKR_hoiGB5XHtHsBLrtq9SGxEMq41j4Brl3-U,3431 +tensorflow/include/google/protobuf/compiler/java/enum_field.h,sha256=P3px5JJseAxoBtZwBDUNw5jPK4-0suIOvJFG43_RAIE,7105 +tensorflow/include/google/protobuf/compiler/java/enum_field_lite.h,sha256=o1cKPyvJ3rM18NFALm0VU0zfE0hzcd27PAOkcqaknaQ,5559 +tensorflow/include/google/protobuf/compiler/java/enum_lite.h,sha256=eGX1R6RLLBUBMC31ZtmCd9s3CTYgP1Ytblpo-9NbzbA,3438 +tensorflow/include/google/protobuf/compiler/java/extension.h,sha256=vRgt98M3nGTqRTXliYuhfryH2tqRu90mjeIFsbg5hk4,4173 +tensorflow/include/google/protobuf/compiler/java/extension_lite.h,sha256=R2V43Xisaa6KYt_HV2ZGuc2nAmBoh57avOXJ4vwuM64,3164 +tensorflow/include/google/protobuf/compiler/java/field.h,sha256=cioPraQkRqGXZKhPTqWnPELeoGD5zjvlkUBxpt9O8-0,7093 +tensorflow/include/google/protobuf/compiler/java/file.h,sha256=cTDSpcEeEX3Wfk8FBISThbp5uoZBy-KVLaOglFT3-2w,4833 +tensorflow/include/google/protobuf/compiler/java/generator.h,sha256=kAjvapLSAubYmRXuK54e52hJs5OqyBQWaB7CIZUgclc,3099 +tensorflow/include/google/protobuf/compiler/java/generator_factory.h,sha256=G9OJs60X1zlL82c0buI_nQOlbDm5wPEbCQ7IQecs6Ag,3652 +tensorflow/include/google/protobuf/compiler/java/helpers.h,sha256=EHCtw9RGx6TwVT4fV9h20rUQYT_KkqhTL_kaS_NkWT8,19669 +tensorflow/include/google/protobuf/compiler/java/java_generator.h,sha256=d6R4gjL26ovo8aMhnMLeE05y5XuJPrKDCHGSyqj2cPs,226 +tensorflow/include/google/protobuf/compiler/java/kotlin_generator.h,sha256=BnOmKzCMT9G_kpH4-bKeSPuVjb7IGTdrsQsO18UtrJg,2995 +tensorflow/include/google/protobuf/compiler/java/map_field.h,sha256=Q-pnYU5AoGXurKsjvI0O5yUszrz7Vgsk4eUOqZ4ZGHY,3758 +tensorflow/include/google/protobuf/compiler/java/map_field_lite.h,sha256=Bp0GQCDlFbw331pRLGxv1Xl_CAsdUKAeQ1Y0QGfU7BI,3204 +tensorflow/include/google/protobuf/compiler/java/message.h,sha256=lnXy7j36bUXtGMtI2FqyzVAV1wEIw6D6jD9YDhj-5yM,6212 +tensorflow/include/google/protobuf/compiler/java/message_builder.h,sha256=j8Zj5lkv__Bx9eyqIyZLUpM1hlXJc-P0RZWXeGxs6JQ,3623 +tensorflow/include/google/protobuf/compiler/java/message_builder_lite.h,sha256=qkwb_Ul_B4Rm15HHv47Fb222Blb_r5TdfD2De3f4YKI,3157 +tensorflow/include/google/protobuf/compiler/java/message_field.h,sha256=lHR42yFRfRulOX6Nda94zEdkfQ31efxqSgQBoMupbLo,8083 +tensorflow/include/google/protobuf/compiler/java/message_field_lite.h,sha256=8l-ygRk9JT03DYxQaSsfjHeLZHBdRo20JTcan69cXeU,5685 +tensorflow/include/google/protobuf/compiler/java/message_lite.h,sha256=oRbEPjEH_D8jH0mDiJcmWWJ6S6IzIGE7VD--46V4EWA,3724 +tensorflow/include/google/protobuf/compiler/java/name_resolver.h,sha256=eeUbry8aYijDAb132-SSq2Zw1dx4046VV7yBjkDNBxA,7403 +tensorflow/include/google/protobuf/compiler/java/names.h,sha256=wUERkxqlTmDF-R-4AQx4QoTZuTU4CIhxKzOA3dFP_8o,3277 +tensorflow/include/google/protobuf/compiler/java/options.h,sha256=ZYqQcjhr0tIJkQnKCB0RPAFKrWFaaDrfL2hyJEqvJWI,2847 +tensorflow/include/google/protobuf/compiler/java/primitive_field.h,sha256=5QKMWZ1MDnCqnvtWVDlfnPFm8Pbhal7Hgpb4NAJ-pNI,7131 +tensorflow/include/google/protobuf/compiler/java/primitive_field_lite.h,sha256=R8zZl6nX2YVcwCW4UOR0b4F6XaRj2MGv6Fet3tZF0Gs,5593 +tensorflow/include/google/protobuf/compiler/java/service.h,sha256=eWRylzBcHBSsMOvEUlQTd1B-Wc817gJlA2G9aaBWgIE,5041 +tensorflow/include/google/protobuf/compiler/java/shared_code_generator.h,sha256=2Nafx53Kvz_mSrDVo3vxM0ZjnM5luKxsJifUDDEGkC0,3310 +tensorflow/include/google/protobuf/compiler/java/string_field.h,sha256=9dHogBRRHaZ9pCf0R25xrauFD2HqDo0ybN-G38ofaUs,6974 +tensorflow/include/google/protobuf/compiler/java/string_field_lite.h,sha256=sjGaaAC4xdpI22toPCK3BrBCo25WQp43RPlbIl5yWb8,5595 +tensorflow/include/google/protobuf/compiler/mock_code_generator.h,sha256=trtqXeCy3zMlLVrfvfACKajjrKcUqjIV4Gyrg7M8nNs,6474 +tensorflow/include/google/protobuf/compiler/objectivec/objectivec_enum.h,sha256=pmpCUhovOy-qdeLy6icBmF1SGVNODd45S-IWpW68w7U,2756 +tensorflow/include/google/protobuf/compiler/objectivec/objectivec_enum_field.h,sha256=n28_zm1GLIoSQsHnGniseRbUBLW5C0qbV505tgwV74Q,3167 +tensorflow/include/google/protobuf/compiler/objectivec/objectivec_extension.h,sha256=LIKrFKNtmEyySXB0NxTFRMofJ6GweUMPvxysxk_UPPA,2786 +tensorflow/include/google/protobuf/compiler/objectivec/objectivec_field.h,sha256=yN2psLAnHzYlVGS6HpnCCLyQmSRsFLjKd418jjAJlSU,7271 +tensorflow/include/google/protobuf/compiler/objectivec/objectivec_file.h,sha256=xQVoNxTvzf_YvpuKmTTxLzYk8--l6O7IUkz1ZVxmAkI,4367 +tensorflow/include/google/protobuf/compiler/objectivec/objectivec_generator.h,sha256=MM4DeNfev-iWgRN398TPbp4eMia64QagYQUAX9waxnU,3399 +tensorflow/include/google/protobuf/compiler/objectivec/objectivec_helpers.h,sha256=74U5a-Rb-UhreNbdUKawidNX6EjBhxf1EFayjFBzh0k,14100 +tensorflow/include/google/protobuf/compiler/objectivec/objectivec_map_field.h,sha256=1xExqv59-Oo51qSws-QTby55eiz8oB8zhhWmhlLRC7c,2873 +tensorflow/include/google/protobuf/compiler/objectivec/objectivec_message.h,sha256=uYH9wiyx4mDQ5u5lB-w3ZydcB5UN3jBzXO6_bwYwIoI,4216 +tensorflow/include/google/protobuf/compiler/objectivec/objectivec_message_field.h,sha256=K-k4j05CDE0gmSeVEqfxnGm2YE-vV074wyLWCLqAIXs,3501 +tensorflow/include/google/protobuf/compiler/objectivec/objectivec_nsobject_methods.h,sha256=ExUbgE1vloAEZGsC4hYKGwpgz7eY-XR2iId4wG1NFLM,5212 +tensorflow/include/google/protobuf/compiler/objectivec/objectivec_oneof.h,sha256=2Tt0AkaNh1bImPHylH7Dq45lsLXYVSeIew0z5eOUTCs,2911 +tensorflow/include/google/protobuf/compiler/objectivec/objectivec_primitive_field.h,sha256=JGfxYSUvzr5lezPC10WE1Q3e8X0hMn3O3ZiluqiTxl8,3664 +tensorflow/include/google/protobuf/compiler/package_info.h,sha256=bVhLLISW2PcMy4qmvf-Ds_sbtZMSQedDII0sS4pxkNE,3211 +tensorflow/include/google/protobuf/compiler/parser.h,sha256=d3IH5GGJG8hn3bcNbqeZdbybJ4yStnguIZ6aRLrPR1g,27832 +tensorflow/include/google/protobuf/compiler/php/php_generator.h,sha256=zYYcWolQpKiIIzIECUua9cFKWpQ1eeWMVLb7lj7U3iU,3548 +tensorflow/include/google/protobuf/compiler/plugin.h,sha256=eykLrZeJKNk0XSiERAqj9ID0vrlg2arsov8Re95Cml0,4376 +tensorflow/include/google/protobuf/compiler/plugin.pb.h,sha256=VdAZ1LWVxKdt7VOK-p-TjwGr2-guOlQbdUsnSx0WE0A,78616 +tensorflow/include/google/protobuf/compiler/python/generator.h,sha256=GI6GGACrZD_eTPOQhkxtG83FaFjcXUqAK1llxGP4wWE,7924 +tensorflow/include/google/protobuf/compiler/python/helpers.h,sha256=cgg5x8BzVgjsaY4buDOco5OMPaBs_7ji5TN3Wyh3M5c,2670 +tensorflow/include/google/protobuf/compiler/python/pyi_generator.h,sha256=ar81a5q0yDEtwOixWH0tpyfMQCe7EwCCfiTGslNRtcY,4894 +tensorflow/include/google/protobuf/compiler/python/python_generator.h,sha256=hfLhhfkhfJfMHXWcnT3wkUxEQgneNirpDa_skK9h_L4,240 +tensorflow/include/google/protobuf/compiler/ruby/ruby_generator.h,sha256=dKPUjehQoPy5hmv91rtmjEQD6K5E27k4oLwq48fi7xo,2820 +tensorflow/include/google/protobuf/compiler/scc.h,sha256=Wh2zLJCkrqblTC2KHMsbomhm7CalipVlmTii3kEhSjQ,5776 +tensorflow/include/google/protobuf/compiler/subprocess.h,sha256=0m10in0hs8QgZ7O3bDj12NIgfqguOFX4DSZ4jSkz8Ng,3946 +tensorflow/include/google/protobuf/compiler/zip_writer.h,sha256=6ZD-xpdolFufQ0QWa47p6y6f4xXVaHFFuBmyVFhNaE8,2506 +tensorflow/include/google/protobuf/descriptor.h,sha256=7U3TVWJg9lDXqgVIDDoldX-dnczYWQR0VI8ODzZrFlA,100824 +tensorflow/include/google/protobuf/descriptor.pb.h,sha256=xwRbumKagkv8ltRb3VdiHcGPBhWZ6oCfjhpe4TXPMQw,611700 +tensorflow/include/google/protobuf/descriptor_database.h,sha256=tXMubqYZXWhN0DHiiG4ifTXl-Wj1zciSHlA2mjUSxn8,18897 +tensorflow/include/google/protobuf/duration.pb.h,sha256=ue696-2fap6w4ahNLafgFi5wvXkss6lDTqKSGTPAWeQ,9169 +tensorflow/include/google/protobuf/dynamic_message.h,sha256=XRnGNXRfqEIvfbGni9_lCNiQ_Bdogb4qwykW13NGrVc,9143 +tensorflow/include/google/protobuf/empty.pb.h,sha256=DooyOhT9xagv0FIE5sv0UVTyKx_SxUPRq5IDzPLUE0k,6732 +tensorflow/include/google/protobuf/endian.h,sha256=2jrKOn21cI3srD-mQGxZMNVWEcgvTc6EAkDuKBFwjHc,5129 +tensorflow/include/google/protobuf/explicitly_constructed.h,sha256=ixVqccaQ4LHhn2Wx3DmWgKauAH_oILMSqyBNDy-7bXk,3927 +tensorflow/include/google/protobuf/extension_set.h,sha256=gKabCy3EjmwQsgQETjvFxeoeTeEl5VRtONf9SPH9sBI,71882 +tensorflow/include/google/protobuf/extension_set_inl.h,sha256=gQt16S3K37wef5FDPBDRRp5eMS2VqS_BN9KX_v7Um2o,12753 +tensorflow/include/google/protobuf/field_access_listener.h,sha256=pXnyawvT4ax-cLRtwWqVKTd9zcq6XlZcFuqKh3phiW4,7457 +tensorflow/include/google/protobuf/field_mask.pb.h,sha256=lhmDPPTs0xthoWRQG3qTOyX7e2xZ8Yqrx5H_NlOn7Xw,11630 +tensorflow/include/google/protobuf/generated_enum_reflection.h,sha256=W7EiXoc19YL_ne3Y5huU4NC8zdpuPq9Xm1FnLRqfHZg,4020 +tensorflow/include/google/protobuf/generated_enum_util.h,sha256=II3yg2uU1V7zDF-U_MEfGRVSPWheeGkSoUXRR0lEn2I,3293 +tensorflow/include/google/protobuf/generated_message_bases.h,sha256=3zalA0lxAhCSbUOUNtKeAebwkgE0Z7itwujzIfXAYzI,3611 +tensorflow/include/google/protobuf/generated_message_reflection.h,sha256=SCT33kgunxw-4oXhDAinqNFQlLeRWmExApATna07xH0,14184 +tensorflow/include/google/protobuf/generated_message_tctable_decl.h,sha256=qj-BPJSRU4GAM8rDzLLtPcrdAT1SFZcdOV_lSRa_3eU,12372 +tensorflow/include/google/protobuf/generated_message_tctable_impl.h,sha256=bzkVxjYZnI0ZN0IHeNtOn_tN27zdNr7qF2Y91_K7hi0,23027 +tensorflow/include/google/protobuf/generated_message_util.h,sha256=EGLXxbeUs3ezaq-KBh98N7iIadi_OAtF-83PLhhpeBU,8241 +tensorflow/include/google/protobuf/has_bits.h,sha256=0CqOb9wXvvuedWUw0emgVCwYYIpC6o-BTZyJk6aSwMc,3574 +tensorflow/include/google/protobuf/implicit_weak_message.h,sha256=JLJPcizIfRBqkNKvQneQKZ7MlINDmomrXnuYcQLDAmA,7794 +tensorflow/include/google/protobuf/inlined_string_field.h,sha256=toA1I0Lsf1lt0wrzCJEZAiUClYBdkRrCZSCZ_dJxcTw,21605 +tensorflow/include/google/protobuf/io/coded_stream.h,sha256=b3shiHylXufu-lrdJ-0QJlZ7v458q-dLkzTXZQpSerY,73504 +tensorflow/include/google/protobuf/io/gzip_stream.h,sha256=rVnAQDZl-HZdoadE__kU98yOz_Ruybm8VNJAwOOT0Z0,6825 +tensorflow/include/google/protobuf/io/io_win32.h,sha256=b0NPnDG-dHyQ5p68xho54b30zCm-PoOLVGeSDUP9Umg,5411 +tensorflow/include/google/protobuf/io/package_info.h,sha256=z-_vsmRgvwAxlQrhQt-rIa2p2r-PGZrFikiJ7ZE24r8,2541 +tensorflow/include/google/protobuf/io/printer.h,sha256=Q-Is0qpkHQc7FoIJ1X-zdohChKu9_Y3mO8pDna9BTec,15953 +tensorflow/include/google/protobuf/io/strtod.h,sha256=ri1B0MEU1A5qH24w2AryLkbJx_4j7C9fUGiOG-A-Bss,2431 +tensorflow/include/google/protobuf/io/tokenizer.h,sha256=7OvLNYzAvXBtizJPZDAiGKDTcBX2hXWyJoSsa2pl75U,18080 +tensorflow/include/google/protobuf/io/zero_copy_stream.h,sha256=AD3vPjoOz7NKEQNGqUmY63Wpd87tblunvQJ_4aHzA5U,10689 +tensorflow/include/google/protobuf/io/zero_copy_stream_impl.h,sha256=PmX75LDLLkaeIsUM9Or153xL_G4wZ0DHaDmwqRn_xJM,13014 +tensorflow/include/google/protobuf/io/zero_copy_stream_impl_lite.h,sha256=htYjPtZ961cJ5P02T2F1bpbGV1lqE5s6xwfAmxwd97o,17098 +tensorflow/include/google/protobuf/map.h,sha256=Df7rdQ6Lv5bT2V6VNeXf2Qne33ZQxCssOAKupkbkzLs,52443 +tensorflow/include/google/protobuf/map_entry.h,sha256=hg5j7UemlBOpIp9QRuRyeY5sP9Wjlc6IAITv2bB8XMY,5743 +tensorflow/include/google/protobuf/map_entry_lite.h,sha256=artSFF6SEqcDhk6UG3YdKZSObAKr7DK-NNQIrnAD7QY,21363 +tensorflow/include/google/protobuf/map_field.h,sha256=itdAAtfm2Cb0uFfcTWBO4ZW0VHXpmTwj2oJSi-J9INc,34694 +tensorflow/include/google/protobuf/map_field_inl.h,sha256=cFXRopY-CT4SMM_40CNfdVdzWVtJ4QrDHHUMVzLQYfA,14537 +tensorflow/include/google/protobuf/map_field_lite.h,sha256=cRhSr-3JZOfOK0PFqTmT-b7NgWqPaI-kTqBH-WgC0us,7783 +tensorflow/include/google/protobuf/map_lite_test_util.h,sha256=bH8hTZRvpaFqwNnQQGSOM4OVpBFcKr1gM_DEaNMPHA0,3515 +tensorflow/include/google/protobuf/map_test.inc,sha256=Vyv_Airnd0PCiCxmJgMBpgTv-IiupTi7C8GH-IgZ1TU,146388 +tensorflow/include/google/protobuf/map_test_util.h,sha256=LHQfQJYHjDRWqk7CvGnjl_XVoslJeZ-N4bcmIYJxj84,2117 +tensorflow/include/google/protobuf/map_test_util.inc,sha256=tbJ7IRoWbiOn-8mJ8JgwAj6RlXuoVROowAikQrxw50U,12943 +tensorflow/include/google/protobuf/map_test_util_impl.h,sha256=uE6IRurUwi5ZbW-TX3pD0ECwTkq4ZnDJ95ER3NrNQXo,22393 +tensorflow/include/google/protobuf/map_type_handler.h,sha256=A3IXMB5rco_4KX4sP6n1gMl33kOSwzqXdykLGcf-koE,34157 +tensorflow/include/google/protobuf/message.h,sha256=De24EZPYRSl6dBQtP71Un1PecH8PbTfNhdVfsjPa6ZM,70146 +tensorflow/include/google/protobuf/message_lite.h,sha256=lw02cWXM1e0M_F8Dbxh8xw5gFCLtaMxYr8TsZMd-Xtg,25860 +tensorflow/include/google/protobuf/message_unittest.inc,sha256=zSflfw141-X5V5vhTkr0SB4Ae8HUZgokFJ0cKovLhoI,38678 +tensorflow/include/google/protobuf/metadata.h,sha256=Yq7QejpBOIH3tUPx9U5NYdWZ_lsbv3Zug5cRZDCfS8c,1857 +tensorflow/include/google/protobuf/metadata_lite.h,sha256=fAAEQHN_HCbJu5H5dYFjMzx8Y49GHvVwa43jcq2IY0I,11072 +tensorflow/include/google/protobuf/package_info.h,sha256=pULbhejMVBdifi26tIwXzo4PMw1A1d_dFHvEBVaGfEA,3323 +tensorflow/include/google/protobuf/parse_context.h,sha256=0oBTaIpCdgT36Hbzeqm_luXvq-Pa-YQBCzDG26_LEE4,38891 +tensorflow/include/google/protobuf/port.h,sha256=I_3ybo-42_SBTeqNTyxneylotqg0jjCxqYFOpLVvmrc,3094 +tensorflow/include/google/protobuf/port_def.inc,sha256=xgooEQwuZUolWiEPjHBkgqwqc8KEHRCmlqoBZXF6-8s,34030 +tensorflow/include/google/protobuf/port_undef.inc,sha256=hYX3pwgfvapgnzDa61iJPPB265OKNLuXQQWtBKn643k,5435 +tensorflow/include/google/protobuf/proto3_lite_unittest.inc,sha256=ub4kVlQfp1J3E0YmYAnqbGzBoFuD1etPUX6Z1DW5gt0,5742 +tensorflow/include/google/protobuf/reflection.h,sha256=gPkOchHhIUkDgUU3x8UcIxjprfvIhF2qrg4vLiBfjkk,22903 +tensorflow/include/google/protobuf/reflection_internal.h,sha256=_TaMfEiqD01izVWTTVmPZq9a21OFMFuPt12_Z0ovzcA,14583 +tensorflow/include/google/protobuf/reflection_ops.h,sha256=XkBrZ_AlVFhGN0i_OInRewXKFGTYdkPNfTK299TTkFs,3836 +tensorflow/include/google/protobuf/reflection_tester.h,sha256=vTaBj_14GsmOXiaLWERqH-eHWvbBb2hUEzPkSrGUmOk,5563 +tensorflow/include/google/protobuf/repeated_field.h,sha256=vLlmgU3WrqcfffF6uKDkgu_Tf5Vm1O7sUoqcMUpt7_Q,42987 +tensorflow/include/google/protobuf/repeated_ptr_field.h,sha256=Auoo8tn3dxbAi6qvFWo3PFwvnQTvhyYj68WmUjB9qVk,71413 +tensorflow/include/google/protobuf/service.h,sha256=yFXaWj8HsxPD3wve6ZTo9DzZO9wQD2V2_k1b1hTREs0,13186 +tensorflow/include/google/protobuf/source_context.pb.h,sha256=fj7NS4lgnQiqVePdJNxdt9PdaLiP-4jc6Oxoj7vikVM,10297 +tensorflow/include/google/protobuf/string_member_robber.h,sha256=xnOzSqDcT6CHXOh6c4EGC_HF1-1EOj63oPlYFW7HkdE,1854 +tensorflow/include/google/protobuf/struct.pb.h,sha256=kpBjahCao7xQte5oNkQqKYG6IsOSmJd75WzI5PW6KIo,42063 +tensorflow/include/google/protobuf/stubs/bytestream.h,sha256=rK8URnVdQ-P8ETD489YOczgY3aeAEjdH5jVh3ePuGBo,11769 +tensorflow/include/google/protobuf/stubs/callback.h,sha256=azRWIkSeMkfL5cdRrRF1hkIQnDAgeqnuZn3eGpe9BB8,17098 +tensorflow/include/google/protobuf/stubs/casts.h,sha256=NrqsnBN2eldtRX_MY9xQWSEsUvpbyNzWpEuTCWRjWOg,5703 +tensorflow/include/google/protobuf/stubs/common.h,sha256=pJA1IfVBgUtYoqdFHazRdoHybqc6kAxNFAgW6PmeW0o,7136 +tensorflow/include/google/protobuf/stubs/hash.h,sha256=PI197Pnxa-F3uj90TYdEk6-pyimQHqufBUsbQERqb8w,3911 +tensorflow/include/google/protobuf/stubs/int128.h,sha256=KaggohpEbsPG7ZEnlSYSJCgcwaCnkAZm-l0u-ns__18,12043 +tensorflow/include/google/protobuf/stubs/logging.h,sha256=aI0GG1TBCd2lYcxaNtJdg5Fa1Wmuzao6vBG117O3fYU,8952 +tensorflow/include/google/protobuf/stubs/macros.h,sha256=DF_YcNVX35QrWa1GEJN6gOjpQyxFu9i3dFlVNpuJkik,4117 +tensorflow/include/google/protobuf/stubs/map_util.h,sha256=J8WPjmcTqQFHdd_94IOOT6ajnvfbGknd64MYHQLvwgg,31213 +tensorflow/include/google/protobuf/stubs/mathutil.h,sha256=peWK7wEqq4MC1V-jXr-838aNVr5uBxHyQsFTVW-MeHc,5977 +tensorflow/include/google/protobuf/stubs/mutex.h,sha256=j7TWi8LuqwcNAgL4MXexAKjeJszBrITZlwvO8hrrBj4,7008 +tensorflow/include/google/protobuf/stubs/once.h,sha256=hF26IIrrRP0L9uH-QQmzXQZhkNBWZDnPpoZ3Wp4MmgQ,2184 +tensorflow/include/google/protobuf/stubs/platform_macros.h,sha256=TmfYS9O7fGk_2giGRzaCfi-YE-QZsd2v_I_TAlnll7s,5150 +tensorflow/include/google/protobuf/stubs/port.h,sha256=URhaYHOaQktY3mZ_GDxtRJ4041YNPbChHcWMh4RmULo,13099 +tensorflow/include/google/protobuf/stubs/status.h,sha256=x5omqY9gJqQusa-nNvu4LXY_tDyKptlOA7oonci_Zj4,8592 +tensorflow/include/google/protobuf/stubs/status_macros.h,sha256=5l9x91lVFPaEth1-tGiOn3O8anwfjxfpu4oxFClQ3CE,3774 +tensorflow/include/google/protobuf/stubs/statusor.h,sha256=xt8-tBDzeVOhgYqKdSPQBAqKsRu9NQXd5BBl0BYTxdA,8016 +tensorflow/include/google/protobuf/stubs/stl_util.h,sha256=lqQ05PrFe_Pkh5CgFns6MOJzraabSKnmBOt7BE8qZOY,3933 +tensorflow/include/google/protobuf/stubs/stringpiece.h,sha256=DUy61xpvkYka1Xg_WoSm7cZhgzQLdgnTqTiJaNuOiXE,15092 +tensorflow/include/google/protobuf/stubs/stringprintf.h,sha256=apJKg1AXZiEGbYGVAajoCVRMpznT_-hCxEfWuxHiWv8,3615 +tensorflow/include/google/protobuf/stubs/strutil.h,sha256=yp-MtxWPVFnTwVX2ZSbVPX3hPpOW0peVAwHxmI-3gXQ,39600 +tensorflow/include/google/protobuf/stubs/substitute.h,sha256=VofC1WW5OaxeiZgH92sV2sro6XUhmCa8VbdO7yoyqos,7911 +tensorflow/include/google/protobuf/stubs/template_util.h,sha256=eWWbVMKQnOR-6qJCAXcd-w5rfN3TCxDMa-7d-SFTvAg,4834 +tensorflow/include/google/protobuf/stubs/time.h,sha256=wblegAIeK3k8-I3O2Kf_ZDU-GvL6E-pwy3p_HvyHM_g,3392 +tensorflow/include/google/protobuf/test_util.h,sha256=khxbp5-kP_6UqgWxKMPKiVdPMPF3-VYqcaNRJcubwlk,64088 +tensorflow/include/google/protobuf/test_util.inc,sha256=WvVxHphQbj4qD1LZtMpJXMUdb-OvI0Vl6ydZ2yxqCTU,117683 +tensorflow/include/google/protobuf/test_util2.h,sha256=QmgOzy8PI34ox0Ctwtzplbc4CYgW-wNM78NKOXhsbwI,4248 +tensorflow/include/google/protobuf/test_util_lite.h,sha256=Y0VsVps0kSx2-BEVLI0eo33yDpF-I7gAAQ6K3N4Tq0A,4513 +tensorflow/include/google/protobuf/testing/file.h,sha256=xLVSHFKcW8f7cZ0cJeA0GP79UJkaB5Ry0HGo502EmaA,4364 +tensorflow/include/google/protobuf/testing/googletest.h,sha256=e5jSr7sX0F1pLSjWOmm4K2PNkH_nzvqaEaRUrVUeTEo,4052 +tensorflow/include/google/protobuf/text_format.h,sha256=4xRe07I0HKHZ8i8Sh26-NDmLbQl_e4SpGhagOLlJbhI,30940 +tensorflow/include/google/protobuf/timestamp.pb.h,sha256=3V9ptN5z-GXACkrRux_4Cm3YThrQPo8FBu33EiR42Dc,9230 +tensorflow/include/google/protobuf/type.pb.h,sha256=pjJpfGDzmQ-XZbvuQdAZSzpo38AE0gppDCWnjg48lds,93697 +tensorflow/include/google/protobuf/unknown_field_set.h,sha256=1DCgE420ZLpD2plm6bC2cwzUEpWUZqtoCxhlyWXHH0M,14172 +tensorflow/include/google/protobuf/util/delimited_message_util.h,sha256=9O6Nw3RlM775TliIlAUQN8iGvuPLiaeXE-TY5vbMaJs,5425 +tensorflow/include/google/protobuf/util/field_comparator.h,sha256=EJhmMb4BGIfhA1yvcZVm8RNyxMfDxpw8mTx2NK1V4Cg,11707 +tensorflow/include/google/protobuf/util/field_mask_util.h,sha256=nA0q-Y2TDLy-AqTGLhbWjlTXgOfQKLuvr2r7O-h8I9Y,11413 +tensorflow/include/google/protobuf/util/internal/constants.h,sha256=9Ehp6gNXugGd92bYl8QyM4oc7jZ1WZhIjJYC_MoV98E,4141 +tensorflow/include/google/protobuf/util/internal/datapiece.h,sha256=HEOnEse7kZnc-i8kVBiBiVvUQyjdGGZsv3BrHSgmnuA,7964 +tensorflow/include/google/protobuf/util/internal/default_value_objectwriter.h,sha256=WLNnlUf3r7ROK0Of9pz-r-gHgiDJlDz5jYxs9QvOsnY,12771 +tensorflow/include/google/protobuf/util/internal/error_listener.h,sha256=fxPS27SmVN2siCAYeq9Ccgh6dh5UwyrnVN2YTQ7idrw,4006 +tensorflow/include/google/protobuf/util/internal/expecting_objectwriter.h,sha256=ijU-9cabPK2emA8Z6g8b80B0diP2wR1e6YUu4dMscLA,9653 +tensorflow/include/google/protobuf/util/internal/field_mask_utility.h,sha256=sp--XngwfyCY26CGJw-q4sEg5T2EShde5j-PxE646GE,3391 +tensorflow/include/google/protobuf/util/internal/json_escaping.h,sha256=LYQzTuYBz4o3hHE-qkxmEGnO30a21nISOFO7vwKH4R4,4249 +tensorflow/include/google/protobuf/util/internal/json_objectwriter.h,sha256=HYsXpSLCdRyKQjMUeW04bOrejVdRvEeHVHrHRS6efYY,9923 +tensorflow/include/google/protobuf/util/internal/json_stream_parser.h,sha256=f2L5URLCLcZfxQ1jqCOr3Am8HyWDVyCq6U0tcZ_7vPY,12679 +tensorflow/include/google/protobuf/util/internal/location_tracker.h,sha256=qh2ntSeZtLl3h308i0sWVB0VQgOSeNOiX7e3tFTh2BA,2701 +tensorflow/include/google/protobuf/util/internal/mock_error_listener.h,sha256=JwDKcm1Osw9waH3ezYDG3jQpa4zjh3yCfWlpu06Qfk4,2837 +tensorflow/include/google/protobuf/util/internal/object_location_tracker.h,sha256=K4qIb31wlCU5fA_I3igcqqbCSQVo18-hDlbI8IeWnGM,2585 +tensorflow/include/google/protobuf/util/internal/object_source.h,sha256=y4kvAlZtJvcaahGm45BsQPeZF-9aU6d-oo_zg0p-I6A,3240 +tensorflow/include/google/protobuf/util/internal/object_writer.h,sha256=sassT3h2rwm8xw1pK-ePHUobwHM9HcrAt7ONMA8nsnE,5513 +tensorflow/include/google/protobuf/util/internal/proto_writer.h,sha256=N8Ugwjtvgnj-VbiGhRDAxkO6tQ3GpjhVs4XTUwIN_BY,15354 +tensorflow/include/google/protobuf/util/internal/protostream_objectsource.h,sha256=g3bz6vbWqt85D_YFP5WjSfooBujC6CI2MRBZfPAbVZw,14733 +tensorflow/include/google/protobuf/util/internal/protostream_objectwriter.h,sha256=TbGGaT63coWEBqewLwyfHF_he97LMM-8m3n_N3iiQ1c,17147 +tensorflow/include/google/protobuf/util/internal/structured_objectwriter.h,sha256=zKL8cjTyt-gVq1gRWW9DnZ_C3_EGWSKV1HCsYMFuGd4,4672 +tensorflow/include/google/protobuf/util/internal/type_info.h,sha256=Pdfr75fbV5EpELbS8NaV4HlmayGTShy_uaXZfltcDqQ,4052 +tensorflow/include/google/protobuf/util/internal/type_info_test_helper.h,sha256=u_Dsdk3wM--QFWBWfEtz5xM5lHZQTBQEORZwK3w-zvg,3999 +tensorflow/include/google/protobuf/util/internal/utility.h,sha256=W2ECxxeUBIGftsU3b2kkkQHeJ44Ddl5oEbo1hn9Bmwg,8456 +tensorflow/include/google/protobuf/util/json_util.h,sha256=kbpEKhjpTRXXMO2xkZiuCj9imIyFitPBorGWMGA2pCo,8585 +tensorflow/include/google/protobuf/util/message_differencer.h,sha256=QACmNyADvPo-cMFW8iFk6WATanfz0a1Fqmgd70m24AM,47444 +tensorflow/include/google/protobuf/util/package_info.h,sha256=gDrP_hRoSQVhUIXYdN8khVmtROfKcBWmV1ZUmsyciPc,2080 +tensorflow/include/google/protobuf/util/time_util.h,sha256=cMQwuf3SJrxO3mZwIQIZ8IVGBfKboHgJLwwmesOuy7g,12258 +tensorflow/include/google/protobuf/util/type_resolver.h,sha256=_TA378Y_gWrduvTwOper_VA3MIQzKEDjJsXVKI5cPAs,2919 +tensorflow/include/google/protobuf/util/type_resolver_util.h,sha256=CrrVVBD3kETmuD3zrRyGgZqf14c36Xkffkq46-963Kc,2433 +tensorflow/include/google/protobuf/wire_format.h,sha256=UCSstxQbAE1zAOoxNfk2QJlEPiknmdybE7lPa7TgsZw,18120 +tensorflow/include/google/protobuf/wire_format_lite.h,sha256=JAPJe_OBPF519IKU86jO7lJqij6-dUWyPurIQQ6cQGw,85753 +tensorflow/include/google/protobuf/wire_format_unittest.inc,sha256=9kG5xYL8GQM8B61MUnt8ndTZEqVhzi2xqDHYQd_6mRc,57604 +tensorflow/include/google/protobuf/wrappers.pb.h,sha256=eS_ngwrXICl2mRRuV41o9LscmvBGtp4KGwh_hogAk7o,59294 +tensorflow/include/include/json/allocator.h,sha256=4oazYhsPJg-2NP58LPdZHOmDq45ZC5cFmBKVtMRQn9Y,2447 +tensorflow/include/include/json/assertions.h,sha256=6jC4-zDvcKUqZDX25u-8N94DVV-hkrM4MuZcvRWbaLs,2817 +tensorflow/include/include/json/config.h,sha256=pgfjLjRJfixR3xxh5mJ3YGGNfWlk2fR9-oFlrTBQY7k,5272 +tensorflow/include/include/json/forwards.h,sha256=TlFEBi8pbIIRB68nLDnfMbesb8_vvrZmN5WHOPwJoRc,917 +tensorflow/include/include/json/json.h,sha256=BcyzWvpVoGj4zCoZXbRtiaf2pFjRlDrgCUZYNMZASmc,447 +tensorflow/include/include/json/json_features.h,sha256=WgikweSvwEeRWgHc4ou7pp_usvRS4IccAtb5Dy0wzWg,1793 +tensorflow/include/include/json/reader.h,sha256=N_SLz_2ynvY3S4lJVpVmJ8_t8QayrOkL_Sbm8N-yVXc,14147 +tensorflow/include/include/json/value.h,sha256=S1e6SUmcBN4D9d-Ej4cU6os0V40ImuVsGlrvoN88X_o,30295 +tensorflow/include/include/json/version.h,sha256=dSzdYcuXrKTcu22D1bkYSfz-AelL3zBI1UO6p6F_oAE,966 +tensorflow/include/include/json/writer.h,sha256=Vayn9-rwre31ofKqgAbbqid9_nplmwSRMEsQQ9kJGms,12095 +tensorflow/include/ml_dtypes/_ml_dtypes_ext.so,sha256=QBV6ReZ1yQ9c_357cMLD9K9goaDQ89E0_freQ0HSIAU,3282120 +tensorflow/include/ml_dtypes/_virtual_includes/float8/ml_dtypes/include/float8.h,sha256=0nmPrU5kN1tWax3x17xEAxPksQJMoI8Szq0-qktz_3I,51353 +tensorflow/include/ml_dtypes/_virtual_includes/int4/ml_dtypes/include/int4.h,sha256=s6mXDDxrFpxBrC_UN19mjT_RtJLUi5EtiUFfoVIqj1A,8784 +tensorflow/include/ml_dtypes/include/float8.h,sha256=0nmPrU5kN1tWax3x17xEAxPksQJMoI8Szq0-qktz_3I,51353 +tensorflow/include/ml_dtypes/include/int4.h,sha256=s6mXDDxrFpxBrC_UN19mjT_RtJLUi5EtiUFfoVIqj1A,8784 +tensorflow/include/tensorflow/c/c_api.h,sha256=LGESlRSXnXf69ibzBQxQOWWbITxOEsKP1X8OpXb3XLU,83812 +tensorflow/include/tensorflow/c/c_api_experimental.h,sha256=z9BLfjiVv2XuBVaiDBMVsRkAXt7NpmBHn0ktFyWYolg,15463 +tensorflow/include/tensorflow/c/c_api_internal.h,sha256=Mv-yPwYcTcHRbDOBqh7lAK_2qNmyacReMGmvcdZNcdw,7781 +tensorflow/include/tensorflow/c/c_api_macros.h,sha256=IiEt4w3Ka8gM-QO1sC-OJAuJzK5NJz2Gs80jIDjeai0,1673 +tensorflow/include/tensorflow/c/c_api_macros_internal.h,sha256=W3cm07zy1fB2RoClppTtyI9OPSw6UgsCjwBBNOvY52U,2535 +tensorflow/include/tensorflow/c/conversion_macros.h,sha256=Lzlv_8ExJPHEhqis5TwJiX-56GrKmCppz54zYbadmmQ,1777 +tensorflow/include/tensorflow/c/eager/abstract_context.h,sha256=8XcAaCw5QK9S20PvMTEMbRcERJGjlTZMoJpnkz0CSE8,3026 +tensorflow/include/tensorflow/c/eager/abstract_function.h,sha256=egxumRzligWM_5pCO_5WE-l5GKKzE3LRRyZFcHpvccY,1782 +tensorflow/include/tensorflow/c/eager/abstract_op_attrs.h,sha256=Dhkqj2txgLvBc62G24u1P8K5Yx-jkibAPkyyn8SbiS8,2018 +tensorflow/include/tensorflow/c/eager/abstract_operation.h,sha256=4h2YjQbsmScgs843f-dWfoSwSmg_JXKNoKUnXepS7xk,6966 +tensorflow/include/tensorflow/c/eager/abstract_tensor_handle.h,sha256=N4iOkM6VHMz0p03vPTD4koFm4Z7r_rYtnZFsxZvpsXQ,3083 +tensorflow/include/tensorflow/c/eager/c_api.h,sha256=PF8LEUqeaw5idMuuo9JyRl6uUgg6Xdn78MwNJ_02yxM,23340 +tensorflow/include/tensorflow/c/eager/c_api_experimental.h,sha256=G5iAfeUxF0gZRjQfSQvezFrULmpCqMJR5cp_O6GA85c,40417 +tensorflow/include/tensorflow/c/eager/c_api_internal.h,sha256=EZiyzC-MKD_v28Vt4l4TUVtwXCnHwWiH5jQBzLHK8PY,1922 +tensorflow/include/tensorflow/c/eager/c_api_unified_experimental.h,sha256=ZNYvUUaXQ0n5q32A9LKGAjCvf3tRE4sFGVGOi_usmUg,7193 +tensorflow/include/tensorflow/c/eager/c_api_unified_experimental_internal.h,sha256=FyuF6j-NqA4Ydj9EVNKhGErmrLfEYaN6SAJmNCNlFXY,5308 +tensorflow/include/tensorflow/c/eager/dlpack.h,sha256=2BEcLmw_pR_xnnnLNJax0Y3LHw5x62ZD5GpI59Bgabs,1674 +tensorflow/include/tensorflow/c/eager/graph_function.h,sha256=L8CNTPGikDI9MJ1hMGpx-LdRg386_sygziPh4m9lb_o,1495 +tensorflow/include/tensorflow/c/eager/immediate_execution_context.h,sha256=w9_q2XJ8IcttDyBGIorFnIXB6If6Gp8QrTEmXYNaFeE,12562 +tensorflow/include/tensorflow/c/eager/immediate_execution_distributed_manager.h,sha256=tVncAuECVqT-R1EY7aHfe9Rhym2kBZ9X6hIUprf-9_4,2952 +tensorflow/include/tensorflow/c/eager/immediate_execution_operation.h,sha256=gnviDXzVOMDiB7X1_nvcE6M-KDp_12G0Jk9joy-cL6A,3657 +tensorflow/include/tensorflow/c/eager/immediate_execution_tensor_handle.h,sha256=FkgiE6tY7thsyv71HvFKeVlRTgEmX6C4BUlEg-GJcM8,4368 +tensorflow/include/tensorflow/c/eager/tape.h,sha256=sSbXonCW5IMxSqdhEg6GyOTTPdVZqi-LR2dm4ASeM9U,48251 +tensorflow/include/tensorflow/c/eager/tfe_cancellation_manager_internal.h,sha256=5IqmgywpklsYmd40a8OxSNnAnz0kdImejJkzSSwli_Q,1342 +tensorflow/include/tensorflow/c/eager/tfe_context_internal.h,sha256=PsSYz5rsbL1FvyNyk7XjXKKR8OMfiDxjR_yr2vNADLQ,1413 +tensorflow/include/tensorflow/c/eager/tfe_executor_internal.h,sha256=CpRSVeNLJyA14ZiGK7pO4zmtWOTJ6CWuQn14N2VhJ6M,1545 +tensorflow/include/tensorflow/c/eager/tfe_monitoring_internal.h,sha256=U1BdQ4X9hPgZcW8ZIBBoPVhYyQnqAyUeXwcKGcwT3QM,5275 +tensorflow/include/tensorflow/c/eager/tfe_op_attrs_internal.h,sha256=_-dsIifn0xxS2ACYudxndZnjaJC-kRUVzyPKvpmn-wI,1634 +tensorflow/include/tensorflow/c/eager/tfe_op_internal.h,sha256=UNnXc4kdh7wa43vSHvJjHPwuEvPVBkpHlWdbNf7YA9Q,1464 +tensorflow/include/tensorflow/c/eager/tfe_tensor_debug_info_internal.h,sha256=W4Z2K1oquhxrgbjJsietgAMH1MaE19ajFudPe8J7fsI,1113 +tensorflow/include/tensorflow/c/eager/tfe_tensorhandle_internal.h,sha256=HPMFZ2txv49RZZekQEKNHLWXZUnWGNnV9HhPmTHjED8,1617 +tensorflow/include/tensorflow/c/env.h,sha256=dxFYmKuhDiW-1pO1SE6VugFcLyCJWGCBvcSylxXOE3Y,9852 +tensorflow/include/tensorflow/c/experimental/filesystem/filesystem_interface.h,sha256=BCtnS_-64RQhBHlEns5ikzDBdsmnUcvdiFgzb84K6uM,54357 +tensorflow/include/tensorflow/c/experimental/filesystem/modular_filesystem.h,sha256=vWF7I_ZQaJWFJikweXQj2abdBssoa1P76WKKBGiQRoI,8844 +tensorflow/include/tensorflow/c/experimental/filesystem/modular_filesystem_registration.h,sha256=ERfVGQeos7XWkWZCVtMBBuAWouasBFqp2MXG10m6Cpc,1414 +tensorflow/include/tensorflow/c/experimental/grappler/grappler.h,sha256=OncH-GC_Ov2Yka2Id_uYkcrrnNclNgmmK4gXCKdJ0Tc,12798 +tensorflow/include/tensorflow/c/experimental/next_pluggable_device/c_api.h,sha256=PHezG96j0Dj4Zo5gzhOKM0jlKkHo6hNPFFgUgF6TP4Q,7044 +tensorflow/include/tensorflow/c/experimental/next_pluggable_device/tensor_pjrt_buffer_util.h,sha256=4AZ9Hf9j3dIEjm-Gl7S7nLaOXYu7tbK9zIOWzSwbgWI,1507 +tensorflow/include/tensorflow/c/experimental/pluggable_profiler/pluggable_profiler.h,sha256=AOD7yu9cqpPrZvZ09lkRAG9EH-O7llmXEyCAONkaorg,7557 +tensorflow/include/tensorflow/c/experimental/stream_executor/stream_executor.h,sha256=85ZWHGh9QCycWDLRp276nWXYN3fY7-gIQub9egBRXr0,22164 +tensorflow/include/tensorflow/c/experimental/stream_executor/stream_executor_internal.h,sha256=qDXPLhfbQ_qVA_tEYpsphMCrfEq9pJDNeWnYvg0ETHU,6238 +tensorflow/include/tensorflow/c/kernels.h,sha256=NothbQNR2_LrTZF6tJuTHdfzUSYDytc-n8QfHqxS8XY,24483 +tensorflow/include/tensorflow/c/kernels/tensor_shape_utils.h,sha256=1IToOSPf3v6dhhTWjaXkvJ3jjUP7-kM08gyR0Rf_UEQ,1333 +tensorflow/include/tensorflow/c/kernels_experimental.h,sha256=xEvDAM374M4qleO0Q1HNJyQETV8ceKzGF_WvOKiZEQI,9656 +tensorflow/include/tensorflow/c/logging.h,sha256=Pzfkr9S7zZsf0J080mnZIR9sUx7vyhZ3rAFzlDIyQLo,1315 +tensorflow/include/tensorflow/c/ops.h,sha256=aMFgtBUDOQkoe4OZOpQn-Kyeq3vg0klvgk_4e9luqzo,16697 +tensorflow/include/tensorflow/c/safe_ptr.h,sha256=TRwM5rSxSVHkaoD6BXYbvhsvCFYUVDCH17wcvdRLF9k,2344 +tensorflow/include/tensorflow/c/tensor_interface.h,sha256=j1pF7Kb8XTxRneq5Vf8HD4xwLOAuIGL9EcZ5qpo7Et4,2507 +tensorflow/include/tensorflow/c/tf_attrtype.h,sha256=Ab9imlK1I8BwhkzhHTHTOqM_wutVlVL-uYb8kPUS7w4,1186 +tensorflow/include/tensorflow/c/tf_buffer.h,sha256=AH8oBnf8Fv5JoVOx5Bxs2eNH6kWlmi-IuFlGu9m9fVY,2043 +tensorflow/include/tensorflow/c/tf_buffer_internal.h,sha256=k_bgZHfUWiZZgGWi_K-_eWPEwA4x29iOBYVNTxEk3RM,1465 +tensorflow/include/tensorflow/c/tf_datatype.h,sha256=JwDDjTNV83ad8jjkflQTrxk8MbYikf0nQ4YSxzuZLvU,2579 +tensorflow/include/tensorflow/c/tf_file_statistics.h,sha256=rMNLMyQ9o3l-UaFfLq4x8vkdsjNHtDZlYi9b2dA7pBU,1231 +tensorflow/include/tensorflow/c/tf_status.h,sha256=mL395HIm5H17leIO5mMCVH5VJ1aZdIkfFpxMATFHH34,3893 +tensorflow/include/tensorflow/c/tf_status_helper.h,sha256=nQcSl4SFZ3v_KBM5KCbWzbmaZWXwHyQxBZZslPFcD9E,2895 +tensorflow/include/tensorflow/c/tf_status_internal.h,sha256=bB2m2VsC_VNoJNujaobklYc5-a6hobHyEYtF-bDtP4c,881 +tensorflow/include/tensorflow/c/tf_tensor.h,sha256=OKYWC3TYS-8jgTw5AM9MadviN6YhLLT0V28XZbUDAZg,6110 +tensorflow/include/tensorflow/c/tf_tensor_helper.h,sha256=hGPznNdwxkvxV4JzQ0CuOeYqWpuRLWH5g0b4QytM8ds,1462 +tensorflow/include/tensorflow/c/tf_tensor_internal.h,sha256=7omDMMx_7bcdyJ5i5QpkByB1y1af6P1b-0zfSiVCTME,4729 +tensorflow/include/tensorflow/c/tf_tstring.h,sha256=2hf2xq5ucX7Koplrv6kTiZ62bS3qtzHOpfatFPiW1wY,1703 +tensorflow/include/tensorflow/cc/client/client_session.h,sha256=g84eRmOGGJwyObA34PfXMYovoARKxtfddUSpNb_4hU8,6204 +tensorflow/include/tensorflow/cc/framework/grad_op_registry.h,sha256=D_s5XiLcZZ1DhHs4VGcOxv-B8zpjzJ97o8qFD9I3WfY,2921 +tensorflow/include/tensorflow/cc/framework/gradients.h,sha256=Ca4F6Wm3hA6GqnqBxxkSfVUfH37W3p7BKZDnW2y9WR0,2337 +tensorflow/include/tensorflow/cc/framework/ops.h,sha256=Qo6AXoJaPnvjrUMslS_O8GWMXsCP-Zck8g-fxgFm-Tw,10792 +tensorflow/include/tensorflow/cc/framework/scope.h,sha256=gGBQ_hTrX8HXyH1UevNFbdmaiI-Jv93JaziB_fG0eAw,10783 +tensorflow/include/tensorflow/cc/framework/scope_internal.h,sha256=AyI7ICtgQmRBNiH5CUnvKvqNJLViyR0pyrm8mSFh2mk,5186 +tensorflow/include/tensorflow/cc/framework/while_gradients.h,sha256=M26VDl5egp5ziS-KJ7o7WqAjZDmagPYx4JYC6mxcgrg,1775 +tensorflow/include/tensorflow/cc/gradients/grad_helper.h,sha256=OWLpyL4LuoNpEjV53SBX0RVCiPtFU5wAai641ntqrjg,1405 +tensorflow/include/tensorflow/cc/ops/array_ops.h,sha256=LLxZs8HcZdPav9kK8wLPfeXFjYzxrJKUGv99NYXzTcc,255771 +tensorflow/include/tensorflow/cc/ops/array_ops_internal.h,sha256=2iFup79u0HBVq_toU9EMvF3lkNf3VAnfnjpzX_KhnDs,8109 +tensorflow/include/tensorflow/cc/ops/audio_ops.h,sha256=1QbbTmUMqAZ2yXev04rTB_W3C0RICYz8pEQS4Jrog0Q,10606 +tensorflow/include/tensorflow/cc/ops/audio_ops_internal.h,sha256=osmTWrxJTTGGHjh4pkNI5mcGEmurwuVREJJk9CuDArA,822 +tensorflow/include/tensorflow/cc/ops/candidate_sampling_ops.h,sha256=UCPuvBlBk9TNEvasJOg3aVlzVnjtj_eB3r5aDkPou6Q,26067 +tensorflow/include/tensorflow/cc/ops/candidate_sampling_ops_internal.h,sha256=FRuUJlbn8NusQNK2I82JnSKpKk4xqLqaatK0bs7u1rk,887 +tensorflow/include/tensorflow/cc/ops/const_op.h,sha256=TgDC-zRLEYuImvJvVmmVVc7_aquZu0VzsUiyn0R22sQ,2916 +tensorflow/include/tensorflow/cc/ops/control_flow_ops.h,sha256=pDPJX1I704hUzny3poHyMaueUClYKSfvYbt4wPsTxFY,7407 +tensorflow/include/tensorflow/cc/ops/control_flow_ops_internal.h,sha256=I8wFzqOcnHiIExbKEa6A-ikch3O80NZcEIBThZRyGL4,7066 +tensorflow/include/tensorflow/cc/ops/data_flow_ops.h,sha256=JCUIEjnYV5quYmk4UVdWs3_kEzXZfslDn9tdqK54h3Q,121359 +tensorflow/include/tensorflow/cc/ops/data_flow_ops_internal.h,sha256=wpwZU3uHMXMbPSJp8Y6LLZKOnbkOcKx3T-4jLjDjkxo,7225 +tensorflow/include/tensorflow/cc/ops/dataset_ops.h,sha256=6j8SDBNdOjec47qMkrvR2l8g_NSmnZKm0L51ar7fvbQ,12121 +tensorflow/include/tensorflow/cc/ops/dataset_ops_internal.h,sha256=ow-6p7zdoteJRy6jM7q6EI_y86zPGLpYiek034swV1o,126755 +tensorflow/include/tensorflow/cc/ops/experimental_dataset_ops.h,sha256=e2KSEwDGd9zfA0hKM3LPUtR7bf24UfMRKfItA5gxs3o,709 +tensorflow/include/tensorflow/cc/ops/experimental_dataset_ops_internal.h,sha256=dvlU66O7XwOKKeevjIPMD6CQxFi0O-orSbuASg0I_AU,162515 +tensorflow/include/tensorflow/cc/ops/functional_ops.h,sha256=5ELJF9An85WFxD5-XCyKXf7zHE8-Usb_O0543P3utB0,16388 +tensorflow/include/tensorflow/cc/ops/image_ops.h,sha256=uwjY35VmohNtVTln00xQT6gJiX1e61kbfwfKk1P4Kbw,110381 +tensorflow/include/tensorflow/cc/ops/image_ops_internal.h,sha256=EPoOd1t837vb6JQkrcLXMj42LXEPoPufzNXxGm0uqaI,22319 +tensorflow/include/tensorflow/cc/ops/io_ops.h,sha256=Ew3O_5EGO05ViaqXEqTwyV3-VnXy3hnenNS8pMfKikU,34518 +tensorflow/include/tensorflow/cc/ops/io_ops_internal.h,sha256=0kQSbinOfZXGdJ6n6CHJxTbIcTv0G37I0_7o3R2tQqo,807 +tensorflow/include/tensorflow/cc/ops/linalg_ops.h,sha256=uPt0TqQEH7BKEEQuIJWJbSZ-AXk8-xFEwRcTNM1Oojg,32408 +tensorflow/include/tensorflow/cc/ops/linalg_ops_internal.h,sha256=piqmdOZiB5wVXwRKndkDkOX2EF4_Fh3fAeVoMtGV2EE,7325 +tensorflow/include/tensorflow/cc/ops/list_ops.h,sha256=9-MjMN0iPF7xpq99ceDMW3fdailnbbIPSzxT1GbJDrU,18634 +tensorflow/include/tensorflow/cc/ops/list_ops_internal.h,sha256=4xrRRKAkjeqCOIkt80nZ6Tmh6SksDk1KNXh1DEKmtAw,817 +tensorflow/include/tensorflow/cc/ops/logging_ops.h,sha256=pLB5vZns2OajXPd2LXBGIEIDFJt_EQHFFK4zgt-fBz4,17635 +tensorflow/include/tensorflow/cc/ops/logging_ops_internal.h,sha256=tubmRpO0iVu5WpMvpf5EgD2bQvxqxHdJI3ChFXbt1Pw,832 +tensorflow/include/tensorflow/cc/ops/lookup_ops.h,sha256=oKdWbv15pEOQCAjjJo9BAFeayCjd-AZfQ-fNDcs1FVg,20025 +tensorflow/include/tensorflow/cc/ops/lookup_ops_internal.h,sha256=FP_3oZamcfyNI5Q73Ti0LxUFXLcjv9Dl4P_yVGSPgIw,9591 +tensorflow/include/tensorflow/cc/ops/manip_ops.h,sha256=XaV8x2kn0Fgm0r9SBag5aiq_hJtDbJlhd0VbMCybm6c,2680 +tensorflow/include/tensorflow/cc/ops/manip_ops_internal.h,sha256=9YauRnogtIhLXzLEA7nTN6R1FJ5JAZKO_9pVGvO0vvU,822 +tensorflow/include/tensorflow/cc/ops/map_ops.h,sha256=VR-UnlTz3ZPIdMTDq45ZShK1GnSMMjRkHQu12M2DM0M,5254 +tensorflow/include/tensorflow/cc/ops/map_ops_internal.h,sha256=FHEONlamlipovGD4GkFLUIA9NaunopdcK1m6c1xeRJk,812 +tensorflow/include/tensorflow/cc/ops/math_ops.h,sha256=NE8ETFNh9JsJceuUtYgDizLs8TfPQb3IS5IfsLReF4Q,175727 +tensorflow/include/tensorflow/cc/ops/math_ops_internal.h,sha256=P9XQaELGNwPvXxhOdrfPM5Ouho4tCjDg81O_ghVCdkw,13299 +tensorflow/include/tensorflow/cc/ops/nn_ops.h,sha256=SeMV1mvtWcvIq-cvzWbseRy_J7fj0GFo_DZ9w2DUaZY,182273 +tensorflow/include/tensorflow/cc/ops/nn_ops_internal.h,sha256=eWLLhPbJ6tWEmY3f8CRX6Iw5A2w4oD1HOJ9l-ffGE7U,95670 +tensorflow/include/tensorflow/cc/ops/no_op.h,sha256=sbI5dhIul18sFi9SZsfyvafzZnZdrnHRURtWr8pHSlU,926 +tensorflow/include/tensorflow/cc/ops/no_op_internal.h,sha256=B0X-PugqVyQuq7NhbgyacHxhHYqY0quQ2S-m61pLk04,802 +tensorflow/include/tensorflow/cc/ops/parsing_ops.h,sha256=F2O0qIQ0aHAaYav8LpzDvWQ-qalgGQCXjrhj5Djuo10,55285 +tensorflow/include/tensorflow/cc/ops/parsing_ops_internal.h,sha256=iSbpWO4bfn4m-3Lx9b3-BNq8ODra1Bpuhr4eRo01hgI,832 +tensorflow/include/tensorflow/cc/ops/random_ops.h,sha256=x4InHddYrCxA4F9JsXITEsQaAeRdL4VaaQx7cSCHn_g,21553 +tensorflow/include/tensorflow/cc/ops/random_ops_internal.h,sha256=VyzGRXltGiqc26ne3XodbnSbSYb0HhRY2cEcautjRNg,1384 +tensorflow/include/tensorflow/cc/ops/resource_variable_ops.h,sha256=-t-jo0npjv6puDsO8gM0SSU1p15VJXwBdSff2AvTToc,15134 +tensorflow/include/tensorflow/cc/ops/sparse_ops.h,sha256=ocJww9CqY2BUcCN7bHbvMGWakeIyHQ_1NB8UtsWt9kY,69912 +tensorflow/include/tensorflow/cc/ops/sparse_ops_internal.h,sha256=fNg-XDeGT7DVJuSonMdsTtwzFfwUzP4MKu8x9_tshE8,827 +tensorflow/include/tensorflow/cc/ops/standard_ops.h,sha256=EfS2CLWl3G0Xs4q70mwzwJaLgTtEE0QDMmTwUlxvjnI,1644 +tensorflow/include/tensorflow/cc/ops/state_ops.h,sha256=3HkM7GgPaR6_ad8LrTcm_V9X-oWpIwYxPBZdW1XbI7A,53612 +tensorflow/include/tensorflow/cc/ops/state_ops_internal.h,sha256=uL4hjLoAvSOpFd4pHhsYqVg0kOTYpQ5Xf3RrlATMjEk,4576 +tensorflow/include/tensorflow/cc/ops/string_ops.h,sha256=NXig9eVlROqVf5ZO4TLv8NOhW2NbQfUPgT-u7GqnNUY,45718 +tensorflow/include/tensorflow/cc/ops/string_ops_internal.h,sha256=xF-69rgCv2FARa0bakoBBmKg17pyzEmjqvQLPTYlkvs,19016 +tensorflow/include/tensorflow/cc/ops/training_ops.h,sha256=Kgl1t2HGBRX2PCs-nVTsIzDLAkwvGSifLjo5-hfknTI,132211 +tensorflow/include/tensorflow/cc/ops/training_ops_internal.h,sha256=YbS06YOUXrZM5RaQZlR_ig10l1zK51GwDak4lik66ok,14792 +tensorflow/include/tensorflow/cc/ops/user_ops.h,sha256=uEMhilteCbyWWq72lmb0iMlpzIFmKEkx4c0VCaMVEHE,1050 +tensorflow/include/tensorflow/cc/ops/user_ops_internal.h,sha256=f5R0d90te6h7aRYwQUNgefrRSS9nFdhyIJl5AoQpIPw,817 +tensorflow/include/tensorflow/cc/ops/while_loop.h,sha256=k76M3n4WZrbOXvNrI4VgQF_GJekzE2ENagil1GzytEo,3465 +tensorflow/include/tensorflow/cc/saved_model/bundle_v2.h,sha256=xnm-nMzp02MVh1Lagy2QsyPR76foupZpmXFMUE_IU0I,3482 +tensorflow/include/tensorflow/cc/saved_model/constants.h,sha256=ni0FBQYF3iLz5C4d4Z9oCyj7JuYsNjlVE62ycfE3ET0,3218 +tensorflow/include/tensorflow/cc/saved_model/fingerprinting.h,sha256=jLZUZDM9Ifm88Df3294Aqev0uFI0Ga0qoylxuF_7m7I,1886 +tensorflow/include/tensorflow/cc/saved_model/loader.h,sha256=ihGhIzzaGl1Lfmi_TgNA8CYLZHDzpwC2UeAEffnMzxA,6172 +tensorflow/include/tensorflow/cc/saved_model/loader_util.h,sha256=GA0vQNp5zRsxCI2qc7YeYqF498U8CddOhbSdUy09vLQ,1495 +tensorflow/include/tensorflow/cc/saved_model/metrics.h,sha256=3gv-mtaYNMwXcU0_Qed7UwCq84swzIffCU8zvMxgjHs,6153 +tensorflow/include/tensorflow/cc/saved_model/reader.h,sha256=1KGbuTC5xdSHVwEB2W_bO9C6dHutwLaXLs1HysI4_nw,1986 +tensorflow/include/tensorflow/cc/saved_model/util.h,sha256=ykKU-RSU_G-sNpgN0kYqyg_11kYuoOt2KWxzTOuq8l8,2183 +tensorflow/include/tensorflow/cc/tools/freeze_saved_model.h,sha256=9r9dVnePxUWnVjVA8Sq2g_2HtUf5s8L6SC3YHwXlTHc,1903 +tensorflow/include/tensorflow/cc/training/coordinator.h,sha256=BCsN5TxQa2rrxnmXW52YevXIJtSVuh6WXhL_2jmFXRQ,4507 +tensorflow/include/tensorflow/cc/training/queue_runner.h,sha256=uIImPDeEAzGOTsi9AuEm4bckC6KFp7hzNxGI06fC0QA,5098 +tensorflow/include/tensorflow/compiler/jit/build_xla_ops_pass.h,sha256=q83J31uZn4oeM4mPhMGXsD9b_WqoTziOM-YNHYRquJI,1744 +tensorflow/include/tensorflow/compiler/jit/clone_constants_for_better_clustering.h,sha256=-CdW1xPPOTKhhZBjO0mzEyCJRwg1rgoyz7Q2G7n5nOQ,2597 +tensorflow/include/tensorflow/compiler/jit/cluster_scoping_pass.h,sha256=8UbXj2CoLrCe7QM7jO7Pe_rSAcDmJ-04LafGwaBU3-M,1553 +tensorflow/include/tensorflow/compiler/jit/compilability_check_util.h,sha256=_rY1fbU5lBPFYhGv_qRue1OhIBKqWnwpfI-OzxIdjkU,15277 +tensorflow/include/tensorflow/compiler/jit/deadness_analysis.h,sha256=PPtRgJ4Y-JhHrBSGyhngThlK_0_YwHVpcUWXPpTxRDQ,3387 +tensorflow/include/tensorflow/compiler/jit/deadness_analysis_internal.h,sha256=helWEIFrQW5Y9W1vzE7XQiliXyeWutH_yfLAOlr1lmk,1400 +tensorflow/include/tensorflow/compiler/jit/defs.h,sha256=TW6yYda2sqsHpzx9zGvVZap3DLljzJE4saZrDwk-Qvs,1790 +tensorflow/include/tensorflow/compiler/jit/device_compilation_cache.h,sha256=B9amydyUSFxtTjgbYfrm8PU6YBfkBOzxHh4I9TEjcO4,9012 +tensorflow/include/tensorflow/compiler/jit/device_compilation_cluster_signature.h,sha256=JcJx1H7JJfdQnEuAMH8KVzl9QU5T6G0RoVXEXcdsfPw,2135 +tensorflow/include/tensorflow/compiler/jit/device_compilation_profiler.h,sha256=bXdPdfEP-DUFxUagXRISHlZp6Vaj8Abkq4QlMzBAaww,3932 +tensorflow/include/tensorflow/compiler/jit/device_compiler.h,sha256=yV1dyfK9HzR3kK6JmMmsbu8KZma0UAz6ISVGGEz4T8s,22469 +tensorflow/include/tensorflow/compiler/jit/device_compiler_client.h,sha256=ZXCGPREwqZnsCa098gC-H2M3kkv9eL6U04mgJMUab2o,2827 +tensorflow/include/tensorflow/compiler/jit/device_executable_persistor.h,sha256=pxtCtAJHJDXt0de5_DxVRTiWdayQYbCSkYqinqqcCoc,17706 +tensorflow/include/tensorflow/compiler/jit/device_util.h,sha256=iYsdAnBZgQ4X4A38I_LHeYMMojErD8Z8QQn3q-ey5Is,7383 +tensorflow/include/tensorflow/compiler/jit/encapsulate_subgraphs_pass.h,sha256=T5tOXkaV8Bo5KcGu5QLhOjlr_DOXsloxH-FWBisdkw4,4996 +tensorflow/include/tensorflow/compiler/jit/encapsulate_util.h,sha256=jaokBxEvPuw5s_oUZGikgY_fCQHwpyaGk72-c0viTc0,7542 +tensorflow/include/tensorflow/compiler/jit/encapsulate_xla_computations_pass.h,sha256=gWue3uokB8t27AF3rZXODSdJWZX1HaueEbcarcW6mBA,3626 +tensorflow/include/tensorflow/compiler/jit/extract_outside_compilation_pass.h,sha256=V6uKNByjp47jq_rX6BpwWrQ5QaCEkukeabfHlZmORVw,5419 +tensorflow/include/tensorflow/compiler/jit/flags.h,sha256=a4MMnLkP7GSjTJTKlMOhfIdpH8BLpy-95hMysZ7oWu0,14650 +tensorflow/include/tensorflow/compiler/jit/force_xla_constants_on_host_pass.h,sha256=qJho8dQTeY7hcu-1DL_uwOhiqRDM5AkxGYhc69LHGdY,1415 +tensorflow/include/tensorflow/compiler/jit/increase_dynamism_for_auto_jit_pass.h,sha256=rbjlZ6wetdnlc_3_4bJhpZebR3lkePYC_aXxWe45wcg,2225 +tensorflow/include/tensorflow/compiler/jit/kernels/xla_ops.h,sha256=vT1AqxxQhzkLI67asTlJvXeBzgp9dPqCycNga4u5fFs,4891 +tensorflow/include/tensorflow/compiler/jit/mark_for_compilation_pass.h,sha256=Egh0Nu8stJ89WdSaf_bK30g7eelyFix2_PevTdJ8kaY,2354 +tensorflow/include/tensorflow/compiler/jit/mark_for_compilation_pass_test_helper.h,sha256=zxO5JNh4aT288N7laJb4Y2SfLxWgcjNI7ocA9omXjLE,2833 +tensorflow/include/tensorflow/compiler/jit/partially_decluster_pass.h,sha256=AGM4dY1oajmM75KTK1dZmwZ11fjmHyEKx9iJOq7tx9o,1333 +tensorflow/include/tensorflow/compiler/jit/pjrt_base_device.h,sha256=OdByUzXs6JLh-wK2IDlLKFlCZAE8LH3H8J9KjzqiPtM,4074 +tensorflow/include/tensorflow/compiler/jit/pjrt_compile_util.h,sha256=iE2ffSoAKhpYROZfMPgelJB5j_mu7xDX30fkioj8Kmw,2801 +tensorflow/include/tensorflow/compiler/jit/pjrt_device_compiler_client.h,sha256=wmtlj7DIOKe_a_gdB0w4TIWk_grENBVZ7jdBG6WzBLw,3151 +tensorflow/include/tensorflow/compiler/jit/pjrt_device_context.h,sha256=6jiob59I42tUQVLrzQl7dD9aDjYlaRV6nkUD8ReStHU,2806 +tensorflow/include/tensorflow/compiler/jit/pjrt_tensor_buffer.h,sha256=dY0wtIVgCQ846yItlqxKPuY7Uc7iY22wqrzBTFbz43I,2060 +tensorflow/include/tensorflow/compiler/jit/pjrt_tensor_buffer_util.h,sha256=n5IH40-YRUjS8yptJsZzrEj6RL6hD-pq755Gjkl5c_8,2341 +tensorflow/include/tensorflow/compiler/jit/report_clustering_info_pass.h,sha256=DYjoMDxgha0bxrVerjeIAVsknLjENrLV3lKfvGNSecI,1326 +tensorflow/include/tensorflow/compiler/jit/resource_operation_safety_analysis.h,sha256=vexJiM5AiwGZn7cPuEAn9P_eRpV1DHT1pKxbp2YhG7k,3252 +tensorflow/include/tensorflow/compiler/jit/shape_inference.h,sha256=VAitk1sgLzk4ixp9T8FBfefIGPhnx-iVb9CUZsbswjI,2098 +tensorflow/include/tensorflow/compiler/jit/shape_inference_helpers.h,sha256=GicmEwy_5obZwqhEOAygSOf3Hid1a_dmblYURFmlq1M,2259 +tensorflow/include/tensorflow/compiler/jit/tf_graph_to_hlo_compiler.h,sha256=7oU_hQjEpnLvqnZwDTlJIyJxNo3wgdyaKzQ9hl_GWmw,2212 +tensorflow/include/tensorflow/compiler/jit/tf_to_hlo_compiler.h,sha256=Eu1CqBK30eEeSqk8G4I-pSKdqqHRp50nC_qSTmintlg,1962 +tensorflow/include/tensorflow/compiler/jit/variable_info.h,sha256=vNApDEgUfYlOqvoZ3pNjx0GFQ1QLskGmc9OqM2btL1g,3373 +tensorflow/include/tensorflow/compiler/jit/variable_info_util.h,sha256=sYqEDRVu1nUNVtIhykpXkj83bHBhkKGuRgYxQ76802Q,4364 +tensorflow/include/tensorflow/compiler/jit/xla_activity.pb.h,sha256=N4hKEsPfIY_SmLudoin1_w_o69pah_1S7x059Ucmg6I,79657 +tensorflow/include/tensorflow/compiler/jit/xla_activity_listener.h,sha256=p8YTs-FEXOTtVRJ9QkMqEybXE-IbMuf01Y-LroJBIOs,2926 +tensorflow/include/tensorflow/compiler/jit/xla_cluster_util.h,sha256=LzwJYFr-YDIzOzBF1RVAsrMGY1YFNGZbLuhK8E-qQmg,4710 +tensorflow/include/tensorflow/compiler/jit/xla_compilation_cache.pb.h,sha256=6dtVb8emkIUvQmrBZHG1a32Dq6YYSP_FtuHMUbJAcqM,33698 +tensorflow/include/tensorflow/compiler/jit/xla_compile_on_demand_op.h,sha256=53Qsc-vOzeyIY4kQGJ1zTz8HHuVLXrgXXvXsFT8gpoA,3282 +tensorflow/include/tensorflow/compiler/jit/xla_compile_util.h,sha256=vnscZ2nJls0qeITNMIOlrJr5Xrs3GZ4Utv0DHBoLpsI,2460 +tensorflow/include/tensorflow/compiler/jit/xla_compiler_options_util.h,sha256=to72SW-QXWLevb1S4CDxWU-v5-0LPndOoFJEytPgVTs,2404 +tensorflow/include/tensorflow/compiler/jit/xla_device.h,sha256=wjjAY0HXBCPDUNnD8V-XD_fbuEnd0O2uVIjAZpy4MPw,13702 +tensorflow/include/tensorflow/compiler/jit/xla_device_compiler_client.h,sha256=jAzBkLSI8RpEhf4c8KwaaYCCjr0XwrNg5imry75cU5c,2456 +tensorflow/include/tensorflow/compiler/jit/xla_device_context.h,sha256=Jq23M7g1xtmTsphIr5NyMhPseuBhiwlmYiwhW6vavVE,5172 +tensorflow/include/tensorflow/compiler/jit/xla_device_ops.h,sha256=9bWDs5nRLpw2siSOt5FjBAuxJWgVg1bPIEUlbbXyWww,17470 +tensorflow/include/tensorflow/compiler/jit/xla_host_recv_device_context.h,sha256=TirxpaRvhq90FuX3KcKpkjFmUZs1HgsnyXTtO9PAoxA,3885 +tensorflow/include/tensorflow/compiler/jit/xla_host_send_device_context.h,sha256=lybHhLjnELYebikgBNsWo25Xkqg0bEqFlVs6JQudr7s,3718 +tensorflow/include/tensorflow/compiler/jit/xla_kernel_creator.h,sha256=g9aY23rYkA_GNmeF4AwWZOFmxdCHgcacCrHo5YNgzEs,1861 +tensorflow/include/tensorflow/compiler/jit/xla_launch_util.h,sha256=KhHAEmEo5UFEjdd5n9sN7D4fTaajRGWyP3kKimJqzVk,12007 +tensorflow/include/tensorflow/compiler/jit/xla_platform_info.h,sha256=4DWT2QJ6i99qSG4Tfy5agN9ueUs-lQoTrZImpHciUSE,6977 +tensorflow/include/tensorflow/compiler/jit/xla_tensor.h,sha256=OCC1ez6aYJR44Afmcc3ri7fREfTC7DBpxPEAsme8aFU,4808 +tensorflow/include/tensorflow/compiler/mlir/lite/quantization/ir/FakeQuantSupport.h,sha256=Uu6GdJA6sUlGbU13_lD0zlk0cqHPEK-qbmyi0dE94oc,3743 +tensorflow/include/tensorflow/compiler/mlir/lite/quantization/ir/Passes.h,sha256=4Z7r01iZ6i6VJ3MgNiBSwEKpfauSWLO1Fw5pHTUsk4E,2354 +tensorflow/include/tensorflow/compiler/mlir/lite/quantization/ir/Passes.h.inc,sha256=mNAt87vYO1fKaPT2lRUVCF1eQMepmvguMV1BbPju63M,10568 +tensorflow/include/tensorflow/compiler/mlir/lite/quantization/ir/QuantOps.h,sha256=KWLciboKu6uks_H84_We15jZs-oqgHySEq2iaacOB9k,1625 +tensorflow/include/tensorflow/compiler/mlir/lite/quantization/ir/QuantOps.h.inc,sha256=1nrTvdVw76aQ2g3iZhoxYx0DUbVmFa1Ec5Z-LEVgq10,67818 +tensorflow/include/tensorflow/compiler/mlir/lite/quantization/ir/QuantOpsDialect.h.inc,sha256=X6cQFdBcQa0w6gnHeElcHT8gBfZN2a7TZP08bngPlKw,1155 +tensorflow/include/tensorflow/compiler/mlir/lite/quantization/ir/QuantizeUtils.h,sha256=sq7FT2vDa5i8kNJieXRIRHY1kynWHKNy0P09tripmAY,3144 +tensorflow/include/tensorflow/compiler/mlir/lite/quantization/ir/UniformSupport.h,sha256=uWkzbw78s1iSfmaj18tW7XA15RHOdDE5jqrznbJ6RbA,9503 +tensorflow/include/tensorflow/compiler/mlir/lite/utils/validators.h,sha256=ildWL8P9MsMvh5a3z1saT82K0qCPe0H-IjGiXkhSUM4,4745 +tensorflow/include/tensorflow/compiler/mlir/mlir_graph_optimization_pass.h,sha256=lUwVaYTjxDIK3KrxX5wXPWJtm_V6V0Bof3cK_MuPCEk,8632 +tensorflow/include/tensorflow/compiler/mlir/op_or_arg_name_mapper.h,sha256=IaGVclFd1jFaJErFGTUYYCmFYvN-T9JquBghEpPgoVo,3837 +tensorflow/include/tensorflow/compiler/mlir/quantization/stablehlo/passes/bridge/passes.h,sha256=y0ktE8zf4DbI6n6z3JB9-eei0thpy6Ok62Wf5ornbT0,2690 +tensorflow/include/tensorflow/compiler/mlir/quantization/stablehlo/passes/bridge/passes.h.inc,sha256=mukoLKqG0q4IzhzioW42p3oN0nzB0AsTipDiVfJ3HRc,22303 +tensorflow/include/tensorflow/compiler/mlir/quantization/stablehlo/utils/math_utils.h,sha256=rSLuLPttkmuj-W_uCNOS-opHlJ2536e2NTTpkMOyCmo,1302 +tensorflow/include/tensorflow/compiler/mlir/quantization/stablehlo/utils/tf_type_utils.h,sha256=_LVsUPd1QuzbmUAAKBcfkp867aHPIs_hIFH7pLInBP8,1773 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/analysis/per_function_aggregate_analysis.h,sha256=zLsPPdFttPzlYVQXbhOnZgTkc-NjY8YPdSyIJovgmn4,2998 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/analysis/resource_alias_analysis.h,sha256=wtntLIOQCww4izJBQZWBU4SfL2pz17iUYz-RZXS3H2M,7229 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/analysis/resource_dataflow.h,sha256=cGicXW8Bk7fsfWpiA4Pg5iUIdIjDJW08e7fyxPM-kBA,3091 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/analysis/resource_value_typed_analyzer.h,sha256=gxZJd9azLRHaYM8M9We1mxCLgMYJgaRR4PoYRLEHk28,2851 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/analysis/side_effect_analysis.h,sha256=V38dUya07In4dTxZYTirvClyR6Sj7MFH6MTaVBsFiu8,9604 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/dialect_registration.h,sha256=wSfCzF1oRJKBEluqzeI9UO-K-6A0wWL5gQfZuy2pJl0,3087 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/ir/tf_all_ops.h.inc,sha256=yxkvVECae7KGPz-PpS8Jtt6ZOA3vb4MsrrVpGKO23_o,5936479 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/ir/tf_arith_ops_folder.h,sha256=093lPa2VmNkbMoWWchudj0gfqjYfS1Z0VGABrHVyCyQ,5409 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/ir/tf_attributes.h,sha256=dA5F6-XIKAcfoXTr1Zj7pmLsj97VXKYhzKH-TKrLipE,1374 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/ir/tf_device.h,sha256=DoAVUDmPIhFD-uyPBxP60m3NzKCHWKPAAS-i9gIi8VE,2277 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/ir/tf_device.h.inc,sha256=Q0nwSyi6Hlc2TbqoOVX5GoA18lnkTpkzsaPGjOH9fGc,61287 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/ir/tf_dialect.h,sha256=JYqL6iUe79xLpVpCPwbXhh0YN3dO3xAsqdTKUqu0xoA,4870 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/ir/tf_executor.h,sha256=ByWlBOY-Mv5svmb8-L1xbo_-5bIqLDDEW07_rRGQrmc,2738 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/ir/tf_executor.h.inc,sha256=CXV0ROGi289FL_nr6lNALuBI_6u3KQJHpHLe2gOD8as,74478 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/ir/tf_op_interfaces.h,sha256=dSI0glDlQdy-uyXjWBJiMYFIGqYUhVe1G5Rmw4IZbgA,6681 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/ir/tf_op_interfaces.h.inc,sha256=qmgjQ511CF3vcFLNN2RnUGkjNaMORdlViEajVgGsfOk,20865 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h,sha256=ZP9VC5YLs0F0GFy6FWcgx95FDVopEln7iAo_G2NIi-E,2696 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/ir/tf_ops_a_m.h,sha256=VNR8c7fLOQKhw7jCIJLg0OFxV3ria8FYWs5r9vMNNhw,3048 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/ir/tf_ops_a_m.h.inc,sha256=Gb2REbAa7CTXIuhcoscikvE_A122DcjFUsPnoHP11wo,2567535 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/ir/tf_ops_canonicalization_helper.h,sha256=3HW606QZE0wtm1w_tshp3uLwKu6l_TE2Uh2Y-n2L1bE,2447 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/ir/tf_ops_device_helper.h,sha256=Qy37Ay7q7Ou5fanw70clslNkAQYPyabXp_NMKmtcge4,1456 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/ir/tf_ops_layout_helper.h,sha256=LmCF-9lVkj8o1skIdfcreUWt90jOPSIe-uatsdrjmME,5413 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/ir/tf_ops_n_z.h,sha256=kKNzxIHeFJ-WRc0jBljJCNbuoAtRIFnCDcSE1BdjEag,2527 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/ir/tf_ops_n_z.h.inc,sha256=81SePbltKCQ0zXgV4-JbckaOa2ekJRSLdJSKS3US55I,3186993 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/ir/tf_ops_tensor_helper.h,sha256=Du_5rr7WSB2rTmoNAv9VWxXg-Fo6Qotrisf7TWQOdC0,3838 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/ir/tf_remaining_ops.h,sha256=oRbbFCDeZgX6EtHlU5RDA-k33589H5NiS9y5_WSOo2w,2329 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/ir/tf_remaining_ops.h.inc,sha256=J-x0fkvZpwS8bwWV8WvSIlC9he82HjWkUWrJsGHp8cw,183981 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/ir/tf_saved_model.h,sha256=kp8-FB10aPg5cqHXT1CmtsPGsFelH-eMktYwsuCqbeU,5107 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/ir/tf_saved_model.h.inc,sha256=2WFQTtaG3ixRf0jlRpFyT5nKeB05AkcnDsUh6yJTsdw,20194 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/ir/tf_side_effects.h,sha256=GUA4K9CnlytLuH2JkurPrLTYOcxLpTPRdRN9WmpkXLo,4783 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/ir/tf_structs.h,sha256=dLBXWlyBf7daCj0uVuqN6xz9XwpHugpp7zVEckp4g6c,2639 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/ir/tf_traits.h,sha256=AR0z38cblvbZfIhARTHM5L0qpYWJDg8F5vDri-kCkSs,12919 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/ir/tf_types.def,sha256=d_MHykXXdKMg1J3LH9DmaeLFKbpJWJRUVKOFIrNOQDQ,3429 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/ir/tf_types.h,sha256=fehIsDA6dyV4t5Xf_b9Bh0zsvCXlJUWcIuFs6JqQaBU,2377 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/ir/tf_verifiers.h,sha256=lK7I4CzgvF_OrNHZNT1m4k3jc_eTbTIcj4sRO_goVzI,1689 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/ir/tfrt_ops.h,sha256=DCfaS-Qunm0dj1GkiNR1gINmnFfgy84vvGiwYGbRaE4,1355 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/ir/tfrt_ops.h.inc,sha256=pLC7x6PER8tSvitDiBqrXe4RNxMZAZOw68j0fFuklx8,19460 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/ir/tpu_embedding_ops_registry.h,sha256=GAcAED41KlYd-wmg6aY_zgd5WMjd0tea3yHm0C2_CGk,2080 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/transforms/bridge.h,sha256=lPtPRKVX-5VyMvjXpPtztW90UybFe_aJRT1rO63x4xQ,2349 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/transforms/cluster_ops_by_policy.h,sha256=BhPuGxaMJ7EuU1pv38wPTmv-Fomp-15aRdCDrLaE6Xo,12358 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/transforms/collection_ops_util.h,sha256=4mfEsBT_7q8R-3Kc58yTO2Dd-0VpE3kRfhWFV4JouGk,4961 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/transforms/decompose_resource_ops.h,sha256=P1GkxwVAM7oYn2xplnIGja3v-2ZVZMkrf4F368_25Jo,1674 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/transforms/einsum.h,sha256=jy-9xdJZrbJDVpW2Hv4rT1kGwZzVEpsM0Zmvt_27DYo,2199 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/transforms/initialize_variables_in_session_init.h,sha256=-2ginLJxM52v7hTXHB5lL_UefrXfh1jlCtIOjGyx-Ec,1420 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/transforms/lift_variables.h,sha256=BOc0a-8vgklgfUP-IvQSa32IoCyKE7nL7e9XBuOYyD4,1431 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/transforms/lower_tf.h,sha256=kJggOjsByL5IAeaVXwjzOt7vTuiyFSHVktCukiD4StQ,2504 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/transforms/mark_initialized_variables.h,sha256=ohxX9N6RiK9zW8BU31x3H8v2nQgQBBv55eiYiZmlLOM,1957 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/transforms/passes.h,sha256=Ac-F89hQ42dwC8vzIkZUBz-vFrqQ5R0-DxSAXWn469w,35119 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/transforms/resource_op_lifting_cleanup.h,sha256=25Wiq9KBSsvrL8hgz9ufLacuqqMI9FS9nYF0FtOAYzA,2368 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/transforms/rewrite_util.h,sha256=5fIoa2dpSJcWKInqT7_edvo6njkYEivIxBi3ajsqILI,3504 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/transforms/set_tpu_infeed_layout.h,sha256=vpFklMbP4yLXzwVx1QleE4jfXMapqQ1IQFUwfmQwQ1o,1422 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/transforms/shape_inference.h,sha256=bPxtS2_oEGVZQJmaxLmJu3kOXC9ndYjHzR_SOnoTkQc,2315 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/transforms/tf_data_optimization.h,sha256=XDEtU-EUoNpz7UQsjPoEWdJCqkQBCH8hEzg4JsYDlAA,1311 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/transforms/tf_device_passes.h.inc,sha256=w5H5xsUN5ZJ677NLw324QbsiqO1Xp40kr6B6SNIwKec,79584 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/transforms/tf_passes.h.inc,sha256=TTID4WLmvB3cHQwI-yHD9AcyAYHkpd6VBVyZ4ERNHPs,556460 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/transforms/tf_saved_model_asset_sinking_pass.h,sha256=1qGgGfwiTjUk4aRQ4rRllTMLqsCqxWfUVyfSVrCvhew,1392 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/transforms/tf_saved_model_passes.h,sha256=uzXiF3n0BIJI3iOfDzAX3QSD0VeW6zV2o9UXbx3N4v4,3851 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/transforms/tf_savedmodel_passes.h.inc,sha256=NcRCJBXLFR_STfxsMfHc-ejzBCgg5mj5dUjQr2py4tM,58445 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/transforms/unroll_batch_matmul.h,sha256=XRS6B0ALyiSGIqvRFwC4epPNvOV2FXybceDuAiat0R0,1700 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/translate/export_graphdef.h,sha256=YDZFDLrNclKpjwwkgeLyMOmlShvbBjCp85Ze_jaTQD8,2980 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/translate/export_tf_dialect_op.h,sha256=OfKS67GX8qwuu0CI6tFON-mc1qwgWJMl6JI5IMSo488,2412 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/translate/import_model.h,sha256=WvXg_-0aszG7uqiTShEgJEOId9r6JCf8nbTCtsqG7pc,7054 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/translate/mlir_import_options.h,sha256=aSt4Z-7SBUeU7ds3Mh3hu3Wm69RySfENTWX3f5c22SI,2543 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/translate/mlir_roundtrip_flags.h,sha256=shK8km9ijPBSXNA1PybEY2gg3wwD7ObIotVvJ6VvJHE,6881 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/translate/split_into_island_per_op_pass.h,sha256=J0vpGxK4KnzsDCEKWw1jxpFp-CaA0M8ugRkXl0PCF98,1263 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/translate/upgrade_graph.h,sha256=mbEfN74yTIgCLQBFbqz9dkGfUtVVRiHxPvoergfouTo,1607 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/utils/attribute_utils.h,sha256=pmZJmwifYHNxRSG8-FauLg0WbhQnEeMg1OMymUAFaSo,7788 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/utils/bridge_logger.h,sha256=VqjeNEyGaOFGhQ-nlSaPub8d6J43pb0PYs44dSE__4k,4972 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/utils/call_graph_util.h,sha256=SkA0wylIVf38NMI2kLPliCGqouv-G5SqgKbn9AemA9I,4260 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/utils/cluster_util.h,sha256=TUhbch9lFeSXChHZhWfPIhX_CPt8cNrKTVv63MjpuxU,2738 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/utils/convert_attr.h,sha256=OxU5WXr1yIyWUDQjMSVA9IJp3bNQadZD6tsDtUYscWE,1704 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/utils/convert_tensor.h,sha256=yhbswB0GfTbGCWffV4dszCxRf7NG7TdsJ0X0vKxzN68,2986 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/utils/convert_type.h,sha256=bPufbfuH5lXvCVET3qLUMgKt4tlq7pteuc1YlEl21JQ,2363 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/utils/data_dumper_logger_config.h,sha256=eqDhR2PYHXRBTMdCAYfP_GnUvspKyKATg_N9bDSGkBs,2197 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/utils/device_util.h,sha256=w12n8IRpwqk-aObcTAXCk4M1CUja2eVsWMSnyGAWdu0,2399 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/utils/dump_graph.h,sha256=57Sbwv8a1j32Hgv65zEoPCtjBphU-UPFBSgnQReNZRY,2639 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/utils/dump_mlir_util.h,sha256=JaflQXcyLj2Zi9iYVCJA60eSDq39ml-UzPSaJc2aCnA,4881 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/utils/dynamic_shape_utils.h,sha256=-gmxqitwFjZLPjhpQnQdPtgccLUTHvemCbHiOan-tqY,1444 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/utils/error_util.h,sha256=6-ZxpUtAkg98VDlo7H8Uqy3e_QsHFkEIuG-uSWAjAho,3014 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/utils/export_utils.h,sha256=Tt8Vwk59Y8Tn1adKS_er8rNMNJWhLJDk-fqCcS7BG2E,3946 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/utils/location_utils.h,sha256=d6RNjGBdpV78apk3Ti7foY853B84zzetaj1Yhyiz_C0,1044 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/utils/mangling_util.h,sha256=9AnudSzuCDvOC2Yyc-NtBnaoaH0-0Tyco-odVw_APrA,2492 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/utils/parallel_execute_util.h,sha256=P1td8you_GSt6ufqS0zORUPn03EcHfoCTIeyU3o1S4c,1764 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/utils/parse_text_proto.h,sha256=mnZwwYLNP0ip4R3Om6PVSreuKKOuu-oR5F-qaZNwiLE,1876 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/utils/serialize_mlir_module_utils.h,sha256=5qTgCma5LTvK2NYkSR8YSKyu3qL93VZh5ROBr9pJLAE,1677 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/utils/session_utils.h,sha256=KKKWouqPdrw3eYlAyGiLGGHDgSOYqVq52y947gFw1Z8,2100 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/utils/shape_inference_utils.h,sha256=woSNQ3xbIlTKmvkqEH7wdXL_1lrz1WV67wC3xkq2MAg,1956 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/utils/stablehlo_custom_call.h,sha256=IqQq8PHbbuHjoQJAA2ojXCdGQQ3hMPYb_bKMeyGeOyQ,1493 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/utils/string_util.h,sha256=BwpxqZbJMsdyLBJ3J7U_WKIKC4lzTIT63ZnV_jyJAlI,2219 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/utils/topological_sort.h,sha256=pvSAu12qED1z4Gja1R1L7zZPRVX4sSMp2X8E5YouUpQ,3324 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/utils/tpu_cluster_util.h,sha256=TE5f70-LJwpnesrnPjOFUew9c3q2WvExnM5OpF1ZcCs,2145 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/utils/tpu_rewrite_device_util.h,sha256=HoLQ8QSdgqh-A797zE4lUcDVbWbQEOZLZ1aepoEBYP0,11526 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/utils/translate_utils.h,sha256=I03rW2zngSTSzwvUh-yDlbzPR6CB6zo9xORW8mjL3Ko,1976 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/utils/verification_utils.h,sha256=k-NqToyYbFfB5DynVbhPeeD5lYPG_iTSXMyYBDm5yb0,1156 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/utils/verify_suitable_for_graph_export.h,sha256=rQR2FzejzG6lEAk7HVeD8yQoOMjdTVGMY9ngzEfIfvg,1383 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/utils/visitor.h,sha256=fEIBoLZJk7J10XYB3jTOkcMLRRRu2d0eG6HFudDCjGw,2219 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/utils/xla_call_module_attrs.h,sha256=hEVcQm7wbZzQ20-3fJu_9_bQOwW-o1mKLCGZvXY4s_4,1785 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/utils/xla_rewrite_util.h,sha256=oNx4fHcvxjEJkhDBG14kB-TW7MFTTN3Ucs59BtfULfM,2801 +tensorflow/include/tensorflow/compiler/mlir/tensorflow/utils/xla_sharding_util.h,sha256=sUP3F2pep77ea43b0uUY7eGxy9gpV4pDPQ8VGVFpCaY,5938 +tensorflow/include/tensorflow/compiler/mlir/tf2xla/api/v1/cluster_tf.h,sha256=COHEaEVOSWHV7k6qSgHU0SB-wz2KTOkR7fzRJtnhL6o,1867 +tensorflow/include/tensorflow/compiler/mlir/tf2xla/api/v1/compile_mlir_util.h,sha256=jAPEpmIthjbvYXbfXXJUyWEivn1YsA2aTWv7b7Sq4Uc,10512 +tensorflow/include/tensorflow/compiler/mlir/tf2xla/api/v1/tf_dialect_to_executor.h,sha256=0pW2KbokZNpov9r2FikgvcXZuioTk7HS67fle1IYU58,2395 +tensorflow/include/tensorflow/compiler/mlir/tf2xla/api/v2/tf_dialect_to_executor.h,sha256=O0IedDnl3R9wagdGNLv5cXCe0Ok_pWlxm_roYMu0Yco,2238 +tensorflow/include/tensorflow/compiler/mlir/tf2xla/internal/clustering_bridge_passes.h,sha256=mtqLcFBAzJs6KmWB87XAmbI6P86eT7BYnXfo1ttjREU,1326 +tensorflow/include/tensorflow/compiler/mlir/tf2xla/internal/inference/inference_passes.h,sha256=BaoZrLyU8x-0zcP_7SkAubrmk7ldh0zIVFYxnCHKoqs,1461 +tensorflow/include/tensorflow/compiler/mlir/tf2xla/internal/inference/inference_passes.h.inc,sha256=ewD0a3TmWcKOA31PeyL7W4txDQ9oo-9aE8QpFe6moEU,5459 +tensorflow/include/tensorflow/compiler/mlir/tf2xla/internal/logging_hooks.h,sha256=6kZ6Fx1WXr55Qb8eIR1lC_b3xdHZV9iL_g1czwGOKfI,1462 +tensorflow/include/tensorflow/compiler/mlir/tf2xla/internal/mlir_pass_instrumentation.h,sha256=DNgV_-74SKDjGOKSD0PGMtEuABgUvxWuJXUj1qE3cAo,1312 +tensorflow/include/tensorflow/compiler/mlir/tf2xla/mlir_bridge_rollout_policy.h,sha256=MZet1m_cDAqCVfw_czUK3AQbdHUHNwjFlRdP6n9pIL4,3612 +tensorflow/include/tensorflow/compiler/mlir/tf2xla/transforms/legalization_op_config.h,sha256=ZmxV1s5azlEjDMuzgzgWv4K51KNAVC7pYmMpusTJbgY,1925 +tensorflow/include/tensorflow/compiler/mlir/tf2xla/transforms/passes.h,sha256=h0YoxqEB2Hr9SfAlKKlp-_tuTfVOasZWQ1jcf-tQZ_I,5774 +tensorflow/include/tensorflow/compiler/mlir/tf2xla/transforms/tf2xla_rewriter.h,sha256=Sada7zoQQowNJg3GQWAlL4Sr7EWGR9C6sIcA8pk2QkU,5082 +tensorflow/include/tensorflow/compiler/mlir/tf2xla/transforms/tf_xla_passes.h.inc,sha256=jd1NDcK9cLI4-rXzkbxaAwI4jFYcHD44FD9ew4a5PPs,5911 +tensorflow/include/tensorflow/compiler/mlir/tf2xla/transforms/utils.h,sha256=sasALKaNTriCn12ekj0vnAW8JDh2anXprRkCEb2lp1Q,2399 +tensorflow/include/tensorflow/compiler/mlir/tf2xla/transforms/xla_legalize_targets.h,sha256=pQzyEL6RD5HeXLpm0xyEq_TLc50pR2yExFCWNVLfaio,1395 +tensorflow/include/tensorflow/compiler/mlir/tf2xla/transforms/xla_legalize_tf_passes.h.inc,sha256=XncUSkj8kSjIP2jUrr9F5hFoZXOhIbWmxI7Vt0V6aOQ,29215 +tensorflow/include/tensorflow/compiler/mlir/tfr/integration/graph_decompose_pass.h,sha256=QBqkjFbbdNxK1BAa6HoP5hvsf36GHhw7jmHuisCAgUQ,2317 +tensorflow/include/tensorflow/compiler/mlir/tfr/integration/node_expansion_pass.h,sha256=dFutE-FBD6sqiX7n3Z6bda_G__LQ0u4JgtUEEZDCxr8,1988 +tensorflow/include/tensorflow/compiler/mlir/tfr/integration/tfr_decompose_ctx.h,sha256=2epHvjtUmZbGIiThX60WLWNMmItJzcF6e41LC9145_g,3262 +tensorflow/include/tensorflow/compiler/mlir/tfr/ir/tfr_ops.h,sha256=8IRbDIK0eFknvtbzhfjmk-ZWTZSnUbsb9ZcmoyRFq08,2518 +tensorflow/include/tensorflow/compiler/mlir/tfr/ir/tfr_ops.h.inc,sha256=8S1c3lG0SmzYxoeaPY_p-kFWnytTIpNFO5qB46TiWrk,97597 +tensorflow/include/tensorflow/compiler/mlir/tfr/ir/tfr_types.h,sha256=chFiRN367_OcL_JHQpG_jYKKqL3M5ysiqrcixnIEQ8I,4084 +tensorflow/include/tensorflow/compiler/mlir/tfr/passes/passes.h,sha256=l3Lt71nxY1aabr6G5wvzcrPMAf__wgFT7EP9lDnogl0,2020 +tensorflow/include/tensorflow/compiler/mlir/tfr/utils/utils.h,sha256=H-tTEIU2ffxd_o6QID0aemX3JtPIzgjVtM1A54nvvcE,2676 +tensorflow/include/tensorflow/compiler/mlir/tools/kernel_gen/compile_cache_item.pb.h,sha256=EUZZ_OcydAuQSHVa0PqLiNJC41uk6UKsfMcfEU7wLP4,13976 +tensorflow/include/tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_framework_dialect.h.inc,sha256=YEeUQonJ8GmYhHzkI35222igEJfSlDtCht6SJf7b2UA,1599 +tensorflow/include/tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_framework_ops.h,sha256=3g43vls1eJhPmSol5hGw_OrCxvsdbn3fnWWo4krrm4s,2528 +tensorflow/include/tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_framework_ops.h.inc,sha256=BFLoBMf3QpWN80mWuO3v0AQlzJrVobPilCdiRx7NN_Q,80709 +tensorflow/include/tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_status.h.inc,sha256=A4K5QicPXFKMkjMo_BRuSB8zEtLpuX48toNDVi4AUyg,4032 +tensorflow/include/tensorflow/compiler/mlir/tools/kernel_gen/kernel_creator.h,sha256=0FK-ncj9Yp0JSZtvD-dnakK6523cMbF1OCSykcKuV2Q,2352 +tensorflow/include/tensorflow/compiler/mlir/tools/kernel_gen/tf_framework_c_interface.h,sha256=n4QmZ9v_oOW5UFRu2hSj0dFg1DNcyjjgJYzekN2HPSc,2028 +tensorflow/include/tensorflow/compiler/mlir/tools/kernel_gen/tf_gpu_runtime_wrappers.h,sha256=XUfYwIOuAkeRer1LKHcWIgVLchZZBVa1n7TX4EluDnI,3422 +tensorflow/include/tensorflow/compiler/mlir/tools/kernel_gen/tf_jit_cache.h,sha256=jwdumq0042b2mWEL2ipo5vhV6YE5oj-HGB1VSOTSSjc,1804 +tensorflow/include/tensorflow/compiler/mlir/tools/kernel_gen/transforms/kernel_gen_passes.h.inc,sha256=KU4hVdMQVM2iwo2eCRgxcGkNMqevg5QrIghfkutjAFM,70809 +tensorflow/include/tensorflow/compiler/mlir/tools/kernel_gen/transforms/passes.h,sha256=c880-Otky_dAToQ0hgGbwupoebOwrYYBekovszxmBnw,4978 +tensorflow/include/tensorflow/compiler/mlir/tools/kernel_gen/transforms/rewriters.h,sha256=m_Qek2UbeNgeTXU6cap3_BcKuNRCdpPxwh_U9IdXUqo,2177 +tensorflow/include/tensorflow/compiler/mlir/tools/kernel_gen/transforms/utils.h,sha256=rcDjT_4Htthwi9vvpsHx20TZJwQJD7XSisyQyBf6WPU,1746 +tensorflow/include/tensorflow/compiler/mlir/utils/array_container_utils.h,sha256=0zDbWpY0hp0_qHrpWArmJIFOMbt0Ywl2lGoZSY2f1VM,1563 +tensorflow/include/tensorflow/compiler/mlir/utils/name_utils.h,sha256=3z3aGa7bRPXSGVb6ZA6BFk-HvaE_CtTus-SnyZaLWJA,1190 +tensorflow/include/tensorflow/compiler/mlir/utils/string_container_utils.h,sha256=gZ1kpf0DrV6z5Gco4qKPUD8zgcIbtD-2cP7ckb_bnNc,1219 +tensorflow/include/tensorflow/compiler/tf2tensorrt/common/datavec.h,sha256=BjQVJL1hW0TjHiAnDXS71jAB-TuMVCphzC00cbeyoHA,1233 +tensorflow/include/tensorflow/compiler/tf2tensorrt/common/utils.h,sha256=IAF4B8bTMXT-nhWJHmk4IcnNRFZVec6st2rUF0SkorA,6947 +tensorflow/include/tensorflow/compiler/tf2tensorrt/convert/algorithm_selector.h,sha256=YMGkHVPCf8hcA-tg7UjzjWbf0sTOM83ZbN4j9tYM7Qo,4793 +tensorflow/include/tensorflow/compiler/tf2tensorrt/convert/convert_graph.h,sha256=8oUlS5G63Vx2kf8VwIZ_bdO5dVk20nV2EUrRspFpQDQ,3087 +tensorflow/include/tensorflow/compiler/tf2tensorrt/convert/convert_nodes.h,sha256=sBy1ErtX4jnHt6jIvFI94VX38NJfgbRgbaK9QAVRYuQ,25696 +tensorflow/include/tensorflow/compiler/tf2tensorrt/convert/logger_registry.h,sha256=tJZS5FwDvxdFdywMka4WXIhZ-MeLLDXebFO--4DWs9o,2161 +tensorflow/include/tensorflow/compiler/tf2tensorrt/convert/op_converter.h,sha256=sqrv1wWfjwMgNN3hEPaALTsrPxv0tMwjdZlATKBHSPk,8292 +tensorflow/include/tensorflow/compiler/tf2tensorrt/convert/op_converter_registry.h,sha256=IPM3sWKm_TYpuekW6PuSNNy9gE9kdF5J17PsAgbm2DA,3541 +tensorflow/include/tensorflow/compiler/tf2tensorrt/convert/ops/layer_utils.h,sha256=2xkWaBqAXQEn8Z0ToR-Nb7Z0wuCoUKIpMfoLxd1LZks,28323 +tensorflow/include/tensorflow/compiler/tf2tensorrt/convert/ops/quantization_ops.h,sha256=05NB7BLg-iN7Dbzq1-XKYmXMK8TZCGWVOra29602vbQ,2792 +tensorflow/include/tensorflow/compiler/tf2tensorrt/convert/ops/slice_ops.h,sha256=II0BxWp3jHcysv1H_iJEC9rXabpy-I-7SLsFWVN5SH8,3579 +tensorflow/include/tensorflow/compiler/tf2tensorrt/convert/timing_cache.h,sha256=L08gf_ixek3OjbKv7-V0PuBJ3DXd22KUtiuXKS4yjyI,2575 +tensorflow/include/tensorflow/compiler/tf2tensorrt/convert/trt_optimization_pass.h,sha256=BL043Pfx0Yfu-9bFlbIwIRFMJHV1IYAtnpafAFbL8AA,2998 +tensorflow/include/tensorflow/compiler/tf2tensorrt/convert/trt_parameters.h,sha256=IYARH5DF0gJGSsVozRAfdqkfoN0ZIrF-rbb8L2b8aAM,3035 +tensorflow/include/tensorflow/compiler/tf2tensorrt/convert/utils.h,sha256=kH6xm9mX5JD3GyotugDm5znYRqLZtCLTHp8L_vmCjIU,14981 +tensorflow/include/tensorflow/compiler/tf2tensorrt/convert/weights.h,sha256=oqhsFlgbto3DIHHp06vbaO-aoQUzdrWPUo1qfcZmnNs,10667 +tensorflow/include/tensorflow/compiler/tf2tensorrt/plugin/trt_plugin.h,sha256=2fYGjei89Xm-bXhSdFB81Gfw-XIwn3L13whh03H4BOk,2661 +tensorflow/include/tensorflow/compiler/tf2tensorrt/segment/segment.h,sha256=BPA1i0WIjcLeBYWQbFMzcVVayxE7JNJzT8GP89KzzG8,3537 +tensorflow/include/tensorflow/compiler/tf2tensorrt/segment/union_find.h,sha256=siII23u0lMRSfalcxaQ57eH3vMny1rwYYJZJaoG84bY,8439 +tensorflow/include/tensorflow/compiler/tf2tensorrt/trt_convert_api.h,sha256=pwEHd5OdxvrTeuCBT4u1jmK8W_HPrzzbb5XAg9BsxpE,5411 +tensorflow/include/tensorflow/compiler/tf2tensorrt/utils/trt_allocator.h,sha256=4GTIG3MJEZ5OexMxLZs5dLvfI0gpc6gFq7ff6HmRKbs,2491 +tensorflow/include/tensorflow/compiler/tf2tensorrt/utils/trt_engine_instance.pb.h,sha256=WQH7liZodynr42CgIpven8rOipLVMdIZyrc3YBOPHyc,13877 +tensorflow/include/tensorflow/compiler/tf2tensorrt/utils/trt_engine_utils.h,sha256=ZE6rexwbBSOpnBpMeYxar6i1qyICh6y2KT-SbzGBfQc,3705 +tensorflow/include/tensorflow/compiler/tf2tensorrt/utils/trt_execution_context.h,sha256=oMB5KvYlFkYGQEmRKknJq4uUf09USKeW_2VN0W3Vu9E,1578 +tensorflow/include/tensorflow/compiler/tf2tensorrt/utils/trt_experimental_features.h,sha256=oMf5P4NBmOslg2MVndEqVqeysV9Hd-0QnIuYVugr-6s,1135 +tensorflow/include/tensorflow/compiler/tf2tensorrt/utils/trt_int8_calibrator.h,sha256=0i5EAfIX8uokbSfd7T1GfIbqO37A3e2OekFcpXr-mEg,3449 +tensorflow/include/tensorflow/compiler/tf2tensorrt/utils/trt_logger.h,sha256=LijpG8vKh-zsauVbtKt44DZsaJ1t6QfJzG2NKFbT7PA,1772 +tensorflow/include/tensorflow/compiler/tf2tensorrt/utils/trt_lru_cache.h,sha256=oEIcLoUISWF9RcYmiMeO6soJfPjZ2XI416M6HAdtkds,9604 +tensorflow/include/tensorflow/compiler/tf2tensorrt/utils/trt_shape_optimization_profiles.h,sha256=KINrx_5j-oolNzBcHceQ93GCJaHBR74WSpgS23DP3Fc,14842 +tensorflow/include/tensorflow/compiler/tf2tensorrt/utils/trt_tensor_proxy.h,sha256=u294E9A-ovy8rY6lwaoXgwFAZv97u0BQFnTH2rvUEEo,14161 +tensorflow/include/tensorflow/compiler/tf2xla/cc/ops/xla_jit_ops.h,sha256=xkYZymIXFIqUp3Fx5KAgeUNH9IW7hcZ_7pA_y3gXfV8,5070 +tensorflow/include/tensorflow/compiler/tf2xla/cc/ops/xla_ops.h,sha256=0TfgYs0mHcENKqzDWxcHax1pZYFyHH9T9JNemzFiFBA,54924 +tensorflow/include/tensorflow/compiler/tf2xla/const_analysis.h,sha256=REHjuP5cMkDPpCg38TjBAAFEE4R3Z6L9W_mvt7fNxv4,2161 +tensorflow/include/tensorflow/compiler/tf2xla/frontend_attributes_util.h,sha256=P83jkIXR4KH8GTTmIwVPqZYnuQ5bCigKOqaqgOoT9No,1376 +tensorflow/include/tensorflow/compiler/tf2xla/functionalize_cond.h,sha256=oIrUxoW1s9HproasN6TfMJFlleBzVOhlktG1m9EB_E8,10964 +tensorflow/include/tensorflow/compiler/tf2xla/functionalize_control_flow.h,sha256=apYLk3HbWfl_63lRRRJ0Q-kQpXYXH1cEzPXmrG0_wE8,3326 +tensorflow/include/tensorflow/compiler/tf2xla/functionalize_control_flow_util.h,sha256=QD1nEEEx3ZrF_M7gkhDYWL_yNtBlVQ1uB0oHfvRQD0s,4092 +tensorflow/include/tensorflow/compiler/tf2xla/functionalize_while.h,sha256=qdM8ObGhN_lO8VaBjpfb-aodSqHd9-XxAOr5aibIrEs,1625 +tensorflow/include/tensorflow/compiler/tf2xla/graph_compiler.h,sha256=IYvnIREbEmM7_hYTzEGIjt4KXEZQZCmOqfoIcJUD8e0,3870 +tensorflow/include/tensorflow/compiler/tf2xla/host_compute_metadata.pb.h,sha256=wFyzZ6iv5gFd-jj1oXi6TzYk__pi1xb8AaVfSS3LOEE,35550 +tensorflow/include/tensorflow/compiler/tf2xla/kernels/callback.pb.h,sha256=dTXAv3uE-J0q4IryxocW-SSp8-pDZBPlORUZqo9tXUE,62908 +tensorflow/include/tensorflow/compiler/tf2xla/kernels/case_op.h,sha256=Z2yMnc8X5YvrRGneWtSIkmtnVHZIg0nKWYQ7E2QPzmE,3068 +tensorflow/include/tensorflow/compiler/tf2xla/kernels/conv_op_helpers.h,sha256=TzGdsR_HSxDCKXulWuA6_R4SDuVBKf-2FkBdiCZVwjE,3682 +tensorflow/include/tensorflow/compiler/tf2xla/kernels/cwise_ops.h,sha256=mDT7DEHcJHBlPpiTGN747jVuGG8_FeNLrFKsqhA5wOQ,3394 +tensorflow/include/tensorflow/compiler/tf2xla/kernels/elu_op.h,sha256=earyGI_RxdXYO78E-F5uFPLxvLj14fvqf1v9VF3Ff0Q,985 +tensorflow/include/tensorflow/compiler/tf2xla/kernels/gather_op_helpers.h,sha256=J85NgHV6TSNZUOP7qKCVuI9ye-6Mcm6386XEtbWuim8,2362 +tensorflow/include/tensorflow/compiler/tf2xla/kernels/if_op.h,sha256=R0y6HMPXUwHEnj-9ZO3ZnMhpDiDHj7eBFPFGrnIpzYM,2424 +tensorflow/include/tensorflow/compiler/tf2xla/kernels/if_while_utils.h,sha256=NEB_Ha4O3AxCQ9RV-nNLd747J8MtWFbHJs_O8yxroQ8,2084 +tensorflow/include/tensorflow/compiler/tf2xla/kernels/image_resize_ops.h,sha256=mcPWVs0vxI17omy71X9OOjS34nzn6wawWdmcPkfqdbc,2193 +tensorflow/include/tensorflow/compiler/tf2xla/kernels/index_ops.h,sha256=dBMDu9mIyCT_NSvmNa3pcJzNjNu8SL5BWc4u2EtbvuE,1442 +tensorflow/include/tensorflow/compiler/tf2xla/kernels/light_outside_compilation.h,sha256=KjQ24gcIK1wn8w7DC08FbO_Z83Olk-1e3M9NVxEuXq4,2557 +tensorflow/include/tensorflow/compiler/tf2xla/kernels/random_ops_util.h,sha256=gE_4NNULVbR4p1CLoQJuZFLU-KKbOq_3uGeyPFyySpI,3870 +tensorflow/include/tensorflow/compiler/tf2xla/kernels/reduction_ops.h,sha256=D5UYRNerfK58yXsViLRsvcfvWD7TCF-ZA6KXVrAeJms,2979 +tensorflow/include/tensorflow/compiler/tf2xla/kernels/relu_op.h,sha256=qtswGgXW43g98MeOLwAb4dbYT9cBxS82nFm1CJfyJrg,990 +tensorflow/include/tensorflow/compiler/tf2xla/kernels/rng_converter_utils.h,sha256=zCCOYDfNCv_d6RYFCsAcBC_L_s0lUIRz_f5Xsx_2nIM,1289 +tensorflow/include/tensorflow/compiler/tf2xla/kernels/shape_util.h,sha256=r1hXyagGiy_WDizF7EEwfbxh7JgsAOLxshJKE38SuiY,1250 +tensorflow/include/tensorflow/compiler/tf2xla/kernels/tensor_list_utils.h,sha256=EdFFKIfn_3nPa0r5-KPn0Tdsim3bOnXO5XZ37LMNh6I,6045 +tensorflow/include/tensorflow/compiler/tf2xla/kernels/while_op.h,sha256=sCEihGP1tSK8ekAbMPmgaRzZaGyhpcSWAtdRiKIel4Q,2972 +tensorflow/include/tensorflow/compiler/tf2xla/kernels/xla_call_module_loader.h,sha256=-9KYfNqTEFGfICQiFiICQtSUJDfYNRVZR4qAOflR7qg,4776 +tensorflow/include/tensorflow/compiler/tf2xla/layout_util.h,sha256=J_g2QxOxK00uCZyoyR3D1pNeUm6ivIfyEXGzHDlBf0Y,3049 +tensorflow/include/tensorflow/compiler/tf2xla/lib/broadcast.h,sha256=4sU-oEg8KlcqSkl5U8_IcqOkK-_3gc8cGefU3UIEUA4,1312 +tensorflow/include/tensorflow/compiler/tf2xla/lib/data_format.h,sha256=qh9ghT_XbaC6Ut8dBmkPhBrzc7t8nAyKPfyOTHKhXvo,1361 +tensorflow/include/tensorflow/compiler/tf2xla/lib/random.h,sha256=bUsUCNWiPi-FNSnTyflUs7qZz8LFVw9fmDZlpiLw6Ls,1700 +tensorflow/include/tensorflow/compiler/tf2xla/lib/scatter.h,sha256=y5R4ptk5jqeEI2JXOSkET63wwndhppRgIrjjYYsKxqU,2251 +tensorflow/include/tensorflow/compiler/tf2xla/lib/util.h,sha256=ExRHRWe9i2BcnShywj2xOSM_-FqDrBN839rPXxXM8N0,1780 +tensorflow/include/tensorflow/compiler/tf2xla/literal_util.h,sha256=RsPTA31FrU_g_C-ssYcTlo0XKrqzhORZOT0IQppkRSE,3639 +tensorflow/include/tensorflow/compiler/tf2xla/mlir_bridge_pass.h,sha256=EknGe_6iBA0aCOyQ_DtF69mQpHbVdPnWu6qEYBoh7Ec,2815 +tensorflow/include/tensorflow/compiler/tf2xla/mlir_xla_op_kernel.h,sha256=HsVLpcCTwGgT_i3gRa0pi6K1cqqAZ-EjTjof1FsP1vU,1395 +tensorflow/include/tensorflow/compiler/tf2xla/rearrange_function_argument.h,sha256=cxPUk_ugcqZTOrWHDxpJVfyUdZ_M2_1dzKg85sqotlU,1800 +tensorflow/include/tensorflow/compiler/tf2xla/resource_operation_table.h,sha256=n7_sHyR6pgn8Kw-4mESQQp6-JbkZx0fBZaxL4yw770w,2542 +tensorflow/include/tensorflow/compiler/tf2xla/shape_util.h,sha256=oKWPJEkMlxTzR2WBRzgHnXjbjibDNjXlnYx_xxeVC0E,4044 +tensorflow/include/tensorflow/compiler/tf2xla/sharding_util.h,sha256=y6dTdUkVKu3mwabiK2HO71rHzYFmNTHBxnlTVaeqsiU,2373 +tensorflow/include/tensorflow/compiler/tf2xla/side_effect_util.h,sha256=P505hoZ3AExts5QzjSYFnqEjG3jx_WU79R0cssu_Mko,2861 +tensorflow/include/tensorflow/compiler/tf2xla/tf2xla.pb.h,sha256=qoJCbrQ4ytGG0UBnLqCuiAYRISDos0t1n62Y8lhJH_M,70274 +tensorflow/include/tensorflow/compiler/tf2xla/tf2xla_defs.h,sha256=l1oL7hmkALYoAqujt_1l1Jf79jZc9myROF80KCUtE3M,2729 +tensorflow/include/tensorflow/compiler/tf2xla/tf2xla_util.h,sha256=YOgnlMq83IdPDGokwe4VigC3S5yMYRIGFFqT7MoiEh8,9291 +tensorflow/include/tensorflow/compiler/tf2xla/type_util.h,sha256=fLUz-V5xZwoCk9Qn5i44CjgffE_UzaUmhQdMeYHUc3c,1802 +tensorflow/include/tensorflow/compiler/tf2xla/xla_argument.h,sha256=Ew6jXG3fls6Thx_mmGZmA3xdndb7Ymcgd-CSHtddvcM,4946 +tensorflow/include/tensorflow/compiler/tf2xla/xla_compilation_device.h,sha256=MXAyHl-G2e5TyQsw4FFlIt5c1___7eazAOvLbFDS9Kc,2613 +tensorflow/include/tensorflow/compiler/tf2xla/xla_compiled_cpu_function.h,sha256=tRTwjBBVqg84kudDQa2tncqkPSAFesQN3VbEWywhh1E,19331 +tensorflow/include/tensorflow/compiler/tf2xla/xla_compiler.h,sha256=TEcgfEB45SuDIwrX-gqd7FnGEf6sP_JabarnLzpCyHc,17794 +tensorflow/include/tensorflow/compiler/tf2xla/xla_context.h,sha256=r26mFFAcs6zP78NveRwxxYt0aU48ve4LjJzPEB-KGc0,7145 +tensorflow/include/tensorflow/compiler/tf2xla/xla_expression.h,sha256=3N_kik5zw2I4UsFZGOiqTCf2wCrUJXIKX5K6xLtL97Y,6392 +tensorflow/include/tensorflow/compiler/tf2xla/xla_helpers.h,sha256=pO5wlcos5bnOmFMERBTNAGiLFOqCFaHkfKBNTt7Gzu4,8200 +tensorflow/include/tensorflow/compiler/tf2xla/xla_op_kernel.h,sha256=Xr-Ni70UihVZ7xppgGkoqpzak8P7JXlSFdO0fqXWCaA,16442 +tensorflow/include/tensorflow/compiler/tf2xla/xla_op_registry.h,sha256=0_QxvYRpCRxpD8Sl1Ze1gbJO4XoP9DNFD_zmVTC1_3I,18043 +tensorflow/include/tensorflow/compiler/tf2xla/xla_resource.h,sha256=60MVeFrXpisBGe6aIj9XzWOal38gydvbg0L2eYrHHMw,7787 +tensorflow/include/tensorflow/compiler/xla/array.h,sha256=qcHnA5xl1YAaUAjzwspX9LVyPGXXmqn3yfEATpaV628,25361 +tensorflow/include/tensorflow/compiler/xla/array2d.h,sha256=dzqY4TmWVSggrokEVzZt5AA4XUgNZO3yk_5HhTE-YdA,3834 +tensorflow/include/tensorflow/compiler/xla/array3d.h,sha256=MnbF6xztyTUSMXqhDIJLIfaezqi-oCpEyraod39v4rw,2543 +tensorflow/include/tensorflow/compiler/xla/array4d.h,sha256=NfmOMlg03ATGKlTA5hGuU14B2MvQ0Py1LKFwzQXSi1Y,6330 +tensorflow/include/tensorflow/compiler/xla/autotune_results.pb.h,sha256=nDSgBVfocjpdIu2PyV8XFYeykb_lm7xsxBKUsfz6hP4,25139 +tensorflow/include/tensorflow/compiler/xla/autotuning.pb.h,sha256=5d9rZu5_GMr5rdVTGXQGQ9_4XZPh3orxEPpnZSwvRBo,142404 +tensorflow/include/tensorflow/compiler/xla/backends/profiler/cpu/host_tracer.h,sha256=3HzWIAOS-_NDm4DocacfRsMyxvslnBIJHGFDUIJ6lRw,1634 +tensorflow/include/tensorflow/compiler/xla/backends/profiler/cpu/metadata_utils.h,sha256=0jUSVjX1iYGkNfgNn1WqXI0DZt6y5jH9HmxtVpgqpSQ,2045 +tensorflow/include/tensorflow/compiler/xla/backends/profiler/gpu/cupti_collector.h,sha256=Bc417SHSHDZ8P5BuFaagp4VNzsr571zZdG_Q36BQ4_0,10385 +tensorflow/include/tensorflow/compiler/xla/backends/profiler/gpu/cupti_error_manager.h,sha256=d181DmKlb0qTt9IQrK91jrJ-iaXtPfkeE3jRDjU0dJM,11992 +tensorflow/include/tensorflow/compiler/xla/backends/profiler/gpu/cupti_interface.h,sha256=918nt6HCaBrTIzVb76QM-sfccRYCRQrmSpSX4yO3c1U,8876 +tensorflow/include/tensorflow/compiler/xla/backends/profiler/gpu/cupti_tracer.h,sha256=e-Ok5g6PbrZPkJjQ6rzP9qBLCjim-b1gnIVwg9Kk-hg,6066 +tensorflow/include/tensorflow/compiler/xla/backends/profiler/gpu/cupti_wrapper.h,sha256=uVQThYs6rvFw5sy-g6LQUKiYOoJ6gUPDqS0SxNEOC-4,7631 +tensorflow/include/tensorflow/compiler/xla/backends/profiler/gpu/nvtx_utils.h,sha256=8SwRd0tqnR_p_OGqcrsuameKbKSE4DPO1xJ2gdOI-h8,1927 +tensorflow/include/tensorflow/compiler/xla/c/c_api_decl.h,sha256=FdUA7v7HuslviFULI3g82Z-kIBpD5OysdxnIh3vSbM4,985 +tensorflow/include/tensorflow/compiler/xla/client/client.h,sha256=LNDhbpw0hIOMQcMJ6stB28s18gAhre_md0x_XTffRPM,11134 +tensorflow/include/tensorflow/compiler/xla/client/client_library.h,sha256=93_NDoBE0TSi_tnR-SH0ZKYTXfzGr2K7r1tQPxrmW7I,5527 +tensorflow/include/tensorflow/compiler/xla/client/compile_only_client.h,sha256=D76FWFkBsOXprlDZEOYCHXVn7qrc7MjmRBGIlg-rWNo,3016 +tensorflow/include/tensorflow/compiler/xla/client/executable_build_options.h,sha256=H4XArNJbwSQDSP6BBg9iUSXqLADb-tr0NLOPTK3REQ8,10785 +tensorflow/include/tensorflow/compiler/xla/client/global_data.h,sha256=KAwJHZV_M_mPe_quL_AJ0xTHpLDv66-cBVJo3YxoIpI,2055 +tensorflow/include/tensorflow/compiler/xla/client/lib/approx_topk.h,sha256=R2R4OG7R4KFyGFlnPG9IOgCu-AQIC1cs2RH03j-4zQI,3528 +tensorflow/include/tensorflow/compiler/xla/client/lib/approx_topk_shape.h,sha256=lwWm0WgHjKAVdUiGYc_krlI4baa4u_442rCOA5ibRKs,1957 +tensorflow/include/tensorflow/compiler/xla/client/lib/arithmetic.h,sha256=kHoV-FKceJSrc2DZbHXvrfmuSpgRooM9NVslYyO4iT4,3939 +tensorflow/include/tensorflow/compiler/xla/client/lib/broadcast.h,sha256=tI0n4F1zXeUAIngV3qlamfo__6qaKzA7FAlE6GaXeik,1183 +tensorflow/include/tensorflow/compiler/xla/client/lib/comparators.h,sha256=LhcUgZN5jT9YX2c0fuVo75rmI1mxGgUUPQQhY1k2dhs,2521 +tensorflow/include/tensorflow/compiler/xla/client/lib/constants.h,sha256=6qJ8_1VdcFBZlrOj3qx-ONyuZPoIvYFShQECa7XZvBQ,5429 +tensorflow/include/tensorflow/compiler/xla/client/lib/conv_grad_size_util.h,sha256=yhw1LoLhvWvoT59gf3_cf4p9otkGNuhW8mVWUnB9JLI,1700 +tensorflow/include/tensorflow/compiler/xla/client/lib/dynamic_shaped_ops.h,sha256=cqN5RmW2qWwxvjR-VdDDEnZxUSR6B_ldkw-f0ktrJMg,2476 +tensorflow/include/tensorflow/compiler/xla/client/lib/loops.h,sha256=B9-ah_M070OaQ0atLC9FPUNxitArfRaSkMXbk1lXzlk,2777 +tensorflow/include/tensorflow/compiler/xla/client/lib/math.h,sha256=zPyQ1uzpvT1KZE7zKxEXhmMChDuWe9m05VlcyNyeWwQ,3825 +tensorflow/include/tensorflow/compiler/xla/client/lib/matrix.h,sha256=_Dh0fU2zV0KOHL709efSHCWgmDPW7trpjImvuVvcPb0,6165 +tensorflow/include/tensorflow/compiler/xla/client/lib/pooling.h,sha256=6lnF0DjbLK7vP0tDzgSmGhaiFld3v10VVzVNwdbtmsU,3173 +tensorflow/include/tensorflow/compiler/xla/client/lib/prng.h,sha256=UbHlkkzWU051a8ZbcP76xs48-75sWQr25TCXTbv2k08,4571 +tensorflow/include/tensorflow/compiler/xla/client/lib/qr.h,sha256=ecte5jMg2zY2MfZLjzCnz6mN_yIt8aySb8wm3OkVlN4,2097 +tensorflow/include/tensorflow/compiler/xla/client/lib/quantize.h,sha256=gps2DrWmahi6eQ9xAo0Q5xnhE4Ca9iVCWJLOEdsrY88,7178 +tensorflow/include/tensorflow/compiler/xla/client/lib/self_adjoint_eig.h,sha256=flqpXRkLSlkHzis3yuRmbDovY-cSJGKo5Pj5e4QCMQE,1517 +tensorflow/include/tensorflow/compiler/xla/client/lib/slicing.h,sha256=uvfGqj5rYhOvsPyyYzAu5OJfDaXUNG45lpf4LFYQKNk,3879 +tensorflow/include/tensorflow/compiler/xla/client/lib/sorting.h,sha256=wN1prvo0MIxttjcKCGxAKitFyax_rKawp_FyEop9Bqk,1505 +tensorflow/include/tensorflow/compiler/xla/client/lib/svd.h,sha256=R4k_4xPCDJKSPS3Oiv8d-JqN1ahaVWwO4-UTI8aWIw8,1882 +tensorflow/include/tensorflow/compiler/xla/client/lib/tridiagonal.h,sha256=CE3_24GPKpTiauhVkHfjI8JHqTQzEBEh4fYZN79TNnc,1447 +tensorflow/include/tensorflow/compiler/xla/client/lib/tuple.h,sha256=SAp6qZsauNZg2AEy-Ue6LE7wzDkm-ICipTlcLogbsQs,1381 +tensorflow/include/tensorflow/compiler/xla/client/local_client.h,sha256=XzwyaS42L6NsESZ_yJRNNqMLh-SAN1feBX3sNxwlDUE,9742 +tensorflow/include/tensorflow/compiler/xla/client/padding.h,sha256=LeYaXcLjnVDhqbj8sNbH56LH4jkoV_nIMuHp-SqAfoQ,2601 +tensorflow/include/tensorflow/compiler/xla/client/sharding_builder.h,sha256=sYUmOpvSfvBjigVInO3zxG3qogjfy3KDdbLVCpdG96E,2215 +tensorflow/include/tensorflow/compiler/xla/client/value_inference.h,sha256=5RxcrNysXQB1x2yT8tuxEwnF-MuOMwabGiUeXv-PgDg,3984 +tensorflow/include/tensorflow/compiler/xla/client/xla_builder.h,sha256=mSWsikVqc8w0OI7pZmGG0GOqLbMFW5g_Y0_qAIkYfHo,138285 +tensorflow/include/tensorflow/compiler/xla/client/xla_computation.h,sha256=EWW85ZEEj_-G8zXFR8hIRWK2Kiq_D2ah4MaMqeyi1K0,2233 +tensorflow/include/tensorflow/compiler/xla/comparison_util.h,sha256=a1zAZ-E5-EdWIBTubRsV94Nt1spU7k5x7T2r1R8erx4,9465 +tensorflow/include/tensorflow/compiler/xla/cpu_function_runtime.h,sha256=sUqfDl7NyEq64cGEh0IFac-W3guK1mMPvdcmkZALZ0I,8566 +tensorflow/include/tensorflow/compiler/xla/debug_options_flags.h,sha256=XA7q8JHvc8Hk8AG92biTuxwcTTrLnNlQhvKIDh1brw4,4297 +tensorflow/include/tensorflow/compiler/xla/debug_options_parsers.h,sha256=dnaq-eZrKGnAv56yMCKrYuP4_5Igo1HRYSIS3iKWWes,1705 +tensorflow/include/tensorflow/compiler/xla/error_spec.h,sha256=ksYTCTlTCIOPX-LTjRmd1_2zqIf4pNI5zZsR4Cda5Ao,1977 +tensorflow/include/tensorflow/compiler/xla/executable_run_options.h,sha256=_T2xmNz1LmYst5HAMThzwVIGluEZ951A8vw3tINtGfk,9255 +tensorflow/include/tensorflow/compiler/xla/execution_options_util.h,sha256=nRHtisxY1F4EW2LxtSjXzB1kaMTt1QT4HN-w6sf9W0U,1032 +tensorflow/include/tensorflow/compiler/xla/frontend_attributes.h,sha256=SCJ75WXuZuU7q9jWAoC1J1fb6gSjKuTlVHOdC8JekAE,1502 +tensorflow/include/tensorflow/compiler/xla/hlo/evaluator/hlo_evaluator.h,sha256=jN_C0n0IQID7bJszX83-mzujhxCAFp4BEfrvXTzqabc,21650 +tensorflow/include/tensorflow/compiler/xla/hlo/evaluator/hlo_evaluator_typed_visitor.h,sha256=tpeQyxDJ2qAb1DzGjj2ydvi3AjPYwF-VqtwWWIKLzVo,68383 +tensorflow/include/tensorflow/compiler/xla/hlo/ir/dfs_hlo_visitor.h,sha256=AhSHJA_NCrR8ZY9nZgXHEhjHV1rr7w3VmnYS5SQCa2s,16852 +tensorflow/include/tensorflow/compiler/xla/hlo/ir/dfs_hlo_visitor_with_default.h,sha256=icXLsmlPQDPdOqsTB1qB5RS1tn6O1Hh3LUd-EcGPNv0,14261 +tensorflow/include/tensorflow/compiler/xla/hlo/ir/dynamic_parameter_binding.h,sha256=Wje8xUrRfr2uvYr05ydr7XMgSMJAPjUi1lAciXPdeLQ,4536 +tensorflow/include/tensorflow/compiler/xla/hlo/ir/hlo_casting_utils.h,sha256=yI5jfBAUaWa2y-XW4PPQ-roVA9WAaHcDQfWf5zFVZCo,4047 +tensorflow/include/tensorflow/compiler/xla/hlo/ir/hlo_clone_context.h,sha256=5t5TqhW90eCo8gaOjJuhdqqmB51nthr75TcTEycT6NQ,3451 +tensorflow/include/tensorflow/compiler/xla/hlo/ir/hlo_computation.h,sha256=E42vBiiBK7QoEVcRGXX_wxgsnCKSy2DjchNvY3iQk6k,42221 +tensorflow/include/tensorflow/compiler/xla/hlo/ir/hlo_domain_metadata.h,sha256=23rCeVKERJo8vCpzG2av8b4Ijx6QN5V2cGVu_k567Wo,3111 +tensorflow/include/tensorflow/compiler/xla/hlo/ir/hlo_frontend_attributes.h,sha256=Gwad_mO7RFw_0ymOIC1SuwdA7SJd8CSVzWUALdHUQ64,990 +tensorflow/include/tensorflow/compiler/xla/hlo/ir/hlo_input_output_alias_config.h,sha256=HIG6KsqoKTcdoDyFiT9hSxLorujZX8If_vLJyDfVVNM,8309 +tensorflow/include/tensorflow/compiler/xla/hlo/ir/hlo_instruction.h,sha256=C9yc41bWA13maGLcHZFzugnBX_qNLT4aGsOVn4DF8uw,112074 +tensorflow/include/tensorflow/compiler/xla/hlo/ir/hlo_instructions.h,sha256=7zAF8yIK5ItadDp8P-ttfvCHnqm2czq6jkWAbmmv0Cw,103493 +tensorflow/include/tensorflow/compiler/xla/hlo/ir/hlo_module.h,sha256=h-LxwlJ0R2lCk0kZDac1PgqSrWvlTz9TS4qswORl1dU,28946 +tensorflow/include/tensorflow/compiler/xla/hlo/ir/hlo_module_group.h,sha256=XDbXwQ7-AOE6VvPl3gOkFbbAHIy_1K-RHaRWwp-OIR4,3919 +tensorflow/include/tensorflow/compiler/xla/hlo/ir/hlo_module_metadata.h,sha256=wmguoCvE0u-mr-Z-XUX_LMFCB6dfU9S9GDIR-Tt6Q9c,4753 +tensorflow/include/tensorflow/compiler/xla/hlo/ir/hlo_op_metadata.h,sha256=UWFBvqqMCzngxLVTjBpPp43Ax_b5xAAhu0K3Q756Ow8,934 +tensorflow/include/tensorflow/compiler/xla/hlo/ir/hlo_opcode.h,sha256=kfS-AamKfESSwyrUFuBmoSkOOEXlhWKzxQ9VuAKh84o,13394 +tensorflow/include/tensorflow/compiler/xla/hlo/ir/hlo_reachability.h,sha256=-xuzB_r3yqGIsDl9hQ0HNTmi0ISuvjIhzPkphftVhnQ,8563 +tensorflow/include/tensorflow/compiler/xla/hlo/ir/hlo_schedule.h,sha256=uteAdz97tPVwRi7msyK4DOoYMjpHcgNKbqp0B9fOCqo,8774 +tensorflow/include/tensorflow/compiler/xla/hlo/ir/hlo_sharding.h,sha256=Ou-bkYlCgEg98cT6ybZEWqB2x8a6WTUyx_XzLoYgYMk,27488 +tensorflow/include/tensorflow/compiler/xla/hlo/ir/hlo_sharding_metadata.h,sha256=2ARhcKEdomJiNRpBJvSxNfVhyE9qn37QsFi7lA-q5SM,3970 +tensorflow/include/tensorflow/compiler/xla/hlo/ir/tile_assignment.h,sha256=Pwi0PbM2k3sUURw8oiit4ElKgG7KPdMe0YR8TWF1B1U,10802 +tensorflow/include/tensorflow/compiler/xla/hlo/transforms/hlo_constant_splitter.h,sha256=Pf7mWQj0AdA1cqPQ2e-idN4B4ST64kkAVb1wJtZUaik,1911 +tensorflow/include/tensorflow/compiler/xla/hlo/utils/hlo_live_range.h,sha256=ddN4UNPSzfIJbaPrAQL4Q3f5odQxNeA0wpXH0Zs08qQ,8737 +tensorflow/include/tensorflow/compiler/xla/hlo/utils/hlo_query.h,sha256=4WcVAeHD2j-Wv24jiLovSbYgNHZ2Hv8iGN6N_p_xh_M,5747 +tensorflow/include/tensorflow/compiler/xla/hlo/utils/hlo_sharding_util.h,sha256=ATP7EuKpGlbbvPPZN52FEDkilD9qJmOeIrF2ami7gwY,23488 +tensorflow/include/tensorflow/compiler/xla/index_util.h,sha256=MTrPmErcmCJe_3sGppcoIdQI9ALl6WsK0JF26IOQFEw,6155 +tensorflow/include/tensorflow/compiler/xla/iterator_util.h,sha256=_klwPpsoOMNSMPF04MGQeqxebMbELbQxYDUuwiYXsFY,5668 +tensorflow/include/tensorflow/compiler/xla/layout.h,sha256=uNG5BfhXl5QX4hwGT0FKgERP9l6ojDDPB0jeguhNisQ,13570 +tensorflow/include/tensorflow/compiler/xla/layout_util.h,sha256=tdr9GCq-lnOEUJE4EhkLfjO1TZODx5zDI3egase-YPw,12756 +tensorflow/include/tensorflow/compiler/xla/lazy.h,sha256=UO3uUcbx_8Rl29arVFuhepfoWMnTpDKJ0hkMYxVbDAU,1275 +tensorflow/include/tensorflow/compiler/xla/literal.h,sha256=-cOIKJMh-9s4RG8SvD4jM4H93uBi3769hJwTut_DVpE,64108 +tensorflow/include/tensorflow/compiler/xla/literal_comparison.h,sha256=uRvkfYL5FR4ZFNZTGiz2d5sGzhYZdlCEiLscXy2wzp0,4209 +tensorflow/include/tensorflow/compiler/xla/literal_util.h,sha256=Qp9Yb7LtwHdLMV1hZ7d3OuMQ_oFV_n3KNhEvdr7e-ro,21512 +tensorflow/include/tensorflow/compiler/xla/map_util.h,sha256=aj1zGs5ZXh9Debnzre48pmOoHyfXCUnGZwMZclf-EAQ,4689 +tensorflow/include/tensorflow/compiler/xla/metric_table_report.h,sha256=1B3sb7Ev1dTGb4p3sHhUCZKing4ya2wemgbRHjBZxqY,6466 +tensorflow/include/tensorflow/compiler/xla/mlir/backends/cpu/transforms/passes.h,sha256=nLH5mbS6fM99pbvcjdReTRKmM84NEaNnNYqCwbhGwHI,2239 +tensorflow/include/tensorflow/compiler/xla/mlir/backends/cpu/transforms/passes.h.inc,sha256=VmvlCAQaDvJXoWGGZjf1Z206LXBc3raZtHTORlBz2HY,42540 +tensorflow/include/tensorflow/compiler/xla/mlir/backends/gpu/transforms/dataflow_analysis.h,sha256=_3z0UOuhqDrij9z4V8Y0AmF_8S9ziyrjATd0sZSQtIo,1992 +tensorflow/include/tensorflow/compiler/xla/mlir/backends/gpu/transforms/passes.h,sha256=7nBCnKZimdHd1H_Fv0iffLKer6vkMiqmYMKqtuEBpEM,5484 +tensorflow/include/tensorflow/compiler/xla/mlir/backends/gpu/transforms/passes.h.inc,sha256=a6zP7CBL28OTjaXBPW_RjSCIL0kPTdSnIhXYuiYxufw,47299 +tensorflow/include/tensorflow/compiler/xla/mlir/backends/gpu/transforms/uid_generator.h,sha256=3PWCI8cS-RGeGAuFl8KlMh9lNUW908GillqsE-KUN7c,1417 +tensorflow/include/tensorflow/compiler/xla/mlir/backends/gpu2/transforms/passes.h,sha256=AzfE2tyoQ6c25oAIUpXDkexLTBCNv9mfHL4KJ9zWouA,2970 +tensorflow/include/tensorflow/compiler/xla/mlir/framework/ir/xla_framework.h,sha256=FcvzCeKLJfuWDLfv0YW_1nuOZI-c2-wmISzzLn814qA,1485 +tensorflow/include/tensorflow/compiler/xla/mlir/framework/ir/xla_framework.h.inc,sha256=bcXIAFzoMP47lDp7tZ3ExsRslOk3SbcbEeRHvz-wXLM,10918 +tensorflow/include/tensorflow/compiler/xla/mlir/framework/ir/xla_framework_dialect.h.inc,sha256=-mRjSDcNyfI4rW7sLVFzh-c6TAF4sqho6nLb0V0WJoY,1593 +tensorflow/include/tensorflow/compiler/xla/mlir/framework/ir/xla_framework_types.h.inc,sha256=WjhlZzX5jf771Z4kCP_Y89lg6ChJ1MomuzmrPVeZziw,1118 +tensorflow/include/tensorflow/compiler/xla/mlir/framework/transforms/passes.h,sha256=lN0F1unnxbMknWMlWr-SgsvvRyjgWOsANDvpm8vDEeg,1637 +tensorflow/include/tensorflow/compiler/xla/mlir/framework/transforms/passes.h.inc,sha256=f6XGO6Qh5inArvu__WQGJSr952ldFH9gw0FYg6a57s0,10958 +tensorflow/include/tensorflow/compiler/xla/mlir/math/transforms/passes.h,sha256=Ke-JY58EHg12cZucWwtzaLueI5R0jB6Ja-shdn4YBXQ,1507 +tensorflow/include/tensorflow/compiler/xla/mlir/math/transforms/passes.h.inc,sha256=mUluYeOVNzsLZim3SLSZ9vz9dex01lJ_b0YwZ5kno4o,11723 +tensorflow/include/tensorflow/compiler/xla/mlir/memref/transforms/passes.h,sha256=ITYlfraMiWy3iZrZ8dZbvpUz-0KGZa0WBXGp62FD4C4,1274 +tensorflow/include/tensorflow/compiler/xla/mlir/memref/transforms/passes.h.inc,sha256=BaEj4IHrL1lyBxYjnJcTx-cl8A1fYrGAXSA1DUY0CZE,6097 +tensorflow/include/tensorflow/compiler/xla/mlir/runtime/ir/rt_attr_interfaces.h.inc,sha256=zIsIlKQbUOrbRXA_qGO15HWiwhuYkkJRsPQehreBnew,2236 +tensorflow/include/tensorflow/compiler/xla/mlir/runtime/ir/rt_attrs.h.inc,sha256=DUal2nLhqJmmOpKS7eXHOfwWOjV7EdtmjAP36y1ZonI,1505 +tensorflow/include/tensorflow/compiler/xla/mlir/runtime/ir/rt_dialect.h,sha256=anMgfa51vad450FDVhIBxYyy0RA8eWuiSELDShPh_9s,1539 +tensorflow/include/tensorflow/compiler/xla/mlir/runtime/ir/rt_dialect.h.inc,sha256=rxU5OPIGD13Tkqh9deL-60M_aMFVqaObjsED7s9FutA,1955 +tensorflow/include/tensorflow/compiler/xla/mlir/runtime/ir/rt_interfaces.h,sha256=LxPvWAFRpjtAeZQ4RGF4qIbf_3L-ykpq32pBWnhzUHI,979 +tensorflow/include/tensorflow/compiler/xla/mlir/runtime/ir/rt_ops.h,sha256=4B6jEnAcfk2FGU1ufvszUXEuKfbJKyJSh8jNweCsI5Q,1425 +tensorflow/include/tensorflow/compiler/xla/mlir/runtime/ir/rt_ops.h.inc,sha256=6EwFFl9jHL_T21qPIWXaxRz7lUXaoS2bKzmJBnXIG7I,54680 +tensorflow/include/tensorflow/compiler/xla/mlir/runtime/ir/rt_types.h.inc,sha256=B9zxCDqq6gW76ypG55ZLDvDZdMkBDzRY84TvaEmBHQE,1728 +tensorflow/include/tensorflow/compiler/xla/mlir/runtime/ir/tests/testlib.h,sha256=W4yn9WscZkvfnzVib0GXPP_p2lYg_gtp1sd2JRU1z8U,1718 +tensorflow/include/tensorflow/compiler/xla/mlir/runtime/ir/tests/testlib_attrs.h.inc,sha256=Uehcb0yadkBTcopNa4o96tCeql9R9D5IVESafuNk6Yg,2927 +tensorflow/include/tensorflow/compiler/xla/mlir/runtime/ir/tests/testlib_dialect.h.inc,sha256=TkvNf79qKT91HnuGmo15j0wJWCTFGFM5ocHzcNYYrcY,1741 +tensorflow/include/tensorflow/compiler/xla/mlir/runtime/ir/tests/testlib_enums.h.inc,sha256=_JgAMtHIBr_u282YqVIIhCc1lrCqkRcNejudb0WKtv4,5670 +tensorflow/include/tensorflow/compiler/xla/mlir/runtime/ir/tests/testlib_types.h.inc,sha256=unrfvuL1yaq9WGjwhGbzF2PcApoU9_oYbexrhiC0k5w,1398 +tensorflow/include/tensorflow/compiler/xla/mlir/runtime/transforms/calling_convention.h,sha256=7h45XP31A-NksW4PY1IPAqNrpH7_3sW_0-DKkl10cng,3814 +tensorflow/include/tensorflow/compiler/xla/mlir/runtime/transforms/compilation_pipeline_cpu.h,sha256=O-kZ0v6y8j1oHE4RKneAm7kyjFqautx3rDZwcLEvi4w,2429 +tensorflow/include/tensorflow/compiler/xla/mlir/runtime/transforms/compilation_pipeline_gpu.h,sha256=57xuwAUhGwpCtjJZrPlUdNHYddSQl4phC4aFLBFSOeU,2015 +tensorflow/include/tensorflow/compiler/xla/mlir/runtime/transforms/compilation_pipeline_options.h,sha256=GvWkRg4VN0GI9CjBqqnqLXWPCahG4vYnT1z62VFfg0E,2237 +tensorflow/include/tensorflow/compiler/xla/mlir/runtime/transforms/compiler.h,sha256=ovqjCzZDPZazFKvAaJ6sS1KL0Dkw_sDKedadB3R45mg,1482 +tensorflow/include/tensorflow/compiler/xla/mlir/runtime/transforms/custom_call_encoding.h,sha256=no-fO6Zm0mX6WJlKmaqNIZLIBvJLXEtBl6kthFHsveY,32681 +tensorflow/include/tensorflow/compiler/xla/mlir/runtime/transforms/jit_compiler.h,sha256=EWiaJoXQalDVLGVV6EvjnrzMkQ0U0_Uxo1YiFSf0IqE,8611 +tensorflow/include/tensorflow/compiler/xla/mlir/runtime/transforms/passes.h,sha256=pIDx9J7McY8nNAFV-0pY1_m14jcBwKvhgXRtDYBjQn4,4365 +tensorflow/include/tensorflow/compiler/xla/mlir/runtime/transforms/passes.h.inc,sha256=m53BL3RgHe8v63Q2natbU_3E0hNPpCnAkopo_fb7iFQ,29840 +tensorflow/include/tensorflow/compiler/xla/mlir/runtime/transforms/specialization.h,sha256=3Ek34dNzJfuaPDkmzqbXlOkisaUgvFajpUhCLdp231Y,2938 +tensorflow/include/tensorflow/compiler/xla/mlir/runtime/transforms/type_converter.h,sha256=9a2WQqRpUqHE4BGuqNfGH0n0hPqll-JeVwQVWEL2pN0,3369 +tensorflow/include/tensorflow/compiler/xla/mlir/runtime/utils/async_runtime_api.h,sha256=JAuPiU1ecYadZEeK3w0f-m32nLOqHkCHE7Sd5O3o7Ew,2553 +tensorflow/include/tensorflow/compiler/xla/mlir/runtime/utils/c_runner_utils.h,sha256=EWxyvMSY_-3CFbSi4cCwXnpV296Zk01HpBNO97cV39I,1581 +tensorflow/include/tensorflow/compiler/xla/mlir/runtime/utils/constraints.h,sha256=_M0ZK6rr9sGy3w_Byw9avVAczVS5ZhHCc2aiaSOp0sw,2058 +tensorflow/include/tensorflow/compiler/xla/mlir/runtime/utils/custom_calls.h,sha256=8rr7RGxp3O9j7ZoXKSgocSTMaeXhqmT8f8O-Az105rk,3022 +tensorflow/include/tensorflow/compiler/xla/mlir/runtime/utils/float_16bits.h,sha256=7KDs3FQP6PlIyu2ImSdl2gScLfaXdIK-fvIr3D9ZXEk,1638 +tensorflow/include/tensorflow/compiler/xla/mlir/utils/error_util.h,sha256=SkzjVRJI--7fXq4E3HMorOdcHzNwpR9D_rgz9LzxeCs,2973 +tensorflow/include/tensorflow/compiler/xla/mlir/xla_cpu/ir/xla_cpu.h,sha256=jYO0iL1TQP2O0dUG_5PKd-WSzLBamwBFD4TWYSgPMJo,1653 +tensorflow/include/tensorflow/compiler/xla/mlir/xla_cpu/ir/xla_cpu.h.inc,sha256=cAuU4YmZhWvtteinwTHWvzsPCGZM01uWY-RLdAR1YHc,91566 +tensorflow/include/tensorflow/compiler/xla/mlir/xla_cpu/ir/xla_cpu_attrdefs.h.inc,sha256=U3evD2fwFkkPQuo5LXuOVzPFNVeUSDPQb09cvVeRyX8,1522 +tensorflow/include/tensorflow/compiler/xla/mlir/xla_cpu/ir/xla_cpu_dialect.h.inc,sha256=HfKyv-3OZdyoMbdPZ0Usl1nRdChI7U1B1Rd5n-te3Yc,1107 +tensorflow/include/tensorflow/compiler/xla/mlir/xla_cpu/ir/xla_cpu_enums.h.inc,sha256=RItkwmIMnX0a8bDMd_FUGxlHRNUsqOXCZ3s4WgQ6noo,3336 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/all_passes/deallocation/transforms/passes.h,sha256=ZZY_6CCZ4ZX_-lIpYK7lwUER10bDIAx-ZZXpvRN7Tn0,2550 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/all_passes/gml_st/transforms/passes.h,sha256=g4SBaJrkbFhmEnEgv5rw6BCc5oSymWNAZizHN_-ew7k,9983 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/all_passes/lhlo/transforms/passes.h,sha256=2Y9uNL7CxQDYyDN2iVBgH4BFoIhM5TchSi_6yhUGbdA,1963 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/all_passes/mhlo/transforms/passes.h,sha256=IvOAuySp_AQnHvfKMhxumXPFkBF4WqfQf8OKDFbDRSQ,8261 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/all_passes/thlo/transforms/passes.h,sha256=0AH2wIhki34dvhq_Pdm1EtE0ktFa8HE9wVD2bHC1ehQ,1303 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/all_passes/transforms/passes.h,sha256=H4pevJJdIMIBCeC-itVnjB9dVi-AY4ZQ5xmMNI4K60U,4807 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/chlo_legalize_to_hlo/mhlo/transforms/rewriters.h,sha256=wTzkKPOJY14JvNDrW4bCvehtX8MAp8BVhFPSaqp7gUc,10921 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/convert_op_folder/utils/convert_op_folder.h,sha256=tEMneDUBuNY42Bt6D1-b9PfP6Jm0EzIvLID4vR7Jlmk,1241 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/deallocation/deallocation/IR/deallocation_ops.h,sha256=kQLaMcVSEAX7c-C0uADV-AmDVcsHA2o7K26vwOZhTiw,1380 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/deallocation_ops_inc_gen/deallocation/IR/deallocation_dialect.h.inc,sha256=jvugWnQjGXGWdoLoB4XmNRDMWoyYZyp7sPFjszxpGLA,1422 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/deallocation_ops_inc_gen/deallocation/IR/deallocation_ops.h.inc,sha256=6l56yKJHRw0DAXD--Mgku4XuM3BHDUSSgbmsadQvCxI,25419 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/deallocation_ops_inc_gen/deallocation/IR/deallocation_typedefs.h.inc,sha256=KxzGTwCMsVGiZVgxxrf-9uG0sgiNHnnWStldmaUyP6k,1166 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/deallocation_passes/deallocation/transforms/analysis.h,sha256=VVNde3mKTlAG06tA_8R0_MrpjRI52wUszqevRbHqpHo,2057 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/deallocation_passes/deallocation/transforms/passes.h,sha256=ZZY_6CCZ4ZX_-lIpYK7lwUER10bDIAx-ZZXpvRN7Tn0,2550 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/deallocation_passes_inc_gen/deallocation/transforms/passes.h.inc,sha256=umMxZ24rTBZJFxPqrWVsZRnKoLUdJjRwDtNE9owIocw,41280 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/deallocation_utils/deallocation/utils/util.h,sha256=c8PPI7Qrdl8GQNszHYmSZc4poAMsSDYSWddZJD2JNak,5675 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/gml_st/gml_st/IR/gml_st_ops.h,sha256=I2MMXQoUFH-GYeW_LQZznUT_14AjC3prRsU507fG3GU,1333 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/gml_st_bufferizable_op_interface/gml_st/interfaces/bufferizable_op_interface_impl.h,sha256=f9a_3ypgiqucrEd3ZqeXUiGrFMd1-9NxrgYd4yPQ_lI,1000 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/gml_st_ops_inc_gen/gml_st/IR/gml_st_dialect.h.inc,sha256=aisknAOSUZebUTcrIFjy-Aj2OQOqpyXoItBqGCZxJF4,1099 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/gml_st_ops_inc_gen/gml_st/IR/gml_st_ops.h.inc,sha256=_lb4ejrD9ltCxJHivjjNDzb16LISJz64CamOlUvdhYY,13250 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/gml_st_passes/gml_st/transforms/fusion/fusion.h,sha256=odEMnPQdxtV1hQu1UWl0M1rnA0Uwjhz1iINtDJ0uxQk,3716 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/gml_st_passes/gml_st/transforms/passes.h,sha256=g4SBaJrkbFhmEnEgv5rw6BCc5oSymWNAZizHN_-ew7k,9983 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/gml_st_passes/gml_st/transforms/peeling/peeling.h,sha256=pgoQUZXH1rZYxCv017hJ_9EDaxLyai-2UQkij8Bj_K0,1939 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/gml_st_passes/gml_st/transforms/scalarization/scalarization.h,sha256=knZv1LmUe2OU6vkMgwxrugv_J3Ksg3YMx2yghGP1SNU,2426 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/gml_st_passes/gml_st/transforms/tiling/tiling.h,sha256=d3rS4Z2q85FgOoesiHBfJ2WjyF_kEfhULFI77wkEtHU,1934 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/gml_st_passes/gml_st/transforms/vectorization/vectorization.h,sha256=v6S0ZnfeMwIqKtIO1yzi9yRO0mHpAye0JxixSZ32ROY,1977 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/gml_st_passes/gml_st/utils/linalg_utils.h,sha256=0Sd3NLbhPe6PPPcTqMozn5wWhFbYdfR5mqTTewk_JpE,3052 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/gml_st_passes/gml_st/utils/tensor_utils.h,sha256=Tk98AIFB1of7ZJ1-ljwNm1jTiNvoPEp1fsjUIfKqtUk,2212 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/gml_st_passes_inc_gen/gml_st/transforms/passes.h.inc,sha256=3jYCVG_DnBdFyEL4CwhGiglTZC7LsfJXjcey8jVq1qE,132420 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/gml_st_transforms/gml_st/transforms/transforms.h,sha256=v5yN-WPAc6C4pNEk7RdO59K1ZAeNQfqNVQOmAiG7RNs,1655 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/gpu_transforms_passes_inc_gen/transforms/gpu_passes.h.inc,sha256=E1SAY94wfPMZAMrH3HS0u62HCL181vmNPtX8HNsP3Go,10552 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/hlo_dialect_registration/mhlo/IR/register.h,sha256=JaZgDMHYOwIdyG_rPu3d9Q2LMjWijRMtvz2SCCvXChk,1023 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/hlo_legalize_to_stablehlo/mhlo/transforms/rewriters.h,sha256=wTzkKPOJY14JvNDrW4bCvehtX8MAp8BVhFPSaqp7gUc,10921 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/hlo_ops_attrs_inc_gen/mhlo/IR/hlo_ops_attrs.h.inc,sha256=LOzYkRIDaytGeShcEQsELwG1LQhO8r_i1rxTZYon4Tw,17559 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/hlo_ops_common/mhlo/IR/hlo_ops_common.h,sha256=opLmnNUo3gj-HJURlD6-GHp99hmoVfd4uCu17Q9bUR8,2397 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/hlo_ops_enums_inc_gen/mhlo/IR/hlo_ops_enums.h.inc,sha256=Pns8uVUaoJk7gNcUNQl1h1asPegKYYLKsSHDTIF_zbI,32552 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/hlo_ops_inc_gen/mhlo/IR/hlo_ops.h.inc,sha256=mlRnvvYERPkbEoXdcvnghxIeoNm3-LDXAyqNEyOE7fk,896979 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/hlo_ops_typedefs_inc_gen/mhlo/IR/hlo_ops_typedefs.h.inc,sha256=O8PdrgZVygmyLSdrubgbCTU53ECFzZCk_ha48I1DmKE,2087 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/legalize_to_linalg_utils/mhlo/utils/legalize_to_linalg_utils.h,sha256=mz0wZGt0sY0TN0Yx7upBPJY3wb6bMQcnn25xKNYsjkw,7231 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/lhlo/lhlo/IR/lhlo_ops.h,sha256=GpRFKeD11KaIYx7jZql50JYvGlUvD8FrTgDdFMKAot0,2207 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/lhlo/lhlo/IR/lhlo_ops_structs.h,sha256=MCHQnVpJq5pN6WDVzUMOHd4aVuK-dEdv3ct-13bwo0Y,1130 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/lhlo/lhlo/utils/lhlo_utils.h,sha256=65i_GTPmu4kdiKYalJEL0kqNKuLI-qct6BY65sz06Mo,2805 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/lhlo_gpu/lhlo_gpu/IR/lhlo_gpu_ops.h,sha256=uyPTD3YmlfoMelHtkD9jX8MDMNYizNLpSrtP9kNVFwo,1562 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/lhlo_gpu_ops_attrdefs_inc_gen/lhlo_gpu/IR/lhlo_gpu_ops_attrdefs.h.inc,sha256=yggcz1fBZ3fZnwjaNO-_oZNqaql55LcLTT3XoeHwF90,6410 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/lhlo_gpu_ops_dialect_inc_gen/lhlo_gpu/IR/lhlo_gpu_ops_dialect.h.inc,sha256=Snrfoz-4tvPDgN03XPjX-t5ZdOCKziOaGFIK6jx9YOU,1485 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/lhlo_gpu_ops_enums_inc_gen/lhlo_gpu/IR/lhlo_gpu_ops_enums.h.inc,sha256=e3PSffiMuJi8rM7dWhrlYQnEa84To7CIen9-6kz_Dxc,12744 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/lhlo_gpu_ops_inc_gen/lhlo_gpu/IR/lhlo_gpu_ops.h.inc,sha256=S2LN0Bv5xuc19x1aDrYQWktU4KE1nqNe159KIqFWH4Q,256626 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/lhlo_gpu_ops_ops/lhlo_gpu/IR/lhlo_gpu_ops.h.inc,sha256=S2LN0Bv5xuc19x1aDrYQWktU4KE1nqNe159KIqFWH4Q,256626 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/lhlo_ops_inc_gen/lhlo/IR/lhlo_ops.h.inc,sha256=8_uJEnFfUxhSopr-25NguH19o8X-LzLzYqNU47x0l5A,603865 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/lhlo_ops_structs_inc_gen/lhlo/IR/lhlo_ops_structs.h.inc,sha256=NZJdkWYKFXEbp0eYOPmCjJ-s_knL_ML8vXDDoD5Xya4,1856 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/lhlo_structured_interface/lhlo/IR/lhlo_structured_interface.h,sha256=p8kuX5-SwDNOEd8zsZ362lxemH6-qVik7WqRNoHS2Bg,970 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/lhlo_structured_interface/lhlo/IR/lhlo_structured_interface.h.inc,sha256=emLUsk4IC-rjoXIb31jY4Gc5cI0LW7VrmHjymIlX1WY,3674 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/lhlo_structured_interface_inc_gen/lhlo/IR/lhlo_structured_interface.h.inc,sha256=emLUsk4IC-rjoXIb31jY4Gc5cI0LW7VrmHjymIlX1WY,3674 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/lmhlo_pass_inc_gen/lhlo/transforms/lmhlo_passes.h.inc,sha256=sOh8JNYZiCf5sUsnaTY7t_qGrCP_fQLBsv2WhSuDCdw,20494 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/lmhlo_passes/lhlo/transforms/passes.h,sha256=2Y9uNL7CxQDYyDN2iVBgH4BFoIhM5TchSi_6yhUGbdA,1963 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/map_chlo_to_hlo_op/mhlo/transforms/map_chlo_to_hlo_op.h,sha256=HImDyyHIJbe068-4PmVYPjeI3t0UKbXj3wekLkocH10,5422 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/map_hlo_to_lhlo_op/lhlo/transforms/map_hlo_to_lhlo_op.h,sha256=ttqAXs2X0yEKAawCQO7d4QSLXhtQdrjAZ7x2RiDd1uo,3148 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/map_lhlo_to_hlo_op/lhlo/transforms/map_lhlo_to_hlo_op.h,sha256=B-CJZEq7cxQI_hIz-Moiuq-H6xZcZwFFDjmSzQsTtcc,3052 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/map_lmhlo_to_scalar_op/lhlo/transforms/map_lmhlo_to_scalar_op.h,sha256=W1uXZfJ_RdM8BFsZo6oqdkfgGz0L-UlmnQJD5GURWdM,2797 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/map_mhlo_to_scalar_op/mhlo/transforms/map_mhlo_to_scalar_op.h,sha256=j5TkgmWrhVVI43sZk1p9fKIY9Pk-rA5zjzeMMxp_YkE,58969 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/map_stablehlo_to_hlo_op/mhlo/transforms/map_stablehlo_to_hlo_op.h,sha256=4qe_RcbGe5Yz3m0ZqY34obnkDQGA7arbEUEawEj4rqk,5686 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/mhlo_pass_inc_gen/mhlo/transforms/mhlo_passes.h.inc,sha256=wk1VgzmfuPQFFfbWMkP3IgV2EDkOK5FVsdIVxy13iB0,264559 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/mhlo_passes/mhlo/interfaces/bufferizable_op_interface_impl.h,sha256=X4yb4Dmx_NlmD9hg-O43IhXXYp8OoVvFO7JFum6ZAyo,1198 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/mhlo_passes/mhlo/transforms/passes.h,sha256=IvOAuySp_AQnHvfKMhxumXPFkBF4WqfQf8OKDFbDRSQ,8261 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/mhlo_passes/mhlo/transforms/rewriters.h,sha256=wTzkKPOJY14JvNDrW4bCvehtX8MAp8BVhFPSaqp7gUc,10921 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/mhlo_passes/mhlo/utils/legalize_to_linalg_utils.h,sha256=mz0wZGt0sY0TN0Yx7upBPJY3wb6bMQcnn25xKNYsjkw,7231 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/mhlo_passes/mhlo/utils/mhlo_rng_utils.h,sha256=h7E2cR2tQBXEFkBYQypX0tds6ba7OCFK5cyX1tXcUBE,1335 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/mhlo_rng_utils/mhlo/utils/mhlo_rng_utils.h,sha256=h7E2cR2tQBXEFkBYQypX0tds6ba7OCFK5cyX1tXcUBE,1335 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/mhlo_scatter_gather_utils/mhlo/utils/mhlo_scatter_gather_utils.h,sha256=603iAPxWZs4Y5iGW9coxW8cuvzwF4BiImL3_CTBZXV0,2932 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/mlir_hlo/mhlo/IR/hlo_ops.h,sha256=QvjiX7wh8zl8D4rxnpkLR9y9Gao9WpY-UhdFWe6UpLI,4196 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/mlir_hlo/mhlo/IR/mhlo_bytecode.h,sha256=AN-gc_qRVfgwojxxIzatbZaMGyEW3edrLukcmqf5LSY,1045 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/mlir_hlo/utils/hlo_utils.h,sha256=dRAH2dJxhChE_AduscFOPNiZKrkHtJpzcAKOByfh-Tc,5601 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/shape_component_analysis/mhlo/analysis/shape_component_analysis.h,sha256=89qd11Yemuc4uabwK9mwjwaPZDhATFc1TfvhWFKMmkM,6547 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/stablehlo_legalize_to_hlo/mhlo/transforms/rewriters.h,sha256=wTzkKPOJY14JvNDrW4bCvehtX8MAp8BVhFPSaqp7gUc,10921 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/thlo/thlo/IR/thlo_ops.h,sha256=BBHaGEjX3YTxHa-DUHO8XARnqaNOFGZknTECBVTf-NI,1359 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/thlo_bufferizable_op_interface/thlo/interfaces/bufferizable_op_interface_impl.h,sha256=z937tWCLFKON5GmPmx3frwdpgpoYoQz9PXY-tDd51dQ,1054 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/thlo_ops_inc_gen/thlo/IR/thlo_dialect.h.inc,sha256=At440BSiEiXlJHTdn7j5PJ3EVbSkgbJaCaa4GA-TwMA,1087 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/thlo_ops_inc_gen/thlo/IR/thlo_ops.h.inc,sha256=5cpHCWjZJr_hOKtRJCe3gIPoksOX4cU8jLM5Stb2jAA,49395 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/thlo_passes/thlo/transforms/passes.h,sha256=0AH2wIhki34dvhq_Pdm1EtE0ktFa8HE9wVD2bHC1ehQ,1303 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/thlo_passes_inc_gen/thlo/transforms/thlo_passes.h.inc,sha256=YoSzfaATxGCmIYICxIsdnGJyzh23OLfZKTXh3_s1OAs,5691 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/transforms_gpu_passes/transforms/gpu_passes.h,sha256=uq3AvgzBVlc-aTgKXGtvf9FbImDpITOcbMFXFM_a6TI,1680 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/transforms_passes/transforms/passes.h,sha256=H4pevJJdIMIBCeC-itVnjB9dVi-AY4ZQ5xmMNI4K60U,4807 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/transforms_passes/transforms/passes.h.inc,sha256=wa2RGQWrDxcbxj2lcqAzJQEOCQpVEfvT4CWnTsOBYzc,82230 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/transforms_passes/transforms/rewriters.h,sha256=U577QT6BIqFg6mmrviQUjiU5Vck7mGhv1UZSYA03xSE,1451 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/transforms_passes_inc_gen/transforms/passes.h.inc,sha256=wa2RGQWrDxcbxj2lcqAzJQEOCQpVEfvT4CWnTsOBYzc,82230 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/type_conversion/mhlo/utils/type_conversion.h,sha256=zd2RcsfZcD0Ou9pcqkbUEeZ_aMcqWXugx0jItj3kZTk,3699 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/unfuse_batch_norm/mhlo/transforms/rewriters.h,sha256=wTzkKPOJY14JvNDrW4bCvehtX8MAp8BVhFPSaqp7gUc,10921 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/_virtual_includes/userange_analysis/analysis/userange_analysis.h,sha256=iydhJNksGuEoI3F_bqGTXeWNU-K1gJ95BtNxKHukiyg,7598 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/analysis/userange_analysis.h,sha256=iydhJNksGuEoI3F_bqGTXeWNU-K1gJ95BtNxKHukiyg,7598 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/deallocation/IR/deallocation_dialect.h.inc,sha256=jvugWnQjGXGWdoLoB4XmNRDMWoyYZyp7sPFjszxpGLA,1422 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/deallocation/IR/deallocation_ops.h,sha256=kQLaMcVSEAX7c-C0uADV-AmDVcsHA2o7K26vwOZhTiw,1380 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/deallocation/IR/deallocation_ops.h.inc,sha256=6l56yKJHRw0DAXD--Mgku4XuM3BHDUSSgbmsadQvCxI,25419 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/deallocation/IR/deallocation_typedefs.h.inc,sha256=KxzGTwCMsVGiZVgxxrf-9uG0sgiNHnnWStldmaUyP6k,1166 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/deallocation/transforms/analysis.h,sha256=VVNde3mKTlAG06tA_8R0_MrpjRI52wUszqevRbHqpHo,2057 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/deallocation/transforms/passes.h,sha256=ZZY_6CCZ4ZX_-lIpYK7lwUER10bDIAx-ZZXpvRN7Tn0,2550 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/deallocation/transforms/passes.h.inc,sha256=umMxZ24rTBZJFxPqrWVsZRnKoLUdJjRwDtNE9owIocw,41280 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/deallocation/utils/util.h,sha256=c8PPI7Qrdl8GQNszHYmSZc4poAMsSDYSWddZJD2JNak,5675 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/gml_st/IR/gml_st_dialect.h.inc,sha256=aisknAOSUZebUTcrIFjy-Aj2OQOqpyXoItBqGCZxJF4,1099 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/gml_st/IR/gml_st_ops.h,sha256=I2MMXQoUFH-GYeW_LQZznUT_14AjC3prRsU507fG3GU,1333 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/gml_st/IR/gml_st_ops.h.inc,sha256=_lb4ejrD9ltCxJHivjjNDzb16LISJz64CamOlUvdhYY,13250 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/gml_st/interfaces/bufferizable_op_interface_impl.h,sha256=f9a_3ypgiqucrEd3ZqeXUiGrFMd1-9NxrgYd4yPQ_lI,1000 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/gml_st/transforms/fusion/fusion.h,sha256=odEMnPQdxtV1hQu1UWl0M1rnA0Uwjhz1iINtDJ0uxQk,3716 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/gml_st/transforms/passes.h,sha256=g4SBaJrkbFhmEnEgv5rw6BCc5oSymWNAZizHN_-ew7k,9983 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/gml_st/transforms/passes.h.inc,sha256=3jYCVG_DnBdFyEL4CwhGiglTZC7LsfJXjcey8jVq1qE,132420 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/gml_st/transforms/peeling/peeling.h,sha256=pgoQUZXH1rZYxCv017hJ_9EDaxLyai-2UQkij8Bj_K0,1939 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/gml_st/transforms/scalarization/scalarization.h,sha256=knZv1LmUe2OU6vkMgwxrugv_J3Ksg3YMx2yghGP1SNU,2426 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/gml_st/transforms/tiling/tiling.h,sha256=d3rS4Z2q85FgOoesiHBfJ2WjyF_kEfhULFI77wkEtHU,1934 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/gml_st/transforms/transforms.h,sha256=v5yN-WPAc6C4pNEk7RdO59K1ZAeNQfqNVQOmAiG7RNs,1655 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/gml_st/transforms/vectorization/vectorization.h,sha256=v6S0ZnfeMwIqKtIO1yzi9yRO0mHpAye0JxixSZ32ROY,1977 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/gml_st/utils/linalg_utils.h,sha256=0Sd3NLbhPe6PPPcTqMozn5wWhFbYdfR5mqTTewk_JpE,3052 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/gml_st/utils/tensor_utils.h,sha256=Tk98AIFB1of7ZJ1-ljwNm1jTiNvoPEp1fsjUIfKqtUk,2212 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/lhlo/IR/lhlo_ops.h,sha256=GpRFKeD11KaIYx7jZql50JYvGlUvD8FrTgDdFMKAot0,2207 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/lhlo/IR/lhlo_ops.h.inc,sha256=8_uJEnFfUxhSopr-25NguH19o8X-LzLzYqNU47x0l5A,603865 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/lhlo/IR/lhlo_ops_structs.h,sha256=MCHQnVpJq5pN6WDVzUMOHd4aVuK-dEdv3ct-13bwo0Y,1130 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/lhlo/IR/lhlo_ops_structs.h.inc,sha256=NZJdkWYKFXEbp0eYOPmCjJ-s_knL_ML8vXDDoD5Xya4,1856 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/lhlo/IR/lhlo_structured_interface.h,sha256=p8kuX5-SwDNOEd8zsZ362lxemH6-qVik7WqRNoHS2Bg,970 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/lhlo/IR/lhlo_structured_interface.h.inc,sha256=emLUsk4IC-rjoXIb31jY4Gc5cI0LW7VrmHjymIlX1WY,3674 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/lhlo/transforms/lmhlo_passes.h.inc,sha256=sOh8JNYZiCf5sUsnaTY7t_qGrCP_fQLBsv2WhSuDCdw,20494 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/lhlo/transforms/map_hlo_to_lhlo_op.h,sha256=ttqAXs2X0yEKAawCQO7d4QSLXhtQdrjAZ7x2RiDd1uo,3148 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/lhlo/transforms/map_lhlo_to_hlo_op.h,sha256=B-CJZEq7cxQI_hIz-Moiuq-H6xZcZwFFDjmSzQsTtcc,3052 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/lhlo/transforms/map_lmhlo_to_scalar_op.h,sha256=W1uXZfJ_RdM8BFsZo6oqdkfgGz0L-UlmnQJD5GURWdM,2797 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/lhlo/transforms/passes.h,sha256=2Y9uNL7CxQDYyDN2iVBgH4BFoIhM5TchSi_6yhUGbdA,1963 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/lhlo/utils/lhlo_utils.h,sha256=65i_GTPmu4kdiKYalJEL0kqNKuLI-qct6BY65sz06Mo,2805 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/lhlo_gpu/IR/lhlo_gpu_ops.h,sha256=uyPTD3YmlfoMelHtkD9jX8MDMNYizNLpSrtP9kNVFwo,1562 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/lhlo_gpu/IR/lhlo_gpu_ops.h.inc,sha256=S2LN0Bv5xuc19x1aDrYQWktU4KE1nqNe159KIqFWH4Q,256626 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/lhlo_gpu/IR/lhlo_gpu_ops_attrdefs.h.inc,sha256=yggcz1fBZ3fZnwjaNO-_oZNqaql55LcLTT3XoeHwF90,6410 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/lhlo_gpu/IR/lhlo_gpu_ops_dialect.h.inc,sha256=Snrfoz-4tvPDgN03XPjX-t5ZdOCKziOaGFIK6jx9YOU,1485 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/lhlo_gpu/IR/lhlo_gpu_ops_enums.h.inc,sha256=e3PSffiMuJi8rM7dWhrlYQnEa84To7CIen9-6kz_Dxc,12744 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/mhlo/IR/hlo_ops.h,sha256=QvjiX7wh8zl8D4rxnpkLR9y9Gao9WpY-UhdFWe6UpLI,4196 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/mhlo/IR/hlo_ops.h.inc,sha256=mlRnvvYERPkbEoXdcvnghxIeoNm3-LDXAyqNEyOE7fk,896979 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/mhlo/IR/hlo_ops_attrs.h.inc,sha256=LOzYkRIDaytGeShcEQsELwG1LQhO8r_i1rxTZYon4Tw,17559 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/mhlo/IR/hlo_ops_common.h,sha256=opLmnNUo3gj-HJURlD6-GHp99hmoVfd4uCu17Q9bUR8,2397 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/mhlo/IR/hlo_ops_enums.h.inc,sha256=Pns8uVUaoJk7gNcUNQl1h1asPegKYYLKsSHDTIF_zbI,32552 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/mhlo/IR/hlo_ops_typedefs.h.inc,sha256=O8PdrgZVygmyLSdrubgbCTU53ECFzZCk_ha48I1DmKE,2087 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/mhlo/IR/mhlo_bytecode.h,sha256=AN-gc_qRVfgwojxxIzatbZaMGyEW3edrLukcmqf5LSY,1045 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/mhlo/IR/register.h,sha256=JaZgDMHYOwIdyG_rPu3d9Q2LMjWijRMtvz2SCCvXChk,1023 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/mhlo/analysis/shape_component_analysis.h,sha256=89qd11Yemuc4uabwK9mwjwaPZDhATFc1TfvhWFKMmkM,6547 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/mhlo/interfaces/bufferizable_op_interface_impl.h,sha256=X4yb4Dmx_NlmD9hg-O43IhXXYp8OoVvFO7JFum6ZAyo,1198 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/mhlo/transforms/map_chlo_to_hlo_op.h,sha256=HImDyyHIJbe068-4PmVYPjeI3t0UKbXj3wekLkocH10,5422 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/mhlo/transforms/map_mhlo_to_scalar_op.h,sha256=j5TkgmWrhVVI43sZk1p9fKIY9Pk-rA5zjzeMMxp_YkE,58969 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/mhlo/transforms/map_stablehlo_to_hlo_op.h,sha256=4qe_RcbGe5Yz3m0ZqY34obnkDQGA7arbEUEawEj4rqk,5686 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/mhlo/transforms/mhlo_passes.h.inc,sha256=wk1VgzmfuPQFFfbWMkP3IgV2EDkOK5FVsdIVxy13iB0,264559 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/mhlo/transforms/passes.h,sha256=IvOAuySp_AQnHvfKMhxumXPFkBF4WqfQf8OKDFbDRSQ,8261 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/mhlo/transforms/rewriters.h,sha256=wTzkKPOJY14JvNDrW4bCvehtX8MAp8BVhFPSaqp7gUc,10921 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/mhlo/utils/legalize_to_linalg_utils.h,sha256=mz0wZGt0sY0TN0Yx7upBPJY3wb6bMQcnn25xKNYsjkw,7231 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/mhlo/utils/mhlo_rng_utils.h,sha256=h7E2cR2tQBXEFkBYQypX0tds6ba7OCFK5cyX1tXcUBE,1335 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/mhlo/utils/mhlo_scatter_gather_utils.h,sha256=603iAPxWZs4Y5iGW9coxW8cuvzwF4BiImL3_CTBZXV0,2932 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/mhlo/utils/type_conversion.h,sha256=zd2RcsfZcD0Ou9pcqkbUEeZ_aMcqWXugx0jItj3kZTk,3699 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/thlo/IR/thlo_dialect.h.inc,sha256=At440BSiEiXlJHTdn7j5PJ3EVbSkgbJaCaa4GA-TwMA,1087 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/thlo/IR/thlo_ops.h,sha256=BBHaGEjX3YTxHa-DUHO8XARnqaNOFGZknTECBVTf-NI,1359 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/thlo/IR/thlo_ops.h.inc,sha256=5cpHCWjZJr_hOKtRJCe3gIPoksOX4cU8jLM5Stb2jAA,49395 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/thlo/interfaces/bufferizable_op_interface_impl.h,sha256=z937tWCLFKON5GmPmx3frwdpgpoYoQz9PXY-tDd51dQ,1054 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/thlo/transforms/passes.h,sha256=0AH2wIhki34dvhq_Pdm1EtE0ktFa8HE9wVD2bHC1ehQ,1303 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/thlo/transforms/thlo_passes.h.inc,sha256=YoSzfaATxGCmIYICxIsdnGJyzh23OLfZKTXh3_s1OAs,5691 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/transforms/gpu_passes.h,sha256=uq3AvgzBVlc-aTgKXGtvf9FbImDpITOcbMFXFM_a6TI,1680 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/transforms/gpu_passes.h.inc,sha256=E1SAY94wfPMZAMrH3HS0u62HCL181vmNPtX8HNsP3Go,10552 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/transforms/passes.h,sha256=H4pevJJdIMIBCeC-itVnjB9dVi-AY4ZQ5xmMNI4K60U,4807 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/transforms/passes.h.inc,sha256=wa2RGQWrDxcbxj2lcqAzJQEOCQpVEfvT4CWnTsOBYzc,82230 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/transforms/rewriters.h,sha256=U577QT6BIqFg6mmrviQUjiU5Vck7mGhv1UZSYA03xSE,1451 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/utils/convert_op_folder.h,sha256=tEMneDUBuNY42Bt6D1-b9PfP6Jm0EzIvLID4vR7Jlmk,1241 +tensorflow/include/tensorflow/compiler/xla/mlir_hlo/utils/hlo_utils.h,sha256=dRAH2dJxhChE_AduscFOPNiZKrkHtJpzcAKOByfh-Tc,5601 +tensorflow/include/tensorflow/compiler/xla/overflow_util.h,sha256=NQpyKypPOwyMfEfBUaRYN8mWnvI-fnwX8WNJx-JOLEE,2656 +tensorflow/include/tensorflow/compiler/xla/parse_flags_from_env.h,sha256=76U0X2oWzdFGAoMU3iGufiUDJDmZGbNK8JB-I1irQ6o,2867 +tensorflow/include/tensorflow/compiler/xla/permutation_util.h,sha256=e_ZS7ioRWA7wWhvTJLmhbrVROW6d1qatpLnr4h1DoSs,3038 +tensorflow/include/tensorflow/compiler/xla/pjrt/abstract_tfrt_cpu_buffer.h,sha256=NsbsK_ZKpTkAVR2IZoO2muabevJfKmupU-MUYEA4INY,17207 +tensorflow/include/tensorflow/compiler/xla/pjrt/c/pjrt_c_api.h,sha256=htH-hRfGYqedhmLkLX2LYObKa0_6yBJU5GHHI4cKK4c,79652 +tensorflow/include/tensorflow/compiler/xla/pjrt/c/pjrt_c_api_helpers.h,sha256=4YmoL03p7HNUNPvN8YiTfY4qa46aJBKaJf3mHzIqru0,10430 +tensorflow/include/tensorflow/compiler/xla/pjrt/compile_options.pb.h,sha256=pwN6w_XxalOm7qxuYlKT1QkrxdMZpK8nNfkj3fxwJ0s,97544 +tensorflow/include/tensorflow/compiler/xla/pjrt/distributed/client.h,sha256=TSynNXsKlmAsHqr_1Iy0ak_gqGHeIuINVVvG_g9dWzw,6423 +tensorflow/include/tensorflow/compiler/xla/pjrt/distributed/protocol.grpc.pb.h,sha256=1sOnkJSjwzYEyYEHWq5TLUAennIeNbbpI3uyfF_9hzk,104194 +tensorflow/include/tensorflow/compiler/xla/pjrt/distributed/protocol.h,sha256=sx5VTArlgqQ5bW9Lq0u6M1KRxdhc2f3jCnG8OQjb13c,907 +tensorflow/include/tensorflow/compiler/xla/pjrt/distributed/protocol.pb.h,sha256=C1fGJHc0FLMWgJdeUxWWggABaXtiV1QacWDcLcMoygk,143732 +tensorflow/include/tensorflow/compiler/xla/pjrt/distributed/protocol_mock.grpc.pb.h,sha256=Kn1mVS06-BWEfXB2s1mefzSKekOa5d019PWSxeIHm64,4659 +tensorflow/include/tensorflow/compiler/xla/pjrt/distributed/topology_util.h,sha256=I0YnBJpGW2HG7Fk1OJ9CVWHHeMZPpbuLMmXwWDMcPdk,1133 +tensorflow/include/tensorflow/compiler/xla/pjrt/distributed/util.h,sha256=kRjZgjd5jhjjV-UO9eokjvc3eGbkNx8YVr7QdUK07vA,1340 +tensorflow/include/tensorflow/compiler/xla/pjrt/event_pool.h,sha256=wosudImKJlo5QpOiKutwfHsPrH1MVK4pm9VtrzR7iME,3562 +tensorflow/include/tensorflow/compiler/xla/pjrt/execute_options.pb.h,sha256=bdwCBdz0QBguArA2ITTzC-dOBCTlgh7BdBZt05WhKIM,20087 +tensorflow/include/tensorflow/compiler/xla/pjrt/gpu/gpu_helpers.h,sha256=vrZKFNKgUahUWf10Tx0LZlv4nrgZEUv5Iwrmvb6yinU,2597 +tensorflow/include/tensorflow/compiler/xla/pjrt/gpu/gpu_topology.h,sha256=LhpDsu4nM6D9tB9GUI305w047k_5gf7MQfaXQPp1FxE,1353 +tensorflow/include/tensorflow/compiler/xla/pjrt/gpu/gpu_topology.pb.h,sha256=EAjNdO6bW0oymIHMGgG20KP45GJ_dvvm6I61N_BeksI,10392 +tensorflow/include/tensorflow/compiler/xla/pjrt/gpu/nccl_id_store.h,sha256=UEv4HLZIjoAClfr2EO-Vjs1IwJbL1uNJ78LmwXqwC6c,2153 +tensorflow/include/tensorflow/compiler/xla/pjrt/gpu/se_gpu_pjrt_client.h,sha256=uPfl2vSHm1dumPVz16Egd5KAYNfWsa2oOrK5b8b_JyE,9180 +tensorflow/include/tensorflow/compiler/xla/pjrt/local_device_state.h,sha256=n5tfMSJ5unrhsTxqall9QJOPzMYrKXQOxg3FcW0_ORo,10177 +tensorflow/include/tensorflow/compiler/xla/pjrt/lru_cache.h,sha256=LMrTUR9Cxfzm7AZ9V0V6Rn1CLGDv2TyXLKzWnB4TcVE,5700 +tensorflow/include/tensorflow/compiler/xla/pjrt/metrics.h,sha256=VWuPiaZrEdkHLwU0Z8IBIev2x9BHkvw3jryVOcfW67M,1669 +tensorflow/include/tensorflow/compiler/xla/pjrt/mlir_to_hlo.h,sha256=QFzIxM1isGGPKXsL-aunFxTNHZb-R71XKwXIntw5YLA,1685 +tensorflow/include/tensorflow/compiler/xla/pjrt/pjrt_api.h,sha256=uX65G6G9lEamnpCitklqh53K5ZMoisexhtN7nyIyQQg,1949 +tensorflow/include/tensorflow/compiler/xla/pjrt/pjrt_c_api_client.h,sha256=SOG7jZsv4t8Qi2pAinJj4Jed1lIZWANiE1Tltjk_OHo,26711 +tensorflow/include/tensorflow/compiler/xla/pjrt/pjrt_client.h,sha256=Z0tIcyUmg22qs6ZJI0rY9ymA5GgrXHYPuT2Xuhh5mEQ,68613 +tensorflow/include/tensorflow/compiler/xla/pjrt/pjrt_common.h,sha256=jR1Biu8iCKe4OyG9fZ4ApqvBg-5T5-sP-4sf1MPvkDc,981 +tensorflow/include/tensorflow/compiler/xla/pjrt/pjrt_compiler.h,sha256=FSctWb7kRdHmJOY8TaCrEvlQ8Ot_1gSjazQvyMVfnvQ,6647 +tensorflow/include/tensorflow/compiler/xla/pjrt/pjrt_device_description.h,sha256=y9cxVNBrV--rchT6EaekF5yodh-Tp2C_oT1JOUwd8QI,2690 +tensorflow/include/tensorflow/compiler/xla/pjrt/pjrt_executable.h,sha256=hbQm0V59V-ns6ixnh4WnNx-zlnBfxUQb4vqjlw4DmW4,14732 +tensorflow/include/tensorflow/compiler/xla/pjrt/pjrt_future.h,sha256=M4pw4xJO6oBqZ_ftzbO89RLjwESkVu_7LzPL6Mvv4Ak,10492 +tensorflow/include/tensorflow/compiler/xla/pjrt/pjrt_stream_executor_client.h,sha256=RTaGVcnI87VgE2SViGDfuVHpWpGLUe7pVcjYAyF6JhY,40546 +tensorflow/include/tensorflow/compiler/xla/pjrt/semaphore.h,sha256=dt7VSFe-yJxr5HbvIvJPuA3cpfm_OqiEl7e59WpCaIY,2075 +tensorflow/include/tensorflow/compiler/xla/pjrt/stream_executor_executable.h,sha256=dreBXJFPVH_m5KK_HMvzQKrSkC9SBdaNlGHT4CjYcJc,2812 +tensorflow/include/tensorflow/compiler/xla/pjrt/stream_executor_executable.pb.h,sha256=WaoxBWEIEZLQeMzJVHMGyqUyfBwP5F9VEhAmZ4Nbj8k,22604 +tensorflow/include/tensorflow/compiler/xla/pjrt/tf_pjrt_client.h,sha256=KVyuEMqV9IJ0RLtCxD5TIhfc8bMGo8L5oPyNZ9ZZDEw,14910 +tensorflow/include/tensorflow/compiler/xla/pjrt/tfrt_cpu_pjrt_client.h,sha256=letxnVtel6154DUCiR1khI_duHRAdrYA22ZKfvFdGhE,19352 +tensorflow/include/tensorflow/compiler/xla/pjrt/tracked_device_buffer.h,sha256=XtLMfgTqxZlnwJyheAsmLc1kTEUPlwEjospgJUicdgE,13955 +tensorflow/include/tensorflow/compiler/xla/pjrt/tracked_tfrt_cpu_device_buffer.h,sha256=8WJMolQ7TKD-mTIuwMb4K_0NXv1H2ztFpYdaoIkCcTw,5749 +tensorflow/include/tensorflow/compiler/xla/pjrt/transpose.h,sha256=yk7XQjRBm6S-L8BD0_0qZVyO8wS9yevodvpBSdjw-NY,11356 +tensorflow/include/tensorflow/compiler/xla/pjrt/transpose_kernels.h,sha256=5cNc-iMMlx_l3hBEjFOKtjepLExXAKbEIUzFXImRoHo,30887 +tensorflow/include/tensorflow/compiler/xla/pjrt/utils.h,sha256=ftuc1HwwQkj1k8EkB9AR7CIiRxO_zNf35C_eIsiAfPs,3727 +tensorflow/include/tensorflow/compiler/xla/pjrt/worker_thread.h,sha256=ilwIdfooWpqplLQmKk9SmDc81pxuWXw4jJ9JzxXWtjI,1624 +tensorflow/include/tensorflow/compiler/xla/primitive_util.h,sha256=L2G1ThKdmC0geYADtinD54tHZjer2NE4NGo4FVJVNGk,22014 +tensorflow/include/tensorflow/compiler/xla/printer.h,sha256=mZpJK2At5IrKgol92qCvv398HBxzM9qCpEPy7aQE62s,3846 +tensorflow/include/tensorflow/compiler/xla/protobuf_util.h,sha256=2U4AzJvSA4t93yIkpc4V2pTsNO2mdICKtlDlgidI2UA,2811 +tensorflow/include/tensorflow/compiler/xla/python/refine_polymorphic_shapes.h,sha256=LGo6NP2HeUFQd5BfJ3UB-LAlnt513iWPFmUmmr_bP8w,2067 +tensorflow/include/tensorflow/compiler/xla/refcounting_hash_map.h,sha256=T9-rRDXPlcKJduJDt4b3wf_HcVcj_RBGuiKhpryBVno,3677 +tensorflow/include/tensorflow/compiler/xla/runtime/aot_ffi_execution_context.h,sha256=X5WqZzw2iyXsW1T7uErjfaDmC0JCWmOdGFKmVCNKZ3I,1472 +tensorflow/include/tensorflow/compiler/xla/runtime/arguments.h,sha256=NQ6OcUwnVcVged2ozZa1w2yhn7hMH2cAHenogOZqOvA,16158 +tensorflow/include/tensorflow/compiler/xla/runtime/async_runtime.h,sha256=fZYKQ_JpuuTllk-nK-i5vs5khS-swnuN3t_smrHH9nE,10334 +tensorflow/include/tensorflow/compiler/xla/runtime/async_values_cache.h,sha256=zMS_-xDRbWayp5C9im-3J7DGIfV-y1Ag9c9ukn-1758,982 +tensorflow/include/tensorflow/compiler/xla/runtime/compiler.h,sha256=S-qYOlFxz1lR15SZPdpRhBklxL4VG_jKErP-LVqVUBw,1103 +tensorflow/include/tensorflow/compiler/xla/runtime/constraints.h,sha256=3wl3MbrVjLS2GPwtJP8ddfM9YZNLQRInIsP3r_MKnVg,6295 +tensorflow/include/tensorflow/compiler/xla/runtime/cpu_event.h,sha256=JTDAk1q2NcjVQFjRH5kZKB0khc2v70P1itnHYj4A4vM,1046 +tensorflow/include/tensorflow/compiler/xla/runtime/custom_call.h,sha256=McJsVRajXIVukhyjAbP02C3QhYzXU71kTCOpw3gIspM,75530 +tensorflow/include/tensorflow/compiler/xla/runtime/custom_call_registry.h,sha256=Na_wimK_Rf_6kOeLSGFF0h5kAoVkjiHSf6RpZ5TTLcU,2814 +tensorflow/include/tensorflow/compiler/xla/runtime/default/async_values_cache.h,sha256=HMSw31Z8_xM-K5VP9yKTNhkXss5z9qG8K5FqL_7KGJA,3976 +tensorflow/include/tensorflow/compiler/xla/runtime/default/memory_mapper.h,sha256=wt4DkPJrPMcT14Ea6Gi1I4iCsMFAV_Vc_3ZA-SIgKtM,1253 +tensorflow/include/tensorflow/compiler/xla/runtime/diagnostics.h,sha256=6NbGxHSOjEfnz5uk8Um59wQsvAH0iIs5yNyGX0VqDqA,5980 +tensorflow/include/tensorflow/compiler/xla/runtime/errors.h,sha256=7LrK5G1sjgm8ltzLVatEHp3yN4q0abKuvExsI0iFRDs,1372 +tensorflow/include/tensorflow/compiler/xla/runtime/executable.h,sha256=iOyvTix8M41-cmbIlkOp2s899Hj_2TbOj84zYJK4yDs,18878 +tensorflow/include/tensorflow/compiler/xla/runtime/execution_engine.h,sha256=9kUMn9M0LJLShlo0wQ8Txggr79-K65f9adysBS3MfHE,7584 +tensorflow/include/tensorflow/compiler/xla/runtime/ffi.h,sha256=wkTppuXFlIASvHAc2SiY1Y6X69LhjznaYlOvXLUAh0A,3419 +tensorflow/include/tensorflow/compiler/xla/runtime/ffi/ffi_abi.h,sha256=HcgRQlOiaguQHI9Xy5sqpBN0QueF9kTfOGUt_RiNCBY,1991 +tensorflow/include/tensorflow/compiler/xla/runtime/ffi/ffi_api.h,sha256=5u0iAI4rJ7K7OEEud_LyITLGIcjW_449DKY6CXJXT1o,44917 +tensorflow/include/tensorflow/compiler/xla/runtime/ffi/ffi_c_api.h,sha256=YdyIJQ6YAZ7P7TNsQu1OIq4tTGSUmTZy-1SMEf-s9hg,9863 +tensorflow/include/tensorflow/compiler/xla/runtime/jit_executable.h,sha256=qLsaiD7NKTQLzj6OPRUjY5u-DLliH8nNIIZ1QF06_Yg,10749 +tensorflow/include/tensorflow/compiler/xla/runtime/logical_result.h,sha256=jtxDXUxmfCL17Mezy9tHQyxdy6KTjHoktVc3yj931_o,1157 +tensorflow/include/tensorflow/compiler/xla/runtime/map_by_type.h,sha256=It1JeulnNt_HHB9arZ3iM80bLbu-15GsX-U0lAGR8Uw,3015 +tensorflow/include/tensorflow/compiler/xla/runtime/memory_mapper.h,sha256=y1OiUhgoNi82J3-DfxvGCxiogrGqEPGLRiyjZgzUiHI,2211 +tensorflow/include/tensorflow/compiler/xla/runtime/memref_view.h,sha256=S5kXQ27dkSMx25BX7jxDsUItAFw7YV_C5dCaQw487lM,1750 +tensorflow/include/tensorflow/compiler/xla/runtime/module.h,sha256=6zCEouckn3aFewf5j3fknGlY6xDpyuFM4oa4JxglU_Q,6500 +tensorflow/include/tensorflow/compiler/xla/runtime/module_registry.h,sha256=eK3_AMRCMdtNzRgJ1g_Y6JqM8n3QW9xDAjRx5jL5ny0,2587 +tensorflow/include/tensorflow/compiler/xla/runtime/results.h,sha256=v42xBDLnbUjWbAeaFTdR2-0Iq3FMT0ip7mFlFFebKq4,7525 +tensorflow/include/tensorflow/compiler/xla/runtime/runtime.h,sha256=F-TWPa8UFLtRw3xeKP98w-rrArAo0IM4y9CcSuA0gas,2727 +tensorflow/include/tensorflow/compiler/xla/runtime/state.h,sha256=qgYzKBoIroLdu-9ENwiaIdZzvKGKhDWKOJUP11bceeo,7200 +tensorflow/include/tensorflow/compiler/xla/runtime/symbolic_shape.h,sha256=FqPuzUxC1b84CejYIZJEMrP5efusCxe82SerHW9Rl2Y,4901 +tensorflow/include/tensorflow/compiler/xla/runtime/tracing.h,sha256=k4hbI340r4MukagdDwNLmJL1J3vYzM7d1VwktC5qzTg,1407 +tensorflow/include/tensorflow/compiler/xla/runtime/type_id.h,sha256=QY1YbSsl00inZTFmrWDolSnwhD-zv7F81tNAA1ropfc,6337 +tensorflow/include/tensorflow/compiler/xla/runtime/types.h,sha256=wVAAYqzkbrop24Km9-iFtpsUYwbzXa1M7IoqjTpWQ-4,11767 +tensorflow/include/tensorflow/compiler/xla/service/algebraic_simplifier.h,sha256=VQvJgTrVjrAtg50bYItIbkTAnqzF8Xa7c6z1LJUTNRI,24640 +tensorflow/include/tensorflow/compiler/xla/service/all_gather_broadcast_reorder.h,sha256=yx622Z3WlRb7Wu8dPhaEbxtYQ9m_5XL6FJgz4l36q-A,1527 +tensorflow/include/tensorflow/compiler/xla/service/all_gather_combiner.h,sha256=Ouun8kJzQAZuPV-2qXcQnaJNbQCxYAy-O_6vT8YAa28,1985 +tensorflow/include/tensorflow/compiler/xla/service/all_gather_decomposer.h,sha256=daRuCZj_h-A0lQO3pYvlq7asy_-hhRLDLLyCv4H_MWo,1871 +tensorflow/include/tensorflow/compiler/xla/service/all_reduce_combiner.h,sha256=CIwtq8YyK-F3yGr2ZKC2lfGXJi5lbAkTsq7k7Gbu5yk,1904 +tensorflow/include/tensorflow/compiler/xla/service/all_reduce_contiguous.h,sha256=NqEkcGkkBsq1MmJKvdpqxPg5hEGxAh77BNqF06uFiGQ,1369 +tensorflow/include/tensorflow/compiler/xla/service/all_reduce_folder.h,sha256=IOa6gF3BHUMGtlnbxbP8SyrlBbJGuoAkzmEz1ZfgOrQ,1616 +tensorflow/include/tensorflow/compiler/xla/service/all_reduce_key.h,sha256=icor8TbEtLpJuRGQqKouBdsxuipY2H6nt3URNH1OTi4,1557 +tensorflow/include/tensorflow/compiler/xla/service/all_reduce_promotion.h,sha256=hQXwNpyCe-0Fb7L_Wr5pwSSpoGHttlo6rHrnro1K2Ys,1356 +tensorflow/include/tensorflow/compiler/xla/service/all_reduce_reassociate.h,sha256=eyf_gVV8xOHFG8KbofkRauPMrUIbWhULqTBDOISzHcg,1898 +tensorflow/include/tensorflow/compiler/xla/service/all_to_all_decomposer.h,sha256=2tc_SVqpNbj5T-nU62GM21u-TPN5nPIdgzEnDk1PtYw,1763 +tensorflow/include/tensorflow/compiler/xla/service/allocation_tracker.h,sha256=V28LdkeXr-TENz3kYYnKao9DkfDrZgcO7j_0a5Sk3ek,6696 +tensorflow/include/tensorflow/compiler/xla/service/async_collective_creator.h,sha256=IY_JsNQyZWJfsHaqpcUOBdzjtDs76WoFZ6-UAjskIsM,2181 +tensorflow/include/tensorflow/compiler/xla/service/backend.h,sha256=jFi4CnvXCYKuLRcqdyqzPxm0w_Nspillwr7XbnNc3qc,8103 +tensorflow/include/tensorflow/compiler/xla/service/batch_dot_simplification.h,sha256=QZwpRLdDlBM0hXP5YubVPZA5YRqPgYqgjBuCn5WPX6o,1529 +tensorflow/include/tensorflow/compiler/xla/service/batchnorm_expander.h,sha256=_y-kbP4UlEDotBToeJpfaxPVHNrY34pr2y6KxRBHlQA,2045 +tensorflow/include/tensorflow/compiler/xla/service/bitcast_dtypes_expander.h,sha256=mjEf3CJJDSjkYam38s3170rlkmZt77wWqI7y1OlWFBw,1542 +tensorflow/include/tensorflow/compiler/xla/service/broadcast_canonicalizer.h,sha256=_NjTUg6CcXPTCsOgni8p74TKGK984hmbCaoOQOVBHjY,1348 +tensorflow/include/tensorflow/compiler/xla/service/buffer_assignment.h,sha256=_nVViS928QNpUeXA5P_dCYB8186HLP4nV9xM7Ui8aqA,33455 +tensorflow/include/tensorflow/compiler/xla/service/buffer_assignment.pb.h,sha256=8U863E5zR3wf8NVZOlLfo4TAsDmBPOqLfaEEDOzJ65Q,16036 +tensorflow/include/tensorflow/compiler/xla/service/buffer_value.h,sha256=C60n9CiEbfawkFfxfj_ViHLTXf5UvcYqRRZ_mYTa2_k,7652 +tensorflow/include/tensorflow/compiler/xla/service/buffer_value_containers.h,sha256=frPA2QTV1l5CYIcMdFbRJHqjEL1klFwECu0FMs_lIA0,1972 +tensorflow/include/tensorflow/compiler/xla/service/call_graph.h,sha256=P3uXiMRyZj9Lu-l6cd0WXns6rOcMnL-VVPk5vEYjU4I,15358 +tensorflow/include/tensorflow/compiler/xla/service/call_inliner.h,sha256=FqZCoWJK2dBhsJfj8msLMJbXw7ZKKkqr6xnrALCtWG4,2118 +tensorflow/include/tensorflow/compiler/xla/service/change_op_data_type.h,sha256=MNGVSLb0xRYU5NiyBhp6twrKNayEcozWVCzVoAAy84o,3181 +tensorflow/include/tensorflow/compiler/xla/service/channel_tracker.h,sha256=lVBk4fy-6KneojZafsio20CzrNu6fWSFlyohWeLg6zo,1710 +tensorflow/include/tensorflow/compiler/xla/service/cholesky_expander.h,sha256=rwujPR4IsdoS3YRmWLyo4Of0zL62_wXL1Yt7HyP82n8,1642 +tensorflow/include/tensorflow/compiler/xla/service/collective_combiner_utils.h,sha256=wL-td4d8aAFbSS9HLjGDGZD8EjWR-DN1vXkknE-sJ6I,5395 +tensorflow/include/tensorflow/compiler/xla/service/collective_decomposer_utils.h,sha256=hNEUD9uBOQ8i7Rvj-usFNtAegBzAyBgKpJnaTDDqqIo,1294 +tensorflow/include/tensorflow/compiler/xla/service/collective_ops_utils.h,sha256=w37ZHMdDArRGRjRmTREeWMvsF5pvyDuuwpoGBZ9mGH4,17411 +tensorflow/include/tensorflow/compiler/xla/service/collective_opt_utils.h,sha256=WF1pEOOS_3KfM-r9vYS22oK0jQ5YsDcPRN6mtrB9jwo,2826 +tensorflow/include/tensorflow/compiler/xla/service/collective_permute_decomposer.h,sha256=g1cyBeJx9G-1Y7Fb1K3XyvjzuttkXPkSxmxAfCkYlUM,2687 +tensorflow/include/tensorflow/compiler/xla/service/collective_pipeliner.h,sha256=i9r-oRtNcHiH4McevMl28wZ46NqpnQMLm8V4W3rbObU,3874 +tensorflow/include/tensorflow/compiler/xla/service/collectives_schedule_linearizer.h,sha256=n6_4-p_nqKCvnYijqZP0rx88XVxXQYRB3ACtHWRqGyw,1754 +tensorflow/include/tensorflow/compiler/xla/service/comparison_expander.h,sha256=XMMOPla2dYNxk0gb6Z6Ke077DYH7CABiE-uDQdTfWKI,1749 +tensorflow/include/tensorflow/compiler/xla/service/compilation_cache.h,sha256=PGIZ1_cayl6X9lkONWycJEANcPABnWaCghl3q5bPaEk,1871 +tensorflow/include/tensorflow/compiler/xla/service/compilation_environments.h,sha256=d8R9BfyoDArq4LKa0VwCiWlbUSBOAV7laOv_eextQzg,5870 +tensorflow/include/tensorflow/compiler/xla/service/compilation_stats.h,sha256=ON1BFhAzuKaT5FDc9e_dTRV8v4ZuLZ_T1WcROZHj6-A,1852 +tensorflow/include/tensorflow/compiler/xla/service/compile_only_service.h,sha256=JaFQ-TXd5HFWtW_yKYHWptVGHhxbemkV4KitEKx92LU,4160 +tensorflow/include/tensorflow/compiler/xla/service/compile_time_cap.h,sha256=h8tGbSaWzkBhqk3t91hgCG68_8_k2hR2PZDOHVAiZmY,2622 +tensorflow/include/tensorflow/compiler/xla/service/compiler.h,sha256=d3IrKmRCoiu128bRGiMoJJocGzetfkeXjpvpbqOV1Jw,17566 +tensorflow/include/tensorflow/compiler/xla/service/computation_layout.h,sha256=zcAgsZV4Dxlr603xfdj5IkpSOTYTUdBxLcarLLGXoto,4152 +tensorflow/include/tensorflow/compiler/xla/service/computation_placer.h,sha256=QqgAy4TBbgOUHAkR7oNZLC6_pVPEsbS4NcEhJF8Oh1c,5109 +tensorflow/include/tensorflow/compiler/xla/service/conditional_canonicalizer.h,sha256=eSF1wKOU-6ya9AxkUeLnldO821nRyclbIX-mCyvsRhA,1448 +tensorflow/include/tensorflow/compiler/xla/service/conditional_simplifier.h,sha256=psv8NmK7B7mQqO98j-gu9afGg23_WbGHrtiEDzVi3kc,1511 +tensorflow/include/tensorflow/compiler/xla/service/conditional_to_select.h,sha256=GUJUXUJF6AxCWW9UGarmfTnZ_aqLjQScnxJ4sZQCQ3o,1538 +tensorflow/include/tensorflow/compiler/xla/service/constant_value.h,sha256=5kc3qyJ1z0Fdhveuz5Bf_Q_GbvqepiXviWUveoQrZBA,3421 +tensorflow/include/tensorflow/compiler/xla/service/convert_async_collectives_to_sync.h,sha256=RR6HhXVTz3Ou8sXuSEebnICDOliR_f1S9Vr37BrRHSw,2352 +tensorflow/include/tensorflow/compiler/xla/service/convert_mover.h,sha256=tzuhCkW8TsF_TKmgLxpLCu-OPO1ap2T7XbHWBUmjYCM,1802 +tensorflow/include/tensorflow/compiler/xla/service/convolution_4d_expander.h,sha256=8S-Ea0x90_i_LD-RQVd4Sy1a8lATVwCwin8XvT_ARj0,1325 +tensorflow/include/tensorflow/compiler/xla/service/convolution_group_converter.h,sha256=0JtJFz_q8JIp1rtQBqNojQyaomljrgxeX5H2DVxOpYQ,2520 +tensorflow/include/tensorflow/compiler/xla/service/convolution_pred_expander.h,sha256=NMiHbvS8OYLRS6osrpgltuerWsotsmR9aB-vGjsU0T8,1580 +tensorflow/include/tensorflow/compiler/xla/service/copy_insertion.h,sha256=2NndyLMEHsHAnlePgBFP0ampZlOso0u3cdFsrESOCHA,5032 +tensorflow/include/tensorflow/compiler/xla/service/cpu/backend_config.pb.h,sha256=4FnTUpSNV4651nZk1i_EDSFB-5ONyRwSaV6fyeIomcg,28156 +tensorflow/include/tensorflow/compiler/xla/service/cpu/buffer_desc.h,sha256=x8D_3SE0mkE-4xcYjDLEFMpdcCyS8Ax7u_fbW7p9M7c,1179 +tensorflow/include/tensorflow/compiler/xla/service/cpu/buffer_info_util.h,sha256=Pn35OtcRVFJxG1YsoFkm9ePyvEIzr79TQ_-QY3leKD8,1771 +tensorflow/include/tensorflow/compiler/xla/service/cpu/compiler_functor.h,sha256=50Gq-VzgtxiPxRV-2zq7oI-uz-3blEGD4FXlbymmpWA,3476 +tensorflow/include/tensorflow/compiler/xla/service/cpu/conv_canonicalization.h,sha256=R7geooDgR-aMmW0zh57QTalf5T_qma31rG9cvLP7iOA,2058 +tensorflow/include/tensorflow/compiler/xla/service/cpu/cpu_compiler.h,sha256=1ykFmW8DZXVq3ONf2D3h9FXoqRxNnIkKj9wUqt67zg8,9560 +tensorflow/include/tensorflow/compiler/xla/service/cpu/cpu_executable.h,sha256=cw5h7b0OROBOO-kZr5d1dlrV68std-q-4c0HsC-vjx8,11639 +tensorflow/include/tensorflow/compiler/xla/service/cpu/cpu_instruction_fusion.h,sha256=laPndjDSfwpKumGkqErtNe4WTTW0vhJu4Tfi9WOOi8w,2215 +tensorflow/include/tensorflow/compiler/xla/service/cpu/cpu_layout_assignment.h,sha256=aQ_YFxAU82qlvDurjsc-cqeqMxYb1Rq0M4tAxaovzkQ,1798 +tensorflow/include/tensorflow/compiler/xla/service/cpu/cpu_options.h,sha256=oYUmmVzbtahQSB7gQiW5av0Pez-nBh0IM6lbJYxviD4,1475 +tensorflow/include/tensorflow/compiler/xla/service/cpu/cpu_runtime.h,sha256=rSJol3p6sklrCo4J0miZhAcXSLR_g65rnnK54s4P1HA,10294 +tensorflow/include/tensorflow/compiler/xla/service/cpu/cpu_transfer_manager.h,sha256=WV3rVq1fZavEqvlLPeazEoSGdxu4x447Ft1DKlSNV7s,2335 +tensorflow/include/tensorflow/compiler/xla/service/cpu/cpu_xfeed.h,sha256=MLd5YhKy_svfIpCRrmvjCMpTBqcau1ksuxAIX-qAkiY,1773 +tensorflow/include/tensorflow/compiler/xla/service/cpu/dot_op_emitter.h,sha256=CEui5wsj6ux3fGdh-l1Kg6uypSPMCzUBxNT-jjXSLfA,3224 +tensorflow/include/tensorflow/compiler/xla/service/cpu/elemental_ir_emitter.h,sha256=VieLmS-4deR2fj5eUQNZUPavgDCQtMbT477nob9bxVI,2315 +tensorflow/include/tensorflow/compiler/xla/service/cpu/executable.pb.h,sha256=LCWaomK2HB-94Kb3WtnSOKoO2kj-vPRNxieKGAXu7bI,20108 +tensorflow/include/tensorflow/compiler/xla/service/cpu/hlo_xla_runtime_pipeline.h,sha256=GfUP-r4_a8tQYdxT_fO93Id8NkQ2VrRyuDfKYBt4WK4,1997 +tensorflow/include/tensorflow/compiler/xla/service/cpu/ir_emission_utils.h,sha256=TNerATsGiI9eiJMqSjUGmeWv7MSeZcexfRSUhv24n24,1995 +tensorflow/include/tensorflow/compiler/xla/service/cpu/ir_emitter.h,sha256=5NF2zrcJJWVL9EsntSzq1uSg8cJDiq0vSHY39tfHya8,30421 +tensorflow/include/tensorflow/compiler/xla/service/cpu/ir_function.h,sha256=bGhcH1i4u2co4-uq7MdH7zieoRU66Mqyaj0qVYEANKo,6434 +tensorflow/include/tensorflow/compiler/xla/service/cpu/llvm_ir_runtime.h,sha256=ks-g3EeR74ZOsNhcUf9uYz9eoarQz9aZZ6KMcfgL57Y,1803 +tensorflow/include/tensorflow/compiler/xla/service/cpu/mlir_emitter.h,sha256=oV6QH60qtqJpqne6virmNkvaf6o2EV1mBeIiOXpDbiM,1798 +tensorflow/include/tensorflow/compiler/xla/service/cpu/onednn_matmul.h,sha256=U3Z6Nnpq2DYcB_fCP0VnkWS_nmDuNE62MdkGwJzbJRc,1594 +tensorflow/include/tensorflow/compiler/xla/service/cpu/onednn_memory_util.h,sha256=NPz5r9lWE7F7hJhMFWAy2zeABBKiWMf1Mf2YFMajA9I,3153 +tensorflow/include/tensorflow/compiler/xla/service/cpu/onednn_rewriter.h,sha256=IDIbcVKem2l6oedpzr7wdH5zXeHx9luRzr-ei2hZB80,1519 +tensorflow/include/tensorflow/compiler/xla/service/cpu/orc_jit_memory_mapper.h,sha256=yaB6OvWqqjAOuUgVqCegO5Zeb6lyz_KY-WCai9J57RI,2234 +tensorflow/include/tensorflow/compiler/xla/service/cpu/parallel_loop_emitter.h,sha256=yPbaS1yQa1m8usrnEjq5qqZQsBGFW4XuO0nyj0nP4zw,3229 +tensorflow/include/tensorflow/compiler/xla/service/cpu/parallel_task_assignment.h,sha256=dNy_CKzJCRdGSEOGpiiMmrr2Z37lZMewC4Z1zZEne68,5066 +tensorflow/include/tensorflow/compiler/xla/service/cpu/runtime/collectives.h,sha256=0mszW7vxi-JhihdKVA2fMMNnpiOo9zrexGTrgvcGFwA,1006 +tensorflow/include/tensorflow/compiler/xla/service/cpu/runtime/convolution.h,sha256=tiyNt63TLM5IV42XZ1TpuULO21F6tBOlkBgg5EPJ4_w,1755 +tensorflow/include/tensorflow/compiler/xla/service/cpu/runtime/convolution_call.h,sha256=MKTlK3LhClYVe2mA2RUO9-npJXkdEctNensnZt1IQSE,1021 +tensorflow/include/tensorflow/compiler/xla/service/cpu/runtime/custom_call.h,sha256=zG_nL86I5uTkPGY1NUE_4KORJ04bDTkpqAUnpcCtNV4,1021 +tensorflow/include/tensorflow/compiler/xla/service/cpu/runtime/fft_call.h,sha256=tsKRgfbopWGLSqDea3y8y8pb23zY46Ne1EVZ3_9sFD8,981 +tensorflow/include/tensorflow/compiler/xla/service/cpu/runtime/rng.h,sha256=lxEtqddFnNfCukyn3pLzi16tB-akneM4c2mGi2SgxKI,1632 +tensorflow/include/tensorflow/compiler/xla/service/cpu/runtime/rng_call.h,sha256=ITGbz8TkW0fx7N76GlEnuM4LeBE116utfHt-TQGzpHU,983 +tensorflow/include/tensorflow/compiler/xla/service/cpu/runtime/xfeed.h,sha256=I8x84EJpb-6KFRBX-EDOxCwZxXukcHfLESZ7U0Zh6jg,987 +tensorflow/include/tensorflow/compiler/xla/service/cpu/runtime_conv2d.h,sha256=Zx2_1HOOdiBVnCHPBf4iUSXoEkNkwgYl3DxVxynxZmU,2248 +tensorflow/include/tensorflow/compiler/xla/service/cpu/runtime_conv2d_acl.h,sha256=O7wEUBBvOvvytHF1vUVc0RN7Mbxv-VoQbxIpo4EEdDQ,3720 +tensorflow/include/tensorflow/compiler/xla/service/cpu/runtime_conv2d_mkl.h,sha256=c2HEmoXwr3v3rY12iWhqx-_1LgeQGWcYtUOT_rFvsck,1481 +tensorflow/include/tensorflow/compiler/xla/service/cpu/runtime_conv3d.h,sha256=1TY7qp0TYjTE5Lpcmnz202DM5fW4EZUzt-9gptJHZ40,2564 +tensorflow/include/tensorflow/compiler/xla/service/cpu/runtime_conv_impl.h,sha256=Nh2X7L7xGkbJaFhe9o1aqfFpWeWli414ClD2imfAzvE,9122 +tensorflow/include/tensorflow/compiler/xla/service/cpu/runtime_custom_call_status.h,sha256=PpuBENyx9bHt2yO57hLErVONJHDjVqG68Gt5ZYixAx8,1097 +tensorflow/include/tensorflow/compiler/xla/service/cpu/runtime_fft.h,sha256=n7MRlmU0Nd6e33Vd4gcER4sQQYlKRdTl1rTxpdpW7MU,1136 +tensorflow/include/tensorflow/compiler/xla/service/cpu/runtime_fft_impl.h,sha256=koXDF52ZoQ56MI0-4Gv0aXhDET4wlDMgjAIpTO5e3JU,11012 +tensorflow/include/tensorflow/compiler/xla/service/cpu/runtime_fork_join.h,sha256=oPxC5-Xmu0UPreF7AjP22Uyv3PmpyT8UEP_qjh9Mzyc,1304 +tensorflow/include/tensorflow/compiler/xla/service/cpu/runtime_fp16.h,sha256=UHckyqethjlYyiHncJeSL028UDYnoLN-_HK4WljCXYE,1812 +tensorflow/include/tensorflow/compiler/xla/service/cpu/runtime_key_value_sort.h,sha256=xMCZUpjet6ZXA3lX8fctJPdkCg1Wk5eSu9HN77mv8r0,2167 +tensorflow/include/tensorflow/compiler/xla/service/cpu/runtime_lightweight_check.h,sha256=AsBJcqgOdj2q_t8tyElb1JMMgQipd8S23ogRaq67Xgo,1672 +tensorflow/include/tensorflow/compiler/xla/service/cpu/runtime_matmul.h,sha256=37hM-Es1u24slbt0Q9GQbmvePx62EZdXkrZfkOAYLcM,2983 +tensorflow/include/tensorflow/compiler/xla/service/cpu/runtime_matmul_acl.h,sha256=dHJHaLZ-Nrjj_oHeFG6QcKWjgQ43ahBLveb94-lJB4I,3110 +tensorflow/include/tensorflow/compiler/xla/service/cpu/runtime_matmul_common.h,sha256=ZjrY0SoBR8xrUk1oXhq5XU6L08KV5EjVs3vO4zHFeyw,5811 +tensorflow/include/tensorflow/compiler/xla/service/cpu/runtime_pow.h,sha256=DLFc43BRpg16kVP6HqWWz_OQZ4eIDbHjM1VCLv0mDsY,994 +tensorflow/include/tensorflow/compiler/xla/service/cpu/runtime_single_threaded_conv2d.h,sha256=3CYIR0CYcpbLq5ONQSiXvjTaorIcBXNJINq6uI7ZuFQ,2324 +tensorflow/include/tensorflow/compiler/xla/service/cpu/runtime_single_threaded_conv3d.h,sha256=JA8tew_Sdw2WDBNpX-8rlmrJAse4vishvVFAJlGRZLA,2640 +tensorflow/include/tensorflow/compiler/xla/service/cpu/runtime_single_threaded_fft.h,sha256=35aWz4RBezlpypKgqSQPy9SNeF9EjFD-vgLxERHCX74,1198 +tensorflow/include/tensorflow/compiler/xla/service/cpu/runtime_single_threaded_matmul.h,sha256=JsV0nByVaaVeHCeawFmuC1Pe2G6AgQdTrk6FwIteEj4,2927 +tensorflow/include/tensorflow/compiler/xla/service/cpu/runtime_single_threaded_matmul_common.h,sha256=affpjnxtyoqmn_pXYIkrj1yFYN48iYM_rHb8BZuyCw0,3357 +tensorflow/include/tensorflow/compiler/xla/service/cpu/runtime_topk.h,sha256=GMh2gbihhyoxa0lCoK-IZoMkWVUtYz86LKOrBsIxa-o,1196 +tensorflow/include/tensorflow/compiler/xla/service/cpu/shape_partition.h,sha256=qMLilGWpc0bTWiDY63zhpyAjuizpeUe7HVHPIF29fb4,3560 +tensorflow/include/tensorflow/compiler/xla/service/cpu/simple_orc_jit.h,sha256=mQFy_U1T9MgCFNVkajD_bSvJ9BYb2xbea5GQLeTO2Qk,5459 +tensorflow/include/tensorflow/compiler/xla/service/cpu/target_machine_features.h,sha256=3zDNgUJOy9g51PwYzsW5Rzy9YE7XC6-RCWjqbTTHBzU,5137 +tensorflow/include/tensorflow/compiler/xla/service/cpu/tiled_dot_emitter.h,sha256=FzDafu0sUZGgQpAXJTeg4m2BmE5OmF65eFKh5_qNoIc,2203 +tensorflow/include/tensorflow/compiler/xla/service/cpu/vector_support_library.h,sha256=fVyEpCvwJv0uXdxej5gdUT98fHJQ-gN9Y-kA1SgJiVM,13351 +tensorflow/include/tensorflow/compiler/xla/service/cpu/windows_compatibility.h,sha256=SXn76-w1RaekcZqAXO6UDBrf2prPkglRPUlkBMNerw4,1010 +tensorflow/include/tensorflow/compiler/xla/service/cpu/xfeed_manager.h,sha256=oPY33uV7ODCk1M3qMM45FNbei9aFSfYcsSnfcrQ_wL4,4585 +tensorflow/include/tensorflow/compiler/xla/service/cpu/xla_framework.h,sha256=ZeSCq9HP-PcxNjtC3uKmh9qlc2kPIPJrf3lU-3s2Xm8,2402 +tensorflow/include/tensorflow/compiler/xla/service/cpu/xla_framework.pb.h,sha256=MA7U3jd-IIBvcQH9FCNvN0tS8PlVT_r2vZfH6_C3Brs,17433 +tensorflow/include/tensorflow/compiler/xla/service/cpu_gpu_shape_verifier.h,sha256=hMDtJkB54T6fvnx8wibVVYYH-YXvPHXCaQEiolpu-XQ,1601 +tensorflow/include/tensorflow/compiler/xla/service/custom_call_sharding_helper.h,sha256=QIYc4uEZFxQv5aeLDkH2Ww1vSwDiJcJbDZ-C5q7aMK0,3187 +tensorflow/include/tensorflow/compiler/xla/service/custom_call_status.h,sha256=7p5TacrLMcKqjsPjJ2-kabAIg3DiMCud8zkf9-v8ync,1670 +tensorflow/include/tensorflow/compiler/xla/service/custom_call_status_internal.h,sha256=ilHcWiQBkZRGYo4SfpSTfac340ct8xIZ-wVdD5ahx_8,1398 +tensorflow/include/tensorflow/compiler/xla/service/custom_call_target_registry.h,sha256=-OnsAml6E55Nx2DkoCCI7LTHfbkhATxzWHbkc9zK0eY,4687 +tensorflow/include/tensorflow/compiler/xla/service/dot_as_convolution_util.h,sha256=1RWSXVg6bRj2FrKfQLAvue9Flul-TUzQAaKWqLPlQl8,4471 +tensorflow/include/tensorflow/compiler/xla/service/dot_decomposer.h,sha256=D1jj8t3hY2XOKnHa9w6CH41rCktw-SKHs6hI3h59ccc,1497 +tensorflow/include/tensorflow/compiler/xla/service/dot_dimension_merger.h,sha256=VMuxZxReokBfmbdrg0vGo9OuE85GCfceMEg2UxtUh_I,1389 +tensorflow/include/tensorflow/compiler/xla/service/dot_merger.h,sha256=yHFIVstgIrYG1qBFRG5zI82b6B0T96n-PFvh0qfEUYA,2514 +tensorflow/include/tensorflow/compiler/xla/service/dump.h,sha256=ReuCSrZbVQliwnopRcQzMZ3e26btAGEBivRbekl3N1w,7169 +tensorflow/include/tensorflow/compiler/xla/service/dynamic_dimension_inference.h,sha256=ZdfJuNvGhDqBfozqqqanZSwPr7UYPhNw0QF9RBldUKI,7318 +tensorflow/include/tensorflow/compiler/xla/service/dynamic_dimension_simplifier.h,sha256=NyE4oBmSaYWQ_f7GCAIfvpk1bFNc7RR3bVs5lmouYIg,1404 +tensorflow/include/tensorflow/compiler/xla/service/dynamic_index_splitter.h,sha256=TweNqpc53Ff6_zgrDK5G3txe6Jo1OWcwgCuklcC60e4,1431 +tensorflow/include/tensorflow/compiler/xla/service/dynamic_padder.h,sha256=17fs2QjxYsg1sIwlB3LzifyDZYg5erKMbe9Sv6HKs-M,3870 +tensorflow/include/tensorflow/compiler/xla/service/dynamic_window_utils.h,sha256=ObpMK9oM_0rWxxQPYNQ1QbL_Wt8TKeSJPLT4GDwku8w,1905 +tensorflow/include/tensorflow/compiler/xla/service/eigh_expander.h,sha256=7_PznKZxDm2dAYH7LLC8ZNnlhggNdNR5qwjW8CBo_mA,1567 +tensorflow/include/tensorflow/compiler/xla/service/elemental_ir_emitter.h,sha256=Mh530GKyKeP009lInvie3o-awM-kZe5kV2oIOZKP5Ow,14176 +tensorflow/include/tensorflow/compiler/xla/service/executable.h,sha256=BlxdHBXsY9mDYoJGBQgm5k0XQrsNtlfPahkOlmrQAB4,16309 +tensorflow/include/tensorflow/compiler/xla/service/execution_tracker.h,sha256=KpkCkknS8-quyvrbQYW8zJjZ4q70CDOle4pQ1GNrGQE,3523 +tensorflow/include/tensorflow/compiler/xla/service/export_hlo.h,sha256=YgOjER6BFWlod1G7vvXvj9jNegVs-Uz51MgDjDu6zSs,2898 +tensorflow/include/tensorflow/compiler/xla/service/flatten_call_graph.h,sha256=Bddt5fOdZPk_ZqkGLLJ4NBuIt05HfjTHEqhzWbgMJzQ,1559 +tensorflow/include/tensorflow/compiler/xla/service/float8_fnuz_ir_emitter.h,sha256=Dvd7_MOvaO67ST8ijPAVtbCZs-CJ69G4x7g9tZyzVvE,2032 +tensorflow/include/tensorflow/compiler/xla/service/float_normalization.h,sha256=Dyw0j6ZS3chxwYKwD4L34QHTFgtcMHRoDl9-_C3Xd7k,3890 +tensorflow/include/tensorflow/compiler/xla/service/float_support.h,sha256=L3Pb9vhGqAdIsVY_ygwPdCPsv5YHRyCfxrpTeHsDjrw,3769 +tensorflow/include/tensorflow/compiler/xla/service/fusion_node_indexing_evaluation.h,sha256=Tt9fKgtS8fGAzVwmz6scBQ5Bg_dvpYTwUO9aE0LiOQY,4626 +tensorflow/include/tensorflow/compiler/xla/service/fusion_queue.h,sha256=iLorPQ8rC0-6EWiOv4-Kn0G1YhFu_JUYJVepCv98Zb8,2375 +tensorflow/include/tensorflow/compiler/xla/service/gather_expander.h,sha256=3BVTlBmioTAEfC5_HJKfMbzMetu18tSIrWiYmcPFXVM,1996 +tensorflow/include/tensorflow/compiler/xla/service/gather_scatter_utils.h,sha256=X9oOjgqHL8eBkC0NPmsnr0v1fKENWh5sYtNTfuvcorE,2330 +tensorflow/include/tensorflow/compiler/xla/service/gather_simplifier.h,sha256=T6TKjbIRdjnu4oHzE5WVbCJgI-Qhn5e2qcJpoQSFz58,1639 +tensorflow/include/tensorflow/compiler/xla/service/generic_transfer_manager.h,sha256=ERdnnJLiQtNn_SmD6BCKF6arEK-gcfR143xcS42IVDA,3107 +tensorflow/include/tensorflow/compiler/xla/service/global_device_id.h,sha256=13nISX5BCxuLd7EOnFvQTeCKU76zH8WLrMDwsERBK48,1410 +tensorflow/include/tensorflow/compiler/xla/service/gpu/alias_passthrough_params.h,sha256=X-AxsSPpC4lTsol0RWxiYl1p9NMz6TEYGa6-JnYmiow,1700 +tensorflow/include/tensorflow/compiler/xla/service/gpu/all_reduce_blueconnect.h,sha256=U4WAWmaS19GWG8OugMGLyxhMVHDAbTTsoHFfRUuTXpI,1892 +tensorflow/include/tensorflow/compiler/xla/service/gpu/analytical_latency_estimator.h,sha256=TagFZhl_fgs0yqjxuowMBg_E0SL8SShzPwJkBZITBME,2260 +tensorflow/include/tensorflow/compiler/xla/service/gpu/autotuner_compile_util.h,sha256=1dJgY2ktYGXw_JDCZG2aOtsKMpmZrIqfUFjW64RAuZ4,4248 +tensorflow/include/tensorflow/compiler/xla/service/gpu/autotuner_util.h,sha256=QjxU-lumGk2cKHy526obXbg2cRAUM4X1mXvFaoxeV_A,10462 +tensorflow/include/tensorflow/compiler/xla/service/gpu/backend_configs.pb.h,sha256=6wNMua1gvHxogNAaPDomQRBFDO3groldynby3wvqC8Q,146867 +tensorflow/include/tensorflow/compiler/xla/service/gpu/buffer_allocations.h,sha256=QORJC0w0fXRf8tyI2zECtRrETo6CzVRo_iccc55I6t0,3715 +tensorflow/include/tensorflow/compiler/xla/service/gpu/buffer_comparator.h,sha256=t1KXn5DtzHJ7ZkKeCbIJyyOd2N3xg3XoHxNxJPDuW3g,1872 +tensorflow/include/tensorflow/compiler/xla/service/gpu/buffer_sharing.h,sha256=w1Uq4eJQc1PhLC5Qih3Ni6utIgmN3AKyHLZpD7kXGcc,1396 +tensorflow/include/tensorflow/compiler/xla/service/gpu/compile_module_to_llvm_ir.h,sha256=oSMPZx7EhcBd8l0OYacGpsFJL9eerGY6Mz6NM0yGpBE,3254 +tensorflow/include/tensorflow/compiler/xla/service/gpu/conditional_thunk.h,sha256=b3ol9yIsnFH21LTicajJGsu3nG8ovAmEcEjaULZFGq8,2687 +tensorflow/include/tensorflow/compiler/xla/service/gpu/conv_algorithm_picker.h,sha256=Q0rEC3_h5H0p5qJvcAJVR3K5vyWygMGS1Pn0S-obdX0,6421 +tensorflow/include/tensorflow/compiler/xla/service/gpu/conv_layout_normalization.h,sha256=SkqwvyGvSlE2jhok-g8KfEP9N8_ipI5yHk3ahJKt2uU,1231 +tensorflow/include/tensorflow/compiler/xla/service/gpu/convolution_thunk.h,sha256=baqy52542KTGS-szusDGq5ydjptU4TGoxQn0ipyQvUc,3527 +tensorflow/include/tensorflow/compiler/xla/service/gpu/copy_fusion.h,sha256=1yViRidON8GIesED94wQih3a-I8REHboyqc20yRZ8hE,1509 +tensorflow/include/tensorflow/compiler/xla/service/gpu/copy_thunk.h,sha256=4Qy6cK_gy1yrsS_sm0YT_yKMW11Gxwg9hSZr2eJDyew,2619 +tensorflow/include/tensorflow/compiler/xla/service/gpu/cublas_cudnn.h,sha256=DBCptVYZOP50tQXtn-uCyEx9hVpYFnSNcUi6NWeyB2A,9198 +tensorflow/include/tensorflow/compiler/xla/service/gpu/cublas_lt_matmul_thunk.h,sha256=lCQfDSorEGXZUp1oM_FCIZYXsN3F8eZ4TUOVjslh2R0,3290 +tensorflow/include/tensorflow/compiler/xla/service/gpu/cublas_pad_for_gemms.h,sha256=TQeU-I5zrsrJJqXNOpYnAfzoKe57vgKYvyrzn1G5E5U,1903 +tensorflow/include/tensorflow/compiler/xla/service/gpu/cublas_padding_requirements.h,sha256=2h-mKZaPaYmQ8cJNVORPe5JeAoamlaart3LbmpfpKC0,1634 +tensorflow/include/tensorflow/compiler/xla/service/gpu/cudnn_fused_conv_rewriter.h,sha256=6P3pQDLbwD1gcXTUfLtHLrYl2GU-2f9b_lWRKU0SACY,4328 +tensorflow/include/tensorflow/compiler/xla/service/gpu/cudnn_fused_mha_rewriter.h,sha256=XdE5s922_4-2LckltmWWS1X-rDJaoTPC9_40AtIoo2I,1923 +tensorflow/include/tensorflow/compiler/xla/service/gpu/cudnn_fused_mha_transpose_fusion.h,sha256=PtrnQHQsXyaMcFIKpnxHfalbK5GD-yg1PhuUbYFYqok,1406 +tensorflow/include/tensorflow/compiler/xla/service/gpu/cudnn_pad_for_convolutions.h,sha256=guvlM87B0WZqGX0pyj-OhmhvXCKia_su9JTrdRzOo_k,1940 +tensorflow/include/tensorflow/compiler/xla/service/gpu/cudnn_simplify_padding.h,sha256=xAZTXdThcwOqyMJ7pLrjSQxT5QjS6Q3XxMgP0owpzbQ,2641 +tensorflow/include/tensorflow/compiler/xla/service/gpu/cudnn_support_utils.h,sha256=W-kYkMEaOET3uSPHZsGvwzvHXQ1f07eZh1M4GIWtekU,3036 +tensorflow/include/tensorflow/compiler/xla/service/gpu/cudnn_vectorize_convolutions.h,sha256=clffOGSptn5yd7AJfozUDTUqOkS0jSx7Jyc9cHKEXQk,2315 +tensorflow/include/tensorflow/compiler/xla/service/gpu/cusolver_context.h,sha256=x7kuMvplXLe0cePNrac6q6h8rZ3p2k-GGCpQag40AqE,4314 +tensorflow/include/tensorflow/compiler/xla/service/gpu/cusolver_rewriter.h,sha256=YhV7czYv68veIveHZTUa3xk04Bx1qZcw-LZ9br1LIWQ,1623 +tensorflow/include/tensorflow/compiler/xla/service/gpu/custom_call_thunk.h,sha256=-bofT0t9N09Bx4F6z-Gm5gyKTBIgaXPjYJY6u1tNrQM,2671 +tensorflow/include/tensorflow/compiler/xla/service/gpu/dot_dimension_sorter.h,sha256=0C5kAzRilMz-E58o77E2teWX-e4X8E9BN4pETTJVug8,1803 +tensorflow/include/tensorflow/compiler/xla/service/gpu/elemental_ir_emitter.h,sha256=rQKYxJiEIDGyghfgrBDkOE7Ez8jEBaS3DCC-lnXvsks,5603 +tensorflow/include/tensorflow/compiler/xla/service/gpu/executable.pb.h,sha256=WRfIy9XYmIYY1Y_dlpyX3aIvjJiX2ML5MWN2XStfTOs,40965 +tensorflow/include/tensorflow/compiler/xla/service/gpu/fft_thunk.h,sha256=E3oNpS5CLd5zSP0kZxHoNOdS1LzZCR7_Zpi48pvuH4c,3418 +tensorflow/include/tensorflow/compiler/xla/service/gpu/for_thunk.h,sha256=0xOW2dOtfFEHBszqdCOcMPpe7D1psLgGqRUN3qORS5M,1774 +tensorflow/include/tensorflow/compiler/xla/service/gpu/fused_mha_thunk.h,sha256=N4a93RTw2-MedjK0J83Lum5TjgYl5zQJ0TxsYeKAh2w,5216 +tensorflow/include/tensorflow/compiler/xla/service/gpu/fusion_merger.h,sha256=AN-t1cz84EnME5RnoF2qehHu-QImxOzAjpk5e_zINDI,3397 +tensorflow/include/tensorflow/compiler/xla/service/gpu/fusion_pipeline.h,sha256=_kxUGZGQCXgqLyigYjEXnPpX-z2c7zNtwzisw-2x-Pg,1463 +tensorflow/include/tensorflow/compiler/xla/service/gpu/fusion_wrapper.h,sha256=MWHuKanpAeMOHm4DCG8cZEhuDnPOs_NepLYQpGwPr28,1497 +tensorflow/include/tensorflow/compiler/xla/service/gpu/fusions/copy.h,sha256=bkLhqKf2ChUrDOvR3N-7teSPDWGSEVaWgsBQkHltuik,1703 +tensorflow/include/tensorflow/compiler/xla/service/gpu/fusions/fusion_emitter.h,sha256=Izm67pcVLcsW6fhGCtuca5ALe1FGU-0oi3EvNNk31dA,3654 +tensorflow/include/tensorflow/compiler/xla/service/gpu/fusions/fusions.h,sha256=7TuX8HueuHSYZEaJL2gKGtC2Sh0N-5UAl6P83rVoDKY,1524 +tensorflow/include/tensorflow/compiler/xla/service/gpu/fusions/in_place_dynamic_update_slice.h,sha256=Q-aUAxFs6dB7nqHGnWsYxaZvv5CwQMuKTWNOJ9NiabU,3327 +tensorflow/include/tensorflow/compiler/xla/service/gpu/fusions/input_slices.h,sha256=_n_yyWzXdc3eIFMWwlORoI7Uplg5isYFrIp16Q265jo,2221 +tensorflow/include/tensorflow/compiler/xla/service/gpu/fusions/loop.h,sha256=6uLa1cJDospoYHY9wVRTL2szBNRSviBfPcwi8G-rGSo,2015 +tensorflow/include/tensorflow/compiler/xla/service/gpu/fusions/reduction.h,sha256=V-5tWuV1J8jK5ocdoO-XA-aWMDqEX0XUNRZijZpwcsg,3752 +tensorflow/include/tensorflow/compiler/xla/service/gpu/fusions/thunk_util.h,sha256=QQM0TeXxIzONMdUF8kfe92F0oD5uFPWcW7Qhx0yHOIc,1351 +tensorflow/include/tensorflow/compiler/xla/service/gpu/fusions/tiling_util.h,sha256=YUeCUFt8uP2TcZMKJAmV36mk5wr-Aky_8q3KywrYwOg,5460 +tensorflow/include/tensorflow/compiler/xla/service/gpu/fusions/transpose.h,sha256=RsqbwiaPOlnyqwHsCL8ihowjuw_SYYUFL1trMrXMZ5E,3405 +tensorflow/include/tensorflow/compiler/xla/service/gpu/gemm_algorithm_picker.h,sha256=5quNiLCPEjOSjFw65cVpTmQpUzowiU6z-rnRceL5DiQ,2985 +tensorflow/include/tensorflow/compiler/xla/service/gpu/gemm_broadcast_folding_rewriter.h,sha256=ojGicqk6TTQuBpNV1Y5zMyI_8nEhZjjSIH8POz1A8oc,1864 +tensorflow/include/tensorflow/compiler/xla/service/gpu/gemm_rewriter.h,sha256=4-cU58q9Cga9G0h5HeaDR8HFRTrEMwv51aq7i1yFw_4,2211 +tensorflow/include/tensorflow/compiler/xla/service/gpu/gemm_rewriter_triton.h,sha256=j2bdL4xWWGC4NDNprq5fs7jgm2bcrzSp8WJt19txn-s,6662 +tensorflow/include/tensorflow/compiler/xla/service/gpu/gemm_thunk.h,sha256=nUKTAKRSt7HEpSQscdNs89xX48qlk1vUExYqX71JCSg,2039 +tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_all_gather_optimizer.h,sha256=3YGefGVa3NLyrWrPmefUhyRo0jh0nj1cstXCVtKCLYo,1438 +tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_asm_opts_util.h,sha256=zhOglTqHno0vnwfijuVeL7KU3tMOlcUeVYl6M8rSboY,1094 +tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_async_collective_annotator.h,sha256=BSc5XYOTTsrqEtNijNdBJwuXIDeoi6RKvSXy-Puvbo0,1557 +tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_autotuning.pb.h,sha256=N11uBi8EDMur51m7IMoUZrgWcXMcLxu6eijZ99RhAzo,57471 +tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_compiler.h,sha256=diprK8ZcJTDZWuXz9DcoEy-lmYqBe4JpvBGvhupzPwQ,10655 +tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_constants.h,sha256=nfFfltC0nd_PasYNThvfUsDnItG4BcKO0_g2iZOFsqY,1980 +tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_conv_padding_legalization.h,sha256=CqvnaszqHnk0mTX2CTljrBZBCVW_XAe1ENrUttoO4Ms,1869 +tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_conv_rewriter.h,sha256=4wnMZ2rXako061o3LPYX4Owymjg0NEyCE0BbwqSBpfY,1910 +tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_conv_runner.h,sha256=sLkHg3ilkpewA_q77aShfh8IzzJAOAEkFn71MbwPDo0,9860 +tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_convert_async_collectives_to_sync.h,sha256=jAI8EKP-JJYAJ7zEQIrgYiioR7_KwzUFKuxRs7ZgjXA,1466 +tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_cost_model_stats_collection.h,sha256=3bO9UIYyMVbXU3hxestDKE_nCyGu2gfcuqfHBytwH8k,2050 +tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_executable.h,sha256=8jzDgsXc_1b6hcdvB0Hanw6YkfWf7XNCGI3OT7bQDM8,14786 +tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_executable_run_options.h,sha256=VFCAfP8kKtekjtXq9Ht-xbUS_cZoSc_xC1KV-s8Oa5I,4766 +tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_float_support.h,sha256=7YF6_mThJo7d0ldmGobsaufRviOUhrhgLeregtmHR94,1723 +tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_fused_mha_runner.h,sha256=Mpq85JZJ5FwOEME1gntiGgcp0-yXDXdigDcsu19fDqI,15047 +tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_fusible.h,sha256=MUvO6o4LQw5q15ywMHg4P5qiou_SIOvEFDUJWba3Eug,8959 +tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_hlo_cost_analysis.h,sha256=wiooeLcXYzvx9BSsRjeScme5Dh4UG1ACQeQpLo8FcaU,4638 +tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_hlo_schedule.h,sha256=cVnAskJx34gb2VIVCHsv5ALj_Mhf9LBEJOSIpZkv2tc,1640 +tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_layout_assignment.h,sha256=suUw2FrDJYoK7fo4h9ANJtDLGM2iB528-sGMPNclKGk,2625 +tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_performance_model.h,sha256=LNDQ0ENq966OLazP9R50SzbIPj4wF05LfYSl2X6A2Wc,5607 +tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_reduce_scatter_creator.h,sha256=jl6cC1SN3T0bzqEvOLZvZA06GFcl7CCxZVXX6xsSiZs,1356 +tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_sanitize_constant_names.h,sha256=ALphBxiqDz1uy4ZBDJh6J9wphSaXWEP2gCU_u5r22DI,1477 +tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_scatter_expander.h,sha256=759KqHm7lUyMuDd-LJtLNW341mCIOfakjbmXcdnR91k,1368 +tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_target_config.h,sha256=GufGsfA8JMykum-KRQ67qTVpLzATy-4aCDxgs6ztrQI,1466 +tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_transfer_manager.h,sha256=Ti8mxGc28cUJEpF7LThgMX9_C6deu2H9MxkMUTT_tBo,4772 +tensorflow/include/tensorflow/compiler/xla/service/gpu/hlo_algorithm_denylist.h,sha256=3d3c0HIUWVJ9XKeJ0x5DoZ_ssJ3IhFUjFua_KQXPtrQ,1196 +tensorflow/include/tensorflow/compiler/xla/service/gpu/hlo_fusion_analysis.h,sha256=3K102gj5SGUhn7gHZ2Mo15gy7lsApFmaN0wCY3qEZ70,5455 +tensorflow/include/tensorflow/compiler/xla/service/gpu/hlo_fusion_stats.h,sha256=OwW9vx-q3ViKCi6CjHT_QfOM-mZ-9nCu7KLny6D9juE,1838 +tensorflow/include/tensorflow/compiler/xla/service/gpu/hlo_op_profile.pb.h,sha256=4qm64DAqnmvCmyebpabx0_hysl9ECNMoU2_hSClaK9o,32660 +tensorflow/include/tensorflow/compiler/xla/service/gpu/hlo_op_profiles.h,sha256=upxArK8aY-iR_QH4xN6htZtiKZoYNDZu9VcA3osgjkk,67284 +tensorflow/include/tensorflow/compiler/xla/service/gpu/hlo_to_ir_bindings.h,sha256=Unf011qHUtk2AdRsiBapBxmbN8Bo0VWFXyq33aKfBnU,4579 +tensorflow/include/tensorflow/compiler/xla/service/gpu/hlo_traversal.h,sha256=4Mv85WsC63Sf6rcHGAj3rrrnmntrYpJaCSilIDmEMyg,3337 +tensorflow/include/tensorflow/compiler/xla/service/gpu/horizontal_input_fusion.h,sha256=7XXuGPBummvG_mZtN_2dTGdMCoRl50j9PFuS62UJAG8,2344 +tensorflow/include/tensorflow/compiler/xla/service/gpu/horizontal_loop_fusion.h,sha256=jkBBFwoA6WXL1BDesWJZr9spN3Ca8S1FNjKOiuZ8t6I,5699 +tensorflow/include/tensorflow/compiler/xla/service/gpu/infeed_manager.h,sha256=fqXEXDhmMaRaWNM-JSHubH5A2c2UvcBLIPtORw40TMo,2410 +tensorflow/include/tensorflow/compiler/xla/service/gpu/infeed_thunk.h,sha256=t19h8j4j_YKTtAgLKgJuXKHGcu2aFWpXqhKcL9QKPKs,1740 +tensorflow/include/tensorflow/compiler/xla/service/gpu/instruction_fusion.h,sha256=FSTyJ92sOdmFtkGP4e5pqXxtxgqXNUATBk_svAaax_Y,3146 +tensorflow/include/tensorflow/compiler/xla/service/gpu/ir_emission_utils.h,sha256=ojuPV-Xwywv11bGbyec9JRaeu5nEGmDIq0a-V-4wPbY,9175 +tensorflow/include/tensorflow/compiler/xla/service/gpu/ir_emitter.h,sha256=DF3-0Oi4I6kPD_SeYL5ut7wWqnR38Qzzpl-pn7s2PH8,6888 +tensorflow/include/tensorflow/compiler/xla/service/gpu/ir_emitter_context.h,sha256=_d0VQyokYTOD_IXWnjFEQOP2t09tNTd9fWH9dnnrxa4,4378 +tensorflow/include/tensorflow/compiler/xla/service/gpu/ir_emitter_nested.h,sha256=r8vM4GEHHLJWpSzHnaQrbB-HAR-wTWaQQNVSffjEALQ,3477 +tensorflow/include/tensorflow/compiler/xla/service/gpu/ir_emitter_triton.h,sha256=0RJ7uVpzOQWswIesuBP49iPwYU1HHJlPSJ4eOdlhapk,4126 +tensorflow/include/tensorflow/compiler/xla/service/gpu/ir_emitter_unnested.h,sha256=Ve-6juoQN3SNYqVquR7h4bvX5xbNLAHV_W3Oc8kf5w8,17911 +tensorflow/include/tensorflow/compiler/xla/service/gpu/kernel_arguments.h,sha256=wlxmYjDlcSPDoVbH9va6JCeiY8qBRnSvUaNqNA662gc,2970 +tensorflow/include/tensorflow/compiler/xla/service/gpu/kernel_mapping_scheme.h,sha256=FMnbAEfp1eR2F3KK2wo58QH2VRlqXGP_N3tYTC49RMI,9111 +tensorflow/include/tensorflow/compiler/xla/service/gpu/kernel_reuse_cache.h,sha256=u1s-qP9_EZcqYQBXY5ZvINq775cjoJmbu4iXMNJrVrw,2664 +tensorflow/include/tensorflow/compiler/xla/service/gpu/kernel_thunk.h,sha256=IEPB1T31V5wsE_fCMoT52eYGCTzmf7h2ZW5LVNm6ykE,4044 +tensorflow/include/tensorflow/compiler/xla/service/gpu/launch_dimensions.h,sha256=sFpkm2zj0rDMfzvLQ3krPm0FURMl09kjTkGSpSvG5QE,4817 +tensorflow/include/tensorflow/compiler/xla/service/gpu/llvm_gpu_backend/gpu_backend_lib.h,sha256=Rh9J4NAi-bETUlWJpf0mr_2pAK6CLf8bgyfekSM_O2o,2783 +tensorflow/include/tensorflow/compiler/xla/service/gpu/llvm_gpu_backend/utils.h,sha256=7i6_1m2UuZp94geiZPDEs0CfmsJjHYDuHpfBQU6EyJs,1793 +tensorflow/include/tensorflow/compiler/xla/service/gpu/loop_double_buffer_transformer.h,sha256=wtmzc1UqtlPy9kCSi_S5Pc6LfGW8fdc99aa0owtOjyM,2070 +tensorflow/include/tensorflow/compiler/xla/service/gpu/matmul_utils.h,sha256=2SQ0AH0GM9wYM2inCSh9LBrJjP03PB9IQ-WPaOvWd94,11025 +tensorflow/include/tensorflow/compiler/xla/service/gpu/memset_thunk.h,sha256=3P2NWH3UYtexJRHLG-txJJey_d4Dd9RqwlznUSbTZjo,2911 +tensorflow/include/tensorflow/compiler/xla/service/gpu/metrics.h,sha256=b3A-WKjvxgK3NFSrAbqbvrtRD2SBU5R_TTR46yvZEJY,1704 +tensorflow/include/tensorflow/compiler/xla/service/gpu/move_copy_to_users.h,sha256=hn4dKjGROo1CJXLl7aGDFrx6a4nfSnNKhHEXRGCklZ4,1372 +tensorflow/include/tensorflow/compiler/xla/service/gpu/multi_output_fusion.h,sha256=EzmMLW0uV9nGaBJx0rck2B07omTThricunEZ0Ay0u_M,5815 +tensorflow/include/tensorflow/compiler/xla/service/gpu/nccl_all_gather_thunk.h,sha256=ZLl-crKAR9qN4AePPqPJVKP6hR3IH_qiT1i6Daecl9c,2317 +tensorflow/include/tensorflow/compiler/xla/service/gpu/nccl_all_reduce_thunk.h,sha256=cfhGgSclNh7LJkYBiJ8a16zfkhRID1xHad-4W0PvmgA,4513 +tensorflow/include/tensorflow/compiler/xla/service/gpu/nccl_all_to_all_thunk.h,sha256=rIljkX2lwPGYw2kl3-LTJ-i5LuBARjBa2voqUQ0dGA0,2468 +tensorflow/include/tensorflow/compiler/xla/service/gpu/nccl_collective_permute_thunk.h,sha256=I3RM3PXsV_sTLPMcElEUp0u7gFGcRmVXz-6izXHSqaY,2780 +tensorflow/include/tensorflow/compiler/xla/service/gpu/nccl_collective_thunk.h,sha256=vmUWrIJ69qR1L8O-0AoTouE94DXSl27WkTnkykNvD1o,7444 +tensorflow/include/tensorflow/compiler/xla/service/gpu/nccl_p2p_thunk_common.h,sha256=uQAogDbaIxDSKLgm1XZV14B8G4dnAKK6RxALl1z3zpI,5167 +tensorflow/include/tensorflow/compiler/xla/service/gpu/nccl_recv_thunk.h,sha256=Doi1Zm4sYQ0jGeABrzGHuh7DB8Cvhnr-xP0K38KHnag,2398 +tensorflow/include/tensorflow/compiler/xla/service/gpu/nccl_send_thunk.h,sha256=8u07Fy1P27JTPvme1EE-Jlq8Ij_fnnebdGW5gWeIKFc,2397 +tensorflow/include/tensorflow/compiler/xla/service/gpu/nccl_utils.h,sha256=0cjY4vHgqbi4BpWSg30WGn41sbLtcuQgoFpuI1xAtX0,4338 +tensorflow/include/tensorflow/compiler/xla/service/gpu/non_atomically_upgradeable_rw_lock.h,sha256=slMiXx7TZvx1fTMERomW_PTNOeezl0ocj-oqKg8igN8,3055 +tensorflow/include/tensorflow/compiler/xla/service/gpu/nvptx_compiler.h,sha256=Fxfwo6HkRJ3G1nwqTDE55YpJ15b_gcNAYr7ypyxHevE,5877 +tensorflow/include/tensorflow/compiler/xla/service/gpu/outfeed_manager.h,sha256=JVZivWiOi98kYkJ5jEwcNki1FGID3R9fhmvZ40fGQOY,2583 +tensorflow/include/tensorflow/compiler/xla/service/gpu/outfeed_thunk.h,sha256=4EPehAD-CL2AZNarQ3MkiTNyqdKCPlBf_59ncYJOb2Y,1715 +tensorflow/include/tensorflow/compiler/xla/service/gpu/parallel_loop_emitter.h,sha256=S_S-M26JiGPYn-5Wpg5GaC3MOc0u6f2dcyUUXhc-uW4,3708 +tensorflow/include/tensorflow/compiler/xla/service/gpu/precompiled_kernels.h,sha256=3tbEyQRybTTtQFsnwlRGLYMjxxQziDVfQivHNM7uR6w,2454 +tensorflow/include/tensorflow/compiler/xla/service/gpu/prepare_hlo_for_ir_emitting_pipeline.h,sha256=7HPleYG2Fa6tpYMjQ4B8-Pfx_yJr1VeJRvtKlmkXElQ,1397 +tensorflow/include/tensorflow/compiler/xla/service/gpu/priority_fusion.h,sha256=6KqFU55jVC3ys7zuOUkonOJoi-b7BxEoieVPrVn7gJk,2793 +tensorflow/include/tensorflow/compiler/xla/service/gpu/reduction_degenerate_dim_remover.h,sha256=v07OBgu1-bR4ndgx3FOlBPoa4LdRxHHRY3B3UmwKagM,1833 +tensorflow/include/tensorflow/compiler/xla/service/gpu/reduction_dimension_grouper.h,sha256=AUilBupJFNfmY_Xq0WuQgofFqdwHZDON7XxV_e_inJo,1789 +tensorflow/include/tensorflow/compiler/xla/service/gpu/reduction_layout_normalizer.h,sha256=DRaXthmSUiFZXwNhtNVnENeJKs1jhWLRxJ7YK4Ug5D8,1823 +tensorflow/include/tensorflow/compiler/xla/service/gpu/reduction_splitter.h,sha256=iL-dhRSLMBHTSePJV5kOQewyw1-qQ3_qA9vLlT5dS6w,2003 +tensorflow/include/tensorflow/compiler/xla/service/gpu/reduction_utils.h,sha256=9UpUyvcEWjNuokk3dcckJpqiWVgIOsnHq4SRD4ceSfA,2803 +tensorflow/include/tensorflow/compiler/xla/service/gpu/replica_id_thunk.h,sha256=LapVLbmz6pk-hrheGOuEGi-ylPIA3anmRzb_4FGge0A,1834 +tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/cholesky.h,sha256=fyVxJfZQ95Ud29Fwb4qhSGjG4b0k83VgE-FwbyYcZ88,1059 +tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/collectives.h,sha256=51eHHko8OJRlFixBMbgOpfUgtsrdFkXSHQ3V-9-KMcc,2929 +tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/concurrent_region.h,sha256=hk1tsoQX_MYwtXW2kB6xzQSUxMVsRJH4mshvoaZiWFQ,2501 +tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/conv.h,sha256=R5q2PhcGig_M8QL8kigdUS498C3imGQPsdap43xZbso,2397 +tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/conv_reorder.h,sha256=QNc9T2mPH5aJI9kKddGkUKT9U65eWPV2dELy5-7uSHk,1090 +tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/cublas_lt_matmul.h,sha256=EuUycBWA5JXV2LCbfqaDGs_agzX9yEQgb--gRowNI_c,1783 +tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/custom_call.h,sha256=tAaMkuWfnlAc1MY51qDahz6Zk5E96QV1zmU6IsYAIb0,1018 +tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/executable.h,sha256=EBhUGzKyCUBdOJD1xduVg42Z4KrWzm3c3rq7_kOaudc,7971 +tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/fft.h,sha256=4-_bjvPGwxSrPABRKbVz7v3zsePzDhJhjk265Qf_Qpk,1429 +tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/fused_attention.h,sha256=Vae-_L0YIUj6V_EqvqBk_GCn5XR-8k_XY6tTDpRKlIg,3925 +tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/gemm.h,sha256=TTqqhkY5Og9R6ikwscbqqv5fV86UifqSIMi5DXYhIEY,1289 +tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/graph_launch.h,sha256=Ilp5sCfe_mtOyyt-mWfVFpYdQTF1RYzkArKigSBLbjI,5333 +tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/io_feed.h,sha256=Dm-FAnzoHTfrbbkzaeC6Ts8Ue6XhRcA1hfrK-rzpm24,1064 +tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/kernel_launch.h,sha256=_Hfsqe8arMN18CNBAdfMPXkB94xyCo36_4rZehyzfPY,1932 +tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/memcpy.h,sha256=YPWZguhuXcSOaSHHCDAf-SNhi-mPUBqMgGdw6VOAUW0,1049 +tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/memset.h,sha256=qXtN9UX1tmH6FFI2uTQE0Na8fU8jx-P_6YhY7Vtj32M,1049 +tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/send_recv.h,sha256=ccr8BZcsITQWQM14lS5nFh6wijdab0J5rvJnXpb2G3Q,2048 +tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/sleep_kernel.h,sha256=Kj-FB67Z_7qEb4NeIpQvfnHU7_R7X3-JAt0mecna7t0,887 +tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/stream_synchronization.h,sha256=WMOnwfTRL00rLcZjxKC9KyGbO_BsNtuTBlLUW7Tn6BQ,1133 +tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/support.h,sha256=g-NiC1yEdi9KP2DgPeS6gqnhbR3t3O0tv-UT5LyY1s8,6139 +tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/topk.h,sha256=pLlYWh7ZpP7ZCNqIGuA0pABEEUGlQ3awK6OEKTmEBEM,1012 +tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/topk_kernel.cu.h,sha256=D04_Dr0fK64TrVJveJ4014NZ9jXohhhqV2uGPBfWVd8,10331 +tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/topk_kernel.h,sha256=-DSlvvbfF6P4WVhAx0poJBYzA9wfkSU2tajGsMj4Jls,1609 +tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/topk_kernel_common.h,sha256=9LiKnnj8DZHfte14eNeYac1TTWUmVQ1Vzz4yDEGCUbs,1273 +tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/tracing.h,sha256=ZnzkeEcSqTtTQBnHxNbrwpQQjLdaj-A4cj9xXz9dPy0,1128 +tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/triangular_solve.h,sha256=luZiZlvXJjx32SOMrnXvAlL2upDA8y91l3Q8ejdcBrk,2020 +tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime2/executable.h,sha256=YVOWsFnh1tcmmzBg_07w10HR8r6ZLQEUfJIlrfPWC04,7099 +tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime3/cholesky_thunk.h,sha256=roAIW52TaSwuvsPD_u1KbM6TLpYkw58_AM7Dr8gNPB4,2812 +tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime_intrinsics.h,sha256=s5NtDCW4yhumB5a6-1Fk7IOFNShfFqhPekKr7Q9EMmM,978 +tensorflow/include/tensorflow/compiler/xla/service/gpu/scatter_slice_simplifier.h,sha256=JHah0WCdT4EXt-43Y_5QmHjv-0s2LQ1oNMUXyFK7sHE,2224 +tensorflow/include/tensorflow/compiler/xla/service/gpu/sequential_thunk.h,sha256=OkgUcOSsY-L7R8GO4HhHLWkOvfvUthJrt7yg_Ln1zd8,1916 +tensorflow/include/tensorflow/compiler/xla/service/gpu/softmax_rewriter_triton.h,sha256=2K0zrIKNzf83E6yvlqpNah_GWCGAFmPGv4rbOnhBTjA,2564 +tensorflow/include/tensorflow/compiler/xla/service/gpu/split_k_gemm_rewriter.h,sha256=OkMwSSkDgfbwifLoasP6vAYqZVlS7nHMctLi-uK692I,1618 +tensorflow/include/tensorflow/compiler/xla/service/gpu/stream_executor_util.h,sha256=Syy9Lz03rv9WSt9z2M1jwVONJwaduigMu7DqkU3s6eU,5360 +tensorflow/include/tensorflow/compiler/xla/service/gpu/target_constants.h,sha256=ahL3UP41P_01x43vbdnmdPfBf9L5nIVFbuQr7rmO6H0,1902 +tensorflow/include/tensorflow/compiler/xla/service/gpu/target_util.h,sha256=BanCnU3d-gHP4BrtDix07QGk57HyQ_RK6CV7yeY20ow,3039 +tensorflow/include/tensorflow/compiler/xla/service/gpu/thunk.h,sha256=JkarHgHYvLW2ONIaL5lWCX8GUMhzKZtKDhAteZsec6o,6715 +tensorflow/include/tensorflow/compiler/xla/service/gpu/topk_specializer.h,sha256=5d7WbGoxxfUO9Yh8gLluYV8XmtI0WDwNO973yTJMVgU,1507 +tensorflow/include/tensorflow/compiler/xla/service/gpu/topk_splitter.h,sha256=rjbD7aqZt6THkiTER8Zoxzbo903p5JdR40_MnpiPbyE,1877 +tensorflow/include/tensorflow/compiler/xla/service/gpu/tree_reduction_rewriter.h,sha256=r3UyZZERad6XA4wezACkLvYr3FFtrezNVaf6rjuCLBs,3231 +tensorflow/include/tensorflow/compiler/xla/service/gpu/triangular_solve_rewriter.h,sha256=LNRSmns3W5VrjX_bl4S2NZCU-44vDFnSl8VhzKeQqkg,2208 +tensorflow/include/tensorflow/compiler/xla/service/gpu/triangular_solve_thunk.h,sha256=A_Qy9DQHM2Hg_4odzxZ6mZ0osfs0DQ6ubKMgSNMTwGI,3331 +tensorflow/include/tensorflow/compiler/xla/service/gpu/triton_autotuner.h,sha256=IPpd4PPaf7V1EIdTmAmzhF-joKZr1VJ--MCmNqBs2Xk,2344 +tensorflow/include/tensorflow/compiler/xla/service/gpu/variadic_op_splitter.h,sha256=jt-z9UF0yAq6i4aSOJbAywGWyQlefs6MBBk-VwAaBr8,1461 +tensorflow/include/tensorflow/compiler/xla/service/gpu/while_thunk.h,sha256=KpE--KYx1Q6cMI9aCrqskT7iASrUf7ry73Mm_u3HECQ,2591 +tensorflow/include/tensorflow/compiler/xla/service/gpu/xfeed_queue.h,sha256=DYBbleDXcb9Dg8B1XHkjMqHB9LVpRzHVAfKD7cdNEfM,5154 +tensorflow/include/tensorflow/compiler/xla/service/gpu/xla_executor_state.h,sha256=JcPnsMfNLco61aSC-mOWTkJR3SnhW-n4Kbd_h8TLc9E,2036 +tensorflow/include/tensorflow/compiler/xla/service/graphcycles/graphcycles.h,sha256=PgHt2S5v8lMDiFkc7EYrk8fauIliXQKEdKQta1Um4sI,6288 +tensorflow/include/tensorflow/compiler/xla/service/graphcycles/ordered_set.h,sha256=PYIO5P0oLZkjEyXL2FMFsUyEltH7758wcsDvNeJDwJ0,2911 +tensorflow/include/tensorflow/compiler/xla/service/heap_simulator.h,sha256=ygr2mna9KiF5K7c6x0cJQ-LQz-vSC-o8IhVSV_2lpwg,38439 +tensorflow/include/tensorflow/compiler/xla/service/hlo.pb.h,sha256=-brvxA8K5DQ0Ui-UEIrr75hEVvnKy20866-4E_lr1vQ,668225 +tensorflow/include/tensorflow/compiler/xla/service/hlo_alias_analysis.h,sha256=EkQEJgXSHQVmCXwNP3mF4BWxj3XEuUJgeKNmHpOVq2A,4655 +tensorflow/include/tensorflow/compiler/xla/service/hlo_buffer.h,sha256=NpoekiQG6aSMfnLH2OsUSVa0JCiatKckeVxBQ2Riqk0,4583 +tensorflow/include/tensorflow/compiler/xla/service/hlo_computation_deduplicator.h,sha256=t_3co305uCfdvTk0yUOa95htEGkshRIZK7Xs9rl8xkY,1898 +tensorflow/include/tensorflow/compiler/xla/service/hlo_constant_folding.h,sha256=mmpK-dDuIqQXXPv-LTui3zg_9AsZO-22rbqVU-hmA4Y,1610 +tensorflow/include/tensorflow/compiler/xla/service/hlo_cost_analysis.h,sha256=j_UtJ5CvEvYiWY42xSsD3RCbUv_KXlYQ3Mg9uKwkfQ4,26819 +tensorflow/include/tensorflow/compiler/xla/service/hlo_creation_utils.h,sha256=KKYbhfrS5MHdem2BcE471smkSjKKrq3j-emdHNv6Vww,19217 +tensorflow/include/tensorflow/compiler/xla/service/hlo_cse.h,sha256=rFtp120bwYwKAiJXlJmNvFqUObrm5rmMYfONdthFlH0,2338 +tensorflow/include/tensorflow/compiler/xla/service/hlo_dataflow_analysis.h,sha256=urBQGYglwMfBcGpTp_B4cHAtd1wU4ENAX6BXTLAgW24,16470 +tensorflow/include/tensorflow/compiler/xla/service/hlo_dce.h,sha256=hmmEOVL-Zc5z559PloGoFxHH1y1t2PQ2m-d-Vy9oGwQ,3033 +tensorflow/include/tensorflow/compiler/xla/service/hlo_domain_isolator.h,sha256=GIWRVxMqj2LQJQ7q27xXimefAI1mcwiZLUHIREGsf90,2402 +tensorflow/include/tensorflow/compiler/xla/service/hlo_domain_map.h,sha256=F70so3ryCfnnZx9bYjKtpQQrdGCd-G4GFvlPdQ2bJn4,5693 +tensorflow/include/tensorflow/compiler/xla/service/hlo_domain_remover.h,sha256=nfBSHWp2lYLHuPRRIxtL9sKtt1UUgLYIcpZp3eEwaqw,2657 +tensorflow/include/tensorflow/compiler/xla/service/hlo_domain_verifier.h,sha256=6_k3leeyr158BJnoRB_CLEHZ4mBHuNBPCK8iCauDogc,2570 +tensorflow/include/tensorflow/compiler/xla/service/hlo_execution_profile.h,sha256=EvTc4qQiyf3_lZxBLA8Fcx_VDujlJTvP5yd6FAsZNHg,6436 +tensorflow/include/tensorflow/compiler/xla/service/hlo_execution_profile_data.pb.h,sha256=yNoCIe1Dh7n6AR9MIOT2VBzr1Q243FmQKOYooJhw9AU,15766 +tensorflow/include/tensorflow/compiler/xla/service/hlo_graph_dumper.h,sha256=TcsN-0A_xWT0mHEaiEPXmL8DB5edEH5mZpjB7QNTNVs,5677 +tensorflow/include/tensorflow/compiler/xla/service/hlo_lexer.h,sha256=tpcOzk7_hL_UbPHVDk6hH6sMmZSlqlf3YzU_u9oa1PQ,6097 +tensorflow/include/tensorflow/compiler/xla/service/hlo_memory_scheduler.h,sha256=wv1EfMkxNIwrViesW2UuEcPcUs-SDZhcQ5hSHstptaM,8120 +tensorflow/include/tensorflow/compiler/xla/service/hlo_module_config.h,sha256=lmK2rFJUu5GtCe9ua72FGA-mzZ8gwQzQqiYC8T-LSww,18915 +tensorflow/include/tensorflow/compiler/xla/service/hlo_module_util.h,sha256=RyVD4Q7p0O1B_Fu00tx9v149E6GkTqbGnmLrqT8Nzyw,2097 +tensorflow/include/tensorflow/compiler/xla/service/hlo_ordering.h,sha256=xPe64XFSRC99LMaKmqiYPJ19JTFZ_jnUSFYrXHggOek,9869 +tensorflow/include/tensorflow/compiler/xla/service/hlo_parser.h,sha256=TIfyQp2SYN5QhfQiSM7Xw6xPXSNwXbscr5yBa-QvIK0,4165 +tensorflow/include/tensorflow/compiler/xla/service/hlo_pass_fix.h,sha256=eqwmd8Kpq17bmty0JFziZM5Y5PEQE7eA5JeEDM-1iug,5411 +tensorflow/include/tensorflow/compiler/xla/service/hlo_pass_interface.h,sha256=zzIIoau6clc4dmPz2Zv8aNRSyea_FO1QjqbqTIOE8vY,7553 +tensorflow/include/tensorflow/compiler/xla/service/hlo_pass_pipeline.h,sha256=8xYThv8jVhVA-Kza4FoyoUamisqKXQdtXzOO-FbOXCw,6805 +tensorflow/include/tensorflow/compiler/xla/service/hlo_phi_graph.h,sha256=MGD2grxnL0NMBzNCoD5n3C8CdMQSr0Qv6HArnppePdY,3492 +tensorflow/include/tensorflow/compiler/xla/service/hlo_profile_printer.h,sha256=f_PGoBGq2TvFikfUUWakD6xq6HkFTkRhneB47Wu2x1w,1191 +tensorflow/include/tensorflow/compiler/xla/service/hlo_profile_printer_data.pb.h,sha256=Grfdd5uQ7SiRtLPtj80yVrCu-MJ3rzhrNL6glj_vcUA,54337 +tensorflow/include/tensorflow/compiler/xla/service/hlo_proto_util.h,sha256=mvwNRnUbDqNeDygtaiUa5GoBr5RjXAFlJBncplIeR5s,2398 +tensorflow/include/tensorflow/compiler/xla/service/hlo_rematerialization.h,sha256=Mwhc5ZF_NO6cTVNq-nwMjCPoQ1KQWZPQUWgN1QZUv68,10644 +tensorflow/include/tensorflow/compiler/xla/service/hlo_replication_analysis.h,sha256=Ob9doym7KGjwkeUsOnflVuMKbFrA-KQ8ZbWhdDhn6Hc,6624 +tensorflow/include/tensorflow/compiler/xla/service/hlo_value.h,sha256=exZRXSzdZ0xv1GpRRxcRCCQpolJJl3zyhOAj3RmekJQ,10242 +tensorflow/include/tensorflow/compiler/xla/service/hlo_verifier.h,sha256=3SHqpy46LeXAx5CtI8CKErJzYaC6tLblIvYYQLapom0,17304 +tensorflow/include/tensorflow/compiler/xla/service/human_readable_profile_builder.h,sha256=lnRFldzkO8hT7pu3gos-5WLofrGdW25tCZbJ4rSH3ek,3147 +tensorflow/include/tensorflow/compiler/xla/service/indexed_array_analysis.h,sha256=9t8iUQGA4lwOkuJ0esXl1Fzef3C_005cSjFzBtzlYFc,15705 +tensorflow/include/tensorflow/compiler/xla/service/instruction_fusion.h,sha256=x08QMQeP-IeDEaYphug1bxNImnwnuD7PukSGTQfCjhY,14800 +tensorflow/include/tensorflow/compiler/xla/service/latency_hiding_scheduler.h,sha256=osTI-SZ1oUmgQkfNjXIyGYcgCLzPz-9VXlrreHA-pDE,37129 +tensorflow/include/tensorflow/compiler/xla/service/layout_assignment.h,sha256=Gjlwi1TZEZjNJxSMGHiGQ_KB4b3Y38_ZB8AqwUY3sxk,32777 +tensorflow/include/tensorflow/compiler/xla/service/layout_normalization.h,sha256=N2eA9XCauno57QpJOqmr5692f90EjvVosCq2gWcouAI,2163 +tensorflow/include/tensorflow/compiler/xla/service/llvm_compiler.h,sha256=qa_EbGBemk9eYzGKKy7p3fYZR57aCu6OQNmOyj453zI,3063 +tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/alias_analysis.h,sha256=OX4CxXRue_wSRZKqTS661Yas5OPnEwSxxhGPO7sU4tE,3453 +tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/buffer_assignment_util.h,sha256=RUFD9-ykz-_6ODBVeWDkQXWCEfvekGd4UdrOJk9t0Pw,1851 +tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/dynamic_update_slice_util.h,sha256=5hnr_4jVmYlsY4m5J_HEdk3-UiU7MxJ4rwneDOdBYZY,4358 +tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/fused_ir_emitter.h,sha256=oFjulIshDVg6mV0IduBPv3g9uC2daYiGhQ8hc3Vm5Xk,3535 +tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/ir_array.h,sha256=uHfPcwp-HeIDla0idfue_i7KRr9PdszkB_sWM525yrk,16653 +tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/ir_builder_mixin.h,sha256=9ud4XH_UC9Z-0T_UIC4oHEZIPsvxW6MjQxPODNEzxXk,13498 +tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/kernel_support_library.h,sha256=5jfmWJnxBPLTXNvnTfyApiKdIB_Edo34SUuu-r8dd1I,12479 +tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/llvm_command_line_options.h,sha256=m9OH-kAx7OEhuP9xI1mofObm3wH5S4b3JZQSy-HeklA,2047 +tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/llvm_loop.h,sha256=aTdsi9S3mBztsd9gFG1tl22mlMTxx35snhsdBNYD1S8,11513 +tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/llvm_type_conversion_util.h,sha256=CITrl3gI-O2CX3Zcyqq7ekRd4ElldabQpGQoozUkPLs,1850 +tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/llvm_util.h,sha256=V0e1rqeoQcO3XlKG9DAApprpL5lL-1Lau7aqHvL4ebE,14812 +tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/loop_emitter.h,sha256=g1XhQaL75NShRmg5fC2w7cZTiW2vl2ciPBXQ1rX_2tI,4494 +tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/math_ops.h,sha256=BURjo49ywByzUYECObdwkPvzqUzrHozgtdhkYad98yU,1123 +tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/sort_util.h,sha256=fTS81k-2oGlFyvJQ0D-nSzqlJX1UnDvGcXCrS-FcDQ8,1897 +tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/tuple_ops.h,sha256=3oCv4hV2Kw_oBkZLj4BzCRngme2DdDHAtzUfXcrN-zw,2391 +tensorflow/include/tensorflow/compiler/xla/service/local_service.h,sha256=W8ZQWMfAIkmtsX_nEauhGsfKeTfIyYAV3hf_QbfgXEE,3798 +tensorflow/include/tensorflow/compiler/xla/service/local_service_utils.h,sha256=6tAKrSa5FroV1Rez6oGkcLRT-jt4zcKtKAYgGiGLlJ4,1448 +tensorflow/include/tensorflow/compiler/xla/service/logical_buffer.h,sha256=sGii0WLRjW4psHzIqnKZq5ahAL-M0Zmp5wU6RMOi0_I,2051 +tensorflow/include/tensorflow/compiler/xla/service/logical_buffer_analysis.h,sha256=USgDxo8kVDX-c2QaCXvPq54FPOXkDOwoHnw0Jjh_NBo,3736 +tensorflow/include/tensorflow/compiler/xla/service/logistic_expander.h,sha256=czDY6Nujij6e0hZQtVtJ_snSxlmDk9ubEHYNaOEElXI,1661 +tensorflow/include/tensorflow/compiler/xla/service/loop_schedule_linearizer.h,sha256=_wQ-STa-VI32MUsPyKug_pTCQnlUyBRac-Eprqflj_s,2278 +tensorflow/include/tensorflow/compiler/xla/service/map_inliner.h,sha256=iXhEWblpCLp3UJ9kIWv2NQzbTZbBtR-s-5SbCo-Zz6o,1489 +tensorflow/include/tensorflow/compiler/xla/service/mapped_ptr_container_sorter.h,sha256=CeYw8OyG_B854WG1kSD4fIRkBwnhGEol_c4T3DwmJMo,17748 +tensorflow/include/tensorflow/compiler/xla/service/maybe_owning_device_memory.h,sha256=zrGEi_TnDTUWshWXhebqJ0aExvd8LC8pDAQyFWErZEc,2869 +tensorflow/include/tensorflow/compiler/xla/service/memory_space_assignment/memory_space_assignment.h,sha256=57xTF7G9YrDw_OLFS8m37qvlDDF0jgNI31oKUYROUs0,116875 +tensorflow/include/tensorflow/compiler/xla/service/memory_space_assignment/memory_space_assignment.pb.h,sha256=LXIkjJ1RGPJhOFWxsMNYJlgtM-e2KTwKQPw-LojH6Dg,23806 +tensorflow/include/tensorflow/compiler/xla/service/memory_space_assignment/repacking.h,sha256=5J2cnTnrVJ9NipnxryVAq9iTJr-zo1XCkpwbV9BqiOU,6262 +tensorflow/include/tensorflow/compiler/xla/service/memory_space_assignment/tuning_utils.h,sha256=WIXVQwH2RdsHfuftYH2ho39Bfn4Q_l1jMicXOzicLSg,1453 +tensorflow/include/tensorflow/compiler/xla/service/memory_space_assignment/utils.h,sha256=ROp03wWHkK5suJZnHsxbOAo9HYj7H4KbFD40Wsj1Whk,1483 +tensorflow/include/tensorflow/compiler/xla/service/metrics.pb.h,sha256=RUUQCDr-ny1pQW_OcP_e4hZ-oyaNCCpcFcmP9PtHFVE,38433 +tensorflow/include/tensorflow/compiler/xla/service/metrics_hook_interface.h,sha256=jtHlXkcReGWEtiZJmo5yhsa690q3UjX9URMZwKymqkI,2474 +tensorflow/include/tensorflow/compiler/xla/service/name_uniquer.h,sha256=_vbkftHufcujlKXjvCjX0kTbEH6eU0E4NO75tns7iSk,2986 +tensorflow/include/tensorflow/compiler/xla/service/op_expander_pass.h,sha256=YSILRbN0J3BOALYs8RJybeM_698bUz8sz4hWvmOrjWI,2083 +tensorflow/include/tensorflow/compiler/xla/service/operand_upcaster.h,sha256=rxeyoAzTUZX43TougnV7B_Dcl49dGUbnUzgxbqlv3QI,1445 +tensorflow/include/tensorflow/compiler/xla/service/optimization_barrier_expander.h,sha256=oRuWxJ8x1hmvvhjoq3c8PlWSrvE9nqQg_6Iy3O_8dKw,1357 +tensorflow/include/tensorflow/compiler/xla/service/p2p_schedule_preparation.h,sha256=ljGEomJRTg90GR35okubc5YKQOEQ6dbr0GBOwm1aP8k,8566 +tensorflow/include/tensorflow/compiler/xla/service/pattern_matcher.h,sha256=t2CNRpP6gQ7OCXhUZMNkfiMaOsQ6292orcbk0zuDe_w,107356 +tensorflow/include/tensorflow/compiler/xla/service/platform_util.h,sha256=0r6rt4bctrBlwwYtSs4Lt9iitSaGJPLjeoQnAr3l92k,2913 +tensorflow/include/tensorflow/compiler/xla/service/profile_guided_latency_estimator.h,sha256=BbriwdtTekzSI8qLsSiEXgmGDmiSsQzmCRFWyY_N8Ec,2255 +tensorflow/include/tensorflow/compiler/xla/service/qr_expander.h,sha256=po3VRtntux93ReiCJ3fq-oRbXf9RaN-CK_SvQWLhFOE,2017 +tensorflow/include/tensorflow/compiler/xla/service/real_imag_expander.h,sha256=FvmKmp6Vo54ipFFqQ2GixmY7tfkqj-O7l-cLFPaW3n0,1235 +tensorflow/include/tensorflow/compiler/xla/service/reduce_decomposer.h,sha256=mMMsZejg03JpBq-Um8iT7TPtv1N_JZI0tGe_ijm0TUI,2481 +tensorflow/include/tensorflow/compiler/xla/service/reduce_scatter_combiner.h,sha256=EZcXaSfLCLsqvA_5NBzPct_e-lSg6J3hMtJjIo-8d9o,1864 +tensorflow/include/tensorflow/compiler/xla/service/reduce_scatter_decomposer.h,sha256=Vb2WeizkjlkB67_Zxpq223-PHFGWTrf0itrEhg8Rdgc,1580 +tensorflow/include/tensorflow/compiler/xla/service/reduce_scatter_reassociate.h,sha256=VpZglkHYyqGiXpAg0yTAyqC6gfPG6gQPr1W5AeTl2_s,1546 +tensorflow/include/tensorflow/compiler/xla/service/rendezvous.h,sha256=QkFArpeTS_kEJ5Gw6_4V4RjVdSHUv4RANNZVQNtONac,5144 +tensorflow/include/tensorflow/compiler/xla/service/reshape_decomposer.h,sha256=oQNOTQS33mFT_g1os_Q4DAmdBI7s58hJaeTiXLV89Kw,1460 +tensorflow/include/tensorflow/compiler/xla/service/reshape_mover.h,sha256=ZFCSsWipQValuXgqD5XA9AHphBQRCDAcmTqgiMYrMIY,2766 +tensorflow/include/tensorflow/compiler/xla/service/result_caster.h,sha256=Q3DgYrq0KT7-AZvkzvkZMj9qd7wO9mZhatKa_w9z4Ag,1545 +tensorflow/include/tensorflow/compiler/xla/service/rng_bit_generator_expander.h,sha256=WB9dETTYWC7VS_RTJpzVj9IrPyaTfBiRHav6Axl84Rg,2576 +tensorflow/include/tensorflow/compiler/xla/service/rng_expander.h,sha256=v6iGkC3EStSxEVv7fSDUg9CkxV-3F26GUg1XkGtZ3Bw,1428 +tensorflow/include/tensorflow/compiler/xla/service/scatter_expander.h,sha256=mPVa2YOQEbPOdJMuM92bZKPNI0_7qs4N2FmSUzbF8E0,2430 +tensorflow/include/tensorflow/compiler/xla/service/scatter_simplifier.h,sha256=WHOjzzS0PJApBHtYILGDFmWOwFf24LRMKhdt_JH43CY,2037 +tensorflow/include/tensorflow/compiler/xla/service/select_and_scatter_expander.h,sha256=tbJmV_3lApiDn8b8LvGkoFctGyx-u3agsDgKyZvGdgE,1419 +tensorflow/include/tensorflow/compiler/xla/service/service.h,sha256=f8g5hX41MZgH640l1BgUMy6D0W-yl9ve0uLbcYhNQKQ,14185 +tensorflow/include/tensorflow/compiler/xla/service/service_executable_run_options.h,sha256=aXEX-bzNMJfANw7FbpzzBu_--aHybNcUwvmxE0jHf-s,3446 +tensorflow/include/tensorflow/compiler/xla/service/shape_inference.h,sha256=hS-FNPxWpZLRuCsRQW-DB6Ai_C8y1c-I5_ex4D9JiXA,21303 +tensorflow/include/tensorflow/compiler/xla/service/shaped_buffer.h,sha256=z0hBjkl25NJEUPZlIdGWpTlB-yMgOeqdemW1qeK4QgA,7990 +tensorflow/include/tensorflow/compiler/xla/service/sharding_propagation.h,sha256=xVKLboZUjuUMwXq5mayzLEoK0e0_QvYm1-W17QqSTzc,7428 +tensorflow/include/tensorflow/compiler/xla/service/sharding_remover.h,sha256=4Ztsesdmk8C46JuEliU5f3b2hPPPCTJjh4zaqu0LEU4,1398 +tensorflow/include/tensorflow/compiler/xla/service/simplify_fp_conversions.h,sha256=8XFErqu-TahWcs2NOnHeWCu1mHySeITFVajqm0H1aW4,2062 +tensorflow/include/tensorflow/compiler/xla/service/slice_sinker.h,sha256=ljNpHJSOOX1wCwwqEuynzg1rkf2GbbjIp7cQK9gqIWc,1286 +tensorflow/include/tensorflow/compiler/xla/service/slow_operation_alarm.h,sha256=cptBsK9AwyQx9Uloxszw8aq2YtJxSqgDcEx4m0J9kdw,3472 +tensorflow/include/tensorflow/compiler/xla/service/sort_simplifier.h,sha256=2EFU1dJaNNGmAlnZbWfkNkdS3cH7IJvk2SzuH6YbkzE,1380 +tensorflow/include/tensorflow/compiler/xla/service/source_map_util.h,sha256=KWZAkZVnnXGF2k0mMNfmu7e6Ioe8W5GKeLgH9IWAe7s,2551 +tensorflow/include/tensorflow/compiler/xla/service/sparse_util.h,sha256=l6dmcojC_1P3yectWwkDsLg8VivN09s95wKxzD-37tk,1204 +tensorflow/include/tensorflow/compiler/xla/service/spmd/collective_permute_motion.h,sha256=NnKSzKO-BWv5jekllgXV0Gg04OuS85BcEMB5yjJN5Zs,1453 +tensorflow/include/tensorflow/compiler/xla/service/spmd/convolution_handler.h,sha256=0CJlOp2Ft4vrnQzOyo_PIj7BRntTYpjJaOhX34pxQPo,1786 +tensorflow/include/tensorflow/compiler/xla/service/spmd/custom_call_handler.h,sha256=Dc71BlEl6NRCDjh5oVfxGTJeQrqfNMsvJsGYCQw9l5s,1224 +tensorflow/include/tensorflow/compiler/xla/service/spmd/spmd_partitioner.h,sha256=zCq2cNHIhpSkczg0vIgOGUq2VmQDMwoLZXYOSf0V3WI,27282 +tensorflow/include/tensorflow/compiler/xla/service/spmd/spmd_partitioner_util.h,sha256=JUq2JDID7tytftH_F-4Ry4oDDS9QR42iugLz5QkV36U,26379 +tensorflow/include/tensorflow/compiler/xla/service/spmd/stateful_rng_spmd_partitioner.h,sha256=UbJrVjSCuJd8BmNEniCakFMyxVosOu4QBp-ysWw1d9k,3189 +tensorflow/include/tensorflow/compiler/xla/service/stable_sort_expander.h,sha256=_Z6qpmJM0TqmazQuvsL6Z7aQvldsXuovLdbV-O7dtAk,1527 +tensorflow/include/tensorflow/compiler/xla/service/stochastic_convert_decomposer.h,sha256=o2d-VjnaqNhJtQ9E1qlUQAUrF-c7vEn5GPXVsgWhW2Y,1384 +tensorflow/include/tensorflow/compiler/xla/service/stream_pool.h,sha256=FF8ANpsEQVUT_u8uRCJvNomQkjnrEoyj8gRyRAvpoxQ,2274 +tensorflow/include/tensorflow/compiler/xla/service/topk_rewriter.h,sha256=AxD5lYyMr9DvuSx3r2ORnLZuiTAK2yGarvy9rHkvkz4,2784 +tensorflow/include/tensorflow/compiler/xla/service/transfer_manager.h,sha256=paMQXqqIVAwBk1AkyorLVq3g9gO6TO6_BoA0nsfeGQA,15229 +tensorflow/include/tensorflow/compiler/xla/service/transpose_folding.h,sha256=bbEWjQGDpwA8UTSOLWXwyxk3-0fO5qPnxuRnOG5gx50,2966 +tensorflow/include/tensorflow/compiler/xla/service/tree_reduction_rewriter.h,sha256=u8EImyJiPqMV5fC07HiDhsbNIXP6DVTIzuseFGCvScw,2334 +tensorflow/include/tensorflow/compiler/xla/service/triangular_solve_expander.h,sha256=NK_PeLZ8AGmSonqDYPQ9s35Dg9IpgYvZcOd_Jagtdlo,2953 +tensorflow/include/tensorflow/compiler/xla/service/tuple_points_to_analysis.h,sha256=cUTQu76BboJyJg8TE6vKrVdv_Mp-lF9NYQETbRf1i1o,15110 +tensorflow/include/tensorflow/compiler/xla/service/tuple_simplifier.h,sha256=hw_oeZhm-MelJ1yBSpBjIBA7Xprwx55-dS4fEvbRH-g,2211 +tensorflow/include/tensorflow/compiler/xla/service/tuple_util.h,sha256=MmGqcVxpOUNhDKAk5PAPd_Uw6uYwJxOiVHBNIo99h5c,2798 +tensorflow/include/tensorflow/compiler/xla/service/value_range.h,sha256=7QRpka91GdXT1vCVv5nb-Ylxe3LTctrDCmmcoxC47qQ,3001 +tensorflow/include/tensorflow/compiler/xla/service/while_loop_all_reduce_code_motion.h,sha256=4ajhLVo0ME6c_7Zg0ZHreg-fRUp2_1fa0sR2LsKkCXk,2082 +tensorflow/include/tensorflow/compiler/xla/service/while_loop_analysis.h,sha256=T5rd9Xfs8Sdjlp1AOZ_hnlIjR0G1izBzyWNv2LSTuOI,2629 +tensorflow/include/tensorflow/compiler/xla/service/while_loop_constant_sinking.h,sha256=Z3GZqLzGEb0l_QrG50h-5rRvu80KeSLQKo1qjEbNJFk,2297 +tensorflow/include/tensorflow/compiler/xla/service/while_loop_invariant_code_motion.h,sha256=QUf2GpiMIV8i8_WqV6VxY0J5h3WA9Gm9fXg5M-1LMWI,3880 +tensorflow/include/tensorflow/compiler/xla/service/while_loop_simplifier.h,sha256=alX4EMUCO8QbIPNwYRzkKaQtOYWh5pUPdtg83zDrSGA,2102 +tensorflow/include/tensorflow/compiler/xla/service/while_loop_trip_count_annotator.h,sha256=S10A_GT0NZurHh_jgZcbF2WzluEY5ZR1KKEAjR7a2hY,1954 +tensorflow/include/tensorflow/compiler/xla/service/while_util.h,sha256=hIdOUdDqHyG4rTtJjGgEXGhzTXAhKtsmrW5kleonUsA,4896 +tensorflow/include/tensorflow/compiler/xla/service/xla_debug_info_manager.h,sha256=L0NaD0IYITnD62ci9Zmwd02ZD-gHX1lKdADIDNS7nIE,3077 +tensorflow/include/tensorflow/compiler/xla/service/zero_sized_hlo_elimination.h,sha256=gLz7bzfuYeJAmJYyUGLU91FxT-kQf92KXRIMNoCk1z0,1333 +tensorflow/include/tensorflow/compiler/xla/service_interface.h,sha256=nQeZkPH1XE_npRufFWzXR_JRzr12-R9BKTG8hLy4x7M,3541 +tensorflow/include/tensorflow/compiler/xla/shape.h,sha256=9xsj3GON6gDC0-JsCPzEwlADdREURt_xUeKvnACLg7I,14026 +tensorflow/include/tensorflow/compiler/xla/shape_layout.h,sha256=tmhzI82mhjWUwRTDgHDDVHIKMj-FZh3bnUTlzFrQsP0,4074 +tensorflow/include/tensorflow/compiler/xla/shape_tree.h,sha256=MPB90j58ZzPCfTXcqMNty7DFZ1jIGPVPPK-naqMM1Go,15949 +tensorflow/include/tensorflow/compiler/xla/shape_util.h,sha256=kN1t4RmbDCTct7GvAVdi8GofH0N_2DD7BO-N3bk6rIA,44424 +tensorflow/include/tensorflow/compiler/xla/sharding_op_util.h,sha256=CNnz2vNDNQ20xUOz2msSkFxxD8tq7bz2hffdss8guK8,1394 +tensorflow/include/tensorflow/compiler/xla/side_effect_util.h,sha256=2y-niBvzYUzSwLzQ18D0zU2b0oc2TvQJ970j1t9XIf0,2694 +tensorflow/include/tensorflow/compiler/xla/status.h,sha256=NV4bccFd-ZXoJmfcm50f0lgiZbslxDIk9oR3UZ6342E,978 +tensorflow/include/tensorflow/compiler/xla/status_macros.h,sha256=lyn-S1D2tvyUcLYc00YWRsA2rA0nKtm72la8kuFIAqc,7194 +tensorflow/include/tensorflow/compiler/xla/statusor.h,sha256=ppOP-8znGzlgblBbrlS4sV8WZ-20FCQwvD5UftKCvm0,951 +tensorflow/include/tensorflow/compiler/xla/stream_executor/allocator_stats.h,sha256=kUQVnJi5guZoupLuTMf7j33tDYKFhTKPaqLs6m0fsEQ,2261 +tensorflow/include/tensorflow/compiler/xla/stream_executor/blas.h,sha256=X5mWSGXHZzTD6CsHXrTQebQ8_KtzTK0seZ961CinFf4,40395 +tensorflow/include/tensorflow/compiler/xla/stream_executor/command_buffer.h,sha256=CLHuMjWYPl0bVMp4nxY2C2IARdLyJgLlXibNmSqkR7E,6290 +tensorflow/include/tensorflow/compiler/xla/stream_executor/cuda/cuda_activation.h,sha256=71Ac5raPYeTj1H3ffTis5RGbRbbGxBN7Fl5Hj1kuCmI,1371 +tensorflow/include/tensorflow/compiler/xla/stream_executor/cuda/cuda_blas.h,sha256=T41m9Ho0xK92KNzN5x4ksxg6VGQ_YnMpgA9ZH2qV4B0,4808 +tensorflow/include/tensorflow/compiler/xla/stream_executor/cuda/cuda_blas_lt.h,sha256=TS3S9k6CWKZaGX1iPHN8q6R0qZGMKhio4FO-BbSgOSA,9599 +tensorflow/include/tensorflow/compiler/xla/stream_executor/cuda/cuda_blas_utils.h,sha256=eR-b9mz1freFjv0q86sI5HeSpEerNtFa6TO26B0_tsE,1524 +tensorflow/include/tensorflow/compiler/xla/stream_executor/cuda/cuda_diagnostics.h,sha256=SsJJtwXAQ866msEkrCTxedn6yXxZQ4XH-o5tJTs6YnY,1526 +tensorflow/include/tensorflow/compiler/xla/stream_executor/cuda/cuda_dnn.h,sha256=NWOllW0lskDbVh7mlPGTzF7aylpT4Ps9TzvTJJHpskg,40808 +tensorflow/include/tensorflow/compiler/xla/stream_executor/cuda/cuda_driver.h,sha256=Ti8gIWVKa212VCsSJn80oK5iG8syVtMhmXQK9Xn9cZU,5713 +tensorflow/include/tensorflow/compiler/xla/stream_executor/cuda/cuda_event.h,sha256=oYrkwQNS2BAm0KHjoEJqqMJk4oPLHoY-Wx6zXXQNfnQ,997 +tensorflow/include/tensorflow/compiler/xla/stream_executor/cuda/cuda_fft.h,sha256=JE1XZCwdoUw617P5xhEuARqmEAEAHP6UreeY2pB3Y4o,5123 +tensorflow/include/tensorflow/compiler/xla/stream_executor/cuda/cuda_helpers.h,sha256=FSU5iUonxXfRupFGu95F_Zn5ipJumMIL2f71ZMJSGgE,1064 +tensorflow/include/tensorflow/compiler/xla/stream_executor/cuda/cuda_kernel.h,sha256=bBTCpRjfY-Hsz2B3RL2cWevwnJESD8OxNm3SEMDhklU,1377 +tensorflow/include/tensorflow/compiler/xla/stream_executor/cuda/cuda_platform_id.h,sha256=nUeQeM-t_hXauvWwqmuLbNdMiB2DIhPJQisfW8BRbZc,1293 +tensorflow/include/tensorflow/compiler/xla/stream_executor/cuda/cuda_stream.h,sha256=q6eL8rSMsVMI3cWTxcs7jOvVnBWG_kZEZJYGVQVnAaQ,1208 +tensorflow/include/tensorflow/compiler/xla/stream_executor/data_type.h,sha256=F5AJ_lTQ7RvgG20s7DJOxXOijMmwZ1wancOAnVjI5ms,2681 +tensorflow/include/tensorflow/compiler/xla/stream_executor/device_description.h,sha256=9CzzceYF5EvTJXGTYReHztB8knIO_K4f24W38NVbS1Y,19231 +tensorflow/include/tensorflow/compiler/xla/stream_executor/device_description.pb.h,sha256=KukWeJhzyF-cFC-Xgmygdg6LUc2KmsETJkKXj69hsTQ,86739 +tensorflow/include/tensorflow/compiler/xla/stream_executor/device_host_allocator.h,sha256=aCPL_1uZeyMLlOTB8xXxDbFs7C5538epuwDVsDoV_Og,2920 +tensorflow/include/tensorflow/compiler/xla/stream_executor/device_id_utils.h,sha256=lcOOhGLUTo-kqZ8SPl1gS8fFv-bqYT-_8yBxl4oj3Tw,1813 +tensorflow/include/tensorflow/compiler/xla/stream_executor/device_mem_allocator.h,sha256=M1hwCV87Rp_ALdU74Nan-XnYqniY-vzaSexpTHmQydc,3297 +tensorflow/include/tensorflow/compiler/xla/stream_executor/device_memory.h,sha256=QDQ3svn75nCCllvmBZIHmx_rkpEXENW5-nYfYeNzm-k,7679 +tensorflow/include/tensorflow/compiler/xla/stream_executor/device_memory_allocator.h,sha256=ruzfcKUg4Zcx-0ntAdbag0ifxtiSKxYWUMt5Tr2cZl8,11661 +tensorflow/include/tensorflow/compiler/xla/stream_executor/device_options.h,sha256=dvCowu-OlJzVv1nleQuKMTJlXRCTgSTNlMwyATLI52U,3678 +tensorflow/include/tensorflow/compiler/xla/stream_executor/dnn.h,sha256=VoGZ6ARezF8p6SwMvpuw8EdsG40_szWSX53j5RU3TVQ,115667 +tensorflow/include/tensorflow/compiler/xla/stream_executor/event.h,sha256=DpPUSmzQarFY5cYGDlqgX29YPaoNOgmZXxIBejtlBPQ,2808 +tensorflow/include/tensorflow/compiler/xla/stream_executor/executor_cache.h,sha256=NcBCNK8b3hebNcvypGs3lbVs2BMF9y5tKltL7Usc2FA,3360 +tensorflow/include/tensorflow/compiler/xla/stream_executor/fft.h,sha256=8AbrMSE1Oc6jT_hd6yawg6uJvbwHgxnU8GFL5zi9Q-g,13616 +tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/asm_compiler.h,sha256=csKIc_92XW4K8TTi20jVVAbZdnj0paXHbq_20NJFESM,5642 +tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_activation.h,sha256=eJU57xexZx1wUS06_z6oKCt2UKYwPDeiDtBgSpzjpos,2044 +tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_asm_opts.h,sha256=cL6VJulOKzHLDBrSz0y0P6m2B4qmSkxAy0Tcs7SvAuY,1894 +tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_command_buffer.h,sha256=d1wXOcTlKl8hEDFZnS6c83uJsgYMQ1eWn2zk6n1dKPM,4519 +tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_cudamallocasync_allocator.h,sha256=Rx6sFOmnLTkBse1EY-gd8022goNQwiFYCFmtBQ49ErQ,5556 +tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_diagnostics.h,sha256=Hjd7k4ZakLXqOwxjUE0vp8cZinWi8Oj85LVgRyxynKE,3850 +tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_driver.h,sha256=dXc0livU-6Iz1sugWwzzNv1Z44ZtOoonz7okCYLGjqo,43887 +tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_event.h,sha256=OIQ3RiewEZj_CnyeMZSW_0byoqObhlYGQm2DcXPw9rA,2023 +tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_executor.h,sha256=gpYoa2KhYAyDG1otVkfhlTeYI_APL1-yjXz6PaqzNVw,15111 +tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_graph.h,sha256=B9lt9ZDvP2E1FzJE5mf7Ty9VLGo7K-hIIEa63Q1oK3U,4919 +tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_helpers.h,sha256=ZTteRvbZez0c9D2v0v2MvPp6mb_c5ZfE5N_6hqvWNh4,3716 +tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_init.h,sha256=dfsCLDyg0oXTp25vxTd54laUoZlaQGWijqcQhR2g0sM,1563 +tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_kernel.h,sha256=F1lL13jf35HPjK8dEdEzUIh4F0RMRmOpbRI4J3gtUP0,4351 +tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_stream.h,sha256=1gsJHfBKcwd8CvpKiRAzWsFSwyuLvg40OD8oMx57PxM,3754 +tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_timer.h,sha256=VOg_3wpXeNWUndFjYwg_OJipW96Dz7Io0goYtHP-raQ,2515 +tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_types.h,sha256=9h4QFzW2Fy-mfmfSjRwjJkUKIrPzL6WIFoq8DDgm-Wk,2785 +tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/redzone_allocator.h,sha256=LCgovchlOxEw4qOwpC1UoS4gaK8PhquaLaFtm2dlwjs,5173 +tensorflow/include/tensorflow/compiler/xla/stream_executor/host/host_gpu_executor.h,sha256=IRmdHluYPXi5pTX8EL6H3sNeE9fKMGS-MHdR4xmpP28,6811 +tensorflow/include/tensorflow/compiler/xla/stream_executor/host/host_platform.h,sha256=2hVLIN2vXyH79yWW3wlOAUtgWYHSPYyNmquSSORbfnQ,2595 +tensorflow/include/tensorflow/compiler/xla/stream_executor/host/host_platform_id.h,sha256=MojYoZKgbInOpKUj-iRU1xwqLMAjMYKr8END7yVBK5M,1299 +tensorflow/include/tensorflow/compiler/xla/stream_executor/host/host_stream.h,sha256=Bf0tWvSAltcgjB_t9ZZaO7tif_4eAzA2n9gB5elFoLk,2373 +tensorflow/include/tensorflow/compiler/xla/stream_executor/host_or_device_scalar.h,sha256=ZAD3Q3OtezVgN3plCoXT5PLYh1H4OiXfiXkth2FZMPQ,1663 +tensorflow/include/tensorflow/compiler/xla/stream_executor/kernel.h,sha256=ReIFFbdKTrDmDN_3JWK6ZTj0xE1YY1-Q47kGjPWmPjc,27996 +tensorflow/include/tensorflow/compiler/xla/stream_executor/kernel_cache_config.h,sha256=qjwJ2P-Tk5xjTdeWSyOseeKXhK4gl8_wDZdO0ZzPcCQ,1600 +tensorflow/include/tensorflow/compiler/xla/stream_executor/kernel_spec.h,sha256=ArhliHqhIcobv3IhgKMzfJFX0FTiuIA12BIlDxWJ7-8,12739 +tensorflow/include/tensorflow/compiler/xla/stream_executor/launch_dim.h,sha256=Sjn56PA7zTv7TgVeSDP5cuiEfyInAl-zU5wwWUVblNA,2756 +tensorflow/include/tensorflow/compiler/xla/stream_executor/lazy_op_runner.h,sha256=l3VUk0TWjewcYc8x2SrXWfeGKNVDkoRe8m7NqKDlVMU,11674 +tensorflow/include/tensorflow/compiler/xla/stream_executor/module_spec.h,sha256=ctInyxQiN4_2jQe7uDve1LAALHmHYshvujU9rZXwGUU,3102 +tensorflow/include/tensorflow/compiler/xla/stream_executor/multi_platform_manager.h,sha256=m079ar3MtMDgO_6WlQzQRG52q_BQRfl7A7A1T9wNcnY,7080 +tensorflow/include/tensorflow/compiler/xla/stream_executor/numeric_options.h,sha256=KEy9yAht6V4cvfH44CBp_kcUdooKdnWIFEvbr-UzDJM,1381 +tensorflow/include/tensorflow/compiler/xla/stream_executor/platform.h,sha256=Kh6cuWAbY5kMEB6Mp9GXLXMHLMf7MMHtHrZZyK2fjgI,6263 +tensorflow/include/tensorflow/compiler/xla/stream_executor/platform/default/dso_loader.h,sha256=0fMC5fgl4TNIY87yFd2zkmmoNNrlbNk9hqxIIlxUIPg,3818 +tensorflow/include/tensorflow/compiler/xla/stream_executor/platform/default/initialize.h,sha256=RN42FG2SUNi1FLgYk0grTByJiX0O3hNl05BUzCD7kCg,2186 +tensorflow/include/tensorflow/compiler/xla/stream_executor/platform/dso_loader.h,sha256=v0MHqWXjN532fsPvoyq3NGFkGE_ORa6CwYpctU2gF8c,1338 +tensorflow/include/tensorflow/compiler/xla/stream_executor/platform/initialize.h,sha256=FAZskWbAI5TN1V7jceT1dy6qIa93mN2FluE_kg14Auw,1123 +tensorflow/include/tensorflow/compiler/xla/stream_executor/platform/platform.h,sha256=abWdY8J5tSTe4eBaD8oFCcJwPezD-ELexLXth3PkglI,1395 +tensorflow/include/tensorflow/compiler/xla/stream_executor/platform/port.h,sha256=djnS48_b3pCUrqwM75fS8MR9wsTF6PjricP57hv3fq8,1543 +tensorflow/include/tensorflow/compiler/xla/stream_executor/plugin.h,sha256=jcajSIoE7dDWj4ZqMu4sEANxIiyQPahuo6SyUXQoIqQ,990 +tensorflow/include/tensorflow/compiler/xla/stream_executor/plugin_registry.h,sha256=fVfAqV45Np-ADNXk3KcmVGh10HazP_sRQ-RbEYytMdM,5045 +tensorflow/include/tensorflow/compiler/xla/stream_executor/rocm/rocm_platform_id.h,sha256=w9kki-rI14GHw1i_gf7mSD3904YKBdZJxlb7F7oHKCc,1293 +tensorflow/include/tensorflow/compiler/xla/stream_executor/scratch_allocator.h,sha256=Cbo0KLCv9yh8Bo378sOkjtc7Bfv6elR3CklaON2SjCI,4253 +tensorflow/include/tensorflow/compiler/xla/stream_executor/stream.h,sha256=erzL073QdzPYEFVvRhnSHWAheqPF4QpGiRTZO5BO9UY,77983 +tensorflow/include/tensorflow/compiler/xla/stream_executor/stream_executor.h,sha256=qCd3wgOWG7HMkrpajF33nYN9Tn0LMZDQjAg_e4xstg4,1782 +tensorflow/include/tensorflow/compiler/xla/stream_executor/stream_executor_internal.h,sha256=Mqhk5m1n03spUUWHoo_-Tn60TPJAJQNY_1J0WncpRgs,18788 +tensorflow/include/tensorflow/compiler/xla/stream_executor/stream_executor_pimpl.h,sha256=q_FM_maI7JgPpnj4RB_gsKKnlU1c3wrpspyRZ42JO_c,32482 +tensorflow/include/tensorflow/compiler/xla/stream_executor/temporary_device_memory.h,sha256=J5QLu0GGjlaH4OTaNbPPRb_aOBto6y0HvEQHI50AFvo,5178 +tensorflow/include/tensorflow/compiler/xla/stream_executor/temporary_memory_manager.h,sha256=4RBeeKvJYsbhTDC0Gretu8y35cvrcLicRS0d_6_fjnw,6032 +tensorflow/include/tensorflow/compiler/xla/stream_executor/tf_allocator_adapter.h,sha256=409RKrZ1GX5GqwfEPeTNeFd9tckeODwfArIDQWxWWg4,6732 +tensorflow/include/tensorflow/compiler/xla/stream_executor/tpu/c_api_conversions.h,sha256=lpn_IrXaGnV7UnJt4B5OOxPLxLW5wwJcy9NxfDnravA,5604 +tensorflow/include/tensorflow/compiler/xla/stream_executor/tpu/c_api_decl.h,sha256=NO1uqNKd60PxX5jUrIL1-J-1udUuWBqNddz_iYcuGY4,9141 +tensorflow/include/tensorflow/compiler/xla/stream_executor/tpu/c_api_defn.h,sha256=uDAQ-kKNYzH3USCfFqNRjvOOifjlgiHppQ3RR1jWHtw,2036 +tensorflow/include/tensorflow/compiler/xla/stream_executor/tpu/libtftpu.h,sha256=bDi__hvi3fBtZ6IwliYW11-6lB91NSGNff9QSibDYB8,1778 +tensorflow/include/tensorflow/compiler/xla/stream_executor/tpu/proto_helper.h,sha256=GYw5frdQ5W7W5F40PJ9_gmKTBhLfgQDGkAUOcSPUxJU,2879 +tensorflow/include/tensorflow/compiler/xla/stream_executor/tpu/tpu_api.h,sha256=catw2De8aTyAABJ7UuWk-oleZtSWQRvOxyW1MM2Lx-4,1223 +tensorflow/include/tensorflow/compiler/xla/stream_executor/tpu/tpu_executor_api.h,sha256=iS2BIlNoIt2ZccyskHcZLdCRMEzqDpk1-XeHGxZOPfA,1460 +tensorflow/include/tensorflow/compiler/xla/stream_executor/tpu/tpu_executor_c_api.h,sha256=6eY9EjGZDywd0WSHFMti0TAssjmUNOP5AspQihVy6ow,27674 +tensorflow/include/tensorflow/compiler/xla/stream_executor/tpu/tpu_ops_c_api.h,sha256=KapVDtZHF69H22Ij_AhxEHCS64_-FEGhnM7OFtQLR9E,30138 +tensorflow/include/tensorflow/compiler/xla/stream_executor/tpu/tpu_profiler_c_api.h,sha256=UbvF4VgoWzkZu98xs_GFjNg4SToxoeV_BtkFD7LUsz8,3404 +tensorflow/include/tensorflow/compiler/xla/stream_executor/trace_listener.h,sha256=okIWx4orApKAF0_yQX5TS1O5Axw-KsT_AsFzqcX7DUc,3330 +tensorflow/include/tensorflow/compiler/xla/translate/hlo_to_mhlo/attribute_importer.h,sha256=0nEVi7zBAmJIQW32aQVBeE05CdfX4_Xsw-ZLdcoqRVc,3314 +tensorflow/include/tensorflow/compiler/xla/translate/hlo_to_mhlo/hlo_function_importer.h,sha256=_8m1zzhsIq2_qSlOSyw3XCK9bgZCZvuDT8CpWm50XpM,13584 +tensorflow/include/tensorflow/compiler/xla/translate/hlo_to_mhlo/hlo_module_importer.h,sha256=qPUhcRykkIZvfnPZQHTWuVOA1yvZ40Ecb8J2LE1F_Yg,2429 +tensorflow/include/tensorflow/compiler/xla/translate/hlo_to_mhlo/hlo_to_mlir_hlo.h,sha256=Aqjik9hL4A5sELREc03uoaT2W4g2UDHpDG0D-_kif2M,1708 +tensorflow/include/tensorflow/compiler/xla/translate/hlo_to_mhlo/hlo_utils.h,sha256=fCa5wG1KLOUICQuO57XyPdfbcO2I57x3bu0JZWGHx4Y,7225 +tensorflow/include/tensorflow/compiler/xla/translate/hlo_to_mhlo/location_importer.h,sha256=Toi-gr1uAaVMLhEIls3t6_K8w1a4eXzO1wnAinO_KjM,1250 +tensorflow/include/tensorflow/compiler/xla/translate/hlo_to_mhlo/stack_location_utils.h,sha256=S1xkgsTeDjP-4qq0tnvaFM6yK6p0t0fW8KDl2KGEF08,1355 +tensorflow/include/tensorflow/compiler/xla/translate/mhlo_to_hlo/attribute_exporter.h,sha256=GcFavRI7Qzn-vOJRQ7mFHulSOdl7Labg2L_pLWtbkNA,3084 +tensorflow/include/tensorflow/compiler/xla/translate/mhlo_to_hlo/layout_util.h,sha256=zh5HeuwAab4E4R-RhKFX27fAFOXJR60J2_MtuA8VONE,3460 +tensorflow/include/tensorflow/compiler/xla/translate/mhlo_to_hlo/location_exporter.h,sha256=fAKB50bukJRdyBeSwv_5885JQZieHArYLHTxxMu9rxc,1773 +tensorflow/include/tensorflow/compiler/xla/translate/mhlo_to_hlo/mlir_hlo_to_hlo.h,sha256=W6nFH68Mv6PUePw-9dBOegl_NZpmT1wjoKD6J0QVZI8,3237 +tensorflow/include/tensorflow/compiler/xla/translate/mhlo_to_hlo/stack_frame_index_builder.h,sha256=waLMNYiS8NPK6_dl8wlCoJF8iDklZ6yOj2NwpfP6G98,1639 +tensorflow/include/tensorflow/compiler/xla/translate/mhlo_to_hlo/type_to_shape.h,sha256=ieXLgSMhzR3M1cR5e6pMtEigZp6TI8P4VGmLpfInfr8,1313 +tensorflow/include/tensorflow/compiler/xla/translate/mhlo_to_lhlo_with_xla/mhlo_to_lhlo_with_xla.h,sha256=0nBbMq0X08A5oODt_s7qFo1GP642o-odmIgoNpTZJjc,15229 +tensorflow/include/tensorflow/compiler/xla/types.h,sha256=RcIy6e44QZ4ligx03Who8KfZpvsVgcHAokcRJQlC4qw,3247 +tensorflow/include/tensorflow/compiler/xla/union_find.h,sha256=Z-QnjH0VGPs1Sak6lnrnwrhdOzsBdNk2X3Mj3a89P2c,2334 +tensorflow/include/tensorflow/compiler/xla/util.h,sha256=xd562y-31bY37mnxEg-D9Kv-zzSAG4YcY7gG0HGd7N0,28258 +tensorflow/include/tensorflow/compiler/xla/window_util.h,sha256=9aMN3_cV458RhLH4Vnl7qZI9ysrXqOsSfNLUFsM2kyY,3979 +tensorflow/include/tensorflow/compiler/xla/xla.pb.h,sha256=2LX5dK1l7t4I4CcbEBq5t9JZnicmirNO9DgmCSOATT0,887834 +tensorflow/include/tensorflow/compiler/xla/xla_data.pb.h,sha256=gbhVPAIMmZG5xT_n-3wiT7KN788fTHsh9VxpuN5exJc,526440 +tensorflow/include/tensorflow/core/activity_watcher/activity.h,sha256=gO1wNqRuB55N5SvSIn_HD_KJbP5eGqI_qiYbSefi1LE,6020 +tensorflow/include/tensorflow/core/activity_watcher/activity_utils.h,sha256=p-OZJCfXtjwF05nEa39ltqFUIjb7TzEYGsqGl9YLNVs,1394 +tensorflow/include/tensorflow/core/common_runtime/all_to_all.h,sha256=8o_6Yts0a8co8HchFkjPJqQQse6l8LS09-zEw6T9CTQ,2455 +tensorflow/include/tensorflow/core/common_runtime/allocator_retry.h,sha256=ukMdTX6Uf91RxM5crx0MpHPsbpzHhzViy-E16_rQi7M,1111 +tensorflow/include/tensorflow/core/common_runtime/arg_ret_placement.h,sha256=P4t_6Ll1HdA3IW49hm8qRZKyhakLhvtfkTaxJ1Ruwnc,8766 +tensorflow/include/tensorflow/core/common_runtime/base_collective_executor.h,sha256=wen6K_Wm8MMM-A0qVlKIKrj562jmtfdFLQm2EwfcvoE,6978 +tensorflow/include/tensorflow/core/common_runtime/bfc_allocator.h,sha256=NnS35HhEU6zlaX_UYRpxpzrT7iyiJGQIQ73lAmFRHCo,1620 +tensorflow/include/tensorflow/core/common_runtime/buf_rendezvous.h,sha256=RprWnZTYyP7btr5430fPtxDWhlCKXw3izw9neak6TI0,5490 +tensorflow/include/tensorflow/core/common_runtime/build_graph_options.h,sha256=I_BpgHS-jqIBWhVIyE1cuT-LxipICC6HfhjeMY8fSQI,1809 +tensorflow/include/tensorflow/core/common_runtime/collective_executor_mgr.h,sha256=d5IirrnsMuI32Z_mDci7V5vyQi0bZzBlhpQ0PfNF96c,3729 +tensorflow/include/tensorflow/core/common_runtime/collective_param_resolver_local.h,sha256=jjUVyvNMwdVLVs5VHzo6VJCwshBvgRmfll4IHHS8hBw,9082 +tensorflow/include/tensorflow/core/common_runtime/collective_rma_local.h,sha256=_ORfz4CkAJ0wkFcIqt4igIgwcwTNU9sVy2jspqBN42Q,3659 +tensorflow/include/tensorflow/core/common_runtime/collective_util.h,sha256=0v3qObeAOkvwV69s5mSScgg6ryvi5bnr8gZzlIV1vb8,2452 +tensorflow/include/tensorflow/core/common_runtime/colocation_graph.h,sha256=cDA0QHJS9wXUSzrrRlN5i9Lmy3-qE4Az6MNQv6N5308,17653 +tensorflow/include/tensorflow/core/common_runtime/composite_device.h,sha256=q-jU5r53vVkIR9IB1kJRwJuDVul2u0sYBJBzoCOyG8M,2676 +tensorflow/include/tensorflow/core/common_runtime/constant_folding.h,sha256=GMRf64Y8yxK4eWBVcO2Zck1_LRfNS1sCbbqWMvhRDkg,3047 +tensorflow/include/tensorflow/core/common_runtime/copy_tensor.h,sha256=OvCuILB8TXhKdpGvLGdoGzMqQ5bQ78KNqPATCuTdXW0,3576 +tensorflow/include/tensorflow/core/common_runtime/cost_constants.h,sha256=VA4OHFcMqoEIRW7p352xqWUs-R9HhiI8pUszmP4QZRI,1738 +tensorflow/include/tensorflow/core/common_runtime/cost_measurement.h,sha256=ipfXgi_AHul5o38JoeCJjoSGbkyP-ziAfUDvgTco0jc,1449 +tensorflow/include/tensorflow/core/common_runtime/cost_measurement_registry.h,sha256=9HuhEIk4a0ZRBBxe9lMPW81cklRZkGDf-LVsGohaMic,3058 +tensorflow/include/tensorflow/core/common_runtime/cost_util.h,sha256=kc850K8Et4P8po8kory-qfE_WllQuHmy_areyuYcznM,1514 +tensorflow/include/tensorflow/core/common_runtime/costmodel_manager.h,sha256=ZTHZRrdnVdgoWF3pHegpI77KRuA8ewXmHDiauA9_htk,1775 +tensorflow/include/tensorflow/core/common_runtime/debugger_state_interface.h,sha256=98lACp76iCA5cMl-AtcwV37QjW1tOalL3urjsDrR-Kw,4749 +tensorflow/include/tensorflow/core/common_runtime/device.h,sha256=KTDhSBY-gUxqDhZi3RpJft9dq_Hyt11qaPalOcpKoD4,867 +tensorflow/include/tensorflow/core/common_runtime/device/device_event_mgr.h,sha256=OJEz8VAjIcwgqGQ-anwprVhOQFCJ0TCy6cNkeDz8S5s,5022 +tensorflow/include/tensorflow/core/common_runtime/device/device_host_allocator.h,sha256=5Ydn57L3Qr8hHETVOQ44Ggk4ceoBRZLKfxuxXiUS58E,1197 +tensorflow/include/tensorflow/core/common_runtime/device/device_id.h,sha256=SUNCBpB8iCm2kaIpy0ckcwXu20t8q-e_SaIiAMXR5hE,4263 +tensorflow/include/tensorflow/core/common_runtime/device/device_id_manager.h,sha256=X223VXhK0k2mrJ0oeilyZZjnMGx42ONxw3-fniEu0V4,1162 +tensorflow/include/tensorflow/core/common_runtime/device/device_mem_allocator.h,sha256=m2IyT7DCvjAZM41OF59s0c-wtfXSWLxo5jKZKCkbkBA,1208 +tensorflow/include/tensorflow/core/common_runtime/device/device_utils.h,sha256=SVeEQ_ohDqeWht8tyqnr6Y06d1WArvPlKfYKN_tp5F0,1927 +tensorflow/include/tensorflow/core/common_runtime/device_factory.h,sha256=5TI1RWZZYOxdH5TKRLcwYuJaSSDkgyIO6wV2Ykojg0s,899 +tensorflow/include/tensorflow/core/common_runtime/device_mgr.h,sha256=FIis4GDUdbk4RI2PrKWyFzOYmJVn7R1IdY3FPwwLT5k,6604 +tensorflow/include/tensorflow/core/common_runtime/device_resolver_local.h,sha256=SyjZHOfDjADxObwkZ3AA3J5WRaVKLRsXuqGKrZUbQnU,1719 +tensorflow/include/tensorflow/core/common_runtime/device_set.h,sha256=QZV5vTdWusNEA8bGOzRNh5puolp6_g9jV-7tw6mvHJ4,5185 +tensorflow/include/tensorflow/core/common_runtime/direct_session.h,sha256=LYJznhxcOySHKwASywS3rKRrnfuUpbShZ3oJbIJfu9A,19034 +tensorflow/include/tensorflow/core/common_runtime/dma_helper.h,sha256=G5Y37YzCQ0gUPpS9igDbWFXWOUEu6JT53XKJCblW5gc,1427 +tensorflow/include/tensorflow/core/common_runtime/eager/attr_builder.h,sha256=f9ZyHaLDQbOyHUAFvZ86eu1cyGNsIx1qsbdT7SJZTso,8900 +tensorflow/include/tensorflow/core/common_runtime/eager/context.h,sha256=yd6LMcZtTaVwp1a89-JlYTHBBdP6MKz9bTXcvRUYHBk,38254 +tensorflow/include/tensorflow/core/common_runtime/eager/context_distributed_manager.h,sha256=Mh4v-Plf5l5VwS9urs3oITzucGDZ2rafHU6Df6Lx9io,3038 +tensorflow/include/tensorflow/core/common_runtime/eager/copy_to_device_node.h,sha256=gH6Eko8e9KIXX8QeGTLbRASARvUFRzJEgksnKQKw5_I,3072 +tensorflow/include/tensorflow/core/common_runtime/eager/custom_device.h,sha256=N4Nt9gPKAGooUnP5bjW6JVV9GRtbUSUPjeMRBsUxrnw,5482 +tensorflow/include/tensorflow/core/common_runtime/eager/custom_device_op_handler.h,sha256=YdoGFozqTzlzOgqr0EIXvI8QkPbmunyO9wZ8I4V9bDE,2404 +tensorflow/include/tensorflow/core/common_runtime/eager/eager_executor.h,sha256=g3XhZSyN73lBSOfFgH1RRQQDiQamJ94ytyrV5Vgk5rU,10851 +tensorflow/include/tensorflow/core/common_runtime/eager/eager_op_rewrite_registry.h,sha256=G6fO8VuJDm42SqwtaSKT602ycWyMxfH_noh0FaE8wBk,3906 +tensorflow/include/tensorflow/core/common_runtime/eager/eager_operation.h,sha256=gxXSGBR5Dd9ddvr98Prcj8O3i4cVYBUste4rWpbnhOM,12672 +tensorflow/include/tensorflow/core/common_runtime/eager/execute.h,sha256=DUPrVFFRnSxhZ74SyyFkJ23_OqkDU6T5fhKK69NcmrI,4583 +tensorflow/include/tensorflow/core/common_runtime/eager/execute_node.h,sha256=-D4NsOcI3t0hCAWQTrDuZyKxETbLBpTwTSI1f-xUMKg,8667 +tensorflow/include/tensorflow/core/common_runtime/eager/kernel_and_device.h,sha256=-vhbKNED1MDx4zEyjcNhIWFNarXie9mmJ9CqnfyiV3M,16971 +tensorflow/include/tensorflow/core/common_runtime/eager/placement_utils.h,sha256=dnAcFxib_UaKDNPJ9nRuu8Ud7toFjkaSx0YZ0D4wkNs,1986 +tensorflow/include/tensorflow/core/common_runtime/eager/rendezvous_cache.h,sha256=KmNTQkrfTancFU5x8AvLVnnD4FbY7YUokvfnyndnoUQ,4661 +tensorflow/include/tensorflow/core/common_runtime/eager/shape_inference.h,sha256=uaxNHWYVhs4BvxU08URVNyKZy2LfKzp9xSVHFecfk2o,1489 +tensorflow/include/tensorflow/core/common_runtime/eager/small_constants_optimizer.h,sha256=mImvCJUNw6iC40ZWmKKs_9UQ_rDLrEEiGveKDP2CodM,1735 +tensorflow/include/tensorflow/core/common_runtime/eager/summary_optimizer.h,sha256=_zYoRauGHdJlcyRRaK31b-03iwBIRnsS_3FzAl_jzqk,2048 +tensorflow/include/tensorflow/core/common_runtime/eager/tensor_handle.h,sha256=CNHbdO0IVjDyF-EL8VSPNuSAb5ELAC47XGw3lfmCt1k,18438 +tensorflow/include/tensorflow/core/common_runtime/eager/tensor_handle_data.h,sha256=WZhxtLwKnu0gvMC-I5AgFqQ-ocy4R-e7LdSH_9iiw5M,4087 +tensorflow/include/tensorflow/core/common_runtime/eval_const_tensor.h,sha256=Czb9dmyl6176EIGDzoGT-Y4jynq9jm-pQsf6RXFWOV8,2424 +tensorflow/include/tensorflow/core/common_runtime/executor.h,sha256=_yd2-Ld10rpX_ew_0xoWu0STWVtxwSp96FSB_U4YvPM,9589 +tensorflow/include/tensorflow/core/common_runtime/executor_factory.h,sha256=G8sk2cbMjWWZ3aQ_y1QYtQfRobNFSA490A7TU7HOkRI,1800 +tensorflow/include/tensorflow/core/common_runtime/function.h,sha256=-GbunhvV78GewYc_hlrENqC-rdC3p7AJEpo4a2Htnyc,3628 +tensorflow/include/tensorflow/core/common_runtime/function_body.h,sha256=qRmSI7-xw6D_AqzQ7a4IwaJomq7nN2iPWjyBBflH8I8,1903 +tensorflow/include/tensorflow/core/common_runtime/function_def_utils.h,sha256=EfZ60LWIKdR_6HzS-aoELRNFYrgEfcSidNb-O26cfMM,1928 +tensorflow/include/tensorflow/core/common_runtime/function_optimization_registry.h,sha256=9jWqwh3w2Hlup2ADRw0nFHDIjfyl3yqFzzkmzCT4J_0,4319 +tensorflow/include/tensorflow/core/common_runtime/function_utils.h,sha256=gW0-iIl7CCvWIODGZEFL0RbJzYuGKIEMIbwo_Zl6aW8,4111 +tensorflow/include/tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.h,sha256=O--NET2SJUHazjlsnnAZRZf0yFgCBIKInJ59jfQPc0w,2117 +tensorflow/include/tensorflow/core/common_runtime/gpu/gpu_cudamalloc_allocator.h,sha256=iylG1E_ZA2pKiYYCAZ3-negSFtfGYS_56kRKT9845ms,1878 +tensorflow/include/tensorflow/core/common_runtime/gpu/gpu_debug_allocator.h,sha256=j8G1GmAjOXdlR1Vb70zbBwyxwsDGAOHV29W1ij72Mqs,3441 +tensorflow/include/tensorflow/core/common_runtime/gpu/gpu_device.h,sha256=HdmfAxUrqsViKeerOGlP0Qt-F6ekwTa7_St0zADtKJ0,18705 +tensorflow/include/tensorflow/core/common_runtime/gpu/gpu_event_mgr.h,sha256=8BYy5ij-_bDEoW-qNtXtMXr4IMbCcjWKSfZ6opR0wIc,1030 +tensorflow/include/tensorflow/core/common_runtime/gpu/gpu_id.h,sha256=HMsqv6nl8f6BCNzSjRXy0iFfX8NaR32Arv1GHqGWkLU,958 +tensorflow/include/tensorflow/core/common_runtime/gpu/gpu_id_manager.h,sha256=CFHJcKPH-CfKHL1EY4DoE5Dr4TujyijiNWovy47_9vg,1640 +tensorflow/include/tensorflow/core/common_runtime/gpu/gpu_managed_allocator.h,sha256=Pj01S7lcU9RVUBoYlUPVEKN08GDDQo1LlrjjbhTa64Q,1494 +tensorflow/include/tensorflow/core/common_runtime/gpu/gpu_process_state.h,sha256=yi-ZGL4amsCOqd7FvPgOve_Gx7SHSRCQ7ff3O8apsu8,7862 +tensorflow/include/tensorflow/core/common_runtime/gpu/gpu_util.h,sha256=1g56SUX6jEwXU1C7hPbdm85aP11wjnpX705GP2_wRzA,4984 +tensorflow/include/tensorflow/core/common_runtime/gpu/gpu_virtual_mem_allocator.h,sha256=1a2jWnL5QFrL5ZD3aHZF64O821pEQC9c5v2vyZDeFmc,4728 +tensorflow/include/tensorflow/core/common_runtime/gpu_device_context.h,sha256=TIX1OaOEZAtflXylGFjssoiZp2QtXSfqRse7E-GAI2U,4112 +tensorflow/include/tensorflow/core/common_runtime/gradients.h,sha256=1n053DabCa4uFTXzQ6AZXkzFgcWY7MOwub1IsaP6c-U,2389 +tensorflow/include/tensorflow/core/common_runtime/graph_constructor.h,sha256=bC5JfPspSeBzO65tjCXd47ESON_4tMh1Fg0npchbGHQ,9133 +tensorflow/include/tensorflow/core/common_runtime/graph_def_builder_util.h,sha256=96yh4S8LHSIPJxIFhq71TwvaMbakTpGGhrKhg_aabH8,1453 +tensorflow/include/tensorflow/core/common_runtime/graph_execution_state.h,sha256=qEatmDHS8JSiv_91LxBFXhlpvwFctGos_vXTzM0r-RM,9509 +tensorflow/include/tensorflow/core/common_runtime/graph_optimizer.h,sha256=D-bPRgfW1bC3ItJwL-dMQkNoEW_bpeX6TjllPC7Hg5A,4069 +tensorflow/include/tensorflow/core/common_runtime/graph_runner.h,sha256=xdrZECBXfvKmGeyBXhW6kd6WjhmkxMcdRoOZ-ULgGjg,2599 +tensorflow/include/tensorflow/core/common_runtime/hierarchical_tree_broadcaster.h,sha256=ijtYWdWiDSCBEA-DISr-TILrLxhbeLWdVlFTX7g3E74,3695 +tensorflow/include/tensorflow/core/common_runtime/inline_function_utils.h,sha256=h6C-EeTQDNzAbZBUuhRIcAzbp-cC4kGrTv19yOAe-K8,11662 +tensorflow/include/tensorflow/core/common_runtime/input_colocation_exemption_registry.h,sha256=JdzcbXZngk63aD-pVef_SMgzdXMyCDoSYGSdqdtxw8Q,2928 +tensorflow/include/tensorflow/core/common_runtime/inspecting_placer.h,sha256=4ThJGB7mALEhYquLlHhzd06UpKyt4B1TNF06-h9ZNYg,3808 +tensorflow/include/tensorflow/core/common_runtime/int32_fulltype.h,sha256=B2X508Icv_6Kynni1Hpp1QJn5mUpN9P-bxQul-XCaaQ,2929 +tensorflow/include/tensorflow/core/common_runtime/isolate_placer_inspection_required_ops_pass.h,sha256=otodZujR7XcxtdY68gjRTuYRzU1IaRPQquQ5xURxtRM,2167 +tensorflow/include/tensorflow/core/common_runtime/local_device.h,sha256=LvBcIAKTWTbgeTqTk8hmSj7-2zeAbMk2f6k-DmLKPHU,1916 +tensorflow/include/tensorflow/core/common_runtime/local_executor_params.h,sha256=ycw4N0Dms08qY0g0TfqyES-hZ2cm4SSLA31vUZPjt3U,2016 +tensorflow/include/tensorflow/core/common_runtime/local_session_selection.h,sha256=ScfyeqZbH1HxHntFu42D7R7hB5X4v19UZTqf6y3aHL4,1226 +tensorflow/include/tensorflow/core/common_runtime/lower_case_op.h,sha256=SY5FD3POFxaLbiT8rde1TGenO3Q-6BtbHy1lmk2b6Q0,1114 +tensorflow/include/tensorflow/core/common_runtime/lower_function_call_inline_policy.h,sha256=O8YTxnIMoQ_qcCRS34BYIKVEFetjm7JX12ji0vUlQMg,2402 +tensorflow/include/tensorflow/core/common_runtime/lower_function_call_op.h,sha256=gXpapwAV669PwyefWb9Drkq_kdvg94A70Sne7bj3n3w,1472 +tensorflow/include/tensorflow/core/common_runtime/lower_functional_ops.h,sha256=FK1qdLBSP9Q5wRqvcmk-tMULGtHrbFJ4WBd8ibj2Gu8,1931 +tensorflow/include/tensorflow/core/common_runtime/lower_if_op.h,sha256=sbE9CEl_XVGOvHNVfAwchV79vmqO29Ip30-tjDnkVTk,1108 +tensorflow/include/tensorflow/core/common_runtime/lower_while_op.h,sha256=h3AUBKlIg15IvdnqSd-7DOvXnyIiftivWL6Rc2VlMsw,1288 +tensorflow/include/tensorflow/core/common_runtime/memory_types.h,sha256=L82Lanz_qyEp2AwkZTdZ0NlxWhAkzhbCl1vZvYGjqrM,2095 +tensorflow/include/tensorflow/core/common_runtime/mkl_cpu_allocator.h,sha256=DFGDhHPVBT_nmyC7OI5PKXSBV_8-lpkL4j5IV2SS4Hk,11922 +tensorflow/include/tensorflow/core/common_runtime/mkl_layout_pass.h,sha256=zpQ7JDsMMQrzmTrBSyzYfYbmbtg1djJzQD-qENzgmyI,1244 +tensorflow/include/tensorflow/core/common_runtime/next_pluggable_device/c/plugin_c_api.h,sha256=RlmvhhRQHD_avTgx61mv25Nix8ssFXk3r6Lzkm5rUkw,7053 +tensorflow/include/tensorflow/core/common_runtime/next_pluggable_device/next_pluggable_device_api.h,sha256=bJ37svihNGgq2eMWUurcSEWCcUwNWg3rCZvCMIUw67k,1412 +tensorflow/include/tensorflow/core/common_runtime/next_pluggable_device/next_pluggable_device_factory.h,sha256=3qUFZeulrUu8uo4Q-S3ZlUFwkkMswNG1V3f9A5g1ByY,2092 +tensorflow/include/tensorflow/core/common_runtime/node_file_writer.h,sha256=YsYmPSUD2PlYMnJGWSuvGM7VIzxNWpNnnIcYyb9QIJ8,2890 +tensorflow/include/tensorflow/core/common_runtime/optimization_registry.h,sha256=fwni-L2nQEL6-ca1skLseR594ZkVsCkkwhsK4F9BPLM,7434 +tensorflow/include/tensorflow/core/common_runtime/optimized_function_graph_info.h,sha256=8eUm_Ix4U3WxziqnmMaG2QyXNyruOkp8w7xYe1vOEk0,3726 +tensorflow/include/tensorflow/core/common_runtime/partitioning_utils.h,sha256=0HGLW4nWOb5VXMpq82uqQ9i8qMQTK7c7E_VzB4MCmTw,5033 +tensorflow/include/tensorflow/core/common_runtime/permuter.h,sha256=dBu14bbGrtfq_1E2hsyZEhg8xJJntsLGC1YUTOqAxUw,2963 +tensorflow/include/tensorflow/core/common_runtime/placer.h,sha256=RdAgaIRcN9s-4EpDsRMeUzCViAXvlE4DoOF6rFQX31w,4759 +tensorflow/include/tensorflow/core/common_runtime/placer_inspection_required_ops_utils.h,sha256=cGUxvyz2oAfMJcnnlof1YDNj74xjkDzfAfSDZYLRssQ,6097 +tensorflow/include/tensorflow/core/common_runtime/pluggable_device/pluggable_device.h,sha256=r0gNVyT7w9Pm4hmwIIT7wtGRBZgVLR0t27S19V81yNc,4711 +tensorflow/include/tensorflow/core/common_runtime/pluggable_device/pluggable_device_bfc_allocator.h,sha256=2ooqTv13NW5i-si98-cZts6O4b0R0KT48fwRqoi6BZA,2373 +tensorflow/include/tensorflow/core/common_runtime/pluggable_device/pluggable_device_context.h,sha256=MsynJX_d_uuf-DARtiSmOPKNhy2UH8G0_QaSiBrWKQ4,3616 +tensorflow/include/tensorflow/core/common_runtime/pluggable_device/pluggable_device_factory.h,sha256=SUVqhYu0GrCVGNCI8c9m5t67o5eiyhv_-ww1kHUfUJc,2675 +tensorflow/include/tensorflow/core/common_runtime/pluggable_device/pluggable_device_init.h,sha256=6alFwmlAuisp_7HNY9hLXAJLp0sqOmetHSvRfJbckwE,1716 +tensorflow/include/tensorflow/core/common_runtime/pluggable_device/pluggable_device_process_state.h,sha256=vWGOikpAZnZw09t_26CWRXVAj2oqdp1NljekFn9b5AA,5027 +tensorflow/include/tensorflow/core/common_runtime/pluggable_device/pluggable_device_simple_allocator.h,sha256=KszTPevbXXMGBU5S9PdnJDkG5yWeR25F61e9Ntynfws,2131 +tensorflow/include/tensorflow/core/common_runtime/pluggable_device/pluggable_device_util.h,sha256=_UVp014bUHE0lT8t7rAoRtMC8egul3JNa7wtESzXX4s,3160 +tensorflow/include/tensorflow/core/common_runtime/pool_allocator.h,sha256=uTPSUQyq8wb6lInmX1klAZwKdtKAcMzs-iHtDYHsVYQ,6343 +tensorflow/include/tensorflow/core/common_runtime/process_function_library_runtime.h,sha256=kNTbP1nQTuuSXz9Z9XW4sBPnr0KjTJVr5YHBmqlRPVM,24332 +tensorflow/include/tensorflow/core/common_runtime/process_state.h,sha256=YjMobrz465KnisgPHnoGM6IXj1vZl_6L2bgd0G18sXw,5513 +tensorflow/include/tensorflow/core/common_runtime/process_util.h,sha256=SOZ9w6GepUEUsf3gVxaQYJzDfltlsR555ngPl5o6Zpk,2800 +tensorflow/include/tensorflow/core/common_runtime/profile_handler.h,sha256=UaQMYy-G0VkC6L2JSyShLh5daUPX0-e2cSyrCPly6V0,2638 +tensorflow/include/tensorflow/core/common_runtime/quantize_training.h,sha256=9Jn7bzR17STvm8cqoNvt4v0Kq7zu0rrO1MKmw2ksqVg,2455 +tensorflow/include/tensorflow/core/common_runtime/renamed_device.h,sha256=AzHkwIccPy-6od6JtMpyMNrNMUSwqgFrSjWO2epV4WE,6509 +tensorflow/include/tensorflow/core/common_runtime/rendezvous_mgr.h,sha256=EVNrjpy4baXmKffI913SL6PPz6A_DuQQ5mIljDYUif4,4207 +tensorflow/include/tensorflow/core/common_runtime/rendezvous_util.h,sha256=ngy086Y7EaGv6ZsTOMTRmpmjVVIwHqOtS4rsM45nZ3Y,2365 +tensorflow/include/tensorflow/core/common_runtime/replicate_constants_pass.h,sha256=_rlTQ8yswACPB7JIVXFffhFwV0V9buqbNCInQ3sE4Fo,2280 +tensorflow/include/tensorflow/core/common_runtime/replicate_per_replica_nodes.h,sha256=Jk5xuf5c4k01DCkpPsWmCkRHgEWljKnRq3fwkjRp7T8,1825 +tensorflow/include/tensorflow/core/common_runtime/request_cost.h,sha256=YVmSvLOumtjYcAH9NiYoCx6tVp1sKVIECCERV1rFmXI,2886 +tensorflow/include/tensorflow/core/common_runtime/request_cost_accessor.h,sha256=RrvtMrHeEqnDHjt1DdL76KO5XJn4TN_YFrgYZmshRqY,1283 +tensorflow/include/tensorflow/core/common_runtime/request_cost_accessor_registry.h,sha256=OtjLEOycjCIdllqnDEHUoctw-FOFXeWwlnk63L4rHaQ,2969 +tensorflow/include/tensorflow/core/common_runtime/ring_alg.h,sha256=IZY6Oj4Q478fVBmMYl86oJ3bRVrcl2d_1TNS_R77EO0,4291 +tensorflow/include/tensorflow/core/common_runtime/ring_gatherer.h,sha256=XiryH0Cc6JWAtERoHthwukQSYgfSIV0NFWGfZEtN-tE,1744 +tensorflow/include/tensorflow/core/common_runtime/ring_reducer.h,sha256=1mA3vQmcMju2gqe4uRJqTjglc_4PsbkCa9XQ2MZTeEI,2010 +tensorflow/include/tensorflow/core/common_runtime/scoped_allocator.h,sha256=0ewXoaw2m6U8S6R4HJG8BTknXJ6NMDU0vcYGS40on4o,4974 +tensorflow/include/tensorflow/core/common_runtime/scoped_allocator_mgr.h,sha256=ica3gL5jdAlMdfdi4dXQ8CnTBnB2RO8aHHJpLRrgqT4,4036 +tensorflow/include/tensorflow/core/common_runtime/session_factory.h,sha256=KzbZYfjgCbF2AzqI3GWxgD1Zf-Za9x6qYeGUqSsOBXU,3178 +tensorflow/include/tensorflow/core/common_runtime/shape_refiner.h,sha256=d0cWuDbPAELwHst3jP25baZwzz1-nB_XJLSSqcwE87w,14636 +tensorflow/include/tensorflow/core/common_runtime/shared_counter.h,sha256=EgFEyj5oqZn2KcOPMV2AwManctTKD6S3zftFaETsHXo,1037 +tensorflow/include/tensorflow/core/common_runtime/single_threaded_cpu_device.h,sha256=yh8vNdY0jHwObul_3mVcDRW8qW8CSW-_dorjAvH1OfE,1305 +tensorflow/include/tensorflow/core/common_runtime/stats_publisher_interface.h,sha256=fejfgGfhEKU5unrVxZuP637uiW_D2KRjTLoaq9GZoac,3174 +tensorflow/include/tensorflow/core/common_runtime/step_stats_collector.h,sha256=SgT3HrofTyhc9GLcCxsXSqv1s4_JwmBicU7VixRfbZQ,8171 +tensorflow/include/tensorflow/core/common_runtime/threadpool_device.h,sha256=WBFFNbHplsJ6kX5a0FapojXslj_LbKsIrcnfmHtzlvc,2631 +tensorflow/include/tensorflow/core/config/flag_defs.h,sha256=_2DOMOWsQRd3qiNW1RyooxGmz15Go_6mZHlwpe9wals,2724 +tensorflow/include/tensorflow/core/config/flags.h,sha256=rt6Q-Rp0GItM9GGr-2RFz8fml9vsJuDz8e8kz-KoPj4,1702 +tensorflow/include/tensorflow/core/data/captured_function.h,sha256=tgn6nle5hDeJTmw6_8L5ScKWkS5ssamqBhF9s5WGQFM,13620 +tensorflow/include/tensorflow/core/data/compression_utils.h,sha256=iu9Pi_Sia5u4qOxMec1ePlT8_DWk-0xupbwZ7iApIDg,1663 +tensorflow/include/tensorflow/core/data/dataset_utils.h,sha256=uyUP534jIo_t6dFvRiMNXyUjOJrv1YIvsIcR2_U7XXA,18573 +tensorflow/include/tensorflow/core/data/finalization_utils.h,sha256=6hzynPOOuo5QZTQQqV8LsZnMknF2DLM1V3uvJA33Npk,1302 +tensorflow/include/tensorflow/core/data/hash_utils.h,sha256=X1JySCmpgnf9T0y5TenUVs3fpuGtvNVuGYJ0unAYEms,2721 +tensorflow/include/tensorflow/core/data/metric_utils.h,sha256=jjnftXhsOslj_oVKNooMcIlFVvttq4ilu-MrVeKtBhA,3399 +tensorflow/include/tensorflow/core/data/name_utils.h,sha256=3cSa5RKs8VpEj87-ft8Nnvod2uNyoS4IXuxCSo1My0o,3575 +tensorflow/include/tensorflow/core/data/rewrite_utils.h,sha256=-gc0txKMH-0fnHA_jOf07Ej58jUIfiHkZrssQTl3728,3811 +tensorflow/include/tensorflow/core/data/root_dataset.h,sha256=xsQqdXYZZr2qYFTOzJmRKrl2bQenVvUzd9RTEzRDYWc,3626 +tensorflow/include/tensorflow/core/data/serialization_utils.h,sha256=kI6Q74ZvJ1R6WltjvGG_yXHZfuWT-CV20QwX7-YzZwY,9193 +tensorflow/include/tensorflow/core/data/snapshot_utils.h,sha256=nLdbZbQzr0okCT2ZcFBDBNBl0a1rSfre9Nbr99nT_Ow,16283 +tensorflow/include/tensorflow/core/data/split_utils.h,sha256=iUkE5Uwjmjg3XQ_NMGLkxMtol5sgeNd3CvY9yJSL4l0,3705 +tensorflow/include/tensorflow/core/data/stats_utils.h,sha256=wIfmlOGa0vbohVz_S15hbLylS-dFn1rhiXifdnAJ_b8,2517 +tensorflow/include/tensorflow/core/data/tfdataz_metrics.h,sha256=6nejLvOiyACav5ayC38bgYMvT5V5o2a7iAUZpiFBwcE,5252 +tensorflow/include/tensorflow/core/data/unbounded_thread_pool.h,sha256=zmOY_K6DM-FEVA9QaGxMcBW9qx8PxyxTEuVCMLZaguY,2457 +tensorflow/include/tensorflow/core/data/utils.h,sha256=J8jPqaHt9_huuDROXybtLIXcFikb5Rfz87ykl_vkYoA,1990 +tensorflow/include/tensorflow/core/debug/debug_callback_registry.h,sha256=Y1fiqzpzBKxHZA1GXfDoGYjOE3yN5RhsGmFHRjtrQC8,2583 +tensorflow/include/tensorflow/core/debug/debug_graph_utils.h,sha256=Qgg48f9SperWNmkImXWcCdF3S9ZoDW7d2usbYLfhxVA,5688 +tensorflow/include/tensorflow/core/debug/debug_io_utils.h,sha256=-DcPon7N8mzBJTlFnCRUJuIHlRRIu4QNEHIwQHejLis,17042 +tensorflow/include/tensorflow/core/debug/debug_node_key.h,sha256=oa_0SEMlXR3Gr0mcTWQbcxtdyFRZtD72WFctq59kwgk,1943 +tensorflow/include/tensorflow/core/debug/debug_service.grpc.pb.h,sha256=GQTl-2AF3gZNwmrmlIV_fRfdFfJ_O6vMgPvMDqhIhx0,43994 +tensorflow/include/tensorflow/core/debug/debug_service.pb.h,sha256=ra195Q_Gg7MEJnoa-NMt6N9ZmKrhmoP0xTfjmf9-sQ4,59230 +tensorflow/include/tensorflow/core/debug/debug_service_mock.grpc.pb.h,sha256=KoE6b4USOkNejddG6QiVyjCCIMDQJNSkyXGuvBZHesI,2305 +tensorflow/include/tensorflow/core/debug/debugger_event_metadata.pb.h,sha256=PHNl9FeXs8NJcr8Y7-MLJkYPTIcsOPwFCxA7BtrWTc8,14198 +tensorflow/include/tensorflow/core/debug/debugger_state_impl.h,sha256=tWfpRgt70zFrcQ1HzDL_QZgGt6jS-LigBAFgT4NyVmM,2164 +tensorflow/include/tensorflow/core/distributed_runtime/base_rendezvous_mgr.h,sha256=uwYO551I4jq6b7WGmg6OiOBeYsy9b8o7L7y4xOAGekE,11400 +tensorflow/include/tensorflow/core/distributed_runtime/call_options.h,sha256=pzp6LAn-VZHJUtvxjDzLcSpYetsew2EdxH47_VGA4fI,1058 +tensorflow/include/tensorflow/core/distributed_runtime/cancellable_call.h,sha256=SrXeLrgeok4SzWLPxCjWEn6vgn2f101E8BgDKnlm1L0,2360 +tensorflow/include/tensorflow/core/distributed_runtime/cluster_function_library_runtime.h,sha256=PBr77SzvBKG350KIBrlhgxcsfab5qtjH44y_IiYMmLQ,4385 +tensorflow/include/tensorflow/core/distributed_runtime/collective_param_resolver_distributed.h,sha256=6PFWrikMERFBhG0geyEs41_IZJzMmCsLTsPz60iep88,4255 +tensorflow/include/tensorflow/core/distributed_runtime/collective_rma_distributed.h,sha256=Z8CM1wG3GqRz6SBzNA2LDFL9fPwI-23rw0fesie-aPE,2804 +tensorflow/include/tensorflow/core/distributed_runtime/coordination/coordination_client.h,sha256=bX6ouYjrZ-F-r0k0AlabnEJIJwSuuaZAccEFCAt2RqM,1218 +tensorflow/include/tensorflow/core/distributed_runtime/coordination/coordination_service_error_util.h,sha256=UeKTZVGSyz5A0e6EaptpOfqoMr8KHMtfZh0RtgCKJ5Y,1239 +tensorflow/include/tensorflow/core/distributed_runtime/device_resolver_distributed.h,sha256=DcUUz5R1PvSviv0mAdeIf6sToB-g-sYWOZu5JwuV2bc,1839 +tensorflow/include/tensorflow/core/distributed_runtime/eager/cluster_function_library_runtime.h,sha256=IdQBrQu9ytkllf7irEeyiI-LY8ACLvZG1mR_kNGb2ss,4958 +tensorflow/include/tensorflow/core/distributed_runtime/eager/destroy_tensor_handle_node.h,sha256=_BV5OZRWcKR4ZAVUP1H4f8Foad7yVvCdnU0AGbV-DBQ,3423 +tensorflow/include/tensorflow/core/distributed_runtime/eager/eager_client.h,sha256=n8hsROG9hHrg5q8NKJYDMIJ2eRcca9MMJOyBthqFtKg,4308 +tensorflow/include/tensorflow/core/distributed_runtime/eager/eager_service_impl.h,sha256=kYZu4928kOZYP2nV0ugfQXIZh4NxJwNFK6dAJ3Wxa6U,8530 +tensorflow/include/tensorflow/core/distributed_runtime/eager/remote_copy_node.h,sha256=_GwvsXBUUvC81bkie3XNKtj98110z-GoCHAj6nzJhuQ,7459 +tensorflow/include/tensorflow/core/distributed_runtime/eager/remote_execute_node.h,sha256=bNYC5HOYisvfaKQkQMYM5acQJVk-zl8Jg-9zOPVfBKY,4904 +tensorflow/include/tensorflow/core/distributed_runtime/eager/remote_mgr.h,sha256=4PX9jWsy2mDEcRcgxUTTVCFwhV4Eqt3P-dcqr14DwqM,5213 +tensorflow/include/tensorflow/core/distributed_runtime/eager/remote_tensor_handle.h,sha256=4ZGT8e6cCjEWC2HYSSLop2_kBeLScXL0qpRok84GObI,1892 +tensorflow/include/tensorflow/core/distributed_runtime/eager/remote_tensor_handle_data.h,sha256=nu8Nq9gozbcmCE3aSxgeGlkZ3ekdWAp0hzsVV-JRroc,3477 +tensorflow/include/tensorflow/core/distributed_runtime/error_payloads.h,sha256=SK4Qpp0bCliAG6MfLP1X3QrMTFSJvXIe1hcz71PdpCc,1515 +tensorflow/include/tensorflow/core/distributed_runtime/graph_mgr.h,sha256=OmC3pgjszafHSMPyFU9x9yXTuOksg3J_OmdzZkiQOP8,7909 +tensorflow/include/tensorflow/core/distributed_runtime/local_master.h,sha256=KGDN7MpuNiZFFtYLGfpBVmhC5ds7k2gFQlUWs7fv8QU,4656 +tensorflow/include/tensorflow/core/distributed_runtime/master.h,sha256=ICVa4b6qjaPHBbvyf5hSqv3R-opKLLfj1SmaGuYnpl8,4201 +tensorflow/include/tensorflow/core/distributed_runtime/master_env.h,sha256=hKoiRgxJNKQCeuRqjw9yEjL19SN7Qv2a9P7FzCodTrs,3955 +tensorflow/include/tensorflow/core/distributed_runtime/master_interface.h,sha256=4D_Av-xODIEgt_QXLjzZHIbADHujf2htGWqlzSkfjzc,5101 +tensorflow/include/tensorflow/core/distributed_runtime/master_session.h,sha256=B1HNy1jnykUnUSOZHzZBO-FfED0acZiGdA_9C8SPCao,10035 +tensorflow/include/tensorflow/core/distributed_runtime/message_wrappers.h,sha256=rZdKA6SnGbHLC283cYPEn0wn-4UWeHpvWS_PL29j_9U,30565 +tensorflow/include/tensorflow/core/distributed_runtime/partial_run_mgr.h,sha256=WdUCU-1ic5qmOgtX08qpN3FrGrxJp0uGhFRt2-iNQKY,3735 +tensorflow/include/tensorflow/core/distributed_runtime/recent_request_ids.h,sha256=QlDRX92MQVwbKSfvsj2V4ychgj2MHQyC1rdlmgGlNgc,4483 +tensorflow/include/tensorflow/core/distributed_runtime/remote_device.h,sha256=vJOnUxTRk-saulhs4IaFiL8tRHkYkDaKVpp6mw8yfn8,2812 +tensorflow/include/tensorflow/core/distributed_runtime/rendezvous_mgr_interface.h,sha256=gtCgHbu8KwnI2-ToUMVZ3ltXycCZlxiTLOhLqfoUp4g,4377 +tensorflow/include/tensorflow/core/distributed_runtime/request_id.h,sha256=_gxld5Ff09RCgHBGoec53b7WUelcQNVBIky60G3xeEU,1220 +tensorflow/include/tensorflow/core/distributed_runtime/rpc/coordination/grpc_coordination_client.h,sha256=pLO4YJdTVwttvzqZuvce7WJF_mV4EYs8BFGezBtg6JM,1251 +tensorflow/include/tensorflow/core/distributed_runtime/rpc/coordination/grpc_coordination_service_impl.h,sha256=Pl6spxnDLWpJkWeTVP5m7FiEKv-Rxd0R-9ckf6Lq75k,1214 +tensorflow/include/tensorflow/core/distributed_runtime/rpc/eager/grpc_eager_client.h,sha256=wXKLxzkKkBZedtB44creLjYFK6K1ucoRam1ta-BtEvM,1266 +tensorflow/include/tensorflow/core/distributed_runtime/rpc/eager/grpc_eager_service.h,sha256=LmPi5Uuj_KZTnEYEfROeg8jm-TWqvgPxBYJztnoEJDg,1010 +tensorflow/include/tensorflow/core/distributed_runtime/rpc/eager/grpc_eager_service_impl.h,sha256=75S9Rhc61JgAnHsF4eGkLURiAy6Wa_AP9mwdN988hhw,7672 +tensorflow/include/tensorflow/core/distributed_runtime/rpc/grpc_channel.h,sha256=AjGCAChHhSFSwEFEac-U65XsOTEYnDWfwaqTwcFY7kY,1287 +tensorflow/include/tensorflow/core/distributed_runtime/rpc/grpc_client_cq_tag.h,sha256=Hlm9KbE1Ef8e36Wp8RtBOpuUESNkys-SFcNCVrrnaM0,1102 +tensorflow/include/tensorflow/core/distributed_runtime/rpc/grpc_master_service.h,sha256=9jozSQhaal6rrYX7s6PobVHIiBcqqBly4lC521wvASU,1297 +tensorflow/include/tensorflow/core/distributed_runtime/rpc/grpc_master_service_impl.h,sha256=wY7FGA2QEfUYNBgIhpoqNmu93awddfxzOHcMVmBNrNo,11560 +tensorflow/include/tensorflow/core/distributed_runtime/rpc/grpc_remote_worker.h,sha256=axcjlSlIO64gXXxCqYA5CkS3o5SNzZM68zi75Wpf7vk,1503 +tensorflow/include/tensorflow/core/distributed_runtime/rpc/grpc_server_lib.h,sha256=cr2nzmvmIqZz_f65eZVDVzdt-XqebObOQq9JhjohHzI,9982 +tensorflow/include/tensorflow/core/distributed_runtime/rpc/grpc_state.h,sha256=PkJLwlb9Jrse0mB_t-XF3xMZysFgrNEYTt8yNdkQmAE,19590 +tensorflow/include/tensorflow/core/distributed_runtime/rpc/grpc_tensor_coding.h,sha256=9A3pi2POd8lXKqil-fn8-j0z_XwXMAq35csCljEo9dQ,2202 +tensorflow/include/tensorflow/core/distributed_runtime/rpc/grpc_util.h,sha256=qtNf9hGX6YAnxbbuWFXwqvGkplXuw5NAA4Oc5fFGzAg,2535 +tensorflow/include/tensorflow/core/distributed_runtime/rpc/grpc_worker_cache.h,sha256=rSF6sVWxLV-p_--poYaTxDAjhCJ3BT43opwGfU0s-dM,2722 +tensorflow/include/tensorflow/core/distributed_runtime/rpc/grpc_worker_service.h,sha256=HjYRCINW60wec3Yc1GP4Nz5LEQf2GAQDdPjPjpCUvFI,3218 +tensorflow/include/tensorflow/core/distributed_runtime/rpc/grpc_worker_service_impl.h,sha256=C9tLNhFJdx6NUlCnj-cbmGLZFuBVjeC0SJh2r6Oy_X4,3716 +tensorflow/include/tensorflow/core/distributed_runtime/rpc/rpc_rendezvous_mgr.h,sha256=0OG9IkRg1XpwyslQC9aTobowjqGnVh8n_1L_TSaAIhI,2299 +tensorflow/include/tensorflow/core/distributed_runtime/rpc/rpc_response_cache.h,sha256=zIcqpwbMoCciwCJIrteP4DwUd5cZW5kmwmlxkRcfw5c,3534 +tensorflow/include/tensorflow/core/distributed_runtime/rpc_collective_executor_mgr.h,sha256=GEDqz4laaJVdHKviow3mXBd7NJeFPTzRzTB0ZbUSdRg,3843 +tensorflow/include/tensorflow/core/distributed_runtime/scheduler.h,sha256=9c3o9Ouk4H2o9rMUgkRaD_y5eMOsWKdbkRMvhZBLlJo,3766 +tensorflow/include/tensorflow/core/distributed_runtime/server_lib.h,sha256=JDd2QIRJ0evo58oW96s1q3bevQFgVLI2WBJwPOhHnqM,4998 +tensorflow/include/tensorflow/core/distributed_runtime/session_mgr.h,sha256=wUgoXe9esEJYqN5zv9nGqVKusXj-N1Qf5qXCUJlFdwg,6869 +tensorflow/include/tensorflow/core/distributed_runtime/tensor_coding.h,sha256=9xLZhdDLDBDsiu9RmKkkpRt6lwgfHr1NrN1go9UC4T8,3948 +tensorflow/include/tensorflow/core/distributed_runtime/worker.h,sha256=T27zhIMvs0rkQadK54mz93VY7y_zOazd6UiSQvoyseA,5761 +tensorflow/include/tensorflow/core/distributed_runtime/worker_cache.h,sha256=VlXm1-hUmWSlPiquLkkhQOQZLU-dC0mnvTCBoQb7ak0,4241 +tensorflow/include/tensorflow/core/distributed_runtime/worker_cache_logger.h,sha256=HuBfY57rIwssSlFynwYOcNXTK5ipmbtljsn5MbfY280,3417 +tensorflow/include/tensorflow/core/distributed_runtime/worker_cache_partial.h,sha256=hy-snw6AMTwvVvXsXTCapPPViYx-zfia_PoFt3xCiC0,2116 +tensorflow/include/tensorflow/core/distributed_runtime/worker_cache_wrapper.h,sha256=mLgIWVzlzNYpooSgcQvRSG7ZrfV9aaruEiWFJc6wtP8,4137 +tensorflow/include/tensorflow/core/distributed_runtime/worker_env.h,sha256=GdJxT4x8Ve3PS-cNWTo7CSDpMbJYYX36iD90yDESIDQ,2624 +tensorflow/include/tensorflow/core/distributed_runtime/worker_interface.h,sha256=-qBRDPakHVZd5wxxQCAcQYswVc4uBu9PIQXKeSyMzEM,9237 +tensorflow/include/tensorflow/core/distributed_runtime/worker_session.h,sha256=ZOxiLpURcfmKPJWQZvlYXWSRLBML-uKJlvCf_QcPhvQ,5433 +tensorflow/include/tensorflow/core/example/example.pb.h,sha256=oO_1jR-7yqDHB66y2MPz8NSJ_9PG_sI6-5cwKBQPMAs,25173 +tensorflow/include/tensorflow/core/example/example.proto,sha256=JOGIIAY0vYrBIvOrux8X4X3d-ZUXnAZrIMXb9NBjGsg,10622 +tensorflow/include/tensorflow/core/example/example_parser_configuration.h,sha256=e3H30SSc9cTDTVVrLva68QVrDSf-ozeYo0YKaALVox8,2392 +tensorflow/include/tensorflow/core/example/example_parser_configuration.pb.h,sha256=bp6B-Sd7vI5kL9YAHzhUS8_xZqIXPFrCNnHifZU8W64,63049 +tensorflow/include/tensorflow/core/example/example_parser_configuration.proto,sha256=a2hmvH80d3hOA9x0xC4kv6zWWhpdqqfqDOK1KewFWB4,1193 +tensorflow/include/tensorflow/core/example/feature.pb.h,sha256=KsbcMJyxxsvuxgfPMFRIMcsyQTJa_Jt6Rjd42eD0muY,68590 +tensorflow/include/tensorflow/core/example/feature.proto,sha256=YSdEURTqGUn6SuD2ce6-PXzqEYCIWycTQmbWuinTEpI,2628 +tensorflow/include/tensorflow/core/example/feature_util.h,sha256=SYs7W5iy2l2dtPQavXdXc4N2zwGRXR2cdszPB7AuwSE,25012 +tensorflow/include/tensorflow/core/framework/allocation_description.pb.h,sha256=RcJvuGcr6QMkjulpw4YJRXYe7WWjaf7uJjXlkveTvNI,16183 +tensorflow/include/tensorflow/core/framework/allocation_description.proto,sha256=OsbZcNh468QkTNuCyD6wyLNivWcmJDr_A0UvKgQH8AU,794 +tensorflow/include/tensorflow/core/framework/allocator.h,sha256=3LH0A3VA-ys3bmMboi1x4m6OxZajG9lTsOoHGZllFR4,1847 +tensorflow/include/tensorflow/core/framework/allocator_registry.h,sha256=BM36MdbQdSf2BkU1iZlC8hngIQFtFNxVauxHLozbI3g,1451 +tensorflow/include/tensorflow/core/framework/api_def.pb.h,sha256=NMHJ7C5P_vtw5kVYKrrN8VJ0jk4VRoIXZR0ZOOSbUFs,87292 +tensorflow/include/tensorflow/core/framework/api_def.proto,sha256=FVchbUXRE-RLPAemxzUEapM17PgIX4X9B6V8SmQKq_Q,5409 +tensorflow/include/tensorflow/core/framework/attr_value.pb.h,sha256=Oqh1PJIhBKkMFI-XHTYPnzUrLs-l1dr2YCDqcUk9Tqs,70649 +tensorflow/include/tensorflow/core/framework/attr_value.proto,sha256=70ixo3rzNlSoi61rBFFi2Yy5hr3-O8mPBa-r9GfZ68E,2603 +tensorflow/include/tensorflow/core/framework/attr_value_util.h,sha256=oC_76JWrF-CdfZ8Oh5RCuU8HZzfYUKIMXbiQHleYmx4,6685 +tensorflow/include/tensorflow/core/framework/bfloat16.h,sha256=jKAd9I31aZg2B1CSgt6fUclOG3ObifBeALbjHell2A8,2665 +tensorflow/include/tensorflow/core/framework/bounds_check.h,sha256=pY1MFFajQ4g07GzLlHas5osAq9iHUn3uKspzHvlPUms,2334 +tensorflow/include/tensorflow/core/framework/cancellation.h,sha256=Fi3Q4C_WwIVEqHCtcmFf-P20-wm1Se73xJugy9NJIDg,1548 +tensorflow/include/tensorflow/core/framework/collective.h,sha256=ESykE3I2SkU8tF_LlybMI4FMbIJqs1OMzQIWztOHhFw,21844 +tensorflow/include/tensorflow/core/framework/common_shape_fns.h,sha256=b6-usKTn2NIhZ9FP2VzNfT5un7c0GUwa_-oMDEdgyg4,12216 +tensorflow/include/tensorflow/core/framework/control_flow.h,sha256=8UNHq5_qoZh0OeQdY62zIDl3trxf_fyutMm_GRXnrHE,2001 +tensorflow/include/tensorflow/core/framework/cost_graph.pb.h,sha256=XQGpmj-tpkjRbnshdgK5KwYfOvSXuG2Mz6dQSTgcMdk,74264 +tensorflow/include/tensorflow/core/framework/cost_graph.proto,sha256=Dx2KkbuKjqtkXkF2fcq05cK9fh5-2mKdIJYFhmGWQZM,2848 +tensorflow/include/tensorflow/core/framework/cpp_shape_inference.pb.h,sha256=RdcCIfQk85B5zr8ax4avj93C2hwWaNoGo92y_sP-lTs,58519 +tensorflow/include/tensorflow/core/framework/cpp_shape_inference.proto,sha256=TGDSUs3u5rJaIg-IeFI-K2vQF74UMO_w1RZUQDO_aY8,923 +tensorflow/include/tensorflow/core/framework/dataset.h,sha256=arFR9aJGLxSam3V3jmUjSmfY9Pb3r82kvzXVRupinNs,65990 +tensorflow/include/tensorflow/core/framework/dataset.pb.h,sha256=tyQRd9P5UKvoqXfkA0KZOAHOOulkwmYdJU_1WGPw80s,37580 +tensorflow/include/tensorflow/core/framework/dataset.proto,sha256=-OmFEfhcW1Y7usCAnX_HTBTb9KcFKEcCGlua0xVqA6Q,1598 +tensorflow/include/tensorflow/core/framework/dataset_metadata.pb.h,sha256=ajUhSbDQ8_Q0jKgze7E5EZGLup1NliCN8CsbOMEjvBw,9908 +tensorflow/include/tensorflow/core/framework/dataset_metadata.proto,sha256=X_1YBsT2_kVR3xYH78UUw5XzpB6sozsqYkTR327BRHk,208 +tensorflow/include/tensorflow/core/framework/dataset_options.pb.h,sha256=36ZgNBop_zSHNbZycTt70ik6SOx0KmvI78yVw53g0XQ,132778 +tensorflow/include/tensorflow/core/framework/dataset_options.proto,sha256=LfAyzUNx5MSIv5bC7r-jPlCKs3VkNO-NHrGTvlp2zS4,8614 +tensorflow/include/tensorflow/core/framework/dataset_stateful_op_allowlist.h,sha256=DoHLGuqnOW8qRLP-Uht5lAqVQvz7MddWPhD-HymNwzY,3128 +tensorflow/include/tensorflow/core/framework/device.h,sha256=ZzcLSobw-dfShBhE7tjzvn-WuKIfy3VIjxXUY9q0MaQ,8697 +tensorflow/include/tensorflow/core/framework/device_attributes.pb.h,sha256=VtO5BGY4Y4uPgtmE7mVoGayYriPUkVukkJsY4dYOnco,50970 +tensorflow/include/tensorflow/core/framework/device_attributes.proto,sha256=f0k7YhLPzzs8hxMqrfvkUHzVpkRwM-Th39pmiXiiVio,1641 +tensorflow/include/tensorflow/core/framework/device_base.h,sha256=XFYFMCQa21ImM8DpO_LJlhPkR4dLl6_Esw5LjpUFqBE,12428 +tensorflow/include/tensorflow/core/framework/device_factory.h,sha256=Q5Y8ohXMNsBUbayS-d8Ron_CGhVDEIXSvsDUk-wZDTg,7130 +tensorflow/include/tensorflow/core/framework/full_type.pb.h,sha256=Y5YdGsU_WnCGbechd18rv0JchMVKsOsAQ-I1zpk6Izc,17761 +tensorflow/include/tensorflow/core/framework/full_type.proto,sha256=8u-Rwp1FOOsGtTwFlIa5KLQLQSzKttC7oeLtNwVjYU8,11871 +tensorflow/include/tensorflow/core/framework/full_type_inference_util.h,sha256=HZ-n5FvEuo-jwatcNbO4W57DPshxzzMQfcceGXSki9I,7675 +tensorflow/include/tensorflow/core/framework/full_type_util.h,sha256=5Q8Csb5ciOikdqtUPHylnYtQaqyvOGS_jGlzphq3ODE,4914 +tensorflow/include/tensorflow/core/framework/function.h,sha256=FA9cGNvg37I673kglTk9CXXB5JvX2DYsGOadBPv6wpU,51027 +tensorflow/include/tensorflow/core/framework/function.pb.h,sha256=vSJ2LSVrW82tzaXB6Usj-PPdM6vYLbK2QZD0dDNbsZA,79942 +tensorflow/include/tensorflow/core/framework/function.proto,sha256=Gk_DUqwa9eIAzPtnJSL3xBlYJzkRtMl-uSKkDPGHfR4,5754 +tensorflow/include/tensorflow/core/framework/function_handle_cache.h,sha256=UW6hj3TLbEfbP0Y8r4KJX4JJHty3sTqqm8X8EorrSO4,2003 +tensorflow/include/tensorflow/core/framework/graph.pb.h,sha256=pRpXTVJNXWVkzDUHJN0KNT5AQ8ZpA0rx6I0GwsvXrPg,23078 +tensorflow/include/tensorflow/core/framework/graph.proto,sha256=Xu5B70Y8eRq-M8V8fEcgO2eNn_70Enn0uD8Hq8PZnGc,2354 +tensorflow/include/tensorflow/core/framework/graph_debug_info.pb.h,sha256=NHgtsxX1FAzV4ImVYtQL73mASWFS8Q7Lly4VzyuHdHc,59435 +tensorflow/include/tensorflow/core/framework/graph_debug_info.proto,sha256=7wwX7my0opxb__yUI5j3K1_H4UQogusmCdHTUSSLYhY,2229 +tensorflow/include/tensorflow/core/framework/graph_def_util.h,sha256=XyGpS1K1wz9HFGAcyG3PbAYrQ5NB3MsipZkMwuutRlg,6263 +tensorflow/include/tensorflow/core/framework/graph_to_functiondef.h,sha256=vzyiV4DdeIqfo3EkCgpr5asZd5kxcNHabnv80O1Gl10,3307 +tensorflow/include/tensorflow/core/framework/graph_transfer_info.pb.h,sha256=hkEJ9ctDLBP_KhEsyU9SAkncjM79hJUd-PwfpZDLdGA,113655 +tensorflow/include/tensorflow/core/framework/graph_transfer_info.proto,sha256=XNswJ3QS8PlYYX2-b4mBwwKMseGhK_tD7kr2tsjn1Iw,1984 +tensorflow/include/tensorflow/core/framework/kernel_def.pb.h,sha256=RWUm4nuF7RljaRF0kjMH5JVaXGGLJXUNZ2kOm0rojnI,42773 +tensorflow/include/tensorflow/core/framework/kernel_def.proto,sha256=_saIzuYOyIKBryMgM6eeLJ50qawJWeBiPVUvciJ-vUs,1460 +tensorflow/include/tensorflow/core/framework/kernel_def_builder.h,sha256=NrSJMoDSXVhh52iNSLlnBUISrtb3zrPLppczoPnDTNo,3809 +tensorflow/include/tensorflow/core/framework/kernel_def_util.h,sha256=iWGNHT7Qe2foOQ1LeFmGo2m5Sv0krR1-Si211RZCNNE,1259 +tensorflow/include/tensorflow/core/framework/kernel_shape_util.h,sha256=xD6oucs35EG8ngXxmegXHJifKVmD4IEFJ7hFLa7Wlno,5398 +tensorflow/include/tensorflow/core/framework/local_rendezvous.h,sha256=tnsU0MW2VcOYNLYuPpwLssZ9n0JPdGQvoCZR2g4WNDo,4427 +tensorflow/include/tensorflow/core/framework/log_memory.h,sha256=yM7P55oqZDavGo30M7YMf-xbloQkF8-Kjx5GYqYKrb8,5168 +tensorflow/include/tensorflow/core/framework/log_memory.pb.h,sha256=DM20ffEdaFfVY8jffxsfdZANdnFqJW2wAyrcGIzD9ns,77607 +tensorflow/include/tensorflow/core/framework/log_memory.proto,sha256=ov0yZEozxRKByJ4jxUoN1iFBCL-zOo2tcnIBuPxmTUY,2326 +tensorflow/include/tensorflow/core/framework/logging.h,sha256=RpeYJ6eZuRhEvVEpSHmzp_GhL-Bd49BPChLBfPT-4Yw,1242 +tensorflow/include/tensorflow/core/framework/lookup_interface.h,sha256=qP9m5wqxerDaMdsihidvMmLBz_bR844YGruHwHnb1DM,6990 +tensorflow/include/tensorflow/core/framework/memory_types.h,sha256=NBh1dztdtgehUm4Ltp53zVJcQblFhnLgGaB_0KdX4qM,1481 +tensorflow/include/tensorflow/core/framework/metrics.h,sha256=FdzbH9Tv5sPX5dC1pJboG6OLw6eAo83nBsfxZsJoe0U,19082 +tensorflow/include/tensorflow/core/framework/model.h,sha256=O30KMXO7FVsrIC2wkWSeBo9GmQS1jaRSVU_i7E_Np5c,52797 +tensorflow/include/tensorflow/core/framework/model.pb.h,sha256=S5MZSjmERaz2QYT4gqjtDkasIMeSY-8lC6KdtLMhKko,77036 +tensorflow/include/tensorflow/core/framework/model.proto,sha256=osiYSmq5Twv9ZjvwYrprTbX1z1fVU2xu7SrJ813cSqg,3652 +tensorflow/include/tensorflow/core/framework/node_def.pb.h,sha256=_UIwzeYbe-vBkgSfIsro7_8C9GcRAtIBaK1rhJyBhrc,49182 +tensorflow/include/tensorflow/core/framework/node_def.proto,sha256=Ysc-wCT6wg0ADtRB2R7-rNm3F3l5cPblhyKrg-_l71A,4242 +tensorflow/include/tensorflow/core/framework/node_def_builder.h,sha256=PwKrTHH4dE1s1UUswvAP94p0cV_6KMrvf9SDwwpPZqw,8436 +tensorflow/include/tensorflow/core/framework/node_def_util.h,sha256=AxqcmH9JRexKOUMxUbfgHD1a3_w6iTlcjeNEJcBhLyE,21892 +tensorflow/include/tensorflow/core/framework/node_properties.h,sha256=NgPE_vQiC62B9EBTJeMMk4e2qz7zk_LZRFDCqbwnAnY,2522 +tensorflow/include/tensorflow/core/framework/numeric_op.h,sha256=jrUTvG78ZGGf4NZ1RF9uGpdSrx9iud045VT-ixgLrDY,3703 +tensorflow/include/tensorflow/core/framework/numeric_types.h,sha256=lpaKQnDVJXip-_8WrZ2fibwwHCw_fjnfxJ-tlGbvA0Q,1450 +tensorflow/include/tensorflow/core/framework/op.h,sha256=JuYl5LGKZjaRHhQ79SDfYa8OnM93KP5KDZHfoT-eJUQ,12308 +tensorflow/include/tensorflow/core/framework/op_def.pb.h,sha256=2Vco9yzbz2m_oWI0xqepDj9-GR7bTD-el3tBIlqY8R8,100955 +tensorflow/include/tensorflow/core/framework/op_def.proto,sha256=uwzncnbDvnk_579pWumURyLAZSkJskfCbiTYE7cw5LU,7896 +tensorflow/include/tensorflow/core/framework/op_def_builder.h,sha256=YHyNTNWQrbNGKbdscAiEoCL6xRLsx6CHIeb1Q0DgHks,12148 +tensorflow/include/tensorflow/core/framework/op_def_util.h,sha256=y0p3CBV74bOwM3PkkxJmJeOficO3DsLZ0OcuxfD-EwI,4714 +tensorflow/include/tensorflow/core/framework/op_gen_lib.h,sha256=uPxGgt4UHSUeg3EleKFiRrfIvZOk494M277TPrhlXfA,4137 +tensorflow/include/tensorflow/core/framework/op_kernel.h,sha256=AVQ4_XCTA2djvoWvVJoOln9NdVAHAJuir7I45kpS2Gc,69994 +tensorflow/include/tensorflow/core/framework/op_requires.h,sha256=DxVaausivJyvVekwrKOsFqEDCe5D8POIklqUaBPAMRY,4828 +tensorflow/include/tensorflow/core/framework/op_segment.h,sha256=1riBlmeEBljrdjYHBsktnlOh6BE1L1fiYCGJ331FFJg,3275 +tensorflow/include/tensorflow/core/framework/ops_util.h,sha256=6HuNxvQWtPmHlXZ2Du6oG-6_fszUKhN8xovmdWsjUho,4413 +tensorflow/include/tensorflow/core/framework/optimized_function_graph.pb.h,sha256=-m2jpc144fggfuwMN-R1RBkTIjxnYcPIyg3amj-r3pI,32306 +tensorflow/include/tensorflow/core/framework/optimized_function_graph.proto,sha256=RvRBW7ciD5f9nvpJK-43OGlcYC00LMKXd9DTc8ivbPw,1699 +tensorflow/include/tensorflow/core/framework/partial_tensor_shape.h,sha256=kkDvAlc4A4skFvZiB6GtV4SlLxi_9zK6hfaC6N48c4c,948 +tensorflow/include/tensorflow/core/framework/queue_interface.h,sha256=QV4VFMp0iQHjLNzWLdZ95KI6-lAN4ZGTrMaQMVYGkg0,4207 +tensorflow/include/tensorflow/core/framework/reader_base.h,sha256=imOGXD_GdcN1ci4PzvSBhAuz8YwLhImIXCpqsrFBel4,5529 +tensorflow/include/tensorflow/core/framework/reader_base.pb.h,sha256=Y4JcerGR8YPMaDVron7TdwK1Iutzd1fFIdQ7DLsaU3w,13595 +tensorflow/include/tensorflow/core/framework/reader_base.proto,sha256=el01IgMAUpsRdstdmyURJq1Z9RSnWJLOtnz3wdNou4c,548 +tensorflow/include/tensorflow/core/framework/reader_interface.h,sha256=ZrNNbrJD9P0K515iNTVlMyzhGrXRtqRRDz3shCLzMj0,3592 +tensorflow/include/tensorflow/core/framework/reader_op_kernel.h,sha256=c4lgT3R9CRx2A1anl75chGo7u8CXmF2QWjm0i5EYE3U,3072 +tensorflow/include/tensorflow/core/framework/ref_var.h,sha256=kOJ55uc0Cp5uOXg1poTC6Hmj9r18NSms3QENAxIj8Vk,1170 +tensorflow/include/tensorflow/core/framework/register_types.h,sha256=ilH7XZ1PyfNJaZepU7iiKZaRzX4ekGLE-Le_h6Cll1E,8461 +tensorflow/include/tensorflow/core/framework/register_types_traits.h,sha256=IK5SObMNkHBOYCBw01bAp9SZogyUQNTRZQp3faPxApM,2974 +tensorflow/include/tensorflow/core/framework/registration/options.h,sha256=WRz30AFnoBTt7WfaEd1yTe7uCSKjmZM94dIhpmSE-O4,1141 +tensorflow/include/tensorflow/core/framework/registration/registration.h,sha256=uGwXCsE8hxKwuv6JMsnsHUwfVwZS46k0Lh3bar1Z98c,6327 +tensorflow/include/tensorflow/core/framework/rendezvous.h,sha256=kFBxcIsPdH06nrck2btuo-TUvlp59voqoPkyv1S704Y,6722 +tensorflow/include/tensorflow/core/framework/resource_base.h,sha256=oVF2Dx-3gm8l6x1-5QxtizBt-y-670_fbYAMED7PZLw,2498 +tensorflow/include/tensorflow/core/framework/resource_handle.h,sha256=d_TiKnvLG2nwrXcqIwtfWpz6XSvMeovYtli2sUnxt84,8615 +tensorflow/include/tensorflow/core/framework/resource_handle.pb.h,sha256=4NsMJ0BML5KcC_Tc2MnHjPjeWTRQZdktWxQVdLVCitg,34081 +tensorflow/include/tensorflow/core/framework/resource_handle.proto,sha256=hVUPTVFTG6DdY1hFTLIXmI1oarcN9aO71WHzeS2lJM8,1369 +tensorflow/include/tensorflow/core/framework/resource_mgr.h,sha256=JhZA3uGH3XupeUqcvNUD7MAxbrntGIehQ38RBHzlU60,39923 +tensorflow/include/tensorflow/core/framework/resource_op_kernel.h,sha256=1WmMMY8htSZOLXqCAs2Eb2FH2YzWWvGa_OSQudIb5cM,6285 +tensorflow/include/tensorflow/core/framework/resource_var.h,sha256=nKbqNZD0RqC7uV2Q2iCs2NdeVCa_bBNomjAnOzmqjSY,6478 +tensorflow/include/tensorflow/core/framework/rng_alg.h,sha256=LmY2tkK1szDsZ1SBfGGquZL3jnlxyihYhcXc8L3A4CY,2325 +tensorflow/include/tensorflow/core/framework/run_handler.h,sha256=Hq93FlbDQOpR_uL-3ZFUqtMZaAOfsufLs3h2W7VKj3Y,9666 +tensorflow/include/tensorflow/core/framework/run_handler_util.h,sha256=ENwiSA3wvYEToyRTc6_MwlfFexX-fpDWEePJoNuweKQ,3896 +tensorflow/include/tensorflow/core/framework/session_state.h,sha256=5yIMIw12xAOVvCeqAtQHLn_zKLoLp62S4xxxobcQK7c,2949 +tensorflow/include/tensorflow/core/framework/shape_inference.h,sha256=a5H8AGwZ3VJaax0PjdysVWDx0t0erdS30QI-3Yl1gSQ,37698 +tensorflow/include/tensorflow/core/framework/shared_ptr_variant.h,sha256=TDJngV9QcRaRSLDdSqdi6dj9HJYPUFrW8acp4UjcrIM,2462 +tensorflow/include/tensorflow/core/framework/stats_aggregator.h,sha256=VmSuV4XCrCz64ZvwhxL_E5LksjL18ac52eU6ZC8d_Xw,3971 +tensorflow/include/tensorflow/core/framework/step_stats.pb.h,sha256=iDoi0Lxk3Gm4-ZIAPhHjkNP202m8at0KNXoiammyq9g,109807 +tensorflow/include/tensorflow/core/framework/step_stats.proto,sha256=D68JJ3lVcJr1ECuJOe-WfET-2h7V_nVKxlrhyL220PM,2786 +tensorflow/include/tensorflow/core/framework/summary.pb.h,sha256=dgpeBDgAzkdjATlN0JVMp54kJX9nLIhiGM-c28NNOkM,105675 +tensorflow/include/tensorflow/core/framework/summary.proto,sha256=seu2s5-Sy9Pw-KglNTF3q_FUQSyX22W5XQvTlTJX61w,4621 +tensorflow/include/tensorflow/core/framework/tensor.h,sha256=D8GCN2zpE3xQTL1AKBJNP6AVsoFM2DgNsS4cPEOUyGo,42635 +tensorflow/include/tensorflow/core/framework/tensor.pb.h,sha256=wykuadjkwZBM4kQQkv7UlgTVBtcCxWoL8QYLBtrVWNE,68813 +tensorflow/include/tensorflow/core/framework/tensor.proto,sha256=TYXqD0iHPfP3lnd6Ah_etrkzZzyzCa40saguZW83rgs,3533 +tensorflow/include/tensorflow/core/framework/tensor_description.pb.h,sha256=5_psoDSbC23WWA__s1Q7-_YF5jLrnoSiHOB9ka30mG4,18505 +tensorflow/include/tensorflow/core/framework/tensor_description.proto,sha256=dju-KhQ7AQCnP6Wdr5qQ3lbetLuvtoSwknTXlZxup4U,758 +tensorflow/include/tensorflow/core/framework/tensor_key.h,sha256=sTIFjuELRL6wDIorMBgIAUrKzawuDVyoGd5XS2C3hvs,2487 +tensorflow/include/tensorflow/core/framework/tensor_reference.h,sha256=CPHQmWTfD6hLRUoQAcaDNp5h0hPrM6XJsuXAw8P66x0,1884 +tensorflow/include/tensorflow/core/framework/tensor_shape.h,sha256=nU8XZf95YCOmfK8vKla0jevEl8Izff6Nb2WtzZfjkCw,30031 +tensorflow/include/tensorflow/core/framework/tensor_shape.pb.h,sha256=8wfOX_nNqM-iMS21VZ1OdcXDV2ohe8FNyBmyuWthdXA,20000 +tensorflow/include/tensorflow/core/framework/tensor_shape.proto,sha256=UjfG0TyMFewe1Ecp1Da-Ovc1r3NPCr_lgzzPxy7eTC0,1663 +tensorflow/include/tensorflow/core/framework/tensor_slice.h,sha256=7XeOV2uAqcffGSuEU-Eq1r9jPHN3Cv1v3K4eBpML9OY,8374 +tensorflow/include/tensorflow/core/framework/tensor_slice.pb.h,sha256=1wqZL-a4dYxT5hwxB0TQyjcCbMPR_W2dMHSqeD53W9c,19392 +tensorflow/include/tensorflow/core/framework/tensor_slice.proto,sha256=2brQK6VoFVWctJ6_69i_UFt-8jK7ZH1OnuZmKTJQk4g,1352 +tensorflow/include/tensorflow/core/framework/tensor_types.h,sha256=kzwP_glsbdp3jc1vI6cLMk2RV-TexMGYXJwylYLI47w,7031 +tensorflow/include/tensorflow/core/framework/tensor_util.h,sha256=0dNb5IqdIgycDWHAtvXDGb4QvHDxHvUFb78XAJkqAVo,13729 +tensorflow/include/tensorflow/core/framework/thread_factory.h,sha256=v8J1aool70W4pa9I5_RLXRXjs9pYWVFc4vSPpNg0ZGA,1500 +tensorflow/include/tensorflow/core/framework/tracking_allocator.h,sha256=Adnwm6jySjIP8y1Sy_2APWuMvQu90MzPCh4npbpX_G8,1348 +tensorflow/include/tensorflow/core/framework/type_index.h,sha256=GnZAvo52SFZ5pBvO6MRxeOqaMzXnALbJ5at6tZT2HEc,3463 +tensorflow/include/tensorflow/core/framework/type_traits.h,sha256=qfIxLy7lCb4uyhwGMIx8w1vn7I2SqQTYIWrSM2zULvQ,1247 +tensorflow/include/tensorflow/core/framework/typed_allocator.h,sha256=MhqkSBkWsPLa4XwHbDtNjZrntMczh9o_FZeg_4pXJHI,4244 +tensorflow/include/tensorflow/core/framework/types.h,sha256=8OQg1uY5ucnGWtDYZZ06Joe1iCm6o6mQ26npIBZl0g8,20886 +tensorflow/include/tensorflow/core/framework/types.pb.h,sha256=0IhQtUeQIoZyTK0hVQF1UN25JEkn2Bel3D1yW5k8YII,11254 +tensorflow/include/tensorflow/core/framework/types.proto,sha256=P7L4a2aRUyz8YLleWFDmmTQbWAPKPUAgMneYPJnAtig,3212 +tensorflow/include/tensorflow/core/framework/variable.pb.h,sha256=WkwvfJIJOQ2rVmYeGqqdWVrrJd72jxugS9MdlM5VsiI,47200 +tensorflow/include/tensorflow/core/framework/variable.proto,sha256=vUUd9p-QDLDcyqfhO1xtJZsXcPFMOviJ7XxtVQF612w,2935 +tensorflow/include/tensorflow/core/framework/variant.h,sha256=FKN7jOECzpzzRURu0ogP8TF3kl9qfdaQKwmb4ghnXZo,21550 +tensorflow/include/tensorflow/core/framework/variant_encode_decode.h,sha256=gNFmk-DHPjSPwIlKKlo_48972uix20nzSmQpraNxlmU,9652 +tensorflow/include/tensorflow/core/framework/variant_op_registry.h,sha256=yd4AKaKOxwREHbwn9NRonKK-R7q1Lf8NegADvvKIb5Q,24836 +tensorflow/include/tensorflow/core/framework/variant_tensor_data.h,sha256=r-WHUKq5xfeETgnGhclWRPANiZAcWtDnwbYyZftDSG0,5036 +tensorflow/include/tensorflow/core/framework/versions.h,sha256=n74n5CU4nteAh2Joza25_iFeDx9QvbNumDSbLPUgNLE,1537 +tensorflow/include/tensorflow/core/framework/versions.pb.h,sha256=sCQJ87zUVUVtErIXdxZgMFM7I9LiLBONCLXryBg7j2A,12153 +tensorflow/include/tensorflow/core/framework/versions.proto,sha256=U6P-uRwJ-5cjyaMR1oZ-jVaT7leKWXKBlX88rY0vPG0,1057 +tensorflow/include/tensorflow/core/graph/algorithm.h,sha256=rvZeYvuy5x8CrKaszTb50ta-Lu_hdbLpNf5JnmxmAH8,6997 +tensorflow/include/tensorflow/core/graph/collective_order.h,sha256=bZV1WK0qZY9fx2KL2Otcdgazj5kukVdg1sRInMRXY4s,1569 +tensorflow/include/tensorflow/core/graph/colors.h,sha256=9dZtgYJCWfP7WMufZ60HAkLST-Ej0k7LLmOvNl3Ugnw,1110 +tensorflow/include/tensorflow/core/graph/control_flow.h,sha256=xXUruTkN-J6htQ-3hNLs8EDHlVkO6h-EcYhnbQyJMSU,2462 +tensorflow/include/tensorflow/core/graph/costmodel.h,sha256=nXBh-bX4TnbWHHRoXo5UE1V85LzcugfjoU3VBls_48c,8869 +tensorflow/include/tensorflow/core/graph/default_device.h,sha256=AfRbC0NZUGyOdBUYBM-VGkihAU2qmKB7uvvC1qry9LY,1379 +tensorflow/include/tensorflow/core/graph/edgeset.h,sha256=Ex359rxRfpiYLJSzJtlhJtz_XJeK-wJ8HhQgX8oWaBk,6612 +tensorflow/include/tensorflow/core/graph/graph.h,sha256=u6LAYZExmk_NwI6LXqGrGy47vqfPAEHI7soUkOv_tek,42918 +tensorflow/include/tensorflow/core/graph/graph_debug_info_builder.h,sha256=e46gDxe4mwFOwx70j7NYEYIrSZZ3f2S_IbhSlz4XW20,8013 +tensorflow/include/tensorflow/core/graph/graph_def_builder.h,sha256=QkQHL3Omr0C5Nawk3-XMjY19vDz_AtNupucdx-mGXI8,8199 +tensorflow/include/tensorflow/core/graph/graph_node_util.h,sha256=mfUCle0au3i5tw7mQRzAPVkzyRopbLuUAGU7Ae2TEKw,2814 +tensorflow/include/tensorflow/core/graph/graph_partition.h,sha256=tU7pb82bD-XPF2Sq-CjIgPjXB2-7XTxG8xb0wP-VCeI,4311 +tensorflow/include/tensorflow/core/graph/mkl_graph_util.h,sha256=LrqPWQTU6TNGm2pmDNBMNdLnQqs4gcSiv6BhZ4aaaW4,12409 +tensorflow/include/tensorflow/core/graph/node_builder.h,sha256=6WssWxwWwNQ6E8dszYFaQMs_94vP0NO8y1e8vygWicY,6897 +tensorflow/include/tensorflow/core/graph/optimizer_cse.h,sha256=nJrVI1760kubazY1KafOcarAAu7gA1vPLxZ20KHCAfw,1409 +tensorflow/include/tensorflow/core/graph/regularization/util.h,sha256=Q-K_CwYloSuR19-eoadWSo3vTbNo5WHKIBmsvMAUQj0,1336 +tensorflow/include/tensorflow/core/graph/subgraph.h,sha256=IV00EIv-clQ8SQh1W5iJ8NP6Bx5TCWvR8xmoI2yJU1o,6908 +tensorflow/include/tensorflow/core/graph/tensor_id.h,sha256=_2nfczKjDBTVLcnZKS1OmfEpAZLarom1Kipn8MBoOXA,3019 +tensorflow/include/tensorflow/core/graph/testlib.h,sha256=IJvvcvz3kj2lXykGglDDoGXfOtif7zfclXbhy3VOWiA,8768 +tensorflow/include/tensorflow/core/graph/types.h,sha256=40WA8FifIEqtGGDd9MLU0SUoILQNzAGu33QPe4c66f8,1222 +tensorflow/include/tensorflow/core/graph/validate.h,sha256=qfErT72Fy_ZAQC7mHUW-WoUCWWVs-ucYuxVTZTesKl8,2938 +tensorflow/include/tensorflow/core/graph/while_context.h,sha256=kBaN0NgdbShVetRh4IYqVmE0xI32jY0vx8MAE_gz5Ss,3183 +tensorflow/include/tensorflow/core/graph/zen_graph_util.h,sha256=K8nG6z6IsXPKDcLBf4ErbX-T3qOVclDuSoTsLXnv5EA,3102 +tensorflow/include/tensorflow/core/grappler/clusters/cluster.h,sha256=s2vOJj139qjR1ly2mtv5Cvsfc98W6RTxRp_DCUCokGI,5792 +tensorflow/include/tensorflow/core/grappler/clusters/single_machine.h,sha256=vnhpSR7qPLnt3E1Kb_5YymB0mD3F-X1r8nGlCFiSoKo,3401 +tensorflow/include/tensorflow/core/grappler/clusters/utils.h,sha256=bsDV9fGlwy2AjC_pXTf5e9v9_GmUw9dHYZz-UeJUPS4,1524 +tensorflow/include/tensorflow/core/grappler/clusters/virtual_cluster.h,sha256=e1_yOlwS9LN3zFikCC6ezhuPjTOU3pMjlmaJAulb6vc,2554 +tensorflow/include/tensorflow/core/grappler/costs/analytical_cost_estimator.h,sha256=F8yl7S5VodrmF-eYFqlulBAtrdZUM2tstXlczZfX3Ew,3422 +tensorflow/include/tensorflow/core/grappler/costs/cost_estimator.h,sha256=Kllrn4EBh6RwD-yHwBWQpBJKpNqrtu-wyvmcLI0upA0,9506 +tensorflow/include/tensorflow/core/grappler/costs/graph_memory.h,sha256=ntkQjh1-Yi58DDU8vx0h4rUGU1QiRNi9Izy71p4u7eI,2837 +tensorflow/include/tensorflow/core/grappler/costs/graph_properties.h,sha256=xddwu2aZt8NCMScsS60vflC2SKvMU7Y9OqQxv_97hXI,9968 +tensorflow/include/tensorflow/core/grappler/costs/op_context.h,sha256=ZkUmPuzwiSzC9E6kfdfazQRhLgrKkKc7rLvObwX8v34,1719 +tensorflow/include/tensorflow/core/grappler/costs/op_level_cost_estimator.h,sha256=BU3_2dXr18DwCoywvhSZqzpW8WXPSy-qL7Q2oq96zsI,15409 +tensorflow/include/tensorflow/core/grappler/costs/op_performance_data.pb.h,sha256=oNtFO7kNWGzq_OYyYd6sH9WcWQ48nSnELiZQCm1ARlM,121183 +tensorflow/include/tensorflow/core/grappler/costs/op_performance_data.proto,sha256=6_-I8Qzd2ZHBBoSlg-cqKzpSj5GX3q8rOW8ERZLyFbA,3604 +tensorflow/include/tensorflow/core/grappler/costs/utils.h,sha256=0p-N1leHKXvlA3d_APcJtTdt_LpTiJeHS0Q7_v94Spc,5180 +tensorflow/include/tensorflow/core/grappler/costs/virtual_placer.h,sha256=mbhMk7FFqvmE4hXiE8JstWwD19YD_dYOVbWjfs8YNzE,2248 +tensorflow/include/tensorflow/core/grappler/costs/virtual_scheduler.h,sha256=q6UYpva1UEbhTCc0IYI9ijy9UHYlI3JFb4rQlP-x_PM,22466 +tensorflow/include/tensorflow/core/grappler/devices.h,sha256=W7pdoT4Sy4yR8aj8RvhXTU5h0oIj7XhzdeRMyC7yncc,1614 +tensorflow/include/tensorflow/core/grappler/graph_topology_view.h,sha256=MVmd0gujnBhJSPrU-WunJ-lKhZxoiQs95wsit5Bpv1A,5355 +tensorflow/include/tensorflow/core/grappler/graph_view.h,sha256=jd4NheNoYcxEYnLXT_74ZEGyWsbstsQ7uFvDgVa-KMY,15585 +tensorflow/include/tensorflow/core/grappler/grappler_item.h,sha256=i1XwAuFuGUGrtBrhnxFurlN3kUPd0tkxkkBUuAj5cmo,5793 +tensorflow/include/tensorflow/core/grappler/grappler_item_builder.h,sha256=KZ7fuvJ8ktMmIz3ePCDtVf_QNCNqv01OEg9Nrn4YKzg,3247 +tensorflow/include/tensorflow/core/grappler/inputs/utils.h,sha256=_W5jNf0ODUENJmbzCm0JwXsG6yjUSsj38ioUGFam2V8,1710 +tensorflow/include/tensorflow/core/grappler/mutable_graph_view.h,sha256=nDJqxQzCCyeed7QuH7mMHy3tHLjMz7-u7TLGw2p30h0,15708 +tensorflow/include/tensorflow/core/grappler/op_types.h,sha256=cvuOk_hlXJhi5SWcc0xw-7d8I9InRtDwRYXNxA28qB8,11092 +tensorflow/include/tensorflow/core/grappler/optimizers/arithmetic_optimizer.h,sha256=v1HHL2QNn6tknGr9zzJAqwBkW3xELY8Gz_LLV6TY0Uk,5626 +tensorflow/include/tensorflow/core/grappler/optimizers/auto_mixed_precision.h,sha256=peg2HKCHFBtE8IXg5jKaVuYRF8MG5c6YZaWeIW83dl4,2557 +tensorflow/include/tensorflow/core/grappler/optimizers/auto_mixed_precision_lists.h,sha256=VPmeb10uGFmFjjWKNKuKtAh8yUbc0HAdn9MIIUcwgjo,17271 +tensorflow/include/tensorflow/core/grappler/optimizers/auto_parallel.h,sha256=WLXYvhvRRqDE5a2D_NpgzmaBx_xS31hvf_ZvTdpxxzU,2346 +tensorflow/include/tensorflow/core/grappler/optimizers/common_subgraph_elimination.h,sha256=QCejAX7-qzP5Xv4HlhvTm4G9_Rl38V5CURjGHilxbdE,2378 +tensorflow/include/tensorflow/core/grappler/optimizers/constant_folding.h,sha256=qLv35w8D4P-CS_DiGfureQi7RAhjxDmNZvkKNBXRONw,16718 +tensorflow/include/tensorflow/core/grappler/optimizers/custom_graph_optimizer.h,sha256=CbD2ARornudVN6zHXaVS0MZTPxDh-ZYKB-W4xJjbj74,1803 +tensorflow/include/tensorflow/core/grappler/optimizers/custom_graph_optimizer_registry.h,sha256=Kw-hC2-bz1pUZfHQmUFVbxzDRtpqCkh9KTG2KCJnU3c,4832 +tensorflow/include/tensorflow/core/grappler/optimizers/data/auto_shard.h,sha256=6GfdXeA72aZ3K96a_SzDzDIk3fjSAGhLH78tQ6U3vlw,2146 +tensorflow/include/tensorflow/core/grappler/optimizers/data/autotune_buffer_sizes.h,sha256=DEjj3WKazaosoD08uEYdZNV15McMtwX9oD8b8GT9tF8,2680 +tensorflow/include/tensorflow/core/grappler/optimizers/data/batch_parallelization.h,sha256=naA8AQP2Fr3OLgyOOOq_r0ehKrmhuWR7GlXYGA9GyhQ,2240 +tensorflow/include/tensorflow/core/grappler/optimizers/data/disable_intra_op_parallelism.h,sha256=BaeE71eEW1Ud1n-HhpgIRrzlBl0obLK9DxDic8Imbgo,1769 +tensorflow/include/tensorflow/core/grappler/optimizers/data/disable_prefetch_legacy_autotune.h,sha256=LbThlemZxTR76qUH8MqBlKeLt74yIpU-AkzI237vcjQ,2341 +tensorflow/include/tensorflow/core/grappler/optimizers/data/enable_gradient_descent.h,sha256=qUapJeG5e2aqMmB1mWZZfO6KFVVCCxQKY3hVB7o4R8w,2281 +tensorflow/include/tensorflow/core/grappler/optimizers/data/filter_fusion.h,sha256=TRy_IX8JMNwsnueSm1edRa2-txzWXbvTJDoYuu1bH1g,1665 +tensorflow/include/tensorflow/core/grappler/optimizers/data/filter_parallelization.h,sha256=spvkoujoTs98HilOJ0JFPbNDAbPgfNbfhiComlr8Lsk,2275 +tensorflow/include/tensorflow/core/grappler/optimizers/data/function_utils.h,sha256=j9nXvjxnek4GU4wL7jhlXN-C6nxIhB4u1NoAmIdMIc0,5847 +tensorflow/include/tensorflow/core/grappler/optimizers/data/fusion_utils.h,sha256=NJPNwQI4KSa3gD_oClcPz9gsF9ySSpDtxvYjVyP_v2g,6447 +tensorflow/include/tensorflow/core/grappler/optimizers/data/graph_utils.h,sha256=K23jUG1wTlOuwUrNQqta5gXYWV27XbhysTHMV0j9zFI,9110 +tensorflow/include/tensorflow/core/grappler/optimizers/data/inject_io_prefetch.h,sha256=_1WdzZdPwZlSXdos_LcZbyEzP-_g7Z0rwM9WiXPOEXQ,2351 +tensorflow/include/tensorflow/core/grappler/optimizers/data/inject_prefetch.h,sha256=Uw-7XfKd-HGTAiriiGKLag-EAyCAPvjJ-cYmQSDnpyQ,2311 +tensorflow/include/tensorflow/core/grappler/optimizers/data/make_deterministic.h,sha256=qvHvADuy5K77hlXRkqn4Se0bC299-xk61Zy_D2YatSc,3534 +tensorflow/include/tensorflow/core/grappler/optimizers/data/make_sloppy.h,sha256=h4_voLejRGF6EH3AeUmgOMx3OHNKn66dCEVw_qG5rhI,1599 +tensorflow/include/tensorflow/core/grappler/optimizers/data/map_and_batch_fusion.h,sha256=q866adGcAiT1XaZBOewDNqyIK3IAsCLL9QFStJTqI-c,1657 +tensorflow/include/tensorflow/core/grappler/optimizers/data/map_and_filter_fusion.h,sha256=3cOMu0eIrFWN7hL7p9UfLFNahC4pDfsMP4LAvOe6Ghg,2222 +tensorflow/include/tensorflow/core/grappler/optimizers/data/map_fusion.h,sha256=KKTGT0-3JOZ7psxvORoEQE5aMLEiqmLI992QjAYEH7g,1672 +tensorflow/include/tensorflow/core/grappler/optimizers/data/map_parallelization.h,sha256=SR-ebb73nuusnMV3mMW543pKRnQJP1YbfD-KpQkBd4w,2251 +tensorflow/include/tensorflow/core/grappler/optimizers/data/meta_optimizer.h,sha256=SqVXITtcSKmgzoeROMfvMKIIHLEJyVICFkf70XsLQl0,1994 +tensorflow/include/tensorflow/core/grappler/optimizers/data/noop_elimination.h,sha256=XImm9MWzunSKwIRRsxQSsP_O38JcwgnCl0KEAqVa1_w,1760 +tensorflow/include/tensorflow/core/grappler/optimizers/data/optimizer_base.h,sha256=ol204jlSejKJ3g4N8xo3VBIC4Uvjux2KLSysDtKBRuw,1744 +tensorflow/include/tensorflow/core/grappler/optimizers/data/parallel_batch.h,sha256=cxsT1yO0HnJuoEjcwe42jU9vKOYjTnYa1QMON-6iErk,1620 +tensorflow/include/tensorflow/core/grappler/optimizers/data/remove_compression_map.h,sha256=rVI0NsbM847JIS9tYNDMhWOVd5kuN6p5kNw5uoylHn0,1673 +tensorflow/include/tensorflow/core/grappler/optimizers/data/replicate_on_split.h,sha256=lFQ_dITC2A_bZciQtodO9imhADOMpk002ArZLGBP2hE,1645 +tensorflow/include/tensorflow/core/grappler/optimizers/data/shuffle_and_repeat_fusion.h,sha256=RRZG6NcMcKjdvBSqBdLZFCHHEXMUb7Rbp9ld6AUcRJo,1692 +tensorflow/include/tensorflow/core/grappler/optimizers/data/slack.h,sha256=hHqRoB1qMiFbzOOYkc71frqiLa94OjEIG47LX4Q_PEc,2342 +tensorflow/include/tensorflow/core/grappler/optimizers/data/split_utils.h,sha256=XCp39qiFRi8Mkvfg3RceFFKCmCEcQdjy8B2s_1xjWJU,3065 +tensorflow/include/tensorflow/core/grappler/optimizers/data/use_private_thread_pool.h,sha256=-76qJA51oGPifAxqR3Xcb7brCpfFwI9-UT2iho1j-F0,1751 +tensorflow/include/tensorflow/core/grappler/optimizers/debug_stripper.h,sha256=lcBVXlyx1PImYGPob0d4GXiIcfy_11YgKsAjfXf_d1Y,1480 +tensorflow/include/tensorflow/core/grappler/optimizers/dependency_optimizer.h,sha256=SO8OXer7p3ZrlAVaS8APpsVZTDdPWdyiIwrQYJ3hL-0,3697 +tensorflow/include/tensorflow/core/grappler/optimizers/evaluation_utils.h,sha256=b-A5aSKdqZo--w9Fa9xRDkGu3GkBL-qiZX_1TC9M-Zw,2089 +tensorflow/include/tensorflow/core/grappler/optimizers/function_api_info.h,sha256=cKdQ6Z4r1EAgu-0viSBkRSHkSh_xNpvVbDP4ABZtc_E,4052 +tensorflow/include/tensorflow/core/grappler/optimizers/function_optimizer.h,sha256=U0NgeptSZGlmsCtHbKPy97hiaJztsz-30fYE27Ofo6Y,2346 +tensorflow/include/tensorflow/core/grappler/optimizers/generic_layout_optimizer.h,sha256=qxO0pWxfhl3LrCNXjZ98-jjiS4XMg7X2hvzAL50F79I,2497 +tensorflow/include/tensorflow/core/grappler/optimizers/generic_layout_optimizer_transposer.h,sha256=bfqWP8RdC-U3PMfikIvLmgM357CgVZ8Cp2kKyw2zkXg,25887 +tensorflow/include/tensorflow/core/grappler/optimizers/generic_layout_optimizer_transposer_factory.h,sha256=ljwVbmtZ13nOq6nC4CchG03wISpPFUjOpOYS4q5OYGo,1680 +tensorflow/include/tensorflow/core/grappler/optimizers/graph_optimizer.h,sha256=cPTbUp6LUE02NCaLPeyIUDC4NyG9rBr5JOODgJVscRw,3679 +tensorflow/include/tensorflow/core/grappler/optimizers/graph_optimizer_stage.h,sha256=ggaedNLTlJalyy3T1Nc30-LwBmpLjhRpK46v1S0bAns,12682 +tensorflow/include/tensorflow/core/grappler/optimizers/implementation_selector.h,sha256=sZuSKwSDAq587IXoHUAWBgP-HmC1PLyxyLsepGzBCAc,6963 +tensorflow/include/tensorflow/core/grappler/optimizers/loop_optimizer.h,sha256=Nll1soWmJsSP4rvaoTbmmWQPN7TpMYPWjONxOqluY3g,2601 +tensorflow/include/tensorflow/core/grappler/optimizers/memory_optimizer.h,sha256=BkiA2qAOWdnSB3vt_r3xd8FTXHQERVstXgwHr7QrxGY,2280 +tensorflow/include/tensorflow/core/grappler/optimizers/meta_optimizer.h,sha256=im-vPIn-bTOn58h4sPA0qwfIeD8A-x_pBQHDsVBFbWk,6856 +tensorflow/include/tensorflow/core/grappler/optimizers/model_pruner.h,sha256=oMeR_pfN_9XtkBxXf5tVRfLToPWOHbyGWYEAhD38ZgM,1489 +tensorflow/include/tensorflow/core/grappler/optimizers/pin_to_host_optimizer.h,sha256=Sulamyx_3kjj-RZmja6SgasLieL4LGuvH3lYhJFokK8,2286 +tensorflow/include/tensorflow/core/grappler/optimizers/remapper.h,sha256=DgjIXXb9MzGdeScmythTscTA8SJI0y2SmKaAGEkEvgA,2069 +tensorflow/include/tensorflow/core/grappler/optimizers/scoped_allocator_optimizer.h,sha256=STzIMUnI7f7GZoIUghTeTcvCRJPE9USQpvRg5qyfWLk,4673 +tensorflow/include/tensorflow/core/grappler/optimizers/shape_optimizer.h,sha256=RjS0UET3x_AQab9Qy2tsk6RA26Gf4t2dwI3kRCjXvgU,1783 +tensorflow/include/tensorflow/core/grappler/optimizers/static_schedule.h,sha256=Xrm6xB_mms3jUwUjuie_4k5UlAzsigO7dGOFvfHv898,2165 +tensorflow/include/tensorflow/core/grappler/optimizers/tfg_optimizer_hook.h,sha256=2E2sE6_WFtheIiDWKH05jSJdwdKuIzhxm9ZT8yZ3CF4,2617 +tensorflow/include/tensorflow/core/grappler/optimizers/tfg_passes_builder.h,sha256=yMnz-gifZxhGggptZyJLGgdGNDzIXVOQ5lTBq-rQlno,1468 +tensorflow/include/tensorflow/core/grappler/utils.h,sha256=H8SmMdTZLn9gp3awK7rwVaqgiDmOy5rzmTKDF322288,15735 +tensorflow/include/tensorflow/core/grappler/utils/canonicalizer.h,sha256=E1_fJ_sH7MtZBrI2_mKzzK8KrIF7J8FP7DC9iaWH6ls,1707 +tensorflow/include/tensorflow/core/grappler/utils/colocation.h,sha256=VDOZk-szReEx54pnZmISCsw_Et-VkWbXMgcF4mMYJq4,1706 +tensorflow/include/tensorflow/core/grappler/utils/frame.h,sha256=zgYqZCeeyrNhH5CMVKlFsN_Q8ob-wX2oaPVISj8bHjY,3037 +tensorflow/include/tensorflow/core/grappler/utils/functions.h,sha256=_iLEjbILAXFzLqrWp2qOQqq7RHZbi3AZjy1V1N1ucSw,8102 +tensorflow/include/tensorflow/core/grappler/utils/graph_view.h,sha256=ns0_NDSVmsw_sj8-Sxjh0xWAYOl-hECqI7t3xANqccM,20182 +tensorflow/include/tensorflow/core/grappler/utils/graph_view_internal.h,sha256=SLjEwVcBw2i620GyA7damsYcvQgdvfQzOSTwt8C57II,34101 +tensorflow/include/tensorflow/core/grappler/utils/pattern_utils.h,sha256=fivWJy5l6_NCNBBoPtVgbPjGRm53FeVqcxqtfVdlEa8,8684 +tensorflow/include/tensorflow/core/grappler/utils/symbolic_shapes.h,sha256=mLJ7jyOxXzV7RPFQyqjEEjmG1JHLOs8ewCbaAucWH74,3617 +tensorflow/include/tensorflow/core/grappler/utils/topological_sort.h,sha256=5MoHqhRsFVQUIUNPNLW2T6zBk6-Ila155tyvmvQD3hc,2310 +tensorflow/include/tensorflow/core/grappler/utils/tpu.h,sha256=oP0V9ykm2QjqBxHSpsuDufXM9806P37bOSUMbIFdkqA,1122 +tensorflow/include/tensorflow/core/grappler/utils/transitive_fanin.h,sha256=LGrvJOn51XZQmc3rLjM-DAfuy5h1FzRe4LEVHcQHWyQ,2164 +tensorflow/include/tensorflow/core/grappler/utils/traversal.h,sha256=2SB_dWbnR9m-aBEz5Ehc7Deco5nS77ByycLgr6q5HXQ,4222 +tensorflow/include/tensorflow/core/grappler/verifiers/graph_verifier.h,sha256=kWrS1LYKkBdl4fF7FHFVQ72bhslZnWjNU71MHwLXXCY,2119 +tensorflow/include/tensorflow/core/grappler/verifiers/structure_verifier.h,sha256=58-UIo6Dd9dL9AgWmeYCyoCTYMpey8POuqkAxNiuqRE,1467 +tensorflow/include/tensorflow/core/ir/dialect.h,sha256=Q7quNwaR4y2l-ygQtX5ydGPDGQqcusPivaX-gV4NueE,3704 +tensorflow/include/tensorflow/core/ir/importexport/convert_attributes.h,sha256=JX89uHnj3dDfe3VC2yE1RtSxoMYBjIVgCPdrYmgC63A,3731 +tensorflow/include/tensorflow/core/ir/importexport/convert_tensor.h,sha256=HNnAIWgQ84_eTzizLqBfOCVtMeLOmi7qSMIEF6KAivA,3981 +tensorflow/include/tensorflow/core/ir/importexport/convert_types.h,sha256=7bhGBRGH8J3aQcHdIqBl3JrWEClT2-42i6TmSaV3SAo,2465 +tensorflow/include/tensorflow/core/ir/importexport/functiondef_export.h,sha256=h282m7nLfu_TjEtv-l287wrvmThIyJK6sw-KR_tHuMY,1371 +tensorflow/include/tensorflow/core/ir/importexport/functiondef_import.h,sha256=Hqp67_j7VOW266g0YCc_rE0OUr7BvcK3WGeAOn5ppRI,1483 +tensorflow/include/tensorflow/core/ir/importexport/graphdef_export.h,sha256=iezcmhQoVm_eidhR2GHCgOQEwoEUziwvVP0IUIksL5g,2460 +tensorflow/include/tensorflow/core/ir/importexport/graphdef_import.h,sha256=S7QmRK1sgSiFqCM-yMqgim36YhoGGDZqIvqpBgbIsTQ,1856 +tensorflow/include/tensorflow/core/ir/importexport/mangling.h,sha256=Wh-RR6eS26MOmnOfX6BQSZEy84cj8Qv3LFmbJw-wKws,3139 +tensorflow/include/tensorflow/core/ir/importexport/parse_text_proto.h,sha256=n6b5aroSMwRJPKsuNEB7a89kbqNhHPVPA2lWurtkYXA,1962 +tensorflow/include/tensorflow/core/ir/interfaces.h,sha256=Th-XzypfCSAhUoQBSRU9CGEMBAO5hcqSjr5RmhJEEW4,3019 +tensorflow/include/tensorflow/core/ir/ops.h,sha256=1nVywuputUOtIKn-CnvUDEgHhMd_ZSQquK8ytqHvGg0,2569 +tensorflow/include/tensorflow/core/ir/tf_op_registry.h,sha256=7wF3YFk5Qm78Xpkj3vg4HlbzKwmOs9bwHUAfxo8GSIw,1821 +tensorflow/include/tensorflow/core/ir/tf_op_wrapper.h,sha256=EG1WmFld0KSfMNGAZBwXOgMLhyz3MsuGvWvYYfUITbs,6878 +tensorflow/include/tensorflow/core/ir/types/dialect.h,sha256=nLhZGI0bkT-ENJTZcYaalTUvL-2ZL1JsPRg1OH8zuOo,13768 +tensorflow/include/tensorflow/core/ir/utility.h,sha256=_aw4TDeeH6mx33yYMF467lkKTrp29WnuPp0_OgSNH6I,3752 +tensorflow/include/tensorflow/core/ir/utils/shape_inference_utils.h,sha256=XA1J7502NWWSByUOad2pLPa34_K8M6WLWbMeMwShjEk,4320 +tensorflow/include/tensorflow/core/kernels/aggregate_ops.h,sha256=bnYVnP9OXjkuR3-CIjF0NRLBgCMw2W9Uzpu6vFCUGxk,9074 +tensorflow/include/tensorflow/core/kernels/aggregate_ops_cpu.h,sha256=-3LI5BFKGN1fxkHyxCBe_HvtgxSPdXcAWUTSbtii6lI,5741 +tensorflow/include/tensorflow/core/kernels/argmax_op.h,sha256=s40DOvDHHdmXd0cO4gpLgeiEoRu9jf7-UWfhJ92z5yI,2540 +tensorflow/include/tensorflow/core/kernels/assign_op.h,sha256=yTaKY4z7zqmgFpq94jvVd-hoxA1Z1i_0YESuRugMMpg,2526 +tensorflow/include/tensorflow/core/kernels/autotune_conv_impl.h,sha256=v2iLUYx6W638bA3fQ9bpfUVaWblPhTBYiXJ1Ps3-UWg,3934 +tensorflow/include/tensorflow/core/kernels/avgpooling_op.h,sha256=UDEqtFN3yQgV_pmf5S7NK0kL2SKeU8dmQaywwbEWtqg,3210 +tensorflow/include/tensorflow/core/kernels/batch_kernel_test_util.h,sha256=BUAmA2FJ1DmpRzIuzRa1AHXlmNJEmqgqzpQNNZeAQDg,1771 +tensorflow/include/tensorflow/core/kernels/batch_kernels.h,sha256=uYx_VaQNJ_l52G-yA2unS_ExoREQODLOFBdFZDYvWdI,5368 +tensorflow/include/tensorflow/core/kernels/batch_norm_op.h,sha256=6rV1NPPy1j7qyJbJ0sJu6uIKPRmwW4vQp5ET6xDf7D8,6064 +tensorflow/include/tensorflow/core/kernels/batch_util.h,sha256=bYj2FL3DFqTtT3pTe7ZMb3_b9wT2kcfyn86fjCj6-L4,955 +tensorflow/include/tensorflow/core/kernels/batching_util/adaptive_shared_batch_scheduler.h,sha256=y-3GuEloMoX6cYPvGQj6K9U7s6dgNqbUUTmIowfc-Q4,35356 +tensorflow/include/tensorflow/core/kernels/batching_util/batch_input_task.h,sha256=afnaPsgs42l5zUtmk352ya-uA-eN4aqNbmBZO1GB4L0,9183 +tensorflow/include/tensorflow/core/kernels/batching_util/batch_resource_base.h,sha256=hyWa4PjXGbRfjJqpmOsFWEeqSS4IPKla-rnEnrGRWII,13934 +tensorflow/include/tensorflow/core/kernels/batching_util/batch_scheduler.h,sha256=4SFGglUdYRkZ2aljyCaMot2kZQQAQWrTYfZFKWok34A,10742 +tensorflow/include/tensorflow/core/kernels/batching_util/bounded_executor.h,sha256=xzbHSk6w8wM6plnV5WqwsmFZAZBytMmDm-tR170nIw0,2658 +tensorflow/include/tensorflow/core/kernels/batching_util/concat_split_util.h,sha256=TzOoUS1Xbn1TpUfFtotMyWHdFJfAimQQWeptFcwBB6g,9299 +tensorflow/include/tensorflow/core/kernels/batching_util/input_split_metadata.h,sha256=gxG_swaX9ixfQ9_YyLKYDlsTnK2eDsDbUFMC1huqdeU,2092 +tensorflow/include/tensorflow/core/kernels/batching_util/periodic_function.h,sha256=zBbFUdhqd5K4IdfD-VOkGnp9Y1eOJ7oLmU1y1fTPfhE,4593 +tensorflow/include/tensorflow/core/kernels/batching_util/shared_batch_scheduler.h,sha256=zOh1pdLt8435wmIg-Xd9l8R9GiTtB01M_3fJVsJHkZo,49606 +tensorflow/include/tensorflow/core/kernels/batching_util/threadsafe_status.h,sha256=SHL24PtpLe7SQJyKf5nFDuadqIdq-kH2oUH4MfhL-5M,2115 +tensorflow/include/tensorflow/core/kernels/batching_util/warmup.h,sha256=ZTEk3oAS0ny3PHO4QJJeu4XmfbHIU2OajQmJrOUC48Q,4157 +tensorflow/include/tensorflow/core/kernels/betainc_op.h,sha256=1qvXXkgFj8ogX7v8JOsLGgfGJTQVVaocC_waaH0Vn70,2104 +tensorflow/include/tensorflow/core/kernels/bias_op.h,sha256=0akNWg5nOoYlPjpjKROt0JBLHPZw1PSfBbm_hTBmUUQ,2447 +tensorflow/include/tensorflow/core/kernels/bias_op_gpu.h,sha256=pYVu8upUPlAnBhpi280ozJCbBzVH2RH8o5Ls3gn-Fw0,2910 +tensorflow/include/tensorflow/core/kernels/bincount_op.h,sha256=snlDwKEpnA4uNm6HEs8Nt3caEFP1b7xF6L2arujouec,2001 +tensorflow/include/tensorflow/core/kernels/broadcast_to_op.h,sha256=IPSoDjFEW9lG1m8qLmCmSx3H7FQDIxztOqRfjDSOXas,3448 +tensorflow/include/tensorflow/core/kernels/bucketize_op.h,sha256=kLti7vj2xHboVl2ce60ep6tdqdsPo40qWMzU8jSrM4k,1520 +tensorflow/include/tensorflow/core/kernels/cast_op.h,sha256=GMg_6YgPkS3Xclls25B7M5AuutWbiRPcfBCfswGlRcI,14480 +tensorflow/include/tensorflow/core/kernels/cast_op_impl.h,sha256=sj0bI7QvD19oNGxmUSgatdVWjx0BgovtyZ6deXKQPYQ,6866 +tensorflow/include/tensorflow/core/kernels/checkpoint_callback_manager.h,sha256=fFIudB2Ep8fpiim3Tpmo_VGErGQXMbfuKQLUEqXOLyE,4376 +tensorflow/include/tensorflow/core/kernels/collective_nccl.h,sha256=-qKrpGsD7kyU8ju8Mi60TVE2sdr_5t2YFCHP9r-eNi4,1626 +tensorflow/include/tensorflow/core/kernels/collective_nccl_all_to_all.h,sha256=dIJ_3Cr2V-WiEmVphb6-bvw5zSjAr79ZSGc6vBFbpZk,1291 +tensorflow/include/tensorflow/core/kernels/collective_nccl_broadcaster.h,sha256=G2T0m8IsGvdd9BZxoy4Rdvr6nIzVcsVH8dCWJf2-Wvw,1302 +tensorflow/include/tensorflow/core/kernels/collective_nccl_gatherer.h,sha256=DLBgkaGooyCpD5P5tk8H3iztmX9CtNmwM73tE6-Gd7M,1279 +tensorflow/include/tensorflow/core/kernels/collective_nccl_reducer.h,sha256=l06hiSQm9LdSzER9oG25PFE0J6bxUwYSMexVt1_VCbc,1596 +tensorflow/include/tensorflow/core/kernels/composite_tensor_variant.h,sha256=z7kKKbaYw0uqsT2EVR-7FzZMg_vrv7epoLITkxM3Tk4,3754 +tensorflow/include/tensorflow/core/kernels/concat_lib.h,sha256=E1EifrLXDbYX_DiVm9fSLxWshCwojz964XUk2cA2F_g,3244 +tensorflow/include/tensorflow/core/kernels/concat_lib_cpu.h,sha256=NlNILviVlaxp_lzjTAjDjt_0x9eGblG789kKy3CEv-k,4490 +tensorflow/include/tensorflow/core/kernels/concat_lib_gpu.h,sha256=ylbNZyHcS6TMHau2V5QlvAXh-Yoestc7EA9TL5aT7HU,3605 +tensorflow/include/tensorflow/core/kernels/conditional_accumulator.h,sha256=tFtuVW3dLEJgJ73KfeZtfZqIzPr8WXuo3-vAQWmga54,5657 +tensorflow/include/tensorflow/core/kernels/conditional_accumulator_base.h,sha256=sEPHjiyJuByhZgcD5GdKPGsKn5dNAvxio3woqbKKJ_U,7833 +tensorflow/include/tensorflow/core/kernels/conditional_accumulator_base_op.h,sha256=kDjW_vQuxL6KiHQfAGl_J05HMjPjs8DPXZYiE_ahv3A,9265 +tensorflow/include/tensorflow/core/kernels/constant_op.h,sha256=JJE2DlhD2-KRtcRSyGlyebxQh6Cs7lxCm1H4YK4wwcg,1747 +tensorflow/include/tensorflow/core/kernels/control_flow_ops.h,sha256=lpKSd78lsyl9UCQ6tN_wn_5hmUCCdHxvTZJjaCXVfX0,5230 +tensorflow/include/tensorflow/core/kernels/conv_2d.h,sha256=mdh66mmK_T9QIY-NaQqVKXfyN9gMYpFGBmFwKVURDjM,26617 +tensorflow/include/tensorflow/core/kernels/conv_2d_gpu.h,sha256=ivGiC04V1JROlFZJbTdAIriq1HU3vYSRLfKsGhND7eE,47133 +tensorflow/include/tensorflow/core/kernels/conv_3d.h,sha256=okzozGH7rSZu5_wlT_TRQt4r4U5CQkvsOAgASiSBlpU,5405 +tensorflow/include/tensorflow/core/kernels/conv_grad_input_ops.h,sha256=JDlTJ5j6jmcraSp3OXsS5COZ1GJEe__zjIHiDHjafeU,32062 +tensorflow/include/tensorflow/core/kernels/conv_grad_ops.h,sha256=c4Q7vY66n2_8Y-yomDuE4UmlyRbrof2OUZwTAeBwRzM,6229 +tensorflow/include/tensorflow/core/kernels/conv_grad_shape_utils.h,sha256=ZnuX4vLuXZh2rQ2z6x4rB0rvLrfOHiIsHvvtcgWbn-M,4173 +tensorflow/include/tensorflow/core/kernels/conv_ops.h,sha256=Bm8A7p9AIK-cD3W_8uWUIie8ah3wtKbx_slY5B3aFTY,5148 +tensorflow/include/tensorflow/core/kernels/conv_ops_fused_impl.h,sha256=I7oJ3j8NBYT5vGrLRPfo_TG_5z7kVIhZ5AY9xnt0XE0,37910 +tensorflow/include/tensorflow/core/kernels/conv_ops_gpu.h,sha256=iSSeXyL4pNW3_gibvsGty23H5WG2u7w76aoEUrdSLKc,9138 +tensorflow/include/tensorflow/core/kernels/conv_ops_impl.h,sha256=5G1umvCWkkJQZHvhmGe-NgmBPczhs4S2ei7rTIiqRy4,55845 +tensorflow/include/tensorflow/core/kernels/cross_op.h,sha256=avq50nQROWHY19X7YgBC_HxbhkQeZH447nHk8sjvzBc,1894 +tensorflow/include/tensorflow/core/kernels/cudnn_pooling_gpu.h,sha256=hJlIk-Rc9kMZ3IX1FZVbXz3PD_9dribaVGMjqgcrz8M,2509 +tensorflow/include/tensorflow/core/kernels/cwise_op_clip.h,sha256=yWT1hQQPah8hHd62GcCTEQw8_FG8OexaT4AGJXyEKpI,2467 +tensorflow/include/tensorflow/core/kernels/cwise_ops.h,sha256=_Ljm0934CRaAslqvuE_rKV5f2YZ9zIykY_uXwXbs4-A,44602 +tensorflow/include/tensorflow/core/kernels/cwise_ops_common.h,sha256=KfZvlK8sThissQTrac9dt-lrGioPmqu10vKCFsCLVKY,27525 +tensorflow/include/tensorflow/core/kernels/cwise_ops_gpu_common.cu.h,sha256=GLZ7ktFDZX6N4S2a9dl7-bmA54YieYgrhdLOZnUY5Ec,8767 +tensorflow/include/tensorflow/core/kernels/cwise_ops_gpu_gradients.cu.h,sha256=mq0ETgHX_5n0BimWa1RClskNzuJf0vVb1j-ku4g32Rk,2783 +tensorflow/include/tensorflow/core/kernels/cwise_ops_gradients.h,sha256=rZdVFgOTx7duASV3ygYqQ_KROSKiqxf0a9P8N0_NcnM,7034 +tensorflow/include/tensorflow/core/kernels/data/batch_dataset_op.h,sha256=gomuzM9fDhzYOslee7e23-Cw1vggyjq3Dw1MPTS8Fso,1787 +tensorflow/include/tensorflow/core/kernels/data/cache_dataset_ops.h,sha256=yyd_Uo19MS2FcHvNMePF9dQQkO74SQc4o9aRWAnQKtc,1743 +tensorflow/include/tensorflow/core/kernels/data/cache_ops.h,sha256=GYrwW2emaYjlD0DuehFkybYgIrjXPHgfHH5QZujvgjk,3231 +tensorflow/include/tensorflow/core/kernels/data/concatenate_dataset_op.h,sha256=PgxTE2cEhYrIcsEfOhDmMdN_eLxiP9NMkUG-GuL7ktg,1665 +tensorflow/include/tensorflow/core/kernels/data/dataset_ops.h,sha256=JeOoa9SXGxWgMvtwz_7WVLXoFfM8rmpznlJe2AkZ9k8,2448 +tensorflow/include/tensorflow/core/kernels/data/experimental/assert_cardinality_dataset_op.h,sha256=dvKljKujvqESlq-Cfum2oKG2sqKdb8Jy6RyIOWWazAw,1842 +tensorflow/include/tensorflow/core/kernels/data/experimental/assert_next_dataset_op.h,sha256=W2ayB2l9suCfIi8YprLjrtqiBWpwNz1ohAKBETBoB8E,1808 +tensorflow/include/tensorflow/core/kernels/data/experimental/assert_prev_dataset_op.h,sha256=jThkTd9_KBAZcPQnBIZFGJvLb4YFQ8enMtxvsEvZ7io,1753 +tensorflow/include/tensorflow/core/kernels/data/experimental/auto_shard_dataset_op.h,sha256=3wp-Y2d-C3MJFaYBtAJxOBsm3NTIlquf7ACXmJxRnPc,2146 +tensorflow/include/tensorflow/core/kernels/data/experimental/compression_ops.h,sha256=HQ4AZAbVbmLvlk4RLfwfRKKYxLZdiyOTOgieXJSExkU,1632 +tensorflow/include/tensorflow/core/kernels/data/experimental/directed_interleave_dataset_op.h,sha256=r-yWCJ07gwK4HkQshm2X_4t3X0u8cNyi0DQAXQU6JJ0,1950 +tensorflow/include/tensorflow/core/kernels/data/experimental/list_dataset_op.h,sha256=eyNxkbZiwGQfyayo7YHc7NLxCKEb4FkkUyDCuGYn3QM,1684 +tensorflow/include/tensorflow/core/kernels/data/experimental/lmdb_dataset_op.h,sha256=AVHPjIUyEt5o9dtyrmAUKOPYp-et_fhhRCk2crVxpfI,1550 +tensorflow/include/tensorflow/core/kernels/data/experimental/load_dataset_op.h,sha256=Ws9CUz9FLAP5XveDJITtni-zpZTltlYdIJekU_UVu2w,2243 +tensorflow/include/tensorflow/core/kernels/data/experimental/map_and_batch_dataset_op.h,sha256=VVxPwthpfAd_dANrLzL0gdkAKzRaH3wXwj8LXK1-Pps,2496 +tensorflow/include/tensorflow/core/kernels/data/experimental/parallel_interleave_dataset_op.h,sha256=poYbQdpo0zKykCvi0il8WL9p_Pp_FEUWGoS7SHAv6fA,2768 +tensorflow/include/tensorflow/core/kernels/data/experimental/random_access_ops.h,sha256=MPuWlVAKcLzaSilzRuJOiPr10_q7qqxg5-nK_zVUiGA,2261 +tensorflow/include/tensorflow/core/kernels/data/experimental/random_dataset_op.h,sha256=bi0N5YP1TaGHNRFezwRHlMSt5-0RNWI1xTzC4QPzjfc,2118 +tensorflow/include/tensorflow/core/kernels/data/experimental/sampling_dataset_op.h,sha256=zjOauUb3f-wD7_sqUOg0iBjHJteBQcsxtAFzbZF666g,2131 +tensorflow/include/tensorflow/core/kernels/data/experimental/save_dataset_op.h,sha256=cytSHAS5JpgTlrugzP1vkRMLFgZfAj4nGc0SlQqhdgQ,4260 +tensorflow/include/tensorflow/core/kernels/data/experimental/snapshot_dataset_op.h,sha256=LHhaiq7Nkt_MSUzolsTWzOqacxcIfwLWEO1WXQdTKg4,3770 +tensorflow/include/tensorflow/core/kernels/data/experimental/sql/driver_manager.h,sha256=AntFA340nMwHiR4E2RNWHnVobayRsZCHApabYf95S1E,1661 +tensorflow/include/tensorflow/core/kernels/data/experimental/sql/query_connection.h,sha256=ZbXMfxHlUfaIEbJI8lODwqLEKJnGyfFCB6lmtT1otp8,3071 +tensorflow/include/tensorflow/core/kernels/data/experimental/sql/sqlite_query_connection.h,sha256=zZuDnF8CmO3te1R7-IXAKAHeGB7FttG6blbswnygJMU,2112 +tensorflow/include/tensorflow/core/kernels/data/experimental/threadpool_dataset_op.h,sha256=dKyNFbM8xCAw1Y3oZ3gwPsrFR1LAAmwvzWp5ZUIA6jQ,2829 +tensorflow/include/tensorflow/core/kernels/data/experimental/unique_dataset_op.h,sha256=ONXo8CwmVcRHIW0Y3kFwRT71ETteyoqALxgPKl4scc4,1660 +tensorflow/include/tensorflow/core/kernels/data/filter_dataset_op.h,sha256=6e38s-PIYP6uK5yveXyRm8LRP2SEUnS3PQDrmwRnmf0,1847 +tensorflow/include/tensorflow/core/kernels/data/finalize_dataset_op.h,sha256=G807GH1mKYgbfAQsx837m_vk5_gMuamFbcUu74kaZwA,2158 +tensorflow/include/tensorflow/core/kernels/data/fixed_length_record_dataset_op.h,sha256=bEepgKpL9JnpqZYZLhmjjqngxGVmi4eZdY1hyaS6xgU,1785 +tensorflow/include/tensorflow/core/kernels/data/flat_map_dataset_op.h,sha256=_5YisB5Mim8JugaOU0URm6wkIIFCfUT9Y6tC_Ekfveg,1957 +tensorflow/include/tensorflow/core/kernels/data/generator_dataset_op.h,sha256=rZEP_BJ1U8SW6Tw-AS6MsTS4CzmRMiuyLgHVabeGlkY,2456 +tensorflow/include/tensorflow/core/kernels/data/get_options_op.h,sha256=Xp9KOkJjoUQ88oG1WMLCkyxGX9fSXiV-j5jaqk0xC6I,1304 +tensorflow/include/tensorflow/core/kernels/data/interleave_dataset_op.h,sha256=DeiXv4vjM9qxb89ZFEXLwqXSqVJTxGIqGomZWlQhL6E,2108 +tensorflow/include/tensorflow/core/kernels/data/iterator_ops.h,sha256=VH94ObRaF3-YsMXoLMHfAGtzV7VLp2XubpCpUk7WtnM,12161 +tensorflow/include/tensorflow/core/kernels/data/map_dataset_op.h,sha256=RTQgroDARKVhqrGYCRMvkzMHrisWsij_MSFFsggJPRw,2114 +tensorflow/include/tensorflow/core/kernels/data/map_defun_op.h,sha256=mQz6YZnmKVIcMZpd8c_QakQbkE1CXu1uRhday-2CHzg,3051 +tensorflow/include/tensorflow/core/kernels/data/model_dataset_op.h,sha256=0ayMi-WJTK2Xadv3fYhifMy0RtXJPCFoibmYAlB2skk,3302 +tensorflow/include/tensorflow/core/kernels/data/optimize_dataset_op.h,sha256=PQTIvGGkvxf1gRynQPJZ1E2FKBhOToqYsEzKDBcDmsU,3982 +tensorflow/include/tensorflow/core/kernels/data/optional_ops.h,sha256=oXKiEn7w_z_L23UCplq8t6LA90SjSRfuLQwAfz_951Y,3390 +tensorflow/include/tensorflow/core/kernels/data/optional_ops_util.h,sha256=z_FyqqNypldgVs-WmkmAD4A8RRV_6QGd_gJIKZ6Ytbs,4038 +tensorflow/include/tensorflow/core/kernels/data/options_dataset_op.h,sha256=GO5wmBvbI4K-hsyR8zEz3OTWfYDGnIFj58xCWc811hE,1671 +tensorflow/include/tensorflow/core/kernels/data/padded_batch_dataset_op.h,sha256=hwL6mNO-zNSgba5oXfnRClqIY1U30FyLRHt4_Jdu_hU,2031 +tensorflow/include/tensorflow/core/kernels/data/parallel_batch_dataset_op.h,sha256=0uHfSe9EIK6IEu40j3z-zMOnFNcicC1aFBlnOs0fSiU,2047 +tensorflow/include/tensorflow/core/kernels/data/parallel_filter_dataset_op.h,sha256=_j0Ko6MHKBddw-nltqzZgzTJjBWSLr8OycFG7I0d4Pk,2132 +tensorflow/include/tensorflow/core/kernels/data/parallel_interleave_dataset_op.h,sha256=WIr8OTIPaNISVimAfXnnnwryXLuDFnlWa53dUxIYXEM,2631 +tensorflow/include/tensorflow/core/kernels/data/parallel_map_dataset_op.h,sha256=irF51aE4SJX0xot_UMdlgakjjf8q-plnuDCiLVKvqkI,3062 +tensorflow/include/tensorflow/core/kernels/data/prefetch_autotuner.h,sha256=_oexJngzAvGzh4uFzyQC8t_1bFyhrR7-L4diZDOhbyo,3171 +tensorflow/include/tensorflow/core/kernels/data/prefetch_dataset_op.h,sha256=I39Se9-F0A2pKaOMgqQ-vyuQwmpwDRRCkeYePusd-fE,2029 +tensorflow/include/tensorflow/core/kernels/data/random_seed_ops.h,sha256=pULZz2YeGUwC7bNhNZMUWcpkOpen82Z3IlHT2jydiOk,5305 +tensorflow/include/tensorflow/core/kernels/data/range_dataset_op.h,sha256=jL7pKUayacPVLhf9VGzrjCLclqLE5sLlAHbih4yywSc,1747 +tensorflow/include/tensorflow/core/kernels/data/reduce_dataset_op.h,sha256=6EPFJfX6PXsavo5mKh5zwm1LEvOdDSewRxwt_dmJ08U,1522 +tensorflow/include/tensorflow/core/kernels/data/repeat_dataset_op.h,sha256=fCpzNPn39Dqcb-5IYIiPNISyx4noHWzRRtaNWvcmMAI,1586 +tensorflow/include/tensorflow/core/kernels/data/rewrite_dataset_op.h,sha256=QCDJdy-DuNoRFCRxBkNcykbQmy5aTDHQd_r3eZlvNKI,1577 +tensorflow/include/tensorflow/core/kernels/data/shard_dataset_op.h,sha256=0kxA9THHzVJvxAZgllyVHADNLvetI85Xej_RGlH4tPo,1748 +tensorflow/include/tensorflow/core/kernels/data/shuffle_dataset_op.h,sha256=4dSWi-hdQ9CdEcYxhM8fW9_JADpTy1Sp5cXT0SaI4k8,2590 +tensorflow/include/tensorflow/core/kernels/data/skip_dataset_op.h,sha256=7LK4kaeu1nzKJYP90xdib72LsLzAP6nRvB2Q8HurTTw,1574 +tensorflow/include/tensorflow/core/kernels/data/take_dataset_op.h,sha256=onb-TXbaHWCPCLAT5xVzGhu2IXjy-_M34RH6GLuZ1HU,2692 +tensorflow/include/tensorflow/core/kernels/data/tensor_dataset_op.h,sha256=hDC2jZXVilbUxFjt3x7bZHhQsBbd1p2TPn2hkMFsfVs,1567 +tensorflow/include/tensorflow/core/kernels/data/tensor_slice_dataset_op.h,sha256=glGwx3NttdvNqQYYFPDjacPal_ZP8ssQFO35thr1hUo,1800 +tensorflow/include/tensorflow/core/kernels/data/text_line_dataset_op.h,sha256=JkV_6P2ycxMAbwoEsb2OMSOF5zA4vYuSSSavpKpOr9c,1499 +tensorflow/include/tensorflow/core/kernels/data/tf_record_dataset_op.h,sha256=rAoJx5av4ThSy2ITs4GPcPS_J-TQgMuRwePyN-efZ6c,1586 +tensorflow/include/tensorflow/core/kernels/data/window_dataset.h,sha256=KliimqdclkISbD2E-VR_FLqaUMcml0ZPLcLWtriKRJ4,2029 +tensorflow/include/tensorflow/core/kernels/data/window_dataset_op.h,sha256=UcVW3giOwioxFSY_vTp1N1NxsPfwzpoI7pjNpHXgc18,1938 +tensorflow/include/tensorflow/core/kernels/data/zip_dataset_op.h,sha256=-xra_A6X4B30wUTyJohVnrSsnXWbQPcM23Tdr0smBq8,1533 +tensorflow/include/tensorflow/core/kernels/data_format_ops.h,sha256=lyndhEprIMbF53BZd0fm6sHxSn557-cqA6mF7iREU1g,3764 +tensorflow/include/tensorflow/core/kernels/debug_ops.h,sha256=vMXye0dOJsbTsQTgZszyaj6-Edt7R39QKd7TpdDFNdg,37090 +tensorflow/include/tensorflow/core/kernels/deep_conv2d.h,sha256=3HGc1S9HYsC6wpI-KHNk5pbaEo6y8GxXqDQUgTAM3Ng,3600 +tensorflow/include/tensorflow/core/kernels/dense_update_functor.h,sha256=onPYm1LCTbWJFc23KBuTZQRT6Ri6LpZFulXKqeU9VL0,2552 +tensorflow/include/tensorflow/core/kernels/depthtospace_op.h,sha256=ZWELGVfY_XMFkVEN4fmbSBzOyIK5UBj9k6Rfr9-zH1A,2632 +tensorflow/include/tensorflow/core/kernels/depthwise_conv_op.h,sha256=dtG0eLi7-KbzshT8UP_Kpj5wmuuVkd5PEiHVKZxsuNw,13705 +tensorflow/include/tensorflow/core/kernels/depthwise_conv_op_gpu.h,sha256=hjlIkGEHKBXIzoxeQ2sMRl472_JU8OM_NNZ65kif59w,77526 +tensorflow/include/tensorflow/core/kernels/diag_op.h,sha256=GVmSlH_fEaQieBz9WvbnVPGKRtwtHWYA5Iyqp_v7Ins,1395 +tensorflow/include/tensorflow/core/kernels/dilation_ops.h,sha256=Myfh5hQvUZsPBMawLAljKfThCy9S81CkW-guE6pewpE,2977 +tensorflow/include/tensorflow/core/kernels/eigen_activations.h,sha256=rzsBbdHs1DbgSTzvYpAzHnqNIKt2um1zMpjx53ojRzg,3836 +tensorflow/include/tensorflow/core/kernels/eigen_attention.h,sha256=mvGeqPbN63eK5XLqk_228Pa8Q2vsA07YqS44OyxnCUY,11967 +tensorflow/include/tensorflow/core/kernels/eigen_backward_cuboid_convolutions.h,sha256=2Ao9Hg4BydJviJz7X17ktJa3j1Aou5DvsUOeGtsOCFs,27525 +tensorflow/include/tensorflow/core/kernels/eigen_backward_spatial_convolutions.h,sha256=gdqs2Wm77cmN-B42vE0Wp9Po5eXz1P6-n6cwShKrxr0,26455 +tensorflow/include/tensorflow/core/kernels/eigen_benchmark.h,sha256=Udy0A7bmGGRJxyhEB3LQh0Krmvm_ntjMN0OOjXbP1sU,11632 +tensorflow/include/tensorflow/core/kernels/eigen_cuboid_convolution.h,sha256=RpqL8pu1IZ5D1T277Z-V6RXpXTWt_IEPEz7fY2BrE_g,85475 +tensorflow/include/tensorflow/core/kernels/eigen_pooling.h,sha256=Qp2iS-IyM1T3w6i4EDnn92JNUzhYY_4_BwgrTVxZOqM,21978 +tensorflow/include/tensorflow/core/kernels/fake_quant_ops_functor.h,sha256=c128pYEmqc93MEOiFqdxnZVb_4St76VC8H56mb8kZZ4,12229 +tensorflow/include/tensorflow/core/kernels/fft_impl.h,sha256=xTzFLJRz83ZceRHRlkBrFYZziFKVph5eZm_VgZVDu7w,1390 +tensorflow/include/tensorflow/core/kernels/fifo_queue.h,sha256=oipXQCVraOVomY-c1Yms620d6SbWX0yXfJ5dTVX7HsQ,3447 +tensorflow/include/tensorflow/core/kernels/fill_empty_rows_functor.h,sha256=C9AVjjs6uTSV3nhjwc5yOJyNlSd0k7awV0ULC_PKGbw,10792 +tensorflow/include/tensorflow/core/kernels/fill_functor.h,sha256=HXHt5n3ibaxZ1MMqJlLu0D3mubU_00SLVDXG22RBHQU,3157 +tensorflow/include/tensorflow/core/kernels/fractional_pool_common.h,sha256=8KimqOVXuJCe8Z-696TJ92iWkR3fclgkXkiHusW7Xpo,3177 +tensorflow/include/tensorflow/core/kernels/function_ops.h,sha256=rs2dzhvNEHEY--K4y2XoVK_x75VB9GLNwfJjyTlpUXU,2828 +tensorflow/include/tensorflow/core/kernels/fused_batch_norm_op.h,sha256=mPMGrWAVDn1RlsLSHugChK_O2dL5eXfiYXAxWbWlYI4,3069 +tensorflow/include/tensorflow/core/kernels/fused_eigen_output_kernels.h,sha256=kR4GNaM8C-QnPrLq6nG83auNHGO1aOnm2dOz9ng4jMo,16388 +tensorflow/include/tensorflow/core/kernels/gather_functor.h,sha256=GHsAnRjhPcSiiqy0zOv-YTbTqqpQAS2oFWbIcXsv94s,7814 +tensorflow/include/tensorflow/core/kernels/gather_functor_batched.h,sha256=PvymxOXuaVtZ8gCl9ZOE_-ggLrLPmz46-Nw6sr_Exwk,8180 +tensorflow/include/tensorflow/core/kernels/gather_functor_batched_gpu.cu.h,sha256=mKyXGoBT8r0eRnjGzGVYnNuU-pCQavjB5WbhFRNgBhI,7775 +tensorflow/include/tensorflow/core/kernels/gather_functor_gpu.cu.h,sha256=20TZ79DQeyn5PbR1dbhVOHPvSHQMba-lwpEJoGEzdDY,6765 +tensorflow/include/tensorflow/core/kernels/gather_nd_op.h,sha256=_MdL3RHcaG5ys2cnWMy31pF8C5USZgMDNgyyn37PHwg,6534 +tensorflow/include/tensorflow/core/kernels/gather_nd_op_cpu_impl.h,sha256=tLJsWyC9R8Z8AJ0rwt0dutGM_DEZIEthgMDx5t4kL-Q,5615 +tensorflow/include/tensorflow/core/kernels/gemm_functors.h,sha256=urI6lDAsZF3zRkMuGU_PqfiMK-CXUxNWDE-zdLpkbY8,6153 +tensorflow/include/tensorflow/core/kernels/gpu_device_array.h,sha256=95rvhXLlGCI6-AqI44nDh1ujLpxh4gjSBB0dSyi65ZE,4298 +tensorflow/include/tensorflow/core/kernels/gpu_device_array_gpu.h,sha256=FsnO20DROGIwWzKsFRp165QSYHHnP_i4G7yg2v_7XVQ,1817 +tensorflow/include/tensorflow/core/kernels/gpu_prim.h,sha256=-5taV_Xb1QNHN1aZJ2S8wE23DMGnR_iXODame0qb_4c,4251 +tensorflow/include/tensorflow/core/kernels/gpu_prim_helpers.h,sha256=u9Bcv2qalqnf8fPk10mKU-dIo7s1NTFUJFwj0AznsuA,12432 +tensorflow/include/tensorflow/core/kernels/gpu_utils.h,sha256=0MLT0CsfyXPaXJ8BpPIgpAZCqiFVZWfg-JpEun4nKCk,17421 +tensorflow/include/tensorflow/core/kernels/hinge-loss.h,sha256=ZQ-_dpIjVLxuR8qOV3zQjFbR8vRY26MVH7h4fPFVzZY,5347 +tensorflow/include/tensorflow/core/kernels/histogram_op.h,sha256=pPKTxZdMrQKBAS2DYP8sRIxzj1R0mCsyzkQyKBwrCaM,1490 +tensorflow/include/tensorflow/core/kernels/host_constant_op.h,sha256=7ea2AZNtL8vSbsCO4K86lv1y2CSJ8LG7VNwiPFFu9GI,1623 +tensorflow/include/tensorflow/core/kernels/identity_n_op.h,sha256=GIqM2-UMochpHGSaN-JKVHZePTFc71Go9_wa-cRv6QA,1961 +tensorflow/include/tensorflow/core/kernels/identity_op.h,sha256=N6A2Vu-KnICXPU17ih_DFGJoITDAVZXi-PYQdAbsxqk,1317 +tensorflow/include/tensorflow/core/kernels/image/adjust_contrast_op.h,sha256=L2F3ct4thfX7mBZgmYRHFQK_sDSWVgk3Gi28IAePKDo,5197 +tensorflow/include/tensorflow/core/kernels/image/adjust_hsv_gpu.cu.h,sha256=0yCbuhkWJsuURe4SSE8BfimJ298QZSy8AKzuSXXvo18,4979 +tensorflow/include/tensorflow/core/kernels/image/adjust_hue_op.h,sha256=_Sn7UFuMljMhQ4c61bRoWUw85ax9n-PZmhQwDD7RmJI,1413 +tensorflow/include/tensorflow/core/kernels/image/adjust_saturation_op.h,sha256=PqKB5bXU4-SPJ3G-8S9FWLe3bWtkZ9QtNv3zsbLVxi0,1441 +tensorflow/include/tensorflow/core/kernels/image/colorspace_op.h,sha256=tcjxihZojJf9k3a9Z_2maHDMGEZZ79i3SJq1iHZ3ygg,3392 +tensorflow/include/tensorflow/core/kernels/image/crop_and_resize_op.h,sha256=2a_ZPWsWHxQmvXlWbdRqwinpsBJIqewlnq4O0KZs1Ys,2991 +tensorflow/include/tensorflow/core/kernels/image/extract_image_patches_op.h,sha256=BKSoOf39lG_ad56SJDIoJd7RMDg4I4JEYWjkiP0bpCQ,2087 +tensorflow/include/tensorflow/core/kernels/image/extract_volume_patches_op.h,sha256=15iIroJgPnRKtPK_Bf7lQ_AYmDuzaRyn5TV6VuQHeLE,2056 +tensorflow/include/tensorflow/core/kernels/image/image_ops.h,sha256=HwtrZv6VRlEXOZw75f4ADmmp0Q4NOJmSYtHvqf-Kqd4,10694 +tensorflow/include/tensorflow/core/kernels/image/mirror_pad_op.h,sha256=m-nEZz9PmQkkUdpF6EZY7ryNSWLqyi5HZ4x_DS6R--8,16683 +tensorflow/include/tensorflow/core/kernels/image/mirror_pad_op_cpu_impl.h,sha256=q70r_5vmVUyMPUrl7C8uj-FJip4G4UgOdTguG-tSbWg,1927 +tensorflow/include/tensorflow/core/kernels/image/non_max_suppression_op.h,sha256=lmCqmEbUq10c9NlTXSF2Ocze108qwxHID3SLLtSzQVc,2197 +tensorflow/include/tensorflow/core/kernels/image/resize_bilinear_op.h,sha256=WDJwxrz8QT7U-HWZBl8I4OGL6Vo5PbMSz2Kw3bhoPiI,1809 +tensorflow/include/tensorflow/core/kernels/image/resize_nearest_neighbor_op.h,sha256=u96ITZyAoiCPxxkSa4k2PHEnIzmI3-m2EA-Po3k3Gwo,1767 +tensorflow/include/tensorflow/core/kernels/image/sampling_kernels.h,sha256=ivW9t1UJWaCWSPAJK-5qyNWrMDBJrC22ZUZUwZjhRTw,6105 +tensorflow/include/tensorflow/core/kernels/image/scale_and_translate_op.h,sha256=EGuMu_5ov5xAjxWJS0CFakKAdNFuT_lHMn26LkXp33Q,3401 +tensorflow/include/tensorflow/core/kernels/immutable_constant_op.h,sha256=GZZuEfqvSa8ZInYsuXZicXzH7e-EXkpdakiGKmsG3iA,1846 +tensorflow/include/tensorflow/core/kernels/in_topk_op.h,sha256=EDASO1eencop6-aEe4DSrO7_mhkzTN34g5WzeZusbCk,3533 +tensorflow/include/tensorflow/core/kernels/initializable_lookup_table.h,sha256=ZYcA7eeODLiRtfUir76kVnqDknSdxIgUnk0tG4vyqmE,10079 +tensorflow/include/tensorflow/core/kernels/inplace_ops_functor.h,sha256=mMrNyYUUHnX5tguOerXwZwNKjLfkws1sBvzYaaReSWo,1734 +tensorflow/include/tensorflow/core/kernels/kernel_platform_strings.h,sha256=gbf8OEK4pPMN2iC9t_3xqrMtNt9jSYEXJoNKbAmXvgg,978 +tensorflow/include/tensorflow/core/kernels/l2loss_op.h,sha256=PxWuLTfIDgx4f6IynsWceZjiHHfwTWRJ3jVzxh1eFjE,1226 +tensorflow/include/tensorflow/core/kernels/linalg/determinant_op.h,sha256=SCIQvRgJwARUuwe5HufnNIjKdHNhjamLcAgLPsoCJes,1864 +tensorflow/include/tensorflow/core/kernels/linalg/eig_op_impl.h,sha256=jOqAK1-EepZO6KfK1_qhJjhqKQouv3vA0jjmo6mKdEE,3764 +tensorflow/include/tensorflow/core/kernels/linalg/einsum_op.h,sha256=qQTOIBRlcfsYFRWf_cGV87KLpnhwbZ3XFA3sW4530M8,1802 +tensorflow/include/tensorflow/core/kernels/linalg/einsum_op_impl.h,sha256=LvfryL3hAirIt9d-KqmvVoP376N2XZNpPfp_63D1A3Y,30531 +tensorflow/include/tensorflow/core/kernels/linalg/eye_functor.h,sha256=bKX58yT3Yom-cpOMhofAxFPGPkXbO8mFhiApRatOLVw,1153 +tensorflow/include/tensorflow/core/kernels/linalg/linalg_ops_common.h,sha256=ERGhTg34wtyQtRfbXUAaQb4Or4djPU0fHNMEDpyoLEM,10945 +tensorflow/include/tensorflow/core/kernels/linalg/matrix_band_part_op.h,sha256=HF-Bn0l46WmH7O8i0uaFJJpdSfPlCANAzbgtQgBTv1s,1434 +tensorflow/include/tensorflow/core/kernels/linalg/matrix_diag_op.h,sha256=t6L6PWxM0YcaZgzKPa-7Q2jKacu1BnY55fgQEABBvcc,3153 +tensorflow/include/tensorflow/core/kernels/linalg/matrix_set_diag_op.h,sha256=Q2k7pfX8Ftvm9m4RJxwFe-Q_Va86dMdjC2ukJGQO3sU,1712 +tensorflow/include/tensorflow/core/kernels/linalg/matrix_solve_ls_op_impl.h,sha256=Z7CQQm_tInpKrey7YsUfmFJs3r87bPTgb7TeXMcbM7I,7444 +tensorflow/include/tensorflow/core/kernels/linalg/matrix_triangular_solve_op_impl.h,sha256=V2amWhukPpv0441r9-Sx5NFtLGWP4nTnzkCWP0Zt0W0,17235 +tensorflow/include/tensorflow/core/kernels/linalg/qr_op_impl.h,sha256=Rxs5S-eJv4StG0hXTm7kiTCJur4xiTB3YSPPWgUVHbc,12350 +tensorflow/include/tensorflow/core/kernels/linalg/self_adjoint_eig_v2_op_impl.h,sha256=AY4j_4kr_fzgV-zmyXArOFv1bnPLM3XdFJSS1Bjqu1M,3377 +tensorflow/include/tensorflow/core/kernels/linalg/svd_op_impl.h,sha256=cjus-YrycmEk_b90WDscjnegVKq5krMvByS1kKhN4-8,5058 +tensorflow/include/tensorflow/core/kernels/linalg_ops_common.h,sha256=Y-FvOVLVsjs-JhiDCsQ0YD3zHMJ5932VTKA1tKT28sw,927 +tensorflow/include/tensorflow/core/kernels/list_kernels.h,sha256=KV9fiLvqjdgM2XQeZWE64KG8CFTKdXD1FlEF58HsNJk,48080 +tensorflow/include/tensorflow/core/kernels/logging_ops.h,sha256=3bna2YY4rNXFmrd2jnxJuyDECjDyTZcwDJqHV4GJPj8,1092 +tensorflow/include/tensorflow/core/kernels/logistic-loss.h,sha256=3sEMnY30XJkMIn_X6tCinawtqO2XeHyTpQlG_rGOG-Y,5491 +tensorflow/include/tensorflow/core/kernels/lookup_table_init_op.h,sha256=yRmQAU-yXLO3C4Ffu7nzFh9n-7thWjzJe37Xug0THMg,1361 +tensorflow/include/tensorflow/core/kernels/lookup_table_op.h,sha256=0j91lPazAZFHbVQvu3H5YCeQlRAJ_eTXdLEqyqiQHow,12454 +tensorflow/include/tensorflow/core/kernels/lookup_util.h,sha256=DOSwwXJK2qndGDNGCG9gh6yy_v0_UIs_jAhkSugM3aA,3189 +tensorflow/include/tensorflow/core/kernels/loss.h,sha256=uZk9RdmdMRRy9-67MY84ks_R9ww-bUBCyqY5WQf4Py8,2539 +tensorflow/include/tensorflow/core/kernels/map_kernels.h,sha256=ZPTKNpvigBWu7kl1j1SeBiGsh6gVtHVsb9j0jPOWs7g,9052 +tensorflow/include/tensorflow/core/kernels/matmul_op.h,sha256=M8Fkcnl4YLw_jmWNNEJ8myTdwQ1HG2shPK5ZfSKO8VQ,3896 +tensorflow/include/tensorflow/core/kernels/matmul_op_impl.h,sha256=zIe73IMeO6Pa1gKLqtJdB4o9UfceXla-uYSLcNLBaLM,48401 +tensorflow/include/tensorflow/core/kernels/matmul_util.h,sha256=232VLr603zyLHAP3ZrQtuSKGkSpKbhnGSD2oqn0Nc-I,4801 +tensorflow/include/tensorflow/core/kernels/maxpooling_op.h,sha256=tr0QBBRACUJaSb6SZ-t9zKYPwWSiE6o2T0t5eSta8QU,2235 +tensorflow/include/tensorflow/core/kernels/maxpooling_op_gpu.h,sha256=rL8FGGF_aJgZYQx8dMIlVeTwMF2SGdVNENmuXjyH3dE,3684 +tensorflow/include/tensorflow/core/kernels/meta_support.h,sha256=gz_6wMwDdi1OF4p3M7PuG6xeUA7UPH_9rEYSAuGVQn8,4886 +tensorflow/include/tensorflow/core/kernels/mfcc.h,sha256=QNqy-i4lSvCcRgstpAuRTCcWrxqd6TInqbq7AgkylBA,2757 +tensorflow/include/tensorflow/core/kernels/mfcc_dct.h,sha256=zs6IArgPqy49m0bB3Tf22gs6JgpnLTcEYe3oaCLD3C8,1389 +tensorflow/include/tensorflow/core/kernels/mfcc_mel_filterbank.h,sha256=5hulxzQsM4BP86IZUYHJ30WIBogEIAkmO87RB2oESR0,2566 +tensorflow/include/tensorflow/core/kernels/mkl/mkl_batch_matmul_helper.h,sha256=Li_vD0BKLwQATaOL7LOQyT6A9YXCmWjN3O_NWJf4Sxo,4344 +tensorflow/include/tensorflow/core/kernels/mkl/mkl_conv_ops.h,sha256=ldeQSvXpZQVH8BawmDx_HZ5UHFAqyVWg5BWt9EY4M6s,31774 +tensorflow/include/tensorflow/core/kernels/mkl/mkl_eltwise_activation_base_op.h,sha256=u3eOZg7D7rXIexs57-6G15642Licprsaehihh_uEpHs,12083 +tensorflow/include/tensorflow/core/kernels/mkl/mkl_kernel_util.h,sha256=reXtHuCdgTGxnbzefGYH7FSZHVM-lUmqbeqb4VWoW_k,3728 +tensorflow/include/tensorflow/core/kernels/mkl/mkl_matmul_ops_common.h,sha256=vWekUeq3VV_AJu4busBOEmTkcntu41PFXrQtL0y69Tg,45565 +tensorflow/include/tensorflow/core/kernels/mkl/mkl_pooling_ops_common.h,sha256=p53X3DB5UQmInI0nC8POBLsTRo6t771Ahw2qEWWaxbM,29092 +tensorflow/include/tensorflow/core/kernels/mkl/mkl_quantized_conv_ops.h,sha256=ieDEyak9KaDWbRTrheiW81FBoPiXqkTErQNP4Pn-7aE,3973 +tensorflow/include/tensorflow/core/kernels/mlir_generated/base_gpu_op.h,sha256=BUQlLpSlkQSo2jIbptkpfFyvcB9hFoLZyufTlhQDee8,5437 +tensorflow/include/tensorflow/core/kernels/mlir_generated/base_op.h,sha256=TttxmAOokEMQowYCVwWDM-yKE0s17mOmoOPcL-MycBU,17945 +tensorflow/include/tensorflow/core/kernels/multinomial_op.h,sha256=fMSeNT6lN5NHr-_sDT_uONibetIz68Ge9Hq70ZjY2ak,1059 +tensorflow/include/tensorflow/core/kernels/nextafter_op.h,sha256=9wxZ6cnrybuQASuzU7emVUIBtbu-LNT710tlOuCUWDw,1338 +tensorflow/include/tensorflow/core/kernels/no_op.h,sha256=JVEkSj8YofIrwRSnE8FnihNbRnQ421kWBVShLa0gdXo,1114 +tensorflow/include/tensorflow/core/kernels/nth_element_op.h,sha256=Q55LEQB1OMEpB_F4rn9lP3EcyBO87rRlV5Mxl3y-Bm4,1259 +tensorflow/include/tensorflow/core/kernels/numeric_options_utils.h,sha256=CAxRkvv9t9pJLuMU5xdWVIWSjdCDfqfh9fk1BfBPq1M,1259 +tensorflow/include/tensorflow/core/kernels/one_hot_op.h,sha256=bTuQE2tYCQAOw_idDj_MnkXn02xHk_LZk2VZdDySIK0,4532 +tensorflow/include/tensorflow/core/kernels/ops_testutil.h,sha256=wpT7Mp_0v1ELmK7cONPwNvLrW9BaqqGnThSM66CiPd0,7761 +tensorflow/include/tensorflow/core/kernels/ops_util.h,sha256=0nj-epTSAcMd0DJYZydD0YJiRdQZzQ10oZNrj0FqJTI,931 +tensorflow/include/tensorflow/core/kernels/pad_op.h,sha256=nw-U-D2KKKmXzmd1GgVdEUUW4uZXo05ddxClRrdUlBs,2175 +tensorflow/include/tensorflow/core/kernels/padding_fifo_queue.h,sha256=zaamBzparAM3ILLM2FmgAFMKIE2Byg5R9MGyfipqog4,3536 +tensorflow/include/tensorflow/core/kernels/parameterized_truncated_normal_op.h,sha256=ofx8aMgUB8xtclJ0O5LeHehRyh9kmrOWi3otekb8YtQ,2839 +tensorflow/include/tensorflow/core/kernels/partitioned_function_ops.h,sha256=MKdYM_LnM7fBGeDBc2B3KFPnZUsXOkvdDu1EVrxQEbA,2884 +tensorflow/include/tensorflow/core/kernels/poisson-loss.h,sha256=c48COcRb-GjL767JRVvR3VQ9zzCz1rAHiPCFvKg3vbg,4335 +tensorflow/include/tensorflow/core/kernels/pooling_ops_3d.h,sha256=oPKe4zY2c7AMdFUvgk7IK0kj36WxuP5whmiVMcQhTkw,2306 +tensorflow/include/tensorflow/core/kernels/pooling_ops_3d_gpu.h,sha256=vrX4ANO4pE16h0mGw-qZY7KYtbSs8XfCPtWV-IStwjM,1913 +tensorflow/include/tensorflow/core/kernels/pooling_ops_common.h,sha256=_E6noLhY9HmsoqQl7bF2ko1Ts9JcKcp0z0Qyyrcu_XM,28991 +tensorflow/include/tensorflow/core/kernels/pooling_ops_common_gpu.h,sha256=2bvytW9LYcb62h5fUprv8_LT6cpiLa_FjpKCoasZpy0,2941 +tensorflow/include/tensorflow/core/kernels/population_count_op.h,sha256=si-9s9a4r9an6i_UgfTXy549UeFOTC6uIrtdtCOJaA4,1273 +tensorflow/include/tensorflow/core/kernels/priority_queue.h,sha256=hd4cmTX1xz2McXpUKGS9QutMwr-OBtWkEORlgiXJPVc,3646 +tensorflow/include/tensorflow/core/kernels/quantization_utils.h,sha256=PwpPT1_sDOoBLcc8atYKjCMwS79wmP6x4PnmKeKrovw,43235 +tensorflow/include/tensorflow/core/kernels/quantize_and_dequantize_op.h,sha256=8ZnKkrj6rmRZZSFtnznCFD1fKMdOmQZU02s9yD0VqPM,14551 +tensorflow/include/tensorflow/core/kernels/queue_base.h,sha256=gvRWFu0s5f1JPpw8uCwUTgNDI30rIRciCLwV0zPK25s,7085 +tensorflow/include/tensorflow/core/kernels/queue_op.h,sha256=0wLywPeZ8AH-_9ouw77v0EojBfdV_GqEawvz-FFEXXw,9115 +tensorflow/include/tensorflow/core/kernels/ragged_tensor_to_variant_op_test.h,sha256=rN1AQz_c6cWVzoo8t77nAstBe2grL1pXA-nINRG3OGk,5899 +tensorflow/include/tensorflow/core/kernels/ragged_tensor_variant.h,sha256=jbwiaBfR6YUcVYUXlDuOBdn-JVjxA1HD-HxjDqwIKtE,4316 +tensorflow/include/tensorflow/core/kernels/random_binomial_op.h,sha256=x_gG3d3ss3Dh1hyl7fHyOHJzlSIKwmmLT4LOW1QpBOA,2791 +tensorflow/include/tensorflow/core/kernels/random_index_shuffle.h,sha256=1C5KvdD6ngL6FQvigHR8ojGfVyFPISphJVyGn7jXlQc,1830 +tensorflow/include/tensorflow/core/kernels/random_op.h,sha256=n8a0e_3LMH_7LxO8POx4kR9kgGF3i3gKlBQYCXY4JKE,2552 +tensorflow/include/tensorflow/core/kernels/random_op_cpu.h,sha256=d8qMYOZzKYO8ntGgBmsZmP8ZaJSh4hIJkE14E6RJKPw,7562 +tensorflow/include/tensorflow/core/kernels/random_op_gpu.h,sha256=PYQzFcEYwiQ_4EdJ3yuAv4ihSkd2bIsyWQA7Gmj95wg,9187 +tensorflow/include/tensorflow/core/kernels/random_ops_util.h,sha256=ZoBe2U7A5UN0cQh8atC1lYextufqeg-KhK88opJzXJs,2649 +tensorflow/include/tensorflow/core/kernels/random_poisson_op.h,sha256=zcqAUiJZ2JCNomigUBk9mm11ZJsP4JDaIdMGgIqXdmA,1394 +tensorflow/include/tensorflow/core/kernels/range_sampler.h,sha256=a06nArqOI7f96vC350yu4iu7WB2CPFtI_-Q2jNuAkqg,9177 +tensorflow/include/tensorflow/core/kernels/record_yielder.h,sha256=VxuytF3LD7tTYVXkfKT11iYLrR4LVyaeOM8MudvLzNE,4936 +tensorflow/include/tensorflow/core/kernels/reduction_gpu_kernels.cu.h,sha256=xr-b6DJxgKmmjQ1wMr8mcGM4tCBFeyv8wy_yqBFxkxw,51997 +tensorflow/include/tensorflow/core/kernels/reduction_ops.h,sha256=am0NtUMs_bx20UMWKZR9QsPQ16R5XIF1-Zt-A4XjTko,9184 +tensorflow/include/tensorflow/core/kernels/reduction_ops_common.h,sha256=Mjxo0nqY9HD4Q8UZA7Hjov6L6dNb8wW3vXIaca3BRCU,11257 +tensorflow/include/tensorflow/core/kernels/reduction_ops_common_gpu.h,sha256=uq8QTPZMJrfpGULmQxGrMSRLD5h_OkdJl5cb7W-eyGs,1698 +tensorflow/include/tensorflow/core/kernels/redux_functor.h,sha256=93k02bJ77JJDT1BIWSgdmct6-w7CWipLNoEl52aCEjI,14317 +tensorflow/include/tensorflow/core/kernels/reference_gemm.h,sha256=rnhQ5u_TRyAOyia5OXU-9ATZzM_3vm6K8ECsKa5rzSs,3327 +tensorflow/include/tensorflow/core/kernels/relu_op.h,sha256=kaV8YBesGO3aRkFRvayUQOY_cvDO36sfwJR2329KEF0,10308 +tensorflow/include/tensorflow/core/kernels/relu_op_functor.h,sha256=byV_ykRj1woSRDMlRp9gOgSQliMv-dr1TBS2_dxgxkg,8418 +tensorflow/include/tensorflow/core/kernels/reshape_op.h,sha256=1u_Qgeca-pW-nU0iIxDyRG7Sm8L7hnYAJ2voXNr0RIc,6569 +tensorflow/include/tensorflow/core/kernels/reshape_util.h,sha256=084dc6wi4MWgB7-2AiyLnxEC-5kP07nENme_b_XCM9M,1912 +tensorflow/include/tensorflow/core/kernels/resource_variable_ops.h,sha256=_MDYcFpy7TJqLwVpHMhPCBfMQDztuGePKdqr-TfdB7o,2966 +tensorflow/include/tensorflow/core/kernels/resource_variable_util.h,sha256=EN3BKKSTMW5ddSUbRrZFsxttSPS2HoT34gjxCOhJpNc,1110 +tensorflow/include/tensorflow/core/kernels/reverse_op.h,sha256=RUl2ehvmpB5TLUitpB6sH46gP3XvVKZQHBqALQA1jxw,1756 +tensorflow/include/tensorflow/core/kernels/reverse_sequence_op.h,sha256=MpbhUt2RotrCm6jmfjkOjCA04ceeagY-eywua4H9tE4,2711 +tensorflow/include/tensorflow/core/kernels/rnn/blas_gemm.h,sha256=uUnRP9CCIq5KuUPh11Dmh-NcFzT6xfY0rJ3YOOfoz3Q,3754 +tensorflow/include/tensorflow/core/kernels/rnn/gru_ops.h,sha256=gN9VIiiChLncZyNwxPaaniFs2YPjNDMsU4uJcR4FNyM,7800 +tensorflow/include/tensorflow/core/kernels/rnn/lstm_ops.h,sha256=GFiLPJVCl7q5PhE8F-GMcOPZ9xArbqPu_mqtZUee8G4,11943 +tensorflow/include/tensorflow/core/kernels/roll_op.h,sha256=ROxEQwkcNwve5bLtg0ICRoneMpGIFhnvKYh_lURctRc,1916 +tensorflow/include/tensorflow/core/kernels/save_restore_tensor.h,sha256=k4jtspQ-9bU39XQtYmXCdZ9NSH_4NomGZUdzCrrxOww,2957 +tensorflow/include/tensorflow/core/kernels/scan_ops.h,sha256=WUcepSPVX61q06BLueaKOF_5kSED9aACxgzc_RWcys0,5354 +tensorflow/include/tensorflow/core/kernels/scan_ops_gpu.h,sha256=weQpjiK-s2fmaFnMKAtS2aAvHpm-SgdmvkeBshs73wE,12219 +tensorflow/include/tensorflow/core/kernels/scatter_functor.h,sha256=ZqX42iINmW5thDIgOEt8KF_kuneVFzSdz-Wxv_o_Swg,16924 +tensorflow/include/tensorflow/core/kernels/scatter_functor_gpu.cu.h,sha256=vIO2USmzVxGN8ViIzIAxkGxOT6QSGoNIXTdiKWTayRM,6868 +tensorflow/include/tensorflow/core/kernels/scatter_nd_op.h,sha256=WGIb2d5AmVXuzbCglZ9Tqjw9aeM8Nc4k_bMqezA5tCo,2852 +tensorflow/include/tensorflow/core/kernels/scatter_nd_op_cpu_impl.h,sha256=QtKl22U1_pOTK9lIjNS2L4bF1buzHidHPv8NF5vJ5Hg,7629 +tensorflow/include/tensorflow/core/kernels/scatter_nd_util.h,sha256=ig60gEnQNNveVyaUZJG5iDO4urgiQ__N7tUNPy1crLE,1986 +tensorflow/include/tensorflow/core/kernels/sdca_internal.h,sha256=EqA90Bysw9XX6UpgjPC8sIPb2fWR2F2_vWxfXBQTpu4,14653 +tensorflow/include/tensorflow/core/kernels/searchsorted_op.h,sha256=oCmbhXCDmObmTZLMT484261sHcl_woALL_s7BlK7LxQ,2294 +tensorflow/include/tensorflow/core/kernels/segment_reduction_ops.h,sha256=IykO7qzTFJcNrCy0AIFZ9_yWwxrQm3u9xwG7FRsMJG0,6156 +tensorflow/include/tensorflow/core/kernels/segment_reduction_ops_gpu.cu.h,sha256=KEbHAhM7cJnYa_nJL33UQ3_e76DuvKHMbTn7cZuYtqw,66426 +tensorflow/include/tensorflow/core/kernels/segment_reduction_ops_impl.h,sha256=uhIzLRBPNCuFmm3e3XpTBgrb3e1fJugqDunMifb7Vk0,57064 +tensorflow/include/tensorflow/core/kernels/sendrecv_ops.h,sha256=17DKdhvPtwTvyg7soRQoT4i8CcaTZPn0pXBx97zHJj0,1782 +tensorflow/include/tensorflow/core/kernels/sequence_ops.h,sha256=1rkBAiqWBV2mgR44YhzaRccMF0XWYFSwKdgTYI-KLKs,1217 +tensorflow/include/tensorflow/core/kernels/shape_ops.h,sha256=Pn6Fncnp9ZmMxGXspruMJL7no6moRDFkGm2E6K3i454,9828 +tensorflow/include/tensorflow/core/kernels/shuffle_common.h,sha256=i0SObL5HE_ELW0OdvRnLC8wiq51qwIbAPD68TOzXKgk,3856 +tensorflow/include/tensorflow/core/kernels/slice_op.h,sha256=CIg1MMgq4rbCkmHxIcgLb-HxvbZboZZbgqa9iUf60fc,1733 +tensorflow/include/tensorflow/core/kernels/slice_op_cpu_impl.h,sha256=tMoCKK-OauysVR3nmibSL1SzTQlSpZdnNgCPjil7Cjk,1274 +tensorflow/include/tensorflow/core/kernels/smooth-hinge-loss.h,sha256=i2ih68H6E4GiIkZPkGZBKr53KAzxcrFpf7wL5Lk3Z74,4302 +tensorflow/include/tensorflow/core/kernels/snapshot_op.h,sha256=4fdTPftUgL4JUv-HuZNeCdSjCZMBvLIMI5fJhVh1CKY,1465 +tensorflow/include/tensorflow/core/kernels/softmax_op_functor.h,sha256=2UFWZOE-HVmeFmjmTo-e2is4KuXnnX0c40Wf3KNZgSA,4010 +tensorflow/include/tensorflow/core/kernels/softplus_op.h,sha256=3zoah2szpj6CJQWaUYf9P2lBeHlyKR1kc63QlsYASJs,3280 +tensorflow/include/tensorflow/core/kernels/softsign_op.h,sha256=9lHl8IStGnZwgkMVCTXvwSrtSunHkvQFior5XXWZqww,2227 +tensorflow/include/tensorflow/core/kernels/spacetobatch_functor.h,sha256=pzw2GS6arKknEXRdojJOTxv8srvx1Rs-KNNSgo4R858,4625 +tensorflow/include/tensorflow/core/kernels/spacetodepth_op.h,sha256=huK_kvqetwOTJCCkUUIfMT1PlNE2kDqhJQwEBD9pwqo,2741 +tensorflow/include/tensorflow/core/kernels/sparse/kernels.h,sha256=XgWQwkq-mzVbjmuExdklza27jCe3ABxR11Q4I5nCvws,9204 +tensorflow/include/tensorflow/core/kernels/sparse/sparse_matrix.h,sha256=yFsTY9ydVT3_CmAI8nu0TeHoeYM0Ki0p0GToD0Q17uQ,23066 +tensorflow/include/tensorflow/core/kernels/sparse/transpose_op.h,sha256=shqENjwXfE52rkq3GcjbNCXDyzPMxKa1rmbkk0UI7sM,2525 +tensorflow/include/tensorflow/core/kernels/sparse/zeros_op.h,sha256=rpcz9MgaB2pBTM8lxguZk2oUDDIz_LkapSD_Fpss_DU,3340 +tensorflow/include/tensorflow/core/kernels/sparse_concat_op.h,sha256=2PyXoKSlMuVndFRU8ahgkiD2PASOPabCwFan4H0OrlM,1224 +tensorflow/include/tensorflow/core/kernels/sparse_conditional_accumulator.h,sha256=KUq6e5pTOpfHFCOzd45AUVVHt6jAsm-oDWnF4Z3piHo,17340 +tensorflow/include/tensorflow/core/kernels/sparse_matmul_op.h,sha256=DHewa7AQlq5sN0WyE19uy3NbaLOHfb5q6ER32RayIPY,17734 +tensorflow/include/tensorflow/core/kernels/sparse_reorder_op.h,sha256=zRm4QQ_FFI9ioNw9iwGiHo79gDJaA49Kyoh64KP6K_M,1197 +tensorflow/include/tensorflow/core/kernels/sparse_slice_grad_op.h,sha256=G1V_pd01MhCzDQDv-wAZ2UCh-tPabLTLvBAjPD_LwM8,1507 +tensorflow/include/tensorflow/core/kernels/sparse_slice_op.h,sha256=n-WlOnOAz43mFBXfJacY48WRnvLXawh7Gh2rl1cFALk,1438 +tensorflow/include/tensorflow/core/kernels/sparse_split_op.h,sha256=-iMyOCXi7y1jri5OKr_bdx6o6QYuZaYIg6FoBloHZ_s,1328 +tensorflow/include/tensorflow/core/kernels/sparse_tensor_dense_add_op.h,sha256=sJbVM3162r32T820AOKgydsTWXimoKNH9-74Dbh5PrA,1757 +tensorflow/include/tensorflow/core/kernels/sparse_tensor_dense_matmul_op.h,sha256=Tzg00IH7IdDOB5HqQs9xci0AR1-hJP01hMIK9JvQljA,2697 +tensorflow/include/tensorflow/core/kernels/sparse_to_dense_op_gpu.h,sha256=1Ya_3ndJRj3ymPOLXx9-tgObcDpY-DMVbxvvCxlINQA,1497 +tensorflow/include/tensorflow/core/kernels/sparse_utils.h,sha256=fFn1kOFxQwfSkXHnl84RnwDUDSN1HK1ncHGTrjU_FTc,3795 +tensorflow/include/tensorflow/core/kernels/sparse_xent_op.h,sha256=2FxS-siEVzw84qmSGUKoD9887VLEKMWKQugyY4nw4mU,9025 +tensorflow/include/tensorflow/core/kernels/special_math/special_math_op_misc_impl.h,sha256=KopF9J2QITqpElWmlinP6P0BscQOXW_nXlDePOXHWN8,24645 +tensorflow/include/tensorflow/core/kernels/spectrogram.h,sha256=qL6SnL8dghdSHzSJoOcR7CY3Fb5AcZy--CrZopG_k7E,5305 +tensorflow/include/tensorflow/core/kernels/spectrogram_test_utils.h,sha256=rkhyL_SnNE__hE6YwfBRYkpV8YHMTyxP0Aq4Br2aDo4,3303 +tensorflow/include/tensorflow/core/kernels/split_lib.h,sha256=LfniZs9RJ163wRCw5oQHL0dcnx-8DG1kCkbbDBmIYvs,2227 +tensorflow/include/tensorflow/core/kernels/split_lib_gpu.h,sha256=xBbkPfNBLWvK6pX8GxGyEFXlB8vx6nxhjnFWO3Ud7bE,2179 +tensorflow/include/tensorflow/core/kernels/squared-loss.h,sha256=33pqIsRGRB9PcS48ooZCDla50fwW_GKvK7eztQBPOOE,3068 +tensorflow/include/tensorflow/core/kernels/stack.h,sha256=mgaepLuke-EEFzBbhbuZid_jLJgXlE07WZCXBM3K6ks,2410 +tensorflow/include/tensorflow/core/kernels/stateful_random_ops.h,sha256=b_cWKkju93_bR-ztaE3rVzCInYxwtNKVG1dDEeVrueI,1649 +tensorflow/include/tensorflow/core/kernels/stateful_random_ops_cpu_gpu.h,sha256=hblSPDQWXiAQDsI17e5YeIIsXkUCxaRaQcNoReT5U5Y,4014 +tensorflow/include/tensorflow/core/kernels/stateless_random_gamma_op.h,sha256=nnFYC8VRlucmG2z7zCTETC6aZk7nuTkqYu-43q6LW_0,3200 +tensorflow/include/tensorflow/core/kernels/stateless_random_ops.h,sha256=AH2n_z9DyCbVQpH8h-C1KdVKTcxfKiSkhD_XEK9whkw,1990 +tensorflow/include/tensorflow/core/kernels/stateless_random_ops_v2.h,sha256=8HOBq-zZzw7LnWlauel-3h4D0nTD1LXbCeC4VbbvIlE,2502 +tensorflow/include/tensorflow/core/kernels/stateless_random_ops_v2_util.h,sha256=3D583ezTpxAQjjneC2ldH85o9U2xBNeuh7idOQXndX8,3441 +tensorflow/include/tensorflow/core/kernels/stochastic_cast_op.h,sha256=r28H_vMPQjnEcymwyY6dIIOe9GIAYPizi3ODs-EkceI,5032 +tensorflow/include/tensorflow/core/kernels/strided_slice_op.h,sha256=PIPOopicT9rKHZIQrmxXB7AJjeK7noqbWn0Z-HuUhgM,5037 +tensorflow/include/tensorflow/core/kernels/strided_slice_op_gpu_impl.h,sha256=qLJMN8b5d4ouJ-G3adtgxbq1y_Y60XRG5A_0JFqvM0Q,2983 +tensorflow/include/tensorflow/core/kernels/strided_slice_op_impl.h,sha256=bI2SgeDE-3AYrY8mFRUe7J3iOXV9LfxxVrxsLuhB6lE,13654 +tensorflow/include/tensorflow/core/kernels/string_to_hash_bucket_fast_op.h,sha256=faPUrAE1wSpdP5fvqyMwic2V09H-A-HdvRn_loMaA2w,2495 +tensorflow/include/tensorflow/core/kernels/string_to_hash_bucket_op.h,sha256=sSrzm7A41mTwZpG0IqIXh5PPfe-aU46wbyxTj4ED6rA,2798 +tensorflow/include/tensorflow/core/kernels/string_util.h,sha256=mix_YY1-AFQb82yORnPMiJBFjAe6WwNuenJEQLaE74E,3680 +tensorflow/include/tensorflow/core/kernels/summary_interface.h,sha256=vlT1fJEzM6fgUkkOvHa4r84H1hVV-osHvu_NHAXQ_2s,2251 +tensorflow/include/tensorflow/core/kernels/tensor_array.h,sha256=mn20P5N7htuJzODaDOAVaprUvUinLvNsK-yQ7FSaFSQ,23819 +tensorflow/include/tensorflow/core/kernels/tensor_cord.h,sha256=DuhH8bdUsrZTF833edEl49xwEDbZP1J3szlhQY9H2GI,11189 +tensorflow/include/tensorflow/core/kernels/tensor_flag_utils.h,sha256=DQj6kv9iS59W6xvYAj9L_eHFD5av9fTHRl_LWREJH1Q,3394 +tensorflow/include/tensorflow/core/kernels/tensor_list.h,sha256=EsAeivZhdkFq4l0ft7AldXRa_tSUUgGOsma5v6Ij0vI,5592 +tensorflow/include/tensorflow/core/kernels/tensor_list_util.h,sha256=va8nexNUOlDhefkYH2_ZTZSewlIQuJ9XjjMIULXPTgo,1490 +tensorflow/include/tensorflow/core/kernels/tensor_map.h,sha256=uWKJI1Bv9ssTKZ5n2q8JUcnTiY28RFfrpoOkQB-cjXY,6118 +tensorflow/include/tensorflow/core/kernels/tensor_to_hash_bucket_op.h,sha256=Sgqvnu4aYmeAgoHJLy-GvL5pE4ZkagIbv2fsg5pbwqQ,2867 +tensorflow/include/tensorflow/core/kernels/tile_functor.h,sha256=CII3SAsU2-03B8JlgrsMca4BTwcfHa_9w2WKAIG-WnI,4072 +tensorflow/include/tensorflow/core/kernels/tile_functor_cpu.h,sha256=wvabQOhbDUkC3EG_bGTJo5_iEqKCL-D2VJUPPP2TMKI,1945 +tensorflow/include/tensorflow/core/kernels/tile_functor_gpu.h,sha256=pGQXXpNVagHTfARn2S_jg-qJAgocRbbxeLVFTTV_ux8,3603 +tensorflow/include/tensorflow/core/kernels/tile_ops_cpu_impl.h,sha256=LMyIfanqJLYF73lQcYgGCVGoip3K8CyASPHvkVKeI6M,1681 +tensorflow/include/tensorflow/core/kernels/tile_ops_gpu_impl.h,sha256=a5fIU4PSeXEmqFCvd9Q77zyxXs_4dzAIm_bSg0pb0Bs,2191 +tensorflow/include/tensorflow/core/kernels/tile_ops_impl.h,sha256=hUi0CsGO6yUkefc-238KlsI9CzGT4hTxyRxZ2veZeRU,2502 +tensorflow/include/tensorflow/core/kernels/topk_op.h,sha256=W7EdLzTVEPKy7KffrwF10Uw5RPa4GIdyzc6qHtjSpik,1590 +tensorflow/include/tensorflow/core/kernels/topk_op_gpu.h,sha256=-BkER2-s96cuOOPmgdiOaT7_83p5_E3W-NaxBIAQM2Q,21097 +tensorflow/include/tensorflow/core/kernels/training_op_helpers.h,sha256=1UakWcP1VMp_6TszEUKVpzB4qSgX3xh5DEtEI4f-Nl8,11573 +tensorflow/include/tensorflow/core/kernels/training_ops.h,sha256=ApTuRcAD3BGAE0CkITp8SbLiwIRBtIUsTu3cu_u432A,14052 +tensorflow/include/tensorflow/core/kernels/transpose_functor.h,sha256=YiBVz0KDkKehW-l9ttcPLjHk8l68kGBi2MWsL9kt1lY,9022 +tensorflow/include/tensorflow/core/kernels/transpose_op.h,sha256=VEkuljiiHGojtsl8dbC-827wSs5M9M94qovXmzlAvyE,3382 +tensorflow/include/tensorflow/core/kernels/typed_conditional_accumulator_base.h,sha256=yibXl9lVZqVngvPAAyJG-FEgYWRWtovaqf4F05uL_JA,3898 +tensorflow/include/tensorflow/core/kernels/typed_queue.h,sha256=zYtvSdxMjfglBpBpryqUkNif2umNI_B6W_CGpT78tN4,3610 +tensorflow/include/tensorflow/core/kernels/uniform_quant_ops/math_utils.h,sha256=kSCm6tLHSKTwZnJjeqTG6eAvKJSUaqfkzGOkxky7zA0,15349 +tensorflow/include/tensorflow/core/kernels/uniform_quant_ops/tensor_utils.h,sha256=1hTzjk_45eAJ603FbIpQCESaOleGaS0EzlGs57XfuKM,3183 +tensorflow/include/tensorflow/core/kernels/unique_op_gpu.cu.h,sha256=R1eG17vXo8TKGuaHfX2O4oJctOhYokXpA27UR5Bu9MQ,19213 +tensorflow/include/tensorflow/core/kernels/variable_ops.h,sha256=pbDKnSxOh8dv-DW9YM0itA5APa2ZwOYpnnV8Axgxra0,1621 +tensorflow/include/tensorflow/core/kernels/variant_ops_util.h,sha256=T6MWE1_JPMzf4zJny0D4kEJzFIRildmYRdSb2rG1zd8,1223 +tensorflow/include/tensorflow/core/kernels/where_op.h,sha256=K6JZzaHpEwLlxUO4Pl2lMqBwhYdJaX_MsjmMLQHEj9U,2390 +tensorflow/include/tensorflow/core/kernels/where_op_gpu.cu.h,sha256=nNAxfuUaJTSFghFazww6fnkiAgNs9XuyrFN6rwN63IU,13309 +tensorflow/include/tensorflow/core/kernels/winograd_transform.h,sha256=KulBQ3370vcpJlI9c_cM6rjP9G-eDsaRYkIbcNesQhY,11751 +tensorflow/include/tensorflow/core/kernels/xent_op.h,sha256=khsgWgnbouUNYlh6S36KHKhmRDtlaDWT68f41NIAiro,4857 +tensorflow/include/tensorflow/core/lib/bfloat16/bfloat16.h,sha256=_4T6HiIZ8AgXujbIztBzYxFbakT0kqFKE4EgB37fggk,869 +tensorflow/include/tensorflow/core/lib/core/arena.h,sha256=6dPk1ix5esqGRVIM4OPRi0rlnRE02Y6xwq9kI8ftnyU,3811 +tensorflow/include/tensorflow/core/lib/core/bitmap.h,sha256=C-QhZ5XizUPrAfnTOzBSGJ5Op77ZzaN-AWvy1WMeOkI,962 +tensorflow/include/tensorflow/core/lib/core/bits.h,sha256=m1xiudggbUaGEPV0-zEZMfACyMUP4yT08PJjZidvT78,1366 +tensorflow/include/tensorflow/core/lib/core/coding.h,sha256=5Tk-IFnxsOkLgta40RckX0P05G4gBQXC81zW5dqb79g,1103 +tensorflow/include/tensorflow/core/lib/core/error_codes.pb.h,sha256=dWSVtRBLSvw3I62r7WsGM2mzar1kaWHj0Jc93Jm_CVw,2596 +tensorflow/include/tensorflow/core/lib/core/error_codes.proto,sha256=pNPuxKrhpoOo_6IN-NIKGX3aC_aE7Ftjq8iIFje3v5U,68 +tensorflow/include/tensorflow/core/lib/core/errors.h,sha256=ebsI6Zsn_b1ZCKKiQSocNomEvNvRU2c5KgBqxoD7fSs,873 +tensorflow/include/tensorflow/core/lib/core/notification.h,sha256=452qm3l7Kfw3zcPKhPhyUOMQmC-dCh0rN6UFU2KInkg,1005 +tensorflow/include/tensorflow/core/lib/core/raw_coding.h,sha256=zzn7xcZRgyfzjeeefXvCLaz5A6-2ErTxSXjQydpWOVE,889 +tensorflow/include/tensorflow/core/lib/core/refcount.h,sha256=PpzMzgoMvI-GMPU4EV8WoM4Gd7u-MUbHW5IjiF-IQbc,881 +tensorflow/include/tensorflow/core/lib/core/status.h,sha256=3k9CMGUOIMaX6zhlqI6goJ1u-f6BIJBz7T47aGf6eD4,873 +tensorflow/include/tensorflow/core/lib/core/status_test_util.h,sha256=rxEHFaAu-4hkeI58_sLTSuGckYGLBMnIF9QT3y8cBUE,920 +tensorflow/include/tensorflow/core/lib/core/stringpiece.h,sha256=zDmW-rx5KBps7nTZ5sekL3QdNMpgpjQzAiII3HMXwo0,1370 +tensorflow/include/tensorflow/core/lib/core/threadpool.h,sha256=YuLBq-yKE2wV7WEBO8Pm3o18oegFzXy2i1bIf9XgdxY,889 +tensorflow/include/tensorflow/core/lib/core/threadpool_interface.h,sha256=Ma7zhmX8NNlqN7VjI74S84chwOXTZcnzw3WmRq6eeb8,929 +tensorflow/include/tensorflow/core/lib/core/threadpool_options.h,sha256=F5CAaSOxq49i2fcRdPN2CEZ8v_MqOavYojdBNoPG3OY,921 +tensorflow/include/tensorflow/core/lib/db/sqlite.h,sha256=qcazRLsxh5ZNcK7BHs6geRJ11S6sKfwRvPk5JCWiRrA,16013 +tensorflow/include/tensorflow/core/lib/gif/gif_io.h,sha256=8NVPUPGrm8-cMUtn4ohIwjZNa-NboHaZ7HOjb9RTK74,2008 +tensorflow/include/tensorflow/core/lib/gtl/array_slice.h,sha256=9TObt7ILQTnkNBLvBZV1e-nTpYIhvtcAU5JLUXGKJ2Q,1236 +tensorflow/include/tensorflow/core/lib/gtl/cleanup.h,sha256=kSM2_K0gOFK90lh6zrceCdGYMKpFq-hCgfhwivY1u2E,3543 +tensorflow/include/tensorflow/core/lib/gtl/compactptrset.h,sha256=83QcWa1YRbRpanjpP04QHf1CKBMXXM35nv5do9gFmwE,1023 +tensorflow/include/tensorflow/core/lib/gtl/edit_distance.h,sha256=wkWLMEpaYjvao1ohOHYxAIcqb_hVhmE8BLDXj7cog9Y,4028 +tensorflow/include/tensorflow/core/lib/gtl/flatmap.h,sha256=hI9PmI0i28sy5Hl0_jNgUGrCCogxKrJvM05E8-TFErg,1165 +tensorflow/include/tensorflow/core/lib/gtl/flatrep.h,sha256=x8BvyvNEQBybcjR3ni6pUOYNqHd64KctvtvSz0CRhDI,1043 +tensorflow/include/tensorflow/core/lib/gtl/flatset.h,sha256=hi-ubVE22hF7rncSdfECnTMftYSI5H9JcAVRS61-dSA,987 +tensorflow/include/tensorflow/core/lib/gtl/inlined_vector.h,sha256=rXbm0DqVU4hONfXzkOQeRzMgcXg8OUQsV8YKntYvgPs,1260 +tensorflow/include/tensorflow/core/lib/gtl/int_type.h,sha256=YYI0_liujtVOCF1-Uz1KvxEteZie90_XJG_hjFaFix8,994 +tensorflow/include/tensorflow/core/lib/gtl/iterator_range.h,sha256=HLdFMFOSrV0EGwI2mfczE9bM9uVxJJ3wvCnyDwEG8zU,1512 +tensorflow/include/tensorflow/core/lib/gtl/manual_constructor.h,sha256=coTix7mWw60SbvexZLwAodYAIIE5OBXvG5ZMwSClxcY,9329 +tensorflow/include/tensorflow/core/lib/gtl/map_util.h,sha256=7VhtzATcz2zEuQU7TnoNDNvPT8EcVRcrBiFewScIaCY,1467 +tensorflow/include/tensorflow/core/lib/gtl/priority_queue_util.h,sha256=o0YnS-BVh6QjHRayaOI9l0V96vR6o-WuKVR3YO9QLqw,1983 +tensorflow/include/tensorflow/core/lib/gtl/subtle/map_traits.h,sha256=zJ3ocTcs4DjqEwJRqtgrnPPwvVKgBWRpFYCL7nurftI,1665 +tensorflow/include/tensorflow/core/lib/gtl/top_n.h,sha256=WWd6S_bQedQHVPONQkqykOw_h3Sa7E0_rqkORuV6YlY,13304 +tensorflow/include/tensorflow/core/lib/hash/crc32c.h,sha256=pbUmZ-G3bhZXOheCyTnkkpwZjdDH-vNPASHozi6fyUQ,1299 +tensorflow/include/tensorflow/core/lib/hash/hash.h,sha256=FiFExK5j1r5-J_IM9VYnAk6Gf9cEv1TLtLRmMAJMy0w,901 +tensorflow/include/tensorflow/core/lib/histogram/histogram.h,sha256=M8kdv4KO5mXlw2aUHMNll2muIr7aA2AIPhMKeAxd6EE,1394 +tensorflow/include/tensorflow/core/lib/io/block.h,sha256=5dNwo2QYK49DqUab1EPEVa0N7PqXJuqG6cjJKEuaKHI,1002 +tensorflow/include/tensorflow/core/lib/io/block_builder.h,sha256=0ezV8J5DPxGS4DW5lxaxFMomp4bLEBh16rjnWBSbw2M,1090 +tensorflow/include/tensorflow/core/lib/io/buffered_inputstream.h,sha256=l9zKdoiZvyuHrClNgaPizcHr372OnyhRY-S5NR_LsOE,1133 +tensorflow/include/tensorflow/core/lib/io/cache.h,sha256=PYNXoZA0BFr-_WpKu7rrw9kncr5FJTuWpIBOtS7bAJk,1154 +tensorflow/include/tensorflow/core/lib/io/compression.h,sha256=pBDOrx0rVhDmpj7zOW-gavpqk69rl7Ou5B1FKY07-aM,1206 +tensorflow/include/tensorflow/core/lib/io/format.h,sha256=fzXr7UPv8X_NDlJkTJAkYQmR3nX7oIgplDrm6lwc0bI,1310 +tensorflow/include/tensorflow/core/lib/io/inputbuffer.h,sha256=uKEvUWJ7yothbUI0DqeGFbHsE4-3CrO90jM8HkXL0GQ,1177 +tensorflow/include/tensorflow/core/lib/io/inputstream_interface.h,sha256=rCzE98BcnWiYPKxO3YyD5mFMsINxfxSlY53gqQwsI1Y,1207 +tensorflow/include/tensorflow/core/lib/io/iterator.h,sha256=wsExSS16dIoygEQfYt4NptoV34vc03d3q-52V6QMEVE,1695 +tensorflow/include/tensorflow/core/lib/io/path.h,sha256=cUFAIrYgBbf0vh09VM4CveZ3dZ5OUixxaIiZhMMx0AY,835 +tensorflow/include/tensorflow/core/lib/io/proto_encode_helper.h,sha256=pEwS9Avoq3sg10CIWqM4q3ET8A3oUpFxZKmLjiJd9_g,1207 +tensorflow/include/tensorflow/core/lib/io/random_inputstream.h,sha256=GCyP99FfqsqoH9EA85Gk3ktn1vv-3Sb8QDqpvXIhAtE,1172 +tensorflow/include/tensorflow/core/lib/io/record_reader.h,sha256=KWvY9T2DrAbPCBUZQ_cfjRL35BcouOz09lsa71jT_lc,1533 +tensorflow/include/tensorflow/core/lib/io/record_writer.h,sha256=QwfbrEWa8bTIr2qvnfNHiAyXgYZOjCL8NijsJvCKzGw,1570 +tensorflow/include/tensorflow/core/lib/io/table.h,sha256=hTn-Nst1mLDaUuAV9n_sc--cFyG0vYPPPlV7wEo9OSY,1002 +tensorflow/include/tensorflow/core/lib/io/table_builder.h,sha256=LOHMa3-JJO-Qls6DPz3_HPxHyd6p5VcEsHf812RqKNU,1500 +tensorflow/include/tensorflow/core/lib/io/table_options.h,sha256=XF2FXg5djYea8h_P9uLL8uZJAXxTq1crxke_C6hBBdQ,1160 +tensorflow/include/tensorflow/core/lib/io/two_level_iterator.h,sha256=oiC9CTV3CDeRBF6EP4nA1QkWKoIdt9jbF47tkuVCIBU,1068 +tensorflow/include/tensorflow/core/lib/io/zlib_compression_options.h,sha256=AQNwYtmK7d5_hQEPA4lfP1y4_qtDMSvX4hAYPcrO3-o,1063 +tensorflow/include/tensorflow/core/lib/io/zlib_inputstream.h,sha256=x8a-NQhnKK-ivaTVxMW2BOyiaElealx3ZtGVVVC0I2Y,1301 +tensorflow/include/tensorflow/core/lib/io/zlib_outputbuffer.h,sha256=fPxnSRKOZHVhJiMJVsN8lidbNaGYyTtKoBwB3G9fcdE,1347 +tensorflow/include/tensorflow/core/lib/jpeg/jpeg_handle.h,sha256=kE4FJpI_3cKXB4e5Nh26IdW2vovv37FX8ckWR8v6UGQ,2116 +tensorflow/include/tensorflow/core/lib/jpeg/jpeg_mem.h,sha256=bP1krNbRad9GtVmlj7mRxFb0pgAeGI7KZgn6T5gpVHM,6362 +tensorflow/include/tensorflow/core/lib/llvm_rtti/llvm_rtti.h,sha256=Dq2e43Oo77aSOhlghfEKcQz0rlixzLcvA-ddrR1FWFs,951 +tensorflow/include/tensorflow/core/lib/math/math_util.h,sha256=5iZn4s6iDcqQQV750T4OMGtW5ZvpfxNjUvCQfqptheg,1089 +tensorflow/include/tensorflow/core/lib/monitoring/cell_reader.h,sha256=bqQV0zKlmwHqmqCweq99_LiUN_6VJcKH7bkbZOLLpvc,1438 +tensorflow/include/tensorflow/core/lib/monitoring/collected_metrics.h,sha256=paiyZjO1DNkNbVisVLtHKbsIsMn8Xzw8BDmQ8v2RvYk,1655 +tensorflow/include/tensorflow/core/lib/monitoring/collection_registry.h,sha256=WyXqcXqL85vGPYtBt8JGoV2Mud5wKCHyX3QVcmBDUtE,2806 +tensorflow/include/tensorflow/core/lib/monitoring/counter.h,sha256=_z3ItXKNfgB2wyDvnZiqJb4354q7j0Lg8HHwjCIv1XM,1641 +tensorflow/include/tensorflow/core/lib/monitoring/gauge.h,sha256=qooF0d5L6IJyZy3BbI7VTI7lfMggXdY0HPgB_qGUhA0,1218 +tensorflow/include/tensorflow/core/lib/monitoring/metric_def.h,sha256=6cFRtVWeB7szWGe7tzHzqBgzgjtCuMYD9t0e6KtuC7c,1427 +tensorflow/include/tensorflow/core/lib/monitoring/percentile_sampler.h,sha256=Tat-jB6u32EDw23Lvc11eBzEodMyR4ds8WRzidbS03E,2391 +tensorflow/include/tensorflow/core/lib/monitoring/sampler.h,sha256=9F_rO7pDUAEtgkQs-Jic-KjnA2nvTHawFT7iCcZenDA,1914 +tensorflow/include/tensorflow/core/lib/monitoring/test_utils.h,sha256=xWIS8bvpDbMOfTaiGb2y315PfdaM3Vg5rPpbpZbxBvc,1353 +tensorflow/include/tensorflow/core/lib/monitoring/timed.h,sha256=D-t4Vl3sKqccdvXhVyoWGP1dPbmhrZXhizAZfdo6Tk8,1145 +tensorflow/include/tensorflow/core/lib/monitoring/types.h,sha256=FD72S4f8ZciB48xUSRwPeGcB_ToKEA0waqeU_KqbdxU,1230 +tensorflow/include/tensorflow/core/lib/png/png_io.h,sha256=clmqhX9ToyOas0YHXRY5LiLfKs3KzMwkqhtqjIGe2Wc,4567 +tensorflow/include/tensorflow/core/lib/random/distribution_sampler.h,sha256=1XIQWoqrlAQ7axFo-B101inDv5YzbGi4EylgKrPd7rI,2037 +tensorflow/include/tensorflow/core/lib/random/exact_uniform_int.h,sha256=SOVPPyP1V4jVDMFGaOUK1ATazN5OGuCA2JowiVfR1iU,1106 +tensorflow/include/tensorflow/core/lib/random/philox_random.h,sha256=0UlzxUBg99KSz5VJJO_uEFrZjfpz14aQu5sDIoliwfk,1321 +tensorflow/include/tensorflow/core/lib/random/random.h,sha256=0PIal81z5I0vpvy7Ed58lrSVzoSah8kvWMhFUXFrtuk,855 +tensorflow/include/tensorflow/core/lib/random/random_distributions.h,sha256=VNjLLZ_-0-I7rRLpceXb5i5RK2ZDRV4rXo48ceIp7e8,1653 +tensorflow/include/tensorflow/core/lib/random/random_distributions_utils.h,sha256=HyTBXPdVUtBbDUGcc9lu_aUqI4M_m2O8Hd2-uEWThQg,1295 +tensorflow/include/tensorflow/core/lib/random/simple_philox.h,sha256=VH-Q86d1ypKRvnrUxe8Fg5KJFI3akUTth03uYSZwIA8,1150 +tensorflow/include/tensorflow/core/lib/random/weighted_picker.h,sha256=cgx09iJs-PgCpEfgutnB1akDD2Nn6woEbZ5JR3x8Gtg,1553 +tensorflow/include/tensorflow/core/lib/strings/base64.h,sha256=-O4z1aqPsXE_vOzOZfUjNB951LsZSJ1OkHgwpS-_FmY,858 +tensorflow/include/tensorflow/core/lib/strings/numbers.h,sha256=TKzFqFUp6TkBhSpVj8TKJv30Y1_xGA1mk_rFCUh-Pjo,862 +tensorflow/include/tensorflow/core/lib/strings/ordered_code.h,sha256=Exg-DgeBiKGT60n-hPbeIFdXVPjQRSkhGZMl8Ra1IFc,4086 +tensorflow/include/tensorflow/core/lib/strings/proto_serialization.h,sha256=riOLGyN_p1hvJPRx373dyQNqIkGzs4hHbQxnpPLCro4,1197 +tensorflow/include/tensorflow/core/lib/strings/proto_text_util.h,sha256=yEjgS5ZclpqKEu6_X9IwhkXGivKuTuiDrfocqlsjTiw,5886 +tensorflow/include/tensorflow/core/lib/strings/scanner.h,sha256=Pg08DEu-Nq5WuwEPH5OemXvzNsbl1R4qZuCCbrWfzN4,886 +tensorflow/include/tensorflow/core/lib/strings/str_util.h,sha256=nLLrc_g8u_puw1JXPE0ljtMBkdPRhHAOXySweU4tTm4,890 +tensorflow/include/tensorflow/core/lib/strings/strcat.h,sha256=fQmL2IfPgPwnRcSGSzQh5SFf9cGWBh-ySN3l5WfYaz4,1003 +tensorflow/include/tensorflow/core/lib/strings/stringprintf.h,sha256=SAvX97LSyk5RIaG8Mb6IsA0wrdd5DlagGELX-hwo3u4,1139 +tensorflow/include/tensorflow/core/lib/wav/wav_io.h,sha256=KRUZFI9uRCioI9O4X2UY_XvHsUHxDYQKqGSP4oXurHo,4165 +tensorflow/include/tensorflow/core/nccl/collective_communicator.h,sha256=Trezj35ExSaYycIOyJk-JQMnlL_CX_O3aP_0xcuQ4s8,1182 +tensorflow/include/tensorflow/core/nccl/nccl_manager.h,sha256=QXyz4W2encG1vvKmmlbw02-GxoOirzv3Vam5d5dwY-s,10698 +tensorflow/include/tensorflow/core/platform/abi.h,sha256=Z-gVuMEhC5-TkHstJXOOXIzyQyBkxdU0BENPJydYfN4,989 +tensorflow/include/tensorflow/core/platform/base64.h,sha256=HAd-FbGSI4oMjg7-LZUO9KJn6C21HwiHmkfC69YVSDw,1076 +tensorflow/include/tensorflow/core/platform/bfloat16.h,sha256=cfH6ju0EC8c0PJP5gN78cg-kKOPav7cXYOE0NVARrpI,1020 +tensorflow/include/tensorflow/core/platform/blocking_counter.h,sha256=zcYjQ5lR1LaDVVzCAQj_8rioR4TtceiM9Uzq4n47ch4,1076 +tensorflow/include/tensorflow/core/platform/byte_order.h,sha256=cLxrsW9c2pd5_jMWTwsW-AWkTL8J1S5CdNIYVIj31eg,1001 +tensorflow/include/tensorflow/core/platform/casts.h,sha256=QUZIA2KjDmTMnjayTyj67gQt-dutrQBoIAM2FaeEIHQ,833 +tensorflow/include/tensorflow/core/platform/coding.h,sha256=yTDpKOB4jF1h36xg3C7LBVG4T1AcS3HELH58zENpHJE,1956 +tensorflow/include/tensorflow/core/platform/context.h,sha256=MUmk4r2YVgxSSEyDqU7xgWJZ2DWq3K66toxe14gA0Wo,1087 +tensorflow/include/tensorflow/core/platform/cord.h,sha256=fHFY35-uVRGcSpedsNhtZk10qiMr4UgpBJDegdvEuls,853 +tensorflow/include/tensorflow/core/platform/cpu_feature_guard.h,sha256=R5G1PI20datb2bg3aWDOXCZciSw_QVg3SrbnRdfolmk,1278 +tensorflow/include/tensorflow/core/platform/cpu_info.h,sha256=vbY75lo0cr0WGbSA9IKc2bIJgYoh_yqbCtreLrO5_WQ,2756 +tensorflow/include/tensorflow/core/platform/crash_analysis.h,sha256=GDkjjlRE6lsgFDI_jxGAU2oUhvmflC5Decb6QHoeYBQ,916 +tensorflow/include/tensorflow/core/platform/ctstring.h,sha256=AtBfmdbkQl8Dibzk4IfjPbBScL628VytKEjsQmY-fPk,845 +tensorflow/include/tensorflow/core/platform/ctstring_internal.h,sha256=rpkVGGea6l14kTgZnUKgj-Q7Q3XOPuox1y3bN6CrDD0,881 +tensorflow/include/tensorflow/core/platform/cuda.h,sha256=FC_SDaRf34DvreJrmcIZRPmYi5pTm62AZ6M7zWGP5jg,943 +tensorflow/include/tensorflow/core/platform/demangle.h,sha256=J7OAM41E1OWyE_kObO5tIq2Bb7S2sHuscOusDE9ayGM,1005 +tensorflow/include/tensorflow/core/platform/denormal.h,sha256=dWLiVV88-_V3J06yAAwFiIYqi_zDWv4if2tiHcZ3KUg,1289 +tensorflow/include/tensorflow/core/platform/dynamic_annotations.h,sha256=foqbKqxHgTjglZDbTee5ZfoLiRtmau-kkwMfWdTwbm0,960 +tensorflow/include/tensorflow/core/platform/enable_tf2_utils.h,sha256=zPOy8OQeDMHDN_eWC_Yoi08ctnU1ncTRKmPm8jfHFPE,1194 +tensorflow/include/tensorflow/core/platform/env.h,sha256=GNHh4ylfpgFG44WGtLVpc-UhU1rAfsPsaiMIiGpwPJs,2033 +tensorflow/include/tensorflow/core/platform/env_time.h,sha256=EbCRJE3MqXAA6UsxI20_LPVQOBmHddBpiDN7Y0N4M7M,991 +tensorflow/include/tensorflow/core/platform/error_logging.h,sha256=HluqnGcXFtgNjJ1Xf4vmS0HWWkuYdMSkz1cwmlUkLN8,947 +tensorflow/include/tensorflow/core/platform/error_payloads.h,sha256=TXuWMKbmLnXVCz0Tx9-XvnUmFEXmQ3aGxjn-a4x0Vsk,1982 +tensorflow/include/tensorflow/core/platform/errors.h,sha256=6Zx_EiyjbZY5p7A4nRZ_gNfPC5ArlMB-ORlF6ZparpE,3813 +tensorflow/include/tensorflow/core/platform/file_statistics.h,sha256=OYIt_uGpCCKLWJ1XOZy4H2pqkkhO-yvyYZMRgcRLpB0,1006 +tensorflow/include/tensorflow/core/platform/file_system.h,sha256=UmM-_xvASAoMgApFwK87IQwaxFkyMauainWTds3HXWA,1638 +tensorflow/include/tensorflow/core/platform/file_system_helper.h,sha256=tM8Ke5O0gaZH8vrjOM9b3lUlr4hA2uHpCqk-DFBArhE,1343 +tensorflow/include/tensorflow/core/platform/fingerprint.h,sha256=PqTYrEFCq5UXRqJA6uhAcr4G4m3eNDKXuMRe3Xc1-A8,1271 +tensorflow/include/tensorflow/core/platform/float8.h,sha256=Dnzcz9VSem6DSa5gjhl2kVp5QHkDqbCEHc64GNjYrrc,971 +tensorflow/include/tensorflow/core/platform/gif.h,sha256=UgJ_OvV4qTxZgq7blEB9CMpG14Fm2a_oomTCXEIxvl4,849 +tensorflow/include/tensorflow/core/platform/hash.h,sha256=v9Y_Iarbh4TgUnHbxCi24cGld1L6M0kk5Q3K_t5eZRE,1177 +tensorflow/include/tensorflow/core/platform/host_info.h,sha256=Kv4NkLTIHX3bpyTgWsGQIzzxXXy1i1Jv0wF71rlOKmU,1060 +tensorflow/include/tensorflow/core/platform/human_readable_json.h,sha256=MVUiwPbWErbqlye2AiIYVqLX9SHWxAyGKQBpMVGtPZU,1106 +tensorflow/include/tensorflow/core/platform/init_main.h,sha256=jk9Kosm9-LUegRDDXpFsVdZQirXZiacU-IxGgUrMhJ8,965 +tensorflow/include/tensorflow/core/platform/intrusive_ptr.h,sha256=TqcXTta7QHbD3KAKl0qRc64u7Mz842He1ie2zxiAhhk,1045 +tensorflow/include/tensorflow/core/platform/jpeg.h,sha256=fprBA5VpAkJCc36eRGhDU5Ua_XLg11Rxn_80I8-WNnA,829 +tensorflow/include/tensorflow/core/platform/load_library.h,sha256=rq5VMC2UVtZwHLWA7MafdAg9a7CE3tkd-w18qEVxwV0,1096 +tensorflow/include/tensorflow/core/platform/logger.h,sha256=tT8DuDPxje1URAIecQYW8aYxH2X-GyqCdpc8lHJ0yBY,1001 +tensorflow/include/tensorflow/core/platform/logging.h,sha256=01hiktNw80UbP8D1Qvvocjn7ALbqr4ggIwZfx83ebKc,1405 +tensorflow/include/tensorflow/core/platform/macros.h,sha256=DxC1wioRFYpjFAPmRJSSDiUfXFh2ozoSusyeqM8QTpQ,1100 +tensorflow/include/tensorflow/core/platform/mem.h,sha256=oM0WgLsUhTQk6T60hp7fh6pPlyoje4NunLUvDfhNSyg,1552 +tensorflow/include/tensorflow/core/platform/mutex.h,sha256=iKQ5Eu2vMCPGQaC0NUGxu7GsBpb6m5_cF7iou87DP1Y,1333 +tensorflow/include/tensorflow/core/platform/net.h,sha256=nrXKf2exdvl6HjG8RIw0L21soJDy2d4BzmU6j4TgOWM,1002 +tensorflow/include/tensorflow/core/platform/notification.h,sha256=49npZb5_s0i5BMrGKdX-Djjsawc0CXPFiBwopGxpnHM,1105 +tensorflow/include/tensorflow/core/platform/null_file_system.h,sha256=s_YbxyMPdwAGOKxZiZdmPBswZG80GevfE8i_xCGcN7I,1034 +tensorflow/include/tensorflow/core/platform/numa.h,sha256=IntY4yb0OeHrjRcIrUowFABxWG4P1Sup1E8aI63Hne8,1284 +tensorflow/include/tensorflow/core/platform/numbers.h,sha256=c9rSXyg5NzGfnna7h_jhewz9tROOPR8jfFu_f5Kz7uY,1964 +tensorflow/include/tensorflow/core/platform/path.h,sha256=FAkuNk2uTaEg6Xkf1hH_7IPJd5tE0TAA8SggTtKaGSA,1550 +tensorflow/include/tensorflow/core/platform/platform.h,sha256=PuWGSlaQ14VZ0iXFYJz7Rqlc7jvbI6AxIvZretmd46s,845 +tensorflow/include/tensorflow/core/platform/platform_strings.h,sha256=MBdU_7SIVMZB0BeaqMsMKLXkQRFXkUxOuEQ0rIfbe7Q,21294 +tensorflow/include/tensorflow/core/platform/platform_strings_computed.h,sha256=Xa7RVxdnRLNeap8-mO4q2Gd59AkRP5AHm_i74mPR_7I,19439 +tensorflow/include/tensorflow/core/platform/png.h,sha256=Rd5tTuNZxjOWCG505D5s6hs9GPWUdA12PGrvKEgLMxE,872 +tensorflow/include/tensorflow/core/platform/prefetch.h,sha256=gztVJG413IxekO7QlcmJZA4P4H3Tpg6uoHWBg6VzC08,1223 +tensorflow/include/tensorflow/core/platform/profile_utils/android_armv7a_cpu_utils_helper.h,sha256=WXsg5ryQzqXIc8lLgro1rkJJ21GvB8oSc_IzQkMgtCY,1613 +tensorflow/include/tensorflow/core/platform/profile_utils/clock_cycle_profiler.h,sha256=cbtq6XUixAc1TWZdCvgmXMxtfpsKCKXBEodGjqVX8x4,1217 +tensorflow/include/tensorflow/core/platform/profile_utils/cpu_utils.h,sha256=IJ_pKpOQC0dgB-t1oFoPBluzGYNRibQhKQwFqTRY6Iw,1322 +tensorflow/include/tensorflow/core/platform/profile_utils/i_cpu_utils_helper.h,sha256=jkYtzS_nj_gbw0bEuJg3QA3c95ms5ZM4Yj5W84FDEF4,1191 +tensorflow/include/tensorflow/core/platform/protobuf.h,sha256=KAbVHUEggd-jrSQJu-QvFz55Jju79lk0ZEkza43zxhg,1463 +tensorflow/include/tensorflow/core/platform/protobuf_internal.h,sha256=YYzZHgK3pw6Ut6Bht27Fw5v3qB4ZqMm3vRQ7yGBbn84,1688 +tensorflow/include/tensorflow/core/platform/ram_file_system.h,sha256=AOVOVWxhF-2Y2ROGBy5414UeIoZvraNxqQcbSn0CiGk,1290 +tensorflow/include/tensorflow/core/platform/random.h,sha256=sTwBWjCg3cienUR4K_WGrESpQOoE54YDoELOdDIS9ow,1070 +tensorflow/include/tensorflow/core/platform/raw_coding.h,sha256=UBgTzuLnUzztPGa73GSPyWqfmy8hpytusElqk-hD3s8,1143 +tensorflow/include/tensorflow/core/platform/refcount.h,sha256=Er6ITZ1_o4q49L_e_mN5bhO-1uX0EUWgPLMsLK3xqcA,1283 +tensorflow/include/tensorflow/core/platform/regexp.h,sha256=jcDgVKwVlfnSNNhhwrUWu1B7ui2BQRrQ7RuoShBsstY,836 +tensorflow/include/tensorflow/core/platform/resource.h,sha256=wzQwFqY2XQUEAF1SnxvLtQiDEYqr3EhhoqUgMINpIp8,982 +tensorflow/include/tensorflow/core/platform/resource_loader.h,sha256=uT7d2kR_uhiG6LqwXr5jEpUr1Ayu4hs87Jp1VZTYo1s,1232 +tensorflow/include/tensorflow/core/platform/retrying_file_system.h,sha256=KAu3jpXPm-JC1XC_rSDovrvI-t3OKS9ITy5cbvHsYXg,1354 +tensorflow/include/tensorflow/core/platform/retrying_utils.h,sha256=awdhn3rwNY1HZeTdKJL7u5PLE2gciFbvFtvx9oDRxFA,1116 +tensorflow/include/tensorflow/core/platform/rocm.h,sha256=fdwYPVLotpf0ZP-wYyU_SsYKS_i9R9Abl2lI9vF0Qb4,943 +tensorflow/include/tensorflow/core/platform/rocm_rocdl_path.h,sha256=O_gOLZAyfZiENcSqJHN6ZN59EY_iRR_DI2hw8rDbabw,1034 +tensorflow/include/tensorflow/core/platform/scanner.h,sha256=qlxt9BEaUqCGkoEezLVDX7ger15PDC73bq7RpX-nuIo,1005 +tensorflow/include/tensorflow/core/platform/setround.h,sha256=7l2sSGvJItT8cz9TYBIK20qy-Kj0XuL3h2PER4ZLLZs,1024 +tensorflow/include/tensorflow/core/platform/snappy.h,sha256=CzRwzynLDWYChxu51X6ITxBW6bn3wEkefq8Fkz10djo,1307 +tensorflow/include/tensorflow/core/platform/stack_frame.h,sha256=CU4dZeKXBOGbzKEeb7W2HP8tlvjMh_VxhscphOdbWXI,944 +tensorflow/include/tensorflow/core/platform/stacktrace.h,sha256=DJo_w9W2mqA66GaA3OpcIGmM__4CbGw99-mmWJFS1wQ,1142 +tensorflow/include/tensorflow/core/platform/stacktrace_handler.h,sha256=I93ZCxVzr6r-SAL1hx69plPkIEzA2pIUrgFs5bayj_w,1294 +tensorflow/include/tensorflow/core/platform/status.h,sha256=dWqBI7VMTJLlAKtHgkfRBEgxxPvQZGdD6rXILRIhhnU,1503 +tensorflow/include/tensorflow/core/platform/status_matchers.h,sha256=Tg3vaj3T4BZqE7PUEyGflZZTS-XIlrKFoMBJHl72eLY,1841 +tensorflow/include/tensorflow/core/platform/statusor.h,sha256=Fa5f3lQm-BXYjmBdU5SoVz7hU4qCRvjvSJP-eWMbqX8,1017 +tensorflow/include/tensorflow/core/platform/str_util.h,sha256=RwGrSl2o66m5dyExHxp440AZskcK5ttiCFj3vJUUt3E,2158 +tensorflow/include/tensorflow/core/platform/strcat.h,sha256=Hfqg3mehXFzF8IM8cU8rcXeDL6LMddHCtZXi3V0hpgs,1812 +tensorflow/include/tensorflow/core/platform/stream_executor.h,sha256=3rORWyj4mHCuIeB8MD3Dn61hTjino7vHm5WwrBmF2jA,1501 +tensorflow/include/tensorflow/core/platform/stream_executor_no_cuda.h,sha256=z5QTbf6Mo7RiNqVZpSscoSifZrhhB00xcQ0qrrwn1Rw,1481 +tensorflow/include/tensorflow/core/platform/stringpiece.h,sha256=n_bNLfEwH6U6om2h6j8jdd-ZjmjOJqJfdlphlSZQ0l0,1449 +tensorflow/include/tensorflow/core/platform/stringprintf.h,sha256=u7eqrq0aZsSu0jqpt1BubCugcdCzxL-Lj8AcuUklZDY,1447 +tensorflow/include/tensorflow/core/platform/strong_hash.h,sha256=ThmTBB8ybMQ25lfC8UB66KRIe-_LJ1VqRm7FU4Yolyc,1743 +tensorflow/include/tensorflow/core/platform/subprocess.h,sha256=tiWe5ZRyXFg-ShzoRW1pmBXjRmbzTvgSWVNk7SyeoWY,1244 +tensorflow/include/tensorflow/core/platform/tensor_coding.h,sha256=Lkdl8TtWsbs2JJt1k8jR3KuNvTuEn79Cuc9RxYGBNy0,5502 +tensorflow/include/tensorflow/core/platform/tensor_float_32_utils.h,sha256=twtcGM4k5r1h2XV2ujheSufOS_FDs5E5cWHlYuDQM5w,1117 +tensorflow/include/tensorflow/core/platform/test.h,sha256=8iqlgbIx18_vIj1m3U_HeIlLTEousd91ubRCI-bPQJE,1251 +tensorflow/include/tensorflow/core/platform/test_benchmark.h,sha256=5q6DzzjJb7gmRMnsV7CFH2HEzaZdEm-JBNhBKhvDqA4,1156 +tensorflow/include/tensorflow/core/platform/thread_annotations.h,sha256=FC-jnnWJvsjEGaykHxF272R3Ype3dAuG0HJ6B-aDxAQ,2039 +tensorflow/include/tensorflow/core/platform/threadpool.h,sha256=pyaYueIFxzpPZPa-YRFk6G3wG9YboSrhTLTD-x55EJQ,1307 +tensorflow/include/tensorflow/core/platform/threadpool_interface.h,sha256=KV7pwnN17fasPG_wDV3gq86jpurFInBaRk75QiSYZxY,1050 +tensorflow/include/tensorflow/core/platform/threadpool_options.h,sha256=hnTnXkuyCQqvDAWTAdZvJLtNM7zC0X6qSiJ0rFGt2g0,1088 +tensorflow/include/tensorflow/core/platform/tracing.h,sha256=JykgxRKmReTVL6RyqfN9CrAObfMVoyd0thnW8JVMXbY,1777 +tensorflow/include/tensorflow/core/platform/tstring.h,sha256=H0shcLd7Gh49ogxbJiyMGWzoy8R_VfVTfUiP6x4N08w,1038 +tensorflow/include/tensorflow/core/platform/types.h,sha256=1mdxE3KbLZy5WSFQ0tZs22hacGGXaZwE-zfeXUWOI-E,2076 +tensorflow/include/tensorflow/core/platform/unbounded_work_queue.h,sha256=0JFx0OyHeL4TzovfWy46ZgEDBwRPx6VtHlSpZF2dTXE,1188 +tensorflow/include/tensorflow/core/profiler/backends/cpu/annotation_stack.h,sha256=7zE0mMyRZ0IoZ-AIPZ95VdP9zv-55BGE7R1PYoZkOG4,1296 +tensorflow/include/tensorflow/core/profiler/backends/cpu/traceme_recorder.h,sha256=X-9vIlkeKNvsDnUhyb3DNtXNHPLyGbI2KumJ5B3ZTrw,1398 +tensorflow/include/tensorflow/core/profiler/convert/xplane_to_step_stats.h,sha256=mt_RLdgP_rOeJdqZxrzNW4ph9LBGMgVvE7rgIEWwcSw,1215 +tensorflow/include/tensorflow/core/profiler/lib/annotated_traceme.h,sha256=jGswAZGhQ_pWVUX4l4q2YTrMdSqh7slXl0KVzABOSnI,2192 +tensorflow/include/tensorflow/core/profiler/lib/connected_traceme.h,sha256=07aF2RU0vTb_XNaxljC3u-5oB2-hJtMPMlEnWC0Xw70,1365 +tensorflow/include/tensorflow/core/profiler/lib/context_types.h,sha256=l7kUCXKecnZ50PuH1z4PhVPsoZWn7qMvLhpYJABnvwE,1141 +tensorflow/include/tensorflow/core/profiler/lib/device_profiler_session.h,sha256=2Xu7M-yDSPH9BL5ktdtQqqfZQDnlx4_BqgmmVjDKSAs,3038 +tensorflow/include/tensorflow/core/profiler/lib/profiler_interface.h,sha256=FNf6eRF7RplS4d1-jP5gEOuwPMu_0jcn2kHvtADoJj4,1151 +tensorflow/include/tensorflow/core/profiler/lib/profiler_lock.h,sha256=wAMIbPRfh9XLjjg5IIN0dcOb5UVqLdIucaUMn3SnvEs,1072 +tensorflow/include/tensorflow/core/profiler/lib/profiler_session.h,sha256=8srpiPFvZY2_nuEJY1QbDpZplMEtbPnw_jrZR7hcRqs,983 +tensorflow/include/tensorflow/core/profiler/lib/scoped_annotation.h,sha256=LI5VN3VQqMbeGeDpTUNPJ6xfXihdWDlD7sxKGrc-56Q,1336 +tensorflow/include/tensorflow/core/profiler/lib/scoped_memory_debug_annotation.h,sha256=x0DYbbDyYOKtUuUqIhaaCnULuvqfWLFZN1g9EP8f-fA,1248 +tensorflow/include/tensorflow/core/profiler/lib/traceme.h,sha256=hquH1ov8ev2o2vU5nmzN8ION9fm0UF8OBYv9cRFv-ps,1825 +tensorflow/include/tensorflow/core/profiler/lib/traceme_encode.h,sha256=wzOrysjvZ232JVMHgRIjGuAdr8F7yj85BuLh6ekBSOI,1450 +tensorflow/include/tensorflow/core/profiler/profile.pb.h,sha256=Zieo-rJO24viCNoYv1hMKMx6BJu7IVSxl9qZ4wtG2V8,2721 +tensorflow/include/tensorflow/core/profiler/profiler_options.pb.h,sha256=uk7gGP8Q2YBfJw_6YwITu_2i4w2ezsx6es7D11ZUOOg,2723 +tensorflow/include/tensorflow/core/profiler/profiler_options.proto,sha256=uRHdbBczNDVKg4m_wyGIkfnByaoRhIn8IGRcSDQJm7E,109 +tensorflow/include/tensorflow/core/profiler/protobuf/xplane.pb.h,sha256=Z_BCN5xhybV7--WRbzAV6GStsrV-lRBFYNYtqQfekOg,2752 +tensorflow/include/tensorflow/core/profiler/protobuf/xplane.proto,sha256=6YV-ETqPcFSqjCQA6F5FhI20vcoNH_CgSMWiKXwspOk,108 +tensorflow/include/tensorflow/core/profiler/rpc/client/save_profile.h,sha256=k_lu0dbd-aki0bMr7Pq08w227nZIzUNQPKXOroKaeQ8,1562 +tensorflow/include/tensorflow/core/profiler/rpc/profiler_service_impl.h,sha256=tUabVFIWb22RGZl6W6A_1JbtzTnPsqSah60fR1-JWM0,1145 +tensorflow/include/tensorflow/core/profiler/tfprof_log.pb.h,sha256=ozkgemE7q7AEwc9ZP3UemoX_VuH64rriR9s5LPJSQU0,199065 +tensorflow/include/tensorflow/core/profiler/tfprof_options.pb.h,sha256=aTJaCK_FkpfaHc4u5FMYmxOKgNt4geZDunh9kpio3Hk,79667 +tensorflow/include/tensorflow/core/profiler/tfprof_output.pb.h,sha256=IYtuThHBvqY1Y_Tf0u8CioQ4Lq8nfxNuv7aIcFONfjs,121949 +tensorflow/include/tensorflow/core/profiler/utils/gpu_event_stats.h,sha256=yQfBzxmYjKiY3LEhXkEQVMvujFOWt9m5uQ8k31MpUuE,2372 +tensorflow/include/tensorflow/core/profiler/utils/math_utils.h,sha256=HldRhl04Bw1qU_v1Q6T-HvNg9W7y00AHERIsy93NELA,2224 +tensorflow/include/tensorflow/core/profiler/utils/xplane_schema.h,sha256=aI-mW-10z0-dVs5H7JlxMD3UaWF1VyPRlyF7xm-8JzA,4056 +tensorflow/include/tensorflow/core/profiler/utils/xplane_utils.h,sha256=TsLrcJJ056q21Hm5v13ueu6_Ms-VeBNQO1EY7oqqaEs,3141 +tensorflow/include/tensorflow/core/profiler/utils/xplane_visitor.h,sha256=-FcLW4IIdk0sRe-dGVk3Tajq-yGp3eMaBaaHuhje3ME,1431 +tensorflow/include/tensorflow/core/protobuf/autotuning.pb.h,sha256=4JjW9Alj9wqPxRvg1xN11cUDyFL5YkoX0rw-GOWYLU4,2645 +tensorflow/include/tensorflow/core/protobuf/bfc_memory_map.pb.h,sha256=Sv56ooy6vsHgNmojtnEGGFv_Np5qrH_z7stsXM1V19Q,2710 +tensorflow/include/tensorflow/core/protobuf/bfc_memory_map.proto,sha256=7Ts8JR1j-rNddtoCXtJgY-ybfaFLxT78ZK-o5Knlqzs,208 +tensorflow/include/tensorflow/core/protobuf/cluster.pb.h,sha256=Wgr3xPpqlIy6UdrRr5Ni3_eF8-mjWd6QwAZHMmJg7Os,20721 +tensorflow/include/tensorflow/core/protobuf/cluster.proto,sha256=cbEeKaWBLLS6k5iwsifj-36Q7c7WLPcj1CJy5aCXe4E,3144 +tensorflow/include/tensorflow/core/protobuf/composite_tensor_variant.pb.h,sha256=ZxhPh_emtvlPFlMj2cFm2b1ul3zmgjHOMfbFwocnTf8,13368 +tensorflow/include/tensorflow/core/protobuf/composite_tensor_variant.proto,sha256=fmhA429Na6acWvgYcAdLbQe800waIIk4TsJAZpMNrpU,548 +tensorflow/include/tensorflow/core/protobuf/config.pb.h,sha256=5In2iKl5UEu_wT1UYTumqkEhDJDRAKmU-twoWWdeFbU,364418 +tensorflow/include/tensorflow/core/protobuf/config.proto,sha256=x3nNy0eKDO7fHS4GRgUPwb22IWta7tYX6S0tCfZJmaI,40647 +tensorflow/include/tensorflow/core/protobuf/control_flow.pb.h,sha256=eSfDSFwaKdqctIAIcRHHcQQo9c0oq4ftg0bvvL_Olbw,90343 +tensorflow/include/tensorflow/core/protobuf/control_flow.proto,sha256=wI9t_n1coA7vf28L1yWUJPzTotiJBx0uQXp_Tl_oQ7g,2495 +tensorflow/include/tensorflow/core/protobuf/conv_autotuning.pb.h,sha256=RN3BH14OgtGmWCTggp3P0OYnXR4T5fWmpxNbYvcFFdE,54646 +tensorflow/include/tensorflow/core/protobuf/core_platform_payloads.pb.h,sha256=78NAFerhVNkmcURpXjLH-34dleIDrf5bPaayt5MSGko,13729 +tensorflow/include/tensorflow/core/protobuf/core_platform_payloads.proto,sha256=gI8adu-L591Tg5NSaBOKD5XnBzGx3RaGRZ9cyM8f70s,698 +tensorflow/include/tensorflow/core/protobuf/data_service.pb.h,sha256=U51lDQfmBIU6A4T1wSM9MpUbpRxpLdb92JQ4sJhzq1M,46762 +tensorflow/include/tensorflow/core/protobuf/data_service.proto,sha256=n7_CV3WUg0_4NRaCdV6tLDuFfRZjoqvWKQpUHeGGRm4,3164 +tensorflow/include/tensorflow/core/protobuf/debug.pb.h,sha256=E5_4_ukDk3sImCwa84horMev6U9yXhPojY6CU97chU8,56680 +tensorflow/include/tensorflow/core/protobuf/debug.proto,sha256=YdFm0p0OEZAX8V4lr6x2pInGPpbAq6o0Vpsx_vj9KCs,3365 +tensorflow/include/tensorflow/core/protobuf/debug_event.pb.h,sha256=u_W470hEPbsZgit2nyjZ76ZJFbvu60gY6jeWZgc6R9k,209646 +tensorflow/include/tensorflow/core/protobuf/debug_event.proto,sha256=6tDgbtVUnPvlZ55oD3pWOgC299SQli1k6hKdtJJwJIs,10213 +tensorflow/include/tensorflow/core/protobuf/device_filters.pb.h,sha256=2a4N00C-cmyGUVbYYQ20XhswYYbW_EkebFKVX4wuJpo,32633 +tensorflow/include/tensorflow/core/protobuf/device_filters.proto,sha256=feTlBero_b6vBJdB5lAUBmQUecp--2x-dNsjFK9z0_M,2678 +tensorflow/include/tensorflow/core/protobuf/device_properties.pb.h,sha256=_MRBPz40wfViM3ZPSkmHBgJ2IBF-rIEWJccIwtEfW_A,40874 +tensorflow/include/tensorflow/core/protobuf/device_properties.proto,sha256=XLiSo1veCzgTV3DRIRzPo_w-SeKyZvrVDIbLLX8JUPE,1882 +tensorflow/include/tensorflow/core/protobuf/eager_service.grpc.pb.h,sha256=Nf5BsU9M-8y8iWzJstYB_Ud7_mC161Rkn-tM3PXp9NE,129741 +tensorflow/include/tensorflow/core/protobuf/eager_service.pb.h,sha256=HtM5zBUEk8MMsopV_uGWg4Ebjbt0XHziuesY7MVN7X8,315314 +tensorflow/include/tensorflow/core/protobuf/eager_service_mock.grpc.pb.h,sha256=9tgH9ByoEsxBEDUYHoBug1n4JY8ODw75A47n2fjeQNw,6052 +tensorflow/include/tensorflow/core/protobuf/error_codes.pb.h,sha256=OHu88NZgmiZE7ec2r5gLVyWrQyWP5CK2h4jZrjvmcA8,2714 +tensorflow/include/tensorflow/core/protobuf/error_codes.proto,sha256=jEv1KrkNZ8lViabgRrKublFwYwHnCEiJxjJbCSphMPY,463 +tensorflow/include/tensorflow/core/protobuf/fingerprint.pb.h,sha256=-Pl4T6AHitOEukwmV8Mnb2wV5SdhibT_JM6Xa9TMAnw,17600 +tensorflow/include/tensorflow/core/protobuf/fingerprint.proto,sha256=Upo2I3saMp-jdKuyuEdgEyrUj2s7L7z3w7XdapST7kc,1090 +tensorflow/include/tensorflow/core/protobuf/master.pb.h,sha256=iGCbHQWbnH6KO0ELCgPz4IWu73texaRff_872G-s5Ks,232263 +tensorflow/include/tensorflow/core/protobuf/meta_graph.pb.h,sha256=YSgqeFE8J-t0PQAEy7CGMy15M7ShDviLhtilaoaBuwc,223976 +tensorflow/include/tensorflow/core/protobuf/meta_graph.proto,sha256=XGlnaoHgyYodTt6ebE3sPhVrKYvzs17gHI6Bo5FL_-E,11551 +tensorflow/include/tensorflow/core/protobuf/named_tensor.pb.h,sha256=cd4W_sBV9a8RyHQP9NPHRvIoGMw1xyL_WyNlIvkgVcg,14256 +tensorflow/include/tensorflow/core/protobuf/named_tensor.proto,sha256=t4c9Df0vKSQUE5886UknFGwip9TNB6ty0IsX9801u8k,827 +tensorflow/include/tensorflow/core/protobuf/queue_runner.pb.h,sha256=TflkYcqiaGRYdVb_Tbu79kgpo9HrUBem9C4CxZXoWSs,23990 +tensorflow/include/tensorflow/core/protobuf/queue_runner.proto,sha256=wiFfw_oojIWjUzxavmBIeJ2JVdKyuuhv_iPnIKzwXXc,889 +tensorflow/include/tensorflow/core/protobuf/remote_tensor_handle.pb.h,sha256=59eNeGJPmlzWyDGaX6qUjRY7k4Z_GmmHqrnhyw8HZIo,30543 +tensorflow/include/tensorflow/core/protobuf/remote_tensor_handle.proto,sha256=9j2nosga-2iP1Yem5haR9fg-Ng7MY8qrOO13LZ4i8Jc,1216 +tensorflow/include/tensorflow/core/protobuf/replay_log.pb.h,sha256=S3CkN_KEL90cOA_c9_9-Pw8O_slJflelmUqxtQVTNdo,105671 +tensorflow/include/tensorflow/core/protobuf/rewriter_config.pb.h,sha256=_AFScg1XReArqvNhyJuP_IIIBWZttoQ8LSKRdKoYH4o,129754 +tensorflow/include/tensorflow/core/protobuf/rewriter_config.proto,sha256=mXYRBxkb-ATf9tPOApM9Q_OZtszL_DXxadnNYdGEzJ8,10562 +tensorflow/include/tensorflow/core/protobuf/rpc_options.pb.h,sha256=01_UwFKwhFk_0lX68EtIpnXHYUo1ucIhOX-QnxmurU0,2674 +tensorflow/include/tensorflow/core/protobuf/rpc_options.proto,sha256=wdhS6s1Mizjux-lLgJ2JplMzGQs8kKbViI9YgJMKLeg,205 +tensorflow/include/tensorflow/core/protobuf/saved_model.pb.h,sha256=Z6JREp_FVBfZ-ZT2oR9K8Cs_AWSxE7W2QO5OgUuN8gw,11335 +tensorflow/include/tensorflow/core/protobuf/saved_model.proto,sha256=kqXwAXsy0tluXe04GTYUjzBmmN0o4Grd_N7lX9AssAY,837 +tensorflow/include/tensorflow/core/protobuf/saved_object_graph.pb.h,sha256=wzMuPYg5_AxKZ7cnZJ-bADAKx1TyKrcgMIIRZRJthS0,224880 +tensorflow/include/tensorflow/core/protobuf/saved_object_graph.proto,sha256=QlrVuzNaoyymiiqCV1Ai8ycTm15TtgDiGNzZUwZVfjE,9947 +tensorflow/include/tensorflow/core/protobuf/saver.pb.h,sha256=dhyomP9LMeEDL8BNlhNEgWlbe9VbzU3Gb_IZT1DIZ4Y,23732 +tensorflow/include/tensorflow/core/protobuf/saver.proto,sha256=1j72FMZF1RHal3oFhEbE21PKo-tfzS_akTjcgsHTaaY,1787 +tensorflow/include/tensorflow/core/protobuf/service_config.pb.h,sha256=YbCbm8kU7Go7uQN5rht5rQ1w8EhSjtI40n3eKKZYlCI,60884 +tensorflow/include/tensorflow/core/protobuf/service_config.proto,sha256=7ajSaSkhq700ks79mzWk5E_P6DyomJS7YHfymOYpVW0,5406 +tensorflow/include/tensorflow/core/protobuf/snapshot.pb.h,sha256=MtFgJv0hmP5BKWkLmp0O5HlCVKxhwgVrj6UYMzdQOXU,59962 +tensorflow/include/tensorflow/core/protobuf/snapshot.proto,sha256=mUzAf2YR64YFsNQ5eWVmJz9aPx7YE2wmVYK32h1YBXo,2012 +tensorflow/include/tensorflow/core/protobuf/status.pb.h,sha256=7xEMdyFYuTuhMSyqKQDRPHTL0NYwVIBU92zv3JQ0ht4,2622 +tensorflow/include/tensorflow/core/protobuf/status.proto,sha256=6u_5pwOygrbIAqmRHKb9tIGAZih14MZFIvBilEcAMcg,444 +tensorflow/include/tensorflow/core/protobuf/struct.pb.h,sha256=y3rvTnqtbwSViKV7bw6Rq3_LBHNnAkD8Z75L1OPHrIQ,165667 +tensorflow/include/tensorflow/core/protobuf/struct.proto,sha256=7Nhek_t2avOmOckfTN57_5icYFb4A5_1Rh-ian7WpqE,6346 +tensorflow/include/tensorflow/core/protobuf/tensor_bundle.pb.h,sha256=n99ZfHzekUnLoNZ2C8Fh50cIMDK5FHvW2QZQ2Vat1ss,34063 +tensorflow/include/tensorflow/core/protobuf/tensor_bundle.proto,sha256=SlDJNikcpXE1Kr6DbX6-CpZCpjx3k3XmK_682LJXHkI,2399 +tensorflow/include/tensorflow/core/protobuf/tensorflow_server.pb.h,sha256=_aeDf-2s7IuBSbbaIl4Cl8zppE3MP5toPsMNF8EHl0g,28939 +tensorflow/include/tensorflow/core/protobuf/tensorflow_server.proto,sha256=bebWkapNQ-CR5nq7tfQzsCuCFq6cxQNqFnuZwy0s3wQ,2288 +tensorflow/include/tensorflow/core/protobuf/tpu/compile_metadata.pb.h,sha256=hDeiX9KPGXi9ZmknDFPoxkXKlphq90yX8HBX6RwYQ1g,113730 +tensorflow/include/tensorflow/core/protobuf/tpu/dynamic_padding.pb.h,sha256=S96F166zpUTR_iUnGQpQUbbHJt8eUXOAHLstzcg-A7M,10648 +tensorflow/include/tensorflow/core/protobuf/tpu/optimization_parameters.pb.h,sha256=3Sz0l04jLrjUvDaIzDfXNCK8BSyuKFdV8mzvrfBJBS0,383287 +tensorflow/include/tensorflow/core/protobuf/tpu/topology.pb.h,sha256=Tai0i_G2N9oTCWyaG3SvdLNeatFFSV6cBR6RchIN9L0,33199 +tensorflow/include/tensorflow/core/protobuf/tpu/tpu_embedding_configuration.pb.h,sha256=mvY9K3E6092JUbmSxmv6tSj3BXl1JUPMmJV0IJ13ND4,85347 +tensorflow/include/tensorflow/core/protobuf/trackable_object_graph.pb.h,sha256=GB9hU3KqXtJ7-Mp-EslGhRM4cR-93OhJHifbmVkC574,89118 +tensorflow/include/tensorflow/core/protobuf/trackable_object_graph.proto,sha256=jonNXVvtyQkrAZuzaA53risJu-e5y2HZJVU4c7r0_sU,2942 +tensorflow/include/tensorflow/core/protobuf/transport_options.pb.h,sha256=PvWRWaItaq556eF4VETVItVUb5oyXvDgE7IUSJDUenE,12702 +tensorflow/include/tensorflow/core/protobuf/transport_options.proto,sha256=TNgGQjlalo6pJkHPqzzgjA3zZgBVxv0jhbAkwnOjmaM,269 +tensorflow/include/tensorflow/core/protobuf/verifier_config.pb.h,sha256=tzLFRfQkqGPpQPQUMO2miNPDJmECQV9BaBSDiU1xc2E,13444 +tensorflow/include/tensorflow/core/protobuf/verifier_config.proto,sha256=OW6wmgrdFmfJU1tyertq2jz4XzQgrJNLn_Weh4GeNHs,742 +tensorflow/include/tensorflow/core/protobuf/worker.pb.h,sha256=jmzzBt9aSWtW0jzSab2kDUq-5q7E3CzwkqByGVEsxxw,442977 +tensorflow/include/tensorflow/core/public/session.h,sha256=fgw7XDiyZBmUv12ZdhkhLCiv61XwoO3lqbX2-9tmfio,15595 +tensorflow/include/tensorflow/core/public/session_options.h,sha256=IvvdnAO6EvBPwC7EuwIqrtZ7zRqmald5KEXYXIC06W4,2219 +tensorflow/include/tensorflow/core/public/version.h,sha256=JznWjpnm-e7wLkFjzpic6z5tgZmnE4O9-JW4AhEsmbI,6018 +tensorflow/include/tensorflow/core/summary/schema.h,sha256=kTWDSbO9fqnp0rNXFbU6TOKC0TUu1eRZrCzK1_CKfDo,1242 +tensorflow/include/tensorflow/core/summary/summary_converter.h,sha256=esfW6ScL_-7guu1bVHa3vLCZO192LHAkIGg4EeXQ1aM,1725 +tensorflow/include/tensorflow/core/summary/summary_db_writer.h,sha256=hTqMyUhQM1lL_e8joPHzDBvwHmQGlqXta7PYHz7RCL4,1773 +tensorflow/include/tensorflow/core/summary/summary_file_writer.h,sha256=YfqgLUupUtxYQxiCvG6DiRZv-0LHj7HGMDMdC_0cvsI,1916 +tensorflow/include/tensorflow/core/tfrt/common/async_value_tensor.h,sha256=F4wMRapthRUqJNj_jHG_ijSKoFOnwEwAWszz0sAWWRg,2513 +tensorflow/include/tensorflow/core/tfrt/common/create_pjrt_client_util.h,sha256=0-aJQk9K4qOTaOWh1FyNHxdJkfxwqvHaRH560D6BMKw,1969 +tensorflow/include/tensorflow/core/tfrt/common/global_state.h,sha256=uouQ72vbiGzqWm7D3ewwcNmXr_JFV3ngNSweTaiXwLU,1376 +tensorflow/include/tensorflow/core/tfrt/common/pjrt_client_factory_options.h,sha256=d0-llRL5BUquwirGdhm_a857fZNFTKDglGduQVjvcfs,1560 +tensorflow/include/tensorflow/core/tfrt/common/pjrt_client_factory_registry.h,sha256=AjnVCR8qPXT1muRa06Pzx-qV1c8gZ1WFtSaxWngL8mU,2812 +tensorflow/include/tensorflow/core/tfrt/common/pjrt_state.h,sha256=xsz1llSrEvLjikSOaJBTBPe3i0KHHZ9ZtnITt3PLJk8,2215 +tensorflow/include/tensorflow/core/tfrt/common/pjrt_util.h,sha256=LDGp9e4Pmp8nxVwu9w5jYy-LMfFDL0H64T7RdUGp8zg,1633 +tensorflow/include/tensorflow/core/tpu/kernels/sparse_core_xla_flags_defaults.h,sha256=TVUZnTiVwyf9zm3wnxHysMLGnGYqhEKIUXk7B3KcIlQ,1218 +tensorflow/include/tensorflow/core/tpu/ops/tpu_embedding_ops.h,sha256=jS8iOhLXo4l22qN9-olzxC5v0QDZ_-CFg1Kmh4U0EvQ,1300 +tensorflow/include/tensorflow/core/tpu/ops/tpu_embedding_shape_util.h,sha256=juHrLG3jXIuRCY0ulOSjGx4zF-qUWHz-wX7WGT8M45g,2985 +tensorflow/include/tensorflow/core/tpu/tpu_defs.h,sha256=OUpc0W3KDd13oo2iBUjA-d_jN8X6lFX0h0milckCrck,2471 +tensorflow/include/tensorflow/core/tpu/tpu_embedding_optimization_parameters_utils.h,sha256=0O8kCxBTt1zbQ9RvMVgJ3I6J9xURxfIftplmVWAqhxw,4929 +tensorflow/include/tensorflow/core/tpu/tpu_embedding_output_layout_utils.h,sha256=RmgWYUY1_A57m3VFo8_OSzynbuuvOINEiQTetg4NgcI,1380 +tensorflow/include/tensorflow/core/transforms/cf_sink/pass.h,sha256=bmADpHaJUEUNH4d04qPAY881KvxrEZmpnHMxjbaKhn0,987 +tensorflow/include/tensorflow/core/transforms/consolidate_attrs/pass.h,sha256=0YbjAneT9UdJYBAK7Qcu9A6W4e1OTLQmlu-XwV3WaWg,1082 +tensorflow/include/tensorflow/core/transforms/const_dedupe_hoist/pass.h,sha256=x4E8XGRxFAQrFCLkFfm2o8Q6gVF14DlLSRVxFX5pymw,1169 +tensorflow/include/tensorflow/core/transforms/constant_folding/pass.h,sha256=6jgH0uG4v8DnYZM9FaaUf-CxLNIJMs3yeBvJwayp-0A,1181 +tensorflow/include/tensorflow/core/transforms/cse/pass.h,sha256=Se_HrIs0N4RiRHoAyNSSIvEaAIm9cwEbxdPVP15eBY0,1000 +tensorflow/include/tensorflow/core/transforms/drop_unregistered_attribute/pass.h,sha256=5XoD17gq_NEwsjqW2hRyDdxrfwDXnVi0nVBU1q5m5QI,1192 +tensorflow/include/tensorflow/core/transforms/eliminate_passthrough_iter_args/pass.h,sha256=DozqDfXPwvt41lT6gHn7dLF8aBtBY9rgL0Rt8jmbsXA,1310 +tensorflow/include/tensorflow/core/transforms/func_to_graph/func_to_graph.h,sha256=rRY2fvXwG6RA9q4g951trGtdT-fhFOS_AYcua99wU-w,1258 +tensorflow/include/tensorflow/core/transforms/func_to_graph/pass.h,sha256=t9o4SXF--AnJxE-hLn6a42-hvL6YWzzHlyQBp13B0qY,1163 +tensorflow/include/tensorflow/core/transforms/functional_to_region/impl.h,sha256=AJWb1BSbW6a1nLq7DdNmZpLOQBSoSbI6CZTglJJeu-M,1187 +tensorflow/include/tensorflow/core/transforms/functional_to_region/pass.h,sha256=IboqhgI8Z956RRGL2JAkWMqEwbAJKOvrDHgVtap4DDw,1029 +tensorflow/include/tensorflow/core/transforms/graph_compactor/pass.h,sha256=OKH1sMon3Iwv_d0SbyWVykSb7jvfS1Ie-Ykd9sXxICQ,1149 +tensorflow/include/tensorflow/core/transforms/graph_to_func/graph_to_func.h,sha256=9JSGE2kRNsN6n62Px3Gf5yWdpVuCWDj0P_vkPDyXFt0,1992 +tensorflow/include/tensorflow/core/transforms/graph_to_func/pass.h,sha256=5KT14-g4KcTbCYXpVQAdznQ-92oL3Mo89a_fZAdBBt4,1521 +tensorflow/include/tensorflow/core/transforms/legacy_call/pass.h,sha256=_mRem0Cw2_G_GfZD-a_oomXcOZb6zThoZ9v6-JU6Q7c,1035 +tensorflow/include/tensorflow/core/transforms/pass_registration.h,sha256=2yZt18thP-fxI1hNjd7XQr_Rr-zLzDSz4qdaD61RSps,2068 +tensorflow/include/tensorflow/core/transforms/region_to_functional/impl.h,sha256=nwSXOpCf07Rp68asRuvEnrPqoi9lXPqvh505g-N8bs0,1393 +tensorflow/include/tensorflow/core/transforms/region_to_functional/pass.h,sha256=ldR_3etlv_xSMjdw-qNtmpAgcaKnfUEu8hiSquYmKKo,1467 +tensorflow/include/tensorflow/core/transforms/remapper/pass.h,sha256=NqFXOq85khPKbzn0ti-o8nY0C21MCSkIhyesJboEel4,1357 +tensorflow/include/tensorflow/core/transforms/remapper/remapping_helper.h,sha256=MrEmimmp7GK88mnUX7J4FQrqcoM92IZmsP27k11kXzE,8980 +tensorflow/include/tensorflow/core/transforms/shape_inference/pass.h,sha256=X9GuPVrWZF4NMX7AtOUEF-FKbyFztJhAN_GNz4ijHLk,1190 +tensorflow/include/tensorflow/core/transforms/toposort/pass.h,sha256=TfEJdnfaJm8EgpP2MD6tbrGh4P1616J26HCMzvHpsw4,1403 +tensorflow/include/tensorflow/core/transforms/utils/eval_utils.h,sha256=euZFOGZyOYzkLRxHel5r3NmK_yk8TQhzSt09TERIs7o,2580 +tensorflow/include/tensorflow/core/transforms/utils/op_cat_helper.h,sha256=sK_I5XtY8z6tR4jQPHmp1ryhcISW4oLqqcu9Ea050Gw,1904 +tensorflow/include/tensorflow/core/transforms/utils/pdll/utils.h,sha256=_3Jr3sEq0UMitvITN1mrKbxXXIBlCZEgftkyOGUZuWk,1057 +tensorflow/include/tensorflow/core/transforms/utils/utils.h,sha256=g3Y1JtZa8tgQKltx6Ekdval5F35hc0GmG4qE2zBc5o4,3201 +tensorflow/include/tensorflow/core/util/activation_mode.h,sha256=E6g5aLkpDIOt-69n1BhvIoPFONxkkjpI1suOL8D5Q4U,1827 +tensorflow/include/tensorflow/core/util/autotune_maps/conv_autotune_maps.h,sha256=FXJgdfVmxFfxE_5ypEklXuf-PAU-_zgHvSxvV26l-lQ,2279 +tensorflow/include/tensorflow/core/util/autotune_maps/conv_parameters.h,sha256=XctGpoB-gIiCHba40mjKMhYNdCGhokQBHEEfoFNMxjg,5294 +tensorflow/include/tensorflow/core/util/autotune_maps/conv_parameters.pb.h,sha256=KNtPd35tVRTlksd-cixyalwDOxtfCwKiqQu3LbKJi7s,65520 +tensorflow/include/tensorflow/core/util/batch_util.h,sha256=_cMgo_EyvogmLcYQ51GdCguh4vZck68Jd19ILjVyux0,2971 +tensorflow/include/tensorflow/core/util/bcast.h,sha256=nnEfHb7lemXyr36tT3Zx8CwyrYTYGDUTtFWwSQOrEqs,16402 +tensorflow/include/tensorflow/core/util/command_line_flags.h,sha256=T3eKivm_df7ZOY7SX0xdl5jIx1QjftdY4GM8tdvnWSM,1081 +tensorflow/include/tensorflow/core/util/ctc/ctc_beam_entry.h,sha256=rtJSAjfN_vozPtKWDFBhZN2JtMOH09b7_SSW6F10dlg,5266 +tensorflow/include/tensorflow/core/util/ctc/ctc_beam_scorer.h,sha256=Vg0KiA_2Vn_1IEhDVnxCNA2N57XX5a2jHTQcPxbdMgI,3426 +tensorflow/include/tensorflow/core/util/ctc/ctc_beam_search.h,sha256=PHFYlhpHA3xuFFZjZGTUizJUnUrXX-2q4DBUyzIHwGA,16997 +tensorflow/include/tensorflow/core/util/ctc/ctc_decoder.h,sha256=RmdSPBPU1tM-MPrQynEKr4cPAq0fQekbVhySjjDDgYE,4494 +tensorflow/include/tensorflow/core/util/ctc/ctc_loss_calculator.h,sha256=uqoVTlpUO0EDMSRMFGbMqLLll7SF0D_w2cc15NoHeys,21260 +tensorflow/include/tensorflow/core/util/ctc/ctc_loss_util.h,sha256=WoOaC9l9a6iH2uM1uX79IPnNnAFv0Qpqbbrz3freBlY,1844 +tensorflow/include/tensorflow/core/util/cuda_sparse.h,sha256=saYyLDV27W7FVA__TpTVmhGRAgi5G5lyDY6QYnibbuc,29440 +tensorflow/include/tensorflow/core/util/debug_data_dumper.h,sha256=QrBHaj3VK8NhqVUOe-vPnyyJgG4XGv9z0uKzcgjwVkI,5610 +tensorflow/include/tensorflow/core/util/debug_events_writer.h,sha256=MZxT6ASZ10FTGIokavFRujNIvwokwjfQCELi3HNmkEk,11913 +tensorflow/include/tensorflow/core/util/determinism.h,sha256=aJgOFaykf07YPJ7ME9cV_Vf8ZBnNHMvFFlKvlDfuImI,999 +tensorflow/include/tensorflow/core/util/device_name_utils.h,sha256=mEtdcIXlo_868Ho_9Mc5Y5U_McrxN6gV1M7VaTlsuRU,1022 +tensorflow/include/tensorflow/core/util/dump_graph.h,sha256=j3AuLZ1CjR4FOq6DLWqPV-WP-pImMesYWO9cKK4dyRA,3472 +tensorflow/include/tensorflow/core/util/einsum_op_util.h,sha256=LoXFdtZLtNdOBHHuLv_-rhCiZxCYh9Tv447Kv5Y3lc4,3265 +tensorflow/include/tensorflow/core/util/env_var.h,sha256=cocFDYrPN-bKjZRzIDMQyMi5soxusA8xFF6rprB8Jrc,1179 +tensorflow/include/tensorflow/core/util/equal_graph_def.h,sha256=1iN4N_bAGdhB8Z9o16UYd3evfxjRe34xK71Hbft77F0,4764 +tensorflow/include/tensorflow/core/util/event.pb.h,sha256=14jSYhWZyqk8XCUlCyAI8f6rLksxGXmgZ2w_2YSgnE4,126242 +tensorflow/include/tensorflow/core/util/event.proto,sha256=Ed_VyEHvWxO6QnMZXcUqmVyQRjO-NZ5E8fR_a6k-li4,4171 +tensorflow/include/tensorflow/core/util/events_writer.h,sha256=WfoOotI5_aFN871wBUTvu5VZMRXwJi6p9zg0oN8-lpo,4129 +tensorflow/include/tensorflow/core/util/example_proto_fast_parsing.h,sha256=PPNYiFmAzO_BLp1P-n51Y1HpuA84UveiQdyHdFhX00Y,6929 +tensorflow/include/tensorflow/core/util/example_proto_helper.h,sha256=TNjvGkxHolZE3XA4nydwkWKp9dPdBAKl0uq1o5kqGLA,15818 +tensorflow/include/tensorflow/core/util/exec_on_stall.h,sha256=8tQYl6QUzD9dtPtPY9MgIblrsItB6hAcaB4aj3eYrkM,2691 +tensorflow/include/tensorflow/core/util/gpu_cuda_alias.h,sha256=MHE_x9aldPv1pc-8fJC_GofRVy5ZzIEAgcfVx_WTFNY,2452 +tensorflow/include/tensorflow/core/util/gpu_device_functions.h,sha256=pM4ATw8BQMHVB8OG5wXNZvc5fKAmZ6sKfpG6kFrWMWg,37410 +tensorflow/include/tensorflow/core/util/gpu_kernel_helper.h,sha256=QHWnwdaowW9HF3MdYwelHxQqg4sMBHRyHV51Xq8KfD4,18775 +tensorflow/include/tensorflow/core/util/gpu_launch_config.h,sha256=y4f00KQpomDQBX-vYAdqYX-SyUGC50MDxbeBed5T2Xo,16193 +tensorflow/include/tensorflow/core/util/gpu_solvers.h,sha256=aBI_sDRK-W40AiKZKAlQgeYixjf32YxTfje6eMjoIHs,30492 +tensorflow/include/tensorflow/core/util/guarded_philox_random.h,sha256=NVd7_HoG0o9ajVyRyisWfiX1Abn5r5r8wcrnUA-CWGI,2984 +tensorflow/include/tensorflow/core/util/image_resizer_state.h,sha256=Lav-faDZHgF3I0VczgC1_w8p2rSm4utiI9UoVQ7-Z8g,10544 +tensorflow/include/tensorflow/core/util/incremental_barrier.h,sha256=Zi32MMweJIri98XGk04ILlkzvA_EMXKztQUpwjhHvaI,2925 +tensorflow/include/tensorflow/core/util/managed_stack_trace.h,sha256=Izn4_K_RdXvYM7Nc_ibbDYE9DG-Q1eQPI0cSO3CwWoM,4545 +tensorflow/include/tensorflow/core/util/matmul_autotune.h,sha256=ij9WRINaX_wWRQCCq73WjEmcLG6DOVRs0Nbj041GwVc,997 +tensorflow/include/tensorflow/core/util/matmul_bcast.h,sha256=8C8U297qSfGWDC2pXyUXPzdcl4iNu_SbxpyGl7Mm_-A,4253 +tensorflow/include/tensorflow/core/util/memmapped_file_system.h,sha256=WaPzoq9sLUzdvAGA3yAq_0OnDAv7kqWXOlER2rnKED0,5546 +tensorflow/include/tensorflow/core/util/memmapped_file_system.pb.h,sha256=67mSwpkmVuiox1eKCfY-A1CTCIxp5wtrFuRVkOWnXCk,22099 +tensorflow/include/tensorflow/core/util/memmapped_file_system.proto,sha256=RXXec4ESOQpD5yMdOSBW6JenIjsju4Kd1-yvum59qdE,1059 +tensorflow/include/tensorflow/core/util/memmapped_file_system_writer.h,sha256=TA-5PrKKJIbT-lEJJk34RapVgoWyWCf7CtCUjIEbUNA,2152 +tensorflow/include/tensorflow/core/util/mirror_pad_mode.h,sha256=wt8IyY4kgWDPn78HNZpRhtFK5xw1a11gsF5iCphw7D4,1877 +tensorflow/include/tensorflow/core/util/mkl_heuristics.h,sha256=VwCQ70H6EuJGv7Hu64JVrJy9V5Rqe_Ybw-5jLVnN3XM,6478 +tensorflow/include/tensorflow/core/util/mkl_util.h,sha256=pBya5EiNuQXPe6pEJDFC8CNQcvQcB4vxgw828KbC3nw,87328 +tensorflow/include/tensorflow/core/util/onednn_env_vars.h,sha256=_3eiUFuP5GoLKAtNnUVWTdtiDoCZWMSOgQ2UeveU8XA,1044 +tensorflow/include/tensorflow/core/util/overflow.h,sha256=l7KbesrzamVnfZ0IMw39n840PdkxMAstE4MEBYYL2jw,2549 +tensorflow/include/tensorflow/core/util/padding.h,sha256=C0ABAYkwgb2Y2DlrJw4pR-haWhHcyKMd0x0yxd9dsg4,2600 +tensorflow/include/tensorflow/core/util/permutation_input_iterator.h,sha256=OjMoBo2jtN4-W5WVIzHtU2L8BoWgdZslkt4nDIraqe4,4190 +tensorflow/include/tensorflow/core/util/permutation_output_iterator.h,sha256=uDGMEDvvyeHpJEk5BKH1gwU1zLHosQyhyoGSjFt4GuQ,4086 +tensorflow/include/tensorflow/core/util/port.h,sha256=urbZFU96FegnInNydmvU7X8Zgxot0ofjNCJGqKIDD4U,1623 +tensorflow/include/tensorflow/core/util/presized_cuckoo_map.h,sha256=LCLQRT6jMnMmO-M_e-rTE9qe6sEFPExV912JZmWSu30,13199 +tensorflow/include/tensorflow/core/util/proto/decode.h,sha256=tXvapbLrFSYEktPKoI8LIN606Q57EnACcHInOmqMYbg,27559 +tensorflow/include/tensorflow/core/util/proto/descriptor_pool_registry.h,sha256=3SUQIr5jrarQ8gelZxpsJEwMbjr6wmnsGLpU5lM5ZGs,2569 +tensorflow/include/tensorflow/core/util/proto/descriptors.h,sha256=O_38zPltt8ZhxWXZGNvUgnhpV9arVyipxfwmiZlC6Ho,2098 +tensorflow/include/tensorflow/core/util/proto/proto_utils.h,sha256=pHOZoALT4bmJT6cQiGlid2XYU8n5A2R6SdRAGXXmFWQ,2797 +tensorflow/include/tensorflow/core/util/quantization/uniform_quant_ops_attr.pb.h,sha256=_XWG6TsdP5FaxL7EbwXZ-X6nQ6RrtKK3TnZrDriGrMk,29990 +tensorflow/include/tensorflow/core/util/quantization/uniform_quant_ops_attr.proto,sha256=423_2myr3dSTMOPRT-N44AE739bqjzvfyQo1DlUbNdQ,2161 +tensorflow/include/tensorflow/core/util/quantization/uniform_quant_ops_params.h,sha256=rXhRTcGlxaRvFfmqgRQ6671RMluYOHnOOcOqYrx0KLU,5142 +tensorflow/include/tensorflow/core/util/ragged_to_dense_util.h,sha256=-t7tPgGxkKCXC8x6feSRDQuqxuFgkJZDOtKaM5YPfpo,2537 +tensorflow/include/tensorflow/core/util/ragged_to_dense_util_common.h,sha256=oAPhZFabyB1b75aQYvYd27b7SzHW---yK1wlmb5AH6I,2842 +tensorflow/include/tensorflow/core/util/reffed_status_callback.h,sha256=6zvVjIKwjeepjR3HFBEzlZfAJRCbEtIrm981JdryhXk,1998 +tensorflow/include/tensorflow/core/util/saved_tensor_slice.pb.h,sha256=8Dm40UH276E4k4amJqrlqo63xPyAKItTkskASKGOF7w,58711 +tensorflow/include/tensorflow/core/util/saved_tensor_slice.proto,sha256=p3rHq30j-FbKOUElH8k3SKVtUpxPxHyn0mB9o8Xd6SM,3112 +tensorflow/include/tensorflow/core/util/saved_tensor_slice_util.h,sha256=-6P8JYBN4inwPNe0wuJdmTxCGzzdKygyiM_XT_VQEGo,9342 +tensorflow/include/tensorflow/core/util/sparse/dim_comparator.h,sha256=CKqK4lWjscpSv7urzZenFYFmboc9KX-i-BBNeT5l20U,4176 +tensorflow/include/tensorflow/core/util/sparse/group_iterator.h,sha256=M6AuqYIpb0QtuSXx51KKGqojrjnw3j4erp7498515fM,4827 +tensorflow/include/tensorflow/core/util/sparse/sparse_tensor.h,sha256=4okwsF0VOOgoCdo_zXhX2oiKtK3tsp8SuV4ptkWBLQo,25148 +tensorflow/include/tensorflow/core/util/stat_summarizer.h,sha256=rzucFSp5xQOxCmJYN_rH9wAP4Nzc0qXSDLeq7j1BPZk,3989 +tensorflow/include/tensorflow/core/util/stat_summarizer_options.h,sha256=vcAx4cj1Gbjz96r1c1GpKUdwQxYaPDb2Bp-rKEjoVkU,974 +tensorflow/include/tensorflow/core/util/stats_calculator.h,sha256=fUevnmfwXEu6HJCGV6Lu6NOpkz2n_DgIp7mWv1zo3MI,1165 +tensorflow/include/tensorflow/core/util/stream_executor_util.h,sha256=3ltiomDsqJje2aJqLdAiiQ1LLLJNhOWAO3ykkIu_P1I,1555 +tensorflow/include/tensorflow/core/util/strided_slice_op.h,sha256=-hPqJ8L_IpV4Vze7cXTMVITsOraNzlQgSXQVY6BjMFE,6928 +tensorflow/include/tensorflow/core/util/tensor_bundle/byte_swap_array.h,sha256=X7PQN0R_RZyhOM1t29s-BphVu19LFjD05-T6ubu5fZM,1149 +tensorflow/include/tensorflow/core/util/tensor_bundle/byte_swap_tensor.h,sha256=x12QozuAfnishq2E5NnDVYzZ1aS_-TZYiL3rPecUcWE,2047 +tensorflow/include/tensorflow/core/util/tensor_bundle/naming.h,sha256=NjJWRR2OCDy_zBvmUr4xWVn0cHzjEIwt-gZR-Afh-h4,1833 +tensorflow/include/tensorflow/core/util/tensor_bundle/tensor_bundle.h,sha256=pJlw43XlDnitfLUqdXfZfyjv67KdBULRdomgIa1H35w,15385 +tensorflow/include/tensorflow/core/util/tensor_format.h,sha256=ERtjmWLnWsEr6Qu5yvpFlogipMHdJXz5I4Y3EGGl_Ug,27096 +tensorflow/include/tensorflow/core/util/tensor_ops_util.h,sha256=3YYCxJ5pNAmfvAZp-wtDCZn5pssPuq8w8qZi5DvZ1xk,4388 +tensorflow/include/tensorflow/core/util/tensor_slice_reader.h,sha256=9GKfCzqjW-gvX0M7oSrpWzHQAsJcgEjTaTDwSvrw60g,8160 +tensorflow/include/tensorflow/core/util/tensor_slice_reader_cache.h,sha256=aG1ZK-MgCh2GRjMUeNX4t9idvWEQWl5-Gb7OYAOKak8,2870 +tensorflow/include/tensorflow/core/util/tensor_slice_set.h,sha256=95112jnHi0HqsKepVnI1FQtEbZFTYm2AMfymxfZPKco,3404 +tensorflow/include/tensorflow/core/util/tensor_slice_util.h,sha256=2jhbUyPh46lrKK3DQKBmAtAHx-kfrPJrh9r6eGgYft4,7930 +tensorflow/include/tensorflow/core/util/tensor_slice_writer.h,sha256=5h18dDIZJEsPTCuvc72q7zloVyN-5WvM1KX_jDlPj-4,8026 +tensorflow/include/tensorflow/core/util/test_log.pb.h,sha256=0ZP5f7IvhlY9Ih4kItKG-qQDRt_1Ukli52xRFi82r64,2622 +tensorflow/include/tensorflow/core/util/test_log.proto,sha256=DcXMk9GeTmhj9X2IzhdUgiShIqFU9BxFKMHkyVDY7SI,170 +tensorflow/include/tensorflow/core/util/transform_output_iterator.h,sha256=mOlbCgnpaXrOywGx6kVD01SMFfs61l9gcUwSTIbaU0Y,4463 +tensorflow/include/tensorflow/core/util/use_cudnn.h,sha256=RMpK8DVIVq85pRN7ri8DMxCB8eOGf6PddLcCqIvBYVg,1287 +tensorflow/include/tensorflow/core/util/util.h,sha256=bQqhB5iPQSq5KltsJ8qNCzKtVvxtK0HNIuzglzs1EXo,2310 +tensorflow/include/tensorflow/core/util/work_sharder.h,sha256=LQGzzv5c458ZedDxWgCoDxN7A5uL_rsOFG_rf245oRk,4186 +tensorflow/include/tensorflow/core/util/xla_config_registry.h,sha256=NY6OYhe4V8kM6Q33ClfWtCFM1Wr3cW6n-LExfkcu8hw,2321 +tensorflow/include/tensorflow/core/util/zen_util.h,sha256=22rdtuDRa6MS6tS8A-HQDtQfv94eK0MeGnir9K2qcZ4,1576 +tensorflow/include/tensorflow/include/external/ml_dtypes/_virtual_includes/float8/ml_dtypes/include/float8.h,sha256=0nmPrU5kN1tWax3x17xEAxPksQJMoI8Szq0-qktz_3I,51353 +tensorflow/include/tensorflow/include/external/ml_dtypes/_virtual_includes/int4/ml_dtypes/include/int4.h,sha256=s6mXDDxrFpxBrC_UN19mjT_RtJLUi5EtiUFfoVIqj1A,8784 +tensorflow/include/tensorflow/include/external/ml_dtypes/include/float8.h,sha256=0nmPrU5kN1tWax3x17xEAxPksQJMoI8Szq0-qktz_3I,51353 +tensorflow/include/tensorflow/include/external/ml_dtypes/include/int4.h,sha256=s6mXDDxrFpxBrC_UN19mjT_RtJLUi5EtiUFfoVIqj1A,8784 +tensorflow/include/tensorflow/lite/kernels/shim/op_kernel.h,sha256=EW0KrswguogGTNkLvK1WDAYoarWfKzVedPuF_g3H0nc,9777 +tensorflow/include/tensorflow/lite/kernels/shim/shape.h,sha256=tlDl9_SQ2B8ChSBOwMg_RO1aIhpHwdXDLswoLKp-kTY,3247 +tensorflow/include/tensorflow/lite/kernels/shim/status_macros.h,sha256=GIosvWXsVb4OaDDftsluvxN7b_2U1i-TGCL_KBoIiS8,3076 +tensorflow/include/tensorflow/lite/kernels/shim/tensor_view.h,sha256=yoramIXYPMH6xcwC8BoHmHrdho0cvbdtGxGHu4OuDS0,8467 +tensorflow/include/tensorflow/lite/kernels/shim/tf_op_shim.h,sha256=BvmszXu61WjRz4x7D0ON2ma9O_i-o4ZYEMfOSU6q4dw,6030 +tensorflow/include/tensorflow/lite/kernels/shim/tf_tensor_view.h,sha256=n1vkfRGFcaywpxflFGpx4A09S--GYR9JlPPJy6IrBlw,3401 +tensorflow/include/tensorflow/python/client/session_ref.h,sha256=USbYdDw4abSI1lpWpKaaoFH5k0BQIK3ogr85VyoGBVI,3497 +tensorflow/include/tensorflow/python/client/tf_session_helper.h,sha256=VKoytQlmRLcUgnyl5o0L31o_WnaRAALLmmlDfnexkmY,12343 +tensorflow/include/tensorflow/python/eager/pywrap_gradient_exclusions.h,sha256=1HY0DG0MwH54dLWrjbcIzfDgArxqYuEZatXyyuII2ak,1971 +tensorflow/include/tensorflow/python/eager/pywrap_tensor.h,sha256=cB7qkcaKSd95v62QGDhjKiIPt8MwR2JZPGNlPdSmEwk,1958 +tensorflow/include/tensorflow/python/eager/pywrap_tensor_conversion.h,sha256=9jLuGjLPnRKsdnzC9V_rpGGAPMMOhmoqt8na51tOYZ4,3645 +tensorflow/include/tensorflow/python/eager/pywrap_tfe.h,sha256=J3daAzjQqMAZ2KX-XUOUfo1OxVBvjVIFE9QSL8jrxNA,21243 +tensorflow/include/tensorflow/python/framework/kythe_metadata.pb.h,sha256=rIJS4nR5LBA_KK-oPcht8DGD07HlWv_7qNmoWVVzLRE,59143 +tensorflow/include/tensorflow/python/framework/op_reg_offset.pb.h,sha256=5soSOV-OvrFxbv1-OFtRcmIy_5n-CIcV62cCpCu1DRo,21496 +tensorflow/include/tensorflow/python/framework/python_op_gen.h,sha256=RQJvmDu1QVMcjCcklpLvAfhSX4-37yOdZ7v4eE9-b70,3138 +tensorflow/include/tensorflow/python/framework/python_op_gen_annotator.h,sha256=N0cUU07QpB1sBBPKS72PfF25PRub7xRzUdtQdelS2Sc,2477 +tensorflow/include/tensorflow/python/framework/test_ops.h,sha256=XmsMm48x8Ojs3VghMWb6hfLdOX22e-pvDrw4g05yOmk,1027 +tensorflow/include/tensorflow/python/grappler/model_analyzer.h,sha256=JDrqrO5vpw6bkBB-F9RruVaYwIchUOuVtm6ZNOyKWJ4,1600 +tensorflow/include/tensorflow/python/lib/core/ndarray_tensor.h,sha256=JrfTXFKS5nkqTG9q5Tj2LYfGP8-BMhI972_mTB3G1Oo,2259 +tensorflow/include/tensorflow/python/lib/core/ndarray_tensor_bridge.h,sha256=XNNmDc8dobbhUuH5LdWVs8ArNwGG22apXh4LN1nxJMM,2143 +tensorflow/include/tensorflow/python/lib/core/py_exception_registry.h,sha256=PnFBs9L7BuBe6CEcQCgxBvNnXsziNLdpm9QZ_ej1H6M,2668 +tensorflow/include/tensorflow/python/lib/core/py_func.h,sha256=CVYPrGeDY_dvUjFe9wIDkt-0tHWPEk8g5KM9Ft82TBY,1938 +tensorflow/include/tensorflow/python/lib/core/py_seq_tensor.h,sha256=6izVYjZ05VK0dX_9NBLk60WdwDvkOCaN_zHfdDv99ws,1674 +tensorflow/include/tensorflow/python/lib/core/py_util.h,sha256=Gl6hkGCV5AVuK8ZiDeiGcULYfbUgABS1xC-XO8CM0dc,1268 +tensorflow/include/tensorflow/python/lib/core/pybind11_absl.h,sha256=_5zmKHsUrd_7Y87mDBRyEXqOTnrnVW-xxRPKaunOe5U,1461 +tensorflow/include/tensorflow/python/lib/core/pybind11_lib.h,sha256=lHYvnL3dDuXS5KmFwHWdHV21yuXwPwVM-J_DCEAitDM,2454 +tensorflow/include/tensorflow/python/lib/core/pybind11_proto.h,sha256=DZxrdSi1xG5bGUtmYR68RMweWvWjchGQBXJLO7ANP14,1787 +tensorflow/include/tensorflow/python/lib/core/pybind11_status.h,sha256=LyJ9vWmO5QLiC4hjePYUXePkAlxHc_M97GfDkYyJwgU,7088 +tensorflow/include/tensorflow/python/lib/core/safe_pyobject_ptr.h,sha256=ed2dURcumu8Bdq2ZWqrmnp9zxfsD913FHPOY3vjG0Lc,1305 +tensorflow/include/tensorflow/python/util/kernel_registry.h,sha256=2ljNcnqjGqS9FDld375OKxRXa29uUbyq7D93LzNV4Gs,1341 +tensorflow/include/tensorflow/python/util/stack_trace.h,sha256=LhvN_FCm4Q4mjiPs4Xne0W9XAmgSJmnkn2fuTrki54I,3124 +tensorflow/include/tensorflow/python/util/util.h,sha256=rIOpSzzYMI8SLGO-pA4mqNFLYw6mNEhPp2sJQXVVSDQ,7489 +tensorflow/include/tensorflow/tsl/c/tsl_status.h,sha256=9NGwXzGl5iNo0-Gbabk9WJfSNn4Vva3oeq91hIDwCPc,3411 +tensorflow/include/tensorflow/tsl/c/tsl_status_helper.h,sha256=bQT_pkgcQCdzUAFsvoYT0iAvBb7Khng6Y_rMEfe0Vxc,1045 +tensorflow/include/tensorflow/tsl/c/tsl_status_internal.h,sha256=36Mw0amVD4kU3H2MxmiEFO0LCZtCbDbGLgLbpCvQs0U,1009 +tensorflow/include/tensorflow/tsl/distributed_runtime/call_options.h,sha256=V7JwtBWQb_y8yeNjMzN6bNRTtDJEzW5aWmBXz28V9Aw,2876 +tensorflow/include/tensorflow/tsl/distributed_runtime/coordination/coordination_client.h,sha256=tT-pN5ACabMqXe6MoOIzwVRuunM9XePoklrrhJ8XbLs,6348 +tensorflow/include/tensorflow/tsl/distributed_runtime/coordination/coordination_service.h,sha256=p4uVH-xoS6teyfGvN-WIV3KFSqy1o7-xG-GKZAIEHzM,11732 +tensorflow/include/tensorflow/tsl/distributed_runtime/coordination/coordination_service_agent.h,sha256=tqtSzQHAbOeQuGUhDaorahwhak23WQOMM5_922S30Bc,13319 +tensorflow/include/tensorflow/tsl/distributed_runtime/coordination/coordination_service_error_util.h,sha256=j6bPunFX7sVrDaCeeYoeS1PVTIR-ZFcPcG2nlmi9SPM,2400 +tensorflow/include/tensorflow/tsl/distributed_runtime/coordination/coordination_service_rpc_handler.h,sha256=gIzFlKrudp2eAel4ny32gnfZythag6xBJnsIIBmikwM,4474 +tensorflow/include/tensorflow/tsl/distributed_runtime/preemption/preemption_notifier.h,sha256=7lQCLIAbB6Fc86ELUl_LeAu94MCvxhG08ayDZdJyotA,6332 +tensorflow/include/tensorflow/tsl/distributed_runtime/rpc/async_service_interface.h,sha256=sByCUwqe_7EBdNW5zeT3r1tS1ypY3hA3me0KQ0LjxMA,1545 +tensorflow/include/tensorflow/tsl/distributed_runtime/rpc/coordination/grpc_coordination_client.h,sha256=uQlxbTBGdP9UsxfVzIOsPEEIbo2-b3ntUiUKcPbUSlo,1321 +tensorflow/include/tensorflow/tsl/distributed_runtime/rpc/coordination/grpc_coordination_service_impl.h,sha256=g1M87sRRzm5uxhaUikArwE-mwJl_hdOHbmvs-BjIgJk,5357 +tensorflow/include/tensorflow/tsl/distributed_runtime/rpc/grpc_call.h,sha256=0XNkmKSMIb_nGZCjcrJOnNBIv5o1xg2rqWqU01szrOA,21318 +tensorflow/include/tensorflow/tsl/distributed_runtime/rpc/grpc_channel.h,sha256=04yC9SB7j1Imj0sReLGrwcB_doBrVPyAgJazTm3iX3E,3516 +tensorflow/include/tensorflow/tsl/distributed_runtime/rpc/grpc_channel_common.h,sha256=Zc8AJKEQfQVEOQNy8gUUtRfMqiKO3AXSu_ZMsdAujVQ,3869 +tensorflow/include/tensorflow/tsl/distributed_runtime/rpc/grpc_client_cq_tag.h,sha256=g5U0qyw47fkhHN3R1phbB-Thy_PPJ9D_D3_OBeY1J8k,1436 +tensorflow/include/tensorflow/tsl/distributed_runtime/rpc/grpc_state.h,sha256=xdOBRQ9myygBzfWtfsbkTbpO99CuL8ikYBgIQcw-zdU,9717 +tensorflow/include/tensorflow/tsl/distributed_runtime/rpc/grpc_util.h,sha256=9gkQMbs-zdz4yMXkxrTASH2stq7XfImtKoiimwvS5H8,5492 +tensorflow/include/tensorflow/tsl/framework/allocator.h,sha256=eUJac-2HCOqfFSDgwvzcgg6AYpEAW_WHvgAyO7Oq9D8,16863 +tensorflow/include/tensorflow/tsl/framework/allocator_registry.h,sha256=rf6J16I16pu8wjNao7VN_XUy4Ac1lVhNKV1HMpIhlXU,5604 +tensorflow/include/tensorflow/tsl/framework/allocator_retry.h,sha256=9pTmi-Sx3hy7ttBDpyJpzpSerXvYqr-7zyUZWTmjcYI,2125 +tensorflow/include/tensorflow/tsl/framework/bfc_allocator.h,sha256=-Vvlb0AciSK2iQyZ6Hy0Fhi6sxAszwZ7shYi3oZKJ_8,23379 +tensorflow/include/tensorflow/tsl/framework/cancellation.h,sha256=Da6iVTrMjR4sPmt5iHPm9tV8G37Zom1sl1PiBFjSqIw,8800 +tensorflow/include/tensorflow/tsl/framework/contraction/eigen_contraction_kernel.h,sha256=GKpkHjec5MA0U5I5sMfvqZipfjVVFcAJ_EQgEDxRYJw,53345 +tensorflow/include/tensorflow/tsl/framework/convolution/eigen_convolution_helpers.h,sha256=2IaIV6vz1IFnMsLiVuXWF8QX79bvslqaVKgL_cZP6YM,4001 +tensorflow/include/tensorflow/tsl/framework/convolution/eigen_spatial_convolutions-inl.h,sha256=fcbH6rq9TnNAg_9sSqLJJmlGWapK9fnj_eea601rOk8,76113 +tensorflow/include/tensorflow/tsl/framework/convolution/eigen_spatial_convolutions.h,sha256=nPS5oUEO_nVjupktLlfMdbi_NfdWu3tV811L1XYTftM,18459 +tensorflow/include/tensorflow/tsl/framework/device_id.h,sha256=rWpzuRFbmjqNGhwhA6AXW1t-tAKAjNlZW24OJkQxiBg,4139 +tensorflow/include/tensorflow/tsl/framework/device_id_manager.h,sha256=klTN2pnJvWOvLluygFX_aJvm8vDFuwxl2LVbSWV6rJo,1976 +tensorflow/include/tensorflow/tsl/framework/device_id_utils.h,sha256=zfaEOEHLkJK64iwiS1J77WLMmlp2DUgVVYAC5XB31l4,2993 +tensorflow/include/tensorflow/tsl/framework/device_type.h,sha256=mGHCEZB5f7QMhSTS34XEbhcJkXhAQzysTLaNQZi1Gtk,1632 +tensorflow/include/tensorflow/tsl/framework/fixedpoint/FixedPoint.h,sha256=pLTBPq3Nj-T9kafqS3JFOT0m2-AM24X-bwsYLQcf6Nc,2267 +tensorflow/include/tensorflow/tsl/framework/fixedpoint/MatMatProduct.h,sha256=XtM02HlVDkyTwuVyI0LsBgrqo-XYPWIp7HKbzW4Uing,12242 +tensorflow/include/tensorflow/tsl/framework/fixedpoint/MatMatProductAVX2.h,sha256=cgLpgTAygIyAAGxiUmiGC3mIZ1nc0w-XYf3c4OJ14VI,97119 +tensorflow/include/tensorflow/tsl/framework/fixedpoint/MatMatProductNEON.h,sha256=sUTcKC5NYNwCP5Rbo0e-J2nc8x2-Md-cVlNNjGSclYs,10843 +tensorflow/include/tensorflow/tsl/framework/fixedpoint/MatVecProduct.h,sha256=OvL8UkuVovzzUgSCPYqzQcub1VO-HTeccCjfrDbg8do,6349 +tensorflow/include/tensorflow/tsl/framework/fixedpoint/PacketMathAVX.h,sha256=nVV3yvskf7VPcvQfQVf6mseUeQ6LgYwBQH2d8DYHu7A,5116 +tensorflow/include/tensorflow/tsl/framework/fixedpoint/PacketMathAVX2.h,sha256=tlnMBg4gckv6hnQdkjPeQIPbkGJZTIDTwRsVj0DT-Qg,18503 +tensorflow/include/tensorflow/tsl/framework/fixedpoint/PacketMathAVX512.h,sha256=ZUdpw38tncVRIj3nxB1QQAEr5_KtDoP1R4Dqu9QPHLw,18943 +tensorflow/include/tensorflow/tsl/framework/fixedpoint/TypeCastingAVX2.h,sha256=r6CA8kJhVzFURKN0mFJx6Du-92nsOkny9i5W12IOHSE,4272 +tensorflow/include/tensorflow/tsl/framework/fixedpoint/TypeCastingAVX512.h,sha256=sLdyyG4y3GSK0Gpxg8wpraWndsvye7aJymrKVw-3AWQ,7930 +tensorflow/include/tensorflow/tsl/framework/fixedpoint_types.h,sha256=oWxzXT90zYmtfwE0u9gW4-DFjohLkYXm3oczD1idERU,12331 +tensorflow/include/tensorflow/tsl/framework/metrics.h,sha256=e9kFGEmWDDCKecaLPJ5JVF2YCD8-kgo9_nP9mXKd-6Y,1047 +tensorflow/include/tensorflow/tsl/framework/numeric_types.h,sha256=tBphRz-3iN-6jpDxjW85FWTrNihEkIQRb-pZLTj7P94,2245 +tensorflow/include/tensorflow/tsl/framework/shared_counter.h,sha256=I-kvNi2vZf4ziKJXk8NM3kbAkOay7KjoePX5wvAdZPo,1152 +tensorflow/include/tensorflow/tsl/framework/tracking_allocator.h,sha256=HeU5hBz1tUkylsuOLlwBWfn3rblKQIR8JPcQhI1efm0,5750 +tensorflow/include/tensorflow/tsl/framework/type_traits.h,sha256=R57tJpNifqUbtNoVcy-6TeNuopJYNl6glvidq7zQ4xk,3697 +tensorflow/include/tensorflow/tsl/lib/core/bitmap.h,sha256=7BS6ASaA3QoW-WiDYwrriqHJu7COPjGmUHeUitSH4Wc,2910 +tensorflow/include/tensorflow/tsl/lib/core/bits.h,sha256=oM3t37JbzG9Hl4jWPE1GciYk9WPQyvejjpGxZ724NBw,3121 +tensorflow/include/tensorflow/tsl/lib/core/status_test_util.h,sha256=W2YBWCfWirZx5_wu8MypEdlOVZKo0Y1HrOvVcdCqHe0,1512 +tensorflow/include/tensorflow/tsl/lib/gtl/compactptrset.h,sha256=KAW3WGpcpmSCRpdrzYpFiqXPPERCaRSF1TR3_4XIpZ0,5388 +tensorflow/include/tensorflow/tsl/lib/gtl/flatmap.h,sha256=DflahgOVx_DtmpAiHA3sd2qEBeMcg3nJHw5cIPccY2Q,11963 +tensorflow/include/tensorflow/tsl/lib/gtl/flatrep.h,sha256=o2cYpb_k50bv0aA-nd1CvHRq6NCctqitgX8yV4pHaKE,11030 +tensorflow/include/tensorflow/tsl/lib/gtl/flatset.h,sha256=DBYD7iEgw9EIluzcAhVvtt_2BPFFlA9uDrGx74U8gu0,8811 +tensorflow/include/tensorflow/tsl/lib/gtl/inlined_vector.h,sha256=l2nGCm7xE5Uebu1Buypj5V6d0STf4DE9qrKoX6mXgy0,1180 +tensorflow/include/tensorflow/tsl/lib/gtl/int_type.h,sha256=cCu2d7EWqhVPCoG7OJ45O83kh4gjcRfM57Ek4C5xZ78,15707 +tensorflow/include/tensorflow/tsl/lib/gtl/iterator_range.h,sha256=Ic5N7M9xoZ3e06GjvdqWS-w_2Jbe3Z-q1gAt268m19A,2358 +tensorflow/include/tensorflow/tsl/lib/gtl/map_util.h,sha256=-F65FC_4PBBSERkB9noPwh7vk2QjEHdhlctt9ufPmew,7889 +tensorflow/include/tensorflow/tsl/lib/gtl/subtle/map_traits.h,sha256=niZRWu07vWr4qfFBPZuqhP_f9haXGo2wjObhkMl-eUI,2596 +tensorflow/include/tensorflow/tsl/lib/hash/crc32c.h,sha256=H2DrQK2IrjyKgxj17F5SpdPiG2SG4M9DvA1RnScZxYo,2183 +tensorflow/include/tensorflow/tsl/lib/histogram/histogram.h,sha256=8CpvxHnGXYF7vJBhrOc9vxaYfohy1jNIuFi10NYAdIE,4723 +tensorflow/include/tensorflow/tsl/lib/io/block.h,sha256=PRbg3aw1Wh71mbcMBjgVMWzx0zHLlq6L-r65GpzK2Eg,1465 +tensorflow/include/tensorflow/tsl/lib/io/block_builder.h,sha256=qbs-_syJFXXazQEVwbiJLPiL1YNFdwJTpy-3z0A3ZwE,2269 +tensorflow/include/tensorflow/tsl/lib/io/buffered_file.h,sha256=RzE5F2L51AxcQfvu7ojCXiMict0UdZI9f6y6TnZkqKs,3550 +tensorflow/include/tensorflow/tsl/lib/io/buffered_inputstream.h,sha256=hBWYK31Hy4LDyuxfbbQ8Eac3v-OYjWckYUOdbfabLls,4939 +tensorflow/include/tensorflow/tsl/lib/io/cache.h,sha256=ewj9-CkENTUYeXKLUBZlx3QZ5yJi6NUdH50hJf6wqGs,4578 +tensorflow/include/tensorflow/tsl/lib/io/compression.h,sha256=65q_1dHgAJbjVw1HxZ9PwbUMlViUIuE0momPT_owUl4,1044 +tensorflow/include/tensorflow/tsl/lib/io/format.h,sha256=U6ftHa-Y5GPCjg0FNIKjsT-9qDM_T-mVOwkEmSvFbCo,3513 +tensorflow/include/tensorflow/tsl/lib/io/inputbuffer.h,sha256=jOjndILdkWT9AZlrVFMagXp59rBSOaYoA-JAzA-ccqo,5528 +tensorflow/include/tensorflow/tsl/lib/io/inputstream_interface.h,sha256=8ASlaRLg2NEfNmN5sOBWb5el5UAkHr4uXeMcE9pkuEI,2463 +tensorflow/include/tensorflow/tsl/lib/io/iterator.h,sha256=XYg3OtrqGlxfD2EA9dVpbeBQk7oE8A6Z1V0MEmYlKAI,3644 +tensorflow/include/tensorflow/tsl/lib/io/proto_encode_helper.h,sha256=xpiIs8tSPmrLcAcyqiVLg7jj_L3IjmCRpFx1Scm9x6s,3153 +tensorflow/include/tensorflow/tsl/lib/io/random_inputstream.h,sha256=fEWy3OJwLBs7Gnis6tr5PTqPilatEUOZm9j6tHEfc6E,2001 +tensorflow/include/tensorflow/tsl/lib/io/record_reader.h,sha256=0kvaxYVCQj7cMsQrlYu6YdM4rKe6xhdSuc3fnCdMYLM,6265 +tensorflow/include/tensorflow/tsl/lib/io/record_writer.h,sha256=4f9mqtQrBFpfECcJ1MFJRGBpZ-cK4ChJaw08SXLD67s,5024 +tensorflow/include/tensorflow/tsl/lib/io/snappy/snappy_compression_options.h,sha256=Riu8tRWkddQ9zqfghPyaQkx9uhF9snL-VQXvP0lxMEg,1278 +tensorflow/include/tensorflow/tsl/lib/io/snappy/snappy_inputbuffer.h,sha256=lk_llFrsFf5-MaRB2-oE5c0gy97Ix2TWl_g1JjkR2TA,5131 +tensorflow/include/tensorflow/tsl/lib/io/snappy/snappy_inputstream.h,sha256=JLnY7yw0DnehdrEIFXMs0yeURZOHgUZG24lTcslVDzw,3169 +tensorflow/include/tensorflow/tsl/lib/io/snappy/snappy_outputbuffer.h,sha256=eFjNmmrBFNlGRUi6w468mOKZGw_PRuCu5mPkioUXdVI,5904 +tensorflow/include/tensorflow/tsl/lib/io/table.h,sha256=I0jb0UgCpeX_vHWLfPn4MvXHgKQpGEQUXBaLSZUdFZ0,3154 +tensorflow/include/tensorflow/tsl/lib/io/table_builder.h,sha256=VYB3KcodIqKCq2TxwNDNYA-HLenTPn-brDx_3_288yY,3573 +tensorflow/include/tensorflow/tsl/lib/io/table_options.h,sha256=-tGltp6nuYbNnuifRLr8GB_AXKrTIXzIM403NXe-7UU,2922 +tensorflow/include/tensorflow/tsl/lib/io/two_level_iterator.h,sha256=VVMGUVhSQcTqKAeyEq0cwsvymn5HRBE0bqhZy3d6qOU,1611 +tensorflow/include/tensorflow/tsl/lib/io/zlib_compression_options.h,sha256=kOZsiFAkPlTovnPlzMx62igJnLQLkf81rHSYv2_0Wdg,6053 +tensorflow/include/tensorflow/tsl/lib/io/zlib_inputstream.h,sha256=akNNAwvYBsgPmc9OW0sGV9Wz_i8XWHDeTBo4mC6Lm2I,5342 +tensorflow/include/tensorflow/tsl/lib/io/zlib_outputbuffer.h,sha256=QKP_RBWqCgZ9uroyqVsYkhvBTkHZqIqvzygUJZAf5tY,5680 +tensorflow/include/tensorflow/tsl/lib/math/math_util.h,sha256=p0WkyVsoIA3hk9byzky5RnIEiNFXQ5_Ryii9JHp2N9w,6575 +tensorflow/include/tensorflow/tsl/lib/monitoring/cell_reader.h,sha256=cNngI2guOnD58MsGR4EI-jOKUzoFCFM1bIG5u7IqnEc,6919 +tensorflow/include/tensorflow/tsl/lib/monitoring/collected_metrics.h,sha256=rQVr-kolLLztwyrboael2RzJAjSgQP78Gbd1QGP8H3w,6069 +tensorflow/include/tensorflow/tsl/lib/monitoring/collection_registry.h,sha256=ITU4fLUaUxk3MIdt6uKjhg464z0bwfKUzoRdLqCsiy0,16847 +tensorflow/include/tensorflow/tsl/lib/monitoring/counter.h,sha256=iEV-fwZX99FDI97HOI79MRsMsW240e9OyvNooivgHbo,7388 +tensorflow/include/tensorflow/tsl/lib/monitoring/gauge.h,sha256=M22uEKXPPx60aunfBch97pqrGYdgdPTh5r18SCkufws,10070 +tensorflow/include/tensorflow/tsl/lib/monitoring/metric_def.h,sha256=kqMP5PqrnpPsDzElMDM1vjDGN8XTQQD2p9GRnwu5FhE,5388 +tensorflow/include/tensorflow/tsl/lib/monitoring/percentile_sampler.h,sha256=TG7grdkl5vECx5LufIoqHBJqQOM8iJjm8aszSQ8z0GM,9855 +tensorflow/include/tensorflow/tsl/lib/monitoring/sampler.h,sha256=2MzQ_Iv6Wxu1mx_TjnD_Sps6Tdp4HXcnJ3pjUwS4T1o,10640 +tensorflow/include/tensorflow/tsl/lib/monitoring/test_utils.h,sha256=-d3KlUq9NHolHV7Wx3M70SMDbEUKJppdH3uN6oKJPUI,3188 +tensorflow/include/tensorflow/tsl/lib/monitoring/timed.h,sha256=0CEtIue8D4R6LjCLU3gTg96dlsAbqoiRCu2XSnFEFho,1494 +tensorflow/include/tensorflow/tsl/lib/monitoring/types.h,sha256=hqzPWdRQnVdapWpQQPh5M_SmPjlvp-ygB8iaWMUIxso,1496 +tensorflow/include/tensorflow/tsl/lib/random/distribution_sampler.h,sha256=eQUyX4p2ORpQPir5xiGPnImcExx0y3Jbi4RmYJgqFjQ,2907 +tensorflow/include/tensorflow/tsl/lib/random/exact_uniform_int.h,sha256=aRnvVno0MUYKGR8TiyJA9ndJd2LGKTLPuw4Pyyi-AhI,2930 +tensorflow/include/tensorflow/tsl/lib/random/philox_random.h,sha256=VZG6RSNMM8-P3jl6vqIzM49TXnBTWYU4Q4UNNeQuJEE,7932 +tensorflow/include/tensorflow/tsl/lib/random/philox_random_test_utils.h,sha256=bfu1qSiMCyAEtwbWO9RNtidXQsMGapYbwY02R2C5WZk,1711 +tensorflow/include/tensorflow/tsl/lib/random/random_distributions.h,sha256=tDEHD1S425NspYGKux7cdUpPzv5lURUoaV_stSdZfNo,27766 +tensorflow/include/tensorflow/tsl/lib/random/random_distributions_utils.h,sha256=i9Hx7pDjKAaM3x8agj6vUIa3y4mK7IMQEAfg21cibvg,3444 +tensorflow/include/tensorflow/tsl/lib/random/simple_philox.h,sha256=KW69FRWE4SQtCOc5XeXZ9YjGwsJFR6Qws5113JB1HI8,2388 +tensorflow/include/tensorflow/tsl/lib/random/weighted_picker.h,sha256=Bp2HmYSyCkQtDJ6Gf-NI4Syh0EGErlw-QVV1an-LLjc,4374 +tensorflow/include/tensorflow/tsl/lib/strings/proto_serialization.h,sha256=56PeUXeHXg6iqW8bGTkc-2rmv_GKUjPbLPgQr-Xkcfw,2236 +tensorflow/include/tensorflow/tsl/platform/abi.h,sha256=cG4eLK-_ZzjPjpqLGlthb2UT8rE_bEBwxVEobZu82Jg,968 +tensorflow/include/tensorflow/tsl/platform/base64.h,sha256=2LeGUh85arAeiFuko2l8rZeP6OVK6BLjwR_6kcvqZKQ,2416 +tensorflow/include/tensorflow/tsl/platform/bfloat16.h,sha256=QfIKVVNzqEvImFXW1B_b0NMtHK-iRepoKEKGovJdmTo,967 +tensorflow/include/tensorflow/tsl/platform/blocking_counter.h,sha256=pqX6xmen8phb8fW9uPQVp-tX8ksdaQMJwMNpcbMZZ-E,2372 +tensorflow/include/tensorflow/tsl/platform/byte_order.h,sha256=1ose7fnE61B8zBpMCPqhn3DK6Y1tOvMTCjzUhSpTg00,1333 +tensorflow/include/tensorflow/tsl/platform/casts.h,sha256=823zefPnyZjRuHK6AKnO02nWl4uUjoc-bVHkFeDZBPU,1280 +tensorflow/include/tensorflow/tsl/platform/cloud/auth_provider.h,sha256=5GAmN5Pqmc_O4CBMOKskL3TTxLahPngUcgN5boxHRM8,1665 +tensorflow/include/tensorflow/tsl/platform/cloud/compute_engine_metadata_client.h,sha256=ewlx-KwK2_ghnljXrikW3kFLURHv7qByLA9yJ1mu0IU,2657 +tensorflow/include/tensorflow/tsl/platform/cloud/compute_engine_zone_provider.h,sha256=6NJWhLdbh28hH_rdJHRVhSTrUWmn8hay2zVZmjPkjtI,1535 +tensorflow/include/tensorflow/tsl/platform/cloud/curl_http_request.h,sha256=eTH7jgGFq_fQaFhj8GtC0_3xPQUZg-LXyHDTqnvrNxw,10813 +tensorflow/include/tensorflow/tsl/platform/cloud/expiring_lru_cache.h,sha256=mEPxgiYMSr2KZiTm4FXqpS-_enuuEBOdRFEAHWdB57Y,6114 +tensorflow/include/tensorflow/tsl/platform/cloud/file_block_cache.h,sha256=FRIpNVmQXOPvN9UyIdZ7Zg3zokCT_an8saFlWlXBxwc,5315 +tensorflow/include/tensorflow/tsl/platform/cloud/gcs_dns_cache.h,sha256=K_-UUagvbbTRbDq8R2RNskdLbh_JpL5OLbkPC5fbxI0,2680 +tensorflow/include/tensorflow/tsl/platform/cloud/gcs_file_system.h,sha256=cH2j7-R_7kGNuCiUcfOfsnWCd2zXFVW0GDfSgfcIf0I,18575 +tensorflow/include/tensorflow/tsl/platform/cloud/gcs_throttle.h,sha256=3B1iCJjMeUjtgxMfxT9YsfOsuWGLLQ3iLFJG3Z1Fphk,5456 +tensorflow/include/tensorflow/tsl/platform/cloud/google_auth_provider.h,sha256=Bk55-JEOshWo2mNtEd6kkxIzVixgCjxzhKgsNqJrL48,2734 +tensorflow/include/tensorflow/tsl/platform/cloud/http_request.h,sha256=UoRFRWpYVGrpakbx-xMSR-NLZGxsVc_UIzvGTqz5_wA,6998 +tensorflow/include/tensorflow/tsl/platform/cloud/oauth_client.h,sha256=ZfMuWDWFF4gs6XM2QtMk_as_IBZUYf2cshbixHqh1ic,2371 +tensorflow/include/tensorflow/tsl/platform/cloud/ram_file_block_cache.h,sha256=ay4DGCuyqA5cg9gjX0gou9cDps9-QwtmdB5Vxv2rvHg,9945 +tensorflow/include/tensorflow/tsl/platform/cloud/time_util.h,sha256=n8_GHzOFyiJpdT5pCdt3DB2QYSXzj0h6RQWHaAEsj5U,1057 +tensorflow/include/tensorflow/tsl/platform/cloud/zone_provider.h,sha256=0Z-gv4stkJ4Upl6WnbJYuhZuXr3oI46T-m2juAws7DA,1580 +tensorflow/include/tensorflow/tsl/platform/coding.h,sha256=INF9SzsLbUGzuG0PVQ23jVAS_HPnQOSUFWgdTV20b1E,2826 +tensorflow/include/tensorflow/tsl/platform/context.h,sha256=5RCfXIf_ewEf-SONDFHH-xEsIswSg6LypEzh3JNwIOM,1532 +tensorflow/include/tensorflow/tsl/platform/cord.h,sha256=A9p3UwG6rsITNfEHYuLUXhtu0GHkUTDUjl7-Mq5bXzc,1028 +tensorflow/include/tensorflow/tsl/platform/cpu_info.h,sha256=Y9ZsGsIS4GaCqjRwSTliXkphQQUIkg9f9UJLJuvHF-0,5965 +tensorflow/include/tensorflow/tsl/platform/crash_analysis.h,sha256=qy6CDl85CFX_glF0bBZ7HHCmrI19ehA__N6AOSaODYw,1106 +tensorflow/include/tensorflow/tsl/platform/criticality.h,sha256=lqTyQNWj1Q6vbFY7lO4SwcCiAEuUf1DNDDDsxAi2cQM,1689 +tensorflow/include/tensorflow/tsl/platform/ctstring.h,sha256=gtcB92SahlLfqo5tDUGUov-LBzBQ33Uo1mwehWsPrMk,6165 +tensorflow/include/tensorflow/tsl/platform/ctstring_internal.h,sha256=o5MhZTcc0SixAfsrgnT9sPNrjnRhwW0Y-wqNiR47BOA,13731 +tensorflow/include/tensorflow/tsl/platform/cuda_libdevice_path.h,sha256=zkxWZvDJ9CfIgh1_l4HYneuLzydBUSg1oPdazgPU4C0,1832 +tensorflow/include/tensorflow/tsl/platform/default/casts.h,sha256=Sxph8btO4VtWqBw9R3DNwlD-Ry0ZMgrqG_L5g4JG6Vc,3937 +tensorflow/include/tensorflow/tsl/platform/default/context.h,sha256=Y7yjtAyjVr_sz-9UaFPbMy5kgd9CS0JihKwyl4Nhdjo,1107 +tensorflow/include/tensorflow/tsl/platform/default/crash_analysis.h,sha256=QU1VmzvV7DFC_6QtpGb-D-YfSi8U9IPtgU4uEWDsxeM,1814 +tensorflow/include/tensorflow/tsl/platform/default/criticality.h,sha256=F-Q1BveYCDQlNE91NP1Tk4kfTZ4_yxLzWkp8MmqNTH8,1065 +tensorflow/include/tensorflow/tsl/platform/default/dso_loader.h,sha256=hWDpUz86PKyLPsQppiYPxqH1smBgEklCyBeL8mqsp40,3590 +tensorflow/include/tensorflow/tsl/platform/default/dynamic_annotations.h,sha256=kxeNd9Z9DMs1MeHt8D4Uvqc2UsYUUPW437N8QuXM2ok,1336 +tensorflow/include/tensorflow/tsl/platform/default/integral_types.h,sha256=L8vUmNYzEsA87wujdhqQs-xdAq4B7h1F9liChWcxTHI,1247 +tensorflow/include/tensorflow/tsl/platform/default/logging.h,sha256=Bxr2MaeuKjNNF4S7fJpIlSQdhl3Ww-Uw0Jwxs6s1DtE,24224 +tensorflow/include/tensorflow/tsl/platform/default/mutex.h,sha256=z4F3uq2uNXjaKjZc5OEdsSaO2uy31jZiZsjWyt0feqw,1446 +tensorflow/include/tensorflow/tsl/platform/default/mutex_data.h,sha256=c6EwSCvLzv4dQVnKwtb6-0O8-6cZFnEvbVZtU0KZx6M,1077 +tensorflow/include/tensorflow/tsl/platform/default/notification.h,sha256=faxTcElkcYYNtCBQ9IDHbHZpSr2Cld4UaYgtSkMwGwI,2701 +tensorflow/include/tensorflow/tsl/platform/default/posix_file_system.h,sha256=3xmyVd0H44Sw8vxPicJM69rWdQuo49qWRjNiKRmrTUI,2992 +tensorflow/include/tensorflow/tsl/platform/default/stacktrace.h,sha256=51wXAYitt_UCR0YiIpeFr83Y6nKNQPuBA1MOM8eUGTI,2693 +tensorflow/include/tensorflow/tsl/platform/default/status.h,sha256=LefV-UkuQ-WFYgVdbOrWuNKn_RJ_YxgNJoXPk-iBi68,917 +tensorflow/include/tensorflow/tsl/platform/default/statusor.h,sha256=2tXFF23VvHXeg4wRdK4eG6aGG8w2EthXAYJnliAvhU0,1416 +tensorflow/include/tensorflow/tsl/platform/default/subprocess.h,sha256=hRAfipBH7rtd4UTN_iBWqoTU05QEcoNAux4Wze_V57c,5256 +tensorflow/include/tensorflow/tsl/platform/default/tracing_impl.h,sha256=GYtRBsH-8pmecaVGf31khmcvg0MtIRLE4scuFhUPyZg,1348 +tensorflow/include/tensorflow/tsl/platform/default/unbounded_work_queue.h,sha256=5Fs04iYHU65bBxUI9IN_rGVKXdME2ptP2PENTQhkLm0,2755 +tensorflow/include/tensorflow/tsl/platform/demangle.h,sha256=-FfgkPNrMWb-UdeOsqSm6WN7l_CVumn__LYXWp8esnY,1169 +tensorflow/include/tensorflow/tsl/platform/denormal.h,sha256=NorvQc6tXh6TVGZ4oZJovYTBlGY3ImK9DTo8enPisw0,3143 +tensorflow/include/tensorflow/tsl/platform/dso_loader.h,sha256=ujWXx-KVW3QUoXXhHYUaVNfV8N2FPA715j-5GUtudHQ,1275 +tensorflow/include/tensorflow/tsl/platform/dynamic_annotations.h,sha256=EaTF_LW0HC7bK9fR1ZIuO90UAlDrEqRZ6r6wNIEjpJw,1408 +tensorflow/include/tensorflow/tsl/platform/env.h,sha256=f-UpPp716usl2TgCegUvzcvIXcilNfoQ4Mgk9BqlBnc,28548 +tensorflow/include/tensorflow/tsl/platform/env_time.h,sha256=kItm1M8CC1Addtbt5zpinomMcIzplTOo-XsYr_zbyyk,2445 +tensorflow/include/tensorflow/tsl/platform/error_logging.h,sha256=oJssRW7EBN_eTNAyHiV0XSPm9dCZ2PBPbQqBV8sXEAI,1053 +tensorflow/include/tensorflow/tsl/platform/errors.h,sha256=IsDjUUJFXKdI7AymI7p5NYliUSUhFeEYSWS8iLgtN3I,24971 +tensorflow/include/tensorflow/tsl/platform/file_statistics.h,sha256=HX49M2SrPmsqEqWYQvnmhFSNhQzUyKb3QcGEQw9y-xQ,1374 +tensorflow/include/tensorflow/tsl/platform/file_system.h,sha256=_0SGjkBPkFhPK0L07XvKlKmg4iS14777-38Z9-3PA04,35355 +tensorflow/include/tensorflow/tsl/platform/file_system_helper.h,sha256=_zu0KScFfD37c0txMwntrJI2dUqZOI7XLGP5EK68zHY,2196 +tensorflow/include/tensorflow/tsl/platform/fingerprint.h,sha256=Ovp8plsygTy66wdh0aU6LV7hSU2WvyhpsQj3YsfgyDs,4480 +tensorflow/include/tensorflow/tsl/platform/float8.h,sha256=tQKh2YjcQWdm81fKz2FB-UEX1WjKDKMmOTP0SI7Xo4I,938 +tensorflow/include/tensorflow/tsl/platform/gif.h,sha256=tUsHFh-yCgQV7Rsmb8Xbuf-X50K4UTUBTODL6FD8CCc,827 +tensorflow/include/tensorflow/tsl/platform/hash.h,sha256=xdcxcB0ILmc_uu-HFkHUhV_0dLGIZbGQlmQF8yGnWj0,4233 +tensorflow/include/tensorflow/tsl/platform/host_info.h,sha256=2a98DcHT2bR4te-78VvKjQ4jPuQcuP2oWcwLNWIuhws,1307 +tensorflow/include/tensorflow/tsl/platform/human_readable_json.h,sha256=yZW_fTshYc0pagEf0O-3TEj8SnZ6CIJRNzWmhqzxIFQ,1875 +tensorflow/include/tensorflow/tsl/platform/init_main.h,sha256=VeGZf2EgW7YnH7Is6a5_MPu-iFVrUpI4TXQMeXZHcLM,945 +tensorflow/include/tensorflow/tsl/platform/intrusive_ptr.h,sha256=HQ-d46uft6LOkQUSvG4b26W80klD2yQ-P9tFZrU6Sxs,2808 +tensorflow/include/tensorflow/tsl/platform/jpeg.h,sha256=5MbrkpprrFdHwQYGQsCnmm5Y51ERMjSfUHE5RnEEDO4,1031 +tensorflow/include/tensorflow/tsl/platform/load_library.h,sha256=TJ3km7DeW2-Jen9fMRVZS4LAE_RxAz85nDmRh6HrQZ8,1195 +tensorflow/include/tensorflow/tsl/platform/logger.h,sha256=-GLNgNpDiSahdHKjOBJeTGQ113e6Nl3mfU3v5Y953wY,2557 +tensorflow/include/tensorflow/tsl/platform/logging.h,sha256=y6PCgZD2smAJ0PldZ37usTB2p9kMdeV7TCbac637lAI,1184 +tensorflow/include/tensorflow/tsl/platform/macros.h,sha256=nlssM168-aJOfK-PDCgNzd_SUPkdLCyCdpz3XAGmXYY,5918 +tensorflow/include/tensorflow/tsl/platform/mem.h,sha256=9inPxfkbcFOiT9mTYHqLvXa23voKwlsZgH0yevBIQwg,3179 +tensorflow/include/tensorflow/tsl/platform/ml_dtypes.h,sha256=LTgWZNHeABwGwgM4viAcX1mWy0mAVdruCS4yenm1gzw,1426 +tensorflow/include/tensorflow/tsl/platform/mutex.h,sha256=42TDQMKQAVL1hnrWhR0KOGDXMXTWV7JhzuINOHck0vo,11557 +tensorflow/include/tensorflow/tsl/platform/net.h,sha256=zNRnSa0Lzv2C_RkxWajj728Xcky5lMLgdPN3TkfxEkc,903 +tensorflow/include/tensorflow/tsl/platform/notification.h,sha256=lupKUX8Nf9arjNGXhTnDTuXqMc3rFVZw26ZExO_avwA,1390 +tensorflow/include/tensorflow/tsl/platform/null_file_system.h,sha256=POv4RND5oCdmeh6LEC-EXU4XO2L4RpLbjDsmlUQFXgQ,3786 +tensorflow/include/tensorflow/tsl/platform/numa.h,sha256=IvaCp9s8ORuJZNZPssleEhbNtsmjpuiLVDOzGp3KG1s,2334 +tensorflow/include/tensorflow/tsl/platform/numbers.h,sha256=YK0KyqApfXyZb7W23wf5NMml_ETZ2Pz90KRkmdWoNVc,6894 +tensorflow/include/tensorflow/tsl/platform/path.h,sha256=DkIRma2hzNVZeR3HExyUi9YDqiyKXPy3SQeTuZ8bxYs,4755 +tensorflow/include/tensorflow/tsl/platform/platform.h,sha256=OcZ90jQbXDzzgCs3aIGfKzSpfqUV0S0nJhddQBaTE6Y,2490 +tensorflow/include/tensorflow/tsl/platform/platform_strings_computed.h,sha256=JuM4fVMQshVbbB6y6Woc1edx4pthTbAcqHW_fj9exm8,19436 +tensorflow/include/tensorflow/tsl/platform/png.h,sha256=hBVSoRsFl51nvaWHSKFnfCumZy3TPM-WNjyiEvSYOGU,1198 +tensorflow/include/tensorflow/tsl/platform/prefetch.h,sha256=Kq61cBLsaA8EHEmC7ZKsOOC7IfHZzDmpDiAQWr0q2i8,2116 +tensorflow/include/tensorflow/tsl/platform/profile_utils/android_armv7a_cpu_utils_helper.h,sha256=hPtVCe54ozVN-6__GQbJaCIn4ZLQ9lPiMfRLTzEeiZs,2417 +tensorflow/include/tensorflow/tsl/platform/profile_utils/clock_cycle_profiler.h,sha256=xnTp6f14BBAYfLCk9356I3HAwiuK6vMcZr6KwXiAimU,3221 +tensorflow/include/tensorflow/tsl/platform/profile_utils/cpu_utils.h,sha256=ldsbULEZaR6vYI4JLvwiyRThNLsHnjbognNIoDQfEf0,7468 +tensorflow/include/tensorflow/tsl/platform/profile_utils/i_cpu_utils_helper.h,sha256=7FwWWX1jaI33Gwv-UInUFoC5QS3QLsrRtPkl4mhwpeE,2084 +tensorflow/include/tensorflow/tsl/platform/protobuf.h,sha256=AuiBnziWVgqlQ_pwOSbpg_hh2ggtjQcKveCnanzqBLM,5152 +tensorflow/include/tensorflow/tsl/platform/protobuf_compiler.h,sha256=5rgqklPQPDhbOQWKTkF2BLezdzrgVquqvRB3WbU4zpA,905 +tensorflow/include/tensorflow/tsl/platform/ram_file_system.h,sha256=uXt7MwI-Ut5eJqu1LfMXHaFU3phNoNBRlWPhtcYCqio,10648 +tensorflow/include/tensorflow/tsl/platform/random.h,sha256=nSn_LMbFFMgxHN4IY_h1fElAOKWe6OOF8x_JPr4abHw,1250 +tensorflow/include/tensorflow/tsl/platform/raw_coding.h,sha256=rzgpzoVTm-XVKn2eQIPanREVj9lGIc7KlAenKTN4cIk,2364 +tensorflow/include/tensorflow/tsl/platform/refcount.h,sha256=Qhg6a7hA221rl231GVJuX_kzt42zQ9vCbxpnJj_F9Tg,10668 +tensorflow/include/tensorflow/tsl/platform/regexp.h,sha256=c9YKykntQYv-ppS1bqckIacBFG5JNO3B7gwcG5I2fzM,1108 +tensorflow/include/tensorflow/tsl/platform/resource.h,sha256=r-7zYEbTnl1bziBYkUbuvUti5jCsWixfT5goqmqijNA,1432 +tensorflow/include/tensorflow/tsl/platform/resource_loader.h,sha256=1M-qlStvtq3gxwSLQCB80wmRBwMRr1ZvACjtJMKgAkk,1226 +tensorflow/include/tensorflow/tsl/platform/retrying_file_system.h,sha256=ZSRvUJ2HODXG1GCSFyyl6xkF-O2bbmlo56UU3H62bwI,10574 +tensorflow/include/tensorflow/tsl/platform/retrying_utils.h,sha256=RkXlONDpYVX4535d6jMBLVrUDRYW-Zyhz-IF-iEttr4,2748 +tensorflow/include/tensorflow/tsl/platform/rocm_rocdl_path.h,sha256=kBKtKTXQzW9wMs6A-UshADOdeMytpzOr2aL2ii2PCf0,1124 +tensorflow/include/tensorflow/tsl/platform/scanner.h,sha256=H9NE_9U8zy4owd4fEraV65Y5HRcq11YndqiuW9Esdys,8060 +tensorflow/include/tensorflow/tsl/platform/setround.h,sha256=gre8uJTLottsEwcHzlsOe_tzhqg62yLTv3etIVsTeyQ,1776 +tensorflow/include/tensorflow/tsl/platform/snappy.h,sha256=AL8BJBiUXR3lUndG2M3cb3Y4bq7LWuqI-2kW5yfrD48,1745 +tensorflow/include/tensorflow/tsl/platform/stack_frame.h,sha256=20wyZNQvPzJm4NhORe8gaY2XzVVkyeSy_3qRsSDUbgw,1721 +tensorflow/include/tensorflow/tsl/platform/stacktrace.h,sha256=N1_cwT8svIORm6Gob7wnzGrVD74eLk6b8TdqDo3OkvY,1459 +tensorflow/include/tensorflow/tsl/platform/stacktrace_handler.h,sha256=kyQ0LMch6MunwOsryjAc2FM7Q-YuWjEgC4zTU-tEO8o,1218 +tensorflow/include/tensorflow/tsl/platform/status.h,sha256=4xsIa2Wzae6dg_vd8oFh42Hi9K3RAv_6sHxI0t38oFY,7113 +tensorflow/include/tensorflow/tsl/platform/status_matchers.h,sha256=2zECao95ewtqJA0LQW8ubzv6z9DneZli_Z91XBGKoDI,11910 +tensorflow/include/tensorflow/tsl/platform/status_to_from_proto.h,sha256=Cp2GAk67upz5DO2l9UovvMX5eKrynsKcR1aqV6dxW2k,1620 +tensorflow/include/tensorflow/tsl/platform/statusor.h,sha256=0AA3gc1VZHNyfEpL5JGKFMPdvHiT-0hMLqDIBIJ7ksc,3652 +tensorflow/include/tensorflow/tsl/platform/str_util.h,sha256=XuVN4XYi0YglmfHKBnHraog_f2aiH5t0pmmcrV23gYU,7059 +tensorflow/include/tensorflow/tsl/platform/strcat.h,sha256=EPxtUJtowrXBqMGgoJpvNy2eRK6CuHv2HqidwIoVfEk,9824 +tensorflow/include/tensorflow/tsl/platform/stringpiece.h,sha256=GkhWyfIjZFtvm0b8HH4EJXq7t3M4W7q6vOuQujTlRQw,1433 +tensorflow/include/tensorflow/tsl/platform/stringprintf.h,sha256=qn-7daP85qADG7lcy8L_qE5pFRMjPh5Hkw-n5G0fiSI,1761 +tensorflow/include/tensorflow/tsl/platform/subprocess.h,sha256=-Ta7RXHJybxNPbYmE-O33VqcPf3y8YH4mNE_HcPkE4I,2402 +tensorflow/include/tensorflow/tsl/platform/tensor_float_32_utils.h,sha256=Bhw_oJ_RcAtS8EYM677qw-r-ptzRPDkuzLM0MGIRBuQ,980 +tensorflow/include/tensorflow/tsl/platform/test.h,sha256=2IgNF8U_eyY28_YBpHArHKCYclcsT4Fcz9vrn7-avHQ,3471 +tensorflow/include/tensorflow/tsl/platform/test_benchmark.h,sha256=NgCqmbbZCImQLMSea_4OpWyfVbJ_rYO9BFPhiDAPG1g,1669 +tensorflow/include/tensorflow/tsl/platform/thread_annotations.h,sha256=4DlDn6a03IgwVQt2EmFo3PtwxtMpL_LOQXKTxli2Pvc,7829 +tensorflow/include/tensorflow/tsl/platform/threadpool.h,sha256=AVtEcmJxOuFr4Xzl7WQ2h6erY2vRjrpC0-tDchNCsX4,10943 +tensorflow/include/tensorflow/tsl/platform/threadpool_interface.h,sha256=1hlti9OWtLseKJmWLih8A0olcB7but46VvtJQA_BKD4,1124 +tensorflow/include/tensorflow/tsl/platform/threadpool_options.h,sha256=H9k8yT_mmon90QIApC7BlF2tngPXeDYtCgvP4qjOO2I,1258 +tensorflow/include/tensorflow/tsl/platform/tracing.h,sha256=xCnJHOZH3i4hdDYtjENiong60Q54dtckOXb4v1T9c54,4762 +tensorflow/include/tensorflow/tsl/platform/tstring.h,sha256=2y74sC-qto6phf5eh7nyQx4OnUblKl3iTOILI1JXUk0,15797 +tensorflow/include/tensorflow/tsl/platform/types.h,sha256=BnkhxZbWa6X6YllAqD1jAMDgeRJ5SzxPSUsswgm4HbA,2923 +tensorflow/include/tensorflow/tsl/platform/unbounded_work_queue.h,sha256=3A9rfd974GncOc6NN5yvdbJkhcY9OiUO_dx3yzFlH7s,1485 +tensorflow/include/tensorflow/tsl/profiler/backends/cpu/annotation_stack.h,sha256=aDZRHJTfoqyJxUnvNLj3qYFUVTagghQJgsuvmNIsx5Q,3152 +tensorflow/include/tensorflow/tsl/profiler/backends/cpu/host_tracer_utils.h,sha256=0zLv1ZSEY-yQ_2UUBkW1L_KlDHJd0-kSrZ-MEcJiGpk,1343 +tensorflow/include/tensorflow/tsl/profiler/backends/cpu/traceme_recorder.h,sha256=NTzgiULJND8QJjNrME4-LvmC4oBcStRcoJ4p7Rs1Jyw,5204 +tensorflow/include/tensorflow/tsl/profiler/convert/xla_op_utils.h,sha256=BoG9JJnf6VRAFFAWd0VsgoyiH87-VHmjEk8-uC60rnk,1462 +tensorflow/include/tensorflow/tsl/profiler/lib/connected_traceme.h,sha256=QR7_Qf27YrJNgP44hdH_vCT4PTStrgframJ8KZU2lIM,4617 +tensorflow/include/tensorflow/tsl/profiler/lib/context_types.h,sha256=S2yDyksXuIvrK1s2MCDDKOVms3ub114hzvY_IBaH9C4,1800 +tensorflow/include/tensorflow/tsl/profiler/lib/nvtx_utils.h,sha256=TuIbfQ4iblcj_s1j_-bVn0lg4F17RHRImgP19mL7c3U,2408 +tensorflow/include/tensorflow/tsl/profiler/lib/profiler_factory.h,sha256=-j2Ej00FGPY0l-RmjyPyEuGk2kO8UmbDLDn3cifmihA,1777 +tensorflow/include/tensorflow/tsl/profiler/lib/profiler_interface.h,sha256=HNel3IptZpsgw3h6OhzC-oQmbB5rVbEfNVVLGcRpN7k,1681 +tensorflow/include/tensorflow/tsl/profiler/lib/profiler_lock.h,sha256=C0qjg3Rw1y_W2cj0vxHhSfsqHYPyMaUeh2UIJn5Doiw,2300 +tensorflow/include/tensorflow/tsl/profiler/lib/profiler_session.h,sha256=4Txk0PzaZv7k1FVmiWBRm7jmnFCdajAn1lYoPId64JM,3335 +tensorflow/include/tensorflow/tsl/profiler/lib/scoped_annotation.h,sha256=6_IKT8UGqkF7gNxps4GjpffAjDo1J0CLnSmlzz06piI,5565 +tensorflow/include/tensorflow/tsl/profiler/lib/scoped_annotation_stack.h,sha256=gXr3x6RFpE3w4UcTHd6maPTNPdE3lrRdPlksLVLR0Ig,3930 +tensorflow/include/tensorflow/tsl/profiler/lib/scoped_memory_debug_annotation.h,sha256=qaR4-nf9NLxrUStUs846e3lbl_pdAfov4Km2q50Wikg,4565 +tensorflow/include/tensorflow/tsl/profiler/lib/traceme.h,sha256=Crk5CFGAtzZGTOBkdnKWRtf1zXXFVoApv5oj7N5cSQk,13014 +tensorflow/include/tensorflow/tsl/profiler/lib/traceme_encode.h,sha256=UUS10qt7kZ74ZnZ3ZTXApiAdpm4Xt2hSTcgPMYn3yI0,6248 +tensorflow/include/tensorflow/tsl/profiler/protobuf/profile.pb.h,sha256=PHjhCjdubWmlIkSUVZxwSg84iBbhXwRXvOWbnWQQXPg,105039 +tensorflow/include/tensorflow/tsl/profiler/protobuf/profiled_instructions.pb.h,sha256=7Uc68sj0BDy_uOvdtoRtcJlffcJoA4fw0WYOop7TuSE,37638 +tensorflow/include/tensorflow/tsl/profiler/protobuf/profiler_analysis.pb.h,sha256=78z_LEU263LFGHN4bjrHrq9Ln_iTwKYmLordQFNUss8,101456 +tensorflow/include/tensorflow/tsl/profiler/protobuf/profiler_options.pb.h,sha256=9xo0QE8G23g_4agFq_yFR_JVtR2YFU6moMlooCtszr4,44476 +tensorflow/include/tensorflow/tsl/profiler/protobuf/profiler_options.proto,sha256=hVBmvbvJcLrUnoamr8B-gR1j6gjS7JrfywOhlUPdtEo,3216 +tensorflow/include/tensorflow/tsl/profiler/protobuf/profiler_service.grpc.pb.h,sha256=OMmyzmvUSIdCQl9VfRl3pefqjxedWSJbewztqJxSp0o,45758 +tensorflow/include/tensorflow/tsl/profiler/protobuf/profiler_service.pb.h,sha256=rvq7HmOd57O5xhcDpgXMkwPSe4n_bi4GUHzNiAzPK80,91599 +tensorflow/include/tensorflow/tsl/profiler/protobuf/profiler_service_mock.grpc.pb.h,sha256=f52sfE0SLYqmCulSyujbKgkkCpfx7obNEEAe0x_EVX4,2366 +tensorflow/include/tensorflow/tsl/profiler/protobuf/profiler_service_monitor_result.pb.h,sha256=-t-qdw9azBLjpZrtujidZq2c15UIP529TeQrMKAz2l8,24010 +tensorflow/include/tensorflow/tsl/profiler/protobuf/xplane.pb.h,sha256=UlV6KFqevwCwcX6jO1owqcznu5p18N79qM3DbqIUjeg,121459 +tensorflow/include/tensorflow/tsl/profiler/protobuf/xplane.proto,sha256=iNIS3zQqYe9oIj9TivspLDIlwjDOzSSEn98-mUpN3SE,4532 +tensorflow/include/tensorflow/tsl/profiler/rpc/client/save_profile.h,sha256=teI3qYxbdJYNYsFdYO42l04-7_Pj0RF5sc0vlyOwYc4,2337 +tensorflow/include/tensorflow/tsl/profiler/rpc/profiler_service_impl.h,sha256=dR14pA0DX7upDVadtkXFZVFEYFmCfMqhvjQIiOdc0oU,1106 +tensorflow/include/tensorflow/tsl/profiler/utils/buffer_pool.h,sha256=sXi2Dyq8yjDildh6HPCntQoWF1mTuHIJvJ_Fug_bUzI,2141 +tensorflow/include/tensorflow/tsl/profiler/utils/file_system_utils.h,sha256=plDRpFoKIK-RnMUEenKTPzU-_gTVYh9qVyIWM4MN1nQ,2037 +tensorflow/include/tensorflow/tsl/profiler/utils/math_utils.h,sha256=1213LtM8p9SI8KJIgHfLLafitiQrvM-QxHVfO6BUHKo,2994 +tensorflow/include/tensorflow/tsl/profiler/utils/parse_annotation.h,sha256=XnhNizcAA-v8uucTF0FtUFDS15Knd_uIU3Ist4GiSuo,1712 +tensorflow/include/tensorflow/tsl/profiler/utils/tf_op_utils.h,sha256=PSeih8S1sCHzRCgcK9SEk8myqL4IOhh02qtap3v0J1U,5476 +tensorflow/include/tensorflow/tsl/profiler/utils/tf_xplane_visitor.h,sha256=Z9Vd2kwpmhIp30US_hgOX3GF-XPZTeZhzv9_Bsanq0M,1280 +tensorflow/include/tensorflow/tsl/profiler/utils/time_utils.h,sha256=9yAwD4dRlG5PhmdZP8rPh96mdLaB2wTRT8WpClHsSkc,1572 +tensorflow/include/tensorflow/tsl/profiler/utils/timespan.h,sha256=EXoKVkuIiRqkDlbjOWb7ZSnRiNg31qlcrCwv_L_m5uc,5051 +tensorflow/include/tensorflow/tsl/profiler/utils/trace_utils.h,sha256=vBL1KGrZ2jdPuDjGqUQnbIZ6C5nAcIMWqLt2oanqLx4,2714 +tensorflow/include/tensorflow/tsl/profiler/utils/xplane_builder.h,sha256=mnoq-Cgy7yVQ9oIsQrn_SQJKn-d_cDeKOwkiWyedcl4,16102 +tensorflow/include/tensorflow/tsl/profiler/utils/xplane_schema.h,sha256=y1D4Ze2aIphq6GI2YyFVPQCS85H2TtD1vWSat0T3iHU,14161 +tensorflow/include/tensorflow/tsl/profiler/utils/xplane_utils.h,sha256=Af7Aep8MGgXzdh9iEtE4y1SWDU8ghwEN6p8OAfyOx9U,8773 +tensorflow/include/tensorflow/tsl/profiler/utils/xplane_visitor.h,sha256=Pj3bqelaooQAQz3OU8V8vyAXUwj2FkIeKs6_eSdH3CM,12013 +tensorflow/include/tensorflow/tsl/protobuf/bfc_memory_map.pb.h,sha256=ET8ZmvevjYUpPknukTL7cVvM9NopDvwggoJbV0jAZXE,63172 +tensorflow/include/tensorflow/tsl/protobuf/bfc_memory_map.proto,sha256=5numCqlHUQYO_qcm6gWwuxouasjkAbleJHl_cm3430k,998 +tensorflow/include/tensorflow/tsl/protobuf/coordination_config.pb.h,sha256=kjiqHKPXpQ7Jum0w4qAF6QOltpqUObC-i8jjtSCj1yI,39922 +tensorflow/include/tensorflow/tsl/protobuf/coordination_config.proto,sha256=DAJeejk-tpAGtUBqtUIkpM75qJvNfh9x-xAfB7O82Bo,2945 +tensorflow/include/tensorflow/tsl/protobuf/coordination_service.grpc.pb.h,sha256=e_IMtefTC5-WTAg4GcM4gEsuxC2UiB06VCwDch7s7sY,235017 +tensorflow/include/tensorflow/tsl/protobuf/coordination_service.pb.h,sha256=CZ3Gt5W1RA9o68PpuR752wQl69r8RZRW3s54d80MQI8,325635 +tensorflow/include/tensorflow/tsl/protobuf/coordination_service_mock.grpc.pb.h,sha256=EnbYUhYu4R7EKcdfxQo90c8Aq4r72mTKYZK0Bqp7rTA,10309 +tensorflow/include/tensorflow/tsl/protobuf/distributed_runtime_payloads.pb.h,sha256=gJxFD7vfKW_4hhvvGsfRNBGXKpUwyHEJM7GnssR3acc,22583 +tensorflow/include/tensorflow/tsl/protobuf/distributed_runtime_payloads.proto,sha256=8hua5uB4F8mlYM1OcH6o3JBlLdMLryTc_FO4oGMrv0E,890 +tensorflow/include/tensorflow/tsl/protobuf/dnn.pb.h,sha256=AYn4FkZiYpw5NHZ_TLps32CDGP1pigxEG3LYXpLE9mQ,88437 +tensorflow/include/tensorflow/tsl/protobuf/error_codes.pb.h,sha256=oXi9DKjyPyFnRcqNqd6XBothzjlURjq8cyLzaeLCHWQ,4241 +tensorflow/include/tensorflow/tsl/protobuf/error_codes.proto,sha256=dfDydWk0PVYqUFWm5Ow7CW8sGIKWf414s4zCmFSrf50,6575 +tensorflow/include/tensorflow/tsl/protobuf/histogram.pb.h,sha256=trsORy2ScuY1pvhBE8oyOQ2a4OwRDYh4KT7Ahw9cumY,16901 +tensorflow/include/tensorflow/tsl/protobuf/histogram.proto,sha256=jt9Qkt6kiRVlxeOXhHBKNBUmng_-L4lECqIpkN0gfpg,798 +tensorflow/include/tensorflow/tsl/protobuf/rpc_options.pb.h,sha256=rjyCk_yb4NwMZfZVb30urTMXGEdTNdsIPPdIbAlo014,16330 +tensorflow/include/tensorflow/tsl/protobuf/rpc_options.proto,sha256=C2K5wJatr61jPbLHsJ6G96QQsg1ZSz413olTQ5twlr0,1846 +tensorflow/include/tensorflow/tsl/protobuf/status.pb.h,sha256=gib5IWmv3KqoVwgtIiMEoyaL8Zgj61l7XkYVMnggWPM,10890 +tensorflow/include/tensorflow/tsl/protobuf/status.proto,sha256=JborF3CrtI1U37iEWY-Gcyte_Bt8zLkWuVWYAzVYYTQ,500 +tensorflow/include/tensorflow/tsl/protobuf/test_log.pb.h,sha256=5pIwklndPBGm4urB2aIY3KuSK0ddH2z86V7T_DdEXzo,243492 +tensorflow/include/tensorflow/tsl/protobuf/test_log.proto,sha256=58HCVNeWqu1iauSkDY6U7WiFZE9mCrUZi_VHynhiEbQ,6736 +tensorflow/include/tensorflow/tsl/python/lib/core/ml_dtypes.h,sha256=e1We5UIv6Rb5IDlSQBY9YAj9ayVvz0glHn4YL8lN2yE,1694 +tensorflow/include/tensorflow/tsl/python/lib/core/numpy.h,sha256=mFx39tFAllsSq3t8OeQUP6kTFb768pDyWfpZBrBCJCA,1597 +tensorflow/include/tensorflow/tsl/util/byte_swap_array.h,sha256=z6v5MkJ7xuLjrdq_Lj2lnZ6B8p2JqngCf5vxeV3GoeY,4299 +tensorflow/include/tensorflow/tsl/util/command_line_flags.h,sha256=YMBgDgJJpOuHUtRvRsY38KayeCDxkOK77cYN17MheuQ,5545 +tensorflow/include/tensorflow/tsl/util/determinism.h,sha256=1fNrl0CrB34sVi4QvnySt6U71X2MKDjMQt7euzcc5nk,947 +tensorflow/include/tensorflow/tsl/util/device_name_utils.h,sha256=XmuW-dn_Z8AIchfJJz92CBS8I7FSesBAm2eM4EIRZog,11728 +tensorflow/include/tensorflow/tsl/util/env_var.h,sha256=GwpsdiW-tHwPELgaJgENSq_BrmZYenZ32uWu1utias4,2550 +tensorflow/include/tensorflow/tsl/util/onednn_threadpool.h,sha256=6KuQXtfNuDU862dYsI-y9zIBUMf3au9H_8ZpZvcx9EM,6508 +tensorflow/include/tensorflow/tsl/util/proto/proto_utils.h,sha256=A2FPl_QYDTmKdMLVabohcQ2S8p1xrULhREV3gkeclJU,1563 +tensorflow/include/tensorflow/tsl/util/stat_summarizer_options.h,sha256=ZSUU9fkc0bR8SX624XU2lnQJ_Tq5AX0pcSUoh2o2_H4,1424 +tensorflow/include/tensorflow/tsl/util/stats_calculator.h,sha256=QMZw7JUSXzwHnmboVU-CRxx_LI06SYn_aqXurNZELwc,5975 +tensorflow/include/tensorflow/tsl/util/use_cudnn.h,sha256=1XiQHCMrNepJ5MxKNKa92XcGsn_eFM8xP7XOqnIeFmw,1604 +tensorflow/include/third_party/eigen3/Eigen/Cholesky,sha256=_j9x7oUlMS8_Uzi0Nu9zvaZ0Z4qH4Gh-vYdzJZpb9vA,26 +tensorflow/include/third_party/eigen3/Eigen/Core,sha256=10fW6Zyf1fS5mW8DX1VNpGRr09iwv5lM0RcbYqtyILw,22 +tensorflow/include/third_party/eigen3/Eigen/Eigenvalues,sha256=7f3zOav_6U6q3m3VZonIlOMm3bU2x604Rl2OSfZxtfI,29 +tensorflow/include/third_party/eigen3/Eigen/LU,sha256=v3e1m24njX2mLR_e6MNwAqaMA-yUs015ySNgkeau2XQ,20 +tensorflow/include/third_party/eigen3/Eigen/OrderingMethods,sha256=65rNcJJBkokilLLs-lj8aJHMTtqduR70-75nXPln8T8,32 +tensorflow/include/third_party/eigen3/Eigen/QR,sha256=S61bJNWAxJZ3aYhT4t0cWwcpzOSRX7N444A_7JYQ9jQ,20 +tensorflow/include/third_party/eigen3/Eigen/SVD,sha256=F4xLDKiGCN0rDMQwz6Dyjxj9isP9_BQKx54ItNoLWEQ,21 +tensorflow/include/third_party/eigen3/Eigen/SparseCholesky,sha256=wM_6Zm2V5x-VB7U86CCz5tmf4lbMHSmK3rxi9u7WdXk,31 +tensorflow/include/third_party/eigen3/Eigen/SparseCore,sha256=rcq9dE8t7jvQ6jttheqa1OFL-XnelbxI4FqNV5ZvnRg,27 +tensorflow/include/third_party/eigen3/unsupported/Eigen/CXX11/Tensor,sha256=Y5NQpQ3WMPPQABg5Sxn6vJSQicyS5_f_x6OmYbwg00s,42 +tensorflow/include/third_party/eigen3/unsupported/Eigen/CXX11/ThreadPool,sha256=-OeOeuSx2Obi6EcTjwzu3fjcRUe4BU9bASgU5Bo09hA,46 +tensorflow/include/third_party/eigen3/unsupported/Eigen/MatrixFunctions,sha256=71QsRFtJUxgTT6hdI7MFO_sXlubwOMxRkIOOfjR_2OY,45 +tensorflow/include/third_party/eigen3/unsupported/Eigen/SpecialFunctions,sha256=mMQpu729SWAAyLposrwHt--JV9dKhfDI9z-odSWvXVo,46 +tensorflow/include/third_party/gpus/cuda/cuda_config.h,sha256=Agt2pQ3WM9tRvpI9kWBSCzOe4BYPhyflDzAcniDB0N4,1148 +tensorflow/include/third_party/gpus/cuda/include/CL/cl.h,sha256=XYgf-K1IMQL8xgoP7JCpwNIWGGqRpKuv5jSVXQ4HDWc,83898 +tensorflow/include/third_party/gpus/cuda/include/CL/cl.hpp,sha256=q9H85bvcgom7daYH3L1VuQvsvKTnDfnUgyrXyuoBrkM,281251 +tensorflow/include/third_party/gpus/cuda/include/CL/cl_egl.h,sha256=52DQKJdj8aGHg1UVB3HcpezACjwNHfsmdJOARfdvYgg,4434 +tensorflow/include/third_party/gpus/cuda/include/CL/cl_ext.h,sha256=9z9oCq_N6un9JMP-8BfFzpeaH0ipFTgLOI4QyBL_t8g,97516 +tensorflow/include/third_party/gpus/cuda/include/CL/cl_gl.h,sha256=nBi2Vk06KWgdHL3qnIbueKPYqn-6czyEHEoM54l22cE,7510 +tensorflow/include/third_party/gpus/cuda/include/CL/cl_gl_ext.h,sha256=dGUhDU7tPyXA_aYkYp5jTOR3gS6I6168q5PjH_FWf_I,905 +tensorflow/include/third_party/gpus/cuda/include/CL/cl_platform.h,sha256=iIMHdbM-9ChqkV3kTu0FxCprIVZ18ggibYzBlZsQaPs,45659 +tensorflow/include/third_party/gpus/cuda/include/CL/cl_version.h,sha256=GxYfc8DwsHEhMUBV9132wZ1qk-Og0kICxvPi3RYVsqI,3125 +tensorflow/include/third_party/gpus/cuda/include/CL/opencl.h,sha256=mnb6Y2MOj9WzC15saS2-erIu3_cI3-agbQSjZxp3FuE,970 +tensorflow/include/third_party/gpus/cuda/include/Openacc/cupti_openacc.h,sha256=Z0OM5e_hbd3cxdXyn3SCHqBBQawLg4QORnlm57Cr2-M,3513 +tensorflow/include/third_party/gpus/cuda/include/Openmp/cupti_openmp.h,sha256=E1WNmeb_7HaUSmBegtUNe4IV1i7pXeNxgzIlyKn1zrM,3491 +tensorflow/include/third_party/gpus/cuda/include/Openmp/omp-tools.h,sha256=AmuC_xPC7VPu3B-W4PmXuCNufFawhY8PjNXePaQFAOg,37403 +tensorflow/include/third_party/gpus/cuda/include/builtin_types.h,sha256=JxT9Vf2q2snxTBOL9ACzNmYzTWACO2VOVUu1KdFt7_g,3150 +tensorflow/include/third_party/gpus/cuda/include/channel_descriptor.h,sha256=no_vNky02LeMLI0CF8GDVGHaPm_uRUGcVUMYdt_Xn4U,21482 +tensorflow/include/third_party/gpus/cuda/include/common_functions.h,sha256=22LTZRVcPZzEH6MJda7nNMCvMgIjSTe0OKR7sEQj6kc,3410 +tensorflow/include/third_party/gpus/cuda/include/cooperative_groups.h,sha256=vToGlGH8RGQ08vYbyxBTDE8CG6-_jRrSV9ZYT7KbSD8,60019 +tensorflow/include/third_party/gpus/cuda/include/cooperative_groups/details/async.h,sha256=xsEHCZP3nuEY3l2p8SU2d1226XiXumUvDP_Gyh8PdVY,19122 +tensorflow/include/third_party/gpus/cuda/include/cooperative_groups/details/coalesced_reduce.h,sha256=vWv1tyxMjSMM2Oc0SdxXhCug_PwaBM6u8iMLjKyeqjE,4561 +tensorflow/include/third_party/gpus/cuda/include/cooperative_groups/details/coalesced_scan.h,sha256=DfZv5d5W0XJv-tZVhgrIdjLjs6aCx_u0oy1lDIpjo1Q,7314 +tensorflow/include/third_party/gpus/cuda/include/cooperative_groups/details/driver_abi.h,sha256=v-ZUb4UgGKJk6NR2WCWHD3x_42y-togI1urFn70Gi-g,3964 +tensorflow/include/third_party/gpus/cuda/include/cooperative_groups/details/functional.h,sha256=2BV8i8Bidz0kgxuYkJCAbwFxOIZRyzHgG-c_rVKhRzc,8905 +tensorflow/include/third_party/gpus/cuda/include/cooperative_groups/details/helpers.h,sha256=qj8ndO_GRp1sKs7HgCytYumlk58KgpsYF9SF6CcVg3c,23777 +tensorflow/include/third_party/gpus/cuda/include/cooperative_groups/details/info.h,sha256=LSrEe6iTHuQRfc7RD3EHQbNqpED8eAbX4HLNyxXgKFA,12286 +tensorflow/include/third_party/gpus/cuda/include/cooperative_groups/details/invoke.h,sha256=Osq3K-tZuXHVCMQJ708PjPo-BwMhjhjApO4b0TYLFJg,8616 +tensorflow/include/third_party/gpus/cuda/include/cooperative_groups/details/memory.h,sha256=WU28eUcYLA1z131VYGulR4eVCSN9xK9KSxbV656YPs0,5484 +tensorflow/include/third_party/gpus/cuda/include/cooperative_groups/details/partitioning.h,sha256=8hCh6F8sfkyfRgMirC37Nqv-b-gIY3A_J0eMYqmD2zU,6001 +tensorflow/include/third_party/gpus/cuda/include/cooperative_groups/details/reduce.h,sha256=kz5m2oMq32PTozeDTGDBPCeJnZ3cxD9lYvZdIwdr5Ks,22730 +tensorflow/include/third_party/gpus/cuda/include/cooperative_groups/details/scan.h,sha256=-Ttwb2AfEEY_tsmqJjR2dojkPpoRx387SoqxgvfdBtQ,17166 +tensorflow/include/third_party/gpus/cuda/include/cooperative_groups/details/sync.h,sha256=hiWcwaCcLlEfrD_rH7D-IQXWdB6T_Ifbc9aNR47wGCU,11801 +tensorflow/include/third_party/gpus/cuda/include/cooperative_groups/memcpy_async.h,sha256=erOIHuObdfxRhBWfrXE3wsZF4B2GUuqwzQrsPwKPpbg,2960 +tensorflow/include/third_party/gpus/cuda/include/cooperative_groups/reduce.h,sha256=B0hgDkqM-6ueqTTgb3b34A0RH4vGz8mBf5e2jT1dJ1o,2949 +tensorflow/include/third_party/gpus/cuda/include/cooperative_groups/scan.h,sha256=2EU6T5cWNwftm2B7FicV31PojoI61yo5fHXGRYkGk40,2940 +tensorflow/include/third_party/gpus/cuda/include/crt/common_functions.h,sha256=-U44f4yUGmwDPwd7Q_3Cz5if05xHGPSlAzz5zMylLSQ,13559 +tensorflow/include/third_party/gpus/cuda/include/crt/cudacc_ext.h,sha256=KW6n0ImOZKS0VqVmBHWTXtHI816hh88YeEgUg2aYdVU,3224 +tensorflow/include/third_party/gpus/cuda/include/crt/device_double_functions.h,sha256=pznu65Pp1kT08mNkXB6J1epefIogxqMapQ0fnabNjr4,39789 +tensorflow/include/third_party/gpus/cuda/include/crt/device_double_functions.hpp,sha256=YYIbqYhb5Qmf8c4YfcC_jytg4FRwcXPjv3TFTwhb24E,8568 +tensorflow/include/third_party/gpus/cuda/include/crt/device_functions.h,sha256=555FTiTAxIq73v80kO6vF6d8G6vI4E8uEI-6sKyvc4g,134713 +tensorflow/include/third_party/gpus/cuda/include/crt/device_functions.hpp,sha256=tnrzMdE4Ve4680L8owOKKHLmACU3T9izelISBgzlZtw,38005 +tensorflow/include/third_party/gpus/cuda/include/crt/func_macro.h,sha256=EOpDlaM917bh9cwBiFBPF689DCMBw5hFarxLxFt-i74,1755 +tensorflow/include/third_party/gpus/cuda/include/crt/host_config.h,sha256=vYshoWp-yS1gw3zSCmTeYVmOATiZxQPcLK-r_rmDTj8,11490 +tensorflow/include/third_party/gpus/cuda/include/crt/host_defines.h,sha256=0QkLt92g6NxmVBtNrUfQrOA5xEZSvMgvBF7EiqZir3k,9277 +tensorflow/include/third_party/gpus/cuda/include/crt/host_runtime.h,sha256=QverDqBf0MLLZxl3kwvkNPyUojIgCB-WbjgDvvRnEaU,9346 +tensorflow/include/third_party/gpus/cuda/include/crt/math_functions.h,sha256=VZ62-Q4rnWa_E6wtwCxppaOa2wYTdMjYEuXMbznXnRM,395949 +tensorflow/include/third_party/gpus/cuda/include/crt/math_functions.hpp,sha256=iBFD7RjY2myyxtQ9qpMl7y2w5qY5lVnrlWbeLEgz8GM,100076 +tensorflow/include/third_party/gpus/cuda/include/crt/mma.h,sha256=OmIQLmGzZl59b3ZfaRyDk_HuKvFGZAOChFFI8iVviQY,62502 +tensorflow/include/third_party/gpus/cuda/include/crt/mma.hpp,sha256=spo0LX71tUCipxK517Bssj0nc-ZHf8oMWzvHoYYB_6I,66599 +tensorflow/include/third_party/gpus/cuda/include/crt/nvfunctional,sha256=FDM0zqWO6bl9jpJKz9U8CMbjt6iTKh18tQalxAvRsag,16900 +tensorflow/include/third_party/gpus/cuda/include/crt/sm_70_rt.h,sha256=b_ub73AMT7ri5Ph2ahZzU6hyrFfIymnEx3NM7lv01UM,6506 +tensorflow/include/third_party/gpus/cuda/include/crt/sm_70_rt.hpp,sha256=3a_rU-Y0MSB4htBDFY4PCQ_jXiWFTe7WT1ZyhMuCJOA,7837 +tensorflow/include/third_party/gpus/cuda/include/crt/sm_80_rt.h,sha256=1LmDr7ftuCDpdqAnyRjgAiD_y85vjF2xUUnN9EelFW8,7449 +tensorflow/include/third_party/gpus/cuda/include/crt/sm_80_rt.hpp,sha256=o-rJu-jpehCeyABGgv-8dYRB7oJTCwuNdvSCq0VURdE,6705 +tensorflow/include/third_party/gpus/cuda/include/crt/sm_90_rt.h,sha256=rsTDnVnMVcP78rrhigv_GOHORtoFP3duKm9tZZSZwqo,6117 +tensorflow/include/third_party/gpus/cuda/include/crt/sm_90_rt.hpp,sha256=YuqVygGV6rgtWtx1J9cPpEI3BXKQBII-Ez6oZFP3wrE,9228 +tensorflow/include/third_party/gpus/cuda/include/crt/storage_class.h,sha256=dzcOZ16pLaN8ejqHaXw4iHbBJ6fXWxfaU-sj2QjYzzg,4791 +tensorflow/include/third_party/gpus/cuda/include/cuComplex.h,sha256=WpcgpaiPhU_o9sTPMcNTEZuyXDIc8x3sz4dUWSztL2g,12186 +tensorflow/include/third_party/gpus/cuda/include/cub/agent/agent_adjacent_difference.cuh,sha256=A9HSbQ1Y9QZJ6oUqZcgxzBgQ4BWUl9dPtwe8OcDIEfA,9725 +tensorflow/include/third_party/gpus/cuda/include/cub/agent/agent_batch_memcpy.cuh,sha256=DWJvS7bwABsi8tJ5kt3ZV6eZPBqwS78kZcCSFL0WEMo,52597 +tensorflow/include/third_party/gpus/cuda/include/cub/agent/agent_histogram.cuh,sha256=N9kl870fLYAu30GzobaQJYRbrZUihsM7zTZWSQvitRE,34460 +tensorflow/include/third_party/gpus/cuda/include/cub/agent/agent_merge_sort.cuh,sha256=yNwvpjjxVWHDYSakMUJxGto8uFFaWkAqmQUP9rOqT_0,26107 +tensorflow/include/third_party/gpus/cuda/include/cub/agent/agent_radix_sort_downsweep.cuh,sha256=4Qwydwt9RgEuKFgMOS0hf_nnDUf8b218DTq3il5ImTg,28822 +tensorflow/include/third_party/gpus/cuda/include/cub/agent/agent_radix_sort_histogram.cuh,sha256=0UbvKHByNp6gELq_sJtAaC5Vlr1Brx961q6iVtdhivA,10492 +tensorflow/include/third_party/gpus/cuda/include/cub/agent/agent_radix_sort_onesweep.cuh,sha256=jzhGahwXfqXf91feNqGtkeUj-KlwNAamlOe7RCtMf_g,25694 +tensorflow/include/third_party/gpus/cuda/include/cub/agent/agent_radix_sort_upsweep.cuh,sha256=sVDpXqlM-gLABmE4-wnORMhywZHa2kJ2NuUYZL9Z8g8,18573 +tensorflow/include/third_party/gpus/cuda/include/cub/agent/agent_reduce.cuh,sha256=Ld0SrYsoEpAuYm8_KXFqiLxBXarplHSxDoyrjdi8Gjs,18284 +tensorflow/include/third_party/gpus/cuda/include/cub/agent/agent_reduce_by_key.cuh,sha256=wU1PA-2NB2b4t7NF2U3Oa3Se6KlIy24xM9Kp2jCmgZM,23919 +tensorflow/include/third_party/gpus/cuda/include/cub/agent/agent_rle.cuh,sha256=sH9MXR2WoTpYDX71w1vGcjTsqa6vJjBkefnOm5SHzls,38794 +tensorflow/include/third_party/gpus/cuda/include/cub/agent/agent_scan.cuh,sha256=YQxv63FSdF4_KIjBdyHGAWuk_KnQS5YcIuBZa6429Q8,19189 +tensorflow/include/third_party/gpus/cuda/include/cub/agent/agent_scan_by_key.cuh,sha256=zpR2fRwz2-V_KFWnlbWtiiapcQooTWHTIsbJGBEwAUI,18550 +tensorflow/include/third_party/gpus/cuda/include/cub/agent/agent_segment_fixup.cuh,sha256=D4NIfwQmdrfY4irAuaodO2Zh-afm-em4IWXhpikRtvQ,16588 +tensorflow/include/third_party/gpus/cuda/include/cub/agent/agent_segmented_radix_sort.cuh,sha256=vvWPUY_hhWhAZw3GjnzfCuR1ztFVV_EtPiq30VE-KJY,10432 +tensorflow/include/third_party/gpus/cuda/include/cub/agent/agent_select_if.cuh,sha256=er36LDtmV6fDVdVyvMGLcf4mgsUWzUo7_Qr5ExIm-54,29398 +tensorflow/include/third_party/gpus/cuda/include/cub/agent/agent_spmv_orig.cuh,sha256=q4A_vygNut8Kj24fqXSkOSiIKZOWMrHs59Z_ug3YGLs,27874 +tensorflow/include/third_party/gpus/cuda/include/cub/agent/agent_sub_warp_merge_sort.cuh,sha256=_nGui0elcCscB5duzz-7nzA2uI8wCDPZCgL777g4cTo,11999 +tensorflow/include/third_party/gpus/cuda/include/cub/agent/agent_three_way_partition.cuh,sha256=7D_XArToljfM2WxcGxzg76W_i8WjyuhqsPxLq_-ovyY,20993 +tensorflow/include/third_party/gpus/cuda/include/cub/agent/agent_unique_by_key.cuh,sha256=E6wlLlpzG_mOsd6FJwMmHgZRm9wEcOrn0vlVP7Fw2hM,21756 +tensorflow/include/third_party/gpus/cuda/include/cub/agent/single_pass_scan_operators.cuh,sha256=m6h0gcAjTIU6lZRZ6kiz6dIoRuVhMWlFfQbS6iksxOI,39754 +tensorflow/include/third_party/gpus/cuda/include/cub/block/block_adjacent_difference.cuh,sha256=9qfaeX5bCvTZu2Qb-A6VN-JT95uJMZlTqFNJOJuyPfs,52579 +tensorflow/include/third_party/gpus/cuda/include/cub/block/block_discontinuity.cuh,sha256=K0X-uUPRbOvkIr1zeNMZdPnvhucT6-6wlcYHah3n97M,52893 +tensorflow/include/third_party/gpus/cuda/include/cub/block/block_exchange.cuh,sha256=z8v7USohDdLnaNf-_vh1laYEjfq51c_Jeu7dU3ZHoH4,50116 +tensorflow/include/third_party/gpus/cuda/include/cub/block/block_histogram.cuh,sha256=6JetJlvo81HBHjAMifSe4ciyY1Nfhr7yBHNjGjvj40w,16713 +tensorflow/include/third_party/gpus/cuda/include/cub/block/block_load.cuh,sha256=tyjP12X0FnQh5riifuh2RH57Wiaq_5VPnALzkK6u2rM,56629 +tensorflow/include/third_party/gpus/cuda/include/cub/block/block_merge_sort.cuh,sha256=i7ZxaufMs7yOEaSD_jU77zgjwjbAYk2qWwtasOppVRk,28724 +tensorflow/include/third_party/gpus/cuda/include/cub/block/block_radix_rank.cuh,sha256=iv-IVvpcHVDa6CuFawtpW_mu542MaRsJOSUN4p4FauI,46953 +tensorflow/include/third_party/gpus/cuda/include/cub/block/block_radix_sort.cuh,sha256=M-M4dLL-i6UhnSzcRwFh5YJlY0jp5gf7pZnXshQFldY,91838 +tensorflow/include/third_party/gpus/cuda/include/cub/block/block_raking_layout.cuh,sha256=SU6b1p6Mkfy3V61hWQaNcyA3pwWB7WgxBRTdFUBVVTY,5964 +tensorflow/include/third_party/gpus/cuda/include/cub/block/block_reduce.cuh,sha256=FSkRDRh9HhyVWp1WIBMS7Pn8gYrEhxZf17ozGW0uXck,25500 +tensorflow/include/third_party/gpus/cuda/include/cub/block/block_run_length_decode.cuh,sha256=xRye2THxjhoX-titRpFe9cJHFNwTC29F6QDmCMRYqYY,18949 +tensorflow/include/third_party/gpus/cuda/include/cub/block/block_scan.cuh,sha256=vuCqd91Zk5dhhynSnjGP_LK7fXkoqDnoJeePqvsUD38,103189 +tensorflow/include/third_party/gpus/cuda/include/cub/block/block_shuffle.cuh,sha256=mdk3hq0etGcMSlJc8emNXCfeQYv_sT9ET1dPApiZOL4,11726 +tensorflow/include/third_party/gpus/cuda/include/cub/block/block_store.cuh,sha256=Yyizys99SWTm4LwxKSAOU2Y5pcUi3GOm1sK7ztdMf-I,44245 +tensorflow/include/third_party/gpus/cuda/include/cub/block/radix_rank_sort_operations.cuh,sha256=_m6cfK9pIrisUY4_LsTB0mL76k8hyy5mgCS6x3_WIOw,20148 +tensorflow/include/third_party/gpus/cuda/include/cub/block/specializations/block_histogram_atomic.cuh,sha256=WDotjXCGrXSqhm9y3gaeb8gwWxOmeVugf_Y6LlBQAIc,3154 +tensorflow/include/third_party/gpus/cuda/include/cub/block/specializations/block_histogram_sort.cuh,sha256=mdO74MCvxWnu7wGeABuV2mB--kQ81E1N1krI0frD_6U,8229 +tensorflow/include/third_party/gpus/cuda/include/cub/block/specializations/block_reduce_raking.cuh,sha256=h-C39T2y5iV9LRC9hN5hVb1W8bWJsYR2Jnh404f3lLY,9620 +tensorflow/include/third_party/gpus/cuda/include/cub/block/specializations/block_reduce_raking_commutative_only.cuh,sha256=BTjuiXagGsmjRzcJI3hzn8AJ7NAdv8gHirZeZFdRySg,8351 +tensorflow/include/third_party/gpus/cuda/include/cub/block/specializations/block_reduce_warp_reductions.cuh,sha256=EbtYPAzcJhQmaQtkY3ckgyBM7GX3lSg-qnlahJMbYg4,9722 +tensorflow/include/third_party/gpus/cuda/include/cub/block/specializations/block_scan_raking.cuh,sha256=UDV5535Qy-7Bx9gPDU0wv2fcqTz_7DGi2m_UcG94E58,28535 +tensorflow/include/third_party/gpus/cuda/include/cub/block/specializations/block_scan_warp_scans.cuh,sha256=MKMXx6wRwqYGVZnycYLS50S0Yqn-gP61i6AIyuLIUm4,19175 +tensorflow/include/third_party/gpus/cuda/include/cub/config.cuh,sha256=EYwE2J1Dxd8dVhpYWAXaJhTuD9qD8BEM_-WBNx3sMCk,2000 +tensorflow/include/third_party/gpus/cuda/include/cub/cub.cuh,sha256=zuziUNhdpbWc7xKk6K4kMsfyisQX0838G982IaLHt3s,4166 +tensorflow/include/third_party/gpus/cuda/include/cub/detail/choose_offset.cuh,sha256=N6Zo8Q7z0sbSAxIchTd2T0OyXppK1rVuUUrSqU1Ve_0,2581 +tensorflow/include/third_party/gpus/cuda/include/cub/detail/cpp_compatibility.cuh,sha256=JuloMrg7UXqbmZgUV2pZ477RRcK1ZNqrNoQe4Ozqr9Q,874 +tensorflow/include/third_party/gpus/cuda/include/cub/detail/detect_cuda_runtime.cuh,sha256=R-e3pyqrJSU_bCY-ZYAj_vBzMNYR4YtMwuVcSLr2g3w,3665 +tensorflow/include/third_party/gpus/cuda/include/cub/detail/device_double_buffer.cuh,sha256=qm38dNC77K5LSf3QLmTXyGaYPm1EqjBiYuvkzH7C3To,2698 +tensorflow/include/third_party/gpus/cuda/include/cub/detail/device_synchronize.cuh,sha256=yKZHV3gFQ6elvsCH3498cSZFI6rPhV0ePiWT1iVJVYY,1926 +tensorflow/include/third_party/gpus/cuda/include/cub/detail/exec_check_disable.cuh,sha256=zQNBZ-1Ap2cK5xIDbzU7mvxdZ0_EmIulp6BkNYe-oMY,1181 +tensorflow/include/third_party/gpus/cuda/include/cub/detail/strong_load.cuh,sha256=StUd0eonWEvIENaHRT0ntFwhxIGGkquP0wNnA9bL4Is,7278 +tensorflow/include/third_party/gpus/cuda/include/cub/detail/strong_store.cuh,sha256=tFLLH6ZM9kzRvKbp6SBnnejc-BatEEvm7xnNbubO5Js,12231 +tensorflow/include/third_party/gpus/cuda/include/cub/detail/temporary_storage.cuh,sha256=KGaKde9oZhI-f4tqs14UFwQPyRb-wiIYsNCevXkbjQQ,8634 +tensorflow/include/third_party/gpus/cuda/include/cub/detail/type_traits.cuh,sha256=8BIXZBy37i2kxUDYPizNtep3l7p3aE8Z2MMmb5vpW_8,2485 +tensorflow/include/third_party/gpus/cuda/include/cub/detail/uninitialized_copy.cuh,sha256=Ow_92GaDnIgWnN7JV8lFNdOIlYQ2sVUE8BNXF5EAJdM,2693 +tensorflow/include/third_party/gpus/cuda/include/cub/device/device_adjacent_difference.cuh,sha256=I2tvsIlWZkrm7XdNaK1fV6lWD6_ETaLpNDgzU_Nmbbo,26211 +tensorflow/include/third_party/gpus/cuda/include/cub/device/device_copy.cuh,sha256=549Ib-sjhCkn5qbgReknBugNbR_Ald4MpAh4xTIo9c0,7813 +tensorflow/include/third_party/gpus/cuda/include/cub/device/device_histogram.cuh,sha256=DGVgwKO7bSyI8RzvMrZmgXr-utWlCo1JQKS1JSM6Guo,71035 +tensorflow/include/third_party/gpus/cuda/include/cub/device/device_memcpy.cuh,sha256=Kln0uP0bWryGE9XPUvtkJp2BMf_RYOvBaDdX-5-ABxA,8866 +tensorflow/include/third_party/gpus/cuda/include/cub/device/device_merge_sort.cuh,sha256=4ii8cSOlp78x_2syZjaYPit1RvelRxJNlP6FqTHWA28,42009 +tensorflow/include/third_party/gpus/cuda/include/cub/device/device_partition.cuh,sha256=vTiPjnYdRy3R0e6-V7lkxwcVm8vvryoM0V5SYxPKCS8,28990 +tensorflow/include/third_party/gpus/cuda/include/cub/device/device_radix_sort.cuh,sha256=I31GzSVQBaJYcQfnmBQb4IW7VsF_Vy2IV869ITYDPAc,158583 +tensorflow/include/third_party/gpus/cuda/include/cub/device/device_reduce.cuh,sha256=SU4gyWTOVLTudCugdseAbldIt4Gy7WjPeMrMCo14R-Y,48462 +tensorflow/include/third_party/gpus/cuda/include/cub/device/device_run_length_encode.cuh,sha256=KSNVzivDsajKc-7LR72azk9pD6TJbXRHhTUr0RsFJYc,18200 +tensorflow/include/third_party/gpus/cuda/include/cub/device/device_scan.cuh,sha256=C9GGuvoSH3RT4ExCXvjvxGFAcqMAacFwDt_snwZQSl4,85061 +tensorflow/include/third_party/gpus/cuda/include/cub/device/device_segmented_radix_sort.cuh,sha256=Wim8EUMkuiPd8sSccWh7m_bgsXIpkA505lrc1HJF3Jc,73338 +tensorflow/include/third_party/gpus/cuda/include/cub/device/device_segmented_reduce.cuh,sha256=wvlRbSzrzjCXDSxzrxInom9LnFUlI5rf8wmyLL66_m4,46509 +tensorflow/include/third_party/gpus/cuda/include/cub/device/device_segmented_sort.cuh,sha256=UwHmlzFfxcSelDSgZr025b42LchmZWVAbiobgj8jMNE,130046 +tensorflow/include/third_party/gpus/cuda/include/cub/device/device_select.cuh,sha256=uPBAHrTjXd5WQG-L8M0_i9ILM4G8ae9ELfw8Kh4eKnw,40912 +tensorflow/include/third_party/gpus/cuda/include/cub/device/device_spmv.cuh,sha256=EPBJqxKjKof2nRNc4FspluY4cHnHx1ANMeWTXiGaFUM,9516 +tensorflow/include/third_party/gpus/cuda/include/cub/device/dispatch/dispatch_adjacent_difference.cuh,sha256=jx4rD2Usw4F4A6a2nV_thDKpBLGk4jU9Bpn45WU-lbo,14322 +tensorflow/include/third_party/gpus/cuda/include/cub/device/dispatch/dispatch_batch_memcpy.cuh,sha256=37aVzXee-_mPfNCTbRi4v6oSZJbL2a65-cHCTl-N2RE,32720 +tensorflow/include/third_party/gpus/cuda/include/cub/device/dispatch/dispatch_histogram.cuh,sha256=2_zo_m1KR6nzMjCo76IL-d5da_RymHrj08wvP28tM-Y,61773 +tensorflow/include/third_party/gpus/cuda/include/cub/device/dispatch/dispatch_merge_sort.cuh,sha256=HFR2WtHsrAT7NgYjwx22OAncNJtM0Y4r6wsWWAn22sM,31943 +tensorflow/include/third_party/gpus/cuda/include/cub/device/dispatch/dispatch_radix_sort.cuh,sha256=YVABkIq3GuN4LANlCgbXF3l9EBAUPMipqJjsRZPAEPA,116742 +tensorflow/include/third_party/gpus/cuda/include/cub/device/dispatch/dispatch_reduce.cuh,sha256=01zcLVVmovUD289HvTmCCCJlnz1ZzbJeppgni-DFiiA,45772 +tensorflow/include/third_party/gpus/cuda/include/cub/device/dispatch/dispatch_reduce_by_key.cuh,sha256=IJRA6yeBpwpgTTTbBYY6onPu5Qgk66gx2yz0rgbj1aI,20606 +tensorflow/include/third_party/gpus/cuda/include/cub/device/dispatch/dispatch_rle.cuh,sha256=UqurbR-gOybWPVP5_sW676awHaTaBMrSqcTt6cDgdZw,19683 +tensorflow/include/third_party/gpus/cuda/include/cub/device/dispatch/dispatch_scan.cuh,sha256=0jtl6PEGGWs2f_EAbntjmKl37XgC5Z1EGEpw9Ofgb7U,20674 +tensorflow/include/third_party/gpus/cuda/include/cub/device/dispatch/dispatch_scan_by_key.cuh,sha256=0Zo3ovOGZ--mOvH94xxyaFeU9QbvRo4098-t8Ztd2TQ,21896 +tensorflow/include/third_party/gpus/cuda/include/cub/device/dispatch/dispatch_segmented_sort.cuh,sha256=VpAqM3e6FjymEqrLXpNTr0a6GNgQnikfTSaFD7C-bQ8,67162 +tensorflow/include/third_party/gpus/cuda/include/cub/device/dispatch/dispatch_select_if.cuh,sha256=TkKXJBA3BzH6oJAXDElLs9QpMUEnsnMeK3l7lu4FDyY,22770 +tensorflow/include/third_party/gpus/cuda/include/cub/device/dispatch/dispatch_spmv_orig.cuh,sha256=EPsETs05k5UVrMzTFN-7E1_7_Q5DW9pYaaaDSybm8MI,35878 +tensorflow/include/third_party/gpus/cuda/include/cub/device/dispatch/dispatch_three_way_partition.cuh,sha256=h_lP1XQtHrX6fBXkDafEnjoMZr5LZu7fTnkMBDIsrCs,17669 +tensorflow/include/third_party/gpus/cuda/include/cub/device/dispatch/dispatch_unique_by_key.cuh,sha256=7t9yPwTE4GNO3QTdTLG8pUdKtYrGc3DD2FsOguC2ZZ8,21562 +tensorflow/include/third_party/gpus/cuda/include/cub/device/dispatch/tuning/tuning_histogram.cuh,sha256=QKn02Uct9Kab0Tp_mvQRiM61FASWM3igVV7TlP9dOjM,6682 +tensorflow/include/third_party/gpus/cuda/include/cub/device/dispatch/tuning/tuning_reduce_by_key.cuh,sha256=zg3BjQcmaXpwV7OxBa1KA_IUgaqsQv8mVTd7wCheNgE,19094 +tensorflow/include/third_party/gpus/cuda/include/cub/device/dispatch/tuning/tuning_run_length_encode.cuh,sha256=b4goed9uOgH0e8PhUW5dTxTBhddM8GE8pkC-cRTcRFQ,21096 +tensorflow/include/third_party/gpus/cuda/include/cub/device/dispatch/tuning/tuning_scan.cuh,sha256=GtLmNYldhsiwxwAYusOyM9OEszFnzndKgXf4UWeeI4I,13323 +tensorflow/include/third_party/gpus/cuda/include/cub/device/dispatch/tuning/tuning_scan_by_key.cuh,sha256=0-UjbA5rbIEXtUyhhUI-kAA_Eb0jai4_gdm3KzalHrA,21025 +tensorflow/include/third_party/gpus/cuda/include/cub/device/dispatch/tuning/tuning_select_if.cuh,sha256=0wQ5AyixuqJf74jiwia66pQ7kPA9n5IRrBrQQwKK5Yg,25281 +tensorflow/include/third_party/gpus/cuda/include/cub/device/dispatch/tuning/tuning_three_way_partition.cuh,sha256=oSf2nPl0DBA0Kzxec6zMd2zBt5jMKpBGoXl9CJAm6ZU,10789 +tensorflow/include/third_party/gpus/cuda/include/cub/device/dispatch/tuning/tuning_unique_by_key.cuh,sha256=Vwq12CkNFjUAqfJ_gGGU62STCDXQ5BvCLtlCxxL1AAI,15221 +tensorflow/include/third_party/gpus/cuda/include/cub/grid/grid_barrier.cuh,sha256=IRGX1OEmM4W9NDFxuhH1-2gId1NlEoeJG0Lqxe4nVjg,5730 +tensorflow/include/third_party/gpus/cuda/include/cub/grid/grid_even_share.cuh,sha256=seJ7nCPuGtoTH6B9feJocKngs_EwxC9nDQAoOZZ1Xz4,8287 +tensorflow/include/third_party/gpus/cuda/include/cub/grid/grid_mapping.cuh,sha256=wm0QeZ-CEgcgKMh0GI7p58LfYrAQkYXcjcv4CvByeao,4696 +tensorflow/include/third_party/gpus/cuda/include/cub/grid/grid_queue.cuh,sha256=JK2_Gc4KphfanDYipyG5rv47TaZbZjoon4S_4CvlWmc,7886 +tensorflow/include/third_party/gpus/cuda/include/cub/host/mutex.cuh,sha256=qbQoiM1iKPEWoSP1055WPO34o9f5KKSb5A7xsBcGaBw,2319 +tensorflow/include/third_party/gpus/cuda/include/cub/iterator/arg_index_input_iterator.cuh,sha256=lvVC9o78hcQF-BMcK1Ppdx4Y0NbKm7fzrD4YrG5hjfg,8668 +tensorflow/include/third_party/gpus/cuda/include/cub/iterator/cache_modified_input_iterator.cuh,sha256=2AlYeWQXKas8dJCj9lI37BTXPDQmeul_SoG98cmpWSo,8020 +tensorflow/include/third_party/gpus/cuda/include/cub/iterator/cache_modified_output_iterator.cuh,sha256=4U2eSLRdR4PU05sy_pWDzgtbsIZDNuTcmjnuKHCD_Xw,8228 +tensorflow/include/third_party/gpus/cuda/include/cub/iterator/constant_input_iterator.cuh,sha256=w6khwE6LFC2fd7EW0kEAznbBeWTLhpqrT5LMpCBmzs4,7570 +tensorflow/include/third_party/gpus/cuda/include/cub/iterator/counting_input_iterator.cuh,sha256=hJruADabQ3B-pxWZcp2P96Sx1E_Z2MaJNNkMmhaNayU,7289 +tensorflow/include/third_party/gpus/cuda/include/cub/iterator/discard_output_iterator.cuh,sha256=OaNwpnsIhfSI3U-V-r_zy4yYv0cYgtJ31_Ity15al4I,6543 +tensorflow/include/third_party/gpus/cuda/include/cub/iterator/tex_obj_input_iterator.cuh,sha256=yFuKsZyicDWBOB8qTaN3r4qfQswJpa5HD_wfXo6rVlA,10903 +tensorflow/include/third_party/gpus/cuda/include/cub/iterator/tex_ref_input_iterator.cuh,sha256=UNDFGNI-4EUO2Yq7ly3PVZbuvDqmG3QaKPxdJiBNxyM,4581 +tensorflow/include/third_party/gpus/cuda/include/cub/iterator/transform_input_iterator.cuh,sha256=qCKC1WfNTyEzxkQt5VqlRrtVGZAi6bNHH1H0lTdinX4,8390 +tensorflow/include/third_party/gpus/cuda/include/cub/thread/thread_load.cuh,sha256=C3tDxla8dWlUisQYh69pJF5wgIN7tjSzC3NZQKWolOA,18053 +tensorflow/include/third_party/gpus/cuda/include/cub/thread/thread_operators.cuh,sha256=M3JZBQ7V4OD-WtHEgP2PtWYThQ_Y3EiQ9tCOHchUCxU,11884 +tensorflow/include/third_party/gpus/cuda/include/cub/thread/thread_reduce.cuh,sha256=9crRrFqXCQlVYbb_h2eRfQ1EiXTgbvvZ8Db1IS2YuuA,6284 +tensorflow/include/third_party/gpus/cuda/include/cub/thread/thread_scan.cuh,sha256=UApS0JYq7OeoSO7li4ufcchMErwauo-JgUp-EaraKnE,10435 +tensorflow/include/third_party/gpus/cuda/include/cub/thread/thread_search.cuh,sha256=DOz_KwvYOFCIyxRk1tfdy9wUt6ZxHJypR02Jh_ZWk98,5630 +tensorflow/include/third_party/gpus/cuda/include/cub/thread/thread_sort.cuh,sha256=VxXRlIMV6-5NUPwCwgBz7NBeJ8Quj8d8W5kTR6Evfeg,3543 +tensorflow/include/third_party/gpus/cuda/include/cub/thread/thread_store.cuh,sha256=gKzGBK3fBDoovK2y8y2yBzWNAx5N0pv8B1-pnXvNvJA,17566 +tensorflow/include/third_party/gpus/cuda/include/cub/util_allocator.cuh,sha256=wuL9rQOel6oOF7Uq3q5S4TvDVhgW-snfImi-JSzqkrA,29025 +tensorflow/include/third_party/gpus/cuda/include/cub/util_arch.cuh,sha256=nG_egh7LNqYrM8BRuPjk_LpD2a8erLrwwvzLdf9Ef9s,6059 +tensorflow/include/third_party/gpus/cuda/include/cub/util_compiler.cuh,sha256=eY8xMPIbk0URcQM7fO8EuaRVHP86J1mpUykpx6rKuCY,3644 +tensorflow/include/third_party/gpus/cuda/include/cub/util_cpp_dialect.cuh,sha256=lOjUgM7To0ky9WlDeq0pDrvaYs7xRUk60O8BqwBzL1U,6333 +tensorflow/include/third_party/gpus/cuda/include/cub/util_debug.cuh,sha256=2JpdOEiqyHcxrzAVH2eNwBL5WgltJjzKqeEqiqYHx3Q,9578 +tensorflow/include/third_party/gpus/cuda/include/cub/util_deprecated.cuh,sha256=GNc0vdKBLjhlxkOKNUKHWnm4DIubvpClLa4ObA_xsY0,3733 +tensorflow/include/third_party/gpus/cuda/include/cub/util_device.cuh,sha256=f-lqIpe1I_j9ZqN2gfPd56_PYFYfNDCKG9cdCPNpMag,23043 +tensorflow/include/third_party/gpus/cuda/include/cub/util_macro.cuh,sha256=yygJuAWEv1dflrpiBJl3979B48EauavV0UXHkv-RyGM,4348 +tensorflow/include/third_party/gpus/cuda/include/cub/util_math.cuh,sha256=mtXLJaHD-Dpx1ak0fi9fT3fNcnWpw2Ve9V1wJnI2szM,4476 +tensorflow/include/third_party/gpus/cuda/include/cub/util_namespace.cuh,sha256=pI6smL4uqwsN7E6duXET_HGFw9RNHBZSjy3mAUEGt4g,11031 +tensorflow/include/third_party/gpus/cuda/include/cub/util_ptx.cuh,sha256=ml3x_VxuwMep8HGJ4azt9EtquGLR-bnJ9bqe2Mw6kbI,24612 +tensorflow/include/third_party/gpus/cuda/include/cub/util_type.cuh,sha256=9NN2VIQA3NAz8LbZylJ3w3QzYi6R5dFgZwoRGjUvq5w,46523 +tensorflow/include/third_party/gpus/cuda/include/cub/version.cuh,sha256=QLEiDDPq2bxZwtSA-gur0PI1BBe-aSGPHCxuaNn40YE,3116 +tensorflow/include/third_party/gpus/cuda/include/cub/warp/specializations/warp_exchange_shfl.cuh,sha256=n6lhlR33j5M7Xtsh3lJp_jduWEtAbFVD5V9xJ4JXhow,14768 +tensorflow/include/third_party/gpus/cuda/include/cub/warp/specializations/warp_exchange_smem.cuh,sha256=xMqXs7OEmTQIYlJZAQfZNi005pCYq8sdC2aPRyU2rhE,6101 +tensorflow/include/third_party/gpus/cuda/include/cub/warp/specializations/warp_reduce_shfl.cuh,sha256=Q_gF4EtjiLH14My16KRcWUHMPSgEAETiRX6tXaiIxlY,23019 +tensorflow/include/third_party/gpus/cuda/include/cub/warp/specializations/warp_reduce_smem.cuh,sha256=cazLSuCUpOq4GqHWnVKEA_TuUqLyIsrGUNXyRtwUts8,13928 +tensorflow/include/third_party/gpus/cuda/include/cub/warp/specializations/warp_scan_shfl.cuh,sha256=SENrUs6UuYg9qAtXQHjptJYqOPO9gBrizf88M-9QcoI,22355 +tensorflow/include/third_party/gpus/cuda/include/cub/warp/specializations/warp_scan_smem.cuh,sha256=lhs-fbTpX0X3ql38yIC3-CmvpDfwPwKiohO6lJwBKug,15617 +tensorflow/include/third_party/gpus/cuda/include/cub/warp/warp_exchange.cuh,sha256=9sXd_ZByN725l8rC4un-dt0eRCJl4b-3q9JGcXjlqCw,16569 +tensorflow/include/third_party/gpus/cuda/include/cub/warp/warp_load.cuh,sha256=0uyH5mmkpDyScv5j-QeNKm8ZsKE6vu2Nbluerup1-RE,25652 +tensorflow/include/third_party/gpus/cuda/include/cub/warp/warp_merge_sort.cuh,sha256=SXdCk8N4P4t1oxGNn6iEV51pkENKEw94QNfJulamyHU,6188 +tensorflow/include/third_party/gpus/cuda/include/cub/warp/warp_reduce.cuh,sha256=Z0X0PAOGzL9-4hNFGLmvZygYCHsdSWGDUYngdpIng28,27137 +tensorflow/include/third_party/gpus/cuda/include/cub/warp/warp_scan.cuh,sha256=M-H6QPN3jJazX3tvB8nqOEDJV5U7zCu2SQn0qs3h0UA,38738 +tensorflow/include/third_party/gpus/cuda/include/cub/warp/warp_store.cuh,sha256=u7-UnF-B8ZJJ0sJS_TP2z4YwXecXpPrphupOoj782ik,19928 +tensorflow/include/third_party/gpus/cuda/include/cublas.h,sha256=a0lLqy-k47NuwyDjuueC3W0Mpc908MTU7o5sMJqE-1w,41246 +tensorflow/include/third_party/gpus/cuda/include/cublasLt.h,sha256=51KyHQc7T9rxmVfNimP9O6vka8JqBdebjZKCWKZakt4,77626 +tensorflow/include/third_party/gpus/cuda/include/cublasXt.h,sha256=CW9dyXYGSUW1wEXrVVyhU6OxBK1PUvMoYdVGlQT7L9A,37380 +tensorflow/include/third_party/gpus/cuda/include/cublas_api.h,sha256=LLtRkdoFYrDvOIlyymH1jfwzOlfiTO9hB3qRE0ChTXo,364749 +tensorflow/include/third_party/gpus/cuda/include/cublas_v2.h,sha256=qxMdB5jb97luEfw61LEAB-Wlr8A9DLBvO4rRypDCNKw,15460 +tensorflow/include/third_party/gpus/cuda/include/cuda.h,sha256=orRDZATDqaQjHWZ8gR8k6d2sJWqz8wx6SGEgVQq9eNU,966317 +tensorflow/include/third_party/gpus/cuda/include/cuda/annotated_ptr,sha256=HnadNEdewiR_SCGxPgxc-d4gL9J4UNM_VuxtgxQ3Qnk,24054 +tensorflow/include/third_party/gpus/cuda/include/cuda/atomic,sha256=wzJ7u9DoQTM-weX4j9joRD_uuUzZKSy3iPdDdC1t-ss,581 +tensorflow/include/third_party/gpus/cuda/include/cuda/barrier,sha256=U9HLFOl6RQaAC91_xHxF889ReSezK8E7PQtXf_MPSa0,585 +tensorflow/include/third_party/gpus/cuda/include/cuda/functional,sha256=HQVQDdIswI1BuQX0Y2h81nSr4-bBwSWDN6pOMq4SR1M,14527 +tensorflow/include/third_party/gpus/cuda/include/cuda/latch,sha256=h9mH8_SY54uABDBYd36GMmK17i2vULOFZTjEKT-9KB8,577 +tensorflow/include/third_party/gpus/cuda/include/cuda/memory_resource,sha256=udCD0grJ1MFWR582V3vtd5u19gSIldRbLD106mWbGvA,24462 +tensorflow/include/third_party/gpus/cuda/include/cuda/pipeline,sha256=tg11_x_w4jbGJSZ4EByDMQ5N2MHukhDXJyrt1lV_lX4,32762 +tensorflow/include/third_party/gpus/cuda/include/cuda/semaphore,sha256=oiaBqKdvGcpvf8JtV_KmHJD82eyo9A4EEc6udWPhHUE,593 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/array,sha256=lr0J_HGeqIRFzwUu_WO1o95u586BydF5y6Tf26nFWTU,657 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/atomic,sha256=innzq3d9P-xjdfeNbQnyJhiTkAdF517Op1Ep50BihMg,704 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/barrier,sha256=QDvkUk3grR6aa5Wxg_5UdOTFzdBN84xIH4-vU7_dLoY,846 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/bit,sha256=iS419UsiC7hK9wFtJCzze9Zz336nwdM71Z7Of-GgXb0,692 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/cassert,sha256=daRs7pIXSHAmboQDfmfXK7gsMyXm90dQRMJPN3iYFkw,708 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/ccomplex,sha256=evFZCJp5uk3Mw1tOjJmy9mq72Yt2o9-ZYW96CWiyG5A,553 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/cfloat,sha256=WsUfjwf1FHJR1Trv5rKy1ubiY3zk8Yvk5wZ2SedhiJI,704 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/chrono,sha256=KFSEVfUB23PXsX0CIqivpKAYtMcR1NIejSNKCpXJX-k,704 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/climits,sha256=EustdLEDjWsg6Hmws2lU40d9EUnoGMzUBugbxGdDukM,708 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/cmath,sha256=-l-SXwBv3rdjTcqGQKSuGmnXFHRQjfbP71SumQ4J6Qg,657 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/complex,sha256=Ud-z0_M7RFV0LVjAAo4aygPzjmdfzZGVMqPfjc270xw,665 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/concepts,sha256=QQlFbqlw0VqeJcYFzccrc6ImHPebWuaTGFZa1FGFAwg,669 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/cstddef,sha256=fsGGJYdLpuALl1Xl30u-RjCYa_OnE7tz11Yen-SmvW8,708 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/cstdint,sha256=6wQV3NY7KrkI6YYQpdD6HwozpBhH1lED4MvJl2-I8do,708 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/ctime,sha256=dDnmpdvGvVilgtz8B7iL0yGzxgVJ_BL7TgZW-XG2d3o,700 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/__access_property,sha256=HqMeQWmYX-D0UIngG53hEMqTOk4ky6Vb5w4eld54d_c,22878 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/__annotated_ptr,sha256=iMobNX-W0Ua4RDXgkLJiUZvuGiLnp-hzCBJ4ip8O7jk,18607 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/__config,sha256=Nla2XiXiqXySURFPqpMXSRPXAIHbAA4eTmnQBGPL5S0,1770 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/__pragma_pop,sha256=SDNO97_pDQYQorfrXtBzyWM0lwprI83gi5jJ5Ijd8bw,532 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/__pragma_push,sha256=9N2-MqaYb9VQ6VX-MX4MttkVKZ2lNdNg6mG6hiyu8NY,574 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__algorithm/swap_ranges.h,sha256=JX4G4bNA0Y2v-j2wwpKJdAIkxE4Q-ZZDts-YPtn0Vuc,1143 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__assert,sha256=wuWdbzJxT9De4MITiyxWJG9Nj9QSfb6ANYRpqsyrJBI,2658 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__availability,sha256=zR0BCrteutMSt1tDosjC94oW76tT1316jTcMCyXtK8Y,17311 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__bit_reference,sha256=GfH2CvLSCpxyY2ogU3N_qZ_rN-wsbFe860lNYMltAxA,53088 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__bsd_locale_defaults.h,sha256=vPnHf_i4BfSM_T9ZlOOkjwphErzTGm9ZCu8VvkbmCL8,2121 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__bsd_locale_fallbacks.h,sha256=QsHpd0FVlR8ksp_6t_WxS22aQRfzlY7klUrNn_Pmlzg,4100 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__concepts/_One_of.h,sha256=pGqOuayNNktjX0LCwkUOVGeV5PiYXA2CrSDMDxrSpZw,1239 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__concepts/__concept_macros.h,sha256=34gXLixC7RN8FjChVPlJe1K9CGOOYDGXquPamkPW2DY,15279 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__concepts/arithmetic.h,sha256=4ethDBgR4X3sbBiXv1xK2DnIPLOQt668HgzDomHG2Fw,1926 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__concepts/assignable.h,sha256=NkOIeRIZbW6mlIAYcw8cx48DktVGtpOTCHNR35MVdp8,1970 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__concepts/boolean_testable.h,sha256=GdOusXfV5-wUhP7LCyJ5cZZCPnJxXvsdSWDi3ExmRrE,1753 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__concepts/class_or_enum.h,sha256=bmberGIWBT4pVSkyTZu6ftLdp_z-wXSkZoZao0-mrtk,1563 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__concepts/common_reference_with.h,sha256=3NT_IDWSRCEbc7jWfVNOl4fPK-ggQi5uVrBLSRzk2YE,2292 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__concepts/common_with.h,sha256=hC8Dr_i1Y3SJAWfHzFJZb5Sy0jPJNFK5KKBxxAoETXQ,3211 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__concepts/constructible.h,sha256=cPK8Q8iuAM4gzuVWFLXl6KWtR67emyQXaMUIK6dxCS8,3819 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__concepts/convertible_to.h,sha256=-rwr-fi5UKGOK4MsWgMO9KwBWNmw9nL_5E0003KMfrA,2260 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__concepts/copyable.h,sha256=Bni6cPpVbLvAvdnXDu7zn_kUuS_ezD-RHNsEnEYK4jE,1651 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__concepts/derived_from.h,sha256=95D-C8jK7hRM13qMfE5NDRhg3jRvxEN_y6ogSn1F55s,1634 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__concepts/destructible.h,sha256=mgF6bmguN6VjAiWYl8ebXIJDoC5nrT4FAKBL2fl0GfU,2599 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__concepts/different_from.h,sha256=bFVlc6oOCkl4Scgq6-dvM4EgWjkTGhAzVr_g5cJPACw,1124 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__concepts/equality_comparable.h,sha256=Y5efheGoEi2ls7GNJfVnWMLfGNGvwqjrjknEaO43ngU,3637 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__concepts/invocable.h,sha256=TRf1oOWGXGEAfeyscbSWHwy68D8Vnsj4upm2tMN0IIQ,2592 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__concepts/movable.h,sha256=immmj6-jlFv0Ya5HJNkrhm8vNjDOig46pu0NagLfiX4,1557 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__concepts/predicate.h,sha256=ouqA5piYQ1tp1xV73NJl7bwRdWqnOIvYyB2T1ALf7AI,1555 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__concepts/regular.h,sha256=D8-CuavILZ3kxhnEjQICyaTmOd6Y4rr8w8QF-18V4QQ,1393 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__concepts/relation.h,sha256=Gq5_TeIxzFxjVBSd9LRU5QYyQYeWtY3mxzD5SVwopMw,2078 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__concepts/same_as.h,sha256=Pmz8hYvON11vJS05dlD1syUd5HRI5oJQIt14mM5q_88,1170 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__concepts/semiregular.h,sha256=CMRyRvOyPA1ishgIIgz9ZIfwG2j-oGc0PVdyvRjHb2U,1410 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__concepts/swappable.h,sha256=jmvypXN4dGPDfCfQjGMTGJ-PLhfz345JivN-nFzdhbE,8299 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__concepts/totally_ordered.h,sha256=gy3xYZlSm6DwkD7OXclS0Eb3ajr2PMF6wMl1SRgfySw,3667 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__config,sha256=dqssMQbyUE-aJKGJzyk3Z-VR3OMnjPCSdbRM91XaK1c,84506 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__config_site.in,sha256=uivMI6bneOUoDkcyxFvshAURC_AjkzQnc2dLVl9IRtc,1532 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__cuda/atomic.h,sha256=L5bdSCvZDkvg_cAcuwqZWeQ5zM7lC3RXzp1G_CMeMaE,10288 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__cuda/atomic_prelude.h,sha256=kRT5TCUc9BAU4JQN006cFheJAVwG5EDvfmSWwDFWGLA,2121 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__cuda/barrier.h,sha256=QA6HnC7V_7OJhM5er3dKoScIhsJ0GXJJqr3sLmRfS1w,35891 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__cuda/chrono.h,sha256=KJlTI3oBhjOVb5B4pH9H1j_aYbGwSyhwLQw6V71UO5U,1783 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__cuda/climits_prelude.h,sha256=fIpu3f6en7VVqYZnuhEQkv6yEkFQjPqhOjVeSzskH7M,3591 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__cuda/cstddef_prelude.h,sha256=AT9YxWDBhtQO2hmoVxs6-us8xoOcTKbiOY4wkn7N9Ro,1046 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__cuda/cstdint_prelude.h,sha256=g_cPkrJJ1egmEPtuyGbc8YxAFkMxKKUb-pcc2i5_LOo,2973 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__cuda/latch.h,sha256=P7MyKbb20Kjc1v_N2Z4AsS4aSrDK1F-sagJXG2yZifM,1005 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__cuda/semaphore.h,sha256=Ewn0dk5cvOxYEzkz-j08oGncFE2oWWfopYnnx37OckQ,1562 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__debug,sha256=n3ksif8LdMu8pTZY9roeYbh9mm-pjwmqSJDZyQbc7OM,7959 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__errc,sha256=oIpDvj2frI3QG62WLtxVMYIhd12qvbGeTDtpRk3OLnA,9276 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__expected/bad_expected_access.h,sha256=oyvVgwN8ybxPeSln6iJv9Ad0Z17tN95D5whJBWRXY0E,2593 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__expected/expected.h,sha256=qTqy5ji7FsGsZOm6Z8MhtYmexow0bMDjMpEiyxdXLgc,81020 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__expected/expected_base.h,sha256=FzeamodvOFeZXVFuVPSdnCajzCBmB4R8qsOHJZfxl0A,46976 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__expected/unexpect.h,sha256=Dai3JGBfbaov0Uporqbq_Fg8enmalAv5S4QtpcVVzxU,973 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__expected/unexpected.h,sha256=FeFDfQbRa_qFwMtdg5GlMEt2_rgHyQQw2onUzGCrJ3M,6287 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__functional/binary_function.h,sha256=XcECiDTLmNhpBF-PE7oVfZyRrfDt6U0XkUWBKoF0NaM,2097 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__functional/binary_negate.h,sha256=Nf7gNbZ7AZOzJIstFUAZiIu0tV142QZTyjkKRMmlguw,2049 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__functional/bind.h,sha256=cakVnlhimHrbsOxGgEnPA3Fg2FQVmFooUkTyiKHQh48,13436 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__functional/bind_back.h,sha256=dTCRQXss4l78RH8mv4CECx4KtGbMhZijdAUkqtZKegM,3449 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__functional/bind_front.h,sha256=DxeiD5EFwQIDQGcH-wjjQ8CcyI_46WavWYoAUVS90Ls,3072 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__functional/binder1st.h,sha256=NyZlJpgTVJ8uAU88NAOVdV_6SG-ZluuRJeyQZOuccpc,2228 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__functional/binder2nd.h,sha256=XVHalupUpPZPI-CRbUxeLauBXtIv6IGiLTq_JGYvlTM,2207 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__functional/compose.h,sha256=sqbEZr1doCbrz9RtlLlek962r1qzijVDU0gDEb-pHUE,2484 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__functional/default_searcher.h,sha256=QLbTAGGlaLjJw6tAHEw6r6Qla8ot40nr9NFppyVKNgo,5718 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__functional/function.h,sha256=SHkQtGIPBB7foZbP-BVl8n7aOx4bePYsKXyCzrAOCGQ,39611 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__functional/hash.h,sha256=bOlK86f5VFkRzybXsxQ6p1prttptPDA8XwR93HWJJkk,20163 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__functional/identity.h,sha256=YWHNzD-uCFF-75Q8--R2ZtYFhfLBNVh_Vea4Z9jntCo,1418 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__functional/invoke.h,sha256=oqkXKIHiu3UR2cS2IbC4CKocJW6eMBqjn84rivBGn5I,19304 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__functional/is_transparent.h,sha256=NXy5ezqcmlg7z6i1R5lf-5tGLGvOSlzFhyPqMN2KwSg,1163 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__functional/mem_fn.h,sha256=56y4CihnolpZpGlYW3WWzq0AVBtJ5jYvOjBzzCdD0MA,1751 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__functional/mem_fun_ref.h,sha256=Gv1h9X68JsbOHYtOaPQGSPtf9xIzdBUXRrHq9n5ZulE,6105 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__functional/not_fn.h,sha256=u99fF9Wc1MPcKhawir8dkHBuaw8SCwCTQe0WkZdg8gw,2509 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__functional/operations.h,sha256=HN5bjWJ5LwWHqXDSuqo9qluMBtrYiqxELjWAqCT5rHM,20602 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__functional/perfect_forward.h,sha256=t7PEuCGRwSwXsXWW9g6qLnqMYsRGjWBY3wXk2aFBXoI,5464 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__functional/pointer_to_binary_function.h,sha256=94OTAzb0cgQKsqUFNDYM-5-i8tKtIdrq9dSaK8wnpjg,1762 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__functional/pointer_to_unary_function.h,sha256=Ncnoou1Bo4Y5cyNUWhMskEAqWyNEB0ViBRQ2_r1bQeM,1745 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__functional/reference_wrapper.h,sha256=jNuofba0thKnr7aCNYalA4XG44Bs188GXoKPX5tKia0,3093 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__functional/unary_function.h,sha256=fgWdlXa-aqPOQ0mw3F5wKRz5iOoqGsVTXmMGFp42gYI,1809 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__functional/unary_negate.h,sha256=m-z4GwOUjBApUfDAYa_GC1ucEVVWz_ZUEtUHxpzBvWA,1851 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__functional/unwrap_ref.h,sha256=9RXe7pa9LDGxyGA1kJAmF4eA4lWB4cLLEY2L4v_VFXA,1695 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__functional/weak_result_type.h,sha256=sFn5ZmjtYhs34tHvE6uwZTPm9QGMKeQlB7p55FBo2-A,8734 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__functional_03,sha256=aoZ3jdQ7RDQVzo03t5CmZ4ZFGF3X06UkJGBBEcodfR4,44955 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__functional_base,sha256=aBP3VpiathgFl-soJ1sOlFTtrI-h9hg04qQwcEal8wk,4445 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__functional_base_03,sha256=XykdB89ANwTj2FUDQWgcOiwMihZJhCBj_PczgVv3bhw,6705 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__fwd/array.h,sha256=ufPI6ZUmaKiIpJGQicrNlpreE9J8sTaXkOrTGGfVQsI,867 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__fwd/get.h,sha256=AGOI65c4m6aXwR1ZNpkHPNVUUV97MVUHUYPd0ubURok,3303 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__fwd/hash.h,sha256=mgyaKjntJ0igV4IZBsUf5kW4Uo2e6y00aweSGjBWXtc,822 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__fwd/memory_resource.h,sha256=9ahyYIu5i8fmeX6yUB0amG9oI0D8JurRUlg74KuoD4E,919 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__fwd/pair.h,sha256=WFc-Utp4aQYhMqiK5l3nkSiBf43YcxZhp7F5QOUDXH0,829 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__fwd/span.h,sha256=9ETAUy1sz7tQa8bzpyNgMBsOLZrnLTyPCAGNYlJlsIw,995 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__fwd/string.h,sha256=NC2odfXOEZgBb4sHcXBSL0TV7oiDQ2YsoZ7n_9O5jVo,3041 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__fwd/string_view.h,sha256=ifmLMSBFtaObBGvtYVt_5MO5QYwi-GyRd8VH3xdho7M,1725 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__fwd/tuple.h,sha256=Mhsm7nRIeq1KfsPveSHliv9_sM8YHuzt7gCnkN4J5BM,894 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__hash_table,sha256=oV3Mic4N79BssQEb56xcsCNmFWMdNLH0f6DcSO9mD6Q,106223 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__iterator/access.h,sha256=sSe87PN4YLljv9SDSyxyUX7JJZDAcU3U0Jn4wJTI57g,2806 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__iterator/advance.h,sha256=5W8iIvfXjbZKJENjDKkEvxZ-YAIH8BmZX7JLJdPvor4,2233 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__iterator/back_insert_iterator.h,sha256=FqAQ_QTd8Shm5rGBHYiwHZAxCvhO0j69MzljFs-Yw4s,2490 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__iterator/concepts.h,sha256=28w4tYyrwuLuZlmrXmK5Y2FlRPG081x_8YcXsSS6VU4,27193 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__iterator/data.h,sha256=acqvi-vj6WtC39gWLIlDpQ2HgsddCL9DMUqJ5heygCg,1540 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__iterator/default_sentinel.h,sha256=2NF6v4sCZwmZJr0iaNKM2_jJvuN3-oGYSsdCcRwg9jc,988 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__iterator/distance.h,sha256=g-h5RcPty9TQ72UNT_uZx2ov1zdoYorXwXbN_JNcVUM,1787 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__iterator/empty.h,sha256=pdFIw2PSWPxXwtauO5lwP5UtyMjCnCfCQqz1Huj7Z4I,1489 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__iterator/erase_if_container.h,sha256=tslW5BDSTRC184y2jEZAEkz40IyFr-nt16C65NWryeo,1337 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__iterator/front_insert_iterator.h,sha256=nst7s5-wAKasTgm6MOv2vPaZliKKMM4AS4xVquh5FsQ,2505 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__iterator/incrementable_traits.h,sha256=nmhaGVI3WomkiloHV_siDBIGgraOox8CodsfqbwTgO0,5294 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__iterator/insert_iterator.h,sha256=u4UAeIkRpiOvmABbjXKmlCN3jrHcUGGd8ZplTtMw0YI,2595 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__iterator/istream_iterator.h,sha256=FlvuVMMIwZQfhQw5PPKAENFNK6ZapGrAZidUiP9o60U,3551 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__iterator/istreambuf_iterator.h,sha256=jvbNXuWqOxJmn-cOP7VEh0vDEkL8ijRud-jYydRc7iY,3757 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__iterator/iter_move.h,sha256=CHx245a8hVLTV_wAQJ7JZLB8r5UAH2WhzWLTjYQejrc,5340 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__iterator/iterator.h,sha256=tVL3NpfmK_XURFPxMLp5bB-A6HXuAm6rdmRH117Xx3I,1218 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__iterator/iterator_traits.h,sha256=JuFS44CPIfWx9UvzhXL7qwl1_KN8NmH4c5NlpXK-DYY,31747 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__iterator/move_iterator.h,sha256=xGsS2GS1QJFlGHWvR5Eu_Ax1JBDyl1byPlG_1wbOFxM,6437 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__iterator/next.h,sha256=VIA_iqTgI5B7YkSt9aCxWf76XN4k-ndiXLUwp3MsX4g,1431 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__iterator/ostream_iterator.h,sha256=iTUtTwVuPIIC2Z0jLgJVziiU4TSXObNIcXgAegGZdYE,2383 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__iterator/ostreambuf_iterator.h,sha256=R2Ey9lgIH0a5HB7HbrMPq1-8UBVyx2q1Ixu9Ztwziqg,2698 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__iterator/prev.h,sha256=wWzkSZGExBMV6EBIewwiqmZHkRPOTyq1PboC2-Y-db8,1431 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__iterator/readable_traits.h,sha256=r7J6ZDuScCVCsme6ROnfUh_elfkVc7Kpag7nkWo_ZPU,6144 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__iterator/reverse_access.h,sha256=JbZuabYCuPkmom60F3W5puoRVuV5ui8tL8HDtI-KHs0,2834 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__iterator/reverse_iterator.h,sha256=a-uXtWUVSlwGXjsJLvSKnR19HsTeT1wO8Ir9heGRK_g,7422 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__iterator/size.h,sha256=Y-hlvVSR0JhSOke9D_1ed4m0dfDxVQ0wocecU0NsgWE,2260 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__iterator/wrap_iter.h,sha256=LaIaYkhTDTi57nRhkGhKBBWkfoVTYMZi6_qYhFQ5IbA,15794 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__libcpp_version,sha256=h24T9OB7s5cFMCwB9EX_0tLDsYCiB-TZWda2ccZ9oJs,6 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__locale,sha256=Vej_w2yF9ejVVH3yILlZ-T0xsmgEs3svmHLGEYng_6k,49720 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__mdspan/compressed_pair.h,sha256=-Zcdh3fUYH6Yc91L5-ckNWUy1TLnAzrdqyGZl5yEdCg,9719 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__mdspan/config.h,sha256=ejHIRZGZd6pojUvHpyFl6j57DcyWbhncpso9tIUxwng,10243 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__mdspan/default_accessor.h,sha256=3EQLkIfgu88y5OFoHK09hrdtE3AJgVn_l4ejWUe2qXw,3367 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__mdspan/dynamic_extent.h,sha256=tAPu8RBPd7I81p8MHKy5sWXA2rCl8qlZ3StRr-ZXd4k,2903 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__mdspan/extents.h,sha256=mP0NKCXKjsWYsiePCa2IGuK5vDFhZGvZFB7xICPd3QY,20598 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__mdspan/full_extent_t.h,sha256=nm1ung403pFHuxyop6uCevckaWSiLVtNpliDlF4k65U,2559 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__mdspan/layout_left.h,sha256=4eHFHXh2ya6rZhopqBzr-qOgMRqKWXO2N-d9UeMUgqI,10129 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__mdspan/layout_right.h,sha256=uW1xVJO4A1tt6gpUxkjqGv1SDF0kA6uSbeYJ8kDG6hc,10447 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__mdspan/layout_stride.h,sha256=gFAP5Rt5COBuIIvBOSh8hquuEx-9ZAUNcu1gZFYW318,21759 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__mdspan/macros.h,sha256=FFZ5Yxo7qtC2-v2wB_g1Fh9TYryKqOyexrOWPAk26bw,24931 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__mdspan/maybe_static_value.h,sha256=dG97rMBQAVXA3tnRQNHQxPqpVqPvm37fOZQAooOuGUc,6176 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__mdspan/mdspan.h,sha256=42CGrrbRuAQmU4gOY2byjIeFg9CvMiLu1gCxJKPQ5Y0,20990 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__mdspan/no_unique_address.h,sha256=AdMYGKDMsLHRglzzz5UY2wiXIg26zMmu5lvcH9c2r2w,5761 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__mdspan/standard_layout_static_array.h,sha256=nzukeXYtDpHAQ4Q8O0venwojLRqrWMY3rMdeDgKXf9w,27523 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__mdspan/static_array.h,sha256=9eYclW77qvzDT3ltQObU2NS053S1DM7DLWH7jRE5st4,12360 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__mdspan/submdspan.h,sha256=LS6x0YWA9WvrPt5FPMoxfPcP0oRaS7LGWWIENvNyLDE,24272 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__mdspan/type_list.h,sha256=XRR0JQ7fQ5z1JwdnH1CnhaSn3XHc2GnjTF28Ddm16dM,4520 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__memory/addressof.h,sha256=OPFP-CaIbbAtV9Wi9JPvlgi5DZluEW6YZQf6Ji4iWlg,2459 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__memory/construct_at.h,sha256=_Eo7KHXbRZQjgXbWaDJtzRYRfUsEfDwf1q7YODnatgc,8944 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__memory/pointer_traits.h,sha256=03BYDVYIwXkQaO62Ms33XYbq6lP2TJL2gGp0zLUq7Vg,12174 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__memory/voidify.h,sha256=vBuPqewpMvACx27LWCZijWCdRUFH9QmCbRm2fuhfM7M,1144 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__mutex_base,sha256=YG8hGAm2IYhGzPR7-rLIaUcvb7BoVfbrjKhAfw9EnsM,17088 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__node_handle,sha256=uDYaTWd-KOu--_3faKsbKCgaf8vZsC9We55iYbvMJ9g,6312 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__nullptr,sha256=qJ1TcX2CaGeQjHYKdIUI-83vLxw170S115pn2igfTKY,1839 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__pragma_pop,sha256=CBqsoTsOO_BHSvlzgKLrmn76-Ox2KYSwHkqiJWJ2OHc,533 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__pragma_push,sha256=JYB_3P2juoJXts-lCjlLcjsHGy6Lj93Q3nzbJ4l5ozg,745 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__split_buffer,sha256=gYCfwdbcPPxxUA5_vU8c9Re_L1zoTiHvNcr--0kto-I,22956 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__sso_allocator,sha256=p_N2zpxYqUZV9m1yVvBBrkIFdugevGaWzOIbRMzOb90,2638 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__std_stream,sha256=D0qFV2bnTffBfKoOquJmwGlRegvXBsDU6XBkHPWlxKA,10638 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__string,sha256=I681ctZr6Y1dIjr1RHetuAj6LO53oHEYvYAKthx1V_Y,32258 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__threading_support,sha256=94Tyg889pzOhKWdkkZWE-hz6t8BOEhMUJ5Z8egMZqcM,22521 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__tree,sha256=AwtJ7fwF9DJlll0yxp1XlB_LFONF-p0uF5YO4YDBpYc,105800 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__tuple_dir/apply_cv.h,sha256=iT6OVf0YZMywKLbvLk8ocloYTyo0fxUlM1G38vQK_kU,2393 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__tuple_dir/make_tuple_types.h,sha256=bkpgwzBd9cYXkXOtweQO8HqH9oTEeAS1UUkxcMowVwI,3265 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__tuple_dir/sfinae_helpers.h,sha256=jzIRXtugNPc8Y8k7E10hRxR-28D2EOYt2dTaRmBQO0w,7608 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__tuple_dir/structured_bindings.h,sha256=FEgnlSwKudjhxIcTWJ5sTaW0bPySSKeM0TK0aE4sSfw,6207 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__tuple_dir/tuple_element.h,sha256=QnmonWnsTp-9NvURp76x6ziAZvjCClv4u_t9Z9vXpqA,3885 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__tuple_dir/tuple_indices.h,sha256=usDn0X4LKAFjJeIX-gTU-jyZ5r3tNWD3dIqKj8HTPIw,1134 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__tuple_dir/tuple_like.h,sha256=ZPzIFWrKJHjjxJfn49yXwnQQ-ccO0vZWNzcBUyUpBK0,1685 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__tuple_dir/tuple_size.h,sha256=w4qJrpwUGUtQSattQ5EM-vZs7TDUthS_kDIXKBuln1E,2722 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__tuple_dir/tuple_types.h,sha256=_iAz1mlUUcI_mLp58wubemgOvWHYRwaaFAEm933B6Lo,845 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/add_const.h,sha256=E4We2WDiEeEVK82tKi7pCATC7lX-bEoUQ5ZsxbvNTxM,1036 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/add_cv.h,sha256=oxoVZClnWdhxgybsNYAAo-p88aghHgYeb65RmurjpYs,1027 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/add_lvalue_reference.h,sha256=SBSP27Sy45sKa3Jcz2tdAhfNGZJjW0PwyJ9V6yk8M3o,1829 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/add_pointer.h,sha256=WCHqghAwEPqG2FLGshnDojVG30I8nXpY0gBz5p9AZFI,1900 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/add_rvalue_reference.h,sha256=OnLXyHhAzF-np8Ig1d1IdaYzZ1iTnUlJWORiCtr4wIk,1805 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/add_volatile.h,sha256=Sbjd2WbptTn-a7g5t7-VaPu4wbT-WQNniMja3QfQPCY,1057 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/aligned_storage.h,sha256=Vdn1GupHV2AInwKN02w8IXhjIIIK_SPnh7wGa4HyxLg,4551 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/aligned_union.h,sha256=QKCPlwN9reNJwZL6G2LPd2UViGN6DT1uVyXj9hhUxXY,1977 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/alignment_of.h,sha256=EaEI9wa910p2PJIyaj9mHgL7pK5LyxdCMVAF1krxisU,1215 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/apply_cv.h,sha256=68vLf5-mk-7dgu0j4AXTgjZBTdCXK_EXUnZf-B3c24Q,2007 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/can_extract_key.h,sha256=nJ1bpxee0QQNrorbLYKODI_0zTnW6L6qyxfViBlmjUg,2340 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/common_reference.h,sha256=lnYbbBQGkEOHerYzRXasKTKqQqZtzRxto_tRm91_Xc4,9109 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/common_type.h,sha256=uSV1iXo3zWqZeMNvN_Ld8Nr851UXIG3tmKSxdQhSUIE,3936 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/conditional.h,sha256=drMeNWHLKfAVg590N08plz-spyuHsihHmPTvr6meUlo,1842 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/conjunction.h,sha256=5v15LXRH3FWHMlFsChBl3n-4OqU3ChNUXDshtXe202M,2086 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/copy_cv.h,sha256=cMQQe216AK3ciZsKCMLiJZzuaqu4ood6hi4qkrqK2LI,1579 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/copy_cvref.h,sha256=LGNfEc6Wom8Gs95A8ZTkCmmLydwVWbc8Fk9btyDTm8A,1437 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/decay.h,sha256=AVPtNeadgSy0pvCQtkA0U5MKvEEiY4VQZCF6UZflzHM,2478 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/dependent_type.h,sha256=Ji-9Ymn0s6VLMF7FzIylz2-lt3Rst4kM17DdcTyxF1o,916 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/disjunction.h,sha256=4pznRHFG_vTYoYzWd7CgLJtccoa_KgtczEdal5lcMWQ,2256 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/enable_if.h,sha256=S066aPm5Dm6H1oIX7ks8nxN-_SSav1cU_YrDpDNAU0s,1236 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/extent.h,sha256=kbd0MDiO2adS4Z-QQ5_4ISEczxwwNAa_gu3FgMkIcjg,2334 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/has_unique_object_representation.h,sha256=lsUmpJ__8_4nAxK5mSi_g24r0I5B2hgmWeAsgZUZ11Y,1527 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/has_virtual_destructor.h,sha256=JUH8UZPILCSpz6_ibGv-OU1uWBG0KcA7xebXHdiP2rs,1606 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/integral_constant.h,sha256=_u1jdnsJS1LqTJuTtYA9jh2t16rEkK1xXloVlrOjzE8,1879 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_abstract.h,sha256=XOjxLF3hFIKQLFT_RO6QKodc8y0nkOr7bWh1wJrfOQs,1172 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_aggregate.h,sha256=6cqLPrxYNDm5ckvi961bfX9ePhHp-ydvqo3_JU4Ui_s,1307 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_allocator.h,sha256=onQ_pihCzVe7EbnD1C-tzfV8nRIf19p4mH0oucxT-6A,1244 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_arithmetic.h,sha256=6suT3Z_4OXi2SREAT-PVyz1xvxuja7U-KJRx7BoSE7s,1359 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_array.h,sha256=1NTq6WDiyDEib2k7QQg9vjhWoMPiUxwhtYJ64Rsgx7g,1993 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_assignable.h,sha256=87Bcqd0ScF19Ad3yxSYa66oUAlo48C5OM-nT6MZOr1E,2515 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_base_of.h,sha256=gtXZ9zO8_zXib0hJqd0dTqYXpbrtwcJNhgY7A6LbMj0,2366 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_bounded_array.h,sha256=W1aCU5PbcYHDF6A6qcGQY5kuzYDppof0zG8JP16Mktw,1503 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_callable.h,sha256=agmMBmBec3-oIkXG9hhCDnIj2CpoIuopbtgHo1DxI4g,1273 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_char_like_type.h,sha256=0OR07bP-H9qG9Ymi4BFxf6_DV45CfrtdkoyxSVmDQfE,1068 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_class.h,sha256=57tlm1oMHNrtqjtLZXUZn5MtTkGQgCpbcQADtnvlfao,1891 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_compound.h,sha256=vZcPAAVzb3YOedEkp0HSqFFwiVRBJZqkflPyaW8QSWs,1753 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_const.h,sha256=7HouPxV6TTF-ZQdbs2r4co5jxL6RbjrRJSFqgXUegRA,1728 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_constant_evaluated.h,sha256=cyJ3DtMTKmMs3hDYYOOAoa_qxdUVnfqUxxzpHlKozFk,1458 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_constructible.h,sha256=h1lkJMBhTCsiptaIBdo4A2iVKHNpuhSJ8ugfEc-D2AU,6480 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_convertible.h,sha256=IDTrzCKENlge2kD-qNjYaP44gA497f6zoSuLl0fFtm0,6386 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_copy_assignable.h,sha256=C_XtBsv3lJG8SYYUS-mN3jfkw1c7GEzc7ljvgg7Y-QA,1391 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_copy_constructible.h,sha256=dcTq9EiD_YEtt57d0H6WxK1rzqxZ7H47yqimdqJvSRM,1362 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_core_convertible.h,sha256=O8YDmCGeLFY45ONI-5PBavgj4pxuF_MJqzwpOBRWAjs,1484 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_default_constructible.h,sha256=0KSMR6tuFq6bnjGJyzEFz9QtuUuR-w-gD3VxxJ71m4g,1227 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_destructible.h,sha256=dKOUviumZM_rBvX5isaBM8bzWQO8SUrop9u5YwmTnxY,3361 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_empty.h,sha256=sVvpsHHvvWf2tMXwWCMsABZqLXKPOd2k1re4Qv6Y84o,1987 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_enum.h,sha256=ce1-CHrOvnfty-tzJ83NDFK_9Hh-Zp17zdvhe3MM6RA,2735 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_final.h,sha256=LnTHan4L8hjAhJHWWLcT7DJfApDI2pKIE6bPEUIzl4Y,1809 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_floating_point.h,sha256=A78VqRQWYX7IbE000LPSaH1J8eng0agRMqDaVDSWuPU,1623 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_function.h,sha256=utuB3VjjDcpuHiQ_Md8QmoWvFpd99M6KbKFPbCiV-pg,1812 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_fundamental.h,sha256=kXxaDAo6b79QWWRGaoekBfai-Si33c1kAkq6_Fuf_e4,1966 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_implicitly_default_constructible.h,sha256=sqnr0x7uU6lrML7FwTOTJVq5bZdgFduUIajctH-jEOE,1881 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_integral.h,sha256=rZVgBnnHIsGmym4yVzSfEzZDVpQL8BByy3cPAAEFixE,3692 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_literal_type.h,sha256=RHCF6lQ6YL6JdFMrQZ1yB7Wnok9l9xY0EzRDWYT4i3A,2090 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_member_function_pointer.h,sha256=ehlHFnjR8vIMcLS25_oDj0BZw3PaZhtvo0Qr1rG_sxI,2391 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_member_object_pointer.h,sha256=1i5vxew9-X8GKnIfrM_LgiEVJ2cIRgsey8vcMW_oAD0,2024 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_member_pointer.h,sha256=8Lpk1b6p9ZcGYuWJhHktTmYvqoLNjfGBW_4qUsAKdGY,1927 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_move_assignable.h,sha256=Kb5x93AB3bbhBsFEZbRrXmLzZQpmdQ6I5wMbrUrLnAc,1349 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_move_constructible.h,sha256=EVlpQGobeZ6dGBis5Rd1HCZ4Eux1Txk2X-cIbHMjZHg,1348 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_nothrow_assignable.h,sha256=I-oL6Pb3u5eOmlMDK2PH__tPtoyWN22NmCXVjoNVq00,4615 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_nothrow_constructible.h,sha256=aL__XVnICzW3Bc_Rxtf4-CERb5YlKqK-R0xrngT2ZOQ,5276 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_nothrow_convertible.h,sha256=UaUiVeX9c0LJSYs66BQ3XDwo8Arr12EIvUxvEzPt_hM,1982 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_nothrow_copy_assignable.h,sha256=NTIuqRrh5zu85RJKpQOXFAj8Tp5a09SAHcAz6QiwHnE,2249 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_nothrow_copy_constructible.h,sha256=ODiGv9fukzqv_3M7MR6CqPH4bLYZhm3D-hhIHcfVj-U,1430 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_nothrow_default_constructible.h,sha256=aYpe-rsGA0Pd9N0-J0kEf-fN9S0osc-R3CB-ExIyD58,1967 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_nothrow_destructible.h,sha256=Y4WhoL7fCiZlWZEnTAoraHgt9VyrvL6_kJH2vbwY2tc,3112 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_nothrow_move_assignable.h,sha256=jA3za6M9cP-ObFCpx3nTu83lZ26204ZxTDxA_U6Kdmc,2148 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_nothrow_move_constructible.h,sha256=hM_aQIPLq-dt7HXh_he-vJIRhnexFSgq-CEIjgnLNHI,1368 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_null_pointer.h,sha256=TVQg61yfZhf4qXYwU_vMMVLewmzaUpwnUZyr_tF-q3w,1612 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_object.h,sha256=SEf0ucEljfGOto4euPx1UUaxmyDK3JaIIBOOwMISLkQ,2018 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_pod.h,sha256=v_eZZsy0PduNx4yUNnHniZWeyXvrfvfb2eZLnDTorQY,2175 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_pointer.h,sha256=AFMG71h73NtoV5t6_2L2w6Vrs7PzIEdV9BFHnBvoJO8,2459 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_polymorphic.h,sha256=vsKq00JMNfPC8lljfLKIv32SpbE52zB4FVekMSxpLbg,2022 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_primary_template.h,sha256=wKtb7ySqe0IStJ-Csx4gVcVxu7eMY8-LhzAHti0GzdQ,1647 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_reference.h,sha256=A4Q4uaSAlxfv2P5EBJL9FUcOXVNOPTYKs5WD-FGa2zI,3255 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_reference_wrapper.h,sha256=tRW3p8USzhHT4z9SzfIoaMhCu5MHtFpBBZz2j488X6o,1292 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_referenceable.h,sha256=As0lSp9TyzVPP2Su5Y4WjmwgGbubMdmJOgNsgau_hN8,1642 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_same.h,sha256=KBDGGWL6KqIfboPa5TcvLOr4TiOTfarep5jkDqgxqUI,2961 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_scalar.h,sha256=YOpVO9zjwWEzxKaRlqRVuCeeAFhwU2NcVnpQHtLMyu4,2561 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_scoped_enum.h,sha256=0flSzBAMcWQrZrLps9KGpwf4GioB8yQE3EFpoCwc5LU,1481 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_signed.h,sha256=24O3ZiCkJ_iFTW-TWvBcWyKFWxb0GertkK30QuSySlo,2138 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_signed_integer.h,sha256=CLBm_OS1dJzkonxPz0slPAhd8D7VHhIq45fRUl9aPhc,1523 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_standard_layout.h,sha256=TJtQEaF96L3sZrD3rU2IomPl0pg-VUtLgLUEILAuM8c,1875 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_swappable.h,sha256=tQAl_iR3Oiso2sT-fQMv94rWbUcVEocxRMr7SJIxOvg,5354 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_trivial.h,sha256=N_lTfMHDZvnX1DVKgFETlwNuiii7byMcXlsC4P1nkaE,1913 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_trivially_assignable.h,sha256=eYQpkJ1bOyTv8ZHgY0bprjKQqq3_pv4eJwnp0nS_vFY,2379 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_trivially_constructible.h,sha256=QeC5VHPZ7Ec4DhqWSSnYlmcPUnR44nTIsmBSgYNTEAQ,2919 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_trivially_copy_assignable.h,sha256=Th5aXUQIJgVEkMw4hvjQ1snGn0uPvvY4r3GIRr-3Ess,2335 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_trivially_copy_constructible.h,sha256=482-_NYDkgdIKdtLVoS4n1kEfgQoz4Iei84SsCFPsJA,2225 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_trivially_copyable.h,sha256=-JHvKBz0EDsjL6f4Rnrzbu60xQ1Z9iBxSxXN6U2fnr4,1962 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_trivially_default_constructible.h,sha256=0PQd5tWcqgbS1G_-vf-lWT6kG7m2onDJtwjW64db6jU,1979 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_trivially_destructible.h,sha256=3IgGenfoZj-luN8zQNofLjEwCU0f0CFb0g7_pGqN_h0,2462 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_trivially_move_assignable.h,sha256=uX9DEgW9TjSMv6rAkBBkq50t0LbHDHGK-ZpgKTk0oLk,2163 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_trivially_move_constructible.h,sha256=Z4WD1Iy1gD2-4qWDDEgYrHMnmcKij6MCHAN4c9N0O4A,2107 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_unbounded_array.h,sha256=rCOTRuAq-rzkrIgvlbCx7BefitqnK7OI1-zGKuCTbCg,1438 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_union.h,sha256=gqhpbvM5p9bRjFWPASCIVmj3ypUC4MJCfS_0R2TfEog,1752 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_unsigned.h,sha256=uOCD6JW0FPRaLzk_fpCV1ql1KSlCsRT3at-fQlqrwHc,2394 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_unsigned_integer.h,sha256=OeW2ELwbd5UPTgKbixY5udX_P74MmjhmBd8DPQnLx1c,1555 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_valid_expansion.h,sha256=NUObjGwwcrPfWdSsk1Kh8Z2ImOt2KEfz_Ks2DHCo01Q,1326 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_void.h,sha256=LCDwMnh3pEfdNYVjbm2M4T1RdbodUzXV8qwytsBeEd4,1698 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/is_volatile.h,sha256=SgzpdtPjHqoU7-8D_GAwJlIt5BzyK43OJ3hYpu6TXgg,1781 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/lazy.h,sha256=IbH537TsoUTceSHUKuNGzg64BQgaGb8Uujzg4Yt9ZNM,887 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/make_32_64_or_128_bit.h,sha256=1Qq7N55COSa7d3km1cG-OuYzeVkW-jU6Catzd1BOfE4,1794 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/make_const_lvalue_ref.h,sha256=rsen81Mp_a9GohUckrIberZ0pz-hk22rgD3YFrb70TM,985 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/make_signed.h,sha256=aS8J5I82jKcfPfGfmZRTqryCEUWVfHNjjMettLOXUfc,3250 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/make_unsigned.h,sha256=LTNdTFFUnc0GyeCVY0RsInOX1gwSqg8HAg2K2aybWCw,3889 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/maybe_const.h,sha256=kJdEIyALCn-5RteTtwlIrCSSvegRp4nxHct2i56hqRY,953 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/nat.h,sha256=FerZOi3GfRJY50EF6fYO_2Svdj4MBGzszLgexVMTJz0,970 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/negation.h,sha256=K_vWpW7-AqkUBdgLCHBBAmDC8AuOFgCsHwip-jyZUK0,1126 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/promote.h,sha256=S2Kro62NezHFRdYSdmyH33AMLLbCCAkh0N17saoxmVg,3111 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/rank.h,sha256=_8KvgpwvTTQNLCsBwm6w5nIcBuzLjsiX0bnJi7p3Vyg,1891 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/remove_all_extents.h,sha256=EgSFIAHi28C1mIqDLnvRB7DNG9YSCNnh2PN1kE5vWJY,1893 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/remove_const.h,sha256=0qppi3JeGMDJQdPI9C9QOADVHziegimjY31WxTFBVao,1586 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/remove_const_ref.h,sha256=n3_27AYO2-LM91QvWk4d_B8bCsECQzXAeK0f1-Uzn18,1023 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/remove_cv.h,sha256=zzGIWEFjQXhzNLoJzTznnxJcC7ebBMaw3jjC4ignqwc,1573 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/remove_cvref.h,sha256=Zyfy7rqHil15knNAz7CJSmaKo4v2-f8jnjrcxQnDET0,1723 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/remove_extent.h,sha256=B_-M9vlc4vCZXXgXAeqHC1YnC77LElOznp6zyp7_E1k,1732 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/remove_pointer.h,sha256=RyY0dQGUKTrpV87rPQYMoTQE-vJ2_wV3hM2AnqdzmGs,2094 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/remove_reference.h,sha256=FZ6CG18p6f578JWVhuQcpsjrXbkmP1KZoYomvFAuznQ,1875 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/remove_volatile.h,sha256=_I_7UBviGJGxbkGizXANU6zYwwXL5v8Uzruho75VflA,1642 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/result_of.h,sha256=WZ0FwJh9DNY5cH6aKIU0wAYhgh7soidZH49G2WCwljc,1423 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/type_identity.h,sha256=hKQOdXFK_CcKJ49EvQEuTScI-5RlbyB3xS6a_56GVXU,1177 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/type_list.h,sha256=-oC6PQ32lvxZzRhYB-VegVD49kd317eYvE4jtq2Etro,1394 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/underlying_type.h,sha256=fjJz3_yqd-cGGTrJiX1aTvB62flc1MOulBIwR-YYj6U,1847 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__type_traits/void_t.h,sha256=NIxWIaTgHol4ptMJua4ymoCROj2iSL8nNiUpihmaftg,920 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__undef_macros,sha256=UR6fxqDFxLn6TuZTtux6EI0ODZf9vCwrzv63rpEGR_M,1071 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__utility/as_const.h,sha256=njjLBf2lmQ06t7OuFUsJJ_W-NX6OFIFg3v1dfYAvE3M,1078 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__utility/auto_cast.h,sha256=0xBDjcKasOs1wHPpErCo0GnPrHmMjJn2E7wQE8JhVtY,877 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__utility/cmp.h,sha256=UP3SmtJw_lruoVs4zwKMEvNnUJfrqEAoGtoAC2oQWFY,3620 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__utility/convert_to_integral.h,sha256=BXhG1ITE27v4t9LNxN8ei7a_vyJHtO5o600YAbTRny4,2705 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__utility/declval.h,sha256=1nMhBBem9TB3TKeq_-8IadC8pnfvtT8FDWiY5Zrk8Oc,1235 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__utility/exception_guard.h,sha256=NgRtO9NAsLrNmTSfQ4QFSmSsU4QOt6hnpom5trVHLf0,6132 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__utility/exchange.h,sha256=_mlS22tF85T0H1kDMe3TZ-9N_4Rv28x2WWUCOS9rRLc,1412 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__utility/forward.h,sha256=Xr94L6OaIZMuQSAlwCKFdedIJ5zKkgO5RlM2qDftv9Q,1426 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__utility/forward_like.h,sha256=XuYpLzX0OXv6Tfj3ave0GZjQmRTYCKnjEabLU_K2_SM,1656 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__utility/in_place.h,sha256=Ng6zn0av6frE-IDfScc1GXnfN-2rcLlaiIG3f825_xI,2019 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__utility/integer_sequence.h,sha256=d-i_POiIehgq_SjgCDN8d6TtL4aq8CaGcv53xVEAfpI,6483 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__utility/move.h,sha256=IvwjmhXRKOcOJe45SzxMPPxo3eMBsd3b7gH_th1p_qM,1680 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__utility/pair.h,sha256=A0KX7zE2tUGoPQagSPLK_QlPDSOOOT9CYgc9h4LvNQo,34281 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__utility/piecewise_construct.h,sha256=kKGw0HEK-aRdTBMDJcHuyoiJPo7CqHVQP3kzVCCaqlI,1242 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__utility/priority_tag.h,sha256=UHCfyDgvoJIPA3GtwuzDp6T9muq2U53RI7wVX4veYTs,941 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__utility/rel_ops.h,sha256=H1COjJvF3vun7xXXd8ybcHRsSIKootrGzcSyl31IIcU,1438 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__utility/swap.h,sha256=BirQWPPeLv-8QFHxlCl0K7nIIDY3qV0C6EfSjY-DFlc,1836 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__utility/to_underlying.h,sha256=pMR31OfN3T9lATWFs65WPryTyyqq0P0uXQMkSM35HO4,1368 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__utility/unreachable.h,sha256=yKuH8CKCnx0-3rwAqWioRUv7W3vD2V9H_TCyJsLs51I,1072 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/__verbose_abort,sha256=o7jLbvtVYe_tyiRoGW61bz5gkKyeyls29D4sQFLS2LI,1874 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/algorithm,sha256=lJoUqpa6ugDkea8RINwFlydDB1jF-F15voB7Zkpd4RY,208002 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/any,sha256=870v3eI6ssGrfAUAHQHwdVWMtYJXhDUUl6_YKABoumk,19445 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/array,sha256=TPMlaz9cGlfu94HZ0LJRbUL3EHbqCypPfyLJ_Wny4Ac,18925 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/atomic,sha256=ZJg_RrZgcpkUPpRfgmPwzDyMc84laPId7TPzyJ6aSWU,105699 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/barrier,sha256=x-rtmBnZ6O_g_3aN7oe5dkaDwRrbVPEdh2eDv3S5oXE,15041 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/bit,sha256=kKOqQ9Cf6y73OpkuEeVlIUzM8KBgGALdMpP10rjj4yU,29854 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/bitset,sha256=3oPtI-0uZLG02HhSNhhbkF6Rn7RFOi8QBZxn_2sjnuY,34361 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/cassert,sha256=RglEOP-oeznI0vVWrN_qLVxmoptZrzXwfNF5AH9x1TM,687 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/ccomplex,sha256=3NYCkoHc4K2Wk82RoXW8-EPi6BHzkK9gzGGdt7A4omY,656 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/cctype,sha256=EOcS9_WVVvSSjGgJT5ey3UCqXwI8zhzEL-myPWtizow,1782 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/cerrno,sha256=CJ31NxpO9G1KwWaqLAH6BlCO5p8SwhJe6D3FFUxtEMg,685 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/cfenv,sha256=lz1IBbBZzW3SL-NubQBEv6BadslqWWy1IRbDBVNuhRs,1625 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/cfloat,sha256=g5WEHZnWOGQPYi2jgymfnux-wdS0ZZJcXymiGbnCyvE,1564 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/charconv,sha256=0L9CNr0im0-zb2i3TxWjdomOFManuislL6GXl3cuzcQ,18313 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/chrono,sha256=OE7ztn3yf39JWzFwJF42jS0JlphaazPVzndmzKCL170,131284 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/cinttypes,sha256=Ch7kFn9pyODliI1XuHEiGo3B6A1VznTWNlDDifOFuy4,3543 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/ciso646,sha256=9ibk-qj_dlW0YAJH9CJ2_Q_DfLfm4sBF0bGzbc4H4bc,615 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/climits,sha256=cc6sz6buTsboGLqx45aZHEZbxHSsW1ryZvJMpM4E5f0,1555 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/clocale,sha256=8J89jzHb2BcNT1n57crdX3N5foIiMKAPVTojw16TFLo,1026 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/cmath,sha256=EKwHuDQyY-p9HaoATvFAQ4Xlikiag590FVyzgdXrUZw,26063 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/codecvt,sha256=Rfxnvjdhk3V9dG1_ivjpqdKR0rbiqIf7-A_RO06-dUQ,20684 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/compare,sha256=NRKfBxSZ8Cf0ABkuT-dd0bNUo-q4CHZBe2klJmMWazo,27228 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/complex,sha256=Qt3AMMCTym1-_RtKm0Xp04b97igFklX19Fc9NwgdziM,69697 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/complex.h,sha256=wVwtYKqQH0ILXU_JF6be_NIogOARA_WkweZraEfNsXs,755 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/concepts,sha256=We7lhdHZ8gvlveO6x2pXot_GwpwOTCYm157g7bYbMFU,5156 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/condition_variable,sha256=A1r7izj95n40T69tZJr7hyKKwd_MXXdPQD92PzLSNp4,7687 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/csetjmp,sha256=FfSqIQmJJVVr0ZScEOkfPjNNHCb6Ux4C-TKYKSdn1_w,837 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/csignal,sha256=IN-YmWZS2JW4IeP10M-yXspoak8-4pxzJywB8ljmnjw,988 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/cstdarg,sha256=a4nE56X9md0Q7n8Yg7ppWr-qTAio9PXskfMkvr1BhiQ,1063 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/cstdbool,sha256=NJWT8qsrkfQ1XoskZIz7reZ1PTH2XhYi4etk3G8XGVQ,873 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/cstddef,sha256=Wy-DlcbPClrArVlwJ5FFhU_dsG5thUJO2JJipMAxwVM,4676 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/cstdint,sha256=aQrre9OJwDJzq3HoJNtAX-fb9Jyq1QTSTd-BrMNNsCY,3156 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/cstdio,sha256=R7pMPkOGN_-nQ1QF42LJ_t1Um1ifkL3GUJSambs6Efo,4365 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/cstdlib,sha256=ak32pjMdQbuPVc4At-GRfptCfzS0a4YDdi5bbfSnnbA,6293 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/cstring,sha256=xSNbcmL8cD4PFol47fGmmOXVWRogox7hTxHrOOBhKPI,2739 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/ctgmath,sha256=kF34lDEPlwjRr68Pqe22sLepzN74FNTS9h7o9zO-b4s,666 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/ctime,sha256=igbhKdRYVwJXYPIJRe55cYZnojEqxEvLU2_Rwo6xCik,2115 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/ctype.h,sha256=XiqOqrXolRKLG8sbGwsfkJAk-cgsCCuQ_qUiCIdG8d8,1165 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/cwchar,sha256=gOJNUNVhNbFK7YZAvyFMWA4bj80GmO64crTGS3Uv12U,6333 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/cwctype,sha256=l_r7OSo9Ubl6AubSeA5kOfda2xTY_6Xd1Y4zgJrDInk,1715 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/deque,sha256=o5AhtgK9v5wFJh3I7F6Ar6JBI9pd6olU5i5p9SpFZjg,110598 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/errno.h,sha256=M-KIqaKFMR12qbtAUjbLQ3euDEYxKU9s3-a70C6khEs,5160 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/exception,sha256=zfiyAo9gzxNopgsHhrEXvciTGNe5DrSKMD8HgOhsZTo,9720 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/execution,sha256=eh7Pcgfipm77fqQKUKphMQxcmBOS0SA3GOkke1D3k6A,615 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/expected,sha256=p5xMzkx2yPfwmYQwiT9L4xFJjchHgvidlI_SNMonchs,988 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/experimental/__config,sha256=9kxvjIFJQWFN7c2n0TszjuE2gsusoLHBqTx7VkVEqOo,3534 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/experimental/__memory,sha256=pNWt0q-Z9WGXImXXa7SwAEKqqkh7oQLDPhWjyaNPp2I,2778 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/experimental/algorithm,sha256=IydLn0L0mfJBA9uVa4j-Fv3MHXBNFigGq2kK_jOdrIc,1491 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/experimental/coroutine,sha256=NYL7wg9IrLyqE3XfhZJacws9SHFjiyJ9wOgWajRwWmE,10579 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/experimental/deque,sha256=kIS5SBu4dBY38BjJcycupVh9sNCl0TvfLrjAekkYq68,1179 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/experimental/filesystem,sha256=Ue5K18V5RuP5kv0vnwIk6YPts0ox6yMLp6CgzgWJwPA,9197 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/experimental/forward_list,sha256=482ER5H0FT6V2Hou6Rh6H-Q_KQei9RcxT7xpbo9P7tM,1242 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/experimental/functional,sha256=kM2X1xEYKec4_Cf1f9-3cJmreTgUYGEw5TBHvy-8qEU,18041 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/experimental/iterator,sha256=cLDd5z9b5Tt0io51_10tjYx3VT2Tv-zDa6wS3jrwg28,3955 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/experimental/list,sha256=sXF9fg8mdoSE1m8osb3IAl2bKHw1mMXLJ93r3AFs5Pw,1169 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/experimental/map,sha256=-_0vtsPiju1OzmYbIPquTqxqqfKMs_f7qyp-Yrma0sc,1739 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/experimental/memory_resource,sha256=M5_EoLneacyXpHm6Uu9SMrl3rFNbKU2v0TceRGZ1Cbo,13705 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/experimental/propagate_const,sha256=463gT5t2fdqfyPVEHX2KCyDhpwZlvI3YYBFw9EJG5QI,21121 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/experimental/regex,sha256=Pfxps3EDJLuACVMlwpXG8DXl1hU11XoRQshaWi_3ZaU,1837 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/experimental/set,sha256=8-uEwgmOx3y6qElXFXAjijmiMXjd6PbgJoz0ljD4Ok4,1670 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/experimental/simd,sha256=4YiG-QQImLFfMqt456MQv9SUewU81q0gNrmgwmbz4B4,61584 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/experimental/string,sha256=ZomeHWfM-54pZ21DJfQhWmUL1ArnctbkYjhESCjfLo4,1810 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/experimental/type_traits,sha256=fvaGOF-OPV_QF_tILR2oBc7J9Zq3dDThKTHIZXXMLYc,5558 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/experimental/unordered_map,sha256=ZQXMdo_UwbD_yoe7nAVzorITJGL_6QhcmkeDoNouZJA,2056 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/experimental/unordered_set,sha256=Q8uqIS6q2O6R_UDbZCb37N0BbX0r9I9SMfCca6gAUfM,1859 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/experimental/utility,sha256=s4AK0GlDhTz8T-DvJ_3XfmI8TEkkPzBwoEWCHlGg01Y,1061 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/experimental/vector,sha256=YSCc1pur-FfH_AxapkrGeTyygujI7yzULSxYBWUdxyw,1190 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/ext/__hash,sha256=qRgYsk-MbVJKvjq1LEJaPQde27Kod9dG0mcCPuQiDeQ,3329 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/ext/hash_map,sha256=6lhA5heovzCGT-YajexSSz_79ARkGppdzepHrWJCPCs,39356 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/ext/hash_set,sha256=ltYC4hPKMSAL4IZagZ49-FMCa8BQBkBthGAu8jGhwuI,25084 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/fenv.h,sha256=GPkOJnJRSuMHFdZPpQ0b4WiGr4W-g3MbOEC3ahbLSso,1879 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/filesystem,sha256=NGf3D_WfoaOimiHo7xTNw8t29jAjln1h9LW94VjPgr4,83706 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/float.h,sha256=s20SOVleS7cjXSITjSkqD13rAFlIOPxiqhLxGftsYfM,1688 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/forward_list,sha256=FB9ZHKNb2MpQhjB34VBiioyH2L0lBX6YmRBxCfn2T7g,63124 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/fstream,sha256=vPttJdJNKeoEHb64IOSnjPkDkSr_QPBEhfVOvbiFCwU,55050 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/functional,sha256=iieGrDiwQR-8Nk842NLL76CPtcS9sADf958iIuNUMIo,17584 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/future,sha256=BMz0FBDEFQbX2ma9_9Gv8J5qv-IBvRXOB07rGLGnWiY,73866 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/initializer_list,sha256=pvOzniXnkZQ-QAb3u7FSkvlhhd1-m2Pz2-UwhKifHUE,3154 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/inttypes.h,sha256=bE0Cn-ZqlQWArt2M2bKFCjr76o5T_OAWhwmVToyiJ-I,3905 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/iomanip,sha256=OxExHTKDY8zsfFSeSk9uq2xGAFT-hJjEHvsryD2typc,18527 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/ios,sha256=E7nheWlG1krtEOMpoQvMpGT-olZcx6gK5eMD1Lg97LY,26748 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/iosfwd,sha256=b6YGe2X2F4YEGvR_g4SOviP85xd18KEX6zrTZsJaSUE,8068 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/iostream,sha256=aEgRzoIAYPaEfAjddOKZ6OsLhAkPgTvm8e6Klu59DhE,1455 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/istream,sha256=VW8T6DBCZYzNWHcYGfZe5OhlwwJ7NIZgLv3DDaquixQ,48516 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/iterator,sha256=i8hSdOCMj61gAMnOVIILyy33qY-MiBvMXPjtxVzRobo,31943 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/latch,sha256=63EbnLAqQg2Tbzc8mJPCumymt0Cr8mlOW97NpEye5Y4,3261 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/limits,sha256=tIV-WodxULY3vaCX7y4FhMZ3AGlCDkLsbUCRiDHIvls,43791 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/limits.h,sha256=d2epHZC9_6Un-43o0jvtvbD96DPUtND-usyhXnKGW78,1539 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/list,sha256=lmO4Wr6ngHLcX9v_3tygTilYhlddSjPOdkUirxKDLbc,81862 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/locale,sha256=ROk3nngrTXGV-mAH4qgkzrf2rVsdQXimLlaIvxz2Q30,155548 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/locale.h,sha256=yHYSZWjh93BZM8VxHVQ7juvN65QWOPb2X42L3B3JB88,792 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/map,sha256=jp7am_mNVFrA3ijytdjn4Gei4ZCWIKi-dhGJP51ssIk,86013 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/math.h,sha256=6e8JGnAysnLGXooLPxSTd3MYBVFCBw8LxCZ8zckgiWA,51607 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/mdspan,sha256=jvLvt1_kSk7U7wosMaPECZo8_wCvAjagXkHm01-WYYM,2582 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/memory,sha256=IJhgGnP7_5bQDIoPqK8HCrjSCIE9_hXtMBCR7vtzUps,163912 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/module.modulemap,sha256=zsMrIbU_hhmcI5vhKWu2yzE_ABRqx2ZMFVQY3UXiYoc,11978 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/mutex,sha256=NOxfUee8hUsFfyn11l6Snv44koWFcXZjeGoUZVPPuEs,17972 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/new,sha256=nVbPwMy0kfTWyD75XHZ4LBiOEh8DnTsxIGR_Y1xJ4Fw,14833 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/numeric,sha256=vCcFfaaU5ex8uhDdFh3nSL09aNvIDL-mPPuWylydM7o,21155 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/optional,sha256=eh1NTzB0LoNCtLCOhj3siqOy7YOMchDX6E1Q2KHdAF8,56454 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/ostream,sha256=aPZxlEnoazXm8Tdc_qHwT_ldbz2lJC9OAlIRIYtvx6o,33426 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/queue,sha256=64-DHyh2keMyy88sxaQtKerIFi_t3lu3NxP1dX6vXYY,28700 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/random,sha256=wH9Pj2AK-7dq9Lfl7Tq79UxqV03Yeb98UCavdd-sU5E,228967 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/ratio,sha256=IvrO13Wa4ejCUnLnOZPEmf6Blf9EfQ3bpBRjtmGNgeg,16901 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/regex,sha256=a3SC7Hkn7ccMUkRfivniVM8qnVynWP0PptCBEW3Fg-k,225287 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/scoped_allocator,sha256=vk16UeNYhK5fPSduaT4jIrbV-4DyQdTzwXWpVZPqmWY,26133 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/semaphore,sha256=PPrYsnkEGqFkBlhpPybOimG-RaYgPLULC1z6pkXLkcw,13661 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/set,sha256=9O0Dm6xp1y9pI-MTft96hJgdNFFkS8NMHWdchRbeXV0,58258 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/setjmp.h,sha256=3EOFmewnhGJWNcSWruB13gvH447NZH3TZn-KUBzgLDc,818 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/shared_mutex,sha256=y_2kHKUeiGLmXuiSZRNsEp1B3kkPFg0TugFUEPBXAQA,15375 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/span,sha256=qKPyI-dAOJoDO9e8tLqr0NCP-fuxqMb0tFDmWiUr188,25511 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/sstream,sha256=VWBHQdeo5coEE3_d2tv0aF_9aef9DIlwfNSkXfyHa2U,33693 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/stack,sha256=ddvdCnFLAMRJ1xBiNNik8Oub_jLfqZhHCm_I_gKp8bs,10329 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/stdbool.h,sha256=mUtb2IkZENg_X-2970HMfEHucE5vyTuqf6flBKOfykI,831 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/stddef.h,sha256=xc2TlxWf6Wy5jaKFsF-VdKlp06L2SogiQk1L9dFtXNw,1405 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/stdexcept,sha256=MdDPIGw-B_ZN5frtzfDPEDYDZGLMH09d0_FLgg3M_Xc,8494 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/stdint.h,sha256=nUzh9MpfQ4ml2ugihv9a7M1h7zhs626eDxstxxzIZzs,2395 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/stdio.h,sha256=lhCXEFbyk77kh23hFx_mN7kzI3u6zfQQhBzBUuNUm4c,3541 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/stdlib.h,sha256=mmh82pa200twP_dau6ZSyogGDTq4NhjYXiU3AC-a7mI,3696 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/streambuf,sha256=VX9COXVCaAl43Zw1BXqj2gE5GmAIVUSh2k9wIFcSjdw,14742 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/string,sha256=-ic6eazN_R1wMI8qjjIH9e3tEjlz77ekHkHgGfy9pms,163775 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/string.h,sha256=rN1U52vlM3hsh5nivnUciM8s0EWPcbjbOeYxl8ppUzk,4821 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/string_view,sha256=fy_SIhen4nB2tVG5dfLcreirW1eCvc-Az3xdsLrW31w,35427 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/strstream,sha256=0OSYo6X5b4QuAjcKmNYeFZ9Hy8YLnzB7sfIwV_b-dkk,11409 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/support/android/locale_bionic.h,sha256=zoPlnOPpTy6gX8BRkCfYaruDsAEmYBSu9nI0tPp5TDg,1836 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/support/atomic/atomic_base.h,sha256=OFWQaAFSOw1touHLkvVWHNH3nYnYd6UZly2bZm7qIIE,9401 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/support/atomic/atomic_c11.h,sha256=Ojad-SdURhQZzDcHcqwPGS2TzEPUF9dpDg-ZGzNbirA,9205 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/support/atomic/atomic_cuda.h,sha256=Ct0K74rYMRUOzEwsCLnEvbikblupwF1fjOHa6bflgIw,20743 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/support/atomic/atomic_cuda_derived.h,sha256=vdcUi2pN2bfPMp5LoWr1lHD8UD8V2zZ9CdX0_PPdMjA,7068 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/support/atomic/atomic_cuda_generated.h,sha256=-RGRhzqsxnNH5rntVksaStkTboPvRdZumxZwajCusSw,265782 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/support/atomic/atomic_gcc.h,sha256=ZEhwk-NyN3lbjkyS7K8QiJNeykJth0rEic-FBadADQI,635 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/support/atomic/atomic_msvc.h,sha256=vQ5u2deIOQgW6wL97JmFmEoPWtYZiSEtIiWGqnQ_HSE,22447 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/support/atomic/atomic_nvrtc.h,sha256=O38aFtM9aYjmZOt_11SCNDo9BhrzCM5fz4Td6ZnjQkE,640 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/support/atomic/atomic_scopes.h,sha256=3nkG3GI1-Nl8ITZRXOObtvBK4vnckk5_toiEaj7XqNY,1770 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/support/atomic/cxx_atomic.h,sha256=lneL4EQ7AHwuwjnyORbnUCu7Kyc0eil-q7bbwHY26qA,6501 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/support/fuchsia/xlocale.h,sha256=Uj1_T50BphJ3EFcR0kLT1IU42nJ_2qFxY_Wang27UgY,719 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/support/ibm/limits.h,sha256=8sOfpm5BDoi-lqKQ94TtEXA6JKAtzqnl2ke_EROnmZM,3622 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/support/ibm/locale_mgmt_aix.h,sha256=SEJsXlFv71PeRExZNluSG_IQrz89IcjmCM2vSauFlo4,2466 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/support/ibm/support.h,sha256=Cx_BLZmSAjKhfeciYbQTucc64dC7Tytij6kE4mUEK0M,1705 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/support/ibm/xlocale.h,sha256=2OqyGg6BZVar1RovGTKwRMyJ1NmbBVNqve58TAInEBg,5718 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/support/musl/xlocale.h,sha256=XsKOT4mPjpkLikFydyP-3N7FvuwpmCBapNpq5GspgVs,1886 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/support/newlib/xlocale.h,sha256=yT3bbVq_tvE4aiMGQjanwjC7L9MZg-e9dADpAGQQodA,845 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/support/solaris/floatingpoint.h,sha256=YRkhZdGInMpeQpowOehgj0Lu6QYXnuBTuBxZPuqYZXg,476 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/support/solaris/wchar.h,sha256=SKQW1ytPSaWFHVXZ-d0dIpXhhVUUvjIzaPm-0nel62I,1230 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/support/solaris/xlocale.h,sha256=wO42pe-u6sHYD4VGHYw51M8TzGXxunHrJODHLxrU6_M,2257 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/support/win32/limits_msvc_win32.h,sha256=yA5eBAhgofiPD-CxDI6eAowDVUoBn83lv4G4eycn__k,2840 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/support/win32/locale_win32.h,sha256=S7kWMncBNewdAZ_AcPi0aHl2VW_sMemqcf5qUzU2Mxo,6858 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/support/xlocale/__nop_locale_mgmt.h,sha256=h3I-8OV_cBw_bHNonm2slYtdyGqwWkv5YhiOQnHJL2I,1439 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/support/xlocale/__posix_l_fallback.h,sha256=XvPhy1AFhpoMPyiV-lMY9Uzu5kEQNF1no2UYbm7iypM,4757 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/support/xlocale/__strtonum_fallback.h,sha256=QIt5-3I0BlY3l_ZP9VwKCcuCWNPs1Ih9CmC1RzVM9u8,2396 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/system_error,sha256=Fcalorqr77OZfESQ7dDfOMY_S84xIczfkX6lID51DIA,14456 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/tgmath.h,sha256=apzZqK3poat7E3xz_Lu68W6lXBGYnKxVQ7DwYqkcT24,748 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/thread,sha256=vCXfwDL4INkLWqASnvsFBVH7FaRIlrYwlu-48zrdrS4,11690 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/tuple,sha256=RjHiZQgyqUTDfNdgGUA46nh9sjhG4qJFOcMSoVxHvU0,61608 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/type_traits,sha256=P0ml1G-gKiZv5ScK5kwyjjwshv_8GUZdGAuQfpFsEh4,33244 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/typeindex,sha256=OeyBbHjrxQslnGWgssBar3SX3Qj2eUhEJuiI3NeNn24,2911 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/typeinfo,sha256=BfOpqz5VuZf9TrY5uWgobwhiVOdptqxWBv1Y0xhzeLU,11506 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/unordered_map,sha256=-XLIKW5UAUfidaUOPrYCpOLnaacV65yg6du5b-aSaA8,100918 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/unordered_set,sha256=34DkeSnSfTpyo7bmNpIDTJXIMI5eBFKeR3yMcrrKvDQ,70286 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/utility,sha256=PRC0zSxjK5s2JQpK4cVOf1SYD0n7WTruyPX751ecpF0,11410 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/valarray,sha256=M0WmH55X6OkueP0JQCocCSM4r4TiCQuK0GwJbU_7-Ec,136663 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/variant,sha256=Vw16W70Mnli-lHsVBK2zhJQYsv4t4vVNQ1BcTXmovvE,63225 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/vector,sha256=iQcgfcZAPKznHwhY9KpmVJZ1oRiYOCEDE2CvGmlx-6M,113415 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/version,sha256=-Zse-U6_nQMjwVR_QLIz8mzENWgR2lX-T1a4d0YHe2c,43105 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/wchar.h,sha256=jc-UJmKth6c-gom3Q1DwzXFXCDuUlz5wURWus6NvVg4,8573 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/detail/libcxx/include/wctype.h,sha256=Bvf6aJp_cB8yBHlOi1dBc60GiM0wRHAchKA_81RfIhY,1570 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/expected,sha256=3FbihRKzlbnIopRG4m15CksRj9d1dC36bXaIMVQq0rE,670 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/functional,sha256=NRFKnIh376i6V6wlQe6Nk7s86R9povEzQRRlUzbPkCY,720 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/initializer_list,sha256=LsFEh_IHvZEQKh4HEKkzjU0lXpFOpw711SezdEHw_WE,701 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/iterator,sha256=VerBzWRIz6dFXw_EZCcwp2pshtVpQtpHTgQJpfVen2s,669 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/latch,sha256=EYqw2qDPbt6uCl87AApSwc7GAMFHgznzd8iJy5RIsAQ,838 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/limits,sha256=XKY6M3p5e0pvihCFwvAcQu9BWBxm4RAbqIEcAaaAu9s,704 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/mdspan,sha256=w5AH8d4c3uaZe3j_Rn3UdHzETl0XwrXQM7YirpWkS4c,704 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/optional,sha256=-PIbjMgjvah4mJUz8t0gyx9QuFKtvqjDtl2S43cwuiQ,670 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/ratio,sha256=rSmNwx0MDZcKBpGSkKDIoQmyOJyzBUxBM6TiirOFUFg,700 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/semaphore,sha256=ynZ7eirgu9AN-BXoHNAqOJZQQXeSz5G7jU3opccS2Ak,854 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/span,sha256=VgJLuaUnBE7rtimq2fCkRP8ms-xyiTqMkw7lHKNb2AU,696 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/tuple,sha256=-BH4PMtFN4UXWP2F2PLwtvZCWiKf5zx-ysB_pOttAq4,700 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/type_traits,sha256=UlsR4232FyIs-_G-1FGxlaZrcaEo1KD8kruIJGXt7aQ,724 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/utility,sha256=tC1hPBwScBkTWZUJBw2po92vk8fLOd4nGSaRAyCUplw,708 +tensorflow/include/third_party/gpus/cuda/include/cuda/std/version,sha256=1T764-TTjxFf9EYg1yQn0sfR4HEyeTmaElAJt6Kvslk,708 +tensorflow/include/third_party/gpus/cuda/include/cuda/stream_ref,sha256=o5cztYLqqcJ_47CQGL9ue4iNGkm4QoHyYwZ-bbbPBJ8,5386 +tensorflow/include/third_party/gpus/cuda/include/cudaEGL.h,sha256=_CwaQ4cEP1vfNyBSSd5qFxznPCYOovF6Cpj-QWSIBq4,39544 +tensorflow/include/third_party/gpus/cuda/include/cudaEGLTypedefs.h,sha256=xF_FAN1Kar9oyHJ3cCU7jztTpxX8WylpiuYyYpGGHek,5645 +tensorflow/include/third_party/gpus/cuda/include/cudaGL.h,sha256=gMT1HPGa-siuji0gAsKYr4X45Lc29HKglC_ttNSGyUM,22501 +tensorflow/include/third_party/gpus/cuda/include/cudaGLTypedefs.h,sha256=dClpQI-LuXgF9rPSBsj7OkIg8g_fXDjT0hLZS8TGpOg,6576 +tensorflow/include/third_party/gpus/cuda/include/cudaProfiler.h,sha256=ucn6cTQbaT-fCw6oBx4SoIaayZr-ZpNFoCFFFjhnVg0,7019 +tensorflow/include/third_party/gpus/cuda/include/cudaProfilerTypedefs.h,sha256=F2aWLIKv_AhNbxNOaZVcRsxIh0kuscnV8UMWWxkBAlY,3297 +tensorflow/include/third_party/gpus/cuda/include/cudaTypedefs.h,sha256=RJqJmPcRqj4ob7WngV2iOk0NILC-XnPb5vFTZ-TW93Q,103089 +tensorflow/include/third_party/gpus/cuda/include/cudaVDPAU.h,sha256=Np7Nc2Wjaz--hkpbhW6f9aapr-NbcPDAgkot0sJerco,12694 +tensorflow/include/third_party/gpus/cuda/include/cudaVDPAUTypedefs.h,sha256=wz8nyOUdwM9mH9JO3QZW-A9dyxt-IufSX7nggSXpCNs,4144 +tensorflow/include/third_party/gpus/cuda/include/cuda_awbarrier.h,sha256=3ZH-ZlXODhSiwSY9rqSni_EQwi25QMHP6Tm-zOdxBwE,9340 +tensorflow/include/third_party/gpus/cuda/include/cuda_awbarrier_helpers.h,sha256=OCskCts5bCKl_RKBe9M74zKSIsVpePn44S_aJp1tFXE,12489 +tensorflow/include/third_party/gpus/cuda/include/cuda_awbarrier_primitives.h,sha256=n5__E1jYYDhlgH-f3u8MQjtz57UZ7v5VshhMye1eicM,4699 +tensorflow/include/third_party/gpus/cuda/include/cuda_bf16.h,sha256=iJHrrsCRTpAP6Md68DLnBf7I1J6l1tbTeBMsXByTeOk,156582 +tensorflow/include/third_party/gpus/cuda/include/cuda_bf16.hpp,sha256=bOiCftzSEDiiIj8wmxJpA4jbjmACjTAj1mufEoebUjk,154655 +tensorflow/include/third_party/gpus/cuda/include/cuda_device_runtime_api.h,sha256=_Opkj-JYQlAk9Xnoqo7VYB2t-MWF2VC6O7e66hoQHmE,39834 +tensorflow/include/third_party/gpus/cuda/include/cuda_egl_interop.h,sha256=PNWYns30MIytJQHSOh7UbZYlaTX5e0bavzK14tde_C8,37109 +tensorflow/include/third_party/gpus/cuda/include/cuda_fp16.h,sha256=hlzkdzCZqF1tp1-wPnW9Dn1yAECd_tLGveFuTFabzRs,147076 +tensorflow/include/third_party/gpus/cuda/include/cuda_fp16.hpp,sha256=D3eeTzMC5x5qRR7QQ2_u3DXpVywW4GJfp416WNUrfD0,141067 +tensorflow/include/third_party/gpus/cuda/include/cuda_fp8.h,sha256=Q3OP5o_3rSYbKtVIlcXVr_CncU3SPM-09j605e2Zegw,13833 +tensorflow/include/third_party/gpus/cuda/include/cuda_fp8.hpp,sha256=lVzRhCH36Z5zUbo0nwddSTKQQU4wEvbIrEGhR4G9zPg,64168 +tensorflow/include/third_party/gpus/cuda/include/cuda_gl_interop.h,sha256=VQEswFeOBF6JN6Q0pdlkvc5WT7bD1FnTfKewvANulCc,19150 +tensorflow/include/third_party/gpus/cuda/include/cuda_occupancy.h,sha256=Kr9HyOe-hlRjBAzbINwUYkNgbbIgIjuvKs09UZhMYQo,67179 +tensorflow/include/third_party/gpus/cuda/include/cuda_pipeline.h,sha256=0enXG49wN4JajlQi3ahbp2ei_ufTY_Mznic7zfWmKHM,8130 +tensorflow/include/third_party/gpus/cuda/include/cuda_pipeline_helpers.h,sha256=bo1L7e6vCuM-K3Il8K1z4wJUja5DyXQKdo_hSWUME-E,13852 +tensorflow/include/third_party/gpus/cuda/include/cuda_pipeline_primitives.h,sha256=FnJJtuV6rHr6LgL56XDwilcSbFr6W1Hj6mf1AJaMI20,8675 +tensorflow/include/third_party/gpus/cuda/include/cuda_profiler_api.h,sha256=u44DwhffEwnM_jJJxPrBvNV3vc_1xllEIXVIGVIEEY4,4566 +tensorflow/include/third_party/gpus/cuda/include/cuda_runtime.h,sha256=VyGTuLIPHzt22XP0SXRBpTf1iTvDIHVQtnkpLymkO9o,89291 +tensorflow/include/third_party/gpus/cuda/include/cuda_runtime_api.h,sha256=SdNg2JdKHkbddZ-o7XFhUgs-zCS7bERpz8tdYrHhCrc,580650 +tensorflow/include/third_party/gpus/cuda/include/cuda_stdint.h,sha256=XbFOk9CtJjKqk7PpYNqbSVsDxAsVM8avA4rWpPi0BjQ,4093 +tensorflow/include/third_party/gpus/cuda/include/cuda_surface_types.h,sha256=Mw5Lo4b8Q-f9mogOvATGyHhu9d2t2K6XOxuqtZrSh3A,3688 +tensorflow/include/third_party/gpus/cuda/include/cuda_texture_types.h,sha256=ITbX-JNnP7Rm-JSgNVdJ9pq6k8FVor8RbnruDsKq6sk,3688 +tensorflow/include/third_party/gpus/cuda/include/cuda_vdpau_interop.h,sha256=bXQanWc2IFXZAKWNGl2xAz9nLvFmQpWyGrsDvfeS9FA,7727 +tensorflow/include/third_party/gpus/cuda/include/cudalibxt.h,sha256=9GDuRiOzJuO61zRDhIpWpF7XHp8FXSOIlHJNoIMwOZQ,4105 +tensorflow/include/third_party/gpus/cuda/include/cudart_platform.h,sha256=YN6sKhB0b9w5tGX1IYL7ulJVPrWAiX9A44qLv4EtW5Q,2717 +tensorflow/include/third_party/gpus/cuda/include/cufft.h,sha256=KyOZQrl4kPOWgsmTJWo9rhf1zQtFKswE65BS4g1Gyto,12421 +tensorflow/include/third_party/gpus/cuda/include/cufftXt.h,sha256=89HUP-Rzqo4uN29Ue20LjjY13PhnennFGxcPilwd8fM,12158 +tensorflow/include/third_party/gpus/cuda/include/cufftw.h,sha256=DBrJQf-dnCWD-OYgdhnEzn8OiAX0U3xdteEaNdhs7mU,19412 +tensorflow/include/third_party/gpus/cuda/include/cufile.h,sha256=OAEGXjGqoxdOEreJaWsCvHORkvd_XAM_Lz-HeAqNW8A,28604 +tensorflow/include/third_party/gpus/cuda/include/cupti.h,sha256=JkVyAGTIMYzwm62dfVqas3nMcILhgP_Wdz6fh4_NED0,4697 +tensorflow/include/third_party/gpus/cuda/include/cupti_activity.h,sha256=1oCUYS0f3MSmAmI8kS0I5_wXbmOmT5Jk_oe5NZlzFNQ,316444 +tensorflow/include/third_party/gpus/cuda/include/cupti_callbacks.h,sha256=tJTEpxqtzcW2mj0iHvtvr-fQvaFWHdxKbMalbh6Gz8U,29004 +tensorflow/include/third_party/gpus/cuda/include/cupti_checkpoint.h,sha256=rTz8JoWxqESBXyZWUhZJGm4xeYcx4OJOtJ7Ld13T_b0,5264 +tensorflow/include/third_party/gpus/cuda/include/cupti_driver_cbid.h,sha256=idmWDh5-L7lKGSZSp6FVBM6bL1E-maFRzIcSk3rTPqc,70934 +tensorflow/include/third_party/gpus/cuda/include/cupti_events.h,sha256=f7lLGmD2e8FzvMhRgnn0-v7U0vTpUkiQHIpQxgARGb0,51896 +tensorflow/include/third_party/gpus/cuda/include/cupti_metrics.h,sha256=iLAOlDrcbHEsIIUmgq0Tp1ZOY9O3Ot3wj2-bI8iYbSs,32148 +tensorflow/include/third_party/gpus/cuda/include/cupti_nvtx_cbid.h,sha256=_azPtR1g4qivvX7qbvHRUg0RHCWF7iEOJyHMN9qZe9E,5912 +tensorflow/include/third_party/gpus/cuda/include/cupti_pcsampling.h,sha256=uT_DtFN0Bye6ADtxfKXUAc8BcrFefotf-VtTuKQGJx0,32395 +tensorflow/include/third_party/gpus/cuda/include/cupti_pcsampling_util.h,sha256=gEiMBes3mtpDJqauxqUtfe0csY4J31qpdg2Cp8On95E,13060 +tensorflow/include/third_party/gpus/cuda/include/cupti_profiler_target.h,sha256=JsceoDuhllWNEzaO0xxT81dJ55NrbF0UtRJJgit0P_E,32131 +tensorflow/include/third_party/gpus/cuda/include/cupti_result.h,sha256=a-C4Y7LAYCiCT1ngOfoDuTi2stEG1YTafwwn6UfL-LU,12603 +tensorflow/include/third_party/gpus/cuda/include/cupti_runtime_cbid.h,sha256=Pq16wH9tjhzV189gi6KnYGVYy6rRz0rD0djkcNgl3kE,44770 +tensorflow/include/third_party/gpus/cuda/include/cupti_sass_metrics.h,sha256=A_TQCaPr14U-N2EJzzfmKBegYDj9nKQc_gz-0bjw2iU,19028 +tensorflow/include/third_party/gpus/cuda/include/cupti_target.h,sha256=x4Vz1Upb6m9ixmVpmGaKQldDWYQI3OZ-ocEXGzNK0EE,1263 +tensorflow/include/third_party/gpus/cuda/include/cupti_version.h,sha256=WOJU7hZnTyMQaNBEVJffbGhcKV0Pzr5Yinr0eQeZApk,4371 +tensorflow/include/third_party/gpus/cuda/include/curand.h,sha256=AlcrbOrvgcmHoQAYy8WJWGR8miCpHIZTIbnumKwxV_A,43966 +tensorflow/include/third_party/gpus/cuda/include/curand_discrete.h,sha256=2qD3BkI622XEu0444wVP7HeYkKAx0Rjr2HDhqU4SA7E,3486 +tensorflow/include/third_party/gpus/cuda/include/curand_discrete2.h,sha256=ZrQTO5R9x83AMX88uq7M8M94DLSC5VEz0PAkfcwtQeg,10883 +tensorflow/include/third_party/gpus/cuda/include/curand_globals.h,sha256=bES1Kx0NrATXk1DReMMkqWrB062nOnaAp39y22wViXU,3717 +tensorflow/include/third_party/gpus/cuda/include/curand_kernel.h,sha256=SjfAeh13ybXIxiekcgczzua02kIAqETopJKRhYvCat8,53133 +tensorflow/include/third_party/gpus/cuda/include/curand_lognormal.h,sha256=-X-iNkJSzWpAYYjogm689EJTZfzore9sxU7ObddljLk,28142 +tensorflow/include/third_party/gpus/cuda/include/curand_mrg32k3a.h,sha256=ZVVREjGNsJQJ-3IzZZ_LKGtGteslicb8E0Aly49BKPs,170296 +tensorflow/include/third_party/gpus/cuda/include/curand_mtgp32.h,sha256=Qhrmx0pHWF-P2Uu5bKwYE9ymEWq3c7qBzCITVMaKMfI,7845 +tensorflow/include/third_party/gpus/cuda/include/curand_mtgp32_host.h,sha256=SXqzmSQkzTLSRJ4pojTg_TNCC3T-G89HdBK-boSDqr4,18274 +tensorflow/include/third_party/gpus/cuda/include/curand_mtgp32_kernel.h,sha256=ajZnXr5ZXnQExElf6LPpigrrKPTmMIZbRyTEnJ-BDhw,13731 +tensorflow/include/third_party/gpus/cuda/include/curand_mtgp32dc_p_11213.h,sha256=7_gGYUH47UugIAEt60vYH5nFa-QUwTpDwSEgLg9cZts,276889 +tensorflow/include/third_party/gpus/cuda/include/curand_normal.h,sha256=lnmYVk2fn0oEVWOytdKhXrHL36GLCjMnB8OnZeCaYcA,26953 +tensorflow/include/third_party/gpus/cuda/include/curand_normal_static.h,sha256=5K4iTC9AuSWCe1LVxuj_0y3BVjtp0bxO6hndv2rbmiw,4727 +tensorflow/include/third_party/gpus/cuda/include/curand_philox4x32_x.h,sha256=T21IP-Rdg3_tSVU9Je4dLKuwEqE4ovfwi7r1hOY92Dw,7166 +tensorflow/include/third_party/gpus/cuda/include/curand_poisson.h,sha256=KrhXOmO_D7aclnj8geIyHqdpSQwWHurS9V_pVtgzodM,25461 +tensorflow/include/third_party/gpus/cuda/include/curand_precalc.h,sha256=I6NZdgT42fMm9qSCtP-rlOAqt4Zsqgal0ajktcPmEak,1392393 +tensorflow/include/third_party/gpus/cuda/include/curand_uniform.h,sha256=gpmRgQu5r6ppgLTg60NXoDdVJS6wMUy6jC5bh8l04e8,17472 +tensorflow/include/third_party/gpus/cuda/include/cusolverDn.h,sha256=lC4ivrRWNuxZ2iKHJzmF04-VeSrOfcypuej78eA5v_U,147950 +tensorflow/include/third_party/gpus/cuda/include/cusolverMg.h,sha256=N8989nnS2BleeMyuftbQgBDJ4sMAkLPSnmy_S_7fxng,11549 +tensorflow/include/third_party/gpus/cuda/include/cusolverRf.h,sha256=7BZfWeuMJ8w1Pz4iZeGmwvDZbDNNq0ivG5MHtiATtls,14292 +tensorflow/include/third_party/gpus/cuda/include/cusolverSp.h,sha256=8fev0XawDBd0xrOxUlQ3WhclKlUuVAT64zKxwnP8iT0,32561 +tensorflow/include/third_party/gpus/cuda/include/cusolverSp_LOWLEVEL_PREVIEW.h,sha256=rTuS0rxwGV3bAz50ua59WVPQ9SvlijORj732oPejoCk,37495 +tensorflow/include/third_party/gpus/cuda/include/cusolver_common.h,sha256=PiN4kjMWAno_3BJpu96orfflx9Y2yH0KqlbcqA1YX8U,8826 +tensorflow/include/third_party/gpus/cuda/include/cusparse.h,sha256=CDvjgq7dmLzfimzoll6C2JR_6fr2m0D-zgV4spCLhuQ,294009 +tensorflow/include/third_party/gpus/cuda/include/cusparse_v2.h,sha256=jkH2A9hYc-TEF0vuQ_SurbhPNEHkYGUIRuxKXhFAqnw,2587 +tensorflow/include/third_party/gpus/cuda/include/device_atomic_functions.h,sha256=JcP0pC6Wm3Hgtx7wbLajeVLfLHb8PM-9d0oeXNCy_t8,9352 +tensorflow/include/third_party/gpus/cuda/include/device_atomic_functions.hpp,sha256=0e7MOiNNUnnloXpB_r9WT5YOws5cxgzQQAzRCYvgaFA,10486 +tensorflow/include/third_party/gpus/cuda/include/device_double_functions.h,sha256=KUxId5Z1fx8SWfLRTxPD7RB-zN7zslzb4n7JaJLfL3I,3452 +tensorflow/include/third_party/gpus/cuda/include/device_functions.h,sha256=bWSrhTYE9NQlss7xMSMEVusvto9j2fgUDXWVH2W_cOA,3410 +tensorflow/include/third_party/gpus/cuda/include/device_launch_parameters.h,sha256=H1_CC-vvAaS26ys4XsTFkMgTxUTciAjdjswjizkisvQ,3846 +tensorflow/include/third_party/gpus/cuda/include/device_types.h,sha256=2LFxoZBJPoA5V0H1EbKTEaXDi3GDJPtzOPdRHDaucIQ,3588 +tensorflow/include/third_party/gpus/cuda/include/driver_functions.h,sha256=cN3IjRAz2Mj2Pj35SyxJIkZNDDusnJqaqzBdMzpQKbA,4625 +tensorflow/include/third_party/gpus/cuda/include/driver_types.h,sha256=EaI1C2V-6DxzJy8hbuhYoLZJYZgX3Zp1J7kIFZsnHTw,151932 +tensorflow/include/third_party/gpus/cuda/include/fatbinary_section.h,sha256=NnuUfy358yGJx4enq0pBnetjv17UWa-nOlgYToUitrw,1809 +tensorflow/include/third_party/gpus/cuda/include/generated_cudaGL_meta.h,sha256=dfd2QuaRdEjbStOKvaQLi1Md_qrpRQh8PfyZznJ8bWY,3115 +tensorflow/include/third_party/gpus/cuda/include/generated_cudaVDPAU_meta.h,sha256=fAedsoQxaU3hIAApAWDOKsa9kgcuQw4tdyf8klLm-3k,1453 +tensorflow/include/third_party/gpus/cuda/include/generated_cuda_gl_interop_meta.h,sha256=LXOqvQCej0sCgAT1LUKKYZ466EFxN4hIwf9oIhXOLF0,2250 +tensorflow/include/third_party/gpus/cuda/include/generated_cuda_meta.h,sha256=H5Gv2KeBfkgWUwTDwLwWjCMFivV-SfPAjdIcRD80HHo,88251 +tensorflow/include/third_party/gpus/cuda/include/generated_cuda_runtime_api_meta.h,sha256=-HGcJWEoTHOCR5FqJGOwzybiVTgd1kjZgpt_4AV_p3o,65628 +tensorflow/include/third_party/gpus/cuda/include/generated_cuda_vdpau_interop_meta.h,sha256=8OLqWN26aEYpTWUXtbHJvA5GYhVv3ybYVOTW7yK37z8,1367 +tensorflow/include/third_party/gpus/cuda/include/generated_cudart_removed_meta.h,sha256=X3I5WXmhtsJNNlgY7coJ5vg4t11G5FRR6Xo7MboIeck,5172 +tensorflow/include/third_party/gpus/cuda/include/generated_nvtx_meta.h,sha256=YHb_RD8g3s4m8PJn7Z0wnxvUHarl7BOAX5ADr-BL3HI,7513 +tensorflow/include/third_party/gpus/cuda/include/host_config.h,sha256=BscH_GazAZbbotddVzL5RmafbQ-QjRx8f-I1O01IBW8,3380 +tensorflow/include/third_party/gpus/cuda/include/host_defines.h,sha256=bBQwQF5C1N1c2qpLV56g1c-weu9Ysgz-gIf2Kn3uz_A,3386 +tensorflow/include/third_party/gpus/cuda/include/library_types.h,sha256=yJvoLFw5oBdRqkQgEhIaX-stsMGlxQW9sZoJ4vbQHwI,4766 +tensorflow/include/third_party/gpus/cuda/include/math_constants.h,sha256=cV6hAyQe8X7f7MBtaKjjIJq3BycOUDp6I5cizJX5HLw,7608 +tensorflow/include/third_party/gpus/cuda/include/math_functions.h,sha256=5XcC6j-fJKttvhwc4hZNoLHNw808a2ZYIOtZ7ry7yd0,3398 +tensorflow/include/third_party/gpus/cuda/include/mma.h,sha256=IY_VenxuEncwGq92MhrWUb-Xswh0ekAXLy9Rbxhxa2Y,2932 +tensorflow/include/third_party/gpus/cuda/include/npp.h,sha256=g7ZUGNOQ8h63ULK_Yq2RM0TzgoX-lStkgMNYMA5H5es,3427 +tensorflow/include/third_party/gpus/cuda/include/nppcore.h,sha256=EUNVU3tXbbOhZB2aBg8MYNMM7UR2xHsQO5pUn_PS-IE,7426 +tensorflow/include/third_party/gpus/cuda/include/nppdefs.h,sha256=P1EWd1i1jQKI0SSkfGEYXrWuqtqXfL4BLB8vVNo3iWU,41454 +tensorflow/include/third_party/gpus/cuda/include/nppi.h,sha256=vaZRX54shH3TIIPfZ9HdpU0SpvVI1eQhMRZIIMUM1ws,4075 +tensorflow/include/third_party/gpus/cuda/include/nppi_arithmetic_and_logical_operations.h,sha256=bgRJ04Iw_HgKpqA4vewPfB3dF125A-tZa2Bo6fFsgTk,1463588 +tensorflow/include/third_party/gpus/cuda/include/nppi_color_conversion.h,sha256=RgrUluM8HZN1i5ttQlqSTWCqGWk66k7Owr8sj86pZ5A,966859 +tensorflow/include/third_party/gpus/cuda/include/nppi_data_exchange_and_initialization.h,sha256=PGcYERDne4RcqtfFFEJ55Or7D7PEGVodIVshf6fSWOY,405869 +tensorflow/include/third_party/gpus/cuda/include/nppi_filtering_functions.h,sha256=yXOHdXHrvnXHqJf7dCKXAsfYTGVmz5B-1TMPiVxTUx4,1191843 +tensorflow/include/third_party/gpus/cuda/include/nppi_geometry_transforms.h,sha256=G-e2oo6tSjGxTU1HIoUHKbkq-KiI4iq25hPcZaTA2nY,363434 +tensorflow/include/third_party/gpus/cuda/include/nppi_linear_transforms.h,sha256=yxrguOtFd7l1Y2OCAM48S7KoSDBLZWuDV_iCz-Sa9Qw,7389 +tensorflow/include/third_party/gpus/cuda/include/nppi_morphological_operations.h,sha256=BhcqJQPK6S9yCybHnMlYZTYeSCgLJ32NvhLBLW_dG0k,145657 +tensorflow/include/third_party/gpus/cuda/include/nppi_statistics_functions.h,sha256=sd668J9XxBE6pauZmbkauWxFYqsKmIP-JCTINcNZesI,1263342 +tensorflow/include/third_party/gpus/cuda/include/nppi_support_functions.h,sha256=2ta-15cjOCUFOJymi912rNw5CVo-fFE_CrGVNzIdWxQ,13631 +tensorflow/include/third_party/gpus/cuda/include/nppi_threshold_and_compare_operations.h,sha256=DDSX4BwrohJOslr9bAuiHM0ouUZoQnzLXTfv4xO7PV4,271090 +tensorflow/include/third_party/gpus/cuda/include/npps.h,sha256=yIRZFvzt3M-ldhMLZ4rPUKNNFfYKpCgz-cFQwXZOF0s,3672 +tensorflow/include/third_party/gpus/cuda/include/npps_arithmetic_and_logical_operations.h,sha256=hkdtGlE4u1MQaGBDRTv6mREgDC2OqTWMIIjqd26Sn6A,385027 +tensorflow/include/third_party/gpus/cuda/include/npps_conversion_functions.h,sha256=w4EADEaqZ61hNqb9KrqOFVuEvzJuCtkFwIVZGb_Fu3Q,100002 +tensorflow/include/third_party/gpus/cuda/include/npps_filtering_functions.h,sha256=l-iO-i1h7ziKTAeeHpHaMi4S7KfVy6wIIw9eb9hJr5Y,4898 +tensorflow/include/third_party/gpus/cuda/include/npps_initialization.h,sha256=J21oUGLyRy26XqgPyHSpWka4bCXR_TT-YkwYZCfhWFw,29942 +tensorflow/include/third_party/gpus/cuda/include/npps_statistics_functions.h,sha256=F8CIgFQ69gFC5vv8psk4W-WE_Y1QwPj0Z2mXNMTrGYY,429105 +tensorflow/include/third_party/gpus/cuda/include/npps_support_functions.h,sha256=DHID1LlmMPgk2vPJnSb9-GwD1qTWWji3H71yvf9Cre4,7981 +tensorflow/include/third_party/gpus/cuda/include/nv/detail/__preprocessor,sha256=atB2sLbUWPYGJpl-6tzeSG5Z_9aNnDeCDxzsynS3lu4,5175 +tensorflow/include/third_party/gpus/cuda/include/nv/detail/__target_macros,sha256=Fs6dKne8OwnqNDL4E-5qxdw_XxO1wQ5ucAsoRTaC15Y,19876 +tensorflow/include/third_party/gpus/cuda/include/nv/target,sha256=CjkX8r2Xo2_0-10WB78Elw8Qzd3JnEFIxgvSbtiZjpw,7424 +tensorflow/include/third_party/gpus/cuda/include/nvJitLink.h,sha256=-pcL9UTohHatD2OOB2_DryfdBtykLgpjwy7J81bokbw,13738 +tensorflow/include/third_party/gpus/cuda/include/nvPTXCompiler.h,sha256=z_v0P6Sj0KfDQBmAKIdgFoPOylhsO4B221w3KDUqbM0,12076 +tensorflow/include/third_party/gpus/cuda/include/nvToolsExt.h,sha256=OiT6v1G2-vlkYnpDQZjiGT1O-THDyk1gw2021qMRvQM,53680 +tensorflow/include/third_party/gpus/cuda/include/nvToolsExtCuda.h,sha256=UDA1pbmvoRFmlJ11Et9tIMEztOtOVw-10mO27Q6K8jg,6009 +tensorflow/include/third_party/gpus/cuda/include/nvToolsExtCudaRt.h,sha256=6IbgdRGObly53jzRqvsZ4FQoTrXJOJwSyCOLuXr9ncA,5192 +tensorflow/include/third_party/gpus/cuda/include/nvToolsExtOpenCL.h,sha256=gETZH9ch_o6MYE_BYQ2pj9SSuxyAo1H4ptmRK-DMWSo,8360 +tensorflow/include/third_party/gpus/cuda/include/nvToolsExtSync.h,sha256=wqONIiycUPaUUCzQBmCippilgKt8sOL9tpzG773u0nY,14562 +tensorflow/include/third_party/gpus/cuda/include/nvblas.h,sha256=dXCLR-2oUiJFzLsDtIAK09m42ct4G0HWdYzBUuDPXpc,23341 +tensorflow/include/third_party/gpus/cuda/include/nvfunctional,sha256=IkFoCi_Q4OhP9nEuBI-5jWwFlR_PfG05hJH7lSMsfWc,2975 +tensorflow/include/third_party/gpus/cuda/include/nvjpeg.h,sha256=YR2I1D35xX-UIhjol-ffkHHvGrmkzl-Yt-RunKvpRTw,33931 +tensorflow/include/third_party/gpus/cuda/include/nvml.h,sha256=bpEvCjwBpyszm09XL2Gxr0PDLU_rWPRmeJLJGFfoFxA,540550 +tensorflow/include/third_party/gpus/cuda/include/nvperf_common.h,sha256=sVWEIb_eAmk8JdGV0BoQXzTzd4vo39BaMRw6mfYIseM,10421 +tensorflow/include/third_party/gpus/cuda/include/nvperf_cuda_host.h,sha256=aBnyIr_hexPDGBkP6WSujN1mI_DYP25sEIXWYY1O7VI,8298 +tensorflow/include/third_party/gpus/cuda/include/nvperf_host.h,sha256=HIdSvWQkhHvWsPGsDGmtRlA_IcjACkJPHL5vwkNwuio,66421 +tensorflow/include/third_party/gpus/cuda/include/nvperf_target.h,sha256=ZDA-JI459tLBW4iLLCQjYYRAMeHwfqDIgXbVqVLDYZ4,22539 +tensorflow/include/third_party/gpus/cuda/include/nvrtc.h,sha256=FtqIEQvMwYKD7reig0oFmzZWdECCRppQswDl25jENzk,34906 +tensorflow/include/third_party/gpus/cuda/include/nvtx3/nvToolsExt.h,sha256=TFEF3fx1043EwMdbS7FqvvavwK0koZeGrIOAsCrB12s,52247 +tensorflow/include/third_party/gpus/cuda/include/nvtx3/nvToolsExtCuda.h,sha256=4ZbZHUMcmHRf4SdKB7nH0E3uHd_9ZhZBuwuWPItK-Vs,6204 +tensorflow/include/third_party/gpus/cuda/include/nvtx3/nvToolsExtCudaRt.h,sha256=boW0zdYobNFFE9wwxCyzBGBLcSGtdbQ5osKjQGNC2E8,5393 +tensorflow/include/third_party/gpus/cuda/include/nvtx3/nvToolsExtOpenCL.h,sha256=RPfsZl3lHAPIOCzTipmz07-vaiIO4cxelcx12EjB2L0,8563 +tensorflow/include/third_party/gpus/cuda/include/nvtx3/nvToolsExtSync.h,sha256=C-HIVBaupxYom3BqMggQ_ePq1bxFhw8kXsOfYJKBWrI,14756 +tensorflow/include/third_party/gpus/cuda/include/nvtx3/nvtxDetail/nvtxImpl.h,sha256=jEnYF3MyLsD72euw2It3Bz0X0GK4Xv_htEd8BeIrPjY,23333 +tensorflow/include/third_party/gpus/cuda/include/nvtx3/nvtxDetail/nvtxImplCore.h,sha256=sYpWqZfYrjsMddxtezPX3qSTIbAOn4dlEoLiYQ9M2nM,9756 +tensorflow/include/third_party/gpus/cuda/include/nvtx3/nvtxDetail/nvtxImplCudaRt_v3.h,sha256=SoaiprvsI80yLmEAnlFX0iFufv6RtKjjMMrVwQZjjQI,4775 +tensorflow/include/third_party/gpus/cuda/include/nvtx3/nvtxDetail/nvtxImplCuda_v3.h,sha256=IEor-ISqComCRGVDdIzKBLU3eWCuDI0Igqz-eRKKcvg,5550 +tensorflow/include/third_party/gpus/cuda/include/nvtx3/nvtxDetail/nvtxImplOpenCL_v3.h,sha256=iPR2x74bJE3plFQBT9FWGBaTm4sC-Pll6WAjpKRnz7g,8275 +tensorflow/include/third_party/gpus/cuda/include/nvtx3/nvtxDetail/nvtxImplSync_v3.h,sha256=TqwQfEUVbwc58bpHioE13NMweFhOuHXNql65BnLzhvc,5022 +tensorflow/include/third_party/gpus/cuda/include/nvtx3/nvtxDetail/nvtxInit.h,sha256=foajOFacvLGx3BN5ntw5v8o4J3OY4hqkVZE5ZC0x3e4,14716 +tensorflow/include/third_party/gpus/cuda/include/nvtx3/nvtxDetail/nvtxInitDecls.h,sha256=-Qyxcy9CDXOBhEtYZ8L7iYd6daJ9aCeyQM48X0BafMM,9361 +tensorflow/include/third_party/gpus/cuda/include/nvtx3/nvtxDetail/nvtxInitDefs.h,sha256=dLhOV4knhNrmT2DnUNzXreOt_Qc6GAa3yIlmqJFCeVI,35432 +tensorflow/include/third_party/gpus/cuda/include/nvtx3/nvtxDetail/nvtxLinkOnce.h,sha256=Jp-z6LTz_p8fKRulcFfdcskIxzcZ6ybbHkGB9mpJa2M,3863 +tensorflow/include/third_party/gpus/cuda/include/nvtx3/nvtxDetail/nvtxTypes.h,sha256=jkbCwyvIP1G-Ef8SwYp4kDi69hjZbzaxKSk7ScgrNI8,17352 +tensorflow/include/third_party/gpus/cuda/include/sm_20_atomic_functions.h,sha256=ClKi9c4_m_J37_fAmQ5l-j5jmVKBARmPSQKudvHBczY,4764 +tensorflow/include/third_party/gpus/cuda/include/sm_20_atomic_functions.hpp,sha256=1l5NLM8DhDbqYZ_E51LoqElQJXObkbwo57d3r-4uEbE,4107 +tensorflow/include/third_party/gpus/cuda/include/sm_20_intrinsics.h,sha256=cQbeg-K9zWgOI4jAVeUmV1WiWOMF5sHPz_nb3CWdAjU,51052 +tensorflow/include/third_party/gpus/cuda/include/sm_20_intrinsics.hpp,sha256=BhEBuXSKBsNGJDBJDtYL0cGRI3wX_w_OIgA5D-YxIWk,7694 +tensorflow/include/third_party/gpus/cuda/include/sm_30_intrinsics.h,sha256=-eZBx9bSLGxhSbqzi-IhoH4Tk0u_fomRAFDu-zNhJqc,17011 +tensorflow/include/third_party/gpus/cuda/include/sm_30_intrinsics.hpp,sha256=yX0ebd265tJ-BDhvluP2BhadPuWXpRZPI2eeQFFt5ys,24567 +tensorflow/include/third_party/gpus/cuda/include/sm_32_atomic_functions.h,sha256=cK37qpMGQ1pEd3nTXO3RUi940i7IBUp2wijYvj_Nh-Y,5493 +tensorflow/include/third_party/gpus/cuda/include/sm_32_atomic_functions.hpp,sha256=CQTTvOEYp-s5hqAgLvAon11vLYDrDp8cTHdel-XRzBQ,6592 +tensorflow/include/third_party/gpus/cuda/include/sm_32_intrinsics.h,sha256=o7IwBBKu2lDZwzHHb2pOLAvyCNpCoEKSHPt0dFaSspI,33390 +tensorflow/include/third_party/gpus/cuda/include/sm_32_intrinsics.hpp,sha256=Gl8aSLDLcit4W3pKQS19GsDG8RYcwD65HwYB_CeZe8M,70616 +tensorflow/include/third_party/gpus/cuda/include/sm_35_atomic_functions.h,sha256=a3XoEsKRCEOf0Q_5Y__rMfmC4pScv4VkUggVgVJVn44,2909 +tensorflow/include/third_party/gpus/cuda/include/sm_35_intrinsics.h,sha256=BEiPNO03ZSv5XtMMul5jiTH4oLWlOu3CYkIAgrWslnk,2952 +tensorflow/include/third_party/gpus/cuda/include/sm_60_atomic_functions.h,sha256=wqC0X3P2jvlY6r48sNo9_-4DazcM3Gid9MvnR-74YsQ,13031 +tensorflow/include/third_party/gpus/cuda/include/sm_60_atomic_functions.hpp,sha256=cgIKddDn2B3QzYlzeBILAP1IRys74QCCxsH0QqaVGls,22903 +tensorflow/include/third_party/gpus/cuda/include/sm_61_intrinsics.h,sha256=gWfLebvNizi3Nc294H5OCS0qYVYgedIm-hpl3TLEkC0,10703 +tensorflow/include/third_party/gpus/cuda/include/sm_61_intrinsics.hpp,sha256=N-nQvcBsPMT2Umy5zR69c9K1q366W-Jqe7NpoLTqTmg,6787 +tensorflow/include/third_party/gpus/cuda/include/surface_functions.h,sha256=b1O82SAvEgWWxA9uZTWQcGimzZUoem2QbAET3wh3fZc,6782 +tensorflow/include/third_party/gpus/cuda/include/surface_indirect_functions.h,sha256=vy9QuFVV-ezZP-x2RT9RLp2qIUgdngACOCmalSfVFPA,10877 +tensorflow/include/third_party/gpus/cuda/include/surface_types.h,sha256=Di766cyRUqNN4JkOnYM3teFqrwMZ02hXMDB_R_2_vz4,4460 +tensorflow/include/third_party/gpus/cuda/include/texture_fetch_functions.h,sha256=KLCmUxf5aY5_UalX8tSFB6e4TrjA8hyUPxLOkMFltAo,12468 +tensorflow/include/third_party/gpus/cuda/include/texture_indirect_functions.h,sha256=lH_y3Ni-hq4RZ0_PMFbBM0th5-OmTn3TtqtpkHHhA8w,21163 +tensorflow/include/third_party/gpus/cuda/include/texture_types.h,sha256=cFqQ6sC4y79Q6YxjLSY_bknwMgKJAOwPdKDARLPFrDI,6290 +tensorflow/include/third_party/gpus/cuda/include/thrust/addressof.h,sha256=RbkUeN_ze0qF3znr_MzOhIWG22GTXbzk_esbrCszbdA,806 +tensorflow/include/third_party/gpus/cuda/include/thrust/adjacent_difference.h,sha256=74xN4bmKcw-W5zaNQGYvqKXNK812bifxLzR32LEmrv8,11470 +tensorflow/include/third_party/gpus/cuda/include/thrust/advance.h,sha256=8mDFZzwrybIim4RY52meXbjrKxnc2cb5TvPZ024IB-M,4146 +tensorflow/include/third_party/gpus/cuda/include/thrust/allocate_unique.h,sha256=K-Zblj0dWL5TBBpGBwAIA492mpIfIkTptq2uRj_TWiQ,11786 +tensorflow/include/third_party/gpus/cuda/include/thrust/async/copy.h,sha256=ziesUak0-DamN2zdC5SJ-ivIZqj4FFAeLTpf4UsmrqU,3897 +tensorflow/include/third_party/gpus/cuda/include/thrust/async/for_each.h,sha256=R3TYFvP1tjZNRH0qKqLWKCBFppmZiV27bxvLZUuYlvQ,2867 +tensorflow/include/third_party/gpus/cuda/include/thrust/async/reduce.h,sha256=CyW7oZT2c-_oa5iwFd0_FurvEfiair9QuR_IX3tVNnA,11680 +tensorflow/include/third_party/gpus/cuda/include/thrust/async/scan.h,sha256=g_pwDLRQG-Awm4Qyl9mbXz7-PPVx2p3RcynaA93LDNk,9648 +tensorflow/include/third_party/gpus/cuda/include/thrust/async/sort.h,sha256=3KaftAf7D1bkQLLMppEMdgmlMmKc8Hozn7aMwqfESqE,6915 +tensorflow/include/third_party/gpus/cuda/include/thrust/async/transform.h,sha256=Dis81wIWDXiCyM3_JZe47Cy7Hcw48c-5qpmEjdJsYO0,3152 +tensorflow/include/third_party/gpus/cuda/include/thrust/binary_search.h,sha256=fuURWLYIYgtvc3G1O0ynB9ea3ZhUW_j-1ejTH6390yQ,84960 +tensorflow/include/third_party/gpus/cuda/include/thrust/complex.h,sha256=IpF1gBxtcO1wq4CcvhLaqmxsyeB1XMc3aGPvu467J6M,30032 +tensorflow/include/third_party/gpus/cuda/include/thrust/copy.h,sha256=66SHHx87PZeS007GOnq4YHuIrSyFac1UGMnTSIJwnkE,22187 +tensorflow/include/third_party/gpus/cuda/include/thrust/count.h,sha256=dOn4b5jmfb9IXMAis8piBbic5gsLfxHHCuADJa4vT1A,8688 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/adjacent_difference.inl,sha256=TO5mkiZPHIGSHRikHS39JkxoSxq3UwFahTVejUrwLAs,3376 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/advance.inl,sha256=3MRGUqjKixwe0zH5oS2DvbB5w1_d3WbAqQkXHn3G76Y,2085 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/algorithm_wrapper.h,sha256=ONJTVZ-KX23XxX0pl75W9P9vhEMzD8xMGoSOqdr7Ef4,1087 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/alignment.h,sha256=nEIAQIzSafrJVTce6jOY5OrOHMokstA46XbEr_TS1vA,7131 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/allocator/allocator_traits.h,sha256=lVP7aXSC4v1Kcas-MYsbvm3HgXKHbYWxDVeNgPWDGm8,13771 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/allocator/allocator_traits.inl,sha256=aMTz6UTiup7qFTHAPk_xwu3_4nD8wiw-p8gArDHdXkI,12771 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/allocator/copy_construct_range.h,sha256=CNGcTZaODtKxtQDyBvEEQ86J9gBrg2t0u4cejPtwXx8,1632 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/allocator/copy_construct_range.inl,sha256=ov8ZLbp4i3DAlWRWOgGjOWR30alveO2eqprL_0ZlI8c,11114 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/allocator/default_construct_range.h,sha256=s5QY5upepz05TQn3Sr-fclDu0EO5JtTJckA-DZ94FAs,968 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/allocator/default_construct_range.inl,sha256=48asoHsb43MsE_mxJJpiNY2PgKIduwL4kHtdIjCW4xs,3139 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/allocator/destroy_range.h,sha256=tuSsXDgT-bii3NHqlY0j67_1zT82u4ITDQnsE0vWK-k,947 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/allocator/destroy_range.inl,sha256=4PhWdWXUTzoQnG7JKfZDBpq_Ykt5WsTvTDx0RkM6YM4,4495 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/allocator/fill_construct_range.h,sha256=FFdyvnHFBPOjsD2n4Zib-gWXNzDSfYq_syQLzwyQjmo,989 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/allocator/fill_construct_range.inl,sha256=J-w8udjjMwaG7UOMedMU1a8_KG7sHUWJ7i-sl6RbZXw,3083 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/allocator/malloc_allocator.h,sha256=IefC8k8Exv1TuPvMa-Z7uKbnClPEWm7PqyRUGelSBus,1388 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/allocator/malloc_allocator.inl,sha256=g4kZzG4ke5Z1vyV_JxXha3BAv9fI8wXVAXiR8UpiNA8,1992 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/allocator/no_throw_allocator.h,sha256=y9s01YTwhhTRx2CRGlVvxlp170VtAcBwTexHBRXkx2Y,1861 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/allocator/tagged_allocator.h,sha256=F-oqb75D2gfimepWl5yNyyntkpDiSFGq48KteaTrGJk,3886 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/allocator/tagged_allocator.inl,sha256=rimP_llkpdkqkjzj-WP9bNoTBpYPc5oV0M03tcjJFXU,2656 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/allocator/temporary_allocator.h,sha256=nz5vOVRLwWSc5aRxp4SrGE2kcUUA3ymNR9lLSxeX0uc,2325 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/allocator/temporary_allocator.inl,sha256=W3VBWcWLMCNHCkvlg0a5bdA9vWZhSa8cx95YtcVT_jY,2481 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/allocator_aware_execution_policy.h,sha256=Z-OtOTemeNM-ZPFFAkmXbAT2HohONZc0WHfQwCGPaKI,2793 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/binary_search.inl,sha256=g9OzWX1gGOlLFJY6SsBi1yMRxZPcDPDbSXusOlGmyB0,19330 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/caching_allocator.h,sha256=GZq65ecCiFglyKdQRDM5PLKVRinlPREVhdZ9JZj-A6U,1329 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/complex/arithmetic.h,sha256=bBCPfKym0Ta4S6ZVH4fJ4KNa_yI3lF46Mb-ak0taCxY,7437 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/complex/c99math.h,sha256=6j5vBfs-LzQJERgU9henU39P-ZHunCRGIrb3Vk-dbhg,4475 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/complex/catrig.h,sha256=PlCDs1Ziw29nQJMQ2FjmYPm3rSgczeZwzryN_Wy8358,24185 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/complex/catrigf.h,sha256=lrWHgBYXlbeAJTxI3ccd3wqip7bMRpgzJ2CTM-20nbQ,14281 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/complex/ccosh.h,sha256=hB-LWw05imaMwNJpKfc69VF3av1glfdzF2gOG9t2kYc,7222 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/complex/ccoshf.h,sha256=uEEhDfwzinNYkKdvy2jgYe4mo6tjEfaIYsCAXOb50YI,4624 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/complex/cexp.h,sha256=1c5jA4aC1XzDOkujsd2SHpcH5Aq57t7TibmdGiBPD70,5818 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/complex/cexpf.h,sha256=MNyhJfp4WDgdCZ8H_W538bh7l8GULIlvAciT2ppC8P4,5039 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/complex/clog.h,sha256=8arDEX_o5OvQiI426LgxmUaiTd8O8rjMVr0BQIC6atU,5851 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/complex/clogf.h,sha256=NSZdqRGE22aNC7ZDhe5EOrb9E0FDaaiKqRBbX0HnG30,5387 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/complex/complex.inl,sha256=Xg1LFmRMTIy0f2Cv_IgkZZbnI_90xnlvfx1iX8ab8L4,8058 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/complex/cpow.h,sha256=bZWcaTLtfU5ha_e9nXEqpUv08nGUm2wxubU4YGad8Zc,1695 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/complex/cproj.h,sha256=aZAj4ybnRDv5IxT-2PK2upEIwJvO4vUSWZN0e2_NnJo,1892 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/complex/csinh.h,sha256=-fTU5E69-dxJMzoo4lRVpfs2fRa4YUY07taDHNkQlos,6787 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/complex/csinhf.h,sha256=vn2B5UmKYlJ00Szo5blgc8JOn9QXNYpq6ySAWJiHXtw,4567 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/complex/csqrt.h,sha256=ADY-gqTf1eeLnGZhUyMPyV1I9yDkYGF_0ehfrQMk8mY,4620 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/complex/csqrtf.h,sha256=--ZdCePExTsqiV9Ml9WBiVz91C-e-QrDL5C17pRXJ_Q,4526 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/complex/ctanh.h,sha256=qYb7IsrPbWxA55JAz90NNSEC2yuH5hgs86sQ8-4Tuq4,6117 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/complex/ctanhf.h,sha256=iB6ji2Ixn5i3sVsQZWWVqEpRPMd9jHA6Zz3e0rQwxqY,3802 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/complex/math_private.h,sha256=QReeueOqsR8jbPEOaMwh4jp2csSYX_W0pivgttuQ7J4,3203 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/complex/stream.h,sha256=FVVTT0oLut0O0Iiq_a2Jyr9f8pDf-H_COLkARS1XJ9s,1725 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/config.h,sha256=TRz2SdEtXruPLeGqQfuNNBb9XuiU3gRZc7CmPm73IqI,768 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/config/compiler.h,sha256=1KD7zQ6T2VsD2d3v3hRKWknKRUrGFj9EIvMTDLsa5ec,8378 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/config/compiler_fence.h,sha256=jT9nSfmgGtg7rVjOJm6QRD7jJi5dvx93x8ujtO1bqrc,2041 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/config/config.h,sha256=so3oix378KiXUSHtWm9dkixc7Zc6ZM3D6ZKhcj8I5ps,1478 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/config/cpp_compatibility.h,sha256=b6-0xj_g-4xIGZOON7CMGOij50ZL6PHzVWeCtoCkfr0,3806 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/config/cpp_dialect.h,sha256=N9jxnLIJJLh1f7Y2sdC6rFvkRkl0veIUocwv847x4HA,5461 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/config/debug.h,sha256=yFwucGYXIDe5E9I2qBAVXDR7DVNaaUkcV5CMsnJUKCI,956 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/config/deprecated.h,sha256=trli-vPkDALMCa5mcgh5CcxUo1v8RAg9jvoawTA1yyU,1437 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/config/device_system.h,sha256=k0bR6q0JRSJxXmYc5T06SJgcUcxzGO9ImegSYb7Q_V0,1575 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/config/exec_check_disable.h,sha256=HxMWrr8XB8u2b_slZoJ6Ss53e6h6RbSh-R1dX6RR8SM,1329 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/config/forceinline.h,sha256=XjHFAsQDjJW0EFKQdPqwq8Zr99Oa5c3pDZ8_64f2eo4,896 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/config/global_workarounds.h,sha256=ErETNAbNnckXwE1MgQpSm3au8BXi-1ze4nBP9AxSooU,995 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/config/host_device.h,sha256=b98M7EtW90IRHB56CgsA9cNLCHcUcO6YhlC6Xn0fxqs,1278 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/config/host_system.h,sha256=qiTho5vbaHD04M04uwjNggild8kCosW1aY-81elRk1g,1386 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/config/memory_resource.h,sha256=LoEE5GlKj4eLXlF1MESwAUIHIMd7KCQ-i6gK8v2cXJA,1222 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/config/namespace.h,sha256=kLDUkDfftJEt3WtF0A_PlQsVP_aG93FQkK84-wYAO_Q,4173 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/config/simple_defines.h,sha256=DUVAkx7Yehw5KyF3hkc92d58GQ5HBMuimY-l1KLggdU,897 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/contiguous_storage.h,sha256=fcxRRSsKQOv2KhbOopLW0Qy_tpO0x8wwEn-sBBmxRRs,7398 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/contiguous_storage.inl,sha256=qWjGz009km81cZ3wiwmOw2Y4EZPdcxSCvrF34hb-ez8,16225 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/copy.h,sha256=zPVaofZSL3cSCl6wh_5tNegTuSkRH0I4FjPr5EwOh1Y,2924 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/copy.inl,sha256=CwwNV3wSjWM25qpeUj5Xs4iVNEZEzs8RF9leo8HF0mo,4690 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/copy_if.h,sha256=DfaQ1kVXx_ZW-8L2WOfgrlkjHTfZbOMfYy-fiWZ1vwE,2369 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/copy_if.inl,sha256=4IOCDkCT_tFUwKSAJmUL_9d6OXdUge_sOD5jKLT_Wxs,3758 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/count.h,sha256=WFytpVyHxYSKYjrBqVeIZTXsacVq_xfGPyJn2sFiTS0,1999 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/count.inl,sha256=FQHMA3hqh8ZNOzxJOQdRyvF0BawfBixt4RR4uyaA9jU,2831 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/cpp11_required.h,sha256=OfV2yprc8S6yuEC0jYG-ZF5W5ggYwfMjkjga_gHo5bY,893 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/cpp14_required.h,sha256=y3OnHr6p03RX1sco5ZjCdrPJvCRYG3kgV5RwpQw9JeM,892 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/cstdint.h,sha256=fPC7pV8OE_38TZJnYxlfUURS2g9T5zTrw_rYgLThWCg,2464 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/dependencies_aware_execution_policy.h,sha256=Y_uJNLKy1tVe5yaqpSHlRX3KZrcph44tflQZAS_KTN0,2827 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/device_delete.inl,sha256=UI5QMUSmXFXbHElHcMNeHo4mKHm8fsjs7MtRPQ1Ykk4,1233 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/device_free.inl,sha256=YX9yx3rnyEjOcgPPd4DN17GriDi8KdD02rpisA6eo8s,1177 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/device_malloc.inl,sha256=vKhai_Mop0xr1w0bO4UbkVdhQDGfjRTW-yJcbiu-GjA,1596 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/device_new.inl,sha256=rRc3q234F_R6gePw0dVbN1QJ7WPgmR69VzE1E3eI-40,1664 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/device_ptr.inl,sha256=Kn10GWQhP2-nWJkL0CZi24ZzqJLnhb_aa3Tcwriy4iA,1703 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/distance.inl,sha256=ZIcDjKfIFbxbzZOzBAjEkxjQIDMEHouGoucEsxUGXA4,1135 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/equal.inl,sha256=it3zsvELxoZB6dS7AZn79ay-wU858yXYsbhLqGRxzL4,2918 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/event_error.h,sha256=u99I1nOKSFEKnHmlg1MKiVoi1LmSwAQKF8Pvc6xWB6k,4450 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/execute_with_allocator.h,sha256=B1JuiwzHrMtYhB-aTed74-h8YpY4YmfKSzujkb-1kJU,5260 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/execute_with_allocator_fwd.h,sha256=wkLgvqX5kIO7p46L0H2ZYuhPPVirKMp7yD3j6yoz01A,3131 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/execute_with_dependencies.h,sha256=UX3cIGNcVMAUNISBESd_mFFmLiK9ljAbjpYZ31WrPO8,7813 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/execution_policy.h,sha256=rhAUVk-2TPROw3_VvkTvJVGMNWCmIw4zKGzr2wc6Mvk,2115 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/extrema.inl,sha256=eNFfDouRHttfC7mYUuLdyMgHkto3JVvthH83nYlvF6U,6164 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/fill.inl,sha256=gC8QFYy4WPLylvItB9vQXW8rq7cOrZVb-3MnfyAqkDA,2730 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/find.inl,sha256=cznqQ6MUNtTyx-0gD1zbxHdX5EEY3CptJGfTI90arck,3633 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/for_each.inl,sha256=EW3CBTxa5Vtzci-vahBnNqB6p4yZolxdVsfBQrlp8KA,2892 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/function.h,sha256=Q4pZhUi5dTzWts63KPqh8fTdGevfhrv92w5iTXnsv4s,4752 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/functional.inl,sha256=THgRT0QNLoQQhySWRbmilMBgWp_YYNkib2uZQFn157g,4292 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/functional/actor.h,sha256=wwgo8wmkrBm7960aNjuvwxOCGPtMrcrqer96Jr_iFTI,3975 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/functional/actor.inl,sha256=utNFdGaWyfF8DgPBNJaL9TEy5BG5tuNsKNFgPpBZQhE,3249 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/functional/argument.h,sha256=gtY-8MAdLrBP5Ee_7i3klmacdAgPBU9aG3wlEoAPjgE,1613 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/functional/composite.h,sha256=xsdikWZ2Boow3hmivBDUGosseXsBPOp46W2PhUqOKkA,4163 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/functional/operators.h,sha256=EYjYTFy703ytp9idItTavNaCJVonx0A8soGpCWjSYGI,1015 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/functional/operators/arithmetic_operators.h,sha256=0tBbO0IAfFb9wJqhOnTxnbIht5cYUVLwtG64OA5IYd4,10319 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/functional/operators/assignment_operator.h,sha256=lEgYRMzv35mJ2Xtpnx9WXQdV1Jd9IlS_F5qv1GWIgaY,2164 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/functional/operators/bitwise_operators.h,sha256=3gKCv5jQnyQbpeZp3Qmi4iVIVuO3o6v_LQKZwLgztYc,8009 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/functional/operators/compound_assignment_operators.h,sha256=HK0C7zrP92PIgmvFfAUIQqSLUBuhf39X8h1xQEkuHOY,12970 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/functional/operators/logical_operators.h,sha256=RG5GLGaXhTtbE43hlsJ2s2xN7laD0PeVtaouxZPwJJY,3583 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/functional/operators/operator_adaptors.h,sha256=7cUdOEhz_RO2j5C2L6_dVRpbluZ1YZHpz3bw6yPthko,3747 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/functional/operators/relational_operators.h,sha256=7vLi-QcB98hK2EXb0_usKR_gOBORu28J8ukDlWwRmLw,7904 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/functional/placeholder.h,sha256=blHSEOnIqDRbgQ49eRsBqb6bn5s3msKPDcmNwAuj7ao,970 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/functional/value.h,sha256=Ygm0SROVPhx0ssQkBlRMJkJ48cKJs7RVup9Oy-tGi0A,1523 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/gather.inl,sha256=YlyX7Af9We5_uQc6WdllaZSxL_v_yCxhRxlk19GnrVM,6932 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/generate.inl,sha256=sxtKk7Gmv9fyjtD8KJuyRSllK48Apm5wARsoYi_xjHc,2899 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/get_iterator_value.h,sha256=zcFS5RQbnoXBc5S6pMmsd0r_8reSNiEwgmln-y1qKgw,2005 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/inner_product.inl,sha256=rp0-txvSvWL4qMRS6b2i6GFAuypfyBMv7SB9FnWxmN0,3771 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/integer_math.h,sha256=IpQ9AUPWp8LHJOO00y0t3zgaAV0xjW0M-s7cOJVGxYA,3653 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/integer_traits.h,sha256=ck65TtVLhbDi8Mito8gxYwZWztbdoveUaaEPjnQiUrc,3006 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/internal_functional.h,sha256=ERoFeQlc-YmiPiibbEQ16xEFpTAGVSP9FcVLm-BMf1A,13655 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/logical.inl,sha256=c6sa7mn8Wz8t-soqEYQ7yF31OSZfCeu0Fv3ighGoGWY,3245 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/malloc_and_free.h,sha256=zJYcTMCfQ7kHwyiUUC7Qz_OdhPvzAmJgp0Hb2JlnN3E,2738 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/memory_algorithms.h,sha256=7tWtJGqmPn0_5a_gy_aCsAGfNcl_a3gzNeCTJcUGi9U,5928 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/memory_wrapper.h,sha256=b7rwWJsQZl5ADZwE1oYKCzc27aFWNUbcjl4EJSLgHhk,1304 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/merge.inl,sha256=7PzuPICd3WHWtZ9_Hl62Bbj6LcFyXZsTn-5Nk1rEyrc,9084 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/minmax.h,sha256=m6yB_7zeqV8OPxrZXbPssp7glObunt7oc_0iuI_PYrU,1465 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/mismatch.inl,sha256=aHNvhQ1pTjRuG6aHH3dJ_7ul1f6JV2pPiBX_1J1agzQ,3765 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/modern_gcc_required.h,sha256=p79DQnw_ZytTBOEt9-jJBUEL6OuwRP8VS40CNcAxHEw,893 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/mpl/math.h,sha256=awEl_FEBdgjnoP6Dgnc0r1y-OYNRJL_N-uI0dez8AwI,3039 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/numeric_traits.h,sha256=Lxm7EJW3dRJ-P2QdzcmBD1CL1sW1h5gvZNN-6BFXuTY,3438 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/numeric_wrapper.h,sha256=btq540LJgulScxMoueN7QzDVWQu6pvlaRPFMGSiszfc,1085 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/overlapped_copy.h,sha256=NNdVAzSsg0CQNz1HJwUxppUjHl_jupumL5EXSPi4FhU,4307 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/pair.inl,sha256=jmbpn_Nbc-jtqXAE1w2ZuW-lKUDtYvLyL0mCABVlDJo,5007 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/partition.inl,sha256=bj-B_SZDqwUSk9gCqrGndC-2XdK997re_TMhswNZI6c,15177 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/pointer.h,sha256=rI6M-PBFm_-0rsIoItAbrP_acgbBUB3KVUFadUj2xd0,9240 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/pointer.inl,sha256=qWNuBvQR13eeKCU87wGQYbnpWZydFsaQKZjK2JCKfvM,6755 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/preprocessor.h,sha256=-cojmw4HM1rqi95Aj6cXVN5vRnBBZGtQ0UNoyvxTJjg,42969 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/range/head_flags.h,sha256=mPH2yILkMzcRu1km7VcEOm5y8BgpTHPZfQkGUS_1BgI,7043 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/range/tail_flags.h,sha256=1oBcLUG5H11CiQ_08Obt1mXpfzbaVp6cqsefj6mDBvI,3933 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/raw_pointer_cast.h,sha256=8pAAhrGPeb9gHoNLrkfpFK1CCz3xYLqjzL1EYDjllxg,1542 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/raw_reference_cast.h,sha256=JbIYvd8lQQtb-M0eZGHO7s-gk2ie0CDKy0K25ATI14s,8069 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/reduce.inl,sha256=8FoxCHdCbENU9AOh5V5Ul6AIVK_60qO-LHd8DWJ0HeI,9632 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/reference.h,sha256=dHS8uQUM1Yh0cIqQ8pwmsLC8n3QCdP-TTPYmZgCf4xI,14913 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/reference_forward_declaration.h,sha256=A7HfG1a_YOGcPI-cUhxck3ci3QJPo-YnMQiFkqDLScY,848 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/remove.inl,sha256=S_87tUoTBvzHLOaQdHj9YWoji95BEc2fZiRs9DWMtUA,8570 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/replace.inl,sha256=4Xub-MFMi731wMAbMhgHZpcJwSgFYETkwWaT77xSihc,8650 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/reverse.inl,sha256=C7K3Z7UrGRKVG8WElICu5rJPVW7LxBXB9ONQAbqNDjw,2974 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/scan.inl,sha256=4cXObzO4gcSbEB40hJ0Zt3GuIfEl6_mYRotdfqxqv1Y,20546 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/scatter.inl,sha256=NlWLFHhZRZewHaTo4fC3YTG7rbNILNVHncqDSAoZvOc,5726 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/select_system.h,sha256=iAVIvFFouNf1u-_HtiSFNfgxhqYE-QFt8CJsPDYKpEE,2514 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/seq.h,sha256=Zejl6M4TUtl1TjQrqd4zd_KVG_acu8uIW3XAkWBkWUo,1460 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/sequence.inl,sha256=2m6mRAyMJdRLMOYzzFvVV9Jcuqa4SbC8BQxM9czCmmk,3537 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/set_operations.inl,sha256=CvKF_vlJ0iHvaVJKl_MyCcJSx9DOqBZq3wimwWcQtgA,41943 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/shuffle.inl,sha256=KnOGq_1D7X5usl8BFPCSrnIz7RQYhCVyjfN7bGGjiyw,2905 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/sort.inl,sha256=1igvT8XU35vV-2AAClzOM3yToPIoiOkqBv5vp9wz134,13901 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/static_assert.h,sha256=Pej-qVtZXOKkqvY_0I8UOFuWMC8iKp2kYgG6jZ-CrtE,3156 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/static_map.h,sha256=n_GaVMwka6rDlX2SU2EQzcHq3WRmfLddAYEgGe0nn64,4363 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/swap.h,sha256=s15SqEeHSHHtK_yYvRYL4-zvxDc-deK_8YhrxQn5YF8,930 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/swap.inl,sha256=QOx6VwivTaCzr1nJjVbjSrWmGdm1a2XhzcGlhmb3A5c,731 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/swap_ranges.inl,sha256=Q0EiMJGg3oEih3g85smyRDr4JBXCtC3teGo-ZCKsY5o,2155 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/tabulate.inl,sha256=FydzVlB4Ew9pB4G85g5LpAFa626Ps9JqIy6VdYL6Ix8,1883 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/temporary_array.h,sha256=7jnuGT-lyw6oylsMk38uZN9niCY-hPdxfbQVVOYYrCM,5245 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/temporary_array.inl,sha256=M8R-qA8eAml1lm9m8d0ZmF8HvoHUoWNad6bZlfMrbA0,5105 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/temporary_buffer.h,sha256=ZCRvTC5SnKXcnYMaaJ92Ta9v-7bOqXoray5iNa5AHqc,2865 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/transform.inl,sha256=3UOkzrUnjr1NuXn8pOqw3gtHcahS9qe5gfX3OB1_t80,9221 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/transform_reduce.inl,sha256=lkbHAdHhIKrKJZQWXDnVQlLpy1O7mlfF-jnsDT6BmS8,2385 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/transform_scan.inl,sha256=Vw-5B3uOnszLzZ6zqFnxmNgCpYsPEQdXhYpu6Vp1KbA,4651 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/trivial_sequence.h,sha256=l9uBfojj1kekth47oj1v-_O9QC_hR0cRar2KsxBTfgw,3050 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/tuple.inl,sha256=z3KWHRmUrG9aJ1oVd5VNYRAY3Z1W_u-veX-2ZcH_fGI,30303 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/tuple_algorithms.h,sha256=Y51LOCydmUXWvW05dXd19_SlZAJ7iSliPfiAMGZOrvM,2869 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/tuple_meta_transform.h,sha256=t9_mPmhIUMhUNcfpXzb83rcHws5hYyt6vtOifv7-ZYc,1833 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/tuple_transform.h,sha256=vhv_fUfK0vgFNAoTkh6akS0R2wLVvdbpxZR7hraX3-s,2577 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/type_deduction.h,sha256=NrQPRRZNyCxjuCpF07_mea5NsR5Ry_Lm0ie4M3CLCvY,3697 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/type_traits.h,sha256=CjuFEQ0S0ha0ErOlWPC3iDpF831Rr6pJG-x_HU8rpgg,20928 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/type_traits/function_traits.h,sha256=5wEEiREk--NV-0ZZz4HI1Nd8zYt-1OgQEFhF78yi1DI,3375 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/type_traits/has_member_function.h,sha256=Y-ojkTnencDYDqfKLMBKY50mLPxa8uhTEc6iypAgrLs,1933 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/type_traits/has_nested_type.h,sha256=pyJvfo4YiaFt4U3V7XxqIjd25vDdO9xB2cOFnWRhlYo,1135 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/type_traits/has_trivial_assign.h,sha256=kDEb5H-c-RnZj6H9ercL9vYOUWRsKAjPtDRUWfAKiGY,1163 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/type_traits/is_call_possible.h,sha256=Ru_Oencdehmr2eCTnSlu8CUzUhG930-ZSrEvbBrMvAU,16096 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/type_traits/is_metafunction_defined.h,sha256=K3gZUxmlWAsLXVIhyxPjrFqk61-ELlyxFyymzIenOU4,1094 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/type_traits/iterator/is_discard_iterator.h,sha256=jTYSEjLrar3EXsnsk7xRQ9djyVtX5PlinxZ18P2x1BU,1073 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/type_traits/iterator/is_output_iterator.h,sha256=x34KsKZM4BZt3cQsHO5RU3lAVxhWZDbmlqzQiQSMoHg,1755 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/type_traits/minimum_type.h,sha256=bvnyG80wVV5rdUPG4cdbYiNuuBvWisw-0lqM8qtaIIY,4445 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/type_traits/pointer_traits.h,sha256=AP_WmW8gcRfS-6pkoshGoti1aPqRo_N9WeVt3-XEhOA,11185 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/type_traits/result_of_adaptable_function.h,sha256=b2u6KpDvPjNZzUyet-O2ziJrDbYYdDMJAxEWeMKhWDM,1743 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/uninitialized_copy.inl,sha256=eQXN5aYtEoi7wDzyZ2WeYwgG1oOGpCd_pq6lzwZI4eA,3481 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/uninitialized_fill.inl,sha256=PXX4xId7nHISn8I9fx4PVC2li8IRmKyeMbkHgjVHYWs,3080 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/unique.inl,sha256=omrHJWkphlFI0ZYuC50a4uZVqRQaj-zMJHQEQMAqiCQ,14409 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/use_default.h,sha256=d428LAhv1pcWL2AEVSfRvdi3tI67qObSyM-VqvCsgZ4,737 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/util/align.h,sha256=cZUWGZdWlJ3N0Qt-cB4HV8X1f6D1ck6DWEl_XPwbjEI,1360 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/vector_base.h,sha256=j11oPKdFrzlTZGj3jV_2xpiAl91fHuSUgTZ9Tnd227k,24113 +tensorflow/include/third_party/gpus/cuda/include/thrust/detail/vector_base.inl,sha256=_c5u-xZb4lD5P_1G4twuZnveWWJ4CLhPpXonefuVbaw,38961 +tensorflow/include/third_party/gpus/cuda/include/thrust/device_allocator.h,sha256=I0SJ2lWrqgKHPwWJPphrLJslafbChvvdt5TDVxL9o90,3909 +tensorflow/include/third_party/gpus/cuda/include/thrust/device_delete.h,sha256=Mghj949mVU8s8ccmiZVtZuWfU9hLlqDzSm16i1d6lv4,1419 +tensorflow/include/third_party/gpus/cuda/include/thrust/device_free.h,sha256=ngdPUUapFONSkQ53g6sHAuXLqAqCRT263T44_QZjFwA,1713 +tensorflow/include/third_party/gpus/cuda/include/thrust/device_make_unique.h,sha256=UR63XsC9yCSd0Nd_xQeYzp9eXC-t-VlzQvAzfcrN7Bw,1855 +tensorflow/include/third_party/gpus/cuda/include/thrust/device_malloc.h,sha256=aOtY_Erv4Iq3476gacVC6xoxSOBIyz6BiozTyxGveE8,2703 +tensorflow/include/third_party/gpus/cuda/include/thrust/device_malloc_allocator.h,sha256=k5jkgs7M_M1RcZdsOl31jiYJFEp9T8svK9RJnbOOseA,5901 +tensorflow/include/third_party/gpus/cuda/include/thrust/device_new.h,sha256=fKEx39pBAtby28ETPUIo9JOP5QXOjXAn-rYbZY2SKSw,2725 +tensorflow/include/third_party/gpus/cuda/include/thrust/device_new_allocator.h,sha256=A3npOKY3NPaFjkepFmfxAewb91p-PUVSyBgEvFJUOlk,5541 +tensorflow/include/third_party/gpus/cuda/include/thrust/device_ptr.h,sha256=6ujIN19_vMZYwLbMnzEauvy522KUIGuStYDDxjlsAP0,6033 +tensorflow/include/third_party/gpus/cuda/include/thrust/device_reference.h,sha256=vsSrBXJk-_5YbKGY5YoHbbj7KHxfTDtKIyDp1_ZQwxc,28560 +tensorflow/include/third_party/gpus/cuda/include/thrust/device_vector.h,sha256=e5THKUt1pkUj8wE7UkNtWTvTMf7kv0OciK563z30Ips,18536 +tensorflow/include/third_party/gpus/cuda/include/thrust/distance.h,sha256=2uL1JZ4z5ECu3R6d2QV8QRYwuEAZWlVy00ksUxgmruU,2358 +tensorflow/include/third_party/gpus/cuda/include/thrust/equal.h,sha256=QeUbFHrsxsPSBQcf9B-xs1rYtuOGyXuKk9RXhQ6P5fg,9996 +tensorflow/include/third_party/gpus/cuda/include/thrust/event.h,sha256=tTm9T0ffaqC3oCE_FvWgssvCWzBMVlP6dDh7ChJ3E6g,813 +tensorflow/include/third_party/gpus/cuda/include/thrust/execution_policy.h,sha256=DyAHmDNWVw9mE4PRr-vTy9CKe4VTM2kdcVFG78IiPEA,12124 +tensorflow/include/third_party/gpus/cuda/include/thrust/extrema.h,sha256=Vjeu-IHY9FEToWYK0B9IOQ9Uz75YYPd-6KbCetb4JRU,31413 +tensorflow/include/third_party/gpus/cuda/include/thrust/fill.h,sha256=pxnshK_V1INuBMWdnEImZ6rBhhbwTXCUj4w2RFnv9-U,7526 +tensorflow/include/third_party/gpus/cuda/include/thrust/find.h,sha256=J9wY_gcrERo9VmHofujaoH48F4eSu9bEKtbtSzJewBU,11830 +tensorflow/include/third_party/gpus/cuda/include/thrust/for_each.h,sha256=RfqAB7ZGlkkuVhUA-sl4isPt1ZUDrfVb6_fRMAFFAPI,10406 +tensorflow/include/third_party/gpus/cuda/include/thrust/functional.h,sha256=AN1hQYGUbmhEKs1VgT_H07KCa_2m4FwEf96wLy8ZIyo,55075 +tensorflow/include/third_party/gpus/cuda/include/thrust/future.h,sha256=MpNf2UyZm3EOQhXOBk58Lp02aanF4rMGNU8AO2JWJxY,5286 +tensorflow/include/third_party/gpus/cuda/include/thrust/gather.h,sha256=t4RvmBnSDtjqkxGYmgJBEiF_vetKR-OwmjloHGEVadc,23135 +tensorflow/include/third_party/gpus/cuda/include/thrust/generate.h,sha256=53B0OnC6ANatYKB6mOo4BVx0xru0PLbvIzsNZIORFuE,8286 +tensorflow/include/third_party/gpus/cuda/include/thrust/host_vector.h,sha256=COmDMU6-V5c90nVSwK20HVnZJaeNwhea78vpCguet-c,18632 +tensorflow/include/third_party/gpus/cuda/include/thrust/inner_product.h,sha256=znPeTbS4f2Lu72jiP04-BF5jOFxPGwSx1kZ20ME3lOI,12051 +tensorflow/include/third_party/gpus/cuda/include/thrust/iterator/constant_iterator.h,sha256=im0UG9jf85nSv_In0KDjeCn3dTlzR9PfudMucF38Aw4,8335 +tensorflow/include/third_party/gpus/cuda/include/thrust/iterator/counting_iterator.h,sha256=wwG5mns6SQUFpxw8JqJSupalInAGpfx79y2TVrAaKAA,8164 +tensorflow/include/third_party/gpus/cuda/include/thrust/iterator/detail/any_assign.h,sha256=micXpS5YyW7StzS5yK7dQpTDfDfgvnTPDgKgSAPSTNg,1196 +tensorflow/include/third_party/gpus/cuda/include/thrust/iterator/detail/any_system_tag.h,sha256=He7EoRFqWcQ6Ku1lbjV7NEWTR83fIh0P0UX4B4q3XPo,1006 +tensorflow/include/third_party/gpus/cuda/include/thrust/iterator/detail/constant_iterator_base.h,sha256=qhENl_wjtilvhEWNeIoRBrQEt_T9f0LUi5MQ4IqQhHY,2159 +tensorflow/include/third_party/gpus/cuda/include/thrust/iterator/detail/counting_iterator.inl,sha256=xjQLoisWCSoNdhLC8cm_wvA9qqNYVq3WYkz63au6wF4,4469 +tensorflow/include/third_party/gpus/cuda/include/thrust/iterator/detail/device_system_tag.h,sha256=VcPs7J_5AjH3IE0uS8U9ppH_SB8dQm3dqtmZYgxGlrU,1033 +tensorflow/include/third_party/gpus/cuda/include/thrust/iterator/detail/discard_iterator_base.h,sha256=Mt85OCEI-kz-lB-sUrrCdyFky15xIYKEpAVL1epToSM,1742 +tensorflow/include/third_party/gpus/cuda/include/thrust/iterator/detail/distance_from_result.h,sha256=9ze2c64BZAW7Iqv86WSt4uFyP4NIDrRMOrTR2GQfcBM,1228 +tensorflow/include/third_party/gpus/cuda/include/thrust/iterator/detail/host_system_tag.h,sha256=Jh-3vQtfDY08hCzYMM6kvW5-zKyhN48tYesK0F976OM,1019 +tensorflow/include/third_party/gpus/cuda/include/thrust/iterator/detail/is_iterator_category.h,sha256=ruEmVmLtWfVsS3lwQwYsVLOGfBbWiE63KhT80NX37Yw,1611 +tensorflow/include/third_party/gpus/cuda/include/thrust/iterator/detail/iterator_adaptor_base.h,sha256=PNjcEnt7CnIVp_1Xj66Zt4wFdcR9pgYwyMkIODFyOg0,2713 +tensorflow/include/third_party/gpus/cuda/include/thrust/iterator/detail/iterator_category_to_system.h,sha256=EChIijUdIcl5DRp2J_CDklnXrC9mAGJqhI3j0xKhRA8,2457 +tensorflow/include/third_party/gpus/cuda/include/thrust/iterator/detail/iterator_category_to_traversal.h,sha256=zNWAdRwQNDmz7peJmnJTrX0Wuqc1B1f0bOQK51U5PkA,4066 +tensorflow/include/third_party/gpus/cuda/include/thrust/iterator/detail/iterator_category_with_system_and_traversal.h,sha256=AW2_MD6_4FGYZYVRnr_nJ6W4VQbfv-OGeGIetOD9J14,1746 +tensorflow/include/third_party/gpus/cuda/include/thrust/iterator/detail/iterator_facade_category.h,sha256=ZKAaztPgwHK5JDakdrJQmjLQTgFKKwtjWGuXN--uOIM,9981 +tensorflow/include/third_party/gpus/cuda/include/thrust/iterator/detail/iterator_traits.inl,sha256=FqvRY0H7CWF_U7zkKWQTn6qvGx6nlOvDevwHYE-lYDM,3578 +tensorflow/include/third_party/gpus/cuda/include/thrust/iterator/detail/iterator_traversal_tags.h,sha256=llQirp6p3gs43jVYonUotv15oxFj1Rm8v-hDAf4trE0,1108 +tensorflow/include/third_party/gpus/cuda/include/thrust/iterator/detail/join_iterator.h,sha256=GLhJ6pe_JWOjSCZiUNhZI4oLMX9Idms_272Rpb4IDK0,4098 +tensorflow/include/third_party/gpus/cuda/include/thrust/iterator/detail/minimum_category.h,sha256=qE3xQwNeo917Nrgm2wDkraZbrZVh4y2dnCy4YkARcJ0,1873 +tensorflow/include/third_party/gpus/cuda/include/thrust/iterator/detail/minimum_system.h,sha256=ljOh_Gs9ffTSnDuHGSbE9iFVAGRcbhoI5cRw24nFsMc,2900 +tensorflow/include/third_party/gpus/cuda/include/thrust/iterator/detail/normal_iterator.h,sha256=BVtigtZQJNeY_kSnRCDbj9qmOu9dV3dmz3PXqCS_yM4,2005 +tensorflow/include/third_party/gpus/cuda/include/thrust/iterator/detail/permutation_iterator_base.h,sha256=gk46wtB2Kd3w4yJF_V6CfZVqpr5CkAC5rNYliE9zxnU,1611 +tensorflow/include/third_party/gpus/cuda/include/thrust/iterator/detail/retag.h,sha256=23xD1JKxyix1tmLN8fr13kEpaiuS6qjE6Pdia1PSv_A,3800 +tensorflow/include/third_party/gpus/cuda/include/thrust/iterator/detail/reverse_iterator.inl,sha256=b7G-nvXAGIYT59QtJD0mHw9P43hIj_pUeRBOw1P0_yo,3494 +tensorflow/include/third_party/gpus/cuda/include/thrust/iterator/detail/reverse_iterator_base.h,sha256=tI5iMSKfiYk4D2qKYfycM8oH61W5FHe6YNjHYjXzxdQ,1119 +tensorflow/include/third_party/gpus/cuda/include/thrust/iterator/detail/tagged_iterator.h,sha256=rwRZezlmy7Atj6XuHmradsJuJJPOtY9MGUXhrxDvpoc,2550 +tensorflow/include/third_party/gpus/cuda/include/thrust/iterator/detail/transform_input_output_iterator.inl,sha256=paBJF66iXfCL7_Kru8Hv9n0sQwdUskuFPj87UxVV0GM,3433 +tensorflow/include/third_party/gpus/cuda/include/thrust/iterator/detail/transform_iterator.inl,sha256=Dt5x11Qu1l-PTnKug2t3lO0gw90DaLboUT66RLdBrAM,2465 +tensorflow/include/third_party/gpus/cuda/include/thrust/iterator/detail/transform_output_iterator.inl,sha256=4FMBo9u5aSWlEIDkpqyPmwJJjXTOmLhr2hWtVy6UBLA,2395 +tensorflow/include/third_party/gpus/cuda/include/thrust/iterator/detail/tuple_of_iterator_references.h,sha256=f59GOfEk9qmWZl3dZ09Gl0BQxGSG_OwE4Q_3yYIBK_I,3978 +tensorflow/include/third_party/gpus/cuda/include/thrust/iterator/detail/universal_categories.h,sha256=U9mK5KvoipJsZa7G5kyzGKOUwSMAthXA7H0jiOR-daY,2475 +tensorflow/include/third_party/gpus/cuda/include/thrust/iterator/detail/zip_iterator.inl,sha256=R98iSlPYkbvISZuI4uTBRFIDFHheEPPxEKmDE2Rhknw,4335 +tensorflow/include/third_party/gpus/cuda/include/thrust/iterator/detail/zip_iterator_base.h,sha256=wqWgJDBYr_Q851Yj0o45dOTjwmFmTPKmY3cEf71AXT0,8879 +tensorflow/include/third_party/gpus/cuda/include/thrust/iterator/discard_iterator.h,sha256=28RT31Li6o4fcm5qC_t7nYTcnZ9QRM5F3gKn-wjVaPk,4968 +tensorflow/include/third_party/gpus/cuda/include/thrust/iterator/iterator_adaptor.h,sha256=rDedHKrMcxa3gkMGbmbmiamoWbu1iyFRbRmGY1MiSRw,8353 +tensorflow/include/third_party/gpus/cuda/include/thrust/iterator/iterator_categories.h,sha256=h5wyuTLNNlmmXuM4nzltU2PaWUA1OIT3UujhhrVFWFA,9225 +tensorflow/include/third_party/gpus/cuda/include/thrust/iterator/iterator_facade.h,sha256=p9fjJq2h0wEfXNAxLEf-O6F5CBHeY27oqCww-uLKbfE,22014 +tensorflow/include/third_party/gpus/cuda/include/thrust/iterator/iterator_traits.h,sha256=XHMmysqUdDYfmsP5jvgvpBGVufzTEBL2fL-8gXy4Nq4,1948 +tensorflow/include/third_party/gpus/cuda/include/thrust/iterator/permutation_iterator.h,sha256=kjokzqUm3A7zgHSnAnKk42XK41BMpeZsmixiJVV_nUI,7252 +tensorflow/include/third_party/gpus/cuda/include/thrust/iterator/retag.h,sha256=_o8O9_Y_wl0WUDiCNEopEqxuT5IrPAJYRZlv8CXXJno,2379 +tensorflow/include/third_party/gpus/cuda/include/thrust/iterator/reverse_iterator.h,sha256=z7diM-p4U_qGddTQofP-WxwcIL_MmqgO0KW-vbl9sPc,7185 +tensorflow/include/third_party/gpus/cuda/include/thrust/iterator/transform_input_output_iterator.h,sha256=9UmTfFIPkcPMwmeAa5m7mZ9j4y2ir8mo1U7kcrIQrVY,5745 +tensorflow/include/third_party/gpus/cuda/include/thrust/iterator/transform_iterator.h,sha256=4I8Z1MdGJI2dUfol_M7jLdId97kydTNiihwdQTYo2O4,11679 +tensorflow/include/third_party/gpus/cuda/include/thrust/iterator/transform_output_iterator.h,sha256=sYiAcJ-JHsWR1a6US5oulR0sMva0fv_e5nI3DY5msVE,5254 +tensorflow/include/third_party/gpus/cuda/include/thrust/iterator/zip_iterator.h,sha256=jJ-2I1vazFScL6BRcIRX_pFbtC3nrAMbxOsHd7aQ2-4,8303 +tensorflow/include/third_party/gpus/cuda/include/thrust/limits.h,sha256=57qgDxGt_xPJLbJaEPSS81LIbVXjxD0b2Her6mZM-l4,412 +tensorflow/include/third_party/gpus/cuda/include/thrust/logical.h,sha256=BE4YBmwy87ZvH4E7Wzvk0EMnQ90ewQiz5UJruHdL5Go,10369 +tensorflow/include/third_party/gpus/cuda/include/thrust/memory.h,sha256=eLHMe2D-9at-mqpc0tXSRu_DkYgCBvf-tAeoZBZSSH0,15359 +tensorflow/include/third_party/gpus/cuda/include/thrust/merge.h,sha256=AnKqFZtxGnxUybQDpbpqEJop_jfPjfbfQGo488WgvmM,39495 +tensorflow/include/third_party/gpus/cuda/include/thrust/mismatch.h,sha256=W3bV1flp4hGEPo3moMPzXb3q9DioFiIx2OsLoJ6Dsmg,11041 +tensorflow/include/third_party/gpus/cuda/include/thrust/mr/allocator.h,sha256=atX81JwtSwGwJWwlhAfcU-QcTs1LMI3qjTpbEnBG20E,8829 +tensorflow/include/third_party/gpus/cuda/include/thrust/mr/device_memory_resource.h,sha256=qUvjtNvkm5NRRKjlytJJv0Gj-02Q8kbx-JKH8GTdDP0,1311 +tensorflow/include/third_party/gpus/cuda/include/thrust/mr/disjoint_pool.h,sha256=6yvGfcVwSORjJQ2lnfpYyQ0p-Sk4EMpDVur_wyjJLX8,17230 +tensorflow/include/third_party/gpus/cuda/include/thrust/mr/disjoint_sync_pool.h,sha256=fL6CnMUE6U-GjBJwF5g-G7hE7DLuYRnBdZSPgb_FnTM,3712 +tensorflow/include/third_party/gpus/cuda/include/thrust/mr/disjoint_tls_pool.h,sha256=L5cKmfTkNB6qWNxawiKL2JdelDBO4RGhjPK9q38VMdc,2064 +tensorflow/include/third_party/gpus/cuda/include/thrust/mr/fancy_pointer_resource.h,sha256=H3EYWZ2N2FWz1ygmxIY68gL5AsTrcLqB9-n_QMV1L_4,1753 +tensorflow/include/third_party/gpus/cuda/include/thrust/mr/host_memory_resource.h,sha256=AueFlZ-kIzhWpV5rHgTTmJPhahW0TxS-01WJVK5zJzU,1041 +tensorflow/include/third_party/gpus/cuda/include/thrust/mr/memory_resource.h,sha256=jY1Kx6UTcBjHw-qNnfIwz224HklIcVPCvtBtx35xgVA,7471 +tensorflow/include/third_party/gpus/cuda/include/thrust/mr/new.h,sha256=QEambFtNMIaL4Oayp2gOmZh7lwpHmk0dmlpLUMb4v6Y,2987 +tensorflow/include/third_party/gpus/cuda/include/thrust/mr/polymorphic_adaptor.h,sha256=HnhmUUeu6JdU6_V-dOAgvR8TTkH_0nm7hc-yl7pkSiQ,1605 +tensorflow/include/third_party/gpus/cuda/include/thrust/mr/pool.h,sha256=ZVbCFP-6aSmfsomssLOMUt0qknVq9NT5KP_RAvPMPIs,19640 +tensorflow/include/third_party/gpus/cuda/include/thrust/mr/pool_options.h,sha256=4xEos3-zmS9yCrI8l2_PhOD6au53dbecmtn7D6XKnZg,5017 +tensorflow/include/third_party/gpus/cuda/include/thrust/mr/sync_pool.h,sha256=vzOBKHZ8VH8qg60uNViat7uqnZXTjNQCfk78SKT-utg,3296 +tensorflow/include/third_party/gpus/cuda/include/thrust/mr/tls_pool.h,sha256=14TFetiD7FtikwQoC94MBQ-z98x7NurDQTnSgltO1aA,1744 +tensorflow/include/third_party/gpus/cuda/include/thrust/mr/universal_memory_resource.h,sha256=xB7NKBhqdMvattTAKFQXJ5qLlD1IpbTlFySQOYG6WS4,714 +tensorflow/include/third_party/gpus/cuda/include/thrust/mr/validator.h,sha256=sU4FygLTA6JIgMK9_DbkZ6FJ7oWTfSN650cdO49aS74,1249 +tensorflow/include/third_party/gpus/cuda/include/thrust/optional.h,sha256=7NyJ-iAFOWzGx2YNwCY5ooEqgMQzyl0BgMsTUu2wG5U,97959 +tensorflow/include/third_party/gpus/cuda/include/thrust/pair.h,sha256=Bdas4Gi72h4TvqiMNN8XR1SeQxU3bpNkli9VQ2tFntg,9424 +tensorflow/include/third_party/gpus/cuda/include/thrust/partition.h,sha256=__e9bQUtk7DlgPMDuvm2M69TvcfudxytwvF88ORgdqs,67577 +tensorflow/include/third_party/gpus/cuda/include/thrust/per_device_resource.h,sha256=cr39paN3ZvTaQAGVGovjihbYI87ihDV1lUaHgREexBQ,3724 +tensorflow/include/third_party/gpus/cuda/include/thrust/random.h,sha256=vEHzunwY40bS6_kiEWaA6_Pte3V7mR3LBnL5WTZLQRg,3773 +tensorflow/include/third_party/gpus/cuda/include/thrust/random/detail/discard_block_engine.inl,sha256=owRqTbae7NxXCxZsCT56eIy_ccqlADPwfapKrgnZG3Q,5053 +tensorflow/include/third_party/gpus/cuda/include/thrust/random/detail/linear_congruential_engine.inl,sha256=v2eyG7H1-4tVVXet3dPdzUC9Xzu07wUNNMiniSfS5eg,4910 +tensorflow/include/third_party/gpus/cuda/include/thrust/random/detail/linear_congruential_engine_discard.h,sha256=Dk8RMYvlgshZTHNmp47IywPu7Xr6BUHx7a4R4z6y1KU,3183 +tensorflow/include/third_party/gpus/cuda/include/thrust/random/detail/linear_feedback_shift_engine.inl,sha256=dD0vEwMpfG2pAu53_03yz52TwxHuwBxaF7F74fzYJSQ,4962 +tensorflow/include/third_party/gpus/cuda/include/thrust/random/detail/linear_feedback_shift_engine_wordmask.h,sha256=F-7WbZY_H_BIy7q6412Ft1ULxXEpVrNzX_BDlFHRfys,1194 +tensorflow/include/third_party/gpus/cuda/include/thrust/random/detail/mod.h,sha256=MmDmrgO5eq5Z-bidViVIME9VwPdlxQ8tJrp8oDWI7uk,1757 +tensorflow/include/third_party/gpus/cuda/include/thrust/random/detail/normal_distribution.inl,sha256=S_WA0V8KHCLcukvWlIIOvDJbT5QWU2UCz2QX2bxyTpU,6499 +tensorflow/include/third_party/gpus/cuda/include/thrust/random/detail/normal_distribution_base.h,sha256=sdvVD4PVxzmuaGWqnAMTiCHG56crnsnE2WA-j_5eyJU,4200 +tensorflow/include/third_party/gpus/cuda/include/thrust/random/detail/random_core_access.h,sha256=AkhSpXVVCZ_ZHEOkIsyAG3Sj_DqS8NeVLMncd46aYYk,1334 +tensorflow/include/third_party/gpus/cuda/include/thrust/random/detail/subtract_with_carry_engine.inl,sha256=nBkbJnV7Cb9k_JruvvMRxpjJNgHZRLGb5x5oHpMek0M,5896 +tensorflow/include/third_party/gpus/cuda/include/thrust/random/detail/uniform_int_distribution.inl,sha256=huh5g5-JjFJloxe7tzR8SMM4kDXvu5F3n5HL-Ns3ZZk,6754 +tensorflow/include/third_party/gpus/cuda/include/thrust/random/detail/uniform_real_distribution.inl,sha256=eQvzyCb2lN2gakZWkCr8WHE5AiMVSf_JBJWOv8JtajU,6699 +tensorflow/include/third_party/gpus/cuda/include/thrust/random/detail/xor_combine_engine.inl,sha256=-B7HU5-R9HFaWC8j9sLvcIkrNZk4w8PDfYpAeXNGF1Y,6274 +tensorflow/include/third_party/gpus/cuda/include/thrust/random/detail/xor_combine_engine_max.h,sha256=aW1qIesRwvuYUHQnHB2Qf4TEaEu1JHjpNhjO8uA2JI0,7961 +tensorflow/include/third_party/gpus/cuda/include/thrust/random/discard_block_engine.h,sha256=vxRiwuc-yNdDj1SKAnK1QkDVhWicdQ64GO8MICB7CJg,8399 +tensorflow/include/third_party/gpus/cuda/include/thrust/random/linear_congruential_engine.h,sha256=hQEtGnUGeZMqY_BfMAF1JItDtNsHpf8M9TKUbADIR34,9594 +tensorflow/include/third_party/gpus/cuda/include/thrust/random/linear_feedback_shift_engine.h,sha256=VBxl6fo7tVUIjHw7AfKsUyJl9v0pGzD22qL98NcJdlc,7463 +tensorflow/include/third_party/gpus/cuda/include/thrust/random/normal_distribution.h,sha256=gb1yEmkWyCDnOlmQshITl1ktYa-2ZWZNxB9QVvDacZM,9535 +tensorflow/include/third_party/gpus/cuda/include/thrust/random/subtract_with_carry_engine.h,sha256=vKOoWorOw5rD7lBQZQLcBTPqIPOjPONCc2o2K_iF5i0,8583 +tensorflow/include/third_party/gpus/cuda/include/thrust/random/uniform_int_distribution.h,sha256=9XF2-MjoDOnDLZSAGTkXnzhe1FK5BNMPJFrLyMFucYg,9527 +tensorflow/include/third_party/gpus/cuda/include/thrust/random/uniform_real_distribution.h,sha256=RUAAWeoUQliV9uK3QQLWZ4cE2qewCF7jDHbvV4_JtOw,9580 +tensorflow/include/third_party/gpus/cuda/include/thrust/random/xor_combine_engine.h,sha256=DBHLCJ9q7ydC97O-VHuXFY-Oov2Fq7q0RgkITf5dDSI,9200 +tensorflow/include/third_party/gpus/cuda/include/thrust/reduce.h,sha256=5aSHEQvHNYd77nTuZ5mNvrmjAdP1M-zq2a0nibu7ues,37631 +tensorflow/include/third_party/gpus/cuda/include/thrust/remove.h,sha256=-hwhV-AIGS1pRcIqomPXNn4tgGgTbJS3j-aarHWchss,37924 +tensorflow/include/third_party/gpus/cuda/include/thrust/replace.h,sha256=oeqIql7MyTNhBZ7CLI15xg4FseCNjV5ChJylxuAl2PY,33675 +tensorflow/include/third_party/gpus/cuda/include/thrust/reverse.h,sha256=bEJDycB8XHUAiSqHHDinDvsvPNyg_2sDvvdi5monlwA,8423 +tensorflow/include/third_party/gpus/cuda/include/thrust/scan.h,sha256=mr5PB-MCOE9HoMvOPpOCSyz0g1SEo1iXPfJeXKJtxA8,80567 +tensorflow/include/third_party/gpus/cuda/include/thrust/scatter.h,sha256=JO7GddnP_WNrEOO0PlIiTzXjjiWavJs3Ql8f_NB3aTo,21699 +tensorflow/include/third_party/gpus/cuda/include/thrust/sequence.h,sha256=N47ImFcja3CgkheQxHuf9FB56LNL6wVn_pvYx7aWwcM,11827 +tensorflow/include/third_party/gpus/cuda/include/thrust/set_operations.h,sha256=aBYyG31JoD1hEocn-HShuRZBISNgjOT-gzcognH6obw,186894 +tensorflow/include/third_party/gpus/cuda/include/thrust/shuffle.h,sha256=zRQK4DP7adNlVXsX6CCxSft-8_J54eeIKiKMyuCaewg,6664 +tensorflow/include/third_party/gpus/cuda/include/thrust/sort.h,sha256=pgSLl1HkjT7T855KFWV4gXHc-5y6C0hBR2Y5RFxMXlg,60965 +tensorflow/include/third_party/gpus/cuda/include/thrust/swap.h,sha256=qcXIALUDEpddMTQBxRT5_vAgeLaCreV8mi2URzf-9Ck,6737 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cpp/detail/adjacent_difference.h,sha256=W32emQRtVVKSvTy46xQBz9szmwSP-pw49z7gIrB55C4,777 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cpp/detail/assign_value.h,sha256=CjOUscYJj9D3frdyqH4ZZr-SWM_j1sUUvnnBFDVox0E,763 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cpp/detail/binary_search.h,sha256=T688eKmvv_jR6c4vpR8vg77uOQnLULmMq2rk3AprJfA,801 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cpp/detail/copy.h,sha256=vmc46XzdLu5TknPy6W2gRLFXIBFlx5eiagmp-5xCmOI,747 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cpp/detail/copy_if.h,sha256=vZCimXUI4rajtASujKcbUV1vFegiuGAH4Rdow5nsrl8,753 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cpp/detail/count.h,sha256=GQw_WjMkFnETvjsLujKULYTrAw9gfznbYTx3biCqrDw,725 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cpp/detail/equal.h,sha256=GQw_WjMkFnETvjsLujKULYTrAw9gfznbYTx3biCqrDw,725 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cpp/detail/execution_policy.h,sha256=39y695N6DL_SKZoPeLUVv3HNcWNY-gpW1vo9WyaLD9Q,2075 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cpp/detail/extrema.h,sha256=p3fg-U_RXXeYQmA1W5SiErMubrb9EBmJYqc6b8sGGwU,764 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cpp/detail/fill.h,sha256=GQw_WjMkFnETvjsLujKULYTrAw9gfznbYTx3biCqrDw,725 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cpp/detail/find.h,sha256=Qa5NTEipV1UkVYqITYTtgzPH1Lx6ZbdkMgCpsbv3cK4,747 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cpp/detail/for_each.h,sha256=Qta225XupwdqspNMoo3JDXl3Yi59bGAKpLcRbm3q2F0,755 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cpp/detail/gather.h,sha256=GQw_WjMkFnETvjsLujKULYTrAw9gfznbYTx3biCqrDw,725 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cpp/detail/generate.h,sha256=GQw_WjMkFnETvjsLujKULYTrAw9gfznbYTx3biCqrDw,725 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cpp/detail/get_value.h,sha256=U2EOxxlwv_XmkKDZgSDwgXZe0b-0bQzDu9XNPjuMyHk,757 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cpp/detail/inner_product.h,sha256=GQw_WjMkFnETvjsLujKULYTrAw9gfznbYTx3biCqrDw,725 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cpp/detail/iter_swap.h,sha256=tKvco4uBsAdE34t3vrDR8xSE162IfySX6lqDU1Kphug,757 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cpp/detail/logical.h,sha256=GQw_WjMkFnETvjsLujKULYTrAw9gfznbYTx3biCqrDw,725 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cpp/detail/malloc_and_free.h,sha256=_xboR0pEYs-ONEGGLWWiOP63wobuHyD1FtmF-KuCxNY,767 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cpp/detail/memory.inl,sha256=bKiLCD_Agh-S7b9aFzYJUtLP1l2eGdX2vPR-uPoo5MY,1346 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cpp/detail/merge.h,sha256=Ip4vCpEHoxWpJHQOFl3EJFFw6fHtaO9gbCGmc6BEcZg,749 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cpp/detail/mismatch.h,sha256=GQw_WjMkFnETvjsLujKULYTrAw9gfznbYTx3biCqrDw,725 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cpp/detail/par.h,sha256=95E-WdJO9gOEdOQ3ghqZAMSfE8s7zKvf3t47V2UF2tk,1340 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cpp/detail/partition.h,sha256=CApTwsfzh2dwTFI8YTiduWfm150yIrlyPDjadyPzrs0,757 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cpp/detail/per_device_resource.h,sha256=RLtmp_wJ628sYmbP2RzVO0ZqCi2_fOAnl0ZGwH4pBk0,723 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cpp/detail/reduce.h,sha256=TouI7M3N8Pa4eltfffbG7gLP-2ifhJ8MhAccr0ZzaYE,751 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cpp/detail/reduce_by_key.h,sha256=JY0a39Ox51t91kAvijXAyOlyuCot-TnfFKm6c_47Fms,765 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cpp/detail/remove.h,sha256=3SpkwtSxB1m-fO9tbEWz4ktYPBoD9bfxefHn5Lm85gU,751 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cpp/detail/replace.h,sha256=GQw_WjMkFnETvjsLujKULYTrAw9gfznbYTx3biCqrDw,725 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cpp/detail/reverse.h,sha256=GQw_WjMkFnETvjsLujKULYTrAw9gfznbYTx3biCqrDw,725 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cpp/detail/scan.h,sha256=XjW900DW6z-hzSG1R2ghK5I-jhWGQvOH3CmWl9aQuMs,747 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cpp/detail/scan_by_key.h,sha256=WIqkEYf0pG32oevHBJcqW0TcVhmMzjVcjpl6YNE7NW8,776 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cpp/detail/scatter.h,sha256=GQw_WjMkFnETvjsLujKULYTrAw9gfznbYTx3biCqrDw,725 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cpp/detail/sequence.h,sha256=GQw_WjMkFnETvjsLujKULYTrAw9gfznbYTx3biCqrDw,725 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cpp/detail/set_operations.h,sha256=Z2y0pvr0b4lGDr0xUvJ_QI4TiBiq1H3IZasDOeBNwbA,771 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cpp/detail/sort.h,sha256=JFzP6_hfBX5sNTX943ZG_o23LQgIzCkDuqMSSvPH_PQ,747 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cpp/detail/swap_ranges.h,sha256=E_6ubAowa1Kx5Uj0vb_9g6Dz_jfQIu-DE4d1beqQXJ8,702 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cpp/detail/tabulate.h,sha256=GQw_WjMkFnETvjsLujKULYTrAw9gfznbYTx3biCqrDw,725 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cpp/detail/temporary_buffer.h,sha256=bbrFO5T87NoZAa4pzet9tlDXbaabzNsr0riRCMWYfhE,725 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cpp/detail/transform.h,sha256=WVzyFrMgmL0xxczZ2xWPUa_rzyBqa4Mxujo57dIbvAY,700 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cpp/detail/transform_reduce.h,sha256=GQw_WjMkFnETvjsLujKULYTrAw9gfznbYTx3biCqrDw,725 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cpp/detail/transform_scan.h,sha256=GQw_WjMkFnETvjsLujKULYTrAw9gfznbYTx3biCqrDw,725 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cpp/detail/uninitialized_copy.h,sha256=GQw_WjMkFnETvjsLujKULYTrAw9gfznbYTx3biCqrDw,725 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cpp/detail/uninitialized_fill.h,sha256=GQw_WjMkFnETvjsLujKULYTrAw9gfznbYTx3biCqrDw,725 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cpp/detail/unique.h,sha256=FdwN9qUKPKI06zhfR1v6vs7XZCwwh1ZHnvI9eRT-xNc,751 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cpp/detail/unique_by_key.h,sha256=ekrEiX4tF17iEMQCYOq7zhuEpXTfjBtlMZx7_7fH3lg,765 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cpp/detail/vector.inl,sha256=xZDCRnQ_u2I8IhPayRW_2f4v20HUx5r9ifsIjg1TiEk,3535 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cpp/execution_policy.h,sha256=ioZGW0-2tvo8iYeF8SIwfJ673JDPx79c5fu-WXrp7jU,5152 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cpp/memory.h,sha256=8mEkQ8Ecw9kwtpCaEL1KZaPtSQ3E0HnXnxPejYGxQqU,3356 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cpp/memory_resource.h,sha256=aCtvGs_qWM7qxAFKemlK6bi3_nYRyuEw3a4_V3Lvygs,2007 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cpp/pointer.h,sha256=4UFh6xUPcMvZ0Q6cMpSa_XACmxTbGTQVFB85wDuVUhE,3773 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cpp/vector.h,sha256=DAahoFgM2qXQleNklLeHPgLRst7wYGaJi2zOHi7sJ4U,3166 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/config.h,sha256=_YuhGzvyHo2Mekte-7xRj82yrp5m_dgZPgLgtLcjjtI,5328 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/adjacent_difference.h,sha256=kLWV9Uuk_bMY5qdf8c-CCD214KWjezRax3r84tlY7Mw,11691 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/assign_value.h,sha256=vdnS-a8SLZip-br0_95STKHaCy34APX9HEqKEV8ITyA,2975 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/async/copy.h,sha256=-tGWr0l8UWi3cvdmQg-EbbJFNHJD0xrGWep9U7WF92M,15870 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/async/customization.h,sha256=pPIY57mkBFqPqZ1oI2B0EOJDwcFbGuelXkIMyNrKvMI,4424 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/async/exclusive_scan.h,sha256=LS3Bf4-8v1qOMek4Ody9g5vvKHRohukzHvxw8nzAGWg,7117 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/async/for_each.h,sha256=93s5PlwLpzo2ihMKaMVcBN_0Q598SyiYCYIDJ5LRnGo,4562 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/async/inclusive_scan.h,sha256=vaMOgHi1a-pKz8cY0ri4n1qRWJM6OXB7r9IT_X2K9Oc,6887 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/async/reduce.h,sha256=eoh6fBm90bIkGauMcQuCjvSePzl969EFArQLEuXDU6I,9060 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/async/scan.h,sha256=Xw3qRWLFLKZed4k9agZyKoh9Bu3NZKww-xDkZFZgEX4,1920 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/async/sort.h,sha256=L339moaKVU46HKDBWPyASskOb9IAIr6HFqXAFzD6F6o,13297 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/async/transform.h,sha256=VuHdMBeX1evZyubFumbL7UoxYjWmTXu9zrYr3eZctCQ,4865 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/binary_search.h,sha256=F08yu3Gs_vBuisSDS7W49HWDyXv3rdehooiIGot0Pas,669 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/cdp_dispatch.h,sha256=8i-25R7YhqQ02w_T8xxgcKqMNp6DRNIVW85fmWWYinA,3268 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/copy.h,sha256=dyFZHWVnYD7hR5VqPNawtCCJGtMsu5REzj1kSZxCov4,6472 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/copy_if.h,sha256=Heay_7OQnpE-prTfqfVNHzBuqKyCj_8Ymxablq8wk2o,29007 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/core/agent_launcher.h,sha256=fZj0IdYV8icgJ4pwG4IrMw4MgWevht1wENlc7jB1B88,56831 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/core/alignment.h,sha256=XvguKp_lTO6P3QqnhrB2mc2JomKYnYVX5T3SqRoU2Dc,4227 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/core/triple_chevron_launch.h,sha256=BZMdCJ1zDNzr4JytptIedxt-4qq_SjaSLA20qsw-uv8,5155 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/core/util.h,sha256=bRnbGuiQlfYkV_PmY0KE8SLwSmHdvOHSJviWbqLVcF8,27432 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/count.h,sha256=bIZ7PMb_a_jm8WQTERVvxTq-cOIvpoJDTnNXIAXzxMY,3412 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/cross_system.h,sha256=mt3LwQjtf-WHMXkI3U-YkNIsx7MmRQNNZm7zMA7NGcM,11581 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/dispatch.h,sha256=14lMg7LMkjK_71EnvPHXJzzDaI27Xu0RomQL3H2BYt4,3678 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/equal.h,sha256=xjd5OnvDWc1dLolNFhkIJs3w7ngshaKGon_zoNqSkbU,2990 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/error.inl,sha256=EZAuS2xe_wjm7furhNlVIrjgVzB1NlZikffeWwb9gco,2351 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/execution_policy.h,sha256=kceWEjTpWPsS8NaRHo5HAqYsCUqRFILOIWx5RT9JT4c,3185 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/extrema.h,sha256=nBDEvj-dYEY1Hz9vKwwyY_0Skc1pAkI1bkFmGPYYT7g,19192 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/fill.h,sha256=VkqE5aZc1wyiCNCiaWjoRZ2kGMHCbIk_oohW14AQA0U,3288 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/find.h,sha256=nlOZHjrAai7K3RqRupaN_EIPlFqVG3-EaDbB_8rDXX4,7127 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/for_each.h,sha256=P4Cst0hpGSLaejW0IRdBnHYaLpRMNGxzouZB6uk5jGY,3744 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/future.inl,sha256=ED--dOi-4GDI3Zr2mzpIOwVnFe2leIGI4hBgk5Wea0U,34440 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/gather.h,sha256=yaEg9pce5ccSFfzejHwQwqo9paxDHqUAf-W75kde15o,4134 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/generate.h,sha256=BNR64W93Px4DHu32qZYMSeQUVUDo9bl3S3GSkTGMTIU,3305 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/get_value.h,sha256=dmiVVZas8Wy4uKvkG2S9_hhjxMQLr3DmqH5dHk1DszA,2538 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/guarded_cuda_runtime_api.h,sha256=E76JAI2KQ6kjRSheLbF2fLW1iMq-dlS5G4eSRI7UyUU,1185 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/guarded_driver_types.h,sha256=-nT7tB3VtQFkjJkzM3Fr1Wm90R2BqLKVPsILOY_7vZU,1925 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/inner_product.h,sha256=8vnAadlr-Iv1X4dF1n55bLRkdFrjzThLZaWa_wa6eDY,3886 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/internal/copy_cross_system.h,sha256=1MWsgwfLI4PMoW87h8MPdcSD5FUNaSjhgPrPpSPAcc4,9487 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/internal/copy_device_to_device.h,sha256=fg7VnS5WpFqUyOUdt8v70M45HoOJxZcMEdgjkMOFRjY,4527 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/iter_swap.h,sha256=Xj370cW8XQXilyoGO9kf6m3jlhANiT5-1zvSBULZe4g,1716 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/logical.h,sha256=GQw_WjMkFnETvjsLujKULYTrAw9gfznbYTx3biCqrDw,725 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/make_unsigned_special.h,sha256=Wmvk7g_fHKMNp0UcA59L5YQNWkARHcosMo-a7VOosDU,1221 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/malloc_and_free.h,sha256=eIodDTHqJZ76cO_qrLVe-4uCtI6iv0OtSBV_zxdoJ3M,3728 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/memory.inl,sha256=vu6ngIdQUJhZJ-VM47xs-KqttTkFFmv7olJDR0xssU0,1378 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/merge.h,sha256=ekSwe-8LRAc-3khHKSqGnQO1RCGzJZCDnkU7VnOwOXc,35370 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/mismatch.h,sha256=qclpoKTcSu1mM3zi_wtS3Y_PHwv0if4zZCRnbsnkT3w,4575 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/par.h,sha256=9l2LGkQ-PEhbP88BUjWCA_WZO6OLkyqDMDSRt3-TQaY,8060 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/par_to_seq.h,sha256=EqtU43fmZaVYR8nEdKcRpMbzg0-Pd4np97nsJouUB-4,3070 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/parallel_for.h,sha256=SEe4InkaIYpyyKEbC-aF5THzDDlUW7sYGtv8h8Z_FCA,5683 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/partition.h,sha256=04oC9NopIrU8VMXRxh9zJxRM7t41bsPNdGdw7Oh-xiE,38777 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/per_device_resource.h,sha256=vzS-H_mfHRVToyz-uWI3NM9BCTGTgOOZDwQezy2-C8g,2637 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/reduce.h,sha256=l0WtqD52z5uB5HmgdFyb6lOREJlUS2txFOatgkz6Xo0,39246 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/reduce_by_key.h,sha256=z5RDyOYn1CzmZDuoSyV4AzC2RyS4IaQJyYqyIiJivA0,46036 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/remove.h,sha256=yFnX9ljWCKGdM5a3g_IFWnAO1l0rUnPsfmKWDvSVBzo,4764 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/replace.h,sha256=ny5SENPaQY2ku9pT6ShuGCa5GItQzZnJfk_TpYtt6Hw,7294 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/reverse.h,sha256=8KRZ75PrSVPq05uXwQelHS7rgKcoxOruLLLeqezu5ro,3770 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/scan.h,sha256=ul8r2Udu_P-84AtpshgiEu_7gFxXFnZ-e9Ebfn702bs,14325 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/scan_by_key.h,sha256=51fqsjcIhEF8nieFdTxlLjNlTqhX6LZhHTcY3niJTyA,18657 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/scatter.h,sha256=SAi44IJ4EuWvMB-O11eBO7RM9k-UT09Skeufv_kK4Ao,3980 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/sequence.h,sha256=GQw_WjMkFnETvjsLujKULYTrAw9gfznbYTx3biCqrDw,725 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/set_operations.h,sha256=e_XEVE9GEndI0-fCyPsEy8SuGwmxKXzM-ZscXMppaKk,69146 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/sort.h,sha256=qa-dtCsoDKDacrJN1F_w01moSIr_Rzbbh2PchA4IxK8,24404 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/swap_ranges.h,sha256=K2QGDNwEqK2ygdSl7dgQ1Ga4es2P5OVpo1WmXsNIblw,3813 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/tabulate.h,sha256=JX2SIcdKPBNiglRFS2aRo86I6vz0RKjE3RyJj-x6W84,3145 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/temporary_buffer.h,sha256=MfkjjK84pVkngfpH285idySHWZWJhK0J7TebnQZgAHs,725 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/terminate.h,sha256=bSB7EgQPNOAsITG-JrFoJQM0SwOUVLlvYBbCQm8IQu4,2218 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/transform.h,sha256=p3YXHzYB_q5Ho5PjIvKkZ9gvGH3mmZ1LA2eCjlGADVI,13521 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/transform_reduce.h,sha256=M73uLKCEO_MBPStP5QaL3BgLmewl5YrZvIQ5kct5zEs,3052 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/transform_scan.h,sha256=Py1Mt5T-6u3orWXErGKnvPvQXAxy9d5Ppw43fRxJkoE,4838 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/uninitialized_copy.h,sha256=2Vt4kE9pim5BZFffY9zN_BWqKuoTKWnnJDSAQ-nP14Y,4129 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/uninitialized_fill.h,sha256=Qwu_SQgBM5aDngYa9MXqQJLTU9cEi6JS0kW_s3uIffA,3924 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/unique.h,sha256=MhFIhYINSvGIRtjGDXL7tmcSexGtQSppookVKA3U2H8,28154 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/unique_by_key.h,sha256=AEa7MAo3QK5wuXMnaL6_iKnGO4ZztHnF5qpxPW-ShBc,32569 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/detail/util.h,sha256=BuqEw2LZYPDYdz5VxllJt_53mKvAIiIibz9L_uu5RAU,16605 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/error.h,sha256=fEzGPrfSkxJWGuiXV_mGz_g4BMt-V_qHYjMZwEDhXsw,6921 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/execution_policy.h,sha256=0JYcchwbXGpT2JbvpWIwUs6fypSK4H9nXK5ZEgnBCbk,1889 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/future.h,sha256=IAutZPn2u5asy_pCspYx5jbkPVlpsYTd1yB5UjUGxhE,1529 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/memory.h,sha256=GQj9Bo6o5ogvXQv9MPkP2FXtTLUzAKpBo3b74iqNXIQ,3672 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/memory_resource.h,sha256=M1Tw81mKpCzEYDTuGbariyaLgsxk66CkTN_D3HM1bLg,3903 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/pointer.h,sha256=sMI9KPafCM_otbPdBh1oNETA3sj3jtAbV3X4dJH-rQU,4433 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/cuda/vector.h,sha256=htSI8qw0DY8G6eMQF2typb0EzHH0WusCaFvmtK-OCqk,3269 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/adl/adjacent_difference.h,sha256=p-b7_mJtQnKya-iw6EzzVJIw6Ru9-1NAqK-PxjWXM5s,1839 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/adl/assign_value.h,sha256=tGhG3cGbQWwX-UH_VrZmPMMwKUaTKUrhKO05md6rE4g,1734 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/adl/async/copy.h,sha256=h6OMIW7bbd3VST8iQaUItDcj-vqEBKqr18J_0w8autg,1315 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/adl/async/for_each.h,sha256=oKDmCqKSW5kXHOwL-oIyDnBhB_a8aiDyWPKagb-f9C4,1359 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/adl/async/reduce.h,sha256=yd_16QCDLjqUc20EEInaXVgannzggUx2wD9uDuy0miY,1337 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/adl/async/scan.h,sha256=Hs9L8Z3fkQvTm-7KugQiDdN-VZh7LsVBsBdJoD6bCJI,1316 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/adl/async/sort.h,sha256=oy7MyxcuNjP_LUg5rm_Gue5AzGEhp3_i8EWMrYAL-hM,1315 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/adl/async/transform.h,sha256=KEy6besC9OldpB1oR0AKQMnpqEN8Vl-o0DCkFHQjH7E,1375 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/adl/binary_search.h,sha256=z-kkgEnP7N0eFxuIw9PsaztZ51hchLVXumTAcUwWOo8,1749 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/adl/copy.h,sha256=UoJEkuP1zsrkrfYMPgojSH0b9BS72uQg5qJH0tlJbhA,1614 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/adl/copy_if.h,sha256=7V2W99NC02THB9AbCcBn2tx6woOzW1JPQD0G69IP_fw,1664 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/adl/count.h,sha256=oLI5K5vdM4RnB_OjfNTB3QD3qkuiakm04SwbWc2Du0I,1630 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/adl/equal.h,sha256=HZMV1bsS0dBOHbB_V-38HpA7y-Sxxd-lvCqknvR6_mY,1630 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/adl/extrema.h,sha256=EUIFBbRimeXIC4b7NmL6fubk0iH6T6Ni_osFijJH0AU,1662 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/adl/fill.h,sha256=jJ6AsTvYXYT8Ge5PyvlCa3nGCRfWfrrcJkcgw6bGd-M,1614 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/adl/find.h,sha256=ppeuo9rP5nKobO0tidgnR4M15iZvSqGkoRAJbCHRlXM,1614 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/adl/for_each.h,sha256=bNlkvtx2ldPMWPWbYkRS96XaFvXtbRnq66S_zrg99HU,1674 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/adl/gather.h,sha256=7rC9Zl8AKk-uS9cE__mwUnp1ilw9CdWBy7NqR7dRPtY,1644 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/adl/generate.h,sha256=PX0gUIg-UkSRt0zNApib1TBEd9GRlYZdwRSFRl23Rfs,1674 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/adl/get_value.h,sha256=-VNISGspqfMayg2Q_pJfYOl6JREFcNYEiSDLvkWeNUk,1689 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/adl/inner_product.h,sha256=A3RiSJpfmL01fuGSlTKBI1GJwZk1jucEJfPWxkMqVPA,1749 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/adl/iter_swap.h,sha256=cLLt0htr3fw8dOGL__8KFVHx8mWIopNySBSMBsBuAXE,1689 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/adl/logical.h,sha256=BrezRf7beIwGriej6cZ_-azICPivcEuwkEN2e6ijVc8,1659 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/adl/malloc_and_free.h,sha256=XNfZRvIUSfnan-eu7gl3I51gL2djJ3WQi_sErQEwXo0,1779 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/adl/merge.h,sha256=z1M2OqdZeuBie2g3M2mxCiMafHTFrkv6NC4hL_AZe-0,1629 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/adl/mismatch.h,sha256=z-3VqIeVs5Ic2DSj_U8y55otEdSbgd7kZ4mgueEwgnI,1661 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/adl/partition.h,sha256=l1SZkz-ZRAyUqur9LD1_5oG9BH40X_l5perqoSjvSY8,1689 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/adl/per_device_resource.h,sha256=1J1ToNyfxM9si_yFnqN0wMPFbG9M7JQ2nC5EZuxQcHU,1647 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/adl/reduce.h,sha256=HITFVQ8cSc5bCQnQKjPAHsuDcqSgMYRk42YkFuSd2mw,1644 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/adl/reduce_by_key.h,sha256=BxDth2q0oWvlsEFFPbyXc8K3E-gjstg7Uze-DFNo_pE,1749 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/adl/remove.h,sha256=7m00QK6ww5wo3JToFLJZCI6AOsMZItFOZfB9jcMohUo,1644 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/adl/replace.h,sha256=DIEXM64t6LI4ts-8tnue12T1SdodU35q9lRkta-f36U,1659 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/adl/reverse.h,sha256=rplw9cNO_IvnJLhZcADldrLeqnfDnXbDMyIpTNzILiU,1659 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/adl/scan.h,sha256=hNSRMIaLkoLZnnVxWH9i_dVynZX4k0OCzHjOXcxwk3E,1601 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/adl/scan_by_key.h,sha256=ALMD6OPq813JWLw-4vDwV-DKSGK6T_0iUECSgUI9W1U,1719 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/adl/scatter.h,sha256=ABiKe-U2MChUNzgGAU_ANZNxlVWXgB8hgdXB6ZEZ-Dk,1659 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/adl/sequence.h,sha256=9GUHw1gPDBf0DvLzpZZx97FMogXkKyylOuxdSiSM0p0,1674 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/adl/set_operations.h,sha256=J-Jf0dsJ8K4R4dJzAwBYT8WQfzdxePgxSLFIWgaVvFU,1764 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/adl/sort.h,sha256=gayIsLNoIn5KZhPJoFoucxZOfcomgkyCbfE4i8yRYyY,1614 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/adl/swap_ranges.h,sha256=iwHkTp7CYBu7bdT9SAIIyIpcxxO3cHkL5e9v4otHs8o,1719 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/adl/tabulate.h,sha256=NbZGSHgr4tjrMtMmO1jru8y24zZbGxo8j7E4SNjSP4Q,1674 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/adl/temporary_buffer.h,sha256=Xbkt4I4fYDnetOZZFze3u9T9fLW5kUoWSNXE_ioLMyI,1825 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/adl/transform.h,sha256=2HWymqXpmfKI25cjGqZLyshaNEN7xnjW6a8YrC7wr98,1689 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/adl/transform_reduce.h,sha256=AxIeUs7DZzwuL6p5TLxib93M88sFNZkVhs7YSxARrU0,1794 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/adl/transform_scan.h,sha256=k756oybQR7T4GIZJNt46dL8c7_O9sJGEV9YF-sQFggQ,1764 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/adl/uninitialized_copy.h,sha256=3RmkPBgHk8mPwWUmUsp1icfnvlGlfvYG7DwhlaXV-EY,1824 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/adl/uninitialized_fill.h,sha256=pGnDpynYG0YrKI_1SDZwhtn492IIRYQ2KsRcHmC9PR4,1824 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/adl/unique.h,sha256=IwElOiupFM7B_s4fPEthlCMAs1WC4j3wE0YWDtxr1fk,1644 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/adl/unique_by_key.h,sha256=Qdqbhw8KHBTxO320gkXnqPZ5GpsOXIG6LNcTkfpgWh4,1749 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/bad_alloc.h,sha256=3qrWvyvtlBs2Na1Zu5e0gqwcho2m3E2e0Zce-PHN_4g,1337 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/errno.h,sha256=FSlhHWa1u8xzWNfgVkrq7Q5ePOe800WnZ8fPZMpE1c4,4271 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/error_category.inl,sha256=G5zg_S3aua-5Q9IxM-mx5KxcpQ50MlVleoPyX0EoGuo,9628 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/error_code.inl,sha256=fdybJk19zUZjnRLm0En6hX-2yjLkQCM8-Z7by4vvy8Q,4539 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/error_condition.inl,sha256=4ftVdUA2snho5YXTpnZplFnZclxTUVW5SMn3cyuCMqM,3203 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/adjacent_difference.h,sha256=-anEUXZCSn_W0zR5BJI01tAQ2h8aNW9_FCbg5Uxq8OE,1786 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/adjacent_difference.inl,sha256=DWmIe3q-xWSKKVa4w7EcqN6I89-X5MLNFr5cHrceZ2I,2697 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/advance.h,sha256=F53eU12kZEu3NOWUk5iPkS0mGZxIvkjvUDCrJyy0JP8,1021 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/advance.inl,sha256=lQz0K-wykBpb3tjiLLayGUp_a7c6KLHxLrKR6Jx7W2A,1744 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/binary_search.h,sha256=W9pJ-5Zdyv2sW_M8HIQKDYxify0i8sg6yHZOA2cKtJg,6884 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/binary_search.inl,sha256=cLMg-ye_4ski-OtvDoAFCZAt7l03UTg3a9DqrFJihiU,14695 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/copy.h,sha256=4-hJKyTXTMaDERp-vX3T5UITAboXGtehUVy6W7Fh_pU,1594 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/copy.inl,sha256=vqL9WR8bZR-xum8VSiant0WcMxjgVCYp5Oc_WZZU5vc,2690 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/copy_if.h,sha256=UQ6YPcpiTfniHqFxoy_rwJ1QPoZYPsno_b2Cw2Hiu2s,1850 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/copy_if.inl,sha256=R6coYb0Scw44yL0IrkhzNYgOA6sNKJo9ik9oSrhuZK0,5234 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/count.h,sha256=fgpsZqkeiA-KKItZO-dzbvh4g9S9vtq8lg1pFXPbuOw,1530 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/count.inl,sha256=vQsAIT3RbzfvMMzSWk_IIySjbp1pcPcHcysdv0SjC4A,2473 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/distance.h,sha256=_jkikpudd3_sxEvHBXCWYzynZoxJ3MoXqlVa4ABh-J0,1133 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/distance.inl,sha256=WCANM8NXpYH7rUJwS2g1HyAJQIv4jPOnRR7HKhRNUZE,2124 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/equal.h,sha256=BWCKuKVrqB0ZBWe_oqX1Qntowcn5Y6eWjdgPq-fElGw,1467 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/equal.inl,sha256=HU8WQAuBKMuuDPfsJQ66vYyuW_biHb_MnPTS9LtnowY,2020 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/extrema.h,sha256=Wk9lOpQEULPzWU_DdmQLvhBavqpIpfD8ldofUYDmMfY,3080 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/extrema.inl,sha256=leE_Ga9hu3ROFyoMEZBO8yvjMO3yvjg5Kh203QsaLBQ,9522 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/fill.h,sha256=zL-W5ZnPy-FURUYGjOaelxrY3WriVTRyRLudjbfSsT4,1814 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/find.h,sha256=Q19eRWMqMTJSABxt6BGkkXtLyJiX1pMHH-ezyVSbUO0,1820 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/find.inl,sha256=L6mHyqW7fkaG9EeoQ9dVumvQxp11ydmRyJmKiyt0xRI,4606 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/for_each.h,sha256=umbzKB5iuClg6H10-3QHCnBwXW25OZGLlzcFYT_oKAs,2155 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/gather.h,sha256=XY3Hm63l0bNMjHUQqDAf1QG6ZdB9BKLZDS8hFYS63U4,2915 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/gather.inl,sha256=xMBdDWcmV1zfUoO1brYBKX1XqtrZ8SgTlbjd0YlqsYA,4258 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/generate.h,sha256=tM0l4Y9okWZt2d4OW5UWgWFWtsGuAwBOkRt4XvqscO0,1595 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/generate.inl,sha256=pHKDE8Kd5HYSzEyFwzY6l38mPdmlu3QqINPzlE_BlNM,3865 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/inner_product.h,sha256=ctjzd7Y48GPK-Iaz-m191FTDqYGNGu5o3EJKmb1wjyU,1894 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/inner_product.inl,sha256=J67ToiOnh7Rv8FZundbtsUMAF0Rq3KGubxCkp7CoxiU,2626 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/logical.h,sha256=fNEa9WKq-2UfyrQhuPt03FPcJ0gUkQYoap1G2Qe15m8,1828 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/memory.h,sha256=Nb4xhEe3iq3Ll2LjKCzSCq3YFwPbjczDf5GZpKI4_QM,2078 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/memory.inl,sha256=Tlkh4VpdMqExVxPu82l4TLAoGVv2jW3ZkyLyAg7aoJs,2876 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/merge.h,sha256=AABdjYSJpG9WrzwKrZltbvR-2On3ljJpRSZPR4gswCk,3335 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/merge.inl,sha256=li1r_kKFEAxEcG4l9oe3X1Zlbm8jh-05pX-1fdB8H-g,5275 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/mismatch.h,sha256=dNkxBRpCsHQ3wiO8uZE8lFSFqs2_3sjE48FZ1Uju1Rw,1653 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/mismatch.inl,sha256=5jFXi-c8-D5SR8Nx8UTHFDNSSkNRL0trz94LifyuVg0,2479 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/partition.h,sha256=DyMZJBiZDVmn3API4mnEYFkS79q7NYCAKX5UbqmFgAk,5622 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/partition.inl,sha256=04xSQj3lzEcVqGzwhhlWbijvUnAkjWGR71zOjKr05X8,8845 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/per_device_resource.h,sha256=i4yano3A3PrPVmT9sTRQL6ELuphLna6RdXUINEU8QTc,1181 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/reduce.h,sha256=ThLcMfOFGfESc_q1jCwKZjSuJp_EMrS1JgQG7MGX1hQ,1712 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/reduce.inl,sha256=1ajeFLAkzs8Tjly8EsH9muuSAiqbhdqeVM8VGoiQIV4,2374 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/reduce_by_key.h,sha256=KA_EBlK_Yu0cGGGZkswoI0_PRbg4RKaTP14upg5eOIU,2862 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/reduce_by_key.inl,sha256=TI_Gg05BoqxGmaV3_o03Ggi8OyU74Xk5sZPimktt-mY,7101 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/remove.h,sha256=OInfu3dRi0gMZwb1GRZj0yOcymwtC3BCryyowGQv1Ww,3501 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/remove.inl,sha256=W5_lmdVBC4BCrEi9B55NGWWbVnIg6GzT4bOn9HZIxCQ,4852 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/replace.h,sha256=lvxkT2QyZOh_px04MmWSOALcV34XIdZ5Tsdu4ghay_E,3478 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/replace.inl,sha256=jcNwPxt0JJhy8ZhM3oM-WWfQpSohs29IQVs1kY0Unn4,5734 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/reverse.h,sha256=L3IyoB5Xk6i_76Uj08zE2NQs97zqHsNf8OcsEP_JlJg,1566 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/reverse.inl,sha256=CDDKU5PSKaqI8EA5dOEFvq3CIyf_m0Fg6bzlPkoulpM,2340 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/scalar/binary_search.h,sha256=XP7MpQMDECXJtk0DpDXzHxKNaxt2rl6FQeXpeJjTR1g,2673 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/scalar/binary_search.inl,sha256=rSePzAcq2Kz2XV2Y3zCPVvkoAH91r1Tylj-JlWh7Azg,4320 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/scan.h,sha256=KfLRufp54PbQcaAb6rMNJiYUDjhFUpEkzm5OqZq46Jc,3226 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/scan.inl,sha256=vjYr-6kqPCDSo94NHYomj_6kTcUqSGEzw6mjeXGG2-M,4151 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/scan_by_key.h,sha256=kGITDGkpmHvckFFdzCOfwG92HkrjFX6xtZSfeOh0pbU,5309 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/scan_by_key.inl,sha256=2vrQyq1xP2eG3bxAMc24hM2Ls0lIoTGUECgJoCnkUFA,9479 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/scatter.h,sha256=pEN_Ex8F83JpjwDDLDxaBMVNf3DbviRZT24twb459AY,2330 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/scatter.inl,sha256=rTBNJH0Z4jfZU_3OCcxgjjvJxhyM8rmljBnCEz1Qa4s,3165 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/select_system.h,sha256=mse9P0DEuxc0T1P3ZDx0unlw7hLFrqHEJnTkBTOcH0A,4713 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/select_system.inl,sha256=AwLTSHYnzaDGCbVkgCRGhwm9HD4dRXFwT4gNcPq_wXM,6033 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/select_system_exists.h,sha256=ex_uzb-r1_aj7LU5-dnhqLHfM-9rhhbX6-ucGYXsyE8,4985 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/sequence.h,sha256=kmXpGOy3tfkumZipVNKaNFgD9K90u0h16eksR_5UpnY,1723 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/sequence.inl,sha256=2m-m7TAqWSzOiv3OoFO1wYpEwpKSaavFqn1apFONY5s,2718 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/set_operations.h,sha256=isxlQtHTVJLWvSdhcQWH-fYZZGua7N-EP-DLSCx9BA0,15559 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/set_operations.inl,sha256=fPHSELyXnceVPN3_b9F48zcq1nLoQkLpNmPQxTCx_5U,22743 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/shuffle.h,sha256=saQPjRLl06FrXxoBSCreqEmXV6p2Vuo7iGixcdKGU1o,1624 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/shuffle.inl,sha256=qauE9CED3fQINvLDyCjFVKMhGj_zC3jHDKPwBWoGgdo,6848 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/sort.h,sha256=-g7YENN7Ax8f4qZD9AZA7C51U6P_VYOTyFA_PCsTXBo,5028 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/sort.inl,sha256=6ymcE7K6jpohxzmPaMzpyZm2ncdaIUUDvMWijp7DTIs,7399 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/swap_ranges.h,sha256=LjPVwVetxsaSqIxwbQb4WS853CnmVw_cc9MnA4aJfJk,1326 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/swap_ranges.inl,sha256=DY-K-30YX-Pv1AV-lPHbdW0eq-lflpm27iqAWUMAN7k,2397 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/tabulate.h,sha256=oweIq60GjqH60zq4rVueLHs0G6R80sk2Ra-2V5DrLQI,1258 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/tabulate.inl,sha256=zLSNSbJ4Zu3ZRZtaMiKoaRGb6UvPN4MQyqyyVzoG7qQ,2056 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/tag.h,sha256=Q9Eywg_AUVOkKgz63untxaEYwfQMSvVI_0Y4B6vOuxY,1153 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/temporary_buffer.h,sha256=_the2sTxenVRY9ljzX16v6WClXYvVheQ_-xmx_LIEfA,1704 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/temporary_buffer.inl,sha256=EG9Q-asLEjRX8v5mK6JLoVa1dav6lkCxrI3zJJPTxmI,2948 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/transform.h,sha256=BP9i34xh8Jh1biLxGXYMMMWWurEr4berwhPPJZrFX4U,3726 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/transform.inl,sha256=p3XoyrPnNnQ4-FiuDzZHHpiWNHFb7dE2hO90uVje00Q,7211 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/transform_reduce.h,sha256=YP2R0_8dO5EiftqnC_7EznXy4Xk1YVhBjivxHXqpgts,1487 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/transform_reduce.inl,sha256=rOPAankNHnGhdHx4PdTYp5g-5ivGvG7zENAkJCcYGmI,1775 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/transform_scan.h,sha256=d6ShtNeKZyVM3s_YD5RLl5gm89Xr1hifh4D5NCC3-zY,2252 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/transform_scan.inl,sha256=bphyu4sjqLWRwTDxdVluib2Om9nxLVZIBKRojOdwKbw,3520 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/uninitialized_copy.h,sha256=LO6MTAjPCOKB7iHmH-ZDlaVbqrkpSK_KasYsLjf4lvY,1755 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/uninitialized_copy.inl,sha256=alOMBCWNpkaSiBTB5pPZoYSyqacLHKWZGC9n44EKKi4,6897 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/uninitialized_fill.h,sha256=8re0-uCPNSRYZcgIn16LozuhW4V2w4KMMHFfCrFSArA,1661 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/uninitialized_fill.inl,sha256=MQo9-ZwbxkFBT0JgP-8SxL7tR-xxAmgyP_fCZY_90qI,4809 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/unique.h,sha256=gSjHAW79L0DA6nbL3umBUGDqGio3_jjq0qXrtW4Eic8,2998 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/unique.inl,sha256=3ce_T4nPnqhBj3o9xe30LMwQKAAYyghm_MDp8bTVEQY,4641 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/unique_by_key.h,sha256=f8zpHup_xd-rtA8hVb-7DIpxv3RgH5OiT7TLbk2q9Sg,3078 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/generic/unique_by_key.inl,sha256=vpgE9Ji3vSQ-7R3k9_3t4c2PKUlkIZ0SW2YdTxPNP9c,5316 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/internal/decompose.h,sha256=ly1vH7Uloz2AVezh2nSxOF0KH7lI6eH7hdv3OuaWehg,3136 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/sequential/adjacent_difference.h,sha256=ndbGgTTZLPRpH9DfFy-xxWpm9ddhPt9vid2YY5oiILk,1874 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/sequential/assign_value.h,sha256=qcZ6CyDh29zpVGdcfhpnBYhmJTDmKyzAdJyzko0apks,1212 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/sequential/binary_search.h,sha256=O5WVBzT_yTM4lBYR1lT3iPG-X6OHddcn6rqLfGbrGpI,3770 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/sequential/copy.h,sha256=GRexvp4aTDhse81WfOlrDySHdPTssLpWEWTGS9ys0Ew,1724 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/sequential/copy.inl,sha256=mc6bgR1H9D8TXz1JO9_VgtnHrbgnLLJv1TgdvmCzFa0,4621 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/sequential/copy_backward.h,sha256=HXNXTdTF2Tvy1qrSJRj7fjw-t9U_1VW5moRovxjggv0,1297 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/sequential/copy_if.h,sha256=ONuPdAROc96ZFmilKDls_EKF1oqtVS-ZonFXIBZFjH0,1825 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/sequential/count.h,sha256=PRv8pS2XZ4iIXQvGKqYbXbadOj3Y4cvWOFZYtFNsYK8,714 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/sequential/equal.h,sha256=_qYe8o50V6W0fiZBsPPMSxLTZDKoluu3PmvQJmewhxM,714 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/sequential/execution_policy.h,sha256=n6FQXzoK2q9rcw_K2uWsIdPlw9DfLsbVzZc2m68dr6A,1770 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/sequential/extrema.h,sha256=1KyJGiY_VeeIgtc557WELpFsx4fX84GAehepemULRG4,3273 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/sequential/fill.h,sha256=8Xi1C9yvMqglR5ew_y4tbUazd7qciGAGa_EOU27wWkk,713 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/sequential/find.h,sha256=VWjfHWsVvYYZGkVDbgoSOHJfENtpeuuEkMG9diaNCC8,1621 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/sequential/for_each.h,sha256=SZFkNbtFRFkt__dOlMxwCSA8dBFPxm5WuLWgtod9wZo,2259 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/sequential/gather.h,sha256=c7DDVt-DPFZ7zvYma7UQ1sRRhZ9nS3Yg-jinYORoVFA,715 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/sequential/general_copy.h,sha256=-_zWgSMqpsK6AmB39txC4xDK3DPeDdLrjU1563vQdIk,3852 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/sequential/generate.h,sha256=4yRVJrms9eTcJPreLAHxC4gH9W8WarJtT3QRCn0PbAU,717 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/sequential/get_value.h,sha256=h0x5OJgbEtzAGNjr3QYKZLR2hGgHbbWwhsujCLl1rlE,1193 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/sequential/inner_product.h,sha256=Z2BthLva9rS15K-dfYV2Nv2bvnJknpZJXSHiK6G_2NE,722 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/sequential/insertion_sort.h,sha256=B_SdE62_6wnSex9WCwNaehzJz7rgmqYKR9Qpub7Tylg,3623 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/sequential/iter_swap.h,sha256=7RwuBMsYQfvEH2qtnB1e4zZb_Uo1kbpAvbebR09R1RE,1259 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/sequential/logical.h,sha256=ZPkv5JeG56AZbbei6wca9PyrmysKoK3f5bW2S7KVScU,716 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/sequential/malloc_and_free.h,sha256=u04Am8g6LKQFlqTxEoUfumIt-sSoK3C-kvuVM4sUG2M,1355 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/sequential/merge.h,sha256=J4ZKarWIG8CZm9v1kVp2oXVpZ2YpBHm9RfsgjfPFi4Q,2389 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/sequential/merge.inl,sha256=284k6-ef9awSe3XkfSXUPhFKBMD-3Clq4tBEmJD7-LM,3953 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/sequential/mismatch.h,sha256=28ZVtT5tR-he1eYDUb-nxPyeMT-3_eNS12nG9EXEbwM,717 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/sequential/partition.h,sha256=BEY257-uLIQEKSvNElLiIl-hojWw6AkCoGWPkY0mX1E,8091 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/sequential/per_device_resource.h,sha256=RLtmp_wJ628sYmbP2RzVO0ZqCi2_fOAnl0ZGwH4pBk0,723 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/sequential/reduce.h,sha256=qdTV8fEjVfUulFL8tjAmNG0oHEfjGoTxJCWsJEHfWxI,1759 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/sequential/reduce_by_key.h,sha256=D6b_Qdd1-ul8uSL4d5fOlM2RqU0bavny6nLo0LPHa-U,2853 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/sequential/remove.h,sha256=gD_F1ctZnK-1TrLAftEhHMckaoXZBjB6s4JYyaLX-Ug,4498 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/sequential/replace.h,sha256=EIBzvk7YtmjV-4zgAKvCchQpRvgbsYgfFCxSTLDFd4M,716 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/sequential/reverse.h,sha256=oLyJGPQzQSNQeqI69XeUEn8n_dtCo2G1q8opCLTOvX4,716 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/sequential/scan.h,sha256=4imjb56V-YtHuwv-LUrzkxudCdigBE8HehkNJMsVU8s,3296 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/sequential/scan_by_key.h,sha256=D2R6ANULqBgne9N315fZTpU8xBxkzMwZY8cJr36vztI,4092 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/sequential/scatter.h,sha256=gpulVFkKtmytZJWf8xo8XHuiUGZufzgulpRiQ7xMFkM,716 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/sequential/sequence.h,sha256=OIslvtJSwTJvnqlQsbvPkvFZoasXdR3-WRgLi4GjOSw,717 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/sequential/set_operations.h,sha256=W8boGqL_OAu_d91Tn9nETHFwqPJz4WXzjXUTHFC8MfM,5906 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/sequential/sort.h,sha256=rwhWUfRJxycM3HpFyCrR_sIF5WIcGRexRB9m-xanZCI,1846 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/sequential/sort.inl,sha256=dX5OViUTfp7cXcIBzv4F2l1Gyi-hgdEFCF28bWHRtWA,6653 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/sequential/stable_merge_sort.h,sha256=YpT9UmUYXaYlnsqbGAwd1h6Bk6Xz-_95rDMI1HNYfI4,1845 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/sequential/stable_merge_sort.inl,sha256=uHxTqT6z0P71dCqWheSNLcQcMbTDFlwqeq2WmY2-Xd8,14742 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/sequential/stable_primitive_sort.h,sha256=b2xzISqkSlJQjMAKEIUBstGe7YNRBzN7Ri8EZNxaMAo,1700 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/sequential/stable_primitive_sort.inl,sha256=EReqAXbJqpHJSdCqCMZsrtPi06Hva7GNZP6_XC63YLA,5091 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/sequential/stable_radix_sort.h,sha256=CDFHO2jgHEIblefhvX4tJGZ6w5osSIOoqAAHXZ0xp0E,1666 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/sequential/stable_radix_sort.inl,sha256=PhdZ77gIYWorxChFX3kewU59vF7avrvpVlBplwZAEMc,17969 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/sequential/swap_ranges.h,sha256=Gf_aZUV5bBRqUBgM2abjoLUx2EDJgr61V-Lba6mnPUo,720 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/sequential/tabulate.h,sha256=lYDyzC8VMStEqI2kKEwWSDi9gQsaPKZn-znR3dv7jHQ,717 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/sequential/temporary_buffer.h,sha256=bbrFO5T87NoZAa4pzet9tlDXbaabzNsr0riRCMWYfhE,725 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/sequential/transform.h,sha256=SF8huhz-O4VzIkJpwVkDtmE5FRmobivhbvx5rZlnhQg,718 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/sequential/transform_reduce.h,sha256=mAyfuQt7cz83j1roh9ytq22fjpffG1yM_lm_IDavBQI,725 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/sequential/transform_scan.h,sha256=GQw_WjMkFnETvjsLujKULYTrAw9gfznbYTx3biCqrDw,725 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/sequential/trivial_copy.h,sha256=HomFSROnQrnyX-kPCaXbXrtByX7TzUlEL46eNf0hPEM,1498 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/sequential/uninitialized_copy.h,sha256=GQw_WjMkFnETvjsLujKULYTrAw9gfznbYTx3biCqrDw,725 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/sequential/uninitialized_fill.h,sha256=sJvMtHfc8fveZHBUUvFzO3DNHRfEpwd3W_kv-nEdGYA,726 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/sequential/unique.h,sha256=UeqncaGAZF40RDYuwhankFxe7-b4GzV4mFJbPwfolb0,3243 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/sequential/unique_by_key.h,sha256=KtZrIcm8Jb5AG0sM9_rFZx9RBetMxB4lJ8oIRmuJSh0,3402 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/detail/system_error.inl,sha256=kiuGBq3hmyWwAO5LKwRY1qmgnmYeVJhdNX2Shsu84XE,2346 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/error_code.h,sha256=cpZAe2e6TFbb241EKWZ7CI04aXBcyTpQSaRW983T_6o,18347 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/adjacent_difference.h,sha256=IgBFhmg6XrYaJHXDSt73uDVFkofGAajUqwxC0lK3_3Q,1586 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/assign_value.h,sha256=RcUcFU1cYkIFBurzQcQzpRzc-NaBecFW_rvCFzQrnOg,756 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/binary_search.h,sha256=w7_sttDU1DTNc_7ePdk1ZvEzLJHlrAnDRRxR-qxRGmc,2463 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/copy.h,sha256=iquWNSzAGcO8dKFFKQ7k0UMN5F5TNXDS4XG1cAtDLPs,1536 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/copy.inl,sha256=MbFBrqPcMDD05T-yF5o5j9dywRVjVlbnK9ioE-0krqA,4299 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/copy_if.h,sha256=A1vEO_U-ucqrXZAEfg56nqEGvQK87jLNrAtutv4ESRk,1379 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/copy_if.inl,sha256=e0BMHg38dNXzTTgedimExZKsM5hUZuSM3abRa6Umijk,1534 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/count.h,sha256=98jgja5BJo71lb2boVPXDFSupCI_itaIlvCtd3V0W-0,742 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/default_decomposition.h,sha256=VMJ-Uv_Pwx_VaqFxwAzFM3Mw3VCYdfuwQhZvse7tpFU,1210 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/default_decomposition.inl,sha256=XIb5d4sMBnu_PPtHVMuAxoLRe2oTouXKuo9G0A4j6qQ,2069 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/equal.h,sha256=8vZJ_vKgrTCVxqtBu1YB-A7BRTZyUiGZfHhIm3-EgNY,742 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/execution_policy.h,sha256=94oSKfITnabZ4YC_NHcfMazpetpm-W0n-9B3eS4R7Dw,2921 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/extrema.h,sha256=xQ4gher02ra-MNKl_j4DAXzCbzyS5rSQZW2fe1gMBGk,2469 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/fill.h,sha256=qw_LEZSHnwZe56Yv6YkuADwdZ1KRErAsmVJW12O3onQ,740 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/find.h,sha256=-3WHqRRi08FPi8YFD8jk4y48NStg_Z6oZqKpG5CWe30,1406 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/for_each.h,sha256=Y07Y0NU2KyaWD9RxEHIXu1OgYMIv7wiiBDC1HMreZ7g,1806 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/for_each.inl,sha256=GXWXTUW4ch_3ZNoSSqZf96q_s48lgmZyHb6Luq45Rp8,3055 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/gather.h,sha256=KmbVgUZ9Mb3WrK4Ckj9IzrN6wv4Eb2bikVBJwpPbjPs,744 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/generate.h,sha256=-DclT7r9SocutdZq7Pp_oR36SpcHvvivaiQob3hzdIA,748 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/get_value.h,sha256=fX9lXM_Fs0xZS2WfUzbav3V-t5dUJfMW-umShVI0zII,750 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/inner_product.h,sha256=iTLvSOE9SnE4rU_a3f4f3xITElDJArIGhk8nHGzhZig,758 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/iter_swap.h,sha256=ikzK5HMw8pTg8NEMh1JobTRcdYuCoqCMJtOSBk3Wje4,750 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/logical.h,sha256=uxA7UGZVai5_O_jomtzA9G9tDQV4r8c5OK77tKK_dJo,746 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/malloc_and_free.h,sha256=EZVyPESVlL8R0ixG1L6VluZ9I_fuk-kEjsSyhtsjAic,762 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/memory.inl,sha256=oPwXh2cM7NZUZAeU7bM3rF_okNMx-gEA_nymFMk7AoY,2423 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/merge.h,sha256=ay66czqdgZHCn3NgWyn5Mwmz9VWEQXUMcCAtlr19SCA,742 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/mismatch.h,sha256=Y_LjyQXF27MYW5j0kkfWLAq6VQ2kRNErmxVm3lSjWNI,748 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/par.h,sha256=FQWzSqPy-sQIfDerN99-i8LBQcp-cFvhiE92zLkfS7U,1330 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/partition.h,sha256=zeah-ESXVfFoilAgjiSfOEIqQWYul5e65JiRs3NoODQ,2951 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/partition.inl,sha256=hqvkEjyhatEsqBfryjiVcXMMEy_dFPJCiXPkWUKB23w,3751 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/per_device_resource.h,sha256=RLtmp_wJ628sYmbP2RzVO0ZqCi2_fOAnl0ZGwH4pBk0,723 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/pragma_omp.h,sha256=a9i6l4YenLfOyJDAUtEEuej5T_aIrYn9SvEWbIjhfgU,2798 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/reduce.h,sha256=MhUugS8zJMYsZf4KEl1o7Em3moanxC1JNe_yPoOLu4M,1383 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/reduce.inl,sha256=7L19nMWpK5lrlVaN0i23lsmcaZP7UZjBr6pfHIBQHk0,2466 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/reduce_by_key.h,sha256=g3iqP6Mvvmigelbm_w-VAjzzX0WLPbQs0ic2Renzc5I,1712 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/reduce_by_key.inl,sha256=hTkN9tj8j_wgDf8UxIDf8NGlAifJkoHOzW2g4B7VlAI,1867 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/reduce_intervals.h,sha256=2_KFOv6e3mQSDCsi_eoLQBp1fat6_STOoeFmE4uRRU0,1471 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/reduce_intervals.inl,sha256=xkuQEu9ogikX-96bOCmkb2hvpfQei2GdTjaXNr5Tmcw,2901 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/remove.h,sha256=A11V-oqzPPrI-emqCrFY2eM_dDc61wpIsVVZtjuqIhI,2568 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/remove.inl,sha256=j7_Bz9srUEsyEqoZg3b8L1BqAjy1-rAsLIfAlMY1BbA,3161 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/replace.h,sha256=VoYvHEIVp4Obr0BWccaX_mvZCQh6TowmYS8hi6UgOTE,753 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/reverse.h,sha256=0P4FTgl2DUupe3DP_lmbGtObnX7mvYmrwWjXBR6Q168,746 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/scan.h,sha256=Jh9St9TdwKSe-cUziG5csHWG66NrCdAcSPZ1TjXHGQ0,740 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/scan_by_key.h,sha256=vGson2UFCY0EZNicIcWlz2Jbt0UzF0tJtU57DYRetvc,757 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/scatter.h,sha256=VoYvHEIVp4Obr0BWccaX_mvZCQh6TowmYS8hi6UgOTE,753 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/sequence.h,sha256=WwaoabBC1IWuPdF-fS8J7eQ9WCCvvu3HXPXxrdE6xQ8,748 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/set_operations.h,sha256=mzGWVsv6vr4Y76yA5yfqKEqniAMTnz5zPQVyksAFWk0,760 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/sort.h,sha256=W_B119KY6GSHtTuSpRPf8sRXUznuMdB3b-7xsbxQ7hA,1689 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/sort.inl,sha256=IH-4-qxc59SSDERXoqQ97zgXwYv5XDLSFUpfVkRY74w,8864 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/swap_ranges.h,sha256=54i4pb4ztxd5ufm3JGRCef7AfwMuvFtw1a15TkX4oR4,746 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/tabulate.h,sha256=uMMw_Qgkg9JDzzJrmN9KwDsDXMspBgwq36QHr_hEusw,748 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/temporary_buffer.h,sha256=bbrFO5T87NoZAa4pzet9tlDXbaabzNsr0riRCMWYfhE,725 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/transform.h,sha256=FXya_cvYQibHQaRzA-saouhIgqwPtVEStDgHsgTM4dQ,742 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/transform_reduce.h,sha256=IJkRtAdJNp_DJfOyN-IE8FTlmfYTdoXvuG2wnBA6HD4,764 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/transform_scan.h,sha256=ZS5GkZA-k0rnRL_8eXSnWLZ-uuIufPCqAdqiNZQaaWs,760 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/uninitialized_copy.h,sha256=f4rtHoG6ix5igcN8s9uyXbjo_RF-DEEOPyDZa19YDm0,768 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/uninitialized_fill.h,sha256=UF_Dz_jppw4b6q1Y3wgw5yKvS5fZ2ypXqik-qbZGy8M,768 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/unique.h,sha256=kon0_EJmQqMuUvG8aDbnSANgBLCHYg-z-aZ731P0tCw,2062 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/unique.inl,sha256=buAKHtmtdlGieIX0canUWVdWJ7zrqZrEGYbIQcko2tc,2542 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/unique_by_key.h,sha256=08Rg5UPYiBIHfcyv0yeX4abBlzrtukncsJftdJQVO9Y,2048 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/detail/unique_by_key.inl,sha256=tD7VtDC1nKD4fTJU6FIz_7uxcThyjdvjD5LXFirhbng,2485 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/execution_policy.h,sha256=2EU0l4hEFFmaWoLt9QIcKC54_RRe9U8_eLdtu9YWdT4,5095 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/memory.h,sha256=y2Y8SKB1UD939Z8W7twcY0Jjqgs6tNlwmojJNiVJkzM,3396 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/memory_resource.h,sha256=jUHh1S6TyjhcKNt8y5gNUPK5D794tuniEsorZDC2NSM,1967 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/pointer.h,sha256=UkCzYEvrWeSG0VNm5LYW8tLA1t_gWXKcz326bGMK41Y,3783 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/omp/vector.h,sha256=H2ffA0rvnoRwlKz6oko7oxod3s_pjZAUFP7E-yP6I64,3161 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/system_error.h,sha256=PqUlltttCLaSd4cY5EUWbKaODbiq87UQwcCqP43skvY,5649 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/adjacent_difference.h,sha256=w4bEKgxzs8PvknFtLHiXAqfkcnQVn3_zJEvOxk315B4,1586 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/assign_value.h,sha256=RcUcFU1cYkIFBurzQcQzpRzc-NaBecFW_rvCFzQrnOg,756 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/binary_search.h,sha256=I3iDJlJ3yGjTtyJeUHsxzDNO2HLR3Utb5kY_iscGa5Q,758 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/copy.h,sha256=WzTALXI-E00pFeM1f2L_dMEW7tf5b3rQEDkW52idj-o,1536 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/copy.inl,sha256=yZJH8zXAcassZiBnAtZky0z3fzi_I9F0qwzUHNMrA5U,4322 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/copy_if.h,sha256=uw9ZnlyBfxLWB6axlrv7qbgy-MxiV1eA_A6JjC8Hl88,1312 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/copy_if.inl,sha256=jRAYhQJ-joyjetT5JA7AnhnIEucVRtEm1-BY0yvLY6w,3295 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/count.h,sha256=98jgja5BJo71lb2boVPXDFSupCI_itaIlvCtd3V0W-0,742 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/equal.h,sha256=8vZJ_vKgrTCVxqtBu1YB-A7BRTZyUiGZfHhIm3-EgNY,742 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/execution_policy.h,sha256=JvKsnJvh2-b2j0QKaAIAsQzkbU4F0nN_mmAuIr955og,2144 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/extrema.h,sha256=rLixBFZW9SACClc2fDOfSRZjkyfNoKyI0RJ8VMziQBs,2469 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/fill.h,sha256=qw_LEZSHnwZe56Yv6YkuADwdZ1KRErAsmVJW12O3onQ,740 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/find.h,sha256=Hem2ZlKmkWp5ukoxHBxAlikGmCMjC2EKmMMp6dfQUMk,1337 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/for_each.h,sha256=q9uQBIIrNu89VHEwNzKn__jm0A1PfBrCAx3pfc25xf8,1654 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/for_each.inl,sha256=3E7hqrJvrqeS9BB8R8cUeIC_nUxm2c9rNA7B26IFLmA,2946 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/gather.h,sha256=KmbVgUZ9Mb3WrK4Ckj9IzrN6wv4Eb2bikVBJwpPbjPs,744 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/generate.h,sha256=-DclT7r9SocutdZq7Pp_oR36SpcHvvivaiQob3hzdIA,748 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/get_value.h,sha256=fX9lXM_Fs0xZS2WfUzbav3V-t5dUJfMW-umShVI0zII,750 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/inner_product.h,sha256=iTLvSOE9SnE4rU_a3f4f3xITElDJArIGhk8nHGzhZig,758 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/iter_swap.h,sha256=ikzK5HMw8pTg8NEMh1JobTRcdYuCoqCMJtOSBk3Wje4,750 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/logical.h,sha256=uxA7UGZVai5_O_jomtzA9G9tDQV4r8c5OK77tKK_dJo,746 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/malloc_and_free.h,sha256=EZVyPESVlL8R0ixG1L6VluZ9I_fuk-kEjsSyhtsjAic,762 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/memory.inl,sha256=8JdtgrME8RpAdywrQEyh9nRpEPqoA2XrB1XmV1-i16E,2424 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/merge.h,sha256=W7uIJhALVNvsGxS__t66WcyR_wTcDIfCLtQUW86CWZ8,2198 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/merge.inl,sha256=PeAnBfR4KDNNM96UC_KqhYvAT_JiVGA4i7L1f3vxJ3c,9380 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/mismatch.h,sha256=Y_LjyQXF27MYW5j0kkfWLAq6VQ2kRNErmxVm3lSjWNI,748 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/par.h,sha256=SpnUOIXJoDlr7R27P7U_hK7ypUB-l-3rZHqSd7va13A,1330 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/partition.h,sha256=WlSF8cl6Blq9pJRit2A9d2qDjx-fEAWtNpG4vaGM3sw,2872 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/partition.inl,sha256=CSHxFGekeHir-5th2hGSu5PInFegToOM4cI2if3DkXM,3670 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/per_device_resource.h,sha256=RLtmp_wJ628sYmbP2RzVO0ZqCi2_fOAnl0ZGwH4pBk0,723 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/reduce.h,sha256=n57quWVHwxaP9nxov5xZT-fTA1u2DdHWd2sz3orJUoI,1368 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/reduce.inl,sha256=QeZrz2Zt1NFLTK1yDVFxSO_swY7tH3xMbsfdWr5ty5s,3470 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/reduce_by_key.h,sha256=Y0jS3DoAiWZdomozZ5q3NHzcjmcKAVWounEKe_WfRjA,1650 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/reduce_by_key.inl,sha256=TLB-ray7_3N4EIXP5kxYs2oyZhMF4Vb6jGs07bT34OY,14239 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/reduce_intervals.h,sha256=b-wEOCf63ctIF3eke5RSMzeVbaCMryE9vRzlzhPLWf0,4287 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/remove.h,sha256=wMrxq3TeIb3DK1qwpwVooyVfOp3n5g0y8RmX1Dkgj8A,2584 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/remove.inl,sha256=5ymtW-u76XEFWkopfwLKDoS4OzPEf359_ogRvHczwpA,3161 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/replace.h,sha256=VoYvHEIVp4Obr0BWccaX_mvZCQh6TowmYS8hi6UgOTE,753 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/reverse.h,sha256=0P4FTgl2DUupe3DP_lmbGtObnX7mvYmrwWjXBR6Q168,746 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/scan.h,sha256=Ml8mLPvsUXr2_aToWa-XeC6b6S_TkZ2FUnY3jPi_iOY,1795 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/scan.inl,sha256=DKfzWZaZSXsgsOjjedR46kwKRwPkVsh_cWitqwwA4Ig,7066 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/scan_by_key.h,sha256=T-J3lA078NKtumfpMRbtQCgt3p9dI0V4l8Li_qRW0t0,754 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/scatter.h,sha256=VoYvHEIVp4Obr0BWccaX_mvZCQh6TowmYS8hi6UgOTE,753 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/sequence.h,sha256=WwaoabBC1IWuPdF-fS8J7eQ9WCCvvu3HXPXxrdE6xQ8,748 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/set_operations.h,sha256=mzGWVsv6vr4Y76yA5yfqKEqniAMTnz5zPQVyksAFWk0,760 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/sort.h,sha256=G0GI2yTM7g9otp_28tCVgpEOW7LM6LGD89HxuC2MJOM,1703 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/sort.inl,sha256=by8qKQ8QkzmIWK-3HnbTuFTdRiFZvjEnAJJ4TBi0IOg,8169 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/swap_ranges.h,sha256=uwPqWdgp82Xx5RAZ3kKMV2cba2XXIYUp6lNtT11mybc,746 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/tabulate.h,sha256=uMMw_Qgkg9JDzzJrmN9KwDsDXMspBgwq36QHr_hEusw,748 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/temporary_buffer.h,sha256=bbrFO5T87NoZAa4pzet9tlDXbaabzNsr0riRCMWYfhE,725 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/transform.h,sha256=FXya_cvYQibHQaRzA-saouhIgqwPtVEStDgHsgTM4dQ,742 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/transform_reduce.h,sha256=IJkRtAdJNp_DJfOyN-IE8FTlmfYTdoXvuG2wnBA6HD4,764 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/transform_scan.h,sha256=ZS5GkZA-k0rnRL_8eXSnWLZ-uuIufPCqAdqiNZQaaWs,760 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/uninitialized_copy.h,sha256=f4rtHoG6ix5igcN8s9uyXbjo_RF-DEEOPyDZa19YDm0,768 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/uninitialized_fill.h,sha256=UF_Dz_jppw4b6q1Y3wgw5yKvS5fZ2ypXqik-qbZGy8M,768 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/unique.h,sha256=vM9XFHC2JtYXpiO8UhxmP-Ha46C2oMQOAJA1QTNS2N0,2070 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/unique.inl,sha256=uAsypnTcXgf6n9U85xk0Y3DJ8IcMXQhA3qf0S09o0gs,2542 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/unique_by_key.h,sha256=qfS_1sPZDOIUnWbKtQVPGH7xb4WgFEL1cqshUEok7ZM,2048 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/detail/unique_by_key.inl,sha256=eLAA1bC9h7oHdsN0TcHAC9kC-QhzTgQWePJKlWrs_hQ,2485 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/execution_policy.h,sha256=K7H8_0LY6JLvc2HeA7UvEavjezA5HRNynaYn4khgGLQ,5071 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/memory.h,sha256=lZEo6ewcyvIf0w7zxOD4g0YydUzIsjl_uKb9q2caD7w,3394 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/memory_resource.h,sha256=Y7JFGJ9Lfgc2Sck4M6nmRc7oI0VlUXhjcadn80kkJLI,1978 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/pointer.h,sha256=HvoX1qwDQfnMho8f32Jyy7ZcgGf4tJiW5E6pH-uvPYg,3780 +tensorflow/include/third_party/gpus/cuda/include/thrust/system/tbb/vector.h,sha256=7gYiMe7mxzsSdaJNS0E3s6PHh21JVPQY6mKxRlyzS0Y,3157 +tensorflow/include/third_party/gpus/cuda/include/thrust/system_error.h,sha256=JzjCAduhgXWGNRKIeeqJ6UNcNDWmarhQLH_4g_jfjaA,1454 +tensorflow/include/third_party/gpus/cuda/include/thrust/tabulate.h,sha256=HPOfxx_UN06T2NXcU31ay3JwIjT7Mck_NMGztaJ2KtY,4785 +tensorflow/include/third_party/gpus/cuda/include/thrust/transform.h,sha256=JhVpEZcnSu2yMmrcVOOjAjukRptyWub1Nhwn_zR1bSg,36715 +tensorflow/include/third_party/gpus/cuda/include/thrust/transform_reduce.h,sha256=SeYjCz-XBnfj5Y3c0AGhPg_ezMZ_R1IAMRqWiynD0ZI,8316 +tensorflow/include/third_party/gpus/cuda/include/thrust/transform_scan.h,sha256=SDpCz4EU8TtDCOppdPUEJ_-xT1tjp8c4mMAjAz5BokY,15301 +tensorflow/include/third_party/gpus/cuda/include/thrust/tuple.h,sha256=UN9Rrw8Sh61WqG9i6Qb2zmsRsA5ynV93iqeR2IKCBh0,20598 +tensorflow/include/third_party/gpus/cuda/include/thrust/type_traits/integer_sequence.h,sha256=0pkkDfSp_7wwV8s1AHGd4NjGFinhkxfn8TGu41hm0lQ,10578 +tensorflow/include/third_party/gpus/cuda/include/thrust/type_traits/is_contiguous_iterator.h,sha256=tfbol3uLKttzfy69rgbvctq8Vb93_GcmadLqcXAYW98,8482 +tensorflow/include/third_party/gpus/cuda/include/thrust/type_traits/is_execution_policy.h,sha256=VPsjaG94Wr03Cw4sDJbfYpRFjnXN2ZUC4ClUdtRdvEg,1702 +tensorflow/include/third_party/gpus/cuda/include/thrust/type_traits/is_operator_less_or_greater_function_object.h,sha256=SKCnDlfbULZlXbJKUKf4M6t8vKk9BGYlXE9MeHHmOqQ,6372 +tensorflow/include/third_party/gpus/cuda/include/thrust/type_traits/is_operator_plus_function_object.h,sha256=-v7QyHEc0Mb1hELPq7W_Nr_zykf8dzA-LUgRYT2q3Rk,3064 +tensorflow/include/third_party/gpus/cuda/include/thrust/type_traits/is_trivially_relocatable.h,sha256=G6fZydS9GObWzjWjV1EqheL2L2FNqOnpHH_cH-U-l3s,12644 +tensorflow/include/third_party/gpus/cuda/include/thrust/type_traits/logical_metafunctions.h,sha256=2FtwIhLsSKDh_W5p4gc7Nh0OObYFUx0k1n4fIhDG1aA,7888 +tensorflow/include/third_party/gpus/cuda/include/thrust/type_traits/remove_cvref.h,sha256=tF41huhxS3QF1UvDGoyAfJgUaIQYkRG20LS1ziEtRws,3187 +tensorflow/include/third_party/gpus/cuda/include/thrust/type_traits/void_t.h,sha256=xjYTLiMoXWV5_ncQhDpVtg-dn7go4u4_keWFLATKrWs,1458 +tensorflow/include/third_party/gpus/cuda/include/thrust/uninitialized_copy.h,sha256=hCDJ0v8KhAMaPZtPvmbqXrYRMB1cVK_7hwL8hMzXOvE,12752 +tensorflow/include/third_party/gpus/cuda/include/thrust/uninitialized_fill.h,sha256=jFTMfr0pBdTymZtxJikFDYIoWnFnlXBTdpvcP-eI_Jc,10409 +tensorflow/include/third_party/gpus/cuda/include/thrust/unique.h,sha256=FPQ3wL0jrQuJoaTHFOgXEoP995bW4JYdPqeNS_we53Q,53968 +tensorflow/include/third_party/gpus/cuda/include/thrust/universal_allocator.h,sha256=YWIxT1Vxv2CEGzzuYA62c3QEcxeLwSvD2PkBDbCTZ7M,2684 +tensorflow/include/third_party/gpus/cuda/include/thrust/universal_ptr.h,sha256=j70tHvGVV51-IsaHNiZ-XRU3-FlVA2ZnrKQORSa34l8,810 +tensorflow/include/third_party/gpus/cuda/include/thrust/universal_vector.h,sha256=KY8y55krR-dgaDibJbnfp5PCyfGaisUurXRINfhFZOc,1918 +tensorflow/include/third_party/gpus/cuda/include/thrust/version.h,sha256=1Y580Wxr8xQG3FOZ8k5z1bY5PA0JiHwAX1-ca9mnoIM,2848 +tensorflow/include/third_party/gpus/cuda/include/thrust/zip_function.h,sha256=aomYMoUpE3q_0PcBALKI6tQ98Yn70p9kJjVGF9JR3f4,6881 +tensorflow/include/third_party/gpus/cuda/include/vector_functions.h,sha256=R5plWOkFciltO_AS5if8NcmsgDp3cFNq6zFFDd3oofk,7847 +tensorflow/include/third_party/gpus/cuda/include/vector_functions.hpp,sha256=afXhNSd3LFTZo96EPtesTLfvxd4nTmLVzgkj967rTRg,10060 +tensorflow/include/third_party/gpus/cuda/include/vector_types.h,sha256=ruVFRp8RioWR9mrvLXX9S15ZSJ97wqTjA8ORCJKKzOQ,13206 +tensorflow/include/tsl/c/tsl_status.h,sha256=9NGwXzGl5iNo0-Gbabk9WJfSNn4Vva3oeq91hIDwCPc,3411 +tensorflow/include/tsl/c/tsl_status_helper.h,sha256=bQT_pkgcQCdzUAFsvoYT0iAvBb7Khng6Y_rMEfe0Vxc,1045 +tensorflow/include/tsl/c/tsl_status_internal.h,sha256=36Mw0amVD4kU3H2MxmiEFO0LCZtCbDbGLgLbpCvQs0U,1009 +tensorflow/include/tsl/distributed_runtime/call_options.h,sha256=V7JwtBWQb_y8yeNjMzN6bNRTtDJEzW5aWmBXz28V9Aw,2876 +tensorflow/include/tsl/distributed_runtime/coordination/coordination_client.h,sha256=tT-pN5ACabMqXe6MoOIzwVRuunM9XePoklrrhJ8XbLs,6348 +tensorflow/include/tsl/distributed_runtime/coordination/coordination_service.h,sha256=p4uVH-xoS6teyfGvN-WIV3KFSqy1o7-xG-GKZAIEHzM,11732 +tensorflow/include/tsl/distributed_runtime/coordination/coordination_service_agent.h,sha256=tqtSzQHAbOeQuGUhDaorahwhak23WQOMM5_922S30Bc,13319 +tensorflow/include/tsl/distributed_runtime/coordination/coordination_service_error_util.h,sha256=j6bPunFX7sVrDaCeeYoeS1PVTIR-ZFcPcG2nlmi9SPM,2400 +tensorflow/include/tsl/distributed_runtime/coordination/coordination_service_rpc_handler.h,sha256=gIzFlKrudp2eAel4ny32gnfZythag6xBJnsIIBmikwM,4474 +tensorflow/include/tsl/distributed_runtime/preemption/preemption_notifier.h,sha256=7lQCLIAbB6Fc86ELUl_LeAu94MCvxhG08ayDZdJyotA,6332 +tensorflow/include/tsl/distributed_runtime/rpc/async_service_interface.h,sha256=sByCUwqe_7EBdNW5zeT3r1tS1ypY3hA3me0KQ0LjxMA,1545 +tensorflow/include/tsl/distributed_runtime/rpc/coordination/grpc_coordination_client.h,sha256=uQlxbTBGdP9UsxfVzIOsPEEIbo2-b3ntUiUKcPbUSlo,1321 +tensorflow/include/tsl/distributed_runtime/rpc/coordination/grpc_coordination_service_impl.h,sha256=g1M87sRRzm5uxhaUikArwE-mwJl_hdOHbmvs-BjIgJk,5357 +tensorflow/include/tsl/distributed_runtime/rpc/grpc_call.h,sha256=0XNkmKSMIb_nGZCjcrJOnNBIv5o1xg2rqWqU01szrOA,21318 +tensorflow/include/tsl/distributed_runtime/rpc/grpc_channel.h,sha256=04yC9SB7j1Imj0sReLGrwcB_doBrVPyAgJazTm3iX3E,3516 +tensorflow/include/tsl/distributed_runtime/rpc/grpc_channel_common.h,sha256=Zc8AJKEQfQVEOQNy8gUUtRfMqiKO3AXSu_ZMsdAujVQ,3869 +tensorflow/include/tsl/distributed_runtime/rpc/grpc_client_cq_tag.h,sha256=g5U0qyw47fkhHN3R1phbB-Thy_PPJ9D_D3_OBeY1J8k,1436 +tensorflow/include/tsl/distributed_runtime/rpc/grpc_state.h,sha256=xdOBRQ9myygBzfWtfsbkTbpO99CuL8ikYBgIQcw-zdU,9717 +tensorflow/include/tsl/distributed_runtime/rpc/grpc_util.h,sha256=9gkQMbs-zdz4yMXkxrTASH2stq7XfImtKoiimwvS5H8,5492 +tensorflow/include/tsl/framework/allocator.h,sha256=eUJac-2HCOqfFSDgwvzcgg6AYpEAW_WHvgAyO7Oq9D8,16863 +tensorflow/include/tsl/framework/allocator_registry.h,sha256=rf6J16I16pu8wjNao7VN_XUy4Ac1lVhNKV1HMpIhlXU,5604 +tensorflow/include/tsl/framework/allocator_retry.h,sha256=9pTmi-Sx3hy7ttBDpyJpzpSerXvYqr-7zyUZWTmjcYI,2125 +tensorflow/include/tsl/framework/bfc_allocator.h,sha256=-Vvlb0AciSK2iQyZ6Hy0Fhi6sxAszwZ7shYi3oZKJ_8,23379 +tensorflow/include/tsl/framework/cancellation.h,sha256=Da6iVTrMjR4sPmt5iHPm9tV8G37Zom1sl1PiBFjSqIw,8800 +tensorflow/include/tsl/framework/contraction/eigen_contraction_kernel.h,sha256=GKpkHjec5MA0U5I5sMfvqZipfjVVFcAJ_EQgEDxRYJw,53345 +tensorflow/include/tsl/framework/convolution/eigen_convolution_helpers.h,sha256=2IaIV6vz1IFnMsLiVuXWF8QX79bvslqaVKgL_cZP6YM,4001 +tensorflow/include/tsl/framework/convolution/eigen_spatial_convolutions-inl.h,sha256=fcbH6rq9TnNAg_9sSqLJJmlGWapK9fnj_eea601rOk8,76113 +tensorflow/include/tsl/framework/convolution/eigen_spatial_convolutions.h,sha256=nPS5oUEO_nVjupktLlfMdbi_NfdWu3tV811L1XYTftM,18459 +tensorflow/include/tsl/framework/device_id.h,sha256=rWpzuRFbmjqNGhwhA6AXW1t-tAKAjNlZW24OJkQxiBg,4139 +tensorflow/include/tsl/framework/device_id_manager.h,sha256=klTN2pnJvWOvLluygFX_aJvm8vDFuwxl2LVbSWV6rJo,1976 +tensorflow/include/tsl/framework/device_id_utils.h,sha256=zfaEOEHLkJK64iwiS1J77WLMmlp2DUgVVYAC5XB31l4,2993 +tensorflow/include/tsl/framework/device_type.h,sha256=mGHCEZB5f7QMhSTS34XEbhcJkXhAQzysTLaNQZi1Gtk,1632 +tensorflow/include/tsl/framework/fixedpoint/FixedPoint.h,sha256=pLTBPq3Nj-T9kafqS3JFOT0m2-AM24X-bwsYLQcf6Nc,2267 +tensorflow/include/tsl/framework/fixedpoint/MatMatProduct.h,sha256=XtM02HlVDkyTwuVyI0LsBgrqo-XYPWIp7HKbzW4Uing,12242 +tensorflow/include/tsl/framework/fixedpoint/MatMatProductAVX2.h,sha256=cgLpgTAygIyAAGxiUmiGC3mIZ1nc0w-XYf3c4OJ14VI,97119 +tensorflow/include/tsl/framework/fixedpoint/MatMatProductNEON.h,sha256=sUTcKC5NYNwCP5Rbo0e-J2nc8x2-Md-cVlNNjGSclYs,10843 +tensorflow/include/tsl/framework/fixedpoint/MatVecProduct.h,sha256=OvL8UkuVovzzUgSCPYqzQcub1VO-HTeccCjfrDbg8do,6349 +tensorflow/include/tsl/framework/fixedpoint/PacketMathAVX.h,sha256=nVV3yvskf7VPcvQfQVf6mseUeQ6LgYwBQH2d8DYHu7A,5116 +tensorflow/include/tsl/framework/fixedpoint/PacketMathAVX2.h,sha256=tlnMBg4gckv6hnQdkjPeQIPbkGJZTIDTwRsVj0DT-Qg,18503 +tensorflow/include/tsl/framework/fixedpoint/PacketMathAVX512.h,sha256=ZUdpw38tncVRIj3nxB1QQAEr5_KtDoP1R4Dqu9QPHLw,18943 +tensorflow/include/tsl/framework/fixedpoint/TypeCastingAVX2.h,sha256=r6CA8kJhVzFURKN0mFJx6Du-92nsOkny9i5W12IOHSE,4272 +tensorflow/include/tsl/framework/fixedpoint/TypeCastingAVX512.h,sha256=sLdyyG4y3GSK0Gpxg8wpraWndsvye7aJymrKVw-3AWQ,7930 +tensorflow/include/tsl/framework/fixedpoint_types.h,sha256=oWxzXT90zYmtfwE0u9gW4-DFjohLkYXm3oczD1idERU,12331 +tensorflow/include/tsl/framework/metrics.h,sha256=e9kFGEmWDDCKecaLPJ5JVF2YCD8-kgo9_nP9mXKd-6Y,1047 +tensorflow/include/tsl/framework/numeric_types.h,sha256=tBphRz-3iN-6jpDxjW85FWTrNihEkIQRb-pZLTj7P94,2245 +tensorflow/include/tsl/framework/shared_counter.h,sha256=I-kvNi2vZf4ziKJXk8NM3kbAkOay7KjoePX5wvAdZPo,1152 +tensorflow/include/tsl/framework/tracking_allocator.h,sha256=HeU5hBz1tUkylsuOLlwBWfn3rblKQIR8JPcQhI1efm0,5750 +tensorflow/include/tsl/framework/type_traits.h,sha256=R57tJpNifqUbtNoVcy-6TeNuopJYNl6glvidq7zQ4xk,3697 +tensorflow/include/tsl/lib/core/bitmap.h,sha256=7BS6ASaA3QoW-WiDYwrriqHJu7COPjGmUHeUitSH4Wc,2910 +tensorflow/include/tsl/lib/core/bits.h,sha256=oM3t37JbzG9Hl4jWPE1GciYk9WPQyvejjpGxZ724NBw,3121 +tensorflow/include/tsl/lib/core/status_test_util.h,sha256=W2YBWCfWirZx5_wu8MypEdlOVZKo0Y1HrOvVcdCqHe0,1512 +tensorflow/include/tsl/lib/gtl/compactptrset.h,sha256=KAW3WGpcpmSCRpdrzYpFiqXPPERCaRSF1TR3_4XIpZ0,5388 +tensorflow/include/tsl/lib/gtl/flatmap.h,sha256=DflahgOVx_DtmpAiHA3sd2qEBeMcg3nJHw5cIPccY2Q,11963 +tensorflow/include/tsl/lib/gtl/flatrep.h,sha256=o2cYpb_k50bv0aA-nd1CvHRq6NCctqitgX8yV4pHaKE,11030 +tensorflow/include/tsl/lib/gtl/flatset.h,sha256=DBYD7iEgw9EIluzcAhVvtt_2BPFFlA9uDrGx74U8gu0,8811 +tensorflow/include/tsl/lib/gtl/inlined_vector.h,sha256=l2nGCm7xE5Uebu1Buypj5V6d0STf4DE9qrKoX6mXgy0,1180 +tensorflow/include/tsl/lib/gtl/int_type.h,sha256=cCu2d7EWqhVPCoG7OJ45O83kh4gjcRfM57Ek4C5xZ78,15707 +tensorflow/include/tsl/lib/gtl/iterator_range.h,sha256=Ic5N7M9xoZ3e06GjvdqWS-w_2Jbe3Z-q1gAt268m19A,2358 +tensorflow/include/tsl/lib/gtl/map_util.h,sha256=-F65FC_4PBBSERkB9noPwh7vk2QjEHdhlctt9ufPmew,7889 +tensorflow/include/tsl/lib/gtl/subtle/map_traits.h,sha256=niZRWu07vWr4qfFBPZuqhP_f9haXGo2wjObhkMl-eUI,2596 +tensorflow/include/tsl/lib/hash/crc32c.h,sha256=H2DrQK2IrjyKgxj17F5SpdPiG2SG4M9DvA1RnScZxYo,2183 +tensorflow/include/tsl/lib/histogram/histogram.h,sha256=8CpvxHnGXYF7vJBhrOc9vxaYfohy1jNIuFi10NYAdIE,4723 +tensorflow/include/tsl/lib/io/block.h,sha256=PRbg3aw1Wh71mbcMBjgVMWzx0zHLlq6L-r65GpzK2Eg,1465 +tensorflow/include/tsl/lib/io/block_builder.h,sha256=qbs-_syJFXXazQEVwbiJLPiL1YNFdwJTpy-3z0A3ZwE,2269 +tensorflow/include/tsl/lib/io/buffered_file.h,sha256=RzE5F2L51AxcQfvu7ojCXiMict0UdZI9f6y6TnZkqKs,3550 +tensorflow/include/tsl/lib/io/buffered_inputstream.h,sha256=hBWYK31Hy4LDyuxfbbQ8Eac3v-OYjWckYUOdbfabLls,4939 +tensorflow/include/tsl/lib/io/cache.h,sha256=ewj9-CkENTUYeXKLUBZlx3QZ5yJi6NUdH50hJf6wqGs,4578 +tensorflow/include/tsl/lib/io/compression.h,sha256=65q_1dHgAJbjVw1HxZ9PwbUMlViUIuE0momPT_owUl4,1044 +tensorflow/include/tsl/lib/io/format.h,sha256=U6ftHa-Y5GPCjg0FNIKjsT-9qDM_T-mVOwkEmSvFbCo,3513 +tensorflow/include/tsl/lib/io/inputbuffer.h,sha256=jOjndILdkWT9AZlrVFMagXp59rBSOaYoA-JAzA-ccqo,5528 +tensorflow/include/tsl/lib/io/inputstream_interface.h,sha256=8ASlaRLg2NEfNmN5sOBWb5el5UAkHr4uXeMcE9pkuEI,2463 +tensorflow/include/tsl/lib/io/iterator.h,sha256=XYg3OtrqGlxfD2EA9dVpbeBQk7oE8A6Z1V0MEmYlKAI,3644 +tensorflow/include/tsl/lib/io/proto_encode_helper.h,sha256=xpiIs8tSPmrLcAcyqiVLg7jj_L3IjmCRpFx1Scm9x6s,3153 +tensorflow/include/tsl/lib/io/random_inputstream.h,sha256=fEWy3OJwLBs7Gnis6tr5PTqPilatEUOZm9j6tHEfc6E,2001 +tensorflow/include/tsl/lib/io/record_reader.h,sha256=0kvaxYVCQj7cMsQrlYu6YdM4rKe6xhdSuc3fnCdMYLM,6265 +tensorflow/include/tsl/lib/io/record_writer.h,sha256=4f9mqtQrBFpfECcJ1MFJRGBpZ-cK4ChJaw08SXLD67s,5024 +tensorflow/include/tsl/lib/io/snappy/snappy_compression_options.h,sha256=Riu8tRWkddQ9zqfghPyaQkx9uhF9snL-VQXvP0lxMEg,1278 +tensorflow/include/tsl/lib/io/snappy/snappy_inputbuffer.h,sha256=lk_llFrsFf5-MaRB2-oE5c0gy97Ix2TWl_g1JjkR2TA,5131 +tensorflow/include/tsl/lib/io/snappy/snappy_inputstream.h,sha256=JLnY7yw0DnehdrEIFXMs0yeURZOHgUZG24lTcslVDzw,3169 +tensorflow/include/tsl/lib/io/snappy/snappy_outputbuffer.h,sha256=eFjNmmrBFNlGRUi6w468mOKZGw_PRuCu5mPkioUXdVI,5904 +tensorflow/include/tsl/lib/io/table.h,sha256=I0jb0UgCpeX_vHWLfPn4MvXHgKQpGEQUXBaLSZUdFZ0,3154 +tensorflow/include/tsl/lib/io/table_builder.h,sha256=VYB3KcodIqKCq2TxwNDNYA-HLenTPn-brDx_3_288yY,3573 +tensorflow/include/tsl/lib/io/table_options.h,sha256=-tGltp6nuYbNnuifRLr8GB_AXKrTIXzIM403NXe-7UU,2922 +tensorflow/include/tsl/lib/io/two_level_iterator.h,sha256=VVMGUVhSQcTqKAeyEq0cwsvymn5HRBE0bqhZy3d6qOU,1611 +tensorflow/include/tsl/lib/io/zlib_compression_options.h,sha256=kOZsiFAkPlTovnPlzMx62igJnLQLkf81rHSYv2_0Wdg,6053 +tensorflow/include/tsl/lib/io/zlib_inputstream.h,sha256=akNNAwvYBsgPmc9OW0sGV9Wz_i8XWHDeTBo4mC6Lm2I,5342 +tensorflow/include/tsl/lib/io/zlib_outputbuffer.h,sha256=QKP_RBWqCgZ9uroyqVsYkhvBTkHZqIqvzygUJZAf5tY,5680 +tensorflow/include/tsl/lib/math/math_util.h,sha256=p0WkyVsoIA3hk9byzky5RnIEiNFXQ5_Ryii9JHp2N9w,6575 +tensorflow/include/tsl/lib/monitoring/cell_reader.h,sha256=cNngI2guOnD58MsGR4EI-jOKUzoFCFM1bIG5u7IqnEc,6919 +tensorflow/include/tsl/lib/monitoring/collected_metrics.h,sha256=rQVr-kolLLztwyrboael2RzJAjSgQP78Gbd1QGP8H3w,6069 +tensorflow/include/tsl/lib/monitoring/collection_registry.h,sha256=ITU4fLUaUxk3MIdt6uKjhg464z0bwfKUzoRdLqCsiy0,16847 +tensorflow/include/tsl/lib/monitoring/counter.h,sha256=iEV-fwZX99FDI97HOI79MRsMsW240e9OyvNooivgHbo,7388 +tensorflow/include/tsl/lib/monitoring/gauge.h,sha256=M22uEKXPPx60aunfBch97pqrGYdgdPTh5r18SCkufws,10070 +tensorflow/include/tsl/lib/monitoring/metric_def.h,sha256=kqMP5PqrnpPsDzElMDM1vjDGN8XTQQD2p9GRnwu5FhE,5388 +tensorflow/include/tsl/lib/monitoring/percentile_sampler.h,sha256=TG7grdkl5vECx5LufIoqHBJqQOM8iJjm8aszSQ8z0GM,9855 +tensorflow/include/tsl/lib/monitoring/sampler.h,sha256=2MzQ_Iv6Wxu1mx_TjnD_Sps6Tdp4HXcnJ3pjUwS4T1o,10640 +tensorflow/include/tsl/lib/monitoring/test_utils.h,sha256=-d3KlUq9NHolHV7Wx3M70SMDbEUKJppdH3uN6oKJPUI,3188 +tensorflow/include/tsl/lib/monitoring/timed.h,sha256=0CEtIue8D4R6LjCLU3gTg96dlsAbqoiRCu2XSnFEFho,1494 +tensorflow/include/tsl/lib/monitoring/types.h,sha256=hqzPWdRQnVdapWpQQPh5M_SmPjlvp-ygB8iaWMUIxso,1496 +tensorflow/include/tsl/lib/random/distribution_sampler.h,sha256=eQUyX4p2ORpQPir5xiGPnImcExx0y3Jbi4RmYJgqFjQ,2907 +tensorflow/include/tsl/lib/random/exact_uniform_int.h,sha256=aRnvVno0MUYKGR8TiyJA9ndJd2LGKTLPuw4Pyyi-AhI,2930 +tensorflow/include/tsl/lib/random/philox_random.h,sha256=VZG6RSNMM8-P3jl6vqIzM49TXnBTWYU4Q4UNNeQuJEE,7932 +tensorflow/include/tsl/lib/random/philox_random_test_utils.h,sha256=bfu1qSiMCyAEtwbWO9RNtidXQsMGapYbwY02R2C5WZk,1711 +tensorflow/include/tsl/lib/random/random_distributions.h,sha256=tDEHD1S425NspYGKux7cdUpPzv5lURUoaV_stSdZfNo,27766 +tensorflow/include/tsl/lib/random/random_distributions_utils.h,sha256=i9Hx7pDjKAaM3x8agj6vUIa3y4mK7IMQEAfg21cibvg,3444 +tensorflow/include/tsl/lib/random/simple_philox.h,sha256=KW69FRWE4SQtCOc5XeXZ9YjGwsJFR6Qws5113JB1HI8,2388 +tensorflow/include/tsl/lib/random/weighted_picker.h,sha256=Bp2HmYSyCkQtDJ6Gf-NI4Syh0EGErlw-QVV1an-LLjc,4374 +tensorflow/include/tsl/lib/strings/proto_serialization.h,sha256=56PeUXeHXg6iqW8bGTkc-2rmv_GKUjPbLPgQr-Xkcfw,2236 +tensorflow/include/tsl/platform/abi.h,sha256=cG4eLK-_ZzjPjpqLGlthb2UT8rE_bEBwxVEobZu82Jg,968 +tensorflow/include/tsl/platform/base64.h,sha256=2LeGUh85arAeiFuko2l8rZeP6OVK6BLjwR_6kcvqZKQ,2416 +tensorflow/include/tsl/platform/bfloat16.h,sha256=QfIKVVNzqEvImFXW1B_b0NMtHK-iRepoKEKGovJdmTo,967 +tensorflow/include/tsl/platform/blocking_counter.h,sha256=pqX6xmen8phb8fW9uPQVp-tX8ksdaQMJwMNpcbMZZ-E,2372 +tensorflow/include/tsl/platform/byte_order.h,sha256=1ose7fnE61B8zBpMCPqhn3DK6Y1tOvMTCjzUhSpTg00,1333 +tensorflow/include/tsl/platform/casts.h,sha256=823zefPnyZjRuHK6AKnO02nWl4uUjoc-bVHkFeDZBPU,1280 +tensorflow/include/tsl/platform/cloud/auth_provider.h,sha256=5GAmN5Pqmc_O4CBMOKskL3TTxLahPngUcgN5boxHRM8,1665 +tensorflow/include/tsl/platform/cloud/compute_engine_metadata_client.h,sha256=ewlx-KwK2_ghnljXrikW3kFLURHv7qByLA9yJ1mu0IU,2657 +tensorflow/include/tsl/platform/cloud/compute_engine_zone_provider.h,sha256=6NJWhLdbh28hH_rdJHRVhSTrUWmn8hay2zVZmjPkjtI,1535 +tensorflow/include/tsl/platform/cloud/curl_http_request.h,sha256=eTH7jgGFq_fQaFhj8GtC0_3xPQUZg-LXyHDTqnvrNxw,10813 +tensorflow/include/tsl/platform/cloud/expiring_lru_cache.h,sha256=mEPxgiYMSr2KZiTm4FXqpS-_enuuEBOdRFEAHWdB57Y,6114 +tensorflow/include/tsl/platform/cloud/file_block_cache.h,sha256=FRIpNVmQXOPvN9UyIdZ7Zg3zokCT_an8saFlWlXBxwc,5315 +tensorflow/include/tsl/platform/cloud/gcs_dns_cache.h,sha256=K_-UUagvbbTRbDq8R2RNskdLbh_JpL5OLbkPC5fbxI0,2680 +tensorflow/include/tsl/platform/cloud/gcs_file_system.h,sha256=cH2j7-R_7kGNuCiUcfOfsnWCd2zXFVW0GDfSgfcIf0I,18575 +tensorflow/include/tsl/platform/cloud/gcs_throttle.h,sha256=3B1iCJjMeUjtgxMfxT9YsfOsuWGLLQ3iLFJG3Z1Fphk,5456 +tensorflow/include/tsl/platform/cloud/google_auth_provider.h,sha256=Bk55-JEOshWo2mNtEd6kkxIzVixgCjxzhKgsNqJrL48,2734 +tensorflow/include/tsl/platform/cloud/http_request.h,sha256=UoRFRWpYVGrpakbx-xMSR-NLZGxsVc_UIzvGTqz5_wA,6998 +tensorflow/include/tsl/platform/cloud/oauth_client.h,sha256=ZfMuWDWFF4gs6XM2QtMk_as_IBZUYf2cshbixHqh1ic,2371 +tensorflow/include/tsl/platform/cloud/ram_file_block_cache.h,sha256=ay4DGCuyqA5cg9gjX0gou9cDps9-QwtmdB5Vxv2rvHg,9945 +tensorflow/include/tsl/platform/cloud/time_util.h,sha256=n8_GHzOFyiJpdT5pCdt3DB2QYSXzj0h6RQWHaAEsj5U,1057 +tensorflow/include/tsl/platform/cloud/zone_provider.h,sha256=0Z-gv4stkJ4Upl6WnbJYuhZuXr3oI46T-m2juAws7DA,1580 +tensorflow/include/tsl/platform/coding.h,sha256=INF9SzsLbUGzuG0PVQ23jVAS_HPnQOSUFWgdTV20b1E,2826 +tensorflow/include/tsl/platform/context.h,sha256=5RCfXIf_ewEf-SONDFHH-xEsIswSg6LypEzh3JNwIOM,1532 +tensorflow/include/tsl/platform/cord.h,sha256=A9p3UwG6rsITNfEHYuLUXhtu0GHkUTDUjl7-Mq5bXzc,1028 +tensorflow/include/tsl/platform/cpu_info.h,sha256=Y9ZsGsIS4GaCqjRwSTliXkphQQUIkg9f9UJLJuvHF-0,5965 +tensorflow/include/tsl/platform/crash_analysis.h,sha256=qy6CDl85CFX_glF0bBZ7HHCmrI19ehA__N6AOSaODYw,1106 +tensorflow/include/tsl/platform/criticality.h,sha256=lqTyQNWj1Q6vbFY7lO4SwcCiAEuUf1DNDDDsxAi2cQM,1689 +tensorflow/include/tsl/platform/ctstring.h,sha256=gtcB92SahlLfqo5tDUGUov-LBzBQ33Uo1mwehWsPrMk,6165 +tensorflow/include/tsl/platform/ctstring_internal.h,sha256=o5MhZTcc0SixAfsrgnT9sPNrjnRhwW0Y-wqNiR47BOA,13731 +tensorflow/include/tsl/platform/cuda_libdevice_path.h,sha256=zkxWZvDJ9CfIgh1_l4HYneuLzydBUSg1oPdazgPU4C0,1832 +tensorflow/include/tsl/platform/default/casts.h,sha256=Sxph8btO4VtWqBw9R3DNwlD-Ry0ZMgrqG_L5g4JG6Vc,3937 +tensorflow/include/tsl/platform/default/context.h,sha256=Y7yjtAyjVr_sz-9UaFPbMy5kgd9CS0JihKwyl4Nhdjo,1107 +tensorflow/include/tsl/platform/default/crash_analysis.h,sha256=QU1VmzvV7DFC_6QtpGb-D-YfSi8U9IPtgU4uEWDsxeM,1814 +tensorflow/include/tsl/platform/default/criticality.h,sha256=F-Q1BveYCDQlNE91NP1Tk4kfTZ4_yxLzWkp8MmqNTH8,1065 +tensorflow/include/tsl/platform/default/dso_loader.h,sha256=hWDpUz86PKyLPsQppiYPxqH1smBgEklCyBeL8mqsp40,3590 +tensorflow/include/tsl/platform/default/dynamic_annotations.h,sha256=kxeNd9Z9DMs1MeHt8D4Uvqc2UsYUUPW437N8QuXM2ok,1336 +tensorflow/include/tsl/platform/default/integral_types.h,sha256=L8vUmNYzEsA87wujdhqQs-xdAq4B7h1F9liChWcxTHI,1247 +tensorflow/include/tsl/platform/default/logging.h,sha256=Bxr2MaeuKjNNF4S7fJpIlSQdhl3Ww-Uw0Jwxs6s1DtE,24224 +tensorflow/include/tsl/platform/default/mutex.h,sha256=z4F3uq2uNXjaKjZc5OEdsSaO2uy31jZiZsjWyt0feqw,1446 +tensorflow/include/tsl/platform/default/mutex_data.h,sha256=c6EwSCvLzv4dQVnKwtb6-0O8-6cZFnEvbVZtU0KZx6M,1077 +tensorflow/include/tsl/platform/default/notification.h,sha256=faxTcElkcYYNtCBQ9IDHbHZpSr2Cld4UaYgtSkMwGwI,2701 +tensorflow/include/tsl/platform/default/posix_file_system.h,sha256=3xmyVd0H44Sw8vxPicJM69rWdQuo49qWRjNiKRmrTUI,2992 +tensorflow/include/tsl/platform/default/stacktrace.h,sha256=51wXAYitt_UCR0YiIpeFr83Y6nKNQPuBA1MOM8eUGTI,2693 +tensorflow/include/tsl/platform/default/status.h,sha256=LefV-UkuQ-WFYgVdbOrWuNKn_RJ_YxgNJoXPk-iBi68,917 +tensorflow/include/tsl/platform/default/statusor.h,sha256=2tXFF23VvHXeg4wRdK4eG6aGG8w2EthXAYJnliAvhU0,1416 +tensorflow/include/tsl/platform/default/subprocess.h,sha256=hRAfipBH7rtd4UTN_iBWqoTU05QEcoNAux4Wze_V57c,5256 +tensorflow/include/tsl/platform/default/tracing_impl.h,sha256=GYtRBsH-8pmecaVGf31khmcvg0MtIRLE4scuFhUPyZg,1348 +tensorflow/include/tsl/platform/default/unbounded_work_queue.h,sha256=5Fs04iYHU65bBxUI9IN_rGVKXdME2ptP2PENTQhkLm0,2755 +tensorflow/include/tsl/platform/demangle.h,sha256=-FfgkPNrMWb-UdeOsqSm6WN7l_CVumn__LYXWp8esnY,1169 +tensorflow/include/tsl/platform/denormal.h,sha256=NorvQc6tXh6TVGZ4oZJovYTBlGY3ImK9DTo8enPisw0,3143 +tensorflow/include/tsl/platform/dso_loader.h,sha256=ujWXx-KVW3QUoXXhHYUaVNfV8N2FPA715j-5GUtudHQ,1275 +tensorflow/include/tsl/platform/dynamic_annotations.h,sha256=EaTF_LW0HC7bK9fR1ZIuO90UAlDrEqRZ6r6wNIEjpJw,1408 +tensorflow/include/tsl/platform/env.h,sha256=f-UpPp716usl2TgCegUvzcvIXcilNfoQ4Mgk9BqlBnc,28548 +tensorflow/include/tsl/platform/env_time.h,sha256=kItm1M8CC1Addtbt5zpinomMcIzplTOo-XsYr_zbyyk,2445 +tensorflow/include/tsl/platform/error_logging.h,sha256=oJssRW7EBN_eTNAyHiV0XSPm9dCZ2PBPbQqBV8sXEAI,1053 +tensorflow/include/tsl/platform/errors.h,sha256=IsDjUUJFXKdI7AymI7p5NYliUSUhFeEYSWS8iLgtN3I,24971 +tensorflow/include/tsl/platform/file_statistics.h,sha256=HX49M2SrPmsqEqWYQvnmhFSNhQzUyKb3QcGEQw9y-xQ,1374 +tensorflow/include/tsl/platform/file_system.h,sha256=_0SGjkBPkFhPK0L07XvKlKmg4iS14777-38Z9-3PA04,35355 +tensorflow/include/tsl/platform/file_system_helper.h,sha256=_zu0KScFfD37c0txMwntrJI2dUqZOI7XLGP5EK68zHY,2196 +tensorflow/include/tsl/platform/fingerprint.h,sha256=Ovp8plsygTy66wdh0aU6LV7hSU2WvyhpsQj3YsfgyDs,4480 +tensorflow/include/tsl/platform/float8.h,sha256=tQKh2YjcQWdm81fKz2FB-UEX1WjKDKMmOTP0SI7Xo4I,938 +tensorflow/include/tsl/platform/gif.h,sha256=tUsHFh-yCgQV7Rsmb8Xbuf-X50K4UTUBTODL6FD8CCc,827 +tensorflow/include/tsl/platform/hash.h,sha256=xdcxcB0ILmc_uu-HFkHUhV_0dLGIZbGQlmQF8yGnWj0,4233 +tensorflow/include/tsl/platform/host_info.h,sha256=2a98DcHT2bR4te-78VvKjQ4jPuQcuP2oWcwLNWIuhws,1307 +tensorflow/include/tsl/platform/human_readable_json.h,sha256=yZW_fTshYc0pagEf0O-3TEj8SnZ6CIJRNzWmhqzxIFQ,1875 +tensorflow/include/tsl/platform/init_main.h,sha256=VeGZf2EgW7YnH7Is6a5_MPu-iFVrUpI4TXQMeXZHcLM,945 +tensorflow/include/tsl/platform/intrusive_ptr.h,sha256=HQ-d46uft6LOkQUSvG4b26W80klD2yQ-P9tFZrU6Sxs,2808 +tensorflow/include/tsl/platform/jpeg.h,sha256=5MbrkpprrFdHwQYGQsCnmm5Y51ERMjSfUHE5RnEEDO4,1031 +tensorflow/include/tsl/platform/load_library.h,sha256=TJ3km7DeW2-Jen9fMRVZS4LAE_RxAz85nDmRh6HrQZ8,1195 +tensorflow/include/tsl/platform/logger.h,sha256=-GLNgNpDiSahdHKjOBJeTGQ113e6Nl3mfU3v5Y953wY,2557 +tensorflow/include/tsl/platform/logging.h,sha256=y6PCgZD2smAJ0PldZ37usTB2p9kMdeV7TCbac637lAI,1184 +tensorflow/include/tsl/platform/macros.h,sha256=nlssM168-aJOfK-PDCgNzd_SUPkdLCyCdpz3XAGmXYY,5918 +tensorflow/include/tsl/platform/mem.h,sha256=9inPxfkbcFOiT9mTYHqLvXa23voKwlsZgH0yevBIQwg,3179 +tensorflow/include/tsl/platform/ml_dtypes.h,sha256=LTgWZNHeABwGwgM4viAcX1mWy0mAVdruCS4yenm1gzw,1426 +tensorflow/include/tsl/platform/mutex.h,sha256=42TDQMKQAVL1hnrWhR0KOGDXMXTWV7JhzuINOHck0vo,11557 +tensorflow/include/tsl/platform/net.h,sha256=zNRnSa0Lzv2C_RkxWajj728Xcky5lMLgdPN3TkfxEkc,903 +tensorflow/include/tsl/platform/notification.h,sha256=lupKUX8Nf9arjNGXhTnDTuXqMc3rFVZw26ZExO_avwA,1390 +tensorflow/include/tsl/platform/null_file_system.h,sha256=POv4RND5oCdmeh6LEC-EXU4XO2L4RpLbjDsmlUQFXgQ,3786 +tensorflow/include/tsl/platform/numa.h,sha256=IvaCp9s8ORuJZNZPssleEhbNtsmjpuiLVDOzGp3KG1s,2334 +tensorflow/include/tsl/platform/numbers.h,sha256=YK0KyqApfXyZb7W23wf5NMml_ETZ2Pz90KRkmdWoNVc,6894 +tensorflow/include/tsl/platform/path.h,sha256=DkIRma2hzNVZeR3HExyUi9YDqiyKXPy3SQeTuZ8bxYs,4755 +tensorflow/include/tsl/platform/platform.h,sha256=OcZ90jQbXDzzgCs3aIGfKzSpfqUV0S0nJhddQBaTE6Y,2490 +tensorflow/include/tsl/platform/platform_strings_computed.h,sha256=JuM4fVMQshVbbB6y6Woc1edx4pthTbAcqHW_fj9exm8,19436 +tensorflow/include/tsl/platform/png.h,sha256=hBVSoRsFl51nvaWHSKFnfCumZy3TPM-WNjyiEvSYOGU,1198 +tensorflow/include/tsl/platform/prefetch.h,sha256=Kq61cBLsaA8EHEmC7ZKsOOC7IfHZzDmpDiAQWr0q2i8,2116 +tensorflow/include/tsl/platform/profile_utils/android_armv7a_cpu_utils_helper.h,sha256=hPtVCe54ozVN-6__GQbJaCIn4ZLQ9lPiMfRLTzEeiZs,2417 +tensorflow/include/tsl/platform/profile_utils/clock_cycle_profiler.h,sha256=xnTp6f14BBAYfLCk9356I3HAwiuK6vMcZr6KwXiAimU,3221 +tensorflow/include/tsl/platform/profile_utils/cpu_utils.h,sha256=ldsbULEZaR6vYI4JLvwiyRThNLsHnjbognNIoDQfEf0,7468 +tensorflow/include/tsl/platform/profile_utils/i_cpu_utils_helper.h,sha256=7FwWWX1jaI33Gwv-UInUFoC5QS3QLsrRtPkl4mhwpeE,2084 +tensorflow/include/tsl/platform/protobuf.h,sha256=AuiBnziWVgqlQ_pwOSbpg_hh2ggtjQcKveCnanzqBLM,5152 +tensorflow/include/tsl/platform/protobuf_compiler.h,sha256=5rgqklPQPDhbOQWKTkF2BLezdzrgVquqvRB3WbU4zpA,905 +tensorflow/include/tsl/platform/ram_file_system.h,sha256=uXt7MwI-Ut5eJqu1LfMXHaFU3phNoNBRlWPhtcYCqio,10648 +tensorflow/include/tsl/platform/random.h,sha256=nSn_LMbFFMgxHN4IY_h1fElAOKWe6OOF8x_JPr4abHw,1250 +tensorflow/include/tsl/platform/raw_coding.h,sha256=rzgpzoVTm-XVKn2eQIPanREVj9lGIc7KlAenKTN4cIk,2364 +tensorflow/include/tsl/platform/refcount.h,sha256=Qhg6a7hA221rl231GVJuX_kzt42zQ9vCbxpnJj_F9Tg,10668 +tensorflow/include/tsl/platform/regexp.h,sha256=c9YKykntQYv-ppS1bqckIacBFG5JNO3B7gwcG5I2fzM,1108 +tensorflow/include/tsl/platform/resource.h,sha256=r-7zYEbTnl1bziBYkUbuvUti5jCsWixfT5goqmqijNA,1432 +tensorflow/include/tsl/platform/resource_loader.h,sha256=1M-qlStvtq3gxwSLQCB80wmRBwMRr1ZvACjtJMKgAkk,1226 +tensorflow/include/tsl/platform/retrying_file_system.h,sha256=ZSRvUJ2HODXG1GCSFyyl6xkF-O2bbmlo56UU3H62bwI,10574 +tensorflow/include/tsl/platform/retrying_utils.h,sha256=RkXlONDpYVX4535d6jMBLVrUDRYW-Zyhz-IF-iEttr4,2748 +tensorflow/include/tsl/platform/rocm_rocdl_path.h,sha256=kBKtKTXQzW9wMs6A-UshADOdeMytpzOr2aL2ii2PCf0,1124 +tensorflow/include/tsl/platform/scanner.h,sha256=H9NE_9U8zy4owd4fEraV65Y5HRcq11YndqiuW9Esdys,8060 +tensorflow/include/tsl/platform/setround.h,sha256=gre8uJTLottsEwcHzlsOe_tzhqg62yLTv3etIVsTeyQ,1776 +tensorflow/include/tsl/platform/snappy.h,sha256=AL8BJBiUXR3lUndG2M3cb3Y4bq7LWuqI-2kW5yfrD48,1745 +tensorflow/include/tsl/platform/stack_frame.h,sha256=20wyZNQvPzJm4NhORe8gaY2XzVVkyeSy_3qRsSDUbgw,1721 +tensorflow/include/tsl/platform/stacktrace.h,sha256=N1_cwT8svIORm6Gob7wnzGrVD74eLk6b8TdqDo3OkvY,1459 +tensorflow/include/tsl/platform/stacktrace_handler.h,sha256=kyQ0LMch6MunwOsryjAc2FM7Q-YuWjEgC4zTU-tEO8o,1218 +tensorflow/include/tsl/platform/status.h,sha256=4xsIa2Wzae6dg_vd8oFh42Hi9K3RAv_6sHxI0t38oFY,7113 +tensorflow/include/tsl/platform/status_matchers.h,sha256=2zECao95ewtqJA0LQW8ubzv6z9DneZli_Z91XBGKoDI,11910 +tensorflow/include/tsl/platform/status_to_from_proto.h,sha256=Cp2GAk67upz5DO2l9UovvMX5eKrynsKcR1aqV6dxW2k,1620 +tensorflow/include/tsl/platform/statusor.h,sha256=0AA3gc1VZHNyfEpL5JGKFMPdvHiT-0hMLqDIBIJ7ksc,3652 +tensorflow/include/tsl/platform/str_util.h,sha256=XuVN4XYi0YglmfHKBnHraog_f2aiH5t0pmmcrV23gYU,7059 +tensorflow/include/tsl/platform/strcat.h,sha256=EPxtUJtowrXBqMGgoJpvNy2eRK6CuHv2HqidwIoVfEk,9824 +tensorflow/include/tsl/platform/stringpiece.h,sha256=GkhWyfIjZFtvm0b8HH4EJXq7t3M4W7q6vOuQujTlRQw,1433 +tensorflow/include/tsl/platform/stringprintf.h,sha256=qn-7daP85qADG7lcy8L_qE5pFRMjPh5Hkw-n5G0fiSI,1761 +tensorflow/include/tsl/platform/subprocess.h,sha256=-Ta7RXHJybxNPbYmE-O33VqcPf3y8YH4mNE_HcPkE4I,2402 +tensorflow/include/tsl/platform/tensor_float_32_utils.h,sha256=Bhw_oJ_RcAtS8EYM677qw-r-ptzRPDkuzLM0MGIRBuQ,980 +tensorflow/include/tsl/platform/test.h,sha256=2IgNF8U_eyY28_YBpHArHKCYclcsT4Fcz9vrn7-avHQ,3471 +tensorflow/include/tsl/platform/test_benchmark.h,sha256=NgCqmbbZCImQLMSea_4OpWyfVbJ_rYO9BFPhiDAPG1g,1669 +tensorflow/include/tsl/platform/thread_annotations.h,sha256=4DlDn6a03IgwVQt2EmFo3PtwxtMpL_LOQXKTxli2Pvc,7829 +tensorflow/include/tsl/platform/threadpool.h,sha256=AVtEcmJxOuFr4Xzl7WQ2h6erY2vRjrpC0-tDchNCsX4,10943 +tensorflow/include/tsl/platform/threadpool_interface.h,sha256=1hlti9OWtLseKJmWLih8A0olcB7but46VvtJQA_BKD4,1124 +tensorflow/include/tsl/platform/threadpool_options.h,sha256=H9k8yT_mmon90QIApC7BlF2tngPXeDYtCgvP4qjOO2I,1258 +tensorflow/include/tsl/platform/tracing.h,sha256=xCnJHOZH3i4hdDYtjENiong60Q54dtckOXb4v1T9c54,4762 +tensorflow/include/tsl/platform/tstring.h,sha256=2y74sC-qto6phf5eh7nyQx4OnUblKl3iTOILI1JXUk0,15797 +tensorflow/include/tsl/platform/types.h,sha256=BnkhxZbWa6X6YllAqD1jAMDgeRJ5SzxPSUsswgm4HbA,2923 +tensorflow/include/tsl/platform/unbounded_work_queue.h,sha256=3A9rfd974GncOc6NN5yvdbJkhcY9OiUO_dx3yzFlH7s,1485 +tensorflow/include/tsl/profiler/backends/cpu/annotation_stack.h,sha256=aDZRHJTfoqyJxUnvNLj3qYFUVTagghQJgsuvmNIsx5Q,3152 +tensorflow/include/tsl/profiler/backends/cpu/host_tracer_utils.h,sha256=0zLv1ZSEY-yQ_2UUBkW1L_KlDHJd0-kSrZ-MEcJiGpk,1343 +tensorflow/include/tsl/profiler/backends/cpu/traceme_recorder.h,sha256=NTzgiULJND8QJjNrME4-LvmC4oBcStRcoJ4p7Rs1Jyw,5204 +tensorflow/include/tsl/profiler/convert/xla_op_utils.h,sha256=BoG9JJnf6VRAFFAWd0VsgoyiH87-VHmjEk8-uC60rnk,1462 +tensorflow/include/tsl/profiler/lib/connected_traceme.h,sha256=QR7_Qf27YrJNgP44hdH_vCT4PTStrgframJ8KZU2lIM,4617 +tensorflow/include/tsl/profiler/lib/context_types.h,sha256=S2yDyksXuIvrK1s2MCDDKOVms3ub114hzvY_IBaH9C4,1800 +tensorflow/include/tsl/profiler/lib/nvtx_utils.h,sha256=TuIbfQ4iblcj_s1j_-bVn0lg4F17RHRImgP19mL7c3U,2408 +tensorflow/include/tsl/profiler/lib/profiler_factory.h,sha256=-j2Ej00FGPY0l-RmjyPyEuGk2kO8UmbDLDn3cifmihA,1777 +tensorflow/include/tsl/profiler/lib/profiler_interface.h,sha256=HNel3IptZpsgw3h6OhzC-oQmbB5rVbEfNVVLGcRpN7k,1681 +tensorflow/include/tsl/profiler/lib/profiler_lock.h,sha256=C0qjg3Rw1y_W2cj0vxHhSfsqHYPyMaUeh2UIJn5Doiw,2300 +tensorflow/include/tsl/profiler/lib/profiler_session.h,sha256=4Txk0PzaZv7k1FVmiWBRm7jmnFCdajAn1lYoPId64JM,3335 +tensorflow/include/tsl/profiler/lib/scoped_annotation.h,sha256=6_IKT8UGqkF7gNxps4GjpffAjDo1J0CLnSmlzz06piI,5565 +tensorflow/include/tsl/profiler/lib/scoped_annotation_stack.h,sha256=gXr3x6RFpE3w4UcTHd6maPTNPdE3lrRdPlksLVLR0Ig,3930 +tensorflow/include/tsl/profiler/lib/scoped_memory_debug_annotation.h,sha256=qaR4-nf9NLxrUStUs846e3lbl_pdAfov4Km2q50Wikg,4565 +tensorflow/include/tsl/profiler/lib/traceme.h,sha256=Crk5CFGAtzZGTOBkdnKWRtf1zXXFVoApv5oj7N5cSQk,13014 +tensorflow/include/tsl/profiler/lib/traceme_encode.h,sha256=UUS10qt7kZ74ZnZ3ZTXApiAdpm4Xt2hSTcgPMYn3yI0,6248 +tensorflow/include/tsl/profiler/protobuf/profile.pb.h,sha256=PHjhCjdubWmlIkSUVZxwSg84iBbhXwRXvOWbnWQQXPg,105039 +tensorflow/include/tsl/profiler/protobuf/profiled_instructions.pb.h,sha256=7Uc68sj0BDy_uOvdtoRtcJlffcJoA4fw0WYOop7TuSE,37638 +tensorflow/include/tsl/profiler/protobuf/profiler_analysis.pb.h,sha256=78z_LEU263LFGHN4bjrHrq9Ln_iTwKYmLordQFNUss8,101456 +tensorflow/include/tsl/profiler/protobuf/profiler_options.pb.h,sha256=9xo0QE8G23g_4agFq_yFR_JVtR2YFU6moMlooCtszr4,44476 +tensorflow/include/tsl/profiler/protobuf/profiler_options.proto,sha256=hVBmvbvJcLrUnoamr8B-gR1j6gjS7JrfywOhlUPdtEo,3216 +tensorflow/include/tsl/profiler/protobuf/profiler_service.grpc.pb.h,sha256=OMmyzmvUSIdCQl9VfRl3pefqjxedWSJbewztqJxSp0o,45758 +tensorflow/include/tsl/profiler/protobuf/profiler_service.pb.h,sha256=rvq7HmOd57O5xhcDpgXMkwPSe4n_bi4GUHzNiAzPK80,91599 +tensorflow/include/tsl/profiler/protobuf/profiler_service_mock.grpc.pb.h,sha256=f52sfE0SLYqmCulSyujbKgkkCpfx7obNEEAe0x_EVX4,2366 +tensorflow/include/tsl/profiler/protobuf/profiler_service_monitor_result.pb.h,sha256=-t-qdw9azBLjpZrtujidZq2c15UIP529TeQrMKAz2l8,24010 +tensorflow/include/tsl/profiler/protobuf/xplane.pb.h,sha256=UlV6KFqevwCwcX6jO1owqcznu5p18N79qM3DbqIUjeg,121459 +tensorflow/include/tsl/profiler/protobuf/xplane.proto,sha256=iNIS3zQqYe9oIj9TivspLDIlwjDOzSSEn98-mUpN3SE,4532 +tensorflow/include/tsl/profiler/rpc/client/save_profile.h,sha256=teI3qYxbdJYNYsFdYO42l04-7_Pj0RF5sc0vlyOwYc4,2337 +tensorflow/include/tsl/profiler/rpc/profiler_service_impl.h,sha256=dR14pA0DX7upDVadtkXFZVFEYFmCfMqhvjQIiOdc0oU,1106 +tensorflow/include/tsl/profiler/utils/buffer_pool.h,sha256=sXi2Dyq8yjDildh6HPCntQoWF1mTuHIJvJ_Fug_bUzI,2141 +tensorflow/include/tsl/profiler/utils/file_system_utils.h,sha256=plDRpFoKIK-RnMUEenKTPzU-_gTVYh9qVyIWM4MN1nQ,2037 +tensorflow/include/tsl/profiler/utils/math_utils.h,sha256=1213LtM8p9SI8KJIgHfLLafitiQrvM-QxHVfO6BUHKo,2994 +tensorflow/include/tsl/profiler/utils/parse_annotation.h,sha256=XnhNizcAA-v8uucTF0FtUFDS15Knd_uIU3Ist4GiSuo,1712 +tensorflow/include/tsl/profiler/utils/tf_op_utils.h,sha256=PSeih8S1sCHzRCgcK9SEk8myqL4IOhh02qtap3v0J1U,5476 +tensorflow/include/tsl/profiler/utils/tf_xplane_visitor.h,sha256=Z9Vd2kwpmhIp30US_hgOX3GF-XPZTeZhzv9_Bsanq0M,1280 +tensorflow/include/tsl/profiler/utils/time_utils.h,sha256=9yAwD4dRlG5PhmdZP8rPh96mdLaB2wTRT8WpClHsSkc,1572 +tensorflow/include/tsl/profiler/utils/timespan.h,sha256=EXoKVkuIiRqkDlbjOWb7ZSnRiNg31qlcrCwv_L_m5uc,5051 +tensorflow/include/tsl/profiler/utils/trace_utils.h,sha256=vBL1KGrZ2jdPuDjGqUQnbIZ6C5nAcIMWqLt2oanqLx4,2714 +tensorflow/include/tsl/profiler/utils/xplane_builder.h,sha256=mnoq-Cgy7yVQ9oIsQrn_SQJKn-d_cDeKOwkiWyedcl4,16102 +tensorflow/include/tsl/profiler/utils/xplane_schema.h,sha256=y1D4Ze2aIphq6GI2YyFVPQCS85H2TtD1vWSat0T3iHU,14161 +tensorflow/include/tsl/profiler/utils/xplane_utils.h,sha256=Af7Aep8MGgXzdh9iEtE4y1SWDU8ghwEN6p8OAfyOx9U,8773 +tensorflow/include/tsl/profiler/utils/xplane_visitor.h,sha256=Pj3bqelaooQAQz3OU8V8vyAXUwj2FkIeKs6_eSdH3CM,12013 +tensorflow/include/tsl/protobuf/bfc_memory_map.pb.h,sha256=ET8ZmvevjYUpPknukTL7cVvM9NopDvwggoJbV0jAZXE,63172 +tensorflow/include/tsl/protobuf/bfc_memory_map.proto,sha256=5numCqlHUQYO_qcm6gWwuxouasjkAbleJHl_cm3430k,998 +tensorflow/include/tsl/protobuf/coordination_config.pb.h,sha256=kjiqHKPXpQ7Jum0w4qAF6QOltpqUObC-i8jjtSCj1yI,39922 +tensorflow/include/tsl/protobuf/coordination_config.proto,sha256=DAJeejk-tpAGtUBqtUIkpM75qJvNfh9x-xAfB7O82Bo,2945 +tensorflow/include/tsl/protobuf/coordination_service.grpc.pb.h,sha256=e_IMtefTC5-WTAg4GcM4gEsuxC2UiB06VCwDch7s7sY,235017 +tensorflow/include/tsl/protobuf/coordination_service.pb.h,sha256=CZ3Gt5W1RA9o68PpuR752wQl69r8RZRW3s54d80MQI8,325635 +tensorflow/include/tsl/protobuf/coordination_service_mock.grpc.pb.h,sha256=EnbYUhYu4R7EKcdfxQo90c8Aq4r72mTKYZK0Bqp7rTA,10309 +tensorflow/include/tsl/protobuf/distributed_runtime_payloads.pb.h,sha256=gJxFD7vfKW_4hhvvGsfRNBGXKpUwyHEJM7GnssR3acc,22583 +tensorflow/include/tsl/protobuf/distributed_runtime_payloads.proto,sha256=8hua5uB4F8mlYM1OcH6o3JBlLdMLryTc_FO4oGMrv0E,890 +tensorflow/include/tsl/protobuf/dnn.pb.h,sha256=AYn4FkZiYpw5NHZ_TLps32CDGP1pigxEG3LYXpLE9mQ,88437 +tensorflow/include/tsl/protobuf/error_codes.pb.h,sha256=oXi9DKjyPyFnRcqNqd6XBothzjlURjq8cyLzaeLCHWQ,4241 +tensorflow/include/tsl/protobuf/error_codes.proto,sha256=dfDydWk0PVYqUFWm5Ow7CW8sGIKWf414s4zCmFSrf50,6575 +tensorflow/include/tsl/protobuf/histogram.pb.h,sha256=trsORy2ScuY1pvhBE8oyOQ2a4OwRDYh4KT7Ahw9cumY,16901 +tensorflow/include/tsl/protobuf/histogram.proto,sha256=jt9Qkt6kiRVlxeOXhHBKNBUmng_-L4lECqIpkN0gfpg,798 +tensorflow/include/tsl/protobuf/rpc_options.pb.h,sha256=rjyCk_yb4NwMZfZVb30urTMXGEdTNdsIPPdIbAlo014,16330 +tensorflow/include/tsl/protobuf/rpc_options.proto,sha256=C2K5wJatr61jPbLHsJ6G96QQsg1ZSz413olTQ5twlr0,1846 +tensorflow/include/tsl/protobuf/status.pb.h,sha256=gib5IWmv3KqoVwgtIiMEoyaL8Zgj61l7XkYVMnggWPM,10890 +tensorflow/include/tsl/protobuf/status.proto,sha256=JborF3CrtI1U37iEWY-Gcyte_Bt8zLkWuVWYAzVYYTQ,500 +tensorflow/include/tsl/protobuf/test_log.pb.h,sha256=5pIwklndPBGm4urB2aIY3KuSK0ddH2z86V7T_DdEXzo,243492 +tensorflow/include/tsl/protobuf/test_log.proto,sha256=58HCVNeWqu1iauSkDY6U7WiFZE9mCrUZi_VHynhiEbQ,6736 +tensorflow/include/tsl/python/lib/core/ml_dtypes.h,sha256=e1We5UIv6Rb5IDlSQBY9YAj9ayVvz0glHn4YL8lN2yE,1694 +tensorflow/include/tsl/python/lib/core/numpy.h,sha256=mFx39tFAllsSq3t8OeQUP6kTFb768pDyWfpZBrBCJCA,1597 +tensorflow/include/tsl/util/byte_swap_array.h,sha256=z6v5MkJ7xuLjrdq_Lj2lnZ6B8p2JqngCf5vxeV3GoeY,4299 +tensorflow/include/tsl/util/command_line_flags.h,sha256=YMBgDgJJpOuHUtRvRsY38KayeCDxkOK77cYN17MheuQ,5545 +tensorflow/include/tsl/util/determinism.h,sha256=1fNrl0CrB34sVi4QvnySt6U71X2MKDjMQt7euzcc5nk,947 +tensorflow/include/tsl/util/device_name_utils.h,sha256=XmuW-dn_Z8AIchfJJz92CBS8I7FSesBAm2eM4EIRZog,11728 +tensorflow/include/tsl/util/env_var.h,sha256=GwpsdiW-tHwPELgaJgENSq_BrmZYenZ32uWu1utias4,2550 +tensorflow/include/tsl/util/onednn_threadpool.h,sha256=6KuQXtfNuDU862dYsI-y9zIBUMf3au9H_8ZpZvcx9EM,6508 +tensorflow/include/tsl/util/proto/proto_utils.h,sha256=A2FPl_QYDTmKdMLVabohcQ2S8p1xrULhREV3gkeclJU,1563 +tensorflow/include/tsl/util/stat_summarizer_options.h,sha256=ZSUU9fkc0bR8SX624XU2lnQJ_Tq5AX0pcSUoh2o2_H4,1424 +tensorflow/include/tsl/util/stats_calculator.h,sha256=QMZw7JUSXzwHnmboVU-CRxx_LI06SYn_aqXurNZELwc,5975 +tensorflow/include/tsl/util/use_cudnn.h,sha256=1XiQHCMrNepJ5MxKNKa92XcGsn_eFM8xP7XOqnIeFmw,1604 +tensorflow/include/unsupported/Eigen/AdolcForward,sha256=t9UZ7hOOFWRvCOE_Wc7wK5OKicqR2pA8uBYutlkhfa8,4449 +tensorflow/include/unsupported/Eigen/AlignedVector3,sha256=NX6wMTbWflaBUDMWJtiNtml9j8via7z9vsdWqAoDnFY,6375 +tensorflow/include/unsupported/Eigen/ArpackSupport,sha256=HrZsPu68DQdD8o5vNosB7lVMxz659n7dfLVWsyNUNdE,943 +tensorflow/include/unsupported/Eigen/AutoDiff,sha256=K_JhrK1h-gQqa2MX7Sab6vM_SI5x5uZ8DB0gwkugEXs,1273 +tensorflow/include/unsupported/Eigen/BVH,sha256=_91sCcp3pq2huj-oHIOIbv9KLDcYT3HvXd14s99W_gw,5581 +tensorflow/include/unsupported/Eigen/CXX11/Tensor,sha256=PuESFfBzRNxQECodVfdCqVZIZAKZktXX256vBAA2EVc,4334 +tensorflow/include/unsupported/Eigen/CXX11/TensorSymmetry,sha256=Erm-_S-il_KpnkPGLV99Mw4C7K5zdEDkWhW4RfxyBIY,1244 +tensorflow/include/unsupported/Eigen/CXX11/ThreadPool,sha256=disLOs1-yA6POdrBowniFZvfP-MFRc2ql3Ijf1aTya4,36 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/InternalHeaderCheck.h,sha256=Jb-NThqx87Zb-HK51HTtHg2bL1pjWOXQWedRK5o9Hcs,162 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/Tensor.h,sha256=bo1YU6R3ABeKt5sMEYEr9vURe5axryq2-mo7eL4iy9U,18405 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorArgMax.h,sha256=K0ob2UnKORhvo_bwdVXXbGb3xBVlfUhNwpcBLKaqA2k,12142 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorAssign.h,sha256=hmqJjc3Mzwv7_OAUspctPBLxPM1zIC_BDn3tYd1wFKU,10078 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorBase.h,sha256=TRdvwDqkS1FTJ8p4JLbE7ElWjSK1w0Qw0AbiEibDKgQ,59977 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorBlock.h,sha256=cuCxtLzv0TviHasDM2sTeB-psluSplssu7xrlzCeqBk,62729 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorBroadcasting.h,sha256=2FId4d3wI5IUAKRzUnngUt9D0vLGjRGVofGVjwUbdXo,41758 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorChipping.h,sha256=Hn_H_sXSLzgf2Kg_TwMLrXWVPbiyiC5A4wBVHwSk3QA,19261 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorConcatenation.h,sha256=ONDctvv0sPWrCd9YZaTUOHi3bz9ydFBdFHfY_OU_gow,15444 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorContraction.h,sha256=JFmd0q2e8KLk5N2abVYjx_cJYOlqkZoBtTmy9jDFTHs,45099 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorContractionBlocking.h,sha256=dAThQYWMiPvbepSSOhPbPqcVoolktQyU2UdrGhUIsHQ,2711 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorContractionCuda.h,sha256=VPqsfc9SMx7FeLLy17XTqUg_BCBz7xOOYaS4_AmrZko,225 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorContractionGpu.h,sha256=kU9wCfBC5l0YQSnH1gNMrKtZC9bnMdbbIyTEcMG_oBY,63322 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorContractionMapper.h,sha256=21Q4T-fI-nH1I_EBWNkmV3v1hCwv9TmhMSSGttw2PoQ,23566 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorContractionSycl.h,sha256=5cFXL2SKZJZa18nIjBv5Jf2TkGtC59usSs0Ol64ekMU,88386 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorContractionThreadPool.h,sha256=yZz0pRNjJpLgNMca7LqsjDmox-JTfkJrjgoAtttiG7U,70664 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorConversion.h,sha256=1muq5oFErqyqVMDqRZSbDvxiVmfIMnTWr8jP06MEb4g,18597 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorConvolution.h,sha256=4AOzJlQy2veKQA0X0Cilr4fgwdA4o-S_eeDuFUnkSME,48765 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorConvolutionSycl.h,sha256=IYIxcT76GfkmzuxTqpsrHpXccpHVw56hkFyKukB9Msk,27348 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorCostModel.h,sha256=nrWQnwjtiQpM8UI6gs8DQTNTXw7QVj_3jplyjlDzb3g,8678 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorCustomOp.h,sha256=Qe3bQl6KxnaRHtxeb8adyuRz_6mH-MS768sn4BQLGXo,12698 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorDevice.h,sha256=La6u2m7RLZRz2a6xNFL-9M_bJvTYbgNerXU3f53ydvo,4932 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorDeviceCuda.h,sha256=WXZ7t5TCv8_pEyJC-OvtrpwhekmmPFivC8g0wDK5q4Y,215 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorDeviceDefault.h,sha256=m6txcX5XumzkpWcCLUogHdRc4hdWrJVIN-xzLwpY8oI,3931 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorDeviceGpu.h,sha256=mhAaWrHY2aAtggY3rK0Gh9hd9w9wCBBeBuqijKWsWrE,14662 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorDeviceSycl.h,sha256=6C2NTuQ8d7E9UGA2qnAZ26uL0Nxj3vGZVg10eZpqG94,26228 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorDeviceThreadPool.h,sha256=d1kdVqjOho8Ik2Cc8sx0OMSxs9E4OWkChhYgt6NUIx0,15564 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorDimensionList.h,sha256=8b1JzfGqFp4Sw1Ogg69_UPk_5XCuWgC0dEQd96rXQHk,4580 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorDimensions.h,sha256=YUHdv2O5iRmBiYGPTpz7J0ABMGrE5zqEDEhjRumkN5A,16338 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorEvalTo.h,sha256=WaKOtutREKQ676RD7mZnBp96daonqoIn3-Hm9WCKt20,8343 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorEvaluator.h,sha256=BAI0T1usa68m7zWFWvNLON9XfEO5G6bRClmlx6gAPeQ,40208 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorExecutor.h,sha256=14e-8Lq1Iani764Xgx9YfdgFgeZire7Wvnptu3kyyv0,28878 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorExpr.h,sha256=y4Pkb0pdDk0n5PeEoqoTVIvID3CdgYXvfX9UkrjwA0Y,16020 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorFFT.h,sha256=H61s6h2BBAY9yhwG3M5kKEtJ46eR4RdqTLTtXPH5gDE,24141 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorFixedSize.h,sha256=Ts-l4-RoR7wFT7w_2KqKtutHnusM6gVcbn-rEM9MweY,10454 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorForcedEval.h,sha256=yLRCIghLewscznh2_2xzNWpkS4sHZ7MKYcRgRF0Adn8,8492 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorForwardDeclarations.h,sha256=e_cnqkAW8qc1nWI78yQ5w4cAUMS00DSzV0hTUNTjQ8I,7776 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorFunctors.h,sha256=ueGc_8oQ5b4HieYbuwx4YO4QHA8FA6v87VCHpmEnATQ,15221 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorGenerator.h,sha256=nj34Q0fN_4_U2ExX61HkutPdDJKG3C4rRr0mHWFXGaE,10683 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorGlobalFunctions.h,sha256=T9M6nTDJ-PGPXP6Iy_06KFn9WiTXpPtS9CKwudOzLgU,1352 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorGpuHipCudaDefines.h,sha256=YakHRNaeknIfRCVYU43eNylY58pCHuQSCLndB_O4Chk,4159 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorGpuHipCudaUndefines.h,sha256=RebU93yGg-gywcGSjVNJxb6AH6lOv330PDvvDiKh69k,1291 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorIO.h,sha256=izL7YYwEj4M5EsQMnAMLDWdlviHe6Bs37GPMNgseGEM,13306 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorImagePatch.h,sha256=ngaq64cM_up8ENh5EsgytRnDfVljn-4GqPW8fJ72ZKg,27771 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorIndexList.h,sha256=Ihqayx6VZ774njX6FPrFXkUNUkvAX84tn1W1m-79ldM,24175 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorInflation.h,sha256=rqlYVv9JhxcmjzKQW_jTcFkPSQ-v_lAyhR1d_3WI5Sc,8917 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorInitializer.h,sha256=_5TTgOHFY8bkbpKKQ-NgnOXLkVXwp0upoRVUIJG7fYY,2691 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorIntDiv.h,sha256=_s84ejMv-bzHbEYVeqHFHSfVc29fqNhuW8a8MJ_2z6c,9014 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorLayoutSwap.h,sha256=NJ2gLXn2KaLp7Gv9QgdQBJnSjIXPHQSI3HlyZugaGlo,7583 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorMacros.h,sha256=pTuTRMGNI5sEPVgVLaMYF_lj7Dhy7WlJVD0b9eRKKA8,3313 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorMap.h,sha256=25iv3v0WDMW5G7PgINx0OES8J5AKQmYasO0bVqVZIjA,9037 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorMeta.h,sha256=P1MzexboL25tjEPT1R4dE0qnAtU7EGGd13IPHvt5aeA,8371 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorMorphing.h,sha256=SqNTaNzE4ZFQ33CkHuZOnWROnXosbvEY4uj0xG6gQww,42601 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorPadding.h,sha256=uJcGTWJ6AcZK6FkqSuld2MWUDagpuG974BztP2zFOKo,28029 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorPatch.h,sha256=pP_16mW7hrFhFDQAlUs2Ogr0grQ0gtkNCtqaFm39TJc,11239 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorRandom.h,sha256=7IYaaTu0Htr00ffdj9xM3Xp09fj6r84adgGFw8Hdb2U,12410 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorReduction.h,sha256=3Z_Z0Bx6PESj5FEuwGzXHQN4lyFlezrwHmYN-bmU7c4,46666 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorReductionGpu.h,sha256=eYvyKBz6htme5QlWX9dhfoTgvh_pQF_HDqnoNMDVZtY,41075 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorReductionSycl.h,sha256=LIouDIiViK-SvdlzKt4mheFNrb5sKDC4nKT8cD6Fd1E,30093 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorRef.h,sha256=N7pqhx0bkltwqjCc4GpMuxRPK0K3Ks9t_6jm_fGlX2k,12761 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorReverse.h,sha256=bN7tOW5HZ_j-oD60nY2GUXOoHOn6O00SEjpoUEbWEDY,16641 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorScan.h,sha256=t3NaY3pvJMC4yQR8EcXBp9oItLYcK_-UVTkdUKtaiVM,19907 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorScanSycl.h,sha256=kabf7Q5mb4pbT4tkeTy4rk2xbK4z712BuCQQrSnDTNY,24935 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorShuffling.h,sha256=ANkp7UcBBEEFdz9GBOoXLG5lHh72-Yq8A8P3NtwyOAM,17877 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorStorage.h,sha256=gdCnpPxt9tgyUf0e0MNfAKtpr8a4opCba0bdN6WhUuA,5353 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorStriding.h,sha256=4aFEESv1-WZ6GFwg153T62dfy7KvHK46MNbQaCfiHT0,13376 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorTrace.h,sha256=dl5lHyRvwNgtYJSy4QPZyPM_b5_wMvxmgpC4pzaMvX4,9964 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorTraits.h,sha256=iUtJR7ux659SkeHBJllvOONf8ThFyj5EPl1Tq-5fpIQ,9492 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorUInt128.h,sha256=lOlR9cX6-goEZkiXGEcFCUgsSMsZvru76NE4mwCIMhE,7582 +tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorVolumePatch.h,sha256=uhQ6YXbMU9oJDYXCNLlBnbbCfHpmG3wtpZYPbxzdmbM,29807 +tensorflow/include/unsupported/Eigen/CXX11/src/TensorSymmetry/DynamicSymmetry.h,sha256=BqHd9nIYhiuCgrDrCa2HlrJfROLDHQqO3a_ZL84vwO4,10893 +tensorflow/include/unsupported/Eigen/CXX11/src/TensorSymmetry/InternalHeaderCheck.h,sha256=QmhbpVZlcL6bX3KaTFPGhSbGLHIggEvv7_P1NCPFXPA,178 +tensorflow/include/unsupported/Eigen/CXX11/src/TensorSymmetry/StaticSymmetry.h,sha256=hGXr1QWdgCLpDHAOgn5pivAb1S4zv4Z2PUZqTqVPYYc,9122 +tensorflow/include/unsupported/Eigen/CXX11/src/TensorSymmetry/Symmetry.h,sha256=cR9yXhtVAQbIEyLZHHU8BY807VW8LA8MqDxJ-jELPzo,13049 +tensorflow/include/unsupported/Eigen/CXX11/src/TensorSymmetry/util/TemplateGroupTheory.h,sha256=CKV_yrodz4tWIZcnCSzfMfLquJJ7p08p_j_jlrRPIJo,21075 +tensorflow/include/unsupported/Eigen/CXX11/src/util/CXX11Meta.h,sha256=8lylk4ZPjsL1kl8Wj49f5cwb7aDx6b6P2AdCyk0JSdM,549 +tensorflow/include/unsupported/Eigen/CXX11/src/util/CXX11Workarounds.h,sha256=AUihv2otJdONkcee0V7IQKuM0UcMiP_etO2bOJ2VEvU,3493 +tensorflow/include/unsupported/Eigen/EulerAngles,sha256=8U1JqboARimG_f-ZSJWGdUlFJI-WwFsn6oBpoPRu5X4,1184 +tensorflow/include/unsupported/Eigen/FFT,sha256=gJb6fKYAeTOb56J88RbbR20bFD1QX4cQNtn406u6_1g,15477 +tensorflow/include/unsupported/Eigen/IterativeSolvers,sha256=yX1nCO24TGnCDX8rYoY0v6fOYSJuwJADG0_UVOfsdgo,2936 +tensorflow/include/unsupported/Eigen/KroneckerProduct,sha256=fRuBg1FoXAxgnJuED0gcecT2f5LHvXcm6uWVThK0zYk,922 +tensorflow/include/unsupported/Eigen/LevenbergMarquardt,sha256=pPBhtSpDNh56Si4PcOgwyZgZV3CFGofenCLvrrsyiVs,1300 +tensorflow/include/unsupported/Eigen/MPRealSupport,sha256=2H7NflX8oKXdd3bq0f-lksnPztIcrKL42iWsBrmxL-A,7656 +tensorflow/include/unsupported/Eigen/MatrixFunctions,sha256=cYrNeKJxPbM-WgJbYsS_PI56bkdzWzA4pEKI9_iPKs0,18003 +tensorflow/include/unsupported/Eigen/MoreVectorization,sha256=H5RwOuLAdRHWmhwtAOWMmVFOwurbDEN9I2MbO6LXmcY,650 +tensorflow/include/unsupported/Eigen/NNLS,sha256=SiIHhGgh_NuLEFcgvxE11cEjsVWNnioA-4YUGSFIkRQ,15174 +tensorflow/include/unsupported/Eigen/NonLinearOptimization,sha256=fcO7Uea-RDbhc_GKbo5cOfU0k53ttWE227E0zQ4gGZw,6026 +tensorflow/include/unsupported/Eigen/NumericalDiff,sha256=FDAxf0GgZOgp2XSZJIxlooiFXI_U-Urc2hiH-URU5as,1843 +tensorflow/include/unsupported/Eigen/OpenGLSupport,sha256=0GLhj7mFJDAkdJlapp--VBU8G6H1uhS3A-POv6VMXdY,19078 +tensorflow/include/unsupported/Eigen/Polynomials,sha256=FgMftptZAztiPd1CHnoejefqZIwa_oTSzaNY_7OvAWM,4807 +tensorflow/include/unsupported/Eigen/Skyline,sha256=903Jxc-uPclc1DigKjVJ_J6wLodjNPGo9etSOU2T1tc,988 +tensorflow/include/unsupported/Eigen/SparseExtra,sha256=IMuTnF37JWbZQsY6_h-oBOYM-8_MfJKXPCwcozbbhno,1752 +tensorflow/include/unsupported/Eigen/SpecialFunctions,sha256=0aORcEkLfFdYlrl-IBaSFsr_yjvNjH3Sr_0c5Vp9PgE,3015 +tensorflow/include/unsupported/Eigen/Splines,sha256=ZCsBCzdJCKzbVb9eXpyeTNj9iO3PsZCV60pV3g0U4-E,1054 +tensorflow/include/unsupported/Eigen/src/AutoDiff/AutoDiffJacobian.h,sha256=wGHviQFlNcBiMAWtUFOSp5VzjPk8MTg_XC07KwjfJZU,2539 +tensorflow/include/unsupported/Eigen/src/AutoDiff/AutoDiffScalar.h,sha256=8M4KvB76mxr1-l0RFYmS7numFGBuKQoUzjuxwA6219o,29161 +tensorflow/include/unsupported/Eigen/src/AutoDiff/AutoDiffVector.h,sha256=MzfmdvPDN7dJV55gqp2z1HeONBUWDdue1kKt5SMyIuo,9065 +tensorflow/include/unsupported/Eigen/src/AutoDiff/InternalHeaderCheck.h,sha256=SiAuFFafKiK4cVCwzqAe7lH3pKkXA_7k3QAkI4L_290,154 +tensorflow/include/unsupported/Eigen/src/BVH/BVAlgorithms.h,sha256=E98kvZDgHP_r9rxxgmPFi9cZFCGJLBktxxh2WQySkmk,13012 +tensorflow/include/unsupported/Eigen/src/BVH/InternalHeaderCheck.h,sha256=BjfSZ2vFUqKpDLiAtfL81QodeAfcyrcyLJavde4pcjs,144 +tensorflow/include/unsupported/Eigen/src/BVH/KdBVH.h,sha256=cY__JYaMg8C9F2H4osZs4FBTd9tjpmxdKXGCrJFhr9E,9202 +tensorflow/include/unsupported/Eigen/src/Eigenvalues/ArpackSelfAdjointEigenSolver.h,sha256=_rO7JsDeQjp8dzyJK1vVXAjxWmeuDqa_iGasnigt7jA,29111 +tensorflow/include/unsupported/Eigen/src/Eigenvalues/InternalHeaderCheck.h,sha256=U0Wgrb9PXrI3jCDfQ2bLgD_GtIwmHCEF-Qs-kc9BeiA,160 +tensorflow/include/unsupported/Eigen/src/EulerAngles/EulerAngles.h,sha256=CsqyZDO9ygZdddOsKA66IQZa-3nOJMvC54rx9Rs8JLQ,15403 +tensorflow/include/unsupported/Eigen/src/EulerAngles/EulerSystem.h,sha256=6rcrfUR6oz0fjpwkDj42O0025B08ZEyjcU1eorYTtoA,11650 +tensorflow/include/unsupported/Eigen/src/EulerAngles/InternalHeaderCheck.h,sha256=UfzVVY3FZR5S1I04vVAR8fkPaIVwnM0soiGWfKgMh4w,160 +tensorflow/include/unsupported/Eigen/src/FFT/InternalHeaderCheck.h,sha256=aE0o63ofJ15paiWWEUVrV2emAeHnuj1jkMFI9OHVcQo,144 +tensorflow/include/unsupported/Eigen/src/FFT/ei_fftw_impl.h,sha256=6ef9YxM37pPz3UdEYxh1RK-D2B9vZHghMEy5mc4DNtg,9484 +tensorflow/include/unsupported/Eigen/src/FFT/ei_imklfft_impl.h,sha256=2cS9uF1l6gijFii3ejP_82v6hMF3qqPERFuAwgJWBes,9626 +tensorflow/include/unsupported/Eigen/src/FFT/ei_kissfft_impl.h,sha256=10g86yMlzObdScXsL7XgDsDQcH2WPt-m0YAU-jJRdsc,13267 +tensorflow/include/unsupported/Eigen/src/FFT/ei_pocketfft_impl.h,sha256=iu7PJeGMqiFH49lDnRo_-W4bLe7CjKVj5JWy65sOgwk,2661 +tensorflow/include/unsupported/Eigen/src/IterativeSolvers/BiCGSTABL.h,sha256=__lxI_o0bciySq2HpsXCJ8kwfvyP6mMuObcM6PTeEN4,11422 +tensorflow/include/unsupported/Eigen/src/IterativeSolvers/DGMRES.h,sha256=eUDSUgeOVbpovdwZEYIxbCKlYnIsW3xfPl2iaDK7HDU,17786 +tensorflow/include/unsupported/Eigen/src/IterativeSolvers/GMRES.h,sha256=xcx4U9ylxrpv_593-fpUmDNo-QJpzqO2uFEV21bATts,10245 +tensorflow/include/unsupported/Eigen/src/IterativeSolvers/IDRS.h,sha256=DJS2zOK3byFaYUgYjy-xqnzBWb3vGBk-dDserAzBXD8,14602 +tensorflow/include/unsupported/Eigen/src/IterativeSolvers/IDRSTABL.h,sha256=TYjZdvoAIKfH1-45hYDGbtGLhbKoao8pvizaYTRqrd8,16866 +tensorflow/include/unsupported/Eigen/src/IterativeSolvers/IncompleteLU.h,sha256=RKos2k-MKisvknzyPKALdB0mV2CZCB29iqvNqeneTkM,2556 +tensorflow/include/unsupported/Eigen/src/IterativeSolvers/InternalHeaderCheck.h,sha256=GKVJO7xaXfKzJTgZE-FBKG4HDqWojL7d__2-v0l-jww,171 +tensorflow/include/unsupported/Eigen/src/IterativeSolvers/MINRES.h,sha256=PCUOfwV4h_Dpug89GYoACu1vR8J3sw_7QpEiFjPdXxs,12410 +tensorflow/include/unsupported/Eigen/src/IterativeSolvers/Scaling.h,sha256=4o2lNVhEz2kuHb16kw5CZXAt3OvnRxwx3kiorPE5CA4,5888 +tensorflow/include/unsupported/Eigen/src/KroneckerProduct/InternalHeaderCheck.h,sha256=dX53OCwVkO0N6hb_4tQMFFVthjC7_ag_5VMijTlPFvs,171 +tensorflow/include/unsupported/Eigen/src/KroneckerProduct/KroneckerTensorProduct.h,sha256=remuirCkHItSwy5Ycnbgv-xNuMaMVkgfskBB78PLcis,10168 +tensorflow/include/unsupported/Eigen/src/LevenbergMarquardt/InternalHeaderCheck.h,sha256=WtpKVvcvunl4jQk9tivKGXTGcZNjUAAiA1CwgZSEe2s,174 +tensorflow/include/unsupported/Eigen/src/LevenbergMarquardt/LMcovar.h,sha256=UoZ7JDeWdn6kJZ2TSZ7NPZKpdNAaRqP8emNZCQx39QE,2479 +tensorflow/include/unsupported/Eigen/src/LevenbergMarquardt/LMonestep.h,sha256=xh_s0YyXxXB84h7Ar4JQ3ovnCJYKOFeQWnveiZLLoAk,6684 +tensorflow/include/unsupported/Eigen/src/LevenbergMarquardt/LMpar.h,sha256=Q_SBrYjv93DDLa9uJMUI15Ncma7i3YQH2pPtDHmPzMg,5075 +tensorflow/include/unsupported/Eigen/src/LevenbergMarquardt/LMqrsolv.h,sha256=YmiVkF-6JqxstTsqUTFn3Pj3t027zUjJSh5IUnz5t-s,6841 +tensorflow/include/unsupported/Eigen/src/LevenbergMarquardt/LevenbergMarquardt.h,sha256=XhqXaZuvv_g846hoQ7klBKXGOFi4saiVzKgY-nFFNeA,13333 +tensorflow/include/unsupported/Eigen/src/MatrixFunctions/InternalHeaderCheck.h,sha256=vg6WO0fMZP1JrXyegJeF8R0uhOCZYAoKuylzi9Hgfms,169 +tensorflow/include/unsupported/Eigen/src/MatrixFunctions/MatrixExponential.h,sha256=L9kcejALCAk-6r5ToLGVydhSTmPruu6Usgya2JUrQI4,16660 +tensorflow/include/unsupported/Eigen/src/MatrixFunctions/MatrixFunction.h,sha256=LXV4lT0mugJWpnlKrKikVH4mcowsYuLvmRUuJj4g73w,22694 +tensorflow/include/unsupported/Eigen/src/MatrixFunctions/MatrixLogarithm.h,sha256=9OqjhEyyA8yk2NlK3AM3RuAIn4SBF_fauQelVW-I57o,17586 +tensorflow/include/unsupported/Eigen/src/MatrixFunctions/MatrixPower.h,sha256=t6QiO1hEYBnD54a7pxlAIWoZcBF2q-bq0JMQZ_n-I-Q,23484 +tensorflow/include/unsupported/Eigen/src/MatrixFunctions/MatrixSquareRoot.h,sha256=EfBMeZDTGvme_VUft8pfBaYrzq6Wc03ZQAPHF_NcH2o,14235 +tensorflow/include/unsupported/Eigen/src/MatrixFunctions/StemFunction.h,sha256=qdD2CtzXjvkK85TmvN9phPhWZvxnBH6PEuaS1bvJ5Og,2143 +tensorflow/include/unsupported/Eigen/src/MoreVectorization/InternalHeaderCheck.h,sha256=8n7JdWCxT07cUeMjDuqrHn-8uGLBNMy0h26RiEpXWgg,172 +tensorflow/include/unsupported/Eigen/src/MoreVectorization/MathFunctions.h,sha256=6E_zfTHj20T5mOmAR89odECzC07G0soyY6SUotToLo8,3060 +tensorflow/include/unsupported/Eigen/src/NonLinearOptimization/HybridNonLinearSolver.h,sha256=dOVA8vYn5-kFTm3DMqhgcRlltpL5phXsexXT6fohKw4,19879 +tensorflow/include/unsupported/Eigen/src/NonLinearOptimization/InternalHeaderCheck.h,sha256=XYidaRsnleyIPzF9EniEQqq_-WI0a0J7MoMItsbchV4,180 +tensorflow/include/unsupported/Eigen/src/NonLinearOptimization/LevenbergMarquardt.h,sha256=jg3yBdnERoOdHPjmdxW8mtbzK4slsnwSn3lYsVCiz1Q,22171 +tensorflow/include/unsupported/Eigen/src/NonLinearOptimization/chkder.h,sha256=Qucnw21IQpngluOy0s4rwiQFLQIc1Nc3IIQx0YFl3y0,1900 +tensorflow/include/unsupported/Eigen/src/NonLinearOptimization/covar.h,sha256=XJCMEIm8fCq2gMJ70Ram-bq_tLD_ALGoUkErDEpt4jY,1951 +tensorflow/include/unsupported/Eigen/src/NonLinearOptimization/dogleg.h,sha256=EylM7riHVGExquX0IJsyhJ2JaAg1K2WW4m7RLLWpxyw,3333 +tensorflow/include/unsupported/Eigen/src/NonLinearOptimization/fdjac1.h,sha256=7LHNwtK19VYrQsOI2UVHYHQnK8jlTmyVnIT8gkmlqHs,2261 +tensorflow/include/unsupported/Eigen/src/NonLinearOptimization/lmpar.h,sha256=1GUgXM9t3FYzLDQnXlbmHEM0VOVRuI245nGm9dQygaM,9147 +tensorflow/include/unsupported/Eigen/src/NonLinearOptimization/qrsolv.h,sha256=FOdO-YZYeyhi6V2NN1EhV6J5apNYo3nt6RHs9u2YE_A,3300 +tensorflow/include/unsupported/Eigen/src/NonLinearOptimization/r1mpyq.h,sha256=Ds9QfaoquU6R4E26RrBygw-FnKharG8SZ6pj2eoNAvs,1117 +tensorflow/include/unsupported/Eigen/src/NonLinearOptimization/r1updt.h,sha256=9I5WC6mOa9HDMY8Cj1e1CMzTdNXyRWjinY1pUYw8dwk,3119 +tensorflow/include/unsupported/Eigen/src/NonLinearOptimization/rwupdt.h,sha256=SsgBTPoFY3Xmo40JKqNHTucBpTTzxhm1KIANYTD1B0k,1398 +tensorflow/include/unsupported/Eigen/src/NumericalDiff/InternalHeaderCheck.h,sha256=CLqrPzPEfoEVo8b1RkEdtSRdc-fafyqyvByngfBB8v0,164 +tensorflow/include/unsupported/Eigen/src/NumericalDiff/NumericalDiff.h,sha256=GXEcAhfoCAiRyNDix6g2Ut0tDMUZWnzexEVgLWlrAYE,4056 +tensorflow/include/unsupported/Eigen/src/Polynomials/Companion.h,sha256=81BB2zNX0DAnKogsxvVFtlSxNmmaS2R_lNs7qNX7vo4,8112 +tensorflow/include/unsupported/Eigen/src/Polynomials/InternalHeaderCheck.h,sha256=vE0sHySZbiFBbt_aKVAAe8y4jLAieYu99fIPwjzVvSQ,160 +tensorflow/include/unsupported/Eigen/src/Polynomials/PolynomialSolver.h,sha256=IzJZ2WGxQohEANQCpUlsl0Bzo-8Q7Vbd4ZNQijY526Q,15671 +tensorflow/include/unsupported/Eigen/src/Polynomials/PolynomialUtils.h,sha256=aWiH4saGUXGL75UTOSGvxHyQxWDVuh3TyqmJneIvKxs,4842 +tensorflow/include/unsupported/Eigen/src/Skyline/InternalHeaderCheck.h,sha256=8QNGRLRhFpRvIYFQOMMttZjJ6d3ZXdnP9lnf_PXz2aI,152 +tensorflow/include/unsupported/Eigen/src/Skyline/SkylineInplaceLU.h,sha256=W094df5k33eit5xXdEcm9QbxTZASowkjkTqTZVSoawI,11401 +tensorflow/include/unsupported/Eigen/src/Skyline/SkylineMatrix.h,sha256=LwAcqmBytWnkRz1ukax7FreVs19BNIaKmphVAdabU8Q,31085 +tensorflow/include/unsupported/Eigen/src/Skyline/SkylineMatrixBase.h,sha256=MxXB4BbFCAiElej6kH9fwwcsDkAF7eLNxL_uXFc07Bs,7822 +tensorflow/include/unsupported/Eigen/src/Skyline/SkylineProduct.h,sha256=2isZjaUvu63rWEqCKmmYDYmYbCai6QXl2iBx2KuuW80,10732 +tensorflow/include/unsupported/Eigen/src/Skyline/SkylineStorage.h,sha256=nh99VwVMoHmDM-ChSl3P6rS2cYqdiRmUb7opVAk3ohE,7977 +tensorflow/include/unsupported/Eigen/src/Skyline/SkylineUtil.h,sha256=mUXdhA_8Hwf-AxTaWhStcO408gS_rLZGh50fUjgakow,3189 +tensorflow/include/unsupported/Eigen/src/SparseExtra/BlockSparseMatrix.h,sha256=c-4PM37NhA0IZcvQsLhTTnG1BkvQuf6EiN4CaUfOE7U,40316 +tensorflow/include/unsupported/Eigen/src/SparseExtra/InternalHeaderCheck.h,sha256=7bGqUoUEjrClk41Cs2dfgXQH1vLStYfs-anNmEr33aY,161 +tensorflow/include/unsupported/Eigen/src/SparseExtra/MarketIO.h,sha256=p6vDi1qG5gFJrSP3laQeo_um61ZfGVA7Pw-o1tlSilQ,11964 +tensorflow/include/unsupported/Eigen/src/SparseExtra/MatrixMarketIterator.h,sha256=4zii6o_e7WsF4gA3cJxZTthvzbrST7mFdFHXIFcsJ5s,7604 +tensorflow/include/unsupported/Eigen/src/SparseExtra/RandomSetter.h,sha256=CdpYmWlkgVLiks1KBJtqBrQzkeAWkSF7Dk9u7s-80HE,11900 +tensorflow/include/unsupported/Eigen/src/SparseExtra/SparseInverse.h,sha256=vP4sI-fmi9OQxkUSARoquC-qq-tN0eD-rYHdvpEGAQE,8653 +tensorflow/include/unsupported/Eigen/src/SpecialFunctions/BesselFunctionsArrayAPI.h,sha256=w6j0pA9BKLEuGAIrLD_67ojdJMumjHcORuf2R_jSz9c,10051 +tensorflow/include/unsupported/Eigen/src/SpecialFunctions/BesselFunctionsBFloat16.h,sha256=AQNBZVIr5mZAVrWAIotfji_6qFnsp5gvnEfl518yBh4,2760 +tensorflow/include/unsupported/Eigen/src/SpecialFunctions/BesselFunctionsFunctors.h,sha256=fp8EYuVRtnRnKL7J_fUAbH7lkf_SVAr9tq3tII16-sA,12109 +tensorflow/include/unsupported/Eigen/src/SpecialFunctions/BesselFunctionsHalf.h,sha256=XBlPMl79RrSx8LCHy2zQy1a1VKZmmnP4KzzMD2FbCuA,2580 +tensorflow/include/unsupported/Eigen/src/SpecialFunctions/BesselFunctionsImpl.h,sha256=gfcvNhRZ2EcmW8cWVivOiApNosh-xu0YdFdRegeZHuo,69608 +tensorflow/include/unsupported/Eigen/src/SpecialFunctions/BesselFunctionsPacketMath.h,sha256=x3cOGrdwyDQK-iqfd7zp9TngzNm6IPgI3kzKD6yhBVY,4042 +tensorflow/include/unsupported/Eigen/src/SpecialFunctions/HipVectorCompatibility.h,sha256=lThqH1V55NuIwJzm9JApLQkZjEhZcWTyHmiRUyn7daA,2525 +tensorflow/include/unsupported/Eigen/src/SpecialFunctions/InternalHeaderCheck.h,sha256=6BfgcDcDGjAi1gtNjBeuak1HEIlieOv_9-tQfFp0Btc,170 +tensorflow/include/unsupported/Eigen/src/SpecialFunctions/SpecialFunctionsArrayAPI.h,sha256=aEF9vLmk9nKSDq2L3W3YhaCKcD58fKytFXHDJi18LDs,7730 +tensorflow/include/unsupported/Eigen/src/SpecialFunctions/SpecialFunctionsBFloat16.h,sha256=JM4WJs0xY-mz_jXFhs1ObWoLqLqNhdnCfIDkxR_ao3o,3123 +tensorflow/include/unsupported/Eigen/src/SpecialFunctions/SpecialFunctionsFunctors.h,sha256=OYTEd9C3RUWBMbDqJkm_Jhy7TCBvfTmYsL9S0fQwTRI,11184 +tensorflow/include/unsupported/Eigen/src/SpecialFunctions/SpecialFunctionsHalf.h,sha256=7Ake7HZKNLk1P7Yle0DDSpj-WGXTZ14wyk6anCuKw7k,2935 +tensorflow/include/unsupported/Eigen/src/SpecialFunctions/SpecialFunctionsImpl.h,sha256=Sweae1htL02amyuubP25mdcgqiq5kAa-u0g1YZmUVTo,58930 +tensorflow/include/unsupported/Eigen/src/SpecialFunctions/SpecialFunctionsPacketMath.h,sha256=BJH7nQ8IUghyeQ7zuXDbe3ZDHziIYBM6nqL0SKdy5as,3749 +tensorflow/include/unsupported/Eigen/src/SpecialFunctions/arch/AVX/BesselFunctions.h,sha256=c8n4ryTNSc3GaLoLt7kSDzMpZpq3RE5dXyqHIGa4YhA,1492 +tensorflow/include/unsupported/Eigen/src/SpecialFunctions/arch/AVX/SpecialFunctions.h,sha256=VihlVEXAV31rLXjBdWBFcFNVMo6dFjMJaGIJZ1DwXt8,398 +tensorflow/include/unsupported/Eigen/src/SpecialFunctions/arch/AVX512/BesselFunctions.h,sha256=YkBb2bDAmHgfDP-Fbok-Z0_8YnQX2YZFu-oPYMMvuwo,1549 +tensorflow/include/unsupported/Eigen/src/SpecialFunctions/arch/AVX512/SpecialFunctions.h,sha256=AlI_TVRNWqXdobwYewoBiKYw5M9Ivm0leDXN9dv22bw,415 +tensorflow/include/unsupported/Eigen/src/SpecialFunctions/arch/GPU/SpecialFunctions.h,sha256=8qB-xEPrv2Rrk96jP61XHo7RVby0mtFB5t0kSoofJJo,10864 +tensorflow/include/unsupported/Eigen/src/SpecialFunctions/arch/NEON/BesselFunctions.h,sha256=6HWKDWP2TlnaAJ7w2f5WLUc2CsrYeXeWWuNzuJBlGCw,2258 +tensorflow/include/unsupported/Eigen/src/SpecialFunctions/arch/NEON/SpecialFunctions.h,sha256=G2EXLzIKd6E_XKOcplAvPBBFGKlco-CcjErDtU3STgM,1283 +tensorflow/include/unsupported/Eigen/src/Splines/InternalHeaderCheck.h,sha256=g6F2b62lbybXJGxoirOOZewQYt9uMq6cHeenp_l-tHU,152 +tensorflow/include/unsupported/Eigen/src/Splines/Spline.h,sha256=eIStTFRuJBvWbLYu-Hu7QgPmUe6bDd3fVwznspgjmuc,18342 +tensorflow/include/unsupported/Eigen/src/Splines/SplineFitting.h,sha256=NqZ7zdZa6_M7YueTzR01jEl6Sc10pVKF7m2wOTpM3RU,16542 +tensorflow/include/unsupported/Eigen/src/Splines/SplineFwd.h,sha256=_DbytthN2vyU61ZUXzL_17ocNzYev9E7spepb7pg_fk,4347 +tensorflow/include/xla/array.h,sha256=qcHnA5xl1YAaUAjzwspX9LVyPGXXmqn3yfEATpaV628,25361 +tensorflow/include/xla/array2d.h,sha256=dzqY4TmWVSggrokEVzZt5AA4XUgNZO3yk_5HhTE-YdA,3834 +tensorflow/include/xla/array3d.h,sha256=MnbF6xztyTUSMXqhDIJLIfaezqi-oCpEyraod39v4rw,2543 +tensorflow/include/xla/array4d.h,sha256=NfmOMlg03ATGKlTA5hGuU14B2MvQ0Py1LKFwzQXSi1Y,6330 +tensorflow/include/xla/autotune_results.pb.h,sha256=nDSgBVfocjpdIu2PyV8XFYeykb_lm7xsxBKUsfz6hP4,25139 +tensorflow/include/xla/autotuning.pb.h,sha256=5d9rZu5_GMr5rdVTGXQGQ9_4XZPh3orxEPpnZSwvRBo,142404 +tensorflow/include/xla/backends/profiler/cpu/host_tracer.h,sha256=3HzWIAOS-_NDm4DocacfRsMyxvslnBIJHGFDUIJ6lRw,1634 +tensorflow/include/xla/backends/profiler/cpu/metadata_utils.h,sha256=0jUSVjX1iYGkNfgNn1WqXI0DZt6y5jH9HmxtVpgqpSQ,2045 +tensorflow/include/xla/backends/profiler/gpu/cupti_collector.h,sha256=Bc417SHSHDZ8P5BuFaagp4VNzsr571zZdG_Q36BQ4_0,10385 +tensorflow/include/xla/backends/profiler/gpu/cupti_error_manager.h,sha256=d181DmKlb0qTt9IQrK91jrJ-iaXtPfkeE3jRDjU0dJM,11992 +tensorflow/include/xla/backends/profiler/gpu/cupti_interface.h,sha256=918nt6HCaBrTIzVb76QM-sfccRYCRQrmSpSX4yO3c1U,8876 +tensorflow/include/xla/backends/profiler/gpu/cupti_tracer.h,sha256=e-Ok5g6PbrZPkJjQ6rzP9qBLCjim-b1gnIVwg9Kk-hg,6066 +tensorflow/include/xla/backends/profiler/gpu/cupti_wrapper.h,sha256=uVQThYs6rvFw5sy-g6LQUKiYOoJ6gUPDqS0SxNEOC-4,7631 +tensorflow/include/xla/backends/profiler/gpu/nvtx_utils.h,sha256=8SwRd0tqnR_p_OGqcrsuameKbKSE4DPO1xJ2gdOI-h8,1927 +tensorflow/include/xla/c/c_api_decl.h,sha256=FdUA7v7HuslviFULI3g82Z-kIBpD5OysdxnIh3vSbM4,985 +tensorflow/include/xla/client/client.h,sha256=LNDhbpw0hIOMQcMJ6stB28s18gAhre_md0x_XTffRPM,11134 +tensorflow/include/xla/client/client_library.h,sha256=93_NDoBE0TSi_tnR-SH0ZKYTXfzGr2K7r1tQPxrmW7I,5527 +tensorflow/include/xla/client/compile_only_client.h,sha256=D76FWFkBsOXprlDZEOYCHXVn7qrc7MjmRBGIlg-rWNo,3016 +tensorflow/include/xla/client/executable_build_options.h,sha256=H4XArNJbwSQDSP6BBg9iUSXqLADb-tr0NLOPTK3REQ8,10785 +tensorflow/include/xla/client/global_data.h,sha256=KAwJHZV_M_mPe_quL_AJ0xTHpLDv66-cBVJo3YxoIpI,2055 +tensorflow/include/xla/client/lib/approx_topk.h,sha256=R2R4OG7R4KFyGFlnPG9IOgCu-AQIC1cs2RH03j-4zQI,3528 +tensorflow/include/xla/client/lib/approx_topk_shape.h,sha256=lwWm0WgHjKAVdUiGYc_krlI4baa4u_442rCOA5ibRKs,1957 +tensorflow/include/xla/client/lib/arithmetic.h,sha256=kHoV-FKceJSrc2DZbHXvrfmuSpgRooM9NVslYyO4iT4,3939 +tensorflow/include/xla/client/lib/broadcast.h,sha256=tI0n4F1zXeUAIngV3qlamfo__6qaKzA7FAlE6GaXeik,1183 +tensorflow/include/xla/client/lib/comparators.h,sha256=LhcUgZN5jT9YX2c0fuVo75rmI1mxGgUUPQQhY1k2dhs,2521 +tensorflow/include/xla/client/lib/constants.h,sha256=6qJ8_1VdcFBZlrOj3qx-ONyuZPoIvYFShQECa7XZvBQ,5429 +tensorflow/include/xla/client/lib/conv_grad_size_util.h,sha256=yhw1LoLhvWvoT59gf3_cf4p9otkGNuhW8mVWUnB9JLI,1700 +tensorflow/include/xla/client/lib/dynamic_shaped_ops.h,sha256=cqN5RmW2qWwxvjR-VdDDEnZxUSR6B_ldkw-f0ktrJMg,2476 +tensorflow/include/xla/client/lib/loops.h,sha256=B9-ah_M070OaQ0atLC9FPUNxitArfRaSkMXbk1lXzlk,2777 +tensorflow/include/xla/client/lib/math.h,sha256=zPyQ1uzpvT1KZE7zKxEXhmMChDuWe9m05VlcyNyeWwQ,3825 +tensorflow/include/xla/client/lib/matrix.h,sha256=_Dh0fU2zV0KOHL709efSHCWgmDPW7trpjImvuVvcPb0,6165 +tensorflow/include/xla/client/lib/pooling.h,sha256=6lnF0DjbLK7vP0tDzgSmGhaiFld3v10VVzVNwdbtmsU,3173 +tensorflow/include/xla/client/lib/prng.h,sha256=UbHlkkzWU051a8ZbcP76xs48-75sWQr25TCXTbv2k08,4571 +tensorflow/include/xla/client/lib/qr.h,sha256=ecte5jMg2zY2MfZLjzCnz6mN_yIt8aySb8wm3OkVlN4,2097 +tensorflow/include/xla/client/lib/quantize.h,sha256=gps2DrWmahi6eQ9xAo0Q5xnhE4Ca9iVCWJLOEdsrY88,7178 +tensorflow/include/xla/client/lib/self_adjoint_eig.h,sha256=flqpXRkLSlkHzis3yuRmbDovY-cSJGKo5Pj5e4QCMQE,1517 +tensorflow/include/xla/client/lib/slicing.h,sha256=uvfGqj5rYhOvsPyyYzAu5OJfDaXUNG45lpf4LFYQKNk,3879 +tensorflow/include/xla/client/lib/sorting.h,sha256=wN1prvo0MIxttjcKCGxAKitFyax_rKawp_FyEop9Bqk,1505 +tensorflow/include/xla/client/lib/svd.h,sha256=R4k_4xPCDJKSPS3Oiv8d-JqN1ahaVWwO4-UTI8aWIw8,1882 +tensorflow/include/xla/client/lib/tridiagonal.h,sha256=CE3_24GPKpTiauhVkHfjI8JHqTQzEBEh4fYZN79TNnc,1447 +tensorflow/include/xla/client/lib/tuple.h,sha256=SAp6qZsauNZg2AEy-Ue6LE7wzDkm-ICipTlcLogbsQs,1381 +tensorflow/include/xla/client/local_client.h,sha256=XzwyaS42L6NsESZ_yJRNNqMLh-SAN1feBX3sNxwlDUE,9742 +tensorflow/include/xla/client/padding.h,sha256=LeYaXcLjnVDhqbj8sNbH56LH4jkoV_nIMuHp-SqAfoQ,2601 +tensorflow/include/xla/client/sharding_builder.h,sha256=sYUmOpvSfvBjigVInO3zxG3qogjfy3KDdbLVCpdG96E,2215 +tensorflow/include/xla/client/value_inference.h,sha256=5RxcrNysXQB1x2yT8tuxEwnF-MuOMwabGiUeXv-PgDg,3984 +tensorflow/include/xla/client/xla_builder.h,sha256=mSWsikVqc8w0OI7pZmGG0GOqLbMFW5g_Y0_qAIkYfHo,138285 +tensorflow/include/xla/client/xla_computation.h,sha256=EWW85ZEEj_-G8zXFR8hIRWK2Kiq_D2ah4MaMqeyi1K0,2233 +tensorflow/include/xla/comparison_util.h,sha256=a1zAZ-E5-EdWIBTubRsV94Nt1spU7k5x7T2r1R8erx4,9465 +tensorflow/include/xla/cpu_function_runtime.h,sha256=sUqfDl7NyEq64cGEh0IFac-W3guK1mMPvdcmkZALZ0I,8566 +tensorflow/include/xla/debug_options_flags.h,sha256=XA7q8JHvc8Hk8AG92biTuxwcTTrLnNlQhvKIDh1brw4,4297 +tensorflow/include/xla/debug_options_parsers.h,sha256=dnaq-eZrKGnAv56yMCKrYuP4_5Igo1HRYSIS3iKWWes,1705 +tensorflow/include/xla/error_spec.h,sha256=ksYTCTlTCIOPX-LTjRmd1_2zqIf4pNI5zZsR4Cda5Ao,1977 +tensorflow/include/xla/executable_run_options.h,sha256=_T2xmNz1LmYst5HAMThzwVIGluEZ951A8vw3tINtGfk,9255 +tensorflow/include/xla/execution_options_util.h,sha256=nRHtisxY1F4EW2LxtSjXzB1kaMTt1QT4HN-w6sf9W0U,1032 +tensorflow/include/xla/frontend_attributes.h,sha256=SCJ75WXuZuU7q9jWAoC1J1fb6gSjKuTlVHOdC8JekAE,1502 +tensorflow/include/xla/hlo/evaluator/hlo_evaluator.h,sha256=jN_C0n0IQID7bJszX83-mzujhxCAFp4BEfrvXTzqabc,21650 +tensorflow/include/xla/hlo/evaluator/hlo_evaluator_typed_visitor.h,sha256=tpeQyxDJ2qAb1DzGjj2ydvi3AjPYwF-VqtwWWIKLzVo,68383 +tensorflow/include/xla/hlo/ir/dfs_hlo_visitor.h,sha256=AhSHJA_NCrR8ZY9nZgXHEhjHV1rr7w3VmnYS5SQCa2s,16852 +tensorflow/include/xla/hlo/ir/dfs_hlo_visitor_with_default.h,sha256=icXLsmlPQDPdOqsTB1qB5RS1tn6O1Hh3LUd-EcGPNv0,14261 +tensorflow/include/xla/hlo/ir/dynamic_parameter_binding.h,sha256=Wje8xUrRfr2uvYr05ydr7XMgSMJAPjUi1lAciXPdeLQ,4536 +tensorflow/include/xla/hlo/ir/hlo_casting_utils.h,sha256=yI5jfBAUaWa2y-XW4PPQ-roVA9WAaHcDQfWf5zFVZCo,4047 +tensorflow/include/xla/hlo/ir/hlo_clone_context.h,sha256=5t5TqhW90eCo8gaOjJuhdqqmB51nthr75TcTEycT6NQ,3451 +tensorflow/include/xla/hlo/ir/hlo_computation.h,sha256=E42vBiiBK7QoEVcRGXX_wxgsnCKSy2DjchNvY3iQk6k,42221 +tensorflow/include/xla/hlo/ir/hlo_domain_metadata.h,sha256=23rCeVKERJo8vCpzG2av8b4Ijx6QN5V2cGVu_k567Wo,3111 +tensorflow/include/xla/hlo/ir/hlo_frontend_attributes.h,sha256=Gwad_mO7RFw_0ymOIC1SuwdA7SJd8CSVzWUALdHUQ64,990 +tensorflow/include/xla/hlo/ir/hlo_input_output_alias_config.h,sha256=HIG6KsqoKTcdoDyFiT9hSxLorujZX8If_vLJyDfVVNM,8309 +tensorflow/include/xla/hlo/ir/hlo_instruction.h,sha256=C9yc41bWA13maGLcHZFzugnBX_qNLT4aGsOVn4DF8uw,112074 +tensorflow/include/xla/hlo/ir/hlo_instructions.h,sha256=7zAF8yIK5ItadDp8P-ttfvCHnqm2czq6jkWAbmmv0Cw,103493 +tensorflow/include/xla/hlo/ir/hlo_module.h,sha256=h-LxwlJ0R2lCk0kZDac1PgqSrWvlTz9TS4qswORl1dU,28946 +tensorflow/include/xla/hlo/ir/hlo_module_group.h,sha256=XDbXwQ7-AOE6VvPl3gOkFbbAHIy_1K-RHaRWwp-OIR4,3919 +tensorflow/include/xla/hlo/ir/hlo_module_metadata.h,sha256=wmguoCvE0u-mr-Z-XUX_LMFCB6dfU9S9GDIR-Tt6Q9c,4753 +tensorflow/include/xla/hlo/ir/hlo_op_metadata.h,sha256=UWFBvqqMCzngxLVTjBpPp43Ax_b5xAAhu0K3Q756Ow8,934 +tensorflow/include/xla/hlo/ir/hlo_opcode.h,sha256=kfS-AamKfESSwyrUFuBmoSkOOEXlhWKzxQ9VuAKh84o,13394 +tensorflow/include/xla/hlo/ir/hlo_reachability.h,sha256=-xuzB_r3yqGIsDl9hQ0HNTmi0ISuvjIhzPkphftVhnQ,8563 +tensorflow/include/xla/hlo/ir/hlo_schedule.h,sha256=uteAdz97tPVwRi7msyK4DOoYMjpHcgNKbqp0B9fOCqo,8774 +tensorflow/include/xla/hlo/ir/hlo_sharding.h,sha256=Ou-bkYlCgEg98cT6ybZEWqB2x8a6WTUyx_XzLoYgYMk,27488 +tensorflow/include/xla/hlo/ir/hlo_sharding_metadata.h,sha256=2ARhcKEdomJiNRpBJvSxNfVhyE9qn37QsFi7lA-q5SM,3970 +tensorflow/include/xla/hlo/ir/tile_assignment.h,sha256=Pwi0PbM2k3sUURw8oiit4ElKgG7KPdMe0YR8TWF1B1U,10802 +tensorflow/include/xla/hlo/transforms/hlo_constant_splitter.h,sha256=Pf7mWQj0AdA1cqPQ2e-idN4B4ST64kkAVb1wJtZUaik,1911 +tensorflow/include/xla/hlo/utils/hlo_live_range.h,sha256=ddN4UNPSzfIJbaPrAQL4Q3f5odQxNeA0wpXH0Zs08qQ,8737 +tensorflow/include/xla/hlo/utils/hlo_query.h,sha256=4WcVAeHD2j-Wv24jiLovSbYgNHZ2Hv8iGN6N_p_xh_M,5747 +tensorflow/include/xla/hlo/utils/hlo_sharding_util.h,sha256=ATP7EuKpGlbbvPPZN52FEDkilD9qJmOeIrF2ami7gwY,23488 +tensorflow/include/xla/index_util.h,sha256=MTrPmErcmCJe_3sGppcoIdQI9ALl6WsK0JF26IOQFEw,6155 +tensorflow/include/xla/iterator_util.h,sha256=_klwPpsoOMNSMPF04MGQeqxebMbELbQxYDUuwiYXsFY,5668 +tensorflow/include/xla/layout.h,sha256=uNG5BfhXl5QX4hwGT0FKgERP9l6ojDDPB0jeguhNisQ,13570 +tensorflow/include/xla/layout_util.h,sha256=tdr9GCq-lnOEUJE4EhkLfjO1TZODx5zDI3egase-YPw,12756 +tensorflow/include/xla/lazy.h,sha256=UO3uUcbx_8Rl29arVFuhepfoWMnTpDKJ0hkMYxVbDAU,1275 +tensorflow/include/xla/literal.h,sha256=-cOIKJMh-9s4RG8SvD4jM4H93uBi3769hJwTut_DVpE,64108 +tensorflow/include/xla/literal_comparison.h,sha256=uRvkfYL5FR4ZFNZTGiz2d5sGzhYZdlCEiLscXy2wzp0,4209 +tensorflow/include/xla/literal_util.h,sha256=Qp9Yb7LtwHdLMV1hZ7d3OuMQ_oFV_n3KNhEvdr7e-ro,21512 +tensorflow/include/xla/map_util.h,sha256=aj1zGs5ZXh9Debnzre48pmOoHyfXCUnGZwMZclf-EAQ,4689 +tensorflow/include/xla/metric_table_report.h,sha256=1B3sb7Ev1dTGb4p3sHhUCZKing4ya2wemgbRHjBZxqY,6466 +tensorflow/include/xla/mlir/backends/cpu/transforms/passes.h,sha256=nLH5mbS6fM99pbvcjdReTRKmM84NEaNnNYqCwbhGwHI,2239 +tensorflow/include/xla/mlir/backends/cpu/transforms/passes.h.inc,sha256=VmvlCAQaDvJXoWGGZjf1Z206LXBc3raZtHTORlBz2HY,42540 +tensorflow/include/xla/mlir/backends/gpu/transforms/dataflow_analysis.h,sha256=_3z0UOuhqDrij9z4V8Y0AmF_8S9ziyrjATd0sZSQtIo,1992 +tensorflow/include/xla/mlir/backends/gpu/transforms/passes.h,sha256=7nBCnKZimdHd1H_Fv0iffLKer6vkMiqmYMKqtuEBpEM,5484 +tensorflow/include/xla/mlir/backends/gpu/transforms/passes.h.inc,sha256=a6zP7CBL28OTjaXBPW_RjSCIL0kPTdSnIhXYuiYxufw,47299 +tensorflow/include/xla/mlir/backends/gpu/transforms/uid_generator.h,sha256=3PWCI8cS-RGeGAuFl8KlMh9lNUW908GillqsE-KUN7c,1417 +tensorflow/include/xla/mlir/backends/gpu2/transforms/passes.h,sha256=AzfE2tyoQ6c25oAIUpXDkexLTBCNv9mfHL4KJ9zWouA,2970 +tensorflow/include/xla/mlir/framework/ir/xla_framework.h,sha256=FcvzCeKLJfuWDLfv0YW_1nuOZI-c2-wmISzzLn814qA,1485 +tensorflow/include/xla/mlir/framework/ir/xla_framework.h.inc,sha256=bcXIAFzoMP47lDp7tZ3ExsRslOk3SbcbEeRHvz-wXLM,10918 +tensorflow/include/xla/mlir/framework/ir/xla_framework_dialect.h.inc,sha256=-mRjSDcNyfI4rW7sLVFzh-c6TAF4sqho6nLb0V0WJoY,1593 +tensorflow/include/xla/mlir/framework/ir/xla_framework_types.h.inc,sha256=WjhlZzX5jf771Z4kCP_Y89lg6ChJ1MomuzmrPVeZziw,1118 +tensorflow/include/xla/mlir/framework/transforms/passes.h,sha256=lN0F1unnxbMknWMlWr-SgsvvRyjgWOsANDvpm8vDEeg,1637 +tensorflow/include/xla/mlir/framework/transforms/passes.h.inc,sha256=f6XGO6Qh5inArvu__WQGJSr952ldFH9gw0FYg6a57s0,10958 +tensorflow/include/xla/mlir/math/transforms/passes.h,sha256=Ke-JY58EHg12cZucWwtzaLueI5R0jB6Ja-shdn4YBXQ,1507 +tensorflow/include/xla/mlir/math/transforms/passes.h.inc,sha256=mUluYeOVNzsLZim3SLSZ9vz9dex01lJ_b0YwZ5kno4o,11723 +tensorflow/include/xla/mlir/memref/transforms/passes.h,sha256=ITYlfraMiWy3iZrZ8dZbvpUz-0KGZa0WBXGp62FD4C4,1274 +tensorflow/include/xla/mlir/memref/transforms/passes.h.inc,sha256=BaEj4IHrL1lyBxYjnJcTx-cl8A1fYrGAXSA1DUY0CZE,6097 +tensorflow/include/xla/mlir/runtime/ir/rt_attr_interfaces.h.inc,sha256=zIsIlKQbUOrbRXA_qGO15HWiwhuYkkJRsPQehreBnew,2236 +tensorflow/include/xla/mlir/runtime/ir/rt_attrs.h.inc,sha256=DUal2nLhqJmmOpKS7eXHOfwWOjV7EdtmjAP36y1ZonI,1505 +tensorflow/include/xla/mlir/runtime/ir/rt_dialect.h,sha256=anMgfa51vad450FDVhIBxYyy0RA8eWuiSELDShPh_9s,1539 +tensorflow/include/xla/mlir/runtime/ir/rt_dialect.h.inc,sha256=rxU5OPIGD13Tkqh9deL-60M_aMFVqaObjsED7s9FutA,1955 +tensorflow/include/xla/mlir/runtime/ir/rt_interfaces.h,sha256=LxPvWAFRpjtAeZQ4RGF4qIbf_3L-ykpq32pBWnhzUHI,979 +tensorflow/include/xla/mlir/runtime/ir/rt_ops.h,sha256=4B6jEnAcfk2FGU1ufvszUXEuKfbJKyJSh8jNweCsI5Q,1425 +tensorflow/include/xla/mlir/runtime/ir/rt_ops.h.inc,sha256=6EwFFl9jHL_T21qPIWXaxRz7lUXaoS2bKzmJBnXIG7I,54680 +tensorflow/include/xla/mlir/runtime/ir/rt_types.h.inc,sha256=B9zxCDqq6gW76ypG55ZLDvDZdMkBDzRY84TvaEmBHQE,1728 +tensorflow/include/xla/mlir/runtime/ir/tests/testlib.h,sha256=W4yn9WscZkvfnzVib0GXPP_p2lYg_gtp1sd2JRU1z8U,1718 +tensorflow/include/xla/mlir/runtime/ir/tests/testlib_attrs.h.inc,sha256=Uehcb0yadkBTcopNa4o96tCeql9R9D5IVESafuNk6Yg,2927 +tensorflow/include/xla/mlir/runtime/ir/tests/testlib_dialect.h.inc,sha256=TkvNf79qKT91HnuGmo15j0wJWCTFGFM5ocHzcNYYrcY,1741 +tensorflow/include/xla/mlir/runtime/ir/tests/testlib_enums.h.inc,sha256=_JgAMtHIBr_u282YqVIIhCc1lrCqkRcNejudb0WKtv4,5670 +tensorflow/include/xla/mlir/runtime/ir/tests/testlib_types.h.inc,sha256=unrfvuL1yaq9WGjwhGbzF2PcApoU9_oYbexrhiC0k5w,1398 +tensorflow/include/xla/mlir/runtime/transforms/calling_convention.h,sha256=7h45XP31A-NksW4PY1IPAqNrpH7_3sW_0-DKkl10cng,3814 +tensorflow/include/xla/mlir/runtime/transforms/compilation_pipeline_cpu.h,sha256=O-kZ0v6y8j1oHE4RKneAm7kyjFqautx3rDZwcLEvi4w,2429 +tensorflow/include/xla/mlir/runtime/transforms/compilation_pipeline_gpu.h,sha256=57xuwAUhGwpCtjJZrPlUdNHYddSQl4phC4aFLBFSOeU,2015 +tensorflow/include/xla/mlir/runtime/transforms/compilation_pipeline_options.h,sha256=GvWkRg4VN0GI9CjBqqnqLXWPCahG4vYnT1z62VFfg0E,2237 +tensorflow/include/xla/mlir/runtime/transforms/compiler.h,sha256=ovqjCzZDPZazFKvAaJ6sS1KL0Dkw_sDKedadB3R45mg,1482 +tensorflow/include/xla/mlir/runtime/transforms/custom_call_encoding.h,sha256=no-fO6Zm0mX6WJlKmaqNIZLIBvJLXEtBl6kthFHsveY,32681 +tensorflow/include/xla/mlir/runtime/transforms/jit_compiler.h,sha256=EWiaJoXQalDVLGVV6EvjnrzMkQ0U0_Uxo1YiFSf0IqE,8611 +tensorflow/include/xla/mlir/runtime/transforms/passes.h,sha256=pIDx9J7McY8nNAFV-0pY1_m14jcBwKvhgXRtDYBjQn4,4365 +tensorflow/include/xla/mlir/runtime/transforms/passes.h.inc,sha256=m53BL3RgHe8v63Q2natbU_3E0hNPpCnAkopo_fb7iFQ,29840 +tensorflow/include/xla/mlir/runtime/transforms/specialization.h,sha256=3Ek34dNzJfuaPDkmzqbXlOkisaUgvFajpUhCLdp231Y,2938 +tensorflow/include/xla/mlir/runtime/transforms/type_converter.h,sha256=9a2WQqRpUqHE4BGuqNfGH0n0hPqll-JeVwQVWEL2pN0,3369 +tensorflow/include/xla/mlir/runtime/utils/async_runtime_api.h,sha256=JAuPiU1ecYadZEeK3w0f-m32nLOqHkCHE7Sd5O3o7Ew,2553 +tensorflow/include/xla/mlir/runtime/utils/c_runner_utils.h,sha256=EWxyvMSY_-3CFbSi4cCwXnpV296Zk01HpBNO97cV39I,1581 +tensorflow/include/xla/mlir/runtime/utils/constraints.h,sha256=_M0ZK6rr9sGy3w_Byw9avVAczVS5ZhHCc2aiaSOp0sw,2058 +tensorflow/include/xla/mlir/runtime/utils/custom_calls.h,sha256=8rr7RGxp3O9j7ZoXKSgocSTMaeXhqmT8f8O-Az105rk,3022 +tensorflow/include/xla/mlir/runtime/utils/float_16bits.h,sha256=7KDs3FQP6PlIyu2ImSdl2gScLfaXdIK-fvIr3D9ZXEk,1638 +tensorflow/include/xla/mlir/utils/error_util.h,sha256=SkzjVRJI--7fXq4E3HMorOdcHzNwpR9D_rgz9LzxeCs,2973 +tensorflow/include/xla/mlir/xla_cpu/ir/xla_cpu.h,sha256=jYO0iL1TQP2O0dUG_5PKd-WSzLBamwBFD4TWYSgPMJo,1653 +tensorflow/include/xla/mlir/xla_cpu/ir/xla_cpu.h.inc,sha256=cAuU4YmZhWvtteinwTHWvzsPCGZM01uWY-RLdAR1YHc,91566 +tensorflow/include/xla/mlir/xla_cpu/ir/xla_cpu_attrdefs.h.inc,sha256=U3evD2fwFkkPQuo5LXuOVzPFNVeUSDPQb09cvVeRyX8,1522 +tensorflow/include/xla/mlir/xla_cpu/ir/xla_cpu_dialect.h.inc,sha256=HfKyv-3OZdyoMbdPZ0Usl1nRdChI7U1B1Rd5n-te3Yc,1107 +tensorflow/include/xla/mlir/xla_cpu/ir/xla_cpu_enums.h.inc,sha256=RItkwmIMnX0a8bDMd_FUGxlHRNUsqOXCZ3s4WgQ6noo,3336 +tensorflow/include/xla/mlir_hlo/_virtual_includes/all_passes/deallocation/transforms/passes.h,sha256=ZZY_6CCZ4ZX_-lIpYK7lwUER10bDIAx-ZZXpvRN7Tn0,2550 +tensorflow/include/xla/mlir_hlo/_virtual_includes/all_passes/gml_st/transforms/passes.h,sha256=g4SBaJrkbFhmEnEgv5rw6BCc5oSymWNAZizHN_-ew7k,9983 +tensorflow/include/xla/mlir_hlo/_virtual_includes/all_passes/lhlo/transforms/passes.h,sha256=2Y9uNL7CxQDYyDN2iVBgH4BFoIhM5TchSi_6yhUGbdA,1963 +tensorflow/include/xla/mlir_hlo/_virtual_includes/all_passes/mhlo/transforms/passes.h,sha256=IvOAuySp_AQnHvfKMhxumXPFkBF4WqfQf8OKDFbDRSQ,8261 +tensorflow/include/xla/mlir_hlo/_virtual_includes/all_passes/thlo/transforms/passes.h,sha256=0AH2wIhki34dvhq_Pdm1EtE0ktFa8HE9wVD2bHC1ehQ,1303 +tensorflow/include/xla/mlir_hlo/_virtual_includes/all_passes/transforms/passes.h,sha256=H4pevJJdIMIBCeC-itVnjB9dVi-AY4ZQ5xmMNI4K60U,4807 +tensorflow/include/xla/mlir_hlo/_virtual_includes/chlo_legalize_to_hlo/mhlo/transforms/rewriters.h,sha256=wTzkKPOJY14JvNDrW4bCvehtX8MAp8BVhFPSaqp7gUc,10921 +tensorflow/include/xla/mlir_hlo/_virtual_includes/convert_op_folder/utils/convert_op_folder.h,sha256=tEMneDUBuNY42Bt6D1-b9PfP6Jm0EzIvLID4vR7Jlmk,1241 +tensorflow/include/xla/mlir_hlo/_virtual_includes/deallocation/deallocation/IR/deallocation_ops.h,sha256=kQLaMcVSEAX7c-C0uADV-AmDVcsHA2o7K26vwOZhTiw,1380 +tensorflow/include/xla/mlir_hlo/_virtual_includes/deallocation_ops_inc_gen/deallocation/IR/deallocation_dialect.h.inc,sha256=jvugWnQjGXGWdoLoB4XmNRDMWoyYZyp7sPFjszxpGLA,1422 +tensorflow/include/xla/mlir_hlo/_virtual_includes/deallocation_ops_inc_gen/deallocation/IR/deallocation_ops.h.inc,sha256=6l56yKJHRw0DAXD--Mgku4XuM3BHDUSSgbmsadQvCxI,25419 +tensorflow/include/xla/mlir_hlo/_virtual_includes/deallocation_ops_inc_gen/deallocation/IR/deallocation_typedefs.h.inc,sha256=KxzGTwCMsVGiZVgxxrf-9uG0sgiNHnnWStldmaUyP6k,1166 +tensorflow/include/xla/mlir_hlo/_virtual_includes/deallocation_passes/deallocation/transforms/analysis.h,sha256=VVNde3mKTlAG06tA_8R0_MrpjRI52wUszqevRbHqpHo,2057 +tensorflow/include/xla/mlir_hlo/_virtual_includes/deallocation_passes/deallocation/transforms/passes.h,sha256=ZZY_6CCZ4ZX_-lIpYK7lwUER10bDIAx-ZZXpvRN7Tn0,2550 +tensorflow/include/xla/mlir_hlo/_virtual_includes/deallocation_passes_inc_gen/deallocation/transforms/passes.h.inc,sha256=umMxZ24rTBZJFxPqrWVsZRnKoLUdJjRwDtNE9owIocw,41280 +tensorflow/include/xla/mlir_hlo/_virtual_includes/deallocation_utils/deallocation/utils/util.h,sha256=c8PPI7Qrdl8GQNszHYmSZc4poAMsSDYSWddZJD2JNak,5675 +tensorflow/include/xla/mlir_hlo/_virtual_includes/gml_st/gml_st/IR/gml_st_ops.h,sha256=I2MMXQoUFH-GYeW_LQZznUT_14AjC3prRsU507fG3GU,1333 +tensorflow/include/xla/mlir_hlo/_virtual_includes/gml_st_bufferizable_op_interface/gml_st/interfaces/bufferizable_op_interface_impl.h,sha256=f9a_3ypgiqucrEd3ZqeXUiGrFMd1-9NxrgYd4yPQ_lI,1000 +tensorflow/include/xla/mlir_hlo/_virtual_includes/gml_st_ops_inc_gen/gml_st/IR/gml_st_dialect.h.inc,sha256=aisknAOSUZebUTcrIFjy-Aj2OQOqpyXoItBqGCZxJF4,1099 +tensorflow/include/xla/mlir_hlo/_virtual_includes/gml_st_ops_inc_gen/gml_st/IR/gml_st_ops.h.inc,sha256=_lb4ejrD9ltCxJHivjjNDzb16LISJz64CamOlUvdhYY,13250 +tensorflow/include/xla/mlir_hlo/_virtual_includes/gml_st_passes/gml_st/transforms/fusion/fusion.h,sha256=odEMnPQdxtV1hQu1UWl0M1rnA0Uwjhz1iINtDJ0uxQk,3716 +tensorflow/include/xla/mlir_hlo/_virtual_includes/gml_st_passes/gml_st/transforms/passes.h,sha256=g4SBaJrkbFhmEnEgv5rw6BCc5oSymWNAZizHN_-ew7k,9983 +tensorflow/include/xla/mlir_hlo/_virtual_includes/gml_st_passes/gml_st/transforms/peeling/peeling.h,sha256=pgoQUZXH1rZYxCv017hJ_9EDaxLyai-2UQkij8Bj_K0,1939 +tensorflow/include/xla/mlir_hlo/_virtual_includes/gml_st_passes/gml_st/transforms/scalarization/scalarization.h,sha256=knZv1LmUe2OU6vkMgwxrugv_J3Ksg3YMx2yghGP1SNU,2426 +tensorflow/include/xla/mlir_hlo/_virtual_includes/gml_st_passes/gml_st/transforms/tiling/tiling.h,sha256=d3rS4Z2q85FgOoesiHBfJ2WjyF_kEfhULFI77wkEtHU,1934 +tensorflow/include/xla/mlir_hlo/_virtual_includes/gml_st_passes/gml_st/transforms/vectorization/vectorization.h,sha256=v6S0ZnfeMwIqKtIO1yzi9yRO0mHpAye0JxixSZ32ROY,1977 +tensorflow/include/xla/mlir_hlo/_virtual_includes/gml_st_passes/gml_st/utils/linalg_utils.h,sha256=0Sd3NLbhPe6PPPcTqMozn5wWhFbYdfR5mqTTewk_JpE,3052 +tensorflow/include/xla/mlir_hlo/_virtual_includes/gml_st_passes/gml_st/utils/tensor_utils.h,sha256=Tk98AIFB1of7ZJ1-ljwNm1jTiNvoPEp1fsjUIfKqtUk,2212 +tensorflow/include/xla/mlir_hlo/_virtual_includes/gml_st_passes_inc_gen/gml_st/transforms/passes.h.inc,sha256=3jYCVG_DnBdFyEL4CwhGiglTZC7LsfJXjcey8jVq1qE,132420 +tensorflow/include/xla/mlir_hlo/_virtual_includes/gml_st_transforms/gml_st/transforms/transforms.h,sha256=v5yN-WPAc6C4pNEk7RdO59K1ZAeNQfqNVQOmAiG7RNs,1655 +tensorflow/include/xla/mlir_hlo/_virtual_includes/gpu_transforms_passes_inc_gen/transforms/gpu_passes.h.inc,sha256=E1SAY94wfPMZAMrH3HS0u62HCL181vmNPtX8HNsP3Go,10552 +tensorflow/include/xla/mlir_hlo/_virtual_includes/hlo_dialect_registration/mhlo/IR/register.h,sha256=JaZgDMHYOwIdyG_rPu3d9Q2LMjWijRMtvz2SCCvXChk,1023 +tensorflow/include/xla/mlir_hlo/_virtual_includes/hlo_legalize_to_stablehlo/mhlo/transforms/rewriters.h,sha256=wTzkKPOJY14JvNDrW4bCvehtX8MAp8BVhFPSaqp7gUc,10921 +tensorflow/include/xla/mlir_hlo/_virtual_includes/hlo_ops_attrs_inc_gen/mhlo/IR/hlo_ops_attrs.h.inc,sha256=LOzYkRIDaytGeShcEQsELwG1LQhO8r_i1rxTZYon4Tw,17559 +tensorflow/include/xla/mlir_hlo/_virtual_includes/hlo_ops_common/mhlo/IR/hlo_ops_common.h,sha256=opLmnNUo3gj-HJURlD6-GHp99hmoVfd4uCu17Q9bUR8,2397 +tensorflow/include/xla/mlir_hlo/_virtual_includes/hlo_ops_enums_inc_gen/mhlo/IR/hlo_ops_enums.h.inc,sha256=Pns8uVUaoJk7gNcUNQl1h1asPegKYYLKsSHDTIF_zbI,32552 +tensorflow/include/xla/mlir_hlo/_virtual_includes/hlo_ops_inc_gen/mhlo/IR/hlo_ops.h.inc,sha256=mlRnvvYERPkbEoXdcvnghxIeoNm3-LDXAyqNEyOE7fk,896979 +tensorflow/include/xla/mlir_hlo/_virtual_includes/hlo_ops_typedefs_inc_gen/mhlo/IR/hlo_ops_typedefs.h.inc,sha256=O8PdrgZVygmyLSdrubgbCTU53ECFzZCk_ha48I1DmKE,2087 +tensorflow/include/xla/mlir_hlo/_virtual_includes/legalize_to_linalg_utils/mhlo/utils/legalize_to_linalg_utils.h,sha256=mz0wZGt0sY0TN0Yx7upBPJY3wb6bMQcnn25xKNYsjkw,7231 +tensorflow/include/xla/mlir_hlo/_virtual_includes/lhlo/lhlo/IR/lhlo_ops.h,sha256=GpRFKeD11KaIYx7jZql50JYvGlUvD8FrTgDdFMKAot0,2207 +tensorflow/include/xla/mlir_hlo/_virtual_includes/lhlo/lhlo/IR/lhlo_ops_structs.h,sha256=MCHQnVpJq5pN6WDVzUMOHd4aVuK-dEdv3ct-13bwo0Y,1130 +tensorflow/include/xla/mlir_hlo/_virtual_includes/lhlo/lhlo/utils/lhlo_utils.h,sha256=65i_GTPmu4kdiKYalJEL0kqNKuLI-qct6BY65sz06Mo,2805 +tensorflow/include/xla/mlir_hlo/_virtual_includes/lhlo_gpu/lhlo_gpu/IR/lhlo_gpu_ops.h,sha256=uyPTD3YmlfoMelHtkD9jX8MDMNYizNLpSrtP9kNVFwo,1562 +tensorflow/include/xla/mlir_hlo/_virtual_includes/lhlo_gpu_ops_attrdefs_inc_gen/lhlo_gpu/IR/lhlo_gpu_ops_attrdefs.h.inc,sha256=yggcz1fBZ3fZnwjaNO-_oZNqaql55LcLTT3XoeHwF90,6410 +tensorflow/include/xla/mlir_hlo/_virtual_includes/lhlo_gpu_ops_dialect_inc_gen/lhlo_gpu/IR/lhlo_gpu_ops_dialect.h.inc,sha256=Snrfoz-4tvPDgN03XPjX-t5ZdOCKziOaGFIK6jx9YOU,1485 +tensorflow/include/xla/mlir_hlo/_virtual_includes/lhlo_gpu_ops_enums_inc_gen/lhlo_gpu/IR/lhlo_gpu_ops_enums.h.inc,sha256=e3PSffiMuJi8rM7dWhrlYQnEa84To7CIen9-6kz_Dxc,12744 +tensorflow/include/xla/mlir_hlo/_virtual_includes/lhlo_gpu_ops_inc_gen/lhlo_gpu/IR/lhlo_gpu_ops.h.inc,sha256=S2LN0Bv5xuc19x1aDrYQWktU4KE1nqNe159KIqFWH4Q,256626 +tensorflow/include/xla/mlir_hlo/_virtual_includes/lhlo_gpu_ops_ops/lhlo_gpu/IR/lhlo_gpu_ops.h.inc,sha256=S2LN0Bv5xuc19x1aDrYQWktU4KE1nqNe159KIqFWH4Q,256626 +tensorflow/include/xla/mlir_hlo/_virtual_includes/lhlo_ops_inc_gen/lhlo/IR/lhlo_ops.h.inc,sha256=8_uJEnFfUxhSopr-25NguH19o8X-LzLzYqNU47x0l5A,603865 +tensorflow/include/xla/mlir_hlo/_virtual_includes/lhlo_ops_structs_inc_gen/lhlo/IR/lhlo_ops_structs.h.inc,sha256=NZJdkWYKFXEbp0eYOPmCjJ-s_knL_ML8vXDDoD5Xya4,1856 +tensorflow/include/xla/mlir_hlo/_virtual_includes/lhlo_structured_interface/lhlo/IR/lhlo_structured_interface.h,sha256=p8kuX5-SwDNOEd8zsZ362lxemH6-qVik7WqRNoHS2Bg,970 +tensorflow/include/xla/mlir_hlo/_virtual_includes/lhlo_structured_interface/lhlo/IR/lhlo_structured_interface.h.inc,sha256=emLUsk4IC-rjoXIb31jY4Gc5cI0LW7VrmHjymIlX1WY,3674 +tensorflow/include/xla/mlir_hlo/_virtual_includes/lhlo_structured_interface_inc_gen/lhlo/IR/lhlo_structured_interface.h.inc,sha256=emLUsk4IC-rjoXIb31jY4Gc5cI0LW7VrmHjymIlX1WY,3674 +tensorflow/include/xla/mlir_hlo/_virtual_includes/lmhlo_pass_inc_gen/lhlo/transforms/lmhlo_passes.h.inc,sha256=sOh8JNYZiCf5sUsnaTY7t_qGrCP_fQLBsv2WhSuDCdw,20494 +tensorflow/include/xla/mlir_hlo/_virtual_includes/lmhlo_passes/lhlo/transforms/passes.h,sha256=2Y9uNL7CxQDYyDN2iVBgH4BFoIhM5TchSi_6yhUGbdA,1963 +tensorflow/include/xla/mlir_hlo/_virtual_includes/map_chlo_to_hlo_op/mhlo/transforms/map_chlo_to_hlo_op.h,sha256=HImDyyHIJbe068-4PmVYPjeI3t0UKbXj3wekLkocH10,5422 +tensorflow/include/xla/mlir_hlo/_virtual_includes/map_hlo_to_lhlo_op/lhlo/transforms/map_hlo_to_lhlo_op.h,sha256=ttqAXs2X0yEKAawCQO7d4QSLXhtQdrjAZ7x2RiDd1uo,3148 +tensorflow/include/xla/mlir_hlo/_virtual_includes/map_lhlo_to_hlo_op/lhlo/transforms/map_lhlo_to_hlo_op.h,sha256=B-CJZEq7cxQI_hIz-Moiuq-H6xZcZwFFDjmSzQsTtcc,3052 +tensorflow/include/xla/mlir_hlo/_virtual_includes/map_lmhlo_to_scalar_op/lhlo/transforms/map_lmhlo_to_scalar_op.h,sha256=W1uXZfJ_RdM8BFsZo6oqdkfgGz0L-UlmnQJD5GURWdM,2797 +tensorflow/include/xla/mlir_hlo/_virtual_includes/map_mhlo_to_scalar_op/mhlo/transforms/map_mhlo_to_scalar_op.h,sha256=j5TkgmWrhVVI43sZk1p9fKIY9Pk-rA5zjzeMMxp_YkE,58969 +tensorflow/include/xla/mlir_hlo/_virtual_includes/map_stablehlo_to_hlo_op/mhlo/transforms/map_stablehlo_to_hlo_op.h,sha256=4qe_RcbGe5Yz3m0ZqY34obnkDQGA7arbEUEawEj4rqk,5686 +tensorflow/include/xla/mlir_hlo/_virtual_includes/mhlo_pass_inc_gen/mhlo/transforms/mhlo_passes.h.inc,sha256=wk1VgzmfuPQFFfbWMkP3IgV2EDkOK5FVsdIVxy13iB0,264559 +tensorflow/include/xla/mlir_hlo/_virtual_includes/mhlo_passes/mhlo/interfaces/bufferizable_op_interface_impl.h,sha256=X4yb4Dmx_NlmD9hg-O43IhXXYp8OoVvFO7JFum6ZAyo,1198 +tensorflow/include/xla/mlir_hlo/_virtual_includes/mhlo_passes/mhlo/transforms/passes.h,sha256=IvOAuySp_AQnHvfKMhxumXPFkBF4WqfQf8OKDFbDRSQ,8261 +tensorflow/include/xla/mlir_hlo/_virtual_includes/mhlo_passes/mhlo/transforms/rewriters.h,sha256=wTzkKPOJY14JvNDrW4bCvehtX8MAp8BVhFPSaqp7gUc,10921 +tensorflow/include/xla/mlir_hlo/_virtual_includes/mhlo_passes/mhlo/utils/legalize_to_linalg_utils.h,sha256=mz0wZGt0sY0TN0Yx7upBPJY3wb6bMQcnn25xKNYsjkw,7231 +tensorflow/include/xla/mlir_hlo/_virtual_includes/mhlo_passes/mhlo/utils/mhlo_rng_utils.h,sha256=h7E2cR2tQBXEFkBYQypX0tds6ba7OCFK5cyX1tXcUBE,1335 +tensorflow/include/xla/mlir_hlo/_virtual_includes/mhlo_rng_utils/mhlo/utils/mhlo_rng_utils.h,sha256=h7E2cR2tQBXEFkBYQypX0tds6ba7OCFK5cyX1tXcUBE,1335 +tensorflow/include/xla/mlir_hlo/_virtual_includes/mhlo_scatter_gather_utils/mhlo/utils/mhlo_scatter_gather_utils.h,sha256=603iAPxWZs4Y5iGW9coxW8cuvzwF4BiImL3_CTBZXV0,2932 +tensorflow/include/xla/mlir_hlo/_virtual_includes/mlir_hlo/mhlo/IR/hlo_ops.h,sha256=QvjiX7wh8zl8D4rxnpkLR9y9Gao9WpY-UhdFWe6UpLI,4196 +tensorflow/include/xla/mlir_hlo/_virtual_includes/mlir_hlo/mhlo/IR/mhlo_bytecode.h,sha256=AN-gc_qRVfgwojxxIzatbZaMGyEW3edrLukcmqf5LSY,1045 +tensorflow/include/xla/mlir_hlo/_virtual_includes/mlir_hlo/utils/hlo_utils.h,sha256=dRAH2dJxhChE_AduscFOPNiZKrkHtJpzcAKOByfh-Tc,5601 +tensorflow/include/xla/mlir_hlo/_virtual_includes/shape_component_analysis/mhlo/analysis/shape_component_analysis.h,sha256=89qd11Yemuc4uabwK9mwjwaPZDhATFc1TfvhWFKMmkM,6547 +tensorflow/include/xla/mlir_hlo/_virtual_includes/stablehlo_legalize_to_hlo/mhlo/transforms/rewriters.h,sha256=wTzkKPOJY14JvNDrW4bCvehtX8MAp8BVhFPSaqp7gUc,10921 +tensorflow/include/xla/mlir_hlo/_virtual_includes/thlo/thlo/IR/thlo_ops.h,sha256=BBHaGEjX3YTxHa-DUHO8XARnqaNOFGZknTECBVTf-NI,1359 +tensorflow/include/xla/mlir_hlo/_virtual_includes/thlo_bufferizable_op_interface/thlo/interfaces/bufferizable_op_interface_impl.h,sha256=z937tWCLFKON5GmPmx3frwdpgpoYoQz9PXY-tDd51dQ,1054 +tensorflow/include/xla/mlir_hlo/_virtual_includes/thlo_ops_inc_gen/thlo/IR/thlo_dialect.h.inc,sha256=At440BSiEiXlJHTdn7j5PJ3EVbSkgbJaCaa4GA-TwMA,1087 +tensorflow/include/xla/mlir_hlo/_virtual_includes/thlo_ops_inc_gen/thlo/IR/thlo_ops.h.inc,sha256=5cpHCWjZJr_hOKtRJCe3gIPoksOX4cU8jLM5Stb2jAA,49395 +tensorflow/include/xla/mlir_hlo/_virtual_includes/thlo_passes/thlo/transforms/passes.h,sha256=0AH2wIhki34dvhq_Pdm1EtE0ktFa8HE9wVD2bHC1ehQ,1303 +tensorflow/include/xla/mlir_hlo/_virtual_includes/thlo_passes_inc_gen/thlo/transforms/thlo_passes.h.inc,sha256=YoSzfaATxGCmIYICxIsdnGJyzh23OLfZKTXh3_s1OAs,5691 +tensorflow/include/xla/mlir_hlo/_virtual_includes/transforms_gpu_passes/transforms/gpu_passes.h,sha256=uq3AvgzBVlc-aTgKXGtvf9FbImDpITOcbMFXFM_a6TI,1680 +tensorflow/include/xla/mlir_hlo/_virtual_includes/transforms_passes/transforms/passes.h,sha256=H4pevJJdIMIBCeC-itVnjB9dVi-AY4ZQ5xmMNI4K60U,4807 +tensorflow/include/xla/mlir_hlo/_virtual_includes/transforms_passes/transforms/passes.h.inc,sha256=wa2RGQWrDxcbxj2lcqAzJQEOCQpVEfvT4CWnTsOBYzc,82230 +tensorflow/include/xla/mlir_hlo/_virtual_includes/transforms_passes/transforms/rewriters.h,sha256=U577QT6BIqFg6mmrviQUjiU5Vck7mGhv1UZSYA03xSE,1451 +tensorflow/include/xla/mlir_hlo/_virtual_includes/transforms_passes_inc_gen/transforms/passes.h.inc,sha256=wa2RGQWrDxcbxj2lcqAzJQEOCQpVEfvT4CWnTsOBYzc,82230 +tensorflow/include/xla/mlir_hlo/_virtual_includes/type_conversion/mhlo/utils/type_conversion.h,sha256=zd2RcsfZcD0Ou9pcqkbUEeZ_aMcqWXugx0jItj3kZTk,3699 +tensorflow/include/xla/mlir_hlo/_virtual_includes/unfuse_batch_norm/mhlo/transforms/rewriters.h,sha256=wTzkKPOJY14JvNDrW4bCvehtX8MAp8BVhFPSaqp7gUc,10921 +tensorflow/include/xla/mlir_hlo/_virtual_includes/userange_analysis/analysis/userange_analysis.h,sha256=iydhJNksGuEoI3F_bqGTXeWNU-K1gJ95BtNxKHukiyg,7598 +tensorflow/include/xla/mlir_hlo/analysis/userange_analysis.h,sha256=iydhJNksGuEoI3F_bqGTXeWNU-K1gJ95BtNxKHukiyg,7598 +tensorflow/include/xla/mlir_hlo/deallocation/IR/deallocation_dialect.h.inc,sha256=jvugWnQjGXGWdoLoB4XmNRDMWoyYZyp7sPFjszxpGLA,1422 +tensorflow/include/xla/mlir_hlo/deallocation/IR/deallocation_ops.h,sha256=kQLaMcVSEAX7c-C0uADV-AmDVcsHA2o7K26vwOZhTiw,1380 +tensorflow/include/xla/mlir_hlo/deallocation/IR/deallocation_ops.h.inc,sha256=6l56yKJHRw0DAXD--Mgku4XuM3BHDUSSgbmsadQvCxI,25419 +tensorflow/include/xla/mlir_hlo/deallocation/IR/deallocation_typedefs.h.inc,sha256=KxzGTwCMsVGiZVgxxrf-9uG0sgiNHnnWStldmaUyP6k,1166 +tensorflow/include/xla/mlir_hlo/deallocation/transforms/analysis.h,sha256=VVNde3mKTlAG06tA_8R0_MrpjRI52wUszqevRbHqpHo,2057 +tensorflow/include/xla/mlir_hlo/deallocation/transforms/passes.h,sha256=ZZY_6CCZ4ZX_-lIpYK7lwUER10bDIAx-ZZXpvRN7Tn0,2550 +tensorflow/include/xla/mlir_hlo/deallocation/transforms/passes.h.inc,sha256=umMxZ24rTBZJFxPqrWVsZRnKoLUdJjRwDtNE9owIocw,41280 +tensorflow/include/xla/mlir_hlo/deallocation/utils/util.h,sha256=c8PPI7Qrdl8GQNszHYmSZc4poAMsSDYSWddZJD2JNak,5675 +tensorflow/include/xla/mlir_hlo/gml_st/IR/gml_st_dialect.h.inc,sha256=aisknAOSUZebUTcrIFjy-Aj2OQOqpyXoItBqGCZxJF4,1099 +tensorflow/include/xla/mlir_hlo/gml_st/IR/gml_st_ops.h,sha256=I2MMXQoUFH-GYeW_LQZznUT_14AjC3prRsU507fG3GU,1333 +tensorflow/include/xla/mlir_hlo/gml_st/IR/gml_st_ops.h.inc,sha256=_lb4ejrD9ltCxJHivjjNDzb16LISJz64CamOlUvdhYY,13250 +tensorflow/include/xla/mlir_hlo/gml_st/interfaces/bufferizable_op_interface_impl.h,sha256=f9a_3ypgiqucrEd3ZqeXUiGrFMd1-9NxrgYd4yPQ_lI,1000 +tensorflow/include/xla/mlir_hlo/gml_st/transforms/fusion/fusion.h,sha256=odEMnPQdxtV1hQu1UWl0M1rnA0Uwjhz1iINtDJ0uxQk,3716 +tensorflow/include/xla/mlir_hlo/gml_st/transforms/passes.h,sha256=g4SBaJrkbFhmEnEgv5rw6BCc5oSymWNAZizHN_-ew7k,9983 +tensorflow/include/xla/mlir_hlo/gml_st/transforms/passes.h.inc,sha256=3jYCVG_DnBdFyEL4CwhGiglTZC7LsfJXjcey8jVq1qE,132420 +tensorflow/include/xla/mlir_hlo/gml_st/transforms/peeling/peeling.h,sha256=pgoQUZXH1rZYxCv017hJ_9EDaxLyai-2UQkij8Bj_K0,1939 +tensorflow/include/xla/mlir_hlo/gml_st/transforms/scalarization/scalarization.h,sha256=knZv1LmUe2OU6vkMgwxrugv_J3Ksg3YMx2yghGP1SNU,2426 +tensorflow/include/xla/mlir_hlo/gml_st/transforms/tiling/tiling.h,sha256=d3rS4Z2q85FgOoesiHBfJ2WjyF_kEfhULFI77wkEtHU,1934 +tensorflow/include/xla/mlir_hlo/gml_st/transforms/transforms.h,sha256=v5yN-WPAc6C4pNEk7RdO59K1ZAeNQfqNVQOmAiG7RNs,1655 +tensorflow/include/xla/mlir_hlo/gml_st/transforms/vectorization/vectorization.h,sha256=v6S0ZnfeMwIqKtIO1yzi9yRO0mHpAye0JxixSZ32ROY,1977 +tensorflow/include/xla/mlir_hlo/gml_st/utils/linalg_utils.h,sha256=0Sd3NLbhPe6PPPcTqMozn5wWhFbYdfR5mqTTewk_JpE,3052 +tensorflow/include/xla/mlir_hlo/gml_st/utils/tensor_utils.h,sha256=Tk98AIFB1of7ZJ1-ljwNm1jTiNvoPEp1fsjUIfKqtUk,2212 +tensorflow/include/xla/mlir_hlo/lhlo/IR/lhlo_ops.h,sha256=GpRFKeD11KaIYx7jZql50JYvGlUvD8FrTgDdFMKAot0,2207 +tensorflow/include/xla/mlir_hlo/lhlo/IR/lhlo_ops.h.inc,sha256=8_uJEnFfUxhSopr-25NguH19o8X-LzLzYqNU47x0l5A,603865 +tensorflow/include/xla/mlir_hlo/lhlo/IR/lhlo_ops_structs.h,sha256=MCHQnVpJq5pN6WDVzUMOHd4aVuK-dEdv3ct-13bwo0Y,1130 +tensorflow/include/xla/mlir_hlo/lhlo/IR/lhlo_ops_structs.h.inc,sha256=NZJdkWYKFXEbp0eYOPmCjJ-s_knL_ML8vXDDoD5Xya4,1856 +tensorflow/include/xla/mlir_hlo/lhlo/IR/lhlo_structured_interface.h,sha256=p8kuX5-SwDNOEd8zsZ362lxemH6-qVik7WqRNoHS2Bg,970 +tensorflow/include/xla/mlir_hlo/lhlo/IR/lhlo_structured_interface.h.inc,sha256=emLUsk4IC-rjoXIb31jY4Gc5cI0LW7VrmHjymIlX1WY,3674 +tensorflow/include/xla/mlir_hlo/lhlo/transforms/lmhlo_passes.h.inc,sha256=sOh8JNYZiCf5sUsnaTY7t_qGrCP_fQLBsv2WhSuDCdw,20494 +tensorflow/include/xla/mlir_hlo/lhlo/transforms/map_hlo_to_lhlo_op.h,sha256=ttqAXs2X0yEKAawCQO7d4QSLXhtQdrjAZ7x2RiDd1uo,3148 +tensorflow/include/xla/mlir_hlo/lhlo/transforms/map_lhlo_to_hlo_op.h,sha256=B-CJZEq7cxQI_hIz-Moiuq-H6xZcZwFFDjmSzQsTtcc,3052 +tensorflow/include/xla/mlir_hlo/lhlo/transforms/map_lmhlo_to_scalar_op.h,sha256=W1uXZfJ_RdM8BFsZo6oqdkfgGz0L-UlmnQJD5GURWdM,2797 +tensorflow/include/xla/mlir_hlo/lhlo/transforms/passes.h,sha256=2Y9uNL7CxQDYyDN2iVBgH4BFoIhM5TchSi_6yhUGbdA,1963 +tensorflow/include/xla/mlir_hlo/lhlo/utils/lhlo_utils.h,sha256=65i_GTPmu4kdiKYalJEL0kqNKuLI-qct6BY65sz06Mo,2805 +tensorflow/include/xla/mlir_hlo/lhlo_gpu/IR/lhlo_gpu_ops.h,sha256=uyPTD3YmlfoMelHtkD9jX8MDMNYizNLpSrtP9kNVFwo,1562 +tensorflow/include/xla/mlir_hlo/lhlo_gpu/IR/lhlo_gpu_ops.h.inc,sha256=S2LN0Bv5xuc19x1aDrYQWktU4KE1nqNe159KIqFWH4Q,256626 +tensorflow/include/xla/mlir_hlo/lhlo_gpu/IR/lhlo_gpu_ops_attrdefs.h.inc,sha256=yggcz1fBZ3fZnwjaNO-_oZNqaql55LcLTT3XoeHwF90,6410 +tensorflow/include/xla/mlir_hlo/lhlo_gpu/IR/lhlo_gpu_ops_dialect.h.inc,sha256=Snrfoz-4tvPDgN03XPjX-t5ZdOCKziOaGFIK6jx9YOU,1485 +tensorflow/include/xla/mlir_hlo/lhlo_gpu/IR/lhlo_gpu_ops_enums.h.inc,sha256=e3PSffiMuJi8rM7dWhrlYQnEa84To7CIen9-6kz_Dxc,12744 +tensorflow/include/xla/mlir_hlo/mhlo/IR/hlo_ops.h,sha256=QvjiX7wh8zl8D4rxnpkLR9y9Gao9WpY-UhdFWe6UpLI,4196 +tensorflow/include/xla/mlir_hlo/mhlo/IR/hlo_ops.h.inc,sha256=mlRnvvYERPkbEoXdcvnghxIeoNm3-LDXAyqNEyOE7fk,896979 +tensorflow/include/xla/mlir_hlo/mhlo/IR/hlo_ops_attrs.h.inc,sha256=LOzYkRIDaytGeShcEQsELwG1LQhO8r_i1rxTZYon4Tw,17559 +tensorflow/include/xla/mlir_hlo/mhlo/IR/hlo_ops_common.h,sha256=opLmnNUo3gj-HJURlD6-GHp99hmoVfd4uCu17Q9bUR8,2397 +tensorflow/include/xla/mlir_hlo/mhlo/IR/hlo_ops_enums.h.inc,sha256=Pns8uVUaoJk7gNcUNQl1h1asPegKYYLKsSHDTIF_zbI,32552 +tensorflow/include/xla/mlir_hlo/mhlo/IR/hlo_ops_typedefs.h.inc,sha256=O8PdrgZVygmyLSdrubgbCTU53ECFzZCk_ha48I1DmKE,2087 +tensorflow/include/xla/mlir_hlo/mhlo/IR/mhlo_bytecode.h,sha256=AN-gc_qRVfgwojxxIzatbZaMGyEW3edrLukcmqf5LSY,1045 +tensorflow/include/xla/mlir_hlo/mhlo/IR/register.h,sha256=JaZgDMHYOwIdyG_rPu3d9Q2LMjWijRMtvz2SCCvXChk,1023 +tensorflow/include/xla/mlir_hlo/mhlo/analysis/shape_component_analysis.h,sha256=89qd11Yemuc4uabwK9mwjwaPZDhATFc1TfvhWFKMmkM,6547 +tensorflow/include/xla/mlir_hlo/mhlo/interfaces/bufferizable_op_interface_impl.h,sha256=X4yb4Dmx_NlmD9hg-O43IhXXYp8OoVvFO7JFum6ZAyo,1198 +tensorflow/include/xla/mlir_hlo/mhlo/transforms/map_chlo_to_hlo_op.h,sha256=HImDyyHIJbe068-4PmVYPjeI3t0UKbXj3wekLkocH10,5422 +tensorflow/include/xla/mlir_hlo/mhlo/transforms/map_mhlo_to_scalar_op.h,sha256=j5TkgmWrhVVI43sZk1p9fKIY9Pk-rA5zjzeMMxp_YkE,58969 +tensorflow/include/xla/mlir_hlo/mhlo/transforms/map_stablehlo_to_hlo_op.h,sha256=4qe_RcbGe5Yz3m0ZqY34obnkDQGA7arbEUEawEj4rqk,5686 +tensorflow/include/xla/mlir_hlo/mhlo/transforms/mhlo_passes.h.inc,sha256=wk1VgzmfuPQFFfbWMkP3IgV2EDkOK5FVsdIVxy13iB0,264559 +tensorflow/include/xla/mlir_hlo/mhlo/transforms/passes.h,sha256=IvOAuySp_AQnHvfKMhxumXPFkBF4WqfQf8OKDFbDRSQ,8261 +tensorflow/include/xla/mlir_hlo/mhlo/transforms/rewriters.h,sha256=wTzkKPOJY14JvNDrW4bCvehtX8MAp8BVhFPSaqp7gUc,10921 +tensorflow/include/xla/mlir_hlo/mhlo/utils/legalize_to_linalg_utils.h,sha256=mz0wZGt0sY0TN0Yx7upBPJY3wb6bMQcnn25xKNYsjkw,7231 +tensorflow/include/xla/mlir_hlo/mhlo/utils/mhlo_rng_utils.h,sha256=h7E2cR2tQBXEFkBYQypX0tds6ba7OCFK5cyX1tXcUBE,1335 +tensorflow/include/xla/mlir_hlo/mhlo/utils/mhlo_scatter_gather_utils.h,sha256=603iAPxWZs4Y5iGW9coxW8cuvzwF4BiImL3_CTBZXV0,2932 +tensorflow/include/xla/mlir_hlo/mhlo/utils/type_conversion.h,sha256=zd2RcsfZcD0Ou9pcqkbUEeZ_aMcqWXugx0jItj3kZTk,3699 +tensorflow/include/xla/mlir_hlo/thlo/IR/thlo_dialect.h.inc,sha256=At440BSiEiXlJHTdn7j5PJ3EVbSkgbJaCaa4GA-TwMA,1087 +tensorflow/include/xla/mlir_hlo/thlo/IR/thlo_ops.h,sha256=BBHaGEjX3YTxHa-DUHO8XARnqaNOFGZknTECBVTf-NI,1359 +tensorflow/include/xla/mlir_hlo/thlo/IR/thlo_ops.h.inc,sha256=5cpHCWjZJr_hOKtRJCe3gIPoksOX4cU8jLM5Stb2jAA,49395 +tensorflow/include/xla/mlir_hlo/thlo/interfaces/bufferizable_op_interface_impl.h,sha256=z937tWCLFKON5GmPmx3frwdpgpoYoQz9PXY-tDd51dQ,1054 +tensorflow/include/xla/mlir_hlo/thlo/transforms/passes.h,sha256=0AH2wIhki34dvhq_Pdm1EtE0ktFa8HE9wVD2bHC1ehQ,1303 +tensorflow/include/xla/mlir_hlo/thlo/transforms/thlo_passes.h.inc,sha256=YoSzfaATxGCmIYICxIsdnGJyzh23OLfZKTXh3_s1OAs,5691 +tensorflow/include/xla/mlir_hlo/transforms/gpu_passes.h,sha256=uq3AvgzBVlc-aTgKXGtvf9FbImDpITOcbMFXFM_a6TI,1680 +tensorflow/include/xla/mlir_hlo/transforms/gpu_passes.h.inc,sha256=E1SAY94wfPMZAMrH3HS0u62HCL181vmNPtX8HNsP3Go,10552 +tensorflow/include/xla/mlir_hlo/transforms/passes.h,sha256=H4pevJJdIMIBCeC-itVnjB9dVi-AY4ZQ5xmMNI4K60U,4807 +tensorflow/include/xla/mlir_hlo/transforms/passes.h.inc,sha256=wa2RGQWrDxcbxj2lcqAzJQEOCQpVEfvT4CWnTsOBYzc,82230 +tensorflow/include/xla/mlir_hlo/transforms/rewriters.h,sha256=U577QT6BIqFg6mmrviQUjiU5Vck7mGhv1UZSYA03xSE,1451 +tensorflow/include/xla/mlir_hlo/utils/convert_op_folder.h,sha256=tEMneDUBuNY42Bt6D1-b9PfP6Jm0EzIvLID4vR7Jlmk,1241 +tensorflow/include/xla/mlir_hlo/utils/hlo_utils.h,sha256=dRAH2dJxhChE_AduscFOPNiZKrkHtJpzcAKOByfh-Tc,5601 +tensorflow/include/xla/overflow_util.h,sha256=NQpyKypPOwyMfEfBUaRYN8mWnvI-fnwX8WNJx-JOLEE,2656 +tensorflow/include/xla/parse_flags_from_env.h,sha256=76U0X2oWzdFGAoMU3iGufiUDJDmZGbNK8JB-I1irQ6o,2867 +tensorflow/include/xla/permutation_util.h,sha256=e_ZS7ioRWA7wWhvTJLmhbrVROW6d1qatpLnr4h1DoSs,3038 +tensorflow/include/xla/pjrt/abstract_tfrt_cpu_buffer.h,sha256=NsbsK_ZKpTkAVR2IZoO2muabevJfKmupU-MUYEA4INY,17207 +tensorflow/include/xla/pjrt/c/pjrt_c_api.h,sha256=htH-hRfGYqedhmLkLX2LYObKa0_6yBJU5GHHI4cKK4c,79652 +tensorflow/include/xla/pjrt/c/pjrt_c_api_helpers.h,sha256=4YmoL03p7HNUNPvN8YiTfY4qa46aJBKaJf3mHzIqru0,10430 +tensorflow/include/xla/pjrt/compile_options.pb.h,sha256=pwN6w_XxalOm7qxuYlKT1QkrxdMZpK8nNfkj3fxwJ0s,97544 +tensorflow/include/xla/pjrt/distributed/client.h,sha256=TSynNXsKlmAsHqr_1Iy0ak_gqGHeIuINVVvG_g9dWzw,6423 +tensorflow/include/xla/pjrt/distributed/protocol.grpc.pb.h,sha256=1sOnkJSjwzYEyYEHWq5TLUAennIeNbbpI3uyfF_9hzk,104194 +tensorflow/include/xla/pjrt/distributed/protocol.h,sha256=sx5VTArlgqQ5bW9Lq0u6M1KRxdhc2f3jCnG8OQjb13c,907 +tensorflow/include/xla/pjrt/distributed/protocol.pb.h,sha256=C1fGJHc0FLMWgJdeUxWWggABaXtiV1QacWDcLcMoygk,143732 +tensorflow/include/xla/pjrt/distributed/protocol_mock.grpc.pb.h,sha256=Kn1mVS06-BWEfXB2s1mefzSKekOa5d019PWSxeIHm64,4659 +tensorflow/include/xla/pjrt/distributed/topology_util.h,sha256=I0YnBJpGW2HG7Fk1OJ9CVWHHeMZPpbuLMmXwWDMcPdk,1133 +tensorflow/include/xla/pjrt/distributed/util.h,sha256=kRjZgjd5jhjjV-UO9eokjvc3eGbkNx8YVr7QdUK07vA,1340 +tensorflow/include/xla/pjrt/event_pool.h,sha256=wosudImKJlo5QpOiKutwfHsPrH1MVK4pm9VtrzR7iME,3562 +tensorflow/include/xla/pjrt/execute_options.pb.h,sha256=bdwCBdz0QBguArA2ITTzC-dOBCTlgh7BdBZt05WhKIM,20087 +tensorflow/include/xla/pjrt/gpu/gpu_helpers.h,sha256=vrZKFNKgUahUWf10Tx0LZlv4nrgZEUv5Iwrmvb6yinU,2597 +tensorflow/include/xla/pjrt/gpu/gpu_topology.h,sha256=LhpDsu4nM6D9tB9GUI305w047k_5gf7MQfaXQPp1FxE,1353 +tensorflow/include/xla/pjrt/gpu/gpu_topology.pb.h,sha256=EAjNdO6bW0oymIHMGgG20KP45GJ_dvvm6I61N_BeksI,10392 +tensorflow/include/xla/pjrt/gpu/nccl_id_store.h,sha256=UEv4HLZIjoAClfr2EO-Vjs1IwJbL1uNJ78LmwXqwC6c,2153 +tensorflow/include/xla/pjrt/gpu/se_gpu_pjrt_client.h,sha256=uPfl2vSHm1dumPVz16Egd5KAYNfWsa2oOrK5b8b_JyE,9180 +tensorflow/include/xla/pjrt/local_device_state.h,sha256=n5tfMSJ5unrhsTxqall9QJOPzMYrKXQOxg3FcW0_ORo,10177 +tensorflow/include/xla/pjrt/lru_cache.h,sha256=LMrTUR9Cxfzm7AZ9V0V6Rn1CLGDv2TyXLKzWnB4TcVE,5700 +tensorflow/include/xla/pjrt/metrics.h,sha256=VWuPiaZrEdkHLwU0Z8IBIev2x9BHkvw3jryVOcfW67M,1669 +tensorflow/include/xla/pjrt/mlir_to_hlo.h,sha256=QFzIxM1isGGPKXsL-aunFxTNHZb-R71XKwXIntw5YLA,1685 +tensorflow/include/xla/pjrt/pjrt_api.h,sha256=uX65G6G9lEamnpCitklqh53K5ZMoisexhtN7nyIyQQg,1949 +tensorflow/include/xla/pjrt/pjrt_c_api_client.h,sha256=SOG7jZsv4t8Qi2pAinJj4Jed1lIZWANiE1Tltjk_OHo,26711 +tensorflow/include/xla/pjrt/pjrt_client.h,sha256=Z0tIcyUmg22qs6ZJI0rY9ymA5GgrXHYPuT2Xuhh5mEQ,68613 +tensorflow/include/xla/pjrt/pjrt_common.h,sha256=jR1Biu8iCKe4OyG9fZ4ApqvBg-5T5-sP-4sf1MPvkDc,981 +tensorflow/include/xla/pjrt/pjrt_compiler.h,sha256=FSctWb7kRdHmJOY8TaCrEvlQ8Ot_1gSjazQvyMVfnvQ,6647 +tensorflow/include/xla/pjrt/pjrt_device_description.h,sha256=y9cxVNBrV--rchT6EaekF5yodh-Tp2C_oT1JOUwd8QI,2690 +tensorflow/include/xla/pjrt/pjrt_executable.h,sha256=hbQm0V59V-ns6ixnh4WnNx-zlnBfxUQb4vqjlw4DmW4,14732 +tensorflow/include/xla/pjrt/pjrt_future.h,sha256=M4pw4xJO6oBqZ_ftzbO89RLjwESkVu_7LzPL6Mvv4Ak,10492 +tensorflow/include/xla/pjrt/pjrt_stream_executor_client.h,sha256=RTaGVcnI87VgE2SViGDfuVHpWpGLUe7pVcjYAyF6JhY,40546 +tensorflow/include/xla/pjrt/semaphore.h,sha256=dt7VSFe-yJxr5HbvIvJPuA3cpfm_OqiEl7e59WpCaIY,2075 +tensorflow/include/xla/pjrt/stream_executor_executable.h,sha256=dreBXJFPVH_m5KK_HMvzQKrSkC9SBdaNlGHT4CjYcJc,2812 +tensorflow/include/xla/pjrt/stream_executor_executable.pb.h,sha256=WaoxBWEIEZLQeMzJVHMGyqUyfBwP5F9VEhAmZ4Nbj8k,22604 +tensorflow/include/xla/pjrt/tf_pjrt_client.h,sha256=KVyuEMqV9IJ0RLtCxD5TIhfc8bMGo8L5oPyNZ9ZZDEw,14910 +tensorflow/include/xla/pjrt/tfrt_cpu_pjrt_client.h,sha256=letxnVtel6154DUCiR1khI_duHRAdrYA22ZKfvFdGhE,19352 +tensorflow/include/xla/pjrt/tracked_device_buffer.h,sha256=XtLMfgTqxZlnwJyheAsmLc1kTEUPlwEjospgJUicdgE,13955 +tensorflow/include/xla/pjrt/tracked_tfrt_cpu_device_buffer.h,sha256=8WJMolQ7TKD-mTIuwMb4K_0NXv1H2ztFpYdaoIkCcTw,5749 +tensorflow/include/xla/pjrt/transpose.h,sha256=yk7XQjRBm6S-L8BD0_0qZVyO8wS9yevodvpBSdjw-NY,11356 +tensorflow/include/xla/pjrt/transpose_kernels.h,sha256=5cNc-iMMlx_l3hBEjFOKtjepLExXAKbEIUzFXImRoHo,30887 +tensorflow/include/xla/pjrt/utils.h,sha256=ftuc1HwwQkj1k8EkB9AR7CIiRxO_zNf35C_eIsiAfPs,3727 +tensorflow/include/xla/pjrt/worker_thread.h,sha256=ilwIdfooWpqplLQmKk9SmDc81pxuWXw4jJ9JzxXWtjI,1624 +tensorflow/include/xla/primitive_util.h,sha256=L2G1ThKdmC0geYADtinD54tHZjer2NE4NGo4FVJVNGk,22014 +tensorflow/include/xla/printer.h,sha256=mZpJK2At5IrKgol92qCvv398HBxzM9qCpEPy7aQE62s,3846 +tensorflow/include/xla/protobuf_util.h,sha256=2U4AzJvSA4t93yIkpc4V2pTsNO2mdICKtlDlgidI2UA,2811 +tensorflow/include/xla/python/refine_polymorphic_shapes.h,sha256=LGo6NP2HeUFQd5BfJ3UB-LAlnt513iWPFmUmmr_bP8w,2067 +tensorflow/include/xla/refcounting_hash_map.h,sha256=T9-rRDXPlcKJduJDt4b3wf_HcVcj_RBGuiKhpryBVno,3677 +tensorflow/include/xla/runtime/aot_ffi_execution_context.h,sha256=X5WqZzw2iyXsW1T7uErjfaDmC0JCWmOdGFKmVCNKZ3I,1472 +tensorflow/include/xla/runtime/arguments.h,sha256=NQ6OcUwnVcVged2ozZa1w2yhn7hMH2cAHenogOZqOvA,16158 +tensorflow/include/xla/runtime/async_runtime.h,sha256=fZYKQ_JpuuTllk-nK-i5vs5khS-swnuN3t_smrHH9nE,10334 +tensorflow/include/xla/runtime/async_values_cache.h,sha256=zMS_-xDRbWayp5C9im-3J7DGIfV-y1Ag9c9ukn-1758,982 +tensorflow/include/xla/runtime/compiler.h,sha256=S-qYOlFxz1lR15SZPdpRhBklxL4VG_jKErP-LVqVUBw,1103 +tensorflow/include/xla/runtime/constraints.h,sha256=3wl3MbrVjLS2GPwtJP8ddfM9YZNLQRInIsP3r_MKnVg,6295 +tensorflow/include/xla/runtime/cpu_event.h,sha256=JTDAk1q2NcjVQFjRH5kZKB0khc2v70P1itnHYj4A4vM,1046 +tensorflow/include/xla/runtime/custom_call.h,sha256=McJsVRajXIVukhyjAbP02C3QhYzXU71kTCOpw3gIspM,75530 +tensorflow/include/xla/runtime/custom_call_registry.h,sha256=Na_wimK_Rf_6kOeLSGFF0h5kAoVkjiHSf6RpZ5TTLcU,2814 +tensorflow/include/xla/runtime/default/async_values_cache.h,sha256=HMSw31Z8_xM-K5VP9yKTNhkXss5z9qG8K5FqL_7KGJA,3976 +tensorflow/include/xla/runtime/default/memory_mapper.h,sha256=wt4DkPJrPMcT14Ea6Gi1I4iCsMFAV_Vc_3ZA-SIgKtM,1253 +tensorflow/include/xla/runtime/diagnostics.h,sha256=6NbGxHSOjEfnz5uk8Um59wQsvAH0iIs5yNyGX0VqDqA,5980 +tensorflow/include/xla/runtime/errors.h,sha256=7LrK5G1sjgm8ltzLVatEHp3yN4q0abKuvExsI0iFRDs,1372 +tensorflow/include/xla/runtime/executable.h,sha256=iOyvTix8M41-cmbIlkOp2s899Hj_2TbOj84zYJK4yDs,18878 +tensorflow/include/xla/runtime/execution_engine.h,sha256=9kUMn9M0LJLShlo0wQ8Txggr79-K65f9adysBS3MfHE,7584 +tensorflow/include/xla/runtime/ffi.h,sha256=wkTppuXFlIASvHAc2SiY1Y6X69LhjznaYlOvXLUAh0A,3419 +tensorflow/include/xla/runtime/ffi/ffi_abi.h,sha256=HcgRQlOiaguQHI9Xy5sqpBN0QueF9kTfOGUt_RiNCBY,1991 +tensorflow/include/xla/runtime/ffi/ffi_api.h,sha256=5u0iAI4rJ7K7OEEud_LyITLGIcjW_449DKY6CXJXT1o,44917 +tensorflow/include/xla/runtime/ffi/ffi_c_api.h,sha256=YdyIJQ6YAZ7P7TNsQu1OIq4tTGSUmTZy-1SMEf-s9hg,9863 +tensorflow/include/xla/runtime/jit_executable.h,sha256=qLsaiD7NKTQLzj6OPRUjY5u-DLliH8nNIIZ1QF06_Yg,10749 +tensorflow/include/xla/runtime/logical_result.h,sha256=jtxDXUxmfCL17Mezy9tHQyxdy6KTjHoktVc3yj931_o,1157 +tensorflow/include/xla/runtime/map_by_type.h,sha256=It1JeulnNt_HHB9arZ3iM80bLbu-15GsX-U0lAGR8Uw,3015 +tensorflow/include/xla/runtime/memory_mapper.h,sha256=y1OiUhgoNi82J3-DfxvGCxiogrGqEPGLRiyjZgzUiHI,2211 +tensorflow/include/xla/runtime/memref_view.h,sha256=S5kXQ27dkSMx25BX7jxDsUItAFw7YV_C5dCaQw487lM,1750 +tensorflow/include/xla/runtime/module.h,sha256=6zCEouckn3aFewf5j3fknGlY6xDpyuFM4oa4JxglU_Q,6500 +tensorflow/include/xla/runtime/module_registry.h,sha256=eK3_AMRCMdtNzRgJ1g_Y6JqM8n3QW9xDAjRx5jL5ny0,2587 +tensorflow/include/xla/runtime/results.h,sha256=v42xBDLnbUjWbAeaFTdR2-0Iq3FMT0ip7mFlFFebKq4,7525 +tensorflow/include/xla/runtime/runtime.h,sha256=F-TWPa8UFLtRw3xeKP98w-rrArAo0IM4y9CcSuA0gas,2727 +tensorflow/include/xla/runtime/state.h,sha256=qgYzKBoIroLdu-9ENwiaIdZzvKGKhDWKOJUP11bceeo,7200 +tensorflow/include/xla/runtime/symbolic_shape.h,sha256=FqPuzUxC1b84CejYIZJEMrP5efusCxe82SerHW9Rl2Y,4901 +tensorflow/include/xla/runtime/tracing.h,sha256=k4hbI340r4MukagdDwNLmJL1J3vYzM7d1VwktC5qzTg,1407 +tensorflow/include/xla/runtime/type_id.h,sha256=QY1YbSsl00inZTFmrWDolSnwhD-zv7F81tNAA1ropfc,6337 +tensorflow/include/xla/runtime/types.h,sha256=wVAAYqzkbrop24Km9-iFtpsUYwbzXa1M7IoqjTpWQ-4,11767 +tensorflow/include/xla/service/algebraic_simplifier.h,sha256=VQvJgTrVjrAtg50bYItIbkTAnqzF8Xa7c6z1LJUTNRI,24640 +tensorflow/include/xla/service/all_gather_broadcast_reorder.h,sha256=yx622Z3WlRb7Wu8dPhaEbxtYQ9m_5XL6FJgz4l36q-A,1527 +tensorflow/include/xla/service/all_gather_combiner.h,sha256=Ouun8kJzQAZuPV-2qXcQnaJNbQCxYAy-O_6vT8YAa28,1985 +tensorflow/include/xla/service/all_gather_decomposer.h,sha256=daRuCZj_h-A0lQO3pYvlq7asy_-hhRLDLLyCv4H_MWo,1871 +tensorflow/include/xla/service/all_reduce_combiner.h,sha256=CIwtq8YyK-F3yGr2ZKC2lfGXJi5lbAkTsq7k7Gbu5yk,1904 +tensorflow/include/xla/service/all_reduce_contiguous.h,sha256=NqEkcGkkBsq1MmJKvdpqxPg5hEGxAh77BNqF06uFiGQ,1369 +tensorflow/include/xla/service/all_reduce_folder.h,sha256=IOa6gF3BHUMGtlnbxbP8SyrlBbJGuoAkzmEz1ZfgOrQ,1616 +tensorflow/include/xla/service/all_reduce_key.h,sha256=icor8TbEtLpJuRGQqKouBdsxuipY2H6nt3URNH1OTi4,1557 +tensorflow/include/xla/service/all_reduce_promotion.h,sha256=hQXwNpyCe-0Fb7L_Wr5pwSSpoGHttlo6rHrnro1K2Ys,1356 +tensorflow/include/xla/service/all_reduce_reassociate.h,sha256=eyf_gVV8xOHFG8KbofkRauPMrUIbWhULqTBDOISzHcg,1898 +tensorflow/include/xla/service/all_to_all_decomposer.h,sha256=2tc_SVqpNbj5T-nU62GM21u-TPN5nPIdgzEnDk1PtYw,1763 +tensorflow/include/xla/service/allocation_tracker.h,sha256=V28LdkeXr-TENz3kYYnKao9DkfDrZgcO7j_0a5Sk3ek,6696 +tensorflow/include/xla/service/async_collective_creator.h,sha256=IY_JsNQyZWJfsHaqpcUOBdzjtDs76WoFZ6-UAjskIsM,2181 +tensorflow/include/xla/service/backend.h,sha256=jFi4CnvXCYKuLRcqdyqzPxm0w_Nspillwr7XbnNc3qc,8103 +tensorflow/include/xla/service/batch_dot_simplification.h,sha256=QZwpRLdDlBM0hXP5YubVPZA5YRqPgYqgjBuCn5WPX6o,1529 +tensorflow/include/xla/service/batchnorm_expander.h,sha256=_y-kbP4UlEDotBToeJpfaxPVHNrY34pr2y6KxRBHlQA,2045 +tensorflow/include/xla/service/bitcast_dtypes_expander.h,sha256=mjEf3CJJDSjkYam38s3170rlkmZt77wWqI7y1OlWFBw,1542 +tensorflow/include/xla/service/broadcast_canonicalizer.h,sha256=_NjTUg6CcXPTCsOgni8p74TKGK984hmbCaoOQOVBHjY,1348 +tensorflow/include/xla/service/buffer_assignment.h,sha256=_nVViS928QNpUeXA5P_dCYB8186HLP4nV9xM7Ui8aqA,33455 +tensorflow/include/xla/service/buffer_assignment.pb.h,sha256=8U863E5zR3wf8NVZOlLfo4TAsDmBPOqLfaEEDOzJ65Q,16036 +tensorflow/include/xla/service/buffer_value.h,sha256=C60n9CiEbfawkFfxfj_ViHLTXf5UvcYqRRZ_mYTa2_k,7652 +tensorflow/include/xla/service/buffer_value_containers.h,sha256=frPA2QTV1l5CYIcMdFbRJHqjEL1klFwECu0FMs_lIA0,1972 +tensorflow/include/xla/service/call_graph.h,sha256=P3uXiMRyZj9Lu-l6cd0WXns6rOcMnL-VVPk5vEYjU4I,15358 +tensorflow/include/xla/service/call_inliner.h,sha256=FqZCoWJK2dBhsJfj8msLMJbXw7ZKKkqr6xnrALCtWG4,2118 +tensorflow/include/xla/service/change_op_data_type.h,sha256=MNGVSLb0xRYU5NiyBhp6twrKNayEcozWVCzVoAAy84o,3181 +tensorflow/include/xla/service/channel_tracker.h,sha256=lVBk4fy-6KneojZafsio20CzrNu6fWSFlyohWeLg6zo,1710 +tensorflow/include/xla/service/cholesky_expander.h,sha256=rwujPR4IsdoS3YRmWLyo4Of0zL62_wXL1Yt7HyP82n8,1642 +tensorflow/include/xla/service/collective_combiner_utils.h,sha256=wL-td4d8aAFbSS9HLjGDGZD8EjWR-DN1vXkknE-sJ6I,5395 +tensorflow/include/xla/service/collective_decomposer_utils.h,sha256=hNEUD9uBOQ8i7Rvj-usFNtAegBzAyBgKpJnaTDDqqIo,1294 +tensorflow/include/xla/service/collective_ops_utils.h,sha256=w37ZHMdDArRGRjRmTREeWMvsF5pvyDuuwpoGBZ9mGH4,17411 +tensorflow/include/xla/service/collective_opt_utils.h,sha256=WF1pEOOS_3KfM-r9vYS22oK0jQ5YsDcPRN6mtrB9jwo,2826 +tensorflow/include/xla/service/collective_permute_decomposer.h,sha256=g1cyBeJx9G-1Y7Fb1K3XyvjzuttkXPkSxmxAfCkYlUM,2687 +tensorflow/include/xla/service/collective_pipeliner.h,sha256=i9r-oRtNcHiH4McevMl28wZ46NqpnQMLm8V4W3rbObU,3874 +tensorflow/include/xla/service/collectives_schedule_linearizer.h,sha256=n6_4-p_nqKCvnYijqZP0rx88XVxXQYRB3ACtHWRqGyw,1754 +tensorflow/include/xla/service/comparison_expander.h,sha256=XMMOPla2dYNxk0gb6Z6Ke077DYH7CABiE-uDQdTfWKI,1749 +tensorflow/include/xla/service/compilation_cache.h,sha256=PGIZ1_cayl6X9lkONWycJEANcPABnWaCghl3q5bPaEk,1871 +tensorflow/include/xla/service/compilation_environments.h,sha256=d8R9BfyoDArq4LKa0VwCiWlbUSBOAV7laOv_eextQzg,5870 +tensorflow/include/xla/service/compilation_stats.h,sha256=ON1BFhAzuKaT5FDc9e_dTRV8v4ZuLZ_T1WcROZHj6-A,1852 +tensorflow/include/xla/service/compile_only_service.h,sha256=JaFQ-TXd5HFWtW_yKYHWptVGHhxbemkV4KitEKx92LU,4160 +tensorflow/include/xla/service/compile_time_cap.h,sha256=h8tGbSaWzkBhqk3t91hgCG68_8_k2hR2PZDOHVAiZmY,2622 +tensorflow/include/xla/service/compiler.h,sha256=d3IrKmRCoiu128bRGiMoJJocGzetfkeXjpvpbqOV1Jw,17566 +tensorflow/include/xla/service/computation_layout.h,sha256=zcAgsZV4Dxlr603xfdj5IkpSOTYTUdBxLcarLLGXoto,4152 +tensorflow/include/xla/service/computation_placer.h,sha256=QqgAy4TBbgOUHAkR7oNZLC6_pVPEsbS4NcEhJF8Oh1c,5109 +tensorflow/include/xla/service/conditional_canonicalizer.h,sha256=eSF1wKOU-6ya9AxkUeLnldO821nRyclbIX-mCyvsRhA,1448 +tensorflow/include/xla/service/conditional_simplifier.h,sha256=psv8NmK7B7mQqO98j-gu9afGg23_WbGHrtiEDzVi3kc,1511 +tensorflow/include/xla/service/conditional_to_select.h,sha256=GUJUXUJF6AxCWW9UGarmfTnZ_aqLjQScnxJ4sZQCQ3o,1538 +tensorflow/include/xla/service/constant_value.h,sha256=5kc3qyJ1z0Fdhveuz5Bf_Q_GbvqepiXviWUveoQrZBA,3421 +tensorflow/include/xla/service/convert_async_collectives_to_sync.h,sha256=RR6HhXVTz3Ou8sXuSEebnICDOliR_f1S9Vr37BrRHSw,2352 +tensorflow/include/xla/service/convert_mover.h,sha256=tzuhCkW8TsF_TKmgLxpLCu-OPO1ap2T7XbHWBUmjYCM,1802 +tensorflow/include/xla/service/convolution_4d_expander.h,sha256=8S-Ea0x90_i_LD-RQVd4Sy1a8lATVwCwin8XvT_ARj0,1325 +tensorflow/include/xla/service/convolution_group_converter.h,sha256=0JtJFz_q8JIp1rtQBqNojQyaomljrgxeX5H2DVxOpYQ,2520 +tensorflow/include/xla/service/convolution_pred_expander.h,sha256=NMiHbvS8OYLRS6osrpgltuerWsotsmR9aB-vGjsU0T8,1580 +tensorflow/include/xla/service/copy_insertion.h,sha256=2NndyLMEHsHAnlePgBFP0ampZlOso0u3cdFsrESOCHA,5032 +tensorflow/include/xla/service/cpu/backend_config.pb.h,sha256=4FnTUpSNV4651nZk1i_EDSFB-5ONyRwSaV6fyeIomcg,28156 +tensorflow/include/xla/service/cpu/buffer_desc.h,sha256=x8D_3SE0mkE-4xcYjDLEFMpdcCyS8Ax7u_fbW7p9M7c,1179 +tensorflow/include/xla/service/cpu/buffer_info_util.h,sha256=Pn35OtcRVFJxG1YsoFkm9ePyvEIzr79TQ_-QY3leKD8,1771 +tensorflow/include/xla/service/cpu/compiler_functor.h,sha256=50Gq-VzgtxiPxRV-2zq7oI-uz-3blEGD4FXlbymmpWA,3476 +tensorflow/include/xla/service/cpu/conv_canonicalization.h,sha256=R7geooDgR-aMmW0zh57QTalf5T_qma31rG9cvLP7iOA,2058 +tensorflow/include/xla/service/cpu/cpu_compiler.h,sha256=1ykFmW8DZXVq3ONf2D3h9FXoqRxNnIkKj9wUqt67zg8,9560 +tensorflow/include/xla/service/cpu/cpu_executable.h,sha256=cw5h7b0OROBOO-kZr5d1dlrV68std-q-4c0HsC-vjx8,11639 +tensorflow/include/xla/service/cpu/cpu_instruction_fusion.h,sha256=laPndjDSfwpKumGkqErtNe4WTTW0vhJu4Tfi9WOOi8w,2215 +tensorflow/include/xla/service/cpu/cpu_layout_assignment.h,sha256=aQ_YFxAU82qlvDurjsc-cqeqMxYb1Rq0M4tAxaovzkQ,1798 +tensorflow/include/xla/service/cpu/cpu_options.h,sha256=oYUmmVzbtahQSB7gQiW5av0Pez-nBh0IM6lbJYxviD4,1475 +tensorflow/include/xla/service/cpu/cpu_runtime.h,sha256=rSJol3p6sklrCo4J0miZhAcXSLR_g65rnnK54s4P1HA,10294 +tensorflow/include/xla/service/cpu/cpu_transfer_manager.h,sha256=WV3rVq1fZavEqvlLPeazEoSGdxu4x447Ft1DKlSNV7s,2335 +tensorflow/include/xla/service/cpu/cpu_xfeed.h,sha256=MLd5YhKy_svfIpCRrmvjCMpTBqcau1ksuxAIX-qAkiY,1773 +tensorflow/include/xla/service/cpu/dot_op_emitter.h,sha256=CEui5wsj6ux3fGdh-l1Kg6uypSPMCzUBxNT-jjXSLfA,3224 +tensorflow/include/xla/service/cpu/elemental_ir_emitter.h,sha256=VieLmS-4deR2fj5eUQNZUPavgDCQtMbT477nob9bxVI,2315 +tensorflow/include/xla/service/cpu/executable.pb.h,sha256=LCWaomK2HB-94Kb3WtnSOKoO2kj-vPRNxieKGAXu7bI,20108 +tensorflow/include/xla/service/cpu/hlo_xla_runtime_pipeline.h,sha256=GfUP-r4_a8tQYdxT_fO93Id8NkQ2VrRyuDfKYBt4WK4,1997 +tensorflow/include/xla/service/cpu/ir_emission_utils.h,sha256=TNerATsGiI9eiJMqSjUGmeWv7MSeZcexfRSUhv24n24,1995 +tensorflow/include/xla/service/cpu/ir_emitter.h,sha256=5NF2zrcJJWVL9EsntSzq1uSg8cJDiq0vSHY39tfHya8,30421 +tensorflow/include/xla/service/cpu/ir_function.h,sha256=bGhcH1i4u2co4-uq7MdH7zieoRU66Mqyaj0qVYEANKo,6434 +tensorflow/include/xla/service/cpu/llvm_ir_runtime.h,sha256=ks-g3EeR74ZOsNhcUf9uYz9eoarQz9aZZ6KMcfgL57Y,1803 +tensorflow/include/xla/service/cpu/mlir_emitter.h,sha256=oV6QH60qtqJpqne6virmNkvaf6o2EV1mBeIiOXpDbiM,1798 +tensorflow/include/xla/service/cpu/onednn_matmul.h,sha256=U3Z6Nnpq2DYcB_fCP0VnkWS_nmDuNE62MdkGwJzbJRc,1594 +tensorflow/include/xla/service/cpu/onednn_memory_util.h,sha256=NPz5r9lWE7F7hJhMFWAy2zeABBKiWMf1Mf2YFMajA9I,3153 +tensorflow/include/xla/service/cpu/onednn_rewriter.h,sha256=IDIbcVKem2l6oedpzr7wdH5zXeHx9luRzr-ei2hZB80,1519 +tensorflow/include/xla/service/cpu/orc_jit_memory_mapper.h,sha256=yaB6OvWqqjAOuUgVqCegO5Zeb6lyz_KY-WCai9J57RI,2234 +tensorflow/include/xla/service/cpu/parallel_loop_emitter.h,sha256=yPbaS1yQa1m8usrnEjq5qqZQsBGFW4XuO0nyj0nP4zw,3229 +tensorflow/include/xla/service/cpu/parallel_task_assignment.h,sha256=dNy_CKzJCRdGSEOGpiiMmrr2Z37lZMewC4Z1zZEne68,5066 +tensorflow/include/xla/service/cpu/runtime/collectives.h,sha256=0mszW7vxi-JhihdKVA2fMMNnpiOo9zrexGTrgvcGFwA,1006 +tensorflow/include/xla/service/cpu/runtime/convolution.h,sha256=tiyNt63TLM5IV42XZ1TpuULO21F6tBOlkBgg5EPJ4_w,1755 +tensorflow/include/xla/service/cpu/runtime/convolution_call.h,sha256=MKTlK3LhClYVe2mA2RUO9-npJXkdEctNensnZt1IQSE,1021 +tensorflow/include/xla/service/cpu/runtime/custom_call.h,sha256=zG_nL86I5uTkPGY1NUE_4KORJ04bDTkpqAUnpcCtNV4,1021 +tensorflow/include/xla/service/cpu/runtime/fft_call.h,sha256=tsKRgfbopWGLSqDea3y8y8pb23zY46Ne1EVZ3_9sFD8,981 +tensorflow/include/xla/service/cpu/runtime/rng.h,sha256=lxEtqddFnNfCukyn3pLzi16tB-akneM4c2mGi2SgxKI,1632 +tensorflow/include/xla/service/cpu/runtime/rng_call.h,sha256=ITGbz8TkW0fx7N76GlEnuM4LeBE116utfHt-TQGzpHU,983 +tensorflow/include/xla/service/cpu/runtime/xfeed.h,sha256=I8x84EJpb-6KFRBX-EDOxCwZxXukcHfLESZ7U0Zh6jg,987 +tensorflow/include/xla/service/cpu/runtime_conv2d.h,sha256=Zx2_1HOOdiBVnCHPBf4iUSXoEkNkwgYl3DxVxynxZmU,2248 +tensorflow/include/xla/service/cpu/runtime_conv2d_acl.h,sha256=O7wEUBBvOvvytHF1vUVc0RN7Mbxv-VoQbxIpo4EEdDQ,3720 +tensorflow/include/xla/service/cpu/runtime_conv2d_mkl.h,sha256=c2HEmoXwr3v3rY12iWhqx-_1LgeQGWcYtUOT_rFvsck,1481 +tensorflow/include/xla/service/cpu/runtime_conv3d.h,sha256=1TY7qp0TYjTE5Lpcmnz202DM5fW4EZUzt-9gptJHZ40,2564 +tensorflow/include/xla/service/cpu/runtime_conv_impl.h,sha256=Nh2X7L7xGkbJaFhe9o1aqfFpWeWli414ClD2imfAzvE,9122 +tensorflow/include/xla/service/cpu/runtime_custom_call_status.h,sha256=PpuBENyx9bHt2yO57hLErVONJHDjVqG68Gt5ZYixAx8,1097 +tensorflow/include/xla/service/cpu/runtime_fft.h,sha256=n7MRlmU0Nd6e33Vd4gcER4sQQYlKRdTl1rTxpdpW7MU,1136 +tensorflow/include/xla/service/cpu/runtime_fft_impl.h,sha256=koXDF52ZoQ56MI0-4Gv0aXhDET4wlDMgjAIpTO5e3JU,11012 +tensorflow/include/xla/service/cpu/runtime_fork_join.h,sha256=oPxC5-Xmu0UPreF7AjP22Uyv3PmpyT8UEP_qjh9Mzyc,1304 +tensorflow/include/xla/service/cpu/runtime_fp16.h,sha256=UHckyqethjlYyiHncJeSL028UDYnoLN-_HK4WljCXYE,1812 +tensorflow/include/xla/service/cpu/runtime_key_value_sort.h,sha256=xMCZUpjet6ZXA3lX8fctJPdkCg1Wk5eSu9HN77mv8r0,2167 +tensorflow/include/xla/service/cpu/runtime_lightweight_check.h,sha256=AsBJcqgOdj2q_t8tyElb1JMMgQipd8S23ogRaq67Xgo,1672 +tensorflow/include/xla/service/cpu/runtime_matmul.h,sha256=37hM-Es1u24slbt0Q9GQbmvePx62EZdXkrZfkOAYLcM,2983 +tensorflow/include/xla/service/cpu/runtime_matmul_acl.h,sha256=dHJHaLZ-Nrjj_oHeFG6QcKWjgQ43ahBLveb94-lJB4I,3110 +tensorflow/include/xla/service/cpu/runtime_matmul_common.h,sha256=ZjrY0SoBR8xrUk1oXhq5XU6L08KV5EjVs3vO4zHFeyw,5811 +tensorflow/include/xla/service/cpu/runtime_pow.h,sha256=DLFc43BRpg16kVP6HqWWz_OQZ4eIDbHjM1VCLv0mDsY,994 +tensorflow/include/xla/service/cpu/runtime_single_threaded_conv2d.h,sha256=3CYIR0CYcpbLq5ONQSiXvjTaorIcBXNJINq6uI7ZuFQ,2324 +tensorflow/include/xla/service/cpu/runtime_single_threaded_conv3d.h,sha256=JA8tew_Sdw2WDBNpX-8rlmrJAse4vishvVFAJlGRZLA,2640 +tensorflow/include/xla/service/cpu/runtime_single_threaded_fft.h,sha256=35aWz4RBezlpypKgqSQPy9SNeF9EjFD-vgLxERHCX74,1198 +tensorflow/include/xla/service/cpu/runtime_single_threaded_matmul.h,sha256=JsV0nByVaaVeHCeawFmuC1Pe2G6AgQdTrk6FwIteEj4,2927 +tensorflow/include/xla/service/cpu/runtime_single_threaded_matmul_common.h,sha256=affpjnxtyoqmn_pXYIkrj1yFYN48iYM_rHb8BZuyCw0,3357 +tensorflow/include/xla/service/cpu/runtime_topk.h,sha256=GMh2gbihhyoxa0lCoK-IZoMkWVUtYz86LKOrBsIxa-o,1196 +tensorflow/include/xla/service/cpu/shape_partition.h,sha256=qMLilGWpc0bTWiDY63zhpyAjuizpeUe7HVHPIF29fb4,3560 +tensorflow/include/xla/service/cpu/simple_orc_jit.h,sha256=mQFy_U1T9MgCFNVkajD_bSvJ9BYb2xbea5GQLeTO2Qk,5459 +tensorflow/include/xla/service/cpu/target_machine_features.h,sha256=3zDNgUJOy9g51PwYzsW5Rzy9YE7XC6-RCWjqbTTHBzU,5137 +tensorflow/include/xla/service/cpu/tiled_dot_emitter.h,sha256=FzDafu0sUZGgQpAXJTeg4m2BmE5OmF65eFKh5_qNoIc,2203 +tensorflow/include/xla/service/cpu/vector_support_library.h,sha256=fVyEpCvwJv0uXdxej5gdUT98fHJQ-gN9Y-kA1SgJiVM,13351 +tensorflow/include/xla/service/cpu/windows_compatibility.h,sha256=SXn76-w1RaekcZqAXO6UDBrf2prPkglRPUlkBMNerw4,1010 +tensorflow/include/xla/service/cpu/xfeed_manager.h,sha256=oPY33uV7ODCk1M3qMM45FNbei9aFSfYcsSnfcrQ_wL4,4585 +tensorflow/include/xla/service/cpu/xla_framework.h,sha256=ZeSCq9HP-PcxNjtC3uKmh9qlc2kPIPJrf3lU-3s2Xm8,2402 +tensorflow/include/xla/service/cpu/xla_framework.pb.h,sha256=MA7U3jd-IIBvcQH9FCNvN0tS8PlVT_r2vZfH6_C3Brs,17433 +tensorflow/include/xla/service/cpu_gpu_shape_verifier.h,sha256=hMDtJkB54T6fvnx8wibVVYYH-YXvPHXCaQEiolpu-XQ,1601 +tensorflow/include/xla/service/custom_call_sharding_helper.h,sha256=QIYc4uEZFxQv5aeLDkH2Ww1vSwDiJcJbDZ-C5q7aMK0,3187 +tensorflow/include/xla/service/custom_call_status.h,sha256=7p5TacrLMcKqjsPjJ2-kabAIg3DiMCud8zkf9-v8ync,1670 +tensorflow/include/xla/service/custom_call_status_internal.h,sha256=ilHcWiQBkZRGYo4SfpSTfac340ct8xIZ-wVdD5ahx_8,1398 +tensorflow/include/xla/service/custom_call_target_registry.h,sha256=-OnsAml6E55Nx2DkoCCI7LTHfbkhATxzWHbkc9zK0eY,4687 +tensorflow/include/xla/service/dot_as_convolution_util.h,sha256=1RWSXVg6bRj2FrKfQLAvue9Flul-TUzQAaKWqLPlQl8,4471 +tensorflow/include/xla/service/dot_decomposer.h,sha256=D1jj8t3hY2XOKnHa9w6CH41rCktw-SKHs6hI3h59ccc,1497 +tensorflow/include/xla/service/dot_dimension_merger.h,sha256=VMuxZxReokBfmbdrg0vGo9OuE85GCfceMEg2UxtUh_I,1389 +tensorflow/include/xla/service/dot_merger.h,sha256=yHFIVstgIrYG1qBFRG5zI82b6B0T96n-PFvh0qfEUYA,2514 +tensorflow/include/xla/service/dump.h,sha256=ReuCSrZbVQliwnopRcQzMZ3e26btAGEBivRbekl3N1w,7169 +tensorflow/include/xla/service/dynamic_dimension_inference.h,sha256=ZdfJuNvGhDqBfozqqqanZSwPr7UYPhNw0QF9RBldUKI,7318 +tensorflow/include/xla/service/dynamic_dimension_simplifier.h,sha256=NyE4oBmSaYWQ_f7GCAIfvpk1bFNc7RR3bVs5lmouYIg,1404 +tensorflow/include/xla/service/dynamic_index_splitter.h,sha256=TweNqpc53Ff6_zgrDK5G3txe6Jo1OWcwgCuklcC60e4,1431 +tensorflow/include/xla/service/dynamic_padder.h,sha256=17fs2QjxYsg1sIwlB3LzifyDZYg5erKMbe9Sv6HKs-M,3870 +tensorflow/include/xla/service/dynamic_window_utils.h,sha256=ObpMK9oM_0rWxxQPYNQ1QbL_Wt8TKeSJPLT4GDwku8w,1905 +tensorflow/include/xla/service/eigh_expander.h,sha256=7_PznKZxDm2dAYH7LLC8ZNnlhggNdNR5qwjW8CBo_mA,1567 +tensorflow/include/xla/service/elemental_ir_emitter.h,sha256=Mh530GKyKeP009lInvie3o-awM-kZe5kV2oIOZKP5Ow,14176 +tensorflow/include/xla/service/executable.h,sha256=BlxdHBXsY9mDYoJGBQgm5k0XQrsNtlfPahkOlmrQAB4,16309 +tensorflow/include/xla/service/execution_tracker.h,sha256=KpkCkknS8-quyvrbQYW8zJjZ4q70CDOle4pQ1GNrGQE,3523 +tensorflow/include/xla/service/export_hlo.h,sha256=YgOjER6BFWlod1G7vvXvj9jNegVs-Uz51MgDjDu6zSs,2898 +tensorflow/include/xla/service/flatten_call_graph.h,sha256=Bddt5fOdZPk_ZqkGLLJ4NBuIt05HfjTHEqhzWbgMJzQ,1559 +tensorflow/include/xla/service/float8_fnuz_ir_emitter.h,sha256=Dvd7_MOvaO67ST8ijPAVtbCZs-CJ69G4x7g9tZyzVvE,2032 +tensorflow/include/xla/service/float_normalization.h,sha256=Dyw0j6ZS3chxwYKwD4L34QHTFgtcMHRoDl9-_C3Xd7k,3890 +tensorflow/include/xla/service/float_support.h,sha256=L3Pb9vhGqAdIsVY_ygwPdCPsv5YHRyCfxrpTeHsDjrw,3769 +tensorflow/include/xla/service/fusion_node_indexing_evaluation.h,sha256=Tt9fKgtS8fGAzVwmz6scBQ5Bg_dvpYTwUO9aE0LiOQY,4626 +tensorflow/include/xla/service/fusion_queue.h,sha256=iLorPQ8rC0-6EWiOv4-Kn0G1YhFu_JUYJVepCv98Zb8,2375 +tensorflow/include/xla/service/gather_expander.h,sha256=3BVTlBmioTAEfC5_HJKfMbzMetu18tSIrWiYmcPFXVM,1996 +tensorflow/include/xla/service/gather_scatter_utils.h,sha256=X9oOjgqHL8eBkC0NPmsnr0v1fKENWh5sYtNTfuvcorE,2330 +tensorflow/include/xla/service/gather_simplifier.h,sha256=T6TKjbIRdjnu4oHzE5WVbCJgI-Qhn5e2qcJpoQSFz58,1639 +tensorflow/include/xla/service/generic_transfer_manager.h,sha256=ERdnnJLiQtNn_SmD6BCKF6arEK-gcfR143xcS42IVDA,3107 +tensorflow/include/xla/service/global_device_id.h,sha256=13nISX5BCxuLd7EOnFvQTeCKU76zH8WLrMDwsERBK48,1410 +tensorflow/include/xla/service/gpu/alias_passthrough_params.h,sha256=X-AxsSPpC4lTsol0RWxiYl1p9NMz6TEYGa6-JnYmiow,1700 +tensorflow/include/xla/service/gpu/all_reduce_blueconnect.h,sha256=U4WAWmaS19GWG8OugMGLyxhMVHDAbTTsoHFfRUuTXpI,1892 +tensorflow/include/xla/service/gpu/analytical_latency_estimator.h,sha256=TagFZhl_fgs0yqjxuowMBg_E0SL8SShzPwJkBZITBME,2260 +tensorflow/include/xla/service/gpu/autotuner_compile_util.h,sha256=1dJgY2ktYGXw_JDCZG2aOtsKMpmZrIqfUFjW64RAuZ4,4248 +tensorflow/include/xla/service/gpu/autotuner_util.h,sha256=QjxU-lumGk2cKHy526obXbg2cRAUM4X1mXvFaoxeV_A,10462 +tensorflow/include/xla/service/gpu/backend_configs.pb.h,sha256=6wNMua1gvHxogNAaPDomQRBFDO3groldynby3wvqC8Q,146867 +tensorflow/include/xla/service/gpu/buffer_allocations.h,sha256=QORJC0w0fXRf8tyI2zECtRrETo6CzVRo_iccc55I6t0,3715 +tensorflow/include/xla/service/gpu/buffer_comparator.h,sha256=t1KXn5DtzHJ7ZkKeCbIJyyOd2N3xg3XoHxNxJPDuW3g,1872 +tensorflow/include/xla/service/gpu/buffer_sharing.h,sha256=w1Uq4eJQc1PhLC5Qih3Ni6utIgmN3AKyHLZpD7kXGcc,1396 +tensorflow/include/xla/service/gpu/compile_module_to_llvm_ir.h,sha256=oSMPZx7EhcBd8l0OYacGpsFJL9eerGY6Mz6NM0yGpBE,3254 +tensorflow/include/xla/service/gpu/conditional_thunk.h,sha256=b3ol9yIsnFH21LTicajJGsu3nG8ovAmEcEjaULZFGq8,2687 +tensorflow/include/xla/service/gpu/conv_algorithm_picker.h,sha256=Q0rEC3_h5H0p5qJvcAJVR3K5vyWygMGS1Pn0S-obdX0,6421 +tensorflow/include/xla/service/gpu/conv_layout_normalization.h,sha256=SkqwvyGvSlE2jhok-g8KfEP9N8_ipI5yHk3ahJKt2uU,1231 +tensorflow/include/xla/service/gpu/convolution_thunk.h,sha256=baqy52542KTGS-szusDGq5ydjptU4TGoxQn0ipyQvUc,3527 +tensorflow/include/xla/service/gpu/copy_fusion.h,sha256=1yViRidON8GIesED94wQih3a-I8REHboyqc20yRZ8hE,1509 +tensorflow/include/xla/service/gpu/copy_thunk.h,sha256=4Qy6cK_gy1yrsS_sm0YT_yKMW11Gxwg9hSZr2eJDyew,2619 +tensorflow/include/xla/service/gpu/cublas_cudnn.h,sha256=DBCptVYZOP50tQXtn-uCyEx9hVpYFnSNcUi6NWeyB2A,9198 +tensorflow/include/xla/service/gpu/cublas_lt_matmul_thunk.h,sha256=lCQfDSorEGXZUp1oM_FCIZYXsN3F8eZ4TUOVjslh2R0,3290 +tensorflow/include/xla/service/gpu/cublas_pad_for_gemms.h,sha256=TQeU-I5zrsrJJqXNOpYnAfzoKe57vgKYvyrzn1G5E5U,1903 +tensorflow/include/xla/service/gpu/cublas_padding_requirements.h,sha256=2h-mKZaPaYmQ8cJNVORPe5JeAoamlaart3LbmpfpKC0,1634 +tensorflow/include/xla/service/gpu/cudnn_fused_conv_rewriter.h,sha256=6P3pQDLbwD1gcXTUfLtHLrYl2GU-2f9b_lWRKU0SACY,4328 +tensorflow/include/xla/service/gpu/cudnn_fused_mha_rewriter.h,sha256=XdE5s922_4-2LckltmWWS1X-rDJaoTPC9_40AtIoo2I,1923 +tensorflow/include/xla/service/gpu/cudnn_fused_mha_transpose_fusion.h,sha256=PtrnQHQsXyaMcFIKpnxHfalbK5GD-yg1PhuUbYFYqok,1406 +tensorflow/include/xla/service/gpu/cudnn_pad_for_convolutions.h,sha256=guvlM87B0WZqGX0pyj-OhmhvXCKia_su9JTrdRzOo_k,1940 +tensorflow/include/xla/service/gpu/cudnn_simplify_padding.h,sha256=xAZTXdThcwOqyMJ7pLrjSQxT5QjS6Q3XxMgP0owpzbQ,2641 +tensorflow/include/xla/service/gpu/cudnn_support_utils.h,sha256=W-kYkMEaOET3uSPHZsGvwzvHXQ1f07eZh1M4GIWtekU,3036 +tensorflow/include/xla/service/gpu/cudnn_vectorize_convolutions.h,sha256=clffOGSptn5yd7AJfozUDTUqOkS0jSx7Jyc9cHKEXQk,2315 +tensorflow/include/xla/service/gpu/cusolver_context.h,sha256=x7kuMvplXLe0cePNrac6q6h8rZ3p2k-GGCpQag40AqE,4314 +tensorflow/include/xla/service/gpu/cusolver_rewriter.h,sha256=YhV7czYv68veIveHZTUa3xk04Bx1qZcw-LZ9br1LIWQ,1623 +tensorflow/include/xla/service/gpu/custom_call_thunk.h,sha256=-bofT0t9N09Bx4F6z-Gm5gyKTBIgaXPjYJY6u1tNrQM,2671 +tensorflow/include/xla/service/gpu/dot_dimension_sorter.h,sha256=0C5kAzRilMz-E58o77E2teWX-e4X8E9BN4pETTJVug8,1803 +tensorflow/include/xla/service/gpu/elemental_ir_emitter.h,sha256=rQKYxJiEIDGyghfgrBDkOE7Ez8jEBaS3DCC-lnXvsks,5603 +tensorflow/include/xla/service/gpu/executable.pb.h,sha256=WRfIy9XYmIYY1Y_dlpyX3aIvjJiX2ML5MWN2XStfTOs,40965 +tensorflow/include/xla/service/gpu/fft_thunk.h,sha256=E3oNpS5CLd5zSP0kZxHoNOdS1LzZCR7_Zpi48pvuH4c,3418 +tensorflow/include/xla/service/gpu/for_thunk.h,sha256=0xOW2dOtfFEHBszqdCOcMPpe7D1psLgGqRUN3qORS5M,1774 +tensorflow/include/xla/service/gpu/fused_mha_thunk.h,sha256=N4a93RTw2-MedjK0J83Lum5TjgYl5zQJ0TxsYeKAh2w,5216 +tensorflow/include/xla/service/gpu/fusion_merger.h,sha256=AN-t1cz84EnME5RnoF2qehHu-QImxOzAjpk5e_zINDI,3397 +tensorflow/include/xla/service/gpu/fusion_pipeline.h,sha256=_kxUGZGQCXgqLyigYjEXnPpX-z2c7zNtwzisw-2x-Pg,1463 +tensorflow/include/xla/service/gpu/fusion_wrapper.h,sha256=MWHuKanpAeMOHm4DCG8cZEhuDnPOs_NepLYQpGwPr28,1497 +tensorflow/include/xla/service/gpu/fusions/copy.h,sha256=bkLhqKf2ChUrDOvR3N-7teSPDWGSEVaWgsBQkHltuik,1703 +tensorflow/include/xla/service/gpu/fusions/fusion_emitter.h,sha256=Izm67pcVLcsW6fhGCtuca5ALe1FGU-0oi3EvNNk31dA,3654 +tensorflow/include/xla/service/gpu/fusions/fusions.h,sha256=7TuX8HueuHSYZEaJL2gKGtC2Sh0N-5UAl6P83rVoDKY,1524 +tensorflow/include/xla/service/gpu/fusions/in_place_dynamic_update_slice.h,sha256=Q-aUAxFs6dB7nqHGnWsYxaZvv5CwQMuKTWNOJ9NiabU,3327 +tensorflow/include/xla/service/gpu/fusions/input_slices.h,sha256=_n_yyWzXdc3eIFMWwlORoI7Uplg5isYFrIp16Q265jo,2221 +tensorflow/include/xla/service/gpu/fusions/loop.h,sha256=6uLa1cJDospoYHY9wVRTL2szBNRSviBfPcwi8G-rGSo,2015 +tensorflow/include/xla/service/gpu/fusions/reduction.h,sha256=V-5tWuV1J8jK5ocdoO-XA-aWMDqEX0XUNRZijZpwcsg,3752 +tensorflow/include/xla/service/gpu/fusions/thunk_util.h,sha256=QQM0TeXxIzONMdUF8kfe92F0oD5uFPWcW7Qhx0yHOIc,1351 +tensorflow/include/xla/service/gpu/fusions/tiling_util.h,sha256=YUeCUFt8uP2TcZMKJAmV36mk5wr-Aky_8q3KywrYwOg,5460 +tensorflow/include/xla/service/gpu/fusions/transpose.h,sha256=RsqbwiaPOlnyqwHsCL8ihowjuw_SYYUFL1trMrXMZ5E,3405 +tensorflow/include/xla/service/gpu/gemm_algorithm_picker.h,sha256=5quNiLCPEjOSjFw65cVpTmQpUzowiU6z-rnRceL5DiQ,2985 +tensorflow/include/xla/service/gpu/gemm_broadcast_folding_rewriter.h,sha256=ojGicqk6TTQuBpNV1Y5zMyI_8nEhZjjSIH8POz1A8oc,1864 +tensorflow/include/xla/service/gpu/gemm_rewriter.h,sha256=4-cU58q9Cga9G0h5HeaDR8HFRTrEMwv51aq7i1yFw_4,2211 +tensorflow/include/xla/service/gpu/gemm_rewriter_triton.h,sha256=j2bdL4xWWGC4NDNprq5fs7jgm2bcrzSp8WJt19txn-s,6662 +tensorflow/include/xla/service/gpu/gemm_thunk.h,sha256=nUKTAKRSt7HEpSQscdNs89xX48qlk1vUExYqX71JCSg,2039 +tensorflow/include/xla/service/gpu/gpu_all_gather_optimizer.h,sha256=3YGefGVa3NLyrWrPmefUhyRo0jh0nj1cstXCVtKCLYo,1438 +tensorflow/include/xla/service/gpu/gpu_asm_opts_util.h,sha256=zhOglTqHno0vnwfijuVeL7KU3tMOlcUeVYl6M8rSboY,1094 +tensorflow/include/xla/service/gpu/gpu_async_collective_annotator.h,sha256=BSc5XYOTTsrqEtNijNdBJwuXIDeoi6RKvSXy-Puvbo0,1557 +tensorflow/include/xla/service/gpu/gpu_autotuning.pb.h,sha256=N11uBi8EDMur51m7IMoUZrgWcXMcLxu6eijZ99RhAzo,57471 +tensorflow/include/xla/service/gpu/gpu_compiler.h,sha256=diprK8ZcJTDZWuXz9DcoEy-lmYqBe4JpvBGvhupzPwQ,10655 +tensorflow/include/xla/service/gpu/gpu_constants.h,sha256=nfFfltC0nd_PasYNThvfUsDnItG4BcKO0_g2iZOFsqY,1980 +tensorflow/include/xla/service/gpu/gpu_conv_padding_legalization.h,sha256=CqvnaszqHnk0mTX2CTljrBZBCVW_XAe1ENrUttoO4Ms,1869 +tensorflow/include/xla/service/gpu/gpu_conv_rewriter.h,sha256=4wnMZ2rXako061o3LPYX4Owymjg0NEyCE0BbwqSBpfY,1910 +tensorflow/include/xla/service/gpu/gpu_conv_runner.h,sha256=sLkHg3ilkpewA_q77aShfh8IzzJAOAEkFn71MbwPDo0,9860 +tensorflow/include/xla/service/gpu/gpu_convert_async_collectives_to_sync.h,sha256=jAI8EKP-JJYAJ7zEQIrgYiioR7_KwzUFKuxRs7ZgjXA,1466 +tensorflow/include/xla/service/gpu/gpu_cost_model_stats_collection.h,sha256=3bO9UIYyMVbXU3hxestDKE_nCyGu2gfcuqfHBytwH8k,2050 +tensorflow/include/xla/service/gpu/gpu_executable.h,sha256=8jzDgsXc_1b6hcdvB0Hanw6YkfWf7XNCGI3OT7bQDM8,14786 +tensorflow/include/xla/service/gpu/gpu_executable_run_options.h,sha256=VFCAfP8kKtekjtXq9Ht-xbUS_cZoSc_xC1KV-s8Oa5I,4766 +tensorflow/include/xla/service/gpu/gpu_float_support.h,sha256=7YF6_mThJo7d0ldmGobsaufRviOUhrhgLeregtmHR94,1723 +tensorflow/include/xla/service/gpu/gpu_fused_mha_runner.h,sha256=Mpq85JZJ5FwOEME1gntiGgcp0-yXDXdigDcsu19fDqI,15047 +tensorflow/include/xla/service/gpu/gpu_fusible.h,sha256=MUvO6o4LQw5q15ywMHg4P5qiou_SIOvEFDUJWba3Eug,8959 +tensorflow/include/xla/service/gpu/gpu_hlo_cost_analysis.h,sha256=wiooeLcXYzvx9BSsRjeScme5Dh4UG1ACQeQpLo8FcaU,4638 +tensorflow/include/xla/service/gpu/gpu_hlo_schedule.h,sha256=cVnAskJx34gb2VIVCHsv5ALj_Mhf9LBEJOSIpZkv2tc,1640 +tensorflow/include/xla/service/gpu/gpu_layout_assignment.h,sha256=suUw2FrDJYoK7fo4h9ANJtDLGM2iB528-sGMPNclKGk,2625 +tensorflow/include/xla/service/gpu/gpu_performance_model.h,sha256=LNDQ0ENq966OLazP9R50SzbIPj4wF05LfYSl2X6A2Wc,5607 +tensorflow/include/xla/service/gpu/gpu_reduce_scatter_creator.h,sha256=jl6cC1SN3T0bzqEvOLZvZA06GFcl7CCxZVXX6xsSiZs,1356 +tensorflow/include/xla/service/gpu/gpu_sanitize_constant_names.h,sha256=ALphBxiqDz1uy4ZBDJh6J9wphSaXWEP2gCU_u5r22DI,1477 +tensorflow/include/xla/service/gpu/gpu_scatter_expander.h,sha256=759KqHm7lUyMuDd-LJtLNW341mCIOfakjbmXcdnR91k,1368 +tensorflow/include/xla/service/gpu/gpu_target_config.h,sha256=GufGsfA8JMykum-KRQ67qTVpLzATy-4aCDxgs6ztrQI,1466 +tensorflow/include/xla/service/gpu/gpu_transfer_manager.h,sha256=Ti8mxGc28cUJEpF7LThgMX9_C6deu2H9MxkMUTT_tBo,4772 +tensorflow/include/xla/service/gpu/hlo_algorithm_denylist.h,sha256=3d3c0HIUWVJ9XKeJ0x5DoZ_ssJ3IhFUjFua_KQXPtrQ,1196 +tensorflow/include/xla/service/gpu/hlo_fusion_analysis.h,sha256=3K102gj5SGUhn7gHZ2Mo15gy7lsApFmaN0wCY3qEZ70,5455 +tensorflow/include/xla/service/gpu/hlo_fusion_stats.h,sha256=OwW9vx-q3ViKCi6CjHT_QfOM-mZ-9nCu7KLny6D9juE,1838 +tensorflow/include/xla/service/gpu/hlo_op_profile.pb.h,sha256=4qm64DAqnmvCmyebpabx0_hysl9ECNMoU2_hSClaK9o,32660 +tensorflow/include/xla/service/gpu/hlo_op_profiles.h,sha256=upxArK8aY-iR_QH4xN6htZtiKZoYNDZu9VcA3osgjkk,67284 +tensorflow/include/xla/service/gpu/hlo_to_ir_bindings.h,sha256=Unf011qHUtk2AdRsiBapBxmbN8Bo0VWFXyq33aKfBnU,4579 +tensorflow/include/xla/service/gpu/hlo_traversal.h,sha256=4Mv85WsC63Sf6rcHGAj3rrrnmntrYpJaCSilIDmEMyg,3337 +tensorflow/include/xla/service/gpu/horizontal_input_fusion.h,sha256=7XXuGPBummvG_mZtN_2dTGdMCoRl50j9PFuS62UJAG8,2344 +tensorflow/include/xla/service/gpu/horizontal_loop_fusion.h,sha256=jkBBFwoA6WXL1BDesWJZr9spN3Ca8S1FNjKOiuZ8t6I,5699 +tensorflow/include/xla/service/gpu/infeed_manager.h,sha256=fqXEXDhmMaRaWNM-JSHubH5A2c2UvcBLIPtORw40TMo,2410 +tensorflow/include/xla/service/gpu/infeed_thunk.h,sha256=t19h8j4j_YKTtAgLKgJuXKHGcu2aFWpXqhKcL9QKPKs,1740 +tensorflow/include/xla/service/gpu/instruction_fusion.h,sha256=FSTyJ92sOdmFtkGP4e5pqXxtxgqXNUATBk_svAaax_Y,3146 +tensorflow/include/xla/service/gpu/ir_emission_utils.h,sha256=ojuPV-Xwywv11bGbyec9JRaeu5nEGmDIq0a-V-4wPbY,9175 +tensorflow/include/xla/service/gpu/ir_emitter.h,sha256=DF3-0Oi4I6kPD_SeYL5ut7wWqnR38Qzzpl-pn7s2PH8,6888 +tensorflow/include/xla/service/gpu/ir_emitter_context.h,sha256=_d0VQyokYTOD_IXWnjFEQOP2t09tNTd9fWH9dnnrxa4,4378 +tensorflow/include/xla/service/gpu/ir_emitter_nested.h,sha256=r8vM4GEHHLJWpSzHnaQrbB-HAR-wTWaQQNVSffjEALQ,3477 +tensorflow/include/xla/service/gpu/ir_emitter_triton.h,sha256=0RJ7uVpzOQWswIesuBP49iPwYU1HHJlPSJ4eOdlhapk,4126 +tensorflow/include/xla/service/gpu/ir_emitter_unnested.h,sha256=Ve-6juoQN3SNYqVquR7h4bvX5xbNLAHV_W3Oc8kf5w8,17911 +tensorflow/include/xla/service/gpu/kernel_arguments.h,sha256=wlxmYjDlcSPDoVbH9va6JCeiY8qBRnSvUaNqNA662gc,2970 +tensorflow/include/xla/service/gpu/kernel_mapping_scheme.h,sha256=FMnbAEfp1eR2F3KK2wo58QH2VRlqXGP_N3tYTC49RMI,9111 +tensorflow/include/xla/service/gpu/kernel_reuse_cache.h,sha256=u1s-qP9_EZcqYQBXY5ZvINq775cjoJmbu4iXMNJrVrw,2664 +tensorflow/include/xla/service/gpu/kernel_thunk.h,sha256=IEPB1T31V5wsE_fCMoT52eYGCTzmf7h2ZW5LVNm6ykE,4044 +tensorflow/include/xla/service/gpu/launch_dimensions.h,sha256=sFpkm2zj0rDMfzvLQ3krPm0FURMl09kjTkGSpSvG5QE,4817 +tensorflow/include/xla/service/gpu/llvm_gpu_backend/gpu_backend_lib.h,sha256=Rh9J4NAi-bETUlWJpf0mr_2pAK6CLf8bgyfekSM_O2o,2783 +tensorflow/include/xla/service/gpu/llvm_gpu_backend/utils.h,sha256=7i6_1m2UuZp94geiZPDEs0CfmsJjHYDuHpfBQU6EyJs,1793 +tensorflow/include/xla/service/gpu/loop_double_buffer_transformer.h,sha256=wtmzc1UqtlPy9kCSi_S5Pc6LfGW8fdc99aa0owtOjyM,2070 +tensorflow/include/xla/service/gpu/matmul_utils.h,sha256=2SQ0AH0GM9wYM2inCSh9LBrJjP03PB9IQ-WPaOvWd94,11025 +tensorflow/include/xla/service/gpu/memset_thunk.h,sha256=3P2NWH3UYtexJRHLG-txJJey_d4Dd9RqwlznUSbTZjo,2911 +tensorflow/include/xla/service/gpu/metrics.h,sha256=b3A-WKjvxgK3NFSrAbqbvrtRD2SBU5R_TTR46yvZEJY,1704 +tensorflow/include/xla/service/gpu/move_copy_to_users.h,sha256=hn4dKjGROo1CJXLl7aGDFrx6a4nfSnNKhHEXRGCklZ4,1372 +tensorflow/include/xla/service/gpu/multi_output_fusion.h,sha256=EzmMLW0uV9nGaBJx0rck2B07omTThricunEZ0Ay0u_M,5815 +tensorflow/include/xla/service/gpu/nccl_all_gather_thunk.h,sha256=ZLl-crKAR9qN4AePPqPJVKP6hR3IH_qiT1i6Daecl9c,2317 +tensorflow/include/xla/service/gpu/nccl_all_reduce_thunk.h,sha256=cfhGgSclNh7LJkYBiJ8a16zfkhRID1xHad-4W0PvmgA,4513 +tensorflow/include/xla/service/gpu/nccl_all_to_all_thunk.h,sha256=rIljkX2lwPGYw2kl3-LTJ-i5LuBARjBa2voqUQ0dGA0,2468 +tensorflow/include/xla/service/gpu/nccl_collective_permute_thunk.h,sha256=I3RM3PXsV_sTLPMcElEUp0u7gFGcRmVXz-6izXHSqaY,2780 +tensorflow/include/xla/service/gpu/nccl_collective_thunk.h,sha256=vmUWrIJ69qR1L8O-0AoTouE94DXSl27WkTnkykNvD1o,7444 +tensorflow/include/xla/service/gpu/nccl_p2p_thunk_common.h,sha256=uQAogDbaIxDSKLgm1XZV14B8G4dnAKK6RxALl1z3zpI,5167 +tensorflow/include/xla/service/gpu/nccl_recv_thunk.h,sha256=Doi1Zm4sYQ0jGeABrzGHuh7DB8Cvhnr-xP0K38KHnag,2398 +tensorflow/include/xla/service/gpu/nccl_send_thunk.h,sha256=8u07Fy1P27JTPvme1EE-Jlq8Ij_fnnebdGW5gWeIKFc,2397 +tensorflow/include/xla/service/gpu/nccl_utils.h,sha256=0cjY4vHgqbi4BpWSg30WGn41sbLtcuQgoFpuI1xAtX0,4338 +tensorflow/include/xla/service/gpu/non_atomically_upgradeable_rw_lock.h,sha256=slMiXx7TZvx1fTMERomW_PTNOeezl0ocj-oqKg8igN8,3055 +tensorflow/include/xla/service/gpu/nvptx_compiler.h,sha256=Fxfwo6HkRJ3G1nwqTDE55YpJ15b_gcNAYr7ypyxHevE,5877 +tensorflow/include/xla/service/gpu/outfeed_manager.h,sha256=JVZivWiOi98kYkJ5jEwcNki1FGID3R9fhmvZ40fGQOY,2583 +tensorflow/include/xla/service/gpu/outfeed_thunk.h,sha256=4EPehAD-CL2AZNarQ3MkiTNyqdKCPlBf_59ncYJOb2Y,1715 +tensorflow/include/xla/service/gpu/parallel_loop_emitter.h,sha256=S_S-M26JiGPYn-5Wpg5GaC3MOc0u6f2dcyUUXhc-uW4,3708 +tensorflow/include/xla/service/gpu/precompiled_kernels.h,sha256=3tbEyQRybTTtQFsnwlRGLYMjxxQziDVfQivHNM7uR6w,2454 +tensorflow/include/xla/service/gpu/prepare_hlo_for_ir_emitting_pipeline.h,sha256=7HPleYG2Fa6tpYMjQ4B8-Pfx_yJr1VeJRvtKlmkXElQ,1397 +tensorflow/include/xla/service/gpu/priority_fusion.h,sha256=6KqFU55jVC3ys7zuOUkonOJoi-b7BxEoieVPrVn7gJk,2793 +tensorflow/include/xla/service/gpu/reduction_degenerate_dim_remover.h,sha256=v07OBgu1-bR4ndgx3FOlBPoa4LdRxHHRY3B3UmwKagM,1833 +tensorflow/include/xla/service/gpu/reduction_dimension_grouper.h,sha256=AUilBupJFNfmY_Xq0WuQgofFqdwHZDON7XxV_e_inJo,1789 +tensorflow/include/xla/service/gpu/reduction_layout_normalizer.h,sha256=DRaXthmSUiFZXwNhtNVnENeJKs1jhWLRxJ7YK4Ug5D8,1823 +tensorflow/include/xla/service/gpu/reduction_splitter.h,sha256=iL-dhRSLMBHTSePJV5kOQewyw1-qQ3_qA9vLlT5dS6w,2003 +tensorflow/include/xla/service/gpu/reduction_utils.h,sha256=9UpUyvcEWjNuokk3dcckJpqiWVgIOsnHq4SRD4ceSfA,2803 +tensorflow/include/xla/service/gpu/replica_id_thunk.h,sha256=LapVLbmz6pk-hrheGOuEGi-ylPIA3anmRzb_4FGge0A,1834 +tensorflow/include/xla/service/gpu/runtime/cholesky.h,sha256=fyVxJfZQ95Ud29Fwb4qhSGjG4b0k83VgE-FwbyYcZ88,1059 +tensorflow/include/xla/service/gpu/runtime/collectives.h,sha256=51eHHko8OJRlFixBMbgOpfUgtsrdFkXSHQ3V-9-KMcc,2929 +tensorflow/include/xla/service/gpu/runtime/concurrent_region.h,sha256=hk1tsoQX_MYwtXW2kB6xzQSUxMVsRJH4mshvoaZiWFQ,2501 +tensorflow/include/xla/service/gpu/runtime/conv.h,sha256=R5q2PhcGig_M8QL8kigdUS498C3imGQPsdap43xZbso,2397 +tensorflow/include/xla/service/gpu/runtime/conv_reorder.h,sha256=QNc9T2mPH5aJI9kKddGkUKT9U65eWPV2dELy5-7uSHk,1090 +tensorflow/include/xla/service/gpu/runtime/cublas_lt_matmul.h,sha256=EuUycBWA5JXV2LCbfqaDGs_agzX9yEQgb--gRowNI_c,1783 +tensorflow/include/xla/service/gpu/runtime/custom_call.h,sha256=tAaMkuWfnlAc1MY51qDahz6Zk5E96QV1zmU6IsYAIb0,1018 +tensorflow/include/xla/service/gpu/runtime/executable.h,sha256=EBhUGzKyCUBdOJD1xduVg42Z4KrWzm3c3rq7_kOaudc,7971 +tensorflow/include/xla/service/gpu/runtime/fft.h,sha256=4-_bjvPGwxSrPABRKbVz7v3zsePzDhJhjk265Qf_Qpk,1429 +tensorflow/include/xla/service/gpu/runtime/fused_attention.h,sha256=Vae-_L0YIUj6V_EqvqBk_GCn5XR-8k_XY6tTDpRKlIg,3925 +tensorflow/include/xla/service/gpu/runtime/gemm.h,sha256=TTqqhkY5Og9R6ikwscbqqv5fV86UifqSIMi5DXYhIEY,1289 +tensorflow/include/xla/service/gpu/runtime/graph_launch.h,sha256=Ilp5sCfe_mtOyyt-mWfVFpYdQTF1RYzkArKigSBLbjI,5333 +tensorflow/include/xla/service/gpu/runtime/io_feed.h,sha256=Dm-FAnzoHTfrbbkzaeC6Ts8Ue6XhRcA1hfrK-rzpm24,1064 +tensorflow/include/xla/service/gpu/runtime/kernel_launch.h,sha256=_Hfsqe8arMN18CNBAdfMPXkB94xyCo36_4rZehyzfPY,1932 +tensorflow/include/xla/service/gpu/runtime/memcpy.h,sha256=YPWZguhuXcSOaSHHCDAf-SNhi-mPUBqMgGdw6VOAUW0,1049 +tensorflow/include/xla/service/gpu/runtime/memset.h,sha256=qXtN9UX1tmH6FFI2uTQE0Na8fU8jx-P_6YhY7Vtj32M,1049 +tensorflow/include/xla/service/gpu/runtime/send_recv.h,sha256=ccr8BZcsITQWQM14lS5nFh6wijdab0J5rvJnXpb2G3Q,2048 +tensorflow/include/xla/service/gpu/runtime/sleep_kernel.h,sha256=Kj-FB67Z_7qEb4NeIpQvfnHU7_R7X3-JAt0mecna7t0,887 +tensorflow/include/xla/service/gpu/runtime/stream_synchronization.h,sha256=WMOnwfTRL00rLcZjxKC9KyGbO_BsNtuTBlLUW7Tn6BQ,1133 +tensorflow/include/xla/service/gpu/runtime/support.h,sha256=g-NiC1yEdi9KP2DgPeS6gqnhbR3t3O0tv-UT5LyY1s8,6139 +tensorflow/include/xla/service/gpu/runtime/topk.h,sha256=pLlYWh7ZpP7ZCNqIGuA0pABEEUGlQ3awK6OEKTmEBEM,1012 +tensorflow/include/xla/service/gpu/runtime/topk_kernel.cu.h,sha256=D04_Dr0fK64TrVJveJ4014NZ9jXohhhqV2uGPBfWVd8,10331 +tensorflow/include/xla/service/gpu/runtime/topk_kernel.h,sha256=-DSlvvbfF6P4WVhAx0poJBYzA9wfkSU2tajGsMj4Jls,1609 +tensorflow/include/xla/service/gpu/runtime/topk_kernel_common.h,sha256=9LiKnnj8DZHfte14eNeYac1TTWUmVQ1Vzz4yDEGCUbs,1273 +tensorflow/include/xla/service/gpu/runtime/tracing.h,sha256=ZnzkeEcSqTtTQBnHxNbrwpQQjLdaj-A4cj9xXz9dPy0,1128 +tensorflow/include/xla/service/gpu/runtime/triangular_solve.h,sha256=luZiZlvXJjx32SOMrnXvAlL2upDA8y91l3Q8ejdcBrk,2020 +tensorflow/include/xla/service/gpu/runtime2/executable.h,sha256=YVOWsFnh1tcmmzBg_07w10HR8r6ZLQEUfJIlrfPWC04,7099 +tensorflow/include/xla/service/gpu/runtime3/cholesky_thunk.h,sha256=roAIW52TaSwuvsPD_u1KbM6TLpYkw58_AM7Dr8gNPB4,2812 +tensorflow/include/xla/service/gpu/runtime_intrinsics.h,sha256=s5NtDCW4yhumB5a6-1Fk7IOFNShfFqhPekKr7Q9EMmM,978 +tensorflow/include/xla/service/gpu/scatter_slice_simplifier.h,sha256=JHah0WCdT4EXt-43Y_5QmHjv-0s2LQ1oNMUXyFK7sHE,2224 +tensorflow/include/xla/service/gpu/sequential_thunk.h,sha256=OkgUcOSsY-L7R8GO4HhHLWkOvfvUthJrt7yg_Ln1zd8,1916 +tensorflow/include/xla/service/gpu/softmax_rewriter_triton.h,sha256=2K0zrIKNzf83E6yvlqpNah_GWCGAFmPGv4rbOnhBTjA,2564 +tensorflow/include/xla/service/gpu/split_k_gemm_rewriter.h,sha256=OkMwSSkDgfbwifLoasP6vAYqZVlS7nHMctLi-uK692I,1618 +tensorflow/include/xla/service/gpu/stream_executor_util.h,sha256=Syy9Lz03rv9WSt9z2M1jwVONJwaduigMu7DqkU3s6eU,5360 +tensorflow/include/xla/service/gpu/target_constants.h,sha256=ahL3UP41P_01x43vbdnmdPfBf9L5nIVFbuQr7rmO6H0,1902 +tensorflow/include/xla/service/gpu/target_util.h,sha256=BanCnU3d-gHP4BrtDix07QGk57HyQ_RK6CV7yeY20ow,3039 +tensorflow/include/xla/service/gpu/thunk.h,sha256=JkarHgHYvLW2ONIaL5lWCX8GUMhzKZtKDhAteZsec6o,6715 +tensorflow/include/xla/service/gpu/topk_specializer.h,sha256=5d7WbGoxxfUO9Yh8gLluYV8XmtI0WDwNO973yTJMVgU,1507 +tensorflow/include/xla/service/gpu/topk_splitter.h,sha256=rjbD7aqZt6THkiTER8Zoxzbo903p5JdR40_MnpiPbyE,1877 +tensorflow/include/xla/service/gpu/tree_reduction_rewriter.h,sha256=r3UyZZERad6XA4wezACkLvYr3FFtrezNVaf6rjuCLBs,3231 +tensorflow/include/xla/service/gpu/triangular_solve_rewriter.h,sha256=LNRSmns3W5VrjX_bl4S2NZCU-44vDFnSl8VhzKeQqkg,2208 +tensorflow/include/xla/service/gpu/triangular_solve_thunk.h,sha256=A_Qy9DQHM2Hg_4odzxZ6mZ0osfs0DQ6ubKMgSNMTwGI,3331 +tensorflow/include/xla/service/gpu/triton_autotuner.h,sha256=IPpd4PPaf7V1EIdTmAmzhF-joKZr1VJ--MCmNqBs2Xk,2344 +tensorflow/include/xla/service/gpu/variadic_op_splitter.h,sha256=jt-z9UF0yAq6i4aSOJbAywGWyQlefs6MBBk-VwAaBr8,1461 +tensorflow/include/xla/service/gpu/while_thunk.h,sha256=KpE--KYx1Q6cMI9aCrqskT7iASrUf7ry73Mm_u3HECQ,2591 +tensorflow/include/xla/service/gpu/xfeed_queue.h,sha256=DYBbleDXcb9Dg8B1XHkjMqHB9LVpRzHVAfKD7cdNEfM,5154 +tensorflow/include/xla/service/gpu/xla_executor_state.h,sha256=JcPnsMfNLco61aSC-mOWTkJR3SnhW-n4Kbd_h8TLc9E,2036 +tensorflow/include/xla/service/graphcycles/graphcycles.h,sha256=PgHt2S5v8lMDiFkc7EYrk8fauIliXQKEdKQta1Um4sI,6288 +tensorflow/include/xla/service/graphcycles/ordered_set.h,sha256=PYIO5P0oLZkjEyXL2FMFsUyEltH7758wcsDvNeJDwJ0,2911 +tensorflow/include/xla/service/heap_simulator.h,sha256=ygr2mna9KiF5K7c6x0cJQ-LQz-vSC-o8IhVSV_2lpwg,38439 +tensorflow/include/xla/service/hlo.pb.h,sha256=-brvxA8K5DQ0Ui-UEIrr75hEVvnKy20866-4E_lr1vQ,668225 +tensorflow/include/xla/service/hlo_alias_analysis.h,sha256=EkQEJgXSHQVmCXwNP3mF4BWxj3XEuUJgeKNmHpOVq2A,4655 +tensorflow/include/xla/service/hlo_buffer.h,sha256=NpoekiQG6aSMfnLH2OsUSVa0JCiatKckeVxBQ2Riqk0,4583 +tensorflow/include/xla/service/hlo_computation_deduplicator.h,sha256=t_3co305uCfdvTk0yUOa95htEGkshRIZK7Xs9rl8xkY,1898 +tensorflow/include/xla/service/hlo_constant_folding.h,sha256=mmpK-dDuIqQXXPv-LTui3zg_9AsZO-22rbqVU-hmA4Y,1610 +tensorflow/include/xla/service/hlo_cost_analysis.h,sha256=j_UtJ5CvEvYiWY42xSsD3RCbUv_KXlYQ3Mg9uKwkfQ4,26819 +tensorflow/include/xla/service/hlo_creation_utils.h,sha256=KKYbhfrS5MHdem2BcE471smkSjKKrq3j-emdHNv6Vww,19217 +tensorflow/include/xla/service/hlo_cse.h,sha256=rFtp120bwYwKAiJXlJmNvFqUObrm5rmMYfONdthFlH0,2338 +tensorflow/include/xla/service/hlo_dataflow_analysis.h,sha256=urBQGYglwMfBcGpTp_B4cHAtd1wU4ENAX6BXTLAgW24,16470 +tensorflow/include/xla/service/hlo_dce.h,sha256=hmmEOVL-Zc5z559PloGoFxHH1y1t2PQ2m-d-Vy9oGwQ,3033 +tensorflow/include/xla/service/hlo_domain_isolator.h,sha256=GIWRVxMqj2LQJQ7q27xXimefAI1mcwiZLUHIREGsf90,2402 +tensorflow/include/xla/service/hlo_domain_map.h,sha256=F70so3ryCfnnZx9bYjKtpQQrdGCd-G4GFvlPdQ2bJn4,5693 +tensorflow/include/xla/service/hlo_domain_remover.h,sha256=nfBSHWp2lYLHuPRRIxtL9sKtt1UUgLYIcpZp3eEwaqw,2657 +tensorflow/include/xla/service/hlo_domain_verifier.h,sha256=6_k3leeyr158BJnoRB_CLEHZ4mBHuNBPCK8iCauDogc,2570 +tensorflow/include/xla/service/hlo_execution_profile.h,sha256=EvTc4qQiyf3_lZxBLA8Fcx_VDujlJTvP5yd6FAsZNHg,6436 +tensorflow/include/xla/service/hlo_execution_profile_data.pb.h,sha256=yNoCIe1Dh7n6AR9MIOT2VBzr1Q243FmQKOYooJhw9AU,15766 +tensorflow/include/xla/service/hlo_graph_dumper.h,sha256=TcsN-0A_xWT0mHEaiEPXmL8DB5edEH5mZpjB7QNTNVs,5677 +tensorflow/include/xla/service/hlo_lexer.h,sha256=tpcOzk7_hL_UbPHVDk6hH6sMmZSlqlf3YzU_u9oa1PQ,6097 +tensorflow/include/xla/service/hlo_memory_scheduler.h,sha256=wv1EfMkxNIwrViesW2UuEcPcUs-SDZhcQ5hSHstptaM,8120 +tensorflow/include/xla/service/hlo_module_config.h,sha256=lmK2rFJUu5GtCe9ua72FGA-mzZ8gwQzQqiYC8T-LSww,18915 +tensorflow/include/xla/service/hlo_module_util.h,sha256=RyVD4Q7p0O1B_Fu00tx9v149E6GkTqbGnmLrqT8Nzyw,2097 +tensorflow/include/xla/service/hlo_ordering.h,sha256=xPe64XFSRC99LMaKmqiYPJ19JTFZ_jnUSFYrXHggOek,9869 +tensorflow/include/xla/service/hlo_parser.h,sha256=TIfyQp2SYN5QhfQiSM7Xw6xPXSNwXbscr5yBa-QvIK0,4165 +tensorflow/include/xla/service/hlo_pass_fix.h,sha256=eqwmd8Kpq17bmty0JFziZM5Y5PEQE7eA5JeEDM-1iug,5411 +tensorflow/include/xla/service/hlo_pass_interface.h,sha256=zzIIoau6clc4dmPz2Zv8aNRSyea_FO1QjqbqTIOE8vY,7553 +tensorflow/include/xla/service/hlo_pass_pipeline.h,sha256=8xYThv8jVhVA-Kza4FoyoUamisqKXQdtXzOO-FbOXCw,6805 +tensorflow/include/xla/service/hlo_phi_graph.h,sha256=MGD2grxnL0NMBzNCoD5n3C8CdMQSr0Qv6HArnppePdY,3492 +tensorflow/include/xla/service/hlo_profile_printer.h,sha256=f_PGoBGq2TvFikfUUWakD6xq6HkFTkRhneB47Wu2x1w,1191 +tensorflow/include/xla/service/hlo_profile_printer_data.pb.h,sha256=Grfdd5uQ7SiRtLPtj80yVrCu-MJ3rzhrNL6glj_vcUA,54337 +tensorflow/include/xla/service/hlo_proto_util.h,sha256=mvwNRnUbDqNeDygtaiUa5GoBr5RjXAFlJBncplIeR5s,2398 +tensorflow/include/xla/service/hlo_rematerialization.h,sha256=Mwhc5ZF_NO6cTVNq-nwMjCPoQ1KQWZPQUWgN1QZUv68,10644 +tensorflow/include/xla/service/hlo_replication_analysis.h,sha256=Ob9doym7KGjwkeUsOnflVuMKbFrA-KQ8ZbWhdDhn6Hc,6624 +tensorflow/include/xla/service/hlo_value.h,sha256=exZRXSzdZ0xv1GpRRxcRCCQpolJJl3zyhOAj3RmekJQ,10242 +tensorflow/include/xla/service/hlo_verifier.h,sha256=3SHqpy46LeXAx5CtI8CKErJzYaC6tLblIvYYQLapom0,17304 +tensorflow/include/xla/service/human_readable_profile_builder.h,sha256=lnRFldzkO8hT7pu3gos-5WLofrGdW25tCZbJ4rSH3ek,3147 +tensorflow/include/xla/service/indexed_array_analysis.h,sha256=9t8iUQGA4lwOkuJ0esXl1Fzef3C_005cSjFzBtzlYFc,15705 +tensorflow/include/xla/service/instruction_fusion.h,sha256=x08QMQeP-IeDEaYphug1bxNImnwnuD7PukSGTQfCjhY,14800 +tensorflow/include/xla/service/latency_hiding_scheduler.h,sha256=osTI-SZ1oUmgQkfNjXIyGYcgCLzPz-9VXlrreHA-pDE,37129 +tensorflow/include/xla/service/layout_assignment.h,sha256=Gjlwi1TZEZjNJxSMGHiGQ_KB4b3Y38_ZB8AqwUY3sxk,32777 +tensorflow/include/xla/service/layout_normalization.h,sha256=N2eA9XCauno57QpJOqmr5692f90EjvVosCq2gWcouAI,2163 +tensorflow/include/xla/service/llvm_compiler.h,sha256=qa_EbGBemk9eYzGKKy7p3fYZR57aCu6OQNmOyj453zI,3063 +tensorflow/include/xla/service/llvm_ir/alias_analysis.h,sha256=OX4CxXRue_wSRZKqTS661Yas5OPnEwSxxhGPO7sU4tE,3453 +tensorflow/include/xla/service/llvm_ir/buffer_assignment_util.h,sha256=RUFD9-ykz-_6ODBVeWDkQXWCEfvekGd4UdrOJk9t0Pw,1851 +tensorflow/include/xla/service/llvm_ir/dynamic_update_slice_util.h,sha256=5hnr_4jVmYlsY4m5J_HEdk3-UiU7MxJ4rwneDOdBYZY,4358 +tensorflow/include/xla/service/llvm_ir/fused_ir_emitter.h,sha256=oFjulIshDVg6mV0IduBPv3g9uC2daYiGhQ8hc3Vm5Xk,3535 +tensorflow/include/xla/service/llvm_ir/ir_array.h,sha256=uHfPcwp-HeIDla0idfue_i7KRr9PdszkB_sWM525yrk,16653 +tensorflow/include/xla/service/llvm_ir/ir_builder_mixin.h,sha256=9ud4XH_UC9Z-0T_UIC4oHEZIPsvxW6MjQxPODNEzxXk,13498 +tensorflow/include/xla/service/llvm_ir/kernel_support_library.h,sha256=5jfmWJnxBPLTXNvnTfyApiKdIB_Edo34SUuu-r8dd1I,12479 +tensorflow/include/xla/service/llvm_ir/llvm_command_line_options.h,sha256=m9OH-kAx7OEhuP9xI1mofObm3wH5S4b3JZQSy-HeklA,2047 +tensorflow/include/xla/service/llvm_ir/llvm_loop.h,sha256=aTdsi9S3mBztsd9gFG1tl22mlMTxx35snhsdBNYD1S8,11513 +tensorflow/include/xla/service/llvm_ir/llvm_type_conversion_util.h,sha256=CITrl3gI-O2CX3Zcyqq7ekRd4ElldabQpGQoozUkPLs,1850 +tensorflow/include/xla/service/llvm_ir/llvm_util.h,sha256=V0e1rqeoQcO3XlKG9DAApprpL5lL-1Lau7aqHvL4ebE,14812 +tensorflow/include/xla/service/llvm_ir/loop_emitter.h,sha256=g1XhQaL75NShRmg5fC2w7cZTiW2vl2ciPBXQ1rX_2tI,4494 +tensorflow/include/xla/service/llvm_ir/math_ops.h,sha256=BURjo49ywByzUYECObdwkPvzqUzrHozgtdhkYad98yU,1123 +tensorflow/include/xla/service/llvm_ir/sort_util.h,sha256=fTS81k-2oGlFyvJQ0D-nSzqlJX1UnDvGcXCrS-FcDQ8,1897 +tensorflow/include/xla/service/llvm_ir/tuple_ops.h,sha256=3oCv4hV2Kw_oBkZLj4BzCRngme2DdDHAtzUfXcrN-zw,2391 +tensorflow/include/xla/service/local_service.h,sha256=W8ZQWMfAIkmtsX_nEauhGsfKeTfIyYAV3hf_QbfgXEE,3798 +tensorflow/include/xla/service/local_service_utils.h,sha256=6tAKrSa5FroV1Rez6oGkcLRT-jt4zcKtKAYgGiGLlJ4,1448 +tensorflow/include/xla/service/logical_buffer.h,sha256=sGii0WLRjW4psHzIqnKZq5ahAL-M0Zmp5wU6RMOi0_I,2051 +tensorflow/include/xla/service/logical_buffer_analysis.h,sha256=USgDxo8kVDX-c2QaCXvPq54FPOXkDOwoHnw0Jjh_NBo,3736 +tensorflow/include/xla/service/logistic_expander.h,sha256=czDY6Nujij6e0hZQtVtJ_snSxlmDk9ubEHYNaOEElXI,1661 +tensorflow/include/xla/service/loop_schedule_linearizer.h,sha256=_wQ-STa-VI32MUsPyKug_pTCQnlUyBRac-Eprqflj_s,2278 +tensorflow/include/xla/service/map_inliner.h,sha256=iXhEWblpCLp3UJ9kIWv2NQzbTZbBtR-s-5SbCo-Zz6o,1489 +tensorflow/include/xla/service/mapped_ptr_container_sorter.h,sha256=CeYw8OyG_B854WG1kSD4fIRkBwnhGEol_c4T3DwmJMo,17748 +tensorflow/include/xla/service/maybe_owning_device_memory.h,sha256=zrGEi_TnDTUWshWXhebqJ0aExvd8LC8pDAQyFWErZEc,2869 +tensorflow/include/xla/service/memory_space_assignment/memory_space_assignment.h,sha256=57xTF7G9YrDw_OLFS8m37qvlDDF0jgNI31oKUYROUs0,116875 +tensorflow/include/xla/service/memory_space_assignment/memory_space_assignment.pb.h,sha256=LXIkjJ1RGPJhOFWxsMNYJlgtM-e2KTwKQPw-LojH6Dg,23806 +tensorflow/include/xla/service/memory_space_assignment/repacking.h,sha256=5J2cnTnrVJ9NipnxryVAq9iTJr-zo1XCkpwbV9BqiOU,6262 +tensorflow/include/xla/service/memory_space_assignment/tuning_utils.h,sha256=WIXVQwH2RdsHfuftYH2ho39Bfn4Q_l1jMicXOzicLSg,1453 +tensorflow/include/xla/service/memory_space_assignment/utils.h,sha256=ROp03wWHkK5suJZnHsxbOAo9HYj7H4KbFD40Wsj1Whk,1483 +tensorflow/include/xla/service/metrics.pb.h,sha256=RUUQCDr-ny1pQW_OcP_e4hZ-oyaNCCpcFcmP9PtHFVE,38433 +tensorflow/include/xla/service/metrics_hook_interface.h,sha256=jtHlXkcReGWEtiZJmo5yhsa690q3UjX9URMZwKymqkI,2474 +tensorflow/include/xla/service/name_uniquer.h,sha256=_vbkftHufcujlKXjvCjX0kTbEH6eU0E4NO75tns7iSk,2986 +tensorflow/include/xla/service/op_expander_pass.h,sha256=YSILRbN0J3BOALYs8RJybeM_698bUz8sz4hWvmOrjWI,2083 +tensorflow/include/xla/service/operand_upcaster.h,sha256=rxeyoAzTUZX43TougnV7B_Dcl49dGUbnUzgxbqlv3QI,1445 +tensorflow/include/xla/service/optimization_barrier_expander.h,sha256=oRuWxJ8x1hmvvhjoq3c8PlWSrvE9nqQg_6Iy3O_8dKw,1357 +tensorflow/include/xla/service/p2p_schedule_preparation.h,sha256=ljGEomJRTg90GR35okubc5YKQOEQ6dbr0GBOwm1aP8k,8566 +tensorflow/include/xla/service/pattern_matcher.h,sha256=t2CNRpP6gQ7OCXhUZMNkfiMaOsQ6292orcbk0zuDe_w,107356 +tensorflow/include/xla/service/platform_util.h,sha256=0r6rt4bctrBlwwYtSs4Lt9iitSaGJPLjeoQnAr3l92k,2913 +tensorflow/include/xla/service/profile_guided_latency_estimator.h,sha256=BbriwdtTekzSI8qLsSiEXgmGDmiSsQzmCRFWyY_N8Ec,2255 +tensorflow/include/xla/service/qr_expander.h,sha256=po3VRtntux93ReiCJ3fq-oRbXf9RaN-CK_SvQWLhFOE,2017 +tensorflow/include/xla/service/real_imag_expander.h,sha256=FvmKmp6Vo54ipFFqQ2GixmY7tfkqj-O7l-cLFPaW3n0,1235 +tensorflow/include/xla/service/reduce_decomposer.h,sha256=mMMsZejg03JpBq-Um8iT7TPtv1N_JZI0tGe_ijm0TUI,2481 +tensorflow/include/xla/service/reduce_scatter_combiner.h,sha256=EZcXaSfLCLsqvA_5NBzPct_e-lSg6J3hMtJjIo-8d9o,1864 +tensorflow/include/xla/service/reduce_scatter_decomposer.h,sha256=Vb2WeizkjlkB67_Zxpq223-PHFGWTrf0itrEhg8Rdgc,1580 +tensorflow/include/xla/service/reduce_scatter_reassociate.h,sha256=VpZglkHYyqGiXpAg0yTAyqC6gfPG6gQPr1W5AeTl2_s,1546 +tensorflow/include/xla/service/rendezvous.h,sha256=QkFArpeTS_kEJ5Gw6_4V4RjVdSHUv4RANNZVQNtONac,5144 +tensorflow/include/xla/service/reshape_decomposer.h,sha256=oQNOTQS33mFT_g1os_Q4DAmdBI7s58hJaeTiXLV89Kw,1460 +tensorflow/include/xla/service/reshape_mover.h,sha256=ZFCSsWipQValuXgqD5XA9AHphBQRCDAcmTqgiMYrMIY,2766 +tensorflow/include/xla/service/result_caster.h,sha256=Q3DgYrq0KT7-AZvkzvkZMj9qd7wO9mZhatKa_w9z4Ag,1545 +tensorflow/include/xla/service/rng_bit_generator_expander.h,sha256=WB9dETTYWC7VS_RTJpzVj9IrPyaTfBiRHav6Axl84Rg,2576 +tensorflow/include/xla/service/rng_expander.h,sha256=v6iGkC3EStSxEVv7fSDUg9CkxV-3F26GUg1XkGtZ3Bw,1428 +tensorflow/include/xla/service/scatter_expander.h,sha256=mPVa2YOQEbPOdJMuM92bZKPNI0_7qs4N2FmSUzbF8E0,2430 +tensorflow/include/xla/service/scatter_simplifier.h,sha256=WHOjzzS0PJApBHtYILGDFmWOwFf24LRMKhdt_JH43CY,2037 +tensorflow/include/xla/service/select_and_scatter_expander.h,sha256=tbJmV_3lApiDn8b8LvGkoFctGyx-u3agsDgKyZvGdgE,1419 +tensorflow/include/xla/service/service.h,sha256=f8g5hX41MZgH640l1BgUMy6D0W-yl9ve0uLbcYhNQKQ,14185 +tensorflow/include/xla/service/service_executable_run_options.h,sha256=aXEX-bzNMJfANw7FbpzzBu_--aHybNcUwvmxE0jHf-s,3446 +tensorflow/include/xla/service/shape_inference.h,sha256=hS-FNPxWpZLRuCsRQW-DB6Ai_C8y1c-I5_ex4D9JiXA,21303 +tensorflow/include/xla/service/shaped_buffer.h,sha256=z0hBjkl25NJEUPZlIdGWpTlB-yMgOeqdemW1qeK4QgA,7990 +tensorflow/include/xla/service/sharding_propagation.h,sha256=xVKLboZUjuUMwXq5mayzLEoK0e0_QvYm1-W17QqSTzc,7428 +tensorflow/include/xla/service/sharding_remover.h,sha256=4Ztsesdmk8C46JuEliU5f3b2hPPPCTJjh4zaqu0LEU4,1398 +tensorflow/include/xla/service/simplify_fp_conversions.h,sha256=8XFErqu-TahWcs2NOnHeWCu1mHySeITFVajqm0H1aW4,2062 +tensorflow/include/xla/service/slice_sinker.h,sha256=ljNpHJSOOX1wCwwqEuynzg1rkf2GbbjIp7cQK9gqIWc,1286 +tensorflow/include/xla/service/slow_operation_alarm.h,sha256=cptBsK9AwyQx9Uloxszw8aq2YtJxSqgDcEx4m0J9kdw,3472 +tensorflow/include/xla/service/sort_simplifier.h,sha256=2EFU1dJaNNGmAlnZbWfkNkdS3cH7IJvk2SzuH6YbkzE,1380 +tensorflow/include/xla/service/source_map_util.h,sha256=KWZAkZVnnXGF2k0mMNfmu7e6Ioe8W5GKeLgH9IWAe7s,2551 +tensorflow/include/xla/service/sparse_util.h,sha256=l6dmcojC_1P3yectWwkDsLg8VivN09s95wKxzD-37tk,1204 +tensorflow/include/xla/service/spmd/collective_permute_motion.h,sha256=NnKSzKO-BWv5jekllgXV0Gg04OuS85BcEMB5yjJN5Zs,1453 +tensorflow/include/xla/service/spmd/convolution_handler.h,sha256=0CJlOp2Ft4vrnQzOyo_PIj7BRntTYpjJaOhX34pxQPo,1786 +tensorflow/include/xla/service/spmd/custom_call_handler.h,sha256=Dc71BlEl6NRCDjh5oVfxGTJeQrqfNMsvJsGYCQw9l5s,1224 +tensorflow/include/xla/service/spmd/spmd_partitioner.h,sha256=zCq2cNHIhpSkczg0vIgOGUq2VmQDMwoLZXYOSf0V3WI,27282 +tensorflow/include/xla/service/spmd/spmd_partitioner_util.h,sha256=JUq2JDID7tytftH_F-4Ry4oDDS9QR42iugLz5QkV36U,26379 +tensorflow/include/xla/service/spmd/stateful_rng_spmd_partitioner.h,sha256=UbJrVjSCuJd8BmNEniCakFMyxVosOu4QBp-ysWw1d9k,3189 +tensorflow/include/xla/service/stable_sort_expander.h,sha256=_Z6qpmJM0TqmazQuvsL6Z7aQvldsXuovLdbV-O7dtAk,1527 +tensorflow/include/xla/service/stochastic_convert_decomposer.h,sha256=o2d-VjnaqNhJtQ9E1qlUQAUrF-c7vEn5GPXVsgWhW2Y,1384 +tensorflow/include/xla/service/stream_pool.h,sha256=FF8ANpsEQVUT_u8uRCJvNomQkjnrEoyj8gRyRAvpoxQ,2274 +tensorflow/include/xla/service/topk_rewriter.h,sha256=AxD5lYyMr9DvuSx3r2ORnLZuiTAK2yGarvy9rHkvkz4,2784 +tensorflow/include/xla/service/transfer_manager.h,sha256=paMQXqqIVAwBk1AkyorLVq3g9gO6TO6_BoA0nsfeGQA,15229 +tensorflow/include/xla/service/transpose_folding.h,sha256=bbEWjQGDpwA8UTSOLWXwyxk3-0fO5qPnxuRnOG5gx50,2966 +tensorflow/include/xla/service/tree_reduction_rewriter.h,sha256=u8EImyJiPqMV5fC07HiDhsbNIXP6DVTIzuseFGCvScw,2334 +tensorflow/include/xla/service/triangular_solve_expander.h,sha256=NK_PeLZ8AGmSonqDYPQ9s35Dg9IpgYvZcOd_Jagtdlo,2953 +tensorflow/include/xla/service/tuple_points_to_analysis.h,sha256=cUTQu76BboJyJg8TE6vKrVdv_Mp-lF9NYQETbRf1i1o,15110 +tensorflow/include/xla/service/tuple_simplifier.h,sha256=hw_oeZhm-MelJ1yBSpBjIBA7Xprwx55-dS4fEvbRH-g,2211 +tensorflow/include/xla/service/tuple_util.h,sha256=MmGqcVxpOUNhDKAk5PAPd_Uw6uYwJxOiVHBNIo99h5c,2798 +tensorflow/include/xla/service/value_range.h,sha256=7QRpka91GdXT1vCVv5nb-Ylxe3LTctrDCmmcoxC47qQ,3001 +tensorflow/include/xla/service/while_loop_all_reduce_code_motion.h,sha256=4ajhLVo0ME6c_7Zg0ZHreg-fRUp2_1fa0sR2LsKkCXk,2082 +tensorflow/include/xla/service/while_loop_analysis.h,sha256=T5rd9Xfs8Sdjlp1AOZ_hnlIjR0G1izBzyWNv2LSTuOI,2629 +tensorflow/include/xla/service/while_loop_constant_sinking.h,sha256=Z3GZqLzGEb0l_QrG50h-5rRvu80KeSLQKo1qjEbNJFk,2297 +tensorflow/include/xla/service/while_loop_invariant_code_motion.h,sha256=QUf2GpiMIV8i8_WqV6VxY0J5h3WA9Gm9fXg5M-1LMWI,3880 +tensorflow/include/xla/service/while_loop_simplifier.h,sha256=alX4EMUCO8QbIPNwYRzkKaQtOYWh5pUPdtg83zDrSGA,2102 +tensorflow/include/xla/service/while_loop_trip_count_annotator.h,sha256=S10A_GT0NZurHh_jgZcbF2WzluEY5ZR1KKEAjR7a2hY,1954 +tensorflow/include/xla/service/while_util.h,sha256=hIdOUdDqHyG4rTtJjGgEXGhzTXAhKtsmrW5kleonUsA,4896 +tensorflow/include/xla/service/xla_debug_info_manager.h,sha256=L0NaD0IYITnD62ci9Zmwd02ZD-gHX1lKdADIDNS7nIE,3077 +tensorflow/include/xla/service/zero_sized_hlo_elimination.h,sha256=gLz7bzfuYeJAmJYyUGLU91FxT-kQf92KXRIMNoCk1z0,1333 +tensorflow/include/xla/service_interface.h,sha256=nQeZkPH1XE_npRufFWzXR_JRzr12-R9BKTG8hLy4x7M,3541 +tensorflow/include/xla/shape.h,sha256=9xsj3GON6gDC0-JsCPzEwlADdREURt_xUeKvnACLg7I,14026 +tensorflow/include/xla/shape_layout.h,sha256=tmhzI82mhjWUwRTDgHDDVHIKMj-FZh3bnUTlzFrQsP0,4074 +tensorflow/include/xla/shape_tree.h,sha256=MPB90j58ZzPCfTXcqMNty7DFZ1jIGPVPPK-naqMM1Go,15949 +tensorflow/include/xla/shape_util.h,sha256=kN1t4RmbDCTct7GvAVdi8GofH0N_2DD7BO-N3bk6rIA,44424 +tensorflow/include/xla/sharding_op_util.h,sha256=CNnz2vNDNQ20xUOz2msSkFxxD8tq7bz2hffdss8guK8,1394 +tensorflow/include/xla/side_effect_util.h,sha256=2y-niBvzYUzSwLzQ18D0zU2b0oc2TvQJ970j1t9XIf0,2694 +tensorflow/include/xla/status.h,sha256=NV4bccFd-ZXoJmfcm50f0lgiZbslxDIk9oR3UZ6342E,978 +tensorflow/include/xla/status_macros.h,sha256=lyn-S1D2tvyUcLYc00YWRsA2rA0nKtm72la8kuFIAqc,7194 +tensorflow/include/xla/statusor.h,sha256=ppOP-8znGzlgblBbrlS4sV8WZ-20FCQwvD5UftKCvm0,951 +tensorflow/include/xla/stream_executor/allocator_stats.h,sha256=kUQVnJi5guZoupLuTMf7j33tDYKFhTKPaqLs6m0fsEQ,2261 +tensorflow/include/xla/stream_executor/blas.h,sha256=X5mWSGXHZzTD6CsHXrTQebQ8_KtzTK0seZ961CinFf4,40395 +tensorflow/include/xla/stream_executor/command_buffer.h,sha256=CLHuMjWYPl0bVMp4nxY2C2IARdLyJgLlXibNmSqkR7E,6290 +tensorflow/include/xla/stream_executor/cuda/cuda_activation.h,sha256=71Ac5raPYeTj1H3ffTis5RGbRbbGxBN7Fl5Hj1kuCmI,1371 +tensorflow/include/xla/stream_executor/cuda/cuda_blas.h,sha256=T41m9Ho0xK92KNzN5x4ksxg6VGQ_YnMpgA9ZH2qV4B0,4808 +tensorflow/include/xla/stream_executor/cuda/cuda_blas_lt.h,sha256=TS3S9k6CWKZaGX1iPHN8q6R0qZGMKhio4FO-BbSgOSA,9599 +tensorflow/include/xla/stream_executor/cuda/cuda_blas_utils.h,sha256=eR-b9mz1freFjv0q86sI5HeSpEerNtFa6TO26B0_tsE,1524 +tensorflow/include/xla/stream_executor/cuda/cuda_diagnostics.h,sha256=SsJJtwXAQ866msEkrCTxedn6yXxZQ4XH-o5tJTs6YnY,1526 +tensorflow/include/xla/stream_executor/cuda/cuda_dnn.h,sha256=NWOllW0lskDbVh7mlPGTzF7aylpT4Ps9TzvTJJHpskg,40808 +tensorflow/include/xla/stream_executor/cuda/cuda_driver.h,sha256=Ti8gIWVKa212VCsSJn80oK5iG8syVtMhmXQK9Xn9cZU,5713 +tensorflow/include/xla/stream_executor/cuda/cuda_event.h,sha256=oYrkwQNS2BAm0KHjoEJqqMJk4oPLHoY-Wx6zXXQNfnQ,997 +tensorflow/include/xla/stream_executor/cuda/cuda_fft.h,sha256=JE1XZCwdoUw617P5xhEuARqmEAEAHP6UreeY2pB3Y4o,5123 +tensorflow/include/xla/stream_executor/cuda/cuda_helpers.h,sha256=FSU5iUonxXfRupFGu95F_Zn5ipJumMIL2f71ZMJSGgE,1064 +tensorflow/include/xla/stream_executor/cuda/cuda_kernel.h,sha256=bBTCpRjfY-Hsz2B3RL2cWevwnJESD8OxNm3SEMDhklU,1377 +tensorflow/include/xla/stream_executor/cuda/cuda_platform_id.h,sha256=nUeQeM-t_hXauvWwqmuLbNdMiB2DIhPJQisfW8BRbZc,1293 +tensorflow/include/xla/stream_executor/cuda/cuda_stream.h,sha256=q6eL8rSMsVMI3cWTxcs7jOvVnBWG_kZEZJYGVQVnAaQ,1208 +tensorflow/include/xla/stream_executor/data_type.h,sha256=F5AJ_lTQ7RvgG20s7DJOxXOijMmwZ1wancOAnVjI5ms,2681 +tensorflow/include/xla/stream_executor/device_description.h,sha256=9CzzceYF5EvTJXGTYReHztB8knIO_K4f24W38NVbS1Y,19231 +tensorflow/include/xla/stream_executor/device_description.pb.h,sha256=KukWeJhzyF-cFC-Xgmygdg6LUc2KmsETJkKXj69hsTQ,86739 +tensorflow/include/xla/stream_executor/device_host_allocator.h,sha256=aCPL_1uZeyMLlOTB8xXxDbFs7C5538epuwDVsDoV_Og,2920 +tensorflow/include/xla/stream_executor/device_id_utils.h,sha256=lcOOhGLUTo-kqZ8SPl1gS8fFv-bqYT-_8yBxl4oj3Tw,1813 +tensorflow/include/xla/stream_executor/device_mem_allocator.h,sha256=M1hwCV87Rp_ALdU74Nan-XnYqniY-vzaSexpTHmQydc,3297 +tensorflow/include/xla/stream_executor/device_memory.h,sha256=QDQ3svn75nCCllvmBZIHmx_rkpEXENW5-nYfYeNzm-k,7679 +tensorflow/include/xla/stream_executor/device_memory_allocator.h,sha256=ruzfcKUg4Zcx-0ntAdbag0ifxtiSKxYWUMt5Tr2cZl8,11661 +tensorflow/include/xla/stream_executor/device_options.h,sha256=dvCowu-OlJzVv1nleQuKMTJlXRCTgSTNlMwyATLI52U,3678 +tensorflow/include/xla/stream_executor/dnn.h,sha256=VoGZ6ARezF8p6SwMvpuw8EdsG40_szWSX53j5RU3TVQ,115667 +tensorflow/include/xla/stream_executor/event.h,sha256=DpPUSmzQarFY5cYGDlqgX29YPaoNOgmZXxIBejtlBPQ,2808 +tensorflow/include/xla/stream_executor/executor_cache.h,sha256=NcBCNK8b3hebNcvypGs3lbVs2BMF9y5tKltL7Usc2FA,3360 +tensorflow/include/xla/stream_executor/fft.h,sha256=8AbrMSE1Oc6jT_hd6yawg6uJvbwHgxnU8GFL5zi9Q-g,13616 +tensorflow/include/xla/stream_executor/gpu/asm_compiler.h,sha256=csKIc_92XW4K8TTi20jVVAbZdnj0paXHbq_20NJFESM,5642 +tensorflow/include/xla/stream_executor/gpu/gpu_activation.h,sha256=eJU57xexZx1wUS06_z6oKCt2UKYwPDeiDtBgSpzjpos,2044 +tensorflow/include/xla/stream_executor/gpu/gpu_asm_opts.h,sha256=cL6VJulOKzHLDBrSz0y0P6m2B4qmSkxAy0Tcs7SvAuY,1894 +tensorflow/include/xla/stream_executor/gpu/gpu_command_buffer.h,sha256=d1wXOcTlKl8hEDFZnS6c83uJsgYMQ1eWn2zk6n1dKPM,4519 +tensorflow/include/xla/stream_executor/gpu/gpu_cudamallocasync_allocator.h,sha256=Rx6sFOmnLTkBse1EY-gd8022goNQwiFYCFmtBQ49ErQ,5556 +tensorflow/include/xla/stream_executor/gpu/gpu_diagnostics.h,sha256=Hjd7k4ZakLXqOwxjUE0vp8cZinWi8Oj85LVgRyxynKE,3850 +tensorflow/include/xla/stream_executor/gpu/gpu_driver.h,sha256=dXc0livU-6Iz1sugWwzzNv1Z44ZtOoonz7okCYLGjqo,43887 +tensorflow/include/xla/stream_executor/gpu/gpu_event.h,sha256=OIQ3RiewEZj_CnyeMZSW_0byoqObhlYGQm2DcXPw9rA,2023 +tensorflow/include/xla/stream_executor/gpu/gpu_executor.h,sha256=gpYoa2KhYAyDG1otVkfhlTeYI_APL1-yjXz6PaqzNVw,15111 +tensorflow/include/xla/stream_executor/gpu/gpu_graph.h,sha256=B9lt9ZDvP2E1FzJE5mf7Ty9VLGo7K-hIIEa63Q1oK3U,4919 +tensorflow/include/xla/stream_executor/gpu/gpu_helpers.h,sha256=ZTteRvbZez0c9D2v0v2MvPp6mb_c5ZfE5N_6hqvWNh4,3716 +tensorflow/include/xla/stream_executor/gpu/gpu_init.h,sha256=dfsCLDyg0oXTp25vxTd54laUoZlaQGWijqcQhR2g0sM,1563 +tensorflow/include/xla/stream_executor/gpu/gpu_kernel.h,sha256=F1lL13jf35HPjK8dEdEzUIh4F0RMRmOpbRI4J3gtUP0,4351 +tensorflow/include/xla/stream_executor/gpu/gpu_stream.h,sha256=1gsJHfBKcwd8CvpKiRAzWsFSwyuLvg40OD8oMx57PxM,3754 +tensorflow/include/xla/stream_executor/gpu/gpu_timer.h,sha256=VOg_3wpXeNWUndFjYwg_OJipW96Dz7Io0goYtHP-raQ,2515 +tensorflow/include/xla/stream_executor/gpu/gpu_types.h,sha256=9h4QFzW2Fy-mfmfSjRwjJkUKIrPzL6WIFoq8DDgm-Wk,2785 +tensorflow/include/xla/stream_executor/gpu/redzone_allocator.h,sha256=LCgovchlOxEw4qOwpC1UoS4gaK8PhquaLaFtm2dlwjs,5173 +tensorflow/include/xla/stream_executor/host/host_gpu_executor.h,sha256=IRmdHluYPXi5pTX8EL6H3sNeE9fKMGS-MHdR4xmpP28,6811 +tensorflow/include/xla/stream_executor/host/host_platform.h,sha256=2hVLIN2vXyH79yWW3wlOAUtgWYHSPYyNmquSSORbfnQ,2595 +tensorflow/include/xla/stream_executor/host/host_platform_id.h,sha256=MojYoZKgbInOpKUj-iRU1xwqLMAjMYKr8END7yVBK5M,1299 +tensorflow/include/xla/stream_executor/host/host_stream.h,sha256=Bf0tWvSAltcgjB_t9ZZaO7tif_4eAzA2n9gB5elFoLk,2373 +tensorflow/include/xla/stream_executor/host_or_device_scalar.h,sha256=ZAD3Q3OtezVgN3plCoXT5PLYh1H4OiXfiXkth2FZMPQ,1663 +tensorflow/include/xla/stream_executor/kernel.h,sha256=ReIFFbdKTrDmDN_3JWK6ZTj0xE1YY1-Q47kGjPWmPjc,27996 +tensorflow/include/xla/stream_executor/kernel_cache_config.h,sha256=qjwJ2P-Tk5xjTdeWSyOseeKXhK4gl8_wDZdO0ZzPcCQ,1600 +tensorflow/include/xla/stream_executor/kernel_spec.h,sha256=ArhliHqhIcobv3IhgKMzfJFX0FTiuIA12BIlDxWJ7-8,12739 +tensorflow/include/xla/stream_executor/launch_dim.h,sha256=Sjn56PA7zTv7TgVeSDP5cuiEfyInAl-zU5wwWUVblNA,2756 +tensorflow/include/xla/stream_executor/lazy_op_runner.h,sha256=l3VUk0TWjewcYc8x2SrXWfeGKNVDkoRe8m7NqKDlVMU,11674 +tensorflow/include/xla/stream_executor/module_spec.h,sha256=ctInyxQiN4_2jQe7uDve1LAALHmHYshvujU9rZXwGUU,3102 +tensorflow/include/xla/stream_executor/multi_platform_manager.h,sha256=m079ar3MtMDgO_6WlQzQRG52q_BQRfl7A7A1T9wNcnY,7080 +tensorflow/include/xla/stream_executor/numeric_options.h,sha256=KEy9yAht6V4cvfH44CBp_kcUdooKdnWIFEvbr-UzDJM,1381 +tensorflow/include/xla/stream_executor/platform.h,sha256=Kh6cuWAbY5kMEB6Mp9GXLXMHLMf7MMHtHrZZyK2fjgI,6263 +tensorflow/include/xla/stream_executor/platform/default/dso_loader.h,sha256=0fMC5fgl4TNIY87yFd2zkmmoNNrlbNk9hqxIIlxUIPg,3818 +tensorflow/include/xla/stream_executor/platform/default/initialize.h,sha256=RN42FG2SUNi1FLgYk0grTByJiX0O3hNl05BUzCD7kCg,2186 +tensorflow/include/xla/stream_executor/platform/dso_loader.h,sha256=v0MHqWXjN532fsPvoyq3NGFkGE_ORa6CwYpctU2gF8c,1338 +tensorflow/include/xla/stream_executor/platform/initialize.h,sha256=FAZskWbAI5TN1V7jceT1dy6qIa93mN2FluE_kg14Auw,1123 +tensorflow/include/xla/stream_executor/platform/platform.h,sha256=abWdY8J5tSTe4eBaD8oFCcJwPezD-ELexLXth3PkglI,1395 +tensorflow/include/xla/stream_executor/platform/port.h,sha256=djnS48_b3pCUrqwM75fS8MR9wsTF6PjricP57hv3fq8,1543 +tensorflow/include/xla/stream_executor/plugin.h,sha256=jcajSIoE7dDWj4ZqMu4sEANxIiyQPahuo6SyUXQoIqQ,990 +tensorflow/include/xla/stream_executor/plugin_registry.h,sha256=fVfAqV45Np-ADNXk3KcmVGh10HazP_sRQ-RbEYytMdM,5045 +tensorflow/include/xla/stream_executor/rocm/rocm_platform_id.h,sha256=w9kki-rI14GHw1i_gf7mSD3904YKBdZJxlb7F7oHKCc,1293 +tensorflow/include/xla/stream_executor/scratch_allocator.h,sha256=Cbo0KLCv9yh8Bo378sOkjtc7Bfv6elR3CklaON2SjCI,4253 +tensorflow/include/xla/stream_executor/stream.h,sha256=erzL073QdzPYEFVvRhnSHWAheqPF4QpGiRTZO5BO9UY,77983 +tensorflow/include/xla/stream_executor/stream_executor.h,sha256=qCd3wgOWG7HMkrpajF33nYN9Tn0LMZDQjAg_e4xstg4,1782 +tensorflow/include/xla/stream_executor/stream_executor_internal.h,sha256=Mqhk5m1n03spUUWHoo_-Tn60TPJAJQNY_1J0WncpRgs,18788 +tensorflow/include/xla/stream_executor/stream_executor_pimpl.h,sha256=q_FM_maI7JgPpnj4RB_gsKKnlU1c3wrpspyRZ42JO_c,32482 +tensorflow/include/xla/stream_executor/temporary_device_memory.h,sha256=J5QLu0GGjlaH4OTaNbPPRb_aOBto6y0HvEQHI50AFvo,5178 +tensorflow/include/xla/stream_executor/temporary_memory_manager.h,sha256=4RBeeKvJYsbhTDC0Gretu8y35cvrcLicRS0d_6_fjnw,6032 +tensorflow/include/xla/stream_executor/tf_allocator_adapter.h,sha256=409RKrZ1GX5GqwfEPeTNeFd9tckeODwfArIDQWxWWg4,6732 +tensorflow/include/xla/stream_executor/tpu/c_api_conversions.h,sha256=lpn_IrXaGnV7UnJt4B5OOxPLxLW5wwJcy9NxfDnravA,5604 +tensorflow/include/xla/stream_executor/tpu/c_api_decl.h,sha256=NO1uqNKd60PxX5jUrIL1-J-1udUuWBqNddz_iYcuGY4,9141 +tensorflow/include/xla/stream_executor/tpu/c_api_defn.h,sha256=uDAQ-kKNYzH3USCfFqNRjvOOifjlgiHppQ3RR1jWHtw,2036 +tensorflow/include/xla/stream_executor/tpu/libtftpu.h,sha256=bDi__hvi3fBtZ6IwliYW11-6lB91NSGNff9QSibDYB8,1778 +tensorflow/include/xla/stream_executor/tpu/proto_helper.h,sha256=GYw5frdQ5W7W5F40PJ9_gmKTBhLfgQDGkAUOcSPUxJU,2879 +tensorflow/include/xla/stream_executor/tpu/tpu_api.h,sha256=catw2De8aTyAABJ7UuWk-oleZtSWQRvOxyW1MM2Lx-4,1223 +tensorflow/include/xla/stream_executor/tpu/tpu_executor_api.h,sha256=iS2BIlNoIt2ZccyskHcZLdCRMEzqDpk1-XeHGxZOPfA,1460 +tensorflow/include/xla/stream_executor/tpu/tpu_executor_c_api.h,sha256=6eY9EjGZDywd0WSHFMti0TAssjmUNOP5AspQihVy6ow,27674 +tensorflow/include/xla/stream_executor/tpu/tpu_ops_c_api.h,sha256=KapVDtZHF69H22Ij_AhxEHCS64_-FEGhnM7OFtQLR9E,30138 +tensorflow/include/xla/stream_executor/tpu/tpu_profiler_c_api.h,sha256=UbvF4VgoWzkZu98xs_GFjNg4SToxoeV_BtkFD7LUsz8,3404 +tensorflow/include/xla/stream_executor/trace_listener.h,sha256=okIWx4orApKAF0_yQX5TS1O5Axw-KsT_AsFzqcX7DUc,3330 +tensorflow/include/xla/translate/hlo_to_mhlo/attribute_importer.h,sha256=0nEVi7zBAmJIQW32aQVBeE05CdfX4_Xsw-ZLdcoqRVc,3314 +tensorflow/include/xla/translate/hlo_to_mhlo/hlo_function_importer.h,sha256=_8m1zzhsIq2_qSlOSyw3XCK9bgZCZvuDT8CpWm50XpM,13584 +tensorflow/include/xla/translate/hlo_to_mhlo/hlo_module_importer.h,sha256=qPUhcRykkIZvfnPZQHTWuVOA1yvZ40Ecb8J2LE1F_Yg,2429 +tensorflow/include/xla/translate/hlo_to_mhlo/hlo_to_mlir_hlo.h,sha256=Aqjik9hL4A5sELREc03uoaT2W4g2UDHpDG0D-_kif2M,1708 +tensorflow/include/xla/translate/hlo_to_mhlo/hlo_utils.h,sha256=fCa5wG1KLOUICQuO57XyPdfbcO2I57x3bu0JZWGHx4Y,7225 +tensorflow/include/xla/translate/hlo_to_mhlo/location_importer.h,sha256=Toi-gr1uAaVMLhEIls3t6_K8w1a4eXzO1wnAinO_KjM,1250 +tensorflow/include/xla/translate/hlo_to_mhlo/stack_location_utils.h,sha256=S1xkgsTeDjP-4qq0tnvaFM6yK6p0t0fW8KDl2KGEF08,1355 +tensorflow/include/xla/translate/mhlo_to_hlo/attribute_exporter.h,sha256=GcFavRI7Qzn-vOJRQ7mFHulSOdl7Labg2L_pLWtbkNA,3084 +tensorflow/include/xla/translate/mhlo_to_hlo/layout_util.h,sha256=zh5HeuwAab4E4R-RhKFX27fAFOXJR60J2_MtuA8VONE,3460 +tensorflow/include/xla/translate/mhlo_to_hlo/location_exporter.h,sha256=fAKB50bukJRdyBeSwv_5885JQZieHArYLHTxxMu9rxc,1773 +tensorflow/include/xla/translate/mhlo_to_hlo/mlir_hlo_to_hlo.h,sha256=W6nFH68Mv6PUePw-9dBOegl_NZpmT1wjoKD6J0QVZI8,3237 +tensorflow/include/xla/translate/mhlo_to_hlo/stack_frame_index_builder.h,sha256=waLMNYiS8NPK6_dl8wlCoJF8iDklZ6yOj2NwpfP6G98,1639 +tensorflow/include/xla/translate/mhlo_to_hlo/type_to_shape.h,sha256=ieXLgSMhzR3M1cR5e6pMtEigZp6TI8P4VGmLpfInfr8,1313 +tensorflow/include/xla/translate/mhlo_to_lhlo_with_xla/mhlo_to_lhlo_with_xla.h,sha256=0nBbMq0X08A5oODt_s7qFo1GP642o-odmIgoNpTZJjc,15229 +tensorflow/include/xla/types.h,sha256=RcIy6e44QZ4ligx03Who8KfZpvsVgcHAokcRJQlC4qw,3247 +tensorflow/include/xla/union_find.h,sha256=Z-QnjH0VGPs1Sak6lnrnwrhdOzsBdNk2X3Mj3a89P2c,2334 +tensorflow/include/xla/util.h,sha256=xd562y-31bY37mnxEg-D9Kv-zzSAG4YcY7gG0HGd7N0,28258 +tensorflow/include/xla/window_util.h,sha256=9aMN3_cV458RhLH4Vnl7qZI9ysrXqOsSfNLUFsM2kyY,3979 +tensorflow/include/xla/xla.pb.h,sha256=2LX5dK1l7t4I4CcbEBq5t9JZnicmirNO9DgmCSOATT0,887834 +tensorflow/include/xla/xla_data.pb.h,sha256=gbhVPAIMmZG5xT_n-3wiT7KN788fTHsh9VxpuN5exJc,526440 +tensorflow/libtensorflow_cc.so.2,sha256=NJM6jEGnU1CpeoQTMXtuO0XBKDtC_fNdjOo7GYmm5V8,977852928 +tensorflow/libtensorflow_framework.so.2,sha256=k4Dgg7pkyM2pGl4JzAZi0pyHIracU13xPKVlwuv9MCY,51968272 +tensorflow/lite/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/lite/__pycache__/__init__.cpython-310.pyc,, +tensorflow/lite/experimental/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/lite/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/lite/experimental/microfrontend/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/lite/experimental/microfrontend/__pycache__/__init__.cpython-310.pyc,, +tensorflow/lite/experimental/microfrontend/ops/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/lite/experimental/microfrontend/ops/__pycache__/__init__.cpython-310.pyc,, +tensorflow/lite/experimental/microfrontend/ops/__pycache__/gen_audio_microfrontend_op.cpython-310.pyc,, +tensorflow/lite/experimental/microfrontend/ops/gen_audio_microfrontend_op.py,sha256=sFiYoJShssB4FbLsfNYjKteZO2W6CEazGfZizQmqAzM,21881 +tensorflow/lite/experimental/microfrontend/python/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/lite/experimental/microfrontend/python/__pycache__/__init__.cpython-310.pyc,, +tensorflow/lite/experimental/microfrontend/python/ops/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/lite/experimental/microfrontend/python/ops/__pycache__/__init__.cpython-310.pyc,, +tensorflow/lite/experimental/microfrontend/python/ops/__pycache__/audio_microfrontend_op.cpython-310.pyc,, +tensorflow/lite/experimental/microfrontend/python/ops/_audio_microfrontend_op.so,sha256=FhO8MO11vOzgiRET1_F_p1KTZSK66s1rXo4pJXuZiY4,1196456 +tensorflow/lite/experimental/microfrontend/python/ops/audio_microfrontend_op.py,sha256=ee44DK79kmgABxWY3IATIn9cmQeZHK-IaUX7UF6jbcU,5088 +tensorflow/lite/python/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/lite/python/__pycache__/__init__.cpython-310.pyc,, +tensorflow/lite/python/__pycache__/analyzer.cpython-310.pyc,, +tensorflow/lite/python/__pycache__/conversion_metadata_schema_py_generated.cpython-310.pyc,, +tensorflow/lite/python/__pycache__/convert.cpython-310.pyc,, +tensorflow/lite/python/__pycache__/convert_phase.cpython-310.pyc,, +tensorflow/lite/python/__pycache__/convert_saved_model.cpython-310.pyc,, +tensorflow/lite/python/__pycache__/interpreter.cpython-310.pyc,, +tensorflow/lite/python/__pycache__/lite.cpython-310.pyc,, +tensorflow/lite/python/__pycache__/lite_constants.cpython-310.pyc,, +tensorflow/lite/python/__pycache__/op_hint.cpython-310.pyc,, +tensorflow/lite/python/__pycache__/schema_py_generated.cpython-310.pyc,, +tensorflow/lite/python/__pycache__/schema_util.cpython-310.pyc,, +tensorflow/lite/python/__pycache__/tflite_convert.cpython-310.pyc,, +tensorflow/lite/python/__pycache__/tflite_keras_util.cpython-310.pyc,, +tensorflow/lite/python/__pycache__/util.cpython-310.pyc,, +tensorflow/lite/python/__pycache__/wrap_toco.cpython-310.pyc,, +tensorflow/lite/python/analyzer.py,sha256=9Rux1Qf7ZvCctoqevbznC0HBw6K2BI5FqoHWbmLBpbA,3937 +tensorflow/lite/python/analyzer_wrapper/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/lite/python/analyzer_wrapper/__pycache__/__init__.cpython-310.pyc,, +tensorflow/lite/python/analyzer_wrapper/_pywrap_analyzer_wrapper.pyi,sha256=2hsshuWi4foajY8dOPoLjo5njEsOGVRdAt1-O4ggkSw,755 +tensorflow/lite/python/analyzer_wrapper/_pywrap_analyzer_wrapper.so,sha256=HqTG_anwku_eGFSI-3WiV-Hdf2umXxb4zk9frKSgLqs,2653824 +tensorflow/lite/python/authoring/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/lite/python/authoring/__pycache__/__init__.cpython-310.pyc,, +tensorflow/lite/python/authoring/__pycache__/authoring.cpython-310.pyc,, +tensorflow/lite/python/authoring/authoring.py,sha256=8se02VC-lR5tEh7Ic5mRcLHJKbDEQL8jXgjZbkR887Q,11209 +tensorflow/lite/python/conversion_metadata_schema_py_generated.py,sha256=jW9Eu1uOt03_6oPKKsTGfIbn06eMD4msHwzeyaD77z4,19428 +tensorflow/lite/python/convert.py,sha256=CIjEP0a9OZsePGcPFzivbZL6yD0GMZ5PKs7UlPtNdF8,48666 +tensorflow/lite/python/convert_phase.py,sha256=dkMIBywoSCDqzersZg1g9qmOplU_zcM9vKwJGSbTaJA,8014 +tensorflow/lite/python/convert_saved_model.py,sha256=lUoKyYd_H5lq-e9N6JGBwV-vUyl_jp0xPcAjcLpTY38,7063 +tensorflow/lite/python/interpreter.py,sha256=WdMKqxuFdoGPyOKoCsZsHbvsVQXs_81OrG7VUE8p5JU,38775 +tensorflow/lite/python/interpreter_wrapper/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/lite/python/interpreter_wrapper/__pycache__/__init__.cpython-310.pyc,, +tensorflow/lite/python/interpreter_wrapper/_pywrap_tensorflow_interpreter_wrapper.pyi,sha256=g4raHUangXnSxQ9zWkm1mGGD7a0vha_957nbtJEUjc0,2548 +tensorflow/lite/python/interpreter_wrapper/_pywrap_tensorflow_interpreter_wrapper.so,sha256=sHEpWZoHXDpTIc3G6EQELdBgGNxw3APlwwSHEW20WMc,5813112 +tensorflow/lite/python/lite.py,sha256=XMgCkPcVpmqpH5Hq5YUmalnS14VmrxfIJggIkuqhE9Y,125914 +tensorflow/lite/python/lite_constants.py,sha256=XQ3Nx4XplfGrL9SpvcZ6yqgoUa5j5_SBbCO6HQB-sf4,2729 +tensorflow/lite/python/metrics/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/lite/python/metrics/__pycache__/__init__.cpython-310.pyc,, +tensorflow/lite/python/metrics/__pycache__/converter_error_data_pb2.cpython-310.pyc,, +tensorflow/lite/python/metrics/__pycache__/metrics.cpython-310.pyc,, +tensorflow/lite/python/metrics/__pycache__/metrics_interface.cpython-310.pyc,, +tensorflow/lite/python/metrics/_pywrap_tensorflow_lite_metrics_wrapper.pyi,sha256=AEPz7JErD0CZUTd4nXADewpXRkBjtH0A3KElISORWeA,802 +tensorflow/lite/python/metrics/_pywrap_tensorflow_lite_metrics_wrapper.so,sha256=UrgzmJNkkhDRI-E1--T7iAhHgTEhMctxw39VUeG9E4U,3769112 +tensorflow/lite/python/metrics/converter_error_data_pb2.py,sha256=j3tzf1hYwxjA42vmFwD5V4AwdZ-bvOo1-neUnNYNlxo,3068 +tensorflow/lite/python/metrics/metrics.py,sha256=YBiMNokP9JtoQaUcCRRY1T_iFSZGeWCjr6L0iUR6eY8,2048 +tensorflow/lite/python/metrics/metrics_interface.py,sha256=dVu6SmbnQUntPgE5o6BxHVMyemwli-7F6tDfVMGrlYI,1542 +tensorflow/lite/python/metrics/wrapper/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/lite/python/metrics/wrapper/__pycache__/__init__.cpython-310.pyc,, +tensorflow/lite/python/metrics/wrapper/__pycache__/metrics_wrapper.cpython-310.pyc,, +tensorflow/lite/python/metrics/wrapper/metrics_wrapper.py,sha256=_AUwMsmu1y-btI8GJE9IK3_Pc9DBN2x_eK3iY6JJVUo,1497 +tensorflow/lite/python/op_hint.py,sha256=7l3k1WTFwhBrPyGSo5hrXNKtI7EUamEbAF4zQnmM188,52962 +tensorflow/lite/python/optimize/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/lite/python/optimize/__pycache__/__init__.cpython-310.pyc,, +tensorflow/lite/python/optimize/__pycache__/calibrator.cpython-310.pyc,, +tensorflow/lite/python/optimize/_pywrap_tensorflow_lite_calibration_wrapper.pyi,sha256=zGCFXGoeo8gWV6ojv7CfauDkUeMa4Ak-VwYgQdU6e5w,1599 +tensorflow/lite/python/optimize/_pywrap_tensorflow_lite_calibration_wrapper.so,sha256=okIAvCQXqScANo5iQKhvBgsqFyTd7WdfLQNhh7U0B7Q,5799312 +tensorflow/lite/python/optimize/calibrator.py,sha256=gKqIBhlCbrOpD82lQWJDb7maLh_jl_bJ57l-w33Hxi0,9497 +tensorflow/lite/python/schema_py_generated.py,sha256=6Fhj9cDU3nbALhoDlOx0S5KA5Yf_xIlcSLigKDFPSm4,629922 +tensorflow/lite/python/schema_util.py,sha256=M1LrSqMKK3e3SKsg-98ovSOkWO4-ly91FFu2JI32TZk,1631 +tensorflow/lite/python/tflite_convert.py,sha256=vGB1lXuWgVTID5_qyjOE3uWsZaiU9_P3IsP2m-kPnNA,26390 +tensorflow/lite/python/tflite_keras_util.py,sha256=dBIwmHWVYQmmY4ELsvz873pScyCoz3y3FurZHGa59O0,6682 +tensorflow/lite/python/util.py,sha256=OTE57h5GJVSi-iXgPme-QtHPgUWxBa2fBE3nAnL6A0s,40697 +tensorflow/lite/python/wrap_toco.py,sha256=Ik5EHLjDxXnZYX-7YP4dTcGzw55qDtrs4x9CpDHGxuI,2735 +tensorflow/lite/toco/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/lite/toco/__pycache__/__init__.cpython-310.pyc,, +tensorflow/lite/toco/__pycache__/model_flags_pb2.cpython-310.pyc,, +tensorflow/lite/toco/__pycache__/toco_flags_pb2.cpython-310.pyc,, +tensorflow/lite/toco/__pycache__/types_pb2.cpython-310.pyc,, +tensorflow/lite/toco/logging/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/lite/toco/logging/__pycache__/__init__.cpython-310.pyc,, +tensorflow/lite/toco/logging/__pycache__/gen_html.cpython-310.pyc,, +tensorflow/lite/toco/logging/__pycache__/toco_conversion_log_pb2.cpython-310.pyc,, +tensorflow/lite/toco/logging/gen_html.py,sha256=wvMhAXZxTVuQOylzFUo0YhgD57DFL3J49NZxmwI79IQ,11025 +tensorflow/lite/toco/logging/toco_conversion_log_pb2.py,sha256=lBEydu5Ou9aU6lWUz6hA-aYauomZKFyi0cR9vLsxWSI,2755 +tensorflow/lite/toco/model_flags_pb2.py,sha256=5Jzca4e7TMKjksM9Yf5kEM9gUUr3NCs6VOnNmuSWDr0,3946 +tensorflow/lite/toco/python/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/lite/toco/python/__pycache__/__init__.cpython-310.pyc,, +tensorflow/lite/toco/python/__pycache__/toco_from_protos.cpython-310.pyc,, +tensorflow/lite/toco/python/toco_from_protos.py,sha256=0r3LDN7fmVeF0yru-FEo1CVIC3SvVK0JK2s_9JxRXm0,3063 +tensorflow/lite/toco/toco_flags_pb2.py,sha256=8OjgmsiY7NNhbJiFZZh-QaYNOo90Jh-ukzR4AutXfWw,5631 +tensorflow/lite/toco/types_pb2.py,sha256=BF4dpiEeW-tWHyBS6t_5RbbcfK3zet1iuOWosjbWf3k,1572 +tensorflow/lite/tools/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/lite/tools/__pycache__/__init__.cpython-310.pyc,, +tensorflow/lite/tools/__pycache__/flatbuffer_utils.cpython-310.pyc,, +tensorflow/lite/tools/__pycache__/visualize.cpython-310.pyc,, +tensorflow/lite/tools/flatbuffer_utils.py,sha256=m8o8FeobY2g_0xrSh0TZvGEc5pyPgKcK3Yp8THG-bb0,14357 +tensorflow/lite/tools/optimize/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/lite/tools/optimize/__pycache__/__init__.cpython-310.pyc,, +tensorflow/lite/tools/optimize/debugging/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/lite/tools/optimize/debugging/__pycache__/__init__.cpython-310.pyc,, +tensorflow/lite/tools/optimize/debugging/python/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/lite/tools/optimize/debugging/python/__pycache__/__init__.cpython-310.pyc,, +tensorflow/lite/tools/optimize/debugging/python/__pycache__/debugger.cpython-310.pyc,, +tensorflow/lite/tools/optimize/debugging/python/debugger.py,sha256=9tFFkf5AQNhthPGaI7IDlzhvTQc6cSv6rluQWVPZBeY,23908 +tensorflow/lite/tools/visualize.py,sha256=SbAt7BuiV-R76ED2GPUW6sc57Fma9AGpeTG6TRNzHEw,16805 +tensorflow/python/__init__.py,sha256=BocMbO-4bmotbBd_jmpUkxeTjB6l_xGZiiq7jjXGmhI,1358 +tensorflow/python/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/__pycache__/proto_exports.cpython-310.pyc,, +tensorflow/python/__pycache__/pywrap_mlir.cpython-310.pyc,, +tensorflow/python/__pycache__/pywrap_sanitizers.cpython-310.pyc,, +tensorflow/python/__pycache__/pywrap_tensorflow.cpython-310.pyc,, +tensorflow/python/__pycache__/pywrap_tensorflow_internal.cpython-310.pyc,, +tensorflow/python/__pycache__/pywrap_tfe.cpython-310.pyc,, +tensorflow/python/__pycache__/tf2.cpython-310.pyc,, +tensorflow/python/_pywrap_dtensor_device.so,sha256=ZI_kHomk86900UO5kd-HRqW_OpSCdqtLxHLw1GaFUY0,2153056 +tensorflow/python/_pywrap_mlir.so,sha256=IPsEQUs1XLnlNnARtIoV36Po9HY1YVJVT8x1P6nJHCA,253160 +tensorflow/python/_pywrap_parallel_device.pyi,sha256=yauatdFsUHKsxCHeHVUpCJAFWAMff8z93e69tKnr9H8,763 +tensorflow/python/_pywrap_parallel_device.so,sha256=T3hr40WJYZ5xVdmI8k6SLABjDW319gC06U74IMWgCk0,365896 +tensorflow/python/_pywrap_py_exception_registry.so,sha256=-bkkxlqRGJV8HmMW2jnr6qFL_6Dxh-cWrKGScJpSoYY,2672488 +tensorflow/python/_pywrap_quantize_training.pyi,sha256=0PWhHw-GIjx1NCslW4xAKjBGfuRrt_IyS7tT0KWPV5Q,769 +tensorflow/python/_pywrap_quantize_training.so,sha256=Xjf3AGi-Uilqy9stnUcE-EN-WZvl-dLvUjJGAkQ_ILc,254448 +tensorflow/python/_pywrap_sanitizers.pyi,sha256=1DXapDKNUulb8QIiaWdjtL2Lxr3zQtQvWwTMFDPMKmA,831 +tensorflow/python/_pywrap_sanitizers.so,sha256=qSBNFhA3ms8PGaiU6n88y9pX_QGYcqTCvdQgxMnN2Rs,140896 +tensorflow/python/_pywrap_tensorflow_internal.so,sha256=4LeO8N6Y8ikKM6BOGcOrPOSPsvF6h3xoBWNI-h1jxtU,2145673 +tensorflow/python/_pywrap_tfcompile.pyi,sha256=BU3sOXPGnvP7tL8vExhD41dFa5Y-Vmife4zwYTO4o9k,1083 +tensorflow/python/_pywrap_tfcompile.so,sha256=nP5ns_hZK-7knBonAfq6m405GWuMVnY2uei_q2rOSL8,2675448 +tensorflow/python/_pywrap_tfe.pyi,sha256=9uzrRpV-yBEOv8MkyNBVlfQ8OqexYDaC6R3yBNhWHlE,21451 +tensorflow/python/_pywrap_tfe.so,sha256=v1b6B8iYE27o78YVDHzA7d18n_IoVJYpdtyTsmj3ceM,3492768 +tensorflow/python/_pywrap_toco_api.pyi,sha256=WW10p_2VCJPd-DYnOaBRfRa97ODk9HE2YN1XT80b6YM,1571 +tensorflow/python/_pywrap_toco_api.so,sha256=r4r6ZTwGJSGJcR0z3TnIFgCsz0DsQJW7n4aY_0GLMbA,162696 +tensorflow/python/autograph/__init__.py,sha256=VNVuBmo-98HV8Pi9u13DbF2cwgP9UqJZl_UFVP-2qVQ,2219 +tensorflow/python/autograph/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/autograph/converters/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/autograph/converters/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/autograph/converters/__pycache__/asserts.cpython-310.pyc,, +tensorflow/python/autograph/converters/__pycache__/break_statements.cpython-310.pyc,, +tensorflow/python/autograph/converters/__pycache__/call_trees.cpython-310.pyc,, +tensorflow/python/autograph/converters/__pycache__/conditional_expressions.cpython-310.pyc,, +tensorflow/python/autograph/converters/__pycache__/continue_statements.cpython-310.pyc,, +tensorflow/python/autograph/converters/__pycache__/control_flow.cpython-310.pyc,, +tensorflow/python/autograph/converters/__pycache__/directives.cpython-310.pyc,, +tensorflow/python/autograph/converters/__pycache__/functions.cpython-310.pyc,, +tensorflow/python/autograph/converters/__pycache__/lists.cpython-310.pyc,, +tensorflow/python/autograph/converters/__pycache__/logical_expressions.cpython-310.pyc,, +tensorflow/python/autograph/converters/__pycache__/return_statements.cpython-310.pyc,, +tensorflow/python/autograph/converters/__pycache__/slices.cpython-310.pyc,, +tensorflow/python/autograph/converters/__pycache__/variables.cpython-310.pyc,, +tensorflow/python/autograph/converters/asserts.py,sha256=kDmc8F0299-sW_JSzHnAQoSYftW2o_1lxpjiRyjJ6SA,1691 +tensorflow/python/autograph/converters/break_statements.py,sha256=xgxTmJ6a3de7QNdIt7AFix3UsVrlYybc2hHhMHaGTIw,5755 +tensorflow/python/autograph/converters/call_trees.py,sha256=4SM3iHZK53p4QoJco_GyGelF4Bo-mhF1U5yKYfv8IJg,7328 +tensorflow/python/autograph/converters/conditional_expressions.py,sha256=65UNN9KJCLV0TWEQhhrSPnMgR16sCq534LtkJy1Oumk,1601 +tensorflow/python/autograph/converters/continue_statements.py,sha256=G7mKOHaCEyRIBeDQSjqD5wYZIBx16LYOF99yHR-GAYA,5821 +tensorflow/python/autograph/converters/control_flow.py,sha256=W4Ho0qjjbtUD2Nl7ad-L7UY-38ngW48021nfKi7lsSI,14837 +tensorflow/python/autograph/converters/directives.py,sha256=NcUtrgUdc4ly1evHArgUX3lRceJbsLkRmOIwQnq6VAY,6741 +tensorflow/python/autograph/converters/functions.py,sha256=u0jr3cuViyU3LDLXP5LgZfacpDGUct-evIO2NBwqQQU,5245 +tensorflow/python/autograph/converters/lists.py,sha256=4rnzwLnrqFrWF3Dv1WrIhasogV1c-L2aL_JB-zODczQ,8328 +tensorflow/python/autograph/converters/logical_expressions.py,sha256=PPiZzX5JVMvdatlCA4RJHTN0ZQoqmmzoGMqXZrbC3v0,4381 +tensorflow/python/autograph/converters/return_statements.py,sha256=HZ0MLWJrK8sv01ZsUXplwRG1SANGht52mwn6wq6TEgA,13067 +tensorflow/python/autograph/converters/slices.py,sha256=sbpD7AyBCxZMQ8-2rVN3PUCDICsIzc56rvegpIwwuiU,2745 +tensorflow/python/autograph/converters/variables.py,sha256=LVNUARVhTT9_0KqPhA3JvmUXXRWHlW0Rb6ARfFTYfK8,2806 +tensorflow/python/autograph/core/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/autograph/core/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/autograph/core/__pycache__/ag_ctx.cpython-310.pyc,, +tensorflow/python/autograph/core/__pycache__/config.cpython-310.pyc,, +tensorflow/python/autograph/core/__pycache__/config_lib.cpython-310.pyc,, +tensorflow/python/autograph/core/__pycache__/converter.cpython-310.pyc,, +tensorflow/python/autograph/core/__pycache__/converter_testing.cpython-310.pyc,, +tensorflow/python/autograph/core/__pycache__/function_wrappers.cpython-310.pyc,, +tensorflow/python/autograph/core/__pycache__/unsupported_features_checker.cpython-310.pyc,, +tensorflow/python/autograph/core/ag_ctx.py,sha256=ZbiUxsVJ2es3t0rXD3tMZm7toDYBtuAxpxaAaFsf3Es,3093 +tensorflow/python/autograph/core/config.py,sha256=2cvDIRz5X-STp_W7pNL6mnE-c114wb2nf816W7_4NTA,1911 +tensorflow/python/autograph/core/config_lib.py,sha256=fRC5MGOO-qwh40VGyjATdQwm4x-RoGNsJJUBLeZetPc,1731 +tensorflow/python/autograph/core/converter.py,sha256=7GkLcQD_jAPnIXYgEzabIenZPM-RMYZ0e0NFbRKO84A,10711 +tensorflow/python/autograph/core/converter_testing.py,sha256=DY80A_EiinutNScW7iWG6BZWZIo5jdN6ix3L6sD7acw,4076 +tensorflow/python/autograph/core/function_wrappers.py,sha256=n8IptsZnB5JMSp5JAKL4_1eG3kYPlEjy-67jUfCYatI,4355 +tensorflow/python/autograph/core/unsupported_features_checker.py,sha256=Ux7U2sxISxQ5-KZvoyOr1teIFWeRdqWrMWtR8FGpMC8,2070 +tensorflow/python/autograph/impl/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/autograph/impl/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/autograph/impl/__pycache__/api.cpython-310.pyc,, +tensorflow/python/autograph/impl/__pycache__/conversion.cpython-310.pyc,, +tensorflow/python/autograph/impl/api.py,sha256=c5P0DUMNDJ1XrqWPuyUdgBY1W7neohNVrEe-XGNHdsY,33218 +tensorflow/python/autograph/impl/conversion.py,sha256=ok1-WmPVwX6RPcSl8y691xHHA4a8KAp9VFirffHG6bQ,8086 +tensorflow/python/autograph/impl/testing/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/autograph/impl/testing/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/autograph/impl/testing/pybind_for_testing.pyi,sha256=gR81NRBv_6J_7dY_UmXRnI_7DIGoIB22TFY1zWzdBaw,782 +tensorflow/python/autograph/impl/testing/pybind_for_testing.so,sha256=REONvIlQgldlextdg12JKl8amdZvwtG_c1R6FSs6QXA,1068312 +tensorflow/python/autograph/lang/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/autograph/lang/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/autograph/lang/__pycache__/directives.cpython-310.pyc,, +tensorflow/python/autograph/lang/__pycache__/special_functions.cpython-310.pyc,, +tensorflow/python/autograph/lang/directives.py,sha256=zUnpw5ZMSCp56NbFld3NmsULiOWc1HltTbZrgXrJYGU,3216 +tensorflow/python/autograph/lang/special_functions.py,sha256=nkdNQzIEWFmfm7IBFlJV-F6W4aOpRkRg5bX0wBdqLrE,4511 +tensorflow/python/autograph/operators/__init__.py,sha256=_Hyr3J9o-hTfegmK3TDLv-pBbF4pjSsgFHoPoj4GVcQ,3607 +tensorflow/python/autograph/operators/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/autograph/operators/__pycache__/conditional_expressions.cpython-310.pyc,, +tensorflow/python/autograph/operators/__pycache__/control_flow.cpython-310.pyc,, +tensorflow/python/autograph/operators/__pycache__/data_structures.cpython-310.pyc,, +tensorflow/python/autograph/operators/__pycache__/exceptions.cpython-310.pyc,, +tensorflow/python/autograph/operators/__pycache__/logical.cpython-310.pyc,, +tensorflow/python/autograph/operators/__pycache__/py_builtins.cpython-310.pyc,, +tensorflow/python/autograph/operators/__pycache__/slices.cpython-310.pyc,, +tensorflow/python/autograph/operators/__pycache__/variables.cpython-310.pyc,, +tensorflow/python/autograph/operators/conditional_expressions.py,sha256=MhmwORt5crheFR_PZvKAXjRj0_PU_q19nz_g_ksnCe8,1829 +tensorflow/python/autograph/operators/control_flow.py,sha256=oM7v7IS9r54dX0lfc-ExcH-mO6jn44i507PaxsZCYr4,46554 +tensorflow/python/autograph/operators/data_structures.py,sha256=p6qdohHqhrK7MNJ0I7-uxzWe67dEHB9vFywpTsk2EZo,11744 +tensorflow/python/autograph/operators/exceptions.py,sha256=VSnGuqcjYFcbNu9hBB7s3NTJuoNXA3f6bzvLoVNXfxM,3120 +tensorflow/python/autograph/operators/logical.py,sha256=WygfnikJ6WcgNbpaHz0MWHnydrhJGOdoeMELT7BYCZE,2618 +tensorflow/python/autograph/operators/py_builtins.py,sha256=N59DISkCpMnRp_2VHxoJ0ev5mesQ5icBuvsYmFK-6U0,16785 +tensorflow/python/autograph/operators/slices.py,sha256=og5678jC3NbELW1VIyz6pKmc0liYH05ZcHDNcPToYqU,4464 +tensorflow/python/autograph/operators/variables.py,sha256=35LS54KqLorXb-M8ndCHmvfK_VOPtbypPwGxr5bqqQE,3186 +tensorflow/python/autograph/pyct/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/autograph/pyct/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/autograph/pyct/__pycache__/anno.cpython-310.pyc,, +tensorflow/python/autograph/pyct/__pycache__/ast_util.cpython-310.pyc,, +tensorflow/python/autograph/pyct/__pycache__/cache.cpython-310.pyc,, +tensorflow/python/autograph/pyct/__pycache__/cfg.cpython-310.pyc,, +tensorflow/python/autograph/pyct/__pycache__/error_utils.cpython-310.pyc,, +tensorflow/python/autograph/pyct/__pycache__/errors.cpython-310.pyc,, +tensorflow/python/autograph/pyct/__pycache__/gast_util.cpython-310.pyc,, +tensorflow/python/autograph/pyct/__pycache__/inspect_utils.cpython-310.pyc,, +tensorflow/python/autograph/pyct/__pycache__/loader.cpython-310.pyc,, +tensorflow/python/autograph/pyct/__pycache__/naming.cpython-310.pyc,, +tensorflow/python/autograph/pyct/__pycache__/origin_info.cpython-310.pyc,, +tensorflow/python/autograph/pyct/__pycache__/parser.cpython-310.pyc,, +tensorflow/python/autograph/pyct/__pycache__/pretty_printer.cpython-310.pyc,, +tensorflow/python/autograph/pyct/__pycache__/qual_names.cpython-310.pyc,, +tensorflow/python/autograph/pyct/__pycache__/templates.cpython-310.pyc,, +tensorflow/python/autograph/pyct/__pycache__/transformer.cpython-310.pyc,, +tensorflow/python/autograph/pyct/__pycache__/transpiler.cpython-310.pyc,, +tensorflow/python/autograph/pyct/anno.py,sha256=oHPal48dX7p7sp3SikWPZXVly-MWFlsLM0lSqonQbZ4,5919 +tensorflow/python/autograph/pyct/ast_util.py,sha256=eC1XWJ_JqjnccIK-HX3yBhtz3_tZBp_F1deFSDkb_ws,10252 +tensorflow/python/autograph/pyct/cache.py,sha256=m2j-3W9sL1MvjyQouX-aHSZLj1N9DzYF8vtB_F6PDEU,2860 +tensorflow/python/autograph/pyct/cfg.py,sha256=3G2DaYFtqvgNNXcY84aSjOfdOIR_w1tJjrwgWJO0w_A,32120 +tensorflow/python/autograph/pyct/common_transformers/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/autograph/pyct/common_transformers/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/autograph/pyct/common_transformers/__pycache__/anf.cpython-310.pyc,, +tensorflow/python/autograph/pyct/common_transformers/anf.py,sha256=XK8GiMctABMen7-a7YmjzknLbSzxemvj1SqTnGSr51w,23477 +tensorflow/python/autograph/pyct/error_utils.py,sha256=Hovm88bZ2tTulVb90yCn8QbCgMTuUjiUjrzKIOaAXfE,7489 +tensorflow/python/autograph/pyct/errors.py,sha256=TdtWMz-2iC4fSSjkynWbEzSaz9PsI4BASIwBUBH6Qk4,1051 +tensorflow/python/autograph/pyct/gast_util.py,sha256=chZ0TntcAn_JiGqL148N4OQhyd88F5sH5OPch65M1c0,2134 +tensorflow/python/autograph/pyct/inspect_utils.py,sha256=MsRg_gSA58QIfqw2FBAWF0f-RcJ-ixSrRRqzv4gzL3o,10975 +tensorflow/python/autograph/pyct/loader.py,sha256=ptF5gws_t5tWayGoiUlCdSDn-IHUyyO4Xy2ahPbA57o,3237 +tensorflow/python/autograph/pyct/naming.py,sha256=pl9JkMsm-QMc9OjpDWRwmnho0OX4frSgWlf_4L9YqEg,1801 +tensorflow/python/autograph/pyct/origin_info.py,sha256=l8KX_HZjhyG89-_QcAT71MxllqAIcB6Ncm2yj7EbXd8,9974 +tensorflow/python/autograph/pyct/parser.py,sha256=12eKsfcJmjyoNhk7befDmHuBQuMmpe2Wp6PqbDtModY,13226 +tensorflow/python/autograph/pyct/pretty_printer.py,sha256=9icCpDOEOoGnXnl-F3YUkXjviB8RY9Vc22m7a39TTKM,4165 +tensorflow/python/autograph/pyct/qual_names.py,sha256=pOa2e8b6anWynrs0U1GIjYZNzBB6myTZt6JYZmG_4OE,8127 +tensorflow/python/autograph/pyct/static_analysis/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/autograph/pyct/static_analysis/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/autograph/pyct/static_analysis/__pycache__/activity.cpython-310.pyc,, +tensorflow/python/autograph/pyct/static_analysis/__pycache__/annos.cpython-310.pyc,, +tensorflow/python/autograph/pyct/static_analysis/__pycache__/liveness.cpython-310.pyc,, +tensorflow/python/autograph/pyct/static_analysis/__pycache__/reaching_definitions.cpython-310.pyc,, +tensorflow/python/autograph/pyct/static_analysis/__pycache__/reaching_fndefs.cpython-310.pyc,, +tensorflow/python/autograph/pyct/static_analysis/__pycache__/type_inference.cpython-310.pyc,, +tensorflow/python/autograph/pyct/static_analysis/activity.py,sha256=3ezVJd8ClcYV0Qb6dUL-HrTfrAjf5NsU4igup0_9zXQ,25695 +tensorflow/python/autograph/pyct/static_analysis/annos.py,sha256=bcWsGR40_HtkxgVGfQ4fUIHlNv9lOrdirL8VxLiuiFk,2019 +tensorflow/python/autograph/pyct/static_analysis/liveness.py,sha256=6jJdQvtitzXZKdEw6SjRm0BZWu2tTqjVyEMkvPPR6s4,7811 +tensorflow/python/autograph/pyct/static_analysis/reaching_definitions.py,sha256=cA7sg6wmfBqAE1CD6DGyO-kmJICi02-utfv4TuaE4oU,9095 +tensorflow/python/autograph/pyct/static_analysis/reaching_fndefs.py,sha256=jfNtXeE56Yxoy-V3iG1sonBfcVqov1ahsV015GQe3mg,5319 +tensorflow/python/autograph/pyct/static_analysis/type_inference.py,sha256=PuHbZKp4p1kto3gsi7-qejGf5xdL487zdZQhhSBLPj8,19811 +tensorflow/python/autograph/pyct/templates.py,sha256=ovEeDZ7Z_9WZ-MJYJGEDGXWc5ExjSMWJHW-QDHhHf-E,9510 +tensorflow/python/autograph/pyct/testing/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/autograph/pyct/testing/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/autograph/pyct/testing/__pycache__/basic_definitions.cpython-310.pyc,, +tensorflow/python/autograph/pyct/testing/__pycache__/decorators.cpython-310.pyc,, +tensorflow/python/autograph/pyct/testing/basic_definitions.py,sha256=lxMK08VYep2e4NE3s7FZZ2to2EfM37FB6Vm0rxmMwMM,1346 +tensorflow/python/autograph/pyct/testing/decorators.py,sha256=v07-yk_sbcXHK4Kr9coRm_AXcv4qCL8W-cq9Y2Emag4,1188 +tensorflow/python/autograph/pyct/transformer.py,sha256=-RXXY8oG8Km-fukLYn4IizhcnzMzvbqeft4Uh4PbtrI,16916 +tensorflow/python/autograph/pyct/transpiler.py,sha256=k3nKJRVN190g9OBihJNmzj7l0U06LBvtbmXo7vnI1Yw,17496 +tensorflow/python/autograph/utils/__init__.py,sha256=RJkLAT7OW2Xcuhisml7imPhiVZ2GTodbB77Y6GiKFMA,996 +tensorflow/python/autograph/utils/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/autograph/utils/__pycache__/ag_logging.cpython-310.pyc,, +tensorflow/python/autograph/utils/__pycache__/context_managers.cpython-310.pyc,, +tensorflow/python/autograph/utils/__pycache__/misc.cpython-310.pyc,, +tensorflow/python/autograph/utils/__pycache__/tensor_list.cpython-310.pyc,, +tensorflow/python/autograph/utils/__pycache__/tensors.cpython-310.pyc,, +tensorflow/python/autograph/utils/__pycache__/testing.cpython-310.pyc,, +tensorflow/python/autograph/utils/__pycache__/type_registry.cpython-310.pyc,, +tensorflow/python/autograph/utils/ag_logging.py,sha256=Bqv12az2MPv2nmEWxFuF7HJgMgZ3clv4jj-oR4g98EM,4080 +tensorflow/python/autograph/utils/context_managers.py,sha256=snrpGQJNXKMaq9uK6rMFmkD6H_EqpN3L_TmTo9Kee1E,1598 +tensorflow/python/autograph/utils/misc.py,sha256=N3gQIwwA9XOk-JHD_gSgG-rZnXeNd96E9q3pPV7kuFs,2123 +tensorflow/python/autograph/utils/tensor_list.py,sha256=vmoKgyxFGpVXEfkGX9XneGobwjbvSqIBARsn7Wv0IVk,2336 +tensorflow/python/autograph/utils/tensors.py,sha256=0OGNciD1bNZ4Z5YmqvDPkPoccekuNlyvK-qHaxz_Dss,1956 +tensorflow/python/autograph/utils/testing.py,sha256=1jy9Fl9sekciIfK2F7rJKG2AinPtW2-fYPcsRRR6NEQ,5200 +tensorflow/python/autograph/utils/type_registry.py,sha256=asKi8BFiRiUD846_RTB4-UxmFD03quJ1cong2rOee7k,1955 +tensorflow/python/checkpoint/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/checkpoint/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/checkpoint/__pycache__/async_checkpoint_helper.cpython-310.pyc,, +tensorflow/python/checkpoint/__pycache__/checkpoint.cpython-310.pyc,, +tensorflow/python/checkpoint/__pycache__/checkpoint_context.cpython-310.pyc,, +tensorflow/python/checkpoint/__pycache__/checkpoint_management.cpython-310.pyc,, +tensorflow/python/checkpoint/__pycache__/checkpoint_options.cpython-310.pyc,, +tensorflow/python/checkpoint/__pycache__/checkpoint_view.cpython-310.pyc,, +tensorflow/python/checkpoint/__pycache__/functional_saver.cpython-310.pyc,, +tensorflow/python/checkpoint/__pycache__/graph_view.cpython-310.pyc,, +tensorflow/python/checkpoint/__pycache__/restore.cpython-310.pyc,, +tensorflow/python/checkpoint/__pycache__/save_util.cpython-310.pyc,, +tensorflow/python/checkpoint/__pycache__/save_util_v1.cpython-310.pyc,, +tensorflow/python/checkpoint/__pycache__/saveable_compat.cpython-310.pyc,, +tensorflow/python/checkpoint/__pycache__/tensor_callable.cpython-310.pyc,, +tensorflow/python/checkpoint/__pycache__/trackable_view.cpython-310.pyc,, +tensorflow/python/checkpoint/__pycache__/util.cpython-310.pyc,, +tensorflow/python/checkpoint/async_checkpoint_helper.py,sha256=lwXfEUEChSTuEww0JswpswCIbC-beWbEMfNnkRklu2k,26195 +tensorflow/python/checkpoint/checkpoint.py,sha256=HXUHG2vGNm_27yqY-1-UE47xzgYR_JogNkPE5UgNunA,114212 +tensorflow/python/checkpoint/checkpoint_context.py,sha256=KeWt3nlXrxF9jsvMm8mIYs2fCe1QbvsK4PFrHNEjBiw,2387 +tensorflow/python/checkpoint/checkpoint_management.py,sha256=fSEz1kG0O1eLDo1GaUG_pTyMM3yPcOQd-vd597ZkRy0,37510 +tensorflow/python/checkpoint/checkpoint_options.py,sha256=toMPmM0Uc0qofLTiEakH57A_muh0A749XL_fw-9Kesg,4710 +tensorflow/python/checkpoint/checkpoint_view.py,sha256=7oiFZyihZXQFXkQS6C4Qgok2hXMNmzpdXR_0mu7-KVY,12045 +tensorflow/python/checkpoint/functional_saver.py,sha256=WduKQ3GD0yv7N9jeylRyGDNk2NEY0d4pb0jTyoc3O-E,21636 +tensorflow/python/checkpoint/graph_view.py,sha256=c0yhsziUyf82Fvb5XEk2OXWMvNZPiByCpkwMC_Xfga4,6793 +tensorflow/python/checkpoint/restore.py,sha256=QaHR7kS6l75qksICLpiqlB19U-IXX1aztYiDqrjZKWg,32012 +tensorflow/python/checkpoint/save_util.py,sha256=KH6BknEM18VsvhwzuxD3f3Behpg4NIYBp40L1hURkGQ,14638 +tensorflow/python/checkpoint/save_util_v1.py,sha256=TAIXsA0Nr7QYwg_H8GM9stdZsVonvzHwBHAt-UW9YfY,14517 +tensorflow/python/checkpoint/saveable_compat.py,sha256=jexxJPLOs4UEI8V-bO0-aMO80DY9JjXHoT2wRYw_9Pg,3523 +tensorflow/python/checkpoint/tensor_callable.py,sha256=b_ea4gegIwHNZpX1Vl0Zo-HVB8aQxRN6QOsBexHUVuY,1679 +tensorflow/python/checkpoint/trackable_view.py,sha256=j89EpQpQa3u-jxvfjxl4ThKyBgE_HIvPhfv1Ey_uY-A,4436 +tensorflow/python/checkpoint/util.py,sha256=bXryyH8tuCsKHFFmpGOh25wFiBlbzyA8lzsaPMyeAOo,7434 +tensorflow/python/client/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/client/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/client/__pycache__/client_lib.cpython-310.pyc,, +tensorflow/python/client/__pycache__/device_lib.cpython-310.pyc,, +tensorflow/python/client/__pycache__/pywrap_tf_session.cpython-310.pyc,, +tensorflow/python/client/__pycache__/session.cpython-310.pyc,, +tensorflow/python/client/__pycache__/timeline.cpython-310.pyc,, +tensorflow/python/client/_pywrap_debug_events_writer.pyi,sha256=sw4KYUmjnfb4NI6sWshmRLbnFFkvTvmK3D9FugL-V8s,1309 +tensorflow/python/client/_pywrap_debug_events_writer.so,sha256=k0t-6lG4pWrsh9K6GwDlBMLUYgGwcr-uEh1MC8Hyb4w,284296 +tensorflow/python/client/_pywrap_device_lib.pyi,sha256=HY6CRp0lFUBXCKNOrkudrQiP1rTR3Lw0Kj21alL0v1E,734 +tensorflow/python/client/_pywrap_device_lib.so,sha256=zPe9-37jRGrcsCG0YUs9UJNY8ZaVE1kzd8jXf8rwU3s,256992 +tensorflow/python/client/_pywrap_events_writer.so,sha256=2UubxTGicnEIOGtGRrkQSUSdGegHwUdxJZaLpCixMOg,300496 +tensorflow/python/client/_pywrap_tf_session.pyi,sha256=m0rtGZAIl3EfJeusglDqta3XYYXo_93kMiKfMS1XMAQ,19819 +tensorflow/python/client/_pywrap_tf_session.so,sha256=G-Il3rK1s0b8Sma2x3-7eQUwEoq2Y5diAMTH4lzmb04,2847112 +tensorflow/python/client/client_lib.py,sha256=w7kFzAIQORpHav6RtKKpJE162KzLhtoR_KsDMzfy7j0,1136 +tensorflow/python/client/device_lib.py,sha256=SxdOPjC4mF-xrGn8djpin82RoYmsvxsXJ0y4PaiVAFs,1618 +tensorflow/python/client/pywrap_tf_session.py,sha256=5qwUGRSAjhk0fePScpw1VdXShMDeLG_CmjFItd2OnCM,3017 +tensorflow/python/client/session.py,sha256=ZzV_h7mkdI_XnPMfoCqmaRgAfERatnS-T2hAWNI_fVc,71043 +tensorflow/python/client/timeline.py,sha256=0JE5bf83TrLmUP_92UUMuznuLwsuB5ackC7HdJInvWk,28612 +tensorflow/python/compat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/compat/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/compat/__pycache__/compat.cpython-310.pyc,, +tensorflow/python/compat/__pycache__/v2_compat.cpython-310.pyc,, +tensorflow/python/compat/compat.py,sha256=VPlEPrZV8r_9WhruLH95Rm9Tcu6iCir5UD7qjkZopKM,6090 +tensorflow/python/compat/v2_compat.py,sha256=o0piH_Akpx3NjW0PsXCs1jFKmX0pXaSLsf9iOA-kYZg,5738 +tensorflow/python/compiler/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/compiler/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/compiler/mlir/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/compiler/mlir/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/compiler/mlir/__pycache__/mlir.cpython-310.pyc,, +tensorflow/python/compiler/mlir/mlir.py,sha256=wn9LuLp-ohcy0pNd2fppQbwmZmMd0Cn68ITs3X5nvHY,7087 +tensorflow/python/compiler/tensorrt/__init__.py,sha256=qPrFooBhfBImDzcD1Qd0Q9HJIYqgld31aZVphBXSwkc,911 +tensorflow/python/compiler/tensorrt/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/compiler/tensorrt/__pycache__/trt_convert.cpython-310.pyc,, +tensorflow/python/compiler/tensorrt/__pycache__/utils.cpython-310.pyc,, +tensorflow/python/compiler/tensorrt/test/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/compiler/tensorrt/test/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/compiler/tensorrt/test/__pycache__/tf_trt_integration_test_base.cpython-310.pyc,, +tensorflow/python/compiler/tensorrt/test/tf_trt_integration_test_base.py,sha256=KP452-pkkqT-Ia5jq9ON0tin8ls6-nNYhE9df8oCv0w,49619 +tensorflow/python/compiler/tensorrt/trt_convert.py,sha256=xy4RgNTob-K5CK4h2Xw_SDUAFR3EaVMHAuKtCuKHy_s,79070 +tensorflow/python/compiler/tensorrt/utils.py,sha256=fWOxI3yJxw6u9kFJzedrWa65r9UqrpPC_2X3c6zwfCc,9024 +tensorflow/python/compiler/xla/__init__.py,sha256=ZAV9Sam5Ecu--PRuEa1HBuRjQFy3j7TTB5B7EjNPO3c,911 +tensorflow/python/compiler/xla/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/compiler/xla/__pycache__/jit.cpython-310.pyc,, +tensorflow/python/compiler/xla/__pycache__/xla.cpython-310.pyc,, +tensorflow/python/compiler/xla/experimental/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/compiler/xla/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/compiler/xla/experimental/__pycache__/xla_sharding.cpython-310.pyc,, +tensorflow/python/compiler/xla/experimental/xla_sharding.py,sha256=IUbkNSrv0rk0Jr_VG7OxgN1BgDIOYzcvkiSTVkAlx2s,21399 +tensorflow/python/compiler/xla/jit.py,sha256=v3R38Uetltu0UNZIYGWnIpCtrvk1svTKGyMShTLxDpI,5626 +tensorflow/python/compiler/xla/xla.py,sha256=sIyTMjP0aXJ1eqzX8ZmsSoQvl3imtGtDorvG9ew3yxA,23327 +tensorflow/python/data/__init__.py,sha256=cJRJOS0gMbvnFaoTh5yFw7-OrHVD42scdFpEIAm_6lo,1677 +tensorflow/python/data/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/data/benchmarks/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/data/benchmarks/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/data/benchmarks/__pycache__/benchmark_base.cpython-310.pyc,, +tensorflow/python/data/benchmarks/benchmark_base.py,sha256=XrJGzwSTedX11wGZ8DoNBnm22Dq_0WIOEjZV63cC5AY,9638 +tensorflow/python/data/experimental/__init__.py,sha256=M3Gpge7xQyIJ3qEMohwU-Vsjq9FdhbfZSAWLzfS44tU,7887 +tensorflow/python/data/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/data/experimental/kernel_tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/data/experimental/kernel_tests/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/data/experimental/kernel_tests/service/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/data/experimental/kernel_tests/service/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/data/experimental/kernel_tests/service/__pycache__/multi_process_cluster.cpython-310.pyc,, +tensorflow/python/data/experimental/kernel_tests/service/__pycache__/test_base.cpython-310.pyc,, +tensorflow/python/data/experimental/kernel_tests/service/multi_process_cluster.py,sha256=HK3DiPz4kXUyudT8V-RGlGmZ7vZUSsuawfrpifm8cbQ,5941 +tensorflow/python/data/experimental/kernel_tests/service/test_base.py,sha256=XGVjPMyUWLIpvzfO86jYrk31_HjOOVYV-MJ-dql-leg,15963 +tensorflow/python/data/experimental/ops/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/data/experimental/ops/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/data/experimental/ops/__pycache__/batching.cpython-310.pyc,, +tensorflow/python/data/experimental/ops/__pycache__/cardinality.cpython-310.pyc,, +tensorflow/python/data/experimental/ops/__pycache__/compression_ops.cpython-310.pyc,, +tensorflow/python/data/experimental/ops/__pycache__/counter.cpython-310.pyc,, +tensorflow/python/data/experimental/ops/__pycache__/data_service_ops.cpython-310.pyc,, +tensorflow/python/data/experimental/ops/__pycache__/distribute.cpython-310.pyc,, +tensorflow/python/data/experimental/ops/__pycache__/distributed_save_op.cpython-310.pyc,, +tensorflow/python/data/experimental/ops/__pycache__/enumerate_ops.cpython-310.pyc,, +tensorflow/python/data/experimental/ops/__pycache__/error_ops.cpython-310.pyc,, +tensorflow/python/data/experimental/ops/__pycache__/from_list.cpython-310.pyc,, +tensorflow/python/data/experimental/ops/__pycache__/get_single_element.cpython-310.pyc,, +tensorflow/python/data/experimental/ops/__pycache__/grouping.cpython-310.pyc,, +tensorflow/python/data/experimental/ops/__pycache__/interleave_ops.cpython-310.pyc,, +tensorflow/python/data/experimental/ops/__pycache__/io.cpython-310.pyc,, +tensorflow/python/data/experimental/ops/__pycache__/iterator_ops.cpython-310.pyc,, +tensorflow/python/data/experimental/ops/__pycache__/lookup_ops.cpython-310.pyc,, +tensorflow/python/data/experimental/ops/__pycache__/map_defun.cpython-310.pyc,, +tensorflow/python/data/experimental/ops/__pycache__/matching_files.cpython-310.pyc,, +tensorflow/python/data/experimental/ops/__pycache__/pad_to_cardinality.cpython-310.pyc,, +tensorflow/python/data/experimental/ops/__pycache__/parsing_ops.cpython-310.pyc,, +tensorflow/python/data/experimental/ops/__pycache__/prefetching_ops.cpython-310.pyc,, +tensorflow/python/data/experimental/ops/__pycache__/random_access.cpython-310.pyc,, +tensorflow/python/data/experimental/ops/__pycache__/random_ops.cpython-310.pyc,, +tensorflow/python/data/experimental/ops/__pycache__/readers.cpython-310.pyc,, +tensorflow/python/data/experimental/ops/__pycache__/resampling.cpython-310.pyc,, +tensorflow/python/data/experimental/ops/__pycache__/scan_ops.cpython-310.pyc,, +tensorflow/python/data/experimental/ops/__pycache__/shuffle_ops.cpython-310.pyc,, +tensorflow/python/data/experimental/ops/__pycache__/snapshot.cpython-310.pyc,, +tensorflow/python/data/experimental/ops/__pycache__/take_while_ops.cpython-310.pyc,, +tensorflow/python/data/experimental/ops/__pycache__/testing.cpython-310.pyc,, +tensorflow/python/data/experimental/ops/__pycache__/unique.cpython-310.pyc,, +tensorflow/python/data/experimental/ops/__pycache__/writers.cpython-310.pyc,, +tensorflow/python/data/experimental/ops/batching.py,sha256=S-IyrsoGMUb-QSyByUY1SmIGNkYZcBeRWhqs32jcBuQ,16589 +tensorflow/python/data/experimental/ops/cardinality.py,sha256=jOqmPgap2zUzJ-6pro3kEuPuhA_7XaVfVhGUpVkhcvA,4578 +tensorflow/python/data/experimental/ops/compression_ops.py,sha256=AC0kp2RAdWJQdI_csvlzhhnNJrcGV3x5g42jYYNkAXg,2002 +tensorflow/python/data/experimental/ops/counter.py,sha256=ARlQR3bA-Nxq3bLrlu5_KKz75WBtI3v7onyb_KBCT3Q,2748 +tensorflow/python/data/experimental/ops/data_service_ops.py,sha256=pa_GNaDiJzWciyN9idUuWB03KjD3GQPMcataR55hbfA,56254 +tensorflow/python/data/experimental/ops/distribute.py,sha256=jJXGakd_2z_YUxKjBmp2p-fib9teKRnWj6Ye0bmC69w,15533 +tensorflow/python/data/experimental/ops/distributed_save_op.py,sha256=LmvgcUH78u3fZ8-UiCpjDsc_D6UeJWqIeIBSs1IXB0Q,2662 +tensorflow/python/data/experimental/ops/enumerate_ops.py,sha256=8wdTVlTYHGJezy3brNSGd9wIWQU9o28O9QR6gJB45uE,1857 +tensorflow/python/data/experimental/ops/error_ops.py,sha256=Zx_iqT-NHr1rnziTl0vYuwNGZHgPy862DkEbNZ2Ce10,2016 +tensorflow/python/data/experimental/ops/from_list.py,sha256=lI9DifyIuBVmiL5fGE9yLvF5X0IzY4rkWbeYhEgwNas,4739 +tensorflow/python/data/experimental/ops/get_single_element.py,sha256=fxSRAH56M2pQVZ6FAx--c6IfLLTOlzqPhBbdkgeBwm4,5629 +tensorflow/python/data/experimental/ops/grouping.py,sha256=t5cq2BAIPCynLKs4DPdfRRV_5ZnMnSrWQuX1XTvQmhQ,17164 +tensorflow/python/data/experimental/ops/interleave_ops.py,sha256=oe1kC-jPwtlIRcOUR0jbJUJztsEvyP7Yt3Zo0sgMQec,10358 +tensorflow/python/data/experimental/ops/io.py,sha256=rKHC3PY08rTGxN_KMmh87t8OpwNYbrvSKHpPkWR7Nyo,6697 +tensorflow/python/data/experimental/ops/iterator_ops.py,sha256=cu3PCYBN_nZCdM_UnNPEtwVZ7floFA7J07PS3n2QoMk,14377 +tensorflow/python/data/experimental/ops/lookup_ops.py,sha256=fD4-If76NX18rRfo_Cn6k8ORM-b9a5J3jEJ-MY8X-w8,10270 +tensorflow/python/data/experimental/ops/map_defun.py,sha256=39zqaDLNc3-pSntvi8z_Zzlen4IM-Ai7wKM7_3uxfWM,2955 +tensorflow/python/data/experimental/ops/matching_files.py,sha256=gM4YSVrerrnzgNdoQ1HpAC3ktf85PjmHZE4JlyQNkrM,1497 +tensorflow/python/data/experimental/ops/pad_to_cardinality.py,sha256=zG0beNvA_6fuDMDsMrzSawS_t6zTbAD-hIoP7MHRGdQ,4031 +tensorflow/python/data/experimental/ops/parsing_ops.py,sha256=svux-nxPvFPJUftZUSm_xLPC8oD5GKhVkh4KWsZgaRU,7281 +tensorflow/python/data/experimental/ops/prefetching_ops.py,sha256=vcabhz8n-B6k_YAGsAjl5NIMSWNrVlYw01OeaTUBjgE,11621 +tensorflow/python/data/experimental/ops/random_access.py,sha256=oCZ2eXOMvlljqPGSU92hMmTvx9rG6A6MWKLysJItthM,2803 +tensorflow/python/data/experimental/ops/random_ops.py,sha256=lftgyRyVuB_Zb6Wqp8VgcTLSCcRgYxOQiHFGVp5uGkY,1782 +tensorflow/python/data/experimental/ops/readers.py,sha256=Vqu8Kstr7dT0sjT6G57UIfjHHNTrfuQ8GXSxqvZQt-4,51247 +tensorflow/python/data/experimental/ops/resampling.py,sha256=eVSmNqdA0g4XxpUfQlX7s7RkTdHJEchB_hGAMJ9Z88I,2104 +tensorflow/python/data/experimental/ops/scan_ops.py,sha256=uNAWTJ9EXi-HtWdp6Bi7PQDd5GZFWQRIMrnykr-6fD4,1890 +tensorflow/python/data/experimental/ops/shuffle_ops.py,sha256=7FSJTHIqFwXu418qlHR0DwkBKlXHlNIFObwCZ3pQ9tc,11707 +tensorflow/python/data/experimental/ops/snapshot.py,sha256=OMuSE6M4sMH-u1kvUf-aV6Q1ELjRo4PpJ4s91YDAQ5Q,12308 +tensorflow/python/data/experimental/ops/take_while_ops.py,sha256=xu-Dixb6Qt7r7msnKN9L_QvBAj-Vfn5cki0c4MPI-vM,1457 +tensorflow/python/data/experimental/ops/testing.py,sha256=7wwR0SwDWdcKOnGKP13r3hQRGGtkSelXfTs1xsx1jDg,7425 +tensorflow/python/data/experimental/ops/unique.py,sha256=ZcTK4EB1uMJMSaSjpb7CgUlr7g7Y6M8_QBSknLTepTo,1564 +tensorflow/python/data/experimental/ops/writers.py,sha256=ta2u9CjdhdS_6ez7VPvu3FeTpRTknu8E1rt1oaTzPV0,4936 +tensorflow/python/data/experimental/service/__init__.py,sha256=_5A2KphwBf34x-sTMxbrGA2ptoKlFp2vvPD2vMoiBlw,19493 +tensorflow/python/data/experimental/service/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/data/experimental/service/__pycache__/server_lib.cpython-310.pyc,, +tensorflow/python/data/experimental/service/_pywrap_server_lib.pyi,sha256=jp-YgjnkqwfGYi6Nm2Itdfgu2-a4q_LTopeaRkDPq9Y,1980 +tensorflow/python/data/experimental/service/_pywrap_server_lib.so,sha256=05UzbajKJl9YPL3fzT9nmy4IXIINJk-MdQM1MCTIUP8,1892248 +tensorflow/python/data/experimental/service/_pywrap_snapshot_utils.pyi,sha256=wMIvmfxlymYHZKDM-3XA78u5il9DARctguYoOpt88tI,923 +tensorflow/python/data/experimental/service/_pywrap_snapshot_utils.so,sha256=xRPC8EsvFKeazlrKszAWEPh9GOC_BTifeAAxk1n6dYg,193168 +tensorflow/python/data/experimental/service/_pywrap_utils.pyi,sha256=iG-_mlxmizesp6uEa6ZVDgg0x2YeK-3wHSvzZMon6X8,732 +tensorflow/python/data/experimental/service/_pywrap_utils.so,sha256=lNQcw1KqqoNVj_6sJCszWl9t9_MQNDZfP7Zpx6X9beI,3715808 +tensorflow/python/data/experimental/service/server_lib.py,sha256=2LGk8wll-pwDTOhL_CsanMJXiRIJk08FX45YCRbSHi4,17830 +tensorflow/python/data/kernel_tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/data/kernel_tests/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/data/kernel_tests/__pycache__/checkpoint_test_base.cpython-310.pyc,, +tensorflow/python/data/kernel_tests/__pycache__/test_base.cpython-310.pyc,, +tensorflow/python/data/kernel_tests/__pycache__/tf_record_test_base.cpython-310.pyc,, +tensorflow/python/data/kernel_tests/checkpoint_test_base.py,sha256=ka0yhIuVUfoV85pvj8QUbWOb56RpR6l2JwVwH2ovgrU,24699 +tensorflow/python/data/kernel_tests/test_base.py,sha256=uzoGw-v0NYa8NiWYE0d0hKpw6SjXaFyk4PBKRpvUbl4,18353 +tensorflow/python/data/kernel_tests/tf_record_test_base.py,sha256=EOU1T-0nQpbd_ih4raR1TOrmhnC2dGoo8N_h-zl7SZE,11740 +tensorflow/python/data/ops/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/data/ops/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/data/ops/__pycache__/batch_op.cpython-310.pyc,, +tensorflow/python/data/ops/__pycache__/cache_op.cpython-310.pyc,, +tensorflow/python/data/ops/__pycache__/choose_from_datasets_op.cpython-310.pyc,, +tensorflow/python/data/ops/__pycache__/concatenate_op.cpython-310.pyc,, +tensorflow/python/data/ops/__pycache__/counter_op.cpython-310.pyc,, +tensorflow/python/data/ops/__pycache__/dataset_autograph.cpython-310.pyc,, +tensorflow/python/data/ops/__pycache__/dataset_ops.cpython-310.pyc,, +tensorflow/python/data/ops/__pycache__/debug_mode.cpython-310.pyc,, +tensorflow/python/data/ops/__pycache__/directed_interleave_op.cpython-310.pyc,, +tensorflow/python/data/ops/__pycache__/filter_op.cpython-310.pyc,, +tensorflow/python/data/ops/__pycache__/flat_map_op.cpython-310.pyc,, +tensorflow/python/data/ops/__pycache__/from_generator_op.cpython-310.pyc,, +tensorflow/python/data/ops/__pycache__/from_sparse_tensor_slices_op.cpython-310.pyc,, +tensorflow/python/data/ops/__pycache__/from_tensor_slices_op.cpython-310.pyc,, +tensorflow/python/data/ops/__pycache__/from_tensors_op.cpython-310.pyc,, +tensorflow/python/data/ops/__pycache__/group_by_window_op.cpython-310.pyc,, +tensorflow/python/data/ops/__pycache__/ignore_errors_op.cpython-310.pyc,, +tensorflow/python/data/ops/__pycache__/interleave_op.cpython-310.pyc,, +tensorflow/python/data/ops/__pycache__/iterator_autograph.cpython-310.pyc,, +tensorflow/python/data/ops/__pycache__/iterator_ops.cpython-310.pyc,, +tensorflow/python/data/ops/__pycache__/load_op.cpython-310.pyc,, +tensorflow/python/data/ops/__pycache__/map_op.cpython-310.pyc,, +tensorflow/python/data/ops/__pycache__/multi_device_iterator_ops.cpython-310.pyc,, +tensorflow/python/data/ops/__pycache__/optional_ops.cpython-310.pyc,, +tensorflow/python/data/ops/__pycache__/options.cpython-310.pyc,, +tensorflow/python/data/ops/__pycache__/padded_batch_op.cpython-310.pyc,, +tensorflow/python/data/ops/__pycache__/prefetch_op.cpython-310.pyc,, +tensorflow/python/data/ops/__pycache__/ragged_batch_op.cpython-310.pyc,, +tensorflow/python/data/ops/__pycache__/random_op.cpython-310.pyc,, +tensorflow/python/data/ops/__pycache__/range_op.cpython-310.pyc,, +tensorflow/python/data/ops/__pycache__/readers.cpython-310.pyc,, +tensorflow/python/data/ops/__pycache__/rebatch_op.cpython-310.pyc,, +tensorflow/python/data/ops/__pycache__/repeat_op.cpython-310.pyc,, +tensorflow/python/data/ops/__pycache__/sample_from_datasets_op.cpython-310.pyc,, +tensorflow/python/data/ops/__pycache__/save_op.cpython-310.pyc,, +tensorflow/python/data/ops/__pycache__/scan_op.cpython-310.pyc,, +tensorflow/python/data/ops/__pycache__/shard_op.cpython-310.pyc,, +tensorflow/python/data/ops/__pycache__/shuffle_op.cpython-310.pyc,, +tensorflow/python/data/ops/__pycache__/skip_op.cpython-310.pyc,, +tensorflow/python/data/ops/__pycache__/snapshot_op.cpython-310.pyc,, +tensorflow/python/data/ops/__pycache__/sparse_batch_op.cpython-310.pyc,, +tensorflow/python/data/ops/__pycache__/structured_function.cpython-310.pyc,, +tensorflow/python/data/ops/__pycache__/take_op.cpython-310.pyc,, +tensorflow/python/data/ops/__pycache__/take_while_op.cpython-310.pyc,, +tensorflow/python/data/ops/__pycache__/test_mode.cpython-310.pyc,, +tensorflow/python/data/ops/__pycache__/unbatch_op.cpython-310.pyc,, +tensorflow/python/data/ops/__pycache__/unique_op.cpython-310.pyc,, +tensorflow/python/data/ops/__pycache__/window_op.cpython-310.pyc,, +tensorflow/python/data/ops/__pycache__/zip_op.cpython-310.pyc,, +tensorflow/python/data/ops/batch_op.py,sha256=O45pIFiKjscwPX9d9qglHC3i5YLkKyO2dFPqbK6D0pk,5508 +tensorflow/python/data/ops/cache_op.py,sha256=GY4EsSTqIE3SS4YaIl2uuH2FUSZdoiSf_P05hRd0vrE,2131 +tensorflow/python/data/ops/choose_from_datasets_op.py,sha256=TolYIdUQgzxKgYba9AUinQyf19TBqNv1L-wgte7PAr4,2329 +tensorflow/python/data/ops/concatenate_op.py,sha256=559bs905C-r1Uf_xdYOF6__kttnPGoBsKFeRCA45YH8,2499 +tensorflow/python/data/ops/counter_op.py,sha256=iCGuUDjH119kW42-610KVPeovVMWbjvFal-MirF-Rm8,1188 +tensorflow/python/data/ops/dataset_autograph.py,sha256=uozRL34AgiGNdS-oi7ChGdSboOhCntzVW8l448CbhPw,8731 +tensorflow/python/data/ops/dataset_ops.py,sha256=czPwWVGN2m50KwVEPSjTBGQNTAFBp7QO5xd72NsYJAI,208810 +tensorflow/python/data/ops/debug_mode.py,sha256=PXp-_xNgKcLmqKIP_hb_8KTU7M5NQCfMSNhit44NNwM,2583 +tensorflow/python/data/ops/directed_interleave_op.py,sha256=u2p3RffXRwfBibwEg6LHJ2SyATZzp2EFmmKvZbquTAo,2878 +tensorflow/python/data/ops/filter_op.py,sha256=NLVoERDh-sXemKtBgylTXO8Gaar3xhh7kClQJOPn7IA,2547 +tensorflow/python/data/ops/flat_map_op.py,sha256=qLcbdfsSsd51iKexd6MivxjZDBOKP3_0SE4Jhfb0VSk,2330 +tensorflow/python/data/ops/from_generator_op.py,sha256=00SPBWMuTzgMUADhWAlvUEs_IoIcd6_65JKmQjX1oew,17583 +tensorflow/python/data/ops/from_sparse_tensor_slices_op.py,sha256=ioAcFR8zktdYo2EbcYv5dxTrVgK6QV_boRdN6eu6u94,2464 +tensorflow/python/data/ops/from_tensor_slices_op.py,sha256=PhfOUanBr3crNj30t6aGhO9axKbZLoYHTsWPDNR5BF8,2409 +tensorflow/python/data/ops/from_tensors_op.py,sha256=GnFGQSaVpqyyT23HZYbiU0rZk7OyUKmM4j1gPnC5SMo,1721 +tensorflow/python/data/ops/group_by_window_op.py,sha256=l-7laGQRJF7E8pJbIrH7n7bD8pY3Xb60Y5M2duE5BFI,5678 +tensorflow/python/data/ops/ignore_errors_op.py,sha256=zFoV40pdl4T9M39wz4UMPG0YzCRizWT4G0_vd2gTyjY,1605 +tensorflow/python/data/ops/interleave_op.py,sha256=P97WUr55foh1kUPn1mIgqW0EWt_AP0gQznwAaNLTfdA,6409 +tensorflow/python/data/ops/iterator_autograph.py,sha256=lVZ0WjV0zH7ntdb9fbb4q8IjqGJRy_0fqShFrhFwufQ,4511 +tensorflow/python/data/ops/iterator_ops.py,sha256=ZwBfsNimDoU57U9Tq5eXMESlQTH_FlqsXlHq-SO_7uQ,40307 +tensorflow/python/data/ops/load_op.py,sha256=TUMInizTfeVsz_c5CKibhLKq1lWxCcecK_kvi9IjgFs,6719 +tensorflow/python/data/ops/map_op.py,sha256=w9IbJk2M5MYYkr3_7unKHt4EDK5G0AXm-VL7ArRc1sk,6552 +tensorflow/python/data/ops/multi_device_iterator_ops.py,sha256=SMwZIJlenHsAXtR8ztoC1o6xnfj0CmgxVW8aSEp3j8U,23690 +tensorflow/python/data/ops/optional_ops.py,sha256=FSO7DFIq-yT8ldwm6pK74ln8n0nS60AwVX9LgmPHA7w,9203 +tensorflow/python/data/ops/options.py,sha256=rDWjI6nG-6ldZApZLJtn5vojQH9x6zwo-iuInLCODX8,28275 +tensorflow/python/data/ops/padded_batch_op.py,sha256=MXzDX2iD8t5Bp6y9AJy6TiHH73IXDnQCnQ9o3qbtYlk,10741 +tensorflow/python/data/ops/prefetch_op.py,sha256=4xFF2tQoZ-MQ8iwuXw4T2RMbFdW4yJGTTiOuyv3vlSg,2226 +tensorflow/python/data/ops/ragged_batch_op.py,sha256=RpURvCg4rS3070ZlMh7DiRUCUjYnAvqjcHnuOgA5NgI,4539 +tensorflow/python/data/ops/random_op.py,sha256=vhSW9tPOPgJzZC6U5wDmpsixpMSigB_J72bjZ-T1fC4,2476 +tensorflow/python/data/ops/range_op.py,sha256=I5ylGZRTbBXtk37fUsXfdQUZfwAJ8wTcrqbycz15O_A,2799 +tensorflow/python/data/ops/readers.py,sha256=4h13-eIGDHVF8vt884GmAtmwTaaE--fUfiLF-uqsKBw,26472 +tensorflow/python/data/ops/rebatch_op.py,sha256=W7gLm3E-AF0eAdk7VjDurU627QQbjrby1b1-PkNN0Ss,5908 +tensorflow/python/data/ops/repeat_op.py,sha256=t0fY0MwH6o1_rqU6nx3zZ8PNxGKN1bT4MLWF8cG7_DE,1853 +tensorflow/python/data/ops/sample_from_datasets_op.py,sha256=kwfgzMdPtdUlg-_zxpH91FkO23vAmUXDL6kdP3sUamU,5337 +tensorflow/python/data/ops/save_op.py,sha256=zhmzalaAv6uKGPcuuqnux4vrrnCUKwuDQiOF3FJPtag,4770 +tensorflow/python/data/ops/scan_op.py,sha256=shCJhfSkZ7rv_V48hDuPGrEqZsBK4cwDcU7y6QdsDK0,7068 +tensorflow/python/data/ops/shard_op.py,sha256=E04gZnryXZauAhZa7_lbBzuHeA8oElgdTZZjB5C6a3I,1873 +tensorflow/python/data/ops/shuffle_op.py,sha256=3hnYu10-mSAQn-UZtY3E13zfF4D9yE9VrYF4udNRhGA,2937 +tensorflow/python/data/ops/skip_op.py,sha256=F_KduhvnC4XMYRlRzax8tAtBpwl9L4a3vyjOqAXa5TQ,1665 +tensorflow/python/data/ops/snapshot_op.py,sha256=Tb-yf41xKBrgWEmYlgo7AWoEoVqMgueKALPVyHQnVNk,4707 +tensorflow/python/data/ops/sparse_batch_op.py,sha256=0J1JXK0ImweZuFr79tTCoppo0wqdYCtHhx5AC6Td7NI,2702 +tensorflow/python/data/ops/structured_function.py,sha256=yT0y2nTE0n-1z4BFq0y4GtxwjC4nFcP0vEOj4oqYX18,12798 +tensorflow/python/data/ops/take_op.py,sha256=neip5EqggbUJfKIptnQ6vj0XXGuAXJUUxmhJXjkgrIo,1673 +tensorflow/python/data/ops/take_while_op.py,sha256=KIrmBrbn_j9XKpmOwChqdWpyWPJupHb4wTYtpO1PMYY,2487 +tensorflow/python/data/ops/test_mode.py,sha256=2z6BJTmV8fLS1fDHhJ0W-afROF9DMod8mmau5ANXFVY,1194 +tensorflow/python/data/ops/unbatch_op.py,sha256=JBsUCQe79Km_9A5ucYzltcU-2WIdbH9Y-paJvIAjn-0,2579 +tensorflow/python/data/ops/unique_op.py,sha256=J7tco7KZavxMsQzshqQx9JHCpzOhwkdeKrwJDUKSXPk,1915 +tensorflow/python/data/ops/window_op.py,sha256=T74jcn7UGREYZFg4-GgsJ7p63B6LUwL8YqNTDSPhCJ0,3135 +tensorflow/python/data/ops/zip_op.py,sha256=8ph4RmznC8O7yH5NVu4PCrdlFsfAzsYXEuXhMA93VNE,2353 +tensorflow/python/data/util/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/data/util/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/data/util/__pycache__/convert.cpython-310.pyc,, +tensorflow/python/data/util/__pycache__/nest.cpython-310.pyc,, +tensorflow/python/data/util/__pycache__/options.cpython-310.pyc,, +tensorflow/python/data/util/__pycache__/random_seed.cpython-310.pyc,, +tensorflow/python/data/util/__pycache__/sparse.cpython-310.pyc,, +tensorflow/python/data/util/__pycache__/structure.cpython-310.pyc,, +tensorflow/python/data/util/__pycache__/traverse.cpython-310.pyc,, +tensorflow/python/data/util/convert.py,sha256=9KlTjmoXoiR8LSLUDRu1MXW1shTs--Gs2RTch3oYRqw,2818 +tensorflow/python/data/util/nest.py,sha256=xHwJiTg3HFEIjW2BdopeYReaHN6s18plY40cYYrdkco,11051 +tensorflow/python/data/util/options.py,sha256=Y5dpq9U6rOnnLaBkrBYAczq6vgP9g5Lrp6haZTWJKIs,6005 +tensorflow/python/data/util/random_seed.py,sha256=uhwiYRmnhXFVxP4z8d2JZIVk8HKOjKWtgEKhap6t2qc,2112 +tensorflow/python/data/util/sparse.py,sha256=t4L-uHwYWNG5oKLOMxLs0udEDmYOQW58M7JNUxJQ9zg,4956 +tensorflow/python/data/util/structure.py,sha256=H3L7poug33TmHZECirlfEc7xDODHW494Vh88t5SapT8,20177 +tensorflow/python/data/util/traverse.py,sha256=JsNrecZEQ0vePydYnIl8GQJTdYCQykix7J0M9a3kam8,2731 +tensorflow/python/debug/__init__.py,sha256=561fOs6xLEXy2PYc6ZeQYNk-u5ORZiaHMbq-0TKjL8Q,2840 +tensorflow/python/debug/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/debug/cli/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/debug/cli/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/debug/cli/__pycache__/analyzer_cli.cpython-310.pyc,, +tensorflow/python/debug/cli/__pycache__/base_ui.cpython-310.pyc,, +tensorflow/python/debug/cli/__pycache__/cli_config.cpython-310.pyc,, +tensorflow/python/debug/cli/__pycache__/cli_shared.cpython-310.pyc,, +tensorflow/python/debug/cli/__pycache__/cli_test_utils.cpython-310.pyc,, +tensorflow/python/debug/cli/__pycache__/command_parser.cpython-310.pyc,, +tensorflow/python/debug/cli/__pycache__/debugger_cli_common.cpython-310.pyc,, +tensorflow/python/debug/cli/__pycache__/evaluator.cpython-310.pyc,, +tensorflow/python/debug/cli/__pycache__/offline_analyzer.cpython-310.pyc,, +tensorflow/python/debug/cli/__pycache__/profile_analyzer_cli.cpython-310.pyc,, +tensorflow/python/debug/cli/__pycache__/readline_ui.cpython-310.pyc,, +tensorflow/python/debug/cli/__pycache__/tensor_format.cpython-310.pyc,, +tensorflow/python/debug/cli/__pycache__/ui_factory.cpython-310.pyc,, +tensorflow/python/debug/cli/analyzer_cli.py,sha256=yuLJG9XPpG6fRDZretvJ-QIHNoem3lvmEli7FhwaAyA,58529 +tensorflow/python/debug/cli/base_ui.py,sha256=Z9EdiiTT2nhH5g_iX-u2LYtShlT1JVo6w2arT4ExUvw,7605 +tensorflow/python/debug/cli/cli_config.py,sha256=VxJkqmFkOhXMCubA5l5dSMHgoH8QciGFDRzUzbo4CuA,5600 +tensorflow/python/debug/cli/cli_shared.py,sha256=4NIK_PmSl1bZyA5zvVihnScgKHQHHq67PxRX-6aGYJk,15884 +tensorflow/python/debug/cli/cli_test_utils.py,sha256=31m4gW6I4JV9YGyOY8rde5BYUdoQaPWJDsmMZjB3ohM,2454 +tensorflow/python/debug/cli/command_parser.py,sha256=fFEam4Iz4yaX6lAnpF0qe6UTcN9aLE7Wpteyisi4RHY,17341 +tensorflow/python/debug/cli/debugger_cli_common.py,sha256=DGUwUrhWGkESWE5HQ0gE9RwTNUZZxIC88KT9rggJNlo,39724 +tensorflow/python/debug/cli/evaluator.py,sha256=EXjpIIj5xR1lVGTFzOOGin17neMXel2LVUdCDkD0Ck4,5617 +tensorflow/python/debug/cli/offline_analyzer.py,sha256=008u4li15qffyPGGE0s19aqTO505ziqLBuip-2fH_OY,2352 +tensorflow/python/debug/cli/profile_analyzer_cli.py,sha256=XoaRBHvTmKnHtZwv77Lf_Oz4uc-Ru1nbm7III3rMCQs,29557 +tensorflow/python/debug/cli/readline_ui.py,sha256=_U_jTpJMkU5Eki5nx6H2jYqjyEbddxfPk8liUSU_gYE,4020 +tensorflow/python/debug/cli/tensor_format.py,sha256=70PELkyWnhn3Igb79Cn6RU3jc_JdnnXjIVhjeO5UILM,20280 +tensorflow/python/debug/cli/ui_factory.py,sha256=RFkCrh7Q1e-E0Vy5OM6_C1yzCS1StUNY9Uj67p0vghs,2231 +tensorflow/python/debug/lib/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/debug/lib/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/debug/lib/__pycache__/check_numerics_callback.cpython-310.pyc,, +tensorflow/python/debug/lib/__pycache__/common.cpython-310.pyc,, +tensorflow/python/debug/lib/__pycache__/debug_data.cpython-310.pyc,, +tensorflow/python/debug/lib/__pycache__/debug_events_monitors.cpython-310.pyc,, +tensorflow/python/debug/lib/__pycache__/debug_events_reader.cpython-310.pyc,, +tensorflow/python/debug/lib/__pycache__/debug_events_writer.cpython-310.pyc,, +tensorflow/python/debug/lib/__pycache__/debug_gradients.cpython-310.pyc,, +tensorflow/python/debug/lib/__pycache__/debug_graphs.cpython-310.pyc,, +tensorflow/python/debug/lib/__pycache__/debug_service_pb2_grpc.cpython-310.pyc,, +tensorflow/python/debug/lib/__pycache__/debug_utils.cpython-310.pyc,, +tensorflow/python/debug/lib/__pycache__/dumping_callback.cpython-310.pyc,, +tensorflow/python/debug/lib/__pycache__/dumping_callback_test_lib.cpython-310.pyc,, +tensorflow/python/debug/lib/__pycache__/grpc_debug_server.cpython-310.pyc,, +tensorflow/python/debug/lib/__pycache__/grpc_debug_test_server.cpython-310.pyc,, +tensorflow/python/debug/lib/__pycache__/grpc_tensorflow_server.cpython-310.pyc,, +tensorflow/python/debug/lib/__pycache__/op_callbacks_common.cpython-310.pyc,, +tensorflow/python/debug/lib/__pycache__/profiling.cpython-310.pyc,, +tensorflow/python/debug/lib/__pycache__/session_debug_testlib.cpython-310.pyc,, +tensorflow/python/debug/lib/__pycache__/source_remote.cpython-310.pyc,, +tensorflow/python/debug/lib/__pycache__/source_utils.cpython-310.pyc,, +tensorflow/python/debug/lib/check_numerics_callback.py,sha256=2O2E2HjFeVCZ7w7m5XtEw2LvOVjOZbl4PDCQWyyqWGw,18410 +tensorflow/python/debug/lib/common.py,sha256=XuFnNnfREVwPD5YLVlnYkAkMt3n140idasQPGrj_LVk,2967 +tensorflow/python/debug/lib/debug_data.py,sha256=3JJqi19WQZrqE4EBC0DGW-YkUZ3lq-zHgIxG9ZA4AmY,59572 +tensorflow/python/debug/lib/debug_events_monitors.py,sha256=Z44nmiD7roKwf51I6LjUt6jlRobPHcMSAPBEVcDYejk,11389 +tensorflow/python/debug/lib/debug_events_reader.py,sha256=XLPCTjRdi8CFICZ7XCRKUeDUylSgC4H0uBKZiHoSUOU,49026 +tensorflow/python/debug/lib/debug_events_writer.py,sha256=xxvb_z1aILsMlQKHeRayDG0VCH9osPHzna-PaPds1Zs,6267 +tensorflow/python/debug/lib/debug_gradients.py,sha256=nF9kQfZlBmY0-OqQlIY1Xf-kyJOTgpX8stk_C8qp95s,15397 +tensorflow/python/debug/lib/debug_graphs.py,sha256=pnigb_Z2YKcdNakqVRpGTBcEts3Dy_05kOxjzGFWBKI,15455 +tensorflow/python/debug/lib/debug_service_pb2_grpc.py,sha256=fBdDZYIsWkiXuEBmY6ElQN2hOx1n4nSzMaBy8-k2uxA,5031 +tensorflow/python/debug/lib/debug_utils.py,sha256=sIRSDGVjpm_8Lq24Gkx6lwzNc7UPcon7JxRCUAqW-zY,12024 +tensorflow/python/debug/lib/dumping_callback.py,sha256=2ws5-0VqK85zm6c-w1n5a3XrdhXlhGIFHky4qrHQqT0,39514 +tensorflow/python/debug/lib/dumping_callback_test_lib.py,sha256=n_TE7wN9MnDvbu_baD_lK3To3Qw-7ENDiiwq5oMTWSM,1987 +tensorflow/python/debug/lib/grpc_debug_server.py,sha256=fEulCz4kpoHEMYYMB76smdX6y8lcV-yTsNX9aIvSTic,18854 +tensorflow/python/debug/lib/grpc_debug_test_server.py,sha256=je4C4bdpPg3WouVK6-yHTc4UK8GfOAhLijfVoyye4Fs,17744 +tensorflow/python/debug/lib/grpc_tensorflow_server.py,sha256=gWv3O-m78cs_tFmo86Zfr5ck1dlROUDEOsXu42arJCE,4555 +tensorflow/python/debug/lib/op_callbacks_common.py,sha256=Af05hx8bqCzDkVVY9HbNhEOPSF6XUjS-W8XRj-UbYH8,1704 +tensorflow/python/debug/lib/profiling.py,sha256=1qIMj2jENXkJTmXvtgMUpy_U-TfvJqIFF7DbMIGZWAk,3595 +tensorflow/python/debug/lib/session_debug_testlib.py,sha256=qDpRGiAjNIEyVTyP2vv_OZIXAzZdoCiMI_hVE7zal9w,64710 +tensorflow/python/debug/lib/source_remote.py,sha256=uZEkgVU9hiFfm_oXRB6vRBAmpHcKhUW_ObxNaWRt3Jw,8664 +tensorflow/python/debug/lib/source_utils.py,sha256=p32H0TXsTBmiytKoo4bVtuTGVKU4KE-fCw1NjVCT6uQ,13651 +tensorflow/python/debug/wrappers/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/debug/wrappers/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/debug/wrappers/__pycache__/dumping_wrapper.cpython-310.pyc,, +tensorflow/python/debug/wrappers/__pycache__/framework.cpython-310.pyc,, +tensorflow/python/debug/wrappers/__pycache__/grpc_wrapper.cpython-310.pyc,, +tensorflow/python/debug/wrappers/__pycache__/hooks.cpython-310.pyc,, +tensorflow/python/debug/wrappers/__pycache__/local_cli_wrapper.cpython-310.pyc,, +tensorflow/python/debug/wrappers/dumping_wrapper.py,sha256=Z4ATvcyLXoIrNGsaD_9lp_iJQew91wWGBUmge-a7-bs,5166 +tensorflow/python/debug/wrappers/framework.py,sha256=QqGRcHzm1KkWDIhoEpqrkocwLSJFwSCS2gkdOS8Od1M,37346 +tensorflow/python/debug/wrappers/grpc_wrapper.py,sha256=0kUUn8j1KFnZPNCvzynl2huwTWGR_dQKtX3ERCQzRvM,8102 +tensorflow/python/debug/wrappers/hooks.py,sha256=DTAdqbGsfTAhZ26sAmvbn7wMZjYW5L9kzRCfsvOv5FQ,13755 +tensorflow/python/debug/wrappers/local_cli_wrapper.py,sha256=lNUsf_BzpchJskSUaaKjI0u8j9hKH6wC1B6gOpesB4o,24293 +tensorflow/python/distribute/__init__.py,sha256=KJTAJjMPUYHNIVI2mVZT2gO_XLyIV2Tfo5IYoY48A8k,10447 +tensorflow/python/distribute/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/distribute/__pycache__/central_storage_strategy.cpython-310.pyc,, +tensorflow/python/distribute/__pycache__/collective_all_reduce_strategy.cpython-310.pyc,, +tensorflow/python/distribute/__pycache__/collective_util.cpython-310.pyc,, +tensorflow/python/distribute/__pycache__/combinations.cpython-310.pyc,, +tensorflow/python/distribute/__pycache__/cross_device_ops.cpython-310.pyc,, +tensorflow/python/distribute/__pycache__/cross_device_utils.cpython-310.pyc,, +tensorflow/python/distribute/__pycache__/device_util.cpython-310.pyc,, +tensorflow/python/distribute/__pycache__/distribute_config.cpython-310.pyc,, +tensorflow/python/distribute/__pycache__/distribute_coordinator.cpython-310.pyc,, +tensorflow/python/distribute/__pycache__/distribute_coordinator_context.cpython-310.pyc,, +tensorflow/python/distribute/__pycache__/distribute_lib.cpython-310.pyc,, +tensorflow/python/distribute/__pycache__/distribute_utils.cpython-310.pyc,, +tensorflow/python/distribute/__pycache__/estimator_training.cpython-310.pyc,, +tensorflow/python/distribute/__pycache__/input_lib.cpython-310.pyc,, +tensorflow/python/distribute/__pycache__/input_ops.cpython-310.pyc,, +tensorflow/python/distribute/__pycache__/input_util.cpython-310.pyc,, +tensorflow/python/distribute/__pycache__/merge_call_interim.cpython-310.pyc,, +tensorflow/python/distribute/__pycache__/mirrored_run.cpython-310.pyc,, +tensorflow/python/distribute/__pycache__/mirrored_strategy.cpython-310.pyc,, +tensorflow/python/distribute/__pycache__/multi_process_lib.cpython-310.pyc,, +tensorflow/python/distribute/__pycache__/multi_process_runner.cpython-310.pyc,, +tensorflow/python/distribute/__pycache__/multi_worker_test_base.cpython-310.pyc,, +tensorflow/python/distribute/__pycache__/multi_worker_util.cpython-310.pyc,, +tensorflow/python/distribute/__pycache__/numpy_dataset.cpython-310.pyc,, +tensorflow/python/distribute/__pycache__/one_device_strategy.cpython-310.pyc,, +tensorflow/python/distribute/__pycache__/packed_distributed_variable.cpython-310.pyc,, +tensorflow/python/distribute/__pycache__/parameter_server_strategy.cpython-310.pyc,, +tensorflow/python/distribute/__pycache__/parameter_server_strategy_v2.cpython-310.pyc,, +tensorflow/python/distribute/__pycache__/ps_values.cpython-310.pyc,, +tensorflow/python/distribute/__pycache__/reduce_util.cpython-310.pyc,, +tensorflow/python/distribute/__pycache__/sharded_variable.cpython-310.pyc,, +tensorflow/python/distribute/__pycache__/shared_variable_creator.cpython-310.pyc,, +tensorflow/python/distribute/__pycache__/single_loss_example.cpython-310.pyc,, +tensorflow/python/distribute/__pycache__/step_fn.cpython-310.pyc,, +tensorflow/python/distribute/__pycache__/strategy_combinations.cpython-310.pyc,, +tensorflow/python/distribute/__pycache__/strategy_test_lib.cpython-310.pyc,, +tensorflow/python/distribute/__pycache__/summary_op_util.cpython-310.pyc,, +tensorflow/python/distribute/__pycache__/test_util.cpython-310.pyc,, +tensorflow/python/distribute/__pycache__/tpu_replicated_variable.cpython-310.pyc,, +tensorflow/python/distribute/__pycache__/tpu_strategy.cpython-310.pyc,, +tensorflow/python/distribute/__pycache__/tpu_util.cpython-310.pyc,, +tensorflow/python/distribute/__pycache__/tpu_values.cpython-310.pyc,, +tensorflow/python/distribute/__pycache__/values.cpython-310.pyc,, +tensorflow/python/distribute/__pycache__/values_util.cpython-310.pyc,, +tensorflow/python/distribute/__pycache__/values_v2.cpython-310.pyc,, +tensorflow/python/distribute/central_storage_strategy.py,sha256=9FZ05fmdapa9X3AXU9-Q2xXokM17VYQB5KumAukwnLM,9353 +tensorflow/python/distribute/cluster_resolver/__init__.py,sha256=zjAJD5VRc6VvZCxc7ziTlQIOc2gjQ1DHXVR-FyAO8fo,1867 +tensorflow/python/distribute/cluster_resolver/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/distribute/cluster_resolver/__pycache__/cluster_resolver.cpython-310.pyc,, +tensorflow/python/distribute/cluster_resolver/__pycache__/gce_cluster_resolver.cpython-310.pyc,, +tensorflow/python/distribute/cluster_resolver/__pycache__/kubernetes_cluster_resolver.cpython-310.pyc,, +tensorflow/python/distribute/cluster_resolver/__pycache__/sagemaker_cluster_resolver.cpython-310.pyc,, +tensorflow/python/distribute/cluster_resolver/__pycache__/slurm_cluster_resolver.cpython-310.pyc,, +tensorflow/python/distribute/cluster_resolver/__pycache__/tfconfig_cluster_resolver.cpython-310.pyc,, +tensorflow/python/distribute/cluster_resolver/__pycache__/tpu_cluster_resolver.cpython-310.pyc,, +tensorflow/python/distribute/cluster_resolver/cluster_resolver.py,sha256=g9Dz8ETSk6WrwPk5aBJ6eSK9k7XbPVMrbAKI9hJpvU0,23829 +tensorflow/python/distribute/cluster_resolver/gce_cluster_resolver.py,sha256=FLeYHy7_E4M4vwDushWT_ii4mD5lpWz2kI8Y2DARWMw,7660 +tensorflow/python/distribute/cluster_resolver/kubernetes_cluster_resolver.py,sha256=FmzY2CQGfcnrEmT0iQtNd6p3QX2wYXZBxCqEklVbRqY,7445 +tensorflow/python/distribute/cluster_resolver/sagemaker_cluster_resolver.py,sha256=n1ZN9LjYx1mpgpv_nIKeOB0JB3C2aXk3YRAiBlh-hTc,6784 +tensorflow/python/distribute/cluster_resolver/slurm_cluster_resolver.py,sha256=ABsRCWEQQhL_LBpul7fLQZmvnfLQ1qcknx60Cxcr9VI,14402 +tensorflow/python/distribute/cluster_resolver/tfconfig_cluster_resolver.py,sha256=--UMSFqnogZjl_sLLEQwPt2FFBGkPeAYgqnfo0zN0KU,6737 +tensorflow/python/distribute/cluster_resolver/tpu/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/distribute/cluster_resolver/tpu/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/distribute/cluster_resolver/tpu/__pycache__/tpu_cluster_resolver.cpython-310.pyc,, +tensorflow/python/distribute/cluster_resolver/tpu/tpu_cluster_resolver.py,sha256=FKMsU0hsaB5cXFVRuL713iF53nCh0_9pHB9YSQpt7ZA,18311 +tensorflow/python/distribute/cluster_resolver/tpu_cluster_resolver.py,sha256=JurfxS90OLhh8to-EsQSJdUzbB-kbbgRAuguuOk_bEU,1492 +tensorflow/python/distribute/collective_all_reduce_strategy.py,sha256=wtY-fM88B-2FhIX9D_L6iMC1saStIhddFn-JcMsUraw,43267 +tensorflow/python/distribute/collective_util.py,sha256=Bu8rs2z3Ak9l5G8DDrjx3MUKUvCj4eH30lh5kxc1w88,8885 +tensorflow/python/distribute/combinations.py,sha256=H0TSstxrvQXn4kZWCCEQsa2gCE4Ycyo5MDGRvQmThGU,24736 +tensorflow/python/distribute/coordinator/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/distribute/coordinator/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/distribute/coordinator/__pycache__/cluster_coordinator.cpython-310.pyc,, +tensorflow/python/distribute/coordinator/__pycache__/coordinator_context.cpython-310.pyc,, +tensorflow/python/distribute/coordinator/__pycache__/fault_tolerance_test_base.cpython-310.pyc,, +tensorflow/python/distribute/coordinator/__pycache__/metric_utils.cpython-310.pyc,, +tensorflow/python/distribute/coordinator/__pycache__/remote_value.cpython-310.pyc,, +tensorflow/python/distribute/coordinator/__pycache__/utils.cpython-310.pyc,, +tensorflow/python/distribute/coordinator/__pycache__/values.cpython-310.pyc,, +tensorflow/python/distribute/coordinator/__pycache__/watchdog.cpython-310.pyc,, +tensorflow/python/distribute/coordinator/cluster_coordinator.py,sha256=nGfVcvAjgFndhMCBjwlrItk4S1pcNmclQSIy-c7RcNY,78474 +tensorflow/python/distribute/coordinator/coordinator_context.py,sha256=059Vpj2MyPMopdkrX89scker8gLLh1b2mquk0gG3BvM,5020 +tensorflow/python/distribute/coordinator/fault_tolerance_test_base.py,sha256=1ukKjBr9lBE8ZKChfZz5e-MtnxCZwvqt1nWW0OLbHGU,25595 +tensorflow/python/distribute/coordinator/metric_utils.py,sha256=23L4pfWUeCKVqTc8ADsQQ7vliudLcprG2R-xigKnpLM,5659 +tensorflow/python/distribute/coordinator/remote_value.py,sha256=BTg-rk_sPF_ZJVEo8f02ibeKmJrQE2msJX1yDnxOmMY,4975 +tensorflow/python/distribute/coordinator/utils.py,sha256=IAqPacAibfHcoasJjfQad9vJGjD-m7cwdbMpv0za6bg,2596 +tensorflow/python/distribute/coordinator/values.py,sha256=eQR_PcV2IimYshV7XVjVQpg-nDTn-dxVFcohIuwnp0I,14272 +tensorflow/python/distribute/coordinator/watchdog.py,sha256=-XZsBJboyNj6qQKEngQROAZK16zmsDrJstHAv7ghais,2409 +tensorflow/python/distribute/cross_device_ops.py,sha256=vFp77_BJbnjIyOnGw_PH8hmlcEma8hYLZg_DwiMaxKc,57548 +tensorflow/python/distribute/cross_device_utils.py,sha256=SmgC9fGBnTtyv-d6qIm-sozecWGzueKvf2E8bn_7Tsc,27282 +tensorflow/python/distribute/device_util.py,sha256=ZrrQGe5xT8Yr5qhHxvBbOoP-aPdCG7GbatxsrwqpWiM,5563 +tensorflow/python/distribute/distribute_config.py,sha256=ANpmfUPyI7KXxRImEKuLp_sc_TLRn-5wBZGiduBu9Ro,1700 +tensorflow/python/distribute/distribute_coordinator.py,sha256=fa9Atg1ArJ4kWdAqLAMDGzB2eTqRSMUW8LHNVuwtw8I,34550 +tensorflow/python/distribute/distribute_coordinator_context.py,sha256=EUBDMLxHPeBvd5rrxRmZF8hffsfQZwxY_lr5VR2I0uc,968 +tensorflow/python/distribute/distribute_lib.py,sha256=jztptxoMdVB1nKqeyhjwXNXU-_hJ2tlcfPX97m955RE,179248 +tensorflow/python/distribute/distribute_utils.py,sha256=7TtPSjgQ1glCPXhEAachMQWDzlmiM_lK1cejv70vku8,19871 +tensorflow/python/distribute/estimator_training.py,sha256=_LgTyAONvVZqPr9r1LxE8e-J5Aq0qzO8BecvTPUH41Y,15991 +tensorflow/python/distribute/experimental/__init__.py,sha256=BqFMVf2LylitrClpl1jUrJdUCy5-QB0zbVz8Fpq3vlc,960 +tensorflow/python/distribute/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/distribute/experimental/__pycache__/dtensor_strategy_extended.cpython-310.pyc,, +tensorflow/python/distribute/experimental/__pycache__/dtensor_util.cpython-310.pyc,, +tensorflow/python/distribute/experimental/__pycache__/mirrored_strategy.cpython-310.pyc,, +tensorflow/python/distribute/experimental/__pycache__/multi_worker_mirrored_strategy.cpython-310.pyc,, +tensorflow/python/distribute/experimental/dtensor_strategy_extended.py,sha256=xAMvc43k4Wkpe-obMqwnYzVKIwAeVmj0jLcy81HKRAE,11727 +tensorflow/python/distribute/experimental/dtensor_util.py,sha256=T0owGszhbzLZ0gT_7oMwgE_YCMHnH6VRZ2OrMa0wM2A,12790 +tensorflow/python/distribute/experimental/mirrored_strategy.py,sha256=0wliuksi355-0SPemFGUbZZGBq7VJ9AKe2UC4NC_Jfo,4313 +tensorflow/python/distribute/experimental/multi_worker_mirrored_strategy.py,sha256=EzWzPHNqKqlX9X0O3_zgTAIEkUPaAl4s7zyTAchwwG0,6509 +tensorflow/python/distribute/experimental/rpc/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/distribute/experimental/rpc/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/distribute/experimental/rpc/__pycache__/rpc_ops.cpython-310.pyc,, +tensorflow/python/distribute/experimental/rpc/rpc_ops.py,sha256=rb2If1t5lGMm5iDO6hD8ZGnCrepF4oCRERenU2XoIdk,19161 +tensorflow/python/distribute/failure_handling/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/distribute/failure_handling/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/distribute/failure_handling/__pycache__/failure_handling.cpython-310.pyc,, +tensorflow/python/distribute/failure_handling/__pycache__/failure_handling_util.cpython-310.pyc,, +tensorflow/python/distribute/failure_handling/__pycache__/preemption_watcher.cpython-310.pyc,, +tensorflow/python/distribute/failure_handling/failure_handling.py,sha256=llV8Vzg5i2jUf3AKgxbkdKP0Mn4W30PyXN3bGJ-DY4M,56955 +tensorflow/python/distribute/failure_handling/failure_handling_util.py,sha256=hkDcO0E2QT2Pa0YR0c0YrZusaqTEQqnaTOdSvZ6CMy8,3983 +tensorflow/python/distribute/failure_handling/preemption_watcher.py,sha256=ToRQQmt7zerVXbBWcJ3Q2UhL4nvlhH-uik6J1c5AM6Q,5789 +tensorflow/python/distribute/input_lib.py,sha256=--mdnXSbT4tlfn5LwmBwk-o9qeMfoZxSnXv9SqTNHNU,78983 +tensorflow/python/distribute/input_ops.py,sha256=7JVsw17P8MGPXSST3an7PRvZ9XmFhJgPX-gzxxWtFak,4479 +tensorflow/python/distribute/input_util.py,sha256=cuWtc08Re5lKyMI5tP1d3-Z3iiT84n50AoxMLaODRB8,6114 +tensorflow/python/distribute/merge_call_interim.py,sha256=uubaP0A788b04Kh5H67ROpU97wBvNGj7gyZftNHt0rY,2311 +tensorflow/python/distribute/mirrored_run.py,sha256=P7XcRowarJA4DhSyzJI7av8BYZh56CuAFeF7WJeFM0I,23268 +tensorflow/python/distribute/mirrored_strategy.py,sha256=WUh3XzZNyd5yj09TD6qkuZdII7OprJLMQHreEnqBHmo,38265 +tensorflow/python/distribute/multi_process_lib.py,sha256=823jOkxrSgfcwXBK_ANqhkdoyrHA6CICVbQWTlIPW_E,5886 +tensorflow/python/distribute/multi_process_runner.py,sha256=SEJcu0tYp1dpLHzD3VpFK0g8COMV7pjv5lJesR6JRXk,57278 +tensorflow/python/distribute/multi_worker_test_base.py,sha256=pv_yhg3j2AHS0esuSMEphjzQNTWVobM49XA8YfdyP9k,29727 +tensorflow/python/distribute/multi_worker_util.py,sha256=x95ZwwUcM9gWnp4ASGbbei2CAWansk4ZQpceLurBEj8,10770 +tensorflow/python/distribute/numpy_dataset.py,sha256=2uwIffdMaw8tVAyitCniF3hOVDDA-xtSTMjMgxquJvM,3800 +tensorflow/python/distribute/one_device_strategy.py,sha256=U0zJpUxGoAKD8VM2byWk9hBrmemdf1Be5-jmZ-Yx75g,18677 +tensorflow/python/distribute/packed_distributed_variable.py,sha256=yZTl4nDhIo83F-5SoIZYZvvspilfAa39cdlh3hRImOQ,13819 +tensorflow/python/distribute/parallel_device/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/distribute/parallel_device/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/distribute/parallel_device/__pycache__/parallel_device.cpython-310.pyc,, +tensorflow/python/distribute/parallel_device/parallel_device.py,sha256=x96w6PqVqQxp1ggmccKHHJToibsviCrDBvI9yXBkqNI,9612 +tensorflow/python/distribute/parameter_server_strategy.py,sha256=jVbNDZVNl96X-azGF8VLutl6kn2ux5cejZm2ZGdgUVM,28342 +tensorflow/python/distribute/parameter_server_strategy_v2.py,sha256=UYgJf5RTdoKDl_1nLz_3poTv0e25dwpZYjk2SBu8TCc,45278 +tensorflow/python/distribute/ps_values.py,sha256=mJtlYiqHZObDvDW69NIo8iv8iidR70L80-MEVgm1w_k,34464 +tensorflow/python/distribute/reduce_util.py,sha256=eh9RxEtCVdbIs5ojcJiINzfG-kcKwlfuTYpzt0gop2M,1673 +tensorflow/python/distribute/sharded_variable.py,sha256=MqcUqcNfNBJrDE9bQjvGw7MLanjs59ficiRQIioHO5U,37847 +tensorflow/python/distribute/shared_variable_creator.py,sha256=t9ESnCVfze8zvXgx5bQtMod9jkMonS25HTeyfXiyW2k,3801 +tensorflow/python/distribute/single_loss_example.py,sha256=ku9RWxqPd2QtN2F0IlGHk-PRbFzTUB3XpE_H7b3t1Eo,4259 +tensorflow/python/distribute/step_fn.py,sha256=iv55xGUL5SI4YVDNhR4KkBCJYiZWqPzIMSHvFJQK6yI,4086 +tensorflow/python/distribute/strategy_combinations.py,sha256=LhEh-bvPlpYx_WMJAzVD7xsUFs_QzxiuGYl_cGaNSL8,27395 +tensorflow/python/distribute/strategy_test_lib.py,sha256=uS9fHHcWTI9i-nos6i7VP3g29TW7x72yFJ6QyR-jAqY,32890 +tensorflow/python/distribute/summary_op_util.py,sha256=SKqIbttXfprRyUe0kFy22zwZM_6y6wXeaqxO4w_XfwE,1796 +tensorflow/python/distribute/test_util.py,sha256=Tlrf2bB0TOQ-lfb-ssxK2XeX7TnTqRUrJnOteZWqSg4,10622 +tensorflow/python/distribute/tpu_replicated_variable.py,sha256=Xm43KmF7Ltk619MlG2z12byrR2WIyXYHtw8HCGewbOk,11804 +tensorflow/python/distribute/tpu_strategy.py,sha256=6bTeyBA8sOAAHZ0D8-xRYx8jLvUhGFGfOdvjDCjs8Rw,85565 +tensorflow/python/distribute/tpu_util.py,sha256=vv7CK6oqAwDyp8HUP79WYUfDtw7-qRSrcTzmQ7WoJxU,6781 +tensorflow/python/distribute/tpu_values.py,sha256=38yksO5Jar4059aN10NYxGua72GLlmunSqtx12Jjgpk,23419 +tensorflow/python/distribute/v1/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/distribute/v1/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/distribute/v1/__pycache__/all_reduce.cpython-310.pyc,, +tensorflow/python/distribute/v1/__pycache__/input_lib.cpython-310.pyc,, +tensorflow/python/distribute/v1/all_reduce.py,sha256=b7ig3rDUF47hEkZIOkFJeewj0GRrhHiNWGAKN1o_biE,32730 +tensorflow/python/distribute/v1/input_lib.py,sha256=xa7BZZd9GX4lZJXkjZJVd4AIPwd0mJWj0Z9O6iQcVow,16259 +tensorflow/python/distribute/values.py,sha256=ryCPIQIH-5WKwnhn6d07O35a69fcqDMK340UYhdOF7k,72095 +tensorflow/python/distribute/values_util.py,sha256=Pjg-f9CH-hdGV4zCNak7htJ7h3bcZ9MagfIgmZQALdo,14647 +tensorflow/python/distribute/values_v2.py,sha256=f1V9NylfVeXFS4kN-HgDivZ0H3IGMz_bpC8rfvF-Juw,10475 +tensorflow/python/dlpack/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/dlpack/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/dlpack/__pycache__/dlpack.cpython-310.pyc,, +tensorflow/python/dlpack/dlpack.py,sha256=txhy1c84HUGFIMh7DhuIM6On2Do4kV86xm4uq46eRpY,2117 +tensorflow/python/eager/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/eager/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/eager/__pycache__/backprop.cpython-310.pyc,, +tensorflow/python/eager/__pycache__/backprop_util.cpython-310.pyc,, +tensorflow/python/eager/__pycache__/benchmarks_test_base.cpython-310.pyc,, +tensorflow/python/eager/__pycache__/cancellation.cpython-310.pyc,, +tensorflow/python/eager/__pycache__/context.cpython-310.pyc,, +tensorflow/python/eager/__pycache__/core.cpython-310.pyc,, +tensorflow/python/eager/__pycache__/def_function.cpython-310.pyc,, +tensorflow/python/eager/__pycache__/execute.cpython-310.pyc,, +tensorflow/python/eager/__pycache__/executor.cpython-310.pyc,, +tensorflow/python/eager/__pycache__/forwardprop.cpython-310.pyc,, +tensorflow/python/eager/__pycache__/forwardprop_util.cpython-310.pyc,, +tensorflow/python/eager/__pycache__/function.cpython-310.pyc,, +tensorflow/python/eager/__pycache__/graph_only_ops.cpython-310.pyc,, +tensorflow/python/eager/__pycache__/imperative_grad.cpython-310.pyc,, +tensorflow/python/eager/__pycache__/lift_to_graph.cpython-310.pyc,, +tensorflow/python/eager/__pycache__/monitoring.cpython-310.pyc,, +tensorflow/python/eager/__pycache__/profiler.cpython-310.pyc,, +tensorflow/python/eager/__pycache__/profiler_client.cpython-310.pyc,, +tensorflow/python/eager/__pycache__/record.cpython-310.pyc,, +tensorflow/python/eager/__pycache__/remote.cpython-310.pyc,, +tensorflow/python/eager/__pycache__/tape.cpython-310.pyc,, +tensorflow/python/eager/__pycache__/test.cpython-310.pyc,, +tensorflow/python/eager/__pycache__/wrap_function.cpython-310.pyc,, +tensorflow/python/eager/backprop.py,sha256=yaRh0GCFvlCiI14j5sMqRkmAX6K1-0PVDn-0Ifku7Xg,50300 +tensorflow/python/eager/backprop_util.py,sha256=Rpdn1SW65s9oScBiVGH3mKMTjGn4XRNAzobikmw0Xa4,4430 +tensorflow/python/eager/benchmarks_test_base.py,sha256=BaY10RyZlpqGhKVJUkskOdsuynCFRyWUbUK8UgrcM7U,3446 +tensorflow/python/eager/cancellation.py,sha256=C3vh3XkRLhU1KWAWo6m4XVoN68kdOS46OPM-22XNgD4,2027 +tensorflow/python/eager/context.py,sha256=THO-PQZlE7cLH1wMEGoiElojhOhfmYv4dh_EWluwOkg,101047 +tensorflow/python/eager/core.py,sha256=oKdkTRLGherZgYfseN5LIyt2A_Pahpbw_P9d4qkuhvk,2744 +tensorflow/python/eager/def_function.py,sha256=ko5-zHwUB-tSuyssLtw_MeEl-sx1kbteBo_bb8NWyCs,1351 +tensorflow/python/eager/execute.py,sha256=LIG3p0g8rwfOXDzuOvO-zicPIHY4Zqva6X8fa_vo9xM,11535 +tensorflow/python/eager/executor.py,sha256=S3rbzKOIA8eDYzJg22YnrUiOaPr2L0C2lR2jP951uw4,2666 +tensorflow/python/eager/forwardprop.py,sha256=6vpkS3kUzV9giyXXf_vEIirTRf79kjr_lcKT0yKFhlQ,20517 +tensorflow/python/eager/forwardprop_util.py,sha256=sAWg-_70ZGqGbtDnCkZ6uSh2j8jD4ux7Vny0BYtQXII,2658 +tensorflow/python/eager/function.py,sha256=esgJEZzBYT8A2LB9jrzX_k6fj1-2sM2N5XZzK15xioA,1951 +tensorflow/python/eager/graph_only_ops.py,sha256=0I3QfVp71m_tGZH2Q4Z6_IOfOPnvzb73WUVGQYUJO68,2036 +tensorflow/python/eager/imperative_grad.py,sha256=zJIbhvazf3unTpVJsn9E4RcDZmYmyzDFM1kKdpxuNA0,2947 +tensorflow/python/eager/lift_to_graph.py,sha256=9SQbiK7cl3SchnW_bieX0glfiDAjNlaG7P0rc4hpbEU,14506 +tensorflow/python/eager/memory_tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/eager/memory_tests/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/eager/memory_tests/__pycache__/memory_test_util.cpython-310.pyc,, +tensorflow/python/eager/memory_tests/memory_test_util.py,sha256=2IItIsmrBj81g87x7ddEOjYEWSfpK4Vfn5LE1gHBIKk,2327 +tensorflow/python/eager/monitoring.py,sha256=9oi7uhtI0Nys2j1vF9yfK9ByRbywI-bdkCyxiXz4dcQ,16679 +tensorflow/python/eager/polymorphic_function/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/eager/polymorphic_function/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/eager/polymorphic_function/__pycache__/atomic_function.cpython-310.pyc,, +tensorflow/python/eager/polymorphic_function/__pycache__/attributes.cpython-310.pyc,, +tensorflow/python/eager/polymorphic_function/__pycache__/autograph_util.cpython-310.pyc,, +tensorflow/python/eager/polymorphic_function/__pycache__/compiler_ir.cpython-310.pyc,, +tensorflow/python/eager/polymorphic_function/__pycache__/composite_tensor_utils.cpython-310.pyc,, +tensorflow/python/eager/polymorphic_function/__pycache__/concrete_function.cpython-310.pyc,, +tensorflow/python/eager/polymorphic_function/__pycache__/eager_function_run.cpython-310.pyc,, +tensorflow/python/eager/polymorphic_function/__pycache__/function_context.cpython-310.pyc,, +tensorflow/python/eager/polymorphic_function/__pycache__/function_type_utils.cpython-310.pyc,, +tensorflow/python/eager/polymorphic_function/__pycache__/polymorphic_function.cpython-310.pyc,, +tensorflow/python/eager/polymorphic_function/__pycache__/saved_model_exported_concrete.cpython-310.pyc,, +tensorflow/python/eager/polymorphic_function/__pycache__/saved_model_utils.cpython-310.pyc,, +tensorflow/python/eager/polymorphic_function/__pycache__/tf_method_target.cpython-310.pyc,, +tensorflow/python/eager/polymorphic_function/__pycache__/tracing_compilation.cpython-310.pyc,, +tensorflow/python/eager/polymorphic_function/__pycache__/transform.cpython-310.pyc,, +tensorflow/python/eager/polymorphic_function/atomic_function.py,sha256=_Y1dFMVXE_-AzAarsuo0cZ9C_6RHHiADxRe0Uhbuz7A,25209 +tensorflow/python/eager/polymorphic_function/attributes.py,sha256=rDp-WiNRK48FtZViRI-Cx61vlOPjewPNdHYls3UEY7U,6380 +tensorflow/python/eager/polymorphic_function/autograph_util.py,sha256=bmRTEKtafD9MEKrtJU00G7q01XZLWHddZ3UKbdQMQmk,2212 +tensorflow/python/eager/polymorphic_function/compiler_ir.py,sha256=xJz4zXdyLi_tXpYWOuinMVBrsVRZXIeo1f2mw0X2oOY,3817 +tensorflow/python/eager/polymorphic_function/composite_tensor_utils.py,sha256=TFiBTP3JPfVcRS1M2xkbAfkEzEH0LTo2W108WJPrmtw,1853 +tensorflow/python/eager/polymorphic_function/concrete_function.py,sha256=CdpEZS2Zw6HW9qTT04waCv0HS4DJ1v9cGkbVRjqoixs,76133 +tensorflow/python/eager/polymorphic_function/eager_function_run.py,sha256=6pxTwp41bj4xlzhsLTIfBUhX0F3E0eUD7cH_1mhkfgs,4043 +tensorflow/python/eager/polymorphic_function/function_context.py,sha256=IcewdjrBSdVwMy0NpQ3YgziHZTaA1Pm3d9mbONt91fc,4882 +tensorflow/python/eager/polymorphic_function/function_type_utils.py,sha256=ykZTvsh45COcr9O4ZRTx_LU1LEZKkkp3KYD4CNz8tew,17425 +tensorflow/python/eager/polymorphic_function/polymorphic_function.py,sha256=aA-7wGMMmTojwDWrQwQmBO8osbqEkm5LduiAf5Szp4o,71086 +tensorflow/python/eager/polymorphic_function/saved_model_exported_concrete.py,sha256=yEg_MnxnmukuSp4yod-AiQMj3RBQOA0WrVBjBGE58pE,5167 +tensorflow/python/eager/polymorphic_function/saved_model_utils.py,sha256=EfsEW2PaGfO0eBFrMdhiTe8avud3NzuLrTOV4eF-Z9Q,3473 +tensorflow/python/eager/polymorphic_function/tf_method_target.py,sha256=RZh-Z9XI5x3-Lbwv9ZV8zzV85ZjhGBYUELpseQ3yXJ4,1841 +tensorflow/python/eager/polymorphic_function/tracing_compilation.py,sha256=l6RbLRqNigQM13J7AHJjaM9vHA8mwGP1sUCmirraWtA,13642 +tensorflow/python/eager/polymorphic_function/transform.py,sha256=PRlRn38rSNcp6eD0OfKFt4xrXmWHwnccnafNK3tWOfA,1306 +tensorflow/python/eager/profiler.py,sha256=ulLbbvtbLKsjoubM_fUY2f-h4BjUBJkb3cWq5aRHdTY,6457 +tensorflow/python/eager/profiler_client.py,sha256=xoJRV5ydy8iWLdq4Nh9idvuggLYBiVAKlVpgBnuWiHQ,2856 +tensorflow/python/eager/record.py,sha256=KnroPXE32MKYgF18E6LwimY5LAya9gL4Cw0P9l4_vbE,4436 +tensorflow/python/eager/remote.py,sha256=bclIdTYYJlyCB9q0f19VNtYCZs4TW0AyMmoVZV6HVKo,11791 +tensorflow/python/eager/tape.py,sha256=wJSYBFYaQl4jzLCrjHyoH2CjXwWlvp-_5DGABGLYj88,3475 +tensorflow/python/eager/test.py,sha256=9bsDmB_DRU6TxAIzQLRZcaBhgLl2Rhsj6B-ALkEmqP4,1068 +tensorflow/python/eager/wrap_function.py,sha256=ietkwhhfNn36w7xfqIDggZMZmGSQn4QeZhfj8dVCX2A,27457 +tensorflow/python/estimator/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/estimator/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/estimator/__pycache__/estimator.cpython-310.pyc,, +tensorflow/python/estimator/__pycache__/estimator_lib.cpython-310.pyc,, +tensorflow/python/estimator/__pycache__/exporter.cpython-310.pyc,, +tensorflow/python/estimator/__pycache__/gc.cpython-310.pyc,, +tensorflow/python/estimator/__pycache__/keras.cpython-310.pyc,, +tensorflow/python/estimator/__pycache__/model_fn.cpython-310.pyc,, +tensorflow/python/estimator/__pycache__/run_config.cpython-310.pyc,, +tensorflow/python/estimator/__pycache__/training.cpython-310.pyc,, +tensorflow/python/estimator/__pycache__/util.cpython-310.pyc,, +tensorflow/python/estimator/canned/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/estimator/canned/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/estimator/canned/__pycache__/baseline.cpython-310.pyc,, +tensorflow/python/estimator/canned/__pycache__/dnn.cpython-310.pyc,, +tensorflow/python/estimator/canned/__pycache__/dnn_linear_combined.cpython-310.pyc,, +tensorflow/python/estimator/canned/__pycache__/head.cpython-310.pyc,, +tensorflow/python/estimator/canned/__pycache__/linear.cpython-310.pyc,, +tensorflow/python/estimator/canned/__pycache__/metric_keys.cpython-310.pyc,, +tensorflow/python/estimator/canned/__pycache__/optimizers.cpython-310.pyc,, +tensorflow/python/estimator/canned/__pycache__/parsing_utils.cpython-310.pyc,, +tensorflow/python/estimator/canned/__pycache__/prediction_keys.cpython-310.pyc,, +tensorflow/python/estimator/canned/baseline.py,sha256=-az7FaqmZ4IAIm7-qoXhxxEehTGYu0dMBotmLIlpAJw,1178 +tensorflow/python/estimator/canned/dnn.py,sha256=V3mJ_jTOu-SB7Bbb96GMNULp2gfR0m-UoinWpqWlCjU,1153 +tensorflow/python/estimator/canned/dnn_linear_combined.py,sha256=mkDFImjD7AfmHuehxjwUYEdeWdTRGNK2AzU9iEhami4,1239 +tensorflow/python/estimator/canned/head.py,sha256=kY2bPN9yJiiEcLRVPJA4QsEhkGeE7W0d1pwLckTrImM,1158 +tensorflow/python/estimator/canned/linear.py,sha256=OTAYdwahOlp46EzOnC67ujddMKpCpGvskTTjAxjUr80,1168 +tensorflow/python/estimator/canned/metric_keys.py,sha256=H0-4MJgeTySKMg6jpS_adgQq5n4LmpgJh-kpXGlrU5g,1193 +tensorflow/python/estimator/canned/optimizers.py,sha256=cVgo8xhgJp6rs4Zb1U_wtdXJBxZApAGSBjOk40TvJqk,1188 +tensorflow/python/estimator/canned/parsing_utils.py,sha256=r9tcgYdxQbYvek6CblzmKTQg5TVWKkoydfuaOOA0ZmY,1209 +tensorflow/python/estimator/canned/prediction_keys.py,sha256=Ci4d-vm_XVLPrkqNdw4tVp261pS6g783BEm4S1SFWUc,1219 +tensorflow/python/estimator/estimator.py,sha256=PeAZY3yqCr1Ik4FMnY6WkVESgtilKVzQcnbbn-yXiI8,1169 +tensorflow/python/estimator/estimator_lib.py,sha256=9_toiqbhD6iaShua0I96kEY4FkU6vX7acsmQoIF19TU,1195 +tensorflow/python/estimator/export/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/estimator/export/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/estimator/export/__pycache__/export.cpython-310.pyc,, +tensorflow/python/estimator/export/__pycache__/export_lib.cpython-310.pyc,, +tensorflow/python/estimator/export/__pycache__/export_output.cpython-310.pyc,, +tensorflow/python/estimator/export/export.py,sha256=T4tUbwAEzlPML39cM5PBwKFVZ6ucnvoiCLyWjlmARx4,1168 +tensorflow/python/estimator/export/export_lib.py,sha256=H8Kup2VRw6psFUrmhJnqkl9Tz6B9tm6sm67Ez_04zmc,1188 +tensorflow/python/estimator/export/export_output.py,sha256=8C5ssHkDL1MzNvhp_AexIJj8W9yOXBZzLbvZsezMduE,1209 +tensorflow/python/estimator/exporter.py,sha256=GmYByK-UBR6Fjz1J_rm7gc5G85JpRV7C5W77sSEkPHw,1164 +tensorflow/python/estimator/gc.py,sha256=R-ksBhHfPauQW55_Qziv3FXLjjyoAN54dGTv_R5MIuw,1134 +tensorflow/python/estimator/inputs/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/estimator/inputs/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/estimator/inputs/__pycache__/inputs.cpython-310.pyc,, +tensorflow/python/estimator/inputs/__pycache__/numpy_io.cpython-310.pyc,, +tensorflow/python/estimator/inputs/__pycache__/pandas_io.cpython-310.pyc,, +tensorflow/python/estimator/inputs/inputs.py,sha256=u7UOe-9ytPoJIsaSz17VnEKbDNe07U69gl-_CP8X4ZM,1168 +tensorflow/python/estimator/inputs/numpy_io.py,sha256=l3zhEUxHsas5qshtZTL6AJVoJny2Ic-DX1-Spn7WcnI,1178 +tensorflow/python/estimator/inputs/pandas_io.py,sha256=skR3BWubHC4yI_wQ460a_IyvFRA64_EjyPd7bPZYzIM,1183 +tensorflow/python/estimator/inputs/queues/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/estimator/inputs/queues/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/estimator/inputs/queues/__pycache__/feeding_functions.cpython-310.pyc,, +tensorflow/python/estimator/inputs/queues/__pycache__/feeding_queue_runner.cpython-310.pyc,, +tensorflow/python/estimator/inputs/queues/feeding_functions.py,sha256=IDAfpx_nzEPLsttWcf9PQFmuu-NZzNJmKRsr-YGoT_o,1243 +tensorflow/python/estimator/inputs/queues/feeding_queue_runner.py,sha256=iFTnkJ-MbPBEj6Svx7V2jH__BI1tVfua57reQd4nruY,1258 +tensorflow/python/estimator/keras.py,sha256=uWXIriYaNdZbmGDY2joaiBcdFNDMY6LbWVvewBDUD4w,1165 +tensorflow/python/estimator/model_fn.py,sha256=SnO_cY_ZGlwn-9dAwlEgvYc2eM95NK39WScgC-6iUx8,1164 +tensorflow/python/estimator/run_config.py,sha256=DDu8YI5tV81A2VUQYlHwXVH5x7gBFXA5DxVsyntNibA,1174 +tensorflow/python/estimator/training.py,sha256=keZdqyJSrjz2SXrubRp0kUtPa6kacY7wElvmo3Gfivg,1164 +tensorflow/python/estimator/util.py,sha256=x_33pFkMl2u-lcFTumHVvK0hmw8FvcUVxQoCa5HXqj8,1144 +tensorflow/python/feature_column/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/feature_column/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/feature_column/__pycache__/feature_column.cpython-310.pyc,, +tensorflow/python/feature_column/__pycache__/feature_column_lib.cpython-310.pyc,, +tensorflow/python/feature_column/__pycache__/feature_column_v2.cpython-310.pyc,, +tensorflow/python/feature_column/__pycache__/feature_column_v2_types.cpython-310.pyc,, +tensorflow/python/feature_column/__pycache__/sequence_feature_column.cpython-310.pyc,, +tensorflow/python/feature_column/__pycache__/serialization.cpython-310.pyc,, +tensorflow/python/feature_column/__pycache__/utils.cpython-310.pyc,, +tensorflow/python/feature_column/feature_column.py,sha256=qhyBafKZ3mE5Bk0-WlQ0aNFfToEv-2Br0memWWnNTRA,129296 +tensorflow/python/feature_column/feature_column_lib.py,sha256=JGtWBgSaF8lhEmKodS5vAoIHziVXqm48gCUq7kBx2oc,1144 +tensorflow/python/feature_column/feature_column_v2.py,sha256=VKp-H23Mj8ZwTEtkiUZ55yKtlOnr0IErOwPpOTdpcD8,179362 +tensorflow/python/feature_column/feature_column_v2_types.py,sha256=gHMsxoEvIGUyAJyoivmnUR2sUpMTQ2KHAwe_GQSuZ5c,9822 +tensorflow/python/feature_column/sequence_feature_column.py,sha256=kIe7ANHpxC4iB433BgKQWorVhJkUaMZQm2by9OwKG78,20567 +tensorflow/python/feature_column/serialization.py,sha256=dAQ6RG0qLCzG0BvToJrwIKspkgMvzqY5C5ixp9FUyGM,13251 +tensorflow/python/feature_column/utils.py,sha256=iDJVFlMy-2IcguEnYKEbraUCSiZ0zTEh8GR0jqfBTA8,6018 +tensorflow/python/flags_pybind.pyi,sha256=hVTf_Tpi0t4Kb_01HfcRZ800gIBkWb0ppfUZ5fuRP-E,1248 +tensorflow/python/flags_pybind.so,sha256=MspICpY8wdCEjvuatcoFJCbTc3GGT3-BPAQ0rz1S4TA,256320 +tensorflow/python/framework/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/framework/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/auto_control_deps.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/auto_control_deps_utils.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/byte_swap_tensor.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/c_api_util.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/combinations.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/common_shapes.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/composite_tensor.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/composite_tensor_gradient.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/config.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/constant_op.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/convert_to_constants.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/cpp_shape_inference_pb2.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/device.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/device_spec.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/dtypes.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/error_interpolation.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/errors.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/errors_impl.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/extension_type.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/extension_type_field.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/flexible_dtypes.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/framework_lib.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/func_graph.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/function.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/function_def_to_graph.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/gpu_util.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/graph_io.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/graph_to_function_def.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/graph_util.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/graph_util_impl.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/immutable_dict.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/importer.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/indexed_slices.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/kernels.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/load_library.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/memory_checker.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/meta_graph.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/none_tensor.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/op_callbacks.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/op_def_library.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/op_def_library_pybind.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/op_def_registry.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/ops.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/python_memory_checker.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/random_seed.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/registry.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/smart_cond.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/sparse_tensor.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/stack.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/strict_mode.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/subscribe.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/tensor.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/tensor_conversion.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/tensor_conversion_registry.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/tensor_shape.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/tensor_spec.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/tensor_util.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/test_combinations.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/test_ops.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/test_util.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/tfrt_utils.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/traceable_stack.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/type_spec.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/type_spec_registry.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/type_utils.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/versions.cpython-310.pyc,, +tensorflow/python/framework/__pycache__/weak_tensor.cpython-310.pyc,, +tensorflow/python/framework/_dtypes.pyi,sha256=DYyc525wnLyENSBaEeTbrzzOXAyM2yur63RIKbjNmGk,1446 +tensorflow/python/framework/_dtypes.so,sha256=kjA6LgREH79FPVuHCnEgsgMOCZLLZrEEPD1OtjDNQbs,216056 +tensorflow/python/framework/_errors_test_helper.pyi,sha256=_SPQCCl6L3Wmy9heGFnVDsMRuwYaxmGkhnb1UnbGdQU,786 +tensorflow/python/framework/_errors_test_helper.so,sha256=2mkHmrD_MR-8uwZfTKTeW0kmHYEGOen4CBdJ38FRq50,285936 +tensorflow/python/framework/_op_def_library_pybind.pyi,sha256=uyPCOiL_0WiOo_fOqNij3M3hdO7PIED9Bvmc8Gqc19E,757 +tensorflow/python/framework/_op_def_library_pybind.so,sha256=ubtix0M2bqMQRkXSOi-rQdmpNte5hO0FZmGpEiqdSuI,365392 +tensorflow/python/framework/_op_def_registry.pyi,sha256=svM0wYX_31uuFnvrE_NO7-HcFotR3AkAGaX17Ztau18,724 +tensorflow/python/framework/_op_def_registry.so,sha256=-wElntOB8MjNYItHtYzmc4AHrXtuIYcgovTjSOP8THw,252384 +tensorflow/python/framework/_proto_comparators.pyi,sha256=wJpqY5TcEeroNKBNFEl1bnb0XXVc6gKk63-Lgms4fLc,853 +tensorflow/python/framework/_proto_comparators.so,sha256=vCA6tQ39rHiC-R84hsNY2cVsownDg_9XkOtuAG2ZxgY,316128 +tensorflow/python/framework/_python_memory_checker_helper.pyi,sha256=TOLSJ-n0WE2xOlCDVDYbrevA7RuHTA2NJxM5086q-Yc,778 +tensorflow/python/framework/_python_memory_checker_helper.so,sha256=gxJkXGGggIozjILHBUTQM8w4FLY_QsM2GiCGf723vwQ,138736 +tensorflow/python/framework/_pywrap_python_api_dispatcher.pyi,sha256=iXAxPzqL-2NuM8mDGo5tC_kjFVAyxbqAOxBPZvns8_c,2357 +tensorflow/python/framework/_pywrap_python_api_dispatcher.so,sha256=Zvj-VhmQlUuPxb7luOh6GWwp9JJjZnDnAN530jLuEfU,396912 +tensorflow/python/framework/_pywrap_python_api_info.pyi,sha256=7TPfUINV1sd6wlB8J9HqB2ZLH9At64yLen5QIWf-WU8,1395 +tensorflow/python/framework/_pywrap_python_api_info.so,sha256=E62-ez7kddQV_Arbh08lsxSYoiPRwSm7EcNgWXfb-Jc,367992 +tensorflow/python/framework/_pywrap_python_api_parameter_converter.pyi,sha256=_Mzv0CI9OOqzngdofv1Fy7xfDp3n_Ic4E1i2CZAHoBQ,755 +tensorflow/python/framework/_pywrap_python_api_parameter_converter.so,sha256=jpfsNHdK-Ey9mWd6afFXRL_kj7ecXg54_ttIC_sjyh8,246072 +tensorflow/python/framework/_pywrap_python_op_gen.pyi,sha256=SPaXr5FbE95_xKmuxQGJF3RuYIY_JnttTEtKEMXKy90,739 +tensorflow/python/framework/_pywrap_python_op_gen.so,sha256=D2S9aMn3cMSjQ8oebGSFMxlAu_2T8nY9n9j56Qx3k38,143080 +tensorflow/python/framework/_test_metrics_util.pyi,sha256=3RzQAOK4RzFIR7NYLC2BI4JQ1ggXK7tM6HN8OGUT6mI,747 +tensorflow/python/framework/_test_metrics_util.so,sha256=7CVRXygD8alx5RDGyEiQ4_Qs-oh5fYFvT30aZ4m5ED0,228904 +tensorflow/python/framework/auto_control_deps.py,sha256=4SRy27B76MoqiRI09Mviv_J2cpV4Yrnf96hj66YJWjo,26451 +tensorflow/python/framework/auto_control_deps_utils.py,sha256=UmAWbvM4UR3uf33gZkeoLDuggaahKen8t4TIHK2VBUc,5418 +tensorflow/python/framework/byte_swap_tensor.py,sha256=srWvd19W3DgAEp6A3DhZeHNqh7cgqfiJiBit2Nkbfqk,3315 +tensorflow/python/framework/c_api_util.py,sha256=csEiGZHUI0Qc4JBmcS_lUGKYa-zP9B_2mpYW8hwnJtg,7408 +tensorflow/python/framework/combinations.py,sha256=L2nalrbSTul-IZ5FxsS8AEwbFJrtp4Az2V9ixiL6sAw,2998 +tensorflow/python/framework/common_shapes.py,sha256=lJ0Li0-WPA-trau70Re1nfIECdq8nv-2bstH2rHtMYA,3961 +tensorflow/python/framework/composite_tensor.py,sha256=wQOIvFKcVlK1yj6tN6ASENc7NUhJmhcvXLu1WZ4Nf0w,5779 +tensorflow/python/framework/composite_tensor_gradient.py,sha256=Q39BSDpShp_1YJ_60f57P0vashQLHIa0yQ8fPzeH77E,6530 +tensorflow/python/framework/config.py,sha256=CteS59Yhd1OORBPQQLpWwT-Gm3F31odqwtdy9Vlha2s,46710 +tensorflow/python/framework/constant_op.py,sha256=AK47n7xLjg0NuzA1zfuDEwhD-p7qaWZKESmbRKopGYg,17063 +tensorflow/python/framework/convert_to_constants.py,sha256=jRIWxheRTNr4cICEEyfPbqgLLgIfV4buBkkPsZiBez0,50582 +tensorflow/python/framework/cpp_shape_inference_pb2.py,sha256=r831ES8WpYbqbWP7H7H1RWCP6QRLmLDg2N0LfRAGjL8,2944 +tensorflow/python/framework/device.py,sha256=I6k9k-oxHGydBmvhTr1b0PQXhQH-ZsnrFxhrlu57uek,5961 +tensorflow/python/framework/device_spec.py,sha256=YdnLfqfysKojQCOQSImAvy29vnyexQjjHtOcJN2b_gg,15863 +tensorflow/python/framework/dtypes.py,sha256=SifG_IbcHmS-3NANoIbLcNyGynLI5o9X_9tZAqf0Mi4,29353 +tensorflow/python/framework/error_interpolation.py,sha256=ZrtBNN2rkplJDHPfTYEcSmPkK6NAx_jEg9zVXwhq6fM,15414 +tensorflow/python/framework/errors.py,sha256=xfWgTgcXn-vtG9mAD8hqlLu-8OK_awwwPF3N_G2luBA,1039 +tensorflow/python/framework/errors_impl.py,sha256=joxVsgY-0ardIG0yKIxrHZKQ0d3Re2C2ImomfL3TxK4,20633 +tensorflow/python/framework/extension_type.py,sha256=4FzGEJ5yrFdk7_5scvLH7ZXXvEXIYV7eesQnvfdrxOo,47654 +tensorflow/python/framework/extension_type_field.py,sha256=TXChqzc-yl8TS16DXKXRnaetndJHupx7DDGMSbR5pFc,16398 +tensorflow/python/framework/fast_tensor_util.so,sha256=Qmgnrv6d5y_YbL3XzsvFJjcDfwhkCWYKs_cj7XMhozM,117816 +tensorflow/python/framework/flexible_dtypes.py,sha256=ZTRpxWZiF3qnx2q4bOQc7fW747ue3vboc7SK2iPAqbM,18236 +tensorflow/python/framework/framework_lib.py,sha256=qSFjfqLPnUwfA2N0VRUaCu8c58gDcaF6GUyMeva0o6Q,3469 +tensorflow/python/framework/func_graph.py,sha256=6RWDECsPXQzUw6Ehj9iZSWVwbKrfc4vHrB5a9jHfGiI,52435 +tensorflow/python/framework/function.py,sha256=alRAQ0o5DCJommtKKvjCjW2uvwFCAoFjVD94A1AKav8,50508 +tensorflow/python/framework/function_def_to_graph.py,sha256=4RRXMAaTBjoXeuztoP0OY9euUEWEQWOVuEyqdTYltP0,17388 +tensorflow/python/framework/gpu_util.py,sha256=G8LE3HVkvVFzRTsKxnkgIIAZ9VPW6UomQf1rl0j6dMA,2063 +tensorflow/python/framework/graph_io.py,sha256=TVD-qRyDxZYaQNxHiiQB4l8OpLFsDZaedYsNniw5-eo,2872 +tensorflow/python/framework/graph_to_function_def.py,sha256=o5q_Uv7gw0D9X7oLsi5IJ1g3tHF54PA-Y3z7D45MAtY,6698 +tensorflow/python/framework/graph_util.py,sha256=39BzImsENbMn3sfpw1UdqOflTr8cr_-jgu_rvGt3vdM,1233 +tensorflow/python/framework/graph_util_impl.py,sha256=_WG5U_R8qikoBSOgM5Vn_t12FyHjqKBrzZkA97TiDto,14336 +tensorflow/python/framework/immutable_dict.py,sha256=6hGuwjOX5mMaqx0PS6VHuLNhscfOk_x7gUpEqgMUwP0,1562 +tensorflow/python/framework/importer.py,sha256=ApD4gTvA0NS2UZV8DnrxfBE7lZpLVB0kp1hMT2Mzj3Y,23137 +tensorflow/python/framework/indexed_slices.py,sha256=PT68FvetqY7l5CF8WMU89V6_ZdZcqS2u8S532JsiSgQ,16722 +tensorflow/python/framework/kernels.py,sha256=3C0b0uBs6kHIu068sZMjHS7DyYOUqiMemdOtuHHuEX0,1599 +tensorflow/python/framework/load_library.py,sha256=uCqasq7Jvjpl9NRMG0g3ewRekQFi8bK4n03X3h4amSQ,7458 +tensorflow/python/framework/memory_checker.py,sha256=g-C96u-QwiuPBnkDBHN-3qfbaTmwA1qOO42lNp720zg,5108 +tensorflow/python/framework/meta_graph.py,sha256=GEhh2ZScRwOnSgCnhR__-UaQ3K5WQKdtSKIF8ctSqgY,43692 +tensorflow/python/framework/none_tensor.py,sha256=182c7LBVswnJS06bnPL-QZ35x82M8-xg0sEJTKv93FI,2418 +tensorflow/python/framework/op_callbacks.py,sha256=ZK1u68kMuuWNn3kaQQew_NWe36cuNrAI49faapOMNG8,9083 +tensorflow/python/framework/op_def_library.py,sha256=unUB7GmAJkh8Hep2zMwccbo-PrYLy_T5NnMlIxs81CM,34905 +tensorflow/python/framework/op_def_library_pybind.py,sha256=oO6aQxItpHnh1h-sOsh8ypTikK-W8YmqzFXM8fy9lqg,1450 +tensorflow/python/framework/op_def_registry.py,sha256=pazDKGTNSN1dZrhizk9zE8at_wPpOKVDQS5P8jzbYFU,1880 +tensorflow/python/framework/ops.py,sha256=Og1iIQTw4ClRZbAyIfU3f86c8LqMQ3lOu1WaXYlSf90,225452 +tensorflow/python/framework/python_memory_checker.py,sha256=dQEIvJkpQZXGJU__-AU0VvVqZcbQozo210TL9W3eQoY,5269 +tensorflow/python/framework/random_seed.py,sha256=vor-Gd5mHcoTFC7nO1wovEOgcxtJRao6nGOJSgY0NCg,12408 +tensorflow/python/framework/registry.py,sha256=r3WwsCq-uLcDLaoCTKiIhXaOznEqaUjYUsi1ScE_wxw,3157 +tensorflow/python/framework/smart_cond.py,sha256=lG4KIPJF8H8ykwVbzurKFRddatJ4S33xYiQjNXyeRZc,4506 +tensorflow/python/framework/sparse_tensor.py,sha256=EfaD6O28tLD76SYiK9ZxHNKeIHNDpzOjD3CRBOlrtj4,21370 +tensorflow/python/framework/stack.py,sha256=s0lxgt0x8hdXm8yHDe60DbyG2J1Yas5dzVnBLT3HkmU,4153 +tensorflow/python/framework/strict_mode.py,sha256=pGbakn81BP1gmxtvPnNCJIOKIDjReR_TqCxYoTdWrQc,1057 +tensorflow/python/framework/subscribe.py,sha256=nhNp0h3cATifEF02iOvxhky-RWdQEHBlwXP01L0EiYc,13004 +tensorflow/python/framework/tensor.py,sha256=8psmuUbHSZ5y5Kn4j8k-lsqPzNoplT40Jo_TDLHTSTk,52128 +tensorflow/python/framework/tensor_conversion.py,sha256=kZiaUbo2Nyz7hRiFm06DRT7zKYo3kz5-zZ2wYHCVBxA,6761 +tensorflow/python/framework/tensor_conversion_registry.py,sha256=YeMGxCSIHBLkRp06AQI8-Y31ILdWyBbJ6oc1s3a33_U,10429 +tensorflow/python/framework/tensor_shape.py,sha256=yWKPLVH5wmSJC5YnTy3QQXk8UQaHePK_Mc1zpK9aVPA,50930 +tensorflow/python/framework/tensor_spec.py,sha256=CaCHGG7JN4P7qtpLm3_J2p1FkjbPg5mWe9QXXycoD-U,1077 +tensorflow/python/framework/tensor_util.py,sha256=zLEHc-9q5MbUYhbPQ8Wwx8H7VwSsJYwmL9Dv_TBlns0,42940 +tensorflow/python/framework/test_combinations.py,sha256=-oWaThiTrrMfazJlENJ7fjLtKCINvGQaFYD9wRyET6I,16270 +tensorflow/python/framework/test_ops.py,sha256=7IC05bawg7_5bsMV-CleZyMYpaQcXP1p6dW0FfnlyuY,305888 +tensorflow/python/framework/test_util.py,sha256=9r0uqFjhPwaFF2RnnYbVhaVjOMrLh1qt2xIS3bCjSVY,146854 +tensorflow/python/framework/tfrt_utils.py,sha256=EhxHhMOydapkHjw7rz5P5WJu4u5TvIAvBF39R8EpL4A,805 +tensorflow/python/framework/traceable_stack.py,sha256=QWur7HS9fMqdB4IUCFWGzFG5hp3RuGIRsq8Tl5ONZ00,4853 +tensorflow/python/framework/type_spec.py,sha256=I1Mv3UTAJrbzr7H3T05yr9fx1xayRgwQ4HGiDgMA8Rw,41097 +tensorflow/python/framework/type_spec_registry.py,sha256=8XugsEnUj1-ZEj94ZuVlxhjesxS89uLoSO6NUsMkaBM,3553 +tensorflow/python/framework/type_utils.py,sha256=kq3h718tfUGv2jN9kFQ4KX9Y9tekYX8E-jlutVDZtK4,8356 +tensorflow/python/framework/versions.py,sha256=Scc02FgWiMx0eILeBMcxwbuh0tduNda4FYqjdNbPwdg,3674 +tensorflow/python/framework/weak_tensor.py,sha256=Zspb4cnd-m8sX24r8djF6-ie9Hcav-8i3limxDgpUcU,8750 +tensorflow/python/grappler/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/grappler/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/grappler/__pycache__/cluster.cpython-310.pyc,, +tensorflow/python/grappler/__pycache__/item.cpython-310.pyc,, +tensorflow/python/grappler/__pycache__/tf_optimizer.cpython-310.pyc,, +tensorflow/python/grappler/_pywrap_tf_cluster.pyi,sha256=xEd24EwtcXujQP12BNsTXs8Xbr3eRRaCBhyJUY-wN9M,1363 +tensorflow/python/grappler/_pywrap_tf_cluster.so,sha256=qkDQPhuaUejje5AX4Pw13EaTjLvP5z9HkAa-5iUqqFk,391160 +tensorflow/python/grappler/_pywrap_tf_item.pyi,sha256=cHHV5q9q4_ZBZmdthzzkoLjqJZBFCmyAt2twlDPYRKM,1059 +tensorflow/python/grappler/_pywrap_tf_item.so,sha256=5IAMRHVIEj67eeaWl55O896IhpDnimEq9_w4eYwHIhQ,905072 +tensorflow/python/grappler/_pywrap_tf_optimizer.pyi,sha256=qtuh7CcfB5clBjvSkJOB8_-8C9EG0f6tXcdjzCxRHYE,872 +tensorflow/python/grappler/_pywrap_tf_optimizer.so,sha256=--vRRLizBW41ZMyfe0FzpPad7SnXVcnaU3q3CtRHQ-k,1832296 +tensorflow/python/grappler/cluster.py,sha256=hgwdOwfaVoY6ur9e37kxX1KGs4ApDwLTsVLxG2CfsGQ,4362 +tensorflow/python/grappler/item.py,sha256=eb7sBU-3Q3Unr2Q5i4wmCZT1vUHBBdVijimpyNxGjm8,3161 +tensorflow/python/grappler/tf_optimizer.py,sha256=B1xiFJxvfOMsaEXo_iIpvTxDWT5wxCnx3DRGG0vwwIc,3585 +tensorflow/python/keras/__init__.py,sha256=Ycly56WwYTZfniSOSpqrRd9DoRJRTkXzw6avPq9AUd8,1256 +tensorflow/python/keras/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/keras/__pycache__/activations.cpython-310.pyc,, +tensorflow/python/keras/__pycache__/backend.cpython-310.pyc,, +tensorflow/python/keras/__pycache__/backend_config.cpython-310.pyc,, +tensorflow/python/keras/__pycache__/callbacks.cpython-310.pyc,, +tensorflow/python/keras/__pycache__/callbacks_v1.cpython-310.pyc,, +tensorflow/python/keras/__pycache__/combinations.cpython-310.pyc,, +tensorflow/python/keras/__pycache__/constraints.cpython-310.pyc,, +tensorflow/python/keras/__pycache__/keras_parameterized.cpython-310.pyc,, +tensorflow/python/keras/__pycache__/losses.cpython-310.pyc,, +tensorflow/python/keras/__pycache__/metrics.cpython-310.pyc,, +tensorflow/python/keras/__pycache__/models.cpython-310.pyc,, +tensorflow/python/keras/__pycache__/optimizer_v1.cpython-310.pyc,, +tensorflow/python/keras/__pycache__/optimizers.cpython-310.pyc,, +tensorflow/python/keras/__pycache__/regularizers.cpython-310.pyc,, +tensorflow/python/keras/__pycache__/testing_utils.cpython-310.pyc,, +tensorflow/python/keras/activations.py,sha256=f-5oPwqMh7HM91AxvCNJSuVnG3O1myVBnpMynbFAvMk,18234 +tensorflow/python/keras/backend.py,sha256=fhZhA3CmOUfFJ4mvUv5li-Ws3MSUnGGuZBoQSYlsDOA,205761 +tensorflow/python/keras/backend_config.py,sha256=uVRp4nCtINkFQ6flTJjRd5TcFJrw8JHy4sbeXWTURXc,3777 +tensorflow/python/keras/callbacks.py,sha256=kA6dDU2g3ZpIwKyaT7ZVyFVTNvbKU2Q7gCKq62gQN2k,109727 +tensorflow/python/keras/callbacks_v1.py,sha256=hz-Dh-ard1VfHd9r4LQCpLIvIYqjZuLgQyDi1oEQVBU,19759 +tensorflow/python/keras/combinations.py,sha256=-8js8G2K5tRTXBxvN1Qz7DamVtmDipS6zONm-Csq8NY,3797 +tensorflow/python/keras/constraints.py,sha256=sOLzCq9Ubd4wtRjjHszUjbHrFh_lz6-FgBsGk9LwThQ,11444 +tensorflow/python/keras/distribute/__init__.py,sha256=u0zaRT5pA0aERhbGzrRRknozmqJiQChH_GSieFI_awU,733 +tensorflow/python/keras/distribute/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/keras/distribute/__pycache__/distribute_coordinator_utils.cpython-310.pyc,, +tensorflow/python/keras/distribute/__pycache__/distributed_file_utils.cpython-310.pyc,, +tensorflow/python/keras/distribute/__pycache__/distributed_training_utils.cpython-310.pyc,, +tensorflow/python/keras/distribute/__pycache__/distributed_training_utils_v1.cpython-310.pyc,, +tensorflow/python/keras/distribute/__pycache__/worker_training_state.cpython-310.pyc,, +tensorflow/python/keras/distribute/distribute_coordinator_utils.py,sha256=x8qjh901BzokiyOwjjw4e2qpb78JiKx7R9aXQiI9FDE,27121 +tensorflow/python/keras/distribute/distributed_file_utils.py,sha256=zlBUA7baJTMVJeUbtZN99L-32lZQ5VNj9GJ9QFbKiLs,5442 +tensorflow/python/keras/distribute/distributed_training_utils.py,sha256=9IrKbgFSWjJiJBduG2IRv6yWa0_YBxoOb_uTTtyYzMY,2473 +tensorflow/python/keras/distribute/distributed_training_utils_v1.py,sha256=SG4dsezvMYf6nkweaqvThuHferpV3WhzCFapSbo-hqk,47120 +tensorflow/python/keras/distribute/worker_training_state.py,sha256=IN0I3emvs-RqBkayv9PpKRd7YFznoXr_2i4-K9Mni6c,6091 +tensorflow/python/keras/engine/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/keras/engine/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/keras/engine/__pycache__/base_layer.cpython-310.pyc,, +tensorflow/python/keras/engine/__pycache__/base_layer_utils.cpython-310.pyc,, +tensorflow/python/keras/engine/__pycache__/base_layer_v1.cpython-310.pyc,, +tensorflow/python/keras/engine/__pycache__/base_preprocessing_layer.cpython-310.pyc,, +tensorflow/python/keras/engine/__pycache__/compile_utils.cpython-310.pyc,, +tensorflow/python/keras/engine/__pycache__/data_adapter.cpython-310.pyc,, +tensorflow/python/keras/engine/__pycache__/functional.cpython-310.pyc,, +tensorflow/python/keras/engine/__pycache__/input_layer.cpython-310.pyc,, +tensorflow/python/keras/engine/__pycache__/input_spec.cpython-310.pyc,, +tensorflow/python/keras/engine/__pycache__/keras_tensor.cpython-310.pyc,, +tensorflow/python/keras/engine/__pycache__/node.cpython-310.pyc,, +tensorflow/python/keras/engine/__pycache__/partial_batch_padding_handler.cpython-310.pyc,, +tensorflow/python/keras/engine/__pycache__/saving.cpython-310.pyc,, +tensorflow/python/keras/engine/__pycache__/sequential.cpython-310.pyc,, +tensorflow/python/keras/engine/__pycache__/training.cpython-310.pyc,, +tensorflow/python/keras/engine/__pycache__/training_arrays_v1.cpython-310.pyc,, +tensorflow/python/keras/engine/__pycache__/training_distributed_v1.cpython-310.pyc,, +tensorflow/python/keras/engine/__pycache__/training_eager_v1.cpython-310.pyc,, +tensorflow/python/keras/engine/__pycache__/training_generator_v1.cpython-310.pyc,, +tensorflow/python/keras/engine/__pycache__/training_utils.cpython-310.pyc,, +tensorflow/python/keras/engine/__pycache__/training_utils_v1.cpython-310.pyc,, +tensorflow/python/keras/engine/__pycache__/training_v1.cpython-310.pyc,, +tensorflow/python/keras/engine/base_layer.py,sha256=59C1dT0I2Knozm-mjnU87P4Mxw2Hkx-5StnuBUwT0n0,130672 +tensorflow/python/keras/engine/base_layer_utils.py,sha256=pf5s26A1ogcR4PwG-15EZa2imTSqHwrEx7E2cr5H9CI,33225 +tensorflow/python/keras/engine/base_layer_v1.py,sha256=ABw7nLJ1lWlBV9UF571DCQJT9T9A0GZziLHAUlBEkrE,97962 +tensorflow/python/keras/engine/base_preprocessing_layer.py,sha256=ODc7yIvb_bkEjD5pasoeXfaJKBk3bNWc64fcYVC-DaY,23669 +tensorflow/python/keras/engine/compile_utils.py,sha256=67gM4EF2ieaUP74bUdq3cxx7aqyNbYkBB5q5oqpw6Yw,25547 +tensorflow/python/keras/engine/data_adapter.py,sha256=RjQ3PCsM6bOMJfO3SFfIC8neEgljr6xfdUt1MgT6e-U,58995 +tensorflow/python/keras/engine/functional.py,sha256=YYTaSg86xd8BkX67-4BbcZgCX4WdnD0Y3cDRUOBplP0,58445 +tensorflow/python/keras/engine/input_layer.py,sha256=ghxD6ADoKx-5j8gVGMw43-SxEXnVe6WHXyHXUfehwOY,16072 +tensorflow/python/keras/engine/input_spec.py,sha256=a3KT3-X9c7EbLYa-gf3UOus6ygfSBp-tz06FTPbkrro,11165 +tensorflow/python/keras/engine/keras_tensor.py,sha256=mCAsPCUiAxin2NxzzZA3pNRgE3UE7-YtgViz18IS9ks,25177 +tensorflow/python/keras/engine/node.py,sha256=yK05HDTQT0eZi_JVZ4uuDVFkfy2ttTRjtQ4dIEkHpf8,11327 +tensorflow/python/keras/engine/partial_batch_padding_handler.py,sha256=oilWt7WrWAIb1RKIqNmECeS1v9yYkR_GyiN3iw0ZZBY,4141 +tensorflow/python/keras/engine/saving.py,sha256=yFYrAUpXOzqYQP7c5K69pNIiSdpL7iylOLwAZsy3scE,913 +tensorflow/python/keras/engine/sequential.py,sha256=1dAKgZ3eTd9YoPOwJM_QlgD_Nv74IgATFXG2ebyZ7xk,23344 +tensorflow/python/keras/engine/training.py,sha256=th2jk1ZgopzbSNla4LszgjCam7X7zI8lP0NktfLjzIg,128573 +tensorflow/python/keras/engine/training_arrays_v1.py,sha256=AAeJ8c6VvtZikURCx-TwJkfF40x0Kn3APlp1Y64i6n4,28119 +tensorflow/python/keras/engine/training_distributed_v1.py,sha256=Fcwmpj4xC5poQPh1JCvOyxNm3LxL8XbICGUvihhdNxw,29780 +tensorflow/python/keras/engine/training_eager_v1.py,sha256=WnAst7dPGNTa_4gdnGPrs8e_iIg3odHErMEMzu1c0s4,14314 +tensorflow/python/keras/engine/training_generator_v1.py,sha256=9yDRonjVYrTLBG3W5eFN-TL3GA5BQdt43neNDk1TMUQ,30841 +tensorflow/python/keras/engine/training_utils.py,sha256=xT3Xo4SvXVh5NbZaNM8AZLbWAtLxzKoPzWxjFX68KXU,8310 +tensorflow/python/keras/engine/training_utils_v1.py,sha256=Ub-6E9iyKfCRRX0i42WxactlcxzFWDEDBBuLPAOb344,77432 +tensorflow/python/keras/engine/training_v1.py,sha256=Mc03eAkp1Mhdxz41_oVMsyHTxUTAn6Z77fs5jGpJTjM,138585 +tensorflow/python/keras/initializers/__init__.py,sha256=VPq_BLa5GTJ_rmQ0YALSqacYM1Btu00J6MWnrRZPGGU,7242 +tensorflow/python/keras/initializers/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/keras/initializers/__pycache__/initializers_v1.cpython-310.pyc,, +tensorflow/python/keras/initializers/__pycache__/initializers_v2.cpython-310.pyc,, +tensorflow/python/keras/initializers/initializers_v1.py,sha256=MufhO12XVSrhyMdLF2YofI1K89GHXXaapB9rTb-H7po,2877 +tensorflow/python/keras/initializers/initializers_v2.py,sha256=tiTfIAxl5syBXiu4R1nQacYfJPciB7N0D8M5JEZKEGI,33602 +tensorflow/python/keras/keras_parameterized.py,sha256=OPnlNMZ7iR6JoR54F1TwhK3XLWRvdILZlDYoiui0N0E,17664 +tensorflow/python/keras/layers/__init__.py,sha256=CbuOrqHNN__spetjv1zUpHn_hKNQskCwaOQc5DOm2go,9570 +tensorflow/python/keras/layers/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/keras/layers/__pycache__/advanced_activations.cpython-310.pyc,, +tensorflow/python/keras/layers/__pycache__/convolutional.cpython-310.pyc,, +tensorflow/python/keras/layers/__pycache__/convolutional_recurrent.cpython-310.pyc,, +tensorflow/python/keras/layers/__pycache__/core.cpython-310.pyc,, +tensorflow/python/keras/layers/__pycache__/dense_attention.cpython-310.pyc,, +tensorflow/python/keras/layers/__pycache__/embeddings.cpython-310.pyc,, +tensorflow/python/keras/layers/__pycache__/merge.cpython-310.pyc,, +tensorflow/python/keras/layers/__pycache__/pooling.cpython-310.pyc,, +tensorflow/python/keras/layers/__pycache__/recurrent.cpython-310.pyc,, +tensorflow/python/keras/layers/__pycache__/rnn_cell_wrapper_v2.cpython-310.pyc,, +tensorflow/python/keras/layers/__pycache__/serialization.cpython-310.pyc,, +tensorflow/python/keras/layers/advanced_activations.py,sha256=M2JXvgjjiQX9JgiafmyMurjuy81kZjniGAqAEpR_qiA,13990 +tensorflow/python/keras/layers/convolutional.py,sha256=EC28x2ffmCtdENDgdbtDx_lk2yOXzFqieBl0D1T9njc,140598 +tensorflow/python/keras/layers/convolutional_recurrent.py,sha256=vp9kRmpmBkWYgHD4rz7JfqDLg5KrFS-QQKiKQ8bD0-8,42681 +tensorflow/python/keras/layers/core.py,sha256=Z8sHxxcNtW-43LmIrFPYEOhpkKv6KxQQs2rW8vtAcSM,68136 +tensorflow/python/keras/layers/dense_attention.py,sha256=HLWoc2dpEgojkkmj10apXvQ4V9CrmHq7Qe2cxz_01P0,20834 +tensorflow/python/keras/layers/embeddings.py,sha256=WDU3xrAM6IgkYBDhaTGRY6DdR5iRIpLkx6k78XWpQvY,8948 +tensorflow/python/keras/layers/legacy_rnn/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/keras/layers/legacy_rnn/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/keras/layers/legacy_rnn/__pycache__/rnn_cell_impl.cpython-310.pyc,, +tensorflow/python/keras/layers/legacy_rnn/__pycache__/rnn_cell_wrapper_impl.cpython-310.pyc,, +tensorflow/python/keras/layers/legacy_rnn/rnn_cell_impl.py,sha256=Q05k1nrucIwUdD_7D4dcq6wEbXp4Q50OK9dtagiaLMU,54483 +tensorflow/python/keras/layers/legacy_rnn/rnn_cell_wrapper_impl.py,sha256=uXOo7Gb4p2ahbHS9kXnNI6Rshbk8mfYL0zPm1ZTK5iE,20660 +tensorflow/python/keras/layers/merge.py,sha256=qwJU12f36SzRxhuJWxpJCSASzIJgOv8MCpYQLtGuK-0,31655 +tensorflow/python/keras/layers/pooling.py,sha256=92qwGkyA5gXAMI3PcvMG6UZ2MA76lD3vXn5byiO7lVM,49322 +tensorflow/python/keras/layers/recurrent.py,sha256=azrGYAM806fS6BD5OcJsRdvewzeCu9yWitIzcX2DQAk,124874 +tensorflow/python/keras/layers/rnn_cell_wrapper_v2.py,sha256=CgQ7eOAnG87LrWKm6YHa_hbE43snI2YrNxn_SViGyj0,5385 +tensorflow/python/keras/layers/serialization.py,sha256=_IPuCey8gtoiIGwTWuH4Qygt53Onqo37EgetAM4Vp84,4464 +tensorflow/python/keras/legacy_tf_layers/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/keras/legacy_tf_layers/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/keras/legacy_tf_layers/__pycache__/base.cpython-310.pyc,, +tensorflow/python/keras/legacy_tf_layers/__pycache__/convolutional.cpython-310.pyc,, +tensorflow/python/keras/legacy_tf_layers/__pycache__/core.cpython-310.pyc,, +tensorflow/python/keras/legacy_tf_layers/__pycache__/pooling.cpython-310.pyc,, +tensorflow/python/keras/legacy_tf_layers/__pycache__/variable_scope_shim.cpython-310.pyc,, +tensorflow/python/keras/legacy_tf_layers/base.py,sha256=IRrP2-1toQo11yj0dd8patZbNmjSjxdaIVoiIeydzio,23678 +tensorflow/python/keras/legacy_tf_layers/convolutional.py,sha256=GNVk6BwyDXIy390js3vUCfA6E9fcUjv2OTUygno4WSo,68708 +tensorflow/python/keras/legacy_tf_layers/core.py,sha256=YosvWOnd-lh_I_GGdkqF5fu3M_IlkM4FCn3BCcKLxWQ,13461 +tensorflow/python/keras/legacy_tf_layers/pooling.py,sha256=GwEY32wCgrAoJH9_FLPasvymkhNJ-oIqerawLLaWxh0,18876 +tensorflow/python/keras/legacy_tf_layers/variable_scope_shim.py,sha256=iCe4UaCXWIbceiTDkUyqgtmTe0qHD9qrxRg_aOb7FtA,30369 +tensorflow/python/keras/losses.py,sha256=zuW5n5fiMb6KJ0yeKGFKme2fAnWIz9iE4Ya4KbPLk1A,77097 +tensorflow/python/keras/metrics.py,sha256=5ZEXkg-sVjnQl9uM7qcVSfz1sae28AI4NhaeWbkLJLg,129455 +tensorflow/python/keras/mixed_precision/__init__.py,sha256=pfiCC5gCQPQhgEoDrQgJ0cG3lRv5reMLeZF0YltfXEg,844 +tensorflow/python/keras/mixed_precision/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/keras/mixed_precision/__pycache__/autocast_variable.cpython-310.pyc,, +tensorflow/python/keras/mixed_precision/__pycache__/device_compatibility_check.cpython-310.pyc,, +tensorflow/python/keras/mixed_precision/__pycache__/get_layer_policy.cpython-310.pyc,, +tensorflow/python/keras/mixed_precision/__pycache__/loss_scale.cpython-310.pyc,, +tensorflow/python/keras/mixed_precision/__pycache__/loss_scale_optimizer.cpython-310.pyc,, +tensorflow/python/keras/mixed_precision/__pycache__/policy.cpython-310.pyc,, +tensorflow/python/keras/mixed_precision/__pycache__/test_util.cpython-310.pyc,, +tensorflow/python/keras/mixed_precision/autocast_variable.py,sha256=1MZQ1cyUAGieJ_mLS-Eh9f7Kd6CZW04nMpYvgAeYolw,20372 +tensorflow/python/keras/mixed_precision/device_compatibility_check.py,sha256=-hMJHlOE7hg_sVRQ5hLNueeuE-nLB4t4tSG89ivE5eE,5931 +tensorflow/python/keras/mixed_precision/get_layer_policy.py,sha256=rXGxU86fi5Cha9YdbDfC0UlvPxgjZptVM2f069oWU1U,1412 +tensorflow/python/keras/mixed_precision/loss_scale.py,sha256=JfchV-ROiCMUMg7VqbDi4Ycufn_NWXlIPs2dqj4mjoo,2068 +tensorflow/python/keras/mixed_precision/loss_scale_optimizer.py,sha256=myszJh82cKFDjoiap-U-xMGLPWn0E-npDERwUqwVooQ,47768 +tensorflow/python/keras/mixed_precision/policy.py,sha256=0th4QpoGZezOBw6YtA4wnV8RWh9ckLqUCwh4144jCIQ,24329 +tensorflow/python/keras/mixed_precision/test_util.py,sha256=1gcDu376UItDvLpE-Ejeyjj8We3aEIGMl1cSqXY5360,8420 +tensorflow/python/keras/models.py,sha256=T0e0XV6A8vAb8qZvQ0wZPC2j5OEM6IDqy71ycOruDDs,31535 +tensorflow/python/keras/optimizer_v1.py,sha256=1DgCgtOk_dUK5lE4xuTbf1pJwPNrW6uZTdJqqkd4BH4,29827 +tensorflow/python/keras/optimizer_v2/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/keras/optimizer_v2/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/keras/optimizer_v2/__pycache__/adadelta.cpython-310.pyc,, +tensorflow/python/keras/optimizer_v2/__pycache__/adagrad.cpython-310.pyc,, +tensorflow/python/keras/optimizer_v2/__pycache__/adam.cpython-310.pyc,, +tensorflow/python/keras/optimizer_v2/__pycache__/adamax.cpython-310.pyc,, +tensorflow/python/keras/optimizer_v2/__pycache__/ftrl.cpython-310.pyc,, +tensorflow/python/keras/optimizer_v2/__pycache__/gradient_descent.cpython-310.pyc,, +tensorflow/python/keras/optimizer_v2/__pycache__/learning_rate_schedule.cpython-310.pyc,, +tensorflow/python/keras/optimizer_v2/__pycache__/legacy_learning_rate_decay.cpython-310.pyc,, +tensorflow/python/keras/optimizer_v2/__pycache__/nadam.cpython-310.pyc,, +tensorflow/python/keras/optimizer_v2/__pycache__/optimizer_v2.cpython-310.pyc,, +tensorflow/python/keras/optimizer_v2/__pycache__/rmsprop.cpython-310.pyc,, +tensorflow/python/keras/optimizer_v2/__pycache__/utils.cpython-310.pyc,, +tensorflow/python/keras/optimizer_v2/adadelta.py,sha256=H42e3ybpvNc4Ax21_WBwuHtMpy5lA3LaKehfax7Futw,6106 +tensorflow/python/keras/optimizer_v2/adagrad.py,sha256=S5GeYEuiDYIkqc9op6-HjKbu1WexTo2DhJIf0i7TLe8,6704 +tensorflow/python/keras/optimizer_v2/adam.py,sha256=GQF5vv70CkrgvVpoxwOyPAj9Tndyp4c1e5mJ5oCtFww,20388 +tensorflow/python/keras/optimizer_v2/adamax.py,sha256=2QkK50d8hVtiOY8-k3IrpOn82YAzInGF4ZOvhHr11to,7700 +tensorflow/python/keras/optimizer_v2/ftrl.py,sha256=qwP1uZi3irKreB467-u0rRf5BsENxtgvDEzDpCRlp3M,10910 +tensorflow/python/keras/optimizer_v2/gradient_descent.py,sha256=1DSFn9T-2ysQwFrCjMApRn-kHmENsqEkXODKInD8QRQ,7011 +tensorflow/python/keras/optimizer_v2/learning_rate_schedule.py,sha256=s_sL0m48vEmZvDjbtihuSnrJD6F8XLuNDFxIp4xRTg4,39281 +tensorflow/python/keras/optimizer_v2/legacy_learning_rate_decay.py,sha256=N0abcFEmoIeOfMYp4NUFKrQfRDQkptdcQMtTnwIISww,29725 +tensorflow/python/keras/optimizer_v2/nadam.py,sha256=p3YdSJaXAYzGZzQ06t0PHBTKuIlNlNlNLN-1tclIoMc,9274 +tensorflow/python/keras/optimizer_v2/optimizer_v2.py,sha256=Bj6OvOeX3dPt8l7wOZGMcOMTFfHlFJUW-DhrgyM6QFc,58525 +tensorflow/python/keras/optimizer_v2/rmsprop.py,sha256=Wbi_sJi8YiTe8SB3T0Hb-WrxYJqxLj_XNqwgEB4kpEk,13039 +tensorflow/python/keras/optimizer_v2/utils.py,sha256=dREejSK0eeVXQ0CdNeTPfGdM9YvZYdvM8-7H_BEL5Qk,5804 +tensorflow/python/keras/optimizers.py,sha256=mEe6JyGCFhq680pLM7krwKgCe5_ZW1Mmvfpqqf1SHnM,5111 +tensorflow/python/keras/protobuf/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/keras/protobuf/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/keras/protobuf/__pycache__/projector_config_pb2.cpython-310.pyc,, +tensorflow/python/keras/protobuf/__pycache__/saved_metadata_pb2.cpython-310.pyc,, +tensorflow/python/keras/protobuf/__pycache__/versions_pb2.cpython-310.pyc,, +tensorflow/python/keras/protobuf/projector_config_pb2.py,sha256=PAjKqHyQOXFzyzBqKUmoUfEkhcgllagElsUzhFITllg,1897 +tensorflow/python/keras/protobuf/saved_metadata_pb2.py,sha256=xBRM0iRgjL2gb6WgtiA1kA42K-P09_lwdzoBaihc2SE,1724 +tensorflow/python/keras/protobuf/versions_pb2.py,sha256=QB7YVVSPrbg5q0uWFzRrSbWdOMoULCWCF-APBqQR0UQ,1176 +tensorflow/python/keras/regularizers.py,sha256=wyWWXvMz57CsNWuDUNSSNC4cy5HdojVNDvDafwFBRL8,12274 +tensorflow/python/keras/saving/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/keras/saving/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/keras/saving/__pycache__/hdf5_format.cpython-310.pyc,, +tensorflow/python/keras/saving/__pycache__/model_config.cpython-310.pyc,, +tensorflow/python/keras/saving/__pycache__/save.cpython-310.pyc,, +tensorflow/python/keras/saving/__pycache__/saved_model_experimental.cpython-310.pyc,, +tensorflow/python/keras/saving/__pycache__/saving_utils.cpython-310.pyc,, +tensorflow/python/keras/saving/hdf5_format.py,sha256=PJRrMBy33dHA_74YVIOSkCLy2WdIwzkjt6rgFv66EnM,33808 +tensorflow/python/keras/saving/model_config.py,sha256=1MD6IHoV2nLtTjOKONoG3pxMnqj4plE-s8Rcv5z7e60,3513 +tensorflow/python/keras/saving/save.py,sha256=CToKgk47u8e7UKWpoa_RAXGXrpaOHFKlInEDwcznfPc,9199 +tensorflow/python/keras/saving/saved_model/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/keras/saving/saved_model/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/keras/saving/saved_model/__pycache__/base_serialization.cpython-310.pyc,, +tensorflow/python/keras/saving/saved_model/__pycache__/constants.cpython-310.pyc,, +tensorflow/python/keras/saving/saved_model/__pycache__/json_utils.cpython-310.pyc,, +tensorflow/python/keras/saving/saved_model/__pycache__/layer_serialization.cpython-310.pyc,, +tensorflow/python/keras/saving/saved_model/__pycache__/load.cpython-310.pyc,, +tensorflow/python/keras/saving/saved_model/__pycache__/load_context.cpython-310.pyc,, +tensorflow/python/keras/saving/saved_model/__pycache__/metric_serialization.cpython-310.pyc,, +tensorflow/python/keras/saving/saved_model/__pycache__/model_serialization.cpython-310.pyc,, +tensorflow/python/keras/saving/saved_model/__pycache__/network_serialization.cpython-310.pyc,, +tensorflow/python/keras/saving/saved_model/__pycache__/save.cpython-310.pyc,, +tensorflow/python/keras/saving/saved_model/__pycache__/save_impl.cpython-310.pyc,, +tensorflow/python/keras/saving/saved_model/__pycache__/serialized_attributes.cpython-310.pyc,, +tensorflow/python/keras/saving/saved_model/__pycache__/utils.cpython-310.pyc,, +tensorflow/python/keras/saving/saved_model/base_serialization.py,sha256=2qy7KH0zzslgIjn9VFqBEz7DbEWUfCHkXGCRk2zGbXw,4663 +tensorflow/python/keras/saving/saved_model/constants.py,sha256=HFG2mAk7fae_Jty-auCDSUXtki_aZwmU1hq32H8UU6U,1769 +tensorflow/python/keras/saving/saved_model/json_utils.py,sha256=lFm0GsJe2xaI6wJbnxtY88zat50C7tJB38jL9MNVfOs,4727 +tensorflow/python/keras/saving/saved_model/layer_serialization.py,sha256=hsg-OXQfB_6x_B5Dw-5ulEjZWWSgznT3NVDbiJY5crQ,7304 +tensorflow/python/keras/saving/saved_model/load.py,sha256=xvh7iqCiwYdHgPZtuS2llGlLBNY6fEJfD4wz7ukrxMA,51029 +tensorflow/python/keras/saving/saved_model/load_context.py,sha256=tw-gjZSFSG9NJiz8GCZx8PL4FMd2aIZvtFs8aKpp8ek,1781 +tensorflow/python/keras/saving/saved_model/metric_serialization.py,sha256=Q_YBg4iRe9iY6voh4YaDEsTSkb-9UYpUATNOTaxm7qg,1937 +tensorflow/python/keras/saving/saved_model/model_serialization.py,sha256=6pflueqEIe34r0zr4n1VMDXv-RgzO8m8fUat9MZRADQ,2646 +tensorflow/python/keras/saving/saved_model/network_serialization.py,sha256=0j-4rbzroosDhUQloEamkGs2qZBkd6T0YsyXIS3VQMw,1177 +tensorflow/python/keras/saving/saved_model/save.py,sha256=6Y_dVo66x0AphDcWl_Ym5gMAYVmKpBcb69uIYyfybkM,5146 +tensorflow/python/keras/saving/saved_model/save_impl.py,sha256=1LcmLghh0pLal-CF8oCm-214fmxaS66uOPb4DKOnwao,29182 +tensorflow/python/keras/saving/saved_model/serialized_attributes.py,sha256=nffEuzGfprxSSexZfw0LYDqzFlA3aVB4rq2lwEydBvo,13231 +tensorflow/python/keras/saving/saved_model/utils.py,sha256=JqGdEgRaMnAdjO6v0MCi80PU_ALtMVhuyqHN_2yRprA,10796 +tensorflow/python/keras/saving/saved_model_experimental.py,sha256=q7h29kwFFV9lb_p4o35KVOBnkwtyD5jz0Rf8w1p-3fk,19129 +tensorflow/python/keras/saving/saving_utils.py,sha256=XMWDOARGnqN7c_Kjp87aP7DczTSSEfs1uADmTVT95l4,12558 +tensorflow/python/keras/saving/utils_v1/__init__.py,sha256=dWkN1KcLjQxtpjfrDRJXuYyevCpyA4YykCAFWYvZeqo,1594 +tensorflow/python/keras/saving/utils_v1/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/keras/saving/utils_v1/__pycache__/export_output.cpython-310.pyc,, +tensorflow/python/keras/saving/utils_v1/__pycache__/export_utils.cpython-310.pyc,, +tensorflow/python/keras/saving/utils_v1/__pycache__/mode_keys.cpython-310.pyc,, +tensorflow/python/keras/saving/utils_v1/__pycache__/signature_def_utils.cpython-310.pyc,, +tensorflow/python/keras/saving/utils_v1/__pycache__/unexported_constants.cpython-310.pyc,, +tensorflow/python/keras/saving/utils_v1/export_output.py,sha256=lVeuobpj7LtbtL_zjotjh1UAOlpI-zdGhPkPxa3zrqw,14093 +tensorflow/python/keras/saving/utils_v1/export_utils.py,sha256=yVNg0D6v9uUIYWZtHUgfU9tDg-rLvNbTDupuDYP9bYU,14969 +tensorflow/python/keras/saving/utils_v1/mode_keys.py,sha256=TDfHmFqYa7_KMH-eTqDjIRGT_5O9g80FVWX93l-Ha5I,3167 +tensorflow/python/keras/saving/utils_v1/signature_def_utils.py,sha256=2qrZ43uiRSbdl4yGztOrbrphtwCZXq-Q9xsbN1Ggl8g,3010 +tensorflow/python/keras/saving/utils_v1/unexported_constants.py,sha256=B7Q1yshB8TimTSEAAipUrw5Ui2QPfbUbwPfjzETCjAs,1220 +tensorflow/python/keras/testing_utils.py,sha256=uf11pSr1ix-rAQTMpCIjss0-eCWSzlryGW6TI0ItFxA,37469 +tensorflow/python/keras/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/keras/utils/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/keras/utils/__pycache__/all_utils.cpython-310.pyc,, +tensorflow/python/keras/utils/__pycache__/control_flow_util.cpython-310.pyc,, +tensorflow/python/keras/utils/__pycache__/conv_utils.cpython-310.pyc,, +tensorflow/python/keras/utils/__pycache__/data_utils.cpython-310.pyc,, +tensorflow/python/keras/utils/__pycache__/dataset_creator.cpython-310.pyc,, +tensorflow/python/keras/utils/__pycache__/generic_utils.cpython-310.pyc,, +tensorflow/python/keras/utils/__pycache__/io_utils.cpython-310.pyc,, +tensorflow/python/keras/utils/__pycache__/kernelized_utils.cpython-310.pyc,, +tensorflow/python/keras/utils/__pycache__/layer_utils.cpython-310.pyc,, +tensorflow/python/keras/utils/__pycache__/losses_utils.cpython-310.pyc,, +tensorflow/python/keras/utils/__pycache__/metrics_utils.cpython-310.pyc,, +tensorflow/python/keras/utils/__pycache__/mode_keys.cpython-310.pyc,, +tensorflow/python/keras/utils/__pycache__/np_utils.cpython-310.pyc,, +tensorflow/python/keras/utils/__pycache__/object_identity.cpython-310.pyc,, +tensorflow/python/keras/utils/__pycache__/tf_contextlib.cpython-310.pyc,, +tensorflow/python/keras/utils/__pycache__/tf_inspect.cpython-310.pyc,, +tensorflow/python/keras/utils/__pycache__/tf_utils.cpython-310.pyc,, +tensorflow/python/keras/utils/__pycache__/version_utils.cpython-310.pyc,, +tensorflow/python/keras/utils/__pycache__/vis_utils.cpython-310.pyc,, +tensorflow/python/keras/utils/all_utils.py,sha256=o95ISRsr0kbk6NqWsK5JERvFBkgzAvSQv8plBfHW1wY,2012 +tensorflow/python/keras/utils/control_flow_util.py,sha256=aNSuQNc-vB2CTJIprnADStb1X0tE63mQ_U8OCgNYNgA,4562 +tensorflow/python/keras/utils/conv_utils.py,sha256=WfMGRF6fiIC3Dx_3pnUlzLHggJjyiPRWLonbPalUg3E,18705 +tensorflow/python/keras/utils/data_utils.py,sha256=NqzM75P2Eng5_JTveoeLnwf1ysF3yDw7Zf05aoRmXTI,27217 +tensorflow/python/keras/utils/dataset_creator.py,sha256=KHkIMgiuvvQ2T-FWqV1sCZhTVZP7WrJmk3MERb5QOuo,4232 +tensorflow/python/keras/utils/generic_utils.py,sha256=3zibO9BRYifhiuJY7Vs3pkhowD0bqAqzikZFAuFoE5E,41603 +tensorflow/python/keras/utils/io_utils.py,sha256=WAtY2oATixk4rdmqTN1BXFn8obapYCwzdJnzstzkU0E,1964 +tensorflow/python/keras/utils/kernelized_utils.py,sha256=fkdc3T3zO4sQGxiiSYg7tD7ihjrYSlGWsI58k2WIBHg,4521 +tensorflow/python/keras/utils/layer_utils.py,sha256=mNGSpk0ZW2_5ZXIVuTIKvHwWWgU_NWvx9aeCNhnPad8,14653 +tensorflow/python/keras/utils/losses_utils.py,sha256=_R2Q28G306MOTLzmCTsFfKE3GKVqdB_yegGuiB5uYoY,15104 +tensorflow/python/keras/utils/metrics_utils.py,sha256=KuBmWFJFitLdKjBmjMVRjGvAeImCDE7AS-9YsaZnDE0,36027 +tensorflow/python/keras/utils/mode_keys.py,sha256=WqMXCSF7kkan6X8rLLa-4zxYxfPeBp4gE7nA2r5UPu4,877 +tensorflow/python/keras/utils/np_utils.py,sha256=y744iSCPVieVEjVU46lOcGxH5Io0JMy8Ub7Hd2PmjJ8,2930 +tensorflow/python/keras/utils/object_identity.py,sha256=4HGJtbBtYdU-bdO_ckk4NxKAua4VevD_wayeTcLnNJc,6954 +tensorflow/python/keras/utils/tf_contextlib.py,sha256=SjRSCXHF2sKqXLWlRW7JzntobxLFO2gZW-hxoWPLYO4,1268 +tensorflow/python/keras/utils/tf_inspect.py,sha256=oqwTfC2Ghehaj8XE2J6aOQDHnlgcOEw3sBvIF_R-fXo,14047 +tensorflow/python/keras/utils/tf_utils.py,sha256=HyPh7v_xAw1bqzo1dF56TiI5n7QufgExTi53j8rAR30,17278 +tensorflow/python/keras/utils/version_utils.py,sha256=eFYRE3yLQSwTre6MznX6rME0847J2jh0kn76JJ62ubM,5138 +tensorflow/python/keras/utils/vis_utils.py,sha256=9g6OCl62HXWmh2lm8RAjJGt8KMA37CV7n-QUErGYsNE,12021 +tensorflow/python/kernel_tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/kernel_tests/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/kernel_tests/nn_ops/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/kernel_tests/nn_ops/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/kernel_tests/nn_ops/__pycache__/bias_op_base.cpython-310.pyc,, +tensorflow/python/kernel_tests/nn_ops/__pycache__/cudnn_deterministic_base.cpython-310.pyc,, +tensorflow/python/kernel_tests/nn_ops/__pycache__/depthwise_conv_op_base.cpython-310.pyc,, +tensorflow/python/kernel_tests/nn_ops/__pycache__/xent_op_test_base.cpython-310.pyc,, +tensorflow/python/kernel_tests/nn_ops/bias_op_base.py,sha256=aFXAVUbVgY6WqjgHW8Ql2KMIMjPxY01cqJp8_phi3h8,13880 +tensorflow/python/kernel_tests/nn_ops/cudnn_deterministic_base.py,sha256=XOLpbKZibP4i7eNLBXhcf1oQEbrntq4mntjFoXapge4,11825 +tensorflow/python/kernel_tests/nn_ops/depthwise_conv_op_base.py,sha256=hbZai9Mb6dJJASUvrKf70bGe5fAPlQu-9E9U-vMhFlQ,47053 +tensorflow/python/kernel_tests/nn_ops/xent_op_test_base.py,sha256=pkgC752P16ta9o8DW1KMPnwosvZ2yRjnjeulni6Ru4g,12416 +tensorflow/python/kernel_tests/random/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/kernel_tests/random/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/kernel_tests/random/__pycache__/util.cpython-310.pyc,, +tensorflow/python/kernel_tests/random/util.py,sha256=PS_9kboosbR26cB0drtS1Ihqf8kBxzfF2B3k741Y1WY,5301 +tensorflow/python/kernel_tests/signal/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/kernel_tests/signal/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/kernel_tests/signal/__pycache__/test_util.cpython-310.pyc,, +tensorflow/python/kernel_tests/signal/test_util.py,sha256=nM0NKm4Kt9igeTdmD9SVVYMXX56LSjIQq3AisXvwyXE,3748 +tensorflow/python/kernel_tests/sparse_ops/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/kernel_tests/sparse_ops/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/kernel_tests/sparse_ops/__pycache__/sparse_xent_op_test_base.cpython-310.pyc,, +tensorflow/python/kernel_tests/sparse_ops/sparse_xent_op_test_base.py,sha256=bHVKgRq_BjdjGRuFGtE8agVfXOnC2sLYmhyHGlXOxW4,13209 +tensorflow/python/layers/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/layers/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/layers/__pycache__/base.cpython-310.pyc,, +tensorflow/python/layers/__pycache__/convolutional.cpython-310.pyc,, +tensorflow/python/layers/__pycache__/core.cpython-310.pyc,, +tensorflow/python/layers/__pycache__/layers.cpython-310.pyc,, +tensorflow/python/layers/__pycache__/normalization.cpython-310.pyc,, +tensorflow/python/layers/__pycache__/pooling.cpython-310.pyc,, +tensorflow/python/layers/__pycache__/utils.cpython-310.pyc,, +tensorflow/python/layers/base.py,sha256=ObPxykQmJrwAf_FMz3ybk3ufIQtdUkubNL7DwOrlS8Y,944 +tensorflow/python/layers/convolutional.py,sha256=CScfUQmVVJl2zbszmyirglNnj3sPVJHJTegfIs5KjK4,1925 +tensorflow/python/layers/core.py,sha256=a6Yb5MrJMNNVql11A0oxLXfY4I2UcY_IgYYE8ODSFTI,1028 +tensorflow/python/layers/layers.py,sha256=9n0JL6y6-pPoUIK69_c7ZWrt0MRLEmDIxvVmgktRIRk,3352 +tensorflow/python/layers/normalization.py,sha256=YrdcGLinB29l8jb1a_6WYIKBNG5VBQ6aZSRYxsiZCcE,1344 +tensorflow/python/layers/pooling.py,sha256=GaXsbCa95SwKm8V7KyCEFcxdIVYpKA0ZtTOSTN4BPYg,1440 +tensorflow/python/layers/utils.py,sha256=f-0iS3RqLBek1lOHa5S0MHBMMsDf1TDsIBCB0l1xOLk,7268 +tensorflow/python/lib/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/lib/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/lib/core/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/lib/core/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/lib/core/_pywrap_py_func.pyi,sha256=K4pNt2FW0QdjLFc42D_Lixh43FY4UqI6CwIeqe3OWG4,746 +tensorflow/python/lib/core/_pywrap_py_func.so,sha256=2ioJZqowBytN8KaYZ2_5Xaz14uMgAVw1w31Z0w37PEk,137976 +tensorflow/python/lib/io/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/lib/io/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/lib/io/__pycache__/file_io.cpython-310.pyc,, +tensorflow/python/lib/io/__pycache__/python_io.cpython-310.pyc,, +tensorflow/python/lib/io/__pycache__/tf_record.cpython-310.pyc,, +tensorflow/python/lib/io/_pywrap_file_io.pyi,sha256=Ly7n_Lfc62sFUboUcsuTk3vdIlLq0-XXQrT1EHBctfo,2689 +tensorflow/python/lib/io/_pywrap_file_io.so,sha256=IIb-Wno956uEq4-qdlrzT63Mmi-CLKWbb4XrUrRpg78,385968 +tensorflow/python/lib/io/_pywrap_record_io.pyi,sha256=p_nSVodzuJzQt2E_Mj3dm-zpYNiTIhqbikZlbzWV44Q,1864 +tensorflow/python/lib/io/_pywrap_record_io.so,sha256=v2jYHDO6GOQobDPQy7Q6Sv_5J-H5JD2RPq__FPPro7I,378208 +tensorflow/python/lib/io/file_io.py,sha256=DkWgiu5UNxJ4oL1lLePbyou7wRlM4S5AjsW5PLfFB08,29190 +tensorflow/python/lib/io/python_io.py,sha256=xtaEwOT5oOZ7Ub10M4Tqc74a00ziKZskfHeaL3vly74,944 +tensorflow/python/lib/io/tf_record.py,sha256=NG2KrDZ9ZrHCsdJvWiZmVxVE9Rr0AfrHi2GghQAi2FM,11670 +tensorflow/python/module/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/module/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/module/__pycache__/module.cpython-310.pyc,, +tensorflow/python/module/module.py,sha256=-BOOGDd93w1EI_HNg4XfhW_YmamRRjs8GXHroFGKRhs,17024 +tensorflow/python/ops/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/ops/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/array_grad.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/array_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/array_ops_stack.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/autograph_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/batch_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/bincount_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/bitwise_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/boosted_trees_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/candidate_sampling_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/check_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/clip_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/clustering_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/collective_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/composite_tensor_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/cond.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/cond_v2.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/confusion_matrix.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/control_flow_assert.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/control_flow_case.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/control_flow_grad.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/control_flow_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/control_flow_state.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/control_flow_switch_case.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/control_flow_util.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/control_flow_util_v2.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/control_flow_v2_func_graphs.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/control_flow_v2_toggles.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/critical_section_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/ctc_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/cudnn_rnn_grad.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/custom_gradient.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/data_flow_grad.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/data_flow_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/default_gradient.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/embedding_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/filesystem_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/functional_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_array_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_audio_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_batch_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_bitwise_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_boosted_trees_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_candidate_sampling_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_checkpoint_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_clustering_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_collective_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_composite_tensor_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_control_flow_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_count_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_ctc_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_cudnn_rnn_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_data_flow_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_dataset_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_debug_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_decode_proto_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_encode_proto_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_experimental_dataset_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_filesystem_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_functional_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_image_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_io_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_linalg_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_list_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_logging_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_lookup_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_manip_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_map_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_math_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_nccl_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_nn_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_optional_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_parsing_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_ragged_array_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_ragged_conversion_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_ragged_math_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_random_index_shuffle_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_random_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_resource_variable_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_rnn_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_script_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_sdca_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_sendrecv_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_set_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_sparse_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_special_math_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_spectral_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_state_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_stateful_random_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_stateless_random_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_stateless_random_ops_v2.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_string_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_summary_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_sync_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_tpu_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_tpu_partition_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_training_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gen_uniform_quant_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gradient_checker.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gradient_checker_v2.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gradients.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gradients_impl.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/gradients_util.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/handle_data_util.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/histogram_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/image_grad.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/image_grad_test_base.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/image_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/image_ops_impl.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/init_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/init_ops_v2.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/initializers_ns.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/inplace_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/io_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/linalg_grad.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/linalg_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/linalg_ops_impl.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/list_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/logging_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/lookup_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/manip_grad.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/manip_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/map_fn.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/map_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/math_grad.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/math_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/metrics.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/metrics_impl.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/nccl_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/nn.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/nn_fused_batch_norm_grad.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/nn_grad.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/nn_impl.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/nn_impl_distribute.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/nn_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/numerics.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/op_selector.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/optional_grad.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/parsing_config.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/parsing_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/partitioned_variables.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/proto_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/random_crop_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/random_grad.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/random_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/random_ops_util.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/ref_variable.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/resource_variable_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/resources.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/rnn.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/rnn_cell.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/rnn_cell_impl.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/rnn_grad.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/script_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/sdca_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/session_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/sets.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/sets_impl.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/shape_util.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/sort_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/sparse_grad.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/sparse_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/special_math_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/standard_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/state_grad.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/state_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/stateful_random_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/stateless_random_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/string_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/summary_op_util.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/summary_ops_v2.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/template.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/tensor_array_grad.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/tensor_array_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/unconnected_gradients.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/variable_scope.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/variable_v1.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/variables.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/weak_tensor_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/weak_tensor_test_util.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/weights_broadcast_ops.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/while_loop.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/while_v2.cpython-310.pyc,, +tensorflow/python/ops/__pycache__/while_v2_indexed_slices_rewriter.cpython-310.pyc,, +tensorflow/python/ops/array_grad.py,sha256=j6_9aNeBidV55Ivwic3A7isvmbBqmfpeCaEy3DAtvNY,46258 +tensorflow/python/ops/array_ops.py,sha256=FysKIRnKkp_8zOjb8z2KMrrNfPi8vny1E-5ve9oMs1U,251023 +tensorflow/python/ops/array_ops_stack.py,sha256=FqQYJ_N6I0Z59MNEdMEI2pNgA56DaSVp8j_9J35PD_o,7160 +tensorflow/python/ops/autograph_ops.py,sha256=9U6wmovl1V8bhqOLgr07kPEwOHY-7xyJ3BERKN1KOIE,5481 +tensorflow/python/ops/batch_ops.py,sha256=P5zaGIQ7nlTOlhsqYktYs-8Zaat7aKhFrNSyoRPcJmY,5261 +tensorflow/python/ops/bincount_ops.py,sha256=Udtv7PDa2k-VSw-oXj45Ku2kOw_XmZ-VGBjtmsPdk5Q,9774 +tensorflow/python/ops/bitwise_ops.py,sha256=Gru_wYf_ePZYJ0h_PtK5nRqeRSffO7JQEzHTv0T4gmg,1240 +tensorflow/python/ops/boosted_trees_ops.py,sha256=VVrmFwT9khYAveYh0YRCx2iV6o0QwS1_dQI03Z9lPF8,13770 +tensorflow/python/ops/candidate_sampling_ops.py,sha256=WMjiP9qxolLxSswTJyYlA1gU0yMcczvgJBqNfYhXMxQ,25316 +tensorflow/python/ops/check_ops.py,sha256=zQ95WbZ2YRzW6MRGlAIN1g8Tjw1UyngmtlXst-D-boY,85316 +tensorflow/python/ops/clip_ops.py,sha256=jbQxi051QX7yThp3iSLUKPaT4lpAq0RbE2XHBqSAI7E,16300 +tensorflow/python/ops/clustering_ops.py,sha256=d4L3IkR-emBCjf07wOv_IpSq0ePWAcSf1XErE8mNzjA,36107 +tensorflow/python/ops/collective_ops.py,sha256=9dE1T5oAlXdzGzXR0QtfJ5gwrZf1JQVlkxC7gEnXhiM,22849 +tensorflow/python/ops/composite_tensor_ops.py,sha256=tn526PQrd0pyy9upHe98qkR55W2MTBQgTkoMpz6CY7k,4872 +tensorflow/python/ops/cond.py,sha256=tDcRYdVDa17-2qkeg9d2a2_wy--vK-BznPoHdmr_2do,16600 +tensorflow/python/ops/cond_v2.py,sha256=sINSCfuXiidaG-C3Cs0oJO0XeF2Vj15AP8peAh4CgMY,54551 +tensorflow/python/ops/confusion_matrix.py,sha256=fL5DOwiZx7QJ6bYqP1M3MscluJx9qPVgTBDUO6jcX8Q,10729 +tensorflow/python/ops/control_flow_assert.py,sha256=qYtbStrBfTjrUwjIStkqWKHhjABDr0N7Emg_2Y36bNc,4759 +tensorflow/python/ops/control_flow_case.py,sha256=enYDfIGGt3df2x0KEDIKu41oQJf73QOGPgKwEeT_U_E,15109 +tensorflow/python/ops/control_flow_grad.py,sha256=fb5ON6Utqf-hPm3p8JcXy0zM2mTzQv74cKUCljQyyi8,9554 +tensorflow/python/ops/control_flow_ops.py,sha256=CYpZU2zBndrH81xqBNq8hPKI8h-4H8gaOaaBZudwp9k,85399 +tensorflow/python/ops/control_flow_state.py,sha256=gAHblhm4efE1QBYh6Qes4ZRuqtLO1oVMUAToIq9TbBo,33732 +tensorflow/python/ops/control_flow_switch_case.py,sha256=y0KFph_E4v0r3oSnzHKIsk-BVv1D6ljKMm5Su4lakbs,9893 +tensorflow/python/ops/control_flow_util.py,sha256=18jFn3XKnObtLduqX1km6yuFy18aNSUF3Np8VhNXYZ4,12761 +tensorflow/python/ops/control_flow_util_v2.py,sha256=SILyYosQXIH7qwOTgUI6UDR461Nojoh0urXDLLsPTwM,16755 +tensorflow/python/ops/control_flow_v2_func_graphs.py,sha256=nFEU1iyrx5biS1gDzYiOQa7nMuKh-DO0Eylpd7bNoqw,2131 +tensorflow/python/ops/control_flow_v2_toggles.py,sha256=xVCekJ7G8oK7AcAVJ_DTSLeCqzUQQk5fQtU0y3S740o,4311 +tensorflow/python/ops/critical_section_ops.py,sha256=kffCt-oXzXnB50-P7IfbEffl2nl1uhhKMzHvVSyOaJo,16398 +tensorflow/python/ops/ctc_ops.py,sha256=gFW5yv6jm9BdZ2Bo4nwdA7NdatWztFdO1vqPgi_iKmI,61245 +tensorflow/python/ops/cudnn_rnn_grad.py,sha256=zXpceTEB0QfXoAPEgwEgnDJifxWM5PGXhp46YXGG8zI,3612 +tensorflow/python/ops/custom_gradient.py,sha256=Ljds8U_udTU1vAsaqdyrtskW494j-WlPnosjWA7pzCA,30693 +tensorflow/python/ops/data_flow_grad.py,sha256=kQ1ujyNngEI9ILjUxLWMiyWB6DqF8_PBdVeMnX-mhb8,3134 +tensorflow/python/ops/data_flow_ops.py,sha256=nk_FZnRxiyVnHTx4y6Bdl8tXWsrzhwWewKZ8lRelpDM,93407 +tensorflow/python/ops/default_gradient.py,sha256=M_RFN_iUKv8SQnLdOHn1XbiXw5NamnCI03dQttOeZ10,2960 +tensorflow/python/ops/distributions/__init__.py,sha256=ShcwVSNGMS_eMBuzh-MxvYc0d0QdCRHTo0sHl1LG1YM,818 +tensorflow/python/ops/distributions/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/ops/distributions/__pycache__/bernoulli.cpython-310.pyc,, +tensorflow/python/ops/distributions/__pycache__/beta.cpython-310.pyc,, +tensorflow/python/ops/distributions/__pycache__/bijector.cpython-310.pyc,, +tensorflow/python/ops/distributions/__pycache__/bijector_impl.cpython-310.pyc,, +tensorflow/python/ops/distributions/__pycache__/bijector_test_util.cpython-310.pyc,, +tensorflow/python/ops/distributions/__pycache__/categorical.cpython-310.pyc,, +tensorflow/python/ops/distributions/__pycache__/dirichlet.cpython-310.pyc,, +tensorflow/python/ops/distributions/__pycache__/dirichlet_multinomial.cpython-310.pyc,, +tensorflow/python/ops/distributions/__pycache__/distribution.cpython-310.pyc,, +tensorflow/python/ops/distributions/__pycache__/distributions.cpython-310.pyc,, +tensorflow/python/ops/distributions/__pycache__/exponential.cpython-310.pyc,, +tensorflow/python/ops/distributions/__pycache__/gamma.cpython-310.pyc,, +tensorflow/python/ops/distributions/__pycache__/identity_bijector.cpython-310.pyc,, +tensorflow/python/ops/distributions/__pycache__/kullback_leibler.cpython-310.pyc,, +tensorflow/python/ops/distributions/__pycache__/laplace.cpython-310.pyc,, +tensorflow/python/ops/distributions/__pycache__/multinomial.cpython-310.pyc,, +tensorflow/python/ops/distributions/__pycache__/normal.cpython-310.pyc,, +tensorflow/python/ops/distributions/__pycache__/special_math.cpython-310.pyc,, +tensorflow/python/ops/distributions/__pycache__/student_t.cpython-310.pyc,, +tensorflow/python/ops/distributions/__pycache__/uniform.cpython-310.pyc,, +tensorflow/python/ops/distributions/__pycache__/util.cpython-310.pyc,, +tensorflow/python/ops/distributions/bernoulli.py,sha256=SGGz0i5tGW2QSVGDPC1RbRyQyzDXaz2kdZzqtvOcBf0,7087 +tensorflow/python/ops/distributions/beta.py,sha256=ZYsvUcvN_DWVGyll24k3QUUPzCRyLiYqq198zMcwr3s,14909 +tensorflow/python/ops/distributions/bijector.py,sha256=5hmnhZhfEs1Ui7KGAeFnI8rlCTVfvdQ-X_wrqnamzzY,902 +tensorflow/python/ops/distributions/bijector_impl.py,sha256=_y1laxyGWXPfIP8uJoYFeYGh7987ZbOVBMWMBI-gfpc,43050 +tensorflow/python/ops/distributions/bijector_test_util.py,sha256=uFaQ2l-ku33wOxsxM1KmDe-rMeRRCvvqoMTYs36PxEs,7836 +tensorflow/python/ops/distributions/categorical.py,sha256=GXhxixGm_9ngd3vvG4mluaqyGaEzTqaAkcBB49XW3Eg,12534 +tensorflow/python/ops/distributions/dirichlet.py,sha256=OFB7lGo61nmq4IRP38UOwcv39xWTOhBn3bCmLO1TRZQ,15132 +tensorflow/python/ops/distributions/dirichlet_multinomial.py,sha256=aTSuAG8IHBvpDK29DZ7_FTdUzJMCQLPDCtXVJH_PbhM,13657 +tensorflow/python/ops/distributions/distribution.py,sha256=QVWdAd9PNi-wEw7HL83QTNaOH1BN-Bb6IEQrGwITbxU,46521 +tensorflow/python/ops/distributions/distributions.py,sha256=f3fJ35ayfCN6E4XIK-pbsx-z1oF2ppRbztLnYVlGF1k,1940 +tensorflow/python/ops/distributions/exponential.py,sha256=l4WlJTJ_K-JY5xKxp_tMeUiZ7Nrfrwu0Gm7FJSS81Rk,5752 +tensorflow/python/ops/distributions/gamma.py,sha256=2EaPzxw869fpNT9TZcrGWqFkPh1ef-aEobCS5UlG5-Y,12218 +tensorflow/python/ops/distributions/identity_bijector.py,sha256=qva3pLfyUPNyD99Mi89RFrJGpGey1lNKJj_0Z_oQ4YY,2074 +tensorflow/python/ops/distributions/kullback_leibler.py,sha256=boPlewProenkR0MmXhoiZP5GX-jUE8o0T7F_idEvvBk,7720 +tensorflow/python/ops/distributions/laplace.py,sha256=VyfZsG-241D8E-6PLHEgCCMg1jhKKPvd_E15nXLOCEI,8190 +tensorflow/python/ops/distributions/multinomial.py,sha256=Z_d1bGkNFJtrOA6a97ePdDma2Bp86zFeSBp337kdho0,11734 +tensorflow/python/ops/distributions/normal.py,sha256=v5XcMGGUWgbCrK-NmfEUI5Ue9JQA_lxahHRw1Gycqq0,9713 +tensorflow/python/ops/distributions/special_math.py,sha256=tR2LRvO0v7-xCeDf2ghCBu95kimDhEBoP7y1xzXjTZw,16817 +tensorflow/python/ops/distributions/student_t.py,sha256=wzYdCn9yGNQy0HW2ZKvpCRKPFb5Tteahn47bG_iAXGk,14185 +tensorflow/python/ops/distributions/uniform.py,sha256=hIgqrCQQXux7YzID9yyHXblr_N4_gOmH1_wZZzE7hwc,7093 +tensorflow/python/ops/distributions/util.py,sha256=IHbnPckMCp2AaP8SupzieiDH7aT1hkIevRWBPNfqhSA,55514 +tensorflow/python/ops/embedding_ops.py,sha256=FjUV9MsSLLoinRyHULFFiPdxL3rMsU41_J0sMon9b6c,47923 +tensorflow/python/ops/filesystem_ops.py,sha256=Y6e2477nCLOXlxhWkeS8rVJitfGsudwjA-7MqNjnyK4,1305 +tensorflow/python/ops/functional_ops.py,sha256=GHausfhlViXbpLeZCYzk0YWThEy5Uz_OB6c075ygkus,43958 +tensorflow/python/ops/gen_array_ops.py,sha256=v31iRoY5ey7wf0Pn_SXbRg5eaCflFmexwUncgC2mseI,583666 +tensorflow/python/ops/gen_audio_ops.py,sha256=lrdzQIKKZvBVMpjhybLeOnbpmtgBIoAdeFhOTmZR0c8,20925 +tensorflow/python/ops/gen_batch_ops.py,sha256=fQKJYoQDan3jwEafvLIXRM6NNdALA4m2MSPfMnXjrg4,36867 +tensorflow/python/ops/gen_bitwise_ops.py,sha256=C5dwlAi0lM21FdlswyZOyLEiQ0U0IAaONvnWps1iF9Y,28981 +tensorflow/python/ops/gen_boosted_trees_ops.py,sha256=L-UqqrKVAzBPV4jGyeHCuytT-hmQswbbK-V0ThLb8OM,143138 +tensorflow/python/ops/gen_candidate_sampling_ops.py,sha256=ZJHBJ__XhGd9It8kT5dgjXoec3QAvnUMMVz42YWqOcg,45032 +tensorflow/python/ops/gen_checkpoint_ops.py,sha256=3xoZS2WtIRBsgs1hCm008uuTZ2mzraiA8qYsK5YRN2k,14793 +tensorflow/python/ops/gen_clustering_ops.py,sha256=eq6FWMnhudvRXwQZJI6Wgs7sU5ep3tp7Ovvf633G6io,10519 +tensorflow/python/ops/gen_collective_ops.py,sha256=kH8xEvsZUBS8J38kFE4BV1x_IzmDuhofUl82eVuWc94,74763 +tensorflow/python/ops/gen_composite_tensor_ops.py,sha256=F3oDB4GU5xaAS5wXT-qeX-fz0Q41l03H9J__sI_wfvc,7575 +tensorflow/python/ops/gen_control_flow_ops.py,sha256=aRJXL-dpMf9iqJhjQKGXK2lZdUhjFfNbwzWy173DFM8,37642 +tensorflow/python/ops/gen_count_ops.py,sha256=Fiqs5eSE9cunYULScKGpiwqtknBpCHsjWFP7XQa886k,17602 +tensorflow/python/ops/gen_ctc_ops.py,sha256=dTy2J99OZvioKunljIFyEjEq6sOAMRi5L8zsF9BUEJ4,24753 +tensorflow/python/ops/gen_cudnn_rnn_ops.py,sha256=OlsxLHNMa9dSwf8v4K7aKscaxMjNPjCBHa67LU19aUE,106890 +tensorflow/python/ops/gen_data_flow_ops.py,sha256=j-KaOuwX1AWHJ7py0jILRMH7FN991saO_-Ceq_F6EiA,371840 +tensorflow/python/ops/gen_dataset_ops.py,sha256=7XCjNpjHb1y7Bu_H_nNXwOFzDrdbtKnzzQpBMY8LC5Q,392265 +tensorflow/python/ops/gen_debug_ops.py,sha256=V0rBG8uHNl9x61xZzd0GzyHT5XMLpza0HPrQ4NMzmO8,53183 +tensorflow/python/ops/gen_decode_proto_ops.py,sha256=_T8R3v8m9Zky0qAZHowJ30na8EZR8kWg_fZT-Kl5Ra0,14118 +tensorflow/python/ops/gen_encode_proto_ops.py,sha256=iHL9vjRg6T-KVwUHKX5Ibv0Skjruh6STsck17x1TFMI,8727 +tensorflow/python/ops/gen_experimental_dataset_ops.py,sha256=t7Nqf6GNBTTO6an1OywzNbXsgidOjBNDr8GMm5h4FUg,533685 +tensorflow/python/ops/gen_filesystem_ops.py,sha256=qSUukHgfzxTWlrUxCZLV0-hUK-7tAk0lcKwRSIh1fSA,3007 +tensorflow/python/ops/gen_functional_ops.py,sha256=l3xOZLjK8nyrSMxa7gBb9lwYc1ik7-aOXfm0ZuwhHzE,56469 +tensorflow/python/ops/gen_image_ops.py,sha256=9STaQ145bbWcSUhXwCqLWYMyLQtWp8HQ39Ju5ztlRgA,236330 +tensorflow/python/ops/gen_io_ops.py,sha256=e4CO1yA-qi5kmjBhMv2amjM0U9JBhSFBuclJPID3yug,98202 +tensorflow/python/ops/gen_linalg_ops.py,sha256=ePGoOcCO25Twv0JXB8lLeYJJNFXh1XPCEtnjXk-gn6E,111762 +tensorflow/python/ops/gen_list_ops.py,sha256=3zZXK-gVs95-LNfeas1RBJItzp3ZVCifiGCp-E3PW2Q,72513 +tensorflow/python/ops/gen_logging_ops.py,sha256=l9iq8UbGLEkYOT2B5BCgfFnx3itvjiOPQVRJgqUTj6k,41653 +tensorflow/python/ops/gen_lookup_ops.py,sha256=wNU3IwjsRnaBQaOyB58TfYr2KRbhp7Ho_TJsz53Bvpc,113278 +tensorflow/python/ops/gen_manip_ops.py,sha256=WWvacApibHs1DRvrIqFrJkCCusCZGRMW-asuS1Qye3U,5356 +tensorflow/python/ops/gen_map_ops.py,sha256=Lw3U-Rt80hZGg78GNQ--y8FT-shHNN4TEgLsLiJL3zM,22019 +tensorflow/python/ops/gen_math_ops.py,sha256=86l0o0B-hSUu35P-yYPugNDLLogLxudp8E-1yc9aATY,583210 +tensorflow/python/ops/gen_nccl_ops.py,sha256=iXZYlJkaIDhed3Mm55TToBL6iF32J4HaY7Fp_kbq1tM,11049 +tensorflow/python/ops/gen_nn_ops.py,sha256=140oeIws765KojyMWZwQM3Mq2rZhILvlHxKTWdX7JWs,662857 +tensorflow/python/ops/gen_optional_ops.py,sha256=UFlEvO3Ja7uXg7qaQtQpNpxye0JKYDlDo6VmsKBXC50,9989 +tensorflow/python/ops/gen_parsing_ops.py,sha256=9a9tFv3e3Ymm07Ak6Rux6LeoQJwNQcfUHhs3D4TU6NI,136833 +tensorflow/python/ops/gen_ragged_array_ops.py,sha256=SQqBxy25v3qbkFJuSDSjz-du3REiwJyVwFjKnteOoGg,27344 +tensorflow/python/ops/gen_ragged_conversion_ops.py,sha256=ZigrlRF_3tPe8hmcZnCyF6XbivdPQgOpb5fhFWdjYZE,30631 +tensorflow/python/ops/gen_ragged_math_ops.py,sha256=IUyql-irnpLddzSJiXZknh1MHG_zT16DwljXZE5oad8,5165 +tensorflow/python/ops/gen_random_index_shuffle_ops.py,sha256=_59dniPVVm11fCaiEQCdG5-KqiUIimMG5PgFzvfU8fU,6365 +tensorflow/python/ops/gen_random_ops.py,sha256=asWB8CJqhMgVd0jtrA9kdIoGhEYyHchpC8H-wq1U1HQ,43963 +tensorflow/python/ops/gen_resource_variable_ops.py,sha256=v3uNUSf7BZ8BYbsFFgjFMoM-cSWUKbuluEmiIRTWNjA,69793 +tensorflow/python/ops/gen_rnn_ops.py,sha256=9jS3oc1jmbi0zzl8PXetabRZMILfppC5GNSpIxXwdr0,51894 +tensorflow/python/ops/gen_script_ops.py,sha256=ss2XV6vJGtFFVD7ilMqNqFSJpb52hrm8K6AsLf08zQA,9412 +tensorflow/python/ops/gen_sdca_ops.py,sha256=61Q5cxALYYT1dzn-UfkzV37ouGcZAOhNkk4ls5fYODY,43623 +tensorflow/python/ops/gen_sendrecv_ops.py,sha256=-Ub0ATgXW2Rm0XOz8H2G_v2VzOIg0uHjFfGKzRDS3Rg,10477 +tensorflow/python/ops/gen_set_ops.py,sha256=AtZTBEOWYZK5XW2RNeg9nuxEfU20BE080ksw4G1hwtk,23562 +tensorflow/python/ops/gen_sparse_ops.py,sha256=WAv3bDROUaEVL93TFmHjLGDcrq777P8ik6rUYiUqN7o,171382 +tensorflow/python/ops/gen_special_math_ops.py,sha256=7MVSlCQWMv9RvxHZLNZo84y1WMJIfYzIy24ZIrikNpA,34739 +tensorflow/python/ops/gen_spectral_ops.py,sha256=pRi-fNrtwgT6xYhEc5ydEaC98qW0qQHmdxn9mgigjZ4,70336 +tensorflow/python/ops/gen_state_ops.py,sha256=sopdoySHWO60Blx0g_GYiiDSgeqnNV5wpj7dwcDPhKM,92198 +tensorflow/python/ops/gen_stateful_random_ops.py,sha256=WUJhV12CJB8edJQiKKESnh3GcjWPPP2CDQm2ixgWpuQ,41422 +tensorflow/python/ops/gen_stateless_random_ops.py,sha256=BxiwUMrMVPqV5JTLgYixQ5rxy4j7Vad5zBteucoSHps,42532 +tensorflow/python/ops/gen_stateless_random_ops_v2.py,sha256=m1SkJgAYS3kjRAn1qa6YIxxMvhawukbbqncj3fiHE2I,38728 +tensorflow/python/ops/gen_string_ops.py,sha256=l5gyJrJ-T8FL_sj8-9nTE8jJBG6gZ46fkwlLAwM58FQ,120672 +tensorflow/python/ops/gen_summary_ops.py,sha256=z1C1cJEyXvqV8abbEkMawUzy4RmoMjbH1HkVU_1E2GM,31773 +tensorflow/python/ops/gen_sync_ops.py,sha256=6_h8y4-GnUq2cvpmVzO3rhbWfchccDvEsFo8K049RaY,2237 +tensorflow/python/ops/gen_tpu_ops.py,sha256=VaP7AVGpyrZQwWxFK30c-Zizs223LOdXajzyJXUfIBA,319194 +tensorflow/python/ops/gen_tpu_partition_ops.py,sha256=WIYoeesGZuEF-PN6VzyB936ThPx0mfeZr8hy2GmZmuY,16986 +tensorflow/python/ops/gen_training_ops.py,sha256=kOSCzZ9nYFOnpy9YwvuxNYrxUjf6N-pCtfR6vU7srb4,277949 +tensorflow/python/ops/gen_uniform_quant_ops.py,sha256=zBOmWuYitlVEjYMEx149bcXcjU6iMe6cTSfES3cxLuU,111174 +tensorflow/python/ops/gradient_checker.py,sha256=LMB0KNWvXBwi8GiJ6k67SN33_2ss2ZQiZ13npBQ85jw,15774 +tensorflow/python/ops/gradient_checker_v2.py,sha256=SZOz6MLR4qYxqIbtFSeQXu-PGl85HD40ZxWAmdK2m9A,12842 +tensorflow/python/ops/gradients.py,sha256=BQzI7OfbyVB-axpmfPcM6_a7TFpv-ARE4KEYg5vVqn0,1318 +tensorflow/python/ops/gradients_impl.py,sha256=u1cokTAuSJM8jM_-liU8qo_kDyWWtYxF_p-zaDfB0ec,20675 +tensorflow/python/ops/gradients_util.py,sha256=Z3lOeLypVPu10jrtvHkuujSjogW5_LetqHirMfsovF4,42617 +tensorflow/python/ops/handle_data_util.py,sha256=Nen9uJB5Vg0HYpnae8qi9BCZxiByiwUiUfyPdDDD6IQ,3517 +tensorflow/python/ops/histogram_ops.py,sha256=4Mj_ixrjRQUQsTteYtr-vQvFPxp8S72PX3t1TS4WrT8,5899 +tensorflow/python/ops/image_grad.py,sha256=VaD_hQULqV2_SP6va9iag6x3Z6WHK4AE3efviqUFqUs,14875 +tensorflow/python/ops/image_grad_test_base.py,sha256=QbN7_qYpCd_-s1CL106wZ-fbjBs6OC_4-S-qMe38pzQ,25755 +tensorflow/python/ops/image_ops.py,sha256=dUIQ26lqWvPO-R-qbnmGV1INk37-J6ChsRzIxQwIGsU,11458 +tensorflow/python/ops/image_ops_impl.py,sha256=rgDZ3nDN2G1ex1ukw4e0zleF5yOYBdUXFywZ3HSCBBo,234253 +tensorflow/python/ops/init_ops.py,sha256=lCxJFUOUKfHT-OzHSePz-6Coxt3B93TgUGzf-rW5RGA,66841 +tensorflow/python/ops/init_ops_v2.py,sha256=ukN3jdWUd10jRx1NK-xZqVc3Tpin9HgX9HJwkE-rheE,40249 +tensorflow/python/ops/initializers_ns.py,sha256=kZfBVSiaJdZ735LzwCRYd32L4m6FG6wWam2NZYSLBLE,1571 +tensorflow/python/ops/inplace_ops.py,sha256=b0GmbCnAdIlYFnpr-hv8K4iHcc9ykSnJd2wE3YclfrI,7262 +tensorflow/python/ops/io_ops.py,sha256=7xbP5WND8dI8ttqVTKUsvZ_I4blzHbPti3v_C-Q5_3Y,20907 +tensorflow/python/ops/linalg/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/ops/linalg/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/ops/linalg/__pycache__/linalg.cpython-310.pyc,, +tensorflow/python/ops/linalg/__pycache__/linalg_impl.cpython-310.pyc,, +tensorflow/python/ops/linalg/__pycache__/linear_operator.cpython-310.pyc,, +tensorflow/python/ops/linalg/__pycache__/linear_operator_addition.cpython-310.pyc,, +tensorflow/python/ops/linalg/__pycache__/linear_operator_adjoint.cpython-310.pyc,, +tensorflow/python/ops/linalg/__pycache__/linear_operator_block_diag.cpython-310.pyc,, +tensorflow/python/ops/linalg/__pycache__/linear_operator_block_lower_triangular.cpython-310.pyc,, +tensorflow/python/ops/linalg/__pycache__/linear_operator_circulant.cpython-310.pyc,, +tensorflow/python/ops/linalg/__pycache__/linear_operator_composition.cpython-310.pyc,, +tensorflow/python/ops/linalg/__pycache__/linear_operator_diag.cpython-310.pyc,, +tensorflow/python/ops/linalg/__pycache__/linear_operator_full_matrix.cpython-310.pyc,, +tensorflow/python/ops/linalg/__pycache__/linear_operator_householder.cpython-310.pyc,, +tensorflow/python/ops/linalg/__pycache__/linear_operator_identity.cpython-310.pyc,, +tensorflow/python/ops/linalg/__pycache__/linear_operator_inversion.cpython-310.pyc,, +tensorflow/python/ops/linalg/__pycache__/linear_operator_kronecker.cpython-310.pyc,, +tensorflow/python/ops/linalg/__pycache__/linear_operator_low_rank_update.cpython-310.pyc,, +tensorflow/python/ops/linalg/__pycache__/linear_operator_lower_triangular.cpython-310.pyc,, +tensorflow/python/ops/linalg/__pycache__/linear_operator_permutation.cpython-310.pyc,, +tensorflow/python/ops/linalg/__pycache__/linear_operator_test_util.cpython-310.pyc,, +tensorflow/python/ops/linalg/__pycache__/linear_operator_toeplitz.cpython-310.pyc,, +tensorflow/python/ops/linalg/__pycache__/linear_operator_tridiag.cpython-310.pyc,, +tensorflow/python/ops/linalg/__pycache__/linear_operator_util.cpython-310.pyc,, +tensorflow/python/ops/linalg/__pycache__/linear_operator_zeros.cpython-310.pyc,, +tensorflow/python/ops/linalg/__pycache__/property_hint_util.cpython-310.pyc,, +tensorflow/python/ops/linalg/__pycache__/slicing.cpython-310.pyc,, +tensorflow/python/ops/linalg/linalg.py,sha256=vpJorfaYeHxj3b3zmZP5oHPC3IN7feHGs3HUOUWg3s4,2334 +tensorflow/python/ops/linalg/linalg_impl.py,sha256=U1tNb82xXISK1SoGJ8iOLRS_EEwq_WG4uv0IM8ZDHJo,65602 +tensorflow/python/ops/linalg/linear_operator.py,sha256=jwkNBm8hLsqPZps9JSHeaUPuF-3OXYvNiRiNiVk9nKE,62232 +tensorflow/python/ops/linalg/linear_operator_addition.py,sha256=BF7YuLwPS2c5ErqbIdSB6ZV8_6DkeWG7SxfjGczLVZE,15681 +tensorflow/python/ops/linalg/linear_operator_adjoint.py,sha256=4oKowyEORFCIdSIqCjvx07zaS62VGYZsvINkT5hN2go,7947 +tensorflow/python/ops/linalg/linear_operator_block_diag.py,sha256=gBD3YzcYCaWSiLtdajcGMRUacggZ0liT-Se6wljse98,32814 +tensorflow/python/ops/linalg/linear_operator_block_lower_triangular.py,sha256=FK1VWHpOfE3IsuL8HvbfO9rGTYjB99jtQ55Jn-FfPrs,41751 +tensorflow/python/ops/linalg/linear_operator_circulant.py,sha256=ByojAKrybGB-liPHM87STndGEHreB5sW7SoLLmwTZ8g,56851 +tensorflow/python/ops/linalg/linear_operator_composition.py,sha256=rWzW1COIIpUQsyyGz48y7fdz5q4F3eluQek7r009rIA,15890 +tensorflow/python/ops/linalg/linear_operator_diag.py,sha256=4lSmzQQqfBXz6gB2nxyhDkbiWO9tXrxME3yOxDNyHz8,14511 +tensorflow/python/ops/linalg/linear_operator_full_matrix.py,sha256=vqfWdCoHN4KCoh1owk6uMZHz7dsYyrUSkKA1o--10sg,7249 +tensorflow/python/ops/linalg/linear_operator_householder.py,sha256=o91l33kqzizck77Iv2ZLoCalDf6PsYoxq-Byb-MTmqM,11311 +tensorflow/python/ops/linalg/linear_operator_identity.py,sha256=kjpGkv5ExOtL4kn01nCDvCqjCfUqHgjryPb5ZCvkY_Q,35439 +tensorflow/python/ops/linalg/linear_operator_inversion.py,sha256=HKNT6F7qhEyZlytcnPLRSwkEm987u5XHZHOo3C4j448,8237 +tensorflow/python/ops/linalg/linear_operator_kronecker.py,sha256=-F8LWJTShTuAUKcUxNqyW1wfO-66wX4pC2lw-5TlGIc,20505 +tensorflow/python/ops/linalg/linear_operator_low_rank_update.py,sha256=K46w6bO4AsGMYJaq3HHZ2GD5z7aM3RKzixZ5jMqzZ8A,19968 +tensorflow/python/ops/linalg/linear_operator_lower_triangular.py,sha256=DFbaqy5AxfiTd2Ca0Uu0JYuhJ5OEcfKJWXCf1SrQK0s,8976 +tensorflow/python/ops/linalg/linear_operator_permutation.py,sha256=wmM9jodRdOC6zMHIBctVvAFStMzu_bPFUAyyPmHehvE,10768 +tensorflow/python/ops/linalg/linear_operator_test_util.py,sha256=Tw75yU2-YVbD1G9hOSPtflG9ve-yXwCONK8SZn3K94A,52272 +tensorflow/python/ops/linalg/linear_operator_toeplitz.py,sha256=3O3wsCkHS47_7ZaTgR-qCasm-ERk4-cLo3m0nJPwuqU,11398 +tensorflow/python/ops/linalg/linear_operator_tridiag.py,sha256=XWzEfb6ti4mLn1b1M1RIl0eqlUhWxU_0bNfoQSAvEsc,15417 +tensorflow/python/ops/linalg/linear_operator_util.py,sha256=-4F_DG06ZVaAmtJMIwh8UYVy9y5qWHbMv8lCmtlVH9I,22137 +tensorflow/python/ops/linalg/linear_operator_zeros.py,sha256=xcFReJQX_fI-6dqRqj1chG21luFZo_jZukZkkLRXPAM,19786 +tensorflow/python/ops/linalg/property_hint_util.py,sha256=3icmPwm-cvEIKBeteua9P_U-l8SK1_50EJlT2cJ41x0,3321 +tensorflow/python/ops/linalg/slicing.py,sha256=yLOLGyY514j4fN63znhXM9Mr5UTF0MGBo3tU_04JFLo,7534 +tensorflow/python/ops/linalg/sparse/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/ops/linalg/sparse/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/ops/linalg/sparse/__pycache__/conjugate_gradient.cpython-310.pyc,, +tensorflow/python/ops/linalg/sparse/__pycache__/gen_sparse_csr_matrix_ops.cpython-310.pyc,, +tensorflow/python/ops/linalg/sparse/__pycache__/sparse.cpython-310.pyc,, +tensorflow/python/ops/linalg/sparse/__pycache__/sparse_csr_matrix_grad.cpython-310.pyc,, +tensorflow/python/ops/linalg/sparse/__pycache__/sparse_csr_matrix_ops.cpython-310.pyc,, +tensorflow/python/ops/linalg/sparse/conjugate_gradient.py,sha256=5NgP9m5N2ZRe1JpOFgPXRpBN0_P3OZEeF89ThlO6VNA,5650 +tensorflow/python/ops/linalg/sparse/gen_sparse_csr_matrix_ops.py,sha256=enroyAqkh0LK7E5Yw78yHQhULRBVGoHG26vQMZajUQU,59806 +tensorflow/python/ops/linalg/sparse/sparse.py,sha256=vNQJ-pLL5VEbAJk1sz0426viv7VbE73s8uct52OSM3k,1101 +tensorflow/python/ops/linalg/sparse/sparse_csr_matrix_grad.py,sha256=_F1a0bcvomNgYQTxKzsYpJ89rErbmY_bym2ScCTtKGg,14227 +tensorflow/python/ops/linalg/sparse/sparse_csr_matrix_ops.py,sha256=ghpqnflnHxIezOfjTIaI-60drRZpF1jJGu-cvJFgWpY,13001 +tensorflow/python/ops/linalg_grad.py,sha256=QbQek8rC385bzSI7zFSY0hYeT0XdtBq1H860K7-L1Ec,46077 +tensorflow/python/ops/linalg_ops.py,sha256=G8PiAYbEBWJTJKQjH9kMk1pkw7OuQsKzbfmcFtrkz7Q,32904 +tensorflow/python/ops/linalg_ops_impl.py,sha256=Pn8_9pV5l7RVEOz8kfDcIiGuNHUFyMt-g3QaRdKnkP4,3221 +tensorflow/python/ops/list_ops.py,sha256=1GfrN4W3bH0fZS5MITVVgNxtlq9PO5nQ6aX5MM2bsBw,14716 +tensorflow/python/ops/logging_ops.py,sha256=8E9lLp9nyYm0q_wJHhXqcrJlF6KVctYSD6gDMCkH6Zc,27477 +tensorflow/python/ops/lookup_ops.py,sha256=joWsg8zeDf4iCmq4SY8CMsziaCwbCFoj0AGCTdenYHU,94298 +tensorflow/python/ops/losses/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/ops/losses/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/ops/losses/__pycache__/losses.cpython-310.pyc,, +tensorflow/python/ops/losses/__pycache__/losses_impl.cpython-310.pyc,, +tensorflow/python/ops/losses/__pycache__/util.cpython-310.pyc,, +tensorflow/python/ops/losses/losses.py,sha256=JBMm7vCYz2bpeXvGbAyJENAQn0zGhY6axe8WVt6bnQk,1026 +tensorflow/python/ops/losses/losses_impl.py,sha256=m5DSGFVlg3hioBsxLJx-PVLKWky5RFd8kVFhBekHrRs,48155 +tensorflow/python/ops/losses/util.py,sha256=k_qLi1xPg_gtkxvmJ-O-lso2nyZa43mPsANaeSVA7Y4,9838 +tensorflow/python/ops/manip_grad.py,sha256=oX30UXiXvWwU057JMQmdIMxIcN-e8yY5WIQV5ioXeoc,1058 +tensorflow/python/ops/manip_ops.py,sha256=alwrt-bIdA37Zi-R3nTGvgYof-4HStMYdFFW4scTo70,1352 +tensorflow/python/ops/map_fn.py,sha256=XuZYlLIKe8xlp3dFTJsz8msQ_TzaFq2XcEd6ihVT3V4,27761 +tensorflow/python/ops/map_ops.py,sha256=YdzfA2kyUm0WJj1AEvF8aDQ8KrjTwh_49ETZIZG3Z_A,2498 +tensorflow/python/ops/math_grad.py,sha256=Axhc8C7h_nXK31ZTboAMwjybn5_cLEOW0CTCOna-GDs,70994 +tensorflow/python/ops/math_ops.py,sha256=s6vYWPD7qSmi8vqJD4gMaSV0JpYAdMgYv1IkyiKajn8,208583 +tensorflow/python/ops/metrics.py,sha256=gWL970WnA-h17A46OLEVvZZ1Xfo2HOnhze-7MLzfQw4,864 +tensorflow/python/ops/metrics_impl.py,sha256=Kq_W87sG6v2wS9AeYaXO1pFcKo8n5jn1qCmRhk8JxU0,171931 +tensorflow/python/ops/nccl_ops.py,sha256=Vg4E-O4HU4dhMXVf2F1CjmHrlkTvXcMHdEE6ZgIG0aw,8147 +tensorflow/python/ops/nn.py,sha256=rmZeeqz4q2L3oclkc4iCrL8p4M6jWlZzsqdbKUUm74Y,1820 +tensorflow/python/ops/nn_fused_batch_norm_grad.py,sha256=GQNjhm-8VMeS0DEKBDS6ipEs42DTR8PxIR846olqqdE,6631 +tensorflow/python/ops/nn_grad.py,sha256=jvqh3whmUPrHn7jYUmhKKmOF9mvVgW0cFq9bkrikvtI,37750 +tensorflow/python/ops/nn_impl.py,sha256=9QC-J_xOmNHlDhrJv_NLFaFCYSKwW8QJjiz819CIzBo,97084 +tensorflow/python/ops/nn_impl_distribute.py,sha256=U2kt6BFZbTTuP6X6gOCXj5l2p2PiebIY4LgK25OLlgc,5408 +tensorflow/python/ops/nn_ops.py,sha256=6HrFHh0P7TXebSJQ9shkiNlBnSyjyT-I_WNTwFmkBsc,274772 +tensorflow/python/ops/numerics.py,sha256=XdPdwGg5zblnVJb8WdUpjerqiRZreYjav81QPC1r5ZI,5155 +tensorflow/python/ops/numpy_ops/__init__.py,sha256=po-XPF0wKGhmDhVVhkvjNwW5_eDNHhUAiB8gjflD06o,6368 +tensorflow/python/ops/numpy_ops/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/ops/numpy_ops/__pycache__/np_array_ops.cpython-310.pyc,, +tensorflow/python/ops/numpy_ops/__pycache__/np_arrays.cpython-310.pyc,, +tensorflow/python/ops/numpy_ops/__pycache__/np_config.cpython-310.pyc,, +tensorflow/python/ops/numpy_ops/__pycache__/np_dtypes.cpython-310.pyc,, +tensorflow/python/ops/numpy_ops/__pycache__/np_math_ops.cpython-310.pyc,, +tensorflow/python/ops/numpy_ops/__pycache__/np_random.cpython-310.pyc,, +tensorflow/python/ops/numpy_ops/__pycache__/np_utils.cpython-310.pyc,, +tensorflow/python/ops/numpy_ops/np_array_ops.py,sha256=eoWWDMAVgz_yZftfSW5BbSjP0GIDdLzcia6IlM8uOXI,67587 +tensorflow/python/ops/numpy_ops/np_arrays.py,sha256=diaqanzInVzro-iRKexlCSUE6CjJayYNj7YmO-WUv54,1992 +tensorflow/python/ops/numpy_ops/np_config.py,sha256=VFgH3xXKqtpsKxiH92xVN3AYBynAZp9MIcQWCwRWTJ4,2703 +tensorflow/python/ops/numpy_ops/np_dtypes.py,sha256=HnF6VhoUfnCdNTqR6eoup4vBDabQj-70Hs_gpnirVTE,5662 +tensorflow/python/ops/numpy_ops/np_math_ops.py,sha256=bgmbmqGNvOFkKB1jmN1BNWG0gpDjCgTSdaWAuFveMgw,49369 +tensorflow/python/ops/numpy_ops/np_random.py,sha256=tKYkeKB6vmPcqIhUo-PLi2JaikGf30ggWSCoPih31nA,4157 +tensorflow/python/ops/numpy_ops/np_utils.py,sha256=XcDEEqbaExViPaCwYFqJJHtSE01J4ZuiiSLZlbC7d_w,21467 +tensorflow/python/ops/op_selector.py,sha256=fzhrZfg914JBHEBByyeGIv81RRyHFl-_SuMirqqlWzA,14168 +tensorflow/python/ops/optional_grad.py,sha256=l0T8zciWVKrHkMMsNefuT_DA68oF9PeYFiu7n81hWeU,1175 +tensorflow/python/ops/parallel_for/__init__.py,sha256=yGeoGZWbANOr_qveN1K2qJWylf7LeKpTIR2OYZ8Q12g,729 +tensorflow/python/ops/parallel_for/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/ops/parallel_for/__pycache__/control_flow_ops.cpython-310.pyc,, +tensorflow/python/ops/parallel_for/__pycache__/gradients.cpython-310.pyc,, +tensorflow/python/ops/parallel_for/__pycache__/pfor.cpython-310.pyc,, +tensorflow/python/ops/parallel_for/__pycache__/test_util.cpython-310.pyc,, +tensorflow/python/ops/parallel_for/control_flow_ops.py,sha256=GufsxeTByhADfrVlrTz7VTkAW8_AxPxwRyajgg00g6s,25242 +tensorflow/python/ops/parallel_for/gradients.py,sha256=pb6AASxRcaj-DgaSDudUfVX7lk0Ervslgdw9YQC6iac,5836 +tensorflow/python/ops/parallel_for/pfor.py,sha256=g_BgrLq6yf46urtFpJKW-6SxNCn0yG33VZOd_k1qatY,207834 +tensorflow/python/ops/parallel_for/test_util.py,sha256=l9bMuGiOqL2YDDY0m-MHkrL-YQcj_DzqNj-4YygywyQ,3112 +tensorflow/python/ops/parsing_config.py,sha256=LLHBKGcQ2JfQvezppX48ZmOEsB5hcjr4ULF8KLHeZyg,41376 +tensorflow/python/ops/parsing_ops.py,sha256=-ijXzvBUN9fmrsTf6n7GQkO2FEiaza_3F8uk32fMEY0,50038 +tensorflow/python/ops/partitioned_variables.py,sha256=OIgx7l3YpSA_v2ybz80Y_DJ-b1KslreSb0vbMaExaqI,13552 +tensorflow/python/ops/proto_ops.py,sha256=Z2JvXPGER9rHn6g3eCXZz32FPGLmL9zjmMPEFBh-iI8,1134 +tensorflow/python/ops/ragged/__init__.py,sha256=tgKHg1IQVHIQB24h9Y7S8fajquqBxzy3HuoT8T-Gwqc,1333 +tensorflow/python/ops/ragged/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/ops/ragged/__pycache__/dynamic_ragged_shape.cpython-310.pyc,, +tensorflow/python/ops/ragged/__pycache__/ragged_array_ops.cpython-310.pyc,, +tensorflow/python/ops/ragged/__pycache__/ragged_autograph.cpython-310.pyc,, +tensorflow/python/ops/ragged/__pycache__/ragged_batch_gather_ops.cpython-310.pyc,, +tensorflow/python/ops/ragged/__pycache__/ragged_batch_gather_with_default_op.cpython-310.pyc,, +tensorflow/python/ops/ragged/__pycache__/ragged_bincount_ops.cpython-310.pyc,, +tensorflow/python/ops/ragged/__pycache__/ragged_check_ops.cpython-310.pyc,, +tensorflow/python/ops/ragged/__pycache__/ragged_concat_ops.cpython-310.pyc,, +tensorflow/python/ops/ragged/__pycache__/ragged_config.cpython-310.pyc,, +tensorflow/python/ops/ragged/__pycache__/ragged_conversion_ops.cpython-310.pyc,, +tensorflow/python/ops/ragged/__pycache__/ragged_dispatch.cpython-310.pyc,, +tensorflow/python/ops/ragged/__pycache__/ragged_embedding_ops.cpython-310.pyc,, +tensorflow/python/ops/ragged/__pycache__/ragged_factory_ops.cpython-310.pyc,, +tensorflow/python/ops/ragged/__pycache__/ragged_functional_ops.cpython-310.pyc,, +tensorflow/python/ops/ragged/__pycache__/ragged_gather_ops.cpython-310.pyc,, +tensorflow/python/ops/ragged/__pycache__/ragged_getitem.cpython-310.pyc,, +tensorflow/python/ops/ragged/__pycache__/ragged_image_ops.cpython-310.pyc,, +tensorflow/python/ops/ragged/__pycache__/ragged_map_ops.cpython-310.pyc,, +tensorflow/python/ops/ragged/__pycache__/ragged_math_ops.cpython-310.pyc,, +tensorflow/python/ops/ragged/__pycache__/ragged_operators.cpython-310.pyc,, +tensorflow/python/ops/ragged/__pycache__/ragged_ops.cpython-310.pyc,, +tensorflow/python/ops/ragged/__pycache__/ragged_squeeze_op.cpython-310.pyc,, +tensorflow/python/ops/ragged/__pycache__/ragged_string_ops.cpython-310.pyc,, +tensorflow/python/ops/ragged/__pycache__/ragged_tensor.cpython-310.pyc,, +tensorflow/python/ops/ragged/__pycache__/ragged_tensor_shape.cpython-310.pyc,, +tensorflow/python/ops/ragged/__pycache__/ragged_tensor_test_ops.cpython-310.pyc,, +tensorflow/python/ops/ragged/__pycache__/ragged_tensor_value.cpython-310.pyc,, +tensorflow/python/ops/ragged/__pycache__/ragged_util.cpython-310.pyc,, +tensorflow/python/ops/ragged/__pycache__/ragged_where_op.cpython-310.pyc,, +tensorflow/python/ops/ragged/__pycache__/row_partition.cpython-310.pyc,, +tensorflow/python/ops/ragged/__pycache__/segment_id_ops.cpython-310.pyc,, +tensorflow/python/ops/ragged/dynamic_ragged_shape.py,sha256=tO9YClXXNRwYw-3Z1qFxZjPOa-M03xKFOkB7De2Gec0,124129 +tensorflow/python/ops/ragged/ragged_array_ops.py,sha256=Gdh1wnmpaeetPfcjEPp0dTNJjEimGzBbBOniSlObgKs,51909 +tensorflow/python/ops/ragged/ragged_autograph.py,sha256=GbpTBXPn8uw8cu6fNpA-oCFQG-G1ectE8e1_rLOpNl4,2465 +tensorflow/python/ops/ragged/ragged_batch_gather_ops.py,sha256=NMkT5_J0PsQewlgWb2LNrhxNLWznluFytLPKFK0HsY0,2601 +tensorflow/python/ops/ragged/ragged_batch_gather_with_default_op.py,sha256=Or3l9QX6eB8zhHrEfXVrwhbkarLQQQ4cuZViAHGHG0A,8089 +tensorflow/python/ops/ragged/ragged_bincount_ops.py,sha256=4QA8YT7YYW5M6ndF4nQG--NsudXIgyZREKXsckv6tBM,16449 +tensorflow/python/ops/ragged/ragged_check_ops.py,sha256=Z2z_KLGcYHtmzzcpMscMEy_OJG6oVdLjjCixx72Dj0k,1139 +tensorflow/python/ops/ragged/ragged_concat_ops.py,sha256=kmCchmX0bzFFmdBdvwjsMc5VcQT16KarlnBDYfV5gMw,13140 +tensorflow/python/ops/ragged/ragged_config.py,sha256=PA4zWry_iSqJRzDqiAau91h3rt4CXVIdcc1px-1Rry4,1125 +tensorflow/python/ops/ragged/ragged_conversion_ops.py,sha256=BsJMsXNwwE7GoFiC5x6QXa-hvnygejzoFQj2hh251MA,7082 +tensorflow/python/ops/ragged/ragged_dispatch.py,sha256=kLbZv-npjFR8zxjnXzaK7ZQK6mCpPAq1a5q_HAL_b40,6168 +tensorflow/python/ops/ragged/ragged_embedding_ops.py,sha256=smNN-6dKhNSpzlqriAWbSmP8S5oSorY16HL_sH2LPPY,16577 +tensorflow/python/ops/ragged/ragged_factory_ops.py,sha256=DK8qpjYlba8gUJ4DvzVQ4yoyRi9iMFfGjZgPwsCK8VI,16294 +tensorflow/python/ops/ragged/ragged_functional_ops.py,sha256=zQhDEPYCencuw1RvaGwKg_sIiHQ8Jb6A5lVA-55BqtU,8474 +tensorflow/python/ops/ragged/ragged_gather_ops.py,sha256=iolubuD7Jt82dRIhOFu2XHT3amZOIWXzlhOmR1KhMUg,21942 +tensorflow/python/ops/ragged/ragged_getitem.py,sha256=zSAg27tQNCIqNhHc7DEvq6lyo1u42yEsK0dhWc176HU,20038 +tensorflow/python/ops/ragged/ragged_image_ops.py,sha256=Z3rj5MxPb2i1zQPtl-iFRwjTPk7YRvwl5iJdWeju-5I,3873 +tensorflow/python/ops/ragged/ragged_map_ops.py,sha256=zPsDg9G7wOhSj1NlsZiuQaDzXqez7kF4c7nE8efbPlA,7117 +tensorflow/python/ops/ragged/ragged_math_ops.py,sha256=00MZJH1P3upiwa-ZfKTO_WHyFXmNw3IsIlkBvl2C81w,51734 +tensorflow/python/ops/ragged/ragged_operators.py,sha256=ko9XxW8JoWHY8unFYeaek3p1syUW_QmuzZ2EYP8PX6Y,12401 +tensorflow/python/ops/ragged/ragged_ops.py,sha256=x6qrWJFU_rTFebYGfLgAlcZW5_sxjpF6STpnldPLg5c,2637 +tensorflow/python/ops/ragged/ragged_squeeze_op.py,sha256=5u3TNe-Db1B99rtkTUTcMq8KXQtJ54bLtDEM3EsxOLU,5742 +tensorflow/python/ops/ragged/ragged_string_ops.py,sha256=209P4EqXpZC-ytbA-KTEfzhjimnnET6BobTB9ZfgyRY,40599 +tensorflow/python/ops/ragged/ragged_tensor.py,sha256=rGqQVADYLfHCwLKcNGAo81pWmQJKFDMuUzUag98rFqc,126856 +tensorflow/python/ops/ragged/ragged_tensor_shape.py,sha256=xS7mPZIREBiMSxKKZzuZH2eEkfgB9IUjXKt8l4RhF4c,26661 +tensorflow/python/ops/ragged/ragged_tensor_test_ops.py,sha256=dOoJnc1VD6i3M-YgEYWBeeFoS3HweQ1N_2Rv05Y53Uk,4994 +tensorflow/python/ops/ragged/ragged_tensor_value.py,sha256=Pb2UE09uy5-ACfNryZ70Qc-JfMuIWFrt0c-SUzmqxqg,4366 +tensorflow/python/ops/ragged/ragged_util.py,sha256=Zg20r0O_bdU76fOF2xdiZ87_PnG6TmvYbtc9hPLmpLM,5251 +tensorflow/python/ops/ragged/ragged_where_op.py,sha256=3fTNIgG2Ou0WLA1Cs39NJXklfCdhtNay0qf9WHtyNXw,11306 +tensorflow/python/ops/ragged/row_partition.py,sha256=5ivZ4cVAAN1fFfExQa3Bq1Clf6dXRa1bEHTrzIZtT4Q,60154 +tensorflow/python/ops/ragged/segment_id_ops.py,sha256=v1EgTDzlDtSzTUQjI9wLWInSBVnVqMPPdf96fG-ORIE,5720 +tensorflow/python/ops/random_crop_ops.py,sha256=b0APsTBqZfQWj1LlMVVIqyhmeFtBlsAYHVnUtgBsBqk,5421 +tensorflow/python/ops/random_grad.py,sha256=HlVbN-OyORrbK94K10vSJZJAloAR1Jp7cHxfLrAqboI,10167 +tensorflow/python/ops/random_ops.py,sha256=VTXQL697qer31XRDHgfWFEyjfHGkcPTVVWx5dsobyms,25622 +tensorflow/python/ops/random_ops_util.py,sha256=k6BOkfbxdUHPLrRRgwITpwzT89GyxUwqiFn4AmSjqY0,7364 +tensorflow/python/ops/ref_variable.py,sha256=mEuxzeIe829zTT-OordmaP-BpzfG0gRGim4Jl2F6ARk,53049 +tensorflow/python/ops/resource_variable_ops.py,sha256=uou0fnJ-3OMyS8nJ21yP7-wbExTiyCSoE4ZsaJjHXSA,113339 +tensorflow/python/ops/resources.py,sha256=Q92WGiuW7fjrbj59WFKN8zEz-F9dg9ghYt_G2hPvgR4,4390 +tensorflow/python/ops/rnn.py,sha256=ukn-PAbzHoArVXFx7hC45BhTuHTdo5LYWKw1TrA1aRw,70378 +tensorflow/python/ops/rnn_cell.py,sha256=lAj0E3jrl7zK0KzBFL58xrpEPIiDb-TCxYb5scyhpSY,871 +tensorflow/python/ops/rnn_cell_impl.py,sha256=pJBAol3A9XuPLYAmmVb3L8d9t0HSkGB0207lzCwvKpg,6160 +tensorflow/python/ops/rnn_grad.py,sha256=_R7m1HcyQe54TdV0kJNwj0rtBGaBruk2WF9zduraSUs,1728 +tensorflow/python/ops/script_ops.py,sha256=u0L3RPuNMbsDgpbqPlL3k1LfVa1BkvYUXrGkskTHUiM,38972 +tensorflow/python/ops/sdca_ops.py,sha256=y785sCc3KWSVOMCiT81-LhSS4W8eJz5QDizqqPlcEyk,1151 +tensorflow/python/ops/session_ops.py,sha256=nZPFINnXtU0r19DNQoS4rOwoap_D5l7G3lbTPn_i3aY,10217 +tensorflow/python/ops/sets.py,sha256=wPi7W-hkBZKIQl6bj51-4GPMyl6F7ep7AFimbVJmM1I,893 +tensorflow/python/ops/sets_impl.py,sha256=q2CTAh7mGO0EgES3c0u6aA2QihvC-rxZn-cxb0lJMCs,12678 +tensorflow/python/ops/shape_util.py,sha256=cFfGoWH9g6BXf4mQtPxJxywPdfRyuxUVaeAGghh7rYA,2919 +tensorflow/python/ops/signal/__init__.py,sha256=2-y1bwsVch6ceSyJymu5Fo1CXY-8QCoVYaa5atTVQUA,1328 +tensorflow/python/ops/signal/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/ops/signal/__pycache__/dct_ops.cpython-310.pyc,, +tensorflow/python/ops/signal/__pycache__/fft_ops.cpython-310.pyc,, +tensorflow/python/ops/signal/__pycache__/mel_ops.cpython-310.pyc,, +tensorflow/python/ops/signal/__pycache__/mfcc_ops.cpython-310.pyc,, +tensorflow/python/ops/signal/__pycache__/reconstruction_ops.cpython-310.pyc,, +tensorflow/python/ops/signal/__pycache__/shape_ops.cpython-310.pyc,, +tensorflow/python/ops/signal/__pycache__/signal.cpython-310.pyc,, +tensorflow/python/ops/signal/__pycache__/spectral_ops.cpython-310.pyc,, +tensorflow/python/ops/signal/__pycache__/util_ops.cpython-310.pyc,, +tensorflow/python/ops/signal/__pycache__/window_ops.cpython-310.pyc,, +tensorflow/python/ops/signal/dct_ops.py,sha256=Iuevy2Hj6KBurnJMTde280bzyKTCvojY5uOho_wMY2w,10335 +tensorflow/python/ops/signal/fft_ops.py,sha256=0EzQMmz-J_oEkGh7zJIWbkCMZGWta-u1CUDHy1ZP6Ig,26479 +tensorflow/python/ops/signal/mel_ops.py,sha256=1xccdppEIuZ3VLL9nRrXC2G3_O-RN5IpLnHi4KAdMWo,9503 +tensorflow/python/ops/signal/mfcc_ops.py,sha256=sNC0oWe5Sm2mdwzfl0PetBjmlwbwrg0vTSHod18kEU4,4762 +tensorflow/python/ops/signal/reconstruction_ops.py,sha256=tJ4I3Po1xtC8JqKEa5LrowxruGBv_IaA3ztKx7HRkrc,6187 +tensorflow/python/ops/signal/shape_ops.py,sha256=dluzeusuip2T34QMhuAvu3o4V21Cgal-pbXWTVD9EQ4,10129 +tensorflow/python/ops/signal/signal.py,sha256=HS66TRDAiwmOcXUm44Gcc2GESZv7HLz210HuUd5u6wI,2344 +tensorflow/python/ops/signal/spectral_ops.py,sha256=qkhHrovFpUXq456ix6GaD-ASss4pEsmQlH7lhz3Xcko,20065 +tensorflow/python/ops/signal/util_ops.py,sha256=4m6I8DECgjep-ugXaRpdJcti5tvE4lcdPNzELmonSOU,2545 +tensorflow/python/ops/signal/window_ops.py,sha256=QyEENBGt2UyKaTYMNw0cxIZh9mRpdB7djwO2FCMorz8,9577 +tensorflow/python/ops/sort_ops.py,sha256=VY89uz6hFEPDynn_kACJ7aflFdSm-RQnbawgwPB1crs,10389 +tensorflow/python/ops/sparse_grad.py,sha256=LuGzNtZ_8g1RGh1nJ5kjFQH0bKHnOMX_sgPnnJSa1_g,13639 +tensorflow/python/ops/sparse_ops.py,sha256=kjZWSMbxMkMHgwzPmwCebmM3NfovHNzmwL9qRrLn1Ns,143193 +tensorflow/python/ops/special_math_ops.py,sha256=hTzwTv5V4SClC0hiN6Ml_EGtT3OaMvhFHizU6P7mzY0,47515 +tensorflow/python/ops/standard_ops.py,sha256=MRRo3pUJUQRjDMwhGa2MOAogr4XlqX7hYqXcxUJhmFI,6077 +tensorflow/python/ops/state_grad.py,sha256=6fI0-viC5DhmI_pmYlzgNPyQHnjPaQYCkeYAFDDl3FM,1339 +tensorflow/python/ops/state_ops.py,sha256=G8QxKUjsieroz9aLgPbDe2GYkSUHw4IdNCZp0gHd_pg,40311 +tensorflow/python/ops/stateful_random_ops.py,sha256=HlpXaboyaTctmYJMvqBE69bNTx-uVxrNW-T0zMPZwFw,40006 +tensorflow/python/ops/stateless_random_ops.py,sha256=leL89s871M0QVB7UQb6nDnZkJhyDe_IHOfXqLrGCxzw,38431 +tensorflow/python/ops/string_ops.py,sha256=LSCEBMNKvSroP3Td9_98ZuAofOqLYXKpPRltTyycj-Q,24777 +tensorflow/python/ops/structured/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/ops/structured/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/ops/structured/__pycache__/structured_array_ops.cpython-310.pyc,, +tensorflow/python/ops/structured/__pycache__/structured_ops.cpython-310.pyc,, +tensorflow/python/ops/structured/__pycache__/structured_tensor.cpython-310.pyc,, +tensorflow/python/ops/structured/__pycache__/structured_tensor_dynamic.cpython-310.pyc,, +tensorflow/python/ops/structured/structured_array_ops.py,sha256=6CUosVb7XTTTQclHzww155Sx85Bz-LCYxiPLqn_81tc,22428 +tensorflow/python/ops/structured/structured_ops.py,sha256=Nxz5xWHUowtNwyS2cHYT2bP9Bbqo7fLzZmbPvxPVFkI,1042 +tensorflow/python/ops/structured/structured_tensor.py,sha256=BzTpAw0iNMZzBaRSVigZUEywk0UGklBp06DbwQc3RSQ,71115 +tensorflow/python/ops/structured/structured_tensor_dynamic.py,sha256=CTBPgZFFNmuSTwphonJSRUdu6nUO5EUpa_mxtKwcFqQ,2154 +tensorflow/python/ops/summary_op_util.py,sha256=FNBrJ8WDwyF-_mms3uWD07AvByiRxz5rQL1sNr-uXZ8,4121 +tensorflow/python/ops/summary_ops_v2.py,sha256=jbVbl3LEfJyR7ncDW4W8xZ02MHE1D1gjVaGgMx1sdTY,53137 +tensorflow/python/ops/template.py,sha256=YN_g8yrCQWGqmXNWAEzLVM7Y8L5Qm0c4O_AjCDSGVlI,31941 +tensorflow/python/ops/tensor_array_grad.py,sha256=ShfWvZzwRcs-Y7MlyY4pZ30FMwweXSGQD9wuopFNR3I,10553 +tensorflow/python/ops/tensor_array_ops.py,sha256=FcHwrHiHvXeQV436hjiJc_IQ_DT0wJN2NpNC_Mko-QQ,57778 +tensorflow/python/ops/unconnected_gradients.py,sha256=f57BW6EsTu3fUV9Bp_VqsNdNpzja0vtlD8dCZbOEfIY,1677 +tensorflow/python/ops/variable_scope.py,sha256=adSM33eyBEDav-KTXI6RYm_XdA7nAxlwPM5YOIWk10g,118834 +tensorflow/python/ops/variable_v1.py,sha256=Xu316vgwL3pa6HCp1V9eCC0eINUufv1lE4mn3Fx0QDM,13789 +tensorflow/python/ops/variables.py,sha256=Ui7zLRzEwsi4LVZCCsMm-xnRFsuoGXP9ab7WgRoZMPU,73713 +tensorflow/python/ops/weak_tensor_ops.py,sha256=F6kqNznWsjaZ9WcGmY8xHf6_I6XnSPKSLWoJXUpPb_U,29346 +tensorflow/python/ops/weak_tensor_test_util.py,sha256=ZeR9OT4hjadNYYD9BJMG18Q4-VPlUuHaUpYAI8EGBXU,3240 +tensorflow/python/ops/weights_broadcast_ops.py,sha256=iPgHyLV_OSsJCSwoUqGh-H910Qaz7xshwpf_f8jFZBM,7775 +tensorflow/python/ops/while_loop.py,sha256=vMYmwihGje7f3eyg8aV9aYk_zpMMX3SVcaICucDCDAY,23199 +tensorflow/python/ops/while_v2.py,sha256=_m1p4VAaLEeSeZ2bT901zeiWMnmdNoWbcNG0WfySOtg,60184 +tensorflow/python/ops/while_v2_indexed_slices_rewriter.py,sha256=zZb_jOnUjw4yYKvrqpmjSjWIEy6IwpUHB236sUgTrNk,12654 +tensorflow/python/platform/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/platform/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/platform/__pycache__/analytics.cpython-310.pyc,, +tensorflow/python/platform/__pycache__/app.cpython-310.pyc,, +tensorflow/python/platform/__pycache__/benchmark.cpython-310.pyc,, +tensorflow/python/platform/__pycache__/build_info.cpython-310.pyc,, +tensorflow/python/platform/__pycache__/device_context.cpython-310.pyc,, +tensorflow/python/platform/__pycache__/flags.cpython-310.pyc,, +tensorflow/python/platform/__pycache__/gfile.cpython-310.pyc,, +tensorflow/python/platform/__pycache__/googletest.cpython-310.pyc,, +tensorflow/python/platform/__pycache__/remote_utils.cpython-310.pyc,, +tensorflow/python/platform/__pycache__/resource_loader.cpython-310.pyc,, +tensorflow/python/platform/__pycache__/self_check.cpython-310.pyc,, +tensorflow/python/platform/__pycache__/sysconfig.cpython-310.pyc,, +tensorflow/python/platform/__pycache__/test.cpython-310.pyc,, +tensorflow/python/platform/__pycache__/tf_logging.cpython-310.pyc,, +tensorflow/python/platform/_pywrap_cpu_feature_guard.pyi,sha256=X8nrDG8adnU2vAjIscTC0EYiQHqdufOqNszYBc2h388,736 +tensorflow/python/platform/_pywrap_cpu_feature_guard.so,sha256=1VH6vitNIxctWTl1qxR_nAjbhYHEYldj4oJJaLB7hmg,138472 +tensorflow/python/platform/_pywrap_stacktrace_handler.pyi,sha256=ua7hYAmdhtx4W7iiJfCpoA97GADhqdchMa3UdM0pVnk,734 +tensorflow/python/platform/_pywrap_stacktrace_handler.so,sha256=bkn71z_OKND8ajmr5kY4ZKXF2XtZwYO4QgQOQGzD0w0,138464 +tensorflow/python/platform/_pywrap_tf2.pyi,sha256=uegEIyosIQKday40Ri3L5qJiSMpGAH4mNIrWWV8DFDA,756 +tensorflow/python/platform/_pywrap_tf2.so,sha256=pvuCOfoqCkA2DDAn_kJZ57U9krJ_Ell2XR-SmC2ZPR8,2604424 +tensorflow/python/platform/analytics.py,sha256=OnvqIWpoYLE4OU2ScUdWnUH2cNhjs-kdIsJn_T_RDz8,980 +tensorflow/python/platform/app.py,sha256=kn7X8yRXnvdgriWo3BKe6iKCDRxrNBEcwZmEMmCGBr0,1326 +tensorflow/python/platform/benchmark.py,sha256=GcrLdtS3kIuiBQxn4F98q0_PjinxKbGAlNpkJGJryzo,17551 +tensorflow/python/platform/build_info.py,sha256=LixRoTofWPben5i5VmoWs7YLmY9YxUa12wiu9eSVgTY,1077 +tensorflow/python/platform/device_context.py,sha256=qAitxy8it63V1uPbmWFIVF3idEFbUVcfkev67MOQlPs,763 +tensorflow/python/platform/flags.py,sha256=byROYLVCsSi7BxkLVLj4g4_YYTjtlsrGEyV5I4ZtP2k,4086 +tensorflow/python/platform/gfile.py,sha256=Pa8AEVojxNk1nLd_9rZX3aWYVeU69FVarDFts_6IMak,5065 +tensorflow/python/platform/googletest.py,sha256=SF0481ahBtjquoFkrs0ofGKXwuGKbQyrxn20fC2PBVA,8902 +tensorflow/python/platform/remote_utils.py,sha256=-LT8izYULhjyLDK53DXUq9yferNcB8HgBGqshYFf4Tw,988 +tensorflow/python/platform/resource_loader.py,sha256=QRg-wQn36S7_McDYpZCC7TQnZVjC_2iqJgQi5wxI9ZE,4412 +tensorflow/python/platform/self_check.py,sha256=U5xJFEtCrZ44q621ZSbrReefP3YIh5R9AS6_4lwwrXE,2843 +tensorflow/python/platform/sysconfig.py,sha256=PGKOTnyoLkdvyRGZGdxIdj1HSPCvJxoySDtZ54behWk,4835 +tensorflow/python/platform/test.py,sha256=hQXG2ZEW4mjejhMQH8wsO80cNoGrr5qI-w1vpWFZQXA,6027 +tensorflow/python/platform/tf_logging.py,sha256=0X2XvI0qZ994uWJw-3LJMNpN3yX5ktTBvcsdNoWE1Og,10635 +tensorflow/python/profiler/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/profiler/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/profiler/__pycache__/model_analyzer.cpython-310.pyc,, +tensorflow/python/profiler/__pycache__/option_builder.cpython-310.pyc,, +tensorflow/python/profiler/__pycache__/profiler.cpython-310.pyc,, +tensorflow/python/profiler/__pycache__/profiler_client.cpython-310.pyc,, +tensorflow/python/profiler/__pycache__/profiler_v2.cpython-310.pyc,, +tensorflow/python/profiler/__pycache__/tfprof_logger.cpython-310.pyc,, +tensorflow/python/profiler/__pycache__/trace.cpython-310.pyc,, +tensorflow/python/profiler/internal/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/profiler/internal/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/profiler/internal/__pycache__/flops_registry.cpython-310.pyc,, +tensorflow/python/profiler/internal/_pywrap_profiler.pyi,sha256=CPYguYQqw1T2XMYW4eTTfFBvVSYAxr528fKnQ6kfQCw,1262 +tensorflow/python/profiler/internal/_pywrap_profiler.so,sha256=jKz1IpdLn4Y5ifJV10m5QauCbJFqQDMRPjOBuREcZ7E,10234528 +tensorflow/python/profiler/internal/_pywrap_traceme.pyi,sha256=lnqV4gAcTtXuKO4rH3VKFxNOFE_UlMuxpKq4-XU9c0k,843 +tensorflow/python/profiler/internal/_pywrap_traceme.so,sha256=XCO0vXZPDz5N4oHzOkZKWXezXKhEP8FR6KutH31Zkp4,219104 +tensorflow/python/profiler/internal/flops_registry.py,sha256=wqD4Rx1M_gpZQTR4E6fA61ZlPeWsd3JQopzwrsIxe0g,17478 +tensorflow/python/profiler/model_analyzer.py,sha256=mx-jVVlMIiS9XuYy2Cd0DvjF-doKAvfxLkFQv2gxFGs,14788 +tensorflow/python/profiler/option_builder.py,sha256=GdskQZnQapz5ZARhT847FwoO53NN9omVCjo2XUK_Dvo,16546 +tensorflow/python/profiler/profiler.py,sha256=2mZ4MgUunHoqQ61TALb3SBSnL95nWzW1ik6Eoc531iw,1933 +tensorflow/python/profiler/profiler_client.py,sha256=GJKmaE51R209qVwvb16qpcsiz2hdlVePGYPfHVLTFfs,6426 +tensorflow/python/profiler/profiler_v2.py,sha256=-bPDkMQCbaS9tBS74NlasTVoC-4p5NzuOgS2bRD1LCs,7426 +tensorflow/python/profiler/tfprof_logger.py,sha256=S11Rn93MoT1QhNY0ztv97D5NE5hkQp-NTNuO2rQoEOk,8033 +tensorflow/python/profiler/trace.py,sha256=4gqPgkmZ9JsCWOe0d1taNqeOQSIWRbdORe_iXmKlUI0,5917 +tensorflow/python/proto_exports.py,sha256=SS9tw-F_IElklApM0ezZcG8fB5cRog0XJSdbcVqQzB0,2795 +tensorflow/python/pywrap_mlir.py,sha256=pcE5eBTzvOvXknFw0iDw8560AEpXOOehuIQIX_PJTyo,3916 +tensorflow/python/pywrap_sanitizers.py,sha256=4DIOlsYGt1xTjfAta9l_yba_QjQjp5ig8-Cdm7CgvdI,955 +tensorflow/python/pywrap_tensorflow.py,sha256=4nRX8Q3zXNFgzlA3rCZM5s0zVIzSts9gAu1hb9prtJk,3797 +tensorflow/python/pywrap_tensorflow_internal.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/pywrap_tfe.py,sha256=U9SJWHx1PmgfjUmDcWe5JSOW4RPUUIMfkIIVgpjLvpY,1230 +tensorflow/python/saved_model/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/saved_model/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/saved_model/__pycache__/builder.cpython-310.pyc,, +tensorflow/python/saved_model/__pycache__/builder_impl.cpython-310.pyc,, +tensorflow/python/saved_model/__pycache__/constants.cpython-310.pyc,, +tensorflow/python/saved_model/__pycache__/fingerprinting.cpython-310.pyc,, +tensorflow/python/saved_model/__pycache__/fingerprinting_utils.cpython-310.pyc,, +tensorflow/python/saved_model/__pycache__/function_deserialization.cpython-310.pyc,, +tensorflow/python/saved_model/__pycache__/function_serialization.cpython-310.pyc,, +tensorflow/python/saved_model/__pycache__/load.cpython-310.pyc,, +tensorflow/python/saved_model/__pycache__/load_options.cpython-310.pyc,, +tensorflow/python/saved_model/__pycache__/load_v1_in_v2.cpython-310.pyc,, +tensorflow/python/saved_model/__pycache__/loader.cpython-310.pyc,, +tensorflow/python/saved_model/__pycache__/loader_impl.cpython-310.pyc,, +tensorflow/python/saved_model/__pycache__/main_op.cpython-310.pyc,, +tensorflow/python/saved_model/__pycache__/main_op_impl.cpython-310.pyc,, +tensorflow/python/saved_model/__pycache__/method_name_updater.cpython-310.pyc,, +tensorflow/python/saved_model/__pycache__/nested_structure_coder.cpython-310.pyc,, +tensorflow/python/saved_model/__pycache__/path_helpers.cpython-310.pyc,, +tensorflow/python/saved_model/__pycache__/revived_types.cpython-310.pyc,, +tensorflow/python/saved_model/__pycache__/save.cpython-310.pyc,, +tensorflow/python/saved_model/__pycache__/save_context.cpython-310.pyc,, +tensorflow/python/saved_model/__pycache__/save_options.cpython-310.pyc,, +tensorflow/python/saved_model/__pycache__/saved_model.cpython-310.pyc,, +tensorflow/python/saved_model/__pycache__/signature_constants.cpython-310.pyc,, +tensorflow/python/saved_model/__pycache__/signature_def_utils.cpython-310.pyc,, +tensorflow/python/saved_model/__pycache__/signature_def_utils_impl.cpython-310.pyc,, +tensorflow/python/saved_model/__pycache__/signature_serialization.cpython-310.pyc,, +tensorflow/python/saved_model/__pycache__/simple_save.cpython-310.pyc,, +tensorflow/python/saved_model/__pycache__/tag_constants.cpython-310.pyc,, +tensorflow/python/saved_model/__pycache__/tracing_utils.cpython-310.pyc,, +tensorflow/python/saved_model/__pycache__/utils.cpython-310.pyc,, +tensorflow/python/saved_model/__pycache__/utils_impl.cpython-310.pyc,, +tensorflow/python/saved_model/builder.py,sha256=RXmpZmvxpHbmP78LfhVeBNl2XuBRfVRV1_EgFWfu1VI,1073 +tensorflow/python/saved_model/builder_impl.py,sha256=sInH7urvOxqa4lltiaptF-ZC977skvxothmCpZ9NfEs,35351 +tensorflow/python/saved_model/constants.py,sha256=ekLp1a60DCTdDJvs-zVMgD9f1RlXYBj1pdJ1pHU2RbU,5103 +tensorflow/python/saved_model/fingerprinting.py,sha256=mbj1Ig1IC46Ver_WNs-0im2l-gb5XpWvomDIPA6GvOQ,7116 +tensorflow/python/saved_model/fingerprinting_utils.py,sha256=GsxxJ4NjWDRBPhxabCvZFZv8oLmcAS6thCk8dCFfdkY,5343 +tensorflow/python/saved_model/function_deserialization.py,sha256=_40Ln__1dS0WA-SuHtvKjglUV9pJWvd36OkUhcF9wyA,29647 +tensorflow/python/saved_model/function_serialization.py,sha256=TljxOlOKPNr9RuuZj-yZbltBCzSjYNA3RBjGL2cVL_w,8763 +tensorflow/python/saved_model/load.py,sha256=sRml99m3SMPdY8dyI3JOrui9rDfJnkv0eg6H8JBhad4,50188 +tensorflow/python/saved_model/load_options.py,sha256=eSYqq26DhQWUVQrUgc73s3hL1Fbq_Z1zeOoCeNjM3as,5335 +tensorflow/python/saved_model/load_v1_in_v2.py,sha256=4ERQ-EXqrXH6YNJQigrMxcBPDfItGj8CdtAep1sYYZ0,13001 +tensorflow/python/saved_model/loader.py,sha256=dBtTcnyc6vKVwA1_vXB8nrF-yx6mw9kF2AO0S3Epm08,2482 +tensorflow/python/saved_model/loader_impl.py,sha256=98HKMTqB0KUP7B4lavBbOjvp-U9EjXBASI735y6P110,20588 +tensorflow/python/saved_model/main_op.py,sha256=Gm7mOu3V3kUlBRR1nVz8Wosd6a7vEnlH1gz3LbkYxH8,1031 +tensorflow/python/saved_model/main_op_impl.py,sha256=xTuz2g_0F2DZHLlW_vUcV5Lyj4QZlDcjcUE4WAQReOE,2653 +tensorflow/python/saved_model/method_name_updater.py,sha256=iHy_rHp2B4ZOgnhTabUV_L4YtxBJ2h0rWGzPZ5sM_8o,6004 +tensorflow/python/saved_model/model_utils/__init__.py,sha256=f4P-hc1aNk2d_RJ-I1W1pwiPNE5tBjwAHT5HwsC5jJo,1608 +tensorflow/python/saved_model/model_utils/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/saved_model/model_utils/__pycache__/export_output.cpython-310.pyc,, +tensorflow/python/saved_model/model_utils/__pycache__/export_utils.cpython-310.pyc,, +tensorflow/python/saved_model/model_utils/__pycache__/mode_keys.cpython-310.pyc,, +tensorflow/python/saved_model/model_utils/export_output.py,sha256=iovmypXDoKTE2Oi4xhIO8mJhuqiTPx8aGKS262OQEiI,15341 +tensorflow/python/saved_model/model_utils/export_utils.py,sha256=2pMTlGEny5eIx73WtjbLyd5Koqvad_I44U99ZGjyOKg,17383 +tensorflow/python/saved_model/model_utils/mode_keys.py,sha256=sAH9XmV98pNKs0_2Rvn3es-k8rJNJLbt0bCPbQq4v4s,3220 +tensorflow/python/saved_model/nested_structure_coder.py,sha256=5x813z4IJTEr3VS26yzze1pUEtb0TRU27zhv4AyYqw4,16128 +tensorflow/python/saved_model/path_helpers.py,sha256=oz2Tw3eFKs7x4mZQ-aUJtyoGogGc_5mJWYKEwVwR2d4,2790 +tensorflow/python/saved_model/pywrap_saved_model.so,sha256=J-u9JHjGU4-OoWLCEa2F2-Z7oYohMf_jmZEOKwXBZjc,1908344 +tensorflow/python/saved_model/pywrap_saved_model/__init__.pyi,sha256=ew28pvurtWKrIxYS7t0ZnWqefHpF4ImRQVoc6ouVhxg,723 +tensorflow/python/saved_model/pywrap_saved_model/constants.pyi,sha256=KjdqYv_TydNadzuqPVBBcqh1w8m8VdkDCu9X4ssRDoo,1150 +tensorflow/python/saved_model/pywrap_saved_model/fingerprinting.pyi,sha256=b_2R6OZ8Wns7mtXYyUXfK1GBG3BdXqpff-eOYam-has,1132 +tensorflow/python/saved_model/pywrap_saved_model/merger.pyi,sha256=1qqKZ1l19gERS66P8HjIKOp9eC-xlR3ngauGwZbocDk,797 +tensorflow/python/saved_model/pywrap_saved_model/metrics.pyi,sha256=JLbQuZ7Vyn-Kdn3HPV0W6GYe6_vJ9WEeSrS71KSRMe0,2466 +tensorflow/python/saved_model/registration/__init__.py,sha256=0cOI680e00oCyYLa13TZYrmuiWOULyiLGq3AEy6VjgA,2456 +tensorflow/python/saved_model/registration/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/saved_model/registration/__pycache__/registration.cpython-310.pyc,, +tensorflow/python/saved_model/registration/registration.py,sha256=8Jc5KcXkuzzME8b7rrDCovH5X84L8jsUB_1GdjZJqpk,15346 +tensorflow/python/saved_model/revived_types.py,sha256=nbVZrX0K08fK4iB1TamOJ59pcIGOPSaxxYxebVakucQ,9637 +tensorflow/python/saved_model/save.py,sha256=2djDGHdiN_XSAeTKuQghZBHEm5hyGUVaeEnpSEzgYrw,67484 +tensorflow/python/saved_model/save_context.py,sha256=BFHVtIMoToAuWr8kmSJlFxyITUB38mUgwXPn3ze5vdE,1865 +tensorflow/python/saved_model/save_options.py,sha256=_tpsmI0TlGaUcznDEQFDxqV0v5F_0ff0jqAAdNX5exQ,9280 +tensorflow/python/saved_model/saved_model.py,sha256=VrLq5yTjriYFsJctU_apbZFhYbGn_kc41Q2CK_TFcSg,1661 +tensorflow/python/saved_model/signature_constants.py,sha256=JBaLBw6-9KQ9DqvyGTHGc31WgAaZcrv5ygBsBYmxahI,4967 +tensorflow/python/saved_model/signature_def_utils.py,sha256=lAzf79PUbeto1wrOtQg6eo6vE7KTKTlq2Qt2zMdHFQE,1682 +tensorflow/python/saved_model/signature_def_utils_impl.py,sha256=HL_x88UDLRzX-x3vZo6DtqDIs0KEinmyjUI-qH4Je5A,15555 +tensorflow/python/saved_model/signature_serialization.py,sha256=CiuM_-0LplhvzPEtyw7ERPzboCqNJF_SHhCYN8wF9os,15414 +tensorflow/python/saved_model/simple_save.py,sha256=5VVo9VKBrpzwfEkJthOod9xdxrB_1chiR3ewEhPhi0U,4093 +tensorflow/python/saved_model/tag_constants.py,sha256=okwsyPXrMvjNItYvoxa8HHgCpL9Pu4ztXI-LklcFsBk,1873 +tensorflow/python/saved_model/tracing_utils.py,sha256=h3ByL1ezfLEClb2zZu0YcLfIYlvoM7-Bf1j6e_WqsX4,2712 +tensorflow/python/saved_model/utils.py,sha256=L5kP0SFcE_ExSM4elUNpxnO2JknJJT9X_b-pFQiiGkE,1102 +tensorflow/python/saved_model/utils_impl.py,sha256=eVndpI6l6LHMHkPUiRFy9bPAFcGRiF2wtu5SOxYiQ9I,8651 +tensorflow/python/summary/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/summary/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/summary/__pycache__/plugin_asset.cpython-310.pyc,, +tensorflow/python/summary/__pycache__/summary.cpython-310.pyc,, +tensorflow/python/summary/__pycache__/summary_iterator.cpython-310.pyc,, +tensorflow/python/summary/plugin_asset.py,sha256=UiNa4PnjUSL8XVKqa69zj2Bhq4ZZ3M245jzRdC0NzT0,5036 +tensorflow/python/summary/summary.py,sha256=r3O898-gnp8zJL6BW4AjNXFjeDlVXY7BpiRhFrev-4U,38236 +tensorflow/python/summary/summary_iterator.py,sha256=ngm_oAMZhU-lKB3Q753bNyhDud6cYn59mgQ8qVGHc-Y,3085 +tensorflow/python/summary/writer/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/summary/writer/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/summary/writer/__pycache__/event_file_writer.cpython-310.pyc,, +tensorflow/python/summary/writer/__pycache__/event_file_writer_v2.cpython-310.pyc,, +tensorflow/python/summary/writer/__pycache__/writer.cpython-310.pyc,, +tensorflow/python/summary/writer/__pycache__/writer_cache.cpython-310.pyc,, +tensorflow/python/summary/writer/event_file_writer.py,sha256=jZCquoce3i_iRD3lpNsLxeSkiKNT368YL15g-wqddI0,10400 +tensorflow/python/summary/writer/event_file_writer_v2.py,sha256=UORugSd6fvY6pkzLoW_3hOkfQ6gSbRiUHw6QBDFrL2A,5678 +tensorflow/python/summary/writer/writer.py,sha256=xEEI3M-i_82uxv4znw3nuBf7s0GTg0U7GMxzn8ipmBE,19182 +tensorflow/python/summary/writer/writer_cache.py,sha256=WHsyzgnnjpDariqXSmINZoYV36yHVO2Rm3xq093nH4Y,1975 +tensorflow/python/tf2.py,sha256=JoTSbJ35qwhptiU2WwU5S6zFlIO2ncO_TpvFAy6sA1E,1290 +tensorflow/python/tools/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/tools/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/tools/__pycache__/freeze_graph.cpython-310.pyc,, +tensorflow/python/tools/__pycache__/import_pb_to_tensorboard.cpython-310.pyc,, +tensorflow/python/tools/__pycache__/inspect_checkpoint.cpython-310.pyc,, +tensorflow/python/tools/__pycache__/module_util.cpython-310.pyc,, +tensorflow/python/tools/__pycache__/optimize_for_inference.cpython-310.pyc,, +tensorflow/python/tools/__pycache__/optimize_for_inference_lib.cpython-310.pyc,, +tensorflow/python/tools/__pycache__/print_selective_registration_header.cpython-310.pyc,, +tensorflow/python/tools/__pycache__/saved_model_aot_compile.cpython-310.pyc,, +tensorflow/python/tools/__pycache__/saved_model_cli.cpython-310.pyc,, +tensorflow/python/tools/__pycache__/saved_model_utils.cpython-310.pyc,, +tensorflow/python/tools/__pycache__/selective_registration_header_lib.cpython-310.pyc,, +tensorflow/python/tools/__pycache__/strip_unused.cpython-310.pyc,, +tensorflow/python/tools/__pycache__/strip_unused_lib.cpython-310.pyc,, +tensorflow/python/tools/api/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/tools/api/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/tools/api/generator/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/tools/api/generator/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/tools/api/generator/__pycache__/create_python_api.cpython-310.pyc,, +tensorflow/python/tools/api/generator/__pycache__/doc_srcs.cpython-310.pyc,, +tensorflow/python/tools/api/generator/create_python_api.py,sha256=esiYrqcv4a4OykehtqX2gSJINnF7MkIXgYpP6RcMp14,33575 +tensorflow/python/tools/api/generator/doc_srcs.py,sha256=wlc2cao9W8EFnegj0Jstf9zPCJo5SsUgtnpHFhEifVI,5121 +tensorflow/python/tools/api/generator2/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/tools/api/generator2/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/tools/api/generator2/extractor/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/tools/api/generator2/extractor/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/tools/api/generator2/extractor/__pycache__/extractor.cpython-310.pyc,, +tensorflow/python/tools/api/generator2/extractor/extractor.py,sha256=osBYxc2ali_Mh6qOsNeG6_q7reEjvwZoDU8wAwZi2VE,12602 +tensorflow/python/tools/api/generator2/generator/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/tools/api/generator2/generator/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/tools/api/generator2/generator/__pycache__/generator.cpython-310.pyc,, +tensorflow/python/tools/api/generator2/generator/generator.py,sha256=Kwrr-8SZ5eaqxyvF153Ydw-nw419v4kPsf9NRny24tE,25293 +tensorflow/python/tools/api/generator2/shared/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/tools/api/generator2/shared/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/tools/api/generator2/shared/__pycache__/exported_api.cpython-310.pyc,, +tensorflow/python/tools/api/generator2/shared/exported_api.py,sha256=UGQAZUk-29H7oJu8KtUmuY5JEiCq_h2ca2dzFyqO4Pg,3278 +tensorflow/python/tools/freeze_graph.py,sha256=0pBAkfVoK0mGCrHio8wLfv5323d1qT3Q-YZ5pQsIKng,18605 +tensorflow/python/tools/import_pb_to_tensorboard.py,sha256=jpRrX841qd9axgW2XfQSDNcRudYd35VTLgqI0zY_uWw,3361 +tensorflow/python/tools/inspect_checkpoint.py,sha256=jSrAKMRt5hsTFCyHWBvkoSwb7hDgR6gYXWLAJ_SmVwM,7505 +tensorflow/python/tools/module_util.py,sha256=ZYfxbhgrLkeDEwmpiEwwDJFEN2u0euBW-u2EdgMfkvs,1593 +tensorflow/python/tools/optimize_for_inference.py,sha256=C5YKHfXEjIuD0tsX1EhCHpmyZ3nJ4ilK-3w8Osk6x2Y,5141 +tensorflow/python/tools/optimize_for_inference_lib.py,sha256=CKJPVe3QxB90DfzW3sAx5t9CHkwUEYC3VfvsJR0K6Ps,21123 +tensorflow/python/tools/print_selective_registration_header.py,sha256=tW96qUlf7tD-mZ-0LxlQnIpI5miEPvsqNpQ_fOeNM5g,3144 +tensorflow/python/tools/saved_model_aot_compile.py,sha256=BcnMvsVo3QRRTpadY62y50e2bDLJoxNxp0elzaPDCrc,21070 +tensorflow/python/tools/saved_model_cli.py,sha256=LTaxrPaqXspLju8LVffoP1f1bvE5iuTlrb647f_PIbk,52178 +tensorflow/python/tools/saved_model_utils.py,sha256=FbO1czEJqZYxV9wjrfAKNjegwZK3ilZ6HE0FlPq-bLo,4654 +tensorflow/python/tools/selective_registration_header_lib.py,sha256=VXjhPEoDSq1DbNF0lPxurOlBpjI3WDWmx2-gZAgMNkY,8423 +tensorflow/python/tools/strip_unused.py,sha256=6EwICtbbgv3aLzYDgSOZPdmWt_DDHbGNHThcoXjV9pM,3655 +tensorflow/python/tools/strip_unused_lib.py,sha256=YXVz_KQKPfosoiaQyGg_gFn50wWqOtM4dBbuxVtbNr8,4841 +tensorflow/python/tpu/__init__.py,sha256=0rcGq06CniAZlHQoiaZRyBehGDZxxuN6UQ_j7wsNsE4,791 +tensorflow/python/tpu/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/tpu/__pycache__/api.cpython-310.pyc,, +tensorflow/python/tpu/__pycache__/async_checkpoint.cpython-310.pyc,, +tensorflow/python/tpu/__pycache__/bfloat16.cpython-310.pyc,, +tensorflow/python/tpu/__pycache__/datasets.cpython-310.pyc,, +tensorflow/python/tpu/__pycache__/device_assignment.cpython-310.pyc,, +tensorflow/python/tpu/__pycache__/error_handling.cpython-310.pyc,, +tensorflow/python/tpu/__pycache__/feature_column.cpython-310.pyc,, +tensorflow/python/tpu/__pycache__/feature_column_v2.cpython-310.pyc,, +tensorflow/python/tpu/__pycache__/functional.cpython-310.pyc,, +tensorflow/python/tpu/__pycache__/preempted_hook.cpython-310.pyc,, +tensorflow/python/tpu/__pycache__/session_support.cpython-310.pyc,, +tensorflow/python/tpu/__pycache__/tensor_tracer.cpython-310.pyc,, +tensorflow/python/tpu/__pycache__/tensor_tracer_flags.cpython-310.pyc,, +tensorflow/python/tpu/__pycache__/tensor_tracer_pb2.cpython-310.pyc,, +tensorflow/python/tpu/__pycache__/tensor_tracer_report.cpython-310.pyc,, +tensorflow/python/tpu/__pycache__/topology.cpython-310.pyc,, +tensorflow/python/tpu/__pycache__/tpu.cpython-310.pyc,, +tensorflow/python/tpu/__pycache__/tpu_config.cpython-310.pyc,, +tensorflow/python/tpu/__pycache__/tpu_context.cpython-310.pyc,, +tensorflow/python/tpu/__pycache__/tpu_embedding.cpython-310.pyc,, +tensorflow/python/tpu/__pycache__/tpu_embedding_base.cpython-310.pyc,, +tensorflow/python/tpu/__pycache__/tpu_embedding_for_serving.cpython-310.pyc,, +tensorflow/python/tpu/__pycache__/tpu_embedding_gradient.cpython-310.pyc,, +tensorflow/python/tpu/__pycache__/tpu_embedding_v1.cpython-310.pyc,, +tensorflow/python/tpu/__pycache__/tpu_embedding_v2.cpython-310.pyc,, +tensorflow/python/tpu/__pycache__/tpu_embedding_v2_utils.cpython-310.pyc,, +tensorflow/python/tpu/__pycache__/tpu_estimator.cpython-310.pyc,, +tensorflow/python/tpu/__pycache__/tpu_feed.cpython-310.pyc,, +tensorflow/python/tpu/__pycache__/tpu_function.cpython-310.pyc,, +tensorflow/python/tpu/__pycache__/tpu_hardware_feature.cpython-310.pyc,, +tensorflow/python/tpu/__pycache__/tpu_name_util.cpython-310.pyc,, +tensorflow/python/tpu/__pycache__/tpu_optimizer.cpython-310.pyc,, +tensorflow/python/tpu/__pycache__/tpu_replication.cpython-310.pyc,, +tensorflow/python/tpu/__pycache__/tpu_sharding.cpython-310.pyc,, +tensorflow/python/tpu/__pycache__/tpu_strategy_util.cpython-310.pyc,, +tensorflow/python/tpu/__pycache__/tpu_system_metadata.cpython-310.pyc,, +tensorflow/python/tpu/__pycache__/training_loop.cpython-310.pyc,, +tensorflow/python/tpu/__pycache__/util.cpython-310.pyc,, +tensorflow/python/tpu/api.py,sha256=uhr9mgtAVqKjzt-UsGLQrFazQ-AYrvy6nFHn60o25Ss,1416 +tensorflow/python/tpu/async_checkpoint.py,sha256=CD9TTwdxnPJgYX6ndMiV3aMygSFIe8b8_PCzy1prlk0,11076 +tensorflow/python/tpu/bfloat16.py,sha256=gi0Jr_9VfYqiutrvBU4BGPVqYVc1fYoo-5vmUsfpRkM,3212 +tensorflow/python/tpu/client/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/tpu/client/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/tpu/client/__pycache__/client.cpython-310.pyc,, +tensorflow/python/tpu/client/__pycache__/version.cpython-310.pyc,, +tensorflow/python/tpu/client/client.py,sha256=mD_uSRmMefS43AAgSsUndR5CcoPB41q33caa1FMHN3s,14785 +tensorflow/python/tpu/client/version.py,sha256=eax4DYdszDedoTNjKK9Knxgh6NpW09zSqxat6TZwy4A,754 +tensorflow/python/tpu/datasets.py,sha256=xN1ooTPyFL63Wt7whX-BMbrD0wU7HNCBnjq08WC4Jp4,8156 +tensorflow/python/tpu/device_assignment.py,sha256=JkXSrNJZQVfqvovXihkZxsWvIFDjSOLCo22cW680PeE,21584 +tensorflow/python/tpu/error_handling.py,sha256=ga1Q5DFuLQ8ftcw3Sy0L9SJtUdhSnsCv95bTjOOzNdc,905 +tensorflow/python/tpu/feature_column.py,sha256=THhHIVTO3LoEFklHICoV11u2azBxCpVkenCxVX492HY,30230 +tensorflow/python/tpu/feature_column_v2.py,sha256=nHZOC_DiEDFcIuCXLsDnZ6gyguArbBEMZfipGYb2cB8,47960 +tensorflow/python/tpu/functional.py,sha256=vq02-2ynUOFGMmRHQUg_l8eNd3lk8ifXxHSyIcsULAQ,847 +tensorflow/python/tpu/ops/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/tpu/ops/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/tpu/ops/__pycache__/tpu_ops.cpython-310.pyc,, +tensorflow/python/tpu/ops/tpu_ops.py,sha256=xmECTUhpn_YOFvjZNWbf2IzAgRRYmCootOl8gS6Y_Ws,28022 +tensorflow/python/tpu/preempted_hook.py,sha256=T1O0hc-mlUMiMtmqHq8PrPQGsnRTYwTJQUCx6-DZIW8,3217 +tensorflow/python/tpu/session_support.py,sha256=s-4-yFeAPXGHXhkB2lPqQMlAWIQQcSKG5OgBwxkS-fQ,15131 +tensorflow/python/tpu/tensor_tracer.py,sha256=l9H09yYbpISkFgbIwX4v1KpD9mFkbMOn_fnDa-OJXwM,98744 +tensorflow/python/tpu/tensor_tracer_flags.py,sha256=8ryvqPX5jkv2xLunWboIiGcu1m8_We1JiFIF5InWeJQ,18459 +tensorflow/python/tpu/tensor_tracer_pb2.py,sha256=T-49RUzOX7DULdsmMcBphq_MjUpnrNn5JN1hSu_efn0,4245 +tensorflow/python/tpu/tensor_tracer_report.py,sha256=Jb607Gq6TIKqwklODC00HbHnOjGC3bBF1kNKoFU7qoA,17979 +tensorflow/python/tpu/topology.py,sha256=RrN50OW3THOiQukPNvOnaJP2YstXQXHhFIRD-OWELps,10126 +tensorflow/python/tpu/tpu.py,sha256=hisO-TOj6_FGhuk0LAIZA4UQFrDzl6Tu8r0yjNjsGYU,72015 +tensorflow/python/tpu/tpu_config.py,sha256=AENjb1saK7qAvAVhjN7IEpWo-DsD-C1BC5iSWPi-chA,901 +tensorflow/python/tpu/tpu_context.py,sha256=hP28XdqLZriyk3pVo_IognOXLEh2MmxSsjc_zJg11_s,902 +tensorflow/python/tpu/tpu_embedding.py,sha256=MmfZQPj221gn_Nj2iK7j5a7M34hG8fZXpG6_-pU62X0,128027 +tensorflow/python/tpu/tpu_embedding_base.py,sha256=2mHym5eqHh9YR8Y5sPwCsXXqvsCs3WCVbyhneYj68sk,6084 +tensorflow/python/tpu/tpu_embedding_for_serving.py,sha256=V1yIbkQu9fIzkzcpljAg8wDNAXLcyqUCFBVi2GQTwyo,23470 +tensorflow/python/tpu/tpu_embedding_gradient.py,sha256=60vZmqsRkdGIbFql-WxxvwxALP-YVJzBMKPfKnOCjkI,7701 +tensorflow/python/tpu/tpu_embedding_v1.py,sha256=HwFGIAqQx6U0RberkWL0-kzX5uM4V36Wxka7pb0GWl0,18433 +tensorflow/python/tpu/tpu_embedding_v2.py,sha256=MiVOR90OUr11mgxdi5h4777CV2lg8fRBA4toQL4vtKQ,78126 +tensorflow/python/tpu/tpu_embedding_v2_utils.py,sha256=iOGDlYXCnkc1ORoVUF4ltG7QzUT0TYzhmN7Xiv2tL0o,55075 +tensorflow/python/tpu/tpu_estimator.py,sha256=tGrlqEmdMzh2YXJfaYbbE3BRqK9ayNt2t7LaAdlsSxc,1741 +tensorflow/python/tpu/tpu_feed.py,sha256=_Z4fy0ZI7IhQxhUN3iKKppMOPS7D3XJ5wiSLf3tdRgY,39306 +tensorflow/python/tpu/tpu_function.py,sha256=Qlyuo9iXl3kQ-jdnAJSVtTjd179R0Vm9MSqrxaKIRyE,2434 +tensorflow/python/tpu/tpu_hardware_feature.py,sha256=9FXhpHJFkmNmWq2aDt7xHeDKxy7wmuU9UeYeuNdo-MA,3041 +tensorflow/python/tpu/tpu_name_util.py,sha256=PYdIy48q4rGsXo0xm5FQ58nkpA3UL37MlGI2dqtz2Kw,1138 +tensorflow/python/tpu/tpu_optimizer.py,sha256=Z_lFPIGXmgSH9hJNthJFDYn2pItMqhz-POakO83uZ5I,8820 +tensorflow/python/tpu/tpu_replication.py,sha256=Zg6bzOikNp-72RTIQMGLVj9uZYlm9AZnFp-37d77JvU,31548 +tensorflow/python/tpu/tpu_sharding.py,sha256=9WAJOKDmVrRJvUZ-A_LgZWpItRSN3Q0NptwBSzPc8l4,11244 +tensorflow/python/tpu/tpu_strategy_util.py,sha256=nFcY3V0X033wka8EIZby7Pr2lPwqrvOUgg02Z3TGWgE,13332 +tensorflow/python/tpu/tpu_system_metadata.py,sha256=DNaA0RB9dBsl04EU427aPJYya67GFiqOc67IPikyNRs,8770 +tensorflow/python/tpu/training_loop.py,sha256=_sBNzJAKHkqPLMU82j6ievAp6_8BhM6M1yCtjIZc3DU,9233 +tensorflow/python/tpu/util.py,sha256=HY5KS3ntqddXzkRoxuy1h6soVRDhNV40XsuvEVzM-hI,895 +tensorflow/python/trackable/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/trackable/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/trackable/__pycache__/asset.cpython-310.pyc,, +tensorflow/python/trackable/__pycache__/autotrackable.cpython-310.pyc,, +tensorflow/python/trackable/__pycache__/base.cpython-310.pyc,, +tensorflow/python/trackable/__pycache__/base_delegate.cpython-310.pyc,, +tensorflow/python/trackable/__pycache__/constants.cpython-310.pyc,, +tensorflow/python/trackable/__pycache__/converter.cpython-310.pyc,, +tensorflow/python/trackable/__pycache__/data_structures.cpython-310.pyc,, +tensorflow/python/trackable/__pycache__/layer_utils.cpython-310.pyc,, +tensorflow/python/trackable/__pycache__/python_state.cpython-310.pyc,, +tensorflow/python/trackable/__pycache__/resource.cpython-310.pyc,, +tensorflow/python/trackable/__pycache__/trackable_utils.cpython-310.pyc,, +tensorflow/python/trackable/asset.py,sha256=9xBugI3okcuhGky4Tf4BONWc6yzEgKkgx3EPH1RTPiE,4368 +tensorflow/python/trackable/autotrackable.py,sha256=RZqUPkXhOb512LK-k12wfp90ziwcBtsQQMXAoH4Xzc0,6127 +tensorflow/python/trackable/base.py,sha256=ahHycQdkH96AJW557rh0YaF19m7Pt4-bcK0gmTI4WiE,41928 +tensorflow/python/trackable/base_delegate.py,sha256=Qv1GCQz1Eulw31YH14WtIkn2PLpf0XczsEgLIq7vza0,5601 +tensorflow/python/trackable/constants.py,sha256=qtnSa-JE-lpTzR17FrYT6G570AMLdZrRYJYWdHdKy3Q,1370 +tensorflow/python/trackable/converter.py,sha256=Xc9K0479JZSOsjDYJNpnzOPUwELK-wy_z7jacYSx8cI,1596 +tensorflow/python/trackable/data_structures.py,sha256=XBJH1xPTb9PVr69JxOAIJuxU9rcIpXDd-lcSf9GPFec,39454 +tensorflow/python/trackable/layer_utils.py,sha256=QnMqWEjJy0KgV7AeD5I7zsRlCCDgBEuLe7BADmiMW_k,5024 +tensorflow/python/trackable/python_state.py,sha256=zx4gceDaWulPHLX3BVwu_bnqBxJp0Lj-qAMa1pAA8x0,2834 +tensorflow/python/trackable/resource.py,sha256=qtpbLK8fZ2k4W1euA_V5DFDH-wfvYejjsXV2hQknaJg,10820 +tensorflow/python/trackable/trackable_utils.py,sha256=cS91_AzCGeRGRww86wEea6uXZjJwQYUGia8UP_e7Deo,6802 +tensorflow/python/training/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/training/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/training/__pycache__/adadelta.cpython-310.pyc,, +tensorflow/python/training/__pycache__/adagrad.cpython-310.pyc,, +tensorflow/python/training/__pycache__/adagrad_da.cpython-310.pyc,, +tensorflow/python/training/__pycache__/adam.cpython-310.pyc,, +tensorflow/python/training/__pycache__/basic_loops.cpython-310.pyc,, +tensorflow/python/training/__pycache__/basic_session_run_hooks.cpython-310.pyc,, +tensorflow/python/training/__pycache__/checkpoint_management.cpython-310.pyc,, +tensorflow/python/training/__pycache__/checkpoint_ops.cpython-310.pyc,, +tensorflow/python/training/__pycache__/checkpoint_state_pb2.cpython-310.pyc,, +tensorflow/python/training/__pycache__/checkpoint_utils.cpython-310.pyc,, +tensorflow/python/training/__pycache__/coordinator.cpython-310.pyc,, +tensorflow/python/training/__pycache__/device_setter.cpython-310.pyc,, +tensorflow/python/training/__pycache__/evaluation.cpython-310.pyc,, +tensorflow/python/training/__pycache__/ftrl.cpython-310.pyc,, +tensorflow/python/training/__pycache__/gen_training_ops.cpython-310.pyc,, +tensorflow/python/training/__pycache__/gradient_descent.cpython-310.pyc,, +tensorflow/python/training/__pycache__/input.cpython-310.pyc,, +tensorflow/python/training/__pycache__/learning_rate_decay.cpython-310.pyc,, +tensorflow/python/training/__pycache__/momentum.cpython-310.pyc,, +tensorflow/python/training/__pycache__/monitored_session.cpython-310.pyc,, +tensorflow/python/training/__pycache__/moving_averages.cpython-310.pyc,, +tensorflow/python/training/__pycache__/optimizer.cpython-310.pyc,, +tensorflow/python/training/__pycache__/proximal_adagrad.cpython-310.pyc,, +tensorflow/python/training/__pycache__/proximal_gradient_descent.cpython-310.pyc,, +tensorflow/python/training/__pycache__/py_checkpoint_reader.cpython-310.pyc,, +tensorflow/python/training/__pycache__/quantize_training.cpython-310.pyc,, +tensorflow/python/training/__pycache__/queue_runner.cpython-310.pyc,, +tensorflow/python/training/__pycache__/queue_runner_impl.cpython-310.pyc,, +tensorflow/python/training/__pycache__/rmsprop.cpython-310.pyc,, +tensorflow/python/training/__pycache__/saver.cpython-310.pyc,, +tensorflow/python/training/__pycache__/saver_test_utils.cpython-310.pyc,, +tensorflow/python/training/__pycache__/server_lib.cpython-310.pyc,, +tensorflow/python/training/__pycache__/session_manager.cpython-310.pyc,, +tensorflow/python/training/__pycache__/session_run_hook.cpython-310.pyc,, +tensorflow/python/training/__pycache__/slot_creator.cpython-310.pyc,, +tensorflow/python/training/__pycache__/summary_io.cpython-310.pyc,, +tensorflow/python/training/__pycache__/supervisor.cpython-310.pyc,, +tensorflow/python/training/__pycache__/sync_replicas_optimizer.cpython-310.pyc,, +tensorflow/python/training/__pycache__/training.cpython-310.pyc,, +tensorflow/python/training/__pycache__/training_ops.cpython-310.pyc,, +tensorflow/python/training/__pycache__/training_util.cpython-310.pyc,, +tensorflow/python/training/__pycache__/warm_starting_util.cpython-310.pyc,, +tensorflow/python/training/adadelta.py,sha256=KY8PKYS_5sUXdzw7S2Hfm-uKEQglPUTKJaBihzbhDxk,7300 +tensorflow/python/training/adagrad.py,sha256=fitkWlqf9T8acKgyiPHP1WBXc-jY3oqDiJSgMJupw-Q,7507 +tensorflow/python/training/adagrad_da.py,sha256=W-kJhhhiVOPf4q49pFhFrYGksdzq-U-qvgIcoeq0o1A,7540 +tensorflow/python/training/adam.py,sha256=YVgg_o235RF8S-AePjU9jJMD_DwwfCWulr1gO_VO4mA,12646 +tensorflow/python/training/basic_loops.py,sha256=Y4SRkMKB6hu865eeJ6ml42rtr1iFcIBlpCZtcPQPn40,2323 +tensorflow/python/training/basic_session_run_hooks.py,sha256=tOg79JMfj5lc7PRlAJXW9rZwBl0LLkjbqSoAC_Nhth0,42659 +tensorflow/python/training/checkpoint_management.py,sha256=8m0iuOQ4HtkyMr1BfMfU5XQwN1NUywWamzn_doZBgqE,1051 +tensorflow/python/training/checkpoint_ops.py,sha256=t5ZEate0RXJrcF0BRxF4S-3XkLbtiEieS1SYtuxJdqY,22652 +tensorflow/python/training/checkpoint_state_pb2.py,sha256=TAi64EPFW65Pdd2xrxsSiwLQIrZxLU2A7qscbB5vS1U,1345 +tensorflow/python/training/checkpoint_utils.py,sha256=xSU1GbxXdR_UdwKyqEyt9eK3wigS3KnKsLdVzPKrdNo,22798 +tensorflow/python/training/coordinator.py,sha256=71M8Yt2Wmk76iDLk9wziXS99dHo28KZ4-4dU5QeejQE,18003 +tensorflow/python/training/device_setter.py,sha256=JXS_BAyuM381KpCXDZhVUKjI-SMJ6flVdzna1yWJtm0,9068 +tensorflow/python/training/evaluation.py,sha256=ZaQXh4tD7mTpz0eeN-SaJWT_89zcpUM9SrWiM3exccs,11009 +tensorflow/python/training/experimental/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/training/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/training/experimental/__pycache__/loss_scale.cpython-310.pyc,, +tensorflow/python/training/experimental/__pycache__/loss_scale_optimizer.cpython-310.pyc,, +tensorflow/python/training/experimental/__pycache__/mixed_precision.cpython-310.pyc,, +tensorflow/python/training/experimental/__pycache__/mixed_precision_global_state.cpython-310.pyc,, +tensorflow/python/training/experimental/loss_scale.py,sha256=Tsf0vQge-XX7aqUmg1oUWrV1suPA65KzuLWV-7o6e94,17066 +tensorflow/python/training/experimental/loss_scale_optimizer.py,sha256=4ndAoUksyi0emCcMwIl5Ka7hyGr7lWEhbB5xKU_RAfI,10651 +tensorflow/python/training/experimental/mixed_precision.py,sha256=lTwhiBnHBDzUmoe84vp1shNLfC54A58VByVX2xl8ddY,12604 +tensorflow/python/training/experimental/mixed_precision_global_state.py,sha256=CZAmUz2tWWXOXJi4oy-0aiVbVtjmmebLUt64cPtLXnA,2525 +tensorflow/python/training/ftrl.py,sha256=HxqLpqOJVcpHvebf5Wi2824ShWeD2vZHtsAftllk53A,13451 +tensorflow/python/training/gen_training_ops.py,sha256=zoS2A0gL1FCmlX1GVhpLdsk1Tv2yfZzzMGopuM4wJzc,1116 +tensorflow/python/training/gradient_descent.py,sha256=dU8nYAOKf7eDLQBUvFZnhd4jVrxm73DsJpPNU0KQ2Fc,3401 +tensorflow/python/training/input.py,sha256=OJ7fmwh0-8wu3Ro5Pl8Wndu2rZnRW-0XIJ80a0rwhxM,68139 +tensorflow/python/training/learning_rate_decay.py,sha256=VU52sPAubIMArb3GVO9nGNssx-8ooabLwU6Dmdde_f8,1378 +tensorflow/python/training/momentum.py,sha256=pId3FFXe3I-5nVc6NDimdlyPZ99w2LP9kI6-aGkN69A,7770 +tensorflow/python/training/monitored_session.py,sha256=GASxcElmR4v9NpFLKLxtXIZpjrP0X64n5LfGTEEOuUQ,59971 +tensorflow/python/training/moving_averages.py,sha256=P--aCtjySpVSLZynycHBLwqs--wAVdQuAfa6jZdoHN4,28641 +tensorflow/python/training/optimizer.py,sha256=6nTrJ_8b0_oixBiGZyHg89nF28WNXhWYLThNy3fwU28,54068 +tensorflow/python/training/proximal_adagrad.py,sha256=PyN7_gQKfSPtnvBg2v9apdD49foRZ7l8mfEZfO3qkuk,5634 +tensorflow/python/training/proximal_gradient_descent.py,sha256=pmMQwFkqE3MlI2tVtCkzzgDXTgPC_QoohDoeaBW0Bu4,4502 +tensorflow/python/training/py_checkpoint_reader.py,sha256=5yKymjgE_5EP_g1qwY7Nn8YnEFmN9T1mAkeDjO3TkWo,3702 +tensorflow/python/training/quantize_training.py,sha256=fnF6Fo_DgxSkYnoNSh1EdsOX3k97c9--jztBejkli5o,1843 +tensorflow/python/training/queue_runner.py,sha256=CnJspvUo77Bv401A_13tYOm2NVintZvz72H7qSQw4ek,890 +tensorflow/python/training/queue_runner_impl.py,sha256=nJo_8iipAuXMFH1MdZEO21J_6XRKErIxw6mqxhOxucI,19777 +tensorflow/python/training/rmsprop.py,sha256=0aJcKylNEwLdfhd8qPI9gmtffkTodobCta7g8nzLpj4,12711 +tensorflow/python/training/saver.py,sha256=TaVsPl3z4naftvLgWzIwdpRl5VqKET7JrqdYN9wilR0,76574 +tensorflow/python/training/saver_test_utils.py,sha256=RhI4LwzgtqBplXeqL5PoPicpOu_4LfWx2fNxL-diay8,3179 +tensorflow/python/training/saving/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/training/saving/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/training/saving/__pycache__/saveable_object.cpython-310.pyc,, +tensorflow/python/training/saving/__pycache__/saveable_object_util.cpython-310.pyc,, +tensorflow/python/training/saving/__pycache__/trace_saveable_util.cpython-310.pyc,, +tensorflow/python/training/saving/saveable_object.py,sha256=HTNQuB-ITFw4g93-mh357VsfDXCToKXbGMWfCkU0SF8,3369 +tensorflow/python/training/saving/saveable_object_util.py,sha256=VNt58OHcTKrOyJh3bdpb2QUaGHDATwesRHRR-qe-eQk,33071 +tensorflow/python/training/saving/trace_saveable_util.py,sha256=m-jPp6RHdjmmLvAF3elC-aoX4oVbdMOTAGhyAfEqQOg,4430 +tensorflow/python/training/server_lib.py,sha256=R5VFxc59HdOriP1FC4enmp3wpkqQXAdkX26Tb-UZesQ,21276 +tensorflow/python/training/session_manager.py,sha256=R3uq_497a8BaZrjTDHM83jdnyicju_ZpH37k1gLS-io,23640 +tensorflow/python/training/session_run_hook.py,sha256=9F13wd2UrRssNR-cPWCTP5veVbaGK2SrkO1S8WGQXoY,10450 +tensorflow/python/training/slot_creator.py,sha256=rFULxdyJm4_d4dBW9pqZXcVKeDCZCPS3VSt0oxLWMxg,10581 +tensorflow/python/training/summary_io.py,sha256=jxnr9CTz4d53kI9G6YmAyiohGiL3IEbigHy7qBIeFUs,3352 +tensorflow/python/training/supervisor.py,sha256=L-d_vTzkFsEp9-uAMb7SGocY54h1gexZ6pSyhjW_Ufg,43419 +tensorflow/python/training/sync_replicas_optimizer.py,sha256=lSgB_yvcwpQKR4D5UfI1qMcIFScEiqGzTPtE2QEustE,21187 +tensorflow/python/training/training.py,sha256=xEsGfHU_Dm2_Yl0ZDD_B-QidOrDWqb4iySUDpYkKFEw,25641 +tensorflow/python/training/training_ops.py,sha256=VUj7ynrmgcaEKkDZuaXWy7qWA_n2TcmNcHz_pLVFIlU,959 +tensorflow/python/training/training_util.py,sha256=HempmDDJrQMc8Zq3P2EWO_VDQ34gU3wdhBP9jwDNyr0,15153 +tensorflow/python/training/warm_starting_util.py,sha256=UG4DOqJ_A27_PkOM36NADvabHVJil9JFnvr5Ft_8AGs,24587 +tensorflow/python/types/__init__.py,sha256=Q7mH2VgCYyfUv9jRK2Tp5X0YD4BE-UMV6RYcIYHeqOI,892 +tensorflow/python/types/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/types/__pycache__/core.cpython-310.pyc,, +tensorflow/python/types/__pycache__/data.cpython-310.pyc,, +tensorflow/python/types/__pycache__/distribute.cpython-310.pyc,, +tensorflow/python/types/__pycache__/doc_typealias.cpython-310.pyc,, +tensorflow/python/types/__pycache__/internal.cpython-310.pyc,, +tensorflow/python/types/__pycache__/trace.cpython-310.pyc,, +tensorflow/python/types/core.py,sha256=b5VdYnwdrBT1qBUqQKWtSQiumZNO72fxERnGYwBz0Vo,14579 +tensorflow/python/types/data.py,sha256=eaSUMjlNmdMinKJQfphYjhmsCdBG8TQ_dFy9o4iHdMQ,1069 +tensorflow/python/types/distribute.py,sha256=0g8B5S-wToP_S1DGZ9T2e-iMNyS9RHas63uIvzr7KTM,21596 +tensorflow/python/types/doc_typealias.py,sha256=yrgAokWtEuZ5Kd9sQPj0r6Bold4ght7EGQHnzgQXcLE,1362 +tensorflow/python/types/internal.py,sha256=oCRFPn8qwmLR02gwT9japv71L2OTUaOpqG_zCMANnak,1808 +tensorflow/python/types/trace.py,sha256=sW-7lsafkQeVvDMYWoTv2wiHYobUVbHYhvXct_Bdjuk,10357 +tensorflow/python/user_ops/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/user_ops/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/user_ops/__pycache__/user_ops.cpython-310.pyc,, +tensorflow/python/user_ops/ops/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/user_ops/ops/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/user_ops/ops/__pycache__/gen_user_ops.cpython-310.pyc,, +tensorflow/python/user_ops/ops/gen_user_ops.py,sha256=vmFSq0sp-pUqN6zOFrC-0u_etkjAAGgqSLwFCUBCagA,2419 +tensorflow/python/user_ops/user_ops.py,sha256=kByPGDzZ_ld72KUJNkGPuf96FH8ea1FyS0_8rAbDZeY,1100 +tensorflow/python/util/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/util/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/util/__pycache__/all_util.cpython-310.pyc,, +tensorflow/python/util/__pycache__/compat.cpython-310.pyc,, +tensorflow/python/util/__pycache__/custom_nest_protocol.cpython-310.pyc,, +tensorflow/python/util/__pycache__/decorator_utils.cpython-310.pyc,, +tensorflow/python/util/__pycache__/deprecated_module.cpython-310.pyc,, +tensorflow/python/util/__pycache__/deprecated_module_new.cpython-310.pyc,, +tensorflow/python/util/__pycache__/deprecation.cpython-310.pyc,, +tensorflow/python/util/__pycache__/dispatch.cpython-310.pyc,, +tensorflow/python/util/__pycache__/example_parser_configuration.cpython-310.pyc,, +tensorflow/python/util/__pycache__/function_utils.cpython-310.pyc,, +tensorflow/python/util/__pycache__/is_in_graph_mode.cpython-310.pyc,, +tensorflow/python/util/__pycache__/keras_deps.cpython-310.pyc,, +tensorflow/python/util/__pycache__/keyword_args.cpython-310.pyc,, +tensorflow/python/util/__pycache__/lazy_loader.cpython-310.pyc,, +tensorflow/python/util/__pycache__/lock_util.cpython-310.pyc,, +tensorflow/python/util/__pycache__/module_wrapper.cpython-310.pyc,, +tensorflow/python/util/__pycache__/nest.cpython-310.pyc,, +tensorflow/python/util/__pycache__/nest_util.cpython-310.pyc,, +tensorflow/python/util/__pycache__/object_identity.cpython-310.pyc,, +tensorflow/python/util/__pycache__/serialization.cpython-310.pyc,, +tensorflow/python/util/__pycache__/tf_contextlib.cpython-310.pyc,, +tensorflow/python/util/__pycache__/tf_decorator.cpython-310.pyc,, +tensorflow/python/util/__pycache__/tf_decorator_export.cpython-310.pyc,, +tensorflow/python/util/__pycache__/tf_export.cpython-310.pyc,, +tensorflow/python/util/__pycache__/tf_inspect.cpython-310.pyc,, +tensorflow/python/util/__pycache__/tf_should_use.cpython-310.pyc,, +tensorflow/python/util/__pycache__/tf_stack.cpython-310.pyc,, +tensorflow/python/util/__pycache__/traceback_utils.cpython-310.pyc,, +tensorflow/python/util/__pycache__/type_annotations.cpython-310.pyc,, +tensorflow/python/util/__pycache__/variable_utils.cpython-310.pyc,, +tensorflow/python/util/_pywrap_checkpoint_reader.pyi,sha256=Bl714Zo6EQgu_wweoNz7sp98Y5lG7WA0QaQUdxhm570,1120 +tensorflow/python/util/_pywrap_checkpoint_reader.so,sha256=UBMhFb3yUgq2k6y82JsspIYISO9gZi5wQ3XziTGSyiM,333848 +tensorflow/python/util/_pywrap_determinism.pyi,sha256=uegEIyosIQKday40Ri3L5qJiSMpGAH4mNIrWWV8DFDA,756 +tensorflow/python/util/_pywrap_determinism.so,sha256=nNyXjJiSeOiUkAB2o-9PEhvkfmVvuU45TOBq9oS0mf8,140640 +tensorflow/python/util/_pywrap_kernel_registry.pyi,sha256=NB0PFw74Gx9RwdibN16bU_cHJk7_Okv8lvZEoE7QdH0,738 +tensorflow/python/util/_pywrap_kernel_registry.so,sha256=88zJx9UhN7XLCx-nsZlBnBuOtHPz1qBF_rchd93KI88,202552 +tensorflow/python/util/_pywrap_nest.so,sha256=ETgZEPjNMI-O1Zv0FgFAO_DRvYCsGYpjSrHK6ozpyAA,139336 +tensorflow/python/util/_pywrap_stat_summarizer.pyi,sha256=JC6yc8qwTjsMqjxEectvkN3vxW9hOpHbCnoDRBO49Rg,1044 +tensorflow/python/util/_pywrap_stat_summarizer.so,sha256=H2cSaCSbZC-aH7f25vhYt7UxFxobibSZE80NJzwrqiE,306280 +tensorflow/python/util/_pywrap_tensor_float_32_execution.pyi,sha256=uegEIyosIQKday40Ri3L5qJiSMpGAH4mNIrWWV8DFDA,756 +tensorflow/python/util/_pywrap_tensor_float_32_execution.so,sha256=Rpm65XyNPvVXEfIUbTsuh_bnR6AxxzkO4a3wc07Ei9w,140784 +tensorflow/python/util/_pywrap_tfprof.pyi,sha256=GU2ES7H_7oRu8dptDW8yCr3Ehk0Z7CMdsQWcweYCaLs,1109 +tensorflow/python/util/_pywrap_tfprof.so,sha256=pVMh1GjC9Iz0tLJGYuHknLD422sQGQTRKwTklEY8nlM,245888 +tensorflow/python/util/_pywrap_transform_graph.pyi,sha256=aLPAUABev-1GFJO3SfrAviJJwCaVAv8k-n7KmQBFg70,795 +tensorflow/python/util/_pywrap_transform_graph.so,sha256=xfyYLGyYHSnqg1l3cG_EfLJl0Ml0mWwyaHJZifT5k4I,262784 +tensorflow/python/util/_pywrap_util_port.pyi,sha256=ovwa9_7_HupRx-9cBEDtvVC27JCyXt533albaiOp7ew,913 +tensorflow/python/util/_pywrap_util_port.so,sha256=lAYDlkAhNHZjy8Wfht6MNQMgDturkPU4RX9uBxa7xgA,272040 +tensorflow/python/util/_pywrap_utils.so,sha256=eqbhXSOBefbqmPQ8DSexV-wE-dLo9KqbL5oUt49qfqc,250856 +tensorflow/python/util/_tf_stack.pyi,sha256=lne4O4PrYs6I-34y66Zy8tA01ElOhZ_x6Wd9VV9-aOg,2378 +tensorflow/python/util/_tf_stack.so,sha256=BLC0IQYfG_jQEzpUSJf2_Y7xp2h2xfzmYwPchYqW5nI,602848 +tensorflow/python/util/all_util.py,sha256=_cTC8BeOksYNjvuUAm9bYFGBWf8-dkqLAUm-MIQrYVE,4583 +tensorflow/python/util/compat.py,sha256=ODU2iN-7mhrfsRAO1RQlZrYQw9v2Vsc0hDXQtEnMpTk,6671 +tensorflow/python/util/custom_nest_protocol.py,sha256=d2maEnTdPeRPLp8y9J4oRJoUnNUqCuW8pXwijzG1_lY,4520 +tensorflow/python/util/decorator_utils.py,sha256=ETGEzLhbochA1797M2F_DAJg7NWwzkpeLdmCb5rHTzY,5915 +tensorflow/python/util/deprecated_module.py,sha256=9t_uyACbNhcahZ1P9-Fb45gYjntgWF_fnNbqck2j2HI,968 +tensorflow/python/util/deprecated_module_new.py,sha256=LEJhzm5JaFySH4CnGr797jOjQOogW2AQww1X_ddr0RM,808 +tensorflow/python/util/deprecation.py,sha256=9kVpzvhmRnpM-r6cXEg2IYRNcVtpfZmDtBl-yWRjaGE,29205 +tensorflow/python/util/dispatch.py,sha256=UeYpuqmrpQIrpFf8d0MTk26OgnkCU1yoPAIQKqDgT0U,50255 +tensorflow/python/util/example_parser_configuration.py,sha256=EOBzS6O3stdH58wE2TvuWAX2mfdfpGRVwaYsq_DoDAc,8157 +tensorflow/python/util/fast_module_type.pyi,sha256=JlfzbmX2s8t49MSOvWNadulXyf6pctXfaUPqb7asj0E,738 +tensorflow/python/util/fast_module_type.so,sha256=PbdpYWBaTf6YnOYyQ0oU9hW7-m591i8prK9w7Y_16oo,191376 +tensorflow/python/util/function_utils.py,sha256=flrn4LElOmOuOjBDJVCnbFMJBejjl6Sm_lnpFlSGEsc,4367 +tensorflow/python/util/is_in_graph_mode.py,sha256=SGsuo4HqYJTrrEb-RIAdHUzPFK2rD7tgQbsXCSwK4RY,909 +tensorflow/python/util/keras_deps.py,sha256=F_nZMdi27J2mjTe4mYgb2vcF-lxIGcLn5qp-oKuskPg,3209 +tensorflow/python/util/keyword_args.py,sha256=3Ci1qJX6c8tneZma35oNZIj4WACj_o5Pu2fdX5j-voA,1666 +tensorflow/python/util/lazy_loader.py,sha256=RLtPNBlPrAfMaF1WQQD2OqMCzfwSX3mVSLc0Nogj-JM,6613 +tensorflow/python/util/lock_util.py,sha256=B42_jNhE6NwjTfGQzt1VMDATsPFX05cuN71_NrZBwss,4253 +tensorflow/python/util/module_wrapper.py,sha256=OLIHP_eqJdpE-CDBuIHKrKJHwEEOEXvP8PxCLEztieE,10217 +tensorflow/python/util/nest.py,sha256=nCAMtgdXGkQzivsI7V2y_EfZyq53YURd3aNd_yYx_5Y,49183 +tensorflow/python/util/nest_util.py,sha256=MBuWcZiwKGZsLtsFsW7UmwYUbKlnj_UVK2kEufICEx0,63434 +tensorflow/python/util/object_identity.py,sha256=Zhy7ynFu9Sa03FO2U6l0ytCp630rhwxLRfBpcgUqlWY,6992 +tensorflow/python/util/protobuf/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/python/util/protobuf/__pycache__/__init__.cpython-310.pyc,, +tensorflow/python/util/protobuf/__pycache__/compare.cpython-310.pyc,, +tensorflow/python/util/protobuf/compare.py,sha256=d1_CJZ1DM2T43dLIKPKXCJ4SvEHFfl-Caemt9RuQWZk,12989 +tensorflow/python/util/pywrap_xla_ops.pyi,sha256=qL5dm6egG-xosyBF0xmPY2T8X9X2PeycojneKg_KeoE,780 +tensorflow/python/util/pywrap_xla_ops.so,sha256=ocRdZirJIshX9gRkEWgTbPL89izJRIolvvpAwPGG6QM,441272 +tensorflow/python/util/serialization.py,sha256=OFB_3zwzK6wG8ByxtEzuSt2vq-e7lkJ8_5-MO9nIye8,2378 +tensorflow/python/util/tf_contextlib.py,sha256=VUbg6J_SYJrMH4-hK8hNJp3PmLSQVf9q7TmX9usWoZM,1267 +tensorflow/python/util/tf_decorator.py,sha256=wZQxo6u4j4qynCCqKWZKP6a9pKXOXVZHUjiAKVjBvu0,12454 +tensorflow/python/util/tf_decorator_export.py,sha256=1to9YHTNtCGQqbIH-Fbrj5gVC2NiKYaGJbIptk8oaUY,1063 +tensorflow/python/util/tf_export.py,sha256=I6UttpjGYQXY5b-ixNwRaeJe-triO1mWsmAXbZtjabc,13121 +tensorflow/python/util/tf_inspect.py,sha256=ilC3x50NI3Y1NUjV57JDMDlNJ2HopX1t70T0VBpW_Xs,15958 +tensorflow/python/util/tf_should_use.py,sha256=aNNYoEi-vnDqsYB7DL2wpWQ0MFlblMaNB9psnoEudUo,9631 +tensorflow/python/util/tf_stack.py,sha256=Vm8hjKukiRv29Lp48osraCvzQ_SZtfWnv0amFctY5SE,6121 +tensorflow/python/util/traceback_utils.py,sha256=0FDrw6Eo3Fd2LHqGuaib6HkSLDHOaFQRqpldTKwRCv4,5733 +tensorflow/python/util/type_annotations.py,sha256=HiM5cHxBNQ9xfKJX-b_G8dPOKTN596UR3-M2QUQE0B8,2151 +tensorflow/python/util/variable_utils.py,sha256=MukxA4TKN1rCBIrzZIHJRenVxzbIPbiL_4vYaWldCUA,3422 +tensorflow/security/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/security/__pycache__/__init__.cpython-310.pyc,, +tensorflow/security/fuzzing/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/security/fuzzing/__pycache__/__init__.cpython-310.pyc,, +tensorflow/security/fuzzing/py/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/security/fuzzing/py/__pycache__/__init__.cpython-310.pyc,, +tensorflow/security/fuzzing/py/__pycache__/annotation_types.cpython-310.pyc,, +tensorflow/security/fuzzing/py/annotation_types.py,sha256=2swSTsnJRHL5TTqpe628BO1-cO63FGJUGu4JZkz7VII,2615 +tensorflow/tools/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/tools/__pycache__/__init__.cpython-310.pyc,, +tensorflow/tools/common/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/tools/common/__pycache__/__init__.cpython-310.pyc,, +tensorflow/tools/common/__pycache__/public_api.cpython-310.pyc,, +tensorflow/tools/common/__pycache__/test_module1.cpython-310.pyc,, +tensorflow/tools/common/__pycache__/test_module2.cpython-310.pyc,, +tensorflow/tools/common/__pycache__/traverse.cpython-310.pyc,, +tensorflow/tools/common/public_api.py,sha256=41QB2VdDG7pjREyPLwXD6ECQ65DZ-7sHF9eSmBpOPtc,5407 +tensorflow/tools/common/test_module1.py,sha256=i9e9cW2NamcgIqI3UezvaFcOwI2rRdGObeZiL-YvXSU,935 +tensorflow/tools/common/test_module2.py,sha256=CNpdd3d5YZnDm0XwWxkyLjwePupjwKADPDQJ_-9Duis,851 +tensorflow/tools/common/traverse.py,sha256=sprGCzsV6AVeRqwWiCZsQLyRRiBdfGk8n7jy9-pEF5Y,3900 +tensorflow/tools/compatibility/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/tools/compatibility/__pycache__/__init__.cpython-310.pyc,, +tensorflow/tools/compatibility/__pycache__/all_renames_v2.cpython-310.pyc,, +tensorflow/tools/compatibility/__pycache__/ast_edits.cpython-310.pyc,, +tensorflow/tools/compatibility/__pycache__/ipynb.cpython-310.pyc,, +tensorflow/tools/compatibility/__pycache__/module_deprecations_v2.cpython-310.pyc,, +tensorflow/tools/compatibility/__pycache__/renames_v2.cpython-310.pyc,, +tensorflow/tools/compatibility/__pycache__/reorders_v2.cpython-310.pyc,, +tensorflow/tools/compatibility/__pycache__/tf_upgrade_v2.cpython-310.pyc,, +tensorflow/tools/compatibility/__pycache__/tf_upgrade_v2_main.cpython-310.pyc,, +tensorflow/tools/compatibility/__pycache__/tf_upgrade_v2_safety.cpython-310.pyc,, +tensorflow/tools/compatibility/all_renames_v2.py,sha256=tf-5v6jz5kGfqgmGhyd-iR-Y4UjpKSo3VYyjsZS2mLg,25018 +tensorflow/tools/compatibility/ast_edits.py,sha256=Uj-eryrFAM1oVzmT1Qcg3_jDrr7uIojqaZ5O_ZpCcZE,39664 +tensorflow/tools/compatibility/ipynb.py,sha256=daz-CWlJ4xUaxfGvSUqTSlR2XC7Qc1nCZxTC6dlEza4,5298 +tensorflow/tools/compatibility/module_deprecations_v2.py,sha256=-HFY4JMnnVFKKzMd6S-ohg-5qpHr17wEKz1CdAfSRCY,2641 +tensorflow/tools/compatibility/renames_v2.py,sha256=h2Tc2mdJFaIOwB4Pn8gCYYh808_rUPsyOY6E9iiKoxg,61168 +tensorflow/tools/compatibility/reorders_v2.py,sha256=QWWuRjDvWKpJAD89FSzRSgXYYYFcs6gySCWkqaECxfU,12379 +tensorflow/tools/compatibility/tf_upgrade_v2.py,sha256=MCrEO1ibi2WtkNbfhjsuXVqpRMO5wCTrMSoQh0FDTOY,104497 +tensorflow/tools/compatibility/tf_upgrade_v2_main.py,sha256=bnTAvXcWoqAP4Nw2QN_z7-P993KSv8Dkv7hJgNeN-r4,7516 +tensorflow/tools/compatibility/tf_upgrade_v2_safety.py,sha256=g-AY79iufOl456DyZsJ1AJc5KDmyY5F5Ndi7rRkpMwY,2439 +tensorflow/tools/docs/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/tools/docs/__pycache__/__init__.cpython-310.pyc,, +tensorflow/tools/docs/__pycache__/doc_controls.cpython-310.pyc,, +tensorflow/tools/docs/__pycache__/tf_doctest_lib.cpython-310.pyc,, +tensorflow/tools/docs/doc_controls.py,sha256=8vS1PDgMxalRTQPINVgAz-1Fo9Q0RC0xm67PDxZt2tQ,7784 +tensorflow/tools/docs/tf_doctest_lib.py,sha256=iEfZfDWirYd6BKaXw0WT7uhjTFb5IYpUNPMvXIfXb0I,8256 +tensorflow/tools/pip_package/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/tools/pip_package/__pycache__/__init__.cpython-310.pyc,, +tensorflow/tools/pip_package/__pycache__/setup.cpython-310.pyc,, +tensorflow/tools/pip_package/setup.py,sha256=xrZvW1zVpR_a_urSVoNM-xi4nVZBZipvWTFkBMDSoCM,17150 +tensorflow/tsl/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/tsl/__pycache__/__init__.cpython-310.pyc,, +tensorflow/tsl/profiler/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/tsl/profiler/__pycache__/__init__.cpython-310.pyc,, +tensorflow/tsl/profiler/protobuf/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/tsl/profiler/protobuf/__pycache__/__init__.cpython-310.pyc,, +tensorflow/tsl/profiler/protobuf/__pycache__/profile_pb2.cpython-310.pyc,, +tensorflow/tsl/profiler/protobuf/__pycache__/profiler_options_pb2.cpython-310.pyc,, +tensorflow/tsl/profiler/protobuf/__pycache__/trace_events_pb2.cpython-310.pyc,, +tensorflow/tsl/profiler/protobuf/__pycache__/xplane_pb2.cpython-310.pyc,, +tensorflow/tsl/profiler/protobuf/profile_pb2.py,sha256=LoB-9vDAqqUQ4A2kIuE2Y3dlvOLRXQbltC20Dg_quBo,3619 +tensorflow/tsl/profiler/protobuf/profiler_options_pb2.py,sha256=SZ2Hd2yWnVKCj1gNnI3py5TiQB1Q4_eGr__LkHaO54g,2265 +tensorflow/tsl/profiler/protobuf/trace_events_pb2.py,sha256=qj4zqj_WqFCweJB0L6BnMFRdBehinp5ixxTWiYWzrXM,3208 +tensorflow/tsl/profiler/protobuf/xplane_pb2.py,sha256=xs8nH32n6gk-DQwLChbk18vuaxqQhlUy8T1T_ga7oII,4270 +tensorflow/tsl/protobuf/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow/tsl/protobuf/__pycache__/__init__.cpython-310.pyc,, +tensorflow/tsl/protobuf/__pycache__/bfc_memory_map_pb2.cpython-310.pyc,, +tensorflow/tsl/protobuf/__pycache__/coordination_config_pb2.cpython-310.pyc,, +tensorflow/tsl/protobuf/__pycache__/distributed_runtime_payloads_pb2.cpython-310.pyc,, +tensorflow/tsl/protobuf/__pycache__/error_codes_pb2.cpython-310.pyc,, +tensorflow/tsl/protobuf/__pycache__/histogram_pb2.cpython-310.pyc,, +tensorflow/tsl/protobuf/__pycache__/rpc_options_pb2.cpython-310.pyc,, +tensorflow/tsl/protobuf/__pycache__/status_pb2.cpython-310.pyc,, +tensorflow/tsl/protobuf/__pycache__/test_log_pb2.cpython-310.pyc,, +tensorflow/tsl/protobuf/bfc_memory_map_pb2.py,sha256=X3Get5MH4Z17dHbMwNQkRrk7NhhtDtIJzFjp19hU45k,2798 +tensorflow/tsl/protobuf/coordination_config_pb2.py,sha256=G4FFeRrZkqoLQypFmVqeXQdXj79mn31TKhKW0SK12uw,2071 +tensorflow/tsl/protobuf/distributed_runtime_payloads_pb2.py,sha256=q60dCkolF-BGs5fTTmeyOHZjVQRGd_atuPleMz3bkXM,1962 +tensorflow/tsl/protobuf/error_codes_pb2.py,sha256=DihIkJ3aqQWg5VNy4Gk1JhWK_lpriBGIgHgnLe0c8gc,1951 +tensorflow/tsl/protobuf/histogram_pb2.py,sha256=OceXxyNCLNw-Alo8aiMRV6wHf5uvEscMI7jK6Rf6d3Q,1831 +tensorflow/tsl/protobuf/rpc_options_pb2.py,sha256=S5e_4-qatDuCYut3cS1_M9OjM4gNxVr5ANQI9GBkAlM,1482 +tensorflow/tsl/protobuf/status_pb2.py,sha256=_zR3dWPGCmljD_WRiSF6c3IURv1n7HnJaavimZOHDOo,1456 +tensorflow/tsl/protobuf/test_log_pb2.py,sha256=orU0vzP0mvSZ-G_8UO6wBN-53Gam6WlD_J7OQMv3ytE,7266 +tensorflow/xla_aot_runtime_src/CMakeLists.txt,sha256=l7ScyFNrRO4KUO1ycu2nVXUF200t97neMcuWMgHFQSs,467 +tensorflow/xla_aot_runtime_src/tensorflow/compiler/tf2xla/xla_compiled_cpu_function.cc,sha256=r2gkOFQb9UgwWgFheymky02Dp7ZeoO3oISH5zHKyTMY,8393 +tensorflow/xla_aot_runtime_src/tensorflow/core/platform/cord.h,sha256=fHFY35-uVRGcSpedsNhtZk10qiMr4UgpBJDegdvEuls,853 +tensorflow/xla_aot_runtime_src/tensorflow/core/platform/ctstring.h,sha256=AtBfmdbkQl8Dibzk4IfjPbBScL628VytKEjsQmY-fPk,845 +tensorflow/xla_aot_runtime_src/tensorflow/core/platform/ctstring_internal.h,sha256=rpkVGGea6l14kTgZnUKgj-Q7Q3XOPuox1y3bN6CrDD0,881 +tensorflow/xla_aot_runtime_src/tensorflow/core/platform/dynamic_annotations.h,sha256=foqbKqxHgTjglZDbTee5ZfoLiRtmau-kkwMfWdTwbm0,960 +tensorflow/xla_aot_runtime_src/tensorflow/core/platform/env_time.h,sha256=EbCRJE3MqXAA6UsxI20_LPVQOBmHddBpiDN7Y0N4M7M,991 +tensorflow/xla_aot_runtime_src/tensorflow/core/platform/macros.h,sha256=DxC1wioRFYpjFAPmRJSSDiUfXFh2ozoSusyeqM8QTpQ,1100 +tensorflow/xla_aot_runtime_src/tensorflow/core/platform/platform.h,sha256=PuWGSlaQ14VZ0iXFYJz7Rqlc7jvbI6AxIvZretmd46s,845 +tensorflow/xla_aot_runtime_src/tensorflow/core/platform/tstring.h,sha256=H0shcLd7Gh49ogxbJiyMGWzoy8R_VfVTfUiP6x4N08w,1038 +tensorflow/xla_aot_runtime_src/tensorflow/core/platform/types.h,sha256=1mdxE3KbLZy5WSFQ0tZs22hacGGXaZwE-zfeXUWOI-E,2076 +tensorflow/xla_aot_runtime_src/tsl/framework/contraction/eigen_contraction_kernel.cc,sha256=cAOANGFjPGybk6NL2zNhZggrz4DyYa3O_u_xzqYQ9x0,2386 +tensorflow/xla_aot_runtime_src/tsl/platform/ctstring.h,sha256=gtcB92SahlLfqo5tDUGUov-LBzBQ33Uo1mwehWsPrMk,6165 +tensorflow/xla_aot_runtime_src/tsl/platform/ctstring_internal.h,sha256=o5MhZTcc0SixAfsrgnT9sPNrjnRhwW0Y-wqNiR47BOA,13731 +tensorflow/xla_aot_runtime_src/tsl/platform/default/dynamic_annotations.h,sha256=kxeNd9Z9DMs1MeHt8D4Uvqc2UsYUUPW437N8QuXM2ok,1336 +tensorflow/xla_aot_runtime_src/tsl/platform/default/env_time.cc,sha256=hKCGDTETeSRCBcYJnffdS3W6rBJp-dVJ_7MqNMrpGp0,994 +tensorflow/xla_aot_runtime_src/tsl/platform/default/integral_types.h,sha256=L8vUmNYzEsA87wujdhqQs-xdAq4B7h1F9liChWcxTHI,1247 +tensorflow/xla_aot_runtime_src/tsl/platform/dynamic_annotations.h,sha256=EaTF_LW0HC7bK9fR1ZIuO90UAlDrEqRZ6r6wNIEjpJw,1408 +tensorflow/xla_aot_runtime_src/tsl/platform/env_time.h,sha256=kItm1M8CC1Addtbt5zpinomMcIzplTOo-XsYr_zbyyk,2445 +tensorflow/xla_aot_runtime_src/tsl/platform/macros.h,sha256=nlssM168-aJOfK-PDCgNzd_SUPkdLCyCdpz3XAGmXYY,5918 +tensorflow/xla_aot_runtime_src/tsl/platform/platform.h,sha256=OcZ90jQbXDzzgCs3aIGfKzSpfqUV0S0nJhddQBaTE6Y,2490 +tensorflow/xla_aot_runtime_src/xla/cpu_function_runtime.cc,sha256=eyPvujPaCKsUlIu-FJtHM1kMgCzVOVY0TAtPXtrQYzs,3659 +tensorflow/xla_aot_runtime_src/xla/executable_run_options.cc,sha256=P8GAg3U-f7wjkXgV9SHcAJrG7NTGaAjl5Sji9vKx1tk,3925 +tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_conv2d.cc,sha256=ugyHJR_0NspyXXN6cKbiZCbDWGOuoIif6Ds1eNN0LUU,3527 +tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_conv3d.cc,sha256=J5HTkGKaLAoKC3xBK6sNBsS82TEKYllYkfZA9PFvIVw,4035 +tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_custom_call_status.cc,sha256=5HyuI4TCAqS3BGxYHmqoa094BW0ZUPc39ZdfsuNIAvg,1061 +tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_fft.cc,sha256=oF32DomceHgnLm9Yg8vVFJQWfxJ1BrXdmDpdQuhhy_0,1679 +tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_fork_join.cc,sha256=HbQMrJ-kOsBiaFzEkfwH7y01bUV8chnfaJ6wdQwvQj4,5258 +tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_fp16.cc,sha256=aRDmHdV3TjXuIbQmU3QbE6ChlUMgHhphoRcC49igFQI,5302 +tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_key_value_sort.cc,sha256=CTIB8vIJwxr3dRAAFZjkpGnHIU2uBwgI32YtmbnWjgA,5406 +tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_matmul_c128.cc,sha256=VcLmeinFoEViosJLfUPbVPFt3FaQ9NqTeMcK2f_miik,1279 +tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_matmul_c64.cc,sha256=zS5OIfY-HNI419jv3pfJ_8DAstiNDt1fQRl-UtoN2A4,1273 +tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_matmul_common.h,sha256=ZjrY0SoBR8xrUk1oXhq5XU6L08KV5EjVs3vO4zHFeyw,5811 +tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_matmul_f16.cc,sha256=nE6P8_lakBotV5bHvVQEp27vGuD4YRVBuzUVPa5obeQ,1260 +tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_matmul_f32.cc,sha256=Sd-dWjpmN7NejyN6ual8Pa9IAgNDB7OncpBNAgDrpf4,1591 +tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_matmul_f64.cc,sha256=FDo0BrypQBZZcMy6T9sCEOZspEXW24r6_ZRePWXjp5U,1189 +tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_matmul_s32.cc,sha256=NcPStelWD9nd0qo0ReEMsjEc3BPQIYWaX8SFu38mjeA,1194 +tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_pow.cc,sha256=Pqfc4ttH2iNHJYf7JTFMhEP_jQW5U02_9Of3Teqt4eY,1123 +tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_single_threaded_conv2d.cc,sha256=TGTHwBY3wZf9D9fj2op-pMtxgUt_Wp0Fi9dYB9e0UOU,3045 +tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_single_threaded_conv3d.cc,sha256=8WNx5QbpoZFq7jve21pk6X6gqpXP1fBNAQKppZgU8XU,3553 +tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_single_threaded_fft.cc,sha256=jO-n19O3o65PnlqTpW_tz7qKQGLqcn6O0-GMRbi8ceI,1381 +tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_single_threaded_matmul_c128.cc,sha256=SqEHn2mQKsdTDHgwhzpwk3G1ECoGnL4SMcr3j8WRIlA,1302 +tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_single_threaded_matmul_c64.cc,sha256=o8K6_v9zLozRLT1Kmcl5Lp7swwaUyf-3sxspynPpMMg,1297 +tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_single_threaded_matmul_common.h,sha256=affpjnxtyoqmn_pXYIkrj1yFYN48iYM_rHb8BZuyCw0,3357 +tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_single_threaded_matmul_f16.cc,sha256=fTHAih0YbgdBMcX4Ccu0xsiMJjtlIcKl5F9yQMU6wJU,1292 +tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_single_threaded_matmul_f32.cc,sha256=uaQf-lensY4JSsZz3aaQ1bA14Z9qSwfXlzYggMJR34o,1433 +tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_single_threaded_matmul_f64.cc,sha256=8s01-vrXnsJgE5QZic35YhlmoxSqU86YPHFXAq1yHAY,1485 +tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_single_threaded_matmul_s32.cc,sha256=KL-1fXuZ_F5jWTnKVtNmsE0GQEUkzMDjWE2If_hiqTc,1452 +tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_topk.cc,sha256=CtYUQ5RkXcZsbfbEGmtRQfi_5-ouqy8m0-ylXvYhn_Y,2912 +tensorflow/xla_aot_runtime_src/xla/service/custom_call_status.cc,sha256=EAO7Mq1LnIL1yAaKI6KliNsv4ZPlSQBna2KXJYPFdeo,1235 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow-2.15.1.dist-info/REQUESTED b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow-2.15.1.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow-2.15.1.dist-info/WHEEL b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow-2.15.1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..a9630e4b88ce3a4c3db89721cfd0f31ffba2bd72 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow-2.15.1.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.38.4) +Root-Is-Purelib: false +Tag: cp310-cp310-manylinux_2_17_x86_64 +Tag: cp310-cp310-manylinux2014_x86_64 + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow-2.15.1.dist-info/entry_points.txt b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow-2.15.1.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..aa95b6a2e1aab5a82fadb194e4b18aa12b2dcfbf --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow-2.15.1.dist-info/entry_points.txt @@ -0,0 +1,9 @@ +[console_scripts] +estimator_ckpt_converter = tensorflow_estimator.python.estimator.tools.checkpoint_converter:main +import_pb_to_tensorboard = tensorflow.python.tools.import_pb_to_tensorboard:main +saved_model_cli = tensorflow.python.tools.saved_model_cli:main +tensorboard = tensorboard.main:run_main +tf_upgrade_v2 = tensorflow.tools.compatibility.tf_upgrade_v2_main:main +tflite_convert = tensorflow.lite.python.tflite_convert:main +toco = tensorflow.lite.python.tflite_convert:main +toco_from_protos = tensorflow.lite.toco.python.toco_from_protos:main diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow-2.15.1.dist-info/top_level.txt b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow-2.15.1.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..da9273a2142eeb866d80f7f866b8a4797e030e1a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow-2.15.1.dist-info/top_level.txt @@ -0,0 +1,2 @@ +tensorflow +third_party diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/client/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/client/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/client/client.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/client/client.py new file mode 100644 index 0000000000000000000000000000000000000000..d86ba094536672f5bbba3fb321c8b8af640bc153 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/client/client.py @@ -0,0 +1,438 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Cloud TPU Client.""" + +from concurrent import futures +import datetime +import json +import logging +import os +import time +import urllib + +from absl import flags + +_GOOGLE_API_CLIENT_INSTALLED = True +try: + from googleapiclient import discovery # pylint: disable=g-import-not-at-top + from oauth2client import client # pylint: disable=g-import-not-at-top +except ImportError: + _GOOGLE_API_CLIENT_INSTALLED = False + +FLAGS = flags.FLAGS + +flags.DEFINE_bool('runtime_oom_exit', True, + 'Exit the script when the TPU runtime is OOM.') +flags.DEFINE_bool('hbm_oom_exit', True, + 'Exit the script when the TPU HBM is OOM.') + +_GKE_ENV_VARIABLE = 'KUBE_GOOGLE_CLOUD_TPU_ENDPOINTS' +_DEFAULT_TPUCONFIG_VARIABLE = 'TPU_CONFIG' +_ENDPOINTS_SEPARATOR = ',' +_DEFAULT_ENV_VARIABLE = 'TPU_NAME' +_DISCOVERY_SERVICE_URL_ENV_VARIABLE = 'TPU_API_DISCOVERY_URL' +_GCE_METADATA_URL_ENV_VARIABLE = 'GCE_METADATA_IP' +_GCE_METADATA_ENDPOINT_ENV_VARIABLE = 'GCE_METADATA_HOST' +_DEFAULT_ENDPOINT_PORT = '8470' +_OOM_EVENT_COOL_TIME_SEC = 90 +_VERSION_SWITCHER_ENDPOINT = 'http://{}:8475/requestversion' + + +def _utcnow(): + """A wrapper function around datetime.datetime.utcnow. + + This function is created for unit testing purpose. It's not easy to do + StubOutWithMock with datetime.datetime package. + + Returns: + datetime.datetime + """ + return datetime.datetime.utcnow() + + +def _environment_discovery_url(): + return os.environ.get(_DISCOVERY_SERVICE_URL_ENV_VARIABLE) + + +def _gce_metadata_endpoint(): + endpoint = os.environ.get(_GCE_METADATA_ENDPOINT_ENV_VARIABLE) + if not endpoint: + endpoint = os.environ.get( + _GCE_METADATA_URL_ENV_VARIABLE, 'metadata.google.internal' + ) + return 'http://' + endpoint + + +def _request_compute_metadata(path): + req = urllib.request.Request( + '%s/computeMetadata/v1/%s' % (_gce_metadata_endpoint(), path), + headers={'Metadata-Flavor': 'Google'}) + resp = urllib.request.urlopen(req) + return _as_text(resp.read()) + + +def _environment_var_to_network_endpoints(endpoints): + """Yields a dict with ip address and port.""" + for endpoint in endpoints.split(','): + grpc_prefix = 'grpc://' + if endpoint.startswith(grpc_prefix): + endpoint = endpoint.split(grpc_prefix)[1] + parts = endpoint.split(':') + ip_address = parts[0] + port = _DEFAULT_ENDPOINT_PORT + if len(parts) > 1: + port = parts[1] + yield { + 'ipAddress': ip_address, + 'port': port + } + + +def _get_tpu_node_config(): + tpu_config_env = os.environ.get(_DEFAULT_TPUCONFIG_VARIABLE) + if tpu_config_env: + return json.loads(tpu_config_env) + return None + + +def _get_tpu_name(tpu): + if tpu: + return tpu + + for e in [_GKE_ENV_VARIABLE, _DEFAULT_ENV_VARIABLE]: + if e in os.environ: + return os.environ[e] + return None + + +def _as_text(s): + if isinstance(s, bytes): + return s.decode('utf-8') + return s + + +class Client: + """Client for working with the Cloud TPU API. + + This client is intended to be used for resolving tpu name to ip addresses. + + It's recommended to use this library as a contextlib to utilize all + functionality. + """ + + def __init__(self, + tpu=None, + zone=None, + project=None, + credentials='default', + service=None, + discovery_url=None): + if isinstance(tpu, list): + if not tpu: + raise ValueError('At least one TPU must be specified.') + if len(tpu) != 1: + raise NotImplementedError( + 'Using multiple TPUs in a single session is not yet implemented') + tpu = tpu[0] + + tpu = _get_tpu_name(tpu) + + if tpu is None: + tpu_node_config = _get_tpu_node_config() + if tpu_node_config: + tpu = tpu_node_config.get('tpu_node_name') + project = project or tpu_node_config.get('project') + zone = zone or tpu_node_config.get('zone') + else: + raise ValueError('Please provide a TPU Name to connect to.') + + self._tpu = _as_text(tpu) + + self._use_api = not self._tpu.startswith('grpc://') + self._service = service + + self._credentials = None + self._project = None + self._zone = None + self._discovery_url = None + if self._use_api: + if credentials != 'default': + self._credentials = credentials + # Automatically detect project and zone if unspecified. + if project: + self._project = _as_text(project) + else: + self._project = _request_compute_metadata('project/project-id') + if zone: + self._zone = _as_text(zone) + else: + zone_path = _request_compute_metadata('instance/zone') + self._zone = zone_path.split('/')[-1] + self._discovery_url = _environment_discovery_url() or discovery_url + + def _symptom_msg(self, msg): + """Return the structured Symptom message.""" + return 'Symptom: ' + msg + + def _oom_event(self, symptoms): + """Check if a runtime OOM event is reported.""" + if not symptoms: + return False + for symptom in reversed(symptoms): + if symptom['symptomType'] != 'OUT_OF_MEMORY': + continue + oom_datetime_str = symptom['createTime'].split('.')[0] + oom_datetime = datetime.datetime.strptime(oom_datetime_str, + '%Y-%m-%dT%H:%M:%S') + time_diff = _utcnow() - oom_datetime + if time_diff < datetime.timedelta(seconds=_OOM_EVENT_COOL_TIME_SEC): + logging.warning( + self._symptom_msg( + 'a recent runtime OOM has occurred ~{} seconds ago. The model ' + 'script will terminate automatically. To prevent future OOM ' + 'events, please consider reducing the model size. To disable this ' + 'behavior, set flag --runtime_oom_exit=false when starting the ' + 'script.'.format(time_diff.seconds))) + return True + return False + + def _hbm_oom_event(self, symptoms): + """Check if a HBM OOM event is reported.""" + if not symptoms: + return False + for symptom in reversed(symptoms): + if symptom['symptomType'] != 'HBM_OUT_OF_MEMORY': + continue + oom_datetime_str = symptom['createTime'].split('.')[0] + oom_datetime = datetime.datetime.strptime(oom_datetime_str, + '%Y-%m-%dT%H:%M:%S') + time_diff = _utcnow() - oom_datetime + if time_diff < datetime.timedelta(seconds=_OOM_EVENT_COOL_TIME_SEC): + logging.warning( + self._symptom_msg( + 'a recent HBM OOM has occurred ~{} seconds ago. The model ' + 'script will terminate automatically. To prevent future HBM OOM ' + 'events, please consider reducing the model size. To disable this ' + 'behavior, set flag --hbm_oom_exit=false when starting the ' + 'script.'.format(time_diff.seconds))) + return True + return False + + def _tpu_service(self): + """Creates a new Cloud TPU API object. + + This works around an issue where the underlying HTTP connection sometimes + times out when the script has been running for too long. Other methods in + this object call this method to get a new API object whenever they need + to communicate with the Cloud API. + + Raises: + RuntimeError: If the dependent Python packages are missing. + + Returns: + A Google Cloud TPU API object. + """ + if self._service: + return self._service + + if not _GOOGLE_API_CLIENT_INSTALLED: + raise RuntimeError('Missing runtime dependency on the Google API client. ' + 'Run `pip install cloud-tpu-client` to fix.') + + credentials = self._credentials + if credentials is None or credentials == 'default': + credentials = client.GoogleCredentials.get_application_default() + + if self._discovery_url: + return discovery.build( + 'tpu', + 'v1', + credentials=credentials, + discoveryServiceUrl=self._discovery_url, + cache_discovery=False) + else: + return discovery.build( + 'tpu', 'v1', credentials=credentials, cache_discovery=False) + + def _full_name(self): + """Returns the full Cloud name for this TPU.""" + return 'projects/%s/locations/%s/nodes/%s' % ( + self._project, self._zone, self._tpu) + + def _fetch_cloud_tpu_metadata(self): + """Returns the TPU metadata object from the TPU Get API call.""" + service = self._tpu_service() + try: + r = service.projects().locations().nodes().get(name=self._full_name()) + return r.execute() + except Exception as e: + raise ValueError("Could not lookup TPU metadata from name '%s'. Please " + 'doublecheck the tpu argument in the TPUClusterResolver ' + 'constructor. Exception: %s' % (self._tpu, e)) + + def _get_tpu_property(self, key): + if self._use_api: + metadata = self._fetch_cloud_tpu_metadata() + return metadata.get(key) + + return None + + def __enter__(self): + self._open = True + + def __exit__(self, type, value, traceback): # pylint: disable=redefined-builtin + del type, value, traceback + + def recoverable(self): + """Returns true if the TPU is in a state where training should eventually resume. + + If false the TPU is in a unrecoverable state and should be recreated. + """ + state = self.state() + symptoms = self.symptoms() + if state and state in ['TERMINATED', 'PREEMPTED']: + return False + elif FLAGS.runtime_oom_exit and self._oom_event(symptoms): + return False + elif FLAGS.hbm_oom_exit and self._hbm_oom_event(symptoms): + return False + return True + + def symptoms(self): + """Return Cloud TPU Symptoms of the TPU.""" + return self._get_tpu_property('symptoms') + + def state(self): + """Return state of the TPU.""" + return self._get_tpu_property('state') + + def health(self): + """Return health of the TPU.""" + return self._get_tpu_property('health') + + def runtime_version(self): + """Return runtime version of the TPU.""" + + if not self._use_api: + # Fallback on getting version directly from TPU. + url = _VERSION_SWITCHER_ENDPOINT.format( + self.network_endpoints()[0]['ipAddress']) + try: + req = urllib.request.Request(url) + resp = urllib.request.urlopen(req) + version_details = json.loads(resp.read()) + return version_details.get('currentVersion') + except urllib.error.HTTPError as e: + status_code = e.code + if status_code == 404: + return None + else: + raise e + return self._get_tpu_property('tensorflowVersion') + + def accelerator_type(self): + """Return accelerator type of the TPU.""" + return self._get_tpu_property('acceleratorType') + + def api_available(self): + """Return if the Cloud TPU API is available, if not certain features will not work.""" + return self._use_api + + def name(self): + """Return the name of the tpu, or the ip address if name is not provided.""" + return self._tpu + + def get_local_ip(self): + """Return the local ip address of the Google Cloud VM the workload is running on.""" + return _request_compute_metadata('instance/network-interfaces/0/ip') + + def network_endpoints(self): + """Return a list of tpu endpoints.""" + if not self._use_api: + return list(_environment_var_to_network_endpoints(self._tpu)) + response = self._fetch_cloud_tpu_metadata() + + if response.get('state') != 'READY': + raise RuntimeError('TPU "%s" is not yet ready; state: "%s"' % + (self._tpu, response.get('state'))) + if 'networkEndpoints' in response: + return response['networkEndpoints'] + else: + return [{'ipAddress': response['ipAddress'], 'port': response['port']}] + + def wait_for_healthy(self, timeout_s=1200, interval=30): + """Wait for TPU to become healthy or raise error if timeout reached. + + Args: + timeout_s (int): The timeout in seconds for waiting TPU to become healthy. + interval (int): The interval in seconds to poll the TPU for health. + + Raises: + RuntimeError: If the TPU doesn't become healthy by the timeout. + """ + timeout = time.time() + timeout_s + while self.health() != 'HEALTHY': + logging.warning( + ('Waiting for TPU "%s" with state "%s" ' + 'and health "%s" to become healthy'), + self.name(), self.state(), self.health()) + if time.time() + interval > timeout: + raise RuntimeError( + 'Timed out waiting for TPU "%s" to become healthy' % self.name()) + time.sleep(interval) + + logging.warning('TPU "%s" is healthy.', self.name()) + + def configure_tpu_version(self, version, restart_type='always'): + """Configure TPU software version. + + Args: + version (string): Version of software to configure the TPU with. + restart_type (string): Restart behaviour when switching versions, + defaults to always restart. Options are 'always', 'ifNeeded'. + + """ + + def configure_worker(worker): + """Configure individual TPU worker. + + Args: + worker: A dict with the field ipAddress where the configure request will + be sent. + """ + ip_address = worker['ipAddress'] + url = (_VERSION_SWITCHER_ENDPOINT + '/{}?restartType={}').format( + ip_address, version, restart_type) + req = urllib.request.Request(url, data=b'') + try: + urllib.request.urlopen(req) + except urllib.error.HTTPError as e: + status_code = e.code + if status_code == 404: + raise Exception( + 'Tensorflow version {} is not available on Cloud TPU, ' + 'try a previous nightly version or refer to ' + 'https://cloud.google.com/tpu/docs/release-notes for ' + 'the latest official version.'.format(version)) + else: + raise Exception('Failed to configure worker {}'.format(ip_address)) + + workers = self.network_endpoints() + + with futures.ThreadPoolExecutor(max_workers=len(workers)) as executor: + results = executor.map(configure_worker, workers) + for result in results: + if result: + result.result() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/client/version.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/client/version.py new file mode 100644 index 0000000000000000000000000000000000000000..bf71101501d1ef41a127c8a876daa4680dac44e7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/client/version.py @@ -0,0 +1,17 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================= +"""Cloud TPU Client version information.""" + +__version__ = "0.11" diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/ops/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/ops/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/ops/tpu_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/ops/tpu_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..d54cb5a68afbb81fcc69de5dc579e323d672aa2c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/ops/tpu_ops.py @@ -0,0 +1,608 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================= +"""Operations for TPUs.""" + +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +# pylint: disable=wildcard-import,unused-import +from tensorflow.python.ops import gen_tpu_ops +from tensorflow.python.ops.gen_tpu_ops import * +# pylint: enable=wildcard-import,unused-import +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.tpu import tpu_function +from tensorflow.python.util.tf_export import tf_export + + +ops.NotDifferentiable("TPUReplicatedInput") + + +def _create_default_group_assignment(): + num_shards = tpu_function.get_tpu_context().number_of_shards + if num_shards is None: + logging.warning( + "cross_replica_sum should be used within a tpu_shard_context, but " + "got unset number_of_shards. Assuming 1.") + num_shards = 1 + group_assignment = [list(range(num_shards))] + return group_assignment + + +def all_to_all(x, + concat_dimension, + split_dimension, + split_count, + group_assignment=None, + name=None): + """Exchange data across TPU replicas. + + Args: + x: The local tensor. + concat_dimension: The dimension number to concatenate. + split_dimension: The dimension number to split. + split_count: The number of splits, this number must equal to the sub-group + size(group_assignment.get_shape()[1]) + group_assignment: Optional 2d int32 lists with shape [num_groups, + num_replicas_per_group]. `group_assignment[i]` represents the replica ids + in the ith subgroup. + name: Optional op name. + + Returns: + A `Tensor` which is concatenated by data from different replicas. + """ + if group_assignment is None: + group_assignment = _create_default_group_assignment() + return gen_tpu_ops.all_to_all( + x, + group_assignment, + concat_dimension=concat_dimension, + split_dimension=split_dimension, + split_count=split_count, + name=name) + + +@ops.RegisterGradient("AllToAll") +def _all_to_all_grad(op, grad): + # The gradient of a all-to-all is also a all-to-all but the + # split_dimension and concat_dimension is swapped. + # The gradient with respect to group_assignment is None. + return [ + gen_tpu_ops.all_to_all( + grad, + op.inputs[1], + concat_dimension=op.get_attr("split_dimension"), + split_dimension=op.get_attr("concat_dimension"), + split_count=op.get_attr("split_count")), None + ] + + +@tf_export(v1=["tpu.cross_replica_sum"]) +def cross_replica_sum(x, group_assignment=None, name=None): + """Sum the input tensor across replicas according to group_assignment. + + Args: + x: The local tensor to the sum. + group_assignment: Optional 2d int32 lists with shape [num_groups, + num_replicas_per_group]. `group_assignment[i]` represents the replica ids + in the ith subgroup. + name: Optional op name. + + Returns: + A `Tensor` which is summed across replicas. + """ + if group_assignment is None: + group_assignment = _create_default_group_assignment() + + return gen_tpu_ops.cross_replica_sum(x, group_assignment, name=name) + + +def collective_permute(x, source_target_pairs, name=None): + """Permute the input tensor across replicas given source_target_pairs. + + For each source_target_pair , we send replica a's input to replica b. + Each replica id must only appear once in the source column. Also it must + only appear once in the target column. + For the replica id not in the target column, this op returns a zero tensor + with the same shape and dtype of the input x. + + For example, suppose there are 4 TPU instances: `[A, B, C, D]`. Passing + source_target_pairs=`[[0,1],[1,2],[2,3]]` gets the outputs: + `[0, A, B, C]`. + + Args: + x: The local tensor to be permuted. + source_target_pairs: 2d int lists with shape [num_pairs, 2]. + source_target_pairs[i][0] represents the source replica id and + source_target_pairs[i][1] represents the target replica id. + name: Optional op name. + + Returns: + A `Tensor` which is permuted. + """ + return gen_tpu_ops.collective_permute(x, source_target_pairs, name=name) + + +@ops.RegisterGradient("CollectivePermute") +def _collective_permute_grad(op, grad): + # The gradient of a collective permute operation is also a collective + # permute, but with source/target pairs reversed. The gradient with respect + # to input argument `source_target_pairs` is `None`. + source_target_pairs = op.inputs[1][:, ::-1] + return [gen_tpu_ops.collective_permute(grad, source_target_pairs), None] + + +@ops.RegisterGradient("CrossReplicaSum") +def _cross_replica_sum_grad(op, grad): + # The gradient of a cross replica sum is also a cross-replica sum. + # The gradient with respect to group_assignment is None. + return [gen_tpu_ops.cross_replica_sum(grad, op.inputs[1]), None] + + +# This extra type checking exists to give a more helpful error message. +_SUPPORTED_INFEED_DTYPES = frozenset([ + dtypes.bool, dtypes.int32, dtypes.int64, dtypes.bfloat16, dtypes.float32, + dtypes.complex64, dtypes.uint32, dtypes.uint8, dtypes.int8 +]) + + +@ops.RegisterGradient("TPUEmbeddingActivations") +def _embedding_activations_grad(activations_op, grad_wrt_activations): + """Saves the gradient of embedding activations ops in a graph collection.""" + g = ops.get_default_graph() + table_id = activations_op.get_attr("table_id") + lookup_id = activations_op.get_attr("lookup_id") + table_gradients = g.get_collection_ref("tpu_embedding_gradients_table_%d" % + table_id) + + if not table_gradients: + raise RuntimeError( + "Gradients for TPUEmbedding have been generated in non-training mode." + "This is not expected. Consider putting your Optimizer.minimize code " + "behind the training mode condition check. For Estimator, you can " + "do \n\n" + " if mode == tf.estimator.ModeKeys.TRAIN:\n" + " train_op = opt.minimize(loss)\n" + "\n") + + if lookup_id < 0 or lookup_id >= len(table_gradients): + raise RuntimeError( + "Gradients (w.r.t. TPUEmbedding activations) generated for table_id {} " + "and lookup_id {}. The lookup_id attribute is outside the expected " + "range [0, {}).".format(table_id, lookup_id, len(table_gradients))) + + if table_gradients[lookup_id] is not None: + raise RuntimeError( + "Duplicate gradients (w.r.t. TPUEmbedding activations) generated for " + "table_id {} and lookup_id {}. This happens when there are multiple " + "calls to tf.gradients in a graph containing TPU embeddings. " + "TF cannot identify which gradient to use for updating the embedding " + "variables. Consider placing tf.StopGradient around tensors where " + "variable update is not required. Previous gradients were generated by " + "the following callstack: {}.".format( + table_id, lookup_id, table_gradients[lookup_id].op.traceback)) + + table_gradients[lookup_id] = array_ops.identity(grad_wrt_activations) + return [ + # RegisterGradient requires that value be returned for all inputs. Since + # the first argument (tpu_gradient_variable_{table_name}) has shape [1], + # we will return zeros(shape=[1]). The actual gradient w.r.t. the + # embedding activations (grad_wrt_activations) has the same shape as the + # activations returned by embedding_activations. + array_ops.zeros(arg.shape, dtype=dtypes.float32) + for arg in activations_op.inputs + ] + + +def infeed_dequeue(dtype, shape, name=None): + """A placeholder op for a value that will be fed into the computation. + + Args: + dtype: A `tf.DType`. The type of elements in the tensor. + shape: A `tf.TensorShape` or list of `ints`. The shape of the tensor. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `dtype`. + A tensor that will be provided using the infeed mechanism. + + Raises: + TypeError: If 'dtype` is not a supported infeed type. + """ + if dtype not in _SUPPORTED_INFEED_DTYPES: + raise TypeError( + "Operation '{}' has type {} which is not a supported TPU infeed type. " + "Supported types are: {}".format(name, dtype, + list(_SUPPORTED_INFEED_DTYPES))) + + return gen_tpu_ops.infeed_dequeue(dtype, shape, name=name) + + +# pylint: disable=redefined-outer-name +def infeed_dequeue_tuple(dtypes, shapes, name=None): + """A placeholder op for values fed into the TPU simultaneously as a tuple. + + Args: + dtypes: A list of `tf.DType`s that has length `>= 1`. The element types of + each element in `outputs`. + shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`). The + shapes of each tensor in `outputs`. + name: A name for the operation (optional). + + Returns: + A list of `Tensor` objects of type `dtypes`. + A list of tensors that will be provided using the infeed mechanism. + + Raises: + TypeError: If a type in 'dtypes` is not a supported infeed type. + """ + for dtype in dtypes: + if dtype not in _SUPPORTED_INFEED_DTYPES: + raise TypeError( + "{} is not a supported TPU infeed type. Supported types are: " + "{}".format(dtype, list(_SUPPORTED_INFEED_DTYPES))) + return gen_tpu_ops.infeed_dequeue_tuple(dtypes, shapes, name=name) + + +# pylint: enable=redefined-outer-name + + +# pylint: disable=protected-access +def send_tpu_embedding_gradients(inputs, + config, + learning_rates=None, + name=None): + """A placeholder op for feeding per-sample gradients to the embedding layer. + + Args: + inputs: A TensorList of gradients with which to update embedding tables. + This argument has the same length and shapes as the return value of + RecvTPUEmbeddingActivations, but contains gradients of the model's loss + with respect to the embedding activations. The embedding tables are + updated from these gradients via the optimizers specified in the TPU + embedding configuration given to tpu.initialize_system. + config: Serialized TPUEmbeddingConfiguration proto. + learning_rates: A TensorList of float32 scalars, one for each dynamic + learning rate tag: see the comments in + //third_party/tensorflow/core/protobuf/tpu/ + optimization_parameters.proto. Multiple tables can share the same + dynamic learning rate tag as specified in the configuration. If the + learning rates for all tables are constant, this list should be empty. + name: A name for the operation (optional). + + Returns: + A SendTPUEmbeddingGradients operation. + """ + if learning_rates is None: + learning_rates = [] + return gen_tpu_ops.send_tpu_embedding_gradients( + inputs=inputs, learning_rates=learning_rates, config=config, name=name) + + +send_tpu_embedding_gradients.__doc__ = ( + gen_tpu_ops.send_tpu_embedding_gradients.__doc__) + + +# pylint: disable=protected-access +def enqueue_tpu_embedding_integer_batch(batch, + device_ordinal, + mode_override=None, + name=None): + """A placeholder op for enqueueing embedding IDs to the TPU. + + Args: + batch: A list of 1D tensors, one for each embedding table, containing the + indices into the tables. + device_ordinal: The TPU device to use. Should be >= 0 and less than the + number of TPU cores in the task on which the node is placed. + mode_override: A string input that overrides the mode specified in the + TPUEmbeddingConfiguration. Supported values are {'unspecified', + 'inference', 'train', 'backward_pass_only'}. When set to 'unspecified', + the mode set in TPUEmbeddingConfiguration is used, otherwise mode_override + is used (optional). + name: A name for the operation (optional). + + Returns: + An EnqueueTPUEmbeddingIntegerBatch operation. + """ + if mode_override is None: + mode_override = "unspecified" + return gen_tpu_ops.enqueue_tpu_embedding_integer_batch( + batch=batch, + device_ordinal=device_ordinal, + mode_override=mode_override, + name=name) + + +enqueue_tpu_embedding_integer_batch.__doc__ = ( + gen_tpu_ops.enqueue_tpu_embedding_integer_batch.__doc__) + + +# pylint: disable=protected-access +def enqueue_tpu_embedding_sparse_batch(sample_indices, + embedding_indices, + aggregation_weights, + device_ordinal, + combiners=None, + mode_override=None, + name=None): + """A placeholder op for enqueueing embedding IDs to the TPU. + + Args: + sample_indices: A list of rank 1 Tensors specifying the training example and + feature to which the corresponding embedding_indices and + aggregation_weights values belong. sample_indices[i] must equal b * nf + + f, where nf is the number of features from the corresponding table, f is + in [0, nf), and b is in [0, batch size). Both int32 and int64 are allowed, + and will be converted to int32 internally. + embedding_indices: A list of rank 1 Tensors, indices into the embedding + tables. Both int32 and int64 are allowed and will be converted to int32 + internally. + aggregation_weights: A list of rank 1 Tensors containing per sample -- i.e., + per (training example, feature) -- aggregation weights. Both float32 and + float64 are allowed and will be converted to float32 internally. + device_ordinal: The TPU device to use. Should be >= 0 and less than the + number of TPU cores in the task on which the node is placed. + combiners: A list of string scalars, one for each embedding table that + specify how to normalize the embedding activations after weighted + summation. Supported combiners are 'mean', 'sum', or 'sqrtn'. It is + invalid to have the sum of the weights be 0 for 'mean' or the sum of the + squared weights be 0 for 'sqrtn'. If combiners isn't passed, the default + is to use 'sum' for all tables (optional). + mode_override: A string input that overrides the mode specified in the + TPUEmbeddingConfiguration. Supported values are {'unspecified', + 'inference', 'train', 'backward_pass_only'}. When set to 'unspecified', + the mode set in TPUEmbeddingConfiguration is used, otherwise mode_override + is used (optional). + name: A name for the operation (optional). + + Returns: + An EnqueueTPUEmbeddingSparseBatch operation. + """ + if mode_override is None: + mode_override = "unspecified" + return gen_tpu_ops.enqueue_tpu_embedding_sparse_batch( + sample_indices=sample_indices, + embedding_indices=embedding_indices, + aggregation_weights=aggregation_weights, + device_ordinal=device_ordinal, + combiners=combiners, + mode_override=mode_override, + name=name) + + +enqueue_tpu_embedding_sparse_batch.__doc__ = ( + gen_tpu_ops.enqueue_tpu_embedding_sparse_batch.__doc__) + + +# pylint: disable=protected-access +def enqueue_tpu_embedding_sparse_tensor_batch(sample_indices, + embedding_indices, + aggregation_weights, + table_ids, + device_ordinal, + max_sequence_lengths=None, + num_features=None, + combiners=None, + mode_override=None, + name=None): + """A placeholder op for enqueueing embedding IDs to the TPU. + + Args: + sample_indices: A list of rank 2 Tensors specifying the training example to + which the corresponding embedding_indices and aggregation_weights values + belong. It corresponds to sp_ids.indices in embedding_lookup_sparse(). If + the size of its first dimension is 0, we assume each embedding_indices + belongs to a different sample. Both int32 and int64 are allowed and will + be converted to int32 internally. + embedding_indices: A list of rank 1 Tensors, indices into the embedding + tables. It corresponds to sp_ids.values in embedding_lookup_sparse(). Both + int32 and int64 are allowed and will be converted to int32 internally. + aggregation_weights: A list of rank 1 Tensors containing per training + example aggregation weights. It corresponds to sp_weights.values in + embedding_lookup_sparse(). If the size of its first dimension is 0, we + assume all weights are 1. Both float32 and float64 are allowed and will be + converted to float32 internally. + table_ids: A list of integers specifying the identifier of the embedding + table (offset of TableDescriptor in the TPUEmbeddingConfiguration) to + lookup the corresponding input. The ith input is looked up using + table_ids[i]. The size of the table_ids list must be equal to that of + sample_indices, embedding_indices and aggregation_weights. + device_ordinal: The TPU device to use. Should be >= 0 and less than the + number of TPU cores in the task on which the node is placed. + max_sequence_lengths: A list of integers, the size of which is equal to + sample_indices. If equal to 0, the corresponding feature is considered to + be a non-sequence feature, If greater than 0, the corresponding feature is + a sequence feature with the given maximal length. If None, then we assume + a list of all zeroes. + num_features: A list of integers, the size of which is equal to + sample_indices. If non-empty, entries in this list must be at least 1. For + each batch element, we will take num_features rows of the input tensor for + embedding lookup. E.g., when sample_indices is empty, the embedding + indices must be of shape (batch_size*num_features). + combiners: A list of string scalars, one for each embedding table that + specify how to normalize the embedding activations after weighted + summation. Supported combiners are 'mean', 'sum', or 'sqrtn'. It is + invalid to have the sum of the weights be 0 for 'mean' or the sum of the + squared weights be 0 for 'sqrtn'. If combiners isn't passed, the default + is to use 'sum' for all tables (optional). + mode_override: A string input that overrides the mode specified in the + TPUEmbeddingConfiguration. Supported values are {'unspecified', + 'inference', 'train', 'backward_pass_only'}. When set to 'unspecified', + the mode set in TPUEmbeddingConfiguration is used, otherwise mode_override + is used (optional). + name: A name for the operation (optional). + + Returns: + An EnqueueTPUEmbeddingSparseTensorBatch operation. + """ + if mode_override is None: + mode_override = "unspecified" + return gen_tpu_ops.enqueue_tpu_embedding_sparse_tensor_batch( + sample_indices=sample_indices, + embedding_indices=embedding_indices, + aggregation_weights=aggregation_weights, + table_ids=table_ids, + device_ordinal=device_ordinal, + max_sequence_lengths=max_sequence_lengths, + combiners=combiners, + mode_override=mode_override, + num_features=num_features, + name=name) + + +enqueue_tpu_embedding_sparse_tensor_batch.__doc__ = ( + gen_tpu_ops.enqueue_tpu_embedding_sparse_tensor_batch.__doc__) + + +# pylint: disable=protected-access +def enqueue_tpu_embedding_ragged_tensor_batch(sample_splits, + embedding_indices, + aggregation_weights, + table_ids, + device_ordinal, + max_sequence_lengths=None, + num_features=None, + combiners=None, + mode_override=None, + name=None): + """A placeholder op for enqueueing embedding IDs to the TPU. + + Args: + sample_splits: A list of rank 1 Tensors specifying the break points for + splitting embedding_indices and aggregation_weights into rows. It + corresponds to ids.row_splits in embedding_lookup(), when ids is a + RaggedTensor. Both int32 and int64 are allowed and will be converted to + int32 internally. + embedding_indices: A list of rank 1 Tensors, indices into the embedding + tables. It corresponds to ids.values in embedding_lookup(), when ids is a + RaggedTensor. Both int32 and int64 are allowed and will be converted to + int32 internally. + aggregation_weights: A list of rank 1 Tensors containing per training + example aggregation weights. It corresponds to the values field of a + RaggedTensor with the same row_splits as ids in embedding_lookup(), when + ids is a RaggedTensor. Both float32 and float64 are allowed and will be + converted to float32 internally. + table_ids: A list of integers specifying the identifier of the embedding + table (offset of TableDescriptor in the TPUEmbeddingConfiguration) to + lookup the corresponding input. The ith input is looked up using + table_ids[i]. The size of the table_ids list must be equal to that of + sample_indices, embedding_indices and aggregation_weights. + device_ordinal: The TPU device to use. Should be >= 0 and less than the + number of TPU cores in the task on which the node is placed. + max_sequence_lengths: A list of integers, the size of which is equal to + sample_indices. If equal to 0, the corresponding feature is considered to + be a non-sequence feature, If greater than 0, the corresponding feature is + a sequence feature with the given maximal length. If None, then we assume + a list of all zeroes. + num_features: A list of integers, the size of which must be equal to + sample_indices. If non-empty, entries in this list must be at least 1. For + each batch element, we will take num_features rows of the input tensor for + embedding lookup. E.g., when sample_indices is empty, the embedding + indices must be of shape (batch_size*num_features). + combiners: A list of string scalars, one for each embedding table that + specify how to normalize the embedding activations after weighted + summation. Supported combiners are 'mean', 'sum', or 'sqrtn'. It is + invalid to have the sum of the weights be 0 for 'mean' or the sum of the + squared weights be 0 for 'sqrtn'. If combiners isn't passed, the default + is to use 'sum' for all tables (optional). + mode_override: A string input that overrides the mode specified in the + TPUEmbeddingConfiguration. Supported values are {'unspecified', + 'inference', 'training', 'backward_pass_only'}. When set to 'unspecified', + the mode set in TPUEmbeddingConfiguration is used, otherwise mode_override + is used (optional). + name: A name for the operation (optional). + + Returns: + An EnqueueTPUEmbeddingRaggedTensorBatch operation. + """ + if mode_override is None: + mode_override = "unspecified" + return gen_tpu_ops.enqueue_tpu_embedding_ragged_tensor_batch( + sample_splits=sample_splits, + embedding_indices=embedding_indices, + aggregation_weights=aggregation_weights, + table_ids=table_ids, + device_ordinal=device_ordinal, + max_sequence_lengths=max_sequence_lengths, + combiners=combiners, + mode_override=mode_override, + num_features=num_features, + name=name) + + +enqueue_tpu_embedding_ragged_tensor_batch.__doc__ = ( + gen_tpu_ops.enqueue_tpu_embedding_ragged_tensor_batch.__doc__) + + +def enqueue_tpu_embedding_arbitrary_tensor_batch(sample_indices_or_row_splits, + embedding_indices, + aggregation_weights, + device_ordinal, + combiners=None, + mode_override=None, + name=None): + """A placeholder op for enqueueing embedding IDs to the TPU. + + Args: + sample_indices_or_row_splits: A list of rank 1 or 2 Tensors. When rank 2, + the tensors specify the training example to which the corresponding + embedding_indices and aggregation_weights values belong. If the size of + its first dimension is 0, we assume each embedding_indices belongs to a + different sample. Both int32 and int64 are allowed and will be converted + to int32 internally. When rank 1, the tensors specify the row splits for + splitting embedding_indices and aggregation_weights into rows. It + corresponds to ids.row_splits in embedding_lookup(), when ids is a + RaggedTensor. When enqueuing N-D ragged tensor, only the last dimension is + allowed to be ragged. the row splits is 1-D dense tensor. When empty, we + assume a dense tensor is passed to the op. Both int32 and int64 are + allowed and will be converted to int32 internally. + embedding_indices: A list of rank 1 Tensors, indices into the embedding + tables. Both int32 and int64 are allowed and will be converted to int32 + internally. + aggregation_weights: A list of rank 1 Tensors containing per training + example aggregation weights. Both float32 and float64 are allowed and will + be converted to float32 internally. + device_ordinal: The TPU device to use. Should be >= 0 and less than the + number of TPU cores in the task on which the node is placed. + combiners: A list of string scalars, one for each embedding table that + specify how to normalize the embedding activations after weighted + summation. Supported combiners are 'mean', 'sum', or 'sqrtn'. It is + invalid to have the sum of the weights be 0 for 'mean' or the sum of the + squared weights be 0 for 'sqrtn'. If combiners isn't passed, the default + is to use 'sum' for all tables (optional). + mode_override: A string input that overrides the mode specified in the + TPUEmbeddingConfiguration. Supported values are {'unspecified', + 'inference', 'training', 'backward_pass_only'}. When set to 'unspecified', + the mode set in TPUEmbeddingConfiguration is used, otherwise mode_override + is used (optional). + name: A name for the operation (optional). + + Returns: + An EnqueueTPUEmbeddingArbitraryTensorBatch operation. + """ + if mode_override is None: + mode_override = "unspecified" + return gen_tpu_ops.enqueue_tpu_embedding_arbitrary_tensor_batch( + sample_indices_or_row_splits=sample_indices_or_row_splits, + embedding_indices=embedding_indices, + aggregation_weights=aggregation_weights, + device_ordinal=device_ordinal, + combiners=combiners, + mode_override=mode_override, + name=name) + + +enqueue_tpu_embedding_arbitrary_tensor_batch.__doc__ = ( + gen_tpu_ops.enqueue_tpu_embedding_arbitrary_tensor_batch.__doc__) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_optimizer.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..0140d34aa1687c77be5a5cd41da0cabc3d71fe3f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_optimizer.py @@ -0,0 +1,225 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================= + +"""Optimizer that implements cross-shard gradient reduction for TPU.""" + + +from tensorflow.python.framework import ops +from tensorflow.python.ops.losses import losses +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.tpu import tpu_function +from tensorflow.python.tpu.ops import tpu_ops +from tensorflow.python.training import optimizer +from tensorflow.python.util.tf_export import tf_export + + +@tf_export(v1=["tpu.CrossShardOptimizer"]) +class CrossShardOptimizer(optimizer.Optimizer): + """An optimizer that averages gradients across TPU shards.""" + + def __init__(self, + opt, + reduction=losses.Reduction.MEAN, + name="CrossShardOptimizer", + group_assignment=None): + """Construct a new cross-shard optimizer. + + Args: + opt: An existing `Optimizer` to encapsulate. + reduction: The reduction to apply to the shard losses. + name: Optional name prefix for the operations created when applying + gradients. Defaults to "CrossShardOptimizer". + group_assignment: Optional 2d int32 lists with shape + [num_groups, num_replicas_per_group] which describles how to apply + optimizer to subgroups. + + Raises: + ValueError: If reduction is not a valid cross-shard reduction. + """ + accepted_reductions = (losses.Reduction.SUM, losses.Reduction.MEAN) + if reduction not in accepted_reductions: + raise ValueError( + f"Argument `reduction` should be one of {accepted_reductions}. " + f"Received: {reduction}") + if not isinstance(opt, optimizer.Optimizer): + raise TypeError( + "CrossShardOptimizer only works with tf.training.Optimizer and not " + f"Keras Optimizer. Received: {opt}. " + "If you are using TPUStrategy, " + "Keras Optimizer will sum gradients across replicas." + "If you are using TPUEstimator, you may instead sum your gradients " + "with:\n" + "`grads = [tf.compat.v1.tpu.cross_replica_sum(g) for g in grads]`\n" + "If you want to average your gradients, rescale your loss with: " + "`loss /= global_batch_size`") + + super(CrossShardOptimizer, self).__init__(False, name) + self._opt = opt + self._reduction = reduction + self._group_assignment = group_assignment + + def _verify_and_get_subgroup_size(self, group_assignment, num_shards): + """Verify group_assignment and get the subgroup size". + + Args: + group_assignment: list of group ids for applying the optimizer + to subgroups. + num_shards: The number of TPU shards. + + Returns: + The size of one subgroup in group_assignment. + + Raises: + ValueError: If group_assignment is invalid. + """ + if not group_assignment: + return None + if not (isinstance(group_assignment, list) and + all(isinstance(i, list) for i in group_assignment)): + raise ValueError( + f"Argument `group_assignment` must be a list of lists. " + f"Received: {group_assignment}") + + replica_ids = set() + for g in group_assignment: + for i in g: + replica_ids.add(i) + + if set(range(num_shards)) != replica_ids: + raise ValueError( + f"Argument `group_assignment` must be a permutation of " + f"range({num_shards}). Received: {group_assignment}") + + subgroup_size_list = [len(group) for group in group_assignment] + if all(subgroup_size_list[0] == size for size in subgroup_size_list): + return subgroup_size_list[0] + else: + raise ValueError("The size of each subgroup in `group_assignment` must " + f"be equal. Received: {group_assignment}") + + def compute_gradients(self, loss, var_list=None, **kwargs): + """Compute gradients of "loss" for the variables in "var_list". + + This simply wraps `compute_gradients()` from the real optimizer. The + gradients will be aggregated in `apply_gradients()` so that user can + modify the gradients like clipping with per replica global norm if needed. + The global norm with aggregated gradients can be bad as one replica's huge + gradients can hurt the gradients from other replicas. + + When the CrossShardOptimizer is constructed with + `reduction == losses.Reduction.MEAN` (default), this function scales the + loss by `1.0 / num_shards` before computing the gradients. Assuming the + optimizer uses the default implementation of `compute_gradients()`, the + gradients of the scaled loss are scaled by `1.0 / num_shards` compared to + the gradients of the original loss. This scaling factor is important because + `apply_gradients()` sums gradients across shards, rather than averaging + them. However, the scaling factor must be taken into account when clipping + the norm of the gradients or performing other postprocessing. + + Args: + loss: A Tensor containing the value to minimize. + var_list: Optional list or tuple of `tf.Variable` to update to minimize + `loss`. Defaults to the list of variables collected in the graph + under the key `GraphKey.TRAINABLE_VARIABLES`. + **kwargs: Keyword arguments for compute_gradients(). + + Returns: + A list of (gradient, variable) pairs. + + Raises: + ValueError: If not within a tpu_shard_context or group_assignment is + invalid. + """ + num_shards = tpu_function.get_tpu_context().number_of_shards + if num_shards is None: + logging.warning( + "CrossShardOptimizer should be used within a tpu_shard_context, but " + "got unset number_of_shards. Assuming 1.") + num_shards = 1 + + subgroup_size = self._verify_and_get_subgroup_size(self._group_assignment, + num_shards) + + if num_shards > 1 and self._reduction == losses.Reduction.MEAN: + if self._group_assignment: + scale = 1.0 / subgroup_size + else: + scale = 1.0 / num_shards + loss *= scale + + return self._opt.compute_gradients(loss, var_list=var_list, **kwargs) + + def apply_gradients(self, grads_and_vars, global_step=None, name=None): + """Apply gradients to variables. + + Calls tpu_ops.cross_replica_sum() to sum gradient contributions across + replicas, and then applies the real optimizer. + + Args: + grads_and_vars: List of (gradient, variable) pairs as returned by + compute_gradients(). + global_step: Optional Variable to increment by one after the + variables have been updated. + name: Optional name for the returned operation. Default to the + name passed to the Optimizer constructor. + + Returns: + An `Operation` that applies the gradients. If `global_step` was not None, + that operation also increments `global_step`. + + Raises: + ValueError: If the grads_and_vars is malformed. + """ + summed_grads_and_vars = [] + for (grad, var) in grads_and_vars: + if grad is None: + summed_grads_and_vars.append((grad, var)) + else: + with ops.colocate_with(grad): + summed_grads_and_vars.append((tpu_ops.cross_replica_sum( + grad, self._group_assignment), var)) + return self._opt.apply_gradients(summed_grads_and_vars, global_step, name) + + def get_slot(self, *args, **kwargs): + """Return a slot named "name" created for "var" by the Optimizer. + + This simply wraps the get_slot() from the actual optimizer. + + Args: + *args: Arguments for get_slot(). + **kwargs: Keyword arguments for get_slot(). + + Returns: + The `Variable` for the slot if it was created, `None` otherwise. + """ + return self._opt.get_slot(*args, **kwargs) + + def get_slot_names(self, *args, **kwargs): + """Return a list of the names of slots created by the `Optimizer`. + + This simply wraps the get_slot_names() from the actual optimizer. + + Args: + *args: Arguments for get_slot(). + **kwargs: Keyword arguments for get_slot(). + + Returns: + A list of strings. + """ + return self._opt.get_slot_names(*args, **kwargs) + + def variables(self): + """Forwarding the variables from the underlying optimizer.""" + return self._opt.variables() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_replication.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_replication.py new file mode 100644 index 0000000000000000000000000000000000000000..f88dd2f192efa1d12137ee60f81d176f73b87e79 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_replication.py @@ -0,0 +1,772 @@ +# Copyright 2023 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file8 except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ====================================== + +"""OutsideCompilation, TPUReplicateContext, and supporting functions.""" + +from typing import Any, Callable, List, Optional, Text, Tuple, Union +from absl import logging +from tensorflow.core.framework import attr_value_pb2 +from tensorflow.python.distribute import device_util +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.framework import device as pydev +from tensorflow.python.framework import errors +from tensorflow.python.framework import func_graph +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import variables +from tensorflow.python.tpu import device_assignment as device_assignment_lib +from tensorflow.python.tpu.ops import tpu_ops +from tensorflow.python.types import core as core_types +from tensorflow.python.util import compat +from tensorflow.python.util.tf_export import tf_export + +_MAX_WARNING_LINES = 5 +_TPU_REPLICATE_ATTR = "_tpu_replicate" +_OUTSIDE_COMPILATION_ATTR = "_xla_outside_compilation" +_MAP_OUTSIDE_COMPILATION_ATTR = "_xla_map_outside_compilation" + +# Operations that indicate some error in the users graph, e.g. a placeholder +# that's introduced outside of the infeed. +_DENYLISTED_OPS = frozenset([ + "Placeholder", +]) + + +# XLA doesn't currently support reading of intermediate tensors, thus some ops +# are not supported. +_UNSUPPORTED_OPS = frozenset([ + "AudioSummary", + "AudioSummaryV2", + "HistogramSummary", + "ImageSummary", + "MergeSummary", + "Print", + "ScalarSummary", + "TensorSummary", + "TensorSummaryV2", +]) + + +def is_tpu_strategy(strategy: Any) -> bool: + is_tpu_strat = lambda k: k.__name__.startswith("TPUStrategy") + clz = strategy.__class__ + return is_tpu_strat(clz) or any(map(is_tpu_strat, clz.__bases__)) + + +def _enclosing_tpu_device_assignment( +) -> Optional[device_assignment_lib.DeviceAssignment]: + if not distribute_lib.has_strategy(): + return None + strategy = distribute_lib.get_strategy() + if not is_tpu_strategy(strategy): + return None + return strategy.extended._device_assignment # pylint: disable=protected-access + + +class TPUReplicateContext(control_flow_ops.XLAControlFlowContext): + """A `ControlFlowContext` for nodes inside a TPU computation. + + The primary role of `TPUReplicateContext` is to mark operators inside a + tpu.replicate() computation with the attribute "_tpu_replicate=XYZ", where XYZ + is a unique name. + + We use a `ControlFlowContext` to perform the annotation since it integrates + with Tensorflow constructs like ResourceVariables. For example, if a + `ResourceVariable` is constructed inside a tpu.replicate() block, the + `ResourceVariable` implementation can use + `with ops.control_dependencies(None)` to build the variable's definition + outside the replicated computation. + """ + + def __init__(self, name: Text, num_replicas: int, pivot: ops.Operation): + """Builds a new TPUReplicateContext. + + Args: + name: a unique name for the context, used to populate the `_tpu_replicate` + attribute. + num_replicas: an integer that gives the number of replicas for the + computation. + pivot: a pivot node. Nodes in the TPUReplicateContext that do not have any + inputs will have a control dependency on the pivot node. This ensures + that nodes are correctly included in any enclosing control flow + contexts. + """ + super(TPUReplicateContext, self).__init__() + self._num_replicas = num_replicas + self._outer_device_function_stack = None + self._oc_dev_fn_stack = None + self._outside_compilation_cluster = None + self._is_map_outside_compilation = False + self._outside_compilation_v2_context = None + self._outside_compilation_counter = 0 + self._in_gradient_colocation = None + self._gradient_colocation_stack = [] + self._host_compute_core = [] + self._name = name + self._tpu_replicate_attr = attr_value_pb2.AttrValue( + s=compat.as_bytes(self._name) + ) + self._unsupported_ops = [] + self._pivot = pivot + self._replicated_vars = {} + + def get_replicated_var_handle(self, + name: Text, + handle_id: Text, + vars_: Union[List[core_types.Tensor], + List[variables.Variable]], + is_mirrored: bool = False, + is_packed: bool = False) -> core_types.Tensor: + """Returns a variable handle for replicated TPU variable 'var'. + + This is a method used by an experimental replicated variable implementation + and is not intended as a public API. + + Args: + name: The common name of the variable. + handle_id: Unique ID of the variable handle, used as the cache key. + vars_: The replicated TPU variables or handles. + is_mirrored: Whether the variables are mirrored, which guarantees the + values in each replica are always the same. + is_packed: Whether the replicated variables are packed into one variable. + + Returns: + The handle of the TPU replicated input node. + """ + device_assignment = _enclosing_tpu_device_assignment() + # We don't need to put device assignment as part of the replicated_vars key + # because each TPUReplicateContext will only have one device assignment. + handle = self._replicated_vars.get(handle_id) + if handle is not None: + return handle + + if device_assignment is not None and not is_packed: + # Find a variable copy for each replica in the device assignment. + # Note that the order of devices for replicas for the variable and the + # device assignment might not match. + job_name = pydev.DeviceSpec.from_string(vars_[0].device).job + devices_to_vars = {device_util.canonicalize(v.device): v for v in vars_} + replicated_vars = [] + for replica_id in range(device_assignment.num_replicas): + for logical_core in range(device_assignment.num_cores_per_replica): + device = device_util.canonicalize( + device_assignment.tpu_device( + replica=replica_id, logical_core=logical_core, job=job_name)) + if device in devices_to_vars: + replicated_vars.append(devices_to_vars[device]) + break + else: + raise ValueError( + "Failed to find a variable on any device in replica {} for " + "current device assignment".format(replica_id) + ) + else: + replicated_vars = vars_ + + # Builds a TPUReplicatedInput node for the variable, if one does not already + # exist. The TPUReplicatedInput node must belong to the enclosing + # control-flow scope of the TPUReplicateContext. + # TODO(phawkins): consider changing the contract of the TPU encapsulation + # so the TPUReplicatedInput nodes go inside the TPUReplicateContext scope + # instead. + + _, graph = _enclosing_tpu_context_and_graph() + with graph.as_default(): + # If replicated_vars are variables, get the handles. Note that this can be + # done inside TPUReplicateContext because replicated_vars.handle may + # create new ops. + if isinstance(replicated_vars[0], variables.Variable): + replicated_vars = [v.handle for v in replicated_vars] + # pylint: disable=protected-access + saved_context = graph._get_control_flow_context() + graph._set_control_flow_context(self.outer_context) + handle = tpu_ops.tpu_replicated_input( + replicated_vars, + name=name + "/handle", + is_mirrored_variable=is_mirrored, + is_packed=is_packed) + graph._set_control_flow_context(saved_context) + # pylint: enable=protected-access + self._replicated_vars[handle_id] = handle + return handle + + def report_unsupported_operations(self) -> None: + if self._unsupported_ops: + op_str = "\n".join( + " %s (%s)" % (op.type, op.name) for op in + self._unsupported_ops[:_MAX_WARNING_LINES]) + logging.warning("%d unsupported operations found: \n%s", + len(self._unsupported_ops), op_str) + if len(self._unsupported_ops + ) > _MAX_WARNING_LINES: + logging.warning("... and %d more", + (len(self._unsupported_ops) - _MAX_WARNING_LINES)) + + def EnterGradientColocation(self, op: ops.Operation, gradient_uid: Text): + if op is not None: + if ops.get_default_graph()._control_flow_context is None: # pylint: disable=protected-access + # If we are in TF 2 functions (control flow V2 functions, or + # tf.function()), we need to attach _xla_outside_compilation attribute + # directly because we are not in TPUReplicateContext. + try: + outside_attr = op.get_attr(_OUTSIDE_COMPILATION_ATTR).decode("ascii") + except ValueError: + # The attr was not present: do nothing. + return + parts = outside_attr.split(".") + cluster = parts[0] + "." + gradient_uid + self._outside_compilation_v2_context = OutsideCompilationV2Context( + cluster) + self._outside_compilation_v2_context.Enter() + return + self._gradient_colocation_stack.append(op) + if not self._outside_compilation_cluster: + try: + outside_attr = op.get_attr(_OUTSIDE_COMPILATION_ATTR).decode("ascii") + if self._in_gradient_colocation: + raise NotImplementedError( + "Cannot nest gradient colocation operations outside compilation" + ) + if gradient_uid == "__unsupported__": + raise NotImplementedError( + "No gradient_uid calling gradient within outside_compilation") + # When we take the gradient of an op X in an outside_compilation + # cluster C in a forward computation we would like to put the ops + # corresponding to the gradient of X into a new outside_compilation + # cluster C'. However, if we take the gradient of X twice, the second + # one should get yet another new outside_compilation cluster C''. + # + # The mechanism we adopt is to use a 'root_cluster' which is the + # cluster that X was in before we took gradients, and a 'gradient_uid' + # which is different for every invocation of gradients, and put the + # gradient of X in cluster 'root_cluster.gradient_uid'. + # + # When taking a gradient of a gradient, some ops will be colocated + # with Op in the forward pass (e.g., cluster root_cluster) and some in + # the backward pass (e.g., cluster root_cluster.initial_gradient_uid). + # We need all of the grad-of-grad ops to be in the same cluster to + # avoid cyclic dependencies between clusters. We adopt a heuristic + # that puts any op clustered with root_cluster. in + # root_cluster.gradient_uid, even if xxx was initial_gradient_uid. + self._in_gradient_colocation = op + parts = outside_attr.split(".") + cluster = parts[0] + "." + gradient_uid + self._EnterOutsideCompilationScope(cluster=cluster) + except ValueError: + # The attr was not present: do nothing. + pass + + def ExitGradientColocation(self, op: ops.Operation, gradient_uid: Text): + if op is not None: + if ops.get_default_graph()._control_flow_context is None: # pylint: disable=protected-access + # Inside a TF2 tf.function or control flow graph and `op` was not + # marked to be outside compiled. + assert self._outside_compilation_v2_context is None + return + if self._outside_compilation_v2_context is not None: + # Inside a TF2 tf.function or control flow graph and `op` was + # marked to be outside compiled. + self._outside_compilation_v2_context.Exit() + self._outside_compilation_v2_context = None + return + if not self._gradient_colocation_stack: + raise errors.InternalError( + op.node_def, op, + ("Badly nested gradient colocation: " + + f"empty stack when popping Op {op.name}") + ) + last_op = self._gradient_colocation_stack.pop() + if op is last_op: + if op is self._in_gradient_colocation: + self._in_gradient_colocation = None + self._ExitOutsideCompilationScope() + else: + raise errors.InternalError( + op.node_def, op, + ("Badly nested gradient colocation, " + + f"expected {last_op}, got {op.name}") + ) + + def _EnterOutsideCompilationScope( + self, cluster: Optional[Text] = None, is_map_outside_compilation=False + ): + class FakeOp(object): + """A helper class to determine the current device. + + Supports only the type and device set/get methods needed to run the + graph's _apply_device_function method. + """ + + def __init__(self): + self._device = "" + + @property + def type(self): + return "FakeOp" + + @property + def device(self): + return self._device + + def _set_device(self, device): + if isinstance(device, pydev.DeviceSpec): + self._device = device.to_string() + else: + self._device = device + + def _set_device_from_string(self, device_str): + self._device = device_str + + if self._outside_compilation_cluster: + raise NotImplementedError("Cannot nest outside_compilation clusters") + if cluster: + self._outside_compilation_cluster = cluster + else: + self._outside_compilation_cluster = str(self._outside_compilation_counter) + self._outside_compilation_counter += 1 + if is_map_outside_compilation: + self._is_map_outside_compilation = True + graph = ops.get_default_graph() + fake_op = FakeOp() + graph._apply_device_functions(fake_op) # pylint: disable=protected-access + device = pydev.DeviceSpec.from_string(fake_op.device) + if (device.device_type == "TPU_REPLICATED_CORE" and + device.device_index is not None): + self._host_compute_core.append(self._outside_compilation_cluster + ":" + + str(device.device_index)) + self._oc_dev_fn_stack = graph._device_function_stack # pylint: disable=protected-access + graph._device_function_stack = self._outer_device_function_stack # pylint: disable=protected-access + + def _ExitOutsideCompilationScope(self): + if not self._outside_compilation_cluster: + raise ValueError( + "Attempted to exit outside_compilation scope when not in scope") + self._outside_compilation_cluster = None + self._is_map_outside_compilation = False + graph = ops.get_default_graph() + graph._device_function_stack = self._oc_dev_fn_stack # pylint: disable=protected-access + + def Enter(self) -> None: + if not self._outer_device_function_stack: + # Capture the device function stack at the time of first entry + # since that is the stack that will be used outside_compilation. + graph = ops.get_default_graph() + # pylint: disable=protected-access + self._outer_device_function_stack = graph._device_function_stack.copy() + # pylint: enable=protected-access + super(TPUReplicateContext, self).Enter() + + def HostComputeCore(self) -> List[Text]: + return self._host_compute_core + + def _RemoveExternalControlEdges( + self, + op: ops.Operation) -> Tuple[List[ops.Operation], List[ops.Operation]]: + """Remove any external control dependency on this op.""" + internal_control_inputs = [] + external_control_inputs = [] + for x in op.control_inputs: + # pylint: disable=protected-access + is_internal_op = False + ctxt = x._get_control_flow_context() + while ctxt is not None: + if ctxt == self: + is_internal_op = True + break + ctxt = ctxt._outer_context + if is_internal_op: + internal_control_inputs.append(x) + else: + external_control_inputs.append(x) + # pylint: enable=protected-access + # pylint: disable=protected-access + op._remove_all_control_inputs() + op._add_control_inputs(internal_control_inputs) + # pylint: enable=protected-access + return internal_control_inputs, external_control_inputs + + def AddOp(self, op: ops.Operation) -> None: + # pylint: disable=protected-access + if op.type in _DENYLISTED_OPS: + logging.error( + "Operation of type %s (%s) is not supported on the TPU. " + "Execution will fail if this op is used in the graph. ", op.type, + op.name) + + if op.type in _UNSUPPORTED_OPS: + self._unsupported_ops.append(op) + + if any(x.dtype._is_ref_dtype for x in op.inputs): + raise NotImplementedError( + f"Non-resource Variables are not supported inside TPU computations " + f"(operator name: {op.name})") + + # TensorFlowOpLayer may clone nodes that are in tpu.rewrite()s. It'll add + # the "_cloned" attribute and we should continue in that case. + if (_TPU_REPLICATE_ATTR in op.node_def.attr and + "_cloned" not in op.node_def.attr): + raise ValueError(f"TPU computations cannot be nested on op ({op})") + op._set_attr(_TPU_REPLICATE_ATTR, self._tpu_replicate_attr) + if self._outside_compilation_cluster: + op._set_attr( + _OUTSIDE_COMPILATION_ATTR, + attr_value_pb2.AttrValue( + s=compat.as_bytes(self._outside_compilation_cluster))) + if self._is_map_outside_compilation: + op._set_attr( + _MAP_OUTSIDE_COMPILATION_ATTR, + attr_value_pb2.AttrValue(b=True), + ) + if self._num_replicas > 1 or not self._outside_compilation_cluster: + # Prevent feeding or fetching anything that is being compiled, + # and any replicated outside_compilation Op. + op.graph.prevent_feeding(op) + op.graph.prevent_fetching(op) + + # Remove any control edges from outer control flow contexts. These may cause + # mismatched frame errors. + (internal_control_inputs, + external_control_inputs) = self._RemoveExternalControlEdges(op) + + if not op.inputs: + # Add a control edge from the control pivot to this op. + if not internal_control_inputs: + # pylint: disable=protected-access + op._add_control_input(self.GetControlPivot()) + # pylint: enable=protected-access + else: + for index in range(len(op.inputs)): + x = op.inputs[index] + real_x = self.AddValue(x) + if real_x is not x: + op._update_input(index, real_x) # pylint: disable=protected-access + + if external_control_inputs: + # Use an identity to pull control inputs as data inputs. Note that we + # ignore ops which don't have outputs. TODO(phawkins): fix that. + with ops.control_dependencies(None): + self.Enter() + external_control_inputs = [ + array_ops.identity(x.outputs[0]).op + for x in external_control_inputs + if x.outputs + ] + self.Exit() + # pylint: disable=protected-access + op._add_control_inputs(external_control_inputs) + # pylint: enable=protected-access + + # Mark op's outputs as seen by this context and any outer contexts. + output_names = [x.name for x in op.outputs] + context = self + while context is not None: + # pylint: disable=protected-access + context._values.update(output_names) + context = context._outer_context + # pylint: enable=protected-access + + if self._outer_context: + self._outer_context.AddInnerOp(op) + + def AddValue(self, val: core_types.Tensor) -> core_types.Tensor: + """Add `val` to the current context and its outer context recursively.""" + if not self._outer_context: + return val + + if val.name in self._values: + # Use the real value if it comes from outer context. + result = self._external_values.get(val.name) + return val if result is None else result + + result = val + self._values.add(val.name) + if self._outer_context: + result = self._outer_context.AddValue(val) + self._values.add(result.name) + + self._external_values[val.name] = result + + return result + + def AddInnerOp(self, op: ops.Operation): + self.AddOp(op) + if self._outer_context: + self._outer_context.AddInnerOp(op) + + @property + def grad_state(self): + # Define the gradient loop state associated with the TPUReplicateContext to + # be None as the TPUReplicateContext does not get nested nor does the + # grad_state outside the TPUReplicateContext affect the graph inside so the + # grad_state should be as if this is the top-level gradient state. + return None + + @property + def back_prop(self): + """Forwards to the enclosing while context, if any.""" + if self.GetWhileContext(): + return self.GetWhileContext().back_prop + return False + + def GetControlPivot(self) -> ops.Operation: + return self._pivot + + def RequiresUniqueFunctionRetracing(self): + # More context: b/158152827. TPU stack uses the TPUReplicateContext to + # create replicated variable handles and cluster TPU computations, thus we + # always retrace a tf.function when the wrapped TPUReplicateContext changes. + return True + + +def _enclosing_tpu_context_and_graph() -> Tuple[Any, Any]: + """Returns the TPUReplicateContext and its associated graph.""" + graph = ops.get_default_graph() + while graph is not None: + # pylint: disable=protected-access + context_ = graph._get_control_flow_context() + # pylint: enable=protected-access + while context_ is not None: + if isinstance(context_, TPUReplicateContext): + return context_, graph + context_ = context_.outer_context + graph = getattr(graph, "outer_graph", None) + raise ValueError("get_replicated_var_handle() called without " + "TPUReplicateContext. This shouldn't happen. Please file " + "a bug.") + + +class OutsideCompilationV2Context(control_flow_ops.ControlFlowContext): + """The context for outside compilation in Tensorflow 2.0. + + Every op added in this context will be assigned an _xla_outside_compilation + attribute. + """ + + def __init__(self, name: Text, is_map_outside_compilation=False): + control_flow_ops.ControlFlowContext.__init__(self) + self._name = name + self._is_map_outside_compilation = is_map_outside_compilation + + def AddOp(self, op: ops.Operation) -> None: + if self._outer_context: + self._outer_context.AddOp(op) + self._set_outside_compilation_attributes(op) + + def AddInnerOp(self, op: ops.Operation) -> None: + if self._outer_context: + self._outer_context.AddInnerOp(op) + self._set_outside_compilation_attributes(op) + + def to_control_flow_context_def(self, context_def, export_scope=None): + raise NotImplementedError + + def _set_outside_compilation_attributes(self, op: ops.Operation) -> None: + # pylint: disable=protected-access + op._set_attr( + _OUTSIDE_COMPILATION_ATTR, + attr_value_pb2.AttrValue(s=compat.as_bytes(self._name)), + ) + if self._is_map_outside_compilation: + op._set_attr( + _MAP_OUTSIDE_COMPILATION_ATTR, attr_value_pb2.AttrValue(b=True) + ) + # pylint: enable=protected-access + + +def outside_compilation_impl( + is_map, computation: Callable[..., Any], *args, **kwargs +) -> Any: + """Tags ops in `computation` with outside compilation attributes for ordinary `outside_compilation` or `map_outside_compilation`.""" + args = [] if args is None else args + graph = ops.get_default_graph() + + # If we are in TF 2 functions (control flow V2 functions, or tf.function()), + # we need to attach _xla_outside_compilation attribute directly because we are + # not in TPUReplicateContext. + if isinstance(graph, func_graph.FuncGraph): + try: + tpu_context, _ = _enclosing_tpu_context_and_graph() + except ValueError: + logging.warning( + "Outside compilation attempted outside TPUReplicateContext " + "scope. As no enclosing TPUReplicateContext can be found, " + "returning the result of `computation` as is." + ) + return computation(*args, **kwargs) + + # pylint: disable=protected-access + outside_compilation_name = str(tpu_context._outside_compilation_counter) + tpu_context._outside_compilation_counter = ( + tpu_context._outside_compilation_counter + 1 + ) + # pylint: enable=protected-access + + outside_compilation_context = OutsideCompilationV2Context( + outside_compilation_name, is_map_outside_compilation=is_map + ) + outside_compilation_context.Enter() + args = [] if args is None else args + retval = computation(*args, **kwargs) + outside_compilation_context.Exit() + return retval + + # If we are in a TPUReplicateContext, signal that we are now + # outside_compilation + initial_context = graph._get_control_flow_context() # pylint: disable=protected-access + context = initial_context + while context: + if isinstance(context, TPUReplicateContext): + context._EnterOutsideCompilationScope(is_map_outside_compilation=is_map) # pylint: disable=protected-access + context = context.outer_context + + retval = computation(*args, **kwargs) + + # If we are in a TPUReplicateContext, signal that we are no longer + # outside_compilation + final_context = graph._get_control_flow_context() # pylint: disable=protected-access + if initial_context is not final_context: + raise NotImplementedError( + "Control-flow context cannot be different at start and end of an " + "outside_compilation scope" + ) + context = initial_context + while context: + if isinstance(context, TPUReplicateContext): + context._ExitOutsideCompilationScope() # pylint: disable=protected-access + context = context.outer_context + + return retval + + +@tf_export(v1=["tpu.outside_compilation"]) +def outside_compilation( + computation: Callable[..., Any], *args, **kwargs +) -> Any: + """Builds part of a computation outside any current TPU replicate scope. + + `tf.tpu.outside_compilation()` is used to run ops in `computation` on CPU + instead of running on TPU. For example, users can run ops that are not + supported on TPU's (e.g. tf.summary.write()) by explicitly placing those + ops on CPU's. Below usage of outside compilation will place ops in + `computation_with_string_ops` on CPU. + + Example usage: + + ```python + def computation_with_string_ops(x): + # strings types are not supported on TPU's and below ops must + # run on CPU instead. + output = tf.strings.format('1{}', x) + return tf.strings.to_number(output) + + def tpu_computation(): + # Expected output is 11. + output = tf.tpu.outside_compilation(computation_with_string_ops, 1) + ``` + + Outside compilation should be called inside TPUReplicateContext. That is, + `tf.tpu.outside_compilation()` should be called inside a function that is + passed to `tpu.split_compile_and_replicate()` -- this is implied when + outside compilation is invoked inside a function passed to TPUStrategy + `run()`. If invoked outside of TPUReplicateContext, + then this simply returns the result of `computation`, and therefore, + would be a no-op. Note that outside compilation is different from + `tf.distribute.experimental.TPUStrategy.merge_call()` as logic in + outside compilation is replicated and executed separately for each + replica. On the other hand, `merge_call()` requires a `merge_fn` + to aggregate the inputs from different replicas and is executed only + once. + + For variables placed in TPU device, which includes variables created inside + TPUStrategy scope, outside compilation logic must not include variable + read/write. For variables placed on host, which is the case when variables + created via TPUEstimator, variable read/write is only allowed if the variable + is not accessed by any other ops in the TPU computation. Variable read/write + from outside compilation cluster is not visible from TPU computation and + vice versa. Therefore, if outside compilation logic contains such host + variables read/write ops and if the variables are accessed by TPU + computation as well, then this may lead to deadlock. + + Internally, `tf.tpu.outside_compilation()` adds outside compilation + attributes to all ops in `computation`. During a later passes ops with outside + compilation attributes are moved to a host-side graph. Inputs to this extract + host-side graph are sent from TPU computation graph to host graph via a pair + of XlaSendToHost and XlaRecvFromHost ops. Note that using + `tf.tpu.outside_compilation()` may result in tensor transfer between TPU and + CPU, leading to non-trivial performance impact. + + Args: + computation: A Python function that builds the computation to place on the + host. + *args: the positional arguments for the computation. + **kwargs: the keyword arguments for the computation. + + Returns: + The Tensors returned by computation. + """ + return outside_compilation_impl(False, computation, *args, **kwargs) + + +def experimental_map_outside_compilation( + computation: Callable[..., Any], *args, **kwargs +) -> Any: + """Maps `computation` onto shards and puts it outside any current TPU replicate scope. + + `experimental_map_outside_compilation(f, x)` maps `f` onto the shards + of `x`, where `x` is split-sharded. Each invocation of `f` on a split occurs + on the CPU that's associated with the TPU that owns the split. + + Example usage: + + ```python + def normalize_each_split(split): + return split - tf.math.reduce_mean(split) + + def tpu_computation(x): + x_split = strategy.experimental_split_to_logical_devices( + x, [num_cores_per_replica, 1]) + y = experimental_map_outside_compilation( + normalize_each_split, x_split) + y_split = strategy.experimental_split_to_logical_devices( + x, [num_cores_per_replica, 1]) + return y_split + ``` + + `experimental_map_outside_compilation` should be called inside + TPUReplicateContext. That is, `outside_compilation()` should be called + inside a function that is passed to `tpu.split_compile_and_replicate()` -- + this is implied when outside compilation is invoked inside a function passed + to TPUStrategy `run()`. It is invalid to invoke outside of + TPUReplicateContext. + + `experimental_map_outside_compilation` should input and output tensors that + are located on the TPU. + + Internally, `experimental_map_outside_compilation()` adds outside + compilation attributes to all ops in `computation` and moves outside-compiled + ops to a host-side graph. This is similar to `tf.tpu.outside_compilation()`. + Send/recv ops from/to the TPU send each split directly to the TPU's host. + + Args: + computation: A Python function that builds the computation to place on the + host. + *args: the positional arguments for the computation. + **kwargs: the keyword arguments for the computation. + + Returns: + The Tensors returned by computation. + """ + return outside_compilation_impl(True, computation, *args, **kwargs) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_sharding.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_sharding.py new file mode 100644 index 0000000000000000000000000000000000000000..3a78f45e5292931042b4fc1faae7c36006979bce --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_sharding.py @@ -0,0 +1,302 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================= +"""Helper library for sharding during TPU compilation.""" + + +from tensorflow.python.framework import tensor_shape + +_DEFAULT_NUMBER_OF_SHARDS = 1 +_DEFAULT_SHARD_DIMENSION = 0 + + +# TODO(b/36777903) change other parts of tpu.py to use this class. +class ShardingPolicy(object): + """An object use to hold the sharding policy for a Tensor.""" + + def __init__(self): + self._number_of_shards = None + self._number_of_partitions = 1 + self._shard_dimension = None + self._frozen = False + + def __str__(self): + if self.number_of_shards is None or self.shard_dimension is None: + return "ShardingPolicy(unset)" + else: + return ("ShardingPolicy(%d shards dimension %d)" % + (self.number_of_shards, self.shard_dimension)) + + def _fill_default_values(self): + if self._number_of_shards is None: + self._number_of_shards = _DEFAULT_NUMBER_OF_SHARDS + if self._shard_dimension is None: + self._shard_dimension = tensor_shape.as_dimension( + _DEFAULT_SHARD_DIMENSION) + + def freeze(self): + """Prevents further modification to the sharding policy. + + Any values that have not been set when freeze is called are set to + defaults. If the ShardingPolicy is already frozen, this is a NoOp. + """ + if not self._frozen: + self._fill_default_values() + self._frozen = True + + @property + def number_of_shards(self): + """Returns the number of shards in the policy or None if unspecified.""" + return self._number_of_shards + + def set_number_of_shards(self, number_of_shards): + """Sets the number of shards for the current policy. + + If the policy has been frozen then number_of_shards must match the + existing setting. + + Args: + number_of_shards: The number of shards to use in the policy. + + Raises: + ValueError: If the policy has been frozen and number_of_shards + differs from the frozen value; or number_of_shards <= 0. + """ + if self._frozen: + if self._number_of_shards != number_of_shards: + raise ValueError( + f"Can't set sharding policy to use {number_of_shards} shards since " + f"it has been frozen to use {self._number_of_shards}") + else: + if number_of_shards > 0: + self._number_of_shards = number_of_shards + else: + raise ValueError( + f"Can't set sharding policy to use {number_of_shards} shards; " + "value must be > 0") + + @property + def number_of_partitions(self): + """Returns the number of partitions of the policy or None if unspecified.""" + return self._number_of_partitions + + def set_number_of_partitions(self, number_of_partitions): + """Sets the number of partitions for the current policy. + + If the policy has been frozen then shard_dimension must match the + existing setting. + + Args: + number_of_partitions: The number of partitions to use in the policy. + + Raises: + ValueError: If the policy has been frozen and shard_dimension + differs from the frozen value. + """ + if self._frozen: + if self._number_of_partitions != number_of_partitions: + raise ValueError( + f"Can't set number_of_partitions to {number_of_partitions} since " + f"it has been frozen to use {self._number_of_partitions}.") + else: + self._number_of_partitions = number_of_partitions + + @property + def shard_dimension(self): + """Returns the shard dimension of the policy or None if unspecified.""" + return self._shard_dimension + + def set_shard_dimension(self, shard_dimension): + """Sets the shard dimension for the current policy. + + If the policy has been frozen then shard_dimension must match the + existing setting. + + Args: + shard_dimension: The shard dimension to use in the policy. + + Raises: + ValueError: If the policy has been frozen and shard_dimension + differs from the frozen value, or shard_dimension can't be + interpreted as a Dimension. + """ + if self._frozen: + if self._shard_dimension != shard_dimension: + raise ValueError( + "Can't set shard dimension to %d since it has been frozen to " + "use %d." % (shard_dimension, self._shard_dimension)) + else: + self._shard_dimension = tensor_shape.as_dimension(shard_dimension) + + def merge(self, other): + """Merges the policy of another policy into the current policy. + + Args: + other: The policy to merge into this one. + + Raises: + ValueError: If this policy has been frozen and the merge conflicts with + the frozen policy. + """ + if other.number_of_shards is not None: + self.set_number_of_shards(other.number_of_shards) + if other.shard_dimension is not None: + self.set_shard_dimension(other.shard_dimension) + + def get_unpartitioned_shape(self, shape): + """Returns the shape of an unpartitioned Tensor. + + When given the shape of a 'sharded-size' Tensor, returns the shape + of the full shape of its unpartitioned Tensor. + + Args: + shape: The shape of the sharded Tensor. + + Returns: + The shape of the unpartitioned version of the Tensor. + + Raises: + ValueError: if shape has unknown sharded dimension + """ + shape = tensor_shape.as_shape(shape) + dims = shape.as_list() + if (self._shard_dimension is None or self._number_of_partitions is None or + not dims): + return None + if dims[self._shard_dimension] is None: + raise ValueError(f"Shape {shape.as_list()} must have a fixed size for " + f"dimension {self._shard_dimension} that is known. ") + if self._number_of_partitions > 1: + dims[self._shard_dimension] *= self._number_of_partitions + return tensor_shape.as_shape(dims) + + def get_sharded_shape(self, shape, shard_index=None): + """Returns the shape of a shard of a full Tensor. + + When given the shape of a 'full-size' Tensor, returns the shape of + the sub-Tensor after it has been sharded. Freezes the policy if it + has not yet been frozen. + + Args: + shape: The shape of the full-size Tensor to be sharded. + shard_index: The index of the shard whose shape should be returned. + shard_index can be None for sharding policies that use the same shape + for every shard. + + Returns: + The shape of the sharded version of the Tensor. + + Raises: + ValueError: If shard_index is None when shards are of different + shapes; or shard_index is not None and + !(0<=shard_index= self.number_of_shards: + raise ValueError( + f"Requested shard_index {shard_index}, but shard_index must be in " + f"[0,{self._number_of_shards}).") + shape = tensor_shape.as_shape(shape) + if self._number_of_shards == 1: + # Don't do anything when there's only one shard. + return shape + ndims = shape.ndims + if ndims is None: + raise ValueError(f"Shape {shape} must be a known shape.") + if ndims <= self._shard_dimension: + raise ValueError( + f"Shape {shape.as_list()} does not contain shard_dimension " + f"{self._shard_dimension}") + dims = shape.as_list() + if dims[self._shard_dimension] is None: + raise ValueError( + f"Shape {shape.as_list()} must have a fixed size for dimension " + f"{self._shard_dimension} that is known at construction time.") + if (dims[self._shard_dimension] % self._number_of_shards) != 0: + raise ValueError( + f"Shape {shape.as_list()} cannot be sharded {self._number_of_shards} " + f"ways along dimension {self._shard_dimension}") + dims[self._shard_dimension] //= self._number_of_shards + return tensor_shape.TensorShape(dims) + + def _unshard_shape(self, shape): + """Return the unsharded shape that would generate a given sharded shape. + + Args: + shape: the sharded shape to unshard + + Returns: + The unsharded shape. + + Raises: + ValueError: if shape is unknown or does not contain + self.shard_dimension + TypeError: if shape is not convertible to a TensorShape + """ + shape = tensor_shape.as_shape(shape) + if self._number_of_shards == 1: + # Don't do anything when there's only one shard. + return shape + ndims = shape.ndims + if ndims is None: + raise ValueError(f"Shape {shape} must be statically known.") + if ndims <= self._shard_dimension: + raise ValueError(f"Shape {shape.as_list()} does not contain " + f"shard_dimension {self._shard_dimension}. " + f"Rank is too small.") + dims = shape.as_list() + dims[self._shard_dimension] *= self._number_of_shards + return tensor_shape.TensorShape(dims) + + def get_unsharded_shape(self, shapes): + """Returns the shape of an unsharded Tensor given a list of shards. + + When given a list of shapes of shards, returns the shape of the + unsharded Tensor that would generate the shards. Sets defaults for the + policy if number_of_shards or shard_dimension is None. + + Args: + shapes: The shapes of the Tensor shards to be combined. + + Returns: + The shape of the unsharded version of the Tensor. + + Raises: + ValueError: if shapes is not a list of length + self.number_of_shards; or any element of shapes is not a valid + shape consistent with the sharding policy; or the list of + shapes is not a valid sharding of a full shape. + TypeError: if an element of shapes is not convertible to a + TensorShape + """ + self._fill_default_values() + if len(shapes) != self.number_of_shards: + raise ValueError( + f"Shapes {shapes} is length {len(shapes)} but must be a list of " + f"length number_of_shards={self.number_of_shards}") + unsharded_shapes = [self._unshard_shape(s) for s in shapes] + for i in range(self.number_of_shards - 1): + if not unsharded_shapes[i].is_compatible_with( + unsharded_shapes[self.number_of_shards - 1]): + raise ValueError( + f"Sharded shapes {shapes} are not consistent shards of a full shape " + f"sharded {self.number_of_shards} ways along " + f"dimension {self.shard_dimension}.") + return unsharded_shapes[0] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_strategy_util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_strategy_util.py new file mode 100644 index 0000000000000000000000000000000000000000..e122d4816ae6b1182d6e590bc961c5a3aa886849 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_strategy_util.py @@ -0,0 +1,305 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""TPU specific APIs to be used in conjunction with TPU Strategy.""" + +import gc + +from tensorflow.core.protobuf import config_pb2 +from tensorflow.python.client import session as session_lib +from tensorflow.python.distribute.cluster_resolver import cluster_resolver as cluster_resolver_lib +from tensorflow.python.eager import context +from tensorflow.python.eager import def_function +from tensorflow.python.eager import monitoring +from tensorflow.python.framework import device +from tensorflow.python.framework import errors +from tensorflow.python.framework import ops +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.tpu import topology +from tensorflow.python.tpu import tpu +from tensorflow.python.util import compat + + +_INITIALIZED_TPU_SYSTEMS = {} +_LOCAL_MASTERS = ("", "local") + + +_tpu_worker_address = monitoring.StringGauge( + "/tensorflow/tpu/worker_address", + "The worker address that the coordinator/client connects to.", "address") + + +def initialize_tpu_system_impl(cluster_resolver, tpu_cluster_resolver_cls): + """Implementation for tpu.experimental.initialize_tpu_system. + + Kept separate to avoid tpu_oss code duplication. + + Initialize the TPU devices. + + Args: + cluster_resolver: A tf.distribute.cluster_resolver.TPUClusterResolver, + which provides information about the TPU cluster. + tpu_cluster_resolver_cls: a reference to + tf.distribute.cluster_resolver.TPUClusterResolver so that an instance + of it can be initialized if cluster_resolver is None. + Returns: + The tf.tpu.Topology object for the topology of the TPU cluster. If called + inside tf.function, it returns the serialized topology object instead. + + Raises: + RuntimeError: If running inside a tf.function. + NotFoundError: If no TPU devices found in eager mode. + TypeError: If tpu_cluster_resolver_cls is + not tf.distribute.cluster_resolver.TPUClusterResolver. + """ + # check that tpu_cluster_resolver_cls is a + # tf.distribute.cluster_resolver.TPUClusterResolver + if tpu_cluster_resolver_cls is None or not issubclass( + tpu_cluster_resolver_cls, cluster_resolver_lib.ClusterResolver + ) or not hasattr(tpu_cluster_resolver_cls, "tpu_hardware_feature"): + raise TypeError( + "tpu_cluster_resolver_cls is not" + " tf.distribute.cluster_resolver.TPUClusterResolver.") + # Deallocate all TPU buffers by clearing out eager context caches and + # triggering garbage collection to avoid keeping invalid tpu buffer around + # after reinitialized tpu system. + logging.info("Deallocate tpu buffers before initializing tpu system.") + context.context()._clear_caches() # pylint: disable=protected-access + context.context().clear_kernel_cache() + gc.collect() + + job = None + if cluster_resolver is None: + # If no cluster resolver is specified, and running eagerly, execute the init + # ops in the current device scope. + if context.executing_eagerly(): + curr_device = device.DeviceSpec.from_string(context.context().device_name) + if curr_device.job is not None: + job = "{}/replica:0/task:0".format(curr_device.job) + + cluster_resolver = tpu_cluster_resolver_cls("") + assert isinstance(cluster_resolver, tpu_cluster_resolver_cls) + + tpu_name = compat.as_text(cluster_resolver._tpu) # pylint: disable=protected-access + if tpu_name in _INITIALIZED_TPU_SYSTEMS: + logging.warning( + "TPU system %s has already been initialized. " + "Reinitializing the TPU can cause previously created " + "variables on TPU to be lost.", tpu_name) + + logging.info("Initializing the TPU system: %s", tpu_name) + + # This function looks as it is for the following non-intuitive reasons. + # tpu.initialize_system creates a dummy op whose sole purpose is to trigger + # DistributedTPURewritePass. This pass actually adds real ops that + # initialize the TPU system. Thus, we can't simply run tpu.initialize_system + # eagerly. We need to wrap it in defun and trigger the rewrite passes on it. + if tpu_name not in _LOCAL_MASTERS: + # Explicitly place the tpu.initialize_system in the first worker to + # avoid the output node match multiple devices error. + job = "{}/replica:0/task:0".format(cluster_resolver.get_job_name()) + + if context.executing_eagerly(): + @def_function.function(autograph=False) + def _tpu_init_fn(): + # In TF1, we usually close chips when compilation fails to clear the data + # in infeed. In TF2, we don't need to do this because infeed is no longer + # used, so user can recover from TPU compilation failures more smoothly. + # Same for the cancellation of a TPU excution. + return tpu.initialize_system( + job=job, + compilation_failure_closes_chips=False, + tpu_cancellation_closes_chips=False) + + # The TPU_SYSTEM device must match the device used in tpu.initialize_system + # exactly, otherwise you can get errors if there are multiple TPU_SYSTEM + # devices available. + run_eagerly = def_function.functions_run_eagerly() + if run_eagerly: + logging.warning( + "It looks like tf.function behavior was disabled, perhaps using" + " tf.config.run_functions_eagerly." + " tf.tpu.experimental.initialize_tpu_system requires tf.function to" + " work. This primitive will override the disable." + ) + def_function.run_functions_eagerly(False) + try: + with ops.device(tpu._tpu_system_device_name(job)): # pylint: disable=protected-access + output = _tpu_init_fn() + context.async_wait() + except errors.InvalidArgumentError as e: + raise errors.NotFoundError( + None, None, + "TPUs not found in the cluster. Failed in initialization: " + + str(e)) + finally: + if run_eagerly is not None: + def_function.run_functions_eagerly(run_eagerly) + # Clear out the eager context caches since the memory is invalid now. + context.context()._initialize_logical_devices() # pylint: disable=protected-access + + serialized_topology = output.numpy() + elif not ops.executing_eagerly_outside_functions(): + master = cluster_resolver.master() + cluster_spec = cluster_resolver.cluster_spec() + + session_config = config_pb2.ConfigProto(allow_soft_placement=True) + if cluster_spec: + session_config.cluster_def.CopyFrom(cluster_spec.as_cluster_def()) + + with ops.Graph().as_default(): + with session_lib.Session(config=session_config, target=master) as sess: + serialized_topology = sess.run(tpu.initialize_system()) + else: + with ops.device(tpu._tpu_system_device_name(job)): # pylint: disable=protected-access + serialized_topology = tpu.initialize_system( + job=job, compilation_failure_closes_chips=False) + # If initialize_tpu_system is called inside tf.function, we only return + # the serialized topology object as the tf.tpu.Topology object has to be + # constructed in eager mode. + return serialized_topology + + logging.info("Finished initializing TPU system.") + tpu_topology = topology.Topology(serialized=serialized_topology) + cluster_resolver.set_tpu_topology(serialized_topology) + _INITIALIZED_TPU_SYSTEMS[tpu_name] = tpu_topology + + # Record the address of the TPU worker-0 that the coordinator connects to. + # This can be used to associate the TPU worker with the right coordinator when + # aggregating the metrics for the application. An example of the address: + # /bns/mb/borg/mb/bns/chienchunh/chienchunh_group_49640234.1.tfm_train_tpu_worker/0 + _tpu_worker_address.get_cell("address").set(cluster_resolver.get_master()) + + return tpu_topology + + +def get_initialized_tpu_systems(): + """Returns all currently initialized tpu systems. + + Returns: + A dictionary, with tpu name as the key and the tpu topology as the value. + """ + return _INITIALIZED_TPU_SYSTEMS.copy() + + +def shutdown_tpu_system_impl(cluster_resolver, tpu_cluster_resolver_cls): + """Implementation for tpu.experimental.shutdown_tpu_system. + + Kept separate to avoid tpu_oss code duplication. + + Shuts down the TPU devices. + + This will clear all caches, even those that are maintained through sequential + calls to tf.tpu.experimental.initialize_tpu_system, such as the compilation + cache. + + Args: + cluster_resolver: A tf.distribute.cluster_resolver.TPUClusterResolver, + which provides information about the TPU cluster. + tpu_cluster_resolver_cls: a reference to + tf.distribute.cluster_resolver.TPUClusterResolver so that an instance + of it can be initialized if cluster_resolver is None. + + Raises: + RuntimeError: If no TPU devices found for eager execution or if run in a + tf.function. + TypeError: If tpu_cluster_resolver_cls is + not tf.distribute.cluster_resolver.TPUClusterResolver. + """ + # check that tpu_cluster_resolver_cls is a + # tf.distribute.cluster_resolver.TPUClusterResolver + if tpu_cluster_resolver_cls is None or not issubclass( + tpu_cluster_resolver_cls, cluster_resolver_lib.ClusterResolver + ) or not hasattr(tpu_cluster_resolver_cls, "tpu_hardware_feature"): + raise TypeError( + "tpu_cluster_resolver_cls is not" + " tf.distribute.cluster_resolver.TPUClusterResolver.") + + job = None + if cluster_resolver is None: + # If no cluster resolver is specified, and running eagerly, execute the init + # ops in the current device scope. + if context.executing_eagerly(): + curr_device = device.DeviceSpec.from_string(context.context().device_name) + if curr_device.job is not None: + job = "{}/replica:0/task:0".format(curr_device.job) + + cluster_resolver = tpu_cluster_resolver_cls("") + assert isinstance(cluster_resolver, tpu_cluster_resolver_cls) + + tpu_name = compat.as_text(cluster_resolver._tpu) # pylint: disable=protected-access + if tpu_name not in _INITIALIZED_TPU_SYSTEMS: + logging.warning("You are shutting down a TPU system %s that has not been " + "initialized." % tpu_name) + + logging.info("Shutting down the TPU system: %s", tpu_name) + + if context.executing_eagerly(): + # This function looks as it is for the following non-intuitive reasons. + # tpu.shutdown_system creates a dummy op whose sole purpose is to trigger + # DistributedTPURewritePass. This pass actually adds real ops that + # shutdown the TPU system. Thus, we can't simply run tpu.shutdown_system + # eagerly. We need to wrap it in defun and trigger the rewrite passes on it. + if tpu_name not in _LOCAL_MASTERS: + # Explicitly place the tpu.shutdown_system in the first worker to + # avoid the output node match multiple devices error. + job = "{}/replica:0/task:0".format(cluster_resolver.get_job_name()) + + @def_function.function(autograph=False) + def _tpu_shutdown_fn(): + tpu.shutdown_system(job=job) + + # The TPU_SYSTEM device must match the device used in tpu.shutdown_system + # exactly, otherwise you can get errors if there are multiple TPU_SYSTEM + # devices available. + run_eagerly = def_function.functions_run_eagerly() + if run_eagerly: + logging.warning( + "It looks like tf.function behavior was disabled, perhaps using" + " tf.config.run_functions_eagerly." + " tf.tpu.experimental.shutdown_tpu_system requires tf.function to" + " work. This primitive will override the disable." + ) + def_function.run_functions_eagerly(False) + try: + with ops.device(tpu._tpu_system_device_name(job)): # pylint: disable=protected-access + _tpu_shutdown_fn() + finally: + if run_eagerly is not None: + def_function.run_functions_eagerly(run_eagerly) + + # Clear out the eager context caches since the memory is invalid now. + logging.info("Clearing out eager caches") + context.context()._clear_caches() # pylint: disable=protected-access + context.context().clear_kernel_cache() + elif not ops.executing_eagerly_outside_functions(): + master = cluster_resolver.master() + cluster_spec = cluster_resolver.cluster_spec() + + session_config = config_pb2.ConfigProto(allow_soft_placement=True) + if cluster_spec: + session_config.cluster_def.CopyFrom(cluster_spec.as_cluster_def()) + + with ops.Graph().as_default(): + with session_lib.Session(config=session_config, target=master) as sess: + sess.run(tpu.shutdown_system()) + else: + raise RuntimeError( + "initialize_tpu_system is not supported within " + "tf.functions. You should call initialize_tpu_system outside of your tf.function. " + ) + + logging.info("Finished shutting down TPU system.") + if tpu_name in _INITIALIZED_TPU_SYSTEMS: + del _INITIALIZED_TPU_SYSTEMS[tpu_name] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_system_metadata.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_system_metadata.py new file mode 100644 index 0000000000000000000000000000000000000000..82f906c6160262c0c8bdea7c13bd49232032f0fa --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_system_metadata.py @@ -0,0 +1,227 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# =================================================================== +"""TPU system metadata and associated tooling.""" + +import collections + +from tensorflow.core.protobuf import config_pb2 +from tensorflow.python.client import session as session_lib +from tensorflow.python.distribute import device_util +from tensorflow.python.eager import context +from tensorflow.python.framework import config +from tensorflow.python.framework import device as tf_device +from tensorflow.python.framework import errors +from tensorflow.python.framework import ops +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.tpu import tpu +from tensorflow.python.util.tf_export import tf_export + +_PINGING_MASTER_TIMEOUT_IN_MS = 5 * 60 * 1000 # 10 min +_RETRY_TIMES = 12 * 24 # 1 day +_INITIAL_TPU_SYSTEM_TIMEOUT_IN_MS = 300 * 1000 # 5 mins + +_DEFAULT_JOB_NAME = 'tpu_worker' +_DEFAULT_COORDINATOR_JOB_NAME = 'coordinator' +_LOCAL_MASTERS = ('', 'local') + + +@tf_export('tpu.experimental.TPUSystemMetadata') +class TPUSystemMetadata( + collections.namedtuple('TPUSystemMetadata', [ + 'num_cores', + 'num_hosts', + 'num_of_cores_per_host', + 'topology', + 'devices', + ])): + """Describes some metadata about the TPU system. + + Attributes: + num_cores: interger. Total number of TPU cores in the TPU system. + num_hosts: interger. Total number of hosts (TPU workers) in the TPU system. + num_of_cores_per_host: interger. Number of TPU cores per host (TPU worker). + topology: an instance of `tf.tpu.experimental.Topology`, which describes the + physical topology of TPU system. + devices: a tuple of strings, which describes all the TPU devices in the + system. + """ + + def __new__(cls, num_cores, num_hosts, num_of_cores_per_host, topology, + devices): + return super(TPUSystemMetadata, + cls).__new__(cls, num_cores, num_hosts, num_of_cores_per_host, + topology, devices) + + +def _query_tpu_system_metadata(master_address, cluster_def=None, + query_topology=False): + """Automatically detects the TPU system metadata in the system.""" + tpu_core_count = 0 + devices = [] + device_dict = collections.defaultdict(list) + + if context.executing_eagerly(): + logical_devices = config.list_logical_devices() + + # We want the output type to match in both eager and session mode + devices = [session_lib._DeviceAttributes(device_util.canonicalize(d.name), # pylint: disable=protected-access + d.device_type, 0, 0) + for d in logical_devices] + else: + # TODO(b/120564445): Replace with standard library for retries. + retry_count = 1 + while True: + logging.info('Querying Tensorflow master (%s) for TPU system metadata.', + master_address) + try: + with ops.Graph().as_default(): + with session_lib.Session( + master_address, + config=get_session_config_with_timeout( + _PINGING_MASTER_TIMEOUT_IN_MS, + cluster_def)) as sess: + devices = sess.list_devices() + break + except errors.DeadlineExceededError: + msg = ('Failed to connect to the Tensorflow master. The TPU worker may ' + 'not be ready (still scheduling) or the Tensorflow master ' + 'address is incorrect: got (%s).' % + (master_address)) + + # TODO(xiejw): For local or grpc master we might not need retry logic + # here. + if retry_count <= _RETRY_TIMES: + logging.warning('%s', msg) + logging.warning('Retrying (%d/%d).', retry_count, _RETRY_TIMES) + retry_count += 1 + else: + raise ValueError(msg) + + for device in devices: + spec = tf_device.DeviceSpec.from_string(device.name) + if spec.device_type == 'TPU': + device_dict[spec.task].append(spec.device_index) + tpu_core_count += 1 + + num_of_cores_per_host = 0 + if tpu_core_count: + num_cores_per_host_set = set( + [len(core_ids) for core_ids in device_dict.values()]) + if len(num_cores_per_host_set) != 1: + raise RuntimeError( + 'TPU cores on each host is not same. This should not happen!. ' + 'devices: {}'.format(devices)) + num_of_cores_per_host = num_cores_per_host_set.pop() + + topology = None + if query_topology: + if not tpu_core_count: + raise RuntimeError( + 'Cannot find any TPU cores in the system (master address {}). ' + 'This usually means the master address is incorrect or the ' + 'TPU worker has some problems. Available devices: {}'.format( + master_address, devices)) + + topology = _obtain_topology(master_address, cluster_def) + + # We sort the metadata devices so that downstream users get a sorted list + # for creating mirrored variables correctly. + def _sort_key(device): + spec = tf_device.DeviceSpec.from_string(device.name) + return (spec.job, spec.replica, spec.task, spec.device_type, + spec.device_index) + devices = tuple(sorted(devices, key=_sort_key)) + + metadata = TPUSystemMetadata( + num_cores=tpu_core_count, + num_hosts=len(device_dict), + num_of_cores_per_host=num_of_cores_per_host, + topology=topology, + devices=devices) + + if tpu_core_count: + logging.info('Found TPU system:') + logging.info('*** Num TPU Cores: %d', metadata.num_cores) + logging.info('*** Num TPU Workers: %d', metadata.num_hosts) + logging.info('*** Num TPU Cores Per Worker: %d', + metadata.num_of_cores_per_host) + for device in metadata.devices: + logging.info('*** Available Device: %s', device) + else: + logging.info('Failed to find TPU: %s', metadata) + return metadata + + +def _obtain_topology(master_address, cluster_def): + """Obtains TPU fabric topology.""" + try: + logging.info('Initializing TPU system (master: %s) to fetch topology ' + 'for model parallelism. This might take a while.', + master_address) + with ops.Graph().as_default(): + session_config = get_session_config_with_timeout( + _INITIAL_TPU_SYSTEM_TIMEOUT_IN_MS, cluster_def) + with session_lib.Session( + master_address, config=session_config) as sess: + topology = sess.run(tpu.initialize_system()) + return topology + except errors.DeadlineExceededError: + raise ValueError( + 'Fail to initialize TPU system with master (%s). ' + 'Please double check the TPU system is functional.' % ( + master_address)) + + +def get_session_config_with_timeout(timeout_in_secs, cluster_def): + """Returns a session given a timeout and a cluster configuration.""" + config_proto = config_pb2.ConfigProto( + operation_timeout_in_ms=timeout_in_secs, cluster_def=cluster_def) + return config_proto + + +def master_job(master, cluster_def): + """Returns the canonical job name to use to place TPU computations on. + + Args: + master: A `string` representing the TensorFlow master to use. + cluster_def: A ClusterDef object describing the TPU cluster. + + Returns: + A string containing the job name, or None if no job should be specified. + + Raises: + ValueError: If the user needs to specify a tpu_job_name, because we are + unable to infer the job name automatically, or if the user-specified job + names are inappropriate. + """ + # If the user specifies the tpu_job_name, use that. + + if master in _LOCAL_MASTERS: + return None + + if (not cluster_def or not cluster_def.job): + return _DEFAULT_JOB_NAME + job_names = set(job.name for job in cluster_def.job) + if _DEFAULT_JOB_NAME in job_names: + # b/37868888 tracks allowing ClusterSpec propagation to reuse job names. + raise ValueError('Currently, tpu_worker is not an allowed job name.') + if len(job_names) == 1: + return cluster_def.job[0].name + if len(job_names) == 2: + if _DEFAULT_COORDINATOR_JOB_NAME in job_names: + job_names.remove(_DEFAULT_COORDINATOR_JOB_NAME) + return job_names.pop() + # TODO(b/67716447): Include more sophisticated heuristics. + raise ValueError('Could not infer TPU job name.') diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/training_loop.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/training_loop.py new file mode 100644 index 0000000000000000000000000000000000000000..ea379e92b5740cdcd72f3d34a7f6f09d6e0c9c9a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/training_loop.py @@ -0,0 +1,229 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================= + +"""Library for constructing a training loop, suitable for TPUs.""" + +from typing import Any, Callable, Iterable, List, Optional, Union + +from tensorflow.python.compiler.xla import xla +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import while_loop as while_loop_tf +from tensorflow.python.tpu import tensor_tracer +from tensorflow.python.tpu import tpu_feed +from tensorflow.python.tpu import tpu_function +from tensorflow.python.types import core as core_types + + +def while_loop(condition: Callable[..., Any], + body: Callable[..., Any], + inputs: Optional[List[Any]] = None, + infeed_queue: Optional[tpu_feed.InfeedQueue] = None, + name: Any = None) -> Any: + """Builds a training loop for TPUs. + + The set of loop-carried tensors corresponds to `inputs`. Both + `condition` and `body` take the current value of the loop-carried + tensors. 'body' additionally takes a tuple of infeed from + infeed_queue if infeed_queue is not None. `condition` must return a + single boolean value that determines whether iteration + continues. `body` must return an updated list of values for the + loop-carried tensors. + + Args: + condition: a Python function that builds the loop condition. + body: a Python function that builds the loop body. + inputs: a list of initial values passed into the training loop, or None + (equivalent to an empty list). + infeed_queue: if not None, the infeed queue from which to append a tuple of + arguments as inputs to condition. + name: (Deprecated) Does nothing. + + Returns: + The final values of the loop-carried tensors. + + Raises: + TypeError: if body or condition has the wrong signature. + """ + del name + # Converts inputs to Tensors. + inputs = [] if inputs is None else [ops.convert_to_tensor(x) for + x in inputs] + input_types = [x.dtype for x in inputs] + input_arity = len(inputs) + + body_arg_error = xla.check_function_argument_count( + body, input_arity, infeed_queue) + if body_arg_error is not None: + if infeed_queue is None: + raise TypeError( + f"Supplied loop body function cannot be called with the specified " + f"inputs. You specified {input_arity} inputs: {[i.name for i in inputs]}, but the loop body needs {body_arg_error}" + ) + else: + raise TypeError( + f"Supplied loop body function cannot be called with the specified " + f"inputs. You specified {input_arity} inputs: {[i.name for i in inputs]} and {infeed_queue.number_of_tuple_elements} additional inputs from " + f"infeed, but the computation needs {body_arg_error}") + condition_arg_error = xla.check_function_argument_count( + condition, input_arity, None) + if condition_arg_error is not None: + if infeed_queue is None: + raise TypeError( + f"Supplied loop condition function cannot be called with the " + f"specified inputs. You specified {input_arity} inputs: {[i.name for i in inputs]}, but the loop " + f"condition needs {condition_arg_error}") + else: + raise TypeError( + f"Supplied loop condition function cannot be called with the " + f"specified inputs. You specified {input_arity} inputs: {[i.name for i in inputs]}, but the loop " + f"condition needs {condition_arg_error}. Note that infeed is not passed to the loop condition." + ) + + def condition_wrapper(*inputs): + # Discards the dummy output added for arity-0 loops. + if input_arity == 0: + inputs = [] + return condition(*inputs) + + def body_wrapper(*inputs): + """Wrapper around `body` that handles infeed queues and control deps.""" + inputs = list(inputs) + + # Discards the dummy output added for arity-0 loops. + if input_arity == 0: + inputs = [] + + # Runs `body` with the dequeue_ops appended. + if infeed_queue: + number_of_shards = tpu_function.get_tpu_context().number_of_shards + if number_of_shards is None: + raise ValueError("Can't build training loop with infeed when there is " + "no tpu_shard_context. Are you building a loop or " + "graph directly rather than from inside tpu.rewrite, " + "tpu.batch_parallel, tpu.shard, or tpu.replicate?") + infeed_queue.set_number_of_shards(number_of_shards) + dequeue_ops = [d for d in infeed_queue.generate_dequeue_op()] + else: + dequeue_ops = [] + outputs = body(*(inputs + dequeue_ops)) + + # If the computation only returned one value, make it a tuple. + if not isinstance(outputs, (list, tuple)): + outputs = (outputs,) + + outputs = [ + o if isinstance(o, ops.Operation) else ops.convert_to_tensor(o) + for o in outputs + ] + + # Separates the returned Operations and Tensors. + output_operations = [o for o in outputs if isinstance(o, ops.Operation)] + output_tensors = [o for o in outputs + if not isinstance(o, ops.Operation)] + + if outputs != output_tensors + output_operations: + raise ValueError( + "TPU training loop body must return zero or more Tensor values " + "followed by zero or more Operations.") + + output_types = [op.dtype for op in output_tensors] + if input_types != output_types: + raise TypeError( + "Mismatch between input types and output types for training loop " + "body: {} vs {}".format(input_types, output_types)) + + # Add the dequeue operations to output_operations to ensure they are run + # by the loop, even if the programmer's loop body does not use them. + output_operations += dequeue_ops + + # Add a dummy output, if needed. + if not output_tensors: + output_tensors = array_ops.constant(0) + + if output_operations: + # TODO(phawkins): in principle this is too restrictive since it serializes + # the training loop steps. In practice it does not matter since this loop + # will be compiled by XLA. + output_tensors = control_flow_ops.tuple(output_tensors, + control_inputs=output_operations) + + if tensor_tracer.TensorTracer.is_enabled(): + num_replicas = tpu_function.get_tpu_context().number_of_shards + if num_replicas is None: + num_replicas = 1 + tt = tensor_tracer.TensorTracer() + output_tensors = tt.trace_tpu(ops.get_default_graph(), + output_tensors, None, + num_replicas) + return output_tensors + + # If the body has arity 0, add a dummy loop-carried value to which we can add + # control dependencies from any side-effecting operations. + if input_arity == 0: + inputs = [array_ops.constant(0)] + return while_loop_tf.while_loop( + condition_wrapper, body_wrapper, inputs, name="", parallel_iterations=1) + + +def repeat( + n: int, + body: Callable[..., Union[core_types.TensorLike, Iterable]], # pylint:disable=g-bare-generic + inputs: Optional[List[core_types.TensorLike]] = None, + infeed_queue: Optional[tpu_feed.InfeedQueue] = None, + name: Any = None) -> List[core_types.TensorLike]: + """Builds a training loop that executes a fixed number of iterations. + + The set of loop-carried tensors correspond to `inputs`. + `body` must be a function that takes and returns the values of the + loop-carried tensors. + + Args: + n: the number of loop iterations + body: a Python function that builds the loop body. + inputs: a list of initial values passed into the training loop or None + (equivalent to an empty list). + infeed_queue: if not None, the infeed queue from which to append a tuple of + arguments as inputs to condition. + name: (Deprecated) Does nothing. + + Returns: + The final values of the loop-carried tensors. + Raises: + ValueError: if there is a type error. + """ + def _convert_to_list(xs): + if not isinstance(xs, (list, tuple)): + return [xs] + else: + return list(xs) + + def cond(i, *args): + del args + return i < n + + def body_wrapper(i, *args): + return [i + 1] + _convert_to_list(body(*args)) + + inputs = [0] if inputs is None else [0] + _convert_to_list(inputs) + outputs = while_loop( + cond, body_wrapper, inputs=inputs, infeed_queue=infeed_queue, name=name) + outputs = _convert_to_list(outputs) + if len(outputs) == 1: + # Returns the Op rather than an empty list. + return outputs[0].op + else: + return outputs[1:] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/util.py new file mode 100644 index 0000000000000000000000000000000000000000..c5b8964b20a6e290558a322edc04d8428dc56eca --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/util.py @@ -0,0 +1,19 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Stub file to maintain backwards compatibility.""" + +# pylint: disable=wildcard-import,unused-import +from tensorflow_estimator.python.estimator.tpu.util import * +# pylint: enable=wildcard-import,unused-import diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/asset.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/asset.py new file mode 100644 index 0000000000000000000000000000000000000000..85a6048804d49ae94bafff13d44bda630376c417 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/asset.py @@ -0,0 +1,116 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Asset-type Trackable object.""" +import os + +from tensorflow.python.eager import context +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_conversion_registry +from tensorflow.python.lib.io import file_io +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.saved_model import path_helpers +from tensorflow.python.trackable import base +from tensorflow.python.util.tf_export import tf_export + + +@tf_export("saved_model.Asset") +class Asset(base.Trackable): + """Represents a file asset to hermetically include in a SavedModel. + + A SavedModel can include arbitrary files, called assets, that are needed + for its use. For example a vocabulary file used initialize a lookup table. + + When a trackable object is exported via `tf.saved_model.save()`, all the + `Asset`s reachable from it are copied into the SavedModel assets directory. + Upon loading, the assets and the serialized functions that depend on them + will refer to the correct filepaths inside the SavedModel directory. + + Example: + + ``` + filename = tf.saved_model.Asset("file.txt") + + @tf.function(input_signature=[]) + def func(): + return tf.io.read_file(filename) + + trackable_obj = tf.train.Checkpoint() + trackable_obj.func = func + trackable_obj.filename = filename + tf.saved_model.save(trackable_obj, "/tmp/saved_model") + + # The created SavedModel is hermetic, it does not depend on + # the original file and can be moved to another path. + tf.io.gfile.remove("file.txt") + tf.io.gfile.rename("/tmp/saved_model", "/tmp/new_location") + + reloaded_obj = tf.saved_model.load("/tmp/new_location") + print(reloaded_obj.func()) + ``` + + Attributes: + asset_path: A path, or a 0-D `tf.string` tensor with path to the asset. + """ + + def __init__(self, path): + """Record the full path to the asset.""" + if isinstance(path, os.PathLike): + path = os.fspath(path) + # The init_scope prevents functions from capturing `path` in an + # initialization graph, since it is transient and should not end up in a + # serialized function body. + with ops.init_scope(), ops.device("CPU"): + self._path = ops.convert_to_tensor( + path, dtype=dtypes.string, name="asset_path") + + @property + def asset_path(self): + """Fetch the current asset path.""" + return self._path + + @classmethod + def _deserialize_from_proto(cls, object_proto, export_dir, asset_file_def, + **unused_kwargs): + proto = object_proto.asset + filename = file_io.join( + path_helpers.get_assets_dir(export_dir), + asset_file_def[proto.asset_file_def_index].filename) + asset = cls(filename) + if not context.executing_eagerly(): + ops.add_to_collection(ops.GraphKeys.ASSET_FILEPATHS, asset.asset_path) + return asset + + def _add_trackable_child(self, name, value): + setattr(self, name, value) + + def _export_to_saved_model_graph(self, tensor_map, **unused_kwargs): + # TODO(b/205008097): Instead of mapping 1-1 between trackable asset + # and asset in the graph def consider deduping the assets that + # point to the same file. + asset_path_initializer = array_ops.placeholder( + shape=self.asset_path.shape, + dtype=dtypes.string, + name="asset_path_initializer") + asset_variable = resource_variable_ops.ResourceVariable( + asset_path_initializer) + + tensor_map[self.asset_path] = asset_variable + return [self.asset_path] + + +tensor_conversion_registry.register_tensor_conversion_function( + Asset, lambda asset, **kw: ops.convert_to_tensor(asset.asset_path, **kw)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/autotrackable.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/autotrackable.py new file mode 100644 index 0000000000000000000000000000000000000000..2a0a20535ebf802a74a9e1427a996931485ea543 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/autotrackable.py @@ -0,0 +1,152 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Dependency tracking for trackable objects.""" + +import warnings + +from absl import logging + +from tensorflow.python.eager import def_function +from tensorflow.python.eager import function as defun +from tensorflow.python.trackable import base +from tensorflow.python.trackable import data_structures +from tensorflow.python.types import core as core_types +from tensorflow.python.util.tf_export import tf_export + + +@tf_export("__internal__.tracking.AutoTrackable", v1=[]) +class AutoTrackable(base.Trackable): + """Manages dependencies on other objects. + + `Trackable` objects may have dependencies: other `Trackable` objects + which should be saved if the object declaring the dependency is saved. A + correctly saveable program has a dependency graph such that if changing a + global variable affects an object (e.g. changes the behavior of any of its + methods) then there is a chain of dependencies from the influenced object to + the variable. + + Dependency edges have names, and are created implicitly when a + `Trackable` object is assigned to an attribute of another + `Trackable` object. For example: + + ``` + obj = Trackable() + obj.v = ResourceVariable(0.) + ``` + + The `Trackable` object `obj` now has a dependency named "v" on a + variable. + + `Trackable` objects may specify `Tensor`s to be saved and restored + directly (e.g. a `Variable` indicating how to save itself) rather than through + dependencies on other objects. See + `Trackable._gather_saveables_for_checkpoint` for details. + """ + + def __setattr__(self, name, value): + """Support self.foo = trackable syntax.""" + try: + if getattr(self, name) is value: + # Short circuit for `self.$x = self.$x`. + return + except AttributeError: + pass + + if getattr(self, "_self_setattr_tracking", True): + value = data_structures.sticky_attribute_assignment( + trackable=self, value=value, name=name) + super(AutoTrackable, self).__setattr__(name, value) + + def __delattr__(self, name): + self._delete_tracking(name) + super(AutoTrackable, self).__delattr__(name) + + def _no_dependency(self, value): + """Override to allow TrackableBase to disable dependency tracking.""" + return data_structures.NoDependency(value) + + def _trackable_children(self, save_type=base.SaveType.CHECKPOINT, **kwargs): + """Returns all children of a trackable, including functions.""" + if save_type != base.SaveType.SAVEDMODEL: + return super(AutoTrackable, self)._trackable_children( + save_type, **kwargs) + + functions = {} + try: + # We get the attributes, suppressing warnings and exceptions. + logging_verbosity = logging.get_verbosity() + logging.set_verbosity(logging.FATAL) + for attribute_name in dir(self): + try: + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + attribute_value = getattr(self, attribute_name, None) + except Exception: # pylint: disable=broad-except + # NOTE: If we make the exception catching here less broad, we might + # need to revisit `finally` block below. + # We really don't want to throw an exception just because some + # object's attribute accessor is broken. + attribute_value = None + if isinstance(attribute_value, (def_function.Function, + defun.ConcreteFunction)): + functions[attribute_name] = attribute_value + finally: + logging.set_verbosity(logging_verbosity) + + # Trace concrete functions to force side-effects: + # 1. populate the cache for functions that have an input_signature + # and have not been called + # 2. force side effects of creation of concrete functions, e.g. create + # variables on first run. + for fn in functions.values(): + if isinstance(fn, def_function.Function): + fn._list_all_concrete_functions_for_serialization() # pylint: disable=protected-access + + # Additional dependencies may have been generated during function tracing + # (e.g. captured variables). Make sure we return those too. + children = {} + for name, child in self._checkpoint_dependencies: + if isinstance(child, (core_types.PolymorphicFunction, + core_types.ConcreteFunction)): + # Skip "tracked" functions for now since there may be objects that + # automatically track functions that should not be saved. + # TODO(kathywu): remove once `_list_functions_for_serialization` has + # been fully deprecated. + continue + + if name in functions and child is not functions[name]: + raise ValueError( + "Can't save object because it has multiple children with the same " + f"name. Object: {self}, attribute name: {name}, child 1: " + f"{child}, child 2: {functions[name]}") + + children[name] = child + + children.update(functions) + return children + + def _delete_tracking(self, name): + """Removes the tracking of name.""" + self._maybe_initialize_trackable() + if name in self._unconditional_dependency_names: + del self._unconditional_dependency_names[name] + for index, (dep_name, _) in enumerate( + self._unconditional_checkpoint_dependencies): + if dep_name == name: + del self._unconditional_checkpoint_dependencies[index] + break + + def _add_trackable_child(self, name, value): + self.__setattr__(name, value) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/base.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/base.py new file mode 100644 index 0000000000000000000000000000000000000000..014cbfe1c64a9f653d983c0d4181fb1173840d3d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/base.py @@ -0,0 +1,1077 @@ +"""An object-local variable management scheme.""" +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +import collections +import weakref + +from tensorflow.python.eager import context +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.ops import gen_control_flow_ops +from tensorflow.python.trackable import constants +from tensorflow.python.training.saving import saveable_object +from tensorflow.python.util import tf_contextlib +from tensorflow.python.util import tf_decorator +from tensorflow.python.util.tf_export import tf_export + +OBJECT_GRAPH_PROTO_KEY = constants.OBJECT_GRAPH_PROTO_KEY +VARIABLE_VALUE_KEY = constants.VARIABLE_VALUE_KEY +OBJECT_CONFIG_JSON_KEY = constants.OBJECT_CONFIG_JSON_KEY +SaveType = constants.SaveType + + +@tf_export("__internal__.tracking.TrackableReference", v1=[]) +class TrackableReference(object): + """A named reference to a trackable object for use with the `Trackable` class. + + These references mark named `Trackable` dependencies of a `Trackable` object + and should be created when overriding `Trackable._checkpoint_dependencies`. + + Attributes: + name: The local name for this dependency. + ref: The `Trackable` object being referenced. + """ + + __slots__ = ("_name", "_ref") + + def __init__(self, name, ref): + self._name = name + self._ref = ref + + @property + def name(self): + return self._name + + @property + def ref(self): + return self._ref + + def __iter__(self): + yield self.name + yield self.ref + + def __repr__(self): + return f"{self.__class__.__name__}(name={self.name}, ref={self.ref})" + + def __eq__(self, o): + if isinstance(o, tuple): + return (self.name, self.ref) == o + elif isinstance(o, TrackableReference): + return self.name == o.name and self.ref == o.ref + else: + return False + + +class WeakTrackableReference(TrackableReference): + """TrackableReference that stores weak references.""" + __slots__ = () + + def __init__(self, name, ref): + if not isinstance(self, weakref.ref): + ref = weakref.ref(ref) + super(WeakTrackableReference, self).__init__(name=name, ref=ref) + + @property + def ref(self): + return self._ref() + + +# TODO(bfontain): Update once sharded initialization interface is finalized. +ShardInfo = collections.namedtuple("CheckpointInitialValueShardInfo", + ["shape", "offset"]) + + +@tf_export("__internal__.tracking.CheckpointInitialValueCallable", v1=[]) +class CheckpointInitialValueCallable(object): + """A callable object that returns a CheckpointInitialValue. + + See CheckpointInitialValue for more information. + """ + + def __init__(self, checkpoint_position): + self._checkpoint_position = checkpoint_position + + @property + def checkpoint_position(self): + return self._checkpoint_position + + def __call__(self, shape=None, dtype=None, shard_info=None): + # Note that the signature here is for compatibility with normal callable + # initializers which take shape and dtype. Although dtype isn't used, it + # will get passed in by a functool.partial_wrapper in places like + # base_layer_utils.py's make_variable. + return CheckpointInitialValue( + self._checkpoint_position, shape, shard_info=shard_info) + + @property + def restore_uid(self): + return self._checkpoint_position.restore_uid + + +@tf_export("__internal__.tracking.CheckpointInitialValue", v1=[]) +class CheckpointInitialValue(object): + """Tensor wrapper for managing update UIDs in `Variables`. + + When supplied as an initial value, objects of this type let a `Variable` + (`Variable`, `ResourceVariable`, etc.) know the UID of the restore the initial + value came from. This allows deferred restorations to be sequenced in the + order the user specified them, and lets us fall back on assignment if an + initial value is not set (e.g. due to a custom getter interfering). + + See comments in _add_variable_with_custom_getter for more information about + how `CheckpointInitialValue` is used. + """ + + def __init__(self, checkpoint_position, shape=None, shard_info=None): + if shard_info: + full_shape_str = " ".join("%d" % d for d in shape) + " " + slice_spec = ":".join( + "%d,%d" % (o, s) for o, s in zip(shard_info.offset, shard_info.shape)) + shape_and_slice = full_shape_str + slice_spec + else: + shape_and_slice = "" + self.wrapped_value = checkpoint_position.value_tensors( + {VARIABLE_VALUE_KEY: shape_and_slice})[VARIABLE_VALUE_KEY] + self._checkpoint_position = checkpoint_position + + def __tf_tensor__(self, dtype=None, name=None): + del dtype + del name + return self.wrapped_value + + @property + def checkpoint_position(self): + return self._checkpoint_position + + +class NoRestoreSaveable(saveable_object.SaveableObject): + """Embeds a tensor in a checkpoint with no restore ops.""" + + def __init__(self, tensor, name, dtype=None, device=None): + spec = saveable_object.SaveSpec( + tensor, "", name, dtype=dtype, device=device) + super(NoRestoreSaveable, self).__init__(tensor, [spec], name) + + def restore(self, restored_tensors, restored_shapes): + return gen_control_flow_ops.no_op() + + +_SlotVariableRestoration = collections.namedtuple( + "_SlotVariableRestoration", + [ + # The checkpoint proto id of the optimizer object. + "optimizer_id", + # The checkpoint proto id of the slot variable. + "slot_variable_id", + "slot_name", + ]) + + +@tf_export("__internal__.tracking.no_automatic_dependency_tracking", v1=[]) +def no_automatic_dependency_tracking(method): + """Disables automatic dependency tracking on attribute assignment. + + Use to decorate any method of a Trackable object. Attribute assignment in + that method will not add dependencies (also respected in Model). Harmless if + used in a class which does not do automatic dependency tracking (which means + it's safe to use in base classes which may have subclasses which also inherit + from Trackable). + + Args: + method: The method to decorate. + + Returns: + A decorated method which sets and un-sets automatic dependency tracking for + the object the method is called on (not thread safe). + """ + + def _method_wrapper(self, *args, **kwargs): + previous_value = getattr(self, "_self_setattr_tracking", True) + self._self_setattr_tracking = False # pylint: disable=protected-access + try: + result = method(self, *args, **kwargs) + finally: + self._self_setattr_tracking = previous_value # pylint: disable=protected-access + return result + + return tf_decorator.make_decorator( + target=method, decorator_func=_method_wrapper) + + +@tf_contextlib.contextmanager +def no_manual_dependency_tracking_scope(obj): + """A context that disables manual dependency tracking for the given `obj`. + + Sometimes library methods might track objects on their own and we might want + to disable that and do the tracking on our own. One can then use this context + manager to disable the tracking the library method does and do your own + tracking. + + For example: + + class TestLayer(tf.keras.Layer): + def build(): + with no_manual_dependency_tracking_scope(self): + var = self.add_variable("name1") # Creates a var and doesn't track it + self._track_trackable("name2", var) # We track variable with name `name2` + + Args: + obj: A trackable object. + + Yields: + a scope in which the object doesn't track dependencies manually. + """ + # pylint: disable=protected-access + previous_value = getattr(obj, "_manual_tracking", True) + obj._manual_tracking = False + try: + yield + finally: + obj._manual_tracking = previous_value + + +@tf_contextlib.contextmanager +def no_automatic_dependency_tracking_scope(obj): + """A context that disables automatic dependency tracking when assigning attrs. + + Objects that inherit from Autotrackable automatically creates dependencies + to trackable objects through attribute assignments, and wraps data structures + (lists or dicts) with trackable classes. This scope may be used to temporarily + disable this behavior. This works similar to the decorator + `no_automatic_dependency_tracking`. + + Example usage: + ``` + model = tf.keras.Model() + model.arr1 = [] # Creates a ListWrapper object + with no_automatic_dependency_tracking_scope(model): + model.arr2 = [] # Creates a regular, untracked python list + ``` + + Args: + obj: A trackable object. + + Yields: + a scope in which the object doesn't track dependencies. + """ + previous_value = getattr(obj, "_setattr_tracking", True) + obj._setattr_tracking = False # pylint: disable=protected-access + try: + yield + finally: + obj._setattr_tracking = previous_value # pylint: disable=protected-access + + +@tf_export("__internal__.tracking.Trackable", v1=[]) +class Trackable(object): + """Base class for `Trackable` objects without automatic dependencies. + + This class has no __setattr__ override for performance reasons. Dependencies + must be added explicitly. Unless attribute assignment is performance-critical, + use `AutoTrackable` instead. Use `Trackable` for `isinstance` + checks. + """ + + # For compatibility with wrapt.ObjectProxy, attributes are all prefixed with + # _self_. We have some properties to forward semi-public attributes to their + # _self_ equivalents. + + @property + def _setattr_tracking(self): + if not hasattr(self, "_self_setattr_tracking"): + self._self_setattr_tracking = True + return self._self_setattr_tracking + + @_setattr_tracking.setter + def _setattr_tracking(self, value): + self._self_setattr_tracking = value + + @property + def _update_uid(self): + return self._self_update_uid + + @_update_uid.setter + def _update_uid(self, value): + self._self_update_uid = value + + @property + def _unconditional_checkpoint_dependencies(self): + return self._self_unconditional_checkpoint_dependencies + + @property + def _unconditional_dependency_names(self): + return self._self_unconditional_dependency_names + + @property + def _name_based_restores(self): + return self._self_name_based_restores + + # Trackable does not do automatic dependency tracking, but uses the + # no_automatic_dependency_tracking decorator so it can avoid adding + # dependencies if a subclass is Trackable / inherits from Model (both of + # which have __setattr__ overrides). + @no_automatic_dependency_tracking + def _maybe_initialize_trackable(self): + """Initialize dependency management. + + Not __init__, since most objects will forget to call it. + """ + if hasattr(self, "_self_unconditional_checkpoint_dependencies"): + # __init__ already called. This check means that we don't need + # Trackable.__init__() in the constructor of every TensorFlow object. + return + # A list of TrackableReference objects. Some classes implementing + # `Trackable`, notably `Optimizer`s, may override the + # _checkpoint_dependencies property with conditional dependencies + # (e.g. based on the current graph when saving). + self._self_unconditional_checkpoint_dependencies = [] + # Maps names -> Trackable objects + self._self_unconditional_dependency_names = {} + # Restorations for other Trackable objects on which this object may + # eventually depend. Maps local name -> CheckpointPosition list. Optimizers + # tack on conditional dependencies, and so need separate management of + # deferred dependencies too. + self._self_unconditional_deferred_dependencies = {} + # The UID of the highest assignment to this object. Used to ensure that the + # last requested assignment determines the final value of an object. + if hasattr(self, "_self_update_uid"): + raise AssertionError( + "Internal error: the object had an update UID set before its " + "initialization code was run.") + self._self_update_uid = -1 + # When executing eagerly, holds a collection of _NameBasedRestoreCoordinator + # instances, which should be checked when creating variables or other + # saveables. These are passed on recursively to all dependencies, since + # unlike object-based checkpoint restores we don't know which subgraph is + # being restored in advance. This mechanism is only necessary for + # restore-on-create when executing eagerly, and so is unused when graph + # building. + self._self_name_based_restores = set() + + # Dictionary of SaveableObjects factories. This dictionary is defined when + # the object is loaded from the SavedModel. When writing a custom class, + # prefer overriding "_gather_saveables_from_checkpoint" to using this + # attribute. + self._self_saveable_object_factories = {} + + @property + def _object_identifier(self): + """String used to identify this object in a SavedModel. + + THIS FIELD HAS BEEN DEPRECATED IN FAVOR OF THE NAME REGISTERED WITH + `register_serializable`. + + Generally, the object identifier is constant across objects of the same + class, while the metadata field is used for instance-specific data. + + Returns: + String object identifier. + """ + return "_generic_user_object" + + def _no_dependency(self, value): + """If automatic dependency tracking is enabled, ignores `value`.""" + return value + + def _name_based_attribute_restore(self, checkpoint): + """Restore the object's attributes from a name-based checkpoint.""" + self._self_name_based_restores.add(checkpoint) + if self._self_update_uid < checkpoint.restore_uid: + checkpoint.eager_restore(self) + self._self_update_uid = checkpoint.restore_uid + + @property + def _checkpoint_dependencies(self): + """All dependencies of this object. + + May be overridden to include conditional dependencies. + + Returns: + A list of `TrackableReference` objects indicating named + `Trackable` dependencies which should be saved along with this + object. + """ + return self._self_unconditional_checkpoint_dependencies + + @property + def _deferred_dependencies(self): + """A dictionary with deferred dependencies. + + Stores restorations for other Trackable objects on which this object + may eventually depend. May be overridden by sub-classes (e.g. Optimizers use + conditional dependencies based the current graph, and so need separate + management of deferred dependencies too). + + Returns: + A dictionary mapping from local name to a list of CheckpointPosition + objects. + """ + return self._self_unconditional_deferred_dependencies + + def _lookup_dependency(self, name, cached_dependencies=None): + """Look up a dependency by name. + + May be overridden to include conditional dependencies. + + Args: + name: The local name of the dependency. + cached_dependencies: Optional dict containing all computed dependencies + returned by `self._trackable_children()`. + + Returns: + A `Trackable` object, or `None` if no dependency by this name was + found. + """ + if cached_dependencies: + return cached_dependencies.get(name) + return self._self_unconditional_dependency_names.get(name) + + def _add_variable_with_custom_getter(self, + name, + shape=None, + dtype=dtypes.float32, + initializer=None, + getter=None, + overwrite=False, + **kwargs_for_getter): + """Restore-on-create for a variable be saved with this `Trackable`. + + If the user has requested that this object or another `Trackable` which + depends on this object be restored from a checkpoint (deferred loading + before variable object creation), `initializer` may be ignored and the value + from the checkpoint used instead. + + Args: + name: A name for the variable. Must be unique within this object. + shape: The shape of the variable. + dtype: The data type of the variable. + initializer: The initializer to use. Ignored if there is a deferred + restoration stored in the Trackable. + getter: The getter to wrap which actually fetches the variable. + overwrite: If True, disables unique name and type checks. + **kwargs_for_getter: Passed to the getter. + + Returns: + The new variable object. + + Raises: + ValueError: If the variable name is not unique. + """ + self._maybe_initialize_trackable() + with ops.init_scope(): + if context.executing_eagerly(): + # If this is a variable with a single Tensor stored in the checkpoint, + # we can set that value as an initializer rather than initializing and + # then assigning (when executing eagerly). This call returns None if + # there is nothing to restore. + checkpoint_initializer = self._preload_simple_restoration(name=name) + else: + checkpoint_initializer = None + if (checkpoint_initializer is not None and + not (isinstance(initializer, CheckpointInitialValueCallable) and + (initializer.restore_uid > checkpoint_initializer.restore_uid))): + # If multiple Trackable objects are "creating" the same variable + # via the magic of custom getters, the one with the highest restore UID + # (the one called last) has to make the final initializer. If another + # custom getter interrupts this process by overwriting the initializer, + # then we'll catch that when we call _track_trackable. So this is + # "best effort" to set the initializer with the highest restore UID. + initializer = checkpoint_initializer + new_variable = getter( + name=name, + shape=shape, + dtype=dtype, + initializer=initializer, + **kwargs_for_getter) + + # If we set an initializer and the variable processed it, tracking will not + # assign again. It will add this variable to our dependencies, and if there + # is a non-trivial restoration queued, it will handle that. This also + # handles slot variables. + if not overwrite or isinstance(new_variable, Trackable): + return self._track_trackable(new_variable, name=name, overwrite=overwrite) + else: + # TODO(allenl): Some variable types are not yet supported. Remove this + # fallback once all get_variable() return types are Trackable. + return new_variable + + def _preload_simple_restoration(self, name): + """Return a dependency's value for restore-on-create. + + Note the restoration is not deleted; if for some reason preload is called + and then not assigned to the variable (for example because a custom getter + overrides the initializer), the assignment will still happen once the + variable is tracked (determined based on checkpoint.restore_uid). + + Args: + name: The object-local name of the dependency holding the variable's + value. + + Returns: + An callable for use as a variable's initializer/initial_value, or None if + one should not be set (either because there was no variable with this name + in the checkpoint or because it needs more complex deserialization). Any + non-trivial deserialization will happen when the variable object is + tracked. + """ + deferred_dependencies_list = self._deferred_dependencies.get(name, ()) + if not deferred_dependencies_list: + # Nothing to do; we don't have a restore for this dependency queued up. + return + for checkpoint_position in deferred_dependencies_list: + if not checkpoint_position.is_simple_variable(): + # If _any_ pending restoration is too complicated to fit in an + # initializer (because it has dependencies, or because there are + # multiple Tensors to restore), bail and let the general tracking code + # handle it. + return None + checkpoint_position = max( + deferred_dependencies_list, + key=lambda restore: restore.checkpoint.restore_uid) + return CheckpointInitialValueCallable( + checkpoint_position=checkpoint_position) + + def _track_trackable(self, trackable, name, overwrite=False): + """Declare a dependency on another `Trackable` object. + + Indicates that checkpoints for this object should include variables from + `trackable`. + + Variables in a checkpoint are mapped to `Trackable`s based on the names + provided when the checkpoint was written. To avoid breaking existing + checkpoints when modifying a class, neither variable names nor dependency + names (the names passed to `_track_trackable`) may change. + + Args: + trackable: A `Trackable` which this object depends on. + name: A local name for `trackable`, used for loading checkpoints into the + correct objects. + overwrite: Boolean, whether silently replacing dependencies is OK. Used + for __setattr__, where throwing an error on attribute reassignment would + be inappropriate. + + Returns: + `trackable`, for convenience when declaring a dependency and + assigning to a member variable in one statement. + + Raises: + TypeError: If `trackable` does not inherit from `Trackable`. + ValueError: If another object is already tracked by this name. + """ + self._maybe_initialize_trackable() + if not isinstance(trackable, Trackable): + raise TypeError( + "Trackable._track_trackable() can only be used to track objects of " + f"type Trackable. Got type {type(trackable)}.") + if not getattr(self, "_manual_tracking", True): + return trackable + new_reference = TrackableReference(name=name, ref=trackable) + current_object = self._lookup_dependency(name) + if (current_object is not None and current_object is not trackable): + if not overwrite: + raise ValueError( + f"Called Trackable._track_trackable() with name='{name}', " + "but a Trackable with this name is already declared as a " + "dependency. Names must be unique (or overwrite=True).") + # This is a weird thing to do, but we're not going to stop people from + # using __setattr__. + for index, (old_name, _) in enumerate( + self._self_unconditional_checkpoint_dependencies): + if name == old_name: + self._self_unconditional_checkpoint_dependencies[ + index] = new_reference + elif current_object is None: + self._self_unconditional_checkpoint_dependencies.append(new_reference) + self._handle_deferred_dependencies(name=name, trackable=trackable) + self._self_unconditional_dependency_names[name] = trackable + return trackable + + def _handle_deferred_dependencies(self, name, trackable): + """Pop and load any deferred checkpoint restores into `trackable`. + + This method does not add a new dependency on `trackable`, but it does + check if any outstanding/deferred dependencies have been queued waiting for + this dependency to be added (matched based on `name`). If so, + `trackable` and its dependencies are restored. The restorations are + considered fulfilled and so are deleted. + + `_track_trackable` is more appropriate for adding a + normal/unconditional dependency, and includes handling for deferred + restorations. This method allows objects such as `Optimizer` to use the same + restoration logic while managing conditional dependencies themselves, by + overriding `_checkpoint_dependencies` and `_lookup_dependency` to change the + object's dependencies based on the context it is saved/restored in (a single + optimizer instance can have state associated with multiple graphs). + + Args: + name: The name of the dependency within this object (`self`), used to + match `trackable` with values saved in a checkpoint. + trackable: The Trackable object to restore (inheriting from `Trackable`). + """ + self._maybe_initialize_trackable() + trackable._maybe_initialize_trackable() # pylint: disable=protected-access + deferred_dependencies_list = self._deferred_dependencies.pop(name, ()) + for checkpoint_position in sorted( + deferred_dependencies_list, + key=lambda restore: restore.checkpoint.restore_uid, + reverse=True): + checkpoint_position.restore(trackable) + + # Pass on any name-based restores queued in this object. + for name_based_restore in sorted( + self._self_name_based_restores, + key=lambda checkpoint: checkpoint.restore_uid, + reverse=True): + trackable._name_based_attribute_restore(name_based_restore) # pylint: disable=protected-access + + def _gather_saveables_for_checkpoint(self): + """Returns a dictionary of values to checkpoint with this object. + + NOTE: This method is deprecated, prefer implementing `_serialize_to_tensors` + and `_restore_from_tensors` instead. This method is only used in the + deprecated `tf.compat.v1.train.Saver`. + + Keys in the returned dictionary are local to this object and in a separate + namespace from dependencies. Values may either be `SaveableObject` factories + or variables easily converted to `SaveableObject`s (as in + `tf.compat.v1.train.Saver`'s + `var_list` constructor argument). + + `SaveableObjects` have a name set, which Trackable needs to generate + itself. So rather than returning `SaveableObjects` directly, this method + should return a dictionary of callables which take `name` arguments and + return `SaveableObjects` with that name. + + If this object may also be passed to the global-name-based + `tf.compat.v1.train.Saver`, + the returned callables should have a default value for their name argument + (i.e. be callable with no arguments). + + Returned values must be saved only by this object; if any value may be + shared, it should instead be a dependency. For example, variable objects + save their own values with the key `VARIABLE_VALUE_KEY`, but objects which + reference variables simply add a dependency. + + **AsyncCheckpoint Support** + If your Trackable implements `_gather_saveables_for_checkpoint`, + `_copy_trackable_to_cpu` needs to be implemented as well to support + asynchronous checkpoint. + + Returns: + The dictionary mapping attribute names to `SaveableObject` factories + described above. For example: + {VARIABLE_VALUE_KEY: + lambda name="global_name_for_this_object": + SaveableObject(name=name, ...)} + """ + return getattr(self, "_self_saveable_object_factories", {}) + + def _serialize_to_tensors(self): + """Gathers tensors to save to the checkpoint. + + You should only override `_serialize_to_tensors` and `_restore_from_tensors` + if you are defining a custom resource or variable with custom ops. + + Otherwise, please store the state of your trackable in `tf.Variable` objects + and add them to Trackable object hierarchy using `setattr` (for subclasses + of `AutoTrackable`) or overriding the `_trackable_children` method. + + For an example of a valid implementation of these two methods, please see + `DenseHashTable`. + + **Invalid implementation** + + ```` + class NamedTrackable(Trackable): + def __init__(self, name: str): + self.name = name + def _serialize_to_tensors(self): + return {"name": self.name} + def _restore_from_tensors(self, restored_tensors): + self.name = restored_tensors["name"] + ``` + + In this example, `NamedTrackable` can be saved and restored from + checkpoints, but is incompatible with SavedModel, which tries to convert + the serialize/restore functions into tf.functions. This fails because + attribute assignment (`self.attr = new_value`) is not graph-friendly. + + **Suggested fix** + + ``` + class NamedTrackable(Trackable): + def __init__(self, name: str): + self.name = tf.Variable(name) + + def _trackable_children(self): + return {"name": self.name} + ``` + + If the `name` attribute should be saved to the checkpoint, then convert it + a `tf.Variable`. + + **TF1 Saver Compatibility** + If your Trackable needs to be comatible with `tf.compat.v1.train.Saver`, + implement `_gather_saveables_from_checkpoint`. + + **AsyncCheckpoint Support** + If your Trackable implements `_serialize_to_tensors`, + `_copy_trackable_to_cpu` needs to be implemented as well to support + asynchronous checkpoint. + + Returns: + A dictionary mapping names to tensors. + """ + raise NotImplementedError + + def _restore_from_tensors(self, restored_tensors): + """Restores checkpointed values to this `Trackable`. + + Please see the documentation for `Trackable._serialize_to_tensors`. + + Args: + restored_tensors: A dictionary mapping names to tensors. The keys to this + dictionary matches the names passed to _serialize_to_tensors. + + Returns: + An op that runs the restoration. + """ + raise NotImplementedError + + def _serialize_to_proto(self, object_proto=None, **kwargs): + """Returns a proto of any type to be saved into the SavedModel. + + Trackable classes decorated with `register_serializable` should overwrite + this method to save metadata for this object to the SavedModel. The proto + returned by this function will be passed to `_deserialize_from_proto` in the + form of a `google.protobuf.Any` proto. + + This data is only saved and used by the Python API. Existing C++ loading + APIs such as `tensorflow::LoadSavedModel` will not read this field at all. + + Args: + object_proto: A `SavedObject` proto that may be filled by this function. + Only the core serializable types (Variable, Function, Constant, Asset) + should modify this argument. + **kwargs: Future keyword arguments passed to the object during saving. + + Returns: + A proto that serializes this class's type. + """ + del object_proto, kwargs # Unused. + + return None + + @classmethod + def _deserialize_from_proto(cls, + proto=None, + dependencies=None, + object_proto=None, + export_dir=None, + asset_file_def=None, + operation_attributes=None, + **kwargs): + """Returns a new object restored by the SavedModel. + + Trackable classes decorated with `register_serializable` should overwrite + this method to change how the object is loaded from SavedModel. By default, + the object is initialized with no arguments. + + Example: + + ``` + def _serialize_to_proto(self, **unused_kwargs): + return Message(name="a") + + @classmethod + def _deserialize_from_proto(cls, proto, **unused_kwargs): + if proto.Is(Message.DESCRIPTOR): + unpacked = Message() + proto.Unpack(unpacked) + return cls(unpacked.name) + else: + return cls() + ``` + + This function is only used by the Python API. C++ and TensorFlow Serving do + not have access to your registered class and cannot execute any of the + non-tf.functions attached to the Python class. However, all signatures and + tf.functions are still accessible. + + **Avoid creating duplicate trackables** + + SavedModel is saved by recursively gathering all of the trackables and their + children. SavedModel loading reverses those steps by creating all + trackables, then reconnecting the children trackables to their parents using + `Trackable._add_trackable_child`. + + That means that if `_deserialize_from_proto` calls the `__init__` function, + which creates all of the children trackables, then those children end up + being created *twice*. + + To avoid this, structure your code so that Trackables are not created + when deserialized from SavedModel: + + ``` + @register_serializable() + class Serializable(trackable): + def __init __(self, from_proto=False): + create_non_trackable_objects() + if not from_proto: + create_variables_and_other_trackables() + + def _deserialize_from_proto(cls, **kwargs): + return cls(from_proto=True) + + def _add_trackable_child(self, name, value): + self.__setattr__(name, value) + ``` + + Args: + proto: A `google.protobuf.Any` proto read from the `SavedModel`. + dependencies: A dictionary mapping names to dependencies (see + `_deserialization_dependencies`) + object_proto: The `SavedObject` proto for this object. + export_dir: The `SavedModel` directory + asset_file_def: The `MetaGraphDef`'s `asset_file_def` field. + operation_attributes: Dictionary mapping nodes to attribute from the + imported `GraphDef`. + **kwargs: Future keyword arguments passed to the object when loading. + + Returns: + A new object. + """ + del (proto, dependencies, object_proto, export_dir, asset_file_def, + operation_attributes, kwargs) + + return cls() + + def _add_trackable_child(self, name, value): + """Restores a connection between trackables when loading from SavedModel. + + SavedModel stores both the object metadata and its list of children. When + loading, this function is used along with `_deserialize_from_proto` to load + objects from the SavedModel: First, all saved objects are created with + `_deserialize_from_proto`. After that is complete, the children are + connected using `_add_trackable_child`. + + **Example** + + `tf.Module`, `tf.keras.Model` and Keras layers use `__setattr__` to track + children. This is why users can call `model.v = tf.Variable(...)`, and the + variable will be automatically saved to the checkpoint. The implementation + of this method for the listed objects is: + + ``` + def _add_trackable_child(self, name, value): + self.__setattr__(name, value) + ``` + + Args: + name: The name of the connection between the parent and child `Trackable`. + value: The child `Trackable` object. + """ + self._track_trackable(value, name, overwrite=True) + + def _deserialization_dependencies(self, children): + """Returns a dictionary containing `Trackables` that this object depends on. + + Dependencies define the order to serialize and deserialize objects in the + SavedModel. For example: + + class A(Trackable): + b = B() + def _deserialization_dependencies(self, children): + return {'b': self.b} + + class B(Trackable): + pass + + We say that object `a=A()` depends on `a.b`. + + Dependencies are guaranteed to be serialized and deserialized before the + object depending on them. The following methods use dependencies: + - `_deserialize_from_proto` [loading] + + SavedModel loads with the bottom-up approach, by first creating all objects + in the order defined by the dependencies, then connecting the children. + + Unlike `_trackable_children`, this function does not define the + `SavedObjectGraph`. It only changes the order in which things are + saved/loaded. Therefore, if there are dependencies that are not in the + `SavedObjectGraph`, saving will fail. + + Args: + children: Dict returned from `_trackable_children`. + + Returns: + A dictionary mapping names to `Trackable`. + """ + del children # Unused. + return {} + + def _trackable_children(self, + save_type=SaveType.CHECKPOINT, + cache=None, + **kwargs): + """Returns this object's `Trackable` attributes. + + This method is used to build the object graph (or the object hierarchy, + in pickling terms) for checkpoint save/restore, and `SavedModel` export. + + Override this method to define the children of this instance. Please read + the implementation restrictions: + + **Rule 1: All children must be convertable to `Trackable`.** + + Must pass `isinstance` check or `converter.convert_to_trackable`. + + **Rule 2: [Checkpoint-only] Do not create new objects.** + + When saving to a `SavedModel`, this method is called *exactly once* for each + `Trackable` in the object graph. When saving or restoring from a checkpoint, + this method may be called *multiple times*. Thus, this method may create + new Trackables when `save_type == SaveType.SAVEDMODEL` but not when + `save_type == SaveType.CHECKPOINT`. + + When saving to `SavedModel`, new `Trackable` children can be created to save + non-Trackable attributes to the `SavedModel`. In the example below, `hyper` + is a regular python float hyperparameter. To save this value, a new Variable + is created to store the value of `hyper`: + + ``` + def __init__(self): + self.hyper = 1e-5 + + def _trackable_children(self, save_type, **unused_kwargs): + # Correct implementation + children = {} + if format == 'saved_model': + children['hyper'] = tf.Variable(self.hyper) + return children + ``` + + An incorrect implementation of `_trackable_children` is shown below. This + function would cause failures when loading the checkpoint, and calling + `load_status.assert_consumed()` or + `load_status.assert_existing_objects_matched`. If you want a value to be + saved in the checkpoint, hyper must be defined as a `tf.Variable` from the + start. + + ``` + def _trackable_children(self, save_type, **unused_kwargs): + # Incorrect implementation + return {'hyper': tf.Variable(self.hyper)} + ``` + + **Rule 3: [`SavedModel`-only] Watch out for un-traced tf.functions.** + + At the begining of `_trackable_children`, always call + `get_concrete_function()` for any `tf.function` that has an input signature. + + When `tf.functions` are saved to `SavedModel`, any `tf.functions` that have + an input signature and has never been called is traced at export time in + order to copy the op graph into the `SavedModel`. `tf.functions` that are + traced for the first time are allowed to create new state: + + + ``` + @tf.function(input_signature=[]): + def fn(self); + if self.v is None: + self.v = tf.Variable(1.) + return self.v + ``` + + A problem occurs when there is a `Trackable` that returns `fn` as one of its + children and `self.v` has not been created yet. When `fn` is traced, + `self.v` is added to the `Trackable`, but `SavedModel` does not see this + modification since the `Trackable`'s children have already been gathered. + + Therefore, as a precaution, call `get_concrete_function()` at the very + start of `_trackable_children` to ensure that the function is traced: + + + ``` + def _trackable_children(self): + self.fn.get_concrete_function() + return {"v": self.v, "fn": self.fn} + ``` + + Args: + save_type: A string, can be 'savedmodel' or 'checkpoint'. Defaults to + SaveType.CHECKPOINT. + cache: May be `None`, or a dictionary. When `save_type == savedmodel`, a + new cache is created at the start of the SavedModel export, and shared + between all `Trackables` in the same object graph. This cache may be + used for advanced saving functionality. + **kwargs: Additional kwargs that may be added at a later time. + + Returns: + Dictionary mapping names to child trackables. + """ + del save_type, cache, kwargs # Unused. + + self._maybe_initialize_trackable() + return {name: ref for name, ref in self._checkpoint_dependencies} + + def _export_to_saved_model_graph(self, + object_map, + tensor_map, + options, + **kwargs): + """Creates a copy of this object's tensors onto SavedModel graph. + + Needs to be overridden if the class contains tensors that must be saved + into the graph. This method should update the `object_map` and `tensor_map` + dictionaries. + + This method is called on all nodes in the Trackable Graph (generated by + `_trackable_children`). The nodes are traversed in the order defined by + `_deserialization_dependencies` + + All usages of _map_resources should be migrated to this method. + + Args: + object_map: A dictionary that maps original Trackables to the copied + Trackables. This only needs to be updated if the object is a + tf.function, or if the copied tensors are necessary for checkpointing + this object. + tensor_map: Dictionary mapping original tensors to copied tensors. + options: A `tf.saved_model.SaveOptions` object. + **kwargs: Additional kwargs that may be added at a later time. + + Returns: + Flat list of original tensors that have been copied. + """ + _, _, _ = object_map, tensor_map, options + del kwargs + return [] + + def _copy_trackable_to_cpu(self, object_map): + """Creates a copy of this object onto CPU, also copies values over. + + Needs to be overridden if the `Trackable` requires AsyncCheckpoint support. + The method first checks whether a copy of `self` is already created in + `object_map`, and creates one if not already created. Then the method copies + the **values** of itself over to its copy mapped by `object_map`. + + Args: + object_map: A dictionary that maps original Trackables to the copied + Trackables, which reside in the CPU. + """ + del object_map # Unused + raise NotImplementedError("Need to implement _copy_trackable_to_cpu() if " + "the Trackable requires AsyncCheckpoint support.") diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/base_delegate.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/base_delegate.py new file mode 100644 index 0000000000000000000000000000000000000000..e032ce1efe1aff741f1b6ec16ff16b1f82a1288f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/base_delegate.py @@ -0,0 +1,146 @@ +# Copyright 2021 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""A mixin class that delegates another Trackable to be used when saving. + +This is intended to be used with wrapper classes that cannot directly proxy the +wrapped object (e.g. with wrapt.ObjectProxy), because there are inner attributes +that cannot be exposed. + +The Wrapper class itself cannot contain any Trackable children, as only the +delegated Trackable will be saved to checkpoint and SavedModel. + +This class will "disappear" and be replaced with the wrapped inner Trackable +after a cycle of SavedModel saving and loading, unless the object is registered +and loaded with Keras. +""" + +from tensorflow.python.util.tf_export import tf_export + + +@tf_export("__internal__.tracking.DelegatingTrackableMixin", v1=[]) +class DelegatingTrackableMixin(object): + """A mixin that delegates all Trackable methods to another trackable object. + + DO NOT USE THIS UNLESS YOU ARE THE KERAS LOSS SCALE OPTIMIZER. + + This class must be used with multiple inheritance. A class that subclasses + Trackable can also subclass this class, which causes all Trackable methods to + be delegated to the trackable object passed in the constructor. + + A subclass can use this mixin to appear as if it were the trackable passed to + the constructor, from a Checkpoint's perspective. LossScaleOptimizer uses this + mixin, so that the checkpoint format for a LossScaleOptimizer is identical to + the checkpoint format for a normal optimizer. This allows a model to be saved + with a normal Optimizer and restored with a LossScaleOptimizer, or vice versa. + The only difference in checkpoint format is that the loss scale is also saved + with a LossScaleOptimizer. + """ + + def __init__(self, trackable_obj): + self._trackable = trackable_obj + + # pylint: disable=protected-access + @property + def _setattr_tracking(self): + return self._trackable._setattr_tracking + + @_setattr_tracking.setter + def _setattr_tracking(self, value): + self._trackable._setattr_tracking = value + + @property + def _update_uid(self): + return self._trackable._update_uid + + @_update_uid.setter + def _update_uid(self, value): + self._trackable._update_uid = value + + @property + def _unconditional_checkpoint_dependencies(self): + return self._trackable._unconditional_checkpoint_dependencies + + @property + def _unconditional_dependency_names(self): + return self._trackable._unconditional_dependency_names + + @property + def _name_based_restores(self): + return self._trackable._name_based_restores + + def _maybe_initialize_trackable(self): + return self._trackable._maybe_initialize_trackable() + + @property + def _object_identifier(self): + return self._trackable._object_identifier + + @property + def _tracking_metadata(self): + return self._trackable._tracking_metadata + + def _no_dependency(self, *args, **kwargs): + return self._trackable._no_dependency(*args, **kwargs) + + def _name_based_attribute_restore(self, *args, **kwargs): + return self._trackable._name_based_attribute_restore(*args, **kwargs) + + @property + def _checkpoint_dependencies(self): + return self._trackable._checkpoint_dependencies + + @property + def _deferred_dependencies(self): + return self._trackable._deferred_dependencies + + def _lookup_dependency(self, *args, **kwargs): + return self._trackable._lookup_dependency(*args, **kwargs) + + def _add_variable_with_custom_getter(self, *args, **kwargs): + return self._trackable._add_variable_with_custom_getter(*args, **kwargs) + + def _preload_simple_restoration(self, *args, **kwargs): + return self._trackable._preload_simple_restoration(*args, **kwargs) + + def _track_trackable(self, *args, **kwargs): # pylint: disable=redefined-outer-name + return self._trackable._track_trackable(*args, **kwargs) + + def _handle_deferred_dependencies(self, name, trackable): # pylint: disable=redefined-outer-name + return self._trackable._handle_deferred_dependencies(name, trackable) + + def _gather_saveables_for_checkpoint(self, *args, **kwargs): + return self._trackable._gather_saveables_for_checkpoint(*args, **kwargs) + + def _trackable_children(self, *args, **kwargs): + return self._trackable._trackable_children(*args, **kwargs) + + def _deserialization_dependencies(self, *args, **kwargs): + return self._trackable._deserialization_dependencies(*args, **kwargs) + + def _export_to_saved_model_graph(self, *args, **kwargs): + return self._trackable._export_to_saved_model_graph(*args, **kwargs) + + def _serialize_to_tensors(self, *args, **kwargs): + return self._trackable._serialize_to_tensors(*args, **kwargs) + + def _restore_from_tensors(self, *args, **kwargs): + return self._trackable._restore_from_tensors(*args, **kwargs) + + def _copy_trackable_to_cpu(self, object_map): + self._trackable._copy_trackable_to_cpu(object_map) + if self not in object_map: + object_map[self] = DelegatingTrackableMixin(object_map[self._trackable]) + # pylint: enable=protected-access + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/constants.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..d65b130bc80248d9e9f656fd62e5dcee356e24cd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/constants.py @@ -0,0 +1,34 @@ +# Copyright 2022 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Constants used in Trackable for checkpointing and serialization.""" + +import enum + + +# Key where the object graph proto is saved in a TensorBundle +OBJECT_GRAPH_PROTO_KEY = "_CHECKPOINTABLE_OBJECT_GRAPH" + +# A key indicating a variable's value in an object's checkpointed Tensors +# (Trackable._gather_saveables_for_checkpoint). If this is the only key and +# the object has no dependencies, then its value may be restored on object +# creation (avoiding double assignment when executing eagerly). +VARIABLE_VALUE_KEY = "VARIABLE_VALUE" +OBJECT_CONFIG_JSON_KEY = "OBJECT_CONFIG_JSON" + + +@enum.unique +class SaveType(str, enum.Enum): + SAVEDMODEL = "savedmodel" + CHECKPOINT = "checkpoint" diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/converter.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/converter.py new file mode 100644 index 0000000000000000000000000000000000000000..f7a33e1b5aa221ddf58b0870b4fa6ab39b6bb281 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/converter.py @@ -0,0 +1,37 @@ +# Copyright 2022 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Util for converting a Python object to a Trackable.""" + + +from tensorflow.python.eager.polymorphic_function import saved_model_utils +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.trackable import base +from tensorflow.python.trackable import data_structures + + +def convert_to_trackable(obj, parent=None): + """Converts `obj` to `Trackable`.""" + if isinstance(obj, base.Trackable): + return obj + obj = data_structures.wrap_or_unwrap(obj) + if (tensor_util.is_tf_type(obj) and + obj.dtype not in (dtypes.variant, dtypes.resource) and + not resource_variable_ops.is_resource_variable(obj)): + return saved_model_utils.TrackableConstant(obj, parent) + if not isinstance(obj, base.Trackable): + raise ValueError(f"Cannot convert {obj} to Trackable.") + return obj diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/data_structures.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/data_structures.py new file mode 100644 index 0000000000000000000000000000000000000000..4cb9904f275c21b0fc08a50a3842efe4475f761a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/data_structures.py @@ -0,0 +1,1112 @@ +"""Trackable data structures.""" +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +import collections +import copy +import sys + +try: + import wrapt +except ImportError: + # Fall back to the build-time dependency if the system package is not available. + from .....third_party import wrapt # pylint: disable=relative-beyond-top-level + +from tensorflow.python.eager import def_function +from tensorflow.python.eager import function as defun +from tensorflow.python.ops import variables +from tensorflow.python.trackable import base +from tensorflow.python.trackable import layer_utils +from tensorflow.python.util.compat import collections_abc +from tensorflow.python.util.tf_export import tf_export + + +class NoDependency: + """Allows attribute assignment to `Trackable` objects with no dependency. + + Example usage: + ```python + obj = Trackable() + obj.has_dependency = tf.Variable(0., name="dep") + obj.no_dependency = NoDependency(tf.Variable(1., name="nodep")) + assert obj.no_dependency.name == "nodep:0" + ``` + + `obj` in this example has a dependency on the variable "dep", and both + attributes contain un-wrapped `Variable` objects. + + `NoDependency` also works with `tf.keras.Model`, but only for checkpoint + dependencies: wrapping a `Layer` in `NoDependency` will assign the (unwrapped) + `Layer` to the attribute without a checkpoint dependency, but the `Model` will + still track the `Layer` (so it will appear in `Model.layers`, and its + variables will appear in `Model.variables`). + """ + + __slots__ = ["value"] + + def __init__(self, value): + self.value = value + + +def _should_wrap_tuple(t): + """Determine if a tuple has any trackable components.""" + # pylint: disable=unidiomatic-typecheck + # Exact type checking to avoid mucking up custom logic in list/dict + # subclasses, e.g. collections.Counter. + for element in t: + if isinstance(element, NoDependency): + return True # We should remove the NoDependency object from the tuple. + if isinstance(element, base.Trackable): + return True + if type(element) == dict: + return True + if type(element) == collections.OrderedDict: + return True + if type(element) == list: + return True + if isinstance(element, tuple) and _should_wrap_tuple(element): + return True + # There are no trackable elements or data structures. Tuples are immutable, so + # mutation isn't a concern. Don't wrap. + return False + # pylint: enable=unidiomatic-typecheck + + +@tf_export("__internal__.tracking.wrap", v1=[]) +def wrap_or_unwrap(value): + """Wraps input value into trackable data structures. + + This is mostly useful for containers like list, dict, etc, which could contain + trackable objects in it. Wrapped data structure will be tracked when + associated with a `tf.Module`, so that save model/checkpoint can properly + track the dependency. + + It will also unwrap NoDependency objects. + + Args: + value: the input object to be wrapped. + + Returns: + Wrapped trackable data structure. + """ + # pylint: disable=unidiomatic-typecheck + # Exact type checking to avoid mucking up custom logic in list/dict + # subclasses, e.g. collections.Counter. + if isinstance(value, NoDependency): + return value.value + if isinstance(value, base.Trackable): + return value # Skip conversion for already trackable objects. + elif type(value) == dict: + return _DictWrapper(value) + elif type(value) == collections.OrderedDict: + return _DictWrapper(value) + elif type(value) == list: + return ListWrapper(value) + elif isinstance(value, tuple) and _should_wrap_tuple(value): + # There are trackable elements or data structures. Wrap the tuple. + return _TupleWrapper(value) + else: + return value + # pylint: enable=unidiomatic-typecheck + + +@tf_export("__internal__.tracking.sticky_attribute_assignment", v1=[]) +def sticky_attribute_assignment(trackable, name, value): + """Adds dependencies, generally called from __setattr__. + + This behavior is shared between Trackable and Model. + + Respects NoDependency indicators, but otherwise makes trackable objects + out of common data structures and tracks objects by their attribute names. + + Args: + trackable: The object to add dependencies to (generally the one having + an attribute assigned). + name: The attribute name being assigned. + value: The value being assigned. Not necessarily a trackable object. + + Returns: + The value which should be stored in the attribute (unwrapped from a + NoDependency object if necessary). + """ + if isinstance(value, NoDependency): + add_dependency = False + else: + add_dependency = True + value = wrap_or_unwrap(value) + if not add_dependency: + return value + if isinstance(value, base.Trackable): + trackable._track_trackable( # pylint: disable=protected-access + value, name=name, + # Allow the user to switch the Trackable which is tracked by this + # name, since assigning a new variable to an attribute has + # historically been fine (e.g. Adam did this). + overwrite=True) + return value + + +class _UntrackableError(ValueError): + + def __init__(self, value): # pylint: disable=super-init-not-called + self._value = value + + def __str__(self): + return ("Only trackable objects (such as Layers or Optimizers) may be " + f"stored in a List object. Got {self._value}, which does not " + "inherit from Trackable.") + + +@tf_export("__internal__.tracking.TrackableDataStructure", v1=[]) +class TrackableDataStructure(base.Trackable): + """Base class for data structures which contain trackable objects.""" + + def __init__(self): + # Attributes prefixed with "_self_" for compatibility with + # wrapt.ObjectProxy. All additional attrs MUST conform to this pattern, as + # extending `__slots__` on a subclass of ObjectProxy breaks in a variety of + # ways. + self._self_trainable = True + self._self_extra_variables = [] + self._self_attribute_sentinel = layer_utils.AttributeSentinel(True) + + @property + def _attribute_sentinel(self): + return self._self_attribute_sentinel + + @property + def trainable(self): + return self._self_trainable + + @trainable.setter + def trainable(self, value): + self._self_trainable = value + + def _track_value(self, value, name): + """Add a dependency on `value`.""" + value = sticky_attribute_assignment( + trackable=self, value=value, name=name) + if isinstance(value, variables.Variable): + self._self_extra_variables.append(value) + if not isinstance(value, base.Trackable): + raise _UntrackableError(value) + if hasattr(value, "_use_resource_variables"): + # In subclassed models, legacy layers (tf.layers) must always use + # resource variables. + value._use_resource_variables = True # pylint: disable=protected-access + value_attribute_sentinel = getattr(value, "_attribute_sentinel", None) + if value_attribute_sentinel: + value_attribute_sentinel.add_parent(self._attribute_sentinel) + return value + + @property + def _values(self): + """An iterable/sequence which may contain trackable objects.""" + raise NotImplementedError("Abstract method") + + @property + def _layers(self): + """All Layers and Layer containers, including empty containers.""" + # Filter objects on demand so that wrapper objects use values from the thing + # they're wrapping if out of sync. + collected = [] + for obj in self._values: + if (isinstance(obj, TrackableDataStructure) + or layer_utils.is_layer(obj) + or layer_utils.has_weights(obj)): + collected.append(obj) + return collected + + @property + def layers(self): + return list(layer_utils.filter_empty_layer_containers(self._layers)) + + @property + def trainable_weights(self): + if not self._self_trainable: + return [] + trainable_variables = [] + for obj in self._values: + if isinstance(obj, base.Trackable) and hasattr( + obj, "trainable_variables"): + trainable_variables += obj.trainable_variables + trainable_extra_variables = [ + v for v in self._self_extra_variables if v.trainable + ] + return trainable_variables + trainable_extra_variables + + @property + def non_trainable_weights(self): + trainable_extra_variables = [ + v for v in self._self_extra_variables if v.trainable + ] + non_trainable_extra_variables = [ + v for v in self._self_extra_variables if not v.trainable + ] + non_trainable_variables = [] + for obj in self._values: + if isinstance(obj, base.Trackable) and hasattr( + obj, "non_trainable_variables"): + non_trainable_variables += obj.non_trainable_variables + + if not self._self_trainable: + # Return order is all trainable vars, then all non-trainable vars. + trainable_variables = [] + for obj in self._values: + if isinstance(obj, base.Trackable) and hasattr( + obj, "trainable_variables"): + trainable_variables += obj.trainable_variables + + non_trainable_variables = ( + trainable_variables + trainable_extra_variables + + non_trainable_variables + non_trainable_extra_variables) + else: + non_trainable_variables = ( + non_trainable_variables + non_trainable_extra_variables) + + return non_trainable_variables + + @property + def weights(self): + return self.trainable_weights + self.non_trainable_weights + + @property + def trainable_variables(self): + return self.trainable_weights + + @property + def non_trainable_variables(self): + return self.non_trainable_weights + + @property + def variables(self): + return self.weights + + @property + def updates(self): + """Aggregate updates from any `Layer` instances.""" + # Updates and conditional losses are forwarded as-is rather than being + # filtered based on inputs, since this is just a container and won't ever + # have any inputs. + aggregated = [] + for layer in self.layers: + if hasattr(layer, "updates"): + aggregated += layer.updates + return aggregated + + @property + def losses(self): + """Aggregate losses from any `Layer` instances.""" + aggregated = [] + for layer in self.layers: + if hasattr(layer, "losses"): + aggregated += layer.losses + return aggregated + + def __hash__(self): + # Support object-identity hashing, so these structures can be used as keys + # in sets/dicts. + return id(self) + + def __eq__(self, other): + # Similar to Tensors, trackable data structures use object-identity + # equality to support set/dict membership. + return self is other + + +class List(TrackableDataStructure, collections_abc.Sequence): + """An append-only sequence type which is trackable. + + Maintains checkpoint dependencies on its contents (which must also be + trackable), and forwards any `Layer` metadata such as updates and losses. + + Note that `List` is purely a container. It lets a `tf.keras.Model` or + other trackable object know about its contents, but does not call any + `Layer` instances which are added to it. To indicate a sequence of `Layer` + instances which should be called sequentially, use `tf.keras.Sequential`. + + Example usage: + ```python + class HasList(tf.keras.Model): + + def __init__(self): + super().__init__() + self.layer_list = List([layers.Dense(3)]) + self.layer_list.append(layers.Dense(4)) + + def call(self, x): + aggregation = 0. + for l in self.layer_list: + x = l(x) + aggregation += tf.reduce_sum(x) + return aggregation + ``` + + This kind of wrapping is necessary because `Trackable` objects do not + (yet) deeply inspect regular Python data structures, so for example assigning + a regular list (`self.layer_list = [layers.Dense(3)]`) does not create a + checkpoint dependency and does not add the `Layer` instance's weights to its + parent `Model`. + """ + + def __init__(self, *args, **kwargs): + """Construct a new sequence. Arguments are passed to `list()`.""" + super().__init__() + self._storage = self._make_storage(*args, **kwargs) + for index, element in enumerate(self._storage): + self._storage[index] = self._track_value( + element, name=self._name_element(index)) + + def copy(self): + return type(self)(copy.copy(self._storage)) + + def __copy__(self): + return self.copy() + + def __deepcopy__(self, memo): + return type(self)(copy.deepcopy(self._storage, memo)) + + def _make_storage(self, *args, **kwargs): + """Determines the backing storage (overridden in subclasses).""" + return list(*args, **kwargs) + + def _name_element(self, index): + return "%d" % (index,) + + @property + def _values(self): + """Collect values for TrackableDataStructure.""" + return self + + def append(self, value): + """Add a new trackable value.""" + value = self._track_value(value, self._name_element(len(self._storage))) + self._storage.append(value) + + def extend(self, values): + """Add a sequence of trackable values.""" + for value in values: + self.append(value) + + def __iadd__(self, values): + self.extend(values) + return self + + def __add__(self, other): + return self._storage + getattr(other, "_storage", other) + + def __imul__(self, y): + if y <= 0: + raise ValueError( + f"List only supports append, multiplying in place by {y} removes " + "elements.") + + n = len(self._storage) + for _ in range(y - 1): + for i in range(n): + self.append(self._storage[i]) + + return self + + def __mul__(self, n): + return self._storage * n + + def __rmul__(self, n): + return self * n + + def __radd__(self, other): + return other + self._storage + + def __getitem__(self, key): + return self._storage[key] + + def __getslice__(self, i, j): + return self._storage[slice(i, j)] + + def __len__(self): + return len(self._storage) + + def __repr__(self): + return "List(%s)" % (repr(self._storage),) + + def __sizeof__(self): + return super().__sizeof__() + sys.getsizeof(self._storage) + + +# TODO(tomhennigan) Update to collections.UserList? +# TODO(allenl): Try switching this to wrapt.ObjectProxy again when we drop +# Python 3.4 support (may still be tricky). +class ListWrapper( + List, + collections_abc.MutableSequence, + # Shadowed, but there for isinstance checks. + list): + """Wraps the built-in `list` to support restore-on-create for variables. + + Unlike `List`, this sequence type is mutable in the same ways built-in lists + are. Instead of throwing an error immediately like `List`, it records + problematic mutations (e.g. assigning a new element to a position already + occupied, meaning both elements get the same names at different times) and + refuses to save. + + On assignment to an attribute of a Model or Trackable object, Python + lists are replaced with ListWrapper. Wrapping a list in a + `NoDependency` object prevents this. + """ + + def __init__(self, wrapped_list): + """Construct a new list wrapper. + + Args: + wrapped_list: The initial value of the data structure. A shallow copy may + be maintained for error checking. `wrapped_list` itself should not be + modified directly after constructing the `ListWrapper`, and if changes + are detected the `ListWrapper` will throw an exception on save. + """ + # Monotonic flags which indicate this object would not be restored properly, + # and therefore should throw an error on save to avoid giving the impression + # that restoring it will work. + self._non_append_mutation_value = False + self._external_modification_value = False + super().__init__(wrapped_list) + self._last_wrapped_list_snapshot = list(self._storage) + + @property + def _non_append_mutation(self): + return self._non_append_mutation_value + + @_non_append_mutation.setter + def _non_append_mutation(self, value): + # Trackable only cares that a mutation occurred at some point; when + # attempting to save it checks whether a mutation occurred and the object is + # in a "dirty" state but otherwise the specifics of how it got to that state + # are ignored. By contrast, the attribute cache needs to signal the mutation + # immediately since a caller could query the value of an attribute (And + # should not hit the cached value since the mutation may have affected the + # result.) + self._attribute_sentinel.invalidate_all() + self._non_append_mutation_value = value + + @property + def _external_modification(self): + return self._external_modification_value + + @_external_modification.setter + def _external_modification(self, value): + # Invalidate for the same reason as `_non_append_mutation` + self._attribute_sentinel.invalidate_all() + self._external_modification_value = value + + # pylint: disable=protected-access + def __copy__(self): + copied = super().__copy__() + copied._non_append_mutation = self._non_append_mutation + copied._external_modification = self._external_modification + return copied + + def __deepcopy__(self, memo): + copied = super().__deepcopy__(memo) + copied._non_append_mutation = self._non_append_mutation + copied._external_modification = self._external_modification + return copied + # pylint: enable=protected-access + + def __reduce_ex__(self, protocol): + return (self.__class__, + (self._storage,)) + + def _make_storage(self, wrapped_list): + """Use the user's original list for storage.""" + return wrapped_list + + def _check_external_modification(self): + """Checks for any changes to the wrapped list not through the wrapper.""" + if self._external_modification or self._non_append_mutation: + return + if self._storage != self._last_wrapped_list_snapshot: + self._external_modification = True + self._last_wrapped_list_snapshot = None + + def _update_snapshot(self): + """Acknowledges tracked changes to the wrapped list.""" + + # Mutation tracking for attributes reuses the same infrastructure as + # Trackable mutation tracking. + self._attribute_sentinel.invalidate_all() + if self._external_modification or self._non_append_mutation: + return + self._last_wrapped_list_snapshot = list(self._storage) + + def _trackable_children(self, save_type=base.SaveType.CHECKPOINT, **kwargs): + self._check_external_modification() + if self._non_append_mutation: + raise ValueError( + f"Unable to save the object {self} (a list wrapper constructed to " + "track trackable TensorFlow objects). A list element was replaced " + "(__setitem__, __setslice__), deleted (__delitem__, __delslice__), " + "or moved (sort). In order to support restoration on object " + "creation, tracking is exclusively for append-only data structures." + "\n\nIf you don't need this list checkpointed, wrap it in a " + "non-trackable object; it will be subsequently ignored.") + if self._external_modification: + raise ValueError( + f"Unable to save the object {self} (a list wrapper constructed to " + "track trackable TensorFlow objects). The wrapped list was modified " + f"outside the wrapper (its final value was {self._storage}, its value" + " when a checkpoint dependency was added was " + f"{self._last_wrapped_list_snapshot}), which breaks " + "restoration on object creation.\n\nIf you don't need this list " + "checkpointed, wrap it in a NoDependency object; it will be " + "subsequently ignored.") + children = super()._trackable_children(save_type, **kwargs) + + if save_type == base.SaveType.SAVEDMODEL: + # Add functions to be serialized. + children.update({ + str(key): value + for key, value in enumerate(self) + if _is_function(value) + }) + + return children + + def _has_mutation_or_trackable(self): + """Short-circuits a check for trackables if there's already a mutation.""" + if self._non_append_mutation: + return True + return any(isinstance(element, base.Trackable) for element in self._storage) + + def __delitem__(self, key): + self._check_external_modification() + if self._has_mutation_or_trackable(): + self._non_append_mutation = True + del self._storage[key] + self._update_snapshot() + + def __setitem__(self, key, value): + self._check_external_modification() + + if isinstance(key, slice): + # Note: this is quite inefficient, but the list API supports a broad range + # of slice setters (e.g. truncate, extend, replace) and imitating this + # for a range of Python versions is non-trivial. + storage_copy = list(self._storage) + self._storage[key] = value + + len_before = len(storage_copy) + len_now = len(self._storage) + for i in range(max(len_before, len_now)): + value_now = self._storage[i] if i < len_now else None + value_before = storage_copy[i] if i < len_before else None + + if isinstance(value_before, base.Trackable): + self._non_append_mutation = True + + if value_now is not None and value_now != value_before: + self._storage[i] = self._track_value(self._storage[i], + self._name_element(i)) + + else: + if isinstance(self._storage[key], base.Trackable): + self._non_append_mutation = True + self._storage[key] = self._track_value(value, self._name_element(key)) + + self._update_snapshot() + + def append(self, value): + """Add a new trackable value.""" + self._check_external_modification() + super().append(value) + self._update_snapshot() + + def extend(self, values): + """Add a sequence of trackable values.""" + self._check_external_modification() + super().extend(values) + self._update_snapshot() + + def __imul__(self, y): + if y <= 0: + self._check_external_modification() + if self._has_mutation_or_trackable(): + self._non_append_mutation = True + self._storage *= y + self._update_snapshot() + return self + + # Relies on super() calling append, which updates the snapshot. + return super().__imul__(y) + + def __eq__(self, other): + return self._storage == getattr(other, "_storage", other) + + def __ne__(self, other): + return self._storage != getattr(other, "_storage", other) + + def __lt__(self, other): + return self._storage < getattr(other, "_storage", other) + + def __le__(self, other): + return self._storage <= getattr(other, "_storage", other) + + def __gt__(self, other): + return self._storage > getattr(other, "_storage", other) + + def __ge__(self, other): + return self._storage >= getattr(other, "_storage", other) + + def __hash__(self): + # List wrappers need to compare like regular lists, and so like regular + # lists they don't belong in hash tables. + raise TypeError("unhashable type: 'ListWrapper'") + + def insert(self, index, obj): + self._check_external_modification() + if (self._has_mutation_or_trackable() or isinstance(obj, base.Trackable)): + self._non_append_mutation = True + self._storage.insert(index, obj) + self._update_snapshot() + + def sort(self): + self._check_external_modification() + if self._has_mutation_or_trackable(): + self._non_append_mutation = True + self._storage.sort() + self._update_snapshot() + + def __setslice__(self, i, j, y): + self.__setitem__(slice(i, j), y) + + def __delslice__(self, i, j): + self._check_external_modification() + if self._has_mutation_or_trackable(): + self._non_append_mutation = True + del self._storage[slice(i, j)] + self._update_snapshot() + + def _track_value(self, value, name): + """Allows storage of non-trackable objects.""" + try: + value = super()._track_value(value=value, name=name) + except ValueError: + # Even if this value isn't trackable, we need to make sure + # NoDependency objects get unwrapped. + value = sticky_attribute_assignment( + trackable=self, value=value, name=name) + return value + + def __repr__(self): + return "ListWrapper(%s)" % (repr(self._storage),) + + +class Mapping(TrackableDataStructure, collections_abc.Mapping): + """An append-only trackable mapping data structure with string keys. + + Maintains checkpoint dependencies on its contents (which must also be + trackable), named based on its keys. + + Note that once a key has been added, it may not be deleted or replaced. + """ + + def __init__(self, *args, **kwargs): + """Construct a new sequence. Arguments are passed to `dict()`.""" + super().__init__() + self._storage = self._make_storage(*args, **kwargs) + self._storage.update( + {key: self._track_value( + value, name=self._name_element(key)) + for key, value in self._storage.items()}) + + def __copy__(self): + return type(self)(copy.copy(self._storage)) + + def __deepcopy__(self, memo): + return type(self)(copy.deepcopy(self._storage, memo)) + + def _make_storage(self, *args, **kwargs): + return dict(*args, **kwargs) + + @property + def _values(self): + """Collect values for TrackableDataStructure.""" + # Sort items deterministically by key + ordered = list(zip(*sorted(self.items(), key=lambda it: it[0]))) + if ordered: + return ordered[1] + return [] + + def _name_element(self, key): + if not isinstance(key, str): + raise TypeError( + f"Mapping accepts only string keys, but got a key {repr(key)}.") + return str(key) + + def __setitem__(self, key, value): + name = self._name_element(key) + value = self._track_value(value, name=name) + current_value = self._storage.setdefault(key, value) + if current_value is not value: + raise ValueError( + "Mappings are an append-only data structure. Tried to overwrite the " + f"key '{key}' with value {value}, but it already contains " + f"{current_value}") + + def update(self, *args, **kwargs): + for key, value in dict(*args, **kwargs).items(): + self[key] = value + + def __getitem__(self, key): + return self._storage[key] + + def __len__(self): + return len(self._storage) + + def __repr__(self): + return "Mapping(%s)" % (repr(self._storage),) + + def __iter__(self): + return iter(self._storage) + + +class _DictWrapper(TrackableDataStructure, wrapt.ObjectProxy): + """Wraps built-in dicts to support restore-on-create for variables. + + _DictWrapper is to Mapping as ListWrapper is to List. Unlike Mapping, + _DictWrapper allows non-string keys and values and arbitrary mutations (delete + keys, reassign values). Like ListWrapper, these mutations mean that + _DictWrapper will raise an exception on save. + """ + + def __init__(self, wrapped_dict=None): + if wrapped_dict is None: + # Allow zero-argument construction, e.g. from session.run's re-wrapping. + wrapped_dict = {} + if not isinstance(wrapped_dict, collections_abc.Mapping): + # Allow construction from a sequence, e.g. from nest.pack_sequence_as. + wrapped_dict = dict(wrapped_dict) + wrapt.ObjectProxy.__init__(self, wrapped_dict) + TrackableDataStructure.__init__(self) + self._self_non_string_key = False + self._self_external_modification = False + self.__wrapped__.update( + {key: self._track_value( + value, name=self._name_element(key)) + for key, value in self.__wrapped__.items()}) + self._update_snapshot() + + def __reduce_ex__(self, protocol): + return (self.__class__, + (self.__wrapped__,)) + + def __getattribute__(self, name): + if (hasattr(type(self), name) + and isinstance(getattr(type(self), name), property)): + # Bypass ObjectProxy for properties. Whether this workaround is necessary + # appears to depend on the Python version but not the wrapt version: 3.4 + # in particular seems to look up properties on the wrapped object instead + # of the wrapper without this logic. + return object.__getattribute__(self, name) + else: + return super().__getattribute__(name) + + def copy(self): + return copy.copy(self) + + # pylint: disable=protected-access + def __copy__(self): + copied = _DictWrapper(copy.copy(self.__wrapped__)) + copied._self_external_modification = self._self_external_modification + copied._self_non_string_key = self._self_non_string_key + return copied + + def __deepcopy__(self, memo): + copied = _DictWrapper(copy.deepcopy(self.__wrapped__, memo)) + copied._self_external_modification = self._self_external_modification + copied._self_non_string_key = self._self_non_string_key + return copied + # pylint: enable=protected-access + + @property + def _values(self): + """Collect values for TrackableDataStructure.""" + # Sort items deterministically by key + ordered = list(zip(*sorted(self.items(), key=lambda it: it[0]))) + if ordered: + return ordered[1] + return [] + + def _trackable_children(self, save_type=base.SaveType.CHECKPOINT, **kwargs): + """Check that the object is saveable before listing its dependencies.""" + self._check_self_external_modification() + if self._self_non_string_key: + raise ValueError( + f"Unable to save the object {self} (a dictionary wrapper constructed " + "automatically on attribute assignment). The wrapped dictionary " + "contains a non-string key which maps to a trackable object or " + "mutable data structure.\n\nIf you don't need this dictionary " + "checkpointed, wrap it in a non-trackable " + "object; it will be subsequently ignored.") + if self._self_external_modification: + raise ValueError( + f"Unable to save the object {self} (a dictionary wrapper constructed " + "automatically on attribute assignment). The wrapped dictionary was " + f"modified outside the wrapper (its final value was {self}, its value" + " when a checkpoint dependency was added was " + f"{self._self_last_wrapped_dict_snapshot}), which breaks " + "restoration on object creation.\n\nIf you don't need this " + "dictionary checkpointed, wrap it in a " + "non-trackable object; it will be subsequently ignored.") + assert not self._dirty # Any reason for dirtiness should have an exception. + children = super()._trackable_children(save_type, **kwargs) + + if save_type == base.SaveType.SAVEDMODEL: + # Add functions to be serialized. + children.update( + {key: value for key, value in self.items() if _is_function(value)}) + + return children + + @property + def _dirty(self): + """Check if there has already been a mutation which prevents saving.""" + return (self._self_external_modification + or self._self_non_string_key) + + def _check_self_external_modification(self): + """Checks for any changes to the wrapped dict not through the wrapper.""" + if self._dirty: + return + if self != self._self_last_wrapped_dict_snapshot: + self._self_external_modification = True + self._self_last_wrapped_dict_snapshot = None + + def _update_snapshot(self): + """Acknowledges tracked changes to the wrapped dict.""" + self._attribute_sentinel.invalidate_all() + if self._dirty: + return + self._self_last_wrapped_dict_snapshot = dict(self) + + def _track_value(self, value, name): + """Allows storage of non-trackable objects.""" + if isinstance(name, str): + string_key = True + else: + name = "-non_string_key" + string_key = False + try: + no_dependency = isinstance(value, NoDependency) + value = super()._track_value(value=value, name=name) + if not (string_key or no_dependency): + # A non-string key maps to a trackable value. This data structure + # is not saveable. + self._self_non_string_key = True + return value + except ValueError: + # Even if this value isn't trackable, we need to make sure + # NoDependency objects get unwrapped. + return sticky_attribute_assignment( + trackable=self, value=value, name=name) + + def _name_element(self, key): + """Tells TrackableDataStructure to use keys as names as-is.""" + return key + + def __setitem__(self, key, value): + """Allow any modifications, but possibly mark the wrapper as unsaveable.""" + self._check_self_external_modification() + self._maybe_initialize_trackable() + no_dep = isinstance(value, NoDependency) + if isinstance(key, str): + value = self._track_value(value, name=key) + else: + value = wrap_or_unwrap(value) + if not no_dep and isinstance(value, base.Trackable): + # Non-string keys are OK as long as we have no reason to add a + # dependency on the value (either because the value is not + # trackable, or because it was wrapped in a NoDependency object). + self._self_non_string_key = True + self.__wrapped__[key] = value + + self._update_snapshot() + + def __delitem__(self, key): + self._check_self_external_modification() + del self.__wrapped__[key] + self._update_snapshot() + + def __repr__(self): + return "DictWrapper(%s)" % (repr(self.__wrapped__),) + + def __hash__(self): + raise TypeError("unhashable type: 'DictWrapper'") + + def __eq__(self, other): + # Override the TrackableDataStructure "== -> is" forwarding and go back to + # the wrapt implementation. + return self.__wrapped__ == other + + def update(self, *args, **kwargs): + for key, value in dict(*args, **kwargs).items(): + self[key] = value + + +class _TupleWrapper(TrackableDataStructure, wrapt.ObjectProxy): + """Trackable wrapper for tuples and namedtuples.""" + + def __init__(self, original_wrapped_tuple=()): + add_dependency = [] + substituted_wrapped_tuple = [] + for element in original_wrapped_tuple: + if isinstance(element, NoDependency): + add_dependency.append(False) + else: + add_dependency.append(True) + substituted_wrapped_tuple.append(wrap_or_unwrap(element)) + try: + fields = original_wrapped_tuple._fields + except AttributeError: + # Not a namedtuple + is_namedtuple = False + else: + is_namedtuple = True + original_type = type(original_wrapped_tuple) + # Flag to poison saving if we can't re-construct a namedtupled because its + # __new__ takes different keyword arguments than its _fields. + self._self_tuple_is_constructable = True + if is_namedtuple: + try: + # NamedTuples take N arguments, unlike tuple which takes a sequence. + substituted_wrapped_tuple = original_type( + **dict(zip(fields, substituted_wrapped_tuple))) + except TypeError: + wrapt.ObjectProxy.__init__(self, original_wrapped_tuple) + TrackableDataStructure.__init__(self) + self._self_tuple_is_constructable = False + return + else: + substituted_wrapped_tuple = original_type(substituted_wrapped_tuple) + wrapt.ObjectProxy.__init__(self, substituted_wrapped_tuple) + TrackableDataStructure.__init__(self) + + if is_namedtuple: + # For namedtuples, also track by names for compatibility with + # dictionaries. + for name, should_depend, element in zip( + fields, add_dependency, substituted_wrapped_tuple): + if should_depend: + self._track_value(element, name=name) + + # Track by index as well, for compatibility with lists. + for index, (should_depend, element) in enumerate( + zip(add_dependency, substituted_wrapped_tuple)): + if should_depend: + self._track_value(element, name="%d" % (index,)) + + @property + def _values(self): + """Collect values for TrackableDataStructure.""" + return self + + def _track_value(self, value, name): + """Allows storage of non-trackable objects.""" + try: + value = super()._track_value(value=value, name=name) + except ValueError: + # Even if this value isn't trackable, we need to make sure + # NoDependency objects get unwrapped. + value = sticky_attribute_assignment( + trackable=self, value=value, name=name) + return value + + def __repr__(self): + return "_TupleWrapper(%s)" % (repr(self.__wrapped__),) + + def __hash__(self): + # Override the TrackableDataStructure hash forwarding and go back to + # the wrapt implementation. + return hash(self.__wrapped__) + + def __eq__(self, other): + # Override the TrackableDataStructure "== -> is" forwarding and go back to + # the wrapt implementation. + return self.__wrapped__ == other + + def __copy__(self): + return _TupleWrapper(copy.copy(self.__wrapped__)) + + def __deepcopy__(self, memo): + return _TupleWrapper(copy.deepcopy(self.__wrapped__, memo)) + + def __reduce_ex__(self, protocol): + return (self.__class__, + (self.__wrapped__,)) + + # imul and iadd are the only tuple-relevant in-place operators. They need to + # be special-cased to avoid mutating the original proxy object. + def __imul__(self, y): + """Avoid running self.__wrapped__ *= y, which mutates `self`.""" + return self.__wrapped__ * y + + def __iadd__(self, y): + """Avoid running self.__wrapped__ += y, which mutates `self`.""" + return self.__wrapped__ + y + + def _trackable_children(self, save_type=base.SaveType.CHECKPOINT, **kwargs): + if not self._self_tuple_is_constructable: + raise ValueError( + f"Unable to save because the namedtuple {self.__wrapped__} is not " + "constructable from its _fields (i.e. __new__ is overridden). " + f"Expected keyword arguments {self.__wrapped__._fields}. If you do " + "not need to save this object, consider wrapping it in a custom " + "object that does not inherit from tuple.") + return super()._trackable_children(save_type, **kwargs) + + def __getattribute__(self, name): + if name != "__wrapped__" and hasattr(self.__wrapped__, name): + # Prefer attributes on the wrapped object when they conflict with + # attributes on the wrapper object. + return getattr(self.__wrapped__, name) + + if (hasattr(type(self), name) + and isinstance(getattr(type(self), name), property)): + # Bypass ObjectProxy for properties. Whether this workaround is necessary + # appears to depend on the Python version but not the wrapt version: 3.4 + # in particular seems to look up properties on the wrapped object instead + # of the wrapper without this logic. + return object.__getattribute__(self, name) + else: + return super().__getattribute__(name) + + +def _is_function(x): + return isinstance(x, (def_function.Function, defun.ConcreteFunction)) + + +def set_list_item(list_object, index_string, value): + item_index = int(index_string) + if len(list_object) <= item_index: + list_object.extend([None] * (1 + item_index - len(list_object))) + list_object[item_index] = value + + +def set_tuple_item(list_object, index_string, value): + try: + item_index = int(index_string) + except ValueError: + # Ignore namedtuple fields. + return + if len(list_object) <= item_index: + list_object.extend([None] * (1 + item_index - len(list_object))) + list_object[item_index] = value diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/layer_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/layer_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f27489860d2f6b3d903f82acf2cd59a1360dbf70 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/layer_utils.py @@ -0,0 +1,141 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Utilities related to layer/model functionality.""" + +# TODO(b/110718070): Move these functions back to tensorflow/python/keras/utils +# once __init__ files no longer require all of tf.keras to be imported together. + +import collections +import weakref + +from tensorflow.python.util import object_identity + +try: + # typing module is only used for comment type annotations. + import typing # pylint: disable=g-import-not-at-top, unused-import +except ImportError: + pass + + +def is_layer(obj): + """Implicit check for Layer-like objects.""" + # TODO(b/110718070): Replace with isinstance(obj, base_layer.Layer). + return hasattr(obj, "_is_layer") and not isinstance(obj, type) + + +def has_weights(obj): + """Implicit check for Layer-like objects.""" + # TODO(b/110718070): Replace with isinstance(obj, base_layer.Layer). + has_weight = (hasattr(type(obj), "trainable_weights") + and hasattr(type(obj), "non_trainable_weights")) + + return has_weight and not isinstance(obj, type) + + +class MutationSentinel(object): + """Container for tracking whether a property is in a cached state.""" + _in_cached_state = False + + def mark_as(self, value): # type: (MutationSentinel, bool) -> bool + may_affect_upstream = (value != self._in_cached_state) + self._in_cached_state = value + return may_affect_upstream + + @property + def in_cached_state(self): + return self._in_cached_state + + +class AttributeSentinel(object): + """Container for managing attribute cache state within a Layer. + + The cache can be invalidated either on an individual basis (for instance when + an attribute is mutated) or a layer-wide basis (such as when a new dependency + is added). + """ + + def __init__(self, always_propagate=False): + self._parents = weakref.WeakSet() + self.attributes = collections.defaultdict(MutationSentinel) + + # The trackable data structure containers are simple pass throughs. They + # don't know or care about particular attributes. As a result, they will + # consider themselves to be in a cached state, so it's up to the Layer + # which contains them to terminate propagation. + self.always_propagate = always_propagate + + def __repr__(self): + return "{}\n {}".format( + super(AttributeSentinel, self).__repr__(), + {k: v.in_cached_state for k, v in self.attributes.items()}) + + def add_parent(self, node): + # type: (AttributeSentinel, AttributeSentinel) -> None + + # Properly tracking removal is quite challenging; however since this is only + # used to invalidate a cache it's alright to be overly conservative. We need + # to invalidate the cache of `node` (since it has implicitly gained a child) + # but we don't need to invalidate self since attributes should not depend on + # parent Layers. + self._parents.add(node) + node.invalidate_all() + + def get(self, key): + # type: (AttributeSentinel, str) -> bool + return self.attributes[key].in_cached_state + + def _set(self, key, value): + # type: (AttributeSentinel, str, bool) -> None + may_affect_upstream = self.attributes[key].mark_as(value) + if may_affect_upstream or self.always_propagate: + for node in self._parents: # type: AttributeSentinel + node.invalidate(key) + + def mark_cached(self, key): + # type: (AttributeSentinel, str) -> None + self._set(key, True) + + def invalidate(self, key): + # type: (AttributeSentinel, str) -> None + self._set(key, False) + + def invalidate_all(self): + # Parents may have different keys than their children, so we locally + # invalidate but use the `invalidate_all` method of parents. + for key in self.attributes.keys(): + self.attributes[key].mark_as(False) + + for node in self._parents: + node.invalidate_all() + + +def filter_empty_layer_containers(layer_list): + """Filter out empty Layer-like containers and uniquify.""" + # TODO(b/130381733): Make this an attribute in base_layer.Layer. + existing = object_identity.ObjectIdentitySet() + to_visit = layer_list[::-1] + while to_visit: + obj = to_visit.pop() + if obj in existing: + continue + existing.add(obj) + if is_layer(obj): + yield obj + else: + sub_layers = getattr(obj, "layers", None) or [] + + # Trackable data structures will not show up in ".layers" lists, but + # the layers they contain will. + to_visit.extend(sub_layers[::-1]) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/python_state.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/python_state.py new file mode 100644 index 0000000000000000000000000000000000000000..dc36c38e8fb242c9b9918a2a83f0acb42b6055c8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/python_state.py @@ -0,0 +1,87 @@ +"""Utilities for including Python state in TensorFlow checkpoints.""" +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +import abc + +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.trackable import base +from tensorflow.python.util.tf_export import tf_export + + +PYTHON_STATE = "py_state" + + +@tf_export("train.experimental.PythonState") +class PythonState(base.Trackable, metaclass=abc.ABCMeta): + """A mixin for putting Python state in an object-based checkpoint. + + This is an abstract class which allows extensions to TensorFlow's object-based + checkpointing (see `tf.train.Checkpoint`). For example a wrapper for NumPy + arrays: + + ```python + import io + import numpy + + class NumpyWrapper(tf.train.experimental.PythonState): + + def __init__(self, array): + self.array = array + + def serialize(self): + string_file = io.BytesIO() + try: + numpy.save(string_file, self.array, allow_pickle=False) + serialized = string_file.getvalue() + finally: + string_file.close() + return serialized + + def deserialize(self, string_value): + string_file = io.BytesIO(string_value) + try: + self.array = numpy.load(string_file, allow_pickle=False) + finally: + string_file.close() + ``` + + Instances of `NumpyWrapper` are checkpointable objects, and will be saved and + restored from checkpoints along with TensorFlow state like variables. + + ```python + root = tf.train.Checkpoint(numpy=NumpyWrapper(numpy.array([1.]))) + save_path = root.save(prefix) + root.numpy.array *= 2. + assert [2.] == root.numpy.array + root.restore(save_path) + assert [1.] == root.numpy.array + ``` + """ + + @abc.abstractmethod + def serialize(self): + """Callback to serialize the object. Returns a string.""" + + @abc.abstractmethod + def deserialize(self, string_value): + """Callback to deserialize the object.""" + + def _serialize_to_tensors(self): + """Implements Trackable._serialize_to_tensors.""" + with ops.init_scope(): + value = constant_op.constant(self.serialize(), dtype=dtypes.string) + return {PYTHON_STATE: value} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/resource.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/resource.py new file mode 100644 index 0000000000000000000000000000000000000000..ee4a5c1361cbba42e7869f07f81ae25ef25c23d1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/resource.py @@ -0,0 +1,308 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Definitions for resource-type trackable object classes.""" + +import contextlib +import copy +import weakref + +from tensorflow.python.eager import context +from tensorflow.python.eager import def_function +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor +from tensorflow.python.trackable import base +from tensorflow.python.util import tf_contextlib +from tensorflow.python.util.tf_export import tf_export + +# global _RESOURCE_TRACKER_STACK +_RESOURCE_TRACKER_STACK = [] + + +class ResourceTracker: + """An object that tracks a list of resources.""" + + __slots__ = ["_resources"] + + def __init__(self): + self._resources = [] + + @property + def resources(self): + return self._resources + + def add_resource(self, resource): + self._resources.append(resource) + + +@tf_contextlib.contextmanager +def resource_tracker_scope(resource_tracker): + """A context to manage resource trackers. + + Use this in order to collect up all resources created within a block of code. + Example usage: + + ```python + resource_tracker = ResourceTracker() + with resource_tracker_scope(resource_tracker): + resource = TrackableResource() + + assert resource_tracker.resources == [resource] + + Args: + resource_tracker: The passed in ResourceTracker object + + Yields: + A scope in which the resource_tracker is active. + """ + global _RESOURCE_TRACKER_STACK + old = list(_RESOURCE_TRACKER_STACK) + _RESOURCE_TRACKER_STACK.append(resource_tracker) + try: + yield + finally: + _RESOURCE_TRACKER_STACK = old + + +def _make_getter(captured_getter, captured_previous): + """To avoid capturing loop variables.""" + + def getter(*args, **kwargs): + return captured_getter(captured_previous, *args, **kwargs) + + return getter + + +class _ResourceMetaclass(type): + """Metaclass for CapturableResource.""" + + def __call__(cls, *args, **kwargs): + + def default_resource_creator(next_creator, *a, **kw): + assert next_creator is None + obj = cls.__new__(cls, *a, **kw) + obj.__init__(*a, **kw) + return obj + + previous_getter = lambda *a, **kw: default_resource_creator(None, *a, **kw) + resource_creator_stack = ops.get_default_graph()._resource_creator_stack + for getter in resource_creator_stack[cls._resource_type()]: + previous_getter = _make_getter(getter, previous_getter) + + return previous_getter(*args, **kwargs) + + +class CapturableResource(base.Trackable, metaclass=_ResourceMetaclass): + """Holds a Tensor which a tf.function can capture. + + `CapturableResource`s are discovered by traversing the graph of object + attributes, e.g. during `tf.saved_model.save`. They are excluded from the + scope-based tracking of `TrackableResource`; generally things that require + initialization should inherit from `TrackableResource` instead of + `CapturableResource` directly. + """ + + def __init__(self, device=""): + """Initialize the `CapturableResource`. + + Args: + device: A string indicating a required placement for this resource, + e.g. "CPU" if this resource must be created on a CPU device. A blank + device allows the user to place resource creation, so generally this + should be blank unless the resource only makes sense on one device. + """ + self._resource_handle_value = None + self._resource_device = device + self._self_destruction_context = ( + context.eager_mode if context.executing_eagerly() + else ops.get_default_graph().as_default) + + @classmethod + def _resource_type(cls): + return cls.__name__ + + @property + def _destruction_context(self): + return getattr(self, "_self_destruction_context", + # no-op context + contextlib.suppress) + + @_destruction_context.setter + def _destruction_context(self, destruction_context): + self._self_destruction_context = destruction_context + + def _create_resource(self): + """A function that creates a resource handle.""" + raise NotImplementedError("TrackableResource._create_resource not " + "implemented.") + + @property + def _resource_handle(self): + return self._resource_handle_value + + @_resource_handle.setter + def _resource_handle(self, value): + if isinstance(value, (tensor.Tensor, ops.EagerTensor)): + value._parent_trackable = weakref.ref(self) # pylint: disable=protected-access + self._resource_handle_value = value + + def _initialize(self): + """A function that initializes the resource. Optional.""" + pass + + def _destroy_resource(self): + """A function that destroys the resource. Optional.""" + pass + + @property + def resource_handle(self): + """Returns the resource handle associated with this Resource.""" + if self._resource_handle is None: + with ops.device(self._resource_device): + self._resource_handle = self._create_resource() + return self._resource_handle + + def _export_to_saved_model_graph( + self, object_map, tensor_map, **unused_kwargs): + """For implementing `Trackable`.""" + new_obj = copy.copy(self) + # pylint: disable=protected-access + with ops.device(self._resource_device): + new_resource = new_obj._create_resource() + new_obj._resource_handle = new_resource + # pylint: enable=protected-access + object_map[self] = new_obj + tensor_map[self.resource_handle] = new_resource + return [self.resource_handle] + + def _trackable_children(self, save_type=base.SaveType.CHECKPOINT, **kwargs): + children = super()._trackable_children(save_type, **kwargs) + if save_type == "savedmodel": + @def_function.function(input_signature=[], autograph=False) + def _creator(): + resource = self._create_resource() + return resource + + @def_function.function(input_signature=[], autograph=False) + def _initializer(): + self._initialize() + return 1 # Dummy return + + @def_function.function(input_signature=[], autograph=False) + def _destroyer(): + self._destroy_resource() + return 1 # Dummy return + + children.update({ + "_create_resource": _creator, + "_initialize": _initializer, + "_destroy_resource": _destroyer, + }) + return children + + def __del__(self): + try: + # Outer race condition: on program exit, the destruction context may be + # deleted before this __del__ is called. At this point we can safely + # exit without calling _destroy_resource() and let Python handle things. + with self._destruction_context(): + # Inner race condition: possible between this and `ScopedTFFunction` + # whereby if an entire garbage collection chain containing both + # objects is moved to unreachable during the same garbage collection + # cycle, the __del__ for `ScopedTFFunction` can be collected before + # this method is called. In that case, we can't do much but + # continue. + self._destroy_resource() + except Exception: # pylint: disable=broad-except + # Silence all error logs that occur when attempting to destroy this + # resource. + pass + + +@tf_export("saved_model.experimental.TrackableResource") +class TrackableResource(CapturableResource): + """Holds a Tensor which a tf.function can capture. + + A TrackableResource is most useful for stateful Tensors that require + initialization, such as `tf.lookup.StaticHashTable`. `TrackableResource`s + are discovered by traversing the graph of object attributes, e.g. during + `tf.saved_model.save`. + + A TrackableResource has three methods to override: + + * `_create_resource` should create the resource tensor handle. + * `_initialize` should initialize the resource held at `self.resource_handle`. + * `_destroy_resource` is called upon a `TrackableResource`'s destruction + and should decrement the resource's ref count. For most resources, this + should be done with a call to `tf.raw_ops.DestroyResourceOp`. + + Example usage: + + >>> class DemoResource(tf.saved_model.experimental.TrackableResource): + ... def __init__(self): + ... super().__init__() + ... self._initialize() + ... def _create_resource(self): + ... return tf.raw_ops.VarHandleOp(dtype=tf.float32, shape=[2]) + ... def _initialize(self): + ... tf.raw_ops.AssignVariableOp( + ... resource=self.resource_handle, value=tf.ones([2])) + ... def _destroy_resource(self): + ... tf.raw_ops.DestroyResourceOp(resource=self.resource_handle) + >>> class DemoModule(tf.Module): + ... def __init__(self): + ... self.resource = DemoResource() + ... def increment(self, tensor): + ... return tensor + tf.raw_ops.ReadVariableOp( + ... resource=self.resource.resource_handle, dtype=tf.float32) + >>> demo = DemoModule() + >>> demo.increment([5, 1]) + + """ + + def __init__(self, device=""): + """Initialize the `TrackableResource`. + + Args: + device: A string indicating a required placement for this resource, + e.g. "CPU" if this resource must be created on a CPU device. A blank + device allows the user to place resource creation, so generally this + should be blank unless the resource only makes sense on one device. + """ + global _RESOURCE_TRACKER_STACK + for resource_tracker in _RESOURCE_TRACKER_STACK: + resource_tracker.add_resource(self) + super().__init__(device=device) + + +# TODO(b/124205571,b/124092991): Solve destruction of resources. +class RestoredResource(TrackableResource): + """Restored SavedResource.""" + + def __init__(self, device=""): + super().__init__(device=device) + + @classmethod + def _deserialize_from_proto(cls, object_proto, dependencies, **unused_kwargs): + obj = cls(device=object_proto.resource.device) + resource_creator = dependencies.get("_create_resource") + if resource_creator is not None: + obj._create_resource = resource_creator # pylint: disable=protected-access + return obj + + def _add_trackable_child(self, name, value): + setattr(self, name, value) + if (isinstance(value, base.Trackable) and + not isinstance(value, def_function.Function)): + self._track_trackable(value, name) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/trackable_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/trackable_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..bb26be9f25798865153ff7753e741775f3813223 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/trackable_utils.py @@ -0,0 +1,178 @@ +# Copyright 2021 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Utility methods for the trackable dependencies.""" +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import collections + + +def pretty_print_node_path(path): + if not path: + return "root object" + else: + return "root." + ".".join([p.name for p in path]) + + +class CyclicDependencyError(Exception): + + def __init__(self, leftover_dependency_map): + """Creates a CyclicDependencyException.""" + # Leftover edges that were not able to be topologically sorted. + self.leftover_dependency_map = leftover_dependency_map + super(CyclicDependencyError, self).__init__() + + +def order_by_dependency(dependency_map): + """Topologically sorts the keys of a map so that dependencies appear first. + + Uses Kahn's algorithm: + https://en.wikipedia.org/wiki/Topological_sorting#Kahn's_algorithm + + Args: + dependency_map: a dict mapping values to a list of dependencies (other keys + in the map). All keys and dependencies must be hashable types. + + Returns: + A sorted array of keys from dependency_map. + + Raises: + CyclicDependencyError: if there is a cycle in the graph. + ValueError: If there are values in the dependency map that are not keys in + the map. + """ + # Maps trackables -> trackables that depend on them. These are the edges used + # in Kahn's algorithm. + reverse_dependency_map = collections.defaultdict(set) + for x, deps in dependency_map.items(): + for dep in deps: + reverse_dependency_map[dep].add(x) + + # Validate that all values in the dependency map are also keys. + unknown_keys = reverse_dependency_map.keys() - dependency_map.keys() + if unknown_keys: + raise ValueError("Found values in the dependency map which are not keys: " + f"{unknown_keys}") + + # Generate the list sorted by objects without dependencies -> dependencies. + # The returned list will reverse this. + reversed_dependency_arr = [] + + # Prefill `to_visit` with all nodes that do not have other objects depending + # on them. + to_visit = [x for x in dependency_map if x not in reverse_dependency_map] + + while to_visit: + x = to_visit.pop(0) + reversed_dependency_arr.append(x) + for dep in set(dependency_map[x]): + edges = reverse_dependency_map[dep] + edges.remove(x) + if not edges: + to_visit.append(dep) + reverse_dependency_map.pop(dep) + + if reverse_dependency_map: + leftover_dependency_map = collections.defaultdict(list) + for dep, xs in reverse_dependency_map.items(): + for x in xs: + leftover_dependency_map[x].append(dep) + raise CyclicDependencyError(leftover_dependency_map) + + return reversed(reversed_dependency_arr) + + +_ESCAPE_CHAR = "." # For avoiding conflicts with user-specified names. + +# Keyword for identifying that the next bit of a checkpoint variable name is a +# slot name. Checkpoint names for slot variables look like: +# +# /<_OPTIMIZER_SLOTS_NAME>// +# +# Where is a full path from the checkpoint root to the +# variable being slotted for. +_OPTIMIZER_SLOTS_NAME = _ESCAPE_CHAR + "OPTIMIZER_SLOT" +# Keyword for separating the path to an object from the name of an +# attribute in checkpoint names. Used like: +# /<_OBJECT_ATTRIBUTES_NAME>/ +OBJECT_ATTRIBUTES_NAME = _ESCAPE_CHAR + "ATTRIBUTES" + +# A constant string that is used to reference the save and restore functions of +# Trackable objects that define `_serialize_to_tensors` and +# `_restore_from_tensors`. This is written as the key in the +# `SavedObject.saveable_objects` map in the SavedModel. +SERIALIZE_TO_TENSORS_NAME = _ESCAPE_CHAR + "TENSORS" + + +def escape_local_name(name): + # We need to support slashes in local names for compatibility, since this + # naming scheme is being patched in to things like Layer.add_variable where + # slashes were previously accepted. We also want to use slashes to indicate + # edges traversed to reach the variable, so we escape forward slashes in + # names. + return (name.replace(_ESCAPE_CHAR, _ESCAPE_CHAR + _ESCAPE_CHAR).replace( + r"/", _ESCAPE_CHAR + "S")) + + +def object_path_to_string(node_path_arr): + """Converts a list of nodes to a string.""" + return "/".join( + (escape_local_name(trackable.name) for trackable in node_path_arr)) + + +def checkpoint_key(object_path, local_name): + """Returns the checkpoint key for a local attribute of an object.""" + key_suffix = escape_local_name(local_name) + if local_name == SERIALIZE_TO_TENSORS_NAME: + # In the case that Trackable uses the _serialize_to_tensor API for defining + # tensors to save to the checkpoint, the suffix should be the key(s) + # returned by `_serialize_to_tensor`. The suffix used here is empty. + key_suffix = "" + + return f"{object_path}/{OBJECT_ATTRIBUTES_NAME}/{key_suffix}" + + +def extract_object_name(key): + """Substrings the checkpoint key to the start of "/.ATTRIBUTES".""" + search_key = "/" + OBJECT_ATTRIBUTES_NAME + return key[:key.index(search_key)] + + +def extract_local_name(key, prefix=None): + """Returns the substring after the "/.ATTIBUTES/" in the checkpoint key.""" + # "local name" refers to the the keys of `Trackable._serialize_to_tensors.` + prefix = prefix or "" + search_key = OBJECT_ATTRIBUTES_NAME + "/" + prefix + # If checkpoint is saved from TF1, return key as is. + try: + return key[key.index(search_key) + len(search_key):] + except ValueError: + return key + + +def slot_variable_key(variable_path, optimizer_path, slot_name): + """Returns checkpoint key for a slot variable.""" + # Name slot variables: + # + # /<_OPTIMIZER_SLOTS_NAME>// + # + # where is exactly the checkpoint name used for the original + # variable, including the path from the checkpoint root and the local name in + # the object which owns it. Note that we only save slot variables if the + # variable it's slotting for is also being saved. + + return (f"{variable_path}/{_OPTIMIZER_SLOTS_NAME}/{optimizer_path}/" + f"{escape_local_name(slot_name)}") diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/adadelta.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/adadelta.py new file mode 100644 index 0000000000000000000000000000000000000000..c3690de5f27eecbd2ae75c5bf2a6563296ba30d1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/adadelta.py @@ -0,0 +1,198 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""Adadelta for TensorFlow.""" +from tensorflow.python.framework import ops +from tensorflow.python.ops import math_ops +from tensorflow.python.training import optimizer +from tensorflow.python.training import training_ops +from tensorflow.python.util.tf_export import tf_export + + +@tf_export(v1=["train.AdadeltaOptimizer"]) +class AdadeltaOptimizer(optimizer.Optimizer): + """Optimizer that implements the Adadelta algorithm. + + References: + ADADELTA - An Adaptive Learning Rate Method: + [Zeiler, 2012](http://arxiv.org/abs/1212.5701) + ([pdf](http://arxiv.org/pdf/1212.5701v1.pdf)) + + @compatibility(TF2) + tf.compat.v1.train.AdadeltaOptimizer is compatible with eager mode and + `tf.function`. + When eager execution is enabled, `learning_rate`, `rho`, + and `epsilon` can each be a callable that + takes no arguments and returns the actual value to use. This can be useful + for changing these values across different invocations of optimizer + functions. + + To switch to native TF2 style, use [`tf.keras.optimizers.Adadelta`] + (https://www.tensorflow.org/api_docs/python/tf/keras/optimizers/Adadelta) + instead. Please notice that due to the implementation differences, + `tf.keras.optimizers.Adadelta` and + `tf.compat.v1.train.AdadeltaOptimizer` may have slight differences in + floating point numerics even though the formula used for the variable + updates still matches. + + #### Structural mapping to native TF2 + + Before: + + ```python + optimizer = tf.compat.v1.train.AdadeltaOptimizer( + learning_rate=learning_rate, + rho=rho, + epsilon=epsilon) + ``` + + After: + + ```python + optimizer = tf.keras.optimizers.Adadelta( + learning_rate=learning_rate, + rho=rho, + epsilon=epsilon) + ``` + + #### How to map arguments + | TF1 Arg Name | TF2 Arg Name | Note | + | ------------------ | ------------- | ------------------------------- | + | `learning_rate` | `learning_rate`| Be careful of setting | + : : : learning_rate tensor value computed from the global step. : + : : : In TF1 this was usually meant to imply a dynamic learning rate and : + : : : would recompute in each step. In TF2 (eager + function) it will : + : : : treat it as a scalar value that only gets computed once instead of : + : : : a symbolic placeholder to be computed each time. : + | `rho` | `rho` | - | + | `epsilon` | `epsilon` | Default value is 1e-08 in TF1, | + : : : but 1e-07 in TF2. : + | `use_locking` | - | Not applicable in TF2. | + + #### Before & after usage example + Before: + + ```python + x = tf.Variable([1,2,3], dtype=tf.float32) + grad = tf.constant([0.1, 0.2, 0.3]) + optimizer = tf.compat.v1.train.AdadeltaOptimizer(learning_rate=0.001) + optimizer.apply_gradients(zip([grad], [x])) + ``` + + After: + + ```python + x = tf.Variable([1,2,3], dtype=tf.float32) + grad = tf.constant([0.1, 0.2, 0.3]) + optimizer = tf.keras.optimizers.Adadelta(learning_rate=0.001) + optimizer.apply_gradients(zip([grad], [x])) + ``` + + @end_compatibility + """ + + def __init__(self, learning_rate=0.001, rho=0.95, epsilon=1e-8, + use_locking=False, name="Adadelta"): + """Construct a new Adadelta optimizer. + + Args: + learning_rate: A `Tensor` or a floating point value. The learning rate. + To match the exact form in the original paper use 1.0. + rho: A `Tensor` or a floating point value. The decay rate. + epsilon: A `Tensor` or a floating point value. A constant epsilon used + to better conditioning the grad update. + use_locking: If `True` use locks for update operations. + name: Optional name prefix for the operations created when applying + gradients. Defaults to "Adadelta". + + + """ + super(AdadeltaOptimizer, self).__init__(use_locking, name) + self._lr = learning_rate + self._rho = rho + self._epsilon = epsilon + + # Tensor versions of the constructor arguments, created in _prepare(). + self._lr_t = None + self._rho_t = None + self._epsilon_t = None + + def _create_slots(self, var_list): + for v in var_list: + self._zeros_slot(v, "accum", self._name) + self._zeros_slot(v, "accum_update", self._name) + + def _prepare(self): + lr = self._call_if_callable(self._lr) + rho = self._call_if_callable(self._rho) + epsilon = self._call_if_callable(self._epsilon) + + self._lr_t = ops.convert_to_tensor(lr, name="lr") + self._rho_t = ops.convert_to_tensor(rho, name="rho") + self._epsilon_t = ops.convert_to_tensor(epsilon, name="epsilon") + + def _apply_dense(self, grad, var): + accum = self.get_slot(var, "accum") + accum_update = self.get_slot(var, "accum_update") + return training_ops.apply_adadelta( + var, + accum, + accum_update, + math_ops.cast(self._lr_t, var.dtype.base_dtype), + math_ops.cast(self._rho_t, var.dtype.base_dtype), + math_ops.cast(self._epsilon_t, var.dtype.base_dtype), + grad, + use_locking=self._use_locking) + + def _resource_apply_dense(self, grad, var): + accum = self.get_slot(var, "accum") + accum_update = self.get_slot(var, "accum_update") + return training_ops.resource_apply_adadelta( + var.handle, + accum.handle, + accum_update.handle, + math_ops.cast(self._lr_t, grad.dtype.base_dtype), + math_ops.cast(self._rho_t, grad.dtype.base_dtype), + math_ops.cast(self._epsilon_t, grad.dtype.base_dtype), + grad, + use_locking=self._use_locking) + + def _apply_sparse(self, grad, var): + accum = self.get_slot(var, "accum") + accum_update = self.get_slot(var, "accum_update") + return training_ops.sparse_apply_adadelta( + var, + accum, + accum_update, + math_ops.cast(self._lr_t, var.dtype.base_dtype), + math_ops.cast(self._rho_t, var.dtype.base_dtype), + math_ops.cast(self._epsilon_t, var.dtype.base_dtype), + grad.values, + grad.indices, + use_locking=self._use_locking) + + def _resource_apply_sparse(self, grad, var, indices): + accum = self.get_slot(var, "accum") + accum_update = self.get_slot(var, "accum_update") + return training_ops.resource_sparse_apply_adadelta( + var.handle, + accum.handle, + accum_update.handle, + math_ops.cast(self._lr_t, grad.dtype), + math_ops.cast(self._rho_t, grad.dtype), + math_ops.cast(self._epsilon_t, grad.dtype), + grad, + indices, + use_locking=self._use_locking) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/adagrad.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/adagrad.py new file mode 100644 index 0000000000000000000000000000000000000000..0fbe9018308ef7f9519010fa81ae33e79420eb04 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/adagrad.py @@ -0,0 +1,195 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""Adagrad for TensorFlow.""" +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gen_array_ops +from tensorflow.python.ops import init_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.training import optimizer +from tensorflow.python.training import training_ops +from tensorflow.python.util.tf_export import tf_export + + +@tf_export(v1=["train.AdagradOptimizer"]) +class AdagradOptimizer(optimizer.Optimizer): + """Optimizer that implements the Adagrad algorithm. + + References: + Adaptive Subgradient Methods for Online Learning and Stochastic Optimization + :[Duchi et al., 2011](http://jmlr.org/papers/v12/duchi11a.html) + ([pdf](http://www.jmlr.org/papers/volume12/duchi11a/duchi11a.pdf)) + + @compatibility(TF2) + tf.compat.v1.train.AdagradOptimizer is compatible with eager mode and + `tf.function`. + When eager execution is enabled, `learning_rate`, + `initial_accumulator_value`, and `epsilon` can each be a callable that + takes no arguments and returns the actual value to use. This can be useful + for changing these values across different invocations of optimizer + functions. + + To switch to native TF2 style, use [`tf.keras.optimizers.Adagrad`] + (https://www.tensorflow.org/api_docs/python/tf/keras/optimizers/Adagrad) + instead. Please notice that due to the implementation differences, + `tf.keras.optimizers.Adagrad` and + `tf.compat.v1.train.AdagradOptimizer` may have slight differences in + floating point numerics even though the formula used for the variable + updates still matches. + + #### Structural mapping to native TF2 + + Before: + + ```python + optimizer = tf.compat.v1.train.AdagradOptimizer( + learning_rate=learning_rate, + initial_accumulator_value=initial_accumulator_value) + ``` + + After: + + ```python + optimizer = tf.keras.optimizers.Adagrad( + learning_rate=learning_rate, + initial_accumulator_value=initial_accumulator_value, + epsilon=1e-07) + ``` + + #### How to map arguments + | TF1 Arg Name | TF2 Arg Name | Note | + | ------------------ | ------------- | ------------------------------- | + | `learning_rate` | `learning_rate` | Be careful of setting | + : : : learning_rate tensor value computed from the global step. : + : : : In TF1 this was usually meant to imply a dynamic learning rate and : + : : : would recompute in each step. In TF2 (eager + function) it will : + : : : treat it as a scalar value that only gets computed once instead of : + : : : a symbolic placeholder to be computed each time. : + | `initial_accumulator_value` | `initial_accumulator_value` | The | + : : : argument can be value of zero in TF2, which is not accepted in TF1.| + | - | `epsilon` | `epsilon` is become configurable in TF2. The | + : : : defualt value is changed from 1e-8 to 1e-7 : + | `use_locking` | - | Not applicable in TF2. | + + #### Before & after usage example + Before: + + ```python + x = tf.Variable([1,2,3], dtype=tf.float32) + grad = tf.constant([0.1, 0.2, 0.3]) + optimizer = tf.compat.v1.train.AdagradOptimizer(learning_rate=0.001) + optimizer.apply_gradients(zip([grad], [x])) + ``` + + After: + + ```python + x = tf.Variable([1,2,3], dtype=tf.float32) + grad = tf.constant([0.1, 0.2, 0.3]) + optimizer = tf.keras.optimizers.Adagrad(learning_rate=0.001) + optimizer.apply_gradients(zip([grad], [x])) + ``` + + @end_compatibility + """ + + def __init__(self, learning_rate, initial_accumulator_value=0.1, + use_locking=False, name="Adagrad"): + """Construct a new Adagrad optimizer. + + Args: + learning_rate: A `Tensor` or a floating point value. The learning rate. + initial_accumulator_value: A floating point value. + Starting value for the accumulators, must be positive. + use_locking: If `True` use locks for update operations. + name: Optional name prefix for the operations created when applying + gradients. Defaults to "Adagrad". + + Raises: + ValueError: If the `initial_accumulator_value` is invalid. + + """ + if initial_accumulator_value <= 0.0: + raise ValueError("initial_accumulator_value must be positive: %s" % + initial_accumulator_value) + super(AdagradOptimizer, self).__init__(use_locking, name) + self._learning_rate = learning_rate + self._initial_accumulator_value = initial_accumulator_value + # Created in Initialize. + self._learning_rate_tensor = None + + def _create_slots(self, var_list): + for v in var_list: + dtype = v.dtype.base_dtype + if v.get_shape().is_fully_defined(): + init = init_ops.constant_initializer(self._initial_accumulator_value, + dtype=dtype) + else: + init = self._init_constant_op(v, dtype) + self._get_or_make_slot_with_initializer(v, init, v.get_shape(), dtype, + "accumulator", self._name) + + def _init_constant_op(self, v, dtype): + def init(): + # Use a Tensor instead of initializer if variable does not have + # static shape. + init_constant = gen_array_ops.fill(array_ops.shape(v), + self._initial_accumulator_value) + return math_ops.cast(init_constant, dtype) + return init + + def _prepare(self): + learning_rate = self._call_if_callable(self._learning_rate) + self._learning_rate_tensor = ops.convert_to_tensor( + learning_rate, name="learning_rate") + + def _apply_dense(self, grad, var): + acc = self.get_slot(var, "accumulator") + return training_ops.apply_adagrad( + var, + acc, + math_ops.cast(self._learning_rate_tensor, var.dtype.base_dtype), + grad, + use_locking=self._use_locking) + + def _resource_apply_dense(self, grad, var): + acc = self.get_slot(var, "accumulator") + return training_ops.resource_apply_adagrad( + var.handle, + acc.handle, + math_ops.cast(self._learning_rate_tensor, grad.dtype.base_dtype), + grad, + use_locking=self._use_locking) + + def _apply_sparse(self, grad, var): + acc = self.get_slot(var, "accumulator") + return training_ops.sparse_apply_adagrad( + var, + acc, + math_ops.cast(self._learning_rate_tensor, var.dtype.base_dtype), + grad.values, + grad.indices, + use_locking=self._use_locking) + + def _resource_apply_sparse(self, grad, var, indices): + acc = self.get_slot(var, "accumulator") + return training_ops.resource_sparse_apply_adagrad( + var.handle, + acc.handle, + math_ops.cast(self._learning_rate_tensor, grad.dtype), + grad, + indices, + use_locking=self._use_locking) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/adagrad_da.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/adagrad_da.py new file mode 100644 index 0000000000000000000000000000000000000000..9f9784fd89488280ef0998d2f08e8136c733b566 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/adagrad_da.py @@ -0,0 +1,171 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Adagrad Dual Averaging for TensorFlow.""" +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.training import optimizer +from tensorflow.python.training import training_ops +from tensorflow.python.util.tf_export import tf_export + + +@tf_export(v1=["train.AdagradDAOptimizer"]) +class AdagradDAOptimizer(optimizer.Optimizer): + """Adagrad Dual Averaging algorithm for sparse linear models. + + This optimizer takes care of regularization of unseen features in a mini batch + by updating them when they are seen with a closed form update rule that is + equivalent to having updated them on every mini-batch. + + AdagradDA is typically used when there is a need for large sparsity in the + trained model. This optimizer only guarantees sparsity for linear models. Be + careful when using AdagradDA for deep networks as it will require careful + initialization of the gradient accumulators for it to train. + + References: + Adaptive Subgradient Methods for Online Learning and Stochastic Optimization + :[Duchi et al., 2011](http://jmlr.org/papers/v12/duchi11a.html) + ([pdf](http://www.jmlr.org/papers/volume12/duchi11a/duchi11a.pdf)) + """ + + def __init__(self, + learning_rate, + global_step, + initial_gradient_squared_accumulator_value=0.1, + l1_regularization_strength=0.0, + l2_regularization_strength=0.0, + use_locking=False, + name="AdagradDA"): + """Construct a new AdagradDA optimizer. + + Args: + learning_rate: A `Tensor` or a floating point value. The learning rate. + global_step: A `Tensor` containing the current training step number. + initial_gradient_squared_accumulator_value: A floating point value. + Starting value for the accumulators, must be positive. + l1_regularization_strength: A float value, must be greater than or + equal to zero. + l2_regularization_strength: A float value, must be greater than or + equal to zero. + use_locking: If `True` use locks for update operations. + name: Optional name prefix for the operations created when applying + gradients. Defaults to "AdagradDA". + + Raises: + ValueError: If the `initial_gradient_squared_accumulator_value` is + invalid. + """ + if initial_gradient_squared_accumulator_value <= 0.0: + raise ValueError("initial_gradient_squared_accumulator_value must be " + "positive: %s" % + initial_gradient_squared_accumulator_value) + super(AdagradDAOptimizer, self).__init__(use_locking, name) + self._learning_rate = learning_rate + self._initial_gradient_squared_accumulator_value = ( + initial_gradient_squared_accumulator_value) + # Created in Initialize. + self._learning_rate_tensor = None + self._l1_regularization_strength = l1_regularization_strength + self._l2_regularization_strength = l2_regularization_strength + self._global_step = global_step + self._global_step_on_worker = None + + def _create_slots(self, var_list): + for v in var_list: + with ops.colocate_with(v): + g_val = constant_op.constant( + 0.0, shape=v.get_shape(), dtype=v.dtype.base_dtype) + gg_val = constant_op.constant( + self._initial_gradient_squared_accumulator_value, + shape=v.get_shape(), + dtype=v.dtype.base_dtype) + self._get_or_make_slot(v, g_val, "gradient_accumulator", self._name) + self._get_or_make_slot(v, gg_val, "gradient_squared_accumulator", + self._name) + + def _prepare(self): + self._learning_rate_tensor = ops.convert_to_tensor( + self._learning_rate, name="learning_rate") + # Performance optimization so that worker creates a copy of the global step + # to avoid overloading the parameter server holding the global step. + with ops.colocate_with(self._learning_rate_tensor): + self._global_step_on_worker = array_ops.identity(self._global_step) + 1 + + def _apply_dense(self, grad, var): + g_acc = self.get_slot(var, "gradient_accumulator") + gg_acc = self.get_slot(var, "gradient_squared_accumulator") + with ops.device(var.device): + global_step = array_ops.identity(self._global_step_on_worker) + return training_ops.apply_adagrad_da( + var, + g_acc, + gg_acc, + grad, + math_ops.cast(self._learning_rate_tensor, var.dtype.base_dtype), + math_ops.cast(self._l1_regularization_strength, var.dtype.base_dtype), + math_ops.cast(self._l2_regularization_strength, var.dtype.base_dtype), + global_step, + use_locking=self._use_locking) + + def _resource_apply_dense(self, grad, var): + g_acc = self.get_slot(var, "gradient_accumulator") + gg_acc = self.get_slot(var, "gradient_squared_accumulator") + with ops.device(var.device): + global_step = array_ops.identity(self._global_step_on_worker) + return training_ops.resource_apply_adagrad_da( + var.handle, + g_acc.handle, + gg_acc.handle, + grad, + math_ops.cast(self._learning_rate_tensor, grad.dtype.base_dtype), + math_ops.cast(self._l1_regularization_strength, grad.dtype.base_dtype), + math_ops.cast(self._l2_regularization_strength, grad.dtype.base_dtype), + global_step, + use_locking=self._use_locking) + + def _apply_sparse(self, grad, var): + g_acc = self.get_slot(var, "gradient_accumulator") + gg_acc = self.get_slot(var, "gradient_squared_accumulator") + with ops.device(var.device): + global_step = array_ops.identity(self._global_step_on_worker) + return training_ops.sparse_apply_adagrad_da( + var, + g_acc, + gg_acc, + grad.values, + grad.indices, + math_ops.cast(self._learning_rate_tensor, var.dtype.base_dtype), + math_ops.cast(self._l1_regularization_strength, var.dtype.base_dtype), + math_ops.cast(self._l2_regularization_strength, var.dtype.base_dtype), + global_step, + use_locking=self._use_locking) + + def _resource_apply_sparse(self, grad, var, indices): + g_acc = self.get_slot(var, "gradient_accumulator") + gg_acc = self.get_slot(var, "gradient_squared_accumulator") + with ops.device(var.device): + global_step = array_ops.identity(self._global_step_on_worker) + return training_ops.resource_sparse_apply_adagrad_da( + var.handle, + g_acc.handle, + gg_acc.handle, + grad, + indices, + math_ops.cast(self._learning_rate_tensor, grad.dtype), + math_ops.cast(self._l1_regularization_strength, grad.dtype), + math_ops.cast(self._l2_regularization_strength, grad.dtype), + global_step, + use_locking=self._use_locking) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/adam.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/adam.py new file mode 100644 index 0000000000000000000000000000000000000000..f479dbb35dc2b7e1013b6cc1464d677f422ae57a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/adam.py @@ -0,0 +1,303 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Adam for TensorFlow.""" +from tensorflow.python.eager import context +from tensorflow.python.framework import ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.ops import state_ops +from tensorflow.python.training import optimizer +from tensorflow.python.training import training_ops +from tensorflow.python.util.tf_export import tf_export + + +@tf_export(v1=["train.AdamOptimizer"]) +class AdamOptimizer(optimizer.Optimizer): + """Optimizer that implements the Adam algorithm. + + References: + Adam - A Method for Stochastic Optimization: + [Kingma et al., 2015](https://arxiv.org/abs/1412.6980) + ([pdf](https://arxiv.org/pdf/1412.6980.pdf)) + + @compatibility(TF2) + tf.compat.v1.train.AdamOptimizer is compatible with eager mode and + `tf.function`. + When eager execution is enabled, `learning_rate`, `beta1`, `beta2`, and + `epsilon` can each be a callable that takes no arguments and returns the + actual value to use. This can be useful for changing these values across + different invocations of optimizer functions. + + To switch to native TF2 style, use [`tf.keras.optimizers.Adam`] + (https://www.tensorflow.org/api_docs/python/tf/keras/optimizers/Adam) + instead. Please notice that due to the implementation differences, + `tf.keras.optimizers.Adam` and + `tf.compat.v1.train.AdamOptimizer` may have slight differences in + floating point numerics even though the formula used for the variable + updates still matches. + + #### Structural Mapping to Native TF2 + + Before: + + ```python + optimizer = tf.compat.v1.train.AdamOptimizer(learning_rate=0.001) + ``` + + After: + + ```python + optimizer = tf.keras.optimizers.Adam(learning_rate=0.001) + ``` + + #### How to Map Arguments + |TF1 Arg Name |TF2 Arg Name |Note | + |----------------------|-------------|----------------------| + |learning_rate |learning_rate|Be careful of setting learning_rate as a + : : : tensor value computed from the global + : : : step. In TF1 this was usually meant to + : : : imply a dynamic learning rate and would + : : : recompute in each step. In TF2 (eager + + : : : function) it will treat it as a scalar + : : : value that only gets computed once + : : : instead of a symbolic placeholder to be + : : : computed each time. : + |beta1 |beta_1 | | + |beta2 |beta_2 | | + |epsilon |epsilon | Default value is 1e-08 in TF1, but + : : : 1e-07 in TF2. : + |use_locking |N/A |Not applicable in TF2. | + + #### Before & After Usage Example + Before: + + ```python + x = tf.Variable([1,2,3], dtype=tf.float32) + grad = tf.constant([0.1, 0.2, 0.3]) + optimizer = tf.compat.v1.train.AdamOptimizer(learning_rate=0.001) + optimizer.apply_gradients(zip([grad], [x])) + ``` + + After: + + ```python + x = tf.Variable([1,2,3], dtype=tf.float32) + grad = tf.constant([0.1, 0.2, 0.3]) + optimizer = tf.keras.optimizers.Adam(learning_rate=0.001) + optimizer.apply_gradients(zip([grad], [x])) + ``` + + @end_compatibility + """ + + def __init__(self, + learning_rate=0.001, + beta1=0.9, + beta2=0.999, + epsilon=1e-8, + use_locking=False, + name="Adam"): + r"""Construct a new Adam optimizer. + + Initialization: + + $$m_0 := 0 \text{(Initialize initial 1st moment vector)}$$ + $$v_0 := 0 \text{(Initialize initial 2nd moment vector)}$$ + $$t := 0 \text{(Initialize timestep)}$$ + + The update rule for `variable` with gradient `g` uses an optimization + described at the end of section 2 of the paper: + + $$t := t + 1$$ + $$\text{lr}_t := \mathrm{learning_rate} * + \sqrt{1 - \beta_2^t} / (1 - \beta_1^t)$$ + + $$m_t := \beta_1 * m_{t-1} + (1 - \beta_1) * g$$ + $$v_t := \beta_2 * v_{t-1} + (1 - \beta_2) * g * g$$ + $$\text{variable} := \text{variable} - + \text{lr}_t * m_t / (\sqrt{v_t} + \epsilon)$$ + + The default value of 1e-8 for epsilon might not be a good default in + general. For example, when training an Inception network on ImageNet a + current good choice is 1.0 or 0.1. Note that since AdamOptimizer uses the + formulation just before Section 2.1 of the Kingma and Ba paper rather than + the formulation in Algorithm 1, the "epsilon" referred to here is "epsilon + hat" in the paper. + + The sparse implementation of this algorithm (used when the gradient is an + IndexedSlices object, typically because of `tf.gather` or an embedding + lookup in the forward pass) does apply momentum to variable slices even if + they were not used in the forward pass (meaning they have a gradient equal + to zero). Momentum decay (beta1) is also applied to the entire momentum + accumulator. This means that the sparse behavior is equivalent to the dense + behavior (in contrast to some momentum implementations which ignore momentum + unless a variable slice was actually used). + + Args: + learning_rate: A Tensor or a floating point value. The learning rate. + beta1: A float value or a constant float tensor. The exponential decay + rate for the 1st moment estimates. + beta2: A float value or a constant float tensor. The exponential decay + rate for the 2nd moment estimates. + epsilon: A small constant for numerical stability. This epsilon is + "epsilon hat" in the Kingma and Ba paper (in the formula just before + Section 2.1), not the epsilon in Algorithm 1 of the paper. + use_locking: If True use locks for update operations. + name: Optional name for the operations created when applying gradients. + Defaults to "Adam". + + + """ + + super(AdamOptimizer, self).__init__(use_locking, name) + self._lr = learning_rate + self._beta1 = beta1 + self._beta2 = beta2 + self._epsilon = epsilon + + # Tensor versions of the constructor arguments, created in _prepare(). + self._lr_t = None + self._beta1_t = None + self._beta2_t = None + self._epsilon_t = None + + def _get_beta_accumulators(self): + with ops.init_scope(): + if context.executing_eagerly(): + graph = None + else: + graph = ops.get_default_graph() + return (self._get_non_slot_variable("beta1_power", graph=graph), + self._get_non_slot_variable("beta2_power", graph=graph)) + + def _create_slots(self, var_list): + # Create the beta1 and beta2 accumulators on the same device as the first + # variable. Sort the var_list to make sure this device is consistent across + # workers (these need to go on the same PS, otherwise some updates are + # silently ignored). + first_var = min(var_list, key=lambda x: x.name) + self._create_non_slot_variable( + initial_value=self._beta1, name="beta1_power", colocate_with=first_var) + self._create_non_slot_variable( + initial_value=self._beta2, name="beta2_power", colocate_with=first_var) + + # Create slots for the first and second moments. + for v in var_list: + self._zeros_slot(v, "m", self._name) + self._zeros_slot(v, "v", self._name) + + def _prepare(self): + lr = self._call_if_callable(self._lr) + beta1 = self._call_if_callable(self._beta1) + beta2 = self._call_if_callable(self._beta2) + epsilon = self._call_if_callable(self._epsilon) + + self._lr_t = ops.convert_to_tensor(lr, name="learning_rate") + self._beta1_t = ops.convert_to_tensor(beta1, name="beta1") + self._beta2_t = ops.convert_to_tensor(beta2, name="beta2") + self._epsilon_t = ops.convert_to_tensor(epsilon, name="epsilon") + + def _apply_dense(self, grad, var): + m = self.get_slot(var, "m") + v = self.get_slot(var, "v") + beta1_power, beta2_power = self._get_beta_accumulators() + return training_ops.apply_adam( + var, + m, + v, + math_ops.cast(beta1_power, var.dtype.base_dtype), + math_ops.cast(beta2_power, var.dtype.base_dtype), + math_ops.cast(self._lr_t, var.dtype.base_dtype), + math_ops.cast(self._beta1_t, var.dtype.base_dtype), + math_ops.cast(self._beta2_t, var.dtype.base_dtype), + math_ops.cast(self._epsilon_t, var.dtype.base_dtype), + grad, + use_locking=self._use_locking).op + + def _resource_apply_dense(self, grad, var): + m = self.get_slot(var, "m") + v = self.get_slot(var, "v") + beta1_power, beta2_power = self._get_beta_accumulators() + return training_ops.resource_apply_adam( + var.handle, + m.handle, + v.handle, + math_ops.cast(beta1_power, grad.dtype.base_dtype), + math_ops.cast(beta2_power, grad.dtype.base_dtype), + math_ops.cast(self._lr_t, grad.dtype.base_dtype), + math_ops.cast(self._beta1_t, grad.dtype.base_dtype), + math_ops.cast(self._beta2_t, grad.dtype.base_dtype), + math_ops.cast(self._epsilon_t, grad.dtype.base_dtype), + grad, + use_locking=self._use_locking) + + def _apply_sparse_shared(self, grad, var, indices, scatter_add): + beta1_power, beta2_power = self._get_beta_accumulators() + beta1_power = math_ops.cast(beta1_power, var.dtype.base_dtype) + beta2_power = math_ops.cast(beta2_power, var.dtype.base_dtype) + lr_t = math_ops.cast(self._lr_t, var.dtype.base_dtype) + beta1_t = math_ops.cast(self._beta1_t, var.dtype.base_dtype) + beta2_t = math_ops.cast(self._beta2_t, var.dtype.base_dtype) + epsilon_t = math_ops.cast(self._epsilon_t, var.dtype.base_dtype) + lr = (lr_t * math_ops.sqrt(1 - beta2_power) / (1 - beta1_power)) + # m_t = beta1 * m + (1 - beta1) * g_t + m = self.get_slot(var, "m") + m_scaled_g_values = grad * (1 - beta1_t) + m_t = state_ops.assign(m, m * beta1_t, use_locking=self._use_locking) + with ops.control_dependencies([m_t]): + m_t = scatter_add(m, indices, m_scaled_g_values) + # v_t = beta2 * v + (1 - beta2) * (g_t * g_t) + v = self.get_slot(var, "v") + v_scaled_g_values = (grad * grad) * (1 - beta2_t) + v_t = state_ops.assign(v, v * beta2_t, use_locking=self._use_locking) + with ops.control_dependencies([v_t]): + v_t = scatter_add(v, indices, v_scaled_g_values) + v_sqrt = math_ops.sqrt(v_t) + var_update = state_ops.assign_sub( + var, lr * m_t / (v_sqrt + epsilon_t), use_locking=self._use_locking) + return control_flow_ops.group(*[var_update, m_t, v_t]) + + def _apply_sparse(self, grad, var): + return self._apply_sparse_shared( + grad.values, + var, + grad.indices, + lambda x, i, v: state_ops.scatter_add( # pylint: disable=g-long-lambda + x, + i, + v, + use_locking=self._use_locking)) + + def _resource_scatter_add(self, x, i, v): + with ops.control_dependencies( + [resource_variable_ops.resource_scatter_add(x.handle, i, v)]): + return x.value() + + def _resource_apply_sparse(self, grad, var, indices): + return self._apply_sparse_shared(grad, var, indices, + self._resource_scatter_add) + + def _finish(self, update_ops, name_scope): + # Update the power accumulators. + with ops.control_dependencies(update_ops): + beta1_power, beta2_power = self._get_beta_accumulators() + with ops.colocate_with(beta1_power): + update_beta1 = beta1_power.assign( + beta1_power * self._beta1_t, use_locking=self._use_locking) + update_beta2 = beta2_power.assign( + beta2_power * self._beta2_t, use_locking=self._use_locking) + return control_flow_ops.group( + *update_ops + [update_beta1, update_beta2], name=name_scope) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/basic_loops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/basic_loops.py new file mode 100644 index 0000000000000000000000000000000000000000..7ca5eee9c2ff990771b3fbbb82a96ccaf4b7becd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/basic_loops.py @@ -0,0 +1,61 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Basic loop for training.""" +from tensorflow.python.framework import errors +from tensorflow.python.util.tf_export import tf_export + + +@tf_export(v1=["train.basic_train_loop"]) +def basic_train_loop(supervisor, + train_step_fn, + args=None, + kwargs=None, + master=""): + """Basic loop to train a model. + + Calls `train_step_fn` in a loop to train a model. The function is called as: + + ```python + train_step_fn(session, *args, **kwargs) + ``` + + It is passed a `tf.compat.v1.Session` in addition to `args` and `kwargs`. The + function + typically runs one training step in the session. + + Args: + supervisor: `tf.compat.v1.train.Supervisor` to run the training services. + train_step_fn: Callable to execute one training step. Called repeatedly as + `train_step_fn(session, *args **kwargs)`. + args: Optional positional arguments passed to `train_step_fn`. + kwargs: Optional keyword arguments passed to `train_step_fn`. + master: Master to use to create the training session. Defaults to `""` + which causes the session to be created in the local process. + """ + if args is None: + args = [] + if kwargs is None: + kwargs = {} + should_retry = True + while should_retry: + try: + should_retry = False + with supervisor.managed_session(master) as sess: + while not supervisor.should_stop(): + train_step_fn(sess, *args, **kwargs) + except errors.AbortedError: + # Always re-run on AbortedError as it indicates a restart of one of the + # distributed tensorflow servers. + should_retry = True diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/basic_session_run_hooks.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/basic_session_run_hooks.py new file mode 100644 index 0000000000000000000000000000000000000000..91951bb9da4df674d9bdb3fe6c9923414886e920 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/basic_session_run_hooks.py @@ -0,0 +1,1118 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Some common SessionRunHook classes. + +Note that the symbols that are exported to v1 tf.train namespace are also +exported to v2 in tf.estimator namespace. See +https://github.com/tensorflow/estimator/blob/master/tensorflow_estimator/python/estimator/hooks/basic_session_run_hooks.py +""" + +import os +import time + +import numpy as np + +from tensorflow.core.framework.summary_pb2 import Summary +from tensorflow.core.protobuf import config_pb2 +from tensorflow.core.util.event_pb2 import SessionLog +from tensorflow.python.client import timeline +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors +from tensorflow.python.framework import meta_graph +from tensorflow.python.framework import ops +from tensorflow.python.ops import init_ops +from tensorflow.python.ops import variable_scope +from tensorflow.python.platform import gfile +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.training import session_run_hook +from tensorflow.python.training import training_util +from tensorflow.python.training.session_run_hook import SessionRunArgs +from tensorflow.python.training.summary_io import SummaryWriterCache +from tensorflow.python.util.tf_export import tf_export + +_HOOKS = "hooks" +_STEPS_PER_RUN_VAR = "steps_per_run" + + +class _HookTimer: + """Base timer for determining when Hooks should trigger. + + Should not be instantiated directly. + """ + + def __init__(self): + pass + + def reset(self): + """Resets the timer.""" + pass + + def should_trigger_for_step(self, step): + """Return true if the timer should trigger for the specified step.""" + raise NotImplementedError + + def update_last_triggered_step(self, step): + """Update the last triggered time and step number. + + Args: + step: The current step. + + Returns: + A pair `(elapsed_time, elapsed_steps)`, where `elapsed_time` is the number + of seconds between the current trigger and the last one (a float), and + `elapsed_steps` is the number of steps between the current trigger and + the last one. Both values will be set to `None` on the first trigger. + """ + raise NotImplementedError + + def last_triggered_step(self): + """Returns the last triggered time step or None if never triggered.""" + raise NotImplementedError + + +@tf_export(v1=["train.SecondOrStepTimer"]) +class SecondOrStepTimer(_HookTimer): + """Timer that triggers at most once every N seconds or once every N steps. + + This symbol is also exported to v2 in tf.estimator namespace. See + https://github.com/tensorflow/estimator/blob/master/tensorflow_estimator/python/estimator/hooks/basic_session_run_hooks.py + """ + + def __init__(self, every_secs=None, every_steps=None): + self.reset() + self._every_secs = every_secs + self._every_steps = every_steps + + if self._every_secs is None and self._every_steps is None: + raise ValueError("Either every_secs or every_steps should be provided.") + if (self._every_secs is not None) and (self._every_steps is not None): + raise ValueError("Can not provide both every_secs and every_steps.") + + super(SecondOrStepTimer, self).__init__() + + def reset(self): + self._last_triggered_step = None + self._last_triggered_time = None + + def should_trigger_for_step(self, step): + """Return true if the timer should trigger for the specified step. + + Args: + step: Training step to trigger on. + + Returns: + True if the difference between the current time and the time of the last + trigger exceeds `every_secs`, or if the difference between the current + step and the last triggered step exceeds `every_steps`. False otherwise. + """ + if self._last_triggered_step is None: + return True + + if self._last_triggered_step == step: + return False + + if self._every_secs is not None: + if time.time() >= self._last_triggered_time + self._every_secs: + return True + + if self._every_steps is not None: + if step >= self._last_triggered_step + self._every_steps: + return True + + return False + + def update_last_triggered_step(self, step): + current_time = time.time() + if self._last_triggered_time is None: + elapsed_secs = None + elapsed_steps = None + else: + elapsed_secs = current_time - self._last_triggered_time + elapsed_steps = step - self._last_triggered_step + + self._last_triggered_time = current_time + self._last_triggered_step = step + return (elapsed_secs, elapsed_steps) + + def last_triggered_step(self): + return self._last_triggered_step + + +class NeverTriggerTimer(_HookTimer): + """Timer that never triggers.""" + + def should_trigger_for_step(self, step): + _ = step + return False + + def update_last_triggered_step(self, step): + _ = step + return (None, None) + + def last_triggered_step(self): + return None + + +@tf_export(v1=["train.LoggingTensorHook"]) +class LoggingTensorHook(session_run_hook.SessionRunHook): + """Prints the given tensors every N local steps, every N seconds, or at end. + + The tensors will be printed to the log, with `INFO` severity. If you are not + seeing the logs, you might want to add the following line after your imports: + + ```python + tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.INFO) + ``` + + Note that if `at_end` is True, `tensors` should not include any tensor + whose evaluation produces a side effect such as consuming additional inputs. + + @compatibility(TF2) + Please check this [notebook][notebook] on how to migrate the API to TF2. + + [notebook]:https://github.com/tensorflow/docs/blob/master/site/en/guide/migrate/logging_stop_hook.ipynb + + @end_compatibility + + """ + + def __init__(self, + tensors, + every_n_iter=None, + every_n_secs=None, + at_end=False, + formatter=None): + """Initializes a `LoggingTensorHook`. + + Args: + tensors: `dict` that maps string-valued tags to tensors/tensor names, or + `iterable` of tensors/tensor names. + every_n_iter: `int`, print the values of `tensors` once every N local + steps taken on the current worker. + every_n_secs: `int` or `float`, print the values of `tensors` once every N + seconds. Exactly one of `every_n_iter` and `every_n_secs` should be + provided. + at_end: `bool` specifying whether to print the values of `tensors` at the + end of the run. + formatter: function, takes dict of `tag`->`Tensor` and returns a string. + If `None` uses default printing all tensors. + + Raises: + ValueError: if `every_n_iter` is non-positive. + """ + only_log_at_end = ( + at_end and (every_n_iter is None) and (every_n_secs is None)) + if (not only_log_at_end and + (every_n_iter is None) == (every_n_secs is None)): + raise ValueError( + "either at_end and/or exactly one of every_n_iter and every_n_secs " + "must be provided.") + if every_n_iter is not None and every_n_iter <= 0: + raise ValueError("invalid every_n_iter=%s." % every_n_iter) + if not isinstance(tensors, dict): + self._tag_order = tensors + tensors = {item: item for item in tensors} + else: + self._tag_order = sorted(tensors.keys()) + self._tensors = tensors + self._formatter = formatter + self._timer = ( + NeverTriggerTimer() if only_log_at_end else SecondOrStepTimer( + every_secs=every_n_secs, every_steps=every_n_iter)) + self._log_at_end = at_end + + def begin(self): + self._timer.reset() + self._iter_count = 0 + # Convert names to tensors if given + self._current_tensors = { + tag: _as_graph_element(tensor) + for (tag, tensor) in self._tensors.items() + } + + def before_run(self, run_context): # pylint: disable=unused-argument + self._should_trigger = self._timer.should_trigger_for_step(self._iter_count) + if self._should_trigger: + return SessionRunArgs(self._current_tensors) + else: + return None + + def _log_tensors(self, tensor_values): + original = np.get_printoptions() + np.set_printoptions(suppress=True) + elapsed_secs, _ = self._timer.update_last_triggered_step(self._iter_count) + if self._formatter: + logging.info(self._formatter(tensor_values)) + else: + stats = [] + for tag in self._tag_order: + stats.append("%s = %s" % (tag, tensor_values[tag])) + if elapsed_secs is not None: + logging.info("%s (%.3f sec)", ", ".join(stats), elapsed_secs) + else: + logging.info("%s", ", ".join(stats)) + np.set_printoptions(**original) + + def after_run(self, run_context, run_values): + _ = run_context + if self._should_trigger: + self._log_tensors(run_values.results) + + self._iter_count += 1 + + def end(self, session): + if self._log_at_end: + values = session.run(self._current_tensors) + self._log_tensors(values) + + +def get_or_create_steps_per_run_variable(): + """Gets or creates the steps_per_run variable. + + In Estimator, the user provided computation, the model_fn, is wrapped + inside a tf.while_loop for peak performance. The iterations of the loop are + specified by this variable, which adjusts its value on the CPU after each + device program execution and before the next execution. + + The purpose of using a variable, rather than a constant, is to allow + Estimator adapt the device training iterations according to the final steps + specified by users. For example, if the user sets the steps_per_run as + 4 and steps as 10 in Estimator.train(), the steps_per_run + variable will have the following value before each training run. + + - 1-st execution: steps_per_run = 4 + - 2-nd execution: steps_per_run = 4 + - 3-rd execution: steps_per_run = 2 + + As model_fn increases the global step once per train_op invocation, the global + step is 10 after all executions, matching the steps=10 inputs passed in by + users. + + Returns: + A TF non-trainable resource variable. + + Raises: + RuntimeError: If multi steps_per_run variables were found. + """ + graph = ops.get_default_graph() + collection_name = "{}_{}".format(_HOOKS, _STEPS_PER_RUN_VAR) + steps_per_run_vars = graph.get_collection(collection_name) + if len(steps_per_run_vars) == 1: + return steps_per_run_vars[0] + elif len(steps_per_run_vars) > 1: + raise RuntimeError("Multiple steps_per_run_var in collection.") + + with variable_scope.variable_scope(_HOOKS, reuse=variable_scope.AUTO_REUSE): + return variable_scope.get_variable( + _STEPS_PER_RUN_VAR, + initializer=init_ops.ones_initializer(), + shape=[], + dtype=dtypes.int32, + trainable=False, + collections=[collection_name, ops.GraphKeys.LOCAL_VARIABLES], + use_resource=True) + + +class _MultiStepStopAtStepHook(session_run_hook.SessionRunHook): + """Hook that requests stop at a specified step.""" + + def __init__(self, num_steps=None, last_step=None, steps_per_run=1): + """Initializes a `MultiStepStopAtStepHook`. + + This hook requests stop after either a number of steps have been + executed or a last step has been reached. Only one of the two options can be + specified. + + if `num_steps` is specified, it indicates the number of steps to execute + after `begin()` is called. If instead `last_step` is specified, it + indicates the last step we want to execute, as passed to the `after_run()` + call. + + In Estimator, the user provided computation, the model_fn, is wrapped + inside a tf.while_loop for peak performance. The steps_per_run variable + determines the number of iterations of the loop before returning to the CPU. + + Args: + num_steps: Number of steps to execute. + last_step: Step after which to stop. + steps_per_run: Number of steps executed per run call. + + Raises: + ValueError: If one of the arguments is invalid. + """ + if num_steps is None and last_step is None: + raise ValueError("One of num_steps or last_step must be specified.") + if num_steps is not None and last_step is not None: + raise ValueError("Only one of num_steps or last_step can be specified.") + if steps_per_run is None or steps_per_run < 1: + raise ValueError("steps_per_run should be greater than 0") + self._num_steps = num_steps + self._last_step = last_step + self._steps_per_run_initial_value = steps_per_run + + def begin(self): + self._global_step_tensor = training_util.get_global_step() + if self._global_step_tensor is None: + raise RuntimeError("Global step should be created to use StopAtStepHook.") + self._steps_per_run_variable = get_or_create_steps_per_run_variable() + + def _update_steps_per_run_variable(self, global_step, session): + steps = min(self._last_step - global_step, + self._steps_per_run_initial_value) + self._steps_per_run_variable.load(steps, session=session) + + def after_create_session(self, session, coord): + global_step = session.run(self._global_step_tensor) + if self._last_step is None: + self._last_step = global_step + self._num_steps + self._update_steps_per_run_variable(global_step, session) + + def after_run(self, run_context, run_values): + # Global step cannot be retrieved via SessionRunArgs and before_run due to + # race condition in hook execution. + global_step = run_context.session.run(self._global_step_tensor) + if global_step >= self._last_step: + run_context.request_stop() + else: + self._update_steps_per_run_variable(global_step, run_context.session) + + +@tf_export(v1=["train.StopAtStepHook"]) +class StopAtStepHook(session_run_hook.SessionRunHook): + """Hook that requests stop at a specified step. + + @compatibility(TF2) + Please check this [notebook][notebook] on how to migrate the API to TF2. + + [notebook]:https://github.com/tensorflow/docs/blob/master/site/en/guide/migrate/logging_stop_hook.ipynb + + @end_compatibility + """ + + def __init__(self, num_steps=None, last_step=None): + """Initializes a `StopAtStepHook`. + + This hook requests stop after either a number of steps have been + executed or a last step has been reached. Only one of the two options can be + specified. + + if `num_steps` is specified, it indicates the number of steps to execute + after `begin()` is called. If instead `last_step` is specified, it + indicates the last step we want to execute, as passed to the `after_run()` + call. + + Args: + num_steps: Number of steps to execute. + last_step: Step after which to stop. + + Raises: + ValueError: If one of the arguments is invalid. + """ + if num_steps is None and last_step is None: + raise ValueError("One of num_steps or last_step must be specified.") + if num_steps is not None and last_step is not None: + raise ValueError("Only one of num_steps or last_step can be specified.") + self._num_steps = num_steps + self._last_step = last_step + + def begin(self): + self._global_step_tensor = training_util._get_or_create_global_step_read() # pylint: disable=protected-access + if self._global_step_tensor is None: + raise RuntimeError("Global step should be created to use StopAtStepHook.") + + def after_create_session(self, session, coord): + if self._last_step is None: + global_step = session.run(self._global_step_tensor) + self._last_step = global_step + self._num_steps + + def before_run(self, run_context): # pylint: disable=unused-argument + return SessionRunArgs(self._global_step_tensor) + + def after_run(self, run_context, run_values): + global_step = run_values.results + 1 + if global_step >= self._last_step: + # Check latest global step to ensure that the targeted last step is + # reached. global_step read tensor is the value of global step + # before running the operation. We're not sure whether current session.run + # incremented the global_step or not. Here we're checking it. + + step = run_context.session.run(self._global_step_tensor) + if step >= self._last_step: + run_context.request_stop() + + +@tf_export(v1=["train.CheckpointSaverListener"]) +class CheckpointSaverListener: + """Interface for listeners that take action before or after checkpoint save. + + `CheckpointSaverListener` triggers only in steps when `CheckpointSaverHook` is + triggered, and provides callbacks at the following points: + - before using the session + - before each call to `Saver.save()` + - after each call to `Saver.save()` + - at the end of session + + To use a listener, implement a class and pass the listener to a + `CheckpointSaverHook`, as in this example: + + ```python + class ExampleCheckpointSaverListener(CheckpointSaverListener): + def begin(self): + # You can add ops to the graph here. + print('Starting the session.') + self.your_tensor = ... + + def before_save(self, session, global_step_value): + print('About to write a checkpoint') + + def after_save(self, session, global_step_value): + print('Done writing checkpoint.') + if decided_to_stop_training(): + return True + + def end(self, session, global_step_value): + print('Done with the session.') + + ... + listener = ExampleCheckpointSaverListener() + saver_hook = tf.estimator.CheckpointSaverHook( + checkpoint_dir, listeners=[listener]) + with + tf.compat.v1.train.MonitoredTrainingSession(chief_only_hooks=[saver_hook]): + ... + ``` + + A `CheckpointSaverListener` may simply take some action after every + checkpoint save. It is also possible for the listener to use its own schedule + to act less frequently, e.g. based on global_step_value. In this case, + implementors should implement the `end()` method to handle actions related to + the last checkpoint save. But the listener should not act twice if + `after_save()` already handled this last checkpoint save. + + A `CheckpointSaverListener` can request training to be stopped, by returning + True in `after_save`. Please note that, in replicated distributed training + setting, only `chief` should use this behavior. Otherwise each worker will do + their own evaluation, which may be wasteful of resources. + """ + + def begin(self): + pass + + def before_save(self, session, global_step_value): + pass + + def after_save(self, session, global_step_value): + pass + + def end(self, session, global_step_value): + pass + + +@tf_export(v1=["train.CheckpointSaverHook"]) +class CheckpointSaverHook(session_run_hook.SessionRunHook): + """Saves checkpoints every N steps or seconds.""" + + def __init__(self, + checkpoint_dir, + save_secs=None, + save_steps=None, + saver=None, + checkpoint_basename="model.ckpt", + scaffold=None, + listeners=None, + save_graph_def=True): + """Initializes a `CheckpointSaverHook`. + + Args: + checkpoint_dir: `str`, base directory for the checkpoint files. + save_secs: `int`, save every N secs. + save_steps: `int`, save every N steps. + saver: `Saver` object, used for saving. + checkpoint_basename: `str`, base name for the checkpoint files. + scaffold: `Scaffold`, use to get saver object. + listeners: List of `CheckpointSaverListener` subclass instances. Used for + callbacks that run immediately before or after this hook saves the + checkpoint. + save_graph_def: Whether to save the GraphDef and MetaGraphDef to + `checkpoint_dir`. The GraphDef is saved after the session is created as + `graph.pbtxt`. MetaGraphDefs are saved out for every checkpoint as + `model.ckpt-*.meta`. + + Raises: + ValueError: One of `save_steps` or `save_secs` should be set. + ValueError: At most one of `saver` or `scaffold` should be set. + """ + logging.info("Create CheckpointSaverHook.") + if saver is not None and scaffold is not None: + raise ValueError("You cannot provide both saver and scaffold.") + self._saver = saver + self._checkpoint_dir = checkpoint_dir + self._save_path = os.path.join(checkpoint_dir, checkpoint_basename) + self._scaffold = scaffold + self._timer = SecondOrStepTimer( + every_secs=save_secs, every_steps=save_steps) + self._listeners = listeners or [] + # Set sufficiently high default that it never skips checking the actual + # global step counter -- unless the user overrides it with the right value + # for the steps_per_run. + self._steps_per_run = 1000000 + self._save_graph_def = save_graph_def + + def _set_steps_per_run(self, steps_per_run): + self._steps_per_run = steps_per_run + + def begin(self): + self._summary_writer = SummaryWriterCache.get(self._checkpoint_dir) + self._global_step_tensor = training_util._get_or_create_global_step_read() # pylint: disable=protected-access + if self._global_step_tensor is None: + raise RuntimeError( + "Global step should be created to use CheckpointSaverHook.") + for l in self._listeners: + l.begin() + + def after_create_session(self, session, coord): + global_step = session.run(self._global_step_tensor) + if self._save_graph_def: + # We do write graph and saver_def at the first call of before_run. + # We cannot do this in begin, since we let other hooks to change graph and + # add variables in begin. Graph is finalized after all begin calls. + training_util.write_graph( + ops.get_default_graph().as_graph_def(add_shapes=True), + self._checkpoint_dir, "graph.pbtxt") + saver_def = self._get_saver().saver_def if self._get_saver() else None + graph = ops.get_default_graph() + meta_graph_def = meta_graph.create_meta_graph_def( + graph_def=graph.as_graph_def(add_shapes=True), saver_def=saver_def) + self._summary_writer.add_graph(graph) + self._summary_writer.add_meta_graph(meta_graph_def) + # The checkpoint saved here is the state at step "global_step". + self._save(session, global_step) + self._timer.update_last_triggered_step(global_step) + + def before_run(self, run_context): # pylint: disable=unused-argument + return SessionRunArgs(self._global_step_tensor) + + def after_run(self, run_context, run_values): + stale_global_step = run_values.results + if self._timer.should_trigger_for_step(stale_global_step + + self._steps_per_run): + # get the real value after train op. + global_step = run_context.session.run(self._global_step_tensor) + if self._timer.should_trigger_for_step(global_step): + self._timer.update_last_triggered_step(global_step) + if self._save(run_context.session, global_step): + run_context.request_stop() + + def end(self, session): + last_step = session.run(self._global_step_tensor) + if last_step != self._timer.last_triggered_step(): + self._save(session, last_step) + for l in self._listeners: + l.end(session, last_step) + + def _save(self, session, step): + """Saves the latest checkpoint, returns should_stop.""" + logging.info("Calling checkpoint listeners before saving checkpoint %d...", + step) + for l in self._listeners: + l.before_save(session, step) + + logging.info("Saving checkpoints for %d into %s.", step, self._save_path) + self._get_saver().save(session, self._save_path, global_step=step, + write_meta_graph=self._save_graph_def) + self._summary_writer.add_session_log( + SessionLog( + status=SessionLog.CHECKPOINT, checkpoint_path=self._save_path), + step) + logging.info("Calling checkpoint listeners after saving checkpoint %d...", + step) + should_stop = False + for l in self._listeners: + if l.after_save(session, step): + logging.info( + "A CheckpointSaverListener requested that training be stopped. " + "listener: {}".format(l)) + should_stop = True + return should_stop + + def _get_saver(self): + if self._saver is not None: + return self._saver + elif self._scaffold is not None: + return self._scaffold.saver + + # Get saver from the SAVERS collection if present. + collection_key = ops.GraphKeys.SAVERS + savers = ops.get_collection(collection_key) + if not savers: + raise RuntimeError( + "No items in collection {}. Please add a saver to the collection " + "or provide a saver or scaffold.".format(collection_key)) + elif len(savers) > 1: + raise RuntimeError( + "More than one item in collection {}. " + "Please indicate which one to use by passing it to the constructor." + .format(collection_key)) + + self._saver = savers[0] + return savers[0] + + +@tf_export(v1=["train.StepCounterHook"]) +class StepCounterHook(session_run_hook.SessionRunHook): + """Hook that counts steps per second.""" + + def __init__(self, + every_n_steps=100, + every_n_secs=None, + output_dir=None, + summary_writer=None): + + if (every_n_steps is None) == (every_n_secs is None): + raise ValueError( + "exactly one of every_n_steps and every_n_secs should be provided.") + self._timer = SecondOrStepTimer( + every_steps=every_n_steps, every_secs=every_n_secs) + + self._summary_writer = summary_writer + self._output_dir = output_dir + self._last_global_step = None + self._steps_per_run = 1 + + def _set_steps_per_run(self, steps_per_run): + self._steps_per_run = steps_per_run + + def begin(self): + if self._summary_writer is None and self._output_dir: + self._summary_writer = SummaryWriterCache.get(self._output_dir) + self._global_step_tensor = training_util._get_or_create_global_step_read() # pylint: disable=protected-access + if self._global_step_tensor is None: + raise RuntimeError( + "Global step should be created to use StepCounterHook.") + self._summary_tag = training_util.get_global_step().op.name + "/sec" + + def before_run(self, run_context): # pylint: disable=unused-argument + return SessionRunArgs(self._global_step_tensor) + + def _log_and_record(self, elapsed_steps, elapsed_time, global_step): + steps_per_sec = elapsed_steps / elapsed_time + if self._summary_writer is not None: + summary = Summary(value=[ + Summary.Value(tag=self._summary_tag, simple_value=steps_per_sec) + ]) + self._summary_writer.add_summary(summary, global_step) + logging.info("%s: %g", self._summary_tag, steps_per_sec) + + def after_run(self, run_context, run_values): + _ = run_context + + stale_global_step = run_values.results + if self._timer.should_trigger_for_step(stale_global_step + + self._steps_per_run): + # get the real value after train op. + global_step = run_context.session.run(self._global_step_tensor) + if self._timer.should_trigger_for_step(global_step): + elapsed_time, elapsed_steps = self._timer.update_last_triggered_step( + global_step) + if elapsed_time is not None: + self._log_and_record(elapsed_steps, elapsed_time, global_step) + + # Check whether the global step has been increased. Here, we do not use the + # timer.last_triggered_step as the timer might record a different global + # step value such that the comparison could be unreliable. For simplicity, + # we just compare the stale_global_step with previously recorded version. + if stale_global_step == self._last_global_step: + # Here, we give a warning in the first 5 times if we have observed that + # the global step has not been increased. For some Optimizers, the global + # step is not increased each time by design. For example, + # SyncReplicaOptimizer doesn't increase the global step in worker's main + # train step. + logging.log_first_n( + logging.WARN, + "It seems that global step (tf.train.get_global_step) has not " + "been increased. Current value (could be stable): %s vs previous " + "value: %s. You could increase the global step by passing " + "tf.train.get_global_step() to Optimizer.apply_gradients or " + "Optimizer.minimize.", 5, stale_global_step, self._last_global_step) + + self._last_global_step = stale_global_step + + +@tf_export(v1=["train.NanLossDuringTrainingError"]) +class NanLossDuringTrainingError(RuntimeError): + + def __str__(self): + return "NaN loss during training." + + +@tf_export(v1=["train.NanTensorHook"]) +class NanTensorHook(session_run_hook.SessionRunHook): + """Monitors the loss tensor and stops training if loss is NaN. + + Can either fail with exception or just stop training. + """ + + def __init__(self, loss_tensor, fail_on_nan_loss=True): + """Initializes a `NanTensorHook`. + + Args: + loss_tensor: `Tensor`, the loss tensor. + fail_on_nan_loss: `bool`, whether to raise exception when loss is NaN. + """ + self._loss_tensor = loss_tensor + self._fail_on_nan_loss = fail_on_nan_loss + + def before_run(self, run_context): # pylint: disable=unused-argument + return SessionRunArgs(self._loss_tensor) + + def after_run(self, run_context, run_values): + if np.isnan(run_values.results): + failure_message = "Model diverged with loss = NaN." + if self._fail_on_nan_loss: + logging.error(failure_message) + raise NanLossDuringTrainingError + else: + logging.warning(failure_message) + # We don't raise an error but we request stop without an exception. + run_context.request_stop() + + +@tf_export(v1=["train.SummarySaverHook"]) +class SummarySaverHook(session_run_hook.SessionRunHook): + """Saves summaries every N steps.""" + + def __init__(self, + save_steps=None, + save_secs=None, + output_dir=None, + summary_writer=None, + scaffold=None, + summary_op=None): + """Initializes a `SummarySaverHook`. + + Args: + save_steps: `int`, save summaries every N steps. Exactly one of + `save_secs` and `save_steps` should be set. + save_secs: `int`, save summaries every N seconds. + output_dir: `string`, the directory to save the summaries to. Only used if + no `summary_writer` is supplied. + summary_writer: `SummaryWriter`. If `None` and an `output_dir` was passed, + one will be created accordingly. + scaffold: `Scaffold` to get summary_op if it's not provided. + summary_op: `Tensor` of type `string` containing the serialized `Summary` + protocol buffer or a list of `Tensor`. They are most likely an output by + TF summary methods like `tf.compat.v1.summary.scalar` or + `tf.compat.v1.summary.merge_all`. It can be passed in as one tensor; if + more than one, they must be passed in as a list. + + Raises: + ValueError: Exactly one of scaffold or summary_op should be set. + """ + if ((scaffold is None and summary_op is None) or + (scaffold is not None and summary_op is not None)): + raise ValueError( + "Exactly one of scaffold or summary_op must be provided.") + self._summary_op = summary_op + self._summary_writer = summary_writer + self._output_dir = output_dir + self._scaffold = scaffold + self._timer = SecondOrStepTimer( + every_secs=save_secs, every_steps=save_steps) + # TODO(mdan): Throw an error if output_dir and summary_writer are None. + + def begin(self): + if self._summary_writer is None and self._output_dir: + self._summary_writer = SummaryWriterCache.get(self._output_dir) + self._next_step = None + self._global_step_tensor = training_util._get_or_create_global_step_read() # pylint: disable=protected-access + if self._global_step_tensor is None: + raise RuntimeError( + "Global step should be created to use SummarySaverHook.") + + def before_run(self, run_context): # pylint: disable=unused-argument + self._request_summary = ( + self._next_step is None or + self._timer.should_trigger_for_step(self._next_step)) + requests = {"global_step": self._global_step_tensor} + if self._request_summary: + if self._get_summary_op() is not None: + requests["summary"] = self._get_summary_op() + + return SessionRunArgs(requests) + + def after_run(self, run_context, run_values): + _ = run_context + if not self._summary_writer: + return + + stale_global_step = run_values.results["global_step"] + global_step = stale_global_step + 1 + if self._next_step is None or self._request_summary: + global_step = run_context.session.run(self._global_step_tensor) + + if self._next_step is None: + self._summary_writer.add_session_log( + SessionLog(status=SessionLog.START), global_step) + + if self._request_summary: + self._timer.update_last_triggered_step(global_step) + if "summary" in run_values.results: + for summary in run_values.results["summary"]: + self._summary_writer.add_summary(summary, global_step) + + self._next_step = global_step + 1 + + def end(self, session=None): + if self._summary_writer: + self._summary_writer.flush() + + def _get_summary_op(self): + """Fetches the summary op either from self._summary_op or self._scaffold. + + Returns: + Returns a list of summary `Tensor`. + """ + summary_op = None + if self._summary_op is not None: + summary_op = self._summary_op + elif self._scaffold.summary_op is not None: + summary_op = self._scaffold.summary_op + + if summary_op is None: + return None + + if not isinstance(summary_op, list): + return [summary_op] + return summary_op + + +@tf_export(v1=["train.GlobalStepWaiterHook"]) +class GlobalStepWaiterHook(session_run_hook.SessionRunHook): + """Delays execution until global step reaches `wait_until_step`. + + This hook delays execution until global step reaches to `wait_until_step`. It + is used to gradually start workers in distributed settings. One example usage + would be setting `wait_until_step=int(K*log(task_id+1))` assuming that + task_id=0 is the chief. + """ + + def __init__(self, wait_until_step): + """Initializes a `GlobalStepWaiterHook`. + + Args: + wait_until_step: an `int` shows until which global step should we wait. + """ + self._wait_until_step = wait_until_step + + def begin(self): + self._worker_is_started = False + self._global_step_tensor = training_util._get_or_create_global_step_read() # pylint: disable=protected-access + if self._global_step_tensor is None: + raise RuntimeError( + "Global step should be created to use _GlobalStepWaiterHook.") + + def before_run(self, run_context): + if self._worker_is_started: + return None + + if self._wait_until_step <= 0: + self._worker_is_started = True + return None + + logging.info("Waiting for global step %d before starting training.", + self._wait_until_step) + last_logged_step = 0 + while True: + current_step = run_context.session.run(self._global_step_tensor) + if current_step >= self._wait_until_step: + self._worker_is_started = True + return None + if current_step - last_logged_step > 1000: + logging.info( + "Waiting for global step %d before starting training. " + "Current step is %d.", self._wait_until_step, current_step) + last_logged_step = current_step + time.sleep(0.5) + + +@tf_export(v1=["train.FinalOpsHook"]) +class FinalOpsHook(session_run_hook.SessionRunHook): + """A hook which evaluates `Tensors` at the end of a session.""" + + def __init__(self, final_ops, final_ops_feed_dict=None): + """Initializes `FinalOpHook` with ops to run at the end of the session. + + Args: + final_ops: A single `Tensor`, a list of `Tensors` or a dictionary of names + to `Tensors`. + final_ops_feed_dict: A feed dictionary to use when running + `final_ops_dict`. + """ + self._final_ops = final_ops + self._final_ops_feed_dict = final_ops_feed_dict + self._final_ops_values = None + + @property + def final_ops_values(self): + return self._final_ops_values + + def end(self, session): + if self._final_ops is not None: + try: + self._final_ops_values = session.run( + self._final_ops, feed_dict=self._final_ops_feed_dict) + except (errors.OutOfRangeError, StopIteration) as e: + logging.warning( + "An OutOfRangeError or StopIteration exception is raised by the " + "code in FinalOpsHook. This typically means the Ops running by the " + "FinalOpsHook have a dependency back to some input source, which " + "should not happen. For example, for metrics in " + "tf.estimator.Estimator, all metrics functions return two Ops: " + "`value_op` and `update_op`. Estimator.evaluate calls the " + "`update_op` for each batch of the data in input source and, once " + "it is exhausted, it call the `value_op` to get the metric values. " + "The `value_op` here should have dependency back to variables " + "reading only, rather than reading another batch from input. " + "Otherwise, the `value_op`, executed by `FinalOpsHook`, triggers " + "another data reading, which ends OutOfRangeError/StopIteration. " + "Please fix that.") + raise e + + +@tf_export(v1=["train.FeedFnHook"]) +class FeedFnHook(session_run_hook.SessionRunHook): + """Runs `feed_fn` and sets the `feed_dict` accordingly.""" + + def __init__(self, feed_fn): + """Initializes a `FeedFnHook`. + + Args: + feed_fn: function that takes no arguments and returns `dict` of `Tensor` + to feed. + """ + self.feed_fn = feed_fn + + def before_run(self, run_context): # pylint: disable=unused-argument + return session_run_hook.SessionRunArgs( + fetches=None, feed_dict=self.feed_fn()) + + +@tf_export(v1=["train.ProfilerHook"]) +class ProfilerHook(session_run_hook.SessionRunHook): + """Captures CPU/GPU profiling information every N steps or seconds. + + This produces files called "timeline-.json", which are in Chrome + Trace format. + + For more information see: + https://github.com/catapult-project/catapult/blob/master/tracing/README.md + """ + + def __init__(self, + save_steps=None, + save_secs=None, + output_dir="", + show_dataflow=True, + show_memory=False): + """Initializes a hook that takes periodic profiling snapshots. + + `options.run_metadata` argument of `tf.Session.Run` is used to collect + metadata about execution. This hook sets the metadata and dumps it in Chrome + Trace format. + + + Args: + save_steps: `int`, save profile traces every N steps. Exactly one of + `save_secs` and `save_steps` should be set. + save_secs: `int` or `float`, save profile traces every N seconds. + output_dir: `string`, the directory to save the profile traces to. + Defaults to the current directory. + show_dataflow: `bool`, if True, add flow events to the trace connecting + producers and consumers of tensors. + show_memory: `bool`, if True, add object snapshot events to the trace + showing the sizes and lifetimes of tensors. + """ + self._output_file = os.path.join(output_dir, "timeline-{}.json") + self._file_writer = SummaryWriterCache.get(output_dir) + self._show_dataflow = show_dataflow + self._show_memory = show_memory + self._timer = SecondOrStepTimer( + every_secs=save_secs, every_steps=save_steps) + + def begin(self): + self._next_step = None + self._global_step_tensor = training_util._get_or_create_global_step_read() # pylint: disable=protected-access + if self._global_step_tensor is None: + raise RuntimeError("Global step should be created to use ProfilerHook.") + + def before_run(self, run_context): + self._request_summary = ( + self._next_step is not None and + self._timer.should_trigger_for_step(self._next_step)) + requests = {"global_step": self._global_step_tensor} + opts = ( + config_pb2.RunOptions(trace_level=config_pb2.RunOptions.FULL_TRACE) + if self._request_summary else None) + + return SessionRunArgs(requests, options=opts) + + def after_run(self, run_context, run_values): + stale_global_step = run_values.results["global_step"] + if self._next_step is None: + # Update the timer so that it does not activate until N steps or seconds + # have passed. + self._timer.update_last_triggered_step(stale_global_step) + global_step = stale_global_step + 1 + if self._request_summary: + global_step = run_context.session.run(self._global_step_tensor) + self._timer.update_last_triggered_step(global_step) + self._save(global_step, self._output_file.format(global_step), + run_values.run_metadata.step_stats) + self._file_writer.add_run_metadata(run_values.run_metadata, + "step_%d" % global_step) + + self._next_step = global_step + 1 + + def _save(self, step, save_path, step_stats): + logging.info("Saving timeline for %d into '%s'.", step, save_path) + with gfile.Open(save_path, "w") as f: + trace = timeline.Timeline(step_stats) + f.write( + trace.generate_chrome_trace_format( + show_dataflow=self._show_dataflow, show_memory=self._show_memory)) + + +def _as_graph_element(obj): + """Retrieves Graph element.""" + graph = ops.get_default_graph() + if not isinstance(obj, str): + if not hasattr(obj, "graph") or obj.graph != graph: + raise ValueError("Passed %s should have graph attribute that is equal " + "to current graph %s." % (obj, graph)) + return obj + if ":" in obj: + element = graph.as_graph_element(obj) + else: + element = graph.as_graph_element(obj + ":0") + # Check that there is no :1 (e.g. it's single output). + try: + graph.as_graph_element(obj + ":1") + except (KeyError, ValueError): + pass + else: + raise ValueError("Name %s is ambiguous, " + "as this `Operation` has multiple outputs " + "(at least 2)." % obj) + return element diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/checkpoint_management.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/checkpoint_management.py new file mode 100644 index 0000000000000000000000000000000000000000..80f47723d26e6544ecea7df813e7d21b87423632 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/checkpoint_management.py @@ -0,0 +1,26 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +# pylint: disable=invalid-name +"""Save and restore variables.""" + + +# TODO(kathywu): Delete this file after all imports have been moved to the path +# below. +from tensorflow.python.checkpoint import checkpoint_management +from tensorflow.python.util import deprecation + +__getattr__ = deprecation.deprecate_moved_module( + __name__, checkpoint_management, "2.9") diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/checkpoint_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/checkpoint_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..4813a8cd61b90ddd403b82dc19c7708dd4d17bd8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/checkpoint_ops.py @@ -0,0 +1,482 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Operations for generating and loading vocab remappings.""" +import math + +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gen_checkpoint_ops +from tensorflow.python.ops import init_ops +from tensorflow.python.ops import math_ops + +ops.NotDifferentiable("GenerateVocabRemapping") +ops.NotDifferentiable("LoadAndRemapMatrix") + + +def _load_and_remap_matrix(ckpt_path, + old_tensor_name, + new_row_vocab_offset, + num_rows_to_load, + new_col_vocab_size, + initializer, + old_row_vocab_size=-1, + old_row_vocab_file=None, + new_row_vocab_file=None, + old_col_vocab_file=None, + new_col_vocab_file=None, + num_row_oov_buckets=0, + num_col_oov_buckets=0, + max_rows_in_memory=-1): + """Loads a 2-D (matrix) `Tensor` from checkpoint. + + Generates 1D-remappings for rows and columns using the + `GenerateVocabRemapping` op, and initializes any anticipated values with the + provided initializer. Then, uses the `LoadAndRemapMatrix` op to create a + matrix that loads existing values from the checkpoint, while filling out + "missing" values with the newly initialized values. See + contrib/framework/ops/checkpoint_ops.cc for more information on the wrapped + functionality (LoadAndRemapMatrix). This wrapper can be used to perform only + row remapping or only col remapping. If only row remapping is desired, + {new,old}_col_vocab_file should be `None`, and vice versa for column + remapping. + + NOTE: This only supports div-partitioning the vocabulary on the 1st dimension + (row axis) via `new_row_vocab_offset`. + + Args: + ckpt_path: Path to the TensorFlow checkpoint (version 2, `TensorBundle`) + from which the old matrix `Tensor` will be loaded. + old_tensor_name: Name of the 2-D `Tensor` to load from checkpoint. + new_row_vocab_offset: A 0-indexed integer representing what line to + start reading at in the new row vocabulary. Used for partitioned + variables. + num_rows_to_load: Number of rows to load for the new vocabulary (note: to + support variable partitioning and partial loading, this does not need to + be the same as the number of entries in `new_row_vocab_file`). + new_col_vocab_size: Number of columns to load - should be the same as the + number of entries in `new_col_vocab_file`, since we don't support + partitioning along the column axis. + initializer: Callable initializer function that accepts a 1-D tensor as the + arg to specify the shape of the returned tensor. Used to initialize + missing values. + old_row_vocab_size: The number of entries to consider in the old vocabulary. + With the default value of -1, the entire old row vocabulary file will be + used. Otherwise, only the first `old_row_vocab_size` entries will be + considered for remapping.Must be smaller than the length of + `old_row_vocab_file`. NOTE: we do not provide an equivalent + `old_col_vocab_size` for classes. + old_row_vocab_file: A scalar `Tensor` of type `string` containing the + path to the old row vocabulary file. Can be None, which represents no + remapping on the row axis. + new_row_vocab_file: A scalar `Tensor` of type `string` containing the path + to the new row vocabulary file. Can be None, which represents no remapping + on the row axis - in which case, `new_row_vocab_offset` and + `num_rows_to_load` work under the assumption that the new row vocab is the + same as the old row vocab. + old_col_vocab_file: A scalar `Tensor` of type `string` containing the + path to the old column vocabulary file. Can be None, which represents no + remapping on the column axis. + new_col_vocab_file: A scalar `Tensor` of type `string` containing the path + to the new column vocabulary file. Can be None, which represents no + remapping on the column axis - in which case, `new_col_vocab_size` works + under the assumption that the new col vocab is the same as the old col + vocab. + num_row_oov_buckets: `int` specifying the number of out-of-vocabulary rows + to append. Must be >= 0. + num_col_oov_buckets: `int` specifying the number of out-of-vocabulary + columns to append. Must be >= 0. + max_rows_in_memory: `int` specifying the maximum number of rows to load from + the checkpoint at once. If less than or equal to 0, the entire matrix will + be loaded into memory. Setting this arg trades increased disk reads for + lower memory usage. + + Returns: + A Tensor of shape `[num_rows_to_load + num_row_oov_buckets, + new_col_vocab_size + num_col_oov_buckets]`, with values loaded from the + specified tensor in the checkpoint, and any missing or OOV values + initialized with the given `initializer`. + + Raises: + ValueError: If `num_row_oov_buckets` or `num_col_oov_buckets` < 0. + ValueError: If either `old_row_vocab_file` or `new_row_vocab_file` is + provided, while the other is not. Same for `old_col_vocab_file` and + `new_col_vocab_file`. + ValueError: If neither row vocabs or col vocabs are provided. + """ + if num_row_oov_buckets < 0: + raise ValueError("num_row_oov_buckets must be >= 0, but received %d" % + num_row_oov_buckets) + if num_col_oov_buckets < 0: + raise ValueError("num_col_oov_buckets must be >= 0, but received %d" % + num_col_oov_buckets) + + if bool(old_row_vocab_file) != bool(new_row_vocab_file): + raise ValueError( + "old_row_vocab_file and new_row_vocab_file must both be specified or " + "left unspecified. old_row_vocab_file='{}', new_row_vocab_file='{}'". + format(old_row_vocab_file, new_row_vocab_file)) + if bool(old_col_vocab_file) != bool(new_col_vocab_file): + raise ValueError( + "old_col_vocab_file and new_col_vocab_file must both be specified or " + "left unspecified. old_col_vocab_file='{}', new_col_vocab_file='{}'". + format(old_col_vocab_file, new_col_vocab_file)) + + remap_rows = new_row_vocab_file and old_row_vocab_file + remap_cols = new_col_vocab_file and old_col_vocab_file + if not (remap_rows or remap_cols): + raise ValueError( + "Must provide either row or column vocab files. If no remapping is " + "necessary, consider using `tf.contrib.framework.init_from_checkpoint` " + "instead.") + + num_rows_present = num_rows_to_load + if remap_rows: + row_remapping, num_rows_present = ( + gen_checkpoint_ops.generate_vocab_remapping( + new_vocab_file=new_row_vocab_file, + old_vocab_file=old_row_vocab_file, + new_vocab_offset=new_row_vocab_offset, + num_new_vocab=num_rows_to_load, + old_vocab_size=old_row_vocab_size)) + else: + # Even when the rows are not being reordered, we still need to generate a + # remapping to account for initializing partitioned Variables (when + # new_row_vocab_offset is non-zero). + row_remapping = math_ops.range( + new_row_vocab_offset, + new_row_vocab_offset + num_rows_to_load, + dtype=dtypes.int64) + + col_remapping = [] + num_cols_present = new_col_vocab_size + if remap_cols: + col_remapping, num_cols_present = ( + gen_checkpoint_ops.generate_vocab_remapping( + new_vocab_file=new_col_vocab_file, + old_vocab_file=old_col_vocab_file, + new_vocab_offset=0, # Offset is unused for cols (no partitioning). + num_new_vocab=new_col_vocab_size)) + + init_vals = initializer([ + num_rows_to_load * new_col_vocab_size - + num_rows_present * num_cols_present, 1 + ]) + return_tensor = gen_checkpoint_ops.load_and_remap_matrix( + ckpt_path=ckpt_path, + old_tensor_name=old_tensor_name, + row_remapping=row_remapping, + col_remapping=col_remapping, + initializing_values=init_vals, + num_rows=num_rows_to_load, + num_cols=new_col_vocab_size, + max_rows_in_memory=max_rows_in_memory) + + # Add OOV row(s) and column(s). + if num_row_oov_buckets > 0: + init_row_oov_val = initializer([num_row_oov_buckets, new_col_vocab_size]) + init_row_oov_val = ops.convert_to_tensor(init_row_oov_val) + return_tensor = array_ops.concat([return_tensor, init_row_oov_val], 0) + if num_col_oov_buckets > 0: + # We need to add any row OOV to the new column shape. + init_col_oov_val = initializer( + [num_rows_to_load + num_row_oov_buckets, num_col_oov_buckets]) + init_col_oov_val = ops.convert_to_tensor(init_col_oov_val) + return_tensor = array_ops.concat([return_tensor, init_col_oov_val], 1) + + return return_tensor + + +def _load_and_remap_matrix_initializer(ckpt_path, + old_tensor_name, + new_row_vocab_size, + new_col_vocab_size, + old_row_vocab_size=-1, + old_row_vocab_file=None, + new_row_vocab_file=None, + old_col_vocab_file=None, + new_col_vocab_file=None, + num_row_oov_buckets=0, + num_col_oov_buckets=0, + initializer=None, + max_rows_in_memory=-1): + r"""Returns a var initializer for loading and remapping a 2-D (matrix) tensor. + + The returned initializer loads a 2-D (matrix) `Tensor` with name + `old_tensor_name` from the checkpoint at `ckpt_path`. It will reorder the + rows/columns according to the specified vocab files and append additional + out-of-vocabulary rows/columns according to the number of OOV buckets. + + The format of the file at the `{old,new}_{row,col}_vocab_file` path should be + a text file, with each line containing a single entity within the vocabulary. + Let the function `line_of(f, "x")` return the 0-indexed line number of the + entity "x" in file f, and the function `entity_at(f, i)` return the entity at + line i of file f. Then, row i of the new output matrix will be taken from row + `line_of(old_row_vocab_file, entity_at(new_row_vocab_file, i))` of the old + matrix. If any entity in `new_row_vocab_file` is not found in + `old_row_vocab_file`, that row is considered a "missing" row, and its values + will be initialized using the `initializer` arg. The same logic also applies + for the columns. + + For example, assuming that: + + * `old_row_vocab_file` contains "mercury\nvenus\nmars" + * `new_row_vocab_file` contains "venus\njupiter\nmercury" + * `old_col_vocab_file` contains "good\nbetter\nbest" + * `new_col_vocab_file` contains "good\nbest\nfantastic" + * `initializer` returns the natural numbers `[1, 2, 3, 4, ...]` + * `w(i, j)` represents the value from row i, column j of the old matrix + + Then the new output matrix will look like: + + `[[w(1, 0), w(1, 2), 1], + [2, 3, 4], + [w(0, 0), w(0, 2), 5]]` + + If we further specify that: + + * `num_row_oov_buckets` == 2 + * `num_col_oov_buckets` == 1 + + Then the new output matrix will look like: + + `[[w(1, 0), w(1, 2), 1, 12], + [2, 3, 4, 13], + [w(0, 0), w(0, 2), 5, 14], + [6, 7, 8, 15], + [9, 10, 11, 16]]` + + If `{old,new}_row_vocab_file` are None, we assume that the old and new row + vocab files are the same, and no row remapping is done. If + `{old,new}_col_vocab_file` are None, we assume that the old and new column + vocab files are the same, and no column remapping is done. + + The returned initializer only supports div-partitioning along the row axis. It + does not support partitioning along the column axis (as this is not common in + practice) or mod-partitioning. + + NOTE: When this is used to warm-start variables, client code should use + `tf.lookup.index_table_from_tensor()` like + contrib/layers/python/layers/feature_column.py does, as opposed to + `tf.feature_to_id()` - in order to ensure the underlying lookup tables are the + same. + + Args: + ckpt_path: Path to the TensorFlow checkpoint (version 2, `TensorBundle`) + from which the old matrix `Tensor` will be loaded. + old_tensor_name: Name of the 2-D `Tensor` to load from checkpoint. + new_row_vocab_size: `int` specifying the number of entries in + `new_row_vocab_file`. If no row remapping is needed (no row vocab + provided), this should be equal to the number of rows to load from the old + matrix (which can theoretically be smaller than the number of rows in the + old matrix). + new_col_vocab_size: `int` specifying the number of entries in + `new_col_vocab_file`. If no column remapping is needed (no column vocab + provided), this should be equal to the number of columns in the old + matrix. + old_row_vocab_size: The number of entries to consider in the old vocabulary. + With the default value of -1, the entire old row vocabulary file will be + used. Otherwise, only the first `old_row_vocab_size` entries will be + considered for remapping.Must be smaller than the length of + `old_row_vocab_file`. NOTE: we do not provide an equivalent + `old_col_vocab_size` for classes. + old_row_vocab_file: A scalar `Tensor` of type `string` containing the + path to the old row vocabulary file. Can be None, which represents no + remapping on the row axis. + new_row_vocab_file: A scalar `Tensor` of type `string` containing the path + to the new row vocabulary file. Can be None, which represents no remapping + on the row axis. + old_col_vocab_file: A scalar `Tensor` of type `string` containing the + path to the old column vocabulary file. Can be None, which represents no + remapping on the column axis. + new_col_vocab_file: A scalar `Tensor` of type `string` containing the path + to the new column vocabulary file. Can be None, which represents no + remapping on the column axis. + num_row_oov_buckets: `int` specifying the number of out-of-vocabulary rows + to append. Must be >= 0. + num_col_oov_buckets: `int` specifying the number of out-of-vocabulary + columns to append. Must be >= 0. + initializer: Initializer function to initialize missing values. Accepts a + 1-D tensor as the arg to specify the shape of the returned tensor. If + `None`, defaults to using `zeros_initializer()`. + max_rows_in_memory: `int` specifying the maximum number of rows to load from + the checkpoint at once. If less than or equal to 0, the entire matrix will + be loaded into memory. Setting this arg trades increased disk reads for + lower memory usage. + + Returns: + A variable initializer function that should be used to initialize a + (potentially partitioned) `Variable` whose complete shape is + `[new_row_vocab_size + num_row_oov_buckets, new_col_vocab_size + + num_col_oov_buckets]`. + + Raises: + TypeError: If `initializer` is specified but not callable. + """ + if initializer is None: + # TODO(b/25671353): Consider using sqrt(6/(fan_in + fan_out)) instead, from + # Glorot and Bengio, 2010. + initializer = init_ops.zeros_initializer() + + if not callable(initializer): + raise TypeError( + "initializer must be callable, instead of being {} of type {}.".format( + initializer, type(initializer))) + + def _initializer(shape, dtype=dtypes.float32, partition_info=None): + """Variable initializer. + + Args: + shape: Shape of `Tensor` to return. Should include OOV on both axes. + dtype: Must be float32. + partition_info: variable_scope._PartitionInfo. + + Returns: + `Tensor` of shape `shape`. + + Raises: + TypeError: If `dtype` is anything other than float32. + ValueError: For shape mismatch upon invocation. + """ + # Sanity checks. + if dtype != dtypes.float32: + raise TypeError( + "Currently, only float32 is supported. Received dtype: {}".format( + dtype)) + if len(shape) != 2: + raise ValueError("Expected 2-dim shape, but received: {}".format(shape)) + if shape[0] <= 0: + raise ValueError( + "Expected 1st dim of shape to be > 0, but received shape: {}".format( + shape)) + if shape[1] != (new_col_vocab_size + num_col_oov_buckets): + raise ValueError( + "Expected 2nd dim of shape to be new_col_vocab_size ({}) + " + "num_col_oov_buckets ({}) = {}, but received shape: {}".format( + new_col_vocab_size, num_col_oov_buckets, + new_col_vocab_size + num_col_oov_buckets, shape)) + + offset = 0 + if partition_info is not None: + offset = partition_info.single_offset(shape) + + if offset + shape[0] > new_row_vocab_size + num_row_oov_buckets: + raise ValueError( + "Trying to initialize {} additional rows after {} rows have already " + "been initialized, which would exceed expected total row count of " + "new_row_vocab_size ({}) + num_row_oov_buckets ({}) = {}.".format( + shape[0], offset, new_row_vocab_size, num_row_oov_buckets, + new_row_vocab_size + num_row_oov_buckets)) + + row_oov_buckets_to_use = min(shape[0], + max(0, offset + shape[0] - new_row_vocab_size)) + num_rows_to_load = shape[0] - row_oov_buckets_to_use + + # We may be operating on an OOV-only partition, in which case we newly + # initialize all rows of this partition. + if offset > new_row_vocab_size: + if shape[0] != row_oov_buckets_to_use: + raise ValueError( + "Partitioned variable offset is greater than new vocab size and " + "not operating on OOV-only partition.") + return initializer(shape) + + return _load_and_remap_matrix( + ckpt_path=ckpt_path, + old_tensor_name=old_tensor_name, + new_row_vocab_offset=offset, + num_rows_to_load=num_rows_to_load, + new_col_vocab_size=new_col_vocab_size, + initializer=initializer, + old_row_vocab_size=old_row_vocab_size, + old_row_vocab_file=old_row_vocab_file, + new_row_vocab_file=new_row_vocab_file, + old_col_vocab_file=old_col_vocab_file, + new_col_vocab_file=new_col_vocab_file, + num_row_oov_buckets=row_oov_buckets_to_use, + num_col_oov_buckets=num_col_oov_buckets, + max_rows_in_memory=max_rows_in_memory) + + return _initializer + + +def _load_embedding_initializer(ckpt_path, + embedding_tensor_name, + new_vocab_size, + embedding_dim, + old_vocab_file, + new_vocab_file, + old_vocab_size=-1, + num_oov_buckets=0, + initializer=None, + max_rows_in_memory=-1): + """Returns a variable initializer for loading pre-trained embeddings. + + Wrapper around `load_and_remap_matrix_initializer()` specialized for loading + embedding weights and remapping according to the provided vocab files. See + docs for `load_and_remap_matrix_initializer()` for more details. + + NOTE: Only for use with div-partitioned variables / vocabularies. + + Args: + ckpt_path: Path to the TensorFlow checkpoint (version 2, `TensorBundle`) + from which the old matrix `Tensor` will be loaded. + embedding_tensor_name: Name of the 2-D `Tensor` to load from checkpoint. + new_vocab_size: Number of entries in the new vocab. + embedding_dim: `int` specifying the dimension of the embedding vectors from + the checkpoint. Must match the number of columns in the old embedding + matrix. + old_vocab_file: A scalar `Tensor` of type `string` containing the + path to the old vocabulary file. + new_vocab_file: A scalar `Tensor` of type `string` containing the + path to the new vocabulary file. + old_vocab_size: The number of entries to consider in the old vocabulary. + With the default value of -1, the entire old row vocabulary file will be + used. Otherwise, only the first `old_vocab_size` entries will be + considered for remapping.Must be smaller than the length of + `old_row_vocab_file`. + num_oov_buckets: `int` specifying the number of out-of-vocabulary + buckets to use. Must be >= 0. + initializer: Initializer function that accepts a 1-D tensor as the arg to + specify the shape of the returned tensor. If `None`, defaults to using + `truncated_normal_initializer()`. + max_rows_in_memory: `int` specifying the maximum number of rows to load from + the checkpoint at once. If less than or equal to 0, the entire matrix will + be loaded into memory. Setting this arg trades increased disk reads for + lower memory usage. + + Returns: + A variable initializer function. + """ + if initializer is None: + # TODO(b/25671353): This should be kept in sync with the stddev used by + # feature_column.py's _EmbeddingColumn. + initializer = init_ops.truncated_normal_initializer( + stddev=1.0 / math.sqrt(embedding_dim)) + + return _load_and_remap_matrix_initializer( + ckpt_path=ckpt_path, + old_tensor_name=embedding_tensor_name, + new_row_vocab_size=new_vocab_size, + new_col_vocab_size=embedding_dim, + old_row_vocab_size=old_vocab_size, + old_row_vocab_file=old_vocab_file, + new_row_vocab_file=new_vocab_file, + old_col_vocab_file=None, + new_col_vocab_file=None, + num_row_oov_buckets=num_oov_buckets, + num_col_oov_buckets=0, + initializer=initializer, + max_rows_in_memory=max_rows_in_memory) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/checkpoint_state_pb2.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/checkpoint_state_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..a8ec8ae9c4ccc15130f18b90421cf9a592ad8071 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/checkpoint_state_pb2.py @@ -0,0 +1,26 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: tensorflow/python/training/checkpoint_state.proto +"""Generated protocol buffer code.""" +from google.protobuf.internal import builder as _builder +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n1tensorflow/python/training/checkpoint_state.proto\x12\ntensorflow\"\x9f\x01\n\x0f\x43heckpointState\x12\x1d\n\x15model_checkpoint_path\x18\x01 \x01(\t\x12\"\n\x1a\x61ll_model_checkpoint_paths\x18\x02 \x03(\t\x12\'\n\x1f\x61ll_model_checkpoint_timestamps\x18\x03 \x03(\x01\x12 \n\x18last_preserved_timestamp\x18\x04 \x01(\x01\x42\x03\xf8\x01\x01\x62\x06proto3') + +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'tensorflow.python.training.checkpoint_state_pb2', globals()) +if _descriptor._USE_C_DESCRIPTORS == False: + + DESCRIPTOR._options = None + DESCRIPTOR._serialized_options = b'\370\001\001' + _CHECKPOINTSTATE._serialized_start=66 + _CHECKPOINTSTATE._serialized_end=225 +# @@protoc_insertion_point(module_scope) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/checkpoint_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/checkpoint_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..b05518b60d464e5d3c6153e58f95e5bd882fac7b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/checkpoint_utils.py @@ -0,0 +1,571 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Tools to work with name-based checkpoints. + +While some of these symbols also work with the TF2 object-based checkpoints, +they are not recommended for TF2. Please check `tensorflow/python/checkpoint` +for newer utilities built to work with TF2 checkpoints. +""" + +from collections import abc +import os +import time + +from tensorflow.python.checkpoint import checkpoint_management +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.framework import ops +from tensorflow.python.ops import io_ops +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.ops import variable_scope as vs +from tensorflow.python.ops import variables +from tensorflow.python.platform import gfile +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.training import py_checkpoint_reader +from tensorflow.python.training.saving import saveable_object_util +from tensorflow.python.util.tf_export import tf_export + + +__all__ = [ + "load_checkpoint", "load_variable", "list_variables", + "checkpoints_iterator", "init_from_checkpoint" +] + + +@tf_export("train.load_checkpoint") +def load_checkpoint(ckpt_dir_or_file): + """Returns `CheckpointReader` for checkpoint found in `ckpt_dir_or_file`. + + If `ckpt_dir_or_file` resolves to a directory with multiple checkpoints, + reader for the latest checkpoint is returned. + + Example usage: + + ```python + import tensorflow as tf + a = tf.Variable(1.0) + b = tf.Variable(2.0) + ckpt = tf.train.Checkpoint(var_list={'a': a, 'b': b}) + ckpt_path = ckpt.save('tmp-ckpt') + reader= tf.train.load_checkpoint(ckpt_path) + print(reader.get_tensor('var_list/a/.ATTRIBUTES/VARIABLE_VALUE')) # 1.0 + ``` + + Args: + ckpt_dir_or_file: Directory with checkpoints file or path to checkpoint + file. + + Returns: + `CheckpointReader` object. + + Raises: + ValueError: If `ckpt_dir_or_file` resolves to a directory with no + checkpoints. + """ + filename = _get_checkpoint_filename(ckpt_dir_or_file) + if filename is None: + raise ValueError("Couldn't find 'checkpoint' file or checkpoints in " + "given directory %s" % ckpt_dir_or_file) + return py_checkpoint_reader.NewCheckpointReader(filename) + + +@tf_export("train.load_variable") +def load_variable(ckpt_dir_or_file, name): + """Returns the tensor value of the given variable in the checkpoint. + + When the variable name is unknown, you can use `tf.train.list_variables` to + inspect all the variable names. + + Example usage: + + ```python + import tensorflow as tf + a = tf.Variable(1.0) + b = tf.Variable(2.0) + ckpt = tf.train.Checkpoint(var_list={'a': a, 'b': b}) + ckpt_path = ckpt.save('tmp-ckpt') + var= tf.train.load_variable( + ckpt_path, 'var_list/a/.ATTRIBUTES/VARIABLE_VALUE') + print(var) # 1.0 + ``` + + Args: + ckpt_dir_or_file: Directory with checkpoints file or path to checkpoint. + name: Name of the variable to return. + + Returns: + A numpy `ndarray` with a copy of the value of this variable. + """ + # TODO(b/29227106): Fix this in the right place and remove this. + if name.endswith(":0"): + name = name[:-2] + reader = load_checkpoint(ckpt_dir_or_file) + return reader.get_tensor(name) + + +@tf_export("train.list_variables") +def list_variables(ckpt_dir_or_file): + """Lists the checkpoint keys and shapes of variables in a checkpoint. + + Checkpoint keys are paths in a checkpoint graph. + + Example usage: + + ```python + import tensorflow as tf + import os + ckpt_directory = "/tmp/training_checkpoints/ckpt" + ckpt = tf.train.Checkpoint(optimizer=optimizer, model=model) + manager = tf.train.CheckpointManager(ckpt, ckpt_directory, max_to_keep=3) + train_and_checkpoint(model, manager) + tf.train.list_variables(manager.latest_checkpoint) + ``` + + Args: + ckpt_dir_or_file: Directory with checkpoints file or path to checkpoint. + + Returns: + List of tuples `(key, shape)`. + """ + reader = load_checkpoint(ckpt_dir_or_file) + variable_map = reader.get_variable_to_shape_map() + names = sorted(variable_map.keys()) + result = [] + for name in names: + result.append((name, variable_map[name])) + return result + + +def wait_for_new_checkpoint(checkpoint_dir, + last_checkpoint=None, + seconds_to_sleep=1, + timeout=None): + """Waits until a new checkpoint file is found. + + Args: + checkpoint_dir: The directory in which checkpoints are saved. + last_checkpoint: The last checkpoint path used or `None` if we're expecting + a checkpoint for the first time. + seconds_to_sleep: The number of seconds to sleep for before looking for a + new checkpoint. + timeout: The maximum number of seconds to wait. If left as `None`, then the + process will wait indefinitely. + + Returns: + a new checkpoint path, or None if the timeout was reached. + """ + logging.info("Waiting for new checkpoint at %s", checkpoint_dir) + stop_time = time.time() + timeout if timeout is not None else None + while True: + checkpoint_path = checkpoint_management.latest_checkpoint(checkpoint_dir) + if checkpoint_path is None or checkpoint_path == last_checkpoint: + if stop_time is not None and time.time() + seconds_to_sleep > stop_time: + return None + time.sleep(seconds_to_sleep) + else: + logging.info("Found new checkpoint at %s", checkpoint_path) + return checkpoint_path + + +@tf_export("train.checkpoints_iterator") +def checkpoints_iterator(checkpoint_dir, + min_interval_secs=0, + timeout=None, + timeout_fn=None): + """Continuously yield new checkpoint files as they appear. + + The iterator only checks for new checkpoints when control flow has been + reverted to it. This means it can miss checkpoints if your code takes longer + to run between iterations than `min_interval_secs` or the interval at which + new checkpoints are written. + + The `timeout` argument is the maximum number of seconds to block waiting for + a new checkpoint. It is used in combination with the `timeout_fn` as + follows: + + * If the timeout expires and no `timeout_fn` was specified, the iterator + stops yielding. + * If a `timeout_fn` was specified, that function is called and if it returns + a true boolean value the iterator stops yielding. + * If the function returns a false boolean value then the iterator resumes the + wait for new checkpoints. At this point the timeout logic applies again. + + This behavior gives control to callers on what to do if checkpoints do not + come fast enough or stop being generated. For example, if callers have a way + to detect that the training has stopped and know that no new checkpoints + will be generated, they can provide a `timeout_fn` that returns `True` when + the training has stopped. If they know that the training is still going on + they return `False` instead. + + Args: + checkpoint_dir: The directory in which checkpoints are saved. + min_interval_secs: The minimum number of seconds between yielding + checkpoints. + timeout: The maximum number of seconds to wait between checkpoints. If left + as `None`, then the process will wait indefinitely. + timeout_fn: Optional function to call after a timeout. If the function + returns True, then it means that no new checkpoints will be generated and + the iterator will exit. The function is called with no arguments. + + Yields: + String paths to latest checkpoint files as they arrive. + """ + checkpoint_path = None + while True: + new_checkpoint_path = wait_for_new_checkpoint( + checkpoint_dir, checkpoint_path, timeout=timeout) + if new_checkpoint_path is None: + if not timeout_fn: + # timed out + logging.info("Timed-out waiting for a checkpoint.") + return + if timeout_fn(): + # The timeout_fn indicated that we are truly done. + return + else: + # The timeout_fn indicated that more checkpoints may come. + continue + start = time.time() + checkpoint_path = new_checkpoint_path + yield checkpoint_path + time_to_next_eval = start + min_interval_secs - time.time() + if time_to_next_eval > 0: + time.sleep(time_to_next_eval) + + +@tf_export(v1=["train.init_from_checkpoint"]) +def init_from_checkpoint(ckpt_dir_or_file, assignment_map): + """Replaces `tf.Variable` initializers so they load from a checkpoint file. + + @compatibility(TF2) + `tf.compat.v1.train.init_from_checkpoint` is not recommended for restoring + variable values in TF2. + + To restore checkpoints in TF2, please use + `tf.keras.Model.load_weights` or `tf.train.Checkpoint.restore`. These APIs use + use an [object-based method of checkpointing] + (https://www.tensorflow.org/guide/checkpoint#loading_mechanics), while + `tf.compat.v1.init_from_checkpoint` relies on a more-fragile variable-name + based method of checkpointing. There is no object-based equivalent of + `init_from_checkpoint` in TF2. + + Please re-write your checkpoints immediately using the object-based APIs, + see [migration guide] + (https://www.tensorflow.org/guide/migrate#checkpoint_compatibility) for more + details. + + You can load a name-based checkpoint written by `tf.compat.v1.train.Saver` + using `tf.train.Checkpoint.restore` or `tf.keras.Model.load_weights`. However, + you may have to change the names of the variables in your model to match the + variable names in the name-based checkpoint, which can be viewed with + `tf.train.list_variables(path)`. + + Another option is to create an `assignment_map` that maps the name of the + variables in the name-based checkpoint to the variables in your model, eg: + ``` + { + 'sequential/dense/bias': model.variables[0], + 'sequential/dense/kernel': model.variables[1] + } + ``` + and use `tf.compat.v1.train.init_from_checkpoint(path, assignment_map)` to + restore the name-based checkpoint. + + After restoring, re-encode your checkpoint using `tf.train.Checkpoint.save` + or `tf.keras.Model.save_weights`. + + @end_compatibility + + Values are not loaded immediately, but when the initializer is run + (typically by running a `tf.compat.v1.global_variables_initializer` op). + + Note: This overrides default initialization ops of specified variables and + redefines dtype. + + Assignment map supports following syntax: + + * `'checkpoint_scope_name/': 'scope_name/'` - will load all variables in + current `scope_name` from `checkpoint_scope_name` with matching tensor + names. + * `'checkpoint_scope_name/some_other_variable': 'scope_name/variable_name'` - + will initialize `scope_name/variable_name` variable + from `checkpoint_scope_name/some_other_variable`. + * `'scope_variable_name': variable` - will initialize given `tf.Variable` + object with tensor 'scope_variable_name' from the checkpoint. + * `'scope_variable_name': list(variable)` - will initialize list of + partitioned variables with tensor 'scope_variable_name' from the checkpoint. + * `'/': 'scope_name/'` - will load all variables in current `scope_name` from + checkpoint's root (e.g. no scope). + + Supports loading into partitioned variables, which are represented as + `'/part_'`. + + Assignment map can be a dict, or a list of pairs. The latter is + necessary to initialize multiple variables in the current graph from + the same variable in the checkpoint. + + Example: + + ```python + + # Say, '/tmp/model.ckpt' has the following tensors: + # -- name='old_scope_1/var1', shape=[20, 2] + # -- name='old_scope_1/var2', shape=[50, 4] + # -- name='old_scope_2/var3', shape=[100, 100] + + # Create new model's variables + with tf.compat.v1.variable_scope('new_scope_1'): + var1 = tf.compat.v1.get_variable('var1', shape=[20, 2], + initializer=tf.compat.v1.zeros_initializer()) + with tf.compat.v1.variable_scope('new_scope_2'): + var2 = tf.compat.v1.get_variable('var2', shape=[50, 4], + initializer=tf.compat.v1.zeros_initializer()) + # Partition into 5 variables along the first axis. + var3 = tf.compat.v1.get_variable(name='var3', shape=[100, 100], + initializer=tf.compat.v1.zeros_initializer(), + partitioner=lambda shape, dtype: [5, 1]) + + # Initialize all variables in `new_scope_1` from `old_scope_1`. + init_from_checkpoint('/tmp/model.ckpt', {'old_scope_1/': 'new_scope_1/'}) + + # Use names to specify which variables to initialize from checkpoint. + init_from_checkpoint('/tmp/model.ckpt', + {'old_scope_1/var1': 'new_scope_1/var1', + 'old_scope_1/var2': 'new_scope_2/var2'}) + + # Or use tf.Variable objects to identify what to initialize. + init_from_checkpoint('/tmp/model.ckpt', + {'old_scope_1/var1': var1, + 'old_scope_1/var2': var2}) + + # Initialize partitioned variables using variable's name + init_from_checkpoint('/tmp/model.ckpt', + {'old_scope_2/var3': 'new_scope_2/var3'}) + + # Or specify the list of tf.Variable objects. + init_from_checkpoint('/tmp/model.ckpt', + {'old_scope_2/var3': var3._get_variable_list()}) + + ``` + + Args: + ckpt_dir_or_file: Directory with checkpoints file or path to checkpoint. + assignment_map: Dict, or a list of key-value pairs, where keys are names + of the variables in the checkpoint and values are current variables or + names of current variables (in default graph). + + Raises: + ValueError: If missing variables in current graph, or if missing + checkpoints or tensors in checkpoints. + + """ + init_from_checkpoint_fn = lambda _: _init_from_checkpoint( + ckpt_dir_or_file, assignment_map) + if distribute_lib.get_cross_replica_context(): + init_from_checkpoint_fn(None) + else: + distribute_lib.get_replica_context().merge_call( + init_from_checkpoint_fn) + + +def _init_from_checkpoint(ckpt_dir_or_file, assignment_map): + """See `init_from_checkpoint` for documentation.""" + ckpt_file = _get_checkpoint_filename(ckpt_dir_or_file) + reader = load_checkpoint(ckpt_dir_or_file) + variable_map = reader.get_variable_to_shape_map() + if isinstance(assignment_map, abc.Mapping): + assignment_map = assignment_map.items() + + # We only want to sort by tensor names. + sort_key = lambda pair: pair[0] + + for tensor_name_in_ckpt, current_var_or_name in sorted( + assignment_map, key=sort_key): + var = None + # Check if this is Variable object or list of Variable objects (in case of + # partitioned variables). + if _is_variable(current_var_or_name) or ( + isinstance(current_var_or_name, list) + and all(_is_variable(v) for v in current_var_or_name)): + var = current_var_or_name + else: + store_vars = vs._get_default_variable_store()._vars # pylint:disable=protected-access + # Check if this variable is in var_store. + var = store_vars.get(current_var_or_name, None) + # Also check if variable is partitioned as list. + if var is None: + var = _collect_partitioned_variable(current_var_or_name, store_vars) + if var is not None: + # If 1 to 1 mapping was provided, find variable in the checkpoint. + if tensor_name_in_ckpt not in variable_map: + raise ValueError("Tensor %s is not found in %s checkpoint %s" % ( + tensor_name_in_ckpt, ckpt_dir_or_file, variable_map + )) + if _is_variable(var): + # Additional at-call-time checks. + if not var.get_shape().is_compatible_with( + variable_map[tensor_name_in_ckpt]): + raise ValueError( + "Shape of variable %s (%s) doesn't match with shape of " + "tensor %s (%s) from checkpoint reader." % ( + var.name, str(var.get_shape()), + tensor_name_in_ckpt, str(variable_map[tensor_name_in_ckpt]) + )) + var_name = var.name + else: + var_name = ",".join(v.name for v in var) + _set_variable_or_list_initializer(var, ckpt_file, tensor_name_in_ckpt) + logging.debug("Initialize variable %s from checkpoint %s with %s", + var_name, ckpt_dir_or_file, tensor_name_in_ckpt) + else: + scopes = "" + # TODO(vihanjain): Support list of 'current_var_or_name' here. + if "/" in current_var_or_name: + scopes = current_var_or_name[:current_var_or_name.rindex("/")] + if not tensor_name_in_ckpt.endswith("/"): + raise ValueError( + "Assignment map with scope only name {} should map to scope only " + "{}. Should be 'scope/': 'other_scope/'.".format( + scopes, tensor_name_in_ckpt)) + # If scope to scope mapping was provided, find all variables in the scope + # and create variable to variable mapping. + scope_variables = set() + for var_name in store_vars: + if not scopes or var_name.startswith(scopes + "/"): + # Consume /part_ if partitioned variable. + if "/part_" in var_name: + var_name = var_name[:var_name.index("/part_")] + scope_variables.add(var_name) + for var_name in sorted(scope_variables): + # Lookup name with specified prefix and suffix from current variable. + # If tensor_name given is '/' (root), don't use it for full name. + full_tensor_name = var_name[len(scopes):] + if current_var_or_name != "/": + full_tensor_name = full_tensor_name[1:] + if tensor_name_in_ckpt != "/": + full_tensor_name = tensor_name_in_ckpt + full_tensor_name + # Remove trailing '/', if any, in the full_tensor_name + if full_tensor_name.endswith("/"): + full_tensor_name = full_tensor_name[:-1] + if full_tensor_name not in variable_map: + raise ValueError( + "Tensor %s (%s in %s) is not found in %s checkpoint" % ( + full_tensor_name, var_name[len(scopes) + 1:], + tensor_name_in_ckpt, ckpt_dir_or_file + )) + var = store_vars.get(var_name, None) + if var is None: + var = _collect_partitioned_variable(var_name, store_vars) + _set_variable_or_list_initializer(var, ckpt_file, full_tensor_name) + logging.debug("Initialize variable %s from checkpoint %s with %s", + var_name, ckpt_dir_or_file, full_tensor_name) + + +def _get_checkpoint_filename(ckpt_dir_or_file): + """Returns checkpoint filename given directory or specific checkpoint file.""" + if isinstance(ckpt_dir_or_file, os.PathLike): + ckpt_dir_or_file = os.fspath(ckpt_dir_or_file) + if gfile.IsDirectory(ckpt_dir_or_file): + return checkpoint_management.latest_checkpoint(ckpt_dir_or_file) + return ckpt_dir_or_file + + +def _set_checkpoint_initializer(variable, + ckpt_file, + tensor_name, + slice_spec, + name="checkpoint_initializer"): + """Overrides given variable's initialization op. + + Sets variable initializer to assign op that initializes variable from tensor's + value in the checkpoint. + + Args: + variable: `tf.Variable` object. + ckpt_file: string, full path of the checkpoint. + tensor_name: Name of the tensor to load from the checkpoint. + slice_spec: Slice specification for loading partitioned tensors. + name: Name of the operation. + """ + base_type = variable.dtype.base_dtype + # Do not colocate with variable since RestoreV2 op only runs on CPU and + # colocation will force variable (and other ops that colocate with variable) + # to be on CPU as well. It is okay to place the variable's initializer op on + # CPU since it will only be run once at the start. + with ops.device(variable.device), ops.device("/cpu:0"): + restore_op = io_ops.restore_v2( + ckpt_file, [tensor_name], [slice_spec], [base_type], name=name)[0] + + names_to_saveables = saveable_object_util.op_list_to_dict([variable]) + saveable_objects = [] + for name, op in names_to_saveables.items(): + for s in saveable_object_util.saveable_objects_for_op(op, name): + saveable_objects.append(s) + + assert len(saveable_objects) == 1 # Should be only one variable. + init_op = saveable_objects[0].restore([restore_op], restored_shapes=None) + + # pylint:disable=protected-access + variable._initializer_op = init_op + restore_op.set_shape(variable.shape) + variable._initial_value = restore_op + # pylint:enable=protected-access + + +def _set_variable_or_list_initializer(variable_or_list, ckpt_file, + tensor_name): + """Overrides initialization op of given variable or list of variables. + + Calls `_set_checkpoint_initializer` for each variable in the given list of + variables. + + Args: + variable_or_list: `tf.Variable` object or a list of `tf.Variable` objects. + ckpt_file: string, full path of the checkpoint. + tensor_name: Name of the tensor to load from the checkpoint. + + Raises: + ValueError: if all objects in `variable_or_list` are not partitions of the + same large variable. + """ + if isinstance(variable_or_list, (list, tuple)): + # A set of slices. + slice_name = None + for v in variable_or_list: + slice_info = v._save_slice_info # pylint:disable=protected-access + if slice_name is None: + slice_name = slice_info.full_name + elif slice_name != slice_info.full_name: + raise ValueError("Slices must all be from the same tensor: %s != %s" % + (slice_name, slice_info.full_name)) + _set_checkpoint_initializer(v, ckpt_file, tensor_name, slice_info.spec) + else: + _set_checkpoint_initializer(variable_or_list, ckpt_file, tensor_name, "") + + +def _is_variable(x): + return (isinstance(x, variables.Variable) or + resource_variable_ops.is_resource_variable(x)) + + +def _collect_partitioned_variable(name, all_vars): + """Returns list of `tf.Variable` that comprise the partitioned variable.""" + if name + "/part_0" in all_vars: + var = [] + i = 0 + while name + "/part_%d" % i in all_vars: + var.append(all_vars[name + "/part_%d" % i]) + i += 1 + return var + return None diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/coordinator.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/coordinator.py new file mode 100644 index 0000000000000000000000000000000000000000..f8a51b5d84bd576b3b8261b468179f6bbc029ca6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/coordinator.py @@ -0,0 +1,507 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Coordinator to help multiple threads stop when requested.""" +import contextlib +import sys +import threading +import time + +from tensorflow.python.framework import errors +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.util import compat +from tensorflow.python.util.tf_export import tf_export + + +@tf_export("train.Coordinator") +class Coordinator: + """A coordinator for threads. + + This class implements a simple mechanism to coordinate the termination of a + set of threads. + + #### Usage: + + ```python + # Create a coordinator. + coord = Coordinator() + # Start a number of threads, passing the coordinator to each of them. + ...start thread 1...(coord, ...) + ...start thread N...(coord, ...) + # Wait for all the threads to terminate. + coord.join(threads) + ``` + + Any of the threads can call `coord.request_stop()` to ask for all the threads + to stop. To cooperate with the requests, each thread must check for + `coord.should_stop()` on a regular basis. `coord.should_stop()` returns + `True` as soon as `coord.request_stop()` has been called. + + A typical thread running with a coordinator will do something like: + + ```python + while not coord.should_stop(): + ...do some work... + ``` + + #### Exception handling: + + A thread can report an exception to the coordinator as part of the + `request_stop()` call. The exception will be re-raised from the + `coord.join()` call. + + Thread code: + + ```python + try: + while not coord.should_stop(): + ...do some work... + except Exception as e: + coord.request_stop(e) + ``` + + Main code: + + ```python + try: + ... + coord = Coordinator() + # Start a number of threads, passing the coordinator to each of them. + ...start thread 1...(coord, ...) + ...start thread N...(coord, ...) + # Wait for all the threads to terminate. + coord.join(threads) + except Exception as e: + ...exception that was passed to coord.request_stop() + ``` + + To simplify the thread implementation, the Coordinator provides a + context handler `stop_on_exception()` that automatically requests a stop if + an exception is raised. Using the context handler the thread code above + can be written as: + + ```python + with coord.stop_on_exception(): + while not coord.should_stop(): + ...do some work... + ``` + + #### Grace period for stopping: + + After a thread has called `coord.request_stop()` the other threads have a + fixed time to stop, this is called the 'stop grace period' and defaults to 2 + minutes. If any of the threads is still alive after the grace period expires + `coord.join()` raises a RuntimeError reporting the laggards. + + ```python + try: + ... + coord = Coordinator() + # Start a number of threads, passing the coordinator to each of them. + ...start thread 1...(coord, ...) + ...start thread N...(coord, ...) + # Wait for all the threads to terminate, give them 10s grace period + coord.join(threads, stop_grace_period_secs=10) + except RuntimeError: + ...one of the threads took more than 10s to stop after request_stop() + ...was called. + except Exception: + ...exception that was passed to coord.request_stop() + ``` + """ + + def __init__(self, clean_stop_exception_types=None): + """Create a new Coordinator. + + Args: + clean_stop_exception_types: Optional tuple of Exception types that should + cause a clean stop of the coordinator. If an exception of one of these + types is reported to `request_stop(ex)` the coordinator will behave as + if `request_stop(None)` was called. Defaults to + `(tf.errors.OutOfRangeError,)` which is used by input queues to signal + the end of input. When feeding training data from a Python iterator it + is common to add `StopIteration` to this list. + """ + if clean_stop_exception_types is None: + clean_stop_exception_types = (errors.OutOfRangeError,) + self._clean_stop_exception_types = tuple(clean_stop_exception_types) + # Protects all attributes. + self._lock = threading.Lock() + # Event set when threads must stop. + self._stop_event = threading.Event() + # Python exc_info to report. + # If not None, it should hold the returned value of sys.exc_info(), which is + # a tuple containing exception (type, value, traceback). + self._exc_info_to_raise = None + # True if we have called join() already. + self._joined = False + # Set of threads registered for joining when join() is called. These + # threads will be joined in addition to the threads passed to the join() + # call. It's ok if threads are both registered and passed to the join() + # call. + self._registered_threads = set() + + def _filter_exception(self, ex): + """Check if the exception indicated in 'ex' should be ignored. + + This method examines `ex` to check if it is an exception that should be + reported to the users. If yes, it returns `ex` as is, otherwise it returns + None. + + The code returns None for exception types listed in + `_clean_stop_exception_types`. + + Args: + ex: None, an `Exception`, or a Python `exc_info` tuple as returned by + `sys.exc_info()`. + + Returns: + ex or None. + """ + if isinstance(ex, tuple): + ex2 = ex[1] + else: + ex2 = ex + if isinstance(ex2, self._clean_stop_exception_types): + # Ignore the exception. + ex = None + return ex + + def request_stop(self, ex=None): + """Request that the threads stop. + + After this is called, calls to `should_stop()` will return `True`. + + Note: If an exception is being passed in, in must be in the context of + handling the exception (i.e. `try: ... except Exception as ex: ...`) and not + a newly created one. + + Args: + ex: Optional `Exception`, or Python `exc_info` tuple as returned by + `sys.exc_info()`. If this is the first call to `request_stop()` the + corresponding exception is recorded and re-raised from `join()`. + """ + with self._lock: + ex = self._filter_exception(ex) + # If we have already joined the coordinator the exception will not have a + # chance to be reported, so just raise it normally. This can happen if + # you continue to use a session have having stopped and joined the + # coordinator threads. + if self._joined: + if isinstance(ex, tuple): + _, ex_instance, _ = ex + raise ex_instance + elif ex is not None: + # NOTE(touts): This is bogus if request_stop() is not called + # from the exception handler that raised ex. + _, ex_instance, _ = sys.exc_info() + raise ex_instance + if not self._stop_event.is_set(): + if ex and self._exc_info_to_raise is None: + if isinstance(ex, tuple): + logging.info("Error reported to Coordinator: %s", + compat.as_str_any(ex[1]), + exc_info=ex) + self._exc_info_to_raise = ex + else: + logging.info("Error reported to Coordinator: %s, %s", + type(ex), + compat.as_str_any(ex)) + self._exc_info_to_raise = sys.exc_info() + # self._exc_info_to_raise should contain a tuple containing exception + # (type, value, traceback) + if (len(self._exc_info_to_raise) != 3 or + not self._exc_info_to_raise[0] or + not self._exc_info_to_raise[1]): + # Raise, catch and record the exception here so that error happens + # where expected. + try: + raise ValueError( + "ex must be a tuple or sys.exc_info must return the current " + "exception: %s" + % self._exc_info_to_raise) + except ValueError: + # Record this error so it kills the coordinator properly. + # NOTE(touts): As above, this is bogus if request_stop() is not + # called from the exception handler that raised ex. + self._exc_info_to_raise = sys.exc_info() + + self._stop_event.set() + + def clear_stop(self): + """Clears the stop flag. + + After this is called, calls to `should_stop()` will return `False`. + """ + with self._lock: + self._joined = False + self._exc_info_to_raise = None + if self._stop_event.is_set(): + self._stop_event.clear() + + def should_stop(self): + """Check if stop was requested. + + Returns: + True if a stop was requested. + """ + return self._stop_event.is_set() + + @contextlib.contextmanager + def stop_on_exception(self): + """Context manager to request stop when an Exception is raised. + + Code that uses a coordinator must catch exceptions and pass + them to the `request_stop()` method to stop the other threads + managed by the coordinator. + + This context handler simplifies the exception handling. + Use it as follows: + + ```python + with coord.stop_on_exception(): + # Any exception raised in the body of the with + # clause is reported to the coordinator before terminating + # the execution of the body. + ...body... + ``` + + This is completely equivalent to the slightly longer code: + + ```python + try: + ...body... + except: + coord.request_stop(sys.exc_info()) + ``` + + Yields: + nothing. + """ + try: + yield + except: # pylint: disable=bare-except + self.request_stop(ex=sys.exc_info()) + + def wait_for_stop(self, timeout=None): + """Wait till the Coordinator is told to stop. + + Args: + timeout: Float. Sleep for up to that many seconds waiting for + should_stop() to become True. + + Returns: + True if the Coordinator is told stop, False if the timeout expired. + """ + return self._stop_event.wait(timeout) + + def register_thread(self, thread): + """Register a thread to join. + + Args: + thread: A Python thread to join. + """ + with self._lock: + self._registered_threads.add(thread) + + def join(self, threads=None, stop_grace_period_secs=120, + ignore_live_threads=False): + """Wait for threads to terminate. + + This call blocks until a set of threads have terminated. The set of thread + is the union of the threads passed in the `threads` argument and the list + of threads that registered with the coordinator by calling + `Coordinator.register_thread()`. + + After the threads stop, if an `exc_info` was passed to `request_stop`, that + exception is re-raised. + + Grace period handling: When `request_stop()` is called, threads are given + 'stop_grace_period_secs' seconds to terminate. If any of them is still + alive after that period expires, a `RuntimeError` is raised. Note that if + an `exc_info` was passed to `request_stop()` then it is raised instead of + that `RuntimeError`. + + Args: + threads: List of `threading.Threads`. The started threads to join in + addition to the registered threads. + stop_grace_period_secs: Number of seconds given to threads to stop after + `request_stop()` has been called. + ignore_live_threads: If `False`, raises an error if any of the threads are + still alive after `stop_grace_period_secs`. + + Raises: + RuntimeError: If any thread is still alive after `request_stop()` + is called and the grace period expires. + """ + # Threads registered after this call will not be joined. + with self._lock: + if threads is None: + threads = self._registered_threads + else: + threads = self._registered_threads.union(set(threads)) + # Copy the set into a list to avoid race conditions where a new thread + # is added while we are waiting. + threads = list(threads) + + # Wait for all threads to stop or for request_stop() to be called. + while any(t.is_alive() for t in threads) and not self.wait_for_stop(1.0): + pass + + # If any thread is still alive, wait for the grace period to expire. + # By the time this check is executed, threads may still be shutting down, + # so we add a sleep of increasing duration to give them a chance to shut + # down without losing too many cycles. + # The sleep duration is limited to the remaining grace duration. + stop_wait_secs = 0.001 + while any(t.is_alive() for t in threads) and stop_grace_period_secs >= 0.0: + time.sleep(stop_wait_secs) + stop_grace_period_secs -= stop_wait_secs + stop_wait_secs = 2 * stop_wait_secs + # Keep the waiting period within sane bounds. + # The minimum value is to avoid decreasing stop_wait_secs to a value + # that could cause stop_grace_period_secs to remain unchanged. + stop_wait_secs = max(min(stop_wait_secs, stop_grace_period_secs), 0.001) + + # List the threads still alive after the grace period. + stragglers = [t.name for t in threads if t.is_alive()] + + # Terminate with an exception if appropriate. + with self._lock: + self._joined = True + self._registered_threads = set() + if self._exc_info_to_raise: + _, ex_instance, _ = self._exc_info_to_raise + raise ex_instance + elif stragglers: + if ignore_live_threads: + logging.info("Coordinator stopped with threads still running: %s", + " ".join(stragglers)) + else: + raise RuntimeError( + "Coordinator stopped with threads still running: %s" % + " ".join(stragglers)) + + @property + def joined(self): + return self._joined + + def raise_requested_exception(self): + """If an exception has been passed to `request_stop`, this raises it.""" + with self._lock: + if self._exc_info_to_raise: + _, ex_instance, _ = self._exc_info_to_raise + raise ex_instance + + +# Threads for the standard services. +@tf_export(v1=["train.LooperThread"]) +class LooperThread(threading.Thread): + """A thread that runs code repeatedly, optionally on a timer. + + This thread class is intended to be used with a `Coordinator`. It repeatedly + runs code specified either as `target` and `args` or by the `run_loop()` + method. + + Before each run the thread checks if the coordinator has requested stop. In + that case the looper thread terminates immediately. + + If the code being run raises an exception, that exception is reported to the + coordinator and the thread terminates. The coordinator will then request all + the other threads it coordinates to stop. + + You typically pass looper threads to the supervisor `Join()` method. + """ + + def __init__(self, coord, timer_interval_secs, target=None, args=None, + kwargs=None): + """Create a LooperThread. + + Args: + coord: A Coordinator. + timer_interval_secs: Time boundaries at which to call Run(), or None + if it should be called back to back. + target: Optional callable object that will be executed in the thread. + args: Optional arguments to pass to `target` when calling it. + kwargs: Optional keyword arguments to pass to `target` when calling it. + + Raises: + ValueError: If one of the arguments is invalid. + """ + if not isinstance(coord, Coordinator): + raise ValueError("'coord' argument must be a Coordinator: %s" % coord) + super(LooperThread, self).__init__() + self.daemon = True + self._coord = coord + self._timer_interval_secs = timer_interval_secs + self._target = target + if self._target: + self._args = args or () + self._kwargs = kwargs or {} + elif args or kwargs: + raise ValueError("'args' and 'kwargs' argument require that you also " + "pass 'target'") + self._coord.register_thread(self) + + @staticmethod + def loop(coord, timer_interval_secs, target, args=None, kwargs=None): + """Start a LooperThread that calls a function periodically. + + If `timer_interval_secs` is None the thread calls `target(args)` + repeatedly. Otherwise `target(args)` is called every `timer_interval_secs` + seconds. The thread terminates when a stop of the coordinator is + requested. + + Args: + coord: A Coordinator. + timer_interval_secs: Number. Time boundaries at which to call `target`. + target: A callable object. + args: Optional arguments to pass to `target` when calling it. + kwargs: Optional keyword arguments to pass to `target` when calling it. + + Returns: + The started thread. + """ + looper = LooperThread(coord, timer_interval_secs, target=target, args=args, + kwargs=kwargs) + looper.start() + return looper + + def run(self): + with self._coord.stop_on_exception(): + self.start_loop() + if self._timer_interval_secs is None: + # Call back-to-back. + while not self._coord.should_stop(): + self.run_loop() + else: + # Next time at which to call run_loop(), starts as 'now'. + next_timer_time = time.time() + while not self._coord.wait_for_stop(next_timer_time - time.time()): + next_timer_time += self._timer_interval_secs + self.run_loop() + self.stop_loop() + + def start_loop(self): + """Called when the thread starts.""" + pass + + def stop_loop(self): + """Called when the thread stops.""" + pass + + def run_loop(self): + """Called at 'timer_interval_secs' boundaries.""" + if self._target: + self._target(*self._args, **self._kwargs) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/device_setter.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/device_setter.py new file mode 100644 index 0000000000000000000000000000000000000000..dc7cfc938c35974bb46b3ee0de5d1209ad254952 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/device_setter.py @@ -0,0 +1,225 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Device function for replicated training.""" +from tensorflow.core.framework import node_def_pb2 +from tensorflow.python.framework import device as pydev +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.training import server_lib +from tensorflow.python.util.tf_export import tf_export + +# This is a tuple of PS ops used by tf.estimator.Estimator which should work in +# almost all of cases. +STANDARD_PS_OPS = ("Variable", "VariableV2", "AutoReloadVariable", + "MutableHashTable", "MutableHashTableV2", + "MutableHashTableOfTensors", "MutableHashTableOfTensorsV2", + "MutableDenseHashTable", "MutableDenseHashTableV2", + "VarHandleOp", "BoostedTreesEnsembleResourceHandleOp", + "BoostedTreesQuantileStreamResourceHandleOp", + "ResourceConditionalAccumulator", + "DecisionTreeResource") + + +class _RoundRobinStrategy: + """Returns the next ps task index for placement in round-robin order. + + This class is not to be used directly by users. See instead + `replica_device_setter()` below. + """ + + def __init__(self, num_tasks): + """Create a new `_RoundRobinStrategy`. + + Args: + num_tasks: Number of ps tasks to cycle among. + """ + self._num_tasks = num_tasks + self._next_task = 0 + + def __call__(self, unused_op): + """Choose a ps task index for the given `Operation`. + + Args: + unused_op: An `Operation` to be placed on ps. + + Returns: + The next ps task index to use for the `Operation`. Returns the next + index, in the range `[offset, offset + num_tasks)`. + """ + task = self._next_task + self._next_task = (self._next_task + 1) % self._num_tasks + return task + + +class _ReplicaDeviceChooser: + """Class to choose devices for Ops in a replicated training setup. + + This class is not to be used directly by users. See instead + `replica_device_setter()` below. + """ + + def __init__(self, ps_tasks, ps_device, worker_device, merge_devices, ps_ops, + ps_strategy): + """Create a new `_ReplicaDeviceChooser`. + + Args: + ps_tasks: Number of tasks in the `ps` job. + ps_device: String. Name of the `ps` job. + worker_device: String. Name of the `worker` job. + merge_devices: Boolean. Set to True to allow merging of device specs. + ps_ops: List of strings representing `Operation` types that need to be + placed on `ps` devices. + ps_strategy: A callable invoked for every ps `Operation` (i.e. matched by + `ps_ops`), that takes the `Operation` and returns the ps task index to + use. + """ + self._ps_tasks = ps_tasks + self._ps_device = ps_device + self._worker_device = worker_device + self._merge_devices = merge_devices + self._ps_ops = ps_ops + self._ps_strategy = ps_strategy + + def device_function(self, op): + """Choose a device for `op`. + + Args: + op: an `Operation`. + + Returns: + The device to use for the `Operation`. + """ + # If we don't return early here, either merge_devices is True, or op.device + # is empty (in which case merging is a no-op). So we can always merge below. + if not self._merge_devices and op.device: + return op.device + + current_device = pydev.DeviceSpec.from_string(op.device or "") + + # The ps_device will be used for specified ops (ps_ops) whenever it is + # present and ps_tasks is non-zero. However, its task number will only be + # set (using ps_strategy) if there is a job field in ps_device that won't be + # changed by the job field (if present) in current_device. + node_def = op if isinstance(op, node_def_pb2.NodeDef) else op.node_def + if self._ps_tasks and self._ps_device and node_def.op in self._ps_ops: + ps_device = pydev.DeviceSpec.from_string(self._ps_device) + + current_job, ps_job = current_device.job, ps_device.job + if ps_job and (not current_job or current_job == ps_job): + ps_device = ps_device.replace(task=self._ps_strategy(op)) + + ps_device = ps_device.make_merged_spec(current_device) + return ps_device.to_string() + + worker_device = pydev.DeviceSpec.from_string(self._worker_device or "") + worker_device = worker_device.make_merged_spec(current_device) + return worker_device.to_string() + + +@tf_export(v1=["train.replica_device_setter"]) +def replica_device_setter(ps_tasks=0, + ps_device="/job:ps", + worker_device="/job:worker", + merge_devices=True, + cluster=None, + ps_ops=None, + ps_strategy=None): + """Return a `device function` to use when building a Graph for replicas. + + Device Functions are used in `with tf.device(device_function):` statement to + automatically assign devices to `Operation` objects as they are constructed, + Device constraints are added from the inner-most context first, working + outwards. The merging behavior adds constraints to fields that are yet unset + by a more inner context. Currently the fields are (job, task, cpu/gpu). + + If `cluster` is `None`, and `ps_tasks` is 0, the returned function is a no-op. + Otherwise, the value of `ps_tasks` is derived from `cluster`. + + By default, only Variable ops are placed on ps tasks, and the placement + strategy is round-robin over all ps tasks. A custom `ps_strategy` may be used + to do more intelligent placement, such as + `tf.contrib.training.GreedyLoadBalancingStrategy`. + + For example, + + ```python + # To build a cluster with two ps jobs on hosts ps0 and ps1, and 3 worker + # jobs on hosts worker0, worker1 and worker2. + cluster_spec = { + "ps": ["ps0:2222", "ps1:2222"], + "worker": ["worker0:2222", "worker1:2222", "worker2:2222"]} + with + tf.compat.v1.device(tf.compat.v1.train.replica_device_setter(cluster=cluster_spec)): + # Build your graph + v1 = tf.Variable(...) # assigned to /job:ps/task:0 + v2 = tf.Variable(...) # assigned to /job:ps/task:1 + v3 = tf.Variable(...) # assigned to /job:ps/task:0 + # Run compute + ``` + + Args: + ps_tasks: Number of tasks in the `ps` job. Ignored if `cluster` is + provided. + ps_device: String. Device of the `ps` job. If empty no `ps` job is used. + Defaults to `ps`. + worker_device: String. Device of the `worker` job. If empty no `worker` + job is used. + merge_devices: `Boolean`. If `True`, merges or only sets a device if the + device constraint is completely unset. merges device specification rather + than overriding them. + cluster: `ClusterDef` proto or `ClusterSpec`. + ps_ops: List of strings representing `Operation` types that need to be + placed on `ps` devices. If `None`, defaults to `STANDARD_PS_OPS`. + ps_strategy: A callable invoked for every ps `Operation` (i.e. matched by + `ps_ops`), that takes the `Operation` and returns the ps task index to + use. If `None`, defaults to a round-robin strategy across all `ps` + devices. + + Returns: + A function to pass to `tf.device()`. + + Raises: + TypeError if `cluster` is not a dictionary or `ClusterDef` protocol buffer, + or if `ps_strategy` is provided but not a callable. + """ + if cluster is not None: + if isinstance(cluster, server_lib.ClusterSpec): + cluster_spec = cluster.as_dict() + else: + cluster_spec = server_lib.ClusterSpec(cluster).as_dict() + # Get ps_job_name from ps_device by stripping "/job:". + ps_job_name = pydev.DeviceSpec.from_string(ps_device).job + if ps_job_name not in cluster_spec or cluster_spec[ps_job_name] is None: + return None + ps_tasks = len(cluster_spec[ps_job_name]) + + if ps_tasks == 0: + return None + + if ps_ops is None: + # TODO(sherrym): Variables in the LOCAL_VARIABLES collection should not be + # placed in the parameter server. + ps_ops = list(STANDARD_PS_OPS) + + if not merge_devices: + logging.warning( + "DEPRECATION: It is recommended to set merge_devices=true in " + "replica_device_setter") + if ps_strategy is None: + ps_strategy = _RoundRobinStrategy(ps_tasks) + if not callable(ps_strategy): + raise TypeError("ps_strategy must be callable") + chooser = _ReplicaDeviceChooser(ps_tasks, ps_device, worker_device, + merge_devices, ps_ops, ps_strategy) + return chooser.device_function diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/evaluation.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/evaluation.py new file mode 100644 index 0000000000000000000000000000000000000000..6c3502e8233fd9c5761da3d5a6c1f0407835bcd5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/evaluation.py @@ -0,0 +1,273 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Contains functions for evaluation and summarization of metrics.""" + +import math +import time + +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import init_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import state_ops +from tensorflow.python.ops import variable_scope +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.training import basic_session_run_hooks +from tensorflow.python.training import monitored_session +from tensorflow.python.training import session_run_hook + + +def _get_or_create_eval_step(): + """Gets or creates the eval step `Tensor`. + + Returns: + A `Tensor` representing a counter for the evaluation step. + + Raises: + ValueError: If multiple `Tensors` have been added to the + `tf.GraphKeys.EVAL_STEP` collection. + """ + graph = ops.get_default_graph() + eval_steps = graph.get_collection(ops.GraphKeys.EVAL_STEP) + if len(eval_steps) == 1: + return eval_steps[0] + elif len(eval_steps) > 1: + raise ValueError('Multiple tensors added to tf.GraphKeys.EVAL_STEP') + else: + counter = variable_scope.get_variable( + 'eval_step', + shape=[], + dtype=dtypes.int64, + initializer=init_ops.zeros_initializer(), + trainable=False, + collections=[ops.GraphKeys.LOCAL_VARIABLES, ops.GraphKeys.EVAL_STEP]) + return counter + + +def _get_latest_eval_step_value(update_ops): + """Gets the eval step `Tensor` value after running `update_ops`. + + Args: + update_ops: A list of `Tensors` or a dictionary of names to `Tensors`, which + are run before reading the eval step value. + + Returns: + A `Tensor` representing the value for the evaluation step. + """ + if isinstance(update_ops, dict): + update_ops = list(update_ops.values()) + + with ops.control_dependencies(update_ops): + return array_ops.identity(_get_or_create_eval_step().read_value()) + + +class _MultiStepStopAfterNEvalsHook(session_run_hook.SessionRunHook): + """Run hook used by the evaluation routines to run the `eval_ops` N times.""" + + def __init__(self, num_evals, steps_per_run=1): + """Constructs the run hook. + + Args: + num_evals: The number of evaluations to run for. if set to None, will + iterate the dataset until all inputs are exhausted. + steps_per_run: Number of steps executed per run call. + """ + self._num_evals = num_evals + self._evals_completed = None + self._steps_per_run_initial_value = steps_per_run + + def _set_evals_completed_tensor(self, updated_eval_step): + self._evals_completed = updated_eval_step + + def begin(self): + self._steps_per_run_variable = \ + basic_session_run_hooks.get_or_create_steps_per_run_variable() + + def after_create_session(self, session, coord): + # Update number of steps to run in the first run call + if self._num_evals is None: + steps = self._steps_per_run_initial_value + else: + steps = min(self._steps_per_run_initial_value, self._num_evals) + self._steps_per_run_variable.load(steps, session=session) + + def before_run(self, run_context): + return session_run_hook.SessionRunArgs( + {'evals_completed': self._evals_completed}) + + def after_run(self, run_context, run_values): + evals_completed = run_values.results['evals_completed'] + # Update number of steps to run in the next iteration + if self._num_evals is None: + steps = self._steps_per_run_initial_value + else: + steps = min(self._num_evals - evals_completed, + self._steps_per_run_initial_value) + self._steps_per_run_variable.load(steps, session=run_context.session) + + if self._num_evals is None: + logging.info('Evaluation [%d]', evals_completed) + else: + logging.info('Evaluation [%d/%d]', evals_completed, self._num_evals) + if self._num_evals is not None and evals_completed >= self._num_evals: + run_context.request_stop() + + +class _StopAfterNEvalsHook(session_run_hook.SessionRunHook): + """Run hook used by the evaluation routines to run the `eval_ops` N times.""" + + def __init__(self, num_evals, log_progress=True): + """Constructs the run hook. + + Args: + num_evals: The number of evaluations to run for. if set to None, will + iterate the dataset until all inputs are exhausted. + log_progress: Whether to log evaluation progress, defaults to True. + """ + # The number of evals to run for. + self._num_evals = num_evals + self._evals_completed = None + self._log_progress = log_progress + # Reduce logging frequency if there are 20 or more evaluations. + self._log_frequency = (1 if (num_evals is None or num_evals < 20) else + math.floor(num_evals / 10.)) + + def _set_evals_completed_tensor(self, updated_eval_step): + self._evals_completed = updated_eval_step + + def before_run(self, run_context): + return session_run_hook.SessionRunArgs( + {'evals_completed': self._evals_completed}) + + def after_run(self, run_context, run_values): + evals_completed = run_values.results['evals_completed'] + if self._log_progress: + if self._num_evals is None: + logging.info('Evaluation [%d]', evals_completed) + else: + if ((evals_completed % self._log_frequency) == 0 or + (self._num_evals == evals_completed)): + logging.info('Evaluation [%d/%d]', evals_completed, self._num_evals) + if self._num_evals is not None and evals_completed >= self._num_evals: + run_context.request_stop() + + +def _evaluate_once(checkpoint_path, + master='', + scaffold=None, + eval_ops=None, + feed_dict=None, + final_ops=None, + final_ops_feed_dict=None, + hooks=None, + config=None): + """Evaluates the model at the given checkpoint path. + + During a single evaluation, the `eval_ops` is run until the session is + interrupted or requested to finish. This is typically requested via a + `tf.contrib.training.StopAfterNEvalsHook` which results in `eval_ops` running + the requested number of times. + + Optionally, a user can pass in `final_ops`, a single `Tensor`, a list of + `Tensors` or a dictionary from names to `Tensors`. The `final_ops` is + evaluated a single time after `eval_ops` has finished running and the fetched + values of `final_ops` are returned. If `final_ops` is left as `None`, then + `None` is returned. + + One may also consider using a `tf.contrib.training.SummaryAtEndHook` to record + summaries after the `eval_ops` have run. If `eval_ops` is `None`, the + summaries run immediately after the model checkpoint has been restored. + + Note that `evaluate_once` creates a local variable used to track the number of + evaluations run via `tf.contrib.training.get_or_create_eval_step`. + Consequently, if a custom local init op is provided via a `scaffold`, the + caller should ensure that the local init op also initializes the eval step. + + Args: + checkpoint_path: The path to a checkpoint to use for evaluation. + master: The BNS address of the TensorFlow master. + scaffold: An tf.compat.v1.train.Scaffold instance for initializing variables + and restoring variables. Note that `scaffold.init_fn` is used by the + function to restore the checkpoint. If you supply a custom init_fn, then + it must also take care of restoring the model from its checkpoint. + eval_ops: A single `Tensor`, a list of `Tensors` or a dictionary of names to + `Tensors`, which is run until the session is requested to stop, commonly + done by a `tf.contrib.training.StopAfterNEvalsHook`. + feed_dict: The feed dictionary to use when executing the `eval_ops`. + final_ops: A single `Tensor`, a list of `Tensors` or a dictionary of names + to `Tensors`. + final_ops_feed_dict: A feed dictionary to use when evaluating `final_ops`. + hooks: List of `tf.estimator.SessionRunHook` callbacks which are run inside + the evaluation loop. + config: An instance of `tf.compat.v1.ConfigProto` that will be used to + configure the `Session`. If left as `None`, the default will be used. + + Returns: + The fetched values of `final_ops` or `None` if `final_ops` is `None`. + """ + eval_step = _get_or_create_eval_step() + + # Prepare the run hooks. + hooks = list(hooks or []) + + if eval_ops is not None: + if any(isinstance(h, _MultiStepStopAfterNEvalsHook) for h in hooks): + steps_per_run_variable = \ + basic_session_run_hooks.get_or_create_steps_per_run_variable() + update_eval_step = state_ops.assign_add( + eval_step, + math_ops.cast(steps_per_run_variable, dtype=eval_step.dtype), + use_locking=True) + else: + update_eval_step = state_ops.assign_add(eval_step, 1, use_locking=True) + + if isinstance(eval_ops, dict): + eval_ops['update_eval_step'] = update_eval_step + elif isinstance(eval_ops, (tuple, list)): + eval_ops = list(eval_ops) + [update_eval_step] + else: + eval_ops = [eval_ops, update_eval_step] + + eval_step_value = _get_latest_eval_step_value(eval_ops) + + for h in hooks: + if isinstance(h, (_StopAfterNEvalsHook, _MultiStepStopAfterNEvalsHook)): + h._set_evals_completed_tensor(eval_step_value) # pylint: disable=protected-access + + logging.info('Starting evaluation at ' + + time.strftime('%Y-%m-%dT%H:%M:%S', time.localtime())) + start = time.time() + # Prepare the session creator. + session_creator = monitored_session.ChiefSessionCreator( + scaffold=scaffold, + checkpoint_filename_with_path=checkpoint_path, + master=master, + config=config) + + final_ops_hook = basic_session_run_hooks.FinalOpsHook(final_ops, + final_ops_feed_dict) + hooks.append(final_ops_hook) + + with monitored_session.MonitoredSession( + session_creator=session_creator, hooks=hooks) as session: + if eval_ops is not None: + while not session.should_stop(): + session.run(eval_ops, feed_dict) + logging.info('Inference Time : {:0.5f}s'.format(time.time() - start)) + + logging.info('Finished evaluation at ' + + time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime())) + return final_ops_hook.final_ops_values diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/experimental/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/experimental/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/experimental/loss_scale.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/experimental/loss_scale.py new file mode 100644 index 0000000000000000000000000000000000000000..53eb63468dde2de7562ebfec34eefb1a707e8c73 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/experimental/loss_scale.py @@ -0,0 +1,453 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Contains LossScale classes.""" +import abc + +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.distribute import reduce_util +from tensorflow.python.eager import context +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import indexed_slices +from tensorflow.python.framework import ops +from tensorflow.python.ops import cond +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import variable_v1 +from tensorflow.python.ops import variables +from tensorflow.python.trackable import base as trackable +from tensorflow.python.util import deprecation +from tensorflow.python.util import nest +from tensorflow.python.util.tf_export import tf_export + + +@deprecation.deprecated_endpoints('mixed_precision.experimental.LossScale', + 'train.experimental.LossScale') +@tf_export( + v1=[ + 'mixed_precision.LossScale', + 'mixed_precision.experimental.LossScale', + 'train.experimental.LossScale' + ]) +class LossScale(trackable.Trackable, metaclass=abc.ABCMeta): + """Base class for all TF1 loss scales. + + This is an abstract base class, so you cannot instantiate it directly. + Instead, use one of its concrete subclasses: + * `tf.compat.v1.mixed_precision.DynamicLossScale` + * `tf.compat.v1.mixed_precision.FixedLossScale` + + Loss scaling is a process that multiplies the loss by a multiplier called the + loss scale, and divides each gradient by the same multiplier. The pseudocode + for this process is: + + ``` + loss = ... + loss *= loss_scale + grads = gradients(loss, vars) + grads /= loss_scale + ``` + + Mathematically, loss scaling has no effect, but can help avoid numerical + underflow in intermediate gradients when float16 tensors are used for mixed + precision training. By multiplying the loss, each intermediate gradient will + have the same multiplier applied. + + Instances of this class represent a loss scale. Calling instances of this + class returns the loss scale as a scalar float32 tensor, while method + `update()` updates the loss scale depending on the values of the gradients. + Optimizers use instances of this class to scale loss and gradients. + + In most functions that accept a LossScale, you can also pass an int (such as + 8) to create a `FixedLossScale` or the string `"dynamic"` to create a dynamic + loss scale. + """ + + def __init__(self): + """Initializes the loss scale class.""" + self._weights = {} + + @abc.abstractmethod + def __call__(self): + """Returns the current loss scale as a scalar `float32` tensor.""" + pass + + @abc.abstractmethod + def update(self, grads): + """Updates the value of the loss scale. + + The loss scale will be potentially updated, based on the value of `grads`. + The tensor returned by calling this class is only updated when this function + is evaluated. + + In eager mode, this directly updates the loss scale, so that calling + `__call__` will return the newly updated loss scale. In graph mode, + this returns an op that, when evaluated, updates the loss scale. + + This function also returns a `should_apply_gradients` bool. If False, + gradients should not be applied to the variables that step, as nonfinite + gradients were found, and the loss scale has been be updated to reduce the + chance of finding nonfinite gradients in the next step. Some loss scale + classes will always return True, as they cannot adjust themselves in + response to nonfinite gradients. + + When a DistributionStrategy is used, this function may only be called in a + cross-replica context. + + Args: + grads: A nested structure of unscaled gradients, each which is the + gradient of the loss with respect to a weight. The gradients should have + already been divided by the loss scale being before passed to this + function. 'None' gradients are accepted, and are ignored. + + Returns: + update_op: In eager mode, None. In graph mode, an op to update the loss + scale. + should_apply_gradients: Either a bool or a scalar boolean tensor. If + False, the caller should skip applying `grads` to the variables this + step. + """ + pass + + def _add_weight(self, name, initial_value, dtype=None): + """Adds a weight to this loss scale. + + Args: + name: Variable name. + initial_value: The variable's initial value. + dtype: The type of the variable. + + Returns: + A variable. + + Raises: + RuntimeError: If a weight with `name` has already been added. + """ + variable = variable_v1.VariableV1( + initial_value=initial_value, + name=name, + dtype=dtype, + trainable=False, + use_resource=True, + synchronization=variables.VariableSynchronization.AUTO, + # Set aggregation to NONE, as loss scaling variables should never be + # aggregated. + aggregation=variables.VariableAggregation.NONE) + if context.executing_eagerly(): + graph_key = None + else: + graph = ops.get_default_graph() + graph_key = graph._graph_key # pylint: disable=protected-access + + key = (name, graph_key) + if self._weights.get(key, None) is not None: + raise RuntimeError('Duplicate variables detected. {}'.format(key)) + self._weights[key] = variable + self._handle_deferred_dependencies(name=name, trackable=variable) + return variable + + def _trackable_children(self, + save_type=trackable.SaveType.CHECKPOINT, + **kwargs): + """From Trackable. Gather graph-specific weights to save.""" + if context.executing_eagerly(): + graph_key = None + else: + graph = ops.get_default_graph() + graph_key = graph._graph_key # pylint: disable=protected-access + weights = {} + for (name, g), v in sorted(self._weights.items(), key=lambda i: i[0][0]): + if g == graph_key: + weights[name] = v + weights.update( + super(LossScale, self)._trackable_children(save_type, **kwargs)) + return weights + + def _lookup_dependency(self, name, cached_dependencies=None): + """From Trackable. Find a weight in the current graph.""" + unconditional = super(LossScale, self)._lookup_dependency( + name, cached_dependencies) + if unconditional is not None: + return unconditional + if context.executing_eagerly(): + graph_key = None + else: + graph = ops.get_default_graph() + graph_key = graph._graph_key # pylint: disable=protected-access + return self._weights.get((name, graph_key), None) + + @abc.abstractmethod + def get_config(self): + """Returns the config of this loss scale.""" + pass + + @classmethod + def from_config(cls, config): + """Creates the LossScale from its config.""" + return cls(**config) + + +@deprecation.deprecated_endpoints('mixed_precision.experimental.FixedLossScale', + 'train.experimental.FixedLossScale') +@tf_export( + v1=[ + 'mixed_precision.FixedLossScale', + 'mixed_precision.experimental.FixedLossScale', + 'train.experimental.FixedLossScale' + ]) +class FixedLossScale(LossScale): + """Loss scale with a fixed value. + + The loss scale is not updated for the lifetime of instances of this class. + A given instance of this class always returns the same number when called. + """ + + @deprecation.deprecated( + None, 'Use tf.keras.mixed_precision.LossScaleOptimizer instead. ' + 'LossScaleOptimizer now has all the functionality of ' + 'FixedLossScale') + def __init__(self, loss_scale_value): + """Creates the fixed loss scale. + + Args: + loss_scale_value: A Python float. Its ideal value varies depending on + models to run. Choosing a too small loss_scale might affect model + quality; a too big loss_scale might cause inf or nan. There is no single + right loss_scale to apply. There is no harm choosing a relatively big + number as long as no nan or inf is encountered in training. + + Raises: + ValueError: If loss_scale_value is less than 1. + """ + super(FixedLossScale, self).__init__() + if not isinstance(loss_scale_value, (int, float)): + raise ValueError('loss_scale_value must be a Python int or float.') + if loss_scale_value < 1: + raise ValueError('loss_scale_value must be at least 1.') + # It's important we do not create tensors in the constructor, as such + # tensors might be on a different device or tf.function vs when the tensor + # is used. This would hurt performance. Therefore, we do not create a tensor + # from loss_scale_value, but instead leave it as a Python float. + # TODO(reedwm): Also do not create tensors in the DynamicLossScale + # constructor. + self._loss_scale_value = float(loss_scale_value) + + def __call__(self): + return ops.convert_to_tensor(self._loss_scale_value) + + def update(self, grads): + del grads + return control_flow_ops.no_op(), True + + def __repr__(self): + return 'FixedLossScale(%s)' % self._loss_scale_value + + def get_config(self): + return {'loss_scale_value': self._loss_scale_value} + + +def _is_all_finite(grads): + """Returns a scalar boolean tensor indicating if all gradients are finite.""" + def raw_values(g): + return g.values if isinstance(g, indexed_slices.IndexedSlices) else g + + is_finite_per_grad = [ + math_ops.reduce_all(math_ops.is_finite(raw_values(g))) + for g in grads + if g is not None + ] + return math_ops.reduce_all(is_finite_per_grad) + + +def _op_in_graph_mode(tensor): + """Returns the tensor's op in graph mode, or the tensor in eager mode. + + This is useful because sometimes an op is needed in graph mode instead of a + tensor. In eager mode, there are no ops. + + Args: + tensor: A tensor. + + Returns: + The tensor's op in graph mode. The tensor in eager mode. + """ + if context.executing_eagerly(): + return tensor + return tensor.op + + +def _assign_if_finite(var, value): + """Assigns a value to a variable if the value is finite.""" + return cond.cond( + math_ops.is_finite(value), lambda: _op_in_graph_mode(var.assign(value)), + control_flow_ops.no_op) + + +@deprecation.deprecated_endpoints( + 'mixed_precision.experimental.DynamicLossScale', + 'train.experimental.DynamicLossScale') +@tf_export( + v1=[ + 'mixed_precision.DynamicLossScale', + 'mixed_precision.experimental.DynamicLossScale', + 'train.experimental.DynamicLossScale' + ]) +class DynamicLossScale(LossScale): + """Loss scale that dynamically adjusts itself. + + Dynamic loss scaling works by adjusting the loss scale as training progresses. + The goal is to keep the loss scale as high as possible without overflowing the + gradients. As long as the gradients do not overflow, raising the loss scale + never hurts. + + The algorithm starts by setting the loss scale to an initial value. Every N + steps that the gradients are finite, the loss scale is increased by some + factor. However, if a NaN or Inf gradient is found, the gradients for that + step are not applied, and the loss scale is decreased by the factor. This + process tends to keep the loss scale as high as possible without gradients + overflowing. + """ + + @deprecation.deprecated( + None, 'Use tf.keras.mixed_precision.LossScaleOptimizer instead. ' + 'LossScaleOptimizer now has all the functionality of ' + 'DynamicLossScale') + def __init__(self, + initial_loss_scale=2 ** 15, # See docstring for why this is big. + increment_period=2000, + multiplier=2.): + """Creates the dynamic loss scale. + + Args: + initial_loss_scale: A Python float. The loss scale to use at the + beginning. It's better to start this at a very high number, because a + loss scale that is too high gets lowered far more quickly than a loss + scale that is too low gets raised. The default is 2 ** 15, which is + approximately half the maximum float16 value. + increment_period: Increases loss scale every `increment_period` + consecutive steps that finite gradients are encountered. If a nonfinite + gradient is encountered, the count is reset back to zero. + multiplier: The multiplier to use when increasing or decreasing the loss + scale. + """ + super(DynamicLossScale, self).__init__() + self._initial_loss_scale = float(initial_loss_scale) + self._increment_period = int(increment_period) + self._multiplier = float(multiplier) + + self._current_loss_scale = self._add_weight( + name='current_loss_scale', + dtype=dtypes.float32, + initial_value=self._initial_loss_scale) + # The number of consecutive steps with finite gradients since the last + # nonfinite gradient or change in loss scale. + self._num_good_steps = self._add_weight( + name='good_steps', dtype=dtypes.int64, initial_value=0) + + @property + def initial_loss_scale(self): + return self._initial_loss_scale + + @property + def increment_period(self): + return self._increment_period + + @property + def multiplier(self): + return self._multiplier + + def __call__(self): + return ops.convert_to_tensor(self._current_loss_scale) + + def update(self, grads): + """Updates loss scale based on if gradients are finite in current step.""" + grads = nest.flatten(grads) + if distribute_lib.has_strategy(): + distribution = distribute_lib.get_cross_replica_context() + + def get_is_finite(grads): + is_finite = _is_all_finite(grads) + # We cast to float, because we cannot reduce booleans with + # DistributionStrategy. + return math_ops.cast(is_finite, dtypes.float32) + + is_finite_float = distribution.extended.call_for_each_replica( + get_is_finite, args=(grads,)) + reduced_is_finite_float = distribution.reduce(reduce_util.ReduceOp.SUM, + is_finite_float, axis=None) + is_finite = math_ops.equal(reduced_is_finite_float, + distribution.num_replicas_in_sync) + else: + is_finite = _is_all_finite(grads) + + def update_if_finite_grads(): + """Update assuming the gradients are finite.""" + + def incr_loss_scale(): + new_loss_scale = self._current_loss_scale * self._multiplier + return control_flow_ops.group( + _assign_if_finite(self._current_loss_scale, new_loss_scale), + self._num_good_steps.assign(0)) + + return cond.cond( + self._num_good_steps + 1 >= self._increment_period, + incr_loss_scale, lambda: _op_in_graph_mode( + self._num_good_steps.assign_add(1))) + + def update_if_not_finite_grads(): + """Update assuming the gradients are nonfinite.""" + + new_loss_scale = math_ops.maximum( + self._current_loss_scale / self._multiplier, 1) + return control_flow_ops.group( + self._num_good_steps.assign(0), + self._current_loss_scale.assign(new_loss_scale)) + + update_op = cond.cond(is_finite, update_if_finite_grads, + update_if_not_finite_grads) + should_apply_gradients = is_finite + return update_op, should_apply_gradients + + def __repr__(self): + if context.executing_eagerly(): + return ('DynamicLossScale(current_loss_scale=%s, num_good_steps=%s, ' + 'initial_loss_scale=%s, increment_period=%s, multiplier=%s)' % + (self._current_loss_scale.numpy(), self._num_good_steps.numpy(), + self.initial_loss_scale, self.increment_period, self.multiplier)) + else: + return ('DynamicLossScale(initial_loss_scale=%s, increment_period=%s, ' + 'multiplier=%s)' % + (self.initial_loss_scale, self.increment_period, self.multiplier)) + + def get_config(self): + return { + 'initial_loss_scale': self.initial_loss_scale, + 'increment_period': self.increment_period, + 'multiplier': self.multiplier, + } + + +def get(identifier): + """Get a loss scale object.""" + if isinstance(identifier, (int, float)): + return FixedLossScale(identifier) + if identifier == 'dynamic': + return DynamicLossScale() + if isinstance(identifier, LossScale): + return identifier + elif identifier is None: + return None + else: + raise ValueError('Could not interpret loss scale identifier: %s' % + identifier) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/experimental/loss_scale_optimizer.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/experimental/loss_scale_optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..703867048742c03937b04839d2840362642ac667 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/experimental/loss_scale_optimizer.py @@ -0,0 +1,251 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Contains LossScale classes.""" +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.framework import indexed_slices +from tensorflow.python.framework import smart_cond +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.training import optimizer +from tensorflow.python.training.experimental import loss_scale as loss_scale_module +from tensorflow.python.util import deprecation +from tensorflow.python.util.tf_export import tf_export + + +@deprecation.deprecated_endpoints( + 'train.experimental.MixedPrecisionLossScaleOptimizer') +@tf_export(v1=['mixed_precision.MixedPrecisionLossScaleOptimizer', + 'train.experimental.MixedPrecisionLossScaleOptimizer']) +class MixedPrecisionLossScaleOptimizer(optimizer.Optimizer): + """An optimizer that applies loss scaling. + + Loss scaling is a process that multiplies the loss by a multiplier called the + loss scale, and divides each gradient by the same multiplier. The pseudocode + for this process is: + + ``` + loss = ... + loss *= loss_scale + grads = gradients(loss, vars) + grads /= loss_scale + ``` + + Mathematically, loss scaling has no effect, but can help avoid numerical + underflow in intermediate gradients when float16 tensors are used for mixed + precision training. By multiplying the loss, each intermediate gradient will + have the same multiplier applied. + + The loss scale can either be a fixed constant, chosen by the user, or be + dynamically determined. Dynamically determining the loss scale is convenient + as a loss scale does not have to be explicitly chosen. However it reduces + performance. + + This optimizer wraps another optimizer and applies loss scaling to it via a + `LossScale`. Loss scaling is applied whenever gradients are + computed, such as through `minimize()`. + """ + + def __init__(self, opt, loss_scale): + if not isinstance(opt, optimizer.Optimizer): + raise ValueError('"opt" must be an instance of Optimizer, but got: %s' % + type(opt)) + self._optimizer = opt + + use_locking = opt._use_locking # pylint: disable=protected-access + name = opt.get_name() + super(MixedPrecisionLossScaleOptimizer, self).__init__(use_locking, name) + + self._loss_scale = loss_scale_module.get(loss_scale) + if self._loss_scale is None: + raise ValueError('loss_scale cannot be None') + self._track_trackable(self._optimizer, 'base_optimizer') + self._track_trackable(self._loss_scale, 'loss_scale') + + def _doing_dynamic_loss_scaling(self): + """Check if `_loss_scale` dynamically manages the loss scale.""" + return isinstance(self._loss_scale, loss_scale_module.DynamicLossScale) + + def compute_gradients(self, + loss, + var_list=None, + gate_gradients=optimizer.Optimizer.GATE_OP, + aggregation_method=None, + colocate_gradients_with_ops=False, + grad_loss=None): + """Compute gradients of `loss` for the variables in `var_list`. + + This adjusts the dynamic range of the gradient evaluation by scaling up + the `loss` value. The gradient values are then scaled back down by the + reciprocal of the loss scale. This is useful in reduced precision training + where small gradient values would otherwise underflow the representable + range. + + Args: + loss: A Tensor containing the value to minimize or a callable taking no + arguments which returns the value to minimize. When eager execution is + enabled it must be a callable. + var_list: Optional list or tuple of `tf.Variable` to update to minimize + `loss`. Defaults to the list of variables collected in the graph under + the key `GraphKeys.TRAINABLE_VARIABLES`. + gate_gradients: How to gate the computation of gradients. Can be + `GATE_NONE`, `GATE_OP`, or `GATE_GRAPH`. + aggregation_method: Specifies the method used to combine gradient terms. + Valid values are defined in the class `AggregationMethod`. + colocate_gradients_with_ops: If True, try colocating gradients with the + corresponding op. + grad_loss: Optional. A `Tensor` holding the gradient computed for `loss`. + + Returns: + A list of (gradient, variable) pairs. Variable is always present, but + gradient can be `None`. + """ + loss = self._scale_loss(loss) + grads_and_vars = self._optimizer.compute_gradients( + loss=loss, + var_list=var_list, + gate_gradients=gate_gradients, + aggregation_method=aggregation_method, + colocate_gradients_with_ops=colocate_gradients_with_ops, + grad_loss=grad_loss) + + grads = [g for g, _ in grads_and_vars] + variables = [v for _, v in grads_and_vars] + unscaled_grads = self._unscale_grads(grads) + return list(zip(unscaled_grads, variables)) + + def _scale_loss(self, loss): + loss_scale = self._loss_scale() + if callable(loss): + def new_loss(): + loss_val = loss() + return loss_val * math_ops.cast(loss_scale, loss_val.dtype) + return new_loss + else: + return loss * math_ops.cast(loss_scale, loss.dtype) + + def _unscale_grads(self, grads): + loss_scale = self._loss_scale() + loss_scale_reciprocal = 1 / loss_scale + return [ + None if g is None else self._scale_grad(g, loss_scale_reciprocal) + for g in grads + ] + + def _scale_grad(self, grad, loss_scale_reciprocal): + if isinstance(grad, indexed_slices.IndexedSlices): + grad_vals = grad.values * loss_scale_reciprocal + return indexed_slices.IndexedSlices(grad_vals, grad.indices, + grad.dense_shape) + return grad * loss_scale_reciprocal + + def apply_gradients(self, grads_and_vars, global_step=None, name=None): + """Apply gradients to variables. + + This is the second part of `minimize()`. It returns an `Operation` that + conditionally applies gradients if all gradient values are finite. + Otherwise no update is performed (nor is `global_step` incremented). + + Args: + grads_and_vars: List of (gradient, variable) pairs as returned by + `compute_gradients()`. + global_step: Optional `Variable` to increment by one after the variables + have been updated. + name: Optional name for the returned operation. Default to the name + passed to the `Optimizer` constructor. + + Returns: + An `Operation` that conditionally applies the specified gradients. If + `global_step` was not None, that operation also increments `global_step`. + + Raises: + RuntimeError: If you should use `_distributed_apply()` instead. + """ + if distribute_lib.in_cross_replica_context(): + raise ValueError('apply_gradients() must be called in a replica context.') + + if not self._doing_dynamic_loss_scaling(): + return self._optimizer.apply_gradients(grads_and_vars, global_step, name) + + replica_context = distribute_lib.get_replica_context() + grads_and_vars = tuple(grads_and_vars) + + # TODO(nluehr) cleanup GraphKeys.TRAIN_OP + return replica_context.merge_call( + self._distributed_apply, args=(grads_and_vars, global_step, name)) + + def _distributed_apply(self, + distribution, + grads_and_vars, + global_step=None, + name=None): + """A version of `apply_gradients` for cross replica context. + + When users are in a cross replica strategy, they must call this rather than + `apply_gradients()`. + + Args: + distribution: a `DistributionStrategy` object. + grads_and_vars: List of (gradient, variable) pairs as returned by + `compute_gradients()` and then aggregated across replicas. + global_step: Optional (mirrored) `Variable` to increment by one after the + variables have been updated. + name: Optional name for the returned operation. Default to the name passed + to the `Optimizer` constructor. + + Returns: + An `Operation` that applies the specified gradients across all + replicas. If `global_step` was not None, that operation also + increments `global_step` + """ + name = name if name is not None else self.get_name() + grads = [g for g, _ in grads_and_vars] + loss_scale_update_op, should_apply_grads = (self._loss_scale.update(grads)) + + def apply_fn(): + return self._apply_gradients(distribution, grads_and_vars, global_step, + name + '-wrapped') + + maybe_apply_op = smart_cond.smart_cond(should_apply_grads, apply_fn, + control_flow_ops.no_op) + return control_flow_ops.group( + maybe_apply_op, loss_scale_update_op, name=name) + + def _apply_gradients(self, distribution, grads_and_vars, global_step, name): + """Unconditionally apply gradients in cross replica context.""" + update_ops = distribution.extended.call_for_each_replica( + self._optimizer.apply_gradients, + args=(grads_and_vars, global_step, name)) + return distribution.group(update_ops) + + def _apply_sparse(self, grad, var): + """This function should never be called.""" + raise RuntimeError('This function should never be called') + + def _apply_dense(self, grad, var): + """This function should never be called.""" + raise RuntimeError('This function should never be called') + + def _resource_apply_sparse(self, grad, handle, indices): + """This function should never be called.""" + raise RuntimeError('This function should never be called') + + def _resource_apply_dense(self, grad, handle): + """This function should never be called.""" + raise RuntimeError('This function should never be called') + + def variables(self): + """Returns the variables of the Optimizer.""" + return (self._optimizer.variables() + + list(self._loss_scale._weights.values())) # pylint: disable=protected-access diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/experimental/mixed_precision.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/experimental/mixed_precision.py new file mode 100644 index 0000000000000000000000000000000000000000..5fde6a8b2515d947b1a03357c117473b17f78d34 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/experimental/mixed_precision.py @@ -0,0 +1,248 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Contains functions to use mixed precision with the graph rewrite.""" + +from tensorflow.python.framework import config +from tensorflow.python.platform import tf_logging +from tensorflow.python.training import optimizer +from tensorflow.python.training.experimental import loss_scale_optimizer as loss_scale_optimizer_v1 +from tensorflow.python.training.experimental import mixed_precision_global_state +from tensorflow.python.util import deprecation +from tensorflow.python.util.tf_export import tf_export + + +# A mapping between optimizers and (wrapper_fn, wrapper_cls) pairs. wrapper_cls +# is a loss scale optimizer class, and wrapper_fn is a function that takes in +# an optimizer and LossScale and returns a wrapper_cls instance. +_REGISTERED_WRAPPER_OPTIMIZER_CLS = { + optimizer.Optimizer: + (loss_scale_optimizer_v1.MixedPrecisionLossScaleOptimizer,) * 2, +} + + +@tf_export('__internal__.mixed_precision.register_loss_scale_wrapper', v1=[]) +def register_loss_scale_wrapper(optimizer_cls, wrapper_fn, wrapper_cls=None): + """Registers a loss scale optimizer wrapper. + + `tf.compat.v1.mixed_precision.enable_mixed_precision_graph_rewrite` + automatically wraps an optimizer with an optimizer wrapper that performs loss + scaling. This function registers a + `(base_cls, wrapper_fn, wrapper_cls)` triple + that is used by `enable_mixed_precision_graph_rewrite`, where + `wrapper_fn` is called to create a `wrapper_cls` instance that wraps an + `optimizer_cls` instance. + + Args: + optimizer_cls: A base optimizer class, e.g. `tf.keras.optimizers.Optimizer`. + wrapper_fn: A function that takes in arguments "optimizer" and + "loss_scale", and returns a loss scale optimizer of type "wrapper_cls" + that wraps "optimizer". + wrapper_cls: A loss scale optimizer class. Defaults to `wrapper_fn`, in + which case `wrapper_fn` should be a loss scale optimizer class whose + constructor takes in arguments "optimizer" and "loss_scale". + """ + _REGISTERED_WRAPPER_OPTIMIZER_CLS[optimizer_cls] = ( + wrapper_fn, wrapper_cls or wrapper_fn) + + +def _wrap_optimizer(opt, loss_scale): + """Wraps an optimizer with a LossScaleOptimizer.""" + + for _, wrapper_optimizer in _REGISTERED_WRAPPER_OPTIMIZER_CLS.values(): + if isinstance(opt, wrapper_optimizer): + raise ValueError('"opt" must not already be an instance of a {cls}. ' + '`enable_mixed_precision_graph_rewrite` will ' + 'automatically wrap the optimizer with a ' + '{cls}.' + .format(cls=wrapper_optimizer.__name__)) + + for optimizer_cls, (wrapper_fn, _) in ( + _REGISTERED_WRAPPER_OPTIMIZER_CLS.items()): + if isinstance(opt, optimizer_cls): + return wrapper_fn(opt, loss_scale) + + raise ValueError('"opt" must be an instance of a tf.train.Optimizer or a ' + 'tf.keras.optimizers.Optimizer, but got: %s' % opt) + + +@deprecation.deprecated_endpoints( + 'train.experimental.enable_mixed_precision_graph_rewrite') +@tf_export(v1=['mixed_precision.enable_mixed_precision_graph_rewrite', + 'train.experimental.enable_mixed_precision_graph_rewrite']) +def enable_mixed_precision_graph_rewrite_v1(opt, loss_scale='dynamic'): + """Enable mixed precision via a graph rewrite. + + Mixed precision is the use of both float32 and float16 data types when + training a model to improve performance. This is achieved via a graph rewrite + operation and a loss-scale optimizer. + + Performing arithmetic operations in float16 takes advantage of specialized + processing units, such as NVIDIA Tensor Cores, for much higher arithmetic + throughput. However, due to the smaller representable range, performing the + entire training with float16 can result in gradient underflow, that is, small + gradient values becoming zeroes. Instead, performing only select arithmetic + operations in float16 results in higher throughput and decreased training + time when using compatible hardware accelerators while also reducing memory + usage, typically without sacrificing model accuracy. + + Note: While the mixed precision rewrite changes the datatype of various + layers throughout the model, the same accuracy reached in float32 is + expected. If a `NaN` gradient occurs with dynamic loss scaling, the model + update for that batch is skipped. In this case, the global step count is not + incremented, and the `LossScaleOptimizer` attempts to decrease the loss + scaling value to avoid `NaN` values in subsequent iterations. This approach + has been shown to achieve the same accuracy as float32 and, in most cases, + better training throughput. + + Example: + + ```python + model = tf.keras.models.Sequential([ + tf.keras.layers.Dense(64, activation='relu'), + tf.keras.layers.Dense(64, activation='softmax'), + ]) + + opt = tf.keras.optimizers.SGD() + opt = tf.train.experimental.enable_mixed_precision_graph_rewrite(opt) + model.compile(loss="mse", optimizer=opt) + + x_train = np.random.random((1024, 64)) + y_train = np.random.random((1024, 64)) + model.fit(x_train, y_train) + ``` + + Calling `enable_mixed_precision_graph_rewrite(opt)` enables the graph rewrite + operation before computing gradients. The function additionally returns an + `Optimizer` (`opt`) wrapped with a `LossScaleOptimizer`. This prevents + underflow in the float16 tensors during the backward pass. An optimizer of + type `tf.train.Optimizer` or `tf.keras.optimizers.Optimizer` must be passed + to this function, which will then be wrapped to use loss scaling. + + The graph rewrite operation changes the `dtype` of certain operations in the + graph from float32 to float16. There are several categories of operations + that are either included or excluded by this rewrite operation. The following + categories of Ops are defined inside corresponding functions under the class + `AutoMixedPrecisionLists` in + + auto_mixed_precision_lists.h: + + * `ClearList`: Ops that do not have numerically significant adverse effects. + E.g. `ArgMax` and `Floor`. + * `AllowList`: Ops that are considered numerically safe for execution in + float16, and thus are always converted. E.g. `Conv2D`. + * `DenyList`: Ops that are numerically unsafe to execute in float16 and + can negatively affect downstream nodes. E.g. `Softmax`. + * `GrayList`: Ops that are considered numerically safe for execution in + float16 unless downstream from a DenyList Op. E.g. `Add` and `AvgPool`. + + When this function is used, gradients should only be computed and applied + with the returned optimizer, either by calling `opt.minimize()` or + `opt.compute_gradients()` followed by `opt.apply_gradients()`. + Gradients should not be computed with `tf.gradients` or `tf.GradientTape`. + This is because the returned optimizer will apply loss scaling, and + `tf.gradients` or `tf.GradientTape` will not. If you do directly use + `tf.gradients` or `tf.GradientTape`, your model may not converge due to + float16 underflow problems. + + When eager execution is enabled, the mixed precision graph rewrite is only + enabled within `tf.function`s, as outside `tf.function`s, there is no graph. + + For NVIDIA GPUs with Tensor cores, as a general performance guide, dimensions + (such as batch size, input size, output size, and channel counts) + should be powers of two if under 256, or otherwise divisible by 8 if above + 256. For more information, check out the + [NVIDIA Deep Learning Performance Guide]( + https://docs.nvidia.com/deeplearning/sdk/dl-performance-guide/index.html). + + Currently, mixed precision is only enabled on NVIDIA Tensor Core GPUs with + Compute Capability 7.0 and above (Volta, Turing, or newer architectures). The + parts of the graph on CPUs and TPUs are untouched by the graph rewrite. + + Raises: + `ValueError`, if the `tf.keras.mixed_precision` API is also used by calling + `tf.keras.mixed_precision.set_global_policy`. Only one mixed precision + API can be used. + + Args: + opt: An instance of a `tf.keras.optimizers.Optimizer` or a + `tf.train.Optimizer`. + loss_scale: Either an int/float, the string `"dynamic"`, or an instance of + a `tf.mixed_precision.experimental.LossScale`. The loss scale to use. It + is recommended to keep this as its default value of `"dynamic"`, which + will adjust the scaling automatically to prevent `Inf` or `NaN` values. + + Returns: + A version of `opt` that will use loss scaling to prevent underflow. + """ + if mixed_precision_global_state.is_using_mixed_precision_policy(): + raise ValueError( + 'The mixed precision graph rewrite cannot be enabled, because the ' + 'global Keras dtype Policy has been set to a mixed precision policy. ' + 'At most, one of the following can be called:\n\n' + ' 1. tf.keras.mixed_precision.set_global_policy() with a mixed ' + 'precision policy (You called this first)\n\n' + ' 2. tf.train.experimental.enable_mixed_precision_graph_rewrite() ' + '(You called this second)\n' + 'You called both functions, which is an error, because both functions ' + 'enable you to use mixed precision. If in doubt which function to use, ' + 'use the first, as it supports Eager execution and is more ' + 'customizable.') + + if mixed_precision_global_state.non_mixed_precision_session_created(): + # TODO(reedwm): Give the stacktrace of the existing Sessions. And if the + # Sessions have already been closed, do not raise this error message. + tf_logging.warn('You already have existing Sessions that do not use mixed ' + 'precision. enable_mixed_precision_graph_rewrite() will ' + 'not affect these Sessions.') + opt = _wrap_optimizer(opt, loss_scale) + config.set_optimizer_experimental_options({'auto_mixed_precision': True}) + mixed_precision_global_state.set_mixed_precision_graph_rewrite_enabled(True) + return opt + + +@deprecation.deprecated_endpoints( + 'train.experimental.disable_mixed_precision_graph_rewrite') +@tf_export(v1=['mixed_precision.disable_mixed_precision_graph_rewrite', + 'train.experimental.disable_mixed_precision_graph_rewrite']) +def disable_mixed_precision_graph_rewrite_v1(): + """Disables the mixed precision graph rewrite. + + After this is called, the mixed precision graph rewrite will no longer run for + new Sessions, and so float32 operations will no longer be converted to float16 + in such Sessions. However, any existing Sessions will continue to have the + graph rewrite enabled if they were created after + `enable_mixed_precision_graph_rewrite` was called but before + `disable_mixed_precision_graph_rewrite` was called. + + This does not undo the effects of loss scaling. Any optimizers wrapped with a + LossScaleOptimizer will continue to do loss scaling, although this loss + scaling will no longer be useful if the optimizer is used in new Sessions, as + the graph rewrite no longer converts the graph to use float16. + + This function is useful for unit testing. A unit tests can test using the + mixed precision graph rewrite, then disable it so future unit tests continue + using float32. If this is done, unit tests should not share a single session, + as `enable_mixed_precision_graph_rewrite` and + `disable_mixed_precision_graph_rewrite` have no effect on existing sessions. + """ + # We only have a separate V1 version of this function, because the V1 + # docstring mentions sessions. + if (not + mixed_precision_global_state.is_mixed_precision_graph_rewrite_enabled()): + tf_logging.warn('disable_mixed_precision_graph_rewrite() called when mixed ' + 'precision is already disabled.') + config.set_optimizer_experimental_options({'auto_mixed_precision': False}) + mixed_precision_global_state.set_mixed_precision_graph_rewrite_enabled(False) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/experimental/mixed_precision_global_state.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/experimental/mixed_precision_global_state.py new file mode 100644 index 0000000000000000000000000000000000000000..92d4abc182a1abf219d998e68776d674fb6f9e65 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/experimental/mixed_precision_global_state.py @@ -0,0 +1,66 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Contains global variables related to mixed precision. + +This is not part of mixed_precision.py to avoid a circular dependency. +mixed_precision.py depends on Session, and Session depends on this file. +""" + +from tensorflow.python.util.tf_export import tf_export + +# Whether the mixed precision graph rewrite has been enabled or not with +# `enable_mixed_precision_graph_rewrite`. Used to turn on auto_mixed_precision +# in ConfigProtos passed to Sessions. +_mixed_precision_graph_rewrite_is_enabled = False + + +# True if a Session has been created without the mixed precision graph rewrite +# being enabled. Used to give a warning if mixed precision is enabled after a +# Session has already been created. +_non_mixed_precision_session_created = False + +# Whether the global tf.keras.mixed_precision.Policy uses mixed precision. Used +# to raise an error message if both a mixed Policy and the graph rewrite are +# used at the same time. +_using_mixed_precision_policy = False + + +@tf_export('__internal__.train.is_mixed_precision_graph_rewrite_enabled', v1=[]) +def is_mixed_precision_graph_rewrite_enabled(): + return _mixed_precision_graph_rewrite_is_enabled + + +def set_mixed_precision_graph_rewrite_enabled(enabled): + global _mixed_precision_graph_rewrite_is_enabled + _mixed_precision_graph_rewrite_is_enabled = enabled + + +def non_mixed_precision_session_created(): + return _non_mixed_precision_session_created + + +def set_non_mixed_precision_session_created(created): + global _non_mixed_precision_session_created + _non_mixed_precision_session_created = created + + +def is_using_mixed_precision_policy(): + return _using_mixed_precision_policy + + +@tf_export('__internal__.train.set_using_mixed_precision_policy', v1=[]) +def set_using_mixed_precision_policy(is_using): + global _using_mixed_precision_policy + _using_mixed_precision_policy = is_using diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/ftrl.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/ftrl.py new file mode 100644 index 0000000000000000000000000000000000000000..282ca74f1e01408939fe368a69a8634f0b1974c3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/ftrl.py @@ -0,0 +1,291 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Ftrl-proximal for TensorFlow.""" +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.training import optimizer +from tensorflow.python.training import training_ops +from tensorflow.python.util.tf_export import tf_export + + +@tf_export(v1=["train.FtrlOptimizer"]) +class FtrlOptimizer(optimizer.Optimizer): + """Optimizer that implements the FTRL algorithm. + + This version has support for both online L2 (McMahan et al., 2013) and + shrinkage-type L2, which is the addition of an L2 penalty + to the loss function. + + References: + Ad-click prediction: + [McMahan et al., 2013](https://dl.acm.org/citation.cfm?id=2488200) + ([pdf](https://dl.acm.org/ft_gateway.cfm?id=2488200&ftid=1388399&dwn=1&CFID=32233078&CFTOKEN=d60fe57a294c056a-CB75C374-F915-E7A6-1573FBBC7BF7D526)) + """ + + def __init__(self, + learning_rate, + learning_rate_power=-0.5, + initial_accumulator_value=0.1, + l1_regularization_strength=0.0, + l2_regularization_strength=0.0, + use_locking=False, + name="Ftrl", + accum_name=None, + linear_name=None, + l2_shrinkage_regularization_strength=0.0, + beta=None): + r"""Construct a new FTRL optimizer. + + Args: + learning_rate: A float value or a constant float `Tensor`. + learning_rate_power: A float value, must be less or equal to zero. + Controls how the learning rate decreases during training. Use zero for + a fixed learning rate. See section 3.1 in (McMahan et al., 2013). + initial_accumulator_value: The starting value for accumulators. + Only zero or positive values are allowed. + l1_regularization_strength: A float value, must be greater than or + equal to zero. + l2_regularization_strength: A float value, must be greater than or + equal to zero. + use_locking: If `True` use locks for update operations. + name: Optional name prefix for the operations created when applying + gradients. Defaults to "Ftrl". + accum_name: The suffix for the variable that keeps the gradient squared + accumulator. If not present, defaults to name. + linear_name: The suffix for the variable that keeps the linear gradient + accumulator. If not present, defaults to name + "_1". + l2_shrinkage_regularization_strength: A float value, must be greater than + or equal to zero. This differs from L2 above in that the L2 above is a + stabilization penalty, whereas this L2 shrinkage is a magnitude penalty. + The FTRL formulation can be written as: + w_{t+1} = argmin_w(\hat{g}_{1:t}w + L1*||w||_1 + L2*||w||_2^2), where + \hat{g} = g + (2*L2_shrinkage*w), and g is the gradient of the loss + function w.r.t. the weights w. + Specifically, in the absence of L1 regularization, it is equivalent to + the following update rule: + w_{t+1} = w_t - lr_t / (beta + 2*L2*lr_t) * g_t - + 2*L2_shrinkage*lr_t / (beta + 2*L2*lr_t) * w_t + where lr_t is the learning rate at t. + When input is sparse shrinkage will only happen on the active weights. + beta: A float value; corresponds to the beta parameter in the paper. + + Raises: + ValueError: If one of the arguments is invalid. + + References: + Ad-click prediction: + [McMahan et al., 2013](https://dl.acm.org/citation.cfm?id=2488200) + ([pdf](https://dl.acm.org/ft_gateway.cfm?id=2488200&ftid=1388399&dwn=1&CFID=32233078&CFTOKEN=d60fe57a294c056a-CB75C374-F915-E7A6-1573FBBC7BF7D526)) + """ + super(FtrlOptimizer, self).__init__(use_locking, name) + + if initial_accumulator_value < 0.0: + raise ValueError( + "initial_accumulator_value %f needs to be positive or zero" % + initial_accumulator_value) + if learning_rate_power > 0.0: + raise ValueError("learning_rate_power %f needs to be negative or zero" % + learning_rate_power) + if l1_regularization_strength < 0.0: + raise ValueError( + "l1_regularization_strength %f needs to be positive or zero" % + l1_regularization_strength) + if l2_regularization_strength < 0.0: + raise ValueError( + "l2_regularization_strength %f needs to be positive or zero" % + l2_regularization_strength) + if l2_shrinkage_regularization_strength < 0.0: + raise ValueError( + "l2_shrinkage_regularization_strength %f needs to be positive" + " or zero" % l2_shrinkage_regularization_strength) + + self._learning_rate = learning_rate + self._learning_rate_power = learning_rate_power + self._initial_accumulator_value = initial_accumulator_value + self._l1_regularization_strength = l1_regularization_strength + self._l2_regularization_strength = l2_regularization_strength + self._beta = (0.0 if beta is None else beta) + self._l2_shrinkage_regularization_strength = ( + l2_shrinkage_regularization_strength) + self._learning_rate_tensor = None + self._learning_rate_power_tensor = None + self._l1_regularization_strength_tensor = None + self._adjusted_l2_regularization_strength_tensor = None + self._l2_shrinkage_regularization_strength_tensor = None + self._accum_name = accum_name + self._linear_name = linear_name + + def _create_slots(self, var_list): + # Create the "accum" and "linear" slots. + def _accum_initializer(shape, dtype=dtypes.float32, partition_info=None): + del partition_info + return array_ops.ones( + shape=shape, dtype=dtype) * self._initial_accumulator_value + for v in var_list: + self._get_or_make_slot_with_initializer( + v, _accum_initializer, v.shape, v.dtype, "accum", + self._accum_name or self._name) + self._zeros_slot(v, "linear", self._linear_name or self._name) + + def _prepare(self): + self._learning_rate_tensor = ops.convert_to_tensor( + self._learning_rate, name="learning_rate") + self._l1_regularization_strength_tensor = ops.convert_to_tensor( + self._l1_regularization_strength, name="l1_regularization_strength") + # L2 regularization strength with beta added in so that the underlying + # TensorFlow ops do not need to include that parameter. + self._adjusted_l2_regularization_strength_tensor = ops.convert_to_tensor( + self._l2_regularization_strength + self._beta / + (2. * math_ops.maximum(self._learning_rate, 1e-36)), + name="adjusted_l2_regularization_strength") + assert self._adjusted_l2_regularization_strength_tensor is not None + self._beta_tensor = ops.convert_to_tensor(self._beta, name="beta") + self._l2_shrinkage_regularization_strength_tensor = ops.convert_to_tensor( + self._l2_shrinkage_regularization_strength, + name="l2_shrinkage_regularization_strength") + self._learning_rate_power_tensor = ops.convert_to_tensor( + self._learning_rate_power, name="learning_rate_power") + + def _apply_dense(self, grad, var): + accum = self.get_slot(var, "accum") + linear = self.get_slot(var, "linear") + if self._l2_shrinkage_regularization_strength <= 0.0: + return training_ops.apply_ftrl( + var, + accum, + linear, + grad, + math_ops.cast(self._learning_rate_tensor, var.dtype.base_dtype), + math_ops.cast(self._l1_regularization_strength_tensor, + var.dtype.base_dtype), + math_ops.cast(self._adjusted_l2_regularization_strength_tensor, + var.dtype.base_dtype), + math_ops.cast(self._learning_rate_power_tensor, var.dtype.base_dtype), + use_locking=self._use_locking) + else: + return training_ops.apply_ftrl_v2( + var, + accum, + linear, + grad, + math_ops.cast(self._learning_rate_tensor, var.dtype.base_dtype), + math_ops.cast(self._l1_regularization_strength_tensor, + var.dtype.base_dtype), + math_ops.cast(self._adjusted_l2_regularization_strength_tensor, + var.dtype.base_dtype), + math_ops.cast(self._l2_shrinkage_regularization_strength_tensor, + var.dtype.base_dtype), + math_ops.cast(self._learning_rate_power_tensor, var.dtype.base_dtype), + use_locking=self._use_locking) + + def _resource_apply_dense(self, grad, var): + accum = self.get_slot(var, "accum") + linear = self.get_slot(var, "linear") + if self._l2_shrinkage_regularization_strength <= 0.0: + return training_ops.resource_apply_ftrl( + var.handle, + accum.handle, + linear.handle, + grad, + math_ops.cast(self._learning_rate_tensor, var.dtype.base_dtype), + math_ops.cast(self._l1_regularization_strength_tensor, + var.dtype.base_dtype), + math_ops.cast(self._adjusted_l2_regularization_strength_tensor, + var.dtype.base_dtype), + math_ops.cast(self._learning_rate_power_tensor, var.dtype.base_dtype), + use_locking=self._use_locking) + else: + return training_ops.resource_apply_ftrl_v2( + var.handle, + accum.handle, + linear.handle, + grad, + math_ops.cast(self._learning_rate_tensor, var.dtype.base_dtype), + math_ops.cast(self._l1_regularization_strength_tensor, + var.dtype.base_dtype), + math_ops.cast(self._adjusted_l2_regularization_strength_tensor, + var.dtype.base_dtype), + math_ops.cast(self._l2_shrinkage_regularization_strength_tensor, + var.dtype.base_dtype), + math_ops.cast(self._learning_rate_power_tensor, var.dtype.base_dtype), + use_locking=self._use_locking) + + def _apply_sparse(self, grad, var): + accum = self.get_slot(var, "accum") + linear = self.get_slot(var, "linear") + if self._l2_shrinkage_regularization_strength <= 0.0: + return training_ops.sparse_apply_ftrl( + var, + accum, + linear, + grad.values, + grad.indices, + math_ops.cast(self._learning_rate_tensor, var.dtype.base_dtype), + math_ops.cast(self._l1_regularization_strength_tensor, + var.dtype.base_dtype), + math_ops.cast(self._adjusted_l2_regularization_strength_tensor, + var.dtype.base_dtype), + math_ops.cast(self._learning_rate_power_tensor, var.dtype.base_dtype), + use_locking=self._use_locking) + else: + return training_ops.sparse_apply_ftrl_v2( + var, + accum, + linear, + grad.values, + grad.indices, + math_ops.cast(self._learning_rate_tensor, var.dtype.base_dtype), + math_ops.cast(self._l1_regularization_strength_tensor, + var.dtype.base_dtype), + math_ops.cast(self._adjusted_l2_regularization_strength_tensor, + var.dtype.base_dtype), + math_ops.cast(self._l2_shrinkage_regularization_strength_tensor, + grad.dtype.base_dtype), + math_ops.cast(self._learning_rate_power_tensor, var.dtype.base_dtype), + use_locking=self._use_locking) + + def _resource_apply_sparse(self, grad, var, indices): + accum = self.get_slot(var, "accum") + linear = self.get_slot(var, "linear") + if self._l2_shrinkage_regularization_strength <= 0.0: + return training_ops.resource_sparse_apply_ftrl( + var.handle, + accum.handle, + linear.handle, + grad, + indices, + math_ops.cast(self._learning_rate_tensor, grad.dtype), + math_ops.cast(self._l1_regularization_strength_tensor, grad.dtype), + math_ops.cast(self._adjusted_l2_regularization_strength_tensor, + grad.dtype), + math_ops.cast(self._learning_rate_power_tensor, grad.dtype), + use_locking=self._use_locking) + else: + return training_ops.resource_sparse_apply_ftrl_v2( + var.handle, + accum.handle, + linear.handle, + grad, + indices, + math_ops.cast(self._learning_rate_tensor, grad.dtype), + math_ops.cast(self._l1_regularization_strength_tensor, grad.dtype), + math_ops.cast(self._adjusted_l2_regularization_strength_tensor, + grad.dtype), + math_ops.cast(self._l2_shrinkage_regularization_strength_tensor, + grad.dtype), + math_ops.cast(self._learning_rate_power_tensor, grad.dtype), + use_locking=self._use_locking) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/gen_training_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/gen_training_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..a569a589b15117f0d756ad0f660bc2f7bd873f07 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/gen_training_ops.py @@ -0,0 +1,25 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""Python wrappers for training ops.""" +# NOTE(allenl): The generated op wrappers for training ops were originally in +# training/gen_training_ops.py. They moved to ops/gen_training_ops.py when +# training/ became a module, and this is an alias to avoid breaking existing +# imports. + +# go/tf-wildcard-import +# pylint: disable=wildcard-import +from tensorflow.python.ops.gen_training_ops import * +# pylint: enable=wildcard-import diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/gradient_descent.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/gradient_descent.py new file mode 100644 index 0000000000000000000000000000000000000000..007efcea58e6fa3c8f9cec6e7e31341aaff2bd14 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/gradient_descent.py @@ -0,0 +1,82 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""GradientDescent for TensorFlow.""" +from tensorflow.python.framework import indexed_slices +from tensorflow.python.framework import ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.training import optimizer +from tensorflow.python.training import training_ops +from tensorflow.python.util.tf_export import tf_export + + +@tf_export(v1=["train.GradientDescentOptimizer"]) +class GradientDescentOptimizer(optimizer.Optimizer): + """Optimizer that implements the gradient descent algorithm. + """ + + def __init__(self, learning_rate, use_locking=False, name="GradientDescent"): + """Construct a new gradient descent optimizer. + + Args: + learning_rate: A Tensor or a floating point value. The learning + rate to use. + use_locking: If True use locks for update operations. + name: Optional name prefix for the operations created when applying + gradients. Defaults to "GradientDescent". + + @compatibility(eager) + When eager execution is enabled, `learning_rate` can be a callable that + takes no arguments and returns the actual value to use. This can be useful + for changing these values across different invocations of optimizer + functions. + @end_compatibility + """ + super(GradientDescentOptimizer, self).__init__(use_locking, name) + self._learning_rate = learning_rate + self._learning_rate_tensor = None + + def _apply_dense(self, grad, var): + return training_ops.apply_gradient_descent( + var, + math_ops.cast(self._learning_rate_tensor, var.dtype.base_dtype), + grad, + use_locking=self._use_locking).op + + def _resource_apply_dense(self, grad, handle): + return training_ops.resource_apply_gradient_descent( + handle.handle, math_ops.cast(self._learning_rate_tensor, + grad.dtype.base_dtype), + grad, use_locking=self._use_locking) + + def _resource_apply_sparse_duplicate_indices(self, grad, handle, indices): + return resource_variable_ops.resource_scatter_add( + handle.handle, + indices, + -grad * math_ops.cast(self._learning_rate_tensor, + grad.dtype.base_dtype)) + + def _apply_sparse_duplicate_indices(self, grad, var): + delta = indexed_slices.IndexedSlices( + grad.values * + math_ops.cast(self._learning_rate_tensor, var.dtype.base_dtype), + grad.indices, grad.dense_shape) + return var.scatter_sub(delta, use_locking=self._use_locking) + + def _prepare(self): + learning_rate = self._call_if_callable(self._learning_rate) + self._learning_rate_tensor = ops.convert_to_tensor( + learning_rate, name="learning_rate") diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/input.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/input.py new file mode 100644 index 0000000000000000000000000000000000000000..23bd73220042c1f1ca9eb9e13512da4551ec3d76 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/input.py @@ -0,0 +1,1577 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""Input pipeline. + +Please see the [reading data +how-to](https://tensorflow.org/api_guides/python/reading_data) +for context. +""" + + +from tensorflow.python.eager import context +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import indexed_slices +from tensorflow.python.framework import ops +from tensorflow.python.framework import sparse_tensor +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.framework import tensor_shape +from tensorflow.python.layers import utils +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import control_flow_assert +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import data_flow_ops +from tensorflow.python.ops import io_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import random_ops +from tensorflow.python.ops import sparse_ops +from tensorflow.python.ops import variable_v1 +from tensorflow.python.summary import summary +from tensorflow.python.training import queue_runner +from tensorflow.python.util import deprecation +from tensorflow.python.util.compat import collections_abc +from tensorflow.python.util.tf_export import tf_export + + +# pylint: disable=protected-access +_store_sparse = sparse_ops._add_sparse_to_tensors_map +_store_many_sparse = sparse_ops._add_many_sparse_to_tensors_map +_restore_sparse = sparse_ops._take_many_sparse_from_tensors_map +# pylint: enable=protected-access + + +@tf_export( + "io.match_filenames_once", + v1=["io.match_filenames_once", "train.match_filenames_once"]) +@deprecation.deprecated_endpoints("train.match_filenames_once") +def match_filenames_once(pattern, name=None): + """Save the list of files matching pattern, so it is only computed once. + + NOTE: The order of the files returned is deterministic. + + Args: + pattern: A file pattern (glob), or 1D tensor of file patterns. + name: A name for the operations (optional). + + Returns: + A variable that is initialized to the list of files matching the pattern(s). + """ + with ops.name_scope(name, "matching_filenames", [pattern]) as name: + return variable_v1.VariableV1( + name=name, initial_value=io_ops.matching_files(pattern), + trainable=False, validate_shape=False, + collections=[ops.GraphKeys.LOCAL_VARIABLES]) + + +@tf_export(v1=["train.limit_epochs"]) +@deprecation.deprecated( + None, "Queue-based input pipelines have been replaced by `tf.data`. Use " + "`tf.data.Dataset.from_tensors(tensor).repeat(num_epochs)`.") +def limit_epochs(tensor, num_epochs=None, name=None): + """Returns tensor `num_epochs` times and then raises an `OutOfRange` error. + + Note: creates local counter `epochs`. Use `local_variables_initializer()` to + initialize local variables. + + Args: + tensor: Any `Tensor`. + num_epochs: A positive integer (optional). If specified, limits the number + of steps the output tensor may be evaluated. + name: A name for the operations (optional). + + Returns: + tensor or `OutOfRange`. + + Raises: + ValueError: if `num_epochs` is invalid. + """ + if num_epochs is None: + return tensor + if num_epochs <= 0: + raise ValueError("num_epochs must be > 0 not %d." % num_epochs) + with ops.name_scope(name, "limit_epochs", [tensor]) as name: + zero64 = constant_op.constant(0, dtype=dtypes.int64) + epochs = variable_v1.VariableV1( + zero64, name="epochs", trainable=False, + collections=[ops.GraphKeys.LOCAL_VARIABLES]) + counter = epochs.count_up_to(num_epochs) + with ops.control_dependencies([counter]): + return array_ops.identity(tensor, name=name) + + +@tf_export(v1=["train.input_producer"]) +@deprecation.deprecated( + None, "Queue-based input pipelines have been replaced by `tf.data`. Use " + "`tf.data.Dataset.from_tensor_slices(input_tensor).shuffle" + "(tf.shape(input_tensor, out_type=tf.int64)[0]).repeat(num_epochs)`. If " + "`shuffle=False`, omit the `.shuffle(...)`.") +def input_producer(input_tensor, + element_shape=None, + num_epochs=None, + shuffle=True, + seed=None, + capacity=32, + shared_name=None, + summary_name=None, + name=None, + cancel_op=None): + """Output the rows of `input_tensor` to a queue for an input pipeline. + + Note: if `num_epochs` is not `None`, this function creates local counter + `epochs`. Use `local_variables_initializer()` to initialize local variables. + + Args: + input_tensor: A tensor with the rows to produce. Must be at least + one-dimensional. Must either have a fully-defined shape, or + `element_shape` must be defined. + element_shape: (Optional.) A `TensorShape` representing the shape of a + row of `input_tensor`, if it cannot be inferred. + num_epochs: (Optional.) An integer. If specified `input_producer` produces + each row of `input_tensor` `num_epochs` times before generating an + `OutOfRange` error. If not specified, `input_producer` can cycle through + the rows of `input_tensor` an unlimited number of times. + shuffle: (Optional.) A boolean. If true, the rows are randomly shuffled + within each epoch. + seed: (Optional.) An integer. The seed to use if `shuffle` is true. + capacity: (Optional.) The capacity of the queue to be used for buffering + the input. + shared_name: (Optional.) If set, this queue will be shared under the given + name across multiple sessions. + summary_name: (Optional.) If set, a scalar summary for the current queue + size will be generated, using this name as part of the tag. + name: (Optional.) A name for queue. + cancel_op: (Optional.) Cancel op for the queue + + Returns: + A queue with the output rows. A `QueueRunner` for the queue is + added to the current `QUEUE_RUNNER` collection of the current + graph. + + Raises: + ValueError: If the shape of the input cannot be inferred from the arguments. + RuntimeError: If called with eager execution enabled. + + @compatibility(eager) + Input pipelines based on Queues are not supported when eager execution is + enabled. Please use the `tf.data` API to ingest data under eager execution. + @end_compatibility + """ + if context.executing_eagerly(): + raise RuntimeError( + "Input pipelines based on Queues are not supported when eager execution" + " is enabled. Please use tf.data to ingest data into your model" + " instead.") + with ops.name_scope(name, "input_producer", [input_tensor]): + input_tensor = ops.convert_to_tensor(input_tensor, name="input_tensor") + element_shape = input_tensor.shape[1:].merge_with(element_shape) + if not element_shape.is_fully_defined(): + raise ValueError("Either `input_tensor` must have a fully defined shape " + "or `element_shape` must be specified") + + if shuffle: + input_tensor = random_ops.random_shuffle(input_tensor, seed=seed) + + input_tensor = limit_epochs(input_tensor, num_epochs) + + q = data_flow_ops.FIFOQueue(capacity=capacity, + dtypes=[input_tensor.dtype.base_dtype], + shapes=[element_shape], + shared_name=shared_name, name=name) + enq = q.enqueue_many([input_tensor]) + queue_runner.add_queue_runner( + queue_runner.QueueRunner( + q, [enq], cancel_op=cancel_op)) + if summary_name is not None: + summary.scalar(summary_name, + math_ops.cast(q.size(), dtypes.float32) * (1. / capacity)) + return q + + +@tf_export(v1=["train.string_input_producer"]) +@deprecation.deprecated( + None, "Queue-based input pipelines have been replaced by `tf.data`. Use " + "`tf.data.Dataset.from_tensor_slices(string_tensor).shuffle" + "(tf.shape(input_tensor, out_type=tf.int64)[0]).repeat(num_epochs)`. If " + "`shuffle=False`, omit the `.shuffle(...)`.") +def string_input_producer(string_tensor, + num_epochs=None, + shuffle=True, + seed=None, + capacity=32, + shared_name=None, + name=None, + cancel_op=None): + """Output strings (e.g. filenames) to a queue for an input pipeline. + + Note: if `num_epochs` is not `None`, this function creates local counter + `epochs`. Use `local_variables_initializer()` to initialize local variables. + + Args: + string_tensor: A 1-D string tensor with the strings to produce. + num_epochs: An integer (optional). If specified, `string_input_producer` + produces each string from `string_tensor` `num_epochs` times before + generating an `OutOfRange` error. If not specified, + `string_input_producer` can cycle through the strings in `string_tensor` + an unlimited number of times. + shuffle: Boolean. If true, the strings are randomly shuffled within each + epoch. + seed: An integer (optional). Seed used if shuffle == True. + capacity: An integer. Sets the queue capacity. + shared_name: (optional). If set, this queue will be shared under the given + name across multiple sessions. All sessions open to the device which has + this queue will be able to access it via the shared_name. Using this in + a distributed setting means each name will only be seen by one of the + sessions which has access to this operation. + name: A name for the operations (optional). + cancel_op: Cancel op for the queue (optional). + + Returns: + A queue with the output strings. A `QueueRunner` for the Queue + is added to the current `Graph`'s `QUEUE_RUNNER` collection. + + Raises: + ValueError: If the string_tensor is a null Python list. At runtime, + will fail with an assertion if string_tensor becomes a null tensor. + + @compatibility(eager) + Input pipelines based on Queues are not supported when eager execution is + enabled. Please use the `tf.data` API to ingest data under eager execution. + @end_compatibility + """ + not_null_err = "string_input_producer requires a non-null input tensor" + if not isinstance(string_tensor, tensor_lib.Tensor) and not string_tensor: + raise ValueError(not_null_err) + + with ops.name_scope(name, "input_producer", [string_tensor]) as name: + string_tensor = ops.convert_to_tensor(string_tensor, dtype=dtypes.string) + with ops.control_dependencies([ + control_flow_assert.Assert( + math_ops.greater(array_ops.size(string_tensor), 0), [not_null_err]) + ]): + string_tensor = array_ops.identity(string_tensor) + return input_producer( + input_tensor=string_tensor, + element_shape=[], + num_epochs=num_epochs, + shuffle=shuffle, + seed=seed, + capacity=capacity, + shared_name=shared_name, + name=name, + summary_name="fraction_of_%d_full" % capacity, + cancel_op=cancel_op) + + +@tf_export(v1=["train.range_input_producer"]) +@deprecation.deprecated( + None, "Queue-based input pipelines have been replaced by `tf.data`. Use " + "`tf.data.Dataset.range(limit).shuffle(limit).repeat(num_epochs)`. If " + "`shuffle=False`, omit the `.shuffle(...)`.") +def range_input_producer(limit, num_epochs=None, shuffle=True, seed=None, + capacity=32, shared_name=None, name=None): + """Produces the integers from 0 to limit-1 in a queue. + + Note: if `num_epochs` is not `None`, this function creates local counter + `epochs`. Use `local_variables_initializer()` to initialize local variables. + + Args: + limit: An int32 scalar tensor. + num_epochs: An integer (optional). If specified, `range_input_producer` + produces each integer `num_epochs` times before generating an + OutOfRange error. If not specified, `range_input_producer` can cycle + through the integers an unlimited number of times. + shuffle: Boolean. If true, the integers are randomly shuffled within each + epoch. + seed: An integer (optional). Seed used if shuffle == True. + capacity: An integer. Sets the queue capacity. + shared_name: (optional). If set, this queue will be shared under the given + name across multiple sessions. + name: A name for the operations (optional). + + Returns: + A Queue with the output integers. A `QueueRunner` for the Queue + is added to the current `Graph`'s `QUEUE_RUNNER` collection. + + @compatibility(eager) + Input pipelines based on Queues are not supported when eager execution is + enabled. Please use the `tf.data` API to ingest data under eager execution. + @end_compatibility + """ + with ops.name_scope(name, "input_producer", [limit]) as name: + range_tensor = math_ops.range(limit) + return input_producer( + range_tensor, [], num_epochs, shuffle, seed, capacity, + shared_name, "fraction_of_%d_full" % capacity, name) + + +@tf_export(v1=["train.slice_input_producer"]) +@deprecation.deprecated( + None, "Queue-based input pipelines have been replaced by `tf.data`. Use " + "`tf.data.Dataset.from_tensor_slices(tuple(tensor_list)).shuffle" + "(tf.shape(input_tensor, out_type=tf.int64)[0]).repeat(num_epochs)`. If " + "`shuffle=False`, omit the `.shuffle(...)`.") +def slice_input_producer(tensor_list, num_epochs=None, shuffle=True, seed=None, + capacity=32, shared_name=None, name=None): + """Produces a slice of each `Tensor` in `tensor_list`. + + Implemented using a Queue -- a `QueueRunner` for the Queue + is added to the current `Graph`'s `QUEUE_RUNNER` collection. + + Args: + tensor_list: A list of `Tensor` objects. Every `Tensor` in + `tensor_list` must have the same size in the first dimension. + num_epochs: An integer (optional). If specified, `slice_input_producer` + produces each slice `num_epochs` times before generating + an `OutOfRange` error. If not specified, `slice_input_producer` can cycle + through the slices an unlimited number of times. + shuffle: Boolean. If true, the integers are randomly shuffled within each + epoch. + seed: An integer (optional). Seed used if shuffle == True. + capacity: An integer. Sets the queue capacity. + shared_name: (optional). If set, this queue will be shared under the given + name across multiple sessions. + name: A name for the operations (optional). + + Returns: + A list of tensors, one for each element of `tensor_list`. If the tensor + in `tensor_list` has shape `[N, a, b, .., z]`, then the corresponding output + tensor will have shape `[a, b, ..., z]`. + + Raises: + ValueError: if `slice_input_producer` produces nothing from `tensor_list`. + + @compatibility(eager) + Input pipelines based on Queues are not supported when eager execution is + enabled. Please use the `tf.data` API to ingest data under eager execution. + @end_compatibility + """ + with ops.name_scope(name, "input_producer", tensor_list): + tensor_list = indexed_slices.convert_n_to_tensor_or_indexed_slices( + tensor_list) + if not tensor_list: + raise ValueError( + "Expected at least one tensor in slice_input_producer().") + range_size = array_ops.shape(tensor_list[0])[0] + # TODO(josh11b): Add an assertion that the first dimension of + # everything in TensorList matches. Maybe just check the inferred shapes? + queue = range_input_producer(range_size, num_epochs=num_epochs, + shuffle=shuffle, seed=seed, capacity=capacity, + shared_name=shared_name) + index = queue.dequeue() + output = [array_ops.gather(t, index) for t in tensor_list] + return output + + +# Helpers for the batching functions ------------------------------------------ + + +def _flatten(tensor_list_list): + return [tensor for tensor_list in tensor_list_list for tensor in tensor_list] + + +class _SparseMetaData: + """Store information about the Tensor: Is it sparse?, map_op, and rank.""" + + def __init__(self, sparse, map_op, rank): + """Create the metadata. + + Args: + sparse: Python boolean. + map_op: The `Operation` that created the `SparseTensorsMap` in question. + This Op contains information about the underlying Map object and the + dtype of the original data. + rank: The statically known rank of the `SparseTensor`. + """ + self._sparse = sparse + self._map_op = map_op + self._rank = tensor_shape.as_dimension(rank) + + def __eq__(self, other): + if self.sparse != other.sparse: + return False + if not self.sparse: + return True + # If map_ops are not the same, the data source is not the same. + if (self.map_op is not None) != (other.map_op is not None): + return False + if self.map_op != other.map_op: + return False + if not self.rank.is_compatible_with(other.rank): + return False + return True + + def __ne__(self, other): + return not self.__eq__(other) + + def __str__(self): + return "[SparseMetaData(%s, %s, %s)]" % (self.sparse, self.map_op.name, + self.rank) + + def merge_with(self, other): + if self != other: + raise ValueError("SparseMetaData objects are incompatible: %s vs. %s" + % (self, other)) + if self.sparse: + self.rank.merge_with(other.rank) + return self + + @property + def map_op(self): + return self._map_op + + @property + def sparse(self): + return self._sparse + + @property + def rank(self): + return self._rank + + +def _as_tensor_list(tensors): + if isinstance(tensors, dict): + return [tensors[k] for k in sorted(tensors, key=str)] + else: + return tensors + + +def _as_tensor_list_list(tensors_list): + if not tensors_list: + raise ValueError("Expected at least one set of tensors") + if isinstance(tensors_list[0], dict): + expected_keys = set(tensors_list[0].keys()) + for tensors in tensors_list[1:]: + if set(tensors.keys()) != expected_keys: + raise ValueError("All dictionaries in tensors_list must have " + "the same keys") + return [_as_tensor_list(tensors) for tensors in tensors_list] + else: + return tensors_list + + +def _as_original_type(original_tensors, tensor_list): + if isinstance(original_tensors, dict): + if len(original_tensors) == 1: + # tensor_list is bogusly returned as a single tensor if only one tensor + # was enqueued. Make it a list again. See b/28117485. + tensor_list = [tensor_list] + return {k: tensor_list[i] + for i, k in enumerate(sorted(original_tensors, key=str))} + else: + return tensor_list + + +def _store_sparse_tensors(tensor_list, enqueue_many, keep_input, + shared_map_ops=None): + """Store SparseTensors for feeding into batch, etc. + + If `shared_map_ops` is provided, the underlying `SparseTensorsMap` objects + are reused (shared). This argument is useful for, e.g., `batch_join` + where multiple enqueue operations write to the same Queue component, + and another (dequeue) thread reads from that same location and must then + restore the associated `SparseTensor` objects. In this case, the sparse + restore must have a single `SparseTensorMap` from which to read out the + handles; so a single `SparseTensorMap` must be shared for storing + across the multiple enqueue operations. This sharing is performed by + calling `_store_sparse_tensors` the first time with `shared_map_ops=None`, + and then in subsequent times with this value set to the list of `Operation` + objects created in the first call. + + Args: + tensor_list: List of `Tensor` and `SparseTensor` objects. + enqueue_many: Python `Boolean`. + keep_input: Must be a scalar bool Tensor (not a Python bool). If False, + don't store. + shared_map_ops: (optional) List of `Operation` objects from a previous + call to `_store_sparse_tensors`. If not `None`, the op types should be + one of `AddSparseToTensorsMap` or `AddManySparseToTensorsMap` in the + locations corresponding to `SparseTensors` in `tensor_list`. + + Returns: + A tuple `(stored_list, sparse_info_list)` where `stored_list` is a list + of `Tensor` objects (same length as `tensor_list`) and `sparse_info_list` + is a list of the same length of `_SparseMetaData` objects. + """ + maybe_shared_map_ops = shared_map_ops or [None] * len(tensor_list) + + def _sparse_meta_data(t, storing_op, map_op): + if not isinstance(t, sparse_tensor.SparseTensor): + return _SparseMetaData(False, None, None) + rank = t.dense_shape.shape.with_rank(1).dims[0] + if enqueue_many: + rank -= 1 + # If a shared map_op was provided, use that. Otherwise use the name of + # the operation used to store the SparseTensor. + return _SparseMetaData( + sparse=True, map_op=map_op or storing_op, rank=rank) + + def _maybe_store(t, shared_map_op): + """Store Sparse tensor, if necessary.""" + if not isinstance(t, sparse_tensor.SparseTensor): + return t + map_op_name = shared_map_op.name if shared_map_op else None + def _maybe_store_sparse(t, map_op_name, keep_input): + """Conditionally store a single sparse Tensor.""" + return utils.smart_cond( + keep_input, + lambda: _store_sparse(t, shared_name=map_op_name), + lambda: constant_op.constant(-1, dtypes.int64)) + def _maybe_store_many_sparse(t, map_op_name, keep_input): + """Conditionally store multiple sparse Tensors.""" + out_tensor = utils.smart_cond( + keep_input, + lambda: _store_many_sparse(t, shared_name=map_op_name), + lambda: -1 * array_ops.ones(array_ops.shape(t)[0:1], dtypes.int64)) + out_tensor.set_shape([None]) # necessary when t.ndims is unknown + return out_tensor + def _sparse_values_to_keep(t, keep_input): + """Convert a per-row `keep_input` vector to a per-value one.""" + # Get the rows of every value in the sparse Tensor. + row_values = t.indices[:, 0] + # The value should be kept iff the row should be kept. + return array_ops.gather(keep_input, row_values) + if keep_input.shape.ndims == 1: + t = sparse_ops.sparse_retain(t, _sparse_values_to_keep(t, keep_input)) + store_f = lambda t, name, _: _store_many_sparse(t, shared_name=name) + elif enqueue_many: + store_f = _maybe_store_many_sparse + else: + store_f = _maybe_store_sparse + return store_f(t, map_op_name, keep_input) + + stored_list = [ + _maybe_store(t, shared_map_op) for t, shared_map_op + in zip(tensor_list, maybe_shared_map_ops)] + # Since the output of `_store{_many}_sparse is wrapped in a tf.cond `Merge`, + # we can't just get the Op of the resulting tensor. + def _sparse_op(stored): + for input_tensor in stored.op.inputs: + if input_tensor.op.type in ("AddSparseToTensorsMap", + "AddManySparseToTensorsMap"): + return input_tensor.op + # If there was no sparse input, then the original stored Tensor wasn't + # sparse and we can just return the original Tensor's Op. + return stored.op + sparse_info_list = [ + _sparse_meta_data(t, _sparse_op(stored), shared_map_op) + for t, stored, shared_map_op + in zip(tensor_list, stored_list, maybe_shared_map_ops)] + # Expand dims of stored tensors by 1 for proper enqueue shape + stored_list = [ + array_ops.expand_dims(s, [-1]) if s_info.sparse else s + for s, s_info in zip(stored_list, sparse_info_list)] + return stored_list, sparse_info_list + + +def _store_sparse_tensors_join(tensor_list_list, enqueue_many, keep_input): + """Store SparseTensors for feeding into batch_join, etc.""" + (s0, sparse_info_list) = _store_sparse_tensors( + tensor_list_list[0], enqueue_many, keep_input) + stored_list_list = [s0] + for tensor_list in tensor_list_list[1:]: + s, sparse_info_candidate = _store_sparse_tensors( + tensor_list, enqueue_many, keep_input, + [st.map_op for st in sparse_info_list]) + if sparse_info_list != sparse_info_candidate: + raise ValueError("Inconsistent SparseTensors list: %s vs. %s" + % (tensor_list_list[0], tensor_list)) + sparse_info_list = [ + info.merge_with(candidate) + for (info, candidate) in zip(sparse_info_list, sparse_info_candidate)] + stored_list_list.append(s) + + return (stored_list_list, sparse_info_list) + + +def _restore_sparse_tensors(stored_list, sparse_info_list): + """Restore SparseTensors after dequeue in batch, batch_join, etc.""" + received_sequence = isinstance(stored_list, collections_abc.Sequence) + if not received_sequence: + stored_list = (stored_list,) + tensors = [ + _restore_sparse(sparse_map_op=info.map_op, + sparse_handles=array_ops.squeeze(s, [1]), + rank=tensor_shape.dimension_value(info.rank + 1)) + if info.sparse else s + for (s, info) in zip(stored_list, sparse_info_list)] + has_st = any(isinstance(x, sparse_tensor.SparseTensor) for x in tensors) + if has_st: + t_values = [ + x.values if isinstance(x, sparse_tensor.SparseTensor) + else x + for x in tensors] + with_deps = lambda x: control_flow_ops.with_dependencies(t_values, x) + ensure_restore_tensors = [ + sparse_tensor.SparseTensor(indices=with_deps(x.indices), + values=with_deps(x.values), + dense_shape=with_deps(x.dense_shape)) + if isinstance(x, sparse_tensor.SparseTensor) + else with_deps(x) + for x in tensors] + else: + ensure_restore_tensors = tensors + return ensure_restore_tensors if received_sequence else tensors[0] + + +def _validate(tensor_list): + tensor_list = indexed_slices.convert_n_to_tensor_or_indexed_slices( + tensor_list) + if not tensor_list: + raise ValueError("Expected at least one tensor in batch().") + return tensor_list + + +def _validate_join(tensor_list_list): + tensor_list_list = [ + indexed_slices.convert_n_to_tensor_or_indexed_slices(tl) + for tl in tensor_list_list + ] + if not tensor_list_list: + raise ValueError("Expected at least one input in batch_join().") + return tensor_list_list + + +def _validate_keep_input(keep_input, enqueue_many): + """Validate `keep_input` argument to conditional batching functions.""" + keep_input = ops.convert_to_tensor(keep_input) + if keep_input.shape.ndims is None: + raise ValueError( + "`keep_input` dimensions must be known at graph construction.") + if not enqueue_many and keep_input.shape.ndims == 1: + raise ValueError( + "`keep_input` cannot be a vector when `enqueue_many=False`.") + if keep_input.shape.ndims > 1: + raise ValueError("`keep_input` must be 0 or 1 dimensions.") + return keep_input + + +def _dtypes(tensor_list_list): + all_types = [[t.dtype for t in tl] for tl in tensor_list_list] + types = all_types[0] + for other_types in all_types[1:]: + if other_types != types: + raise TypeError("Expected types to be consistent: %s vs. %s." % + (", ".join(x.name for x in types), + ", ".join(x.name for x in other_types))) + return types + + +def _merge_shapes(shape_list, enqueue_many): + shape_list = [tensor_shape.as_shape(s) for s in shape_list] + if enqueue_many: + # We want the shapes without the leading batch dimension. + shape_list = [s.with_rank_at_least(1)[1:] for s in shape_list] + merged_shape = shape_list[0] + for s in shape_list[1:]: + merged_shape.merge_with(s) + return merged_shape.as_list() + + +def _shapes(tensor_list_list, shapes, enqueue_many): + """Calculate and merge the shapes of incoming tensors. + + Args: + tensor_list_list: List of tensor lists. + shapes: List of shape tuples corresponding to tensors within the lists. + enqueue_many: Boolean describing whether shapes will be enqueued as + batches or individual entries. + + Returns: + A list of shapes aggregating shape inference info from `tensor_list_list`, + or returning `shapes` if it is not `None`. + + Raises: + ValueError: If any of the inferred shapes in `tensor_list_list` lack a + well defined rank. + """ + if shapes is None: + len0 = len(tensor_list_list[0]) + + for tl in tensor_list_list: + for i in range(len0): + if tl[i].shape.ndims is None: + raise ValueError("Cannot infer Tensor's rank: %s" % tl[i]) + + shapes = [ + _merge_shapes([tl[i].shape.as_list() + for tl in tensor_list_list], enqueue_many) + for i in range(len0) + ] + return shapes + + +def _select_which_to_enqueue(tensor_list, keep_input): + """Select which examples to enqueue based on vector `keep_input`.""" + select_i = math_ops.cast(keep_input, dtypes.int32) + tensor_list = [ + data_flow_ops.dynamic_partition(x, select_i, num_partitions=2)[1] + for x in tensor_list] + return tensor_list + + +def _enqueue_join(queue, tensor_list_list, enqueue_many, keep_input): + """Enqueue `tensor_list_list` in `queue`.""" + if enqueue_many: + enqueue_fn = queue.enqueue_many + else: + enqueue_fn = queue.enqueue + if keep_input.shape.ndims == 1: + enqueue_ops = [enqueue_fn(_select_which_to_enqueue(x, keep_input)) + for x in tensor_list_list] + else: + enqueue_ops = [utils.smart_cond( + keep_input, + lambda: enqueue_fn(tl), # pylint:disable=cell-var-from-loop + control_flow_ops.no_op) for tl in tensor_list_list] + queue_runner.add_queue_runner(queue_runner.QueueRunner(queue, enqueue_ops)) + + +def _enqueue(queue, tensor_list, threads, enqueue_many, keep_input): + """Enqueue `tensor_list` in `queue`.""" + if enqueue_many: + enqueue_fn = queue.enqueue_many + else: + enqueue_fn = queue.enqueue + if keep_input.shape.ndims == 1: + enqueue_ops = [ + enqueue_fn(_select_which_to_enqueue(tensor_list, keep_input))] * threads + else: + enqueue_ops = [utils.smart_cond( + keep_input, + lambda: enqueue_fn(tensor_list), + control_flow_ops.no_op)] * threads + queue_runner.add_queue_runner(queue_runner.QueueRunner(queue, enqueue_ops)) + + +def _which_queue(dynamic_pad): + return (data_flow_ops.PaddingFIFOQueue if dynamic_pad + else data_flow_ops.FIFOQueue) + + +def _batch(tensors, batch_size, keep_input, num_threads=1, capacity=32, + enqueue_many=False, shapes=None, dynamic_pad=False, + allow_smaller_final_batch=False, shared_name=None, + name=None): + """Helper function for `batch` and `maybe_batch`.""" + if context.executing_eagerly(): + raise ValueError( + "Input pipelines based on Queues are not supported when eager execution" + " is enabled. Please use tf.data to ingest data into your model" + " instead.") + tensor_list = _as_tensor_list(tensors) + with ops.name_scope(name, "batch", list(tensor_list) + [keep_input]) as name: + tensor_list = _validate(tensor_list) + keep_input = _validate_keep_input(keep_input, enqueue_many) + (tensor_list, sparse_info) = _store_sparse_tensors( + tensor_list, enqueue_many, keep_input) + types = _dtypes([tensor_list]) + shapes = _shapes([tensor_list], shapes, enqueue_many) + # TODO(josh11b,mrry): Switch to BatchQueue once it is written. + queue = _which_queue(dynamic_pad)( + capacity=capacity, dtypes=types, shapes=shapes, shared_name=shared_name) + _enqueue(queue, tensor_list, num_threads, enqueue_many, keep_input) + summary.scalar( + "fraction_of_%d_full" % capacity, + math_ops.cast(queue.size(), dtypes.float32) * (1. / capacity)) + + if allow_smaller_final_batch: + dequeued = queue.dequeue_up_to(batch_size, name=name) + else: + dequeued = queue.dequeue_many(batch_size, name=name) + dequeued = _restore_sparse_tensors(dequeued, sparse_info) + return _as_original_type(tensors, dequeued) + + +# TODO(josh11b): Add a thread_multiplier or num_threads (that has to be +# a multiple of len(tensor_list_list)?) parameter, to address the use +# case where you want more parallelism than you can support different +# readers (either because you don't have that many files or can't +# read that many files in parallel due to the number of seeks required). +# Once this is done, batch() can be written as a call to batch_join(). +def _batch_join(tensors_list, batch_size, keep_input, capacity=32, + enqueue_many=False, shapes=None, dynamic_pad=False, + allow_smaller_final_batch=False, shared_name=None, name=None): + """Helper function for `batch_join` and `maybe_batch_join`.""" + if context.executing_eagerly(): + raise ValueError( + "Input pipelines based on Queues are not supported when eager execution" + " is enabled. Please use tf.data to ingest data into your model" + " instead.") + tensor_list_list = _as_tensor_list_list(tensors_list) + with ops.name_scope(name, "batch_join", + _flatten(tensor_list_list) + [keep_input]) as name: + tensor_list_list = _validate_join(tensor_list_list) + keep_input = _validate_keep_input(keep_input, enqueue_many) + tensor_list_list, sparse_info = _store_sparse_tensors_join( + tensor_list_list, enqueue_many, keep_input) + types = _dtypes(tensor_list_list) + shapes = _shapes(tensor_list_list, shapes, enqueue_many) + # TODO(josh11b,mrry): Switch to BatchQueue once it is written. + queue = _which_queue(dynamic_pad)( + capacity=capacity, dtypes=types, shapes=shapes, shared_name=shared_name) + _enqueue_join(queue, tensor_list_list, enqueue_many, keep_input) + summary.scalar( + "fraction_of_%d_full" % capacity, + math_ops.cast(queue.size(), dtypes.float32) * (1. / capacity)) + + if allow_smaller_final_batch: + dequeued = queue.dequeue_up_to(batch_size, name=name) + else: + dequeued = queue.dequeue_many(batch_size, name=name) + dequeued = _restore_sparse_tensors(dequeued, sparse_info) + # tensors_list was validated to not be empty. + return _as_original_type(tensors_list[0], dequeued) + + +def _shuffle_batch(tensors, batch_size, capacity, min_after_dequeue, + keep_input, num_threads=1, seed=None, enqueue_many=False, + shapes=None, allow_smaller_final_batch=False, + shared_name=None, name=None): + """Helper function for `shuffle_batch` and `maybe_shuffle_batch`.""" + if context.executing_eagerly(): + raise ValueError( + "Input pipelines based on Queues are not supported when eager execution" + " is enabled. Please use tf.data to ingest data into your model" + " instead.") + tensor_list = _as_tensor_list(tensors) + with ops.name_scope(name, "shuffle_batch", + list(tensor_list) + [keep_input]) as name: + if capacity <= min_after_dequeue: + raise ValueError("capacity %d must be bigger than min_after_dequeue %d." + % (capacity, min_after_dequeue)) + tensor_list = _validate(tensor_list) + keep_input = _validate_keep_input(keep_input, enqueue_many) + tensor_list, sparse_info = _store_sparse_tensors( + tensor_list, enqueue_many, keep_input) + types = _dtypes([tensor_list]) + shapes = _shapes([tensor_list], shapes, enqueue_many) + queue = data_flow_ops.RandomShuffleQueue( + capacity=capacity, min_after_dequeue=min_after_dequeue, seed=seed, + dtypes=types, shapes=shapes, shared_name=shared_name) + _enqueue(queue, tensor_list, num_threads, enqueue_many, keep_input) + full = (math_ops.cast( + math_ops.maximum(0, queue.size() - min_after_dequeue), dtypes.float32) * + (1. / (capacity - min_after_dequeue))) + # Note that name contains a '/' at the end so we intentionally do not place + # a '/' after %s below. + summary_name = ( + "fraction_over_%d_of_%d_full" % + (min_after_dequeue, capacity - min_after_dequeue)) + summary.scalar(summary_name, full) + + if allow_smaller_final_batch: + dequeued = queue.dequeue_up_to(batch_size, name=name) + else: + dequeued = queue.dequeue_many(batch_size, name=name) + dequeued = _restore_sparse_tensors(dequeued, sparse_info) + return _as_original_type(tensors, dequeued) + + +def _shuffle_batch_join(tensors_list, batch_size, capacity, + min_after_dequeue, keep_input, seed=None, + enqueue_many=False, shapes=None, + allow_smaller_final_batch=False, shared_name=None, + name=None): + """Helper function for `shuffle_batch_join` and `maybe_shuffle_batch_join`.""" + if context.executing_eagerly(): + raise ValueError( + "Input pipelines based on Queues are not supported when eager execution" + " is enabled. Please use tf.data to ingest data into your model" + " instead.") + tensor_list_list = _as_tensor_list_list(tensors_list) + with ops.name_scope(name, "shuffle_batch_join", + _flatten(tensor_list_list) + [keep_input]) as name: + tensor_list_list = _validate_join(tensor_list_list) + keep_input = _validate_keep_input(keep_input, enqueue_many) + tensor_list_list, sparse_info = _store_sparse_tensors_join( + tensor_list_list, enqueue_many, keep_input) + types = _dtypes(tensor_list_list) + shapes = _shapes(tensor_list_list, shapes, enqueue_many) + queue = data_flow_ops.RandomShuffleQueue( + capacity=capacity, min_after_dequeue=min_after_dequeue, seed=seed, + dtypes=types, shapes=shapes, shared_name=shared_name) + _enqueue_join(queue, tensor_list_list, enqueue_many, keep_input) + full = (math_ops.cast( + math_ops.maximum(0, queue.size() - min_after_dequeue), dtypes.float32) * + (1. / (capacity - min_after_dequeue))) + # Note that name contains a '/' at the end so we intentionally do not place + # a '/' after %s below. + summary_name = ( + "fraction_over_%d_of_%d_full" % + (min_after_dequeue, capacity - min_after_dequeue)) + summary.scalar(summary_name, full) + + if allow_smaller_final_batch: + dequeued = queue.dequeue_up_to(batch_size, name=name) + else: + dequeued = queue.dequeue_many(batch_size, name=name) + dequeued = _restore_sparse_tensors(dequeued, sparse_info) + # tensors_list was validated to not be empty. + return _as_original_type(tensors_list[0], dequeued) + +# Batching functions ---------------------------------------------------------- + + +@tf_export(v1=["train.batch"]) +@deprecation.deprecated( + None, "Queue-based input pipelines have been replaced by `tf.data`. Use " + "`tf.data.Dataset.batch(batch_size)` (or `padded_batch(...)` if " + "`dynamic_pad=True`).") +def batch(tensors, batch_size, num_threads=1, capacity=32, + enqueue_many=False, shapes=None, dynamic_pad=False, + allow_smaller_final_batch=False, shared_name=None, name=None): + """Creates batches of tensors in `tensors`. + + The argument `tensors` can be a list or a dictionary of tensors. + The value returned by the function will be of the same type + as `tensors`. + + This function is implemented using a queue. A `QueueRunner` for the + queue is added to the current `Graph`'s `QUEUE_RUNNER` collection. + + If `enqueue_many` is `False`, `tensors` is assumed to represent a single + example. An input tensor with shape `[x, y, z]` will be output as a tensor + with shape `[batch_size, x, y, z]`. + + If `enqueue_many` is `True`, `tensors` is assumed to represent a batch of + examples, where the first dimension is indexed by example, and all members of + `tensors` should have the same size in the first dimension. If an input + tensor has shape `[*, x, y, z]`, the output will have shape `[batch_size, x, + y, z]`. The `capacity` argument controls the how long the prefetching is + allowed to grow the queues. + + The returned operation is a dequeue operation and will throw + `tf.errors.OutOfRangeError` if the input queue is exhausted. If this + operation is feeding another input queue, its queue runner will catch + this exception, however, if this operation is used in your main thread + you are responsible for catching this yourself. + + *N.B.:* If `dynamic_pad` is `False`, you must ensure that either + (i) the `shapes` argument is passed, or (ii) all of the tensors in + `tensors` must have fully-defined shapes. `ValueError` will be + raised if neither of these conditions holds. + + If `dynamic_pad` is `True`, it is sufficient that the *rank* of the + tensors is known, but individual dimensions may have shape `None`. + In this case, for each enqueue the dimensions with value `None` + may have a variable length; upon dequeue, the output tensors will be padded + on the right to the maximum shape of the tensors in the current minibatch. + For numbers, this padding takes value 0. For strings, this padding is + the empty string. See `PaddingFIFOQueue` for more info. + + If `allow_smaller_final_batch` is `True`, a smaller batch value than + `batch_size` is returned when the queue is closed and there are not enough + elements to fill the batch, otherwise the pending elements are discarded. + In addition, all output tensors' static shapes, as accessed via the + `shape` property will have a first `Dimension` value of `None`, and + operations that depend on fixed batch_size would fail. + + Args: + tensors: The list or dictionary of tensors to enqueue. + batch_size: The new batch size pulled from the queue. + num_threads: The number of threads enqueuing `tensors`. The batching will + be nondeterministic if `num_threads > 1`. + capacity: An integer. The maximum number of elements in the queue. + enqueue_many: Whether each tensor in `tensors` is a single example. + shapes: (Optional) The shapes for each example. Defaults to the + inferred shapes for `tensors`. + dynamic_pad: Boolean. Allow variable dimensions in input shapes. + The given dimensions are padded upon dequeue so that tensors within a + batch have the same shapes. + allow_smaller_final_batch: (Optional) Boolean. If `True`, allow the final + batch to be smaller if there are insufficient items left in the queue. + shared_name: (Optional). If set, this queue will be shared under the given + name across multiple sessions. + name: (Optional) A name for the operations. + + Returns: + A list or dictionary of tensors with the same types as `tensors` (except if + the input is a list of one element, then it returns a tensor, not a list). + + Raises: + ValueError: If the `shapes` are not specified, and cannot be + inferred from the elements of `tensors`. + + @compatibility(eager) + Input pipelines based on Queues are not supported when eager execution is + enabled. Please use the `tf.data` API to ingest data under eager execution. + @end_compatibility + """ + return _batch( + tensors, + batch_size, + keep_input=True, + num_threads=num_threads, + capacity=capacity, + enqueue_many=enqueue_many, + shapes=shapes, + dynamic_pad=dynamic_pad, + allow_smaller_final_batch=allow_smaller_final_batch, + shared_name=shared_name, + name=name) + + +@tf_export(v1=["train.maybe_batch"]) +@deprecation.deprecated( + None, "Queue-based input pipelines have been replaced by `tf.data`. Use " + "`tf.data.Dataset.filter(...).batch(batch_size)` (or `padded_batch(...)`" + " if `dynamic_pad=True`).") +def maybe_batch(tensors, keep_input, batch_size, num_threads=1, capacity=32, + enqueue_many=False, shapes=None, dynamic_pad=False, + allow_smaller_final_batch=False, shared_name=None, name=None): + """Conditionally creates batches of tensors based on `keep_input`. + + See docstring in `batch` for more details. + + Args: + tensors: The list or dictionary of tensors to enqueue. + keep_input: A `bool` Tensor. This tensor controls whether the input is + added to the queue or not. If it is a scalar and evaluates `True`, then + `tensors` are all added to the queue. If it is a vector and `enqueue_many` + is `True`, then each example is added to the queue only if the + corresponding value in `keep_input` is `True`. This tensor essentially + acts as a filtering mechanism. + batch_size: The new batch size pulled from the queue. + num_threads: The number of threads enqueuing `tensors`. The batching will + be nondeterministic if `num_threads > 1`. + capacity: An integer. The maximum number of elements in the queue. + enqueue_many: Whether each tensor in `tensors` is a single example. + shapes: (Optional) The shapes for each example. Defaults to the + inferred shapes for `tensors`. + dynamic_pad: Boolean. Allow variable dimensions in input shapes. + The given dimensions are padded upon dequeue so that tensors within a + batch have the same shapes. + allow_smaller_final_batch: (Optional) Boolean. If `True`, allow the final + batch to be smaller if there are insufficient items left in the queue. + shared_name: (Optional). If set, this queue will be shared under the given + name across multiple sessions. + name: (Optional) A name for the operations. + + Returns: + A list or dictionary of tensors with the same types as `tensors`. + + Raises: + ValueError: If the `shapes` are not specified, and cannot be + inferred from the elements of `tensors`. + """ + return _batch( + tensors, + batch_size, + keep_input, + num_threads=num_threads, + capacity=capacity, + enqueue_many=enqueue_many, + shapes=shapes, + dynamic_pad=dynamic_pad, + allow_smaller_final_batch=allow_smaller_final_batch, + shared_name=shared_name, + name=name) + + +@tf_export(v1=["train.batch_join"]) +@deprecation.deprecated( + None, "Queue-based input pipelines have been replaced by `tf.data`. Use " + "`tf.data.Dataset.interleave(...).batch(batch_size)` (or " + "`padded_batch(...)` if `dynamic_pad=True`).") +def batch_join(tensors_list, batch_size, capacity=32, enqueue_many=False, + shapes=None, dynamic_pad=False, allow_smaller_final_batch=False, + shared_name=None, name=None): + """Runs a list of tensors to fill a queue to create batches of examples. + + The `tensors_list` argument is a list of tuples of tensors, or a list of + dictionaries of tensors. Each element in the list is treated similarly + to the `tensors` argument of `tf.compat.v1.train.batch()`. + + WARNING: This function is nondeterministic, since it starts a separate thread + for each tensor. + + Enqueues a different list of tensors in different threads. + Implemented using a queue -- a `QueueRunner` for the queue + is added to the current `Graph`'s `QUEUE_RUNNER` collection. + + `len(tensors_list)` threads will be started, + with thread `i` enqueuing the tensors from + `tensors_list[i]`. `tensors_list[i1][j]` must match + `tensors_list[i2][j]` in type and shape, except in the first + dimension if `enqueue_many` is true. + + If `enqueue_many` is `False`, each `tensors_list[i]` is assumed + to represent a single example. An input tensor `x` will be output as a + tensor with shape `[batch_size] + x.shape`. + + If `enqueue_many` is `True`, `tensors_list[i]` is assumed to + represent a batch of examples, where the first dimension is indexed + by example, and all members of `tensors_list[i]` should have the + same size in the first dimension. The slices of any input tensor + `x` are treated as examples, and the output tensors will have shape + `[batch_size] + x.shape[1:]`. + + The `capacity` argument controls the how long the prefetching is allowed to + grow the queues. + + The returned operation is a dequeue operation and will throw + `tf.errors.OutOfRangeError` if the input queue is exhausted. If this + operation is feeding another input queue, its queue runner will catch + this exception, however, if this operation is used in your main thread + you are responsible for catching this yourself. + + *N.B.:* If `dynamic_pad` is `False`, you must ensure that either + (i) the `shapes` argument is passed, or (ii) all of the tensors in + `tensors_list` must have fully-defined shapes. `ValueError` will be + raised if neither of these conditions holds. + + If `dynamic_pad` is `True`, it is sufficient that the *rank* of the + tensors is known, but individual dimensions may have value `None`. + In this case, for each enqueue the dimensions with value `None` + may have a variable length; upon dequeue, the output tensors will be padded + on the right to the maximum shape of the tensors in the current minibatch. + For numbers, this padding takes value 0. For strings, this padding is + the empty string. See `PaddingFIFOQueue` for more info. + + If `allow_smaller_final_batch` is `True`, a smaller batch value than + `batch_size` is returned when the queue is closed and there are not enough + elements to fill the batch, otherwise the pending elements are discarded. + In addition, all output tensors' static shapes, as accessed via the + `shape` property will have a first `Dimension` value of `None`, and + operations that depend on fixed batch_size would fail. + + Args: + tensors_list: A list of tuples or dictionaries of tensors to enqueue. + batch_size: An integer. The new batch size pulled from the queue. + capacity: An integer. The maximum number of elements in the queue. + enqueue_many: Whether each tensor in `tensor_list_list` is a single + example. + shapes: (Optional) The shapes for each example. Defaults to the + inferred shapes for `tensor_list_list[i]`. + dynamic_pad: Boolean. Allow variable dimensions in input shapes. + The given dimensions are padded upon dequeue so that tensors within a + batch have the same shapes. + allow_smaller_final_batch: (Optional) Boolean. If `True`, allow the final + batch to be smaller if there are insufficient items left in the queue. + shared_name: (Optional) If set, this queue will be shared under the given + name across multiple sessions. + name: (Optional) A name for the operations. + + Returns: + A list or dictionary of tensors with the same number and types as + `tensors_list[i]`. + + Raises: + ValueError: If the `shapes` are not specified, and cannot be + inferred from the elements of `tensor_list_list`. + + @compatibility(eager) + Input pipelines based on Queues are not supported when eager execution is + enabled. Please use the `tf.data` API to ingest data under eager execution. + @end_compatibility + """ + return _batch_join( + tensors_list, + batch_size, + keep_input=True, + capacity=capacity, + enqueue_many=enqueue_many, + shapes=shapes, + dynamic_pad=dynamic_pad, + allow_smaller_final_batch=allow_smaller_final_batch, + shared_name=shared_name, + name=name) + + +@tf_export(v1=["train.maybe_batch_join"]) +@deprecation.deprecated( + None, "Queue-based input pipelines have been replaced by `tf.data`. Use " + "`tf.data.Dataset.interleave(...).filter(...).batch(batch_size)` (or " + "`padded_batch(...)` if `dynamic_pad=True`).") +def maybe_batch_join(tensors_list, keep_input, batch_size, capacity=32, + enqueue_many=False, shapes=None, dynamic_pad=False, + allow_smaller_final_batch=False, shared_name=None, + name=None): + """Runs a list of tensors to conditionally fill a queue to create batches. + + See docstring in `batch_join` for more details. + + Args: + tensors_list: A list of tuples or dictionaries of tensors to enqueue. + keep_input: A `bool` Tensor. This tensor controls whether the input is + added to the queue or not. If it is a scalar and evaluates `True`, then + `tensors` are all added to the queue. If it is a vector and `enqueue_many` + is `True`, then each example is added to the queue only if the + corresponding value in `keep_input` is `True`. This tensor essentially + acts as a filtering mechanism. + batch_size: An integer. The new batch size pulled from the queue. + capacity: An integer. The maximum number of elements in the queue. + enqueue_many: Whether each tensor in `tensor_list_list` is a single + example. + shapes: (Optional) The shapes for each example. Defaults to the + inferred shapes for `tensor_list_list[i]`. + dynamic_pad: Boolean. Allow variable dimensions in input shapes. + The given dimensions are padded upon dequeue so that tensors within a + batch have the same shapes. + allow_smaller_final_batch: (Optional) Boolean. If `True`, allow the final + batch to be smaller if there are insufficient items left in the queue. + shared_name: (Optional) If set, this queue will be shared under the given + name across multiple sessions. + name: (Optional) A name for the operations. + + Returns: + A list or dictionary of tensors with the same number and types as + `tensors_list[i]`. + + Raises: + ValueError: If the `shapes` are not specified, and cannot be + inferred from the elements of `tensor_list_list`. + """ + return _batch_join( + tensors_list, + batch_size, + keep_input, + capacity=capacity, + enqueue_many=enqueue_many, + shapes=shapes, + dynamic_pad=dynamic_pad, + allow_smaller_final_batch=allow_smaller_final_batch, + shared_name=shared_name, + name=name) + + +@tf_export(v1=["train.shuffle_batch"]) +@deprecation.deprecated( + None, "Queue-based input pipelines have been replaced by `tf.data`. Use " + "`tf.data.Dataset.shuffle(min_after_dequeue).batch(batch_size)`.") +def shuffle_batch(tensors, batch_size, capacity, min_after_dequeue, + num_threads=1, seed=None, enqueue_many=False, shapes=None, + allow_smaller_final_batch=False, shared_name=None, name=None): + """Creates batches by randomly shuffling tensors. + + This function adds the following to the current `Graph`: + + * A shuffling queue into which tensors from `tensors` are enqueued. + * A `dequeue_many` operation to create batches from the queue. + * A `QueueRunner` to `QUEUE_RUNNER` collection, to enqueue the tensors + from `tensors`. + + If `enqueue_many` is `False`, `tensors` is assumed to represent a + single example. An input tensor with shape `[x, y, z]` will be output + as a tensor with shape `[batch_size, x, y, z]`. + + If `enqueue_many` is `True`, `tensors` is assumed to represent a + batch of examples, where the first dimension is indexed by example, + and all members of `tensors` should have the same size in the + first dimension. If an input tensor has shape `[*, x, y, z]`, the + output will have shape `[batch_size, x, y, z]`. + + The `capacity` argument controls the how long the prefetching is allowed to + grow the queues. + + The returned operation is a dequeue operation and will throw + `tf.errors.OutOfRangeError` if the input queue is exhausted. If this + operation is feeding another input queue, its queue runner will catch + this exception, however, if this operation is used in your main thread + you are responsible for catching this yourself. + + For example: + + ```python + # Creates batches of 32 images and 32 labels. + image_batch, label_batch = tf.compat.v1.train.shuffle_batch( + [single_image, single_label], + batch_size=32, + num_threads=4, + capacity=50000, + min_after_dequeue=10000) + ``` + + *N.B.:* You must ensure that either (i) the `shapes` argument is + passed, or (ii) all of the tensors in `tensors` must have + fully-defined shapes. `ValueError` will be raised if neither of + these conditions holds. + + If `allow_smaller_final_batch` is `True`, a smaller batch value than + `batch_size` is returned when the queue is closed and there are not enough + elements to fill the batch, otherwise the pending elements are discarded. + In addition, all output tensors' static shapes, as accessed via the + `shape` property will have a first `Dimension` value of `None`, and + operations that depend on fixed batch_size would fail. + + Args: + tensors: The list or dictionary of tensors to enqueue. + batch_size: The new batch size pulled from the queue. + capacity: An integer. The maximum number of elements in the queue. + min_after_dequeue: Minimum number elements in the queue after a + dequeue, used to ensure a level of mixing of elements. + num_threads: The number of threads enqueuing `tensor_list`. + seed: Seed for the random shuffling within the queue. + enqueue_many: Whether each tensor in `tensor_list` is a single example. + shapes: (Optional) The shapes for each example. Defaults to the + inferred shapes for `tensor_list`. + allow_smaller_final_batch: (Optional) Boolean. If `True`, allow the final + batch to be smaller if there are insufficient items left in the queue. + shared_name: (Optional) If set, this queue will be shared under the given + name across multiple sessions. + name: (Optional) A name for the operations. + + Returns: + A list or dictionary of tensors with the types as `tensors`. + + Raises: + ValueError: If the `shapes` are not specified, and cannot be + inferred from the elements of `tensors`. + + @compatibility(eager) + Input pipelines based on Queues are not supported when eager execution is + enabled. Please use the `tf.data` API to ingest data under eager execution. + @end_compatibility + """ + return _shuffle_batch( + tensors, + batch_size, + capacity, + min_after_dequeue, + keep_input=True, + num_threads=num_threads, + seed=seed, + enqueue_many=enqueue_many, + shapes=shapes, + allow_smaller_final_batch=allow_smaller_final_batch, + shared_name=shared_name, + name=name) + + +@tf_export(v1=["train.maybe_shuffle_batch"]) +@deprecation.deprecated( + None, "Queue-based input pipelines have been replaced by `tf.data`. Use " + "`tf.data.Dataset.filter(...).shuffle(min_after_dequeue).batch(batch_size)`" + ".") +def maybe_shuffle_batch(tensors, batch_size, capacity, min_after_dequeue, + keep_input, num_threads=1, seed=None, + enqueue_many=False, shapes=None, + allow_smaller_final_batch=False, shared_name=None, + name=None): + """Creates batches by randomly shuffling conditionally-enqueued tensors. + + See docstring in `shuffle_batch` for more details. + + Args: + tensors: The list or dictionary of tensors to enqueue. + batch_size: The new batch size pulled from the queue. + capacity: An integer. The maximum number of elements in the queue. + min_after_dequeue: Minimum number elements in the queue after a + dequeue, used to ensure a level of mixing of elements. + keep_input: A `bool` Tensor. This tensor controls whether the input is + added to the queue or not. If it is a scalar and evaluates `True`, then + `tensors` are all added to the queue. If it is a vector and `enqueue_many` + is `True`, then each example is added to the queue only if the + corresponding value in `keep_input` is `True`. This tensor essentially + acts as a filtering mechanism. + num_threads: The number of threads enqueuing `tensor_list`. + seed: Seed for the random shuffling within the queue. + enqueue_many: Whether each tensor in `tensor_list` is a single example. + shapes: (Optional) The shapes for each example. Defaults to the + inferred shapes for `tensor_list`. + allow_smaller_final_batch: (Optional) Boolean. If `True`, allow the final + batch to be smaller if there are insufficient items left in the queue. + shared_name: (Optional) If set, this queue will be shared under the given + name across multiple sessions. + name: (Optional) A name for the operations. + + Returns: + A list or dictionary of tensors with the types as `tensors`. + + Raises: + ValueError: If the `shapes` are not specified, and cannot be + inferred from the elements of `tensors`. + + @compatibility(eager) + Input pipelines based on Queues are not supported when eager execution is + enabled. Please use the `tf.data` API to ingest data under eager execution. + @end_compatibility + """ + return _shuffle_batch( + tensors, + batch_size, + capacity, + min_after_dequeue, + keep_input, + num_threads=num_threads, + seed=seed, + enqueue_many=enqueue_many, + shapes=shapes, + allow_smaller_final_batch=allow_smaller_final_batch, + shared_name=shared_name, + name=name) + + +@tf_export(v1=["train.shuffle_batch_join"]) +@deprecation.deprecated( + None, "Queue-based input pipelines have been replaced by `tf.data`. Use " + "`tf.data.Dataset.interleave(...).shuffle(min_after_dequeue).batch" + "(batch_size)`.") +def shuffle_batch_join(tensors_list, batch_size, capacity, + min_after_dequeue, seed=None, enqueue_many=False, + shapes=None, allow_smaller_final_batch=False, + shared_name=None, name=None): + """Create batches by randomly shuffling tensors. + + The `tensors_list` argument is a list of tuples of tensors, or a list of + dictionaries of tensors. Each element in the list is treated similarly + to the `tensors` argument of `tf.compat.v1.train.shuffle_batch()`. + + This version enqueues a different list of tensors in different threads. + It adds the following to the current `Graph`: + + * A shuffling queue into which tensors from `tensors_list` are enqueued. + * A `dequeue_many` operation to create batches from the queue. + * A `QueueRunner` to `QUEUE_RUNNER` collection, to enqueue the tensors + from `tensors_list`. + + `len(tensors_list)` threads will be started, with thread `i` enqueuing + the tensors from `tensors_list[i]`. `tensors_list[i1][j]` must match + `tensors_list[i2][j]` in type and shape, except in the first dimension if + `enqueue_many` is true. + + If `enqueue_many` is `False`, each `tensors_list[i]` is assumed + to represent a single example. An input tensor with shape `[x, y, z]` + will be output as a tensor with shape `[batch_size, x, y, z]`. + + If `enqueue_many` is `True`, `tensors_list[i]` is assumed to + represent a batch of examples, where the first dimension is indexed + by example, and all members of `tensors_list[i]` should have the + same size in the first dimension. If an input tensor has shape `[*, x, + y, z]`, the output will have shape `[batch_size, x, y, z]`. + + The `capacity` argument controls the how long the prefetching is allowed to + grow the queues. + + The returned operation is a dequeue operation and will throw + `tf.errors.OutOfRangeError` if the input queue is exhausted. If this + operation is feeding another input queue, its queue runner will catch + this exception, however, if this operation is used in your main thread + you are responsible for catching this yourself. + + If `allow_smaller_final_batch` is `True`, a smaller batch value than + `batch_size` is returned when the queue is closed and there are not enough + elements to fill the batch, otherwise the pending elements are discarded. + In addition, all output tensors' static shapes, as accessed via the + `shape` property will have a first `Dimension` value of `None`, and + operations that depend on fixed batch_size would fail. + + Args: + tensors_list: A list of tuples or dictionaries of tensors to enqueue. + batch_size: An integer. The new batch size pulled from the queue. + capacity: An integer. The maximum number of elements in the queue. + min_after_dequeue: Minimum number elements in the queue after a + dequeue, used to ensure a level of mixing of elements. + seed: Seed for the random shuffling within the queue. + enqueue_many: Whether each tensor in `tensor_list_list` is a single + example. + shapes: (Optional) The shapes for each example. Defaults to the + inferred shapes for `tensors_list[i]`. + allow_smaller_final_batch: (Optional) Boolean. If `True`, allow the final + batch to be smaller if there are insufficient items left in the queue. + shared_name: (optional). If set, this queue will be shared under the given + name across multiple sessions. + name: (Optional) A name for the operations. + + Returns: + A list or dictionary of tensors with the same number and types as + `tensors_list[i]`. + + Raises: + ValueError: If the `shapes` are not specified, and cannot be + inferred from the elements of `tensors_list`. + + @compatibility(eager) + Input pipelines based on Queues are not supported when eager execution is + enabled. Please use the `tf.data` API to ingest data under eager execution. + @end_compatibility + """ + return _shuffle_batch_join( + tensors_list, + batch_size, + capacity, + min_after_dequeue, + keep_input=True, + seed=seed, + enqueue_many=enqueue_many, + shapes=shapes, + allow_smaller_final_batch=allow_smaller_final_batch, + shared_name=shared_name, + name=name) + + +@tf_export(v1=["train.maybe_shuffle_batch_join"]) +@deprecation.deprecated( + None, "Queue-based input pipelines have been replaced by `tf.data`. Use " + "`tf.data.Dataset.interleave(...).filter(...).shuffle(min_after_dequeue)" + ".batch(batch_size)`.") +def maybe_shuffle_batch_join(tensors_list, batch_size, capacity, + min_after_dequeue, keep_input, seed=None, + enqueue_many=False, shapes=None, + allow_smaller_final_batch=False, shared_name=None, + name=None): + """Create batches by randomly shuffling conditionally-enqueued tensors. + + See docstring in `shuffle_batch_join` for more details. + + Args: + tensors_list: A list of tuples or dictionaries of tensors to enqueue. + batch_size: An integer. The new batch size pulled from the queue. + capacity: An integer. The maximum number of elements in the queue. + min_after_dequeue: Minimum number elements in the queue after a + dequeue, used to ensure a level of mixing of elements. + keep_input: A `bool` Tensor. This tensor controls whether the input is + added to the queue or not. If it is a scalar and evaluates `True`, then + `tensors` are all added to the queue. If it is a vector and `enqueue_many` + is `True`, then each example is added to the queue only if the + corresponding value in `keep_input` is `True`. This tensor essentially + acts as a filtering mechanism. + seed: Seed for the random shuffling within the queue. + enqueue_many: Whether each tensor in `tensor_list_list` is a single + example. + shapes: (Optional) The shapes for each example. Defaults to the + inferred shapes for `tensors_list[i]`. + allow_smaller_final_batch: (Optional) Boolean. If `True`, allow the final + batch to be smaller if there are insufficient items left in the queue. + shared_name: (optional). If set, this queue will be shared under the given + name across multiple sessions. + name: (Optional) A name for the operations. + + Returns: + A list or dictionary of tensors with the same number and types as + `tensors_list[i]`. + + Raises: + ValueError: If the `shapes` are not specified, and cannot be + inferred from the elements of `tensors_list`. + + @compatibility(eager) + Input pipelines based on Queues are not supported when eager execution is + enabled. Please use the `tf.data` API to ingest data under eager execution. + @end_compatibility + """ + return _shuffle_batch_join( + tensors_list, + batch_size, + capacity, + min_after_dequeue, + keep_input, + seed=seed, + enqueue_many=enqueue_many, + shapes=shapes, + allow_smaller_final_batch=allow_smaller_final_batch, + shared_name=shared_name, + name=name) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/learning_rate_decay.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/learning_rate_decay.py new file mode 100644 index 0000000000000000000000000000000000000000..59d326d22f0f6e49eaea719bd0cbb792ed1c1389 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/learning_rate_decay.py @@ -0,0 +1,28 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Various learning rate decay functions.""" + +from tensorflow.python.keras.optimizer_v2 import legacy_learning_rate_decay as learning_rate_decay + + +exponential_decay = learning_rate_decay.exponential_decay +piecewise_constant = learning_rate_decay.piecewise_constant +polynomial_decay = learning_rate_decay.polynomial_decay +natural_exp_decay = learning_rate_decay.natural_exp_decay +inverse_time_decay = learning_rate_decay.inverse_time_decay +cosine_decay = learning_rate_decay.cosine_decay +cosine_decay_restarts = learning_rate_decay.cosine_decay_restarts +linear_cosine_decay = learning_rate_decay.linear_cosine_decay +noisy_linear_cosine_decay = learning_rate_decay.noisy_linear_cosine_decay diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/momentum.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/momentum.py new file mode 100644 index 0000000000000000000000000000000000000000..b7fec55e24e7c233767e663b1ae67415451d4273 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/momentum.py @@ -0,0 +1,203 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""Momentum for TensorFlow.""" +from tensorflow.python.framework import ops +from tensorflow.python.ops import math_ops +from tensorflow.python.training import optimizer +from tensorflow.python.training import training_ops +from tensorflow.python.util.tf_export import tf_export + + +@tf_export(v1=["train.MomentumOptimizer"]) +class MomentumOptimizer(optimizer.Optimizer): + """Optimizer that implements the Momentum algorithm. + + Computes (if `use_nesterov = False`): + + ``` + accumulation = momentum * accumulation + gradient + variable -= learning_rate * accumulation + ``` + + Note that in the dense version of this algorithm, `accumulation` is updated + and applied regardless of a gradient's value, whereas the sparse version (when + the gradient is an `IndexedSlices`, typically because of `tf.gather` or an + embedding) only updates variable slices and corresponding `accumulation` terms + when that part of the variable was used in the forward pass. + + @compatibility(TF2) + tf.compat.v1.train.MomentumOptimizer is compatible with eager mode and + `tf.function`. + When eager execution is enabled, `learning_rate`,`momentum`, can each be a + callable that takes no arguments and returns the actual value to use. This + can be useful for changing these values across different invocations of + optimizer functions. + + To switch to native TF2 style, please directly use + [`tf.keras.optimizers.SGD`] + (https://www.tensorflow.org/api_docs/python/tf/keras/optimizers/SGD) + with the `momentum` argument. + + #### Structural mapping to native TF2 + + Before: + + ```python + optimizer = tf.compat.v1.train.MomentumOptimizer( + learning_rate=learning_rate, + momentum=momentum, + use_nesterov=use_nesterov) + ``` + + After: + + ```python + optimizer = tf.keras.optimizers.SGD( + learning_rate=learning_rate, + momentum=momentum, + nesterov=use_nesterov) + ``` + + #### How to map arguments + | TF1 Arg Name | TF2 Arg Name | Note | + | ------------------ | ------------- | ------------------------------- | + | `learning_rate` | `learning_rate`| Be careful of setting | + : : : learning_rate tensor value computed from the global step. : + : : : In TF1 this was usually meant to imply a dynamic learning rate and : + : : : would recompute in each step. In TF2 (eager + function) it will : + : : : treat it as a scalar value that only gets computed once instead of : + : : : a symbolic placeholder to be computed each time. : + | `momentum` | `momentum` | - | + | `use_locking` | - | Not applicable in TF2. | + | `use_nesterov` | `nesterov` | - | + + #### Before & after usage example + Before: + + ```python + x = tf.Variable([1,2,3], dtype=tf.float32) + grad = tf.constant([0.1, 0.2, 0.3]) + optimizer = tf.compat.v1.train.MomentumOptimizer( + learning_rate=0.001, + momentum=0.9, + use_nesterov=False) + optimizer.apply_gradients(zip([grad], [x])) + ``` + + After: + + ```python + x = tf.Variable([1,2,3], dtype=tf.float32) + grad = tf.constant([0.1, 0.2, 0.3]) + optimizer = tf.keras.optimizers.SGD( + learning_rate=0.001, + momentum=0.9, + nesterov=False) + optimizer.apply_gradients(zip([grad], [x])) + ``` + + @end_compatibility + + """ + + def __init__(self, learning_rate, momentum, + use_locking=False, name="Momentum", use_nesterov=False): + """Construct a new Momentum optimizer. + + Args: + learning_rate: A `Tensor` or a floating point value. The learning rate. + momentum: A `Tensor` or a floating point value. The momentum. + use_locking: If `True` use locks for update operations. + name: Optional name prefix for the operations created when applying + gradients. Defaults to "Momentum". + use_nesterov: If `True` use Nesterov Momentum. + See (Sutskever et al., 2013). + This implementation always computes gradients at the value of the + variable(s) passed to the optimizer. Using Nesterov Momentum makes the + variable(s) track the values called `theta_t + mu*v_t` in the paper. + This implementation is an approximation of the original formula, valid + for high values of momentum. It will compute the "adjusted gradient" + in NAG by assuming that the new gradient will be estimated by the + current average gradient plus the product of momentum and the change + in the average gradient. + + References: + On the importance of initialization and momentum in deep learning: + [Sutskever et al., 2013] + (http://proceedings.mlr.press/v28/sutskever13.html) + ([pdf](http://proceedings.mlr.press/v28/sutskever13.pdf)) + + + """ + super(MomentumOptimizer, self).__init__(use_locking, name) + self._learning_rate = learning_rate + self._momentum = momentum + self._use_nesterov = use_nesterov + + def _create_slots(self, var_list): + for v in var_list: + self._zeros_slot(v, "momentum", self._name) + + def _prepare(self): + learning_rate = self._learning_rate + if callable(learning_rate): + learning_rate = learning_rate() + self._learning_rate_tensor = ops.convert_to_tensor(learning_rate, + name="learning_rate") + momentum = self._momentum + if callable(momentum): + momentum = momentum() + self._momentum_tensor = ops.convert_to_tensor(momentum, name="momentum") + + def _apply_dense(self, grad, var): + mom = self.get_slot(var, "momentum") + return training_ops.apply_momentum( + var, mom, + math_ops.cast(self._learning_rate_tensor, var.dtype.base_dtype), + grad, + math_ops.cast(self._momentum_tensor, var.dtype.base_dtype), + use_locking=self._use_locking, + use_nesterov=self._use_nesterov).op + + def _resource_apply_dense(self, grad, var): + mom = self.get_slot(var, "momentum") + return training_ops.resource_apply_momentum( + var.handle, mom.handle, + math_ops.cast(self._learning_rate_tensor, grad.dtype.base_dtype), + grad, + math_ops.cast(self._momentum_tensor, grad.dtype.base_dtype), + use_locking=self._use_locking, + use_nesterov=self._use_nesterov) + + def _apply_sparse(self, grad, var): + mom = self.get_slot(var, "momentum") + return training_ops.sparse_apply_momentum( + var, mom, + math_ops.cast(self._learning_rate_tensor, var.dtype.base_dtype), + grad.values, grad.indices, + math_ops.cast(self._momentum_tensor, var.dtype.base_dtype), + use_locking=self._use_locking, + use_nesterov=self._use_nesterov).op + + def _resource_apply_sparse(self, grad, var, indices): + mom = self.get_slot(var, "momentum") + return training_ops.resource_sparse_apply_momentum( + var.handle, mom.handle, + math_ops.cast(self._learning_rate_tensor, grad.dtype), + grad, indices, + math_ops.cast(self._momentum_tensor, grad.dtype), + use_locking=self._use_locking, + use_nesterov=self._use_nesterov) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/monitored_session.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/monitored_session.py new file mode 100644 index 0000000000000000000000000000000000000000..23d5eca67ba4393e7585b4ab4f28db44f2d2e024 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/monitored_session.py @@ -0,0 +1,1543 @@ +# pylint: disable=g-bad-file-header +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""A wrapper of Session API which runs hooks.""" + +import abc +import os + +from tensorflow.core.protobuf import config_pb2 +from tensorflow.python.checkpoint import checkpoint as trackable_util +from tensorflow.python.checkpoint import graph_view +from tensorflow.python.distribute import distribute_coordinator_context +from tensorflow.python.framework import errors +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import lookup_ops +from tensorflow.python.ops import resources +from tensorflow.python.ops import variables +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.summary import summary +from tensorflow.python.training import basic_session_run_hooks +from tensorflow.python.training import coordinator +from tensorflow.python.training import queue_runner +from tensorflow.python.training import saver as training_saver +from tensorflow.python.training import session_manager as sm +from tensorflow.python.training import session_run_hook +from tensorflow.python.util import function_utils +from tensorflow.python.util.tf_export import tf_export + +# The list of exceptions that we should recover from. Exceptions not in this +# list may terminate the job. +_PREEMPTION_ERRORS = (errors.AbortedError, errors.UnavailableError) + +# Value that indicates no value was provided. +USE_DEFAULT = object() + + +@tf_export(v1=['train.Scaffold']) +class Scaffold: + """Structure to create or gather pieces commonly needed to train a model. + + When you build a model for training you usually need ops to initialize + variables, a `Saver` to checkpoint them, an op to collect summaries for + the visualizer, and so on. + + Various libraries built on top of the core TensorFlow library take care of + creating some or all of these pieces and storing them in well known + collections in the graph. The `Scaffold` class helps pick these pieces from + the graph collections, creating and adding them to the collections if needed. + + If you call the scaffold constructor without any arguments, it will pick + pieces from the collections, creating default ones if needed when + `scaffold.finalize()` is called. You can pass arguments to the constructor to + provide your own pieces. Pieces that you pass to the constructor are not + added to the graph collections. + + The following pieces are directly accessible as attributes of the `Scaffold` + object: + + * `saver`: A `tf.compat.v1.train.Saver` object taking care of saving the + variables. + Picked from and stored into the `SAVERS` collection in the graph by default. + * `init_op`: An op to run to initialize the variables. Picked from and + stored into the `INIT_OP` collection in the graph by default. + * `ready_op`: An op to verify that the variables are initialized. Picked + from and stored into the `READY_OP` collection in the graph by default. + * `ready_for_local_init_op`: An op to verify that global state has been + initialized and it is alright to run `local_init_op`. Picked from and + stored into the `READY_FOR_LOCAL_INIT_OP` collection in the graph by + default. This is needed when the initialization of local variables depends + on the values of global variables. + * `local_init_op`: An op to initialize the local variables. Picked + from and stored into the `LOCAL_INIT_OP` collection in the graph by default. + * `summary_op`: An op to run and merge the summaries in the graph. Picked + from and stored into the `SUMMARY_OP` collection in the graph by default. + + You can also pass the following additional pieces to the constructor: + + * `init_feed_dict`: A session feed dictionary that should be used when + running the init op. + * `init_fn`: A callable to run after the init op to perform additional + initializations. The callable will be called as + `init_fn(scaffold, session)`. + + """ + + def __init__(self, + init_op=None, + init_feed_dict=None, + init_fn=None, + ready_op=None, + ready_for_local_init_op=None, + local_init_op=None, + summary_op=None, + saver=None, + copy_from_scaffold=None, + local_init_feed_dict=None): + """Create a scaffold. + + Args: + init_op: Optional op for initializing variables. + init_feed_dict: Optional session feed dictionary to use when running the + init_op. + init_fn: Optional function to use to initialize the model after running + the init_op. Will be called as `init_fn(scaffold, session)`. + ready_op: Optional op to verify that the variables are initialized. Must + return an empty 1D string tensor when the variables are initialized, or + a non-empty 1D string tensor listing the names of the non-initialized + variables. + ready_for_local_init_op: Optional op to verify that the global variables + are initialized and `local_init_op` can be run. Must return an empty 1D + string tensor when the global variables are initialized, or a non-empty + 1D string tensor listing the names of the non-initialized global + variables. + local_init_op: Optional op to initialize local variables. + summary_op: Optional op to gather all summaries. Must return a scalar + string tensor containing a serialized `Summary` proto. + saver: Optional `tf.compat.v1.train.Saver` object to use to save and + restore variables. May also be a `tf.train.Checkpoint` object, in which + case object-based checkpoints are saved. This will also load some + object-based checkpoints saved from elsewhere, but that loading may be + fragile since it uses fixed keys rather than performing a full + graph-based match. For example if a variable has two paths from the + `Checkpoint` object because two `Model` objects share the `Layer` object + that owns it, removing one `Model` may change the keys and break + checkpoint loading through this API, whereas a graph-based match would + match the variable through the other `Model`. + copy_from_scaffold: Optional scaffold object to copy fields from. Its + fields will be overwritten by the provided fields in this function. + local_init_feed_dict: Optional session feed dictionary to use when running + the local_init_op. + """ + if copy_from_scaffold is not None: + if not isinstance(copy_from_scaffold, Scaffold): + raise TypeError('copy_from_scaffold is not a Scaffold instance.') + # We need _coalesce since Tensor is not converted to bool automatically, + # so the common idiom of (a or b) does not work. + coalesce = lambda a, b: a if a is not None else b + init_op = coalesce(init_op, copy_from_scaffold.init_op) + init_feed_dict = coalesce(init_feed_dict, + copy_from_scaffold.init_feed_dict) + # Use the original init_fn provided by the user to init the new Scaffold. + init_fn = coalesce(init_fn, copy_from_scaffold._user_init_fn) # pylint: disable=protected-access + ready_op = coalesce(ready_op, copy_from_scaffold.ready_op) + ready_for_local_init_op = coalesce( + ready_for_local_init_op, copy_from_scaffold.ready_for_local_init_op) + local_init_op = coalesce(local_init_op, copy_from_scaffold.local_init_op) + local_init_feed_dict = coalesce(local_init_feed_dict, + copy_from_scaffold.local_init_feed_dict) + summary_op = coalesce(summary_op, copy_from_scaffold.summary_op) + saver = coalesce(saver, copy_from_scaffold.saver) + + # NOTE(touts): modifying the init function to be passed the scaffold is a + # hack to make it easy to find the saver. Is there a better way? + self._user_init_fn = init_fn + if init_fn: + self._init_fn = lambda sess: init_fn(self, sess) + else: + self._init_fn = None + + self._init_op = init_op + self._init_feed_dict = init_feed_dict + self._ready_op = ready_op + self._ready_for_local_init_op = ready_for_local_init_op + self._local_init_op = local_init_op + self._local_init_feed_dict = local_init_feed_dict + self._summary_op = summary_op + self._saver = saver + + def finalize(self): + """Creates operations if needed and finalizes the graph.""" + if self._init_op is None: + + def default_init_op(): + return control_flow_ops.group( + variables.global_variables_initializer(), + resources.initialize_resources(resources.shared_resources()), + ops.get_collection('saved_model_initializers')) + + self._init_op = Scaffold.get_or_default('init_op', ops.GraphKeys.INIT_OP, + default_init_op) + if self._ready_op is None: + + def default_ready_op(): + return array_ops.concat([ + variables.report_uninitialized_variables(), + resources.report_uninitialized_resources() + ], 0) + + self._ready_op = Scaffold.get_or_default('ready_op', + ops.GraphKeys.READY_OP, + default_ready_op) + if self._ready_for_local_init_op is None: + + def default_ready_for_local_init_op(): + return array_ops.concat([ + variables.report_uninitialized_variables( + variables.global_variables()), + resources.report_uninitialized_resources( + resources.shared_resources()) + ], 0) + + self._ready_for_local_init_op = Scaffold.get_or_default( + 'ready_for_local_init_op', ops.GraphKeys.READY_FOR_LOCAL_INIT_OP, + default_ready_for_local_init_op) + if self._local_init_op is None: + self._local_init_op = Scaffold.get_or_default( + 'local_init_op', ops.GraphKeys.LOCAL_INIT_OP, + Scaffold.default_local_init_op) + if self._summary_op is None: + self._summary_op = Scaffold.get_or_default('summary_op', + ops.GraphKeys.SUMMARY_OP, + summary.merge_all) + # pylint: disable=g-long-lambda + if self._saver is None: + self._saver = training_saver._get_saver_or_default() # pylint: disable=protected-access + # pylint: enable=g-long-lambda + if isinstance(self._saver, trackable_util.Checkpoint): + self._saver = training_saver.Saver( + var_list=graph_view.ObjectGraphView( + self._saver).frozen_saveable_objects(), + sharded=True) + else: + self._saver.build() + + ops.get_default_graph().finalize() + logging.info('Graph was finalized.') + return self + + @property + def init_fn(self): + return self._init_fn + + @property + def init_op(self): + return self._init_op + + @property + def ready_op(self): + return self._ready_op + + @property + def ready_for_local_init_op(self): + return self._ready_for_local_init_op + + @property + def local_init_op(self): + return self._local_init_op + + @property + def local_init_feed_dict(self): + return self._local_init_feed_dict + + @property + def summary_op(self): + return self._summary_op + + @property + def saver(self): + return self._saver + + @property + def init_feed_dict(self): + return self._init_feed_dict + + @staticmethod + def get_or_default(arg_name, collection_key, default_constructor): + """Get from cache or create a default operation.""" + elements = ops.get_collection(collection_key) + if elements: + if len(elements) > 1: + raise RuntimeError( + 'More than one item in the collection "%s". ' + 'Please indicate which one to use by passing it to ' + 'the tf.Scaffold constructor as: ' + 'tf.Scaffold(%s=item to use)', collection_key, arg_name) + return elements[0] + op = default_constructor() + if op is not None: + ops.add_to_collection(collection_key, op) + return op + + @staticmethod + def default_local_init_op(): + """Returns an op that groups the default local init ops. + + This op is used during session initialization when a Scaffold is + initialized without specifying the local_init_op arg. It includes + `tf.compat.v1.local_variables_initializer`, + `tf.compat.v1.tables_initializer`, and also + initializes local session resources. + + Returns: + The default Scaffold local init op. + """ + return control_flow_ops.group( + variables.local_variables_initializer(), + lookup_ops.tables_initializer(), + resources.initialize_resources(resources.local_resources())) + + +def _create_monitored_session_with_worker_context( + worker_context, # pylint: disable=missing-docstring + scaffold, + checkpoint_dir=None, + hooks=None, + chief_only_hooks=None, + save_checkpoint_secs=None, + save_summaries_steps=None, + save_summaries_secs=None, + config=None, + stop_grace_period_secs=120, + log_step_count_steps=100, + max_wait_secs=7200, + save_checkpoint_steps=None, + summary_dir=None, + save_graph_def=True): + all_hooks = [] + if hooks: + all_hooks.extend(hooks) + if chief_only_hooks and worker_context.is_chief: + all_hooks.extend(chief_only_hooks) + + # We need to call save or summary ops on all workers since these ops may + # contain collective ops, only running save ops on some workers would make + # collective ops hang. Therefore on those workers that don't need to actually + # write checkpoints or summaries, we let them write to a temp directory. + # pylint: disable=protected-access + if type( + worker_context._strategy).__name__ in ('CollectiveAllReduceStrategy', + 'CollectiveAllReduceStrategyV1', + 'MultiWorkerMirroredStrategy'): + if worker_context.task_type: + tmpdir = 'tmp_%s_%d' % (worker_context.task_type, worker_context.task_id) + else: + tmpdir = 'tmp' + + if save_checkpoint_secs: + logging.warning('Collective ops may deadlock with ' + '`save_checkpoints_secs` please use ' + '`save_checkpoint_steps` instead. Clearing ' + '`save_checkpoint_secs` and setting ' + '`save_checkpoint_steps` to 1000 now.') + save_checkpoint_secs = None + save_checkpoint_steps = 1000 + if save_summaries_secs: + logging.warning('Collective ops may run out of sync with' + '`save_summaries_secs`, please use ' + '`save_summaries_steps` instead.') + else: + tmpdir = None + + summary_dir = summary_dir or checkpoint_dir + if summary_dir and log_step_count_steps and log_step_count_steps > 0: + if worker_context.should_save_summary: + all_hooks.append( + basic_session_run_hooks.StepCounterHook( + output_dir=summary_dir, every_n_steps=log_step_count_steps)) + elif tmpdir: + all_hooks.append( + basic_session_run_hooks.StepCounterHook( + output_dir=os.path.join(summary_dir, tmpdir), + every_n_steps=log_step_count_steps)) + + if (((save_summaries_steps and save_summaries_steps > 0) or + (save_summaries_secs and save_summaries_secs > 0)) and summary_dir): + if worker_context.should_save_summary: + all_hooks.append( + basic_session_run_hooks.SummarySaverHook( + scaffold=scaffold, + save_steps=save_summaries_steps, + save_secs=save_summaries_secs, + output_dir=summary_dir)) + elif tmpdir: + all_hooks.append( + basic_session_run_hooks.SummarySaverHook( + scaffold=scaffold, + save_steps=save_summaries_steps, + save_secs=save_summaries_secs, + output_dir=os.path.join(summary_dir, tmpdir))) + + if (((save_checkpoint_secs and save_checkpoint_secs > 0) or + (save_checkpoint_steps and save_checkpoint_steps > 0)) and + checkpoint_dir): + if worker_context.should_checkpoint: + all_hooks.append( + basic_session_run_hooks.CheckpointSaverHook( + checkpoint_dir, + save_steps=save_checkpoint_steps, + save_secs=save_checkpoint_secs, + scaffold=scaffold, + save_graph_def=save_graph_def)) + elif tmpdir: + all_hooks.append( + basic_session_run_hooks.CheckpointSaverHook( + os.path.join(checkpoint_dir, tmpdir), + save_steps=save_checkpoint_steps, + save_secs=save_checkpoint_secs, + scaffold=scaffold, + save_graph_def=save_graph_def)) + + logging.info('all_hooks %r', all_hooks) + session_creator = worker_context.session_creator( + scaffold, + config=config, + checkpoint_dir=checkpoint_dir, + max_wait_secs=max_wait_secs) + return MonitoredSession( + session_creator=session_creator, + hooks=all_hooks, + stop_grace_period_secs=stop_grace_period_secs) + + +@tf_export(v1=['train.MonitoredTrainingSession']) +def MonitoredTrainingSession( + master='', # pylint: disable=invalid-name + is_chief=True, + checkpoint_dir=None, + scaffold=None, + hooks=None, + chief_only_hooks=None, + save_checkpoint_secs=USE_DEFAULT, + save_summaries_steps=USE_DEFAULT, + save_summaries_secs=USE_DEFAULT, + config=None, + stop_grace_period_secs=120, + log_step_count_steps=100, + max_wait_secs=7200, + save_checkpoint_steps=USE_DEFAULT, + summary_dir=None, + save_graph_def=True): + """Creates a `MonitoredSession` for training. + + For a chief, this utility sets proper session initializer/restorer. It also + creates hooks related to checkpoint and summary saving. For workers, this + utility sets proper session creator which waits for the chief to + initialize/restore. Please check `tf.compat.v1.train.MonitoredSession` for + more + information. + + @compatibility(TF2) + This API is not compatible with eager execution and `tf.function`. To migrate + to TF2, rewrite the code to be compatible with eager execution. Check the + [migration + guide](https://www.tensorflow.org/guide/migrate#1_replace_v1sessionrun_calls) + on replacing `Session.run` calls. In Keras, session hooks can be replaced by + Callbacks e.g. [logging hook notebook]( + https://github.com/tensorflow/docs/blob/master/site/en/guide/migrate/logging_stop_hook.ipynb) + For more details please read [Better + performance with tf.function](https://www.tensorflow.org/guide/function). + @end_compatibility + + Args: + master: `String` the TensorFlow master to use. + is_chief: If `True`, it will take care of initialization and recovery the + underlying TensorFlow session. If `False`, it will wait on a chief to + initialize or recover the TensorFlow session. + checkpoint_dir: A string. Optional path to a directory where to restore + variables. + scaffold: A `Scaffold` used for gathering or building supportive ops. If not + specified, a default one is created. It's used to finalize the graph. + hooks: Optional list of `SessionRunHook` objects. + chief_only_hooks: list of `SessionRunHook` objects. Activate these hooks if + `is_chief==True`, ignore otherwise. + save_checkpoint_secs: The frequency, in seconds, that a checkpoint is saved + using a default checkpoint saver. If both `save_checkpoint_steps` and + `save_checkpoint_secs` are set to `None`, then the default checkpoint + saver isn't used. If both are provided, then only `save_checkpoint_secs` + is used. Default 600. + save_summaries_steps: The frequency, in number of global steps, that the + summaries are written to disk using a default summary saver. If both + `save_summaries_steps` and `save_summaries_secs` are set to `None`, then + the default summary saver isn't used. Default 100. + save_summaries_secs: The frequency, in secs, that the summaries are written + to disk using a default summary saver. If both `save_summaries_steps` and + `save_summaries_secs` are set to `None`, then the default summary saver + isn't used. Default not enabled. + config: an instance of `tf.compat.v1.ConfigProto` proto used to configure + the session. It's the `config` argument of constructor of + `tf.compat.v1.Session`. + stop_grace_period_secs: Number of seconds given to threads to stop after + `close()` has been called. + log_step_count_steps: The frequency, in number of global steps, that the + global step/sec is logged. + max_wait_secs: Maximum time workers should wait for the session to become + available. This should be kept relatively short to help detect incorrect + code, but sometimes may need to be increased if the chief takes a while to + start up. + save_checkpoint_steps: The frequency, in number of global steps, that a + checkpoint is saved using a default checkpoint saver. If both + `save_checkpoint_steps` and `save_checkpoint_secs` are set to `None`, then + the default checkpoint saver isn't used. If both are provided, then only + `save_checkpoint_secs` is used. Default not enabled. + summary_dir: A string. Optional path to a directory where to save + summaries. If None, checkpoint_dir is used instead. + save_graph_def: Whether to save the GraphDef and MetaGraphDef to + `checkpoint_dir`. The GraphDef is saved after the session is created as + `graph.pbtxt`. MetaGraphDefs are saved out for every checkpoint as + `model.ckpt-*.meta`. + + Returns: + A `MonitoredSession` object. + """ + if save_summaries_steps == USE_DEFAULT and save_summaries_secs == USE_DEFAULT: + save_summaries_steps = 100 + save_summaries_secs = None + elif save_summaries_secs == USE_DEFAULT: + save_summaries_secs = None + elif save_summaries_steps == USE_DEFAULT: + save_summaries_steps = None + + if (save_checkpoint_steps == USE_DEFAULT and + save_checkpoint_secs == USE_DEFAULT): + save_checkpoint_steps = None + save_checkpoint_secs = 600 + elif save_checkpoint_secs == USE_DEFAULT: + save_checkpoint_secs = None + elif save_checkpoint_steps == USE_DEFAULT: + save_checkpoint_steps = None + + scaffold = scaffold or Scaffold() + worker_context = distribute_coordinator_context.get_current_worker_context() + + if worker_context: + return _create_monitored_session_with_worker_context( + worker_context, + scaffold, + checkpoint_dir=checkpoint_dir, + hooks=hooks, + chief_only_hooks=chief_only_hooks, + save_checkpoint_secs=save_checkpoint_secs, + save_summaries_steps=save_summaries_steps, + save_summaries_secs=save_summaries_secs, + config=config, + stop_grace_period_secs=stop_grace_period_secs, + log_step_count_steps=log_step_count_steps, + max_wait_secs=max_wait_secs, + save_checkpoint_steps=save_checkpoint_steps, + summary_dir=summary_dir, + save_graph_def=save_graph_def) + + if not is_chief: + session_creator = WorkerSessionCreator( + scaffold=scaffold, + master=master, + config=config, + max_wait_secs=max_wait_secs) + return MonitoredSession( + session_creator=session_creator, + hooks=hooks or [], + stop_grace_period_secs=stop_grace_period_secs) + + all_hooks = [] + if chief_only_hooks: + all_hooks.extend(chief_only_hooks) + session_creator = ChiefSessionCreator( + scaffold=scaffold, + checkpoint_dir=checkpoint_dir, + master=master, + config=config) + + summary_dir = summary_dir or checkpoint_dir + if summary_dir: + if log_step_count_steps and log_step_count_steps > 0: + all_hooks.append( + basic_session_run_hooks.StepCounterHook( + output_dir=summary_dir, every_n_steps=log_step_count_steps)) + + if (save_summaries_steps and + save_summaries_steps > 0) or (save_summaries_secs and + save_summaries_secs > 0): + all_hooks.append( + basic_session_run_hooks.SummarySaverHook( + scaffold=scaffold, + save_steps=save_summaries_steps, + save_secs=save_summaries_secs, + output_dir=summary_dir)) + + if checkpoint_dir: + if (save_checkpoint_secs and + save_checkpoint_secs > 0) or (save_checkpoint_steps and + save_checkpoint_steps > 0): + all_hooks.append( + basic_session_run_hooks.CheckpointSaverHook( + checkpoint_dir, + save_steps=save_checkpoint_steps, + save_secs=save_checkpoint_secs, + scaffold=scaffold, + save_graph_def=save_graph_def)) + + if hooks: + all_hooks.extend(hooks) + return MonitoredSession( + session_creator=session_creator, + hooks=all_hooks, + stop_grace_period_secs=stop_grace_period_secs) + + +@tf_export(v1=['train.SessionCreator']) +class SessionCreator(metaclass=abc.ABCMeta): + """A factory for tf.Session.""" + + @abc.abstractmethod + def create_session(self): + raise NotImplementedError( + 'create_session is not implemented for {}.'.format(self)) + + +@tf_export(v1=['train.ChiefSessionCreator']) +class ChiefSessionCreator(SessionCreator): + """Creates a tf.compat.v1.Session for a chief.""" + + def __init__(self, + scaffold=None, + master='', + config=None, + checkpoint_dir=None, + checkpoint_filename_with_path=None): + """Initializes a chief session creator. + + Args: + scaffold: A `Scaffold` used for gathering or building supportive ops. If + not specified a default one is created. It's used to finalize the graph. + master: `String` representation of the TensorFlow master to use. + config: `ConfigProto` proto used to configure the session. + checkpoint_dir: A string. Optional path to a directory where to restore + variables. + checkpoint_filename_with_path: Full file name path to the checkpoint file. + """ + self._checkpoint_dir = checkpoint_dir + self._checkpoint_filename_with_path = checkpoint_filename_with_path + self._scaffold = scaffold or Scaffold() + self._session_manager = None + self._master = master + self._config = config + + def _get_session_manager(self): + """Gets or creates a SessionManager.""" + if self._session_manager: + return self._session_manager + + self._session_manager = sm.SessionManager( + local_init_op=self._scaffold.local_init_op, + local_init_feed_dict=self._scaffold.local_init_feed_dict, + ready_op=self._scaffold.ready_op, + ready_for_local_init_op=self._scaffold.ready_for_local_init_op, + graph=ops.get_default_graph()) + return self._session_manager + + def create_session(self): + self._scaffold.finalize() + return self._get_session_manager().prepare_session( + self._master, + saver=self._scaffold.saver, + checkpoint_dir=self._checkpoint_dir, + checkpoint_filename_with_path=self._checkpoint_filename_with_path, + config=self._config, + init_op=self._scaffold.init_op, + init_feed_dict=self._scaffold.init_feed_dict, + init_fn=self._scaffold.init_fn) + + +@tf_export(v1=['train.WorkerSessionCreator']) +class WorkerSessionCreator(SessionCreator): + """Creates a tf.compat.v1.Session for a worker.""" + + def __init__(self, + scaffold=None, + master='', + config=None, + max_wait_secs=30 * 60): + """Initializes a worker session creator. + + Args: + scaffold: A `Scaffold` used for gathering or building supportive ops. If + not specified a default one is created. It's used to finalize the graph. + master: `String` representation of the TensorFlow master to use. + config: `ConfigProto` proto used to configure the session. + max_wait_secs: Maximum time to wait for the session to become available. + """ + self._scaffold = scaffold or Scaffold() + self._session_manager = None + self._master = master + self._config = config + self._max_wait_secs = max_wait_secs + + def _get_session_manager(self): + """Gets or creates a SessionManager.""" + if self._session_manager: + return self._session_manager + + self._session_manager = sm.SessionManager( + local_init_op=self._scaffold.local_init_op, + local_init_feed_dict=self._scaffold.local_init_feed_dict, + ready_op=self._scaffold.ready_op, + ready_for_local_init_op=self._scaffold.ready_for_local_init_op, + graph=ops.get_default_graph()) + return self._session_manager + + def create_session(self): + self._scaffold.finalize() + return self._get_session_manager().wait_for_session( + self._master, config=self._config, max_wait_secs=self._max_wait_secs) + + +class _MonitoredSession: + """See `MonitoredSession` or `SingularMonitoredSession`.""" + + def __init__(self, + session_creator, + hooks, + should_recover, + stop_grace_period_secs=120): + """Sets up a Monitored or Hooked Session. + + Args: + session_creator: A factory object to create session. Typically a + `ChiefSessionCreator` or a `WorkerSessionCreator`. + hooks: An iterable of `SessionRunHook' objects. + should_recover: A bool. Indicates whether to recover from `AbortedError` + and `UnavailableError` or not. + stop_grace_period_secs: Number of seconds given to threads to stop after + `close()` has been called. + """ + self._graph_was_finalized = ops.get_default_graph().finalized + self._hooks = hooks or [] + for h in self._hooks: + h.begin() + + worker_context = distribute_coordinator_context.get_current_worker_context() + if not session_creator and worker_context: + session_creator = worker_context.session_creator() + + # Create the session. + self._coordinated_creator = self._CoordinatedSessionCreator( + session_creator=session_creator or ChiefSessionCreator(), + hooks=self._hooks, + stop_grace_period_secs=stop_grace_period_secs) + if should_recover: + self._sess = _RecoverableSession(self._coordinated_creator) + else: + self._sess = self._coordinated_creator.create_session() + + @property + def graph(self): + """The graph that was launched in this session.""" + if self._tf_sess() is None: + return None + return self._tf_sess().graph + + def run(self, fetches, feed_dict=None, options=None, run_metadata=None): + """Run ops in the monitored session. + + This method is completely compatible with the `tf.Session.run()` method. + + Args: + fetches: Same as `tf.Session.run()`. + feed_dict: Same as `tf.Session.run()`. + options: Same as `tf.Session.run()`. + run_metadata: Same as `tf.Session.run()`. + + Returns: + Same as `tf.Session.run()`. + """ + return self._sess.run( + fetches, + feed_dict=feed_dict, + options=options, + run_metadata=run_metadata) + + def run_step_fn(self, step_fn): + """Run ops using a step function. + + Args: + step_fn: A function or a method with a single argument of type + `StepContext`. The function may use methods of the argument to perform + computations with access to a raw session. The returned value of the + `step_fn` will be returned from `run_step_fn`, unless a stop is + requested. In that case, the next `should_stop` call will return True. + Example usage: + ```python + with tf.Graph().as_default(): + c = tf.compat.v1.placeholder(dtypes.float32) + v = tf.add(c, 4.0) + w = tf.add(c, 0.5) + def step_fn(step_context): + a = step_context.session.run(fetches=v, feed_dict={c: 0.5}) + if a <= 4.5: + step_context.request_stop() + return step_context.run_with_hooks(fetches=w, + feed_dict={c: 0.1}) + + with tf.MonitoredSession() as session: + while not session.should_stop(): + a = session.run_step_fn(step_fn) + ``` + Hooks interact with the `run_with_hooks()` call inside the + `step_fn` as they do with a `MonitoredSession.run` call. + + Returns: + Returns the returned value of `step_fn`. + + Raises: + StopIteration: if `step_fn` has called `request_stop()`. It may be + caught by `with tf.MonitoredSession()` to close the session. + ValueError: if `step_fn` doesn't have a single argument called + `step_context`. It may also optionally have `self` for cases when it + belongs to an object. + """ + step_fn_arguments = function_utils.fn_args(step_fn) + if step_fn_arguments != ('step_context',) and step_fn_arguments != ( + 'self', + 'step_context', + ): + raise ValueError( + '`step_fn` may either have one `step_context` argument, or' + ' `self` and `step_context` arguments if it\'s an instance' + ' method. Got {} instead.'.format(step_fn_arguments)) + + # `self._sess` is either `_RecoverableSession` or a `_CoordinatedSession`. + # Setting `run_with_hooks` to `None` will cause `run_with_hooks` to be + # `_CoordinatedSession.run` downstream in either case. This allows + # `_PREEMPTION_ERRORS` to propage from within `step_fn` to + # `_RecoverableSession.run_step_fn`. + return self._sess.run_step_fn(step_fn, self._tf_sess(), run_with_hooks=None) + + class StepContext: + """Control flow instrument for the `step_fn` from `run_step_fn()`. + + Users of `step_fn` may perform `run()` calls without running hooks + by accessing the `session`. A `run()` call with hooks may be performed + using `run_with_hooks()`. Computation flow can be interrupted using + `request_stop()`. + """ + + def __init__(self, session, run_with_hooks_fn): + """Initializes the `step_context` argument for a `step_fn` invocation. + + Args: + session: An instance of `tf.compat.v1.Session`. + run_with_hooks_fn: A function for running fetches and hooks. + """ + self._session = session + self._run_with_hooks_fn = run_with_hooks_fn + + @property + def session(self): + return self._session + + def run_with_hooks(self, *args, **kwargs): + """Same as `MonitoredSession.run`. Accepts the same arguments.""" + return self._run_with_hooks_fn(*args, **kwargs) + + def request_stop(self): + """Exit the training loop by causing `should_stop()` to return `True`. + + Causes `step_fn` to exit by raising an exception. + + Raises: + StopIteration + """ + raise StopIteration('step_fn has requested the iterations to stop.') + + def should_stop(self): + return self._sess is None or self._sess.should_stop() + + def close(self): + self._close_internal() + + def __enter__(self): + return self + + def __exit__(self, exception_type, exception_value, traceback): + if exception_type in [errors.OutOfRangeError, StopIteration]: + exception_type = None + self._close_internal(exception_type) + # __exit__ should return True to suppress an exception. + return exception_type is None + + class _CoordinatedSessionCreator(SessionCreator): + """Factory for _CoordinatedSession.""" + + def __init__(self, session_creator, hooks, stop_grace_period_secs): + self._session_creator = session_creator + self._hooks = hooks + self.coord = None + self.tf_sess = None + self._stop_grace_period_secs = stop_grace_period_secs + + def create_session(self): + """Creates a coordinated session.""" + # Keep the tf_sess for unit testing. + self.tf_sess = self._session_creator.create_session() + # We don't want coordinator to suppress any exception. + self.coord = coordinator.Coordinator(clean_stop_exception_types=[]) + if ops.get_collection(ops.GraphKeys.QUEUE_RUNNERS): + queue_runner.start_queue_runners(sess=self.tf_sess, coord=self.coord) + # Inform the hooks that a new session has been created. + for hook in self._hooks: + hook.after_create_session(self.tf_sess, self.coord) + return _CoordinatedSession( + _HookedSession(self.tf_sess, self._hooks), self.coord, + self._stop_grace_period_secs) + + def _close_internal(self, exception_type=None): + try: + if not exception_type: + for h in self._hooks: + h.end(self._coordinated_creator.tf_sess) + finally: + try: + if self._sess is None: + raise RuntimeError('Session is already closed.') + self._sess.close() + finally: + self._sess = None + self._coordinated_creator.tf_sess = None + self._coordinated_creator.coord = None + if not self._graph_was_finalized: + ops.get_default_graph()._unsafe_unfinalize() # pylint: disable=protected-access + + def _is_closed(self): + """Return True if the monitored session is closed. + + For tests only. + + Returns: + A boolean. + """ + return self._coordinated_creator.tf_sess is None + + def _tf_sess(self): + """Return underlying tf.compat.v1.Session object. + + Warning: accessing the returned object in user code is likely to cause races + or "flaky tests". + + Returns: + A tf.compat.v1.Session object. + """ + return self._coordinated_creator.tf_sess + + +@tf_export(v1=['train.MonitoredSession']) +class MonitoredSession(_MonitoredSession): + """Session-like object that handles initialization, recovery and hooks. + + Example usage: + + ```python + saver_hook = CheckpointSaverHook(...) + summary_hook = SummarySaverHook(...) + with MonitoredSession(session_creator=ChiefSessionCreator(...), + hooks=[saver_hook, summary_hook]) as sess: + while not sess.should_stop(): + sess.run(train_op) + ``` + + Initialization: At creation time the monitored session does following things + in given order: + + * calls `hook.begin()` for each given hook + * finalizes the graph via `scaffold.finalize()` + * create session + * initializes the model via initialization ops provided by `Scaffold` + * restores variables if a checkpoint exists + * launches queue runners + * calls `hook.after_create_session()` + + Run: When `run()` is called, the monitored session does following things: + + * calls `hook.before_run()` + * calls TensorFlow `session.run()` with merged fetches and feed_dict + * calls `hook.after_run()` + * returns result of `session.run()` asked by user + * if `AbortedError` or `UnavailableError` occurs, it recovers or + reinitializes the session before executing the run() call again + + + Exit: At the `close()`, the monitored session does following things in order: + + * calls `hook.end()` + * closes the queue runners and the session + * suppresses `OutOfRange` error which indicates that all inputs have been + processed if the monitored_session is used as a context + + How to set `tf.compat.v1.Session` arguments: + + * In most cases you can set session arguments as follows: + + ```python + MonitoredSession( + session_creator=ChiefSessionCreator(master=..., config=...)) + ``` + + * In distributed setting for a non-chief worker, you can use following: + + ```python + MonitoredSession( + session_creator=WorkerSessionCreator(master=..., config=...)) + ``` + + See `MonitoredTrainingSession` for an example usage based on chief or worker. + + Note: This is not a `tf.compat.v1.Session`. For example, it cannot do + following: + + * it cannot be set as default session. + * it cannot be sent to saver.save. + * it cannot be sent to tf.train.start_queue_runners. + + @compatibility(TF2) + This API is not compatible with eager execution and `tf.function`. To migrate + to TF2, rewrite the code to be compatible with eager execution. Check the + [migration + guide](https://www.tensorflow.org/guide/migrate#1_replace_v1sessionrun_calls) + on replacing `Session.run` calls. In Keras, session hooks can be replaced by + Callbacks e.g. [logging hook notebook]( + https://github.com/tensorflow/docs/blob/master/site/en/guide/migrate/logging_stop_hook.ipynb) + For more details please read [Better + performance with tf.function](https://www.tensorflow.org/guide/function). + @end_compatibility + + Args: + session_creator: A factory object to create session. Typically a + `ChiefSessionCreator` which is the default one. + hooks: An iterable of `SessionRunHook' objects. + + Returns: + A MonitoredSession object. + """ + + def __init__(self, + session_creator=None, + hooks=None, + stop_grace_period_secs=120): + super(MonitoredSession, self).__init__( + session_creator, + hooks, + should_recover=True, + stop_grace_period_secs=stop_grace_period_secs) + + +@tf_export(v1=['train.SingularMonitoredSession']) +class SingularMonitoredSession(_MonitoredSession): + """Session-like object that handles initialization, restoring, and hooks. + + Please note that this utility is not recommended for distributed settings. + For distributed settings, please use `tf.compat.v1.train.MonitoredSession`. + The + differences between `MonitoredSession` and `SingularMonitoredSession` are: + + * `MonitoredSession` handles `AbortedError` and `UnavailableError` for + distributed settings, but `SingularMonitoredSession` does not. + * `MonitoredSession` can be created in `chief` or `worker` modes. + `SingularMonitoredSession` is always created as `chief`. + * You can access the raw `tf.compat.v1.Session` object used by + `SingularMonitoredSession`, whereas in MonitoredSession the raw session is + private. This can be used: + - To `run` without hooks. + - To save and restore. + * All other functionality is identical. + + Example usage: + ```python + saver_hook = CheckpointSaverHook(...) + summary_hook = SummarySaverHook(...) + with SingularMonitoredSession(hooks=[saver_hook, summary_hook]) as sess: + while not sess.should_stop(): + sess.run(train_op) + ``` + + Initialization: At creation time the hooked session does following things + in given order: + + * calls `hook.begin()` for each given hook + * finalizes the graph via `scaffold.finalize()` + * create session + * initializes the model via initialization ops provided by `Scaffold` + * restores variables if a checkpoint exists + * launches queue runners + + Run: When `run()` is called, the hooked session does following things: + + * calls `hook.before_run()` + * calls TensorFlow `session.run()` with merged fetches and feed_dict + * calls `hook.after_run()` + * returns result of `session.run()` asked by user + + Exit: At the `close()`, the hooked session does following things in order: + + * calls `hook.end()` + * closes the queue runners and the session + * suppresses `OutOfRange` error which indicates that all inputs have been + processed if the `SingularMonitoredSession` is used as a context. + + @compatibility(TF2) + This API is not compatible with eager execution and `tf.function`. To migrate + to TF2, rewrite the code to be compatible with eager execution. Check the + [migration + guide](https://www.tensorflow.org/guide/migrate#1_replace_v1sessionrun_calls) + on replacing `Session.run` calls. In Keras, session hooks can be replaced by + Callbacks e.g. [logging hook notebook]( + https://github.com/tensorflow/docs/blob/master/site/en/guide/migrate/logging_stop_hook.ipynb) + For more details please read [Better + performance with tf.function](https://www.tensorflow.org/guide/function). + @end_compatibility + """ + + def __init__(self, + hooks=None, + scaffold=None, + master='', + config=None, + checkpoint_dir=None, + stop_grace_period_secs=120, + checkpoint_filename_with_path=None): + """Creates a SingularMonitoredSession. + + Args: + hooks: An iterable of `SessionRunHook' objects. + scaffold: A `Scaffold` used for gathering or building supportive ops. If + not specified a default one is created. It's used to finalize the graph. + master: `String` representation of the TensorFlow master to use. + config: `ConfigProto` proto used to configure the session. + checkpoint_dir: A string. Optional path to a directory where to restore + variables. + stop_grace_period_secs: Number of seconds given to threads to stop after + `close()` has been called. + checkpoint_filename_with_path: A string. Optional path to a checkpoint + file from which to restore variables. + """ + session_creator = ChiefSessionCreator( + scaffold=scaffold, + master=master, + config=config, + checkpoint_dir=checkpoint_dir, + checkpoint_filename_with_path=checkpoint_filename_with_path) + super(SingularMonitoredSession, self).__init__( + session_creator, + hooks, + should_recover=False, + stop_grace_period_secs=stop_grace_period_secs) + + def raw_session(self): + """Returns underlying `TensorFlow.Session` object.""" + return self._tf_sess() + + +class _WrappedSession: + """Wrapper around a `tf.compat.v1.Session`. + + This wrapper is used as a base class for various session wrappers + that provide additional functionality such as monitoring, coordination, + and recovery. + + In addition to the methods exported by `SessionInterface` the wrapper + provides a method to check for stop and never raises exceptions from + calls to `close()`. + """ + + def __init__(self, sess): + """Creates a `_WrappedSession`. + + Args: + sess: A `tf.compat.v1.Session` or `_WrappedSession` object. The wrapped + session. + """ + self._sess = sess + self._wrapped_is_stoppable = isinstance(self._sess, _WrappedSession) + + @property + def graph(self): + return self._sess.graph + + @property + def sess_str(self): + return self._sess.sess_str + + def should_stop(self): + """Return true if this session should not be used anymore. + + Always return True if the session was closed. + + Returns: + True if the session should stop, False otherwise. + """ + if self._check_stop(): + return True + if self._sess: + return self._wrapped_is_stoppable and self._sess.should_stop() + return True + + def _check_stop(self): + """Hook for subclasses to provide their own stop condition. + + Returns: + True if the session should stop, False otherwise. + """ + return False + + def close(self): + if self._sess: + try: + self._sess.close() + except _PREEMPTION_ERRORS as e: + logging.error( + 'An error occurred when attempting to close the ' + 'session. This may be due to a preemption in a ' + 'connected worker or parameter server. Error: %s', e) + finally: + self._sess = None + + def run(self, *args, **kwargs): + return self._sess.run(*args, **kwargs) + + def run_step_fn(self, step_fn, raw_session, run_with_hooks): + # `_RecoverableSession` sets `run_with_hooks` to `_CoordinatedSession.run`. + # It is `None` when called from `_CoordinatedSession`. In that case + # `self.run` is `_CoordinatedSession.run`. + run_with_hooks = run_with_hooks or self.run + return step_fn(_MonitoredSession.StepContext(raw_session, run_with_hooks)) + + +class _RecoverableSession(_WrappedSession): + """A wrapped session that recreates a session upon certain kinds of errors. + + The constructor is passed a SessionCreator object, not a session. + + Calls to `run()` are delegated to the wrapped session. If a call raises the + exception `tf.errors.AbortedError` or `tf.errors.UnavailableError`, the + wrapped session is closed, and a new one is created by calling the factory + again. + """ + + def __init__(self, sess_creator): + """Create a new `_RecoverableSession`. + + The value returned by calling `sess_creator.create_session()` will be the + session wrapped by this recoverable session. + + Args: + sess_creator: A 'SessionCreator' to be wrapped by recoverable. + """ + self._sess_creator = sess_creator + _WrappedSession.__init__(self, self._create_session()) + + def _create_session(self): + while True: + try: + return self._sess_creator.create_session() + except _PREEMPTION_ERRORS as e: + logging.info( + 'An error was raised while a session was being created. ' + 'This may be due to a preemption of a connected worker ' + 'or parameter server. A new session will be created. ' + 'This error may also occur due to a gRPC failure caused ' + 'by high memory or network bandwidth usage in the ' + 'parameter servers. If this error occurs repeatedly, try ' + 'increasing the number of parameter servers assigned to ' + 'the job. Error: %s', e) + + def _check_stop(self): + try: + if self._sess: + return self._sess._check_stop() # pylint: disable=protected-access + else: + return True + except _PREEMPTION_ERRORS as e: + logging.info( + 'An error was raised while considering whether the ' + 'session is complete. This may be due to a preemption in ' + 'a connected worker or parameter server. The current ' + 'session will be closed and a new session will be ' + 'created. This error may also occur due to a gRPC failure ' + 'caused by high memory or network bandwidth usage in the ' + 'parameter servers. If this error occurs repeatedly, try ' + 'increasing the number of parameter servers assigned to ' + 'the job. Error: %s', e) + self.close() + self._sess = self._create_session() + # Since we have just recreated the session, the overall computation should + # not stop: + return False + except Exception: # pylint: disable=broad-except + # `should_stop` should return True instead of raising an exception. + return True + + def run(self, fetches, feed_dict=None, options=None, run_metadata=None): + while True: + try: + if not self._sess: + self._sess = self._create_session() + return self._sess.run( + fetches, + feed_dict=feed_dict, + options=options, + run_metadata=run_metadata) + except _PREEMPTION_ERRORS as e: + logging.info( + 'An error was raised. This may be due to a preemption in ' + 'a connected worker or parameter server. The current ' + 'session will be closed and a new session will be ' + 'created. This error may also occur due to a gRPC failure ' + 'caused by high memory or network bandwidth usage in the ' + 'parameter servers. If this error occurs repeatedly, try ' + 'increasing the number of parameter servers assigned to ' + 'the job. Error: %s', e) + self.close() + self._sess = None + + def run_step_fn(self, step_fn, raw_session, run_with_hooks): + while True: + try: + if not self._sess: + self._sess = self._create_session() + + run_with_hooks = self._sess.run + return self._sess.run_step_fn(step_fn, raw_session, run_with_hooks) + except _PREEMPTION_ERRORS as e: + logging.info( + 'An error was raised. This may be due to a preemption in ' + 'a connected worker or parameter server. The current ' + 'session will be closed and a new session will be ' + 'created. This error may also occur due to a gRPC failure ' + 'caused by high memory or network bandwidth usage in the ' + 'parameter servers. If this error occurs repeatedly, try ' + 'increasing the number of parameter servers assigned to ' + 'the job. Error: %s', e) + self.close() + self._sess = None + + +class _CoordinatedSession(_WrappedSession): + """A wrapped session that works with a `tf.Coordinator`. + + Calls to `run()` are delegated to the wrapped session. If a call + raises an exception, the exception is reported to the coordinator. + + In addition, after each call to `run()` this session ask the coordinator if + the session should stop. In that case it will join all the threads + registered with the coordinator before returning. + + If the coordinator was requested to stop with an exception, that exception + will be re-raised from the call to `run()`. + """ + + def __init__(self, sess, coord, stop_grace_period_secs=120): + """Create a new `_CoordinatedSession`. + + Args: + sess: A `tf.compat.v1.Session` object. The wrapped session. + coord: A `tf.train.Coordinator` object. + stop_grace_period_secs: Number of seconds given to threads to stop after + `close()` has been called. + """ + _WrappedSession.__init__(self, sess) + self._coord = coord + self._stop_grace_period_secs = stop_grace_period_secs + + def _check_stop(self): + # If the coordinator was asked to stop due to an exception, then it needs + # to be propagated to this stack. + self._coord.raise_requested_exception() + # At this point, no exceptions are recorded in the coordinator. + return self._coord.should_stop() + + def close(self): + self._coord.request_stop() + try: + self._coord.join( + stop_grace_period_secs=self._stop_grace_period_secs, + ignore_live_threads=True) + finally: + try: + _WrappedSession.close(self) + except Exception: # pylint: disable=broad-except + # We intentionally suppress exceptions from the close() here since + # useful exceptions are already reported by join(). + pass + + def run(self, *args, **kwargs): + try: + return self._sess.run(*args, **kwargs) + except _PREEMPTION_ERRORS: + raise + except Exception as original_exception: # pylint: disable=broad-except + # A non-preemption error could have been caused by a preemption error + # in the coordinator. If this is the case, raise that exception instead, + # since it's the root cause. Otherwise, stick to the `original_exception`. + try: + self._coord.raise_requested_exception() + except _PREEMPTION_ERRORS: + raise + except Exception: # pylint: disable=broad-except + raise original_exception from None + else: + raise + + +class _HookedSession(_WrappedSession): + """A _WrappedSession that calls hooks during calls to run(). + + The list of hooks to call is passed in the constructor. Before each call + to `run()` the session calls the `before_run()` method of the hooks, which + can return additional ops or tensors to run. These are added to the arguments + of the call to `run()`. + + When the `run()` call finishes, the session calls the `after_run()` methods of + the hooks, passing the values returned by the `run()` call corresponding to + the ops and tensors that each hook requested. + + If any call to the hooks, requests stop via run_context the session will be + marked as needing to stop and its `should_stop()` method will now return + `True`. + """ + + def __init__(self, sess, hooks): + """Initializes a _HookedSession object. + + Args: + sess: A `tf.compat.v1.Session` or a `_WrappedSession` object. + hooks: An iterable of `SessionRunHook' objects. + """ + + _WrappedSession.__init__(self, sess) + self._hooks = hooks + self._should_stop = False + + def _check_stop(self): + """See base class.""" + return self._should_stop + + def run(self, fetches, feed_dict=None, options=None, run_metadata=None): + """See base class.""" + if self.should_stop(): + raise RuntimeError('Run called even after should_stop requested.') + + actual_fetches = {'caller': fetches} + + run_context = session_run_hook.SessionRunContext( + original_args=session_run_hook.SessionRunArgs(fetches, feed_dict), + session=self._sess) + + options = options or config_pb2.RunOptions() + feed_dict = self._call_hook_before_run(run_context, actual_fetches, + feed_dict, options) + + # Do session run. + run_metadata = run_metadata or config_pb2.RunMetadata() + outputs = _WrappedSession.run( + self, + fetches=actual_fetches, + feed_dict=feed_dict, + options=options, + run_metadata=run_metadata) + + for hook in self._hooks: + hook.after_run( + run_context, + session_run_hook.SessionRunValues( + results=outputs[hook] if hook in outputs else None, + options=options, + run_metadata=run_metadata)) + self._should_stop = self._should_stop or run_context.stop_requested + + return outputs['caller'] + + def _call_hook_before_run(self, run_context, fetch_dict, user_feed_dict, + options): + """Calls hooks.before_run and handles requests from hooks.""" + hook_feeds = {} + for hook in self._hooks: + request = hook.before_run(run_context) + if request is not None: + if request.fetches is not None: + fetch_dict[hook] = request.fetches + if request.feed_dict: + self._raise_if_feeds_intersects(hook_feeds, request.feed_dict, + 'Same tensor is fed by two hooks.') + hook_feeds.update(request.feed_dict) + if request.options: + self._merge_run_options(options, request.options) + + if not hook_feeds: + return user_feed_dict + + if not user_feed_dict: + return hook_feeds + + self._raise_if_feeds_intersects( + user_feed_dict, hook_feeds, + 'Same tensor is fed by a SessionRunHook and user.') + hook_feeds.update(user_feed_dict) + return hook_feeds + + def _raise_if_feeds_intersects(self, feeds1, feeds2, message): + intersection = set(feeds1.keys()) & set(feeds2.keys()) + if intersection: + raise RuntimeError(message + ' Conflict(s): ' + str(list(intersection))) + + def _merge_run_options(self, options, incoming_options): + """Merge two instances of RunOptions into the first one. + + During the merger, the numerical fields including trace_level, + timeout_in_ms, inter_op_thread_pool are set to the larger one of the two. + The boolean value is set to the logical OR of the two. + debug_tensor_watch_opts of the original options is extended with that from + the incoming one. + + Args: + options: The options to merge into. + incoming_options: The options to be merged into the first argument. + """ + options.trace_level = max(options.trace_level, incoming_options.trace_level) + options.timeout_in_ms = max(options.timeout_in_ms, + incoming_options.timeout_in_ms) + options.inter_op_thread_pool = max(options.inter_op_thread_pool, + incoming_options.inter_op_thread_pool) + options.output_partition_graphs = max( + options.output_partition_graphs, + incoming_options.output_partition_graphs) + options.debug_options.debug_tensor_watch_opts.extend( + incoming_options.debug_options.debug_tensor_watch_opts) + options.debug_options.reset_disk_byte_usage = ( + options.debug_options.reset_disk_byte_usage or + incoming_options.debug_options.reset_disk_byte_usage) + options.report_tensor_allocations_upon_oom = ( + options.report_tensor_allocations_upon_oom or + incoming_options.report_tensor_allocations_upon_oom) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/moving_averages.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/moving_averages.py new file mode 100644 index 0000000000000000000000000000000000000000..d310f3488f152458054aa1bd7ef9666a0de14119 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/moving_averages.py @@ -0,0 +1,689 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Maintain moving averages of parameters.""" +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.distribute import reduce_util as ds_reduce_util +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor +from tensorflow.python.ops import cond +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import init_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import state_ops +from tensorflow.python.ops import variable_scope +from tensorflow.python.ops import variable_v1 +from tensorflow.python.ops import variables +from tensorflow.python.training import slot_creator +from tensorflow.python.util.tf_export import tf_export +from tensorflow.tools.docs import doc_controls + + +@tf_export("__internal__.train.assign_moving_average", v1=[]) +def assign_moving_average(variable, value, decay, zero_debias=True, name=None): + """Compute the moving average of a variable. + + The moving average of 'variable' updated with 'value' is: + variable * decay + value * (1 - decay) + + The returned Operation sets 'variable' to the newly computed moving average, + by performing this subtraction: + variable -= (1 - decay) * (variable - value) + + Since variables that are initialized to a `0` value will be `0` biased, + `zero_debias` optionally enables scaling by the mathematically correct + debiasing factor of + 1 - decay ** num_updates + See Section 3 of (Kingma et al., 2015) for more details. + + The names of the debias shadow variables, by default, include both the scope + they were created in and the scope of the variables they debias. They are also + given a uniquifying-suffix. + + E.g.: + + ``` + with tf.compat.v1.variable_scope('scope1'): + with tf.compat.v1.variable_scope('scope2'): + var = tf.compat.v1.get_variable('foo') + update_1 = tf.assign_moving_average(var, 0.0, 1.0) + update_2 = tf.assign_moving_average(var, 0.0, 0.9) + + # var.name: 'scope1/scope2/foo' + # shadow var names: 'scope1/scope2/scope1/scope2/foo/biased' + # 'scope1/scope2/scope1/scope2/foo/biased_1' + ``` + + Args: + variable: A Variable. + value: A tensor with the same shape as 'variable'. + decay: A float `Tensor` or float value. The moving average decay. + zero_debias: A python bool. If true, assume the variable is 0-initialized + and unbias it, as in (Kingma et al., 2015). See docstring in + `_zero_debias` for more details. + name: Optional name of the returned operation. + + Returns: + A tensor which if evaluated will compute and return the new moving average. + + References: + Adam - A Method for Stochastic Optimization: + [Kingma et al., 2015](https://arxiv.org/abs/1412.6980) + ([pdf](https://arxiv.org/pdf/1412.6980.pdf)) + """ + with ops.name_scope(name, "AssignMovingAvg", + [variable, value, decay]) as scope: + decay = ops.convert_to_tensor(1.0 - decay, name="decay") + if decay.dtype != variable.dtype.base_dtype: + decay = math_ops.cast(decay, variable.dtype.base_dtype) + + def update_fn(v, value): + return state_ops.assign_sub(v, (v - value) * decay, name=scope) + + def update(strategy, v, value): + if zero_debias: + return _zero_debias(strategy, v, value, decay) + else: + return _update(strategy, v, update_fn, args=(value,)) + + replica_context = distribute_lib.get_replica_context() + if replica_context: + # In a replica context, we update variable using the mean of value across + # replicas. + def merge_fn(strategy, v, value): + value = strategy.extended.reduce_to(ds_reduce_util.ReduceOp.MEAN, value, + v) + return update(strategy, v, value) + + return replica_context.merge_call(merge_fn, args=(variable, value)) + else: + strategy = distribute_lib.get_cross_replica_context() + return update(strategy, variable, value) + + +def weighted_moving_average(value, + decay, + weight, + truediv=True, + collections=None, + name=None): + """Compute the weighted moving average of `value`. + + Conceptually, the weighted moving average is: + `moving_average(value * weight) / moving_average(weight)`, + where a moving average updates by the rule + `new_value = decay * old_value + (1 - decay) * update` + Internally, this Op keeps moving average variables of both `value * weight` + and `weight`. + + Args: + value: A numeric `Tensor`. + decay: A float `Tensor` or float value. The moving average decay. + weight: `Tensor` that keeps the current value of a weight. Shape should be + able to multiply `value`. + truediv: Boolean, if `True`, dividing by `moving_average(weight)` is + floating point division. If `False`, use division implied by dtypes. + collections: List of graph collections keys to add the internal variables + `value * weight` and `weight` to. Defaults to + `[GraphKeys.GLOBAL_VARIABLES]`. + name: Optional name of the returned operation. Defaults to + "WeightedMovingAvg". + + Returns: + An Operation that updates and returns the weighted moving average. + """ + # Unlike assign_moving_average, the weighted moving average doesn't modify + # user-visible variables. It is the ratio of two internal variables, which are + # moving averages of the updates. Thus, the signature of this function is + # quite different than assign_moving_average. + if collections is None: + collections = [ops.GraphKeys.GLOBAL_VARIABLES] + with variable_scope.variable_scope(name, "WeightedMovingAvg", + [value, weight, decay]) as scope: + value_x_weight_var = variable_scope.get_variable( + "value_x_weight", + shape=value.get_shape(), + dtype=value.dtype, + initializer=init_ops.zeros_initializer(), + trainable=False, + collections=collections) + weight_var = variable_scope.get_variable( + "weight", + shape=weight.get_shape(), + dtype=weight.dtype, + initializer=init_ops.zeros_initializer(), + trainable=False, + collections=collections) + numerator = assign_moving_average( + value_x_weight_var, value * weight, decay, zero_debias=False) + denominator = assign_moving_average( + weight_var, weight, decay, zero_debias=False) + + if truediv: + return math_ops.truediv(numerator, denominator, name=scope.name) + else: + return math_ops.divide(numerator, denominator, name=scope.name) + + +def _update(strategy, var, update_fn, args): + """Applies updates depending on the context.""" + assert distribute_lib.in_cross_replica_context(), ( + "_update can only be called in cross-replica context") + if distribute_lib.get_update_replica_id() is not None: + # Call update_fn on var to delegate the implementation. We expect `var` will + # do the right thing in update context, e.g, if `var` is a MirroredVariable, + # it should pick its component variable based on `update_replica_id` and + # only update that. + return update_fn(var, *args) + else: + return strategy.extended.update(var, update_fn, args) + + +def _zero_debias(strategy, unbiased_var, value, decay): + """Compute the delta required for a debiased Variable. + + All exponential moving averages initialized with Tensors are initialized to 0, + and therefore are biased to 0. Variables initialized to 0 and used as EMAs are + similarly biased. This function creates the debias updated amount according to + a scale factor, as in (Kingma et al., 2015). + + To demonstrate the bias the results from 0-initialization, take an EMA that + was initialized to `0` with decay `b`. After `t` timesteps of seeing the + constant `c`, the variable have the following value: + + ``` + EMA = 0*b^(t) + c*(1 - b)*b^(t-1) + c*(1 - b)*b^(t-2) + ... + = c*(1 - b^t) + ``` + + To have the true value `c`, we would divide by the scale factor `1 - b^t`. + + In order to perform debiasing, we use two shadow variables. One keeps track of + the biased estimate, and the other keeps track of the number of updates that + have occurred. + + Args: + strategy: `Strategy` used to create and update variables. + unbiased_var: A Variable representing the current value of the unbiased EMA. + value: A Tensor representing the most recent value. + decay: A Tensor representing `1-decay` for the EMA. + + Returns: + The amount that the unbiased variable should be updated. Computing this + tensor will also update the shadow variables appropriately. + + References: + Adam - A Method for Stochastic Optimization: + [Kingma et al., 2015](https://arxiv.org/abs/1412.6980) + ([pdf](https://arxiv.org/pdf/1412.6980.pdf)) + + """ + with variable_scope.variable_scope( + unbiased_var.name[:-len(":0")], values=[unbiased_var, value, decay]): + with ops.init_scope(): + biased_initializer = init_ops.zeros_initializer() + local_step_initializer = init_ops.zeros_initializer() + + def _maybe_get_unique(name): + """Get name for a unique variable, if not `reuse=True`.""" + if variable_scope.get_variable_scope().reuse: + return name + vs_vars = [ + x.op.name + for x in variable_scope.get_variable_scope().global_variables() + ] + full_name = variable_scope.get_variable_scope().name + "/" + name + if full_name not in vs_vars: + return name + idx = 1 + while full_name + ("_%d" % idx) in vs_vars: + idx += 1 + return name + ("_%d" % idx) + + with strategy.extended.colocate_vars_with(unbiased_var): + biased_var = variable_scope.get_variable( + _maybe_get_unique("biased"), + initializer=biased_initializer, + shape=unbiased_var.get_shape(), + dtype=unbiased_var.dtype, + trainable=False) + local_step = variable_scope.get_variable( + _maybe_get_unique("local_step"), + shape=[], + dtype=unbiased_var.dtype, + initializer=local_step_initializer, + trainable=False) + + def update_fn(v, value, biased_var, local_step): + update_biased = state_ops.assign_sub(biased_var, + (biased_var - value) * decay) + update_local_step = local_step.assign_add(1) + + # This function gets `1 - decay`, so use `1.0 - decay` in the exponent. + bias_factor = 1 - math_ops.pow(1.0 - decay, update_local_step) + return state_ops.assign( + v, update_biased / bias_factor, name=ops.get_name_scope() + "/") + + return _update( + strategy, unbiased_var, update_fn, args=(value, biased_var, local_step)) + + +@tf_export("train.ExponentialMovingAverage") +class ExponentialMovingAverage: + """Maintains moving averages of variables by employing an exponential decay. + + When training a model, it is often beneficial to maintain moving averages of + the trained parameters. Evaluations that use averaged parameters sometimes + produce significantly better results than the final trained values. + + The `apply()` method adds shadow copies of trained variables the first time + it is called, and maintains a moving average of the trained variables in + their shadow copies at every additional invocation. + It should generally be called immediately after creating the model weights, + and then after each training step. + + The `average()` method gives access to the shadow variables. + It allows you to use the moving averages in place of the last trained values + for evaluations, by loading the moving averages into your model via + `var.assign(ema.average(var))`. + Additionally, although `ExponentialMovingAverage` + objects are not directly trackable by checkpoints, + `average()` returns the moving average variables for your model weights, + which you can then checkpoint. (There is an example + of this near the bottom of this docstring). + So, `average()` is useful when + building an evaluation model, or when restoring a model from a checkpoint + file. + + The moving averages are computed using exponential decay. You specify the + decay value (as a scalar float value, `Tensor`, or `Variable`) when creating + the `ExponentialMovingAverage` object. The shadow variables are initialized + with the same initial values as the trained variables. When you run `apply` + to update the moving averages, each shadow variable is updated with the + formula: + + `shadow_variable -= (1 - decay) * (shadow_variable - variable)` + + This is mathematically equivalent to the classic formula below, but the use + of an `assign_sub` op (the `"-="` in the formula) allows concurrent lockless + updates to the variables: + + `shadow_variable = decay * shadow_variable + (1 - decay) * variable` + + Reasonable values for `decay` are close to 1.0, typically in the + multiple-nines range: 0.999, 0.9999, etc. + + To have fine-grained control over the value of the decay parameter during + training, pass a scalar `tf.Variable` as the `decay` value to the constructor, + and update the variable as needed. + + Example usage when creating a training model: + + ```python + # Create variables. + var0 = tf.Variable(...) + var1 = tf.Variable(...) + # ... use the variables to build a training model... + + # Create an ExponentialMovingAverage object + ema = tf.train.ExponentialMovingAverage(decay=0.9999) + + # The first `apply` creates the shadow variables that hold the moving averages + ema.apply([var0, var1]) + + # grab the moving averages for checkpointing purposes or to be able to + # load the moving averages into the model weights + averages = [ema.average(var0), ema.average(var1)] + + ... + def train_step(...): + ... + # Apply the optimizer. + opt.minimize(my_loss, [var0, var1]) + + # Update the moving averages + # of var0 and var1 with additional calls to `apply` + ema.apply([var0, var1]) + + ...train the model by running train_step multiple times... + ``` + + There are several ways to use the moving averages for evaluations: + + 1. Assign the values of the shadow variables to your model variables with + `Variable.assign(...)` before evaluating your + model. You can use the `average()` + method to get the shadow variable for a given variable. To continue + training after using this approach, make sure to record the unaveraged + weights and restore them before continuing to train. You can see the + tensorflow-addons' MovingAverage optimizer's `swap_weights` method for + one example of how to swap variables efficiently in distributed settings: + https://github.com/tensorflow/addons/blob/v0.13.0/tensorflow_addons/optimizers/moving_average.py#L151 + 2. Make sure to checkpoint out your moving average variables in your + `tf.train.Checkpoint`. At evaluation time, create your shadow variables and + use `tf.train.Checkpoint` to restore the moving averages into the shadow + variables. Then, load the moving averages into the actual model weights via + `var.assign(moving_avg)`. + 3. Checkpoint out your moving average variables in your `tf.train.Checkpoint`. + For evaluation, restore your model weights directly from the moving + averages instead of from the non-averaged weights. + Caution: If you choose this approach, include only the object-graph paths + to the averaged path in your checkpoint restore. + If you point both the unaveraged and averaged paths in a checkpoint + restore to the same variables, it is hard to reason about whether your + model will restore the averaged or non-averaged variables. + + Example of saving out then restoring the shadow variable values: + + ```python + # Create variables. + var0 = tf.Variable(...) + var1 = tf.Variable(...) + # ... use the variables to build a training model... + + # Create an ExponentialMovingAverage object, create the shadow variables, + # and grab the moving averages for checkpointing purposes. + # (The ExponentialMovingAverage object itself is not checkpointable) + ema = tf.train.ExponentialMovingAverage(decay=0.9999) + ema.apply([var0, var1]) + avg_var0 = ema.average(var0) + avg_var1 = ema.average(var1) + + # Create a Checkpoint that will manage the model weights and the averages, + checkpoint = tf.train.Checkpoint(model_weights=[var0, var1], + averaged_weights=[avg_var0, avg_var1]) + ... # Do training + + # Save out the checkpoint including the model weights and the moving averages + checkpoint.save(...) + ``` + + Restore option: restore all averaged & non-averaged weights, then load + moving averages into the model via `var.assign()` + ```python + # Create variables. + var0 = tf.Variable(...) + var1 = tf.Variable(...) + # ... use the variables to build a training model... + + # Create an ExponentialMovingAverage object, create the shadow variables, + # and grab the moving averages for checkpoint restore purposes. + # (The ExponentialMovingAverage object itself is not checkpointable) + ema = tf.train.ExponentialMovingAverage(decay=0.9999) + ema.apply([var0, var1]) + avg_var0 = ema.average(var0) + avg_var1 = ema.average(var1) + + # Create a Checkpoint that will manage the model weights and the averages, + checkpoint = tf.train.Checkpoint(model_weights=[var0, var1], + averaged_weights=[avg_var0, avg_var1]) + checkpoint.restore(...) + var0.assign(avg_var0) + var1.assign(avg_var1) + # var0 and var1 now hold the moving average values + ``` + + Restore option: Directly restore the moving averages into the model weights. + ```python + # Create variables. + var0 = tf.Variable(...) + var1 = tf.Variable(...) + # ... use the variables to build a training model... + + # Create a Checkpoint that will manage two objects with trackable state, + checkpoint = tf.train.Checkpoint(averaged_weights=[var0, var1]) + checkpoint.restore(...) + # var0 and var1 now hold the moving average values + ``` + """ + + def __init__(self, + decay, + num_updates=None, + zero_debias=False, + name="ExponentialMovingAverage"): + """Creates a new ExponentialMovingAverage object. + + The `apply()` method has to be called to create shadow variables. + Follow-on calls to the `apply()` method will update the moving averages + in the shadow variables. + (In TF 1.x graphs `apply()` will return an update op to update + the moving averages which must be explicitly run). + + The optional `num_updates` parameter allows one to tweak the decay rate + dynamically. It is typical to pass the count of training steps, usually + kept in a variable that is incremented at each step, in which case the + decay rate is lower at the start of training. This makes moving averages + move faster. If passed, the actual decay rate used is: + + `min(decay, (1 + num_updates) / (10 + num_updates))` + + Args: + decay: A scalar float value, `Tensor`, or `Variable`. The decay parameter. + num_updates: Optional count of number of updates applied to variables. + zero_debias: If `True`, zero debias moving-averages that are initialized + with tensors. (Note: moving averages may not be initialized with + non-variable tensors when eager execution is enabled). + name: String. Optional prefix name to use for the name of ops added in + `apply()`. + """ + self._decay = decay + self._num_updates = num_updates + self._zero_debias = zero_debias + self._name = name + self._averages = {} + + @property + def name(self): + """The name of this ExponentialMovingAverage object.""" + return self._name + + def apply(self, var_list=None): + """Maintains moving averages of variables. + + `var_list` must be a list of `Variable` objects. This method + creates shadow variables (holding the moving averages) + for all elements of `var_list`, and + updates the moving averages using the current `var_list` values. Shadow + variables for `Variable` objects are initialized to the variable's initial + value. + + Shadow variables are created with `trainable=False`. To access them you + can use the EMA object's `average` method. Note that `EMA` objects are + not trackable by checkpoints, so if you want to checkpoint or restore the + moving variables you will need to manually grab the shadow + variables via `average()` and assign them as `tf.Module` properties or + directly pass them to your `tf.train.Checkpoint`. + + Note that `apply()` can be called multiple times. When eager execution is + enabled each call to apply will update the variables once, so this needs to + be called in a loop. + + In legacy TF 1.x graphs, this method returns an op that updates all + shadow variables from the current value of their associated variables. In + TF 1.x graphs without automatically control dependencies this op needs to be + manually run. + + Args: + var_list: A list of Variable objects. The variables + must be of types bfloat16, float16, float32, or float64. + (In legacy TF 1.x graphs these may be tensors, but this is unsupported + when eager execution is enabled.) + + Returns: + An Operation that updates the moving averages. + + Raises: + TypeError: If the arguments are not an allowed type. + """ + # TODO(touts): op_scope + if var_list is None: + var_list = variables.trainable_variables() + for v in var_list: + if (isinstance(v, tensor.Tensor) + and ops.executing_eagerly_outside_functions()): + raise TypeError( + "tf.train.ExponentialMovingAverage does not support non-Variable" + " tensors when eager execution is enabled.") + zero_debias_true = set() # set of vars to set `zero_debias=True` + for var in var_list: + if var.dtype.base_dtype not in [ + dtypes.bfloat16, dtypes.float16, dtypes.float32, dtypes.float64 + ]: + raise TypeError("The variables must be half, float, or double: %s" % + var.name) + + if var.ref() not in self._averages: + # For variables: to lower communication bandwidth across devices we keep + # the moving averages on the same device as the variables. For other + # tensors, we rely on the existing device allocation mechanism. + with ops.init_scope(): + if isinstance(var, variables.Variable): + with ops.device(var.device): + initialized_value = cond.cond( + variable_v1.is_variable_initialized(var), var.read_value, + lambda: var.initial_value) # pylint: disable=cell-var-from-loop + avg = slot_creator.create_slot( + var, + initialized_value, + self.name, + colocate_with_primary=True, + copy_xla_sharding=True) + # NOTE(mrry): We only add `tf.Variable` objects to the + # `MOVING_AVERAGE_VARIABLES` collection. + ops.add_to_collection(ops.GraphKeys.MOVING_AVERAGE_VARIABLES, var) + else: + avg = slot_creator.create_zeros_slot( + var, + self.name, + colocate_with_primary=(var.op.type in [ + "Variable", "VariableV2", "VarHandleOp" + ]), + copy_xla_sharding=True) + if self._zero_debias: + zero_debias_true.add(avg.ref()) + self._averages[var.ref()] = avg + + with ops.name_scope(self.name) as scope: + decay = ops.convert_to_tensor( + self._decay, dtype=dtypes.float32, name="decay") + if self._num_updates is not None: + num_updates = math_ops.cast( + self._num_updates, dtypes.float32, name="num_updates") + decay = math_ops.minimum(decay, + (1.0 + num_updates) / (10.0 + num_updates)) + updates = [] + for var in var_list: + avg = self._averages[var.ref()] + zero_debias = avg.ref() in zero_debias_true + updates.append(assign_moving_average(avg, var, decay, zero_debias)) + return control_flow_ops.group(*updates, name=scope) + + def average(self, var): + """Returns the `Variable` holding the average of `var`. + + Args: + var: A `Variable` object. + + Returns: + A `Variable` object or `None` if the moving average of `var` + is not maintained. + """ + return self._averages.get(var.ref(), None) + + @doc_controls.do_not_generate_docs + def average_name(self, var): + """[Meant for TF1] Returns name of `Variable` holding the average for `var`. + + (Designed to work with legacy `tf.compat.v1.train.Saver`, it is sensitive to + specific variable names and not recommended for TF2) + + The typical scenario for `ExponentialMovingAverage` is to compute moving + averages of variables during training, and restore the variables from the + computed moving averages during evaluations. + + To restore variables, you have to know the name of the shadow variables. + That name and the original variable can then be passed to a `Saver()` object + to restore the variable from the moving average value with: + `saver = tf.compat.v1.train.Saver({ema.average_name(var): var})` + + `average_name()` can be called whether or not `apply()` has been called. + + Args: + var: A `Variable` object. + + Returns: + A string: The name of the variable that will be used or was used + by the `ExponentialMovingAverage class` to hold the moving average of + `var`. + """ + if var.ref() in self._averages: + return self._averages[var.ref()].name[:-len(":0")] + return ops.get_default_graph().unique_name( + var.name[:-len(":0")] + "/" + self.name, mark_as_used=False) + + @doc_controls.do_not_generate_docs + def variables_to_restore(self, moving_avg_variables=None): + """[Designed for TF 1.x] Returns a map of names to `Variables` to restore. + + (Designed to work with legacy `tf.compat.v1.train.Saver`, sensitive to + specific variable names and not recommended for TF2) + + If a variable has a moving average, use the moving average variable name as + the restore name; otherwise, use the variable name. + + For example, + + ```python + variables_to_restore = ema.variables_to_restore() + saver = tf.compat.v1.train.Saver(variables_to_restore) + ``` + + Below is an example of such mapping: + + ``` + conv/batchnorm/gamma/ExponentialMovingAverage: conv/batchnorm/gamma, + conv_4/conv2d_params/ExponentialMovingAverage: conv_4/conv2d_params, + global_step: global_step + ``` + + Args: + moving_avg_variables: a list of variables that require to use of the + moving average variable name to be restored. If None, it will default to + variables.moving_average_variables() + variables.trainable_variables() + + Returns: + A map from restore_names to variables. The restore_name is either the + original or the moving average version of the variable name, depending + on whether the variable name is in the `moving_avg_variables`. + """ + name_map = {} + if moving_avg_variables is None: + # Include trainable variables and variables which have been explicitly + # added to the moving_average_variables collection. + moving_avg_variables = variables.trainable_variables() + moving_avg_variables += variables.moving_average_variables() + # Remove duplicates + moving_avg_variables = set(v.ref() for v in moving_avg_variables) + # Collect all the variables with moving average, + for v in moving_avg_variables: + name_map[self.average_name(v.deref())] = v.deref() + # Make sure we restore variables without moving averages as well. + moving_avg_variable_names = set( + v.deref().name for v in moving_avg_variables) + for v in list(set(variables.global_variables())): + if v.name not in moving_avg_variable_names and v.op.name not in name_map: + name_map[v.op.name] = v + return name_map diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/optimizer.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..aa59f2e343cdf8f5d1207df3813219038d6bcfed --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/optimizer.py @@ -0,0 +1,1356 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""Base class for optimizers.""" +# pylint: disable=g-bad-name + +import abc + +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.distribute import distribute_utils +from tensorflow.python.distribute import reduce_util as ds_reduce_util +from tensorflow.python.eager import backprop +from tensorflow.python.eager import context +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import indexed_slices +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import gradients +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.ops import state_ops +from tensorflow.python.ops import variable_v1 +from tensorflow.python.ops import variables +from tensorflow.python.trackable import base as trackable +from tensorflow.python.training import slot_creator +from tensorflow.python.util import nest +from tensorflow.python.util.tf_export import tf_export + + +def get_filtered_grad_fn(grad_fn): + # `distributed_context.join()` requires that its arguments are parallel + # across threads, and in particular that `grads_and_vars` has the same + # variables in the same order. + + # When computing gradients in eager mode with multiple threads, you + # can get extra variables with a gradient of `None`. This happens when + # those variables are accessed in another thread during the gradient + # computation. To get a consistent set of variables, we filter out + # those with `None` gradients. + def filtered_grad_fn(*args, **kwargs): + return [(g, v) for g, v in grad_fn(*args, **kwargs) if g is not None] + + return filtered_grad_fn + + +def _deduplicate_indexed_slices(values, indices): + """Sums `values` associated with any non-unique `indices`. + + Args: + values: A `Tensor` with rank >= 1. + indices: A one-dimensional integer `Tensor`, indexing into the first + dimension of `values` (as in an IndexedSlices object). + Returns: + A tuple of (`summed_values`, `unique_indices`) where `unique_indices` is a + de-duplicated version of `indices` and `summed_values` contains the sum of + `values` slices associated with each unique index. + """ + unique_indices, new_index_positions = array_ops.unique(indices) + summed_values = math_ops.unsorted_segment_sum( + values, new_index_positions, + array_ops.shape(unique_indices)[0]) + return (summed_values, unique_indices) + + +def _var_key(var): + """Returns slot key for `var`.""" + # pylint: disable=protected-access + var = distribute_utils.value_container(var) + if (distribute_utils.is_distributed_variable(var) and + not ops.executing_eagerly_outside_functions()): + return (var.graph, var._shared_name) + if hasattr(var, "op"): + return (var.op.graph, var.op.name) + return var._unique_id + # pylint: enable=protected-access + + +class _OptimizableVariable(metaclass=abc.ABCMeta): + """Interface for abstracting over variables in the optimizers.""" + + @abc.abstractmethod + def target(self): + """Returns the optimization target for this variable.""" + raise NotImplementedError("Calling an abstract method.") + + @abc.abstractmethod + def update_op(self, optimizer, g): + """Returns the update ops for updating the variable.""" + raise NotImplementedError("Calling an abstract method.") + + +class _RefVariableProcessor(_OptimizableVariable): + """Processor for Variable.""" + + def __init__(self, v): + self._v = v + + def __str__(self): + return "<_RefVariableProcessor(%s)>" % self._v + + def target(self): + return self._v._ref() # pylint: disable=protected-access + + def update_op(self, optimizer, g): + if isinstance(g, tensor.Tensor): + update_op = optimizer._apply_dense(g, self._v) # pylint: disable=protected-access + if self._v.constraint is not None: + with ops.control_dependencies([update_op]): + return self._v.assign(self._v.constraint(self._v)) + else: + return update_op + else: + assert isinstance(g, indexed_slices.IndexedSlices), ( + "Gradient ", g, " is neither a tensor nor IndexedSlices.") + if self._v.constraint is not None: + raise RuntimeError( + "Cannot use a constraint function on a sparse variable.") + # pylint: disable=protected-access + return optimizer._apply_sparse_duplicate_indices(g, self._v) + + +class _DenseReadResourceVariableProcessor(_OptimizableVariable): + """Processor for dense ResourceVariables.""" + + def __init__(self, v): + self._v = v + + def target(self): + return self._v + + def update_op(self, optimizer, g): + # pylint: disable=protected-access + update_op = optimizer._resource_apply_dense(g, self._v.op.inputs[0]) + if self._v.constraint is not None: + with ops.control_dependencies([update_op]): + return self._v.assign(self._v.constraint(self._v)) + else: + return update_op + + +class _DenseResourceVariableProcessor(_OptimizableVariable): + """Processor for dense ResourceVariables.""" + + def __init__(self, v): + self._v = v + + def target(self): + return self._v + + def update_op(self, optimizer, g): + # pylint: disable=protected-access + if isinstance(g, indexed_slices.IndexedSlices): + if self._v.constraint is not None: + raise RuntimeError( + "Cannot use a constraint function on a sparse variable.") + return optimizer._resource_apply_sparse_duplicate_indices( + g.values, self._v, g.indices) + update_op = optimizer._resource_apply_dense(g, self._v) + if self._v.constraint is not None: + with ops.control_dependencies([update_op]): + return self._v.assign(self._v.constraint(self._v)) + else: + return update_op + + +class _TensorProcessor(_OptimizableVariable): + """Processor for ordinary Tensors. + + Even though a Tensor can't really be updated, sometimes it is useful to + compute the gradients with respect to a Tensor using the optimizer. Updating + the Tensor is, of course, unsupported. + """ + + def __init__(self, v): + self._v = v + + def target(self): + return self._v + + def update_op(self, optimizer, g): + raise NotImplementedError("Trying to update a Tensor ", self._v) + + +def _get_processor(v): + """The processor of v.""" + if context.executing_eagerly(): + if isinstance(v, tensor.Tensor): + return _TensorProcessor(v) + else: + return _DenseResourceVariableProcessor(v) + if resource_variable_ops.is_resource_variable(v) and not v._in_graph_mode: # pylint: disable=protected-access + # True if and only if `v` was initialized eagerly. + return _DenseResourceVariableProcessor(v) + if v.op.type == "VarHandleOp": + return _DenseResourceVariableProcessor(v) + if isinstance(v, variables.Variable): + return _RefVariableProcessor(v) + if isinstance(v, tensor.Tensor): + return _TensorProcessor(v) + raise NotImplementedError("Trying to optimize unsupported type ", v) + + +@tf_export(v1=["train.Optimizer"]) +class Optimizer( + # Optimizers inherit from Trackable rather than AutoTrackable + # since they do most of their dependency management themselves (slot + # variables are special-cased, and non-slot variables are keyed to graphs). + trackable.Trackable): + """Base class for optimizers. + + This class defines the API to add Ops to train a model. You never use this + class directly, but instead instantiate one of its subclasses such as + `GradientDescentOptimizer`, `AdagradOptimizer`, or `MomentumOptimizer`. + + ### Usage + + ```python + # Create an optimizer with the desired parameters. + opt = GradientDescentOptimizer(learning_rate=0.1) + # Add Ops to the graph to minimize a cost by updating a list of variables. + # "cost" is a Tensor, and the list of variables contains tf.Variable + # objects. + opt_op = opt.minimize(cost, var_list=) + ``` + + In the training program you will just have to run the returned Op. + + ```python + # Execute opt_op to do one step of training: + opt_op.run() + ``` + + ### Processing gradients before applying them. + + Calling `minimize()` takes care of both computing the gradients and + applying them to the variables. If you want to process the gradients + before applying them you can instead use the optimizer in three steps: + + 1. Compute the gradients with `compute_gradients()`. + 2. Process the gradients as you wish. + 3. Apply the processed gradients with `apply_gradients()`. + + Example: + + ```python + # Create an optimizer. + opt = GradientDescentOptimizer(learning_rate=0.1) + + # Compute the gradients for a list of variables. + grads_and_vars = opt.compute_gradients(loss, ) + + # grads_and_vars is a list of tuples (gradient, variable). Do whatever you + # need to the 'gradient' part, for example cap them, etc. + capped_grads_and_vars = [(MyCapper(gv[0]), gv[1]) for gv in grads_and_vars] + + # Ask the optimizer to apply the capped gradients. + opt.apply_gradients(capped_grads_and_vars) + ``` + + ### Gating Gradients + + Both `minimize()` and `compute_gradients()` accept a `gate_gradients` + argument that controls the degree of parallelism during the application of + the gradients. + + The possible values are: `GATE_NONE`, `GATE_OP`, and `GATE_GRAPH`. + + `GATE_NONE`: Compute and apply gradients in parallel. This provides + the maximum parallelism in execution, at the cost of some non-reproducibility + in the results. For example the two gradients of `matmul` depend on the input + values: With `GATE_NONE` one of the gradients could be applied to one of the + inputs _before_ the other gradient is computed resulting in non-reproducible + results. + + `GATE_OP`: For each Op, make sure all gradients are computed before + they are used. This prevents race conditions for Ops that generate gradients + for multiple inputs where the gradients depend on the inputs. + + `GATE_GRAPH`: Make sure all gradients for all variables are computed + before any one of them is used. This provides the least parallelism but can + be useful if you want to process all gradients before applying any of them. + + ### Slots + + Some optimizer subclasses, such as `MomentumOptimizer` and `AdagradOptimizer` + allocate and manage additional variables associated with the variables to + train. These are called Slots. Slots have names and you can ask the + optimizer for the names of the slots that it uses. Once you have a slot name + you can ask the optimizer for the variable it created to hold the slot value. + + This can be useful if you want to log debug a training algorithm, report stats + about the slots, etc. + + @compatibility(TF2) + `tf.compat.v1.train.Optimizer` can be used in eager mode and `tf.function`, + but it is not recommended. Please use the subclasses of + `tf.keras.optimizers.Optimizer` instead in TF2. Please see [Basic training + loops](https://www.tensorflow.org/guide/basic_training_loops) or + [Writing a training loop from scratch] + (https://www.tensorflow.org/guide/keras/writing_a_training_loop_from_scratch) + for examples. + + If your TF1 code contains a `tf.compat.v1.train.Optimizer` symbol, whether it + is used with or without a `tf.estimator.Estimator`, you cannot simply replace + that with the corresponding `tf.keras.optimizers.Optimizer`s. To migrate to + TF2, it is advised the whole training program used with `Estimator` to be + migrated to Keras `Model.fit` based or TF2 custom training loops. + + #### Structural Mapping to Native TF2 + + Before: + + ```python + sgd_op = tf.compat.v1.train.GradientDescentOptimizer(3.0) + opt_op = sgd_op.minimize(cost, global_step, [var0, var1]) + opt_op.run(session=session) + ``` + + After: + + ```python + sgd = tf.keras.optimizers.SGD(3.0) + sgd.minimize(cost_fn, [var0, var1]) + ``` + + #### How to Map Arguments + + | TF1 Arg Name | TF2 Arg Name | Note | + | :-------------------- | :-------------- | :------------------------- | + | `use_locking` | Not supported | - | + | `name` | `name. ` | - | + + #### Before & After Usage Example + + Before: + + >>> g = tf.compat.v1.Graph() + >>> with g.as_default(): + ... var0 = tf.compat.v1.Variable([1.0, 2.0]) + ... var1 = tf.compat.v1.Variable([3.0, 4.0]) + ... cost = 5 * var0 + 3 * var1 + ... global_step = tf.compat.v1.Variable( + ... tf.compat.v1.zeros([], tf.compat.v1.int64), name='global_step') + ... init_op = tf.compat.v1.initialize_all_variables() + ... sgd_op = tf.compat.v1.train.GradientDescentOptimizer(3.0) + ... opt_op = sgd_op.minimize(cost, global_step, [var0, var1]) + >>> session = tf.compat.v1.Session(graph=g) + >>> session.run(init_op) + >>> opt_op.run(session=session) + >>> print(session.run(var0)) + [-14. -13.] + + + After: + >>> var0 = tf.Variable([1.0, 2.0]) + >>> var1 = tf.Variable([3.0, 4.0]) + >>> cost_fn = lambda: 5 * var0 + 3 * var1 + >>> sgd = tf.keras.optimizers.SGD(3.0) + >>> sgd.minimize(cost_fn, [var0, var1]) + >>> print(var0.numpy()) + [-14. -13.] + + @end_compatibility + + + """ + + # Values for gate_gradients. + GATE_NONE = 0 + GATE_OP = 1 + GATE_GRAPH = 2 + + def __init__(self, use_locking, name): + """Create a new Optimizer. + + This must be called by the constructors of subclasses. + + Args: + use_locking: Bool. If True apply use locks to prevent concurrent updates + to variables. + name: A non-empty string. The name to use for accumulators created + for the optimizer. + + Raises: + ValueError: If name is malformed. + """ + if not name: + raise ValueError("Must specify the optimizer name") + self._use_locking = use_locking + self._name = name + # Dictionary of slots. + # {slot_name : + # {_var_key(variable_to_train): slot_for_the_variable, ... }, + # ... } + self._slots = {} + self._non_slot_dict = {} + # For implementing Trackable. Stores information about how to restore + # slot variables which have not yet been created + # (trackable._CheckpointPosition objects). + # {slot_name : + # {_var_key(variable_to_train): [checkpoint_position, ... ], ... }, + # ... } + self._deferred_slot_restorations = {} + + # TODO(isaprykin): When using a DistributionStrategy, and when an + # optimizer is created in each replica, it might be dangerous to + # rely on some Optimizer methods. When such methods are called on a + # per-replica optimizer, an exception needs to be thrown. We do + # allow creation per-replica optimizers however, because the + # compute_gradients()->apply_gradients() sequence is safe. + + def get_name(self): + return self._name + + def minimize(self, loss, global_step=None, var_list=None, + gate_gradients=GATE_OP, aggregation_method=None, + colocate_gradients_with_ops=False, name=None, + grad_loss=None): + """Add operations to minimize `loss` by updating `var_list`. + + This method simply combines calls `compute_gradients()` and + `apply_gradients()`. If you want to process the gradient before applying + them call `compute_gradients()` and `apply_gradients()` explicitly instead + of using this function. + + Args: + loss: A `Tensor` containing the value to minimize. + global_step: Optional `Variable` to increment by one after the + variables have been updated. + var_list: Optional list or tuple of `Variable` objects to update to + minimize `loss`. Defaults to the list of variables collected in + the graph under the key `GraphKeys.TRAINABLE_VARIABLES`. + gate_gradients: How to gate the computation of gradients. Can be + `GATE_NONE`, `GATE_OP`, or `GATE_GRAPH`. + aggregation_method: Specifies the method used to combine gradient terms. + Valid values are defined in the class `AggregationMethod`. + colocate_gradients_with_ops: If True, try colocating gradients with + the corresponding op. + name: Optional name for the returned operation. + grad_loss: Optional. A `Tensor` holding the gradient computed for `loss`. + + Returns: + An Operation that updates the variables in `var_list`. If `global_step` + was not `None`, that operation also increments `global_step`. + + Raises: + ValueError: If some of the variables are not `Variable` objects. + + @compatibility(eager) + When eager execution is enabled, `loss` should be a Python function that + takes no arguments and computes the value to be minimized. Minimization (and + gradient computation) is done with respect to the elements of `var_list` if + not None, else with respect to any trainable variables created during the + execution of the `loss` function. `gate_gradients`, `aggregation_method`, + `colocate_gradients_with_ops` and `grad_loss` are ignored when eager + execution is enabled. + @end_compatibility + """ + grads_and_vars = self.compute_gradients( + loss, var_list=var_list, gate_gradients=gate_gradients, + aggregation_method=aggregation_method, + colocate_gradients_with_ops=colocate_gradients_with_ops, + grad_loss=grad_loss) + + vars_with_grad = [v for g, v in grads_and_vars if g is not None] + if not vars_with_grad: + raise ValueError( + "No gradients provided for any variable, check your graph for ops" + " that do not support gradients, between variables %s and loss %s." % + ([str(v) for _, v in grads_and_vars], loss)) + + return self.apply_gradients(grads_and_vars, global_step=global_step, + name=name) + + def compute_gradients(self, loss, var_list=None, + gate_gradients=GATE_OP, + aggregation_method=None, + colocate_gradients_with_ops=False, + grad_loss=None): + """Compute gradients of `loss` for the variables in `var_list`. + + This is the first part of `minimize()`. It returns a list + of (gradient, variable) pairs where "gradient" is the gradient + for "variable". Note that "gradient" can be a `Tensor`, an + `IndexedSlices`, or `None` if there is no gradient for the + given variable. + + @compatibility(TF2) + `tf.keras.optimizers.Optimizer` in TF2 does not provide a + `compute_gradients` method, and you should use a `tf.GradientTape` to + obtain the gradients: + + ```python + @tf.function + def train step(inputs): + batch_data, labels = inputs + with tf.GradientTape() as tape: + predictions = model(batch_data, training=True) + loss = tf.keras.losses.CategoricalCrossentropy( + reduction=tf.keras.losses.Reduction.NONE)(labels, predictions) + gradients = tape.gradient(loss, model.trainable_variables) + optimizer.apply_gradients(zip(gradients, model.trainable_variables)) + ``` + + Args: + loss: A Tensor containing the value to minimize or a callable taking + no arguments which returns the value to minimize. When eager execution + is enabled it must be a callable. + var_list: Optional list or tuple of `tf.Variable` to update to minimize + `loss`. Defaults to the list of variables collected in the graph + under the key `GraphKeys.TRAINABLE_VARIABLES`. + gate_gradients: How to gate the computation of gradients. Can be + `GATE_NONE`, `GATE_OP`, or `GATE_GRAPH`. + aggregation_method: Specifies the method used to combine gradient terms. + Valid values are defined in the class `AggregationMethod`. + colocate_gradients_with_ops: If True, try colocating gradients with + the corresponding op. + grad_loss: Optional. A `Tensor` holding the gradient computed for `loss`. + + Returns: + A list of (gradient, variable) pairs. Variable is always present, but + gradient can be `None`. + + Raises: + TypeError: If `var_list` contains anything else than `Variable` objects. + ValueError: If some arguments are invalid. + RuntimeError: If called with eager execution enabled and `loss` is + not callable. + + @compatibility(eager) + When eager execution is enabled, `gate_gradients`, `aggregation_method`, + and `colocate_gradients_with_ops` are ignored. + @end_compatibility + """ + if callable(loss): + with backprop.GradientTape() as tape: + if var_list is not None: + tape.watch(var_list) + loss_value = loss() + + # Scale loss if using a "mean" loss reduction and multiple replicas. + # Have to be careful to call distribute_utils.get_loss_reduction() + # *after* loss() is evaluated, so we know what loss reduction it uses. + # TODO(josh11b): Test that we handle weight decay in a reasonable way. + loss_value = self._scale_loss(loss_value) + + if var_list is None: + var_list = tape.watched_variables() + # TODO(jhseu): Figure out why GradientTape's gradients don't require loss + # to be executed. + with ops.control_dependencies([loss_value]): + grads = tape.gradient(loss_value, var_list, grad_loss) + return list(zip(grads, var_list)) + + # Non-callable/Tensor loss case + if context.executing_eagerly(): + raise RuntimeError( + "`loss` passed to Optimizer.compute_gradients should " + "be a function when eager execution is enabled.") + + # Scale loss if using a "mean" loss reduction and multiple replicas. + loss = self._scale_loss(loss) + + if gate_gradients not in [Optimizer.GATE_NONE, Optimizer.GATE_OP, + Optimizer.GATE_GRAPH]: + raise ValueError("gate_gradients must be one of: Optimizer.GATE_NONE, " + "Optimizer.GATE_OP, Optimizer.GATE_GRAPH. Not %s" % + gate_gradients) + self._assert_valid_dtypes([loss]) + if grad_loss is not None: + self._assert_valid_dtypes([grad_loss]) + if var_list is None: + var_list = ( + variables.trainable_variables() + + ops.get_collection(ops.GraphKeys.TRAINABLE_RESOURCE_VARIABLES)) + else: + var_list = nest.flatten(var_list) + # pylint: disable=protected-access + var_list += ops.get_collection(ops.GraphKeys._STREAMING_MODEL_PORTS) + # pylint: enable=protected-access + processors = [_get_processor(v) for v in var_list] + if not var_list: + raise ValueError("No variables to optimize.") + var_refs = [p.target() for p in processors] + grads = gradients.gradients( + loss, var_refs, grad_ys=grad_loss, + gate_gradients=(gate_gradients == Optimizer.GATE_OP), + aggregation_method=aggregation_method, + colocate_gradients_with_ops=colocate_gradients_with_ops) + if gate_gradients == Optimizer.GATE_GRAPH: + grads = control_flow_ops.tuple(grads) + grads_and_vars = list(zip(grads, var_list)) + self._assert_valid_dtypes( + [v for g, v in grads_and_vars + if g is not None and v.dtype != dtypes.resource]) + return grads_and_vars + + @staticmethod + def _scale_loss(loss_value): + ops.get_default_graph()._is_loss_scaled_by_optimizer = False # pylint: disable=protected-access + if distribute_utils.get_loss_reduction() == ds_reduce_util.ReduceOp.MEAN: + num_replicas = distribute_lib.get_strategy().num_replicas_in_sync + if num_replicas > 1: + loss_value *= (1. / num_replicas) + ops.get_default_graph()._is_loss_scaled_by_optimizer = True # pylint: disable=protected-access + return loss_value + + def apply_gradients( + self, + grads_and_vars, + global_step=None, + name=None, + skip_gradients_aggregation=False, + ): + """Apply gradients to variables. + + This is the second part of `minimize()`. It returns an `Operation` that + applies gradients. + + @compatibility(TF2) + #### How to Map Arguments + + | TF1 Arg Name | TF2 Arg Name | Note | + | :-------------------- | :-------------- | :------------------------- | + | `grads_and_vars` | `grads_and_vars`| - | + | `global_step` | Not supported. | Use `optimizer.iterations` | + | `name` | `name. ` | - | + + Args: + grads_and_vars: List of (gradient, variable) pairs as returned by + `compute_gradients()`. + global_step: Optional `Variable` to increment by one after the variables + have been updated. + name: Optional name for the returned operation. Default to the name + passed to the `Optimizer` constructor. + skip_gradients_aggregation: If true, gradients aggregation will not be + performed inside optimizer. Usually this arg is set to True when you + write custom code aggregating gradients outside the optimizer. + + Returns: + An `Operation` that applies the specified gradients. If `global_step` + was not None, that operation also increments `global_step`. + + Raises: + TypeError: If `grads_and_vars` is malformed. + ValueError: If none of the variables have gradients. + RuntimeError: If you should use `_distributed_apply()` instead. + """ + # This is a default implementation of apply_gradients() that can be shared + # by most optimizers. It relies on the subclass implementing the following + # methods: _create_slots(), _prepare(), _apply_dense(), and _apply_sparse(). + + # TODO(isaprykin): Get rid of `has_strategy()` check by + # always calling _distributed_apply(), using the default distribution + # as needed. + if distribute_lib.has_strategy() and not skip_gradients_aggregation: + # Handle DistributionStrategy case. + if distribute_lib.in_cross_replica_context(): + raise RuntimeError("Use `_distributed_apply()` instead of " + "`apply_gradients()` in a cross-replica context.") + + grads_and_vars = get_filtered_grad_fn(lambda: grads_and_vars)() + return distribute_lib.get_replica_context().merge_call( + self._distributed_apply, args=(grads_and_vars, global_step, name)) + + # No DistributionStrategy case. + grads_and_vars = tuple(grads_and_vars) # Make sure repeat iteration works. + if not grads_and_vars: + raise ValueError("No variables provided.") + converted_grads_and_vars = [] + for g, v in grads_and_vars: + if g is not None: + try: + # Convert the grad to Tensor or IndexedSlices if necessary. + g = indexed_slices.convert_to_tensor_or_indexed_slices(g) + except TypeError: + raise TypeError( + "Gradient must be convertible to a Tensor" + " or IndexedSlices, or None: %s" % g) + if not isinstance(g, (tensor.Tensor, indexed_slices.IndexedSlices)): + raise TypeError( + "Gradient must be a Tensor, IndexedSlices, or None: %s" % g) + p = _get_processor(v) + converted_grads_and_vars.append((g, v, p)) + + converted_grads_and_vars = tuple(converted_grads_and_vars) + var_list = [v for g, v, _ in converted_grads_and_vars if g is not None] + if not var_list: + raise ValueError("No gradients provided for any variable: %s." % + ([str(v) for _, v, _ in converted_grads_and_vars],)) + with ops.init_scope(): + self._create_slots(var_list) + update_ops = [] + with ops.name_scope(name, self._name, skip_on_eager=False) as name: + self._prepare() + for grad, var, processor in converted_grads_and_vars: + if grad is None: + continue + # We colocate all ops created in _apply_dense or _apply_sparse + # on the same device as the variable. + # TODO(apassos): figure out how to get the variable name here. + if (context.executing_eagerly() or + resource_variable_ops.is_resource_variable(var) + and not var._in_graph_mode): # pylint: disable=protected-access + scope_name = "" + else: + scope_name = var.op.name + with ops.name_scope( + "update_" + scope_name, + skip_on_eager=False), ops.colocate_with(var): + update_ops.append(processor.update_op(self, grad)) + if global_step is None: + apply_updates = self._finish(update_ops, name) + else: + with ops.control_dependencies([self._finish(update_ops, "update")]): + with ops.colocate_with(global_step): + if isinstance( + global_step, resource_variable_ops.BaseResourceVariable): + # TODO(apassos): the implicit read in assign_add is slow; consider + # making it less so. + apply_updates = resource_variable_ops.assign_add_variable_op( + global_step.handle, + ops.convert_to_tensor(1, dtype=global_step.dtype), + name=name) + else: + apply_updates = state_ops.assign_add(global_step, 1, name=name) + + if not context.executing_eagerly(): + if isinstance(apply_updates, tensor.Tensor): + apply_updates = apply_updates.op + train_op = ops.get_collection_ref(ops.GraphKeys.TRAIN_OP) + if apply_updates not in train_op: + train_op.append(apply_updates) + + return apply_updates + + def _distributed_apply(self, + distribution, + grads_and_vars, + global_step=None, + name=None): + """A version of `apply_gradients` for cross-replica context. + + This is a version of `apply_gradients()` for when you are using a + `DistributionStrategy` and are in a cross-replica context. If in a + replica context, use `apply_gradients()` as normal. + + Args: + distribution: A `DistributionStrategy` object. + grads_and_vars: List of (gradient, variable) pairs as returned by + `compute_gradients()`, and then aggregated across replicas. + global_step: Optional (mirrored) `Variable` to increment by one + after the variables have been updated. + name: Optional name for the returned operation. Default to the + name passed to the `Optimizer` constructor. + + Returns: + An `Operation` that applies the specified gradients across all + replicas. If `global_step` was not None, that operation also + increments `global_step` + """ + reduced_grads = distribution.extended.batch_reduce_to( + ds_reduce_util.ReduceOp.SUM, grads_and_vars) + var_list = [v for _, v in grads_and_vars] + grads_and_vars = zip(reduced_grads, var_list) + + # Note that this is called in a cross-replica context. + with ops.init_scope(): + self._create_slots(var_list) + + def update(v, g): + """Apply gradients to a replica variable.""" + assert v is not None + + try: + # Convert the grad to Tensor or IndexedSlices if necessary. + g = indexed_slices.convert_to_tensor_or_indexed_slices(g) + except TypeError: + raise TypeError("Gradient must be convertible to a Tensor" + " or IndexedSlices, or None: %s" % g) + if not isinstance(g, (tensor.Tensor, indexed_slices.IndexedSlices)): + raise TypeError( + "Gradient must be a Tensor, IndexedSlices, or None: %s" % g) + p = _get_processor(v) + + if context.executing_eagerly() or ( + resource_variable_ops.is_resource_variable(v) and + not v._in_graph_mode): # pylint: disable=protected-access + scope_name = v.name.split(":")[0] + else: + scope_name = v.op.name + + # device_policy is set because non-mirrored tensors will be read in + # `update_op`. `_resource_apply_dense`, `lr_t`, `beta1_t` and `beta2_t` + # is an example. + with ops.name_scope("update_" + scope_name): + return p.update_op(self, g) + + with ops.name_scope(name, self._name) as name: + self._prepare() + + update_ops = [ + op + for grad, var in grads_and_vars + for op in distribution.extended.update( + var, update, args=(grad,), group=False) + ] + + def finish(self, update_ops): + return self._finish(update_ops, "update") + + non_slot_devices = distribution.extended.non_slot_devices(var_list) + finish_updates = distribution.extended.update_non_slot( + non_slot_devices, finish, args=(self, update_ops), group=False) + if global_step is None: + apply_updates = distribution.group(finish_updates, name=name) + else: + with ops.control_dependencies(finish_updates): + apply_updates = distribution.extended.update( + global_step, state_ops.assign_add, args=(1,), + kwargs={"name": name}) + + if not context.executing_eagerly(): + if isinstance(apply_updates, tensor.Tensor): + apply_updates = apply_updates.op + train_op = ops.get_collection_ref(ops.GraphKeys.TRAIN_OP) + if apply_updates not in train_op: + train_op.append(apply_updates) + + return apply_updates + + def get_slot(self, var, name): + """Return a slot named `name` created for `var` by the Optimizer. + + Some `Optimizer` subclasses use additional variables. For example + `Momentum` and `Adagrad` use variables to accumulate updates. This method + gives access to these `Variable` objects if for some reason you need them. + + Use `get_slot_names()` to get the list of slot names created by the + `Optimizer`. + + Args: + var: A variable passed to `minimize()` or `apply_gradients()`. + name: A string. + + Returns: + The `Variable` for the slot if it was created, `None` otherwise. + """ + named_slots = self._slots.get(name, None) + if not named_slots: + return None + slot = named_slots.get(_var_key(var), None) + if (distribute_utils.is_distributed_variable(slot) and + not distribute_utils.is_distributed_variable(var)): + # Make sure var and slot are either both DistributedVariable, or both + # per replica variables. + slot = slot._get_on_device_or_primary() # pylint: disable=protected-access + return slot + + def get_slot_names(self): + """Return a list of the names of slots created by the `Optimizer`. + + See `get_slot()`. + + Returns: + A list of strings. + """ + return sorted(self._slots.keys()) + + def variables(self): + """A list of variables which encode the current state of `Optimizer`. + + Includes slot variables and additional global variables created by the + optimizer in the current default graph. + + Returns: + A list of variables. + """ + current_graph = ops.get_default_graph() + + def _from_current_graph(variable): + if variable._in_graph_mode: # pylint: disable=protected-access + return variable.op.graph is current_graph + else: + # No variable.op in eager mode. We don't expect lots of eager graphs, + # but behavior should be consistent with graph mode. + return variable._graph_key == current_graph._graph_key # pylint: disable=protected-access + + optimizer_variables = [v for v in self._non_slot_variables() + if _from_current_graph(v)] + for _, variable_dict in self._slots.items(): + for _, slot_for_variable in variable_dict.items(): + if _from_current_graph(slot_for_variable): + optimizer_variables.append(slot_for_variable) + # Sort variables by name so that the return is deterministic. + return sorted(optimizer_variables, key=lambda v: v.name) + + def _create_non_slot_variable(self, initial_value, name, colocate_with): + """Add an extra variable, not associated with a slot.""" + # Recommendation: Use OptimizerV2 if your optimizer uses non-slot variables. + eager = ops.executing_eagerly_outside_functions() + graph = None if eager else colocate_with.graph + + key = (name, graph) + v = self._non_slot_dict.get(key, None) + if v is None: + self._maybe_initialize_trackable() + distribution_strategy = distribute_lib.get_strategy() + with distribution_strategy.extended.colocate_vars_with(colocate_with): + if eager: + restored_initial_value = self._preload_simple_restoration( + name=name) + if restored_initial_value is not None: + initial_value = restored_initial_value + v = variable_v1.VariableV1( + initial_value, name=name, trainable=False, + use_resource=resource_variable_ops.is_resource_variable( + colocate_with)) + # Restore this variable by name if necessary, but don't add a + # Trackable dependency. Optimizers return the current graph's + # non-slot variables from _checkpoint_dependencies explicitly rather + # than unconditionally adding dependencies (since there may be multiple + # non-slot variables with the same name in different graphs, trying to + # save all of them would result in errors). + self._handle_deferred_dependencies(name=name, trackable=v) + self._non_slot_dict[key] = v + + return v + + def _trackable_children(self, + save_type=trackable.SaveType.CHECKPOINT, + **kwargs): + """From Trackable. Gather graph-specific non-slot variables to save.""" + current_graph_non_slot_variables = {} + current_graph_key = ops.get_default_graph()._graph_key # pylint: disable=protected-access + for (name, _), variable_object in sorted(self._non_slot_dict.items(), + # Avoid comparing graphs + key=lambda item: item[0][0]): + # Skip checking for graph key for eager mode since there's only one graph. + # This is necessary because there are cases where _trackable_children() is + # called in a differenr thread from the main thread (e.g., async + # checkpoint) and hence the default graph key would be different. + if (context.executing_eagerly() + or variable_object._graph_key == current_graph_key): # pylint: disable=protected-access + current_graph_non_slot_variables[name] = variable_object + current_graph_non_slot_variables.update( + super()._trackable_children(save_type, **kwargs) + ) + return current_graph_non_slot_variables + + def _lookup_dependency(self, name, cached_dependencies=None): + """From Trackable. Find a non-slot variable in the current graph.""" + unconditional = super()._lookup_dependency(name, cached_dependencies) + if unconditional is not None: + return unconditional + graph = None if context.executing_eagerly() else ops.get_default_graph() + return self._get_non_slot_variable(name, graph=graph) + + def _get_non_slot_variable(self, name, graph=None): + non_slot = self._non_slot_dict.get((name, graph), None) + if distribute_utils.value_container(non_slot) is not non_slot: + # This is a mirrored non-slot. In order to enable code like `_finish` + # to assign to a non-slot, return the current context replica. + return non_slot.get() + else: + return non_slot + + def _non_slot_variables(self): + """Additional variables created by the `Optimizer`. + + Returns: + A list or tuple of variables. + """ + return self._non_slot_dict.values() + + def _assert_valid_dtypes(self, tensors): + """Asserts tensors are all valid types (see `_valid_dtypes`). + + Args: + tensors: Tensors to check. + + Raises: + ValueError: If any tensor is not a valid type. + """ + valid_dtypes = self._valid_dtypes() + for t in tensors: + dtype = t.dtype.base_dtype + if dtype not in valid_dtypes: + raise ValueError( + "Invalid type %r for %s, expected: %s." % ( + dtype, t.name, [v for v in valid_dtypes])) + + # -------------- + # Methods to be implemented by subclasses if they want to use the + # inherited implementation of apply_gradients() or compute_gradients(). + # -------------- + def _valid_dtypes(self): + """Valid types for loss, variables and gradients. + + Subclasses should override to allow other float types. + + Returns: + Valid types for loss, variables and gradients. + """ + return set( + [dtypes.float16, dtypes.bfloat16, dtypes.float32, dtypes.float64]) + + def _create_slots(self, var_list): + """Create all slots needed by the variables. + + Args: + var_list: A list of `Variable` objects. + """ + # No slots needed by default + pass + + def _prepare(self): + """Create all needed tensors before applying gradients. + + This is called with the name_scope using the "name" that + users have chosen for the application of gradients. + """ + pass + + def _apply_dense(self, grad, var): + """Add ops to apply dense gradients to `var`. + + Args: + grad: A `Tensor`. + var: A `Variable` object. + + Returns: + An `Operation`. + """ + raise NotImplementedError() + + def _resource_apply_dense(self, grad, handle): + """Add ops to apply dense gradients to the variable `handle`. + + Args: + grad: a `Tensor` representing the gradient. + handle: a `Tensor` of dtype `resource` which points to the variable + to be updated. + + Returns: + An `Operation` which updates the value of the variable. + """ + raise NotImplementedError() + + def _resource_apply_sparse_duplicate_indices(self, grad, handle, indices): + """Add ops to apply sparse gradients to `handle`, with repeated indices. + + Optimizers which override this method must deal with repeated indices. See + the docstring of `_apply_sparse_duplicate_indices` for details. By default + the correct behavior, to sum non-unique indices and their associated + gradients, is enforced by first pre-processing `grad` and `indices` and + passing them on to `_resource_apply_sparse`. Optimizers which deal correctly + with duplicate indices may instead override this method to avoid the + overhead of summing. + + Args: + grad: a `Tensor` representing the gradient for the affected indices. + handle: a `Tensor` of dtype `resource` which points to the variable + to be updated. + indices: a `Tensor` of integral type representing the indices for + which the gradient is nonzero. Indices may be repeated. + + Returns: + An `Operation` which updates the value of the variable. + """ + summed_grad, unique_indices = _deduplicate_indexed_slices( + values=grad, indices=indices) + return self._resource_apply_sparse(summed_grad, handle, unique_indices) + + def _resource_apply_sparse(self, grad, handle, indices): + """Add ops to apply sparse gradients to the variable `handle`. + + Similar to `_apply_sparse`, the `indices` argument to this method has been + de-duplicated. Optimizers which deal correctly with non-unique indices may + instead override `_resource_apply_sparse_duplicate_indices` to avoid this + overhead. + + Args: + grad: a `Tensor` representing the gradient for the affected indices. + handle: a `Tensor` of dtype `resource` which points to the variable + to be updated. + indices: a `Tensor` of integral type representing the indices for + which the gradient is nonzero. Indices are unique. + + Returns: + An `Operation` which updates the value of the variable. + """ + raise NotImplementedError() + + def _apply_sparse_duplicate_indices(self, grad, var): + """Add ops to apply sparse gradients to `var`, with repeated sparse indices. + + Optimizers which override this method must deal with IndexedSlices objects + such as the following: + + IndexedSlicesValue(values=[1, 1], indices=[0, 0], dense_shape=[1]) + + The correct interpretation is: + + IndexedSlicesValue(values=[2], indices=[0], dense_shape=[1]) + + Many optimizers deal incorrectly with repeated indices when updating based + on sparse gradients (e.g. summing squares rather than squaring the sum, or + applying momentum terms multiple times). Adding first is always the correct + behavior, so this is enforced here by reconstructing the IndexedSlices to + have only unique indices, then calling _apply_sparse. + + Optimizers which deal correctly with repeated indices may instead override + this method to avoid the overhead of summing indices. + + Args: + grad: `IndexedSlices`. + var: A `Variable` object. + + Returns: + An `Operation`. + """ + summed_values, unique_indices = _deduplicate_indexed_slices( + values=grad.values, indices=grad.indices) + gradient_no_duplicate_indices = indexed_slices.IndexedSlices( + indices=unique_indices, + values=summed_values, + dense_shape=grad.dense_shape) + return self._apply_sparse(gradient_no_duplicate_indices, var) + + def _apply_sparse(self, grad, var): + """Add ops to apply sparse gradients to `var`. + + The IndexedSlices object passed to `grad` in this function is by default + pre-processed in `_apply_sparse_duplicate_indices` to remove duplicate + indices (see its docstring for details). Optimizers which can tolerate or + have correct special cases for duplicate sparse indices may override + `_apply_sparse_duplicate_indices` instead of this function, avoiding that + overhead. + + Args: + grad: `IndexedSlices`, with no repeated indices. + var: A `Variable` object. + + Returns: + An `Operation`. + """ + raise NotImplementedError() + + def _finish(self, update_ops, name_scope): + """Do what is needed to finish the update. + + This is called with the `name_scope` using the "name" that + users have chosen for the application of gradients. + + Args: + update_ops: List of `Operation` objects to update variables. This list + contains the values returned by the `_apply_dense()` and + `_apply_sparse()` calls. + name_scope: String. Name to use for the returned operation. + + Returns: + The operation to apply updates. + """ + return control_flow_ops.group(*update_ops, name=name_scope) + + # -------------- + # Utility methods for subclasses. + # -------------- + + def _slot_dict(self, slot_name): + """Returns a dict for caching slots created under the given name. + + Args: + slot_name: Name for the slot. + + Returns: + A dict that maps primary `Variable` objects to the slot created + for that variable, under the given slot name. + """ + named_slots = self._slots.get(slot_name, None) + if named_slots is None: + named_slots = {} + self._slots[slot_name] = named_slots + return named_slots + + def _get_or_make_slot(self, var, val, slot_name, op_name): + """Find or create a slot for a variable. + + Args: + var: A `Variable` object. + val: A `Tensor`. The initial value of the slot. + slot_name: Name for the slot. + op_name: Name to use when scoping the Variable that + needs to be created for the slot. + + Returns: + A `Variable` object. + """ + named_slots = self._slot_dict(slot_name) + if _var_key(var) not in named_slots: + new_slot_variable = slot_creator.create_slot( + var, val, op_name, copy_xla_sharding=True) + self._restore_slot_variable( + slot_name=slot_name, variable=var, + slot_variable=new_slot_variable) + named_slots[_var_key(var)] = new_slot_variable + return named_slots[_var_key(var)] + + def _get_or_make_slot_with_initializer(self, var, initializer, shape, dtype, + slot_name, op_name): + """Find or create a slot for a variable, using an Initializer. + + Args: + var: A `Variable` object. + initializer: An `Initializer`. The initial value of the slot. + shape: Shape of the initial value of the slot. + dtype: Type of the value of the slot. + slot_name: Name for the slot. + op_name: Name to use when scoping the Variable that + needs to be created for the slot. + + Returns: + A `Variable` object. + """ + named_slots = self._slot_dict(slot_name) + if _var_key(var) not in named_slots: + new_slot_variable = slot_creator.create_slot_with_initializer( + var, initializer, shape, dtype, op_name, copy_xla_sharding=True) + self._restore_slot_variable( + slot_name=slot_name, variable=var, + slot_variable=new_slot_variable) + named_slots[_var_key(var)] = new_slot_variable + return named_slots[_var_key(var)] + + def _zeros_slot(self, var, slot_name, op_name): + """Find or create a slot initialized with 0.0. + + Args: + var: A `Variable` object. + slot_name: Name for the slot. + op_name: Name to use when scoping the Variable that + needs to be created for the slot. + + Returns: + A `Variable` object. + """ + named_slots = self._slot_dict(slot_name) + if _var_key(var) not in named_slots: + new_slot_variable = slot_creator.create_zeros_slot( + var, op_name, copy_xla_sharding=True) + self._restore_slot_variable( + slot_name=slot_name, variable=var, + slot_variable=new_slot_variable) + named_slots[_var_key(var)] = new_slot_variable + return named_slots[_var_key(var)] + + # -------------- + # For implementing the Trackable interface. + # -------------- + + def _restore_slot_variable(self, slot_name, variable, slot_variable): + """Restore a newly created slot variable's value.""" + variable_key = _var_key(variable) + deferred_restorations = self._deferred_slot_restorations.get( + slot_name, {}).pop(variable_key, []) + # Iterate over restores, highest restore UID first to minimize the number + # of assignments. + deferred_restorations.sort(key=lambda position: position.restore_uid, + reverse=True) + for checkpoint_position in deferred_restorations: + checkpoint_position.restore(slot_variable) + + def _create_or_restore_slot_variable( + self, slot_variable_position, slot_name, variable): + """Restore a slot variable's value, possibly creating it. + + Called when a variable which has an associated slot variable is created or + restored. When executing eagerly, we create the slot variable with a + restoring initializer. + + No new variables are created when graph building. Instead, + _restore_slot_variable catches these after normal creation and adds restore + ops to the graph. This method is nonetheless important when graph building + for the case when a slot variable has already been created but `variable` + has just been added to a dependency graph (causing us to realize that the + slot variable needs to be restored). + + Args: + slot_variable_position: A `trackable._CheckpointPosition` object + indicating the slot variable `Trackable` object to be restored. + slot_name: The name of this `Optimizer`'s slot to restore into. + variable: The variable object this slot is being created for. + """ + named_slots = self._slot_dict(slot_name) + variable_key = _var_key(variable) + slot_variable = named_slots.get(variable_key, None) + if (slot_variable is None and context.executing_eagerly() and + slot_variable_position.is_simple_variable() + # Defer slot variable creation if there is an active variable creator + # scope. Generally we'd like to eagerly create/restore slot variables + # when possible, but this may mean that scopes intended to catch + # `variable` also catch its eagerly created slot variable + # unintentionally (specifically make_template would add a dependency on + # a slot variable if not for this case). Deferring is mostly harmless + # (aside from double initialization), and makes variable creator scopes + # behave the same way they do when graph building. + and not ops.get_default_graph()._variable_creator_stack): # pylint: disable=protected-access + initializer = trackable.CheckpointInitialValueCallable( + checkpoint_position=slot_variable_position) + # CheckpointInitialValueCallable will ignore the shape and dtype + # parameters but they must be passed. + slot_variable = self._get_or_make_slot_with_initializer( + var=variable, + initializer=initializer, + shape=variable.shape, + dtype=variable.dtype, + slot_name=slot_name, + op_name=self._name) + # Slot variables are not owned by any one object (because we don't want to + # save the slot variable if the optimizer is saved without the non-slot + # variable, or if the non-slot variable is saved without the optimizer; + # it's a dependency hypergraph with edges of the form (optimizer, non-slot + # variable, variable)). So we don't _track_ slot variables anywhere, and + # instead special-case this dependency and otherwise pretend it's a normal + # graph. + if slot_variable is not None: + # If we've either made this slot variable, or if we've pulled out an + # existing slot variable, we should restore it. + slot_variable_position.restore(slot_variable) + else: + # We didn't make the slot variable. Defer restoring until it gets created + # normally. We keep a list rather than the one with the highest restore + # UID in case slot variables have their own dependencies, in which case + # those could differ between restores. + self._deferred_slot_restorations.setdefault( + slot_name, {}).setdefault(variable_key, []).append( + slot_variable_position) + + def _call_if_callable(self, param): + """Call the function if param is callable.""" + return param() if callable(param) else param diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/proximal_adagrad.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/proximal_adagrad.py new file mode 100644 index 0000000000000000000000000000000000000000..9001a452d6786b91093738fafa949088255e2c78 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/proximal_adagrad.py @@ -0,0 +1,123 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""ProximalAdagrad for TensorFlow.""" +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import ops +from tensorflow.python.ops import math_ops +from tensorflow.python.training import optimizer +from tensorflow.python.training import training_ops +from tensorflow.python.util.tf_export import tf_export + + +@tf_export(v1=["train.ProximalAdagradOptimizer"]) +class ProximalAdagradOptimizer(optimizer.Optimizer): + # pylint: disable=line-too-long + """Optimizer that implements the Proximal Adagrad algorithm. + + References: + Adaptive Subgradient Methods for Online Learning and Stochastic Optimization: + [Duchi et al., 2011](http://jmlr.org/papers/v12/duchi11a.html) + ([pdf](http://www.jmlr.org/papers/volume12/duchi11a/duchi11a.pdf)) + Efficient Learning using Forward-Backward Splitting: + [Duchi et al., 2009](http://papers.nips.cc/paper/3793-efficient-learning-using-forward-backward-splitting) + ([pdf](http://papers.nips.cc/paper/3793-efficient-learning-using-forward-backward-splitting.pdf)) + """ + + def __init__(self, learning_rate, initial_accumulator_value=0.1, + l1_regularization_strength=0.0, l2_regularization_strength=0.0, + use_locking=False, name="ProximalAdagrad"): + """Construct a new ProximalAdagrad optimizer. + + Args: + learning_rate: A `Tensor` or a floating point value. The learning rate. + initial_accumulator_value: A floating point value. + Starting value for the accumulators, must be positive. + l1_regularization_strength: A float value, must be greater than or + equal to zero. + l2_regularization_strength: A float value, must be greater than or + equal to zero. + use_locking: If `True` use locks for update operations. + name: Optional name prefix for the operations created when applying + gradients. Defaults to "Adagrad". + + Raises: + ValueError: If the `initial_accumulator_value` is invalid. + """ + if initial_accumulator_value <= 0.0: + raise ValueError("initial_accumulator_value must be positive: %s" % + initial_accumulator_value) + super(ProximalAdagradOptimizer, self).__init__(use_locking, name) + self._learning_rate = learning_rate + self._initial_accumulator_value = initial_accumulator_value + self._l1_regularization_strength = l1_regularization_strength + self._l2_regularization_strength = l2_regularization_strength + # Created in Initialize. + self._l1_regularization_strength_tensor = None + self._l2_regularization_strength_tensor = None + self._learning_rate_tensor = None + + def _create_slots(self, var_list): + for v in var_list: + with ops.colocate_with(v): + val = constant_op.constant(self._initial_accumulator_value, + shape=v.get_shape(), + dtype=v.dtype.base_dtype) + self._get_or_make_slot(v, val, "accumulator", self._name) + + def _prepare(self): + self._learning_rate_tensor = ops.convert_to_tensor(self._learning_rate, + name="learning_rate") + self._l1_regularization_strength_tensor = ops.convert_to_tensor( + self._l1_regularization_strength, + name="l1_regularization_strength") + self._l2_regularization_strength_tensor = ops.convert_to_tensor( + self._l2_regularization_strength, + name="l2_regularization_strength") + + def _apply_dense(self, grad, var): + acc = self.get_slot(var, "accumulator") + return training_ops.apply_proximal_adagrad( + var, acc, self._learning_rate_tensor, + self._l1_regularization_strength_tensor, + self._l2_regularization_strength_tensor, + grad, use_locking=self._use_locking) + + def _resource_apply_dense(self, grad, var): + acc = self.get_slot(var, "accumulator") + return training_ops.resource_apply_proximal_adagrad( + var.handle, acc.handle, self._learning_rate_tensor, + self._l1_regularization_strength_tensor, + self._l2_regularization_strength_tensor, + grad, use_locking=self._use_locking) + + def _apply_sparse(self, grad, var): + acc = self.get_slot(var, "accumulator") + return training_ops.sparse_apply_proximal_adagrad( + var, acc, self._learning_rate_tensor, + self._l1_regularization_strength_tensor, + self._l2_regularization_strength_tensor, + grad.values, grad.indices, + use_locking=self._use_locking) + + def _resource_apply_sparse(self, grad, var, indices): + acc = self.get_slot(var, "accumulator") + return training_ops.resource_sparse_apply_proximal_adagrad( + var.handle, acc.handle, + math_ops.cast(self._learning_rate_tensor, grad.dtype), + math_ops.cast(self._l1_regularization_strength_tensor, grad.dtype), + math_ops.cast(self._l2_regularization_strength_tensor, grad.dtype), + grad, indices, + use_locking=self._use_locking) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/proximal_gradient_descent.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/proximal_gradient_descent.py new file mode 100644 index 0000000000000000000000000000000000000000..70f6997595d829ef9db36a8c5751561e957cc67f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/proximal_gradient_descent.py @@ -0,0 +1,104 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""ProximalGradientDescent for TensorFlow.""" +from tensorflow.python.framework import ops +# pylint: disable=unused-import +from tensorflow.python.ops import math_ops +# pylint: enable=unused-import +from tensorflow.python.training import optimizer +from tensorflow.python.training import training_ops +from tensorflow.python.util.tf_export import tf_export + + +@tf_export(v1=["train.ProximalGradientDescentOptimizer"]) +class ProximalGradientDescentOptimizer(optimizer.Optimizer): + # pylint: disable=line-too-long + """Optimizer that implements the proximal gradient descent algorithm. + + References: + Efficient Learning using Forward-Backward Splitting: + [Duchi et al., 2009](http://papers.nips.cc/paper/3793-efficient-learning-using-forward-backward-splitting) + ([pdf](http://papers.nips.cc/paper/3793-efficient-learning-using-forward-backward-splitting.pdf)) + """ + + def __init__(self, learning_rate, l1_regularization_strength=0.0, + l2_regularization_strength=0.0, use_locking=False, + name="ProximalGradientDescent"): + """Construct a new proximal gradient descent optimizer. + + Args: + learning_rate: A Tensor or a floating point value. The learning + rate to use. + l1_regularization_strength: A float value, must be greater than or + equal to zero. + l2_regularization_strength: A float value, must be greater than or + equal to zero. + use_locking: If True use locks for update operations. + name: Optional name prefix for the operations created when applying + gradients. Defaults to "GradientDescent". + """ + super(ProximalGradientDescentOptimizer, self).__init__(use_locking, name) + self._learning_rate = learning_rate + self._l1_regularization_strength = l1_regularization_strength + self._l2_regularization_strength = l2_regularization_strength + self._l1_regularization_strength_tensor = None + self._l2_regularization_strength_tensor = None + + def _apply_dense(self, grad, var): + return training_ops.apply_proximal_gradient_descent( + var, + self._learning_rate_tensor, + self._l1_regularization_strength_tensor, + self._l2_regularization_strength_tensor, + grad, + use_locking=self._use_locking).op + + def _resource_apply_dense(self, grad, var): + return training_ops.resource_apply_proximal_gradient_descent( + var.handle, + self._learning_rate_tensor, + self._l1_regularization_strength_tensor, + self._l2_regularization_strength_tensor, + grad, + use_locking=self._use_locking) + + def _apply_sparse(self, grad, var): + return training_ops.sparse_apply_proximal_gradient_descent( + var, + self._learning_rate_tensor, + self._l1_regularization_strength_tensor, + self._l2_regularization_strength_tensor, + grad.values, + grad.indices, + use_locking=self._use_locking).op + + def _resource_apply_sparse(self, grad, var, indices): + return training_ops.resource_sparse_apply_proximal_gradient_descent( + var.handle, + math_ops.cast(self._learning_rate_tensor, grad.dtype), + math_ops.cast(self._l1_regularization_strength_tensor, grad.dtype), + math_ops.cast(self._l2_regularization_strength_tensor, grad.dtype), + grad, + indices, + use_locking=self._use_locking) + + def _prepare(self): + self._learning_rate_tensor = ops.convert_to_tensor(self._learning_rate, + name="learning_rate") + self._l1_regularization_strength_tensor = ops.convert_to_tensor( + self._l1_regularization_strength, name="l1_regularization_strength") + self._l2_regularization_strength_tensor = ops.convert_to_tensor( + self._l2_regularization_strength, name="l2_regularization_strength") diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/py_checkpoint_reader.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/py_checkpoint_reader.py new file mode 100644 index 0000000000000000000000000000000000000000..32d7f4ec5d1c9f53ec53c42a6e4e3f802f991a65 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/py_checkpoint_reader.py @@ -0,0 +1,96 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Extending CheckpointReader for TensorFlow.""" +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors_impl +from tensorflow.python.util import compat +from tensorflow.python.util._pywrap_checkpoint_reader import CheckpointReader +from tensorflow.python.util.tf_export import tf_export + + +def error_translator(e): + """Translate the tensor_slice_reader.cc errors.""" + # TODO(b/143319754): Remove the RuntimeError casting logic once we resolve the + # issue with throwing python exceptions from C++. + error_message = str(e) + if 'not found in checkpoint' in error_message or ( + 'Failed to find any ' + 'matching files for') in error_message: + raise errors_impl.NotFoundError(None, None, error_message) + elif 'Sliced checkpoints are not supported' in error_message or ( + 'Data type ' + 'not ' + 'supported') in error_message: + raise errors_impl.UnimplementedError(None, None, error_message) + elif 'Failed to get matching files on' in error_message: + raise errors_impl.InvalidArgumentError(None, None, error_message) + elif 'Unable to open table file' in error_message: + raise errors_impl.DataLossError(None, None, error_message) + elif 'Failed to find the saved tensor slices' in error_message or ( + 'not convertible to numpy dtype' in error_message): + raise errors_impl.InternalError(None, None, error_message) + else: + raise errors_impl.OpError(None, None, error_message, errors_impl.UNKNOWN) + + +def get_variable_to_dtype_map(self): + return { + name: dtypes.DType(type_enum) + for name, type_enum in self._GetVariableToDataTypeMap().items() # pylint: disable=protected-access + } + +CheckpointReader.get_variable_to_dtype_map = get_variable_to_dtype_map + + +def has_tensor(self, tensor_str): + return self._HasTensor(compat.as_bytes(tensor_str)) # pylint: disable=protected-access + +CheckpointReader.has_tensor = has_tensor + + +def get_tensor(self, tensor_str): + """Get the tensor from the Checkpoint object.""" + try: + return CheckpointReader.CheckpointReader_GetTensor( + self, compat.as_bytes(tensor_str)) + # TODO(b/143319754): Remove the RuntimeError casting logic once we resolve the + # issue with throwing python exceptions from C++. + except RuntimeError as e: + error_translator(e) + + +CheckpointReader.get_tensor = get_tensor + + +# Disable invalid name to keep backwards compatibility with that function. +# It was previously exported from py_checkpoint_reader.i which did not conform +# to pylint checks. +# pylint: disable=invalid-name +@tf_export(v1=['train.NewCheckpointReader']) +def NewCheckpointReader(filepattern): + """A function that returns a CheckPointReader. + + Args: + filepattern: The filename. + + Returns: + A CheckpointReader object. + """ + try: + return CheckpointReader(compat.as_bytes(filepattern)) + # TODO(b/143319754): Remove the RuntimeError casting logic once we resolve the + # issue with throwing python exceptions from C++. + except RuntimeError as e: + error_translator(e) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/quantize_training.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/quantize_training.py new file mode 100644 index 0000000000000000000000000000000000000000..66ff447d3987465087074e0971f70bc6ed6c380a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/quantize_training.py @@ -0,0 +1,46 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Quantize training for TensorFlow.""" +from tensorflow.core.framework import graph_pb2 +from tensorflow.python._pywrap_quantize_training import DoQuantizeTrainingOnGraphDefHelper +from tensorflow.python.util import deprecation +from tensorflow.python.util.tf_export import tf_export + + +# Migrated this python code from deprecated quantize_training.i +@deprecation.deprecated( + None, + "GraphDef quantized training rewriter is deprecated in the long term.") +@tf_export(v1=["train.do_quantize_training_on_graphdef"]) +def do_quantize_training_on_graphdef(input_graph, num_bits): + """A general quantization scheme is being developed in `tf.contrib.quantize`. + + Consider using that instead, though since it is in the tf.contrib namespace, + it is not subject to backward compatibility guarantees. + + Args: + input_graph: A `GraphDef`. + num_bits: The number of bits for quantize training. + + Returns: + The graph with quantize training done. + """ + + graph = graph_pb2.GraphDef() + result_graph_string = DoQuantizeTrainingOnGraphDefHelper( + input_graph.SerializeToString(), num_bits) + + graph.ParseFromString(result_graph_string) + return graph diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/queue_runner.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/queue_runner.py new file mode 100644 index 0000000000000000000000000000000000000000..c122d7dcb37fabc2dbe730bf0a4aa5ee78714c9c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/queue_runner.py @@ -0,0 +1,20 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""Create threads to run multiple enqueue ops.""" +# go/tf-wildcard-import +# pylint: disable=wildcard-import +from tensorflow.python.training.queue_runner_impl import * +# pylint: enable=wildcard-import diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/queue_runner_impl.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/queue_runner_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..5ee9d5ec5f9af601a59f3668d97936c40ece1980 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/queue_runner_impl.py @@ -0,0 +1,490 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""Create threads to run multiple enqueue ops.""" +import threading +import weakref + +from tensorflow.core.protobuf import queue_runner_pb2 +from tensorflow.python.client import session +from tensorflow.python.eager import context +from tensorflow.python.framework import errors +from tensorflow.python.framework import ops +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.util import deprecation +from tensorflow.python.util.tf_export import tf_export + +_DEPRECATION_INSTRUCTION = ( + "To construct input pipelines, use the `tf.data` module.") + + +@tf_export(v1=["train.queue_runner.QueueRunner", "train.QueueRunner"]) +class QueueRunner: + """Holds a list of enqueue operations for a queue, each to be run in a thread. + + Queues are a convenient TensorFlow mechanism to compute tensors + asynchronously using multiple threads. For example in the canonical 'Input + Reader' setup one set of threads generates filenames in a queue; a second set + of threads read records from the files, processes them, and enqueues tensors + on a second queue; a third set of threads dequeues these input records to + construct batches and runs them through training operations. + + There are several delicate issues when running multiple threads that way: + closing the queues in sequence as the input is exhausted, correctly catching + and reporting exceptions, etc. + + The `QueueRunner`, combined with the `Coordinator`, helps handle these issues. + + @compatibility(TF2) + QueueRunners are not compatible with eager execution. Instead, please + use [tf.data](https://www.tensorflow.org/guide/data) to get data into your + model. + @end_compatibility + """ + + @deprecation.deprecated(None, _DEPRECATION_INSTRUCTION) + def __init__(self, queue=None, enqueue_ops=None, close_op=None, + cancel_op=None, queue_closed_exception_types=None, + queue_runner_def=None, import_scope=None): + """Create a QueueRunner. + + On construction the `QueueRunner` adds an op to close the queue. That op + will be run if the enqueue ops raise exceptions. + + When you later call the `create_threads()` method, the `QueueRunner` will + create one thread for each op in `enqueue_ops`. Each thread will run its + enqueue op in parallel with the other threads. The enqueue ops do not have + to all be the same op, but it is expected that they all enqueue tensors in + `queue`. + + Args: + queue: A `Queue`. + enqueue_ops: List of enqueue ops to run in threads later. + close_op: Op to close the queue. Pending enqueue ops are preserved. + cancel_op: Op to close the queue and cancel pending enqueue ops. + queue_closed_exception_types: Optional tuple of Exception types that + indicate that the queue has been closed when raised during an enqueue + operation. Defaults to `(tf.errors.OutOfRangeError,)`. Another common + case includes `(tf.errors.OutOfRangeError, tf.errors.CancelledError)`, + when some of the enqueue ops may dequeue from other Queues. + queue_runner_def: Optional `QueueRunnerDef` protocol buffer. If specified, + recreates the QueueRunner from its contents. `queue_runner_def` and the + other arguments are mutually exclusive. + import_scope: Optional `string`. Name scope to add. Only used when + initializing from protocol buffer. + + Raises: + ValueError: If both `queue_runner_def` and `queue` are both specified. + ValueError: If `queue` or `enqueue_ops` are not provided when not + restoring from `queue_runner_def`. + RuntimeError: If eager execution is enabled. + """ + if context.executing_eagerly(): + raise RuntimeError( + "QueueRunners are not supported when eager execution is enabled. " + "Instead, please use tf.data to get data into your model.") + + if queue_runner_def: + if queue or enqueue_ops: + raise ValueError("queue_runner_def and queue are mutually exclusive.") + self._init_from_proto(queue_runner_def, + import_scope=import_scope) + else: + self._init_from_args( + queue=queue, enqueue_ops=enqueue_ops, + close_op=close_op, cancel_op=cancel_op, + queue_closed_exception_types=queue_closed_exception_types) + # Protect the count of runs to wait for. + self._lock = threading.Lock() + # A map from a session object to the number of outstanding queue runner + # threads for that session. + self._runs_per_session = weakref.WeakKeyDictionary() + # List of exceptions raised by the running threads. + self._exceptions_raised = [] + + def _init_from_args(self, queue=None, enqueue_ops=None, close_op=None, + cancel_op=None, queue_closed_exception_types=None): + """Create a QueueRunner from arguments. + + Args: + queue: A `Queue`. + enqueue_ops: List of enqueue ops to run in threads later. + close_op: Op to close the queue. Pending enqueue ops are preserved. + cancel_op: Op to close the queue and cancel pending enqueue ops. + queue_closed_exception_types: Tuple of exception types, which indicate + the queue has been safely closed. + + Raises: + ValueError: If `queue` or `enqueue_ops` are not provided when not + restoring from `queue_runner_def`. + TypeError: If `queue_closed_exception_types` is provided, but is not + a non-empty tuple of error types (subclasses of `tf.errors.OpError`). + """ + if not queue or not enqueue_ops: + raise ValueError("Must provide queue and enqueue_ops.") + self._queue = queue + self._enqueue_ops = enqueue_ops + self._close_op = close_op + self._cancel_op = cancel_op + if queue_closed_exception_types is not None: + if (not isinstance(queue_closed_exception_types, tuple) + or not queue_closed_exception_types + or not all(issubclass(t, errors.OpError) + for t in queue_closed_exception_types)): + raise TypeError( + "queue_closed_exception_types, when provided, " + "must be a tuple of tf.error types, but saw: %s" + % queue_closed_exception_types) + self._queue_closed_exception_types = queue_closed_exception_types + # Close when no more will be produced, but pending enqueues should be + # preserved. + if self._close_op is None: + self._close_op = self._queue.close() + # Close and cancel pending enqueues since there was an error and we want + # to unblock everything so we can cleanly exit. + if self._cancel_op is None: + self._cancel_op = self._queue.close(cancel_pending_enqueues=True) + if not self._queue_closed_exception_types: + self._queue_closed_exception_types = (errors.OutOfRangeError,) + else: + self._queue_closed_exception_types = tuple( + self._queue_closed_exception_types) + + def _init_from_proto(self, queue_runner_def, import_scope=None): + """Create a QueueRunner from `QueueRunnerDef`. + + Args: + queue_runner_def: Optional `QueueRunnerDef` protocol buffer. + import_scope: Optional `string`. Name scope to add. + """ + assert isinstance(queue_runner_def, queue_runner_pb2.QueueRunnerDef) + g = ops.get_default_graph() + self._queue = g.as_graph_element( + ops.prepend_name_scope(queue_runner_def.queue_name, import_scope)) + self._enqueue_ops = [g.as_graph_element( + ops.prepend_name_scope(op, import_scope)) + for op in queue_runner_def.enqueue_op_name] + self._close_op = g.as_graph_element(ops.prepend_name_scope( + queue_runner_def.close_op_name, import_scope)) + self._cancel_op = g.as_graph_element(ops.prepend_name_scope( + queue_runner_def.cancel_op_name, import_scope)) + self._queue_closed_exception_types = tuple( + errors.exception_type_from_error_code(code) + for code in queue_runner_def.queue_closed_exception_types) + # Legacy support for old QueueRunnerDefs created before this field + # was added. + if not self._queue_closed_exception_types: + self._queue_closed_exception_types = (errors.OutOfRangeError,) + + @property + def queue(self): + return self._queue + + @property + def enqueue_ops(self): + return self._enqueue_ops + + @property + def close_op(self): + return self._close_op + + @property + def cancel_op(self): + return self._cancel_op + + @property + def queue_closed_exception_types(self): + return self._queue_closed_exception_types + + @property + def exceptions_raised(self): + """Exceptions raised but not handled by the `QueueRunner` threads. + + Exceptions raised in queue runner threads are handled in one of two ways + depending on whether or not a `Coordinator` was passed to + `create_threads()`: + + * With a `Coordinator`, exceptions are reported to the coordinator and + forgotten by the `QueueRunner`. + * Without a `Coordinator`, exceptions are captured by the `QueueRunner` and + made available in this `exceptions_raised` property. + + Returns: + A list of Python `Exception` objects. The list is empty if no exception + was captured. (No exceptions are captured when using a Coordinator.) + """ + return self._exceptions_raised + + @property + def name(self): + """The string name of the underlying Queue.""" + return self._queue.name + + # pylint: disable=broad-except + def _run(self, sess, enqueue_op, coord=None): + """Execute the enqueue op in a loop, close the queue in case of error. + + Args: + sess: A Session. + enqueue_op: The Operation to run. + coord: Optional Coordinator object for reporting errors and checking + for stop conditions. + """ + decremented = False + try: + # Make a cached callable from the `enqueue_op` to decrease the + # Python overhead in the queue-runner loop. + enqueue_callable = sess.make_callable(enqueue_op) + while True: + if coord and coord.should_stop(): + break + try: + enqueue_callable() + except self._queue_closed_exception_types: # pylint: disable=catching-non-exception + # This exception indicates that a queue was closed. + with self._lock: + self._runs_per_session[sess] -= 1 + decremented = True + if self._runs_per_session[sess] == 0: + try: + sess.run(self._close_op) + except Exception as e: + # Intentionally ignore errors from close_op. + logging.vlog(1, "Ignored exception: %s", str(e)) + return + except Exception as e: + # This catches all other exceptions. + if coord: + coord.request_stop(e) + else: + logging.error("Exception in QueueRunner: %s", str(e)) + with self._lock: + self._exceptions_raised.append(e) + raise + finally: + # Make sure we account for all terminations: normal or errors. + if not decremented: + with self._lock: + self._runs_per_session[sess] -= 1 + + def _close_on_stop(self, sess, cancel_op, coord): + """Close the queue when the Coordinator requests stop. + + Args: + sess: A Session. + cancel_op: The Operation to run. + coord: Coordinator. + """ + coord.wait_for_stop() + try: + sess.run(cancel_op) + except Exception as e: + # Intentionally ignore errors from cancel_op. + logging.vlog(1, "Ignored exception: %s", str(e)) + # pylint: enable=broad-except + + def create_threads(self, sess, coord=None, daemon=False, start=False): + """Create threads to run the enqueue ops for the given session. + + This method requires a session in which the graph was launched. It creates + a list of threads, optionally starting them. There is one thread for each + op passed in `enqueue_ops`. + + The `coord` argument is an optional coordinator that the threads will use + to terminate together and report exceptions. If a coordinator is given, + this method starts an additional thread to close the queue when the + coordinator requests a stop. + + If previously created threads for the given session are still running, no + new threads will be created. + + Args: + sess: A `Session`. + coord: Optional `Coordinator` object for reporting errors and checking + stop conditions. + daemon: Boolean. If `True` make the threads daemon threads. + start: Boolean. If `True` starts the threads. If `False` the + caller must call the `start()` method of the returned threads. + + Returns: + A list of threads. + """ + with self._lock: + try: + if self._runs_per_session[sess] > 0: + # Already started: no new threads to return. + return [] + except KeyError: + # We haven't seen this session yet. + pass + self._runs_per_session[sess] = len(self._enqueue_ops) + self._exceptions_raised = [] + + ret_threads = [] + for op in self._enqueue_ops: + name = "QueueRunnerThread-{}-{}".format(self.name, op.name) + ret_threads.append(threading.Thread(target=self._run, + args=(sess, op, coord), + name=name)) + if coord: + name = "QueueRunnerThread-{}-close_on_stop".format(self.name) + ret_threads.append(threading.Thread(target=self._close_on_stop, + args=(sess, self._cancel_op, coord), + name=name)) + for t in ret_threads: + if coord: + coord.register_thread(t) + if daemon: + t.daemon = True + if start: + t.start() + return ret_threads + + def to_proto(self, export_scope=None): + """Converts this `QueueRunner` to a `QueueRunnerDef` protocol buffer. + + Args: + export_scope: Optional `string`. Name scope to remove. + + Returns: + A `QueueRunnerDef` protocol buffer, or `None` if the `Variable` is not in + the specified name scope. + """ + if (export_scope is None or + self.queue.name.startswith(export_scope)): + queue_runner_def = queue_runner_pb2.QueueRunnerDef() + queue_runner_def.queue_name = ops.strip_name_scope( + self.queue.name, export_scope) + for enqueue_op in self.enqueue_ops: + queue_runner_def.enqueue_op_name.append( + ops.strip_name_scope(enqueue_op.name, export_scope)) + queue_runner_def.close_op_name = ops.strip_name_scope( + self.close_op.name, export_scope) + queue_runner_def.cancel_op_name = ops.strip_name_scope( + self.cancel_op.name, export_scope) + queue_runner_def.queue_closed_exception_types.extend([ + errors.error_code_from_exception_type(cls) + for cls in self._queue_closed_exception_types]) + return queue_runner_def + else: + return None + + @staticmethod + def from_proto(queue_runner_def, import_scope=None): + """Returns a `QueueRunner` object created from `queue_runner_def`.""" + return QueueRunner(queue_runner_def=queue_runner_def, + import_scope=import_scope) + + +@tf_export(v1=["train.queue_runner.add_queue_runner", "train.add_queue_runner"]) +@deprecation.deprecated(None, _DEPRECATION_INSTRUCTION) +def add_queue_runner(qr, collection=ops.GraphKeys.QUEUE_RUNNERS): + """Adds a `QueueRunner` to a collection in the graph. + + When building a complex model that uses many queues it is often difficult to + gather all the queue runners that need to be run. This convenience function + allows you to add a queue runner to a well known collection in the graph. + + The companion method `start_queue_runners()` can be used to start threads for + all the collected queue runners. + + @compatibility(TF2) + QueueRunners are not compatible with eager execution. Instead, please + use [tf.data](https://www.tensorflow.org/guide/data) to get data into your + model. + @end_compatibility + + Args: + qr: A `QueueRunner`. + collection: A `GraphKey` specifying the graph collection to add + the queue runner to. Defaults to `GraphKeys.QUEUE_RUNNERS`. + """ + ops.add_to_collection(collection, qr) + + +@tf_export(v1=["train.queue_runner.start_queue_runners", + "train.start_queue_runners"]) +@deprecation.deprecated(None, _DEPRECATION_INSTRUCTION) +def start_queue_runners(sess=None, coord=None, daemon=True, start=True, + collection=ops.GraphKeys.QUEUE_RUNNERS): + """Starts all queue runners collected in the graph. + + This is a companion method to `add_queue_runner()`. It just starts + threads for all queue runners collected in the graph. It returns + the list of all threads. + + @compatibility(TF2) + QueueRunners are not compatible with eager execution. Instead, please + use [tf.data](https://www.tensorflow.org/guide/data) to get data into your + model. + @end_compatibility + + Args: + sess: `Session` used to run the queue ops. Defaults to the + default session. + coord: Optional `Coordinator` for coordinating the started threads. + daemon: Whether the threads should be marked as `daemons`, meaning + they don't block program exit. + start: Set to `False` to only create the threads, not start them. + collection: A `GraphKey` specifying the graph collection to + get the queue runners from. Defaults to `GraphKeys.QUEUE_RUNNERS`. + + Raises: + ValueError: if `sess` is None and there isn't any default session. + TypeError: if `sess` is not a `tf.compat.v1.Session` object. + + Returns: + A list of threads. + + Raises: + RuntimeError: If called with eager execution enabled. + ValueError: If called without a default `tf.compat.v1.Session` registered. + """ + if context.executing_eagerly(): + raise RuntimeError("Queues are not compatible with eager execution.") + if sess is None: + sess = ops.get_default_session() + if not sess: + raise ValueError("Cannot start queue runners: No default session is " + "registered. Use `with sess.as_default()` or pass an " + "explicit session to tf.start_queue_runners(sess=sess)") + + if not isinstance(sess, session.SessionInterface): + # Following check is due to backward compatibility. (b/62061352) + if sess.__class__.__name__ in [ + "MonitoredSession", "SingularMonitoredSession"]: + return [] + raise TypeError("sess must be a `tf.Session` object. " + "Given class: {}".format(sess.__class__)) + + queue_runners = ops.get_collection(collection) + if not queue_runners: + logging.warning( + "`tf.train.start_queue_runners()` was called when no queue runners " + "were defined. You can safely remove the call to this deprecated " + "function.") + + with sess.graph.as_default(): + threads = [] + for qr in ops.get_collection(collection): + threads.extend(qr.create_threads(sess, coord=coord, daemon=daemon, + start=start)) + return threads + + +ops.register_proto_function(ops.GraphKeys.QUEUE_RUNNERS, + proto_type=queue_runner_pb2.QueueRunnerDef, + to_proto=QueueRunner.to_proto, + from_proto=QueueRunner.from_proto) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/rmsprop.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/rmsprop.py new file mode 100644 index 0000000000000000000000000000000000000000..c20ea36d946228da45517e5d3abdcfc1bc3dbaf7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/rmsprop.py @@ -0,0 +1,323 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""One-line documentation for rmsprop module. + +rmsprop algorithm [tieleman2012rmsprop] + +A detailed description of rmsprop. + +- maintain a moving (discounted) average of the square of gradients +- divide gradient by the root of this average + +mean_square = decay * mean_square{t-1} + (1-decay) * gradient ** 2 +mom = momentum * mom{t-1} + learning_rate * g_t / sqrt(mean_square + epsilon) +delta = - mom + +This implementation of RMSProp uses plain momentum, not Nesterov momentum. + +The centered version additionally maintains a moving (discounted) average of the +gradients, and uses that average to estimate the variance: + +mean_grad = decay * mean_grad{t-1} + (1-decay) * gradient +mean_square = decay * mean_square{t-1} + (1-decay) * gradient ** 2 +mom = momentum * mom{t-1} + learning_rate * g_t / + sqrt(mean_square - mean_grad**2 + epsilon) +delta = - mom +""" + +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import init_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.training import optimizer +from tensorflow.python.training import training_ops +from tensorflow.python.util.tf_export import tf_export + + +@tf_export(v1=["train.RMSPropOptimizer"]) +class RMSPropOptimizer(optimizer.Optimizer): + """Optimizer that implements the RMSProp algorithm (Tielemans et al. + + 2012). + + References: + Coursera slide 29: + Hinton, 2012 + ([pdf](http://www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf)) + + @compatibility(TF2) + tf.compat.v1.train.RMSPropOptimizer is compatible with eager mode and + `tf.function`. + When eager execution is enabled, `learning_rate`, `decay`, `momentum`, + and `epsilon` can each be a callable that + takes no arguments and returns the actual value to use. This can be useful + for changing these values across different invocations of optimizer + functions. + + To switch to native TF2 style, use [`tf.keras.optimizers.RMSprop`] + (https://www.tensorflow.org/api_docs/python/tf/keras/optimizers/RMSprop) + instead. Please notice that due to the implementation differences, + `tf.keras.optimizers.RMSprop` and + `tf.compat.v1.train.RMSPropOptimizer` may have slight differences in + floating point numerics even though the formula used for the variable + updates still matches. + + #### Structural mapping to native TF2 + + Before: + + ```python + optimizer = tf.compat.v1.train.RMSPropOptimizer( + learning_rate=learning_rate, + decay=decay, + momentum=momentum, + epsilon=epsilon) + ``` + + After: + + ```python + optimizer = tf.keras.optimizers.RMSprop( + learning_rate=learning_rate, + rho=decay, + momentum=momentum, + epsilon=epsilon) + ``` + + #### How to map arguments + | TF1 Arg Name | TF2 Arg Name | Note | + | ------------------ | ------------- | ------------------------------- | + | `learning_rate` | `learning_rate`| Be careful of setting | + : : : learning_rate tensor value computed from the global step. : + : : : In TF1 this was usually meant to imply a dynamic learning rate and : + : : : would recompute in each step. In TF2 (eager + function) it will : + : : : treat it as a scalar value that only gets computed once instead of : + : : : a symbolic placeholder to be computed each time. : + | `decay` | `rho` | - | + | `momentum` | `momentum` | - | + | `epsilon` | `epsilon` | Default value is 1e-10 in TF1, | + : : : but 1e-07 in TF2. : + | `use_locking` | - | Not applicable in TF2. | + + #### Before & after usage example + Before: + + ```python + x = tf.Variable([1,2,3], dtype=tf.float32) + grad = tf.constant([0.1, 0.2, 0.3]) + optimizer = tf.compat.v1.train.RMSPropOptimizer(learning_rate=0.001) + optimizer.apply_gradients(zip([grad], [x])) + ``` + + After: + + ```python + x = tf.Variable([1,2,3], dtype=tf.float32) + grad = tf.constant([0.1, 0.2, 0.3]) + optimizer = tf.keras.optimizers.RMSprop(learning_rate=0.001) + optimizer.apply_gradients(zip([grad], [x])) + ``` + + @end_compatibility + """ + + def __init__(self, + learning_rate, + decay=0.9, + momentum=0.0, + epsilon=1e-10, + use_locking=False, + centered=False, + name="RMSProp"): + """Construct a new RMSProp optimizer. + + Note that in the dense implementation of this algorithm, variables and their + corresponding accumulators (momentum, gradient moving average, square + gradient moving average) will be updated even if the gradient is zero + (i.e. accumulators will decay, momentum will be applied). The sparse + implementation (used when the gradient is an `IndexedSlices` object, + typically because of `tf.gather` or an embedding lookup in the forward pass) + will not update variable slices or their accumulators unless those slices + were used in the forward pass (nor is there an "eventual" correction to + account for these omitted updates). This leads to more efficient updates for + large embedding lookup tables (where most of the slices are not accessed in + a particular graph execution), but differs from the published algorithm. + + Args: + learning_rate: A Tensor or a floating point value. The learning rate. + decay: Discounting factor for the history/coming gradient + momentum: A scalar tensor. + epsilon: Small value to avoid zero denominator. + use_locking: If True use locks for update operation. + centered: If True, gradients are normalized by the estimated variance of + the gradient; if False, by the uncentered second moment. Setting this to + True may help with training, but is slightly more expensive in terms of + computation and memory. Defaults to False. + name: Optional name prefix for the operations created when applying + gradients. Defaults to "RMSProp". + + """ + super(RMSPropOptimizer, self).__init__(use_locking, name) + self._learning_rate = learning_rate + self._decay = decay + self._momentum = momentum + self._epsilon = epsilon + self._centered = centered + + # Tensors for learning rate and momentum. Created in _prepare. + self._learning_rate_tensor = None + self._decay_tensor = None + self._momentum_tensor = None + self._epsilon_tensor = None + + def _create_slots(self, var_list): + for v in var_list: + if v.get_shape().is_fully_defined(): + init_rms = init_ops.ones_initializer(dtype=v.dtype.base_dtype) + else: + init_rms = array_ops.ones_like(v) + self._get_or_make_slot_with_initializer(v, init_rms, v.get_shape(), + v.dtype.base_dtype, "rms", + self._name) + if self._centered: + self._zeros_slot(v, "mg", self._name) + self._zeros_slot(v, "momentum", self._name) + + def _prepare(self): + lr = self._call_if_callable(self._learning_rate) + decay = self._call_if_callable(self._decay) + momentum = self._call_if_callable(self._momentum) + epsilon = self._call_if_callable(self._epsilon) + + self._learning_rate_tensor = ops.convert_to_tensor(lr, name="learning_rate") + self._decay_tensor = ops.convert_to_tensor(decay, name="decay") + self._momentum_tensor = ops.convert_to_tensor(momentum, name="momentum") + self._epsilon_tensor = ops.convert_to_tensor(epsilon, name="epsilon") + + def _apply_dense(self, grad, var): + rms = self.get_slot(var, "rms") + mom = self.get_slot(var, "momentum") + if self._centered: + mg = self.get_slot(var, "mg") + return training_ops.apply_centered_rms_prop( + var, + mg, + rms, + mom, + math_ops.cast(self._learning_rate_tensor, var.dtype.base_dtype), + math_ops.cast(self._decay_tensor, var.dtype.base_dtype), + math_ops.cast(self._momentum_tensor, var.dtype.base_dtype), + math_ops.cast(self._epsilon_tensor, var.dtype.base_dtype), + grad, + use_locking=self._use_locking).op + else: + return training_ops.apply_rms_prop( + var, + rms, + mom, + math_ops.cast(self._learning_rate_tensor, var.dtype.base_dtype), + math_ops.cast(self._decay_tensor, var.dtype.base_dtype), + math_ops.cast(self._momentum_tensor, var.dtype.base_dtype), + math_ops.cast(self._epsilon_tensor, var.dtype.base_dtype), + grad, + use_locking=self._use_locking).op + + def _resource_apply_dense(self, grad, var): + rms = self.get_slot(var, "rms") + mom = self.get_slot(var, "momentum") + if self._centered: + mg = self.get_slot(var, "mg") + return training_ops.resource_apply_centered_rms_prop( + var.handle, + mg.handle, + rms.handle, + mom.handle, + math_ops.cast(self._learning_rate_tensor, grad.dtype.base_dtype), + math_ops.cast(self._decay_tensor, grad.dtype.base_dtype), + math_ops.cast(self._momentum_tensor, grad.dtype.base_dtype), + math_ops.cast(self._epsilon_tensor, grad.dtype.base_dtype), + grad, + use_locking=self._use_locking) + else: + return training_ops.resource_apply_rms_prop( + var.handle, + rms.handle, + mom.handle, + math_ops.cast(self._learning_rate_tensor, grad.dtype.base_dtype), + math_ops.cast(self._decay_tensor, grad.dtype.base_dtype), + math_ops.cast(self._momentum_tensor, grad.dtype.base_dtype), + math_ops.cast(self._epsilon_tensor, grad.dtype.base_dtype), + grad, + use_locking=self._use_locking) + + def _apply_sparse(self, grad, var): + rms = self.get_slot(var, "rms") + mom = self.get_slot(var, "momentum") + if self._centered: + mg = self.get_slot(var, "mg") + return training_ops.sparse_apply_centered_rms_prop( + var, + mg, + rms, + mom, + math_ops.cast(self._learning_rate_tensor, var.dtype.base_dtype), + math_ops.cast(self._decay_tensor, var.dtype.base_dtype), + math_ops.cast(self._momentum_tensor, var.dtype.base_dtype), + math_ops.cast(self._epsilon_tensor, var.dtype.base_dtype), + grad.values, + grad.indices, + use_locking=self._use_locking) + else: + return training_ops.sparse_apply_rms_prop( + var, + rms, + mom, + math_ops.cast(self._learning_rate_tensor, var.dtype.base_dtype), + math_ops.cast(self._decay_tensor, var.dtype.base_dtype), + math_ops.cast(self._momentum_tensor, var.dtype.base_dtype), + math_ops.cast(self._epsilon_tensor, var.dtype.base_dtype), + grad.values, + grad.indices, + use_locking=self._use_locking) + + def _resource_apply_sparse(self, grad, var, indices): + rms = self.get_slot(var, "rms") + mom = self.get_slot(var, "momentum") + if self._centered: + mg = self.get_slot(var, "mg") + return training_ops.resource_sparse_apply_centered_rms_prop( + var.handle, + mg.handle, + rms.handle, + mom.handle, + math_ops.cast(self._learning_rate_tensor, grad.dtype), + math_ops.cast(self._decay_tensor, grad.dtype), + math_ops.cast(self._momentum_tensor, grad.dtype), + math_ops.cast(self._epsilon_tensor, grad.dtype), + grad, + indices, + use_locking=self._use_locking) + else: + return training_ops.resource_sparse_apply_rms_prop( + var.handle, + rms.handle, + mom.handle, + math_ops.cast(self._learning_rate_tensor, grad.dtype), + math_ops.cast(self._decay_tensor, grad.dtype), + math_ops.cast(self._momentum_tensor, grad.dtype), + math_ops.cast(self._epsilon_tensor, grad.dtype), + grad, + indices, + use_locking=self._use_locking) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/saver.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/saver.py new file mode 100644 index 0000000000000000000000000000000000000000..4fa6c57f37fcf5530ec40c46c33fa6a9a2e67947 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/saver.py @@ -0,0 +1,1854 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +# pylint: disable=invalid-name +"""Save and restore variables. + +Symbols in this file are deprecated. See replacements in +tensorflow/python/training/trackable and tensorflow/python/training/saving. +""" +import collections +import glob +import os.path +import threading +import time + +import numpy as np +from tensorflow.core.protobuf import meta_graph_pb2 +from tensorflow.core.protobuf import saver_pb2 +from tensorflow.core.protobuf import trackable_object_graph_pb2 +from tensorflow.python.checkpoint import checkpoint_management +from tensorflow.python.client import session +from tensorflow.python.eager import context +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import device as pydev +from tensorflow.python.framework import errors +from tensorflow.python.framework import meta_graph +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import gen_io_ops +from tensorflow.python.ops import io_ops +from tensorflow.python.ops import string_ops +from tensorflow.python.ops import variables +from tensorflow.python.platform import gfile +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.saved_model.pywrap_saved_model import metrics +from tensorflow.python.trackable import base as trackable +from tensorflow.python.training import py_checkpoint_reader +from tensorflow.python.training import training_util +from tensorflow.python.training.saving import saveable_object +from tensorflow.python.training.saving import saveable_object_util +from tensorflow.python.util import compat +from tensorflow.python.util.tf_export import tf_export + +# TODO(allenl): Remove these aliases once all users are migrated off. +get_checkpoint_state = checkpoint_management.get_checkpoint_state +update_checkpoint_state = checkpoint_management.update_checkpoint_state +generate_checkpoint_state_proto = ( + checkpoint_management.generate_checkpoint_state_proto) +latest_checkpoint = checkpoint_management.latest_checkpoint +checkpoint_exists = checkpoint_management.checkpoint_exists +get_checkpoint_mtimes = checkpoint_management.get_checkpoint_mtimes +remove_checkpoint = checkpoint_management.remove_checkpoint + +# Captures the timestamp of the first Saver object instantiation or end of a +# save operation. Can be accessed by multiple Saver instances. +_END_TIME_OF_LAST_WRITE = None +_END_TIME_OF_LAST_WRITE_LOCK = threading.Lock() + +# API label for cell name used in checkpoint metrics. +_SAVER_LABEL = "saver_v1" + + +def _get_duration_microseconds(start_time_seconds, end_time_seconds): + if end_time_seconds < start_time_seconds: + # Avoid returning negative value in case of clock skew. + return 0 + return round((end_time_seconds - start_time_seconds) * 1000000) + + +def _get_checkpoint_size(prefix): + """Calculates filesize of checkpoint based on prefix.""" + size = 0 + # Gather all files beginning with prefix (.index plus sharded data files). + files = glob.glob("{}*".format(prefix)) + for file in files: + # Use TensorFlow's C++ FileSystem API. + size += metrics.CalculateFileSize(file) + return size + + +class BaseSaverBuilder: + """Base class for Savers. + + Can be extended to create different Ops. + """ + + SaveSpec = saveable_object.SaveSpec + SaveableObject = saveable_object.SaveableObject + + # Aliases for code which was moved but still has lots of users. + VariableSaveable = saveable_object_util.ReferenceVariableSaveable + ResourceVariableSaveable = saveable_object_util.ResourceVariableSaveable + + def __init__(self, write_version=saver_pb2.SaverDef.V2): + self._write_version = write_version + + def save_op(self, filename_tensor, saveables): + """Create an Op to save 'saveables'. + + This is intended to be overridden by subclasses that want to generate + different Ops. + + Args: + filename_tensor: String Tensor. + saveables: A list of BaseSaverBuilder.SaveableObject objects. + + Returns: + An Operation that save the variables. + + Raises: + RuntimeError: (implementation detail) if "self._write_version" is an + unexpected value. + """ + # pylint: disable=protected-access + tensor_names = [] + tensors = [] + tensor_slices = [] + for saveable in saveables: + for spec in saveable.specs: + tensor_names.append(spec.name) + tensors.append(spec.tensor) + tensor_slices.append(spec.slice_spec) + if self._write_version == saver_pb2.SaverDef.V1: + return io_ops._save( + filename=filename_tensor, + tensor_names=tensor_names, + tensors=tensors, + tensor_slices=tensor_slices) + elif self._write_version == saver_pb2.SaverDef.V2: + # "filename_tensor" is interpreted *NOT AS A FILENAME*, but as a prefix + # of a V2 checkpoint: e.g. "/fs/train/ckpt-/tmp/worker-". + return io_ops.save_v2(filename_tensor, tensor_names, tensor_slices, + tensors) + else: + raise RuntimeError("Unexpected write_version: " + self._write_version) + + def bulk_restore(self, filename_tensor, saveables, preferred_shard, + restore_sequentially): + """Restore all tensors contained in saveables. + + By default, this issues separate calls to `restore_op` for each saveable. + Subclasses may override to load multiple saveables in a single call. + + Args: + filename_tensor: String Tensor. + saveables: List of BaseSaverBuilder.SaveableObject objects. + preferred_shard: Int. Shard to open first when loading a sharded file. + restore_sequentially: Unused. Bool. If true, each restore is sequential. + + Returns: + A list of Tensors resulting from reading 'saveable' from + 'filename'. + + """ + del restore_sequentially + all_tensors = [] + for saveable in saveables: + if saveable.device: + device = saveable_object_util.set_cpu0(saveable.device) + else: + device = None + with ops.device(device): + all_tensors.extend( + self.restore_op(filename_tensor, saveable, preferred_shard)) + return all_tensors + + # pylint: disable=unused-argument + def restore_op(self, filename_tensor, saveable, preferred_shard): + """Create ops to restore 'saveable'. + + This is intended to be overridden by subclasses that want to generate + different Ops. + + Args: + filename_tensor: String Tensor. + saveable: A BaseSaverBuilder.SaveableObject object. + preferred_shard: Int. Shard to open first when loading a sharded file. + + Returns: + A list of Tensors resulting from reading 'saveable' from + 'filename'. + """ + # pylint: disable=protected-access + tensors = [] + for spec in saveable.specs: + tensors.append( + io_ops.restore_v2(filename_tensor, [spec.name], [spec.slice_spec], + [spec.dtype])[0]) + + return tensors + + # pylint: enable=unused-argument + + def sharded_filename(self, filename_tensor, shard, num_shards): + """Append sharding information to a filename. + + Args: + filename_tensor: A string tensor. + shard: Integer. The shard for the filename. + num_shards: An int Tensor for the number of shards. + + Returns: + A string tensor. + """ + return gen_io_ops.sharded_filename(filename_tensor, shard, num_shards) + + def _AddSaveOps(self, filename_tensor, saveables): + """Add ops to save variables that are on the same shard. + + Args: + filename_tensor: String Tensor. + saveables: A list of SaveableObject objects. + + Returns: + A tensor with the filename used to save. + """ + save = self.save_op(filename_tensor, saveables) + return control_flow_ops.with_dependencies([save], filename_tensor) + + def _AddShardedSaveOpsForV2(self, checkpoint_prefix, per_device): + """Add ops to save the params per shard, for the V2 format. + + Note that the sharded save procedure for the V2 format is different from + V1: there is a special "merge" step that merges the small metadata produced + from each device. + + Args: + checkpoint_prefix: scalar String Tensor. Interpreted *NOT AS A FILENAME*, + but as a prefix of a V2 checkpoint; + per_device: A list of (device, BaseSaverBuilder.VarToSave) pairs, as + returned by _GroupByDevices(). + + Returns: + An op to save the variables, which, when evaluated, returns the prefix + "" only and does not include the sharded spec suffix. + """ + # IMPLEMENTATION DETAILS: most clients should skip. + # + # Suffix for any well-formed "checkpoint_prefix", when sharded. + # Transformations: + # * Users pass in "save_path" in save() and restore(). Say "myckpt". + # * checkpoint_prefix gets fed <_SHARDED_SUFFIX>. + # * If checkpoint_prefix is a S3 bucket path ".part" is appended to it + # * Otherwise _temp/part is appended which is normalized relative to the OS + # Example: + # During runtime, a temporary directory is first created, which contains + # files + # + # /myckpt_temp/ + # part-?????-of-?????{.index, .data-00000-of-00001} + # + # Before .save() finishes, they will be (hopefully, atomically) renamed to + # + # / + # myckpt{.index, .data-?????-of-?????} + # + # Filesystems with eventual consistency (such as S3), don't need a + # temporary location. Using a temporary directory in those cases might + # cause situations where files are not available during copy. + # + # Users only need to interact with the user-specified prefix, which is + # "/myckpt" in this case. Save() and Restore() work with the + # prefix directly, instead of any physical pathname. (On failure and + # subsequent restore, an outdated and orphaned temporary directory can be + # safely removed.) + with ops.device("CPU"): + _SHARDED_SUFFIX = array_ops.where( + string_ops.regex_full_match(checkpoint_prefix, "^s3://.*"), + constant_op.constant(".part"), + constant_op.constant(os.path.normpath("_temp/part"))) + tmp_checkpoint_prefix = string_ops.string_join( + [checkpoint_prefix, _SHARDED_SUFFIX]) + + num_shards = len(per_device) + sharded_saves = [] + sharded_prefixes = [] + num_shards_tensor = constant_op.constant(num_shards, name="num_shards") + last_device = None + for shard, (device, saveables) in enumerate(per_device): + last_device = device + with ops.device(saveable_object_util.set_cpu0(device)): + sharded_filename = self.sharded_filename(tmp_checkpoint_prefix, shard, + num_shards_tensor) + sharded_prefixes.append(sharded_filename) + sharded_saves.append(self._AddSaveOps(sharded_filename, saveables)) + + with ops.control_dependencies([x.op for x in sharded_saves]): + # Co-locates the merge step with the last device. + with ops.device(saveable_object_util.set_cpu0(last_device)): + # V2 format write path consists of a metadata merge step. Once merged, + # attempts to delete the temporary directory, "_temp". + merge_step = gen_io_ops.merge_v2_checkpoints( + sharded_prefixes, checkpoint_prefix, delete_old_dirs=True) + with ops.control_dependencies([merge_step]): + # Returns the prefix "" only. DOES NOT include the + # sharded spec suffix. + return array_ops.identity(checkpoint_prefix) + + def _AddShardedSaveOps(self, filename_tensor, per_device): + """Add ops to save the params per shard. + + Args: + filename_tensor: a scalar String Tensor. + per_device: A list of (device, BaseSaverBuilder.SaveableObject) pairs, as + returned by _GroupByDevices(). + + Returns: + An op to save the variables. + """ + if self._write_version == saver_pb2.SaverDef.V2: + return self._AddShardedSaveOpsForV2(filename_tensor, per_device) + + num_shards = len(per_device) + sharded_saves = [] + num_shards_tensor = constant_op.constant(num_shards, name="num_shards") + for shard, (device, saveables) in enumerate(per_device): + with ops.device(device): + sharded_filename = self.sharded_filename(filename_tensor, shard, + num_shards_tensor) + sharded_saves.append(self._AddSaveOps(sharded_filename, saveables)) + # Return the sharded name for the save path. + with ops.control_dependencies([x.op for x in sharded_saves]): + return gen_io_ops.sharded_filespec(filename_tensor, num_shards_tensor) + + def _AddRestoreOps(self, + filename_tensor, + saveables, + restore_sequentially, + reshape, + preferred_shard=-1, + name="restore_all"): + """Add operations to restore saveables. + + Args: + filename_tensor: Tensor for the path of the file to load. + saveables: A list of SaveableObject objects. + restore_sequentially: True if we want to restore variables sequentially + within a shard. + reshape: True if we want to reshape loaded tensors to the shape of the + corresponding variable. + preferred_shard: Shard to open first when loading a sharded file. + name: Name for the returned op. + + Returns: + An Operation that restores the variables. + """ + all_tensors = self.bulk_restore(filename_tensor, saveables, preferred_shard, + restore_sequentially) + + assign_ops = [] + idx = 0 + # Load and optionally reshape on the CPU, as string tensors are not + # available on the GPU. + # TODO(touts): Re-enable restore on GPU when we can support annotating + # string tensors as "HostMemory" inputs. + for saveable in saveables: + shapes = None + if reshape: + # Compute the shapes, let the restore op decide if and how to do + # the reshape. + shapes = [] + for spec in saveable.specs: + v = spec.tensor + shape = v.get_shape() + if not shape.is_fully_defined(): + shape = array_ops.shape(v) + shapes.append(shape) + saveable_tensors = all_tensors[idx:idx + len(saveable.specs)] + idx += len(saveable.specs) + assign_ops.append(saveable.restore(saveable_tensors, shapes)) + + # Create a Noop that has control dependencies from all the updates. + return control_flow_ops.group(*assign_ops, name=name) + + def _AddShardedRestoreOps(self, filename_tensor, per_device, + restore_sequentially, reshape): + """Add Ops to restore variables from multiple devices. + + Args: + filename_tensor: Tensor for the path of the file to load. + per_device: A list of (device, SaveableObject) pairs, as returned by + _GroupByDevices(). + restore_sequentially: True if we want to restore variables sequentially + within a shard. + reshape: True if we want to reshape loaded tensors to the shape of the + corresponding variable. + + Returns: + An Operation that restores the variables. + """ + sharded_restores = [] + for shard, (device, saveables) in enumerate(per_device): + with ops.device(device): + sharded_restores.append( + self._AddRestoreOps( + filename_tensor, + saveables, + restore_sequentially, + reshape, + preferred_shard=shard, + name="restore_shard")) + return control_flow_ops.group(*sharded_restores, name="restore_all") + + def _GroupByDevices(self, saveables): + """Group Variable tensor slices per device. + + TODO(touts): Make sure that all the devices found are on different + job/replica/task/cpu|gpu. It would be bad if 2 were on the same device. + It can happen if the devices are unspecified. + + Args: + saveables: A list of BaseSaverBuilder.SaveableObject objects. + + Returns: + A list of tuples: (device_name, BaseSaverBuilder.SaveableObject) tuples. + The list is sorted by ascending device_name. + + Raises: + ValueError: If the tensors of a saveable are on different devices. + """ + per_device = collections.defaultdict(lambda: []) + for saveable in saveables: + canonical_device = set( + pydev.canonical_name(spec.device) for spec in saveable.specs) + if len(canonical_device) != 1: + raise ValueError("All tensors of a saveable object must be " + "on the same device: %s" % saveable.name) + per_device[canonical_device.pop()].append(saveable) + return sorted(per_device.items(), key=lambda t: t[0]) + + def build(self, + names_to_saveables, + reshape=False, + sharded=False, + max_to_keep=5, + keep_checkpoint_every_n_hours=10000.0, + name=None, + restore_sequentially=False, + filename="model"): + """Builds save/restore graph nodes or runs save/restore in eager mode. + + Args: + names_to_saveables: A dictionary mapping name to a Variable or + SaveableObject. Each name will be associated with the corresponding + variable in the checkpoint. + reshape: If True, allow restoring parameters from a checkpoint that where + the parameters have a different shape. This is only needed when you try + to restore from a Dist-Belief checkpoint, and only some times. + sharded: If True, shard the checkpoints, one per device that has Variable + nodes. + max_to_keep: Maximum number of checkpoints to keep. As new checkpoints + are created, old ones are deleted. If None or 0, no checkpoints are + deleted from the filesystem but only the last one is kept in the + `checkpoint` file. Presently the number is only roughly enforced. For + example in case of restarts more than max_to_keep checkpoints may be + kept. + keep_checkpoint_every_n_hours: How often checkpoints should be kept. + Defaults to 10,000 hours. + name: String. Optional name to use as a prefix when adding operations. + restore_sequentially: A Bool, which if true, causes restore of different + variables to happen sequentially within each device. + filename: If known at graph construction time, filename used for variable + loading/saving. If None, then the default name "model" will be used. + + Returns: + A SaverDef proto. + + Raises: + TypeError: If 'names_to_saveables' is not a dictionary mapping string + keys to variable Tensors. + ValueError: If any of the keys or values in 'names_to_saveables' is not + unique. + """ + return self._build_internal( + names_to_saveables=names_to_saveables, + reshape=reshape, + sharded=sharded, + max_to_keep=max_to_keep, + keep_checkpoint_every_n_hours=keep_checkpoint_every_n_hours, + name=name, + restore_sequentially=restore_sequentially, + filename=filename) + + def _build_internal(self, + names_to_saveables, + reshape=False, + sharded=False, + max_to_keep=5, + keep_checkpoint_every_n_hours=10000.0, + name=None, + restore_sequentially=False, + filename="model", + build_save=True, + build_restore=True): + """build() with option to only perform save and restore.""" + if not context.executing_eagerly() and (not build_save or + not build_restore): + raise ValueError("save and restore operations need to be built together " + " when eager execution is not enabled.") + + if not isinstance(names_to_saveables, dict): + names_to_saveables = saveable_object_util.op_list_to_dict( + names_to_saveables) + saveables = saveable_object_util.validate_and_slice_inputs( + names_to_saveables) + if max_to_keep is None: + max_to_keep = 0 + + with ops.name_scope(name, "save", + [saveable.op for saveable in saveables]) as name: + # Add a placeholder string tensor for the filename. + filename_tensor = array_ops.placeholder_with_default( + filename or "model", shape=(), name="filename") + # Keep the name "Const" for backwards compatibility. + filename_tensor = array_ops.placeholder_with_default( + filename_tensor, shape=(), name="Const") + + # Add the save ops. + if sharded: + per_device = self._GroupByDevices(saveables) + if build_save: + save_tensor = self._AddShardedSaveOps(filename_tensor, per_device) + if build_restore: + restore_op = self._AddShardedRestoreOps(filename_tensor, per_device, + restore_sequentially, reshape) + else: + if build_save: + save_tensor = self._AddSaveOps(filename_tensor, saveables) + if build_restore: + restore_op = self._AddRestoreOps(filename_tensor, saveables, + restore_sequentially, reshape) + + # In the following use case, it's possible to have restore_ops be called + # something else: + # - Build inference graph and export a meta_graph. + # - Import the inference meta_graph + # - Extend the inference graph to a train graph. + # - Export a new meta_graph. + # Now the second restore_op will be called "restore_all_1". + # As such, comment out the assert for now until we know whether supporting + # such usage model makes sense. + # + # assert restore_op.name.endswith("restore_all"), restore_op.name + if context.executing_eagerly(): + # Store the tensor values to the tensor_names. + save_tensor_name = save_tensor.numpy() if build_save else "" + return saver_pb2.SaverDef( + filename_tensor_name=filename_tensor.numpy(), + save_tensor_name=save_tensor_name, + restore_op_name="", + max_to_keep=max_to_keep, + sharded=sharded, + keep_checkpoint_every_n_hours=keep_checkpoint_every_n_hours, + version=self._write_version) + else: + graph = ops.get_default_graph() + # Do some sanity checking on collections containing + # PartitionedVariables. If a saved collection has a PartitionedVariable, + # the GraphDef needs to include concat ops to get the value (or there'll + # be a lookup error on load). + check_collection_list = graph.get_all_collection_keys() + for collection_type in check_collection_list: + for element in graph.get_collection(collection_type): + if isinstance(element, variables.PartitionedVariable): + try: + graph.get_operation_by_name(element.name) + except KeyError: + # Create a concat op for this PartitionedVariable. The user may + # not need it, but we'll try looking it up on MetaGraph restore + # since it's in a collection. + element.as_tensor() + return saver_pb2.SaverDef( + filename_tensor_name=filename_tensor.name, + save_tensor_name=save_tensor.name, + restore_op_name=restore_op.name, + max_to_keep=max_to_keep, + sharded=sharded, + keep_checkpoint_every_n_hours=keep_checkpoint_every_n_hours, + version=self._write_version) + + +class BulkSaverBuilder(BaseSaverBuilder): + """SaverBuilder with support for bulk restoring multiple saveables.""" + + def bulk_restore(self, filename_tensor, saveables, preferred_shard, + restore_sequentially): + + # Ignored: bulk restore is internally sequential. + del restore_sequentially + restore_specs = [] + for saveable in saveables: + for spec in saveable.specs: + restore_specs.append((spec.name, spec.slice_spec, spec.dtype)) + + names, slices, dtypes = zip(*restore_specs) + # Load all tensors onto CPU 0 for compatibility with existing code. + with ops.device("cpu:0"): + return io_ops.restore_v2(filename_tensor, names, slices, dtypes) + + +def _get_saver_or_default(): + """Returns the saver from SAVERS collection, or creates a default one. + + This method is used by other members of the training module, such as + `Scaffold`, or `CheckpointSaverHook`. + + Returns: + `Saver`. + + Raises: + RuntimeError: If the SAVERS collection already has more than one items. + """ + collection_key = ops.GraphKeys.SAVERS + savers = ops.get_collection(collection_key) + if savers: + if len(savers) > 1: + raise RuntimeError( + "More than one item in collection {}. " + "Please indicate which one to use by passing it to the constructor." + .format(collection_key)) + return savers[0] + saver = Saver(sharded=True, allow_empty=True) + if saver is not None: + ops.add_to_collection(collection_key, saver) + return saver + + +@tf_export(v1=["train.Saver"]) +class Saver: + # pylint: disable=line-too-long + """Saves and restores variables. + + @compatibility(TF2) + `tf.compat.v1.train.Saver` is not supported for saving and restoring + checkpoints in TF2. Please switch to `tf.train.Checkpoint` or + `tf.keras.Model.save_weights`, which perform a more robust [object-based + saving](https://www.tensorflow.org/guide/checkpoint#loading_mechanics). + + ### How to Rewrite Checkpoints + + Please rewrite your checkpoints immediately using the object-based checkpoint + APIs. + + You can load a name-based checkpoint written by `tf.compat.v1.train.Saver` + using `tf.train.Checkpoint.restore` or `tf.keras.Model.load_weights`. However, + you may have to change the names of the variables in your model to match the + variable names in the name-based checkpoint, which can be viewed with + `tf.train.list_variables(path)`. + + Another option is to create an `assignment_map` that maps the name of the + variables in the name-based checkpoint to the variables in your model, eg: + ``` + { + 'sequential/dense/bias': model.variables[0], + 'sequential/dense/kernel': model.variables[1] + } + ``` + and use `tf.compat.v1.train.init_from_checkpoint(path, assignment_map)` to + restore the name-based checkpoint. + + After restoring, re-encode your checkpoint + using `tf.train.Checkpoint.save` or `tf.keras.Model.save_weights`. + + See the [Checkpoint compatibility]( + https://www.tensorflow.org/guide/migrate#checkpoint_compatibility) + section of the migration guide for more details. + + + ### Checkpoint Management in TF2 + + Use `tf.train.CheckpointManager` to manage checkpoints in TF2. + `tf.train.CheckpointManager` offers equivalent `keep_checkpoint_every_n_hours` + and `max_to_keep` parameters. + + To recover the latest checkpoint, + + ``` + checkpoint = tf.train.Checkpoint(model) + manager = tf.train.CheckpointManager(checkpoint) + status = checkpoint.restore(manager.latest_checkpoint) + ``` + + `tf.train.CheckpointManager` also writes a [`CheckpointState` proto] + (https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/training/checkpoint_state.proto) + which contains the timestamp when each checkpoint was created. + + ### Writing `MetaGraphDef`s in TF2 + + To replace, `tf.compat.v1.train.Saver.save(write_meta_graph=True)`, use + `tf.saved_model.save` to write the `MetaGraphDef` (which is contained in + `saved_model.pb`). + + @end_compatibility + + See [Variables](https://tensorflow.org/guide/variables) + for an overview of variables, saving and restoring. + + The `Saver` class adds ops to save and restore variables to and from + *checkpoints*. It also provides convenience methods to run these ops. + + Checkpoints are binary files in a proprietary format which map variable names + to tensor values. The best way to examine the contents of a checkpoint is to + load it using a `Saver`. + + Savers can automatically number checkpoint filenames with a provided counter. + This lets you keep multiple checkpoints at different steps while training a + model. For example you can number the checkpoint filenames with the training + step number. To avoid filling up disks, savers manage checkpoint files + automatically. For example, they can keep only the N most recent files, or + one checkpoint for every N hours of training. + + You number checkpoint filenames by passing a value to the optional + `global_step` argument to `save()`: + + ```python + saver.save(sess, 'my-model', global_step=0) ==> filename: 'my-model-0' + ... + saver.save(sess, 'my-model', global_step=1000) ==> filename: 'my-model-1000' + ``` + + Additionally, optional arguments to the `Saver()` constructor let you control + the proliferation of checkpoint files on disk: + + * `max_to_keep` indicates the maximum number of recent checkpoint files to + keep. As new files are created, older files are deleted. If None or 0, + no checkpoints are deleted from the filesystem but only the last one is + kept in the `checkpoint` file. Defaults to 5 (that is, the 5 most recent + checkpoint files are kept.) + + * `keep_checkpoint_every_n_hours`: In addition to keeping the most recent + `max_to_keep` checkpoint files, you might want to keep one checkpoint file + for every N hours of training. This can be useful if you want to later + analyze how a model progressed during a long training session. For + example, passing `keep_checkpoint_every_n_hours=2` ensures that you keep + one checkpoint file for every 2 hours of training. The default value of + 10,000 hours effectively disables the feature. + + Note that you still have to call the `save()` method to save the model. + Passing these arguments to the constructor will not save variables + automatically for you. + + A training program that saves regularly looks like: + + ```python + ... + # Create a saver. + saver = tf.compat.v1.train.Saver(...variables...) + # Launch the graph and train, saving the model every 1,000 steps. + sess = tf.compat.v1.Session() + for step in range(1000000): + sess.run(..training_op..) + if step % 1000 == 0: + # Append the step number to the checkpoint name: + saver.save(sess, 'my-model', global_step=step) + ``` + + In addition to checkpoint files, savers keep a protocol buffer on disk with + the list of recent checkpoints. This is used to manage numbered checkpoint + files and by `latest_checkpoint()`, which makes it easy to discover the path + to the most recent checkpoint. That protocol buffer is stored in a file named + 'checkpoint' next to the checkpoint files. + + If you create several savers, you can specify a different filename for the + protocol buffer file in the call to `save()`. + """ + + # pylint: enable=line-too-long + + def __init__(self, + var_list=None, + reshape=False, + sharded=False, + max_to_keep=5, + keep_checkpoint_every_n_hours=10000.0, + name=None, + restore_sequentially=False, + saver_def=None, + builder=None, + defer_build=False, + allow_empty=False, + write_version=saver_pb2.SaverDef.V2, + pad_step_number=False, + save_relative_paths=False, + filename=None): + """Creates a `Saver`. + + The constructor adds ops to save and restore variables. + + `var_list` specifies the variables that will be saved and restored. It can + be passed as a `dict` or a list: + + * A `dict` of names to variables: The keys are the names that will be + used to save or restore the variables in the checkpoint files. + * A list of variables: The variables will be keyed with their op name in + the checkpoint files. + + For example: + + ```python + v1 = tf.Variable(..., name='v1') + v2 = tf.Variable(..., name='v2') + + # Pass the variables as a dict: + saver = tf.compat.v1.train.Saver({'v1': v1, 'v2': v2}) + + # Or pass them as a list. + saver = tf.compat.v1.train.Saver([v1, v2]) + # Passing a list is equivalent to passing a dict with the variable op names + # as keys: + saver = tf.compat.v1.train.Saver({v.op.name: v for v in [v1, v2]}) + ``` + + Note: the newer `AutoTrackable` API is not supported by `Saver`. In this + case, the `tf.train.Checkpoint` class should be used. + + The optional `reshape` argument, if `True`, allows restoring a variable from + a save file where the variable had a different shape, but the same number + of elements and type. This is useful if you have reshaped a variable and + want to reload it from an older checkpoint. + + The optional `sharded` argument, if `True`, instructs the saver to shard + checkpoints per device. + + Args: + var_list: A list of `Variable`/`SaveableObject`, or a dictionary mapping + names to `SaveableObject`s. If `None`, defaults to the list of all + saveable objects. + reshape: If `True`, allows restoring parameters from a checkpoint where + the variables have a different shape. + sharded: If `True`, shard the checkpoints, one per device. + max_to_keep: Maximum number of recent checkpoints to keep. Defaults to 5. + keep_checkpoint_every_n_hours: How often to keep checkpoints. Defaults to + 10,000 hours. + name: String. Optional name to use as a prefix when adding operations. + restore_sequentially: A `Bool`, which if true, causes restore of different + variables to happen sequentially within each device. This can lower + memory usage when restoring very large models. + saver_def: Optional `SaverDef` proto to use instead of running the + builder. This is only useful for specialty code that wants to recreate a + `Saver` object for a previously built `Graph` that had a `Saver`. The + `saver_def` proto should be the one returned by the `as_saver_def()` + call of the `Saver` that was created for that `Graph`. + builder: Optional `SaverBuilder` to use if a `saver_def` was not provided. + Defaults to `BulkSaverBuilder()`. + defer_build: If `True`, defer adding the save and restore ops to the + `build()` call. In that case `build()` should be called before + finalizing the graph or using the saver. + allow_empty: If `False` (default) raise an error if there are no variables + in the graph. Otherwise, construct the saver anyway and make it a no-op. + write_version: controls what format to use when saving checkpoints. It + also affects certain filepath matching logic. The V2 format is the + recommended choice: it is much more optimized than V1 in terms of memory + required and latency incurred during restore. Regardless of this flag, + the Saver is able to restore from both V2 and V1 checkpoints. + pad_step_number: if True, pads the global step number in the checkpoint + filepaths to some fixed width (8 by default). This is turned off by + default. + save_relative_paths: If `True`, will write relative paths to the + checkpoint state file. This is needed if the user wants to copy the + checkpoint directory and reload from the copied directory. + filename: If known at graph construction time, filename used for variable + loading/saving. + + Raises: + TypeError: If `var_list` is invalid. + ValueError: If any of the keys or values in `var_list` are not unique. + RuntimeError: If eager execution is enabled and`var_list` does not specify + a list of variables to save. + + @compatibility(eager) + When eager execution is enabled, `var_list` must specify a `list` or `dict` + of variables to save. Otherwise, a `RuntimeError` will be raised. + + Although Saver works in some cases when executing eagerly, it is + fragile. Please switch to `tf.train.Checkpoint` or + `tf.keras.Model.save_weights`, which perform a more robust object-based + saving. These APIs will load checkpoints written by `Saver`. + @end_compatibility + """ + global _END_TIME_OF_LAST_WRITE + with _END_TIME_OF_LAST_WRITE_LOCK: + if _END_TIME_OF_LAST_WRITE is None: + _END_TIME_OF_LAST_WRITE = time.time() + + if defer_build and var_list: + raise ValueError( + "If `var_list` is provided then build cannot be deferred. " + "Either set defer_build=False or var_list=None.") + if context.executing_eagerly(): + logging.warning( + "Saver is deprecated, please switch to tf.train.Checkpoint or " + "tf.keras.Model.save_weights for training checkpoints. When " + "executing eagerly variables do not necessarily have unique names, " + "and so the variable.name-based lookups Saver performs are " + "error-prone.") + if var_list is None: + raise RuntimeError( + "When eager execution is enabled, `var_list` must specify a list " + "or dict of variables to save") + self._var_list = var_list + self._reshape = reshape + self._sharded = sharded + self._max_to_keep = max_to_keep + self._keep_checkpoint_every_n_hours = keep_checkpoint_every_n_hours + self._name = name + self._restore_sequentially = restore_sequentially + self.saver_def = saver_def + self._builder = builder + self._is_built = False + self._allow_empty = allow_empty + self._is_empty = None + self._write_version = write_version + self._pad_step_number = pad_step_number + self._filename = filename + self._last_checkpoints = [] + self._checkpoints_to_be_deleted = [] + if context.executing_eagerly(): + self._next_checkpoint_time = ( + time.time() + self._keep_checkpoint_every_n_hours * 3600) + elif not defer_build: + self.build() + if self.saver_def: + self._check_saver_def() + self._write_version = self.saver_def.version + self._save_relative_paths = save_relative_paths + # For compatibility with object-based checkpoints, we may build a second + # Saver to read the renamed keys. + self._object_restore_saver = None + + def build(self): + if context.executing_eagerly(): + raise RuntimeError("Use save/restore instead of build in eager mode.") + self._build(self._filename, build_save=True, build_restore=True) + + def _build_eager(self, checkpoint_path, build_save, build_restore): + self._build( + checkpoint_path, build_save=build_save, build_restore=build_restore) + + def _build(self, checkpoint_path, build_save, build_restore): + """Builds saver_def.""" + if not context.executing_eagerly(): + if self._is_built: + return + self._is_built = True + + if not self.saver_def or context.executing_eagerly(): + if self._builder is None: + self._builder = BulkSaverBuilder(self._write_version) + + if self._var_list is None: + # pylint: disable=protected-access + self._var_list = variables._all_saveable_objects() + if not self._var_list: + if self._allow_empty: + self._is_empty = True + return + else: + raise ValueError("No variables to save") + self._is_empty = False + + self.saver_def = self._builder._build_internal( # pylint: disable=protected-access + self._var_list, + reshape=self._reshape, + sharded=self._sharded, + max_to_keep=self._max_to_keep, + keep_checkpoint_every_n_hours=self._keep_checkpoint_every_n_hours, + name=self._name, + restore_sequentially=self._restore_sequentially, + filename=checkpoint_path, + build_save=build_save, + build_restore=build_restore) + elif self.saver_def and self._name: + # Since self._name is used as a name_scope by builder(), we are + # overloading the use of this field to represent the "import_scope" as + # well. + self.saver_def.filename_tensor_name = ops.prepend_name_scope( + self.saver_def.filename_tensor_name, self._name) + self.saver_def.save_tensor_name = ops.prepend_name_scope( + self.saver_def.save_tensor_name, self._name) + self.saver_def.restore_op_name = ops.prepend_name_scope( + self.saver_def.restore_op_name, self._name) + + self._check_saver_def() + if not context.executing_eagerly(): + # Updates next checkpoint time. + # Set in __init__ when executing eagerly. + self._next_checkpoint_time = ( + time.time() + self.saver_def.keep_checkpoint_every_n_hours * 3600) + + def _check_saver_def(self): + if not isinstance(self.saver_def, saver_pb2.SaverDef): + raise ValueError("saver_def must be a saver_pb2.SaverDef: %s" % + self.saver_def) + if not context.executing_eagerly(): + if not self.saver_def.save_tensor_name: + raise ValueError("saver_def must specify the save_tensor_name: %s" % + str(self.saver_def)) + if not self.saver_def.restore_op_name: + raise ValueError("saver_def must specify the restore_op_name: %s" % + str(self.saver_def)) + + def _CheckpointFilename(self, p): + """Returns the checkpoint filename given a `(filename, time)` pair. + + Args: + p: (filename, time) pair. + + Returns: + Checkpoint file name. + """ + name, _ = p + return name + + def _RecordLastCheckpoint(self, latest_save_path): + """Manages the list of the latest checkpoints.""" + if not self.saver_def.max_to_keep: + return + # Remove first from list if the same name was used before. + for p in self._last_checkpoints: + if latest_save_path == self._CheckpointFilename(p): + self._last_checkpoints.remove(p) + # Append new path to list + self._last_checkpoints.append((latest_save_path, time.time())) + + # If more than max_to_keep, remove oldest. + if len(self._last_checkpoints) > self.saver_def.max_to_keep: + self._checkpoints_to_be_deleted.append(self._last_checkpoints.pop(0)) + + def _MaybeDeleteOldCheckpoints(self, meta_graph_suffix="meta"): + """Deletes old checkpoints if necessary. + + `self._checkpoints_to_be_deleted` is going to contain checkpoints that are + over `max_to_keep`. They are going to be deleted. If + `keep_checkpoint_every_n_hours` was specified, keep an additional checkpoint + every `N` hours. For example, if `N` is 0.5, an additional checkpoint is + kept for every 0.5 hours of training; if `N` is 10, an additional + checkpoint is kept for every 10 hours of training. + + Args: + meta_graph_suffix: Suffix for `MetaGraphDef` file. Defaults to 'meta'. + """ + if self._checkpoints_to_be_deleted: + p = self._checkpoints_to_be_deleted.pop(0) + # Do not delete the file if we keep_checkpoint_every_n_hours is set and we + # have reached N hours of training. + should_keep = p[1] > self._next_checkpoint_time + if should_keep: + self._next_checkpoint_time += ( + self.saver_def.keep_checkpoint_every_n_hours * 3600) + return + + # Otherwise delete the files. + try: + checkpoint_management.remove_checkpoint( + self._CheckpointFilename(p), self.saver_def.version, + meta_graph_suffix) + except Exception as e: # pylint: disable=broad-except + logging.warning("Ignoring: %s", str(e)) + + def as_saver_def(self): + """Generates a `SaverDef` representation of this saver. + + Returns: + A `SaverDef` proto. + """ + return self.saver_def + + def to_proto(self, export_scope=None): + """Converts this `Saver` to a `SaverDef` protocol buffer. + + Args: + export_scope: Optional `string`. Name scope to remove. + + Returns: + A `SaverDef` protocol buffer. + """ + if export_scope is None: + return self.saver_def + + if not (self.saver_def.filename_tensor_name.startswith(export_scope) and + self.saver_def.save_tensor_name.startswith(export_scope) and + self.saver_def.restore_op_name.startswith(export_scope)): + return None + + saver_def = saver_pb2.SaverDef() + saver_def.CopyFrom(self.saver_def) + saver_def.filename_tensor_name = ops.strip_name_scope( + saver_def.filename_tensor_name, export_scope) + saver_def.save_tensor_name = ops.strip_name_scope( + saver_def.save_tensor_name, export_scope) + saver_def.restore_op_name = ops.strip_name_scope(saver_def.restore_op_name, + export_scope) + return saver_def + + @staticmethod + def from_proto(saver_def, import_scope=None): + """Returns a `Saver` object created from `saver_def`. + + Args: + saver_def: a `SaverDef` protocol buffer. + import_scope: Optional `string`. Name scope to use. + + Returns: + A `Saver` built from saver_def. + """ + return Saver(saver_def=saver_def, name=import_scope) + + @property + def last_checkpoints(self): + """List of not-yet-deleted checkpoint filenames. + + You can pass any of the returned values to `restore()`. + + Returns: + A list of checkpoint filenames, sorted from oldest to newest. + """ + return list(self._CheckpointFilename(p) for p in self._last_checkpoints) + + def set_last_checkpoints(self, last_checkpoints): + """DEPRECATED: Use set_last_checkpoints_with_time. + + Sets the list of old checkpoint filenames. + + Args: + last_checkpoints: A list of checkpoint filenames. + + Raises: + AssertionError: If last_checkpoints is not a list. + """ + assert isinstance(last_checkpoints, list) + # We use a timestamp of +inf so that this checkpoint will never be + # deleted. This is both safe and backwards compatible to a previous + # version of the code which used s[1] as the "timestamp". + self._last_checkpoints = [(s, np.inf) for s in last_checkpoints] + + def set_last_checkpoints_with_time(self, last_checkpoints_with_time): + """Sets the list of old checkpoint filenames and timestamps. + + Args: + last_checkpoints_with_time: A list of tuples of checkpoint filenames and + timestamps. + + Raises: + AssertionError: If last_checkpoints_with_time is not a list. + """ + assert isinstance(last_checkpoints_with_time, list) + self._last_checkpoints = last_checkpoints_with_time + + def recover_last_checkpoints(self, checkpoint_paths): + """Recovers the internal saver state after a crash. + + This method is useful for recovering the "self._last_checkpoints" state. + + Globs for the checkpoints pointed to by `checkpoint_paths`. If the files + exist, use their mtime as the checkpoint timestamp. + + Args: + checkpoint_paths: a list of checkpoint paths. + """ + checkpoints_with_mtimes = [] + for checkpoint_path in checkpoint_paths: + try: + mtime = checkpoint_management.get_checkpoint_mtimes([checkpoint_path]) + except errors.NotFoundError: + # It's fine if some other thread/process is deleting some older + # checkpoint concurrently. + continue + if mtime: + checkpoints_with_mtimes.append((checkpoint_path, mtime[0])) + self.set_last_checkpoints_with_time(checkpoints_with_mtimes) + + def save(self, + sess, + save_path, + global_step=None, + latest_filename=None, + meta_graph_suffix="meta", + write_meta_graph=True, + write_state=True, + strip_default_attrs=False, + save_debug_info=False): + # pylint: disable=line-too-long + """Saves variables. + + This method runs the ops added by the constructor for saving variables. + It requires a session in which the graph was launched. The variables to + save must also have been initialized. + + The method returns the path prefix of the newly created checkpoint files. + This string can be passed directly to a call to `restore()`. + + Args: + sess: A Session to use to save the variables. + save_path: String. Prefix of filenames created for the checkpoint. + global_step: If provided the global step number is appended to `save_path` + to create the checkpoint filenames. The optional argument can be a + `Tensor`, a `Tensor` name or an integer. + latest_filename: Optional name for the protocol buffer file that will + contains the list of most recent checkpoints. That file, kept in the + same directory as the checkpoint files, is automatically managed by the + saver to keep track of recent checkpoints. Defaults to 'checkpoint'. + meta_graph_suffix: Suffix for `MetaGraphDef` file. Defaults to 'meta'. + write_meta_graph: `Boolean` indicating whether or not to write the meta + graph file. + write_state: `Boolean` indicating whether or not to write the + `CheckpointStateProto`. + strip_default_attrs: Boolean. If `True`, default-valued attributes will be + removed from the NodeDefs. For a detailed guide, see [Stripping + Default-Valued + Attributes](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md#stripping-default-valued-attributes). + save_debug_info: If `True`, save the GraphDebugInfo to a separate file, + which in the same directory of save_path and with `_debug` added before + the file extension. This is only enabled when `write_meta_graph` is + `True` + + Returns: + A string: path prefix used for the checkpoint files. If the saver is + sharded, this string ends with: '-?????-of-nnnnn' where 'nnnnn' + is the number of shards created. + If the saver is empty, returns None. + + Raises: + TypeError: If `sess` is not a `Session`. + ValueError: If `latest_filename` contains path components, or if it + collides with `save_path`. + RuntimeError: If save and restore ops weren't built. + """ + # pylint: enable=line-too-long + start_time = time.time() + if not self._is_built and not context.executing_eagerly(): + raise RuntimeError( + "`build()` should be called before save if defer_build==True") + if latest_filename is None: + latest_filename = "checkpoint" + if self._write_version != saver_pb2.SaverDef.V2: + logging.warning("*******************************************************") + logging.warning("TensorFlow's V1 checkpoint format has been deprecated.") + logging.warning("Consider switching to the more efficient V2 format:") + logging.warning(" `tf.train.Saver(write_version=tf.train.SaverDef.V2)`") + logging.warning("now on by default.") + logging.warning("*******************************************************") + + if os.path.split(latest_filename)[0]: + raise ValueError("'latest_filename' must not contain path components") + + save_path = compat.as_str(save_path) + if global_step is not None: + if not isinstance(global_step, compat.integral_types): + global_step = training_util.global_step(sess, global_step) + checkpoint_file = "%s-%d" % (save_path, global_step) + if self._pad_step_number: + # Zero-pads the step numbers, so that they are sorted when listed. + checkpoint_file = "%s-%s" % (save_path, "{:08d}".format(global_step)) + else: + checkpoint_file = save_path + if os.path.basename(save_path) == latest_filename and not self._sharded: + # Guard against collision between data file and checkpoint state file. + raise ValueError( + "'latest_filename' collides with 'save_path': '%s' and '%s'" % + (latest_filename, save_path)) + + if (not context.executing_eagerly() and + not isinstance(sess, session.SessionInterface)): + raise TypeError("'sess' must be a Session; %s" % sess) + + save_path_parent = os.path.dirname(save_path) + if not self._is_empty: + try: + if context.executing_eagerly(): + self._build_eager( + checkpoint_file, build_save=True, build_restore=False) + model_checkpoint_path = self.saver_def.save_tensor_name + else: + model_checkpoint_path = sess.run( + self.saver_def.save_tensor_name, + {self.saver_def.filename_tensor_name: checkpoint_file}) + + model_checkpoint_path = compat.as_str(model_checkpoint_path) + if write_state: + self._RecordLastCheckpoint(model_checkpoint_path) + checkpoint_management.update_checkpoint_state_internal( + save_dir=save_path_parent, + model_checkpoint_path=model_checkpoint_path, + all_model_checkpoint_paths=self.last_checkpoints, + latest_filename=latest_filename, + save_relative_paths=self._save_relative_paths) + self._MaybeDeleteOldCheckpoints(meta_graph_suffix=meta_graph_suffix) + except (errors.FailedPreconditionError, errors.NotFoundError) as exc: + if not gfile.IsDirectory(save_path_parent): + exc = ValueError( + "Parent directory of {} doesn't exist, can't save.".format( + save_path)) + raise exc + + end_time = time.time() + metrics.AddCheckpointWriteDuration( + api_label=_SAVER_LABEL, + microseconds=_get_duration_microseconds(start_time, end_time)) + global _END_TIME_OF_LAST_WRITE + with _END_TIME_OF_LAST_WRITE_LOCK: + metrics.AddTrainingTimeSaved( + api_label=_SAVER_LABEL, + microseconds=_get_duration_microseconds(_END_TIME_OF_LAST_WRITE, + end_time)) + _END_TIME_OF_LAST_WRITE = end_time + + if write_meta_graph: + meta_graph_filename = checkpoint_management.meta_graph_filename( + checkpoint_file, meta_graph_suffix=meta_graph_suffix) + if not context.executing_eagerly(): + with sess.graph.as_default(): + self.export_meta_graph( + meta_graph_filename, + strip_default_attrs=strip_default_attrs, + save_debug_info=save_debug_info) + + if self._is_empty: + return None + else: + metrics.RecordCheckpointSize( + api_label=_SAVER_LABEL, + filesize=_get_checkpoint_size(model_checkpoint_path)) + return model_checkpoint_path + + def export_meta_graph(self, + filename=None, + collection_list=None, + as_text=False, + export_scope=None, + clear_devices=False, + clear_extraneous_savers=False, + strip_default_attrs=False, + save_debug_info=False): + # pylint: disable=line-too-long + """Writes `MetaGraphDef` to save_path/filename. + + Args: + filename: Optional meta_graph filename including the path. + collection_list: List of string keys to collect. + as_text: If `True`, writes the meta_graph as an ASCII proto. + export_scope: Optional `string`. Name scope to remove. + clear_devices: Whether or not to clear the device field for an `Operation` + or `Tensor` during export. + clear_extraneous_savers: Remove any Saver-related information from the + graph (both Save/Restore ops and SaverDefs) that are not associated with + this Saver. + strip_default_attrs: Boolean. If `True`, default-valued attributes will be + removed from the NodeDefs. For a detailed guide, see [Stripping + Default-Valued + Attributes](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md#stripping-default-valued-attributes). + save_debug_info: If `True`, save the GraphDebugInfo to a separate file, + which in the same directory of filename and with `_debug` added before + the file extension. + + Returns: + A `MetaGraphDef` proto. + """ + # pylint: enable=line-too-long + return export_meta_graph( + filename=filename, + graph_def=ops.get_default_graph().as_graph_def(add_shapes=True), + saver_def=self.saver_def, + collection_list=collection_list, + as_text=as_text, + export_scope=export_scope, + clear_devices=clear_devices, + clear_extraneous_savers=clear_extraneous_savers, + strip_default_attrs=strip_default_attrs, + save_debug_info=save_debug_info) + + def restore(self, sess, save_path): + """Restores previously saved variables. + + This method runs the ops added by the constructor for restoring variables. + It requires a session in which the graph was launched. The variables to + restore do not have to have been initialized, as restoring is itself a way + to initialize variables. + + The `save_path` argument is typically a value previously returned from a + `save()` call, or a call to `latest_checkpoint()`. + + Args: + sess: A `Session` to use to restore the parameters. None in eager mode. + save_path: Path where parameters were previously saved. + + Raises: + ValueError: If save_path is None or not a valid checkpoint. + """ + start_time = time.time() + if self._is_empty: + return + if save_path is None: + raise ValueError("Can't load save_path when it is None.") + + checkpoint_prefix = compat.as_text(save_path) + if not checkpoint_management.checkpoint_exists_internal(checkpoint_prefix): + raise ValueError("The passed save_path is not a valid checkpoint: " + + checkpoint_prefix) + + logging.info("Restoring parameters from %s", checkpoint_prefix) + try: + if context.executing_eagerly(): + self._build_eager(save_path, build_save=False, build_restore=True) + else: + sess.run(self.saver_def.restore_op_name, + {self.saver_def.filename_tensor_name: save_path}) + except errors.NotFoundError as err: + # There are three common conditions that might cause this error: + # 0. The file is missing. We ignore here, as this is checked above. + # 1. This is an object-based checkpoint trying name-based loading. + # 2. The graph has been altered and a variable or other name is missing. + + # 1. The checkpoint would not be loaded successfully as is. Try to parse + # it as an object-based checkpoint. + try: + names_to_keys = object_graph_key_mapping(save_path) + except errors.NotFoundError: + # 2. This is not an object-based checkpoint, which likely means there + # is a graph mismatch. Re-raise the original error with + # a helpful message (b/110263146) + raise _wrap_restore_error_with_msg( + err, "a Variable name or other graph key that is missing") + + # This is an object-based checkpoint. We'll print a warning and then do + # the restore. + logging.warning( + "Restoring an object-based checkpoint using a name-based saver. This " + "may be somewhat fragile, and will re-build the Saver. Instead, " + "consider loading object-based checkpoints using " + "tf.train.Checkpoint().") + self._object_restore_saver = saver_from_object_based_checkpoint( + checkpoint_path=save_path, + var_list=self._var_list, + builder=self._builder, + names_to_keys=names_to_keys, + cached_saver=self._object_restore_saver) + self._object_restore_saver.restore(sess=sess, save_path=save_path) + except errors.InvalidArgumentError as err: + # There is a mismatch between the graph and the checkpoint being loaded. + # We add a more reasonable error message here to help users (b/110263146) + raise _wrap_restore_error_with_msg( + err, "a mismatch between the current graph and the graph") + metrics.AddCheckpointReadDuration( + api_label=_SAVER_LABEL, + microseconds=_get_duration_microseconds(start_time, time.time())) + + @staticmethod + def _add_collection_def(meta_graph_def, key, export_scope=None): + """Adds a collection to MetaGraphDef protocol buffer. + + Args: + meta_graph_def: MetaGraphDef protocol buffer. + key: One of the GraphKeys or user-defined string. + export_scope: Optional `string`. Name scope to remove. + """ + meta_graph.add_collection_def( + meta_graph_def, key, export_scope=export_scope) + + +@tf_export(v1=["train.import_meta_graph"]) +def import_meta_graph(meta_graph_or_file, + clear_devices=False, + import_scope=None, + **kwargs): + """Recreates a Graph saved in a `MetaGraphDef` proto. + + This function takes a `MetaGraphDef` protocol buffer as input. If + the argument is a file containing a `MetaGraphDef` protocol buffer , + it constructs a protocol buffer from the file content. The function + then adds all the nodes from the `graph_def` field to the + current graph, recreates all the collections, and returns a saver + constructed from the `saver_def` field. + + In combination with `export_meta_graph()`, this function can be used to + + * Serialize a graph along with other Python objects such as `QueueRunner`, + `Variable` into a `MetaGraphDef`. + + * Restart training from a saved graph and checkpoints. + + * Run inference from a saved graph and checkpoints. + + ```Python + ... + # Create a saver. + saver = tf.compat.v1.train.Saver(...variables...) + # Remember the training_op we want to run by adding it to a collection. + tf.compat.v1.add_to_collection('train_op', train_op) + sess = tf.compat.v1.Session() + for step in range(1000000): + sess.run(train_op) + if step % 1000 == 0: + # Saves checkpoint, which by default also exports a meta_graph + # named 'my-model-global_step.meta'. + saver.save(sess, 'my-model', global_step=step) + ``` + + Later we can continue training from this saved `meta_graph` without building + the model from scratch. + + ```Python + with tf.Session() as sess: + new_saver = + tf.train.import_meta_graph('my-save-dir/my-model-10000.meta') + new_saver.restore(sess, 'my-save-dir/my-model-10000') + # tf.get_collection() returns a list. In this example we only want + # the first one. + train_op = tf.get_collection('train_op')[0] + for step in range(1000000): + sess.run(train_op) + ``` + + NOTE: Restarting training from saved `meta_graph` only works if the + device assignments have not changed. + + Example: + Variables, placeholders, and independent operations can also be stored, as + shown in the following example. + + ```Python + # Saving contents and operations. + v1 = tf.placeholder(tf.float32, name="v1") + v2 = tf.placeholder(tf.float32, name="v2") + v3 = tf.math.multiply(v1, v2) + vx = tf.Variable(10.0, name="vx") + v4 = tf.add(v3, vx, name="v4") + saver = tf.train.Saver([vx]) + sess = tf.Session() + sess.run(tf.global_variables_initializer()) + sess.run(vx.assign(tf.add(vx, vx))) + result = sess.run(v4, feed_dict={v1:12.0, v2:3.3}) + print(result) + saver.save(sess, "./model_ex1") + ``` + + Later this model can be restored and contents loaded. + + ```Python + # Restoring variables and running operations. + saver = tf.train.import_meta_graph("./model_ex1.meta") + sess = tf.Session() + saver.restore(sess, "./model_ex1") + result = sess.run("v4:0", feed_dict={"v1:0": 12.0, "v2:0": 3.3}) + print(result) + ``` + + Args: + meta_graph_or_file: `MetaGraphDef` protocol buffer or filename (including + the path) containing a `MetaGraphDef`. + clear_devices: Whether or not to clear the device field for an `Operation` + or `Tensor` during import. + import_scope: Optional `string`. Name scope to add. Only used when + initializing from protocol buffer. + **kwargs: Optional keyed arguments. + + Returns: + A saver constructed from `saver_def` in `MetaGraphDef` or None. + + A None value is returned if no variables exist in the `MetaGraphDef` + (i.e., there are no variables to restore). + + Raises: + RuntimeError: If called with eager execution enabled. + + @compatibility(eager) + Exporting/importing meta graphs is not supported. No graph exists when eager + execution is enabled. + @end_compatibility + """ # pylint: disable=g-doc-exception + return _import_meta_graph_with_return_elements(meta_graph_or_file, + clear_devices, import_scope, + **kwargs)[0] + + +def _import_meta_graph_with_return_elements(meta_graph_or_file, + clear_devices=False, + import_scope=None, + return_elements=None, + **kwargs): + """Import MetaGraph, and return both a saver and returned elements.""" + if context.executing_eagerly(): + raise RuntimeError("Exporting/importing meta graphs is not supported when " + "eager execution is enabled. No graph exists when eager " + "execution is enabled.") + if not isinstance(meta_graph_or_file, meta_graph_pb2.MetaGraphDef): + meta_graph_def = meta_graph.read_meta_graph_file(meta_graph_or_file) + else: + meta_graph_def = meta_graph_or_file + + imported_vars, imported_return_elements = ( + meta_graph.import_scoped_meta_graph_with_return_elements( + meta_graph_def, + clear_devices=clear_devices, + import_scope=import_scope, + return_elements=return_elements, + **kwargs)) + + saver = _create_saver_from_imported_meta_graph(meta_graph_def, import_scope, + imported_vars) + return saver, imported_return_elements + + +def _create_saver_from_imported_meta_graph(meta_graph_def, import_scope, + imported_vars): + """Return a saver for restoring variable values to an imported MetaGraph.""" + if meta_graph_def.HasField("saver_def"): + # Infer the scope that is prepended by `import_scoped_meta_graph`. + scope = import_scope + var_names = list(imported_vars.keys()) + if var_names: + sample_key = var_names[0] + sample_var = imported_vars[sample_key] + scope = sample_var.name[:-len(sample_key)] + + return Saver(saver_def=meta_graph_def.saver_def, name=scope) + else: + if variables._all_saveable_objects(scope=import_scope): # pylint: disable=protected-access + # Return the default saver instance for all graph variables. + return Saver() + else: + # If no graph variables exist, then a Saver cannot be constructed. + logging.info("Saver not created because there are no variables in the" + " graph to restore") + return None + + +@tf_export(v1=["train.export_meta_graph"]) +def export_meta_graph(filename=None, + meta_info_def=None, + graph_def=None, + saver_def=None, + collection_list=None, + as_text=False, + graph=None, + export_scope=None, + clear_devices=False, + clear_extraneous_savers=False, + strip_default_attrs=False, + save_debug_info=False, + **kwargs): + # pylint: disable=line-too-long + """Returns `MetaGraphDef` proto. + + Optionally writes it to filename. + + This function exports the graph, saver, and collection objects into + `MetaGraphDef` protocol buffer with the intention of it being imported + at a later time or location to restart training, run inference, or be + a subgraph. + + Args: + filename: Optional filename including the path for writing the generated + `MetaGraphDef` protocol buffer. + meta_info_def: `MetaInfoDef` protocol buffer. + graph_def: `GraphDef` protocol buffer. + saver_def: `SaverDef` protocol buffer. + collection_list: List of string keys to collect. + as_text: If `True`, writes the `MetaGraphDef` as an ASCII proto. + graph: The `Graph` to export. If `None`, use the default graph. + export_scope: Optional `string`. Name scope under which to extract the + subgraph. The scope name will be striped from the node definitions for + easy import later into new name scopes. If `None`, the whole graph is + exported. graph_def and export_scope cannot both be specified. + clear_devices: Whether or not to clear the device field for an `Operation` + or `Tensor` during export. + clear_extraneous_savers: Remove any Saver-related information from the graph + (both Save/Restore ops and SaverDefs) that are not associated with the + provided SaverDef. + strip_default_attrs: Boolean. If `True`, default-valued attributes will be + removed from the NodeDefs. For a detailed guide, see [Stripping + Default-Valued + Attributes](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md#stripping-default-valued-attributes). + save_debug_info: If `True`, save the GraphDebugInfo to a separate file, + which in the same directory of filename and with `_debug` added before the + file extend. + **kwargs: Optional keyed arguments. + + Returns: + A `MetaGraphDef` proto. + + Raises: + ValueError: When the `GraphDef` is larger than 2GB. + RuntimeError: If called with eager execution enabled. + + @compatibility(eager) + Exporting/importing meta graphs is not supported unless both `graph_def` and + `graph` are provided. No graph exists when eager execution is enabled. + @end_compatibility + """ + # pylint: enable=line-too-long + if context.executing_eagerly() and not (graph_def is not None and + graph is not None): + raise RuntimeError("Exporting/importing meta graphs is not supported when " + "eager execution is enabled. No graph exists when eager " + "execution is enabled.") + meta_graph_def, _ = meta_graph.export_scoped_meta_graph( + filename=filename, + meta_info_def=meta_info_def, + graph_def=graph_def, + saver_def=saver_def, + collection_list=collection_list, + as_text=as_text, + graph=graph, + export_scope=export_scope, + clear_devices=clear_devices, + clear_extraneous_savers=clear_extraneous_savers, + strip_default_attrs=strip_default_attrs, + save_debug_info=save_debug_info, + **kwargs) + return meta_graph_def + + +def _wrap_restore_error_with_msg(err, extra_verbiage): + err_msg = ("Restoring from checkpoint failed. This is most likely " + "due to {} from the checkpoint. Please ensure that you " + "have not altered the graph expected based on the checkpoint. " + "Original error:\n\n{}").format(extra_verbiage, err.message) + return err.__class__(err.node_def, err.op, err_msg) + + +ops.register_proto_function( + ops.GraphKeys.SAVERS, + proto_type=saver_pb2.SaverDef, + to_proto=Saver.to_proto, + from_proto=Saver.from_proto) + + +def object_graph_key_mapping(checkpoint_path): + """Return name to key mappings from the checkpoint. + + Args: + checkpoint_path: string, path to object-based checkpoint + + Returns: + Dictionary mapping tensor names to checkpoint keys. + """ + reader = py_checkpoint_reader.NewCheckpointReader(checkpoint_path) + object_graph_string = reader.get_tensor(trackable.OBJECT_GRAPH_PROTO_KEY) + object_graph_proto = (trackable_object_graph_pb2.TrackableObjectGraph()) + object_graph_proto.ParseFromString(object_graph_string) + names_to_keys = {} + for node in object_graph_proto.nodes: + for attribute in node.attributes: + names_to_keys[attribute.full_name] = attribute.checkpoint_key + return names_to_keys + + +def saver_from_object_based_checkpoint(checkpoint_path, + var_list=None, + builder=None, + names_to_keys=None, + cached_saver=None): + """Return a `Saver` which reads from an object-based checkpoint. + + This function validates that all variables in the variables list are remapped + in the object-based checkpoint (or `names_to_keys` dict if provided). A + saver will be created with the list of remapped variables. + + The `cached_saver` argument allows the user to pass in a previously created + saver, so multiple `saver.restore()` calls don't pollute the graph when graph + building. This assumes that keys are consistent, meaning that the + 1) `checkpoint_path` checkpoint, and + 2) checkpoint used to create the `cached_saver` + are the same type of object-based checkpoint. If this argument is set, this + function will simply validate that all variables have been remapped by the + checkpoint at `checkpoint_path`. + + Note that in general, `tf.train.Checkpoint` should be used to restore/save an + object-based checkpoint. + + Args: + checkpoint_path: string, path to object-based checkpoint + var_list: list of `Variables` that appear in the checkpoint. If `None`, + `var_list` will be set to all saveable objects. + builder: a `BaseSaverBuilder` instance. If `None`, a new `BulkSaverBuilder` + will be created. + names_to_keys: dict mapping string tensor names to checkpoint keys. If + `None`, this dict will be generated from the checkpoint file. + cached_saver: Cached `Saver` object with remapped variables. + + Returns: + `Saver` with remapped variables for reading from an object-based checkpoint. + + Raises: + ValueError if the checkpoint provided is not an object-based checkpoint. + NotFoundError: If one of the variables in `var_list` can not be found in the + checkpoint. This could mean the checkpoint or `names_to_keys` mapping is + missing the variable. + """ + if names_to_keys is None: + try: + names_to_keys = object_graph_key_mapping(checkpoint_path) + except errors.NotFoundError: + raise ValueError("Checkpoint in %s not an object-based checkpoint." % + checkpoint_path) + if var_list is None: + var_list = variables._all_saveable_objects() # pylint: disable=protected-access + if builder is None: + builder = BulkSaverBuilder() + + if not isinstance(var_list, dict): + var_list = saveable_object_util.op_list_to_dict(var_list) + saveables = saveable_object_util.validate_and_slice_inputs(var_list) + current_names = set() + for saveable in saveables: + for spec in saveable.specs: + current_names.add(spec.name) + previous_names = set(names_to_keys.keys()) + missing_names = current_names - previous_names + if missing_names: + extra_names = previous_names - current_names + intersecting_names = previous_names.intersection(current_names) + raise errors.NotFoundError( + None, + None, + message=( + "\n\nExisting variables not in the checkpoint: %s\n\n" + "Variables names when this checkpoint was written which don't " + "exist now: %s\n\n" + "(%d variable name(s) did match)\n\n" + "Could not find some variables in the checkpoint (see names " + "above). Saver was attempting to load an object-based checkpoint " + "(saved using tf.train.Checkpoint or tf.keras.Model.save_weights) " + "using variable names. If the checkpoint was written with eager " + "execution enabled, it's possible that variable names have " + "changed (for example missing a '_1' suffix). It's also " + "possible that there are new variables which did not exist " + "when the checkpoint was written. You can construct a " + "Saver(var_list=...) with only the variables which previously " + "existed, and if variable names have changed you may need to " + "make this a dictionary with the old names as keys. If you're " + "using an Estimator, you'll need to return a tf.train.Saver " + "inside a tf.train.Scaffold from your model_fn.") % + (", ".join(sorted(missing_names)), ", ".join( + sorted(extra_names)), len(intersecting_names))) + for saveable in saveables: + for spec in saveable.specs: + spec.name = names_to_keys[spec.name] + if cached_saver is None: + return Saver(saveables) + return cached_saver diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/saver_test_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/saver_test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..bae7f5721dc7403e97d34ca5994d8959c3bb5c99 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/saver_test_utils.py @@ -0,0 +1,87 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================= +"""Utility classes for testing checkpointing.""" + +from tensorflow.python.eager import context +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops as ops_lib +from tensorflow.python.ops import gen_lookup_ops +from tensorflow.python.training import saver as saver_module + + +class CheckpointedOp: + """Op with a custom checkpointing implementation. + + Defined as part of the test because the MutableHashTable Python code is + currently in contrib. + """ + + # pylint: disable=protected-access + def __init__(self, name, table_ref=None): + if table_ref is None: + self.table_ref = gen_lookup_ops.mutable_hash_table_v2( + key_dtype=dtypes.string, value_dtype=dtypes.float32, name=name) + else: + self.table_ref = table_ref + self._name = name + if not context.executing_eagerly(): + self._saveable = CheckpointedOp.CustomSaveable(self, name) + ops_lib.add_to_collection(ops_lib.GraphKeys.SAVEABLE_OBJECTS, + self._saveable) + + @property + def name(self): + return self._name + + @property + def saveable(self): + if context.executing_eagerly(): + return CheckpointedOp.CustomSaveable(self, self.name) + else: + return self._saveable + + def insert(self, keys, values): + return gen_lookup_ops.lookup_table_insert_v2(self.table_ref, keys, values) + + def lookup(self, keys, default): + return gen_lookup_ops.lookup_table_find_v2(self.table_ref, keys, default) + + def keys(self): + return self._export()[0] + + def values(self): + return self._export()[1] + + def _export(self): + return gen_lookup_ops.lookup_table_export_v2(self.table_ref, dtypes.string, + dtypes.float32) + + class CustomSaveable(saver_module.BaseSaverBuilder.SaveableObject): + """A custom saveable for CheckpointedOp.""" + + def __init__(self, table, name): + tensors = table._export() + specs = [ + saver_module.BaseSaverBuilder.SaveSpec(tensors[0], "", + name + "-keys"), + saver_module.BaseSaverBuilder.SaveSpec(tensors[1], "", + name + "-values") + ] + super(CheckpointedOp.CustomSaveable, self).__init__(table, specs, name) + + def restore(self, restore_tensors, shapes): + return gen_lookup_ops.lookup_table_import_v2( + self.op.table_ref, restore_tensors[0], restore_tensors[1]) + # pylint: enable=protected-access diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/saving/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/saving/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/saving/saveable_object.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/saving/saveable_object.py new file mode 100644 index 0000000000000000000000000000000000000000..ce1bc15eda595df037d995f198a3e6799aea5663 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/saving/saveable_object.py @@ -0,0 +1,94 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Types for specifying saving and loading behavior.""" + + +class SaveSpec: + """Class used to describe tensor slices that need to be saved.""" + + def __init__(self, tensor, slice_spec, name, dtype=None, device=None): + """Creates a `SaveSpec` object. + + Args: + tensor: the tensor to save or callable that produces a tensor to save. + If the value is `None`, the `SaveSpec` is ignored. + slice_spec: the slice to be saved. See `Variable.SaveSliceInfo`. + name: the name to save the tensor under. + dtype: The data type of the Tensor. Required if `tensor` is callable. + Used for error checking in the restore op. + device: The device generating and consuming this tensor. Required if + `tensor` is callable. Used to group objects to save by device. + """ + self._tensor = tensor + self.slice_spec = slice_spec + self.name = name + if callable(self._tensor): + if dtype is None or device is None: + raise AssertionError( + "When passing a callable `tensor` to a SaveSpec, an explicit " + "dtype and device must be provided.") + self.dtype = dtype + self.device = device + else: + self.dtype = tensor.dtype + if device is not None: + self.device = device + else: + self.device = tensor.device + + @property + def tensor(self): + return self._tensor() if callable(self._tensor) else self._tensor + + +class SaveableObject: + """Base class for saving and restoring saveable objects.""" + + def __init__(self, op, specs, name): + """Creates a `SaveableObject` object. + + Args: + op: the "producer" object that this class wraps; it produces a list of + tensors to save. E.g., a "Variable" object saving its backing tensor. + specs: a list of SaveSpec, each element of which describes one tensor to + save under this object. All Tensors must be on the same device. + name: the name to save the object under. + """ + self.op = op + self.specs = specs + self.name = name + + @property + def device(self): + """The device for SaveSpec Tensors.""" + return self.specs[0].device + + def restore(self, restored_tensors, restored_shapes): + """Restores this object from 'restored_tensors'. + + Args: + restored_tensors: the tensors that were loaded from a checkpoint + restored_shapes: the shapes this object should conform to after + restore, or None. + + Returns: + An operation that restores the state of the object. + + Raises: + ValueError: If the object cannot be restored using the provided + parameters. + """ + # pylint: disable=unused-argument + raise ValueError("Calling an abstract method.") diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/saving/saveable_object_util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/saving/saveable_object_util.py new file mode 100644 index 0000000000000000000000000000000000000000..a3a4b4f2873b3e38b7d936e58389c86954f121d2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/saving/saveable_object_util.py @@ -0,0 +1,839 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Utilities for working with and creating SaveableObjects.""" +import functools + +from tensorflow.python.checkpoint import saveable_compat +from tensorflow.python.client import session +from tensorflow.python.eager import context + +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import device as pydev +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.framework import tensor_util + +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gen_control_flow_ops +from tensorflow.python.ops import ref_variable +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.ops import state_ops +from tensorflow.python.ops import variables +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.trackable import base as trackable +from tensorflow.python.trackable import base_delegate +from tensorflow.python.trackable import python_state +from tensorflow.python.trackable import trackable_utils +from tensorflow.python.training.saving import saveable_object +from tensorflow.python.types import core +from tensorflow.python.util import compat +from tensorflow.python.util import nest +from tensorflow.python.util import object_identity +from tensorflow.python.util.tf_export import tf_export + +# Op names which identify variable reads which should be saved. +_VARIABLE_OPS = set(["Variable", + "VariableV2", + "AutoReloadVariable", + "VarHandleOp", + "ReadVariableOp"]) + +_REF_VARIABLE_OPS = frozenset(["Variable", "VariableV2", "AutoReloadVariable"]) + + +def set_cpu0(device_string): + """Creates a new device string based on `device_string` but using /CPU:0. + + If the device is already on /CPU:0 or it is a custom device, this is a no-op. + + Args: + device_string: A device string. + + Returns: + A device string. + """ + if context.is_custom_device(device_string): + return device_string + parsed_device = pydev.DeviceSpec.from_string(device_string) + parsed_device = parsed_device.replace(device_type="CPU", device_index=0) + return parsed_device.to_string() + + +class ReferenceVariableSaveable(saveable_object.SaveableObject): + """SaveableObject implementation that handles reference variables.""" + + def __init__(self, var, slice_spec, name): + spec = saveable_object.SaveSpec(var, slice_spec, name, dtype=var.dtype) + super(ReferenceVariableSaveable, self).__init__(var, [spec], name) + + def restore(self, restored_tensors, restored_shapes): + restored_tensor = restored_tensors[0] + if restored_shapes is not None: + restored_tensor = array_ops.reshape(restored_tensor, restored_shapes[0]) + return state_ops.assign( + self.op, + restored_tensor, + validate_shape=restored_shapes is None and + self.op.get_shape().is_fully_defined()) + + +class ResourceVariableSaveable(saveable_object.SaveableObject): + """SaveableObject implementation that handles ResourceVariables.""" + + def __init__(self, var, slice_spec, name): + self._var_device = var.device + self._var_shape = var.shape + if isinstance(var, tensor_lib.Tensor): + self.handle_op = var.op.inputs[0] + tensor = var + elif resource_variable_ops.is_resource_variable(var): + + def _read_variable_closure(v): + def f(): + with ops.device(v.device): + if context.executing_eagerly() and not v.is_initialized(): + # A SaveSpec tensor value of `None` indicates that the variable is + # uninitialized. + return None + # Read the variable without making a copy to limit memory usage. + x = v.read_value_no_copy() + # To allow variables placed on non-CPU devices to be checkpointed, + # we copy them to CPU on the same machine first. + with ops.device("/device:CPU:0"): + return array_ops.identity(x) + + return f + + self.handle_op = var.handle + tensor = _read_variable_closure(var) + else: + raise ValueError( + "Saveable is neither a resource variable nor a read operation." + f" Got: {repr(var)}") + spec = saveable_object.SaveSpec(tensor, slice_spec, name, + dtype=var.dtype, device=var.device) + super(ResourceVariableSaveable, self).__init__(var, [spec], name) + + def restore(self, restored_tensors, restored_shapes): + """Restores tensors. Raises ValueError if incompatible shape found.""" + restored_tensor = restored_tensors[0] + if restored_shapes is not None: + restored_tensor = array_ops.reshape(restored_tensor, restored_shapes[0]) + # Copy the restored tensor to the variable's device. + with ops.device(self._var_device): + restored_tensor = array_ops.identity(restored_tensor) + try: + assigned_variable = resource_variable_ops.shape_safe_assign_variable_handle( + self.handle_op, self._var_shape, restored_tensor) + except ValueError as e: + raise ValueError( + f"Received incompatible tensor with shape {restored_tensor.shape} " + f"when attempting to restore variable with shape {self._var_shape} " + f"and name {self.name}.") from e + return assigned_variable + + +def _tensor_comes_from_variable(v): + return isinstance(v, tensor_lib.Tensor) and v.op.type in _VARIABLE_OPS + + +def saveable_objects_for_op(op, name): + """Create `SaveableObject`s from an operation. + + Args: + op: A variable, operation, or SaveableObject to coerce into a + SaveableObject. + name: A string name for the SaveableObject. + + Yields: + `SaveableObject`s which together save/restore `op`. + + Raises: + TypeError: If `name` is not a string. + ValueError: For operations with no known conversion to SaveableObject. + """ + if not isinstance(name, str): + raise TypeError( + "names_to_saveables must be a dict mapping string names to " + f"trackable operations. Name is not a string: {name}") + if isinstance(op, saveable_object.SaveableObject): + yield op + elif isinstance(op, (list, tuple, variables.PartitionedVariable)): + if isinstance(op, variables.PartitionedVariable): + op = list(op) + # A set of slices. + slice_name = None + # pylint: disable=protected-access + for variable in op: + if isinstance(variable, saveable_object.SaveableObject): + yield variable + continue + if not isinstance(variable, variables.Variable): + raise ValueError(f"Slices must all be Variables: {variable}") + if not variable._save_slice_info: + raise ValueError(f"Slices must all be slices: {variable}") + if slice_name is None: + slice_name = variable._save_slice_info.full_name + elif slice_name != variable._save_slice_info.full_name: + raise ValueError( + f"Slices must all be from the same tensor: {slice_name} != " + f"{variable._save_slice_info.full_name}") + if variable.op.type in _REF_VARIABLE_OPS: + yield ReferenceVariableSaveable( + variable, variable._save_slice_info.spec, name) + else: + yield ResourceVariableSaveable(variable, variable._save_slice_info.spec, + name) + # pylint: enable=protected-access + elif isinstance(op, trackable.Trackable) and not isinstance( + op, variables.Variable): + # pylint: disable=protected-access + for attr, factory in saveable_objects_from_trackable( + op, tf1_saver=True).items(): + if attr == trackable.VARIABLE_VALUE_KEY: + # Keep original name for classes masquerading as variables and + # Trackables that define _serialize_to_tensors. + full_name = name + elif attr == trackable_utils.SERIALIZE_TO_TENSORS_NAME: + full_name = name + else: + full_name = name + "_" + attr + op = (factory(full_name) if callable(factory) else factory) + for op in saveable_objects_for_op(op, op.name): + yield op + # pylint: enable=protected-access + else: + # A variable or tensor. + if isinstance(op, resource_variable_ops.BaseResourceVariable): + if op._in_graph_mode: # pylint: disable=protected-access + variable = op._graph_element # pylint: disable=protected-access + else: + variable = op + yield ResourceVariableSaveable(variable, "", name) + else: + if context.executing_eagerly(): + raise ValueError("Can only save/restore ResourceVariables when " + f"executing eagerly, got type: {type(op)}.") + + variable = ops.convert_to_tensor(op, as_ref=True) + if not _tensor_comes_from_variable(variable): + raise TypeError( + "names_to_saveables must be a dict mapping string " + f"names to Tensors/Variables. Not a variable: {variable}") + if variable.op.type in _REF_VARIABLE_OPS: + yield ReferenceVariableSaveable(variable, "", name) + else: + yield ResourceVariableSaveable(variable, "", name) + + +def op_list_to_dict(op_list, convert_variable_to_tensor=True): + """Create a dictionary of names to operation lists. + + This method is only used when the variable name matters (e.g. when saving + or restoring from a TF1 name-based checkpoint). In TF2, this can be called + from `tf.train.Checkpoint.restore` when loading from a name-based checkpoint. + + Args: + op_list: A (nested) list, tuple, or set of Variables or SaveableObjects. + convert_variable_to_tensor: Whether or not to convert single Variables + with no slice info into Tensors. + + Returns: + A dictionary of names to the operations that must be saved under + that name. Variables with save_slice_info are grouped together under the + same key in no particular order. + + Raises: + TypeError: If the type of op_list or its elements is not supported. + ValueError: If at least two saveables share the same name. + """ + if not isinstance(op_list, (list, tuple, set)): + raise TypeError("Variables to save should be passed in a dict or a " + f"list. Got {op_list}") + # List casting is necessary to support sets. + op_list = nest.flatten(list(op_list)) + # When ResourceVariables are converted to Tensors, read ops are added to the + # graph. Sorting the op_list ensures that the resulting graph is always + # constructed in a deterministic way: + op_list = sorted(op_list, key=lambda x: x.name) + names_to_saveables = {} + # pylint: disable=protected-access + for var in op_list: + resource_or_ref_variable = ( + isinstance(var, resource_variable_ops.BaseResourceVariable) or + isinstance(var, ref_variable.RefVariable)) + + if isinstance(var, saveable_object.SaveableObject): + names_to_saveables[var.name] = var + elif isinstance(var, variables.PartitionedVariable): + if var.name in names_to_saveables: + raise ValueError( + f"At least two variables have the same name: {var.name}") + names_to_saveables[var.name] = var + elif isinstance(var, variables.Variable) and var._save_slice_info: + name = var._save_slice_info.full_name + if name in names_to_saveables: + if not isinstance(names_to_saveables[name], list): + raise ValueError("Mixing slices and non-slices with the same name: " + f"{name}") + names_to_saveables[name].append(var) + else: + names_to_saveables[name] = [var] + elif isinstance(var, trackable.Trackable) and not resource_or_ref_variable: + trackable_saveables = [ + (factory() if callable(factory) else factory) + for factory in ( + saveable_objects_from_trackable(var, tf1_saver=True).values())] + names_to_saveables.update( + op_list_to_dict(trackable_saveables)) + else: + # Variables (reference and resource) have an _in_graph_mode property + # indicating whether they were created in a graph building context. We + # also get Tensors when graph building, which do not have this property. + if not getattr(var, "_in_graph_mode", True): + if not isinstance(var, resource_variable_ops.BaseResourceVariable): + raise ValueError( + "Can only save/restore ResourceVariables when eager execution " + f"is enabled. Got type: {type(var)}.") + set_var = names_to_saveables.setdefault(var._shared_name, var) + if set_var is not var: + raise ValueError( + "Two different ResourceVariable objects with the same " + f"shared_name '{var._shared_name}' were passed to the Saver. This" + " likely means that they were created in different Graphs or " + "isolated contexts, and may not be checkpointed together.") + else: + if convert_variable_to_tensor: + if isinstance(var, resource_variable_ops.BaseResourceVariable): + var = var._graph_element # pylint: disable=protected-access + else: + var = ops.convert_to_tensor(var, as_ref=True) + if not _tensor_comes_from_variable(var): + raise TypeError(f"Variable to save is not a Variable: {var}") + if var.op.type == "ReadVariableOp": + name = var.op.inputs[0].op.name + else: + name = var.op.name + if name in names_to_saveables: + raise ValueError(f"At least two variables have the same name: {name}") + names_to_saveables[name] = var + + # pylint: enable=protected-access + return names_to_saveables + + +def _add_saveable(saveables, seen_ops, saveable): + """Adds the saveable to the saveables list. + + Args: + saveables: List to append the SaveableObject to. + seen_ops: Set of the ops of the saveables already processed. Used to + check that each saveable is only saved once. + saveable: The saveable. + + Raises: + ValueError: If the saveable has already been processed. + """ + if saveable.op is not None and saveable.op in seen_ops: + raise ValueError("The same saveable will be restored with two names: " + f"{saveable.name}") + saveables.append(saveable) + seen_ops.add(saveable.op) + + +def validate_and_slice_inputs(names_to_saveables): + """Returns the variables and names that will be used for a Saver. + + Args: + names_to_saveables: A dict (k, v) where k is the name of an operation and + v is an operation to save or a BaseSaverBuilder.Saver. + + Returns: + A list of SaveableObjects. + + Raises: + TypeError: If any of the keys are not strings or any of the + values are not one of Tensor or Variable or a trackable operation. + ValueError: If the same operation is given in more than one value + (this also applies to slices of SlicedVariables). + """ + saveables = [] + seen_ops = object_identity.ObjectIdentitySet() + for name, op in sorted(names_to_saveables.items(), + # Avoid comparing ops, sort only by name. + key=lambda x: x[0]): + for converted_saveable_object in saveable_objects_for_op(op, name): + _add_saveable(saveables, seen_ops, converted_saveable_object) + return saveables + + +def validate_saveables_for_saved_model(saveables, obj): + """Makes sure SaveableObjects are compatible with SavedModel.""" + if isinstance(obj, python_state.PythonState): + logging.warn( + f"Note that object {obj} stores python values into the checkpoint. " + "These values will not be restored when loading the SavedModel " + "into python.") + return [] + if any(isinstance(saveable, trackable.NoRestoreSaveable) + for saveable in saveables): + return [] + return saveables + + +class RestoredSaveableObject(saveable_object.SaveableObject): + """SaveableObject restored from SavedModel using the traced save/restore.""" + + def __init__(self, names_and_slices, save_function, restore_function, name): + self.save_function = save_function + self.restore_function = restore_function + + if tensor_util.is_tf_type(name): + name_tensor = name + else: + with ops.init_scope(): + name_tensor = constant_op.constant(name) + tensors = save_function(name_tensor) + specs = [] + for (str_name, str_slice), tensor_info in zip(names_and_slices, tensors): + specs.append(saveable_object.SaveSpec(tensor_info["tensor"], str_slice, + name + str_name)) + super(RestoredSaveableObject, self).__init__(None, specs, name) + + def restore(self, restored_tensors, restored_shapes): + del restored_shapes # unused + return self.restore_function( + *[restored_tensors[i] for i in range(len(self.specs))]) + + +def recreate_saveable_objects(saveable_fn_by_name, temp_session): + """Returns a dict of SaveableObject factories generated from loaded fns.""" + + names_and_slices = [] + + with ops.init_scope(): + + for save_fn, _ in saveable_fn_by_name.values(): + for tensor_info in save_fn(""): + name = tensor_info["name"] + slice_spec = tensor_info["slice_spec"] + if not context.executing_eagerly(): + sess = ops.get_default_session() + if sess is None: + if temp_session[0] is not None: + sess = temp_session[0] + else: + sess = temp_session[0] = session.Session() + name, slice_spec = sess.run([name, slice_spec]) + names_and_slices.append(( + _convert_to_string(name), + _convert_to_string(slice_spec))) + + saveable_factories = {} + for name, (save_fn, restore_fn) in saveable_fn_by_name.items(): + saveable_factories[name] = functools.partial( + RestoredSaveableObject, + names_and_slices=names_and_slices, + save_function=save_fn, + restore_function=restore_fn) + return saveable_factories + + +def create_saveable_object(name, key, factory, call_with_mapped_captures): + """Creates a SaveableObject while potentially in a different graph. + + When creating the frozen saver for SavedModel, the save and restore ops are + placed in a separate graph. Since RestoredSaveableObject uses tf.functions to + save and restore, the function captures must be mapped to the new graph. + + Args: + name: Name of SaveableObject factory. + key: Checkpoint key of this SaveableObject. + factory: Factory method for creating the SaveableObject. + call_with_mapped_captures: Helper that calls a tf.function while remapping + the captures. + + Returns: + a SaveableObject. + """ + if call_with_mapped_captures is None: + return factory(name=key) + if name == trackable_utils.SERIALIZE_TO_TENSORS_NAME: + return factory(name=key, + call_with_mapped_captures=call_with_mapped_captures) + elif is_factory_for_restored_saveable_object(factory): + concrete_save_fn = factory.keywords["save_function"] + + def save_fn(name): + return call_with_mapped_captures(concrete_save_fn, [name]) + + concrete_restore_fn = factory.keywords["restore_function"] + + def restore_fn(*restored_tensors): + return call_with_mapped_captures(concrete_restore_fn, restored_tensors) + + return factory(save_function=save_fn, restore_function=restore_fn, + name=key) + else: + return factory(name=key) + + +def is_factory_for_restored_saveable_object(factory): + return (isinstance(factory, functools.partial) and + factory.func is RestoredSaveableObject) + + +@tf_export("__internal__.tracking.saveable_objects_from_trackable", v1=[]) +def saveable_objects_from_trackable(obj, tf1_saver=False): + """Returns SaveableObject factory dict from a Trackable. + + Args: + obj: A `Trackable` + tf1_saver: Boolean, whether this is being called from a TF1 Saver ( + `tf.compat.v1.train.Saver`). When this is True, the SaveableObject will + be generated from `obj`'s legacy `_gather_saveables_for_checkpoint` fn. + When saving with TF2, `Trackable._serialize_from_tensors` is preferred. + + Returns: + A dict mapping attribute names to SaveableObject factories (callables that + produce a SaveableObject). + """ + if isinstance(obj, python_state.PythonState): + return { + python_state.PYTHON_STATE: + functools.partial( + _PythonStringStateSaveable, + state_callback=obj.serialize, + restore_callback=obj.deserialize) + } + + if tf1_saver: + saveable_factories = obj._gather_saveables_for_checkpoint() # pylint: disable=protected-access + if saveable_factories: + return saveable_factories + + if trackable_has_serialize_to_tensor(obj): + + def create_saveable(name="", call_with_mapped_captures=None): + save_fn = obj._serialize_to_tensors # pylint: disable=protected-access + if (call_with_mapped_captures and + isinstance(save_fn, core.ConcreteFunction)): + tensor_dict = call_with_mapped_captures(save_fn, []) + else: + tensor_dict = save_fn() + + specs = [] + local_names = [] + for tensor_name, maybe_tensor in tensor_dict.items(): + local_names.append(tensor_name) + + if not isinstance(maybe_tensor, dict): + maybe_tensor = {"": maybe_tensor} + + spec_name = name + trackable_utils.escape_local_name(tensor_name) + # Create separate specs for each slice spec. + for slice_spec, tensor in maybe_tensor.items(): + if isinstance(tensor, saveable_object.SaveSpec): + spec = tensor + spec.name = spec_name + spec.slice_spec = slice_spec + else: + spec = saveable_object.SaveSpec(tensor, slice_spec, spec_name) + specs.append(spec) + + return TrackableSaveable( + obj=obj, + specs=specs, + name=name, + local_names=local_names, + prefix=saveable_compat.get_saveable_name(obj) or "", + call_with_mapped_captures=call_with_mapped_captures) + + return {trackable_utils.SERIALIZE_TO_TENSORS_NAME: create_saveable} + else: + return obj._gather_saveables_for_checkpoint() # pylint: disable=protected-access + + +class TrackableSaveable(saveable_object.SaveableObject): + """A SaveableObject that defines `Trackable` checkpointing steps.""" + + def __init__(self, obj, specs, name, local_names, prefix, + call_with_mapped_captures=None): + self._prefix = prefix + self._local_names = local_names + self._trackable = obj + self._call_with_mapped_captures = call_with_mapped_captures + super(TrackableSaveable, self).__init__(obj, specs, name) + + def restore(self, restored_tensors, restored_shapes): + del restored_shapes # Unused. + restored_tensor_dict = {} + for n, local_name in enumerate(self._local_names): + restored_tensor_dict[local_name] = restored_tensors[n] + + restore_fn = self._trackable._restore_from_tensors # pylint: disable=protected-access + + # When restoring a RefVariable, call the restore function directly. + # pylint: disable=protected-access + if not ops.executing_eagerly_outside_functions() and any([ + spec._tensor.op.type in _REF_VARIABLE_OPS + for spec in self.specs + if isinstance(spec._tensor, tensor_lib.Tensor)]): + return restore_fn(restored_tensor_dict) + # pylint: enable=protected-access + + if (self._call_with_mapped_captures and + isinstance(restore_fn, core.ConcreteFunction)): + ret = self._call_with_mapped_captures(restore_fn, [restored_tensor_dict]) + else: + ret = restore_fn(restored_tensor_dict) + if ret is not None: + return ret + return gen_control_flow_ops.no_op() + + def get_proto_names_and_checkpoint_keys(self): + return [(self._prefix + local_name, spec.name) + for local_name, spec in zip(self._local_names, self.specs)] + + +class _PythonStringStateSaveable(saveable_object.SaveableObject): + """Saves Python state in a checkpoint.""" + + def __init__(self, name, state_callback, restore_callback): + """Configure saving. + + Args: + name: The checkpoint key to write to. + state_callback: A function taking no arguments which returns a string. + This function is run every time a checkpoint is written. + restore_callback: A function taking a Python string, used to restore + state. + """ + + def _state_callback_wrapper(): + with ops.init_scope(): + return state_callback() + + self._state_callback = _state_callback_wrapper + self._restore_callback = restore_callback + with ops.device("/cpu:0"): + self._save_string = constant_op.constant("", dtype=dtypes.string) + spec = saveable_object.SaveSpec( + self._save_string, "", name, dtype=dtypes.string) + super(_PythonStringStateSaveable, self).__init__(self._save_string, [spec], + name) + + def feed_dict_additions(self): + """When running a graph, indicates fresh state to feed.""" + return {self._save_string: self._state_callback()} + + def freeze(self): + """Create a frozen `SaveableObject` which saves the current state.""" + + def _constant_state(): + return constant_op.constant(self._state_callback(), dtype=dtypes.string) + + return trackable.NoRestoreSaveable( + tensor=_constant_state, + dtype=dtypes.string, + name=self.name, + device="cpu:0") + + +def trackable_has_serialize_to_tensor(obj): + """Returns whether obj's class has `_serialize_to_tensors` defined.""" + if obj is base_delegate.DelegatingTrackableMixin: + # DelegatingTrackableMixin always delegates "_serialize_to_tensors" + # to its inner `trackable`, so we check whether the inner trackable + # has `_serialize_to_tensor`. + return trackable_has_serialize_to_tensor(obj._trackable) # pylint: disable=protected-access + + try: + if "_serialize_to_tensors" in obj.__dict__: + # In some cases (e.g. restored objects), the object may have + # `_serialize_to_tensors` even if the class does not. + return True + except (AttributeError, TypeError): + # Data structure proxy wrappers don't have __dict__. + pass + + # Use MRO so that if a parent class has `_serialize_to_tensors`, but the + # object class has not yet been migrated, we'll continue to use the obj + # class's `_gather_saveables_for_checkpoint` method. + for t in type(obj).mro(): + if t is base_delegate.DelegatingTrackableMixin: + # DelegatingTrackableMixin always delegates "_serialize_to_tensors" + # to its inner `trackable`, so we check whether the inner trackable + # has `_serialize_to_tensor`. + return trackable_has_serialize_to_tensor(obj._trackable) # pylint: disable=protected-access + if t is trackable.Trackable: + # Base case. Return False since _serialize_to_tensors will raise a + # NotImplemented Error. + return False + elif "_serialize_to_tensors" in t.__dict__: + return True + elif "_gather_saveables_for_checkpoint" in t.__dict__: + return False + return False + + +def _convert_to_string(x): + return compat.as_str(tensor_util.constant_value(x)) + + +class SaveableCompatibilityConverter(trackable.Trackable): + """Converts object's `SaveableObjects` to functions used in TF2 checkpointing. + + A class that converts a Trackable object's `SaveableObjects` to save and + restore functions with the same signatures as + `Trackable._serialize_to_tensors` and `Trackable._restore_from_tensors`. + This class also produces a method for filling the object proto. + """ + + __slots__ = ("_obj", "_saveables") + + def __init__(self, obj, saveables): + """Constructor. + + Args: + obj: A Trackable object. + saveables: A list of saveables for `obj`. + """ + self._obj = obj + self._saveables = saveables + + @property + def obj(self): + return self._obj + + @property + def saveables(self): + """Returns a list of SaveableObjects generated from the Trackable object.""" + return self._saveables + + def _serialize_to_tensors(self): + """Returns a dict of tensors to serialize.""" + return saveable_object_to_tensor_dict(self.saveables) + + def _restore_from_tensors(self, restored_tensors): + """Returns the restore ops defined in the Saveables.""" + # Map restored tensors to the corresponding SaveableObjects, then call + # restore. There must be an exact match between restored tensors and the + # expected attributes. + expected_keys = [] + for saveable in self.saveables: + expected_keys.extend( + trackable_utils.extract_local_name(_convert_to_string(spec.name)) + for spec in saveable.specs) + if set(expected_keys) != restored_tensors.keys(): + raise ValueError(f"Could not restore object {self._obj} because not all " + "expected tensors were in the checkpoint." + f"\n\tExpected: {expected_keys}" + f"\n\tGot: {list(restored_tensors.keys())}") + + return saveable_object_to_restore_fn(self.saveables)(restored_tensors) + + +def saveable_object_to_tensor_dict(saveables): + """Converts a list of SaveableObjects to a tensor dictionary.""" + tensor_dict = {} + for saveable in saveables: + for spec in saveable.specs: + name = _convert_to_string(spec.name) + slice_spec = _convert_to_string(spec.slice_spec) + # Currently, tensor dict cannot handle callable tensor values (which + # are needed for uninitialized variables), so keep using SaveSpec. + tensor = spec if callable(spec._tensor) else spec._tensor # pylint: disable=protected-access + if slice_spec: + tensor_dict.setdefault(name, {})[slice_spec] = tensor + else: + tensor_dict[name] = tensor + return tensor_dict + + +def saveable_object_to_restore_fn(saveables): + """Generates `Trackable._restore_from_tensors` from SaveableObjects.""" + + def _restore_from_tensors(restored_tensors): + restore_ops = {} + + for saveable in saveables: + saveable_restored_tensors = [] + for spec in saveable.specs: + name = trackable_utils.extract_local_name(_convert_to_string(spec.name)) + slice_spec = _convert_to_string(spec.slice_spec) + + maybe_tensor = restored_tensors[name] + if not isinstance(maybe_tensor, dict): + maybe_tensor = {"": maybe_tensor} + + saveable_restored_tensors.append(maybe_tensor[slice_spec]) + restore_ops[saveable.name] = saveable.restore( + saveable_restored_tensors, restored_shapes=None) + return restore_ops + + return _restore_from_tensors + + +def serialized_tensors_to_saveable_cache(serialized_tensors): + """Converts a tensor dict to a SaveableObject cache. + + Args: + serialized_tensors: Map from Trackable to a tensor dict. The tensor dict + maps checkpoint key (-> slice_spec) -> Tensor + + Returns: + A dict mapping Trackable objects to a map from local savable name to + SaveableObject. + """ + saveables_cache = object_identity.ObjectIdentityWeakKeyDictionary() + + for obj, tensor_dict in serialized_tensors.items(): + if not tensor_dict: continue + if isinstance(obj, SaveableCompatibilityConverter): + trackable_obj = obj.obj + saveables_cache[trackable_obj] = {} + for saveable in obj.saveables: + local_name = trackable_utils.extract_local_name(saveable.name) + saveables_cache[trackable_obj][local_name] = [saveable] + continue + + specs = [] + # The local names and prefixes are computed to ensure that the generated + # SaveableObject can call `Trackable._restore_from_tensors()` + local_names = [] + prefix = saveable_compat.get_saveable_name(obj) or "" + for checkpoint_key, maybe_tensor in tensor_dict.items(): + # Make sure that `maybe_tensor` is a dict from `slice_spec` to `tensor`. + if not isinstance(maybe_tensor, dict): + maybe_tensor = {"": maybe_tensor} + + for slice_spec, tensor in maybe_tensor.items(): + if isinstance(tensor, saveable_object.SaveSpec): + specs.append(tensor) + else: + specs.append(saveable_object.SaveSpec(tensor, + slice_spec, + checkpoint_key)) + local_names.append(trackable_utils.extract_local_name(checkpoint_key, + prefix)) + + object_name = trackable_utils.extract_object_name( + next(iter(tensor_dict.keys()))) + saveables_cache[obj] = { + trackable_utils.SERIALIZE_TO_TENSORS_NAME: [TrackableSaveable( + obj, specs, object_name, local_names=local_names, prefix=prefix)]} + return saveables_cache diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/saving/trace_saveable_util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/saving/trace_saveable_util.py new file mode 100644 index 0000000000000000000000000000000000000000..de111a3629359269ecfc21c175bb4fa8a42e08fb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/saving/trace_saveable_util.py @@ -0,0 +1,116 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Utilities for tracing save and restore functions for SaveableObjects.""" + +from tensorflow.python.eager import def_function +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import tensor_spec +from tensorflow.python.framework import type_spec + +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.training.saving import saveable_object +from tensorflow.python.training.saving import saveable_object_util +from tensorflow.python.util import nest + + +def trace_save_restore_function_map(obj, factory_data_list): + """Traces all save and restore functions in the provided factory list. + + Args: + obj: `Trackable` object. + factory_data_list: List of `_CheckpointFactoryData`. + + Returns: + Dict mapping atttribute names to tuples of concrete save/restore functions. + """ + saveable_fns = {} + + for factory_data in factory_data_list: + saveable_factory = factory_data.factory + attribute_name = factory_data.name + + # If object revives as a resource (or TPU/Mirrored) variable, + # there is no need to trace the save and restore functions. + if (resource_variable_ops.is_resource_variable(obj) or + resource_variable_ops.is_resource_variable(saveable_factory) or + not callable(saveable_factory)): + continue + + concrete_save, concrete_restore = ( + _trace_save_restore_functions(saveable_factory, obj)) + if not concrete_save: + continue + saveable_fns[attribute_name] = (concrete_save, concrete_restore) + return saveable_fns + + +def _trace_save_restore_functions(saveable_factory, obj): + """Traces save and restore functions.""" + if saveable_object_util.is_factory_for_restored_saveable_object( + saveable_factory): + return ( + saveable_factory.keywords["save_function"], + saveable_factory.keywords["restore_function"], + ) + + saveables = [] # Store the saveables in a data structure accessible to both + # the save and restore functions. + + @def_function.function( + input_signature=[tensor_spec.TensorSpec([], dtypes.string)] + ) + def save_fn(checkpoint_key): + maybe_saveable = saveable_factory(name=checkpoint_key) + if isinstance(maybe_saveable, saveable_object.SaveableObject): + maybe_saveable = [maybe_saveable] + saveables[:] = maybe_saveable + + # Return list of all SaveSpecs created by the factory. + ret = [] + for saveable in saveables: + for spec in saveable.specs: + ret.append({"name": spec.name, "tensor": spec.tensor, + "slice_spec": spec.slice_spec}) + return ret + + concrete_save = save_fn.get_concrete_function() + + # The SaveableObjects are produced when `save_fn` is traced. + saveables = saveable_object_util.validate_saveables_for_saved_model( + saveables, obj) + if not saveables: + return None, None + + # Use the SaveSpecs to define the input signature of the restore function. + restored_type_specs = [] + tensor_structure = [] + for saveable in saveables: + saveable_tensor_structure = [] + tensor_structure.append(saveable_tensor_structure) + for spec in saveable.specs: + restored_type_specs.append(type_spec.type_spec_from_value(spec.tensor)) + saveable_tensor_structure.append(spec.name) + + @def_function.function(input_signature=restored_type_specs) + def restore_fn(*restored_tensors): + structured_restored_tensors = nest.pack_sequence_as( + tensor_structure, restored_tensors) + for saveable, restored_tensors in zip(saveables, + structured_restored_tensors): + saveable.restore(restored_tensors, restored_shapes=None) + return 1 # Return dummy tensor + + concrete_restore = restore_fn.get_concrete_function() + return concrete_save, concrete_restore diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/server_lib.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/server_lib.py new file mode 100644 index 0000000000000000000000000000000000000000..97a5d0cb3a6ad32768a1ebcf33908145b5b86ef8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/server_lib.py @@ -0,0 +1,574 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""A Python interface for creating TensorFlow servers.""" + +from tensorflow.core.protobuf import cluster_pb2 +from tensorflow.core.protobuf import device_filters_pb2 +from tensorflow.core.protobuf import tensorflow_server_pb2 +from tensorflow.python.client import pywrap_tf_session as c_api +from tensorflow.python.framework import errors +from tensorflow.python.util import compat +from tensorflow.python.util import deprecation +from tensorflow.python.util.tf_export import tf_export + + +def _make_server_def(server_or_cluster_def, job_name, task_index, protocol, + config): + """Creates a `tf.train.ServerDef` protocol buffer. + + Args: + server_or_cluster_def: A `tf.train.ServerDef` or `tf.train.ClusterDef` + protocol buffer, or a `tf.train.ClusterSpec` object, describing the server + to be defined and/or the cluster of which it is a member. + job_name: (Optional.) Specifies the name of the job of which the server is a + member. Defaults to the value in `server_or_cluster_def`, if specified. + task_index: (Optional.) Specifies the task index of the server in its job. + Defaults to the value in `server_or_cluster_def`, if specified. Otherwise + defaults to 0 if the server's job has only one task. + protocol: (Optional.) Specifies the protocol to be used by the server. + Acceptable values include `"grpc", "grpc+verbs"`. Defaults to the value in + `server_or_cluster_def`, if specified. Otherwise defaults to `"grpc"`. + config: (Options.) A `tf.compat.v1.ConfigProto` that specifies default + configuration options for all sessions that run on this server. + + Returns: + A `tf.train.ServerDef`. + + Raises: + TypeError: If the arguments do not have the appropriate type. + ValueError: If an argument is not specified and cannot be inferred. + """ + server_def = tensorflow_server_pb2.ServerDef() + if isinstance(server_or_cluster_def, tensorflow_server_pb2.ServerDef): + server_def.MergeFrom(server_or_cluster_def) + if job_name is not None: + server_def.job_name = job_name + if task_index is not None: + server_def.task_index = task_index + if protocol is not None: + server_def.protocol = protocol + if config is not None: + server_def.default_session_config.MergeFrom(config) + else: + try: + cluster_spec = ClusterSpec(server_or_cluster_def) + except TypeError: + raise TypeError("Could not convert `server_or_cluster_def` to a " + "`tf.train.ServerDef` or `tf.train.ClusterSpec`.") + if job_name is None: + if len(cluster_spec.jobs) == 1: + job_name = cluster_spec.jobs[0] + else: + raise ValueError("Must specify an explicit `job_name`.") + if task_index is None: + task_indices = cluster_spec.task_indices(job_name) + if len(task_indices) == 1: + task_index = task_indices[0] + else: + raise ValueError("Must specify an explicit `task_index`.") + if protocol is None: + protocol = "grpc" + + server_def = tensorflow_server_pb2.ServerDef( + cluster=cluster_spec.as_cluster_def(), + job_name=job_name, + task_index=task_index, + protocol=protocol) + if config is not None: + server_def.default_session_config.MergeFrom(config) + return server_def + + +@tf_export("distribute.Server", v1=["distribute.Server", "train.Server"]) +@deprecation.deprecated_endpoints("train.Server") +class Server: + """An in-process TensorFlow server, for use in distributed training. + + A `tf.distribute.Server` instance encapsulates a set of devices and a + `tf.compat.v1.Session` target that + can participate in distributed training. A server belongs to a + cluster (specified by a `tf.train.ClusterSpec`), and + corresponds to a particular task in a named job. The server can + communicate with any other server in the same cluster. + """ + + def __init__(self, + server_or_cluster_def, + job_name=None, + task_index=None, + protocol=None, + config=None, + start=True): + """Creates a new server with the given definition. + + The `job_name`, `task_index`, and `protocol` arguments are optional, and + override any information provided in `server_or_cluster_def`. + + Args: + server_or_cluster_def: A `tf.train.ServerDef` or `tf.train.ClusterDef` + protocol buffer, or a `tf.train.ClusterSpec` object, describing the + server to be created and/or the cluster of which it is a member. + job_name: (Optional.) Specifies the name of the job of which the server is + a member. Defaults to the value in `server_or_cluster_def`, if + specified. + task_index: (Optional.) Specifies the task index of the server in its job. + Defaults to the value in `server_or_cluster_def`, if specified. + Otherwise defaults to 0 if the server's job has only one task. + protocol: (Optional.) Specifies the protocol to be used by the server. + Acceptable values include `"grpc", "grpc+verbs"`. Defaults to the value + in `server_or_cluster_def`, if specified. Otherwise defaults to + `"grpc"`. + config: (Options.) A `tf.compat.v1.ConfigProto` that specifies default + configuration options for all sessions that run on this server. + start: (Optional.) Boolean, indicating whether to start the server after + creating it. Defaults to `True`. + + Raises: + tf.errors.OpError: Or one of its subclasses if an error occurs while + creating the TensorFlow server. + """ + self._server_def = _make_server_def(server_or_cluster_def, job_name, + task_index, protocol, config) + self._server = c_api.TF_NewServer(self._server_def.SerializeToString()) + if start: + self.start() + + def __del__(self): + # At shutdown, `errors` may have been garbage collected. + if errors is not None: + exception = errors.UnimplementedError + else: + exception = Exception + try: + c_api.TF_ServerStop(self._server) + # Clean shutdown of servers is not yet implemented, so + # we leak instead of calling c_api.TF_DeleteServer here. + # See: + # https://github.com/tensorflow/tensorflow/blob/0495317a6e9dd4cac577b9d5cf9525e62b571018/tensorflow/core/distributed_runtime/rpc/grpc_server_lib.h#L73 + except AttributeError: + # At shutdown, `c_api` may have been garbage collected. + pass + except exception: + pass + self._server = None + + def start(self): + """Starts this server. + + Raises: + tf.errors.OpError: Or one of its subclasses if an error occurs while + starting the TensorFlow server. + """ + c_api.TF_ServerStart(self._server) + + def join(self): + """Blocks until the server has shut down. + + This method currently blocks forever. + + Raises: + tf.errors.OpError: Or one of its subclasses if an error occurs while + joining the TensorFlow server. + """ + c_api.TF_ServerJoin(self._server) + + @property + def server_def(self): + """Returns the `tf.train.ServerDef` for this server. + + Returns: + A `tf.train.ServerDef` protocol buffer that describes the configuration + of this server. + """ + return self._server_def + + @property + def target(self): + """Returns the target for a `tf.compat.v1.Session` to connect to this server. + + To create a + `tf.compat.v1.Session` that + connects to this server, use the following snippet: + + ```python + server = tf.distribute.Server(...) + with tf.compat.v1.Session(server.target): + # ... + ``` + + Returns: + A string containing a session target for this server. + """ + return c_api.TF_ServerTarget(self._server) + + @staticmethod + def create_local_server(config=None, start=True): + """Creates a new single-process cluster running on the local host. + + This method is a convenience wrapper for creating a + `tf.distribute.Server` with a `tf.train.ServerDef` that specifies a + single-process cluster containing a single task in a job called + `"local"`. + + Args: + config: (Options.) A `tf.compat.v1.ConfigProto` that specifies default + configuration options for all sessions that run on this server. + start: (Optional.) Boolean, indicating whether to start the server after + creating it. Defaults to `True`. + + Returns: + A local `tf.distribute.Server`. + """ + # Specifying port 0 means that the OS will choose a free port for the + # server. + return Server({"localhost": ["localhost:0"]}, + protocol="grpc", + config=config, + start=start) + + +@tf_export("train.ClusterSpec") +class ClusterSpec: + """Represents a cluster as a set of "tasks", organized into "jobs". + + A `tf.train.ClusterSpec` represents the set of processes that + participate in a distributed TensorFlow computation. Every + `tf.distribute.Server` is constructed in a particular cluster. + + To create a cluster with two jobs and five tasks, you specify the + mapping from job names to lists of network addresses (typically + hostname-port pairs). + + ```python + cluster = tf.train.ClusterSpec({"worker": ["worker0.example.com:2222", + "worker1.example.com:2222", + "worker2.example.com:2222"], + "ps": ["ps0.example.com:2222", + "ps1.example.com:2222"]}) + ``` + + Each job may also be specified as a sparse mapping from task indices + to network addresses. This enables a server to be configured without + needing to know the identity of (for example) all other worker + tasks: + + ```python + cluster = tf.train.ClusterSpec({"worker": {1: "worker1.example.com:2222"}, + "ps": ["ps0.example.com:2222", + "ps1.example.com:2222"]}) + ``` + """ + + def __init__(self, cluster): + """Creates a `ClusterSpec`. + + Args: + cluster: A dictionary mapping one or more job names to (i) a list of + network addresses, or (ii) a dictionary mapping integer task indices to + network addresses; or a `tf.train.ClusterDef` protocol buffer. + + Raises: + TypeError: If `cluster` is not a dictionary mapping strings to lists + of strings, and not a `tf.train.ClusterDef` protobuf. + """ + if isinstance(cluster, dict): + self._cluster_spec = {} + for job_name, tasks in cluster.items(): + if isinstance(tasks, (list, tuple)): + job_tasks = {i: task for i, task in enumerate(tasks)} + elif isinstance(tasks, dict): + job_tasks = {int(i): task for i, task in tasks.items()} + else: + raise TypeError("The tasks for job %r must be a list or a dictionary " + "from integers to strings." % job_name) + self._cluster_spec[job_name] = job_tasks + self._make_cluster_def() + elif isinstance(cluster, cluster_pb2.ClusterDef): + self._cluster_def = cluster + self._cluster_spec = {} + for job_def in self._cluster_def.job: + self._cluster_spec[job_def.name] = { + i: t for i, t in job_def.tasks.items() + } + elif isinstance(cluster, ClusterSpec): + self._cluster_def = cluster_pb2.ClusterDef() + self._cluster_def.MergeFrom(cluster.as_cluster_def()) + self._cluster_spec = {} + for job_def in self._cluster_def.job: + self._cluster_spec[job_def.name] = { + i: t for i, t in job_def.tasks.items() + } + else: + raise TypeError("`cluster` must be a dictionary mapping one or more " + "job names to lists of network addresses, or a " + "`ClusterDef` protocol buffer") + + def __bool__(self): + return bool(self._cluster_spec) + + # Python 2.x + __nonzero__ = __bool__ + + def __eq__(self, other): + return self._cluster_spec == other + + def __ne__(self, other): + return self._cluster_spec != other + + def __repr__(self): + key_values = self.as_dict() + string_items = [ + repr(k) + ": " + repr(key_values[k]) for k in sorted(key_values) + ] + return "ClusterSpec({" + ", ".join(string_items) + "})" + + def as_dict(self): + """Returns a dictionary from job names to their tasks. + + For each job, if the task index space is dense, the corresponding + value will be a list of network addresses; otherwise it will be a + dictionary mapping (sparse) task indices to the corresponding + addresses. + + Returns: + A dictionary mapping job names to lists or dictionaries + describing the tasks in those jobs. + """ + ret = {} + for job in self.jobs: + task_indices = self.task_indices(job) + if len(task_indices) == 0: + ret[job] = {} + continue + if max(task_indices) + 1 == len(task_indices): + # Return a list because the task indices are dense. This + # matches the behavior of `as_dict()` before support for + # sparse jobs was added. + ret[job] = self.job_tasks(job) + else: + ret[job] = {i: self.task_address(job, i) for i in task_indices} + return ret + + def as_cluster_def(self): + """Returns a `tf.train.ClusterDef` protocol buffer based on this cluster.""" + return self._cluster_def + + @property + def jobs(self): + """Returns a list of job names in this cluster. + + Returns: + A list of strings, corresponding to the names of jobs in this cluster. + """ + return list(self._cluster_spec.keys()) + + def num_tasks(self, job_name): + """Returns the number of tasks defined in the given job. + + Args: + job_name: The string name of a job in this cluster. + + Returns: + The number of tasks defined in the given job. + + Raises: + ValueError: If `job_name` does not name a job in this cluster. + """ + try: + job = self._cluster_spec[job_name] + except KeyError: + raise ValueError("No such job in cluster: %r" % job_name) + return len(job) + + def task_indices(self, job_name): + """Returns a list of valid task indices in the given job. + + Args: + job_name: The string name of a job in this cluster. + + Returns: + A list of valid task indices in the given job. + + Raises: + ValueError: If `job_name` does not name a job in this cluster, + or no task with index `task_index` is defined in that job. + """ + try: + job = self._cluster_spec[job_name] + except KeyError: + raise ValueError("No such job in cluster: %r" % job_name) + return list(sorted(job.keys())) + + def task_address(self, job_name, task_index): + """Returns the address of the given task in the given job. + + Args: + job_name: The string name of a job in this cluster. + task_index: A non-negative integer. + + Returns: + The address of the given task in the given job. + + Raises: + ValueError: If `job_name` does not name a job in this cluster, + or no task with index `task_index` is defined in that job. + """ + try: + job = self._cluster_spec[job_name] + except KeyError: + raise ValueError("No such job in cluster: %r" % job_name) + try: + return job[task_index] + except KeyError: + raise ValueError("No task with index %r in job %r" % + (task_index, job_name)) + + def job_tasks(self, job_name): + """Returns a mapping from task ID to address in the given job. + + NOTE: For backwards compatibility, this method returns a list. If + the given job was defined with a sparse set of task indices, the + length of this list may not reflect the number of tasks defined in + this job. Use the `tf.train.ClusterSpec.num_tasks` method + to find the number of tasks defined in a particular job. + + Args: + job_name: The string name of a job in this cluster. + + Returns: + A list of task addresses, where the index in the list + corresponds to the task index of each task. The list may contain + `None` if the job was defined with a sparse set of task indices. + + Raises: + ValueError: If `job_name` does not name a job in this cluster. + """ + try: + job = self._cluster_spec[job_name] + except KeyError: + raise ValueError("No such job in cluster: %r" % job_name) + ret = [None for _ in range(max(job.keys()) + 1)] + for i, task in job.items(): + ret[i] = task + return ret + + def _make_cluster_def(self): + """Creates a `tf.train.ClusterDef` based on the given `cluster_spec`. + + Raises: + TypeError: If `cluster_spec` is not a dictionary mapping strings to lists + of strings. + """ + self._cluster_def = cluster_pb2.ClusterDef() + + # NOTE(mrry): Sort by job_name to produce deterministic protobufs. + for job_name, tasks in sorted(self._cluster_spec.items()): + try: + job_name = compat.as_bytes(job_name) + except TypeError: + raise TypeError("Job name %r must be bytes or unicode" % job_name) + + job_def = self._cluster_def.job.add() + job_def.name = job_name + + for i, task_address in sorted(tasks.items()): + try: + task_address = compat.as_bytes(task_address) + except TypeError: + raise TypeError("Task address %r must be bytes or unicode" % + task_address) + job_def.tasks[i] = task_address + + +@tf_export("config.experimental.ClusterDeviceFilters") +class ClusterDeviceFilters: + """Represent a collection of device filters for the remote workers in cluster. + + NOTE: this is an experimental API and subject to changes. + + Set device filters for selective jobs and tasks. For each remote worker, the + device filters are a list of strings. When any filters are present, the remote + worker will ignore all devices which do not match any of its filters. Each + filter can be partially specified, e.g. "/job:ps", "/job:worker/replica:3", + etc. Note that a device is always visible to the worker it is located on. + + For example, to set the device filters for a parameter server cluster: + + ```python + cdf = tf.config.experimental.ClusterDeviceFilters() + for i in range(num_workers): + cdf.set_device_filters('worker', i, ['/job:ps']) + for i in range(num_ps): + cdf.set_device_filters('ps', i, ['/job:worker']) + + tf.config.experimental_connect_to_cluster(cluster_def, + cluster_device_filters=cdf) + ``` + + The device filters can be partically specified. For remote tasks that do not + have device filters specified, all devices will be visible to them. + """ + + def __init__(self): + # `_device_filters` is a dict mapping job names to job device filters. + # Job device filters further maps task IDs to task device filters. + # Task device filters are a list of strings, each one is a device filter. + self._device_filters = {} + + # Serialized protobuf for cluster device filters. + self._cluster_device_filters = None + + def set_device_filters(self, job_name, task_index, device_filters): + """Set the device filters for given job name and task id.""" + assert all(isinstance(df, str) for df in device_filters) + self._device_filters.setdefault(job_name, {}) + self._device_filters[job_name][task_index] = [df for df in device_filters] + # Due to updates in data, invalidate the serialized proto cache. + self._cluster_device_filters = None + + def _as_cluster_device_filters(self): + """Returns a serialized protobuf of cluster device filters.""" + if self._cluster_device_filters: + return self._cluster_device_filters + + self._make_cluster_device_filters() + return self._cluster_device_filters + + def _make_cluster_device_filters(self): + """Creates `ClusterDeviceFilters` proto based on the `_device_filters`. + + Raises: + TypeError: If `_device_filters` is not a dictionary mapping strings to + a map of task indices and device filters. + """ + self._cluster_device_filters = device_filters_pb2.ClusterDeviceFilters() + + # Sort by job_name to produce deterministic protobufs. + for job_name, tasks in sorted(self._device_filters.items()): + try: + job_name = compat.as_bytes(job_name) + except TypeError: + raise TypeError("Job name %r must be bytes or unicode" % job_name) + + jdf = self._cluster_device_filters.jobs.add() + jdf.name = job_name + + for i, task_device_filters in sorted(tasks.items()): + for tdf in task_device_filters: + try: + tdf = compat.as_bytes(tdf) + except TypeError: + raise TypeError("Device filter %r must be bytes or unicode" % tdf) + jdf.tasks[i].device_filters.append(tdf) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/session_manager.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/session_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..af2797bb309352e0efb12f2f3ce7279b6b591cf8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/session_manager.py @@ -0,0 +1,607 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Training helper that checkpoints models and creates session.""" + +import time +from typing import Optional, Tuple + +import numpy as np + +from tensorflow.python.checkpoint import checkpoint_management +from tensorflow.python.client import session +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.framework import errors +from tensorflow.python.framework import ops +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.training import saver as saver_lib +from tensorflow.python.util.tf_export import tf_export + + +def _maybe_name(obj) -> str: + """Returns object name if it has one, or a message otherwise. + + This is useful for names that apper in error messages. + Args: + obj: Object to get the name of. + Returns: + name, "None", or a "no name" message. + """ + if obj is None: + return "None" + elif hasattr(obj, "name"): + return obj.name + else: + return "" % type(obj) + + +def _restore_checkpoint_and_maybe_run_saved_model_initializers( + sess: session.Session, saver: saver_lib.Saver, path: str +): + """Restores checkpoint values and SavedModel initializers if found.""" + # NOTE: All references to SavedModel refer to SavedModels loaded from the + # load_v2 API (which does not require the `sess` argument). + + # If the graph contains resources loaded from a SavedModel, they are not + # restored when calling `saver.restore`. Thus, the SavedModel initializer must + # be called with `saver.restore` to properly initialize the model. + + # The SavedModel init is stored in the "saved_model_initializers" collection. + # This collection is part of the MetaGraph's default_init_op, so it is already + # called by MonitoredSession as long as the saver doesn't restore any + # checkpoints from the working dir. + saved_model_init_ops = ops.get_collection("saved_model_initializers") + if saved_model_init_ops: + sess.run(saved_model_init_ops) + + # The saver must be called *after* the SavedModel init, because the SavedModel + # init will restore the variables from the SavedModel variables directory. + # Initializing/restoring twice is not ideal but there's no other way to do it. + saver.restore(sess, path) + + +@tf_export(v1=["train.SessionManager"]) +class SessionManager: + """Training helper that restores from checkpoint and creates session. + + This class is a small wrapper that takes care of session creation and + checkpoint recovery. It also provides functions that to facilitate + coordination among multiple training threads or processes. + + * Checkpointing trained variables as the training progresses. + * Initializing variables on startup, restoring them from the most recent + checkpoint after a crash, or wait for checkpoints to become available. + + ### Usage: + + ```python + with tf.Graph().as_default(): + ...add operations to the graph... + # Create a SessionManager that will checkpoint the model in '/tmp/mydir'. + sm = SessionManager() + sess = sm.prepare_session(master, init_op, saver, checkpoint_dir) + # Use the session to train the graph. + while True: + sess.run() + ``` + + `prepare_session()` initializes or restores a model. It requires `init_op` + and `saver` as an argument. + + A second process could wait for the model to be ready by doing the following: + + ```python + with tf.Graph().as_default(): + ...add operations to the graph... + # Create a SessionManager that will wait for the model to become ready. + sm = SessionManager() + sess = sm.wait_for_session(master) + # Use the session to train the graph. + while True: + sess.run() + ``` + + `wait_for_session()` waits for a model to be initialized by other processes. + + """ + + def __init__( + self, + local_init_op: ops.Operation = None, + ready_op: ops.Operation = None, + ready_for_local_init_op: ops.Operation = None, + graph: ops.Graph = None, + recovery_wait_secs=30, + local_init_run_options: "distribute_lib.RunOptions" = None, + local_init_feed_dict=None, + ): + """Creates a SessionManager. + + The `local_init_op` is an `Operation` that is run always after a new session + was created. If `None`, this step is skipped. + + The `ready_op` is an `Operation` used to check if the model is ready. The + model is considered ready if that operation returns an empty 1D string + tensor. If the operation returns a non empty 1D string tensor, the elements + are concatenated and used to indicate to the user why the model is not + ready. + + The `ready_for_local_init_op` is an `Operation` used to check if the model + is ready to run local_init_op. The model is considered ready if that + operation returns an empty 1D string tensor. If the operation returns a non + empty 1D string tensor, the elements are concatenated and used to indicate + to the user why the model is not ready. + + If `ready_op` is `None`, the model is not checked for readiness. + + `recovery_wait_secs` is the number of seconds between checks that + the model is ready. It is used by processes to wait for a model to + be initialized or restored. Defaults to 30 seconds. + + Args: + local_init_op: An `Operation` run immediately after session creation. + Usually used to initialize tables and local variables. + ready_op: An `Operation` to check if the model is initialized. + ready_for_local_init_op: An `Operation` to check if the model is ready + to run local_init_op. + graph: The `Graph` that the model will use. + recovery_wait_secs: Seconds between checks for the model to be ready. + local_init_run_options: RunOptions to be passed to session.run when + executing the local_init_op. + local_init_feed_dict: Optional session feed dictionary to use when running + the local_init_op. + + Raises: + ValueError: If ready_for_local_init_op is not None but local_init_op is + None + """ + # Sets default values of arguments. + if graph is None: + graph = ops.get_default_graph() + self._local_init_op = local_init_op + self._ready_op = ready_op + self._ready_for_local_init_op = ready_for_local_init_op + self._graph = graph + self._recovery_wait_secs = recovery_wait_secs + self._target = None + self._local_init_run_options = local_init_run_options + self._local_init_feed_dict = local_init_feed_dict + if ready_for_local_init_op is not None and local_init_op is None: + raise ValueError("If you pass a ready_for_local_init_op " + "you must also pass a local_init_op " + ", ready_for_local_init_op [%s]" % + ready_for_local_init_op) + + def _restore_checkpoint( + self, + master: str, + saver: saver_lib.Saver = None, + checkpoint_dir: str = None, + checkpoint_filename_with_path: str = None, + wait_for_checkpoint=False, + max_wait_secs=7200, + config=None, + ) -> Tuple[session.Session, bool]: + """Creates a `Session`, and tries to restore a checkpoint. + + + Args: + master: `String` representation of the TensorFlow master to use. + saver: A `Saver` object used to restore a model. + checkpoint_dir: Path to the checkpoint files. The latest checkpoint in the + dir will be used to restore. + checkpoint_filename_with_path: Full file name path to the checkpoint file. + wait_for_checkpoint: Whether to wait for checkpoint to become available. + max_wait_secs: Maximum time to wait for checkpoints to become available. + config: Optional `ConfigProto` proto used to configure the session. + + Returns: + A pair (sess, is_restored) where 'is_restored' is `True` if + the session could be restored, `False` otherwise. + + Raises: + ValueError: If both checkpoint_dir and checkpoint_filename_with_path are + set. + """ + self._target = master + + # This is required to so that we initialize the TPU device before + # restoring from checkpoint since we'll be placing variables on the device + # and TPUInitialize wipes out the memory of the device. + strategy = distribute_lib.get_strategy() + if strategy and hasattr(strategy.extended, + "_experimental_initialize_system"): + strategy.extended._experimental_initialize_system() # pylint: disable=protected-access + + sess = session.Session(self._target, graph=self._graph, config=config) + if checkpoint_dir and checkpoint_filename_with_path: + raise ValueError("Can not provide both checkpoint_dir and " + "checkpoint_filename_with_path.") + # If either saver or checkpoint_* is not specified, cannot restore. Just + # return. + if not saver or not (checkpoint_dir or checkpoint_filename_with_path): + return sess, False + + if checkpoint_filename_with_path: + _restore_checkpoint_and_maybe_run_saved_model_initializers( + sess, saver, checkpoint_filename_with_path) + return sess, True + + # Waits up until max_wait_secs for checkpoint to become available. + wait_time = 0 + ckpt = checkpoint_management.get_checkpoint_state(checkpoint_dir) + while not ckpt or not ckpt.model_checkpoint_path: + if wait_for_checkpoint and wait_time < max_wait_secs: + logging.info("Waiting for checkpoint to be available.") + time.sleep(self._recovery_wait_secs) + wait_time += self._recovery_wait_secs + ckpt = checkpoint_management.get_checkpoint_state(checkpoint_dir) + else: + return sess, False + + # Loads the checkpoint. + _restore_checkpoint_and_maybe_run_saved_model_initializers( + sess, saver, ckpt.model_checkpoint_path) + saver.recover_last_checkpoints(ckpt.all_model_checkpoint_paths) + return sess, True + + def prepare_session( + self, + master: str, + init_op: ops.Operation = None, + saver: saver_lib.Saver = None, + checkpoint_dir: str = None, + checkpoint_filename_with_path: str = None, + wait_for_checkpoint=False, + max_wait_secs=7200, + config=None, + init_feed_dict=None, + init_fn=None, + ) -> session.Session: + """Creates a `Session`. Makes sure the model is ready to be used. + + Creates a `Session` on 'master'. If a `saver` object is passed in, and + `checkpoint_dir` points to a directory containing valid checkpoint + files, then it will try to recover the model from checkpoint. If + no checkpoint files are available, and `wait_for_checkpoint` is + `True`, then the process would check every `recovery_wait_secs`, + up to `max_wait_secs`, for recovery to succeed. + + If the model cannot be recovered successfully then it is initialized by + running the `init_op` and calling `init_fn` if they are provided. + The `local_init_op` is also run after init_op and init_fn, regardless of + whether the model was recovered successfully, but only if + `ready_for_local_init_op` passes. + + If the model is recovered from a checkpoint it is assumed that all + global variables have been initialized, in particular neither `init_op` + nor `init_fn` will be executed. + + It is an error if the model cannot be recovered and no `init_op` + or `init_fn` or `local_init_op` are passed. + + Args: + master: `String` representation of the TensorFlow master to use. + init_op: Optional `Operation` used to initialize the model. + saver: A `Saver` object used to restore a model. + checkpoint_dir: Path to the checkpoint files. The latest checkpoint in the + dir will be used to restore. + checkpoint_filename_with_path: Full file name path to the checkpoint file. + wait_for_checkpoint: Whether to wait for checkpoint to become available. + max_wait_secs: Maximum time to wait for checkpoints to become available. + config: Optional `ConfigProto` proto used to configure the session. + init_feed_dict: Optional dictionary that maps `Tensor` objects to feed + values. This feed dictionary is passed to the session `run()` call when + running the init op. + init_fn: Optional callable used to initialize the model. Called after the + optional `init_op` is called. The callable must accept one argument, + the session being initialized. + + Returns: + A `Session` object that can be used to drive the model. + + Raises: + RuntimeError: If the model cannot be initialized or recovered. + ValueError: If both checkpoint_dir and checkpoint_filename_with_path are + set. + """ + + sess, is_loaded_from_checkpoint = self._restore_checkpoint( + master, + saver, + checkpoint_dir=checkpoint_dir, + checkpoint_filename_with_path=checkpoint_filename_with_path, + wait_for_checkpoint=wait_for_checkpoint, + max_wait_secs=max_wait_secs, + config=config) + if not is_loaded_from_checkpoint: + if init_op is None and not init_fn and self._local_init_op is None: + raise RuntimeError("Model is not initialized and no init_op or " + "init_fn or local_init_op was given") + if init_op is not None: + sess.run(init_op, feed_dict=init_feed_dict) + if init_fn: + init_fn(sess) + + local_init_success, msg = self._try_run_local_init_op(sess) + if not local_init_success: + raise RuntimeError( + "Init operations did not make model ready for local_init. " + "Init op: %s, init fn: %s, error: %s" % (_maybe_name(init_op), + init_fn, + msg)) + + is_ready, msg = self._model_ready(sess) + if not is_ready: + raise RuntimeError( + "Init operations did not make model ready. " + "Init op: %s, init fn: %s, local_init_op: %s, error: %s" % + (_maybe_name(init_op), init_fn, self._local_init_op, msg)) + return sess + + def recover_session( + self, + master: str, + saver: saver_lib.Saver = None, + checkpoint_dir: str = None, + checkpoint_filename_with_path: str = None, + wait_for_checkpoint=False, + max_wait_secs=7200, + config=None, + ) -> Tuple[session.Session, bool]: + """Creates a `Session`, recovering if possible. + + Creates a new session on 'master'. If the session is not initialized + and can be recovered from a checkpoint, recover it. + + Args: + master: `String` representation of the TensorFlow master to use. + saver: A `Saver` object used to restore a model. + checkpoint_dir: Path to the checkpoint files. The latest checkpoint in the + dir will be used to restore. + checkpoint_filename_with_path: Full file name path to the checkpoint file. + wait_for_checkpoint: Whether to wait for checkpoint to become available. + max_wait_secs: Maximum time to wait for checkpoints to become available. + config: Optional `ConfigProto` proto used to configure the session. + + Returns: + A pair (sess, initialized) where 'initialized' is `True` if + the session could be recovered and initialized, `False` otherwise. + + Raises: + ValueError: If both checkpoint_dir and checkpoint_filename_with_path are + set. + """ + + sess, is_loaded_from_checkpoint = self._restore_checkpoint( + master, + saver, + checkpoint_dir=checkpoint_dir, + checkpoint_filename_with_path=checkpoint_filename_with_path, + wait_for_checkpoint=wait_for_checkpoint, + max_wait_secs=max_wait_secs, + config=config) + + # Always try to run local_init_op + local_init_success, msg = self._try_run_local_init_op(sess) + + if not is_loaded_from_checkpoint: + # Do not need to run checks for readiness + return sess, False + + restoring_file = checkpoint_dir or checkpoint_filename_with_path + if not local_init_success: + logging.info( + "Restoring model from %s did not make model ready for local init:" + " %s", restoring_file, msg) + return sess, False + + is_ready, msg = self._model_ready(sess) + if not is_ready: + logging.info("Restoring model from %s did not make model ready: %s", + restoring_file, msg) + return sess, False + + logging.info("Restored model from %s", restoring_file) + return sess, is_loaded_from_checkpoint + + def wait_for_session( + self, master: str, config=None, max_wait_secs=float("Inf") + ) -> Optional[session.Session]: + """Creates a new `Session` and waits for model to be ready. + + Creates a new `Session` on 'master'. Waits for the model to be + initialized or recovered from a checkpoint. It's expected that + another thread or process will make the model ready, and that this + is intended to be used by threads/processes that participate in a + distributed training configuration where a different thread/process + is responsible for initializing or recovering the model being trained. + + NB: The amount of time this method waits for the session is bounded + by max_wait_secs. By default, this function will wait indefinitely. + + Args: + master: `String` representation of the TensorFlow master to use. + config: Optional ConfigProto proto used to configure the session. + max_wait_secs: Maximum time to wait for the session to become available. + + Returns: + A `Session`. May be None if the operation exceeds the timeout + specified by config.operation_timeout_in_ms. + + Raises: + tf.DeadlineExceededError: if the session is not available after + max_wait_secs. + """ + self._target = master + + if max_wait_secs is None: + max_wait_secs = float("Inf") + timer = _CountDownTimer(max_wait_secs) + + while True: + sess = session.Session(self._target, graph=self._graph, config=config) + not_ready_msg = None + not_ready_local_msg = None + local_init_success, not_ready_local_msg = self._try_run_local_init_op( + sess) + if local_init_success: + # Successful if local_init_op is None, or ready_for_local_init_op passes + is_ready, not_ready_msg = self._model_ready(sess) + if is_ready: + return sess + + self._safe_close(sess) + + # Do we have enough time left to try again? + remaining_ms_after_wait = ( + timer.secs_remaining() - self._recovery_wait_secs) + if remaining_ms_after_wait < 0: + raise errors.DeadlineExceededError( + None, None, + "Session was not ready after waiting %d secs." % (max_wait_secs,)) + + logging.info("Waiting for model to be ready. " + "Ready_for_local_init_op: %s, ready: %s", + not_ready_local_msg, not_ready_msg) + time.sleep(self._recovery_wait_secs) + + def _safe_close(self, sess: session.Session): + """Closes a session without raising an exception. + + Just like sess.close() but ignores exceptions. + + Args: + sess: A `Session`. + """ + # pylint: disable=broad-except + try: + sess.close() + except Exception: + # Intentionally not logging to avoid user complaints that + # they get cryptic errors. We really do not care that Close + # fails. + pass + # pylint: enable=broad-except + + def _model_ready(self, sess: session.Session) -> Tuple[bool, Optional[str]]: + """Checks if the model is ready or not. + + Args: + sess: A `Session`. + + Returns: + A tuple (is_ready, msg), where is_ready is True if ready and False + otherwise, and msg is `None` if the model is ready, a `String` with the + reason why it is not ready otherwise. + """ + return _ready(self._ready_op, sess, "Model not ready") + + def _model_ready_for_local_init( + self, sess: session.Session + ) -> Tuple[bool, Optional[str]]: + """Checks if the model is ready to run local_init_op. + + Args: + sess: A `Session`. + + Returns: + A tuple (is_ready, msg), where is_ready is True if ready to run + local_init_op and False otherwise, and msg is `None` if the model is + ready to run local_init_op, a `String` with the reason why it is not ready + otherwise. + """ + return _ready(self._ready_for_local_init_op, sess, + "Model not ready for local init") + + def _try_run_local_init_op( + self, sess: session.Session + ) -> Tuple[bool, Optional[str]]: + """Tries to run _local_init_op, if not None, and is ready for local init. + + Args: + sess: A `Session`. + + Returns: + A tuple (is_successful, msg), where is_successful is True if + _local_init_op is None, or we ran _local_init_op, and False otherwise; + and msg is a `String` with the reason why the model was not ready to run + local init. + """ + if self._local_init_op is not None: + is_ready_for_local_init, msg = self._model_ready_for_local_init(sess) + if is_ready_for_local_init: + logging.info("Running local_init_op.") + sess.run(self._local_init_op, feed_dict=self._local_init_feed_dict, + options=self._local_init_run_options) + logging.info("Done running local_init_op.") + return True, None + else: + return False, msg + return True, None + + +def _ready( + op: ops.Operation, sess: session.Session, msg +) -> Tuple[bool, Optional[str]]: + """Checks if the model is ready or not, as determined by op. + + Args: + op: An op, either _ready_op or _ready_for_local_init_op, which defines the + readiness of the model. + sess: A `Session`. + msg: A message to log to warning if not ready + + Returns: + A tuple (is_ready, msg), where is_ready is True if ready and False + otherwise, and msg is `None` if the model is ready, a `String` with the + reason why it is not ready otherwise. + """ + if op is None: + return True, None + else: + try: + ready_value = sess.run(op) + # The model is considered ready if ready_op returns an empty 1-D tensor. + # Also compare to `None` and dtype being int32 for backward + # compatibility. + if (ready_value is None or ready_value.dtype == np.int32 or + ready_value.size == 0): + return True, None + else: + # TODO(sherrym): If a custom ready_op returns other types of tensor, + # or strings other than variable names, this message could be + # confusing. + non_initialized_varnames = ", ".join( + [i.decode("utf-8") for i in ready_value]) + return False, "Variables not initialized: " + non_initialized_varnames + except errors.FailedPreconditionError as e: + if "uninitialized" not in str(e): + logging.warning("%s : error [%s]", msg, str(e)) + raise e + return False, str(e) + + +class _CountDownTimer: + """A timer that tracks a duration since creation.""" + + __slots__ = ["_start_time_secs", "_duration_secs"] + + def __init__(self, duration_secs): + self._start_time_secs = time.time() + self._duration_secs = duration_secs + + def secs_remaining(self): + diff = self._duration_secs - (time.time() - self._start_time_secs) + return max(0, diff) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/session_run_hook.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/session_run_hook.py new file mode 100644 index 0000000000000000000000000000000000000000..a78a81fe6a8863d72b9c168071abbbb466b90a67 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/session_run_hook.py @@ -0,0 +1,283 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""A SessionRunHook extends `session.run()` calls for the `MonitoredSession`. + +SessionRunHooks are useful to track training, report progress, request early +stopping and more. SessionRunHooks use the observer pattern and notify at the +following points: + - when a session starts being used + - before a call to the `session.run()` + - after a call to the `session.run()` + - when the session closed + +A SessionRunHook encapsulates a piece of reusable/composable computation that +can piggyback a call to `MonitoredSession.run()`. A hook can add any +ops-or-tensor/feeds to the run call, and when the run call finishes with success +gets the outputs it requested. Hooks are allowed to add ops to the graph in +`hook.begin()`. The graph is finalized after the `begin()` method is called. + +There are a few pre-defined hooks: + - StopAtStepHook: Request stop based on global_step + - CheckpointSaverHook: saves checkpoint + - LoggingTensorHook: outputs one or more tensor values to log + - NanTensorHook: Request stop if given `Tensor` contains Nans. + - SummarySaverHook: saves summaries to a summary writer + +For more specific needs, you can create custom hooks: + class ExampleHook(SessionRunHook): + def begin(self): + # You can add ops to the graph here. + print('Starting the session.') + self.your_tensor = ... + + def after_create_session(self, session, coord): + # When this is called, the graph is finalized and + # ops can no longer be added to the graph. + print('Session created.') + + def before_run(self, run_context): + print('Before calling session.run().') + return SessionRunArgs(self.your_tensor) + + def after_run(self, run_context, run_values): + print('Done running one step. The value of my tensor: %s', + run_values.results) + if you-need-to-stop-loop: + run_context.request_stop() + + def end(self, session): + print('Done with the session.') + +To understand how hooks interact with calls to `MonitoredSession.run()`, +look at following code: + with MonitoredTrainingSession(hooks=your_hooks, ...) as sess: + while not sess.should_stop(): + sess.run(your_fetches) + +Above user code leads to following execution: + call hooks.begin() + sess = tf.compat.v1.Session() + call hooks.after_create_session() + while not stop is requested: + call hooks.before_run() + try: + results = sess.run(merged_fetches, feed_dict=merged_feeds) + except (errors.OutOfRangeError, StopIteration): + break + call hooks.after_run() + call hooks.end() + sess.close() + +Note that if sess.run() raises OutOfRangeError or StopIteration then +hooks.after_run() will not be called but hooks.end() will still be called. +If sess.run() raises any other exception then neither hooks.after_run() nor +hooks.end() will be called. +""" + +import collections +from tensorflow.python.util.tf_export import tf_export + + +@tf_export(v1=["train.SessionRunHook"]) +class SessionRunHook: + """Hook to extend calls to MonitoredSession.run().""" + + def begin(self): + """Called once before using the session. + + When called, the default graph is the one that will be launched in the + session. The hook can modify the graph by adding new operations to it. + After the `begin()` call the graph will be finalized and the other callbacks + can not modify the graph anymore. Second call of `begin()` on the same + graph, should not change the graph. + """ + pass + + def after_create_session(self, session, coord): # pylint: disable=unused-argument + """Called when new TensorFlow session is created. + + This is called to signal the hooks that a new session has been created. This + has two essential differences with the situation in which `begin` is called: + + * When this is called, the graph is finalized and ops can no longer be added + to the graph. + * This method will also be called as a result of recovering a wrapped + session, not only at the beginning of the overall session. + + Args: + session: A TensorFlow Session that has been created. + coord: A Coordinator object which keeps track of all threads. + """ + pass + + def before_run(self, run_context): # pylint: disable=unused-argument + """Called before each call to run(). + + You can return from this call a `SessionRunArgs` object indicating ops or + tensors to add to the upcoming `run()` call. These ops/tensors will be run + together with the ops/tensors originally passed to the original run() call. + The run args you return can also contain feeds to be added to the run() + call. + + The `run_context` argument is a `SessionRunContext` that provides + information about the upcoming `run()` call: the originally requested + op/tensors, the TensorFlow Session. + + At this point graph is finalized and you can not add ops. + + Args: + run_context: A `SessionRunContext` object. + + Returns: + None or a `SessionRunArgs` object. + """ + return None + + def after_run(self, + run_context, # pylint: disable=unused-argument + run_values): # pylint: disable=unused-argument + """Called after each call to run(). + + The `run_values` argument contains results of requested ops/tensors by + `before_run()`. + + The `run_context` argument is the same one send to `before_run` call. + `run_context.request_stop()` can be called to stop the iteration. + + If `session.run()` raises any exceptions then `after_run()` is not called. + + Args: + run_context: A `SessionRunContext` object. + run_values: A SessionRunValues object. + """ + pass + + def end(self, session): # pylint: disable=unused-argument + """Called at the end of session. + + The `session` argument can be used in case the hook wants to run final ops, + such as saving a last checkpoint. + + If `session.run()` raises exception other than OutOfRangeError or + StopIteration then `end()` is not called. + Note the difference between `end()` and `after_run()` behavior when + `session.run()` raises OutOfRangeError or StopIteration. In that case + `end()` is called but `after_run()` is not called. + + Args: + session: A TensorFlow Session that will be soon closed. + """ + pass + + +@tf_export(v1=["train.SessionRunArgs"]) +class SessionRunArgs( + collections.namedtuple("SessionRunArgs", + ["fetches", "feed_dict", "options"])): + """Represents arguments to be added to a `Session.run()` call. + + Args: + fetches: Exactly like the 'fetches' argument to Session.Run(). + Can be a single tensor or op, a list of 'fetches' or a dictionary + of fetches. For example: + fetches = global_step_tensor + fetches = [train_op, summary_op, global_step_tensor] + fetches = {'step': global_step_tensor, 'summ': summary_op} + Note that this can recurse as expected: + fetches = {'step': global_step_tensor, + 'ops': [train_op, check_nan_op]} + feed_dict: Exactly like the `feed_dict` argument to `Session.Run()` + options: Exactly like the `options` argument to `Session.run()`, i.e., a + config_pb2.RunOptions proto. + """ + + def __new__(cls, fetches, feed_dict=None, options=None): + return super(SessionRunArgs, cls).__new__(cls, fetches, feed_dict, options) + + +@tf_export(v1=["train.SessionRunContext"]) +class SessionRunContext: + """Provides information about the `session.run()` call being made. + + Provides information about original request to `Session.Run()` function. + SessionRunHook objects can stop the loop by calling `request_stop()` of + `run_context`. In the future we may use this object to add more information + about run without changing the Hook API. + """ + + def __init__(self, original_args, session): + """Initializes SessionRunContext.""" + self._original_args = original_args + self._session = session + self._stop_requested = False + + @property + def original_args(self): + """A `SessionRunArgs` object holding the original arguments of `run()`. + + If user called `MonitoredSession.run(fetches=a, feed_dict=b)`, then this + field is equal to SessionRunArgs(a, b). + + Returns: + A `SessionRunArgs` object + """ + return self._original_args + + @property + def session(self): + """A TensorFlow session object which will execute the `run`.""" + return self._session + + @property + def stop_requested(self): + """Returns whether a stop is requested or not. + + If true, `MonitoredSession` stops iterations. + Returns: + A `bool` + """ + return self._stop_requested + + def request_stop(self): + """Sets stop requested field. + + Hooks can use this function to request stop of iterations. + `MonitoredSession` checks whether this is called or not. + """ + self._stop_requested = True + + +@tf_export(v1=["train.SessionRunValues"]) +class SessionRunValues( + collections.namedtuple("SessionRunValues", + ["results", "options", "run_metadata"])): + """Contains the results of `Session.run()`. + + In the future we may use this object to add more information about result of + run without changing the Hook API. + + Args: + results: The return values from `Session.run()` corresponding to the fetches + attribute returned in the RunArgs. Note that this has the same shape as + the RunArgs fetches. For example: + fetches = global_step_tensor + => results = nparray(int) + fetches = [train_op, summary_op, global_step_tensor] + => results = [None, nparray(string), nparray(int)] + fetches = {'step': global_step_tensor, 'summ': summary_op} + => results = {'step': nparray(int), 'summ': nparray(string)} + options: `RunOptions` from the `Session.run()` call. + run_metadata: `RunMetadata` from the `Session.run()` call. + """ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/slot_creator.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/slot_creator.py new file mode 100644 index 0000000000000000000000000000000000000000..a6a088a0456224cc178828e0fd39ac5d8d33e36e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/slot_creator.py @@ -0,0 +1,281 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""Standard functions for creating slots. + +A slot is a `Variable` created with the same first m-dimension as a primary +variable or `Tensor`. A slot is always scoped in the namespace of the primary +object and typically has the same device and type. + +Slots are typically used as accumulators to track values associated with +the primary object: + +```python +# Optimizers can create a slot for each variable to track accumulators +accumulators = {var : create_zeros_slot(var, "momentum") for var in vs} +for var in vs: + apply_momentum(var, accumulators[var], lr, grad, momentum_tensor) + +# Slots can also be used for moving averages +mavg = create_slot(var, var.initialized_value(), "exponential_moving_avg") +update_mavg = mavg.assign_sub((mavg - var) * (1 - decay)) +``` +""" +# pylint: disable=g-bad-name + +from tensorflow.python.compiler.xla.experimental import xla_sharding +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import cond +from tensorflow.python.ops import init_ops +from tensorflow.python.ops import ref_variable +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.ops import variable_scope +from tensorflow.python.ops import variable_v1 +from tensorflow.python.ops import variables + + +def _create_slot_var(primary, + val, + scope, + validate_shape, + shape, + dtype, + *, + copy_xla_sharding=False): + """Helper function for creating a slot variable.""" + + # TODO(lukaszkaiser): Consider allowing partitioners to be set in the current + # scope. + current_partitioner = variable_scope.get_variable_scope().partitioner + variable_scope.get_variable_scope().set_partitioner(None) + # When init from val instead of callable initializer, the shape is expected to + # be None, not or any fully defined shape. + shape = shape if callable(val) else None + if resource_variable_ops.is_resource_variable(primary): + use_resource = True + elif isinstance(primary, ref_variable.RefVariable): + use_resource = False + else: + use_resource = None + slot = variable_scope.get_variable( + scope, + initializer=val, + trainable=False, + use_resource=use_resource, + shape=shape, + dtype=dtype, + validate_shape=validate_shape) + variable_scope.get_variable_scope().set_partitioner(current_partitioner) + + # pylint: disable=protected-access + if isinstance(primary, variables.Variable) and primary._save_slice_info: + # Primary is a partitioned variable, so we need to also indicate that + # the slot is a partitioned variable. Slots have the same partitioning + # as their primaries. + # For examples when using AdamOptimizer in linear model, slot.name + # here can be "linear//weights/Adam:0", while primary.op.name is + # "linear//weight". We want to get 'Adam' as real_slot_name, so we + # remove "'linear//weight' + '/'" and ':0'. + real_slot_name = slot.name[len(primary.op.name + "/"):-2] + slice_info = primary._save_slice_info + # support slot's shape not same as primary's shape + # example: primary's shape = [10, 20, 30], slot's shape = + # None, [], [10], [10, 20] or [10, 20, 30] is allowed + # slot's shape = None or [10, 20, 30], set slot's slice_info same as primary + # slot's shape = [], don't set slot's slice_info + # slot's shape = [10] or [10, 20], set slot's slice_info according to ndims + n = slot.shape.ndims + if n is None or n > 0: + slot._set_save_slice_info( + variables.Variable.SaveSliceInfo( + slice_info.full_name + "/" + real_slot_name, + slice_info.full_shape[:n], slice_info.var_offset[:n], + slice_info.var_shape[:n])) + # pylint: enable=protected-access + + # Copy XLA sharding attributes from the primary if the slot variable has the + # same rank as the primary. + def _has_same_rank(primary_shape, slot_shape): + return (primary_shape.rank is not None and slot_shape.rank is not None and + primary_shape.rank == slot_shape.rank) + + if copy_xla_sharding and _has_same_rank(primary.shape, slot.shape): + slot = xla_sharding.copy_sharding(primary, slot, use_sharding_op=False) + return slot + + +def create_slot(primary, + val, + name, + colocate_with_primary=True, + *, + copy_xla_sharding=False): + """Create a slot initialized to the given value. + + The type of the slot is determined by the given value. + + Args: + primary: The primary `Variable` or `Tensor`. + val: A `Tensor` specifying the initial value of the slot. + name: Name to use for the slot variable. + colocate_with_primary: Boolean. If True the slot is located + on the same device as `primary`. + copy_xla_sharding: Boolean. If True also copies XLA sharding + from primary. + + Returns: + A `Variable` object. + """ + # Scope the slot name in the namespace of the primary variable. + # Set primary's name + '/' + name as default name, so the scope name of + # optimizer can be shared when reuse is True. Meanwhile when reuse is False + # and the same name has been previously used, the scope name will add '_N' + # as suffix for unique identifications. + validate_shape = val.get_shape().is_fully_defined() + if isinstance(primary, variables.Variable): + prefix = primary._shared_name # pylint: disable=protected-access + else: + prefix = primary.op.name + with variable_scope.variable_scope(None, prefix + "/" + name): + if colocate_with_primary: + distribution_strategy = distribute_lib.get_strategy() + with distribution_strategy.extended.colocate_vars_with(primary): + return _create_slot_var( + primary, + val, + "", + validate_shape, + None, + None, + copy_xla_sharding=copy_xla_sharding) + else: + return _create_slot_var( + primary, + val, + "", + validate_shape, + None, + None, + copy_xla_sharding=copy_xla_sharding) + + +def create_slot_with_initializer(primary, + initializer, + shape, + dtype, + name, + colocate_with_primary=True, + *, + copy_xla_sharding=False): + """Creates a slot initialized using an `Initializer`. + + The type of the slot is determined by the given value. + + Args: + primary: The primary `Variable` or `Tensor`. + initializer: An `Initializer`. The initial value of the slot. + shape: Shape of the initial value of the slot. + dtype: Type of the value of the slot. + name: Name to use for the slot variable. + colocate_with_primary: Boolean. If True the slot is located + on the same device as `primary`. + copy_xla_sharding: Boolean. If True also copies XLA sharding + from primary. + + Returns: + A `Variable` object. + """ + # Scope the slot name in the namespace of the primary variable. + # Set "primary.op.name + '/' + name" as default name, so the scope name of + # optimizer can be shared when reuse is True. Meanwhile when reuse is False + # and the same name has been previously used, the scope name will add '_N' + # as suffix for unique identifications. + validate_shape = shape.is_fully_defined() + if isinstance(primary, variables.Variable): + prefix = primary._shared_name # pylint: disable=protected-access + else: + prefix = primary.op.name + with variable_scope.variable_scope(None, prefix + "/" + name): + if colocate_with_primary: + distribution_strategy = distribute_lib.get_strategy() + with distribution_strategy.extended.colocate_vars_with(primary): + return _create_slot_var( + primary, + initializer, + "", + validate_shape, + shape, + dtype, + copy_xla_sharding=copy_xla_sharding) + else: + return _create_slot_var( + primary, + initializer, + "", + validate_shape, + shape, + dtype, + copy_xla_sharding=copy_xla_sharding) + + +def create_zeros_slot(primary, + name, + dtype=None, + colocate_with_primary=True, + *, + copy_xla_sharding=False): + """Create a slot initialized to 0 with same shape as the primary object. + + Args: + primary: The primary `Variable` or `Tensor`. + name: Name to use for the slot variable. + dtype: Type of the slot variable. Defaults to the type of `primary`. + colocate_with_primary: Boolean. If True the slot is located + on the same device as `primary`. + copy_xla_sharding: Boolean. If True also copies XLA sharding + from primary. + + Returns: + A `Variable` object. + """ + if dtype is None: + dtype = primary.dtype + slot_shape = primary.get_shape() + if slot_shape.is_fully_defined(): + initializer = init_ops.zeros_initializer() + return create_slot_with_initializer( + primary, + initializer, + slot_shape, + dtype, + name, + colocate_with_primary=colocate_with_primary, + copy_xla_sharding=copy_xla_sharding) + else: + if isinstance(primary, variables.Variable): + slot_shape = array_ops.shape( + cond.cond( + variable_v1.is_variable_initialized(primary), primary.read_value, + lambda: primary.initial_value)) + else: + slot_shape = array_ops.shape(primary) + val = array_ops.zeros(slot_shape, dtype=dtype) + return create_slot( + primary, + val, + name, + colocate_with_primary=colocate_with_primary, + copy_xla_sharding=copy_xla_sharding) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/summary_io.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/summary_io.py new file mode 100644 index 0000000000000000000000000000000000000000..5e75751f667bbe45016d39e8141ec32c7c4ec1a5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/summary_io.py @@ -0,0 +1,77 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Reads Summaries from and writes Summaries to event files.""" + +# pylint: disable=unused-import +from tensorflow.python.summary.summary_iterator import summary_iterator +from tensorflow.python.summary.writer.writer import FileWriter as _FileWriter +from tensorflow.python.summary.writer.writer_cache import FileWriterCache as SummaryWriterCache +# pylint: enable=unused-import +from tensorflow.python.util.deprecation import deprecated + + +class SummaryWriter(_FileWriter): + + @deprecated("2016-11-30", + "Please switch to tf.summary.FileWriter. The interface and " + "behavior is the same; this is just a rename.") + def __init__(self, + logdir, + graph=None, + max_queue=10, + flush_secs=120, + graph_def=None): + """Creates a `SummaryWriter` and an event file. + + This class is deprecated, and should be replaced with tf.summary.FileWriter. + + On construction the summary writer creates a new event file in `logdir`. + This event file will contain `Event` protocol buffers constructed when you + call one of the following functions: `add_summary()`, `add_session_log()`, + `add_event()`, or `add_graph()`. + + If you pass a `Graph` to the constructor it is added to + the event file. (This is equivalent to calling `add_graph()` later). + + TensorBoard will pick the graph from the file and display it graphically so + you can interactively explore the graph you built. You will usually pass + the graph from the session in which you launched it: + + ```python + ...create a graph... + # Launch the graph in a session. + sess = tf.compat.v1.Session() + # Create a summary writer, add the 'graph' to the event file. + writer = tf.compat.v1.summary.FileWriter(, sess.graph) + ``` + + The other arguments to the constructor control the asynchronous writes to + the event file: + + * `flush_secs`: How often, in seconds, to flush the added summaries + and events to disk. + * `max_queue`: Maximum number of summaries or events pending to be + written to disk before one of the 'add' calls block. + + Args: + logdir: A string. Directory where event file will be written. + graph: A `Graph` object, such as `sess.graph`. + max_queue: Integer. Size of the queue for pending events and summaries. + flush_secs: Number. How often, in seconds, to flush the + pending events and summaries to disk. + graph_def: DEPRECATED: Use the `graph` argument instead. + """ + super(SummaryWriter, self).__init__(logdir, graph, max_queue, flush_secs, + graph_def) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/supervisor.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/supervisor.py new file mode 100644 index 0000000000000000000000000000000000000000..fc3ba09c03d148c9316b8d108024fb933765d377 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/supervisor.py @@ -0,0 +1,1134 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Training helper that checkpoints models and computes summaries.""" +import contextlib +import os +import time + +from tensorflow.core.framework.summary_pb2 import Summary +from tensorflow.core.util.event_pb2 import SessionLog +from tensorflow.python.eager import context +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import meta_graph +from tensorflow.python.framework import ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import lookup_ops +from tensorflow.python.ops import variables +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.summary import summary as _summary +from tensorflow.python.training import coordinator +from tensorflow.python.training import saver as saver_mod +from tensorflow.python.training import session_manager as session_manager_mod +from tensorflow.python.training import training_util +from tensorflow.python.util import deprecation +from tensorflow.python.util.tf_export import tf_export + + +@tf_export(v1=["train.Supervisor"]) +class Supervisor: + """A training helper that checkpoints models and computes summaries. + + This class is deprecated. Please use + `tf.compat.v1.train.MonitoredTrainingSession` instead. + + The Supervisor is a small wrapper around a `Coordinator`, a `Saver`, + and a `SessionManager` that takes care of common needs of TensorFlow + training programs. + + #### Use for a single program + + ```python + with tf.Graph().as_default(): + ...add operations to the graph... + # Create a Supervisor that will checkpoint the model in '/tmp/mydir'. + sv = Supervisor(logdir='/tmp/mydir') + # Get a TensorFlow session managed by the supervisor. + with sv.managed_session(FLAGS.master) as sess: + # Use the session to train the graph. + while not sv.should_stop(): + sess.run() + ``` + + Within the `with sv.managed_session()` block all variables in the graph have + been initialized. In addition, a few services have been started to + checkpoint the model and add summaries to the event log. + + If the program crashes and is restarted, the managed session automatically + reinitialize variables from the most recent checkpoint. + + The supervisor is notified of any exception raised by one of the services. + After an exception is raised, `should_stop()` returns `True`. In that case + the training loop should also stop. This is why the training loop has to + check for `sv.should_stop()`. + + Exceptions that indicate that the training inputs have been exhausted, + `tf.errors.OutOfRangeError`, also cause `sv.should_stop()` to return `True` + but are not re-raised from the `with` block: they indicate a normal + termination. + + #### Use for multiple replicas + + To train with replicas you deploy the same program in a `Cluster`. + One of the tasks must be identified as the *chief*: the task that handles + initialization, checkpoints, summaries, and recovery. The other tasks + depend on the *chief* for these services. + + The only change you have to do to the single program code is to indicate + if the program is running as the *chief*. + + ```python + # Choose a task as the chief. This could be based on server_def.task_index, + # or job_def.name, or job_def.tasks. It's entirely up to the end user. + # But there can be only one *chief*. + is_chief = (server_def.task_index == 0) + server = tf.distribute.Server(server_def) + + with tf.Graph().as_default(): + ...add operations to the graph... + # Create a Supervisor that uses log directory on a shared file system. + # Indicate if you are the 'chief' + sv = Supervisor(logdir='/shared_directory/...', is_chief=is_chief) + # Get a Session in a TensorFlow server on the cluster. + with sv.managed_session(server.target) as sess: + # Use the session to train the graph. + while not sv.should_stop(): + sess.run() + ``` + + In the *chief* task, the `Supervisor` works exactly as in the first example + above. In the other tasks `sv.managed_session()` waits for the Model to have + been initialized before returning a session to the training code. The + non-chief tasks depend on the chief task for initializing the model. + + If one of the tasks crashes and restarts, `managed_session()` + checks if the Model is initialized. If yes, it just creates a session and + returns it to the training code that proceeds normally. If the model needs + to be initialized, the chief task takes care of reinitializing it; the other + tasks just wait for the model to have been initialized. + + NOTE: This modified program still works fine as a single program. + The single program marks itself as the chief. + + #### What `master` string to use + + Whether you are running on your machine or in the cluster you can use the + following values for the --master flag: + + * Specifying `''` requests an in-process session that does not use RPC. + + * Specifying `'local'` requests a session that uses the RPC-based + "Master interface" to run TensorFlow programs. See + `tf.train.Server.create_local_server` for + details. + + * Specifying `'grpc://hostname:port'` requests a session that uses + the RPC interface to a specific host, and also allows the in-process + master to access remote tensorflow workers. Often, it is + appropriate to pass `server.target` (for some `tf.distribute.Server` + named `server). + + #### Advanced use + + ##### Launching additional services + + `managed_session()` launches the Checkpoint and Summary services (threads). + If you need more services to run you can simply launch them in the block + controlled by `managed_session()`. + + Example: Start a thread to print losses. We want this thread to run + every 60 seconds, so we launch it with `sv.loop()`. + + ```python + ... + sv = Supervisor(logdir='/tmp/mydir') + with sv.managed_session(FLAGS.master) as sess: + sv.loop(60, print_loss, (sess, )) + while not sv.should_stop(): + sess.run(my_train_op) + ``` + + ##### Launching fewer services + + `managed_session()` launches the "summary" and "checkpoint" threads which use + either the optionally `summary_op` and `saver` passed to the constructor, or + default ones created automatically by the supervisor. If you want to run + your own summary and checkpointing logic, disable these services by passing + `None` to the `summary_op` and `saver` parameters. + + Example: Create summaries manually every 100 steps in the chief. + + ```python + # Create a Supervisor with no automatic summaries. + sv = Supervisor(logdir='/tmp/mydir', is_chief=is_chief, summary_op=None) + # As summary_op was None, managed_session() does not start the + # summary thread. + with sv.managed_session(FLAGS.master) as sess: + for step in range(1000000): + if sv.should_stop(): + break + if is_chief and step % 100 == 0: + # Create the summary every 100 chief steps. + sv.summary_computed(sess, sess.run(my_summary_op)) + else: + # Train normally + sess.run(my_train_op) + ``` + + ##### Custom model initialization + + `managed_session()` only supports initializing the model by running an + `init_op` or restoring from the latest checkpoint. If you have special + initialization needs, see how to specify a `local_init_op` when creating the + supervisor. You can also use the `SessionManager` directly to create a + session and check if it could be initialized automatically. + """ + + # Value to pass for the 'ready_op', 'init_op', 'summary_op', 'saver', + # and 'global_step' parameters of Supervisor.__init__() to indicate that + # the default behavior should be used. + USE_DEFAULT = 0 + + @deprecation.deprecated(None, + "Please switch to tf.train.MonitoredTrainingSession") + def __init__(self, + graph=None, + ready_op=USE_DEFAULT, + ready_for_local_init_op=USE_DEFAULT, + is_chief=True, + init_op=USE_DEFAULT, + init_feed_dict=None, + local_init_op=USE_DEFAULT, + logdir=None, + summary_op=USE_DEFAULT, + saver=USE_DEFAULT, + global_step=USE_DEFAULT, + save_summaries_secs=120, + save_model_secs=600, + recovery_wait_secs=30, + stop_grace_secs=120, + checkpoint_basename="model.ckpt", + session_manager=None, + summary_writer=USE_DEFAULT, + init_fn=None, + local_init_run_options=None): + """Create a `Supervisor`. + + Args: + graph: A `Graph`. The graph that the model will use. Defaults to the + default `Graph`. The supervisor may add operations to the graph before + creating a session, but the graph should not be modified by the caller + after passing it to the supervisor. + ready_op: 1-D string `Tensor`. This tensor is evaluated by supervisors in + `prepare_or_wait_for_session()` to check if the model is ready to use. + The model is considered ready if it returns an empty array. Defaults to + the tensor returned from `tf.compat.v1.report_uninitialized_variables()` + If `None`, the model is not checked for readiness. + ready_for_local_init_op: 1-D string `Tensor`. This tensor is evaluated by + supervisors in `prepare_or_wait_for_session()` to check if the model is + ready to run the local_init_op. The model is considered ready if it + returns an empty array. Defaults to `None`. If `None`, the model is not + checked for readiness before running local_init_op. + is_chief: If True, create a chief supervisor in charge of initializing and + restoring the model. If False, create a supervisor that relies on a + chief supervisor for inits and restore. + init_op: `Operation`. Used by chief supervisors to initialize the model + when it can not be recovered. Defaults to an `Operation` that + initializes all global variables. If `None`, no initialization is done + automatically unless you pass a value for `init_fn`, see below. + init_feed_dict: A dictionary that maps `Tensor` objects to feed values. + This feed dictionary will be used when `init_op` is evaluated. + local_init_op: `Operation`. Used by all supervisors to run initializations + that should run for every new supervisor instance. By default these are + table initializers and initializers for local variables. If `None`, no + further per supervisor-instance initialization is done automatically. + logdir: A string. Optional path to a directory where to checkpoint the + model and log events for the visualizer. Used by chief supervisors. The + directory will be created if it does not exist. + summary_op: An `Operation` that returns a Summary for the event logs. Used + by chief supervisors if a `logdir` was specified. Defaults to the + operation returned from summary.merge_all(). If `None`, summaries are + not computed automatically. + saver: A Saver object. Used by chief supervisors if a `logdir` was + specified. Defaults to the saved returned by Saver(). If `None`, the + model is not saved automatically. + global_step: An integer Tensor of size 1 that counts steps. The value + from 'global_step' is used in summaries and checkpoint filenames. + Default to the op named 'global_step' in the graph if it exists, is of + rank 1, size 1, and of type tf.int32 or tf.int64. If `None` the global + step is not recorded in summaries and checkpoint files. Used by chief + supervisors if a `logdir` was specified. + save_summaries_secs: Number of seconds between the computation of + summaries for the event log. Defaults to 120 seconds. Pass 0 to + disable summaries. + save_model_secs: Number of seconds between the creation of model + checkpoints. Defaults to 600 seconds. Pass 0 to disable checkpoints. + recovery_wait_secs: Number of seconds between checks that the model is + ready. Used by supervisors when waiting for a chief supervisor to + initialize or restore the model. Defaults to 30 seconds. + stop_grace_secs: Grace period, in seconds, given to running threads to + stop when `stop()` is called. Defaults to 120 seconds. + checkpoint_basename: The basename for checkpoint saving. + session_manager: `SessionManager`, which manages Session creation and + recovery. If it is `None`, a default `SessionManager` will be created + with the set of arguments passed in for backwards compatibility. + summary_writer: `SummaryWriter` to use or `USE_DEFAULT`. Can be `None` to + indicate that no summaries should be written. + init_fn: Optional callable used to initialize the model. Called after the + optional `init_op` is called. The callable must accept one argument, + the session being initialized. + local_init_run_options: RunOptions to be passed as the SessionManager + local_init_run_options parameter. + + Returns: + A `Supervisor`. + + Raises: + RuntimeError: If called with eager execution enabled. + + @compatibility(eager) + `Supervisor`s are not supported when eager execution is enabled. + @end_compatibility + """ + if context.executing_eagerly(): + raise RuntimeError("Supervisors are incompatible with eager execution.") + # Set default values of arguments. + if graph is None: + graph = ops.get_default_graph() + with graph.as_default(): + self._init_ready_op( + ready_op=ready_op, ready_for_local_init_op=ready_for_local_init_op) + self._init_init_op(init_op=init_op, init_feed_dict=init_feed_dict) + self._init_local_init_op(local_init_op=local_init_op) + self._init_saver(saver=saver) + self._init_summary_op(summary_op=summary_op) + self._init_global_step(global_step=global_step) + self._graph = graph + self._meta_graph_def = meta_graph.create_meta_graph_def( + graph_def=graph.as_graph_def(add_shapes=True), + saver_def=self._saver.saver_def if self._saver else None) + self._is_chief = is_chief + self._coord = coordinator.Coordinator() + self._recovery_wait_secs = recovery_wait_secs + self._stop_grace_secs = stop_grace_secs + self._init_fn = init_fn + self._local_init_run_options = local_init_run_options + + # Set all attributes related to checkpointing and writing events to None. + # Afterwards, set them appropriately for chief supervisors, as these are + # the only supervisors that can write checkpoints and events. + self._logdir = None + self._save_summaries_secs = None + self._save_model_secs = None + self._save_path = None + self._summary_writer = None + + if self._is_chief: + self._logdir = logdir + self._save_summaries_secs = save_summaries_secs + self._save_model_secs = save_model_secs + if self._logdir: + self._save_path = os.path.join(self._logdir, checkpoint_basename) + if summary_writer is Supervisor.USE_DEFAULT: + if self._logdir: + self._summary_writer = _summary.FileWriter(self._logdir) + else: + self._summary_writer = summary_writer + self._graph_added_to_summary = False + + self._init_session_manager(session_manager=session_manager) + self._verify_setup() + # The graph is not allowed to change anymore. + graph.finalize() + + def _init_session_manager(self, session_manager=None): + if session_manager is None: + self._session_manager = session_manager_mod.SessionManager( + local_init_op=self._local_init_op, + ready_op=self._ready_op, + ready_for_local_init_op=self._ready_for_local_init_op, + graph=self._graph, + recovery_wait_secs=self._recovery_wait_secs, + local_init_run_options=self._local_init_run_options) + else: + self._session_manager = session_manager + + def _get_first_op_from_collection(self, key): + """Returns the first `Operation` from a collection. + + Args: + key: A string collection key. + + Returns: + The first Op found in a collection, or `None` if the collection is empty. + """ + try: + op_list = ops.get_collection(key) + if len(op_list) > 1: + logging.info("Found %d %s operations. Returning the first one.", + len(op_list), key) + if op_list: + return op_list[0] + except LookupError: + pass + + return None + + def _init_ready_op(self, + ready_op=USE_DEFAULT, + ready_for_local_init_op=USE_DEFAULT): + """Initializes ready_op. + + Args: + ready_op: `Tensor` to check if the model is initialized. If it's set to + USE_DEFAULT, creates an op that checks all the variables are + initialized. + ready_for_local_init_op: `Tensor` to check if the model is ready to run + local_init_op. If it's set to USE_DEFAULT, creates an op that checks all + the global variables are initialized. + """ + if ready_op is Supervisor.USE_DEFAULT: + ready_op = self._get_first_op_from_collection(ops.GraphKeys.READY_OP) + if ready_op is None: + ready_op = variables.report_uninitialized_variables() + ops.add_to_collection(ops.GraphKeys.READY_OP, ready_op) + self._ready_op = ready_op + + # ready_for_local_init_op defaults to None for backward compatibility + if ready_for_local_init_op is Supervisor.USE_DEFAULT: + ready_for_local_init_op = self._get_first_op_from_collection( + ops.GraphKeys.READY_FOR_LOCAL_INIT_OP) + self._ready_for_local_init_op = ready_for_local_init_op + + def _init_init_op(self, init_op=USE_DEFAULT, init_feed_dict=None): + """Initializes init_op. + + Args: + init_op: `Operation` to initialize the variables. If set to USE_DEFAULT, + create an op that initializes all variables and tables. + init_feed_dict: A dictionary that maps `Tensor` objects to feed values. + This feed dictionary will be used when `init_op` is evaluated. + """ + if init_op is Supervisor.USE_DEFAULT: + init_op = self._get_first_op_from_collection(ops.GraphKeys.INIT_OP) + if init_op is None: + init_op = variables.global_variables_initializer() + ops.add_to_collection(ops.GraphKeys.INIT_OP, init_op) + self._init_op = init_op + self._init_feed_dict = init_feed_dict + + def _init_local_init_op(self, local_init_op=USE_DEFAULT): + """Initializes local_init_op. + + Args: + local_init_op: `Operation` run for every new supervisor instance. If set + to USE_DEFAULT, use the first op from the GraphKeys.LOCAL_INIT_OP + collection. If the collection is empty, create an op that initializes + all local variables and all tables. + """ + if local_init_op is Supervisor.USE_DEFAULT: + local_init_op = self._get_first_op_from_collection( + ops.GraphKeys.LOCAL_INIT_OP) + if local_init_op is None: + op_list = [ + variables.local_variables_initializer(), + lookup_ops.tables_initializer() + ] + if op_list: + local_init_op = control_flow_ops.group(*op_list) + ops.add_to_collection(ops.GraphKeys.LOCAL_INIT_OP, local_init_op) + self._local_init_op = local_init_op + + def _init_saver(self, saver=USE_DEFAULT): + """Initializes saver. + + Args: + saver: A `Saver` object. If set to USE_DEFAULT, create one that saves all + the variables. + """ + if saver is Supervisor.USE_DEFAULT: + saver = self._get_first_op_from_collection(ops.GraphKeys.SAVERS) + if saver is None and variables.global_variables(): + saver = saver_mod.Saver() + ops.add_to_collection(ops.GraphKeys.SAVERS, saver) + self._saver = saver + + def _init_summary_op(self, summary_op=USE_DEFAULT): + """Initializes summary_op. + + Args: + summary_op: An Operation that returns a Summary for the event logs. If set + to USE_DEFAULT, create an op that merges all the summaries. + """ + if summary_op is Supervisor.USE_DEFAULT: + summary_op = self._get_first_op_from_collection(ops.GraphKeys.SUMMARY_OP) + if summary_op is None: + summary_op = _summary.merge_all() + if summary_op is not None: + ops.add_to_collection(ops.GraphKeys.SUMMARY_OP, summary_op) + self._summary_op = summary_op + + def _init_global_step(self, global_step=USE_DEFAULT): + """Initializes global_step. + + Args: + global_step: An integer Tensor of size 1 that counts steps. If set to + USE_DEFAULT, creates global_step tensor. + """ + if global_step is Supervisor.USE_DEFAULT: + global_step = self._get_first_op_from_collection( + ops.GraphKeys.GLOBAL_STEP) + if global_step is None: + global_step = self._default_global_step_tensor() + if global_step is not None: + ops.add_to_collection(ops.GraphKeys.GLOBAL_STEP, global_step) + self._global_step = global_step + + @property + def is_chief(self): + """Return True if this is a chief supervisor. + + Returns: + A bool. + """ + return self._is_chief + + @property + def session_manager(self): + """Return the SessionManager used by the Supervisor. + + Returns: + A SessionManager object. + """ + return self._session_manager + + @property + def coord(self): + """Return the Coordinator used by the Supervisor. + + The Coordinator can be useful if you want to run multiple threads + during your training. + + Returns: + A Coordinator object. + """ + return self._coord + + @property + def init_op(self): + """Return the Init Op used by the supervisor. + + Returns: + An Op or `None`. + """ + return self._init_op + + @property + def init_feed_dict(self): + """Return the feed dictionary used when evaluating the `init_op`. + + Returns: + A feed dictionary or `None`. + """ + return self._init_feed_dict + + @property + def ready_op(self): + """Return the Ready Op used by the supervisor. + + Returns: + An Op or `None`. + """ + return self._ready_op + + @property + def ready_for_local_init_op(self): + return self._ready_for_local_init_op + + @property + def summary_writer(self): + """Return the SummaryWriter used by the chief supervisor. + + Returns: + A SummaryWriter. + """ + return self._summary_writer + + @property + def summary_op(self): + """Return the Summary Tensor used by the chief supervisor. + + Returns: + A string Tensor for the summary or `None`. + """ + return self._summary_op + + @property + def save_summaries_secs(self): + """Return the delay between summary computations. + + Returns: + A timestamp. + """ + return self._save_summaries_secs + + @property + def global_step(self): + """Return the global_step Tensor used by the supervisor. + + Returns: + An integer Tensor for the global_step. + """ + return self._global_step + + @property + def saver(self): + """Return the Saver used by the supervisor. + + Returns: + A Saver object. + """ + return self._saver + + @property + def save_model_secs(self): + """Return the delay between checkpoints. + + Returns: + A timestamp. + """ + return self._save_model_secs + + @property + def save_path(self): + """Return the save path used by the supervisor. + + Returns: + A string. + """ + return self._save_path + + def _write_graph(self): + """Writes graph_def to `logdir` and adds it to summary if applicable.""" + assert self._is_chief + if self._logdir: + training_util.write_graph( + self._graph.as_graph_def(add_shapes=True), self._logdir, + "graph.pbtxt") + if self._summary_writer and not self._graph_added_to_summary: + self._summary_writer.add_graph(self._graph) + self._summary_writer.add_meta_graph(self._meta_graph_def) + self._graph_added_to_summary = True + + def start_standard_services(self, sess): + """Start the standard services for 'sess'. + + This starts services in the background. The services started depend + on the parameters to the constructor and may include: + + - A Summary thread computing summaries every save_summaries_secs. + - A Checkpoint thread saving the model every save_model_secs. + - A StepCounter thread measure step time. + + Args: + sess: A Session. + + Returns: + A list of threads that are running the standard services. You can use + the Supervisor's Coordinator to join these threads with: + sv.coord.Join() + + Raises: + RuntimeError: If called with a non-chief Supervisor. + ValueError: If not `logdir` was passed to the constructor as the + services need a log directory. + """ + if not self._is_chief: + raise RuntimeError("Only chief supervisor can start standard services. " + "Because only chief supervisors can write events.") + + if not self._logdir: + logging.warning("Standard services need a 'logdir' " + "passed to the SessionManager") + return + + if self._global_step is not None and self._summary_writer: + # Only add the session log if we keep track of global step. + # TensorBoard cannot use START message for purging expired events + # if there is no step value. + current_step = training_util.global_step(sess, self._global_step) + self._summary_writer.add_session_log( + SessionLog(status=SessionLog.START), current_step) + + threads = [] + if self._save_summaries_secs and self._summary_writer: + if self._summary_op is not None: + threads.append(SVSummaryThread(self, sess)) + if self._global_step is not None: + threads.append(SVStepCounterThread(self, sess)) + if self.saver and self._save_model_secs: + threads.append(SVTimerCheckpointThread(self, sess)) + for t in threads: + t.start() + return threads + + def prepare_or_wait_for_session(self, + master="", + config=None, + wait_for_checkpoint=False, + max_wait_secs=7200, + start_standard_services=True): + """Make sure the model is ready to be used. + + Create a session on 'master', recovering or initializing the model as + needed, or wait for a session to be ready. If running as the chief + and `start_standard_service` is set to True, also call the session + manager to start the standard services. + + Args: + master: name of the TensorFlow master to use. See the + `tf.compat.v1.Session` constructor for how this is interpreted. + config: Optional ConfigProto proto used to configure the session, which is + passed as-is to create the session. + wait_for_checkpoint: Whether we should wait for the availability of a + checkpoint before creating Session. Defaults to False. + max_wait_secs: Maximum time to wait for the session to become available. + start_standard_services: Whether to start the standard services and the + queue runners. + + Returns: + A Session object that can be used to drive the model. + """ + # For users who recreate the session with prepare_or_wait_for_session(), we + # need to clear the coordinator's stop_event so that threads managed by the + # coordinator can run. + self._coord.clear_stop() + if self._summary_writer: + self._summary_writer.reopen() + + if self._is_chief: + sess = self._session_manager.prepare_session( + master, + init_op=self.init_op, + saver=self.saver, + checkpoint_dir=self._logdir, + wait_for_checkpoint=wait_for_checkpoint, + max_wait_secs=max_wait_secs, + config=config, + init_feed_dict=self._init_feed_dict, + init_fn=self._init_fn) + self._write_graph() + if start_standard_services: + logging.info("Starting standard services.") + self.start_standard_services(sess) + else: + sess = self._session_manager.wait_for_session( + master, config=config, max_wait_secs=max_wait_secs) + if start_standard_services: + logging.info("Starting queue runners.") + self.start_queue_runners(sess) + return sess + + def start_queue_runners(self, sess, queue_runners=None): + """Start threads for `QueueRunners`. + + Note that the queue runners collected in the graph key `QUEUE_RUNNERS` + are already started automatically when you create a session with the + supervisor, so unless you have non-collected queue runners to start + you do not need to call this explicitly. + + Args: + sess: A `Session`. + queue_runners: A list of `QueueRunners`. If not specified, we'll use the + list of queue runners gathered in the graph under the key + `GraphKeys.QUEUE_RUNNERS`. + + Returns: + The list of threads started for the `QueueRunners`. + + Raises: + RuntimeError: If called with eager execution enabled. + + @compatibility(eager) + Queues are not compatible with eager execution. To ingest data when eager + execution is enabled, use the `tf.data` API. + @end_compatibility + """ + if context.executing_eagerly(): + raise RuntimeError("Queues are not compatible with eager execution.") + if queue_runners is None: + queue_runners = self._graph.get_collection(ops.GraphKeys.QUEUE_RUNNERS) + threads = [] + for qr in queue_runners: + threads.extend( + qr.create_threads(sess, coord=self._coord, daemon=True, start=True)) + return threads + + def loop(self, timer_interval_secs, target, args=None, kwargs=None): + """Start a LooperThread that calls a function periodically. + + If `timer_interval_secs` is None the thread calls `target(*args, **kwargs)` + repeatedly. Otherwise it calls it every `timer_interval_secs` + seconds. The thread terminates when a stop is requested. + + The started thread is added to the list of threads managed by the supervisor + so it does not need to be passed to the `stop()` method. + + Args: + timer_interval_secs: Number. Time boundaries at which to call `target`. + target: A callable object. + args: Optional arguments to pass to `target` when calling it. + kwargs: Optional keyword arguments to pass to `target` when calling it. + + Returns: + The started thread. + """ + looper = coordinator.LooperThread( + self._coord, + timer_interval_secs, + target=target, + args=args, + kwargs=kwargs) + looper.start() + return looper + + def stop(self, + threads=None, + close_summary_writer=True, + ignore_live_threads=False): + """Stop the services and the coordinator. + + This does not close the session. + + Args: + threads: Optional list of threads to join with the coordinator. If + `None`, defaults to the threads running the standard services, the + threads started for `QueueRunners`, and the threads started by the + `loop()` method. To wait on additional threads, pass the list in this + parameter. + close_summary_writer: Whether to close the `summary_writer`. Defaults to + `True` if the summary writer was created by the supervisor, `False` + otherwise. + ignore_live_threads: If `True` ignores threads that remain running after a + grace period when joining threads via the coordinator, instead of + raising a RuntimeError. + """ + self._coord.request_stop() + try: + # coord.join() re-raises the first reported exception; the "finally" + # block ensures that we clean up whether or not an exception was + # reported. + self._coord.join( + threads, + stop_grace_period_secs=self._stop_grace_secs, + ignore_live_threads=ignore_live_threads) + finally: + # Close the writer last, in case one of the running threads was using it. + if close_summary_writer and self._summary_writer: + # Stop messages are not logged with event.step, + # since the session may have already terminated. + self._summary_writer.add_session_log(SessionLog(status=SessionLog.STOP)) + self._summary_writer.close() + self._graph_added_to_summary = False + + def request_stop(self, ex=None): + """Request that the coordinator stop the threads. + + See `Coordinator.request_stop()`. + + Args: + ex: Optional `Exception`, or Python `exc_info` tuple as returned by + `sys.exc_info()`. If this is the first call to `request_stop()` the + corresponding exception is recorded and re-raised from `join()`. + """ + self._coord.request_stop(ex=ex) + + def should_stop(self): + """Check if the coordinator was told to stop. + + See `Coordinator.should_stop()`. + + Returns: + True if the coordinator was told to stop, False otherwise. + """ + return self._coord.should_stop() + + def stop_on_exception(self): + """Context handler to stop the supervisor when an exception is raised. + + See `Coordinator.stop_on_exception()`. + + Returns: + A context handler. + """ + return self._coord.stop_on_exception() + + def wait_for_stop(self): + """Block waiting for the coordinator to stop.""" + self._coord.wait_for_stop() + + def summary_computed(self, sess, summary, global_step=None): + """Indicate that a summary was computed. + + Args: + sess: A `Session` object. + summary: A Summary proto, or a string holding a serialized summary proto. + global_step: Int. global step this summary is associated with. If `None`, + it will try to fetch the current step. + + Raises: + TypeError: if 'summary' is not a Summary proto or a string. + RuntimeError: if the Supervisor was created without a `logdir`. + """ + if not self._summary_writer: + raise RuntimeError("Writing a summary requires a summary writer.") + if global_step is None and self.global_step is not None: + global_step = training_util.global_step(sess, self.global_step) + self._summary_writer.add_summary(summary, global_step) + + def _default_global_step_tensor(self): + """Returns the global_step from the default graph. + + Returns: + The global step `Tensor` or `None`. + """ + try: + gs = ops.get_default_graph().get_tensor_by_name("global_step:0") + if gs.dtype.base_dtype in [dtypes.int32, dtypes.int64]: + return gs + else: + logging.warning("Found 'global_step' is not an int type: %s", gs.dtype) + return None + except KeyError: + return None + + def _verify_setup(self): + """Check that all is good. + + Raises: + ValueError: If something is not good. + """ + # Not running as chief means that replicas are used. + # In that case all Variables must have their device set. + if not self._is_chief: + for op in self._graph.get_operations(): + if op.type in ["Variable", "VariableV2"] and not op.device: + raise ValueError("When using replicas, all Variables must have " + "their device set: %s" % op) + + # pylint: disable=g-doc-return-or-yield,broad-except + @contextlib.contextmanager + def managed_session(self, + master="", + config=None, + start_standard_services=True, + close_summary_writer=True): + """Returns a context manager for a managed session. + + This context manager creates and automatically recovers a session. It + optionally starts the standard services that handle checkpoints and + summaries. It monitors exceptions raised from the `with` block or from the + services and stops the supervisor as needed. + + The context manager is typically used as follows: + + ```python + def train(): + sv = tf.compat.v1.train.Supervisor(...) + with sv.managed_session() as sess: + for step in range(..): + if sv.should_stop(): + break + sess.run() + ...do other things needed at each training step... + ``` + + An exception raised from the `with` block or one of the service threads is + raised again when the block exits. This is done after stopping all threads + and closing the session. For example, an `AbortedError` exception, raised + in case of preemption of one of the workers in a distributed model, is + raised again when the block exits. + + If you want to retry the training loop in case of preemption you can do it + as follows: + + ```python + def main(...): + while True + try: + train() + except tf.errors.Aborted: + pass + ``` + + As a special case, exceptions used for control flow, such as + `OutOfRangeError` which reports that input queues are exhausted, are not + raised again from the `with` block: they indicate a clean termination of + the training loop and are considered normal termination. + + Args: + master: name of the TensorFlow master to use. See the + `tf.compat.v1.Session` constructor for how this is interpreted. + config: Optional `ConfigProto` proto used to configure the session. Passed + as-is to create the session. + start_standard_services: Whether to start the standard services, such as + checkpoint, summary and step counter. + close_summary_writer: Whether to close the summary writer when closing the + session. Defaults to True. + + Returns: + A context manager that yields a `Session` restored from the latest + checkpoint or initialized from scratch if not checkpoint exists. The + session is closed when the `with` block exits. + """ + try: + sess = self.prepare_or_wait_for_session( + master=master, + config=config, + start_standard_services=start_standard_services) + yield sess + except Exception as e: + self.request_stop(e) + finally: + try: + # Request all the threads to stop and wait for them to do so. Any + # exception raised by the threads is raised again from stop(). + # Passing stop_grace_period_secs is for blocked enqueue/dequeue + # threads which are not checking for `should_stop()`. They + # will be stopped when we close the session further down. + self.stop(close_summary_writer=close_summary_writer) + finally: + # Close the session to finish up all pending calls. We do not care + # about exceptions raised when closing. This takes care of + # blocked enqueue/dequeue calls. + try: + sess.close() + except Exception: + # Silently ignore exceptions raised by close(). + pass + + # pylint: enable=g-doc-return-or-yield,broad-except + + +class SVSummaryThread(coordinator.LooperThread): + """A thread to save summaries on a timer.""" + + def __init__(self, sv, sess): + """Create a SVSummaryThread. + + Args: + sv: A `Supervisor`. + sess: A `Session`. + """ + super(SVSummaryThread, self).__init__(sv.coord, sv.save_summaries_secs) + self._sv = sv + self._sess = sess + + def run_loop(self): + if self._sv.global_step is not None: + summary_strs, global_step = self._sess.run( + [self._sv.summary_op, self._sv.global_step]) + else: + summary_strs = self._sess.run(self._sv.summary_op) + global_step = None + if self._sv.summary_writer: + logging.info("Recording summary at step %s.", global_step) + self._sv.summary_writer.add_summary(summary_strs, global_step) + + +class SVStepCounterThread(coordinator.LooperThread): + """Threads to count steps and measure their duration.""" + + def __init__(self, sv, sess, step_counter=None): + """Create a `SVStepCounterThread`. + + Args: + sv: A `Supervisor`. + sess: A `Session`. + step_counter: A `Tensor` holding the step counter. By defaults, it uses + sv.global_step. + """ + super(SVStepCounterThread, self).__init__(sv.coord, sv.save_summaries_secs) + self._sv = sv + self._sess = sess + self._last_time = 0.0 + self._last_step = 0 + step_counter = sv.global_step if step_counter is None else step_counter + self._step_counter = step_counter + self._summary_tag = "%s/sec" % self._step_counter.op.name + + def start_loop(self): + self._last_time = time.time() + self._last_step = training_util.global_step(self._sess, self._step_counter) + + def run_loop(self): + # Count the steps. + current_step = training_util.global_step(self._sess, self._step_counter) + added_steps = current_step - self._last_step + self._last_step = current_step + # Measure the elapsed time. + current_time = time.time() + elapsed_time = current_time - self._last_time + self._last_time = current_time + # Reports the number of steps done per second + if elapsed_time > 0.: + steps_per_sec = added_steps / elapsed_time + else: + steps_per_sec = float("inf") + summary = Summary(value=[ + Summary.Value(tag=self._summary_tag, simple_value=steps_per_sec) + ]) + if self._sv.summary_writer: + self._sv.summary_writer.add_summary(summary, current_step) + logging.log_first_n(logging.INFO, "%s: %g", 10, self._summary_tag, + steps_per_sec) + + +class SVTimerCheckpointThread(coordinator.LooperThread): + """A thread to checkpoint on a timer.""" + + def __init__(self, sv, sess): + """Create a `SVTimerCheckpointThread`. + + Args: + sv: A `Supervisor`. + sess: A `Session`. + """ + super(SVTimerCheckpointThread, self).__init__(sv.coord, sv.save_model_secs) + self._sv = sv + self._sess = sess + + def run_loop(self): + logging.info("Saving checkpoint to path %s", self._sv.save_path) + self._sv.saver.save( + self._sess, self._sv.save_path, global_step=self._sv.global_step) + if self._sv.summary_writer and self._sv.global_step is not None: + current_step = training_util.global_step(self._sess, self._sv.global_step) + self._sv.summary_writer.add_session_log( + SessionLog( + status=SessionLog.CHECKPOINT, checkpoint_path=self._sv.save_path), + current_step) + + +# TODO(sherrym): All non-PEP8 compliant names will be deprecated shortly. +setattr(Supervisor, "PrepareSession", Supervisor.prepare_or_wait_for_session) +setattr(Supervisor, "StartQueueRunners", Supervisor.start_queue_runners) +setattr(Supervisor, "StartStandardServices", Supervisor.start_standard_services) +setattr(Supervisor, "Stop", Supervisor.stop) +setattr(Supervisor, "RequestStop", Supervisor.request_stop) +setattr(Supervisor, "Loop", Supervisor.loop) +setattr(Supervisor, "ShouldStop", Supervisor.should_stop) +setattr(Supervisor, "StopOnException", Supervisor.stop_on_exception) +setattr(Supervisor, "WaitForStop", Supervisor.wait_for_stop) +setattr(Supervisor, "SummaryComputed", Supervisor.summary_computed) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/sync_replicas_optimizer.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/sync_replicas_optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..26c26dc1ff7627284b65e0f27ab3e5024db8e5ee --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/sync_replicas_optimizer.py @@ -0,0 +1,501 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""Synchronize replicas for training.""" +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.framework import indexed_slices +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import data_flow_ops +from tensorflow.python.ops import state_ops +from tensorflow.python.ops import variable_v1 +from tensorflow.python.ops import variables +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.training import optimizer +from tensorflow.python.training import queue_runner +from tensorflow.python.training import session_manager +from tensorflow.python.training import session_run_hook +from tensorflow.python.util import deprecation +from tensorflow.python.util.tf_export import tf_export + + +# Please note that the gradients from replicas are averaged instead of summed +# (as in the old sync_replicas_optimizer) so you need to increase the learning +# rate according to the number of replicas. This change is introduced to be +# consistent with how gradients are aggregated (averaged) within a batch in a +# replica. +@tf_export(v1=["train.SyncReplicasOptimizer"]) +class SyncReplicasOptimizer(optimizer.Optimizer): + """Class to synchronize, aggregate gradients and pass them to the optimizer. + + This class is deprecated. For synchronous training, please use [Distribution + Strategies](https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/distribute). + + In a typical asynchronous training environment, it's common to have some + stale gradients. For example, with a N-replica asynchronous training, + gradients will be applied to the variables N times independently. Depending + on each replica's training speed, some gradients might be calculated from + copies of the variable from several steps back (N-1 steps on average). This + optimizer avoids stale gradients by collecting gradients from all replicas, + averaging them, then applying them to the variables in one shot, after + which replicas can fetch the new variables and continue. + + The following accumulators/queue are created: + + * N `gradient accumulators`, one per variable to train. Gradients are pushed + to them and the chief worker will wait until enough gradients are collected + and then average them before applying to variables. The accumulator will + drop all stale gradients (more details in the accumulator op). + * 1 `token` queue where the optimizer pushes the new global_step value after + all variables are updated. + + The following local variable is created: + * `sync_rep_local_step`, one per replica. Compared against the global_step in + each accumulator to check for staleness of the gradients. + + The optimizer adds nodes to the graph to collect gradients and pause the + trainers until variables are updated. + For the Parameter Server job: + + 1. An accumulator is created for each variable, and each replica pushes the + gradients into the accumulators instead of directly applying them to the + variables. + 2. Each accumulator averages once enough gradients (replicas_to_aggregate) + have been accumulated. + 3. Apply the averaged gradients to the variables. + 4. Only after all variables have been updated, increment the global step. + 5. Only after step 4, pushes `global_step` in the `token_queue`, once for + each worker replica. The workers can now fetch the global step, use it to + update its local_step variable and start the next batch. Please note that + some workers can consume multiple minibatches, while some may not consume + even one. This is because each worker fetches minibatches as long as + a token exists. If one worker is stuck for some reason and does not + consume a token, another worker can use it. + + For the replicas: + + 1. Start a step: fetch variables and compute gradients. + 2. Once the gradients have been computed, push them into gradient + accumulators. Each accumulator will check the staleness and drop the stale. + 3. After pushing all the gradients, dequeue an updated value of global_step + from the token queue and record that step to its local_step variable. Note + that this is effectively a barrier. + 4. Start the next batch. + + ### Usage + + ```python + # Create any optimizer to update the variables, say a simple SGD: + opt = GradientDescentOptimizer(learning_rate=0.1) + + # Wrap the optimizer with sync_replicas_optimizer with 50 replicas: at each + # step the optimizer collects 50 gradients before applying to variables. + # Note that if you want to have 2 backup replicas, you can change + # total_num_replicas=52 and make sure this number matches how many physical + # replicas you started in your job. + opt = tf.compat.v1.train.SyncReplicasOptimizer(opt, replicas_to_aggregate=50, + total_num_replicas=50) + + # Some models have startup_delays to help stabilize the model but when using + # sync_replicas training, set it to 0. + + # Now you can call `minimize()` or `compute_gradients()` and + # `apply_gradients()` normally + training_op = opt.minimize(total_loss, global_step=self.global_step) + + + # You can create the hook which handles initialization and queues. + sync_replicas_hook = opt.make_session_run_hook(is_chief) + ``` + + In the training program, every worker will run the train_op as if not + synchronized. + + ```python + with training.MonitoredTrainingSession( + master=workers[worker_id].target, is_chief=is_chief, + hooks=[sync_replicas_hook]) as mon_sess: + while not mon_sess.should_stop(): + mon_sess.run(training_op) + ``` + + To use SyncReplicasOptimizer with an `Estimator`, you need to send + sync_replicas_hook while calling the fit. + ```python + my_estimator = DNNClassifier(..., optimizer=opt) + my_estimator.fit(..., hooks=[sync_replicas_hook]) + ``` + """ + + @deprecation.deprecated( + None, "The `SyncReplicaOptimizer` class is deprecated. For synchronous " + "training, please use [Distribution Strategies](https://github.com/" + "tensorflow/tensorflow/tree/master/tensorflow/contrib/distribute).", + warn_once=True) + def __init__(self, + opt, + replicas_to_aggregate, + total_num_replicas=None, + variable_averages=None, + variables_to_average=None, + use_locking=False, + name="sync_replicas"): + """Construct a sync_replicas optimizer. + + Args: + opt: The actual optimizer that will be used to compute and apply the + gradients. Must be one of the Optimizer classes. + replicas_to_aggregate: number of replicas to aggregate for each variable + update. + total_num_replicas: Total number of tasks/workers/replicas, could be + different from replicas_to_aggregate. + If total_num_replicas > replicas_to_aggregate: it is backup_replicas + + replicas_to_aggregate. + If total_num_replicas < replicas_to_aggregate: Replicas compute + multiple batches per update to variables. + variable_averages: Optional `ExponentialMovingAverage` object, used to + maintain moving averages for the variables passed in + `variables_to_average`. + variables_to_average: a list of variables that need to be averaged. Only + needed if variable_averages is passed in. + use_locking: If True use locks for update operation. + name: string. Optional name of the returned operation. + """ + if total_num_replicas is None: + total_num_replicas = replicas_to_aggregate + + super(SyncReplicasOptimizer, self).__init__(use_locking, name) + logging.info( + "SyncReplicasV2: replicas_to_aggregate=%s; total_num_replicas=%s", + replicas_to_aggregate, total_num_replicas) + self._opt = opt + self._replicas_to_aggregate = replicas_to_aggregate + self._gradients_applied = False + self._variable_averages = variable_averages + self._variables_to_average = variables_to_average + self._total_num_replicas = total_num_replicas + self._tokens_per_step = max(total_num_replicas, replicas_to_aggregate) + self._global_step = None + self._sync_token_queue = None + + # The synchronization op will be executed in a queue runner which should + # only be executed by one of the replicas (usually the chief). + self._chief_queue_runner = None + + # Remember which accumulator is on which device to set the initial step in + # the accumulator to be global step. This list contains list of the + # following format: (accumulator, device). + self._accumulator_list = [] + + def compute_gradients(self, *args, **kwargs): + """Compute gradients of "loss" for the variables in "var_list". + + This simply wraps the compute_gradients() from the real optimizer. The + gradients will be aggregated in the apply_gradients() so that user can + modify the gradients like clipping with per replica global norm if needed. + The global norm with aggregated gradients can be bad as one replica's huge + gradients can hurt the gradients from other replicas. + + Args: + *args: Arguments for compute_gradients(). + **kwargs: Keyword arguments for compute_gradients(). + + Returns: + A list of (gradient, variable) pairs. + """ + return self._opt.compute_gradients(*args, **kwargs) + + def apply_gradients(self, grads_and_vars, global_step=None, name=None): + """Apply gradients to variables. + + This contains most of the synchronization implementation and also wraps the + apply_gradients() from the real optimizer. + + Args: + grads_and_vars: List of (gradient, variable) pairs as returned by + compute_gradients(). + global_step: Optional Variable to increment by one after the + variables have been updated. + name: Optional name for the returned operation. Default to the + name passed to the Optimizer constructor. + + Returns: + train_op: The op to dequeue a token so the replicas can exit this batch + and start the next one. This is executed by each replica. + + Raises: + ValueError: If the grads_and_vars is empty. + ValueError: If global step is not provided, the staleness cannot be + checked. + """ + if not grads_and_vars: + raise ValueError("Must supply at least one variable") + + if global_step is None: + raise ValueError("Global step is required to check staleness") + + self._global_step = global_step + train_ops = [] + aggregated_grad = [] + var_list = [] + + # local_anchor op will be placed on this worker task by default. + local_anchor = control_flow_ops.no_op() + # Colocating local_step variable prevents it being placed on the PS. + distribution_strategy = distribute_lib.get_strategy() + with distribution_strategy.extended.colocate_vars_with(local_anchor): + self._local_step = variable_v1.VariableV1( + initial_value=0, + trainable=False, + collections=[ops.GraphKeys.LOCAL_VARIABLES], + dtype=global_step.dtype.base_dtype, + name="sync_rep_local_step") + + self.local_step_init_op = state_ops.assign(self._local_step, global_step) + chief_init_ops = [self.local_step_init_op] + self.ready_for_local_init_op = variables.report_uninitialized_variables( + variables.global_variables()) + + with ops.name_scope(None, self._name): + for grad, var in grads_and_vars: + var_list.append(var) + with ops.device(var.device): + # Dense gradients. + if grad is None: + aggregated_grad.append(None) # pass-through. + continue + elif isinstance(grad, tensor.Tensor): + grad_accum = data_flow_ops.ConditionalAccumulator( + grad.dtype, + shape=var.get_shape(), + shared_name=var.name + "/grad_accum") + train_ops.append(grad_accum.apply_grad( + grad, local_step=self._local_step)) + aggregated_grad.append(grad_accum.take_grad( + self._replicas_to_aggregate)) + else: + if not isinstance(grad, indexed_slices.IndexedSlices): + raise ValueError("Unknown grad type!") + grad_accum = data_flow_ops.SparseConditionalAccumulator( + grad.dtype, shape=(), shared_name=var.name + "/grad_accum") + train_ops.append(grad_accum.apply_indexed_slices_grad( + grad, local_step=self._local_step)) + aggregated_grad.append(grad_accum.take_indexed_slices_grad( + self._replicas_to_aggregate)) + + self._accumulator_list.append((grad_accum, var.device)) + + aggregated_grads_and_vars = zip(aggregated_grad, var_list) + + # sync_op will be assigned to the same device as the global step. + with ops.device(global_step.device), ops.name_scope(""): + update_op = self._opt.apply_gradients(aggregated_grads_and_vars, + global_step) + + # Create token queue. + with ops.device(global_step.device), ops.name_scope(""): + sync_token_queue = ( + data_flow_ops.FIFOQueue(-1, + global_step.dtype.base_dtype, + shapes=(), + name="sync_token_q", + shared_name="sync_token_q")) + self._sync_token_queue = sync_token_queue + + with ops.device(global_step.device), ops.name_scope(""): + # Replicas have to wait until they can get a token from the token queue. + with ops.control_dependencies(train_ops): + token = sync_token_queue.dequeue() + train_op = state_ops.assign(self._local_step, token) + + with ops.control_dependencies([update_op]): + # Sync_op needs to insert tokens to the token queue at the end of the + # step so the replicas can fetch them to start the next step. + tokens = array_ops.fill([self._tokens_per_step], global_step) + sync_op = sync_token_queue.enqueue_many((tokens,)) + + if self._variable_averages is not None: + with ops.control_dependencies([sync_op]), ops.name_scope(""): + sync_op = self._variable_averages.apply( + self._variables_to_average) + + self._chief_queue_runner = queue_runner.QueueRunner( + sync_token_queue, [sync_op]) + for accum, dev in self._accumulator_list: + with ops.device(dev): + chief_init_ops.append( + accum.set_global_step( + global_step, name="SetGlobalStep")) + self.chief_init_op = control_flow_ops.group(*(chief_init_ops)) + self._gradients_applied = True + return train_op + + def get_chief_queue_runner(self): + """Returns the QueueRunner for the chief to execute. + + This includes the operations to synchronize replicas: aggregate gradients, + apply to variables, increment global step, insert tokens to token queue. + + Note that this can only be called after calling apply_gradients() which + actually generates this queuerunner. + + Returns: + A `QueueRunner` for chief to execute. + + Raises: + ValueError: If this is called before apply_gradients(). + """ + if self._gradients_applied is False: + raise ValueError("Should be called after apply_gradients().") + + return self._chief_queue_runner + + def get_slot(self, *args, **kwargs): + """Return a slot named "name" created for "var" by the Optimizer. + + This simply wraps the get_slot() from the actual optimizer. + + Args: + *args: Arguments for get_slot(). + **kwargs: Keyword arguments for get_slot(). + + Returns: + The `Variable` for the slot if it was created, `None` otherwise. + """ + return self._opt.get_slot(*args, **kwargs) + + def variables(self): + """Fetches a list of optimizer variables in the default graph. + + This wraps `variables()` from the actual optimizer. It does not include + the `SyncReplicasOptimizer`'s local step. + + Returns: + A list of variables. + """ + return self._opt.variables() + + def get_slot_names(self, *args, **kwargs): + """Return a list of the names of slots created by the `Optimizer`. + + This simply wraps the get_slot_names() from the actual optimizer. + + Args: + *args: Arguments for get_slot(). + **kwargs: Keyword arguments for get_slot(). + + Returns: + A list of strings. + """ + return self._opt.get_slot_names(*args, **kwargs) + + def get_init_tokens_op(self, num_tokens=-1): + """Returns the op to fill the sync_token_queue with the tokens. + + This is supposed to be executed in the beginning of the chief/sync thread + so that even if the total_num_replicas is less than replicas_to_aggregate, + the model can still proceed as the replicas can compute multiple steps per + variable update. Make sure: + `num_tokens >= replicas_to_aggregate - total_num_replicas`. + + Args: + num_tokens: Number of tokens to add to the queue. + + Returns: + An op for the chief/sync replica to fill the token queue. + + Raises: + ValueError: If this is called before apply_gradients(). + ValueError: If num_tokens are smaller than replicas_to_aggregate - + total_num_replicas. + """ + if self._gradients_applied is False: + raise ValueError( + "get_init_tokens_op() should be called after apply_gradients().") + + tokens_needed = self._replicas_to_aggregate - self._total_num_replicas + if num_tokens == -1: + num_tokens = self._replicas_to_aggregate + elif num_tokens < tokens_needed: + raise ValueError( + "Too few tokens to finish the first step: %d (given) vs %d (needed)" % + (num_tokens, tokens_needed)) + + if num_tokens > 0: + with ops.device(self._global_step.device), ops.name_scope(""): + tokens = array_ops.fill([num_tokens], self._global_step) + init_tokens = self._sync_token_queue.enqueue_many((tokens,)) + else: + init_tokens = control_flow_ops.no_op(name="no_init_tokens") + + return init_tokens + + def make_session_run_hook(self, is_chief, num_tokens=-1): + """Creates a hook to handle SyncReplicasHook ops such as initialization.""" + return _SyncReplicasOptimizerHook(self, is_chief, num_tokens) + + +class _SyncReplicasOptimizerHook(session_run_hook.SessionRunHook): + """A SessionRunHook handles ops related to SyncReplicasOptimizer.""" + + def __init__(self, sync_optimizer, is_chief, num_tokens): + """Creates hook to handle SyncReplicasOptimizer initialization ops. + + Args: + sync_optimizer: `SyncReplicasOptimizer` which this hook will initialize. + is_chief: `Bool`, whether is this a chief replica or not. + num_tokens: Number of tokens to add to the queue. + """ + self._sync_optimizer = sync_optimizer + self._is_chief = is_chief + self._num_tokens = num_tokens + + def begin(self): + if self._sync_optimizer._gradients_applied is False: # pylint: disable=protected-access + raise ValueError( + "SyncReplicasOptimizer.apply_gradient should be called before using " + "the hook.") + if self._is_chief: + self._local_init_op = self._sync_optimizer.chief_init_op + self._ready_for_local_init_op = ( + self._sync_optimizer.ready_for_local_init_op) + self._q_runner = self._sync_optimizer.get_chief_queue_runner() + self._init_tokens_op = self._sync_optimizer.get_init_tokens_op( + self._num_tokens) + else: + self._local_init_op = self._sync_optimizer.local_step_init_op + self._ready_for_local_init_op = ( + self._sync_optimizer.ready_for_local_init_op) + self._q_runner = None + self._init_tokens_op = None + + def after_create_session(self, session, coord): + """Runs SyncReplicasOptimizer initialization ops.""" + local_init_success, msg = session_manager._ready( # pylint: disable=protected-access + self._ready_for_local_init_op, session, + "Model is not ready for SyncReplicasOptimizer local init.") + if not local_init_success: + raise RuntimeError( + "Init operations did not make model ready for SyncReplicasOptimizer " + "local_init. Init op: %s, error: %s" % + (self._local_init_op.name, msg)) + session.run(self._local_init_op) + if self._init_tokens_op is not None: + session.run(self._init_tokens_op) + if self._q_runner is not None: + self._q_runner.create_threads( + session, coord=coord, daemon=True, start=True) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/training.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/training.py new file mode 100644 index 0000000000000000000000000000000000000000..6c7c8cbe58c5c7e156eae43501262c44916f52ce --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/training.py @@ -0,0 +1,733 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""Support for training models. + +See the [Training](https://tensorflow.org/api_guides/python/train) guide. +""" + +# Optimizers. +# pylint: disable=g-bad-import-order,unused-import +from tensorflow.python.ops.sdca_ops import sdca_optimizer +from tensorflow.python.ops.sdca_ops import sdca_fprint +from tensorflow.python.ops.sdca_ops import sdca_shrink_l1 +from tensorflow.python.training.adadelta import AdadeltaOptimizer +from tensorflow.python.training.adagrad import AdagradOptimizer +from tensorflow.python.training.adagrad_da import AdagradDAOptimizer +from tensorflow.python.training.proximal_adagrad import ProximalAdagradOptimizer +from tensorflow.python.training.adam import AdamOptimizer +from tensorflow.python.training.ftrl import FtrlOptimizer +from tensorflow.python.training.experimental.loss_scale_optimizer import MixedPrecisionLossScaleOptimizer +from tensorflow.python.training.experimental.mixed_precision import enable_mixed_precision_graph_rewrite_v1 +from tensorflow.python.training.momentum import MomentumOptimizer +from tensorflow.python.training.moving_averages import ExponentialMovingAverage +from tensorflow.python.training.optimizer import Optimizer +from tensorflow.python.training.rmsprop import RMSPropOptimizer +from tensorflow.python.training.gradient_descent import GradientDescentOptimizer +from tensorflow.python.training.proximal_gradient_descent import ProximalGradientDescentOptimizer +from tensorflow.python.training.sync_replicas_optimizer import SyncReplicasOptimizer + +# Utility classes for training. +from tensorflow.python.training.coordinator import Coordinator +from tensorflow.python.training.coordinator import LooperThread +# go/tf-wildcard-import +# pylint: disable=wildcard-import +from tensorflow.python.training.queue_runner import * + +# For the module level doc. +from tensorflow.python.training import input as _input +from tensorflow.python.training.input import * # pylint: disable=redefined-builtin +# pylint: enable=wildcard-import + +from tensorflow.python.training.basic_session_run_hooks import get_or_create_steps_per_run_variable +from tensorflow.python.training.basic_session_run_hooks import SecondOrStepTimer +from tensorflow.python.training.basic_session_run_hooks import LoggingTensorHook +from tensorflow.python.training.basic_session_run_hooks import StopAtStepHook +from tensorflow.python.training.basic_session_run_hooks import CheckpointSaverHook +from tensorflow.python.training.basic_session_run_hooks import CheckpointSaverListener +from tensorflow.python.training.basic_session_run_hooks import StepCounterHook +from tensorflow.python.training.basic_session_run_hooks import NanLossDuringTrainingError +from tensorflow.python.training.basic_session_run_hooks import NanTensorHook +from tensorflow.python.training.basic_session_run_hooks import SummarySaverHook +from tensorflow.python.training.basic_session_run_hooks import GlobalStepWaiterHook +from tensorflow.python.training.basic_session_run_hooks import FinalOpsHook +from tensorflow.python.training.basic_session_run_hooks import FeedFnHook +from tensorflow.python.training.basic_session_run_hooks import ProfilerHook +from tensorflow.python.training.basic_loops import basic_train_loop +from tensorflow.python.trackable.python_state import PythonState +from tensorflow.python.checkpoint.checkpoint import Checkpoint +from tensorflow.python.checkpoint.checkpoint_view import CheckpointView +from tensorflow.python.training.checkpoint_utils import init_from_checkpoint +from tensorflow.python.training.checkpoint_utils import list_variables +from tensorflow.python.training.checkpoint_utils import load_checkpoint +from tensorflow.python.training.checkpoint_utils import load_variable + +from tensorflow.python.training.device_setter import replica_device_setter +from tensorflow.python.training.monitored_session import Scaffold +from tensorflow.python.training.monitored_session import MonitoredTrainingSession +from tensorflow.python.training.monitored_session import SessionCreator +from tensorflow.python.training.monitored_session import ChiefSessionCreator +from tensorflow.python.training.monitored_session import WorkerSessionCreator +from tensorflow.python.training.monitored_session import MonitoredSession +from tensorflow.python.training.monitored_session import SingularMonitoredSession +from tensorflow.python.training.saver import Saver +from tensorflow.python.checkpoint.checkpoint_management import checkpoint_exists +from tensorflow.python.checkpoint.checkpoint_management import generate_checkpoint_state_proto +from tensorflow.python.checkpoint.checkpoint_management import get_checkpoint_mtimes +from tensorflow.python.checkpoint.checkpoint_management import get_checkpoint_state +from tensorflow.python.checkpoint.checkpoint_management import latest_checkpoint +from tensorflow.python.checkpoint.checkpoint_management import update_checkpoint_state +from tensorflow.python.training.saver import export_meta_graph +from tensorflow.python.training.saver import import_meta_graph +from tensorflow.python.training.saving import saveable_object_util +from tensorflow.python.training.session_run_hook import SessionRunHook +from tensorflow.python.training.session_run_hook import SessionRunArgs +from tensorflow.python.training.session_run_hook import SessionRunContext +from tensorflow.python.training.session_run_hook import SessionRunValues +from tensorflow.python.training.session_manager import SessionManager +from tensorflow.python.training.summary_io import summary_iterator +from tensorflow.python.training.supervisor import Supervisor +from tensorflow.python.training.training_util import write_graph +from tensorflow.python.training.training_util import global_step +from tensorflow.python.training.training_util import get_global_step +from tensorflow.python.training.training_util import assert_global_step +from tensorflow.python.training.training_util import create_global_step +from tensorflow.python.training.training_util import get_or_create_global_step +from tensorflow.python.training.warm_starting_util import VocabInfo +from tensorflow.python.training.warm_starting_util import warm_start +from tensorflow.python.training.py_checkpoint_reader import NewCheckpointReader +from tensorflow.python.util.tf_export import tf_export + +# pylint: disable=wildcard-import +# Training data protos. +from tensorflow.core.example.example_pb2 import * +from tensorflow.core.example.feature_pb2 import * +from tensorflow.core.protobuf.saver_pb2 import * + +# Utility op. Open Source. TODO(touts): move to nn? +from tensorflow.python.training.learning_rate_decay import * +# pylint: enable=wildcard-import + +# Distributed computing support. +from tensorflow.core.protobuf.cluster_pb2 import ClusterDef +from tensorflow.core.protobuf.cluster_pb2 import JobDef +from tensorflow.core.protobuf.tensorflow_server_pb2 import ServerDef +from tensorflow.python.training.server_lib import ClusterSpec +from tensorflow.python.training.server_lib import Server + +# pylint: disable=undefined-variable +tf_export("train.BytesList")(BytesList) +tf_export("train.ClusterDef")(ClusterDef) +tf_export("train.Example")(Example) +tf_export("train.Feature")(Feature) +tf_export("train.Features")(Features) +tf_export("train.FeatureList")(FeatureList) +tf_export("train.FeatureLists")(FeatureLists) +tf_export("train.FloatList")(FloatList) +tf_export("train.Int64List")(Int64List) +tf_export("train.JobDef")(JobDef) +tf_export(v1=["train.SaverDef"])(SaverDef) +tf_export("train.SequenceExample")(SequenceExample) +tf_export("train.ServerDef")(ServerDef) + +BytesList.__doc__ = """\ +Used in `tf.train.Example` protos. Holds a list of byte-strings. + +An `Example` proto is a representation of the following python type: + +``` +Dict[str, + Union[List[bytes], + List[int64], + List[float]]] +``` + +This proto implements the `List[bytes]` portion. + +>>> from google.protobuf import text_format +>>> example = text_format.Parse(''' +... features { +... feature {key: "my_feature" +... value {bytes_list {value: ['abc', '12345' ]}}} +... }''', +... tf.train.Example()) +>>> +>>> example.features.feature['my_feature'].bytes_list.value +["abc", "12345"] + +Use `tf.io.parse_example` to extract tensors from a serialized `Example` proto: + +>>> tf.io.parse_example( +... example.SerializeToString(), +... features = {'my_feature': tf.io.RaggedFeature(dtype=tf.string)}) +{'my_feature': } + + +See the [`tf.train.Example`](https://www.tensorflow.org/tutorials/load_data/tfrecord#tftrainexample) +guide for usage details. +""" + +FloatList.__doc__ = """\ +Used in `tf.train.Example` protos. Holds a list of floats. + +An `Example` proto is a representation of the following python type: + +``` +Dict[str, + Union[List[bytes], + List[int64], + List[float]]] +``` + +This proto implements the `List[float]` portion. + +>>> from google.protobuf import text_format +>>> example = text_format.Parse(''' +... features { +... feature {key: "my_feature" +... value {float_list {value: [1., 2., 3., 4. ]}}} +... }''', +... tf.train.Example()) +>>> +>>> example.features.feature['my_feature'].float_list.value +[1.0, 2.0, 3.0, 4.0] + +Use `tf.io.parse_example` to extract tensors from a serialized `Example` proto: + +>>> tf.io.parse_example( +... example.SerializeToString(), +... features = {'my_feature': tf.io.RaggedFeature(dtype=tf.float32)}) +{'my_feature': } + +See the [`tf.train.Example`](https://www.tensorflow.org/tutorials/load_data/tfrecord#tftrainexample) +guide for usage details. +""" + +Int64List.__doc__ = """\ +Used in `tf.train.Example` protos. Holds a list of Int64s. + +An `Example` proto is a representation of the following python type: + +``` +Dict[str, + Union[List[bytes], + List[int64], + List[float]]] +``` + +This proto implements the `List[int64]` portion. + +>>> from google.protobuf import text_format +>>> example = text_format.Parse(''' +... features { +... feature {key: "my_feature" +... value {int64_list {value: [1, 2, 3, 4]}}} +... }''', +... tf.train.Example()) +>>> +>>> example.features.feature['my_feature'].int64_list.value +[1, 2, 3, 4] + +Use `tf.io.parse_example` to extract tensors from a serialized `Example` proto: + +>>> tf.io.parse_example( +... example.SerializeToString(), +... features = {'my_feature': tf.io.RaggedFeature(dtype=tf.int64)}) +{'my_feature': } + +See the [`tf.train.Example`](https://www.tensorflow.org/tutorials/load_data/tfrecord#tftrainexample) +guide for usage details. +""" + +Feature.__doc__ = """\ +Used in `tf.train.Example` protos. Contains a list of values. + +An `Example` proto is a representation of the following python type: + +``` +Dict[str, + Union[List[bytes], + List[int64], + List[float]]] +``` + +This proto implements the `Union`. + +The contained list can be one of three types: + + - `tf.train.BytesList` + - `tf.train.FloatList` + - `tf.train.Int64List` + +>>> int_feature = tf.train.Feature( +... int64_list=tf.train.Int64List(value=[1, 2, 3, 4])) +>>> float_feature = tf.train.Feature( +... float_list=tf.train.FloatList(value=[1., 2., 3., 4.])) +>>> bytes_feature = tf.train.Feature( +... bytes_list=tf.train.BytesList(value=[b"abc", b"1234"])) +>>> +>>> example = tf.train.Example( +... features=tf.train.Features(feature={ +... 'my_ints': int_feature, +... 'my_floats': float_feature, +... 'my_bytes': bytes_feature, +... })) + +Use `tf.io.parse_example` to extract tensors from a serialized `Example` proto: + +>>> tf.io.parse_example( +... example.SerializeToString(), +... features = { +... 'my_ints': tf.io.RaggedFeature(dtype=tf.int64), +... 'my_floats': tf.io.RaggedFeature(dtype=tf.float32), +... 'my_bytes': tf.io.RaggedFeature(dtype=tf.string)}) +{'my_bytes': , + 'my_floats': , + 'my_ints': } + +""" + +Features.__doc__ = """\ +Used in `tf.train.Example` protos. Contains the mapping from keys to `Feature`. + +An `Example` proto is a representation of the following python type: + +``` +Dict[str, + Union[List[bytes], + List[int64], + List[float]]] +``` + +This proto implements the `Dict`. + +>>> int_feature = tf.train.Feature( +... int64_list=tf.train.Int64List(value=[1, 2, 3, 4])) +>>> float_feature = tf.train.Feature( +... float_list=tf.train.FloatList(value=[1., 2., 3., 4.])) +>>> bytes_feature = tf.train.Feature( +... bytes_list=tf.train.BytesList(value=[b"abc", b"1234"])) +>>> +>>> example = tf.train.Example( +... features=tf.train.Features(feature={ +... 'my_ints': int_feature, +... 'my_floats': float_feature, +... 'my_bytes': bytes_feature, +... })) + +Use `tf.io.parse_example` to extract tensors from a serialized `Example` proto: + +>>> tf.io.parse_example( +... example.SerializeToString(), +... features = { +... 'my_ints': tf.io.RaggedFeature(dtype=tf.int64), +... 'my_floats': tf.io.RaggedFeature(dtype=tf.float32), +... 'my_bytes': tf.io.RaggedFeature(dtype=tf.string)}) +{'my_bytes': , + 'my_floats': , + 'my_ints': } + +""" + +FeatureList.__doc__ = """\ +Mainly used as part of a `tf.train.SequenceExample`. + +Contains a list of `tf.train.Feature`s. + +The `tf.train.SequenceExample` proto can be thought of as a +proto implementation of the following python type: + +``` +# tf.train.Feature +Feature = Union[List[bytes], + List[int64], + List[float]] + +# tf.train.FeatureList +FeatureList = List[Feature] + +# tf.train.FeatureLists +FeatureLists = Dict[str, FeatureList] + +class SequenceExample(typing.NamedTuple): + context: Dict[str, Feature] + feature_lists: FeatureLists +``` + +This proto implements the `List[Feature]` portion. + +""" + +FeatureLists.__doc__ = """\ +Mainly used as part of a `tf.train.SequenceExample`. + +Contains a list of `tf.train.Feature`s. + +The `tf.train.SequenceExample` proto can be thought of as a +proto implementation of the following python type: + +``` +# tf.train.Feature +Feature = Union[List[bytes], + List[int64], + List[float]] + +# tf.train.FeatureList +FeatureList = List[Feature] + +# tf.train.FeatureLists +FeatureLists = Dict[str, FeatureList] + +class SequenceExample(typing.NamedTuple): + context: Dict[str, Feature] + feature_lists: FeatureLists +``` + +This proto implements the `Dict[str, FeatureList]` portion. +""" + + +Example.__doc__ = """\ +An `Example` is a standard proto storing data for training and inference. + +An `Example` proto is a representation of the following python type: + +``` +Dict[str, + Union[List[bytes], + List[int64], + List[float]]] +``` + +It contains a key-value store `Example.features` where each key (string) maps +to a `tf.train.Feature` message which contains a fixed-type list. This flexible +and compact format allows the storage of large amounts of typed data, but +requires that the data shape and use be determined by the configuration files +and parsers that are used to read and write this format (refer to +`tf.io.parse_example` for details). + +>>> from google.protobuf import text_format +>>> example = text_format.Parse(''' +... features { +... feature {key: "my_feature" +... value {int64_list {value: [1, 2, 3, 4]}}} +... }''', +... tf.train.Example()) + +Use `tf.io.parse_example` to extract tensors from a serialized `Example` proto: + +>>> tf.io.parse_example( +... example.SerializeToString(), +... features = {'my_feature': tf.io.RaggedFeature(dtype=tf.int64)}) +{'my_feature': } + +While the list of keys, and the contents of each key _could_ be different for +every `Example`, TensorFlow expects a fixed list of keys, each with a fixed +`tf.dtype`. A conformant `Example` dataset obeys the following conventions: + + - If a Feature `K` exists in one example with data type `T`, it must be of + type `T` in all other examples when present. It may be omitted. + - The number of instances of Feature `K` list data may vary across examples, + depending on the requirements of the model. + - If a Feature `K` doesn't exist in an example, a `K`-specific default will be + used, if configured. + - If a Feature `K` exists in an example but contains no items, the intent + is considered to be an empty tensor and no default will be used. + +""" + +SequenceExample.__doc__ = """\ +A `SequenceExample` represents a sequence of features and some context. + +It can be thought of as a proto-implementation of the following python type: + +``` +Feature = Union[List[bytes], + List[int64], + List[float]] + +class SequenceExample(typing.NamedTuple): + context: Dict[str, Feature] + feature_lists: Dict[str, List[Feature]] +``` + +To implement this as protos it's broken up into sub-messages as follows: + +``` +# tf.train.Feature +Feature = Union[List[bytes], + List[int64], + List[float]] + +# tf.train.FeatureList +FeatureList = List[Feature] + +# tf.train.FeatureLists +FeatureLists = Dict[str, FeatureList] + +# tf.train.SequenceExample +class SequenceExample(typing.NamedTuple): + context: Dict[str, Feature] + feature_lists: FeatureLists +``` + +To parse a `SequenceExample` in TensorFlow refer to the +`tf.io.parse_sequence_example` function. + +The `context` contains features which apply to the entire +example. The `feature_lists` contain a key, value map where each key is +associated with a repeated set of `tf.train.Features` (a `tf.train.FeatureList`). +A `FeatureList` represents the values of a feature identified by its key +over time / frames. + +Below is a `SequenceExample` for a movie recommendation application recording a +sequence of ratings by a user. The time-independent features ("locale", +"age", "favorites") describing the user are part of the context. The sequence +of movies the user rated are part of the feature_lists. For each movie in the +sequence we have information on its name and actors and the user's rating. +This information is recorded in three separate `feature_list`s. +In the example below there are only two movies. All three `feature_list`s, +namely "movie_ratings", "movie_names", and "actors" have a feature value for +both movies. Note, that "actors" is itself a `bytes_list` with multiple +strings per movie. + +``` + context: { + feature: { + key : "locale" + value: { + bytes_list: { + value: [ "pt_BR" ] + } + } + } + feature: { + key : "age" + value: { + float_list: { + value: [ 19.0 ] + } + } + } + feature: { + key : "favorites" + value: { + bytes_list: { + value: [ "Majesty Rose", "Savannah Outen", "One Direction" ] + } + } + } + } + feature_lists: { + feature_list: { + key : "movie_ratings" + value: { + feature: { + float_list: { + value: [ 4.5 ] + } + } + feature: { + float_list: { + value: [ 5.0 ] + } + } + } + } + feature_list: { + key : "movie_names" + value: { + feature: { + bytes_list: { + value: [ "The Shawshank Redemption" ] + } + } + feature: { + bytes_list: { + value: [ "Fight Club" ] + } + } + } + } + feature_list: { + key : "actors" + value: { + feature: { + bytes_list: { + value: [ "Tim Robbins", "Morgan Freeman" ] + } + } + feature: { + bytes_list: { + value: [ "Brad Pitt", "Edward Norton", "Helena Bonham Carter" ] + } + } + } + } + } +``` + +A conformant `SequenceExample` data set obeys the following conventions: + +`context`: + + - All conformant context features `K` must obey the same conventions as + a conformant Example's features (see above). + +`feature_lists`: + + - A `FeatureList L` may be missing in an example; it is up to the + parser configuration to determine if this is allowed or considered + an empty list (zero length). + - If a `FeatureList L` exists, it may be empty (zero length). + - If a `FeatureList L` is non-empty, all features within the `FeatureList` + must have the same data type `T`. Even across `SequenceExample`s, the type `T` + of the `FeatureList` identified by the same key must be the same. An entry + without any values may serve as an empty feature. + - If a `FeatureList L` is non-empty, it is up to the parser configuration + to determine if all features within the `FeatureList` must + have the same size. The same holds for this `FeatureList` across multiple + examples. + - For sequence modeling ([example](https://github.com/tensorflow/nmt)), the + feature lists represent a sequence of frames. In this scenario, all + `FeatureList`s in a `SequenceExample` have the same number of `Feature` + messages, so that the i-th element in each `FeatureList` is part of the + i-th frame (or time step). + +**Examples of conformant and non-conformant examples' `FeatureLists`:** + +Conformant `FeatureLists`: + +``` + feature_lists: { feature_list: { + key: "movie_ratings" + value: { feature: { float_list: { value: [ 4.5 ] } } + feature: { float_list: { value: [ 5.0 ] } } } + } } +``` + +Non-conformant `FeatureLists` (mismatched types): + +``` + feature_lists: { feature_list: { + key: "movie_ratings" + value: { feature: { float_list: { value: [ 4.5 ] } } + feature: { int64_list: { value: [ 5 ] } } } + } } +``` + +Conditionally conformant `FeatureLists`, the parser configuration determines +if the feature sizes must match: + +``` + feature_lists: { feature_list: { + key: "movie_ratings" + value: { feature: { float_list: { value: [ 4.5 ] } } + feature: { float_list: { value: [ 5.0, 6.0 ] } } } + } } +``` + +**Examples of conformant and non-conformant `SequenceExample`s:** + +Conformant pair of SequenceExample: + +``` + feature_lists: { feature_list: { + key: "movie_ratings" + value: { feature: { float_list: { value: [ 4.5 ] } } + feature: { float_list: { value: [ 5.0 ] } } } + } } + + feature_lists: { feature_list: { + key: "movie_ratings" + value: { feature: { float_list: { value: [ 4.5 ] } } + feature: { float_list: { value: [ 5.0 ] } } + feature: { float_list: { value: [ 2.0 ] } } } + } } +``` + +Conformant pair of `SequenceExample`s: + +``` + feature_lists: { feature_list: { + key: "movie_ratings" + value: { feature: { float_list: { value: [ 4.5 ] } } + feature: { float_list: { value: [ 5.0 ] } } } + } } + + feature_lists: { feature_list: { + key: "movie_ratings" + value: { } + } } +``` + +Conditionally conformant pair of `SequenceExample`s, the parser configuration +determines if the second `feature_lists` is consistent (zero-length) or +invalid (missing "movie_ratings"): + +``` + feature_lists: { feature_list: { + key: "movie_ratings" + value: { feature: { float_list: { value: [ 4.5 ] } } + feature: { float_list: { value: [ 5.0 ] } } } + } } + + feature_lists: { } +``` + +Non-conformant pair of `SequenceExample`s (mismatched types): + +``` + feature_lists: { feature_list: { + key: "movie_ratings" + value: { feature: { float_list: { value: [ 4.5 ] } } + feature: { float_list: { value: [ 5.0 ] } } } + } } + + feature_lists: { feature_list: { + key: "movie_ratings" + value: { feature: { int64_list: { value: [ 4 ] } } + feature: { int64_list: { value: [ 5 ] } } + feature: { int64_list: { value: [ 2 ] } } } + } } +``` + +Conditionally conformant pair of `SequenceExample`s; the parser configuration +determines if the feature sizes must match: + +``` + feature_lists: { feature_list: { + key: "movie_ratings" + value: { feature: { float_list: { value: [ 4.5 ] } } + feature: { float_list: { value: [ 5.0 ] } } } + } } + + feature_lists: { feature_list: { + key: "movie_ratings" + value: { feature: { float_list: { value: [ 4.0 ] } } + feature: { float_list: { value: [ 5.0, 3.0 ] } } + } } +``` +""" diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/training_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/training_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..80a47f8aeccba28b53cf62a67c208a058a20aa3c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/training_ops.py @@ -0,0 +1,22 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""Python wrappers for training ops.""" + +from tensorflow.python.ops import gen_training_ops # pylint: disable=unused-import +# go/tf-wildcard-import +# pylint: disable=wildcard-import +from tensorflow.python.ops.gen_training_ops import * +# pylint: enable=wildcard-import diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/training_util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/training_util.py new file mode 100644 index 0000000000000000000000000000000000000000..778ad9771f8591c073833260639995568f2f69e3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/training_util.py @@ -0,0 +1,423 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Utility functions for training.""" +from tensorflow.python.eager import context +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import graph_io +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor +from tensorflow.python.ops import cond +from tensorflow.python.ops import init_ops +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.ops import state_ops +from tensorflow.python.ops import variable_scope +from tensorflow.python.ops import variable_v1 +from tensorflow.python.ops import variables +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.util.tf_export import tf_export + +# Picked a long key value to minimize the chance of collision with user defined +# collection keys. +GLOBAL_STEP_READ_KEY = 'global_step_read_op_cache' + +# TODO(drpng): remove this after legacy uses are resolved. +write_graph = graph_io.write_graph + + +@tf_export(v1=['train.global_step']) +def global_step(sess, global_step_tensor): + """Small helper to get the global step. + + ```python + # Create a variable to hold the global_step. + global_step_tensor = tf.Variable(10, trainable=False, name='global_step') + # Create a session. + sess = tf.compat.v1.Session() + # Initialize the variable + sess.run(global_step_tensor.initializer) + # Get the variable value. + print('global_step: %s' % tf.compat.v1.train.global_step(sess, + global_step_tensor)) + + global_step: 10 + ``` + + Args: + sess: A TensorFlow `Session` object. + global_step_tensor: `Tensor` or the `name` of the operation that contains + the global step. + + Returns: + The global step value. + """ + if context.executing_eagerly(): + return int(global_step_tensor.numpy()) + return int(sess.run(global_step_tensor)) + + +@tf_export(v1=['train.get_global_step']) +def get_global_step(graph=None): + """Get the global step tensor. + + The global step tensor must be an integer variable. We first try to find it + in the collection `GLOBAL_STEP`, or by name `global_step:0`. + + Args: + graph: The graph to find the global step in. If missing, use default graph. + + Returns: + The global step variable, or `None` if none was found. + + Raises: + TypeError: If the global step tensor has a non-integer type, or if it is not + a `Variable`. + + @compatibility(TF2) + With the deprecation of global graphs, TF no longer tracks variables in + collections. In other words, there are no global variables in TF2. Thus, the + global step functions have been removed (`get_or_create_global_step`, + `create_global_step`, `get_global_step`) . You have two options for migrating: + + 1. Create a Keras optimizer, which generates an `iterations` variable. This + variable is automatically incremented when calling `apply_gradients`. + 2. Manually create and increment a `tf.Variable`. + + Below is an example of migrating away from using a global step to using a + Keras optimizer: + + Define a dummy model and loss: + + >>> def compute_loss(x): + ... v = tf.Variable(3.0) + ... y = x * v + ... loss = x * 5 - x * v + ... return loss, [v] + + Before migrating: + + >>> g = tf.Graph() + >>> with g.as_default(): + ... x = tf.compat.v1.placeholder(tf.float32, []) + ... loss, var_list = compute_loss(x) + ... global_step = tf.compat.v1.train.get_or_create_global_step() + ... global_init = tf.compat.v1.global_variables_initializer() + ... optimizer = tf.compat.v1.train.GradientDescentOptimizer(0.1) + ... train_op = optimizer.minimize(loss, global_step, var_list) + >>> sess = tf.compat.v1.Session(graph=g) + >>> sess.run(global_init) + >>> print("before training:", sess.run(global_step)) + before training: 0 + >>> sess.run(train_op, feed_dict={x: 3}) + >>> print("after training:", sess.run(global_step)) + after training: 1 + + Using `get_global_step`: + + >>> with g.as_default(): + ... print(sess.run(tf.compat.v1.train.get_global_step())) + 1 + + Migrating to a Keras optimizer: + + >>> optimizer = tf.keras.optimizers.SGD(.01) + >>> print("before training:", optimizer.iterations.numpy()) + before training: 0 + >>> with tf.GradientTape() as tape: + ... loss, var_list = compute_loss(3) + ... grads = tape.gradient(loss, var_list) + ... optimizer.apply_gradients(zip(grads, var_list)) + >>> print("after training:", optimizer.iterations.numpy()) + after training: 1 + + @end_compatibility + """ + graph = graph or ops.get_default_graph() + global_step_tensor = None + global_step_tensors = graph.get_collection(ops.GraphKeys.GLOBAL_STEP) + if len(global_step_tensors) == 1: + global_step_tensor = global_step_tensors[0] + elif not global_step_tensors: + try: + global_step_tensor = graph.get_tensor_by_name('global_step:0') + except KeyError: + return None + else: + logging.error('Multiple tensors in global_step collection.') + return None + + assert_global_step(global_step_tensor) + return global_step_tensor + + +@tf_export(v1=['train.create_global_step']) +def create_global_step(graph=None): + """Create global step tensor in graph. + + Args: + graph: The graph in which to create the global step tensor. If missing, use + default graph. + + Returns: + Global step tensor. + + Raises: + ValueError: if global step tensor is already defined. + + @compatibility(TF2) + With the deprecation of global graphs, TF no longer tracks variables in + collections. In other words, there are no global variables in TF2. Thus, the + global step functions have been removed (`get_or_create_global_step`, + `create_global_step`, `get_global_step`) . You have two options for migrating: + + 1. Create a Keras optimizer, which generates an `iterations` variable. This + variable is automatically incremented when calling `apply_gradients`. + 2. Manually create and increment a `tf.Variable`. + + Below is an example of migrating away from using a global step to using a + Keras optimizer: + + Define a dummy model and loss: + + >>> def compute_loss(x): + ... v = tf.Variable(3.0) + ... y = x * v + ... loss = x * 5 - x * v + ... return loss, [v] + + Before migrating: + + >>> g = tf.Graph() + >>> with g.as_default(): + ... x = tf.compat.v1.placeholder(tf.float32, []) + ... loss, var_list = compute_loss(x) + ... global_step = tf.compat.v1.train.create_global_step() + ... global_init = tf.compat.v1.global_variables_initializer() + ... optimizer = tf.compat.v1.train.GradientDescentOptimizer(0.1) + ... train_op = optimizer.minimize(loss, global_step, var_list) + >>> sess = tf.compat.v1.Session(graph=g) + >>> sess.run(global_init) + >>> print("before training:", sess.run(global_step)) + before training: 0 + >>> sess.run(train_op, feed_dict={x: 3}) + >>> print("after training:", sess.run(global_step)) + after training: 1 + + Migrating to a Keras optimizer: + + >>> optimizer = tf.keras.optimizers.SGD(.01) + >>> print("before training:", optimizer.iterations.numpy()) + before training: 0 + >>> with tf.GradientTape() as tape: + ... loss, var_list = compute_loss(3) + ... grads = tape.gradient(loss, var_list) + ... optimizer.apply_gradients(zip(grads, var_list)) + >>> print("after training:", optimizer.iterations.numpy()) + after training: 1 + + @end_compatibility + """ + graph = graph or ops.get_default_graph() + if get_global_step(graph) is not None: + raise ValueError('"global_step" already exists.') + if context.executing_eagerly(): + with ops.device('cpu:0'): + return variable_scope.get_variable( + ops.GraphKeys.GLOBAL_STEP, + shape=[], + dtype=dtypes.int64, + initializer=init_ops.zeros_initializer(), + trainable=False, + aggregation=variables.VariableAggregation.ONLY_FIRST_REPLICA, + collections=[ + ops.GraphKeys.GLOBAL_VARIABLES, ops.GraphKeys.GLOBAL_STEP + ]) + # Create in proper graph and base name_scope. + with graph.as_default() as g, g.name_scope(None): + return variable_scope.get_variable( + ops.GraphKeys.GLOBAL_STEP, + shape=[], + dtype=dtypes.int64, + initializer=init_ops.zeros_initializer(), + trainable=False, + aggregation=variables.VariableAggregation.ONLY_FIRST_REPLICA, + collections=[ops.GraphKeys.GLOBAL_VARIABLES, ops.GraphKeys.GLOBAL_STEP]) + + +@tf_export(v1=['train.get_or_create_global_step']) +def get_or_create_global_step(graph=None): + """Returns and create (if necessary) the global step tensor. + + Args: + graph: The graph in which to create the global step tensor. If missing, use + default graph. + + Returns: + The global step tensor. + + @compatibility(TF2) + With the deprecation of global graphs, TF no longer tracks variables in + collections. In other words, there are no global variables in TF2. Thus, the + global step functions have been removed (`get_or_create_global_step`, + `create_global_step`, `get_global_step`) . You have two options for migrating: + + 1. Create a Keras optimizer, which generates an `iterations` variable. This + variable is automatically incremented when calling `apply_gradients`. + 2. Manually create and increment a `tf.Variable`. + + Below is an example of migrating away from using a global step to using a + Keras optimizer: + + Define a dummy model and loss: + + >>> def compute_loss(x): + ... v = tf.Variable(3.0) + ... y = x * v + ... loss = x * 5 - x * v + ... return loss, [v] + + Before migrating: + + >>> g = tf.Graph() + >>> with g.as_default(): + ... x = tf.compat.v1.placeholder(tf.float32, []) + ... loss, var_list = compute_loss(x) + ... global_step = tf.compat.v1.train.get_or_create_global_step() + ... global_init = tf.compat.v1.global_variables_initializer() + ... optimizer = tf.compat.v1.train.GradientDescentOptimizer(0.1) + ... train_op = optimizer.minimize(loss, global_step, var_list) + >>> sess = tf.compat.v1.Session(graph=g) + >>> sess.run(global_init) + >>> print("before training:", sess.run(global_step)) + before training: 0 + >>> sess.run(train_op, feed_dict={x: 3}) + >>> print("after training:", sess.run(global_step)) + after training: 1 + + Migrating to a Keras optimizer: + + >>> optimizer = tf.keras.optimizers.SGD(.01) + >>> print("before training:", optimizer.iterations.numpy()) + before training: 0 + >>> with tf.GradientTape() as tape: + ... loss, var_list = compute_loss(3) + ... grads = tape.gradient(loss, var_list) + ... optimizer.apply_gradients(zip(grads, var_list)) + >>> print("after training:", optimizer.iterations.numpy()) + after training: 1 + + @end_compatibility + """ + graph = graph or ops.get_default_graph() + global_step_tensor = get_global_step(graph) + if global_step_tensor is None: + global_step_tensor = create_global_step(graph) + return global_step_tensor + + +@tf_export(v1=['train.assert_global_step']) +def assert_global_step(global_step_tensor): + """Asserts `global_step_tensor` is a scalar int `Variable` or `Tensor`. + + Args: + global_step_tensor: `Tensor` to test. + """ + if not (isinstance(global_step_tensor, variables.Variable) or + isinstance(global_step_tensor, tensor.Tensor) or + resource_variable_ops.is_resource_variable(global_step_tensor)): + raise TypeError('Existing "global_step" must be a Variable or Tensor: %s.' % + global_step_tensor) + + if not global_step_tensor.dtype.base_dtype.is_integer: + raise TypeError('Existing "global_step" does not have integer type: %s' % + global_step_tensor.dtype) + + if (global_step_tensor.get_shape().ndims != 0 and + global_step_tensor.get_shape().is_fully_defined()): + raise TypeError('Existing "global_step" is not scalar: %s' % + global_step_tensor.get_shape()) + + +def _get_global_step_read(graph=None): + """Gets global step read tensor in graph. + + Args: + graph: The graph in which to create the global step read tensor. If missing, + use default graph. + + Returns: + Global step read tensor. + + Raises: + RuntimeError: if multiple items found in collection GLOBAL_STEP_READ_KEY. + """ + graph = graph or ops.get_default_graph() + global_step_read_tensors = graph.get_collection(GLOBAL_STEP_READ_KEY) + if len(global_step_read_tensors) > 1: + raise RuntimeError('There are multiple items in collection {}. ' + 'There should be only one.'.format(GLOBAL_STEP_READ_KEY)) + + if len(global_step_read_tensors) == 1: + return global_step_read_tensors[0] + return None + + +def _get_or_create_global_step_read(graph=None): + """Gets or creates global step read tensor in graph. + + Args: + graph: The graph in which to create the global step read tensor. If missing, + use default graph. + + Returns: + Global step read tensor if there is global_step_tensor else return None. + """ + graph = graph or ops.get_default_graph() + global_step_read_tensor = _get_global_step_read(graph) + if global_step_read_tensor is not None: + return global_step_read_tensor + global_step_tensor = get_global_step(graph) + if global_step_tensor is None: + return None + # add 'zero' so that it will create a copy of variable as Tensor. + with graph.as_default() as g, g.name_scope(None): + with g.name_scope(global_step_tensor.op.name + '/'): + # must ensure that global_step is initialized before + # this run. This is needed for example Estimator makes all model_fn build + # under global_step_read_tensor dependency. + if isinstance(global_step_tensor, variables.Variable): + global_step_value = cond.cond( + variable_v1.is_variable_initialized(global_step_tensor), + global_step_tensor.read_value, + lambda: global_step_tensor.initial_value) + else: + global_step_value = global_step_tensor + + global_step_read_tensor = global_step_value + 0 + ops.add_to_collection(GLOBAL_STEP_READ_KEY, global_step_read_tensor) + return _get_global_step_read(graph) + + +def _increment_global_step(increment, graph=None): + graph = graph or ops.get_default_graph() + global_step_tensor = get_global_step(graph) + if global_step_tensor is None: + raise ValueError( + 'Global step tensor should be created by ' + 'tf.train.get_or_create_global_step before calling increment.') + global_step_read_tensor = _get_or_create_global_step_read(graph) + with graph.as_default() as g, g.name_scope(None): + with g.name_scope(global_step_tensor.op.name + '/'): + with ops.control_dependencies([global_step_read_tensor]): + return state_ops.assign_add(global_step_tensor, increment) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/warm_starting_util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/warm_starting_util.py new file mode 100644 index 0000000000000000000000000000000000000000..01196b78e6097e6abd5ab3a909575baf6926a3ac --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/warm_starting_util.py @@ -0,0 +1,561 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Utilities to warm-start TF.Learn Estimators.""" + +import collections + +from tensorflow.python.framework import errors +from tensorflow.python.framework import ops +from tensorflow.python.ops import state_ops +from tensorflow.python.ops import variable_scope +from tensorflow.python.ops import variables as variables_lib +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.training import checkpoint_ops +from tensorflow.python.training import checkpoint_utils +from tensorflow.python.training import saver as saver_lib +from tensorflow.python.training.saving import saveable_object_util +from tensorflow.python.util.tf_export import tf_export + + +@tf_export(v1=["train.VocabInfo"]) +class VocabInfo( + collections.namedtuple("VocabInfo", [ + "new_vocab", + "new_vocab_size", + "num_oov_buckets", + "old_vocab", + "old_vocab_size", + "backup_initializer", + "axis", + ])): + """Vocabulary information for warm-starting. + + See `tf.estimator.WarmStartSettings` for examples of using + VocabInfo to warm-start. + + Args: + new_vocab: [Required] A path to the new vocabulary file (used with the model + to be trained). + new_vocab_size: [Required] An integer indicating how many entries of the new + vocabulary will used in training. + num_oov_buckets: [Required] An integer indicating how many OOV buckets are + associated with the vocabulary. + old_vocab: [Required] A path to the old vocabulary file (used with the + checkpoint to be warm-started from). + old_vocab_size: [Optional] An integer indicating how many entries of the old + vocabulary were used in the creation of the checkpoint. If not provided, + the entire old vocabulary will be used. + backup_initializer: [Optional] A variable initializer used for variables + corresponding to new vocabulary entries and OOV. If not provided, these + entries will be zero-initialized. + axis: [Optional] Denotes what axis the vocabulary corresponds to. The + default, 0, corresponds to the most common use case (embeddings or + linear weights for binary classification / regression). An axis of 1 + could be used for warm-starting output layers with class vocabularies. + + Returns: + A `VocabInfo` which represents the vocabulary information for warm-starting. + + Raises: + ValueError: `axis` is neither 0 or 1. + + Example Usage: +```python + embeddings_vocab_info = tf.VocabInfo( + new_vocab='embeddings_vocab', + new_vocab_size=100, + num_oov_buckets=1, + old_vocab='pretrained_embeddings_vocab', + old_vocab_size=10000, + backup_initializer=tf.compat.v1.truncated_normal_initializer( + mean=0.0, stddev=(1 / math.sqrt(embedding_dim))), + axis=0) + + softmax_output_layer_kernel_vocab_info = tf.VocabInfo( + new_vocab='class_vocab', + new_vocab_size=5, + num_oov_buckets=0, # No OOV for classes. + old_vocab='old_class_vocab', + old_vocab_size=8, + backup_initializer=tf.compat.v1.glorot_uniform_initializer(), + axis=1) + + softmax_output_layer_bias_vocab_info = tf.VocabInfo( + new_vocab='class_vocab', + new_vocab_size=5, + num_oov_buckets=0, # No OOV for classes. + old_vocab='old_class_vocab', + old_vocab_size=8, + backup_initializer=tf.compat.v1.zeros_initializer(), + axis=0) + + #Currently, only axis=0 and axis=1 are supported. + ``` + """ + + def __new__(cls, + new_vocab, + new_vocab_size, + num_oov_buckets, + old_vocab, + old_vocab_size=-1, + backup_initializer=None, + axis=0): + if axis != 0 and axis != 1: + raise ValueError("The only supported values for the axis argument are 0 " + "and 1. Provided axis: {}".format(axis)) + + return super(VocabInfo, cls).__new__( + cls, + new_vocab, + new_vocab_size, + num_oov_buckets, + old_vocab, + old_vocab_size, + backup_initializer, + axis, + ) + + +def _infer_var_name(var): + """Returns name of the `var`. + + Args: + var: A list. The list can contain either of the following: + (i) A single `Variable` + (ii) A single `ResourceVariable` + (iii) Multiple `Variable` objects which must be slices of the same larger + variable. + (iv) A single `PartitionedVariable` + + Returns: + Name of the `var` + """ + name_to_var_dict = saveable_object_util.op_list_to_dict(var) + if len(name_to_var_dict) > 1: + raise TypeError("`var` = %s passed as arg violates the constraints. " + "name_to_var_dict = %s" % (var, name_to_var_dict)) + return list(name_to_var_dict.keys())[0] + + +def _get_var_info(var, prev_tensor_name=None): + """Helper method for standarizing Variable and naming. + + Args: + var: Current graph's variable that needs to be warm-started (initialized). + Can be either of the following: (i) `Variable` (ii) `ResourceVariable` + (iii) list of `Variable`: The list must contain slices of the same larger + variable. (iv) `PartitionedVariable` + prev_tensor_name: Name of the tensor to lookup in provided `prev_ckpt`. If + None, we lookup tensor with same name as given `var`. + + Returns: + A tuple of the Tensor name and var. + """ + if checkpoint_utils._is_variable(var): # pylint: disable=protected-access + current_var_name = _infer_var_name([var]) + elif (isinstance(var, list) and + all(checkpoint_utils._is_variable(v) for v in var)): # pylint: disable=protected-access + current_var_name = _infer_var_name(var) + elif isinstance(var, variables_lib.PartitionedVariable): + current_var_name = _infer_var_name([var]) + var = var._get_variable_list() # pylint: disable=protected-access + else: + raise TypeError( + "var MUST be one of the following: a Variable, list of Variable or " + "PartitionedVariable, but is {}".format(type(var))) + if not prev_tensor_name: + # Assume tensor name remains the same. + prev_tensor_name = current_var_name + + return prev_tensor_name, var + + +# pylint: disable=protected-access +# Accesses protected members of tf.Variable to reset the variable's internal +# state. +def _warm_start_var_with_vocab(var, + current_vocab_path, + current_vocab_size, + prev_ckpt, + prev_vocab_path, + previous_vocab_size=-1, + current_oov_buckets=0, + prev_tensor_name=None, + initializer=None, + axis=0): + """Warm-starts given variable from `prev_tensor_name` tensor in `prev_ckpt`. + + Use this method when the `var` is backed by vocabulary. This method stitches + the given `var` such that values corresponding to individual features in the + vocabulary remain consistent irrespective of changing order of the features + between old and new vocabularies. + + Args: + var: Current graph's variable that needs to be warm-started (initialized). + Can be either of the following: + (i) `Variable` + (ii) `ResourceVariable` + (iii) list of `Variable`: The list must contain slices of the same larger + variable. + (iv) `PartitionedVariable` + current_vocab_path: Path to the vocab file used for the given `var`. + current_vocab_size: An `int` specifying the number of entries in the current + vocab. + prev_ckpt: A string specifying the directory with checkpoint file(s) or path + to checkpoint. The given checkpoint must have tensor with name + `prev_tensor_name` (if not None) or tensor with name same as given `var`. + prev_vocab_path: Path to the vocab file used for the tensor in `prev_ckpt`. + previous_vocab_size: If provided, will constrain previous vocab to the first + `previous_vocab_size` entries. -1 means use the entire previous vocab. + current_oov_buckets: An `int` specifying the number of out-of-vocabulary + buckets used for given `var`. + prev_tensor_name: Name of the tensor to lookup in provided `prev_ckpt`. If + None, we lookup tensor with same name as given `var`. + initializer: Variable initializer to be used for missing entries. If None, + missing entries will be zero-initialized. + axis: Axis of the variable that the provided vocabulary corresponds to. + + Raises: + ValueError: If required args are not provided. + """ + if not (current_vocab_path and current_vocab_size and prev_ckpt and + prev_vocab_path): + raise ValueError("Invalid args: Must provide all of [current_vocab_path, " + "current_vocab_size, prev_ckpt, prev_vocab_path}.") + if checkpoint_utils._is_variable(var): + var = [var] + elif (isinstance(var, list) and + all(checkpoint_utils._is_variable(v) for v in var)): + var = var + elif isinstance(var, variables_lib.PartitionedVariable): + var = var._get_variable_list() + else: + raise TypeError( + "var MUST be one of the following: a Variable, list of Variable or " + "PartitionedVariable, but is {}".format(type(var))) + + if not prev_tensor_name: + # Assume tensor name remains the same. + prev_tensor_name = _infer_var_name(var) + + total_v_first_axis = sum(v.get_shape().as_list()[0] for v in var) + for v in var: + v_shape = v.get_shape().as_list() + slice_info = v._get_save_slice_info() + partition_info = None + if slice_info: + partition_info = variable_scope._PartitionInfo( + full_shape=slice_info.full_shape, var_offset=slice_info.var_offset) + + if axis == 0: + new_row_vocab_size = current_vocab_size + new_col_vocab_size = v_shape[1] + old_row_vocab_size = previous_vocab_size + old_row_vocab_file = prev_vocab_path + new_row_vocab_file = current_vocab_path + old_col_vocab_file = None + new_col_vocab_file = None + num_row_oov_buckets = current_oov_buckets + num_col_oov_buckets = 0 + elif axis == 1: + # Note that we must compute this value across all partitions, whereas + # in the axis = 0 case, we can simply use v_shape[1] because we don't + # allow partitioning across axis = 1. + new_row_vocab_size = total_v_first_axis + new_col_vocab_size = current_vocab_size + old_row_vocab_size = -1 + old_row_vocab_file = None + new_row_vocab_file = None + old_col_vocab_file = prev_vocab_path + new_col_vocab_file = current_vocab_path + num_row_oov_buckets = 0 + num_col_oov_buckets = current_oov_buckets + else: + raise ValueError("The only supported values for the axis argument are 0 " + "and 1. Provided axis: {}".format(axis)) + + init = checkpoint_ops._load_and_remap_matrix_initializer( + ckpt_path=checkpoint_utils._get_checkpoint_filename(prev_ckpt), + old_tensor_name=prev_tensor_name, + new_row_vocab_size=new_row_vocab_size, + new_col_vocab_size=new_col_vocab_size, + old_row_vocab_size=old_row_vocab_size, + old_row_vocab_file=old_row_vocab_file, + new_row_vocab_file=new_row_vocab_file, + old_col_vocab_file=old_col_vocab_file, + new_col_vocab_file=new_col_vocab_file, + num_row_oov_buckets=num_row_oov_buckets, + num_col_oov_buckets=num_col_oov_buckets, + initializer=initializer) + new_init_val = ops.convert_to_tensor( + init(shape=v_shape, partition_info=partition_info)) + v._initializer_op = state_ops.assign(v, new_init_val) + + +# pylint: enable=protected-access + + +def _get_grouped_variables(vars_to_warm_start): + """Collects and groups (possibly partitioned) variables into a dictionary. + + The variables can be provided explicitly through vars_to_warm_start, or they + are retrieved from collections (see below). + + Args: + vars_to_warm_start: One of the following: + + - A regular expression (string) that captures which variables to + warm-start (see tf.compat.v1.get_collection). This expression will + only consider variables in the TRAINABLE_VARIABLES collection. + - A list of strings, each representing a full variable name to warm-start. + These will consider variables in GLOBAL_VARIABLES collection. + - A list of Variables to warm-start. + - `None`, in which case all variables in TRAINABLE_VARIABLES will be used. + Returns: + A dictionary mapping variable names (strings) to lists of Variables. + Raises: + ValueError: If vars_to_warm_start is not a string, `None`, a list of + `Variables`, or a list of strings. + """ + # TODO(b/143899805): Remove unicode checks when deprecating Python2. + if isinstance(vars_to_warm_start, str) or vars_to_warm_start is None: + # Both vars_to_warm_start = '.*' and vars_to_warm_start = None will match + # everything (in TRAINABLE_VARIABLES) here. + logging.info("Warm-starting variables only in TRAINABLE_VARIABLES.") + list_of_vars = ops.get_collection( + ops.GraphKeys.TRAINABLE_VARIABLES, scope=vars_to_warm_start) + elif isinstance(vars_to_warm_start, list): + if all(isinstance(v, str) for v in vars_to_warm_start): + list_of_vars = [] + for v in vars_to_warm_start: + list_of_vars += ops.get_collection( + ops.GraphKeys.GLOBAL_VARIABLES, scope=v) + elif all(checkpoint_utils._is_variable(v) for v in vars_to_warm_start): # pylint: disable=protected-access + list_of_vars = vars_to_warm_start + else: + raise ValueError("If `vars_to_warm_start` is a list, it must be all " + "`Variable` or all `str`. Given types are {}".format( + [type(v) for v in vars_to_warm_start])) + else: + raise ValueError("`vars_to_warm_start must be a `list` or `str`. Given " + "type is {}".format(type(vars_to_warm_start))) + # We have to deal with partitioned variables, since get_collection flattens + # out the list. + grouped_variables = {} + for v in list_of_vars: + t = [v] if not isinstance(v, list) else v + var_name = _infer_var_name(t) + grouped_variables.setdefault(var_name, []).append(v) + + return grouped_variables + + +def _get_object_checkpoint_renames(path, variable_names): + """Returns a dictionary mapping variable names to checkpoint keys. + + The warm-starting utility expects variable names to match with the variable + names in the checkpoint. For object-based checkpoints, the variable names + and names in the checkpoint are different. Thus, for object-based checkpoints, + this function is used to obtain the map from variable names to checkpoint + keys. + + Args: + path: path to checkpoint directory or file. + variable_names: list of variable names to load from the checkpoint. + + Returns: + If the checkpoint is object-based, this function returns a map from variable + names to their corresponding checkpoint keys. + If the checkpoint is name-based, this returns an empty dict. + + Raises: + ValueError: If the object-based checkpoint is missing variables. + """ + fname = checkpoint_utils._get_checkpoint_filename(path) # pylint: disable=protected-access + try: + names_to_keys = saver_lib.object_graph_key_mapping(fname) + except errors.NotFoundError: + # If an error is raised from `object_graph_key_mapping`, then the + # checkpoint is name-based. There are no renames, so return an empty dict. + return {} + + missing_names = set(variable_names) - set(names_to_keys.keys()) + if missing_names: + raise ValueError( + "Attempting to warm-start from an object-based checkpoint, but found " + "that the checkpoint did not contain values for all variables. The " + "following variables were missing: {}" + .format(missing_names)) + return {name: names_to_keys[name] for name in variable_names} + + +@tf_export(v1=["train.warm_start"]) +def warm_start(ckpt_to_initialize_from, + vars_to_warm_start=".*", + var_name_to_vocab_info=None, + var_name_to_prev_var_name=None): + """Warm-starts a model using the given settings. + + If you are using a tf.estimator.Estimator, this will automatically be called + during training. + + Args: + ckpt_to_initialize_from: [Required] A string specifying the directory with + checkpoint file(s) or path to checkpoint from which to warm-start the + model parameters. + vars_to_warm_start: [Optional] One of the following: + + - A regular expression (string) that captures which variables to + warm-start (see tf.compat.v1.get_collection). This expression will only + consider variables in the TRAINABLE_VARIABLES collection -- if you need + to warm-start non_TRAINABLE vars (such as optimizer accumulators or + batch norm statistics), please use the below option. + - A list of strings, each a regex scope provided to + tf.compat.v1.get_collection with GLOBAL_VARIABLES (please see + tf.compat.v1.get_collection). For backwards compatibility reasons, + this is separate from the single-string argument type. + - A list of Variables to warm-start. If you do not have access to the + `Variable` objects at the call site, please use the above option. + - `None`, in which case only TRAINABLE variables specified in + `var_name_to_vocab_info` will be warm-started. + + Defaults to `'.*'`, which warm-starts all variables in the + TRAINABLE_VARIABLES collection. Note that this excludes variables such + as accumulators and moving statistics from batch norm. + var_name_to_vocab_info: [Optional] Dict of variable names (strings) to + `tf.estimator.VocabInfo`. The variable names should be "full" variables, + not the names of the partitions. If not explicitly provided, the variable + is assumed to have no (changes to) vocabulary. + var_name_to_prev_var_name: [Optional] Dict of variable names (strings) to + name of the previously-trained variable in `ckpt_to_initialize_from`. If + not explicitly provided, the name of the variable is assumed to be same + between previous checkpoint and current model. Note that this has no + effect on the set of variables that is warm-started, and only controls + name mapping (use `vars_to_warm_start` for controlling what variables to + warm-start). + + Raises: + ValueError: If the WarmStartSettings contains prev_var_name or VocabInfo + configuration for variable names that are not used. This is to ensure + a stronger check for variable configuration than relying on users to + examine the logs. + """ + logging.info("Warm-starting from: {}".format(ckpt_to_initialize_from)) + grouped_variables = _get_grouped_variables(vars_to_warm_start) + + if var_name_to_vocab_info is None: + var_name_to_vocab_info = {} + + if not var_name_to_prev_var_name: + # Detect whether the checkpoint is object-based, in which case the + # var_name_to_prev_var_name dictionary should map variable names to + # checkpoint keys. If the user has specified var_name_to_prev_var_name, we + # do not override it. + var_name_to_prev_var_name = _get_object_checkpoint_renames( + ckpt_to_initialize_from, grouped_variables.keys()) + + warmstarted_count = 0 + + # Keep track of which var_names in var_name_to_prev_var_name and + # var_name_to_vocab_info have been used. Err on the safer side by throwing an + # exception if any are unused by the end of the loop. It is easy to misname + # a variable during this configuration, in which case without this check, we + # would fail to warm-start silently. + prev_var_name_used = set() + vocab_info_used = set() + + # Group the vocabless vars into one call to init_from_checkpoint. + vocabless_vars = {} + for var_name, variable in grouped_variables.items(): + prev_var_name = var_name_to_prev_var_name.get(var_name) + if prev_var_name: + prev_var_name_used.add(var_name) + vocab_info = var_name_to_vocab_info.get(var_name) + if vocab_info: + vocab_info_used.add(var_name) + warmstarted_count += 1 + logging.debug( + "Warm-starting variable: {}; current_vocab: {} current_vocab_size: {}" + " prev_vocab: {} prev_vocab_size: {} current_oov: {} prev_tensor: {}" + " initializer: {}".format( + var_name, vocab_info.new_vocab, vocab_info.new_vocab_size, + vocab_info.old_vocab, (vocab_info.old_vocab_size if + vocab_info.old_vocab_size > 0 else "All"), + vocab_info.num_oov_buckets, prev_var_name or "Unchanged", + vocab_info.backup_initializer or "zero-initialized")) + _warm_start_var_with_vocab( + variable, + current_vocab_path=vocab_info.new_vocab, + current_vocab_size=vocab_info.new_vocab_size, + prev_ckpt=ckpt_to_initialize_from, + prev_vocab_path=vocab_info.old_vocab, + previous_vocab_size=vocab_info.old_vocab_size, + current_oov_buckets=vocab_info.num_oov_buckets, + prev_tensor_name=prev_var_name, + initializer=vocab_info.backup_initializer, + axis=vocab_info.axis) + else: + # For the special value of vars_to_warm_start = None, + # we only warm-start variables with explicitly specified vocabularies. + if vars_to_warm_start: + warmstarted_count += 1 + logging.debug("Warm-starting variable: {}; prev_var_name: {}".format( + var_name, prev_var_name or "Unchanged")) + # Because we use a default empty list in grouped_variables, single + # unpartitioned variables will be lists here, which we rectify in order + # for init_from_checkpoint logic to work correctly. + if len(variable) == 1: + variable = variable[0] + prev_tensor_name, var = _get_var_info(variable, prev_var_name) + if prev_tensor_name in vocabless_vars: + # The API for checkpoint_utils.init_from_checkpoint accepts a mapping + # from checkpoint tensor names to model variable names, so it does not + # support warm-starting two variables from the same tensor. Our work- + # around is to run init_from_checkpoint multiple times, each time we + # encounter a new variable that should be initialized by a previously- + # used tensor. + logging.debug("Requested prev_var_name {} initialize both {} and {}; " + "calling init_from_checkpoint.".format( + prev_tensor_name, + vocabless_vars[prev_tensor_name], + var)) + checkpoint_utils.init_from_checkpoint(ckpt_to_initialize_from, + vocabless_vars) + vocabless_vars.clear() + vocabless_vars[prev_tensor_name] = var + + if vocabless_vars: + checkpoint_utils.init_from_checkpoint(ckpt_to_initialize_from, + vocabless_vars) + prev_var_name_not_used = set( + var_name_to_prev_var_name.keys()) - prev_var_name_used + vocab_info_not_used = set(var_name_to_vocab_info.keys()) - vocab_info_used + + logging.info("Warm-started %d variables.", warmstarted_count) + + if prev_var_name_not_used: + raise ValueError( + "You provided the following variables in " + "var_name_to_prev_var_name that were not used: " + "{0}. Perhaps you misspelled them? Here is the list of viable " + "variable names: {1}".format(prev_var_name_not_used, + grouped_variables.keys())) + if vocab_info_not_used: + raise ValueError( + "You provided the following variables in " + "var_name_to_vocab_info that were not used: {0}. " + " Perhaps you misspelled them? Here is the list of viable variable " + "names: {1}".format(vocab_info_not_used, grouped_variables.keys())) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/types/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/types/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..65d2db48c3dbf144d209d32b58e28c9a8e9afedb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/types/__init__.py @@ -0,0 +1,21 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Public TensorFlow type definitions. + +For details, see +https://github.com/tensorflow/community/blob/master/rfcs/20200211-tf-types.md. +""" + +# Note: this module should contain **type definitions only**. diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/types/core.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/types/core.py new file mode 100644 index 0000000000000000000000000000000000000000..16c9d24593e2ab58cec8112bae13b2c6a9e46ed5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/types/core.py @@ -0,0 +1,420 @@ +# Copyright 2020 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Core TensorFlow types.""" + +import abc +import inspect +import sys +import textwrap +from typing import Union + +import numpy as np + +from tensorflow.python.types import doc_typealias + + +from tensorflow.python import pywrap_tensorflow # pylint: disable=unused-import, g-bad-import-order +from tensorflow.python.util import _pywrap_utils +from tensorflow.python.util.tf_export import tf_export + +# pylint:disable=g-import-not-at-top +if sys.version_info >= (3, 8): + from typing import Protocol + from typing import runtime_checkable +else: + from typing_extensions import Protocol + from typing_extensions import runtime_checkable +# pylint:enable=g-import-not-at-top + +# TODO(mdan): Consider adding ABC once the dependence on isinstance is reduced. +# TODO(mdan): Add type annotations. + + +# TODO(b/178822082): Revisit this API when tf.types gets more resource. +@tf_export("__internal__.types.Tensor", v1=[]) +class Tensor(object): + """The base class of all dense Tensor objects. + + A dense tensor has a static data type (dtype), and may have a static rank and + shape. Tensor objects are immutable. Mutable objects may be backed by a Tensor + which holds the unique handle that identifies the mutable object. + """ + + @property + def dtype(self): + pass + + @property + def shape(self): + pass + + +# `ops.EagerTensor` subclasses `Symbol` by way of subclassing `tensor.Tensor`; +# care should be taken when performing `isinstance` checks on `Value`, e.g.: +# +# ``` +# if isinstance(core.Symbol) and not isinstance(core.Value): +# ... +# ``` +class Symbol(Tensor): + """Symbolic "graph" Tensor. + + These objects represent the output of an op definition and do not carry a + value. + """ + pass + + +class Value(Tensor): + """Tensor that can be associated with a value (aka "eager tensor"). + + These objects represent the (usually future) output of executing an op + immediately. + """ + + def numpy(self): + pass + + +@tf_export("types.experimental.FunctionType") +class FunctionType(inspect.Signature, metaclass=abc.ABCMeta): + """Represents the type of a TensorFlow callable. + + FunctionType inherits from inspect.Signature which canonically represents the + structure (and optionally type) information of input parameters and output of + a Python function. Additionally, it integrates with the tf.function type + system (`tf.types.experimental.TraceType`) to provide a holistic + representation of the the I/O contract of the callable. It is used for: + - Canonicalization and type-checking of Python input arguments + - Type-based dispatch to concrete functions + - Packing/unpacking structured python values to Tensors + - Generation of structured placeholder values for tracing + """ + + # The signature of this method changes in Py3.10 so we override to enforce it. + @classmethod + def from_callable(cls, obj, *, follow_wrapped=True): + return super().from_callable(obj, follow_wrapped=follow_wrapped) + + +@tf_export("types.experimental.Callable", v1=[]) +class Callable(metaclass=abc.ABCMeta): + """Base class for TF callables like those created by tf.function. + + Note: Callables are conceptually very similar to `tf.Operation`: a + `tf.Operation` is a kind of callable. + """ + + @property + @abc.abstractmethod + def function_type(self) -> FunctionType: + """Returns a FunctionType describing this callable.""" + + def __call__(self, *args, **kwargs): + """Executes this callable. + + This behaves like a regular op - in eager mode, it immediately starts + execution, returning results. In graph mode, it creates ops which return + symbolic TensorFlow values (like `tf.Tensor`, `tf.data.Dataset`, + etc.). For example, `tf.function` callables typically generate a + `tf.raw_ops.PartitionedCall` op, but not always - the + exact operations being generated are an internal implementation detail. + + Args: + *args: positional argument for this call + **kwargs: keyword arguments for this call + Returns: + The execution results. + """ + + +@tf_export("types.experimental.AtomicFunction", v1=[]) +class AtomicFunction(Callable): + """Base class for graph functions. + + An `AtomicFunction` encapsulates a single graph function definition. + + `AtomicFunction` can be called directly only if no captures are needed + according to the `FunctionType`. If captures are present, please use + `call_with_captures` instead. + + `AtomicFunction` does not support gradients. Please use the parent + `ConcreteFunction` if you need gradient support. + """ + + def call_with_captures(self, args, kwargs, captures): + """Calls this AtomicFunction with captures as defined by its FunctionType. + + Args: + args: Tuple containing positional arguments + kwargs: Dict containing keyword arguments + captures: Tuple of tensors supplying captured tensor values. + + Returns: + A structured output value based on the inputs. + """ + + +@tf_export("types.experimental.ConcreteFunction", v1=[]) +class ConcreteFunction(Callable, metaclass=abc.ABCMeta): + """Base class for differentiable graph functions. + + A `ConcreteFunction` encapsulates the original graph function definition with + support for differentiability under `tf.GradientTape` contexts. In the + process, it may generate new graph functions (using the original) to + efficiently perform forwards and backwards passes. + """ + + @property + @abc.abstractmethod + def inference_fn(self) -> AtomicFunction: + """Returns the original `AtomicFunction` owned by this ConcreteFunction.""" + + +# TODO(fmuham): Remove the export as GenericFunction in future release. +@tf_export( + "types.experimental.PolymorphicFunction", + "types.experimental.GenericFunction", # Deprecated + v1=[], +) +class PolymorphicFunction(Callable, metaclass=abc.ABCMeta): + """Base class for polymorphic graph functions. + + Graph functions are Python callable objects that dispatch calls to a + TensorFlow graph. Polymorphic graph functions can be backed by multiple TF + graphs, and automatically select the appropriate specialization based on the + type of input they were called with. They may also create specializations on + the fly if necessary, for example by tracing. + + Also see `tf.function`. + """ + + @abc.abstractmethod + def get_concrete_function(self, *args, **kwargs) -> ConcreteFunction: + """Returns a `ConcreteFunction` specialized to input types. + + The arguments specified by `args` and `kwargs` follow normal function call + rules. The returned `ConcreteFunction` has the same set of positional and + keyword arguments as `self`, but their types are compatible to the types + specified by `args` and `kwargs` (though not neccessarily equal). + + >>> @tf.function + ... def f(x): + ... return x + >>> f_concrete = f.get_concrete_function(tf.constant(1.0)) + >>> f_concrete = f.get_concrete_function(x=tf.constant(1.0)) + + Unlike normal calls, `get_concrete_function` allow type specifiers instead + of TensorFlow objects, so for example `tf.Tensor`s may be replaced with + `tf.TensorSpec`s. + + >>> @tf.function + ... def f(x): + ... return x + >>> f_concrete = f.get_concrete_function(tf.TensorSpec([], tf.float64)) + + If the function definition allows only one specialization, `args` and + `kwargs` may be omitted altogether. + + >>> @tf.function(input_signature=[tf.TensorSpec(None, tf.float32)]) + ... def f(x): + ... return x + >>> f_concrete = f.get_concrete_function() + + The returned `ConcreteFunction` can be called normally: + + >>> f_concrete(tf.constant(1.0)) + + >>> f_concrete(x=tf.constant(1.0)) + + + Args: + *args: inputs to specialize on. + **kwargs: inputs to specialize on. + + Returns: + A `ConcreteFunction`. + """ + pass + + def experimental_get_compiler_ir(self, *args, **kwargs): + """Returns compiler IR for the compiled function. + + This API is intended *only* for debugging as there are no guarantees on + backwards compatibility of returned IR or the allowed values of `stage`. + + Args: + *args: compilation args supports inputs either: (1) all inputs are + TensorSpec or (2) all inputs are tf.Tensor/Python variables. + **kwargs: Keyword arguments used for compilation. Same requirement as + compiliation args. + + Returns: + Function callable with the following kwargs: + - `stage` at which the compiler IR should be serialized. Allowed values + are: + - `hlo`: HLO output after conversion from TF + (https://www.tensorflow.org/xla/operation_semantics). + - `hlo_serialized`: Like stage=`hlo`, but the output is a serialized + HLO module proto (a bytes object). + - `optimized_hlo`: HLO after compiler optimizations. + - `optimized_hlo_serialized`: Like stage=`optimized_hlo`, but the + output is a serialized HLO module proto (a bytes object). + - `optimized_hlo_dot`: optimized HLO in DOT format suitable for + Graphviz. + - `device_name` can be either None, in which case the preferred device + is used for compilation, or a device name. It can be a full device + name, or a partial one, e.g., `/device:CPU:0`. + + For example, for + + ```python + @tf.function(jit_compile=True) + def f(x): + return x + 1 + + f.experimental_get_compiler_ir(tf.random.normal([10, 10])(stage='hlo') + ``` + + the output is: + + ``` + HloModule a_inference_f_13__.9 + + ENTRY %a_inference_f_13__.9 (arg0.1: f32[10,10]) -> f32[10,10] { + %arg0.1 = f32[10,10]{1,0} parameter(0), parameter_replication={false} + %reshape.2 = f32[10,10]{1,0} reshape(f32[10,10]{1,0} %arg0.1) + %constant.3 = f32[] constant(1) + %broadcast.4 = f32[10,10]{1,0} broadcast(f32[] %constant.3) + %add.5 = f32[10,10]{1,0} add(f32[10,10]{1,0} %reshape.2, + f32[10,10]{1,0} %broadcast.4) + %reshape.6 = f32[10,10]{1,0} reshape(f32[10,10]{1,0} %add.5) + %tuple.7 = (f32[10,10]{1,0}) tuple(f32[10,10]{1,0} %reshape.6) + ROOT %get-tuple-element.8 = f32[10,10]{1,0} + get-tuple-element((f32[10,10]{1,0}) %tuple.7), index=0 + } + ``` + + Here is another example using tf.TensorSpec inputs: + + ```python + y = tf.Variable(tf.zeros([10, 20], dtype=tf.float32)) + + @tf.function(jit_compile=True) + def f(x): + return x + y + + hlo_str = f.experimental_get_compiler_ir(tf.TensorSpec(shape=(10, + 20)))(stage='hlo') + ``` + + The output is: + + ``` + HloModule a_inference_f_120__.8, + entry_computation_layout={(f32[10,20]{1,0},f32[10,20]{1,0})->f32[10,20]{1,0}} + + ENTRY %a_inference_f_120__.8 (arg0.1: f32[10,20], arg1.2: f32[10,20]) -> + f32[10,20] { + %arg0.1 = f32[10,20]{1,0} parameter(0), parameter_replication={false}, + metadata={op_name="XLA_Args"} + %reshape.3 = f32[10,20]{1,0} reshape(f32[10,20]{1,0} %arg0.1) + %arg1.2 = f32[10,20]{1,0} parameter(1), parameter_replication={false}, + metadata={op_name="XLA_Args"} + %add.4 = f32[10,20]{1,0} add(f32[10,20]{1,0} %reshape.3, f32[10,20]{1,0} + %arg1.2), metadata={op_type="AddV2" op_name="add" + source_file="" source_line=4} + %reshape.5 = f32[10,20]{1,0} reshape(f32[10,20]{1,0} %add.4), + metadata={op_name="XLA_Retvals"} + %tuple.6 = (f32[10,20]{1,0}) tuple(f32[10,20]{1,0} %reshape.5), + metadata={op_name="XLA_Retvals"} + ROOT %get-tuple-element.7 = f32[10,20]{1,0} + get-tuple-element((f32[10,20]{1,0}) %tuple.6), index=0, + metadata={op_name="XLA_Retvals"} + } + ``` + + The HLO module accepts a flat list of inputs. To retrieve the order + of these inputs signatures, users can call the + `concrete_fn.structured_input_signature` and `concrete_fn.captured_inputs`: + + ```python + # Use concrete_fn to get the hlo_module flat_args. + concrete_fn = f.get_concrete_function(tf.TensorSpec(shape=(10, 20))) + flat_args = list( + tf.nest.flatten(concrete_fn.structured_input_signature) + ) + concrete_fn.captured_inputs + ``` + + Raises: + ValueError: + (1) If an invalid `stage` is selected + (2) or if applied to a function which is not compiled + (`jit_compile=True` is not set). + (3) or if input shapes are not fully defined for tf.TensorSpec inputs + TypeError: When called with input in graph mode. + """ + pass + + +@runtime_checkable +class TensorProtocol(Protocol): + """Protocol type for objects that can be converted to Tensor.""" + + def __tf_tensor__(self, dtype=None, name=None): + """Converts this object to a Tensor. + + Args: + dtype: data type for the returned Tensor + name: a name for the operations which create the Tensor + Returns: + A Tensor. + """ + pass + + +_pywrap_utils.RegisterType("TensorProtocol", TensorProtocol) +_pywrap_utils.RegisterType("CoreTypeValue", Value) + + +# TODO(rahulkamat): Add missing types that are convertible to Tensor. +TensorLike = Union[Tensor, TensorProtocol, int, float, bool, str, bytes, + complex, tuple, list, np.ndarray, np.generic] +doc_typealias.document( + obj=TensorLike, + doc=textwrap.dedent("""\ + Union of all types that can be converted to a `tf.Tensor` by `tf.convert_to_tensor`. + + This definition may be used in user code. Additional types may be added + in the future as more input types are supported. + + Example: + + ``` + def foo(x: TensorLike): + pass + ``` + + This definition passes static type verification for: + + ``` + foo(tf.constant([1, 2, 3])) + foo([1, 2, 3]) + foo(np.array([1, 2, 3])) + ``` + """), +) +tf_export("types.experimental.TensorLike").export_constant( + __name__, "TensorLike") diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/types/data.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/types/data.py new file mode 100644 index 0000000000000000000000000000000000000000..59c09001086ef3b967fe290a9850525978352991 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/types/data.py @@ -0,0 +1,29 @@ +# Copyright 2023 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Dataset types.""" + +import abc + +from tensorflow.python.util.tf_export import tf_export + + +@tf_export("__internal__.types.data.Dataset", v1=[]) +class DatasetV2(abc.ABC): + """Represents the TensorFlow 2 type `tf.data.Dataset`.""" + + +@tf_export(v1=["__internal__.types.data.Dataset"]) +class DatasetV1(DatasetV2, abc.ABC): + """Represents the TensorFlow 1 type `tf.data.Dataset`.""" diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/types/distribute.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/types/distribute.py new file mode 100644 index 0000000000000000000000000000000000000000..00ba6c9a9c8379dbcfa3c9ea74b63bf1e352b24b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/types/distribute.py @@ -0,0 +1,508 @@ +# Copyright 2020 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Types specific to tf.distribute.""" + +from tensorflow.python.util.tf_export import tf_export +from tensorflow.tools.docs import doc_controls + +# TODO(mdan, anjalisridhar): Decide the location of this file. + + +class Iterable(object): + """Interface for distributed objects that admit iteration/reduction.""" + + def __iter__(self): + pass + + # TODO(mdan): Describe this contract. + def reduce(self, initial_state, reduce_func): + """Reduces this iterable object to a single element. + + The transformation calls `reduce_func` successively on each element. + The `initial_state` argument is used for the initial state and the final + state is returned as the result. + + Args: + initial_state: An element representing the initial state of the + reduction. + reduce_func: A function that maps `(old_state, input_element)` to + `new_state`. The structure of `new_state` must match the structure of + `old_state`. For the first element, `old_state` is `initial_state`. + + Returns: + The final state of the transformation. + """ + + +class Iterator(object): + """Interface for distributed iterators.""" + + def get_next(self): + """Unlike __next__, this may use a non-raising mechanism.""" + + def __next__(self): + pass + + def __iter__(self): + pass + + +@tf_export("distribute.DistributedValues", v1=[]) +class DistributedValues(object): + """Base class for representing distributed values. + + A subclass instance of `tf.distribute.DistributedValues` is created when + creating variables within a distribution strategy, iterating a + `tf.distribute.DistributedDataset` or through `tf.distribute.Strategy.run`. + This base class should never be instantiated directly. + `tf.distribute.DistributedValues` contains a value per replica. Depending on + the subclass, the values could either be synced on update, synced on demand, + or never synced. + + Two representative types of `tf.distribute.DistributedValues` are + `tf.types.experimental.PerReplica` and `tf.types.experimental.Mirrored` + values. + + `PerReplica` values exist on the worker devices, with a different value for + each replica. They are produced by iterating through a distributed dataset + returned by `tf.distribute.Strategy.experimental_distribute_dataset` (Example + 1, below) and `tf.distribute.Strategy.distribute_datasets_from_function`. They + are also the typical result returned by `tf.distribute.Strategy.run` (Example + 2). + + `Mirrored` values are like `PerReplica` values, except we know that the value + on all replicas are the same. `Mirrored` values are kept synchronized by the + distribution strategy in use, while `PerReplica` values are left + unsynchronized. `Mirrored` values typically represent model weights. We can + safely read a `Mirrored` value in a cross-replica context by using the value + on any replica, while PerReplica values should not be read or manipulated in + a cross-replica context." + + `tf.distribute.DistributedValues` can be reduced via `strategy.reduce` to + obtain a single value across replicas (Example 4), used as input into + `tf.distribute.Strategy.run` (Example 3), or collected to inspect the + per-replica values using `tf.distribute.Strategy.experimental_local_results` + (Example 5). + + Example usages: + + 1. Created from a `tf.distribute.DistributedDataset`: + + >>> strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"]) + >>> dataset = tf.data.Dataset.from_tensor_slices([5., 6., 7., 8.]).batch(2) + >>> dataset_iterator = iter(strategy.experimental_distribute_dataset(dataset)) + >>> distributed_values = next(dataset_iterator) + >>> distributed_values + PerReplica:{ + 0: , + 1: + } + + 2. Returned by `run`: + + >>> strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"]) + >>> @tf.function + ... def run(): + ... ctx = tf.distribute.get_replica_context() + ... return ctx.replica_id_in_sync_group + >>> distributed_values = strategy.run(run) + >>> distributed_values + PerReplica:{ + 0: , + 1: + } + + 3. As input into `run`: + + >>> strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"]) + >>> dataset = tf.data.Dataset.from_tensor_slices([5., 6., 7., 8.]).batch(2) + >>> dataset_iterator = iter(strategy.experimental_distribute_dataset(dataset)) + >>> distributed_values = next(dataset_iterator) + >>> @tf.function + ... def run(input): + ... return input + 1.0 + >>> updated_value = strategy.run(run, args=(distributed_values,)) + >>> updated_value + PerReplica:{ + 0: , + 1: + } + + 4. As input into `reduce`: + + >>> strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"]) + >>> dataset = tf.data.Dataset.from_tensor_slices([5., 6., 7., 8.]).batch(2) + >>> dataset_iterator = iter(strategy.experimental_distribute_dataset(dataset)) + >>> distributed_values = next(dataset_iterator) + >>> reduced_value = strategy.reduce(tf.distribute.ReduceOp.SUM, + ... distributed_values, + ... axis = 0) + >>> reduced_value + + + 5. How to inspect per-replica values locally: + + >>> strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"]) + >>> dataset = tf.data.Dataset.from_tensor_slices([5., 6., 7., 8.]).batch(2) + >>> dataset_iterator = iter(strategy.experimental_distribute_dataset(dataset)) + >>> per_replica_values = strategy.experimental_local_results( + ... distributed_values) + >>> per_replica_values + (, + ) + + """ + + +@tf_export("types.experimental.distributed.PerReplica", v1=[]) +class PerReplica(DistributedValues): + """Holds a distributed value: a map from replica id to unsynchronized values. + + `PerReplica` values exist on the worker devices, with a different value for + each replica. They can be produced many ways, often by iterating through a + distributed dataset returned by + `tf.distribute.Strategy.experimental_distribute_dataset` and + `tf.distribute.Strategy.distribute_datasets_from_function`. They are also the + typical result returned by `tf.distribute.Strategy.run`. + """ + + +@tf_export("types.experimental.distributed.Mirrored", v1=[]) +class Mirrored(DistributedValues): + """Holds a distributed value: a map from replica id to synchronized values. + + `Mirrored` values are `tf.distribute.DistributedValues` for which we know that + the value on all replicas is the same. `Mirrored` values are kept synchronized + by the distribution strategy in use, while `tf.types.experimental.PerReplica` + values are left unsynchronized. `Mirrored` values typically represent model + weights. We can safely read a `Mirrored` value in a cross-replica context by + using the value on any replica, while `PerReplica` values should not be read + or manipulated directly by the user in a cross-replica context. + """ + + +@tf_export("distribute.DistributedIterator", v1=[]) +class DistributedIteratorInterface(Iterator): + """An iterator over `tf.distribute.DistributedDataset`. + + `tf.distribute.DistributedIterator` is the primary mechanism for enumerating + elements of a `tf.distribute.DistributedDataset`. It supports the Python + Iterator protocol, which means it can be iterated over using a for-loop or by + fetching individual elements explicitly via `get_next()`. + + You can create a `tf.distribute.DistributedIterator` by calling `iter` on + a `tf.distribute.DistributedDataset` or creating a python loop over a + `tf.distribute.DistributedDataset`. + + Visit the [tutorial](https://www.tensorflow.org/tutorials/distribute/input) + on distributed input for more examples and caveats. + """ + + def get_next(self): + """Returns the next input from the iterator for all replicas. + + Example use: + + >>> strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"]) + >>> dataset = tf.data.Dataset.range(100).batch(2) + >>> dist_dataset = strategy.experimental_distribute_dataset(dataset) + >>> dist_dataset_iterator = iter(dist_dataset) + >>> @tf.function + ... def one_step(input): + ... return input + >>> step_num = 5 + >>> for _ in range(step_num): + ... strategy.run(one_step, args=(dist_dataset_iterator.get_next(),)) + >>> strategy.experimental_local_results(dist_dataset_iterator.get_next()) + (, + ) + + Returns: + A single `tf.Tensor` or a `tf.distribute.DistributedValues` which contains + the next input for all replicas. + + Raises: + `tf.errors.OutOfRangeError`: If the end of the iterator has been reached. + """ + raise NotImplementedError( + "DistributedIterator.get_next() must be implemented in descendants.") + + @property + def element_spec(self): + # pylint: disable=line-too-long + """The type specification of an element of `tf.distribute.DistributedIterator`. + + Example usage: + + >>> global_batch_size = 16 + >>> strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"]) + >>> dataset = tf.data.Dataset.from_tensors(([1.],[2])).repeat(100).batch(global_batch_size) + >>> distributed_iterator = iter(strategy.experimental_distribute_dataset(dataset)) + >>> distributed_iterator.element_spec + (PerReplicaSpec(TensorSpec(shape=(None, 1), dtype=tf.float32, name=None), + TensorSpec(shape=(None, 1), dtype=tf.float32, name=None)), + PerReplicaSpec(TensorSpec(shape=(None, 1), dtype=tf.int32, name=None), + TensorSpec(shape=(None, 1), dtype=tf.int32, name=None))) + + Returns: + A nested structure of `tf.TypeSpec` objects matching the structure of an + element of this `tf.distribute.DistributedIterator`. This returned value + is typically a `tf.distribute.DistributedValues` object and specifies the + `tf.TensorSpec` of individual components. + """ + raise NotImplementedError( + "DistributedIterator.element_spec() must be implemented in descendants") + + def get_next_as_optional(self): + # pylint: disable=line-too-long + """Returns a `tf.experimental.Optional` that contains the next value for all replicas. + + If the `tf.distribute.DistributedIterator` has reached the end of the + sequence, the returned `tf.experimental.Optional` will have no value. + + Example usage: + + >>> strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"]) + >>> global_batch_size = 2 + >>> steps_per_loop = 2 + >>> dataset = tf.data.Dataset.range(10).batch(global_batch_size) + >>> distributed_iterator = iter( + ... strategy.experimental_distribute_dataset(dataset)) + >>> def step_fn(x): + ... # train the model with inputs + ... return x + >>> @tf.function + ... def train_fn(distributed_iterator): + ... for _ in tf.range(steps_per_loop): + ... optional_data = distributed_iterator.get_next_as_optional() + ... if not optional_data.has_value(): + ... break + ... per_replica_results = strategy.run(step_fn, args=(optional_data.get_value(),)) + ... tf.print(strategy.experimental_local_results(per_replica_results)) + >>> train_fn(distributed_iterator) + ... # ([0 1], [2 3]) + ... # ([4], []) + + Returns: + An `tf.experimental.Optional` object representing the next value from the + `tf.distribute.DistributedIterator` (if it has one) or no value. + """ + # pylint: enable=line-too-long + raise NotImplementedError( + "get_next_as_optional() not implemented in descendants") + + +@tf_export("distribute.DistributedDataset", v1=[]) +class DistributedDatasetInterface(Iterable): + # pylint: disable=line-too-long + """Represents a dataset distributed among devices and machines. + + A `tf.distribute.DistributedDataset` could be thought of as a "distributed" + dataset. When you use `tf.distribute` API to scale training to multiple + devices or machines, you also need to distribute the input data, which leads + to a `tf.distribute.DistributedDataset` instance, instead of a + `tf.data.Dataset` instance in the non-distributed case. In TF 2.x, + `tf.distribute.DistributedDataset` objects are Python iterables. + + Note: `tf.distribute.DistributedDataset` instances are *not* of type + `tf.data.Dataset`. It only supports two usages we will mention below: + iteration and `element_spec`. We don't support any other APIs to transform or + inspect the dataset. + + There are two APIs to create a `tf.distribute.DistributedDataset` object: + `tf.distribute.Strategy.experimental_distribute_dataset(dataset)`and + `tf.distribute.Strategy.distribute_datasets_from_function(dataset_fn)`. + *When to use which?* When you have a `tf.data.Dataset` instance, and the + regular batch splitting (i.e. re-batch the input `tf.data.Dataset` instance + with a new batch size that is equal to the global batch size divided by the + number of replicas in sync) and autosharding (i.e. the + `tf.data.experimental.AutoShardPolicy` options) work for you, use the former + API. Otherwise, if you are *not* using a canonical `tf.data.Dataset` instance, + or you would like to customize the batch splitting or sharding, you can wrap + these logic in a `dataset_fn` and use the latter API. Both API handles + prefetch to device for the user. For more details and examples, follow the + links to the APIs. + + + There are two main usages of a `DistributedDataset` object: + + 1. Iterate over it to generate the input for a single device or multiple + devices, which is a `tf.distribute.DistributedValues` instance. To do this, + you can: + + * use a pythonic for-loop construct: + + >>> global_batch_size = 4 + >>> strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"]) + >>> dataset = tf.data.Dataset.from_tensors(([1.],[1.])).repeat(4).batch(global_batch_size) + >>> dist_dataset = strategy.experimental_distribute_dataset(dataset) + >>> @tf.function + ... def train_step(input): + ... features, labels = input + ... return labels - 0.3 * features + >>> for x in dist_dataset: + ... # train_step trains the model using the dataset elements + ... loss = strategy.run(train_step, args=(x,)) + ... print("Loss is", loss) + Loss is PerReplica:{ + 0: tf.Tensor( + [[0.7] + [0.7]], shape=(2, 1), dtype=float32), + 1: tf.Tensor( + [[0.7] + [0.7]], shape=(2, 1), dtype=float32) + } + + Placing the loop inside a `tf.function` will give a performance boost. + However `break` and `return` are currently not supported if the loop is + placed inside a `tf.function`. We also don't support placing the loop + inside a `tf.function` when using + `tf.distribute.experimental.MultiWorkerMirroredStrategy` or + `tf.distribute.experimental.TPUStrategy` with multiple workers. + + * use `__iter__` to create an explicit iterator, which is of type + `tf.distribute.DistributedIterator` + + >>> global_batch_size = 4 + >>> strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"]) + >>> train_dataset = tf.data.Dataset.from_tensors(([1.],[1.])).repeat(50).batch(global_batch_size) + >>> train_dist_dataset = strategy.experimental_distribute_dataset(train_dataset) + >>> @tf.function + ... def distributed_train_step(dataset_inputs): + ... def train_step(input): + ... loss = tf.constant(0.1) + ... return loss + ... per_replica_losses = strategy.run(train_step, args=(dataset_inputs,)) + ... return strategy.reduce(tf.distribute.ReduceOp.SUM, per_replica_losses,axis=None) + >>> EPOCHS = 2 + >>> STEPS = 3 + >>> for epoch in range(EPOCHS): + ... total_loss = 0.0 + ... num_batches = 0 + ... dist_dataset_iterator = iter(train_dist_dataset) + ... for _ in range(STEPS): + ... total_loss += distributed_train_step(next(dist_dataset_iterator)) + ... num_batches += 1 + ... average_train_loss = total_loss / num_batches + ... template = ("Epoch {}, Loss: {:.4f}") + ... print (template.format(epoch+1, average_train_loss)) + Epoch 1, Loss: 0.2000 + Epoch 2, Loss: 0.2000 + + + To achieve a performance improvement, you can also wrap the `strategy.run` + call with a `tf.range` inside a `tf.function`. This runs multiple steps in a + `tf.function`. Autograph will convert it to a `tf.while_loop` on the worker. + However, it is less flexible comparing with running a single step inside + `tf.function`. For example, you cannot run things eagerly or arbitrary + python code within the steps. + + + 2. Inspect the `tf.TypeSpec` of the data generated by `DistributedDataset`. + + `tf.distribute.DistributedDataset` generates + `tf.distribute.DistributedValues` as input to the devices. If you pass the + input to a `tf.function` and would like to specify the shape and type of + each Tensor argument to the function, you can pass a `tf.TypeSpec` object to + the `input_signature` argument of the `tf.function`. To get the + `tf.TypeSpec` of the input, you can use the `element_spec` property of the + `tf.distribute.DistributedDataset` or `tf.distribute.DistributedIterator` + object. + + For example: + + >>> global_batch_size = 4 + >>> epochs = 1 + >>> steps_per_epoch = 1 + >>> mirrored_strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"]) + >>> dataset = tf.data.Dataset.from_tensors(([2.])).repeat(100).batch(global_batch_size) + >>> dist_dataset = mirrored_strategy.experimental_distribute_dataset(dataset) + >>> @tf.function(input_signature=[dist_dataset.element_spec]) + ... def train_step(per_replica_inputs): + ... def step_fn(inputs): + ... return tf.square(inputs) + ... return mirrored_strategy.run(step_fn, args=(per_replica_inputs,)) + >>> for _ in range(epochs): + ... iterator = iter(dist_dataset) + ... for _ in range(steps_per_epoch): + ... output = train_step(next(iterator)) + ... print(output) + PerReplica:{ + 0: tf.Tensor( + [[4.] + [4.]], shape=(2, 1), dtype=float32), + 1: tf.Tensor( + [[4.] + [4.]], shape=(2, 1), dtype=float32) + } + + + Visit the [tutorial](https://www.tensorflow.org/tutorials/distribute/input) + on distributed input for more examples and caveats. + """ + + def __iter__(self): + """Creates an iterator for the `tf.distribute.DistributedDataset`. + + The returned iterator implements the Python Iterator protocol. + + Example usage: + + >>> global_batch_size = 4 + >>> strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"]) + >>> dataset = tf.data.Dataset.from_tensor_slices([1, 2, 3, 4]).repeat().batch(global_batch_size) + >>> distributed_iterator = iter(strategy.experimental_distribute_dataset(dataset)) + >>> print(next(distributed_iterator)) + PerReplica:{ + 0: tf.Tensor([1 2], shape=(2,), dtype=int32), + 1: tf.Tensor([3 4], shape=(2,), dtype=int32) + } + + Returns: + An `tf.distribute.DistributedIterator` instance for the given + `tf.distribute.DistributedDataset` object to enumerate over the + distributed data. + """ + raise NotImplementedError("Must be implemented in descendants") + + @property + def element_spec(self): + """The type specification of an element of this `tf.distribute.DistributedDataset`. + + Example usage: + + >>> global_batch_size = 16 + >>> strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"]) + >>> dataset = tf.data.Dataset.from_tensors(([1.],[2])).repeat(100).batch(global_batch_size) + >>> dist_dataset = strategy.experimental_distribute_dataset(dataset) + >>> dist_dataset.element_spec + (PerReplicaSpec(TensorSpec(shape=(None, 1), dtype=tf.float32, name=None), + TensorSpec(shape=(None, 1), dtype=tf.float32, name=None)), + PerReplicaSpec(TensorSpec(shape=(None, 1), dtype=tf.int32, name=None), + TensorSpec(shape=(None, 1), dtype=tf.int32, name=None))) + + Returns: + A nested structure of `tf.TypeSpec` objects matching the structure of an + element of this `tf.distribute.DistributedDataset`. This returned value is + typically a `tf.distribute.DistributedValues` object and specifies the + `tf.TensorSpec` of individual components. + """ + raise NotImplementedError( + "DistributedDataset.element_spec must be implemented in descendants.") + + @doc_controls.do_not_generate_docs + def reduce(self, initial_state, reduce_func): + raise NotImplementedError( + "DistributedDataset.reduce must be implemented in descendants.") diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/types/doc_typealias.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/types/doc_typealias.py new file mode 100644 index 0000000000000000000000000000000000000000..43a1d9dc6dd7bcb090e33a5fc1566ccd455bd4c2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/types/doc_typealias.py @@ -0,0 +1,37 @@ +# Copyright 2020 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Helper functions to add documentation to type aliases.""" + +from typing import Dict + +# Not useful for builtin `help()`. But these get passed to the +# doc generator so that the description is still displayed on the site. +_EXTRA_DOCS: Dict[int, str] = {} + + +def document(obj, doc): + """Adds a docstring to typealias by overriding the `__doc__` attribute. + + Note: Overriding `__doc__` is only possible after python 3.7. + + Args: + obj: Typealias object that needs to be documented. + doc: Docstring of the typealias. It should follow the standard pystyle + docstring rules. + """ + try: + obj.__doc__ = doc + except AttributeError: + _EXTRA_DOCS[id(obj)] = doc diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/types/internal.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/types/internal.py new file mode 100644 index 0000000000000000000000000000000000000000..b600078c7439cc4c4ad525131081b29e8d1dd3ec --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/types/internal.py @@ -0,0 +1,61 @@ +# Copyright 2020 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Types internal to TensorFlow. + +These types should not be exported. External code should not rely on these. +""" + + +# TODO(mdan): Is this strictly needed? Only ops.py really uses it. +class NativeObject(object): + """Types natively supported by various TF operations. + + The most notable example of NativeObject is Tensor. + """ + + +class TypeSpec(object): + """Interface for internal isinstance checks to framework/type_spec.py. + + This helps to avoid circular dependencies. + """ + + +class TensorSpec(object): + """Interface for internal isinstance checks to framework/tensor_spec.py. + + This helps to avoid circular dependencies. + """ + + +class IndexedSlices(object): + """Interface for internal isinstance checks to framework/indexed_slices.py. + + This helps to avoid circular dependencies. + """ + + +class RaggedTensor(object): + """Interface for internal isinstance checks to ops/ragged/ragged_tensor.py. + + This helps to avoid circular dependencies. + """ + + +class RaggedTensorSpec(object): + """Interface for internal isinstance checks to ops/ragged/ragged_tensor.py. + + This helps to avoid circular dependencies. + """ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/types/trace.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/types/trace.py new file mode 100644 index 0000000000000000000000000000000000000000..e47a0c0f0536019e5f3a7afd4b93ad2957c0d09b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/types/trace.py @@ -0,0 +1,309 @@ +# Copyright 2021 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""tf.function tracing types. + +See `core.PolymorphicFunction` and `core.ConcreteFunction`. + +`PolymorphicFunction` assigns types to call arguments, forming a signature. +Function signatures are used to match arguments to `ConcreteFunction`s. +For example, when a new `ConcreteFunction` is traced, it is assigned a +the signature of the arguments it was traced with. Subsequent call arguments +which match its signature will be dispatched to the same `ConcreteFunction`. +If no `ConcreteFunction` with a matching signature is found, a new one may be +traced (a process known as retracing). +""" + +import abc +from typing import Any, Iterator, List, Optional, Sequence + +from typing_extensions import Protocol +from typing_extensions import runtime_checkable + +from tensorflow.python.types import core +from tensorflow.python.util.tf_export import tf_export +from tensorflow.tools.docs import doc_controls + + +@tf_export("types.experimental.TraceType", v1=[]) +class TraceType(metaclass=abc.ABCMeta): + """Represents the type of object(s) for tf.function tracing purposes. + + `TraceType` is an abstract class that other classes might inherit from to + provide information regarding associated class(es) for the purposes of + tf.function tracing. The typing logic provided through this mechanism will be + used to make decisions regarding usage of cached concrete functions and + retracing. + + For example, if we have the following tf.function and classes: + ```python + @tf.function + def get_mixed_flavor(fruit_a, fruit_b): + return fruit_a.flavor + fruit_b.flavor + + class Fruit: + flavor = tf.constant([0, 0]) + + class Apple(Fruit): + flavor = tf.constant([1, 2]) + + class Mango(Fruit): + flavor = tf.constant([3, 4]) + ``` + + tf.function does not know when to re-use an existing concrete function in + regards to the `Fruit` class so naively it retraces for every new instance. + ```python + get_mixed_flavor(Apple(), Mango()) # Traces a new concrete function + get_mixed_flavor(Apple(), Mango()) # Traces a new concrete function again + ``` + + However, we, as the designers of the `Fruit` class, know that each subclass + has a fixed flavor and we can reuse an existing traced concrete function if + it was the same subclass. Avoiding such unnecessary tracing of concrete + functions can have significant performance benefits. + + ```python + class FruitTraceType(tf.types.experimental.TraceType): + def __init__(self, fruit): + self.fruit_type = type(fruit) + self.fruit_value = fruit + + def is_subtype_of(self, other): + return (type(other) is FruitTraceType and + self.fruit_type is other.fruit_type) + + def most_specific_common_supertype(self, others): + return self if all(self == other for other in others) else None + + def placeholder_value(self, placeholder_context=None): + return self.fruit_value + + class Fruit: + + def __tf_tracing_type__(self, context): + return FruitTraceType(self) + ``` + + Now if we try calling it again: + ```python + get_mixed_flavor(Apple(), Mango()) # Traces a new concrete function + get_mixed_flavor(Apple(), Mango()) # Re-uses the traced concrete function + ``` + """ + + @abc.abstractmethod + def is_subtype_of(self, other: "TraceType") -> bool: + """Returns True if `self` is a subtype of `other`. + + For example, `tf.function` uses subtyping for dispatch: + if `a.is_subtype_of(b)` is True, then an argument of `TraceType` + `a` can be used as argument to a `ConcreteFunction` traced with an + a `TraceType` `b`. + + Args: + other: A TraceType object to be compared against. + + Example: + + ```python + class Dimension(TraceType): + def __init__(self, value: Optional[int]): + self.value = value + + def is_subtype_of(self, other): + # Either the value is the same or other has a generalized value that + # can represent any specific ones. + return (self.value == other.value) or (other.value is None) + ``` + """ + + @abc.abstractmethod + def most_specific_common_supertype( + self, others: Sequence["TraceType"] + ) -> Optional["TraceType"]: + """Returns the most specific supertype of `self` and `others`, if exists. + + The returned `TraceType` is a supertype of `self` and `others`, that is, + they are all subtypes (see `is_subtype_of`) of it. + It is also most specific, that is, there it has no subtype that is also + a common supertype of `self` and `others`. + + If `self` and `others` have no common supertype, this returns `None`. + + Args: + others: A sequence of TraceTypes. + + Example: + ```python + class Dimension(TraceType): + def __init__(self, value: Optional[int]): + self.value = value + + def most_specific_common_supertype(self, other): + # Either the value is the same or other has a generalized value that + # can represent any specific ones. + if self.value == other.value: + return self.value + else: + return Dimension(None) + ``` + """ + + @abc.abstractmethod + def placeholder_value(self, placeholder_context) -> Any: + """Creates a placeholder for tracing. + + tf.funcion traces with the placeholder value rather than the actual value. + For example, a placeholder value can represent multiple different + actual values. This means that the trace generated with that placeholder + value is more general and reusable which saves expensive retracing. + + Args: + placeholder_context: A context reserved for internal/future usage. + For the `Fruit` example shared above, implementing: + + ```python + class FruitTraceType: + def placeholder_value(self, placeholder_context): + return Fruit() + ``` + instructs tf.function to trace with the `Fruit()` objects + instead of the actual `Apple()` and `Mango()` objects when it receives a + call to `get_mixed_flavor(Apple(), Mango())`. For example, Tensor arguments + are replaced with Tensors of similar shape and dtype, output from + a tf.Placeholder op. + + More generally, placeholder values are the arguments of a tf.function, + as seen from the function's body: + ```python + @tf.function + def foo(x): + # Here `x` is be the placeholder value + ... + + foo(x) # Here `x` is the actual value + ``` + """ + + def to_tensors(self, value: Any) -> List[core.Tensor]: + """Breaks down a value of this type into Tensors. + + For a TraceType instance, the number of tensors generated for corresponding + value should be constant. + + Args: + value: A value belonging to this TraceType + + Returns: + List of Tensors. + """ + del value + return [] + + def from_tensors(self, tensors: Iterator[core.Tensor]) -> Any: + """Generates a value of this type from Tensors. + + Must use the same fixed amount of tensors as `to_tensors`. + + Args: + tensors: An iterator from which the tensors can be pulled. + + Returns: + A value of this type. + """ + del tensors + return self.placeholder_value(PlaceholderContext()) + + def flatten(self) -> List["TraceType"]: + """Returns a list of TensorSpecs corresponding to `to_tensors` values.""" + return [] + + def cast(self, value, cast_context) -> Any: + """Cast value to this type. + + Args: + value: An input value belonging to this TraceType. + cast_context: A context reserved for internal/future usage. + + Returns: + The value casted to this TraceType. + + Raises: + AssertionError: When _cast is not overloaded in subclass, + the value is returned directly, and it should be the same to + self.placeholder_value(). + """ + del cast_context + assert value == self.placeholder_value( + PlaceholderContext()), f"Can not cast {value!r} to type {self!r}" + return value + + @abc.abstractmethod + def __hash__(self) -> int: + pass + + @abc.abstractmethod + def __eq__(self, other) -> bool: + pass + + +class TracingContext(metaclass=abc.ABCMeta): + """Contains information scoped to the tracing of multiple objects. + + `TracingContext` is a container class for flags and variables that have + any kind of influence on the tracing behaviour of the class implementing + the __tf_tracing_type__. This context will be shared across all + __tf_tracing_type__ calls while constructing the TraceType for a particular + set of objects. + """ + + +class PlaceholderContext(): + """Contains context information for generating placeholders within a scope.""" + + +class CastContext(): + """Contains context info and rules for casting values to a TypeSpec.""" + + +@runtime_checkable +class SupportsTracingProtocol(Protocol): + """A protocol allowing custom classes to control tf.function retracing.""" + + @doc_controls.doc_private + @abc.abstractmethod + def __tf_tracing_type__(self, context: TracingContext) -> TraceType: + """Returns the tracing type of this object. + + The tracing type is used to build the signature of a tf.function + when traced, and to match arguments with existing signatures. + When a Function object is called, tf.function looks at the tracing type + of the call arguments. If an existing signature of matching type exists, + it will be used. Otherwise, a new function is traced, and its signature + will use the tracing type of the call arguments. + + Args: + context: a context reserved for internal/future usage. + + Returns: + The tracing type of this object. + """ + + +# TODO(b/219556836): Direct tf_export decorator adds non-method members to the +# Protocol which breaks @runtime_checkable since it does not support them. +tf_export("types.experimental.SupportsTracingProtocol", v1=[]).export_constant( + __name__, "SupportsTracingProtocol" +) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/user_ops/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/user_ops/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/user_ops/ops/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/user_ops/ops/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/user_ops/ops/gen_user_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/user_ops/ops/gen_user_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..14612df2a34eba48a4545c8c1a1de07ac5ae6039 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/user_ops/ops/gen_user_ops.py @@ -0,0 +1,75 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated + +def fact(name=None) -> Annotated[Any, _atypes.String]: + r"""Output a fact about factorials. + + Args: + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Fact", name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return fact_eager_fallback( + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Fact", name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "Fact", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Fact = tf_export("raw_ops.Fact")(_ops.to_raw_op(fact)) + + +def fact_eager_fallback(name, ctx) -> Annotated[Any, _atypes.String]: + _inputs_flat = [] + _attrs = None + _result = _execute.execute(b"Fact", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Fact", _inputs_flat, _attrs, _result) + _result, = _result + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/user_ops/user_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/user_ops/user_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..e2ec1ec06451524f966b7f7265c04096da281835 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/user_ops/user_ops.py @@ -0,0 +1,28 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""All user ops.""" + +from tensorflow.python.user_ops.ops import gen_user_ops as _gen_user_ops + +# go/tf-wildcard-import +from tensorflow.python.user_ops.ops.gen_user_ops import * # pylint: disable=wildcard-import +from tensorflow.python.util.tf_export import tf_export + + +@tf_export(v1=['user_ops.my_fact']) +def my_fact(): + """Example of overriding the generated code for an Op.""" + return _gen_user_ops.fact() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/_pywrap_checkpoint_reader.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/_pywrap_checkpoint_reader.pyi new file mode 100644 index 0000000000000000000000000000000000000000..1402d60148afeb9f28c35c15f12c974d31be0322 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/_pywrap_checkpoint_reader.pyi @@ -0,0 +1,25 @@ +# Copyright 2023 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +from typing import Any + +class CheckpointReader: + def __init__(self, arg0: str) -> None: ... + @classmethod + def CheckpointReader_GetTensor(cls, arg0: CheckpointReader, arg1: str) -> object: ... + def _GetVariableToDataTypeMap(self, *args, **kwargs) -> Any: ... + def _HasTensor(self, arg0: str) -> bool: ... + def debug_string(self) -> bytes: ... + def get_variable_to_shape_map(self, *args, **kwargs) -> Any: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/_pywrap_determinism.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/_pywrap_determinism.pyi new file mode 100644 index 0000000000000000000000000000000000000000..cd6c39347b6d2870cfa313148e8e33999a82d0cd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/_pywrap_determinism.pyi @@ -0,0 +1,17 @@ +# Copyright 2023 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +def enable(arg0: bool) -> None: ... +def is_enabled() -> bool: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/_pywrap_kernel_registry.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/_pywrap_kernel_registry.pyi new file mode 100644 index 0000000000000000000000000000000000000000..bb54143b2887435e7c941b72962787748728749e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/_pywrap_kernel_registry.pyi @@ -0,0 +1,16 @@ +# Copyright 2023 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +def TryFindKernelClass(arg0: str) -> bytes: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/_pywrap_stat_summarizer.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/_pywrap_stat_summarizer.pyi new file mode 100644 index 0000000000000000000000000000000000000000..ba10303b2f04406b888af65e4b76e59b6525cf05 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/_pywrap_stat_summarizer.pyi @@ -0,0 +1,26 @@ +# Copyright 2023 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +from typing import overload + +class StatSummarizer: + @overload + def __init__(self, arg0: str) -> None: ... + @overload + def __init__(self) -> None: ... + def GetOutputString(self) -> str: ... + def PrintStepStats(self) -> None: ... + def ProcessStepStats(self, arg0) -> None: ... + def ProcessStepStatsStr(self, arg0: str) -> None: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/_pywrap_tensor_float_32_execution.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/_pywrap_tensor_float_32_execution.pyi new file mode 100644 index 0000000000000000000000000000000000000000..cd6c39347b6d2870cfa313148e8e33999a82d0cd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/_pywrap_tensor_float_32_execution.pyi @@ -0,0 +1,17 @@ +# Copyright 2023 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +def enable(arg0: bool) -> None: ... +def is_enabled() -> bool: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/_pywrap_tfprof.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/_pywrap_tfprof.pyi new file mode 100644 index 0000000000000000000000000000000000000000..a307be13a4c60efd2477c4e90c1c57f491a9fc04 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/_pywrap_tfprof.pyi @@ -0,0 +1,23 @@ +# Copyright 2023 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +def AddStep(arg0: int, arg1: str, arg2: str, arg3: str) -> float: ... +def DeleteProfiler() -> None: ... +def NewProfiler(arg0: str, arg1: str) -> bool: ... +def PrintModelAnalysis(arg0: str, arg1: str, arg2: str, arg3: str, arg4: str) -> bytes: ... +def Profile(arg0: str, arg1: str) -> bytes: ... +def ProfilerFromFile(arg0: str) -> None: ... +def SerializeToString() -> bytes: ... +def WriteProfile(arg0: str) -> None: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/_pywrap_transform_graph.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/_pywrap_transform_graph.pyi new file mode 100644 index 0000000000000000000000000000000000000000..0de83df042d914119b7ad1167cdc3e0e508c2958 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/_pywrap_transform_graph.pyi @@ -0,0 +1,16 @@ +# Copyright 2023 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +def TransformGraphWithStringInputs(arg0: object, arg1: object, arg2: object, arg3: object) -> bytes: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/_pywrap_util_port.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/_pywrap_util_port.pyi new file mode 100644 index 0000000000000000000000000000000000000000..f6a5ec7bbd92753260438f235cf8bc1bc87c43b1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/_pywrap_util_port.pyi @@ -0,0 +1,21 @@ +# Copyright 2023 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +def GpuSupportsHalfMatMulAndConv() -> bool: ... +def IsBuiltWithNvcc() -> bool: ... +def IsBuiltWithROCm() -> bool: ... +def IsBuiltWithXLA() -> bool: ... +def IsGoogleCudaEnabled() -> bool: ... +def IsMklEnabled() -> bool: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/_tf_stack.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/_tf_stack.pyi new file mode 100644 index 0000000000000000000000000000000000000000..cc906680cbc7056c556442f42f9e918beb303b72 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/_tf_stack.pyi @@ -0,0 +1,64 @@ +# Copyright 2023 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +from typing import Iterator + +from typing import overload + +class GraphDebugInfoBuilder: + def __init__(self) -> None: ... + def AccumulateStackTrace(self, function: str, op: str, trace) -> None: ... + def AppendGraphDebugInfo(self, prefix: str, debug_info: bytes) -> None: ... + def Build(self) -> bytes: ... + +class PyBindFileSet: + def __init__(self) -> None: ... + def update_to(self, arg0: set) -> None: ... + +class PyBindSourceMap: + def __init__(self) -> None: ... + def update_to(self, arg0: tuple) -> None: ... + +class StackFrame: + def __init__(self, *args, **kwargs) -> None: ... + def __eq__(self, arg0: StackFrame) -> bool: ... + def __getitem__(self, arg0: object) -> object: ... + def __hash__(self) -> int: ... + def __iter__(self) -> Iterator: ... + def __len__(self) -> int: ... + def __ne__(self, arg0: StackFrame) -> bool: ... + @property + def filename(self) -> str: ... + @property + def line(self) -> str: ... + @property + def lineno(self) -> int: ... + @property + def name(self) -> str: ... + +class StackTrace: + def __init__(self, *args, **kwargs) -> None: ... + def get_user_frames(self) -> StackTrace: ... + def last_user_frame(self) -> StackFrame: ... + def __eq__(self, arg0: StackTrace) -> bool: ... + @overload + def __getitem__(self, arg0: int) -> StackFrame: ... + @overload + def __getitem__(self, arg0: slice) -> StackTrace: ... + def __hash__(self) -> int: ... + def __len__(self) -> int: ... + +def LoadTracesFromDebugInfo(debug_info_proto: bytes) -> dict[str,StackTrace]: ... +def extract_stack(source_map: PyBindSourceMap, file_set: PyBindFileSet, stacklevel: int = ...) -> StackTrace: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/all_util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/all_util.py new file mode 100644 index 0000000000000000000000000000000000000000..b2d2ab5a6735e257b5c5f6697896e4ed33db0da0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/all_util.py @@ -0,0 +1,117 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""Generate __all__ from a module docstring.""" +import re as _re +import sys as _sys + +from tensorflow.python.util import tf_inspect as _tf_inspect + + +_reference_pattern = _re.compile(r'^@@(\w+)$', flags=_re.MULTILINE) + + +def make_all(module_name, doc_string_modules=None): + """Generates `__all__` from the docstring of one or more modules. + + Usage: `make_all(__name__)` or + `make_all(__name__, [sys.modules(__name__), other_module])`. The doc string + modules must each a docstring, and `__all__` will contain all symbols with + `@@` references, where that symbol currently exists in the module named + `module_name`. + + Args: + module_name: The name of the module (usually `__name__`). + doc_string_modules: a list of modules from which to take docstring. + If None, then a list containing only the module named `module_name` is used. + + Returns: + A list suitable for use as `__all__`. + """ + if doc_string_modules is None: + doc_string_modules = [_sys.modules[module_name]] + cur_members = set( + name for name, _ in _tf_inspect.getmembers(_sys.modules[module_name])) + + results = set() + for doc_module in doc_string_modules: + results.update([m.group(1) + for m in _reference_pattern.finditer(doc_module.__doc__) + if m.group(1) in cur_members]) + return list(results) + +# Hidden attributes are attributes that have been hidden by +# `remove_undocumented`. They can be re-instated by `reveal_undocumented`. +# This maps symbol names to a tuple, containing: +# (module object, attribute value) +_HIDDEN_ATTRIBUTES = {} + + +def reveal_undocumented(symbol_name, target_module=None): + """Reveals a symbol that was previously removed by `remove_undocumented`. + + This should be used by tensorflow internal tests only. It explicitly + defeats the encapsulation afforded by `remove_undocumented`. + + It throws an exception when the symbol was not hidden in the first place. + + Args: + symbol_name: a string representing the full absolute path of the symbol. + target_module: if specified, the module in which to restore the symbol. + """ + if symbol_name not in _HIDDEN_ATTRIBUTES: + raise LookupError('Symbol %s is not a hidden symbol' % symbol_name) + symbol_basename = symbol_name.split('.')[-1] + (original_module, attr_value) = _HIDDEN_ATTRIBUTES[symbol_name] + if not target_module: target_module = original_module + setattr(target_module, symbol_basename, attr_value) + + +def remove_undocumented(module_name, allowed_exception_list=None, + doc_string_modules=None): + """Removes symbols in a module that are not referenced by a docstring. + + Args: + module_name: the name of the module (usually `__name__`). + allowed_exception_list: a list of names that should not be removed. + doc_string_modules: a list of modules from which to take the docstrings. + If None, then a list containing only the module named `module_name` is used. + + Furthermore, if a symbol previously added with `add_to_global_allowlist`, + then it will always be allowed. This is useful for internal tests. + + Returns: + None + """ + current_symbols = set(dir(_sys.modules[module_name])) + should_have = make_all(module_name, doc_string_modules) + should_have += allowed_exception_list or [] + extra_symbols = current_symbols - set(should_have) + target_module = _sys.modules[module_name] + for extra_symbol in extra_symbols: + # Skip over __file__, etc. Also preserves internal symbols. + if extra_symbol.startswith('_'): continue + fully_qualified_name = module_name + '.' + extra_symbol + _HIDDEN_ATTRIBUTES[fully_qualified_name] = (target_module, + getattr(target_module, + extra_symbol)) + delattr(target_module, extra_symbol) + + +__all__ = [ + 'make_all', + 'remove_undocumented', + 'reveal_undocumented', +] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/compat.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/compat.py new file mode 100644 index 0000000000000000000000000000000000000000..0d3c1a2b3c658234e63354206fc4965fad606ed0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/compat.py @@ -0,0 +1,217 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Compatibility functions. + +The `tf.compat` module contains two sets of compatibility functions. + +## Tensorflow 1.x and 2.x APIs + +The `compat.v1` and `compat.v2` submodules provide a complete copy of both the +`v1` and `v2` APIs for backwards and forwards compatibility across TensorFlow +versions 1.x and 2.x. See the +[migration guide](https://www.tensorflow.org/guide/migrate) for details. + +## Utilities for writing compatible code + +Aside from the `compat.v1` and `compat.v2` submodules, `tf.compat` also contains +a set of helper functions for writing code that works in both: + +* TensorFlow 1.x and 2.x +* Python 2 and 3 + + +## Type collections + +The compatibility module also provides the following aliases for common +sets of python types: + +* `bytes_or_text_types` +* `complex_types` +* `integral_types` +* `real_types` + +API docstring: tensorflow.compat +""" + +import numbers as _numbers + +import numpy as _np +import six as _six +import codecs + +from tensorflow.python.util.tf_export import tf_export + +try: + # This import only works on python 3.3 and above. + import collections.abc as collections_abc # pylint: disable=unused-import +except ImportError: + import collections as collections_abc # pylint: disable=unused-import + + +def as_bytes(bytes_or_text, encoding='utf-8'): + """Converts `bytearray`, `bytes`, or unicode python input types to `bytes`. + + Uses utf-8 encoding for text by default. + + Args: + bytes_or_text: A `bytearray`, `bytes`, `str`, or `unicode` object. + encoding: A string indicating the charset for encoding unicode. + + Returns: + A `bytes` object. + + Raises: + TypeError: If `bytes_or_text` is not a binary or unicode string. + """ + # Validate encoding, a LookupError will be raised if invalid. + encoding = codecs.lookup(encoding).name + if isinstance(bytes_or_text, bytearray): + return bytes(bytes_or_text) + elif isinstance(bytes_or_text, _six.text_type): + return bytes_or_text.encode(encoding) + elif isinstance(bytes_or_text, bytes): + return bytes_or_text + else: + raise TypeError('Expected binary or unicode string, got %r' % + (bytes_or_text,)) + + +def as_text(bytes_or_text, encoding='utf-8'): + """Converts any string-like python input types to unicode. + + Returns the input as a unicode string. Uses utf-8 encoding for text + by default. + + Args: + bytes_or_text: A `bytes`, `str`, or `unicode` object. + encoding: A string indicating the charset for decoding unicode. + + Returns: + A `unicode` (Python 2) or `str` (Python 3) object. + + Raises: + TypeError: If `bytes_or_text` is not a binary or unicode string. + """ + # Validate encoding, a LookupError will be raised if invalid. + encoding = codecs.lookup(encoding).name + if isinstance(bytes_or_text, _six.text_type): + return bytes_or_text + elif isinstance(bytes_or_text, bytes): + return bytes_or_text.decode(encoding) + else: + raise TypeError('Expected binary or unicode string, got %r' % bytes_or_text) + + +def as_str(bytes_or_text, encoding='utf-8'): + return as_text(bytes_or_text, encoding) + +tf_export('compat.as_text')(as_text) +tf_export('compat.as_bytes')(as_bytes) +tf_export('compat.as_str')(as_str) + + +@tf_export('compat.as_str_any') +def as_str_any(value, encoding='utf-8'): + """Converts input to `str` type. + + Uses `str(value)`, except for `bytes` typed inputs, which are converted + using `as_str`. + + Args: + value: A object that can be converted to `str`. + encoding: Encoding for `bytes` typed inputs. + + Returns: + A `str` object. + """ + if isinstance(value, bytes): + return as_str(value, encoding=encoding) + else: + return str(value) + + +@tf_export('compat.path_to_str') +def path_to_str(path): + r"""Converts input which is a `PathLike` object to `str` type. + + Converts from any python constant representation of a `PathLike` object to + a string. If the input is not a `PathLike` object, simply returns the input. + + Args: + path: An object that can be converted to path representation. + + Returns: + A `str` object. + + Usage: + In case a simplified `str` version of the path is needed from an + `os.PathLike` object. + + Examples: + ```python + $ tf.compat.path_to_str('C:\XYZ\tensorflow\./.././tensorflow') + 'C:\XYZ\tensorflow\./.././tensorflow' # Windows OS + $ tf.compat.path_to_str(Path('C:\XYZ\tensorflow\./.././tensorflow')) + 'C:\XYZ\tensorflow\..\tensorflow' # Windows OS + $ tf.compat.path_to_str(Path('./corpus')) + 'corpus' # Linux OS + $ tf.compat.path_to_str('./.././Corpus') + './.././Corpus' # Linux OS + $ tf.compat.path_to_str(Path('./.././Corpus')) + '../Corpus' # Linux OS + $ tf.compat.path_to_str(Path('./..////../')) + '../..' # Linux OS + + ``` + """ + if hasattr(path, '__fspath__'): + path = as_str_any(path.__fspath__()) + return path + + +def path_to_bytes(path): + r"""Converts input which is a `PathLike` object to `bytes`. + + Converts from any python constant representation of a `PathLike` object + or `str` to bytes. + + Args: + path: An object that can be converted to path representation. + + Returns: + A `bytes` object. + + Usage: + In case a simplified `bytes` version of the path is needed from an + `os.PathLike` object. + """ + if hasattr(path, '__fspath__'): + path = path.__fspath__() + return as_bytes(path) + + +# Numpy 1.8 scalars don't inherit from numbers.Integral in Python 3, so we +# need to check them specifically. The same goes from Real and Complex. +integral_types = (_numbers.Integral, _np.integer) +tf_export('compat.integral_types').export_constant(__name__, 'integral_types') +real_types = (_numbers.Real, _np.integer, _np.floating) +tf_export('compat.real_types').export_constant(__name__, 'real_types') +complex_types = (_numbers.Complex, _np.number) +tf_export('compat.complex_types').export_constant(__name__, 'complex_types') + +# Either bytes or text. +bytes_or_text_types = (bytes, _six.text_type) +tf_export('compat.bytes_or_text_types').export_constant(__name__, + 'bytes_or_text_types') diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/custom_nest_protocol.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/custom_nest_protocol.py new file mode 100644 index 0000000000000000000000000000000000000000..1da4e463604b5fddd474e0221af3643dc4bc96aa --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/custom_nest_protocol.py @@ -0,0 +1,120 @@ +# Copyright 2023 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""Protocol class for custom tf.nest support.""" + +import typing +from typing import Protocol + + +@typing.runtime_checkable +class CustomNestProtocol(Protocol): + """Protocol for adding custom tf.nest support in user-defined classes. + + User classes should implement the two methods defined in this protocol in + order to be supported by nest functions. + - `__tf_flatten__` for generating the flattened components and the metadata + of the current object. + - `__tf_unflatten__` for creating a new object based on the input metadata + and the components. + See the method doc for details. + + In terms of support level, classes implementing this protocol + - are supported by tf.nest and tf.data functions. + - have limited support from tf.function, which requires writing a custom + TraceType subclass to be used as the input or output of a tf.function. + - are NOT supported by SavedModel. + + Code Examples: + + >>> import dataclasses + >>> @dataclasses.dataclass + ... class MaskedTensor: + ... mask: bool + ... value: tf.Tensor + ... + ... def __tf_flatten__(self): + ... metadata = (self.mask,) # static config. + ... components = (self.value,) # dynamic values. + ... return metadata, components + ... + ... @classmethod + ... def __tf_unflatten__(cls, metadata, components): + ... mask = metadata[0] + ... value = components[0] + ... return MaskedTensor(mask=mask, value=value) + ... + >>> mt = MaskedTensor(mask=True, value=tf.constant([1])) + >>> mt + MaskedTensor(mask=True, value=) + >>> tf.nest.is_nested(mt) + True + >>> mt2 = MaskedTensor(mask=False, value=tf.constant([2])) + >>> tf.nest.assert_same_structure(mt, mt2) + + >>> leaves = tf.nest.flatten(mt) + >>> leaves + [] + + >>> mt3 = tf.nest.pack_sequence_as(mt, leaves) + >>> mt3 + MaskedTensor(mask=True, value=) + >>> bool(mt == mt3) + True + + >>> tf.nest.map_structure(lambda x: x * 2, mt) + MaskedTensor(mask=True, value=) + + More examples are available in the unit tests (nest_test.py). + """ + + def __tf_flatten__(self): + """Flatten current object into (metadata, components). + + Returns: + A `tuple` of (metadata, components), where + - metadata is a custom Python object that stands for the static config + of the current object, which is supposed to be fixed and not affected + by data transformation. + - components is a `tuple` that contains the modifiable fields of the + current object. + + Implementation Note: + - This method should not invoke any TensorFlow ops. + - This method only needs to flatten the current level. If current object has + an attribute that also need custom flattening, nest functions (such as + `nest.flatten`) will utilize this method to do recursive flattening. + - Components must ba a `tuple`, not a `list` + """ + + @classmethod + def __tf_unflatten__(cls, metadata, components): + """Create a user-defined object from (metadata, components). + + Args: + metadata: a custom Python objet that stands for the static config for + reconstructing a new object of the current class. + components: a `tuple` that contains the dynamic data fields of the current + class, for object reconstruction. + + Returns: + The user-defined object, with the same class of the current object. + + Implementation Note: + - This method should not invoke any TensorFlow ops. + - This method only needs to unflatten the current level. If the object has + an attribute that also need custom unflattening, nest functions will + utilize this method to do recursive unflattening. + """ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/decorator_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/decorator_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..7ba87878cb1482b37b5bb950e626719f29c39953 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/decorator_utils.py @@ -0,0 +1,203 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""Utility functions for writing decorators (which modify docstrings).""" +import sys + + +def get_qualified_name(function): + # Python 3 + if hasattr(function, '__qualname__'): + return function.__qualname__ + + # Python 2 + if hasattr(function, 'im_class'): + return function.im_class.__name__ + '.' + function.__name__ + return function.__name__ + + +def _normalize_docstring(docstring): + """Normalizes the docstring. + + Replaces tabs with spaces, removes leading and trailing blanks lines, and + removes any indentation. + + Copied from PEP-257: + https://www.python.org/dev/peps/pep-0257/#handling-docstring-indentation + + Args: + docstring: the docstring to normalize + + Returns: + The normalized docstring + """ + if not docstring: + return '' + # Convert tabs to spaces (following the normal Python rules) + # and split into a list of lines: + lines = docstring.expandtabs().splitlines() + # Determine minimum indentation (first line doesn't count): + # (we use sys.maxsize because sys.maxint doesn't exist in Python 3) + indent = sys.maxsize + for line in lines[1:]: + stripped = line.lstrip() + if stripped: + indent = min(indent, len(line) - len(stripped)) + # Remove indentation (first line is special): + trimmed = [lines[0].strip()] + if indent < sys.maxsize: + for line in lines[1:]: + trimmed.append(line[indent:].rstrip()) + # Strip off trailing and leading blank lines: + while trimmed and not trimmed[-1]: + trimmed.pop() + while trimmed and not trimmed[0]: + trimmed.pop(0) + # Return a single string: + return '\n'.join(trimmed) + + +def add_notice_to_docstring(doc, + instructions, + no_doc_str, + suffix_str, + notice, + notice_type='Warning'): + """Adds a deprecation notice to a docstring. + + Args: + doc: The original docstring. + instructions: A string, describing how to fix the problem. + no_doc_str: The default value to use for `doc` if `doc` is empty. + suffix_str: Is added to the end of the first line. + notice: A list of strings. The main notice warning body. + notice_type: The type of notice to use. Should be one of `[Caution, + Deprecated, Important, Note, Warning]` + + Returns: + A new docstring, with the notice attached. + + Raises: + ValueError: If `notice` is empty. + """ + allowed_notice_types = ['Deprecated', 'Warning', 'Caution', 'Important', + 'Note'] + if notice_type not in allowed_notice_types: + raise ValueError( + f'Unrecognized notice type. Should be one of: {allowed_notice_types}') + + if not doc: + lines = [no_doc_str] + else: + lines = _normalize_docstring(doc).splitlines() + lines[0] += ' ' + suffix_str + + if not notice: + raise ValueError('The `notice` arg must not be empty.') + + notice[0] = f'{notice_type}: {notice[0]}' + notice = [''] + notice + ([instructions] if instructions else []) + + if len(lines) > 1: + # Make sure that we keep our distance from the main body + if lines[1].strip(): + notice.append('') + + lines[1:1] = notice + else: + lines += notice + + return '\n'.join(lines) + + +def validate_callable(func, decorator_name): + if not hasattr(func, '__call__'): + raise ValueError( + '%s is not a function. If this is a property, make sure' + ' @property appears before @%s in your source code:' + '\n\n@property\n@%s\ndef method(...)' % ( + func, decorator_name, decorator_name)) + + +class classproperty(object): # pylint: disable=invalid-name + """Class property decorator. + + Example usage: + + class MyClass(object): + + @classproperty + def value(cls): + return '123' + + > print MyClass.value + 123 + """ + + def __init__(self, func): + self._func = func + + def __get__(self, owner_self, owner_cls): + return self._func(owner_cls) + + +class _CachedClassProperty(object): + """Cached class property decorator. + + Transforms a class method into a property whose value is computed once + and then cached as a normal attribute for the life of the class. Example + usage: + + >>> class MyClass(object): + ... @cached_classproperty + ... def value(cls): + ... print("Computing value") + ... return '' % cls.__name__ + >>> class MySubclass(MyClass): + ... pass + >>> MyClass.value + Computing value + '' + >>> MyClass.value # uses cached value + '' + >>> MySubclass.value + Computing value + '' + + This decorator is similar to `functools.cached_property`, but it adds a + property to the class, not to individual instances. + """ + + def __init__(self, func): + self._func = func + self._cache = {} + + def __get__(self, obj, objtype): + if objtype not in self._cache: + self._cache[objtype] = self._func(objtype) + return self._cache[objtype] + + def __set__(self, obj, value): + raise AttributeError('property %s is read-only' % self._func.__name__) + + def __delete__(self, obj): + raise AttributeError('property %s is read-only' % self._func.__name__) + + +def cached_classproperty(func): + return _CachedClassProperty(func) + + +cached_classproperty.__doc__ = _CachedClassProperty.__doc__ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/deprecated_module.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/deprecated_module.py new file mode 100644 index 0000000000000000000000000000000000000000..ad26c5c97e57a4b0765b4e44b2e245a9d77b8944 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/deprecated_module.py @@ -0,0 +1,24 @@ +# Copyright 2022 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""A deprecated module. + +For testing `deprecation.deprecate_moved_module`. +""" + +from tensorflow.python.util import deprecated_module_new +from tensorflow.python.util import deprecation + +__getattr__ = deprecation.deprecate_moved_module( + __name__, deprecated_module_new, "2.9") diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/deprecated_module_new.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/deprecated_module_new.py new file mode 100644 index 0000000000000000000000000000000000000000..762c4b022cf69f6f60f43a3b83d8a1725ab18694 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/deprecated_module_new.py @@ -0,0 +1,22 @@ +# Copyright 2022 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""A module to replace deprecated_module. + +For testing `deprecation.deprecate_moved_module`. +""" + + +def a(): + return 1 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/deprecation.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/deprecation.py new file mode 100644 index 0000000000000000000000000000000000000000..08c117bd78f69f49126855ff1f645ff9fd88459a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/deprecation.py @@ -0,0 +1,767 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Tensor utility functions.""" +import collections +import functools +import inspect +import re + +from tensorflow.python.framework import strict_mode +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.util import decorator_utils +from tensorflow.python.util import is_in_graph_mode +from tensorflow.python.util import tf_contextlib +from tensorflow.python.util import tf_decorator +from tensorflow.python.util import tf_inspect +from tensorflow.tools.docs import doc_controls + +# Allow deprecation warnings to be silenced temporarily with a context manager. +_PRINT_DEPRECATION_WARNINGS = True + +# Remember which deprecation warnings have been printed already. +_PRINTED_WARNING = {} + + +class DeprecatedNamesAlreadySetError(Exception): + """Raised when setting deprecated names multiple times for the same symbol.""" + + +def _log_deprecation(msg, *args, **kwargs): + """Raises errors for deprecated methods if in strict mode, warns otherwise.""" + if strict_mode.STRICT_MODE: + logging.error(msg, *args, **kwargs) + raise RuntimeError( + 'This behavior has been deprecated, which raises an error in strict' + ' mode.' + ) + else: + logging.warning(msg, *args, **kwargs) + + +def _add_deprecated_function_notice_to_docstring(doc, date, instructions): + """Adds a deprecation notice to a docstring for deprecated functions.""" + main_text = [ + 'THIS FUNCTION IS DEPRECATED. It will be removed %s.' + % ('in a future version' if date is None else ('after %s' % date)) + ] + if instructions: + main_text.append('Instructions for updating:') + return decorator_utils.add_notice_to_docstring( + doc, + instructions, + 'DEPRECATED FUNCTION', + '(deprecated)', + main_text, + notice_type='Deprecated') + + +def _add_deprecated_arg_notice_to_docstring(doc, date, instructions, + deprecated_names): + """Adds a deprecation notice to a docstring for deprecated arguments.""" + + deprecation_string = ', '.join(sorted(deprecated_names)) + + return decorator_utils.add_notice_to_docstring( + doc, + instructions, + 'DEPRECATED FUNCTION ARGUMENTS', + '(deprecated arguments)', [ + 'SOME ARGUMENTS ARE DEPRECATED: `(%s)`. ' + 'They will be removed %s.' % + (deprecation_string, 'in a future version' if date is None else + ('after %s' % date)), 'Instructions for updating:' + ], + notice_type='Deprecated') + + +def _add_deprecated_arg_value_notice_to_docstring(doc, date, instructions, + deprecated_name_value_dict): + """Adds a deprecation notice to a docstring for deprecated arguments.""" + + deprecation_string = ', '.join( + '%s=%r' % (key, value) + for key, value in sorted(deprecated_name_value_dict.items())) + + when = 'in a future version' if date is None else ('after %s' % date) + + return decorator_utils.add_notice_to_docstring( + doc, + instructions, + 'DEPRECATED FUNCTION ARGUMENT VALUES', + '(deprecated argument values)', [ + 'SOME ARGUMENT VALUES ARE DEPRECATED: `(%s)`. ' + 'They will be removed %s.' % + (deprecation_string, when), 'Instructions for updating:' + ], + notice_type='Deprecated') + + +def _validate_deprecation_args(date, instructions): + if date is not None and not re.match(r'20\d\d-[01]\d-[0123]\d', date): + raise ValueError(f'Date must be in format YYYY-MM-DD. Received: {date}') + if not instructions: + raise ValueError( + 'Don\'t deprecate things without conversion instructions! Specify ' + 'the `instructions` argument.') + + +def _call_location(outer=False): + """Returns call location given level up from current call.""" + # Two up: <_call_location>, <_call_location's caller> + # tf_inspect is not required here. Please ignore the lint warning by adding + # DISABLE_IMPORT_INSPECT_CHECK=TRUE to your cl description. Using it caused + # test timeouts (b/189384061). + f = inspect.currentframe().f_back.f_back + parent = f and f.f_back + if outer and parent is not None: + f = parent + return '{}:{}'.format(f.f_code.co_filename, f.f_lineno) + + +def _safe_eq(a, b): + if a is None or b is None: + return a is None and b is None + return a == b + + +def _wrap_decorator(wrapped_function, decorator_name): + """Indicate that one function wraps another. + + This decorator wraps a function using `tf_decorator.make_decorator` + so that doc generation scripts can pick up original function + signature. + It would be better to use @functools.wrap decorator, but it would + not update function signature to match wrapped function in Python 2. + + Args: + wrapped_function: The function that decorated function wraps. + decorator_name: The name of the decorator. + + Returns: + Function that accepts wrapper function as an argument and returns + `TFDecorator` instance. + """ + + def wrapper(wrapper_func): + return tf_decorator.make_decorator(wrapped_function, wrapper_func, + decorator_name) + + return wrapper + + +def deprecated_alias(deprecated_name, name, func_or_class, warn_once=True): + """Deprecate a symbol in favor of a new name with identical semantics. + + This function is meant to be used when defining a backwards-compatibility + alias for a symbol which has been moved. For example: + + module1.py: + ```python + class NewNameForClass: pass + ``` + + module2.py: + ```python + import module1 + + DeprecatedNameForClass = deprecated_alias( + deprecated_name='module2.DeprecatedNameForClass', + name='module1.NewNameForClass', + func_or_class=module1.NewNameForClass) + ``` + + This function works for classes and functions. + + For classes, it creates a new class which is functionally identical (it + inherits from the original, and overrides its constructor), but which prints + a deprecation warning when an instance is created. It also adds a deprecation + notice to the class' docstring. + + For functions, it returns a function wrapped by `tf_decorator.make_decorator`. + That function prints a warning when used, and has a deprecation notice in its + docstring. This is more or less equivalent (the deprecation warning has + slightly different text) to writing: + + ```python + @deprecated + def deprecated_alias(original_args): + real_function(original_args) + ``` + + Args: + deprecated_name: The name of the symbol that is being deprecated, to be used + in the warning message. This should be its fully qualified name to avoid + confusion. + name: The name of the symbol that is to be used instead of the deprecated + name. This should be a fully qualified name to avoid confusion. + func_or_class: The (non-deprecated) class or function for which a deprecated + alias should be created. + warn_once: If True (the default), only print a deprecation warning the first + time this function is used, or the class is instantiated. + + Returns: + A wrapped version of `func_or_class` which prints a deprecation warning on + use and has a modified docstring. + """ + if tf_inspect.isclass(func_or_class): + + # Make a new class with __init__ wrapped in a warning. + class _NewClass(func_or_class): # pylint: disable=missing-docstring + __doc__ = decorator_utils.add_notice_to_docstring( + func_or_class.__doc__, + 'Please use %s instead.' % name, + 'DEPRECATED CLASS', + '(deprecated)', [('THIS CLASS IS DEPRECATED. ' + 'It will be removed in a future version. ')], + notice_type='Deprecated') + __name__ = func_or_class.__name__ + __module__ = _call_location(outer=True) + + @_wrap_decorator(func_or_class.__init__, 'deprecated_alias') + def __init__(self, *args, **kwargs): + if hasattr(_NewClass.__init__, '__func__'): + # Python 2 + _NewClass.__init__.__func__.__doc__ = func_or_class.__init__.__doc__ + else: + # Python 3 + _NewClass.__init__.__doc__ = func_or_class.__init__.__doc__ + + if _PRINT_DEPRECATION_WARNINGS: + # We're making the alias as we speak. The original may have other + # aliases, so we cannot use it to check for whether it's already been + # warned about. + if _NewClass.__init__ not in _PRINTED_WARNING: + if warn_once: + _PRINTED_WARNING[_NewClass.__init__] = True + _log_deprecation( + 'From %s: The name %s is deprecated. Please use %s instead.\n', + _call_location(), deprecated_name, name) + super(_NewClass, self).__init__(*args, **kwargs) + + return _NewClass + else: + decorator_utils.validate_callable(func_or_class, 'deprecated') + + # Make a wrapper for the original + @functools.wraps(func_or_class) + def new_func(*args, **kwargs): # pylint: disable=missing-docstring + if _PRINT_DEPRECATION_WARNINGS: + # We're making the alias as we speak. The original may have other + # aliases, so we cannot use it to check for whether it's already been + # warned about. + if new_func not in _PRINTED_WARNING: + if warn_once: + _PRINTED_WARNING[new_func] = True + _log_deprecation( + 'From %s: The name %s is deprecated. Please use %s instead.\n', + _call_location(), deprecated_name, name) + return func_or_class(*args, **kwargs) + + return tf_decorator.make_decorator( + func_or_class, new_func, 'deprecated', + _add_deprecated_function_notice_to_docstring( + func_or_class.__doc__, None, 'Please use %s instead.' % name)) + + +def deprecated_endpoints(*args): + """Decorator for marking endpoints deprecated. + + This decorator does not print deprecation messages. + TODO(annarev): eventually start printing deprecation warnings when + @deprecation_endpoints decorator is added. + + Args: + *args: Deprecated endpoint names. + + Returns: + A function that takes symbol as an argument and adds + _tf_deprecated_api_names to that symbol. + _tf_deprecated_api_names would be set to a list of deprecated + endpoint names for the symbol. + """ + + def deprecated_wrapper(func): + # pylint: disable=protected-access + if '_tf_deprecated_api_names' in func.__dict__: + raise DeprecatedNamesAlreadySetError( + f'Cannot set deprecated names for {func.__name__} to {args}. ' + 'Deprecated names are already set to ' + f'{func._tf_deprecated_api_names}.') + func._tf_deprecated_api_names = args + # pylint: disable=protected-access + return func + + return deprecated_wrapper + + +def deprecated(date, instructions, warn_once=True): + """Decorator for marking functions or methods deprecated. + + This decorator logs a deprecation warning whenever the decorated function is + called. It has the following format: + + (from ) is deprecated and will be removed after . + Instructions for updating: + + + If `date` is None, 'after ' is replaced with 'in a future version'. + will include the class name if it is a method. + + It also edits the docstring of the function: ' (deprecated)' is appended + to the first line of the docstring and a deprecation notice is prepended + to the rest of the docstring. + + Args: + date: String or None. The date the function is scheduled to be removed. Must + be ISO 8601 (YYYY-MM-DD), or None. + instructions: String. Instructions on how to update code using the + deprecated function. + warn_once: Boolean. Set to `True` to warn only the first time the decorated + function is called. Otherwise, every call will log a warning. + + Returns: + Decorated function or method. + + Raises: + ValueError: If date is not None or in ISO 8601 format, or instructions are + empty. + """ + _validate_deprecation_args(date, instructions) + + def deprecated_wrapper(func_or_class): + """Deprecation wrapper.""" + if isinstance(func_or_class, type): + # If a class is deprecated, you actually want to wrap the constructor. + cls = func_or_class + if cls.__new__ is object.__new__: + # If a class defaults to its parent's constructor, wrap that instead. + func = cls.__init__ + constructor_name = '__init__' + decorators, _ = tf_decorator.unwrap(func) + for decorator in decorators: + if decorator.decorator_name == 'deprecated': + # If the parent is already deprecated, there's nothing to do. + return cls + else: + func = cls.__new__ + constructor_name = '__new__' + + else: + cls = None + constructor_name = None + func = func_or_class + + decorator_utils.validate_callable(func, 'deprecated') + + @_wrap_decorator(func, 'deprecated') + def new_func(*args, **kwargs): # pylint: disable=missing-docstring + if _PRINT_DEPRECATION_WARNINGS: + if func not in _PRINTED_WARNING and cls not in _PRINTED_WARNING: + if warn_once: + _PRINTED_WARNING[func] = True + if cls: + _PRINTED_WARNING[cls] = True + _log_deprecation( + 'From %s: %s (from %s) is deprecated and will be removed %s.\n' + 'Instructions for updating:\n%s', _call_location(), + decorator_utils.get_qualified_name(func), + func_or_class.__module__, + 'in a future version' if date is None else ('after %s' % date), + instructions) + return func(*args, **kwargs) + + doc_controls.set_deprecated(new_func) + new_func = tf_decorator.make_decorator( + func, new_func, 'deprecated', + _add_deprecated_function_notice_to_docstring(func.__doc__, date, + instructions)) + new_func.__signature__ = inspect.signature(func) + + if cls is None: + return new_func + else: + # Insert the wrapped function as the constructor + setattr(cls, constructor_name, new_func) + + # And update the docstring of the class. + cls.__doc__ = _add_deprecated_function_notice_to_docstring( + cls.__doc__, date, instructions) + + return cls + + return deprecated_wrapper + + +DeprecatedArgSpec = collections.namedtuple( + 'DeprecatedArgSpec', ['position', 'has_ok_value', 'ok_value']) + + +def deprecated_args(date, instructions, *deprecated_arg_names_or_tuples, + **kwargs): + """Decorator for marking specific function arguments as deprecated. + + This decorator logs a deprecation warning whenever the decorated function is + called with the deprecated argument. It has the following format: + + Calling (from ) with is deprecated and will be + removed after . Instructions for updating: + + + If `date` is None, 'after ' is replaced with 'in a future version'. + includes the class name if it is a method. + + It also edits the docstring of the function: ' (deprecated arguments)' is + appended to the first line of the docstring and a deprecation notice is + prepended to the rest of the docstring. + + Args: + date: String or None. The date the function is scheduled to be removed. Must + be ISO 8601 (YYYY-MM-DD), or None. + instructions: String. Instructions on how to update code using the + deprecated function. + *deprecated_arg_names_or_tuples: String or 2-Tuple (String, ok_val). The + string is the deprecated argument name. Optionally, an ok-value may be + provided. If the user provided argument equals this value, the warning is + suppressed. + **kwargs: If `warn_once=False` is passed, every call with a deprecated + argument will log a warning. The default behavior is to only warn the + first time the function is called with any given deprecated argument. All + other kwargs raise `ValueError`. + + Returns: + Decorated function or method. + + Raises: + ValueError: If date is not None or in ISO 8601 format, instructions are + empty, the deprecated arguments are not present in the function + signature, the second element of a deprecated_tuple is not a + list, or if a kwarg other than `warn_once` is passed. + """ + _validate_deprecation_args(date, instructions) + if not deprecated_arg_names_or_tuples: + raise ValueError('Specify which argument is deprecated.') + if kwargs and list(kwargs.keys()) != ['warn_once']: + kwargs.pop('warn_once', None) + raise ValueError(f'Illegal argument passed to deprecated_args: {kwargs}') + warn_once = kwargs.get('warn_once', True) + + def _get_arg_names_to_ok_vals(): + """Returns a dict mapping arg_name to DeprecatedArgSpec w/o position.""" + d = {} + for name_or_tuple in deprecated_arg_names_or_tuples: + if isinstance(name_or_tuple, tuple): + d[name_or_tuple[0]] = DeprecatedArgSpec(-1, True, name_or_tuple[1]) + else: + d[name_or_tuple] = DeprecatedArgSpec(-1, False, None) + return d + + def _get_deprecated_positional_arguments(names_to_ok_vals, arg_spec): + """Builds a dictionary from deprecated arguments to their spec. + + Returned dict is keyed by argument name. + Each value is a DeprecatedArgSpec with the following fields: + position: The zero-based argument position of the argument + within the signature. None if the argument isn't found in + the signature. + ok_values: Values of this argument for which warning will be + suppressed. + + Args: + names_to_ok_vals: dict from string arg_name to a list of values, possibly + empty, which should not elicit a warning. + arg_spec: Output from tf_inspect.getfullargspec on the called function. + + Returns: + Dictionary from arg_name to DeprecatedArgSpec. + """ + # Extract argument list + arg_space = arg_spec.args + arg_spec.kwonlyargs + arg_name_to_pos = {name: pos for pos, name in enumerate(arg_space)} + deprecated_positional_args = {} + for arg_name, spec in iter(names_to_ok_vals.items()): + if arg_name in arg_name_to_pos: + pos = arg_name_to_pos[arg_name] + deprecated_positional_args[arg_name] = DeprecatedArgSpec( + pos, spec.has_ok_value, spec.ok_value) + return deprecated_positional_args + + deprecated_arg_names = _get_arg_names_to_ok_vals() + + def deprecated_wrapper(func): + """Deprecation decorator.""" + decorator_utils.validate_callable(func, 'deprecated_args') + + arg_spec = tf_inspect.getfullargspec(func) + deprecated_positions = _get_deprecated_positional_arguments( + deprecated_arg_names, arg_spec) + + is_varargs_deprecated = arg_spec.varargs in deprecated_arg_names + is_kwargs_deprecated = arg_spec.varkw in deprecated_arg_names + + if (len(deprecated_positions) + is_varargs_deprecated + is_kwargs_deprecated + != len(deprecated_arg_names_or_tuples)): + known_args = ( + arg_spec.args + arg_spec.kwonlyargs + + [arg_spec.varargs, arg_spec.varkw]) + missing_args = [ + arg_name for arg_name in deprecated_arg_names + if arg_name not in known_args + ] + raise ValueError('The following deprecated arguments are not present ' + f'in the function signature: {missing_args}. ' + 'Expected arguments from the following list: ' + f'{known_args}.') + + def _same_value(a, b): + """A comparison operation that works for multiple object types. + + Returns True for two empty lists, two numeric values with the + same value, etc. + + Returns False for (pd.DataFrame, None), and other pairs which + should not be considered equivalent. + + Args: + a: value one of the comparison. + b: value two of the comparison. + + Returns: + A boolean indicating whether the two inputs are the same value + for the purposes of deprecation. + """ + if a is b: + return True + try: + equality = a == b + if isinstance(equality, bool): + return equality + except TypeError: + return False + return False + + @functools.wraps(func) + def new_func(*args, **kwargs): + """Deprecation wrapper.""" + # TODO(apassos) figure out a way to have reasonable performance with + # deprecation warnings and eager mode. + if is_in_graph_mode.IS_IN_GRAPH_MODE() and _PRINT_DEPRECATION_WARNINGS: + invalid_args = [] + named_args = tf_inspect.getcallargs(func, *args, **kwargs) + for arg_name, spec in iter(deprecated_positions.items()): + if (spec.position < len(args) and + not (spec.has_ok_value and + _same_value(named_args[arg_name], spec.ok_value))): + invalid_args.append(arg_name) + if is_varargs_deprecated and len(args) > len(arg_spec.args): + invalid_args.append(arg_spec.varargs) + if is_kwargs_deprecated and kwargs: + invalid_args.append(arg_spec.varkw) + for arg_name in deprecated_arg_names: + if (arg_name in kwargs and + not (deprecated_positions[arg_name].has_ok_value and + _same_value(named_args[arg_name], + deprecated_positions[arg_name].ok_value))): + invalid_args.append(arg_name) + for arg_name in invalid_args: + if (func, arg_name) not in _PRINTED_WARNING: + if warn_once: + _PRINTED_WARNING[(func, arg_name)] = True + _log_deprecation( + 'From %s: calling %s (from %s) with %s is deprecated and will ' + 'be removed %s.\nInstructions for updating:\n%s', + _call_location(), decorator_utils.get_qualified_name(func), + func.__module__, arg_name, + 'in a future version' if date is None else ('after %s' % date), + instructions) + return func(*args, **kwargs) + + doc = _add_deprecated_arg_notice_to_docstring( + func.__doc__, date, instructions, sorted(deprecated_arg_names.keys())) + return tf_decorator.make_decorator(func, new_func, 'deprecated', doc) + + return deprecated_wrapper + + +def deprecated_arg_values(date, + instructions, + warn_once=True, + **deprecated_kwargs): + """Decorator for marking specific function argument values as deprecated. + + This decorator logs a deprecation warning whenever the decorated function is + called with the deprecated argument values. It has the following format: + + Calling (from ) with = is deprecated and + will be removed after . Instructions for updating: + + + If `date` is None, 'after ' is replaced with 'in a future version'. + will include the class name if it is a method. + + It also edits the docstring of the function: ' (deprecated arguments)' is + appended to the first line of the docstring and a deprecation notice is + prepended to the rest of the docstring. + + Args: + date: String or None. The date the function is scheduled to be removed. Must + be ISO 8601 (YYYY-MM-DD), or None + instructions: String. Instructions on how to update code using the + deprecated function. + warn_once: If `True`, warn only the first time this function is called with + deprecated argument values. Otherwise, every call (with a deprecated + argument value) will log a warning. + **deprecated_kwargs: The deprecated argument values. + + Returns: + Decorated function or method. + + Raises: + ValueError: If date is not None or in ISO 8601 format, or instructions are + empty. + """ + _validate_deprecation_args(date, instructions) + if not deprecated_kwargs: + raise ValueError('Specify which argument values are deprecated.') + + def deprecated_wrapper(func): + """Deprecation decorator.""" + decorator_utils.validate_callable(func, 'deprecated_arg_values') + + @functools.wraps(func) + def new_func(*args, **kwargs): + """Deprecation wrapper.""" + if _PRINT_DEPRECATION_WARNINGS: + named_args = tf_inspect.getcallargs(func, *args, **kwargs) + for arg_name, arg_value in deprecated_kwargs.items(): + if arg_name in named_args and _safe_eq(named_args[arg_name], + arg_value): + if (func, arg_name) not in _PRINTED_WARNING: + if warn_once: + _PRINTED_WARNING[(func, arg_name)] = True + _log_deprecation( + 'From %s: calling %s (from %s) with %s=%s is deprecated and ' + 'will be removed %s.\nInstructions for updating:\n%s', + _call_location(), decorator_utils.get_qualified_name(func), + func.__module__, arg_name, arg_value, + 'in a future version' if date is None else + ('after %s' % date), instructions) + return func(*args, **kwargs) + + doc = _add_deprecated_arg_value_notice_to_docstring(func.__doc__, date, + instructions, + deprecated_kwargs) + return tf_decorator.make_decorator(func, new_func, 'deprecated', doc) + + return deprecated_wrapper + + +def deprecated_argument_lookup(new_name, new_value, old_name, old_value): + """Looks up deprecated argument name and ensures both are not used. + + Args: + new_name: new name of argument + new_value: value of new argument (or None if not used) + old_name: old name of argument + old_value: value of old argument (or None if not used) + + Returns: + The effective argument that should be used. + Raises: + ValueError: if new_value and old_value are both non-null + """ + if old_value is not None: + if new_value is not None: + raise ValueError(f"Cannot specify both '{old_name}' and '{new_name}'.") + return old_value + return new_value + + +def rewrite_argument_docstring(old_doc, old_argument, new_argument): + return old_doc.replace('`%s`' % old_argument, + '`%s`' % new_argument).replace('%s:' % old_argument, + '%s:' % new_argument) + + +@tf_contextlib.contextmanager +def silence(): + """Temporarily silence deprecation warnings.""" + global _PRINT_DEPRECATION_WARNINGS + print_deprecation_warnings = _PRINT_DEPRECATION_WARNINGS + _PRINT_DEPRECATION_WARNINGS = False + yield + _PRINT_DEPRECATION_WARNINGS = print_deprecation_warnings + + +def deprecate_moved_module(deprecated_name, new_module, deletion_version): + """Logs a warning when a module that has been moved to a new location is used. + + Copy the following code into the old module: + + ``` + import deprecation + import new_module + + __getattr__ = deprecation.deprecate_moved_module( + __name__, new_module, "2.9") # adjust version number. + ``` + + Args: + deprecated_name: Name of old module. + new_module: Module to replace the old module. + deletion_version: Version of TensorFlow in which the old module will be + removed. + + Returns: + A function that logs a warning and returns the symbol from the new module. + Set this function as the module's `__getattr__`. + """ + + def getter(name): + if getter not in _PRINTED_WARNING and _PRINT_DEPRECATION_WARNINGS: + _PRINTED_WARNING[getter] = True + _log_deprecation( + 'Please fix your imports. Module %s has been moved to %s. The old ' + 'module will be deleted in version %s.', deprecated_name, + new_module.__name__, deletion_version) + return getattr(new_module, name) + + return getter + + +class HiddenTfApiAttribute(property): + """Hides a class attribute from the public API. + + Attributes in public classes can be hidden from the API by having an '_' in + front of the name (e.g. ClassName._variables). This doesn't work when + attributes or methods are inherited from a parent class. To hide inherited + attributes, set their values to be `deprecation.hide_attribute_from_api`. + For example, this is used in V2 Estimator to hide the deprecated + export_savedmodel method: + class EstimatorV2(Estimator): + export_savedmodel = deprecation.hide_attribute_from_api('...') + """ + + def __init__(self, deprecation_message): + + def raise_error(unused_self): + raise AttributeError(deprecation_message) + + super(HiddenTfApiAttribute, self).__init__(raise_error) + + +hide_attribute_from_api = HiddenTfApiAttribute # pylint: disable=invalid-name + +# TODO(kathywu): Remove once cl/246395236 is submitted. +HIDDEN_ATTRIBUTE = HiddenTfApiAttribute('This attribute has been deprecated.') diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/dispatch.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/dispatch.py new file mode 100644 index 0000000000000000000000000000000000000000..2605c2a17c7695896b0e44168cefc2c7ddbbe574 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/dispatch.py @@ -0,0 +1,1302 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Type-based dispatch for TensorFlow's Python APIs. + +"Python APIs" refers to Python functions that have been exported with +`tf_export`, such as `tf.add` and `tf.linalg.matmul`; they are sometimes also +referred to as "ops". + +There are currently two dispatch systems for TensorFlow: + + * The "fallback dispatch" system calls an API's standard implementation first, + and only tries to perform dispatch if that standard implementation raises a + TypeError (or ValueError) exception. + + * The "type-based dispatch" system checks the types of the parameters passed + to an API, and performs dispatch if those types match any signatures that + have been registered for dispatch. + +The fallback dispatch system was the original dispatch system, but it was +somewhat brittle and had limitations, such as an inability to support dispatch +for some operations (like convert_to_tensor). We plan to remove the fallback +dispatch system in favor of the type-based dispatch system, once all users have +been switched over to use it. + +### Fallback Dispatch + +The fallback dispatch system is based on "operation dispatchers", which can be +used to override the behavior for TensorFlow ops when they are called with +otherwise unsupported argument types. In particular, when an operation is +called with arguments that would cause it to raise a TypeError, it falls back on +its registered operation dispatchers. If any registered dispatchers can handle +the arguments, then its result is returned. Otherwise, the original TypeError is +raised. + +### Type-based Dispatch + +The main interface for the type-based dispatch system is the `dispatch_for_api` +decorator, which overrides the default implementation for a TensorFlow API. +The decorated function (known as the "dispatch target") will override the +default implementation for the API when the API is called with parameters that +match a specified type signature. + +### Dispatch Support + +By default, dispatch support is added to the generated op wrappers for any +visible ops by default. APIs/ops that are implemented in Python can opt in to +dispatch support using the `add_dispatch_support` decorator. +""" + +import collections +import itertools +import typing # pylint: disable=unused-import (used in doctests) + +from tensorflow.python.framework import _pywrap_python_api_dispatcher as _api_dispatcher +from tensorflow.python.framework import ops +from tensorflow.python.util import tf_decorator +from tensorflow.python.util import tf_export as tf_export_lib +from tensorflow.python.util import tf_inspect +from tensorflow.python.util import traceback_utils +from tensorflow.python.util import type_annotations +from tensorflow.python.util.tf_export import tf_export + + +# Private function attributes used to store dispatchers on TensorFlow APIs. +FALLBACK_DISPATCH_ATTR = "_tf_fallback_dispatchers" +TYPE_BASED_DISPATCH_ATTR = "_tf_type_based_dispatcher" + +# OpDispatchers which should be used for all operations. +_GLOBAL_DISPATCHERS = [] + + +################################################################################ +# Fallback Dispatch +################################################################################ + + +@tf_export("__internal__.dispatch.OpDispatcher", v1=[]) +class OpDispatcher(object): + """Abstract base class for TensorFlow operator dispatchers. + + Each operation dispatcher acts as an override handler for a single + TensorFlow operation, and its results are used when the handler indicates + that it can handle the operation's arguments (by returning any value other + than `OpDispatcher.NOT_SUPPORTED`). + """ + + # Sentinel value that can be returned to indicate that an operation + # dispatcher does not support a given set of arguments. + NOT_SUPPORTED = object() + + def handle(self, args, kwargs): # pylint: disable=unused-argument + """Handle this dispatcher's operation with the specified arguments. + + If this operation dispatcher can handle the given arguments, then + return an appropriate value (or raise an appropriate exception). + + Args: + args: The arguments to the operation. + kwargs: They keyword arguments to the operation. + + Returns: + The result of the operation, or `OpDispatcher.NOT_SUPPORTED` if this + dispatcher can not handle the given arguments. + """ + return self.NOT_SUPPORTED + + def register(self, op): + """Register this dispatcher as a handler for `op`. + + Args: + op: Python function: the TensorFlow operation that should be handled. Must + have a dispatch list (which is added automatically for generated ops, + and can be added to Python ops using the `add_dispatch_support` + decorator). + """ + if not hasattr(op, FALLBACK_DISPATCH_ATTR): + raise AssertionError("Dispatching not enabled for %s" % op) + getattr(op, FALLBACK_DISPATCH_ATTR).append(self) + + +@tf_export("__internal__.dispatch.GlobalOpDispatcher", v1=[]) +class GlobalOpDispatcher(object): + """Abstract base class for TensorFlow global operator dispatchers.""" + + NOT_SUPPORTED = OpDispatcher.NOT_SUPPORTED + + def handle(self, op, args, kwargs): + """Handle the specified operation with the specified arguments.""" + + def register(self): + """Register this dispatcher as a handler for all ops.""" + _GLOBAL_DISPATCHERS.append(self) + + +def dispatch(op, args, kwargs): + """Returns the result from the first successful dispatcher for a given op. + + Calls the `handle` method of each `OpDispatcher` that has been registered + to handle `op`, and returns the value from the first successful handler. + + Args: + op: Python function: the operation to dispatch for. + args: The arguments to the operation. + kwargs: They keyword arguments to the operation. + + Returns: + The result of the operation, or `NOT_SUPPORTED` if no registered + dispatcher can handle the given arguments. + """ + for dispatcher in getattr(op, FALLBACK_DISPATCH_ATTR): + result = dispatcher.handle(args, kwargs) + if result is not OpDispatcher.NOT_SUPPORTED: + return result + for dispatcher in _GLOBAL_DISPATCHERS: + result = dispatcher.handle(op, args, kwargs) + if result is not OpDispatcher.NOT_SUPPORTED: + return result + return OpDispatcher.NOT_SUPPORTED + + +class _TypeBasedDispatcher(OpDispatcher): + """Dispatcher that handles op if any arguments have a specified type. + + Checks the types of the arguments and keyword arguments (including elements + of lists or tuples), and if any argument values have the indicated type(s), + then delegates to an override function. + """ + + def __init__(self, override_func, types): + self._types = types + self._override_func = override_func + + def _handles(self, args, kwargs): + for arg in itertools.chain(args, kwargs.values()): + if (isinstance(arg, self._types) or + (isinstance(arg, (list, tuple)) and + any(isinstance(elt, self._types) for elt in arg))): + return True + return False + + def handle(self, args, kwargs): + if self._handles(args, kwargs): + return self._override_func(*args, **kwargs) + else: + return self.NOT_SUPPORTED + + +def _remove_annotation(sig): + """Removes annotation from a python Signature.""" + parameters = [p.replace(annotation=p.empty) for p in sig.parameters.values()] + return sig.replace(parameters=parameters, return_annotation=sig.empty) + + +def _get_required_param_names(sig): + """Returns a list of required parameter names from a python Signature.""" + params = [] + for p in sig.parameters.values(): + if p.kind == p.VAR_POSITIONAL: + continue + if p.kind == p.VAR_KEYWORD: + continue + if p.default is not p.empty: + continue + params.append(p.name) + return params + + +def get_compatible_func(op, func): + """Returns a compatible function. + + Args: + op: a callable with whose signature the returned function is compatible. + func: a callable which is called by the returned function. + + Returns: + a compatible function, which conducts the actions of `func` but can + be called like `op`, given that: + - the list of required arguments in `func` and `op` are the same. + - there is no override of the default arguments of `op` that are not + supported by `func`. + """ + op_signature = _remove_annotation(tf_inspect.signature(op)) + func_signature = _remove_annotation(tf_inspect.signature(func)) + + # Identitical signatures, no need to apply compatibility fixes. + if op_signature == func_signature: + return func + + # When calling func: + # - Positional args without default must be in the same order. + # - Ignore missing optional arguments from op + + op_pos_names = _get_required_param_names(op_signature) + func_pos_names = _get_required_param_names(func_signature) + + if op_pos_names != func_pos_names: + raise AssertionError( + "The decorated function's non-default arguments must be identical" + " to that of the overridden op." + f" func has {func_pos_names}. op has {op_pos_names}." + ) + + func_missing_params = {} + + for name in set(op_signature.parameters.keys()) - set( + func_signature.parameters.keys() + ): + p = op_signature.parameters[name] + if p.default is p.empty: + raise AssertionError( + "The decorated function's signature must implement all of the" + f" non-default arguments of the overridden op. Argument `{name}` is" + " unimplemented." + ) + func_missing_params[name] = p + + def compatible_func(*args, **kwargs): + bound = op_signature.bind(*args, **kwargs) + for name, param in func_missing_params.items(): + if name not in bound.arguments: + continue + value = bound.arguments.pop(name) + if value is not param.default: + raise AssertionError( + f"Dispatched op is called with argument `{name}` set to a" + " non-default value, which is not supported by the decorated" + " function" + ) + return func(*bound.args, **bound.kwargs) + + return compatible_func + + +# pylint: disable=g-doc-return-or-yield +def dispatch_for_types(op, *types): + """Decorator to declare that a Python function overrides an op for a type. + + The decorated function is used to override `op` if any of the arguments or + keyword arguments (including elements of lists or tuples) have one of the + specified types. + + Example: + + ```python + @dispatch_for_types(math_ops.add, RaggedTensor, RaggedTensorValue) + def ragged_add(x, y, name=None): ... + ``` + + Args: + op: Python function: the operation that should be overridden. + *types: The argument types for which this function should be used. + """ + + def decorator(func): + + _TypeBasedDispatcher(get_compatible_func(op, func), types).register(op) + return func + + return decorator + + +# pylint: enable=g-doc-return-or-yield + + +def add_fallback_dispatch_list(target): + """Decorator that adds a dispatch_list attribute to an op.""" + if hasattr(target, FALLBACK_DISPATCH_ATTR): + raise AssertionError("%s already has a dispatch list" % target) + setattr(target, FALLBACK_DISPATCH_ATTR, []) + return target + + +# Alias for backwards-compatibility. +add_dispatch_list = add_fallback_dispatch_list + + +################################################################################ +# Type-based Dispatch +################################################################################ + + +@tf_export("experimental.dispatch_for_api") +def dispatch_for_api(api, *signatures): + """Decorator that overrides the default implementation for a TensorFlow API. + + The decorated function (known as the "dispatch target") will override the + default implementation for the API when the API is called with parameters that + match a specified type signature. Signatures are specified using dictionaries + that map parameter names to type annotations. E.g., in the following example, + `masked_add` will be called for `tf.add` if both `x` and `y` are + `MaskedTensor`s: + + >>> class MaskedTensor(tf.experimental.ExtensionType): + ... values: tf.Tensor + ... mask: tf.Tensor + + >>> @dispatch_for_api(tf.math.add, {'x': MaskedTensor, 'y': MaskedTensor}) + ... def masked_add(x, y, name=None): + ... return MaskedTensor(x.values + y.values, x.mask & y.mask) + + >>> mt = tf.add(MaskedTensor([1, 2], [True, False]), MaskedTensor(10, True)) + >>> print(f"values={mt.values.numpy()}, mask={mt.mask.numpy()}") + values=[11 12], mask=[ True False] + + If multiple type signatures are specified, then the dispatch target will be + called if any of the signatures match. For example, the following code + registers `masked_add` to be called if `x` is a `MaskedTensor` *or* `y` is + a `MaskedTensor`. + + >>> @dispatch_for_api(tf.math.add, {'x': MaskedTensor}, {'y':MaskedTensor}) + ... def masked_add(x, y): + ... x_values = x.values if isinstance(x, MaskedTensor) else x + ... x_mask = x.mask if isinstance(x, MaskedTensor) else True + ... y_values = y.values if isinstance(y, MaskedTensor) else y + ... y_mask = y.mask if isinstance(y, MaskedTensor) else True + ... return MaskedTensor(x_values + y_values, x_mask & y_mask) + + The type annotations in type signatures may be type objects (e.g., + `MaskedTensor`), `typing.List` values, or `typing.Union` values. For + example, the following will register `masked_concat` to be called if `values` + is a list of `MaskedTensor` values: + + >>> @dispatch_for_api(tf.concat, {'values': typing.List[MaskedTensor]}) + ... def masked_concat(values, axis): + ... return MaskedTensor(tf.concat([v.values for v in values], axis), + ... tf.concat([v.mask for v in values], axis)) + + Each type signature must contain at least one subclass of `tf.CompositeTensor` + (which includes subclasses of `tf.ExtensionType`), and dispatch will only be + triggered if at least one type-annotated parameter contains a + `CompositeTensor` value. This rule avoids invoking dispatch in degenerate + cases, such as the following examples: + + * `@dispatch_for_api(tf.concat, {'values': List[MaskedTensor]})`: Will not + dispatch to the decorated dispatch target when the user calls + `tf.concat([])`. + + * `@dispatch_for_api(tf.add, {'x': Union[MaskedTensor, Tensor], 'y': + Union[MaskedTensor, Tensor]})`: Will not dispatch to the decorated dispatch + target when the user calls `tf.add(tf.constant(1), tf.constant(2))`. + + The dispatch target's signature must match the signature of the API that is + being overridden. In particular, parameters must have the same names, and + must occur in the same order. The dispatch target may optionally elide the + "name" parameter, in which case it will be wrapped with a call to + `tf.name_scope` when appropraite. + + Args: + api: The TensorFlow API to override. + *signatures: Dictionaries mapping parameter names or indices to type + annotations, specifying when the dispatch target should be called. In + particular, the dispatch target will be called if any signature matches; + and a signature matches if all of the specified parameters have types that + match with the indicated type annotations. If no signatures are + specified, then a signature will be read from the dispatch target + function's type annotations. + + Returns: + A decorator that overrides the default implementation for `api`. + + #### Registered APIs + + The TensorFlow APIs that may be overridden by `@dispatch_for_api` are: + + <> + """ + dispatcher = getattr(api, TYPE_BASED_DISPATCH_ATTR, None) + if dispatcher is None: + raise ValueError(f"{api} does not support dispatch.") + + api_signature = tf_inspect.signature(api) + signature_checkers = [ + _make_signature_checker(api_signature, signature) + for signature in signatures + ] + + def decorator(dispatch_target): + """Decorator that registers the given dispatch target.""" + if not callable(dispatch_target): + raise TypeError("Expected dispatch_target to be callable; " + f"got {dispatch_target!r}") + dispatch_target = _add_name_scope_wrapper(dispatch_target, api_signature) + _check_signature(api_signature, dispatch_target) + + for signature_checker in signature_checkers: + dispatcher.Register(signature_checker, dispatch_target) + _TYPE_BASED_DISPATCH_SIGNATURES[api][dispatch_target].extend(signatures) + + if not signature_checkers: + signature = _signature_from_annotations(dispatch_target) + checker = _make_signature_checker(api_signature, signature) + dispatcher.Register(checker, dispatch_target) + _TYPE_BASED_DISPATCH_SIGNATURES[api][dispatch_target].append(signature) + + return dispatch_target + + return decorator + + +# Nested dict mapping `api_func` -> `dispatch_target` -> `List[signature]`, +# which can be used for documentation generation and for improved error messages +# when APIs are called with unsupported types. +_TYPE_BASED_DISPATCH_SIGNATURES = {} + + +def apis_with_type_based_dispatch(): + """Returns a list of TensorFlow APIs that support type-based dispatch.""" + return sorted( + _TYPE_BASED_DISPATCH_SIGNATURES, + key=lambda api: f"{api.__module__}.{api.__name__}") + + +def type_based_dispatch_signatures_for(cls): + """Returns dispatch signatures that have been registered for a given class. + + This function is intended for documentation-generation purposes. + + Args: + cls: The class to search for. Type signatures are searched recursively, so + e.g., if `cls=RaggedTensor`, then information will be returned for all + dispatch targets that have `RaggedTensor` anywhere in their type + annotations (including nested in `typing.Union` or `typing.List`.) + + Returns: + A `dict` mapping `api` -> `signatures`, where `api` is a TensorFlow API + function; and `signatures` is a list of dispatch signatures for `api` + that include `cls`. (Each signature is a dict mapping argument names to + type annotations; see `dispatch_for_api` for more info.) + """ + + def contains_cls(x): + """Returns true if `x` contains `cls`.""" + if isinstance(x, dict): + return any(contains_cls(v) for v in x.values()) + elif x is cls: + return True + elif (type_annotations.is_generic_list(x) or + type_annotations.is_generic_union(x)): + type_args = type_annotations.get_generic_type_args(x) + return any(contains_cls(arg) for arg in type_args) + else: + return False + + result = {} + for api, api_signatures in _TYPE_BASED_DISPATCH_SIGNATURES.items(): + for _, signatures in api_signatures.items(): + filtered = list(filter(contains_cls, signatures)) + if filtered: + result.setdefault(api, []).extend(filtered) + return result + + +# TODO(edloper): Consider using a mechanism like this to automatically add +# the `name` argument to all TensorFlow APIs that are implemented in Python +# (so each Python function doesn't need to do it manually). +def _add_name_scope_wrapper(func, api_signature): + """Wraps `func` to expect a "name" arg, and use it to call `ops.name_scope`. + + If `func` already expects a "name" arg, or if `api_signature` does not + expect a "name" arg, then returns `func` as-is. + + Args: + func: The function to wrap. Signature must match `api_signature` (except + the "name" parameter may be missing. + api_signature: The signature of the original API (used to find the index for + the "name" parameter). + + Returns: + The wrapped function (or the original function if no wrapping is needed). + """ + if "name" not in api_signature.parameters: + return func # no wrapping needed (API has no name parameter). + + func_signature = tf_inspect.signature(func) + func_argspec = tf_inspect.getargspec(func) + if "name" in func_signature.parameters or func_argspec.keywords is not None: + return func # No wrapping needed (already has name parameter). + + name_index = list(api_signature.parameters).index("name") + + def wrapped_func(*args, **kwargs): + if name_index < len(args): + name = args[name_index] + args = args[:name_index] + args[name_index + 1:] + else: + name = kwargs.pop("name", None) + if name is None: + return func(*args, **kwargs) + else: + with ops.name_scope(name): + return func(*args, **kwargs) + + wrapped_func = tf_decorator.make_decorator(func, wrapped_func) + wrapped_func.__signature__ = func_signature.replace( + parameters=(list(func_signature.parameters.values()) + + [api_signature.parameters["name"]])) + del wrapped_func._tf_decorator + return wrapped_func + + +@tf_export("experimental.unregister_dispatch_for") +def unregister_dispatch_for(dispatch_target): + """Unregisters a function that was registered with `@dispatch_for_*`. + + This is primarily intended for testing purposes. + + Example: + + >>> # Define a type and register a dispatcher to override `tf.abs`: + >>> class MyTensor(tf.experimental.ExtensionType): + ... value: tf.Tensor + >>> @tf.experimental.dispatch_for_api(tf.abs) + ... def my_abs(x: MyTensor): + ... return MyTensor(tf.abs(x.value)) + >>> tf.abs(MyTensor(5)) + MyTensor(value=) + + >>> # Unregister the dispatcher, so `tf.abs` no longer calls `my_abs`. + >>> unregister_dispatch_for(my_abs) + >>> tf.abs(MyTensor(5)) + Traceback (most recent call last): + ... + ValueError: Attempt to convert a value ... to a Tensor. + + Args: + dispatch_target: The function to unregister. + + Raises: + ValueError: If `dispatch_target` was not registered using `@dispatch_for`, + `@dispatch_for_unary_elementwise_apis`, or + `@dispatch_for_binary_elementwise_apis`. + """ + found = False + + # Check if dispatch_target registered by `@dispatch_for_api` + for api, signatures in _TYPE_BASED_DISPATCH_SIGNATURES.items(): + if dispatch_target in signatures: + dispatcher = getattr(api, TYPE_BASED_DISPATCH_ATTR) + dispatcher.Unregister(dispatch_target) + del signatures[dispatch_target] + found = True + + # Check if dispatch_target registered by `@dispatch_for_*_elementwise_apis` + elementwise_keys_to_delete = [ + key for (key, handler) in _ELEMENTWISE_API_HANDLERS.items() + if handler is dispatch_target + ] + for key in set(elementwise_keys_to_delete): + for _, target in _ELEMENTWISE_API_TARGETS[key]: + unregister_dispatch_for(target) + del _ELEMENTWISE_API_HANDLERS[key] + del _ELEMENTWISE_API_TARGETS[key] + found = True + + if not found: + raise ValueError(f"Function {dispatch_target} was not registered using " + "a `@dispatch_for_*` decorator.") + + +def register_dispatchable_type(cls): + """Class decorator that registers a type for use with type-based dispatch. + + Should *not* be used with subclasses of `CompositeTensor` or `ExtensionType` + (which are automatically registered). + + Note: this function is intended to support internal legacy use cases (such + as RaggedTensorValue), and will probably not be exposed as a public API. + + Args: + cls: The class to register. + + Returns: + `cls`. + """ + _api_dispatcher.register_dispatchable_type(cls) + return cls + + +def add_type_based_api_dispatcher(target): + """Adds a PythonAPIDispatcher to the given TensorFlow API function.""" + if hasattr(target, TYPE_BASED_DISPATCH_ATTR): + raise ValueError(f"{target} already has a type-based API dispatcher.") + + _, unwrapped = tf_decorator.unwrap(target) + target_argspec = tf_inspect.getargspec(unwrapped) + if target_argspec.varargs or target_argspec.keywords: + # @TODO(b/194903203) Add v2 dispatch support for APIs that take varargs + # and keywords. Examples of APIs that take varargs and kwargs: meshgrid, + # einsum, map_values, map_flat_values. + return target + + setattr( + target, TYPE_BASED_DISPATCH_ATTR, + _api_dispatcher.PythonAPIDispatcher(unwrapped.__name__, + target_argspec.args, + target_argspec.defaults)) + _TYPE_BASED_DISPATCH_SIGNATURES[target] = collections.defaultdict(list) + return target + + +def _check_signature(api_signature, func): + """Checks that a dispatch target's signature is compatible with an API. + + Args: + api_signature: The signature of the TensorFlow API. + func: The dispatch target. + + Raises: + ValueError: if the signatures are incompatible. Two signatures are + considered compatible if they have the same number of parameters, and all + corresponding parameters have the same `name` and `kind`. (Parameters + are not required to have the same default value or the same annotation.) + """ + # Special case: if func_signature is (*args, **kwargs), then assume it's ok. + func_argspec = tf_inspect.getargspec(func) + if (func_argspec.varargs is not None and func_argspec.keywords is not None + and not func_argspec.args): + return + + func_signature = tf_inspect.signature(func) + ok = len(api_signature.parameters) == len(func_signature.parameters) + if ok: + for param_1, param_2 in zip(api_signature.parameters.values(), + func_signature.parameters.values()): + if (param_1.name != param_2.name) or (param_1.kind != param_2.kind): + ok = False + if not ok: + raise ValueError(f"Dispatch function's signature {func_signature} does " + f"not match API's signature {api_signature}.") + + +def _make_signature_checker(api_signature, signature): + """Builds a PySignatureChecker for the given type signature. + + Args: + api_signature: The `inspect.Signature` of the API whose signature is + being checked. + signature: Dictionary mapping parameter names to type annotations. + + Returns: + A `PySignatureChecker`. + """ + if not (isinstance(signature, dict) and + all(isinstance(k, (str, int)) for k in signature)): + raise TypeError("signatures must be dictionaries mapping parameter names " + "to type annotations.") + checkers = [] + + param_names = list(api_signature.parameters) + for param_name, param_type in signature.items(): + # Convert positional parameters to named parameters. + if (isinstance(param_name, int) and + param_name < len(api_signature.parameters)): + param_name = list(api_signature.parameters.values())[param_name].name + + # Check that the parameter exists, and has an appropriate kind. + param = api_signature.parameters.get(param_name, None) + if param is None: + raise ValueError("signature includes annotation for unknown " + f"parameter {param_name!r}.") + if param.kind not in (tf_inspect.Parameter.POSITIONAL_ONLY, + tf_inspect.Parameter.POSITIONAL_OR_KEYWORD): + raise ValueError("Dispatch currently only supports type annotations " + "for positional parameters; can't handle annotation " + f"for {param.kind!r} parameter {param_name}.") + + checker = make_type_checker(param_type) + index = param_names.index(param_name) + checkers.append((index, checker)) + + return _api_dispatcher.PySignatureChecker(checkers) + + +# Cache for InstanceTypeChecker objects (we only want to create one +# InstanceTypeChecker for each type, since each one uses an internal cache +# to avoid repeated calls back into Python's isinstance). +_is_instance_checker_cache = {} + + +def make_type_checker(annotation): + """Builds a PyTypeChecker for the given type annotation.""" + if type_annotations.is_generic_union(annotation): + type_args = type_annotations.get_generic_type_args(annotation) + + # If the union contains two or more simple types, then use a single + # InstanceChecker to check them. + simple_types = [t for t in type_args if isinstance(t, type)] + simple_types = tuple(sorted(simple_types, key=id)) + if len(simple_types) > 1: + if simple_types not in _is_instance_checker_cache: + checker = _api_dispatcher.MakeInstanceChecker(*simple_types) + _is_instance_checker_cache[simple_types] = checker + options = ([_is_instance_checker_cache[simple_types]] + + [make_type_checker(t) for t in type_args + if not isinstance(t, type)]) + return _api_dispatcher.MakeUnionChecker(options) + + options = [make_type_checker(t) for t in type_args] + return _api_dispatcher.MakeUnionChecker(options) + + elif type_annotations.is_generic_list(annotation): + type_args = type_annotations.get_generic_type_args(annotation) + if len(type_args) != 1: + raise AssertionError("Expected List[...] to have a single type parameter") + elt_type = make_type_checker(type_args[0]) + return _api_dispatcher.MakeListChecker(elt_type) + + elif isinstance(annotation, type): + if annotation not in _is_instance_checker_cache: + checker = _api_dispatcher.MakeInstanceChecker(annotation) + _is_instance_checker_cache[annotation] = checker + return _is_instance_checker_cache[annotation] + + elif annotation is None: + return make_type_checker(type(None)) + + else: + raise ValueError(f"Type annotation {annotation} is not currently supported" + " by dispatch. Supported annotations: type objects, " + " List[...], and Union[...]") + + +def _signature_from_annotations(func): + """Builds a dict mapping from parameter names to type annotations.""" + func_signature = tf_inspect.signature(func) + + signature = dict([(name, param.annotation) + for (name, param) in func_signature.parameters.items() + if param.annotation != tf_inspect.Parameter.empty]) + if not signature: + raise ValueError("The dispatch_for_api decorator must be called with at " + "least one signature, or applied to a function that " + "has type annotations on its parameters.") + return signature + + +# Registries for elementwise APIs and API handlers. +# +# _*_ELEMENTWISE_APIS: A list of TensorFlow APIs that have been registered +# as elementwise operations using the `register_*_elementwise_api` +# decorators. +# +# _ELEMENTWISE_API_HANDLERS: Dicts mapping from argument type(s) to API +# handlers that have been registered with the `dispatch_for_*_elementwise_apis` +# decorators. +# +# _ELEMENTWISE_API_TARGETS: Dict mapping from argument type(s) to lists of +# `(api, dispatch_target)` pairs. Used to impelement +# `unregister_elementwise_api_handler`. +_UNARY_ELEMENTWISE_APIS = [] +_BINARY_ELEMENTWISE_APIS = [] +_BINARY_ELEMENTWISE_ASSERT_APIS = [] +_ELEMENTWISE_API_HANDLERS = {} +_ELEMENTWISE_API_TARGETS = {} + +_ASSERT_API_TAG = "ASSERT_API_TAG" + + +@tf_export("experimental.dispatch_for_unary_elementwise_apis") +def dispatch_for_unary_elementwise_apis(x_type): + """Decorator to override default implementation for unary elementwise APIs. + + The decorated function (known as the "elementwise api handler") overrides + the default implementation for any unary elementwise API whenever the value + for the first argument (typically named `x`) matches the type annotation + `x_type`. The elementwise api handler is called with two arguments: + + `elementwise_api_handler(api_func, x)` + + Where `api_func` is a function that takes a single parameter and performs the + elementwise operation (e.g., `tf.abs`), and `x` is the first argument to the + elementwise api. + + The following example shows how this decorator can be used to update all + unary elementwise operations to handle a `MaskedTensor` type: + + >>> class MaskedTensor(tf.experimental.ExtensionType): + ... values: tf.Tensor + ... mask: tf.Tensor + >>> @dispatch_for_unary_elementwise_apis(MaskedTensor) + ... def unary_elementwise_api_handler(api_func, x): + ... return MaskedTensor(api_func(x.values), x.mask) + >>> mt = MaskedTensor([1, -2, -3], [True, False, True]) + >>> abs_mt = tf.abs(mt) + >>> print(f"values={abs_mt.values.numpy()}, mask={abs_mt.mask.numpy()}") + values=[1 2 3], mask=[ True False True] + + For unary elementwise operations that take extra arguments beyond `x`, those + arguments are *not* passed to the elementwise api handler, but are + automatically added when `api_func` is called. E.g., in the following + example, the `dtype` parameter is not passed to + `unary_elementwise_api_handler`, but is added by `api_func`. + + >>> ones_mt = tf.ones_like(mt, dtype=tf.float32) + >>> print(f"values={ones_mt.values.numpy()}, mask={ones_mt.mask.numpy()}") + values=[1.0 1.0 1.0], mask=[ True False True] + + Args: + x_type: A type annotation indicating when the api handler should be called. + See `dispatch_for_api` for a list of supported annotation types. + + Returns: + A decorator. + + #### Registered APIs + + The unary elementwise APIs are: + + <> + """ + + def decorator(handler): + if (x_type,) in _ELEMENTWISE_API_HANDLERS: + raise ValueError("A unary elementwise dispatch handler " + f"({_ELEMENTWISE_API_HANDLERS[(x_type,)]}) " + f"has already been registered for {x_type}.") + _ELEMENTWISE_API_HANDLERS[(x_type,)] = handler + for api in _UNARY_ELEMENTWISE_APIS: + _add_dispatch_for_unary_elementwise_api(api, x_type, handler) + + return handler + + return decorator + + +@tf_export("experimental.dispatch_for_binary_elementwise_apis") +def dispatch_for_binary_elementwise_apis(x_type, y_type): + """Decorator to override default implementation for binary elementwise APIs. + + The decorated function (known as the "elementwise api handler") overrides + the default implementation for any binary elementwise API whenever the value + for the first two arguments (typically named `x` and `y`) match the specified + type annotations. The elementwise api handler is called with two arguments: + + `elementwise_api_handler(api_func, x, y)` + + Where `x` and `y` are the first two arguments to the elementwise api, and + `api_func` is a TensorFlow function that takes two parameters and performs the + elementwise operation (e.g., `tf.add`). + + The following example shows how this decorator can be used to update all + binary elementwise operations to handle a `MaskedTensor` type: + + >>> class MaskedTensor(tf.experimental.ExtensionType): + ... values: tf.Tensor + ... mask: tf.Tensor + >>> @dispatch_for_binary_elementwise_apis(MaskedTensor, MaskedTensor) + ... def binary_elementwise_api_handler(api_func, x, y): + ... return MaskedTensor(api_func(x.values, y.values), x.mask & y.mask) + >>> a = MaskedTensor([1, 2, 3, 4, 5], [True, True, True, True, False]) + >>> b = MaskedTensor([2, 4, 6, 8, 0], [True, True, True, False, True]) + >>> c = tf.add(a, b) + >>> print(f"values={c.values.numpy()}, mask={c.mask.numpy()}") + values=[ 3 6 9 12 5], mask=[ True True True False False] + + Args: + x_type: A type annotation indicating when the api handler should be called. + y_type: A type annotation indicating when the api handler should be called. + + Returns: + A decorator. + + #### Registered APIs + + The binary elementwise APIs are: + + <> + """ + + def decorator(handler): + if (x_type, y_type) in _ELEMENTWISE_API_HANDLERS: + raise ValueError("A binary elementwise dispatch handler " + f"({_ELEMENTWISE_API_HANDLERS[x_type, y_type]}) " + f"has already been registered for ({x_type}, {y_type}).") + _ELEMENTWISE_API_HANDLERS[x_type, y_type] = handler + for api in _BINARY_ELEMENTWISE_APIS: + _add_dispatch_for_binary_elementwise_api(api, x_type, y_type, handler) + + return handler + + return decorator + + +@tf_export("experimental.dispatch_for_binary_elementwise_assert_apis") +def dispatch_for_binary_elementwise_assert_apis(x_type, y_type): + """Decorator to override default implementation for binary elementwise assert APIs. + + The decorated function (known as the "elementwise assert handler") + overrides the default implementation for any binary elementwise assert API + whenever the value for the first two arguments (typically named `x` and `y`) + match the specified type annotations. The handler is called with two + arguments: + + `elementwise_assert_handler(assert_func, x, y)` + + Where `x` and `y` are the first two arguments to the binary elementwise assert + operation, and `assert_func` is a TensorFlow function that takes two + parameters and performs the elementwise assert operation (e.g., + `tf.debugging.assert_equal`). + + The following example shows how this decorator can be used to update all + binary elementwise assert operations to handle a `MaskedTensor` type: + + >>> class MaskedTensor(tf.experimental.ExtensionType): + ... values: tf.Tensor + ... mask: tf.Tensor + >>> @dispatch_for_binary_elementwise_assert_apis(MaskedTensor, MaskedTensor) + ... def binary_elementwise_assert_api_handler(assert_func, x, y): + ... merged_mask = tf.logical_and(x.mask, y.mask) + ... selected_x_values = tf.boolean_mask(x.values, merged_mask) + ... selected_y_values = tf.boolean_mask(y.values, merged_mask) + ... assert_func(selected_x_values, selected_y_values) + >>> a = MaskedTensor([1, 1, 0, 1, 1], [False, False, True, True, True]) + >>> b = MaskedTensor([2, 2, 0, 2, 2], [True, True, True, False, False]) + >>> tf.debugging.assert_equal(a, b) # assert passed; no exception was thrown + + >>> a = MaskedTensor([1, 1, 1, 1, 1], [True, True, True, True, True]) + >>> b = MaskedTensor([0, 0, 0, 0, 2], [True, True, True, True, True]) + >>> tf.debugging.assert_greater(a, b) + Traceback (most recent call last): + ... + InvalidArgumentError: Condition x > y did not hold. + + Args: + x_type: A type annotation indicating when the api handler should be called. + y_type: A type annotation indicating when the api handler should be called. + + Returns: + A decorator. + + #### Registered APIs + + The binary elementwise assert APIs are: + + <> + """ + + def decorator(handler): + api_handler_key = (x_type, y_type, _ASSERT_API_TAG) + if api_handler_key in _ELEMENTWISE_API_HANDLERS: + raise ValueError("A binary elementwise assert dispatch handler " + f"({_ELEMENTWISE_API_HANDLERS[api_handler_key]}) " + f"has already been registered for ({x_type}, {y_type}).") + _ELEMENTWISE_API_HANDLERS[api_handler_key] = handler + for api in _BINARY_ELEMENTWISE_ASSERT_APIS: + _add_dispatch_for_binary_elementwise_api(api, x_type, y_type, handler) + + return handler + + return decorator + + +def register_unary_elementwise_api(func): + """Decorator that registers a TensorFlow op as a unary elementwise API.""" + _UNARY_ELEMENTWISE_APIS.append(func) + for args, handler in _ELEMENTWISE_API_HANDLERS.items(): + if len(args) == 1: + _add_dispatch_for_unary_elementwise_api(func, args[0], handler) + return func + + +def register_binary_elementwise_api(func): + """Decorator that registers a TensorFlow op as a binary elementwise API.""" + _BINARY_ELEMENTWISE_APIS.append(func) + for args, handler in _ELEMENTWISE_API_HANDLERS.items(): + if len(args) == 2: + _add_dispatch_for_binary_elementwise_api(func, args[0], args[1], handler) + return func + + +def register_binary_elementwise_assert_api(func): + """Decorator that registers a TensorFlow op as a binary elementwise assert API. + + Different from `dispatch_for_binary_elementwise_apis`, this decorator is used + for assert apis, such as assert_equal, assert_none_equal, etc, which return + None in eager mode and an op in graph mode. + + Args: + func: The function that implements the binary elementwise assert API. + + Returns: + `func` + """ + _BINARY_ELEMENTWISE_ASSERT_APIS.append(func) + for args, handler in _ELEMENTWISE_API_HANDLERS.items(): + if len(args) == 3 and args[2] is _ASSERT_API_TAG: + _add_dispatch_for_binary_elementwise_api(func, args[0], args[1], handler) + return func + + +def unary_elementwise_apis(): + """Returns a list of APIs that have been registered as unary elementwise.""" + return tuple(_UNARY_ELEMENTWISE_APIS) + + +def binary_elementwise_apis(): + """Returns a list of APIs that have been registered as binary elementwise.""" + return tuple(_BINARY_ELEMENTWISE_APIS) + + +def _add_dispatch_for_unary_elementwise_api(api, x_type, + elementwise_api_handler): + """Registers a unary elementwise handler as a dispatcher for a given API.""" + api_signature = tf_inspect.signature(api) + x_name = list(api_signature.parameters)[0] + name_index = _find_name_index(api_signature) + + need_to_bind_api_args = ( + len(api_signature.parameters) > 2 or + "name" not in api_signature.parameters) + + @dispatch_for_api(api, {x_name: x_type}) + def dispatch_target(*args, **kwargs): + args, kwargs, name = _extract_name_arg(args, kwargs, name_index) + if args: + x, args = args[0], args[1:] + else: + x = kwargs.pop(x_name) + + if need_to_bind_api_args: + tensor_api = lambda v: api(v, *args, **kwargs) + else: + tensor_api = api + + if name is None: + return elementwise_api_handler(tensor_api, x) + else: + with ops.name_scope(name, None, [x]): + return elementwise_api_handler(tensor_api, x) + + dispatch_target.__name__ = "elementwise_dispatch_target_for_" + api.__name__ + dispatch_target.__qualname__ = dispatch_target.__name__ + # Keep track of what targets we've registered (so we can unregister them). + target_list = _ELEMENTWISE_API_TARGETS.setdefault((x_type,), []) + target_list.append((api, dispatch_target)) + + +def _add_dispatch_for_binary_elementwise_api(api, x_type, y_type, + elementwise_api_handler): + """Registers a binary elementwise handler as a dispatcher for a given API.""" + api_signature = tf_inspect.signature(api) + x_name, y_name = list(api_signature.parameters)[:2] + name_index = _find_name_index(api_signature) + + need_to_bind_api_args = (len(api_signature.parameters) > 3 or + "name" not in api_signature.parameters) + + @dispatch_for_api(api, {x_name: x_type, y_name: y_type}) + def dispatch_target(*args, **kwargs): + args, kwargs, name = _extract_name_arg(args, kwargs, name_index) + if len(args) > 1: + x, y, args = args[0], args[1], args[2:] + elif args: + x, args = args[0], args[1:] + y = kwargs.pop(y_name, None) + else: + x = kwargs.pop(x_name, None) + y = kwargs.pop(y_name, None) + + if need_to_bind_api_args: + tensor_api = lambda v1, v2: api(v1, v2, *args, **kwargs) + else: + tensor_api = api + + if name is None: + return elementwise_api_handler(tensor_api, x, y) + else: + with ops.name_scope(name, None, [x, y]): + return elementwise_api_handler(tensor_api, x, y) + + dispatch_target.__name__ = "elementwise_dispatch_target_for_" + api.__name__ + dispatch_target.__qualname__ = dispatch_target.__name__ + # Keep track of what targets we've registered (so we can unregister them). + target_list = _ELEMENTWISE_API_TARGETS.setdefault((x_type, y_type), []) + target_list.append((api, dispatch_target)) + + +def _find_name_index(signature): + """Returns the index of the `name` parameter, or -1 if it's not present.""" + try: + return list(signature.parameters).index("name") + except ValueError: + return -1 + + +def _extract_name_arg(args, kwargs, name_index): + """Extracts the parameter `name` and returns `(args, kwargs, name_value)`.""" + if name_index < 0: + name_value = None + elif name_index < len(args): + name_value = args[name_index] + args = args[:name_index] + args[name_index + 1:] + else: + name_value = kwargs.pop("name", None) + return args, kwargs, name_value + + +def update_docstrings_with_api_lists(): + """Updates the docstrings of dispatch decorators with API lists. + + Updates docstrings for `dispatch_for_api`, + `dispatch_for_unary_elementwise_apis`, and + `dispatch_for_binary_elementwise_apis`, by replacing the string '<>' + with a list of APIs that have been registered for that decorator. + """ + _update_docstring_with_api_list(dispatch_for_unary_elementwise_apis, + _UNARY_ELEMENTWISE_APIS) + _update_docstring_with_api_list(dispatch_for_binary_elementwise_apis, + _BINARY_ELEMENTWISE_APIS) + _update_docstring_with_api_list(dispatch_for_binary_elementwise_assert_apis, + _BINARY_ELEMENTWISE_ASSERT_APIS) + _update_docstring_with_api_list(dispatch_for_api, + _TYPE_BASED_DISPATCH_SIGNATURES) + + +def _update_docstring_with_api_list(target, api_list): + """Replaces `<>` in target.__doc__ with the given list of APIs.""" + lines = [] + for func in api_list: + name = tf_export_lib.get_canonical_name_for_symbol( + func, add_prefix_to_v1_names=True) + if name is not None: + params = tf_inspect.signature(func).parameters.keys() + lines.append(f" * `tf.{name}({', '.join(params)})`") + lines.sort() + target.__doc__ = target.__doc__.replace(" <>", "\n".join(lines)) + + +################################################################################ +# Dispatch Support +################################################################################ +@tf_export("__internal__.dispatch.add_dispatch_support", v1=[]) +def add_dispatch_support(target=None, iterable_parameters=None): + """Decorator that adds a dispatch handling wrapper to a TensorFlow Python API. + + This wrapper adds the decorated function as an API that can be overridden + using the `@dispatch_for_api` decorator. In the following example, we first + define a new API (`double`) that supports dispatch, then define a custom type + (`MaskedTensor`) and finally use `dispatch_for_api` to override the default + implementation of `double` when called with `MaskedTensor` values: + + >>> @add_dispatch_support + ... def double(x): + ... return x * 2 + >>> class MaskedTensor(tf.experimental.ExtensionType): + ... values: tf.Tensor + ... mask: tf.Tensor + >>> @dispatch_for_api(double, {'x': MaskedTensor}) + ... def masked_double(x): + ... return MaskedTensor(x.values * 2, y.mask) + + The optional `iterable_parameter` argument can be used to mark parameters that + can take arbitrary iterable values (such as generator expressions). These + need to be handled specially during dispatch, since just iterating over an + iterable uses up its values. In the following example, we define a new API + whose second argument can be an iterable value; and then override the default + implementatio of that API when the iterable contains MaskedTensors: + + >>> @add_dispatch_support(iterable_parameters=['ys']) + ... def add_tensor_to_list_of_tensors(x, ys): + ... return [x + y for y in ys] + >>> @dispatch_for_api(add_tensor_to_list_of_tensors, + ... {'ys': typing.List[MaskedTensor]}) + ... def masked_add_tensor_to_list_of_tensors(x, ys): + ... return [MaskedTensor(x+y.values, y.mask) for y in ys] + + (Note: the only TensorFlow API that currently supports iterables is `add_n`.) + + Args: + target: The TensorFlow API that should support dispatch. + iterable_parameters: Optional list of parameter names that may be called + with iterables (such as the `inputs` parameter for `tf.add_n`). + + Returns: + A decorator. + """ + + if not (iterable_parameters is None or + (isinstance(iterable_parameters, (list, tuple)) and + all(isinstance(p, str) for p in iterable_parameters))): + raise TypeError("iterable_parameters should be a list or tuple of string.") + + def decorator(dispatch_target): + + # Get the name & index for each iterable parameter. + if iterable_parameters is None: + iterable_params = None + else: + arg_names = tf_inspect.getargspec(dispatch_target).args + iterable_params = [ + (name, arg_names.index(name)) for name in iterable_parameters + ] + + @traceback_utils.filter_traceback + def op_dispatch_handler(*args, **kwargs): + """Call `dispatch_target`, peforming dispatch when appropriate.""" + + # Type-based dispatch system (dispatch v2): + if api_dispatcher is not None: + if iterable_params is not None: + args, kwargs = replace_iterable_params(args, kwargs, iterable_params) + result = api_dispatcher.Dispatch(args, kwargs) + if result is not NotImplemented: + return result + + # Fallback dispatch system (dispatch v1): + try: + return dispatch_target(*args, **kwargs) + except (TypeError, ValueError): + # Note: convert_to_eager_tensor currently raises a ValueError, not a + # TypeError, when given unexpected types. So we need to catch both. + result = dispatch(op_dispatch_handler, args, kwargs) + if result is not OpDispatcher.NOT_SUPPORTED: + return result + else: + raise + + add_fallback_dispatch_list(op_dispatch_handler) + op_dispatch_handler = tf_decorator.make_decorator(dispatch_target, + op_dispatch_handler) + add_type_based_api_dispatcher(op_dispatch_handler) + api_dispatcher = getattr(op_dispatch_handler, TYPE_BASED_DISPATCH_ATTR, + None) + return op_dispatch_handler + + if target is None: + return decorator + else: + return decorator(target) + + +def replace_iterable_params(args, kwargs, iterable_params): + """Returns (args, kwargs) with any iterable parameters converted to lists. + + Args: + args: Positional rguments to a function + kwargs: Keyword arguments to a function. + iterable_params: A list of (name, index) tuples for iterable parameters. + + Returns: + A tuple (args, kwargs), where any positional or keyword parameters in + `iterable_params` have their value converted to a `list`. + """ + args = list(args) + for name, index in iterable_params: + if index < len(args): + args[index] = list(args[index]) + elif name in kwargs: + kwargs[name] = list(kwargs[name]) + return tuple(args), kwargs diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/example_parser_configuration.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/example_parser_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..fbbc0e66169971ee921cf682adb9c2524fe14f30 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/example_parser_configuration.py @@ -0,0 +1,206 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Extract parse_example op configuration to a proto.""" + +from tensorflow.core.example import example_parser_configuration_pb2 +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_util + + +def extract_example_parser_configuration(parse_example_op, sess): + """Returns an ExampleParserConfig proto. + + Args: + parse_example_op: A ParseExample or ParseExampleV2 `Operation` + sess: A tf.compat.v1.Session needed to obtain some configuration values. + Returns: + A ExampleParserConfig proto. + + Raises: + ValueError: If attributes are inconsistent. + """ + if parse_example_op.type == "ParseExample": + return _extract_from_parse_example(parse_example_op, sess) + elif parse_example_op.type == "ParseExampleV2": + return _extract_from_parse_example_v2(parse_example_op, sess) + else: + raise ValueError( + "Found unexpected type when parsing example. Expected `ParseExample` " + f"object. Received type: {parse_example_op.type}") + + +def _extract_from_parse_example(parse_example_op, sess): + """Extract ExampleParserConfig from ParseExample op.""" + config = example_parser_configuration_pb2.ExampleParserConfiguration() + + num_sparse = parse_example_op.get_attr("Nsparse") + num_dense = parse_example_op.get_attr("Ndense") + total_features = num_dense + num_sparse + + sparse_types = parse_example_op.get_attr("sparse_types") + dense_types = parse_example_op.get_attr("Tdense") + dense_shapes = parse_example_op.get_attr("dense_shapes") + + if len(sparse_types) != num_sparse: + raise ValueError("len(sparse_types) attribute does not match " + "Nsparse attribute (%d vs %d)" % + (len(sparse_types), num_sparse)) + + if len(dense_types) != num_dense: + raise ValueError("len(dense_types) attribute does not match " + "Ndense attribute (%d vs %d)" % + (len(dense_types), num_dense)) + + if len(dense_shapes) != num_dense: + raise ValueError("len(dense_shapes) attribute does not match " + "Ndense attribute (%d vs %d)" % + (len(dense_shapes), num_dense)) + + # Skip over the serialized input, and the names input. + fetch_list = parse_example_op.inputs[2:] + + # Fetch total_features key names and num_dense default values. + if len(fetch_list) != (total_features + num_dense): + raise ValueError("len(fetch_list) does not match total features + " + "num_dense (%d vs %d)" % + (len(fetch_list), (total_features + num_dense))) + + fetched = sess.run(fetch_list) + + if len(fetched) != len(fetch_list): + raise ValueError("len(fetched) does not match len(fetch_list) " + "(%d vs %d)" % (len(fetched), len(fetch_list))) + + # Fetch indices. + sparse_keys_start = 0 + dense_keys_start = sparse_keys_start + num_sparse + dense_def_start = dense_keys_start + num_dense + + # Output tensor indices. + sparse_indices_start = 0 + sparse_values_start = num_sparse + sparse_shapes_start = sparse_values_start + num_sparse + dense_values_start = sparse_shapes_start + num_sparse + + # Dense features. + for i in range(num_dense): + key = fetched[dense_keys_start + i] + feature_config = config.feature_map[key] + # Convert the default value numpy array fetched from the session run + # into a TensorProto. + fixed_config = feature_config.fixed_len_feature + + fixed_config.default_value.CopyFrom( + tensor_util.make_tensor_proto(fetched[dense_def_start + i])) + # Convert the shape from the attributes + # into a TensorShapeProto. + fixed_config.shape.CopyFrom( + tensor_shape.TensorShape(dense_shapes[i]).as_proto()) + + fixed_config.dtype = dense_types[i].as_datatype_enum + # Get the output tensor name. + fixed_config.values_output_tensor_name = parse_example_op.outputs[ + dense_values_start + i].name + + # Sparse features. + for i in range(num_sparse): + key = fetched[sparse_keys_start + i] + feature_config = config.feature_map[key] + var_len_feature = feature_config.var_len_feature + var_len_feature.dtype = sparse_types[i].as_datatype_enum + var_len_feature.indices_output_tensor_name = parse_example_op.outputs[ + sparse_indices_start + i].name + var_len_feature.values_output_tensor_name = parse_example_op.outputs[ + sparse_values_start + i].name + var_len_feature.shapes_output_tensor_name = parse_example_op.outputs[ + sparse_shapes_start + i].name + + return config + + +def _extract_from_parse_example_v2(parse_example_op, sess): + """Extract ExampleParserConfig from ParseExampleV2 op.""" + config = example_parser_configuration_pb2.ExampleParserConfiguration() + + dense_types = parse_example_op.get_attr("Tdense") + num_sparse = parse_example_op.get_attr("num_sparse") + sparse_types = parse_example_op.get_attr("sparse_types") + ragged_value_types = parse_example_op.get_attr("ragged_value_types") + ragged_split_types = parse_example_op.get_attr("ragged_split_types") + dense_shapes = parse_example_op.get_attr("dense_shapes") + + num_dense = len(dense_types) + num_ragged = len(ragged_value_types) + assert len(ragged_value_types) == len(ragged_split_types) + assert len(parse_example_op.inputs) == 5 + num_dense + + # Skip over the serialized input, and the names input. + fetched = sess.run(parse_example_op.inputs[2:]) + sparse_keys = fetched[0].tolist() + dense_keys = fetched[1].tolist() + ragged_keys = fetched[2].tolist() + dense_defaults = fetched[3:] + assert len(sparse_keys) == num_sparse + assert len(dense_keys) == num_dense + assert len(ragged_keys) == num_ragged + + # Output tensor indices. + sparse_indices_start = 0 + sparse_values_start = num_sparse + sparse_shapes_start = sparse_values_start + num_sparse + dense_values_start = sparse_shapes_start + num_sparse + ragged_values_start = dense_values_start + num_dense + ragged_row_splits_start = ragged_values_start + num_ragged + + # Dense features. + for i in range(num_dense): + key = dense_keys[i] + feature_config = config.feature_map[key] + # Convert the default value numpy array fetched from the session run + # into a TensorProto. + fixed_config = feature_config.fixed_len_feature + + fixed_config.default_value.CopyFrom( + tensor_util.make_tensor_proto(dense_defaults[i])) + # Convert the shape from the attributes + # into a TensorShapeProto. + fixed_config.shape.CopyFrom( + tensor_shape.TensorShape(dense_shapes[i]).as_proto()) + + fixed_config.dtype = dense_types[i].as_datatype_enum + # Get the output tensor name. + fixed_config.values_output_tensor_name = parse_example_op.outputs[ + dense_values_start + i].name + + # Sparse features. + for i in range(num_sparse): + key = sparse_keys[i] + feature_config = config.feature_map[key] + var_len_feature = feature_config.var_len_feature + var_len_feature.dtype = sparse_types[i].as_datatype_enum + var_len_feature.indices_output_tensor_name = parse_example_op.outputs[ + sparse_indices_start + i].name + var_len_feature.values_output_tensor_name = parse_example_op.outputs[ + sparse_values_start + i].name + var_len_feature.shapes_output_tensor_name = parse_example_op.outputs[ + sparse_shapes_start + i].name + + if num_ragged != 0: + del ragged_values_start # unused + del ragged_row_splits_start # unused + raise ValueError("Ragged features are not yet supported by " + "example_parser_configuration.proto") + + return config diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/fast_module_type.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/fast_module_type.pyi new file mode 100644 index 0000000000000000000000000000000000000000..a04c7f7468b5695b2140450c76ca2e02095c94d1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/fast_module_type.pyi @@ -0,0 +1,16 @@ +# Copyright 2023 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +def get_fast_module_type_class() -> object: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/function_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/function_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..fa978fe12d56acc3b4779b6f17d1728ef8cba26b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/function_utils.py @@ -0,0 +1,132 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Utility to retrieve function args.""" + +import functools + +import six + +from tensorflow.core.protobuf import config_pb2 +from tensorflow.python.util import tf_decorator +from tensorflow.python.util import tf_inspect + + +def _is_bound_method(fn): + _, fn = tf_decorator.unwrap(fn) + return tf_inspect.ismethod(fn) and (fn.__self__ is not None) + + +def _is_callable_object(obj): + return hasattr(obj, '__call__') and tf_inspect.ismethod(obj.__call__) + + +def fn_args(fn): + """Get argument names for function-like object. + + Args: + fn: Function, or function-like object (e.g., result of `functools.partial`). + + Returns: + `tuple` of string argument names. + + Raises: + ValueError: if partial function has positionally bound arguments + """ + if isinstance(fn, functools.partial): + args = fn_args(fn.func) + args = [a for a in args[len(fn.args):] if a not in (fn.keywords or [])] + else: + if _is_callable_object(fn): + fn = fn.__call__ + args = tf_inspect.getfullargspec(fn).args + if _is_bound_method(fn) and args: + # If it's a bound method, it may or may not have a self/cls first + # argument; for example, self could be captured in *args. + # If it does have a positional argument, it is self/cls. + args.pop(0) + return tuple(args) + + +def has_kwargs(fn): + """Returns whether the passed callable has **kwargs in its signature. + + Args: + fn: Function, or function-like object (e.g., result of `functools.partial`). + + Returns: + `bool`: if `fn` has **kwargs in its signature. + + Raises: + `TypeError`: If fn is not a Function, or function-like object. + """ + if isinstance(fn, functools.partial): + fn = fn.func + elif _is_callable_object(fn): + fn = fn.__call__ + elif not callable(fn): + raise TypeError( + 'Argument `fn` should be a callable. ' + f'Received: fn={fn} (of type {type(fn)})') + return tf_inspect.getfullargspec(fn).varkw is not None + + +def get_func_name(func): + """Returns name of passed callable.""" + _, func = tf_decorator.unwrap(func) + if callable(func): + if tf_inspect.isfunction(func): + return func.__name__ + elif tf_inspect.ismethod(func): + return '%s.%s' % (six.get_method_self(func).__class__.__name__, + six.get_method_function(func).__name__) + else: # Probably a class instance with __call__ + return str(type(func)) + else: + raise ValueError( + 'Argument `func` must be a callable. ' + f'Received func={func} (of type {type(func)})') + + +def get_func_code(func): + """Returns func_code of passed callable, or None if not available.""" + _, func = tf_decorator.unwrap(func) + if callable(func): + if tf_inspect.isfunction(func) or tf_inspect.ismethod(func): + return six.get_function_code(func) + # Since the object is not a function or method, but is a callable, we will + # try to access the __call__method as a function. This works with callable + # classes but fails with functool.partial objects despite their __call__ + # attribute. + try: + return six.get_function_code(func.__call__) + except AttributeError: + return None + else: + raise ValueError( + 'Argument `func` must be a callable. ' + f'Received func={func} (of type {type(func)})') + + +_rewriter_config_optimizer_disabled = None + + +def get_disabled_rewriter_config(): + global _rewriter_config_optimizer_disabled + if _rewriter_config_optimizer_disabled is None: + config = config_pb2.ConfigProto() + rewriter_config = config.graph_options.rewrite_options + rewriter_config.disable_meta_optimizer = True + _rewriter_config_optimizer_disabled = config.SerializeToString() + return _rewriter_config_optimizer_disabled diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/is_in_graph_mode.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/is_in_graph_mode.py new file mode 100644 index 0000000000000000000000000000000000000000..7fd8ae9e023325cb701522943958b41e9443c466 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/is_in_graph_mode.py @@ -0,0 +1,18 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""A function that tells you if the program is running in graph mode.""" +# Call IS_IN_GRAPH_MODE() when you want to know whether the thread is in +# graph mode. By default, we always are. +IS_IN_GRAPH_MODE = lambda: True diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/keras_deps.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/keras_deps.py new file mode 100644 index 0000000000000000000000000000000000000000..99daeaa237863461ca280774512cd59f90021496 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/keras_deps.py @@ -0,0 +1,95 @@ +# Copyright 2020 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""Interface that provides access to Keras dependencies. + +This library is a common interface that contains Keras functions needed by +TensorFlow and TensorFlow Lite and is required as per the dependency inversion +principle (https://en.wikipedia.org/wiki/Dependency_inversion_principle). As per +this principle, high-level modules (eg: TensorFlow and TensorFlow Lite) should +not depend on low-level modules (eg: Keras) and instead both should depend on a +common interface such as this file. +""" + + +from tensorflow.python.util.tf_export import tf_export + +_KERAS_CALL_CONTEXT_FUNCTION = None +_KERAS_CLEAR_SESSION_FUNCTION = None +_KERAS_GET_SESSION_FUNCTION = None +_KERAS_LOAD_MODEL_FUNCTION = None +_KERAS_LOAD_CONTEXT_FUNCTION = None + +# TODO(b/169898786): Use the Keras public API when TFLite moves out of TF + + +# Register functions +@tf_export('__internal__.register_call_context_function', v1=[]) +def register_call_context_function(func): + global _KERAS_CALL_CONTEXT_FUNCTION + _KERAS_CALL_CONTEXT_FUNCTION = func + + +@tf_export('__internal__.register_clear_session_function', v1=[]) +def register_clear_session_function(func): + global _KERAS_CLEAR_SESSION_FUNCTION + _KERAS_CLEAR_SESSION_FUNCTION = func + + +@tf_export('__internal__.register_get_session_function', v1=[]) +def register_get_session_function(func): + global _KERAS_GET_SESSION_FUNCTION + _KERAS_GET_SESSION_FUNCTION = func + + +@tf_export('__internal__.register_load_model_function', v1=[]) +def register_load_model_function(func): + global _KERAS_LOAD_MODEL_FUNCTION + _KERAS_LOAD_MODEL_FUNCTION = func + + +# This is used to register the in_load_context function in +# third_party/py/tf_keras/saving/saved_model/load_context.py for use in +# third_party/tensorflow library. +@tf_export('__internal__.register_load_context_function', v1=[]) +def register_load_context_function(func): + global _KERAS_LOAD_CONTEXT_FUNCTION + _KERAS_LOAD_CONTEXT_FUNCTION = func + + +# Get functions +def get_call_context_function(): + global _KERAS_CALL_CONTEXT_FUNCTION + return _KERAS_CALL_CONTEXT_FUNCTION + + +def get_clear_session_function(): + global _KERAS_CLEAR_SESSION_FUNCTION + return _KERAS_CLEAR_SESSION_FUNCTION + + +def get_get_session_function(): + global _KERAS_GET_SESSION_FUNCTION + return _KERAS_GET_SESSION_FUNCTION + + +def get_load_model_function(): + global _KERAS_LOAD_MODEL_FUNCTION + return _KERAS_LOAD_MODEL_FUNCTION + + +def get_load_context_function(): + global _KERAS_LOAD_CONTEXT_FUNCTION # pylint: disable=global-variable-not-assigned + return _KERAS_LOAD_CONTEXT_FUNCTION diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/keyword_args.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/keyword_args.py new file mode 100644 index 0000000000000000000000000000000000000000..ddd96b91f9f6699f4e6c49cdcb5dba25f4ff04ad --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/keyword_args.py @@ -0,0 +1,50 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""Keyword args functions.""" + +import functools + +from tensorflow.python.util import decorator_utils + + +def keyword_args_only(func): + """Decorator for marking specific function accepting keyword args only. + + This decorator raises a `ValueError` if the input `func` is called with any + non-keyword args. This prevents the caller from providing the arguments in + wrong order. + + Args: + func: The function or method needed to be decorated. + + Returns: + Decorated function or method. + + Raises: + ValueError: If `func` is not callable. + """ + + decorator_utils.validate_callable(func, "keyword_args_only") + @functools.wraps(func) + def new_func(*args, **kwargs): + """Keyword args only wrapper.""" + if args: + raise ValueError( + f"The function {func.__name__} only accepts keyword arguments. " + "Do not pass positional arguments. Received the following positional " + f"arguments: {args}") + return func(**kwargs) + return new_func diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/lazy_loader.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/lazy_loader.py new file mode 100644 index 0000000000000000000000000000000000000000..08e0fb0609b4d5d8ce0791a1d535b258c03b7edb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/lazy_loader.py @@ -0,0 +1,182 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""A LazyLoader class.""" + +import importlib +import os +import types +from tensorflow.python.platform import tf_logging as logging + + +class LazyLoader(types.ModuleType): + """Lazily import a module, mainly to avoid pulling in large dependencies. + + `contrib`, and `ffmpeg` are examples of modules that are large and not always + needed, and this allows them to only be loaded when they are used. + """ + + # The lint error here is incorrect. + def __init__(self, local_name, parent_module_globals, name, warning=None): + self._local_name = local_name + self._parent_module_globals = parent_module_globals + self._warning = warning + + # These members allows doctest correctly process this module member without + # triggering self._load(). self._load() mutates parant_module_globals and + # triggers a dict mutated during iteration error from doctest.py. + # - for from_module() + self.__module__ = name.rsplit(".", 1)[0] + # - for is_routine() + self.__wrapped__ = None + + super(LazyLoader, self).__init__(name) + + def _load(self): + """Load the module and insert it into the parent's globals.""" + # Import the target module and insert it into the parent's namespace + module = importlib.import_module(self.__name__) + self._parent_module_globals[self._local_name] = module + + # Emit a warning if one was specified + if self._warning: + logging.warning(self._warning) + # Make sure to only warn once. + self._warning = None + + # Update this object's dict so that if someone keeps a reference to the + # LazyLoader, lookups are efficient (__getattr__ is only called on lookups + # that fail). + self.__dict__.update(module.__dict__) + + return module + + def __getattr__(self, item): + module = self._load() + return getattr(module, item) + + def __repr__(self): + # Carefully to not trigger _load, since repr may be called in very + # sensitive places. + return f"" + + def __dir__(self): + module = self._load() + return dir(module) + + +class KerasLazyLoader(LazyLoader): + """LazyLoader that handles routing to different Keras version.""" + + def __init__( # pylint: disable=super-init-not-called + self, parent_module_globals, mode=None, submodule=None, name="keras"): + self._parent_module_globals = parent_module_globals + self._mode = mode + self._submodule = submodule + self._name = name + self._initialized = False + + def _initialize(self): + """Resolve the Keras version to use and initialize the loader.""" + self._initialized = True + package_name = None + keras_version = None + if os.environ.get("TF_USE_LEGACY_KERAS", None) in ("true", "True", "1"): + try: + import tf_keras # pylint: disable=g-import-not-at-top,unused-import + + keras_version = "tf_keras" + if self._mode == "v1": + package_name = "tf_keras.api._v1.keras" + else: + package_name = "tf_keras.api._v2.keras" + except ImportError: + logging.warning( + "Your environment has TF_USE_LEGACY_KERAS set to True, but you " + "do not have the tf_keras package installed. You must install it " + "in order to use the legacy tf.keras. Install it via: " + "`pip install tf_keras`" + ) + else: + try: + import keras # pylint: disable=g-import-not-at-top + + if keras.__version__.startswith("3."): + # This is the Keras 3.x case. + keras_version = "keras_3" + package_name = "keras._tf_keras.keras" + else: + # This is the Keras 2.x case. + keras_version = "keras_2" + if self._mode == "v1": + package_name = "keras.api._v1.keras" + else: + package_name = "keras.api._v2.keras" + except ImportError: + raise ImportError( # pylint: disable=raise-missing-from + "Keras cannot be imported. Check that it is installed." + ) + + self._keras_version = keras_version + if keras_version is not None: + if self._submodule is not None: + package_name += "." + self._submodule + super().__init__(self._name, self._parent_module_globals, package_name) + else: + raise ImportError( # pylint: disable=raise-missing-from + "Keras cannot be imported. Check that it is installed." + ) + + def __getattr__(self, item): + if item in ("_mode", "_initialized", "_name"): + return super(types.ModuleType, self).__getattribute__(item) + if not self._initialized: + self._initialize() + if self._keras_version == "keras_3": + if (self._mode == "v1" and + not self._submodule and + item.startswith("compat.v1.")): + raise AttributeError( + "`tf.compat.v1.keras` is not available with Keras 3. Keras 3 has " + "no support for TF 1 APIs. You can install the `tf_keras` package " + "as an alternative, and set the environment variable " + "`TF_USE_LEGACY_KERAS=True` to configure TensorFlow to route " + "`tf.compat.v1.keras` to `tf_keras`." + ) + elif (self._mode == "v2" and + not self._submodule and + item.startswith("compat.v2.")): + raise AttributeError( + "`tf.compat.v2.keras` is not available with Keras 3. Just use " + "`import keras` instead." + ) + elif (self._submodule and + self._submodule.startswith("__internal__.legacy.")): + raise AttributeError( + f"`{item}` is not available with Keras 3." + ) + module = self._load() + return getattr(module, item) + + def __repr__(self): + if self._initialized: + return (f"") + return "" + + def __dir__(self): + if not self._initialized: + self._initialize() + return super().__dir__() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/lock_util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/lock_util.py new file mode 100644 index 0000000000000000000000000000000000000000..6832011e1550931432293cb9c7274ff0be9f1646 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/lock_util.py @@ -0,0 +1,130 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Locking related utils.""" + +import threading + + +class GroupLock(object): + """A lock to allow many members of a group to access a resource exclusively. + + This lock provides a way to allow access to a resource by multiple threads + belonging to a logical group at the same time, while restricting access to + threads from all other groups. You can think of this as an extension of a + reader-writer lock, where you allow multiple writers at the same time. We + made it generic to support multiple groups instead of just two - readers and + writers. + + Simple usage example with two groups accessing the same resource: + + ```python + lock = GroupLock(num_groups=2) + + # In a member of group 0: + with lock.group(0): + # do stuff, access the resource + # ... + + # In a member of group 1: + with lock.group(1): + # do stuff, access the resource + # ... + ``` + + Using as a context manager with `.group(group_id)` is the easiest way. You + can also use the `acquire` and `release` method directly. + """ + + __slots__ = ["_ready", "_num_groups", "_group_member_counts"] + + def __init__(self, num_groups=2): + """Initialize a group lock. + + Args: + num_groups: The number of groups that will be accessing the resource under + consideration. Should be a positive number. + + Returns: + A group lock that can then be used to synchronize code. + + Raises: + ValueError: If num_groups is less than 1. + """ + if num_groups < 1: + raise ValueError( + "Argument `num_groups` must be a positive integer. " + f"Received: num_groups={num_groups}") + self._ready = threading.Condition(threading.Lock()) + self._num_groups = num_groups + self._group_member_counts = [0] * self._num_groups + + def group(self, group_id): + """Enter a context where the lock is with group `group_id`. + + Args: + group_id: The group for which to acquire and release the lock. + + Returns: + A context manager which will acquire the lock for `group_id`. + """ + self._validate_group_id(group_id) + return self._Context(self, group_id) + + def acquire(self, group_id): + """Acquire the group lock for a specific group `group_id`.""" + self._validate_group_id(group_id) + + self._ready.acquire() + while self._another_group_active(group_id): + self._ready.wait() + self._group_member_counts[group_id] += 1 + self._ready.release() + + def release(self, group_id): + """Release the group lock for a specific group `group_id`.""" + self._validate_group_id(group_id) + + self._ready.acquire() + self._group_member_counts[group_id] -= 1 + if self._group_member_counts[group_id] == 0: + self._ready.notify_all() + self._ready.release() + + def _another_group_active(self, group_id): + return any( + c > 0 for g, c in enumerate(self._group_member_counts) if g != group_id) + + def _validate_group_id(self, group_id): + if group_id < 0 or group_id >= self._num_groups: + raise ValueError( + "Argument `group_id` should verify `0 <= group_id < num_groups` " + f"(with `num_groups={self._num_groups}`). " + f"Received: group_id={group_id}") + + class _Context(object): + """Context manager helper for `GroupLock`.""" + + __slots__ = ["_lock", "_group_id"] + + def __init__(self, lock, group_id): + self._lock = lock + self._group_id = group_id + + def __enter__(self): + self._lock.acquire(self._group_id) + + def __exit__(self, type_arg, value_arg, traceback_arg): + del type_arg, value_arg, traceback_arg + self._lock.release(self._group_id) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/module_wrapper.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/module_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..0611cc43c79e8ffe47d7e4e38b4e3db888b7a445 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/module_wrapper.py @@ -0,0 +1,283 @@ +# Copyright 2021 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Provides wrapper for TensorFlow modules.""" + +import importlib + +from tensorflow.python.eager import monitoring +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.util import fast_module_type +from tensorflow.python.util import tf_decorator +from tensorflow.python.util import tf_inspect +from tensorflow.tools.compatibility import all_renames_v2 + +FastModuleType = fast_module_type.get_fast_module_type_class() +_PER_MODULE_WARNING_LIMIT = 1 +compat_v1_usage_gauge = monitoring.BoolGauge('/tensorflow/api/compat/v1', + 'compat.v1 usage') + + +def get_rename_v2(name): + if name not in all_renames_v2.symbol_renames: + return None + return all_renames_v2.symbol_renames[name] + + +def _call_location(): + """Extracts the caller filename and line number as a string. + + Returns: + A string describing the caller source location. + """ + frame = tf_inspect.currentframe() + assert frame.f_back.f_code.co_name == '_tfmw_add_deprecation_warning', ( + 'This function should be called directly from ' + '_tfmw_add_deprecation_warning, as the caller is identified ' + 'heuristically by chopping off the top stack frames.') + + # We want to get stack frame 3 frames up from current frame, + # i.e. above __getattr__, _tfmw_add_deprecation_warning, + # and _call_location calls. + for _ in range(3): + parent = frame.f_back + if parent is None: + break + frame = parent + return '{}:{}'.format(frame.f_code.co_filename, frame.f_lineno) + + +def contains_deprecation_decorator(decorators): + return any(d.decorator_name == 'deprecated' for d in decorators) + + +def has_deprecation_decorator(symbol): + """Checks if given object has a deprecation decorator. + + We check if deprecation decorator is in decorators as well as + whether symbol is a class whose __init__ method has a deprecation + decorator. + Args: + symbol: Python object. + + Returns: + True if symbol has deprecation decorator. + """ + decorators, symbol = tf_decorator.unwrap(symbol) + if contains_deprecation_decorator(decorators): + return True + if tf_inspect.isfunction(symbol): + return False + if not tf_inspect.isclass(symbol): + return False + if not hasattr(symbol, '__init__'): + return False + init_decorators, _ = tf_decorator.unwrap(symbol.__init__) + return contains_deprecation_decorator(init_decorators) + + +class TFModuleWrapper(FastModuleType): + """Wrapper for TF modules to support deprecation messages and lazyloading.""" + # Ensures that compat.v1 API usage is recorded at most once + compat_v1_usage_recorded = False + + def __init__( + self, + wrapped, + module_name, + public_apis=None, + deprecation=True, + has_lite=False): + super(TFModuleWrapper, self).__init__(wrapped.__name__) + FastModuleType.set_getattr_callback(self, TFModuleWrapper._getattr) + FastModuleType.set_getattribute_callback(self, + TFModuleWrapper._getattribute) + self.__dict__.update(wrapped.__dict__) + # Prefix all local attributes with _tfmw_ so that we can + # handle them differently in attribute access methods. + self._tfmw_wrapped_module = wrapped + self._tfmw_module_name = module_name + self._tfmw_public_apis = public_apis + self._tfmw_print_deprecation_warnings = deprecation + self._tfmw_has_lite = has_lite + self._tfmw_is_compat_v1 = (wrapped.__name__.endswith('.compat.v1')) + # Set __all__ so that import * work for lazy loaded modules + if self._tfmw_public_apis: + self._tfmw_wrapped_module.__all__ = list(self._tfmw_public_apis.keys()) + self.__all__ = list(self._tfmw_public_apis.keys()) + else: + if hasattr(self._tfmw_wrapped_module, '__all__'): + self.__all__ = self._tfmw_wrapped_module.__all__ + else: + self._tfmw_wrapped_module.__all__ = [ + attr for attr in dir(self._tfmw_wrapped_module) + if not attr.startswith('_') + ] + self.__all__ = self._tfmw_wrapped_module.__all__ + + # names we already checked for deprecation + self._tfmw_deprecated_checked = set() + self._tfmw_warning_count = 0 + + def _tfmw_add_deprecation_warning(self, name, attr): + """Print deprecation warning for attr with given name if necessary.""" + if (self._tfmw_warning_count < _PER_MODULE_WARNING_LIMIT and + name not in self._tfmw_deprecated_checked): + + self._tfmw_deprecated_checked.add(name) + + if self._tfmw_module_name: + full_name = 'tf.%s.%s' % (self._tfmw_module_name, name) + else: + full_name = 'tf.%s' % name + rename = get_rename_v2(full_name) + if rename and not has_deprecation_decorator(attr): + call_location = _call_location() + # skip locations in Python source + if not call_location.startswith('<'): + logging.warning( + 'From %s: The name %s is deprecated. Please use %s instead.\n', + _call_location(), full_name, rename) + self._tfmw_warning_count += 1 + return True + return False + + def _tfmw_import_module(self, name): + """Lazily loading the modules.""" + # We ignore 'app' because it is accessed in __init__.py of tf.compat.v1. + # That way, if a user only imports tensorflow.compat.v1, it is not + # considered v1 API usage. + if (self._tfmw_is_compat_v1 and name != 'app' and + not TFModuleWrapper.compat_v1_usage_recorded): + TFModuleWrapper.compat_v1_usage_recorded = True + compat_v1_usage_gauge.get_cell().set(True) + + symbol_loc_info = self._tfmw_public_apis[name] + if symbol_loc_info[0]: + module = importlib.import_module(symbol_loc_info[0]) + attr = getattr(module, symbol_loc_info[1]) + else: + attr = importlib.import_module(symbol_loc_info[1]) + setattr(self._tfmw_wrapped_module, name, attr) + self.__dict__[name] = attr + # Cache the pair + self._fastdict_insert(name, attr) + return attr + + def _getattribute(self, name): + # pylint: disable=g-doc-return-or-yield,g-doc-args + """Imports and caches pre-defined API. + + Warns if necessary. + + This method is a replacement for __getattribute__(). It will be added into + the extended python module as a callback to reduce API overhead. + """ + # Avoid infinite recursions + func__fastdict_insert = object.__getattribute__(self, '_fastdict_insert') + + # Make sure we do not import from tensorflow/lite/__init__.py + if name == 'lite': + if self._tfmw_has_lite: + attr = self._tfmw_import_module(name) + setattr(self._tfmw_wrapped_module, 'lite', attr) + func__fastdict_insert(name, attr) + return attr + # Placeholder for Google-internal contrib error + + attr = object.__getattribute__(self, name) + + # Return and cache dunders and our own members. + # This is necessary to guarantee successful construction. + # In addition, all the accessed attributes used during the construction must + # begin with "__" or "_tfmw" or "_fastdict_". + if name.startswith('__') or name.startswith('_tfmw_') or name.startswith( + '_fastdict_'): + func__fastdict_insert(name, attr) + return attr + + # Print deprecations, only cache functions after deprecation warnings have + # stopped. + if not (self._tfmw_print_deprecation_warnings and + self._tfmw_add_deprecation_warning(name, attr)): + func__fastdict_insert(name, attr) + + return attr + + def _getattr(self, name): + # pylint: disable=g-doc-return-or-yield,g-doc-args + """Imports and caches pre-defined API. + + Warns if necessary. + + This method is a replacement for __getattr__(). It will be added into the + extended python module as a callback to reduce API overhead. Instead of + relying on implicit AttributeError handling, this added callback function + will + be called explicitly from the extended C API if the default attribute lookup + fails. + """ + try: + attr = getattr(self._tfmw_wrapped_module, name) + except AttributeError: + # Placeholder for Google-internal contrib error + + if not self._tfmw_public_apis: + raise + if name not in self._tfmw_public_apis: + raise + attr = self._tfmw_import_module(name) + + if self._tfmw_print_deprecation_warnings: + self._tfmw_add_deprecation_warning(name, attr) + return attr + + def __setattr__(self, arg, val): + if not arg.startswith('_tfmw_'): + setattr(self._tfmw_wrapped_module, arg, val) + self.__dict__[arg] = val + if arg not in self.__all__ and arg != '__all__': + self.__all__.append(arg) + # Update the cache + if self._fastdict_key_in(arg): + self._fastdict_insert(arg, val) + super(TFModuleWrapper, self).__setattr__(arg, val) + + def __dir__(self): + if self._tfmw_public_apis: + return list( + set(self._tfmw_public_apis.keys()).union( + set([ + attr for attr in dir(self._tfmw_wrapped_module) + if not attr.startswith('_') + ]))) + else: + return dir(self._tfmw_wrapped_module) + + def __delattr__(self, name): + if name.startswith('_tfmw_'): + super(TFModuleWrapper, self).__delattr__(name) + else: + delattr(self._tfmw_wrapped_module, name) + self.__dict__.pop(name) + if name in self.__all__: + self.__all__.remove(name) + self._fastdict_pop(name) + # delattr(self._tfmw_wrapped_module, name) + + def __repr__(self): + return self._tfmw_wrapped_module.__repr__() + + def __reduce__(self): + return importlib.import_module, (self.__name__,) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/nest.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/nest.py new file mode 100644 index 0000000000000000000000000000000000000000..d7acf836ce5e1f19ea25723491b24a86c3a190f5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/nest.py @@ -0,0 +1,1324 @@ +# Copyright 2021 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""Functions that work with structures. + +A structure is either: + +* one of the recognized Python collections, holding _nested structures_; +* a value of any other type, typically a TensorFlow data type like Tensor, + Variable, or of compatible types such as int, float, ndarray, etc. these are + commonly referred to as _atoms_ of the structure. + +A structure of type `T` is a structure whose atomic items are of type `T`. +For example, a structure of `tf.Tensor` only contains `tf.Tensor` as its atoms. + +Historically a _nested structure_ was called a _nested sequence_ in TensorFlow. +A nested structure is sometimes called a _nest_ or a _tree_, but the formal +name _nested structure_ is preferred. + +Refer to [Nesting Data Structures] +(https://en.wikipedia.org/wiki/Nesting_(computing)#Data_structures). + +The following collection types are recognized by `tf.nest` as nested +structures: + +* `collections.abc.Sequence` (except `string` and `bytes`). + This includes `list`, `tuple`, and `namedtuple`. +* `collections.abc.Mapping` (with sortable keys). + This includes `dict` and `collections.OrderedDict`. +* `collections.abc.MappingView` (with sortable keys). +* [`attr.s` classes](https://www.attrs.org/). +* Classes (including + [`dataclass`](https://docs.python.org/library/dataclasses.html)) + that implement the `__tf_flatten__` and `__tf_unflatten__` methods. + See examples in + [`nest_util.py`](https://github.com/tensorflow/tensorflow/blob/04869b4e63bfc03cb13627b3e1b879fdd0f69e34/tensorflow/python/util/nest_util.py#L97) + +Any other values are considered **atoms**. Not all collection types are +considered nested structures. For example, the following types are +considered atoms: + +* `set`; `{"a", "b"}` is an atom, while `["a", "b"]` is a nested structure. +* [`dataclass` classes](https://docs.python.org/library/dataclasses.html) that +don't implement the custom flattening/unflattening methods mentioned above. +* `tf.Tensor`. +* `numpy.array`. + +`tf.nest.is_nested` checks whether an object is a nested structure or an atom. +For example: + + >>> tf.nest.is_nested("1234") + False + >>> tf.nest.is_nested([1, 3, [4, 5]]) + True + >>> tf.nest.is_nested(((7, 8), (5, 6))) + True + >>> tf.nest.is_nested([]) + True + >>> tf.nest.is_nested({"a": 1, "b": 2}) + True + >>> tf.nest.is_nested({"a": 1, "b": 2}.keys()) + True + >>> tf.nest.is_nested({"a": 1, "b": 2}.values()) + True + >>> tf.nest.is_nested({"a": 1, "b": 2}.items()) + True + >>> tf.nest.is_nested(set([1, 2])) + False + >>> ones = tf.ones([2, 3]) + >>> tf.nest.is_nested(ones) + False + +Note: A proper structure shall form a tree. The user shall ensure there is no +cyclic references within the items in the structure, +i.e., no references in the structure of the input of these functions +should be recursive. The behavior is undefined if there is a cycle. + +API docstring: tensorflow.nest +""" + +import wrapt as _wrapt + +from tensorflow.python.util import _pywrap_nest +from tensorflow.python.util import _pywrap_utils +from tensorflow.python.util import nest_util +from tensorflow.python.util.compat import collections_abc as _collections_abc +from tensorflow.python.util.tf_export import tf_export + + +STRUCTURES_HAVE_MISMATCHING_LENGTHS = ( + nest_util.STRUCTURES_HAVE_MISMATCHING_LENGTHS +) + +STRUCTURES_HAVE_MISMATCHING_TYPES = nest_util.STRUCTURES_HAVE_MISMATCHING_TYPES + +SHALLOW_TREE_HAS_INVALID_KEYS = nest_util.SHALLOW_TREE_HAS_INVALID_KEYS + +INPUT_TREE_SMALLER_THAN_SHALLOW_TREE = ( + nest_util.INPUT_TREE_SMALLER_THAN_SHALLOW_TREE +) + +IF_SHALLOW_IS_SEQ_INPUT_MUST_BE_SEQ = ( + "If shallow structure is a sequence, input must also be a sequence. " + "Input has type: {}." +) + +is_namedtuple = nest_util.is_namedtuple +_is_namedtuple = nest_util.is_namedtuple +_is_attrs = _pywrap_utils.IsAttrs +_is_mapping = _pywrap_utils.IsMapping +same_namedtuples = nest_util.same_namedtuples + + +def _yield_value(iterable): + return nest_util.yield_value(nest_util.Modality.CORE, iterable) + + +def _yield_sorted_items(iterable): + return nest_util.yield_sorted_items(nest_util.Modality.CORE, iterable) + + +@tf_export("__internal__.nest.is_mapping", v1=[]) +def is_mapping(obj): + """Returns a true if its input is a collections.Mapping.""" + return _is_mapping(obj) + + +# TODO(b/225045380): Move to a "leaf" library to use in trace_type. +@tf_export("__internal__.nest.is_attrs", v1=[]) +def is_attrs(obj): + """Returns a true if its input is an instance of an attr.s decorated class.""" + return _is_attrs(obj) + + +@tf_export("__internal__.nest.sequence_like", v1=[]) +def _sequence_like(instance, args): + """Converts the sequence `args` to the same type as `instance`. + + Args: + instance: an instance of `tuple`, `list`, `namedtuple`, `dict`, + `collections.OrderedDict`, or `composite_tensor.Composite_Tensor` + or `type_spec.TypeSpec`. + args: items to be converted to the `instance` type. + + Returns: + `args` with the type of `instance`. + """ + return nest_util.sequence_like(instance, args) + + +_is_nested_or_composite = _pywrap_utils.IsNestedOrComposite + + +@tf_export("nest.is_nested") +def is_nested(seq): + """Returns true if its input is a nested structure. + + Refer to [tf.nest](https://www.tensorflow.org/api_docs/python/tf/nest) + for the definition of a nested structure. + + Args: + seq: the value to test. + + Returns: + True if the input is a nested structure. + """ + return nest_util.is_nested(nest_util.Modality.CORE, seq) + + +def is_nested_or_composite(seq): + """Returns true if its input is a nested structure or a composite. + + Refer to [tf.nest](https://www.tensorflow.org/api_docs/python/tf/nest) + for the definition of a nested structure. + + Args: + seq: the value to test. + + Returns: + True if the input is a nested structure or a composite. + """ + return _is_nested_or_composite(seq) + + +def is_sequence_or_composite(seq): + return _is_nested_or_composite(seq) + + +@tf_export("nest.flatten") +def flatten(structure, expand_composites=False): + """Returns a flat list from a given structure. + + Refer to [tf.nest](https://www.tensorflow.org/api_docs/python/tf/nest) + for the definition of a structure. + + If the structure is an atom, then returns a single-item list: [structure]. + + This is the inverse of the `nest.pack_sequence_as` method that takes in a + flattened list and re-packs it into the nested structure. + + In the case of dict instances, the sequence consists of the values, sorted by + key to ensure deterministic behavior. This is true also for OrderedDict + instances: their sequence order is ignored, the sorting order of keys is used + instead. The same convention is followed in `nest.pack_sequence_as`. This + correctly repacks dicts and OrderedDicts after they have been flattened, and + also allows flattening an OrderedDict and then repacking it back using a + corresponding plain dict, or vice-versa. Dictionaries with non-sortable keys + cannot be flattened. + + Users must not modify any collections used in nest while this function is + running. + + Examples: + + 1. Python dict (ordered by key): + + >>> dict = { "key3": "value3", "key1": "value1", "key2": "value2" } + >>> tf.nest.flatten(dict) + ['value1', 'value2', 'value3'] + + 2. For a nested python tuple: + + >>> tuple = ((1.0, 2.0), (3.0, 4.0, 5.0), 6.0) + >>> tf.nest.flatten(tuple) + [1.0, 2.0, 3.0, 4.0, 5.0, 6.0] + + 3. For a nested dictionary of dictionaries: + + >>> dict = { "key3": {"c": (1.0, 2.0), "a": (3.0)}, + ... "key1": {"m": "val1", "g": "val2"} } + >>> tf.nest.flatten(dict) + ['val2', 'val1', 3.0, 1.0, 2.0] + + 4. Numpy array (will not flatten): + + >>> array = np.array([[1, 2], [3, 4]]) + >>> tf.nest.flatten(array) + [array([[1, 2], + [3, 4]])] + + 5. `tf.Tensor` (will not flatten): + + >>> tensor = tf.constant([[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]]) + >>> tf.nest.flatten(tensor) + [] + + 6. `tf.RaggedTensor`: This is a composite tensor thats representation consists + of a flattened list of 'values' and a list of 'row_splits' which indicate how + to chop up the flattened list into different rows. For more details on + `tf.RaggedTensor`, please visit + https://www.tensorflow.org/api_docs/python/tf/RaggedTensor. + + with `expand_composites=False`, we just return the RaggedTensor as is. + + >>> tensor = tf.ragged.constant([[3, 1, 4, 1], [], [5, 9, 2]]) + >>> tf.nest.flatten(tensor, expand_composites=False) + [] + + with `expand_composites=True`, we return the component Tensors that make up + the RaggedTensor representation (the values and row_splits tensors) + + >>> tensor = tf.ragged.constant([[3, 1, 4, 1], [], [5, 9, 2]]) + >>> tf.nest.flatten(tensor, expand_composites=True) + [, + ] + + Args: + structure: an atom or a nested structure. Note, numpy arrays are considered + atoms and are not flattened. + expand_composites: If true, then composite tensors such as + `tf.sparse.SparseTensor` and `tf.RaggedTensor` are expanded into their + component tensors. + + Returns: + A Python list, the flattened version of the input. + + Raises: + TypeError: The nest is or contains a dict with non-sortable keys. + """ + return nest_util.flatten( + nest_util.Modality.CORE, structure, expand_composites + ) + + +@tf_export("nest.assert_same_structure") +def assert_same_structure(nest1, nest2, check_types=True, + expand_composites=False): + """Asserts that two structures are nested in the same way. + + Refer to [tf.nest](https://www.tensorflow.org/api_docs/python/tf/nest) + for the definition of a structure. + + Note the method does not check the types of atoms inside the structures. + + Examples: + + * These atom vs. atom comparisons will pass: + + >>> tf.nest.assert_same_structure(1.5, tf.Variable(1, tf.uint32)) + >>> tf.nest.assert_same_structure("abc", np.array([1, 2])) + + * These nested structure vs. nested structure comparisons will pass: + + >>> structure1 = (((1, 2), 3), 4, (5, 6)) + >>> structure2 = ((("foo1", "foo2"), "foo3"), "foo4", ("foo5", "foo6")) + >>> structure3 = [(("a", "b"), "c"), "d", ["e", "f"]] + >>> tf.nest.assert_same_structure(structure1, structure2) + >>> tf.nest.assert_same_structure(structure1, structure3, check_types=False) + + >>> import collections + >>> tf.nest.assert_same_structure( + ... collections.namedtuple("bar", "a b")(1, 2), + ... collections.namedtuple("foo", "a b")(2, 3), + ... check_types=False) + + >>> tf.nest.assert_same_structure( + ... collections.namedtuple("bar", "a b")(1, 2), + ... { "a": 1, "b": 2 }, + ... check_types=False) + + >>> tf.nest.assert_same_structure( + ... { "a": 1, "b": 2, "c": 3 }, + ... { "c": 6, "b": 5, "a": 4 }) + + >>> ragged_tensor1 = tf.RaggedTensor.from_row_splits( + ... values=[3, 1, 4, 1, 5, 9, 2, 6], + ... row_splits=[0, 4, 4, 7, 8, 8]) + >>> ragged_tensor2 = tf.RaggedTensor.from_row_splits( + ... values=[3, 1, 4], + ... row_splits=[0, 3]) + >>> tf.nest.assert_same_structure( + ... ragged_tensor1, + ... ragged_tensor2, + ... expand_composites=True) + + * These examples will raise exceptions: + + >>> tf.nest.assert_same_structure([0, 1], np.array([0, 1])) + Traceback (most recent call last): + ... + ValueError: The two structures don't have the same nested structure + + >>> tf.nest.assert_same_structure( + ... collections.namedtuple('bar', 'a b')(1, 2), + ... collections.namedtuple('foo', 'a b')(2, 3)) + Traceback (most recent call last): + ... + TypeError: The two structures don't have the same nested structure + + Args: + nest1: an atom or a nested structure. + nest2: an atom or a nested structure. + check_types: if `True` (default) types of structures are checked as well, + including the keys of dictionaries. If set to `False`, for example a list + and a tuple of objects will look the same if they have the same size. Note + that namedtuples with identical name and fields are always considered to + have the same shallow structure. Two types will also be considered the + same if they are both list subtypes (which allows "list" and + "_ListWrapper" from trackable dependency tracking to compare equal). + `check_types=True` only checks type of sub-structures. The types of atoms + are not checked. + expand_composites: If true, then composite tensors such as + `tf.sparse.SparseTensor` and `tf.RaggedTensor` are expanded into their + component tensors. + + Raises: + ValueError: If the two structures do not have the same number of atoms or + if the two structures are not nested in the same way. + TypeError: If the two structures differ in the type of sequence in any of + their substructures. Only possible if `check_types` is `True`. + """ + nest_util.assert_same_structure( + nest_util.Modality.CORE, nest1, nest2, check_types, expand_composites + ) + + +def flatten_dict_items(dictionary): + """Returns a dictionary with flattened keys and values. + + This function flattens the keys and values of a dictionary, which can be + arbitrarily nested structures, and returns the flattened version of such + structures: + + ```python + example_dictionary = {(4, 5, (6, 8)): ("a", "b", ("c", "d"))} + result = {4: "a", 5: "b", 6: "c", 8: "d"} + flatten_dict_items(example_dictionary) == result + ``` + + The input dictionary must satisfy two properties: + + 1. Its keys and values should have the same exact nested structure. + 2. The set of all flattened keys of the dictionary must not contain repeated + keys. + + Args: + dictionary: the dictionary to zip + + Returns: + The zipped dictionary. + + Raises: + TypeError: If the input is not a dictionary. + ValueError: If any key and value do not have the same structure layout, or + if keys are not unique. + """ + return _pywrap_nest.FlattenDictItems(dictionary) + + +@tf_export("nest.pack_sequence_as") +def pack_sequence_as(structure, flat_sequence, expand_composites=False): + """Returns a given flattened sequence packed into a given structure. + + Refer to [tf.nest](https://www.tensorflow.org/api_docs/python/tf/nest) + for the definition of a structure. + + If `structure` is an atom, `flat_sequence` must be a single-item list; + in this case the return value is `flat_sequence[0]`. + + If `structure` is or contains a dict instance, the keys will be sorted to + pack the flat sequence in deterministic order. This is true also for + `OrderedDict` instances: their sequence order is ignored, the sorting order of + keys is used instead. The same convention is followed in `flatten`. + This correctly repacks dicts and `OrderedDict`s after they have been + flattened, and also allows flattening an `OrderedDict` and then repacking it + back using a corresponding plain dict, or vice-versa. + Dictionaries with non-sortable keys cannot be flattened. + + Examples: + + 1. Python dict: + + >>> structure = { "key3": "", "key1": "", "key2": "" } + >>> flat_sequence = ["value1", "value2", "value3"] + >>> tf.nest.pack_sequence_as(structure, flat_sequence) + {'key3': 'value3', 'key1': 'value1', 'key2': 'value2'} + + 2. For a nested python tuple: + + >>> structure = (('a','b'), ('c','d','e'), 'f') + >>> flat_sequence = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0] + >>> tf.nest.pack_sequence_as(structure, flat_sequence) + ((1.0, 2.0), (3.0, 4.0, 5.0), 6.0) + + 3. For a nested dictionary of dictionaries: + + >>> structure = { "key3": {"c": ('alpha', 'beta'), "a": ('gamma')}, + ... "key1": {"e": "val1", "d": "val2"} } + >>> flat_sequence = ['val2', 'val1', 3.0, 1.0, 2.0] + >>> tf.nest.pack_sequence_as(structure, flat_sequence) + {'key3': {'c': (1.0, 2.0), 'a': 3.0}, 'key1': {'e': 'val1', 'd': 'val2'}} + + 4. Numpy array (considered a scalar): + + >>> structure = ['a'] + >>> flat_sequence = [np.array([[1, 2], [3, 4]])] + >>> tf.nest.pack_sequence_as(structure, flat_sequence) + [array([[1, 2], + [3, 4]])] + + 5. tf.Tensor (considered a scalar): + + >>> structure = ['a'] + >>> flat_sequence = [tf.constant([[1., 2., 3.], [4., 5., 6.]])] + >>> tf.nest.pack_sequence_as(structure, flat_sequence) + [] + + 6. `tf.RaggedTensor`: This is a composite tensor thats representation consists + of a flattened list of 'values' and a list of 'row_splits' which indicate how + to chop up the flattened list into different rows. For more details on + `tf.RaggedTensor`, please visit + https://www.tensorflow.org/api_docs/python/tf/RaggedTensor. + + With `expand_composites=False`, we treat RaggedTensor as a scalar. + + >>> structure = { "foo": tf.ragged.constant([[1, 2], [3]]), + ... "bar": tf.constant([[5]]) } + >>> flat_sequence = [ "one", "two" ] + >>> tf.nest.pack_sequence_as(structure, flat_sequence, + ... expand_composites=False) + {'foo': 'two', 'bar': 'one'} + + With `expand_composites=True`, we expect that the flattened input contains + the tensors making up the ragged tensor i.e. the values and row_splits + tensors. + + >>> structure = { "foo": tf.ragged.constant([[1., 2.], [3.]]), + ... "bar": tf.constant([[5.]]) } + >>> tensors = tf.nest.flatten(structure, expand_composites=True) + >>> print(tensors) + [, + , + ] + >>> verified_tensors = [tf.debugging.check_numerics(t, 'invalid tensor: ') + ... if t.dtype==tf.float32 else t + ... for t in tensors] + >>> tf.nest.pack_sequence_as(structure, verified_tensors, + ... expand_composites=True) + {'foo': , + 'bar': } + + Args: + structure: Nested structure, whose structure is given by nested lists, + tuples, and dicts. Note: numpy arrays and strings are considered + scalars. + flat_sequence: flat sequence to pack. + expand_composites: If true, then composite tensors such as + `tf.sparse.SparseTensor` and `tf.RaggedTensor` are expanded into their + component tensors. + + Returns: + packed: `flat_sequence` converted to have the same recursive structure as + `structure`. + + Raises: + ValueError: If `flat_sequence` and `structure` have different + atom counts. + TypeError: `structure` is or contains a dict with non-sortable keys. + """ + return nest_util.pack_sequence_as( + nest_util.Modality.CORE, structure, flat_sequence, expand_composites + ) + + +@tf_export("nest.map_structure") +def map_structure(func, *structure, **kwargs): + """Creates a new structure by applying `func` to each atom in `structure`. + + Refer to [tf.nest](https://www.tensorflow.org/api_docs/python/tf/nest) + for the definition of a structure. + + Applies `func(x[0], x[1], ...)` where x[i] enumerates all atoms in + `structure[i]`. All items in `structure` must have the same arity, + and the return value will contain results with the same structure layout. + + Examples: + + * A single Python dict: + + >>> a = {"hello": 24, "world": 76} + >>> tf.nest.map_structure(lambda p: p * 2, a) + {'hello': 48, 'world': 152} + + * Multiple Python dictionaries: + + >>> d1 = {"hello": 24, "world": 76} + >>> d2 = {"hello": 36, "world": 14} + >>> tf.nest.map_structure(lambda p1, p2: p1 + p2, d1, d2) + {'hello': 60, 'world': 90} + + * A single Python list: + + >>> a = [24, 76, "ab"] + >>> tf.nest.map_structure(lambda p: p * 2, a) + [48, 152, 'abab'] + + * Scalars: + + >>> tf.nest.map_structure(lambda x, y: x + y, 3, 4) + 7 + + * Empty structures: + + >>> tf.nest.map_structure(lambda x: x + 1, ()) + () + + * Check the types of iterables: + + >>> s1 = (((1, 2), 3), 4, (5, 6)) + >>> s1_list = [[[1, 2], 3], 4, [5, 6]] + >>> tf.nest.map_structure(lambda x, y: None, s1, s1_list) + Traceback (most recent call last): + ... + TypeError: The two structures don't have the same nested structure + + * Type check is set to False: + + >>> s1 = (((1, 2), 3), 4, (5, 6)) + >>> s1_list = [[[1, 2], 3], 4, [5, 6]] + >>> tf.nest.map_structure(lambda x, y: None, s1, s1_list, check_types=False) + (((None, None), None), None, (None, None)) + + Args: + func: A callable that accepts as many arguments as there are structures. + *structure: atom or nested structure. + **kwargs: Valid keyword args are: + * `check_types`: If set to `True` (default) the types of iterables within + the structures have to be same (e.g. `map_structure(func, [1], (1,))` + raises a `TypeError` exception). To allow this set this argument to + `False`. Note that namedtuples with identical name and fields are always + considered to have the same shallow structure. + * `expand_composites`: If set to `True`, then composite tensors such as + `tf.sparse.SparseTensor` and `tf.RaggedTensor` are expanded into their + component tensors. If `False` (the default), then composite tensors are + not expanded. + + Returns: + A new structure with the same arity as `structure[0]`, whose atoms + correspond to `func(x[0], x[1], ...)` where `x[i]` is the atom in the + corresponding location in `structure[i]`. If there are different structure + types and `check_types` is `False` the structure types of the first + structure will be used. + + Raises: + TypeError: If `func` is not callable or if the structures do not match + each other by depth tree. + ValueError: If no structure is provided or if the structures do not match + each other by type. + ValueError: If wrong keyword arguments are provided. + """ + return nest_util.map_structure( + nest_util.Modality.CORE, func, *structure, **kwargs + ) + + +def map_structure_with_paths(func, *structure, **kwargs): + """Applies `func` to each entry in `structure` and returns a new structure. + + Applies `func(path, x[0], x[1], ..., **kwargs)` where x[i] is an entry in + `structure[i]` and `path` is the common path to x[i] in the structures. All + structures in `structure` must have the same arity, and the return value will + contain the results with the same structure layout. Special kwarg + `check_types` determines whether the types of iterables within the structure + must be the same-- see **kwargs definition below. + + Args: + func: A callable with the signature func(path, *values, **kwargs) that is + evaluated on the leaves of the structure. + *structure: A variable number of compatible structures to process. + **kwargs: Optional kwargs to be passed through to func. Special kwarg + `check_types` is not passed to func, but instead determines whether the + types of iterables within the structures have to be same (e.g., + `map_structure(func, [1], (1,))` raises a `TypeError` exception). By + default, the types must match. To allow iteration over structures of + different types (but common arity), set this kwarg to `False`. + + Returns: + A structure of the same form as the input structures whose leaves are the + result of evaluating func on corresponding leaves of the input structures. + + Raises: + TypeError: If `func` is not callable or if the structures do not match + each other by depth tree. + TypeError: If `check_types` is not `False` and the two structures differ in + the type of sequence in any of their substructures. + ValueError: If no structures are provided. + """ + def wrapper_func(tuple_path, *inputs, **kwargs): + string_path = "/".join(str(s) for s in tuple_path) + return func(string_path, *inputs, **kwargs) + + return nest_util.map_structure_up_to( + nest_util.Modality.CORE, structure[0], wrapper_func, *structure, **kwargs + ) + + +def map_structure_with_tuple_paths(func, *structure, **kwargs): + """Applies `func` to each entry in `structure` and returns a new structure. + + Applies `func(tuple_path, x[0], x[1], ..., **kwargs)` where `x[i]` is an entry + in `structure[i]` and `tuple_path` is a tuple of indices and/or dictionary + keys (as returned by `nest.yield_flat_paths`), which uniquely specifies the + common path to x[i] in the structures. All structures in `structure` must have + the same arity, and the return value will contain the results in the same + structure. Special kwarg `check_types` determines whether the types of + iterables within the structure must be the same-- see **kwargs definition + below. + + Args: + func: A callable with the signature `func(tuple_path, *values, **kwargs)` + that is evaluated on the leaves of the structure. + *structure: A variable number of compatible structures to process. + **kwargs: Optional kwargs to be passed through to func. Special kwarg + `check_types` is not passed to func, but instead determines whether the + types of iterables within the structures have to be same (e.g. + `map_structure(func, [1], (1,))` raises a `TypeError` exception). To allow + this set this argument to `False`. + + Returns: + A structure of the same form as the input structures whose leaves are the + result of evaluating func on corresponding leaves of the input structures. + + Raises: + TypeError: If `func` is not callable or if the structures do not match + each other by depth tree. + TypeError: If `check_types` is not `False` and the two structures differ in + the type of sequence in any of their substructures. + ValueError: If no structures are provided. + """ + return nest_util.map_structure_up_to( + nest_util.Modality.CORE, structure[0], func, *structure, **kwargs + ) + + +def assert_shallow_structure(shallow_tree, + input_tree, + check_types=True, + expand_composites=False): + """Asserts that `shallow_tree` is a shallow structure of `input_tree`. + + That is, this function tests if the `input_tree` structure can be created from + the `shallow_tree` structure by replacing its leaf nodes with deeper + tree structures. + + Examples: + + The following code will raise an exception: + ```python + shallow_tree = {"a": "A", "b": "B"} + input_tree = {"a": 1, "c": 2} + assert_shallow_structure(shallow_tree, input_tree) + ``` + + The following code will raise an exception: + ```python + shallow_tree = ["a", "b"] + input_tree = ["c", ["d", "e"], "f"] + assert_shallow_structure(shallow_tree, input_tree) + ``` + + Args: + shallow_tree: an arbitrarily nested structure. + input_tree: an arbitrarily nested structure. + check_types: if `True` (default) the sequence types of `shallow_tree` and + `input_tree` have to be the same. Note that even with check_types==True, + this function will consider two different namedtuple classes with the same + name and _fields attribute to be the same class. + expand_composites: If true, then composite tensors such as + `tf.sparse.SparseTensor` and `tf.RaggedTensor` are expanded into their + component tensors. + Raises: + TypeError: If `shallow_tree` is a sequence but `input_tree` is not. + TypeError: If the sequence types of `shallow_tree` are different from + `input_tree`. Only raised if `check_types` is `True`. + ValueError: If the sequence lengths of `shallow_tree` are different from + `input_tree`. + """ + nest_util.assert_shallow_structure( + nest_util.Modality.CORE, + shallow_tree, + input_tree, + check_types, + expand_composites, + ) + + +@tf_export("__internal__.nest.flatten_up_to", v1=[]) +def flatten_up_to(shallow_tree, input_tree, check_types=True, + expand_composites=False): + """Flattens `input_tree` up to `shallow_tree`. + + Refer to [tf.nest](https://www.tensorflow.org/api_docs/python/tf/nest) + for the definition of a structure. + + Any further depth in structure in `input_tree` is retained as structures in + the partially flatten output. + + If `shallow_tree` and `input_tree` are atoms, this returns a + single-item list: `[input_tree]`. + + Use Case: + + Sometimes we may wish to partially flatten a structure, retaining some + of the nested structure. We achieve this by specifying a shallow structure, + `shallow_tree`, we wish to flatten up to. + + The input, `input_tree`, can be thought of as having the same structure layout + as `shallow_tree`, but with leaf nodes that are themselves tree structures. + + Examples: + + ```python + input_tree = [[[2, 2], [3, 3]], [[4, 9], [5, 5]]] + shallow_tree = [[True, True], [False, True]] + + flattened_input_tree = flatten_up_to(shallow_tree, input_tree) + flattened_shallow_tree = flatten_up_to(shallow_tree, shallow_tree) + + # Output is: + # [[2, 2], [3, 3], [4, 9], [5, 5]] + # [True, True, False, True] + ``` + + ```python + input_tree = [[('a', 1), [('b', 2), [('c', 3), [('d', 4)]]]]] + shallow_tree = [['level_1', ['level_2', ['level_3', ['level_4']]]]] + + input_tree_flattened_as_shallow_tree = flatten_up_to(shallow_tree, input_tree) + input_tree_flattened = flatten(input_tree) + + # Output is: + # [('a', 1), ('b', 2), ('c', 3), ('d', 4)] + # ['a', 1, 'b', 2, 'c', 3, 'd', 4] + ``` + + Edge Cases for atoms: + + ```python + flatten_up_to(0, 0) # Output: [0] + flatten_up_to(0, [0, 1, 2]) # Output: [[0, 1, 2]] + flatten_up_to([0, 1, 2], 0) # Output: TypeError + flatten_up_to([0, 1, 2], [0, 1, 2]) # Output: [0, 1, 2] + ``` + + Args: + shallow_tree: a possibly pruned structure of input_tree. + input_tree: an atom or a nested structure. + Note, numpy arrays are considered atoms. + check_types: bool. If True, check that each node in shallow_tree has the + same type as the corresponding node in input_tree. + expand_composites: If true, then composite tensors such as + `tf.sparse.SparseTensor` and `tf.RaggedTensor` are expanded into their + component tensors. + + Returns: + A Python list, the partially flattened version of `input_tree` according to + the structure of `shallow_tree`. + + Raises: + TypeError: If `shallow_tree` is a nested structure but `input_tree` is not. + TypeError: If the structure types of `shallow_tree` are different from + `input_tree`. + ValueError: If the structure lengths of `shallow_tree` are different from + `input_tree`. + """ + return nest_util.flatten_up_to( + nest_util.Modality.CORE, + shallow_tree, + input_tree, + check_types, + expand_composites, + ) + + +def flatten_with_tuple_paths_up_to(shallow_tree, + input_tree, + check_types=True, + expand_composites=False): + """Flattens `input_tree` up to `shallow_tree`. + + Any further depth in structure in `input_tree` is retained as structures in + the partially flattened output. + + Returns a list of (path, value) pairs, where value a leaf node in the + flattened tree, and path is the tuple path of that leaf in input_tree. + + If `shallow_tree` and `input_tree` are not sequences, this returns a + single-item list: `[((), input_tree)]`. + + Use Case: + + Sometimes we may wish to partially flatten a nested sequence, retaining some + of the nested structure. We achieve this by specifying a shallow structure, + `shallow_tree`, we wish to flatten up to. + + The input, `input_tree`, can be thought of as having the same structure layout + as `shallow_tree`, but with leaf nodes that are themselves tree structures. + + Examples: + + ```python + input_tree = [[[2, 2], [3, 3]], [[4, 9], [5, 5]]] + shallow_tree = [[True, True], [False, True]] + + flattened_input_tree = flatten_with_tuple_paths_up_to(shallow_tree, + input_tree) + flattened_shallow_tree = flatten_with_tuple_paths_up_to(shallow_tree, + shallow_tree) + + # Output is: + # [((0, 0), [2, 2]), + # ((0, 1), [3, 3]), + # ((1, 0), [4, 9]), + # ((1, 1), [5, 5])] + # + # [((0, 0), True), + # ((0, 1), True), + # ((1, 0), False), + # ((1, 1), True)] + ``` + + ```python + input_tree = [[('a', 1), [('b', 2), [('c', 3), [('d', 4)]]]]] + shallow_tree = [['level_1', ['level_2', ['level_3', ['level_4']]]]] + + input_tree_flattened_as_shallow_tree = flatten_up_to(shallow_tree, input_tree) + input_tree_flattened = flatten(input_tree) + + # Output is: + # [((0, 0), ('a', 1)), + # ((0, 1, 0), ('b', 2)), + # ((0, 1, 1, 0), ('c', 3)), + # ((0, 1, 1, 1), ('d', 4))] + # ['a', 1, 'b', 2, 'c', 3, 'd', 4] + ``` + + Non-Sequence Edge Cases: + + ```python + flatten_with_tuple_paths_up_to(0, 0) # Output: [(), 0] + + flatten_with_tuple_paths_up_to(0, [0, 1, 2]) # Output: [(), [0, 1, 2]] + + flatten_with_tuple_paths_up_to([0, 1, 2], 0) # Output: TypeError + + flatten_with_tuple_paths_up_to([0, 1, 2], [0, 1, 2]) + # Output: [((0,) 0), ((1,), 1), ((2,), 2)] + ``` + + Args: + shallow_tree: a possibly pruned structure of input_tree. + input_tree: an atom or a nested structure. + Note, numpy arrays are considered atoms. + check_types: bool. If True, check that each node in shallow_tree has the + same type as the corresponding node in input_tree. + expand_composites: If true, then composite tensors such as + `tf.sparse.SparseTensor` and `tf.RaggedTensor` are expanded into their + component tensors. + + Returns: + A Python list, the partially flattened version of `input_tree` according to + the structure of `shallow_tree`. + + Raises: + TypeError: If `shallow_tree` is a nested structure but `input_tree` is not. + TypeError: If the structure types of `shallow_tree` are different from + `input_tree`. + ValueError: If the structure lengths of `shallow_tree` are different from + `input_tree`. + """ + is_nested_fn = _is_nested_or_composite if expand_composites else is_nested + assert_shallow_structure(shallow_tree, + input_tree, + check_types=check_types, + expand_composites=expand_composites) + return list( + nest_util.yield_flat_up_to( + nest_util.Modality.CORE, shallow_tree, input_tree, is_nested_fn + ) + ) + + +@tf_export("__internal__.nest.map_structure_up_to", v1=[]) +def map_structure_up_to(shallow_tree, func, *inputs, **kwargs): + """Applies a function or op to a number of partially flattened inputs. + + The `inputs` are flattened up to `shallow_tree` before being mapped. + + Use Case: + + Sometimes we wish to apply a function to a partially flattened + structure (for example when the function itself takes structure inputs). We + achieve this by specifying a shallow structure, `shallow_tree` we wish to + flatten up to. + + The `inputs`, can be thought of as having the same structure layout as + `shallow_tree`, but with leaf nodes that are themselves tree structures. + + This function therefore will return something with the same base structure as + `shallow_tree`. + + Examples: + + ```python + shallow_tree = [None, None] + inp_val = [1, 2, 3] + out = map_structure_up_to(shallow_tree, lambda x: 2 * x, inp_val) + + # Output is: [2, 4] + ``` + + ```python + ab_tuple = collections.namedtuple("ab_tuple", "a, b") + op_tuple = collections.namedtuple("op_tuple", "add, mul") + inp_val = ab_tuple(a=2, b=3) + inp_ops = ab_tuple(a=op_tuple(add=1, mul=2), b=op_tuple(add=2, mul=3)) + out = map_structure_up_to(inp_val, lambda val, ops: (val + ops.add) * ops.mul, + inp_val, inp_ops) + + # Output is: ab_tuple(a=6, b=15) + ``` + + ```python + data_list = [[2, 4, 6, 8], [[1, 3, 5, 7, 9], [3, 5, 7]]] + name_list = ['evens', ['odds', 'primes']] + out = map_structure_up_to( + name_list, + lambda name, sec: "first_{}_{}".format(len(sec), name), + name_list, data_list) + + # Output is: ['first_4_evens', ['first_5_odds', 'first_3_primes']] + ``` + + Args: + shallow_tree: a shallow structure, common to all the inputs. + func: callable which will be applied to each input individually. + *inputs: structures that are compatible with shallow_tree. The function + `func` is applied to corresponding structures due to partial flattening + of each input, so the function must support arity of `len(inputs)`. + **kwargs: kwargs to feed to func(). Special kwarg + `check_types` is not passed to func, but instead determines whether the + types of iterables within the structures have to be same (e.g. + `map_structure(func, [1], (1,))` raises a `TypeError` exception). To allow + this set this argument to `False`. + + Raises: + TypeError: If `shallow_tree` is a nested structure but `input_tree` is not. + TypeError: If the structure types of `shallow_tree` are different from + `input_tree`. + ValueError: If the structure lengths of `shallow_tree` are different from + `input_tree`. + + Returns: + result of repeatedly applying `func`, with the same structure layout as + `shallow_tree`. + """ + return nest_util.map_structure_up_to( + nest_util.Modality.CORE, + shallow_tree, + lambda _, *values: func(*values), # Discards the path arg. + *inputs, + **kwargs, + ) + + +def map_structure_with_tuple_paths_up_to(shallow_tree, func, *inputs, **kwargs): + """Applies a function or op to a number of partially flattened inputs. + + Like map_structure_up_to(), except that the 'func' argument takes a path + tuple as its first argument, followed by the corresponding values from + *inputs. + + Example: + + ```python + lowercase = {'a': 'a', 'b': ('b0', 'b1')} + uppercase = {'a': 'A', 'b': ('B0', 'B1')} + + def print_path_and_values(path, *values): + print("path: {}, values: {}".format(path, values)) + + shallow_tree = {'a': None} + map_structure_with_tuple_paths_up_to(shallow_tree, + print_path_and_values, + lowercase, + uppercase) + path: ('a',), values: ('a', 'A') + path: ('b', 0), values: ('b0', 'B0') + path: ('b', 1), values: ('b1', 'B1') + + shallow_tree = {'b': None} + map_structure_with_tuple_paths_up_to(shallow_tree, + print_path_and_values, + lowercase, + uppercase, + check_types=False) + path: ('b', 1), values: (('bo', 'b1'), ('B0', 'B1')) + + shallow_tree = {'a': None, 'b': {1: None}} + map_structure_with_tuple_paths_up_to(shallow_tree, + print_path_and_values, + lowercase, + uppercase, + check_types=False) + path: ('a',), values: ('a', 'A') + path: ('b', 1), values: ('b1', B1') + ``` + + Args: + shallow_tree: a shallow structure, common to all the inputs. + func: callable that takes args (path, inputs_0_value, ... , inputs_N_value), + where path is a tuple path to an atom in shallow_tree, and inputs_i_value + is the corresponding value from inputs[i]. + *inputs: structures that are all structurally compatible with shallow_tree. + **kwargs: kwargs to feed to func(). Special kwarg `check_types` is not + passed to func, but instead determines whether the types of iterables + within the structures have to be same (e.g. `map_structure(func, [1], + (1,))` raises a `TypeError` exception). To allow this set this argument to + `False`. + + Raises: + TypeError: If `shallow_tree` is a nested structure but one of `*inputs` is + not. + TypeError: If the structure types of `shallow_tree` are different from + `input_tree`. + ValueError: If the structure lengths of `shallow_tree` are different from + `input_tree`. + + Returns: + Result of repeatedly applying `func`. Has the same structure layout as + `shallow_tree`. + """ + return nest_util.map_structure_up_to( + nest_util.Modality.CORE, shallow_tree, func, *inputs, **kwargs + ) + + +@tf_export("__internal__.nest.get_traverse_shallow_structure", v1=[]) +def get_traverse_shallow_structure(traverse_fn, structure, + expand_composites=False): + """Generates a shallow structure from a `traverse_fn` and `structure`. + + `traverse_fn` must accept any possible subtree of `structure` and return + a depth=1 structure containing `True` or `False` values, describing which + of the top-level subtrees may be traversed. It may also + return scalar `True` or `False` "traversal is OK / not OK for all subtrees." + + Examples are available in the unit tests (nest_test.py). + + Args: + traverse_fn: Function taking a substructure and returning either a scalar + `bool` (whether to traverse that substructure or not) or a depth=1 + shallow structure of the same type, describing which parts of the + substructure to traverse. + structure: The structure to traverse. + expand_composites: If true, then composite tensors such as + `tf.sparse.SparseTensor` and `tf.RaggedTensor` are expanded into their + component tensors. + + Returns: + A shallow structure containing python bools, which can be passed to + `map_structure_up_to` and `flatten_up_to`. + + Raises: + TypeError: if `traverse_fn` returns a nested structure for an atom input. + or a structure with depth higher than 1 for a nested structure input, + or if any leaf values in the returned structure or scalar are not type + `bool`. + """ + is_nested_fn = _is_nested_or_composite if expand_composites else is_nested + to_traverse = traverse_fn(structure) + if not is_nested_fn(structure): + if not isinstance(to_traverse, bool): + raise TypeError("traverse_fn returned structure: %s for non-structure: %s" + % (to_traverse, structure)) + return to_traverse + level_traverse = [] + if isinstance(to_traverse, bool): + if not to_traverse: + # Do not traverse this substructure at all. Exit early. + return False + else: + # Traverse the entire substructure. + for branch in nest_util.yield_value(nest_util.Modality.CORE, structure): + level_traverse.append( + get_traverse_shallow_structure(traverse_fn, branch, + expand_composites=expand_composites)) + elif not is_nested_fn(to_traverse): + raise TypeError("traverse_fn returned a non-bool scalar: %s for input: %s" + % (to_traverse, structure)) + else: + # Traverse some subset of this substructure. + assert_shallow_structure(to_traverse, structure, + expand_composites=expand_composites) + for t, branch in zip( + nest_util.yield_value(nest_util.Modality.CORE, to_traverse), + nest_util.yield_value(nest_util.Modality.CORE, structure), + ): + if not isinstance(t, bool): + raise TypeError( + "traverse_fn didn't return a depth=1 structure of bools. saw: %s " + " for structure: %s" % (to_traverse, structure)) + if t: + level_traverse.append( + get_traverse_shallow_structure(traverse_fn, branch)) + else: + level_traverse.append(False) + return nest_util.sequence_like(structure, level_traverse) + + +@tf_export("__internal__.nest.yield_flat_paths", v1=[]) +def yield_flat_paths(nest, expand_composites=False): + """Yields paths for some nested structure. + + Refer to [tf.nest](https://www.tensorflow.org/api_docs/python/tf/nest) + for the definition of a structure. + + Paths are lists of objects which can be str-converted, which may include + integers or other types which are used as indices in a dict. + + The flat list will be in the corresponding order as if you called + `nest.flatten` on the structure. This is handy for naming Tensors such + the TF scope structure matches the tuple structure. + + E.g. if we have a tuple `value = Foo(a=3, b=Bar(c=23, d=42))` + + ```shell + nest.flatten(value) + [3, 23, 42] + list(nest.yield_flat_paths(value)) + [('a',), ('b', 'c'), ('b', 'd')] + ``` + + ```shell + list(nest.yield_flat_paths({'a': [3]})) + [('a', 0)] + list(nest.yield_flat_paths({'a': 3})) + [('a',)] + ``` + + Args: + nest: the value to produce a flattened paths list for. + expand_composites: If true, then composite tensors such as + `tf.sparse.SparseTensor` and `tf.RaggedTensor` are expanded into their + component tensors. + + Yields: + Tuples containing index or key values which form the path to a specific + leaf value in the nested structure. + """ + is_nested_fn = _is_nested_or_composite if expand_composites else is_nested + for k, _ in nest_util.yield_flat_up_to( + nest_util.Modality.CORE, nest, nest, is_nested_fn + ): + yield k + + +def flatten_with_joined_string_paths(structure, separator="/", + expand_composites=False): + """Returns a list of (string path, atom) tuples. + + The order of tuples produced matches that of `nest.flatten`. This allows you + to flatten a nested structure while keeping information about where in the + structure each atom was located. See `nest.yield_flat_paths` + for more information. + + Args: + structure: the nested structure to flatten. + separator: string to separate levels of hierarchy in the results, defaults + to '/'. + expand_composites: If true, then composite tensors such as + `tf.sparse.SparseTensor` and `tf.RaggedTensor` are expanded into their + component tensors. + + Returns: + A list of (string, atom) tuples. + """ + flat_paths = yield_flat_paths(structure, expand_composites=expand_composites) + def stringify_and_join(path_elements): + return separator.join(str(path_element) for path_element in path_elements) + + flat_string_paths = (stringify_and_join(path) for path in flat_paths) + return list(zip(flat_string_paths, + flatten(structure, expand_composites=expand_composites))) + + +def flatten_with_tuple_paths(structure, expand_composites=False): + """Returns a list of `(tuple_path, atom)` tuples. + + The order of pairs produced matches that of `nest.flatten`. This allows you + to flatten a nested structure while keeping information about where in the + structure each atom was located. See `nest.yield_flat_paths` + for more information about tuple paths. + + Args: + structure: the nested structure to flatten. + expand_composites: If true, then composite tensors such as + `tf.sparse.SparseTensor` and `tf.RaggedTensor` are expanded into their + component tensors. + + Returns: + A list of `(tuple_path, atom)` tuples. Each `tuple_path` is a tuple + of indices and/or dictionary keys that uniquely specify the path to + `atom` within `structure`. + """ + return list(zip(yield_flat_paths(structure, + expand_composites=expand_composites), + flatten(structure, expand_composites=expand_composites))) + + +@tf_export("__internal__.nest.list_to_tuple", v1=[]) +def list_to_tuple(structure): + """Replace all lists with tuples. + + The fork of nest that tf.data uses treats lists as atoms, while + tf.nest treats them as structures to recurse into. Keras has chosen to adopt + the latter convention, and must therefore deeply replace all lists with tuples + before passing structures to Dataset.from_generator. + + Args: + structure: A nested structure to be remapped. + + Returns: + structure mapped to replace all lists with tuples. + """ + def sequence_fn(instance, args): + if isinstance(instance, list): + return tuple(args) + return nest_util.sequence_like(instance, args) + + return nest_util.pack_sequence_as( + nest_util.Modality.CORE, + structure, + flatten(structure), + False, + sequence_fn=sequence_fn, + ) + + +_pywrap_utils.RegisterType("Mapping", _collections_abc.Mapping) +_pywrap_utils.RegisterType("MutableMapping", _collections_abc.MutableMapping) +_pywrap_utils.RegisterType("Sequence", _collections_abc.Sequence) +_pywrap_utils.RegisterType("MappingView", _collections_abc.MappingView) +_pywrap_utils.RegisterType("ObjectProxy", _wrapt.ObjectProxy) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/nest_util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/nest_util.py new file mode 100644 index 0000000000000000000000000000000000000000..f40cc2d3642341113c797ed69fbe6a0b4c740e8e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/nest_util.py @@ -0,0 +1,1727 @@ +# Copyright 2023 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""Utility methods for handling nests. + +This module encapsulates different semantics of handling nests by the public +tf.nest APIs and internal tf.data APIs. The difference in semantics exists for +historic reasons and reconciliation would require a non-backwards compatible +change. + +The implementation of the different semantics use a common utility to +avoid / minimize further divergence between the two APIs over time. +""" + +import collections as _collections +import enum + +import six as _six +import wrapt as _wrapt + +from tensorflow.python import pywrap_tensorflow # pylint: disable=unused-import +from tensorflow.python.platform import tf_logging +from tensorflow.python.util import _pywrap_utils +from tensorflow.python.util.compat import collections_abc as _collections_abc +from tensorflow.python.util.custom_nest_protocol import CustomNestProtocol + + +_is_mapping_view = _pywrap_utils.IsMappingView +_is_attrs = _pywrap_utils.IsAttrs +_is_composite_tensor = _pywrap_utils.IsCompositeTensor +_is_type_spec = _pywrap_utils.IsTypeSpec +_is_mutable_mapping = _pywrap_utils.IsMutableMapping +_is_mapping = _pywrap_utils.IsMapping +_tf_data_is_nested = _pywrap_utils.IsNestedForData +_tf_data_flatten = _pywrap_utils.FlattenForData +_tf_core_is_nested = _pywrap_utils.IsNested +_is_nested_or_composite = _pywrap_utils.IsNestedOrComposite +# See the swig file (util.i) for documentation. +same_namedtuples = _pywrap_utils.SameNamedtuples + + +STRUCTURES_HAVE_MISMATCHING_TYPES = ( + "The two structures don't have the same sequence type. Input structure has " + "type {input_type}, while shallow structure has type {shallow_type}." +) + +STRUCTURES_HAVE_MISMATCHING_LENGTHS = ( + "The two structures don't have the same sequence length. Input " + "structure has length {input_length}, while shallow structure has length " + "{shallow_length}." +) + +INPUT_TREE_SMALLER_THAN_SHALLOW_TREE = ( + "The input_tree has fewer items than the shallow_tree. Input structure " + "has length {input_size}, while shallow structure has length " + "{shallow_size}." +) + +SHALLOW_TREE_HAS_INVALID_KEYS = ( + "The shallow_tree's keys are not a subset of the input_tree's keys. The " + "shallow_tree has the following keys that are not in the input_tree: {}." +) + + +class Modality(enum.Enum): + """Modality/semantic used for treating nested structures. + + - Modality.CORE follows tensorflow_core/tf.nest semantics. + + The following collection types are recognized by `tf.nest` as nested + structures: + + * `collections.abc.Sequence` (except `string` and `bytes`). + This includes `list`, `tuple`, and `namedtuple`. + * `collections.abc.Mapping` (with sortable keys). + This includes `dict` and `collections.OrderedDict`. + * `collections.abc.MappingView` (with sortable keys). + * [`attr.s` classes](https://www.attrs.org/). + + Any other values are considered **atoms**. Not all collection types are + considered nested structures. For example, the following types are + considered atoms: + + * `set`; `{"a", "b"}` is an atom, while `["a", "b"]` is a nested structure. + * [`dataclass` classes](https://docs.python.org/library/dataclasses.html) + * `tf.Tensor` + * `numpy.array` + + - Modality.DATA follows tf.data's nest semantics. + + This modality makes two changes: + 1. It removes support for lists as a level of nesting in nested structures. + 2. It adds support for `SparseTensorValue` as an atomic element. + + The motivation for this change is twofold: + + 1. It seems more natural for lists to be treated (e.g. in Dataset + constructors) + as tensors, rather than lists of (lists of...) tensors. + 2. This is needed because `SparseTensorValue` is implemented as a `namedtuple` + that would normally be flattened and we want to be able to create sparse + tensor from `SparseTensorValue's similarly to creating tensors from numpy + arrays. + """ + + CORE = "CORE" + DATA = "DATA" + + +class _DotString(object): + __slots__ = [] + + def __str__(self): + return "." + + def __repr__(self): + return "." + + +_DOT = _DotString() + + +def is_nested(modality, structure): + """Returns true if its input is a nested structure. + + For Modality.CORE refer to + [tf.nest](https://www.tensorflow.org/api_docs/python/tf/nest) + for the definition of a nested structure. + + Args: + modality: enum value of supported modality [Modality.CORE or Modality.DATA] + structure: the value to test. + + Returns: + True if the input is a nested structure. + """ + if modality == Modality.CORE: + return _tf_core_is_nested(structure) + elif modality == Modality.DATA: + return _tf_data_is_nested(structure) + else: + raise ValueError( + "Unknown modality used {} for nested structure".format(modality) + ) + + +# TODO(b/225045380): Move to a "leaf" library to use in trace_type. +def is_namedtuple(instance, strict=False): + """Returns True iff `instance` is a `namedtuple`. + + Args: + instance: An instance of a Python object. + strict: If True, `instance` is considered to be a `namedtuple` only if it is + a "plain" namedtuple. For instance, a class inheriting from a `namedtuple` + will be considered to be a `namedtuple` iff `strict=False`. + + Returns: + True if `instance` is a `namedtuple`. + """ + return _pywrap_utils.IsNamedtuple(instance, strict) + + +def sequence_like(instance, args): + """Converts the sequence `args` to the same type as `instance`. + + Args: + instance: an instance of `tuple`, `list`, `namedtuple`, `dict`, + `collections.OrderedDict`, or `composite_tensor.Composite_Tensor` or + `type_spec.TypeSpec`. + args: items to be converted to the `instance` type. + + Returns: + `args` with the type of `instance`. + """ + if _is_mutable_mapping(instance): + # Pack dictionaries in a deterministic order by sorting the keys. + # Notice this means that we ignore the original order of `OrderedDict` + # instances. This is intentional, to avoid potential bugs caused by mixing + # ordered and plain dicts (e.g., flattening a dict but using a + # corresponding `OrderedDict` to pack it back). + result = dict(zip(_tf_core_sorted(instance), args)) + instance_type = type(instance) + if instance_type == _collections.defaultdict: + d = _collections.defaultdict(instance.default_factory) + else: + d = instance_type() + for key in instance: + d[key] = result[key] + return d + elif _is_mapping(instance): + result = dict(zip(_tf_core_sorted(instance), args)) + instance_type = type(instance) + if not getattr(instance_type, "__supported_by_tf_nest__", False): + tf_logging.log_first_n( + tf_logging.WARN, + "Mapping types may not work well with tf.nest. " + "Prefer using MutableMapping for {}".format(instance_type), + 1, + ) + try: + return instance_type((key, result[key]) for key in instance) + except TypeError as err: + # pylint: disable=raise-missing-from + raise TypeError( + "Error creating an object of type {} like {}. Note that " + "it must accept a single positional argument " + "representing an iterable of key-value pairs, in " + "addition to self. Cause: {}".format(type(instance), instance, err) + ) + elif _is_mapping_view(instance): + # We can't directly construct mapping views, so we create a list instead + return list(args) + elif is_namedtuple(instance) or _is_attrs(instance): + if isinstance(instance, _wrapt.ObjectProxy): + instance_type = type(instance.__wrapped__) + else: + instance_type = type(instance) + return instance_type(*args) + elif _is_composite_tensor(instance): + assert len(args) == 1 + spec = instance._type_spec # pylint: disable=protected-access + return spec._from_components(args[0]) # pylint: disable=protected-access + elif _is_type_spec(instance): + # Pack a CompositeTensor's components according to a TypeSpec. + assert len(args) == 1 + return instance._from_components(args[0]) # pylint: disable=protected-access + elif isinstance(instance, _six.moves.range): + return sequence_like(list(instance), args) + elif isinstance(instance, _wrapt.ObjectProxy): + # For object proxies, first create the underlying type and then re-wrap it + # in the proxy type. + return type(instance)(sequence_like(instance.__wrapped__, args)) + elif isinstance(instance, CustomNestProtocol): + metadata = instance.__tf_flatten__()[0] + return instance.__tf_unflatten__(metadata, tuple(args)) + else: + # Not a namedtuple + return type(instance)(args) + + +def _get_attrs_items(obj): + """Returns a list of (name, value) pairs from an attrs instance. + + TODO(b/268078256): check if this comment is valid, and if so, ensure it's + handled in the function below. + The list will be sorted by name. + + Args: + obj: an object. + + Returns: + A list of (attr_name, attr_value) pairs, sorted by attr_name. + """ + attrs = getattr(obj.__class__, "__attrs_attrs__") + attr_names = (a.name for a in attrs) + return [(attr_name, getattr(obj, attr_name)) for attr_name in attr_names] + + +def _tf_core_sorted(dict_): + """Returns a sorted list of the dict keys, with error if keys not sortable.""" + try: + return sorted(dict_.keys()) + except TypeError: + # pylint: disable=raise-missing-from + raise TypeError("nest only supports dicts with sortable keys.") + + +def _tf_data_sorted(dict_): + """Returns a sorted list of the dict keys, with error if keys not sortable.""" + try: + return sorted(list(dict_)) + except TypeError as e: + # pylint: disable=raise-missing-from + raise TypeError( + f"nest only supports dicts with sortable keys. Error: {e.message}" + ) + + +def yield_value(modality, iterable): + """Yield elements of `iterable` in a deterministic order. + + Args: + modality: enum value of supported modality [Modality.CORE or Modality.DATA] + iterable: an iterable. + + Yields: + The iterable elements in a deterministic order. + """ + if modality == Modality.CORE: + yield from _tf_core_yield_value(iterable) + elif modality == Modality.DATA: + yield from _tf_data_yield_value(iterable) + else: + raise ValueError( + "Unknown modality used {} for nested structure".format(modality) + ) + + +def _tf_core_yield_value(iterable): + for _, v in _tf_core_yield_sorted_items(iterable): + yield v + + +def yield_sorted_items(modality, iterable): + if modality == Modality.CORE: + return _tf_core_yield_sorted_items(iterable) + else: + raise ValueError( + "Unknown modality used {} for nested structure".format(modality) + ) + + +def _tf_core_yield_sorted_items(iterable): + """Yield (key, value) pairs for `iterable` in a deterministic order. + + For Sequences, the key will be an int, the array index of a value. + For Mappings, the key will be the dictionary key. + For objects (e.g. namedtuples), the key will be the attribute name. + + In all cases, the keys will be iterated in sorted order. + + Args: + iterable: an iterable. + + Yields: + The iterable's (key, value) pairs, in order of sorted keys. + """ + # Ordered to check common structure types (list, tuple, dict) first. + if isinstance(iterable, list): + for item in enumerate(iterable): + yield item + # namedtuples handled separately to avoid expensive namedtuple check. + elif type(iterable) == tuple: # pylint: disable=unidiomatic-typecheck + for item in enumerate(iterable): + yield item + elif isinstance(iterable, (dict, _collections_abc.Mapping)): + # Iterate through dictionaries in a deterministic order by sorting the + # keys. Notice this means that we ignore the original order of `OrderedDict` + # instances. This is intentional, to avoid potential bugs caused by mixing + # ordered and plain dicts (e.g., flattening a dict but using a + # corresponding `OrderedDict` to pack it back). + for key in _tf_core_sorted(iterable): + yield key, iterable[key] + elif _is_attrs(iterable): + for item in _get_attrs_items(iterable): + yield item + elif is_namedtuple(iterable): + for field in iterable._fields: + yield field, getattr(iterable, field) + elif _is_composite_tensor(iterable): + type_spec = iterable._type_spec # pylint: disable=protected-access + yield type_spec.value_type.__name__, type_spec._to_components(iterable) # pylint: disable=protected-access + elif _is_type_spec(iterable): + # Note: to allow CompositeTensors and their TypeSpecs to have matching + # structures, we need to use the same key string here. + yield iterable.value_type.__name__, iterable._component_specs # pylint: disable=protected-access + elif isinstance(iterable, CustomNestProtocol): + flat_component = iterable.__tf_flatten__()[1] + assert isinstance(flat_component, tuple) + yield from enumerate(flat_component) + else: + for item in enumerate(iterable): + yield item + + +def _tf_data_yield_value(iterable): + """Yield elements of `iterable` in a deterministic order. + + Args: + iterable: an iterable. + + Yields: + The iterable elements in a deterministic order. + """ + # pylint: disable=protected-access + if isinstance(iterable, _collections_abc.Mapping): + # Iterate through dictionaries in a deterministic order by sorting the + # keys. Notice this means that we ignore the original order of `OrderedDict` + # instances. This is intentional, to avoid potential bugs caused by mixing + # ordered and plain dicts (e.g., flattening a dict but using a + # corresponding `OrderedDict` to pack it back). + for key in _tf_data_sorted(iterable): + yield iterable[key] + # To avoid circular imports. sparse_tensor + # depends on tensorflow/python/util/nest.py transitively, and if we try to + # import sparse_tensor again, it results in a circular import. Instead, here + # we check the class name instead of using `isinstance`. + elif iterable.__class__.__name__ == "SparseTensorValue": + yield iterable + elif _is_attrs(iterable): + for _, attr in _get_attrs_items(iterable): + yield attr + elif isinstance(iterable, CustomNestProtocol): + flat_component = iterable.__tf_flatten__()[1] + assert isinstance(flat_component, tuple) + yield from flat_component + else: + for value in iterable: + yield value + + +def assert_same_structure( + modality, nest1, nest2, check_types=True, expand_composites=False +): + """Asserts that two structures are nested in the same way. + + For Modality.CORE refer to + [tf.nest](https://www.tensorflow.org/api_docs/python/tf/nest) + for the definition of a structure. Note the method does not check the types of + atoms inside the structures. + + Examples: + + * These atom vs. atom comparisons will pass: + + >>> tf.nest.assert_same_structure(1.5, tf.Variable(1, tf.uint32)) + >>> tf.nest.assert_same_structure("abc", np.array([1, 2])) + + * These nested structure vs. nested structure comparisons will pass: + + >>> structure1 = (((1, 2), 3), 4, (5, 6)) + >>> structure2 = ((("foo1", "foo2"), "foo3"), "foo4", ("foo5", "foo6")) + >>> structure3 = [(("a", "b"), "c"), "d", ["e", "f"]] + >>> tf.nest.assert_same_structure(structure1, structure2) + >>> tf.nest.assert_same_structure(structure1, structure3, check_types=False) + + >>> import collections + >>> tf.nest.assert_same_structure( + ... collections.namedtuple("bar", "a b")(1, 2), + ... collections.namedtuple("foo", "a b")(2, 3), + ... check_types=False) + + >>> tf.nest.assert_same_structure( + ... collections.namedtuple("bar", "a b")(1, 2), + ... { "a": 1, "b": 2 }, + ... check_types=False) + + >>> tf.nest.assert_same_structure( + ... { "a": 1, "b": 2, "c": 3 }, + ... { "c": 6, "b": 5, "a": 4 }) + + >>> ragged_tensor1 = tf.RaggedTensor.from_row_splits( + ... values=[3, 1, 4, 1, 5, 9, 2, 6], + ... row_splits=[0, 4, 4, 7, 8, 8]) + >>> ragged_tensor2 = tf.RaggedTensor.from_row_splits( + ... values=[3, 1, 4], + ... row_splits=[0, 3]) + >>> tf.nest.assert_same_structure( + ... ragged_tensor1, + ... ragged_tensor2, + ... expand_composites=True) + + * These examples will raise exceptions: + + >>> tf.nest.assert_same_structure([0, 1], np.array([0, 1])) + Traceback (most recent call last): + ... + ValueError: The two structures don't have the same nested structure + + >>> tf.nest.assert_same_structure( + ... collections.namedtuple('bar', 'a b')(1, 2), + ... collections.namedtuple('foo', 'a b')(2, 3)) + Traceback (most recent call last): + ... + TypeError: The two structures don't have the same nested structure + + For Modality.DATA, nested structures are treated differently than + Modality.CORE. Please refer to class Modality's documentation above to read up + on these differences. + + Args: + modality: enum value of supported modality [Modality.CORE or Modality.DATA] + nest1: an atom or a nested structure. + nest2: an atom or a nested structure. + check_types: - For Modality.CORE: if `True` (default) types of structures + are checked as well, including the keys of dictionaries. If set to + `False`, for example a list and a tuple of objects will look the same if + they have the same size. Note that namedtuples with identical name and + fields are always considered to have the same shallow structure. Two types + will also be considered the same if they are both list subtypes (which + allows "list" and "_ListWrapper" from trackable dependency tracking to + compare equal). `check_types=True` only checks type of sub-structures. The + types of atoms are not checked. - For Modality.DATA: if `True` (default) + types of sequences should be same as well. For dictionary, "type" of + dictionary is considered to include its keys. In other words, two + dictionaries with different keys are considered to have a different + "type". If set to `False`, two iterables are considered same as long as + they yield the elements that have same structures. + expand_composites: Arg only valid for Modality.CORE. If true, then composite + tensors such as `tf.sparse.SparseTensor` and `tf.RaggedTensor` are + expanded into their component tensors. + + Raises: + ValueError: If the two structures do not have the same number of atoms or + if the two structures are not nested in the same way. + TypeError: If the two structures differ in the type of sequence in any of + their substructures. Only possible if `check_types` is `True`. + """ + if modality == Modality.CORE: + _tf_core_assert_same_structure(nest1, nest2, check_types, expand_composites) + elif modality == Modality.DATA: + _tf_data_assert_same_structure(nest1, nest2, check_types) + else: + raise ValueError( + "Unknown modality used {} for nested structure".format(modality) + ) + + +# pylint: disable=missing-function-docstring +def _tf_core_assert_same_structure( + nest1, nest2, check_types=True, expand_composites=False +): + # Convert to bool explicitly as otherwise pybind will not be able# to handle + # type mismatch message correctly. See GitHub issue 42329 for details. + check_types = bool(check_types) + expand_composites = bool(expand_composites) + try: + _pywrap_utils.AssertSameStructure( + nest1, nest2, check_types, expand_composites + ) + except (ValueError, TypeError) as e: + str1 = str(_tf_core_map_structure(lambda _: _DOT, nest1)) + str2 = str(_tf_core_map_structure(lambda _: _DOT, nest2)) + raise type(e)( + "%s\nEntire first structure:\n%s\nEntire second structure:\n%s" + % (str(e), str1, str2) + ) + + +def _tf_data_assert_same_structure(nest1, nest2, check_types=True): + _pywrap_utils.AssertSameStructureForData(nest1, nest2, check_types) + + +def _tf_core_packed_nest_with_indices( + structure, flat, index, is_nested_fn, sequence_fn=None +): + """Helper function for pack_sequence_as. + + Args: + structure: structure to mimic. + flat: Flattened values to output substructure for. + index: Index at which to start reading from flat. + is_nested_fn: Function used to test if a value should be treated as a nested + structure. + sequence_fn: Function used to generate a new strcuture instance. + + Returns: + The tuple (new_index, child), where: + * new_index - the updated index into `flat` having processed `structure`. + * packed - the subset of `flat` corresponding to `structure`, + having started at `index`, and packed into the same nested + format. + + Raises: + ValueError: if `structure` contains more atoms than `flat` + (assuming indexing starts from `index`). + """ + packed = [] + sequence_fn = sequence_fn or sequence_like + for s in _tf_core_yield_value(structure): + if is_nested_fn(s): + new_index, child = _tf_core_packed_nest_with_indices( + s, flat, index, is_nested_fn, sequence_fn + ) + packed.append(sequence_fn(s, child)) + index = new_index + else: + packed.append(flat[index]) + index += 1 + return index, packed + + +def _tf_data_packed_nest_with_indices(structure, flat, index): + """Helper function for pack_nest_as. + + Args: + structure: Substructure (tuple of elements and/or tuples) to mimic + flat: Flattened values to output substructure for. + index: Index at which to start reading from flat. + + Returns: + The tuple (new_index, child), where: + * new_index - the updated index into `flat` having processed `structure`. + * packed - the subset of `flat` corresponding to `structure`, + having started at `index`, and packed into the same nested + format. + + Raises: + ValueError: if `structure` contains more elements than `flat` + (assuming indexing starts from `index`). + """ + packed = [] + for s in _tf_data_yield_value(structure): + if _tf_data_is_nested(s): + new_index, child = _tf_data_packed_nest_with_indices(s, flat, index) + packed.append(sequence_like(s, child)) # pylint: disable=protected-access + index = new_index + else: + packed.append(flat[index]) + index += 1 + return index, packed + + +def flatten(modality, structure, expand_composites=False): + """Flattens a nested structure. + + - For Modality.CORE: refer to + [tf.nest](https://www.tensorflow.org/api_docs/python/tf/nest) + for the definition of a structure. + + If the structure is an atom, then returns a single-item list: [structure]. + + This is the inverse of the `nest.pack_sequence_as` method that takes in a + flattened list and re-packs it into the nested structure. + + In the case of dict instances, the sequence consists of the values, sorted by + key to ensure deterministic behavior. This is true also for OrderedDict + instances: their sequence order is ignored, the sorting order of keys is used + instead. The same convention is followed in `nest.pack_sequence_as`. This + correctly repacks dicts and OrderedDicts after they have been flattened, and + also allows flattening an OrderedDict and then repacking it back using a + corresponding plain dict, or vice-versa. Dictionaries with non-sortable keys + cannot be flattened. + + Users must not modify any collections used in nest while this function is + running. + + Examples: + + 1. Python dict (ordered by key): + + >>> dict = { "key3": "value3", "key1": "value1", "key2": "value2" } + >>> tf.nest.flatten(dict) + ['value1', 'value2', 'value3'] + + 2. For a nested python tuple: + + >>> tuple = ((1.0, 2.0), (3.0, 4.0, 5.0), 6.0) + >>> tf.nest.flatten(tuple) + [1.0, 2.0, 3.0, 4.0, 5.0, 6.0] + + 3. For a nested dictionary of dictionaries: + + >>> dict = { "key3": {"c": (1.0, 2.0), "a": (3.0)}, + ... "key1": {"m": "val1", "g": "val2"} } + >>> tf.nest.flatten(dict) + ['val2', 'val1', 3.0, 1.0, 2.0] + + 4. Numpy array (will not flatten): + + >>> array = np.array([[1, 2], [3, 4]]) + >>> tf.nest.flatten(array) + [array([[1, 2], + [3, 4]])] + + 5. `tf.Tensor` (will not flatten): + + >>> tensor = tf.constant([[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]]) + >>> tf.nest.flatten(tensor) + [] + + 6. `tf.RaggedTensor`: This is a composite tensor thats representation consists + of a flattened list of 'values' and a list of 'row_splits' which indicate how + to chop up the flattened list into different rows. For more details on + `tf.RaggedTensor`, please visit + https://www.tensorflow.org/api_docs/python/tf/RaggedTensor. + + with `expand_composites=False`, we just return the RaggedTensor as is. + + >>> tensor = tf.ragged.constant([[3, 1, 4, 1], [], [5, 9, 2]]) + >>> tf.nest.flatten(tensor, expand_composites=False) + [] + + with `expand_composites=True`, we return the component Tensors that make up + the RaggedTensor representation (the values and row_splits tensors) + + >>> tensor = tf.ragged.constant([[3, 1, 4, 1], [], [5, 9, 2]]) + >>> tf.nest.flatten(tensor, expand_composites=True) + [, + ] + + Args: + modality: enum value of supported modality [Modality.CORE or Modality.DATA] + structure: an atom or a nested structure. Note, numpy arrays are considered + atoms and are not flattened. + expand_composites: Arg valid for Modality.CORE only. If true, then composite + tensors such as `tf.sparse.SparseTensor` and `tf.RaggedTensor` are + expanded into their component tensors. + + Returns: + A Python list, the flattened version of the input. + + Raises: + TypeError: The nest is or contains a dict with non-sortable keys. + """ + if modality == Modality.CORE: + return _tf_core_flatten(structure, expand_composites) + elif modality == Modality.DATA: + return _tf_data_flatten(structure) + else: + raise ValueError( + "Unknown modality used {} for nested structure".format(modality) + ) + + +def _tf_core_flatten(structure, expand_composites=False): + """See comments for flatten() in tensorflow/python/util/nest.py.""" + if structure is None: + return [None] + expand_composites = bool(expand_composites) + return _pywrap_utils.Flatten(structure, expand_composites) + + +def pack_sequence_as( + modality, structure, flat_sequence, expand_composites, sequence_fn=None +): + """Returns a given flattened sequence packed into a given structure. + + - For Modality.CORE: Refer to + [tf.nest](https://www.tensorflow.org/api_docs/python/tf/nest) + for the definition of a structure. + + If `structure` is an atom, `flat_sequence` must be a single-item list; + in this case the return value is `flat_sequence[0]`. + + If `structure` is or contains a dict instance, the keys will be sorted to + pack the flat sequence in deterministic order. This is true also for + `OrderedDict` instances: their sequence order is ignored, the sorting order of + keys is used instead. The same convention is followed in `flatten`. + This correctly repacks dicts and `OrderedDict`s after they have been + flattened, and also allows flattening an `OrderedDict` and then repacking it + back using a corresponding plain dict, or vice-versa. + Dictionaries with non-sortable keys cannot be flattened. + + Examples: + + 1. Python dict: + + >>> structure = { "key3": "", "key1": "", "key2": "" } + >>> flat_sequence = ["value1", "value2", "value3"] + >>> tf.nest.pack_sequence_as(structure, flat_sequence) + {'key3': 'value3', 'key1': 'value1', 'key2': 'value2'} + + 2. For a nested python tuple: + + >>> structure = (('a','b'), ('c','d','e'), 'f') + >>> flat_sequence = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0] + >>> tf.nest.pack_sequence_as(structure, flat_sequence) + ((1.0, 2.0), (3.0, 4.0, 5.0), 6.0) + + 3. For a nested dictionary of dictionaries: + + >>> structure = { "key3": {"c": ('alpha', 'beta'), "a": ('gamma')}, + ... "key1": {"e": "val1", "d": "val2"} } + >>> flat_sequence = ['val2', 'val1', 3.0, 1.0, 2.0] + >>> tf.nest.pack_sequence_as(structure, flat_sequence) + {'key3': {'c': (1.0, 2.0), 'a': 3.0}, 'key1': {'e': 'val1', 'd': 'val2'}} + + 4. Numpy array (considered a scalar): + + >>> structure = ['a'] + >>> flat_sequence = [np.array([[1, 2], [3, 4]])] + >>> tf.nest.pack_sequence_as(structure, flat_sequence) + [array([[1, 2], + [3, 4]])] + + 5. tf.Tensor (considered a scalar): + + >>> structure = ['a'] + >>> flat_sequence = [tf.constant([[1., 2., 3.], [4., 5., 6.]])] + >>> tf.nest.pack_sequence_as(structure, flat_sequence) + [] + + 6. `tf.RaggedTensor`: This is a composite tensor thats representation consists + of a flattened list of 'values' and a list of 'row_splits' which indicate how + to chop up the flattened list into different rows. For more details on + `tf.RaggedTensor`, please visit + https://www.tensorflow.org/api_docs/python/tf/RaggedTensor. + + With `expand_composites=False`, we treat RaggedTensor as a scalar. + + >>> structure = { "foo": tf.ragged.constant([[1, 2], [3]]), + ... "bar": tf.constant([[5]]) } + >>> flat_sequence = [ "one", "two" ] + >>> tf.nest.pack_sequence_as(structure, flat_sequence, + ... expand_composites=False) + {'foo': 'two', 'bar': 'one'} + + With `expand_composites=True`, we expect that the flattened input contains + the tensors making up the ragged tensor i.e. the values and row_splits + tensors. + + >>> structure = { "foo": tf.ragged.constant([[1., 2.], [3.]]), + ... "bar": tf.constant([[5.]]) } + >>> tensors = tf.nest.flatten(structure, expand_composites=True) + >>> print(tensors) + [, + , + ] + >>> verified_tensors = [tf.debugging.check_numerics(t, 'invalid tensor: ') + ... if t.dtype==tf.float32 else t + ... for t in tensors] + >>> tf.nest.pack_sequence_as(structure, verified_tensors, + ... expand_composites=True) + {'foo': , + 'bar': } + + - For Modality.DATA: If `structure` is a scalar, `flat_sequence` must be a + single-element list; + in this case the return value is `flat_sequence[0]`. + + Args: + modality: enum value of supported modality [Modality.CORE or Modality.DATA] + structure: - For Modality.CORE: Nested structure, whose structure is given + by nested lists, tuples, and dicts. Note: numpy arrays and strings are + considered scalars. - For Modality.DATA: tuple or list constructed of + scalars and/or other tuples/lists, or a scalar. Note: numpy arrays are + considered scalars. + flat_sequence: flat sequence to pack. + expand_composites: Arg valid for Modality.CORE only. If true, then composite + tensors such as `tf.sparse.SparseTensor` and `tf.RaggedTensor` are + expanded into their component tensors. + sequence_fn: Arg valid for Modality.CORE only. + + Returns: + packed: `flat_sequence` converted to have the same recursive structure as + `structure`. + + Raises: + ValueError: If `flat_sequence` and `structure` have different + atom counts. + TypeError: For Modality.CORE only. `structure` is or contains a dict with + non-sortable keys. + """ + if modality == Modality.CORE: + return _tf_core_pack_sequence_as( + structure, flat_sequence, expand_composites, sequence_fn + ) + elif modality == Modality.DATA: + return _tf_data_pack_sequence_as(structure, flat_sequence) + else: + raise ValueError( + "Unknown modality used {} for nested structure".format(modality) + ) + + +def _tf_core_pack_sequence_as( + structure, flat_sequence, expand_composites, sequence_fn=None +): + """Implements sequence packing, with the option to alter the structure.""" + is_nested_fn = ( + _is_nested_or_composite if expand_composites else _tf_core_is_nested + ) + sequence_fn = sequence_fn or sequence_like + + def truncate(value, length): + value_str = str(value) + return value_str[:length] + (value_str[length:] and "...") + + if not is_nested_fn(flat_sequence): + raise TypeError( + "Attempted to pack value:\n {}\ninto a structure, but found " + "incompatible type `{}` instead.".format( + truncate(flat_sequence, 100), type(flat_sequence) + ) + ) + + if not is_nested_fn(structure): + if len(flat_sequence) != 1: + raise ValueError( + "The target structure is of type `{}`\n {}\nHowever the input " + "is a sequence ({}) of length {}.\n {}\nnest cannot " + "guarantee that it is safe to map one to the other.".format( + type(structure), + truncate(structure, 100), + type(flat_sequence), + len(flat_sequence), + truncate(flat_sequence, 100), + ) + ) + return flat_sequence[0] + + try: + final_index, packed = _tf_core_packed_nest_with_indices( + structure, flat_sequence, 0, is_nested_fn, sequence_fn + ) + if final_index < len(flat_sequence): + raise IndexError + except IndexError: + flat_structure = _tf_core_flatten( + structure, expand_composites=expand_composites + ) + if len(flat_structure) != len(flat_sequence): + # pylint: disable=raise-missing-from + raise ValueError( + "Could not pack sequence. Structure had %d atoms, but " + "flat_sequence had %d items. Structure: %s, flat_sequence: %s." + % (len(flat_structure), len(flat_sequence), structure, flat_sequence) + ) + return sequence_fn(structure, packed) + + +def _tf_data_pack_sequence_as(structure, flat_sequence): + """Returns a given flattened sequence packed into a nest. + + If `structure` is a scalar, `flat_sequence` must be a single-element list; + in this case the return value is `flat_sequence[0]`. + + Args: + structure: tuple or list constructed of scalars and/or other tuples/lists, + or a scalar. Note: numpy arrays are considered scalars. + flat_sequence: flat sequence to pack. + + Returns: + packed: `flat_sequence` converted to have the same recursive structure as + `structure`. + + Raises: + ValueError: If nest and structure have different element counts. + """ + if not (_tf_data_is_nested(flat_sequence) or isinstance(flat_sequence, list)): + raise TypeError( + "Argument `flat_sequence` must be a sequence. Got " + f"'{type(flat_sequence).__name__}'." + ) + + if not _tf_data_is_nested(structure): + if len(flat_sequence) != 1: + raise ValueError( + "Argument `structure` is a scalar but " + f"`len(flat_sequence)`={len(flat_sequence)} > 1" + ) + return flat_sequence[0] + + flat_structure = _tf_data_flatten(structure) + if len(flat_structure) != len(flat_sequence): + raise ValueError( + "Could not pack sequence. Argument `structure` had " + f"{len(flat_structure)} elements, but argument `flat_sequence` had " + f"{len(flat_sequence)} elements. Received structure: " + f"{structure}, flat_sequence: {flat_sequence}." + ) + + _, packed = _tf_data_packed_nest_with_indices(structure, flat_sequence, 0) + return sequence_like(structure, packed) # pylint: disable=protected-access + + +def map_structure(modality, func, *structure, **kwargs): + """Creates a new structure by applying `func` to each atom in `structure`. + + - For Modality.CORE: Refer to + [tf.nest](https://www.tensorflow.org/api_docs/python/tf/nest) + for the definition of a structure. + + Applies `func(x[0], x[1], ...)` where x[i] enumerates all atoms in + `structure[i]`. All items in `structure` must have the same arity, + and the return value will contain results with the same structure layout. + + Examples: + + * A single Python dict: + + >>> a = {"hello": 24, "world": 76} + >>> tf.nest.map_structure(lambda p: p * 2, a) + {'hello': 48, 'world': 152} + + * Multiple Python dictionaries: + + >>> d1 = {"hello": 24, "world": 76} + >>> d2 = {"hello": 36, "world": 14} + >>> tf.nest.map_structure(lambda p1, p2: p1 + p2, d1, d2) + {'hello': 60, 'world': 90} + + * A single Python list: + + >>> a = [24, 76, "ab"] + >>> tf.nest.map_structure(lambda p: p * 2, a) + [48, 152, 'abab'] + + * Scalars: + + >>> tf.nest.map_structure(lambda x, y: x + y, 3, 4) + 7 + + * Empty structures: + + >>> tf.nest.map_structure(lambda x: x + 1, ()) + () + + * Check the types of iterables: + + >>> s1 = (((1, 2), 3), 4, (5, 6)) + >>> s1_list = [[[1, 2], 3], 4, [5, 6]] + >>> tf.nest.map_structure(lambda x, y: None, s1, s1_list) + Traceback (most recent call last): + ... + TypeError: The two structures don't have the same nested structure + + * Type check is set to False: + + >>> s1 = (((1, 2), 3), 4, (5, 6)) + >>> s1_list = [[[1, 2], 3], 4, [5, 6]] + >>> tf.nest.map_structure(lambda x, y: None, s1, s1_list, check_types=False) + (((None, None), None), None, (None, None)) + + - For Modality.DATA: Applies `func(x[0], x[1], ...)` where x[i] is an entry in + `structure[i]`. All structures in `structure` must have the same arity, + and the return value will contain the results in the same structure. + + Args: + modality: enum value of supported modality [Modality.CORE or Modality.DATA] + func: A callable that accepts as many arguments as there are structures. + *structure: - For Modality.CORE: atom or nested structure. - For + Modality.DATA: scalar, or tuple or list of constructed scalars and/or + other tuples/lists, or scalars. Note: numpy arrays are considered + scalars. + **kwargs: Valid keyword args are: * `check_types`: - For Modality.CORE: If + set to `True` (default) the types of iterables within the structures have + to be same (e.g. `map_structure(func, [1], (1,))` raises a `TypeError` + exception). To allow this set this argument to `False`. Note that + namedtuples with identical name and fields are always considered to have + the same shallow structure. - For Modality.DATA: only valid keyword + argument is `check_types`. If set to `True` (default) the types of + iterables within the structures have to be same (e.g. `map_structure(func, + [1], (1,))` raises a `TypeError` exception). To allow this set this + argument to `False`. * `expand_composites`: Valid for Modality.CORE only. + If set to `True`, then composite tensors such as `tf.sparse.SparseTensor` + and `tf.RaggedTensor` are expanded into their component tensors. If + `False` (the default), then composite tensors are not expanded. + + Returns: + A new structure with the same arity as `structure[0]`, whose atoms + correspond to `func(x[0], x[1], ...)` where `x[i]` is the atom in the + corresponding location in `structure[i]`. If there are different structure + types and `check_types` is `False` the structure types of the first + structure will be used. + + Raises: + TypeError: If `func` is not callable or if the structures do not match + each other by depth tree. + ValueError: If no structure is provided or if the structures do not match + each other by type. + ValueError: If wrong keyword arguments are provided. + """ + if modality == Modality.CORE: + return _tf_core_map_structure(func, *structure, **kwargs) + elif modality == Modality.DATA: + return _tf_data_map_structure(func, *structure, **kwargs) + else: + raise ValueError( + "Unknown modality used {} for nested structure".format(modality) + ) + + +# pylint: disable=missing-function-docstring +def _tf_core_map_structure(func, *structure, **kwargs): + if not callable(func): + raise TypeError("func must be callable, got: %s" % func) + + if not structure: + raise ValueError("Must provide at least one structure") + + check_types = kwargs.pop("check_types", True) + expand_composites = kwargs.pop("expand_composites", False) + + if kwargs: + raise ValueError( + "Only valid keyword arguments are `check_types` and " + "`expand_composites`, not: `%s`" + % "`, `".join(kwargs.keys()) + ) + + for other in structure[1:]: + _tf_core_assert_same_structure( + structure[0], + other, + check_types=check_types, + expand_composites=expand_composites, + ) + + flat_structure = (_tf_core_flatten(s, expand_composites) for s in structure) + entries = zip(*flat_structure) + + return _tf_core_pack_sequence_as( + structure[0], + [func(*x) for x in entries], + expand_composites=expand_composites, + ) + + +# pylint: disable=missing-function-docstring +def _tf_data_map_structure(func, *structure, **check_types_dict): + if not callable(func): + raise TypeError(f"Argument `func` must be callable, got: {func}") + + if not structure: + raise ValueError("Must provide at least one structure") + + if check_types_dict: + if "check_types" not in check_types_dict or len(check_types_dict) > 1: + raise ValueError( + "Only valid keyword argument for `check_types_dict` is " + f"'check_types'. Got {check_types_dict}." + ) + check_types = check_types_dict["check_types"] + else: + check_types = True + + for other in structure[1:]: + _tf_data_assert_same_structure(structure[0], other, check_types=check_types) + + flat_structure = (_tf_data_flatten(s) for s in structure) + entries = zip(*flat_structure) + + return _tf_data_pack_sequence_as(structure[0], [func(*x) for x in entries]) + + +def yield_flat_up_to(modality, shallow_tree, input_tree, is_nested_fn, path=()): + """Yields (path, value) pairs of input_tree flattened up to shallow_tree. + + - For Modality.CORE: See comments for _tf_core_yield_flat_up_to() below + - For Modality.DATA: See comments for _tf_data_yield_flat_up_to() below + + Args: + modality: enum value of supported modality [Modality.CORE or Modality.DATA] + shallow_tree: Nested structure. Traverse no further than its leaf nodes. + input_tree: Nested structure. Return the paths and values from this tree. + Must have the same upper structure as shallow_tree. + is_nested_fn: Arg valid for Modality.CORE only. Function used to test if a + value should be treated as a nested structure. + path: Arg valid for Modality.CORE only. Tuple. Optional argument, only used + when recursing. The path from the root of the original shallow_tree, down + to the root of the shallow_tree arg of this recursive call. + + Yields: + Pairs of (path, value), where path the tuple path of a leaf node in + shallow_tree, and value is the value of the corresponding node in + input_tree. + """ + if modality == Modality.CORE: + yield from _tf_core_yield_flat_up_to( + shallow_tree, input_tree, is_nested_fn, path + ) + elif modality == Modality.DATA: + yield from _tf_data_yield_flat_up_to(shallow_tree, input_tree) + else: + raise ValueError( + "Unknown modality used {} for nested structure".format(modality) + ) + + +def _tf_core_yield_flat_up_to(shallow_tree, input_tree, is_nested_fn, path=()): + """Yields (path, value) pairs of input_tree flattened up to shallow_tree. + + Args: + shallow_tree: Nested structure. Traverse no further than its leaf nodes. + input_tree: Nested structure. Return the paths and values from this tree. + Must have the same upper structure as shallow_tree. + is_nested_fn: Function used to test if a value should be treated as a nested + structure. + path: Tuple. Optional argument, only used when recursing. The path from the + root of the original shallow_tree, down to the root of the shallow_tree + arg of this recursive call. + + Yields: + Pairs of (path, value), where path the tuple path of a leaf node in + shallow_tree, and value is the value of the corresponding node in + input_tree. + """ + if not is_nested_fn(shallow_tree): + yield (path, input_tree) + else: + input_tree = dict(_tf_core_yield_sorted_items(input_tree)) + for ( + shallow_key, + shallow_subtree, + ) in _tf_core_yield_sorted_items(shallow_tree): + subpath = path + (shallow_key,) + input_subtree = input_tree[shallow_key] + for leaf_path, leaf_value in _tf_core_yield_flat_up_to( + shallow_subtree, input_subtree, is_nested_fn, path=subpath + ): + yield (leaf_path, leaf_value) + + +def _tf_data_yield_flat_up_to(shallow_tree, input_tree): + """Yields elements `input_tree` partially flattened up to `shallow_tree`.""" + if _tf_data_is_nested(shallow_tree): + for shallow_branch, input_branch in zip( + _tf_data_yield_value(shallow_tree), _tf_data_yield_value(input_tree) + ): + for input_leaf in _tf_data_yield_flat_up_to(shallow_branch, input_branch): + yield input_leaf + else: + yield input_tree + + +def assert_shallow_structure( + modality, + shallow_tree, + input_tree, + check_types=True, + expand_composites=False, +): + """Asserts that `shallow_tree` is a shallow structure of `input_tree`. + + This function tests if the `input_tree` structure can be created from + the `shallow_tree` structure by replacing its leaf nodes with deeper + tree structures. + + Examples: + + The following code will raise an exception: + ```python + shallow_tree = {"a": "A", "b": "B"} + input_tree = {"a": 1, "c": 2} + assert_shallow_structure(shallow_tree, input_tree) + ``` + + The following code will raise an exception: + ```python + shallow_tree = ["a", "b"] + input_tree = ["c", ["d", "e"], "f"] + assert_shallow_structure(shallow_tree, input_tree) + ``` + + Args: + modality: enum value of supported modality [Modality.CORE or Modality.DATA] + shallow_tree: an arbitrarily nested structure. + input_tree: an arbitrarily nested structure. + check_types: if `True` (default) the sequence types of `shallow_tree` and + `input_tree` have to be the same. Note that even with check_types==True, + this function will consider two different namedtuple classes with the same + name and _fields attribute to be the same class. + expand_composites: Valid for Modality.CORE only. If true, then composite + tensors such as `tf.sparse.SparseTensor` and `tf.RaggedTensor` are + expanded into their component tensors. + + Raises: + TypeError: If `shallow_tree` is a sequence but `input_tree` is not. + TypeError: If the sequence types of `shallow_tree` are different from + `input_tree`. Only raised if `check_types` is `True`. + ValueError: If the sequence lengths of `shallow_tree` are different from + `input_tree`. + """ + if modality == Modality.CORE: + _tf_core_assert_shallow_structure( + shallow_tree, input_tree, check_types, expand_composites + ) + elif modality == Modality.DATA: + _tf_data_assert_shallow_structure(shallow_tree, input_tree, check_types) + else: + raise ValueError( + "Unknown modality used {} for nested structure".format(modality) + ) + + +# pylint: disable=missing-function-docstring +def _tf_core_assert_shallow_structure( + shallow_tree, input_tree, check_types=True, expand_composites=False +): + is_nested_fn = ( + _is_nested_or_composite if expand_composites else _tf_core_is_nested + ) + if is_nested_fn(shallow_tree): + if not is_nested_fn(input_tree): + raise TypeError( + "If shallow structure is a sequence, input must also be a sequence. " + "Input has type: %s." + % type(input_tree) + ) + + if isinstance(shallow_tree, _wrapt.ObjectProxy): + shallow_type = type(shallow_tree.__wrapped__) + else: + shallow_type = type(shallow_tree) + + if check_types and not isinstance(input_tree, shallow_type): + # Duck-typing means that nest should be fine with two different + # namedtuples with identical name and fields. + shallow_is_namedtuple = is_namedtuple(shallow_tree, False) + input_is_namedtuple = is_namedtuple(input_tree, False) + if shallow_is_namedtuple and input_is_namedtuple: + if not same_namedtuples(shallow_tree, input_tree): + raise TypeError( + STRUCTURES_HAVE_MISMATCHING_TYPES.format( + input_type=type(input_tree), shallow_type=type(shallow_tree) + ) + ) + + elif isinstance(shallow_tree, list) and isinstance(input_tree, list): + # List subclasses are considered the same, + # e.g. python list vs. _ListWrapper. + pass + + elif ( + _is_composite_tensor(shallow_tree) or _is_type_spec(shallow_tree) + ) and (_is_composite_tensor(input_tree) or _is_type_spec(input_tree)): + pass # Compatibility will be checked below. + + elif not ( + isinstance(shallow_tree, _collections_abc.Mapping) + and isinstance(input_tree, _collections_abc.Mapping) + ): + raise TypeError( + STRUCTURES_HAVE_MISMATCHING_TYPES.format( + input_type=type(input_tree), shallow_type=type(shallow_tree) + ) + ) + + if _is_composite_tensor(shallow_tree) or _is_composite_tensor(input_tree): + if not ( + (_is_composite_tensor(input_tree) or _is_type_spec(input_tree)) + and ( + _is_composite_tensor(shallow_tree) or _is_type_spec(shallow_tree) + ) + ): + raise TypeError( + STRUCTURES_HAVE_MISMATCHING_TYPES.format( + input_type=type(input_tree), shallow_type=type(shallow_tree) + ) + ) + # pylint: disable=protected-access + type_spec_1 = ( + shallow_tree + if _is_type_spec(shallow_tree) + else shallow_tree._type_spec + )._without_tensor_names() + type_spec_2 = ( + input_tree if _is_type_spec(input_tree) else input_tree._type_spec + )._without_tensor_names() + # TODO(b/246356867): Replace the most_specific_common_supertype below + # with get_structure. + if hasattr(type_spec_1, "_get_structure") and hasattr( + type_spec_2, "_get_structure" + ): + result = ( + type_spec_1._get_structure() == type_spec_2._get_structure() or None + ) + else: + result = type_spec_1.most_specific_common_supertype([type_spec_2]) + if result is None: + raise ValueError( + "Incompatible CompositeTensor TypeSpecs: %s vs. %s" + % (type_spec_1, type_spec_2) + ) + # pylint: enable=protected-access + + elif _is_type_spec(shallow_tree): + if not _is_type_spec(input_tree): + raise TypeError( + "If shallow structure is a TypeSpec, input must also " + "be a TypeSpec. Input has type: %s." + % type(input_tree) + ) + else: + if len(input_tree) != len(shallow_tree): + raise ValueError( + STRUCTURES_HAVE_MISMATCHING_LENGTHS.format( + input_length=len(input_tree), shallow_length=len(shallow_tree) + ) + ) + elif len(input_tree) < len(shallow_tree): + raise ValueError( + INPUT_TREE_SMALLER_THAN_SHALLOW_TREE.format( + input_size=len(input_tree), shallow_size=len(shallow_tree) + ) + ) + + if isinstance(shallow_tree, _collections_abc.Mapping): + absent_keys = set(shallow_tree) - set(input_tree) + if absent_keys: + raise ValueError( + SHALLOW_TREE_HAS_INVALID_KEYS.format(sorted(absent_keys)) + ) + + for shallow_branch, input_branch in zip( + _tf_core_yield_value(shallow_tree), + _tf_core_yield_value(input_tree), + ): + _tf_core_assert_shallow_structure( + shallow_branch, + input_branch, + check_types=check_types, + expand_composites=expand_composites, + ) + + +# pylint: disable=missing-function-docstring +def _tf_data_assert_shallow_structure( + shallow_tree, input_tree, check_types=True +): + if _tf_data_is_nested(shallow_tree): + if not _tf_data_is_nested(input_tree): + raise TypeError( + "If shallow structure is a sequence, input must also be a sequence. " + f"Input has type: '{type(input_tree).__name__}'." + ) + + if check_types and not isinstance(input_tree, type(shallow_tree)): + raise TypeError( + "The two structures don't have the same sequence type. Input " + f"structure has type '{type(input_tree).__name__}', while shallow " + f"structure has type '{type(shallow_tree).__name__}'." + ) + + if len(input_tree) != len(shallow_tree): + raise ValueError( + "The two structures don't have the same sequence length. Input " + f"structure has length {len(input_tree)}, while shallow structure " + f"has length {len(shallow_tree)}." + ) + + if check_types and isinstance(shallow_tree, _collections_abc.Mapping): + if set(input_tree) != set(shallow_tree): + raise ValueError( + "The two structures don't have the same keys. Input " + f"structure has keys {list(input_tree)}, while shallow structure " + f"has keys {list(shallow_tree)}." + ) + input_tree = sorted(input_tree.items()) + shallow_tree = sorted(shallow_tree.items()) + + for shallow_branch, input_branch in zip(shallow_tree, input_tree): + _tf_data_assert_shallow_structure( + shallow_branch, input_branch, check_types=check_types + ) + + +def flatten_up_to( + modality, + shallow_tree, + input_tree, + check_types=True, + expand_composites=False, +): + # pylint: disable=g-doc-return-or-yield,g-doc-args + """Flattens `input_tree` up to `shallow_tree`. + + - For Modality.CORE: refer to + [tf.nest](https://www.tensorflow.org/api_docs/python/tf/nest) + for the definition of a structure. + + Any further depth in structure in `input_tree` is retained as structures in + the partially flatten output. + + If `shallow_tree` and `input_tree` are atoms, this returns a + single-item list: `[input_tree]`. + + Use Case: + + Sometimes we may wish to partially flatten a structure, retaining some + of the nested structure. We achieve this by specifying a shallow structure, + `shallow_tree`, we wish to flatten up to. + + The input, `input_tree`, can be thought of as having the same structure layout + as `shallow_tree`, but with leaf nodes that are themselves tree structures. + + Examples: + + ```python + input_tree = [[[2, 2], [3, 3]], [[4, 9], [5, 5]]] + shallow_tree = [[True, True], [False, True]] + + flattened_input_tree = flatten_up_to(shallow_tree, input_tree) + flattened_shallow_tree = flatten_up_to(shallow_tree, shallow_tree) + + # Output is: + # [[2, 2], [3, 3], [4, 9], [5, 5]] + # [True, True, False, True] + ``` + + ```python + input_tree = [[('a', 1), [('b', 2), [('c', 3), [('d', 4)]]]]] + shallow_tree = [['level_1', ['level_2', ['level_3', ['level_4']]]]] + + input_tree_flattened_as_shallow_tree = flatten_up_to(shallow_tree, input_tree) + input_tree_flattened = flatten(input_tree) + + # Output is: + # [('a', 1), ('b', 2), ('c', 3), ('d', 4)] + # ['a', 1, 'b', 2, 'c', 3, 'd', 4] + ``` + + Edge Cases: + + ```python + flatten_up_to(0, 0) # Output: [0] + flatten_up_to(0, [0, 1, 2]) # Output: [[0, 1, 2]] + flatten_up_to([0, 1, 2], 0) # Output: TypeError + flatten_up_to([0, 1, 2], [0, 1, 2]) # Output: [0, 1, 2] + + ``` + + Args: + modality: enum value of supported modality [Modality.CORE or Modality.DATA] + shallow_tree: a possibly pruned structure of input_tree. + input_tree: an atom or a nested structure. Note, numpy arrays are considered + atoms. + check_types: bool. If True, check that each node in shallow_tree has the + same type as the corresponding node in input_tree. + expand_composites: Arg valid for Modality.CORE only. If true, then composite + tensors such as `tf.sparse.SparseTensor` and `tf.RaggedTensor` are + expanded into their component tensors. + + Returns: + A Python list, the partially flattened version of `input_tree` according to + the structure of `shallow_tree`. + + Raises: + TypeError: If `shallow_tree` is a nested structure but `input_tree` is not. + TypeError: If the structure types of `shallow_tree` are different from + `input_tree`. + ValueError: If the structure lengths of `shallow_tree` are different from + `input_tree`. + """ + if modality == Modality.CORE: + return _tf_core_flatten_up_to( + shallow_tree, input_tree, check_types, expand_composites + ) + elif modality == Modality.DATA: + return _tf_data_flatten_up_to(shallow_tree, input_tree) + else: + raise ValueError( + "Unknown modality used {} for nested structure".format(modality) + ) + + +def _tf_core_flatten_up_to( + shallow_tree, input_tree, check_types=True, expand_composites=False +): + is_nested_fn = ( + _is_nested_or_composite if expand_composites else _tf_core_is_nested + ) + _tf_core_assert_shallow_structure( + shallow_tree, + input_tree, + check_types=check_types, + expand_composites=expand_composites, + ) + # Discard paths returned by nest_util._tf_core_yield_flat_up_to. + return [ + v + for _, v in _tf_core_yield_flat_up_to( + shallow_tree, input_tree, is_nested_fn + ) + ] + + +def _tf_data_flatten_up_to(shallow_tree, input_tree): + _tf_data_assert_shallow_structure(shallow_tree, input_tree) + return list(_tf_data_yield_flat_up_to(shallow_tree, input_tree)) + + +def map_structure_up_to(modality, shallow_tree, func, *inputs, **kwargs): + """Applies a function or op to a number of partially flattened inputs. + + The `inputs` are flattened up to `shallow_tree` before being mapped. + + Use Case: + + Sometimes we wish to apply a function to a partially flattened + structure (for example when the function itself takes structure inputs). We + achieve this by specifying a shallow structure, `shallow_tree` we wish to + flatten up to. + + The `inputs`, can be thought of as having the same structure layout as + `shallow_tree`, but with leaf nodes that are themselves tree structures. + + This function therefore will return something with the same base structure as + `shallow_tree`. + + Examples: + + ```python + shallow_tree = [None, None] + inp_val = [1, 2, 3] + out = map_structure_up_to(shallow_tree, lambda x: 2 * x, inp_val) + + # Output is: [2, 4] + ``` + + ```python + ab_tuple = collections.namedtuple("ab_tuple", "a, b") + op_tuple = collections.namedtuple("op_tuple", "add, mul") + inp_val = ab_tuple(a=2, b=3) + inp_ops = ab_tuple(a=op_tuple(add=1, mul=2), b=op_tuple(add=2, mul=3)) + out = map_structure_up_to(inp_val, lambda val, ops: (val + ops.add) * ops.mul, + inp_val, inp_ops) + + # Output is: ab_tuple(a=6, b=15) + ``` + + ```python + data_list = [[2, 4, 6, 8], [[1, 3, 5, 7, 9], [3, 5, 7]]] + name_list = ['evens', ['odds', 'primes']] + out = map_structure_up_to( + name_list, + lambda name, sec: "first_{}_{}".format(len(sec), name), + name_list, data_list) + + # Output is: ['first_4_evens', ['first_5_odds', 'first_3_primes']] + ``` + + Args: + modality: enum value of supported modality [Modality.CORE or Modality.DATA] + shallow_tree: a shallow structure, common to all the inputs. + func: callable which will be applied to each input individually. + *inputs: structures that are compatible with shallow_tree. The function + `func` is applied to corresponding structures due to partial flattening of + each input, so the function must support arity of `len(inputs)`. + **kwargs: Arg valid for Modality.CORE only. kwargs to feed to func(). + Special kwarg `check_types` is not passed to func, but instead determines + whether the types of iterables within the structures have to be same (e.g. + `map_structure(func, [1], (1,))` raises a `TypeError` exception). To allow + this set this argument to `False`. + + Raises: + TypeError: If `shallow_tree` is a nested structure but `input_tree` is not. + TypeError: If the structure types of `shallow_tree` are different from + `input_tree`. + ValueError: If the structure lengths of `shallow_tree` are different from + `input_tree`. + + Returns: + result of repeatedly applying `func`, with the same structure layout as + `shallow_tree`. + """ + if modality == Modality.CORE: + return _tf_core_map_structure_with_tuple_paths_up_to( + shallow_tree, func, *inputs, **kwargs + ) + elif modality == Modality.DATA: + return _tf_data_map_structure_up_to(shallow_tree, func, *inputs) + else: + raise ValueError( + "Unknown modality used {} for nested structure".format(modality) + ) + + +def _tf_core_map_structure_with_tuple_paths_up_to( + shallow_tree, func, *inputs, **kwargs +): + """See comments for map_structure_with_tuple_paths_up_to() in tensorflow/python/util/nest.py.""" + if not inputs: + raise ValueError("Cannot map over no sequences") + + check_types = kwargs.pop("check_types", True) + expand_composites = kwargs.pop("expand_composites", False) + is_nested_fn = ( + _is_nested_or_composite if expand_composites else _tf_core_is_nested + ) + + for input_tree in inputs: + _tf_core_assert_shallow_structure( + shallow_tree, + input_tree, + check_types=check_types, + expand_composites=expand_composites, + ) + + # Flatten each input separately, apply the function to corresponding items, + # then repack based on the structure of the first input. + flat_value_gen = ( + _tf_core_flatten_up_to( # pylint: disable=g-complex-comprehension + shallow_tree, + input_tree, + check_types, + expand_composites=expand_composites, + ) + for input_tree in inputs + ) + flat_path_gen = ( + path + for path, _ in _tf_core_yield_flat_up_to( + shallow_tree, inputs[0], is_nested_fn + ) + ) + results = [ + func(*args, **kwargs) for args in zip(flat_path_gen, *flat_value_gen) + ] + return _tf_core_pack_sequence_as( + structure=shallow_tree, + flat_sequence=results, + expand_composites=expand_composites, + ) + + +# pylint: disable=missing-function-docstring +def _tf_data_map_structure_up_to(shallow_tree, func, *inputs): + if not inputs: + raise ValueError( + "Argument `inputs` is empty. Cannot map over no sequences." + ) + for input_tree in inputs: + _tf_data_assert_shallow_structure(shallow_tree, input_tree) + + # Flatten each input separately, apply the function to corresponding elements, + # then repack based on the structure of the first input. + all_flattened_up_to = ( + _tf_data_flatten_up_to(shallow_tree, input_tree) for input_tree in inputs + ) + + results = [func(*tensors) for tensors in zip(*all_flattened_up_to)] + return _tf_data_pack_sequence_as( + structure=shallow_tree, flat_sequence=results + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/object_identity.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/object_identity.py new file mode 100644 index 0000000000000000000000000000000000000000..0ffa5755604d380d91d5985b9d7e8106c8a5deab --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/object_identity.py @@ -0,0 +1,265 @@ +"""Utilities for collecting objects based on "is" comparison.""" +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +from typing import Any, Set +import weakref + +from tensorflow.python.util.compat import collections_abc + + +# LINT.IfChange +class _ObjectIdentityWrapper: + """Wraps an object, mapping __eq__ on wrapper to "is" on wrapped. + + Since __eq__ is based on object identity, it's safe to also define __hash__ + based on object ids. This lets us add unhashable types like trackable + _ListWrapper objects to object-identity collections. + """ + + __slots__ = ["_wrapped", "__weakref__"] + + def __init__(self, wrapped): + self._wrapped = wrapped + + @property + def unwrapped(self): + return self._wrapped + + def _assert_type(self, other): + if not isinstance(other, _ObjectIdentityWrapper): + raise TypeError("Cannot compare wrapped object with unwrapped object") + + def __lt__(self, other): + self._assert_type(other) + return id(self._wrapped) < id(other._wrapped) # pylint: disable=protected-access + + def __gt__(self, other): + self._assert_type(other) + return id(self._wrapped) > id(other._wrapped) # pylint: disable=protected-access + + def __eq__(self, other): + if other is None: + return False + self._assert_type(other) + return self._wrapped is other._wrapped # pylint: disable=protected-access + + def __ne__(self, other): + return not self.__eq__(other) + + def __hash__(self): + # Wrapper id() is also fine for weakrefs. In fact, we rely on + # id(weakref.ref(a)) == id(weakref.ref(a)) and weakref.ref(a) is + # weakref.ref(a) in _WeakObjectIdentityWrapper. + return id(self._wrapped) + + def __repr__(self): + return "<{} wrapping {!r}>".format(type(self).__name__, self._wrapped) + + +class _WeakObjectIdentityWrapper(_ObjectIdentityWrapper): + + __slots__ = () + + def __init__(self, wrapped): + super(_WeakObjectIdentityWrapper, self).__init__(weakref.ref(wrapped)) + + @property + def unwrapped(self): + return self._wrapped() + + +class Reference(_ObjectIdentityWrapper): + """Reference that refers an object. + + ```python + x = [1] + y = [1] + + x_ref1 = Reference(x) + x_ref2 = Reference(x) + y_ref2 = Reference(y) + + print(x_ref1 == x_ref2) + ==> True + + print(x_ref1 == y) + ==> False + ``` + """ + + __slots__ = () + + # Disabling super class' unwrapped field. + unwrapped = property() + + def deref(self): + """Returns the referenced object. + + ```python + x_ref = Reference(x) + print(x is x_ref.deref()) + ==> True + ``` + """ + return self._wrapped + + +class ObjectIdentityDictionary(collections_abc.MutableMapping): + """A mutable mapping data structure which compares using "is". + + This is necessary because we have trackable objects (_ListWrapper) which + have behavior identical to built-in Python lists (including being unhashable + and comparing based on the equality of their contents by default). + """ + + __slots__ = ["_storage"] + + def __init__(self): + self._storage = {} + + def _wrap_key(self, key): + return _ObjectIdentityWrapper(key) + + def __getitem__(self, key): + return self._storage[self._wrap_key(key)] + + def __setitem__(self, key, value): + self._storage[self._wrap_key(key)] = value + + def __delitem__(self, key): + del self._storage[self._wrap_key(key)] + + def __len__(self): + return len(self._storage) + + def __iter__(self): + for key in self._storage: + yield key.unwrapped + + def __repr__(self): + return "ObjectIdentityDictionary(%s)" % repr(self._storage) + + +class ObjectIdentityWeakKeyDictionary(ObjectIdentityDictionary): + """Like weakref.WeakKeyDictionary, but compares objects with "is".""" + + __slots__ = ["__weakref__"] + + def _wrap_key(self, key): + return _WeakObjectIdentityWrapper(key) + + def __len__(self): + # Iterate, discarding old weak refs + return len(list(self._storage)) + + def __iter__(self): + keys = self._storage.keys() + for key in keys: + unwrapped = key.unwrapped + if unwrapped is None: + del self[key] + else: + yield unwrapped + + +class ObjectIdentitySet(collections_abc.MutableSet): + """Like the built-in set, but compares objects with "is".""" + + __slots__ = ["_storage", "__weakref__"] + + def __init__(self, *args): + self._storage = set(self._wrap_key(obj) for obj in list(*args)) + + def __le__(self, other: Set[Any]) -> bool: + if not isinstance(other, Set): + return NotImplemented + if len(self) > len(other): + return False + for item in self._storage: + if item not in other: + return False + return True + + def __ge__(self, other: Set[Any]) -> bool: + if not isinstance(other, Set): + return NotImplemented + if len(self) < len(other): + return False + for item in other: + if item not in self: + return False + return True + + @staticmethod + def _from_storage(storage): + result = ObjectIdentitySet() + result._storage = storage # pylint: disable=protected-access + return result + + def _wrap_key(self, key): + return _ObjectIdentityWrapper(key) + + def __contains__(self, key): + return self._wrap_key(key) in self._storage + + def discard(self, key): + self._storage.discard(self._wrap_key(key)) + + def add(self, key): + self._storage.add(self._wrap_key(key)) + + def update(self, items): + self._storage.update([self._wrap_key(item) for item in items]) + + def clear(self): + self._storage.clear() + + def intersection(self, items): + return self._storage.intersection([self._wrap_key(item) for item in items]) + + def difference(self, items): + return ObjectIdentitySet._from_storage( + self._storage.difference([self._wrap_key(item) for item in items])) + + def __len__(self): + return len(self._storage) + + def __iter__(self): + keys = list(self._storage) + for key in keys: + yield key.unwrapped + + +class ObjectIdentityWeakSet(ObjectIdentitySet): + """Like weakref.WeakSet, but compares objects with "is".""" + + __slots__ = () + + def _wrap_key(self, key): + return _WeakObjectIdentityWrapper(key) + + def __len__(self): + # Iterate, discarding old weak refs + return len([_ for _ in self]) + + def __iter__(self): + keys = list(self._storage) + for key in keys: + unwrapped = key.unwrapped + if unwrapped is None: + self.discard(key) + else: + yield unwrapped +# LINT.ThenChange(//tensorflow/python/keras/utils/object_identity.py) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/protobuf/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/protobuf/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/protobuf/compare.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/protobuf/compare.py new file mode 100644 index 0000000000000000000000000000000000000000..44a9bfd15b3b75341015be527a8620f7e33d2c68 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/protobuf/compare.py @@ -0,0 +1,379 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""Utility functions for comparing proto2 messages in Python. + +ProtoEq() compares two proto2 messages for equality. + +ClearDefaultValuedFields() recursively clears the fields that are set to their +default values. This is useful for comparing protocol buffers where the +semantics of unset fields and default valued fields are the same. + +assertProtoEqual() is useful for unit tests. It produces much more helpful +output than assertEqual() for proto2 messages, e.g. this: + + outer { + inner { +- strings: "x" +? ^ ++ strings: "y" +? ^ + } + } + +...compared to the default output from assertEqual() that looks like this: + +AssertionError: != + +Call it inside your unit test's googletest.TestCase subclasses like this: + + from tensorflow.python.util.protobuf import compare + + class MyTest(googletest.TestCase): + ... + def testXXX(self): + ... + compare.assertProtoEqual(self, a, b) + +Alternatively: + + from tensorflow.python.util.protobuf import compare + + class MyTest(compare.ProtoAssertions, googletest.TestCase): + ... + def testXXX(self): + ... + self.assertProtoEqual(a, b) +""" + +import difflib +import math + +from ..compat import collections_abc +import six + +from google.protobuf import descriptor +from google.protobuf import descriptor_pool +from google.protobuf import message +from google.protobuf import text_format + + +# TODO(alankelly): Distinguish between signalling and quiet NaNs. +def isClose(x, y, relative_tolerance): # pylint: disable=invalid-name + """Returns True if x is close to y given the relative tolerance or if x and y are both inf, both -inf, or both NaNs. + + This function does not distinguish between signalling and non-signalling NaN. + + Args: + x: float value to be compared + y: float value to be compared + relative_tolerance: float. The allowable difference between the two values + being compared is determined by multiplying the relative tolerance by the + maximum of the two values. If this is not provided, then all floats are + compared using string comparison. + """ + # NaNs are considered equal. + if math.isnan(x) or math.isnan(y): + return math.isnan(x) == math.isnan(y) + + if math.isinf(x) or math.isinf(y): + return x == y + + return abs(x - y) <= relative_tolerance * max(abs(x), abs(y)) + + +def checkFloatEqAndReplace(self, expected, actual, relative_tolerance): # pylint: disable=invalid-name + """Recursively replaces the floats in actual with those in expected iff they are approximately equal. + + This is done because string equality will consider values such as 5.0999999999 + and 5.1 as not being equal, despite being extremely close. + + Args: + self: googletest.TestCase + expected: expected values + actual: actual values + relative_tolerance: float, relative tolerance. + """ + + for expected_fields, actual_fields in zip( + expected.ListFields(), actual.ListFields() + ): + is_repeated = True + expected_desc, expected_values = expected_fields + actual_values = actual_fields[1] + if expected_desc.label != descriptor.FieldDescriptor.LABEL_REPEATED: + is_repeated = False + expected_values = [expected_values] + actual_values = [actual_values] + + if ( + expected_desc.type == descriptor.FieldDescriptor.TYPE_FLOAT + or expected_desc.type == descriptor.FieldDescriptor.TYPE_DOUBLE + ): + for i, (x, y) in enumerate(zip(expected_values, actual_values)): + # Replace the actual value with the expected value if the test passes, + # otherwise leave it and let it fail in the next test so that the error + # message is nicely formatted + if isClose(x, y, relative_tolerance): + if is_repeated: + getattr(actual, actual_fields[0].name)[i] = x + else: + setattr(actual, actual_fields[0].name, x) + + if ( + expected_desc.type == descriptor.FieldDescriptor.TYPE_MESSAGE + or expected_desc.type == descriptor.FieldDescriptor.TYPE_GROUP + ): + if ( + expected_desc.type == descriptor.FieldDescriptor.TYPE_MESSAGE + and expected_desc.message_type.has_options + and expected_desc.message_type.GetOptions().map_entry + ): + # This is a map, only recurse if it has type message type. + if ( + expected_desc.message_type.fields_by_number[2].type + == descriptor.FieldDescriptor.TYPE_MESSAGE + ): + for e_v, a_v in zip( + six.itervalues(expected_values), six.itervalues(actual_values) + ): + checkFloatEqAndReplace( + self, + expected=e_v, + actual=a_v, + relative_tolerance=relative_tolerance, + ) + else: + for v, a in zip(expected_values, actual_values): + # recursive step + checkFloatEqAndReplace( + self, expected=v, actual=a, relative_tolerance=relative_tolerance + ) + + +def assertProtoEqual( + self, + a, + b, + check_initialized=True, + normalize_numbers=False, + msg=None, + relative_tolerance=None, +): # pylint: disable=invalid-name( + """Fails with a useful error if a and b aren't equal. + + Comparison of repeated fields matches the semantics of + unittest.TestCase.assertEqual(), ie order and extra duplicates fields matter. + + Args: + self: googletest.TestCase + a: proto2 PB instance, or text string representing one. + b: proto2 PB instance -- message.Message or subclass thereof. + check_initialized: boolean, whether to fail if either a or b isn't + initialized. + normalize_numbers: boolean, whether to normalize types and precision of + numbers before comparison. + msg: if specified, is used as the error message on failure. + relative_tolerance: float, relative tolerance. If this is not provided, then + all floats are compared using string comparison otherwise, floating point + comparisons are done using the relative tolerance provided. + """ + pool = descriptor_pool.Default() + if isinstance(a, six.string_types): + a = text_format.Parse(a, b.__class__(), descriptor_pool=pool) + + for pb in a, b: + if check_initialized: + errors = pb.FindInitializationErrors() + if errors: + self.fail('Initialization errors: %s\n%s' % (errors, pb)) + if normalize_numbers: + NormalizeNumberFields(pb) + + if relative_tolerance is not None: + checkFloatEqAndReplace( + self, expected=b, actual=a, relative_tolerance=relative_tolerance + ) + + a_str = text_format.MessageToString(a, descriptor_pool=pool) + b_str = text_format.MessageToString(b, descriptor_pool=pool) + + # Some Python versions would perform regular diff instead of multi-line + # diff if string is longer than 2**16. We substitute this behavior + # with a call to unified_diff instead to have easier-to-read diffs. + # For context, see: https://bugs.python.org/issue11763. + if len(a_str) < 2**16 and len(b_str) < 2**16: + self.assertMultiLineEqual(a_str, b_str, msg=msg) + else: + diff = ''.join( + difflib.unified_diff(a_str.splitlines(True), b_str.splitlines(True))) + if diff: + self.fail('%s :\n%s' % (msg, diff)) + + +def NormalizeNumberFields(pb): + """Normalizes types and precisions of number fields in a protocol buffer. + + Due to subtleties in the python protocol buffer implementation, it is possible + for values to have different types and precision depending on whether they + were set and retrieved directly or deserialized from a protobuf. This function + normalizes integer values to ints and longs based on width, 32-bit floats to + five digits of precision to account for python always storing them as 64-bit, + and ensures doubles are floating point for when they're set to integers. + + Modifies pb in place. Recurses into nested objects. + + Args: + pb: proto2 message. + + Returns: + the given pb, modified in place. + """ + for desc, values in pb.ListFields(): + is_repeated = True + if desc.label != descriptor.FieldDescriptor.LABEL_REPEATED: + is_repeated = False + values = [values] + + normalized_values = None + + # We force 32-bit values to int and 64-bit values to long to make + # alternate implementations where the distinction is more significant + # (e.g. the C++ implementation) simpler. + if desc.type in (descriptor.FieldDescriptor.TYPE_INT64, + descriptor.FieldDescriptor.TYPE_UINT64, + descriptor.FieldDescriptor.TYPE_SINT64): + normalized_values = [int(x) for x in values] + elif desc.type in (descriptor.FieldDescriptor.TYPE_INT32, + descriptor.FieldDescriptor.TYPE_UINT32, + descriptor.FieldDescriptor.TYPE_SINT32, + descriptor.FieldDescriptor.TYPE_ENUM): + normalized_values = [int(x) for x in values] + elif desc.type == descriptor.FieldDescriptor.TYPE_FLOAT: + normalized_values = [round(x, 6) for x in values] + elif desc.type == descriptor.FieldDescriptor.TYPE_DOUBLE: + normalized_values = [round(float(x), 7) for x in values] + + if normalized_values is not None: + if is_repeated: + pb.ClearField(desc.name) + getattr(pb, desc.name).extend(normalized_values) + else: + setattr(pb, desc.name, normalized_values[0]) + + if (desc.type == descriptor.FieldDescriptor.TYPE_MESSAGE or + desc.type == descriptor.FieldDescriptor.TYPE_GROUP): + if (desc.type == descriptor.FieldDescriptor.TYPE_MESSAGE and + desc.message_type.has_options and + desc.message_type.GetOptions().map_entry): + # This is a map, only recurse if the values have a message type. + if (desc.message_type.fields_by_number[2].type == + descriptor.FieldDescriptor.TYPE_MESSAGE): + for v in six.itervalues(values): + NormalizeNumberFields(v) + else: + for v in values: + # recursive step + NormalizeNumberFields(v) + + return pb + + +def _IsMap(value): + return isinstance(value, collections_abc.Mapping) + + +def _IsRepeatedContainer(value): + if isinstance(value, six.string_types): + return False + try: + iter(value) + return True + except TypeError: + return False + + +def ProtoEq(a, b): + """Compares two proto2 objects for equality. + + Recurses into nested messages. Uses list (not set) semantics for comparing + repeated fields, ie duplicates and order matter. + + Args: + a: A proto2 message or a primitive. + b: A proto2 message or a primitive. + + Returns: + `True` if the messages are equal. + """ + def Format(pb): + """Returns a dictionary or unchanged pb bases on its type. + + Specifically, this function returns a dictionary that maps tag + number (for messages) or element index (for repeated fields) to + value, or just pb unchanged if it's neither. + + Args: + pb: A proto2 message or a primitive. + Returns: + A dict or unchanged pb. + """ + if isinstance(pb, message.Message): + return dict((desc.number, value) for desc, value in pb.ListFields()) + elif _IsMap(pb): + return dict(pb.items()) + elif _IsRepeatedContainer(pb): + return dict(enumerate(list(pb))) + else: + return pb + + a, b = Format(a), Format(b) + + # Base case + if not isinstance(a, dict) or not isinstance(b, dict): + return a == b + + # This list performs double duty: it compares two messages by tag value *or* + # two repeated fields by element, in order. the magic is in the format() + # function, which converts them both to the same easily comparable format. + for tag in sorted(set(a.keys()) | set(b.keys())): + if tag not in a or tag not in b: + return False + else: + # Recursive step + if not ProtoEq(a[tag], b[tag]): + return False + + # Didn't find any values that differed, so they're equal! + return True + + +class ProtoAssertions(object): + """Mix this into a googletest.TestCase class to get proto2 assertions. + + Usage: + + class SomeTestCase(compare.ProtoAssertions, googletest.TestCase): + ... + def testSomething(self): + ... + self.assertProtoEqual(a, b) + + See module-level definitions for method documentation. + """ + + # pylint: disable=invalid-name + def assertProtoEqual(self, *args, **kwargs): + return assertProtoEqual(self, *args, **kwargs) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/pywrap_xla_ops.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/pywrap_xla_ops.pyi new file mode 100644 index 0000000000000000000000000000000000000000..28f484dc3b1285d76637a83dd33eae8d77417097 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/pywrap_xla_ops.pyi @@ -0,0 +1,17 @@ +# Copyright 2023 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +def get_cpu_kernel_names() -> list[str]: ... +def get_gpu_kernel_names() -> list[str]: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/serialization.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/serialization.py new file mode 100644 index 0000000000000000000000000000000000000000..5b7bf0dde7888d5d39262c1544b7c1760f839da8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/serialization.py @@ -0,0 +1,78 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Utilities for serializing Python objects.""" + +import numpy as np +import wrapt + +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import tensor_shape +from tensorflow.python.util.compat import collections_abc + + +def get_json_type(obj): + """Serializes any object to a JSON-serializable structure. + + Args: + obj: the object to serialize + + Returns: + JSON-serializable structure representing `obj`. + + Raises: + TypeError: if `obj` cannot be serialized. + """ + # if obj is a serializable Keras class instance + # e.g. optimizer, layer + if hasattr(obj, 'get_config'): + return {'class_name': obj.__class__.__name__, 'config': obj.get_config()} + + # if obj is any numpy type + if type(obj).__module__ == np.__name__: + if isinstance(obj, np.ndarray): + return obj.tolist() + else: + return obj.item() + + # misc functions (e.g. loss function) + if callable(obj): + return obj.__name__ + + # if obj is a python 'type' + if type(obj).__name__ == type.__name__: + return obj.__name__ + + if isinstance(obj, tensor_shape.Dimension): + return obj.value + + if isinstance(obj, tensor_shape.TensorShape): + return obj.as_list() + + if isinstance(obj, dtypes.DType): + return obj.name + + if isinstance(obj, collections_abc.Mapping): + return dict(obj) + + if obj is Ellipsis: + return {'class_name': '__ellipsis__'} + + if isinstance(obj, wrapt.ObjectProxy): + return obj.__wrapped__ + + raise TypeError(f'Object {obj} is not JSON-serializable. You may implement ' + 'a `get_config()` method on the class ' + '(returning a JSON-serializable dictionary) to make it ' + 'serializable.') diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/tf_contextlib.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/tf_contextlib.py new file mode 100644 index 0000000000000000000000000000000000000000..06a947e26249bb9724fe5c8ba6a2d5a8f37523e6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/tf_contextlib.py @@ -0,0 +1,32 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""TFDecorator-aware replacements for the contextlib module.""" +import contextlib as _contextlib + +from tensorflow.python.util import tf_decorator + + +def contextmanager(target): + """A tf_decorator-aware wrapper for `contextlib.contextmanager`. + + Usage is identical to `contextlib.contextmanager`. + + Args: + target: A callable to be wrapped in a contextmanager. + Returns: + A callable that can be used inside of a `with` statement. + """ + context_manager = _contextlib.contextmanager(target) + return tf_decorator.make_decorator(target, context_manager, 'contextmanager') diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/tf_decorator.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/tf_decorator.py new file mode 100644 index 0000000000000000000000000000000000000000..906bf87c61b210e7a997418efbd5045f3d14e27a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/tf_decorator.py @@ -0,0 +1,361 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Base TFDecorator class and utility functions for working with decorators. + +There are two ways to create decorators that TensorFlow can introspect into. +This is important for documentation generation purposes, so that function +signatures aren't obscured by the (*args, **kwds) signature that decorators +often provide. + +1. Call `tf_decorator.make_decorator` on your wrapper function. If your +decorator is stateless, or can capture all of the variables it needs to work +with through lexical closure, this is the simplest option. Create your wrapper +function as usual, but instead of returning it, return +`tf_decorator.make_decorator(target, your_wrapper)`. This will attach some +decorator introspection metadata onto your wrapper and return it. + +Example: + + def print_hello_before_calling(target): + def wrapper(*args, **kwargs): + print('hello') + return target(*args, **kwargs) + return tf_decorator.make_decorator(target, wrapper) + +2. Derive from TFDecorator. If your decorator needs to be stateful, you can +implement it in terms of a TFDecorator. Store whatever state you need in your +derived class, and implement the `__call__` method to do your work before +calling into your target. You can retrieve the target via +`super(MyDecoratorClass, self).decorated_target`, and call it with whatever +parameters it needs. + +Example: + + class CallCounter(tf_decorator.TFDecorator): + def __init__(self, target): + super(CallCounter, self).__init__('count_calls', target) + self.call_count = 0 + + def __call__(self, *args, **kwargs): + self.call_count += 1 + return super(CallCounter, self).decorated_target(*args, **kwargs) + + def count_calls(target): + return CallCounter(target) +""" +import inspect +from typing import Dict, Any + + +def _make_default_values(fullargspec: inspect.FullArgSpec) -> Dict[str, Any]: + """Returns default values from the function's fullargspec.""" + if fullargspec.defaults is not None: + defaults = { + name: value for name, value in zip( + fullargspec.args[-len(fullargspec.defaults):], fullargspec.defaults) + } + else: + defaults = {} + + if fullargspec.kwonlydefaults is not None: + defaults.update(fullargspec.kwonlydefaults) + + return defaults + + +def fullargspec_to_signature( + fullargspec: inspect.FullArgSpec) -> inspect.Signature: + """Repackages fullargspec information into an equivalent inspect.Signature.""" + defaults = _make_default_values(fullargspec) + parameters = [] + + for arg in fullargspec.args: + parameters.append( + inspect.Parameter( + arg, + inspect.Parameter.POSITIONAL_OR_KEYWORD, + default=defaults.get(arg, inspect.Parameter.empty), + ) + ) + + if fullargspec.varargs is not None: + parameters.append( + inspect.Parameter(fullargspec.varargs, inspect.Parameter.VAR_POSITIONAL) + ) + + for kwarg in fullargspec.kwonlyargs: + parameters.append( + inspect.Parameter( + kwarg, + inspect.Parameter.KEYWORD_ONLY, + default=defaults.get(kwarg, inspect.Parameter.empty), + ) + ) + + if fullargspec.varkw is not None: + parameters.append( + inspect.Parameter(fullargspec.varkw, inspect.Parameter.VAR_KEYWORD) + ) + + return inspect.Signature(parameters) + + +def make_decorator(target, + decorator_func, + decorator_name=None, + decorator_doc='', + decorator_argspec=None): + """Make a decorator from a wrapper and a target. + + Args: + target: The final callable to be wrapped. + decorator_func: The wrapper function. + decorator_name: The name of the decorator. If `None`, the name of the + function calling make_decorator. + decorator_doc: Documentation specific to this application of + `decorator_func` to `target`. + decorator_argspec: Override the signature using FullArgSpec. + + Returns: + The `decorator_func` argument with new metadata attached. + """ + if decorator_name is None: + decorator_name = inspect.currentframe().f_back.f_code.co_name + decorator = TFDecorator(decorator_name, target, decorator_doc, + decorator_argspec) + setattr(decorator_func, '_tf_decorator', decorator) + # Objects that are callables (e.g., a functools.partial object) may not have + # the following attributes. + if hasattr(target, '__name__'): + decorator_func.__name__ = target.__name__ + if hasattr(target, '__qualname__'): + decorator_func.__qualname__ = target.__qualname__ + if hasattr(target, '__module__'): + decorator_func.__module__ = target.__module__ + if hasattr(target, '__dict__'): + # Copy dict entries from target which are not overridden by decorator_func. + for name in target.__dict__: + if name not in decorator_func.__dict__: + decorator_func.__dict__[name] = target.__dict__[name] + if hasattr(target, '__doc__'): + decorator_func.__doc__ = decorator.__doc__ + decorator_func.__wrapped__ = target + # Keeping a second handle to `target` allows callers to detect whether the + # decorator was modified using `rewrap`. + decorator_func.__original_wrapped__ = target + if decorator_argspec: + decorator_func.__signature__ = fullargspec_to_signature( + decorator_argspec) + elif callable(target): + try: + signature = inspect.signature(target) + except (TypeError, ValueError): + # Certain callables such as builtins can not be inspected for signature. + pass + else: + bound_instance = _get_bound_instance(target) + # Present the decorated func as a method as well + if bound_instance and 'self' in signature.parameters: + signature = inspect.Signature(list(signature.parameters.values())[1:]) + decorator_func.__self__ = bound_instance + + decorator_func.__signature__ = signature + + return decorator_func + + +def _get_bound_instance(target): + """Returns the instance any of the targets is attached to.""" + decorators, target = unwrap(target) + for decorator in decorators: + if inspect.ismethod(decorator.decorated_target): + return decorator.decorated_target.__self__ + + +def _has_tf_decorator_attr(obj): + """Checks if object has _tf_decorator attribute. + + This check would work for mocked object as well since it would + check if returned attribute has the right type. + + Args: + obj: Python object. + """ + return (hasattr(obj, '_tf_decorator') and + isinstance(getattr(obj, '_tf_decorator'), TFDecorator)) + + +def rewrap(decorator_func, previous_target, new_target): + """Injects a new target into a function built by make_decorator. + + This function allows replacing a function wrapped by `decorator_func`, + assuming the decorator that wraps the function is written as described below. + + The decorator function must use `.__wrapped__` instead of the + wrapped function that is normally used: + + Example: + + # Instead of this: + def simple_parametrized_wrapper(*args, **kwds): + return wrapped_fn(*args, **kwds) + + tf_decorator.make_decorator(simple_parametrized_wrapper, wrapped_fn) + + # Write this: + def simple_parametrized_wrapper(*args, **kwds): + return simple_parametrized_wrapper.__wrapped__(*args, **kwds) + + tf_decorator.make_decorator(simple_parametrized_wrapper, wrapped_fn) + + Note that this process modifies decorator_func. + + Args: + decorator_func: Callable returned by `wrap`. + previous_target: Callable that needs to be replaced. + new_target: Callable to replace previous_target with. + + Returns: + The updated decorator. If decorator_func is not a tf_decorator, new_target + is returned. + """ + # Because the process mutates the decorator, we only need to alter the + # innermost function that wraps previous_target. + cur = decorator_func + innermost_decorator = None + target = None + while _has_tf_decorator_attr(cur): + innermost_decorator = cur + target = getattr(cur, '_tf_decorator') + if target.decorated_target is previous_target: + break + cur = target.decorated_target + assert cur is not None + + # If decorator_func is not a decorator, new_target replaces it directly. + if innermost_decorator is None: + # Consistency check. The caller should always pass the result of + # tf_decorator.unwrap as previous_target. If decorator_func is not a + # decorator, that will have returned decorator_func itself. + assert decorator_func is previous_target + return new_target + + target.decorated_target = new_target + + if inspect.ismethod(innermost_decorator): + # Bound methods can't be assigned attributes. Thankfully, they seem to + # be just proxies for their unbound counterpart, and we can modify that. + if hasattr(innermost_decorator, '__func__'): + innermost_decorator.__func__.__wrapped__ = new_target + elif hasattr(innermost_decorator, 'im_func'): + innermost_decorator.im_func.__wrapped__ = new_target + else: + innermost_decorator.__wrapped__ = new_target + else: + innermost_decorator.__wrapped__ = new_target + + return decorator_func + + +def unwrap(maybe_tf_decorator): + """Unwraps an object into a list of TFDecorators and a final target. + + Args: + maybe_tf_decorator: Any callable object. + + Returns: + A tuple whose first element is an list of TFDecorator-derived objects that + were applied to the final callable target, and whose second element is the + final undecorated callable target. If the `maybe_tf_decorator` parameter is + not decorated by any TFDecorators, the first tuple element will be an empty + list. The `TFDecorator` list is ordered from outermost to innermost + decorators. + """ + decorators = [] + cur = maybe_tf_decorator + while True: + if isinstance(cur, TFDecorator): + decorators.append(cur) + elif _has_tf_decorator_attr(cur): + decorators.append(getattr(cur, '_tf_decorator')) + else: + break + if not hasattr(decorators[-1], 'decorated_target'): + break + cur = decorators[-1].decorated_target + return decorators, cur + + +class TFDecorator(object): + """Base class for all TensorFlow decorators. + + TFDecorator captures and exposes the wrapped target, and provides details + about the current decorator. + """ + + def __init__(self, + decorator_name, + target, + decorator_doc='', + decorator_argspec=None): + self._decorated_target = target + self._decorator_name = decorator_name + self._decorator_doc = decorator_doc + self._decorator_argspec = decorator_argspec + if hasattr(target, '__name__'): + self.__name__ = target.__name__ + if hasattr(target, '__qualname__'): + self.__qualname__ = target.__qualname__ + if self._decorator_doc: + self.__doc__ = self._decorator_doc + elif hasattr(target, '__doc__') and target.__doc__: + self.__doc__ = target.__doc__ + else: + self.__doc__ = '' + + if decorator_argspec: + self.__signature__ = fullargspec_to_signature(decorator_argspec) + elif callable(target): + try: + self.__signature__ = inspect.signature(target) + except (TypeError, ValueError): + # Certain callables such as builtins can not be inspected for signature. + pass + + def __get__(self, instance, owner): + return self._decorated_target.__get__(instance, owner) + + def __call__(self, *args, **kwargs): + return self._decorated_target(*args, **kwargs) + + @property + def decorated_target(self): + return self._decorated_target + + @decorated_target.setter + def decorated_target(self, decorated_target): + self._decorated_target = decorated_target + + @property + def decorator_name(self): + return self._decorator_name + + @property + def decorator_doc(self): + return self._decorator_doc + + @property + def decorator_argspec(self): + return self._decorator_argspec diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/tf_decorator_export.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/tf_decorator_export.py new file mode 100644 index 0000000000000000000000000000000000000000..58115c7290abc9c5983594a160fab5bac1fc32c1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/tf_decorator_export.py @@ -0,0 +1,26 @@ +# Copyright 2023 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Exports functions from tf_decorator.py to avoid cycles.""" + +from tensorflow.python.util import tf_decorator +from tensorflow.python.util import tf_export + + +make_decorator = tf_export.tf_export( + '__internal__.decorator.make_decorator', v1=[] +)(tf_decorator.make_decorator) +unwrap = tf_export.tf_export('__internal__.decorator.unwrap', v1=[])( + tf_decorator.unwrap +) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/tf_export.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/tf_export.py new file mode 100644 index 0000000000000000000000000000000000000000..ade7504ca75fae9d760524fcb0adeff94f761b42 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/tf_export.py @@ -0,0 +1,424 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Utilities for exporting TensorFlow symbols to the API. + +Exporting a function or a class: + +To export a function or a class use tf_export decorator. For e.g.: +```python +@tf_export('foo', 'bar.foo') +def foo(...): + ... +``` + +If a function is assigned to a variable, you can export it by calling +tf_export explicitly. For e.g.: +```python +foo = get_foo(...) +tf_export('foo', 'bar.foo')(foo) +``` + + +Exporting a constant +```python +foo = 1 +tf_export('consts.foo').export_constant(__name__, 'foo') +``` +""" +from collections.abc import Sequence +import functools +import sys +from typing import Any, NamedTuple, Optional, Protocol, TypeVar + +from tensorflow.python.util import tf_decorator +from tensorflow.python.util import tf_inspect + +ESTIMATOR_API_NAME = 'estimator' +KERAS_API_NAME = 'keras' +TENSORFLOW_API_NAME = 'tensorflow' + +# List of subpackage names used by TensorFlow components. Have to check that +# TensorFlow core repo does not export any symbols under these names. +SUBPACKAGE_NAMESPACES = [ESTIMATOR_API_NAME] + + +class _Attributes(NamedTuple): + names: str + constants: str + + +# Attribute values must be unique to each API. +API_ATTRS = { + TENSORFLOW_API_NAME: _Attributes('_tf_api_names', '_tf_api_constants'), + ESTIMATOR_API_NAME: _Attributes( + '_estimator_api_names', '_estimator_api_constants' + ), + KERAS_API_NAME: _Attributes('_keras_api_names', '_keras_api_constants'), +} + +API_ATTRS_V1 = { + TENSORFLOW_API_NAME: _Attributes( + '_tf_api_names_v1', '_tf_api_constants_v1' + ), + ESTIMATOR_API_NAME: _Attributes( + '_estimator_api_names_v1', '_estimator_api_constants_v1' + ), + KERAS_API_NAME: _Attributes( + '_keras_api_names_v1', '_keras_api_constants_v1' + ), +} + + +class InvalidSymbolNameError(Exception): + """Raised when trying to export symbol as an invalid or unallowed name.""" + + +_NAME_TO_SYMBOL_MAPPING: dict[str, Any] = dict() + + +def get_symbol_from_name(name: str) -> Optional[Any]: + return _NAME_TO_SYMBOL_MAPPING.get(name) + + +def get_canonical_name_for_symbol( + symbol: Any, + api_name: str = TENSORFLOW_API_NAME, + add_prefix_to_v1_names: bool = False, +) -> Optional[str]: + """Get canonical name for the API symbol. + + Example: + ```python + from tensorflow.python.util import tf_export + cls = tf_export.get_symbol_from_name('keras.optimizers.Adam') + + # Gives `` + print(cls) + + # Gives `keras.optimizers.Adam` + print(tf_export.get_canonical_name_for_symbol(cls, api_name='keras')) + ``` + + Args: + symbol: API function or class. + api_name: API name (tensorflow or estimator). + add_prefix_to_v1_names: Specifies whether a name available only in V1 should + be prefixed with compat.v1. + + Returns: + Canonical name for the API symbol (for e.g. initializers.zeros) if + canonical name could be determined. Otherwise, returns None. + """ + if not hasattr(symbol, '__dict__'): + return None + api_names_attr = API_ATTRS[api_name].names + _, undecorated_symbol = tf_decorator.unwrap(symbol) + if api_names_attr not in undecorated_symbol.__dict__: + return None + api_names = getattr(undecorated_symbol, api_names_attr) + deprecated_api_names = undecorated_symbol.__dict__.get( + '_tf_deprecated_api_names', [] + ) + + canonical_name = get_canonical_name(api_names, deprecated_api_names) + if canonical_name: + return canonical_name + + # If there is no V2 canonical name, get V1 canonical name. + api_names_attr = API_ATTRS_V1[api_name].names + api_names = getattr(undecorated_symbol, api_names_attr) + v1_canonical_name = get_canonical_name(api_names, deprecated_api_names) + if add_prefix_to_v1_names: + return 'compat.v1.%s' % v1_canonical_name + return v1_canonical_name + + +def get_canonical_name( + api_names: Sequence[str], deprecated_api_names: Sequence[str] +) -> Optional[str]: + """Get preferred endpoint name. + + Args: + api_names: API names iterable. + deprecated_api_names: Deprecated API names iterable. + + Returns: + Returns one of the following in decreasing preference: + - first non-deprecated endpoint + - first endpoint + - None + """ + non_deprecated_name = next( + (name for name in api_names if name not in deprecated_api_names), None + ) + if non_deprecated_name: + return non_deprecated_name + if api_names: + return api_names[0] + return None + + +def get_v1_names(symbol: Any) -> Sequence[str]: + """Get a list of TF 1.* names for this symbol. + + Args: + symbol: symbol to get API names for. + + Returns: + List of all API names for this symbol including TensorFlow and + Estimator names. + """ + names_v1 = [] + tensorflow_api_attr_v1 = API_ATTRS_V1[TENSORFLOW_API_NAME].names + estimator_api_attr_v1 = API_ATTRS_V1[ESTIMATOR_API_NAME].names + keras_api_attr_v1 = API_ATTRS_V1[KERAS_API_NAME].names + + if not hasattr(symbol, '__dict__'): + return names_v1 + if tensorflow_api_attr_v1 in symbol.__dict__: + names_v1.extend(getattr(symbol, tensorflow_api_attr_v1)) + if estimator_api_attr_v1 in symbol.__dict__: + names_v1.extend(getattr(symbol, estimator_api_attr_v1)) + if keras_api_attr_v1 in symbol.__dict__: + names_v1.extend(getattr(symbol, keras_api_attr_v1)) + return names_v1 + + +def get_v2_names(symbol: Any) -> Sequence[str]: + """Get a list of TF 2.0 names for this symbol. + + Args: + symbol: symbol to get API names for. + + Returns: + List of all API names for this symbol including TensorFlow and + Estimator names. + """ + names_v2 = [] + tensorflow_api_attr = API_ATTRS[TENSORFLOW_API_NAME].names + estimator_api_attr = API_ATTRS[ESTIMATOR_API_NAME].names + keras_api_attr = API_ATTRS[KERAS_API_NAME].names + + if not hasattr(symbol, '__dict__'): + return names_v2 + if tensorflow_api_attr in symbol.__dict__: + names_v2.extend(getattr(symbol, tensorflow_api_attr)) + if estimator_api_attr in symbol.__dict__: + names_v2.extend(getattr(symbol, estimator_api_attr)) + if keras_api_attr in symbol.__dict__: + names_v2.extend(getattr(symbol, keras_api_attr)) + return names_v2 + + +def get_v1_constants(module: Any) -> Sequence[str]: + """Get a list of TF 1.* constants in this module. + + Args: + module: TensorFlow module. + + Returns: + List of all API constants under the given module including TensorFlow and + Estimator constants. + """ + constants_v1 = [] + tensorflow_constants_attr_v1 = API_ATTRS_V1[TENSORFLOW_API_NAME].constants + estimator_constants_attr_v1 = API_ATTRS_V1[ESTIMATOR_API_NAME].constants + + if hasattr(module, tensorflow_constants_attr_v1): + constants_v1.extend(getattr(module, tensorflow_constants_attr_v1)) + if hasattr(module, estimator_constants_attr_v1): + constants_v1.extend(getattr(module, estimator_constants_attr_v1)) + return constants_v1 + + +def get_v2_constants(module: Any) -> Sequence[str]: + """Get a list of TF 2.0 constants in this module. + + Args: + module: TensorFlow module. + + Returns: + List of all API constants under the given module including TensorFlow and + Estimator constants. + """ + constants_v2 = [] + tensorflow_constants_attr = API_ATTRS[TENSORFLOW_API_NAME].constants + estimator_constants_attr = API_ATTRS[ESTIMATOR_API_NAME].constants + + if hasattr(module, tensorflow_constants_attr): + constants_v2.extend(getattr(module, tensorflow_constants_attr)) + if hasattr(module, estimator_constants_attr): + constants_v2.extend(getattr(module, estimator_constants_attr)) + return constants_v2 + + +T = TypeVar('T') + + +class api_export(object): # pylint: disable=invalid-name + """Provides ways to export symbols to the TensorFlow API.""" + + _names: Sequence[str] + _names_v1: Sequence[str] + _api_name: str + + def __init__( + self, + *args: str, + api_name: str = TENSORFLOW_API_NAME, + v1: Optional[Sequence[str]] = None, + allow_multiple_exports: bool = True, # pylint: disable=unused-argument + ): + """Export under the names *args (first one is considered canonical). + + Args: + *args: API names in dot delimited format. + api_name: Name of the API you want to generate (e.g. `tensorflow` or + `estimator`). Default is `tensorflow`. + v1: Names for the TensorFlow V1 API. If not set, we will use V2 API names + both for TensorFlow V1 and V2 APIs. + allow_multiple_exports: Deprecated. + """ + self._names = args + self._names_v1 = v1 if v1 is not None else args + self._api_name = api_name + + self._validate_symbol_names() + + def _validate_symbol_names(self) -> None: + """Validate you are exporting symbols under an allowed package. + + We need to ensure things exported by tf_export, estimator_export, etc. + export symbols under disjoint top-level package names. + + For TensorFlow, we check that it does not export anything under subpackage + names used by components (estimator, keras, etc.). + + For each component, we check that it exports everything under its own + subpackage. + + Raises: + InvalidSymbolNameError: If you try to export symbol under disallowed name. + """ + all_symbol_names = set(self._names) | set(self._names_v1) + if self._api_name == TENSORFLOW_API_NAME: + for subpackage in SUBPACKAGE_NAMESPACES: + if any(n.startswith(subpackage) for n in all_symbol_names): + raise InvalidSymbolNameError( + '@tf_export is not allowed to export symbols under %s.*' + % (subpackage) + ) + else: + if not all(n.startswith(self._api_name) for n in all_symbol_names): + raise InvalidSymbolNameError( + 'Can only export symbols under package name of component. ' + 'e.g. tensorflow_estimator must export all symbols under ' + 'tf.estimator' + ) + + def __call__(self, func: T) -> T: + """Calls this decorator. + + Args: + func: decorated symbol (function or class). + + Returns: + The input function with _tf_api_names attribute set. + """ + api_names_attr = API_ATTRS[self._api_name].names + api_names_attr_v1 = API_ATTRS_V1[self._api_name].names + + _, undecorated_func = tf_decorator.unwrap(func) + self.set_attr(undecorated_func, api_names_attr, self._names) + self.set_attr(undecorated_func, api_names_attr_v1, self._names_v1) + + for name in self._names: + _NAME_TO_SYMBOL_MAPPING[name] = func + for name_v1 in self._names_v1: + _NAME_TO_SYMBOL_MAPPING['compat.v1.%s' % name_v1] = func + + return func + + def set_attr( + self, func: Any, api_names_attr: str, names: Sequence[str] + ) -> None: + setattr(func, api_names_attr, names) + + def export_constant(self, module_name: str, name: str) -> None: + """Store export information for constants/string literals. + + Export information is stored in the module where constants/string literals + are defined. + + e.g. + ```python + foo = 1 + bar = 2 + tf_export("consts.foo").export_constant(__name__, 'foo') + tf_export("consts.bar").export_constant(__name__, 'bar') + ``` + + Args: + module_name: (string) Name of the module to store constant at. + name: (string) Current constant name. + """ + module = sys.modules[module_name] + api_constants_attr = API_ATTRS[self._api_name].constants + api_constants_attr_v1 = API_ATTRS_V1[self._api_name].constants + + if not hasattr(module, api_constants_attr): + setattr(module, api_constants_attr, []) + # pylint: disable=protected-access + getattr(module, api_constants_attr).append((self._names, name)) + + if not hasattr(module, api_constants_attr_v1): + setattr(module, api_constants_attr_v1, []) + getattr(module, api_constants_attr_v1).append((self._names_v1, name)) + + +def kwarg_only(f: Any) -> Any: + """A wrapper that throws away all non-kwarg arguments.""" + f_argspec = tf_inspect.getfullargspec(f) + + def wrapper(*args, **kwargs): + if args: + raise TypeError( + '{f} only takes keyword args (possible keys: {kwargs}). ' + 'Please pass these args as kwargs instead.'.format( + f=f.__name__, kwargs=f_argspec.args + ) + ) + return f(**kwargs) + + return tf_decorator.make_decorator(f, wrapper, decorator_argspec=f_argspec) + + +class ExportType(Protocol): + + def __call__( + self, + *v2: str, + v1: Optional[Sequence[str]] = None, + allow_multiple_exports: bool = True, # Deprecated, no-op + ) -> api_export: + ... + + +tf_export: ExportType = functools.partial( + api_export, api_name=TENSORFLOW_API_NAME +) +keras_export: ExportType = functools.partial( + api_export, api_name=KERAS_API_NAME +) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/tf_inspect.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/tf_inspect.py new file mode 100644 index 0000000000000000000000000000000000000000..781dcb2ae89ee66aae5520f77b82935e63ffb8ca --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/tf_inspect.py @@ -0,0 +1,472 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""TFDecorator-aware replacements for the inspect module.""" +import collections +import functools +import inspect as _inspect + +import six + +from tensorflow.python.util import tf_decorator + + +# inspect.signature() is preferred over inspect.getfullargspec() in PY3. +# Note that while it can handle TFDecorators, it will ignore a TFDecorator's +# provided ArgSpec/FullArgSpec and instead return the signature of the +# inner-most function. +def signature(obj, *, follow_wrapped=True): + """TFDecorator-aware replacement for inspect.signature.""" + return _inspect.signature( + tf_decorator.unwrap(obj)[1], follow_wrapped=follow_wrapped) + + +Parameter = _inspect.Parameter +Signature = _inspect.Signature + +if hasattr(_inspect, 'ArgSpec'): + ArgSpec = _inspect.ArgSpec +else: + ArgSpec = collections.namedtuple( + 'ArgSpec', + [ + 'args', + 'varargs', + 'keywords', + 'defaults', + ], + ) + + +if hasattr(_inspect, 'FullArgSpec'): + FullArgSpec = _inspect.FullArgSpec # pylint: disable=invalid-name +else: + FullArgSpec = collections.namedtuple('FullArgSpec', [ + 'args', 'varargs', 'varkw', 'defaults', 'kwonlyargs', 'kwonlydefaults', + 'annotations' + ]) + + +def _convert_maybe_argspec_to_fullargspec(argspec): + if isinstance(argspec, FullArgSpec): + return argspec + return FullArgSpec( + args=argspec.args, + varargs=argspec.varargs, + varkw=argspec.keywords, + defaults=argspec.defaults, + kwonlyargs=[], + kwonlydefaults=None, + annotations={}) + +if hasattr(_inspect, 'getfullargspec'): + _getfullargspec = _inspect.getfullargspec # pylint: disable=invalid-name + + def _getargspec(target): + """A python3 version of getargspec. + + Calls `getfullargspec` and assigns args, varargs, + varkw, and defaults to a python 2/3 compatible `ArgSpec`. + + The parameter name 'varkw' is changed to 'keywords' to fit the + `ArgSpec` struct. + + Args: + target: the target object to inspect. + + Returns: + An ArgSpec with args, varargs, keywords, and defaults parameters + from FullArgSpec. + """ + fullargspecs = getfullargspec(target) + + defaults = fullargspecs.defaults or () + if fullargspecs.kwonlydefaults: + defaults += tuple(fullargspecs.kwonlydefaults.values()) + + if not defaults: + defaults = None + + argspecs = ArgSpec( + args=fullargspecs.args + fullargspecs.kwonlyargs, + varargs=fullargspecs.varargs, + keywords=fullargspecs.varkw, + defaults=defaults, + ) + return argspecs +else: + _getargspec = _inspect.getargspec + + def _getfullargspec(target): + """A python2 version of getfullargspec. + + Args: + target: the target object to inspect. + + Returns: + A FullArgSpec with empty kwonlyargs, kwonlydefaults and annotations. + """ + return _convert_maybe_argspec_to_fullargspec(getargspec(target)) + + +def currentframe(): + """TFDecorator-aware replacement for inspect.currentframe.""" + return _inspect.stack()[1][0] + + +def getargspec(obj): + """TFDecorator-aware replacement for `inspect.getargspec`. + + Note: `getfullargspec` is recommended as the python 2/3 compatible + replacement for this function. + + Args: + obj: A function, partial function, or callable object, possibly decorated. + + Returns: + The `ArgSpec` that describes the signature of the outermost decorator that + changes the callable's signature, or the `ArgSpec` that describes + the object if not decorated. + + Raises: + ValueError: When callable's signature can not be expressed with + ArgSpec. + TypeError: For objects of unsupported types. + """ + if isinstance(obj, functools.partial): + return _get_argspec_for_partial(obj) + + decorators, target = tf_decorator.unwrap(obj) + + spec = next((d.decorator_argspec + for d in decorators + if d.decorator_argspec is not None), None) + if spec: + return spec + + try: + # Python3 will handle most callables here (not partial). + return _getargspec(target) + except TypeError: + pass + + if isinstance(target, type): + try: + return _getargspec(target.__init__) + except TypeError: + pass + + try: + return _getargspec(target.__new__) + except TypeError: + pass + + # The `type(target)` ensures that if a class is received we don't return + # the signature of its __call__ method. + return _getargspec(type(target).__call__) + + +def _get_argspec_for_partial(obj): + """Implements `getargspec` for `functools.partial` objects. + + Args: + obj: The `functools.partial` object + Returns: + An `inspect.ArgSpec` + Raises: + ValueError: When callable's signature can not be expressed with + ArgSpec. + """ + # When callable is a functools.partial object, we construct its ArgSpec with + # following strategy: + # - If callable partial contains default value for positional arguments (ie. + # object.args), then final ArgSpec doesn't contain those positional arguments. + # - If callable partial contains default value for keyword arguments (ie. + # object.keywords), then we merge them with wrapped target. Default values + # from callable partial takes precedence over those from wrapped target. + # + # However, there is a case where it is impossible to construct a valid + # ArgSpec. Python requires arguments that have no default values must be + # defined before those with default values. ArgSpec structure is only valid + # when this presumption holds true because default values are expressed as a + # tuple of values without keywords and they are always assumed to belong to + # last K arguments where K is number of default values present. + # + # Since functools.partial can give default value to any argument, this + # presumption may no longer hold in some cases. For example: + # + # def func(m, n): + # return 2 * m + n + # partialed = functools.partial(func, m=1) + # + # This example will result in m having a default value but n doesn't. This is + # usually not allowed in Python and can not be expressed in ArgSpec correctly. + # + # Thus, we must detect cases like this by finding first argument with default + # value and ensures all following arguments also have default values. When + # this is not true, a ValueError is raised. + + n_prune_args = len(obj.args) + partial_keywords = obj.keywords or {} + + args, varargs, keywords, defaults = getargspec(obj.func) + + # Pruning first n_prune_args arguments. + args = args[n_prune_args:] + + # Partial function may give default value to any argument, therefore length + # of default value list must be len(args) to allow each argument to + # potentially be given a default value. + no_default = object() + all_defaults = [no_default] * len(args) + + if defaults: + all_defaults[-len(defaults):] = defaults + + # Fill in default values provided by partial function in all_defaults. + for kw, default in six.iteritems(partial_keywords): + if kw in args: + idx = args.index(kw) + all_defaults[idx] = default + elif not keywords: + raise ValueError(f'{obj} does not have a **kwargs parameter, but ' + f'contains an unknown partial keyword {kw}.') + + # Find first argument with default value set. + first_default = next( + (idx for idx, x in enumerate(all_defaults) if x is not no_default), None) + + # If no default values are found, return ArgSpec with defaults=None. + if first_default is None: + return ArgSpec(args, varargs, keywords, None) + + # Checks if all arguments have default value set after first one. + invalid_default_values = [ + args[i] for i, j in enumerate(all_defaults) + if j is no_default and i > first_default + ] + + if invalid_default_values: + raise ValueError(f'{obj} has some keyword-only arguments, which are not' + f' supported: {invalid_default_values}.') + + return ArgSpec(args, varargs, keywords, tuple(all_defaults[first_default:])) + + +def getfullargspec(obj): + """TFDecorator-aware replacement for `inspect.getfullargspec`. + + This wrapper emulates `inspect.getfullargspec` in[^)]* Python2. + + Args: + obj: A callable, possibly decorated. + + Returns: + The `FullArgSpec` that describes the signature of + the outermost decorator that changes the callable's signature. If the + callable is not decorated, `inspect.getfullargspec()` will be called + directly on the callable. + """ + decorators, target = tf_decorator.unwrap(obj) + + for d in decorators: + if d.decorator_argspec is not None: + return _convert_maybe_argspec_to_fullargspec(d.decorator_argspec) + return _getfullargspec(target) + + +def getcallargs(*func_and_positional, **named): + """TFDecorator-aware replacement for inspect.getcallargs. + + Args: + *func_and_positional: A callable, possibly decorated, followed by any + positional arguments that would be passed to `func`. + **named: The named argument dictionary that would be passed to `func`. + + Returns: + A dictionary mapping `func`'s named arguments to the values they would + receive if `func(*positional, **named)` were called. + + `getcallargs` will use the argspec from the outermost decorator that provides + it. If no attached decorators modify argspec, the final unwrapped target's + argspec will be used. + """ + func = func_and_positional[0] + positional = func_and_positional[1:] + argspec = getfullargspec(func) + call_args = named.copy() + this = getattr(func, 'im_self', None) or getattr(func, '__self__', None) + if ismethod(func) and this: + positional = (this,) + positional + remaining_positionals = [arg for arg in argspec.args if arg not in call_args] + call_args.update(dict(zip(remaining_positionals, positional))) + default_count = 0 if not argspec.defaults else len(argspec.defaults) + if default_count: + for arg, value in zip(argspec.args[-default_count:], argspec.defaults): + if arg not in call_args: + call_args[arg] = value + if argspec.kwonlydefaults is not None: + for k, v in argspec.kwonlydefaults.items(): + if k not in call_args: + call_args[k] = v + return call_args + + +def getframeinfo(*args, **kwargs): + return _inspect.getframeinfo(*args, **kwargs) + + +def getdoc(object): # pylint: disable=redefined-builtin + """TFDecorator-aware replacement for inspect.getdoc. + + Args: + object: An object, possibly decorated. + + Returns: + The docstring associated with the object. + + The outermost-decorated object is intended to have the most complete + documentation, so the decorated parameter is not unwrapped. + """ + return _inspect.getdoc(object) + + +def getfile(object): # pylint: disable=redefined-builtin + """TFDecorator-aware replacement for inspect.getfile.""" + unwrapped_object = tf_decorator.unwrap(object)[1] + + # Work around for the case when object is a stack frame + # and only .pyc files are used. In this case, getfile + # might return incorrect path. So, we get the path from f_globals + # instead. + if (hasattr(unwrapped_object, 'f_globals') and + '__file__' in unwrapped_object.f_globals): + return unwrapped_object.f_globals['__file__'] + return _inspect.getfile(unwrapped_object) + + +def getmembers(object, predicate=None): # pylint: disable=redefined-builtin + """TFDecorator-aware replacement for inspect.getmembers.""" + return _inspect.getmembers(object, predicate) + + +def getmodule(object): # pylint: disable=redefined-builtin + """TFDecorator-aware replacement for inspect.getmodule.""" + return _inspect.getmodule(object) + + +def getmro(cls): + """TFDecorator-aware replacement for inspect.getmro.""" + return _inspect.getmro(cls) + + +def getsource(object): # pylint: disable=redefined-builtin + """TFDecorator-aware replacement for inspect.getsource.""" + return _inspect.getsource(tf_decorator.unwrap(object)[1]) + + +def getsourcefile(object): # pylint: disable=redefined-builtin + """TFDecorator-aware replacement for inspect.getsourcefile.""" + return _inspect.getsourcefile(tf_decorator.unwrap(object)[1]) + + +def getsourcelines(object): # pylint: disable=redefined-builtin + """TFDecorator-aware replacement for inspect.getsourcelines.""" + return _inspect.getsourcelines(tf_decorator.unwrap(object)[1]) + + +def isbuiltin(object): # pylint: disable=redefined-builtin + """TFDecorator-aware replacement for inspect.isbuiltin.""" + return _inspect.isbuiltin(tf_decorator.unwrap(object)[1]) + + +def isclass(object): # pylint: disable=redefined-builtin + """TFDecorator-aware replacement for inspect.isclass.""" + return _inspect.isclass(tf_decorator.unwrap(object)[1]) + + +def isfunction(object): # pylint: disable=redefined-builtin + """TFDecorator-aware replacement for inspect.isfunction.""" + return _inspect.isfunction(tf_decorator.unwrap(object)[1]) + + +def isframe(object): # pylint: disable=redefined-builtin + """TFDecorator-aware replacement for inspect.ismodule.""" + return _inspect.isframe(tf_decorator.unwrap(object)[1]) + + +def isgenerator(object): # pylint: disable=redefined-builtin + """TFDecorator-aware replacement for inspect.isgenerator.""" + return _inspect.isgenerator(tf_decorator.unwrap(object)[1]) + + +def isgeneratorfunction(object): # pylint: disable=redefined-builtin + """TFDecorator-aware replacement for inspect.isgeneratorfunction.""" + return _inspect.isgeneratorfunction(tf_decorator.unwrap(object)[1]) + + +def ismethod(object): # pylint: disable=redefined-builtin + """TFDecorator-aware replacement for inspect.ismethod.""" + return _inspect.ismethod(tf_decorator.unwrap(object)[1]) + + +def isanytargetmethod(object): # pylint: disable=redefined-builtin + # pylint: disable=g-doc-args,g-doc-return-or-yield + """Checks if `object` or a TF Decorator wrapped target contains self or cls. + + This function could be used along with `tf_inspect.getfullargspec` to + determine if the first argument of `object` argspec is self or cls. If the + first argument is self or cls, it needs to be excluded from argspec when we + compare the argspec to the input arguments and, if provided, the tf.function + input_signature. + + Like `tf_inspect.getfullargspec` and python `inspect.getfullargspec`, it + does not unwrap python decorators. + + Args: + obj: An method, function, or functool.partial, possibly decorated by + TFDecorator. + + Returns: + A bool indicates if `object` or any target along the chain of TF decorators + is a method. + """ + decorators, target = tf_decorator.unwrap(object) + for decorator in decorators: + if _inspect.ismethod(decorator.decorated_target): + return True + + # TODO(b/194845243): Implement the long term solution with inspect.signature. + # A functools.partial object is not a function or method. But if the wrapped + # func is a method, the argspec will contain self/cls. + while isinstance(target, functools.partial): + target = target.func + + # `target` is a method or an instance with __call__ + return callable(target) and not _inspect.isfunction(target) + + +def ismodule(object): # pylint: disable=redefined-builtin + """TFDecorator-aware replacement for inspect.ismodule.""" + return _inspect.ismodule(tf_decorator.unwrap(object)[1]) + + +def isroutine(object): # pylint: disable=redefined-builtin + """TFDecorator-aware replacement for inspect.isroutine.""" + return _inspect.isroutine(tf_decorator.unwrap(object)[1]) + + +def stack(context=1): + """TFDecorator-aware replacement for inspect.stack.""" + return _inspect.stack(context)[1:] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/tf_should_use.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/tf_should_use.py new file mode 100644 index 0000000000000000000000000000000000000000..8f45edd6874ab092799bb10bd1d683d2497ba316 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/tf_should_use.py @@ -0,0 +1,311 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Decorator that provides a warning if the wrapped object is never used.""" +import copy +import sys +import textwrap +import traceback +import types + +from tensorflow.python.eager import context +from tensorflow.python.framework import ops +from tensorflow.python.platform import tf_logging +from tensorflow.python.util import tf_decorator + + +class _TFShouldUseHelper(object): + """Object stored in TFShouldUse-wrapped objects. + + When it is deleted it will emit a warning or error if its `sate` method + has not been called by time of deletion, and Tensorflow is not executing + eagerly or inside a tf.function (which use autodeps and resolve the + main issues this wrapper warns about). + """ + + def __init__(self, type_, repr_, stack_frame, error_in_function, + warn_in_eager): + self._type = type_ + self._repr = repr_ + self._stack_frame = stack_frame + self._error_in_function = error_in_function + if context.executing_eagerly(): + # If warn_in_eager, sated == False. Otherwise true. + self._sated = not warn_in_eager + elif ops.inside_function(): + if error_in_function: + self._sated = False + ops.add_exit_callback_to_default_func_graph( + lambda: self._check_sated(raise_error=True)) + else: + self._sated = True + else: + # TF1 graph building mode + self._sated = False + + def sate(self): + self._sated = True + self._type = None + self._repr = None + self._stack_frame = None + self._logging_module = None + + def _check_sated(self, raise_error): + """Check if the object has been sated.""" + if self._sated: + return + creation_stack = ''.join( + [line.rstrip() + for line in traceback.format_stack(self._stack_frame, limit=5)]) + if raise_error: + try: + raise RuntimeError( + 'Object was never used (type {}): {}. If you want to mark it as ' + 'used call its "mark_used()" method. It was originally created ' + 'here:\n{}'.format(self._type, self._repr, creation_stack)) + finally: + self.sate() + else: + tf_logging.error( + '==================================\n' + 'Object was never used (type {}):\n{}\nIf you want to mark it as ' + 'used call its "mark_used()" method.\nIt was originally created ' + 'here:\n{}\n' + '==================================' + .format(self._type, self._repr, creation_stack)) + + def __del__(self): + self._check_sated(raise_error=False) + + +def _new__init__(self, wrapped_value, tf_should_use_helper): + # pylint: disable=protected-access + self._tf_should_use_helper = tf_should_use_helper + self._tf_should_use_wrapped_value = wrapped_value + + +def _new__setattr__(self, key, value): + if key in ('_tf_should_use_helper', '_tf_should_use_wrapped_value'): + return object.__setattr__(self, key, value) + return setattr( + object.__getattribute__(self, '_tf_should_use_wrapped_value'), + key, value) + + +def _new__getattribute__(self, key): + if key not in ('_tf_should_use_helper', '_tf_should_use_wrapped_value'): + object.__getattribute__(self, '_tf_should_use_helper').sate() + if key in ( + '_tf_should_use_wrapped_value', + '_tf_should_use_helper', + 'mark_used', + '__setattr__', + ): + return object.__getattribute__(self, key) + return getattr( + object.__getattribute__(self, '_tf_should_use_wrapped_value'), key) + + +def _new_mark_used(self, *args, **kwargs): + object.__getattribute__(self, '_tf_should_use_helper').sate() + try: + mu = object.__getattribute__( + object.__getattribute__(self, '_tf_should_use_wrapped_value'), + 'mark_used') + return mu(*args, **kwargs) + except AttributeError: + pass + +OVERLOADABLE_OPERATORS = { + '__add__', + '__radd__', + '__sub__', + '__rsub__', + '__mul__', + '__rmul__', + '__div__', + '__rdiv__', + '__truediv__', + '__rtruediv__', + '__floordiv__', + '__rfloordiv__', + '__mod__', + '__rmod__', + '__lt__', + '__le__', + '__gt__', + '__ge__', + '__ne__', + '__eq__', + '__and__', + '__rand__', + '__or__', + '__ror__', + '__xor__', + '__rxor__', + '__getitem__', + '__pow__', + '__rpow__', + '__invert__', + '__neg__', + '__abs__', + '__matmul__', + '__rmatmul__', +} + + +_WRAPPERS = {} + + +class ShouldUseWrapper(object): + pass + + +def _get_wrapper(x, tf_should_use_helper): + """Create a wrapper for object x, whose class subclasses type(x). + + The wrapper will emit a warning if it is deleted without any of its + properties being accessed or methods being called. + + Args: + x: The instance to wrap. + tf_should_use_helper: The object that tracks usage. + + Returns: + An object wrapping `x`, of type `type(x)`. + """ + type_x = type(x) + memoized = _WRAPPERS.get(type_x, None) + if memoized: + return memoized(x, tf_should_use_helper) + + # Make a copy of `object` + tx = copy.deepcopy(ShouldUseWrapper) + # Prefer using __orig_bases__, which preserve generic type arguments. + bases = getattr(tx, '__orig_bases__', tx.__bases__) + + def set_body(ns): + ns.update(tx.__dict__) + return ns + + copy_tx = types.new_class(tx.__name__, bases, exec_body=set_body) + copy_tx.__init__ = _new__init__ + copy_tx.__getattribute__ = _new__getattribute__ + for op in OVERLOADABLE_OPERATORS: + if hasattr(type_x, op): + setattr(copy_tx, op, getattr(type_x, op)) + + copy_tx.mark_used = _new_mark_used + copy_tx.__setattr__ = _new__setattr__ + _WRAPPERS[type_x] = copy_tx + + return copy_tx(x, tf_should_use_helper) + + +def _add_should_use_warning(x, error_in_function=False, warn_in_eager=False): + """Wraps object x so that if it is never used, a warning is logged. + + Args: + x: Python object. + error_in_function: Python bool. If `True`, a `RuntimeError` is raised + if the returned value is never used when created during `tf.function` + tracing. + warn_in_eager: Python bool. If `True` raise warning if in Eager mode as well + as graph mode. + + Returns: + An instance of `TFShouldUseWarningWrapper` which subclasses `type(x)` + and is a very shallow wrapper for `x` which logs access into `x`. + """ + if x is None or (isinstance(x, list) and not x): + return x + + if context.executing_eagerly() and not warn_in_eager: + return x + + if ops.inside_function() and not error_in_function: + # We don't currently log warnings in tf.function calls, so just skip it. + return x + + # Extract the current frame for later use by traceback printing. + try: + raise ValueError() + except ValueError: + stack_frame = sys.exc_info()[2].tb_frame.f_back + + tf_should_use_helper = _TFShouldUseHelper( + type_=type(x), + repr_=repr(x), + stack_frame=stack_frame, + error_in_function=error_in_function, + warn_in_eager=warn_in_eager) + + return _get_wrapper(x, tf_should_use_helper) + + +def should_use_result(fn=None, warn_in_eager=False, error_in_function=False): + """Function wrapper that ensures the function's output is used. + + If the output is not used, a `logging.error` is logged. If + `error_in_function` is set, then a `RuntimeError` will be raised at the + end of function tracing if the output is not used by that point. + + An output is marked as used if any of its attributes are read, modified, or + updated. Examples when the output is a `Tensor` include: + + - Using it in any capacity (e.g. `y = t + 0`, `sess.run(t)`) + - Accessing a property (e.g. getting `t.name` or `t.op`). + - Calling `t.mark_used()`. + + Note, certain behaviors cannot be tracked - for these the object may not + be marked as used. Examples include: + + - `t != 0`. In this case, comparison is done on types / ids. + - `isinstance(t, tf.Tensor)`. Similar to above. + + Args: + fn: The function to wrap. + warn_in_eager: Whether to create warnings in Eager as well. + error_in_function: Whether to raise an error when creating a tf.function. + + Returns: + The wrapped function. + """ + def decorated(fn): + """Decorates the input function.""" + def wrapped(*args, **kwargs): + return _add_should_use_warning(fn(*args, **kwargs), + warn_in_eager=warn_in_eager, + error_in_function=error_in_function) + fn_doc = fn.__doc__ or '' + split_doc = fn_doc.split('\n', 1) + if len(split_doc) == 1: + updated_doc = fn_doc + else: + brief, rest = split_doc + updated_doc = '\n'.join([brief, textwrap.dedent(rest)]) + + note = ('\n\nNote: The output of this function should be used. If it is ' + 'not, a warning will be logged or an error may be raised. ' + 'To mark the output as used, call its .mark_used() method.') + return tf_decorator.make_decorator( + target=fn, + decorator_func=wrapped, + decorator_name='should_use_result', + decorator_doc=updated_doc + note) + + if fn is not None: + return decorated(fn) + else: + return decorated diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/tf_stack.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/tf_stack.py new file mode 100644 index 0000000000000000000000000000000000000000..ae68e39e265ebf086c4b036c11e9c78d59a72e5c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/tf_stack.py @@ -0,0 +1,187 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Functions used to extract and analyze stacks. Faster than Python libs.""" +# pylint: disable=g-bad-name +import collections +import inspect +import threading + +from tensorflow.core.framework import graph_debug_info_pb2 +from tensorflow.python.util import _tf_stack + +# Generally such lookups should be done using `threading.local()`. See +# https://blogs.gnome.org/jamesh/2008/06/11/tls-python/ for a detailed +# explanation of why. However the transform stacks are expected to be empty +# when a thread is joined, so reusing the key does not introduce a correctness +# issue. Moreover, get_ident is faster than storing and retrieving a unique +# key in a thread local store. +_get_thread_key = threading.get_ident + + +# TODO(mdan): Move these to C++ as well. +# Moving to C++ can further avoid extra copies made by get_effective_map. +_source_mapper_stacks = collections.defaultdict(lambda: [SentinelMapper()]) +_source_filter_stacks = collections.defaultdict(lambda: [SentinelFilter()]) + + +class StackTraceTransform(object): + """Base class for stack trace transformation functions.""" + + _stack_dict = None # Subclasses should override + _thread_key = None + + def __enter__(self): + # Any given instance is assumed to be used by a single thread, which reduces + # expensive thread local lookups. + if self._thread_key is None: + self._thread_key = _get_thread_key() + else: + assert self._thread_key == _get_thread_key(), 'Shared across threads?' + + stack = self._stack_dict[self._thread_key] + self.parent = stack[-1] + stack.append(self) + self.update() + return self + + def __exit__(self, unused_type, unused_value, unused_traceback): + top = self._stack_dict[self._thread_key].pop() + assert top is self, 'Concurrent access?' + + def update(self): + raise NotImplementedError('subclasses need to override this') + + +class StackTraceMapper(StackTraceTransform): + """Allows remapping traceback information to different source code.""" + _stack_dict = _source_mapper_stacks + + def __init__(self): + self.internal_map = _tf_stack.PyBindSourceMap() + + def update(self): + self.internal_map.update_to(tuple(self.get_effective_source_map().items())) + + def get_effective_source_map(self): + """Returns a map (filename, lineno) -> (filename, lineno, function_name).""" + raise NotImplementedError('subclasses need to override this') + + +EMPTY_DICT = {} + + +class SentinelMapper(StackTraceMapper): + + def get_effective_source_map(self): + return EMPTY_DICT + + +class StackTraceFilter(StackTraceTransform): + """Allows filtering traceback information by removing superfluous frames.""" + _stack_dict = _source_filter_stacks + + def __init__(self): + self.internal_set = _tf_stack.PyBindFileSet() + + def update(self): + self.internal_set.update_to(set(self.get_filtered_filenames())) + + def get_filtered_filenames(self): + raise NotImplementedError('subclasses need to override this') + + +EMPTY_SET = frozenset() + + +class SentinelFilter(StackTraceFilter): + + def get_filtered_filenames(self): + return EMPTY_SET + + +class CurrentModuleFilter(StackTraceFilter): + """Filters stack frames from the module where this is used (best effort).""" + + def __init__(self): + super().__init__() + filter_filename = None + outer_f = None + f = inspect.currentframe() + try: + if f is not None: + # The current frame is __init__. The first outer frame should be the + # caller. + outer_f = f.f_back + if outer_f is not None: + filter_filename = inspect.getsourcefile(outer_f) + self._filename = filter_filename + # This may be called repeatedly: once on entry by the superclass, then by + # each child context manager. + self._cached_set = None + finally: + # Avoid reference cycles, see: + # https://docs.python.org/3.7/library/inspect.html#the-interpreter-stack + del f + del outer_f + + def get_filtered_filenames(self): + if self._cached_set is not None: + return self._cached_set + + filtered_filenames = frozenset((self._filename,)) + if self.parent is not None: + filtered_filenames |= self.parent.get_filtered_filenames() + self._cached_set = filtered_filenames + return filtered_filenames + + +def extract_stack(stacklevel=1): + """An eager-friendly alternative to traceback.extract_stack. + + Args: + stacklevel: number of initial frames to skip when producing the stack. + + Returns: + A list-like FrameSummary containing StackFrame-like objects, which are + namedtuple-like objects with the following fields: filename, lineno, name, + line, meant to masquerade as traceback.FrameSummary objects. + """ + thread_key = _get_thread_key() + return _tf_stack.extract_stack( + _source_mapper_stacks[thread_key][-1].internal_map, + _source_filter_stacks[thread_key][-1].internal_set, + stacklevel, + ) + + +def LoadTracesFromDebugInfo(debug_info): + return _tf_stack.LoadTracesFromDebugInfo(debug_info.SerializeToString()) + + +class GraphDebugInfoBuilder(_tf_stack.GraphDebugInfoBuilder): + + def AppendGraphDebugInfo(self, fn_name, fn_debug_info): + debug_info_str = fn_debug_info.SerializeToString() + super().AppendGraphDebugInfo(fn_name, debug_info_str) + + def Build(self): + debug_info_str = super().Build() + debug_info = graph_debug_info_pb2.GraphDebugInfo() + debug_info.ParseFromString(debug_info_str) + return debug_info + + +StackSummary = _tf_stack.StackTrace +FrameSummary = _tf_stack.StackFrame diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/traceback_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/traceback_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..8bff91ea4c3f90bff11354e50799719325e65555 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/traceback_utils.py @@ -0,0 +1,157 @@ +# Copyright 2021 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Utilities related to TensorFlow exception stack trace prettifying.""" + +import os +import sys +import threading +import traceback +import types +from tensorflow.python.util import tf_decorator +from tensorflow.python.util.tf_export import tf_export + + +_ENABLE_TRACEBACK_FILTERING = threading.local() +_EXCLUDED_PATHS = ( + os.path.abspath(os.path.join(__file__, '..', '..')), +) + + +@tf_export('debugging.is_traceback_filtering_enabled') +def is_traceback_filtering_enabled(): + """Check whether traceback filtering is currently enabled. + + See also `tf.debugging.enable_traceback_filtering()` and + `tf.debugging.disable_traceback_filtering()`. Note that filtering out + internal frames from the tracebacks of exceptions raised by TensorFlow code + is the default behavior. + + Returns: + True if traceback filtering is enabled + (e.g. if `tf.debugging.enable_traceback_filtering()` was called), + and False otherwise (e.g. if `tf.debugging.disable_traceback_filtering()` + was called). + """ + value = getattr(_ENABLE_TRACEBACK_FILTERING, 'value', True) + return value + + +@tf_export('debugging.enable_traceback_filtering') +def enable_traceback_filtering(): + """Enable filtering out TensorFlow-internal frames in exception stack traces. + + Raw TensorFlow stack traces involve many internal frames, which can be + challenging to read through, while not being actionable for end users. + By default, TensorFlow filters internal frames in most exceptions that it + raises, to keep stack traces short, readable, and focused on what's + actionable for end users (their own code). + + If you have previously disabled traceback filtering via + `tf.debugging.disable_traceback_filtering()`, you can re-enable it via + `tf.debugging.enable_traceback_filtering()`. + + Raises: + RuntimeError: If Python version is not at least 3.7. + """ + if sys.version_info.major != 3 or sys.version_info.minor < 7: + raise RuntimeError( + f'Traceback filtering is only available with Python 3.7 or higher. ' + f'This Python version: {sys.version}') + global _ENABLE_TRACEBACK_FILTERING + _ENABLE_TRACEBACK_FILTERING.value = True + + +@tf_export('debugging.disable_traceback_filtering') +def disable_traceback_filtering(): + """Disable filtering out TensorFlow-internal frames in exception stack traces. + + Raw TensorFlow stack traces involve many internal frames, which can be + challenging to read through, while not being actionable for end users. + By default, TensorFlow filters internal frames in most exceptions that it + raises, to keep stack traces short, readable, and focused on what's + actionable for end users (their own code). + + Calling `tf.debugging.disable_traceback_filtering` disables this filtering + mechanism, meaning that TensorFlow exceptions stack traces will include + all frames, in particular TensorFlow-internal ones. + + **If you are debugging a TensorFlow-internal issue, you need to call + `tf.debugging.disable_traceback_filtering`**. + To re-enable traceback filtering afterwards, you can call + `tf.debugging.enable_traceback_filtering()`. + """ + global _ENABLE_TRACEBACK_FILTERING + _ENABLE_TRACEBACK_FILTERING.value = False + + +def include_frame(fname): + for exclusion in _EXCLUDED_PATHS: + if exclusion in fname: + return False + return True + + +def _process_traceback_frames(tb): + new_tb = None + tb_list = list(traceback.walk_tb(tb)) + for f, line_no in reversed(tb_list): + if include_frame(f.f_code.co_filename): + new_tb = types.TracebackType(new_tb, f, f.f_lasti, line_no) + if new_tb is None and tb_list: + f, line_no = tb_list[-1] + new_tb = types.TracebackType(new_tb, f, f.f_lasti, line_no) + return new_tb + + +def filter_traceback(fn): + """Decorator to filter out TF-internal stack trace frames in exceptions. + + Raw TensorFlow stack traces involve many internal frames, which can be + challenging to read through, while not being actionable for end users. + By default, TensorFlow filters internal frames in most exceptions that it + raises, to keep stack traces short, readable, and focused on what's + actionable for end users (their own code). + + Arguments: + fn: The function or method to decorate. Any exception raised within the + function will be reraised with its internal stack trace frames filtered + out. + + Returns: + Decorated function or method. + """ + if sys.version_info.major != 3 or sys.version_info.minor < 7: + return fn + + def error_handler(*args, **kwargs): + try: + if not is_traceback_filtering_enabled(): + return fn(*args, **kwargs) + except NameError: + # In some very rare cases, + # `is_traceback_filtering_enabled` (from the outer scope) may not be + # accessible from inside this function + return fn(*args, **kwargs) + + filtered_tb = None + try: + return fn(*args, **kwargs) + except Exception as e: + filtered_tb = _process_traceback_frames(e.__traceback__) + raise e.with_traceback(filtered_tb) from None + finally: + del filtered_tb + + return tf_decorator.make_decorator(fn, error_handler) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/type_annotations.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/type_annotations.py new file mode 100644 index 0000000000000000000000000000000000000000..97196bd16a7103130c90f3841248841d57b8f8f6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/type_annotations.py @@ -0,0 +1,59 @@ +# Copyright 2021 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Utilities for accessing Python generic type annotations (typing.*).""" + +import collections.abc +import typing + + +def is_generic_union(tp): + """Returns true if `tp` is a parameterized typing.Union value.""" + return (tp is not typing.Union and + getattr(tp, '__origin__', None) is typing.Union) + + +def is_generic_tuple(tp): + """Returns true if `tp` is a parameterized typing.Tuple value.""" + return (tp not in (tuple, typing.Tuple) and + getattr(tp, '__origin__', None) in (tuple, typing.Tuple)) + + +def is_generic_list(tp): + """Returns true if `tp` is a parameterized typing.List value.""" + return (tp not in (list, typing.List) and + getattr(tp, '__origin__', None) in (list, typing.List)) + + +def is_generic_mapping(tp): + """Returns true if `tp` is a parameterized typing.Mapping value.""" + return (tp not in (collections.abc.Mapping, typing.Mapping) and getattr( + tp, '__origin__', None) in (collections.abc.Mapping, typing.Mapping)) + + +def is_forward_ref(tp): + """Returns true if `tp` is a typing forward reference.""" + if hasattr(typing, 'ForwardRef'): + return isinstance(tp, typing.ForwardRef) + elif hasattr(typing, '_ForwardRef'): + return isinstance(tp, typing._ForwardRef) # pylint: disable=protected-access + else: + return False + + +# Note: typing.get_args was added in Python 3.8. +if hasattr(typing, 'get_args'): + get_generic_type_args = typing.get_args +else: + get_generic_type_args = lambda tp: tp.__args__ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/variable_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/variable_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..9680b338e4943134078552b7583b1d5a245889ba --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/util/variable_utils.py @@ -0,0 +1,83 @@ +# Copyright 2022 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Utility to manipulate resource variables.""" + +from tensorflow.python.framework import composite_tensor +from tensorflow.python.framework import ops +from tensorflow.python.util import _pywrap_utils +from tensorflow.python.util import nest + + +def convert_variables_to_tensors(values): + """Converts `ResourceVariable`s in `values` to `Tensor`s. + + If an object is a `CompositeTensor` and overrides its + `_convert_variables_to_tensors` method, its `ResourceVariable` components + will also be converted to `Tensor`s. Objects other than `ResourceVariable`s + in `values` will be returned unchanged. + + Args: + values: A nested structure of `ResourceVariable`s, or any other objects. + + Returns: + A new structure with `ResourceVariable`s in `values` converted to `Tensor`s. + """ + def _convert_resource_variable_to_tensor(x): + if _pywrap_utils.IsResourceVariable(x): + return ops.convert_to_tensor(x) + elif isinstance(x, composite_tensor.CompositeTensor): + return composite_tensor.convert_variables_to_tensors(x) + else: + return x + + return nest.map_structure(_convert_resource_variable_to_tensor, values) + + +def replace_variables_with_atoms(values): + """Replaces `ResourceVariable`s in `values` with tf.nest atoms. + + This function is mostly for backward compatibility. Historically, + `ResourceVariable`s are treated as tf.nest atoms. This is no + longer the case after `ResourceVariable` becoming `CompositeTensor`. + Unfortunately, tf.nest doesn't allow customization of what objects + are treated as atoms. Calling this function to manually convert + `ResourceVariable`s to atoms to avoid breaking tf.assert_same_structure + with inputs of a `ResourceVariable` and an atom, like a `Tensor`. + + The specific implementation uses 0 as the tf.nest atom, but other tf.nest + atoms could also serve the purpose. Note, the `TypeSpec` of None is not a + tf.nest atom. + + Objects other than `ResourceVariable`s in `values` will be returned unchanged. + + Note: this function does not look into `CompositeTensor`s. Replacing + `ResourceVariable`s in a `CompositeTensor` with atoms will change the + `TypeSpec` of the `CompositeTensor`, which violates the semantics of + `CompositeTensor` and tf.nest. So `ResourceVariable`s in `CompositeTensor`s + will be returned as they are. + + Args: + values: A nested structure of `ResourceVariable`s, or any other objects. + + Returns: + A new structure with `ResourceVariable`s in `values` converted to atoms. + """ + def _replace_resource_variable_with_atom(x): + if _pywrap_utils.IsResourceVariable(x): + return 0 # tf.nest treats 0 or tf.constant(0) as an atom. + else: + return x + + return nest.map_structure(_replace_resource_variable_with_atom, values) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/security/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/security/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/security/fuzzing/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/security/fuzzing/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/security/fuzzing/py/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/security/fuzzing/py/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/security/fuzzing/py/annotation_types.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/security/fuzzing/py/annotation_types.py new file mode 100644 index 0000000000000000000000000000000000000000..4ce6fa3cf85fb33822bf9aef9a0a6d49fb6bace9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/security/fuzzing/py/annotation_types.py @@ -0,0 +1,54 @@ +# Copyright 2023 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Library of types used for type annotation.""" +from tensorflow.python.framework import dtypes as _dtypes + + +class DTypeAnnotation: + pass + + +def _create_dtype_wrapper(name, underlying_dtype: _dtypes.DType): + return type(name, (DTypeAnnotation,), {"underlying_dtype": underlying_dtype}) + + +BFloat16 = _create_dtype_wrapper("BFloat16", _dtypes.bfloat16) +Bool = _create_dtype_wrapper("Bool", _dtypes.bool) +Complex128 = _create_dtype_wrapper("Complex128", _dtypes.complex128) +Complex64 = _create_dtype_wrapper("Complex64", _dtypes.complex64) +Float8e4m3fn = _create_dtype_wrapper("Float8e4m3fn", _dtypes.float8_e4m3fn) +Float8e5m2 = _create_dtype_wrapper("Float8e5m2", _dtypes.float8_e5m2) +Float16 = _create_dtype_wrapper("Float16", _dtypes.float16) +Float32 = _create_dtype_wrapper("Float32", _dtypes.float32) +Float64 = _create_dtype_wrapper("Float64", _dtypes.float64) +Half = _create_dtype_wrapper("Half", _dtypes.float16) +Int4 = _create_dtype_wrapper("Int4", _dtypes.int4) +Int8 = _create_dtype_wrapper("Int8", _dtypes.int8) +Int16 = _create_dtype_wrapper("Int16", _dtypes.int16) +Int32 = _create_dtype_wrapper("Int32", _dtypes.int32) +Int64 = _create_dtype_wrapper("Int64", _dtypes.int64) +UInt4 = _create_dtype_wrapper("UInt4", _dtypes.uint4) +UInt8 = _create_dtype_wrapper("UInt8", _dtypes.uint8) +UInt16 = _create_dtype_wrapper("UInt16", _dtypes.uint16) +UInt32 = _create_dtype_wrapper("UInt32", _dtypes.uint32) +UInt64 = _create_dtype_wrapper("UInt64", _dtypes.uint64) +QInt8 = _create_dtype_wrapper("QInt8", _dtypes.qint8) +QInt16 = _create_dtype_wrapper("QInt16", _dtypes.qint16) +QInt32 = _create_dtype_wrapper("QInt32", _dtypes.qint32) +QUInt16 = _create_dtype_wrapper("QUInt16", _dtypes.quint16) +QUInt8 = _create_dtype_wrapper("QUInt8", _dtypes.quint8) +Resource = _create_dtype_wrapper("Resource", _dtypes.resource) +String = _create_dtype_wrapper("String", _dtypes.string) +Variant = _create_dtype_wrapper("Variant", _dtypes.variant) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tools/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tools/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tools/common/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tools/common/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tools/common/public_api.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tools/common/public_api.py new file mode 100644 index 0000000000000000000000000000000000000000..1a9c2d3ed51baa807ad69ab33fabf67a201427ff --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tools/common/public_api.py @@ -0,0 +1,147 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Visitor restricting traversal to only the public tensorflow API.""" + +import re + +from tensorflow.python.util import tf_inspect + + +class PublicAPIVisitor: + """Visitor to use with `traverse` to visit exactly the public TF API.""" + + def __init__(self, visitor): + """Constructor. + + `visitor` should be a callable suitable as a visitor for `traverse`. It will + be called only for members of the public TensorFlow API. + + Args: + visitor: A visitor to call for the public API. + """ + self._visitor = visitor + self._root_name = 'tf' + + # Modules/classes we want to suppress entirely. + self._private_map = { + 'tf': [ + 'compiler', + 'core', + # TODO(scottzhu): See b/227410870 for more details. Currently + # dtensor API is exposed under tf.experimental.dtensor, but in the + # meantime, we have tensorflow/dtensor directory which will be treat + # as a python package. We want to avoid step into the + # tensorflow/dtensor directory when visit the API. + # When the tf.dtensor becomes the public API, it will actually pick + # up from tf.compat.v2.dtensor as priority and hide the + # tensorflow/dtensor package. + 'security', + 'dtensor', + 'python', + 'tsl', # TODO(tlongeri): Remove after TSL is moved out of TF. + ], + # Some implementations have this internal module that we shouldn't + # expose. + 'tf.flags': ['cpp_flags'], + } + + # Modules/classes we do not want to descend into if we hit them. Usually, + # system modules exposed through platforms for compatibility reasons. + # Each entry maps a module path to a name to ignore in traversal. + self._do_not_descend_map = { + 'tf': [ + 'examples', + 'flags', # Don't add flags + # TODO(drpng): This can be removed once sealed off. + 'platform', + # TODO(drpng): This can be removed once sealed. + 'pywrap_tensorflow', + # TODO(drpng): This can be removed once sealed. + 'user_ops', + 'tools', + 'tensorboard', + ], + + ## Everything below here is legitimate. + # It'll stay, but it's not officially part of the API. + 'tf.app': ['flags'], + # Imported for compatibility between py2/3. + 'tf.test': ['mock'], + } + + @property + def private_map(self): + """A map from parents to symbols that should not be included at all. + + This map can be edited, but it should not be edited once traversal has + begun. + + Returns: + The map marking symbols to not include. + """ + return self._private_map + + @property + def do_not_descend_map(self): + """A map from parents to symbols that should not be descended into. + + This map can be edited, but it should not be edited once traversal has + begun. + + Returns: + The map marking symbols to not explore. + """ + return self._do_not_descend_map + + def set_root_name(self, root_name): + """Override the default root name of 'tf'.""" + self._root_name = root_name + + def _is_private(self, path, name, obj=None): + """Return whether a name is private.""" + # TODO(wicke): Find out what names to exclude. + del obj # Unused. + return ((path in self._private_map and name in self._private_map[path]) or + (name.startswith('_') and not re.match('__.*__$', name) or + name in ['__base__', '__class__', '__next_in_mro__'])) + + def _do_not_descend(self, path, name): + """Safely queries if a specific fully qualified name should be excluded.""" + return (path in self._do_not_descend_map and + name in self._do_not_descend_map[path]) + + def __call__(self, path, parent, children): + """Visitor interface, see `traverse` for details.""" + + # Avoid long waits in cases of pretty unambiguous failure. + if tf_inspect.ismodule(parent) and len(path.split('.')) > 10: + raise RuntimeError('Modules nested too deep:\n%s.%s\n\nThis is likely a ' + 'problem with an accidental public import.' % + (self._root_name, path)) + + # Includes self._root_name + full_path = '.'.join([self._root_name, path]) if path else self._root_name + + # Remove things that are not visible. + for name, child in list(children): + if self._is_private(full_path, name, child): + children.remove((name, child)) + + self._visitor(path, parent, children) + + # Remove things that are visible, but which should not be descended into. + for name, child in list(children): + if self._do_not_descend(full_path, name): + children.remove((name, child)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tools/common/test_module1.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tools/common/test_module1.py new file mode 100644 index 0000000000000000000000000000000000000000..c034e4a233145574cdc73c4db0ccd9bdf9b6d09c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tools/common/test_module1.py @@ -0,0 +1,27 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""A module target for TraverseTest.test_module.""" + +from tensorflow.tools.common import test_module2 + + +class ModuleClass1(object): + + def __init__(self): + self._m2 = test_module2.ModuleClass2() + + def __model_class1_method__(self): + pass + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tools/common/test_module2.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tools/common/test_module2.py new file mode 100644 index 0000000000000000000000000000000000000000..057cb0bfd6da61c45434677858a58ce32bc55e35 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tools/common/test_module2.py @@ -0,0 +1,25 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""A module target for TraverseTest.test_module.""" + + +class ModuleClass2(object): + + def __init__(self): + pass + + def __model_class1_method__(self): + pass + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tools/common/traverse.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tools/common/traverse.py new file mode 100644 index 0000000000000000000000000000000000000000..a38364b99341afa9b97ce322805d92bbf37d7bae --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tools/common/traverse.py @@ -0,0 +1,103 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Traversing Python modules and classes.""" + +import enum +import sys + +from tensorflow.python.util import tf_inspect + +__all__ = ['traverse'] + + +def _traverse_internal(root, visit, stack, path): + """Internal helper for traverse.""" + + # Only traverse modules and classes + if not tf_inspect.isclass(root) and not tf_inspect.ismodule(root): + return + + try: + children = tf_inspect.getmembers(root) + + # Add labels for duplicate values in Enum. + if tf_inspect.isclass(root) and issubclass(root, enum.Enum): + for enum_member in root.__members__.items(): + if enum_member not in children: + children.append(enum_member) + children = sorted(children) + except ImportError: + # Children could be missing for one of two reasons: + # 1. On some Python installations, some modules do not support enumerating + # members, leading to import errors. + # 2. Children are lazy-loaded. + try: + children = [] + for child_name in root.__all__: + children.append((child_name, getattr(root, child_name))) + except AttributeError: + children = [] + + new_stack = stack + [root] + visit(path, root, children) + for name, child in children: + # Do not descend into built-in modules + if tf_inspect.ismodule( + child) and child.__name__ in sys.builtin_module_names: + continue + + # Break cycles + if any(child is item for item in new_stack): # `in`, but using `is` + continue + + child_path = path + '.' + name if path else name + _traverse_internal(child, visit, new_stack, child_path) + + +def traverse(root, visit): + """Recursively enumerate all members of `root`. + + Similar to the Python library function `os.path.walk`. + + Traverses the tree of Python objects starting with `root`, depth first. + Parent-child relationships in the tree are defined by membership in modules or + classes. The function `visit` is called with arguments + `(path, parent, children)` for each module or class `parent` found in the tree + of python objects starting with `root`. `path` is a string containing the name + with which `parent` is reachable from the current context. For example, if + `root` is a local class called `X` which contains a class `Y`, `visit` will be + called with `('Y', X.Y, children)`). + + If `root` is not a module or class, `visit` is never called. `traverse` + never descends into built-in modules. + + `children`, a list of `(name, object)` pairs are determined by + `tf_inspect.getmembers`. To avoid visiting parts of the tree, `children` can + be modified in place, using `del` or slice assignment. + + Cycles (determined by reference equality, `is`) stop the traversal. A stack of + objects is kept to find cycles. Objects forming cycles may appear in + `children`, but `visit` will not be called with any object as `parent` which + is already in the stack. + + Traversing system modules can take a long time, it is advisable to pass a + `visit` callable which denylists such modules. + + Args: + root: A python object with which to start the traversal. + visit: A function taking arguments `(path, parent, children)`. Will be + called for each object found in the traversal. + """ + _traverse_internal(root, visit, [], '') diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tools/compatibility/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tools/compatibility/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tools/compatibility/all_renames_v2.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tools/compatibility/all_renames_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..7520be36faed2e2bcd9cac7cb2915b345dcec170 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tools/compatibility/all_renames_v2.py @@ -0,0 +1,542 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Provides a list of renames between TensorFlow 1.* and 2.0.""" +from tensorflow.tools.compatibility import renames_v2 + +# pylint: disable=line-too-long + +# Add additional renames not in renames_v2.py here. +# IMPORTANT: For the renames in here, if you also need to add to +# function_reorders or function_keyword_renames in tf_upgrade_v2.py, +# use the OLD function name. +# These renames happen after the arguments have been processed. +# After modifying this dict, run the following to update reorders_v2.py: +# bazel run tensorflow/tools/compatibility/update:generate_v2_reorders_map +manual_symbol_renames = { + "tf.batch_to_space_nd": "tf.batch_to_space", + "tf.batch_gather": "tf.compat.v1.batch_gather", + "tf.space_to_batch_nd": "tf.space_to_batch", + "tf.nn.space_to_batch": "tf.space_to_batch", + "tf.estimator.inputs": "tf.compat.v1.estimator.inputs", + "tf.extract_image_patches": "tf.image.extract_patches", + "tf.image.extract_image_patches": "tf.image.extract_patches", + "tf.gfile.Copy": "tf.io.gfile.copy", + "tf.gfile.DeleteRecursively": "tf.io.gfile.rmtree", + "tf.gfile.Exists": "tf.io.gfile.exists", + "tf.gfile.Glob": "tf.io.gfile.glob", + "tf.gfile.GFile": "tf.io.gfile.GFile", + "tf.gfile.IsDirectory": "tf.io.gfile.isdir", + "tf.gfile.ListDirectory": "tf.io.gfile.listdir", + "tf.gfile.MakeDirs": "tf.io.gfile.makedirs", + "tf.gfile.MkDir": "tf.io.gfile.mkdir", + "tf.gfile.Open": "tf.io.gfile.GFile", + "tf.gfile.Remove": "tf.io.gfile.remove", + "tf.gfile.Rename": "tf.io.gfile.rename", + "tf.gfile.Stat": "tf.io.gfile.stat", + "tf.gfile.Walk": "tf.io.gfile.walk", + "tf.contrib.cluster_resolver.ClusterResolver": ( + "tf.distribute.cluster_resolver.ClusterResolver" + ), + "tf.contrib.cluster_resolver.GceClusterResolver": ( + "tf.distribute.cluster_resolver.GCEClusterResolver" + ), + "tf.contrib.cluster_resolver.KubernetesClusterResolver": ( + "tf.distribute.cluster_resolver.KubernetesClusterResolver" + ), + "tf.contrib.cluster_resolver.SimpleClusterResolver": ( + "tf.distribute.cluster_resolver.SimpleClusterResolver" + ), + "tf.contrib.cluster_resolver.SlurmClusterResolver": ( + "tf.distribute.cluster_resolver.SlurmClusterResolver" + ), + "tf.contrib.cluster_resolver.TFConfigClusterResolver": ( + "tf.distribute.cluster_resolver.TFConfigClusterResolver" + ), + "tf.contrib.cluster_resolver.TPUClusterResolver": ( + "tf.distribute.cluster_resolver.TPUClusterResolver" + ), + "tf.contrib.cluster_resolver.UnionClusterResolver": ( + "tf.distribute.cluster_resolver.UnionClusterResolver" + ), + "tf.contrib.data.AUTOTUNE": "tf.data.experimental.AUTOTUNE", + "tf.contrib.data.Counter": "tf.data.experimental.Counter", + "tf.contrib.data.CheckpointInputPipelineHook": ( + "tf.data.experimental.CheckpointInputPipelineHook" + ), + "tf.contrib.data.CsvDataset": "tf.data.experimental.CsvDataset", + "tf.contrib.data.Optional": "tf.data.experimental.Optional", + "tf.contrib.data.RandomDataset": "tf.data.experimental.RandomDataset", + "tf.contrib.data.Reducer": "tf.data.experimental.Reducer", + "tf.contrib.data.SqlDataset": "tf.data.experimental.SqlDataset", + "tf.contrib.data.StatsAggregator": "tf.data.experimental.StatsAggregator", + "tf.contrib.data.TFRecordWriter": "tf.data.experimental.TFRecordWriter", + "tf.contrib.data.assert_element_shape": ( + "tf.data.experimental.assert_element_shape" + ), + "tf.contrib.data.bucket_by_sequence_length": ( + "tf.data.experimental.bucket_by_sequence_length" + ), + "tf.contrib.data.choose_from_datasets": ( + "tf.data.experimental.choose_from_datasets" + ), + "tf.contrib.data.copy_to_device": "tf.data.experimental.copy_to_device", + "tf.contrib.data.dense_to_sparse_batch": ( + "tf.data.experimental.dense_to_sparse_batch" + ), + "tf.contrib.data.enumerate_dataset": ( + "tf.data.experimental.enumerate_dataset" + ), + "tf.contrib.data.get_next_as_optional": ( + "tf.data.experimental.get_next_as_optional" + ), + "tf.contrib.data.get_single_element": ( + "tf.data.experimental.get_single_element" + ), + "tf.contrib.data.group_by_reducer": "tf.data.experimental.group_by_reducer", + "tf.contrib.data.group_by_window": "tf.data.experimental.group_by_window", + "tf.contrib.data.ignore_errors": "tf.data.experimental.ignore_errors", + "tf.contrib.data.latency_stats": "tf.data.experimental.latency_stats", + "tf.contrib.data.make_batched_features_dataset": ( + "tf.data.experimental.make_batched_features_dataset" + ), + "tf.contrib.data.make_csv_dataset": "tf.data.experimental.make_csv_dataset", + "tf.contrib.data.make_saveable_from_iterator": ( + "tf.data.experimental.make_saveable_from_iterator" + ), + "tf.contrib.data.map_and_batch": "tf.data.experimental.map_and_batch", + "tf.contrib.data.parallel_interleave": ( + "tf.data.experimental.parallel_interleave" + ), + "tf.contrib.data.parse_example_dataset": ( + "tf.data.experimental.parse_example_dataset" + ), + "tf.contrib.data.prefetch_to_device": ( + "tf.data.experimental.prefetch_to_device" + ), + "tf.contrib.data.rejection_resample": ( + "tf.data.experimental.rejection_resample" + ), + "tf.contrib.data.sample_from_datasets": ( + "tf.data.experimental.sample_from_datasets" + ), + "tf.contrib.data.scan": "tf.data.experimental.scan", + "tf.contrib.data.set_stats_aggregator": ( + "tf.data.experimental.set_stats_aggregator" + ), + "tf.contrib.data.shuffle_and_repeat": ( + "tf.data.experimental.shuffle_and_repeat" + ), + "tf.contrib.data.unbatch": "tf.data.experimental.unbatch", + "tf.contrib.data.unique": "tf.data.experimental.unique", + "tf.contrib.distribute.CrossDeviceOps": "tf.distribute.CrossDeviceOps", + "tf.contrib.distribute.ReductionToOneDeviceCrossDeviceOps": ( + "tf.distribute.ReductionToOneDevice" + ), + "tf.contrib.estimator.make_early_stopping_hook": ( + "tf.estimator.experimental.make_early_stopping_hook" + ), + "tf.contrib.estimator.stop_if_higher_hook": ( + "tf.estimator.experimental.stop_if_higher_hook" + ), + "tf.contrib.estimator.stop_if_lower_hook": ( + "tf.estimator.experimental.stop_if_lower_hook" + ), + "tf.contrib.estimator.stop_if_no_decrease_hook": ( + "tf.estimator.experimental.stop_if_no_decrease_hook" + ), + "tf.contrib.estimator.stop_if_no_increase_hook": ( + "tf.estimator.experimental.stop_if_no_increase_hook" + ), + "tf.contrib.framework.CriticalSection": "tf.CriticalSection", + "tf.contrib.framework.is_tensor": "tf.is_tensor", + "tf.contrib.framework.load_variable": "tf.train.load_variable", + "tf.contrib.framework.nest.assert_same_structure": ( + "tf.nest.assert_same_structure" + ), + "tf.contrib.framework.nest.flatten": "tf.nest.flatten", + "tf.contrib.framework.nest.is_nested": "tf.nest.is_nested", + "tf.contrib.framework.nest.map_structure": "tf.nest.map_structure", + "tf.contrib.framework.nest.pack_sequence_as": "tf.nest.pack_sequence_as", + "tf.contrib.batching.batch_function": "tf.nondifferentiable_batch_function", + "tf.contrib.util.constant_value": "tf.get_static_value", + "tf.contrib.saved_model.load_keras_model": ( + "tf.compat.v1.keras.experimental.load_from_saved_model" + ), + "tf.contrib.saved_model.save_keras_model": ( + "tf.compat.v1.keras.experimental.export_saved_model" + ), + "tf.contrib.rnn.RNNCell": "tf.compat.v1.nn.rnn_cell.RNNCell", + "tf.contrib.rnn.LSTMStateTuple": "tf.nn.rnn_cell.LSTMStateTuple", + "tf.contrib.rnn.BasicLSTMCell": "tf.compat.v1.nn.rnn_cell.BasicLSTMCell", + "tf.contrib.rnn.BasicRNNCell": "tf.compat.v1.nn.rnn_cell.BasicRNNCell", + "tf.contrib.rnn.GRUCell": "tf.compat.v1.nn.rnn_cell.GRUCell", + "tf.contrib.rnn.LSTMCell": "tf.compat.v1.nn.rnn_cell.LSTMCell", + "tf.contrib.rnn.MultiRNNCell": "tf.compat.v1.nn.rnn_cell.MultiRNNCell", + "tf.contrib.rnn.static_rnn": "tf.compat.v1.nn.static_rnn", + "tf.contrib.rnn.static_state_saving_rnn": ( + "tf.compat.v1.nn.static_state_saving_rnn" + ), + "tf.contrib.rnn.static_bidirectional_rnn": ( + "tf.compat.v1.nn.static_bidirectional_rnn" + ), + "tf.contrib.framework.sort": "tf.sort", + "tf.contrib.framework.argsort": "tf.argsort", + "tf.contrib.summary.all_summary_ops": ( + "tf.compat.v1.summary.all_v2_summary_ops" + ), + "tf.contrib.summary.always_record_summaries": ( + "tf.compat.v2.summary.record_if" + ), + "tf.contrib.summary.audio": "tf.compat.v2.summary.audio", + "tf.contrib.summary.create_file_writer": ( + "tf.compat.v2.summary.create_file_writer" + ), + "tf.contrib.summary.flush": "tf.compat.v2.summary.flush", + "tf.contrib.summary.generic": "tf.compat.v2.summary.write", + "tf.contrib.summary.histogram": "tf.compat.v2.summary.histogram", + "tf.contrib.summary.image": "tf.compat.v2.summary.image", + "tf.contrib.summary.initialize": "tf.compat.v1.summary.initialize", + "tf.contrib.summary.never_record_summaries": ( + "tf.compat.v2.summary.record_if" + ), + "tf.contrib.summary.scalar": "tf.compat.v2.summary.scalar", + "tf.contrib.tpu.CrossShardOptimizer": ( + "tf.compat.v1.tpu.CrossShardOptimizer" + ), + "tf.contrib.tpu.InputPipelineConfig": ( + "tf.compat.v1.estimator.tpu.InputPipelineConfig" + ), + "tf.contrib.tpu.RunConfig": "tf.compat.v1.estimator.tpu.RunConfig", + "tf.contrib.tpu.TPUConfig": "tf.compat.v1.estimator.tpu.TPUConfig", + "tf.contrib.tpu.TPUEstimator": "tf.compat.v1.estimator.tpu.TPUEstimator", + "tf.contrib.tpu.TPUEstimatorSpec": ( + "tf.compat.v1.estimator.tpu.TPUEstimatorSpec" + ), + "tf.contrib.tpu.batch_parallel": "tf.compat.v1.tpu.batch_parallel", + "tf.contrib.tpu.bfloat16_scope": "tf.compat.v1.tpu.bfloat16_scope", + "tf.contrib.tpu.core": "tf.compat.v1.tpu.core", + "tf.contrib.tpu.cross_replica_sum": "tf.compat.v1.tpu.cross_replica_sum", + "tf.contrib.tpu.initialize_system": "tf.compat.v1.tpu.initialize_system", + "tf.contrib.tpu.outside_compilation": ( + "tf.compat.v1.tpu.outside_compilation" + ), + "tf.contrib.tpu.replicate": "tf.compat.v1.tpu.replicate", + "tf.contrib.tpu.rewrite": "tf.compat.v1.tpu.rewrite", + "tf.contrib.tpu.shard": "tf.compat.v1.tpu.shard", + "tf.contrib.tpu.shutdown_system": "tf.compat.v1.tpu.shutdown_system", + "tf.contrib.training.checkpoints_iterator": "tf.train.checkpoints_iterator", + "tf.contrib.layers.recompute_grad": "tf.recompute_grad", + "tf.count_nonzero": "tf.math.count_nonzero", + "tf.decode_raw": "tf.io.decode_raw", + "tf.manip.batch_to_space_nd": "tf.batch_to_space", + "tf.quantize_v2": "tf.quantization.quantize", + "tf.sparse_matmul": "tf.linalg.matmul", + "tf.random.stateless_multinomial": "tf.random.stateless_categorical", + "tf.substr": "tf.strings.substr", + # TODO(b/129398290) + "tf.string_split": "tf.compat.v1.string_split", + "tf.string_to_hash_bucket": "tf.strings.to_hash_bucket", + "tf.string_to_number": "tf.strings.to_number", + "tf.multinomial": "tf.random.categorical", + "tf.random.multinomial": "tf.random.categorical", + "tf.reduce_join": "tf.strings.reduce_join", + "tf.load_file_system_library": "tf.load_library", + "tf.bincount": "tf.math.bincount", + "tf.confusion_matrix": "tf.math.confusion_matrix", + "tf.train.confusion_matrix": "tf.math.confusion_matrix", + "tf.train.sdca_fprint": "tf.raw_ops.SdcaFprint", + "tf.train.sdca_optimizer": "tf.raw_ops.SdcaOptimizer", + "tf.train.sdca_shrink_l1": "tf.raw_ops.SdcaShrinkL1", + "tf.decode_csv": "tf.io.decode_csv", + "tf.data.Iterator": "tf.compat.v1.data.Iterator", + "tf.data.experimental.DatasetStructure": "tf.data.DatasetSpec", + "tf.data.experimental.OptionalStructure": "tf.OptionalSpec", + "tf.data.experimental.RaggedTensorStructure": "tf.RaggedTensorSpec", + "tf.data.experimental.SparseTensorStructure": "tf.SparseTensorSpec", + "tf.data.experimental.Structure": "tf.TypeSpec", + "tf.data.experimental.TensorArrayStructure": "tf.TensorArraySpec", + "tf.data.experimental.TensorStructure": "tf.TensorSpec", + "tf.parse_example": "tf.io.parse_example", + "tf.parse_single_example": "tf.io.parse_single_example", + "tf.nn.fused_batch_norm": "tf.compat.v1.nn.fused_batch_norm", + "tf.nn.softmax_cross_entropy_with_logits_v2": ( + "tf.nn.softmax_cross_entropy_with_logits" + ), + "tf.losses.Reduction.MEAN": "tf.compat.v1.losses.Reduction.MEAN", + "tf.losses.Reduction.SUM_BY_NONZERO_WEIGHTS": ( + "tf.compat.v1.losses.Reduction.SUM_BY_NONZERO_WEIGHTS" + ), + "tf.losses.Reduction.SUM_OVER_NONZERO_WEIGHTS": ( + "tf.compat.v1.losses.Reduction.SUM_OVER_NONZERO_WEIGHTS" + ), + "tf.lite.constants.FLOAT": "tf.float32", + "tf.lite.constants.FLOAT16": "tf.float16", + "tf.lite.constants.INT16": "tf.int16", + "tf.lite.constants.INT32": "tf.int32", + "tf.lite.constants.INT64": "tf.int64", + "tf.lite.constants.INT8": "tf.int8", + "tf.lite.constants.STRING": "tf.string", + "tf.lite.constants.QUANTIZED_UINT8": "tf.uint8", + "tf.arg_max": "tf.argmax", + "tf.arg_min": "tf.argmin", + # tf.nn.ctc_loss is still available in 2.0 but behavior + # changed significantly. + "tf.nn.ctc_loss": "tf.compat.v1.nn.ctc_loss", + # tf.saved_model.load in 1.x has no equivalent in 2.x, but there is a + # symbol with the same name. + "tf.saved_model.load": "tf.compat.v1.saved_model.load", + "tf.saved_model.loader.load": "tf.compat.v1.saved_model.load", + "tf.saved_model.load_v2": "tf.compat.v2.saved_model.load", + "tf.image.resize_images": "tf.image.resize", + "tf.assert_equal": "tf.compat.v1.assert_equal", + "tf.assert_greater": "tf.compat.v1.assert_greater", + "tf.assert_greater_equal": "tf.compat.v1.assert_greater_equal", + "tf.assert_integer": "tf.compat.v1.assert_integer", + "tf.assert_less": "tf.compat.v1.assert_less", + "tf.assert_less_equal": "tf.compat.v1.assert_less_equal", + "tf.assert_near": "tf.compat.v1.assert_near", + "tf.assert_negative": "tf.compat.v1.assert_negative", + "tf.assert_non_negative": "tf.compat.v1.assert_non_negative", + "tf.assert_non_positive": "tf.compat.v1.assert_non_positive", + "tf.assert_none_equal": "tf.compat.v1.assert_none_equal", + "tf.assert_positive": "tf.compat.v1.assert_positive", + "tf.assert_rank": "tf.compat.v1.assert_rank", + "tf.assert_rank_at_least": "tf.compat.v1.assert_rank_at_least", + "tf.assert_rank_in": "tf.compat.v1.assert_rank_in", + "tf.assert_scalar": "tf.compat.v1.assert_scalar", + "tf.assert_type": "tf.compat.v1.assert_type", + "tf.assert_variables_initialized": ( + "tf.compat.v1.assert_variables_initialized" + ), + "tf.debugging.assert_equal": "tf.compat.v1.debugging.assert_equal", + "tf.debugging.assert_greater": "tf.compat.v1.debugging.assert_greater", + "tf.debugging.assert_greater_equal": ( + "tf.compat.v1.debugging.assert_greater_equal" + ), + "tf.debugging.assert_integer": "tf.compat.v1.debugging.assert_integer", + "tf.debugging.assert_less": "tf.compat.v1.debugging.assert_less", + "tf.debugging.assert_less_equal": ( + "tf.compat.v1.debugging.assert_less_equal" + ), + "tf.debugging.assert_near": "tf.compat.v1.debugging.assert_near", + "tf.debugging.assert_negative": "tf.compat.v1.debugging.assert_negative", + "tf.debugging.assert_non_negative": ( + "tf.compat.v1.debugging.assert_non_negative" + ), + "tf.debugging.assert_non_positive": ( + "tf.compat.v1.debugging.assert_non_positive" + ), + "tf.debugging.assert_none_equal": ( + "tf.compat.v1.debugging.assert_none_equal" + ), + "tf.debugging.assert_positive": "tf.compat.v1.debugging.assert_positive", + "tf.debugging.assert_rank": "tf.compat.v1.debugging.assert_rank", + "tf.debugging.assert_rank_at_least": ( + "tf.compat.v1.debugging.assert_rank_at_least" + ), + "tf.debugging.assert_rank_in": "tf.compat.v1.debugging.assert_rank_in", + "tf.debugging.assert_scalar": "tf.compat.v1.debugging.assert_scalar", + "tf.debugging.assert_type": "tf.compat.v1.debugging.assert_type", + "tf.errors.exception_type_from_error_code": ( + "tf.compat.v1.errors.exception_type_from_error_code" + ), + "tf.errors.error_code_from_exception_type": ( + "tf.compat.v1.errors.error_code_from_exception_type" + ), + "tf.errors.raise_exception_on_not_ok_status": ( + "tf.compat.v1.errors.raise_exception_on_not_ok_status" + ), + "tf.nn.max_pool": "tf.nn.max_pool2d", + "tf.nn.avg_pool": "tf.nn.avg_pool2d", + "tf.keras.initializers.zeros": "tf.compat.v1.keras.initializers.zeros", + "tf.keras.initializers.Zeros": "tf.compat.v1.keras.initializers.Zeros", + "tf.keras.initializers.ones": "tf.compat.v1.keras.initializers.ones", + "tf.keras.initializers.Ones": "tf.compat.v1.keras.initializers.Ones", + "tf.keras.initializers.constant": ( + "tf.compat.v1.keras.initializers.constant" + ), + "tf.keras.initializers.Constant": ( + "tf.compat.v1.keras.initializers.Constant" + ), + "tf.keras.initializers.VarianceScaling": ( + "tf.compat.v1.keras.initializers.VarianceScaling" + ), + "tf.keras.initializers.Orthogonal": ( + "tf.compat.v1.keras.initializers.Orthogonal" + ), + "tf.keras.initializers.orthogonal": ( + "tf.compat.v1.keras.initializers.orthogonal" + ), + "tf.keras.initializers.Identity": ( + "tf.compat.v1.keras.initializers.Identity" + ), + "tf.keras.initializers.identity": ( + "tf.compat.v1.keras.initializers.identity" + ), + "tf.keras.initializers.glorot_uniform": ( + "tf.compat.v1.keras.initializers.glorot_uniform" + ), + "tf.keras.initializers.glorot_normal": ( + "tf.compat.v1.keras.initializers.glorot_normal" + ), + "tf.keras.initializers.lecun_normal": ( + "tf.compat.v1.keras.initializers.lecun_normal" + ), + "tf.keras.initializers.lecun_uniform": ( + "tf.compat.v1.keras.initializers.lecun_uniform" + ), + "tf.keras.initializers.he_normal": ( + "tf.compat.v1.keras.initializers.he_normal" + ), + "tf.keras.initializers.he_uniform": ( + "tf.compat.v1.keras.initializers.he_uniform" + ), + "tf.keras.initializers.TruncatedNormal": ( + "tf.compat.v1.keras.initializers.TruncatedNormal" + ), + "tf.keras.initializers.truncated_normal": ( + "tf.compat.v1.keras.initializers.truncated_normal" + ), + "tf.keras.initializers.RandomUniform": ( + "tf.compat.v1.keras.initializers.RandomUniform" + ), + "tf.keras.initializers.uniform": "tf.compat.v1.keras.initializers.uniform", + "tf.keras.initializers.random_uniform": ( + "tf.compat.v1.keras.initializers.random_uniform" + ), + "tf.keras.initializers.RandomNormal": ( + "tf.compat.v1.keras.initializers.RandomNormal" + ), + "tf.keras.initializers.normal": "tf.compat.v1.keras.initializers.normal", + "tf.keras.initializers.random_normal": ( + "tf.compat.v1.keras.initializers.random_normal" + ), + "tf.zeros_initializer": "tf.compat.v1.zeros_initializer", + "tf.initializers.zeros": "tf.compat.v1.initializers.zeros", + "tf.ones_initializer": "tf.compat.v1.ones_initializer", + "tf.initializers.ones": "tf.compat.v1.initializers.ones", + "tf.constant_initializer": "tf.compat.v1.constant_initializer", + "tf.initializers.constant": "tf.compat.v1.initializers.constant", + "tf.random_uniform_initializer": "tf.compat.v1.random_uniform_initializer", + "tf.initializers.random_uniform": ( + "tf.compat.v1.initializers.random_uniform" + ), + "tf.random_normal_initializer": "tf.compat.v1.random_normal_initializer", + "tf.initializers.random_normal": "tf.compat.v1.initializers.random_normal", + "tf.truncated_normal_initializer": ( + "tf.compat.v1.truncated_normal_initializer" + ), + "tf.initializers.truncated_normal": ( + "tf.compat.v1.initializers.truncated_normal" + ), + "tf.variance_scaling_initializer": ( + "tf.compat.v1.variance_scaling_initializer" + ), + "tf.initializers.variance_scaling": ( + "tf.compat.v1.initializers.variance_scaling" + ), + "tf.orthogonal_initializer": "tf.compat.v1.orthogonal_initializer", + "tf.initializers.orthogonal": "tf.compat.v1.initializers.orthogonal", + "tf.glorot_uniform_initializer": "tf.compat.v1.glorot_uniform_initializer", + "tf.initializers.glorot_uniform": ( + "tf.compat.v1.initializers.glorot_uniform" + ), + "tf.glorot_normal_initializer": "tf.compat.v1.glorot_normal_initializer", + "tf.initializers.glorot_normal": "tf.compat.v1.initializers.glorot_normal", + "tf.initializers.identity": "tf.compat.v1.initializers.identity", + "tf.initializers.lecun_normal": "tf.compat.v1.initializers.lecun_normal", + "tf.initializers.lecun_uniform": "tf.compat.v1.initializers.lecun_uniform", + "tf.initializers.he_normal": "tf.compat.v1.initializers.he_normal", + "tf.initializers.he_uniform": "tf.compat.v1.initializers.he_uniform", + "tf.data.experimental.map_and_batch_with_legacy_function": ( + "tf.compat.v1.data.experimental.map_and_batch_with_legacy_function" + ), + "tf.nn.conv2d_backprop_input": "tf.nn.conv2d_transpose", + "tf.test.compute_gradient": "tf.compat.v1.test.compute_gradient", + "tf.floor_div": "tf.math.floordiv", + "tf.where": "tf.compat.v1.where", + "tf.where_v2": "tf.compat.v2.where", + "tf.app.flags": "tf.compat.v1.app.flags", +} +# pylint: enable=line-too-long + + +def add_contrib_direct_import_support(symbol_dict): + """Add support for `tf.contrib.*` alias `contrib_*.` Updates dict in place.""" + for symbol_name in list(symbol_dict.keys()): + symbol_alias = symbol_name.replace("tf.contrib.", "contrib_") + symbol_dict[symbol_alias] = symbol_dict[symbol_name] + +add_contrib_direct_import_support(manual_symbol_renames) + +symbol_renames = renames_v2.renames +symbol_renames.update(manual_symbol_renames) + +addons_symbol_mappings = { + "tf.contrib.layers.poincare_normalize": + "tfa.layers.PoincareNormalize", + "tf.contrib.layers.maxout": + "tfa.layers.Maxout", + "tf.contrib.layers.group_norm": + "tfa.layers.GroupNormalization", + "tf.contrib.layers.instance_norm": + "tfa.layers.InstanceNormalization", + "tf.contrib.sparsemax.sparsemax": + "tfa.activations.sparsemax", + "tf.contrib.losses.metric_learning.contrastive_loss": + "tfa.losses.ContrastiveLoss", + "tf.contrib.losses.metric_learning.lifted_struct_loss": + "tfa.losses.LiftedStructLoss", + "tf.contrib.sparsemax.sparsemax_loss": + "tfa.losses.SparsemaxLoss", + "tf.contrib.losses.metric_learning.triplet_semihard_loss": + "tfa.losses.TripletSemiHardLoss", + "tf.contrib.opt.LazyAdamOptimizer": + "tfa.optimizers.LazyAdam", + "tf.contrib.opt.MovingAverageOptimizer": + "tfa.optimizers.MovingAverage", + "tf.contrib.opt.MomentumWOptimizer": + "tfa.optimizers.SGDW", + "tf.contrib.opt.AdamWOptimizer": + "tfa.optimizers.AdamW", + "tf.contrib.opt.extend_with_decoupled_weight_decay": + "tfa.optimizers.extend_with_decoupled_weight_decay", + "tf.contrib.text.skip_gram_sample": + "tfa.text.skip_gram_sample", + "tf.contrib.text.skip_gram_sample_with_text_vocab": + "tfa.text.skip_gram_sample_with_text_vocab", + "tf.contrib.image.dense_image_warp": + "tfa.image.dense_image_warp", + "tf.contrib.image.adjust_hsv_in_yiq": + "tfa.image.adjust_hsv_in_yiq", + "tf.contrib.image.compose_transforms": + "tfa.image.compose_transforms", + "tf.contrib.image.random_hsv_in_yiq": + "tfa.image.random_hsv_in_yiq", + "tf.contrib.image.angles_to_projective_transforms": + "tfa.image.angles_to_projective_transforms", + "tf.contrib.image.matrices_to_flat_transforms": + "tfa.image.matrices_to_flat_transforms", + "tf.contrib.image.rotate": + "tfa.image.rotate", + "tf.contrib.image.transform": + "tfa.image.transform", + "tf.contrib.rnn.NASCell": + "tfa.rnn.NASCell", + "tf.contrib.rnn.LayerNormBasicLSTMCell": + "tfa.rnn.LayerNormLSTMCell" +} + +add_contrib_direct_import_support(addons_symbol_mappings) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tools/compatibility/ast_edits.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tools/compatibility/ast_edits.py new file mode 100644 index 0000000000000000000000000000000000000000..ed595ba05135b0fe74b8882be205433df72ef32e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tools/compatibility/ast_edits.py @@ -0,0 +1,1101 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Upgrader for Python scripts according to an API change specification.""" + +import ast +import collections +import os +import re +import shutil +import sys +import tempfile +import traceback + +import pasta + + +# Some regular expressions we will need for parsing +FIND_OPEN = re.compile(r"^\s*(\[).*$") +FIND_STRING_CHARS = re.compile(r"['\"]") + + +INFO = "INFO" +WARNING = "WARNING" +ERROR = "ERROR" + + +ImportRename = collections.namedtuple( + "ImportRename", ["new_name", "excluded_prefixes"]) + + +def full_name_node(name, ctx=ast.Load()): + """Make an Attribute or Name node for name. + + Translate a qualified name into nested Attribute nodes (and a Name node). + + Args: + name: The name to translate to a node. + ctx: What context this name is used in. Defaults to Load() + + Returns: + A Name or Attribute node. + """ + names = name.split(".") + names.reverse() + node = ast.Name(id=names.pop(), ctx=ast.Load()) + while names: + node = ast.Attribute(value=node, attr=names.pop(), ctx=ast.Load()) + + # Change outermost ctx to the one given to us (inner ones should be Load). + node.ctx = ctx + return node + + +def get_arg_value(node, arg_name, arg_pos=None): + """Get the value of an argument from a ast.Call node. + + This function goes through the positional and keyword arguments to check + whether a given argument was used, and if so, returns its value (the node + representing its value). + + This cannot introspect *args or **args, but it safely handles *args in + Python3.5+. + + Args: + node: The ast.Call node to extract arg values from. + arg_name: The name of the argument to extract. + arg_pos: The position of the argument (in case it's passed as a positional + argument). + + Returns: + A tuple (arg_present, arg_value) containing a boolean indicating whether + the argument is present, and its value in case it is. + """ + # Check keyword args + if arg_name is not None: + for kw in node.keywords: + if kw.arg == arg_name: + return (True, kw.value) + + # Check positional args + if arg_pos is not None: + idx = 0 + for arg in node.args: + if sys.version_info[:2] >= (3, 5) and isinstance(arg, ast.Starred): + continue # Can't parse Starred + if idx == arg_pos: + return (True, arg) + idx += 1 + + return (False, None) + + +def uses_star_args_in_call(node): + """Check if an ast.Call node uses arbitrary-length positional *args. + + This function works with the AST call node format of Python3.5+ + as well as the different AST format of earlier versions of Python. + + Args: + node: The ast.Call node to check arg values for. + + Returns: + True if the node uses starred variadic positional args or keyword args. + False if it does not. + """ + if sys.version_info[:2] >= (3, 5): + # Check for an *args usage in python 3.5+ + for arg in node.args: + if isinstance(arg, ast.Starred): + return True + else: + if node.starargs: + return True + return False + + +def uses_star_kwargs_in_call(node): + """Check if an ast.Call node uses arbitrary-length **kwargs. + + This function works with the AST call node format of Python3.5+ + as well as the different AST format of earlier versions of Python. + + Args: + node: The ast.Call node to check arg values for. + + Returns: + True if the node uses starred variadic positional args or keyword args. + False if it does not. + """ + if sys.version_info[:2] >= (3, 5): + # Check for a **kwarg usage in python 3.5+ + for keyword in node.keywords: + if keyword.arg is None: + return True + else: + if node.kwargs: + return True + return False + + +def uses_star_args_or_kwargs_in_call(node): + """Check if an ast.Call node uses arbitrary-length *args or **kwargs. + + This function works with the AST call node format of Python3.5+ + as well as the different AST format of earlier versions of Python. + + Args: + node: The ast.Call node to check arg values for. + + Returns: + True if the node uses starred variadic positional args or keyword args. + False if it does not. + """ + return uses_star_args_in_call(node) or uses_star_kwargs_in_call(node) + + +def excluded_from_module_rename(module, import_rename_spec): + """Check if this module import should not be renamed. + + Args: + module: (string) module name. + import_rename_spec: ImportRename instance. + + Returns: + True if this import should not be renamed according to the + import_rename_spec. + """ + for excluded_prefix in import_rename_spec.excluded_prefixes: + if module.startswith(excluded_prefix): + return True + return False + + +class APIChangeSpec: + """This class defines the transformations that need to happen. + + This class must provide the following fields: + + * `function_keyword_renames`: maps function names to a map of old -> new + argument names + * `symbol_renames`: maps function names to new function names + * `change_to_function`: a set of function names that have changed (for + notifications) + * `function_reorders`: maps functions whose argument order has changed to the + list of arguments in the new order + * `function_warnings`: maps full names of functions to warnings that will be + printed out if the function is used. (e.g. tf.nn.convolution()) + * `function_transformers`: maps function names to custom handlers + * `module_deprecations`: maps module names to warnings that will be printed + if the module is still used after all other transformations have run + * `import_renames`: maps import name (must be a short name without '.') + to ImportRename instance. + + For an example, see `TFAPIChangeSpec`. + """ + + def preprocess(self, root_node): # pylint: disable=unused-argument + """Preprocess a parse tree. Return a preprocessed node, logs and errors.""" + return root_node, [], [] + + def clear_preprocessing(self): + """Restore this APIChangeSpec to before it preprocessed a file. + + This is needed if preprocessing a file changed any rewriting rules. + """ + pass + + +class NoUpdateSpec(APIChangeSpec): + """A specification of an API change which doesn't change anything.""" + + def __init__(self): + self.function_handle = {} + self.function_reorders = {} + self.function_keyword_renames = {} + self.symbol_renames = {} + self.function_warnings = {} + self.change_to_function = {} + self.module_deprecations = {} + self.function_transformers = {} + self.import_renames = {} + + +class _PastaEditVisitor(ast.NodeVisitor): + """AST Visitor that processes function calls. + + Updates function calls from old API version to new API version using a given + change spec. + """ + + def __init__(self, api_change_spec): + self._api_change_spec = api_change_spec + self._log = [] # Holds 4-tuples: severity, line, col, msg. + self._stack = [] # Allow easy access to parents. + + # Overridden to maintain a stack of nodes to allow for parent access + def visit(self, node): + self._stack.append(node) + super(_PastaEditVisitor, self).visit(node) + self._stack.pop() + + @property + def errors(self): + return [log for log in self._log if log[0] == ERROR] + + @property + def warnings(self): + return [log for log in self._log if log[0] == WARNING] + + @property + def warnings_and_errors(self): + return [log for log in self._log if log[0] in (WARNING, ERROR)] + + @property + def info(self): + return [log for log in self._log if log[0] == INFO] + + @property + def log(self): + return self._log + + def add_log(self, severity, lineno, col, msg): + self._log.append((severity, lineno, col, msg)) + print("%s line %d:%d: %s" % (severity, lineno, col, msg)) + + def add_logs(self, logs): + """Record a log and print it. + + The log should be a tuple `(severity, lineno, col_offset, msg)`, which will + be printed and recorded. It is part of the log available in the `self.log` + property. + + Args: + logs: The logs to add. Must be a list of tuples + `(severity, lineno, col_offset, msg)`. + """ + self._log.extend(logs) + for log in logs: + print("%s line %d:%d: %s" % log) + + def _get_applicable_entries(self, transformer_field, full_name, name): + """Get all list entries indexed by name that apply to full_name or name.""" + # Transformers are indexed to full name, name, or no name + # as a performance optimization. + function_transformers = getattr(self._api_change_spec, + transformer_field, {}) + + glob_name = "*." + name if name else None + transformers = [] + if full_name in function_transformers: + transformers.append(function_transformers[full_name]) + if glob_name in function_transformers: + transformers.append(function_transformers[glob_name]) + if "*" in function_transformers: + transformers.append(function_transformers["*"]) + return transformers + + def _get_applicable_dict(self, transformer_field, full_name, name): + """Get all dict entries indexed by name that apply to full_name or name.""" + # Transformers are indexed to full name, name, or no name + # as a performance optimization. + function_transformers = getattr(self._api_change_spec, + transformer_field, {}) + + glob_name = "*." + name if name else None + transformers = function_transformers.get("*", {}).copy() + transformers.update(function_transformers.get(glob_name, {})) + transformers.update(function_transformers.get(full_name, {})) + return transformers + + def _get_full_name(self, node): + """Traverse an Attribute node to generate a full name, e.g., "tf.foo.bar". + + This is the inverse of `full_name_node`. + + Args: + node: A Node of type Attribute. + + Returns: + a '.'-delimited full-name or None if node was not Attribute or Name. + i.e. `foo()+b).bar` returns None, while `a.b.c` would return "a.b.c". + """ + curr = node + items = [] + while not isinstance(curr, ast.Name): + if not isinstance(curr, ast.Attribute): + return None + items.append(curr.attr) + curr = curr.value + items.append(curr.id) + return ".".join(reversed(items)) + + def _maybe_add_warning(self, node, full_name): + """Adds an error to be printed about full_name at node.""" + function_warnings = self._api_change_spec.function_warnings + if full_name in function_warnings: + level, message = function_warnings[full_name] + message = message.replace("", full_name) + self.add_log(level, node.lineno, node.col_offset, + "%s requires manual check. %s" % (full_name, message)) + return True + else: + return False + + def _maybe_add_module_deprecation_warning(self, node, full_name, whole_name): + """Adds a warning if full_name is a deprecated module.""" + warnings = self._api_change_spec.module_deprecations + if full_name in warnings: + level, message = warnings[full_name] + message = message.replace("", whole_name) + self.add_log(level, node.lineno, node.col_offset, + "Using member %s in deprecated module %s. %s" % (whole_name, + full_name, + message)) + return True + else: + return False + + def _maybe_add_call_warning(self, node, full_name, name): + """Print a warning when specific functions are called with selected args. + + The function _print_warning_for_function matches the full name of the called + function, e.g., tf.foo.bar(). This function matches the function name that + is called, as long as the function is an attribute. For example, + `tf.foo.bar()` and `foo.bar()` are matched, but not `bar()`. + + Args: + node: ast.Call object + full_name: The precomputed full name of the callable, if one exists, None + otherwise. + name: The precomputed name of the callable, if one exists, None otherwise. + + Returns: + Whether an error was recorded. + """ + # Only look for *.-warnings here, the other will be handled by the Attribute + # visitor. Also, do not warn for bare functions, only if the call func is + # an attribute. + warned = False + if isinstance(node.func, ast.Attribute): + warned = self._maybe_add_warning(node, "*." + name) + + # All arg warnings are handled here, since only we have the args + arg_warnings = self._get_applicable_dict("function_arg_warnings", + full_name, name) + + variadic_args = uses_star_args_or_kwargs_in_call(node) + + for (kwarg, arg), (level, warning) in sorted(arg_warnings.items()): + present, _ = get_arg_value(node, kwarg, arg) or variadic_args + if present: + warned = True + warning_message = warning.replace("", full_name or name) + template = "%s called with %s argument, requires manual check: %s" + if variadic_args: + template = ("%s called with *args or **kwargs that may include %s, " + "requires manual check: %s") + self.add_log(level, node.lineno, node.col_offset, + template % (full_name or name, kwarg, warning_message)) + + return warned + + def _maybe_rename(self, parent, node, full_name): + """Replace node (Attribute or Name) with a node representing full_name.""" + new_name = self._api_change_spec.symbol_renames.get(full_name, None) + if new_name: + self.add_log(INFO, node.lineno, node.col_offset, + "Renamed %r to %r" % (full_name, new_name)) + new_node = full_name_node(new_name, node.ctx) + ast.copy_location(new_node, node) + pasta.ast_utils.replace_child(parent, node, new_node) + return True + else: + return False + + def _maybe_change_to_function_call(self, parent, node, full_name): + """Wraps node (typically, an Attribute or Expr) in a Call.""" + if full_name in self._api_change_spec.change_to_function: + if not isinstance(parent, ast.Call): + # ast.Call's constructor is really picky about how many arguments it + # wants, and also, it changed between Py2 and Py3. + new_node = ast.Call(node, [], []) + pasta.ast_utils.replace_child(parent, node, new_node) + ast.copy_location(new_node, node) + self.add_log(INFO, node.lineno, node.col_offset, + "Changed %r to a function call" % full_name) + return True + return False + + def _maybe_add_arg_names(self, node, full_name): + """Make args into keyword args if function called full_name requires it.""" + function_reorders = self._api_change_spec.function_reorders + + if full_name in function_reorders: + if uses_star_args_in_call(node): + self.add_log(WARNING, node.lineno, node.col_offset, + "(Manual check required) upgrading %s may require " + "re-ordering the call arguments, but it was passed " + "variable-length positional *args. The upgrade " + "script cannot handle these automatically." % full_name) + + reordered = function_reorders[full_name] + new_args = [] + new_keywords = [] + idx = 0 + for arg in node.args: + if sys.version_info[:2] >= (3, 5) and isinstance(arg, ast.Starred): + continue # Can't move Starred to keywords + keyword_arg = reordered[idx] + if keyword_arg: + new_keywords.append(ast.keyword(arg=keyword_arg, value=arg)) + else: + new_args.append(arg) + idx += 1 + + if new_keywords: + self.add_log(INFO, node.lineno, node.col_offset, + "Added keywords to args of function %r" % full_name) + node.args = new_args + node.keywords = new_keywords + (node.keywords or []) + return True + return False + + def _maybe_modify_args(self, node, full_name, name): + """Rename keyword args if the function called full_name requires it.""" + renamed_keywords = self._get_applicable_dict("function_keyword_renames", + full_name, name) + + if not renamed_keywords: + return False + + if uses_star_kwargs_in_call(node): + self.add_log(WARNING, node.lineno, node.col_offset, + "(Manual check required) upgrading %s may require " + "renaming or removing call arguments, but it was passed " + "variable-length *args or **kwargs. The upgrade " + "script cannot handle these automatically." % + (full_name or name)) + modified = False + new_keywords = [] + for keyword in node.keywords: + argkey = keyword.arg + if argkey in renamed_keywords: + modified = True + if renamed_keywords[argkey] is None: + lineno = getattr(keyword, "lineno", node.lineno) + col_offset = getattr(keyword, "col_offset", node.col_offset) + self.add_log(INFO, lineno, col_offset, + "Removed argument %s for function %s" % ( + argkey, full_name or name)) + else: + keyword.arg = renamed_keywords[argkey] + lineno = getattr(keyword, "lineno", node.lineno) + col_offset = getattr(keyword, "col_offset", node.col_offset) + self.add_log(INFO, lineno, col_offset, + "Renamed keyword argument for %s from %s to %s" % ( + full_name, argkey, renamed_keywords[argkey])) + new_keywords.append(keyword) + else: + new_keywords.append(keyword) + + if modified: + node.keywords = new_keywords + return modified + + def visit_Call(self, node): # pylint: disable=invalid-name + """Handle visiting a call node in the AST. + + Args: + node: Current Node + """ + assert self._stack[-1] is node + + # Get the name for this call, so we can index stuff with it. + full_name = self._get_full_name(node.func) + if full_name: + name = full_name.split(".")[-1] + elif isinstance(node.func, ast.Name): + name = node.func.id + elif isinstance(node.func, ast.Attribute): + name = node.func.attr + else: + name = None + + # Call standard transformers for this node. + # Make sure warnings come first, since args or names triggering warnings + # may be removed by the other transformations. + self._maybe_add_call_warning(node, full_name, name) + # Make all args into kwargs + self._maybe_add_arg_names(node, full_name) + # Argument name changes or deletions + self._maybe_modify_args(node, full_name, name) + + # Call transformers. These have the ability to modify the node, and if they + # do, will return the new node they created (or the same node if they just + # changed it). The are given the parent, but we will take care of + # integrating their changes into the parent if they return a new node. + # + # These are matched on the old name, since renaming is performed by the + # Attribute visitor, which happens later. + transformers = self._get_applicable_entries("function_transformers", + full_name, name) + + parent = self._stack[-2] + + if transformers: + if uses_star_args_or_kwargs_in_call(node): + self.add_log(WARNING, node.lineno, node.col_offset, + "(Manual check required) upgrading %s may require " + "modifying call arguments, but it was passed " + "variable-length *args or **kwargs. The upgrade " + "script cannot handle these automatically." % + (full_name or name)) + + for transformer in transformers: + logs = [] + new_node = transformer(parent, node, full_name, name, logs) + self.add_logs(logs) + if new_node and new_node is not node: + pasta.ast_utils.replace_child(parent, node, new_node) + node = new_node + self._stack[-1] = node + + self.generic_visit(node) + + def visit_Attribute(self, node): # pylint: disable=invalid-name + """Handle bare Attributes i.e. [tf.foo, tf.bar].""" + assert self._stack[-1] is node + + full_name = self._get_full_name(node) + if full_name: + parent = self._stack[-2] + + # Make sure the warning comes first, otherwise the name may have changed + self._maybe_add_warning(node, full_name) + + # Once we did a modification, node is invalid and not worth inspecting + # further. Also, we only perform modifications for simple nodes, so + # There'd be no point in descending further. + if self._maybe_rename(parent, node, full_name): + return + if self._maybe_change_to_function_call(parent, node, full_name): + return + + # The isinstance check is enough -- a bare Attribute is never root. + i = 2 + while isinstance(self._stack[-i], ast.Attribute): + i += 1 + whole_name = pasta.dump(self._stack[-(i-1)]) + + self._maybe_add_module_deprecation_warning(node, full_name, whole_name) + + self.generic_visit(node) + + def visit_Import(self, node): # pylint: disable=invalid-name + """Handle visiting an import node in the AST. + + Args: + node: Current Node + """ + new_aliases = [] + import_updated = False + import_renames = getattr(self._api_change_spec, "import_renames", {}) + max_submodule_depth = getattr(self._api_change_spec, "max_submodule_depth", + 1) + inserts_after_imports = getattr(self._api_change_spec, + "inserts_after_imports", {}) + + # This loop processes imports in the format + # import foo as f, bar as b + for import_alias in node.names: + all_import_components = import_alias.name.split(".") + # Look for rename, starting with longest import levels. + found_update = False + for i in reversed(list(range(1, max_submodule_depth + 1))): + import_component = all_import_components[0] + for j in range(1, min(i, len(all_import_components))): + import_component += "." + all_import_components[j] + import_rename_spec = import_renames.get(import_component, None) + + if not import_rename_spec or excluded_from_module_rename( + import_alias.name, import_rename_spec): + continue + + new_name = ( + import_rename_spec.new_name + + import_alias.name[len(import_component):]) + + # If current import is + # import foo + # then new import should preserve imported name: + # import new_foo as foo + # This happens when module has just one component. + new_asname = import_alias.asname + if not new_asname and "." not in import_alias.name: + new_asname = import_alias.name + + new_alias = ast.alias(name=new_name, asname=new_asname) + new_aliases.append(new_alias) + import_updated = True + found_update = True + + # Insert any followup lines that should happen after this import. + full_import = (import_alias.name, import_alias.asname) + insert_offset = 1 + for line_to_insert in inserts_after_imports.get(full_import, []): + assert self._stack[-1] is node + parent = self._stack[-2] + + new_line_node = pasta.parse(line_to_insert) + ast.copy_location(new_line_node, node) + parent.body.insert( + parent.body.index(node) + insert_offset, new_line_node) + insert_offset += 1 + + # Insert a newline after the import if necessary + old_suffix = pasta.base.formatting.get(node, "suffix") + if old_suffix is None: + old_suffix = os.linesep + if os.linesep not in old_suffix: + pasta.base.formatting.set(node, "suffix", old_suffix + os.linesep) + + # Apply indentation to new node. + pasta.base.formatting.set(new_line_node, "prefix", + pasta.base.formatting.get(node, "prefix")) + pasta.base.formatting.set(new_line_node, "suffix", os.linesep) + self.add_log( + INFO, node.lineno, node.col_offset, + "Adding `%s` after import of %s" % + (new_line_node, import_alias.name)) + # Find one match, break + if found_update: + break + # No rename is found for all levels + if not found_update: + new_aliases.append(import_alias) # no change needed + + # Replace the node if at least one import needs to be updated. + if import_updated: + assert self._stack[-1] is node + parent = self._stack[-2] + + new_node = ast.Import(new_aliases) + ast.copy_location(new_node, node) + pasta.ast_utils.replace_child(parent, node, new_node) + self.add_log( + INFO, node.lineno, node.col_offset, + "Changed import from %r to %r." % + (pasta.dump(node), pasta.dump(new_node))) + + self.generic_visit(node) + + def visit_ImportFrom(self, node): # pylint: disable=invalid-name + """Handle visiting an import-from node in the AST. + + Args: + node: Current Node + """ + if not node.module: + self.generic_visit(node) + return + + from_import = node.module + + # Look for rename based on first component of from-import. + # i.e. based on foo in foo.bar. + from_import_first_component = from_import.split(".")[0] + import_renames = getattr(self._api_change_spec, "import_renames", {}) + import_rename_spec = import_renames.get(from_import_first_component, None) + if not import_rename_spec: + self.generic_visit(node) + return + + # Split module aliases into the ones that require import update + # and those that don't. For e.g. if we want to rename "a" to "b" + # unless we import "a.c" in the following: + # from a import c, d + # we want to update import for "d" but not for "c". + updated_aliases = [] + same_aliases = [] + for import_alias in node.names: + full_module_name = "%s.%s" % (from_import, import_alias.name) + if excluded_from_module_rename(full_module_name, import_rename_spec): + same_aliases.append(import_alias) + else: + updated_aliases.append(import_alias) + + if not updated_aliases: + self.generic_visit(node) + return + + assert self._stack[-1] is node + parent = self._stack[-2] + + # Replace first component of from-import with new name. + new_from_import = ( + import_rename_spec.new_name + + from_import[len(from_import_first_component):]) + updated_node = ast.ImportFrom(new_from_import, updated_aliases, node.level) + ast.copy_location(updated_node, node) + pasta.ast_utils.replace_child(parent, node, updated_node) + + # If some imports had to stay the same, add another import for them. + additional_import_log = "" + if same_aliases: + same_node = ast.ImportFrom(from_import, same_aliases, node.level, + col_offset=node.col_offset, lineno=node.lineno) + ast.copy_location(same_node, node) + parent.body.insert(parent.body.index(updated_node), same_node) + # Apply indentation to new node. + pasta.base.formatting.set( + same_node, "prefix", + pasta.base.formatting.get(updated_node, "prefix")) + additional_import_log = " and %r" % pasta.dump(same_node) + + self.add_log( + INFO, node.lineno, node.col_offset, + "Changed import from %r to %r%s." % + (pasta.dump(node), + pasta.dump(updated_node), + additional_import_log)) + + self.generic_visit(node) + + +class AnalysisResult: + """This class represents an analysis result and how it should be logged. + + This class must provide the following fields: + + * `log_level`: The log level to which this detection should be logged + * `log_message`: The message that should be logged for this detection + + For an example, see `VersionedTFImport`. + """ + + +class APIAnalysisSpec: + """This class defines how `AnalysisResult`s should be generated. + + It specifies how to map imports and symbols to `AnalysisResult`s. + + This class must provide the following fields: + + * `symbols_to_detect`: maps function names to `AnalysisResult`s + * `imports_to_detect`: maps imports represented as (full module name, alias) + tuples to `AnalysisResult`s + notifications) + + For an example, see `TFAPIImportAnalysisSpec`. + """ + + +class PastaAnalyzeVisitor(_PastaEditVisitor): + """AST Visitor that looks for specific API usage without editing anything. + + This is used before any rewriting is done to detect if any symbols are used + that require changing imports or disabling rewriting altogether. + """ + + def __init__(self, api_analysis_spec): + super(PastaAnalyzeVisitor, self).__init__(NoUpdateSpec()) + self._api_analysis_spec = api_analysis_spec + self._results = [] # Holds AnalysisResult objects + + @property + def results(self): + return self._results + + def add_result(self, analysis_result): + self._results.append(analysis_result) + + def visit_Attribute(self, node): # pylint: disable=invalid-name + """Handle bare Attributes i.e. [tf.foo, tf.bar].""" + full_name = self._get_full_name(node) + if full_name: + detection = self._api_analysis_spec.symbols_to_detect.get(full_name, None) + if detection: + self.add_result(detection) + self.add_log( + detection.log_level, node.lineno, node.col_offset, + detection.log_message) + + self.generic_visit(node) + + def visit_Import(self, node): # pylint: disable=invalid-name + """Handle visiting an import node in the AST. + + Args: + node: Current Node + """ + for import_alias in node.names: + # Detect based on full import name and alias) + full_import = (import_alias.name, import_alias.asname) + detection = (self._api_analysis_spec + .imports_to_detect.get(full_import, None)) + if detection: + self.add_result(detection) + self.add_log( + detection.log_level, node.lineno, node.col_offset, + detection.log_message) + + self.generic_visit(node) + + def visit_ImportFrom(self, node): # pylint: disable=invalid-name + """Handle visiting an import-from node in the AST. + + Args: + node: Current Node + """ + if not node.module: + self.generic_visit(node) + return + + from_import = node.module + + for import_alias in node.names: + # Detect based on full import name(to & as) + full_module_name = "%s.%s" % (from_import, import_alias.name) + full_import = (full_module_name, import_alias.asname) + detection = (self._api_analysis_spec + .imports_to_detect.get(full_import, None)) + if detection: + self.add_result(detection) + self.add_log( + detection.log_level, node.lineno, node.col_offset, + detection.log_message) + + self.generic_visit(node) + + +class ASTCodeUpgrader: + """Handles upgrading a set of Python files using a given API change spec.""" + + def __init__(self, api_change_spec): + if not isinstance(api_change_spec, APIChangeSpec): + raise TypeError("Must pass APIChangeSpec to ASTCodeUpgrader, got %s" % + type(api_change_spec)) + self._api_change_spec = api_change_spec + + def process_file(self, + in_filename, + out_filename, + no_change_to_outfile_on_error=False): + """Process the given python file for incompatible changes. + + Args: + in_filename: filename to parse + out_filename: output file to write to + no_change_to_outfile_on_error: not modify the output file on errors + Returns: + A tuple representing number of files processed, log of actions, errors + """ + + # Write to a temporary file, just in case we are doing an implace modify. + # pylint: disable=g-backslash-continuation + with open(in_filename, "r") as in_file, \ + tempfile.NamedTemporaryFile("w", delete=False) as temp_file: + ret = self.process_opened_file(in_filename, in_file, out_filename, + temp_file) + # pylint: enable=g-backslash-continuation + + if no_change_to_outfile_on_error and ret[0] == 0: + os.remove(temp_file.name) + else: + shutil.move(temp_file.name, out_filename) + return ret + + def format_log(self, log, in_filename): + log_string = "%d:%d: %s: %s" % (log[1], log[2], log[0], log[3]) + if in_filename: + return in_filename + ":" + log_string + else: + return log_string + + def update_string_pasta(self, text, in_filename): + """Updates a file using pasta.""" + try: + t = pasta.parse(text) + except (SyntaxError, ValueError, TypeError): + log = ["ERROR: Failed to parse.\n" + traceback.format_exc()] + return 0, "", log, [] + + t, preprocess_logs, preprocess_errors = self._api_change_spec.preprocess(t) + + visitor = _PastaEditVisitor(self._api_change_spec) + visitor.visit(t) + + self._api_change_spec.clear_preprocessing() + + logs = [self.format_log(log, None) for log in (preprocess_logs + + visitor.log)] + errors = [self.format_log(error, in_filename) + for error in (preprocess_errors + + visitor.warnings_and_errors)] + return 1, pasta.dump(t), logs, errors + + def _format_log(self, log, in_filename, out_filename): + text = "-" * 80 + "\n" + text += "Processing file %r\n outputting to %r\n" % (in_filename, + out_filename) + text += "-" * 80 + "\n\n" + text += "\n".join(log) + "\n" + text += "-" * 80 + "\n\n" + return text + + def process_opened_file(self, in_filename, in_file, out_filename, out_file): + """Process the given python file for incompatible changes. + + This function is split out to facilitate StringIO testing from + tf_upgrade_test.py. + + Args: + in_filename: filename to parse + in_file: opened file (or StringIO) + out_filename: output file to write to + out_file: opened file (or StringIO) + Returns: + A tuple representing number of files processed, log of actions, errors + """ + lines = in_file.readlines() + processed_file, new_file_content, log, process_errors = ( + self.update_string_pasta("".join(lines), in_filename)) + + if out_file and processed_file: + out_file.write(new_file_content) + + return (processed_file, + self._format_log(log, in_filename, out_filename), + process_errors) + + def process_tree(self, root_directory, output_root_directory, + copy_other_files): + """Processes upgrades on an entire tree of python files in place. + + Note that only Python files. If you have custom code in other languages, + you will need to manually upgrade those. + + Args: + root_directory: Directory to walk and process. + output_root_directory: Directory to use as base. + copy_other_files: Copy files that are not touched by this converter. + + Returns: + A tuple of files processed, the report string for all files, and a dict + mapping filenames to errors encountered in that file. + """ + + if output_root_directory == root_directory: + return self.process_tree_inplace(root_directory) + + # make sure output directory doesn't exist + if output_root_directory and os.path.exists(output_root_directory): + print("Output directory %r must not already exist." % + (output_root_directory)) + sys.exit(1) + + # make sure output directory does not overlap with root_directory + norm_root = os.path.split(os.path.normpath(root_directory)) + norm_output = os.path.split(os.path.normpath(output_root_directory)) + if norm_root == norm_output: + print("Output directory %r same as input directory %r" % + (root_directory, output_root_directory)) + sys.exit(1) + + # Collect list of files to process (we do this to correctly handle if the + # user puts the output directory in some sub directory of the input dir) + files_to_process = [] + files_to_copy = [] + for dir_name, _, file_list in os.walk(root_directory): + py_files = [f for f in file_list if f.endswith(".py")] + copy_files = [f for f in file_list if not f.endswith(".py")] + for filename in py_files: + fullpath = os.path.join(dir_name, filename) + fullpath_output = os.path.join(output_root_directory, + os.path.relpath(fullpath, + root_directory)) + files_to_process.append((fullpath, fullpath_output)) + if copy_other_files: + for filename in copy_files: + fullpath = os.path.join(dir_name, filename) + fullpath_output = os.path.join(output_root_directory, + os.path.relpath( + fullpath, root_directory)) + files_to_copy.append((fullpath, fullpath_output)) + + file_count = 0 + tree_errors = {} + report = "" + report += ("=" * 80) + "\n" + report += "Input tree: %r\n" % root_directory + report += ("=" * 80) + "\n" + + for input_path, output_path in files_to_process: + output_directory = os.path.dirname(output_path) + if not os.path.isdir(output_directory): + os.makedirs(output_directory) + + if os.path.islink(input_path): + link_target = os.readlink(input_path) + link_target_output = os.path.join( + output_root_directory, os.path.relpath(link_target, root_directory)) + if (link_target, link_target_output) in files_to_process: + # Create a link to the new location of the target file + os.symlink(link_target_output, output_path) + else: + report += "Copying symlink %s without modifying its target %s" % ( + input_path, link_target) + os.symlink(link_target, output_path) + continue + + file_count += 1 + _, l_report, l_errors = self.process_file(input_path, output_path) + tree_errors[input_path] = l_errors + report += l_report + + for input_path, output_path in files_to_copy: + output_directory = os.path.dirname(output_path) + if not os.path.isdir(output_directory): + os.makedirs(output_directory) + shutil.copy(input_path, output_path) + return file_count, report, tree_errors + + def process_tree_inplace(self, root_directory): + """Process a directory of python files in place.""" + files_to_process = [] + for dir_name, _, file_list in os.walk(root_directory): + py_files = [ + os.path.join(dir_name, f) for f in file_list if f.endswith(".py") + ] + files_to_process += py_files + + file_count = 0 + tree_errors = {} + report = "" + report += ("=" * 80) + "\n" + report += "Input tree: %r\n" % root_directory + report += ("=" * 80) + "\n" + + for path in files_to_process: + if os.path.islink(path): + report += "Skipping symlink %s.\n" % path + continue + file_count += 1 + _, l_report, l_errors = self.process_file(path, path) + tree_errors[path] = l_errors + report += l_report + + return file_count, report, tree_errors diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tools/compatibility/ipynb.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tools/compatibility/ipynb.py new file mode 100644 index 0000000000000000000000000000000000000000..c371baa73d8b1e667c83fb9f19b6759b44ef538b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tools/compatibility/ipynb.py @@ -0,0 +1,170 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================= +"""A module to support operations on ipynb files""" + +import collections +import copy +import json +import re +import shutil +import tempfile + +CodeLine = collections.namedtuple("CodeLine", ["cell_number", "code"]) + +def is_python(cell): + """Checks if the cell consists of Python code.""" + return (cell["cell_type"] == "code" # code cells only + and cell["source"] # non-empty cells + and not cell["source"][0].startswith("%%")) # multiline eg: %%bash + + +def process_file(in_filename, out_filename, upgrader): + """The function where we inject the support for ipynb upgrade.""" + print("Extracting code lines from original notebook") + raw_code, notebook = _get_code(in_filename) + raw_lines = [cl.code for cl in raw_code] + + # The function follows the original flow from `upgrader.process_fil` + with tempfile.NamedTemporaryFile("w", delete=False) as temp_file: + + processed_file, new_file_content, log, process_errors = ( + upgrader.update_string_pasta("\n".join(raw_lines), in_filename)) + + if temp_file and processed_file: + new_notebook = _update_notebook(notebook, raw_code, + new_file_content.split("\n")) + json.dump(new_notebook, temp_file) + else: + raise SyntaxError( + "Was not able to process the file: \n%s\n" % "".join(log)) + + files_processed = processed_file + report_text = upgrader._format_log(log, in_filename, out_filename) + errors = process_errors + + shutil.move(temp_file.name, out_filename) + + return files_processed, report_text, errors + + +def skip_magic(code_line, magic_list): + """Checks if the cell has magic, that is not Python-based. + + Args: + code_line: A line of Python code + magic_list: A list of jupyter "magic" exceptions + + Returns: + If the line jupyter "magic" line, not Python line + + >>> skip_magic('!ls -laF', ['%', '!', '?']) + True + """ + + for magic in magic_list: + if code_line.startswith(magic): + return True + + return False + + +def check_line_split(code_line): + r"""Checks if a line was split with `\`. + + Args: + code_line: A line of Python code + + Returns: + If the line was split with `\` + + >>> skip_magic("!gcloud ml-engine models create ${MODEL} \\\n") + True + """ + + return re.search(r"\\\s*\n$", code_line) + + +def _get_code(input_file): + """Loads the ipynb file and returns a list of CodeLines.""" + + raw_code = [] + + with open(input_file) as in_file: + notebook = json.load(in_file) + + cell_index = 0 + for cell in notebook["cells"]: + if is_python(cell): + cell_lines = cell["source"] + + is_line_split = False + for line_idx, code_line in enumerate(cell_lines): + + # Sometimes, jupyter has more than python code + # Idea is to comment these lines, for upgrade time + if skip_magic(code_line, ["%", "!", "?"]) or is_line_split: + # Found a special character, need to "encode" + code_line = "###!!!" + code_line + + # if this cell ends with `\` -> skip the next line + is_line_split = check_line_split(code_line) + + if is_line_split: + is_line_split = check_line_split(code_line) + + # Sometimes, people leave \n at the end of cell + # in order to migrate only related things, and make the diff + # the smallest -> here is another hack + if (line_idx == len(cell_lines) - 1) and code_line.endswith("\n"): + code_line = code_line.replace("\n", "###===") + + # sometimes a line would start with `\n` and content after + # that's the hack for this + raw_code.append( + CodeLine(cell_index, + code_line.rstrip().replace("\n", "###==="))) + + cell_index += 1 + + return raw_code, notebook + + +def _update_notebook(original_notebook, original_raw_lines, updated_code_lines): + """Updates notebook, once migration is done.""" + + new_notebook = copy.deepcopy(original_notebook) + + # validate that the number of lines is the same + assert len(original_raw_lines) == len(updated_code_lines), \ + ("The lengths of input and converted files are not the same: " + "{} vs {}".format(len(original_raw_lines), len(updated_code_lines))) + + code_cell_idx = 0 + for cell in new_notebook["cells"]: + if not is_python(cell): + continue + + applicable_lines = [ + idx for idx, code_line in enumerate(original_raw_lines) + if code_line.cell_number == code_cell_idx + ] + + new_code = [updated_code_lines[idx] for idx in applicable_lines] + + cell["source"] = "\n".join(new_code).replace("###!!!", "").replace( + "###===", "\n") + code_cell_idx += 1 + + return new_notebook diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tools/compatibility/module_deprecations_v2.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tools/compatibility/module_deprecations_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..3c647b3653c23ee21bef83a7f5c34c8a60245f29 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tools/compatibility/module_deprecations_v2.py @@ -0,0 +1,66 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Module deprecation warnings for TensorFlow 2.0.""" + +from tensorflow.tools.compatibility import ast_edits + + +_CONTRIB_WARNING = ( + ast_edits.ERROR, + " cannot be converted automatically. tf.contrib will not" + " be distributed with TensorFlow 2.0, please consider an alternative in" + " non-contrib TensorFlow, a community-maintained repository such as " + "tensorflow/addons, or fork the required code.") + +_FLAGS_WARNING = ( + ast_edits.ERROR, + "tf.flags and tf.app.flags have been removed, please use the argparse or " + "absl modules if you need command line parsing.") + +_CONTRIB_CUDNN_RNN_WARNING = ( + ast_edits.WARNING, + "(Manual edit required) tf.contrib.cudnn_rnn.* has been deprecated, " + "and the CuDNN kernel has been integrated with " + "tf.keras.layers.LSTM/GRU in TensorFlow 2.0. Please check the new API " + "and use that instead." +) + +_CONTRIB_RNN_WARNING = ( + ast_edits.WARNING, + "(Manual edit required) tf.contrib.rnn.* has been deprecated, and " + "widely used cells/functions will be moved to tensorflow/addons " + "repository. Please check it there and file Github issues if necessary." +) + +_CONTRIB_DIST_STRAT_WARNING = ( + ast_edits.WARNING, + "(Manual edit required) tf.contrib.distribute.* have been migrated to " + "tf.distribute.*. Please check out the new module for updated APIs.") + +_CONTRIB_SEQ2SEQ_WARNING = ( + ast_edits.WARNING, + "(Manual edit required) tf.contrib.seq2seq.* have been migrated to " + "`tfa.seq2seq.*` in TensorFlow Addons. Please see " + "https://github.com/tensorflow/addons for more info.") + +MODULE_DEPRECATIONS = { + "tf.contrib": _CONTRIB_WARNING, + "tf.contrib.cudnn_rnn": _CONTRIB_CUDNN_RNN_WARNING, + "tf.contrib.rnn": _CONTRIB_RNN_WARNING, + "tf.flags": _FLAGS_WARNING, + "tf.app.flags": _FLAGS_WARNING, + "tf.contrib.distribute": _CONTRIB_DIST_STRAT_WARNING, + "tf.contrib.seq2seq": _CONTRIB_SEQ2SEQ_WARNING +} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tools/compatibility/renames_v2.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tools/compatibility/renames_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..4067b091316801a0a98cb34800d35dce7a511b89 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tools/compatibility/renames_v2.py @@ -0,0 +1,1613 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +# pylint: disable=line-too-long +"""List of renames to apply when converting from TF 1.0 to TF 2.0. + +THIS FILE IS AUTOGENERATED: To update, please run: + bazel run tensorflow/tools/compatibility/update:generate_v2_renames_map +This file should be updated whenever endpoints are deprecated. +""" +renames = { + 'tf.AUTO_REUSE': + 'tf.compat.v1.AUTO_REUSE', + 'tf.AttrValue': + 'tf.compat.v1.AttrValue', + 'tf.COMPILER_VERSION': + 'tf.version.COMPILER_VERSION', + 'tf.CXX11_ABI_FLAG': + 'tf.sysconfig.CXX11_ABI_FLAG', + 'tf.CXX_VERSION': + 'tf.sysconfig.CXX_VERSION', + 'tf.ConditionalAccumulator': + 'tf.compat.v1.ConditionalAccumulator', + 'tf.ConditionalAccumulatorBase': + 'tf.compat.v1.ConditionalAccumulatorBase', + 'tf.ConfigProto': + 'tf.compat.v1.ConfigProto', + 'tf.Dimension': + 'tf.compat.v1.Dimension', + 'tf.Event': + 'tf.compat.v1.Event', + 'tf.FIFOQueue': + 'tf.queue.FIFOQueue', + 'tf.FixedLenFeature': + 'tf.io.FixedLenFeature', + 'tf.FixedLenSequenceFeature': + 'tf.io.FixedLenSequenceFeature', + 'tf.FixedLengthRecordReader': + 'tf.compat.v1.FixedLengthRecordReader', + 'tf.GIT_VERSION': + 'tf.version.GIT_VERSION', + 'tf.GPUOptions': + 'tf.compat.v1.GPUOptions', + 'tf.GRAPH_DEF_VERSION': + 'tf.version.GRAPH_DEF_VERSION', + 'tf.GRAPH_DEF_VERSION_MIN_CONSUMER': + 'tf.version.GRAPH_DEF_VERSION_MIN_CONSUMER', + 'tf.GRAPH_DEF_VERSION_MIN_PRODUCER': + 'tf.version.GRAPH_DEF_VERSION_MIN_PRODUCER', + 'tf.GraphDef': + 'tf.compat.v1.GraphDef', + 'tf.GraphKeys': + 'tf.compat.v1.GraphKeys', + 'tf.GraphOptions': + 'tf.compat.v1.GraphOptions', + 'tf.HistogramProto': + 'tf.compat.v1.HistogramProto', + 'tf.IdentityReader': + 'tf.compat.v1.IdentityReader', + 'tf.InteractiveSession': + 'tf.compat.v1.InteractiveSession', + 'tf.LMDBReader': + 'tf.compat.v1.LMDBReader', + 'tf.LogMessage': + 'tf.compat.v1.LogMessage', + 'tf.MONOLITHIC_BUILD': + 'tf.sysconfig.MONOLITHIC_BUILD', + 'tf.MetaGraphDef': + 'tf.compat.v1.MetaGraphDef', + 'tf.NameAttrList': + 'tf.compat.v1.NameAttrList', + 'tf.NoGradient': + 'tf.no_gradient', + 'tf.NodeDef': + 'tf.compat.v1.NodeDef', + 'tf.NotDifferentiable': + 'tf.no_gradient', + 'tf.OpError': + 'tf.errors.OpError', + 'tf.OptimizerOptions': + 'tf.compat.v1.OptimizerOptions', + 'tf.PaddingFIFOQueue': + 'tf.queue.PaddingFIFOQueue', + 'tf.Print': + 'tf.compat.v1.Print', + 'tf.PriorityQueue': + 'tf.queue.PriorityQueue', + 'tf.QUANTIZED_DTYPES': + 'tf.dtypes.QUANTIZED_DTYPES', + 'tf.QueueBase': + 'tf.queue.QueueBase', + 'tf.RandomShuffleQueue': + 'tf.queue.RandomShuffleQueue', + 'tf.ReaderBase': + 'tf.compat.v1.ReaderBase', + 'tf.RunMetadata': + 'tf.compat.v1.RunMetadata', + 'tf.RunOptions': + 'tf.compat.v1.RunOptions', + 'tf.Session': + 'tf.compat.v1.Session', + 'tf.SessionLog': + 'tf.compat.v1.SessionLog', + 'tf.SparseConditionalAccumulator': + 'tf.compat.v1.SparseConditionalAccumulator', + 'tf.SparseFeature': + 'tf.io.SparseFeature', + 'tf.SparseTensorValue': + 'tf.compat.v1.SparseTensorValue', + 'tf.Summary': + 'tf.compat.v1.Summary', + 'tf.SummaryMetadata': + 'tf.compat.v1.SummaryMetadata', + 'tf.TFRecordReader': + 'tf.compat.v1.TFRecordReader', + 'tf.TensorInfo': + 'tf.compat.v1.TensorInfo', + 'tf.TextLineReader': + 'tf.compat.v1.TextLineReader', + 'tf.VERSION': + 'tf.version.VERSION', + 'tf.VarLenFeature': + 'tf.io.VarLenFeature', + 'tf.VariableScope': + 'tf.compat.v1.VariableScope', + 'tf.WholeFileReader': + 'tf.compat.v1.WholeFileReader', + 'tf.accumulate_n': + 'tf.math.accumulate_n', + 'tf.add_check_numerics_ops': + 'tf.compat.v1.add_check_numerics_ops', + 'tf.add_to_collection': + 'tf.compat.v1.add_to_collection', + 'tf.add_to_collections': + 'tf.compat.v1.add_to_collections', + 'tf.all_variables': + 'tf.compat.v1.all_variables', + 'tf.angle': + 'tf.math.angle', + 'tf.app.run': + 'tf.compat.v1.app.run', + 'tf.assert_proper_iterable': + 'tf.debugging.assert_proper_iterable', + 'tf.assert_same_float_dtype': + 'tf.debugging.assert_same_float_dtype', + 'tf.assign': + 'tf.compat.v1.assign', + 'tf.assign_add': + 'tf.compat.v1.assign_add', + 'tf.assign_sub': + 'tf.compat.v1.assign_sub', + 'tf.batch_scatter_update': + 'tf.compat.v1.batch_scatter_update', + 'tf.betainc': + 'tf.math.betainc', + 'tf.ceil': + 'tf.math.ceil', + 'tf.check_numerics': + 'tf.debugging.check_numerics', + 'tf.cholesky': + 'tf.linalg.cholesky', + 'tf.cholesky_solve': + 'tf.linalg.cholesky_solve', + 'tf.clip_by_average_norm': + 'tf.compat.v1.clip_by_average_norm', + 'tf.colocate_with': + 'tf.compat.v1.colocate_with', + 'tf.conj': + 'tf.math.conj', + 'tf.container': + 'tf.compat.v1.container', + 'tf.control_flow_v2_enabled': + 'tf.compat.v1.control_flow_v2_enabled', + 'tf.convert_to_tensor_or_indexed_slices': + 'tf.compat.v1.convert_to_tensor_or_indexed_slices', + 'tf.convert_to_tensor_or_sparse_tensor': + 'tf.compat.v1.convert_to_tensor_or_sparse_tensor', + 'tf.count_up_to': + 'tf.compat.v1.count_up_to', + 'tf.create_partitioned_variables': + 'tf.compat.v1.create_partitioned_variables', + 'tf.cross': + 'tf.linalg.cross', + 'tf.cumprod': + 'tf.math.cumprod', + 'tf.data.get_output_classes': + 'tf.compat.v1.data.get_output_classes', + 'tf.data.get_output_shapes': + 'tf.compat.v1.data.get_output_shapes', + 'tf.data.get_output_types': + 'tf.compat.v1.data.get_output_types', + 'tf.data.make_initializable_iterator': + 'tf.compat.v1.data.make_initializable_iterator', + 'tf.data.make_one_shot_iterator': + 'tf.compat.v1.data.make_one_shot_iterator', + 'tf.debugging.is_finite': + 'tf.math.is_finite', + 'tf.debugging.is_inf': + 'tf.math.is_inf', + 'tf.debugging.is_nan': + 'tf.math.is_nan', + 'tf.debugging.is_non_decreasing': + 'tf.math.is_non_decreasing', + 'tf.debugging.is_strictly_increasing': + 'tf.math.is_strictly_increasing', + 'tf.decode_base64': + 'tf.io.decode_base64', + 'tf.decode_compressed': + 'tf.io.decode_compressed', + 'tf.decode_json_example': + 'tf.io.decode_json_example', + 'tf.delete_session_tensor': + 'tf.compat.v1.delete_session_tensor', + 'tf.depth_to_space': + 'tf.nn.depth_to_space', + 'tf.dequantize': + 'tf.quantization.dequantize', + 'tf.deserialize_many_sparse': + 'tf.io.deserialize_many_sparse', + 'tf.diag': + 'tf.linalg.tensor_diag', + 'tf.diag_part': + 'tf.linalg.tensor_diag_part', + 'tf.digamma': + 'tf.math.digamma', + 'tf.dimension_at_index': + 'tf.compat.dimension_at_index', + 'tf.dimension_value': + 'tf.compat.dimension_value', + 'tf.disable_control_flow_v2': + 'tf.compat.v1.disable_control_flow_v2', + 'tf.disable_eager_execution': + 'tf.compat.v1.disable_eager_execution', + 'tf.disable_resource_variables': + 'tf.compat.v1.disable_resource_variables', + 'tf.disable_tensor_equality': + 'tf.compat.v1.disable_tensor_equality', + 'tf.disable_v2_behavior': + 'tf.compat.v1.disable_v2_behavior', + 'tf.disable_v2_tensorshape': + 'tf.compat.v1.disable_v2_tensorshape', + 'tf.distribute.get_loss_reduction': + 'tf.compat.v1.distribute.get_loss_reduction', + 'tf.distributions.Bernoulli': + 'tf.compat.v1.distributions.Bernoulli', + 'tf.distributions.Beta': + 'tf.compat.v1.distributions.Beta', + 'tf.distributions.Categorical': + 'tf.compat.v1.distributions.Categorical', + 'tf.distributions.Dirichlet': + 'tf.compat.v1.distributions.Dirichlet', + 'tf.distributions.DirichletMultinomial': + 'tf.compat.v1.distributions.DirichletMultinomial', + 'tf.distributions.Distribution': + 'tf.compat.v1.distributions.Distribution', + 'tf.distributions.Exponential': + 'tf.compat.v1.distributions.Exponential', + 'tf.distributions.FULLY_REPARAMETERIZED': + 'tf.compat.v1.distributions.FULLY_REPARAMETERIZED', + 'tf.distributions.Gamma': + 'tf.compat.v1.distributions.Gamma', + 'tf.distributions.Laplace': + 'tf.compat.v1.distributions.Laplace', + 'tf.distributions.Multinomial': + 'tf.compat.v1.distributions.Multinomial', + 'tf.distributions.NOT_REPARAMETERIZED': + 'tf.compat.v1.distributions.NOT_REPARAMETERIZED', + 'tf.distributions.Normal': + 'tf.compat.v1.distributions.Normal', + 'tf.distributions.RegisterKL': + 'tf.compat.v1.distributions.RegisterKL', + 'tf.distributions.ReparameterizationType': + 'tf.compat.v1.distributions.ReparameterizationType', + 'tf.distributions.StudentT': + 'tf.compat.v1.distributions.StudentT', + 'tf.distributions.Uniform': + 'tf.compat.v1.distributions.Uniform', + 'tf.distributions.kl_divergence': + 'tf.compat.v1.distributions.kl_divergence', + 'tf.div': + 'tf.compat.v1.div', + 'tf.div_no_nan': + 'tf.math.divide_no_nan', + 'tf.dtypes.as_string': + 'tf.strings.as_string', + 'tf.enable_control_flow_v2': + 'tf.compat.v1.enable_control_flow_v2', + 'tf.enable_eager_execution': + 'tf.compat.v1.enable_eager_execution', + 'tf.enable_resource_variables': + 'tf.compat.v1.enable_resource_variables', + 'tf.enable_tensor_equality': + 'tf.compat.v1.enable_tensor_equality', + 'tf.enable_v2_behavior': + 'tf.compat.v1.enable_v2_behavior', + 'tf.enable_v2_tensorshape': + 'tf.compat.v1.enable_v2_tensorshape', + 'tf.encode_base64': + 'tf.io.encode_base64', + 'tf.erf': + 'tf.math.erf', + 'tf.erfc': + 'tf.math.erfc', + 'tf.estimator.experimental.KMeans': + 'tf.compat.v1.estimator.experimental.KMeans', + 'tf.estimator.experimental.dnn_logit_fn_builder': + 'tf.compat.v1.estimator.experimental.dnn_logit_fn_builder', + 'tf.estimator.experimental.linear_logit_fn_builder': + 'tf.compat.v1.estimator.experimental.linear_logit_fn_builder', + 'tf.estimator.inputs.numpy_input_fn': + 'tf.compat.v1.estimator.inputs.numpy_input_fn', + 'tf.estimator.inputs.pandas_input_fn': + 'tf.compat.v1.estimator.inputs.pandas_input_fn', + 'tf.estimator.tpu.InputPipelineConfig': + 'tf.compat.v1.estimator.tpu.InputPipelineConfig', + 'tf.estimator.tpu.RunConfig': + 'tf.compat.v1.estimator.tpu.RunConfig', + 'tf.estimator.tpu.TPUConfig': + 'tf.compat.v1.estimator.tpu.TPUConfig', + 'tf.estimator.tpu.TPUEstimator': + 'tf.compat.v1.estimator.tpu.TPUEstimator', + 'tf.estimator.tpu.TPUEstimatorSpec': + 'tf.compat.v1.estimator.tpu.TPUEstimatorSpec', + 'tf.estimator.tpu.experimental.EmbeddingConfigSpec': + 'tf.compat.v1.estimator.tpu.experimental.EmbeddingConfigSpec', + 'tf.executing_eagerly_outside_functions': + 'tf.compat.v1.executing_eagerly_outside_functions', + 'tf.experimental.output_all_intermediates': + 'tf.compat.v1.experimental.output_all_intermediates', + 'tf.expm1': + 'tf.math.expm1', + 'tf.fake_quant_with_min_max_args': + 'tf.quantization.fake_quant_with_min_max_args', + 'tf.fake_quant_with_min_max_args_gradient': + 'tf.quantization.fake_quant_with_min_max_args_gradient', + 'tf.fake_quant_with_min_max_vars': + 'tf.quantization.fake_quant_with_min_max_vars', + 'tf.fake_quant_with_min_max_vars_gradient': + 'tf.quantization.fake_quant_with_min_max_vars_gradient', + 'tf.fake_quant_with_min_max_vars_per_channel': + 'tf.quantization.fake_quant_with_min_max_vars_per_channel', + 'tf.fake_quant_with_min_max_vars_per_channel_gradient': + 'tf.quantization.fake_quant_with_min_max_vars_per_channel_gradient', + 'tf.feature_column.input_layer': + 'tf.compat.v1.feature_column.input_layer', + 'tf.feature_column.linear_model': + 'tf.compat.v1.feature_column.linear_model', + 'tf.feature_column.shared_embedding_columns': + 'tf.compat.v1.feature_column.shared_embedding_columns', + 'tf.fft': + 'tf.signal.fft', + 'tf.fft2d': + 'tf.signal.fft2d', + 'tf.fft3d': + 'tf.signal.fft3d', + 'tf.fixed_size_partitioner': + 'tf.compat.v1.fixed_size_partitioner', + 'tf.floordiv': + 'tf.math.floordiv', + 'tf.floormod': + 'tf.math.floormod', + 'tf.get_collection': + 'tf.compat.v1.get_collection', + 'tf.get_collection_ref': + 'tf.compat.v1.get_collection_ref', + 'tf.get_default_graph': + 'tf.compat.v1.get_default_graph', + 'tf.get_default_session': + 'tf.compat.v1.get_default_session', + 'tf.get_local_variable': + 'tf.compat.v1.get_local_variable', + 'tf.get_seed': + 'tf.compat.v1.get_seed', + 'tf.get_session_handle': + 'tf.compat.v1.get_session_handle', + 'tf.get_session_tensor': + 'tf.compat.v1.get_session_tensor', + 'tf.get_variable': + 'tf.compat.v1.get_variable', + 'tf.get_variable_scope': + 'tf.compat.v1.get_variable_scope', + 'tf.gfile.FastGFile': + 'tf.compat.v1.gfile.FastGFile', + 'tf.global_norm': + 'tf.linalg.global_norm', + 'tf.global_variables': + 'tf.compat.v1.global_variables', + 'tf.global_variables_initializer': + 'tf.compat.v1.global_variables_initializer', + 'tf.graph_util.convert_variables_to_constants': + 'tf.compat.v1.graph_util.convert_variables_to_constants', + 'tf.graph_util.extract_sub_graph': + 'tf.compat.v1.graph_util.extract_sub_graph', + 'tf.graph_util.must_run_on_cpu': + 'tf.compat.v1.graph_util.must_run_on_cpu', + 'tf.graph_util.remove_training_nodes': + 'tf.compat.v1.graph_util.remove_training_nodes', + 'tf.graph_util.tensor_shape_from_node_def_name': + 'tf.compat.v1.graph_util.tensor_shape_from_node_def_name', + 'tf.ifft': + 'tf.signal.ifft', + 'tf.ifft2d': + 'tf.signal.ifft2d', + 'tf.ifft3d': + 'tf.signal.ifft3d', + 'tf.igamma': + 'tf.math.igamma', + 'tf.igammac': + 'tf.math.igammac', + 'tf.imag': + 'tf.math.imag', + 'tf.image.resize_area': + 'tf.compat.v1.image.resize_area', + 'tf.image.resize_bicubic': + 'tf.compat.v1.image.resize_bicubic', + 'tf.image.resize_bilinear': + 'tf.compat.v1.image.resize_bilinear', + 'tf.image.resize_image_with_crop_or_pad': + 'tf.image.resize_with_crop_or_pad', + 'tf.image.resize_image_with_pad': + 'tf.compat.v1.image.resize_image_with_pad', + 'tf.image.resize_nearest_neighbor': + 'tf.compat.v1.image.resize_nearest_neighbor', + 'tf.image.transpose_image': + 'tf.image.transpose', + 'tf.initialize_all_tables': + 'tf.compat.v1.initialize_all_tables', + 'tf.initialize_all_variables': + 'tf.compat.v1.initialize_all_variables', + 'tf.initialize_local_variables': + 'tf.compat.v1.initialize_local_variables', + 'tf.initialize_variables': + 'tf.compat.v1.initialize_variables', + 'tf.initializers.global_variables': + 'tf.compat.v1.initializers.global_variables', + 'tf.initializers.local_variables': + 'tf.compat.v1.initializers.local_variables', + 'tf.initializers.tables_initializer': + 'tf.compat.v1.initializers.tables_initializer', + 'tf.initializers.uniform_unit_scaling': + 'tf.compat.v1.initializers.uniform_unit_scaling', + 'tf.initializers.variables': + 'tf.compat.v1.initializers.variables', + 'tf.invert_permutation': + 'tf.math.invert_permutation', + 'tf.io.PaddingFIFOQueue': + 'tf.queue.PaddingFIFOQueue', + 'tf.io.PriorityQueue': + 'tf.queue.PriorityQueue', + 'tf.io.QueueBase': + 'tf.queue.QueueBase', + 'tf.io.RandomShuffleQueue': + 'tf.queue.RandomShuffleQueue', + 'tf.io.TFRecordCompressionType': + 'tf.compat.v1.io.TFRecordCompressionType', + 'tf.io.tf_record_iterator': + 'tf.compat.v1.io.tf_record_iterator', + 'tf.is_finite': + 'tf.math.is_finite', + 'tf.is_inf': + 'tf.math.is_inf', + 'tf.is_nan': + 'tf.math.is_nan', + 'tf.is_non_decreasing': + 'tf.math.is_non_decreasing', + 'tf.is_numeric_tensor': + 'tf.debugging.is_numeric_tensor', + 'tf.is_strictly_increasing': + 'tf.math.is_strictly_increasing', + 'tf.is_variable_initialized': + 'tf.compat.v1.is_variable_initialized', + 'tf.keras.backend.get_session': + 'tf.compat.v1.keras.backend.get_session', + 'tf.keras.backend.set_session': + 'tf.compat.v1.keras.backend.set_session', + 'tf.keras.layers.CuDNNGRU': + 'tf.compat.v1.keras.layers.CuDNNGRU', + 'tf.keras.layers.CuDNNLSTM': + 'tf.compat.v1.keras.layers.CuDNNLSTM', + 'tf.keras.layers.disable_v2_dtype_behavior': + 'tf.compat.v1.keras.layers.disable_v2_dtype_behavior', + 'tf.keras.layers.enable_v2_dtype_behavior': + 'tf.compat.v1.keras.layers.enable_v2_dtype_behavior', + 'tf.keras.losses.cosine': + 'tf.keras.losses.cosine_similarity', + 'tf.keras.losses.cosine_proximity': + 'tf.keras.losses.cosine_similarity', + 'tf.keras.metrics.cosine': + 'tf.keras.losses.cosine_similarity', + 'tf.keras.metrics.cosine_proximity': + 'tf.keras.losses.cosine_similarity', + 'tf.keras.models.LinearModel': + 'tf.keras.experimental.LinearModel', + 'tf.keras.models.WideDeepModel': + 'tf.keras.experimental.WideDeepModel', + 'tf.keras.optimizers.Adadelta': + 'tf.keras.optimizers.legacy.Adadelta', + 'tf.keras.optimizers.Adagrad': + 'tf.keras.optimizers.legacy.Adagrad', + 'tf.keras.optimizers.Adam': + 'tf.keras.optimizers.legacy.Adam', + 'tf.keras.optimizers.Adamax': + 'tf.keras.optimizers.legacy.Adamax', + 'tf.keras.optimizers.Ftrl': + 'tf.keras.optimizers.legacy.Ftrl', + 'tf.keras.optimizers.Nadam': + 'tf.keras.optimizers.legacy.Nadam', + 'tf.keras.optimizers.Optimizer': + 'tf.keras.optimizers.legacy.Optimizer', + 'tf.keras.optimizers.RMSprop': + 'tf.keras.optimizers.legacy.RMSprop', + 'tf.keras.optimizers.SGD': + 'tf.keras.optimizers.legacy.SGD', + 'tf.keras.utils.DeterministicRandomTestTool': + 'tf.compat.v1.keras.utils.DeterministicRandomTestTool', + 'tf.keras.utils.get_or_create_layer': + 'tf.compat.v1.keras.utils.get_or_create_layer', + 'tf.keras.utils.track_tf1_style_variables': + 'tf.compat.v1.keras.utils.track_tf1_style_variables', + 'tf.layers.AveragePooling1D': + 'tf.compat.v1.layers.AveragePooling1D', + 'tf.layers.AveragePooling2D': + 'tf.compat.v1.layers.AveragePooling2D', + 'tf.layers.AveragePooling3D': + 'tf.compat.v1.layers.AveragePooling3D', + 'tf.layers.BatchNormalization': + 'tf.compat.v1.layers.BatchNormalization', + 'tf.layers.Conv1D': + 'tf.compat.v1.layers.Conv1D', + 'tf.layers.Conv2D': + 'tf.compat.v1.layers.Conv2D', + 'tf.layers.Conv2DTranspose': + 'tf.compat.v1.layers.Conv2DTranspose', + 'tf.layers.Conv3D': + 'tf.compat.v1.layers.Conv3D', + 'tf.layers.Conv3DTranspose': + 'tf.compat.v1.layers.Conv3DTranspose', + 'tf.layers.Dense': + 'tf.compat.v1.layers.Dense', + 'tf.layers.Dropout': + 'tf.compat.v1.layers.Dropout', + 'tf.layers.Flatten': + 'tf.compat.v1.layers.Flatten', + 'tf.layers.InputSpec': + 'tf.keras.layers.InputSpec', + 'tf.layers.Layer': + 'tf.compat.v1.layers.Layer', + 'tf.layers.MaxPooling1D': + 'tf.compat.v1.layers.MaxPooling1D', + 'tf.layers.MaxPooling2D': + 'tf.compat.v1.layers.MaxPooling2D', + 'tf.layers.MaxPooling3D': + 'tf.compat.v1.layers.MaxPooling3D', + 'tf.layers.SeparableConv1D': + 'tf.compat.v1.layers.SeparableConv1D', + 'tf.layers.SeparableConv2D': + 'tf.compat.v1.layers.SeparableConv2D', + 'tf.layers.average_pooling1d': + 'tf.compat.v1.layers.average_pooling1d', + 'tf.layers.average_pooling2d': + 'tf.compat.v1.layers.average_pooling2d', + 'tf.layers.average_pooling3d': + 'tf.compat.v1.layers.average_pooling3d', + 'tf.layers.batch_normalization': + 'tf.compat.v1.layers.batch_normalization', + 'tf.layers.conv1d': + 'tf.compat.v1.layers.conv1d', + 'tf.layers.conv2d': + 'tf.compat.v1.layers.conv2d', + 'tf.layers.conv2d_transpose': + 'tf.compat.v1.layers.conv2d_transpose', + 'tf.layers.conv3d': + 'tf.compat.v1.layers.conv3d', + 'tf.layers.conv3d_transpose': + 'tf.compat.v1.layers.conv3d_transpose', + 'tf.layers.dense': + 'tf.compat.v1.layers.dense', + 'tf.layers.dropout': + 'tf.compat.v1.layers.dropout', + 'tf.layers.experimental.keras_style_scope': + 'tf.compat.v1.layers.experimental.keras_style_scope', + 'tf.layers.experimental.set_keras_style': + 'tf.compat.v1.layers.experimental.set_keras_style', + 'tf.layers.flatten': + 'tf.compat.v1.layers.flatten', + 'tf.layers.max_pooling1d': + 'tf.compat.v1.layers.max_pooling1d', + 'tf.layers.max_pooling2d': + 'tf.compat.v1.layers.max_pooling2d', + 'tf.layers.max_pooling3d': + 'tf.compat.v1.layers.max_pooling3d', + 'tf.layers.separable_conv1d': + 'tf.compat.v1.layers.separable_conv1d', + 'tf.layers.separable_conv2d': + 'tf.compat.v1.layers.separable_conv2d', + 'tf.lbeta': + 'tf.math.lbeta', + 'tf.lgamma': + 'tf.math.lgamma', + 'tf.lin_space': + 'tf.linspace', + 'tf.linalg.transpose': + 'tf.linalg.matrix_transpose', + 'tf.lite.OpHint': + 'tf.compat.v1.lite.OpHint', + 'tf.lite.TocoConverter': + 'tf.compat.v1.lite.TocoConverter', + 'tf.lite.constants.GRAPHVIZ_DOT': + 'tf.compat.v1.lite.constants.GRAPHVIZ_DOT', + 'tf.lite.constants.TFLITE': + 'tf.compat.v1.lite.constants.TFLITE', + 'tf.lite.experimental.convert_op_hints_to_stubs': + 'tf.compat.v1.lite.experimental.convert_op_hints_to_stubs', + 'tf.lite.toco_convert': + 'tf.compat.v1.lite.toco_convert', + 'tf.local_variables': + 'tf.compat.v1.local_variables', + 'tf.local_variables_initializer': + 'tf.compat.v1.local_variables_initializer', + 'tf.log': + 'tf.math.log', + 'tf.log1p': + 'tf.math.log1p', + 'tf.log_sigmoid': + 'tf.math.log_sigmoid', + 'tf.logging.DEBUG': + 'tf.compat.v1.logging.DEBUG', + 'tf.logging.ERROR': + 'tf.compat.v1.logging.ERROR', + 'tf.logging.FATAL': + 'tf.compat.v1.logging.FATAL', + 'tf.logging.INFO': + 'tf.compat.v1.logging.INFO', + 'tf.logging.TaskLevelStatusMessage': + 'tf.compat.v1.logging.TaskLevelStatusMessage', + 'tf.logging.WARN': + 'tf.compat.v1.logging.WARN', + 'tf.logging.debug': + 'tf.compat.v1.logging.debug', + 'tf.logging.error': + 'tf.compat.v1.logging.error', + 'tf.logging.fatal': + 'tf.compat.v1.logging.fatal', + 'tf.logging.flush': + 'tf.compat.v1.logging.flush', + 'tf.logging.get_verbosity': + 'tf.compat.v1.logging.get_verbosity', + 'tf.logging.info': + 'tf.compat.v1.logging.info', + 'tf.logging.log': + 'tf.compat.v1.logging.log', + 'tf.logging.log_every_n': + 'tf.compat.v1.logging.log_every_n', + 'tf.logging.log_first_n': + 'tf.compat.v1.logging.log_first_n', + 'tf.logging.log_if': + 'tf.compat.v1.logging.log_if', + 'tf.logging.set_verbosity': + 'tf.compat.v1.logging.set_verbosity', + 'tf.logging.vlog': + 'tf.compat.v1.logging.vlog', + 'tf.logging.warn': + 'tf.compat.v1.logging.warn', + 'tf.logging.warning': + 'tf.compat.v1.logging.warning', + 'tf.logical_xor': + 'tf.math.logical_xor', + 'tf.losses.Reduction': + 'tf.compat.v1.losses.Reduction', + 'tf.losses.absolute_difference': + 'tf.compat.v1.losses.absolute_difference', + 'tf.losses.add_loss': + 'tf.compat.v1.losses.add_loss', + 'tf.losses.compute_weighted_loss': + 'tf.compat.v1.losses.compute_weighted_loss', + 'tf.losses.cosine_distance': + 'tf.compat.v1.losses.cosine_distance', + 'tf.losses.get_losses': + 'tf.compat.v1.losses.get_losses', + 'tf.losses.get_regularization_loss': + 'tf.compat.v1.losses.get_regularization_loss', + 'tf.losses.get_regularization_losses': + 'tf.compat.v1.losses.get_regularization_losses', + 'tf.losses.get_total_loss': + 'tf.compat.v1.losses.get_total_loss', + 'tf.losses.hinge_loss': + 'tf.compat.v1.losses.hinge_loss', + 'tf.losses.huber_loss': + 'tf.compat.v1.losses.huber_loss', + 'tf.losses.log_loss': + 'tf.compat.v1.losses.log_loss', + 'tf.losses.mean_pairwise_squared_error': + 'tf.compat.v1.losses.mean_pairwise_squared_error', + 'tf.losses.mean_squared_error': + 'tf.compat.v1.losses.mean_squared_error', + 'tf.losses.sigmoid_cross_entropy': + 'tf.compat.v1.losses.sigmoid_cross_entropy', + 'tf.losses.softmax_cross_entropy': + 'tf.compat.v1.losses.softmax_cross_entropy', + 'tf.losses.sparse_softmax_cross_entropy': + 'tf.compat.v1.losses.sparse_softmax_cross_entropy', + 'tf.make_template': + 'tf.compat.v1.make_template', + 'tf.manip.gather_nd': + 'tf.gather_nd', + 'tf.manip.reshape': + 'tf.reshape', + 'tf.manip.reverse': + 'tf.reverse', + 'tf.manip.roll': + 'tf.roll', + 'tf.manip.scatter_nd': + 'tf.scatter_nd', + 'tf.manip.space_to_batch_nd': + 'tf.space_to_batch_nd', + 'tf.manip.tile': + 'tf.tile', + 'tf.matching_files': + 'tf.io.matching_files', + 'tf.matrix_band_part': + 'tf.linalg.band_part', + 'tf.matrix_determinant': + 'tf.linalg.det', + 'tf.matrix_diag': + 'tf.linalg.diag', + 'tf.matrix_diag_part': + 'tf.linalg.diag_part', + 'tf.matrix_inverse': + 'tf.linalg.inv', + 'tf.matrix_set_diag': + 'tf.linalg.set_diag', + 'tf.matrix_solve': + 'tf.linalg.solve', + 'tf.matrix_solve_ls': + 'tf.linalg.lstsq', + 'tf.matrix_transpose': + 'tf.linalg.matrix_transpose', + 'tf.matrix_triangular_solve': + 'tf.linalg.triangular_solve', + 'tf.metrics.accuracy': + 'tf.compat.v1.metrics.accuracy', + 'tf.metrics.auc': + 'tf.compat.v1.metrics.auc', + 'tf.metrics.average_precision_at_k': + 'tf.compat.v1.metrics.average_precision_at_k', + 'tf.metrics.false_negatives': + 'tf.compat.v1.metrics.false_negatives', + 'tf.metrics.false_negatives_at_thresholds': + 'tf.compat.v1.metrics.false_negatives_at_thresholds', + 'tf.metrics.false_positives': + 'tf.compat.v1.metrics.false_positives', + 'tf.metrics.false_positives_at_thresholds': + 'tf.compat.v1.metrics.false_positives_at_thresholds', + 'tf.metrics.mean': + 'tf.compat.v1.metrics.mean', + 'tf.metrics.mean_absolute_error': + 'tf.compat.v1.metrics.mean_absolute_error', + 'tf.metrics.mean_cosine_distance': + 'tf.compat.v1.metrics.mean_cosine_distance', + 'tf.metrics.mean_iou': + 'tf.compat.v1.metrics.mean_iou', + 'tf.metrics.mean_per_class_accuracy': + 'tf.compat.v1.metrics.mean_per_class_accuracy', + 'tf.metrics.mean_relative_error': + 'tf.compat.v1.metrics.mean_relative_error', + 'tf.metrics.mean_squared_error': + 'tf.compat.v1.metrics.mean_squared_error', + 'tf.metrics.mean_tensor': + 'tf.compat.v1.metrics.mean_tensor', + 'tf.metrics.percentage_below': + 'tf.compat.v1.metrics.percentage_below', + 'tf.metrics.precision': + 'tf.compat.v1.metrics.precision', + 'tf.metrics.precision_at_k': + 'tf.compat.v1.metrics.precision_at_k', + 'tf.metrics.precision_at_thresholds': + 'tf.compat.v1.metrics.precision_at_thresholds', + 'tf.metrics.precision_at_top_k': + 'tf.compat.v1.metrics.precision_at_top_k', + 'tf.metrics.recall': + 'tf.compat.v1.metrics.recall', + 'tf.metrics.recall_at_k': + 'tf.compat.v1.metrics.recall_at_k', + 'tf.metrics.recall_at_thresholds': + 'tf.compat.v1.metrics.recall_at_thresholds', + 'tf.metrics.recall_at_top_k': + 'tf.compat.v1.metrics.recall_at_top_k', + 'tf.metrics.root_mean_squared_error': + 'tf.compat.v1.metrics.root_mean_squared_error', + 'tf.metrics.sensitivity_at_specificity': + 'tf.compat.v1.metrics.sensitivity_at_specificity', + 'tf.metrics.sparse_average_precision_at_k': + 'tf.compat.v1.metrics.sparse_average_precision_at_k', + 'tf.metrics.sparse_precision_at_k': + 'tf.compat.v1.metrics.sparse_precision_at_k', + 'tf.metrics.specificity_at_sensitivity': + 'tf.compat.v1.metrics.specificity_at_sensitivity', + 'tf.metrics.true_negatives': + 'tf.compat.v1.metrics.true_negatives', + 'tf.metrics.true_negatives_at_thresholds': + 'tf.compat.v1.metrics.true_negatives_at_thresholds', + 'tf.metrics.true_positives': + 'tf.compat.v1.metrics.true_positives', + 'tf.metrics.true_positives_at_thresholds': + 'tf.compat.v1.metrics.true_positives_at_thresholds', + 'tf.min_max_variable_partitioner': + 'tf.compat.v1.min_max_variable_partitioner', + 'tf.mixed_precision.DynamicLossScale': + 'tf.compat.v1.mixed_precision.DynamicLossScale', + 'tf.mixed_precision.FixedLossScale': + 'tf.compat.v1.mixed_precision.FixedLossScale', + 'tf.mixed_precision.LossScale': + 'tf.compat.v1.mixed_precision.LossScale', + 'tf.mixed_precision.MixedPrecisionLossScaleOptimizer': + 'tf.compat.v1.mixed_precision.MixedPrecisionLossScaleOptimizer', + 'tf.mixed_precision.disable_mixed_precision_graph_rewrite': + 'tf.compat.v1.mixed_precision.disable_mixed_precision_graph_rewrite', + 'tf.mixed_precision.enable_mixed_precision_graph_rewrite': + 'tf.compat.v1.mixed_precision.enable_mixed_precision_graph_rewrite', + 'tf.mixed_precision.experimental.DynamicLossScale': + 'tf.compat.v1.mixed_precision.experimental.DynamicLossScale', + 'tf.mixed_precision.experimental.FixedLossScale': + 'tf.compat.v1.mixed_precision.experimental.FixedLossScale', + 'tf.mixed_precision.experimental.LossScale': + 'tf.compat.v1.mixed_precision.experimental.LossScale', + 'tf.mod': + 'tf.math.floormod', + 'tf.model_variables': + 'tf.compat.v1.model_variables', + 'tf.moving_average_variables': + 'tf.compat.v1.moving_average_variables', + 'tf.nn.avg_pool_v2': + 'tf.nn.avg_pool', + 'tf.nn.bidirectional_dynamic_rnn': + 'tf.compat.v1.nn.bidirectional_dynamic_rnn', + 'tf.nn.conv2d_backprop_filter': + 'tf.compat.v1.nn.conv2d_backprop_filter', + 'tf.nn.conv3d_backprop_filter': + 'tf.compat.v1.nn.conv3d_backprop_filter', + 'tf.nn.conv3d_backprop_filter_v2': + 'tf.compat.v1.nn.conv3d_backprop_filter_v2', + 'tf.nn.ctc_beam_search_decoder_v2': + 'tf.nn.ctc_beam_search_decoder', + 'tf.nn.ctc_loss_v2': + 'tf.compat.v1.nn.ctc_loss_v2', + 'tf.nn.depthwise_conv2d_native': + 'tf.compat.v1.nn.depthwise_conv2d_native', + 'tf.nn.depthwise_conv2d_native_backprop_filter': + 'tf.nn.depthwise_conv2d_backprop_filter', + 'tf.nn.depthwise_conv2d_native_backprop_input': + 'tf.nn.depthwise_conv2d_backprop_input', + 'tf.nn.dynamic_rnn': + 'tf.compat.v1.nn.dynamic_rnn', + 'tf.nn.log_uniform_candidate_sampler': + 'tf.random.log_uniform_candidate_sampler', + 'tf.nn.max_pool_v2': + 'tf.nn.max_pool', + 'tf.nn.quantized_avg_pool': + 'tf.compat.v1.nn.quantized_avg_pool', + 'tf.nn.quantized_conv2d': + 'tf.compat.v1.nn.quantized_conv2d', + 'tf.nn.quantized_max_pool': + 'tf.compat.v1.nn.quantized_max_pool', + 'tf.nn.quantized_relu_x': + 'tf.compat.v1.nn.quantized_relu_x', + 'tf.nn.raw_rnn': + 'tf.compat.v1.nn.raw_rnn', + 'tf.nn.relu_layer': + 'tf.compat.v1.nn.relu_layer', + 'tf.nn.rnn_cell.BasicLSTMCell': + 'tf.compat.v1.nn.rnn_cell.BasicLSTMCell', + 'tf.nn.rnn_cell.BasicRNNCell': + 'tf.compat.v1.nn.rnn_cell.BasicRNNCell', + 'tf.nn.rnn_cell.DeviceWrapper': + 'tf.compat.v1.nn.rnn_cell.DeviceWrapper', + 'tf.nn.rnn_cell.DropoutWrapper': + 'tf.compat.v1.nn.rnn_cell.DropoutWrapper', + 'tf.nn.rnn_cell.GRUCell': + 'tf.compat.v1.nn.rnn_cell.GRUCell', + 'tf.nn.rnn_cell.LSTMCell': + 'tf.compat.v1.nn.rnn_cell.LSTMCell', + 'tf.nn.rnn_cell.LSTMStateTuple': + 'tf.compat.v1.nn.rnn_cell.LSTMStateTuple', + 'tf.nn.rnn_cell.MultiRNNCell': + 'tf.compat.v1.nn.rnn_cell.MultiRNNCell', + 'tf.nn.rnn_cell.RNNCell': + 'tf.compat.v1.nn.rnn_cell.RNNCell', + 'tf.nn.rnn_cell.ResidualWrapper': + 'tf.compat.v1.nn.rnn_cell.ResidualWrapper', + 'tf.nn.static_bidirectional_rnn': + 'tf.compat.v1.nn.static_bidirectional_rnn', + 'tf.nn.static_rnn': + 'tf.compat.v1.nn.static_rnn', + 'tf.nn.static_state_saving_rnn': + 'tf.compat.v1.nn.static_state_saving_rnn', + 'tf.nn.uniform_candidate_sampler': + 'tf.random.uniform_candidate_sampler', + 'tf.nn.xw_plus_b': + 'tf.compat.v1.nn.xw_plus_b', + 'tf.no_regularizer': + 'tf.compat.v1.no_regularizer', + 'tf.op_scope': + 'tf.compat.v1.op_scope', + 'tf.parse_single_sequence_example': + 'tf.io.parse_single_sequence_example', + 'tf.parse_tensor': + 'tf.io.parse_tensor', + 'tf.placeholder': + 'tf.compat.v1.placeholder', + 'tf.placeholder_with_default': + 'tf.compat.v1.placeholder_with_default', + 'tf.polygamma': + 'tf.math.polygamma', + 'tf.profiler.AdviceProto': + 'tf.compat.v1.profiler.AdviceProto', + 'tf.profiler.GraphNodeProto': + 'tf.compat.v1.profiler.GraphNodeProto', + 'tf.profiler.MultiGraphNodeProto': + 'tf.compat.v1.profiler.MultiGraphNodeProto', + 'tf.profiler.OpLogProto': + 'tf.compat.v1.profiler.OpLogProto', + 'tf.profiler.ProfileOptionBuilder': + 'tf.compat.v1.profiler.ProfileOptionBuilder', + 'tf.profiler.Profiler': + 'tf.compat.v1.profiler.Profiler', + 'tf.profiler.advise': + 'tf.compat.v1.profiler.advise', + 'tf.profiler.profile': + 'tf.compat.v1.profiler.profile', + 'tf.profiler.write_op_log': + 'tf.compat.v1.profiler.write_op_log', + 'tf.py_func': + 'tf.compat.v1.py_func', + 'tf.python_io.TFRecordCompressionType': + 'tf.compat.v1.python_io.TFRecordCompressionType', + 'tf.python_io.TFRecordOptions': + 'tf.io.TFRecordOptions', + 'tf.python_io.TFRecordWriter': + 'tf.io.TFRecordWriter', + 'tf.python_io.tf_record_iterator': + 'tf.compat.v1.python_io.tf_record_iterator', + 'tf.qr': + 'tf.linalg.qr', + 'tf.quantize': + 'tf.quantization.quantize', + 'tf.quantized_concat': + 'tf.quantization.quantized_concat', + 'tf.ragged.RaggedTensorValue': + 'tf.compat.v1.ragged.RaggedTensorValue', + 'tf.ragged.constant_value': + 'tf.compat.v1.ragged.constant_value', + 'tf.ragged.placeholder': + 'tf.compat.v1.ragged.placeholder', + 'tf.random.get_seed': + 'tf.compat.v1.random.get_seed', + 'tf.random.set_random_seed': + 'tf.compat.v1.random.set_random_seed', + 'tf.random_crop': + 'tf.image.random_crop', + 'tf.random_gamma': + 'tf.random.gamma', + 'tf.random_normal': + 'tf.random.normal', + 'tf.random_poisson': + 'tf.random.poisson', + 'tf.random_shuffle': + 'tf.random.shuffle', + 'tf.random_uniform': + 'tf.random.uniform', + 'tf.read_file': + 'tf.io.read_file', + 'tf.real': + 'tf.math.real', + 'tf.reciprocal': + 'tf.math.reciprocal', + 'tf.regex_replace': + 'tf.strings.regex_replace', + 'tf.report_uninitialized_variables': + 'tf.compat.v1.report_uninitialized_variables', + 'tf.reset_default_graph': + 'tf.compat.v1.reset_default_graph', + 'tf.resource_loader.get_data_files_path': + 'tf.compat.v1.resource_loader.get_data_files_path', + 'tf.resource_loader.get_path_to_datafile': + 'tf.compat.v1.resource_loader.get_path_to_datafile', + 'tf.resource_loader.get_root_dir_with_all_resources': + 'tf.compat.v1.resource_loader.get_root_dir_with_all_resources', + 'tf.resource_loader.load_resource': + 'tf.compat.v1.resource_loader.load_resource', + 'tf.resource_loader.readahead_file_path': + 'tf.compat.v1.resource_loader.readahead_file_path', + 'tf.resource_variables_enabled': + 'tf.compat.v1.resource_variables_enabled', + 'tf.reverse_v2': + 'tf.reverse', + 'tf.rint': + 'tf.math.rint', + 'tf.rsqrt': + 'tf.math.rsqrt', + 'tf.saved_model.Builder': + 'tf.compat.v1.saved_model.Builder', + 'tf.saved_model.LEGACY_INIT_OP_KEY': + 'tf.compat.v1.saved_model.LEGACY_INIT_OP_KEY', + 'tf.saved_model.MAIN_OP_KEY': + 'tf.compat.v1.saved_model.MAIN_OP_KEY', + 'tf.saved_model.build_signature_def': + 'tf.compat.v1.saved_model.build_signature_def', + 'tf.saved_model.build_tensor_info': + 'tf.compat.v1.saved_model.build_tensor_info', + 'tf.saved_model.builder.SavedModelBuilder': + 'tf.compat.v1.saved_model.builder.SavedModelBuilder', + 'tf.saved_model.classification_signature_def': + 'tf.compat.v1.saved_model.classification_signature_def', + 'tf.saved_model.constants.ASSETS_DIRECTORY': + 'tf.saved_model.ASSETS_DIRECTORY', + 'tf.saved_model.constants.ASSETS_KEY': + 'tf.saved_model.ASSETS_KEY', + 'tf.saved_model.constants.DEBUG_DIRECTORY': + 'tf.saved_model.DEBUG_DIRECTORY', + 'tf.saved_model.constants.DEBUG_INFO_FILENAME_PB': + 'tf.saved_model.DEBUG_INFO_FILENAME_PB', + 'tf.saved_model.constants.LEGACY_INIT_OP_KEY': + 'tf.compat.v1.saved_model.constants.LEGACY_INIT_OP_KEY', + 'tf.saved_model.constants.MAIN_OP_KEY': + 'tf.compat.v1.saved_model.constants.MAIN_OP_KEY', + 'tf.saved_model.constants.SAVED_MODEL_FILENAME_PB': + 'tf.saved_model.SAVED_MODEL_FILENAME_PB', + 'tf.saved_model.constants.SAVED_MODEL_FILENAME_PBTXT': + 'tf.saved_model.SAVED_MODEL_FILENAME_PBTXT', + 'tf.saved_model.constants.SAVED_MODEL_SCHEMA_VERSION': + 'tf.saved_model.SAVED_MODEL_SCHEMA_VERSION', + 'tf.saved_model.constants.VARIABLES_DIRECTORY': + 'tf.saved_model.VARIABLES_DIRECTORY', + 'tf.saved_model.constants.VARIABLES_FILENAME': + 'tf.saved_model.VARIABLES_FILENAME', + 'tf.saved_model.experimental.save': + 'tf.saved_model.save', + 'tf.saved_model.get_tensor_from_tensor_info': + 'tf.compat.v1.saved_model.get_tensor_from_tensor_info', + 'tf.saved_model.is_valid_signature': + 'tf.compat.v1.saved_model.is_valid_signature', + 'tf.saved_model.loader.maybe_saved_model_directory': + 'tf.saved_model.contains_saved_model', + 'tf.saved_model.main_op.main_op': + 'tf.compat.v1.saved_model.main_op.main_op', + 'tf.saved_model.main_op.main_op_with_restore': + 'tf.compat.v1.saved_model.main_op.main_op_with_restore', + 'tf.saved_model.main_op_with_restore': + 'tf.compat.v1.saved_model.main_op_with_restore', + 'tf.saved_model.maybe_saved_model_directory': + 'tf.saved_model.contains_saved_model', + 'tf.saved_model.predict_signature_def': + 'tf.compat.v1.saved_model.predict_signature_def', + 'tf.saved_model.regression_signature_def': + 'tf.compat.v1.saved_model.regression_signature_def', + 'tf.saved_model.signature_constants.CLASSIFY_INPUTS': + 'tf.saved_model.CLASSIFY_INPUTS', + 'tf.saved_model.signature_constants.CLASSIFY_METHOD_NAME': + 'tf.saved_model.CLASSIFY_METHOD_NAME', + 'tf.saved_model.signature_constants.CLASSIFY_OUTPUT_CLASSES': + 'tf.saved_model.CLASSIFY_OUTPUT_CLASSES', + 'tf.saved_model.signature_constants.CLASSIFY_OUTPUT_SCORES': + 'tf.saved_model.CLASSIFY_OUTPUT_SCORES', + 'tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY': + 'tf.saved_model.DEFAULT_SERVING_SIGNATURE_DEF_KEY', + 'tf.saved_model.signature_constants.PREDICT_INPUTS': + 'tf.saved_model.PREDICT_INPUTS', + 'tf.saved_model.signature_constants.PREDICT_METHOD_NAME': + 'tf.saved_model.PREDICT_METHOD_NAME', + 'tf.saved_model.signature_constants.PREDICT_OUTPUTS': + 'tf.saved_model.PREDICT_OUTPUTS', + 'tf.saved_model.signature_constants.REGRESS_INPUTS': + 'tf.saved_model.REGRESS_INPUTS', + 'tf.saved_model.signature_constants.REGRESS_METHOD_NAME': + 'tf.saved_model.REGRESS_METHOD_NAME', + 'tf.saved_model.signature_constants.REGRESS_OUTPUTS': + 'tf.saved_model.REGRESS_OUTPUTS', + 'tf.saved_model.signature_def_utils.MethodNameUpdater': + 'tf.compat.v1.saved_model.signature_def_utils.MethodNameUpdater', + 'tf.saved_model.signature_def_utils.build_signature_def': + 'tf.compat.v1.saved_model.signature_def_utils.build_signature_def', + 'tf.saved_model.signature_def_utils.classification_signature_def': + 'tf.compat.v1.saved_model.signature_def_utils.classification_signature_def', + 'tf.saved_model.signature_def_utils.is_valid_signature': + 'tf.compat.v1.saved_model.signature_def_utils.is_valid_signature', + 'tf.saved_model.signature_def_utils.predict_signature_def': + 'tf.compat.v1.saved_model.signature_def_utils.predict_signature_def', + 'tf.saved_model.signature_def_utils.regression_signature_def': + 'tf.compat.v1.saved_model.signature_def_utils.regression_signature_def', + 'tf.saved_model.simple_save': + 'tf.compat.v1.saved_model.simple_save', + 'tf.saved_model.tag_constants.GPU': + 'tf.saved_model.GPU', + 'tf.saved_model.tag_constants.SERVING': + 'tf.saved_model.SERVING', + 'tf.saved_model.tag_constants.TPU': + 'tf.saved_model.TPU', + 'tf.saved_model.tag_constants.TRAINING': + 'tf.saved_model.TRAINING', + 'tf.saved_model.utils.build_tensor_info': + 'tf.compat.v1.saved_model.utils.build_tensor_info', + 'tf.saved_model.utils.get_tensor_from_tensor_info': + 'tf.compat.v1.saved_model.utils.get_tensor_from_tensor_info', + 'tf.scatter_add': + 'tf.compat.v1.scatter_add', + 'tf.scatter_div': + 'tf.compat.v1.scatter_div', + 'tf.scatter_max': + 'tf.compat.v1.scatter_max', + 'tf.scatter_min': + 'tf.compat.v1.scatter_min', + 'tf.scatter_mul': + 'tf.compat.v1.scatter_mul', + 'tf.scatter_nd_add': + 'tf.compat.v1.scatter_nd_add', + 'tf.scatter_nd_sub': + 'tf.compat.v1.scatter_nd_sub', + 'tf.scatter_nd_update': + 'tf.compat.v1.scatter_nd_update', + 'tf.scatter_sub': + 'tf.compat.v1.scatter_sub', + 'tf.scatter_update': + 'tf.compat.v1.scatter_update', + 'tf.segment_max': + 'tf.math.segment_max', + 'tf.segment_mean': + 'tf.math.segment_mean', + 'tf.segment_min': + 'tf.math.segment_min', + 'tf.segment_prod': + 'tf.math.segment_prod', + 'tf.segment_sum': + 'tf.math.segment_sum', + 'tf.self_adjoint_eig': + 'tf.linalg.eigh', + 'tf.self_adjoint_eigvals': + 'tf.linalg.eigvalsh', + 'tf.serialize_many_sparse': + 'tf.io.serialize_many_sparse', + 'tf.serialize_sparse': + 'tf.io.serialize_sparse', + 'tf.serialize_tensor': + 'tf.io.serialize_tensor', + 'tf.set_random_seed': + 'tf.compat.v1.set_random_seed', + 'tf.setdiff1d': + 'tf.compat.v1.setdiff1d', + 'tf.sets.set_difference': + 'tf.sets.difference', + 'tf.sets.set_intersection': + 'tf.sets.intersection', + 'tf.sets.set_size': + 'tf.sets.size', + 'tf.sets.set_union': + 'tf.sets.union', + 'tf.space_to_depth': + 'tf.nn.space_to_depth', + 'tf.sparse.SparseConditionalAccumulator': + 'tf.compat.v1.sparse.SparseConditionalAccumulator', + 'tf.sparse.matmul': + 'tf.sparse.sparse_dense_matmul', + 'tf.sparse.merge': + 'tf.compat.v1.sparse.merge', + 'tf.sparse.placeholder': + 'tf.compat.v1.sparse.placeholder', + 'tf.sparse.reduce_max_sparse': + 'tf.compat.v1.sparse.reduce_max_sparse', + 'tf.sparse.reduce_sum_sparse': + 'tf.compat.v1.sparse.reduce_sum_sparse', + 'tf.sparse_add': + 'tf.sparse.add', + 'tf.sparse_concat': + 'tf.sparse.concat', + 'tf.sparse_fill_empty_rows': + 'tf.sparse.fill_empty_rows', + 'tf.sparse_mask': + 'tf.sparse.mask', + 'tf.sparse_maximum': + 'tf.sparse.maximum', + 'tf.sparse_merge': + 'tf.compat.v1.sparse_merge', + 'tf.sparse_minimum': + 'tf.sparse.minimum', + 'tf.sparse_placeholder': + 'tf.compat.v1.sparse_placeholder', + 'tf.sparse_reduce_max': + 'tf.sparse.reduce_max', + 'tf.sparse_reduce_max_sparse': + 'tf.compat.v1.sparse_reduce_max_sparse', + 'tf.sparse_reduce_sum': + 'tf.sparse.reduce_sum', + 'tf.sparse_reduce_sum_sparse': + 'tf.compat.v1.sparse_reduce_sum_sparse', + 'tf.sparse_reorder': + 'tf.sparse.reorder', + 'tf.sparse_reset_shape': + 'tf.sparse.reset_shape', + 'tf.sparse_reshape': + 'tf.sparse.reshape', + 'tf.sparse_retain': + 'tf.sparse.retain', + 'tf.sparse_segment_mean': + 'tf.sparse.segment_mean', + 'tf.sparse_segment_sqrt_n': + 'tf.sparse.segment_sqrt_n', + 'tf.sparse_segment_sum': + 'tf.sparse.segment_sum', + 'tf.sparse_slice': + 'tf.sparse.slice', + 'tf.sparse_softmax': + 'tf.sparse.softmax', + 'tf.sparse_split': + 'tf.sparse.split', + 'tf.sparse_tensor_dense_matmul': + 'tf.sparse.sparse_dense_matmul', + 'tf.sparse_tensor_to_dense': + 'tf.sparse.to_dense', + 'tf.sparse_to_dense': + 'tf.compat.v1.sparse_to_dense', + 'tf.sparse_to_indicator': + 'tf.sparse.to_indicator', + 'tf.sparse_transpose': + 'tf.sparse.transpose', + 'tf.spectral.dct': + 'tf.signal.dct', + 'tf.spectral.fft': + 'tf.signal.fft', + 'tf.spectral.fft2d': + 'tf.signal.fft2d', + 'tf.spectral.fft3d': + 'tf.signal.fft3d', + 'tf.spectral.idct': + 'tf.signal.idct', + 'tf.spectral.ifft': + 'tf.signal.ifft', + 'tf.spectral.ifft2d': + 'tf.signal.ifft2d', + 'tf.spectral.ifft3d': + 'tf.signal.ifft3d', + 'tf.spectral.irfft': + 'tf.signal.irfft', + 'tf.spectral.irfft2d': + 'tf.signal.irfft2d', + 'tf.spectral.irfft3d': + 'tf.signal.irfft3d', + 'tf.spectral.rfft': + 'tf.signal.rfft', + 'tf.spectral.rfft2d': + 'tf.signal.rfft2d', + 'tf.spectral.rfft3d': + 'tf.signal.rfft3d', + 'tf.squared_difference': + 'tf.math.squared_difference', + 'tf.string_join': + 'tf.strings.join', + 'tf.string_strip': + 'tf.strings.strip', + 'tf.string_to_hash_bucket_fast': + 'tf.strings.to_hash_bucket_fast', + 'tf.string_to_hash_bucket_strong': + 'tf.strings.to_hash_bucket_strong', + 'tf.summary.Event': + 'tf.compat.v1.summary.Event', + 'tf.summary.FileWriter': + 'tf.compat.v1.summary.FileWriter', + 'tf.summary.FileWriterCache': + 'tf.compat.v1.summary.FileWriterCache', + 'tf.summary.SessionLog': + 'tf.compat.v1.summary.SessionLog', + 'tf.summary.Summary': + 'tf.compat.v1.summary.Summary', + 'tf.summary.SummaryDescription': + 'tf.compat.v1.summary.SummaryDescription', + 'tf.summary.TaggedRunMetadata': + 'tf.compat.v1.summary.TaggedRunMetadata', + 'tf.summary.all_v2_summary_ops': + 'tf.compat.v1.summary.all_v2_summary_ops', + 'tf.summary.audio': + 'tf.compat.v1.summary.audio', + 'tf.summary.get_summary_description': + 'tf.compat.v1.summary.get_summary_description', + 'tf.summary.histogram': + 'tf.compat.v1.summary.histogram', + 'tf.summary.image': + 'tf.compat.v1.summary.image', + 'tf.summary.initialize': + 'tf.compat.v1.summary.initialize', + 'tf.summary.merge': + 'tf.compat.v1.summary.merge', + 'tf.summary.merge_all': + 'tf.compat.v1.summary.merge_all', + 'tf.summary.scalar': + 'tf.compat.v1.summary.scalar', + 'tf.summary.tensor_summary': + 'tf.compat.v1.summary.tensor_summary', + 'tf.summary.text': + 'tf.compat.v1.summary.text', + 'tf.svd': + 'tf.linalg.svd', + 'tf.tables_initializer': + 'tf.compat.v1.tables_initializer', + 'tf.tensor_scatter_add': + 'tf.tensor_scatter_nd_add', + 'tf.tensor_scatter_sub': + 'tf.tensor_scatter_nd_sub', + 'tf.tensor_scatter_update': + 'tf.tensor_scatter_nd_update', + 'tf.test.StubOutForTesting': + 'tf.compat.v1.test.StubOutForTesting', + 'tf.test.compute_gradient_error': + 'tf.compat.v1.test.compute_gradient_error', + 'tf.test.get_temp_dir': + 'tf.compat.v1.test.get_temp_dir', + 'tf.test.mock': + 'tf.compat.v1.test.mock', + 'tf.test.test_src_dir_path': + 'tf.compat.v1.test.test_src_dir_path', + 'tf.to_bfloat16': + 'tf.compat.v1.to_bfloat16', + 'tf.to_complex128': + 'tf.compat.v1.to_complex128', + 'tf.to_complex64': + 'tf.compat.v1.to_complex64', + 'tf.to_double': + 'tf.compat.v1.to_double', + 'tf.to_float': + 'tf.compat.v1.to_float', + 'tf.to_int32': + 'tf.compat.v1.to_int32', + 'tf.to_int64': + 'tf.compat.v1.to_int64', + 'tf.tpu.CrossShardOptimizer': + 'tf.compat.v1.tpu.CrossShardOptimizer', + 'tf.tpu.PaddingSpec': + 'tf.compat.v1.tpu.PaddingSpec', + 'tf.tpu.batch_parallel': + 'tf.compat.v1.tpu.batch_parallel', + 'tf.tpu.bfloat16_scope': + 'tf.compat.v1.tpu.bfloat16_scope', + 'tf.tpu.core': + 'tf.compat.v1.tpu.core', + 'tf.tpu.cross_replica_sum': + 'tf.compat.v1.tpu.cross_replica_sum', + 'tf.tpu.experimental.AdagradParameters': + 'tf.compat.v1.tpu.experimental.AdagradParameters', + 'tf.tpu.experimental.AdamParameters': + 'tf.compat.v1.tpu.experimental.AdamParameters', + 'tf.tpu.experimental.FtrlParameters': + 'tf.compat.v1.tpu.experimental.FtrlParameters', + 'tf.tpu.experimental.StochasticGradientDescentParameters': + 'tf.compat.v1.tpu.experimental.StochasticGradientDescentParameters', + 'tf.tpu.experimental.embedding_column': + 'tf.compat.v1.tpu.experimental.embedding_column', + 'tf.tpu.experimental.shared_embedding_columns': + 'tf.compat.v1.tpu.experimental.shared_embedding_columns', + 'tf.tpu.initialize_system': + 'tf.compat.v1.tpu.initialize_system', + 'tf.tpu.outside_compilation': + 'tf.compat.v1.tpu.outside_compilation', + 'tf.tpu.replicate': + 'tf.compat.v1.tpu.replicate', + 'tf.tpu.rewrite': + 'tf.compat.v1.tpu.rewrite', + 'tf.tpu.shard': + 'tf.compat.v1.tpu.shard', + 'tf.tpu.shutdown_system': + 'tf.compat.v1.tpu.shutdown_system', + 'tf.trace': + 'tf.linalg.trace', + 'tf.train.AdadeltaOptimizer': + 'tf.compat.v1.train.AdadeltaOptimizer', + 'tf.train.AdagradDAOptimizer': + 'tf.compat.v1.train.AdagradDAOptimizer', + 'tf.train.AdagradOptimizer': + 'tf.compat.v1.train.AdagradOptimizer', + 'tf.train.AdamOptimizer': + 'tf.compat.v1.train.AdamOptimizer', + 'tf.train.CheckpointSaverHook': + 'tf.estimator.CheckpointSaverHook', + 'tf.train.CheckpointSaverListener': + 'tf.estimator.CheckpointSaverListener', + 'tf.train.ChiefSessionCreator': + 'tf.compat.v1.train.ChiefSessionCreator', + 'tf.train.FeedFnHook': + 'tf.estimator.FeedFnHook', + 'tf.train.FinalOpsHook': + 'tf.estimator.FinalOpsHook', + 'tf.train.FtrlOptimizer': + 'tf.compat.v1.train.FtrlOptimizer', + 'tf.train.GlobalStepWaiterHook': + 'tf.estimator.GlobalStepWaiterHook', + 'tf.train.GradientDescentOptimizer': + 'tf.compat.v1.train.GradientDescentOptimizer', + 'tf.train.LoggingTensorHook': + 'tf.estimator.LoggingTensorHook', + 'tf.train.LooperThread': + 'tf.compat.v1.train.LooperThread', + 'tf.train.MomentumOptimizer': + 'tf.compat.v1.train.MomentumOptimizer', + 'tf.train.MonitoredSession': + 'tf.compat.v1.train.MonitoredSession', + 'tf.train.MonitoredTrainingSession': + 'tf.compat.v1.train.MonitoredTrainingSession', + 'tf.train.NanLossDuringTrainingError': + 'tf.estimator.NanLossDuringTrainingError', + 'tf.train.NanTensorHook': + 'tf.estimator.NanTensorHook', + 'tf.train.NewCheckpointReader': + 'tf.compat.v1.train.NewCheckpointReader', + 'tf.train.Optimizer': + 'tf.compat.v1.train.Optimizer', + 'tf.train.ProfilerHook': + 'tf.estimator.ProfilerHook', + 'tf.train.ProximalAdagradOptimizer': + 'tf.compat.v1.train.ProximalAdagradOptimizer', + 'tf.train.ProximalGradientDescentOptimizer': + 'tf.compat.v1.train.ProximalGradientDescentOptimizer', + 'tf.train.QueueRunner': + 'tf.compat.v1.train.QueueRunner', + 'tf.train.RMSPropOptimizer': + 'tf.compat.v1.train.RMSPropOptimizer', + 'tf.train.Saver': + 'tf.compat.v1.train.Saver', + 'tf.train.SaverDef': + 'tf.compat.v1.train.SaverDef', + 'tf.train.Scaffold': + 'tf.compat.v1.train.Scaffold', + 'tf.train.SecondOrStepTimer': + 'tf.estimator.SecondOrStepTimer', + 'tf.train.Server': + 'tf.distribute.Server', + 'tf.train.SessionCreator': + 'tf.compat.v1.train.SessionCreator', + 'tf.train.SessionManager': + 'tf.compat.v1.train.SessionManager', + 'tf.train.SessionRunArgs': + 'tf.estimator.SessionRunArgs', + 'tf.train.SessionRunContext': + 'tf.estimator.SessionRunContext', + 'tf.train.SessionRunHook': + 'tf.estimator.SessionRunHook', + 'tf.train.SessionRunValues': + 'tf.estimator.SessionRunValues', + 'tf.train.SingularMonitoredSession': + 'tf.compat.v1.train.SingularMonitoredSession', + 'tf.train.StepCounterHook': + 'tf.estimator.StepCounterHook', + 'tf.train.StopAtStepHook': + 'tf.estimator.StopAtStepHook', + 'tf.train.SummarySaverHook': + 'tf.estimator.SummarySaverHook', + 'tf.train.Supervisor': + 'tf.compat.v1.train.Supervisor', + 'tf.train.SyncReplicasOptimizer': + 'tf.compat.v1.train.SyncReplicasOptimizer', + 'tf.train.VocabInfo': + 'tf.estimator.VocabInfo', + 'tf.train.WorkerSessionCreator': + 'tf.compat.v1.train.WorkerSessionCreator', + 'tf.train.add_queue_runner': + 'tf.compat.v1.train.add_queue_runner', + 'tf.train.assert_global_step': + 'tf.compat.v1.train.assert_global_step', + 'tf.train.basic_train_loop': + 'tf.compat.v1.train.basic_train_loop', + 'tf.train.batch': + 'tf.compat.v1.train.batch', + 'tf.train.batch_join': + 'tf.compat.v1.train.batch_join', + 'tf.train.checkpoint_exists': + 'tf.compat.v1.train.checkpoint_exists', + 'tf.train.cosine_decay': + 'tf.compat.v1.train.cosine_decay', + 'tf.train.cosine_decay_restarts': + 'tf.compat.v1.train.cosine_decay_restarts', + 'tf.train.create_global_step': + 'tf.compat.v1.train.create_global_step', + 'tf.train.do_quantize_training_on_graphdef': + 'tf.compat.v1.train.do_quantize_training_on_graphdef', + 'tf.train.experimental.DynamicLossScale': + 'tf.compat.v1.train.experimental.DynamicLossScale', + 'tf.train.experimental.FixedLossScale': + 'tf.compat.v1.train.experimental.FixedLossScale', + 'tf.train.experimental.LossScale': + 'tf.compat.v1.train.experimental.LossScale', + 'tf.train.experimental.MixedPrecisionLossScaleOptimizer': + 'tf.compat.v1.train.experimental.MixedPrecisionLossScaleOptimizer', + 'tf.train.experimental.disable_mixed_precision_graph_rewrite': + 'tf.compat.v1.train.experimental.disable_mixed_precision_graph_rewrite', + 'tf.train.experimental.enable_mixed_precision_graph_rewrite': + 'tf.compat.v1.train.experimental.enable_mixed_precision_graph_rewrite', + 'tf.train.exponential_decay': + 'tf.compat.v1.train.exponential_decay', + 'tf.train.export_meta_graph': + 'tf.compat.v1.train.export_meta_graph', + 'tf.train.generate_checkpoint_state_proto': + 'tf.compat.v1.train.generate_checkpoint_state_proto', + 'tf.train.get_checkpoint_mtimes': + 'tf.compat.v1.train.get_checkpoint_mtimes', + 'tf.train.get_global_step': + 'tf.compat.v1.train.get_global_step', + 'tf.train.get_or_create_global_step': + 'tf.compat.v1.train.get_or_create_global_step', + 'tf.train.global_step': + 'tf.compat.v1.train.global_step', + 'tf.train.import_meta_graph': + 'tf.compat.v1.train.import_meta_graph', + 'tf.train.init_from_checkpoint': + 'tf.compat.v1.train.init_from_checkpoint', + 'tf.train.input_producer': + 'tf.compat.v1.train.input_producer', + 'tf.train.inverse_time_decay': + 'tf.compat.v1.train.inverse_time_decay', + 'tf.train.limit_epochs': + 'tf.compat.v1.train.limit_epochs', + 'tf.train.linear_cosine_decay': + 'tf.compat.v1.train.linear_cosine_decay', + 'tf.train.match_filenames_once': + 'tf.io.match_filenames_once', + 'tf.train.maybe_batch': + 'tf.compat.v1.train.maybe_batch', + 'tf.train.maybe_batch_join': + 'tf.compat.v1.train.maybe_batch_join', + 'tf.train.maybe_shuffle_batch': + 'tf.compat.v1.train.maybe_shuffle_batch', + 'tf.train.maybe_shuffle_batch_join': + 'tf.compat.v1.train.maybe_shuffle_batch_join', + 'tf.train.natural_exp_decay': + 'tf.compat.v1.train.natural_exp_decay', + 'tf.train.noisy_linear_cosine_decay': + 'tf.compat.v1.train.noisy_linear_cosine_decay', + 'tf.train.piecewise_constant': + 'tf.compat.v1.train.piecewise_constant', + 'tf.train.piecewise_constant_decay': + 'tf.compat.v1.train.piecewise_constant_decay', + 'tf.train.polynomial_decay': + 'tf.compat.v1.train.polynomial_decay', + 'tf.train.queue_runner.QueueRunner': + 'tf.compat.v1.train.queue_runner.QueueRunner', + 'tf.train.queue_runner.add_queue_runner': + 'tf.compat.v1.train.queue_runner.add_queue_runner', + 'tf.train.queue_runner.start_queue_runners': + 'tf.compat.v1.train.queue_runner.start_queue_runners', + 'tf.train.range_input_producer': + 'tf.compat.v1.train.range_input_producer', + 'tf.train.remove_checkpoint': + 'tf.compat.v1.train.remove_checkpoint', + 'tf.train.replica_device_setter': + 'tf.compat.v1.train.replica_device_setter', + 'tf.train.shuffle_batch': + 'tf.compat.v1.train.shuffle_batch', + 'tf.train.shuffle_batch_join': + 'tf.compat.v1.train.shuffle_batch_join', + 'tf.train.slice_input_producer': + 'tf.compat.v1.train.slice_input_producer', + 'tf.train.start_queue_runners': + 'tf.compat.v1.train.start_queue_runners', + 'tf.train.string_input_producer': + 'tf.compat.v1.train.string_input_producer', + 'tf.train.summary_iterator': + 'tf.compat.v1.train.summary_iterator', + 'tf.train.update_checkpoint_state': + 'tf.compat.v1.train.update_checkpoint_state', + 'tf.train.warm_start': + 'tf.compat.v1.train.warm_start', + 'tf.train.write_graph': + 'tf.io.write_graph', + 'tf.trainable_variables': + 'tf.compat.v1.trainable_variables', + 'tf.truncated_normal': + 'tf.random.truncated_normal', + 'tf.uniform_unit_scaling_initializer': + 'tf.compat.v1.uniform_unit_scaling_initializer', + 'tf.unsorted_segment_max': + 'tf.math.unsorted_segment_max', + 'tf.unsorted_segment_mean': + 'tf.math.unsorted_segment_mean', + 'tf.unsorted_segment_min': + 'tf.math.unsorted_segment_min', + 'tf.unsorted_segment_prod': + 'tf.math.unsorted_segment_prod', + 'tf.unsorted_segment_sqrt_n': + 'tf.math.unsorted_segment_sqrt_n', + 'tf.unsorted_segment_sum': + 'tf.math.unsorted_segment_sum', + 'tf.variable_axis_size_partitioner': + 'tf.compat.v1.variable_axis_size_partitioner', + 'tf.variable_op_scope': + 'tf.compat.v1.variable_op_scope', + 'tf.variable_scope': + 'tf.compat.v1.variable_scope', + 'tf.variables_initializer': + 'tf.compat.v1.variables_initializer', + 'tf.verify_tensor_all_finite': + 'tf.debugging.assert_all_finite', + 'tf.wrap_function': + 'tf.compat.v1.wrap_function', + 'tf.write_file': + 'tf.io.write_file', + 'tf.zeta': + 'tf.math.zeta' +} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tools/compatibility/reorders_v2.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tools/compatibility/reorders_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..99a0d1b4e473a168b73c642b7658a9303d25d8e1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tools/compatibility/reorders_v2.py @@ -0,0 +1,144 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +# pylint: disable=line-too-long +"""List of renames to apply when converting from TF 1.0 to TF 2.0. + +THIS FILE IS AUTOGENERATED: To update, please run: + bazel run tensorflow/tools/compatibility/update:generate_v2_reorders_map +This file should be updated whenever a function is added to +self.reordered_function_names in tf_upgrade_v2.py. +""" +reorders = { + 'tf.argmax': [None, None, 'name', 'dimension', 'output_type'], + 'tf.argmin': [None, None, 'name', 'dimension', 'output_type'], + 'tf.batch_to_space': [None, 'crops', 'block_size', 'name', 'block_shape'], + 'tf.boolean_mask': [None, None, 'name', 'axis'], + 'tf.cond': [None, None, None, 'strict', 'name', 'fn1', 'fn2'], + 'tf.confusion_matrix': [None, None, None, 'dtype', 'name', 'weights'], + 'tf.convert_to_tensor': [None, None, 'name', 'preferred_dtype', 'dtype_hint'], + 'tf.data.experimental.RaggedTensorStructure': ['dtype', 'shape', 'ragged_rank'], + 'tf.data.experimental.SparseTensorStructure': ['dtype', 'shape'], + 'tf.data.experimental.TensorArrayStructure': ['dtype', 'element_shape', 'dynamic_size', 'infer_shape'], + 'tf.data.experimental.TensorStructure': ['dtype', 'shape'], + 'tf.debugging.assert_all_finite': ['t', 'msg', 'name', 'x', 'message'], + 'tf.decode_csv': [None, None, None, None, 'name', 'na_value', 'select_cols'], + 'tf.depth_to_space': [None, None, 'name', 'data_format'], + 'tf.estimator.BaselineClassifier': ['model_dir', 'n_classes', 'weight_column', 'label_vocabulary', 'optimizer', 'config', 'loss_reduction'], + 'tf.estimator.BaselineRegressor': ['model_dir', 'label_dimension', 'weight_column', 'optimizer', 'config', 'loss_reduction'], + 'tf.estimator.DNNClassifier': ['hidden_units', 'feature_columns', 'model_dir', 'n_classes', 'weight_column', 'label_vocabulary', 'optimizer', 'activation_fn', 'dropout', 'input_layer_partitioner', 'config', 'warm_start_from', 'loss_reduction', 'batch_norm'], + 'tf.estimator.DNNLinearCombinedClassifier': ['model_dir', 'linear_feature_columns', 'linear_optimizer', 'dnn_feature_columns', 'dnn_optimizer', 'dnn_hidden_units', 'dnn_activation_fn', 'dnn_dropout', 'n_classes', 'weight_column', 'label_vocabulary', 'input_layer_partitioner', 'config', 'warm_start_from', 'loss_reduction', 'batch_norm', 'linear_sparse_combiner'], + 'tf.estimator.DNNLinearCombinedRegressor': ['model_dir', 'linear_feature_columns', 'linear_optimizer', 'dnn_feature_columns', 'dnn_optimizer', 'dnn_hidden_units', 'dnn_activation_fn', 'dnn_dropout', 'label_dimension', 'weight_column', 'input_layer_partitioner', 'config', 'warm_start_from', 'loss_reduction', 'batch_norm', 'linear_sparse_combiner'], + 'tf.estimator.DNNRegressor': ['hidden_units', 'feature_columns', 'model_dir', 'label_dimension', 'weight_column', 'optimizer', 'activation_fn', 'dropout', 'input_layer_partitioner', 'config', 'warm_start_from', 'loss_reduction', 'batch_norm'], + 'tf.estimator.LinearClassifier': ['feature_columns', 'model_dir', 'n_classes', 'weight_column', 'label_vocabulary', 'optimizer', 'config', 'partitioner', 'warm_start_from', 'loss_reduction', 'sparse_combiner'], + 'tf.estimator.LinearRegressor': ['feature_columns', 'model_dir', 'label_dimension', 'weight_column', 'optimizer', 'config', 'partitioner', 'warm_start_from', 'loss_reduction', 'sparse_combiner'], + 'tf.feature_column.categorical_column_with_vocabulary_file': [None, None, None, 'num_oov_buckets', 'default_value', 'dtype'], + 'tf.gather_nd': [None, None, 'name', 'batch_dims'], + 'tf.gradients': [None, None, None, None, 'colocate_gradients_with_ops', 'gate_gradients', 'aggregation_method', 'stop_gradients', 'unconnected_gradients'], + 'tf.hessians': [None, None, 'name', 'colocate_gradients_with_ops', 'gate_gradients', 'aggregation_method'], + 'tf.image.sample_distorted_bounding_box': [None, None, None, 'seed2', 'min_object_covered', 'aspect_ratio_range', 'area_range', 'max_attempts', 'use_image_if_no_bounding_boxes', 'name'], + 'tf.initializers.uniform_unit_scaling': ['factor', 'seed', 'dtype'], + 'tf.io.decode_csv': [None, None, None, None, 'name', 'na_value', 'select_cols'], + 'tf.io.parse_example': [None, None, 'name', 'example_names'], + 'tf.io.parse_single_example': [None, None, 'name', 'example_names'], + 'tf.io.serialize_many_sparse': [None, 'name', 'out_type'], + 'tf.io.serialize_sparse': [None, 'name', 'out_type'], + 'tf.linalg.norm': [None, None, None, None, None, 'keep_dims'], + 'tf.manip.gather_nd': [None, None, 'name', 'batch_dims'], + 'tf.math.argmax': [None, None, 'name', 'dimension', 'output_type'], + 'tf.math.argmin': [None, None, 'name', 'dimension', 'output_type'], + 'tf.math.confusion_matrix': [None, None, None, 'dtype', 'name', 'weights'], + 'tf.math.in_top_k': ['predictions', 'targets', 'k', 'name'], + 'tf.math.reduce_all': [None, None, None, None, 'reduction_indices', 'keep_dims'], + 'tf.math.reduce_any': [None, None, None, None, 'reduction_indices', 'keep_dims'], + 'tf.math.reduce_logsumexp': [None, None, None, None, 'reduction_indices', 'keep_dims'], + 'tf.math.reduce_max': [None, None, None, None, 'reduction_indices', 'keep_dims'], + 'tf.math.reduce_mean': [None, None, None, None, 'reduction_indices', 'keep_dims'], + 'tf.math.reduce_min': [None, None, None, None, 'reduction_indices', 'keep_dims'], + 'tf.math.reduce_prod': [None, None, None, None, 'reduction_indices', 'keep_dims'], + 'tf.math.reduce_sum': [None, None, None, None, 'reduction_indices', 'keep_dims'], + 'tf.multinomial': [None, None, 'seed', 'name', 'output_dtype'], + 'tf.nn.avg_pool': ['value', 'ksize', 'strides', 'padding', 'data_format', 'name', 'input'], + 'tf.nn.avg_pool2d': ['value', 'ksize', 'strides', 'padding', 'data_format', 'name', 'input'], + 'tf.nn.conv1d': ['value', 'filters', 'stride', 'padding', 'use_cudnn_on_gpu', 'data_format', 'name', 'input', 'dilations'], + 'tf.nn.conv2d': [None, 'filter', 'strides', 'padding', 'use_cudnn_on_gpu', 'data_format', 'dilations', 'name', 'filters'], + 'tf.nn.conv2d_backprop_input': ['input_sizes', 'filter', 'out_backprop', 'strides', 'padding', 'use_cudnn_on_gpu', 'data_format', 'dilations', 'name', 'filters'], + 'tf.nn.convolution': [None, 'filter', 'padding', 'strides', 'dilation_rate', 'name', 'data_format', 'filters', 'dilations'], + 'tf.nn.crelu': [None, 'name', 'axis'], + 'tf.nn.ctc_beam_search_decoder': ['inputs', 'sequence_length', 'beam_width', 'top_paths', 'merge_repeated'], + 'tf.nn.depth_to_space': [None, None, 'name', 'data_format'], + 'tf.nn.depthwise_conv2d': [None, None, None, None, 'rate', 'name', 'data_format', 'dilations'], + 'tf.nn.embedding_lookup': [None, None, 'partition_strategy', 'name', 'validate_indices', 'max_norm'], + 'tf.nn.embedding_lookup_sparse': [None, None, None, 'partition_strategy', 'name', 'combiner', 'max_norm'], + 'tf.nn.fractional_avg_pool': ['value', 'pooling_ratio', 'pseudo_random', 'overlapping', 'deterministic', 'seed', 'seed2', 'name'], + 'tf.nn.fractional_max_pool': ['value', 'pooling_ratio', 'pseudo_random', 'overlapping', 'deterministic', 'seed', 'seed2', 'name'], + 'tf.nn.in_top_k': ['predictions', 'targets', 'k', 'name'], + 'tf.nn.max_pool': ['value', 'ksize', 'strides', 'padding', 'data_format', 'name', 'input'], + 'tf.nn.moments': [None, None, None, 'name', 'keep_dims', 'keepdims'], + 'tf.nn.pool': [None, None, None, 'padding', 'dilation_rate', 'strides', 'name', 'data_format', 'dilations'], + 'tf.nn.separable_conv2d': [None, None, None, None, None, 'rate', 'name', 'data_format', 'dilations'], + 'tf.nn.softmax_cross_entropy_with_logits': ['labels', 'logits', 'dim', 'name', 'axis'], + 'tf.nn.space_to_batch': [None, 'paddings', 'block_size', 'name', 'block_shape'], + 'tf.nn.space_to_depth': [None, None, 'name', 'data_format'], + 'tf.nn.weighted_moments': [None, None, None, 'name', 'keep_dims', 'keepdims'], + 'tf.norm': [None, None, None, None, None, 'keep_dims'], + 'tf.pad': [None, None, None, 'name', 'constant_values'], + 'tf.parse_example': [None, None, 'name', 'example_names'], + 'tf.parse_single_example': [None, None, 'name', 'example_names'], + 'tf.quantize_v2': [None, None, None, None, None, 'name', 'round_mode', 'narrow_range', 'axis', 'ensure_minimum_range'], + 'tf.random.multinomial': [None, None, 'seed', 'name', 'output_dtype'], + 'tf.random.poisson': ['lam', 'shape', 'dtype', 'seed', 'name'], + 'tf.random_poisson': ['lam', 'shape', 'dtype', 'seed', 'name'], + 'tf.reduce_all': [None, None, None, None, 'reduction_indices', 'keep_dims'], + 'tf.reduce_any': [None, None, None, None, 'reduction_indices', 'keep_dims'], + 'tf.reduce_join': [None, None, 'keep_dims', 'separator', 'name', 'reduction_indices', 'keepdims'], + 'tf.reduce_logsumexp': [None, None, None, None, 'reduction_indices', 'keep_dims'], + 'tf.reduce_max': [None, None, None, None, 'reduction_indices', 'keep_dims'], + 'tf.reduce_mean': [None, None, None, None, 'reduction_indices', 'keep_dims'], + 'tf.reduce_min': [None, None, None, None, 'reduction_indices', 'keep_dims'], + 'tf.reduce_prod': [None, None, None, None, 'reduction_indices', 'keep_dims'], + 'tf.reduce_sum': [None, None, None, None, 'reduction_indices', 'keep_dims'], + 'tf.reverse_sequence': [None, None, None, None, None, 'seq_dim', 'batch_dim'], + 'tf.serialize_many_sparse': [None, 'name', 'out_type'], + 'tf.serialize_sparse': [None, 'name', 'out_type'], + 'tf.shape': [None, 'name', 'out_type'], + 'tf.size': [None, 'name', 'out_type'], + 'tf.space_to_batch': [None, 'paddings', 'block_size', 'name', 'block_shape'], + 'tf.space_to_depth': [None, None, 'name', 'data_format'], + 'tf.sparse.add': [None, None, None, 'thresh'], + 'tf.sparse.concat': [None, None, 'name', 'expand_nonconcat_dim', 'concat_dim', 'expand_nonconcat_dims'], + 'tf.sparse.reduce_max': [None, None, None, 'reduction_axes', 'keep_dims'], + 'tf.sparse.segment_mean': [None, None, None, 'name', 'num_segments'], + 'tf.sparse.segment_sqrt_n': [None, None, None, 'name', 'num_segments'], + 'tf.sparse.segment_sum': [None, None, None, 'name', 'num_segments'], + 'tf.sparse.split': ['keyword_required', 'sp_input', 'num_split', 'axis', 'name', 'split_dim'], + 'tf.sparse_add': [None, None, None, 'thresh'], + 'tf.sparse_concat': [None, None, 'name', 'expand_nonconcat_dim', 'concat_dim', 'expand_nonconcat_dims'], + 'tf.sparse_matmul': [None, None, None, None, 'a_is_sparse', 'b_is_sparse', 'name'], + 'tf.sparse_reduce_max': [None, None, None, 'reduction_axes', 'keep_dims'], + 'tf.sparse_segment_mean': [None, None, None, 'name', 'num_segments'], + 'tf.sparse_segment_sqrt_n': [None, None, None, 'name', 'num_segments'], + 'tf.sparse_segment_sum': [None, None, None, 'name', 'num_segments'], + 'tf.sparse_split': ['keyword_required', 'sp_input', 'num_split', 'axis', 'name', 'split_dim'], + 'tf.strings.length': [None, 'name', 'unit'], + 'tf.strings.reduce_join': [None, None, 'keep_dims', 'separator', 'name', 'reduction_indices', 'keepdims'], + 'tf.strings.substr': [None, None, None, 'name', 'unit'], + 'tf.substr': [None, None, None, 'name', 'unit'], + 'tf.test.assert_equal_graph_def': ['actual', 'expected', 'checkpoint_v2', 'hash_table_shared_name'], + 'tf.transpose': [None, None, 'name', 'conjugate'], + 'tf.tuple': [None, 'name', 'control_inputs'], + 'tf.uniform_unit_scaling_initializer': ['factor', 'seed', 'dtype'], + 'tf.verify_tensor_all_finite': ['t', 'msg', 'name', 'x', 'message'], + 'tf.while_loop': ['cond', 'body', 'loop_vars', 'shape_invariants', 'parallel_iterations', 'back_prop', 'swap_memory', 'name', 'maximum_iterations', 'return_same_structure'] +} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tools/compatibility/tf_upgrade_v2.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tools/compatibility/tf_upgrade_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..b6632d288941e5cc72a5ba3b9b38556aebd3ad4a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tools/compatibility/tf_upgrade_v2.py @@ -0,0 +1,2645 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Upgrader for Python scripts from 1.* TensorFlow to 2.0 TensorFlow.""" + +import ast +import copy +import functools +import sys + +import pasta + +from tensorflow.tools.compatibility import all_renames_v2 +from tensorflow.tools.compatibility import ast_edits +from tensorflow.tools.compatibility import module_deprecations_v2 +from tensorflow.tools.compatibility import reorders_v2 + +# These pylint warnings are a mistake. +# pylint: disable=g-explicit-bool-comparison,g-bool-id-comparison + + +class UnaliasedTFImport(ast_edits.AnalysisResult): + + def __init__(self): + self.log_level = ast_edits.ERROR + self.log_message = ("The tf_upgrade_v2 script detected an unaliased " + "`import tensorflow`. The script can only run when " + "importing with `import tensorflow as tf`.") + + +class VersionedTFImport(ast_edits.AnalysisResult): + + def __init__(self, version): + self.log_level = ast_edits.INFO + self.log_message = ("Not upgrading symbols because `tensorflow." + version + + "` was directly imported as `tf`.") + + +compat_v1_import = VersionedTFImport("compat.v1") +compat_v2_import = VersionedTFImport("compat.v2") + + +class TFAPIImportAnalysisSpec(ast_edits.APIAnalysisSpec): + + def __init__(self): + self.symbols_to_detect = {} + self.imports_to_detect = { + ("tensorflow", None): UnaliasedTFImport(), + ("tensorflow.compat.v1", "tf"): compat_v1_import, + ("tensorflow.compat.v2", "tf"): compat_v2_import, + } + + +class CompatV1ImportReplacer(ast.NodeVisitor): + """AST Visitor that replaces `import tensorflow.compat.v1 as tf`. + + Converts `import tensorflow.compat.v1 as tf` to `import tensorflow as tf` + """ + + def visit_Import(self, node): # pylint: disable=invalid-name + """Handle visiting an import node in the AST. + + Args: + node: Current Node + """ + for import_alias in node.names: + # Detect based on full import name and alias + if (import_alias.name == "tensorflow.compat.v1" and + import_alias.asname == "tf"): + import_alias.name = "tensorflow" + self.generic_visit(node) + + +class TFAPIChangeSpec(ast_edits.NoUpdateSpec): + """List of maps that describe what changed in the API.""" + + def __init__(self, import_rename=False, upgrade_compat_v1_import=False): + self.upgrade_compat_v1_import = upgrade_compat_v1_import + + # Maps from a function name to a dictionary that describes how to + # map from an old argument keyword to the new argument keyword. + # If the new argument is None, it will be removed. + # Only keyword args are handled, so make sure to also put any function in + # function_reorders to ensure that all args are made into keywords first. + self.function_keyword_renames = { + # TODO(b/129398290) + # "tf.string_split": { + # "delimiter": "sep", + # }, + "tf.test.assert_equal_graph_def": { + "checkpoint_v2": None, + "hash_table_shared_name": None, + }, + "tf.autograph.to_code": { + "arg_types": None, + "arg_values": None, + "indentation": None, + }, + "tf.autograph.to_graph": { + "arg_types": None, + "arg_values": None, + }, + "tf.nn.embedding_lookup": { + "validate_indices": None, + }, + "tf.image.sample_distorted_bounding_box": { + "seed2": None, + }, + "tf.gradients": { + "colocate_gradients_with_ops": None, + }, + "tf.hessians": { + "colocate_gradients_with_ops": None, + }, + "*.minimize": { + "colocate_gradients_with_ops": None, + }, + "*.compute_gradients": { + "colocate_gradients_with_ops": None, + }, + "tf.cond": { + "strict": None, + "fn1": "true_fn", + "fn2": "false_fn" + }, + "tf.argmin": { + "dimension": "axis", + }, + "tf.argmax": { + "dimension": "axis", + }, + "tf.arg_min": { + "dimension": "axis", + }, + "tf.arg_max": { + "dimension": "axis", + }, + "tf.math.argmin": { + "dimension": "axis", + }, + "tf.math.argmax": { + "dimension": "axis", + }, + "tf.image.crop_and_resize": { + "box_ind": "box_indices", + }, + "tf.extract_image_patches": { + "ksizes": "sizes", + }, + "tf.image.extract_image_patches": { + "ksizes": "sizes", + }, + "tf.image.resize": { + "align_corners": None, + }, + "tf.image.resize_images": { + "align_corners": None, + }, + "tf.expand_dims": { + "dim": "axis", + }, + "tf.batch_to_space": { + "block_size": "block_shape", + }, + "tf.space_to_batch": { + "block_size": "block_shape", + }, + "tf.nn.space_to_batch": { + "block_size": "block_shape", + }, + "tf.constant": { + "verify_shape": "verify_shape_is_now_always_true", + }, + "tf.convert_to_tensor": { + "preferred_dtype": "dtype_hint" + }, + "tf.nn.softmax_cross_entropy_with_logits": { + "dim": "axis", + }, + "tf.nn.softmax_cross_entropy_with_logits_v2": { + "dim": "axis" + }, + "tf.linalg.l2_normalize": { + "dim": "axis", + }, + "tf.linalg.norm": { + "keep_dims": "keepdims", + }, + "tf.norm": { + "keep_dims": "keepdims", + }, + "tf.load_file_system_library": { + "library_filename": "library_location", + }, + "tf.count_nonzero": { + "input_tensor": "input", + "keep_dims": "keepdims", + "reduction_indices": "axis", + }, + "tf.math.count_nonzero": { + "input_tensor": "input", + "keep_dims": "keepdims", + "reduction_indices": "axis", + }, + "tf.nn.erosion2d": { + "kernel": "filters", + "rates": "dilations", + }, + "tf.math.l2_normalize": { + "dim": "axis", + }, + "tf.math.log_softmax": { + "dim": "axis", + }, + "tf.math.softmax": { + "dim": "axis" + }, + "tf.nn.l2_normalize": { + "dim": "axis", + }, + "tf.nn.log_softmax": { + "dim": "axis", + }, + "tf.nn.moments": { + "keep_dims": "keepdims", + }, + "tf.nn.pool": { + "dilation_rate": "dilations" + }, + "tf.nn.separable_conv2d": { + "rate": "dilations" + }, + "tf.nn.depthwise_conv2d": { + "rate": "dilations" + }, + "tf.nn.softmax": { + "dim": "axis" + }, + "tf.nn.sufficient_statistics": { + "keep_dims": "keepdims" + }, + "tf.debugging.assert_all_finite": { + "t": "x", + "msg": "message", + }, + "tf.verify_tensor_all_finite": { + "t": "x", + "msg": "message", + }, + "tf.sparse.add": { + "thresh": "threshold", + }, + "tf.sparse_add": { + "thresh": "threshold", + }, + "tf.sparse.concat": { + "concat_dim": "axis", + "expand_nonconcat_dim": "expand_nonconcat_dims", + }, + "tf.sparse_concat": { + "concat_dim": "axis", + "expand_nonconcat_dim": "expand_nonconcat_dims", + }, + "tf.sparse.split": { + "split_dim": "axis", + }, + "tf.sparse_split": { + "split_dim": "axis", + }, + "tf.sparse.reduce_max": { + "reduction_axes": "axis", + "keep_dims": "keepdims", + }, + "tf.sparse_reduce_max": { + "reduction_axes": "axis", + "keep_dims": "keepdims", + }, + "tf.sparse.reduce_sum": { + "reduction_axes": "axis", + "keep_dims": "keepdims", + }, + "tf.sparse_reduce_sum": { + "reduction_axes": "axis", + "keep_dims": "keepdims", + }, + "tf.nn.max_pool_with_argmax": { + "Targmax": "output_dtype", + }, + "tf.nn.max_pool": { + "value": "input" + }, + "tf.nn.avg_pool": { + "value": "input" + }, + "tf.nn.avg_pool2d": { + "value": "input" + }, + "tf.multinomial": { + "output_dtype": "dtype", + }, + "tf.random.multinomial": { + "output_dtype": "dtype", + }, + "tf.reverse_sequence": { + "seq_dim": "seq_axis", + "batch_dim": "batch_axis", + }, + "tf.nn.batch_norm_with_global_normalization": { + "t": "input", + "m": "mean", + "v": "variance", + }, + "tf.nn.dilation2d": { + "filter": "filters", + "rates": "dilations", + }, + "tf.nn.conv3d": { + "filter": "filters" + }, + "tf.zeros_like": { + "tensor": "input", + }, + "tf.ones_like": { + "tensor": "input", + }, + "tf.nn.conv2d_transpose": { + "value": "input", + "filter": "filters", + }, + "tf.nn.conv3d_transpose": { + "value": "input", + "filter": "filters", + }, + "tf.nn.convolution": { + "filter": "filters", + "dilation_rate": "dilations", + }, + "tf.gfile.Exists": { + "filename": "path", + }, + "tf.gfile.Remove": { + "filename": "path", + }, + "tf.gfile.Stat": { + "filename": "path", + }, + "tf.gfile.Glob": { + "filename": "pattern", + }, + "tf.gfile.MkDir": { + "dirname": "path", + }, + "tf.gfile.MakeDirs": { + "dirname": "path", + }, + "tf.gfile.DeleteRecursively": { + "dirname": "path", + }, + "tf.gfile.IsDirectory": { + "dirname": "path", + }, + "tf.gfile.ListDirectory": { + "dirname": "path", + }, + "tf.gfile.Copy": { + "oldpath": "src", + "newpath": "dst", + }, + "tf.gfile.Rename": { + "oldname": "src", + "newname": "dst", + }, + "tf.gfile.Walk": { + "in_order": "topdown", + }, + "tf.random.stateless_multinomial": { + "output_dtype": "dtype", + }, + "tf.string_to_number": { + "string_tensor": "input", + }, + "tf.strings.to_number": { + "string_tensor": "input", + }, + "tf.string_to_hash_bucket": { + "string_tensor": "input", + }, + "tf.strings.to_hash_bucket": { + "string_tensor": "input", + }, + "tf.reduce_all": { + "reduction_indices": "axis", + "keep_dims": "keepdims", + }, + "tf.math.reduce_all": { + "reduction_indices": "axis", + "keep_dims": "keepdims", + }, + "tf.reduce_any": { + "reduction_indices": "axis", + "keep_dims": "keepdims", + }, + "tf.math.reduce_any": { + "reduction_indices": "axis", + "keep_dims": "keepdims", + }, + "tf.reduce_min": { + "reduction_indices": "axis", + "keep_dims": "keepdims", + }, + "tf.math.reduce_min": { + "reduction_indices": "axis", + "keep_dims": "keepdims", + }, + "tf.reduce_max": { + "reduction_indices": "axis", + "keep_dims": "keepdims", + }, + "tf.math.reduce_max": { + "reduction_indices": "axis", + "keep_dims": "keepdims", + }, + "tf.reduce_sum": { + "reduction_indices": "axis", + "keep_dims": "keepdims", + }, + "tf.math.reduce_sum": { + "reduction_indices": "axis", + "keep_dims": "keepdims", + }, + "tf.reduce_mean": { + "reduction_indices": "axis", + "keep_dims": "keepdims", + }, + "tf.math.reduce_mean": { + "reduction_indices": "axis", + "keep_dims": "keepdims", + }, + "tf.reduce_prod": { + "reduction_indices": "axis", + "keep_dims": "keepdims", + }, + "tf.math.reduce_prod": { + "reduction_indices": "axis", + "keep_dims": "keepdims", + }, + "tf.reduce_logsumexp": { + "reduction_indices": "axis", + "keep_dims": "keepdims", + }, + "tf.math.reduce_logsumexp": { + "reduction_indices": "axis", + "keep_dims": "keepdims", + }, + "tf.reduce_join": { + "keep_dims": "keepdims", + "reduction_indices": "axis" + }, + "tf.strings.reduce_join": { + "keep_dims": "keepdims", + "reduction_indices": "axis" + }, + "tf.squeeze": { + "squeeze_dims": "axis", + }, + "tf.nn.weighted_moments": { + "keep_dims": "keepdims" + }, + "tf.nn.conv1d": { + "value": "input", + "use_cudnn_on_gpu": None, + }, + "tf.nn.conv2d": { + "filter": "filters", + "use_cudnn_on_gpu": None, + }, + "tf.nn.conv2d_backprop_input": { + "use_cudnn_on_gpu": None, + "input_sizes": "output_shape", + "out_backprop": "input", + "filter": "filters", + }, + "tf.contrib.summary.audio": { + "tensor": "data", + "family": None, + }, + "tf.contrib.summary.create_file_writer": { + "name": None, + }, + "tf.contrib.summary.generic": { + "name": "tag", + "tensor": "data", + "family": None, + }, + "tf.contrib.summary.histogram": { + "tensor": "data", + "family": None, + }, + "tf.contrib.summary.image": { + "tensor": "data", + "bad_color": None, + "max_images": "max_outputs", + "family": None, + }, + "tf.contrib.summary.scalar": { + "tensor": "data", + "family": None, + }, + "tf.nn.weighted_cross_entropy_with_logits": { + "targets": "labels", + }, + "tf.decode_raw": { + "bytes": "input_bytes", + }, + "tf.io.decode_raw": { + "bytes": "input_bytes", + }, + "tf.contrib.framework.load_variable": { + "checkpoint_dir": "ckpt_dir_or_file", + } + } + all_renames_v2.add_contrib_direct_import_support( + self.function_keyword_renames) + + # Mapping from function to the new name of the function + # Add additional renames not in renames_v2.py to all_renames_v2.py. + self.symbol_renames = all_renames_v2.symbol_renames + self.import_rename = import_rename + if self.import_rename: + self.import_renames = { + "tensorflow": + ast_edits.ImportRename( + "tensorflow.compat.v2", + excluded_prefixes=[ + "tensorflow.contrib", "tensorflow.flags", + "tensorflow.compat.v1", "tensorflow.compat.v2", + "tensorflow.google" + ], + ) + } + else: + self.import_renames = {} + + # Variables that should be changed to functions. + self.change_to_function = {} + + # pylint: disable=line-too-long + # This list contains names of functions that had their arguments reordered. + # After modifying this list, run the following to update reorders_v2.py: + # bazel run tensorflow/tools/compatibility/update:generate_v2_reorders_map + # pylint: enable=line-too-long + self.reordered_function_names = { + "tf.io.serialize_sparse", + "tf.io.serialize_many_sparse", + "tf.argmax", + "tf.argmin", + "tf.batch_to_space", + "tf.cond", + "tf.nn.space_to_batch", + "tf.boolean_mask", + "tf.convert_to_tensor", + "tf.nn.conv1d", + "tf.nn.conv2d", + "tf.nn.conv2d_backprop_input", + "tf.nn.ctc_beam_search_decoder", + "tf.nn.moments", + "tf.nn.convolution", + "tf.nn.crelu", + "tf.nn.weighted_moments", + "tf.nn.pool", + "tf.nn.separable_conv2d", + "tf.nn.depthwise_conv2d", + "tf.multinomial", + "tf.random.multinomial", + "tf.pad", + "tf.quantize_v2", + "tf.feature_column.categorical_column_with_vocabulary_file", + "tf.shape", + "tf.size", + # TODO(b/129398290) + # "tf.string_split", + "tf.random.poisson", + "tf.sparse.add", + "tf.sparse_add", + "tf.sparse.concat", + "tf.sparse_concat", + "tf.sparse.segment_mean", + "tf.sparse.segment_sqrt_n", + "tf.sparse.segment_sum", + "tf.sparse_matmul", + "tf.sparse.reduce_max", + "tf.sparse_reduce_max", + "tf.io.decode_csv", + "tf.strings.length", + "tf.strings.reduce_join", + "tf.strings.substr", + "tf.substr", + "tf.transpose", + "tf.tuple", + "tf.parse_example", + "tf.parse_single_example", + "tf.io.parse_example", + "tf.io.parse_single_example", + "tf.while_loop", + "tf.reduce_all", + "tf.math.reduce_all", + "tf.reduce_any", + "tf.math.reduce_any", + "tf.reduce_min", + "tf.math.reduce_min", + "tf.reduce_max", + "tf.math.reduce_max", + "tf.reduce_sum", + "tf.math.reduce_sum", + "tf.reduce_mean", + "tf.math.reduce_mean", + "tf.reduce_prod", + "tf.math.reduce_prod", + "tf.reduce_logsumexp", + "tf.math.reduce_logsumexp", + "tf.reduce_join", + "tf.confusion_matrix", + "tf.math.confusion_matrix", + "tf.math.in_top_k", + "tf.nn.depth_to_space", + "tf.nn.embedding_lookup", + "tf.nn.embedding_lookup_sparse", + "tf.nn.in_top_k", + "tf.nn.space_to_depth", + "tf.test.assert_equal_graph_def", + "tf.linalg.norm", + "tf.norm", + "tf.reverse_sequence", + "tf.sparse_split", + # tf.nn.softmax_cross_entropy_with_logits *must* be called with + # keyword arguments. Add keyword arguments in rare case when they + # are not specified. + "tf.nn.softmax_cross_entropy_with_logits", + "tf.nn.fractional_avg_pool", + "tf.nn.fractional_max_pool", + "tf.image.sample_distorted_bounding_box", + "tf.gradients", + "tf.hessians", + "tf.nn.max_pool", + "tf.nn.avg_pool", + "tf.estimator.LinearClassifier", + "tf.estimator.LinearRegressor", + "tf.estimator.DNNLinearCombinedClassifier", + "tf.estimator.DNNLinearCombinedRegressor", + "tf.estimator.DNNRegressor", + "tf.estimator.DNNClassifier", + "tf.estimator.BaselineClassifier", + "tf.estimator.BaselineRegressor", + "tf.initializers.uniform_unit_scaling", + "tf.uniform_unit_scaling_initializer", + "tf.data.experimental.TensorStructure", + "tf.data.experimental.SparseTensorStructure", + "tf.data.experimental.RaggedTensorStructure", + "tf.data.experimental.TensorArrayStructure", + "tf.debugging.assert_all_finite", + "tf.gather_nd", + } + + # Manual mapping of function names to be reordered to their list of argument + # names, in order. Only use this if argument names cannot be autodetected, + # e.g. if the functions are in contrib. + self.manual_function_reorders = { + "tf.contrib.summary.audio": [ + "name", "tensor", "sample_rate", "max_outputs", "family", "step"], + "tf.contrib.summary.create_file_writer": [ + "logdir", "max_queue", "flush_millis", "filename_suffix", "name"], + "tf.contrib.summary.generic": [ + "name", "tensor", "metadata", "family", "step"], + "tf.contrib.summary.histogram": [ + "name", "tensor", "family", "step"], + "tf.contrib.summary.image": [ + "name", "tensor", "bad_color", "max_images", "family", "step"], + "tf.contrib.summary.scalar": [ + "name", "tensor", "family", "step"], + } + # Functions that were reordered should be changed to the new keyword args + # for safety, if positional arguments are used. If you have reversed the + # positional arguments yourself, this could do the wrong thing. + self.function_reorders = dict(reorders_v2.reorders) + self.function_reorders.update(self.manual_function_reorders) + + decay_function_comment = ( + ast_edits.INFO, + "To use learning rate decay schedules with TensorFlow 2.0, switch to " + "the schedules in `tf.keras.optimizers.schedules`.\n" + ) + + assert_return_type_comment = ( + ast_edits.INFO, + " has been changed to return None, the " + "data argument has been removed, and arguments have been reordered." + "\nThe calls have been converted to compat.v1 for safety (even though " + " they may already have been correct)." + ) + + assert_rank_comment = ( + ast_edits.INFO, + " has been changed to return None, and" + " the data and summarize arguments have been removed." + "\nThe calls have been converted to compat.v1 for safety (even though " + " they may already have been correct)." + ) + + contrib_layers_layer_norm_comment = ( + ast_edits.WARNING, + "(Manual edit required) `tf.contrib.layers.layer_norm` has been " + "deprecated, and its implementation has been integrated with " + "`tf.keras.layers.LayerNormalization` in TensorFlow 2.0. " + "Note that, the default value of `epsilon` is changed to `1e-3` in the " + "new API from `1e-12`, and this may introduce numerical differences. " + "Please check the new API and use that instead." + ) + + contrib_estimator_head_comment = ( + ast_edits.WARNING, + "(Manual edit required) `tf.contrib.estimator.*_head` has been " + "deprecated, and its implementation has been integrated with " + "`tf.estimator.*Head` in TensorFlow 2.0. " + "Please check the new API and use that instead." + ) + + initializers_no_dtype_comment = ( + ast_edits.INFO, "Initializers no longer have the " + "dtype argument in the constructor or partition_info argument in the " + "__call__ method.\nThe calls have been converted to compat.v1 for " + "safety (even though they may already have been correct).") + + metrics_comment = ( + ast_edits.INFO, + "tf.metrics have been replaced with object oriented versions in" + " TF 2.0 and after. The metric function calls have been converted to " + "compat.v1 for backward compatibility. Please update these calls to " + "the TF 2.0 versions.") + + losses_comment = ( + ast_edits.INFO, + "tf.losses have been replaced with object oriented versions in" + " TF 2.0 and after. The loss function calls have been converted to " + "compat.v1 for backward compatibility. Please update these calls to " + "the TF 2.0 versions.") + + # This could be done with a _rename_if_arg_not_found_transformer + deprecate_partition_strategy_comment = ( + ast_edits.WARNING, + "`partition_strategy` has been removed from . " + " The 'div' strategy will be used by default.") + + # make change instead + uniform_unit_scaling_initializer_comment = ( + ast_edits.ERROR, + "uniform_unit_scaling_initializer has been removed. Please use" + " tf.initializers.variance_scaling instead with distribution=uniform " + "to get equivalent behaviour.") + + # Make change instead (issue warning about strip_...) + export_saved_model_renamed = ( + ast_edits.ERROR, + "(Manual edit required) Please rename the method export_savedmodel() " + "to export_saved_model(). Two things to note:\n\t(1) The argument " + "strip_default_attributes has been removed. The function will always " + "strip the default attributes from ops. If this breaks your code, " + "please switch to tf.compat.v1.estimator.Estimator.\n\t(2) This change " + "only effects core estimator. If you are using " + "tf.contrib.learn.Estimator, please switch to using core estimator.") + + summary_api_comment = ( + ast_edits.INFO, + "The TF 1.x summary API cannot be automatically migrated to TF 2.0, so " + "symbols have been converted to tf.compat.v1.summary.* and must be " + "migrated manually. Typical usage will only require changes to the " + "summary writing logic, not to individual calls like scalar(). " + "For examples of the new summary API, see the Effective TF 2.0 " + "migration document or check the TF 2.0 TensorBoard tutorials.") + + contrib_summary_comment = ( + ast_edits.WARNING, + "tf.contrib.summary.* functions have been migrated best-effort to " + "tf.compat.v2.summary.* equivalents where possible, but the resulting " + "code is not guaranteed to work, so please check carefully. For more " + "information about the new summary API, see the Effective TF 2.0 " + "migration document or check the updated TensorBoard tutorials.") + + contrib_summary_family_arg_comment = ( + ast_edits.WARNING, + " replacement does not accept a 'family' argument; " + "instead regular name scoping should be used. This call site specifies " + "a family argument that has been removed on conversion, so the emitted " + "tag names may be incorrect without manual editing.") + + contrib_create_file_writer_comment = ( + ast_edits.WARNING, + "tf.contrib.summary.create_file_writer() has been ported to the new " + "tf.compat.v2.summary.create_file_writer(), which no longer re-uses " + "existing event files for the same logdir; instead it always opens a " + "new writer/file. The python writer objects must be re-used explicitly " + "if the reusing behavior is desired.") + + contrib_summary_record_every_n_comment = ( + ast_edits.ERROR, + "(Manual edit required) " + "tf.contrib.summary.record_summaries_every_n_global_steps(n, step) " + "should be replaced by a call to tf.compat.v2.summary.record_if() with " + "the argument `lambda: tf.math.equal(0, global_step % n)` (or in graph " + "mode, the lambda body can be used directly). If no global step was " + "passed, instead use tf.compat.v1.train.get_or_create_global_step().") + + contrib_summary_graph_comment = ( + ast_edits.ERROR, + "(Manual edit required) tf.contrib.summary.graph() has no direct " + "equivalent in TF 2.0 because manual graph construction has been " + "superseded by use of tf.function. To log tf.function execution graphs " + "to the summary writer, use the new tf.compat.v2.summary.trace_* " + "functions instead.") + + contrib_summary_import_event_comment = ( + ast_edits.ERROR, + "(Manual edit required) tf.contrib.summary.import_event() has no " + "direct equivalent in TF 2.0. For a similar experimental feature, try " + "tf.compat.v2.summary.experimental.write_raw_pb() which also accepts " + "serialized summary protocol buffer input, but for tf.Summary " + "protobufs rather than tf.Events.") + + keras_default_save_format_comment = ( + ast_edits.WARNING, + "(This warning is only applicable if the code saves a tf.Keras model) " + "Keras model.save now saves to the Tensorflow SavedModel format by " + "default, instead of HDF5. To continue saving to HDF5, add the " + "argument save_format='h5' to the save() function.") + + distribute_strategy_api_changes = ( + "If you're using the strategy with a " + "custom training loop, note the following changes in methods: " + "make_dataset_iterator->experimental_distribute_dataset, " + "experimental_make_numpy_iterator->experimental_make_numpy_dataset, " + "extended.call_for_each_replica->run, " + "reduce requires an axis argument, " + "unwrap->experimental_local_results " + "experimental_initialize and experimental_finalize no longer needed ") + + contrib_mirrored_strategy_warning = ( + ast_edits.ERROR, + "(Manual edit required) tf.contrib.distribute.MirroredStrategy has " + "been migrated to tf.distribute.MirroredStrategy. Things to note: " + "Constructor arguments have changed. If you are using " + "MirroredStrategy with Keras training framework, the input provided to " + "`model.fit` will be assumed to have global batch size and split " + "across the replicas. " + distribute_strategy_api_changes) + + core_mirrored_strategy_warning = ( + ast_edits.WARNING, + "(Manual edit may be required) tf.distribute.MirroredStrategy API has " + "changed. " + distribute_strategy_api_changes) + + contrib_one_device_strategy_warning = ( + ast_edits.ERROR, + "(Manual edit required) tf.contrib.distribute.OneDeviceStrategy has " + "been migrated to tf.distribute.OneDeviceStrategy. " + + distribute_strategy_api_changes) + + contrib_tpu_strategy_warning = ( + ast_edits.ERROR, + "(Manual edit required) tf.contrib.distribute.TPUStrategy has " + "been migrated to tf.distribute.TPUStrategy. Note the " + "slight changes in constructor. " + distribute_strategy_api_changes) + + contrib_collective_strategy_warning = ( + ast_edits.ERROR, + "(Manual edit required) " + "tf.contrib.distribute.CollectiveAllReduceStrategy has " + "been migrated to " + "tf.distribute.experimental.MultiWorkerMirroredStrategy. Note the " + "changes in constructor. " + distribute_strategy_api_changes) + + contrib_ps_strategy_warning = ( + ast_edits.ERROR, "(Manual edit required) " + "tf.contrib.distribute.ParameterServerStrategy has " + "been migrated to " + "tf.compat.v1.distribute.experimental.ParameterServerStrategy (multi " + "machine) and tf.distribute.experimental.CentralStorageStrategy (one " + "machine). Note the changes in constructors. " + + distribute_strategy_api_changes) + + keras_experimental_export_comment = ( + ast_edits.WARNING, + "tf.keras.experimental.export_saved_model and " + "tf.keras.experimental.load_from_saved_model have been deprecated." + "Please use model.save(path, save_format='tf') " + "(or alternatively tf.keras.models.save_model), and " + "tf.keras.models.load_model(path) instead.") + + saved_model_load_warning = ( + ast_edits.WARNING, + "tf.saved_model.load works differently in 2.0 compared to 1.0. See " + "migration information in the documentation of " + "tf.compat.v1.saved_model.load." + "\nThe calls have been converted to compat.v1.") + + # Function warnings. placeholder inside warnings will be + # replaced by function name. + # You can use *. to add items which do not check the FQN, and apply to e.g., + # methods. + self.function_warnings = { + "*.export_savedmodel": + export_saved_model_renamed, + "*.save": + keras_default_save_format_comment, + "tf.assert_equal": + assert_return_type_comment, + "tf.assert_none_equal": + assert_return_type_comment, + "tf.assert_negative": + assert_return_type_comment, + "tf.assert_positive": + assert_return_type_comment, + "tf.assert_non_negative": + assert_return_type_comment, + "tf.assert_non_positive": + assert_return_type_comment, + "tf.assert_near": + assert_return_type_comment, + "tf.assert_less": + assert_return_type_comment, + "tf.assert_less_equal": + assert_return_type_comment, + "tf.assert_greater": + assert_return_type_comment, + "tf.assert_greater_equal": + assert_return_type_comment, + "tf.assert_integer": + assert_return_type_comment, + "tf.assert_type": + assert_return_type_comment, + "tf.assert_scalar": + assert_return_type_comment, + "tf.assert_rank": + assert_rank_comment, + "tf.assert_rank_at_least": + assert_rank_comment, + "tf.assert_rank_in": + assert_rank_comment, + "tf.contrib.layers.layer_norm": + contrib_layers_layer_norm_comment, + "tf.contrib.estimator.binary_classification_head": + contrib_estimator_head_comment, + "tf.contrib.estimator.logistic_regression_head": + contrib_estimator_head_comment, + "tf.contrib.estimator.multi_class_head": + contrib_estimator_head_comment, + "tf.contrib.estimator.multi_head": + contrib_estimator_head_comment, + "tf.contrib.estimator.multi_label_head": + contrib_estimator_head_comment, + "tf.contrib.estimator.poisson_regression_head": + contrib_estimator_head_comment, + "tf.contrib.estimator.regression_head": + contrib_estimator_head_comment, + "tf.contrib.saved_model.load_keras_model": + keras_experimental_export_comment, + "tf.contrib.saved_model.save_keras_model": + keras_experimental_export_comment, + "tf.contrib.summary.all_summary_ops": + contrib_summary_comment, + "tf.contrib.summary.audio": + contrib_summary_comment, + "tf.contrib.summary.create_file_writer": + contrib_create_file_writer_comment, + "tf.contrib.summary.generic": + contrib_summary_comment, + "tf.contrib.summary.graph": + contrib_summary_graph_comment, + "tf.contrib.summary.histogram": + contrib_summary_comment, + "tf.contrib.summary.import_event": + contrib_summary_import_event_comment, + "tf.contrib.summary.image": + contrib_summary_comment, + "tf.contrib.summary.record_summaries_every_n_global_steps": + contrib_summary_record_every_n_comment, + "tf.contrib.summary.scalar": + contrib_summary_comment, + "tf.debugging.assert_equal": + assert_return_type_comment, + "tf.debugging.assert_greater": + assert_return_type_comment, + "tf.debugging.assert_greater_equal": + assert_return_type_comment, + "tf.debugging.assert_integer": + assert_return_type_comment, + "tf.debugging.assert_less": + assert_return_type_comment, + "tf.debugging.assert_less_equal": + assert_return_type_comment, + "tf.debugging.assert_near": + assert_return_type_comment, + "tf.debugging.assert_negative": + assert_return_type_comment, + "tf.debugging.assert_non_negative": + assert_return_type_comment, + "tf.debugging.assert_non_positive": + assert_return_type_comment, + "tf.debugging.assert_none_equal": + assert_return_type_comment, + "tf.debugging.assert_positive": + assert_return_type_comment, + "tf.debugging.assert_type": + assert_return_type_comment, + "tf.debugging.assert_scalar": + assert_return_type_comment, + "tf.debugging.assert_rank": + assert_rank_comment, + "tf.debugging.assert_rank_at_least": + assert_rank_comment, + "tf.debugging.assert_rank_in": + assert_rank_comment, + "tf.train.exponential_decay": + decay_function_comment, + "tf.train.piecewise_constant_decay": + decay_function_comment, + "tf.train.polynomial_decay": + decay_function_comment, + "tf.train.natural_exp_decay": + decay_function_comment, + "tf.train.inverse_time_decay": + decay_function_comment, + "tf.train.cosine_decay": + decay_function_comment, + "tf.train.cosine_decay_restarts": + decay_function_comment, + "tf.train.linear_cosine_decay": + decay_function_comment, + "tf.train.noisy_linear_cosine_decay": + decay_function_comment, + "tf.nn.embedding_lookup": + deprecate_partition_strategy_comment, + "tf.nn.embedding_lookup_sparse": + deprecate_partition_strategy_comment, + "tf.nn.nce_loss": + deprecate_partition_strategy_comment, + "tf.nn.safe_embedding_lookup_sparse": + deprecate_partition_strategy_comment, + "tf.nn.sampled_softmax_loss": + deprecate_partition_strategy_comment, + "tf.keras.estimator.model_to_estimator": + (ast_edits.WARNING, + "Estimators from will save object-based " + "checkpoints (format used by `keras_model.save_weights` and " + "`keras_model.load_weights`) by default in 2.0. To continue " + "saving name-based checkpoints, set `checkpoint_format='saver'`."), + "tf.keras.experimental.export_saved_model": + keras_experimental_export_comment, + "tf.keras.experimental.load_from_saved_model": + keras_experimental_export_comment, + "tf.keras.initializers.Zeros": + initializers_no_dtype_comment, + "tf.keras.initializers.zeros": + initializers_no_dtype_comment, + "tf.keras.initializers.Ones": + initializers_no_dtype_comment, + "tf.keras.initializers.ones": + initializers_no_dtype_comment, + "tf.keras.initializers.Constant": + initializers_no_dtype_comment, + "tf.keras.initializers.constant": + initializers_no_dtype_comment, + "tf.keras.initializers.VarianceScaling": + initializers_no_dtype_comment, + "tf.keras.initializers.Orthogonal": + initializers_no_dtype_comment, + "tf.keras.initializers.orthogonal": + initializers_no_dtype_comment, + "tf.keras.initializers.Identity": + initializers_no_dtype_comment, + "tf.keras.initializers.identity": + initializers_no_dtype_comment, + "tf.keras.initializers.glorot_uniform": + initializers_no_dtype_comment, + "tf.keras.initializers.glorot_normal": + initializers_no_dtype_comment, + "tf.initializers.zeros": + initializers_no_dtype_comment, + "tf.zeros_initializer": + initializers_no_dtype_comment, + "tf.initializers.ones": + initializers_no_dtype_comment, + "tf.ones_initializer": + initializers_no_dtype_comment, + "tf.initializers.constant": + initializers_no_dtype_comment, + "tf.constant_initializer": + initializers_no_dtype_comment, + "tf.initializers.random_uniform": + initializers_no_dtype_comment, + "tf.random_uniform_initializer": + initializers_no_dtype_comment, + "tf.initializers.random_normal": + initializers_no_dtype_comment, + "tf.random_normal_initializer": + initializers_no_dtype_comment, + "tf.initializers.truncated_normal": + initializers_no_dtype_comment, + "tf.truncated_normal_initializer": + initializers_no_dtype_comment, + "tf.initializers.variance_scaling": + initializers_no_dtype_comment, + "tf.variance_scaling_initializer": + initializers_no_dtype_comment, + "tf.initializers.orthogonal": + initializers_no_dtype_comment, + "tf.orthogonal_initializer": + initializers_no_dtype_comment, + "tf.initializers.identity": + initializers_no_dtype_comment, + "tf.glorot_uniform_initializer": + initializers_no_dtype_comment, + "tf.initializers.glorot_uniform": + initializers_no_dtype_comment, + "tf.glorot_normal_initializer": + initializers_no_dtype_comment, + "tf.initializers.glorot_normal": + initializers_no_dtype_comment, + "tf.losses.absolute_difference": + losses_comment, + "tf.losses.add_loss": + losses_comment, + "tf.losses.compute_weighted_loss": + losses_comment, + "tf.losses.cosine_distance": + losses_comment, + "tf.losses.get_losses": + losses_comment, + "tf.losses.get_regularization_loss": + losses_comment, + "tf.losses.get_regularization_losses": + losses_comment, + "tf.losses.get_total_loss": + losses_comment, + "tf.losses.hinge_loss": + losses_comment, + "tf.losses.huber_loss": + losses_comment, + "tf.losses.log_loss": + losses_comment, + "tf.losses.mean_pairwise_squared_error": + losses_comment, + "tf.losses.mean_squared_error": + losses_comment, + "tf.losses.sigmoid_cross_entropy": + losses_comment, + "tf.losses.softmax_cross_entropy": + losses_comment, + "tf.losses.sparse_softmax_cross_entropy": + losses_comment, + "tf.metrics.accuracy": + metrics_comment, + "tf.metrics.auc": + metrics_comment, + "tf.metrics.average_precision_at_k": + metrics_comment, + "tf.metrics.false_negatives": + metrics_comment, + "tf.metrics.false_negatives_at_thresholds": + metrics_comment, + "tf.metrics.false_positives": + metrics_comment, + "tf.metrics.false_positives_at_thresholds": + metrics_comment, + "tf.metrics.mean": + metrics_comment, + "tf.metrics.mean_absolute_error": + metrics_comment, + "tf.metrics.mean_cosine_distance": + metrics_comment, + "tf.metrics.mean_iou": + metrics_comment, + "tf.metrics.mean_per_class_accuracy": + metrics_comment, + "tf.metrics.mean_relative_error": + metrics_comment, + "tf.metrics.mean_squared_error": + metrics_comment, + "tf.metrics.mean_tensor": + metrics_comment, + "tf.metrics.percentage_below": + metrics_comment, + "tf.metrics.precision": + metrics_comment, + "tf.metrics.precision_at_k": + metrics_comment, + "tf.metrics.precision_at_thresholds": + metrics_comment, + "tf.metrics.precision_at_top_k": + metrics_comment, + "tf.metrics.recall": + metrics_comment, + "tf.metrics.recall_at_k": + metrics_comment, + "tf.metrics.recall_at_thresholds": + metrics_comment, + "tf.metrics.recall_at_top_k": + metrics_comment, + "tf.metrics.root_mean_squared_error": + metrics_comment, + "tf.metrics.sensitivity_at_specificity": + metrics_comment, + "tf.metrics.sparse_average_precision_at_k": + metrics_comment, + "tf.metrics.sparse_precision_at_k": + metrics_comment, + "tf.metrics.specificity_at_sensitivity": + metrics_comment, + "tf.metrics.true_negatives": + metrics_comment, + "tf.metrics.true_negatives_at_thresholds": + metrics_comment, + "tf.metrics.true_positives": + metrics_comment, + "tf.metrics.true_positives_at_thresholds": + metrics_comment, + "tf.get_variable": + (ast_edits.WARNING, + " returns ResourceVariables by default in 2.0, " + "which have well-defined semantics and are stricter about shapes. " + "You can disable this behavior by passing use_resource=False, or " + "by calling tf.compat.v1.disable_resource_variables()."), + "tf.pywrap_tensorflow": + (ast_edits.ERROR, + " cannot be converted automatically. " + "`tf.pywrap_tensorflow` will not be distributed with " + "TensorFlow 2.0, please consider an alternative in public " + "TensorFlow APIs."), + "tf.contrib.distribute.MirroredStrategy": + contrib_mirrored_strategy_warning, + "tf.distribute.MirroredStrategy": + core_mirrored_strategy_warning, + "tf.contrib.distribute.OneDeviceStrategy": + contrib_one_device_strategy_warning, + "tf.contrib.distribute.TPUStrategy": + contrib_tpu_strategy_warning, + "tf.contrib.distribute.CollectiveAllReduceStrategy": + contrib_collective_strategy_warning, + "tf.contrib.distribute.ParameterServerStrategy": + contrib_ps_strategy_warning, + "tf.summary.FileWriter": summary_api_comment, + "tf.summary.FileWriterCache": summary_api_comment, + "tf.summary.Summary": summary_api_comment, + "tf.summary.audio": summary_api_comment, + "tf.summary.histogram": summary_api_comment, + "tf.summary.image": summary_api_comment, + "tf.summary.merge": summary_api_comment, + "tf.summary.merge_all": summary_api_comment, + "tf.summary.scalar": summary_api_comment, + "tf.summary.tensor_summary": summary_api_comment, + "tf.summary.text": summary_api_comment, + "tf.saved_model.load": saved_model_load_warning, + "tf.saved_model.loader.load": saved_model_load_warning, + } + all_renames_v2.add_contrib_direct_import_support(self.function_warnings) + + for symbol, replacement in all_renames_v2.addons_symbol_mappings.items(): + warning = ( + ast_edits.WARNING, ( + "(Manual edit required) `{}` has been migrated to `{}` in " + "TensorFlow Addons. The API spec may have changed during the " + "migration. Please see https://github.com/tensorflow/addons " + "for more info.").format(symbol, replacement)) + self.function_warnings[symbol] = warning + + # Warnings that are emitted only if a specific arg is found. + self.function_arg_warnings = { + "tf.nn.conv1d": { + ("use_cudnn_on_gpu", 4): + (ast_edits.WARNING, + "use_cudnn_on_gpu has been removed, behavior is now equivalent" + "to setting it to True."), + }, + "tf.nn.conv2d": { + ("use_cudnn_on_gpu", 4): + (ast_edits.WARNING, + "use_cudnn_on_gpu has been removed, behavior is now equivalent" + "to setting it to True."), + }, + "tf.nn.conv2d_backprop_filter": { + ("use_cudnn_on_gpu", 5): + (ast_edits.WARNING, + "use_cudnn_on_gpu has been removed, behavior is now equivalent" + "to setting it to True."), + }, + "tf.nn.conv2d_backprop_input": { + ("use_cudnn_on_gpu", 5): + (ast_edits.WARNING, + "use_cudnn_on_gpu has been removed, behavior is now equivalent" + "to setting it to True."), + }, + "tf.gradients": { + ("colocate_gradients_with_ops", 4): + (ast_edits.INFO, "tf.gradients no longer takes " + "'colocate_gradients_with_ops' argument, it behaves as if it " + "was set to True."), + }, + "tf.hessians": { + ("colocate_gradients_with_ops", 3): + (ast_edits.INFO, "tf.hessians no longer takes " + "'colocate_gradients_with_ops' argument, it behaves as if it " + "was set to True."), + }, + "*.minimize": { + ("colocate_gradients_with_ops", 5): + (ast_edits.INFO, "Optimizer.minimize no longer takes " + "'colocate_gradients_with_ops' argument, it behaves as if it " + "was set to True."), + }, + "*.compute_gradients": { + ("colocate_gradients_with_ops", 4): + (ast_edits.INFO, "Optimizer.compute_gradients no " + "longer takes 'colocate_gradients_with_ops' argument, it " + "behaves as if it was set to True."), + }, + "tf.cond": { + ("strict", 3): + (ast_edits.WARNING, + "tf.cond no longer takes 'strict' argument, it behaves as " + "if was set to True.") + }, + "tf.contrib.summary.audio": { + ("family", 4): contrib_summary_family_arg_comment, + }, + "tf.contrib.summary.create_file_writer": { + ("name", 4): + (ast_edits.WARNING, + "tf.contrib.summary.create_file_writer() no longer supports " + "implicit writer re-use based on shared logdirs or resource " + "names; this call site passed a 'name' argument that has been " + "removed. The new tf.compat.v2.summary.create_file_writer() " + "replacement has a 'name' parameter but the semantics are " + "the usual ones to name the op itself and do not control " + "writer re-use; writers must be manually re-used if desired.") + }, + "tf.contrib.summary.generic": { + ("name", 0): ( + ast_edits.WARNING, + "tf.contrib.summary.generic() takes a 'name' argument for the " + "op name that also determines the emitted tag (prefixed by any " + "active name scopes), but tf.compat.v2.summary.write(), which " + "replaces it, separates these into 'tag' and 'name' arguments. " + "The 'name' argument here has been converted to 'tag' to " + "preserve a meaningful tag, but any name scopes will not be " + "reflected in the tag without manual editing."), + ("family", 3): contrib_summary_family_arg_comment, + }, + "tf.contrib.summary.histogram": { + ("family", 2): contrib_summary_family_arg_comment, + }, + "tf.contrib.summary.image": { + ("bad_color", 2): ( + ast_edits.WARNING, + "tf.contrib.summary.image no longer takes the 'bad_color' " + "argument; caller must now preprocess if needed. This call " + "site specifies a bad_color argument so it cannot be converted " + "safely."), + ("family", 4): contrib_summary_family_arg_comment, + }, + "tf.contrib.summary.scalar": { + ("family", 2): contrib_summary_family_arg_comment, + }, + "tf.image.resize": { + ("align_corners", 3): + (ast_edits.WARNING, + "align_corners is not supported by tf.image.resize, the new " + "default transformation is close to what v1 provided. If you " + "require exactly the same transformation as before, use " + "compat.v1.image.resize."), + }, + "tf.image.resize_bilinear": { + ("align_corners", 2): + (ast_edits.WARNING, + "align_corners is not supported by tf.image.resize, the new " + "default transformation is close to what v1 provided. If you " + "require exactly the same transformation as before, use " + "compat.v1.image.resize_bilinear."), + }, + "tf.image.resize_area": { + ("align_corners", 2): + (ast_edits.WARNING, + "align_corners is not supported by tf.image.resize, the new " + "default transformation is close to what v1 provided. If you " + "require exactly the same transformation as before, use " + "compat.v1.image.resize_area."), + }, + "tf.image.resize_bicubic": { + ("align_corners", 2): + (ast_edits.WARNING, + "align_corners is not supported by tf.image.resize, the new " + "default transformation is close to what v1 provided. If you " + "require exactly the same transformation as before, use " + "compat.v1.image.resize_bicubic."), + }, + "tf.image.resize_nearest_neighbor": { + ("align_corners", 2): + (ast_edits.WARNING, + "align_corners is not supported by tf.image.resize, the new " + "default transformation is close to what v1 provided. If you " + "require exactly the same transformation as before, use " + "compat.v1.image.resize_nearest_neighbor."), + }, + } + all_renames_v2.add_contrib_direct_import_support(self.function_arg_warnings) + + # pylint: disable=line-too-long + # Specially handled functions + # Each transformer is a callable which will be called with the arguments + # transformer(parent, node, full_name, name, logs) + # Where logs is a list to which (level, line, col, msg) tuples can be + # appended, full_name is the FQN of the function called (or None if that is + # unknown), name is the name of the function called (or None is that is + # unknown). node is an ast.Call node representing this function call, and + # parent is its parent in the AST. + # The function may modify node (but not parent), and must return + # - none, if nothing was modified + # - node, if node was modified in place (make sure to use + # pasta.ast_utils.replace_child to swap out children, otherwise formatting + # may get messy) + # - a replacement for node, if the whole call node was replaced. The caller + # will take care of changing parent. + # After modifying this dict, run the following to update reorders_v2.py: + # bazel run tensorflow/tools/compatibility/update:generate_v2_reorders_map + # pylint: enable=line-too-long + canned_estimator_msg_optimizer = ( + "tf.keras.optimizers.* only, so the call was converted to compat.v1. " + "Please note that tf.train.Optimizers have one-to-one correspondents " + "in tf.keras.optimizers, so you may be able to convert to the new " + "optimizers directly (See https://www.tensorflow.org/api_docs/python" + "/tf/keras/optimizers). Checkpoint compatibility is not guaranteed, " + "but there is a checkpoint converter tool that you can use.") + canned_estimator_msg = ( + "no longer takes `input_layer_partitioner` arg, and it supports " + + canned_estimator_msg_optimizer) + self.function_transformers = { + "*.make_initializable_iterator": _iterator_transformer, + "*.make_one_shot_iterator": _iterator_transformer, + "tf.nn.dropout": _dropout_transformer, + "tf.to_bfloat16": _cast_transformer, + "tf.to_complex128": _cast_transformer, + "tf.to_complex64": _cast_transformer, + "tf.to_double": _cast_transformer, + "tf.to_float": _cast_transformer, + "tf.to_int32": _cast_transformer, + "tf.to_int64": _cast_transformer, + "tf.nn.softmax_cross_entropy_with_logits": + _softmax_cross_entropy_with_logits_transformer, + "tf.image.extract_glimpse": _extract_glimpse_transformer, + "tf.image.resize_area": _image_resize_transformer, + "tf.image.resize_bicubic": _image_resize_transformer, + "tf.image.resize_bilinear": _image_resize_transformer, + "tf.image.resize_nearest_neighbor": _image_resize_transformer, + "tf.nn.fractional_avg_pool": _pool_seed_transformer, + "tf.nn.fractional_max_pool": _pool_seed_transformer, + "tf.name_scope": _name_scope_transformer, + # TODO(b/129398290) + # "tf.string_split": _string_split_transformer, + "tf.strings.split": _string_split_rtype_transformer, + "tf.estimator.BaselineEstimator": + functools.partial( + _rename_if_arg_found_transformer, + arg_name="optimizer", + message=("tf.estimator.BaselineEstimator supports " + + canned_estimator_msg_optimizer), + ), + "tf.estimator.BaselineClassifier": + functools.partial( + _rename_if_arg_found_and_add_loss_reduction_transformer, + arg_names=["optimizer"], + message=("tf.estimator.BaselineClassifier supports " + + canned_estimator_msg_optimizer), + ), + "tf.estimator.BaselineRegressor": + functools.partial( + _rename_if_arg_found_and_add_loss_reduction_transformer, + arg_names=["input_layer_partitioner", "optimizer"], + message=("tf.estimator.BaselineRegressor supports " + + canned_estimator_msg_optimizer), + ), + "tf.estimator.DNNEstimator": + functools.partial( + _rename_if_any_arg_found_transformer, + arg_names=["input_layer_partitioner", "optimizer"], + message="tf.estimator.DNNEstimator no longer takes " + "input_layer_partitioner, so the call was converted to " + "compat.v1." + ), + "tf.estimator.DNNClassifier": + functools.partial( + _rename_if_arg_found_and_add_loss_reduction_transformer, + arg_names=["input_layer_partitioner", "optimizer"], + message="tf.estimator.DNNClassifier " + canned_estimator_msg, + ), + "tf.estimator.DNNRegressor": + functools.partial( + _rename_if_arg_found_and_add_loss_reduction_transformer, + arg_names=["input_layer_partitioner", "optimizer"], + message="tf.estimator.DNNRegressor " + canned_estimator_msg, + ), + "tf.estimator.LinearEstimator": + functools.partial( + _rename_if_any_arg_found_transformer, + arg_names=["input_layer_partitioner", "optimizer"], + message="tf.estimator.LinearEstimator " + canned_estimator_msg, + ), + "tf.estimator.LinearClassifier": + functools.partial( + _rename_if_arg_found_and_add_loss_reduction_transformer, + arg_names=["input_layer_partitioner", "optimizer"], + message="tf.estimator.LinearClassifier " + canned_estimator_msg, + ), + "tf.estimator.LinearRegressor": + functools.partial( + _rename_if_arg_found_and_add_loss_reduction_transformer, + arg_names=["input_layer_partitioner", "optimizer"], + message="tf.estimator.LinearRegressor " + canned_estimator_msg, + ), + "tf.estimator.DNNLinearCombinedEstimator": + functools.partial( + _rename_if_any_arg_found_transformer, + arg_names=[ + "input_layer_partitioner", "dnn_optimizer", + "linear_optimizer" + ], + message=("tf.estimator.DNNLinearCombinedEstimator " + + canned_estimator_msg), + ), + "tf.estimator.DNNLinearCombinedClassifier": + functools.partial( + _rename_if_arg_found_and_add_loss_reduction_transformer, + arg_names=[ + "input_layer_partitioner", "dnn_optimizer", + "linear_optimizer" + ], + message=("tf.estimator.DNNLinearCombinedClassifier " + + canned_estimator_msg), + ), + "tf.estimator.DNNLinearCombinedRegressor": + functools.partial( + _rename_if_arg_found_and_add_loss_reduction_transformer, + arg_names=[ + "input_layer_partitioner", "dnn_optimizer", + "linear_optimizer" + ], + message=("tf.estimator.DNNLinearCombinedRegressor " + + canned_estimator_msg), + ), + "tf.device": functools.partial( + _rename_if_arg_found_transformer, arg_name="device_name", + arg_ok_predicate=_is_ast_str, remove_if_ok=False, + message="tf.device no longer takes functions as an argument. " + "We could not determine that the argument value is a string, so " + "the call was converted to compat.v1."), + "tf.zeros_like": functools.partial( + _rename_if_arg_found_transformer, arg_name="optimize", + arg_ok_predicate=_is_ast_true, remove_if_ok=True, + message="tf.zeros_like no longer takes an optimize argument, and " + "behaves as if optimize=True. This call site specifies something " + "other than optimize=True, so it was converted to compat.v1."), + "tf.ones_like": functools.partial( + _rename_if_arg_found_transformer, arg_name="optimize", + arg_ok_predicate=_is_ast_true, remove_if_ok=True, + message="tf.ones_like no longer takes an optimize argument, and " + "behaves as if optimize=True. This call site specifies something " + "other than optimize=True, so it was converted to compat.v1."), + "tf.while_loop": functools.partial( + _rename_if_arg_found_transformer, + arg_name="return_same_structure", + arg_ok_predicate=_is_ast_true, remove_if_ok=True, + message="tf.while_loop no longer takes 'return_same_structure' " + "argument and behaves as if return_same_structure=True. This call " + "site specifies something other than return_same_structure=True, " + "so it was converted to compat.v1."), + "tf.nn.ctc_beam_search_decoder": functools.partial( + _rename_if_arg_found_transformer, + arg_name="merge_repeated", + arg_ok_predicate=_is_ast_false, remove_if_ok=True, + message="tf.nn.ctc_beam_search_decoder no longer takes the " + "'merge_repeated' argument and behaves as if merge_repeated=False. " + "This call site specifies something other than " + "merge_repeated=False, so it was converted to compat.v1."), + "tf.nn.dilation2d": functools.partial( + _add_argument_transformer, + arg_name="data_format", + arg_value_ast=ast.Str("NHWC")), + "tf.nn.erosion2d": functools.partial( + _add_argument_transformer, + arg_name="data_format", + arg_value_ast=ast.Str("NHWC")), + "tf.contrib.summary.always_record_summaries": functools.partial( + _add_summary_recording_cond_transformer, cond="True"), + "tf.contrib.summary.audio": _add_summary_step_transformer, + "tf.contrib.summary.generic": _add_summary_step_transformer, + "tf.contrib.summary.histogram": _add_summary_step_transformer, + "tf.contrib.summary.image": _add_summary_step_transformer, + "tf.contrib.summary.never_record_summaries": functools.partial( + _add_summary_recording_cond_transformer, cond="False"), + "tf.contrib.summary.scalar": _add_summary_step_transformer, + "tf.contrib.layers.l1_regularizer": + _contrib_layers_l1_regularizer_transformer, + "tf.contrib.layers.l2_regularizer": + _contrib_layers_l2_regularizer_transformer, + "tf.contrib.layers.xavier_initializer": + _contrib_layers_xavier_initializer_transformer, + "tf.contrib.layers.xavier_initializer_conv2d": + _contrib_layers_xavier_initializer_transformer, + "tf.contrib.layers.variance_scaling_initializer": + _contrib_layers_variance_scaling_initializer_transformer, + "tf.initializers.uniform_unit_scaling": + _add_uniform_scaling_initializer_transformer, + "tf.uniform_unit_scaling_initializer": + _add_uniform_scaling_initializer_transformer, + "slim.l1_regularizer": + _contrib_layers_l1_regularizer_transformer, + "slim.l2_regularizer": + _contrib_layers_l2_regularizer_transformer, + "slim.xavier_initializer": + _contrib_layers_xavier_initializer_transformer, + "slim.xavier_initializer_conv2d": + _contrib_layers_xavier_initializer_transformer, + "slim.variance_scaling_initializer": + _contrib_layers_variance_scaling_initializer_transformer, + "tf.keras.models.save_model": functools.partial( + _add_argument_transformer, + arg_name="save_format", + arg_value_ast=ast.Str("h5")), + } + all_renames_v2.add_contrib_direct_import_support(self.function_transformers) + + self.module_deprecations = module_deprecations_v2.MODULE_DEPRECATIONS + + def preprocess(self, root_node, after_compat_v1_upgrade=False): + visitor = ast_edits.PastaAnalyzeVisitor(TFAPIImportAnalysisSpec()) + visitor.visit(root_node) + detections = set(visitor.results) + + # Upgrade explicit compat v1 imports if `upgrade_compat_v1_import` is + # enabled. Then preprocess the updated root node. + # We only do this upgrading once, because some forms of the import may + # still cause errors but aren't trivially upgradeable, and we don't want + # to enter an infinite loop. E.g. `from tensorflow.compat import v1, v2`. + if (compat_v1_import in detections and self.upgrade_compat_v1_import and + not after_compat_v1_upgrade): + CompatV1ImportReplacer().visit(root_node) + return self.preprocess(root_node, after_compat_v1_upgrade=True) + + # If we have detected the presence of imports of specific TF versions, + # We want to modify the update spec to check only module deprecations + # and skip all other conversions. + if detections: + self.function_handle = {} + self.function_reorders = {} + self.function_keyword_renames = {} + self.symbol_renames = {} + self.function_warnings = {} + self.change_to_function = {} + self.module_deprecations = module_deprecations_v2.MODULE_DEPRECATIONS + self.function_transformers = {} + self.import_renames = {} + return root_node, visitor.log, visitor.warnings_and_errors + + def clear_preprocessing(self): + self.__init__(import_rename=self.import_rename, + upgrade_compat_v1_import=self.upgrade_compat_v1_import) + + +def _is_ast_str(node): + """Determine whether this node represents a string.""" + allowed_types = [ast.Str] + if hasattr(ast, "Bytes"): + allowed_types += [ast.Bytes] + if hasattr(ast, "JoinedStr"): + allowed_types += [ast.JoinedStr] + if hasattr(ast, "FormattedValue"): + allowed_types += [ast.FormattedValue] + return isinstance(node, allowed_types) + + +def _is_ast_true(node): + if hasattr(ast, "NameConstant"): + return isinstance(node, ast.NameConstant) and node.value is True + else: + return isinstance(node, ast.Name) and node.id == "True" + + +def _is_ast_false(node): + if hasattr(ast, "NameConstant"): + return isinstance(node, ast.NameConstant) and node.value is False + else: + return isinstance(node, ast.Name) and node.id == "False" + + +# Lots of unused arguments below, since these are called in a standard manner. +# pylint: disable=unused-argument + + +def _rename_if_arg_found_transformer(parent, node, full_name, name, logs, + arg_name=None, + arg_ok_predicate=None, + remove_if_ok=False, + message=None): + """Replaces the given call with tf.compat.v1 if the given arg is found. + + This requires the function to be called with all named args, so for using + this transformer, the function should also be added to renames. + + If the arg is not found, the call site is left alone. + + If the arg is found, and if arg_ok_predicate is given, it is called with + the ast Expression representing the argument value found. If it returns + True, the function is left alone. + + If the arg is found, arg_ok_predicate is not None and returns ok, and + remove_if_ok is True, the argument is removed from the call. + + Otherwise, `compat.v1` is inserted between tf and the function name. + + Args: + parent: Parent of node. + node: ast.Call node to maybe modify. + full_name: full name of function to modify + name: name of function to modify + logs: list of logs to append to + arg_name: name of the argument to look for + arg_ok_predicate: predicate callable with the ast of the argument value, + returns whether the argument value is allowed. + remove_if_ok: remove the argument if present and ok as determined by + arg_ok_predicate. + message: message to print if a non-ok arg is found (and hence, the function + is renamed to its compat.v1 version). + + Returns: + node, if it was modified, else None. + """ + # Check whether arg is there. + arg_present, arg_value = ast_edits.get_arg_value(node, arg_name) + if not arg_present: + return + + # Check whether arg is problematic (and if not, maybe remove it). + if arg_ok_predicate and arg_ok_predicate(arg_value): + if remove_if_ok: + for i, kw in enumerate(node.keywords): + if kw.arg == arg_name: + node.keywords.pop(i) + logs.append((ast_edits.INFO, node.lineno, node.col_offset, + "Removed argument %s for function %s" % ( + arg_name, full_name or name))) + break + return node + else: + return + + # All conditions met, insert v1 and log what we did. + # We must have a full name, so the func is an attribute. + new_name = full_name.replace("tf.", "tf.compat.v1.", 1) + node.func = ast_edits.full_name_node(new_name) + logs.append(( + ast_edits.INFO, node.lineno, node.col_offset, + "Renaming %s to %s because argument %s is present. %s" % + (full_name, new_name, arg_name, message if message is not None else "") + )) + return node + + +def _add_argument_transformer(parent, node, full_name, name, logs, + arg_name, arg_value_ast): + """Adds an argument (as a final kwarg arg_name=arg_value_ast).""" + node.keywords.append(ast.keyword(arg=arg_name, value=arg_value_ast)) + logs.append(( + ast_edits.INFO, node.lineno, node.col_offset, + "Adding argument '%s' to call to %s." % (pasta.dump(node.keywords[-1]), + full_name or name) + )) + return node + + +def _iterator_transformer(parent, node, full_name, name, logs): + """Transform iterator methods to compat function calls.""" + # First, check that node.func.value is not already something we like + # (tf.compat.v1.data), or something which is handled in the rename + # (tf.data). This transformer only handles the method call to function call + # conversion. + if full_name and (full_name.startswith("tf.compat.v1.data") or + full_name.startswith("tf.data")): + return + + # This should never happen, since we're only called for Attribute nodes. + if not isinstance(node.func, ast.Attribute): + return + + # Transform from x.f(y) to tf.compat.v1.data.f(x, y) + # Fortunately, node.func.value should already have valid position info + node.args = [node.func.value] + node.args + node.func.value = ast_edits.full_name_node("tf.compat.v1.data") + + logs.append((ast_edits.WARNING, node.lineno, node.col_offset, + "Changing dataset.%s() to tf.compat.v1.data.%s(dataset). " + "Please check this transformation.\n" % (name, name))) + + return node + + +def _dropout_transformer(parent, node, full_name, name, logs): + """Replace keep_prob with 1-rate.""" + def _replace_keep_prob_node(parent, old_value): + """Replaces old_value with 1-(old_value).""" + one = ast.Num(n=1) + one.lineno = 0 + one.col_offset = 0 + new_value = ast.BinOp(left=one, op=ast.Sub(), + right=old_value) + # This copies the prefix and suffix on old_value to new_value. + pasta.ast_utils.replace_child(parent, old_value, new_value) + ast.copy_location(new_value, old_value) + # Put parentheses around keep_prob.value (and remove the old prefix/ + # suffix, they should only be around new_value). + pasta.base.formatting.set(old_value, "prefix", "(") + pasta.base.formatting.set(old_value, "suffix", ")") + + # Check if we have a keep_prob keyword arg + for keep_prob in node.keywords: + if keep_prob.arg == "keep_prob": + logs.append((ast_edits.INFO, node.lineno, node.col_offset, + "Changing keep_prob arg of tf.nn.dropout to rate\n")) + keep_prob.arg = "rate" + _replace_keep_prob_node(keep_prob, keep_prob.value) + return node + + # Maybe it was a positional arg + if len(node.args) < 2: + logs.append((ast_edits.ERROR, node.lineno, node.col_offset, + "tf.nn.dropout called without arguments, so " + "automatic fix was disabled. tf.nn.dropout has changed " + "the semantics of the second argument.")) + else: + rate_arg = ast.keyword(arg="rate", value=node.args[1]) + _replace_keep_prob_node(rate_arg, rate_arg.value) + node.keywords.append(rate_arg) + del node.args[1] + logs.append((ast_edits.INFO, node.lineno, node.col_offset, + "Changing keep_prob arg of tf.nn.dropout to rate, and " + "recomputing value.\n")) + + return node + + +def _cast_transformer(parent, node, full_name, name, logs): + """Transforms to_int and to_float to cast(..., dtype=...).""" + + # Find out the dtype to cast to from the function name + dtype_str = name[3:] + # Special cases where the full dtype is not given + if dtype_str == "float": + dtype_str = "float32" + elif dtype_str == "double": + dtype_str = "float64" + new_arg = ast.keyword(arg="dtype", + value=ast.Attribute(value=ast.Name(id="tf", + ctx=ast.Load()), + attr=dtype_str, ctx=ast.Load())) + # Ensures a valid transformation when a positional name arg is given + if len(node.args) == 2: + name_arg = ast.keyword(arg="name", + value=node.args[-1]) + node.args = node.args[:-1] + node.keywords.append(name_arg) + + # Python3 ast requires the args for the Attribute, but codegen will mess up + # the arg order if we just set them to 0. + new_arg.value.lineno = node.lineno + new_arg.value.col_offset = node.col_offset+100 + + node.keywords.append(new_arg) + if isinstance(node.func, ast.Attribute): + node.func.attr = "cast" + else: + assert isinstance(node.func, ast.Name) + node.func.id = "cast" + + logs.append((ast_edits.INFO, node.lineno, node.col_offset, + "Changed %s call to tf.cast(..., dtype=tf.%s)." % (full_name, + dtype_str))) + return node + + +def _softmax_cross_entropy_with_logits_transformer( + parent, node, full_name, name, logs): + """Wrap labels argument with stop_gradients.""" + def _wrap_label(parent, old_value): + """Wrap labels with tf.stop_gradient.""" + already_stop_grad = (isinstance(old_value, ast.Call) and + isinstance(old_value.func, ast.Attribute) and + old_value.func.attr == "stop_gradient" and + isinstance(old_value.func.value, ast.Name) and + old_value.func.value.id == "tf") + if already_stop_grad: + return False + try: + new_value = ast.Call( + ast.Name(id="tf.stop_gradient", ctx=ast.Load()), + [old_value], []) + except TypeError: + new_value = ast.Call( + ast.Name(id="tf.stop_gradient", ctx=ast.Load()), + [old_value], [], None, None) + + # This copies the prefix and suffix on old_value to new_value. + pasta.ast_utils.replace_child(parent, old_value, new_value) + ast.copy_location(new_value, old_value) + return True + + # Check if we have a labels keyword arg + for karg in node.keywords: + if karg.arg == "labels": + if _wrap_label(karg, karg.value): + logs.append((ast_edits.INFO, node.lineno, node.col_offset, + "Changing labels arg of " + "tf.nn.softmax_cross_entropy_with_logits to " + "tf.stop_gradient(labels). Please check this " + "transformation.\n")) + return node + return node + + +def _image_resize_transformer(parent, node, full_name, name, logs): + """Transforms image.resize_* to image.resize(..., method=*, ...).""" + resize_method = name[7:].upper() + new_arg = ast.keyword(arg="method", + value=ast.Attribute( + value=ast.Attribute( + value=ast.Attribute( + value=ast.Name(id="tf", ctx=ast.Load()), + attr="image", ctx=ast.Load()), + attr="ResizeMethod", ctx=ast.Load()), + attr=resize_method, ctx=ast.Load())) + + # Ensures a valid transformation when a positional name arg is given + if len(node.args) == 4: + pos_arg = ast.keyword(arg="preserve_aspect_ratio", + value=node.args[-1]) + node.args = node.args[:-1] + node.keywords.append(pos_arg) + if len(node.args) == 3: + pos_arg = ast.keyword(arg="align_corners", + value=node.args[-1]) + node.args = node.args[:-1] + + new_keywords = [] + for kw in node.keywords: + if kw.arg != "align_corners": + new_keywords.append(kw) + node.keywords = new_keywords + + # Python3 ast requires the args for the Attribute, but codegen will mess up + # the arg order if we just set them to 0. + new_arg.value.lineno = node.lineno + new_arg.value.col_offset = node.col_offset+100 + + node.keywords.append(new_arg) + if isinstance(node.func, ast.Attribute): + node.func.attr = "resize" + else: + assert isinstance(node.func, ast.Name) + node.func.id = "resize" + + logs.append((ast_edits.INFO, node.lineno, node.col_offset, + "Changed %s call to tf.image.resize(..., " + "method=tf.image.ResizeMethod.%s)." % (full_name, + resize_method))) + return node + + +def _pool_seed_transformer(parent, node, full_name, name, logs): + """Removes seed2 and deterministic, and adds non-zero seed if needed.""" + # This requires that this function uses all kwargs (add to renames!). + seed_arg = None + deterministic = False + modified = False + new_keywords = [] + + for kw in node.keywords: + if sys.version_info[:2] >= (3, 5) and isinstance(kw, ast.Starred): + pass + elif kw.arg == "seed": + seed_arg = kw + elif kw.arg == "seed2" or kw.arg == "deterministic": + lineno = getattr(kw, "lineno", node.lineno) + col_offset = getattr(kw, "col_offset", node.col_offset) + logs.append((ast_edits.INFO, lineno, col_offset, + "Removed argument %s for function %s" % ( + kw.arg, full_name or name))) + if kw.arg == "deterministic": + if not _is_ast_false(kw.value): + deterministic = True + modified = True + continue + new_keywords.append(kw) + + if deterministic: + if seed_arg is None: + new_keywords.append(ast.keyword(arg="seed", value=ast.Num(42))) + logs.add(( + ast_edits.INFO, node.lineno, node.col_offset, + "Adding seed=42 to call to %s since determinism was requested" % ( + full_name or name) + )) + else: + logs.add(( + ast_edits.WARNING, node.lineno, node.col_offset, + "The deterministic argument is deprecated for %s, pass a " + "non-zero seed for determinism. The deterministic argument is " + "present, possibly not False, and the seed is already set. The " + "converter cannot determine whether it is nonzero, please check." + )) + + if modified: + node.keywords = new_keywords + return node + else: + return + + +def _extract_glimpse_transformer(parent, node, full_name, name, logs): + + def _replace_uniform_noise_node(parent, old_value): + """Replaces old_value with 'uniform' or 'gaussian'.""" + uniform = ast.Str(s="uniform") + gaussian = ast.Str(s="gaussian") + new_value = ast.IfExp(body=uniform, test=old_value, orelse=gaussian) + # This copies the prefix and suffix on old_value to new_value. + pasta.ast_utils.replace_child(parent, old_value, new_value) + ast.copy_location(new_value, old_value) + # Put parentheses around noise.value.test (and remove the old prefix/ + # suffix, they should only be around new_value.test), so that: + # "uniform" if (a if b else c) else "gaussian" is valid. + pasta.base.formatting.set(new_value.test, "prefix", "(") + pasta.base.formatting.set(new_value.test, "suffix", ")") + + # Check if we have a uniform_noise keyword arg + for uniform_noise in node.keywords: + if uniform_noise.arg == "uniform_noise": + logs.append((ast_edits.INFO, node.lineno, node.col_offset, + "Changing uniform_noise arg of tf.image.extract_glimpse " + "to noise, and recomputing value. Please check this " + "transformation.\n")) + uniform_noise.arg = "noise" + value = "uniform" if uniform_noise.value else "gaussian" + _replace_uniform_noise_node(uniform_noise, uniform_noise.value) + return node + + # Since `noise`/`uniform_noise` is optional arg, nothing needs to be + # done if len(node.args) < 5. + if len(node.args) >= 5: + _replace_uniform_noise_node(node, node.args[5]) + logs.append((ast_edits.INFO, node.lineno, node.col_offset, + "Changing uniform_noise arg of tf.image.extract_glimpse to " + "noise, and recomputing value.\n")) + return node + +def _add_summary_step_transformer(parent, node, full_name, name, logs): + """Adds a step argument to the summary API call if not specified. + + The inserted argument value is tf.compat.v1.train.get_or_create_global_step(). + """ + for keyword_arg in node.keywords: + if keyword_arg.arg == "step": + return node + default_value = "tf.compat.v1.train.get_or_create_global_step()" + ast_value = ast.parse(default_value).body[0].value + del ast_value.lineno # hack to prevent spurious reordering of call args + node.keywords.append(ast.keyword(arg="step", value=ast_value)) + logs.append(( + ast_edits.WARNING, node.lineno, node.col_offset, + "Summary API writing function %s now requires a 'step' argument; " + "inserting default of %s." % (full_name or name, default_value))) + return node + + +def _add_summary_recording_cond_transformer(parent, node, full_name, name, logs, + cond): + """Adds cond argument to tf.contrib.summary.xxx_record_summaries(). + + This is in anticipation of them being renamed to tf.summary.record_if(), which + requires the cond argument. + """ + node.args.append(pasta.parse(cond)) + logs.append(( + ast_edits.INFO, node.lineno, node.col_offset, + "Adding `%s` argument to %s in anticipation of it being renamed to " + "tf.compat.v2.summary.record_if()" % (cond, full_name or name))) + return node + + +def _add_loss_reduction_transformer(parent, node, full_name, name, logs): + """Adds a loss_reduction argument if not specified. + + Default value for tf.estimator.*Classifier and tf.estimator.*Regressor + loss_reduction argument changed to SUM_OVER_BATCH_SIZE. So, we update + existing calls to use the old default value `tf.keras.losses.Reduction.SUM`. + + Note: to apply this transformation, symbol must be added + to reordered_function_names above. + """ + for keyword_arg in node.keywords: + if keyword_arg.arg == "loss_reduction": + return node + default_value = "tf.keras.losses.Reduction.SUM" + # Parse with pasta instead of ast to avoid emitting a spurious trailing \n. + ast_value = pasta.parse(default_value) + node.keywords.append(ast.keyword(arg="loss_reduction", value=ast_value)) + logs.append(( + ast_edits.INFO, node.lineno, node.col_offset, + "%s: Default value of loss_reduction has been changed to " + "SUM_OVER_BATCH_SIZE; inserting old default value %s.\n" + % (full_name or name, default_value))) + return node + + +def _rename_if_any_arg_found_transformer( + parent, + node, + full_name, + name, + logs, + arg_names=None, + arg_ok_predicate=None, + remove_if_ok=False, + message=None): + """Replaces the given call with tf.compat.v1 if any of the arg_names is found. + + Args: + parent: Parent of node. + node: ast.Call node to modify. + full_name: full name of function to modify. + name: name of function to modify. + logs: list of logs to append to. + arg_names: list of names of the argument to look for. + arg_ok_predicate: predicate callable with the ast of the argument value, + returns whether the argument value is allowed. + remove_if_ok: remove the argument if present and ok as determined by + arg_ok_predicate. + message: message to print if a non-ok arg is found (and hence, the function + is renamed to its compat.v1 version). + + Returns: + node, if it was modified, else None. + """ + for arg_name in arg_names: + rename_node = _rename_if_arg_found_transformer(parent, node, + full_name, name, logs, + arg_name, arg_ok_predicate, + remove_if_ok, message) + node = rename_node if rename_node else node + + return node + + +def _rename_if_arg_found_and_add_loss_reduction_transformer( + parent, + node, + full_name, + name, + logs, + arg_names=None, + arg_ok_predicate=None, + remove_if_ok=False, + message=None): + """Combination of _rename_if_arg_found and _add_loss_reduction transformers. + + Args: + parent: Parent of node. + node: ast.Call node to maybe modify. + full_name: full name of function to modify + name: name of function to modify + logs: list of logs to append to + arg_names: list of names of the argument to look for + arg_ok_predicate: predicate callable with the ast of the argument value, + returns whether the argument value is allowed. + remove_if_ok: remove the argument if present and ok as determined by + arg_ok_predicate. + message: message to print if a non-ok arg is found (and hence, the function + is renamed to its compat.v1 version). + + Returns: + node, if it was modified, else None. + """ + + node = _add_loss_reduction_transformer(parent, node, full_name, name, logs) + for arg_name in arg_names: + rename_node = _rename_if_arg_found_transformer(parent, node, full_name, + name, logs, arg_name, + arg_ok_predicate, + remove_if_ok, message) + node = rename_node if rename_node else node + + return node + + +def _add_uniform_scaling_initializer_transformer( + parent, node, full_name, name, logs): + """Updates references to uniform_unit_scaling_initializer. + + Transforms: + tf.uniform_unit_scaling_initializer(factor, seed, dtype) to + tf.compat.v1.keras.initializers.VarianceScaling( + scale=factor, distribution="uniform", seed=seed) + + Note: to apply this transformation, symbol must be added + to reordered_function_names above. + """ + for keyword_arg in node.keywords: + if keyword_arg.arg == "factor": + keyword_arg.arg = "scale" + + distribution_value = "\"uniform\"" + # Parse with pasta instead of ast to avoid emitting a spurious trailing \n. + ast_value = pasta.parse(distribution_value) + node.keywords.append(ast.keyword(arg="distribution", value=ast_value)) + + lineno = node.func.value.lineno + col_offset = node.func.value.col_offset + node.func.value = ast_edits.full_name_node("tf.compat.v1.keras.initializers") + node.func.value.lineno = lineno + node.func.value.col_offset = col_offset + node.func.attr = "VarianceScaling" + return node + + +def _contrib_layers_xavier_initializer_transformer( + parent, node, full_name, name, logs): + """Updates references to contrib.layers.xavier_initializer. + + Transforms: + tf.contrib.layers.xavier_initializer(uniform, seed, dtype) to + tf.compat.v1.keras.initializers.VarianceScaling( + scale=1.0, mode="fan_avg", + distribution=("uniform" if uniform else "truncated_normal"), + seed=seed, dtype=dtype) + + Returns: The new node + """ + def _get_distribution(old_value): + """Returns an AST matching the following: + ("uniform" if (old_value) else "truncated_normal") + """ + dist = pasta.parse("\"uniform\" if old_value else \"truncated_normal\"") + ifexpr = dist.body[0].value + pasta.ast_utils.replace_child(ifexpr, ifexpr.test, old_value) + + pasta.base.formatting.set(dist, "prefix", "(") + pasta.base.formatting.set(dist, "suffix", ")") + + return dist + + found_distribution = False + for keyword_arg in node.keywords: + if keyword_arg.arg == "uniform": + found_distribution = True + keyword_arg.arg = "distribution" + + old_value = keyword_arg.value + new_value = _get_distribution(keyword_arg.value) + + pasta.ast_utils.replace_child(keyword_arg, old_value, new_value) + + pasta.base.formatting.set(keyword_arg.value, "prefix", "(") + pasta.base.formatting.set(keyword_arg.value, "suffix", ")") + + new_keywords = [] + scale = pasta.parse("1.0") + new_keywords.append(ast.keyword(arg="scale", value=scale)) + + mode = pasta.parse("\"fan_avg\"") + new_keywords.append(ast.keyword(arg="mode", value=mode)) + + if len(node.args) >= 1: + found_distribution = True + dist = _get_distribution(node.args[0]) + new_keywords.append(ast.keyword(arg="distribution", value=dist)) + if not found_distribution: + # Parse with pasta instead of ast to avoid emitting a spurious trailing \n. + uniform_dist = pasta.parse("\"uniform\"") + new_keywords.append(ast.keyword(arg="distribution", value=uniform_dist)) + if len(node.args) >= 2: + new_keywords.append(ast.keyword(arg="seed", value=node.args[1])) + if len(node.args) >= 3: + new_keywords.append(ast.keyword(arg="dtype", value=node.args[2])) + node.args = [] + + node.keywords = new_keywords + node.keywords + + lineno = node.func.value.lineno + col_offset = node.func.value.col_offset + node.func.value = ast_edits.full_name_node("tf.compat.v1.keras.initializers") + node.func.value.lineno = lineno + node.func.value.col_offset = col_offset + node.func.attr = "VarianceScaling" + + logs.append((ast_edits.INFO, node.lineno, node.col_offset, + "Changing tf.contrib.layers xavier initializer" + " to a tf.compat.v1.keras.initializers.VarianceScaling and" + " converting arguments.\n")) + + return node + + +def _contrib_layers_variance_scaling_initializer_transformer( + parent, node, full_name, name, logs): + """Updates references to contrib.layers.variance_scaling_initializer. + + Transforms: + tf.contrib.layers.variance_scaling_initializer( + factor, mode, uniform, seed, dtype + ) to + tf.compat.v1.keras.initializers.VarianceScaling( + scale=factor, mode=mode.lower(), + distribution=("uniform" if uniform else "truncated_normal"), + seed=seed, dtype=dtype) + + And handles the case where no factor is provided and scale needs to be + set to 2.0 to match contrib's default instead of tf.keras.initializer's + default of 1.0 + """ + def _replace_distribution(parent, old_value): + """Replaces old_value: ("uniform" if (old_value) else "truncated_normal")""" + new_value = pasta.parse( + "\"uniform\" if old_value else \"truncated_normal\"") + ifexpr = new_value.body[0].value + pasta.ast_utils.replace_child(ifexpr, ifexpr.test, old_value) + + pasta.ast_utils.replace_child(parent, old_value, new_value) + + pasta.base.formatting.set(new_value, "prefix", "(") + pasta.base.formatting.set(new_value, "suffix", ")") + + def _replace_mode(parent, old_value): + """Replaces old_value with (old_value).lower().""" + new_value = pasta.parse("mode.lower()") + mode = new_value.body[0].value.func + pasta.ast_utils.replace_child(mode, mode.value, old_value) + + # This copies the prefix and suffix on old_value to new_value. + pasta.ast_utils.replace_child(parent, old_value, new_value) + + # Put parentheses around keep_prob.value (and remove the old prefix/ + # suffix, they should only be around new_value). + pasta.base.formatting.set(old_value, "prefix", "(") + pasta.base.formatting.set(old_value, "suffix", ")") + + # Need to keep track of scale because slim & keras + # have different defaults + found_scale = False + for keyword_arg in node.keywords: + if keyword_arg.arg == "factor": + keyword_arg.arg = "scale" + found_scale = True + if keyword_arg.arg == "mode": + _replace_mode(keyword_arg, keyword_arg.value) + if keyword_arg.arg == "uniform": + keyword_arg.arg = "distribution" + _replace_distribution(keyword_arg, keyword_arg.value) + + # Handle any detected positional arguments + if len(node.args) >= 1: + found_scale = True + if len(node.args) >= 2: + _replace_mode(node, node.args[1]) + if len(node.args) >= 3: + _replace_distribution(node, node.args[2]) + + # If no scale was provided, make tf 2.0 use slim's default factor + if not found_scale: + # Parse with pasta instead of ast to avoid emitting a spurious trailing \n. + scale_value = pasta.parse("2.0") + node.keywords = ([ast.keyword(arg="scale", value=scale_value)] + + node.keywords) + + lineno = node.func.value.lineno + col_offset = node.func.value.col_offset + node.func.value = ast_edits.full_name_node("tf.compat.v1.keras.initializers") + node.func.value.lineno = lineno + node.func.value.col_offset = col_offset + node.func.attr = "VarianceScaling" + + logs.append((ast_edits.INFO, node.lineno, node.col_offset, + "Changing tf.contrib.layers.variance_scaling_initializer" + " to a tf.compat.v1.keras.initializers.VarianceScaling and" + " converting arguments.\n")) + + return node + + +def _contrib_layers_l1_regularizer_transformer( + parent, node, full_name, name, logs): + """Replace slim l1 regularizer with Keras one. + + This entails renaming the 'scale' arg to 'l' and dropping any + provided scope arg. + """ + # Check if we have a scale or scope keyword arg + scope_keyword = None + for keyword in node.keywords: + if keyword.arg == "scale": + logs.append((ast_edits.INFO, node.lineno, node.col_offset, + "Renaming scale arg of regularizer\n")) + keyword.arg = "l" + if keyword.arg == "scope": + scope_keyword = keyword + + # Remove the scope keyword or arg if it is present + if scope_keyword: + logs.append((ast_edits.INFO, node.lineno, node.col_offset, + "Dropping scope arg from tf.contrib.layers.l1_regularizer," + " because it is unsupported in tf.keras.regularizers.l1\n")) + node.keywords.remove(scope_keyword) + if len(node.args) > 1: + node.args = node.args[:1] + logs.append((ast_edits.INFO, node.lineno, node.col_offset, + "Dropping scope arg from tf.contrib.layers.l1_regularizer," + " because it is unsupported in tf.keras.regularizers.l1\n")) + + lineno = node.func.value.lineno + col_offset = node.func.value.col_offset + node.func.value = ast_edits.full_name_node("tf.keras.regularizers") + node.func.value.lineno = lineno + node.func.value.col_offset = col_offset + node.func.attr = "l1" + + return node + + +def _contrib_layers_l2_regularizer_transformer( + parent, node, full_name, name, logs): + """Replace slim l2 regularizer with Keras one, with l=0.5*scale. + + Also drops the scope argument. + """ + def _replace_scale_node(parent, old_value): + """Replaces old_value with 0.5*(old_value).""" + half = ast.Num(n=0.5) + half.lineno = 0 + half.col_offset = 0 + new_value = ast.BinOp(left=half, op=ast.Mult(), + right=old_value) + # This copies the prefix and suffix on old_value to new_value. + pasta.ast_utils.replace_child(parent, old_value, new_value) + + # Put parentheses around scale.value (and remove the old prefix/ + # suffix, they should only be around new_value). + pasta.base.formatting.set(old_value, "prefix", "(") + pasta.base.formatting.set(old_value, "suffix", ")") + + # Check if we have a scale or scope keyword arg + scope_keyword = None + for keyword in node.keywords: + if keyword.arg == "scale": + keyword.arg = "l" + _replace_scale_node(keyword, keyword.value) + if keyword.arg == "scope": + scope_keyword = keyword + + # Maybe it was a positional arg + if len(node.args) >= 1: + _replace_scale_node(node, node.args[0]) + + # Remove the scope keyword or arg if it is present + if scope_keyword: + logs.append((ast_edits.INFO, node.lineno, node.col_offset, + "Dropping scope arg from tf.contrib.layers.l2_regularizer," + " because it is unsupported in tf.keras.regularizers.l2\n")) + node.keywords.remove(scope_keyword) + if len(node.args) > 1: + node.args = node.args[:1] + logs.append((ast_edits.INFO, node.lineno, node.col_offset, + "Dropping scope arg from tf.contrib.layers.l2_regularizer," + " because it is unsupported in tf.keras.regularizers.l2\n")) + + logs.append((ast_edits.INFO, node.lineno, node.col_offset, + "Multiplying scale arg of tf.contrib.layers.l2_regularizer" + " by half to what tf.keras.regularizers.l2 expects.\n")) + + lineno = node.func.value.lineno + col_offset = node.func.value.col_offset + node.func.value = ast_edits.full_name_node("tf.keras.regularizers") + node.func.value.lineno = lineno + node.func.value.col_offset = col_offset + node.func.attr = "l2" + + return node + + +def _name_scope_transformer(parent, node, full_name, name, logs): + """Fix name scope invocation to use 'default_name' and omit 'values' args.""" + + name_found, name = ast_edits.get_arg_value(node, "name", 0) + default_found, default_name = ast_edits.get_arg_value(node, "default_name", 1) + + # If an actual name was given... + if name_found and pasta.dump(name) != "None": + logs.append((ast_edits.INFO, node.lineno, node.col_offset, + "`name` passed to `name_scope`. Because you may be re-entering" + " an existing scope, it is not safe to convert automatically, " + " the v2 name_scope does not support re-entering scopes by" + " name.\n")) + # Rename to compat.v1 + new_name = "tf.compat.v1.name_scope" + logs.append((ast_edits.INFO, node.func.lineno, node.func.col_offset, + "Renamed %r to %r" % (full_name, new_name))) + new_name_node = ast_edits.full_name_node(new_name, node.func.ctx) + ast.copy_location(new_name_node, node.func) + pasta.ast_utils.replace_child(node, node.func, new_name_node) + return node + + if default_found: + # New name scope doesn't have name, but it has a default name. We use + # name=default_name, and values can be dropped (it's only for + # error reporting and useless outside of graph mode). + logs.append((ast_edits.INFO, node.lineno, node.col_offset, + "Using default_name as name in call to name_scope.\n")) + # Remove all args other than name + node.args = [] + node.keywords = [ast.keyword(arg="name", value=default_name)] + return node + + logs.append((ast_edits.ERROR, node.lineno, node.col_offset, + "name_scope call with neither name nor default_name cannot be " + "converted properly.")) + + +def _rename_to_compat_v1(node, full_name, logs, reason): + new_name = full_name.replace("tf.", "tf.compat.v1.", 1) + return _rename_func(node, full_name, new_name, logs, reason) + + +def _rename_func(node, full_name, new_name, logs, reason): + logs.append((ast_edits.INFO, node.lineno, node.col_offset, + "Renamed %r to %r: %s" % (full_name, new_name, reason))) + new_name_node = ast_edits.full_name_node(new_name, node.func.ctx) + ast.copy_location(new_name_node, node.func) + pasta.ast_utils.replace_child(node, node.func, new_name_node) + return node + + +def _string_split_transformer(parent, node, full_name, name, logs): + """Update tf.string_split arguments: skip_empty, sep, result_type, source.""" + # Check the skip_empty parameter: if not false, then use compat.v1. + for i, kw in enumerate(node.keywords): + if kw.arg == "skip_empty": + if _is_ast_false(kw.value): + logs.append((ast_edits.INFO, node.lineno, node.col_offset, + "removed argument skip_empty for tf.string_split.")) + node.keywords.pop(i) + break + else: + return _rename_to_compat_v1( + node, full_name, logs, "tf.string_split's replacement no longer " + "takes the skip_empty argument.") + + # Check the sep parameter: if it's definitely an empty string, use + # tf.strings.bytes_split(). If we can't tell, then use compat.v1. + found_sep = False + for i, kw in enumerate(node.keywords): + if kw.arg == "sep": + found_sep = True + if isinstance(kw.value, ast.Str): + if kw.value.s == "": + node = _rename_func( + node, full_name, "tf.strings.bytes_split", logs, + "Splitting bytes is not handled by tf.strings.bytes_split().") + node.keywords.pop(i) + else: + return _rename_to_compat_v1( + node, full_name, logs, + "The semantics for tf.string_split's sep parameter have changed " + "when sep is the empty string; but sep is not a string literal, " + "so we can't tell if it's an empty string.") + if not found_sep: + return _rename_to_compat_v1( + node, full_name, logs, + "The semantics for tf.string_split's sep parameter have changed " + "when sep unspecified: it now splits on all whitespace, not just " + "the space character.") + # Check the result_type parameter + return _string_split_rtype_transformer(parent, node, full_name, name, logs) + + +def _string_split_rtype_transformer(parent, node, full_name, name, logs): + """Update tf.strings.split arguments: result_type, source.""" + # Remove the "result_type" argument. + need_to_sparse = True + for i, kw in enumerate(node.keywords): + if kw.arg == "result_type": + if (isinstance(kw.value, ast.Str) and + kw.value.s in ("RaggedTensor", "SparseTensor")): + logs.append((ast_edits.INFO, node.lineno, node.col_offset, + "Removed argument result_type=%r for function %s" % + (kw.value.s, full_name or name))) + node.keywords.pop(i) + if kw.value.s == "RaggedTensor": + need_to_sparse = False + else: + return _rename_to_compat_v1( + node, full_name, logs, + "%s no longer takes the result_type parameter." % full_name) + break + + for i, kw in enumerate(node.keywords): + if kw.arg == "source": + kw.arg = "input" + + # If necessary, add a call to .to_sparse() to convert the output of + # strings.split from a RaggedTensor to a SparseTensor. + if need_to_sparse: + if (isinstance(parent, ast.Attribute) and parent.attr == "to_sparse"): + return # Prevent infinite recursion (since child nodes are transformed) + logs.append( + (ast_edits.INFO, node.lineno, node.col_offset, + "Adding call to RaggedTensor.to_sparse() to result of strings.split, " + "since it now returns a RaggedTensor.")) + node = ast.Attribute(value=copy.deepcopy(node), attr="to_sparse") + try: + node = ast.Call(node, [], []) + except TypeError: + node = ast.Call(node, [], [], None, None) + + return node diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tools/compatibility/tf_upgrade_v2_main.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tools/compatibility/tf_upgrade_v2_main.py new file mode 100644 index 0000000000000000000000000000000000000000..5ac3bf6e875c7dbbdde6a240dbb28abacd9a32c9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tools/compatibility/tf_upgrade_v2_main.py @@ -0,0 +1,206 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Upgrader for Python scripts from 1.x TensorFlow to 2.0 TensorFlow.""" + +import argparse + +from tensorflow.tools.compatibility import ast_edits +from tensorflow.tools.compatibility import ipynb +from tensorflow.tools.compatibility import tf_upgrade_v2 +from tensorflow.tools.compatibility import tf_upgrade_v2_safety + +# Make straightforward changes to convert to 2.0. In harder cases, +# use compat.v1. +_DEFAULT_MODE = "DEFAULT" + +# Convert to use compat.v1. +_SAFETY_MODE = "SAFETY" + +# Whether to rename to compat.v2 +_IMPORT_RENAME_DEFAULT = False + + +def process_file(in_filename, out_filename, upgrader): + """Process a file of type `.py` or `.ipynb`.""" + + if in_filename.endswith(".py"): + files_processed, report_text, errors = \ + upgrader.process_file(in_filename, out_filename) + elif in_filename.endswith(".ipynb"): + files_processed, report_text, errors = \ + ipynb.process_file(in_filename, out_filename, upgrader) + else: + raise NotImplementedError( + "Currently converter only supports python or ipynb") + + return files_processed, report_text, errors + + +def main(): + parser = argparse.ArgumentParser( + formatter_class=argparse.RawDescriptionHelpFormatter, + description="""Convert a TensorFlow Python file from 1.x to 2.0 + +Simple usage: + tf_upgrade_v2.py --infile foo.py --outfile bar.py + tf_upgrade_v2.py --infile foo.ipynb --outfile bar.ipynb + tf_upgrade_v2.py --intree ~/code/old --outtree ~/code/new +""") + parser.add_argument( + "--infile", + dest="input_file", + help="If converting a single file, the name of the file " + "to convert") + parser.add_argument( + "--outfile", + dest="output_file", + help="If converting a single file, the output filename.") + parser.add_argument( + "--intree", + dest="input_tree", + help="If converting a whole tree of files, the directory " + "to read from (relative or absolute).") + parser.add_argument( + "--outtree", + dest="output_tree", + help="If converting a whole tree of files, the output " + "directory (relative or absolute).") + parser.add_argument( + "--copyotherfiles", + dest="copy_other_files", + help=("If converting a whole tree of files, whether to " + "copy the other files."), + type=bool, + default=True) + parser.add_argument( + "--inplace", + dest="in_place", + help=("If converting a set of files, whether to " + "allow the conversion to be performed on the " + "input files."), + action="store_true") + parser.add_argument( + "--no_import_rename", + dest="no_import_rename", + help=("Not to rename import to compat.v2 explicitly."), + action="store_true") + parser.add_argument( + "--no_upgrade_compat_v1_import", + dest="no_upgrade_compat_v1_import", + help=("If specified, don't upgrade explicit imports of " + "`tensorflow.compat.v1 as tf` to the v2 APIs. Otherwise, " + "explicit imports of the form `tensorflow.compat.v1 as tf` will " + "be upgraded."), + action="store_true") + parser.add_argument( + "--reportfile", + dest="report_filename", + help=("The name of the file where the report log is " + "stored." + "(default: %(default)s)"), + default="report.txt") + parser.add_argument( + "--mode", + dest="mode", + choices=[_DEFAULT_MODE, _SAFETY_MODE], + help=("Upgrade script mode. Supported modes:\n" + "%s: Perform only straightforward conversions to upgrade to " + "2.0. In more difficult cases, switch to use compat.v1.\n" + "%s: Keep 1.* code intact and import compat.v1 " + "module." % + (_DEFAULT_MODE, _SAFETY_MODE)), + default=_DEFAULT_MODE) + parser.add_argument( + "--print_all", + dest="print_all", + help="Print full log to stdout instead of just printing errors", + action="store_true") + args = parser.parse_args() + + if args.mode == _SAFETY_MODE: + change_spec = tf_upgrade_v2_safety.TFAPIChangeSpec() + else: + if args.no_import_rename: + change_spec = tf_upgrade_v2.TFAPIChangeSpec( + import_rename=False, + upgrade_compat_v1_import=not args.no_upgrade_compat_v1_import) + else: + change_spec = tf_upgrade_v2.TFAPIChangeSpec( + import_rename=_IMPORT_RENAME_DEFAULT, + upgrade_compat_v1_import=not args.no_upgrade_compat_v1_import) + upgrade = ast_edits.ASTCodeUpgrader(change_spec) + + report_text = None + report_filename = args.report_filename + files_processed = 0 + if args.input_file: + if not args.in_place and not args.output_file: + raise ValueError( + "--outfile= argument is required when converting a " + "single file.") + if args.in_place and args.output_file: + raise ValueError("--outfile argument is invalid when converting in place") + output_file = args.input_file if args.in_place else args.output_file + files_processed, report_text, errors = process_file( + args.input_file, output_file, upgrade) + errors = {args.input_file: errors} + files_processed = 1 + elif args.input_tree: + if not args.in_place and not args.output_tree: + raise ValueError( + "--outtree= argument is required when converting a " + "file tree.") + if args.in_place and args.output_tree: + raise ValueError("--outtree argument is invalid when converting in place") + output_tree = args.input_tree if args.in_place else args.output_tree + files_processed, report_text, errors = upgrade.process_tree( + args.input_tree, output_tree, args.copy_other_files) + else: + parser.print_help() + if report_text: + num_errors = 0 + report = [] + for f in errors: + if errors[f]: + num_errors += len(errors[f]) + report.append("-" * 80 + "\n") + report.append("File: %s\n" % f) + report.append("-" * 80 + "\n") + report.append("\n".join(errors[f]) + "\n") + + report = ("TensorFlow 2.0 Upgrade Script\n" + "-----------------------------\n" + "Converted %d files\n" % files_processed + + "Detected %d issues that require attention" % num_errors + "\n" + + "-" * 80 + "\n") + "".join(report) + detailed_report_header = "=" * 80 + "\n" + detailed_report_header += "Detailed log follows:\n\n" + detailed_report_header += "=" * 80 + "\n" + + with open(report_filename, "w") as report_file: + report_file.write(report) + report_file.write(detailed_report_header) + report_file.write(report_text) + + if args.print_all: + print(report) + print(detailed_report_header) + print(report_text) + else: + print(report) + print("\nMake sure to read the detailed log %r\n" % report_filename) + +if __name__ == "__main__": + main() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tools/compatibility/tf_upgrade_v2_safety.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tools/compatibility/tf_upgrade_v2_safety.py new file mode 100644 index 0000000000000000000000000000000000000000..4aa05a72801aab4980407f6c808116a786358f2f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tools/compatibility/tf_upgrade_v2_safety.py @@ -0,0 +1,58 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Upgrader for Python scripts from 1.* to 2.0 TensorFlow using SAFETY mode.""" + +from tensorflow.tools.compatibility import all_renames_v2 +from tensorflow.tools.compatibility import ast_edits +from tensorflow.tools.compatibility import module_deprecations_v2 + + +class TFAPIChangeSpec(ast_edits.APIChangeSpec): + """List of maps that describe what changed in the API.""" + + def __init__(self): + self.function_keyword_renames = {} + self.symbol_renames = {} + self.change_to_function = {} + self.function_reorders = {} + self.function_warnings = {} + self.function_transformers = {} + self.module_deprecations = module_deprecations_v2.MODULE_DEPRECATIONS + + ## Inform about the addons mappings + for symbol, replacement in all_renames_v2.addons_symbol_mappings.items(): + warning = ( + ast_edits.WARNING, ( + "(Manual edit required) `{}` has been migrated to `{}` in " + "TensorFlow Addons. The API spec may have changed during the " + "migration. Please see https://github.com/tensorflow/addons " + "for more info.").format(symbol, replacement)) + self.function_warnings[symbol] = warning + + # List module renames. If changed, please update max_submodule_depth. + self.import_renames = { + "tensorflow": + ast_edits.ImportRename( + "tensorflow.compat.v1", + excluded_prefixes=[ + "tensorflow.contrib", "tensorflow.flags", + "tensorflow.compat", + "tensorflow.compat.v1", "tensorflow.compat.v2", + "tensorflow.google" + ], + ) + } + # Needs to be updated if self.import_renames is changed. + self.max_submodule_depth = 2 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tools/docs/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tools/docs/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tools/docs/doc_controls.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tools/docs/doc_controls.py new file mode 100644 index 0000000000000000000000000000000000000000..e9cc6c17edf025488e3d9d7f75f01ac44e545193 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tools/docs/doc_controls.py @@ -0,0 +1,368 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Documentation control decorators.""" + +from typing import Optional, TypeVar + +T = TypeVar("T") + + +_DEPRECATED = "_tf_docs_deprecated" + + +def set_deprecated(obj: T) -> T: + """Explicitly tag an object as deprecated for the doc generator.""" + setattr(obj, _DEPRECATED, None) + return obj + + +_INHERITABLE_HEADER = "_tf_docs_inheritable_header" + + +def inheritable_header(text): + + def _wrapped(cls): + setattr(cls, _INHERITABLE_HEADER, text) + return cls + + return _wrapped + + +def get_inheritable_header(obj) -> Optional[str]: + return getattr(obj, _INHERITABLE_HEADER, None) + + +header = inheritable_header +get_header = get_inheritable_header + +_DO_NOT_DOC = "_tf_docs_do_not_document" + + +def do_not_generate_docs(obj: T) -> T: + """A decorator: Do not generate docs for this object. + + For example the following classes: + + ``` + class Parent(object): + def method1(self): + pass + def method2(self): + pass + + class Child(Parent): + def method1(self): + pass + def method2(self): + pass + ``` + + Produce the following api_docs: + + ``` + /Parent.md + # method1 + # method2 + /Child.md + # method1 + # method2 + ``` + + This decorator allows you to skip classes or methods: + + ``` + @do_not_generate_docs + class Parent(object): + def method1(self): + pass + def method2(self): + pass + + class Child(Parent): + @do_not_generate_docs + def method1(self): + pass + def method2(self): + pass + ``` + + This will only produce the following docs: + + ``` + /Child.md + # method2 + ``` + + Note: This is implemented by adding a hidden attribute on the object, so it + cannot be used on objects which do not allow new attributes to be added. So + this decorator must go *below* `@property`, `@classmethod`, + or `@staticmethod`: + + ``` + class Example(object): + @property + @do_not_generate_docs + def x(self): + return self._x + ``` + + Args: + obj: The object to hide from the generated docs. + + Returns: + obj + """ + setattr(obj, _DO_NOT_DOC, None) + return obj + + +_DO_NOT_DOC_INHERITABLE = "_tf_docs_do_not_doc_inheritable" + + +def do_not_doc_inheritable(obj: T) -> T: + """A decorator: Do not generate docs for this method. + + This version of the decorator is "inherited" by subclasses. No docs will be + generated for the decorated method in any subclass. Even if the sub-class + overrides the method. + + For example, to ensure that `method1` is **never documented** use this + decorator on the base-class: + + ``` + class Parent(object): + @do_not_doc_inheritable + def method1(self): + pass + def method2(self): + pass + + class Child(Parent): + def method1(self): + pass + def method2(self): + pass + ``` + This will produce the following docs: + + ``` + /Parent.md + # method2 + /Child.md + # method2 + ``` + + When generating docs for a class's arributes, the `__mro__` is searched and + the attribute will be skipped if this decorator is detected on the attribute + on any class in the `__mro__`. + + Note: This is implemented by adding a hidden attribute on the object, so it + cannot be used on objects which do not allow new attributes to be added. So + this decorator must go *below* `@property`, `@classmethod`, + or `@staticmethod`: + + ``` + class Example(object): + @property + @do_not_doc_inheritable + def x(self): + return self._x + ``` + + Args: + obj: The class-attribute to hide from the generated docs. + + Returns: + obj + """ + setattr(obj, _DO_NOT_DOC_INHERITABLE, None) + return obj + + +_FOR_SUBCLASS_IMPLEMENTERS = "_tf_docs_tools_for_subclass_implementers" + + +def for_subclass_implementers(obj: T) -> T: + """A decorator: Only generate docs for this method in the defining class. + + Also group this method's docs with and `@abstractmethod` in the class's docs. + + No docs will generated for this class attribute in sub-classes. + + The canonical use case for this is `tf.keras.layers.Layer.call`: It's a + public method, essential for anyone implementing a subclass, but it should + never be called directly. + + Works on method, or other class-attributes. + + When generating docs for a class's arributes, the `__mro__` is searched and + the attribute will be skipped if this decorator is detected on the attribute + on any **parent** class in the `__mro__`. + + For example: + + ``` + class Parent(object): + @for_subclass_implementers + def method1(self): + pass + def method2(self): + pass + + class Child1(Parent): + def method1(self): + pass + def method2(self): + pass + + class Child2(Parent): + def method1(self): + pass + def method2(self): + pass + ``` + + This will produce the following docs: + + ``` + /Parent.md + # method1 + # method2 + /Child1.md + # method2 + /Child2.md + # method2 + ``` + + Note: This is implemented by adding a hidden attribute on the object, so it + cannot be used on objects which do not allow new attributes to be added. So + this decorator must go *below* `@property`, `@classmethod`, + or `@staticmethod`: + + ``` + class Example(object): + @property + @for_subclass_implementers + def x(self): + return self._x + ``` + + Args: + obj: The class-attribute to hide from the generated docs. + + Returns: + obj + """ + setattr(obj, _FOR_SUBCLASS_IMPLEMENTERS, None) + return obj + + +do_not_doc_in_subclasses = for_subclass_implementers + +_DOC_PRIVATE = "_tf_docs_doc_private" + + +def doc_private(obj: T) -> T: + """A decorator: Generates docs for private methods/functions. + + For example: + + ``` + class Try: + + @doc_controls.doc_private + def _private(self): + ... + ``` + + As a rule of thumb, private(beginning with `_`) methods/functions are + not documented. + + This decorator allows to force document a private method/function. + + Args: + obj: The class-attribute to hide from the generated docs. + + Returns: + obj + """ + + setattr(obj, _DOC_PRIVATE, None) + return obj + + +_DOC_IN_CURRENT_AND_SUBCLASSES = "_tf_docs_doc_in_current_and_subclasses" + + +def doc_in_current_and_subclasses(obj: T) -> T: + """Overrides `do_not_doc_in_subclasses` decorator. + + If this decorator is set on a child class's method whose parent's method + contains `do_not_doc_in_subclasses`, then that will be overriden and the + child method will get documented. All classes inherting from the child will + also document that method. + + For example: + + ``` + class Parent: + @do_not_doc_in_subclasses + def method1(self): + pass + def method2(self): + pass + + class Child1(Parent): + @doc_in_current_and_subclasses + def method1(self): + pass + def method2(self): + pass + + class Child2(Parent): + def method1(self): + pass + def method2(self): + pass + + class Child11(Child1): + pass + ``` + + This will produce the following docs: + + ``` + /Parent.md + # method1 + # method2 + /Child1.md + # method1 + # method2 + /Child2.md + # method2 + /Child11.md + # method1 + # method2 + ``` + + Args: + obj: The class-attribute to hide from the generated docs. + + Returns: + obj + """ + + setattr(obj, _DOC_IN_CURRENT_AND_SUBCLASSES, None) + return obj diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tools/docs/tf_doctest_lib.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tools/docs/tf_doctest_lib.py new file mode 100644 index 0000000000000000000000000000000000000000..7424de437f7e1e177ddc47669ec308d756dca7a4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tools/docs/tf_doctest_lib.py @@ -0,0 +1,224 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Run doctests for tensorflow.""" + +import doctest +import re +import textwrap + +import numpy as np + + +class _FloatExtractor(object): + """Class for extracting floats from a string. + + For example: + + >>> text_parts, floats = _FloatExtractor()("Text 1.0 Text") + >>> text_parts + ["Text ", " Text"] + >>> floats + np.array([1.0]) + """ + + # Note: non-capturing groups "(?" are not returned in matched groups, or by + # re.split. + _FLOAT_RE = re.compile( + r""" + ( # Captures the float value. + (?: + [-+]| # Start with a sign is okay anywhere. + (?: # Otherwise: + ^| # Start after the start of string + (?<=[^\w.]) # Not after a word char, or a . + ) + ) + (?: # Digits and exponent - something like: + {digits_dot_maybe_digits}{exponent}?| # "1.0" "1." "1.0e3", "1.e3" + {dot_digits}{exponent}?| # ".1" ".1e3" + {digits}{exponent}| # "1e3" + {digits}(?=j) # "300j" + ) + ) + j? # Optional j for cplx numbers, not captured. + (?= # Only accept the match if + $| # * At the end of the string, or + [^\w.] # * Next char is not a word char or "." + ) + """.format( + # Digits, a "." and optional more digits: "1.1". + digits_dot_maybe_digits=r'(?:[0-9]+\.(?:[0-9]*))', + # A "." with trailing digits ".23" + dot_digits=r'(?:\.[0-9]+)', + # digits: "12" + digits=r'(?:[0-9]+)', + # The exponent: An "e" or "E", optional sign, and at least one digit. + # "e-123", "E+12", "e12" + exponent=r'(?:[eE][-+]?[0-9]+)'), + re.VERBOSE) + + def __call__(self, string): + """Extracts floats from a string. + + >>> text_parts, floats = _FloatExtractor()("Text 1.0 Text") + >>> text_parts + ["Text ", " Text"] + >>> floats + np.array([1.0]) + + Args: + string: the string to extract floats from. + + Returns: + A (string, array) pair, where `string` has each float replaced by "..." + and `array` is a `float32` `numpy.array` containing the extracted floats. + """ + texts = [] + floats = [] + for i, part in enumerate(self._FLOAT_RE.split(string)): + if i % 2 == 0: + texts.append(part) + else: + floats.append(float(part)) + + return texts, np.array(floats) + + +class TfDoctestOutputChecker(doctest.OutputChecker, object): + """Customizes how `want` and `got` are compared, see `check_output`.""" + + def __init__(self, *args, **kwargs): + super(TfDoctestOutputChecker, self).__init__(*args, **kwargs) + self.extract_floats = _FloatExtractor() + self.text_good = None + self.float_size_good = None + + _ADDRESS_RE = re.compile(r'\bat 0x[0-9a-f]*?>') + # TODO(yashkatariya): Add other tensor's string substitutions too. + # tf.RaggedTensor doesn't need one. + _NUMPY_OUTPUT_RE = re.compile(r'', re.DOTALL) + + def _allclose(self, want, got, rtol=1e-3, atol=1e-3): + return np.allclose(want, got, rtol=rtol, atol=atol) + + def _tf_tensor_numpy_output(self, string): + modified_string = self._NUMPY_OUTPUT_RE.sub(r'\1', string) + return modified_string, modified_string != string + + MESSAGE = textwrap.dedent("""\n + ############################################################# + Check the documentation (https://www.tensorflow.org/community/contribute/docs_ref) on how to + write testable docstrings. + #############################################################""") + + def check_output(self, want, got, optionflags): + """Compares the docstring output to the output gotten by running the code. + + Python addresses in the output are replaced with wildcards. + + Float values in the output compared as using `np.allclose`: + + * Float values are extracted from the text and replaced with wildcards. + * The wildcard text is compared to the actual output. + * The float values are compared using `np.allclose`. + + The method returns `True` if both the text comparison and the numeric + comparison are successful. + + The numeric comparison will fail if either: + + * The wrong number of floats are found. + * The float values are not within tolerence. + + Args: + want: The output in the docstring. + got: The output generated after running the snippet. + optionflags: Flags passed to the doctest. + + Returns: + A bool, indicating if the check was successful or not. + """ + + # If the docstring's output is empty and there is some output generated + # after running the snippet, return True. This is because if the user + # doesn't want to display output, respect that over what the doctest wants. + if got and not want: + return True + + if want is None: + want = '' + + if want == got: + return True + + # Replace python's addresses with ellipsis (`...`) since it can change on + # each execution. + want = self._ADDRESS_RE.sub('at ...>', want) + + # Replace tf.Tensor strings with only their numpy field values. + want, want_changed = self._tf_tensor_numpy_output(want) + if want_changed: + got, _ = self._tf_tensor_numpy_output(got) + + # Separate out the floats, and replace `want` with the wild-card version + # "result=7.0" => "result=..." + want_text_parts, self.want_floats = self.extract_floats(want) + # numpy sometimes pads floats in arrays with spaces + # got: [1.2345, 2.3456, 3.0 ] want: [1.2345, 2.3456, 3.0001] + # And "normalize whitespace" only works when there's at least one space, + # so strip them and let the wildcard handle it. + want_text_parts = [part.strip(' ') for part in want_text_parts] + want_text_wild = '...'.join(want_text_parts) + if '....' in want_text_wild: + # If a float comes just after a period you'll end up four dots and the + # first three count as the ellipsis. Replace it with three dots. + want_text_wild = re.sub(r'\.\.\.\.+', '...', want_text_wild) + + # Find the floats in the string returned by the test + _, self.got_floats = self.extract_floats(got) + + self.text_good = super(TfDoctestOutputChecker, self).check_output( + want=want_text_wild, got=got, optionflags=optionflags) + if not self.text_good: + return False + + if self.want_floats.size == 0: + # If there are no floats in the "want" string, ignore all the floats in + # the result. "np.array([ ... ])" matches "np.array([ 1.0, 2.0 ])" + return True + + self.float_size_good = (self.want_floats.size == self.got_floats.size) + + if self.float_size_good: + return self._allclose(self.want_floats, self.got_floats) + else: + return False + + def output_difference(self, example, got, optionflags): + got = [got] + + # If the some of the float output is hidden with `...`, `float_size_good` + # will be False. This is because the floats extracted from the string is + # converted into a 1-D numpy array. Hence hidding floats is not allowed + # anymore. + if self.text_good: + if not self.float_size_good: + got.append("\n\nCAUTION: tf_doctest doesn't work if *some* of the " + "*float output* is hidden with a \"...\".") + + got.append(self.MESSAGE) + got = '\n'.join(got) + return (super(TfDoctestOutputChecker, + self).output_difference(example, got, optionflags)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tools/pip_package/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tools/pip_package/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tools/pip_package/setup.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tools/pip_package/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..fc5fd364c47138701f66322c23bb7f1f1b00be97 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tools/pip_package/setup.py @@ -0,0 +1,425 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License.. +# ============================================================================== +"""TensorFlow is an open source machine learning framework for everyone. + +[![Python](https://img.shields.io/pypi/pyversions/tensorflow.svg?style=plastic)](https://badge.fury.io/py/tensorflow) +[![PyPI](https://badge.fury.io/py/tensorflow.svg)](https://badge.fury.io/py/tensorflow) + +TensorFlow is an open source software library for high performance numerical +computation. Its flexible architecture allows easy deployment of computation +across a variety of platforms (CPUs, GPUs, TPUs), and from desktops to clusters +of servers to mobile and edge devices. + +Originally developed by researchers and engineers from the Google Brain team +within Google's AI organization, it comes with strong support for machine +learning and deep learning and the flexible numerical computation core is used +across many other scientific domains. TensorFlow is licensed under [Apache +2.0](https://github.com/tensorflow/tensorflow/blob/master/LICENSE). +""" + +import fnmatch +import os +import platform +import re +import sys + +from setuptools import Command +from setuptools import find_namespace_packages +from setuptools import setup +from setuptools.command.install import install as InstallCommandBase +from setuptools.dist import Distribution + + +# This version string is semver compatible, but incompatible with pip. +# For pip, we will remove all '-' characters from this string, and use the +# result for pip. +# Also update tensorflow/tensorflow.bzl and +# tensorflow/core/public/version.h +_VERSION = '2.15.1' + + +# We use the same setup.py for all tensorflow_* packages and for the nightly +# equivalents (tf_nightly_*). The package is controlled from the argument line +# when building the pip package. +project_name = 'tensorflow' +if '--project_name' in sys.argv: + project_name_idx = sys.argv.index('--project_name') + project_name = sys.argv[project_name_idx + 1] + sys.argv.remove('--project_name') + sys.argv.pop(project_name_idx) + + +collaborator_build = False +if '--collaborator_build' in sys.argv: + sys.argv.remove('--collaborator_build') + collaborator_build = True + + +# Returns standard if a tensorflow-* package is being built, and nightly if a +# tf_nightly-* package is being built. +def standard_or_nightly(standard, nightly): + return nightly if 'tf_nightly' in project_name else standard + +# All versions of TF need these packages. We indicate the widest possible range +# of package releases possible to be as up-to-date as possible as well as to +# accomodate as many pre-installed packages as possible. +# For packages that don't have yet a stable release, we pin using `~= 0.x` which +# means we accept any `0.y` version (y >= x) but not the first major release. We +# will need additional testing for that. +# NOTE: This assumes that all packages follow SemVer. If a package follows a +# different versioning scheme (e.g., PVP), we use different bound specifier and +# comment the versioning scheme. +REQUIRED_PACKAGES = [ + 'absl-py >= 1.0.0', + 'astunparse >= 1.6.0', + 'flatbuffers >= 23.5.26', + 'gast >=0.2.1,!=0.5.0,!=0.5.1,!=0.5.2', + 'google_pasta >= 0.1.1', + 'h5py >= 2.9.0', + 'libclang >= 13.0.0', + 'ml_dtypes ~= 0.3.1', + 'numpy >= 1.23.5, < 2.0.0', + 'opt_einsum >= 2.3.2', + 'packaging', + # pylint:disable=line-too-long + ( + 'protobuf>=3.20.3,<5.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5' + ), + 'setuptools', + 'six >= 1.12.0', + 'termcolor >= 1.1.0', + 'typing_extensions >= 3.6.6', + 'wrapt >= 1.11.0, < 1.15', + 'tensorflow-io-gcs-filesystem >= 0.23.1', + # grpcio does not build correctly on big-endian machines due to lack of + # BoringSSL support. + # See https://github.com/tensorflow/tensorflow/issues/17882. + 'grpcio >= 1.24.3, < 2.0' if sys.byteorder == 'little' else None, + # TensorFlow exposes the TF API for certain TF ecosystem packages like + # keras. When TF depends on those packages, the package version needs to + # match the current TF version. For tf_nightly, we install the nightly + # variant of each package instead, which must be one version ahead of the + # current release version. These also usually have "alpha" or "dev" in their + # version name. During the TF release process the version of these + # dependencies on the release branch is updated to the stable releases (RC + # or final). For example, 'keras-nightly ~= 2.14.0.dev' will be replaced by + # 'keras >= 2.14.0rc0, < 2.15' on the release branch after the branch cut. + 'tensorboard >= 2.15, < 2.16', + 'tensorflow_estimator >= 2.15.0, < 2.16', + 'keras >= 2.15.0, < 2.16' +] +REQUIRED_PACKAGES = [p for p in REQUIRED_PACKAGES if p is not None] + +FAKE_REQUIRED_PACKAGES = [ + # The depedencies here below are not actually used but are needed for + # package managers like poetry to parse as they are confused by the + # different architectures having different requirements. + # The entries here should be a simple duplicate of those in the collaborator + # build section. + standard_or_nightly('tensorflow-cpu-aws', 'tf-nightly-cpu-aws') + '==' + + _VERSION + ';platform_system=="Linux" and (platform_machine=="arm64" or ' + 'platform_machine=="aarch64")', + standard_or_nightly('tensorflow-intel', 'tf-nightly-intel') + '==' + + _VERSION + ';platform_system=="Windows"', +] + +if platform.system() == 'Linux' and platform.machine() == 'x86_64': + REQUIRED_PACKAGES.append(FAKE_REQUIRED_PACKAGES) + +if collaborator_build: + # If this is a collaborator build, then build an "installer" wheel and + # add the collaborator packages as the only dependencies. + REQUIRED_PACKAGES = [ + # Install the TensorFlow package built by AWS if the user is running + # Linux on an Aarch64 machine. + standard_or_nightly('tensorflow-cpu-aws', 'tf-nightly-cpu-aws') + '==' + + _VERSION + ';platform_system=="Linux" and (platform_machine=="arm64" or ' + 'platform_machine=="aarch64")', + # Install the TensorFlow package built by Intel if the user is on a + # Windows machine. + standard_or_nightly('tensorflow-intel', 'tf-nightly-intel') + '==' + + _VERSION + ';platform_system=="Windows"', + # Install the TensorFlow package built by Apple if the user is running + # macOS on an Apple Silicon machine. + standard_or_nightly('tensorflow-macos', 'tf-nightly-macos') + '==' + + _VERSION + ';platform_system=="Darwin" and platform_machine=="arm64"', + ] + +# Set up extra packages, which are optional sets of other Python package deps. +# E.g. "pip install tensorflow[and-cuda]" below installs the normal TF deps +# plus the CUDA libraries listed. +EXTRA_PACKAGES = {} +EXTRA_PACKAGES['and-cuda'] = [ + # TODO(nluehr): set nvidia-* versions based on build components. + 'nvidia-cublas-cu12 == 12.2.5.6', + 'nvidia-cuda-cupti-cu12 == 12.2.142', + 'nvidia-cuda-nvcc-cu12 == 12.2.140', + 'nvidia-cuda-nvrtc-cu12 == 12.2.140', + 'nvidia-cuda-runtime-cu12 == 12.2.140', + 'nvidia-cudnn-cu12 == 8.9.4.25', + 'nvidia-cufft-cu12 == 11.0.8.103', + 'nvidia-curand-cu12 == 10.3.3.141', + 'nvidia-cusolver-cu12 == 11.5.2.141', + 'nvidia-cusparse-cu12 == 12.1.2.141', + 'nvidia-nccl-cu12 == 2.16.5', + 'nvidia-nvjitlink-cu12 == 12.2.140', +] + +DOCLINES = __doc__.split('\n') + +# pylint: disable=line-too-long +CONSOLE_SCRIPTS = [ + 'toco_from_protos = tensorflow.lite.toco.python.toco_from_protos:main', + 'tflite_convert = tensorflow.lite.python.tflite_convert:main', + 'toco = tensorflow.lite.python.tflite_convert:main', + 'saved_model_cli = tensorflow.python.tools.saved_model_cli:main', + ( + 'import_pb_to_tensorboard =' + ' tensorflow.python.tools.import_pb_to_tensorboard:main' + ), + # We need to keep the TensorBoard command, even though the console script + # is now declared by the tensorboard pip package. If we remove the + # TensorBoard command, pip will inappropriately remove it during install, + # even though the command is not removed, just moved to a different wheel. + # We exclude it anyway if building tf_nightly. + standard_or_nightly('tensorboard = tensorboard.main:run_main', None), + 'tf_upgrade_v2 = tensorflow.tools.compatibility.tf_upgrade_v2_main:main', + ( + 'estimator_ckpt_converter =' + ' tensorflow_estimator.python.estimator.tools.checkpoint_converter:main' + ), +] +CONSOLE_SCRIPTS = [s for s in CONSOLE_SCRIPTS if s is not None] +# pylint: enable=line-too-long + + +class BinaryDistribution(Distribution): + + def has_ext_modules(self): + return True + + +class InstallCommand(InstallCommandBase): + """Override the dir where the headers go.""" + + def finalize_options(self): + ret = InstallCommandBase.finalize_options(self) # pylint: disable=assignment-from-no-return + self.install_headers = os.path.join(self.install_platlib, 'tensorflow', + 'include') + self.install_lib = self.install_platlib + return ret + + +class InstallHeaders(Command): + """Override how headers are copied. + + The install_headers that comes with setuptools copies all files to + the same directory. But we need the files to be in a specific directory + hierarchy for -I to work correctly. + """ + description = 'install C/C++ header files' + + user_options = [ + ('install-dir=', 'd', 'directory to install header files to'), + ('force', 'f', 'force installation (overwrite existing files)'), + ] + + boolean_options = ['force'] + + def initialize_options(self): + self.install_dir = None + self.force = 0 + self.outfiles = [] + + def finalize_options(self): + self.set_undefined_options('install', ('install_headers', 'install_dir'), + ('force', 'force')) + + def mkdir_and_copy_file(self, header): + install_dir = os.path.join(self.install_dir, os.path.dirname(header)) + # Get rid of some extra intervening directories so we can have fewer + # directories for -I + install_dir = re.sub('/google/protobuf_archive/src', '', install_dir) + + # Copy external code headers into tensorflow/include. + # A symlink would do, but the wheel file that gets created ignores + # symlink within the directory hierarchy. + # NOTE(keveman): Figure out how to customize bdist_wheel package so + # we can do the symlink. + # pylint: disable=line-too-long + external_header_locations = { + '/tensorflow/include/external/eigen_archive': '', + '/tensorflow/include/external/com_google_absl': '', + '/tensorflow/include/external/ml_dtypes': '/ml_dtypes', + '/tensorflow/include/tensorflow/compiler/xla': '/tensorflow/include/xla', + '/tensorflow/include/tensorflow/tsl': '/tensorflow/include/tsl', + } + # pylint: enable=line-too-long + + for location in external_header_locations: + if location in install_dir: + extra_dir = install_dir.replace(location, + external_header_locations[location]) + if not os.path.exists(extra_dir): + self.mkpath(extra_dir) + self.copy_file(header, extra_dir) + + if not os.path.exists(install_dir): + self.mkpath(install_dir) + return self.copy_file(header, install_dir) + + def run(self): + hdrs = self.distribution.headers + if not hdrs: + return + + self.mkpath(self.install_dir) + for header in hdrs: + (out, _) = self.mkdir_and_copy_file(header) + self.outfiles.append(out) + + def get_inputs(self): + return self.distribution.headers or [] + + def get_outputs(self): + return self.outfiles + + +def find_files(pattern, root): + """Return all the files matching pattern below root dir.""" + for dirpath, _, files in os.walk(root): + for filename in fnmatch.filter(files, pattern): + yield os.path.join(dirpath, filename) + + +so_lib_paths = [ + i for i in os.listdir('.') + if os.path.isdir(i) and fnmatch.fnmatch(i, '_solib_*') +] + +matches = [] +for path in so_lib_paths: + matches.extend(['../' + x for x in find_files('*', path) if '.py' not in x]) + +# If building a tpu package, bundle libtpu.so as part of the wheel +if '_tpu' in project_name: + matches.append('tensorflow/lib/libtpu.so') + +if os.name == 'nt': + EXTENSION_NAME = 'python/_pywrap_tensorflow_internal.pyd' +else: + EXTENSION_NAME = 'python/_pywrap_tensorflow_internal.so' + +headers = ( + list(find_files('*.proto', 'tensorflow/compiler')) + + list(find_files('*.proto', 'tensorflow/core')) + + list(find_files('*.proto', 'tensorflow/python')) + + list(find_files('*.proto', 'tensorflow/python/framework')) + + list(find_files('*.proto', 'tensorflow/tsl')) + + list(find_files('*.def', 'tensorflow/compiler')) + + list(find_files('*.h', 'tensorflow/c')) + + list(find_files('*.h', 'tensorflow/cc')) + + list(find_files('*.h', 'tensorflow/compiler')) + + list(find_files('*.h.inc', 'tensorflow/compiler')) + + list(find_files('*.h', 'tensorflow/core')) + + list(find_files('*.h', 'tensorflow/lite/kernels/shim')) + + list(find_files('*.h', 'tensorflow/python')) + + list(find_files('*.h', 'tensorflow/python/client')) + + list(find_files('*.h', 'tensorflow/python/framework')) + + list(find_files('*.h', 'tensorflow/stream_executor')) + + list(find_files('*.h', 'tensorflow/compiler/xla/stream_executor')) + + list(find_files('*.h', 'tensorflow/tsl')) + + list(find_files('*.h', 'google/com_google_protobuf/src')) + + list(find_files('*.inc', 'google/com_google_protobuf/src')) + + list(find_files('*', 'third_party/eigen3')) + + list(find_files('*', 'third_party/gpus')) + + list(find_files('*.h', 'tensorflow/include/external/com_google_absl')) + + list(find_files('*.inc', 'tensorflow/include/external/com_google_absl')) + + list(find_files('*', 'tensorflow/include/external/eigen_archive')) + + list(find_files('*.h', 'tensorflow/include/external/ml_dtypes'))) + +# Quite a lot of setup() options are different if this is a collaborator package +# build. We explicitly list the differences here, then unpack the dict as +# options at the end of the call to setup() below. For what each keyword does, +# see https://setuptools.pypa.io/en/latest/references/keywords.html. +if collaborator_build: + collaborator_build_dependent_options = { + 'cmdclass': {}, + 'distclass': None, + 'entry_points': {}, + 'headers': [], + 'include_package_data': None, + 'packages': [], + 'package_data': {}, + } +else: + collaborator_build_dependent_options = { + 'cmdclass': { + 'install_headers': InstallHeaders, + 'install': InstallCommand, + }, + 'distclass': BinaryDistribution, + 'entry_points': { + 'console_scripts': CONSOLE_SCRIPTS, + }, + 'headers': headers, + 'include_package_data': True, + 'packages': find_namespace_packages(), + 'package_data': { + 'tensorflow': [EXTENSION_NAME] + matches, + }, + } + +setup( + name=project_name, + version=_VERSION.replace('-', ''), + description=DOCLINES[0], + long_description='\n'.join(DOCLINES[2:]), + long_description_content_type='text/markdown', + url='https://www.tensorflow.org/', + download_url='https://github.com/tensorflow/tensorflow/tags', + author='Google Inc.', + author_email='packages@tensorflow.org', + install_requires=REQUIRED_PACKAGES, + extras_require=EXTRA_PACKAGES, + # Add in any packaged data. + zip_safe=False, + # Supported Python versions + python_requires='>=3.9', + # PyPI package information. + classifiers=sorted([ + 'Development Status :: 5 - Production/Stable', + # TODO(angerson) Add IFTTT when possible + 'Environment :: GPU :: NVIDIA CUDA :: 11.8', + 'Intended Audience :: Developers', + 'Intended Audience :: Education', + 'Intended Audience :: Science/Research', + 'License :: OSI Approved :: Apache Software License', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.9', + 'Programming Language :: Python :: 3.10', + 'Programming Language :: Python :: 3.11', + 'Programming Language :: Python :: 3 :: Only', + 'Topic :: Scientific/Engineering', + 'Topic :: Scientific/Engineering :: Mathematics', + 'Topic :: Scientific/Engineering :: Artificial Intelligence', + 'Topic :: Software Development', + 'Topic :: Software Development :: Libraries', + 'Topic :: Software Development :: Libraries :: Python Modules', + ]), + license='Apache 2.0', + keywords='tensorflow tensor machine learning', + **collaborator_build_dependent_options +) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tsl/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tsl/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tsl/profiler/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tsl/profiler/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tsl/profiler/protobuf/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tsl/profiler/protobuf/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tsl/profiler/protobuf/profile_pb2.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tsl/profiler/protobuf/profile_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..38e93c7ceda0c3431e62659dd34e4a05e79d4d6c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tsl/profiler/protobuf/profile_pb2.py @@ -0,0 +1,39 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: tsl/profiler/protobuf/profile.proto +"""Generated protocol buffer code.""" +from google.protobuf.internal import builder as _builder +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n#tsl/profiler/protobuf/profile.proto\x12\x17tensorflow.tfprof.pprof\"\xf3\x03\n\x07Profile\x12\x37\n\x0bsample_type\x18\x01 \x03(\x0b\x32\".tensorflow.tfprof.pprof.ValueType\x12/\n\x06sample\x18\x02 \x03(\x0b\x32\x1f.tensorflow.tfprof.pprof.Sample\x12\x31\n\x07mapping\x18\x03 \x03(\x0b\x32 .tensorflow.tfprof.pprof.Mapping\x12\x33\n\x08location\x18\x04 \x03(\x0b\x32!.tensorflow.tfprof.pprof.Location\x12\x33\n\x08\x66unction\x18\x05 \x03(\x0b\x32!.tensorflow.tfprof.pprof.Function\x12\x14\n\x0cstring_table\x18\x06 \x03(\t\x12\x13\n\x0b\x64rop_frames\x18\x07 \x01(\x03\x12\x13\n\x0bkeep_frames\x18\x08 \x01(\x03\x12\x12\n\ntime_nanos\x18\t \x01(\x03\x12\x16\n\x0e\x64uration_nanos\x18\n \x01(\x03\x12\x37\n\x0bperiod_type\x18\x0b \x01(\x0b\x32\".tensorflow.tfprof.pprof.ValueType\x12\x0e\n\x06period\x18\x0c \x01(\x03\x12\x0f\n\x07\x63omment\x18\r \x03(\x03\x12\x1b\n\x13\x64\x65\x66\x61ult_sample_type\x18\x0e \x01(\x03\"\'\n\tValueType\x12\x0c\n\x04type\x18\x01 \x01(\x03\x12\x0c\n\x04unit\x18\x02 \x01(\x03\"[\n\x06Sample\x12\x13\n\x0blocation_id\x18\x01 \x03(\x04\x12\r\n\x05value\x18\x02 \x03(\x03\x12-\n\x05label\x18\x03 \x03(\x0b\x32\x1e.tensorflow.tfprof.pprof.Label\".\n\x05Label\x12\x0b\n\x03key\x18\x01 \x01(\x03\x12\x0b\n\x03str\x18\x02 \x01(\x03\x12\x0b\n\x03num\x18\x03 \x01(\x03\"\xdd\x01\n\x07Mapping\x12\n\n\x02id\x18\x01 \x01(\x04\x12\x14\n\x0cmemory_start\x18\x02 \x01(\x04\x12\x14\n\x0cmemory_limit\x18\x03 \x01(\x04\x12\x13\n\x0b\x66ile_offset\x18\x04 \x01(\x04\x12\x10\n\x08\x66ilename\x18\x05 \x01(\x03\x12\x10\n\x08\x62uild_id\x18\x06 \x01(\x03\x12\x15\n\rhas_functions\x18\x07 \x01(\x08\x12\x15\n\rhas_filenames\x18\x08 \x01(\x08\x12\x18\n\x10has_line_numbers\x18\t \x01(\x08\x12\x19\n\x11has_inline_frames\x18\n \x01(\x08\"h\n\x08Location\x12\n\n\x02id\x18\x01 \x01(\x04\x12\x12\n\nmapping_id\x18\x02 \x01(\x04\x12\x0f\n\x07\x61\x64\x64ress\x18\x03 \x01(\x04\x12+\n\x04line\x18\x04 \x03(\x0b\x32\x1d.tensorflow.tfprof.pprof.Line\")\n\x04Line\x12\x13\n\x0b\x66unction_id\x18\x01 \x01(\x04\x12\x0c\n\x04line\x18\x02 \x01(\x03\"_\n\x08\x46unction\x12\n\n\x02id\x18\x01 \x01(\x04\x12\x0c\n\x04name\x18\x02 \x01(\x03\x12\x13\n\x0bsystem_name\x18\x03 \x01(\x03\x12\x10\n\x08\x66ilename\x18\x04 \x01(\x03\x12\x12\n\nstart_line\x18\x05 \x01(\x03\x62\x06proto3') + +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'tsl.profiler.protobuf.profile_pb2', globals()) +if _descriptor._USE_C_DESCRIPTORS == False: + + DESCRIPTOR._options = None + _PROFILE._serialized_start=65 + _PROFILE._serialized_end=564 + _VALUETYPE._serialized_start=566 + _VALUETYPE._serialized_end=605 + _SAMPLE._serialized_start=607 + _SAMPLE._serialized_end=698 + _LABEL._serialized_start=700 + _LABEL._serialized_end=746 + _MAPPING._serialized_start=749 + _MAPPING._serialized_end=970 + _LOCATION._serialized_start=972 + _LOCATION._serialized_end=1076 + _LINE._serialized_start=1078 + _LINE._serialized_end=1119 + _FUNCTION._serialized_start=1121 + _FUNCTION._serialized_end=1216 +# @@protoc_insertion_point(module_scope) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tsl/profiler/protobuf/profiler_options_pb2.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tsl/profiler/protobuf/profiler_options_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..5ec6b5c1ce3ccae9291b81c00f8a5030afbf2178 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tsl/profiler/protobuf/profiler_options_pb2.py @@ -0,0 +1,29 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: tsl/profiler/protobuf/profiler_options.proto +"""Generated protocol buffer code.""" +from google.protobuf.internal import builder as _builder +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n,tsl/profiler/protobuf/profiler_options.proto\x12\ntensorflow\"\x83\x03\n\x0eProfileOptions\x12\x0f\n\x07version\x18\x05 \x01(\r\x12:\n\x0b\x64\x65vice_type\x18\x06 \x01(\x0e\x32%.tensorflow.ProfileOptions.DeviceType\x12\x1b\n\x13include_dataset_ops\x18\x01 \x01(\x08\x12\x19\n\x11host_tracer_level\x18\x02 \x01(\r\x12\x1b\n\x13\x64\x65vice_tracer_level\x18\x03 \x01(\r\x12\x1b\n\x13python_tracer_level\x18\x04 \x01(\r\x12\x18\n\x10\x65nable_hlo_proto\x18\x07 \x01(\x08\x12\x1a\n\x12start_timestamp_ns\x18\x08 \x01(\x04\x12\x13\n\x0b\x64uration_ms\x18\t \x01(\x04\x12\x17\n\x0frepository_path\x18\n \x01(\t\"N\n\nDeviceType\x12\x0f\n\x0bUNSPECIFIED\x10\x00\x12\x07\n\x03\x43PU\x10\x01\x12\x07\n\x03GPU\x10\x02\x12\x07\n\x03TPU\x10\x03\x12\x14\n\x10PLUGGABLE_DEVICE\x10\x04\"\xd0\x01\n#RemoteProfilerSessionManagerOptions\x12\x34\n\x10profiler_options\x18\x01 \x01(\x0b\x32\x1a.tensorflow.ProfileOptions\x12\x19\n\x11service_addresses\x18\x02 \x03(\t\x12%\n\x1dsession_creation_timestamp_ns\x18\x03 \x01(\x04\x12\x1f\n\x17max_session_duration_ms\x18\x04 \x01(\x04\x12\x10\n\x08\x64\x65lay_ms\x18\x05 \x01(\x04\x62\x06proto3') + +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'tsl.profiler.protobuf.profiler_options_pb2', globals()) +if _descriptor._USE_C_DESCRIPTORS == False: + + DESCRIPTOR._options = None + _PROFILEOPTIONS._serialized_start=61 + _PROFILEOPTIONS._serialized_end=448 + _PROFILEOPTIONS_DEVICETYPE._serialized_start=370 + _PROFILEOPTIONS_DEVICETYPE._serialized_end=448 + _REMOTEPROFILERSESSIONMANAGEROPTIONS._serialized_start=451 + _REMOTEPROFILERSESSIONMANAGEROPTIONS._serialized_end=659 +# @@protoc_insertion_point(module_scope) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tsl/profiler/protobuf/trace_events_pb2.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tsl/profiler/protobuf/trace_events_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..826ff181c70935b1fba8ba2930d2d335eea76da9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tsl/profiler/protobuf/trace_events_pb2.py @@ -0,0 +1,44 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: tsl/profiler/protobuf/trace_events.proto +"""Generated protocol buffer code.""" +from google.protobuf.internal import builder as _builder +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n(tsl/profiler/protobuf/trace_events.proto\x12\x0ctsl.profiler\"\xb0\x01\n\x05Trace\x12\x31\n\x07\x64\x65vices\x18\x01 \x03(\x0b\x32 .tsl.profiler.Trace.DevicesEntry\x12.\n\x0ctrace_events\x18\x04 \x03(\x0b\x32\x18.tsl.profiler.TraceEvent\x1a\x44\n\x0c\x44\x65vicesEntry\x12\x0b\n\x03key\x18\x01 \x01(\r\x12#\n\x05value\x18\x02 \x01(\x0b\x32\x14.tsl.profiler.Device:\x02\x38\x01\"\xab\x01\n\x06\x44\x65vice\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x11\n\tdevice_id\x18\x02 \x01(\r\x12\x36\n\tresources\x18\x03 \x03(\x0b\x32#.tsl.profiler.Device.ResourcesEntry\x1aH\n\x0eResourcesEntry\x12\x0b\n\x03key\x18\x01 \x01(\r\x12%\n\x05value\x18\x02 \x01(\x0b\x32\x16.tsl.profiler.Resource:\x02\x38\x01\"A\n\x08Resource\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x13\n\x0bresource_id\x18\x02 \x01(\r\x12\x12\n\nsort_index\x18\x03 \x01(\r\"\xcc\x01\n\nTraceEvent\x12\x11\n\tdevice_id\x18\x01 \x01(\r\x12\x13\n\x0bresource_id\x18\x02 \x01(\r\x12\x0c\n\x04name\x18\x03 \x01(\t\x12\x14\n\x0ctimestamp_ps\x18\t \x01(\x04\x12\x13\n\x0b\x64uration_ps\x18\n \x01(\x04\x12\x30\n\x04\x61rgs\x18\x0b \x03(\x0b\x32\".tsl.profiler.TraceEvent.ArgsEntry\x1a+\n\tArgsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x42|\n\x18org.tensorflow.frameworkB\x11TraceEventsProtosP\x01ZHgithub.com/tensorflow/tensorflow/tensorflow/go/core/core_protos_go_proto\xf8\x01\x01\x62\x06proto3') + +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'tsl.profiler.protobuf.trace_events_pb2', globals()) +if _descriptor._USE_C_DESCRIPTORS == False: + + DESCRIPTOR._options = None + DESCRIPTOR._serialized_options = b'\n\030org.tensorflow.frameworkB\021TraceEventsProtosP\001ZHgithub.com/tensorflow/tensorflow/tensorflow/go/core/core_protos_go_proto\370\001\001' + _TRACE_DEVICESENTRY._options = None + _TRACE_DEVICESENTRY._serialized_options = b'8\001' + _DEVICE_RESOURCESENTRY._options = None + _DEVICE_RESOURCESENTRY._serialized_options = b'8\001' + _TRACEEVENT_ARGSENTRY._options = None + _TRACEEVENT_ARGSENTRY._serialized_options = b'8\001' + _TRACE._serialized_start=59 + _TRACE._serialized_end=235 + _TRACE_DEVICESENTRY._serialized_start=167 + _TRACE_DEVICESENTRY._serialized_end=235 + _DEVICE._serialized_start=238 + _DEVICE._serialized_end=409 + _DEVICE_RESOURCESENTRY._serialized_start=337 + _DEVICE_RESOURCESENTRY._serialized_end=409 + _RESOURCE._serialized_start=411 + _RESOURCE._serialized_end=476 + _TRACEEVENT._serialized_start=479 + _TRACEEVENT._serialized_end=683 + _TRACEEVENT_ARGSENTRY._serialized_start=640 + _TRACEEVENT_ARGSENTRY._serialized_end=683 +# @@protoc_insertion_point(module_scope) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tsl/profiler/protobuf/xplane_pb2.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tsl/profiler/protobuf/xplane_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..048b3c97467988bbc309af7b87bea0d8b8088984 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tsl/profiler/protobuf/xplane_pb2.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: tsl/profiler/protobuf/xplane.proto +"""Generated protocol buffer code.""" +from google.protobuf.internal import builder as _builder +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\"tsl/profiler/protobuf/xplane.proto\x12\x13tensorflow.profiler\"j\n\x06XSpace\x12+\n\x06planes\x18\x01 \x03(\x0b\x32\x1b.tensorflow.profiler.XPlane\x12\x0e\n\x06\x65rrors\x18\x02 \x03(\t\x12\x10\n\x08warnings\x18\x03 \x03(\t\x12\x11\n\thostnames\x18\x04 \x03(\t\"\xba\x03\n\x06XPlane\x12\n\n\x02id\x18\x01 \x01(\x03\x12\x0c\n\x04name\x18\x02 \x01(\t\x12)\n\x05lines\x18\x03 \x03(\x0b\x32\x1a.tensorflow.profiler.XLine\x12\x46\n\x0e\x65vent_metadata\x18\x04 \x03(\x0b\x32..tensorflow.profiler.XPlane.EventMetadataEntry\x12\x44\n\rstat_metadata\x18\x05 \x03(\x0b\x32-.tensorflow.profiler.XPlane.StatMetadataEntry\x12)\n\x05stats\x18\x06 \x03(\x0b\x32\x1a.tensorflow.profiler.XStat\x1aY\n\x12\x45ventMetadataEntry\x12\x0b\n\x03key\x18\x01 \x01(\x03\x12\x32\n\x05value\x18\x02 \x01(\x0b\x32#.tensorflow.profiler.XEventMetadata:\x02\x38\x01\x1aW\n\x11StatMetadataEntry\x12\x0b\n\x03key\x18\x01 \x01(\x03\x12\x31\n\x05value\x18\x02 \x01(\x0b\x32\".tensorflow.profiler.XStatMetadata:\x02\x38\x01\"\xbb\x01\n\x05XLine\x12\n\n\x02id\x18\x01 \x01(\x03\x12\x12\n\ndisplay_id\x18\n \x01(\x03\x12\x0c\n\x04name\x18\x02 \x01(\t\x12\x14\n\x0c\x64isplay_name\x18\x0b \x01(\t\x12\x14\n\x0ctimestamp_ns\x18\x03 \x01(\x03\x12\x13\n\x0b\x64uration_ps\x18\t \x01(\x03\x12+\n\x06\x65vents\x18\x04 \x03(\x0b\x32\x1b.tensorflow.profiler.XEventJ\x04\x08\x05\x10\x06J\x04\x08\x06\x10\x07J\x04\x08\x07\x10\x08J\x04\x08\x08\x10\t\"\x95\x01\n\x06XEvent\x12\x13\n\x0bmetadata_id\x18\x01 \x01(\x03\x12\x13\n\toffset_ps\x18\x02 \x01(\x03H\x00\x12\x19\n\x0fnum_occurrences\x18\x05 \x01(\x03H\x00\x12\x13\n\x0b\x64uration_ps\x18\x03 \x01(\x03\x12)\n\x05stats\x18\x04 \x03(\x0b\x32\x1a.tensorflow.profiler.XStatB\x06\n\x04\x64\x61ta\"\xad\x01\n\x05XStat\x12\x13\n\x0bmetadata_id\x18\x01 \x01(\x03\x12\x16\n\x0c\x64ouble_value\x18\x02 \x01(\x01H\x00\x12\x16\n\x0cuint64_value\x18\x03 \x01(\x04H\x00\x12\x15\n\x0bint64_value\x18\x04 \x01(\x03H\x00\x12\x13\n\tstr_value\x18\x05 \x01(\tH\x00\x12\x15\n\x0b\x62ytes_value\x18\x06 \x01(\x0cH\x00\x12\x13\n\tref_value\x18\x07 \x01(\x04H\x00\x42\x07\n\x05value\"\x8f\x01\n\x0eXEventMetadata\x12\n\n\x02id\x18\x01 \x01(\x03\x12\x0c\n\x04name\x18\x02 \x01(\t\x12\x14\n\x0c\x64isplay_name\x18\x04 \x01(\t\x12\x10\n\x08metadata\x18\x03 \x01(\x0c\x12)\n\x05stats\x18\x05 \x03(\x0b\x32\x1a.tensorflow.profiler.XStat\x12\x10\n\x08\x63hild_id\x18\x06 \x03(\x03\">\n\rXStatMetadata\x12\n\n\x02id\x18\x01 \x01(\x03\x12\x0c\n\x04name\x18\x02 \x01(\t\x12\x13\n\x0b\x64\x65scription\x18\x03 \x01(\tB\x03\xf8\x01\x01\x62\x06proto3') + +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'tsl.profiler.protobuf.xplane_pb2', globals()) +if _descriptor._USE_C_DESCRIPTORS == False: + + DESCRIPTOR._options = None + DESCRIPTOR._serialized_options = b'\370\001\001' + _XPLANE_EVENTMETADATAENTRY._options = None + _XPLANE_EVENTMETADATAENTRY._serialized_options = b'8\001' + _XPLANE_STATMETADATAENTRY._options = None + _XPLANE_STATMETADATAENTRY._serialized_options = b'8\001' + _XSPACE._serialized_start=59 + _XSPACE._serialized_end=165 + _XPLANE._serialized_start=168 + _XPLANE._serialized_end=610 + _XPLANE_EVENTMETADATAENTRY._serialized_start=432 + _XPLANE_EVENTMETADATAENTRY._serialized_end=521 + _XPLANE_STATMETADATAENTRY._serialized_start=523 + _XPLANE_STATMETADATAENTRY._serialized_end=610 + _XLINE._serialized_start=613 + _XLINE._serialized_end=800 + _XEVENT._serialized_start=803 + _XEVENT._serialized_end=952 + _XSTAT._serialized_start=955 + _XSTAT._serialized_end=1128 + _XEVENTMETADATA._serialized_start=1131 + _XEVENTMETADATA._serialized_end=1274 + _XSTATMETADATA._serialized_start=1276 + _XSTATMETADATA._serialized_end=1338 +# @@protoc_insertion_point(module_scope) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tsl/protobuf/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tsl/protobuf/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tsl/protobuf/bfc_memory_map_pb2.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tsl/protobuf/bfc_memory_map_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..cdd4eeb6f88e6b03c1d59ab4956d9e4aef6e7f1d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tsl/protobuf/bfc_memory_map_pb2.py @@ -0,0 +1,34 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: tsl/protobuf/bfc_memory_map.proto +"""Generated protocol buffer code.""" +from google.protobuf.internal import builder as _builder +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n!tsl/protobuf/bfc_memory_map.proto\x12\ntensorflow\"\x92\x01\n\x11MemAllocatorStats\x12\x12\n\nnum_allocs\x18\x01 \x01(\x03\x12\x14\n\x0c\x62ytes_in_use\x18\x02 \x01(\x03\x12\x19\n\x11peak_bytes_in_use\x18\x03 \x01(\x03\x12\x1a\n\x12largest_alloc_size\x18\x04 \x01(\x03\x12\x1c\n\x14\x66ragmentation_metric\x18\x05 \x01(\x02\"\xae\x01\n\x08MemChunk\x12\x0f\n\x07\x61\x64\x64ress\x18\x01 \x01(\x04\x12\x0c\n\x04size\x18\x02 \x01(\x03\x12\x16\n\x0erequested_size\x18\x03 \x01(\x03\x12\x0b\n\x03\x62in\x18\x04 \x01(\x05\x12\x0f\n\x07op_name\x18\x05 \x01(\t\x12\x16\n\x0e\x66reed_at_count\x18\x06 \x01(\x04\x12\x14\n\x0c\x61\x63tion_count\x18\x07 \x01(\x04\x12\x0e\n\x06in_use\x18\x08 \x01(\x08\x12\x0f\n\x07step_id\x18\t \x01(\x04\"\x8b\x01\n\nBinSummary\x12\x0b\n\x03\x62in\x18\x01 \x01(\x05\x12\x1a\n\x12total_bytes_in_use\x18\x02 \x01(\x03\x12\x1a\n\x12total_bytes_in_bin\x18\x03 \x01(\x03\x12\x1b\n\x13total_chunks_in_use\x18\x04 \x01(\x03\x12\x1b\n\x13total_chunks_in_bin\x18\x05 \x01(\x03\".\n\x08SnapShot\x12\x14\n\x0c\x61\x63tion_count\x18\x01 \x01(\x04\x12\x0c\n\x04size\x18\x02 \x01(\x03\"\xcd\x01\n\nMemoryDump\x12\x16\n\x0e\x61llocator_name\x18\x01 \x01(\t\x12+\n\x0b\x62in_summary\x18\x02 \x03(\x0b\x32\x16.tensorflow.BinSummary\x12#\n\x05\x63hunk\x18\x03 \x03(\x0b\x32\x14.tensorflow.MemChunk\x12\'\n\tsnap_shot\x18\x04 \x03(\x0b\x32\x14.tensorflow.SnapShot\x12,\n\x05stats\x18\x05 \x01(\x0b\x32\x1d.tensorflow.MemAllocatorStatsB@Z>github.com/google/tsl/tsl/go/protobuf/for_core_protos_go_protob\x06proto3') + +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'tsl.protobuf.bfc_memory_map_pb2', globals()) +if _descriptor._USE_C_DESCRIPTORS == False: + + DESCRIPTOR._options = None + DESCRIPTOR._serialized_options = b'Z>github.com/google/tsl/tsl/go/protobuf/for_core_protos_go_proto' + _MEMALLOCATORSTATS._serialized_start=50 + _MEMALLOCATORSTATS._serialized_end=196 + _MEMCHUNK._serialized_start=199 + _MEMCHUNK._serialized_end=373 + _BINSUMMARY._serialized_start=376 + _BINSUMMARY._serialized_end=515 + _SNAPSHOT._serialized_start=517 + _SNAPSHOT._serialized_end=563 + _MEMORYDUMP._serialized_start=566 + _MEMORYDUMP._serialized_end=771 +# @@protoc_insertion_point(module_scope) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tsl/protobuf/coordination_config_pb2.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tsl/protobuf/coordination_config_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..6b812d255fb1dacd29f9d8b53296361bd91ce3ae --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tsl/protobuf/coordination_config_pb2.py @@ -0,0 +1,28 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: tsl/protobuf/coordination_config.proto +"""Generated protocol buffer code.""" +from google.protobuf.internal import builder as _builder +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n&tsl/protobuf/coordination_config.proto\x12\ntensorflow\"1\n\x0e\x43oordinatedJob\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x11\n\tnum_tasks\x18\x02 \x01(\x05\"\xa0\x03\n\x19\x43oordinationServiceConfig\x12\x14\n\x0cservice_type\x18\x01 \x01(\t\x12\x16\n\x0eservice_leader\x18\x02 \x01(\t\x12\x1b\n\x13\x65nable_health_check\x18\x03 \x01(\x08\x12&\n\x1e\x63luster_register_timeout_in_ms\x18\x04 \x01(\x03\x12\x1f\n\x17heartbeat_timeout_in_ms\x18\x05 \x01(\x03\x12\x38\n\x14\x63oordinated_job_list\x18\n \x03(\x0b\x32\x1a.tensorflow.CoordinatedJob\x12&\n\x1eshutdown_barrier_timeout_in_ms\x18\x07 \x01(\x03\x12*\n\"agent_destruction_without_shutdown\x18\x08 \x01(\x08\x12\x18\n\x10recoverable_jobs\x18\t \x03(\t\x12*\n\"allow_new_incarnation_to_reconnect\x18\x0b \x01(\x08\x12\x15\n\rforce_disable\x18\x0c \x01(\x08J\x04\x08\x06\x10\x07\x42WZUgithub.com/tensorflow/tensorflow/tensorflow/go/core/protobuf/for_core_protos_go_protob\x06proto3') + +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'tsl.protobuf.coordination_config_pb2', globals()) +if _descriptor._USE_C_DESCRIPTORS == False: + + DESCRIPTOR._options = None + DESCRIPTOR._serialized_options = b'ZUgithub.com/tensorflow/tensorflow/tensorflow/go/core/protobuf/for_core_protos_go_proto' + _COORDINATEDJOB._serialized_start=54 + _COORDINATEDJOB._serialized_end=103 + _COORDINATIONSERVICECONFIG._serialized_start=106 + _COORDINATIONSERVICECONFIG._serialized_end=522 +# @@protoc_insertion_point(module_scope) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tsl/protobuf/distributed_runtime_payloads_pb2.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tsl/protobuf/distributed_runtime_payloads_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..f75c723014dbe70b8dafa8816d6d4f033a8f5251 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tsl/protobuf/distributed_runtime_payloads_pb2.py @@ -0,0 +1,34 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: tsl/protobuf/distributed_runtime_payloads.proto +"""Generated protocol buffer code.""" +from google.protobuf.internal import builder as _builder +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n/tsl/protobuf/distributed_runtime_payloads.proto\x12\x1etensorflow.distributed_runtime\"\x9d\x01\n\x14GrpcPayloadContainer\x12T\n\x08payloads\x18\x01 \x03(\x0b\x32\x42.tensorflow.distributed_runtime.GrpcPayloadContainer.PayloadsEntry\x1a/\n\rPayloadsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\x0c:\x02\x38\x01\"\x12\n\x10GrpcPayloadsLost\"\x19\n\x17WorkerPossiblyRestartedBAZgithub.com/google/tsl/tsl/go/protobuf/for_core_protos_go_proto\xf8\x01\x01\x62\x06proto3') + +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'tsl.protobuf.error_codes_pb2', globals()) +if _descriptor._USE_C_DESCRIPTORS == False: + + DESCRIPTOR._options = None + DESCRIPTOR._serialized_options = b'\n\030org.tensorflow.frameworkB\020ErrorCodesProtosP\001Z>github.com/google/tsl/tsl/go/protobuf/for_core_protos_go_proto\370\001\001' + _CODE._serialized_start=53 + _CODE._serialized_end=441 +# @@protoc_insertion_point(module_scope) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tsl/protobuf/histogram_pb2.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tsl/protobuf/histogram_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..084338bb3904c1e7d01a584bdc564aa320b223ca --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tsl/protobuf/histogram_pb2.py @@ -0,0 +1,30 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: tsl/protobuf/histogram.proto +"""Generated protocol buffer code.""" +from google.protobuf.internal import builder as _builder +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1ctsl/protobuf/histogram.proto\x12\ntensorflow\"\x87\x01\n\x0eHistogramProto\x12\x0b\n\x03min\x18\x01 \x01(\x01\x12\x0b\n\x03max\x18\x02 \x01(\x01\x12\x0b\n\x03num\x18\x03 \x01(\x01\x12\x0b\n\x03sum\x18\x04 \x01(\x01\x12\x13\n\x0bsum_squares\x18\x05 \x01(\x01\x12\x18\n\x0c\x62ucket_limit\x18\x06 \x03(\x01\x42\x02\x10\x01\x12\x12\n\x06\x62ucket\x18\x07 \x03(\x01\x42\x02\x10\x01\x42\\\n\x18org.tensorflow.frameworkP\x01Z;github.com/google/tsl/tsl/go/core/protobuf/summary_go_proto\xf8\x01\x01\x62\x06proto3') + +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'tsl.protobuf.histogram_pb2', globals()) +if _descriptor._USE_C_DESCRIPTORS == False: + + DESCRIPTOR._options = None + DESCRIPTOR._serialized_options = b'\n\030org.tensorflow.frameworkP\001Z;github.com/google/tsl/tsl/go/core/protobuf/summary_go_proto\370\001\001' + _HISTOGRAMPROTO.fields_by_name['bucket_limit']._options = None + _HISTOGRAMPROTO.fields_by_name['bucket_limit']._serialized_options = b'\020\001' + _HISTOGRAMPROTO.fields_by_name['bucket']._options = None + _HISTOGRAMPROTO.fields_by_name['bucket']._serialized_options = b'\020\001' + _HISTOGRAMPROTO._serialized_start=45 + _HISTOGRAMPROTO._serialized_end=180 +# @@protoc_insertion_point(module_scope) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tsl/protobuf/rpc_options_pb2.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tsl/protobuf/rpc_options_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..7fbb53257e648b0c8d0a92863f2a287a15de5003 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tsl/protobuf/rpc_options_pb2.py @@ -0,0 +1,26 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: tsl/protobuf/rpc_options.proto +"""Generated protocol buffer code.""" +from google.protobuf.internal import builder as _builder +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1etsl/protobuf/rpc_options.proto\x12\ntensorflow\"\xd5\x01\n\nRPCOptions\x12$\n\x1cuse_rpc_for_inprocess_master\x18\x01 \x01(\x08\x12\x1d\n\x15\x63ompression_algorithm\x18\x02 \x01(\t\x12\x19\n\x11\x63ompression_level\x18\x03 \x01(\x05\x12\x1a\n\x12\x63\x61\x63he_rpc_response\x18\x04 \x01(\x08\x12*\n\"disable_session_connection_sharing\x18\x05 \x01(\x08\x12\x1f\n\x17num_channels_per_target\x18\x06 \x01(\x05\x42@Z>github.com/google/tsl/tsl/go/protobuf/for_core_protos_go_protob\x06proto3') + +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'tsl.protobuf.rpc_options_pb2', globals()) +if _descriptor._USE_C_DESCRIPTORS == False: + + DESCRIPTOR._options = None + DESCRIPTOR._serialized_options = b'Z>github.com/google/tsl/tsl/go/protobuf/for_core_protos_go_proto' + _RPCOPTIONS._serialized_start=47 + _RPCOPTIONS._serialized_end=260 +# @@protoc_insertion_point(module_scope) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tsl/protobuf/status_pb2.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tsl/protobuf/status_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..ad05de8373b9e57f7d0d057599f80d6a2d8f265a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tsl/protobuf/status_pb2.py @@ -0,0 +1,27 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: tsl/protobuf/status.proto +"""Generated protocol buffer code.""" +from google.protobuf.internal import builder as _builder +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from tensorflow.tsl.protobuf import error_codes_pb2 as tsl_dot_protobuf_dot_error__codes__pb2 + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x19tsl/protobuf/status.proto\x12\ntensorflow\x1a\x1etsl/protobuf/error_codes.proto\"D\n\x0bStatusProto\x12$\n\x04\x63ode\x18\x01 \x01(\x0e\x32\x16.tensorflow.error.Code\x12\x0f\n\x07message\x18\x02 \x01(\tB_\n\x18org.tensorflow.frameworkP\x01Z>github.com/google/tsl/tsl/go/protobuf/for_core_protos_go_proto\xf8\x01\x01\x62\x06proto3') + +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'tsl.protobuf.status_pb2', globals()) +if _descriptor._USE_C_DESCRIPTORS == False: + + DESCRIPTOR._options = None + DESCRIPTOR._serialized_options = b'\n\030org.tensorflow.frameworkP\001Z>github.com/google/tsl/tsl/go/protobuf/for_core_protos_go_proto\370\001\001' + _STATUSPROTO._serialized_start=73 + _STATUSPROTO._serialized_end=141 +# @@protoc_insertion_point(module_scope) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tsl/protobuf/test_log_pb2.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tsl/protobuf/test_log_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..8481dcd38ac19a0638aaf7e37d1b553d0eca793d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/tsl/protobuf/test_log_pb2.py @@ -0,0 +1,68 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: tsl/protobuf/test_log.proto +"""Generated protocol buffer code.""" +from google.protobuf.internal import builder as _builder +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from google.protobuf import any_pb2 as google_dot_protobuf_dot_any__pb2 +from google.protobuf import wrappers_pb2 as google_dot_protobuf_dot_wrappers__pb2 + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1btsl/protobuf/test_log.proto\x12\ntensorflow\x1a\x19google/protobuf/any.proto\x1a\x1egoogle/protobuf/wrappers.proto\"D\n\nEntryValue\x12\x16\n\x0c\x64ouble_value\x18\x01 \x01(\x01H\x00\x12\x16\n\x0cstring_value\x18\x02 \x01(\tH\x00\x42\x06\n\x04kind\"\x8c\x01\n\x0bMetricEntry\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\x01\x12/\n\tmin_value\x18\x03 \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12/\n\tmax_value\x18\x04 \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\"\x8f\x02\n\x0e\x42\x65nchmarkEntry\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\r\n\x05iters\x18\x02 \x01(\x03\x12\x10\n\x08\x63pu_time\x18\x03 \x01(\x01\x12\x11\n\twall_time\x18\x04 \x01(\x01\x12\x12\n\nthroughput\x18\x05 \x01(\x01\x12\x36\n\x06\x65xtras\x18\x06 \x03(\x0b\x32&.tensorflow.BenchmarkEntry.ExtrasEntry\x12(\n\x07metrics\x18\x07 \x03(\x0b\x32\x17.tensorflow.MetricEntry\x1a\x45\n\x0b\x45xtrasEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12%\n\x05value\x18\x02 \x01(\x0b\x32\x16.tensorflow.EntryValue:\x02\x38\x01\"=\n\x10\x42\x65nchmarkEntries\x12)\n\x05\x65ntry\x18\x01 \x03(\x0b\x32\x1a.tensorflow.BenchmarkEntry\"B\n\x12\x42uildConfiguration\x12\x0c\n\x04mode\x18\x01 \x01(\t\x12\x10\n\x08\x63\x63_flags\x18\x02 \x03(\t\x12\x0c\n\x04opts\x18\x03 \x03(\t\"f\n\x08\x43ommitId\x12\x14\n\nchangelist\x18\x01 \x01(\x03H\x00\x12\x0e\n\x04hash\x18\x02 \x01(\tH\x00\x12\x10\n\x08snapshot\x18\x03 \x01(\t\x12\x1a\n\x12pending_changelist\x18\x04 \x01(\x03\x42\x06\n\x04kind\"\xde\x01\n\x07\x43PUInfo\x12\x11\n\tnum_cores\x18\x01 \x01(\x03\x12\x19\n\x11num_cores_allowed\x18\x02 \x01(\x03\x12\x13\n\x0bmhz_per_cpu\x18\x03 \x01(\x01\x12\x10\n\x08\x63pu_info\x18\x04 \x01(\t\x12\x14\n\x0c\x63pu_governor\x18\x05 \x01(\t\x12\x36\n\ncache_size\x18\x06 \x03(\x0b\x32\".tensorflow.CPUInfo.CacheSizeEntry\x1a\x30\n\x0e\x43\x61\x63heSizeEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\x03:\x02\x38\x01\".\n\nMemoryInfo\x12\r\n\x05total\x18\x01 \x01(\x03\x12\x11\n\tavailable\x18\x02 \x01(\x03\"6\n\x07GPUInfo\x12\r\n\x05model\x18\x01 \x01(\t\x12\x0c\n\x04uuid\x18\x02 \x01(\t\x12\x0e\n\x06\x62us_id\x18\x03 \x01(\t\"p\n\x0cPlatformInfo\x12\x0c\n\x04\x62its\x18\x01 \x01(\t\x12\x0f\n\x07linkage\x18\x02 \x01(\t\x12\x0f\n\x07machine\x18\x03 \x01(\t\x12\x0f\n\x07release\x18\x04 \x01(\t\x12\x0e\n\x06system\x18\x05 \x01(\t\x12\x0f\n\x07version\x18\x06 \x01(\t\"e\n\x13\x41vailableDeviceInfo\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0c\n\x04type\x18\x02 \x01(\t\x12\x14\n\x0cmemory_limit\x18\x03 \x01(\x03\x12\x1c\n\x14physical_description\x18\x04 \x01(\t\"\xb3\x02\n\x14MachineConfiguration\x12\x10\n\x08hostname\x18\x01 \x01(\t\x12\x19\n\x11serial_identifier\x18\x07 \x01(\t\x12/\n\rplatform_info\x18\x02 \x01(\x0b\x32\x18.tensorflow.PlatformInfo\x12%\n\x08\x63pu_info\x18\x03 \x01(\x0b\x32\x13.tensorflow.CPUInfo\x12)\n\x0b\x64\x65vice_info\x18\x04 \x03(\x0b\x32\x14.google.protobuf.Any\x12>\n\x15\x61vailable_device_info\x18\x05 \x03(\x0b\x32\x1f.tensorflow.AvailableDeviceInfo\x12+\n\x0bmemory_info\x18\x06 \x01(\x0b\x32\x16.tensorflow.MemoryInfo\"\x91\x01\n\x10RunConfiguration\x12\x10\n\x08\x61rgument\x18\x01 \x03(\t\x12;\n\x08\x65nv_vars\x18\x02 \x03(\x0b\x32).tensorflow.RunConfiguration.EnvVarsEntry\x1a.\n\x0c\x45nvVarsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"\xd0\x04\n\x0bTestResults\x12\x0e\n\x06target\x18\x01 \x01(\t\x12-\n\x07\x65ntries\x18\x02 \x01(\x0b\x32\x1c.tensorflow.BenchmarkEntries\x12;\n\x13\x62uild_configuration\x18\x03 \x01(\x0b\x32\x1e.tensorflow.BuildConfiguration\x12\'\n\tcommit_id\x18\x04 \x01(\x0b\x32\x14.tensorflow.CommitId\x12\x12\n\nstart_time\x18\x05 \x01(\x03\x12\x10\n\x08run_time\x18\x06 \x01(\x01\x12?\n\x15machine_configuration\x18\x07 \x01(\x0b\x32 .tensorflow.MachineConfiguration\x12\x37\n\x11run_configuration\x18\x08 \x01(\x0b\x32\x1c.tensorflow.RunConfiguration\x12\x0c\n\x04name\x18\t \x01(\t\x12=\n\x0e\x62\x65nchmark_type\x18\n \x01(\x0e\x32%.tensorflow.TestResults.BenchmarkType\x12\x10\n\x08run_mode\x18\x0b \x01(\t\x12\x12\n\ntf_version\x18\x0c \x01(\t\"\x88\x01\n\rBenchmarkType\x12\x0b\n\x07UNKNOWN\x10\x00\x12\x16\n\x12\x43PP_MICROBENCHMARK\x10\x01\x12\x14\n\x10PYTHON_BENCHMARK\x10\x02\x12\x15\n\x11\x41NDROID_BENCHMARK\x10\x03\x12\x12\n\x0e\x45\x44GE_BENCHMARK\x10\x04\x12\x11\n\rIOS_BENCHMARK\x10\x05\x42\x31\n\x1borg.tensorflow.util.testlogB\rTestLogProtosP\x01\xf8\x01\x01\x62\x06proto3') + +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'tsl.protobuf.test_log_pb2', globals()) +if _descriptor._USE_C_DESCRIPTORS == False: + + DESCRIPTOR._options = None + DESCRIPTOR._serialized_options = b'\n\033org.tensorflow.util.testlogB\rTestLogProtosP\001\370\001\001' + _BENCHMARKENTRY_EXTRASENTRY._options = None + _BENCHMARKENTRY_EXTRASENTRY._serialized_options = b'8\001' + _CPUINFO_CACHESIZEENTRY._options = None + _CPUINFO_CACHESIZEENTRY._serialized_options = b'8\001' + _RUNCONFIGURATION_ENVVARSENTRY._options = None + _RUNCONFIGURATION_ENVVARSENTRY._serialized_options = b'8\001' + _ENTRYVALUE._serialized_start=102 + _ENTRYVALUE._serialized_end=170 + _METRICENTRY._serialized_start=173 + _METRICENTRY._serialized_end=313 + _BENCHMARKENTRY._serialized_start=316 + _BENCHMARKENTRY._serialized_end=587 + _BENCHMARKENTRY_EXTRASENTRY._serialized_start=518 + _BENCHMARKENTRY_EXTRASENTRY._serialized_end=587 + _BENCHMARKENTRIES._serialized_start=589 + _BENCHMARKENTRIES._serialized_end=650 + _BUILDCONFIGURATION._serialized_start=652 + _BUILDCONFIGURATION._serialized_end=718 + _COMMITID._serialized_start=720 + _COMMITID._serialized_end=822 + _CPUINFO._serialized_start=825 + _CPUINFO._serialized_end=1047 + _CPUINFO_CACHESIZEENTRY._serialized_start=999 + _CPUINFO_CACHESIZEENTRY._serialized_end=1047 + _MEMORYINFO._serialized_start=1049 + _MEMORYINFO._serialized_end=1095 + _GPUINFO._serialized_start=1097 + _GPUINFO._serialized_end=1151 + _PLATFORMINFO._serialized_start=1153 + _PLATFORMINFO._serialized_end=1265 + _AVAILABLEDEVICEINFO._serialized_start=1267 + _AVAILABLEDEVICEINFO._serialized_end=1368 + _MACHINECONFIGURATION._serialized_start=1371 + _MACHINECONFIGURATION._serialized_end=1678 + _RUNCONFIGURATION._serialized_start=1681 + _RUNCONFIGURATION._serialized_end=1826 + _RUNCONFIGURATION_ENVVARSENTRY._serialized_start=1780 + _RUNCONFIGURATION_ENVVARSENTRY._serialized_end=1826 + _TESTRESULTS._serialized_start=1829 + _TESTRESULTS._serialized_end=2421 + _TESTRESULTS_BENCHMARKTYPE._serialized_start=2285 + _TESTRESULTS_BENCHMARKTYPE._serialized_end=2421 +# @@protoc_insertion_point(module_scope) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/CMakeLists.txt b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..1690338a6257542839ce490ad14968ce4e4d6089 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/CMakeLists.txt @@ -0,0 +1,19 @@ +cmake_minimum_required(VERSION 3.4.3) + +file(GLOB_RECURSE TF_RUNTIME_SRC "*.cc") +add_library(tf_xla_runtime_objects OBJECT + ${TF_RUNTIME_SRC} +) + +target_include_directories(tf_xla_runtime_objects PRIVATE ../include) +target_compile_options(tf_xla_runtime_objects PRIVATE + -ftemplate-backtrace-limit=0 + -Wno-ignored-attributes + -Wno-deprecated-copy + -Wno-cast-qual + -Wno-sign-compare +) + +add_library(tf_xla_runtime STATIC + $ +) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tensorflow/compiler/tf2xla/xla_compiled_cpu_function.cc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tensorflow/compiler/tf2xla/xla_compiled_cpu_function.cc new file mode 100644 index 0000000000000000000000000000000000000000..917d775c80011d71453d0a20034eeb7ab9c83a10 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tensorflow/compiler/tf2xla/xla_compiled_cpu_function.cc @@ -0,0 +1,231 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#include "tensorflow/compiler/tf2xla/xla_compiled_cpu_function.h" + +#include +#include +#include + +#include "xla/cpu_function_runtime.h" +#include "xla/runtime/aot_ffi_execution_context.h" + +namespace tensorflow { + +namespace { +// MemrefDesc's are part of the XLA Runtime ABI. Redefine them here (with a +// slightly different name to avoid confusion) because we cannot depend on +// XLA Runtime's headers. +// Note: this is an internal type, to be used exclusively in this file. +struct MemrefHolder { + MemrefHolder(const XlaCompiledCpuFunction::ShapeInfo& shape_info, + void* data_ptr) + : rank(shape_info.num_dimensions), data(data_ptr), offset(0) { + sizes.resize(shape_info.num_dimensions); + strides.resize(shape_info.num_dimensions); + int64_t multiplier = 1; + for (int i = shape_info.num_dimensions - 1; i >= 0; --i) { + int64_t size = shape_info.dimensions[i]; + sizes[i] = size; + strides[i] = multiplier; + multiplier *= size; + } + } + + unsigned rank = 0; + // Note: dtype is not needed here. + void* data = nullptr; + int64_t offset = 0; + std::vector sizes; + std::vector strides; +}; +} // namespace + +XlaCompiledCpuFunction::XlaCompiledCpuFunction(const StaticData& static_data, + AllocMode alloc_mode) + : raw_function_(static_data.raw_function_), + external_run_function_(static_data.external_run_function_), + cpu_executable_(static_data.cpu_executable_), + result_index_(static_data.result_index_), + buffer_table_(new void*[static_data.num_buffers_]), + buffer_infos_(static_data.buffer_infos_), + num_buffers_(static_data.num_buffers_), + num_results_(static_data.num_results_), + result_index_table_(static_data.result_index_table_), + arg_index_table_(static_data.arg_index_table_), + num_args_(static_data.num_args_), + num_variables_(static_data.num_variables_), + arg_shape_infos_(static_data.arg_shape_infos_), + result_shape_infos_(static_data.result_shape_infos_), + arg_names_(static_data.arg_names_), + variable_names_(static_data.variable_names_), + result_names_(static_data.result_names_), + program_shape_(static_data.program_shape_), + hlo_profile_printer_data_(static_data.hlo_profile_printer_data_), + use_xla_runtime_(static_data.use_xla_runtime_) { + bool allocate_entry_params = + alloc_mode == AllocMode::ARGS_VARIABLES_RESULTS_PROFILES_AND_TEMPS; + // Allocate arg and temp buffers. + alloc_buffer_table_ = xla::cpu_function_runtime::MallocContiguousBuffers( + static_data.buffer_infos_, static_data.num_buffers_, + /*allocate_entry_params=*/allocate_entry_params, buffer_table_, + /*annotate_initialized=*/true); + // If Hlo profiling is enabled the generated code expects an appropriately + // sized buffer to be passed in as the last argument. If Hlo profiling is + // disabled the last function argument is still present in the function + // signature, but it is ignored by the generated code and we pass in null for + // it. + if (hlo_profiling_enabled()) { + profile_counters_ = new int64_t[static_data.profile_counters_size_](); + } +} + +bool XlaCompiledCpuFunction::RunXlaRuntime() { + size_t num_memref_args = num_args_ + num_results_; + std::vector memref_args; + memref_args.reserve(num_memref_args); + + size_t num_ptrs = 1; // execution context. + + // Append arguments. + for (int i = 0; i < num_args_; ++i) { + const ShapeInfo& shape_info = arg_shape_infos_[i]; + memref_args.emplace_back(shape_info, buffer_table_[arg_index_table_[i]]); + num_ptrs += 3 + 2 * shape_info.num_dimensions; + } + + // Append results. + for (int i = 0; i < num_results_; ++i) { + const ShapeInfo& shape_info = result_shape_infos_[i]; + memref_args.emplace_back(shape_info, buffer_table_[result_index_table_[i]]); + num_ptrs += 3 + 2 * shape_info.num_dimensions; + + // Point to this result from the "result" entry in the buffer table. + void** results = static_cast(buffer_table_[result_index_]); + results[i] = buffer_table_[result_index_table_[i]]; + } + + std::vector call_frame; + call_frame.resize(num_ptrs); + size_t ptr_index = 1; + for (const MemrefHolder& memref : memref_args) { + auto cast = [](const void* p) { return const_cast(p); }; + call_frame[ptr_index + 0] = cast(&memref.data); // memref.basePtr + call_frame[ptr_index + 1] = cast(&memref.data); // memref.data + call_frame[ptr_index + 2] = cast(&memref.offset); + unsigned rank = memref.rank; + for (int64_t d = 0; d < rank; ++d) { + call_frame[ptr_index + 3 + d] = cast(&memref.sizes[d]); + call_frame[ptr_index + 3 + d + rank] = cast(&memref.strides[d]); + } + ptr_index += 3 + 2 * rank; + } + + assert(num_ptrs == ptr_index); + + xla::runtime::aot::ExecutionContext execution_context; + execution_context.custom_call_data = &run_options_; + xla::runtime::aot::ExecutionContext* execution_context_ptr = + &execution_context; + call_frame[0] = &execution_context_ptr; + + auto xla_runtime_func = + reinterpret_cast(raw_function_); + xla_runtime_func(call_frame.data()); + if (execution_context.error) { + // No error support in XLA; dump error message to stderr. + std::cerr << "XLA AOT error: " << execution_context.error << ".\n"; + return false; + } + return true; +} + +bool XlaCompiledCpuFunction::Run() { + if (use_xla_runtime_) { + return RunXlaRuntime(); + } + if (external_run_function_) { + std::vector descriptor_table = + MakeXlaRuntimeDescriptorTable(); + return external_run_function_(cpu_executable_, descriptor_table, + &run_options_); + } + XlaCustomCallStatus status; + raw_function_(buffer_table_[result_index_], &run_options_, nullptr, + buffer_table_, &status, profile_counters_); + return !xla::CustomCallStatusGetMessage(&status).has_value(); +} + +std::vector +XlaCompiledCpuFunction::MakeXlaRuntimeDescriptorTable() { + std::vector descriptor_table; + descriptor_table.reserve(num_buffers_); + for (int32_t i = 0; i < num_buffers_; ++i) { + void* data = buffer_table_[i]; + uint64_t size = buffer_infos_[i].size(); + descriptor_table.emplace_back(data, size); + } + return descriptor_table; +} + +XlaCompiledCpuFunction::~XlaCompiledCpuFunction() { + xla::cpu_function_runtime::FreeContiguous(alloc_buffer_table_); + delete[] buffer_table_; + delete[] profile_counters_; +} + +namespace { + +constexpr int kNotFound = -1; + +// Linear search through `names` looking for a match with `name`. Returns -1 if +// the name isn't found, or is empty. +// +// REQUIRES: `names` is a nullptr-terminated array. +int LookupNameIndex(const string& name, const char** names) { + // Hitting this assert means that there is no name-to-index data available; + // for AOT try the setting the tfcompile --gen_name_to_index flag. + assert(names != nullptr); + + if (name.empty()) { + return kNotFound; + } + for (int index = 0; names[index] != nullptr; ++index) { + if (name == names[index]) { + return index; + } + } + return kNotFound; +} + +} // namespace + +int XlaCompiledCpuFunction::LookupArgIndex(const string& name) const { + return LookupNameIndex(name, arg_names_); +} + +int XlaCompiledCpuFunction::LookupVariableIndex(const string& name) const { + int index = LookupNameIndex(name, variable_names_); + if (index == kNotFound) { + return kNotFound; + } + return num_args_ - num_variables_ + index; +} + +int XlaCompiledCpuFunction::LookupResultIndex(const string& name) const { + return LookupNameIndex(name, result_names_); +} + +} // namespace tensorflow diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tensorflow/core/platform/cord.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tensorflow/core/platform/cord.h new file mode 100644 index 0000000000000000000000000000000000000000..fa7d2a5dc2ef9de24ad45040143f689d6f52de7f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tensorflow/core/platform/cord.h @@ -0,0 +1,21 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_PLATFORM_CORD_H_ +#define TENSORFLOW_CORE_PLATFORM_CORD_H_ + +#include "tsl/platform/cord.h" // IWYU pragma: export + +#endif // TENSORFLOW_CORE_PLATFORM_CORD_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tensorflow/core/platform/ctstring.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tensorflow/core/platform/ctstring.h new file mode 100644 index 0000000000000000000000000000000000000000..3b9359d4752840e8d321e4866c9ad2c460155419 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tensorflow/core/platform/ctstring.h @@ -0,0 +1,21 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_PLATFORM_CTSTRING_H_ +#define TENSORFLOW_CORE_PLATFORM_CTSTRING_H_ + +#include "tsl/platform/ctstring.h" + +#endif // TENSORFLOW_CORE_PLATFORM_CTSTRING_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tensorflow/core/platform/ctstring_internal.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tensorflow/core/platform/ctstring_internal.h new file mode 100644 index 0000000000000000000000000000000000000000..c087dbcaad70a5f1850a98d10453f87745f8ffd8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tensorflow/core/platform/ctstring_internal.h @@ -0,0 +1,21 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_PLATFORM_CTSTRING_INTERNAL_H_ +#define TENSORFLOW_CORE_PLATFORM_CTSTRING_INTERNAL_H_ + +#include "tsl/platform/ctstring_internal.h" + +#endif // TENSORFLOW_CORE_PLATFORM_CTSTRING_INTERNAL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tensorflow/core/platform/dynamic_annotations.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tensorflow/core/platform/dynamic_annotations.h new file mode 100644 index 0000000000000000000000000000000000000000..795c978f5549356419ac3ab2031a9ab6cc9452d2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tensorflow/core/platform/dynamic_annotations.h @@ -0,0 +1,22 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_PLATFORM_DYNAMIC_ANNOTATIONS_H_ +#define TENSORFLOW_CORE_PLATFORM_DYNAMIC_ANNOTATIONS_H_ + +#include "tensorflow/core/platform/platform.h" +#include "tsl/platform/dynamic_annotations.h" // IWYU pragma: export + +#endif // TENSORFLOW_CORE_PLATFORM_DYNAMIC_ANNOTATIONS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tensorflow/core/platform/env_time.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tensorflow/core/platform/env_time.h new file mode 100644 index 0000000000000000000000000000000000000000..b2831965bb2ac596f01cd63999ec261ab9c405e8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tensorflow/core/platform/env_time.h @@ -0,0 +1,27 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef TENSORFLOW_CORE_PLATFORM_ENV_TIME_H_ +#define TENSORFLOW_CORE_PLATFORM_ENV_TIME_H_ + +#include + +#include "tensorflow/core/platform/types.h" +#include "tsl/platform/env_time.h" + +namespace tensorflow { +using tsl::EnvTime; // NOLINT +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_PLATFORM_ENV_TIME_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tensorflow/core/platform/macros.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tensorflow/core/platform/macros.h new file mode 100644 index 0000000000000000000000000000000000000000..975f1c5939cbfe21c05268055cd20ecbfce9879d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tensorflow/core/platform/macros.h @@ -0,0 +1,29 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_PLATFORM_MACROS_H_ +#define TENSORFLOW_CORE_PLATFORM_MACROS_H_ + +#include "tsl/platform/macros.h" // IWYU pragma: export + +namespace tensorflow { +namespace internal { +template +constexpr auto remove_unused_variable_compiler_warning = + tsl::internal::remove_unused_variable_compiler_warning; +} // namespace internal +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_PLATFORM_MACROS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tensorflow/core/platform/platform.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tensorflow/core/platform/platform.h new file mode 100644 index 0000000000000000000000000000000000000000..6d5d987934655d43f07b37ae2ae5ea8f3d433fa7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tensorflow/core/platform/platform.h @@ -0,0 +1,21 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_PLATFORM_PLATFORM_H_ +#define TENSORFLOW_CORE_PLATFORM_PLATFORM_H_ + +#include "tsl/platform/platform.h" + +#endif // TENSORFLOW_CORE_PLATFORM_PLATFORM_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tensorflow/core/platform/tstring.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tensorflow/core/platform/tstring.h new file mode 100644 index 0000000000000000000000000000000000000000..7795811d03305b06124590eb666524444be085d1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tensorflow/core/platform/tstring.h @@ -0,0 +1,29 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_PLATFORM_TSTRING_H_ +#define TENSORFLOW_CORE_PLATFORM_TSTRING_H_ + +#include "tensorflow/core/platform/cord.h" +#include "tensorflow/core/platform/ctstring.h" +#include "tensorflow/core/platform/stringpiece.h" +#include "tsl/platform/tstring.h" + +namespace tensorflow { + +using tstring = tsl::tstring; +} + +#endif // TENSORFLOW_CORE_PLATFORM_TSTRING_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tensorflow/core/platform/types.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tensorflow/core/platform/types.h new file mode 100644 index 0000000000000000000000000000000000000000..a3159bfe8abea92dd5d17134e1193f9083630259 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tensorflow/core/platform/types.h @@ -0,0 +1,63 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_PLATFORM_TYPES_H_ +#define TENSORFLOW_CORE_PLATFORM_TYPES_H_ + +#include "tensorflow/core/platform/bfloat16.h" +#include "tensorflow/core/platform/platform.h" +#include "tensorflow/core/platform/tstring.h" +#include "tsl/platform/types.h" + +namespace tensorflow { + +// Alias tensorflow::string to std::string. +using tsl::string; + +using tsl::uint16; +using tsl::uint32; +using tsl::uint4; +using tsl::uint64; +using tsl::uint8; + +using tsl::int16; +using tsl::int32; +using tsl::int4; +using tsl::int64; +using tsl::int8; + +using tsl::float8_e4m3fn; +using tsl::float8_e5m2; + +static const uint8 kuint8max = tsl::kuint8max; +static const uint16 kuint16max = tsl::kuint16max; +static const uint32 kuint32max = tsl::kuint32max; +static const uint64 kuint64max = tsl::kuint64max; +static const int8_t kint8min = tsl::kint8min; +static const int8_t kint8max = tsl::kint8max; +static const int16_t kint16min = tsl::kint16min; +static const int16_t kint16max = tsl::kint16max; +static const int32_t kint32min = tsl::kint32min; +static const int32_t kint32max = tsl::kint32max; +static const int64_t kint64min = tsl::kint64min; +static const int64_t kint64max = tsl::kint64max; + +// A typedef for a uint64 used as a short fingerprint. +using tsl::bfloat16; +using tsl::Fprint; +using tsl::tstring; // NOLINT: suppress 'using decl 'tstring' is unused' +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_PLATFORM_TYPES_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tsl/framework/contraction/eigen_contraction_kernel.cc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tsl/framework/contraction/eigen_contraction_kernel.cc new file mode 100644 index 0000000000000000000000000000000000000000..0efa53567bb7da1c8032cb0129b5217442134a4e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tsl/framework/contraction/eigen_contraction_kernel.cc @@ -0,0 +1,67 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#include "tsl/framework/contraction/eigen_contraction_kernel.h" + +#include // NOLINT(build/c++11) + +#include "absl/base/call_once.h" + +// We need a pair of compile time and runtime flags to disable compilation of +// custom contraction kernels for unsupported architectures (e.g. Android, +// iOS, ARM and PPC CPUs, etc...), and to be able to fallback on default Eigen +// matrix multiplication at runtime. +// +// It's not allowed to use absl flags library in Tensorflow, so we have to pass +// the configuration through the environment variable. +// +// Example: +// bazel test \ +// --test_env=TENSORFLOW_USE_CUSTOM_CONTRACTION_KERNEL=false \ +// //path/to:test + +#if defined(TENSORFLOW_USE_CUSTOM_CONTRACTION_KERNEL) + +namespace Eigen { +namespace internal { + +// TODO(ezhulenev): This is a temporary workaround for disabling custom kernels +// at runtime in tests. We should always rely on compile time flags for that. +// +// Example: +// bazel test \ +// --test_env=TENSORFLOW_USE_CUSTOM_CONTRACTION_KERNEL=false \ +// //path/to:test +EIGEN_DEVICE_FUNC EIGEN_DONT_INLINE bool UseCustomContractionKernels() { + static bool use_custom_contraction_kernel = true; + +// This subroutine should not be used in GPU. In case it is, a custom kernel +// should always be used +#if !defined __NVCC__ && !defined __HIP_DEVICE_COMPILE__ + static absl::once_flag initialized; + absl::call_once(initialized, [&] { + char* flag = std::getenv("TENSORFLOW_USE_CUSTOM_CONTRACTION_KERNEL"); + if (flag && (strcmp(flag, "false") == 0 || strcmp(flag, "0") == 0)) { + use_custom_contraction_kernel = false; + } + }); +#endif + + return use_custom_contraction_kernel; +} + +} // namespace internal +} // namespace Eigen +#endif diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tsl/platform/ctstring.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tsl/platform/ctstring.h new file mode 100644 index 0000000000000000000000000000000000000000..f841e5f4d22af5634ac5d94ec6ca0e4d07c44516 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tsl/platform/ctstring.h @@ -0,0 +1,123 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_TSL_PLATFORM_CTSTRING_H_ +#define TENSORFLOW_TSL_PLATFORM_CTSTRING_H_ + +#include +#include + +#include "tsl/platform/ctstring_internal.h" + +// Initialize a new tstring. This must be called before using any function +// below. +inline void TF_TString_Init(TF_TString *str); +// Deallocate a tstring. +inline void TF_TString_Dealloc(TF_TString *str); + +// Resizes `str' to `new_size'. This function will appropriately grow or shrink +// the string buffer to fit a `new_size' string. Grown regions of the string +// will be initialized with `c'. +inline char *TF_TString_Resize(TF_TString *str, size_t new_size, char c); +// Similar to TF_TString_Resize, except the newly allocated regions will remain +// uninitialized. This is useful if you plan on overwriting the newly grown +// regions immediately after allocation; doing so will elide a superfluous +// initialization of the new buffer. +inline char *TF_TString_ResizeUninitialized(TF_TString *str, size_t new_size); +// Reserves a string buffer with a capacity of at least `new_cap'. +// Reserve will not change the size, or the contents of the existing +// string. This is useful if you have a rough idea of `str's upperbound in +// size, and want to avoid allocations as you append to `str'. It should not be +// considered safe to write in the region between size and capacity; explicitly +// resize before doing so. +inline void TF_TString_Reserve(TF_TString *str, size_t new_cap); +// Similar to TF_TString_Reserve, except that we ensure amortized growth, i.e. +// that we grow the capacity by at least a constant factor >1. +inline void TF_TString_ReserveAmortized(TF_TString *str, size_t new_cap); + +// Returns the size of the string. +inline size_t TF_TString_GetSize(const TF_TString *str); +// Returns the capacity of the string buffer. It should not be considered safe +// to write in the region between size and capacity---call Resize or +// ResizeUninitialized before doing so. +inline size_t TF_TString_GetCapacity(const TF_TString *str); +// Returns the underlying type of the tstring: +// TF_TSTR_SMALL: +// Small string optimization; the contents of strings +// less than 22-bytes are stored in the TF_TString struct. This avoids any +// heap allocations. +// TF_TSTR_LARGE: +// Heap allocated string. +// TF_TSTR_OFFSET: (currently unused) +// An offset defined string. The string buffer begins at an internally +// defined little-endian offset from `str'; i.e. GetDataPointer() = str + +// offset. This type is useful for memory mapping or reading string tensors +// directly from file, without the need to deserialize the data. For +// security reasons, it is imperative that OFFSET based string tensors are +// validated before use, or are from a trusted source. +// TF_TSTR_VIEW: +// A view into an unowned character string. +// +// NOTE: +// VIEW and OFFSET types are immutable, so any modifcation via Append, +// AppendN, or GetMutableDataPointer of a VIEW/OFFSET based tstring will +// result in a conversion to an owned type (SMALL/LARGE). +inline TF_TString_Type TF_TString_GetType(const TF_TString *str); + +// Returns a const char pointer to the start of the underlying string. The +// underlying character buffer may not be null-terminated. +inline const char *TF_TString_GetDataPointer(const TF_TString *str); +// Returns a char pointer to a mutable representation of the underlying string. +// In the case of VIEW and OFFSET types, `src' is converted to an owned type +// (SMALL/LARGE). The underlying character buffer may not be null-terminated. +inline char *TF_TString_GetMutableDataPointer(TF_TString *str); + +// Sets `dst' as a VIEW type to `src'. `dst' will not take ownership of `src'. +// It is the user's responsibility to ensure that the lifetime of `src' exceeds +// `dst'. Any mutations to `dst' via Append, AppendN, or GetMutableDataPointer, +// will result in a copy into an owned SMALL or LARGE type, and will not modify +// `src'. +inline void TF_TString_AssignView(TF_TString *dst, const char *src, + size_t size); + +// Appends `src' onto `dst'. If `dst' is a VIEW or OFFSET type, it will first +// be converted to an owned LARGE or SMALL type. `dst' should not point to +// memory owned by `src'. +inline void TF_TString_Append(TF_TString *dst, const TF_TString *src); +inline void TF_TString_AppendN(TF_TString *dst, const char *src, size_t size); + +// Copy/Move/Assign semantics +// +// | src | dst | complexity +// Copy | * | SMALL/LARGE | fixed/O(size) +// Assign | SMALL | SMALL | fixed +// Assign | OFFSET | VIEW | fixed +// Assign | VIEW | VIEW | fixed +// Assign | LARGE | LARGE | O(size) +// Move | * | same as src | fixed + +// Copies `src' to `dst'. `dst' will be an owned type (SMALL/LARGE). `src' +// should not point to memory owned by `dst'. +inline void TF_TString_Copy(TF_TString *dst, const char *src, size_t size); +// Assigns a `src' tstring to `dst'. An OFFSET `src' type will yield a `VIEW' +// `dst'. LARGE `src' types will be copied to a new buffer; all other `src' +// types will incur a fixed cost. +inline void TF_TString_Assign(TF_TString *dst, const TF_TString *src); +// Moves a `src' tstring to `dst'. Moving a LARGE `src' to `dst' will result in +// a valid but unspecified `src'. This function incurs a fixed cost for all +// inputs. +inline void TF_TString_Move(TF_TString *dst, TF_TString *src); + +#endif // TENSORFLOW_TSL_PLATFORM_CTSTRING_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tsl/platform/ctstring_internal.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tsl/platform/ctstring_internal.h new file mode 100644 index 0000000000000000000000000000000000000000..43e909a8065aaaa70ddb26ab45a4e222d79ba574 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tsl/platform/ctstring_internal.h @@ -0,0 +1,455 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_TSL_PLATFORM_CTSTRING_INTERNAL_H_ +#define TENSORFLOW_TSL_PLATFORM_CTSTRING_INTERNAL_H_ + +#include +#include +#include +#include + +#if (defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__) && \ + __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) || \ + defined(_WIN32) +#define TF_TSTRING_LITTLE_ENDIAN 1 +#elif defined(__BYTE_ORDER__) && defined(__ORDER_BIG_ENDIAN__) && \ + __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ +#define TF_TSTRING_LITTLE_ENDIAN 0 +#else +#error "Unable to detect endianness." +#endif + +#if defined(__clang__) || \ + (defined(__GNUC__) && \ + ((__GNUC__ == 4 && __GNUC_MINOR__ >= 8) || __GNUC__ >= 5)) +static inline uint32_t TF_swap32(uint32_t host_int) { + return __builtin_bswap32(host_int); +} + +#elif defined(_MSC_VER) +static inline uint32_t TF_swap32(uint32_t host_int) { + return _byteswap_ulong(host_int); +} + +#elif defined(__APPLE__) +static inline uint32_t TF_swap32(uint32_t host_int) { + return OSSwapInt32(host_int); +} + +#else +static inline uint32_t TF_swap32(uint32_t host_int) { +#if defined(__GLIBC__) + return bswap_32(host_int); +#else // defined(__GLIBC__) + return (((host_int & uint32_t{0xFF}) << 24) | + ((host_int & uint32_t{0xFF00}) << 8) | + ((host_int & uint32_t{0xFF0000}) >> 8) | + ((host_int & uint32_t{0xFF000000}) >> 24)); +#endif // defined(__GLIBC__) +} +#endif + +#if TF_TSTRING_LITTLE_ENDIAN +#define TF_le32toh(x) x +#else // TF_TSTRING_LITTLE_ENDIAN +#define TF_le32toh(x) TF_swap32(x) +#endif // TF_TSTRING_LITTLE_ENDIAN + +static inline size_t TF_align16(size_t i) { return (i + 0xF) & ~0xF; } + +static inline size_t TF_max(size_t a, size_t b) { return a > b ? a : b; } +static inline size_t TF_min(size_t a, size_t b) { return a < b ? a : b; } + +typedef enum TF_TString_Type { // NOLINT + TF_TSTR_SMALL = 0x00, + TF_TSTR_LARGE = 0x01, + TF_TSTR_OFFSET = 0x02, + TF_TSTR_VIEW = 0x03, + TF_TSTR_TYPE_MASK = 0x03 +} TF_TString_Type; + +typedef struct TF_TString_Large { // NOLINT + size_t size; + size_t cap; + char *ptr; +} TF_TString_Large; + +typedef struct TF_TString_Offset { // NOLINT + uint32_t size; + uint32_t offset; + uint32_t count; +} TF_TString_Offset; + +typedef struct TF_TString_View { // NOLINT + size_t size; + const char *ptr; +} TF_TString_View; + +typedef struct TF_TString_Raw { // NOLINT + uint8_t raw[24]; +} TF_TString_Raw; + +typedef union TF_TString_Union { // NOLINT + TF_TString_Large large; + TF_TString_Offset offset; + TF_TString_View view; + TF_TString_Raw raw; +} TF_TString_Union; + +enum { + TF_TString_SmallCapacity = + (sizeof(TF_TString_Union) - sizeof(/* null delim */ char) - + sizeof(/* uint8_t size */ uint8_t)), +}; + +typedef struct TF_TString_Small { // NOLINT + uint8_t size; + char str[TF_TString_SmallCapacity + sizeof(/* null delim */ char)]; +} TF_TString_Small; + +typedef struct TF_TString { // NOLINT + union { + // small conflicts with '#define small char' in RpcNdr.h for MSVC, so we use + // smll instead. + TF_TString_Small smll; + TF_TString_Large large; + TF_TString_Offset offset; + TF_TString_View view; + TF_TString_Raw raw; + } u; +} TF_TString; + +// TODO(dero): Fix for OSS, and add C only build test. +// _Static_assert(CHAR_BIT == 8); +// _Static_assert(sizeof(TF_TString) == 24); + +static inline TF_TString_Type TF_TString_GetType(const TF_TString *str) { + return (TF_TString_Type)(str->u.raw.raw[0] & TF_TSTR_TYPE_MASK); // NOLINT +} + +// XXX(dero): For the big-endian case, this function could potentially be more +// performant and readable by always storing the string size as little-endian +// and always byte-swapping on big endian, resulting in a simple 'bswap'+'shr' +// (for architectures that have a bswap op). +static inline size_t TF_TString_ToActualSizeT(size_t size) { +#if TF_TSTRING_LITTLE_ENDIAN + return size >> 2; +#else // TF_TSTRING_LITTLE_ENDIAN + // 0xFF000000 or 0xFF00000000000000 depending on platform + static const size_t mask = ~((~(size_t)0) >> 8); + + return (((mask << 2) & size) >> 2) | (~mask & size); +#endif // TF_TSTRING_LITTLE_ENDIAN +} + +static inline size_t TF_TString_ToInternalSizeT(size_t size, + TF_TString_Type type) { +#if TF_TSTRING_LITTLE_ENDIAN + return (size << 2) | type; +#else // TF_TSTRING_LITTLE_ENDIAN + // 0xFF000000 or 0xFF00000000000000 depending on platform + static const size_t mask = ~((~(size_t)0) >> 8); + + return (mask & (size << 2)) | (~mask & size) | + ((size_t)type << ((sizeof(size_t) - 1) * 8)); // NOLINT +#endif // TF_TSTRING_LITTLE_ENDIAN +} + +static inline void TF_TString_Init(TF_TString *str) { + memset(str->u.raw.raw, 0, sizeof(TF_TString_Raw)); +} + +static inline void TF_TString_Dealloc(TF_TString *str) { + if (TF_TString_GetType(str) == TF_TSTR_LARGE && + str->u.large.ptr != NULL) { // NOLINT + free(str->u.large.ptr); + TF_TString_Init(str); + } +} + +static inline size_t TF_TString_GetSize(const TF_TString *str) { + switch (TF_TString_GetType(str)) { + case TF_TSTR_SMALL: + return str->u.smll.size >> 2; + case TF_TSTR_LARGE: + return TF_TString_ToActualSizeT(str->u.large.size); + case TF_TSTR_OFFSET: + return TF_le32toh(str->u.offset.size) >> 2; + case TF_TSTR_VIEW: + return TF_TString_ToActualSizeT(str->u.view.size); + default: + return 0; // Unreachable. + } +} + +static inline size_t TF_TString_GetCapacity(const TF_TString *str) { + switch (TF_TString_GetType(str)) { + case TF_TSTR_SMALL: + return TF_TString_SmallCapacity; + case TF_TSTR_LARGE: + return str->u.large.cap; + case TF_TSTR_OFFSET: + case TF_TSTR_VIEW: + default: + return 0; + } +} + +static inline const char *TF_TString_GetDataPointer(const TF_TString *str) { + switch (TF_TString_GetType(str)) { + case TF_TSTR_SMALL: + return str->u.smll.str; + case TF_TSTR_LARGE: + return str->u.large.ptr; + case TF_TSTR_OFFSET: + return (const char *)str + TF_le32toh(str->u.offset.offset); // NOLINT + case TF_TSTR_VIEW: + return str->u.view.ptr; + default: + // Unreachable. + return NULL; // NOLINT + } +} + +static inline char *TF_TString_ResizeUninitialized(TF_TString *str, + size_t new_size) { + size_t curr_size = TF_TString_GetSize(str); + size_t copy_size = TF_min(new_size, curr_size); + + TF_TString_Type curr_type = TF_TString_GetType(str); + const char *curr_ptr = TF_TString_GetDataPointer(str); + + // Case: SMALL/LARGE/VIEW/OFFSET -> SMALL + if (new_size <= TF_TString_SmallCapacity) { + str->u.smll.size = (uint8_t)((new_size << 2) | TF_TSTR_SMALL); // NOLINT + str->u.smll.str[new_size] = '\0'; + + if (curr_type != TF_TSTR_SMALL && copy_size) { + memcpy(str->u.smll.str, curr_ptr, copy_size); + } + + if (curr_type == TF_TSTR_LARGE) { + free((void *)curr_ptr); // NOLINT + } + + // We do not clear out the newly excluded region. + + return str->u.smll.str; + } + + // Case: SMALL/LARGE/VIEW/OFFSET -> LARGE + size_t new_cap; + size_t curr_cap = TF_TString_GetCapacity(str); + + if (new_size < curr_size && new_size < curr_cap / 2) { + // TODO(dero): Replace with shrink_to_fit flag. + new_cap = TF_align16(curr_cap / 2 + 1) - 1; + } else if (new_size > curr_cap) { + new_cap = TF_align16(new_size + 1) - 1; + } else { + new_cap = curr_cap; + } + + char *new_ptr; + if (new_cap == curr_cap) { + new_ptr = str->u.large.ptr; + } else if (curr_type == TF_TSTR_LARGE) { + new_ptr = (char *)realloc(str->u.large.ptr, new_cap + 1); // NOLINT + } else { + new_ptr = (char *)malloc(new_cap + 1); // NOLINT + if (copy_size) { + memcpy(new_ptr, curr_ptr, copy_size); + } + } + + str->u.large.size = TF_TString_ToInternalSizeT(new_size, TF_TSTR_LARGE); + str->u.large.ptr = new_ptr; + str->u.large.ptr[new_size] = '\0'; + str->u.large.cap = new_cap; + + return str->u.large.ptr; +} + +static inline char *TF_TString_GetMutableDataPointer(TF_TString *str) { + switch (TF_TString_GetType(str)) { + case TF_TSTR_SMALL: + return str->u.smll.str; + case TF_TSTR_OFFSET: + case TF_TSTR_VIEW: + // Convert OFFSET/VIEW to SMALL/LARGE + TF_TString_ResizeUninitialized(str, TF_TString_GetSize(str)); + return (TF_TString_GetType(str) == TF_TSTR_SMALL) ? str->u.smll.str + : str->u.large.ptr; + case TF_TSTR_LARGE: + return str->u.large.ptr; + default: + // Unreachable. + return NULL; // NOLINT + } +} + +static inline void TF_TString_Reserve(TF_TString *str, size_t new_cap) { + TF_TString_Type curr_type = TF_TString_GetType(str); + + if (new_cap <= TF_TString_SmallCapacity) { + // We do nothing, we let Resize/GetMutableDataPointer handle the + // conversion to SMALL from VIEW/OFFSET when the need arises. + // In the degenerate case, where new_cap <= TF_TString_SmallCapacity, + // curr_size > TF_TString_SmallCapacity, and the type is VIEW/OFFSET, we + // defer the malloc to Resize/GetMutableDataPointer. + return; + } + + if (curr_type == TF_TSTR_LARGE && new_cap <= str->u.large.cap) { + // We handle reduced cap in resize. + return; + } + + // Case: VIEW/OFFSET -> LARGE or grow an existing LARGE type + size_t curr_size = TF_TString_GetSize(str); + const char *curr_ptr = TF_TString_GetDataPointer(str); + + // Since VIEW and OFFSET types are read-only, their capacity is effectively 0. + // So we make sure we have enough room in the VIEW and OFFSET cases. + new_cap = TF_align16(TF_max(new_cap, curr_size) + 1) - 1; + + if (curr_type == TF_TSTR_LARGE) { + str->u.large.ptr = + (char *)realloc(str->u.large.ptr, new_cap + 1); // NOLINT + } else { + // Convert to Large + char *new_ptr = (char *)malloc(new_cap + 1); // NOLINT + memcpy(new_ptr, curr_ptr, curr_size); + + str->u.large.size = TF_TString_ToInternalSizeT(curr_size, TF_TSTR_LARGE); + str->u.large.ptr = new_ptr; + str->u.large.ptr[curr_size] = '\0'; + } + + str->u.large.cap = new_cap; +} + +static inline void TF_TString_ReserveAmortized(TF_TString *str, + size_t new_cap) { + const size_t curr_cap = TF_TString_GetCapacity(str); + if (new_cap > curr_cap) { + TF_TString_Reserve(str, new_cap > 2 * curr_cap ? new_cap : 2 * curr_cap); + } +} + +static inline char *TF_TString_Resize(TF_TString *str, size_t new_size, + char c) { + size_t curr_size = TF_TString_GetSize(str); + char *cstr = TF_TString_ResizeUninitialized(str, new_size); + + if (new_size > curr_size) { + memset(cstr + curr_size, c, new_size - curr_size); + } + + return cstr; +} + +static inline void TF_TString_AssignView(TF_TString *dst, const char *src, + size_t size) { + TF_TString_Dealloc(dst); + + dst->u.view.size = TF_TString_ToInternalSizeT(size, TF_TSTR_VIEW); + dst->u.view.ptr = src; +} + +static inline void TF_TString_AppendN(TF_TString *dst, const char *src, + size_t src_size) { + if (!src_size) return; + + size_t dst_size = TF_TString_GetSize(dst); + + // For append use cases, we want to ensure amortized growth. + TF_TString_ReserveAmortized(dst, dst_size + src_size); + char *dst_c = TF_TString_ResizeUninitialized(dst, dst_size + src_size); + + memcpy(dst_c + dst_size, src, src_size); +} + +static inline void TF_TString_Append(TF_TString *dst, const TF_TString *src) { + const char *src_c = TF_TString_GetDataPointer(src); + size_t size = TF_TString_GetSize(src); + + TF_TString_AppendN(dst, src_c, size); +} + +static inline void TF_TString_Copy(TF_TString *dst, const char *src, + size_t size) { + char *dst_c = TF_TString_ResizeUninitialized(dst, size); + + if (size) memcpy(dst_c, src, size); +} + +static inline void TF_TString_Assign(TF_TString *dst, const TF_TString *src) { + if (dst == src) return; + + TF_TString_Dealloc(dst); + + switch (TF_TString_GetType(src)) { + case TF_TSTR_SMALL: + case TF_TSTR_VIEW: + *dst = *src; + return; + case TF_TSTR_LARGE: { + const char *src_c = TF_TString_GetDataPointer(src); + size_t size = TF_TString_GetSize(src); + + TF_TString_Copy(dst, src_c, size); + } + return; + case TF_TSTR_OFFSET: { + const char *src_c = TF_TString_GetDataPointer(src); + size_t size = TF_TString_GetSize(src); + + TF_TString_AssignView(dst, src_c, size); + } + return; + default: + return; // Unreachable. + } +} + +static inline void TF_TString_Move(TF_TString *dst, TF_TString *src) { + if (dst == src) return; + + TF_TString_Dealloc(dst); + + switch (TF_TString_GetType(src)) { + case TF_TSTR_SMALL: + case TF_TSTR_VIEW: + *dst = *src; + return; + case TF_TSTR_LARGE: + *dst = *src; + TF_TString_Init(src); + return; + case TF_TSTR_OFFSET: { + const char *src_c = TF_TString_GetDataPointer(src); + size_t size = TF_TString_GetSize(src); + + TF_TString_AssignView(dst, src_c, size); + } + return; + default: + return; // Unreachable. + } +} + +#endif // TENSORFLOW_TSL_PLATFORM_CTSTRING_INTERNAL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tsl/platform/default/dynamic_annotations.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tsl/platform/default/dynamic_annotations.h new file mode 100644 index 0000000000000000000000000000000000000000..4d275cc1169a60594fa848fef092d88791bb97fd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tsl/platform/default/dynamic_annotations.h @@ -0,0 +1,34 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_TSL_PLATFORM_DEFAULT_DYNAMIC_ANNOTATIONS_H_ +#define TENSORFLOW_TSL_PLATFORM_DEFAULT_DYNAMIC_ANNOTATIONS_H_ + +// IWYU pragma: private, include "tsl/platform/dynamic_annotations.h" +// IWYU pragma: friend third_party/tensorflow/tsl/platform/dynamic_annotations.h + +// Do nothing for this platform. + +#define TF_ANNOTATE_MEMORY_IS_INITIALIZED(ptr, bytes) \ + do { \ + } while (0) + +#define TF_ANNOTATE_BENIGN_RACE(ptr, description) \ + do { \ + } while (0) + +#define TF_ATTRIBUTE_NO_SANITIZE_MEMORY + +#endif // TENSORFLOW_TSL_PLATFORM_DEFAULT_DYNAMIC_ANNOTATIONS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tsl/platform/default/env_time.cc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tsl/platform/default/env_time.cc new file mode 100644 index 0000000000000000000000000000000000000000..6d8b583d527504cfc2abe2e2a51389fb11ab6cff --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tsl/platform/default/env_time.cc @@ -0,0 +1,31 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#include "tsl/platform/env_time.h" + +#include +#include + +namespace tsl { + +/* static */ +uint64 EnvTime::NowNanos() { + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + return (static_cast(ts.tv_sec) * kSecondsToNanos + + static_cast(ts.tv_nsec)); +} + +} // namespace tsl diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tsl/platform/default/integral_types.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tsl/platform/default/integral_types.h new file mode 100644 index 0000000000000000000000000000000000000000..6f2f4c560cade78de6c700ad2d38cf73e79be811 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tsl/platform/default/integral_types.h @@ -0,0 +1,38 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_TSL_PLATFORM_DEFAULT_INTEGRAL_TYPES_H_ +#define TENSORFLOW_TSL_PLATFORM_DEFAULT_INTEGRAL_TYPES_H_ + +#include + +// IWYU pragma: private, include "tsl/platform/types.h" +// IWYU pragma: friend third_party/tensorflow/tsl/platform/types.h + +namespace tsl { + +typedef signed char int8; +typedef short int16; +typedef int int32; +typedef ::std::int64_t int64; + +typedef unsigned char uint8; +typedef unsigned short uint16; +typedef unsigned int uint32; +typedef std::uint64_t uint64; + +} // namespace tsl + +#endif // TENSORFLOW_TSL_PLATFORM_DEFAULT_INTEGRAL_TYPES_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tsl/platform/dynamic_annotations.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tsl/platform/dynamic_annotations.h new file mode 100644 index 0000000000000000000000000000000000000000..88912f7b7519bda9a3e6ef534723765cf6aee156 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tsl/platform/dynamic_annotations.h @@ -0,0 +1,32 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_TSL_PLATFORM_DYNAMIC_ANNOTATIONS_H_ +#define TENSORFLOW_TSL_PLATFORM_DYNAMIC_ANNOTATIONS_H_ + +#include "tsl/platform/platform.h" + +// Include appropriate platform-dependent implementation. +#if defined(PLATFORM_GOOGLE) +#include "tsl/platform/google/dynamic_annotations.h" // IWYU pragma: export +#elif defined(PLATFORM_POSIX) || defined(PLATFORM_POSIX_ANDROID) || \ + defined(PLATFORM_GOOGLE_ANDROID) || defined(PLATFORM_POSIX_IOS) || \ + defined(PLATFORM_GOOGLE_IOS) || defined(PLATFORM_WINDOWS) +#include "tsl/platform/default/dynamic_annotations.h" // IWYU pragma: export +#else +#error Define the appropriate PLATFORM_ macro for this platform +#endif + +#endif // TENSORFLOW_TSL_PLATFORM_DYNAMIC_ANNOTATIONS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tsl/platform/env_time.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tsl/platform/env_time.h new file mode 100644 index 0000000000000000000000000000000000000000..2ec888069ead327d32bddce4b912810cfaae8b42 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tsl/platform/env_time.h @@ -0,0 +1,65 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef TENSORFLOW_TSL_PLATFORM_ENV_TIME_H_ +#define TENSORFLOW_TSL_PLATFORM_ENV_TIME_H_ + +#include + +#include "tsl/platform/types.h" + +namespace tsl { + +/// \brief An interface used by the tsl implementation to +/// access timer related operations. +class EnvTime { + public: + static constexpr uint64 kMicrosToPicos = 1000ULL * 1000ULL; + static constexpr uint64 kMicrosToNanos = 1000ULL; + static constexpr uint64 kMillisToMicros = 1000ULL; + static constexpr uint64 kMillisToNanos = 1000ULL * 1000ULL; + static constexpr uint64 kNanosToPicos = 1000ULL; + static constexpr uint64 kSecondsToMillis = 1000ULL; + static constexpr uint64 kSecondsToMicros = 1000ULL * 1000ULL; + static constexpr uint64 kSecondsToNanos = 1000ULL * 1000ULL * 1000ULL; + + EnvTime() = default; + virtual ~EnvTime() = default; + + /// \brief Returns the number of nano-seconds since the Unix epoch. + static uint64 NowNanos(); + + /// \brief Returns the number of micro-seconds since the Unix epoch. + static uint64 NowMicros() { return NowNanos() / kMicrosToNanos; } + + /// \brief Returns the number of seconds since the Unix epoch. + static uint64 NowSeconds() { return NowNanos() / kSecondsToNanos; } + + /// \brief A version of NowNanos() that may be overridden by a subclass. + virtual uint64 GetOverridableNowNanos() const { return NowNanos(); } + + /// \brief A version of NowMicros() that may be overridden by a subclass. + virtual uint64 GetOverridableNowMicros() const { + return GetOverridableNowNanos() / kMicrosToNanos; + } + + /// \brief A version of NowSeconds() that may be overridden by a subclass. + virtual uint64 GetOverridableNowSeconds() const { + return GetOverridableNowNanos() / kSecondsToNanos; + } +}; + +} // namespace tsl + +#endif // TENSORFLOW_TSL_PLATFORM_ENV_TIME_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tsl/platform/macros.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tsl/platform/macros.h new file mode 100644 index 0000000000000000000000000000000000000000..cb91c4ff64e8477ff949c4062bdfe0142bd861b2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tsl/platform/macros.h @@ -0,0 +1,162 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_TSL_PLATFORM_MACROS_H_ +#define TENSORFLOW_TSL_PLATFORM_MACROS_H_ + +// Compiler attributes +#if (defined(__GNUC__) || defined(__APPLE__)) && !defined(SWIG) +// Compiler supports GCC-style attributes +#define TF_ATTRIBUTE_NORETURN __attribute__((noreturn)) +#define TF_ATTRIBUTE_ALWAYS_INLINE __attribute__((always_inline)) +#define TF_ATTRIBUTE_NOINLINE __attribute__((noinline)) +#define TF_ATTRIBUTE_UNUSED __attribute__((unused)) +#define TF_ATTRIBUTE_COLD __attribute__((cold)) +#define TF_ATTRIBUTE_WEAK __attribute__((weak)) +#define TF_PACKED __attribute__((packed)) +#define TF_MUST_USE_RESULT __attribute__((warn_unused_result)) +#define TF_PRINTF_ATTRIBUTE(string_index, first_to_check) \ + __attribute__((__format__(__printf__, string_index, first_to_check))) +#define TF_SCANF_ATTRIBUTE(string_index, first_to_check) \ + __attribute__((__format__(__scanf__, string_index, first_to_check))) +#elif defined(_MSC_VER) +// Non-GCC equivalents +#define TF_ATTRIBUTE_NORETURN __declspec(noreturn) +#define TF_ATTRIBUTE_ALWAYS_INLINE __forceinline +#define TF_ATTRIBUTE_NOINLINE +#define TF_ATTRIBUTE_UNUSED +#define TF_ATTRIBUTE_COLD +#define TF_ATTRIBUTE_WEAK +#define TF_MUST_USE_RESULT +#define TF_PACKED +#define TF_PRINTF_ATTRIBUTE(string_index, first_to_check) +#define TF_SCANF_ATTRIBUTE(string_index, first_to_check) +#else +// Non-GCC equivalents +#define TF_ATTRIBUTE_NORETURN +#define TF_ATTRIBUTE_ALWAYS_INLINE +#define TF_ATTRIBUTE_NOINLINE +#define TF_ATTRIBUTE_UNUSED +#define TF_ATTRIBUTE_COLD +#define TF_ATTRIBUTE_WEAK +#define TF_MUST_USE_RESULT +#define TF_PACKED +#define TF_PRINTF_ATTRIBUTE(string_index, first_to_check) +#define TF_SCANF_ATTRIBUTE(string_index, first_to_check) +#endif + +// Control visibility outside .so +#if defined(_WIN32) +#ifdef TF_COMPILE_LIBRARY +#define TF_EXPORT __declspec(dllexport) +#else +#define TF_EXPORT __declspec(dllimport) +#endif // TF_COMPILE_LIBRARY +#else +#define TF_EXPORT __attribute__((visibility("default"))) +#endif // _WIN32 + +#ifdef __has_builtin +#define TF_HAS_BUILTIN(x) __has_builtin(x) +#else +#define TF_HAS_BUILTIN(x) 0 +#endif + +// C++11-style attributes (N2761) +#if defined(__has_cpp_attribute) +// Safely checks if an attribute is supported. Equivalent to +// ABSL_HAVE_CPP_ATTRIBUTE. +#define TF_HAS_CPP_ATTRIBUTE(n) __has_cpp_attribute(n) +#else +#define TF_HAS_CPP_ATTRIBUTE(n) 0 +#endif + +// [[clang::annotate("x")]] allows attaching custom strings (e.g. "x") to +// declarations (variables, functions, fields, etc.) for use by tools. They are +// represented in the Clang AST (as AnnotateAttr nodes) and in LLVM IR, but not +// in final output. +#if TF_HAS_CPP_ATTRIBUTE(clang::annotate) +#define TF_ATTRIBUTE_ANNOTATE(str) [[clang::annotate(str)]] +#else +#define TF_ATTRIBUTE_ANNOTATE(str) +#endif + +// A variable declaration annotated with the `TF_CONST_INIT` attribute will +// not compile (on supported platforms) unless the variable has a constant +// initializer. +#if TF_HAS_CPP_ATTRIBUTE(clang::require_constant_initialization) +#define TF_CONST_INIT [[clang::require_constant_initialization]] +#else +#define TF_CONST_INIT +#endif + +// Compilers can be told that a certain branch is not likely to be taken +// (for instance, a CHECK failure), and use that information in static +// analysis. Giving it this information can help it optimize for the +// common case in the absence of better information (ie. +// -fprofile-arcs). +#if TF_HAS_BUILTIN(__builtin_expect) || (defined(__GNUC__) && __GNUC__ >= 3) +#define TF_PREDICT_FALSE(x) (__builtin_expect(x, 0)) +#define TF_PREDICT_TRUE(x) (__builtin_expect(!!(x), 1)) +#else +#define TF_PREDICT_FALSE(x) (x) +#define TF_PREDICT_TRUE(x) (x) +#endif + +// DEPRECATED: directly use the macro implementation instead. +// A macro to disallow the copy constructor and operator= functions +// This is usually placed in the private: declarations for a class. +#define TF_DISALLOW_COPY_AND_ASSIGN(TypeName) \ + TypeName(const TypeName&) = delete; \ + void operator=(const TypeName&) = delete + +// The TF_ARRAYSIZE(arr) macro returns the # of elements in an array arr. +// +// The expression TF_ARRAYSIZE(a) is a compile-time constant of type +// size_t. +#define TF_ARRAYSIZE(a) \ + ((sizeof(a) / sizeof(*(a))) / \ + static_cast(!(sizeof(a) % sizeof(*(a))))) + +#if defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L || \ + (defined(_MSC_VER) && _MSC_VER >= 1900) +// Define this to 1 if the code is compiled in C++11 mode; leave it +// undefined otherwise. Do NOT define it to 0 -- that causes +// '#ifdef LANG_CXX11' to behave differently from '#if LANG_CXX11'. +#define LANG_CXX11 1 +#endif + +#if defined(__clang__) && defined(LANG_CXX11) && defined(__has_warning) +#if __has_feature(cxx_attributes) && __has_warning("-Wimplicit-fallthrough") +#define TF_FALLTHROUGH_INTENDED [[clang::fallthrough]] // NOLINT +#endif +#endif + +#ifndef TF_FALLTHROUGH_INTENDED +#define TF_FALLTHROUGH_INTENDED \ + do { \ + } while (0) +#endif + +namespace tsl { +namespace internal { +template +void remove_unused_variable_compiler_warning(const T&){}; +} // namespace internal +} // namespace tsl +#define TF_UNUSED_VARIABLE(x) \ + tensorflow::internal::remove_unused_variable_compiler_warning(x) + +#endif // TENSORFLOW_TSL_PLATFORM_MACROS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tsl/platform/platform.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tsl/platform/platform.h new file mode 100644 index 0000000000000000000000000000000000000000..9456687727a1ace93f9793099cf17243d72f61f7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/tsl/platform/platform.h @@ -0,0 +1,85 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_TSL_PLATFORM_PLATFORM_H_ +#define TENSORFLOW_TSL_PLATFORM_PLATFORM_H_ + +// Set one PLATFORM_* macro and set IS_MOBILE_PLATFORM if the platform is for +// mobile. + +#if !defined(PLATFORM_POSIX) && !defined(PLATFORM_GOOGLE) && \ + !defined(PLATFORM_POSIX_ANDROID) && !defined(PLATFORM_GOOGLE_ANDROID) && \ + !defined(PLATFORM_WINDOWS) + +// Choose which platform we are on. +#if defined(ANDROID) || defined(__ANDROID__) +#define PLATFORM_POSIX_ANDROID +#define IS_MOBILE_PLATFORM + +#elif defined(__APPLE__) +#include "TargetConditionals.h" +#if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE +#define PLATFORM_POSIX_IOS +#define IS_MOBILE_PLATFORM +#else +// If no platform specified, use: +#define PLATFORM_POSIX +#endif + +#elif defined(_WIN32) +#define PLATFORM_WINDOWS + +#elif defined(__EMSCRIPTEN__) +#define PLATFORM_PORTABLE_GOOGLE +#define PLATFORM_POSIX +// EMSCRIPTEN builds are considered "mobile" for the sake of portability. +#define IS_MOBILE_PLATFORM + +#elif defined(__TF_CHROMIUMOS__) +#define PLATFORM_PORTABLE_GOOGLE +#define PLATFORM_POSIX +#define PLATFORM_CHROMIUMOS + +#elif defined(__Fuchsia__) +#define PLATFORM_FUCHSIA +// PLATFORM_GOOGLE needs to be defined by default to get the right header +// files. +#define PLATFORM_GOOGLE + +#else +// If no platform specified, use: +#define PLATFORM_POSIX + +#endif +#endif + +// Look for both gcc/clang and Visual Studio macros indicating we're compiling +// for an x86 device. +#if defined(__x86_64__) || defined(__amd64__) || defined(_M_IX86) || \ + defined(_M_X64) +#define PLATFORM_IS_X86 +#endif + +// Check if we are compmiling for an arm device. +#if defined(__arm__) || defined(__aarch64__) +#define PLATFORM_IS_ARM +#if defined(__aarch64__) +#define PLATFORM_IS_ARM64 +#else +#define PLATFORM_IS_ARM32 +#endif +#endif + +#endif // TENSORFLOW_TSL_PLATFORM_PLATFORM_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/cpu_function_runtime.cc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/cpu_function_runtime.cc new file mode 100644 index 0000000000000000000000000000000000000000..bc361a662caae84c86b7bbdfc24721a1ca0e1ff2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/cpu_function_runtime.cc @@ -0,0 +1,108 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#include "xla/cpu_function_runtime.h" + +#include "absl/base/dynamic_annotations.h" + +namespace xla { +namespace { +// Inline memory allocation routines here, because depending on '//base' brings +// in libraries which use c++ streams, which adds considerable code size on +// android. +void* aligned_malloc(size_t size, int minimum_alignment) { +#if defined(__ANDROID__) || defined(OS_ANDROID) || defined(OS_CYGWIN) + return memalign(minimum_alignment, size); +#elif defined(_WIN32) + return _aligned_malloc(size, minimum_alignment); +#else // !__ANDROID__ && !OS_ANDROID && !OS_CYGWIN + void* ptr = nullptr; + // posix_memalign requires that the requested alignment be at least + // sizeof(void*). In this case, fall back on malloc which should return memory + // aligned to at least the size of a pointer. + const int required_alignment = sizeof(void*); + if (minimum_alignment < required_alignment) return malloc(size); + if (posix_memalign(&ptr, minimum_alignment, size) != 0) + return nullptr; + else + return ptr; +#endif +} + +void aligned_free(void* aligned_memory) { +#if defined(_WIN32) + _aligned_free(aligned_memory); +#else + free(aligned_memory); +#endif +} + +size_t align_to(size_t n, size_t align) { + return (((n - 1) / align) + 1) * align; +} +} // namespace + +namespace cpu_function_runtime { +size_t AlignedBufferBytes(const BufferInfo* buffer_infos, size_t n, + bool allocate_entry_params) { + size_t total = 0; + for (size_t i = 0; i < n; ++i) { + bool should_allocate = + buffer_infos[i].is_temp_buffer() || + (buffer_infos[i].is_entry_parameter() && allocate_entry_params); + + if (should_allocate) { + total += align_to(buffer_infos[i].size(), Align()); + } + } + return total; +} + +void* MallocContiguousBuffers(const BufferInfo* buffer_infos, size_t n, + bool allocate_entry_params, void** bufs, + bool annotate_initialized) { + const size_t total = + AlignedBufferBytes(buffer_infos, n, allocate_entry_params); + void* contiguous = nullptr; + if (total > 0) { + contiguous = aligned_malloc(total, Align()); + if (annotate_initialized) { + // Since the memory for temp buffers is written to by JITed code, msan has + // no way of knowing the memory was initialized, so explicitly mark it. + ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(contiguous, total); + } + } + uintptr_t pos = reinterpret_cast(contiguous); + for (size_t i = 0; i < n; ++i) { + bool should_allocate = + buffer_infos[i].is_temp_buffer() || + (buffer_infos[i].is_entry_parameter() && allocate_entry_params); + if (should_allocate) { + bufs[i] = reinterpret_cast(pos); + pos += align_to(buffer_infos[i].size(), Align()); + } else { + bufs[i] = nullptr; + } + } + return contiguous; +} + +void FreeContiguous(void* contiguous) { + if (contiguous != nullptr) { + aligned_free(contiguous); + } +} +} // namespace cpu_function_runtime +} // namespace xla diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/executable_run_options.cc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/executable_run_options.cc new file mode 100644 index 0000000000000000000000000000000000000000..795c5fc4176431e6a5761a29225952e745af198b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/executable_run_options.cc @@ -0,0 +1,141 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#include "xla/executable_run_options.h" + +#include +#include + +namespace xla { + +RunId::RunId() { + static std::atomic counter{0}; + data_ = counter.fetch_add(1); +} + +bool operator==(const RunId& a, const RunId& b) { return a.data_ == b.data_; } + +std::string RunId::ToString() const { + return "RunId: " + std::to_string(data_); +} + +int64_t RunId::ToInt() const { return data_; } + +ExecutableRunOptions& ExecutableRunOptions::set_device_ordinal( + int device_ordinal) { + device_ordinal_ = device_ordinal; + return *this; +} + +int ExecutableRunOptions::device_ordinal() const { return device_ordinal_; } + +ExecutableRunOptions& ExecutableRunOptions::set_allocator( + stream_executor::DeviceMemoryAllocator* allocator) { + allocator_ = allocator; + return *this; +} + +stream_executor::DeviceMemoryAllocator* ExecutableRunOptions::allocator() + const { + return allocator_; +} + +ExecutableRunOptions& ExecutableRunOptions::set_stream( + stream_executor::Stream* stream) { + stream_ = stream; + return *this; +} + +stream_executor::Stream* ExecutableRunOptions::stream() const { + return stream_; +} + +ExecutableRunOptions& ExecutableRunOptions::set_host_to_device_stream( + stream_executor::Stream* stream) { + host_to_device_stream_ = stream; + return *this; +} + +stream_executor::Stream* ExecutableRunOptions::host_to_device_stream() const { + return host_to_device_stream_; +} + +ExecutableRunOptions& ExecutableRunOptions::set_device_to_host_stream( + stream_executor::Stream* stream) { + device_to_host_stream_ = stream; + return *this; +} + +stream_executor::Stream* ExecutableRunOptions::device_to_host_stream() const { + return device_to_host_stream_; +} + +ExecutableRunOptions& ExecutableRunOptions::set_intra_op_thread_pool( + const Eigen::ThreadPoolDevice* intra_op_thread_pool) { + intra_op_thread_pool_ = intra_op_thread_pool; + return *this; +} + +const Eigen::ThreadPoolDevice* ExecutableRunOptions::intra_op_thread_pool() + const { + return intra_op_thread_pool_; +} + +ExecutableRunOptions& ExecutableRunOptions::set_execution_profile( + ExecutionProfile* profile) { + execution_profile_ = profile; + return *this; +} + +ExecutionProfile* ExecutableRunOptions::execution_profile() const { + return execution_profile_; +} + +ExecutableRunOptions& ExecutableRunOptions::set_device_assignment( + const DeviceAssignment* device_assignment) { + device_assignment_ = device_assignment; + return *this; +} + +const DeviceAssignment* ExecutableRunOptions::device_assignment() const { + return device_assignment_; +} + +ExecutableRunOptions& ExecutableRunOptions::set_gpu_executable_run_options( + const gpu::GpuExecutableRunOptions* gpu_executable_run_options) { + gpu_executable_run_options_ = gpu_executable_run_options; + return *this; +} + +const gpu::GpuExecutableRunOptions* +ExecutableRunOptions::gpu_executable_run_options() const { + return gpu_executable_run_options_; +} + +ExecutableRunOptions& ExecutableRunOptions::set_rng_seed(int rng_seed) { + rng_seed_ = rng_seed; + return *this; +} + +int ExecutableRunOptions::rng_seed() const { return rng_seed_; } + +ExecutableRunOptions& ExecutableRunOptions::set_run_id(RunId id) { + run_id_ = id; + return *this; +} + +RunId ExecutableRunOptions::run_id() const { return run_id_; } + +} // namespace xla diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_conv2d.cc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_conv2d.cc new file mode 100644 index 0000000000000000000000000000000000000000..9278f2af8f550687173a63d2fed04053c2cddc7e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_conv2d.cc @@ -0,0 +1,67 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#include "xla/service/cpu/runtime_conv2d.h" + +#define EIGEN_USE_THREADS + +#include "absl/base/dynamic_annotations.h" +#include "xla/executable_run_options.h" +#include "xla/service/cpu/runtime_conv_impl.h" +#include "xla/service/cpu/runtime_lightweight_check.h" + +ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY void __xla_cpu_runtime_EigenConv2DF32( + const void* run_options_ptr, float* out, float* lhs, float* rhs, + int64_t input_batch, int64_t input_rows, int64_t input_cols, + int64_t input_channels, int64_t kernel_rows, int64_t kernel_cols, + int64_t kernel_channels, int64_t kernel_filters, int64_t output_rows, + int64_t output_cols, int64_t row_stride, int64_t col_stride, + int64_t padding_top, int64_t padding_bottom, int64_t padding_left, + int64_t padding_right, int64_t lhs_row_dilation, int64_t lhs_col_dilation, + int64_t rhs_row_dilation, int64_t rhs_col_dilation, + int64_t feature_group_count) { + const xla::ExecutableRunOptions* run_options = + static_cast(run_options_ptr); + XLA_LIGHTWEIGHT_CHECK(run_options->intra_op_thread_pool() != nullptr); + tensorflow::xla::EigenConv2DImpl( + *run_options->intra_op_thread_pool(), out, lhs, rhs, input_batch, + input_rows, input_cols, input_channels, kernel_rows, kernel_cols, + kernel_channels, kernel_filters, output_rows, output_cols, row_stride, + col_stride, padding_top, padding_bottom, padding_left, padding_right, + lhs_row_dilation, lhs_col_dilation, rhs_row_dilation, rhs_col_dilation, + feature_group_count); +} + +ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY void __xla_cpu_runtime_EigenConv2DF16( + const void* run_options_ptr, Eigen::half* out, Eigen::half* lhs, + Eigen::half* rhs, int64_t input_batch, int64_t input_rows, + int64_t input_cols, int64_t input_channels, int64_t kernel_rows, + int64_t kernel_cols, int64_t kernel_channels, int64_t kernel_filters, + int64_t output_rows, int64_t output_cols, int64_t row_stride, + int64_t col_stride, int64_t padding_top, int64_t padding_bottom, + int64_t padding_left, int64_t padding_right, int64_t lhs_row_dilation, + int64_t lhs_col_dilation, int64_t rhs_row_dilation, + int64_t rhs_col_dilation, int64_t feature_group_count) { + const xla::ExecutableRunOptions* run_options = + static_cast(run_options_ptr); + XLA_LIGHTWEIGHT_CHECK(run_options->intra_op_thread_pool() != nullptr); + tensorflow::xla::EigenConv2DImpl( + *run_options->intra_op_thread_pool(), out, lhs, rhs, input_batch, + input_rows, input_cols, input_channels, kernel_rows, kernel_cols, + kernel_channels, kernel_filters, output_rows, output_cols, row_stride, + col_stride, padding_top, padding_bottom, padding_left, padding_right, + lhs_row_dilation, lhs_col_dilation, rhs_row_dilation, rhs_col_dilation, + feature_group_count); +} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_conv3d.cc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_conv3d.cc new file mode 100644 index 0000000000000000000000000000000000000000..a8e0d0a7a72009b9e23a7e3eba517d5bd66c0a9d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_conv3d.cc @@ -0,0 +1,73 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#include "xla/service/cpu/runtime_conv3d.h" + +#define EIGEN_USE_THREADS + +#include "absl/base/dynamic_annotations.h" +#include "xla/executable_run_options.h" +#include "xla/service/cpu/runtime_conv_impl.h" +#include "xla/service/cpu/runtime_lightweight_check.h" + +ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY void __xla_cpu_runtime_EigenConv3DF32( + const void* run_options_ptr, float* out, float* lhs, float* rhs, + int64_t input_batch, int64_t input_x, int64_t input_y, int64_t input_z, + int64_t input_channels, int64_t kernel_x, int64_t kernel_y, + int64_t kernel_z, int64_t kernel_channels, int64_t kernel_filters, + int64_t output_x, int64_t output_y, int64_t output_z, int64_t x_stride, + int64_t y_stride, int64_t z_stride, int64_t padding_x_before, + int64_t padding_x_after, int64_t padding_y_before, int64_t padding_y_after, + int64_t padding_z_before, int64_t padding_z_after, int64_t lhs_x_dilation, + int64_t lhs_y_dilation, int64_t lhs_z_dilation, int64_t rhs_x_dilation, + int64_t rhs_y_dilation, int64_t rhs_z_dilation, + int64_t feature_group_count) { + const xla::ExecutableRunOptions* run_options = + static_cast(run_options_ptr); + XLA_LIGHTWEIGHT_CHECK(run_options->intra_op_thread_pool() != nullptr); + tensorflow::xla::EigenConv3DImpl( + *run_options->intra_op_thread_pool(), out, lhs, rhs, input_batch, input_x, + input_y, input_z, input_channels, kernel_x, kernel_y, kernel_z, + kernel_channels, kernel_filters, output_x, output_y, output_z, x_stride, + y_stride, z_stride, padding_x_before, padding_x_after, padding_y_before, + padding_y_after, padding_z_before, padding_z_after, lhs_x_dilation, + lhs_y_dilation, lhs_z_dilation, rhs_x_dilation, rhs_y_dilation, + rhs_z_dilation, feature_group_count); +} + +ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY void __xla_cpu_runtime_EigenConv3DF16( + const void* run_options_ptr, Eigen::half* out, Eigen::half* lhs, + Eigen::half* rhs, int64_t input_batch, int64_t input_x, int64_t input_y, + int64_t input_z, int64_t input_channels, int64_t kernel_x, int64_t kernel_y, + int64_t kernel_z, int64_t kernel_channels, int64_t kernel_filters, + int64_t output_x, int64_t output_y, int64_t output_z, int64_t x_stride, + int64_t y_stride, int64_t z_stride, int64_t padding_x_before, + int64_t padding_x_after, int64_t padding_y_before, int64_t padding_y_after, + int64_t padding_z_before, int64_t padding_z_after, int64_t lhs_x_dilation, + int64_t lhs_y_dilation, int64_t lhs_z_dilation, int64_t rhs_x_dilation, + int64_t rhs_y_dilation, int64_t rhs_z_dilation, + int64_t feature_group_count) { + const xla::ExecutableRunOptions* run_options = + static_cast(run_options_ptr); + XLA_LIGHTWEIGHT_CHECK(run_options->intra_op_thread_pool() != nullptr); + tensorflow::xla::EigenConv3DImpl( + *run_options->intra_op_thread_pool(), out, lhs, rhs, input_batch, input_x, + input_y, input_z, input_channels, kernel_x, kernel_y, kernel_z, + kernel_channels, kernel_filters, output_x, output_y, output_z, x_stride, + y_stride, z_stride, padding_x_before, padding_x_after, padding_y_before, + padding_y_after, padding_z_before, padding_z_after, lhs_x_dilation, + lhs_y_dilation, lhs_z_dilation, rhs_x_dilation, rhs_y_dilation, + rhs_z_dilation, feature_group_count); +} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_custom_call_status.cc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_custom_call_status.cc new file mode 100644 index 0000000000000000000000000000000000000000..42ad966245ea672df771598b4aa8bfb99ff87ab0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_custom_call_status.cc @@ -0,0 +1,24 @@ +/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#include "xla/service/cpu/runtime_custom_call_status.h" + +#include "absl/base/dynamic_annotations.h" +#include "xla/service/custom_call_status_internal.h" + +ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY bool __xla_cpu_runtime_StatusIsSuccess( + const void* status_ptr) { + auto status = static_cast(status_ptr); + return !xla::CustomCallStatusGetMessage(status).has_value(); +} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_fft.cc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_fft.cc new file mode 100644 index 0000000000000000000000000000000000000000..26e3316425ecda4ffaf9b7240f60ffd963a67aad --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_fft.cc @@ -0,0 +1,36 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#include "xla/service/cpu/runtime_fft.h" + +#define EIGEN_USE_THREADS + +#include "absl/base/dynamic_annotations.h" +#include "xla/executable_run_options.h" +#include "xla/service/cpu/runtime_fft_impl.h" +#include "xla/service/cpu/runtime_lightweight_check.h" + +ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY void __xla_cpu_runtime_EigenFft( + const void* run_options_ptr, void* out, void* operand, int32_t fft_type, + int32_t double_precision, int32_t fft_rank, int64_t input_batch, + int64_t fft_length0, int64_t fft_length1, int64_t fft_length2) { + const xla::ExecutableRunOptions* run_options = + static_cast(run_options_ptr); + XLA_LIGHTWEIGHT_CHECK(run_options->intra_op_thread_pool() != nullptr); + xla::EigenFftImpl(*run_options->intra_op_thread_pool(), out, operand, + static_cast(fft_type), + static_cast(double_precision), fft_rank, input_batch, + fft_length0, fft_length1, fft_length2); +} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_fork_join.cc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_fork_join.cc new file mode 100644 index 0000000000000000000000000000000000000000..7e8ab842fe83f0d642bf0024378c2e08185c68ab --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_fork_join.cc @@ -0,0 +1,131 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#include "xla/service/cpu/runtime_fork_join.h" + +#define EIGEN_USE_THREADS + +#include "absl/base/dynamic_annotations.h" +#include "absl/strings/str_format.h" +#include "absl/strings/str_join.h" +#include "unsupported/Eigen/CXX11/Tensor" // from @eigen_archive +#include "xla/executable_run_options.h" +#include "xla/service/custom_call_status_internal.h" +#include "tsl/platform/blocking_counter.h" +#include "tsl/platform/logging.h" + +using ComputeFunctionType = void (*)(void*, const void*, const void**, void**, + void*, int64_t*, uint64_t*); + +// Dispatches 'num_partitions - 1' calls to 'function_ptr' in parallel. +// Calls 'function_ptr' for first partition inline. +// Uses blocking counter to synchronize threads after parallel calls complete. +// +// The 'partitions' array has a total number of elements equal to +// 'num_partitions * num_partitioned_dims * 2' (the '2' is necessary to specify +// dimension start and limit indices). +// +// The 'partitions' array layout stores array elements in memory with dimension +// start limit as the most-minor dimension, followed by dimension, then +// partition. +// +// EX: Layout of 'partitions' array with 'num_partitions = 2', and +// 'num_partitioned_dims = 3' +// +// [partition0_dim0_start] +// [partition0_dim0_limit] +// [partition0_dim1_start] +// [partition0_dim1_limit] +// [partition0_dim2_start] +// [partition0_dim2_limit] +// [partition1_dim0_start] +// [partition1_dim0_limit] +// [partition1_dim1_start] +// [partition1_dim1_limit] +// [partition1_dim2_start] +// [partition1_dim2_limit] +// +ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY void __xla_cpu_runtime_ParallelForkJoin( + void* result_ptr, const void* run_options_ptr, const void** params, + void** buffer_table, void* status, uint64_t* prof_counters, + int32_t num_partitions, int64_t* partitions, int32_t num_partitioned_dims, + void* function_ptr) { + VLOG(2) << "ParallelForkJoin ENTRY" + << " num_partitions: " << num_partitions + << " num_partitioned_dims: " << num_partitioned_dims; + CHECK_EQ(params, nullptr); + CHECK_GT(num_partitions, 1); + CHECK_GT(num_partitioned_dims, 0); + CHECK_NE(function_ptr, nullptr); + CHECK_NE(partitions, nullptr); + const xla::ExecutableRunOptions* run_options = + static_cast(run_options_ptr); + CHECK_NE(run_options, nullptr); + CHECK_NE(run_options->intra_op_thread_pool(), nullptr); + + ComputeFunctionType function = + reinterpret_cast(function_ptr); + // Compute partition stride in 'partitions' array. + const int64_t stride = 2 * num_partitioned_dims; + + std::vector statuses(num_partitions); + + // Dispatch 'num_partitions - 1' compute functions to run in parallel. + tsl::BlockingCounter bc(num_partitions - 1); + for (int32_t i = 1; i < num_partitions; ++i) { + const int64_t offset = i * stride; + run_options->intra_op_thread_pool()->enqueueNoNotification( + [i, function, result_ptr, run_options_ptr, buffer_table, prof_counters, + partitions, offset, &bc, &statuses]() { + function(result_ptr, run_options_ptr, nullptr, buffer_table, + &statuses[i], &partitions[offset], prof_counters); + bc.DecrementCount(); + VLOG(3) << "ParallelForkJoin partition " << i << " done."; + }); + } + + // Call first compute function inline. + function(result_ptr, run_options_ptr, params, buffer_table, &statuses[0], + &partitions[0], prof_counters); + VLOG(3) << "ParallelForkJoin partition 0 done."; + bc.Wait(); + + // Collect all error messages (if any). + std::vector> error_messages; + for (int32_t i = 0; i < num_partitions; ++i) { + std::optional msg = + xla::CustomCallStatusGetMessage(&statuses[i]); + if (msg) { + error_messages.emplace_back(i, *msg); + } + } + + if (!error_messages.empty()) { + // Join all error messages into a single string to serve as the message for + // the returned status. + std::string error_message = absl::StrJoin( + error_messages, "\n", + [](std::string* out, std::pair p) { + int32_t idx = p.first; + absl::string_view msg = p.second; + absl::StrAppend(out, + absl::StrFormat("Partition %d error: %s", idx, msg)); + }); + XlaCustomCallStatusSetFailure( + reinterpret_cast(status), error_message.data(), + error_message.length()); + } + VLOG(2) << "ParallelForkJoin EXIT"; +} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_fp16.cc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_fp16.cc new file mode 100644 index 0000000000000000000000000000000000000000..f63b24f17d4168ea06c28025e9a474256e8ff5a1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_fp16.cc @@ -0,0 +1,145 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#include "xla/service/cpu/runtime_fp16.h" + +#include + +#include "absl/base/attributes.h" + +namespace { + +// Helper class that lets us access the underlying bit representation +// of a float without breaking C++ strict aliasing. +class AliasedFloatInt { + public: + static_assert(sizeof(float) == sizeof(uint32_t), ""); + + static AliasedFloatInt FromFloat(float f) { + AliasedFloatInt value; + value.set_float(f); + return value; + } + + static AliasedFloatInt FromUInt(uint32_t u) { + AliasedFloatInt value; + value.set_uint(u); + return value; + } + + void set_float(float f) { memcpy(&value_, &f, sizeof(f)); } + float as_float() const { + float f; + memcpy(&f, &value_, sizeof(f)); + return f; + } + + void set_uint(uint32_t u) { value_ = u; } + uint32_t as_uint() const { return value_; } + + private: + uint32_t value_; +}; +} // namespace + +// __gnu_f2h_ieee and __gnu_h2f_ieee are marked as weak symbols so if XLA is +// built with compiler-rt (that also defines these symbols) we don't get a +// duplicate definition linker error. Making these symbols weak also ensures +// that the compiler-rt definitions "win", but that isn't essential. + +// Algorithm copied from Eigen. +XlaF16ABIType ABSL_ATTRIBUTE_WEAK __gnu_f2h_ieee(float float_value) { + AliasedFloatInt f = AliasedFloatInt::FromFloat(float_value); + + const AliasedFloatInt f32infty = AliasedFloatInt::FromUInt(255 << 23); + const AliasedFloatInt f16max = AliasedFloatInt::FromUInt((127 + 16) << 23); + const AliasedFloatInt denorm_magic = + AliasedFloatInt::FromUInt(((127 - 15) + (23 - 10) + 1) << 23); + unsigned int sign_mask = 0x80000000u; + uint32_t o = static_cast(0x0u); + + unsigned int sign = f.as_uint() & sign_mask; + f.set_uint(f.as_uint() ^ sign); + + // NOTE all the integer compares in this function can be safely + // compiled into signed compares since all operands are below + // 0x80000000. Important if you want fast straight SSE2 code + // (since there's no unsigned PCMPGTD). + + if (f.as_uint() >= + f16max.as_uint()) { // result is Inf or NaN (all exponent bits set) + o = (f.as_uint() > f32infty.as_uint()) ? 0x7e00 + : 0x7c00; // NaN->qNaN and Inf->Inf + } else { // (De)normalized number or zero + if (f.as_uint() < (113 << 23)) { // resulting FP16 is subnormal or zero + // use a magic value to align our 10 mantissa bits at the bottom of + // the float. as long as FP addition is round-to-nearest-even this + // just works. + f.set_float(f.as_float() + denorm_magic.as_float()); + + // and one integer subtract of the bias later, we have our final float! + o = static_cast(f.as_uint() - denorm_magic.as_uint()); + } else { + unsigned int mant_odd = + (f.as_uint() >> 13) & 1; // resulting mantissa is odd + + // update exponent, rounding bias part 1 + f.set_uint(f.as_uint() + (static_cast(15 - 127) << 23) + + 0xfff); + // rounding bias part 2 + f.set_uint(f.as_uint() + mant_odd); + // take the bits! + o = static_cast(f.as_uint() >> 13); + } + } + + o |= static_cast(sign >> 16); + // The output can be a float type, bitcast it from uint16_t. + auto ho = static_cast(o); + XlaF16ABIType ret = 0; + std::memcpy(&ret, &ho, sizeof(ho)); + return ret; +} + +// Algorithm copied from Eigen. +float ABSL_ATTRIBUTE_WEAK __gnu_h2f_ieee(XlaF16ABIType hf) { + const AliasedFloatInt magic = AliasedFloatInt::FromUInt(113 << 23); + const unsigned int shifted_exp = 0x7c00 << 13; // exponent mask after shift + AliasedFloatInt o; + + // The input can be a float type, bitcast it to uint16_t. + uint16_t h; + std::memcpy(&h, &hf, sizeof(h)); + o.set_uint((h & 0x7fff) << 13); // exponent/mantissa bits + unsigned int exp = shifted_exp & o.as_uint(); // just the exponent + o.set_uint(o.as_uint() + ((127 - 15) << 23)); // exponent adjust + + // handle exponent special cases + if (exp == shifted_exp) { // Inf/NaN? + o.set_uint(o.as_uint() + ((128 - 16) << 23)); // extra exp adjust + } else if (exp == 0) { // Zero/Denormal? + o.set_uint(o.as_uint() + (1 << 23)); // extra exp adjust + o.set_float(o.as_float() - magic.as_float()); // renormalize + } + + o.set_uint(o.as_uint() | (h & 0x8000) << 16); // sign bit + return o.as_float(); +} + +XlaF16ABIType ABSL_ATTRIBUTE_WEAK __truncdfhf2(double d) { + // This does a double rounding step, but it's precise enough for our use + // cases. + return __gnu_f2h_ieee(static_cast(d)); +} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_key_value_sort.cc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_key_value_sort.cc new file mode 100644 index 0000000000000000000000000000000000000000..148984ae9930aacc0605be20367242aeabe8b198 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_key_value_sort.cc @@ -0,0 +1,111 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#include "xla/service/cpu/runtime_key_value_sort.h" + +#include +#include +#include +#include +#include + +#include "absl/base/dynamic_annotations.h" +#include "unsupported/Eigen/CXX11/Tensor" // from @eigen_archive + +ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY void __xla_cpu_runtime_KeyValueSort( + int64_t a, int64_t b, int64_t c, char** values, int32_t values_count, + int32_t* values_primitive_type_size_in_bytes, bool is_stable, + char* run_options, int64_t* prof_counters, + void (*less_than)(char*, char*, char**, char**, int64_t*)) { + // 'values' and 'values_primitive_type_size_in_bytes' are managed by the JIT + // code, so msan can't tell they are initialized. + ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(values, values_count * sizeof(char*)); + ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(values_primitive_type_size_in_bytes, + values_count * sizeof(int32_t)); + + // High-level idea of the iteration/sorting logic: + // Conceptually we have a 3-dimensional shape [a, b, c]. b corresponds to the + // dimension to sort, c is the product of the more minor dimensions (set to 1 + // if b is the most minor dimension), and a is the product of the more major + // dimensions (set to 1 if b is the most major dimension). There are a * c + // many rows that we need to sort. We iterate through these, calculate a + // 'base_offset' value which points to the first element in that row, and add + // i * c for accessing the 'i'-th element in that row. + + int64_t sort_dimension_elements = b; + int64_t num_iteration_elements = a * c; + int64_t sort_dimension_offset = c; + + std::unique_ptr indices(new int64_t[sort_dimension_elements]); + std::unique_ptr comparison_values(new char*[2 * values_count]); + std::iota(indices.get(), indices.get() + sort_dimension_elements, 0); + std::unique_ptr reordered_values( + new std::string[sort_dimension_elements]); + for (int64_t index = 0; index < num_iteration_elements; ++index) { + // If the sort should be stable, we have to reinitialize indices to iota to + // guarantee that we still keep the relative order in case of ties. + if (is_stable && index > 0) { + std::iota(indices.get(), indices.get() + sort_dimension_elements, 0); + } + // 'index' can be split into two values which index into the 'c' dimension + // and the 'a' dimension, respectively. 'index' % 'c' is the index into the + // 'c' dimension, 'index' / 'c' is the index into the 'a' dimension. When + // calculating the base offset, we need to multiply the index into the 'a' + // dimension with 'b' * 'c'. + // 'index' / 'c' * 'c' * 'b' = ('index' - 'index' % 'c') * 'b'. + int64_t base_offset = + index % sort_dimension_offset + + (index - index % sort_dimension_offset) * sort_dimension_elements; + auto compare_function = [&](int64_t a, int64_t b) -> bool { + for (int32_t i = 0; i < values_count; ++i) { + int64_t memory_index_lhs = (base_offset + a * sort_dimension_offset) * + values_primitive_type_size_in_bytes[i]; + int64_t memory_index_rhs = (base_offset + b * sort_dimension_offset) * + values_primitive_type_size_in_bytes[i]; + comparison_values[i * 2] = values[i] + memory_index_lhs; + comparison_values[i * 2 + 1] = values[i] + memory_index_rhs; + } + char result = 0; // Overwritten by less_than. + less_than(&result, run_options, comparison_values.get(), nullptr, + prof_counters); + return result != 0u; + }; + if (is_stable) { + std::stable_sort(indices.get(), indices.get() + sort_dimension_elements, + compare_function); + } else { + std::sort(indices.get(), indices.get() + sort_dimension_elements, + compare_function); + } + + // Reorder the values according to the order defined by 'indices'. + for (int32_t idx = 0; idx < values_count; ++idx) { + for (int64_t i = 0; i < sort_dimension_elements; ++i) { + int64_t memory_index = + (base_offset + indices[i] * sort_dimension_offset) * + values_primitive_type_size_in_bytes[idx]; + + reordered_values[i] = + std::string(values[idx] + memory_index, + values_primitive_type_size_in_bytes[idx]); + } + for (int64_t i = 0; i < sort_dimension_elements; ++i) { + int64_t memory_index = (base_offset + i * sort_dimension_offset) * + values_primitive_type_size_in_bytes[idx]; + memcpy(values[idx] + memory_index, reordered_values[i].c_str(), + values_primitive_type_size_in_bytes[idx]); + } + } + } +} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_matmul_c128.cc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_matmul_c128.cc new file mode 100644 index 0000000000000000000000000000000000000000..c237763d1bc60898663a106ae4dd9627cb15b59f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_matmul_c128.cc @@ -0,0 +1,30 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#include "xla/service/cpu/runtime_matmul.h" + +#include +#include + +#include "absl/base/attributes.h" +#include "xla/service/cpu/runtime_matmul_common.h" + +ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY void __xla_cpu_runtime_EigenMatMulC128( + const void* run_options_ptr, std::complex* out, + std::complex* lhs, std::complex* rhs, int64_t m, int64_t n, + int64_t k, int32_t transpose_lhs, int32_t transpose_rhs) { + xla::MatMulDispatch>(run_options_ptr, out, lhs, rhs, m, + n, k, transpose_lhs, transpose_rhs); +} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_matmul_c64.cc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_matmul_c64.cc new file mode 100644 index 0000000000000000000000000000000000000000..e526061f7fad66114046581cca650397f0a70e5a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_matmul_c64.cc @@ -0,0 +1,30 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#include "xla/service/cpu/runtime_matmul.h" + +#include +#include + +#include "absl/base/attributes.h" +#include "xla/service/cpu/runtime_matmul_common.h" + +ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY void __xla_cpu_runtime_EigenMatMulC64( + const void* run_options_ptr, std::complex* out, + std::complex* lhs, std::complex* rhs, int64_t m, int64_t n, + int64_t k, int32_t transpose_lhs, int32_t transpose_rhs) { + xla::MatMulDispatch>(run_options_ptr, out, lhs, rhs, m, n, + k, transpose_lhs, transpose_rhs); +} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_matmul_common.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_matmul_common.h new file mode 100644 index 0000000000000000000000000000000000000000..a08be9d36680ebea3a812997d91de71bcf754b6a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_matmul_common.h @@ -0,0 +1,154 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_CPU_RUNTIME_MATMUL_COMMON_H_ +#define XLA_SERVICE_CPU_RUNTIME_MATMUL_COMMON_H_ + +#include + +#define EIGEN_USE_THREADS + +#include "absl/base/dynamic_annotations.h" +#include "unsupported/Eigen/CXX11/Tensor" // from @eigen_archive +#include "xla/executable_run_options.h" +#include "xla/service/cpu/runtime_lightweight_check.h" + +#if defined(TENSORFLOW_USE_CUSTOM_CONTRACTION_KERNEL) +#include "tsl/framework/contraction/eigen_contraction_kernel.h" +#endif + +namespace xla { + +static inline bool Is16BytesAligned(void* ptr) { + return reinterpret_cast(ptr) % 16 == 0; +} + +template +void MatMul(const void* run_options_ptr, T* out, T* lhs, T* rhs, int64_t m, + int64_t n, int64_t k, int32_t transpose_lhs, + int32_t transpose_rhs) { + const xla::ExecutableRunOptions* run_options = + static_cast(run_options_ptr); + + int64_t lhs_rows = m; + int64_t lhs_cols = k; + if (transpose_lhs) { + std::swap(lhs_rows, lhs_cols); + } + + int64_t rhs_rows = k; + int64_t rhs_cols = n; + if (transpose_rhs) { + std::swap(rhs_rows, rhs_cols); + } + + const Eigen::TensorMap, Alignment> A(lhs, lhs_rows, + lhs_cols); + const Eigen::TensorMap, Alignment> B(rhs, rhs_rows, + rhs_cols); + Eigen::TensorMap, Alignment> C(out, m, n); + + typedef typename Eigen::Tensor::DimensionPair DimPair; + int lhs_contract_dim = transpose_lhs ? 0 : 1; + int rhs_contract_dim = transpose_rhs ? 1 : 0; + const Eigen::array dims( + {DimPair(lhs_contract_dim, rhs_contract_dim)}); + + // Matrix multiply is a special case of the "contract" operation where + // the contraction is performed along dimension 1 of the lhs and dimension + // 0 of the rhs. + XLA_LIGHTWEIGHT_CHECK(run_options->intra_op_thread_pool() != nullptr); + C.device(*run_options->intra_op_thread_pool()) = A.contract(B, dims); +} + +template +void MatMul_Batch(const void* run_options_ptr, T* out, T* lhs, T* rhs, + int64_t m, int64_t n, int64_t k, Eigen::Index batch_size, + int32_t transpose_lhs, int32_t transpose_rhs) { + const xla::ExecutableRunOptions* run_options = + static_cast(run_options_ptr); + + int64_t lhs_rows = m; + int64_t lhs_cols = k; + if (transpose_lhs) { + std::swap(lhs_rows, lhs_cols); + } + + int64_t rhs_rows = k; + int64_t rhs_cols = n; + if (transpose_rhs) { + std::swap(rhs_rows, rhs_cols); + } + + const Eigen::TensorMap, Alignment> A( + lhs, lhs_rows, lhs_cols, batch_size); + const Eigen::TensorMap, Alignment> B( + rhs, rhs_rows, rhs_cols, batch_size); + Eigen::TensorMap, Alignment> C(out, m, n, batch_size); + + typedef typename Eigen::Tensor::DimensionPair DimPair; + int lhs_contract_dim = transpose_lhs ? 0 : 1; + int rhs_contract_dim = transpose_rhs ? 1 : 0; + + const Eigen::array dims( + {DimPair(lhs_contract_dim, rhs_contract_dim)}); + + // Matrix multiply is a special case of the "contract" operation where + // the contraction is performed along dimension 1 of the lhs and dimension + // 0 of the rhs. + XLA_LIGHTWEIGHT_CHECK(run_options->intra_op_thread_pool() != nullptr); + + for (int64_t i = 0; i < batch_size; ++i) { + C.chip(i, 2).device(*run_options->intra_op_thread_pool()) = + A.chip(i, 2).contract(B.chip(i, 2), dims); + } +} + +template +void MatMulDispatch(const void* run_options_ptr, T* out, T* lhs, T* rhs, + int64_t m, int64_t n, int64_t k, int32_t transpose_lhs, + int32_t transpose_rhs) { + bool all_buffers_16b_aligned = + Is16BytesAligned(out) && Is16BytesAligned(lhs) && Is16BytesAligned(rhs); + + if (!all_buffers_16b_aligned) { + MatMul(run_options_ptr, out, lhs, rhs, m, n, k, + transpose_lhs, transpose_rhs); + return; + } + + MatMul(run_options_ptr, out, lhs, rhs, m, n, k, + transpose_lhs, transpose_rhs); +} + +template +void BatchMatMulDispatch(const void* run_options_ptr, T* out, T* lhs, T* rhs, + int64_t m, int64_t n, int64_t k, int64_t batch_size, + int32_t transpose_lhs, int32_t transpose_rhs) { + bool all_buffers_16b_aligned = + Is16BytesAligned(out) && Is16BytesAligned(lhs) && Is16BytesAligned(rhs); + + if (!all_buffers_16b_aligned) { + MatMul_Batch(run_options_ptr, out, lhs, rhs, m, n, k, + batch_size, transpose_lhs, transpose_rhs); + return; + } + MatMul_Batch(run_options_ptr, out, lhs, rhs, m, n, k, + batch_size, transpose_lhs, transpose_rhs); +} + +} // namespace xla + +#endif // XLA_SERVICE_CPU_RUNTIME_MATMUL_COMMON_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_matmul_f16.cc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_matmul_f16.cc new file mode 100644 index 0000000000000000000000000000000000000000..72d80d39f0cf4021ddef74a5917fafaff1e7a5dd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_matmul_f16.cc @@ -0,0 +1,30 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#include "xla/service/cpu/runtime_matmul.h" + +#include + +#include "absl/base/attributes.h" +#include "Eigen/Core" // from @eigen_archive +#include "xla/service/cpu/runtime_matmul_common.h" + +ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY void __xla_cpu_runtime_EigenMatMulF16( + const void* run_options_ptr, Eigen::half* out, Eigen::half* lhs, + Eigen::half* rhs, int64_t m, int64_t n, int64_t k, int32_t transpose_lhs, + int32_t transpose_rhs) { + xla::MatMulDispatch(run_options_ptr, out, lhs, rhs, m, n, k, + transpose_lhs, transpose_rhs); +} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_matmul_f32.cc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_matmul_f32.cc new file mode 100644 index 0000000000000000000000000000000000000000..7e40231590f401000e579ba5504b3b518b66121c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_matmul_f32.cc @@ -0,0 +1,36 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#include "xla/service/cpu/runtime_matmul.h" + +#include + +#include "absl/base/attributes.h" +#include "xla/service/cpu/runtime_matmul_common.h" + +ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY void __xla_cpu_runtime_EigenMatMulF32( + const void* run_options_ptr, float* out, float* lhs, float* rhs, int64_t m, + int64_t n, int64_t k, int32_t transpose_lhs, int32_t transpose_rhs) { + xla::MatMulDispatch(run_options_ptr, out, lhs, rhs, m, n, k, + transpose_lhs, transpose_rhs); +} + +ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY void __xla_cpu_runtime_EigenBatchMatMulF32( + const void* run_options_ptr, float* out, float* lhs, float* rhs, int64_t m, + int64_t n, int64_t k, int64_t batch_size, int32_t transpose_lhs, + int32_t transpose_rhs) { + xla::BatchMatMulDispatch(run_options_ptr, out, lhs, rhs, m, n, k, + batch_size, transpose_lhs, transpose_rhs); +} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_matmul_f64.cc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_matmul_f64.cc new file mode 100644 index 0000000000000000000000000000000000000000..d75c400e4a5e777a8c5ba87eef59d6ff9fa370dd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_matmul_f64.cc @@ -0,0 +1,29 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#include "xla/service/cpu/runtime_matmul.h" + +#include + +#include "absl/base/attributes.h" +#include "xla/service/cpu/runtime_matmul_common.h" + +ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY void __xla_cpu_runtime_EigenMatMulF64( + const void* run_options_ptr, double* out, double* lhs, double* rhs, + int64_t m, int64_t n, int64_t k, int32_t transpose_lhs, + int32_t transpose_rhs) { + xla::MatMulDispatch(run_options_ptr, out, lhs, rhs, m, n, k, + transpose_lhs, transpose_rhs); +} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_matmul_s32.cc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_matmul_s32.cc new file mode 100644 index 0000000000000000000000000000000000000000..69c8634426d137af1c2b2ee876cfdc9efb641406 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_matmul_s32.cc @@ -0,0 +1,29 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#include "xla/service/cpu/runtime_matmul.h" + +#include + +#include "absl/base/attributes.h" +#include "xla/service/cpu/runtime_matmul_common.h" + +ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY void __xla_cpu_runtime_EigenMatMulS32( + const void* run_options_ptr, int32_t* out, int32_t* lhs, int32_t* rhs, + int64_t m, int64_t n, int64_t k, int32_t transpose_lhs, + int32_t transpose_rhs) { + xla::MatMulDispatch(run_options_ptr, out, lhs, rhs, m, n, k, + transpose_lhs, transpose_rhs); +} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_pow.cc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_pow.cc new file mode 100644 index 0000000000000000000000000000000000000000..d391a1409e83d411df56efa2fca3317914200039 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_pow.cc @@ -0,0 +1,35 @@ +/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#include "xla/service/cpu/runtime_pow.h" + +#include "absl/base/attributes.h" + +template +static T Powi(T a, int32_t b) { + const bool recip = b < 0; + T r = 1; + while (true) { + if (b & 1) r *= a; + b /= 2; + if (b == 0) break; + a *= a; + } + return recip ? 1 / r : r; +} + +float ABSL_ATTRIBUTE_WEAK __powisf2(float a, int32_t b) { return Powi(a, b); } + +double ABSL_ATTRIBUTE_WEAK __powidf2(double a, int32_t b) { return Powi(a, b); } diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_single_threaded_conv2d.cc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_single_threaded_conv2d.cc new file mode 100644 index 0000000000000000000000000000000000000000..32b0cb4a4682472838b4e287198296f604df3cb2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_single_threaded_conv2d.cc @@ -0,0 +1,59 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#include "xla/service/cpu/runtime_single_threaded_conv2d.h" + +#include "absl/base/dynamic_annotations.h" +#include "xla/service/cpu/runtime_conv_impl.h" + +ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY void +__xla_cpu_runtime_EigenSingleThreadedConv2DF16( + const void* /*run_options_ptr*/, Eigen::half* out, Eigen::half* lhs, + Eigen::half* rhs, int64_t input_batch, int64_t input_rows, + int64_t input_cols, int64_t input_channels, int64_t kernel_rows, + int64_t kernel_cols, int64_t kernel_channels, int64_t kernel_filters, + int64_t output_rows, int64_t output_cols, int64_t row_stride, + int64_t col_stride, int64_t padding_top, int64_t padding_bottom, + int64_t padding_left, int64_t padding_right, int64_t lhs_row_dilation, + int64_t lhs_col_dilation, int64_t rhs_row_dilation, + int64_t rhs_col_dilation, int64_t feature_group_count) { + tensorflow::xla::EigenConv2DImpl( + Eigen::DefaultDevice(), out, lhs, rhs, input_batch, input_rows, + input_cols, input_channels, kernel_rows, kernel_cols, kernel_channels, + kernel_filters, output_rows, output_cols, row_stride, col_stride, + padding_top, padding_bottom, padding_left, padding_right, + lhs_row_dilation, lhs_col_dilation, rhs_row_dilation, rhs_col_dilation, + feature_group_count); +} + +ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY void +__xla_cpu_runtime_EigenSingleThreadedConv2DF32( + const void* /*run_options_ptr*/, float* out, float* lhs, float* rhs, + int64_t input_batch, int64_t input_rows, int64_t input_cols, + int64_t input_channels, int64_t kernel_rows, int64_t kernel_cols, + int64_t kernel_channels, int64_t kernel_filters, int64_t output_rows, + int64_t output_cols, int64_t row_stride, int64_t col_stride, + int64_t padding_top, int64_t padding_bottom, int64_t padding_left, + int64_t padding_right, int64_t lhs_row_dilation, int64_t lhs_col_dilation, + int64_t rhs_row_dilation, int64_t rhs_col_dilation, + int64_t feature_group_count) { + tensorflow::xla::EigenConv2DImpl( + Eigen::DefaultDevice(), out, lhs, rhs, input_batch, input_rows, + input_cols, input_channels, kernel_rows, kernel_cols, kernel_channels, + kernel_filters, output_rows, output_cols, row_stride, col_stride, + padding_top, padding_bottom, padding_left, padding_right, + lhs_row_dilation, lhs_col_dilation, rhs_row_dilation, rhs_col_dilation, + feature_group_count); +} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_single_threaded_conv3d.cc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_single_threaded_conv3d.cc new file mode 100644 index 0000000000000000000000000000000000000000..154d4369e3e3c64734c30ef85cc6e7503d823a55 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_single_threaded_conv3d.cc @@ -0,0 +1,65 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#include "xla/service/cpu/runtime_single_threaded_conv3d.h" + +#include "absl/base/dynamic_annotations.h" +#include "xla/service/cpu/runtime_conv_impl.h" + +ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY void +__xla_cpu_runtime_EigenSingleThreadedConv3DF32( + const void* /*run_options_ptr*/, float* out, float* lhs, float* rhs, + int64_t input_batch, int64_t input_x, int64_t input_y, int64_t input_z, + int64_t input_channels, int64_t kernel_x, int64_t kernel_y, + int64_t kernel_z, int64_t kernel_channels, int64_t kernel_filters, + int64_t output_x, int64_t output_y, int64_t output_z, int64_t x_stride, + int64_t y_stride, int64_t z_stride, int64_t padding_x_before, + int64_t padding_x_after, int64_t padding_y_before, int64_t padding_y_after, + int64_t padding_z_before, int64_t padding_z_after, int64_t lhs_x_dilation, + int64_t lhs_y_dilation, int64_t lhs_z_dilation, int64_t rhs_x_dilation, + int64_t rhs_y_dilation, int64_t rhs_z_dilation, + int64_t feature_group_count) { + tensorflow::xla::EigenConv3DImpl( + Eigen::DefaultDevice(), out, lhs, rhs, input_batch, input_x, input_y, + input_z, input_channels, kernel_x, kernel_y, kernel_z, kernel_channels, + kernel_filters, output_x, output_y, output_z, x_stride, y_stride, + z_stride, padding_x_before, padding_x_after, padding_y_before, + padding_y_after, padding_z_before, padding_z_after, lhs_x_dilation, + lhs_y_dilation, lhs_z_dilation, rhs_x_dilation, rhs_y_dilation, + rhs_z_dilation, feature_group_count); +} + +ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY void +__xla_cpu_runtime_EigenSingleThreadedConv3DF16( + const void* /*run_options_ptr*/, Eigen::half* out, Eigen::half* lhs, + Eigen::half* rhs, int64_t input_batch, int64_t input_x, int64_t input_y, + int64_t input_z, int64_t input_channels, int64_t kernel_x, int64_t kernel_y, + int64_t kernel_z, int64_t kernel_channels, int64_t kernel_filters, + int64_t output_x, int64_t output_y, int64_t output_z, int64_t x_stride, + int64_t y_stride, int64_t z_stride, int64_t padding_x_before, + int64_t padding_x_after, int64_t padding_y_before, int64_t padding_y_after, + int64_t padding_z_before, int64_t padding_z_after, int64_t lhs_x_dilation, + int64_t lhs_y_dilation, int64_t lhs_z_dilation, int64_t rhs_x_dilation, + int64_t rhs_y_dilation, int64_t rhs_z_dilation, + int64_t feature_group_count) { + tensorflow::xla::EigenConv3DImpl( + Eigen::DefaultDevice(), out, lhs, rhs, input_batch, input_x, input_y, + input_z, input_channels, kernel_x, kernel_y, kernel_z, kernel_channels, + kernel_filters, output_x, output_y, output_z, x_stride, y_stride, + z_stride, padding_x_before, padding_x_after, padding_y_before, + padding_y_after, padding_z_before, padding_z_after, lhs_x_dilation, + lhs_y_dilation, lhs_z_dilation, rhs_x_dilation, rhs_y_dilation, + rhs_z_dilation, feature_group_count); +} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_single_threaded_fft.cc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_single_threaded_fft.cc new file mode 100644 index 0000000000000000000000000000000000000000..56897d28806aa44ed9b7137ad14ad4b266452d98 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_single_threaded_fft.cc @@ -0,0 +1,29 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#include "xla/service/cpu/runtime_single_threaded_fft.h" + +#include "absl/base/dynamic_annotations.h" +#include "xla/service/cpu/runtime_fft_impl.h" + +ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY void __xla_cpu_runtime_EigenSingleThreadedFft( + const void* run_options_ptr, void* out, void* operand, int32_t fft_type, + int32_t double_precision, int32_t fft_rank, int64_t input_batch, + int64_t fft_length0, int64_t fft_length1, int64_t fft_length2) { + xla::EigenFftImpl(Eigen::DefaultDevice(), out, operand, + static_cast(fft_type), + static_cast(double_precision), fft_rank, input_batch, + fft_length0, fft_length1, fft_length2); +} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_single_threaded_matmul_c128.cc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_single_threaded_matmul_c128.cc new file mode 100644 index 0000000000000000000000000000000000000000..921b5b4317496565873b771bd3460981e24dc02e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_single_threaded_matmul_c128.cc @@ -0,0 +1,31 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#include "xla/service/cpu/runtime_single_threaded_matmul.h" + +#include +#include + +#include "absl/base/attributes.h" +#include "xla/service/cpu/runtime_single_threaded_matmul_common.h" + +ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY void +__xla_cpu_runtime_EigenSingleThreadedMatMulC128( + const void* run_options_ptr, std::complex* out, + std::complex* lhs, std::complex* rhs, int64_t m, int64_t n, + int64_t k, int32_t transpose_lhs, int32_t transpose_rhs) { + xla::SingleThreadedMatMulDispatch>( + run_options_ptr, out, lhs, rhs, m, n, k, transpose_lhs, transpose_rhs); +} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_single_threaded_matmul_c64.cc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_single_threaded_matmul_c64.cc new file mode 100644 index 0000000000000000000000000000000000000000..64341138b638a5d42b71a6b9a0fb7ff53e1d8b91 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_single_threaded_matmul_c64.cc @@ -0,0 +1,31 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#include "xla/service/cpu/runtime_single_threaded_matmul.h" + +#include +#include + +#include "absl/base/attributes.h" +#include "xla/service/cpu/runtime_single_threaded_matmul_common.h" + +ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY void +__xla_cpu_runtime_EigenSingleThreadedMatMulC64( + const void* run_options_ptr, std::complex* out, + std::complex* lhs, std::complex* rhs, int64_t m, int64_t n, + int64_t k, int32_t transpose_lhs, int32_t transpose_rhs) { + xla::SingleThreadedMatMulDispatch>( + run_options_ptr, out, lhs, rhs, m, n, k, transpose_lhs, transpose_rhs); +} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_single_threaded_matmul_common.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_single_threaded_matmul_common.h new file mode 100644 index 0000000000000000000000000000000000000000..f6e3cd5c34209bfdbcf8978dfc64deb9fabc498f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_single_threaded_matmul_common.h @@ -0,0 +1,88 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_CPU_RUNTIME_SINGLE_THREADED_MATMUL_COMMON_H_ +#define XLA_SERVICE_CPU_RUNTIME_SINGLE_THREADED_MATMUL_COMMON_H_ + +#include + +#include "absl/base/attributes.h" +#include "Eigen/Core" // from @eigen_archive +#include "unsupported/Eigen/CXX11/Tensor" // from @eigen_archive + +#if defined(TENSORFLOW_USE_CUSTOM_CONTRACTION_KERNEL) +#include "tsl/framework/contraction/eigen_contraction_kernel.h" +#endif + +namespace xla { + +static inline bool Is16BytesAligned(void* ptr) { + return reinterpret_cast(ptr) % 16 == 0; +} + +template +void SingleThreadedMatMul(const void* run_options_ptr, T* out, T* lhs, T* rhs, + int64_t m, int64_t n, int64_t k, + int32_t transpose_lhs, int32_t transpose_rhs) { + int64_t lhs_rows = m; + int64_t lhs_cols = k; + if (transpose_lhs) { + std::swap(lhs_rows, lhs_cols); + } + + int64_t rhs_rows = k; + int64_t rhs_cols = n; + if (transpose_rhs) { + std::swap(rhs_rows, rhs_cols); + } + + const Eigen::TensorMap, Alignment> A(lhs, lhs_rows, + lhs_cols); + const Eigen::TensorMap, Alignment> B(rhs, rhs_rows, + rhs_cols); + Eigen::TensorMap, Alignment> C(out, m, n); + + typedef typename Eigen::Tensor::DimensionPair DimPair; + int lhs_contract_dim = transpose_lhs ? 0 : 1; + int rhs_contract_dim = transpose_rhs ? 1 : 0; + const Eigen::array dims( + {DimPair(lhs_contract_dim, rhs_contract_dim)}); + + // Matrix multiply is a special case of the "contract" operation where + // the contraction is performed along dimension 1 of the lhs and dimension + // 0 of the rhs. + C = A.contract(B, dims); +} + +template +void SingleThreadedMatMulDispatch(const void* run_options_ptr, T* out, T* lhs, + T* rhs, int64_t m, int64_t n, int64_t k, + int32_t transpose_lhs, + int32_t transpose_rhs) { + bool all_buffers_16b_aligned = + Is16BytesAligned(out) && Is16BytesAligned(lhs) && Is16BytesAligned(rhs); + + if (!all_buffers_16b_aligned) { + SingleThreadedMatMul( + run_options_ptr, out, lhs, rhs, m, n, k, transpose_lhs, transpose_rhs); + } + + SingleThreadedMatMul(run_options_ptr, out, lhs, rhs, m, + n, k, transpose_lhs, transpose_rhs); +} + +} // namespace xla + +#endif // XLA_SERVICE_CPU_RUNTIME_SINGLE_THREADED_MATMUL_COMMON_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_single_threaded_matmul_f16.cc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_single_threaded_matmul_f16.cc new file mode 100644 index 0000000000000000000000000000000000000000..f9f44ff12899ef0948afb7e2fa4d9b44b41fd626 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_single_threaded_matmul_f16.cc @@ -0,0 +1,31 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#include "xla/service/cpu/runtime_single_threaded_matmul.h" + +#include + +#include "absl/base/attributes.h" +#include "Eigen/Core" // from @eigen_archive +#include "xla/service/cpu/runtime_single_threaded_matmul_common.h" + +ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY void +__xla_cpu_runtime_EigenSingleThreadedMatMulF16( + const void* run_options_ptr, Eigen::half* out, Eigen::half* lhs, + Eigen::half* rhs, int64_t m, int64_t n, int64_t k, int32_t transpose_lhs, + int32_t transpose_rhs) { + xla::SingleThreadedMatMulDispatch( + run_options_ptr, out, lhs, rhs, m, n, k, transpose_lhs, transpose_rhs); +} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_single_threaded_matmul_f32.cc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_single_threaded_matmul_f32.cc new file mode 100644 index 0000000000000000000000000000000000000000..85339d895af4f51cbb1fa3f677a7bca673b93e61 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_single_threaded_matmul_f32.cc @@ -0,0 +1,31 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#include "xla/service/cpu/runtime_single_threaded_matmul.h" + +#include + +#include "absl/base/attributes.h" +#include "xla/service/cpu/runtime_single_threaded_matmul_common.h" + +ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY void +__xla_cpu_runtime_EigenSingleThreadedMatMulF32(const void* run_options_ptr, + float* out, float* lhs, + float* rhs, int64_t m, int64_t n, + int64_t k, int32_t transpose_lhs, + int32_t transpose_rhs) { + xla::SingleThreadedMatMulDispatch(run_options_ptr, out, lhs, rhs, m, n, + k, transpose_lhs, transpose_rhs); +} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_single_threaded_matmul_f64.cc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_single_threaded_matmul_f64.cc new file mode 100644 index 0000000000000000000000000000000000000000..989fc520de41dbd3b05dac1337f190382525a4ba --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_single_threaded_matmul_f64.cc @@ -0,0 +1,32 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#include "xla/service/cpu/runtime_single_threaded_matmul.h" + +#include + +#include "absl/base/attributes.h" +#include "xla/service/cpu/runtime_single_threaded_matmul_common.h" + +ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY void +__xla_cpu_runtime_EigenSingleThreadedMatMulF64(const void* run_options_ptr, + double* out, double* lhs, + double* rhs, int64_t m, + int64_t n, int64_t k, + int32_t transpose_lhs, + int32_t transpose_rhs) { + xla::SingleThreadedMatMulDispatch(run_options_ptr, out, lhs, rhs, m, + n, k, transpose_lhs, transpose_rhs); +} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_single_threaded_matmul_s32.cc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_single_threaded_matmul_s32.cc new file mode 100644 index 0000000000000000000000000000000000000000..5f14070da155abe45f185310c4851f4f32acac20 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_single_threaded_matmul_s32.cc @@ -0,0 +1,32 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#include "xla/service/cpu/runtime_single_threaded_matmul.h" + +#include + +#include "absl/base/attributes.h" +#include "xla/service/cpu/runtime_single_threaded_matmul_common.h" + +ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY void +__xla_cpu_runtime_EigenSingleThreadedMatMulS32(const void* run_options_ptr, + int32_t* out, int32_t* lhs, + int32_t* rhs, int64_t m, + int64_t n, int64_t k, + int32_t transpose_lhs, + int32_t transpose_rhs) { + xla::SingleThreadedMatMulDispatch( + run_options_ptr, out, lhs, rhs, m, n, k, transpose_lhs, transpose_rhs); +} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_topk.cc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_topk.cc new file mode 100644 index 0000000000000000000000000000000000000000..d59ccea13df3bf7456e3b29d801c48de0424917f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/cpu/runtime_topk.cc @@ -0,0 +1,75 @@ +/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#include "xla/service/cpu/runtime_topk.h" + +#include +#include +#include +#include +#include +#include + +#include "absl/base/dynamic_annotations.h" + +template +static void TopK(int64_t batch_size, int64_t input_size, int64_t k, + const T* values, T* out_values, int32_t* out_indices) { + // 'values' is managed by the JIT code, so msan can't tell they are + // initialized. + ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(values, + input_size * batch_size * sizeof(T)); + + std::vector temp_indices(input_size); + for (int64_t batch = 0; batch != batch_size; ++batch) { + std::iota(temp_indices.begin(), temp_indices.end(), 0); + + const T* values_batch = values + batch * input_size; + + auto convert_to_int = [](T value) { + uint32_t x; + std::memcpy(&x, &value, sizeof(x)); + return static_cast(x) < 0 + ? std::numeric_limits::max() - x + : x; + }; + + auto kth_element = temp_indices.begin() + k; + std::partial_sort(temp_indices.begin(), kth_element, temp_indices.end(), + [&](size_t i1, size_t i2) { + // Do the comparison in integers to enforce a total + // order of -NaN < -Inf < -0 < +0 < +Inf < +NaN. + int32_t v1 = convert_to_int(values_batch[i1]); + int32_t v2 = convert_to_int(values_batch[i2]); + if (v1 == v2) { + return i1 < i2; // Stabilize sorting. + } + return v1 > v2; + }); + + T* out_values_batch = out_values + batch * k; + int32_t* out_indices_batch = out_indices + batch * k; + std::copy(temp_indices.begin(), kth_element, out_indices_batch); + for (int64_t i = 0; i < k; i++) { + out_values_batch[i] = values_batch[temp_indices[i]]; + } + } +} + +ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY void __xla_cpu_runtime_TopKF32( + int64_t batch_size, int64_t input_size, int64_t k, const float* values, + float* out_values, int32_t* out_indices) { + TopK(batch_size, input_size, k, values, out_values, out_indices); +} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/custom_call_status.cc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/custom_call_status.cc new file mode 100644 index 0000000000000000000000000000000000000000..2e07ef3c51fcd5acadb39aace5e74637493b3f58 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/xla_aot_runtime_src/xla/service/custom_call_status.cc @@ -0,0 +1,35 @@ +/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#include "xla/service/custom_call_status_internal.h" + +namespace xla { +// Internal functions + +std::optional CustomCallStatusGetMessage( + const XlaCustomCallStatus* status) { + return status->message; +} + +} // namespace xla + +void XlaCustomCallStatusSetSuccess(XlaCustomCallStatus* status) { + status->message = std::nullopt; +} + +void XlaCustomCallStatusSetFailure(XlaCustomCallStatus* status, + const char* message, size_t message_len) { + status->message = std::string(message, strnlen(message, message_len)); +} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator-2.15.0.dist-info/INSTALLER b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator-2.15.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator-2.15.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator-2.15.0.dist-info/METADATA b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator-2.15.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..1e24a77f8572a0452838aa3773c9ae75ff5e9889 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator-2.15.0.dist-info/METADATA @@ -0,0 +1,29 @@ +Metadata-Version: 2.1 +Name: tensorflow-estimator +Version: 2.15.0 +Summary: TensorFlow Estimator. +Home-page: https://www.tensorflow.org/ +Download-URL: https://github.com/tensorflow/estimator/tags +Author: Google Inc. +License: Apache 2.0 +Keywords: tensorflow estimator tensor machine learning +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: Education +Classifier: Intended Audience :: Science/Research +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Topic :: Scientific/Engineering +Classifier: Topic :: Scientific/Engineering :: Mathematics +Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence +Classifier: Topic :: Software Development +Classifier: Topic :: Software Development :: Libraries +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Requires-Python: >=3.7 + +TensorFlow Estimator is a high-level API that encapsulates model training, +evaluation, prediction, and exporting. diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator-2.15.0.dist-info/RECORD b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator-2.15.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..bd9ada25ed8f92c23bea1487d8b8c6c17e86a57f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator-2.15.0.dist-info/RECORD @@ -0,0 +1,237 @@ +tensorflow_estimator-2.15.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +tensorflow_estimator-2.15.0.dist-info/METADATA,sha256=LHw_VYPy1CWDQiXkVKUMA46RlHm9wld78VFgp5un00I,1276 +tensorflow_estimator-2.15.0.dist-info/RECORD,, +tensorflow_estimator-2.15.0.dist-info/WHEEL,sha256=iYlv5fX357PQyRT2o6tw1bN-YcKFFHKqB_LwHO5wP-g,110 +tensorflow_estimator-2.15.0.dist-info/top_level.txt,sha256=I5a_-JjZRx_kmmdAqOEr7B9_4ynRkb0cLUdgoYHDeJY,21 +tensorflow_estimator/__init__.py,sha256=RgAj1e3EB5-HQzr4Dm-CdfbpNONZQIHJXCQkMQHG34w,557 +tensorflow_estimator/__pycache__/__init__.cpython-310.pyc,, +tensorflow_estimator/_api/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow_estimator/_api/__pycache__/__init__.cpython-310.pyc,, +tensorflow_estimator/_api/v1/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow_estimator/_api/v1/__pycache__/__init__.cpython-310.pyc,, +tensorflow_estimator/_api/v1/__pycache__/v1.cpython-310.pyc,, +tensorflow_estimator/_api/v1/estimator/__init__.py,sha256=zRdMbFDT8IDNfuL-XHBiYDsAN7hqfmUp3t06H5KoetI,5918 +tensorflow_estimator/_api/v1/estimator/__pycache__/__init__.cpython-310.pyc,, +tensorflow_estimator/_api/v1/estimator/experimental/__init__.py,sha256=7Q7g0hZ_7H-53DMcxpi0c_t_bYCh7GnvWX6kNvmmGIA,1833 +tensorflow_estimator/_api/v1/estimator/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow_estimator/_api/v1/estimator/export/__init__.py,sha256=sySwkYwdzrDq__FkgW9OIxsbZ3udykrJmVwwnWNNwKQ,1453 +tensorflow_estimator/_api/v1/estimator/export/__pycache__/__init__.cpython-310.pyc,, +tensorflow_estimator/_api/v1/estimator/inputs/__init__.py,sha256=zjEJ8Y099I3ZwZLuFqSnibJvmmQXYAVSfYSJaJoqzbE,725 +tensorflow_estimator/_api/v1/estimator/inputs/__pycache__/__init__.cpython-310.pyc,, +tensorflow_estimator/_api/v1/estimator/tpu/__init__.py,sha256=a3SVsLU0m58gZKlTTWWdtlcpUIw8HDvMywHXAFzEswA,1061 +tensorflow_estimator/_api/v1/estimator/tpu/__pycache__/__init__.cpython-310.pyc,, +tensorflow_estimator/_api/v1/estimator/tpu/experimental/__init__.py,sha256=5vGlPIS1Mxpd3yZSwzb2S46i9H7oA-kTRw0qz3URtqg,670 +tensorflow_estimator/_api/v1/estimator/tpu/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow_estimator/_api/v1/v1.py,sha256=RgAj1e3EB5-HQzr4Dm-CdfbpNONZQIHJXCQkMQHG34w,557 +tensorflow_estimator/_api/v2/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow_estimator/_api/v2/__pycache__/__init__.cpython-310.pyc,, +tensorflow_estimator/_api/v2/__pycache__/v2.cpython-310.pyc,, +tensorflow_estimator/_api/v2/estimator/__init__.py,sha256=JZNQyNF1mWtdJmdxnuiVvzIhRbVR8liRAKJUhvC9Lv0,5868 +tensorflow_estimator/_api/v2/estimator/__pycache__/__init__.cpython-310.pyc,, +tensorflow_estimator/_api/v2/estimator/experimental/__init__.py,sha256=daqeqo6-B-VPBt5hJXIhcxpZhVhkkSB3WfpHdQNuSis,1389 +tensorflow_estimator/_api/v2/estimator/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow_estimator/_api/v2/estimator/export/__init__.py,sha256=R2Afbs8l2Z39Bp6ya--_cHWtU8pcZXf_B5_MV1NCGvQ,1138 +tensorflow_estimator/_api/v2/estimator/export/__pycache__/__init__.cpython-310.pyc,, +tensorflow_estimator/_api/v2/estimator/inputs/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow_estimator/_api/v2/estimator/inputs/__pycache__/__init__.cpython-310.pyc,, +tensorflow_estimator/_api/v2/v2.py,sha256=YhnqveiWuchOhvLk_4oGs3lQr4TItJSXNZ2U_wjaEmg,258 +tensorflow_estimator/python/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow_estimator/python/__pycache__/__init__.cpython-310.pyc,, +tensorflow_estimator/python/estimator/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow_estimator/python/estimator/__pycache__/__init__.cpython-310.pyc,, +tensorflow_estimator/python/estimator/__pycache__/early_stopping.cpython-310.pyc,, +tensorflow_estimator/python/estimator/__pycache__/estimator.cpython-310.pyc,, +tensorflow_estimator/python/estimator/__pycache__/estimator_export.cpython-310.pyc,, +tensorflow_estimator/python/estimator/__pycache__/estimator_lib.cpython-310.pyc,, +tensorflow_estimator/python/estimator/__pycache__/exporter.cpython-310.pyc,, +tensorflow_estimator/python/estimator/__pycache__/extenders.cpython-310.pyc,, +tensorflow_estimator/python/estimator/__pycache__/gc.cpython-310.pyc,, +tensorflow_estimator/python/estimator/__pycache__/keras_lib.cpython-310.pyc,, +tensorflow_estimator/python/estimator/__pycache__/mode_keys.cpython-310.pyc,, +tensorflow_estimator/python/estimator/__pycache__/model_fn.cpython-310.pyc,, +tensorflow_estimator/python/estimator/__pycache__/run_config.cpython-310.pyc,, +tensorflow_estimator/python/estimator/__pycache__/training.cpython-310.pyc,, +tensorflow_estimator/python/estimator/__pycache__/util.cpython-310.pyc,, +tensorflow_estimator/python/estimator/api/__init__.py,sha256=647OwS7suQGAaoN-kTIneiCXg-rBKg9kRNfQXIllFms,591 +tensorflow_estimator/python/estimator/api/__pycache__/__init__.cpython-310.pyc,, +tensorflow_estimator/python/estimator/api/_v1/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow_estimator/python/estimator/api/_v1/__pycache__/__init__.cpython-310.pyc,, +tensorflow_estimator/python/estimator/api/_v1/__pycache__/v1.cpython-310.pyc,, +tensorflow_estimator/python/estimator/api/_v1/estimator/__init__.py,sha256=jjseOoKwjAzHdhIWEkBAWVC54mLmdmQAk_tk4VhJVVU,6003 +tensorflow_estimator/python/estimator/api/_v1/estimator/__pycache__/__init__.cpython-310.pyc,, +tensorflow_estimator/python/estimator/api/_v1/estimator/experimental/__init__.py,sha256=UYX3N77j2wexA4LKQXW9GVzxtU4FkbMAI7KuZEOHpzM,1850 +tensorflow_estimator/python/estimator/api/_v1/estimator/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow_estimator/python/estimator/api/_v1/estimator/export/__init__.py,sha256=DcfAeS6AccFeLs0BeQr3MhDVwK48e1x2PC27UH2Cr3Y,1470 +tensorflow_estimator/python/estimator/api/_v1/estimator/export/__pycache__/__init__.cpython-310.pyc,, +tensorflow_estimator/python/estimator/api/_v1/estimator/inputs/__init__.py,sha256=k5d2SfVqqMriut_Pa1v5x7veNbA9jU6jYujV6LB0jI4,742 +tensorflow_estimator/python/estimator/api/_v1/estimator/inputs/__pycache__/__init__.cpython-310.pyc,, +tensorflow_estimator/python/estimator/api/_v1/estimator/tpu/__init__.py,sha256=_L8NSaV-T0AxbllKgPdMA7sGgkX15MgC_o3vM_INaTk,1095 +tensorflow_estimator/python/estimator/api/_v1/estimator/tpu/__pycache__/__init__.cpython-310.pyc,, +tensorflow_estimator/python/estimator/api/_v1/estimator/tpu/experimental/__init__.py,sha256=P3ueUv1OmB6MiI1ymZrhtDzDN1yUQI0lRQqQEg4XGAw,687 +tensorflow_estimator/python/estimator/api/_v1/estimator/tpu/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow_estimator/python/estimator/api/_v1/v1.py,sha256=647OwS7suQGAaoN-kTIneiCXg-rBKg9kRNfQXIllFms,591 +tensorflow_estimator/python/estimator/api/_v2/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow_estimator/python/estimator/api/_v2/__pycache__/__init__.cpython-310.pyc,, +tensorflow_estimator/python/estimator/api/_v2/__pycache__/v2.cpython-310.pyc,, +tensorflow_estimator/python/estimator/api/_v2/estimator/__init__.py,sha256=7yq3cLrBzQ6mmU3k_ygv3F4YzQrNUJFQ8QQFdlpOZmI,5919 +tensorflow_estimator/python/estimator/api/_v2/estimator/__pycache__/__init__.cpython-310.pyc,, +tensorflow_estimator/python/estimator/api/_v2/estimator/experimental/__init__.py,sha256=5NZLVY2if_uCpcSiUi16pUmf2rTsKFLS7hB3H_HsWXU,1406 +tensorflow_estimator/python/estimator/api/_v2/estimator/experimental/__pycache__/__init__.cpython-310.pyc,, +tensorflow_estimator/python/estimator/api/_v2/estimator/export/__init__.py,sha256=ZxXg_L-ia4O1_Yc71OBekQzZFcAF-r8IIhpZymEFXOo,1155 +tensorflow_estimator/python/estimator/api/_v2/estimator/export/__pycache__/__init__.cpython-310.pyc,, +tensorflow_estimator/python/estimator/api/_v2/estimator/inputs/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow_estimator/python/estimator/api/_v2/estimator/inputs/__pycache__/__init__.cpython-310.pyc,, +tensorflow_estimator/python/estimator/api/_v2/v2.py,sha256=wv7jToCi1vJ0F6hjJU0shmpMzRq-yatxUHq_VaL7Ixg,292 +tensorflow_estimator/python/estimator/canned/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow_estimator/python/estimator/canned/__pycache__/__init__.cpython-310.pyc,, +tensorflow_estimator/python/estimator/canned/__pycache__/baseline.cpython-310.pyc,, +tensorflow_estimator/python/estimator/canned/__pycache__/dnn.cpython-310.pyc,, +tensorflow_estimator/python/estimator/canned/__pycache__/dnn_linear_combined.cpython-310.pyc,, +tensorflow_estimator/python/estimator/canned/__pycache__/dnn_testing_utils.cpython-310.pyc,, +tensorflow_estimator/python/estimator/canned/__pycache__/head.cpython-310.pyc,, +tensorflow_estimator/python/estimator/canned/__pycache__/kmeans.cpython-310.pyc,, +tensorflow_estimator/python/estimator/canned/__pycache__/linear.cpython-310.pyc,, +tensorflow_estimator/python/estimator/canned/__pycache__/linear_testing_utils.cpython-310.pyc,, +tensorflow_estimator/python/estimator/canned/__pycache__/metric_keys.cpython-310.pyc,, +tensorflow_estimator/python/estimator/canned/__pycache__/optimizers.cpython-310.pyc,, +tensorflow_estimator/python/estimator/canned/__pycache__/parsing_utils.cpython-310.pyc,, +tensorflow_estimator/python/estimator/canned/__pycache__/prediction_keys.cpython-310.pyc,, +tensorflow_estimator/python/estimator/canned/__pycache__/rnn.cpython-310.pyc,, +tensorflow_estimator/python/estimator/canned/__pycache__/saved_model_estimator.cpython-310.pyc,, +tensorflow_estimator/python/estimator/canned/baseline.py,sha256=2sz97HvaVnIxTBNkPHGN8L_ZFPCW2Nkoa8r8DtQXhKs,23473 +tensorflow_estimator/python/estimator/canned/dnn.py,sha256=xrEYFdsXpdOesxE1d_Wf6e6bLW-QuSPdp5BDlzMHmaw,48403 +tensorflow_estimator/python/estimator/canned/dnn_linear_combined.py,sha256=TMkCfCO3lOpfgRYWokosevcwKwyIIVv1qLsR4weRfKM,48471 +tensorflow_estimator/python/estimator/canned/dnn_testing_utils.py,sha256=VyzICgDlVsTcHiN6O3Tuwl8RyVimeLHcSdLZgWrOpfc,82060 +tensorflow_estimator/python/estimator/canned/head.py,sha256=kLKW7ZGOm5U9XCltxwLb8n84F79ie_j2kTEpK1jPmPw,72566 +tensorflow_estimator/python/estimator/canned/kmeans.py,sha256=LPyTxdFcJ7IjHlMd0b17tnWUqL6-lFBBwDtHw-eDfh8,20395 +tensorflow_estimator/python/estimator/canned/linear.py,sha256=DtgvYZ2mG357jK0-MspnnwB5rqPed060JDDA1sxdmTE,68064 +tensorflow_estimator/python/estimator/canned/linear_optimizer/__init__.py,sha256=MLbcdSxHXsd5ySoHzyIcLAakGCMK0AfrrN336JEKnUw,994 +tensorflow_estimator/python/estimator/canned/linear_optimizer/__pycache__/__init__.cpython-310.pyc,, +tensorflow_estimator/python/estimator/canned/linear_optimizer/python/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow_estimator/python/estimator/canned/linear_optimizer/python/__pycache__/__init__.cpython-310.pyc,, +tensorflow_estimator/python/estimator/canned/linear_optimizer/python/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow_estimator/python/estimator/canned/linear_optimizer/python/utils/__pycache__/__init__.cpython-310.pyc,, +tensorflow_estimator/python/estimator/canned/linear_optimizer/python/utils/__pycache__/sdca_ops.cpython-310.pyc,, +tensorflow_estimator/python/estimator/canned/linear_optimizer/python/utils/__pycache__/sharded_mutable_dense_hashtable.cpython-310.pyc,, +tensorflow_estimator/python/estimator/canned/linear_optimizer/python/utils/sdca_ops.py,sha256=rvxlg4GFEFo573C6a6BZmHZBK70wsEBgNE23AtEWShI,32502 +tensorflow_estimator/python/estimator/canned/linear_optimizer/python/utils/sharded_mutable_dense_hashtable.py,sha256=eITEchvBA_L1DP5V-7df3stTD_nFmvkjzN1Dk8HfpnA,14506 +tensorflow_estimator/python/estimator/canned/linear_testing_utils.py,sha256=p_mv2gRJPCnra2lewoE0DZU1EQbSv3oaFmJisuqxu0s,84203 +tensorflow_estimator/python/estimator/canned/metric_keys.py,sha256=6PP6vlsIpYTtBS4Z5HNWmiKBKPukLPZrPNoxmLIrNiA,2364 +tensorflow_estimator/python/estimator/canned/optimizers.py,sha256=FAKvos2jKUubuJkBo71NWenfqKjSe5eQp8LQwagBcKc,6332 +tensorflow_estimator/python/estimator/canned/parsing_utils.py,sha256=M5IRXs1eA6JY5XQMMCEwTKWMpYOp53iD1hyv6C6S4dY,15354 +tensorflow_estimator/python/estimator/canned/prediction_keys.py,sha256=zjnNIOLJkzGKNXAUVYKLzkPv3Zm8mQXy7BrSiPQGApg,1275 +tensorflow_estimator/python/estimator/canned/rnn.py,sha256=ULYKHdKHcumg67mZ6MH2sIdDxuMygI2Y8T5CUTUuOgU,28682 +tensorflow_estimator/python/estimator/canned/saved_model_estimator.py,sha256=u6Kf1zRKHHF7j8kAxi09Ls0e2DYklcRkiLDA62f70iQ,20175 +tensorflow_estimator/python/estimator/canned/timeseries/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow_estimator/python/estimator/canned/timeseries/__pycache__/__init__.cpython-310.pyc,, +tensorflow_estimator/python/estimator/canned/timeseries/__pycache__/ar_model.cpython-310.pyc,, +tensorflow_estimator/python/estimator/canned/timeseries/__pycache__/estimators.cpython-310.pyc,, +tensorflow_estimator/python/estimator/canned/timeseries/__pycache__/feature_keys.cpython-310.pyc,, +tensorflow_estimator/python/estimator/canned/timeseries/__pycache__/head.cpython-310.pyc,, +tensorflow_estimator/python/estimator/canned/timeseries/__pycache__/math_utils.cpython-310.pyc,, +tensorflow_estimator/python/estimator/canned/timeseries/__pycache__/model.cpython-310.pyc,, +tensorflow_estimator/python/estimator/canned/timeseries/__pycache__/model_utils.cpython-310.pyc,, +tensorflow_estimator/python/estimator/canned/timeseries/__pycache__/saved_model_utils.cpython-310.pyc,, +tensorflow_estimator/python/estimator/canned/timeseries/__pycache__/state_management.cpython-310.pyc,, +tensorflow_estimator/python/estimator/canned/timeseries/ar_model.py,sha256=Zo3fwCaIC6KaQVrzPTH3C6WLrpfA2vmIhczWMBSMePs,38336 +tensorflow_estimator/python/estimator/canned/timeseries/estimators.py,sha256=Hq0JC8B_hPDGvIm6cjg7e302pX27wYbovDtgcmgK9xA,20770 +tensorflow_estimator/python/estimator/canned/timeseries/feature_keys.py,sha256=CLMNttwFVloDyAfbvl37ov85o8dt51K94H83C8u7pTM,2314 +tensorflow_estimator/python/estimator/canned/timeseries/head.py,sha256=Q-JPsPxRn_dNTB3sBYGUFK5_g6qC9KVMeIQqniMFLOc,21379 +tensorflow_estimator/python/estimator/canned/timeseries/math_utils.py,sha256=fbrrJqsS3oMN3mD8-Gmd0o2CsMci3-1PgeCjLSJC1wU,19761 +tensorflow_estimator/python/estimator/canned/timeseries/model.py,sha256=AbpPj-xlA79JXsqLLbE6dT5vSAvi58ZerCiPcrXnKII,14441 +tensorflow_estimator/python/estimator/canned/timeseries/model_utils.py,sha256=Sw3s8gDh-84RGNNHyYFF6sIw77arm90A-mD0xlOOcx8,3212 +tensorflow_estimator/python/estimator/canned/timeseries/saved_model_utils.py,sha256=FTBGOgJmvhOIRXvKfRQ7SBHkeGhZk22273dqkgowuFc,14941 +tensorflow_estimator/python/estimator/canned/timeseries/state_management.py,sha256=qnzTQulz0s28On9BqZl4RNGSY81foVLtknRd35m-mvI,4004 +tensorflow_estimator/python/estimator/canned/v1/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow_estimator/python/estimator/canned/v1/__pycache__/__init__.cpython-310.pyc,, +tensorflow_estimator/python/estimator/canned/v1/__pycache__/dnn_testing_utils_v1.cpython-310.pyc,, +tensorflow_estimator/python/estimator/canned/v1/__pycache__/linear_testing_utils_v1.cpython-310.pyc,, +tensorflow_estimator/python/estimator/canned/v1/dnn_testing_utils_v1.py,sha256=5dvNlrl30w-UFFRt0nAFrfYQxAivd7iF2K519BG2v3I,82598 +tensorflow_estimator/python/estimator/canned/v1/linear_testing_utils_v1.py,sha256=wFzO6wsdQ0IPguk629pQVHrtkagazz8lBsDm8pjnJqg,91091 +tensorflow_estimator/python/estimator/early_stopping.py,sha256=jFlbjNAja4nOEwueZRkNoIR0fmpE9bzaiNRB5pc2nS8,23550 +tensorflow_estimator/python/estimator/estimator.py,sha256=BqMXgpK4gh4wx-L76jVlPu30JjZMYF7sVPxdavrHOBc,103327 +tensorflow_estimator/python/estimator/estimator_export.py,sha256=bJqydJvbO5qiZZQvrMgQRufCVzvGtyGAl8aTNMYCofo,2425 +tensorflow_estimator/python/estimator/estimator_lib.py,sha256=4X7MN_7e2ynkDbmUXCdjnxDRcAaaUsfatkpK4pHXejw,4886 +tensorflow_estimator/python/estimator/export/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow_estimator/python/estimator/export/__pycache__/__init__.cpython-310.pyc,, +tensorflow_estimator/python/estimator/export/__pycache__/export.cpython-310.pyc,, +tensorflow_estimator/python/estimator/export/__pycache__/export_lib.cpython-310.pyc,, +tensorflow_estimator/python/estimator/export/__pycache__/export_output.cpython-310.pyc,, +tensorflow_estimator/python/estimator/export/__pycache__/function.cpython-310.pyc,, +tensorflow_estimator/python/estimator/export/export.py,sha256=nU1a8lU0l9NnPEwr2RaY_AWtkI_Y90qrDSdThR3bzg0,20652 +tensorflow_estimator/python/estimator/export/export_lib.py,sha256=CyumaeOc_6LrwFyYcyr9NKZiTdI9uphRcACtKuBa6F0,3055 +tensorflow_estimator/python/estimator/export/export_output.py,sha256=y-A1w-8XOdqWpeTxmM39lVy8c_lg4ZEhZysDiRb1gyE,1924 +tensorflow_estimator/python/estimator/export/function.py,sha256=YeXyS2XwT5uQ3rte2RCMYH0nT_opUf6m3qqg7YGijIg,13836 +tensorflow_estimator/python/estimator/exporter.py,sha256=F-d3bUTrcMBMPPmdevcu8bLETqb-K1HnoFcy6Urd3V4,19873 +tensorflow_estimator/python/estimator/extenders.py,sha256=gKnu3VkNtLLhHDCPUHq4Higyydzw_GHQstMeU3DnLQM,4896 +tensorflow_estimator/python/estimator/gc.py,sha256=u39vcSzNBDuqbdtO_KcHWv6yWIDTsnUDxTKzqcy4nF0,6327 +tensorflow_estimator/python/estimator/head/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow_estimator/python/estimator/head/__pycache__/__init__.cpython-310.pyc,, +tensorflow_estimator/python/estimator/head/__pycache__/base_head.cpython-310.pyc,, +tensorflow_estimator/python/estimator/head/__pycache__/binary_class_head.cpython-310.pyc,, +tensorflow_estimator/python/estimator/head/__pycache__/head_utils.cpython-310.pyc,, +tensorflow_estimator/python/estimator/head/__pycache__/multi_class_head.cpython-310.pyc,, +tensorflow_estimator/python/estimator/head/__pycache__/multi_head.cpython-310.pyc,, +tensorflow_estimator/python/estimator/head/__pycache__/multi_label_head.cpython-310.pyc,, +tensorflow_estimator/python/estimator/head/__pycache__/regression_head.cpython-310.pyc,, +tensorflow_estimator/python/estimator/head/__pycache__/sequential_head.cpython-310.pyc,, +tensorflow_estimator/python/estimator/head/base_head.py,sha256=LBQUWzpOlkvpi-0WuT4rOFNoa71RrCOBVCO7tK0yNhQ,39655 +tensorflow_estimator/python/estimator/head/binary_class_head.py,sha256=sNzSbpBnFusWamOJ6OJFrL5oitL6_wuKzNfeCc9x0Es,26876 +tensorflow_estimator/python/estimator/head/head_utils.py,sha256=Gs5A8UjAAk5X6ECRpQKDrdx-cuQaHQoxz8rikFCPDTw,3986 +tensorflow_estimator/python/estimator/head/multi_class_head.py,sha256=eRQthuoGGmVGSJAx23-leBwLtdoWxZN5UHG-2GHutGU,21400 +tensorflow_estimator/python/estimator/head/multi_head.py,sha256=UVqscFHSQZgcrYTNAIYPYon8CbHzRbrP-BZ33jy9Yls,23307 +tensorflow_estimator/python/estimator/head/multi_label_head.py,sha256=L7Px82_6RNRL0VjLJ821ArMIMYlC-53aA2x5astzF-o,26774 +tensorflow_estimator/python/estimator/head/regression_head.py,sha256=hsl5QhkmQGjKSLHFOI1_GfDFhSk8_N3oMfKctKqP5vE,23738 +tensorflow_estimator/python/estimator/head/sequential_head.py,sha256=VkV9Oe42ApfbOkkCCLGQxoCg9xQ8c1T1xXqexDOq9TA,20736 +tensorflow_estimator/python/estimator/hooks/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow_estimator/python/estimator/hooks/__pycache__/__init__.cpython-310.pyc,, +tensorflow_estimator/python/estimator/hooks/__pycache__/basic_session_run_hooks.cpython-310.pyc,, +tensorflow_estimator/python/estimator/hooks/__pycache__/fake_summary_writer.cpython-310.pyc,, +tensorflow_estimator/python/estimator/hooks/__pycache__/hooks.cpython-310.pyc,, +tensorflow_estimator/python/estimator/hooks/__pycache__/session_run_hook.cpython-310.pyc,, +tensorflow_estimator/python/estimator/hooks/basic_session_run_hooks.py,sha256=ZbglRqHgM7M_ziIdNsP51FiGGrSkskDkYGZ0o-6UruM,2835 +tensorflow_estimator/python/estimator/hooks/fake_summary_writer.py,sha256=mcenQ5maQfZnkwx-aXeIsvQliP7h1jQJ4xXtk354cnE,5595 +tensorflow_estimator/python/estimator/hooks/hooks.py,sha256=yz5TLJa6FjFtDC0gao-ZTRe3g0ZGT2u5zsz-PKR8X2E,11072 +tensorflow_estimator/python/estimator/hooks/session_run_hook.py,sha256=n-t7mLp18R_HIC7hKd1iNtK1LXZ0tmm8c-pWjdi10UE,4204 +tensorflow_estimator/python/estimator/inputs/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow_estimator/python/estimator/inputs/__pycache__/__init__.cpython-310.pyc,, +tensorflow_estimator/python/estimator/inputs/__pycache__/inputs.cpython-310.pyc,, +tensorflow_estimator/python/estimator/inputs/__pycache__/numpy_io.cpython-310.pyc,, +tensorflow_estimator/python/estimator/inputs/__pycache__/pandas_io.cpython-310.pyc,, +tensorflow_estimator/python/estimator/inputs/inputs.py,sha256=LlrWANUzivltc7re_cWw2GOFjA3Nv3Og6eDHE9_0b4M,1106 +tensorflow_estimator/python/estimator/inputs/numpy_io.py,sha256=gEOheCAe_7xXgXZEhDstlQCu5wVCy7M17v0zgdkNvnU,8018 +tensorflow_estimator/python/estimator/inputs/pandas_io.py,sha256=02HiXh15UwOGruoeTmt_-U3w1YXYFqUrY94H2lZcHL8,5859 +tensorflow_estimator/python/estimator/inputs/queues/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow_estimator/python/estimator/inputs/queues/__pycache__/__init__.cpython-310.pyc,, +tensorflow_estimator/python/estimator/inputs/queues/__pycache__/feeding_functions.cpython-310.pyc,, +tensorflow_estimator/python/estimator/inputs/queues/__pycache__/feeding_queue_runner.cpython-310.pyc,, +tensorflow_estimator/python/estimator/inputs/queues/feeding_functions.py,sha256=gA7rAl6PZyyRCTKnwG46OpYQDVlVUBqIqQXfzBB4Idk,18804 +tensorflow_estimator/python/estimator/inputs/queues/feeding_queue_runner.py,sha256=ncwpuDkE_UT_UoQhqa1iHJwYIyopkAlRNuvGlEOqWEw,6883 +tensorflow_estimator/python/estimator/keras_lib.py,sha256=LuZMw1XECr8NWvn1Xcxsdyvh1NromGLWhYAKa2sgbRo,33514 +tensorflow_estimator/python/estimator/mode_keys.py,sha256=oxefT5BvfVXUEHQJ9ITDhUun0lT0YAL-nTMjsYW-6SA,1080 +tensorflow_estimator/python/estimator/model_fn.py,sha256=2CTwQcWtUY73eGACSTbO2Aeipa2XWOmv92_jIkxBkTQ,25009 +tensorflow_estimator/python/estimator/run_config.py,sha256=ltwgC9FSn6hE_z4OtV5OYQz2HEv_-qO9_D3VHworX1s,38460 +tensorflow_estimator/python/estimator/tools/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow_estimator/python/estimator/tools/__pycache__/__init__.cpython-310.pyc,, +tensorflow_estimator/python/estimator/tools/__pycache__/analytics.cpython-310.pyc,, +tensorflow_estimator/python/estimator/tools/__pycache__/checkpoint_converter.cpython-310.pyc,, +tensorflow_estimator/python/estimator/tools/analytics.py,sha256=6u-GRvFu3eYiozLNbl7Aj0IVliDHtOxsnvOuT4k0YvI,1265 +tensorflow_estimator/python/estimator/tools/checkpoint_converter.py,sha256=X_hlYEgFlxtp6uJDsE1jVU6PS3PPM-XmDJhzeyi28FM,14924 +tensorflow_estimator/python/estimator/tpu/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow_estimator/python/estimator/tpu/__pycache__/__init__.cpython-310.pyc,, +tensorflow_estimator/python/estimator/tpu/__pycache__/_tpu_estimator_embedding.cpython-310.pyc,, +tensorflow_estimator/python/estimator/tpu/__pycache__/error_handling.cpython-310.pyc,, +tensorflow_estimator/python/estimator/tpu/__pycache__/iteration_count_estimator.cpython-310.pyc,, +tensorflow_estimator/python/estimator/tpu/__pycache__/tpu_config.cpython-310.pyc,, +tensorflow_estimator/python/estimator/tpu/__pycache__/tpu_context.cpython-310.pyc,, +tensorflow_estimator/python/estimator/tpu/__pycache__/tpu_estimator.cpython-310.pyc,, +tensorflow_estimator/python/estimator/tpu/__pycache__/util.cpython-310.pyc,, +tensorflow_estimator/python/estimator/tpu/_tpu_estimator_embedding.py,sha256=bZNhd0MRTegJLmMUoQb2k7aL4VewH9hnGzJcr3MNAbM,28939 +tensorflow_estimator/python/estimator/tpu/error_handling.py,sha256=brmHZ_LB3uGfKmWNcMAbj9GSaOjHCMXKdp8tmr_uwyA,5327 +tensorflow_estimator/python/estimator/tpu/iteration_count_estimator.py,sha256=-6F6Ap1jv3ukv7_S0G50LgjbTfd-lI7FqxhUoyvL63U,7833 +tensorflow_estimator/python/estimator/tpu/tpu_config.py,sha256=lbKqhXanQF0sYN_OnxZQjrgtzphgm1wP8DyEwcSrH8s,15727 +tensorflow_estimator/python/estimator/tpu/tpu_context.py,sha256=wZSf4WkDPjE8HfvotcGt34A1Hnugi4ZlUgbGr_VSUTc,34455 +tensorflow_estimator/python/estimator/tpu/tpu_estimator.py,sha256=3w65uhRCceF-P5Q1E8Y-OyMA_mP9yZO5dJnxUccj9Ng,184949 +tensorflow_estimator/python/estimator/tpu/util.py,sha256=tpB0jmmBzcCZPF5n7Rc3EsPdBXKtTeenl_UhlGJUhWw,3607 +tensorflow_estimator/python/estimator/training.py,sha256=5bzRUJiuwu8V_ToIBQ0U-UuXw5UZVvJ7EDjxNhrxNxE,44016 +tensorflow_estimator/python/estimator/util.py,sha256=s6smUjOOKng5RBDN3EyiV8O0CWPxT0ydhuvcACgdtcs,4129 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator-2.15.0.dist-info/WHEEL b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator-2.15.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..c34f1162ef9a50c355df1261ef6194ffc1b39975 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator-2.15.0.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.41.2) +Root-Is-Purelib: true +Tag: py2-none-any +Tag: py3-none-any + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator-2.15.0.dist-info/top_level.txt b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator-2.15.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..a909c9e72a454ff2b5fb26206bca47363c470ccd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator-2.15.0.dist-info/top_level.txt @@ -0,0 +1 @@ +tensorflow_estimator diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..997ce5df864a7a5a2e79954633f11dacd66aa63a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/__init__.py @@ -0,0 +1,15 @@ +# This file is MACHINE GENERATED! Do not edit. +# Generated by: tensorflow/python/tools/api/generator2/generator/generator.py script. +"""Public API for tf_estimator._api.v1 namespace +""" + +import sys as _sys + +from tensorflow_estimator._api.v1 import estimator + +from tensorflow.python.util import module_wrapper as _module_wrapper + +if not isinstance(_sys.modules[__name__], _module_wrapper.TFModuleWrapper): + _sys.modules[__name__] = _module_wrapper.TFModuleWrapper( + _sys.modules[__name__], "", public_apis=None, deprecation=True, + has_lite=False) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/_api/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/_api/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/_api/v1/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/_api/v1/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/_api/v1/estimator/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/_api/v1/estimator/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..faaa4fae5cd8d4d00ef5984e774145e0762ab757 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/_api/v1/estimator/__init__.py @@ -0,0 +1,71 @@ +# This file is MACHINE GENERATED! Do not edit. +# Generated by: tensorflow/python/tools/api/generator2/generator/generator.py script. +"""Public API for tf_estimator._api.v1.estimator namespace +""" + +import sys as _sys + +from tensorflow_estimator._api.v1.estimator import experimental +from tensorflow_estimator._api.v1.estimator import export +from tensorflow_estimator._api.v1.estimator import inputs +from tensorflow_estimator._api.v1.estimator import tpu +from tensorflow_estimator.python.estimator.canned.baseline import BaselineClassifier # line: 403 +from tensorflow_estimator.python.estimator.canned.baseline import BaselineEstimator # line: 511 +from tensorflow_estimator.python.estimator.canned.baseline import BaselineRegressor # line: 626 +from tensorflow_estimator.python.estimator.canned.dnn import DNNClassifier # line: 766 +from tensorflow_estimator.python.estimator.canned.dnn import DNNEstimator # line: 969 +from tensorflow_estimator.python.estimator.canned.dnn import DNNRegressor # line: 1179 +from tensorflow_estimator.python.estimator.canned.dnn_linear_combined import DNNLinearCombinedClassifier # line: 593 +from tensorflow_estimator.python.estimator.canned.dnn_linear_combined import DNNLinearCombinedEstimator # line: 851 +from tensorflow_estimator.python.estimator.canned.dnn_linear_combined import DNNLinearCombinedRegressor # line: 1090 +from tensorflow_estimator.python.estimator.canned.linear import LinearClassifier # line: 951 +from tensorflow_estimator.python.estimator.canned.linear import LinearEstimator # line: 1129 +from tensorflow_estimator.python.estimator.canned.linear import LinearRegressor # line: 1369 +from tensorflow_estimator.python.estimator.canned.parsing_utils import classifier_parse_example_spec # line: 315 +from tensorflow_estimator.python.estimator.canned.parsing_utils import regressor_parse_example_spec # line: 334 +from tensorflow_estimator.python.estimator.estimator import Estimator # line: 67 +from tensorflow_estimator.python.estimator.estimator import VocabInfo # line: 2173 +from tensorflow_estimator.python.estimator.estimator import WarmStartSettings # line: 2176 +from tensorflow_estimator.python.estimator.exporter import BestExporter # line: 164 +from tensorflow_estimator.python.estimator.exporter import Exporter # line: 30 +from tensorflow_estimator.python.estimator.exporter import FinalExporter # line: 368 +from tensorflow_estimator.python.estimator.exporter import LatestExporter # line: 421 +from tensorflow_estimator.python.estimator.extenders import add_metrics # line: 29 +from tensorflow_estimator.python.estimator.head.base_head import Head # line: 43 +from tensorflow_estimator.python.estimator.head.binary_class_head import BinaryClassHead # line: 33 +from tensorflow_estimator.python.estimator.head.multi_class_head import MultiClassHead # line: 33 +from tensorflow_estimator.python.estimator.head.multi_head import MultiHead # line: 52 +from tensorflow_estimator.python.estimator.head.multi_label_head import MultiLabelHead # line: 34 +from tensorflow_estimator.python.estimator.head.regression_head import LogisticRegressionHead # line: 499 +from tensorflow_estimator.python.estimator.head.regression_head import PoissonRegressionHead # line: 409 +from tensorflow_estimator.python.estimator.head.regression_head import RegressionHead # line: 33 +from tensorflow_estimator.python.estimator.hooks.basic_session_run_hooks import CheckpointSaverHook # line: 40 +from tensorflow_estimator.python.estimator.hooks.basic_session_run_hooks import CheckpointSaverListener # line: 39 +from tensorflow_estimator.python.estimator.hooks.basic_session_run_hooks import FeedFnHook # line: 48 +from tensorflow_estimator.python.estimator.hooks.basic_session_run_hooks import FinalOpsHook # line: 47 +from tensorflow_estimator.python.estimator.hooks.basic_session_run_hooks import GlobalStepWaiterHook # line: 46 +from tensorflow_estimator.python.estimator.hooks.basic_session_run_hooks import LoggingTensorHook # line: 37 +from tensorflow_estimator.python.estimator.hooks.basic_session_run_hooks import NanLossDuringTrainingError # line: 42 +from tensorflow_estimator.python.estimator.hooks.basic_session_run_hooks import NanTensorHook # line: 44 +from tensorflow_estimator.python.estimator.hooks.basic_session_run_hooks import ProfilerHook # line: 49 +from tensorflow_estimator.python.estimator.hooks.basic_session_run_hooks import SecondOrStepTimer # line: 36 +from tensorflow_estimator.python.estimator.hooks.basic_session_run_hooks import StepCounterHook # line: 41 +from tensorflow_estimator.python.estimator.hooks.basic_session_run_hooks import StopAtStepHook # line: 38 +from tensorflow_estimator.python.estimator.hooks.basic_session_run_hooks import SummarySaverHook # line: 45 +from tensorflow_estimator.python.estimator.hooks.session_run_hook import SessionRunArgs # line: 99 +from tensorflow_estimator.python.estimator.hooks.session_run_hook import SessionRunContext # line: 100 +from tensorflow_estimator.python.estimator.hooks.session_run_hook import SessionRunHook # line: 98 +from tensorflow_estimator.python.estimator.hooks.session_run_hook import SessionRunValues # line: 101 +from tensorflow_estimator.python.estimator.mode_keys import ModeKeys # line: 24 +from tensorflow_estimator.python.estimator.model_fn import EstimatorSpec # line: 35 +from tensorflow_estimator.python.estimator.run_config import RunConfig # line: 343 +from tensorflow_estimator.python.estimator.training import EvalSpec # line: 200 +from tensorflow_estimator.python.estimator.training import TrainSpec # line: 127 +from tensorflow_estimator.python.estimator.training import train_and_evaluate # line: 296 + +from tensorflow.python.util import module_wrapper as _module_wrapper + +if not isinstance(_sys.modules[__name__], _module_wrapper.TFModuleWrapper): + _sys.modules[__name__] = _module_wrapper.TFModuleWrapper( + _sys.modules[__name__], "estimator", public_apis=None, deprecation=True, + has_lite=False) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/_api/v1/estimator/experimental/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/_api/v1/estimator/experimental/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ba939711b249174f8036857e5b321bacdfb4b764 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/_api/v1/estimator/experimental/__init__.py @@ -0,0 +1,27 @@ +# This file is MACHINE GENERATED! Do not edit. +# Generated by: tensorflow/python/tools/api/generator2/generator/generator.py script. +"""Public API for tf_estimator._api.v1.estimator.experimental namespace +""" + +import sys as _sys + +from tensorflow_estimator.python.estimator.canned.dnn import dnn_logit_fn_builder # line: 45 +from tensorflow_estimator.python.estimator.canned.kmeans import KMeansClustering as KMeans # line: 240 +from tensorflow_estimator.python.estimator.canned.linear import LinearSDCA # line: 45 +from tensorflow_estimator.python.estimator.canned.linear import linear_logit_fn_builder # line: 377 +from tensorflow_estimator.python.estimator.early_stopping import make_early_stopping_hook # line: 29 +from tensorflow_estimator.python.estimator.early_stopping import stop_if_higher_hook # line: 98 +from tensorflow_estimator.python.estimator.early_stopping import stop_if_lower_hook # line: 155 +from tensorflow_estimator.python.estimator.early_stopping import stop_if_no_decrease_hook # line: 270 +from tensorflow_estimator.python.estimator.early_stopping import stop_if_no_increase_hook # line: 212 +from tensorflow_estimator.python.estimator.export.export import build_raw_supervised_input_receiver_fn # line: 380 +from tensorflow_estimator.python.estimator.hooks.hooks import InMemoryEvaluatorHook # line: 30 +from tensorflow_estimator.python.estimator.hooks.hooks import make_stop_at_checkpoint_step_hook # line: 269 +from tensorflow_estimator.python.estimator.model_fn import call_logit_fn # line: 562 + +from tensorflow.python.util import module_wrapper as _module_wrapper + +if not isinstance(_sys.modules[__name__], _module_wrapper.TFModuleWrapper): + _sys.modules[__name__] = _module_wrapper.TFModuleWrapper( + _sys.modules[__name__], "estimator.experimental", public_apis=None, deprecation=True, + has_lite=False) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/_api/v1/estimator/export/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/_api/v1/estimator/export/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f0b4d7feae64f80fafd010ab185c5d907911a910 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/_api/v1/estimator/export/__init__.py @@ -0,0 +1,23 @@ +# This file is MACHINE GENERATED! Do not edit. +# Generated by: tensorflow/python/tools/api/generator2/generator/generator.py script. +"""Public API for tf_estimator._api.v1.estimator.export namespace +""" + +import sys as _sys + +from tensorflow_estimator.python.estimator.export.export import ServingInputReceiver # line: 108 +from tensorflow_estimator.python.estimator.export.export import TensorServingInputReceiver # line: 165 +from tensorflow_estimator.python.estimator.export.export import build_parsing_serving_input_receiver_fn # line: 285 +from tensorflow_estimator.python.estimator.export.export import build_raw_serving_input_receiver_fn # line: 355 +from tensorflow_estimator.python.estimator.export.export_output import ClassificationOutput # line: 33 +from tensorflow_estimator.python.estimator.export.export_output import EvalOutput # line: 36 +from tensorflow_estimator.python.estimator.export.export_output import ExportOutput # line: 32 +from tensorflow_estimator.python.estimator.export.export_output import PredictOutput # line: 35 +from tensorflow_estimator.python.estimator.export.export_output import RegressionOutput # line: 34 + +from tensorflow.python.util import module_wrapper as _module_wrapper + +if not isinstance(_sys.modules[__name__], _module_wrapper.TFModuleWrapper): + _sys.modules[__name__] = _module_wrapper.TFModuleWrapper( + _sys.modules[__name__], "estimator.export", public_apis=None, deprecation=True, + has_lite=False) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/_api/v1/estimator/inputs/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/_api/v1/estimator/inputs/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..45659a528421a02715b392eb6699f86ec35f4adc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/_api/v1/estimator/inputs/__init__.py @@ -0,0 +1,16 @@ +# This file is MACHINE GENERATED! Do not edit. +# Generated by: tensorflow/python/tools/api/generator2/generator/generator.py script. +"""Public API for tf_estimator._api.v1.estimator.inputs namespace +""" + +import sys as _sys + +from tensorflow_estimator.python.estimator.inputs.numpy_io import numpy_input_fn # line: 89 +from tensorflow_estimator.python.estimator.inputs.pandas_io import pandas_input_fn # line: 55 + +from tensorflow.python.util import module_wrapper as _module_wrapper + +if not isinstance(_sys.modules[__name__], _module_wrapper.TFModuleWrapper): + _sys.modules[__name__] = _module_wrapper.TFModuleWrapper( + _sys.modules[__name__], "estimator.inputs", public_apis=None, deprecation=True, + has_lite=False) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/_api/v1/estimator/tpu/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/_api/v1/estimator/tpu/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e7b0f8c20a1c4e922b91b2391fa892c27042f38e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/_api/v1/estimator/tpu/__init__.py @@ -0,0 +1,20 @@ +# This file is MACHINE GENERATED! Do not edit. +# Generated by: tensorflow/python/tools/api/generator2/generator/generator.py script. +"""Public API for tf_estimator._api.v1.estimator.tpu namespace +""" + +import sys as _sys + +from tensorflow_estimator._api.v1.estimator.tpu import experimental +from tensorflow_estimator.python.estimator.tpu.tpu_config import InputPipelineConfig # line: 36 +from tensorflow_estimator.python.estimator.tpu.tpu_config import RunConfig # line: 237 +from tensorflow_estimator.python.estimator.tpu.tpu_config import TPUConfig # line: 54 +from tensorflow_estimator.python.estimator.tpu.tpu_estimator import TPUEstimator # line: 2457 +from tensorflow_estimator.python.estimator.tpu.tpu_estimator import TPUEstimatorSpec # line: 282 + +from tensorflow.python.util import module_wrapper as _module_wrapper + +if not isinstance(_sys.modules[__name__], _module_wrapper.TFModuleWrapper): + _sys.modules[__name__] = _module_wrapper.TFModuleWrapper( + _sys.modules[__name__], "estimator.tpu", public_apis=None, deprecation=True, + has_lite=False) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/_api/v1/estimator/tpu/experimental/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/_api/v1/estimator/tpu/experimental/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0639613dc9ffb63361501ed39c8712ae1b30c9a4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/_api/v1/estimator/tpu/experimental/__init__.py @@ -0,0 +1,15 @@ +# This file is MACHINE GENERATED! Do not edit. +# Generated by: tensorflow/python/tools/api/generator2/generator/generator.py script. +"""Public API for tf_estimator._api.v1.estimator.tpu.experimental namespace +""" + +import sys as _sys + +from tensorflow_estimator.python.estimator.tpu._tpu_estimator_embedding import EmbeddingConfigSpec # line: 201 + +from tensorflow.python.util import module_wrapper as _module_wrapper + +if not isinstance(_sys.modules[__name__], _module_wrapper.TFModuleWrapper): + _sys.modules[__name__] = _module_wrapper.TFModuleWrapper( + _sys.modules[__name__], "estimator.tpu.experimental", public_apis=None, deprecation=True, + has_lite=False) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/_api/v1/v1.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/_api/v1/v1.py new file mode 100644 index 0000000000000000000000000000000000000000..997ce5df864a7a5a2e79954633f11dacd66aa63a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/_api/v1/v1.py @@ -0,0 +1,15 @@ +# This file is MACHINE GENERATED! Do not edit. +# Generated by: tensorflow/python/tools/api/generator2/generator/generator.py script. +"""Public API for tf_estimator._api.v1 namespace +""" + +import sys as _sys + +from tensorflow_estimator._api.v1 import estimator + +from tensorflow.python.util import module_wrapper as _module_wrapper + +if not isinstance(_sys.modules[__name__], _module_wrapper.TFModuleWrapper): + _sys.modules[__name__] = _module_wrapper.TFModuleWrapper( + _sys.modules[__name__], "", public_apis=None, deprecation=True, + has_lite=False) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/_api/v2/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/_api/v2/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/_api/v2/estimator/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/_api/v2/estimator/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f95b90ab52e09446fbb762656cdfdd20823054be --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/_api/v2/estimator/__init__.py @@ -0,0 +1,62 @@ +# This file is MACHINE GENERATED! Do not edit. +# Generated by: tensorflow/python/tools/api/generator2/generator/generator.py script. +"""Public API for tf_estimator._api.v2.estimator namespace +""" + +import sys as _sys + +from tensorflow_estimator._api.v2.estimator import experimental +from tensorflow_estimator._api.v2.estimator import export +from tensorflow_estimator.python.estimator.canned.baseline import BaselineClassifierV2 as BaselineClassifier # line: 292 +from tensorflow_estimator.python.estimator.canned.baseline import BaselineEstimatorV2 as BaselineEstimator # line: 432 +from tensorflow_estimator.python.estimator.canned.baseline import BaselineRegressorV2 as BaselineRegressor # line: 530 +from tensorflow_estimator.python.estimator.canned.dnn import DNNClassifierV2 as DNNClassifier # line: 589 +from tensorflow_estimator.python.estimator.canned.dnn import DNNEstimatorV2 as DNNEstimator # line: 814 +from tensorflow_estimator.python.estimator.canned.dnn import DNNRegressorV2 as DNNRegressor # line: 1010 +from tensorflow_estimator.python.estimator.canned.dnn_linear_combined import DNNLinearCombinedClassifierV2 as DNNLinearCombinedClassifier # line: 392 +from tensorflow_estimator.python.estimator.canned.dnn_linear_combined import DNNLinearCombinedEstimatorV2 as DNNLinearCombinedEstimator # line: 686 +from tensorflow_estimator.python.estimator.canned.dnn_linear_combined import DNNLinearCombinedRegressorV2 as DNNLinearCombinedRegressor # line: 898 +from tensorflow_estimator.python.estimator.canned.linear import LinearClassifierV2 as LinearClassifier # line: 769 +from tensorflow_estimator.python.estimator.canned.linear import LinearEstimatorV2 as LinearEstimator # line: 997 +from tensorflow_estimator.python.estimator.canned.linear import LinearRegressorV2 as LinearRegressor # line: 1203 +from tensorflow_estimator.python.estimator.canned.parsing_utils import classifier_parse_example_spec_v2 as classifier_parse_example_spec # line: 27 +from tensorflow_estimator.python.estimator.canned.parsing_utils import regressor_parse_example_spec_v2 as regressor_parse_example_spec # line: 147 +from tensorflow_estimator.python.estimator.estimator import EstimatorV2 as Estimator # line: 1767 +from tensorflow_estimator.python.estimator.estimator import VocabInfo # line: 2173 +from tensorflow_estimator.python.estimator.estimator import WarmStartSettings # line: 2176 +from tensorflow_estimator.python.estimator.exporter import BestExporter # line: 164 +from tensorflow_estimator.python.estimator.exporter import Exporter # line: 30 +from tensorflow_estimator.python.estimator.exporter import FinalExporter # line: 368 +from tensorflow_estimator.python.estimator.exporter import LatestExporter # line: 421 +from tensorflow_estimator.python.estimator.extenders import add_metrics # line: 29 +from tensorflow_estimator.python.estimator.head.base_head import Head # line: 43 +from tensorflow_estimator.python.estimator.head.binary_class_head import BinaryClassHead # line: 33 +from tensorflow_estimator.python.estimator.head.multi_class_head import MultiClassHead # line: 33 +from tensorflow_estimator.python.estimator.head.multi_head import MultiHead # line: 52 +from tensorflow_estimator.python.estimator.head.multi_label_head import MultiLabelHead # line: 34 +from tensorflow_estimator.python.estimator.head.regression_head import LogisticRegressionHead # line: 499 +from tensorflow_estimator.python.estimator.head.regression_head import PoissonRegressionHead # line: 409 +from tensorflow_estimator.python.estimator.head.regression_head import RegressionHead # line: 33 +from tensorflow_estimator.python.estimator.hooks.basic_session_run_hooks import CheckpointSaverHook # line: 40 +from tensorflow_estimator.python.estimator.hooks.basic_session_run_hooks import CheckpointSaverListener # line: 39 +from tensorflow_estimator.python.estimator.hooks.basic_session_run_hooks import FeedFnHook # line: 48 +from tensorflow_estimator.python.estimator.hooks.basic_session_run_hooks import FinalOpsHook # line: 47 +from tensorflow_estimator.python.estimator.hooks.basic_session_run_hooks import GlobalStepWaiterHook # line: 46 +from tensorflow_estimator.python.estimator.hooks.basic_session_run_hooks import LoggingTensorHook # line: 37 +from tensorflow_estimator.python.estimator.hooks.basic_session_run_hooks import NanLossDuringTrainingError # line: 42 +from tensorflow_estimator.python.estimator.hooks.basic_session_run_hooks import NanTensorHook # line: 44 +from tensorflow_estimator.python.estimator.hooks.basic_session_run_hooks import ProfilerHook # line: 49 +from tensorflow_estimator.python.estimator.hooks.basic_session_run_hooks import SecondOrStepTimer # line: 36 +from tensorflow_estimator.python.estimator.hooks.basic_session_run_hooks import StepCounterHook # line: 41 +from tensorflow_estimator.python.estimator.hooks.basic_session_run_hooks import StopAtStepHook # line: 38 +from tensorflow_estimator.python.estimator.hooks.basic_session_run_hooks import SummarySaverHook # line: 45 +from tensorflow_estimator.python.estimator.hooks.session_run_hook import SessionRunArgs # line: 99 +from tensorflow_estimator.python.estimator.hooks.session_run_hook import SessionRunContext # line: 100 +from tensorflow_estimator.python.estimator.hooks.session_run_hook import SessionRunHook # line: 98 +from tensorflow_estimator.python.estimator.hooks.session_run_hook import SessionRunValues # line: 101 +from tensorflow_estimator.python.estimator.mode_keys import ModeKeys # line: 24 +from tensorflow_estimator.python.estimator.model_fn import EstimatorSpec # line: 35 +from tensorflow_estimator.python.estimator.run_config import RunConfig # line: 343 +from tensorflow_estimator.python.estimator.training import EvalSpec # line: 200 +from tensorflow_estimator.python.estimator.training import TrainSpec # line: 127 +from tensorflow_estimator.python.estimator.training import train_and_evaluate # line: 296 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/_api/v2/estimator/experimental/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/_api/v2/estimator/experimental/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0270d7ddc5e35a65e13a75fc971f6b7795289cf3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/_api/v2/estimator/experimental/__init__.py @@ -0,0 +1,19 @@ +# This file is MACHINE GENERATED! Do not edit. +# Generated by: tensorflow/python/tools/api/generator2/generator/generator.py script. +"""Public API for tf_estimator._api.v2.estimator.experimental namespace +""" + +import sys as _sys + +from tensorflow_estimator.python.estimator.canned.linear import LinearSDCA # line: 45 +from tensorflow_estimator.python.estimator.canned.rnn import RNNClassifier # line: 516 +from tensorflow_estimator.python.estimator.canned.rnn import RNNEstimator # line: 363 +from tensorflow_estimator.python.estimator.early_stopping import make_early_stopping_hook # line: 29 +from tensorflow_estimator.python.estimator.early_stopping import stop_if_higher_hook # line: 98 +from tensorflow_estimator.python.estimator.early_stopping import stop_if_lower_hook # line: 155 +from tensorflow_estimator.python.estimator.early_stopping import stop_if_no_decrease_hook # line: 270 +from tensorflow_estimator.python.estimator.early_stopping import stop_if_no_increase_hook # line: 212 +from tensorflow_estimator.python.estimator.export.export import build_raw_supervised_input_receiver_fn # line: 380 +from tensorflow_estimator.python.estimator.hooks.hooks import InMemoryEvaluatorHook # line: 30 +from tensorflow_estimator.python.estimator.hooks.hooks import make_stop_at_checkpoint_step_hook # line: 269 +from tensorflow_estimator.python.estimator.model_fn import call_logit_fn # line: 562 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/_api/v2/estimator/export/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/_api/v2/estimator/export/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..88c902331f0675deea602d05f997f3cc43bf313f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/_api/v2/estimator/export/__init__.py @@ -0,0 +1,16 @@ +# This file is MACHINE GENERATED! Do not edit. +# Generated by: tensorflow/python/tools/api/generator2/generator/generator.py script. +"""Public API for tf_estimator._api.v2.estimator.export namespace +""" + +import sys as _sys + +from tensorflow_estimator.python.estimator.export.export import ServingInputReceiver # line: 108 +from tensorflow_estimator.python.estimator.export.export import TensorServingInputReceiver # line: 165 +from tensorflow_estimator.python.estimator.export.export import build_parsing_serving_input_receiver_fn # line: 285 +from tensorflow_estimator.python.estimator.export.export import build_raw_serving_input_receiver_fn # line: 355 +from tensorflow_estimator.python.estimator.export.export_output import ClassificationOutput # line: 33 +from tensorflow_estimator.python.estimator.export.export_output import EvalOutput # line: 36 +from tensorflow_estimator.python.estimator.export.export_output import ExportOutput # line: 32 +from tensorflow_estimator.python.estimator.export.export_output import PredictOutput # line: 35 +from tensorflow_estimator.python.estimator.export.export_output import RegressionOutput # line: 34 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/_api/v2/estimator/inputs/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/_api/v2/estimator/inputs/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/_api/v2/v2.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/_api/v2/v2.py new file mode 100644 index 0000000000000000000000000000000000000000..72b09bca86585eefd8e9da0808a4a829a212971b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/_api/v2/v2.py @@ -0,0 +1,8 @@ +# This file is MACHINE GENERATED! Do not edit. +# Generated by: tensorflow/python/tools/api/generator2/generator/generator.py script. +"""Public API for tf_estimator._api.v2 namespace +""" + +import sys as _sys + +from tensorflow_estimator._api.v2 import estimator diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/api/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/api/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a79f9d8fb1ab760de62827c60339fca23b7207cb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/api/__init__.py @@ -0,0 +1,15 @@ +# This file is MACHINE GENERATED! Do not edit. +# Generated by: tensorflow/python/tools/api/generator2/generator/generator.py script. +"""Public API for tf_estimator.python.estimator.api._v1 namespace +""" + +import sys as _sys + +from tensorflow_estimator.python.estimator.api._v1 import estimator + +from tensorflow.python.util import module_wrapper as _module_wrapper + +if not isinstance(_sys.modules[__name__], _module_wrapper.TFModuleWrapper): + _sys.modules[__name__] = _module_wrapper.TFModuleWrapper( + _sys.modules[__name__], "", public_apis=None, deprecation=True, + has_lite=False) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/api/_v1/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/api/_v1/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/api/_v1/estimator/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/api/_v1/estimator/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f432b4d531379fac8e66105fdb218437ba18c0d1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/api/_v1/estimator/__init__.py @@ -0,0 +1,71 @@ +# This file is MACHINE GENERATED! Do not edit. +# Generated by: tensorflow/python/tools/api/generator2/generator/generator.py script. +"""Public API for tf_estimator.python.estimator.api._v1.estimator namespace +""" + +import sys as _sys + +from tensorflow_estimator.python.estimator.api._v1.estimator import experimental +from tensorflow_estimator.python.estimator.api._v1.estimator import export +from tensorflow_estimator.python.estimator.api._v1.estimator import inputs +from tensorflow_estimator.python.estimator.api._v1.estimator import tpu +from tensorflow_estimator.python.estimator.canned.baseline import BaselineClassifier # line: 403 +from tensorflow_estimator.python.estimator.canned.baseline import BaselineEstimator # line: 511 +from tensorflow_estimator.python.estimator.canned.baseline import BaselineRegressor # line: 626 +from tensorflow_estimator.python.estimator.canned.dnn import DNNClassifier # line: 766 +from tensorflow_estimator.python.estimator.canned.dnn import DNNEstimator # line: 969 +from tensorflow_estimator.python.estimator.canned.dnn import DNNRegressor # line: 1179 +from tensorflow_estimator.python.estimator.canned.dnn_linear_combined import DNNLinearCombinedClassifier # line: 593 +from tensorflow_estimator.python.estimator.canned.dnn_linear_combined import DNNLinearCombinedEstimator # line: 851 +from tensorflow_estimator.python.estimator.canned.dnn_linear_combined import DNNLinearCombinedRegressor # line: 1090 +from tensorflow_estimator.python.estimator.canned.linear import LinearClassifier # line: 951 +from tensorflow_estimator.python.estimator.canned.linear import LinearEstimator # line: 1129 +from tensorflow_estimator.python.estimator.canned.linear import LinearRegressor # line: 1369 +from tensorflow_estimator.python.estimator.canned.parsing_utils import classifier_parse_example_spec # line: 315 +from tensorflow_estimator.python.estimator.canned.parsing_utils import regressor_parse_example_spec # line: 334 +from tensorflow_estimator.python.estimator.estimator import Estimator # line: 67 +from tensorflow_estimator.python.estimator.estimator import VocabInfo # line: 2173 +from tensorflow_estimator.python.estimator.estimator import WarmStartSettings # line: 2176 +from tensorflow_estimator.python.estimator.exporter import BestExporter # line: 164 +from tensorflow_estimator.python.estimator.exporter import Exporter # line: 30 +from tensorflow_estimator.python.estimator.exporter import FinalExporter # line: 368 +from tensorflow_estimator.python.estimator.exporter import LatestExporter # line: 421 +from tensorflow_estimator.python.estimator.extenders import add_metrics # line: 29 +from tensorflow_estimator.python.estimator.head.base_head import Head # line: 43 +from tensorflow_estimator.python.estimator.head.binary_class_head import BinaryClassHead # line: 33 +from tensorflow_estimator.python.estimator.head.multi_class_head import MultiClassHead # line: 33 +from tensorflow_estimator.python.estimator.head.multi_head import MultiHead # line: 52 +from tensorflow_estimator.python.estimator.head.multi_label_head import MultiLabelHead # line: 34 +from tensorflow_estimator.python.estimator.head.regression_head import LogisticRegressionHead # line: 499 +from tensorflow_estimator.python.estimator.head.regression_head import PoissonRegressionHead # line: 409 +from tensorflow_estimator.python.estimator.head.regression_head import RegressionHead # line: 33 +from tensorflow_estimator.python.estimator.hooks.basic_session_run_hooks import CheckpointSaverHook # line: 40 +from tensorflow_estimator.python.estimator.hooks.basic_session_run_hooks import CheckpointSaverListener # line: 39 +from tensorflow_estimator.python.estimator.hooks.basic_session_run_hooks import FeedFnHook # line: 48 +from tensorflow_estimator.python.estimator.hooks.basic_session_run_hooks import FinalOpsHook # line: 47 +from tensorflow_estimator.python.estimator.hooks.basic_session_run_hooks import GlobalStepWaiterHook # line: 46 +from tensorflow_estimator.python.estimator.hooks.basic_session_run_hooks import LoggingTensorHook # line: 37 +from tensorflow_estimator.python.estimator.hooks.basic_session_run_hooks import NanLossDuringTrainingError # line: 42 +from tensorflow_estimator.python.estimator.hooks.basic_session_run_hooks import NanTensorHook # line: 44 +from tensorflow_estimator.python.estimator.hooks.basic_session_run_hooks import ProfilerHook # line: 49 +from tensorflow_estimator.python.estimator.hooks.basic_session_run_hooks import SecondOrStepTimer # line: 36 +from tensorflow_estimator.python.estimator.hooks.basic_session_run_hooks import StepCounterHook # line: 41 +from tensorflow_estimator.python.estimator.hooks.basic_session_run_hooks import StopAtStepHook # line: 38 +from tensorflow_estimator.python.estimator.hooks.basic_session_run_hooks import SummarySaverHook # line: 45 +from tensorflow_estimator.python.estimator.hooks.session_run_hook import SessionRunArgs # line: 99 +from tensorflow_estimator.python.estimator.hooks.session_run_hook import SessionRunContext # line: 100 +from tensorflow_estimator.python.estimator.hooks.session_run_hook import SessionRunHook # line: 98 +from tensorflow_estimator.python.estimator.hooks.session_run_hook import SessionRunValues # line: 101 +from tensorflow_estimator.python.estimator.mode_keys import ModeKeys # line: 24 +from tensorflow_estimator.python.estimator.model_fn import EstimatorSpec # line: 35 +from tensorflow_estimator.python.estimator.run_config import RunConfig # line: 343 +from tensorflow_estimator.python.estimator.training import EvalSpec # line: 200 +from tensorflow_estimator.python.estimator.training import TrainSpec # line: 127 +from tensorflow_estimator.python.estimator.training import train_and_evaluate # line: 296 + +from tensorflow.python.util import module_wrapper as _module_wrapper + +if not isinstance(_sys.modules[__name__], _module_wrapper.TFModuleWrapper): + _sys.modules[__name__] = _module_wrapper.TFModuleWrapper( + _sys.modules[__name__], "estimator", public_apis=None, deprecation=True, + has_lite=False) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/api/_v1/estimator/experimental/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/api/_v1/estimator/experimental/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ee42e9cbf0ca0c94ca09f0ec46afc14de2091ea5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/api/_v1/estimator/experimental/__init__.py @@ -0,0 +1,27 @@ +# This file is MACHINE GENERATED! Do not edit. +# Generated by: tensorflow/python/tools/api/generator2/generator/generator.py script. +"""Public API for tf_estimator.python.estimator.api._v1.estimator.experimental namespace +""" + +import sys as _sys + +from tensorflow_estimator.python.estimator.canned.dnn import dnn_logit_fn_builder # line: 45 +from tensorflow_estimator.python.estimator.canned.kmeans import KMeansClustering as KMeans # line: 240 +from tensorflow_estimator.python.estimator.canned.linear import LinearSDCA # line: 45 +from tensorflow_estimator.python.estimator.canned.linear import linear_logit_fn_builder # line: 377 +from tensorflow_estimator.python.estimator.early_stopping import make_early_stopping_hook # line: 29 +from tensorflow_estimator.python.estimator.early_stopping import stop_if_higher_hook # line: 98 +from tensorflow_estimator.python.estimator.early_stopping import stop_if_lower_hook # line: 155 +from tensorflow_estimator.python.estimator.early_stopping import stop_if_no_decrease_hook # line: 270 +from tensorflow_estimator.python.estimator.early_stopping import stop_if_no_increase_hook # line: 212 +from tensorflow_estimator.python.estimator.export.export import build_raw_supervised_input_receiver_fn # line: 380 +from tensorflow_estimator.python.estimator.hooks.hooks import InMemoryEvaluatorHook # line: 30 +from tensorflow_estimator.python.estimator.hooks.hooks import make_stop_at_checkpoint_step_hook # line: 269 +from tensorflow_estimator.python.estimator.model_fn import call_logit_fn # line: 562 + +from tensorflow.python.util import module_wrapper as _module_wrapper + +if not isinstance(_sys.modules[__name__], _module_wrapper.TFModuleWrapper): + _sys.modules[__name__] = _module_wrapper.TFModuleWrapper( + _sys.modules[__name__], "estimator.experimental", public_apis=None, deprecation=True, + has_lite=False) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/api/_v1/estimator/export/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/api/_v1/estimator/export/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..24b0b711417831e0e5632536a9e7b85b485343eb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/api/_v1/estimator/export/__init__.py @@ -0,0 +1,23 @@ +# This file is MACHINE GENERATED! Do not edit. +# Generated by: tensorflow/python/tools/api/generator2/generator/generator.py script. +"""Public API for tf_estimator.python.estimator.api._v1.estimator.export namespace +""" + +import sys as _sys + +from tensorflow_estimator.python.estimator.export.export import ServingInputReceiver # line: 108 +from tensorflow_estimator.python.estimator.export.export import TensorServingInputReceiver # line: 165 +from tensorflow_estimator.python.estimator.export.export import build_parsing_serving_input_receiver_fn # line: 285 +from tensorflow_estimator.python.estimator.export.export import build_raw_serving_input_receiver_fn # line: 355 +from tensorflow_estimator.python.estimator.export.export_output import ClassificationOutput # line: 33 +from tensorflow_estimator.python.estimator.export.export_output import EvalOutput # line: 36 +from tensorflow_estimator.python.estimator.export.export_output import ExportOutput # line: 32 +from tensorflow_estimator.python.estimator.export.export_output import PredictOutput # line: 35 +from tensorflow_estimator.python.estimator.export.export_output import RegressionOutput # line: 34 + +from tensorflow.python.util import module_wrapper as _module_wrapper + +if not isinstance(_sys.modules[__name__], _module_wrapper.TFModuleWrapper): + _sys.modules[__name__] = _module_wrapper.TFModuleWrapper( + _sys.modules[__name__], "estimator.export", public_apis=None, deprecation=True, + has_lite=False) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/api/_v1/estimator/inputs/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/api/_v1/estimator/inputs/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..54c416a35b51bda5c44d88be239f0f7e2da560b5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/api/_v1/estimator/inputs/__init__.py @@ -0,0 +1,16 @@ +# This file is MACHINE GENERATED! Do not edit. +# Generated by: tensorflow/python/tools/api/generator2/generator/generator.py script. +"""Public API for tf_estimator.python.estimator.api._v1.estimator.inputs namespace +""" + +import sys as _sys + +from tensorflow_estimator.python.estimator.inputs.numpy_io import numpy_input_fn # line: 89 +from tensorflow_estimator.python.estimator.inputs.pandas_io import pandas_input_fn # line: 55 + +from tensorflow.python.util import module_wrapper as _module_wrapper + +if not isinstance(_sys.modules[__name__], _module_wrapper.TFModuleWrapper): + _sys.modules[__name__] = _module_wrapper.TFModuleWrapper( + _sys.modules[__name__], "estimator.inputs", public_apis=None, deprecation=True, + has_lite=False) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/api/_v1/estimator/tpu/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/api/_v1/estimator/tpu/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c8a905a0f8892ab56f54b294c551ceecf4001beb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/api/_v1/estimator/tpu/__init__.py @@ -0,0 +1,20 @@ +# This file is MACHINE GENERATED! Do not edit. +# Generated by: tensorflow/python/tools/api/generator2/generator/generator.py script. +"""Public API for tf_estimator.python.estimator.api._v1.estimator.tpu namespace +""" + +import sys as _sys + +from tensorflow_estimator.python.estimator.api._v1.estimator.tpu import experimental +from tensorflow_estimator.python.estimator.tpu.tpu_config import InputPipelineConfig # line: 36 +from tensorflow_estimator.python.estimator.tpu.tpu_config import RunConfig # line: 237 +from tensorflow_estimator.python.estimator.tpu.tpu_config import TPUConfig # line: 54 +from tensorflow_estimator.python.estimator.tpu.tpu_estimator import TPUEstimator # line: 2457 +from tensorflow_estimator.python.estimator.tpu.tpu_estimator import TPUEstimatorSpec # line: 282 + +from tensorflow.python.util import module_wrapper as _module_wrapper + +if not isinstance(_sys.modules[__name__], _module_wrapper.TFModuleWrapper): + _sys.modules[__name__] = _module_wrapper.TFModuleWrapper( + _sys.modules[__name__], "estimator.tpu", public_apis=None, deprecation=True, + has_lite=False) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/api/_v1/estimator/tpu/experimental/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/api/_v1/estimator/tpu/experimental/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..44a24f3ab9697b5d238066489dd4ab7d7e199ff5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/api/_v1/estimator/tpu/experimental/__init__.py @@ -0,0 +1,15 @@ +# This file is MACHINE GENERATED! Do not edit. +# Generated by: tensorflow/python/tools/api/generator2/generator/generator.py script. +"""Public API for tf_estimator.python.estimator.api._v1.estimator.tpu.experimental namespace +""" + +import sys as _sys + +from tensorflow_estimator.python.estimator.tpu._tpu_estimator_embedding import EmbeddingConfigSpec # line: 201 + +from tensorflow.python.util import module_wrapper as _module_wrapper + +if not isinstance(_sys.modules[__name__], _module_wrapper.TFModuleWrapper): + _sys.modules[__name__] = _module_wrapper.TFModuleWrapper( + _sys.modules[__name__], "estimator.tpu.experimental", public_apis=None, deprecation=True, + has_lite=False) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/api/_v1/v1.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/api/_v1/v1.py new file mode 100644 index 0000000000000000000000000000000000000000..a79f9d8fb1ab760de62827c60339fca23b7207cb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/api/_v1/v1.py @@ -0,0 +1,15 @@ +# This file is MACHINE GENERATED! Do not edit. +# Generated by: tensorflow/python/tools/api/generator2/generator/generator.py script. +"""Public API for tf_estimator.python.estimator.api._v1 namespace +""" + +import sys as _sys + +from tensorflow_estimator.python.estimator.api._v1 import estimator + +from tensorflow.python.util import module_wrapper as _module_wrapper + +if not isinstance(_sys.modules[__name__], _module_wrapper.TFModuleWrapper): + _sys.modules[__name__] = _module_wrapper.TFModuleWrapper( + _sys.modules[__name__], "", public_apis=None, deprecation=True, + has_lite=False) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/api/_v2/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/api/_v2/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/api/_v2/estimator/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/api/_v2/estimator/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5e599cc54a29c785cafff070a26dc0e88ccee14d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/api/_v2/estimator/__init__.py @@ -0,0 +1,62 @@ +# This file is MACHINE GENERATED! Do not edit. +# Generated by: tensorflow/python/tools/api/generator2/generator/generator.py script. +"""Public API for tf_estimator.python.estimator.api._v2.estimator namespace +""" + +import sys as _sys + +from tensorflow_estimator.python.estimator.api._v2.estimator import experimental +from tensorflow_estimator.python.estimator.api._v2.estimator import export +from tensorflow_estimator.python.estimator.canned.baseline import BaselineClassifierV2 as BaselineClassifier # line: 292 +from tensorflow_estimator.python.estimator.canned.baseline import BaselineEstimatorV2 as BaselineEstimator # line: 432 +from tensorflow_estimator.python.estimator.canned.baseline import BaselineRegressorV2 as BaselineRegressor # line: 530 +from tensorflow_estimator.python.estimator.canned.dnn import DNNClassifierV2 as DNNClassifier # line: 589 +from tensorflow_estimator.python.estimator.canned.dnn import DNNEstimatorV2 as DNNEstimator # line: 814 +from tensorflow_estimator.python.estimator.canned.dnn import DNNRegressorV2 as DNNRegressor # line: 1010 +from tensorflow_estimator.python.estimator.canned.dnn_linear_combined import DNNLinearCombinedClassifierV2 as DNNLinearCombinedClassifier # line: 392 +from tensorflow_estimator.python.estimator.canned.dnn_linear_combined import DNNLinearCombinedEstimatorV2 as DNNLinearCombinedEstimator # line: 686 +from tensorflow_estimator.python.estimator.canned.dnn_linear_combined import DNNLinearCombinedRegressorV2 as DNNLinearCombinedRegressor # line: 898 +from tensorflow_estimator.python.estimator.canned.linear import LinearClassifierV2 as LinearClassifier # line: 769 +from tensorflow_estimator.python.estimator.canned.linear import LinearEstimatorV2 as LinearEstimator # line: 997 +from tensorflow_estimator.python.estimator.canned.linear import LinearRegressorV2 as LinearRegressor # line: 1203 +from tensorflow_estimator.python.estimator.canned.parsing_utils import classifier_parse_example_spec_v2 as classifier_parse_example_spec # line: 27 +from tensorflow_estimator.python.estimator.canned.parsing_utils import regressor_parse_example_spec_v2 as regressor_parse_example_spec # line: 147 +from tensorflow_estimator.python.estimator.estimator import EstimatorV2 as Estimator # line: 1767 +from tensorflow_estimator.python.estimator.estimator import VocabInfo # line: 2173 +from tensorflow_estimator.python.estimator.estimator import WarmStartSettings # line: 2176 +from tensorflow_estimator.python.estimator.exporter import BestExporter # line: 164 +from tensorflow_estimator.python.estimator.exporter import Exporter # line: 30 +from tensorflow_estimator.python.estimator.exporter import FinalExporter # line: 368 +from tensorflow_estimator.python.estimator.exporter import LatestExporter # line: 421 +from tensorflow_estimator.python.estimator.extenders import add_metrics # line: 29 +from tensorflow_estimator.python.estimator.head.base_head import Head # line: 43 +from tensorflow_estimator.python.estimator.head.binary_class_head import BinaryClassHead # line: 33 +from tensorflow_estimator.python.estimator.head.multi_class_head import MultiClassHead # line: 33 +from tensorflow_estimator.python.estimator.head.multi_head import MultiHead # line: 52 +from tensorflow_estimator.python.estimator.head.multi_label_head import MultiLabelHead # line: 34 +from tensorflow_estimator.python.estimator.head.regression_head import LogisticRegressionHead # line: 499 +from tensorflow_estimator.python.estimator.head.regression_head import PoissonRegressionHead # line: 409 +from tensorflow_estimator.python.estimator.head.regression_head import RegressionHead # line: 33 +from tensorflow_estimator.python.estimator.hooks.basic_session_run_hooks import CheckpointSaverHook # line: 40 +from tensorflow_estimator.python.estimator.hooks.basic_session_run_hooks import CheckpointSaverListener # line: 39 +from tensorflow_estimator.python.estimator.hooks.basic_session_run_hooks import FeedFnHook # line: 48 +from tensorflow_estimator.python.estimator.hooks.basic_session_run_hooks import FinalOpsHook # line: 47 +from tensorflow_estimator.python.estimator.hooks.basic_session_run_hooks import GlobalStepWaiterHook # line: 46 +from tensorflow_estimator.python.estimator.hooks.basic_session_run_hooks import LoggingTensorHook # line: 37 +from tensorflow_estimator.python.estimator.hooks.basic_session_run_hooks import NanLossDuringTrainingError # line: 42 +from tensorflow_estimator.python.estimator.hooks.basic_session_run_hooks import NanTensorHook # line: 44 +from tensorflow_estimator.python.estimator.hooks.basic_session_run_hooks import ProfilerHook # line: 49 +from tensorflow_estimator.python.estimator.hooks.basic_session_run_hooks import SecondOrStepTimer # line: 36 +from tensorflow_estimator.python.estimator.hooks.basic_session_run_hooks import StepCounterHook # line: 41 +from tensorflow_estimator.python.estimator.hooks.basic_session_run_hooks import StopAtStepHook # line: 38 +from tensorflow_estimator.python.estimator.hooks.basic_session_run_hooks import SummarySaverHook # line: 45 +from tensorflow_estimator.python.estimator.hooks.session_run_hook import SessionRunArgs # line: 99 +from tensorflow_estimator.python.estimator.hooks.session_run_hook import SessionRunContext # line: 100 +from tensorflow_estimator.python.estimator.hooks.session_run_hook import SessionRunHook # line: 98 +from tensorflow_estimator.python.estimator.hooks.session_run_hook import SessionRunValues # line: 101 +from tensorflow_estimator.python.estimator.mode_keys import ModeKeys # line: 24 +from tensorflow_estimator.python.estimator.model_fn import EstimatorSpec # line: 35 +from tensorflow_estimator.python.estimator.run_config import RunConfig # line: 343 +from tensorflow_estimator.python.estimator.training import EvalSpec # line: 200 +from tensorflow_estimator.python.estimator.training import TrainSpec # line: 127 +from tensorflow_estimator.python.estimator.training import train_and_evaluate # line: 296 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/api/_v2/estimator/experimental/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/api/_v2/estimator/experimental/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..117fbd797cf97323ab55142e96bfc3e00e2e8d42 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/api/_v2/estimator/experimental/__init__.py @@ -0,0 +1,19 @@ +# This file is MACHINE GENERATED! Do not edit. +# Generated by: tensorflow/python/tools/api/generator2/generator/generator.py script. +"""Public API for tf_estimator.python.estimator.api._v2.estimator.experimental namespace +""" + +import sys as _sys + +from tensorflow_estimator.python.estimator.canned.linear import LinearSDCA # line: 45 +from tensorflow_estimator.python.estimator.canned.rnn import RNNClassifier # line: 516 +from tensorflow_estimator.python.estimator.canned.rnn import RNNEstimator # line: 363 +from tensorflow_estimator.python.estimator.early_stopping import make_early_stopping_hook # line: 29 +from tensorflow_estimator.python.estimator.early_stopping import stop_if_higher_hook # line: 98 +from tensorflow_estimator.python.estimator.early_stopping import stop_if_lower_hook # line: 155 +from tensorflow_estimator.python.estimator.early_stopping import stop_if_no_decrease_hook # line: 270 +from tensorflow_estimator.python.estimator.early_stopping import stop_if_no_increase_hook # line: 212 +from tensorflow_estimator.python.estimator.export.export import build_raw_supervised_input_receiver_fn # line: 380 +from tensorflow_estimator.python.estimator.hooks.hooks import InMemoryEvaluatorHook # line: 30 +from tensorflow_estimator.python.estimator.hooks.hooks import make_stop_at_checkpoint_step_hook # line: 269 +from tensorflow_estimator.python.estimator.model_fn import call_logit_fn # line: 562 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/api/_v2/estimator/export/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/api/_v2/estimator/export/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ae563bb9279d309516a6d5acfdad18460c7b242c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/api/_v2/estimator/export/__init__.py @@ -0,0 +1,16 @@ +# This file is MACHINE GENERATED! Do not edit. +# Generated by: tensorflow/python/tools/api/generator2/generator/generator.py script. +"""Public API for tf_estimator.python.estimator.api._v2.estimator.export namespace +""" + +import sys as _sys + +from tensorflow_estimator.python.estimator.export.export import ServingInputReceiver # line: 108 +from tensorflow_estimator.python.estimator.export.export import TensorServingInputReceiver # line: 165 +from tensorflow_estimator.python.estimator.export.export import build_parsing_serving_input_receiver_fn # line: 285 +from tensorflow_estimator.python.estimator.export.export import build_raw_serving_input_receiver_fn # line: 355 +from tensorflow_estimator.python.estimator.export.export_output import ClassificationOutput # line: 33 +from tensorflow_estimator.python.estimator.export.export_output import EvalOutput # line: 36 +from tensorflow_estimator.python.estimator.export.export_output import ExportOutput # line: 32 +from tensorflow_estimator.python.estimator.export.export_output import PredictOutput # line: 35 +from tensorflow_estimator.python.estimator.export.export_output import RegressionOutput # line: 34 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/api/_v2/estimator/inputs/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/api/_v2/estimator/inputs/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/api/_v2/v2.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/api/_v2/v2.py new file mode 100644 index 0000000000000000000000000000000000000000..3e12fb69d3c00b8731710bc5b1972f769a7d9bc8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/api/_v2/v2.py @@ -0,0 +1,8 @@ +# This file is MACHINE GENERATED! Do not edit. +# Generated by: tensorflow/python/tools/api/generator2/generator/generator.py script. +"""Public API for tf_estimator.python.estimator.api._v2 namespace +""" + +import sys as _sys + +from tensorflow_estimator.python.estimator.api._v2 import estimator diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/baseline.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/baseline.py new file mode 100644 index 0000000000000000000000000000000000000000..bf518e49bbc3fe7f60dfc3549f70929d02d535a1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/baseline.py @@ -0,0 +1,652 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Baseline estimators. + +Baseline estimators are bias-only estimators that can be used for debugging +and as simple baselines. + +Example: + +``` +# Build BaselineClassifier +classifier = BaselineClassifier(n_classes=3) + +# Input builders +def input_fn_train(): + # Returns tf.data.Dataset of (x, y) tuple where y represents label's class + # index. + pass + +def input_fn_eval(): + # Returns tf.data.Dataset of (x, y) tuple where y represents label's class + # index. + pass + +# Fit model. +classifier.train(input_fn=input_fn_train) + +# Evaluate cross entropy between the test and train labels. +loss = classifier.evaluate(input_fn=input_fn_eval)["loss"] + +# predict outputs the probability distribution of the classes as seen in +# training. +predictions = classifier.predict(new_samples) +``` +""" +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import six +import tensorflow as tf +from tensorflow.python.feature_column import feature_column as feature_column_v1 +from tensorflow.python.feature_column import feature_column_v2 +from tensorflow.python.framework import ops +from tensorflow_estimator.python.estimator import estimator +from tensorflow_estimator.python.estimator.canned import head as head_lib +from tensorflow_estimator.python.estimator.canned import optimizers +from tensorflow_estimator.python.estimator.estimator_export import estimator_export +from tensorflow_estimator.python.estimator.head import head_utils +from tensorflow_estimator.python.estimator.head import regression_head +from tensorflow_estimator.python.estimator.mode_keys import ModeKeys + +# The default learning rate of 0.3 is a historical artifact of the initial +# implementation, but seems a reasonable choice. +_LEARNING_RATE = 0.3 + + +def _get_weight_column_key(weight_column): + if weight_column is None: + return None + if isinstance(weight_column, six.string_types): + return weight_column + if not isinstance(weight_column, feature_column_v1._NumericColumn): # pylint: disable=protected-access + raise TypeError('Weight column must be either a string or _NumericColumn.' + ' Given type: {}.'.format(type(weight_column))) + return weight_column.key() + + +def _get_weight_column_key_v2(weight_column): + if weight_column is None: + return None + if isinstance(weight_column, six.string_types): + return weight_column + if not isinstance(weight_column, feature_column_v2.NumericColumn): + raise TypeError('Weight column must be either a string or NumericColumn. ' + 'Given type: {}.'.format(type(weight_column))) + return weight_column.key() + + +def _get_batch_size_and_size_checks(features, weight_column_key): + """Returns batch_size and size_checks.""" + size_checks = [] + batch_size = None + + # The first dimension is assumed to be a batch size and must be consistent + # among all of the features. + for key, feature in features.items(): + # Skip weight_column to ensure we don't add size checks to it. + # These would introduce a dependency on the weight at serving time. + if key == weight_column_key: + continue + first_dim = tf.compat.v1.shape(feature)[0] + if batch_size is None: + batch_size = first_dim + else: + size_checks.append( + tf.compat.v1.debugging.assert_equal(batch_size, first_dim)) + + return size_checks, batch_size + + +def _baseline_logit_fn_builder(num_outputs, weight_column=None): + """Function builder for a baseline logit_fn. + + Args: + num_outputs: Number of outputs for the model. + weight_column: A string or a `_NumericColumn` created by + `tf.feature_column.numeric_column` defining feature column representing + weights. It will be multiplied by the loss of the example. + + Returns: + A logit_fn (see below). + """ + + def baseline_logit_fn(features): + """Baseline model logit_fn. + + The baseline model simply learns a bias, so the output logits are a + `Variable` with one weight for each output that learns the bias for the + corresponding output. + + Args: + features: The first item returned from the `input_fn` passed to `train`, + `evaluate`, and `predict`. This should be a single `Tensor` or dict with + `Tensor` values. + + Returns: + A `Tensor` representing the logits. + """ + weight_column_key = _get_weight_column_key(weight_column) + size_checks, batch_size = _get_batch_size_and_size_checks( + features, weight_column_key) + with tf.control_dependencies(size_checks): + with tf.compat.v1.variable_scope('baseline'): + bias = tf.compat.v1.get_variable( + 'bias', + shape=[num_outputs], + initializer=tf.compat.v1.initializers.zeros) + return tf.math.multiply(bias, tf.ones([batch_size, num_outputs])) + + return baseline_logit_fn + + +def _baseline_model_fn(features, + labels, + mode, + head, + optimizer, + weight_column=None, + config=None): + """Model_fn for baseline models. + + Args: + features: `Tensor` or dict of `Tensor` (depends on data passed to `train`). + labels: `Tensor` of labels that are compatible with the `Head` instance. + mode: Defines whether this is training, evaluation or prediction. See + `ModeKeys`. + head: A `Head` instance. + optimizer: String, `tf.Optimizer` object, or callable that creates the + optimizer to use for training. If not specified, will use `FtrlOptimizer` + with a default learning rate of 0.3. + weight_column: A string or a `_NumericColumn` created by + `tf.feature_column.numeric_column` defining feature column representing + weights. It will be multiplied by the loss of the example. + config: `RunConfig` object to configure the runtime settings. + + Raises: + KeyError: If weight column is specified but not present. + ValueError: If features is an empty dictionary. + + Returns: + An `EstimatorSpec` instance. + """ + del config # Unused. + + logit_fn = _baseline_logit_fn_builder(head.logits_dimension, weight_column) + logits = logit_fn(features) + + def train_op_fn(loss): + opt = optimizers.get_optimizer_instance( + optimizer, learning_rate=_LEARNING_RATE) + return opt.minimize(loss, global_step=tf.compat.v1.train.get_global_step()) + + return head.create_estimator_spec( + features=features, + mode=mode, + logits=logits, + labels=labels, + train_op_fn=train_op_fn) + + +def _baseline_model_fn_builder_v2(features, num_outputs, weight_column=None): + """Function builder for a baseline logit_fn. + + Args: + features: The first item returned from the `input_fn` passed to `train`, + `evaluate`, and `predict`. This should be a single `Tensor` or dict with + `Tensor` values. + num_outputs: Number of outputs for the model. + weight_column: A string or a `NumericColumn` created by + `tf.feature_column.numeric_column` defining feature column representing + weights. It will be multiplied by the loss of the example. + + Returns: + A list of trainable variables and a `Tensor` representing the logits. + """ + weight_column_key = _get_weight_column_key_v2(weight_column) + size_checks, batch_size = _get_batch_size_and_size_checks( + features, weight_column_key) + with tf.control_dependencies(size_checks): + with ops.name_scope('baseline'): + bias = tf.Variable(initial_value=tf.zeros([num_outputs]), name='bias') + logits = tf.math.multiply(bias, tf.ones([batch_size, num_outputs])) + return [bias], logits + + +def _baseline_model_fn_v2( + features, + labels, + mode, + head, + optimizer, + weight_column=None, + config=None, + loss_reduction=tf.losses.Reduction.SUM_OVER_BATCH_SIZE): + """Model_fn for baseline models. + + Args: + features: `Tensor` or dict of `Tensor` (depends on data passed to `train`). + labels: `Tensor` of labels that are compatible with the `Head` instance. + mode: Defines whether this is training, evaluation or prediction. See + `ModeKeys`. + head: A `Head` instance. + optimizer: String, `tf.Optimizer` object, or callable that creates the + optimizer to use for training. If not specified, will use `FtrlOptimizer` + with a default learning rate of 0.3. + weight_column: A string or a `NumericColumn` created by + `tf.feature_column.numeric_column` defining feature column representing + weights. It will be multiplied by the loss of the example. + config: `RunConfig` object to configure the runtime settings. + loss_reduction: One of `tf.keras.losses.Reduction` except `NONE`. Describes + how to reduce training loss over batch. Defaults to `SUM_OVER_BATCH_SIZE`. + + Raises: + KeyError: If weight column is specified but not present. + ValueError: If features is an empty dictionary. + + Returns: + An `EstimatorSpec` instance. + """ + del config # Unused. + + trainable_variables, logits = _baseline_model_fn_builder_v2( + features, head.logits_dimension, weight_column) + + # In TRAIN mode, create optimizer and assign global_step variable to + # optimizer.iterations to make global_step increased correctly, as Hooks + # relies on global step as step counter. + if mode == ModeKeys.TRAIN: + opt = optimizers.get_optimizer_instance_v2( + optimizer, learning_rate=_LEARNING_RATE) + opt.iterations = tf.compat.v1.train.get_or_create_global_step() + + def train_op_fn(loss): + # Scale loss by number of replicas. + if loss_reduction == tf.losses.Reduction.SUM_OVER_BATCH_SIZE: + num_replicas = tf.distribute.get_strategy().num_replicas_in_sync + if num_replicas > 1: + loss *= (1. / num_replicas) + return opt.get_updates(loss, trainable_variables)[0] + + return head.create_estimator_spec( + features=features, + mode=mode, + logits=logits, + labels=labels, + train_op_fn=train_op_fn) + + +@estimator_export('estimator.BaselineClassifier', v1=[]) +class BaselineClassifierV2(estimator.EstimatorV2): + """A classifier that can establish a simple baseline. + + This classifier ignores feature values and will learn to predict the average + value of each label. For single-label problems, this will predict the + probability distribution of the classes as seen in the labels. For multi-label + problems, this will predict the fraction of examples that are positive for + each class. + + Example: + + ```python + + # Build BaselineClassifier + classifier = tf.estimator.BaselineClassifier(n_classes=3) + + # Input builders + def input_fn_train: + # Returns tf.data.Dataset of (x, y) tuple where y represents label's class + # index. + pass + + def input_fn_eval: + # Returns tf.data.Dataset of (x, y) tuple where y represents label's class + # index. + pass + + # Fit model. + classifier.train(input_fn=input_fn_train) + + # Evaluate cross entropy between the test and train labels. + loss = classifier.evaluate(input_fn=input_fn_eval)["loss"] + + # predict outputs the probability distribution of the classes as seen in + # training. + predictions = classifier.predict(new_samples) + + ``` + + Input of `train` and `evaluate` should have following features, + otherwise there will be a `KeyError`: + + * if `weight_column` is not `None`, a feature with + `key=weight_column` whose value is a `Tensor`. + + @compatibility(eager) + Estimators can be used while eager execution is enabled. Note that `input_fn` + and all hooks are executed inside a graph context, so they have to be written + to be compatible with graph mode. Note that `input_fn` code using `tf.data` + generally works in both graph and eager modes. + @end_compatibility + """ + + def __init__(self, + model_dir=None, + n_classes=2, + weight_column=None, + label_vocabulary=None, + optimizer='Ftrl', + config=None, + loss_reduction=tf.losses.Reduction.SUM_OVER_BATCH_SIZE): + """Initializes a BaselineClassifier instance. + + Args: + model_dir: Directory to save model parameters, graph and etc. This can + also be used to load checkpoints from the directory into a estimator to + continue training a previously saved model. + n_classes: number of label classes. Default is binary classification. + It must be greater than 1. Note: Class labels are integers representing + the class index (i.e. values from 0 to n_classes-1). For arbitrary + label values (e.g. string labels), convert to class indices first. + weight_column: A string or a `NumericColumn` created by + `tf.feature_column.numeric_column` defining feature column representing + weights. It will be multiplied by the loss of the example. + label_vocabulary: Optional list of strings with size `[n_classes]` + defining the label vocabulary. Only supported for `n_classes` > 2. + optimizer: String, `tf.keras.optimizers.*` object, or callable that + creates the optimizer to use for training. If not specified, will use + `Ftrl` as the default optimizer. + config: `RunConfig` object to configure the runtime settings. + loss_reduction: One of `tf.losses.Reduction` except `NONE`. Describes how + to reduce training loss over batch. Defaults to `SUM_OVER_BATCH_SIZE`. + + Returns: + A `BaselineClassifier` estimator. + + Raises: + ValueError: If `n_classes` < 2. + """ + head = head_utils.binary_or_multi_class_head( + n_classes, + weight_column=weight_column, + label_vocabulary=label_vocabulary, + loss_reduction=loss_reduction) + + def _model_fn(features, labels, mode, config): + return _baseline_model_fn_v2( + features=features, + labels=labels, + mode=mode, + head=head, + optimizer=optimizer, + weight_column=weight_column, + config=config, + loss_reduction=loss_reduction) + + super(BaselineClassifierV2, self).__init__( + model_fn=_model_fn, model_dir=model_dir, config=config) + + +@estimator_export(v1=['estimator.BaselineClassifier']) # pylint: disable=missing-docstring +class BaselineClassifier(estimator.Estimator): + __doc__ = BaselineClassifierV2.__doc__.replace('SUM_OVER_BATCH_SIZE', 'SUM') + + def __init__(self, + model_dir=None, + n_classes=2, + weight_column=None, + label_vocabulary=None, + optimizer='Ftrl', + config=None, + loss_reduction=tf.compat.v1.losses.Reduction.SUM): + head = head_lib._binary_logistic_or_multi_class_head( # pylint: disable=protected-access + n_classes, weight_column, label_vocabulary, loss_reduction) + + def _model_fn(features, labels, mode, config): + return _baseline_model_fn( + features=features, + labels=labels, + mode=mode, + head=head, + optimizer=optimizer, + weight_column=weight_column, + config=config) + + super(BaselineClassifier, self).__init__( + model_fn=_model_fn, model_dir=model_dir, config=config) + + +@estimator_export('estimator.BaselineEstimator', v1=[]) +class BaselineEstimatorV2(estimator.EstimatorV2): + """An estimator that can establish a simple baseline. + + The estimator uses a user-specified head. + + This estimator ignores feature values and will learn to predict the average + value of each label. E.g. for single-label classification problems, this will + predict the probability distribution of the classes as seen in the labels. + For multi-label classification problems, it will predict the ratio of examples + that contain each class. + + Example: + + ```python + + # Build baseline multi-label classifier. + estimator = tf.estimator.BaselineEstimator( + head=tf.estimator.MultiLabelHead(n_classes=3)) + + # Input builders + def input_fn_train: + # Returns tf.data.Dataset of (x, y) tuple where y represents label's class + # index. + pass + + def input_fn_eval: + # Returns tf.data.Dataset of (x, y) tuple where y represents label's class + # index. + pass + + # Fit model. + estimator.train(input_fn=input_fn_train) + + # Evaluates cross entropy between the test and train labels. + loss = estimator.evaluate(input_fn=input_fn_eval)["loss"] + + # For each class, predicts the ratio of training examples that contain the + # class. + predictions = estimator.predict(new_samples) + + ``` + + Input of `train` and `evaluate` should have following features, + otherwise there will be a `KeyError`: + + * if `weight_column` is specified in the `head` constructor (and not None) for + the head passed to BaselineEstimator's constructor, a feature with + `key=weight_column` whose value is a `Tensor`. + """ + + def __init__(self, head, model_dir=None, optimizer='Ftrl', config=None): + """Initializes a BaselineEstimator instance. + + Args: + head: A `Head` instance constructed with a method such as + `tf.estimator.MultiLabelHead`. + model_dir: Directory to save model parameters, graph and etc. This can + also be used to load checkpoints from the directory into a estimator to + continue training a previously saved model. + optimizer: String, `tf.keras.optimizers.*` object, or callable that + creates the optimizer to use for training. If not specified, will use + `Ftrl` as the default optimizer. + config: `RunConfig` object to configure the runtime settings. + """ + + def _model_fn(features, labels, mode, config): + return _baseline_model_fn_v2( + features=features, + labels=labels, + mode=mode, + head=head, + optimizer=optimizer, + config=config) + + super(BaselineEstimatorV2, self).__init__( + model_fn=_model_fn, model_dir=model_dir, config=config) + + +@estimator_export(v1=['estimator.BaselineEstimator']) # pylint: disable=missing-docstring +class BaselineEstimator(estimator.Estimator): + __doc__ = BaselineEstimatorV2.__doc__ + + def __init__(self, head, model_dir=None, optimizer='Ftrl', config=None): + + def _model_fn(features, labels, mode, config): + return _baseline_model_fn( + features=features, + labels=labels, + mode=mode, + head=head, + optimizer=optimizer, + config=config) + + super(BaselineEstimator, self).__init__( + model_fn=_model_fn, model_dir=model_dir, config=config) + + +@estimator_export('estimator.BaselineRegressor', v1=[]) +class BaselineRegressorV2(estimator.EstimatorV2): + """A regressor that can establish a simple baseline. + + This regressor ignores feature values and will learn to predict the average + value of each label. + + Example: + + ```python + + # Build BaselineRegressor + regressor = tf.estimator.BaselineRegressor() + + # Input builders + def input_fn_train: + # Returns tf.data.Dataset of (x, y) tuple where y represents label's class + # index. + pass + + def input_fn_eval: + # Returns tf.data.Dataset of (x, y) tuple where y represents label's class + # index. + pass + + # Fit model. + regressor.train(input_fn=input_fn_train) + + # Evaluate squared-loss between the test and train targets. + loss = regressor.evaluate(input_fn=input_fn_eval)["loss"] + + # predict outputs the mean value seen during training. + predictions = regressor.predict(new_samples) + ``` + + Input of `train` and `evaluate` should have following features, + otherwise there will be a `KeyError`: + + * if `weight_column` is not `None`, a feature with + `key=weight_column` whose value is a `Tensor`. + + @compatibility(eager) + Estimators can be used while eager execution is enabled. Note that `input_fn` + and all hooks are executed inside a graph context, so they have to be written + to be compatible with graph mode. Note that `input_fn` code using `tf.data` + generally works in both graph and eager modes. + @end_compatibility + """ + + def __init__(self, + model_dir=None, + label_dimension=1, + weight_column=None, + optimizer='Ftrl', + config=None, + loss_reduction=tf.losses.Reduction.SUM_OVER_BATCH_SIZE): + """Initializes a BaselineRegressor instance. + + Args: + model_dir: Directory to save model parameters, graph and etc. This can + also be used to load checkpoints from the directory into a estimator to + continue training a previously saved model. + label_dimension: Number of regression targets per example. This is the + size of the last dimension of the labels and logits `Tensor` objects + (typically, these have shape `[batch_size, label_dimension]`). + weight_column: A string or a `_NumericColumn` created by + `tf.feature_column.numeric_column` defining feature column representing + weights. It will be multiplied by the loss of the example. + optimizer: String, `tf.keras.optimizers.*` object, or callable that + creates the optimizer to use for training. If not specified, will use + `Ftrl` as the default optimizer. + config: `RunConfig` object to configure the runtime settings. + loss_reduction: One of `tf.losses.Reduction` except `NONE`. Describes how + to reduce training loss over batch. Defaults to `SUM_OVER_BATCH_SIZE`. + + Returns: + A `BaselineRegressor` estimator. + """ + head = regression_head.RegressionHead( + label_dimension=label_dimension, + weight_column=weight_column, + loss_reduction=loss_reduction) + + def _model_fn(features, labels, mode, config): + return _baseline_model_fn_v2( + features=features, + labels=labels, + mode=mode, + head=head, + optimizer=optimizer, + config=config) + + super(BaselineRegressorV2, self).__init__( + model_fn=_model_fn, model_dir=model_dir, config=config) + + +@estimator_export(v1=['estimator.BaselineRegressor']) # pylint: disable=missing-docstring +class BaselineRegressor(estimator.Estimator): + __doc__ = BaselineRegressorV2.__doc__.replace('SUM_OVER_BATCH_SIZE', 'SUM') + + def __init__(self, + model_dir=None, + label_dimension=1, + weight_column=None, + optimizer='Ftrl', + config=None, + loss_reduction=tf.compat.v1.losses.Reduction.SUM): + head = head_lib._regression_head( # pylint: disable=protected-access + label_dimension=label_dimension, + weight_column=weight_column, + loss_reduction=loss_reduction) + + def _model_fn(features, labels, mode, config): + return _baseline_model_fn( + features=features, + labels=labels, + mode=mode, + head=head, + optimizer=optimizer, + config=config) + + super(BaselineRegressor, self).__init__( + model_fn=_model_fn, model_dir=model_dir, config=config) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/dnn.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/dnn.py new file mode 100644 index 0000000000000000000000000000000000000000..9daf64bb7b1c733fbc1e2157162254b41048e07f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/dnn.py @@ -0,0 +1,1225 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Deep Neural Network estimators.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import six +import tensorflow as tf +from tensorflow.python.feature_column import feature_column +from tensorflow.python.feature_column import feature_column_lib +from tensorflow.python.framework import ops +from tensorflow_estimator.python.estimator import estimator +from tensorflow_estimator.python.estimator.canned import head as head_lib +from tensorflow_estimator.python.estimator.canned import optimizers +from tensorflow_estimator.python.estimator.estimator_export import estimator_export +from tensorflow_estimator.python.estimator.head import head_utils +from tensorflow_estimator.python.estimator.head import regression_head +from tensorflow_estimator.python.estimator.mode_keys import ModeKeys + +# The default learning rate of 0.05 is a historical artifact of the initial +# implementation, but seems a reasonable choice. +_LEARNING_RATE = 0.05 + + +def _add_hidden_layer_summary(value, tag): + tf.compat.v1.summary.scalar('%s/fraction_of_zero_values' % tag, + tf.math.zero_fraction(value)) + tf.compat.v1.summary.histogram('%s/activation' % tag, value) + + +@estimator_export(v1=['estimator.experimental.dnn_logit_fn_builder']) +def dnn_logit_fn_builder(units, hidden_units, feature_columns, activation_fn, + dropout, input_layer_partitioner, batch_norm): + """Function builder for a dnn logit_fn. + + Args: + units: An int indicating the dimension of the logit layer. In the MultiHead + case, this should be the sum of all component Heads' logit dimensions. + hidden_units: Iterable of integer number of hidden units per layer. + feature_columns: Iterable of `feature_column._FeatureColumn` model inputs. + activation_fn: Activation function applied to each layer. + dropout: When not `None`, the probability we will drop out a given + coordinate. + input_layer_partitioner: Partitioner for input layer. + batch_norm: Whether to use batch normalization after each hidden layer. + + Returns: + A logit_fn (see below). + + Raises: + ValueError: If units is not an int. + """ + if not isinstance(units, six.integer_types): + raise ValueError('units must be an int. Given type: {}'.format( + type(units))) + + def dnn_logit_fn(features, mode): + """Deep Neural Network logit_fn. + + Args: + features: This is the first item returned from the `input_fn` passed to + `train`, `evaluate`, and `predict`. This should be a single `Tensor` or + `dict` of same. + mode: Optional. Specifies if this training, evaluation or prediction. See + `ModeKeys`. + + Returns: + A `Tensor` representing the logits, or a list of `Tensor`'s representing + multiple logits in the MultiHead case. + """ + dnn_model = _DNNModel( + units, + hidden_units, + feature_columns, + activation_fn, + dropout, + input_layer_partitioner, + batch_norm, + name='dnn') + return dnn_model(features, mode) + + return dnn_logit_fn + + +def dnn_logit_fn_builder_v2(units, hidden_units, feature_columns, activation_fn, + dropout, batch_norm): + """Function builder for a dnn logit_fn. + + Args: + units: An int indicating the dimension of the logit layer. In the MultiHead + case, this should be the sum of all component Heads' logit dimensions. + hidden_units: Iterable of integer number of hidden units per layer. + feature_columns: Iterable of `feature_column._FeatureColumn` model inputs. + activation_fn: Activation function applied to each layer. + dropout: When not `None`, the probability we will drop out a given + coordinate. + batch_norm: Whether to use batch normalization after each hidden layer. + + Returns: + A logit_fn (see below). + + Raises: + ValueError: If units is not an int. + """ + if not isinstance(units, six.integer_types): + raise ValueError('units must be an int. Given type: {}'.format( + type(units))) + + def dnn_logit_fn(features, mode): + """Deep Neural Network logit_fn. + + Args: + features: This is the first item returned from the `input_fn` passed to + `train`, `evaluate`, and `predict`. This should be a single `Tensor` or + `dict` of same. + mode: Optional. Specifies if this training, evaluation or prediction. See + `ModeKeys`. + + Returns: + A `Tensor` representing the logits, or a list of `Tensor`'s representing + multiple logits in the MultiHead case. + """ + dnn_model = _DNNModelV2( + units, + hidden_units, + feature_columns, + activation_fn, + dropout, + batch_norm, + name='dnn') + return dnn_model(features, mode) + + return dnn_logit_fn + + +def _get_previous_name_scope(): + current_name_scope = tf.compat.v2.__internal__.get_name_scope() + return current_name_scope.rsplit('/', 1)[0] + '/' + + +class _DNNModel(tf.keras.Model): + """A DNN Model.""" + + def __init__(self, + units, + hidden_units, + feature_columns, + activation_fn, + dropout, + input_layer_partitioner, + batch_norm, + name=None, + **kwargs): + super(_DNNModel, self).__init__(name=name, **kwargs) + if feature_column_lib.is_feature_column_v2(feature_columns): + self._input_layer = tf.compat.v1.keras.layers.DenseFeatures( + feature_columns=feature_columns, name='input_layer') + else: + self._input_layer = feature_column.InputLayer( + feature_columns=feature_columns, + name='input_layer', + create_scope_now=False) + + self._add_layer(self._input_layer, 'input_layer') + + self._dropout = dropout + self._batch_norm = batch_norm + + self._hidden_layers = [] + self._dropout_layers = [] + self._batch_norm_layers = [] + self._hidden_layer_scope_names = [] + for layer_id, num_hidden_units in enumerate(hidden_units): + with tf.compat.v1.variable_scope('hiddenlayer_%d' % + layer_id) as hidden_layer_scope: + hidden_layer = tf.compat.v1.layers.Dense( + units=num_hidden_units, + activation=activation_fn, + kernel_initializer=tf.compat.v1.glorot_uniform_initializer(), + name=hidden_layer_scope, + _scope=hidden_layer_scope) + self._add_layer(hidden_layer, hidden_layer_scope.name) + self._hidden_layer_scope_names.append(hidden_layer_scope.name) + self._hidden_layers.append(hidden_layer) + if self._dropout is not None: + dropout_layer = tf.compat.v1.layers.Dropout(rate=self._dropout) + self._add_layer(dropout_layer, dropout_layer.name) + self._dropout_layers.append(dropout_layer) + if self._batch_norm: + batch_norm_layer = tf.compat.v1.layers.BatchNormalization( + # The default momentum 0.99 actually crashes on certain + # problem, so here we use 0.999, which is the default of + # tf.contrib.layers.batch_norm. + momentum=0.999, + trainable=True, + name='batchnorm_%d' % layer_id, + _scope='batchnorm_%d' % layer_id) + self._add_layer(batch_norm_layer, batch_norm_layer.name) + self._batch_norm_layers.append(batch_norm_layer) + + with tf.compat.v1.variable_scope('logits') as logits_scope: + self._logits_layer = tf.compat.v1.layers.Dense( + units=units, + activation=None, + kernel_initializer=tf.compat.v1.glorot_uniform_initializer(), + name=logits_scope, + _scope=logits_scope) + self._add_layer(self._logits_layer, logits_scope.name) + self._logits_scope_name = logits_scope.name + self._input_layer_partitioner = input_layer_partitioner + + def call(self, features, mode): + is_training = mode == ModeKeys.TRAIN + # The Keras training.Model adds a name_scope with the name of the model + # which modifies the constructed graph. Hence we add another name_scope + # here which is the one before the training.Model one was applied. + # TODO(rohanj): Remove this in TF 2.0 (b/116728605) + with ops.name_scope(name=_get_previous_name_scope()): + # TODO(rohanj): Remove dependence on variable scope for partitioning. + with tf.compat.v1.variable_scope( + 'input_from_feature_columns', + partitioner=self._input_layer_partitioner): + try: + net = self._input_layer(features, training=is_training) + except TypeError: + net = self._input_layer(features) + for i in range(len(self._hidden_layers)): + net = self._hidden_layers[i](net) + if self._dropout is not None and is_training: + net = self._dropout_layers[i](net, training=True) + if self._batch_norm: + net = self._batch_norm_layers[i](net, training=is_training) + _add_hidden_layer_summary(net, self._hidden_layer_scope_names[i]) + + logits = self._logits_layer(net) + _add_hidden_layer_summary(logits, self._logits_scope_name) + return logits + + def _add_layer(self, layer, layer_name): + # "Magic" required for keras.Model classes to track all the variables in + # a list of layers.Layer objects. + # TODO(ashankar): Figure out API so user code doesn't have to do this. + setattr(self, layer_name, layer) + + +def _name_from_scope_name(name): + """Returns the name of an op given the name of its scope. + + Args: + name: the name of the scope. + + Returns: + the name of the op (equal to scope name minus any trailing slash). + """ + return name[:-1] if (name and name[-1] == '/') else name + + +class _DNNModelV2(tf.keras.Model): + """A DNN Model.""" + + def __init__(self, + units, + hidden_units, + feature_columns, + activation_fn, + dropout, + batch_norm, + name=None, + **kwargs): + super(_DNNModelV2, self).__init__(name=name, **kwargs) + with ops.name_scope( + 'input_from_feature_columns') as input_feature_column_scope: + layer_name = input_feature_column_scope + 'input_layer' + if feature_column_lib.is_feature_column_v2(feature_columns): + self._input_layer = tf.keras.layers.DenseFeatures( + feature_columns=feature_columns, name=layer_name) + else: + raise ValueError( + 'Received a feature column from TensorFlow v1, but this is a ' + 'TensorFlow v2 Estimator. Please either use v2 feature columns ' + '(accessible via tf.feature_column.* in TF 2.x) with this ' + 'Estimator, or switch to a v1 Estimator for use with v1 feature ' + 'columns (accessible via tf.compat.v1.estimator.* and ' + 'tf.compat.v1.feature_column.*, respectively.') + + self._dropout = dropout + self._batch_norm = batch_norm + + self._hidden_layers = [] + self._dropout_layers = [] + self._batch_norm_layers = [] + self._hidden_layer_scope_names = [] + for layer_id, num_hidden_units in enumerate(hidden_units): + with ops.name_scope('hiddenlayer_%d' % layer_id) as hidden_layer_scope: + # Get scope name without the trailing slash. + hidden_shared_name = _name_from_scope_name(hidden_layer_scope) + hidden_layer = tf.keras.layers.Dense( + units=num_hidden_units, + activation=activation_fn, + kernel_initializer=tf.compat.v1.glorot_uniform_initializer(), + name=hidden_shared_name) + self._hidden_layer_scope_names.append(hidden_shared_name) + self._hidden_layers.append(hidden_layer) + if self._dropout is not None: + dropout_layer = tf.keras.layers.Dropout(rate=self._dropout) + self._dropout_layers.append(dropout_layer) + if self._batch_norm: + batch_norm_name = hidden_shared_name + '/batchnorm_%d' % layer_id + # TODO(scottzhu): Change back to use BatchNormalization when the + # cleanup is done. + batch_norm_layer = tf.keras.layers.BatchNormalization( + # The default momentum 0.99 actually crashes on certain + # problem, so here we use 0.999, which is the default of + # tf.contrib.layers.batch_norm. + momentum=0.999, + trainable=True, + name=batch_norm_name) + self._batch_norm_layers.append(batch_norm_layer) + + with ops.name_scope('logits') as logits_scope: + logits_shared_name = _name_from_scope_name(logits_scope) + self._logits_layer = tf.keras.layers.Dense( + units=units, + activation=None, + kernel_initializer=tf.compat.v1.glorot_uniform_initializer(), + name=logits_shared_name) + self._logits_scope_name = logits_shared_name + + def call(self, features, mode): + is_training = mode == ModeKeys.TRAIN + try: + net = self._input_layer(features, training=is_training) + except TypeError: + net = self._input_layer(features) + for i in range(len(self._hidden_layers)): + net = self._hidden_layers[i](net) + if self._dropout is not None and is_training: + net = self._dropout_layers[i](net, training=True) + if self._batch_norm: + net = self._batch_norm_layers[i](net, training=is_training) + _add_hidden_layer_summary(net, self._hidden_layer_scope_names[i]) + + logits = self._logits_layer(net) + _add_hidden_layer_summary(logits, self._logits_scope_name) + return logits + + +def _validate_features(features): + if not isinstance(features, dict): + raise ValueError('features should be a dictionary of `Tensor`s. ' + 'Given type: {}'.format(type(features))) + + +def _get_dnn_estimator_spec(use_tpu, head, features, labels, mode, logits, + optimizer): + """Get EstimatorSpec for DNN Model.""" + if use_tpu: + return head._create_tpu_estimator_spec( # pylint: disable=protected-access + features=features, + mode=mode, + labels=labels, + optimizer=optimizer, + logits=logits) + else: + return head.create_estimator_spec( + features=features, + mode=mode, + labels=labels, + optimizer=optimizer, + logits=logits) + + +def _dnn_model_fn(features, + labels, + mode, + head, + hidden_units, + feature_columns, + optimizer='Adagrad', + activation_fn=tf.nn.relu, + dropout=None, + input_layer_partitioner=None, + config=None, + use_tpu=False, + batch_norm=False): + """Deep Neural Net model_fn v1. + + Args: + features: dict of `Tensor`. + labels: `Tensor` of shape [batch_size, 1] or [batch_size] labels of dtype + `int32` or `int64` in the range `[0, n_classes)`. + mode: Defines whether this is training, evaluation or prediction. See + `ModeKeys`. + head: A `head_lib._Head` instance. + hidden_units: Iterable of integer number of hidden units per layer. + feature_columns: Iterable of `feature_column._FeatureColumn` model inputs. + optimizer: String, `tf.Optimizer` object, or callable that creates the + optimizer to use for training. If not specified, will use the Adagrad + optimizer with a default learning rate of 0.05. + activation_fn: Activation function applied to each layer. + dropout: When not `None`, the probability we will drop out a given + coordinate. + input_layer_partitioner: Partitioner for input layer. Defaults to + `min_max_variable_partitioner` with `min_slice_size` 64 << 20. + config: `RunConfig` object to configure the runtime settings. + use_tpu: Whether to make a DNN model able to run on TPU. Will make function + return a `_TPUEstimatorSpec` instance and disable variable partitioning. + batch_norm: Whether to use batch normalization after each hidden layer. + + Returns: + An `EstimatorSpec` instance. + + Raises: + ValueError: If features has the wrong type. + """ + + optimizer = optimizers.get_optimizer_instance( + optimizer, learning_rate=_LEARNING_RATE) + + _validate_features(features) + + num_ps_replicas = config.num_ps_replicas if config else 0 + + partitioner = (None if use_tpu else tf.compat.v1.min_max_variable_partitioner( + max_partitions=num_ps_replicas)) + with tf.compat.v1.variable_scope( + 'dnn', values=tuple(six.itervalues(features)), partitioner=partitioner): + input_layer_partitioner = input_layer_partitioner or ( + None if use_tpu else tf.compat.v1.min_max_variable_partitioner( + max_partitions=num_ps_replicas, min_slice_size=64 << 20)) + + logit_fn = dnn_logit_fn_builder( + units=head.logits_dimension, + hidden_units=hidden_units, + feature_columns=feature_columns, + activation_fn=activation_fn, + dropout=dropout, + input_layer_partitioner=input_layer_partitioner, + batch_norm=batch_norm) + logits = logit_fn(features=features, mode=mode) + + return _get_dnn_estimator_spec(use_tpu, head, features, labels, mode, + logits, optimizer) + + +def _dnn_model_fn_builder_v2(units, hidden_units, feature_columns, + activation_fn, dropout, batch_norm, features, + mode): + """Function builder for dnn logits, trainable variables and update ops. + + Args: + units: An int indicating the dimension of the logit layer. In the MultiHead + case, this should be the sum of all component Heads' logit dimensions. + hidden_units: Iterable of integer number of hidden units per layer. + feature_columns: Iterable of `feature_column._FeatureColumn` model inputs. + activation_fn: Activation function applied to each layer. + dropout: When not `None`, the probability we will drop out a given + coordinate. + batch_norm: Whether to use batch normalization after each hidden layer. + features: This is the first item returned from the `input_fn` passed to + `train`, `evaluate`, and `predict`. This should be a single `Tensor` or + `dict` of same. + mode: Optional. Specifies if this training, evaluation or prediction. See + `ModeKeys`. + + Returns: + A `Tensor` representing the logits, or a list of `Tensor`'s representing + multiple logits in the MultiHead case. + A list of trainable variables. + A list of update ops. + + Raises: + ValueError: If units is not an int. + """ + if not isinstance(units, six.integer_types): + raise ValueError('units must be an int. Given type: {}'.format( + type(units))) + dnn_model = _DNNModelV2( + units, + hidden_units, + feature_columns, + activation_fn, + dropout, + batch_norm, + name='dnn') + logits = dnn_model(features, mode) + trainable_variables = dnn_model.trainable_variables + update_ops = dnn_model.updates + + return logits, trainable_variables, update_ops + + +def dnn_model_fn_v2(features, + labels, + mode, + head, + hidden_units, + feature_columns, + optimizer='Adagrad', + activation_fn=tf.nn.relu, + dropout=None, + config=None, + use_tpu=False, + batch_norm=False): + """Deep Neural Net model_fn v2. + + This function is different than _dnn_model_fn_v1 in the way it handles the + optimizer when a String optimizer name is passed. + + Args: + features: dict of `Tensor`. + labels: `Tensor` of shape [batch_size, 1] or [batch_size] labels of dtype + `int32` or `int64` in the range `[0, n_classes)`. + mode: Defines whether this is training, evaluation or prediction. See + `ModeKeys`. + head: A `base_head.Head` instance. + hidden_units: Iterable of integer number of hidden units per layer. + feature_columns: Iterable of `feature_column._FeatureColumn` model inputs. + optimizer: String, `tf.keras.optimizers.Optimizer` object, or callable that + creates the optimizer to use for training. If not specified, will use the + Adagrad optimizer. If it is String, the default learning rate of the + optimizer will be used. If it is String, and optimizer does not have a + default learning rate, then, a fixed learning rate of 0.05 is used. + activation_fn: Activation function applied to each layer. + dropout: When not `None`, the probability we will drop out a given + coordinate. + config: `RunConfig` object to configure the runtime settings. + use_tpu: Whether to make a DNN model able to run on TPU. Will make function + return a `_TPUEstimatorSpec` instance and disable variable partitioning. + batch_norm: Whether to use batch normalization after each hidden layer. + + Returns: + An `EstimatorSpec` instance. + + Raises: + ValueError: If features has the wrong type. + """ + _validate_features(features) + + del config + + logits, trainable_variables, update_ops = _dnn_model_fn_builder_v2( + units=head.logits_dimension, + hidden_units=hidden_units, + feature_columns=feature_columns, + activation_fn=activation_fn, + dropout=dropout, + batch_norm=batch_norm, + features=features, + mode=mode) + + # In TRAIN mode, create optimizer and assign global_step variable to + # optimizer.iterations to make global_step increased correctly, as Hooks + # relies on global step as step counter. + if mode == ModeKeys.TRAIN: + optimizer = optimizers.get_optimizer_instance_v2(optimizer) + optimizer.iterations = tf.compat.v1.train.get_or_create_global_step() + + # Create EstimatorSpec. + if use_tpu: + estimator_spec_fn = head._create_tpu_estimator_spec # pylint: disable=protected-access + else: + estimator_spec_fn = head.create_estimator_spec # pylint: disable=protected-access + + return estimator_spec_fn( + features=features, + mode=mode, + labels=labels, + optimizer=optimizer, + logits=logits, + trainable_variables=trainable_variables, + update_ops=update_ops) + + +@estimator_export('estimator.DNNClassifier', v1=[]) +class DNNClassifierV2(estimator.EstimatorV2): + """A classifier for TensorFlow DNN models. + + Example: + + ```python + categorical_feature_a = categorical_column_with_hash_bucket(...) + categorical_feature_b = categorical_column_with_hash_bucket(...) + + categorical_feature_a_emb = embedding_column( + categorical_column=categorical_feature_a, ...) + categorical_feature_b_emb = embedding_column( + categorical_column=categorical_feature_b, ...) + + estimator = tf.estimator.DNNClassifier( + feature_columns=[categorical_feature_a_emb, categorical_feature_b_emb], + hidden_units=[1024, 512, 256]) + + # Or estimator using the ProximalAdagradOptimizer optimizer with + # regularization. + estimator = tf.estimator.DNNClassifier( + feature_columns=[categorical_feature_a_emb, categorical_feature_b_emb], + hidden_units=[1024, 512, 256], + optimizer=tf.compat.v1.train.ProximalAdagradOptimizer( + learning_rate=0.1, + l1_regularization_strength=0.001 + )) + + # Or estimator using an optimizer with a learning rate decay. + estimator = tf.estimator.DNNClassifier( + feature_columns=[categorical_feature_a_emb, categorical_feature_b_emb], + hidden_units=[1024, 512, 256], + optimizer=lambda: tf.keras.optimizers.Adam( + learning_rate=tf.compat.v1.train.exponential_decay( + learning_rate=0.1, + global_step=tf.compat.v1.train.get_global_step(), + decay_steps=10000, + decay_rate=0.96)) + + # Or estimator with warm-starting from a previous checkpoint. + estimator = tf.estimator.DNNClassifier( + feature_columns=[categorical_feature_a_emb, categorical_feature_b_emb], + hidden_units=[1024, 512, 256], + warm_start_from="/path/to/checkpoint/dir") + + # Input builders + def input_fn_train: + # Returns tf.data.Dataset of (x, y) tuple where y represents label's class + # index. + pass + def input_fn_eval: + # Returns tf.data.Dataset of (x, y) tuple where y represents label's class + # index. + pass + def input_fn_predict: + # Returns tf.data.Dataset of (x, None) tuple. + pass + estimator.train(input_fn=input_fn_train) + metrics = estimator.evaluate(input_fn=input_fn_eval) + predictions = estimator.predict(input_fn=input_fn_predict) + ``` + + Input of `train` and `evaluate` should have following features, + otherwise there will be a `KeyError`: + + * if `weight_column` is not `None`, a feature with `key=weight_column` whose + value is a `Tensor`. + * for each `column` in `feature_columns`: + - if `column` is a `CategoricalColumn`, a feature with `key=column.name` + whose `value` is a `SparseTensor`. + - if `column` is a `WeightedCategoricalColumn`, two features: the first + with `key` the id column name, the second with `key` the weight column + name. Both features' `value` must be a `SparseTensor`. + - if `column` is a `DenseColumn`, a feature with `key=column.name` + whose `value` is a `Tensor`. + + Loss is calculated by using softmax cross entropy. + + @compatibility(eager) + Estimators can be used while eager execution is enabled. Note that `input_fn` + and all hooks are executed inside a graph context, so they have to be written + to be compatible with graph mode. Note that `input_fn` code using `tf.data` + generally works in both graph and eager modes. + @end_compatibility + """ + + def __init__( + self, + hidden_units, + feature_columns, + model_dir=None, + n_classes=2, + weight_column=None, + label_vocabulary=None, + optimizer='Adagrad', + activation_fn=tf.nn.relu, + dropout=None, + config=None, + warm_start_from=None, + loss_reduction=tf.losses.Reduction.SUM_OVER_BATCH_SIZE, + batch_norm=False, + ): + """Initializes a `DNNClassifier` instance. + + Args: + hidden_units: Iterable of number hidden units per layer. All layers are + fully connected. Ex. `[64, 32]` means first layer has 64 nodes and + second one has 32. + feature_columns: An iterable containing all the feature columns used by + the model. All items in the set should be instances of classes derived + from `_FeatureColumn`. + model_dir: Directory to save model parameters, graph and etc. This can + also be used to load checkpoints from the directory into a estimator to + continue training a previously saved model. + n_classes: Number of label classes. Defaults to 2, namely binary + classification. Must be > 1. + weight_column: A string or a `NumericColumn` created by + `tf.feature_column.numeric_column` defining feature column representing + weights. It is used to down weight or boost examples during training. It + will be multiplied by the loss of the example. If it is a string, it is + used as a key to fetch weight tensor from the `features`. If it is a + `_NumericColumn`, raw tensor is fetched by key `weight_column.key`, then + weight_column.normalizer_fn is applied on it to get weight tensor. + label_vocabulary: A list of strings represents possible label values. If + given, labels must be string type and have any value in + `label_vocabulary`. If it is not given, that means labels are already + encoded as integer or float within [0, 1] for `n_classes=2` and encoded + as integer values in {0, 1,..., n_classes-1} for `n_classes`>2 . Also + there will be errors if vocabulary is not provided and labels are + string. + optimizer: An instance of `tf.keras.optimizers.*` used to train the model. + Can also be a string (one of 'Adagrad', 'Adam', 'Ftrl', 'RMSProp', + SGD'), or callable. Defaults to Adagrad optimizer. + activation_fn: Activation function applied to each layer. If `None`, will + use `tf.nn.relu`. + dropout: When not `None`, the probability we will drop out a given + coordinate. + config: `RunConfig` object to configure the runtime settings. + warm_start_from: A string filepath to a checkpoint to warm-start from, or + a `WarmStartSettings` object to fully configure warm-starting. If the + string filepath is provided instead of a `WarmStartSettings`, then all + weights are warm-started, and it is assumed that vocabularies and Tensor + names are unchanged. + loss_reduction: One of `tf.losses.Reduction` except `NONE`. Describes how + to reduce training loss over batch. Defaults to `SUM_OVER_BATCH_SIZE`. + batch_norm: Whether to use batch normalization after each hidden layer. + """ + head = head_utils.binary_or_multi_class_head( + n_classes, + weight_column=weight_column, + label_vocabulary=label_vocabulary, + loss_reduction=loss_reduction) + estimator._canned_estimator_api_gauge.get_cell('Classifier').set('DNN') + + def _model_fn(features, labels, mode, config): + """Call the defined shared dnn_model_fn_v2.""" + return dnn_model_fn_v2( + features=features, + labels=labels, + mode=mode, + head=head, + hidden_units=hidden_units, + feature_columns=tuple(feature_columns or []), + optimizer=optimizer, + activation_fn=activation_fn, + dropout=dropout, + config=config, + batch_norm=batch_norm) + + super(DNNClassifierV2, self).__init__( + model_fn=_model_fn, + model_dir=model_dir, + config=config, + warm_start_from=warm_start_from) + + +@estimator_export(v1=['estimator.DNNClassifier']) # pylint: disable=missing-docstring +class DNNClassifier(estimator.Estimator): + __doc__ = DNNClassifierV2.__doc__.replace('SUM_OVER_BATCH_SIZE', 'SUM') + + def __init__( + self, + hidden_units, + feature_columns, + model_dir=None, + n_classes=2, + weight_column=None, + label_vocabulary=None, + optimizer='Adagrad', + activation_fn=tf.nn.relu, + dropout=None, + input_layer_partitioner=None, + config=None, + warm_start_from=None, + loss_reduction=tf.compat.v1.losses.Reduction.SUM, + batch_norm=False, + ): + head = head_lib._binary_logistic_or_multi_class_head( # pylint: disable=protected-access + n_classes, weight_column, label_vocabulary, loss_reduction) + estimator._canned_estimator_api_gauge.get_cell('Classifier').set('DNN') + + def _model_fn(features, labels, mode, config): + """Call the defined shared dnn_model_fn.""" + return _dnn_model_fn( + features=features, + labels=labels, + mode=mode, + head=head, + hidden_units=hidden_units, + feature_columns=tuple(feature_columns or []), + optimizer=optimizer, + activation_fn=activation_fn, + dropout=dropout, + input_layer_partitioner=input_layer_partitioner, + config=config, + batch_norm=batch_norm) + + super(DNNClassifier, self).__init__( + model_fn=_model_fn, + model_dir=model_dir, + config=config, + warm_start_from=warm_start_from) + + +@estimator_export('estimator.DNNEstimator', v1=[]) +class DNNEstimatorV2(estimator.EstimatorV2): + """An estimator for TensorFlow DNN models with user-specified head. + + Example: + + ```python + sparse_feature_a = sparse_column_with_hash_bucket(...) + sparse_feature_b = sparse_column_with_hash_bucket(...) + + sparse_feature_a_emb = embedding_column(sparse_id_column=sparse_feature_a, + ...) + sparse_feature_b_emb = embedding_column(sparse_id_column=sparse_feature_b, + ...) + + estimator = tf.estimator.DNNEstimator( + head=tf.estimator.MultiLabelHead(n_classes=3), + feature_columns=[sparse_feature_a_emb, sparse_feature_b_emb], + hidden_units=[1024, 512, 256]) + + # Or estimator using the ProximalAdagradOptimizer optimizer with + # regularization. + estimator = tf.estimator.DNNEstimator( + head=tf.estimator.MultiLabelHead(n_classes=3), + feature_columns=[sparse_feature_a_emb, sparse_feature_b_emb], + hidden_units=[1024, 512, 256], + optimizer=tf.compat.v1.train.ProximalAdagradOptimizer( + learning_rate=0.1, + l1_regularization_strength=0.001 + )) + + # Or estimator using an optimizer with a learning rate decay. + estimator = tf.estimator.DNNEstimator( + head=tf.estimator.MultiLabelHead(n_classes=3), + feature_columns=[sparse_feature_a_emb, sparse_feature_b_emb], + hidden_units=[1024, 512, 256], + optimizer=lambda: tf.keras.optimizers.Adam( + learning_rate=tf.compat.v1.train.exponential_decay( + learning_rate=0.1, + global_step=tf.compat.v1.train.get_global_step(), + decay_steps=10000, + decay_rate=0.96)) + + # Or estimator with warm-starting from a previous checkpoint. + estimator = tf.estimator.DNNEstimator( + head=tf.estimator.MultiLabelHead(n_classes=3), + feature_columns=[sparse_feature_a_emb, sparse_feature_b_emb], + hidden_units=[1024, 512, 256], + warm_start_from="/path/to/checkpoint/dir") + + # Input builders + def input_fn_train: + # Returns tf.data.Dataset of (x, y) tuple where y represents label's class + # index. + pass + def input_fn_eval: + # Returns tf.data.Dataset of (x, y) tuple where y represents label's class + # index. + pass + def input_fn_predict: + # Returns tf.data.Dataset of (x, None) tuple. + pass + estimator.train(input_fn=input_fn_train) + metrics = estimator.evaluate(input_fn=input_fn_eval) + predictions = estimator.predict(input_fn=input_fn_predict) + ``` + + Input of `train` and `evaluate` should have following features, + otherwise there will be a `KeyError`: + + * if `weight_column` is not `None`, a feature with `key=weight_column` whose + value is a `Tensor`. + * for each `column` in `feature_columns`: + - if `column` is a `CategoricalColumn`, a feature with `key=column.name` + whose `value` is a `SparseTensor`. + - if `column` is a `WeightedCategoricalColumn`, two features: the first + with `key` the id column name, the second with `key` the weight column + name. Both features' `value` must be a `SparseTensor`. + - if `column` is a `DenseColumn`, a feature with `key=column.name` + whose `value` is a `Tensor`. + + Loss and predicted output are determined by the specified head. + + @compatibility(eager) + Estimators can be used while eager execution is enabled. Note that `input_fn` + and all hooks are executed inside a graph context, so they have to be written + to be compatible with graph mode. Note that `input_fn` code using `tf.data` + generally works in both graph and eager modes. + @end_compatibility + """ + + def __init__(self, + head, + hidden_units, + feature_columns, + model_dir=None, + optimizer='Adagrad', + activation_fn=tf.nn.relu, + dropout=None, + config=None, + warm_start_from=None, + batch_norm=False): + """Initializes a `DNNEstimator` instance. + + Args: + head: A `_Head` instance constructed with a method such as + `tf.contrib.estimator.multi_label_head`. + hidden_units: Iterable of number hidden units per layer. All layers are + fully connected. Ex. `[64, 32]` means first layer has 64 nodes and + second one has 32. + feature_columns: An iterable containing all the feature columns used by + the model. All items in the set should be instances of classes derived + from `_FeatureColumn`. + model_dir: Directory to save model parameters, graph and etc. This can + also be used to load checkpoints from the directory into a estimator to + continue training a previously saved model. + optimizer: An instance of `tf.keras.optimizers.*` used to train the model. + Can also be a string (one of 'Adagrad', 'Adam', 'Ftrl', 'RMSProp', + SGD'), or callable. Defaults to Adagrad optimizer. + activation_fn: Activation function applied to each layer. If `None`, will + use `tf.nn.relu`. + dropout: When not `None`, the probability we will drop out a given + coordinate. + config: `RunConfig` object to configure the runtime settings. + warm_start_from: A string filepath to a checkpoint to warm-start from, or + a `WarmStartSettings` object to fully configure warm-starting. If the + string filepath is provided instead of a `WarmStartSettings`, then all + weights are warm-started, and it is assumed that vocabularies and Tensor + names are unchanged. + batch_norm: Whether to use batch normalization after each hidden layer. + """ + + def _model_fn(features, labels, mode, config): + """Call the defined shared dnn_model_fn_v2.""" + return dnn_model_fn_v2( + features=features, + labels=labels, + mode=mode, + head=head, + hidden_units=hidden_units, + feature_columns=tuple(feature_columns or []), + optimizer=optimizer, + activation_fn=activation_fn, + dropout=dropout, + config=config, + batch_norm=batch_norm) + + estimator._canned_estimator_api_gauge.get_cell('Estimator').set('DNN') # pylint: disable=protected-access + super(DNNEstimatorV2, self).__init__( + model_fn=_model_fn, + model_dir=model_dir, + config=config, + warm_start_from=warm_start_from) + + +@estimator_export(v1=['estimator.DNNEstimator']) # pylint: disable=missing-docstring +class DNNEstimator(estimator.Estimator): + __doc__ = DNNEstimatorV2.__doc__ + + def __init__(self, + head, + hidden_units, + feature_columns, + model_dir=None, + optimizer='Adagrad', + activation_fn=tf.nn.relu, + dropout=None, + input_layer_partitioner=None, + config=None, + warm_start_from=None, + batch_norm=False): + + def _model_fn(features, labels, mode, config): + """Call the defined shared _dnn_model_fn.""" + return _dnn_model_fn( + features=features, + labels=labels, + mode=mode, + head=head, + hidden_units=hidden_units, + feature_columns=tuple(feature_columns or []), + optimizer=optimizer, + activation_fn=activation_fn, + dropout=dropout, + input_layer_partitioner=input_layer_partitioner, + config=config, + batch_norm=batch_norm) + + estimator._canned_estimator_api_gauge.get_cell('Estimator').set('DNN') # pylint: disable=protected-access + super(DNNEstimator, self).__init__( + model_fn=_model_fn, + model_dir=model_dir, + config=config, + warm_start_from=warm_start_from) + + +@estimator_export('estimator.DNNRegressor', v1=[]) +class DNNRegressorV2(estimator.EstimatorV2): + """A regressor for TensorFlow DNN models. + + Example: + + ```python + categorical_feature_a = categorical_column_with_hash_bucket(...) + categorical_feature_b = categorical_column_with_hash_bucket(...) + + categorical_feature_a_emb = embedding_column( + categorical_column=categorical_feature_a, ...) + categorical_feature_b_emb = embedding_column( + categorical_column=categorical_feature_b, ...) + + estimator = tf.estimator.DNNRegressor( + feature_columns=[categorical_feature_a_emb, categorical_feature_b_emb], + hidden_units=[1024, 512, 256]) + + # Or estimator using the ProximalAdagradOptimizer optimizer with + # regularization. + estimator = tf.estimator.DNNRegressor( + feature_columns=[categorical_feature_a_emb, categorical_feature_b_emb], + hidden_units=[1024, 512, 256], + optimizer=tf.compat.v1.train.ProximalAdagradOptimizer( + learning_rate=0.1, + l1_regularization_strength=0.001 + )) + + # Or estimator using an optimizer with a learning rate decay. + estimator = tf.estimator.DNNRegressor( + feature_columns=[categorical_feature_a_emb, categorical_feature_b_emb], + hidden_units=[1024, 512, 256], + optimizer=lambda: tf.keras.optimizers.Adam( + learning_rate=tf.compat.v1.train.exponential_decay( + learning_rate=0.1, + global_step=tf.compat.v1.train.get_global_step(), + decay_steps=10000, + decay_rate=0.96)) + + # Or estimator with warm-starting from a previous checkpoint. + estimator = tf.estimator.DNNRegressor( + feature_columns=[categorical_feature_a_emb, categorical_feature_b_emb], + hidden_units=[1024, 512, 256], + warm_start_from="/path/to/checkpoint/dir") + + # Input builders + def input_fn_train: + # Returns tf.data.Dataset of (x, y) tuple where y represents label's class + # index. + pass + def input_fn_eval: + # Returns tf.data.Dataset of (x, y) tuple where y represents label's class + # index. + pass + def input_fn_predict: + # Returns tf.data.Dataset of (x, None) tuple. + pass + estimator.train(input_fn=input_fn_train) + metrics = estimator.evaluate(input_fn=input_fn_eval) + predictions = estimator.predict(input_fn=input_fn_predict) + ``` + + Input of `train` and `evaluate` should have following features, + otherwise there will be a `KeyError`: + + * if `weight_column` is not `None`, a feature with `key=weight_column` whose + value is a `Tensor`. + * for each `column` in `feature_columns`: + - if `column` is a `CategoricalColumn`, a feature with `key=column.name` + whose `value` is a `SparseTensor`. + - if `column` is a `WeightedCategoricalColumn`, two features: the first + with `key` the id column name, the second with `key` the weight column + name. Both features' `value` must be a `SparseTensor`. + - if `column` is a `DenseColumn`, a feature with `key=column.name` + whose `value` is a `Tensor`. + + Loss is calculated by using mean squared error. + + @compatibility(eager) + Estimators can be used while eager execution is enabled. Note that `input_fn` + and all hooks are executed inside a graph context, so they have to be written + to be compatible with graph mode. Note that `input_fn` code using `tf.data` + generally works in both graph and eager modes. + @end_compatibility + """ + + def __init__( + self, + hidden_units, + feature_columns, + model_dir=None, + label_dimension=1, + weight_column=None, + optimizer='Adagrad', + activation_fn=tf.nn.relu, + dropout=None, + config=None, + warm_start_from=None, + loss_reduction=tf.losses.Reduction.SUM_OVER_BATCH_SIZE, + batch_norm=False, + ): + """Initializes a `DNNRegressor` instance. + + Args: + hidden_units: Iterable of number hidden units per layer. All layers are + fully connected. Ex. `[64, 32]` means first layer has 64 nodes and + second one has 32. + feature_columns: An iterable containing all the feature columns used by + the model. All items in the set should be instances of classes derived + from `FeatureColumn`. + model_dir: Directory to save model parameters, graph and etc. This can + also be used to load checkpoints from the directory into a estimator to + continue training a previously saved model. + label_dimension: Number of regression targets per example. This is the + size of the last dimension of the labels and logits `Tensor` objects + (typically, these have shape `[batch_size, label_dimension]`). + weight_column: A string or a `NumericColumn` created by + `tf.feature_column.numeric_column` defining feature column representing + weights. It is used to down weight or boost examples during training. It + will be multiplied by the loss of the example. If it is a string, it is + used as a key to fetch weight tensor from the `features`. If it is a + `NumericColumn`, raw tensor is fetched by key `weight_column.key`, then + weight_column.normalizer_fn is applied on it to get weight tensor. + optimizer: An instance of `tf.keras.optimizers.*` used to train the model. + Can also be a string (one of 'Adagrad', 'Adam', 'Ftrl', 'RMSProp', + SGD'), or callable. Defaults to Adagrad optimizer. + activation_fn: Activation function applied to each layer. If `None`, will + use `tf.nn.relu`. + dropout: When not `None`, the probability we will drop out a given + coordinate. + config: `RunConfig` object to configure the runtime settings. + warm_start_from: A string filepath to a checkpoint to warm-start from, or + a `WarmStartSettings` object to fully configure warm-starting. If the + string filepath is provided instead of a `WarmStartSettings`, then all + weights are warm-started, and it is assumed that vocabularies and Tensor + names are unchanged. + loss_reduction: One of `tf.losses.Reduction` except `NONE`. Describes how + to reduce training loss over batch. Defaults to `SUM_OVER_BATCH_SIZE`. + batch_norm: Whether to use batch normalization after each hidden layer. + """ + head = regression_head.RegressionHead( + label_dimension=label_dimension, + weight_column=weight_column, + loss_reduction=loss_reduction) + estimator._canned_estimator_api_gauge.get_cell('Regressor').set('DNN') # pylint: disable=protected-access + + def _model_fn(features, labels, mode, config): + """Call the defined shared dnn_model_fn_v2.""" + return dnn_model_fn_v2( + features=features, + labels=labels, + mode=mode, + head=head, + hidden_units=hidden_units, + feature_columns=tuple(feature_columns or []), + optimizer=optimizer, + activation_fn=activation_fn, + dropout=dropout, + config=config, + batch_norm=batch_norm) + + super(DNNRegressorV2, self).__init__( + model_fn=_model_fn, + model_dir=model_dir, + config=config, + warm_start_from=warm_start_from) + + +@estimator_export(v1=['estimator.DNNRegressor']) # pylint: disable=missing-docstring +class DNNRegressor(estimator.Estimator): + __doc__ = DNNRegressorV2.__doc__.replace('SUM_OVER_BATCH_SIZE', 'SUM') + + def __init__( + self, + hidden_units, + feature_columns, + model_dir=None, + label_dimension=1, + weight_column=None, + optimizer='Adagrad', + activation_fn=tf.nn.relu, + dropout=None, + input_layer_partitioner=None, + config=None, + warm_start_from=None, + loss_reduction=tf.compat.v1.losses.Reduction.SUM, + batch_norm=False, + ): + head = head_lib._regression_head( # pylint: disable=protected-access + label_dimension=label_dimension, + weight_column=weight_column, + loss_reduction=loss_reduction) + estimator._canned_estimator_api_gauge.get_cell('Regressor').set('DNN') # pylint: disable=protected-access + + def _model_fn(features, labels, mode, config): + """Call the defined shared _dnn_model_fn.""" + return _dnn_model_fn( + features=features, + labels=labels, + mode=mode, + head=head, + hidden_units=hidden_units, + feature_columns=tuple(feature_columns or []), + optimizer=optimizer, + activation_fn=activation_fn, + dropout=dropout, + input_layer_partitioner=input_layer_partitioner, + config=config, + batch_norm=batch_norm) + + super(DNNRegressor, self).__init__( + model_fn=_model_fn, + model_dir=model_dir, + config=config, + warm_start_from=warm_start_from) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/dnn_linear_combined.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/dnn_linear_combined.py new file mode 100644 index 0000000000000000000000000000000000000000..2ce2a937c8af08c1376c1a3924de510f020fc7fa --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/dnn_linear_combined.py @@ -0,0 +1,1146 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""TensorFlow estimators for Linear and DNN joined training models.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import math + +import six +import tensorflow as tf +from tensorflow_estimator.python.estimator import estimator +from tensorflow_estimator.python.estimator.canned import dnn +from tensorflow_estimator.python.estimator.canned import head as head_lib +from tensorflow_estimator.python.estimator.canned import linear +from tensorflow_estimator.python.estimator.canned import optimizers +from tensorflow_estimator.python.estimator.estimator_export import estimator_export +from tensorflow_estimator.python.estimator.head import head_utils +from tensorflow_estimator.python.estimator.head import regression_head +from tensorflow_estimator.python.estimator.mode_keys import ModeKeys + +# The default learning rates are a historical artifact of the initial +# implementation. +_DNN_LEARNING_RATE = 0.001 +_LINEAR_LEARNING_RATE = 0.005 + + +def _check_no_sync_replicas_optimizer(optimizer): + if isinstance(optimizer, tf.compat.v1.train.SyncReplicasOptimizer): + raise ValueError( + 'SyncReplicasOptimizer does not support multi optimizers case. ' + 'Therefore, it is not supported in DNNLinearCombined model. ' + 'If you want to use this optimizer, please use either DNN or Linear ' + 'model.') + + +def _linear_learning_rate(num_linear_feature_columns): + """Returns the default learning rate of the linear model. + + The calculation is a historical artifact of this initial implementation, but + has proven a reasonable choice. + + Args: + num_linear_feature_columns: The number of feature columns of the linear + model. + + Returns: + A float. + """ + default_learning_rate = 1. / math.sqrt(num_linear_feature_columns) + return min(_LINEAR_LEARNING_RATE, default_learning_rate) + + +def _add_layer_summary(value, tag): + tf.compat.v1.summary.scalar('%s/fraction_of_zero_values' % tag, + tf.math.zero_fraction(value)) + tf.compat.v1.summary.histogram('%s/activation' % tag, value) + + +def _validate_feature_columns(linear_feature_columns, dnn_feature_columns): + """Validates feature columns DNNLinearCombinedRegressor.""" + linear_feature_columns = linear_feature_columns or [] + dnn_feature_columns = dnn_feature_columns or [] + feature_columns = (list(linear_feature_columns) + list(dnn_feature_columns)) + if not feature_columns: + raise ValueError('Either linear_feature_columns or dnn_feature_columns ' + 'must be defined.') + return feature_columns + + +def _dnn_linear_combined_model_fn_v2( + features, + labels, + mode, + head, + linear_feature_columns=None, + linear_optimizer='Ftrl', + dnn_feature_columns=None, + dnn_optimizer='Adagrad', + dnn_hidden_units=None, + dnn_activation_fn=tf.nn.relu, + dnn_dropout=None, + config=None, + batch_norm=False, + linear_sparse_combiner='sum', + loss_reduction=tf.losses.Reduction.SUM_OVER_BATCH_SIZE): + """Deep Neural Net and Linear combined model_fn. + + Args: + features: dict of `Tensor`. + labels: `Tensor` of shape [batch_size, 1] or [batch_size] labels of dtype + `int32` or `int64` in the range `[0, n_classes)`. + mode: Defines whether this is training, evaluation or prediction. See + `ModeKeys`. + head: A `Head` instance. + linear_feature_columns: An iterable containing all the feature columns used + by the Linear model. + linear_optimizer: string, `Optimizer` object, or callable that defines the + optimizer to use for training the Linear model. Defaults to the Ftrl + optimizer. + dnn_feature_columns: An iterable containing all the feature columns used by + the DNN model. + dnn_optimizer: string, `Optimizer` object, or callable that defines the + optimizer to use for training the DNN model. Defaults to the Adagrad + optimizer. + dnn_hidden_units: List of hidden units per DNN layer. + dnn_activation_fn: Activation function applied to each DNN layer. If `None`, + will use `tf.nn.relu`. + dnn_dropout: When not `None`, the probability we will drop out a given DNN + coordinate. + config: `RunConfig` object to configure the runtime settings. + batch_norm: Whether to use batch normalization after each hidden layer. + linear_sparse_combiner: A string specifying how to reduce the linear model + if a categorical column is multivalent. One of "mean", "sqrtn", and + "sum". + loss_reduction: One of `tf.keras.losses.Reduction` except `NONE`. Describes + how to reduce training loss over batch. Defaults to `SUM_OVER_BATCH_SIZE`. + + Returns: + An `EstimatorSpec` instance. + + Raises: + ValueError: If both `linear_feature_columns` and `dnn_features_columns` + are empty at the same time, or `input_layer_partitioner` is missing, + or features has the wrong type. + """ + if not isinstance(features, dict): + raise ValueError('features should be a dictionary of `Tensor`s. ' + 'Given type: {}'.format(type(features))) + if not linear_feature_columns and not dnn_feature_columns: + raise ValueError( + 'Either linear_feature_columns or dnn_feature_columns must be defined.') + + del config + + # Build DNN Logits. + if not dnn_feature_columns: + dnn_logits = None + else: + if mode == ModeKeys.TRAIN: + dnn_optimizer = optimizers.get_optimizer_instance_v2( + dnn_optimizer, learning_rate=_DNN_LEARNING_RATE) + _check_no_sync_replicas_optimizer(dnn_optimizer) + + if not dnn_hidden_units: + raise ValueError( + 'dnn_hidden_units must be defined when dnn_feature_columns is ' + 'specified.') + dnn_logits, dnn_trainable_variables, dnn_update_ops = ( + dnn._dnn_model_fn_builder_v2( # pylint: disable=protected-access + units=head.logits_dimension, + hidden_units=dnn_hidden_units, + feature_columns=dnn_feature_columns, + activation_fn=dnn_activation_fn, + dropout=dnn_dropout, + batch_norm=batch_norm, + features=features, + mode=mode)) + + if not linear_feature_columns: + linear_logits = None + else: + if mode == ModeKeys.TRAIN: + linear_optimizer = optimizers.get_optimizer_instance_v2( + linear_optimizer, + learning_rate=_linear_learning_rate(len(linear_feature_columns))) + _check_no_sync_replicas_optimizer(linear_optimizer) + + linear_logits, linear_trainable_variables = ( + linear._linear_model_fn_builder_v2( # pylint: disable=protected-access + units=head.logits_dimension, + feature_columns=linear_feature_columns, + sparse_combiner=linear_sparse_combiner, + features=features)) + _add_layer_summary(linear_logits, 'linear') + + # Combine logits and build full model. + if dnn_logits is not None and linear_logits is not None: + logits = dnn_logits + linear_logits + elif dnn_logits is not None: + logits = dnn_logits + else: + logits = linear_logits + + def _train_op_fn(loss): + """Returns the op to optimize the loss.""" + train_ops = [] + # Scale loss by number of replicas. + if loss_reduction == tf.losses.Reduction.SUM_OVER_BATCH_SIZE: + num_replicas = tf.distribute.get_strategy().num_replicas_in_sync + if num_replicas > 1: + loss *= (1. / num_replicas) + + if dnn_logits is not None: + train_ops.extend(dnn_optimizer.get_updates(loss, dnn_trainable_variables)) + if dnn_update_ops is not None: + train_ops.extend(dnn_update_ops) + if linear_logits is not None: + train_ops.extend( + linear_optimizer.get_updates(loss, linear_trainable_variables)) + train_op = tf.group(*train_ops) + return train_op + + # In TRAIN mode, asssign global_step variable to optimizer.iterations to + # make global_step increased correctly, as Hooks relies on global step as + # step counter. Note that, Only one model's optimizer needs this assignment. + if mode == ModeKeys.TRAIN: + if dnn_logits is not None: + dnn_optimizer.iterations = tf.compat.v1.train.get_or_create_global_step() + else: + linear_optimizer.iterations = \ + tf.compat.v1.train.get_or_create_global_step() + + return head.create_estimator_spec( + features=features, + mode=mode, + labels=labels, + train_op_fn=_train_op_fn, + logits=logits) + + +def _dnn_linear_combined_model_fn(features, + labels, + mode, + head, + linear_feature_columns=None, + linear_optimizer='Ftrl', + dnn_feature_columns=None, + dnn_optimizer='Adagrad', + dnn_hidden_units=None, + dnn_activation_fn=tf.nn.relu, + dnn_dropout=None, + input_layer_partitioner=None, + config=None, + batch_norm=False, + linear_sparse_combiner='sum'): + """Deep Neural Net and Linear combined model_fn. + + Args: + features: dict of `Tensor`. + labels: `Tensor` of shape [batch_size, 1] or [batch_size] labels of dtype + `int32` or `int64` in the range `[0, n_classes)`. + mode: Defines whether this is training, evaluation or prediction. See + `ModeKeys`. + head: A `Head` instance. + linear_feature_columns: An iterable containing all the feature columns used + by the Linear model. + linear_optimizer: string, `Optimizer` object, or callable that defines the + optimizer to use for training the Linear model. Defaults to the Ftrl + optimizer. + dnn_feature_columns: An iterable containing all the feature columns used by + the DNN model. + dnn_optimizer: string, `Optimizer` object, or callable that defines the + optimizer to use for training the DNN model. Defaults to the Adagrad + optimizer. + dnn_hidden_units: List of hidden units per DNN layer. + dnn_activation_fn: Activation function applied to each DNN layer. If `None`, + will use `tf.nn.relu`. + dnn_dropout: When not `None`, the probability we will drop out a given DNN + coordinate. + input_layer_partitioner: Partitioner for input layer. + config: `RunConfig` object to configure the runtime settings. + batch_norm: Whether to use batch normalization after each hidden layer. + linear_sparse_combiner: A string specifying how to reduce the linear model + if a categorical column is multivalent. One of "mean", "sqrtn", and + "sum". + + Returns: + An `EstimatorSpec` instance. + + Raises: + ValueError: If both `linear_feature_columns` and `dnn_features_columns` + are empty at the same time, or `input_layer_partitioner` is missing, + or features has the wrong type. + """ + if not isinstance(features, dict): + raise ValueError('features should be a dictionary of `Tensor`s. ' + 'Given type: {}'.format(type(features))) + if not linear_feature_columns and not dnn_feature_columns: + raise ValueError( + 'Either linear_feature_columns or dnn_feature_columns must be defined.') + + num_ps_replicas = config.num_ps_replicas if config else 0 + input_layer_partitioner = input_layer_partitioner or ( + tf.compat.v1.min_max_variable_partitioner( + max_partitions=num_ps_replicas, min_slice_size=64 << 20)) + + # Build DNN Logits. + dnn_parent_scope = 'dnn' + + if not dnn_feature_columns: + dnn_logits = None + else: + dnn_optimizer = optimizers.get_optimizer_instance( + dnn_optimizer, learning_rate=_DNN_LEARNING_RATE) + _check_no_sync_replicas_optimizer(dnn_optimizer) + if not dnn_hidden_units: + raise ValueError( + 'dnn_hidden_units must be defined when dnn_feature_columns is ' + 'specified.') + dnn_partitioner = ( + tf.compat.v1.min_max_variable_partitioner( + max_partitions=num_ps_replicas)) + with tf.compat.v1.variable_scope( + dnn_parent_scope, + values=tuple(six.itervalues(features)), + partitioner=dnn_partitioner) as scope: + dnn_absolute_scope = scope.name + dnn_logit_fn = dnn.dnn_logit_fn_builder( + units=head.logits_dimension, + hidden_units=dnn_hidden_units, + feature_columns=dnn_feature_columns, + activation_fn=dnn_activation_fn, + dropout=dnn_dropout, + batch_norm=batch_norm, + input_layer_partitioner=input_layer_partitioner) + dnn_logits = dnn_logit_fn(features=features, mode=mode) + + linear_parent_scope = 'linear' + + if not linear_feature_columns: + linear_logits = None + else: + linear_optimizer = optimizers.get_optimizer_instance( + linear_optimizer, + learning_rate=_linear_learning_rate(len(linear_feature_columns))) + _check_no_sync_replicas_optimizer(linear_optimizer) + with tf.compat.v1.variable_scope( + linear_parent_scope, + values=tuple(six.itervalues(features)), + partitioner=input_layer_partitioner) as scope: + linear_absolute_scope = scope.name + logit_fn = linear.linear_logit_fn_builder( + units=head.logits_dimension, + feature_columns=linear_feature_columns, + sparse_combiner=linear_sparse_combiner) + linear_logits = logit_fn(features=features) + _add_layer_summary(linear_logits, scope.name) + + # Combine logits and build full model. + if dnn_logits is not None and linear_logits is not None: + logits = dnn_logits + linear_logits + elif dnn_logits is not None: + logits = dnn_logits + else: + logits = linear_logits + + def _train_op_fn(loss): + """Returns the op to optimize the loss.""" + train_ops = [] + global_step = tf.compat.v1.train.get_global_step() + if dnn_logits is not None: + train_ops.append( + dnn_optimizer.minimize( + loss, + var_list=tf.compat.v1.get_collection( + tf.compat.v1.GraphKeys.TRAINABLE_VARIABLES, + scope=dnn_absolute_scope))) + if linear_logits is not None: + train_ops.append( + linear_optimizer.minimize( + loss, + var_list=tf.compat.v1.get_collection( + tf.compat.v1.GraphKeys.TRAINABLE_VARIABLES, + scope=linear_absolute_scope))) + + train_op = tf.group(*train_ops) + with tf.control_dependencies([train_op]): + return tf.compat.v1.assign_add(global_step, 1).op + + return head.create_estimator_spec( + features=features, + mode=mode, + labels=labels, + train_op_fn=_train_op_fn, + logits=logits) + + +@estimator_export('estimator.DNNLinearCombinedClassifier', v1=[]) +class DNNLinearCombinedClassifierV2(estimator.EstimatorV2): + """An estimator for TensorFlow Linear and DNN joined classification models. + + Note: This estimator is also known as wide-n-deep. + + Example: + + ```python + numeric_feature = numeric_column(...) + categorical_column_a = categorical_column_with_hash_bucket(...) + categorical_column_b = categorical_column_with_hash_bucket(...) + + categorical_feature_a_x_categorical_feature_b = crossed_column(...) + categorical_feature_a_emb = embedding_column( + categorical_column=categorical_feature_a, ...) + categorical_feature_b_emb = embedding_column( + categorical_id_column=categorical_feature_b, ...) + + estimator = tf.estimator.DNNLinearCombinedClassifier( + # wide settings + linear_feature_columns=[categorical_feature_a_x_categorical_feature_b], + linear_optimizer=tf.keras.optimizers.Ftrl(...), + # deep settings + dnn_feature_columns=[ + categorical_feature_a_emb, categorical_feature_b_emb, + numeric_feature], + dnn_hidden_units=[1000, 500, 100], + dnn_optimizer=tf.keras.optimizers.Adagrad(...), + # warm-start settings + warm_start_from="/path/to/checkpoint/dir") + + # To apply L1 and L2 regularization, you can set dnn_optimizer to: + tf.compat.v1.train.ProximalAdagradOptimizer( + learning_rate=0.1, + l1_regularization_strength=0.001, + l2_regularization_strength=0.001) + # To apply learning rate decay, you can set dnn_optimizer to a callable: + lambda: tf.keras.optimizers.Adam( + learning_rate=tf.compat.v1.train.exponential_decay( + learning_rate=0.1, + global_step=tf.compat.v1.train.get_global_step(), + decay_steps=10000, + decay_rate=0.96) + # It is the same for linear_optimizer. + + # Input builders + def input_fn_train: + # Returns tf.data.Dataset of (x, y) tuple where y represents label's class + # index. + pass + def input_fn_eval: + # Returns tf.data.Dataset of (x, y) tuple where y represents label's class + # index. + pass + def input_fn_predict: + # Returns tf.data.Dataset of (x, None) tuple. + pass + estimator.train(input_fn=input_fn_train, steps=100) + metrics = estimator.evaluate(input_fn=input_fn_eval, steps=10) + predictions = estimator.predict(input_fn=input_fn_predict) + ``` + + Input of `train` and `evaluate` should have following features, + otherwise there will be a `KeyError`: + + * for each `column` in `dnn_feature_columns` + `linear_feature_columns`: + - if `column` is a `CategoricalColumn`, a feature with `key=column.name` + whose `value` is a `SparseTensor`. + - if `column` is a `WeightedCategoricalColumn`, two features: the first + with `key` the id column name, the second with `key` the weight column + name. Both features' `value` must be a `SparseTensor`. + - if `column` is a `DenseColumn`, a feature with `key=column.name` + whose `value` is a `Tensor`. + + Loss is calculated by using softmax cross entropy. + + @compatibility(eager) + Estimators can be used while eager execution is enabled. Note that `input_fn` + and all hooks are executed inside a graph context, so they have to be written + to be compatible with graph mode. Note that `input_fn` code using `tf.data` + generally works in both graph and eager modes. + @end_compatibility + """ + + def __init__(self, + model_dir=None, + linear_feature_columns=None, + linear_optimizer='Ftrl', + dnn_feature_columns=None, + dnn_optimizer='Adagrad', + dnn_hidden_units=None, + dnn_activation_fn=tf.nn.relu, + dnn_dropout=None, + n_classes=2, + weight_column=None, + label_vocabulary=None, + config=None, + warm_start_from=None, + loss_reduction=tf.losses.Reduction.SUM_OVER_BATCH_SIZE, + batch_norm=False, + linear_sparse_combiner='sum'): + """Initializes a DNNLinearCombinedClassifier instance. + + Args: + model_dir: Directory to save model parameters, graph and etc. This can + also be used to load checkpoints from the directory into a estimator to + continue training a previously saved model. + linear_feature_columns: An iterable containing all the feature columns + used by linear part of the model. All items in the set must be instances + of classes derived from `FeatureColumn`. + linear_optimizer: An instance of `tf.keras.optimizers.*` used to apply + gradients to the linear part of the model. Can also be a string (one of + 'Adagrad', 'Adam', 'Ftrl', 'RMSProp', 'SGD'), or callable. Defaults to + FTRL optimizer. + dnn_feature_columns: An iterable containing all the feature columns used + by deep part of the model. All items in the set must be instances of + classes derived from `FeatureColumn`. + dnn_optimizer: An instance of `tf.keras.optimizers.*` used to apply + gradients to the deep part of the model. Can also be a string (one of + 'Adagrad', 'Adam', 'Ftrl', 'RMSProp', 'SGD'), or callable. Defaults to + Adagrad optimizer. + dnn_hidden_units: List of hidden units per layer. All layers are fully + connected. + dnn_activation_fn: Activation function applied to each layer. If None, + will use `tf.nn.relu`. + dnn_dropout: When not None, the probability we will drop out a given + coordinate. + n_classes: Number of label classes. Defaults to 2, namely binary + classification. Must be > 1. + weight_column: A string or a `_NumericColumn` created by + `tf.feature_column.numeric_column` defining feature column representing + weights. It is used to down weight or boost examples during training. It + will be multiplied by the loss of the example. If it is a string, it is + used as a key to fetch weight tensor from the `features`. If it is a + `_NumericColumn`, raw tensor is fetched by key `weight_column.key`, then + weight_column.normalizer_fn is applied on it to get weight tensor. + label_vocabulary: A list of strings represents possible label values. If + given, labels must be string type and have any value in + `label_vocabulary`. If it is not given, that means labels are already + encoded as integer or float within [0, 1] for `n_classes=2` and encoded + as integer values in {0, 1,..., n_classes-1} for `n_classes`>2 . Also + there will be errors if vocabulary is not provided and labels are + string. + config: RunConfig object to configure the runtime settings. + warm_start_from: A string filepath to a checkpoint to warm-start from, or + a `WarmStartSettings` object to fully configure warm-starting. If the + string filepath is provided instead of a `WarmStartSettings`, then all + weights are warm-started, and it is assumed that vocabularies and Tensor + names are unchanged. + loss_reduction: One of `tf.losses.Reduction` except `NONE`. Describes how + to reduce training loss over batch. Defaults to `SUM_OVER_BATCH_SIZE`. + batch_norm: Whether to use batch normalization after each hidden layer. + linear_sparse_combiner: A string specifying how to reduce the linear model + if a categorical column is multivalent. One of "mean", "sqrtn", and + "sum" -- these are effectively different ways to do example-level + normalization, which can be useful for bag-of-words features. For more + details, see `tf.feature_column.linear_model`. + + Raises: + ValueError: If both linear_feature_columns and dnn_features_columns are + empty at the same time. + """ + self._feature_columns = _validate_feature_columns( + linear_feature_columns=linear_feature_columns, + dnn_feature_columns=dnn_feature_columns) + + head = head_utils.binary_or_multi_class_head( + n_classes, + weight_column=weight_column, + label_vocabulary=label_vocabulary, + loss_reduction=loss_reduction) + estimator._canned_estimator_api_gauge.get_cell('Classifier').set( # pylint: disable=protected-access + 'DNNLinearCombined') + + def _model_fn(features, labels, mode, config): + """Call the _dnn_linear_combined_model_fn.""" + return _dnn_linear_combined_model_fn_v2( + features=features, + labels=labels, + mode=mode, + head=head, + linear_feature_columns=linear_feature_columns, + linear_optimizer=linear_optimizer, + dnn_feature_columns=dnn_feature_columns, + dnn_optimizer=dnn_optimizer, + dnn_hidden_units=dnn_hidden_units, + dnn_activation_fn=dnn_activation_fn, + dnn_dropout=dnn_dropout, + config=config, + batch_norm=batch_norm, + linear_sparse_combiner=linear_sparse_combiner, + loss_reduction=loss_reduction) + + super(DNNLinearCombinedClassifierV2, self).__init__( + model_fn=_model_fn, + model_dir=model_dir, + config=config, + warm_start_from=warm_start_from) + + +@estimator_export(v1=['estimator.DNNLinearCombinedClassifier']) # pylint: disable=missing-docstring +class DNNLinearCombinedClassifier(estimator.Estimator): + __doc__ = DNNLinearCombinedClassifierV2.__doc__.replace( + 'SUM_OVER_BATCH_SIZE', 'SUM') + + def __init__(self, + model_dir=None, + linear_feature_columns=None, + linear_optimizer='Ftrl', + dnn_feature_columns=None, + dnn_optimizer='Adagrad', + dnn_hidden_units=None, + dnn_activation_fn=tf.nn.relu, + dnn_dropout=None, + n_classes=2, + weight_column=None, + label_vocabulary=None, + input_layer_partitioner=None, + config=None, + warm_start_from=None, + loss_reduction=tf.compat.v1.losses.Reduction.SUM, + batch_norm=False, + linear_sparse_combiner='sum'): + self._feature_columns = _validate_feature_columns( + linear_feature_columns=linear_feature_columns, + dnn_feature_columns=dnn_feature_columns) + + head = head_lib._binary_logistic_or_multi_class_head( # pylint: disable=protected-access + n_classes, weight_column, label_vocabulary, loss_reduction) + estimator._canned_estimator_api_gauge.get_cell('Classifier').set( + 'DNNLinearCombined') # pylint: disable=protected-access + + def _model_fn(features, labels, mode, config): + """Call the _dnn_linear_combined_model_fn.""" + return _dnn_linear_combined_model_fn( + features=features, + labels=labels, + mode=mode, + head=head, + linear_feature_columns=linear_feature_columns, + linear_optimizer=linear_optimizer, + dnn_feature_columns=dnn_feature_columns, + dnn_optimizer=dnn_optimizer, + dnn_hidden_units=dnn_hidden_units, + dnn_activation_fn=dnn_activation_fn, + dnn_dropout=dnn_dropout, + input_layer_partitioner=input_layer_partitioner, + config=config, + batch_norm=batch_norm, + linear_sparse_combiner=linear_sparse_combiner) + + super(DNNLinearCombinedClassifier, self).__init__( + model_fn=_model_fn, + model_dir=model_dir, + config=config, + warm_start_from=warm_start_from) + + +def _init_dnn_linear_combined_estimator(head, linear_feature_columns, + linear_optimizer, dnn_feature_columns, + dnn_optimizer, dnn_hidden_units, + dnn_activation_fn, dnn_dropout, + input_layer_partitioner, + linear_sparse_combiner): + """Helper function for the initialization of DNNLinearCombinedEstimator.""" + linear_feature_columns = linear_feature_columns or [] + dnn_feature_columns = dnn_feature_columns or [] + feature_columns = (list(linear_feature_columns) + list(dnn_feature_columns)) + if not feature_columns: + raise ValueError('Either linear_feature_columns or dnn_feature_columns ' + 'must be defined.') + + def _model_fn(features, labels, mode, config): + """Call the _dnn_linear_combined_model_fn.""" + return _dnn_linear_combined_model_fn( + features=features, + labels=labels, + mode=mode, + head=head, + linear_feature_columns=linear_feature_columns, + linear_optimizer=linear_optimizer, + dnn_feature_columns=dnn_feature_columns, + dnn_optimizer=dnn_optimizer, + dnn_hidden_units=dnn_hidden_units, + dnn_activation_fn=dnn_activation_fn, + dnn_dropout=dnn_dropout, + input_layer_partitioner=input_layer_partitioner, + config=config, + linear_sparse_combiner=linear_sparse_combiner) + + return feature_columns, _model_fn + + +@estimator_export('estimator.DNNLinearCombinedEstimator', v1=[]) +class DNNLinearCombinedEstimatorV2(estimator.EstimatorV2): + """An estimator for TensorFlow Linear and DNN joined models with custom head. + + Note: This estimator is also known as wide-n-deep. + + Example: + + ```python + numeric_feature = numeric_column(...) + categorical_column_a = categorical_column_with_hash_bucket(...) + categorical_column_b = categorical_column_with_hash_bucket(...) + + categorical_feature_a_x_categorical_feature_b = crossed_column(...) + categorical_feature_a_emb = embedding_column( + categorical_column=categorical_feature_a, ...) + categorical_feature_b_emb = embedding_column( + categorical_column=categorical_feature_b, ...) + + estimator = tf.estimator.DNNLinearCombinedEstimator( + head=tf.estimator.MultiLabelHead(n_classes=3), + # wide settings + linear_feature_columns=[categorical_feature_a_x_categorical_feature_b], + linear_optimizer=tf.keras.optimizers.Ftrl(...), + # deep settings + dnn_feature_columns=[ + categorical_feature_a_emb, categorical_feature_b_emb, + numeric_feature], + dnn_hidden_units=[1000, 500, 100], + dnn_optimizer=tf.keras.optimizers.Adagrad(...)) + + # To apply L1 and L2 regularization, you can set dnn_optimizer to: + tf.compat.v1.train.ProximalAdagradOptimizer( + learning_rate=0.1, + l1_regularization_strength=0.001, + l2_regularization_strength=0.001) + # To apply learning rate decay, you can set dnn_optimizer to a callable: + lambda: tf.keras.optimizers.Adam( + learning_rate=tf.compat.v1.train.exponential_decay( + learning_rate=0.1, + global_step=tf.compat.v1.train.get_global_step(), + decay_steps=10000, + decay_rate=0.96) + # It is the same for linear_optimizer. + + # Input builders + def input_fn_train: + # Returns tf.data.Dataset of (x, y) tuple where y represents label's class + # index. + pass + def input_fn_eval: + # Returns tf.data.Dataset of (x, y) tuple where y represents label's class + # index. + pass + def input_fn_predict: + # Returns tf.data.Dataset of (x, None) tuple. + pass + estimator.train(input_fn=input_fn_train, steps=100) + metrics = estimator.evaluate(input_fn=input_fn_eval, steps=10) + predictions = estimator.predict(input_fn=input_fn_predict) + ``` + + Input of `train` and `evaluate` should have following features, + otherwise there will be a `KeyError`: + + * for each `column` in `dnn_feature_columns` + `linear_feature_columns`: + - if `column` is a `CategoricalColumn`, a feature with `key=column.name` + whose `value` is a `SparseTensor`. + - if `column` is a `WeightedCategoricalColumn`, two features: the first + with `key` the id column name, the second with `key` the weight column + name. Both features' `value` must be a `SparseTensor`. + - if `column` is a `DenseColumn`, a feature with `key=column.name` + whose `value` is a `Tensor`. + + Loss is calculated by using mean squared error. + + @compatibility(eager) + Estimators can be used while eager execution is enabled. Note that `input_fn` + and all hooks are executed inside a graph context, so they have to be written + to be compatible with graph mode. Note that `input_fn` code using `tf.data` + generally works in both graph and eager modes. + @end_compatibility + """ + + def __init__(self, + head, + model_dir=None, + linear_feature_columns=None, + linear_optimizer='Ftrl', + dnn_feature_columns=None, + dnn_optimizer='Adagrad', + dnn_hidden_units=None, + dnn_activation_fn=tf.nn.relu, + dnn_dropout=None, + config=None, + batch_norm=False, + linear_sparse_combiner='sum'): + """Initializes a DNNLinearCombinedEstimator instance. + + Args: + head: A `Head` instance constructed with a method such as + `tf.estimator.MultiLabelHead`. + model_dir: Directory to save model parameters, graph and etc. This can + also be used to load checkpoints from the directory into an estimator to + continue training a previously saved model. + linear_feature_columns: An iterable containing all the feature columns + used by linear part of the model. All items in the set must be instances + of classes derived from `FeatureColumn`. + linear_optimizer: An instance of `tf.keras.optimizers.*` used to apply + gradients to the linear part of the model. Can also be a string (one of + 'Adagrad', 'Adam', 'Ftrl', 'RMSProp', 'SGD'), or callable. Defaults to + FTRL optimizer. + dnn_feature_columns: An iterable containing all the feature columns used + by deep part of the model. All items in the set must be instances of + classes derived from `FeatureColumn`. + dnn_optimizer: An instance of `tf.keras.optimizers.*` used to apply + gradients to the deep part of the model. Can also be a string (one of + 'Adagrad', 'Adam', 'Ftrl', 'RMSProp', 'SGD'), or callable. Defaults to + Adagrad optimizer. + dnn_hidden_units: List of hidden units per layer. All layers are fully + connected. + dnn_activation_fn: Activation function applied to each layer. If None, + will use `tf.nn.relu`. + dnn_dropout: When not None, the probability we will drop out a given + coordinate. + config: RunConfig object to configure the runtime settings. + batch_norm: Whether to use batch normalization after each hidden layer. + linear_sparse_combiner: A string specifying how to reduce the linear model + if a categorical column is multivalent. One of "mean", "sqrtn", and + "sum" -- these are effectively different ways to do example-level + normalization, which can be useful for bag-of-words features. For more + details, see `tf.feature_column.linear_model`. + + Raises: + ValueError: If both linear_feature_columns and dnn_features_columns are + empty at the same time. + """ + self._feature_columns = _validate_feature_columns( + linear_feature_columns=linear_feature_columns, + dnn_feature_columns=dnn_feature_columns) + estimator._canned_estimator_api_gauge.get_cell('Estimator').set( + 'DNNLinearCombined') # pylint: disable=protected-access + + def _model_fn(features, labels, mode, config): + """Call the _dnn_linear_combined_model_fn.""" + return _dnn_linear_combined_model_fn_v2( + features=features, + labels=labels, + mode=mode, + head=head, + linear_feature_columns=linear_feature_columns, + linear_optimizer=linear_optimizer, + dnn_feature_columns=dnn_feature_columns, + dnn_optimizer=dnn_optimizer, + dnn_hidden_units=dnn_hidden_units, + dnn_activation_fn=dnn_activation_fn, + dnn_dropout=dnn_dropout, + config=config, + batch_norm=batch_norm, + linear_sparse_combiner=linear_sparse_combiner) + + super(DNNLinearCombinedEstimatorV2, self).__init__( + model_fn=_model_fn, model_dir=model_dir, config=config) + + +@estimator_export(v1=['estimator.DNNLinearCombinedEstimator']) # pylint: disable=missing-docstring +class DNNLinearCombinedEstimator(estimator.Estimator): + __doc__ = DNNLinearCombinedEstimatorV2.__doc__ + + def __init__(self, + head, + model_dir=None, + linear_feature_columns=None, + linear_optimizer='Ftrl', + dnn_feature_columns=None, + dnn_optimizer='Adagrad', + dnn_hidden_units=None, + dnn_activation_fn=tf.nn.relu, + dnn_dropout=None, + input_layer_partitioner=None, + config=None, + batch_norm=False, + linear_sparse_combiner='sum'): + self._feature_columns = _validate_feature_columns( + linear_feature_columns=linear_feature_columns, + dnn_feature_columns=dnn_feature_columns) + estimator._canned_estimator_api_gauge.get_cell('Estimator').set( + 'DNNLinearCombined') # pylint: disable=protected-access + + def _model_fn(features, labels, mode, config): + """Call the _dnn_linear_combined_model_fn.""" + return _dnn_linear_combined_model_fn( + features=features, + labels=labels, + mode=mode, + head=head, + linear_feature_columns=linear_feature_columns, + linear_optimizer=linear_optimizer, + dnn_feature_columns=dnn_feature_columns, + dnn_optimizer=dnn_optimizer, + dnn_hidden_units=dnn_hidden_units, + dnn_activation_fn=dnn_activation_fn, + dnn_dropout=dnn_dropout, + input_layer_partitioner=input_layer_partitioner, + config=config, + batch_norm=batch_norm, + linear_sparse_combiner=linear_sparse_combiner) + + super(DNNLinearCombinedEstimator, self).__init__( + model_fn=_model_fn, model_dir=model_dir, config=config) + + +@estimator_export('estimator.DNNLinearCombinedRegressor', v1=[]) +class DNNLinearCombinedRegressorV2(estimator.EstimatorV2): + """An estimator for TensorFlow Linear and DNN joined models for regression. + + Note: This estimator is also known as wide-n-deep. + + Example: + + ```python + numeric_feature = numeric_column(...) + categorical_column_a = categorical_column_with_hash_bucket(...) + categorical_column_b = categorical_column_with_hash_bucket(...) + + categorical_feature_a_x_categorical_feature_b = crossed_column(...) + categorical_feature_a_emb = embedding_column( + categorical_column=categorical_feature_a, ...) + categorical_feature_b_emb = embedding_column( + categorical_column=categorical_feature_b, ...) + + estimator = tf.estimator.DNNLinearCombinedRegressor( + # wide settings + linear_feature_columns=[categorical_feature_a_x_categorical_feature_b], + linear_optimizer=tf.keras.optimizers.Ftrl(...), + # deep settings + dnn_feature_columns=[ + categorical_feature_a_emb, categorical_feature_b_emb, + numeric_feature], + dnn_hidden_units=[1000, 500, 100], + dnn_optimizer=tf.keras.optimizers.Adagrad(...), + # warm-start settings + warm_start_from="/path/to/checkpoint/dir") + + # To apply L1 and L2 regularization, you can set dnn_optimizer to: + tf.compat.v1.train.ProximalAdagradOptimizer( + learning_rate=0.1, + l1_regularization_strength=0.001, + l2_regularization_strength=0.001) + # To apply learning rate decay, you can set dnn_optimizer to a callable: + lambda: tf.keras.optimizers.Adam( + learning_rate=tf.compat.v1.train.exponential_decay( + learning_rate=0.1, + global_step=tf.compat.v1.train.get_global_step(), + decay_steps=10000, + decay_rate=0.96) + # It is the same for linear_optimizer. + + # Input builders + def input_fn_train: + # Returns tf.data.Dataset of (x, y) tuple where y represents label's class + # index. + pass + def input_fn_eval: + # Returns tf.data.Dataset of (x, y) tuple where y represents label's class + # index. + pass + def input_fn_predict: + # Returns tf.data.Dataset of (x, None) tuple. + pass + estimator.train(input_fn=input_fn_train, steps=100) + metrics = estimator.evaluate(input_fn=input_fn_eval, steps=10) + predictions = estimator.predict(input_fn=input_fn_predict) + ``` + + Input of `train` and `evaluate` should have following features, + otherwise there will be a `KeyError`: + + * for each `column` in `dnn_feature_columns` + `linear_feature_columns`: + - if `column` is a `CategoricalColumn`, a feature with `key=column.name` + whose `value` is a `SparseTensor`. + - if `column` is a `WeightedCategoricalColumn`, two features: the first + with `key` the id column name, the second with `key` the weight column + name. Both features' `value` must be a `SparseTensor`. + - if `column` is a `DenseColumn`, a feature with `key=column.name` + whose `value` is a `Tensor`. + + Loss is calculated by using mean squared error. + + @compatibility(eager) + Estimators can be used while eager execution is enabled. Note that `input_fn` + and all hooks are executed inside a graph context, so they have to be written + to be compatible with graph mode. Note that `input_fn` code using `tf.data` + generally works in both graph and eager modes. + @end_compatibility + """ + + def __init__(self, + model_dir=None, + linear_feature_columns=None, + linear_optimizer='Ftrl', + dnn_feature_columns=None, + dnn_optimizer='Adagrad', + dnn_hidden_units=None, + dnn_activation_fn=tf.nn.relu, + dnn_dropout=None, + label_dimension=1, + weight_column=None, + config=None, + warm_start_from=None, + loss_reduction=tf.losses.Reduction.SUM_OVER_BATCH_SIZE, + batch_norm=False, + linear_sparse_combiner='sum'): + """Initializes a DNNLinearCombinedRegressor instance. + + Args: + model_dir: Directory to save model parameters, graph and etc. This can + also be used to load checkpoints from the directory into a estimator to + continue training a previously saved model. + linear_feature_columns: An iterable containing all the feature columns + used by linear part of the model. All items in the set must be instances + of classes derived from `FeatureColumn`. + linear_optimizer: An instance of `tf.keras.optimizers.*` used to apply + gradients to the linear part of the model. Can also be a string (one of + 'Adagrad', 'Adam', 'Ftrl', 'RMSProp', 'SGD'), or callable. Defaults to + FTRL optimizer. + dnn_feature_columns: An iterable containing all the feature columns used + by deep part of the model. All items in the set must be instances of + classes derived from `FeatureColumn`. + dnn_optimizer: An instance of `tf.keras.optimizers.*` used to apply + gradients to the deep part of the model. Can also be a string (one of + 'Adagrad', 'Adam', 'Ftrl', 'RMSProp', 'SGD'), or callable. Defaults to + Adagrad optimizer. + dnn_hidden_units: List of hidden units per layer. All layers are fully + connected. + dnn_activation_fn: Activation function applied to each layer. If None, + will use `tf.nn.relu`. + dnn_dropout: When not None, the probability we will drop out a given + coordinate. + label_dimension: Number of regression targets per example. This is the + size of the last dimension of the labels and logits `Tensor` objects + (typically, these have shape `[batch_size, label_dimension]`). + weight_column: A string or a `NumericColumn` created by + `tf.feature_column.numeric_column` defining feature column representing + weights. It is used to down weight or boost examples during training. It + will be multiplied by the loss of the example. If it is a string, it is + used as a key to fetch weight tensor from the `features`. If it is a + `_NumericColumn`, raw tensor is fetched by key `weight_column.key`, then + weight_column.normalizer_fn is applied on it to get weight tensor. + config: RunConfig object to configure the runtime settings. + warm_start_from: A string filepath to a checkpoint to warm-start from, or + a `WarmStartSettings` object to fully configure warm-starting. If the + string filepath is provided instead of a `WarmStartSettings`, then all + weights are warm-started, and it is assumed that vocabularies and Tensor + names are unchanged. + loss_reduction: One of `tf.losses.Reduction` except `NONE`. Describes how + to reduce training loss over batch. Defaults to `SUM_OVER_BATCH_SIZE`. + batch_norm: Whether to use batch normalization after each hidden layer. + linear_sparse_combiner: A string specifying how to reduce the linear model + if a categorical column is multivalent. One of "mean", "sqrtn", and + "sum" -- these are effectively different ways to do example-level + normalization, which can be useful for bag-of-words features. For more + details, see `tf.feature_column.linear_model`. + + Raises: + ValueError: If both linear_feature_columns and dnn_features_columns are + empty at the same time. + """ + self._feature_columns = _validate_feature_columns( + linear_feature_columns=linear_feature_columns, + dnn_feature_columns=dnn_feature_columns) + + head = regression_head.RegressionHead( + label_dimension=label_dimension, + weight_column=weight_column, + loss_reduction=loss_reduction) + estimator._canned_estimator_api_gauge.get_cell('Regressor').set( + 'DNNLinearCombined') # pylint: disable=protected-access + + def _model_fn(features, labels, mode, config): + """Call the _dnn_linear_combined_model_fn.""" + return _dnn_linear_combined_model_fn_v2( + features=features, + labels=labels, + mode=mode, + head=head, + linear_feature_columns=linear_feature_columns, + linear_optimizer=linear_optimizer, + dnn_feature_columns=dnn_feature_columns, + dnn_optimizer=dnn_optimizer, + dnn_hidden_units=dnn_hidden_units, + dnn_activation_fn=dnn_activation_fn, + dnn_dropout=dnn_dropout, + config=config, + batch_norm=batch_norm, + linear_sparse_combiner=linear_sparse_combiner) + + super(DNNLinearCombinedRegressorV2, self).__init__( + model_fn=_model_fn, + model_dir=model_dir, + config=config, + warm_start_from=warm_start_from) + + +@estimator_export(v1=['estimator.DNNLinearCombinedRegressor']) # pylint: disable=missing-docstring +class DNNLinearCombinedRegressor(estimator.Estimator): + __doc__ = DNNLinearCombinedRegressorV2.__doc__.replace( + 'SUM_OVER_BATCH_SIZE', 'SUM') + + def __init__(self, + model_dir=None, + linear_feature_columns=None, + linear_optimizer='Ftrl', + dnn_feature_columns=None, + dnn_optimizer='Adagrad', + dnn_hidden_units=None, + dnn_activation_fn=tf.nn.relu, + dnn_dropout=None, + label_dimension=1, + weight_column=None, + input_layer_partitioner=None, + config=None, + warm_start_from=None, + loss_reduction=tf.compat.v1.losses.Reduction.SUM, + batch_norm=False, + linear_sparse_combiner='sum'): + self._feature_columns = _validate_feature_columns( + linear_feature_columns=linear_feature_columns, + dnn_feature_columns=dnn_feature_columns) + estimator._canned_estimator_api_gauge.get_cell('Regressor').set( + 'DNNLinearCombined') # pylint: disable=protected-access + + head = head_lib._regression_head( # pylint: disable=protected-access + label_dimension=label_dimension, + weight_column=weight_column, + loss_reduction=loss_reduction) + + def _model_fn(features, labels, mode, config): + """Call the _dnn_linear_combined_model_fn.""" + return _dnn_linear_combined_model_fn( + features=features, + labels=labels, + mode=mode, + head=head, + linear_feature_columns=linear_feature_columns, + linear_optimizer=linear_optimizer, + dnn_feature_columns=dnn_feature_columns, + dnn_optimizer=dnn_optimizer, + dnn_hidden_units=dnn_hidden_units, + dnn_activation_fn=dnn_activation_fn, + dnn_dropout=dnn_dropout, + input_layer_partitioner=input_layer_partitioner, + config=config, + batch_norm=batch_norm, + linear_sparse_combiner=linear_sparse_combiner) + + super(DNNLinearCombinedRegressor, self).__init__( + model_fn=_model_fn, + model_dir=model_dir, + config=config, + warm_start_from=warm_start_from) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/dnn_testing_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/dnn_testing_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..7e3b0436c5d07b445a771c442e776449ad1ebf40 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/dnn_testing_utils.py @@ -0,0 +1,2138 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Utils to be used in testing DNN estimators.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import os +import shutil +import tempfile + +import numpy as np +import six +import tensorflow as tf +from tensorflow.python.feature_column import feature_column_v2 +from tensorflow.python.framework import ops +from tensorflow_estimator.python.estimator import estimator +from tensorflow_estimator.python.estimator import model_fn +from tensorflow_estimator.python.estimator.canned import metric_keys +from tensorflow_estimator.python.estimator.canned import prediction_keys +from tensorflow_estimator.python.estimator.head import base_head +from tensorflow_estimator.python.estimator.inputs import numpy_io +from tensorflow_estimator.python.estimator.mode_keys import ModeKeys + +# pylint rules which are disabled by default for test files. +# pylint: disable=invalid-name,protected-access,missing-docstring + +# Names of variables created by model. +LEARNING_RATE_NAME = 'dnn/regression_head/dnn/learning_rate' +HIDDEN_WEIGHTS_NAME_PATTERN = 'dnn/hiddenlayer_%d/kernel' +HIDDEN_BIASES_NAME_PATTERN = 'dnn/hiddenlayer_%d/bias' +BATCH_NORM_BETA_NAME_PATTERN = 'dnn/hiddenlayer_%d/batchnorm_%d/beta' +BATCH_NORM_GAMMA_NAME_PATTERN = 'dnn/hiddenlayer_%d/batchnorm_%d/gamma' +BATCH_NORM_MEAN_NAME_PATTERN = 'dnn/hiddenlayer_%d/batchnorm_%d/moving_mean' +BATCH_NORM_VARIANCE_NAME_PATTERN = ( + 'dnn/hiddenlayer_%d/batchnorm_%d/moving_variance') +LOGITS_WEIGHTS_NAME = 'dnn/logits/kernel' +LOGITS_BIASES_NAME = 'dnn/logits/bias' +OCCUPATION_EMBEDDING_NAME = ('dnn/input_from_feature_columns/input_layer/' + 'occupation_embedding/embedding_weights') +CITY_EMBEDDING_NAME = ('dnn/input_from_feature_columns/input_layer/' + 'city_embedding/embedding_weights') + + +def assert_close(expected, actual, rtol=1e-04, message='', name='assert_close'): + with ops.name_scope(name, 'assert_close', (expected, actual, rtol)) as scope: + expected = ops.convert_to_tensor(expected, name='expected') + actual = ops.convert_to_tensor(actual, name='actual') + rdiff = tf.math.abs((expected - actual) / expected, 'diff') + rtol = ops.convert_to_tensor(rtol, name='rtol') + return tf.compat.v1.debugging.assert_less( + rdiff, + rtol, + data=('Condition expected =~ actual did not hold element-wise:' + 'expected = ', expected, 'actual = ', actual, 'rdiff = ', rdiff, + 'rtol = ', rtol,), + summarize=expected.get_shape().num_elements(), + name=scope) + + +def create_checkpoint(weights_and_biases, + global_step, + model_dir, + batch_norm_vars=None): + """Create checkpoint file with provided model weights. + + Args: + weights_and_biases: Iterable of tuples of weight and bias values. + global_step: Initial global step to save in checkpoint. + model_dir: Directory into which checkpoint is saved. + batch_norm_vars: Variables used for batch normalization. + """ + weights, biases = zip(*weights_and_biases) + if batch_norm_vars: + assert len(batch_norm_vars) == len(weights_and_biases) - 1 + (bn_betas, bn_gammas, bn_means, bn_variances) = zip(*batch_norm_vars) + model_weights = {} + + # Hidden layer weights. + for i in range(0, len(weights) - 1): + model_weights[HIDDEN_WEIGHTS_NAME_PATTERN % i] = weights[i] + model_weights[HIDDEN_BIASES_NAME_PATTERN % i] = biases[i] + if batch_norm_vars: + model_weights[BATCH_NORM_BETA_NAME_PATTERN % (i, i)] = bn_betas[i] + model_weights[BATCH_NORM_GAMMA_NAME_PATTERN % (i, i)] = bn_gammas[i] + model_weights[BATCH_NORM_MEAN_NAME_PATTERN % (i, i)] = bn_means[i] + model_weights[BATCH_NORM_VARIANCE_NAME_PATTERN % (i, i)] = bn_variances[i] + + # Output layer weights. + model_weights[LOGITS_WEIGHTS_NAME] = weights[-1] + model_weights[LOGITS_BIASES_NAME] = biases[-1] + + with tf.Graph().as_default(): + # Create model variables. + for k, v in six.iteritems(model_weights): + tf.Variable(v, name=k, dtype=tf.dtypes.float32) + + # Create non-model variables. + global_step_var = tf.compat.v1.train.create_global_step() + + # Initialize vars and save checkpoint. + with tf.compat.v1.Session() as sess: + tf.compat.v1.initializers.global_variables().run() + global_step_var.assign(global_step).eval() + tf.compat.v1.train.Saver().save(sess, + os.path.join(model_dir, 'model.ckpt')) + + +def mock_head(testcase, hidden_units, logits_dimension, expected_logits): + """Returns a mock head that validates logits values and variable names.""" + hidden_weights_names = [(HIDDEN_WEIGHTS_NAME_PATTERN + ':0') % i + for i in range(len(hidden_units))] + hidden_biases_names = [ + (HIDDEN_BIASES_NAME_PATTERN + ':0') % i for i in range(len(hidden_units)) + ] + expected_var_names = ( + hidden_weights_names + hidden_biases_names + + [LOGITS_WEIGHTS_NAME + ':0', LOGITS_BIASES_NAME + ':0']) + + def _create_tpu_estimator_spec(features, + mode, + logits, + labels, + trainable_variables=None, + train_op_fn=None, + optimizer=None, + update_ops=None): + del features, labels # Not used. + trainable_vars = tf.compat.v1.get_collection( + tf.compat.v1.GraphKeys.TRAINABLE_VARIABLES) + testcase.assertItemsEqual(expected_var_names, + [var.name for var in trainable_vars]) + loss = tf.constant(1.) + assert_logits = assert_close( + expected_logits, logits, message='Failed for mode={}. '.format(mode)) + with tf.control_dependencies([assert_logits]): + if mode == ModeKeys.TRAIN: + if train_op_fn is not None: + train_op = train_op_fn(loss) + elif optimizer is not None: + train_op = optimizer.get_updates(loss, trainable_variables) + if update_ops is not None: + train_op = tf.group(train_op, *update_ops) + return model_fn._TPUEstimatorSpec( + mode=mode, loss=loss, train_op=train_op) + elif mode == ModeKeys.EVAL: + return model_fn._TPUEstimatorSpec(mode=mode, loss=tf.identity(loss)) + elif mode == ModeKeys.PREDICT: + return model_fn._TPUEstimatorSpec( + mode=mode, predictions={'logits': tf.identity(logits)}) + else: + testcase.fail('Invalid mode: {}'.format(mode)) + + def _create_estimator_spec(features, + mode, + logits, + labels, + trainable_variables=None, + train_op_fn=None, + optimizer=None, + update_ops=None): + tpu_spec = _create_tpu_estimator_spec(features, mode, logits, labels, + trainable_variables, train_op_fn, + optimizer, update_ops) + return tpu_spec.as_estimator_spec() + + head = tf.compat.v1.test.mock.NonCallableMagicMock(spec=base_head.Head) + head.logits_dimension = logits_dimension + head._create_tpu_estimator_spec = tf.compat.v1.test.mock.MagicMock( + wraps=_create_tpu_estimator_spec) + head.create_estimator_spec = tf.compat.v1.test.mock.MagicMock( + wraps=_create_estimator_spec) + + return head + + +def mock_optimizer(testcase, hidden_units, expected_loss=None): + """Creates a mock optimizer to test the train method. + + Args: + testcase: A TestCase instance. + hidden_units: Iterable of integer sizes for the hidden layers. + expected_loss: If given, will assert the loss value. + + Returns: + A mock Optimizer. + """ + hidden_weights_names = [(HIDDEN_WEIGHTS_NAME_PATTERN + ':0') % i + for i in range(len(hidden_units))] + hidden_biases_names = [ + (HIDDEN_BIASES_NAME_PATTERN + ':0') % i for i in range(len(hidden_units)) + ] + expected_var_names = ( + hidden_weights_names + hidden_biases_names + + [LOGITS_WEIGHTS_NAME + ':0', LOGITS_BIASES_NAME + ':0']) + + class _Optimizer(tf.keras.optimizers.legacy.Optimizer): + + def get_updates(self, loss, params): + trainable_vars = params + testcase.assertItemsEqual(expected_var_names, + [var.name for var in trainable_vars]) + + # Verify loss. We can't check the value directly, so we add an assert op. + testcase.assertEquals(0, loss.shape.ndims) + if expected_loss is None: + if self.iterations is not None: + return [self.iterations.assign_add(1).op] + return [tf.no_op()] + assert_loss = assert_close( + tf.cast(expected_loss, name='expected', dtype=tf.dtypes.float32), + loss, + name='assert_loss') + with tf.control_dependencies((assert_loss,)): + if self.iterations is not None: + return [self.iterations.assign_add(1).op] + return [tf.no_op()] + + def get_config(self): + config = super(_Optimizer, self).get_config() + return config + + optimizer = _Optimizer(name='my_optimizer') + + return optimizer + + +class BaseDNNModelFnTest(object): + """Tests that _dnn_model_fn passes expected logits to mock head.""" + + def __init__(self, dnn_model_fn, fc_impl=feature_column_v2): + self._dnn_model_fn = dnn_model_fn + self._fc_impl = fc_impl + + def setUp(self): + self._model_dir = tempfile.mkdtemp() + + def tearDown(self): + if self._model_dir: + tf.compat.v1.summary.FileWriterCache.clear() + shutil.rmtree(self._model_dir) + + def _test_logits(self, mode, hidden_units, logits_dimension, inputs, + expected_logits): + """Tests that the expected logits are passed to mock head.""" + with tf.Graph().as_default(): + tf.compat.v1.train.create_global_step() + head = mock_head( + self, + hidden_units=hidden_units, + logits_dimension=logits_dimension, + expected_logits=expected_logits) + estimator_spec = self._dnn_model_fn( + features={'age': tf.constant(inputs)}, + labels=tf.constant([[1]]), + mode=mode, + head=head, + hidden_units=hidden_units, + feature_columns=[ + self._fc_impl.numeric_column( + 'age', shape=np.array(inputs).shape[1:]) + ], + optimizer=mock_optimizer(self, hidden_units)) + with tf.compat.v1.train.MonitoredTrainingSession( + checkpoint_dir=self._model_dir) as sess: + if mode == ModeKeys.TRAIN: + sess.run(estimator_spec.train_op) + elif mode == ModeKeys.EVAL: + sess.run(estimator_spec.loss) + elif mode == ModeKeys.PREDICT: + sess.run(estimator_spec.predictions) + else: + self.fail('Invalid mode: {}'.format(mode)) + + def test_one_dim_logits(self): + """Tests one-dimensional logits. + + input_layer = [[10]] + hidden_layer_0 = [[relu(0.6*10 +0.1), relu(0.5*10 -0.1)]] = [[6.1, 4.9]] + hidden_layer_1 = [[relu(1*6.1 -0.8*4.9 +0.2), relu(0.8*6.1 -1*4.9 -0.1)]] + = [[relu(2.38), relu(-0.12)]] = [[2.38, 0]] + logits = [[-1*2.38 +1*0 +0.3]] = [[-2.08]] + """ + base_global_step = 100 + create_checkpoint(( + ([[.6, .5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1.], [1.]], [.3]), + ), base_global_step, self._model_dir) + + for mode in [ModeKeys.TRAIN, ModeKeys.EVAL, ModeKeys.PREDICT]: + self._test_logits( + mode, + hidden_units=(2, 2), + logits_dimension=1, + inputs=[[10.]], + expected_logits=[[-2.08]]) + + def test_multi_dim_logits(self): + """Tests multi-dimensional logits. + + input_layer = [[10]] + hidden_layer_0 = [[relu(0.6*10 +0.1), relu(0.5*10 -0.1)]] = [[6.1, 4.9]] + hidden_layer_1 = [[relu(1*6.1 -0.8*4.9 +0.2), relu(0.8*6.1 -1*4.9 -0.1)]] + = [[relu(2.38), relu(-0.12)]] = [[2.38, 0]] + logits = [[-1*2.38 +0.3, 1*2.38 -0.3, 0.5*2.38]] + = [[-2.08, 2.08, 1.19]] + """ + base_global_step = 100 + create_checkpoint(( + ([[.6, .5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1., 1., .5], [-1., 1., .5]], [.3, -.3, .0]), + ), base_global_step, self._model_dir) + + for mode in [ModeKeys.TRAIN, ModeKeys.EVAL, ModeKeys.PREDICT]: + self._test_logits( + mode, + hidden_units=(2, 2), + logits_dimension=3, + inputs=[[10.]], + expected_logits=[[-2.08, 2.08, 1.19]]) + + def test_multi_example_multi_dim_logits(self): + """Tests multiple examples and multi-dimensional logits. + + input_layer = [[10], [5]] + hidden_layer_0 = [[relu(0.6*10 +0.1), relu(0.5*10 -0.1)], + [relu(0.6*5 +0.1), relu(0.5*5 -0.1)]] + = [[6.1, 4.9], [3.1, 2.4]] + hidden_layer_1 = [[relu(1*6.1 -0.8*4.9 +0.2), relu(0.8*6.1 -1*4.9 -0.1)], + [relu(1*3.1 -0.8*2.4 +0.2), relu(0.8*3.1 -1*2.4 -0.1)]] + = [[2.38, 0], [1.38, 0]] + logits = [[-1*2.38 +0.3, 1*2.38 -0.3, 0.5*2.38], + [-1*1.38 +0.3, 1*1.38 -0.3, 0.5*1.38]] + = [[-2.08, 2.08, 1.19], [-1.08, 1.08, 0.69]] + """ + base_global_step = 100 + create_checkpoint(( + ([[.6, .5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1., 1., .5], [-1., 1., .5]], [.3, -.3, .0]), + ), base_global_step, self._model_dir) + + for mode in [ModeKeys.TRAIN, ModeKeys.EVAL, ModeKeys.PREDICT]: + self._test_logits( + mode, + hidden_units=(2, 2), + logits_dimension=3, + inputs=[[10.], [5.]], + expected_logits=[[-2.08, 2.08, 1.19], [-1.08, 1.08, .69]]) + + def test_multi_dim_input_one_dim_logits(self): + """Tests multi-dimensional inputs and one-dimensional logits. + + input_layer = [[10, 8]] + hidden_layer_0 = [[relu(0.6*10 -0.6*8 +0.1), relu(0.5*10 -0.5*8 -0.1)]] + = [[1.3, 0.9]] + hidden_layer_1 = [[relu(1*1.3 -0.8*0.9 + 0.2), relu(0.8*1.3 -1*0.9 -0.2)]] + = [[0.78, relu(-0.06)]] = [[0.78, 0]] + logits = [[-1*0.78 +1*0 +0.3]] = [[-0.48]] + """ + base_global_step = 100 + create_checkpoint(( + ([[.6, .5], [-.6, -.5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1.], [1.]], [.3]), + ), base_global_step, self._model_dir) + + for mode in [ModeKeys.TRAIN, ModeKeys.EVAL, ModeKeys.PREDICT]: + self._test_logits( + mode, + hidden_units=(2, 2), + logits_dimension=1, + inputs=[[10., 8.]], + expected_logits=[[-0.48]]) + + def test_multi_dim_input_multi_dim_logits(self): + """Tests multi-dimensional inputs and multi-dimensional logits. + + input_layer = [[10, 8]] + hidden_layer_0 = [[relu(0.6*10 -0.6*8 +0.1), relu(0.5*10 -0.5*8 -0.1)]] + = [[1.3, 0.9]] + hidden_layer_1 = [[relu(1*1.3 -0.8*0.9 + 0.2), relu(0.8*1.3 -1*0.9 -0.2)]] + = [[0.78, relu(-0.06)]] = [[0.78, 0]] + logits = [[-1*0.78 + 0.3, 1*0.78 -0.3, 0.5*0.78]] = [[-0.48, 0.48, 0.39]] + """ + base_global_step = 100 + create_checkpoint(( + ([[.6, .5], [-.6, -.5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1., 1., .5], [-1., 1., .5]], [.3, -.3, .0]), + ), base_global_step, self._model_dir) + + for mode in [ModeKeys.TRAIN, ModeKeys.EVAL, ModeKeys.PREDICT]: + self._test_logits( + mode, + hidden_units=(2, 2), + logits_dimension=3, + inputs=[[10., 8.]], + expected_logits=[[-0.48, 0.48, 0.39]]) + + def test_multi_feature_column_multi_dim_logits(self): + """Tests multiple feature columns and multi-dimensional logits. + + All numbers are the same as test_multi_dim_input_multi_dim_logits. The only + difference is that the input consists of two 1D feature columns, instead of + one 2D feature column. + """ + base_global_step = 100 + create_checkpoint(( + ([[.6, .5], [-.6, -.5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1., 1., .5], [-1., 1., .5]], [.3, -.3, .0]), + ), base_global_step, self._model_dir) + hidden_units = (2, 2) + logits_dimension = 3 + inputs = ([[10.]], [[8.]]) + expected_logits = [[-0.48, 0.48, 0.39]] + + for mode in [ModeKeys.TRAIN, ModeKeys.EVAL, ModeKeys.PREDICT]: + with tf.Graph().as_default(): + tf.compat.v1.train.create_global_step() + head = mock_head( + self, + hidden_units=hidden_units, + logits_dimension=logits_dimension, + expected_logits=expected_logits) + estimator_spec = self._dnn_model_fn( + features={ + 'age': tf.constant(inputs[0]), + 'height': tf.constant(inputs[1]) + }, + labels=tf.constant([[1]]), + mode=mode, + head=head, + hidden_units=hidden_units, + feature_columns=[ + self._fc_impl.numeric_column('age'), + self._fc_impl.numeric_column('height') + ], + optimizer=mock_optimizer(self, hidden_units)) + with tf.compat.v1.train.MonitoredTrainingSession( + checkpoint_dir=self._model_dir) as sess: + if mode == ModeKeys.TRAIN: + sess.run(estimator_spec.train_op) + elif mode == ModeKeys.EVAL: + sess.run(estimator_spec.loss) + elif mode == ModeKeys.PREDICT: + sess.run(estimator_spec.predictions) + else: + self.fail('Invalid mode: {}'.format(mode)) + + def test_multi_feature_column_mix_multi_dim_logits(self): + """Tests multiple feature columns and multi-dimensional logits. + + All numbers are the same as test_multi_dim_input_multi_dim_logits. The only + difference is that the input consists of two 1D feature columns, instead of + one 2D feature column. + """ + base_global_step = 100 + create_checkpoint(( + ([[.6, .5], [-.6, -.5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1., 1., .5], [-1., 1., .5]], [.3, -.3, .0]), + ), base_global_step, self._model_dir) + hidden_units = (2, 2) + logits_dimension = 3 + inputs = ([[10.]], [[8.]]) + expected_logits = [[-0.48, 0.48, 0.39]] + + for mode in [ModeKeys.TRAIN, ModeKeys.EVAL, ModeKeys.PREDICT]: + with tf.Graph().as_default(): + tf.compat.v1.train.create_global_step() + head = mock_head( + self, + hidden_units=hidden_units, + logits_dimension=logits_dimension, + expected_logits=expected_logits) + estimator_spec = self._dnn_model_fn( + features={ + 'age': tf.constant(inputs[0]), + 'height': tf.constant(inputs[1]) + }, + labels=tf.constant([[1]]), + mode=mode, + head=head, + hidden_units=hidden_units, + feature_columns=[ + tf.feature_column.numeric_column('age'), + tf.feature_column.numeric_column('height') + ], + optimizer=mock_optimizer(self, hidden_units)) + with tf.compat.v1.train.MonitoredTrainingSession( + checkpoint_dir=self._model_dir) as sess: + if mode == ModeKeys.TRAIN: + sess.run(estimator_spec.train_op) + elif mode == ModeKeys.EVAL: + sess.run(estimator_spec.loss) + elif mode == ModeKeys.PREDICT: + sess.run(estimator_spec.predictions) + else: + self.fail('Invalid mode: {}'.format(mode)) + + def test_features_tensor_raises_value_error(self): + """Tests that passing a Tensor for features raises a ValueError.""" + hidden_units = (2, 2) + logits_dimension = 3 + inputs = ([[10.]], [[8.]]) + expected_logits = [[0, 0, 0]] + + with tf.Graph().as_default(): + tf.compat.v1.train.create_global_step() + head = mock_head( + self, + hidden_units=hidden_units, + logits_dimension=logits_dimension, + expected_logits=expected_logits) + with self.assertRaisesRegexp(ValueError, 'features should be a dict'): + self._dnn_model_fn( + features=tf.constant(inputs), + labels=tf.constant([[1]]), + mode=ModeKeys.TRAIN, + head=head, + hidden_units=hidden_units, + feature_columns=[ + self._fc_impl.numeric_column( + 'age', shape=np.array(inputs).shape[1:]) + ], + optimizer=mock_optimizer(self, hidden_units)) + + +class BaseDNNLogitFnTest(object): + """Tests correctness of logits calculated from _dnn_logit_fn_builder.""" + + def __init__(self, dnn_logit_fn_builder, fc_impl=feature_column_v2): + self._dnn_logit_fn_builder = dnn_logit_fn_builder + self._fc_impl = fc_impl + + def setUp(self): + self._model_dir = tempfile.mkdtemp() + + def tearDown(self): + if self._model_dir: + tf.compat.v1.summary.FileWriterCache.clear() + shutil.rmtree(self._model_dir) + + def _test_logits(self, + mode, + hidden_units, + logits_dimension, + inputs, + expected_logits, + batch_norm=False): + """Tests that the expected logits are calculated.""" + with tf.Graph().as_default(): + # Global step needed for MonitoredSession, which is in turn used to + # explicitly set variable weights through a checkpoint. + tf.compat.v1.train.create_global_step() + logit_fn = self._dnn_logit_fn_builder( + units=logits_dimension, + hidden_units=hidden_units, + feature_columns=[ + self._fc_impl.numeric_column( + 'age', shape=np.array(inputs).shape[1:]) + ], + activation_fn=tf.nn.relu, + dropout=None, + batch_norm=batch_norm) + logits = logit_fn(features={'age': tf.constant(inputs)}, mode=mode) + with tf.compat.v1.train.MonitoredTrainingSession( + checkpoint_dir=self._model_dir) as sess: + self.assertAllClose(expected_logits, sess.run(logits)) + + def test_one_dim_logits(self): + """Tests one-dimensional logits. + + input_layer = [[10]] + hidden_layer_0 = [[relu(0.6*10 +0.1), relu(0.5*10 -0.1)]] = [[6.1, 4.9]] + hidden_layer_1 = [[relu(1*6.1 -0.8*4.9 +0.2), relu(0.8*6.1 -1*4.9 -0.1)]] + = [[relu(2.38), relu(-0.12)]] = [[2.38, 0]] + logits = [[-1*2.38 +1*0 +0.3]] = [[-2.08]] + """ + base_global_step = 100 + create_checkpoint(( + ([[.6, .5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1.], [1.]], [.3]), + ), base_global_step, self._model_dir) + for mode in [ModeKeys.TRAIN, ModeKeys.EVAL, ModeKeys.PREDICT]: + self._test_logits( + mode, + hidden_units=(2, 2), + logits_dimension=1, + inputs=[[10.]], + expected_logits=[[-2.08]]) + + def test_one_dim_logits_with_batch_norm(self): + """Tests one-dimensional logits. + + input_layer = [[10]] + hidden_layer_0 = [[relu(0.6*10 +1), relu(0.5*10 -1)]] = [[7, 4]] + hidden_layer_0 = [[relu(0.6*20 +1), relu(0.5*20 -1)]] = [[13, 9]] + + batch_norm_0, training (epsilon = 0.001): + mean1 = 1/2*(7+13) = 10, + variance1 = 1/2*(3^2+3^2) = 9 + x11 = (7-10)/sqrt(9+0.001) = -0.999944449, + x21 = (13-10)/sqrt(9+0.001) = 0.999944449, + + mean2 = 1/2*(4+9) = 6.5, + variance2 = 1/2*(2.5^2+.2.5^2) = 6.25 + x12 = (4-6.5)/sqrt(6.25+0.001) = -0.99992001, + x22 = (9-6.5)/sqrt(6.25+0.001) = 0.99992001, + + logits = [[-1*(-0.999944449) + 2*(-0.99992001) + 0.3], + [-1*0.999944449 + 2*0.99992001 + 0.3]] + = [[-0.699895571],[1.299895571]] + + batch_norm_0, not training (epsilon = 0.001): + moving_mean1 = 0, moving_variance1 = 1 + x11 = (7-0)/sqrt(1+0.001) = 6.996502623, + x21 = (13-0)/sqrt(1+0.001) = 12.993504871, + moving_mean2 = 0, moving_variance2 = 1 + x12 = (4-0)/sqrt(1+0.001) = 3.998001499, + x22 = (9-0)/sqrt(1+0.001) = 8.995503372, + + logits = [[-1*6.996502623 + 2*3.998001499 + 0.3], + [-1*12.993504871 + 2*8.995503372 + 0.3]] + = [[1.299500375],[5.297501873]] + """ + base_global_step = 100 + create_checkpoint( + ( + ([[.6, .5]], [1., -1.]), + ([[-1.], [2.]], [.3]), + ), + base_global_step, + self._model_dir, + batch_norm_vars=( + [ + [0, 0], # beta. + [1, 1], # gamma. + [0, 0], # moving mean. + [1, 1], # moving variance. + ],)) + self._test_logits( + ModeKeys.TRAIN, + hidden_units=[2], + logits_dimension=1, + inputs=[[10.], [20.]], + expected_logits=[[-0.699895571], [1.299895571]], + batch_norm=True) + for mode in [ModeKeys.EVAL, ModeKeys.PREDICT]: + self._test_logits( + mode, + hidden_units=[2], + logits_dimension=1, + inputs=[[10.], [20.]], + expected_logits=[[1.299500375], [5.297501873]], + batch_norm=True) + + def test_multi_dim_logits(self): + """Tests multi-dimensional logits. + + input_layer = [[10]] + hidden_layer_0 = [[relu(0.6*10 +0.1), relu(0.5*10 -0.1)]] = [[6.1, 4.9]] + hidden_layer_1 = [[relu(1*6.1 -0.8*4.9 +0.2), relu(0.8*6.1 -1*4.9 -0.1)]] + = [[relu(2.38), relu(-0.12)]] = [[2.38, 0]] + logits = [[-1*2.38 +0.3, 1*2.38 -0.3, 0.5*2.38]] + = [[-2.08, 2.08, 1.19]] + """ + base_global_step = 100 + create_checkpoint(( + ([[.6, .5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1., 1., .5], [-1., 1., .5]], [.3, -.3, .0]), + ), base_global_step, self._model_dir) + for mode in [ModeKeys.TRAIN, ModeKeys.EVAL, ModeKeys.PREDICT]: + self._test_logits( + mode, + hidden_units=(2, 2), + logits_dimension=3, + inputs=[[10.]], + expected_logits=[[-2.08, 2.08, 1.19]]) + + def test_multi_example_multi_dim_logits(self): + """Tests multiple examples and multi-dimensional logits. + + input_layer = [[10], [5]] + hidden_layer_0 = [[relu(0.6*10 +0.1), relu(0.5*10 -0.1)], + [relu(0.6*5 +0.1), relu(0.5*5 -0.1)]] + = [[6.1, 4.9], [3.1, 2.4]] + hidden_layer_1 = [[relu(1*6.1 -0.8*4.9 +0.2), relu(0.8*6.1 -1*4.9 -0.1)], + [relu(1*3.1 -0.8*2.4 +0.2), relu(0.8*3.1 -1*2.4 -0.1)]] + = [[2.38, 0], [1.38, 0]] + logits = [[-1*2.38 +0.3, 1*2.38 -0.3, 0.5*2.38], + [-1*1.38 +0.3, 1*1.38 -0.3, 0.5*1.38]] + = [[-2.08, 2.08, 1.19], [-1.08, 1.08, 0.69]] + """ + base_global_step = 100 + create_checkpoint(( + ([[.6, .5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1., 1., .5], [-1., 1., .5]], [.3, -.3, .0]), + ), base_global_step, self._model_dir) + for mode in [ModeKeys.TRAIN, ModeKeys.EVAL, ModeKeys.PREDICT]: + self._test_logits( + mode, + hidden_units=(2, 2), + logits_dimension=3, + inputs=[[10.], [5.]], + expected_logits=[[-2.08, 2.08, 1.19], [-1.08, 1.08, .69]]) + + def test_multi_dim_input_one_dim_logits(self): + """Tests multi-dimensional inputs and one-dimensional logits. + + input_layer = [[10, 8]] + hidden_layer_0 = [[relu(0.6*10 -0.6*8 +0.1), relu(0.5*10 -0.5*8 -0.1)]] + = [[1.3, 0.9]] + hidden_layer_1 = [[relu(1*1.3 -0.8*0.9 + 0.2), relu(0.8*1.3 -1*0.9 -0.2)]] + = [[0.78, relu(-0.06)]] = [[0.78, 0]] + logits = [[-1*0.78 +1*0 +0.3]] = [[-0.48]] + """ + base_global_step = 100 + create_checkpoint(( + ([[.6, .5], [-.6, -.5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1.], [1.]], [.3]), + ), base_global_step, self._model_dir) + + for mode in [ModeKeys.TRAIN, ModeKeys.EVAL, ModeKeys.PREDICT]: + self._test_logits( + mode, + hidden_units=(2, 2), + logits_dimension=1, + inputs=[[10., 8.]], + expected_logits=[[-0.48]]) + + def test_multi_dim_input_multi_dim_logits(self): + """Tests multi-dimensional inputs and multi-dimensional logits. + + input_layer = [[10, 8]] + hidden_layer_0 = [[relu(0.6*10 -0.6*8 +0.1), relu(0.5*10 -0.5*8 -0.1)]] + = [[1.3, 0.9]] + hidden_layer_1 = [[relu(1*1.3 -0.8*0.9 + 0.2), relu(0.8*1.3 -1*0.9 -0.2)]] + = [[0.78, relu(-0.06)]] = [[0.78, 0]] + logits = [[-1*0.78 + 0.3, 1*0.78 -0.3, 0.5*0.78]] = [[-0.48, 0.48, 0.39]] + """ + base_global_step = 100 + create_checkpoint(( + ([[.6, .5], [-.6, -.5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1., 1., .5], [-1., 1., .5]], [.3, -.3, .0]), + ), base_global_step, self._model_dir) + for mode in [ModeKeys.TRAIN, ModeKeys.EVAL, ModeKeys.PREDICT]: + self._test_logits( + mode, + hidden_units=(2, 2), + logits_dimension=3, + inputs=[[10., 8.]], + expected_logits=[[-0.48, 0.48, 0.39]]) + + def test_multi_feature_column_multi_dim_logits(self): + """Tests multiple feature columns and multi-dimensional logits. + + All numbers are the same as test_multi_dim_input_multi_dim_logits. The only + difference is that the input consists of two 1D feature columns, instead of + one 2D feature column. + """ + base_global_step = 100 + create_checkpoint(( + ([[.6, .5], [-.6, -.5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1., 1., .5], [-1., 1., .5]], [.3, -.3, .0]), + ), base_global_step, self._model_dir) + + hidden_units = (2, 2) + logits_dimension = 3 + inputs = ([[10.]], [[8.]]) + expected_logits = [[-0.48, 0.48, 0.39]] + + for mode in [ModeKeys.TRAIN, ModeKeys.EVAL, ModeKeys.PREDICT]: + with tf.Graph().as_default(): + # Global step needed for MonitoredSession, which is in turn used to + # explicitly set variable weights through a checkpoint. + tf.compat.v1.train.create_global_step() + logit_fn = self._dnn_logit_fn_builder( + units=logits_dimension, + hidden_units=hidden_units, + feature_columns=[ + self._fc_impl.numeric_column('age'), + self._fc_impl.numeric_column('height') + ], + activation_fn=tf.nn.relu, + dropout=None, + batch_norm=False) + logits = logit_fn( + features={ + 'age': tf.constant(inputs[0]), + 'height': tf.constant(inputs[1]) + }, + mode=mode) + with tf.compat.v1.train.MonitoredTrainingSession( + checkpoint_dir=self._model_dir) as sess: + self.assertAllClose(expected_logits, sess.run(logits)) + + def test_multi_feature_column_mix_multi_dim_logits(self): + """Tests multiple feature columns and multi-dimensional logits. + + All numbers are the same as test_multi_dim_input_multi_dim_logits. The only + difference is that the input consists of two 1D feature columns, instead of + one 2D feature column. + """ + base_global_step = 100 + create_checkpoint(( + ([[.6, .5], [-.6, -.5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1., 1., .5], [-1., 1., .5]], [.3, -.3, .0]), + ), base_global_step, self._model_dir) + + hidden_units = (2, 2) + logits_dimension = 3 + inputs = ([[10.]], [[8.]]) + expected_logits = [[-0.48, 0.48, 0.39]] + + for mode in [ModeKeys.TRAIN, ModeKeys.EVAL, ModeKeys.PREDICT]: + with tf.Graph().as_default(): + # Global step needed for MonitoredSession, which is in turn used to + # explicitly set variable weights through a checkpoint. + tf.compat.v1.train.create_global_step() + logit_fn = self._dnn_logit_fn_builder( + units=logits_dimension, + hidden_units=hidden_units, + feature_columns=[ + tf.feature_column.numeric_column('age'), + tf.feature_column.numeric_column('height') + ], + activation_fn=tf.nn.relu, + dropout=None, + batch_norm=False) + logits = logit_fn( + features={ + 'age': tf.constant(inputs[0]), + 'height': tf.constant(inputs[1]) + }, + mode=mode) + with tf.compat.v1.train.MonitoredTrainingSession( + checkpoint_dir=self._model_dir) as sess: + self.assertAllClose(expected_logits, sess.run(logits)) + + +class BaseDNNWarmStartingTest(object): + + def __init__(self, + _dnn_classifier_fn, + _dnn_regressor_fn, + fc_impl=feature_column_v2): + self._dnn_classifier_fn = _dnn_classifier_fn + self._dnn_regressor_fn = _dnn_regressor_fn + self._fc_impl = fc_impl + + def setUp(self): + # Create a directory to save our old checkpoint and vocabularies to. + self._ckpt_and_vocab_dir = tempfile.mkdtemp() + # Reset the default graph in each test method to avoid the Keras optimizer + # naming issue during warm starting. + tf.compat.v1.reset_default_graph() + + # Make a dummy input_fn. + def _input_fn(): + features = { + 'city': [['Palo Alto'], ['Mountain View']], + 'locality': [['Palo Alto'], ['Mountain View']], + 'occupation': [['doctor'], ['consultant']] + } + return features, [0, 1] + + self._input_fn = _input_fn + + def tearDown(self): + # Clean up checkpoint / vocab dir. + tf.compat.v1.summary.FileWriterCache.clear() + shutil.rmtree(self._ckpt_and_vocab_dir) + + def assertAllNotClose(self, t1, t2): + """Helper assert for arrays.""" + sum_of_abs_diff = 0.0 + for x, y in zip(t1, t2): + try: + for a, b in zip(x, y): + sum_of_abs_diff += abs(b - a) + except TypeError: + sum_of_abs_diff += abs(y - x) + self.assertGreater(sum_of_abs_diff, 0) + + def test_classifier_basic_warm_starting(self): + """Tests correctness of DNNClassifier default warm-start.""" + city = self._fc_impl.embedding_column( + self._fc_impl.categorical_column_with_vocabulary_list( + 'city', vocabulary_list=['Mountain View', 'Palo Alto']), + dimension=5) + + # Create a DNNClassifier and train to save a checkpoint. + dnn_classifier = self._dnn_classifier_fn( + hidden_units=[256, 128], + feature_columns=[city], + model_dir=self._ckpt_and_vocab_dir, + n_classes=4, + optimizer='SGD') + dnn_classifier.train(input_fn=self._input_fn, max_steps=1) + + # Create a second DNNClassifier, warm-started from the first. Use a + # learning_rate = 0.0 optimizer to check values (use SGD so we don't have + # accumulator values that change). + warm_started_dnn_classifier = self._dnn_classifier_fn( + hidden_units=[256, 128], + feature_columns=[city], + n_classes=4, + optimizer=tf.keras.optimizers.legacy.SGD(learning_rate=0.0), + warm_start_from=dnn_classifier.model_dir) + + warm_started_dnn_classifier.train(input_fn=self._input_fn, max_steps=1) + for variable_name in warm_started_dnn_classifier.get_variable_names(): + # Learning rate is also checkpointed in V2 optimizer. So we need to make + # sure it uses the new value after warm started. + if 'learning_rate' in variable_name: + self.assertAllClose( + 0.0, warm_started_dnn_classifier.get_variable_value(variable_name)) + else: + self.assertAllClose( + dnn_classifier.get_variable_value(variable_name), + warm_started_dnn_classifier.get_variable_value(variable_name)) + + def test_regressor_basic_warm_starting(self): + """Tests correctness of DNNRegressor default warm-start.""" + city = self._fc_impl.embedding_column( + self._fc_impl.categorical_column_with_vocabulary_list( + 'city', vocabulary_list=['Mountain View', 'Palo Alto']), + dimension=5) + + # Create a DNNRegressor and train to save a checkpoint. + dnn_regressor = self._dnn_regressor_fn( + hidden_units=[256, 128], + feature_columns=[city], + model_dir=self._ckpt_and_vocab_dir, + optimizer='SGD') + dnn_regressor.train(input_fn=self._input_fn, max_steps=1) + + # Create a second DNNRegressor, warm-started from the first. Use a + # learning_rate = 0.0 optimizer to check values (use SGD so we don't have + # accumulator values that change). + warm_started_dnn_regressor = self._dnn_regressor_fn( + hidden_units=[256, 128], + feature_columns=[city], + optimizer=tf.keras.optimizers.legacy.SGD(learning_rate=0.0), + warm_start_from=dnn_regressor.model_dir) + + warm_started_dnn_regressor.train(input_fn=self._input_fn, max_steps=1) + for variable_name in warm_started_dnn_regressor.get_variable_names(): + # Learning rate is also checkpointed in V2 optimizer. So we need to make + # sure it uses the new value after warm started. + if 'learning_rate' in variable_name: + self.assertAllClose( + 0.0, warm_started_dnn_regressor.get_variable_value(variable_name)) + else: + self.assertAllClose( + dnn_regressor.get_variable_value(variable_name), + warm_started_dnn_regressor.get_variable_value(variable_name)) + + def test_warm_starting_selective_variables(self): + """Tests selecting variables to warm-start.""" + city = self._fc_impl.embedding_column( + self._fc_impl.categorical_column_with_vocabulary_list( + 'city', vocabulary_list=['Mountain View', 'Palo Alto']), + dimension=5) + + # Create a DNNClassifier and train to save a checkpoint. + dnn_classifier = self._dnn_classifier_fn( + hidden_units=[256, 128], + feature_columns=[city], + model_dir=self._ckpt_and_vocab_dir, + n_classes=4, + optimizer='SGD') + dnn_classifier.train(input_fn=self._input_fn, max_steps=1) + + # Create a second DNNClassifier, warm-started from the first. Use a + # learning_rate = 0.0 optimizer to check values (use SGD so we don't have + # accumulator values that change). + warm_started_dnn_classifier = self._dnn_classifier_fn( + hidden_units=[256, 128], + feature_columns=[city], + n_classes=4, + optimizer=tf.keras.optimizers.legacy.SGD(learning_rate=0.0), + # The provided regular expression will only warm-start the city + # embedding, not the kernels and biases of the hidden weights. + warm_start_from=estimator.WarmStartSettings( + ckpt_to_initialize_from=dnn_classifier.model_dir, + vars_to_warm_start='.*(city).*')) + + warm_started_dnn_classifier.train(input_fn=self._input_fn, max_steps=1) + for variable_name in warm_started_dnn_classifier.get_variable_names(): + if 'city' in variable_name: + self.assertAllClose( + dnn_classifier.get_variable_value(variable_name), + warm_started_dnn_classifier.get_variable_value(variable_name)) + elif 'bias' in variable_name: + # Hidden layer biases are zero-initialized. + bias_values = warm_started_dnn_classifier.get_variable_value( + variable_name) + self.assertAllClose(np.zeros_like(bias_values), bias_values) + elif 'kernel' in variable_name: + # We can't override the glorot uniform initializer used for the kernels + # in the dense layers, so just make sure we're not getting the same + # values from the old checkpoint. + self.assertAllNotClose( + dnn_classifier.get_variable_value(variable_name), + warm_started_dnn_classifier.get_variable_value(variable_name)) + + def test_warm_starting_with_vocab_remapping(self): + """Tests warm-starting with vocab remapping.""" + vocab_list = ['doctor', 'lawyer', 'consultant'] + vocab_file = os.path.join(self._ckpt_and_vocab_dir, 'occupation_vocab') + with open(vocab_file, 'w') as f: + f.write('\n'.join(vocab_list)) + occupation = self._fc_impl.embedding_column( + self._fc_impl.categorical_column_with_vocabulary_file( + 'occupation', + vocabulary_file=vocab_file, + vocabulary_size=len(vocab_list)), + dimension=2) + + # Create a DNNClassifier and train to save a checkpoint. + dnn_classifier = self._dnn_classifier_fn( + hidden_units=[256, 128], + feature_columns=[occupation], + model_dir=self._ckpt_and_vocab_dir, + n_classes=4, + optimizer='SGD') + dnn_classifier.train(input_fn=self._input_fn, max_steps=1) + + # Create a second DNNClassifier, warm-started from the first. Use a + # learning_rate = 0.0 optimizer to check values (use SGD so we don't have + # accumulator values that change). Use a new FeatureColumn with a + # different vocabulary for occupation. + new_vocab_list = ['doctor', 'consultant', 'engineer'] + new_vocab_file = os.path.join(self._ckpt_and_vocab_dir, + 'new_occupation_vocab') + with open(new_vocab_file, 'w') as f: + f.write('\n'.join(new_vocab_list)) + new_occupation = self._fc_impl.embedding_column( + self._fc_impl.categorical_column_with_vocabulary_file( + 'occupation', + vocabulary_file=new_vocab_file, + vocabulary_size=len(new_vocab_list)), + dimension=2) + # We can create our VocabInfo object from the new and old occupation + # FeatureColumn's. + occupation_vocab_info = estimator.VocabInfo( + new_vocab=new_occupation.categorical_column.vocabulary_file, + new_vocab_size=new_occupation.categorical_column.vocabulary_size, + num_oov_buckets=new_occupation.categorical_column.num_oov_buckets, + old_vocab=occupation.categorical_column.vocabulary_file, + old_vocab_size=occupation.categorical_column.vocabulary_size, + # Can't use constant_initializer with load_and_remap. In practice, + # use a truncated normal initializer. + backup_initializer=tf.compat.v1.initializers.random_uniform( + minval=0.39, maxval=0.39)) + warm_started_dnn_classifier = self._dnn_classifier_fn( + hidden_units=[256, 128], + feature_columns=[occupation], + n_classes=4, + optimizer=tf.keras.optimizers.legacy.SGD(learning_rate=0.0), + warm_start_from=estimator.WarmStartSettings( + ckpt_to_initialize_from=dnn_classifier.model_dir, + var_name_to_vocab_info={ + OCCUPATION_EMBEDDING_NAME: occupation_vocab_info + }, + # Explicitly providing None here will only warm-start variables + # referenced in var_name_to_vocab_info (no hidden weights will be + # warmstarted). + vars_to_warm_start=None)) + + warm_started_dnn_classifier.train(input_fn=self._input_fn, max_steps=1) + # 'doctor' was ID-0 and still ID-0. + self.assertAllClose( + dnn_classifier.get_variable_value(OCCUPATION_EMBEDDING_NAME)[0, :], + warm_started_dnn_classifier.get_variable_value( + OCCUPATION_EMBEDDING_NAME)[0, :]) + # 'consultant' was ID-2 and now ID-1. + self.assertAllClose( + dnn_classifier.get_variable_value(OCCUPATION_EMBEDDING_NAME)[2, :], + warm_started_dnn_classifier.get_variable_value( + OCCUPATION_EMBEDDING_NAME)[1, :]) + # 'engineer' is a new entry and should be initialized with the + # backup_initializer in VocabInfo. + self.assertAllClose([0.39] * 2, + warm_started_dnn_classifier.get_variable_value( + OCCUPATION_EMBEDDING_NAME)[2, :]) + for variable_name in warm_started_dnn_classifier.get_variable_names(): + if 'bias' in variable_name: + # Hidden layer biases are zero-initialized. + bias_values = warm_started_dnn_classifier.get_variable_value( + variable_name) + self.assertAllClose(np.zeros_like(bias_values), bias_values) + elif 'kernel' in variable_name: + # We can't override the glorot uniform initializer used for the kernels + # in the dense layers, so just make sure we're not getting the same + # values from the old checkpoint. + self.assertAllNotClose( + dnn_classifier.get_variable_value(variable_name), + warm_started_dnn_classifier.get_variable_value(variable_name)) + + def test_warm_starting_with_naming_change(self): + """Tests warm-starting with a Tensor name remapping.""" + locality = self._fc_impl.embedding_column( + self._fc_impl.categorical_column_with_vocabulary_list( + 'locality', vocabulary_list=['Mountain View', 'Palo Alto']), + dimension=5) + + # Create a DNNClassifier and train to save a checkpoint. + dnn_classifier = self._dnn_classifier_fn( + hidden_units=[256, 128], + feature_columns=[locality], + model_dir=self._ckpt_and_vocab_dir, + n_classes=4, + optimizer='SGD') + dnn_classifier.train(input_fn=self._input_fn, max_steps=1) + + # Create a second DNNClassifier, warm-started from the first. Use a + # learning_rate = 0.0 optimizer to check values (use SGD so we don't have + # accumulator values that change). + city = self._fc_impl.embedding_column( + self._fc_impl.categorical_column_with_vocabulary_list( + 'city', vocabulary_list=['Mountain View', 'Palo Alto']), + dimension=5) + warm_started_dnn_classifier = self._dnn_classifier_fn( + hidden_units=[256, 128], + feature_columns=[city], + n_classes=4, + optimizer=tf.keras.optimizers.legacy.SGD(learning_rate=0.0), + # The 'city' variable correspond to the 'locality' variable in the + # previous model. + warm_start_from=estimator.WarmStartSettings( + ckpt_to_initialize_from=dnn_classifier.model_dir, + var_name_to_prev_var_name={ + CITY_EMBEDDING_NAME: + CITY_EMBEDDING_NAME.replace('city', 'locality') + })) + + warm_started_dnn_classifier.train(input_fn=self._input_fn, max_steps=1) + for variable_name in warm_started_dnn_classifier.get_variable_names(): + if 'city' in variable_name: + self.assertAllClose( + dnn_classifier.get_variable_value( + CITY_EMBEDDING_NAME.replace('city', 'locality')), + warm_started_dnn_classifier.get_variable_value(CITY_EMBEDDING_NAME)) + # Learning rate is also checkpointed in V2 optimizer. So we need to make + # sure it uses the new value after warm started. + elif 'learning_rate' in variable_name: + self.assertAllClose( + 0.0, warm_started_dnn_classifier.get_variable_value(variable_name)) + else: + self.assertAllClose( + dnn_classifier.get_variable_value(variable_name), + warm_started_dnn_classifier.get_variable_value(variable_name)) + + +class BaseDNNClassifierEvaluateTest(object): + + def __init__(self, dnn_classifier_fn, fc_impl=feature_column_v2): + self._dnn_classifier_fn = dnn_classifier_fn + self._fc_impl = fc_impl + + def setUp(self): + self._model_dir = tempfile.mkdtemp() + + def tearDown(self): + if self._model_dir: + tf.compat.v1.summary.FileWriterCache.clear() + shutil.rmtree(self._model_dir) + + def test_one_dim(self): + """Asserts evaluation metrics for one-dimensional input and logits.""" + global_step = 100 + create_checkpoint(( + ([[.6, .5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1.], [1.]], [.3]), + ), global_step, self._model_dir) + + dnn_classifier = self._dnn_classifier_fn( + hidden_units=(2, 2), + feature_columns=[self._fc_impl.numeric_column('age')], + model_dir=self._model_dir) + + def _input_fn(): + # batch_size = 2, one false label, and one true. + return {'age': [[10.], [10.]]}, [[1], [0]] + + # Uses identical numbers as DNNModelTest.test_one_dim_logits. + # See that test for calculation of logits. + # logits = [[-2.08], [-2.08]] => + # logistic = 1/(1 + exp(-logits)) = [[0.11105597], [0.11105597]] + # loss = (-1. * log(0.111) -1. * log(0.889) = 2.31544200) / 2 + expected_loss = 1.157721 + self.assertAllClose( + { + metric_keys.MetricKeys.LOSS: + expected_loss, + metric_keys.MetricKeys.LOSS_MEAN: + expected_loss, + metric_keys.MetricKeys.ACCURACY: + 0.5, + metric_keys.MetricKeys.PRECISION: + 0.0, + metric_keys.MetricKeys.RECALL: + 0.0, + metric_keys.MetricKeys.PREDICTION_MEAN: + 0.11105597, + metric_keys.MetricKeys.LABEL_MEAN: + 0.5, + metric_keys.MetricKeys.ACCURACY_BASELINE: + 0.5, + # There is no good way to calculate AUC for only two data points. + # But that is what the algorithm returns. + metric_keys.MetricKeys.AUC: + 0.5, + metric_keys.MetricKeys.AUC_PR: + 0.5, + tf.compat.v1.GraphKeys.GLOBAL_STEP: + global_step + }, + dnn_classifier.evaluate(input_fn=_input_fn, steps=1)) + + def test_multi_dim(self): + """Asserts evaluation metrics for multi-dimensional input and logits.""" + global_step = 100 + create_checkpoint(( + ([[.6, .5], [-.6, -.5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1., 1., .5], [-1., 1., .5]], [.3, -.3, .0]), + ), global_step, self._model_dir) + n_classes = 3 + + dnn_classifier = self._dnn_classifier_fn( + hidden_units=(2, 2), + feature_columns=[self._fc_impl.numeric_column('age', shape=[2])], + n_classes=n_classes, + model_dir=self._model_dir) + + def _input_fn(): + # batch_size = 2, one false label, and one true. + return {'age': [[10., 8.], [10., 8.]]}, [[1], [0]] + + # Uses identical numbers as + # DNNModelFnTest.test_multi_dim_input_multi_dim_logits. + # See that test for calculation of logits. + # logits = [[-0.48, 0.48, 0.39], [-0.48, 0.48, 0.39]] + # probabilities = exp(logits)/sum(exp(logits)) + # = [[0.16670536, 0.43538380, 0.39791084], + # [0.16670536, 0.43538380, 0.39791084]] + # loss = -log(0.43538380) - log(0.16670536) + expected_loss = 2.62305466 / 2 # batch size + self.assertAllClose( + { + metric_keys.MetricKeys.LOSS: expected_loss, + metric_keys.MetricKeys.LOSS_MEAN: expected_loss, + metric_keys.MetricKeys.ACCURACY: 0.5, + tf.compat.v1.GraphKeys.GLOBAL_STEP: global_step + }, dnn_classifier.evaluate(input_fn=_input_fn, steps=1)) + + def test_float_labels(self): + """Asserts evaluation metrics for float labels in binary classification.""" + global_step = 100 + create_checkpoint(( + ([[.6, .5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1.], [1.]], [.3]), + ), global_step, self._model_dir) + + dnn_classifier = self._dnn_classifier_fn( + hidden_units=(2, 2), + feature_columns=[self._fc_impl.numeric_column('age')], + model_dir=self._model_dir) + + def _input_fn(): + # batch_size = 2, one false label, and one true. + return {'age': [[10.], [10.]]}, [[0.8], [0.4]] + + # Uses identical numbers as DNNModelTest.test_one_dim_logits. + # See that test for calculation of logits. + # logits = [[-2.08], [-2.08]] => + # logistic = 1/(1 + exp(-logits)) = [[0.11105597], [0.11105597]] + # loss = (-0.8 * log(0.111) -0.2 * log(0.889) + # -0.4 * log(0.111) -0.6 * log(0.889)) / 2 = 2.7314420 / 2 + expected_loss = 1.365721 + metrics = dnn_classifier.evaluate(input_fn=_input_fn, steps=1) + self.assertAlmostEqual(expected_loss, metrics[metric_keys.MetricKeys.LOSS]) + + def test_multi_dim_weights(self): + """Tests evaluation with weights.""" + # Uses same checkpoint with test_multi_dims + global_step = 100 + create_checkpoint(( + ([[.6, .5], [-.6, -.5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1., 1., .5], [-1., 1., .5]], [.3, -.3, .0]), + ), global_step, self._model_dir) + n_classes = 3 + + dnn_classifier = self._dnn_classifier_fn( + hidden_units=(2, 2), + feature_columns=[self._fc_impl.numeric_column('age', shape=[2])], + n_classes=n_classes, + weight_column='w', + model_dir=self._model_dir) + + def _input_fn(): + # batch_size = 2, one false label, and one true. + return {'age': [[10., 8.], [10., 8.]], 'w': [[10.], [100.]]}, [[1], [0]] + + # Uses identical numbers as test_multi_dims + # See that test for calculation of logits. + # loss = (-log(0.43538380)*10 - log(0.16670536)*100) / 2 + expected_loss = 93.734 + metrics = dnn_classifier.evaluate(input_fn=_input_fn, steps=1) + self.assertAlmostEqual( + expected_loss, metrics[metric_keys.MetricKeys.LOSS], places=3) + + +class BaseDNNRegressorEvaluateTest(object): + + def __init__(self, dnn_regressor_fn, fc_impl=feature_column_v2): + self._dnn_regressor_fn = dnn_regressor_fn + self._fc_impl = fc_impl + + def setUp(self): + self._model_dir = tempfile.mkdtemp() + + def tearDown(self): + if self._model_dir: + tf.compat.v1.summary.FileWriterCache.clear() + shutil.rmtree(self._model_dir) + + def test_one_dim(self): + """Asserts evaluation metrics for one-dimensional input and logits.""" + # Create checkpoint: num_inputs=1, hidden_units=(2, 2), num_outputs=1. + global_step = 100 + create_checkpoint(( + ([[.6, .5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1.], [1.]], [.3]), + ), global_step, self._model_dir) + + dnn_regressor = self._dnn_regressor_fn( + hidden_units=(2, 2), + feature_columns=[self._fc_impl.numeric_column('age')], + model_dir=self._model_dir) + + def _input_fn(): + return {'age': [[10.]]}, [[1.]] + + # Uses identical numbers as DNNModelTest.test_one_dim_logits. + # See that test for calculation of logits. + # logits = [[-2.08]] => predictions = [-2.08]. + # loss = (1+2.08)^2 = 9.4864 + expected_loss = 9.4864 + self.assertAllClose( + { + metric_keys.MetricKeys.LOSS: expected_loss, + metric_keys.MetricKeys.LOSS_MEAN: expected_loss, + metric_keys.MetricKeys.PREDICTION_MEAN: -2.08, + metric_keys.MetricKeys.LABEL_MEAN: 1.0, + tf.compat.v1.GraphKeys.GLOBAL_STEP: global_step + }, dnn_regressor.evaluate(input_fn=_input_fn, steps=1)) + + def test_multi_dim(self): + """Asserts evaluation metrics for multi-dimensional input and logits.""" + # Create checkpoint: num_inputs=2, hidden_units=(2, 2), num_outputs=3. + global_step = 100 + create_checkpoint(( + ([[.6, .5], [-.6, -.5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1., 1., .5], [-1., 1., .5]], [.3, -.3, .0]), + ), global_step, self._model_dir) + label_dimension = 3 + + dnn_regressor = self._dnn_regressor_fn( + hidden_units=(2, 2), + feature_columns=[self._fc_impl.numeric_column('age', shape=[2])], + label_dimension=label_dimension, + model_dir=self._model_dir) + + def _input_fn(): + return {'age': [[10., 8.]]}, [[1., -1., 0.5]] + + # Uses identical numbers as + # DNNModelFnTest.test_multi_dim_input_multi_dim_logits. + # See that test for calculation of logits. + # logits = [[-0.48, 0.48, 0.39]] + # loss = (1+0.48)^2 + (-1-0.48)^2 + (0.5-0.39)^2 = 4.3929 + # expected_loss = loss / 3 + expected_loss = 1.4643 + self.assertAllClose( + { + metric_keys.MetricKeys.LOSS: expected_loss, + metric_keys.MetricKeys.LOSS_MEAN: expected_loss, + metric_keys.MetricKeys.PREDICTION_MEAN: 0.39 / 3.0, + metric_keys.MetricKeys.LABEL_MEAN: 0.5 / 3.0, + tf.compat.v1.GraphKeys.GLOBAL_STEP: global_step + }, dnn_regressor.evaluate(input_fn=_input_fn, steps=1)) + + def test_multi_dim_weights(self): + """Asserts evaluation metrics for multi-dimensional input and logits.""" + # same checkpoint with test_multi_dim. + global_step = 100 + create_checkpoint(( + ([[.6, .5], [-.6, -.5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1., 1., .5], [-1., 1., .5]], [.3, -.3, .0]), + ), global_step, self._model_dir) + label_dimension = 3 + + dnn_regressor = self._dnn_regressor_fn( + hidden_units=(2, 2), + feature_columns=[self._fc_impl.numeric_column('age', shape=[2])], + label_dimension=label_dimension, + weight_column='w', + model_dir=self._model_dir) + + def _input_fn(): + return {'age': [[10., 8.]], 'w': [10.]}, [[1., -1., 0.5]] + + # Uses identical numbers as test_multi_dim. + # See that test for calculation of logits. + # loss = 4.3929*10/3 + expected_loss = 14.643 + metrics = dnn_regressor.evaluate(input_fn=_input_fn, steps=1) + self.assertAlmostEqual( + expected_loss, metrics[metric_keys.MetricKeys.LOSS], places=3) + + +class BaseDNNClassifierPredictTest(object): + + def __init__(self, dnn_classifier_fn, fc_impl=feature_column_v2): + self._dnn_classifier_fn = dnn_classifier_fn + self._fc_impl = fc_impl + + def setUp(self): + self._model_dir = tempfile.mkdtemp() + + def tearDown(self): + if self._model_dir: + tf.compat.v1.summary.FileWriterCache.clear() + shutil.rmtree(self._model_dir) + + def _test_one_dim(self, label_vocabulary, label_output_fn): + """Asserts predictions for one-dimensional input and logits.""" + create_checkpoint(( + ([[.6, .5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1.], [1.]], [.3]), + ), + global_step=0, + model_dir=self._model_dir) + + dnn_classifier = self._dnn_classifier_fn( + hidden_units=(2, 2), + label_vocabulary=label_vocabulary, + feature_columns=(self._fc_impl.numeric_column('x'),), + model_dir=self._model_dir) + input_fn = numpy_io.numpy_input_fn( + x={'x': np.array([[10.]])}, batch_size=1, shuffle=False) + # Uses identical numbers as DNNModelTest.test_one_dim_logits. + # See that test for calculation of logits. + # logits = [-2.08] => + # logistic = exp(-2.08)/(1 + exp(-2.08)) = 0.11105597 + # probabilities = [1-logistic, logistic] = [0.88894403, 0.11105597] + # class_ids = argmax(probabilities) = [0] + predictions = next(dnn_classifier.predict(input_fn=input_fn)) + self.assertAllClose([-2.08], + predictions[prediction_keys.PredictionKeys.LOGITS]) + self.assertAllClose([0.11105597], + predictions[prediction_keys.PredictionKeys.LOGISTIC]) + self.assertAllClose( + [0.88894403, 0.11105597], + predictions[prediction_keys.PredictionKeys.PROBABILITIES]) + self.assertAllClose([0], + predictions[prediction_keys.PredictionKeys.CLASS_IDS]) + self.assertAllEqual([label_output_fn(0)], + predictions[prediction_keys.PredictionKeys.CLASSES]) + self.assertAllClose( + [0, 1], predictions[prediction_keys.PredictionKeys.ALL_CLASS_IDS]) + self.assertAllEqual( + [label_output_fn(0), label_output_fn(1)], + predictions[prediction_keys.PredictionKeys.ALL_CLASSES]) + + def test_one_dim_without_label_vocabulary(self): + self._test_one_dim( + label_vocabulary=None, label_output_fn=lambda x: ('%s' % x).encode()) + + def test_one_dim_with_label_vocabulary(self): + n_classes = 2 + self._test_one_dim( + label_vocabulary=['class_vocab_{}'.format(i) for i in range(n_classes)], + label_output_fn=lambda x: ('class_vocab_%s' % x).encode()) + + def _test_multi_dim_with_3_classes(self, label_vocabulary, label_output_fn): + """Asserts predictions for multi-dimensional input and logits.""" + create_checkpoint(( + ([[.6, .5], [-.6, -.5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1., 1., .5], [-1., 1., .5]], [.3, -.3, .0]), + ), + global_step=0, + model_dir=self._model_dir) + + dnn_classifier = self._dnn_classifier_fn( + hidden_units=(2, 2), + feature_columns=(self._fc_impl.numeric_column('x', shape=(2,)),), + label_vocabulary=label_vocabulary, + n_classes=3, + model_dir=self._model_dir) + input_fn = numpy_io.numpy_input_fn( + # Inputs shape is (batch_size, num_inputs). + x={'x': np.array([[10., 8.]])}, + batch_size=1, + shuffle=False) + # Uses identical numbers as + # DNNModelFnTest.test_multi_dim_input_multi_dim_logits. + # See that test for calculation of logits. + # logits = [-0.48, 0.48, 0.39] => + # probabilities[i] = exp(logits[i]) / sum_j exp(logits[j]) => + # probabilities = [0.16670536, 0.43538380, 0.39791084] + # class_ids = argmax(probabilities) = [1] + predictions = next(dnn_classifier.predict(input_fn=input_fn)) + self.assertItemsEqual([ + prediction_keys.PredictionKeys.LOGITS, + prediction_keys.PredictionKeys.PROBABILITIES, + prediction_keys.PredictionKeys.CLASS_IDS, + prediction_keys.PredictionKeys.CLASSES, + prediction_keys.PredictionKeys.ALL_CLASS_IDS, + prediction_keys.PredictionKeys.ALL_CLASSES + ], six.iterkeys(predictions)) + self.assertAllClose([-0.48, 0.48, 0.39], + predictions[prediction_keys.PredictionKeys.LOGITS]) + self.assertAllClose( + [0.16670536, 0.43538380, 0.39791084], + predictions[prediction_keys.PredictionKeys.PROBABILITIES]) + self.assertAllEqual([1], + predictions[prediction_keys.PredictionKeys.CLASS_IDS]) + self.assertAllEqual([label_output_fn(1)], + predictions[prediction_keys.PredictionKeys.CLASSES]) + self.assertAllEqual( + [0, 1, 2], predictions[prediction_keys.PredictionKeys.ALL_CLASS_IDS]) + self.assertAllEqual( + [label_output_fn(0), + label_output_fn(1), + label_output_fn(2)], + predictions[prediction_keys.PredictionKeys.ALL_CLASSES]) + + def test_multi_dim_with_3_classes_but_no_label_vocab(self): + self._test_multi_dim_with_3_classes( + label_vocabulary=None, label_output_fn=lambda x: ('%s' % x).encode()) + + def test_multi_dim_with_3_classes_and_label_vocab(self): + n_classes = 3 + self._test_multi_dim_with_3_classes( + label_vocabulary=['class_vocab_{}'.format(i) for i in range(n_classes)], + label_output_fn=lambda x: ('class_vocab_%s' % x).encode()) + + +class BaseDNNRegressorPredictTest(object): + + def __init__(self, dnn_regressor_fn, fc_impl=feature_column_v2): + self._dnn_regressor_fn = dnn_regressor_fn + self._fc_impl = fc_impl + + def setUp(self): + self._model_dir = tempfile.mkdtemp() + + def tearDown(self): + if self._model_dir: + tf.compat.v1.summary.FileWriterCache.clear() + shutil.rmtree(self._model_dir) + + def test_one_dim(self): + """Asserts predictions for one-dimensional input and logits.""" + # Create checkpoint: num_inputs=1, hidden_units=(2, 2), num_outputs=1. + create_checkpoint(( + ([[.6, .5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1.], [1.]], [.3]), + ), + global_step=0, + model_dir=self._model_dir) + + dnn_regressor = self._dnn_regressor_fn( + hidden_units=(2, 2), + feature_columns=(self._fc_impl.numeric_column('x'),), + model_dir=self._model_dir) + input_fn = numpy_io.numpy_input_fn( + x={'x': np.array([[10.]])}, batch_size=1, shuffle=False) + # Uses identical numbers as DNNModelTest.test_one_dim_logits. + # See that test for calculation of logits. + # logits = [[-2.08]] => predictions = [-2.08]. + self.assertAllClose({ + prediction_keys.PredictionKeys.PREDICTIONS: [-2.08], + }, next(dnn_regressor.predict(input_fn=input_fn))) + + def test_multi_dim(self): + """Asserts predictions for multi-dimensional input and logits.""" + # Create checkpoint: num_inputs=2, hidden_units=(2, 2), num_outputs=3. + create_checkpoint(( + ([[.6, .5], [-.6, -.5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1., 1., .5], [-1., 1., .5]], [.3, -.3, .0]), + ), 100, self._model_dir) + + dnn_regressor = self._dnn_regressor_fn( + hidden_units=(2, 2), + feature_columns=(self._fc_impl.numeric_column('x', shape=(2,)),), + label_dimension=3, + model_dir=self._model_dir) + input_fn = numpy_io.numpy_input_fn( + # Inputs shape is (batch_size, num_inputs). + x={'x': np.array([[10., 8.]])}, + batch_size=1, + shuffle=False) + # Uses identical numbers as + # DNNModelFnTest.test_multi_dim_input_multi_dim_logits. + # See that test for calculation of logits. + # logits = [[-0.48, 0.48, 0.39]] => predictions = [-0.48, 0.48, 0.39] + self.assertAllClose( + { + prediction_keys.PredictionKeys.PREDICTIONS: [-0.48, 0.48, 0.39], + }, next(dnn_regressor.predict(input_fn=input_fn))) + + +class _SummaryHook(tf.compat.v1.train.SessionRunHook): + """Saves summaries every N steps.""" + + def __init__(self): + self._summaries = [] + + def begin(self): + self._summary_op = tf.compat.v1.summary.merge_all() + + def before_run(self, run_context): + return tf.compat.v1.train.SessionRunArgs({'summary': self._summary_op}) + + def after_run(self, run_context, run_values): + s = tf.compat.v1.summary.Summary() + s.ParseFromString(run_values.results['summary']) + self._summaries.append(s) + + def summaries(self): + return tuple(self._summaries) + + +def _assert_checkpoint(testcase, global_step, input_units, hidden_units, + output_units, model_dir): + """Asserts checkpoint contains expected variables with proper shapes. + + Args: + testcase: A TestCase instance. + global_step: Expected global step value. + input_units: The dimension of input layer. + hidden_units: Iterable of integer sizes for the hidden layers. + output_units: The dimension of output layer (logits). + model_dir: The model directory. + """ + shapes = {name: shape for (name, shape) in tf.train.list_variables(model_dir)} + + # Global step. + testcase.assertEqual([], shapes[tf.compat.v1.GraphKeys.GLOBAL_STEP]) + testcase.assertEqual( + global_step, + tf.train.load_variable(model_dir, tf.compat.v1.GraphKeys.GLOBAL_STEP)) + + # Hidden layer weights. + prev_layer_units = input_units + for i in range(len(hidden_units)): + layer_units = hidden_units[i] + testcase.assertAllEqual((prev_layer_units, layer_units), + shapes[HIDDEN_WEIGHTS_NAME_PATTERN % i]) + testcase.assertAllEqual((layer_units,), + shapes[HIDDEN_BIASES_NAME_PATTERN % i]) + prev_layer_units = layer_units + + # Output layer weights. + testcase.assertAllEqual((prev_layer_units, output_units), + shapes[LOGITS_WEIGHTS_NAME]) + testcase.assertAllEqual((output_units,), shapes[LOGITS_BIASES_NAME]) + + +def _assert_simple_summary(testcase, expected_values, actual_summary): + """Assert summary the specified simple values. + + Args: + testcase: A TestCase instance. + expected_values: Dict of expected tags and simple values. + actual_summary: `summary_pb2.Summary`. + """ + testcase.assertAllClose( + expected_values, { + v.tag: v.simple_value + for v in actual_summary.value + if (v.tag in expected_values) + }) + + +class BaseDNNClassifierTrainTest(object): + + def __init__(self, dnn_classifier_fn, fc_impl=feature_column_v2): + self._dnn_classifier_fn = dnn_classifier_fn + self._fc_impl = fc_impl + + def setUp(self): + self._model_dir = tempfile.mkdtemp() + + def tearDown(self): + if self._model_dir: + tf.compat.v1.summary.FileWriterCache.clear() + shutil.rmtree(self._model_dir) + + def test_from_scratch_with_default_optimizer_binary(self): + hidden_units = (2, 2) + dnn_classifier = self._dnn_classifier_fn( + hidden_units=hidden_units, + feature_columns=(self._fc_impl.numeric_column('age'),), + model_dir=self._model_dir) + + # Train for a few steps, then validate final checkpoint. + num_steps = 5 + dnn_classifier.train( + input_fn=lambda: ({ + 'age': [[10.]] + }, [[1]]), steps=num_steps) + _assert_checkpoint( + self, + num_steps, + input_units=1, + hidden_units=hidden_units, + output_units=1, + model_dir=self._model_dir) + + def test_from_scratch_with_default_optimizer_multi_class(self): + hidden_units = (2, 2) + n_classes = 3 + dnn_classifier = self._dnn_classifier_fn( + hidden_units=hidden_units, + feature_columns=(self._fc_impl.numeric_column('age'),), + n_classes=n_classes, + model_dir=self._model_dir) + + # Train for a few steps, then validate final checkpoint. + num_steps = 5 + dnn_classifier.train( + input_fn=lambda: ({ + 'age': [[10.]] + }, [[2]]), steps=num_steps) + _assert_checkpoint( + self, + num_steps, + input_units=1, + hidden_units=hidden_units, + output_units=n_classes, + model_dir=self._model_dir) + + def test_from_scratch_validate_summary(self): + hidden_units = (2, 2) + opt = mock_optimizer(self, hidden_units=hidden_units) + dnn_classifier = self._dnn_classifier_fn( + hidden_units=hidden_units, + feature_columns=(self._fc_impl.numeric_column('age'),), + optimizer=opt, + model_dir=self._model_dir) + + # Train for a few steps, then validate optimizer, summaries, and + # checkpoint. + num_steps = 5 + summary_hook = _SummaryHook() + dnn_classifier.train( + input_fn=lambda: ({ + 'age': [[10.]] + }, [[1]]), + steps=num_steps, + hooks=(summary_hook,)) + self.assertEqual(num_steps, + dnn_classifier.get_variable_value(opt.iterations.name)) + _assert_checkpoint( + self, + num_steps, + input_units=1, + hidden_units=hidden_units, + output_units=1, + model_dir=self._model_dir) + summaries = summary_hook.summaries() + self.assertEqual(num_steps, len(summaries)) + for summary in summaries: + summary_keys = [v.tag for v in summary.value] + self.assertIn(metric_keys.MetricKeys.LOSS, summary_keys) + + def test_binary_classification(self): + base_global_step = 100 + hidden_units = (2, 2) + create_checkpoint(( + ([[.6, .5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1.], [1.]], [.3]), + ), base_global_step, self._model_dir) + + # Uses identical numbers as DNNModelFnTest.test_one_dim_logits. + # See that test for calculation of logits. + # logits = [-2.08] => probabilities = [0.889, 0.111] + # loss = -1. * log(0.111) = 2.19772100 + expected_loss = 2.19772100 + opt = mock_optimizer( + self, hidden_units=hidden_units, expected_loss=expected_loss) + dnn_classifier = self._dnn_classifier_fn( + hidden_units=hidden_units, + feature_columns=(self._fc_impl.numeric_column('age'),), + optimizer=opt, + model_dir=self._model_dir) + + # Train for a few steps, then validate optimizer, summaries, and + # checkpoint. + num_steps = 5 + summary_hook = _SummaryHook() + dnn_classifier.train( + input_fn=lambda: ({ + 'age': [[10.]] + }, [[1]]), + steps=num_steps, + hooks=(summary_hook,)) + self.assertEqual(base_global_step + num_steps, + dnn_classifier.get_variable_value(opt.iterations.name)) + summaries = summary_hook.summaries() + self.assertEqual(num_steps, len(summaries)) + for summary in summaries: + _assert_simple_summary( + self, { + 'dnn/hiddenlayer_0/fraction_of_zero_values': 0., + 'dnn/hiddenlayer_1/fraction_of_zero_values': .5, + 'dnn/logits/fraction_of_zero_values': 0., + metric_keys.MetricKeys.LOSS: expected_loss, + }, summary) + _assert_checkpoint( + self, + base_global_step + num_steps, + input_units=1, + hidden_units=hidden_units, + output_units=1, + model_dir=self._model_dir) + + def test_binary_classification_float_labels(self): + base_global_step = 100 + hidden_units = (2, 2) + create_checkpoint(( + ([[.6, .5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1.], [1.]], [.3]), + ), base_global_step, self._model_dir) + + # Uses identical numbers as DNNModelFnTest.test_one_dim_logits. + # See that test for calculation of logits. + # logits = [-2.08] => probabilities = [0.889, 0.111] + # loss = -0.8 * log(0.111) -0.2 * log(0.889) = 1.7817210 + expected_loss = 1.7817210 + opt = mock_optimizer( + self, hidden_units=hidden_units, expected_loss=expected_loss) + dnn_classifier = self._dnn_classifier_fn( + hidden_units=hidden_units, + feature_columns=(self._fc_impl.numeric_column('age'),), + optimizer=opt, + model_dir=self._model_dir) + + # Train for a few steps, then validate optimizer, summaries, and + # checkpoint. + num_steps = 5 + dnn_classifier.train( + input_fn=lambda: ({ + 'age': [[10.]] + }, [[0.8]]), steps=num_steps) + self.assertEqual(base_global_step + num_steps, + dnn_classifier.get_variable_value(opt.iterations.name)) + + def test_multi_class(self): + n_classes = 3 + base_global_step = 100 + hidden_units = (2, 2) + create_checkpoint(( + ([[.6, .5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1., 1., .5], [-1., 1., .5]], [.3, -.3, .0]), + ), base_global_step, self._model_dir) + + # Uses identical numbers as DNNModelFnTest.test_multi_dim_logits. + # See that test for calculation of logits. + # logits = [-2.08, 2.08, 1.19] => probabilities = [0.0109, 0.7011, 0.2879] + # loss = -1. * log(0.7011) = 0.35505795 + expected_loss = 0.35505795 + opt = mock_optimizer( + self, hidden_units=hidden_units, expected_loss=expected_loss) + dnn_classifier = self._dnn_classifier_fn( + n_classes=n_classes, + hidden_units=hidden_units, + feature_columns=(self._fc_impl.numeric_column('age'),), + optimizer=opt, + model_dir=self._model_dir) + + # Train for a few steps, then validate optimizer, summaries, and + # checkpoint. + num_steps = 5 + summary_hook = _SummaryHook() + dnn_classifier.train( + input_fn=lambda: ({ + 'age': [[10.]] + }, [[1]]), + steps=num_steps, + hooks=(summary_hook,)) + self.assertEqual(base_global_step + num_steps, + dnn_classifier.get_variable_value(opt.iterations.name)) + summaries = summary_hook.summaries() + self.assertEqual(num_steps, len(summaries)) + for summary in summaries: + _assert_simple_summary( + self, { + 'dnn/hiddenlayer_0/fraction_of_zero_values': 0., + 'dnn/hiddenlayer_1/fraction_of_zero_values': .5, + 'dnn/logits/fraction_of_zero_values': 0., + metric_keys.MetricKeys.LOSS: expected_loss, + }, summary) + _assert_checkpoint( + self, + base_global_step + num_steps, + input_units=1, + hidden_units=hidden_units, + output_units=n_classes, + model_dir=self._model_dir) + + +class BaseDNNRegressorTrainTest(object): + + def __init__(self, dnn_regressor_fn, fc_impl=feature_column_v2): + self._dnn_regressor_fn = dnn_regressor_fn + self._fc_impl = fc_impl + + def setUp(self): + self._model_dir = tempfile.mkdtemp() + + def tearDown(self): + if self._model_dir: + tf.compat.v1.summary.FileWriterCache.clear() + shutil.rmtree(self._model_dir) + + def test_from_scratch_with_default_optimizer(self): + hidden_units = (2, 2) + dnn_regressor = self._dnn_regressor_fn( + hidden_units=hidden_units, + feature_columns=(self._fc_impl.numeric_column('age'),), + model_dir=self._model_dir) + + # Train for a few steps, then validate final checkpoint. + num_steps = 5 + dnn_regressor.train( + input_fn=lambda: ({ + 'age': ((1,),) + }, ((10,),)), steps=num_steps) + _assert_checkpoint( + self, + num_steps, + input_units=1, + hidden_units=hidden_units, + output_units=1, + model_dir=self._model_dir) + + def test_from_scratch(self): + hidden_units = (2, 2) + opt = mock_optimizer(self, hidden_units=hidden_units) + dnn_regressor = self._dnn_regressor_fn( + hidden_units=hidden_units, + feature_columns=(self._fc_impl.numeric_column('age'),), + optimizer=opt, + model_dir=self._model_dir) + + # Train for a few steps, then validate optimizer, summaries, and + # checkpoint. + num_steps = 5 + summary_hook = _SummaryHook() + dnn_regressor.train( + input_fn=lambda: ({ + 'age': ((1,),) + }, ((5.,),)), + steps=num_steps, + hooks=(summary_hook,)) + self.assertEqual(num_steps, + dnn_regressor.get_variable_value(opt.iterations.name)) + _assert_checkpoint( + self, + num_steps, + input_units=1, + hidden_units=hidden_units, + output_units=1, + model_dir=self._model_dir) + summaries = summary_hook.summaries() + self.assertEqual(num_steps, len(summaries)) + for summary in summaries: + summary_keys = [v.tag for v in summary.value] + self.assertIn(metric_keys.MetricKeys.LOSS, summary_keys) + + def test_one_dim(self): + """Asserts train loss for one-dimensional input and logits.""" + base_global_step = 100 + hidden_units = (2, 2) + create_checkpoint(( + ([[.6, .5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1.], [1.]], [.3]), + ), base_global_step, self._model_dir) + + # Uses identical numbers as DNNModelFnTest.test_one_dim_logits. + # See that test for calculation of logits. + # logits = [-2.08] => predictions = [-2.08] + # loss = (1 + 2.08)^2 = 9.4864 + expected_loss = 9.4864 + opt = mock_optimizer( + self, hidden_units=hidden_units, expected_loss=expected_loss) + dnn_regressor = self._dnn_regressor_fn( + hidden_units=hidden_units, + feature_columns=(self._fc_impl.numeric_column('age'),), + optimizer=opt, + model_dir=self._model_dir) + + # Train for a few steps, then validate optimizer, summaries, and + # checkpoint. + num_steps = 5 + summary_hook = _SummaryHook() + dnn_regressor.train( + input_fn=lambda: ({ + 'age': [[10.]] + }, [[1.]]), + steps=num_steps, + hooks=(summary_hook,)) + self.assertEqual(base_global_step + num_steps, + dnn_regressor.get_variable_value(opt.iterations.name)) + summaries = summary_hook.summaries() + self.assertEqual(num_steps, len(summaries)) + for summary in summaries: + _assert_simple_summary( + self, { + 'dnn/hiddenlayer_0/fraction_of_zero_values': 0., + 'dnn/hiddenlayer_1/fraction_of_zero_values': 0.5, + 'dnn/logits/fraction_of_zero_values': 0., + metric_keys.MetricKeys.LOSS: expected_loss, + }, summary) + _assert_checkpoint( + self, + base_global_step + num_steps, + input_units=1, + hidden_units=hidden_units, + output_units=1, + model_dir=self._model_dir) + + def test_multi_dim(self): + """Asserts train loss for multi-dimensional input and logits.""" + base_global_step = 100 + hidden_units = (2, 2) + create_checkpoint(( + ([[.6, .5], [-.6, -.5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1., 1., .5], [-1., 1., .5]], [.3, -.3, .0]), + ), base_global_step, self._model_dir) + input_dimension = 2 + label_dimension = 3 + + # Uses identical numbers as + # DNNModelFnTest.test_multi_dim_input_multi_dim_logits. + # See that test for calculation of logits. + # logits = [[-0.48, 0.48, 0.39]] + # loss = (1+0.48)^2 + (-1-0.48)^2 + (0.5-0.39)^2 = 4.3929 + # expected_loss = loss / 3 (batch size) + expected_loss = 1.4643 + opt = mock_optimizer( + self, hidden_units=hidden_units, expected_loss=expected_loss) + dnn_regressor = self._dnn_regressor_fn( + hidden_units=hidden_units, + feature_columns=[ + self._fc_impl.numeric_column('age', shape=[input_dimension]) + ], + label_dimension=label_dimension, + optimizer=opt, + model_dir=self._model_dir) + + # Train for a few steps, then validate optimizer, summaries, and + # checkpoint. + num_steps = 5 + summary_hook = _SummaryHook() + dnn_regressor.train( + input_fn=lambda: ({ + 'age': [[10., 8.]] + }, [[1., -1., 0.5]]), + steps=num_steps, + hooks=(summary_hook,)) + self.assertEqual(base_global_step + num_steps, + dnn_regressor.get_variable_value(opt.iterations.name)) + summaries = summary_hook.summaries() + self.assertEqual(num_steps, len(summaries)) + for summary in summaries: + _assert_simple_summary( + self, { + 'dnn/hiddenlayer_0/fraction_of_zero_values': 0., + 'dnn/hiddenlayer_1/fraction_of_zero_values': 0.5, + 'dnn/logits/fraction_of_zero_values': 0., + metric_keys.MetricKeys.LOSS: expected_loss, + }, summary) + _assert_checkpoint( + self, + base_global_step + num_steps, + input_units=input_dimension, + hidden_units=hidden_units, + output_units=label_dimension, + model_dir=self._model_dir) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/head.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/head.py new file mode 100644 index 0000000000000000000000000000000000000000..646d1d5854b4cf277aa0e040930193d7db6cea16 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/head.py @@ -0,0 +1,1713 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Abstractions for the head(s) of a model.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import abc +import collections + +import six +import tensorflow as tf +from tensorflow.python.feature_column import feature_column +from tensorflow.python.framework import ops +from tensorflow.python.ops import lookup_ops +from tensorflow.python.ops import string_ops +from tensorflow.python.util import function_utils +from tensorflow_estimator.python.estimator import model_fn +from tensorflow_estimator.python.estimator.canned import metric_keys +from tensorflow_estimator.python.estimator.canned import prediction_keys +from tensorflow_estimator.python.estimator.export import export_output +from tensorflow_estimator.python.estimator.mode_keys import ModeKeys + +_DEFAULT_SERVING_KEY = tf.saved_model.DEFAULT_SERVING_SIGNATURE_DEF_KEY + +# The above default is defined by TF Serving, but these next three are just +# a local convention without any special meaning. +_CLASSIFY_SERVING_KEY = 'classification' +_REGRESS_SERVING_KEY = 'regression' +_PREDICT_SERVING_KEY = 'predict' + +# A LossSpec contains +# * a scalar `Tensor` representing reduced weighted training loss +# * a `Tensor` representing the unreduced unweighted loss +# * a `Tensor` representing the example weights +# * possibly processed labels (e.g. vocabulary lookup, shape manipulation, etc) +LossSpec = collections.namedtuple( + 'LossSpec', + ['training_loss', 'unreduced_loss', 'weights', 'processed_labels']) + + +def _summary_key(head_name, val): + return '%s/%s' % (val, head_name) if head_name else val + + +def _create_eval_metrics_tuple(fn, kwargs): + """Creates TPU eval metrics tuple. + + Helper function to make eval_metric tuple (eval_metric_fn, fn_kwargs) used + by `TPUEstimator`. TPUEstimator requires that `eval_metric_fn` take + exclusively Tensor arguments. This helper can help create such a function from + a more generic function that can take both Tensor and non-Tensor arguments. + + Args: + fn: A eval_metric_fn that takes both Tensor and non-Tensor arguments. This + function must return a dict of form + {'metric name': (metric_tensor, eval_op)} + kwargs: Dict of arguments for `fn`. + + Returns: + `eval_metric` tuple that can be passed to a `model_fn._TPUEstimatorSpec`. + """ + tensor_kwargs = {} + nontensor_kwargs = {} + for k, v in six.iteritems(kwargs): + if tf.is_tensor(v): + tensor_kwargs[k] = v + else: + nontensor_kwargs[k] = v + + def _fn(**tensors): + return fn(**dict(nontensor_kwargs, **tensors)) + + return (_fn, tensor_kwargs) + + +class _Head(object): + """Interface for the head/top of a model. + + Given logits (or output of a hidden layer), a Head knows how to compute + predictions, loss, train_op, metrics and export outputs. It is meant to: + + 1. Simplify writing model_fn and to make model_fn more configurable + 2. Support wide range of machine learning models. Since most heads can work + with logits, they can support DNN, RNN, Wide, Wide&Deep, + Global objectives, Gradient boosted trees and many other types + of machine learning models. + + Common usage: + Here is simplified model_fn to build a DNN regression model. + ```python + def _my_dnn_model_fn(features, labels, mode, params, config=None): + # Optionally your callers can pass head to model_fn as a param. + head = tf.contrib.estimator.regression_head(...) + inputs = tf.feature_column.input_layer(features, ...) + hidden_layer0 = tf.layers.dense( + inputs, units=1000, activation=tf.nn.relu) + hidden_layer1 = tf.layers.dense( + hidden_layer0, units=500, activation=tf.nn.relu) + logits = tf.layers.dense( + hidden_layer1, units=head.logits_dimension, activation=None) + + return head.create_estimator_spec( + features=features, + labels=labels, + mode=mode, + logits=logits, + optimizer=optimizer) + ``` + + There are cases where computing and applying gradients can not be meaningfully + captured with optimizer or train_op_fn we support (for example, with sync + optimizer). In such case, you can take the responsibility on your own. Here is + a common use case, + ```python + estimator_spec = head.create_estimator_spec( + features=features, + labels=labels, + mode=mode, + logits=logits, + train_op_fn=lambda _: tf.no_op()) + if mode == ModeKeys.TRAIN: + optimizer = ... + sync = tf.train.SyncReplicasOptimizer(opt=optimizer, ...) + update_op = sync.minimize( + estimator_spec.loss, global_step=tf.get_global_step()) + hooks = [sync.make_session_run_hook(is_chief)] + ... update train_op and hooks in EstimatorSpec and return + ``` + """ + __metaclass__ = abc.ABCMeta + + @abc.abstractproperty + def name(self): + """The name of this head. + + Returns: + A string. + """ + raise NotImplementedError('Calling an abstract method.') + + @abc.abstractproperty + def logits_dimension(self): + """Size of the last dimension of the logits `Tensor`. + + Typically, logits is of shape `[batch_size, logits_dimension]`. + + Returns: + The expected size of the `logits` tensor. + """ + raise NotImplementedError('Calling an abstract method.') + + @abc.abstractmethod + def create_loss(self, features, mode, logits, labels): + """Returns a loss Tensor from provided logits. + + This function is designed to be used by framework developers. Almost all + users should use create_estimator_spec(), which calls this internally. + `mode` and `features` are most likely not used, but some Head + implementations may require them. + + Args: + features: Input `dict` of `Tensor` objects. + mode: Estimator's `ModeKeys`. + logits: logits `Tensor` to be used for loss construction. + labels: Labels `Tensor`, or `dict` of same. + + Returns: + A LossSpec that contains + * the scalar `Tensor` representing reduced weighted training loss + * the `Tensor` representing the unreduced unweighted loss + * the `Tensor` representing the example weights + * possibly processed labels (e.g. vocabulary lookup, shape manipulation, + etc.) + + To be extendable in the future. + """ + raise NotImplementedError('Calling an abstract method.') + + # TODO(b/65403806): By default, collect regularization_losses from + # GraphKeys.REGULARIZATION_LOSSES collection. + def create_estimator_spec(self, + features, + mode, + logits, + labels=None, + optimizer=None, + train_op_fn=None, + regularization_losses=None): + """Returns `EstimatorSpec` that a model_fn can return. + + Please note that, + + All args must be passed via name. + + Args: + features: Input `dict` of `Tensor` or `SparseTensor` objects. + mode: Estimator's `ModeKeys`. + logits: logits `Tensor` to be used by the head. + labels: Labels `Tensor`, or `dict` of same. + optimizer: `Optimizer` instance to optimize the loss in TRAIN mode. + Namely, sets `train_op = optimizer.minimize(loss, global_step)`, which + updates variables and increments `global_step`. + train_op_fn: Function that takes a scalar loss `Tensor` and returns an op + to optimize the model with the loss in TRAIN mode. Used if `optimizer` + is `None`. Exactly one of `train_op_fn` and `optimizer` must be set in + TRAIN mode. None is allowed in other modes. If you want to optimize loss + yourself you can pass `lambda _: tf.no_op()` and then use + EstimatorSpec.loss to compute and apply gradients. + regularization_losses: A list of additional scalar losses to be added to + the training loss, such as regularization losses. + + Returns: + `EstimatorSpec`. + """ + try: + tpu_estimator_spec = ( + self._create_tpu_estimator_spec(features, mode, logits, labels, + optimizer, train_op_fn, + regularization_losses)) + return tpu_estimator_spec.as_estimator_spec() + except NotImplementedError: + # Not all subclasses of _Head will have implemented + # _create_tpu_estimator_spec. If it is implemented, we can use it to + # create our `EstimatorSpec` here. + raise NotImplementedError( + 'Subclasses of _Head must implement `create_estimator_spec()` or ' + '_create_tpu_estimator_spec().') + + def _create_tpu_estimator_spec(self, + features, + mode, + logits, + labels=None, + optimizer=None, + train_op_fn=None, + regularization_losses=None): + """Returns `model_fn._TPUEstimatorSpec` that a model_fn can return. + + Args: + features: Input `dict` of `Tensor` or `SparseTensor` objects. + mode: Estimator's `ModeKeys`. + logits: logits `Tensor` to be used by the head. + labels: Labels `Tensor`, or `dict` of same. + optimizer: `Optimizer` instance to optimize the loss in TRAIN mode. + Namely, sets `train_op = optimizer.minimize(loss, global_step)`, which + updates variables and increments `global_step`. + train_op_fn: Function that takes a scalar loss `Tensor` and returns an op + to optimize the model with the loss in TRAIN mode. Used if `optimizer` + is `None`. Exactly one of `train_op_fn` and `optimizer` must be set in + TRAIN mode. None is allowed in other modes. If you want to optimize loss + yourself you can pass `lambda _: tf.no_op()` and then use + EstimatorSpec.loss to compute and apply gradients. + regularization_losses: A list of additional scalar losses to be added to + the training loss, such as regularization losses. + + Returns: + A `model_fn._TPUEstimatorSpec' instance. + """ + raise NotImplementedError( + 'TPUEstimatorSpec not available for this model head.') + + +def _check_dense_labels_match_logits_and_reshape(labels, logits, + expected_labels_dimension): + """Checks that labels shape matches logits and reshapes if needed. + + Consider logits of shape [D0, D1, ... DN, logits_dimension]. Then labels + shape must be [D0, D1, ... DN, expected_labels_dimension]. + If expected_labels_dimension=1, labels could be [D0, D1, ... DN] and this + method reshapes them to [D0, D1, ... DN, 1]. + + Args: + labels: labels Tensor. + logits: logits Tensor. + expected_labels_dimension: Integer. + + Returns: + Validated and reshaped labels Tensor. + Raises: + ValueError: If labels is a SparseTensor. + ValueError: If labels shape is statically defined and fails validation. + OpError: If labels shape is not statically defined and fails validation. + """ + if labels is None: + raise ValueError( + 'You must provide a labels Tensor. Given: None. ' + 'Suggested troubleshooting steps: Check that your data contain ' + 'your label feature. Check that your input_fn properly parses and ' + 'returns labels.') + with ops.name_scope(None, 'labels', (labels, logits)) as scope: + labels = tf.compat.v1.convert_to_tensor_or_sparse_tensor(labels) + if isinstance(labels, tf.sparse.SparseTensor): + raise ValueError( + 'SparseTensor labels are not supported. ' + 'labels must be a Tensor of shape [D0, D1, ..., DN, %s], ' + 'e.g. [batch_size, %s]. ' + 'Suggested Fix (1): Check the label feature in your data. ' + 'Each example must contain %s value(s). If not, your choice of label ' + 'was probably incorrect. ' + 'Suggested Fix (2): In your input_fn, use ' + 'tf.sparse_tensor_to_dense() to turn labels into a Tensor.' + '' % (expected_labels_dimension, expected_labels_dimension, + expected_labels_dimension)) + if (labels.shape.ndims is not None and logits.shape.ndims is not None and + labels.shape.ndims == logits.shape.ndims - 1): + labels = tf.compat.v1.expand_dims(labels, -1) + labels_shape = tf.compat.v1.shape(labels) + logits_shape = tf.compat.v1.shape(logits) + err_msg = ( + 'labels shape must be [D0, D1, ... DN, {}]. ' + 'Suggested Fix: check your n_classes argument to the estimator ' + 'and/or the shape of your label.'.format(expected_labels_dimension)) + assert_rank = tf.compat.v1.debugging.assert_rank_at_least( + labels, 2, message=err_msg) + with tf.control_dependencies([assert_rank]): + static_shape = labels.shape + if static_shape.ndims is not None: + dim1 = static_shape[-1] + if (dim1 is not None) and (dim1 != expected_labels_dimension): + raise ValueError('Mismatched label shape. ' + 'Expected labels dimension=%s. Received %s. ' + 'Suggested Fix:' + 'If your classifier expects one-hot encoding label,' + 'check your n_classes argument to the estimator ' + 'and/or the shape of your label. ' + 'Otherwise, check the shape of your label.' % + (expected_labels_dimension, dim1)) + expected_labels_shape = tf.concat( + [logits_shape[:-1], [expected_labels_dimension]], axis=0) + assert_dimension = tf.compat.v1.debugging.assert_equal( + expected_labels_shape, + labels_shape, + message=err_msg, + data=[ + 'expected_labels_shape: ', expected_labels_shape, + 'labels_shape: ', labels_shape + ]) + with tf.control_dependencies([assert_dimension]): + return tf.identity(labels, name=scope) + + +def _get_weights_and_check_match_logits(features, + weight_column, + logits, + allow_per_logit_weights=False): + """Fetches weights from features and checks that the shape matches logits. + + Consider logits of shape [D0, D1, ... DN, logits_dimension]. Weights shape + can be either: + * [D0, D1, ... DN, logits_dimension] if `allow_per_logit_weights=True`. + * [D0, D1, ... DN, 1] + * [D0, D1, ... DN]: In this case, weights is reshaped into + [D0, D1, ... DN, 1] to work with weight broadcasting rules. + + Args: + features: The features dict that contains weights. + weight_column: The weight column. If not given, this method returns 1. + logits: logits Tensor. + allow_per_logit_weights: Boolean. Whether we allow weights along the logits + dimension, namely shape `[D0, D1, ... DN, logits_dimension]`. + + Returns: + Validated and reshaped weights Tensor. + Raises: + ValueError: If the weights `Tensor` cannot be cast into float. + """ + if allow_per_logit_weights: + err_msg = ('weights shape must be [D0, D1, ... DN], [D0, D1, ... DN, 1] or ' + '[D0, D1, ... DN, logits_dimension]') + else: + err_msg = ('weights shape must be [D0, D1, ... DN] or [D0, D1, ... DN, 1]') + with ops.name_scope( + None, 'weights', + values=tuple(six.itervalues(features)) + (logits,)) as scope: + # Fetch the weights. + if weight_column is None: + return 1. + if isinstance(weight_column, six.string_types): + weight_column = tf.feature_column.numeric_column( + key=weight_column, shape=(1,)) + if not isinstance( + weight_column, + (tf.compat.v2.__internal__.feature_column.DenseColumn, feature_column._DenseColumn)): # pylint: disable=protected-access + raise TypeError('Weight column must be either a string or _DenseColumn.' + ' Given type: {}.'.format(type(weight_column))) + weights = weight_column._get_dense_tensor( # pylint: disable=protected-access + feature_column._LazyBuilder(features)) # pylint: disable=protected-access + if not (weights.dtype.is_floating or weights.dtype.is_integer): + raise ValueError('Weight column should be castable to float. ' + 'Given dtype: {}'.format(weights.dtype)) + weights = tf.cast(weights, name='weights', dtype=tf.dtypes.float32) + + # Validate the weights shape. + weights_shape = tf.compat.v1.shape(weights, name='weights_shape') + logits_shape = tf.compat.v1.shape(logits, name='logits_shape') + if (weights.shape.ndims is not None and logits.shape.ndims is not None and + weights.shape.ndims == logits.shape.ndims - 1): + assert_dimension = tf.compat.v1.debugging.assert_equal( + logits_shape[:-1], + weights_shape, + message=err_msg, + data=[ + 'logits_shape: ', logits_shape, 'weights_shape: ', weights_shape + ]) + with tf.control_dependencies([assert_dimension]): + return tf.compat.v1.expand_dims(weights, -1, name=scope) + supported_weights_shape = tf.concat([logits_shape[:-1], [1]], axis=0) + if allow_per_logit_weights: + condition = tf.math.reduce_any([ + tf.reduce_all(tf.math.equal(logits_shape, weights_shape)), + tf.reduce_all(tf.math.equal(supported_weights_shape, weights_shape)) + ]) + assert_dimension = tf.debugging.Assert( + condition=condition, + data=[ + err_msg, 'logits_shape: ', logits_shape, 'weights_shape: ', + weights_shape + ]) + else: + assert_dimension = tf.compat.v1.debugging.assert_equal( + supported_weights_shape, + weights_shape, + message=err_msg, + data=[ + 'logits_shape: ', logits_shape, 'weights_shape: ', weights_shape + ]) + with tf.control_dependencies([assert_dimension]): + return tf.identity(weights, name=scope) + + +def _check_logits_final_dim(logits, expected_logits_dimension): + """Checks that logits shape is [D0, D1, ... DN, logits_dimension].""" + with ops.name_scope(None, 'logits', (logits,)) as scope: + logits = tf.cast(logits, dtype=tf.dtypes.float32) + logits_shape = tf.compat.v1.shape(logits) + assert_rank = tf.compat.v1.debugging.assert_rank_at_least( + logits, + 2, + data=[logits_shape], + message='logits shape must be [D0, D1, ... DN, logits_dimension]') + with tf.control_dependencies([assert_rank]): + static_shape = logits.shape + if static_shape.ndims is not None and static_shape[-1] is not None: + if (isinstance(expected_logits_dimension, int) and + static_shape[-1] != expected_logits_dimension): + raise ValueError( + 'logits shape must be [D0, D1, ... DN, logits_dimension=%s], ' + 'got %s.' % (expected_logits_dimension, static_shape)) + return logits + assert_dimension = tf.compat.v1.debugging.assert_equal( + expected_logits_dimension, + logits_shape[-1], + data=[logits_shape], + message=('logits shape must be [D0, D1, ... DN, ' + 'logits_dimension=%s]' % (expected_logits_dimension,))) + with tf.control_dependencies([assert_dimension]): + return tf.identity(logits, name=scope) + + +def _validate_loss_fn_args(loss_fn): + """Validates loss_fn arguments. + + Required arguments: labels, logits. + Optional arguments: features. + + Args: + loss_fn: The loss function. + + Raises: + ValueError: If the signature is unexpected. + """ + loss_fn_args = function_utils.fn_args(loss_fn) + for required_arg in ['labels', 'logits']: + if required_arg not in loss_fn_args: + raise ValueError('loss_fn must contain argument: {}. ' + 'Given arguments: {}'.format(required_arg, loss_fn_args)) + invalid_args = list(set(loss_fn_args) - set(['labels', 'logits', 'features'])) + if invalid_args: + raise ValueError('loss_fn has unexpected args: {}'.format(invalid_args)) + + +def _validate_n_classes(n_classes): + """Validates n_classes argument. + + Required arguments: n_classes. + + Args: + n_classes: The number of classes. + + Raises: + ValueError: If n_classes is <= 2 and n_classes is a Python integer. + Returns: + n_classes in its original type. + """ + if isinstance(n_classes, int) and (n_classes <= 2): + raise ValueError('n_classes must be > 2: %s.' % n_classes) + + n_classes_as_tensor = ops.convert_to_tensor(n_classes) + assert_n_classes = tf.compat.v1.debugging.assert_greater( + n_classes_as_tensor, 2, message='n_classes must be greater than 2') + with tf.control_dependencies([assert_n_classes]): + tf.no_op() + # Return n_classes in its original type, so that any code + # using the accessor logits_dimension() has the original type. + return n_classes + + +def _call_loss_fn(loss_fn, labels, logits, features, expected_loss_dim=1): + """Calls loss_fn and checks the returned shape. + + Args: + loss_fn: The loss function. + labels: Processed labels Tensor. + logits: Logits Tensor of shape [D0, D1, ... DN, logits_dimension]. + features: Features dict. + expected_loss_dim: The expected last dimension of loss Tensor. + + Returns: + Loss Tensor with shape [D0, D1, ... DN, expected_loss_dim]. + """ + loss_fn_args = function_utils.fn_args(loss_fn) + kwargs = {} + if 'features' in loss_fn_args: + kwargs['features'] = features + with ops.name_scope( + None, + 'call_loss_fn', + values=[labels, logits] + list(six.itervalues(features))): + unweighted_loss = loss_fn(labels=labels, logits=logits, **kwargs) + logits_shape = tf.compat.v1.shape(logits, name='logits_shape') + expected_loss_shape = tf.concat([logits_shape[:-1], [expected_loss_dim]], + axis=0, + name='expected_loss_shape') + loss_shape = tf.compat.v1.shape(unweighted_loss, name='loss_shape') + check_loss_shape_op = tf.debugging.Assert( + tf.reduce_all(tf.math.equal(loss_shape, expected_loss_shape)), + data=[ + 'loss_fn must return Tensor of shape ' + '[D0, D1, ... DN, {}]. '.format(expected_loss_dim), + 'logits_shape: ', logits_shape, 'loss_shape: ', loss_shape + ], + name='check_loss_shape') + with tf.control_dependencies([check_loss_shape_op]): + return tf.identity(unweighted_loss) + + +def _indicator_labels_mean(labels, weights=None, name=None): + with ops.name_scope(name, 'labels_mean', (labels, weights)) as scope: + labels = tf.cast(labels, name='labels', dtype=tf.dtypes.float32) + if weights is not None: + weights = tf.compat.v2.__internal__.ops.broadcast_weights(weights, labels) + return tf.compat.v1.metrics.mean(labels, weights=weights, name=scope) + + +def _all_class_ids(logits, n_classes): + batch_size = tf.compat.v1.shape(logits)[0] + class_id_list = tf.range(n_classes) + return tf.tile( + input=tf.compat.v1.expand_dims(input=class_id_list, axis=0), + multiples=[batch_size, 1]) + + +def _all_classes(logits, n_classes, label_vocabulary=None): + batch_size = tf.compat.v1.shape(logits)[0] + if label_vocabulary: + classes_list = label_vocabulary + else: + classes_list = string_ops.as_string(tf.range(n_classes)) + return tf.tile( + input=tf.compat.v1.expand_dims(input=classes_list, axis=0), + multiples=[batch_size, 1]) + + +def _classification_output(scores, n_classes, label_vocabulary=None): + batch_size = tf.compat.v1.shape(scores)[0] + if label_vocabulary: + export_class_list = label_vocabulary + else: + export_class_list = string_ops.as_string(tf.range(n_classes)) + export_output_classes = tf.tile( + input=tf.compat.v1.expand_dims(input=export_class_list, axis=0), + multiples=[batch_size, 1]) + return export_output.ClassificationOutput( + scores=scores, + # `ClassificationOutput` requires string classes. + classes=export_output_classes) + + +def _accuracy_baseline(labels_mean): + """Return accuracy baseline based on labels mean. + + This is the best the model could do by always predicting one class. + + Args: + labels_mean: Tuple of value and update op. + + Returns: + Tuple of value and update op. + """ + with ops.name_scope(None, 'accuracy_baseline', labels_mean): + value, update_op = labels_mean + return (tf.math.maximum(value, 1. - value, name='value'), + tf.math.maximum(update_op, 1 - update_op, name='update_op')) + + +def _predictions_mean(predictions, weights=None, name=None): + with ops.name_scope(name, 'predictions_mean', + (predictions, weights)) as scope: + predictions = tf.cast( + predictions, name='predictions', dtype=tf.dtypes.float32) + if weights is not None: + weights = tf.compat.v2.__internal__.ops.broadcast_weights(weights, predictions) + return tf.compat.v1.metrics.mean(predictions, weights=weights, name=scope) + + +def _auc(labels, predictions, weights=None, curve='ROC', name=None): + with ops.name_scope(name, 'auc', (predictions, labels, weights)) as scope: + predictions = tf.cast( + predictions, name='predictions', dtype=tf.dtypes.float32) + if weights is not None: + weights = tf.compat.v2.__internal__.ops.broadcast_weights(weights, predictions) + return tf.compat.v1.metrics.auc( + labels=labels, + predictions=predictions, + weights=weights, + curve=curve, + name=scope) + + +def _accuracy_at_threshold(labels, predictions, weights, threshold, name=None): + with ops.name_scope(name, 'accuracy_at_%s' % threshold, + (predictions, labels, weights, threshold)) as scope: + threshold_predictions = tf.compat.v1.to_float( + tf.math.greater_equal(predictions, threshold)) + return tf.compat.v1.metrics.accuracy( + labels=labels, + predictions=threshold_predictions, + weights=weights, + name=scope) + + +def _precision_at_threshold(labels, predictions, weights, threshold, name=None): + with ops.name_scope(name, 'precision_at_%s' % threshold, + (predictions, labels, weights, threshold)) as scope: + precision_tensor, update_op = tf.compat.v1.metrics.precision_at_thresholds( + labels=labels, + predictions=predictions, + thresholds=(threshold,), + weights=weights, + name=scope) + return tf.compat.v1.squeeze(precision_tensor), tf.compat.v1.squeeze( + update_op) + + +def _recall_at_threshold(labels, predictions, weights, threshold, name=None): + with ops.name_scope(name, 'recall_at_%s' % threshold, + (predictions, labels, weights, threshold)) as scope: + precision_tensor, update_op = tf.compat.v1.metrics.recall_at_thresholds( + labels=labels, + predictions=predictions, + thresholds=(threshold,), + weights=weights, + name=scope) + return tf.compat.v1.squeeze(precision_tensor), tf.compat.v1.squeeze( + update_op) + + +def _multi_class_head_with_softmax_cross_entropy_loss( + n_classes, + weight_column=None, + label_vocabulary=None, + loss_reduction=tf.compat.v1.losses.Reduction.SUM, + loss_fn=None, + name=None): + """Creates a '_Head' for multi class classification. + + The head expects `logits` with shape `[D0, D1, ... DN, n_classes]`. + In many applications, the shape is `[batch_size, n_classes]`. + + `labels` must be a dense `Tensor` with shape matching `logits`, namely + `[D0, D1, ... DN, 1]`. If `label_vocabulary` given, `labels` must be a string + `Tensor` with values from the vocabulary. If `label_vocabulary` is not given, + `labels` must be an integer `Tensor` with values specifying the class index. + + If `weight_column` is specified, weights must be of shape + `[D0, D1, ... DN]`, or `[D0, D1, ... DN, 1]`. + + The loss is the weighted sum over the input dimensions. Namely, if the input + labels have shape `[batch_size, 1]`, the loss is the weighted sum over + `batch_size`. + + Also supports custom `loss_fn`. `loss_fn` takes `(labels, logits)` or + `(labels, logits, features)` as arguments and returns unreduced loss with + shape `[D0, D1, ... DN, 1]`. `loss_fn` must support integer `labels` with + shape `[D0, D1, ... DN, 1]`. Namely, the head applies `label_vocabulary` to + the input labels before passing them to `loss_fn`. + + Args: + n_classes: Number of classes, must be greater than 2 (for 2 classes, use + `_BinaryLogisticHeadWithSigmoidCrossEntropyLoss`). + weight_column: A string or a `_NumericColumn` created by + `tf.feature_column.numeric_column` defining feature column representing + weights. It is used to down weight or boost examples during training. It + will be multiplied by the loss of the example. + label_vocabulary: A list or tuple of strings representing possible label + values. If it is not given, that means labels are already encoded as an + integer within [0, n_classes). If given, labels must be of string type and + have any value in `label_vocabulary`. Note that errors will be raised if + `label_vocabulary` is not provided but labels are strings. + loss_reduction: One of `tf.losses.Reduction` except `NONE`. Describes how to + reduce training loss over batch. Defaults to `SUM`. + loss_fn: Optional loss function. + name: name of the head. If provided, summary and metrics keys will be + suffixed by `"/" + name`. Also used as `name_scope` when creating ops. + + Returns: + An instance of `_Head` for multi class classification. + + Raises: + ValueError: If `n_classes`, `label_vocabulary` or `loss_reduction` is + invalid. + """ + if label_vocabulary is not None and not isinstance(label_vocabulary, + (list, tuple)): + raise ValueError( + 'label_vocabulary should be a list or a tuple. Given type: {}'.format( + type(label_vocabulary))) + if (loss_reduction not in tf.compat.v1.losses.Reduction.all() or + loss_reduction == tf.compat.v1.losses.Reduction.NONE): + raise ValueError('Invalid loss_reduction: {}'.format(loss_reduction)) + if loss_fn: + _validate_loss_fn_args(loss_fn) + return _MultiClassHeadWithSoftmaxCrossEntropyLoss( + n_classes=n_classes, + weight_column=weight_column, + label_vocabulary=label_vocabulary, + loss_reduction=loss_reduction, + loss_fn=loss_fn, + name=name) + + +class _MultiClassHeadWithSoftmaxCrossEntropyLoss(_Head): + """See `_multi_class_head_with_softmax_cross_entropy_loss`.""" + + def __init__(self, + n_classes, + weight_column=None, + label_vocabulary=None, + loss_reduction=tf.compat.v1.losses.Reduction.SUM, + loss_fn=None, + name=None): + if n_classes is None: + raise ValueError('n_classes cannot be None') + self._n_classes = _validate_n_classes(n_classes) + self._weight_column = weight_column + self._label_vocabulary = label_vocabulary + self._loss_reduction = loss_reduction + self._loss_fn = loss_fn + self._name = name + + @property + def name(self): + return self._name + + @property + def logits_dimension(self): + return self._n_classes + + def _eval_metric_ops(self, labels, class_ids, weights, unreduced_loss, + regularization_loss): + """Returns the Eval metric ops.""" + with ops.name_scope( + None, 'metrics', + (labels, class_ids, weights, unreduced_loss, regularization_loss)): + keys = metric_keys.MetricKeys + metric_ops = { + # Estimator already adds a metric for loss. + # TODO(xiejw): Any other metrics? + _summary_key(self._name, keys.LOSS_MEAN): + tf.compat.v1.metrics.mean( + values=unreduced_loss, weights=weights, name=keys.LOSS_MEAN), + _summary_key(self._name, keys.ACCURACY): + tf.compat.v1.metrics.accuracy( + labels=labels, + predictions=class_ids, + weights=weights, + name=keys.ACCURACY), + } + if regularization_loss is not None: + metric_ops[_summary_key(self._name, keys.LOSS_REGULARIZATION)] = ( + tf.compat.v1.metrics.mean( + values=regularization_loss, name=keys.LOSS_REGULARIZATION)) + return metric_ops + + def _label_ids(self, labels): + """Converts labels to integer id space.""" + if self._label_vocabulary is None: + if not labels.dtype.is_integer: + raise ValueError( + 'Labels dtype should be integer. Instead got {}.'.format( + labels.dtype)) + label_ids = labels + else: + if labels.dtype != tf.dtypes.string: + raise ValueError('Labels dtype should be string if there is a ' + 'vocabulary. Instead got {}'.format(labels.dtype)) + label_ids = lookup_ops.index_table_from_tensor( + vocabulary_list=tuple(self._label_vocabulary), + name='class_id_lookup').lookup(labels) + return _assert_range(label_ids, self._n_classes) + + def create_loss(self, features, mode, logits, labels): + """See `Head`.""" + del mode # Unused for this head. + logits = ops.convert_to_tensor(logits) + labels = _check_dense_labels_match_logits_and_reshape( + labels=labels, logits=logits, expected_labels_dimension=1) + label_ids = self._label_ids(labels) + if self._loss_fn: + unweighted_loss = _call_loss_fn( + loss_fn=self._loss_fn, + labels=label_ids, + logits=logits, + features=features, + expected_loss_dim=1) + else: + unweighted_loss = tf.compat.v1.losses.sparse_softmax_cross_entropy( + labels=label_ids, + logits=logits, + reduction=tf.compat.v1.losses.Reduction.NONE) + # Restore the squeezed dim, so unweighted_loss matches the weights shape. + unweighted_loss = tf.compat.v1.expand_dims(unweighted_loss, axis=-1) + weights = _get_weights_and_check_match_logits( + features=features, weight_column=self._weight_column, logits=logits) + training_loss = tf.compat.v1.losses.compute_weighted_loss( + unweighted_loss, weights=weights, reduction=self._loss_reduction) + return LossSpec( + training_loss=training_loss, + unreduced_loss=unweighted_loss, + weights=weights, + processed_labels=label_ids) + + def _create_tpu_estimator_spec(self, + features, + mode, + logits, + labels=None, + optimizer=None, + train_op_fn=None, + regularization_losses=None): + """Returns a `model_fn._TPUEstimatorSpec`. + + Args: + features: Input `dict` of `Tensor` or `SparseTensor` objects. + mode: Estimator's `ModeKeys`. + logits: logits `Tensor` with shape `[D0, D1, ... DN, logits_dimension]`. + For many applications, the shape is `[batch_size, logits_dimension]`. + labels: Labels integer or string `Tensor` with shape matching `logits`, + namely `[D0, D1, ... DN, 1]` or `[D0, D1, ... DN]`. `labels` is required + argument when `mode` equals `TRAIN` or `EVAL`. + optimizer: `Optimizer` instance to optimize the loss in TRAIN mode. + Namely, sets `train_op = optimizer.minimize(loss, global_step)`, which + updates variables and increments `global_step`. + train_op_fn: Function that takes a scalar loss `Tensor` and returns + `train_op`. Used if `optimizer` is `None`. + regularization_losses: A list of additional scalar losses to be added to + the training loss, such as regularization losses. These losses are + usually expressed as a batch average, so for best results users need to + set `loss_reduction=SUM_OVER_BATCH_SIZE` when creating the head to avoid + scaling errors. + + Returns: + A `model_fn._TPUEstimatorSpec` instance. + Raises: + ValueError: If both `train_op_fn` and `optimizer` are `None` in TRAIN + mode, or if both are set. + """ + with ops.name_scope(self._name, 'head'): + logits = _check_logits_final_dim(logits, self.logits_dimension) + + # Predict. + pred_keys = prediction_keys.PredictionKeys + with ops.name_scope(None, 'predictions', (logits,)): + all_class_ids = _all_class_ids(logits, self._n_classes) + all_classes = _all_classes( + logits, self._n_classes, label_vocabulary=self._label_vocabulary) + # class_ids's shape is [D0, D1, ... DN]. + class_ids = tf.compat.v1.math.argmax( + logits, axis=-1, name=pred_keys.CLASS_IDS) + class_ids = tf.compat.v1.expand_dims(class_ids, axis=-1) + if self._label_vocabulary: + table = lookup_ops.index_to_string_table_from_tensor( + vocabulary_list=self._label_vocabulary, + name='class_string_lookup') + classes = table.lookup(class_ids) + else: + classes = tf.strings.as_string(class_ids, name='str_classes') + + probabilities = tf.compat.v1.nn.softmax( + logits, name=pred_keys.PROBABILITIES) + predictions = { + pred_keys.LOGITS: logits, + pred_keys.PROBABILITIES: probabilities, + # Expand to [batch_size, 1] + pred_keys.CLASS_IDS: class_ids, + pred_keys.CLASSES: classes, + pred_keys.ALL_CLASS_IDS: all_class_ids, + pred_keys.ALL_CLASSES: all_classes, + } + if mode == ModeKeys.PREDICT: + classifier_output = _classification_output( + scores=probabilities, + n_classes=self._n_classes, + label_vocabulary=self._label_vocabulary) + return model_fn._TPUEstimatorSpec( # pylint: disable=protected-access + mode=ModeKeys.PREDICT, + predictions=predictions, + export_outputs={ + _DEFAULT_SERVING_KEY: classifier_output, + _CLASSIFY_SERVING_KEY: classifier_output, + _PREDICT_SERVING_KEY: export_output.PredictOutput(predictions) + }) + + training_loss, unreduced_loss, weights, label_ids = self.create_loss( + features=features, mode=mode, logits=logits, labels=labels) + if regularization_losses: + regularization_loss = tf.math.add_n(regularization_losses) + regularized_training_loss = tf.math.add_n( + [training_loss, regularization_loss]) + else: + regularization_loss = None + regularized_training_loss = training_loss + # Eval. + if mode == ModeKeys.EVAL: + return model_fn._TPUEstimatorSpec( # pylint: disable=protected-access + mode=ModeKeys.EVAL, + predictions=predictions, + loss=regularized_training_loss, + eval_metrics=_create_eval_metrics_tuple( + self._eval_metric_ops, { + 'labels': label_ids, + 'class_ids': class_ids, + 'weights': weights, + 'unreduced_loss': unreduced_loss, + 'regularization_loss': regularization_loss + })) + + # Train. + if optimizer is not None: + if train_op_fn is not None: + raise ValueError('train_op_fn and optimizer cannot both be set.') + train_op = optimizer.minimize( + regularized_training_loss, + global_step=tf.compat.v1.train.get_global_step()) + elif train_op_fn is not None: + train_op = train_op_fn(regularized_training_loss) + else: + raise ValueError('train_op_fn and optimizer cannot both be None.') + train_op = _append_update_ops(train_op) + # Only summarize mean_loss for SUM reduction to preserve backwards + # compatibility. Otherwise skip it to avoid unnecessary computation. + if self._loss_reduction == tf.compat.v1.losses.Reduction.SUM: + example_weight_sum = tf.math.reduce_sum( + weights * tf.compat.v1.ones_like(unreduced_loss)) + mean_loss = training_loss / example_weight_sum + else: + mean_loss = None + with ops.name_scope(''): + keys = metric_keys.MetricKeys + tf.compat.v1.summary.scalar( + _summary_key(self._name, keys.LOSS), regularized_training_loss) + if mean_loss is not None: + tf.compat.v1.summary.scalar( + _summary_key(self._name, keys.LOSS_MEAN), mean_loss) + if regularization_loss is not None: + tf.compat.v1.summary.scalar( + _summary_key(self._name, keys.LOSS_REGULARIZATION), + regularization_loss) + return model_fn._TPUEstimatorSpec( # pylint: disable=protected-access + mode=ModeKeys.TRAIN, + predictions=predictions, + loss=regularized_training_loss, + train_op=train_op) + + +def _binary_logistic_head_with_sigmoid_cross_entropy_loss( + weight_column=None, + thresholds=None, + label_vocabulary=None, + loss_reduction=tf.compat.v1.losses.Reduction.SUM, + loss_fn=None, + name=None): + """Creates a `_Head` for single label binary classification. + + This head uses `sigmoid_cross_entropy_with_logits` loss. + + The head expects `logits` with shape `[D0, D1, ... DN, 1]`. + In many applications, the shape is `[batch_size, 1]`. + + `labels` must be a dense `Tensor` with shape matching `logits`, namely + `[D0, D1, ... DN, 1]`. If `label_vocabulary` given, `labels` must be a string + `Tensor` with values from the vocabulary. If `label_vocabulary` is not given, + `labels` must be float `Tensor` with values in the interval `[0, 1]`. + + If `weight_column` is specified, weights must be of shape + `[D0, D1, ... DN]`, or `[D0, D1, ... DN, 1]`. + + The loss is the weighted sum over the input dimensions. Namely, if the input + labels have shape `[batch_size, 1]`, the loss is the weighted sum over + `batch_size`. + + Also supports custom `loss_fn`. `loss_fn` takes `(labels, logits)` or + `(labels, logits, features)` as arguments and returns unreduced loss with + shape `[D0, D1, ... DN, 1]`. `loss_fn` must support float `labels` with + shape `[D0, D1, ... DN, 1]`. Namely, the head applies `label_vocabulary` to + the input labels before passing them to `loss_fn`. + + Args: + weight_column: A string or a `_NumericColumn` created by + `tf.feature_column.numeric_column` defining feature column representing + weights. It is used to down weight or boost examples during training. It + will be multiplied by the loss of the example. + thresholds: Iterable of floats in the range `(0, 1)`. For binary + classification metrics such as precision and recall, an eval metric is + generated for each threshold value. This threshold is applied to the + logistic values to determine the binary classification (i.e., above the + threshold is `true`, below is `false`. + label_vocabulary: A list or tuple of strings representing possible label + values. If it is not given, that means labels are already encoded within + [0, 1]. If given, labels must be string type and have any value in + `label_vocabulary`. Note that errors will be raised if `label_vocabulary` + is not provided but labels are strings. + loss_reduction: One of `tf.losses.Reduction` except `NONE`. Describes how to + reduce training loss over batch. Defaults to `SUM`. + loss_fn: Optional loss function. + name: name of the head. If provided, summary and metrics keys will be + suffixed by `"/" + name`. Also used as `name_scope` when creating ops. + + Returns: + An instance of `_Head` for binary classification. + + Raises: + ValueError: If `thresholds` contains a value outside of `(0, 1)`. + ValueError: If `loss_reduction` is invalid. + TypeError: if `label_vocabulary` has invalid type. + """ + thresholds = tuple(thresholds) if thresholds else tuple() + if label_vocabulary is not None and not isinstance(label_vocabulary, + (list, tuple)): + raise TypeError( + 'label_vocabulary should be a list or tuple. Given type: {}'.format( + type(label_vocabulary))) + + for threshold in thresholds: + if (threshold <= 0.0) or (threshold >= 1.0): + raise ValueError('thresholds not in (0, 1): {}.'.format((thresholds,))) + if (loss_reduction not in tf.compat.v1.losses.Reduction.all() or + loss_reduction == tf.compat.v1.losses.Reduction.NONE): + raise ValueError('Invalid loss_reduction: {}'.format(loss_reduction)) + if loss_fn: + _validate_loss_fn_args(loss_fn) + return _BinaryLogisticHeadWithSigmoidCrossEntropyLoss( + weight_column=weight_column, + thresholds=thresholds, + label_vocabulary=label_vocabulary, + loss_reduction=loss_reduction, + loss_fn=loss_fn, + name=name) + + +class _BinaryLogisticHeadWithSigmoidCrossEntropyLoss(_Head): + """See `_binary_logistic_head_with_sigmoid_cross_entropy_loss`.""" + + def __init__(self, + weight_column=None, + thresholds=None, + label_vocabulary=None, + loss_reduction=tf.compat.v1.losses.Reduction.SUM, + loss_fn=None, + name=None): + self._weight_column = weight_column + self._thresholds = tuple(thresholds) if thresholds else tuple() + self._label_vocabulary = label_vocabulary + self._loss_reduction = loss_reduction + self._loss_fn = loss_fn + self._name = name + + @property + def name(self): + return self._name + + @property + def logits_dimension(self): + return 1 + + def _eval_metric_ops(self, labels, logits, logistic, class_ids, weights, + unreduced_loss, regularization_loss): + with ops.name_scope(None, 'metrics', + (labels, logits, logistic, class_ids, weights, + unreduced_loss, regularization_loss)): + keys = metric_keys.MetricKeys + labels_mean = _indicator_labels_mean( + labels=labels, weights=weights, name=keys.LABEL_MEAN) + metric_ops = { + # Estimator already adds a metric for loss. + _summary_key(self._name, keys.LOSS_MEAN): + tf.compat.v1.metrics.mean( + values=unreduced_loss, weights=weights, name=keys.LOSS_MEAN), + _summary_key(self._name, keys.ACCURACY): + tf.compat.v1.metrics.accuracy( + labels=labels, + predictions=class_ids, + weights=weights, + name=keys.ACCURACY), + _summary_key(self._name, keys.PRECISION): + tf.compat.v1.metrics.precision( + labels=labels, + predictions=class_ids, + weights=weights, + name=keys.PRECISION), + _summary_key(self._name, keys.RECALL): + tf.compat.v1.metrics.recall( + labels=labels, + predictions=class_ids, + weights=weights, + name=keys.RECALL), + _summary_key(self._name, keys.PREDICTION_MEAN): + _predictions_mean( + predictions=logistic, + weights=weights, + name=keys.PREDICTION_MEAN), + _summary_key(self._name, keys.LABEL_MEAN): + labels_mean, + _summary_key(self._name, keys.ACCURACY_BASELINE): + _accuracy_baseline(labels_mean), + _summary_key(self._name, keys.AUC): + _auc( + labels=labels, + predictions=logistic, + weights=weights, + name=keys.AUC), + _summary_key(self._name, keys.AUC_PR): + _auc( + labels=labels, + predictions=logistic, + weights=weights, + curve='PR', + name=keys.AUC_PR) + } + if regularization_loss is not None: + metric_ops[_summary_key(self._name, keys.LOSS_REGULARIZATION)] = ( + tf.compat.v1.metrics.mean( + values=regularization_loss, name=keys.LOSS_REGULARIZATION)) + for threshold in self._thresholds: + accuracy_key = keys.ACCURACY_AT_THRESHOLD % threshold + metric_ops[_summary_key(self._name, + accuracy_key)] = _accuracy_at_threshold( + labels=labels, + predictions=logistic, + weights=weights, + threshold=threshold, + name=accuracy_key) + # Precision for positive examples. + precision_key = keys.PRECISION_AT_THRESHOLD % threshold + metric_ops[_summary_key(self._name, + precision_key)] = _precision_at_threshold( + labels=labels, + predictions=logistic, + weights=weights, + threshold=threshold, + name=precision_key) + # Recall for positive examples. + recall_key = keys.RECALL_AT_THRESHOLD % threshold + metric_ops[_summary_key(self._name, recall_key)] = _recall_at_threshold( + labels=labels, + predictions=logistic, + weights=weights, + threshold=threshold, + name=recall_key) + return metric_ops + + def create_loss(self, features, mode, logits, labels): + """See `Head`.""" + del mode # Unused for this head. + logits = ops.convert_to_tensor(logits) + labels = _check_dense_labels_match_logits_and_reshape( + labels=labels, logits=logits, expected_labels_dimension=1) + if self._label_vocabulary is not None: + labels = lookup_ops.index_table_from_tensor( + vocabulary_list=tuple(self._label_vocabulary), + name='class_id_lookup').lookup(labels) + labels = tf.cast(labels, dtype=tf.dtypes.float32) + labels = _assert_range(labels, n_classes=2) + if self._loss_fn: + unweighted_loss = _call_loss_fn( + loss_fn=self._loss_fn, + labels=labels, + logits=logits, + features=features, + expected_loss_dim=1) + else: + unweighted_loss = tf.compat.v1.nn.sigmoid_cross_entropy_with_logits( + labels=labels, logits=logits) + weights = _get_weights_and_check_match_logits( + features=features, weight_column=self._weight_column, logits=logits) + training_loss = tf.compat.v1.losses.compute_weighted_loss( + unweighted_loss, weights=weights, reduction=self._loss_reduction) + return LossSpec( + training_loss=training_loss, + unreduced_loss=unweighted_loss, + weights=weights, + processed_labels=labels) + + def _create_tpu_estimator_spec(self, + features, + mode, + logits, + labels=None, + optimizer=None, + train_op_fn=None, + regularization_losses=None): + """Returns an `EstimatorSpec`. + + Args: + features: Input `dict` of `Tensor` or `SparseTensor` objects. + mode: Estimator's `ModeKeys`. + logits: logits `Tensor` with shape `[D0, D1, ... DN, 1]`. For many + applications, the shape is `[batch_size, 1]`. + labels: Labels integer or string `Tensor` with shape matching `logits`, + namely `[D0, D1, ... DN, 1]` or `[D0, D1, ... DN]`. `labels` is required + argument when `mode` equals `TRAIN` or `EVAL`. + optimizer: `Optimizer` instance to optimize the loss in TRAIN mode. + Namely, sets `train_op = optimizer.minimize(loss, global_step)`, which + updates variables and increments `global_step`. + train_op_fn: Function that takes a scalar loss `Tensor` and returns + `train_op`. Used if `optimizer` is `None`. + regularization_losses: A list of additional scalar losses to be added to + the training loss, such as regularization losses. These losses are + usually expressed as a batch average, so for best results users need to + set `loss_reduction=SUM_OVER_BATCH_SIZE` when creating the head to avoid + scaling errors. + + Returns: + `EstimatorSpec`. + Raises: + ValueError: If both `train_op_fn` and `optimizer` are `None` in TRAIN + mode, or if both are set. + """ + # Predict. + with ops.name_scope(self._name, 'head'): + with ops.name_scope(None, 'predictions', (logits,)): + pred_keys = prediction_keys.PredictionKeys + logits = _check_logits_final_dim(logits, self.logits_dimension) + logistic = tf.math.sigmoid(logits, name=pred_keys.LOGISTIC) + two_class_logits = tf.concat((tf.compat.v1.zeros_like(logits), logits), + axis=-1, + name='two_class_logits') + probabilities = tf.compat.v1.nn.softmax( + two_class_logits, name=pred_keys.PROBABILITIES) + class_ids = tf.compat.v1.math.argmax( + two_class_logits, axis=-1, name=pred_keys.CLASS_IDS) + class_ids = tf.compat.v1.expand_dims(class_ids, axis=-1) + all_class_ids = _all_class_ids(logits, n_classes=2) + all_classes = _all_classes( + logits, n_classes=2, label_vocabulary=self._label_vocabulary) + + if self._label_vocabulary: + table = lookup_ops.index_to_string_table_from_tensor( + vocabulary_list=self._label_vocabulary, + name='class_string_lookup') + classes = table.lookup(class_ids) + else: + classes = string_ops.as_string(class_ids, name='str_classes') + predictions = { + pred_keys.LOGITS: logits, + pred_keys.LOGISTIC: logistic, + pred_keys.PROBABILITIES: probabilities, + pred_keys.CLASS_IDS: class_ids, + pred_keys.CLASSES: classes, + pred_keys.ALL_CLASS_IDS: all_class_ids, + pred_keys.ALL_CLASSES: all_classes, + } + if mode == ModeKeys.PREDICT: + classifier_output = _classification_output( + scores=probabilities, + n_classes=2, + label_vocabulary=self._label_vocabulary) + return model_fn._TPUEstimatorSpec( # pylint: disable=protected-access + mode=ModeKeys.PREDICT, + predictions=predictions, + export_outputs={ + _DEFAULT_SERVING_KEY: classifier_output, + _CLASSIFY_SERVING_KEY: classifier_output, + _REGRESS_SERVING_KEY: export_output.RegressionOutput( + value=logistic), + _PREDICT_SERVING_KEY: export_output.PredictOutput(predictions) + }) + + (training_loss, unreduced_loss, weights, processed_labels) = ( + self.create_loss( + features=features, mode=mode, logits=logits, labels=labels)) + if regularization_losses: + regularization_loss = tf.math.add_n(regularization_losses) + regularized_training_loss = tf.math.add_n( + [training_loss, regularization_loss]) + else: + regularization_loss = None + regularized_training_loss = training_loss + + # Eval. + if mode == ModeKeys.EVAL: + return model_fn._TPUEstimatorSpec( # pylint: disable=protected-access + mode=ModeKeys.EVAL, + predictions=predictions, + loss=regularized_training_loss, + eval_metrics=_create_eval_metrics_tuple( + self._eval_metric_ops, { + 'labels': processed_labels, + 'logits': logits, + 'logistic': logistic, + 'class_ids': class_ids, + 'weights': weights, + 'unreduced_loss': unreduced_loss, + 'regularization_loss': regularization_loss + })) + + # Train. + if optimizer is not None: + if train_op_fn is not None: + raise ValueError('train_op_fn and optimizer cannot both be set.') + train_op = optimizer.minimize( + regularized_training_loss, + global_step=tf.compat.v1.train.get_global_step()) + elif train_op_fn is not None: + train_op = train_op_fn(regularized_training_loss) + else: + raise ValueError('train_op_fn and optimizer cannot both be None.') + train_op = _append_update_ops(train_op) + # Only summarize mean_loss for SUM reduction to preserve backwards + # compatibility. Otherwise skip it to avoid unnecessary computation. + if self._loss_reduction == tf.compat.v1.losses.Reduction.SUM: + example_weight_sum = tf.math.reduce_sum( + weights * tf.compat.v1.ones_like(unreduced_loss)) + mean_loss = training_loss / example_weight_sum + else: + mean_loss = None + with ops.name_scope(''): + keys = metric_keys.MetricKeys + tf.compat.v1.summary.scalar( + _summary_key(self._name, keys.LOSS), regularized_training_loss) + if mean_loss is not None: + tf.compat.v1.summary.scalar( + _summary_key(self._name, keys.LOSS_MEAN), mean_loss) + if regularization_loss is not None: + tf.compat.v1.summary.scalar( + _summary_key(self._name, keys.LOSS_REGULARIZATION), + regularization_loss) + return model_fn._TPUEstimatorSpec( # pylint: disable=protected-access + mode=ModeKeys.TRAIN, + predictions=predictions, + loss=regularized_training_loss, + train_op=train_op) + + +def _regression_head(weight_column=None, + label_dimension=1, + loss_reduction=tf.compat.v1.losses.Reduction.SUM, + loss_fn=None, + inverse_link_fn=None, + name=None): + """Creates a `_Head` for regression using the `mean_squared_error` loss. + + The loss is the weighted sum over all input dimensions. Namely, if the input + labels have shape `[batch_size, label_dimension]`, the loss is the weighted + sum over both `batch_size` and `label_dimension`. + + The head expects `logits` with shape `[D0, D1, ... DN, label_dimension]`. + In many applications, the shape is `[batch_size, label_dimension]`. + + The `labels` shape must match `logits`, namely + `[D0, D1, ... DN, label_dimension]`. If `label_dimension=1`, shape + `[D0, D1, ... DN]` is also supported. + + If `weight_column` is specified, weights must be of shape + `[D0, D1, ... DN]`, `[D0, D1, ... DN, 1]` or + `[D0, D1, ... DN, label_dimension]`. + + Supports custom `loss_fn`. `loss_fn` takes `(labels, logits)` or + `(labels, logits, features)` as arguments and returns unreduced loss with + shape `[D0, D1, ... DN, label_dimension]`. + + Also supports custom `inverse_link_fn`, also known as 'mean function'. + `inverse_link_fn` takes `logits` as argument and returns predicted values. + This function is the inverse of the link function defined in + https://en.wikipedia.org/wiki/Generalized_linear_model#Link_function + Namely, for poisson regression, set `inverse_link_fn=tf.exp`. + + Args: + weight_column: A string or a `_NumericColumn` created by + `tf.feature_column.numeric_column` defining feature column representing + weights. It is used to down weight or boost examples during training. It + will be multiplied by the loss of the example. + label_dimension: Number of regression labels per example. This is the size + of the last dimension of the labels `Tensor` (typically, this has shape + `[batch_size, label_dimension]`). + loss_reduction: One of `tf.losses.Reduction` except `NONE`. Describes how to + reduce training loss over batch. Defaults to `SUM`. + loss_fn: Optional loss function. Defaults to `mean_squared_error`. + inverse_link_fn: Optional inverse link function, also known as 'mean + function'. Defaults to identity. + name: name of the head. If provided, summary and metrics keys will be + suffixed by `"/" + name`. Also used as `name_scope` when creating ops. + + Returns: + An instance of `_Head` for linear regression. + + Raises: + ValueError: If `label_dimension` or `loss_reduction` is invalid. + """ + if (loss_reduction not in tf.compat.v1.losses.Reduction.all() or + loss_reduction == tf.compat.v1.losses.Reduction.NONE): + raise ValueError('Invalid loss_reduction: {}'.format(loss_reduction)) + if loss_fn: + _validate_loss_fn_args(loss_fn) + return _RegressionHeadWithMeanSquaredErrorLoss( + weight_column=weight_column, + label_dimension=label_dimension, + loss_reduction=loss_reduction, + loss_fn=loss_fn, + inverse_link_fn=inverse_link_fn, + name=name) + + +class _RegressionHeadWithMeanSquaredErrorLoss(_Head): + """`Head` for regression using the mean squared loss.""" + + def __init__(self, + label_dimension, + weight_column=None, + loss_reduction=tf.compat.v1.losses.Reduction.SUM, + loss_fn=None, + inverse_link_fn=None, + name=None): + """`Head` for regression.""" + if label_dimension < 1: + raise ValueError('Invalid label_dimension %s.' % label_dimension) + self._logits_dimension = label_dimension + self._weight_column = weight_column + self._loss_reduction = loss_reduction + self._loss_fn = loss_fn + self._inverse_link_fn = inverse_link_fn + self._name = name + + @property + def name(self): + return self._name + + @property + def logits_dimension(self): + return self._logits_dimension + + def create_loss(self, features, mode, logits, labels): + """See `Head`.""" + del mode # Unused for this head. + logits = ops.convert_to_tensor(logits) + labels = _check_dense_labels_match_logits_and_reshape( + labels=labels, + logits=logits, + expected_labels_dimension=self._logits_dimension) + labels = tf.cast(labels, dtype=tf.dtypes.float32) + if self._loss_fn: + unweighted_loss = _call_loss_fn( + loss_fn=self._loss_fn, + labels=labels, + logits=logits, + features=features, + expected_loss_dim=self._logits_dimension) + else: + unweighted_loss = tf.compat.v1.losses.mean_squared_error( + labels=labels, + predictions=logits, + reduction=tf.compat.v1.losses.Reduction.NONE) + weights = _get_weights_and_check_match_logits( + features=features, + weight_column=self._weight_column, + logits=logits, + allow_per_logit_weights=True) + training_loss = tf.compat.v1.losses.compute_weighted_loss( + unweighted_loss, weights=weights, reduction=self._loss_reduction) + return LossSpec( + training_loss=training_loss, + unreduced_loss=unweighted_loss, + weights=weights, + processed_labels=labels) + + def _eval_metric_ops(self, predicted_value, labels, weights, unreduced_loss, + regularization_loss): + """Returns the Eval metric ops.""" + keys = metric_keys.MetricKeys + # Estimator already adds a metric for loss. + eval_metric_ops = { + _summary_key(self._name, keys.LOSS_MEAN): + tf.compat.v1.metrics.mean(values=unreduced_loss, weights=weights), + _summary_key(self._name, keys.PREDICTION_MEAN): + _predictions_mean( + predictions=predicted_value, + weights=weights, + name=keys.PREDICTION_MEAN), + _summary_key(self._name, keys.LABEL_MEAN): + tf.compat.v1.metrics.mean(values=labels, weights=weights) + } + if regularization_loss is not None: + regularization_loss_key = _summary_key(self._name, + keys.LOSS_REGULARIZATION) + eval_metric_ops[regularization_loss_key] = tf.compat.v1.metrics.mean( + values=regularization_loss, name=keys.LOSS_REGULARIZATION) + return eval_metric_ops + + def _create_tpu_estimator_spec(self, + features, + mode, + logits, + labels=None, + optimizer=None, + train_op_fn=None, + regularization_losses=None): + """Returns an `EstimatorSpec`. + + Args: + features: Input `dict` of `Tensor` or `SparseTensor` objects. + mode: Estimator's `ModeKeys`. + logits: logits `Tensor` with shape `[D0, D1, ... DN, logits_dimension]`. + For many applications, the shape is `[batch_size, logits_dimension]`. + labels: Labels `Tensor` with shape matching `logits`, namely `[D0, D1, ... + DN, logits_dimension]`. When `logits_dimension=1`, shape `[D0, D1, ... + DN]` is also supported. `labels` is required argument when `mode` equals + `TRAIN` or `EVAL`. + optimizer: `Optimizer` instance to optimize the loss in TRAIN mode. + Namely, sets `train_op = optimizer.minimize(loss, global_step)`, which + updates variables and increments `global_step`. + train_op_fn: Function that takes a scalar loss `Tensor` and returns + `train_op`. Used if `optimizer` is `None`. + regularization_losses: A list of additional scalar losses to be added to + the training loss, such as regularization losses. These losses are + usually expressed as a batch average, so for best results users need to + set `loss_reduction=SUM_OVER_BATCH_SIZE` when creating the head to avoid + scaling errors. + + Returns: + A `model_fn._TPUEstimatorSpec` instance. + Raises: + ValueError: If both `train_op_fn` and `optimizer` are `None` in TRAIN + mode, or if both are set. + """ + # Predict. + with ops.name_scope(self._name, 'head'): + logits = _check_logits_final_dim(logits, self._logits_dimension) + if self._inverse_link_fn: + predicted_value = self._inverse_link_fn(logits) + predictions = { + prediction_keys.PredictionKeys.PREDICTIONS: predicted_value, + prediction_keys.PredictionKeys.LOGITS: logits, + } + else: + predicted_value = logits + predictions = { + prediction_keys.PredictionKeys.PREDICTIONS: predicted_value + } + if mode == ModeKeys.PREDICT: + regression_output = export_output.RegressionOutput( + value=predicted_value) + return model_fn._TPUEstimatorSpec( # pylint: disable=protected-access + mode=ModeKeys.PREDICT, + predictions=predictions, + export_outputs={ + _DEFAULT_SERVING_KEY: regression_output, + _REGRESS_SERVING_KEY: regression_output, + _PREDICT_SERVING_KEY: export_output.PredictOutput(predictions) + }) + + training_loss, unreduced_loss, weights, _ = self.create_loss( + features=features, mode=mode, logits=logits, labels=labels) + if regularization_losses: + regularization_loss = tf.math.add_n(regularization_losses) + regularized_training_loss = tf.math.add_n( + [training_loss, regularization_loss]) + else: + regularization_loss = None + regularized_training_loss = training_loss + + # Eval. + if mode == ModeKeys.EVAL: + return model_fn._TPUEstimatorSpec( # pylint: disable=protected-access + mode=ModeKeys.EVAL, + predictions=predictions, + loss=regularized_training_loss, + eval_metrics=_create_eval_metrics_tuple( + self._eval_metric_ops, { + 'predicted_value': predicted_value, + 'labels': labels, + 'weights': weights, + 'unreduced_loss': unreduced_loss, + 'regularization_loss': regularization_loss, + })) + + # Train. + if optimizer is not None: + if train_op_fn is not None: + raise ValueError('train_op_fn and optimizer cannot both be set.') + train_op = optimizer.minimize( + regularized_training_loss, + global_step=tf.compat.v1.train.get_global_step()) + elif train_op_fn is not None: + train_op = train_op_fn(regularized_training_loss) + else: + raise ValueError('train_op_fn and optimizer cannot both be None.') + train_op = _append_update_ops(train_op) + # Only summarize mean_loss for SUM reduction to preserve backwards + # compatibility. Otherwise skip it to avoid unnecessary computation. + if self._loss_reduction == tf.compat.v1.losses.Reduction.SUM: + example_weight_sum = tf.math.reduce_sum( + weights * tf.compat.v1.ones_like(unreduced_loss)) + mean_loss = training_loss / example_weight_sum + else: + mean_loss = None + with ops.name_scope(''): + keys = metric_keys.MetricKeys + tf.compat.v1.summary.scalar( + _summary_key(self._name, keys.LOSS), regularized_training_loss) + if mean_loss is not None: + tf.compat.v1.summary.scalar( + _summary_key(self._name, keys.LOSS_MEAN), mean_loss) + if regularization_loss is not None: + tf.compat.v1.summary.scalar( + _summary_key(self._name, keys.LOSS_REGULARIZATION), + regularization_loss) + return model_fn._TPUEstimatorSpec( # pylint: disable=protected-access + mode=ModeKeys.TRAIN, + predictions=predictions, + loss=regularized_training_loss, + train_op=train_op) + + +def _append_update_ops(train_op): + """Returns `train_op` appending `UPDATE_OPS` collection if present.""" + update_ops = tf.compat.v1.get_collection(tf.compat.v1.GraphKeys.UPDATE_OPS) + if update_ops: + return tf.group(train_op, *update_ops) + return train_op + + +def _assert_range(labels, n_classes, message=None): + with ops.name_scope(None, 'assert_range', (labels,)): + assert_less = tf.compat.v1.debugging.assert_less_equal( + labels, + ops.convert_to_tensor(n_classes - 1, dtype=labels.dtype), + message=message or 'Labels must <= n_classes - 1') + assert_greater = tf.compat.v1.debugging.assert_non_negative( + labels, message=message or 'Labels must >= 0') + with tf.control_dependencies((assert_less, assert_greater)): + return tf.identity(labels) + + +def _binary_logistic_or_multi_class_head(n_classes, weight_column, + label_vocabulary, loss_reduction): + """Creates either binary or multi-class head. + + Args: + n_classes: Number of label classes. + weight_column: A string or a `_NumericColumn` created by + `tf.feature_column.numeric_column` defining feature column representing + weights. It is used to down weight or boost examples during training. It + will be multiplied by the loss of the example. If it is a string, it is + used as a key to fetch weight tensor from the `features`. If it is a + `_NumericColumn`, raw tensor is fetched by key `weight_column.key`, then + weight_column.normalizer_fn is applied on it to get weight tensor. + label_vocabulary: A list of strings represents possible label values. If + given, labels must be string type and have any value in + `label_vocabulary`. If it is not given, that means labels are already + encoded as integer or float within [0, 1] for `n_classes=2` and encoded as + integer values in {0, 1,..., n_classes-1} for `n_classes`>2 . Also there + will be errors if vocabulary is not provided and labels are string. + loss_reduction: One of `tf.losses.Reduction` except `NONE`. Describes how to + reduce training loss over batch. Defaults to `SUM`. + + Returns: + `head._Head` instance. + """ + if n_classes == 2: + head = _binary_logistic_head_with_sigmoid_cross_entropy_loss( + weight_column=weight_column, + label_vocabulary=label_vocabulary, + loss_reduction=loss_reduction) + else: + head = _multi_class_head_with_softmax_cross_entropy_loss( + n_classes, + weight_column=weight_column, + label_vocabulary=label_vocabulary, + loss_reduction=loss_reduction) + return head diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/kmeans.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/kmeans.py new file mode 100644 index 0000000000000000000000000000000000000000..ece5999c11680eb8186edd86b2a60000da02533d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/kmeans.py @@ -0,0 +1,479 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""A canned Estimator for k-means clustering.""" + +# TODO(ccolby): Move clustering_ops.py into this file and streamline the code. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import time + +import numpy as np +import tensorflow as tf +from tensorflow.python.framework import ops +from tensorflow.python.ops import clustering_ops +from tensorflow.python.ops import control_flow_ops +from tensorflow_estimator.python.estimator import estimator +from tensorflow_estimator.python.estimator import model_fn as model_fn_lib +from tensorflow_estimator.python.estimator.estimator_export import estimator_export +from tensorflow_estimator.python.estimator.export import export_output + + +class _LossRelativeChangeHook(tf.compat.v1.train.SessionRunHook): + """Stops when the change in loss goes below a tolerance.""" + + def __init__(self, loss_tensor, tolerance): + """Creates a _LossRelativeChangeHook. + + Args: + loss_tensor: A scalar tensor of the loss value. + tolerance: A relative tolerance of loss change between iterations. + """ + self._loss_tensor = loss_tensor + self._tolerance = tolerance + self._prev_loss = None + + def before_run(self, run_context): + del run_context # unused + return tf.compat.v1.train.SessionRunArgs(self._loss_tensor) + + def after_run(self, run_context, run_values): + loss = run_values.results + assert loss is not None + if self._prev_loss: + relative_change = ( + abs(loss - self._prev_loss) / (1 + abs(self._prev_loss))) + if relative_change < self._tolerance: + run_context.request_stop() + self._prev_loss = loss + + +class _InitializeClustersHook(tf.compat.v1.train.SessionRunHook): + """Initializes the cluster centers. + + The chief repeatedly invokes an initialization op until all cluster centers + are initialized. The workers wait for the initialization phase to complete. + """ + + def __init__(self, init_op, is_initialized_var, is_chief): + """Creates an _InitializeClustersHook. + + Args: + init_op: An op that, when run, will choose some initial cluster centers. + This op may need to be run multiple times to choose all the centers. + is_initialized_var: A boolean variable reporting whether all initial + centers have been chosen. + is_chief: A boolean specifying whether this task is the chief. + """ + self._init_op = init_op + self._is_initialized_var = is_initialized_var + self._is_chief = is_chief + + def after_create_session(self, session, coord): + del coord # unused + assert self._init_op.graph is tf.compat.v1.get_default_graph() + assert self._is_initialized_var.graph is self._init_op.graph + while True: + try: + if session.run(self._is_initialized_var): + break + elif self._is_chief: + session.run(self._init_op) + else: + time.sleep(1) + except RuntimeError as e: + tf.compat.v1.logging.info(e) + + +def _parse_features_if_necessary(features, feature_columns): + """Helper function to convert the input points into a usable format. + + Args: + features: The input features. + feature_columns: An optionable iterable containing all the feature columns + used by the model. All items in the set should be feature column instances + that can be passed to `tf.feature_column.input_layer`. If this is None, + all features will be used. + + Returns: + If `features` is a dict of `k` features (optionally filtered by + `feature_columns`), each of which is a vector of `n` scalars, the return + value is a Tensor of shape `(n, k)` representing `n` input points, where the + items in the `k` dimension are sorted lexicographically by `features` key. + If `features` is not a dict, it is returned unmodified. + """ + if not isinstance(features, dict): + return features + + if feature_columns: + return tf.compat.v1.feature_column.input_layer(features, feature_columns) + + keys = sorted(features.keys()) + with ops.colocate_with(features[keys[0]]): + return tf.concat([features[k] for k in keys], axis=1) + + +class _ModelFn(object): + """Model function for the estimator.""" + + def __init__(self, num_clusters, initial_clusters, distance_metric, seed, + use_mini_batch, mini_batch_steps_per_iteration, + kmeans_plus_plus_num_retries, relative_tolerance, + feature_columns): + self._num_clusters = num_clusters + self._initial_clusters = initial_clusters + self._distance_metric = distance_metric + self._seed = seed + self._use_mini_batch = use_mini_batch + self._mini_batch_steps_per_iteration = mini_batch_steps_per_iteration + self._kmeans_plus_plus_num_retries = kmeans_plus_plus_num_retries + self._relative_tolerance = relative_tolerance + self._feature_columns = feature_columns + + def model_fn(self, features, mode, config): + """Model function for the estimator. + + Note that this does not take a `labels` arg. This works, but `input_fn` must + return either `features` or, equivalently, `(features, None)`. + + Args: + features: The input points. See `tf.estimator.Estimator`. + mode: See `tf.estimator.Estimator`. + config: See `tf.estimator.Estimator`. + + Returns: + A `tf.estimator.EstimatorSpec` (see `tf.estimator.Estimator`) specifying + this behavior: + * `train_op`: Execute one mini-batch or full-batch run of Lloyd's + algorithm. + * `loss`: The sum of the squared distances from each input point to its + closest center. + * `eval_metric_ops`: Maps `SCORE` to `loss`. + * `predictions`: Maps `ALL_DISTANCES` to the distance from each input + point to each cluster center; maps `CLUSTER_INDEX` to the index of + the closest cluster center for each input point. + """ + # input_points is a single Tensor. Therefore, the sharding functionality + # in clustering_ops is unused, and some of the values below are lists of a + # single item. + input_points = _parse_features_if_necessary(features, self._feature_columns) + + # Let N = the number of input_points. + # all_distances: A list of one matrix of shape (N, num_clusters). Each value + # is the distance from an input point to a cluster center. + # model_predictions: A list of one vector of shape (N). Each value is the + # cluster id of an input point. + # losses: Similar to cluster_idx but provides the distance to the cluster + # center. + # is_initialized: scalar indicating whether the initial cluster centers + # have been chosen; see init_op. + # init_op: an op to choose the initial cluster centers. A single worker + # repeatedly executes init_op until is_initialized becomes True. + # training_op: an op that runs an iteration of training, either an entire + # Lloyd iteration or a mini-batch of a Lloyd iteration. Multiple workers + # may execute this op, but only after is_initialized becomes True. + (all_distances, model_predictions, losses, is_initialized, init_op, + training_op) = clustering_ops.KMeans( + inputs=input_points, + num_clusters=self._num_clusters, + initial_clusters=self._initial_clusters, + distance_metric=self._distance_metric, + use_mini_batch=self._use_mini_batch, + mini_batch_steps_per_iteration=self._mini_batch_steps_per_iteration, + random_seed=self._seed, + kmeans_plus_plus_num_retries=self._kmeans_plus_plus_num_retries + ).training_graph() + + loss = tf.math.reduce_sum(losses) + tf.compat.v1.summary.scalar('loss/raw', loss) + + incr_step = tf.compat.v1.assign_add(tf.compat.v1.train.get_global_step(), 1) + training_op = control_flow_ops.with_dependencies([training_op, incr_step], + loss) + + training_hooks = [ + _InitializeClustersHook(init_op, is_initialized, config.is_chief) + ] + if self._relative_tolerance is not None: + training_hooks.append( + _LossRelativeChangeHook(loss, self._relative_tolerance)) + + export_outputs = { + KMeansClustering.ALL_DISTANCES: + export_output.PredictOutput(all_distances[0]), + KMeansClustering.CLUSTER_INDEX: + export_output.PredictOutput(model_predictions[0]), + tf.saved_model.DEFAULT_SERVING_SIGNATURE_DEF_KEY: + export_output.PredictOutput(model_predictions[0]) + } + + return model_fn_lib.EstimatorSpec( + mode=mode, + predictions={ + KMeansClustering.ALL_DISTANCES: all_distances[0], + KMeansClustering.CLUSTER_INDEX: model_predictions[0], + }, + loss=loss, + train_op=training_op, + eval_metric_ops={ + KMeansClustering.SCORE: tf.compat.v1.metrics.mean(loss) + }, + training_hooks=training_hooks, + export_outputs=export_outputs) + + +# TODO(agarwal,ands): support sharded input. +@estimator_export(v1=['estimator.experimental.KMeans']) +class KMeansClustering(estimator.Estimator): + """An Estimator for K-Means clustering. + + Example: + ``` + import numpy as np + import tensorflow as tf + + num_points = 100 + dimensions = 2 + points = np.random.uniform(0, 1000, [num_points, dimensions]) + + def input_fn(): + return tf.compat.v1.train.limit_epochs( + tf.convert_to_tensor(points, dtype=tf.float32), num_epochs=1) + + num_clusters = 5 + kmeans = tf.compat.v1.estimator.experimental.KMeans( + num_clusters=num_clusters, use_mini_batch=False) + + # train + num_iterations = 10 + previous_centers = None + for _ in xrange(num_iterations): + kmeans.train(input_fn) + cluster_centers = kmeans.cluster_centers() + if previous_centers is not None: + print 'delta:', cluster_centers - previous_centers + previous_centers = cluster_centers + print 'score:', kmeans.score(input_fn) + print 'cluster centers:', cluster_centers + + # map the input points to their clusters + cluster_indices = list(kmeans.predict_cluster_index(input_fn)) + for i, point in enumerate(points): + cluster_index = cluster_indices[i] + center = cluster_centers[cluster_index] + print 'point:', point, 'is in cluster', cluster_index, 'centered at', center + ``` + + The `SavedModel` saved by the `export_saved_model` method does not include the + cluster centers. However, the cluster centers may be retrieved by the + latest checkpoint saved during training. Specifically, + ``` + kmeans.cluster_centers() + ``` + is equivalent to + ``` + tf.train.load_variable( + kmeans.model_dir, KMeansClustering.CLUSTER_CENTERS_VAR_NAME) + ``` + """ + + # Valid values for the distance_metric constructor argument. + SQUARED_EUCLIDEAN_DISTANCE = clustering_ops.SQUARED_EUCLIDEAN_DISTANCE + COSINE_DISTANCE = clustering_ops.COSINE_DISTANCE + + # Values for initial_clusters constructor argument. + RANDOM_INIT = clustering_ops.RANDOM_INIT + KMEANS_PLUS_PLUS_INIT = clustering_ops.KMEANS_PLUS_PLUS_INIT + + # Metric returned by evaluate(): The sum of the squared distances from each + # input point to its closest center. + SCORE = 'score' + + # Keys returned by predict(). + # ALL_DISTANCES: The distance from each input point to each cluster center. + # CLUSTER_INDEX: The index of the closest cluster center for each input point. + CLUSTER_INDEX = 'cluster_index' + ALL_DISTANCES = 'all_distances' + + # Variable name used by cluster_centers(). + CLUSTER_CENTERS_VAR_NAME = clustering_ops.CLUSTERS_VAR_NAME + + def __init__(self, + num_clusters, + model_dir=None, + initial_clusters=RANDOM_INIT, + distance_metric=SQUARED_EUCLIDEAN_DISTANCE, + seed=None, + use_mini_batch=True, + mini_batch_steps_per_iteration=1, + kmeans_plus_plus_num_retries=2, + relative_tolerance=None, + config=None, + feature_columns=None): + r"""Creates an Estimator for running KMeans training and inference. + + This Estimator implements the following variants of the K-means algorithm: + + If `use_mini_batch` is False, it runs standard full batch K-means. Each + training step runs a single iteration of K-Means and must process the full + input at once. To run in this mode, the `input_fn` passed to `train` must + return the entire input dataset. + + If `use_mini_batch` is True, it runs a generalization of the mini-batch + K-means algorithm. It runs multiple iterations, where each iteration is + composed of `mini_batch_steps_per_iteration` steps. Each training step + accumulates the contribution from one mini-batch into temporary storage. + Every `mini_batch_steps_per_iteration` steps, the cluster centers are + updated and the temporary storage cleared for the next iteration. + For example: the entire dataset contains 64k examples, where the batch size + is 64. User can choose mini_batch_steps_per_iteration = 100 to run 10% of + the entire data every iteration in order to update the cluster centers. + Note that: + * If `mini_batch_steps_per_iteration=1`, the algorithm reduces to the + standard K-means mini-batch algorithm. + * If `mini_batch_steps_per_iteration = num_inputs / batch_size`, the + algorithm becomes an asynchronous version of the full-batch algorithm. + However, there is no guarantee by this implementation that each input + is seen exactly once per iteration. Also, different updates are applied + asynchronously without locking. So this asynchronous version may not + behave exactly like a full-batch version. + + Args: + num_clusters: An integer tensor specifying the number of clusters. This + argument is ignored if `initial_clusters` is a tensor or numpy array. + model_dir: The directory to save the model results and log files. + initial_clusters: Specifies how the initial cluster centers are chosen. + One of the following: * a tensor or numpy array with the initial cluster + centers. * a callable `f(inputs, k)` that selects and returns up to + `k` centers from an input batch. `f` is free to return any number of + centers from `0` to `k`. It will be invoked on successive input + batches as necessary until all `num_clusters` centers are chosen. + * `KMeansClustering.RANDOM_INIT`: Choose centers randomly from an input + batch. If the batch size is less than `num_clusters` then the entire + batch is chosen to be initial cluster centers and the remaining + centers are chosen from successive input batches. + * `KMeansClustering.KMEANS_PLUS_PLUS_INIT`: Use kmeans++ to choose + centers from the first input batch. If the batch size is less than + `num_clusters`, a TensorFlow runtime error occurs. + distance_metric: The distance metric used for clustering. One of: + * `KMeansClustering.SQUARED_EUCLIDEAN_DISTANCE`: Euclidean distance + between vectors `u` and `v` is defined as \\(||u - v||_2\\) which is + the square root of the sum of the absolute squares of the elements' + difference. + * `KMeansClustering.COSINE_DISTANCE`: Cosine distance between vectors + `u` and `v` is defined as \\(1 - (u . v) / (||u||_2 ||v||_2)\\). + seed: Python integer. Seed for PRNG used to initialize centers. + use_mini_batch: A boolean specifying whether to use the mini-batch k-means + algorithm. See explanation above. + mini_batch_steps_per_iteration: The number of steps after which the + updated cluster centers are synced back to a master copy. Used only if + `use_mini_batch=True`. See explanation above. + kmeans_plus_plus_num_retries: For each point that is sampled during + kmeans++ initialization, this parameter specifies the number of + additional points to draw from the current distribution before selecting + the best. If a negative value is specified, a heuristic is used to + sample `O(log(num_to_sample))` additional points. Used only if + `initial_clusters=KMeansClustering.KMEANS_PLUS_PLUS_INIT`. + relative_tolerance: A relative tolerance of change in the loss between + iterations. Stops learning if the loss changes less than this amount. + This may not work correctly if `use_mini_batch=True`. + config: See `tf.estimator.Estimator`. + feature_columns: An optionable iterable containing all the feature columns + used by the model. All items in the set should be feature column + instances that can be passed to `tf.feature_column.input_layer`. If this + is None, all features will be used. + + Raises: + ValueError: An invalid argument was passed to `initial_clusters` or + `distance_metric`. + """ + if isinstance(initial_clusters, str) and initial_clusters not in [ + KMeansClustering.RANDOM_INIT, KMeansClustering.KMEANS_PLUS_PLUS_INIT + ]: + raise ValueError("Unsupported initialization algorithm '%s'" % + initial_clusters) + if distance_metric not in [ + KMeansClustering.SQUARED_EUCLIDEAN_DISTANCE, + KMeansClustering.COSINE_DISTANCE + ]: + raise ValueError("Unsupported distance metric '%s'" % distance_metric) + self._distance_metric = distance_metric + super(KMeansClustering, self).__init__( + model_fn=_ModelFn(num_clusters, initial_clusters, distance_metric, seed, + use_mini_batch, mini_batch_steps_per_iteration, + kmeans_plus_plus_num_retries, relative_tolerance, + feature_columns).model_fn, + model_dir=model_dir, + config=config) + + def _predict_one_key(self, input_fn, predict_key): + for result in self.predict(input_fn=input_fn, predict_keys=[predict_key]): + yield result[predict_key] + + def predict_cluster_index(self, input_fn): + """Finds the index of the closest cluster center to each input point. + + Args: + input_fn: Input points. See `tf.estimator.Estimator.predict`. + + Yields: + The index of the closest cluster center for each input point. + """ + for index in self._predict_one_key(input_fn, + KMeansClustering.CLUSTER_INDEX): + yield index + + def score(self, input_fn): + """Returns the sum of squared distances to nearest clusters. + + Note that this function is different from the corresponding one in sklearn + which returns the negative sum. + + Args: + input_fn: Input points. See `tf.estimator.Estimator.evaluate`. Only one + batch is retrieved. + + Returns: + The sum of the squared distance from each point in the first batch of + inputs to its nearest cluster center. + """ + return self.evaluate(input_fn=input_fn, steps=1)[KMeansClustering.SCORE] + + def transform(self, input_fn): + """Transforms each input point to its distances to all cluster centers. + + Note that if `distance_metric=KMeansClustering.SQUARED_EUCLIDEAN_DISTANCE`, + this + function returns the squared Euclidean distance while the corresponding + sklearn function returns the Euclidean distance. + + Args: + input_fn: Input points. See `tf.estimator.Estimator.predict`. + + Yields: + The distances from each input point to each cluster center. + """ + for distances in self._predict_one_key(input_fn, + KMeansClustering.ALL_DISTANCES): + if self._distance_metric == KMeansClustering.SQUARED_EUCLIDEAN_DISTANCE: + yield np.sqrt(distances) + else: + yield distances + + def cluster_centers(self): + """Returns the cluster centers.""" + return self.get_variable_value(KMeansClustering.CLUSTER_CENTERS_VAR_NAME) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/linear.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/linear.py new file mode 100644 index 0000000000000000000000000000000000000000..a6592f524654675a5d9b1559c1bb6f270b23c5ff --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/linear.py @@ -0,0 +1,1672 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Linear Estimators.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import math + +import six +import tensorflow as tf +from tensorflow.python.feature_column import feature_column +from tensorflow.python.feature_column import feature_column_lib +from tensorflow.python.feature_column import feature_column_v2 as fc_v2 +from tensorflow.python.framework import ops +from tensorflow.python.ops import variable_scope +from tensorflow_estimator.python.estimator import estimator +from tensorflow_estimator.python.estimator.canned import head as head_lib +from tensorflow_estimator.python.estimator.canned import optimizers +from tensorflow_estimator.python.estimator.canned.linear_optimizer.python.utils import sdca_ops +from tensorflow_estimator.python.estimator.estimator_export import estimator_export +from tensorflow_estimator.python.estimator.head import binary_class_head +from tensorflow_estimator.python.estimator.head import head_utils +from tensorflow_estimator.python.estimator.head import regression_head +from tensorflow_estimator.python.estimator.mode_keys import ModeKeys + +# The default learning rate of 0.2 is a historical artifact of the initial +# implementation, but seems a reasonable choice. +_LEARNING_RATE = 0.2 + + +@estimator_export('estimator.experimental.LinearSDCA') +class LinearSDCA(object): + """Stochastic Dual Coordinate Ascent helper for linear estimators. + + Objects of this class are intended to be provided as the optimizer argument + (though LinearSDCA objects do not implement the `tf.train.Optimizer` + interface) + when creating `tf.estimator.LinearClassifier` or + `tf.estimator.LinearRegressor`. + + SDCA can only be used with `LinearClassifier` and `LinearRegressor` under the + following conditions: + + - Feature columns are of type V2. + - Multivalent categorical columns are not normalized. In other words the + `sparse_combiner` argument in the estimator constructor should be "sum". + - For classification: binary label. + - For regression: one-dimensional label. + + Example usage: + + ```python + real_feature_column = numeric_column(...) + sparse_feature_column = categorical_column_with_hash_bucket(...) + linear_sdca = tf.estimator.experimental.LinearSDCA( + example_id_column='example_id', + num_loss_partitions=1, + num_table_shards=1, + symmetric_l2_regularization=2.0) + classifier = tf.estimator.LinearClassifier( + feature_columns=[real_feature_column, sparse_feature_column], + weight_column=..., + optimizer=linear_sdca) + classifier.train(input_fn_train, steps=50) + classifier.evaluate(input_fn=input_fn_eval) + ``` + + Here the expectation is that the `input_fn_*` functions passed to train and + evaluate return a pair (dict, label_tensor) where dict has `example_id_column` + as `key` whose value is a `Tensor` of shape [batch_size] and dtype string. + num_loss_partitions defines sigma' in eq (11) of [3]. Convergence of (global) + loss is guaranteed if `num_loss_partitions` is larger or equal to the product + `(#concurrent train ops/per worker) x (#workers)`. Larger values for + `num_loss_partitions` lead to slower convergence. The recommended value for + `num_loss_partitions` in `tf.estimator` (where currently there is one process + per worker) is the number of workers running the train steps. It defaults to 1 + (single machine). + `num_table_shards` defines the number of shards for the internal state + table, typically set to match the number of parameter servers for large + data sets. + + The SDCA algorithm was originally introduced in [1] and it was followed by + the L1 proximal step [2], a distributed version [3] and adaptive sampling [4]. + [1] www.jmlr.org/papers/volume14/shalev-shwartz13a/shalev-shwartz13a.pdf + [2] https://arxiv.org/pdf/1309.2375.pdf + [3] https://arxiv.org/pdf/1502.03508.pdf + [4] https://arxiv.org/pdf/1502.08053.pdf + Details specific to this implementation are provided in: + https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/canned/linear_optimizer/doc/sdca.ipynb + """ + + def __init__(self, + example_id_column, + num_loss_partitions=1, + num_table_shards=None, + symmetric_l1_regularization=0.0, + symmetric_l2_regularization=1.0, + adaptive=False): + """Construct a new SDCA optimizer for linear estimators. + + Args: + example_id_column: The column name containing the example ids. + num_loss_partitions: Number of workers. + num_table_shards: Number of shards of the internal state table, typically + set to match the number of parameter servers. + symmetric_l1_regularization: A float value, must be greater than or equal + to zero. + symmetric_l2_regularization: A float value, must be greater than zero and + should typically be greater than 1. + adaptive: A boolean indicating whether to use adaptive sampling. + """ + + self._example_id_column = example_id_column + self._num_loss_partitions = num_loss_partitions + self._num_table_shards = num_table_shards + self._symmetric_l1_regularization = symmetric_l1_regularization + self._symmetric_l2_regularization = symmetric_l2_regularization + self._adaptive = adaptive + + def _prune_and_unique_sparse_ids(self, id_weight_pair): + """Remove duplicate and negative ids in a sparse tendor.""" + + id_tensor = id_weight_pair.id_tensor + if id_weight_pair.weight_tensor: + weight_tensor = id_weight_pair.weight_tensor.values + else: + weight_tensor = tf.ones([tf.compat.v1.shape(id_tensor.indices)[0]], + tf.dtypes.float32) + + example_ids = tf.reshape(id_tensor.indices[:, 0], [-1]) + flat_ids = tf.cast( + tf.reshape(id_tensor.values, [-1]), dtype=tf.dtypes.int64) + # Prune invalid IDs (< 0) from the flat_ids, example_ids, and + # weight_tensor. These can come from looking up an OOV entry in the + # vocabulary (default value being -1). + is_id_valid = tf.math.greater_equal(flat_ids, 0) + flat_ids = tf.compat.v1.boolean_mask(flat_ids, is_id_valid) + example_ids = tf.compat.v1.boolean_mask(example_ids, is_id_valid) + weight_tensor = tf.compat.v1.boolean_mask(weight_tensor, is_id_valid) + + projection_length = tf.math.reduce_max(flat_ids) + 1 + # project ids based on example ids so that we can dedup ids that + # occur multiple times for a single example. + projected_ids = projection_length * example_ids + flat_ids + + # Remove any redundant ids. + ids, idx = tf.unique(projected_ids) + # Keep only one example id per duplicated ids. + example_ids_filtered = tf.math.unsorted_segment_min( + example_ids, idx, + tf.compat.v1.shape(ids)[0]) + + # reproject ids back feature id space. + reproject_ids = (ids - projection_length * example_ids_filtered) + + weights = tf.reshape( + tf.math.unsorted_segment_sum(weight_tensor, idx, + tf.compat.v1.shape(ids)[0]), [-1]) + return sdca_ops._SparseFeatureColumn( # pylint: disable=protected-access + example_ids_filtered, reproject_ids, weights) + + def get_train_step(self, state_manager, weight_column_name, loss_type, + feature_columns, features, targets, bias_var, global_step): + """Returns the training operation of an SdcaModel optimizer.""" + + batch_size = tf.compat.v1.shape(targets)[0] + cache = tf.compat.v2.__internal__.feature_column.FeatureTransformationCache(features) + + # Iterate over all feature columns and create appropriate lists for dense + # and sparse features as well as dense and sparse weights (variables) for + # SDCA. + dense_features, dense_feature_weights = [], [] + sparse_feature_with_values, sparse_feature_with_values_weights = [], [] + for column in sorted(feature_columns, key=lambda x: x.name): + if isinstance(column, feature_column_lib.CategoricalColumn): + id_weight_pair = column.get_sparse_tensors(cache, state_manager) + sparse_feature_with_values.append( + self._prune_and_unique_sparse_ids(id_weight_pair)) + # If a partitioner was used during variable creation, we will have a + # list of Variables here larger than 1. + sparse_feature_with_values_weights.append( + state_manager.get_variable(column, 'weights')) + elif isinstance(column, tf.compat.v2.__internal__.feature_column.DenseColumn): + if column.variable_shape.ndims != 1: + raise ValueError('Column %s has rank %d, larger than 1.' % + (type(column).__name__, column.variable_shape.ndims)) + dense_features.append(column.get_dense_tensor(cache, state_manager)) + # For real valued columns, the variables list contains exactly one + # element. + dense_feature_weights.append( + state_manager.get_variable(column, 'weights')) + else: + raise ValueError('LinearSDCA does not support column type %s.' % + type(column).__name__) + + # Add the bias column + dense_features.append(tf.ones([batch_size, 1])) + dense_feature_weights.append(bias_var) + + example_weights = tf.reshape( + features[weight_column_name], + shape=[-1]) if weight_column_name else tf.ones([batch_size]) + example_ids = features[self._example_id_column] + training_examples = dict( + sparse_features=sparse_feature_with_values, + dense_features=dense_features, + example_labels=tf.compat.v1.to_float(tf.reshape(targets, shape=[-1])), + example_weights=example_weights, + example_ids=example_ids) + training_variables = dict( + sparse_features_weights=sparse_feature_with_values_weights, + dense_features_weights=dense_feature_weights) + sdca_model = sdca_ops._SDCAModel( # pylint: disable=protected-access + examples=training_examples, + variables=training_variables, + options=dict( + symmetric_l1_regularization=self._symmetric_l1_regularization, + symmetric_l2_regularization=self._symmetric_l2_regularization, + adaptive=self._adaptive, + num_loss_partitions=self._num_loss_partitions, + num_table_shards=self._num_table_shards, + loss_type=loss_type)) + train_op = sdca_model.minimize(global_step=global_step) + return sdca_model, train_op + + +def _get_default_optimizer_v2(feature_columns): + learning_rate = min(_LEARNING_RATE, 1.0 / math.sqrt(len(feature_columns))) + return tf.keras.optimizers.legacy.Ftrl(learning_rate=learning_rate) + + +def _get_default_optimizer(feature_columns): + learning_rate = min(_LEARNING_RATE, 1.0 / math.sqrt(len(feature_columns))) + return tf.compat.v1.train.FtrlOptimizer(learning_rate=learning_rate) + + +def _get_expanded_variable_list(var_list): + """Given an iterable of variables, expands them if they are partitioned. + + Args: + var_list: An iterable of variables. + + Returns: + A list of variables where each partitioned variable is expanded to its + components. + """ + returned_list = [] + for variable in var_list: + if (isinstance(variable, tf.Variable) or + tf.compat.v2.__internal__.ops.is_resource_variable(variable) or + isinstance(variable, tf.Tensor)): + returned_list.append(variable) # Single variable/tensor case. + else: # Must be a PartitionedVariable, so convert into a list. + returned_list.extend(list(variable)) + return returned_list + + +# TODO(rohanj): Consider making this a public utility method. +def _compute_fraction_of_zero(variables): + """Given a linear variables list, compute the fraction of zero weights. + + Args: + variables: A list or list of list of variables + + Returns: + The fraction of zeros (sparsity) in the linear model. + """ + with ops.name_scope('zero_fraction'): + variables = tf.nest.flatten(variables) + + with ops.name_scope('total_size'): + sizes = [ + tf.compat.v1.size(x, out_type=tf.dtypes.int64) for x in variables + ] + total_size_int64 = tf.math.add_n(sizes) + with ops.name_scope('total_zero'): + total_zero_float32 = tf.math.add_n([ + tf.compat.v1.cond( + tf.math.equal(size, tf.constant(0, dtype=tf.dtypes.int64)), + true_fn=lambda: tf.constant(0, dtype=tf.dtypes.float32), + false_fn=lambda: tf.math.zero_fraction(x) * tf.cast( + size, dtype=tf.dtypes.float32), + name='zero_count') for x, size in zip(variables, sizes) + ]) + + with ops.name_scope('compute'): + total_size_float32 = tf.cast( + total_size_int64, dtype=tf.dtypes.float32, name='float32_size') + zero_fraction_or_nan = total_zero_float32 / total_size_float32 + + zero_fraction_or_nan = tf.identity( + zero_fraction_or_nan, name='zero_fraction_or_nan') + return zero_fraction_or_nan + + +def linear_logit_fn_builder_v2(units, feature_columns, sparse_combiner='sum'): + """Function builder for a linear logit_fn. + + Args: + units: An int indicating the dimension of the logit layer. + feature_columns: An iterable containing all the feature columns used by the + model. + sparse_combiner: A string specifying how to reduce if a categorical column + is multivalent. One of "mean", "sqrtn", and "sum". + + Returns: + A logit_fn (see below). + + """ + + def linear_logit_fn(features): + """Linear model logit_fn. + + Args: + features: This is the first item returned from the `input_fn` passed to + `train`, `evaluate`, and `predict`. This should be a single `Tensor` or + `dict` of same. + + Returns: + A `Tensor` representing the logits. + """ + if not feature_column_lib.is_feature_column_v2(feature_columns): + raise ValueError( + 'Received a feature column from TensorFlow v1, but this is a ' + 'TensorFlow v2 Estimator. Please either use v2 feature columns ' + '(accessible via tf.feature_column.* in TF 2.x) with this ' + 'Estimator, or switch to a v1 Estimator for use with v1 feature ' + 'columns (accessible via tf.compat.v1.estimator.* and ' + 'tf.compat.v1.feature_column.*, respectively.') + + linear_model = LinearModel( + feature_columns=feature_columns, + units=units, + sparse_combiner=sparse_combiner, + name='linear_model') + logits = linear_model(features) + bias = linear_model.bias + + # We'd like to get all the non-bias variables associated with this + # LinearModel. + # TODO(rohanj): Figure out how to get shared embedding weights variable + # here. + variables = linear_model.variables + variables.remove(bias) + + # Expand (potential) Partitioned variables + bias = _get_expanded_variable_list([bias]) + variables = _get_expanded_variable_list(variables) + + if units > 1: + tf.compat.v1.summary.histogram('bias', bias) + else: + # If units == 1, the bias value is a length-1 list of a scalar Tensor, + # so we should provide a scalar summary. + tf.compat.v1.summary.scalar('bias', bias[0][0]) + tf.compat.v1.summary.scalar('fraction_of_zero_weights', + _compute_fraction_of_zero(variables)) + return logits + + return linear_logit_fn + + +@estimator_export(v1=['estimator.experimental.linear_logit_fn_builder']) +def linear_logit_fn_builder(units, feature_columns, sparse_combiner='sum'): + """Function builder for a linear logit_fn. + + Args: + units: An int indicating the dimension of the logit layer. + feature_columns: An iterable containing all the feature columns used by the + model. + sparse_combiner: A string specifying how to reduce if a categorical column + is multivalent. One of "mean", "sqrtn", and "sum". + + Returns: + A logit_fn (see below). + + """ + + def linear_logit_fn(features): + """Linear model logit_fn. + + Args: + features: This is the first item returned from the `input_fn` passed to + `train`, `evaluate`, and `predict`. This should be a single `Tensor` or + `dict` of same. + + Returns: + A `Tensor` representing the logits. + """ + if feature_column_lib.is_feature_column_v2(feature_columns): + linear_model = LinearModel( + feature_columns=feature_columns, + units=units, + sparse_combiner=sparse_combiner, + name='linear_model') + logits = linear_model(features) + + # We'd like to get all the non-bias variables associated with this + # LinearModel. + # TODO(rohanj): Figure out how to get shared embedding weights variable + # here. + bias = linear_model.bias + variables = linear_model.variables + # Expand (potential) Partitioned variables + bias = _get_expanded_variable_list([bias]) + variables = _get_expanded_variable_list(variables) + variables = [var for var in variables if var not in bias] + + # Expand (potential) Partitioned variables + bias = _get_expanded_variable_list([bias]) + else: + linear_model = feature_column._LinearModel( # pylint: disable=protected-access + feature_columns=feature_columns, + units=units, + sparse_combiner=sparse_combiner, + name='linear_model') + logits = linear_model(features) + cols_to_vars = linear_model.cols_to_vars() + bias = cols_to_vars.pop('bias') + variables = cols_to_vars.values() + variables = _get_expanded_variable_list(variables) + + if units > 1: + tf.compat.v1.summary.histogram('bias', bias) + else: + # If units == 1, the bias value is a length-1 list of a scalar Tensor, + # so we should provide a scalar summary. + tf.compat.v1.summary.scalar('bias', bias[0][0]) + tf.compat.v1.summary.scalar('fraction_of_zero_weights', + _compute_fraction_of_zero(variables)) + return logits + + return linear_logit_fn + + +def _sdca_model_fn(features, labels, mode, head, feature_columns, optimizer): + """A model_fn for linear models that use the SDCA optimizer. + + Args: + features: dict of `Tensor`. + labels: `Tensor` of shape `[batch_size]`. + mode: Defines whether this is training, evaluation or prediction. See + `ModeKeys`. + head: A `Head` instance. + feature_columns: An iterable containing all the feature columns used by the + model. + optimizer: a `LinearSDCA` instance. + + Returns: + An `EstimatorSpec` instance. + + Raises: + ValueError: mode or params are invalid, or features has the wrong type. + """ + assert feature_column_lib.is_feature_column_v2(feature_columns) + if isinstance(head, + (binary_class_head.BinaryClassHead, + head_lib._BinaryLogisticHeadWithSigmoidCrossEntropyLoss)): # pylint: disable=protected-access + loss_type = 'logistic_loss' + elif isinstance(head, (regression_head.RegressionHead, + head_lib._RegressionHeadWithMeanSquaredErrorLoss)): # pylint: disable=protected-access + assert head.logits_dimension == 1 + loss_type = 'squared_loss' + else: + raise ValueError('Unsupported head type: {}'.format(head)) + + # The default name for LinearModel. + linear_model_name = 'linear_model' + + # Name scope has no effect on variables in LinearModel, as it uses + # tf.get_variables() for variable creation. So we modify the model name to + # keep the variable names the same for checkpoint backward compatibility in + # canned Linear v2. + if isinstance( + head, + (binary_class_head.BinaryClassHead, regression_head.RegressionHead)): + linear_model_name = 'linear/linear_model' + + linear_model = LinearModel( + feature_columns=feature_columns, + units=1, + sparse_combiner='sum', + name=linear_model_name) + logits = linear_model(features) + + # We'd like to get all the non-bias variables associated with this + # LinearModel. + # TODO(rohanj): Figure out how to get shared embedding weights variable + # here. + bias = linear_model.bias + variables = linear_model.variables + # Expand (potential) Partitioned variables + bias = _get_expanded_variable_list([bias]) + variables = _get_expanded_variable_list(variables) + variables = [var for var in variables if var not in bias] + + tf.compat.v1.summary.scalar('bias', bias[0][0]) + tf.compat.v1.summary.scalar('fraction_of_zero_weights', + _compute_fraction_of_zero(variables)) + + if mode == ModeKeys.TRAIN: + sdca_model, train_op = optimizer.get_train_step( + linear_model.layer._state_manager, # pylint: disable=protected-access + head._weight_column, # pylint: disable=protected-access + loss_type, + feature_columns, + features, + labels, + linear_model.bias, + tf.compat.v1.train.get_global_step()) + + update_weights_hook = _SDCAUpdateWeightsHook(sdca_model, train_op) + + model_fn_ops = head.create_estimator_spec( + features=features, + mode=mode, + labels=labels, + train_op_fn=lambda unused_loss_fn: train_op, + logits=logits) + return model_fn_ops._replace( + training_chief_hooks=(model_fn_ops.training_chief_hooks + + (update_weights_hook,))) + else: + return head.create_estimator_spec( + features=features, mode=mode, labels=labels, logits=logits) + + +class _SDCAUpdateWeightsHook(tf.compat.v1.train.SessionRunHook): + """SessionRunHook to update and shrink SDCA model weights.""" + + def __init__(self, sdca_model, train_op): + self._sdca_model = sdca_model + self._train_op = train_op + + def begin(self): + """Construct the update_weights op. + + The op is implicitly added to the default graph. + """ + self._update_op = self._sdca_model.update_weights(self._train_op) + + def before_run(self, run_context): + """Return the update_weights op so that it is executed during this run.""" + return tf.compat.v1.train.SessionRunArgs(self._update_op) + + +def _linear_model_fn_builder_v2(units, + feature_columns, + sparse_combiner='sum', + features=None): + """Function builder for a linear model_fn. + + Args: + units: An int indicating the dimension of the logit layer. + feature_columns: An iterable containing all the feature columns used by the + model. + sparse_combiner: A string specifying how to reduce if a categorical column + is multivalent. One of "mean", "sqrtn", and "sum". + features: This is the first item returned from the `input_fn` passed to + `train`, `evaluate`, and `predict`. This should be a single `Tensor` or + `dict` of same. + + Returns: + A `Tensor` representing the logits. + A list of trainable variables. + + """ + if not feature_column_lib.is_feature_column_v2(feature_columns): + raise ValueError( + 'Received a feature column from TensorFlow v1, but this is a ' + 'TensorFlow v2 Estimator. Please either use v2 feature columns ' + '(accessible via tf.feature_column.* in TF 2.x) with this ' + 'Estimator, or switch to a v1 Estimator for use with v1 feature ' + 'columns (accessible via tf.compat.v1.estimator.* and ' + 'tf.compat.v1.feature_column.*, respectively.') + + # Name scope has no effect on variables in LinearModel, as it uses + # tf.get_variables() for variable creation. So we modify the model name to + # keep the variable names the same for checkpoint backward compatibility. + linear_model = LinearModel( + feature_columns=feature_columns, + units=units, + sparse_combiner=sparse_combiner, + name='linear/linear_model') + logits = linear_model(features) + bias = linear_model.bias + + # We'd like to get all the non-bias variables associated with this + # LinearModel. + # TODO(rohanj): Figure out how to get shared embedding weights variable + # here. + variables = linear_model.variables + variables.remove(bias) + + if units > 1: + tf.compat.v1.summary.histogram('bias', bias) + else: + # If units == 1, the bias value is a length-1 list of a scalar Tensor, + # so we should provide a scalar summary. + tf.compat.v1.summary.scalar('bias', bias[0]) + tf.compat.v1.summary.scalar('fraction_of_zero_weights', + _compute_fraction_of_zero(variables)) + + return logits, linear_model.variables + + +def _linear_model_fn_v2(features, + labels, + mode, + head, + feature_columns, + optimizer, + config, + sparse_combiner='sum'): + """A model_fn for linear models that use a gradient-based optimizer. + + Args: + features: dict of `Tensor`. + labels: `Tensor` of shape `[batch_size, logits_dimension]`. + mode: Defines whether this is training, evaluation or prediction. See + `ModeKeys`. + head: A `Head` instance. + feature_columns: An iterable containing all the feature columns used by the + model. + optimizer: string, `Optimizer` object, or callable that defines the + optimizer to use for training. If `None`, will use a FTRL optimizer. + config: `RunConfig` object to configure the runtime settings. + sparse_combiner: A string specifying how to reduce if a categorical column + is multivalent. One of "mean", "sqrtn", and "sum". + + Returns: + An `EstimatorSpec` instance. + + Raises: + ValueError: mode or params are invalid, or features has the wrong type. + """ + if not isinstance(features, dict): + raise ValueError('features should be a dictionary of `Tensor`s. ' + 'Given type: {}'.format(type(features))) + + del config + + if isinstance(optimizer, LinearSDCA): + assert sparse_combiner == 'sum' + return _sdca_model_fn(features, labels, mode, head, feature_columns, + optimizer) + else: + logits, trainable_variables = _linear_model_fn_builder_v2( + units=head.logits_dimension, + feature_columns=feature_columns, + sparse_combiner=sparse_combiner, + features=features) + + # In TRAIN mode, create optimizer and assign global_step variable to + # optimizer.iterations to make global_step increased correctly, as Hooks + # relies on global step as step counter. + if mode == ModeKeys.TRAIN: + optimizer = optimizers.get_optimizer_instance_v2( + optimizer or _get_default_optimizer_v2(feature_columns), + learning_rate=_LEARNING_RATE) + optimizer.iterations = tf.compat.v1.train.get_or_create_global_step() + + return head.create_estimator_spec( + features=features, + mode=mode, + labels=labels, + optimizer=optimizer, + trainable_variables=trainable_variables, + logits=logits) + + +def _linear_model_fn(features, + labels, + mode, + head, + feature_columns, + optimizer, + partitioner, + config, + sparse_combiner='sum'): + """A model_fn for linear models that use a gradient-based optimizer. + + Args: + features: dict of `Tensor`. + labels: `Tensor` of shape `[batch_size, logits_dimension]`. + mode: Defines whether this is training, evaluation or prediction. See + `ModeKeys`. + head: A `Head` instance. + feature_columns: An iterable containing all the feature columns used by the + model. + optimizer: string, `Optimizer` object, or callable that defines the + optimizer to use for training. If `None`, will use a FTRL optimizer. + partitioner: Partitioner for variables. + config: `RunConfig` object to configure the runtime settings. + sparse_combiner: A string specifying how to reduce if a categorical column + is multivalent. One of "mean", "sqrtn", and "sum". + + Returns: + An `EstimatorSpec` instance. + + Raises: + ValueError: mode or params are invalid, or features has the wrong type. + """ + if not isinstance(features, dict): + raise ValueError('features should be a dictionary of `Tensor`s. ' + 'Given type: {}'.format(type(features))) + + num_ps_replicas = config.num_ps_replicas if config else 0 + + partitioner = partitioner or (tf.compat.v1.min_max_variable_partitioner( + max_partitions=num_ps_replicas, min_slice_size=64 << 20)) + + with tf.compat.v1.variable_scope( + 'linear', values=tuple(six.itervalues(features)), + partitioner=partitioner): + + if isinstance(optimizer, LinearSDCA): + assert sparse_combiner == 'sum' + return _sdca_model_fn(features, labels, mode, head, feature_columns, + optimizer) + else: + logit_fn = linear_logit_fn_builder( + units=head.logits_dimension, + feature_columns=feature_columns, + sparse_combiner=sparse_combiner, + ) + logits = logit_fn(features=features) + + optimizer = optimizers.get_optimizer_instance( + optimizer or _get_default_optimizer(feature_columns), + learning_rate=_LEARNING_RATE) + + return head.create_estimator_spec( + features=features, + mode=mode, + labels=labels, + optimizer=optimizer, + logits=logits) + + +def _validate_linear_sdca_optimizer_for_linear_classifier( + feature_columns, n_classes, optimizer, sparse_combiner): + """Helper function for the initialization of LinearClassifier.""" + if isinstance(optimizer, LinearSDCA): + if sparse_combiner != 'sum': + raise ValueError('sparse_combiner must be "sum" when optimizer ' + 'is a LinearSDCA object.') + if not feature_column_lib.is_feature_column_v2(feature_columns): + raise ValueError('V2 feature columns required when optimizer ' + 'is a LinearSDCA object.') + if n_classes > 2: + raise ValueError('LinearSDCA cannot be used in a multi-class setting.') + + +@estimator_export('estimator.LinearClassifier', v1=[]) +class LinearClassifierV2(estimator.EstimatorV2): + """Linear classifier model. + + Train a linear model to classify instances into one of multiple possible + classes. When number of possible classes is 2, this is binary classification. + + Example: + + ```python + categorical_column_a = categorical_column_with_hash_bucket(...) + categorical_column_b = categorical_column_with_hash_bucket(...) + + categorical_feature_a_x_categorical_feature_b = crossed_column(...) + + # Estimator using the default optimizer. + estimator = tf.estimator.LinearClassifier( + feature_columns=[categorical_column_a, + categorical_feature_a_x_categorical_feature_b]) + + # Or estimator using the FTRL optimizer with regularization. + estimator = tf.estimator.LinearClassifier( + feature_columns=[categorical_column_a, + categorical_feature_a_x_categorical_feature_b], + optimizer=tf.keras.optimizers.Ftrl( + learning_rate=0.1, + l1_regularization_strength=0.001 + )) + + # Or estimator using an optimizer with a learning rate decay. + estimator = tf.estimator.LinearClassifier( + feature_columns=[categorical_column_a, + categorical_feature_a_x_categorical_feature_b], + optimizer=lambda: tf.keras.optimizers.Ftrl( + learning_rate=tf.exponential_decay( + learning_rate=0.1, + global_step=tf.get_global_step(), + decay_steps=10000, + decay_rate=0.96)) + + # Or estimator with warm-starting from a previous checkpoint. + estimator = tf.estimator.LinearClassifier( + feature_columns=[categorical_column_a, + categorical_feature_a_x_categorical_feature_b], + warm_start_from="/path/to/checkpoint/dir") + + + # Input builders + def input_fn_train: + # Returns tf.data.Dataset of (x, y) tuple where y represents label's class + # index. + pass + def input_fn_eval: + # Returns tf.data.Dataset of (x, y) tuple where y represents label's class + # index. + pass + def input_fn_predict: + # Returns tf.data.Dataset of (x, None) tuple. + pass + estimator.train(input_fn=input_fn_train) + metrics = estimator.evaluate(input_fn=input_fn_eval) + predictions = estimator.predict(input_fn=input_fn_predict) + ``` + + Input of `train` and `evaluate` should have following features, + otherwise there will be a `KeyError`: + + * if `weight_column` is not `None`, a feature with `key=weight_column` whose + value is a `Tensor`. + * for each `column` in `feature_columns`: + - if `column` is a `SparseColumn`, a feature with `key=column.name` + whose `value` is a `SparseTensor`. + - if `column` is a `WeightedSparseColumn`, two features: the first with + `key` the id column name, the second with `key` the weight column name. + Both features' `value` must be a `SparseTensor`. + - if `column` is a `RealValuedColumn`, a feature with `key=column.name` + whose `value` is a `Tensor`. + + Loss is calculated by using softmax cross entropy. + + @compatibility(eager) + Estimators can be used while eager execution is enabled. Note that `input_fn` + and all hooks are executed inside a graph context, so they have to be written + to be compatible with graph mode. Note that `input_fn` code using `tf.data` + generally works in both graph and eager modes. + @end_compatibility + """ + + def __init__(self, + feature_columns, + model_dir=None, + n_classes=2, + weight_column=None, + label_vocabulary=None, + optimizer='Ftrl', + config=None, + warm_start_from=None, + loss_reduction=tf.losses.Reduction.SUM_OVER_BATCH_SIZE, + sparse_combiner='sum'): + """Construct a `LinearClassifier` estimator object. + + Args: + feature_columns: An iterable containing all the feature columns used by + the model. All items in the set should be instances of classes derived + from `FeatureColumn`. + model_dir: Directory to save model parameters, graph and etc. This can + also be used to load checkpoints from the directory into a estimator to + continue training a previously saved model. + n_classes: number of label classes. Default is binary classification. Note + that class labels are integers representing the class index (i.e. values + from 0 to n_classes-1). For arbitrary label values (e.g. string labels), + convert to class indices first. + weight_column: A string or a `_NumericColumn` created by + `tf.feature_column.numeric_column` defining feature column representing + weights. It is used to down weight or boost examples during training. It + will be multiplied by the loss of the example. If it is a string, it is + used as a key to fetch weight tensor from the `features`. If it is a + `_NumericColumn`, raw tensor is fetched by key `weight_column.key`, then + weight_column.normalizer_fn is applied on it to get weight tensor. + label_vocabulary: A list of strings represents possible label values. If + given, labels must be string type and have any value in + `label_vocabulary`. If it is not given, that means labels are already + encoded as integer or float within [0, 1] for `n_classes=2` and encoded + as integer values in {0, 1,..., n_classes-1} for `n_classes`>2 . Also + there will be errors if vocabulary is not provided and labels are + string. + optimizer: An instance of `tf.keras.optimizers.*` or + `tf.estimator.experimental.LinearSDCA` used to train the model. Can also + be a string (one of 'Adagrad', 'Adam', 'Ftrl', 'RMSProp', 'SGD'), or + callable. Defaults to FTRL optimizer. + config: `RunConfig` object to configure the runtime settings. + warm_start_from: A string filepath to a checkpoint to warm-start from, or + a `WarmStartSettings` object to fully configure warm-starting. If the + string filepath is provided instead of a `WarmStartSettings`, then all + weights and biases are warm-started, and it is assumed that vocabularies + and Tensor names are unchanged. + loss_reduction: One of `tf.losses.Reduction` except `NONE`. Describes how + to reduce training loss over batch. Defaults to `SUM_OVER_BATCH_SIZE`. + sparse_combiner: A string specifying how to reduce if a categorical column + is multivalent. One of "mean", "sqrtn", and "sum" -- these are + effectively different ways to do example-level normalization, which can + be useful for bag-of-words features. for more details, see + `tf.feature_column.linear_model`. + + Returns: + A `LinearClassifier` estimator. + + Raises: + ValueError: if n_classes < 2. + """ + _validate_linear_sdca_optimizer_for_linear_classifier( + feature_columns=feature_columns, + n_classes=n_classes, + optimizer=optimizer, + sparse_combiner=sparse_combiner) + estimator._canned_estimator_api_gauge.get_cell('Classifier').set('Linear') # pylint: disable=protected-access + + head = head_utils.binary_or_multi_class_head( + n_classes, + weight_column=weight_column, + label_vocabulary=label_vocabulary, + loss_reduction=loss_reduction) + + def _model_fn(features, labels, mode, config): + """Call the defined shared _linear_model_fn.""" + return _linear_model_fn_v2( + features=features, + labels=labels, + mode=mode, + head=head, + feature_columns=tuple(feature_columns or []), + optimizer=optimizer, + config=config, + sparse_combiner=sparse_combiner) + + super(LinearClassifierV2, self).__init__( + model_fn=_model_fn, + model_dir=model_dir, + config=config, + warm_start_from=warm_start_from) + + +@estimator_export(v1=['estimator.LinearClassifier']) # pylint: disable=missing-docstring +class LinearClassifier(estimator.Estimator): + __doc__ = LinearClassifierV2.__doc__.replace('SUM_OVER_BATCH_SIZE', 'SUM') + + def __init__(self, + feature_columns, + model_dir=None, + n_classes=2, + weight_column=None, + label_vocabulary=None, + optimizer='Ftrl', + config=None, + partitioner=None, + warm_start_from=None, + loss_reduction=tf.compat.v1.losses.Reduction.SUM, + sparse_combiner='sum'): + _validate_linear_sdca_optimizer_for_linear_classifier( + feature_columns=feature_columns, + n_classes=n_classes, + optimizer=optimizer, + sparse_combiner=sparse_combiner) + estimator._canned_estimator_api_gauge.get_cell('Classifier').set('Linear') # pylint: disable=protected-access + + head = head_lib._binary_logistic_or_multi_class_head( # pylint: disable=protected-access + n_classes, weight_column, label_vocabulary, loss_reduction) + + def _model_fn(features, labels, mode, config): + """Call the defined shared _linear_model_fn.""" + return _linear_model_fn( + features=features, + labels=labels, + mode=mode, + head=head, + feature_columns=tuple(feature_columns or []), + optimizer=optimizer, + partitioner=partitioner, + config=config, + sparse_combiner=sparse_combiner) + + super(LinearClassifier, self).__init__( + model_fn=_model_fn, + model_dir=model_dir, + config=config, + warm_start_from=warm_start_from) + + +@estimator_export('estimator.LinearEstimator', v1=[]) +class LinearEstimatorV2(estimator.EstimatorV2): + """An estimator for TensorFlow linear models with user-specified head. + + Example: + + ```python + categorical_column_a = categorical_column_with_hash_bucket(...) + categorical_column_b = categorical_column_with_hash_bucket(...) + + categorical_feature_a_x_categorical_feature_b = crossed_column(...) + + # Estimator using the default optimizer. + estimator = tf.estimator.LinearEstimator( + head=tf.estimator.MultiLabelHead(n_classes=3), + feature_columns=[categorical_column_a, + categorical_feature_a_x_categorical_feature_b]) + + # Or estimator using an optimizer with a learning rate decay. + estimator = tf.estimator.LinearEstimator( + head=tf.estimator.MultiLabelHead(n_classes=3), + feature_columns=[categorical_column_a, + categorical_feature_a_x_categorical_feature_b], + optimizer=lambda: tf.keras.optimizers.Ftrl( + learning_rate=tf.compat.v1.train.exponential_decay( + learning_rate=0.1, + global_step=tf.compat.v1.train.get_global_step(), + decay_steps=10000, + decay_rate=0.96)) + + # Or estimator using the FTRL optimizer with regularization. + estimator = tf.estimator.LinearEstimator( + head=tf.estimator.MultiLabelHead(n_classes=3), + feature_columns=[categorical_column_a, + categorical_feature_a_x_categorical_feature_b]) + optimizer=tf.keras.optimizers.Ftrl( + learning_rate=0.1, + l1_regularization_strength=0.001 + )) + + def input_fn_train: + # Returns tf.data.Dataset of (x, y) tuple where y represents label's class + # index. + pass + def input_fn_eval: + # Returns tf.data.Dataset of (x, y) tuple where y represents label's class + # index. + pass + def input_fn_predict: + # Returns tf.data.Dataset of (x, None) tuple. + pass + estimator.train(input_fn=input_fn_train, steps=100) + metrics = estimator.evaluate(input_fn=input_fn_eval, steps=10) + predictions = estimator.predict(input_fn=input_fn_predict) + ``` + + Input of `train` and `evaluate` should have following features, + otherwise there will be a `KeyError`: + + * if `weight_column` is not `None`, a feature with `key=weight_column` whose + value is a `Tensor`. + * for each `column` in `feature_columns`: + - if `column` is a `CategoricalColumn`, a feature with `key=column.name` + whose `value` is a `SparseTensor`. + - if `column` is a `WeightedCategoricalColumn`, two features: the first + with `key` the id column name, the second with `key` the weight column + name. Both features' `value` must be a `SparseTensor`. + - if `column` is a `DenseColumn`, a feature with `key=column.name` + whose `value` is a `Tensor`. + + Loss and predicted output are determined by the specified head. + + @compatibility(eager) + Estimators can be used while eager execution is enabled. Note that `input_fn` + and all hooks are executed inside a graph context, so they have to be written + to be compatible with graph mode. Note that `input_fn` code using `tf.data` + generally works in both graph and eager modes. + @end_compatibility + """ + + def __init__(self, + head, + feature_columns, + model_dir=None, + optimizer='Ftrl', + config=None, + sparse_combiner='sum', + warm_start_from=None): + """Initializes a `LinearEstimator` instance. + + Args: + head: A `Head` instance constructed with a method such as + `tf.estimator.MultiLabelHead`. + feature_columns: An iterable containing all the feature columns used by + the model. All items in the set should be instances of classes derived + from `FeatureColumn`. + model_dir: Directory to save model parameters, graph and etc. This can + also be used to load checkpoints from the directory into a estimator to + continue training a previously saved model. + optimizer: An instance of `tf.keras.optimizers.*` used to train the model. + Can also be a string (one of 'Adagrad', 'Adam', 'Ftrl', 'RMSProp', + 'SGD'), or callable. Defaults to FTRL optimizer. + config: `RunConfig` object to configure the runtime settings. + sparse_combiner: A string specifying how to reduce if a categorical column + is multivalent. One of "mean", "sqrtn", and "sum" -- these are + effectively different ways to do example-level normalization, which can + be useful for bag-of-words features. for more details, see + `tf.feature_column.linear_model`. + warm_start_from: A string filepath to a checkpoint to warm-start from, or + a `WarmStartSettings` object to fully configure warm-starting. If the + string filepath is provided instead of a `WarmStartSettings`, then all + weights and biases are warm-started, and it is assumed that vocabularies + and Tensor names are unchanged. + """ + + def _model_fn(features, labels, mode, config): + return _linear_model_fn_v2( + features=features, + labels=labels, + mode=mode, + head=head, + feature_columns=tuple(feature_columns or []), + optimizer=optimizer, + config=config, + sparse_combiner=sparse_combiner) + + estimator._canned_estimator_api_gauge.get_cell('Estimator').set('Linear') # pylint: disable=protected-access + super(LinearEstimatorV2, self).__init__( + model_fn=_model_fn, model_dir=model_dir, config=config, + warm_start_from=warm_start_from) + + +@estimator_export(v1=['estimator.LinearEstimator']) # pylint: disable=missing-docstring +class LinearEstimator(estimator.Estimator): + __doc__ = LinearEstimatorV2.__doc__ + + def __init__(self, + head, + feature_columns, + model_dir=None, + optimizer='Ftrl', + config=None, + partitioner=None, + sparse_combiner='sum', + warm_start_from=None): + """Initializes a `LinearEstimator` instance. + + Args: + head: A `_Head` instance constructed with a method such as + `tf.contrib.estimator.multi_label_head`. + feature_columns: An iterable containing all the feature columns used by + the model. All items in the set should be instances of classes derived + from `FeatureColumn`. + model_dir: Directory to save model parameters, graph and etc. This can + also be used to load checkpoints from the directory into a estimator to + continue training a previously saved model. + optimizer: An instance of `tf.Optimizer` used to train the model. Can also + be a string (one of 'Adagrad', 'Adam', 'Ftrl', 'RMSProp', 'SGD'), or + callable. Defaults to FTRL optimizer. + config: `RunConfig` object to configure the runtime settings. + partitioner: Optional. Partitioner for input layer. + sparse_combiner: A string specifying how to reduce if a categorical column + is multivalent. One of "mean", "sqrtn", and "sum" -- these are + effectively different ways to do example-level normalization, which can + be useful for bag-of-words features. for more details, see + `tf.feature_column.linear_model`. + warm_start_from: A string filepath to a checkpoint to warm-start from, or + a `WarmStartSettings` object to fully configure warm-starting. If the + string filepath is provided instead of a `WarmStartSettings`, then all + weights and biases are warm-started, and it is assumed that vocabularies + and Tensor names are unchanged. + """ + + def _model_fn(features, labels, mode, config): + return _linear_model_fn( + features=features, + labels=labels, + mode=mode, + head=head, + feature_columns=tuple(feature_columns or []), + optimizer=optimizer, + partitioner=partitioner, + config=config, + sparse_combiner=sparse_combiner) + + estimator._canned_estimator_api_gauge.get_cell('Estimator').set('Linear') # pylint: disable=protected-access + super(LinearEstimator, self).__init__( + model_fn=_model_fn, model_dir=model_dir, config=config, + warm_start_from=warm_start_from) + + +def _validate_linear_sdca_optimizer_for_linear_regressor( + feature_columns, label_dimension, optimizer, sparse_combiner): + """Helper function for the initialization of LinearRegressor.""" + if isinstance(optimizer, LinearSDCA): + if sparse_combiner != 'sum': + raise ValueError('sparse_combiner must be "sum" when optimizer ' + 'is a LinearSDCA object.') + if not feature_column_lib.is_feature_column_v2(feature_columns): + raise ValueError('V2 feature columns required when optimizer ' + 'is a LinearSDCA object.') + if label_dimension > 1: + raise ValueError('LinearSDCA can only be used with one-dimensional ' + 'label.') + + +@estimator_export('estimator.LinearRegressor', v1=[]) +class LinearRegressorV2(estimator.EstimatorV2): + """An estimator for TensorFlow Linear regression problems. + + Train a linear regression model to predict label value given observation of + feature values. + + Example: + + ```python + categorical_column_a = categorical_column_with_hash_bucket(...) + categorical_column_b = categorical_column_with_hash_bucket(...) + + categorical_feature_a_x_categorical_feature_b = crossed_column(...) + + # Estimator using the default optimizer. + estimator = tf.estimator.LinearRegressor( + feature_columns=[categorical_column_a, + categorical_feature_a_x_categorical_feature_b]) + + # Or estimator using the FTRL optimizer with regularization. + estimator = tf.estimator.LinearRegressor( + feature_columns=[categorical_column_a, + categorical_feature_a_x_categorical_feature_b], + optimizer=tf.keras.optimizers.Ftrl( + learning_rate=0.1, + l1_regularization_strength=0.001 + )) + + # Or estimator using an optimizer with a learning rate decay. + estimator = tf.estimator.LinearRegressor( + feature_columns=[categorical_column_a, + categorical_feature_a_x_categorical_feature_b], + optimizer=lambda: tf.keras.optimizers.Ftrl( + learning_rate=tf.compat.v1.train.exponential_decay( + learning_rate=0.1, + global_step=tf.compat.v1.train.get_global_step(), + decay_steps=10000, + decay_rate=0.96)) + + # Or estimator with warm-starting from a previous checkpoint. + estimator = tf.estimator.LinearRegressor( + feature_columns=[categorical_column_a, + categorical_feature_a_x_categorical_feature_b], + warm_start_from="/path/to/checkpoint/dir") + + + # Input builders + def input_fn_train: + # Returns tf.data.Dataset of (x, y) tuple where y represents label's class + # index. + pass + def input_fn_eval: + # Returns tf.data.Dataset of (x, y) tuple where y represents label's class + # index. + pass + def input_fn_predict: + # Returns tf.data.Dataset of (x, None) tuple. + pass + estimator.train(input_fn=input_fn_train) + metrics = estimator.evaluate(input_fn=input_fn_eval) + predictions = estimator.predict(input_fn=input_fn_predict) + ``` + + Input of `train` and `evaluate` should have following features, + otherwise there will be a KeyError: + + * if `weight_column` is not `None`, a feature with `key=weight_column` whose + value is a `Tensor`. + * for each `column` in `feature_columns`: + - if `column` is a `SparseColumn`, a feature with `key=column.name` + whose `value` is a `SparseTensor`. + - if `column` is a `WeightedSparseColumn`, two features: the first with + `key` the id column name, the second with `key` the weight column name. + Both features' `value` must be a `SparseTensor`. + - if `column` is a `RealValuedColumn`, a feature with `key=column.name` + whose `value` is a `Tensor`. + + Loss is calculated by using mean squared error. + + @compatibility(eager) + Estimators can be used while eager execution is enabled. Note that `input_fn` + and all hooks are executed inside a graph context, so they have to be written + to be compatible with graph mode. Note that `input_fn` code using `tf.data` + generally works in both graph and eager modes. + @end_compatibility + """ + + def __init__(self, + feature_columns, + model_dir=None, + label_dimension=1, + weight_column=None, + optimizer='Ftrl', + config=None, + warm_start_from=None, + loss_reduction=tf.losses.Reduction.SUM_OVER_BATCH_SIZE, + sparse_combiner='sum'): + """Initializes a `LinearRegressor` instance. + + Args: + feature_columns: An iterable containing all the feature columns used by + the model. All items in the set should be instances of classes derived + from `FeatureColumn`. + model_dir: Directory to save model parameters, graph and etc. This can + also be used to load checkpoints from the directory into a estimator to + continue training a previously saved model. + label_dimension: Number of regression targets per example. This is the + size of the last dimension of the labels and logits `Tensor` objects + (typically, these have shape `[batch_size, label_dimension]`). + weight_column: A string or a `NumericColumn` created by + `tf.feature_column.numeric_column` defining feature column representing + weights. It is used to down weight or boost examples during training. It + will be multiplied by the loss of the example. If it is a string, it is + used as a key to fetch weight tensor from the `features`. If it is a + `NumericColumn`, raw tensor is fetched by key `weight_column.key`, then + weight_column.normalizer_fn is applied on it to get weight tensor. + optimizer: An instance of `tf.keras.optimizers.*` or + `tf.estimator.experimental.LinearSDCA` used to train the model. Can also + be a string (one of 'Adagrad', 'Adam', 'Ftrl', 'RMSProp', 'SGD'), or + callable. Defaults to FTRL optimizer. + config: `RunConfig` object to configure the runtime settings. + warm_start_from: A string filepath to a checkpoint to warm-start from, or + a `WarmStartSettings` object to fully configure warm-starting. If the + string filepath is provided instead of a `WarmStartSettings`, then all + weights and biases are warm-started, and it is assumed that vocabularies + and Tensor names are unchanged. + loss_reduction: One of `tf.losses.Reduction` except `NONE`. Describes how + to reduce training loss over batch. Defaults to `SUM`. + sparse_combiner: A string specifying how to reduce if a categorical column + is multivalent. One of "mean", "sqrtn", and "sum" -- these are + effectively different ways to do example-level normalization, which can + be useful for bag-of-words features. for more details, see + `tf.feature_column.linear_model`. + """ + _validate_linear_sdca_optimizer_for_linear_regressor( + feature_columns=feature_columns, + label_dimension=label_dimension, + optimizer=optimizer, + sparse_combiner=sparse_combiner) + + head = regression_head.RegressionHead( + label_dimension=label_dimension, + weight_column=weight_column, + loss_reduction=loss_reduction) + estimator._canned_estimator_api_gauge.get_cell('Regressor').set('Linear') # pylint: disable=protected-access + + def _model_fn(features, labels, mode, config): + """Call the defined shared _linear_model_fn.""" + return _linear_model_fn_v2( + features=features, + labels=labels, + mode=mode, + head=head, + feature_columns=tuple(feature_columns or []), + optimizer=optimizer, + config=config, + sparse_combiner=sparse_combiner) + + super(LinearRegressorV2, self).__init__( + model_fn=_model_fn, + model_dir=model_dir, + config=config, + warm_start_from=warm_start_from) + + +@estimator_export(v1=['estimator.LinearRegressor']) # pylint: disable=missing-docstring +class LinearRegressor(estimator.Estimator): + __doc__ = LinearRegressorV2.__doc__.replace('SUM_OVER_BATCH_SIZE', 'SUM') + + def __init__(self, + feature_columns, + model_dir=None, + label_dimension=1, + weight_column=None, + optimizer='Ftrl', + config=None, + partitioner=None, + warm_start_from=None, + loss_reduction=tf.compat.v1.losses.Reduction.SUM, + sparse_combiner='sum'): + _validate_linear_sdca_optimizer_for_linear_regressor( + feature_columns=feature_columns, + label_dimension=label_dimension, + optimizer=optimizer, + sparse_combiner=sparse_combiner) + + head = head_lib._regression_head( # pylint: disable=protected-access + label_dimension=label_dimension, + weight_column=weight_column, + loss_reduction=loss_reduction) + estimator._canned_estimator_api_gauge.get_cell('Regressor').set('Linear') # pylint: disable=protected-access + + def _model_fn(features, labels, mode, config): + """Call the defined shared _linear_model_fn.""" + return _linear_model_fn( + features=features, + labels=labels, + mode=mode, + head=head, + feature_columns=tuple(feature_columns or []), + optimizer=optimizer, + partitioner=partitioner, + config=config, + sparse_combiner=sparse_combiner) + + super(LinearRegressor, self).__init__( + model_fn=_model_fn, + model_dir=model_dir, + config=config, + warm_start_from=warm_start_from) + + +class _LinearModelLayer(tf.keras.layers.Layer): + """Layer that contains logic for `LinearModel`.""" + + def __init__(self, + feature_columns, + units=1, + sparse_combiner='sum', + trainable=True, + name=None, + **kwargs): + super(_LinearModelLayer, self).__init__( + name=name, trainable=trainable, **kwargs) + + self._feature_columns = fc_v2._normalize_feature_columns(feature_columns) # pylint: disable=protected-access + for column in self._feature_columns: + if not isinstance(column, (tf.compat.v2.__internal__.feature_column.DenseColumn, fc_v2.CategoricalColumn)): + raise ValueError( + 'Items of feature_columns must be either a ' + 'DenseColumn or CategoricalColumn. Given: {}'.format(column)) + + self._units = units + self._sparse_combiner = sparse_combiner + + self._state_manager = tf.compat.v2.__internal__.feature_column.StateManager(self, self.trainable) # pylint: disable=protected-access + self.bias = None + + def build(self, _): + # We need variable scopes for now because we want the variable partitioning + # information to percolate down. We also use _pure_variable_scope's here + # since we want to open up a name_scope in the `call` method while creating + # the ops. + with variable_scope._pure_variable_scope(self.name): # pylint: disable=protected-access + for column in self._feature_columns: + with variable_scope._pure_variable_scope( # pylint: disable=protected-access + fc_v2._sanitize_column_name_for_variable_scope(column.name)): # pylint: disable=protected-access + # Create the state for each feature column + column.create_state(self._state_manager) + + # Create a weight variable for each column. + if isinstance(column, fc_v2.CategoricalColumn): + first_dim = column.num_buckets + else: + first_dim = column.variable_shape.num_elements() + self._state_manager.create_variable( + column, + name='weights', + dtype=tf.float32, + shape=(first_dim, self._units), + initializer=tf.keras.initializers.zeros(), + trainable=self.trainable) + + # Create a bias variable. + self.bias = self.add_weight( + name='bias_weights', + dtype=tf.float32, + shape=[self._units], + initializer=tf.keras.initializers.zeros(), + trainable=self.trainable, + use_resource=True, + # TODO(rohanj): Get rid of this hack once we have a mechanism for + # specifying a default partitioner for an entire layer. In that case, + # the default getter for Layers should work. + getter=tf.compat.v1.get_variable) + + super(_LinearModelLayer, self).build(None) + + def call(self, features): + if not isinstance(features, dict): + raise ValueError('We expected a dictionary here. Instead we got: {}' + .format(features)) + with ops.name_scope(self.name): + transformation_cache = tf.compat.v2.__internal__.feature_column.FeatureTransformationCache(features) + weighted_sums = [] + for column in self._feature_columns: + with ops.name_scope( + fc_v2._sanitize_column_name_for_variable_scope(column.name)): # pylint: disable=protected-access + # All the weights used in the linear model are owned by the state + # manager associated with this Linear Model. + weight_var = self._state_manager.get_variable(column, 'weights') + + weighted_sum = fc_v2._create_weighted_sum( # pylint: disable=protected-access + column=column, + transformation_cache=transformation_cache, + state_manager=self._state_manager, + sparse_combiner=self._sparse_combiner, + weight_var=weight_var) + weighted_sums.append(weighted_sum) + + fc_v2._verify_static_batch_size_equality( # pylint: disable=protected-access + weighted_sums, self._feature_columns) + predictions_no_bias = tf.math.add_n( + weighted_sums, name='weighted_sum_no_bias') + predictions = tf.nn.bias_add( + predictions_no_bias, self.bias, name='weighted_sum') + return predictions + + def get_config(self): + # Import here to avoid circular imports. + from tensorflow.python.feature_column import serialization # pylint: disable=g-import-not-at-top + column_configs = serialization.serialize_feature_columns( + self._feature_columns) + config = { + 'feature_columns': column_configs, + 'units': self._units, + 'sparse_combiner': self._sparse_combiner + } + + base_config = super( # pylint: disable=bad-super-call + _LinearModelLayer, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + @classmethod + def from_config(cls, config, custom_objects=None): + # Import here to avoid circular imports. + from tensorflow.python.feature_column import serialization # pylint: disable=g-import-not-at-top + config_cp = config.copy() + columns = serialization.deserialize_feature_columns( + config_cp['feature_columns'], custom_objects=custom_objects) + + del config_cp['feature_columns'] + return cls(feature_columns=columns, **config_cp) + + +class LinearModel(tf.keras.Model): + """Produces a linear prediction `Tensor` based on given `feature_columns`. + + This layer generates a weighted sum based on output dimension `units`. + Weighted sum refers to logits in classification problems. It refers to the + prediction itself for linear regression problems. + + Note on supported columns: `LinearLayer` treats categorical columns as + `indicator_column`s. To be specific, assume the input as `SparseTensor` looks + like: + + ```python + shape = [2, 2] + { + [0, 0]: "a" + [1, 0]: "b" + [1, 1]: "c" + } + ``` + `linear_model` assigns weights for the presence of "a", "b", "c' implicitly, + just like `indicator_column`, while `input_layer` explicitly requires wrapping + each of categorical columns with an `embedding_column` or an + `indicator_column`. + + Example of usage: + + ```python + price = numeric_column('price') + price_buckets = bucketized_column(price, boundaries=[0., 10., 100., 1000.]) + keywords = categorical_column_with_hash_bucket("keywords", 10K) + keywords_price = crossed_column('keywords', price_buckets, ...) + columns = [price_buckets, keywords, keywords_price ...] + linear_model = LinearLayer(columns) + + features = tf.io.parse_example(..., features=make_parse_example_spec(columns)) + prediction = linear_model(features) + ``` + """ + + def __init__(self, + feature_columns, + units=1, + sparse_combiner='sum', + trainable=True, + name=None, + **kwargs): + """Constructs a LinearLayer. + + Args: + feature_columns: An iterable containing the FeatureColumns to use as + inputs to your model. All items should be instances of classes derived + from `_FeatureColumn`s. + units: An integer, dimensionality of the output space. Default value is 1. + sparse_combiner: A string specifying how to reduce if a categorical column + is multivalent. Except `numeric_column`, almost all columns passed to + `linear_model` are considered as categorical columns. It combines each + categorical column independently. Currently "mean", "sqrtn" and "sum" + are supported, with "sum" the default for linear model. "sqrtn" often + achieves good accuracy, in particular with bag-of-words columns. + * "sum": do not normalize features in the column + * "mean": do l1 normalization on features in the column + * "sqrtn": do l2 normalization on features in the column + For example, for two features represented as the categorical columns: + + ```python + # Feature 1 + + shape = [2, 2] + { + [0, 0]: "a" + [0, 1]: "b" + [1, 0]: "c" + } + + # Feature 2 + + shape = [2, 3] + { + [0, 0]: "d" + [1, 0]: "e" + [1, 1]: "f" + [1, 2]: "g" + } + ``` + + with `sparse_combiner` as "mean", the linear model outputs conceptually + are + ``` + y_0 = 1.0 / 2.0 * ( w_a + w_ b) + w_c + b_0 + y_1 = w_d + 1.0 / 3.0 * ( w_e + w_ f + w_g) + b_1 + ``` + where `y_i` is the output, `b_i` is the bias, and `w_x` is the weight + assigned to the presence of `x` in the input features. + trainable: If `True` also add the variable to the graph collection + `GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`). + name: Name to give to the Linear Model. All variables and ops created will + be scoped by this name. + **kwargs: Keyword arguments to construct a layer. + + Raises: + ValueError: if an item in `feature_columns` is neither a `DenseColumn` + nor `CategoricalColumn`. + """ + + super(LinearModel, self).__init__(name=name, **kwargs) + self.layer = _LinearModelLayer( + feature_columns, + units, + sparse_combiner, + trainable, + name=self.name, + **kwargs) + + def call(self, features): + """Returns a `Tensor` the represents the predictions of a linear model. + + Args: + features: A mapping from key to tensors. `_FeatureColumn`s look up via + these keys. For example `numeric_column('price')` will look at 'price' + key in this dict. Values are `Tensor` or `SparseTensor` depending on + corresponding `_FeatureColumn`. + + Returns: + A `Tensor` which represents predictions/logits of a linear model. Its + shape is (batch_size, units) and its dtype is `float32`. + + Raises: + ValueError: If features are not a dictionary. + """ + return self.layer(features) + + @property + def bias(self): + return self.layer.bias diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/linear_optimizer/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/linear_optimizer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..322ec627b8371e43332a738bb367aa28866cf99d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/linear_optimizer/__init__.py @@ -0,0 +1,25 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Ops for training linear models. + +## This package provides optimizers to train linear models. + +""" +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +from tensorflow.python.util.all_util import remove_undocumented +remove_undocumented(__name__) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/linear_optimizer/python/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/linear_optimizer/python/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/linear_optimizer/python/utils/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/linear_optimizer/python/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/linear_optimizer/python/utils/sdca_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/linear_optimizer/python/utils/sdca_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..1541ea3a15df6d388f5e0691cc3d03c4b5d50c07 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/linear_optimizer/python/utils/sdca_ops.py @@ -0,0 +1,791 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Proximal stochastic dual coordinate ascent optimizer for linear models.""" +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import collections + +from six.moves import range +import tensorflow as tf +from tensorflow.python.framework import ops +from tensorflow.python.framework.ops import internal_convert_to_tensor +from tensorflow.python.framework.ops import name_scope +from tensorflow.python.ops import gen_sdca_ops +from tensorflow.python.ops import variables as var_ops +from tensorflow.python.ops.nn import log_poisson_loss +from tensorflow.python.ops.nn import sigmoid_cross_entropy_with_logits +from tensorflow_estimator.python.estimator.canned.linear_optimizer.python.utils.sharded_mutable_dense_hashtable import _ShardedMutableDenseHashTable + + +class _SparseFeatureColumn(object): + """Represents a sparse feature column. + + This is meant to be a more efficient representation than tf.SparseFeature for + the purpose of SDCA optimization. + Contains three tensors representing a sparse feature column, they are + example indices (`int64`), feature indices (`int64`), and feature + values (`float`). + Feature weights are optional, and are treated as `1.0f` if missing. + + For example, consider a batch of 4 examples, which contains the following + features in a particular `_SparseFeatureColumn`: + + * Example 0: feature 5, value 1 + * Example 1: feature 6, value 1 and feature 10, value 0.5 + * Example 2: no features + * Example 3: two copies of feature 2, value 1 + + This _SparseFeatureColumn will be represented as follows: + + ``` + <0, 5, 1> + <1, 6, 1> + <1, 10, 0.5> + <3, 2, 1> + <3, 2, 1> + ``` + + For a batch of 2 examples below: + + * Example 0: feature 5 + * Example 1: feature 6 + + is represented by `_SparseFeatureColumn` as: + + ``` + <0, 5, 1> + <1, 6, 1> + + ``` + + @@__init__ + @@example_indices + @@feature_indices + @@feature_values + """ + + def __init__(self, example_indices, feature_indices, feature_values): + """Creates a `_SparseFeatureColumn` representation. + + Args: + example_indices: A 1-D int64 tensor of shape `[N]`. Also, accepts python + lists, or numpy arrays. + feature_indices: A 1-D int64 tensor of shape `[N]`. Also, accepts python + lists, or numpy arrays. + feature_values: An optional 1-D tensor float tensor of shape `[N]`. Also, + accepts python lists, or numpy arrays. + + Returns: + A `_SparseFeatureColumn` + """ + with name_scope(None, 'SparseFeatureColumn', + [example_indices, feature_indices]): + self._example_indices = internal_convert_to_tensor( + example_indices, name='example_indices', dtype=tf.dtypes.int64) + self._feature_indices = internal_convert_to_tensor( + feature_indices, name='feature_indices', dtype=tf.dtypes.int64) + self._feature_values = None + if feature_values is not None: + with name_scope(None, 'SparseFeatureColumn', [feature_values]): + self._feature_values = internal_convert_to_tensor( + feature_values, name='feature_values', dtype=tf.dtypes.float32) + + @property + def example_indices(self): + """The example indices represented as a dense tensor. + + Returns: + A 1-D Tensor of int64 with shape `[N]`. + """ + return self._example_indices + + @property + def feature_indices(self): + """The feature indices represented as a dense tensor. + + Returns: + A 1-D Tensor of int64 with shape `[N]`. + """ + return self._feature_indices + + @property + def feature_values(self): + """The feature values represented as a dense tensor. + + Returns: + May return None, or a 1-D Tensor of float32 with shape `[N]`. + """ + return self._feature_values + + +class _SDCAModel(object): + """Stochastic dual coordinate ascent solver for linear models. + + Loss functions supported: + + * Binary logistic loss + * Squared loss + * Hinge loss + * Smooth hinge loss + * Poisson log loss + + ### Usage + + ```python + # Create a solver with the desired parameters. + lr = _SDCAModel(examples, variables, options) + min_op = lr.minimize() + opt_op = lr.update_weights(min_op) + + predictions = lr.predictions(examples) + # Primal loss + L1 loss + L2 loss. + regularized_loss = lr.regularized_loss(examples) + # Primal loss only + unregularized_loss = lr.unregularized_loss(examples) + + examples: { + sparse_features: list of SparseFeatureColumn. + dense_features: list of dense tensors of type float32. + example_labels: a tensor of type float32 and shape [Num examples] + example_weights: a tensor of type float32 and shape [Num examples] + example_ids: a tensor of type string and shape [Num examples] + } + variables: { + sparse_features_weights: list of tensors of shape [vocab size] + dense_features_weights: list of tensors of shape [dense_feature_dimension] + } + options: { + symmetric_l1_regularization: 0.0 + symmetric_l2_regularization: 1.0 + loss_type: "logistic_loss" + num_loss_partitions: 1 (Optional, with default value of 1. Number of + partitions of the global loss function, 1 means single machine solver, + and >1 when we have more than one optimizer working concurrently.) + num_table_shards: 1 (Optional, with default value of 1. Number of shards + of the internal state table, typically set to match the number of + parameter servers for large data sets. + } + ``` + + In the training program you will just have to run the returned Op from + minimize(). + + ```python + # Execute opt_op and train for num_steps. + for _ in range(num_steps): + opt_op.run() + + # You can also check for convergence by calling + lr.approximate_duality_gap() + ``` + """ + + def __init__(self, examples, variables, options): + """Create a new sdca optimizer.""" + + if not examples or not variables or not options: + raise ValueError('examples, variables and options must all be specified.') + + supported_losses = ('logistic_loss', 'squared_loss', 'hinge_loss', + 'smooth_hinge_loss', 'poisson_loss') + if options['loss_type'] not in supported_losses: + raise ValueError('Unsupported loss_type: ', options['loss_type']) + + self._assert_specified([ + 'example_labels', 'example_weights', 'example_ids', 'sparse_features', + 'dense_features' + ], examples) + self._assert_list(['sparse_features', 'dense_features'], examples) + + self._assert_specified( + ['sparse_features_weights', 'dense_features_weights'], variables) + self._assert_list(['sparse_features_weights', 'dense_features_weights'], + variables) + + self._assert_specified([ + 'loss_type', 'symmetric_l2_regularization', + 'symmetric_l1_regularization' + ], options) + + if options['symmetric_l2_regularization'] <= 0.0: + raise ValueError('symmetric_l2_regularization should be positive.') + if options['symmetric_l2_regularization'] <= 1.0: + tf.compat.v1.logging.warn( + 'symmetric_l2_regularization for SDCA should typically be ' + 'larger than for online optimization methods. Recommended ' + 'value is of the order of the average L2 norm of the ' + 'training examples.') + if options['symmetric_l1_regularization'] < 0.0: + raise ValueError('symmetric_l1_regularization should be non-negative.') + + self._examples = examples + self._variables = variables + self._options = options + self._create_slots() + self._hashtable = _ShardedMutableDenseHashTable( + key_dtype=tf.dtypes.int64, + value_dtype=tf.dtypes.float32, + num_shards=self._num_table_shards(), + default_value=[0.0, 0.0, 0.0, 0.0], + # SdcaFprint never returns 0 or 1 for the low64 bits, so this a safe + # empty_key (that will never collide with actual payloads). + empty_key=[0, 0], + deleted_key=[1, 1]) + + tf.compat.v1.summary.scalar('approximate_duality_gap', + self.approximate_duality_gap()) + tf.compat.v1.summary.scalar('examples_seen', self._hashtable.size()) + + def _symmetric_l1_regularization(self): + return self._options['symmetric_l1_regularization'] + + def _symmetric_l2_regularization(self): + return self._options['symmetric_l2_regularization'] + + def _num_loss_partitions(self): + # Number of partitions of the global objective. + return self._options.get('num_loss_partitions', 1) + + def _adaptive(self): + # Perform adaptive sampling. + return self._options.get('adaptive', True) + + def _num_table_shards(self): + # Number of hash table shards. + # Return 1 if not specified or if the value is 'None' + num_shards = self._options.get('num_table_shards') + return 1 if num_shards is None else num_shards + + def _create_slots(self): + """Make unshrunk internal variables (slots).""" + # Unshrunk variables have the updates before applying L1 regularization. + # Each unshrunk slot variable is either a `Variable` or list of + # `Variable`, depending on the value of its corresponding primary variable. + # We avoid using `PartitionedVariable` for the unshrunk slots since we do + # not need any of the extra information. + self._slots = collections.defaultdict(list) + for name in ['sparse_features_weights', 'dense_features_weights']: + for var in self._variables[name]: + # Our primary variable may be either a PartitionedVariable, or a list + # of Variables (each representing a partition). + if (isinstance(var, var_ops.PartitionedVariable) or + isinstance(var, list)): + var_list = [] + for v in var: + with ops.colocate_with(v): + slot_var = tf.Variable( + initial_value=tf.compat.v1.zeros_like( + tf.cond( + tf.compat.v1.is_variable_initialized(v), + v.read_value, + lambda: v.initial_value), + tf.dtypes.float32), + name=v.op.name + '_unshrunk') + var_list.append(slot_var) + self._slots['unshrunk_' + name].append(var_list) + else: + with tf.compat.v1.device(var.device): + self._slots['unshrunk_' + name].append( + tf.Variable( + tf.compat.v1.zeros_like( + tf.cond( + tf.compat.v1.is_variable_initialized(var), + var.read_value, + lambda: var.initial_value), + tf.dtypes.float32), + name=var.op.name + '_unshrunk')) + + def _assert_specified(self, items, check_in): + for x in items: + if check_in[x] is None: + raise ValueError(check_in[x] + ' must be specified.') + + def _assert_list(self, items, check_in): + for x in items: + if not isinstance(check_in[x], list): + raise ValueError(x + ' must be a list.') + + def _var_to_list(self, var): + """Wraps var in a list if it is not a list or PartitionedVariable.""" + if not isinstance(var, (list, var_ops.PartitionedVariable)): + var = [var] + return var + + def _l1_loss(self): + """Computes the (un-normalized) l1 loss of the model.""" + with name_scope('sdca/l1_loss'): + sums = [] + for name in ['sparse_features_weights', 'dense_features_weights']: + for var in self._variables[name]: + for v in self._var_to_list(var): + weights = internal_convert_to_tensor(v) + with tf.compat.v1.device(weights.device): + sums.append( + tf.math.reduce_sum( + tf.math.abs(tf.cast(weights, tf.dtypes.float64)))) + # SDCA L1 regularization cost is: l1 * sum(|weights|) + return self._symmetric_l1_regularization() * tf.math.add_n(sums) + + def _l2_loss(self): + """Computes the (un-normalized) l2 loss of the model.""" + with name_scope('sdca/l2_loss'): + sums = [] + for name in ['sparse_features_weights', 'dense_features_weights']: + for var in self._variables[name]: + for v in self._var_to_list(var): + weights = internal_convert_to_tensor(v) + with tf.compat.v1.device(weights.device): + sums.append( + tf.math.reduce_sum( + tf.math.square(tf.cast(weights, tf.dtypes.float64)))) + # SDCA L2 regularization cost is: l2 * sum(weights^2) / 2 + return self._symmetric_l2_regularization() * tf.math.add_n(sums) / 2.0 + + def _convert_n_to_tensor(self, input_list, as_ref=False): + """Converts input list to a set of tensors.""" + # input_list can be a list of Variables (that are implicitly partitioned), + # in which case the underlying logic in internal_convert_to_tensor will not + # concatenate the partitions together. This method takes care of the + # concatenating (we only allow partitioning on the first axis). + output_list = [] + for x in input_list: + tensor_to_convert = x + if isinstance(x, list) or isinstance(x, var_ops.PartitionedVariable): + # We only allow for partitioning on the first axis. + tensor_to_convert = tf.concat(x, axis=0) + output_list.append( + internal_convert_to_tensor(tensor_to_convert, as_ref=as_ref)) + return output_list + + def _get_first_dimension_size_statically(self, w, num_partitions): + """Compute the static size of the first dimension for a sharded variable.""" + dim_0_size = w[0].get_shape()[0] + for p in range(1, num_partitions): + dim_0_size += w[p].get_shape()[0] + return dim_0_size + + def _linear_predictions(self, examples): + """Returns predictions of the form w*x. + + Args: + examples: Examples to compute predictions on. + """ + with name_scope('sdca/prediction'): + batch_size = tf.compat.v1.shape(examples['example_ids'])[0] + + predictions = tf.zeros([batch_size]) + sparse_variables = self._convert_n_to_tensor( + self._variables['sparse_features_weights']) + for sfc, sv in zip(examples['sparse_features'], sparse_variables): + unpadded_dot_product = tf.math.segment_sum( + tf.math.multiply( + tf.compat.v1.gather(sv, sfc.feature_indices), + sfc.feature_values), sfc.example_indices) + predictions += tf.compat.v1.pad( + unpadded_dot_product, + [[0, batch_size - tf.compat.v1.shape(unpadded_dot_product)[0]]]) + + dense_features = self._convert_n_to_tensor(examples['dense_features']) + dense_variables = self._convert_n_to_tensor( + self._variables['dense_features_weights']) + for i in range(len(dense_variables)): + predictions += tf.compat.v1.squeeze( + tf.linalg.matmul(dense_features[i], + tf.compat.v1.expand_dims(dense_variables[i], -1))) + + return predictions + + def predictions(self, examples): + """Add operations to compute predictions by the model. + + If logistic_loss is being used, predicted probabilities are returned. + If poisson_loss is being used, predictions are exponentiated. + Otherwise, (raw) linear predictions (w*x) are returned. + + Args: + examples: Examples to compute predictions on. + + Returns: + An Operation that computes the predictions for examples. + + Raises: + ValueError: if examples are not well defined. + """ + self._assert_specified( + ['example_weights', 'sparse_features', 'dense_features'], examples) + self._assert_list(['sparse_features', 'dense_features'], examples) + + result = self._linear_predictions(examples) + if self._options['loss_type'] == 'logistic_loss': + # Convert logits to probability for logistic loss predictions. + with name_scope('sdca/logistic_prediction'): + result = tf.math.sigmoid(result) + elif self._options['loss_type'] == 'poisson_loss': + # Exponeniate the prediction for poisson loss predictions. + with name_scope('sdca/poisson_prediction'): + result = tf.math.exp(result) + return result + + def _get_partitioned_update_ops(self, v_num, num_partitions_by_var, + p_assignments_by_var, gather_ids_by_var, + weights, full_update, p_assignments, + num_partitions): + """Get updates for partitioned variables.""" + num_partitions = num_partitions_by_var[v_num] + p_assignments = p_assignments_by_var[v_num] + gather_ids = gather_ids_by_var[v_num] + updates = tf.dynamic_partition(full_update, p_assignments, num_partitions) + update_ops = [] + for p in range(num_partitions): + with ops.colocate_with(weights[p]): + result = tf.compat.v1.scatter_add(weights[p], gather_ids[p], updates[p]) + update_ops.append(result) + return update_ops + + def minimize(self, global_step=None, name=None): + """Add operations to train a linear model by minimizing the loss function. + + Args: + global_step: Optional `Variable` to increment by one after the variables + have been updated. + name: Optional name for the returned operation. + + Returns: + An Operation that updates the variables passed in the constructor. + """ + # Technically, the op depends on a lot more than the variables, + # but we'll keep the list short. + with name_scope(name, 'sdca/minimize'): + sparse_example_indices = [] + sparse_feature_indices = [] + sparse_features_values = [] + for sf in self._examples['sparse_features']: + sparse_example_indices.append(sf.example_indices) + sparse_feature_indices.append(sf.feature_indices) + # If feature values are missing, sdca assumes a value of 1.0f. + if sf.feature_values is not None: + sparse_features_values.append(sf.feature_values) + + example_ids_hashed = tf.compat.v1.train.sdca_fprint( + internal_convert_to_tensor(self._examples['example_ids'])) + example_state_data = self._hashtable.lookup(example_ids_hashed) + # Solver returns example_state_update, new delta sparse_feature_weights + # and delta dense_feature_weights. + + sparse_weights = [] + sparse_indices = [] + # If we have partitioned variables, keep a few dictionaries of Tensors + # around that we need for the assign_add after the op call to + # gen_sdca_ops.sdca_optimizer(). These are keyed because we may have a + # mix of partitioned and un-partitioned variables. + num_partitions_by_var = {} + p_assignments_by_var = {} + gather_ids_by_var = {} + for v_num, (w, i) in enumerate( + zip(self._slots['unshrunk_sparse_features_weights'], + sparse_feature_indices)): + # Append the sparse_indices (in full-variable space). + sparse_idx = tf.cast( + tf.unique(tf.cast(i, tf.dtypes.int32))[0], tf.dtypes.int64) + sparse_indices.append(sparse_idx) + if isinstance(w, list) or isinstance(w, var_ops.PartitionedVariable): + num_partitions = len(w) + flat_ids = tf.reshape(sparse_idx, [-1]) + # We use div partitioning, which is easiest to support downstream. + # Compute num_total_ids as the sum of dim-0 of w, then assign + # to partitions based on a constant number of ids per partition. + # Optimize if we already know the full shape statically. + dim_0_size = self._get_first_dimension_size_statically( + w, num_partitions) + + if tf.compat.dimension_value(dim_0_size): + num_total_ids = tf.constant( + tf.compat.dimension_value(dim_0_size), flat_ids.dtype) + else: + dim_0_sizes = [] + for p in range(num_partitions): + if tf.compat.dimension_value(w[p].shape[0]) is not None: + dim_0_sizes.append(tf.compat.dimension_value(w[p].shape[0])) + else: + with ops.colocate_with(w[p]): + dim_0_sizes.append(tf.compat.v1.shape(w[p])[0]) + num_total_ids = tf.math.reduce_sum( + tf.cast(tf.stack(dim_0_sizes), flat_ids.dtype)) + ids_per_partition = num_total_ids // num_partitions + extras = num_total_ids % num_partitions + + p_assignments = tf.math.maximum(flat_ids // (ids_per_partition + 1), + (flat_ids - extras) // + ids_per_partition) + + # Emulate a conditional using a boolean indicator tensor + new_ids = tf.where(p_assignments < extras, + flat_ids % (ids_per_partition + 1), + (flat_ids - extras) % ids_per_partition) + + # Cast partition assignments to int32 for use in dynamic_partition. + # There really should not be more than 2^32 partitions. + p_assignments = tf.cast(p_assignments, tf.dtypes.int32) + # Partition list of ids based on assignments into num_partitions + # separate lists. + gather_ids = tf.dynamic_partition(new_ids, p_assignments, + num_partitions) + # Add these into the dictionaries for use in the later update. + num_partitions_by_var[v_num] = num_partitions + p_assignments_by_var[v_num] = p_assignments + gather_ids_by_var[v_num] = gather_ids + + # Gather the weights from each partition. + partition_gathered_weights = [] + for p in range(num_partitions): + with ops.colocate_with(w[p]): + partition_gathered_weights.append( + tf.compat.v1.gather(w[p], gather_ids[p])) + + # Stitch the weights back together in the same order they were before + # we dynamic_partitioned them. + condition_indices = tf.dynamic_partition( + tf.range(tf.compat.v1.shape(new_ids)[0]), p_assignments, + num_partitions) + batch_gathered_weights = tf.dynamic_stitch( + condition_indices, partition_gathered_weights) + else: + w_as_tensor = internal_convert_to_tensor(w) + with tf.compat.v1.device(w_as_tensor.device): + batch_gathered_weights = tf.compat.v1.gather( + w_as_tensor, sparse_idx) + sparse_weights.append(batch_gathered_weights) + + if tf.compat.forward_compatible(year=2018, month=10, day=30): + esu, sfw, dfw = gen_sdca_ops.sdca_optimizer_v2( + sparse_example_indices, + sparse_feature_indices, + sparse_features_values, + self._convert_n_to_tensor(self._examples['dense_features']), + internal_convert_to_tensor(self._examples['example_weights']), + internal_convert_to_tensor(self._examples['example_labels']), + sparse_indices, + sparse_weights, + self._convert_n_to_tensor( + self._slots['unshrunk_dense_features_weights']), + example_state_data, + loss_type=self._options['loss_type'], + l1=self._symmetric_l1_regularization(), + l2=self._symmetric_l2_regularization(), + num_loss_partitions=self._num_loss_partitions(), + num_inner_iterations=1, + adaptive=self._adaptive()) + else: + esu, sfw, dfw = tf.compat.v1.train.sdca_optimizer( + sparse_example_indices, + sparse_feature_indices, + sparse_features_values, + self._convert_n_to_tensor(self._examples['dense_features']), + internal_convert_to_tensor(self._examples['example_weights']), + internal_convert_to_tensor(self._examples['example_labels']), + sparse_indices, + sparse_weights, + self._convert_n_to_tensor( + self._slots['unshrunk_dense_features_weights']), + example_state_data, + loss_type=self._options['loss_type'], + l1=self._symmetric_l1_regularization(), + l2=self._symmetric_l2_regularization(), + num_loss_partitions=self._num_loss_partitions(), + num_inner_iterations=1, + adaptative=self._adaptive()) + + with tf.control_dependencies([esu]): + update_ops = [self._hashtable.insert(example_ids_hashed, esu)] + # Update the weights before the proximal step. + for v_num, (w, i, u) in enumerate( + zip(self._slots['unshrunk_sparse_features_weights'], sparse_indices, + sfw)): + if (isinstance(w, var_ops.PartitionedVariable) or + isinstance(w, list)): + update_ops += self._get_partitioned_update_ops( + v_num, num_partitions_by_var, p_assignments_by_var, + gather_ids_by_var, w, u, p_assignments, num_partitions) + else: + update_ops.append(tf.compat.v1.scatter_add(w, i, u)) + for w, u in zip(self._slots['unshrunk_dense_features_weights'], dfw): + if (isinstance(w, var_ops.PartitionedVariable) or + isinstance(w, list)): + split_updates = tf.split( + u, num_or_size_splits=[v.shape.as_list()[0] for v in w]) + for v, split_update in zip(w, split_updates): + update_ops.append(tf.compat.v1.assign_add(v, split_update)) + else: + update_ops.append(tf.compat.v1.assign_add(w, u)) + if global_step is None: + return tf.group(*update_ops) + with tf.control_dependencies(update_ops): + return tf.compat.v1.assign_add(global_step, 1, name=name).op + + def update_weights(self, train_op): + """Updates the model weights. + + This function must be called on at least one worker after `minimize`. + In distributed training this call can be omitted on non-chief workers to + speed up training. + + Args: + train_op: The operation returned by the `minimize` call. + + Returns: + An Operation that updates the model weights. + """ + with tf.control_dependencies([train_op]): + update_ops = [] + # Copy over unshrunk weights to user provided variables. + for name in ['sparse_features_weights', 'dense_features_weights']: + for var, slot_var in zip(self._variables[name], + self._slots['unshrunk_' + name]): + for v, sv in zip(self._var_to_list(var), self._var_to_list(slot_var)): + update_ops.append(v.assign(sv)) + + # Apply proximal step. + if self._symmetric_l1_regularization() > 0: + shrinkage = ( + self._symmetric_l1_regularization() / + self._symmetric_l2_regularization()) + with tf.control_dependencies(update_ops): + update_ops = [] + for name in ['sparse_features_weights', 'dense_features_weights']: + for var in self._variables[name]: + for v in self._var_to_list(var): + with tf.compat.v1.device(v.device): + v_shrunk = tf.math.sign(v) * tf.math.maximum( + 0.0, + tf.math.abs(v) - shrinkage) + update_ops.append(v.assign(v_shrunk)) + return tf.group(*update_ops) + else: + return tf.group(*update_ops) + + def approximate_duality_gap(self): + """Add operations to compute the approximate duality gap. + + Returns: + An Operation that computes the approximate duality gap over all + examples. + """ + with name_scope('sdca/approximate_duality_gap'): + _, values_list = self._hashtable.export_sharded() + shard_sums = [] + for values in values_list: + with tf.compat.v1.device(values.device): + # For large tables to_double() below allocates a large temporary + # tensor that is freed once the sum operation completes. To reduce + # peak memory usage in cases where we have multiple large tables on a + # single device, we serialize these operations. + # Note that we need double precision to get accurate results. + with tf.control_dependencies(shard_sums): + shard_sums.append( + tf.math.reduce_sum(tf.cast(values, dtype=tf.dtypes.float64), 0)) + summed_values = tf.math.add_n(shard_sums) + + primal_loss = summed_values[1] + dual_loss = summed_values[2] + example_weights = summed_values[3] + # Note: we return NaN if there are no weights or all weights are 0, e.g. + # if no examples have been processed + return (primal_loss + dual_loss + self._l1_loss() + + (2.0 * self._l2_loss())) / example_weights + + def unregularized_loss(self, examples): + """Add operations to compute the loss (without the regularization loss). + + Args: + examples: Examples to compute unregularized loss on. + + Returns: + An Operation that computes mean (unregularized) loss for given set of + examples. + + Raises: + ValueError: if examples are not well defined. + """ + self._assert_specified([ + 'example_labels', 'example_weights', 'sparse_features', 'dense_features' + ], examples) + self._assert_list(['sparse_features', 'dense_features'], examples) + with name_scope('sdca/unregularized_loss'): + predictions = tf.cast( + self._linear_predictions(examples), tf.dtypes.float64) + labels = tf.cast( + internal_convert_to_tensor(examples['example_labels']), + tf.dtypes.float64) + weights = tf.cast( + internal_convert_to_tensor(examples['example_weights']), + tf.dtypes.float64) + + if self._options['loss_type'] == 'logistic_loss': + return tf.math.reduce_sum( + tf.math.multiply( + sigmoid_cross_entropy_with_logits( + labels=labels, logits=predictions), + weights)) / tf.math.reduce_sum(weights) + + if self._options['loss_type'] == 'poisson_loss': + return tf.math.reduce_sum( + tf.math.multiply( + log_poisson_loss(targets=labels, log_input=predictions), + weights)) / tf.math.reduce_sum(weights) + + if self._options['loss_type'] in ['hinge_loss', 'smooth_hinge_loss']: + # hinge_loss = max{0, 1 - y_i w*x} where y_i \in {-1, 1}. So, we need to + # first convert 0/1 labels into -1/1 labels. + all_ones = tf.compat.v1.ones_like(predictions) + adjusted_labels = tf.math.subtract(2 * labels, all_ones) + # Tensor that contains (unweighted) error (hinge loss) per + # example. + error = tf.nn.relu( + tf.math.subtract(all_ones, + tf.math.multiply(adjusted_labels, predictions))) + weighted_error = tf.math.multiply(error, weights) + return tf.math.reduce_sum(weighted_error) / tf.math.reduce_sum(weights) + + # squared loss + err = tf.math.subtract(labels, predictions) + + weighted_squared_err = tf.math.multiply(tf.math.square(err), weights) + # SDCA squared loss function is sum(err^2) / (2*sum(weights)) + return (tf.math.reduce_sum(weighted_squared_err) / + (2.0 * tf.math.reduce_sum(weights))) + + def regularized_loss(self, examples): + """Add operations to compute the loss with regularization loss included. + + Args: + examples: Examples to compute loss on. + + Returns: + An Operation that computes mean (regularized) loss for given set of + examples. + Raises: + ValueError: if examples are not well defined. + """ + self._assert_specified([ + 'example_labels', 'example_weights', 'sparse_features', 'dense_features' + ], examples) + self._assert_list(['sparse_features', 'dense_features'], examples) + with name_scope('sdca/regularized_loss'): + weights = internal_convert_to_tensor(examples['example_weights']) + return ((self._l1_loss() + self._l2_loss()) / + tf.math.reduce_sum(tf.cast(weights, tf.dtypes.float64)) + + self.unregularized_loss(examples)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/linear_optimizer/python/utils/sharded_mutable_dense_hashtable.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/linear_optimizer/python/utils/sharded_mutable_dense_hashtable.py new file mode 100644 index 0000000000000000000000000000000000000000..b57492cccd09603112b4c7efdb7e1c4889e6aa32 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/linear_optimizer/python/utils/sharded_mutable_dense_hashtable.py @@ -0,0 +1,375 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Sharded mutable dense hash table.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import functools + +from six.moves import range +import tensorflow as tf +from tensorflow.python.framework import ops +from tensorflow.python.ops import gen_lookup_ops +from tensorflow.python.ops import lookup_ops +from tensorflow.python.training.saver import BaseSaverBuilder +from tensorflow.python.checkpoint import saveable_compat + + +@saveable_compat.legacy_saveable_name("table") +class _MutableDenseHashTable(lookup_ops.LookupInterface): + """Copy of tf.contrib.lookup.MutableDenseHashTable.""" + + # TODO(b/118148303): Swap this with the core version + def __init__(self, + key_dtype, + value_dtype, + default_value, + empty_key, + deleted_key, + initial_num_buckets=None, + shared_name=None, + name="MutableDenseHashTable", + checkpoint=True): + """Creates an empty `_MutableDenseHashTable` object. + + Creates a table, the type of its keys and values are specified by key_dtype + and value_dtype, respectively. + + Args: + key_dtype: the type of the key tensors. + value_dtype: the type of the value tensors. + default_value: The value to use if a key is missing in the table. + empty_key: the key to use to represent empty buckets internally. Must not + be used in insert, remove or lookup operations. + deleted_key: the key to use to represent deleted buckets internally. Must + not be used in insert, remove or lookup operations and be different from + the empty_key. + initial_num_buckets: the initial number of buckets. + shared_name: If non-empty, this table will be shared under the given name + across multiple sessions. + name: A name for the operation (optional). + checkpoint: if True, the contents of the table are saved to and restored + from checkpoints. If `shared_name` is empty for a checkpointed table, it + is shared using the table node name. + + Returns: + A `_MutableDenseHashTable` object. + + Raises: + ValueError: If checkpoint is True and no name was specified. + """ + self._default_value = ops.convert_to_tensor( + default_value, dtype=value_dtype, name="default_value") + self._key_dtype = key_dtype + self._value_dtype = value_dtype + self._initial_num_buckets = initial_num_buckets + self._value_shape = self._default_value.get_shape() + self._checkpoint = checkpoint + self._name = name + + self._empty_key = ops.convert_to_tensor( + empty_key, dtype=key_dtype, name="empty_key") + self._deleted_key = ops.convert_to_tensor( + deleted_key, dtype=key_dtype, name="deleted_key") + if tf.executing_eagerly() and shared_name is None: + # TODO(allenl): This will leak memory due to kernel caching by the + # shared_name attribute value (but is better than the alternative of + # sharing everything by default when executing eagerly; hopefully creating + # tables in a loop is uncommon). + shared_name = "table_%d" % (ops.uid(),) + self._shared_name = shared_name + super(_MutableDenseHashTable, self).__init__(key_dtype, value_dtype) + + self._resource_handle = self._create_resource() + if checkpoint: + saveable = _MutableDenseHashTable._Saveable(self, name) + if not tf.executing_eagerly(): + tf.compat.v1.add_to_collection(tf.compat.v1.GraphKeys.SAVEABLE_OBJECTS, + saveable) + + def _create_resource(self): + # The table must be shared if checkpointing is requested for multi-worker + # training to work correctly. Use the node name if no shared_name has been + # explicitly specified. + use_node_name_sharing = self._checkpoint and self._shared_name is None + table_ref = gen_lookup_ops.mutable_dense_hash_table_v2( + empty_key=self._empty_key, + deleted_key=self._deleted_key, + shared_name=self._shared_name, + use_node_name_sharing=use_node_name_sharing, + value_dtype=self._value_dtype, + value_shape=self._value_shape, + initial_num_buckets=self._initial_num_buckets, + name=self._name) + if tf.executing_eagerly(): + self._table_name = None + else: + self._table_name = table_ref.op.name.split("/")[-1] + return table_ref + + @property + def name(self): + return self._table_name + + def size(self, name=None): + """Compute the number of elements in this table. + + Args: + name: A name for the operation (optional). + + Returns: + A scalar tensor containing the number of elements in this table. + """ + with ops.name_scope(name, "%s_Size" % self.name, + [self.resource_handle]) as name: + with ops.colocate_with(self.resource_handle): + return gen_lookup_ops.lookup_table_size_v2( + self.resource_handle, name=name) + + def lookup(self, keys, name=None): + """Looks up `keys` in a table, outputs the corresponding values. + + The `default_value` is used for keys not present in the table. + + Args: + keys: Keys to look up. Can be a tensor of any shape. Must match the + table's key_dtype. + name: A name for the operation (optional). + + Returns: + A tensor containing the values in the same shape as `keys` using the + table's value type. + + Raises: + TypeError: when `keys` do not match the table data types. + """ + with ops.name_scope(name, "%s_lookup_table_find" % self.name, + [self.resource_handle, keys]) as name: + keys = ops.convert_to_tensor(keys, dtype=self._key_dtype, name="keys") + with ops.colocate_with(self.resource_handle): + values = gen_lookup_ops.lookup_table_find_v2( + self.resource_handle, keys, self._default_value, name=name) + + return values + + def insert(self, keys, values, name=None): + """Associates `keys` with `values`. + + Args: + keys: Keys to insert. Can be a tensor of any shape. Must match the table's + key type. + values: Values to be associated with keys. Must be a tensor of the same + shape as `keys` and match the table's value type. + name: A name for the operation (optional). + + Returns: + The created Operation. + + Raises: + TypeError: when `keys` or `values` doesn't match the table data + types. + """ + with ops.name_scope(name, "%s_lookup_table_insert" % self.name, + [self.resource_handle, keys, values]) as name: + keys = ops.convert_to_tensor(keys, dtype=self._key_dtype, name="keys") + values = ops.convert_to_tensor( + values, dtype=self._value_dtype, name="values") + with ops.colocate_with(self.resource_handle): + op = gen_lookup_ops.lookup_table_insert_v2( + self.resource_handle, keys, values, name=name) + return op + + def export(self, name=None): + """Returns tensors of all keys and values in the table. + + Args: + name: A name for the operation (optional). + + Returns: + A pair of tensors with the first tensor containing all keys and the + second tensors containing all values in the table. + """ + with ops.name_scope(name, "%s_lookup_table_export_values" % self.name, + [self.resource_handle]) as name: + with ops.colocate_with(self.resource_handle): + exported_keys, exported_values = gen_lookup_ops.lookup_table_export_v2( + self.resource_handle, self._key_dtype, self._value_dtype, name=name) + + return exported_keys, exported_values + + def _serialize_to_tensors(self): + tesnors = self.export() + return {"-keys": tesnors[0], "-values": tesnors[1]} + + def _restore_from_tensors(self, restored_tensors): + with ops.colocate_with(self.resource_handle): + return gen_lookup_ops.lookup_table_import_v2(self.resource_handle, + restored_tensors["-keys"], + restored_tensors["-values"]) + + class _Saveable(BaseSaverBuilder.SaveableObject): + """SaveableObject implementation for _MutableDenseHashTable.""" + + def __init__(self, table, name): + tensors = table.export() + specs = [ + BaseSaverBuilder.SaveSpec(tensors[0], "", name + "-keys"), + BaseSaverBuilder.SaveSpec(tensors[1], "", name + "-values") + ] + # pylint: disable=protected-access + super(_MutableDenseHashTable._Saveable, self).__init__(table, specs, name) + + def restore(self, restored_tensors, restored_shapes): + del restored_shapes # unused + # pylint: disable=protected-access + with ops.colocate_with(self.op.resource_handle): + return gen_lookup_ops.lookup_table_import_v2(self.op.resource_handle, + restored_tensors[0], + restored_tensors[1]) + + +# TODO(rohanj): This should subclass Checkpointable and implement +# _gather_saveables_for_checkpoint. +class _ShardedMutableDenseHashTable(object): + """A sharded version of _MutableDenseHashTable. + + It is designed to be interface compatible with LookupInterface and + MutableDenseHashTable, with the exception of the export method, which is + replaced by an export_sharded method. + + The _ShardedMutableDenseHashTable keeps `num_shards` _MutableDenseHashTable + internally. The shard is computed via the modulo operation on the key. + """ + + def __init__(self, + key_dtype, + value_dtype, + default_value, + empty_key, + deleted_key, + num_shards=1, + checkpoint=True, + name="ShardedMutableHashTable"): + self._key_dtype = key_dtype + self._value_dtype = value_dtype + with ops.name_scope(name, "sharded_mutable_hash_table") as scope: + table_shards = [] + for i in range(num_shards): + self._table_name = scope + table_shards.append( + _MutableDenseHashTable( + key_dtype=key_dtype, + value_dtype=value_dtype, + default_value=default_value, + empty_key=empty_key, + deleted_key=deleted_key, + checkpoint=checkpoint, + name="%s-%d-of-%d" % (name, i + 1, num_shards))) + self._table_shards = table_shards + # TODO(andreasst): add a value_shape() method to LookupInterface + # pylint: disable=protected-access + self._value_shape = self._table_shards[0]._value_shape + # pylint: enable=protected-access + + @property + def name(self): + return self._table_name + + @property + def _num_shards(self): + return len(self._table_shards) + + @property + def table_shards(self): + return self._table_shards + + def size(self, name=None): + with ops.name_scope(name, "sharded_mutable_hash_table_size"): + sizes = [self._table_shards[i].size() for i in range(self._num_shards)] + return tf.math.add_n(sizes) + + def _shard_indices(self, keys): + key_shape = keys.get_shape() + if key_shape.ndims > 1: + # If keys are a matrix (i.e. a single key is a vector), we use the first + # element of each key vector to determine the shard. + keys = tf.reshape(tf.slice(keys, [0, 0], [-1, 1]), [-1]) + indices = tf.math.floormod(tf.math.abs(keys), self._num_shards) + return tf.cast(indices, tf.dtypes.int32) + + def _check_keys(self, keys): + if keys.get_shape().ndims != 1 and keys.get_shape().ndims != 2: + raise ValueError("Expected a vector or matrix for keys, got %s." % + keys.get_shape()) + + def lookup(self, keys, name=None): + """Looks up `keys` in a table, outputs the corresponding values.""" + if keys.dtype.base_dtype != self._key_dtype: + raise TypeError("Signature mismatch. Keys must be dtype %s, got %s." % + (self._key_dtype, keys.dtype)) + self._check_keys(keys) + num_shards = self._num_shards + if num_shards == 1: + return self._table_shards[0].lookup(keys, name=name) + + shard_indices = self._shard_indices(keys) + key_shards = tf.dynamic_partition(keys, shard_indices, num_shards) + value_shards = [ + self._table_shards[i].lookup(key_shards[i], name=name) + for i in range(num_shards) + ] + + num_keys = tf.compat.v1.shape(keys)[0] + original_indices = tf.range(num_keys) + partitioned_indices = tf.dynamic_partition(original_indices, shard_indices, + num_shards) + return tf.dynamic_stitch(partitioned_indices, value_shards) + + def insert(self, keys, values, name=None): + """Inserts `keys` in a table.""" + self._check_keys(keys) + num_shards = self._num_shards + if num_shards == 1: + return self._table_shards[0].insert(keys, values, name=name) + + shard_indices = self._shard_indices(keys) + key_shards = tf.dynamic_partition(keys, shard_indices, num_shards) + value_shards = tf.dynamic_partition(values, shard_indices, num_shards) + return_values = [ + self._table_shards[i].insert(key_shards[i], value_shards[i], name=name) + for i in range(num_shards) + ] + + return tf.group(*return_values) + + def export_sharded(self, name=None): + """Returns lists of the keys and values tensors in the sharded table. + + Args: + name: name of the table. + + Returns: + A pair of lists with the first list containing the key tensors and the + second list containing the value tensors from each shard. + """ + keys_list = [] + values_list = [] + for table_shard in self._table_shards: + exported_keys, exported_values = table_shard.export(name=name) + keys_list.append(exported_keys) + values_list.append(exported_values) + return keys_list, values_list diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/linear_testing_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/linear_testing_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..be380f6d521a001973b4f22d3385035e2353090b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/linear_testing_utils.py @@ -0,0 +1,2236 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Utils for testing linear estimators.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import math +import os +import shutil +import tempfile + +import numpy as np +import six +import tensorflow as tf +from tensorflow.core.example import example_pb2 +from tensorflow.core.example import feature_pb2 +from tensorflow.python.feature_column import feature_column_v2 +from tensorflow.python.framework import ops +from tensorflow_estimator.python.estimator import estimator +from tensorflow_estimator.python.estimator.canned import linear +from tensorflow_estimator.python.estimator.canned import metric_keys +from tensorflow_estimator.python.estimator.export import export +from tensorflow_estimator.python.estimator.inputs import numpy_io +from tensorflow_estimator.python.estimator.inputs import pandas_io + +try: + # pylint: disable=g-import-not-at-top + import pandas as pd + HAS_PANDAS = True +except IOError: + # Pandas writes a temporary file during import. If it fails, don't use pandas. + HAS_PANDAS = False +except ImportError: + HAS_PANDAS = False + +# pylint rules which are disabled by default for test files. +# pylint: disable=invalid-name,protected-access,missing-docstring + +# Names of variables created by model. +AGE_WEIGHT_NAME = 'linear/linear_model/age/weights' +HEIGHT_WEIGHT_NAME = 'linear/linear_model/height/weights' +OCCUPATION_WEIGHT_NAME = 'linear/linear_model/occupation/weights' +BIAS_NAME = 'linear/linear_model/bias_weights' +LANGUAGE_WEIGHT_NAME = 'linear/linear_model/language/weights' + + +def assert_close(expected, actual, rtol=1e-04, name='assert_close'): + with ops.name_scope(name, 'assert_close', (expected, actual, rtol)) as scope: + expected = ops.convert_to_tensor(expected, name='expected') + actual = ops.convert_to_tensor(actual, name='actual') + rdiff = tf.math.abs(expected - actual, 'diff') / tf.math.abs(expected) + rtol = ops.convert_to_tensor(rtol, name='rtol') + return tf.compat.v1.debugging.assert_less( + rdiff, + rtol, + data=('Condition expected =~ actual did not hold element-wise:' + 'expected = ', expected, 'actual = ', actual, 'rdiff = ', rdiff, + 'rtol = ', rtol,), + name=scope) + + +def save_variables_to_ckpt(model_dir): + init_all_op = [tf.compat.v1.initializers.global_variables()] + with tf.compat.v1.Session() as sess: + sess.run(init_all_op) + tf.compat.v1.train.Saver().save(sess, os.path.join(model_dir, 'model.ckpt')) + + +def queue_parsed_features(feature_map): + tensors_to_enqueue = [] + keys = [] + for key, tensor in six.iteritems(feature_map): + keys.append(key) + tensors_to_enqueue.append(tensor) + queue_dtypes = [x.dtype for x in tensors_to_enqueue] + input_queue = tf.queue.FIFOQueue(capacity=100, dtypes=queue_dtypes) + tf.compat.v1.train.queue_runner.add_queue_runner( + tf.compat.v1.train.queue_runner.QueueRunner( + input_queue, [input_queue.enqueue(tensors_to_enqueue)])) + dequeued_tensors = input_queue.dequeue() + return {keys[i]: dequeued_tensors[i] for i in range(len(dequeued_tensors))} + + +def sorted_key_dict(unsorted_dict): + return {k: unsorted_dict[k] for k in sorted(unsorted_dict)} + + +def sigmoid(x): + return 1 / (1 + np.exp(-1.0 * x)) + + +def mock_optimizer(testcase, expected_loss=None): + expected_var_names = ['%s:0' % AGE_WEIGHT_NAME, '%s:0' % BIAS_NAME] + + class _Optimizer(tf.keras.optimizers.legacy.Optimizer): + + def get_updates(self, loss, params): + trainable_vars = params + testcase.assertItemsEqual(expected_var_names, + [var.name for var in trainable_vars]) + + # Verify loss. We can't check the value directly, so we add an assert op. + testcase.assertEquals(0, loss.shape.ndims) + if expected_loss is None: + if self.iterations is not None: + return [self.iterations.assign_add(1).op] + return [tf.no_op()] + assert_loss = assert_close( + tf.cast(expected_loss, name='expected', dtype=tf.dtypes.float32), + loss, + name='assert_loss') + with tf.control_dependencies((assert_loss,)): + if self.iterations is not None: + return [self.iterations.assign_add(1).op] + return [tf.no_op()] + + def get_config(self): + config = super(_Optimizer, self).get_config() + return config + + optimizer = _Optimizer(name='my_optimizer') + + return optimizer + + +# TODO(b/36813849): Add tests with dynamic shape inputs using placeholders. +class BaseLinearRegressorEvaluationTest(object): + + def __init__(self, linear_regressor_fn, fc_lib=feature_column_v2): + self._linear_regressor_fn = linear_regressor_fn + self._fc_lib = fc_lib + + def setUp(self): + self._model_dir = tempfile.mkdtemp() + + def tearDown(self): + if self._model_dir: + tf.compat.v1.summary.FileWriterCache.clear() + shutil.rmtree(self._model_dir) + + def test_evaluation_for_simple_data(self): + with tf.Graph().as_default(): + tf.Variable([[11.0]], name=AGE_WEIGHT_NAME) + tf.Variable([2.0], name=BIAS_NAME) + tf.Variable( + 100, name=tf.compat.v1.GraphKeys.GLOBAL_STEP, dtype=tf.dtypes.int64) + save_variables_to_ckpt(self._model_dir) + + linear_regressor = self._linear_regressor_fn( + feature_columns=(self._fc_lib.numeric_column('age'),), + model_dir=self._model_dir) + eval_metrics = linear_regressor.evaluate( + input_fn=lambda: ({ + 'age': ((1,),) + }, ((10.,),)), steps=1) + + # Logit is (1. * 11.0 + 2.0) = 13, while label is 10. Loss is 3**2 = 9. + self.assertDictEqual( + { + metric_keys.MetricKeys.LOSS: 9., + metric_keys.MetricKeys.LOSS_MEAN: 9., + metric_keys.MetricKeys.PREDICTION_MEAN: 13., + metric_keys.MetricKeys.LABEL_MEAN: 10., + tf.compat.v1.GraphKeys.GLOBAL_STEP: 100 + }, eval_metrics) + + def test_evaluation_batch(self): + """Tests evaluation for batch_size==2.""" + with tf.Graph().as_default(): + tf.Variable([[11.0]], name=AGE_WEIGHT_NAME) + tf.Variable([2.0], name=BIAS_NAME) + tf.Variable( + 100, name=tf.compat.v1.GraphKeys.GLOBAL_STEP, dtype=tf.dtypes.int64) + save_variables_to_ckpt(self._model_dir) + + linear_regressor = self._linear_regressor_fn( + feature_columns=(self._fc_lib.numeric_column('age'),), + model_dir=self._model_dir) + eval_metrics = linear_regressor.evaluate( + input_fn=lambda: ({ + 'age': ((1,), (1,)) + }, ((10.,), (10.,))), steps=1) + + # Logit is (1. * 11.0 + 2.0) = 13, while label is 10. + # Loss per example is 3**2 = 9. + # Training loss is the sum over batch size = (9 + 9) / 2 = 9 + # Average loss is the average over batch = 9 + self.assertDictEqual( + { + metric_keys.MetricKeys.LOSS: 9., + metric_keys.MetricKeys.LOSS_MEAN: 9., + metric_keys.MetricKeys.PREDICTION_MEAN: 13., + metric_keys.MetricKeys.LABEL_MEAN: 10., + tf.compat.v1.GraphKeys.GLOBAL_STEP: 100 + }, eval_metrics) + + def test_evaluation_weights(self): + """Tests evaluation with weights.""" + with tf.Graph().as_default(): + tf.Variable([[11.0]], name=AGE_WEIGHT_NAME) + tf.Variable([2.0], name=BIAS_NAME) + tf.Variable( + 100, name=tf.compat.v1.GraphKeys.GLOBAL_STEP, dtype=tf.dtypes.int64) + save_variables_to_ckpt(self._model_dir) + + def _input_fn(): + features = {'age': ((1,), (1,)), 'weights': ((1.,), (2.,))} + labels = ((10.,), (10.,)) + return features, labels + + linear_regressor = self._linear_regressor_fn( + feature_columns=(self._fc_lib.numeric_column('age'),), + weight_column='weights', + model_dir=self._model_dir) + eval_metrics = linear_regressor.evaluate(input_fn=_input_fn, steps=1) + + # Logit is (1. * 11.0 + 2.0) = 13, while label is 10. + # Loss per example is 3**2 = 9. + # Training loss is the weighted sum over batch / batch size = + # (9 + 2*9) / 2 = 13.5 + # average loss is the weighted average = 9 + 2*9 / (1 + 2) = 9 + self.assertDictEqual( + { + metric_keys.MetricKeys.LOSS: 13.5, + metric_keys.MetricKeys.LOSS_MEAN: 9., + metric_keys.MetricKeys.PREDICTION_MEAN: 13., + metric_keys.MetricKeys.LABEL_MEAN: 10., + tf.compat.v1.GraphKeys.GLOBAL_STEP: 100 + }, eval_metrics) + + def test_evaluation_for_multi_dimensions(self): + x_dim = 3 + label_dim = 2 + with tf.Graph().as_default(): + tf.Variable([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]], name=AGE_WEIGHT_NAME) + tf.Variable([7.0, 8.0], name=BIAS_NAME) + tf.Variable(100, name='global_step', dtype=tf.dtypes.int64) + save_variables_to_ckpt(self._model_dir) + + linear_regressor = self._linear_regressor_fn( + feature_columns=(self._fc_lib.numeric_column('age', shape=(x_dim,)),), + label_dimension=label_dim, + model_dir=self._model_dir) + input_fn = numpy_io.numpy_input_fn( + x={ + 'age': np.array([[2., 4., 5.]]), + }, + y=np.array([[46., 58.]]), + batch_size=1, + num_epochs=None, + shuffle=False) + eval_metrics = linear_regressor.evaluate(input_fn=input_fn, steps=1) + + self.assertItemsEqual( + (metric_keys.MetricKeys.LOSS, metric_keys.MetricKeys.LOSS_MEAN, + metric_keys.MetricKeys.PREDICTION_MEAN, + metric_keys.MetricKeys.LABEL_MEAN, tf.compat.v1.GraphKeys.GLOBAL_STEP), + eval_metrics.keys()) + + # Logit is + # [2., 4., 5.] * [1.0, 2.0] + [7.0, 8.0] = [39, 50] + [7.0, 8.0] + # [3.0, 4.0] + # [5.0, 6.0] + # which is [46, 58] + self.assertAlmostEqual(0, eval_metrics[metric_keys.MetricKeys.LOSS]) + + def test_evaluation_for_multiple_feature_columns(self): + with tf.Graph().as_default(): + tf.Variable([[10.0]], name=AGE_WEIGHT_NAME) + tf.Variable([[2.0]], name=HEIGHT_WEIGHT_NAME) + tf.Variable([5.0], name=BIAS_NAME) + tf.Variable( + 100, name=tf.compat.v1.GraphKeys.GLOBAL_STEP, dtype=tf.dtypes.int64) + save_variables_to_ckpt(self._model_dir) + + batch_size = 2 + feature_columns = [ + self._fc_lib.numeric_column('age'), + self._fc_lib.numeric_column('height') + ] + input_fn = numpy_io.numpy_input_fn( + x={ + 'age': np.array([20, 40]), + 'height': np.array([4, 8]) + }, + y=np.array([[213.], [421.]]), + batch_size=batch_size, + num_epochs=None, + shuffle=False) + + est = self._linear_regressor_fn( + feature_columns=feature_columns, model_dir=self._model_dir) + + eval_metrics = est.evaluate(input_fn=input_fn, steps=1) + self.assertItemsEqual( + (metric_keys.MetricKeys.LOSS, metric_keys.MetricKeys.LOSS_MEAN, + metric_keys.MetricKeys.PREDICTION_MEAN, + metric_keys.MetricKeys.LABEL_MEAN, tf.compat.v1.GraphKeys.GLOBAL_STEP), + eval_metrics.keys()) + + # Logit is [(20. * 10.0 + 4 * 2.0 + 5.0), (40. * 10.0 + 8 * 2.0 + 5.0)] = + # [213.0, 421.0], while label is [213., 421.]. Loss = 0. + self.assertAlmostEqual(0, eval_metrics[metric_keys.MetricKeys.LOSS]) + + def test_evaluation_for_multiple_feature_columns_mix(self): + with tf.Graph().as_default(): + tf.Variable([[10.0]], name=AGE_WEIGHT_NAME) + tf.Variable([[2.0]], name=HEIGHT_WEIGHT_NAME) + tf.Variable([5.0], name=BIAS_NAME) + tf.Variable( + 100, name=tf.compat.v1.GraphKeys.GLOBAL_STEP, dtype=tf.dtypes.int64) + save_variables_to_ckpt(self._model_dir) + + batch_size = 2 + feature_columns = [ + tf.feature_column.numeric_column('age'), + tf.feature_column.numeric_column('height') + ] + + def _input_fn(): + features_ds = tf.compat.v1.data.Dataset.from_tensor_slices({ + 'age': np.array([20, 40]), + 'height': np.array([4, 8]) + }) + labels_ds = tf.compat.v1.data.Dataset.from_tensor_slices( + np.array([[213.], [421.]])) + return (tf.compat.v1.data.Dataset.zip( + (features_ds, labels_ds)).batch(batch_size).repeat(None)) + + est = self._linear_regressor_fn( + feature_columns=feature_columns, model_dir=self._model_dir) + + eval_metrics = est.evaluate(input_fn=_input_fn, steps=1) + self.assertItemsEqual( + (metric_keys.MetricKeys.LOSS, metric_keys.MetricKeys.LOSS_MEAN, + metric_keys.MetricKeys.PREDICTION_MEAN, + metric_keys.MetricKeys.LABEL_MEAN, tf.compat.v1.GraphKeys.GLOBAL_STEP), + eval_metrics.keys()) + + # Logit is [(20. * 10.0 + 4 * 2.0 + 5.0), (40. * 10.0 + 8 * 2.0 + 5.0)] = + # [213.0, 421.0], while label is [213., 421.]. Loss = 0. + self.assertAlmostEqual(0, eval_metrics[metric_keys.MetricKeys.LOSS]) + + +class BaseLinearRegressorPredictTest(object): + + def __init__(self, linear_regressor_fn, fc_lib=feature_column_v2): + self._linear_regressor_fn = linear_regressor_fn + self._fc_lib = fc_lib + + def setUp(self): + self._model_dir = tempfile.mkdtemp() + + def tearDown(self): + if self._model_dir: + tf.compat.v1.summary.FileWriterCache.clear() + shutil.rmtree(self._model_dir) + + def test_1d(self): + """Tests predict when all variables are one-dimensional.""" + with tf.Graph().as_default(): + tf.Variable([[10.]], name='linear/linear_model/x/weights') + tf.Variable([.2], name=BIAS_NAME) + tf.Variable(100, name='global_step', dtype=tf.dtypes.int64) + save_variables_to_ckpt(self._model_dir) + + linear_regressor = self._linear_regressor_fn( + feature_columns=(self._fc_lib.numeric_column('x'),), + model_dir=self._model_dir) + + predict_input_fn = numpy_io.numpy_input_fn( + x={'x': np.array([[2.]])}, + y=None, + batch_size=1, + num_epochs=1, + shuffle=False) + predictions = linear_regressor.predict(input_fn=predict_input_fn) + predicted_scores = list([x['predictions'] for x in predictions]) + # x * weight + bias = 2. * 10. + .2 = 20.2 + self.assertAllClose([[20.2]], predicted_scores) + + def testMultiDim(self): + """Tests predict when all variables are multi-dimenstional.""" + batch_size = 2 + label_dimension = 3 + x_dim = 4 + feature_columns = (self._fc_lib.numeric_column('x', shape=(x_dim,)),) + with tf.Graph().as_default(): + tf.Variable( # shape=[x_dim, label_dimension] + [[1., 2., 3.], [2., 3., 4.], [3., 4., 5.], [4., 5., 6.]], + name='linear/linear_model/x/weights') + tf.Variable( # shape=[label_dimension] + [.2, .4, .6], name=BIAS_NAME) + tf.Variable(100, name='global_step', dtype=tf.dtypes.int64) + save_variables_to_ckpt(self._model_dir) + + linear_regressor = self._linear_regressor_fn( + feature_columns=feature_columns, + label_dimension=label_dimension, + model_dir=self._model_dir) + + predict_input_fn = numpy_io.numpy_input_fn( + # x shape=[batch_size, x_dim] + x={'x': np.array([[1., 2., 3., 4.], [5., 6., 7., 8.]])}, + y=None, + batch_size=batch_size, + num_epochs=1, + shuffle=False) + predictions = linear_regressor.predict(input_fn=predict_input_fn) + predicted_scores = list([x['predictions'] for x in predictions]) + # score = x * weight + bias, shape=[batch_size, label_dimension] + self.assertAllClose([[30.2, 40.4, 50.6], [70.2, 96.4, 122.6]], + predicted_scores) + + def testTwoFeatureColumns(self): + """Tests predict with two feature columns.""" + with tf.Graph().as_default(): + tf.Variable([[10.]], name='linear/linear_model/x0/weights') + tf.Variable([[20.]], name='linear/linear_model/x1/weights') + tf.Variable([.2], name=BIAS_NAME) + tf.Variable(100, name='global_step', dtype=tf.dtypes.int64) + save_variables_to_ckpt(self._model_dir) + + linear_regressor = self._linear_regressor_fn( + feature_columns=(self._fc_lib.numeric_column('x0'), + self._fc_lib.numeric_column('x1')), + model_dir=self._model_dir) + + predict_input_fn = numpy_io.numpy_input_fn( + x={ + 'x0': np.array([[2.]]), + 'x1': np.array([[3.]]) + }, + y=None, + batch_size=1, + num_epochs=1, + shuffle=False) + predictions = linear_regressor.predict(input_fn=predict_input_fn) + predicted_scores = list([x['predictions'] for x in predictions]) + # x0 * weight0 + x1 * weight1 + bias = 2. * 10. + 3. * 20 + .2 = 80.2 + self.assertAllClose([[80.2]], predicted_scores) + + def testTwoFeatureColumnsMix(self): + """Tests predict with two feature columns.""" + with tf.Graph().as_default(): + tf.Variable([[10.]], name='linear/linear_model/x0/weights') + tf.Variable([[20.]], name='linear/linear_model/x1/weights') + tf.Variable([.2], name=BIAS_NAME) + tf.Variable(100, name='global_step', dtype=tf.dtypes.int64) + save_variables_to_ckpt(self._model_dir) + + linear_regressor = self._linear_regressor_fn( + feature_columns=(tf.feature_column.numeric_column('x0'), + tf.feature_column.numeric_column('x1')), + model_dir=self._model_dir) + + def _predict_input_fn(): + return tf.compat.v1.data.Dataset.from_tensor_slices({ + 'x0': np.array([[2.]]), + 'x1': np.array([[3.]]) + }).batch(1) + + predictions = linear_regressor.predict(input_fn=_predict_input_fn) + predicted_scores = list([x['predictions'] for x in predictions]) + # x0 * weight0 + x1 * weight1 + bias = 2. * 10. + 3. * 20 + .2 = 80.2 + self.assertAllClose([[80.2]], predicted_scores) + + def testSparseCombiner(self): + w_a = 2.0 + w_b = 3.0 + w_c = 5.0 + bias = 5.0 + with tf.Graph().as_default(): + tf.Variable([[w_a], [w_b], [w_c]], name=LANGUAGE_WEIGHT_NAME) + tf.Variable([bias], name=BIAS_NAME) + tf.Variable( + 1, name=tf.compat.v1.GraphKeys.GLOBAL_STEP, dtype=tf.dtypes.int64) + save_variables_to_ckpt(self._model_dir) + + def _input_fn(): + return tf.compat.v1.data.Dataset.from_tensors({ + 'language': + tf.sparse.SparseTensor( + values=['a', 'c', 'b', 'c'], + indices=[[0, 0], [0, 1], [1, 0], [1, 1]], + dense_shape=[2, 2]), + }) + + feature_columns = (self._fc_lib.categorical_column_with_vocabulary_list( + 'language', vocabulary_list=['a', 'b', 'c']),) + + # Check prediction for each sparse_combiner. + # With sparse_combiner = 'sum', we have + # logits_1 = w_a + w_c + bias + # = 2.0 + 5.0 + 5.0 = 12.0 + # logits_2 = w_b + w_c + bias + # = 3.0 + 5.0 + 5.0 = 13.0 + linear_regressor = self._linear_regressor_fn( + feature_columns=feature_columns, model_dir=self._model_dir) + predictions = linear_regressor.predict(input_fn=_input_fn) + predicted_scores = list([x['predictions'] for x in predictions]) + self.assertAllClose([[12.0], [13.0]], predicted_scores) + + # With sparse_combiner = 'mean', we have + # logits_1 = 1/2 * (w_a + w_c) + bias + # = 1/2 * (2.0 + 5.0) + 5.0 = 8.5 + # logits_2 = 1/2 * (w_b + w_c) + bias + # = 1/2 * (3.0 + 5.0) + 5.0 = 9.0 + linear_regressor = self._linear_regressor_fn( + feature_columns=feature_columns, + model_dir=self._model_dir, + sparse_combiner='mean') + predictions = linear_regressor.predict(input_fn=_input_fn) + predicted_scores = list([x['predictions'] for x in predictions]) + self.assertAllClose([[8.5], [9.0]], predicted_scores) + + # With sparse_combiner = 'sqrtn', we have + # logits_1 = sqrt(2)/2 * (w_a + w_c) + bias + # = sqrt(2)/2 * (2.0 + 5.0) + 5.0 = 9.94974 + # logits_2 = sqrt(2)/2 * (w_b + w_c) + bias + # = sqrt(2)/2 * (3.0 + 5.0) + 5.0 = 10.65685 + linear_regressor = self._linear_regressor_fn( + feature_columns=feature_columns, + model_dir=self._model_dir, + sparse_combiner='sqrtn') + predictions = linear_regressor.predict(input_fn=_input_fn) + predicted_scores = list([x['predictions'] for x in predictions]) + self.assertAllClose([[9.94974], [10.65685]], predicted_scores) + + +class BaseLinearRegressorIntegrationTest(object): + + def __init__(self, linear_regressor_fn, fc_lib=feature_column_v2): + self._linear_regressor_fn = linear_regressor_fn + self._fc_lib = fc_lib + + def setUp(self): + self._model_dir = tempfile.mkdtemp() + + def tearDown(self): + if self._model_dir: + tf.compat.v1.summary.FileWriterCache.clear() + shutil.rmtree(self._model_dir) + + def _test_complete_flow(self, train_input_fn, eval_input_fn, predict_input_fn, + input_dimension, label_dimension, prediction_length): + feature_columns = [ + self._fc_lib.numeric_column('x', shape=(input_dimension,)) + ] + est = self._linear_regressor_fn( + feature_columns=feature_columns, + label_dimension=label_dimension, + model_dir=self._model_dir) + + # TRAIN + # learn y = x + est.train(train_input_fn, steps=200) + + # EVALUTE + scores = est.evaluate(eval_input_fn) + self.assertEqual(200, scores[tf.compat.v1.GraphKeys.GLOBAL_STEP]) + self.assertIn(metric_keys.MetricKeys.LOSS, six.iterkeys(scores)) + + # PREDICT + predictions = np.array( + [x['predictions'] for x in est.predict(predict_input_fn)]) + self.assertAllEqual((prediction_length, label_dimension), predictions.shape) + + # EXPORT + feature_spec = tf.feature_column.make_parse_example_spec(feature_columns) + serving_input_receiver_fn = export.build_parsing_serving_input_receiver_fn( + feature_spec) + export_dir = est.export_saved_model(tempfile.mkdtemp(), + serving_input_receiver_fn) + self.assertTrue(tf.compat.v1.gfile.Exists(export_dir)) + + def test_numpy_input_fn(self): + """Tests complete flow with numpy_input_fn.""" + label_dimension = 2 + input_dimension = label_dimension + batch_size = 10 + prediction_length = batch_size + data = np.linspace(0., 2., batch_size * label_dimension, dtype=np.float32) + data = data.reshape(batch_size, label_dimension) + + train_input_fn = numpy_io.numpy_input_fn( + x={'x': data}, + y=data, + batch_size=batch_size, + num_epochs=None, + shuffle=True) + eval_input_fn = numpy_io.numpy_input_fn( + x={'x': data}, + y=data, + batch_size=batch_size, + num_epochs=1, + shuffle=False) + predict_input_fn = numpy_io.numpy_input_fn( + x={'x': data}, + y=None, + batch_size=batch_size, + num_epochs=1, + shuffle=False) + + self._test_complete_flow( + train_input_fn=train_input_fn, + eval_input_fn=eval_input_fn, + predict_input_fn=predict_input_fn, + input_dimension=input_dimension, + label_dimension=label_dimension, + prediction_length=prediction_length) + + def test_pandas_input_fn(self): + """Tests complete flow with pandas_input_fn.""" + if not HAS_PANDAS: + return + + # Pandas DataFrame natually supports 1 dim data only. + label_dimension = 1 + input_dimension = label_dimension + batch_size = 10 + data = np.array([1., 2., 3., 4.], dtype=np.float32) + x = pd.DataFrame({'x': data}) + y = pd.Series(data) + prediction_length = 4 + + train_input_fn = pandas_io.pandas_input_fn( + x=x, y=y, batch_size=batch_size, num_epochs=None, shuffle=True) + eval_input_fn = pandas_io.pandas_input_fn( + x=x, y=y, batch_size=batch_size, shuffle=False) + predict_input_fn = pandas_io.pandas_input_fn( + x=x, batch_size=batch_size, shuffle=False) + + self._test_complete_flow( + train_input_fn=train_input_fn, + eval_input_fn=eval_input_fn, + predict_input_fn=predict_input_fn, + input_dimension=input_dimension, + label_dimension=label_dimension, + prediction_length=prediction_length) + + def test_input_fn_from_parse_example(self): + """Tests complete flow with input_fn constructed from parse_example.""" + label_dimension = 2 + input_dimension = label_dimension + batch_size = 10 + prediction_length = batch_size + data = np.linspace(0., 2., batch_size * label_dimension, dtype=np.float32) + data = data.reshape(batch_size, label_dimension) + + serialized_examples = [] + for datum in data: + example = example_pb2.Example( + features=feature_pb2.Features( + feature={ + 'x': + feature_pb2.Feature( + float_list=feature_pb2.FloatList(value=datum)), + 'y': + feature_pb2.Feature( + float_list=feature_pb2.FloatList( + value=datum[:label_dimension])), + })) + serialized_examples.append(example.SerializeToString()) + + feature_spec = { + 'x': tf.io.FixedLenFeature([input_dimension], tf.dtypes.float32), + 'y': tf.io.FixedLenFeature([label_dimension], tf.dtypes.float32), + } + + def _train_input_fn(): + feature_map = tf.compat.v1.io.parse_example(serialized_examples, + feature_spec) + features = queue_parsed_features(feature_map) + labels = features.pop('y') + return features, labels + + def _eval_input_fn(): + feature_map = tf.compat.v1.io.parse_example( + tf.compat.v1.train.limit_epochs(serialized_examples, num_epochs=1), + feature_spec) + features = queue_parsed_features(feature_map) + labels = features.pop('y') + return features, labels + + def _predict_input_fn(): + feature_map = tf.compat.v1.io.parse_example( + tf.compat.v1.train.limit_epochs(serialized_examples, num_epochs=1), + feature_spec) + features = queue_parsed_features(feature_map) + features.pop('y') + return features, None + + self._test_complete_flow( + train_input_fn=_train_input_fn, + eval_input_fn=_eval_input_fn, + predict_input_fn=_predict_input_fn, + input_dimension=input_dimension, + label_dimension=label_dimension, + prediction_length=prediction_length) + + +class BaseLinearRegressorTrainingTest(object): + + def __init__(self, linear_regressor_fn, fc_lib=feature_column_v2): + self._linear_regressor_fn = linear_regressor_fn + self._fc_lib = fc_lib + + def setUp(self): + self._model_dir = tempfile.mkdtemp() + + def tearDown(self): + if self._model_dir: + tf.compat.v1.summary.FileWriterCache.clear() + shutil.rmtree(self._model_dir) + + def _assert_checkpoint(self, + expected_global_step, + expected_age_weight=None, + expected_bias=None): + shapes = { + name: shape + for (name, shape) in tf.train.list_variables(self._model_dir) + } + + self.assertEqual([], shapes[tf.compat.v1.GraphKeys.GLOBAL_STEP]) + self.assertEqual( + expected_global_step, + tf.train.load_variable(self._model_dir, + tf.compat.v1.GraphKeys.GLOBAL_STEP)) + + self.assertEqual([1, 1], shapes[AGE_WEIGHT_NAME]) + if expected_age_weight is not None: + self.assertEqual(expected_age_weight, + tf.train.load_variable(self._model_dir, AGE_WEIGHT_NAME)) + + self.assertEqual([1], shapes[BIAS_NAME]) + if expected_bias is not None: + self.assertEqual(expected_bias, + tf.train.load_variable(self._model_dir, BIAS_NAME)) + + def testFromScratchWithDefaultOptimizer(self): + # Create LinearRegressor. + label = 5. + age = 17 + linear_regressor = self._linear_regressor_fn( + feature_columns=(self._fc_lib.numeric_column('age'),), + model_dir=self._model_dir) + + # Train for a few steps, and validate final checkpoint. + num_steps = 10 + linear_regressor.train( + input_fn=lambda: ({ + 'age': ((age,),) + }, ((label,),)), steps=num_steps) + self._assert_checkpoint(num_steps) + + def testTrainWithOneDimLabel(self): + label_dimension = 1 + batch_size = 20 + feature_columns = [self._fc_lib.numeric_column('age', shape=(1,))] + est = self._linear_regressor_fn( + feature_columns=feature_columns, + label_dimension=label_dimension, + model_dir=self._model_dir) + data_rank_1 = np.linspace(0., 2., batch_size, dtype=np.float32) + self.assertEqual((batch_size,), data_rank_1.shape) + + train_input_fn = numpy_io.numpy_input_fn( + x={'age': data_rank_1}, + y=data_rank_1, + batch_size=batch_size, + num_epochs=None, + shuffle=True) + est.train(train_input_fn, steps=200) + self._assert_checkpoint(200) + + def testTrainWithOneDimWeight(self): + label_dimension = 1 + batch_size = 20 + feature_columns = [self._fc_lib.numeric_column('age', shape=(1,))] + est = self._linear_regressor_fn( + feature_columns=feature_columns, + label_dimension=label_dimension, + weight_column='w', + model_dir=self._model_dir) + + data_rank_1 = np.linspace(0., 2., batch_size, dtype=np.float32) + self.assertEqual((batch_size,), data_rank_1.shape) + + train_input_fn = numpy_io.numpy_input_fn( + x={ + 'age': data_rank_1, + 'w': data_rank_1 + }, + y=data_rank_1, + batch_size=batch_size, + num_epochs=None, + shuffle=True) + est.train(train_input_fn, steps=200) + self._assert_checkpoint(200) + + def testFromScratch(self): + # Create LinearRegressor. + label = 5. + age = 17 + # loss = (logits - label)^2 = (0 - 5.)^2 = 25. + mock_opt = mock_optimizer(self, expected_loss=25.) + linear_regressor = self._linear_regressor_fn( + feature_columns=(self._fc_lib.numeric_column('age'),), + model_dir=self._model_dir, + optimizer=mock_opt) + + # Train for a few steps, and validate optimizer and final checkpoint. + num_steps = 10 + linear_regressor.train( + input_fn=lambda: ({ + 'age': ((age,),) + }, ((label,),)), steps=num_steps) + self.assertEqual( + num_steps, + linear_regressor.get_variable_value(mock_opt.iterations.name)) + self._assert_checkpoint( + expected_global_step=num_steps, + expected_age_weight=0., + expected_bias=0.) + + def testFromCheckpoint(self): + # Create initial checkpoint. + age_weight = 10.0 + bias = 5.0 + initial_global_step = 100 + with tf.Graph().as_default(): + tf.Variable([[age_weight]], name=AGE_WEIGHT_NAME) + tf.Variable([bias], name=BIAS_NAME) + tf.Variable( + initial_global_step, + name=tf.compat.v1.GraphKeys.GLOBAL_STEP, + dtype=tf.dtypes.int64) + save_variables_to_ckpt(self._model_dir) + + # logits = age * age_weight + bias = 17 * 10. + 5. = 175 + # loss = (logits - label)^2 = (175 - 5)^2 = 28900 + mock_opt = mock_optimizer(self, expected_loss=28900.) + linear_regressor = self._linear_regressor_fn( + feature_columns=(self._fc_lib.numeric_column('age'),), + model_dir=self._model_dir, + optimizer=mock_opt) + + # Train for a few steps, and validate optimizer and final checkpoint. + num_steps = 10 + linear_regressor.train( + input_fn=lambda: ({ + 'age': ((17,),) + }, ((5.,),)), steps=num_steps) + self.assertEqual( + initial_global_step + num_steps, + linear_regressor.get_variable_value(mock_opt.iterations.name)) + self._assert_checkpoint( + expected_global_step=initial_global_step + num_steps, + expected_age_weight=age_weight, + expected_bias=bias) + + def testFromCheckpointMultiBatch(self): + # Create initial checkpoint. + age_weight = 10.0 + bias = 5.0 + initial_global_step = 100 + with tf.Graph().as_default(): + tf.Variable([[age_weight]], name=AGE_WEIGHT_NAME) + tf.Variable([bias], name=BIAS_NAME) + tf.Variable( + initial_global_step, + name=tf.compat.v1.GraphKeys.GLOBAL_STEP, + dtype=tf.dtypes.int64) + save_variables_to_ckpt(self._model_dir) + + # logits = age * age_weight + bias + # logits[0] = 17 * 10. + 5. = 175 + # logits[1] = 15 * 10. + 5. = 155 + # loss = sum(logits - label)^2 = (175 - 5)^2 + (155 - 3)^2 = 52004 + # expected_loss = loss / 2 = 26002 + mock_opt = mock_optimizer(self, expected_loss=26002.) + linear_regressor = self._linear_regressor_fn( + feature_columns=(self._fc_lib.numeric_column('age'),), + model_dir=self._model_dir, + optimizer=mock_opt) + + # Train for a few steps, and validate optimizer and final checkpoint. + num_steps = 10 + linear_regressor.train( + input_fn=lambda: ({ + 'age': ((17,), (15,)) + }, ((5.,), (3.,))), + steps=num_steps) + self.assertEqual( + initial_global_step + num_steps, + linear_regressor.get_variable_value(mock_opt.iterations.name)) + self._assert_checkpoint( + expected_global_step=initial_global_step + num_steps, + expected_age_weight=age_weight, + expected_bias=bias) + + +class BaseLinearClassifierTrainingTest(object): + + def __init__(self, linear_classifier_fn, fc_lib=feature_column_v2): + self._linear_classifier_fn = linear_classifier_fn + self._fc_lib = fc_lib + + def setUp(self): + self._model_dir = tempfile.mkdtemp() + + def tearDown(self): + if self._model_dir: + shutil.rmtree(self._model_dir) + + def _assert_checkpoint(self, + n_classes, + expected_global_step, + expected_age_weight=None, + expected_bias=None): + logits_dimension = n_classes if n_classes > 2 else 1 + + shapes = { + name: shape + for (name, shape) in tf.train.list_variables(self._model_dir) + } + + self.assertEqual([], shapes[tf.compat.v1.GraphKeys.GLOBAL_STEP]) + self.assertEqual( + expected_global_step, + tf.train.load_variable(self._model_dir, + tf.compat.v1.GraphKeys.GLOBAL_STEP)) + + self.assertEqual([1, logits_dimension], shapes[AGE_WEIGHT_NAME]) + if expected_age_weight is not None: + self.assertAllEqual( + expected_age_weight, + tf.train.load_variable(self._model_dir, AGE_WEIGHT_NAME)) + + self.assertEqual([logits_dimension], shapes[BIAS_NAME]) + if expected_bias is not None: + self.assertAllEqual(expected_bias, + tf.train.load_variable(self._model_dir, BIAS_NAME)) + + def _testFromScratchWithDefaultOptimizer(self, n_classes): + label = 0 + age = 17 + est = linear.LinearClassifierV2( + feature_columns=(self._fc_lib.numeric_column('age'),), + n_classes=n_classes, + model_dir=self._model_dir) + + # Train for a few steps, and validate final checkpoint. + num_steps = 10 + est.train( + input_fn=lambda: ({ + 'age': ((age,),) + }, ((label,),)), steps=num_steps) + self._assert_checkpoint(n_classes, num_steps) + + def testBinaryClassesFromScratchWithDefaultOptimizer(self): + self._testFromScratchWithDefaultOptimizer(n_classes=2) + + def testMultiClassesFromScratchWithDefaultOptimizer(self): + self._testFromScratchWithDefaultOptimizer(n_classes=4) + + def _testTrainWithTwoDimsLabel(self, n_classes): + batch_size = 20 + + est = linear.LinearClassifierV2( + feature_columns=(self._fc_lib.numeric_column('age'),), + n_classes=n_classes, + model_dir=self._model_dir) + data_rank_1 = np.array([0, 1]) + data_rank_2 = np.array([[0], [1]]) + self.assertEqual((2,), data_rank_1.shape) + self.assertEqual((2, 1), data_rank_2.shape) + + train_input_fn = numpy_io.numpy_input_fn( + x={'age': data_rank_1}, + y=data_rank_2, + batch_size=batch_size, + num_epochs=None, + shuffle=True) + est.train(train_input_fn, steps=200) + self._assert_checkpoint(n_classes, 200) + + def testBinaryClassesTrainWithTwoDimsLabel(self): + self._testTrainWithTwoDimsLabel(n_classes=2) + + def testMultiClassesTrainWithTwoDimsLabel(self): + self._testTrainWithTwoDimsLabel(n_classes=4) + + def _testTrainWithOneDimLabel(self, n_classes): + batch_size = 20 + + est = linear.LinearClassifierV2( + feature_columns=(self._fc_lib.numeric_column('age'),), + n_classes=n_classes, + model_dir=self._model_dir) + data_rank_1 = np.array([0, 1]) + self.assertEqual((2,), data_rank_1.shape) + + train_input_fn = numpy_io.numpy_input_fn( + x={'age': data_rank_1}, + y=data_rank_1, + batch_size=batch_size, + num_epochs=None, + shuffle=True) + est.train(train_input_fn, steps=200) + self._assert_checkpoint(n_classes, 200) + + def testBinaryClassesTrainWithOneDimLabel(self): + self._testTrainWithOneDimLabel(n_classes=2) + + def testMultiClassesTrainWithOneDimLabel(self): + self._testTrainWithOneDimLabel(n_classes=4) + + def _testTrainWithTwoDimsWeight(self, n_classes): + batch_size = 20 + + est = linear.LinearClassifierV2( + feature_columns=(self._fc_lib.numeric_column('age'),), + weight_column='w', + n_classes=n_classes, + model_dir=self._model_dir) + data_rank_1 = np.array([0, 1]) + data_rank_2 = np.array([[0], [1]]) + self.assertEqual((2,), data_rank_1.shape) + self.assertEqual((2, 1), data_rank_2.shape) + + train_input_fn = numpy_io.numpy_input_fn( + x={ + 'age': data_rank_1, + 'w': data_rank_2 + }, + y=data_rank_1, + batch_size=batch_size, + num_epochs=None, + shuffle=True) + est.train(train_input_fn, steps=200) + self._assert_checkpoint(n_classes, 200) + + def testBinaryClassesTrainWithTwoDimsWeight(self): + self._testTrainWithTwoDimsWeight(n_classes=2) + + def testMultiClassesTrainWithTwoDimsWeight(self): + self._testTrainWithTwoDimsWeight(n_classes=4) + + def _testTrainWithOneDimWeight(self, n_classes): + batch_size = 20 + + est = linear.LinearClassifierV2( + feature_columns=(self._fc_lib.numeric_column('age'),), + weight_column='w', + n_classes=n_classes, + model_dir=self._model_dir) + data_rank_1 = np.array([0, 1]) + self.assertEqual((2,), data_rank_1.shape) + + train_input_fn = numpy_io.numpy_input_fn( + x={ + 'age': data_rank_1, + 'w': data_rank_1 + }, + y=data_rank_1, + batch_size=batch_size, + num_epochs=None, + shuffle=True) + est.train(train_input_fn, steps=200) + self._assert_checkpoint(n_classes, 200) + + def testBinaryClassesTrainWithOneDimWeight(self): + self._testTrainWithOneDimWeight(n_classes=2) + + def testMultiClassesTrainWithOneDimWeight(self): + self._testTrainWithOneDimWeight(n_classes=4) + + def _testFromScratch(self, n_classes): + label = 1 + age = 17 + # For binary classifier: + # loss = sigmoid_cross_entropy(logits, label) where logits=0 (weights are + # all zero initially) and label = 1 so, + # loss = 1 * -log ( sigmoid(logits) ) = 0.69315 + # For multi class classifier: + # loss = cross_entropy(logits, label) where logits are all 0s (weights are + # all zero initially) and label = 1 so, + # loss = 1 * -log ( 1.0 / n_classes ) + # For this particular test case, as logits are same, the formular + # 1 * -log ( 1.0 / n_classes ) covers both binary and multi class cases. + mock_opt = mock_optimizer( + self, expected_loss=-1 * math.log(1.0 / n_classes)) + + est = linear.LinearClassifierV2( + feature_columns=(self._fc_lib.numeric_column('age'),), + n_classes=n_classes, + optimizer=mock_opt, + model_dir=self._model_dir) + + # Train for a few steps, and validate optimizer and final checkpoint. + num_steps = 10 + est.train( + input_fn=lambda: ({ + 'age': ((age,),) + }, ((label,),)), steps=num_steps) + self.assertEqual(num_steps, + est.get_variable_value(mock_opt.iterations.name)) + self._assert_checkpoint( + n_classes, + expected_global_step=num_steps, + expected_age_weight=[[0.]] if n_classes == 2 else [[0.] * n_classes], + expected_bias=[0.] if n_classes == 2 else [.0] * n_classes) + + def testBinaryClassesFromScratch(self): + self._testFromScratch(n_classes=2) + + def testMultiClassesFromScratch(self): + self._testFromScratch(n_classes=4) + + def _testFromCheckpoint(self, n_classes): + # Create initial checkpoint. + label = 1 + age = 17 + # For binary case, the expected weight has shape (1,1). For multi class + # case, the shape is (1, n_classes). In order to test the weights, set + # weights as 2.0 * range(n_classes). + age_weight = [[2.0]] if n_classes == 2 else (np.reshape( + 2.0 * np.array(list(range(n_classes)), dtype=np.float32), + (1, n_classes))) + bias = [-35.0] if n_classes == 2 else [-35.0] * n_classes + initial_global_step = 100 + with tf.Graph().as_default(): + tf.Variable(age_weight, name=AGE_WEIGHT_NAME) + tf.Variable(bias, name=BIAS_NAME) + tf.Variable( + initial_global_step, + name=tf.compat.v1.GraphKeys.GLOBAL_STEP, + dtype=tf.dtypes.int64) + save_variables_to_ckpt(self._model_dir) + + # For binary classifier: + # logits = age * age_weight + bias = 17 * 2. - 35. = -1. + # loss = sigmoid_cross_entropy(logits, label) + # so, loss = 1 * -log ( sigmoid(-1) ) = 1.3133 + # For multi class classifier: + # loss = cross_entropy(logits, label) + # where logits = 17 * age_weight + bias and label = 1 + # so, loss = 1 * -log ( soft_max(logits)[1] ) + if n_classes == 2: + expected_loss = 1.3133 + else: + logits = age_weight * age + bias + logits_exp = np.exp(logits) + softmax = logits_exp / logits_exp.sum() + expected_loss = -1 * math.log(softmax[0, label]) + + mock_opt = mock_optimizer(self, expected_loss=expected_loss) + + est = linear.LinearClassifierV2( + feature_columns=(self._fc_lib.numeric_column('age'),), + n_classes=n_classes, + optimizer=mock_opt, + model_dir=self._model_dir) + + # Train for a few steps, and validate optimizer and final checkpoint. + num_steps = 10 + est.train( + input_fn=lambda: ({ + 'age': ((age,),) + }, ((label,),)), steps=num_steps) + self.assertEqual(initial_global_step + num_steps, + est.get_variable_value(mock_opt.iterations.name)) + self._assert_checkpoint( + n_classes, + expected_global_step=initial_global_step + num_steps, + expected_age_weight=age_weight, + expected_bias=bias) + + def testBinaryClassesFromCheckpoint(self): + self._testFromCheckpoint(n_classes=2) + + def testMultiClassesFromCheckpoint(self): + self._testFromCheckpoint(n_classes=4) + + def _testFromCheckpointFloatLabels(self, n_classes): + """Tests float labels for binary classification.""" + # Create initial checkpoint. + if n_classes > 2: + return + label = 0.8 + age = 17 + age_weight = [[2.0]] + bias = [-35.0] + initial_global_step = 100 + with tf.Graph().as_default(): + tf.Variable(age_weight, name=AGE_WEIGHT_NAME) + tf.Variable(bias, name=BIAS_NAME) + tf.Variable( + initial_global_step, + name=tf.compat.v1.GraphKeys.GLOBAL_STEP, + dtype=tf.dtypes.int64) + save_variables_to_ckpt(self._model_dir) + + # logits = age * age_weight + bias = 17 * 2. - 35. = -1. + # loss = sigmoid_cross_entropy(logits, label) + # => loss = -0.8 * log(sigmoid(-1)) -0.2 * log(sigmoid(+1)) = 1.1132617 + mock_opt = mock_optimizer(self, expected_loss=1.1132617) + + est = linear.LinearClassifierV2( + feature_columns=(self._fc_lib.numeric_column('age'),), + n_classes=n_classes, + optimizer=mock_opt, + model_dir=self._model_dir) + + # Train for a few steps, and validate optimizer and final checkpoint. + num_steps = 10 + est.train( + input_fn=lambda: ({ + 'age': ((age,),) + }, ((label,),)), steps=num_steps) + self.assertEqual(initial_global_step + num_steps, + est.get_variable_value(mock_opt.iterations.name)) + + def testBinaryClassesFromCheckpointFloatLabels(self): + self._testFromCheckpointFloatLabels(n_classes=2) + + def testMultiClassesFromCheckpointFloatLabels(self): + self._testFromCheckpointFloatLabels(n_classes=4) + + def _testFromCheckpointMultiBatch(self, n_classes): + # Create initial checkpoint. + label = [1, 0] + age = [17.0, 18.5] + # For binary case, the expected weight has shape (1,1). For multi class + # case, the shape is (1, n_classes). In order to test the weights, set + # weights as 2.0 * range(n_classes). + age_weight = [[2.0]] if n_classes == 2 else (np.reshape( + 2.0 * np.array(list(range(n_classes)), dtype=np.float32), + (1, n_classes))) + bias = [-35.0] if n_classes == 2 else [-35.0] * n_classes + initial_global_step = 100 + with tf.Graph().as_default(): + tf.Variable(age_weight, name=AGE_WEIGHT_NAME) + tf.Variable(bias, name=BIAS_NAME) + tf.Variable( + initial_global_step, + name=tf.compat.v1.GraphKeys.GLOBAL_STEP, + dtype=tf.dtypes.int64) + save_variables_to_ckpt(self._model_dir) + + # For binary classifier: + # logits = age * age_weight + bias + # logits[0] = 17 * 2. - 35. = -1. + # logits[1] = 18.5 * 2. - 35. = 2. + # loss = sigmoid_cross_entropy(logits, label) + # so, loss[0] = 1 * -log ( sigmoid(-1) ) = 1.3133 + # loss[1] = (1 - 0) * -log ( 1- sigmoid(2) ) = 2.1269 + # expected_loss = (loss[0] + loss[1]) / batch size (2) + # For multi class classifier: + # loss = cross_entropy(logits, label) + # where logits = [17, 18.5] * age_weight + bias and label = [1, 0] + # so, loss = 1 * -log ( soft_max(logits)[label] ) + # expected_loss = (loss[0] + loss[1]) / batch size (2) + if n_classes == 2: + expected_loss = (1.3133 + 2.1269) / 2 + else: + logits = age_weight * np.reshape(age, (2, 1)) + bias + logits_exp = np.exp(logits) + softmax_row_0 = logits_exp[0] / logits_exp[0].sum() + softmax_row_1 = logits_exp[1] / logits_exp[1].sum() + expected_loss_0 = -1 * math.log(softmax_row_0[label[0]]) + expected_loss_1 = -1 * math.log(softmax_row_1[label[1]]) + expected_loss = (expected_loss_0 + expected_loss_1) / 2 + + mock_opt = mock_optimizer(self, expected_loss=expected_loss) + + est = linear.LinearClassifierV2( + feature_columns=(self._fc_lib.numeric_column('age'),), + n_classes=n_classes, + optimizer=mock_opt, + model_dir=self._model_dir) + + # Train for a few steps, and validate optimizer and final checkpoint. + num_steps = 10 + est.train(input_fn=lambda: ({'age': (age)}, (label)), steps=num_steps) + self.assertEqual(initial_global_step + num_steps, + est.get_variable_value(mock_opt.iterations.name)) + self._assert_checkpoint( + n_classes, + expected_global_step=initial_global_step + num_steps, + expected_age_weight=age_weight, + expected_bias=bias) + + def testBinaryClassesFromCheckpointMultiBatch(self): + self._testFromCheckpointMultiBatch(n_classes=2) + + def testMultiClassesFromCheckpointMultiBatch(self): + self._testFromCheckpointMultiBatch(n_classes=4) + + +class BaseLinearClassifierEvaluationTest(object): + + def __init__(self, linear_classifier_fn, fc_lib=feature_column_v2): + self._linear_classifier_fn = linear_classifier_fn + self._fc_lib = fc_lib + + def setUp(self): + self._model_dir = tempfile.mkdtemp() + + def tearDown(self): + if self._model_dir: + shutil.rmtree(self._model_dir) + + def _test_evaluation_for_simple_data(self, n_classes): + label = 1 + age = 1. + + # For binary case, the expected weight has shape (1,1). For multi class + # case, the shape is (1, n_classes). In order to test the weights, set + # weights as 2.0 * range(n_classes). + age_weight = [[-11.0]] if n_classes == 2 else (np.reshape( + -11.0 * np.array(list(range(n_classes)), dtype=np.float32), + (1, n_classes))) + bias = [-30.0] if n_classes == 2 else [-30.0] * n_classes + + with tf.Graph().as_default(): + tf.Variable(age_weight, name=AGE_WEIGHT_NAME) + tf.Variable(bias, name=BIAS_NAME) + tf.Variable( + 100, name=tf.compat.v1.GraphKeys.GLOBAL_STEP, dtype=tf.dtypes.int64) + save_variables_to_ckpt(self._model_dir) + + est = self._linear_classifier_fn( + feature_columns=(self._fc_lib.numeric_column('age'),), + n_classes=n_classes, + model_dir=self._model_dir) + eval_metrics = est.evaluate( + input_fn=lambda: ({ + 'age': ((age,),) + }, ((label,),)), steps=1) + + if n_classes == 2: + # Binary classes: loss = sum(corss_entropy(41)) = 41. + expected_metrics = { + metric_keys.MetricKeys.LOSS: 41., + tf.compat.v1.GraphKeys.GLOBAL_STEP: 100, + metric_keys.MetricKeys.LOSS_MEAN: 41., + metric_keys.MetricKeys.ACCURACY: 0., + metric_keys.MetricKeys.PRECISION: 0., + metric_keys.MetricKeys.RECALL: 0., + metric_keys.MetricKeys.PREDICTION_MEAN: 0., + metric_keys.MetricKeys.LABEL_MEAN: 1., + metric_keys.MetricKeys.ACCURACY_BASELINE: 1, + metric_keys.MetricKeys.AUC: 0., + metric_keys.MetricKeys.AUC_PR: 1., + } + else: + # Multi classes: loss = 1 * -log ( soft_max(logits)[label] ) + logits = age_weight * age + bias + logits_exp = np.exp(logits) + softmax = logits_exp / logits_exp.sum() + expected_loss = -1 * math.log(softmax[0, label]) + + expected_metrics = { + metric_keys.MetricKeys.LOSS: expected_loss, + metric_keys.MetricKeys.LOSS_MEAN: expected_loss, + tf.compat.v1.GraphKeys.GLOBAL_STEP: 100, + metric_keys.MetricKeys.ACCURACY: 0., + } + + self.assertAllClose( + sorted_key_dict(expected_metrics), + sorted_key_dict(eval_metrics), + rtol=1e-3) + + def test_binary_classes_evaluation_for_simple_data(self): + self._test_evaluation_for_simple_data(n_classes=2) + + def test_multi_classes_evaluation_for_simple_data(self): + self._test_evaluation_for_simple_data(n_classes=4) + + def _test_evaluation_batch(self, n_classes): + """Tests evaluation for batch_size==2.""" + label = [1, 0] + age = [17., 18.] + # For binary case, the expected weight has shape (1,1). For multi class + # case, the shape is (1, n_classes). In order to test the weights, set + # weights as 2.0 * range(n_classes). + age_weight = [[2.0]] if n_classes == 2 else (np.reshape( + 2.0 * np.array(list(range(n_classes)), dtype=np.float32), + (1, n_classes))) + bias = [-35.0] if n_classes == 2 else [-35.0] * n_classes + initial_global_step = 100 + with tf.Graph().as_default(): + tf.Variable(age_weight, name=AGE_WEIGHT_NAME) + tf.Variable(bias, name=BIAS_NAME) + tf.Variable( + initial_global_step, + name=tf.compat.v1.GraphKeys.GLOBAL_STEP, + dtype=tf.dtypes.int64) + save_variables_to_ckpt(self._model_dir) + + est = self._linear_classifier_fn( + feature_columns=(self._fc_lib.numeric_column('age'),), + n_classes=n_classes, + model_dir=self._model_dir) + eval_metrics = est.evaluate( + input_fn=lambda: ({ + 'age': (age) + }, (label)), steps=1) + + if n_classes == 2: + # Logits are (-1., 1.) labels are (1, 0). + # Loss is + # loss for row 1: 1 * -log(sigmoid(-1)) = 1.3133 + # loss for row 2: (1 - 0) * -log(1 - sigmoid(1)) = 1.3133 + expected_loss = (1.3133 * 2) / 2 # Divided by batch size + + expected_metrics = { + metric_keys.MetricKeys.LOSS: expected_loss, + tf.compat.v1.GraphKeys.GLOBAL_STEP: 100, + metric_keys.MetricKeys.LOSS_MEAN: expected_loss, + metric_keys.MetricKeys.ACCURACY: 0., + metric_keys.MetricKeys.PRECISION: 0., + metric_keys.MetricKeys.RECALL: 0., + metric_keys.MetricKeys.PREDICTION_MEAN: 0.5, + metric_keys.MetricKeys.LABEL_MEAN: 0.5, + metric_keys.MetricKeys.ACCURACY_BASELINE: 0.5, + metric_keys.MetricKeys.AUC: 0., + metric_keys.MetricKeys.AUC_PR: 0.3068, + } + else: + # Multi classes: loss = 1 * -log ( soft_max(logits)[label] ) + logits = age_weight * np.reshape(age, (2, 1)) + bias + logits_exp = np.exp(logits) + softmax_row_0 = logits_exp[0] / logits_exp[0].sum() + softmax_row_1 = logits_exp[1] / logits_exp[1].sum() + expected_loss_0 = -1 * math.log(softmax_row_0[label[0]]) + expected_loss_1 = -1 * math.log(softmax_row_1[label[1]]) + expected_loss = (expected_loss_0 + expected_loss_1) / 2 # batch size + + expected_metrics = { + metric_keys.MetricKeys.LOSS: expected_loss, + metric_keys.MetricKeys.LOSS_MEAN: expected_loss, + tf.compat.v1.GraphKeys.GLOBAL_STEP: 100, + metric_keys.MetricKeys.ACCURACY: 0., + } + + self.assertAllClose( + sorted_key_dict(expected_metrics), + sorted_key_dict(eval_metrics), + rtol=1e-3) + + def test_binary_classes_evaluation_batch(self): + self._test_evaluation_batch(n_classes=2) + + def test_multi_classes_evaluation_batch(self): + self._test_evaluation_batch(n_classes=4) + + def _test_evaluation_weights(self, n_classes): + """Tests evaluation with weights.""" + + label = [1, 0] + age = [17., 18.] + weights = [1., 2.] + # For binary case, the expected weight has shape (1,1). For multi class + # case, the shape is (1, n_classes). In order to test the weights, set + # weights as 2.0 * range(n_classes). + age_weight = [[2.0]] if n_classes == 2 else (np.reshape( + 2.0 * np.array(list(range(n_classes)), dtype=np.float32), + (1, n_classes))) + bias = [-35.0] if n_classes == 2 else [-35.0] * n_classes + initial_global_step = 100 + with tf.Graph().as_default(): + tf.Variable(age_weight, name=AGE_WEIGHT_NAME) + tf.Variable(bias, name=BIAS_NAME) + tf.Variable( + initial_global_step, + name=tf.compat.v1.GraphKeys.GLOBAL_STEP, + dtype=tf.dtypes.int64) + save_variables_to_ckpt(self._model_dir) + + est = self._linear_classifier_fn( + feature_columns=(self._fc_lib.numeric_column('age'),), + n_classes=n_classes, + weight_column='w', + model_dir=self._model_dir) + eval_metrics = est.evaluate( + input_fn=lambda: ({ + 'age': (age), + 'w': (weights) + }, (label)), steps=1) + + if n_classes == 2: + # Logits are (-1., 1.) labels are (1, 0). + # Loss is + # loss for row 1: 1 * -log(sigmoid(-1)) = 1.3133 + # loss for row 2: (1 - 0) * -log(1 - sigmoid(1)) = 1.3133 + # weights = [1., 2.] + expected_loss = (1.3133 * (1. + 2.)) / 2 # Divided by batch size + loss_mean = (1.3133 * (1. + 2.)) / (1.0 + 2.0) + label_mean = np.average(label, weights=weights) + logits = [-1, 1] + logistics = sigmoid(np.array(logits)) + predictions_mean = np.average(logistics, weights=weights) + + expected_metrics = { + metric_keys.MetricKeys.LOSS: expected_loss, + tf.compat.v1.GraphKeys.GLOBAL_STEP: 100, + metric_keys.MetricKeys.LOSS_MEAN: loss_mean, + metric_keys.MetricKeys.ACCURACY: 0., + metric_keys.MetricKeys.PRECISION: 0., + metric_keys.MetricKeys.RECALL: 0., + metric_keys.MetricKeys.PREDICTION_MEAN: predictions_mean, + metric_keys.MetricKeys.LABEL_MEAN: label_mean, + metric_keys.MetricKeys.ACCURACY_BASELINE: + (max(label_mean, 1 - label_mean)), + metric_keys.MetricKeys.AUC: 0., + metric_keys.MetricKeys.AUC_PR: 0.1891, + } + else: + # Multi classes: unweighted_loss = 1 * -log ( soft_max(logits)[label] ) + logits = age_weight * np.reshape(age, (2, 1)) + bias + logits_exp = np.exp(logits) + softmax_row_0 = logits_exp[0] / logits_exp[0].sum() + softmax_row_1 = logits_exp[1] / logits_exp[1].sum() + expected_loss_0 = -1 * math.log(softmax_row_0[label[0]]) + expected_loss_1 = -1 * math.log(softmax_row_1[label[1]]) + loss_mean = np.average([expected_loss_0, expected_loss_1], + weights=weights) + expected_loss = (loss_mean * np.sum(weights)) / 2 # batch size + + expected_metrics = { + metric_keys.MetricKeys.LOSS: expected_loss, + metric_keys.MetricKeys.LOSS_MEAN: loss_mean, + tf.compat.v1.GraphKeys.GLOBAL_STEP: 100, + metric_keys.MetricKeys.ACCURACY: 0., + } + + self.assertAllClose( + sorted_key_dict(expected_metrics), + sorted_key_dict(eval_metrics), + rtol=1e-3) + + def test_binary_classes_evaluation_weights(self): + self._test_evaluation_weights(n_classes=2) + + def test_multi_classes_evaluation_weights(self): + self._test_evaluation_weights(n_classes=4) + + +class BaseLinearClassifierPredictTest(object): + + def __init__(self, linear_classifier_fn, fc_lib=feature_column_v2): + self._linear_classifier_fn = linear_classifier_fn + self._fc_lib = fc_lib + + def setUp(self): + self._model_dir = tempfile.mkdtemp() + + def tearDown(self): + if self._model_dir: + shutil.rmtree(self._model_dir) + + def _testPredictions(self, n_classes, label_vocabulary, label_output_fn): + """Tests predict when all variables are one-dimensional.""" + age = 1. + + # For binary case, the expected weight has shape (1,1). For multi class + # case, the shape is (1, n_classes). In order to test the weights, set + # weights as 2.0 * range(n_classes). + age_weight = [[-11.0]] if n_classes == 2 else (np.reshape( + -11.0 * np.array(list(range(n_classes)), dtype=np.float32), + (1, n_classes))) + bias = [10.0] if n_classes == 2 else [10.0] * n_classes + + with tf.Graph().as_default(): + tf.Variable(age_weight, name=AGE_WEIGHT_NAME) + tf.Variable(bias, name=BIAS_NAME) + tf.Variable(100, name='global_step', dtype=tf.dtypes.int64) + save_variables_to_ckpt(self._model_dir) + + est = self._linear_classifier_fn( + feature_columns=(self._fc_lib.numeric_column('age'),), + label_vocabulary=label_vocabulary, + n_classes=n_classes, + model_dir=self._model_dir) + + predict_input_fn = numpy_io.numpy_input_fn( + x={'age': np.array([[age]])}, + y=None, + batch_size=1, + num_epochs=1, + shuffle=False) + predictions = list(est.predict(input_fn=predict_input_fn)) + + if n_classes == 2: + scalar_logits = np.reshape(np.array(age_weight) * age + bias, (1,)).item() + two_classes_logits = [0, scalar_logits] + two_classes_logits_exp = np.exp(two_classes_logits) + softmax = two_classes_logits_exp / two_classes_logits_exp.sum() + + expected_predictions = { + 'class_ids': [0], + 'all_class_ids': [0, 1], + 'classes': [label_output_fn(0)], + 'all_classes': [label_output_fn(0), + label_output_fn(1)], + 'logistic': [sigmoid(np.array(scalar_logits))], + 'logits': [scalar_logits], + 'probabilities': softmax, + } + else: + onedim_logits = np.reshape(np.array(age_weight) * age + bias, (-1,)) + class_ids = onedim_logits.argmax() + all_class_ids = list(range(len(onedim_logits))) + logits_exp = np.exp(onedim_logits) + softmax = logits_exp / logits_exp.sum() + expected_predictions = { + 'class_ids': [class_ids], + 'all_class_ids': all_class_ids, + 'classes': [label_output_fn(class_ids)], + 'all_classes': [label_output_fn(i) for i in all_class_ids], + 'logits': onedim_logits, + 'probabilities': softmax, + } + + self.assertEqual(1, len(predictions)) + # assertAllClose cannot handle byte type. + self.assertEqual(expected_predictions['classes'], predictions[0]['classes']) + expected_predictions.pop('classes') + predictions[0].pop('classes') + self.assertAllEqual(expected_predictions['all_classes'], + predictions[0]['all_classes']) + expected_predictions.pop('all_classes') + predictions[0].pop('all_classes') + self.assertAllClose( + sorted_key_dict(expected_predictions), sorted_key_dict(predictions[0])) + + def testBinaryClassesWithoutLabelVocabulary(self): + n_classes = 2 + self._testPredictions( + n_classes, + label_vocabulary=None, + label_output_fn=lambda x: ('%s' % x).encode()) + + def testBinaryClassesWithLabelVocabulary(self): + n_classes = 2 + self._testPredictions( + n_classes, + label_vocabulary=['class_vocab_{}'.format(i) for i in range(n_classes)], + label_output_fn=lambda x: ('class_vocab_%s' % x).encode()) + + def testMultiClassesWithoutLabelVocabulary(self): + n_classes = 4 + self._testPredictions( + n_classes, + label_vocabulary=None, + label_output_fn=lambda x: ('%s' % x).encode()) + + def testMultiClassesWithLabelVocabulary(self): + n_classes = 4 + self._testPredictions( + n_classes, + label_vocabulary=['class_vocab_{}'.format(i) for i in range(n_classes)], + label_output_fn=lambda x: ('class_vocab_%s' % x).encode()) + + def testSparseCombiner(self): + w_a = 2.0 + w_b = 3.0 + w_c = 5.0 + bias = 5.0 + with tf.Graph().as_default(): + tf.Variable([[w_a], [w_b], [w_c]], name=LANGUAGE_WEIGHT_NAME) + tf.Variable([bias], name=BIAS_NAME) + tf.Variable( + 1, name=tf.compat.v1.GraphKeys.GLOBAL_STEP, dtype=tf.dtypes.int64) + save_variables_to_ckpt(self._model_dir) + + def _input_fn(): + return tf.compat.v1.data.Dataset.from_tensors({ + 'language': + tf.sparse.SparseTensor( + values=['a', 'c', 'b', 'c'], + indices=[[0, 0], [0, 1], [1, 0], [1, 1]], + dense_shape=[2, 2]), + }) + + feature_columns = (self._fc_lib.categorical_column_with_vocabulary_list( + 'language', vocabulary_list=['a', 'b', 'c']),) + + # Check prediction for each sparse_combiner. + # With sparse_combiner = 'sum', we have + # logits_1 = w_a + w_c + bias + # = 2.0 + 5.0 + 5.0 = 12.0 + # logits_2 = w_b + w_c + bias + # = 3.0 + 5.0 + 5.0 = 13.0 + linear_classifier = self._linear_classifier_fn( + feature_columns=feature_columns, model_dir=self._model_dir) + predictions = linear_classifier.predict(input_fn=_input_fn) + predicted_scores = list([x['logits'] for x in predictions]) + self.assertAllClose([[12.0], [13.0]], predicted_scores) + + # With sparse_combiner = 'mean', we have + # logits_1 = 1/2 * (w_a + w_c) + bias + # = 1/2 * (2.0 + 5.0) + 5.0 = 8.5 + # logits_2 = 1/2 * (w_b + w_c) + bias + # = 1/2 * (3.0 + 5.0) + 5.0 = 9.0 + linear_classifier = self._linear_classifier_fn( + feature_columns=feature_columns, + model_dir=self._model_dir, + sparse_combiner='mean') + predictions = linear_classifier.predict(input_fn=_input_fn) + predicted_scores = list([x['logits'] for x in predictions]) + self.assertAllClose([[8.5], [9.0]], predicted_scores) + + # With sparse_combiner = 'sqrtn', we have + # logits_1 = sqrt(2)/2 * (w_a + w_c) + bias + # = sqrt(2)/2 * (2.0 + 5.0) + 5.0 = 9.94974 + # logits_2 = sqrt(2)/2 * (w_b + w_c) + bias + # = sqrt(2)/2 * (3.0 + 5.0) + 5.0 = 10.65685 + linear_classifier = self._linear_classifier_fn( + feature_columns=feature_columns, + model_dir=self._model_dir, + sparse_combiner='sqrtn') + predictions = linear_classifier.predict(input_fn=_input_fn) + predicted_scores = list([x['logits'] for x in predictions]) + self.assertAllClose([[9.94974], [10.65685]], predicted_scores) + + +class BaseLinearClassifierIntegrationTest(object): + + def __init__(self, linear_classifier_fn, fc_lib=feature_column_v2): + self._linear_classifier_fn = linear_classifier_fn + self._fc_lib = fc_lib + + def setUp(self): + self._model_dir = tempfile.mkdtemp() + + def tearDown(self): + if self._model_dir: + shutil.rmtree(self._model_dir) + + def _test_complete_flow(self, n_classes, train_input_fn, eval_input_fn, + predict_input_fn, input_dimension, prediction_length): + feature_columns = [ + self._fc_lib.numeric_column('x', shape=(input_dimension,)) + ] + est = self._linear_classifier_fn( + feature_columns=feature_columns, + n_classes=n_classes, + model_dir=self._model_dir) + + # TRAIN + # learn y = x + est.train(train_input_fn, steps=200) + + # EVALUTE + scores = est.evaluate(eval_input_fn) + self.assertEqual(200, scores[tf.compat.v1.GraphKeys.GLOBAL_STEP]) + self.assertIn(metric_keys.MetricKeys.LOSS, six.iterkeys(scores)) + + # PREDICT + predictions = np.array( + [x['classes'] for x in est.predict(predict_input_fn)]) + self.assertAllEqual((prediction_length, 1), predictions.shape) + + # EXPORT + feature_spec = tf.feature_column.make_parse_example_spec(feature_columns) + serving_input_receiver_fn = export.build_parsing_serving_input_receiver_fn( + feature_spec) + export_dir = est.export_saved_model(tempfile.mkdtemp(), + serving_input_receiver_fn) + self.assertTrue(tf.compat.v1.gfile.Exists(export_dir)) + + def _test_numpy_input_fn(self, n_classes): + """Tests complete flow with numpy_input_fn.""" + input_dimension = 4 + batch_size = 10 + prediction_length = batch_size + data = np.linspace(0., 2., batch_size * input_dimension, dtype=np.float32) + data = data.reshape(batch_size, input_dimension) + target = np.array([1] * batch_size) + + train_input_fn = numpy_io.numpy_input_fn( + x={'x': data}, + y=target, + batch_size=batch_size, + num_epochs=None, + shuffle=True) + eval_input_fn = numpy_io.numpy_input_fn( + x={'x': data}, + y=target, + batch_size=batch_size, + num_epochs=1, + shuffle=False) + predict_input_fn = numpy_io.numpy_input_fn( + x={'x': data}, + y=None, + batch_size=batch_size, + num_epochs=1, + shuffle=False) + + self._test_complete_flow( + n_classes=n_classes, + train_input_fn=train_input_fn, + eval_input_fn=eval_input_fn, + predict_input_fn=predict_input_fn, + input_dimension=input_dimension, + prediction_length=prediction_length) + + def test_binary_classes_numpy_input_fn(self): + self._test_numpy_input_fn(n_classes=2) + + def test_multi_classes_numpy_input_fn(self): + self._test_numpy_input_fn(n_classes=4) + + def _test_pandas_input_fn(self, n_classes): + """Tests complete flow with pandas_input_fn.""" + if not HAS_PANDAS: + return + + # Pandas DataFrame natually supports 1 dim data only. + input_dimension = 1 + batch_size = 10 + data = np.array([1., 2., 3., 4.], dtype=np.float32) + target = np.array([1, 0, 1, 0], dtype=np.int32) + x = pd.DataFrame({'x': data}) + y = pd.Series(target) + prediction_length = 4 + + train_input_fn = pandas_io.pandas_input_fn( + x=x, y=y, batch_size=batch_size, num_epochs=None, shuffle=True) + eval_input_fn = pandas_io.pandas_input_fn( + x=x, y=y, batch_size=batch_size, shuffle=False) + predict_input_fn = pandas_io.pandas_input_fn( + x=x, batch_size=batch_size, shuffle=False) + + self._test_complete_flow( + n_classes=n_classes, + train_input_fn=train_input_fn, + eval_input_fn=eval_input_fn, + predict_input_fn=predict_input_fn, + input_dimension=input_dimension, + prediction_length=prediction_length) + + def test_binary_classes_pandas_input_fn(self): + self._test_pandas_input_fn(n_classes=2) + + def test_multi_classes_pandas_input_fn(self): + self._test_pandas_input_fn(n_classes=4) + + def _test_input_fn_from_parse_example(self, n_classes): + """Tests complete flow with input_fn constructed from parse_example.""" + input_dimension = 2 + batch_size = 10 + prediction_length = batch_size + data = np.linspace(0., 2., batch_size * input_dimension, dtype=np.float32) + data = data.reshape(batch_size, input_dimension) + target = np.array([1] * batch_size, dtype=np.int64) + + serialized_examples = [] + for x, y in zip(data, target): + example = example_pb2.Example( + features=feature_pb2.Features( + feature={ + 'x': + feature_pb2.Feature( + float_list=feature_pb2.FloatList(value=x)), + 'y': + feature_pb2.Feature( + int64_list=feature_pb2.Int64List(value=[y])), + })) + serialized_examples.append(example.SerializeToString()) + + feature_spec = { + 'x': tf.io.FixedLenFeature([input_dimension], tf.dtypes.float32), + 'y': tf.io.FixedLenFeature([1], tf.dtypes.int64), + } + + def _train_input_fn(): + feature_map = tf.compat.v1.io.parse_example(serialized_examples, + feature_spec) + features = queue_parsed_features(feature_map) + labels = features.pop('y') + return features, labels + + def _eval_input_fn(): + feature_map = tf.compat.v1.io.parse_example( + tf.compat.v1.train.limit_epochs(serialized_examples, num_epochs=1), + feature_spec) + features = queue_parsed_features(feature_map) + labels = features.pop('y') + return features, labels + + def _predict_input_fn(): + feature_map = tf.compat.v1.io.parse_example( + tf.compat.v1.train.limit_epochs(serialized_examples, num_epochs=1), + feature_spec) + features = queue_parsed_features(feature_map) + features.pop('y') + return features, None + + self._test_complete_flow( + n_classes=n_classes, + train_input_fn=_train_input_fn, + eval_input_fn=_eval_input_fn, + predict_input_fn=_predict_input_fn, + input_dimension=input_dimension, + prediction_length=prediction_length) + + def test_binary_classes_input_fn_from_parse_example(self): + self._test_input_fn_from_parse_example(n_classes=2) + + def test_multi_classes_input_fn_from_parse_example(self): + self._test_input_fn_from_parse_example(n_classes=4) + + +class BaseLinearLogitFnTest(object): + + def __init__(self, fc_lib=feature_column_v2): + self._fc_lib = fc_lib + + def test_basic_logit_correctness(self): + """linear_logit_fn simply wraps feature_column_lib.linear_model.""" + age = self._fc_lib.numeric_column('age') + with tf.Graph().as_default(): + logit_fn = linear.linear_logit_fn_builder(units=2, feature_columns=[age]) + logits = logit_fn(features={'age': [[23.], [31.]]}) + bias_var = tf.compat.v1.get_collection( + tf.compat.v1.GraphKeys.GLOBAL_VARIABLES, + 'linear_model/bias_weights')[0] + age_var = tf.compat.v1.get_collection( + tf.compat.v1.GraphKeys.GLOBAL_VARIABLES, 'linear_model/age')[0] + with tf.compat.v1.Session() as sess: + sess.run([tf.compat.v1.initializers.global_variables()]) + self.assertAllClose([[0., 0.], [0., 0.]], logits.eval()) + sess.run(bias_var.assign([10., 5.])) + self.assertAllClose([[10., 5.], [10., 5.]], logits.eval()) + sess.run(age_var.assign([[2.0, 3.0]])) + # [2 * 23 + 10, 3 * 23 + 5] = [56, 74]. + # [2 * 31 + 10, 3 * 31 + 5] = [72, 98] + self.assertAllClose([[56., 74.], [72., 98.]], logits.eval()) + + def test_compute_fraction_of_zero_v2(self): + """Tests the calculation of sparsity.""" + if self._fc_lib != feature_column_v2: + return + + age = tf.feature_column.numeric_column('age') + occupation = tf.feature_column.categorical_column_with_hash_bucket( + 'occupation', hash_bucket_size=5) + with tf.Graph().as_default(): + model = linear.LinearModel( + feature_columns=[age, occupation], units=3, name='linear_model') + features = { + 'age': [[23.], [31.]], + 'occupation': [['doctor'], ['engineer']] + } + model(features) + variables = model.variables + variables.remove(model.bias) + fraction_zero = linear._compute_fraction_of_zero(variables) + age_var = tf.compat.v1.get_collection( + tf.compat.v1.GraphKeys.GLOBAL_VARIABLES, 'linear_model/age')[0] + with tf.compat.v1.Session() as sess: + sess.run([tf.compat.v1.initializers.global_variables()]) + # Upon initialization, all variables will be zero. + self.assertAllClose(1, fraction_zero.eval()) + + sess.run(age_var.assign([[2.0, 0.0, -1.0]])) + # 1 of the 3 age weights are zero, and all of the 15 (5 hash buckets + # x 3-dim output) are zero. + self.assertAllClose(16. / 18., fraction_zero.eval()) + + +class BaseLinearWarmStartingTest(object): + + def __init__(self, + _linear_classifier_fn, + _linear_regressor_fn, + fc_lib=feature_column_v2): + self._linear_classifier_fn = _linear_classifier_fn + self._linear_regressor_fn = _linear_regressor_fn + self._fc_lib = fc_lib + + def setUp(self): + # Create a directory to save our old checkpoint and vocabularies to. + self._ckpt_and_vocab_dir = tempfile.mkdtemp() + + # Make a dummy input_fn. + def _input_fn(): + features = { + 'age': [[23.], [31.]], + 'age_in_years': [[23.], [31.]], + 'occupation': [['doctor'], ['consultant']] + } + return features, [0, 1] + + self._input_fn = _input_fn + + def tearDown(self): + # Clean up checkpoint / vocab dir. + tf.compat.v1.summary.FileWriterCache.clear() + shutil.rmtree(self._ckpt_and_vocab_dir) + + def test_classifier_basic_warm_starting(self): + """Tests correctness of LinearClassifier default warm-start.""" + age = self._fc_lib.numeric_column('age') + + # Create a LinearClassifier and train to save a checkpoint. + linear_classifier = self._linear_classifier_fn( + feature_columns=[age], + model_dir=self._ckpt_and_vocab_dir, + n_classes=4, + optimizer='SGD') + linear_classifier.train(input_fn=self._input_fn, max_steps=1) + + # Create a second LinearClassifier, warm-started from the first. Use a + # learning_rate = 0.0 optimizer to check values (use SGD so we don't have + # accumulator values that change). + warm_started_linear_classifier = self._linear_classifier_fn( + feature_columns=[age], + n_classes=4, + optimizer=tf.keras.optimizers.legacy.SGD(learning_rate=0.0), + warm_start_from=linear_classifier.model_dir) + + warm_started_linear_classifier.train(input_fn=self._input_fn, max_steps=1) + for variable_name in warm_started_linear_classifier.get_variable_names(): + # Learning rate is also checkpointed in V2 optimizer. So we need to make + # sure it uses the new value after warm started. + if 'learning_rate' in variable_name: + self.assertAllClose( + 0.0, + warm_started_linear_classifier.get_variable_value(variable_name)) + else: + self.assertAllClose( + linear_classifier.get_variable_value(variable_name), + warm_started_linear_classifier.get_variable_value(variable_name)) + + def test_regressor_basic_warm_starting(self): + """Tests correctness of LinearRegressor default warm-start.""" + age = self._fc_lib.numeric_column('age') + + # Create a LinearRegressor and train to save a checkpoint. + linear_regressor = self._linear_regressor_fn( + feature_columns=[age], + model_dir=self._ckpt_and_vocab_dir, + optimizer='SGD') + linear_regressor.train(input_fn=self._input_fn, max_steps=1) + + # Create a second LinearRegressor, warm-started from the first. Use a + # learning_rate = 0.0 optimizer to check values (use SGD so we don't have + # accumulator values that change). + warm_started_linear_regressor = self._linear_regressor_fn( + feature_columns=[age], + optimizer=tf.keras.optimizers.legacy.SGD(learning_rate=0.0), + warm_start_from=linear_regressor.model_dir) + + warm_started_linear_regressor.train(input_fn=self._input_fn, max_steps=1) + for variable_name in warm_started_linear_regressor.get_variable_names(): + # Learning rate is also checkpointed in V2 optimizer. So we need to make + # sure it uses the new value after warm started. + if 'learning_rate' in variable_name: + self.assertAllClose( + 0.0, + warm_started_linear_regressor.get_variable_value(variable_name)) + else: + self.assertAllClose( + linear_regressor.get_variable_value(variable_name), + warm_started_linear_regressor.get_variable_value(variable_name)) + + def test_warm_starting_selective_variables(self): + """Tests selecting variables to warm-start.""" + age = self._fc_lib.numeric_column('age') + + # Create a LinearClassifier and train to save a checkpoint. + linear_classifier = self._linear_classifier_fn( + feature_columns=[age], + model_dir=self._ckpt_and_vocab_dir, + n_classes=4, + optimizer='SGD') + linear_classifier.train(input_fn=self._input_fn, max_steps=1) + + # Create a second LinearClassifier, warm-started from the first. Use a + # learning_rate = 0.0 optimizer to check values (use SGD so we don't have + # accumulator values that change). + warm_started_linear_classifier = self._linear_classifier_fn( + feature_columns=[age], + n_classes=4, + optimizer=tf.keras.optimizers.legacy.SGD(learning_rate=0.0), + # The provided regular expression will only warm-start the age variable + # and not the bias. + warm_start_from=estimator.WarmStartSettings( + ckpt_to_initialize_from=linear_classifier.model_dir, + vars_to_warm_start='.*(age).*')) + + warm_started_linear_classifier.train(input_fn=self._input_fn, max_steps=1) + self.assertAllClose( + linear_classifier.get_variable_value(AGE_WEIGHT_NAME), + warm_started_linear_classifier.get_variable_value(AGE_WEIGHT_NAME)) + # Bias should still be zero from initialization. + self.assertAllClose( + [0.0] * 4, warm_started_linear_classifier.get_variable_value(BIAS_NAME)) + + def test_warm_starting_with_vocab_remapping_and_partitioning(self): + """Tests warm-starting with vocab remapping and partitioning.""" + vocab_list = ['doctor', 'lawyer', 'consultant'] + vocab_file = os.path.join(self._ckpt_and_vocab_dir, 'occupation_vocab') + with open(vocab_file, 'w') as f: + f.write('\n'.join(vocab_list)) + occupation = self._fc_lib.categorical_column_with_vocabulary_file( + 'occupation', + vocabulary_file=vocab_file, + vocabulary_size=len(vocab_list)) + + # Create a LinearClassifier and train to save a checkpoint. + linear_classifier = self._linear_classifier_fn( + feature_columns=[occupation], + model_dir=self._ckpt_and_vocab_dir, + n_classes=4, + optimizer='SGD') + linear_classifier.train(input_fn=self._input_fn, max_steps=1) + + # Create a second LinearClassifier, warm-started from the first. Use a + # learning_rate = 0.0 optimizer to check values (use SGD so we don't have + # accumulator values that change). Use a new FeatureColumn with a + # different vocabulary for occupation. + new_vocab_list = ['doctor', 'consultant', 'engineer'] + new_vocab_file = os.path.join(self._ckpt_and_vocab_dir, + 'new_occupation_vocab') + with open(new_vocab_file, 'w') as f: + f.write('\n'.join(new_vocab_list)) + new_occupation = self._fc_lib.categorical_column_with_vocabulary_file( + 'occupation', + vocabulary_file=new_vocab_file, + vocabulary_size=len(new_vocab_list)) + # We can create our VocabInfo object from the new and old occupation + # FeatureColumn's. + occupation_vocab_info = estimator.VocabInfo( + new_vocab=new_occupation.vocabulary_file, + new_vocab_size=new_occupation.vocabulary_size, + num_oov_buckets=new_occupation.num_oov_buckets, + old_vocab=occupation.vocabulary_file, + old_vocab_size=occupation.vocabulary_size, + # Can't use constant_initializer with load_and_remap. In practice, + # use a truncated normal initializer. + backup_initializer=tf.compat.v1.initializers.random_uniform( + minval=0.39, maxval=0.39)) + warm_started_linear_classifier = self._linear_classifier_fn( + feature_columns=[occupation], + n_classes=4, + optimizer=tf.keras.optimizers.legacy.SGD(learning_rate=0.0), + warm_start_from=estimator.WarmStartSettings( + ckpt_to_initialize_from=linear_classifier.model_dir, + var_name_to_vocab_info={ + OCCUPATION_WEIGHT_NAME: occupation_vocab_info + }, + # Explicitly providing None here will only warm-start variables + # referenced in var_name_to_vocab_info (the bias will not be + # warm-started). + vars_to_warm_start=None)) + + warm_started_linear_classifier.train(input_fn=self._input_fn, max_steps=1) + # 'doctor' was ID-0 and still ID-0. + self.assertAllClose( + linear_classifier.get_variable_value(OCCUPATION_WEIGHT_NAME)[0, :], + warm_started_linear_classifier.get_variable_value( + OCCUPATION_WEIGHT_NAME)[0, :]) + # 'consultant' was ID-2 and now ID-1. + self.assertAllClose( + linear_classifier.get_variable_value(OCCUPATION_WEIGHT_NAME)[2, :], + warm_started_linear_classifier.get_variable_value( + OCCUPATION_WEIGHT_NAME)[1, :]) + # 'engineer' is a new entry and should be initialized with the + # backup_initializer in VocabInfo. + self.assertAllClose([0.39] * 4, + warm_started_linear_classifier.get_variable_value( + OCCUPATION_WEIGHT_NAME)[2, :]) + # Bias should still be zero (from initialization logic). + self.assertAllClose( + [0.0] * 4, warm_started_linear_classifier.get_variable_value(BIAS_NAME)) + + def test_warm_starting_with_naming_change(self): + """Tests warm-starting with a Tensor name remapping.""" + age_in_years = self._fc_lib.numeric_column('age_in_years') + + # Create a LinearClassifier and train to save a checkpoint. + linear_classifier = self._linear_classifier_fn( + feature_columns=[age_in_years], + model_dir=self._ckpt_and_vocab_dir, + n_classes=4, + optimizer='SGD') + linear_classifier.train(input_fn=self._input_fn, max_steps=1) + + # Create a second LinearClassifier, warm-started from the first. Use a + # learning_rate = 0.0 optimizer to check values (use SGD so we don't have + # accumulator values that change). + warm_started_linear_classifier = self._linear_classifier_fn( + feature_columns=[self._fc_lib.numeric_column('age')], + n_classes=4, + optimizer=tf.keras.optimizers.legacy.SGD(learning_rate=0.0), + # The 'age' variable correspond to the 'age_in_years' variable in the + # previous model. + warm_start_from=estimator.WarmStartSettings( + ckpt_to_initialize_from=linear_classifier.model_dir, + var_name_to_prev_var_name={ + AGE_WEIGHT_NAME: AGE_WEIGHT_NAME.replace('age', 'age_in_years') + })) + + warm_started_linear_classifier.train(input_fn=self._input_fn, max_steps=1) + self.assertAllClose( + linear_classifier.get_variable_value( + AGE_WEIGHT_NAME.replace('age', 'age_in_years')), + warm_started_linear_classifier.get_variable_value(AGE_WEIGHT_NAME)) + # The bias is also warm-started (with no name remapping). + self.assertAllClose( + linear_classifier.get_variable_value(BIAS_NAME), + warm_started_linear_classifier.get_variable_value(BIAS_NAME)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/metric_keys.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/metric_keys.py new file mode 100644 index 0000000000000000000000000000000000000000..2974306ff808b87b154271fded2df7d4e3b7e5dc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/metric_keys.py @@ -0,0 +1,61 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Enum for model prediction keys.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +from tensorflow_estimator.python.estimator import model_fn + + +class MetricKeys(object): + """Metric key strings.""" + LOSS = model_fn.LOSS_METRIC_KEY + LOSS_MEAN = model_fn.AVERAGE_LOSS_METRIC_KEY + LOSS_REGULARIZATION = 'regularization_loss' + + ACCURACY = 'accuracy' + PRECISION = 'precision' + RECALL = 'recall' + # This is the best the model could do by always predicting one class. + # Should be < ACCURACY in a trained model. + ACCURACY_BASELINE = 'accuracy_baseline' + AUC = 'auc' + AUC_PR = 'auc_precision_recall' + LABEL_MEAN = 'label/mean' + PREDICTION_MEAN = 'prediction/mean' + + # The following require a threshold applied, should be float in range (0, 1). + ACCURACY_AT_THRESHOLD = 'accuracy/positive_threshold_%g' + PRECISION_AT_THRESHOLD = 'precision/positive_threshold_%g' + RECALL_AT_THRESHOLD = 'recall/positive_threshold_%g' + + # The following require a constraint on a competing metric to be applied, + # float in range (0, 1). + PRECISION_AT_RECALL = 'precision_at_recall_%g' + RECALL_AT_PRECISION = 'recall_at_precision_%g' + SENSITIVITY_AT_SPECIFICITY = 'sensitivity_at_specificity_%g' + SPECIFICITY_AT_SENSITIVITY = 'specificity_at_sensitivity_%g' + + # The following require a class id applied. + PROBABILITY_MEAN_AT_CLASS = 'probability_mean/class%d' + AUC_AT_CLASS = 'auc/class%d' + AUC_PR_AT_CLASS = 'auc_precision_recall/class%d' + + # The following require a class name applied. + PROBABILITY_MEAN_AT_NAME = 'probability_mean/%s' + AUC_AT_NAME = 'auc/%s' + AUC_PR_AT_NAME = 'auc_precision_recall/%s' diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/optimizers.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/optimizers.py new file mode 100644 index 0000000000000000000000000000000000000000..fac16e9e0c96cbf8b20c55692845a250ccb89e14 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/optimizers.py @@ -0,0 +1,159 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Methods related to optimizers used in canned_estimators.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import inspect +from absl import logging +import six +import tensorflow as tf + +_OPTIMIZER_CLS_NAMES = { + 'Adagrad': tf.compat.v1.train.AdagradOptimizer, + 'Adam': tf.compat.v1.train.AdamOptimizer, + 'Ftrl': tf.compat.v1.train.FtrlOptimizer, + 'RMSProp': tf.compat.v1.train.RMSPropOptimizer, + 'SGD': tf.compat.v1.train.GradientDescentOptimizer, +} + +_OPTIMIZER_CLS_NAMES_V2 = { + 'Adagrad': tf.keras.optimizers.legacy.Adagrad, + 'Adam': tf.keras.optimizers.legacy.Adam, + 'Ftrl': tf.keras.optimizers.legacy.Ftrl, + 'RMSProp': tf.keras.optimizers.legacy.RMSprop, + 'SGD': tf.keras.optimizers.legacy.SGD, +} + +# The default learning rate of 0.05 is a historical artifact of the initial +# implementation, but seems a reasonable choice. +_LEARNING_RATE = 0.05 + + +def get_optimizer_instance(opt, learning_rate=None): + """Returns an optimizer instance. + + Supports the following types for the given `opt`: + * An `Optimizer` instance: Returns the given `opt`. + * A string: Creates an `Optimizer` subclass with the given `learning_rate`. + Supported strings: + * 'Adagrad': Returns an `AdagradOptimizer`. + * 'Adam': Returns an `AdamOptimizer`. + * 'Ftrl': Returns an `FtrlOptimizer`. + * 'RMSProp': Returns an `RMSPropOptimizer`. + * 'SGD': Returns a `GradientDescentOptimizer`. + + Args: + opt: An `Optimizer` instance, or string, as discussed above. + learning_rate: A float. Only used if `opt` is a string. + + Returns: + An `Optimizer` instance. + + Raises: + ValueError: If `opt` is an unsupported string. + ValueError: If `opt` is a supported string but `learning_rate` was not + specified. + ValueError: If `opt` is none of the above types. + """ + if isinstance(opt, six.string_types): + if opt in six.iterkeys(_OPTIMIZER_CLS_NAMES): + if not learning_rate: + raise ValueError('learning_rate must be specified when opt is string.') + return _OPTIMIZER_CLS_NAMES[opt](learning_rate=learning_rate) + raise ValueError( + 'Unsupported optimizer name: {}. Supported names are: {}'.format( + opt, tuple(sorted(six.iterkeys(_OPTIMIZER_CLS_NAMES))))) + if callable(opt): + opt = opt() + if not isinstance(opt, tf.compat.v1.train.Optimizer): + raise ValueError( + 'The given object is not an Optimizer instance. Given: {}'.format(opt)) + return opt + + +def _optimizer_has_default_learning_rate(opt): + signature = inspect.getfullargspec(opt.__init__) + default_name_to_value = dict(zip(signature.args[::-1], signature.defaults)) + for name in signature.kwonlyargs: + if name in signature.kwonlydefaults: + default_name_to_value[name] = signature.kwonlydefaults[name] + return 'learning_rate' in default_name_to_value + + +def get_optimizer_instance_v2(opt, learning_rate=None): + """Returns an optimizer_v2.OptimizerV2 instance. + + Supports the following types for the given `opt`: + * An `optimizer_v2.OptimizerV2` instance: Returns the given `opt`. + * A string: Creates an `optimizer_v2.OptimizerV2` subclass with the given + `learning_rate`. + Supported strings: + * 'Adagrad': Returns an tf.keras.optimizers.Adagrad. + * 'Adam': Returns an tf.keras.optimizers.Adam. + * 'Ftrl': Returns an tf.keras.optimizers.Ftrl. + * 'RMSProp': Returns an tf.keras.optimizers.RMSProp. + * 'SGD': Returns a tf.keras.optimizers.SGD. + + Args: + opt: An `tf.keras.optimizers.Optimizer` instance, or string, as discussed + above. + learning_rate: A float. Only used if `opt` is a string. If None, and opt is + string, it will use the default learning_rate of the optimizer. + + Returns: + An `tf.keras.optimizers.Optimizer` instance. + + Raises: + ValueError: If `opt` is an unsupported string. + ValueError: If `opt` is a supported string but `learning_rate` was not + specified. + ValueError: If `opt` is none of the above types. + """ + if isinstance(opt, six.string_types): + if opt in six.iterkeys(_OPTIMIZER_CLS_NAMES_V2): + if not learning_rate: + if _optimizer_has_default_learning_rate(_OPTIMIZER_CLS_NAMES_V2[opt]): + return _OPTIMIZER_CLS_NAMES_V2[opt]() + else: + return _OPTIMIZER_CLS_NAMES_V2[opt](learning_rate=_LEARNING_RATE) + return _OPTIMIZER_CLS_NAMES_V2[opt](learning_rate=learning_rate) + raise ValueError( + 'Unsupported optimizer name: {}. Supported names are: {}'.format( + opt, tuple(sorted(six.iterkeys(_OPTIMIZER_CLS_NAMES_V2))))) + if callable(opt): + opt = opt() + if isinstance(opt, tf.keras.optimizers.experimental.Optimizer): + if tf.executing_eagerly(): + logging.warning( + 'You are using `tf.keras.optimizers.experimental.Optimizer` in TF ' + 'estimator, which only supports ' + '`tf.keras.optimizers.legacy.Optimizer`. Automatically converting ' + 'your optimizer to `tf.keras.optimizers.legacy.Optimizer`.') + opt = tf.keras.__internal__.optimizers.convert_to_legacy_optimizer(opt) + else: + raise ValueError('Please set your optimizer as an instance of ' + '`tf.keras.optimizers.legacy.Optimizer`, e.g., ' + f'`tf.keras.optimizers.legacy.{opt.__class__.__name__}`.' + f'Received optimizer type: {type(opt)}.') + if not isinstance( + opt, + (tf.keras.optimizers.legacy.Optimizer, tf.keras.optimizers.Optimizer)): + raise ValueError( + 'The given object is not a tf.keras.optimizers.Optimizer instance.' + ' Given: {}'.format(opt)) + return opt diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/parsing_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/parsing_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..4009ad0a39e016197fbbce6ba8970c51c2d56d6d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/parsing_utils.py @@ -0,0 +1,353 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Parsing related helper function to be used in `input_fn`.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import six +import tensorflow as tf +from tensorflow.python.feature_column import feature_column_lib as fc +from tensorflow_estimator.python.estimator.estimator_export import estimator_export + + +@estimator_export('estimator.classifier_parse_example_spec', v1=[]) +def classifier_parse_example_spec_v2(feature_columns, + label_key, + label_dtype=tf.dtypes.int64, + label_default=None, + weight_column=None): + """Generates parsing spec for tf.parse_example to be used with classifiers. + + If users keep data in tf.Example format, they need to call tf.parse_example + with a proper feature spec. There are two main things that this utility helps: + + * Users need to combine parsing spec of features with labels and weights + (if any) since they are all parsed from same tf.Example instance. This + utility combines these specs. + * It is difficult to map expected label by a classifier such as + `DNNClassifier` to corresponding tf.parse_example spec. This utility encodes + it by getting related information from users (key, dtype). + + Example output of parsing spec: + + ```python + # Define features and transformations + feature_b = tf.feature_column.numeric_column(...) + feature_c_bucketized = tf.feature_column.bucketized_column( + tf.feature_column.numeric_column("feature_c"), ...) + feature_a_x_feature_c = tf.feature_column.crossed_column( + columns=["feature_a", feature_c_bucketized], ...) + + feature_columns = [feature_b, feature_c_bucketized, feature_a_x_feature_c] + parsing_spec = tf.estimator.classifier_parse_example_spec( + feature_columns, label_key='my-label', label_dtype=tf.string) + + # For the above example, classifier_parse_example_spec would return the dict: + assert parsing_spec == { + "feature_a": parsing_ops.VarLenFeature(tf.string), + "feature_b": parsing_ops.FixedLenFeature([1], dtype=tf.float32), + "feature_c": parsing_ops.FixedLenFeature([1], dtype=tf.float32) + "my-label" : parsing_ops.FixedLenFeature([1], dtype=tf.string) + } + ``` + + Example usage with a classifier: + + ```python + feature_columns = # define features via tf.feature_column + estimator = DNNClassifier( + n_classes=1000, + feature_columns=feature_columns, + weight_column='example-weight', + label_vocabulary=['photos', 'keep', ...], + hidden_units=[256, 64, 16]) + # This label configuration tells the classifier the following: + # * weights are retrieved with key 'example-weight' + # * label is string and can be one of the following ['photos', 'keep', ...] + # * integer id for label 'photos' is 0, 'keep' is 1, ... + + + # Input builders + def input_fn_train(): # Returns a tuple of features and labels. + features = tf.contrib.learn.read_keyed_batch_features( + file_pattern=train_files, + batch_size=batch_size, + # creates parsing configuration for tf.parse_example + features=tf.estimator.classifier_parse_example_spec( + feature_columns, + label_key='my-label', + label_dtype=tf.string, + weight_column='example-weight'), + reader=tf.RecordIOReader) + labels = features.pop('my-label') + return features, labels + + estimator.train(input_fn=input_fn_train) + ``` + + Args: + feature_columns: An iterable containing all feature columns. All items + should be instances of classes derived from `FeatureColumn`. + label_key: A string identifying the label. It means tf.Example stores labels + with this key. + label_dtype: A `tf.dtype` identifies the type of labels. By default it is + `tf.int64`. If user defines a `label_vocabulary`, this should be set as + `tf.string`. `tf.float32` labels are only supported for binary + classification. + label_default: used as label if label_key does not exist in given + tf.Example. An example usage: let's say `label_key` is 'clicked' and + tf.Example contains clicked data only for positive examples in following + format `key:clicked, value:1`. This means that if there is no data with + key 'clicked' it should count as negative example by setting + `label_deafault=0`. Type of this value should be compatible with + `label_dtype`. + weight_column: A string or a `NumericColumn` created by + `tf.feature_column.numeric_column` defining feature column representing + weights. It is used to down weight or boost examples during training. It + will be multiplied by the loss of the example. If it is a string, it is + used as a key to fetch weight tensor from the `features`. If it is a + `NumericColumn`, raw tensor is fetched by key `weight_column.key`, then + weight_column.normalizer_fn is applied on it to get weight tensor. + + Returns: + A dict mapping each feature key to a `FixedLenFeature` or `VarLenFeature` + value. + + Raises: + ValueError: If label is used in `feature_columns`. + ValueError: If weight_column is used in `feature_columns`. + ValueError: If any of the given `feature_columns` is not a `_FeatureColumn` + instance. + ValueError: If `weight_column` is not a `NumericColumn` instance. + ValueError: if label_key is None. + """ + parsing_spec = tf.compat.v2.feature_column.make_parse_example_spec(feature_columns) + label_spec = tf.io.FixedLenFeature((1,), label_dtype, label_default) + return _add_label_and_weight_to_parsing_spec( + parsing_spec=parsing_spec, + label_key=label_key, + label_spec=label_spec, + weight_column=weight_column) + + +@estimator_export('estimator.regressor_parse_example_spec', v1=[]) +def regressor_parse_example_spec_v2(feature_columns, + label_key, + label_dtype=tf.dtypes.float32, + label_default=None, + label_dimension=1, + weight_column=None): + """Generates parsing spec for tf.parse_example to be used with regressors. + + If users keep data in tf.Example format, they need to call tf.parse_example + with a proper feature spec. There are two main things that this utility helps: + + * Users need to combine parsing spec of features with labels and weights + (if any) since they are all parsed from same tf.Example instance. This + utility combines these specs. + * It is difficult to map expected label by a regressor such as `DNNRegressor` + to corresponding tf.parse_example spec. This utility encodes it by getting + related information from users (key, dtype). + + Example output of parsing spec: + + ```python + # Define features and transformations + feature_b = tf.feature_column.numeric_column(...) + feature_c_bucketized = tf.feature_column.bucketized_column( + tf.feature_column.numeric_column("feature_c"), ...) + feature_a_x_feature_c = tf.feature_column.crossed_column( + columns=["feature_a", feature_c_bucketized], ...) + + feature_columns = [feature_b, feature_c_bucketized, feature_a_x_feature_c] + parsing_spec = tf.estimator.regressor_parse_example_spec( + feature_columns, label_key='my-label') + + # For the above example, regressor_parse_example_spec would return the dict: + assert parsing_spec == { + "feature_a": parsing_ops.VarLenFeature(tf.string), + "feature_b": parsing_ops.FixedLenFeature([1], dtype=tf.float32), + "feature_c": parsing_ops.FixedLenFeature([1], dtype=tf.float32) + "my-label" : parsing_ops.FixedLenFeature([1], dtype=tf.float32) + } + ``` + + Example usage with a regressor: + + ```python + feature_columns = # define features via tf.feature_column + estimator = DNNRegressor( + hidden_units=[256, 64, 16], + feature_columns=feature_columns, + weight_column='example-weight', + label_dimension=3) + # This label configuration tells the regressor the following: + # * weights are retrieved with key 'example-weight' + # * label is a 3 dimension tensor with float32 dtype. + + + # Input builders + def input_fn_train(): # Returns a tuple of features and labels. + features = tf.contrib.learn.read_keyed_batch_features( + file_pattern=train_files, + batch_size=batch_size, + # creates parsing configuration for tf.parse_example + features=tf.estimator.classifier_parse_example_spec( + feature_columns, + label_key='my-label', + label_dimension=3, + weight_column='example-weight'), + reader=tf.RecordIOReader) + labels = features.pop('my-label') + return features, labels + + estimator.train(input_fn=input_fn_train) + ``` + + Args: + feature_columns: An iterable containing all feature columns. All items + should be instances of classes derived from `_FeatureColumn`. + label_key: A string identifying the label. It means tf.Example stores labels + with this key. + label_dtype: A `tf.dtype` identifies the type of labels. By default it is + `tf.float32`. + label_default: used as label if label_key does not exist in given + tf.Example. By default default_value is none, which means + `tf.parse_example` will error out if there is any missing label. + label_dimension: Number of regression targets per example. This is the size + of the last dimension of the labels and logits `Tensor` objects + (typically, these have shape `[batch_size, label_dimension]`). + weight_column: A string or a `NumericColumn` created by + `tf.feature_column.numeric_column` defining feature column representing + weights. It is used to down weight or boost examples during training. It + will be multiplied by the loss of the example. If it is a string, it is + used as a key to fetch weight tensor from the `features`. If it is a + `NumericColumn`, raw tensor is fetched by key `weight_column.key`, then + weight_column.normalizer_fn is applied on it to get weight tensor. + + Returns: + A dict mapping each feature key to a `FixedLenFeature` or `VarLenFeature` + value. + + Raises: + ValueError: If label is used in `feature_columns`. + ValueError: If weight_column is used in `feature_columns`. + ValueError: If any of the given `feature_columns` is not a `_FeatureColumn` + instance. + ValueError: If `weight_column` is not a `NumericColumn` instance. + ValueError: if label_key is None. + """ + parsing_spec = tf.compat.v2.feature_column.make_parse_example_spec(feature_columns) + label_spec = tf.io.FixedLenFeature((label_dimension,), label_dtype, + label_default) + return _add_label_and_weight_to_parsing_spec( + parsing_spec=parsing_spec, + label_key=label_key, + label_spec=label_spec, + weight_column=weight_column) + + +def _add_label_and_weight_to_parsing_spec(parsing_spec, + label_key, + label_spec, + weight_column=None): + """Adds label and weight spec to given parsing spec. + + Args: + parsing_spec: A dict mapping each feature key to a `FixedLenFeature` or + `VarLenFeature` to which label and weight spec are added. + label_key: A string identifying the label. It means tf.Example stores labels + with this key. + label_spec: A `FixedLenFeature`. + weight_column: A string or a `NumericColumn` created by + `tf.feature_column.numeric_column` defining feature column representing + weights. It is used to down weight or boost examples during training. It + will be multiplied by the loss of the example. If it is a string, it is + used as a key to fetch weight tensor from the `features`. If it is a + `NumericColumn`, raw tensor is fetched by key `weight_column.key`, then + weight_column.normalizer_fn is applied on it to get weight tensor. + + Returns: + A dict mapping each feature key to a `FixedLenFeature` or `VarLenFeature` + value. + """ + if label_key in parsing_spec: + raise ValueError('label should not be used as feature. ' + 'label_key: {}, features: {}'.format( + label_key, parsing_spec.keys())) + parsing_spec[label_key] = label_spec + + if weight_column is None: + return parsing_spec + + if isinstance(weight_column, six.string_types): + weight_column = tf.feature_column.numeric_column(weight_column) + + if not isinstance(weight_column, fc.NumericColumn): + raise ValueError('weight_column should be an instance of ' + 'tf.feature_column.numeric_column. ' + 'Given type: {} value: {}'.format( + type(weight_column), weight_column)) + + if weight_column.key in parsing_spec: + raise ValueError('weight_column should not be used as feature. ' + 'weight_column: {}, features: {}'.format( + weight_column.key, parsing_spec.keys())) + + parsing_spec.update(weight_column.parse_example_spec) + return parsing_spec + + +@estimator_export(v1=['estimator.classifier_parse_example_spec']) +def classifier_parse_example_spec(feature_columns, + label_key, + label_dtype=tf.dtypes.int64, + label_default=None, + weight_column=None): + parsing_spec = tf.compat.v1.feature_column.make_parse_example_spec( + feature_columns) + label_spec = tf.io.FixedLenFeature((1,), label_dtype, label_default) + return _add_label_and_weight_to_parsing_spec( + parsing_spec=parsing_spec, + label_key=label_key, + label_spec=label_spec, + weight_column=weight_column) + + +classifier_parse_example_spec.__doc__ = classifier_parse_example_spec_v2.__doc__ + + +@estimator_export(v1=['estimator.regressor_parse_example_spec']) +def regressor_parse_example_spec( + feature_columns, # pylint: disable=missing-docstring + label_key, + label_dtype=tf.dtypes.float32, + label_default=None, + label_dimension=1, + weight_column=None): + parsing_spec = tf.compat.v1.feature_column.make_parse_example_spec( + feature_columns) + label_spec = tf.io.FixedLenFeature((label_dimension,), label_dtype, + label_default) + return _add_label_and_weight_to_parsing_spec( + parsing_spec=parsing_spec, + label_key=label_key, + label_spec=label_spec, + weight_column=weight_column) + + +regressor_parse_example_spec.__doc__ = regressor_parse_example_spec_v2.__doc__ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/prediction_keys.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/prediction_keys.py new file mode 100644 index 0000000000000000000000000000000000000000..3d79419eda249c8c349c60a04425d3fc42f0db95 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/prediction_keys.py @@ -0,0 +1,37 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Enum for model prediction keys.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + + +class PredictionKeys(object): + """Enum for canonical model prediction keys. + + The following values are defined: + PREDICTIONS: Used by models that predict values, such as regressor models. + """ + + CLASSES = 'classes' + CLASS_IDS = 'class_ids' + ALL_CLASSES = 'all_classes' + ALL_CLASS_IDS = 'all_class_ids' + LOGISTIC = 'logistic' + LOGITS = 'logits' + PREDICTIONS = 'predictions' + PROBABILITIES = 'probabilities' + TOP_K = 'top_k' diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/rnn.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/rnn.py new file mode 100644 index 0000000000000000000000000000000000000000..b97c236db1af1697d6b453c92d255bec349db85d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/rnn.py @@ -0,0 +1,685 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Recurrent Neural Network model and estimators.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import six +import tensorflow as tf +from tensorflow.python.feature_column import feature_column_lib as fc +from tensorflow.python.framework import ops +from tensorflow_estimator.python.estimator import estimator +from tensorflow_estimator.python.estimator import model_fn +from tensorflow_estimator.python.estimator.canned import optimizers +from tensorflow_estimator.python.estimator.estimator_export import estimator_export +from tensorflow_estimator.python.estimator.head import binary_class_head as binary_head_lib +from tensorflow_estimator.python.estimator.head import multi_class_head as multi_head_lib +from tensorflow_estimator.python.estimator.head import sequential_head as seq_head_lib + +# The defaults are historical artifacts of the initial implementation, but seem +# reasonable choices. +# TODO(aarg): Also apply default learning rate and clipping to Keras model so +# they apply when the optimizer is set via `compile` and the model trained via +# the `fit` method. +_DEFAULT_LEARNING_RATE = 0.05 +_DEFAULT_CLIP_NORM = 5.0 + +_SIMPLE_RNN_KEY = 'simple_rnn' +_LSTM_KEY = 'lstm' +_GRU_KEY = 'gru' + +_CELL_TYPE_TO_LAYER_MAPPING = { + _LSTM_KEY: tf.keras.layers.LSTM, + _GRU_KEY: tf.keras.layers.GRU, + _SIMPLE_RNN_KEY: tf.keras.layers.SimpleRNN +} + +_CELL_TYPES = { + _LSTM_KEY: tf.keras.layers.LSTMCell, + _GRU_KEY: tf.keras.layers.GRUCell, + _SIMPLE_RNN_KEY: tf.keras.layers.SimpleRNNCell +} + +# Indicates no value was provided by the user to a kwarg. +USE_DEFAULT = object() + + +def _single_rnn_cell(units, cell_type): + """Initializes a RNN cell.""" + cell_type = _CELL_TYPES.get(cell_type, cell_type) + if not callable(cell_type): + raise ValueError( + '`cell_type` should be a class producing a RNN cell, or a string ' + 'specifying the cell type. Supported strings are: {}.'.format( + [_SIMPLE_RNN_KEY, _LSTM_KEY, _GRU_KEY])) + cell = cell_type(units=units) + if hasattr(cell, '_enable_caching_device'): + # Enable the caching_device to speed up the repeative varaible read in + # tf.while. This should work only with tf.session. + cell._enable_caching_device = True # pylint: disable=protected-access + if not hasattr(cell, 'call') or not hasattr(cell, 'state_size'): + raise ValueError('RNN cell should have a `call` and `state_size` method.') + return cell + + +def _make_rnn_cell_fn(units, cell_type=_SIMPLE_RNN_KEY): + """Convenience function to create `rnn_cell_fn` for canned RNN Estimators. + + Args: + units: Iterable of integer number of hidden units per RNN layer. + cell_type: A class producing a RNN cell or a string specifying the cell + type. Supported strings are: `'simple_rnn'`, `'lstm'`, and `'gru'`. + + Returns: + A function that returns a RNN cell. + + Raises: + ValueError: If cell_type is not supported. + """ + + def rnn_cell_fn(): + cells = [_single_rnn_cell(n, cell_type) for n in units] + if len(cells) == 1: + return cells[0] + return cells + + return rnn_cell_fn + + +class RNNModel(tf.keras.models.Model): + """A Keras RNN model. + + Composition of layers to compute logits from RNN model, along with training + and inference features. See `tf.keras.models.Model` for more details on Keras + models. + + Example of usage: + + ```python + rating = tf.feature_column.embedding_column( + tf.feature_column.sequence_categorical_column_with_identity('rating', 5), + 10) + rnn_layer = tf.keras.layers.SimpleRNN(20) + rnn_model = RNNModel(rnn_layer, units=1, sequence_feature_columns=[rating]) + + rnn_model.compile( + tf.keras.optimizers.Adam(), loss=tf.keras.losses.MeanSquaredError()) + rnn_model.fit(generator(), epochs=10, steps_per_epoch=100) + rnn_model.predict({'rating': np.array([[0, 1], [2, 3]])}, steps=1) + ``` + """ + + # TODO(aarg): Update arguments to support multiple rnn layers. + def __init__(self, + rnn_layer, + units, + sequence_feature_columns, + context_feature_columns=None, + activation=None, + return_sequences=False, + **kwargs): + """Initializes a RNNModel instance. + + Args: + rnn_layer: A Keras RNN layer. + units: An int indicating the dimension of the logit layer, and of the + model output. + sequence_feature_columns: An iterable containing the `FeatureColumn`s that + represent sequential input. All items in the set should either be + sequence columns (e.g. `sequence_numeric_column`) or constructed from + one (e.g. `embedding_column` with `sequence_categorical_column_*` as + input). + context_feature_columns: An iterable containing the `FeatureColumn`s for + contextual input. The data represented by these columns will be + replicated and given to the RNN at each timestep. These columns must be + instances of classes derived from `DenseColumn` such as + `numeric_column`, not the sequential variants. + activation: Activation function to apply to the logit layer (for instance + `tf.keras.activations.sigmoid`). If you don't specify anything, no + activation is applied. + return_sequences: A boolean indicating whether to return the last output + in the output sequence, or the full sequence. + **kwargs: Additional arguments. + + Raises: + ValueError: If `units` is not an int. + """ + super(RNNModel, self).__init__(**kwargs) + if not isinstance(units, int): + raise ValueError('units must be an int. Given type: {}'.format( + type(units))) + self._return_sequences = return_sequences + self._sequence_feature_columns = sequence_feature_columns + self._context_feature_columns = context_feature_columns + self._sequence_features_layer = tf.keras.experimental.SequenceFeatures( + sequence_feature_columns) + self._dense_features_layer = None + if context_feature_columns: + self._dense_features_layer = tf.compat.v1.keras.layers.DenseFeatures( + context_feature_columns) + self._rnn_layer = rnn_layer + self._logits_layer = tf.keras.layers.Dense( + units=units, activation=activation, name='logits') + + def call(self, inputs, training=None): + """Computes the RNN output. + + By default no activation is applied and the logits are returned. To output + probabilites an activation needs to be specified such as sigmoid or softmax. + + Args: + inputs: A dict mapping keys to input tensors. + training: Python boolean indicating whether the layers should behave in + training mode or in inference mode. This argument is passed to the + model's layers. This is for instance used with cells that use dropout. + + Returns: + A `Tensor` with logits from RNN model. It has shape + (batch_size, time_step, logits_size) if `return_sequence` is `True`, + (batch_size, logits_size) otherwise. + """ + if not isinstance(inputs, dict): + raise ValueError('inputs should be a dictionary of `Tensor`s. ' + 'Given type: {}'.format(type(inputs))) + with ops.name_scope('sequence_input_layer'): + try: + sequence_input, sequence_length = self._sequence_features_layer( + inputs, training=training) + except TypeError: + sequence_input, sequence_length = self._sequence_features_layer(inputs) + tf.compat.v1.summary.histogram('sequence_length', sequence_length) + + if self._context_feature_columns: + try: + context_input = self._dense_features_layer(inputs, training=training) + except TypeError: + context_input = self._dense_features_layer(inputs) + sequence_input = fc.concatenate_context_input( + context_input, sequence_input=sequence_input) + + sequence_length_mask = tf.sequence_mask(sequence_length) + rnn_outputs = self._rnn_layer( + sequence_input, mask=sequence_length_mask, training=training) + + logits = self._logits_layer(rnn_outputs) + if self._return_sequences: + # Passes sequence mask as `_keras_mask` to be used in Keras model for + # loss and metrics aggregation to exclude padding in the sequential case. + logits._keras_mask = sequence_length_mask # pylint: disable=protected-access + return logits + + def get_config(self): + """Returns a dictionary with the config of the model.""" + config = {'name': self.name} + config['rnn_layer'] = { + 'class_name': self._rnn_layer.__class__.__name__, + 'config': self._rnn_layer.get_config() + } + config['units'] = self._logits_layer.units + config['return_sequences'] = self._return_sequences + config['activation'] = tf.keras.activations.serialize(self._logits_layer.activation) + config['sequence_feature_columns'] = fc.serialize_feature_columns( + self._sequence_feature_columns) + config['context_feature_columns'] = ( + fc.serialize_feature_columns(self._context_feature_columns) + if self._context_feature_columns else None) + return config + + @classmethod + def from_config(cls, config, custom_objects=None): + """Creates a RNNModel from its config. + + Args: + config: A Python dictionary, typically the output of `get_config`. + custom_objects: Optional dictionary mapping names (strings) to custom + classes or functions to be considered during deserialization. + + Returns: + A RNNModel. + """ + rnn_layer = tf.keras.layers.deserialize( + config.pop('rnn_layer'), custom_objects=custom_objects) + sequence_feature_columns = fc.deserialize_feature_columns( + config.pop('sequence_feature_columns'), custom_objects=custom_objects) + context_feature_columns = config.pop('context_feature_columns', None) + if context_feature_columns: + context_feature_columns = fc.deserialize_feature_columns( + context_feature_columns, custom_objects=custom_objects) + activation = tf.keras.activations.deserialize( + config.pop('activation', None), custom_objects=custom_objects) + return cls( + rnn_layer=rnn_layer, + sequence_feature_columns=sequence_feature_columns, + context_feature_columns=context_feature_columns, + activation=activation, + **config) + + +def _get_rnn_estimator_spec(features, labels, mode, head, rnn_model, optimizer, + return_sequences): + """Computes `EstimatorSpec` from logits to use in estimator model function. + + Args: + features: dict of `Tensor` and `SparseTensor` objects returned from + `input_fn`. + labels: `Tensor` of shape [batch_size, 1] or [batch_size] with labels. + mode: Defines whether this is training, evaluation or prediction. See + `ModeKeys`. + head: A `Head` instance. + rnn_model: A Keras model that computes RNN logits from features. + optimizer: String, `tf.keras.optimizers.Optimizer` object, or callable that + creates the optimizer to use for training. If not specified, will use the + Adagrad optimizer with a default learning rate of 0.05 and gradient clip + norm of 5.0. + return_sequences: A boolean indicating whether to return the last output in + the output sequence, or the full sequence. + + Returns: + An `EstimatorSpec` instance. + + Raises: + ValueError: If mode or optimizer is invalid, or features has the wrong type. + """ + training = (mode == model_fn.ModeKeys.TRAIN) + # In TRAIN mode, create optimizer and assign global_step variable to + # optimizer.iterations to make global_step increased correctly, as Hooks + # relies on global step as step counter - otherwise skip optimizer + # initialization and set it to None. + if training: + # If user does not provide an optimizer instance, use the optimizer + # specified by the string with default learning rate and gradient clipping. + if isinstance(optimizer, six.string_types): + optimizer = optimizers.get_optimizer_instance_v2( + optimizer, learning_rate=_DEFAULT_LEARNING_RATE) + optimizer.clipnorm = _DEFAULT_CLIP_NORM + else: + optimizer = optimizers.get_optimizer_instance_v2(optimizer) + optimizer.iterations = tf.compat.v1.train.get_or_create_global_step() + else: + optimizer = None + + logits = rnn_model(features, training) + + if return_sequences and head.input_sequence_mask_key not in features: + features[head.input_sequence_mask_key] = logits._keras_mask # pylint: disable=protected-access + + return head.create_estimator_spec( + features=features, + mode=mode, + labels=labels, + optimizer=optimizer, + logits=logits, + update_ops=rnn_model.updates, + trainable_variables=rnn_model.trainable_variables) + + +def _verify_rnn_cell_input(rnn_cell_fn, units, cell_type): + if rnn_cell_fn and (units or cell_type != USE_DEFAULT): + raise ValueError( + 'units and cell_type must not be specified when using rnn_cell_fn') + + +def _make_rnn_layer(rnn_cell_fn, units, cell_type, return_sequences): + """Assert arguments are valid and return rnn_layer_fn. + + Args: + rnn_cell_fn: A function that returns a RNN cell instance that will be used + to construct the RNN. + units: Iterable of integer number of hidden units per RNN layer. + cell_type: A class producing a RNN cell or a string specifying the cell + type. + return_sequences: A boolean indicating whether to return the last output + in the output sequence, or the full sequence.: + + Returns: + A tf.keras.layers.RNN layer. + """ + _verify_rnn_cell_input(rnn_cell_fn, units, cell_type) + if cell_type in _CELL_TYPE_TO_LAYER_MAPPING and isinstance(units, int): + return _CELL_TYPE_TO_LAYER_MAPPING[cell_type]( + units=units, return_sequences=return_sequences) + if not rnn_cell_fn: + if cell_type == USE_DEFAULT: + cell_type = _SIMPLE_RNN_KEY + rnn_cell_fn = _make_rnn_cell_fn(units, cell_type) + + return tf.keras.layers.RNN(cell=rnn_cell_fn(), return_sequences=return_sequences) + + +@estimator_export('estimator.experimental.RNNEstimator', v1=[]) +class RNNEstimator(estimator.Estimator): + """An Estimator for TensorFlow RNN models with user-specified head. + + Example: + + ```python + token_sequence = sequence_categorical_column_with_hash_bucket(...) + token_emb = embedding_column(categorical_column=token_sequence, ...) + + estimator = RNNEstimator( + head=tf.estimator.RegressionHead(), + sequence_feature_columns=[token_emb], + units=[32, 16], cell_type='lstm') + + # Or with custom RNN cell: + def rnn_cell_fn(_): + cells = [ tf.keras.layers.LSTMCell(size) for size in [32, 16] ] + return tf.keras.layers.StackedRNNCells(cells) + + estimator = RNNEstimator( + head=tf.estimator.RegressionHead(), + sequence_feature_columns=[token_emb], + rnn_cell_fn=rnn_cell_fn) + + # Input builders + def input_fn_train: # returns x, y + pass + estimator.train(input_fn=input_fn_train, steps=100) + + def input_fn_eval: # returns x, y + pass + metrics = estimator.evaluate(input_fn=input_fn_eval, steps=10) + def input_fn_predict: # returns x, None + pass + predictions = estimator.predict(input_fn=input_fn_predict) + ``` + + Input of `train` and `evaluate` should have following features, + otherwise there will be a `KeyError`: + + * if the head's `weight_column` is not `None`, a feature with + `key=weight_column` whose value is a `Tensor`. + * for each `column` in `sequence_feature_columns`: + - a feature with `key=column.name` whose `value` is a `SparseTensor`. + * for each `column` in `context_feature_columns`: + - if `column` is a `CategoricalColumn`, a feature with `key=column.name` + whose `value` is a `SparseTensor`. + - if `column` is a `WeightedCategoricalColumn`, two features: the first + with `key` the id column name, the second with `key` the weight column + name. Both features' `value` must be a `SparseTensor`. + - if `column` is a `DenseColumn`, a feature with `key=column.name` + whose `value` is a `Tensor`. + + Loss and predicted output are determined by the specified head. + + @compatibility(eager) + Estimators are not compatible with eager execution. + @end_compatibility + """ + + def __init__(self, + head, + sequence_feature_columns, + context_feature_columns=None, + units=None, + cell_type=USE_DEFAULT, + rnn_cell_fn=None, + return_sequences=False, + model_dir=None, + optimizer='Adagrad', + config=None): + """Initializes a `RNNEstimator` instance. + + Args: + head: A `Head` instance. This specifies the model's output and loss + function to be optimized. + sequence_feature_columns: An iterable containing the `FeatureColumn`s that + represent sequential input. All items in the set should either be + sequence columns (e.g. `sequence_numeric_column`) or constructed from + one (e.g. `embedding_column` with `sequence_categorical_column_*` as + input). + context_feature_columns: An iterable containing the `FeatureColumn`s for + contextual input. The data represented by these columns will be + replicated and given to the RNN at each timestep. These columns must be + instances of classes derived from `DenseColumn` such as + `numeric_column`, not the sequential variants. + units: Iterable of integer number of hidden units per RNN layer. If set, + `cell_type` must also be specified and `rnn_cell_fn` must be `None`. + cell_type: A class producing a RNN cell or a string specifying the cell + type. Supported strings are: `'simple_rnn'`, `'lstm'`, and `'gru'`. If + set, `units` must also be specified and `rnn_cell_fn` must be `None`. + rnn_cell_fn: A function that returns a RNN cell instance that will be used + to construct the RNN. If set, `units` and `cell_type` cannot be set. + This is for advanced users who need additional customization beyond + `units` and `cell_type`. Note that `tf.keras.layers.StackedRNNCells` is + needed for stacked RNNs. + return_sequences: A boolean indicating whether to return the last output + in the output sequence, or the full sequence. + model_dir: Directory to save model parameters, graph and etc. This can + also be used to load checkpoints from the directory into a estimator to + continue training a previously saved model. + optimizer: An instance of `tf.Optimizer` or string specifying optimizer + type. Defaults to Adagrad optimizer. + config: `RunConfig` object to configure the runtime settings. + + Note that a RNN cell has: + - a `call` method. + - a `state_size` attribute. + - a `output_size` attribute. + - a `get_initial_state` method. + + See the documentation on `tf.keras.layers.RNN` for more details. + + Raises: + ValueError: If `units`, `cell_type`, and `rnn_cell_fn` are not + compatible. + """ + + # TODO(aarg): Instead of raising an error convert head to sequential head. + if return_sequences and not isinstance(head, seq_head_lib._SequentialHead): # pylint: disable=protected-access + raise ValueError('Provided head must be a `_SequentialHead` object when ' + '`return_sequences` is set to True.') + _verify_rnn_cell_input(rnn_cell_fn, units, cell_type) + + def _model_fn(features, labels, mode, config): + """RNNEstimator model function.""" + del config # Unused. + rnn_layer = _make_rnn_layer( + rnn_cell_fn=rnn_cell_fn, + units=units, + cell_type=cell_type, + return_sequences=return_sequences) + rnn_model = RNNModel( + rnn_layer=rnn_layer, + units=head.logits_dimension, + sequence_feature_columns=sequence_feature_columns, + context_feature_columns=context_feature_columns, + return_sequences=return_sequences, + name='rnn_model') + return _get_rnn_estimator_spec( + features, + labels, + mode, + head=head, + rnn_model=rnn_model, + optimizer=optimizer, + return_sequences=return_sequences) + + super(RNNEstimator, self).__init__( + model_fn=_model_fn, model_dir=model_dir, config=config) + + +@estimator_export('estimator.experimental.RNNClassifier', v1=[]) +class RNNClassifier(RNNEstimator): + """A classifier for TensorFlow RNN models. + + Trains a recurrent neural network model to classify instances into one of + multiple classes. + + Example: + + ```python + token_sequence = sequence_categorical_column_with_hash_bucket(...) + token_emb = embedding_column(categorical_column=token_sequence, ...) + + estimator = RNNClassifier( + sequence_feature_columns=[token_emb], + units=[32, 16], cell_type='lstm') + + # Input builders + def input_fn_train: # returns x, y + pass + estimator.train(input_fn=input_fn_train, steps=100) + + def input_fn_eval: # returns x, y + pass + metrics = estimator.evaluate(input_fn=input_fn_eval, steps=10) + def input_fn_predict: # returns x, None + pass + predictions = estimator.predict(input_fn=input_fn_predict) + ``` + + Input of `train` and `evaluate` should have following features, + otherwise there will be a `KeyError`: + + * if `weight_column` is not `None`, a feature with + `key=weight_column` whose value is a `Tensor`. + * for each `column` in `sequence_feature_columns`: + - a feature with `key=column.name` whose `value` is a `SparseTensor`. + * for each `column` in `context_feature_columns`: + - if `column` is a `CategoricalColumn`, a feature with `key=column.name` + whose `value` is a `SparseTensor`. + - if `column` is a `WeightedCategoricalColumn`, two features: the first + with `key` the id column name, the second with `key` the weight column + name. Both features' `value` must be a `SparseTensor`. + - if `column` is a `DenseColumn`, a feature with `key=column.name` + whose `value` is a `Tensor`. + + Loss is calculated by using softmax cross entropy. + + @compatibility(eager) + Estimators are not compatible with eager execution. + @end_compatibility + """ + + def __init__(self, + sequence_feature_columns, + context_feature_columns=None, + units=None, + cell_type=USE_DEFAULT, + rnn_cell_fn=None, + return_sequences=False, + model_dir=None, + n_classes=2, + weight_column=None, + label_vocabulary=None, + optimizer='Adagrad', + loss_reduction=tf.losses.Reduction.SUM_OVER_BATCH_SIZE, + sequence_mask='sequence_mask', + config=None): + """Initializes a `RNNClassifier` instance. + + Args: + sequence_feature_columns: An iterable containing the `FeatureColumn`s that + represent sequential input. All items in the set should either be + sequence columns (e.g. `sequence_numeric_column`) or constructed from + one (e.g. `embedding_column` with `sequence_categorical_column_*` as + input). + context_feature_columns: An iterable containing the `FeatureColumn`s for + contextual input. The data represented by these columns will be + replicated and given to the RNN at each timestep. These columns must be + instances of classes derived from `DenseColumn` such as + `numeric_column`, not the sequential variants. + units: Iterable of integer number of hidden units per RNN layer. If set, + `cell_type` must also be specified and `rnn_cell_fn` must be `None`. + cell_type: A class producing a RNN cell or a string specifying the cell + type. Supported strings are: `'simple_rnn'`, `'lstm'`, and `'gru'`. If + set, `units` must also be specified and `rnn_cell_fn` must be `None`. + rnn_cell_fn: A function that returns a RNN cell instance that will be used + to construct the RNN. If set, `units` and `cell_type` cannot be set. + This is for advanced users who need additional customization beyond + `units` and `cell_type`. Note that `tf.keras.layers.StackedRNNCells` is + needed for stacked RNNs. + return_sequences: A boolean indicating whether to return the last output + in the output sequence, or the full sequence. Note that if True, + `weight_column` must be None or a string. + model_dir: Directory to save model parameters, graph and etc. This can + also be used to load checkpoints from the directory into a estimator to + continue training a previously saved model. + n_classes: Number of label classes. Defaults to 2, namely binary + classification. Must be > 1. + weight_column: A string or a `NumericColumn` created by + `tf.feature_column.numeric_column` defining feature column representing + weights. It is used to down weight or boost examples during training. It + will be multiplied by the loss of the example. If it is a string, it is + used as a key to fetch weight tensor from the `features`. If it is a + `NumericColumn`, raw tensor is fetched by key `weight_column.key`, then + weight_column.normalizer_fn is applied on it to get weight tensor. + label_vocabulary: A list of strings represents possible label values. If + given, labels must be string type and have any value in + `label_vocabulary`. If it is not given, that means labels are already + encoded as integer or float within [0, 1] for `n_classes=2` and encoded + as integer values in {0, 1,..., n_classes-1} for `n_classes`>2 . Also + there will be errors if vocabulary is not provided and labels are + string. + optimizer: An instance of `tf.Optimizer` or string specifying optimizer + type. Defaults to Adagrad optimizer. + loss_reduction: One of `tf.losses.Reduction` except `NONE`. Describes how + to reduce training loss over batch. Defaults to `SUM_OVER_BATCH_SIZE`. + sequence_mask: A string with the name of the sequence mask tensor. If + `sequence_mask` is in the features dictionary, the provided tensor is + used, otherwise the sequence mask is computed from the length of + sequential features. The sequence mask is used in evaluation and + training mode to aggregate loss and metrics computation while excluding + padding steps. It is also added to the predictions dictionary in + prediction mode to indicate which steps are padding. + config: `RunConfig` object to configure the runtime settings. + + Note that a RNN cell has: + - a `call` method. + - a `state_size` attribute. + - a `output_size` attribute. + - a `get_initial_state` method. + + See the documentation on `tf.keras.layers.RNN` for more details. + + Raises: + ValueError: If `units`, `cell_type`, and `rnn_cell_fn` are not + compatible. + """ + if n_classes == 2: + head = binary_head_lib.BinaryClassHead( + weight_column=weight_column, + label_vocabulary=label_vocabulary, + loss_reduction=loss_reduction) + else: + head = multi_head_lib.MultiClassHead( + n_classes=n_classes, + weight_column=weight_column, + label_vocabulary=label_vocabulary, + loss_reduction=loss_reduction) + + if return_sequences: + tf.compat.v1.logging.info( + 'Converting head to sequential head with ' + '`SequentialHeadWrapper` to allow sequential predictions.') + head = seq_head_lib.SequentialHeadWrapper( + head, + sequence_length_mask=sequence_mask, + feature_columns=weight_column) + + super(RNNClassifier, self).__init__( + head=head, + sequence_feature_columns=sequence_feature_columns, + context_feature_columns=context_feature_columns, + units=units, + cell_type=cell_type, + rnn_cell_fn=rnn_cell_fn, + return_sequences=return_sequences, + model_dir=model_dir, + optimizer=optimizer, + config=config) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/saved_model_estimator.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/saved_model_estimator.py new file mode 100644 index 0000000000000000000000000000000000000000..2c2f84d03d193bb4ea5c806730953de35c322129 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/saved_model_estimator.py @@ -0,0 +1,494 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Class that creates an Estimator from a SavedModel.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import os + +import six +import tensorflow as tf +from tensorflow.python.saved_model import constants +from tensorflow.python.saved_model import loader_impl +from tensorflow.python.saved_model import path_helpers +from tensorflow.python.saved_model import signature_constants +from tensorflow_estimator.python.estimator import estimator as estimator_lib +from tensorflow_estimator.python.estimator import model_fn as model_fn_lib +from tensorflow_estimator.python.estimator.export import export_lib +from tensorflow_estimator.python.estimator.mode_keys import ModeKeys + + +class SavedModelEstimator(estimator_lib.EstimatorV2): + """Create an Estimator from a SavedModel. + + Only SavedModels exported with + `tf.estimator.Estimator.experimental_export_all_saved_models()` or + `tf.estimator.Estimator.export_saved_model()` are supported for this class. + + Example with `tf.estimator.DNNClassifier`: + + **Step 1: Create and train DNNClassifier.** + + ```python + feature1 = tf.feature_column.embedding_column( + tf.feature_column.categorical_column_with_vocabulary_list( + key='feature1', vocabulary_list=('green', 'yellow')), dimension=1) + feature2 = tf.feature_column.numeric_column(key='feature2', default_value=0.0) + + classifier = tf.estimator.DNNClassifier( + hidden_units=[4,2], feature_columns=[feature1, feature2]) + + def input_fn(): + features = {'feature1': tf.constant(['green', 'green', 'yellow']), + 'feature2': tf.constant([3.5, 4.2, 6.1])} + label = tf.constant([1., 0., 0.]) + return tf.data.Dataset.from_tensors((features, label)).repeat() + + classifier.train(input_fn=input_fn, steps=10) + ``` + + **Step 2: Export classifier.** + First, build functions that specify the expected inputs. + + ```python + # During train and evaluation, both the features and labels should be defined. + supervised_input_receiver_fn = ( + tf.estimator.experimental.build_raw_supervised_input_receiver_fn( + {'feature1': tf.placeholder(dtype=tf.string, shape=[None]), + 'feature2': tf.placeholder(dtype=tf.float32, shape=[None])}, + tf.placeholder(dtype=tf.float32, shape=[None]))) + + # During predict mode, expect to receive a `tf.Example` proto, so a parsing + # function is used. + serving_input_receiver_fn = ( + tf.estimator.export.build_parsing_serving_input_receiver_fn( + tf.feature_column.make_parse_example_spec([feature1, feature2]))) + ``` + + Next, export the model as a SavedModel. A timestamped directory will be + created (for example `/tmp/export_all/1234567890`). + + ```python + # Option 1: Save all modes (train, eval, predict) + export_dir = classifier.experimental_export_all_saved_models( + '/tmp/export_all', + {tf.estimator.ModeKeys.TRAIN: supervised_input_receiver_fn, + tf.estimator.ModeKeys.EVAL: supervised_input_receiver_fn, + tf.estimator.ModeKeys.PREDICT: serving_input_receiver_fn}) + + # Option 2: Only export predict mode + export_dir = classifier.export_saved_model( + '/tmp/export_predict', serving_input_receiver_fn) + ``` + + **Step 3: Create a SavedModelEstimator from the exported SavedModel.** + + ```python + est = tf.estimator.experimental.SavedModelEstimator(export_dir) + + # If all modes were exported, you can immediately evaluate and predict, or + # continue training. Otherwise only predict is available. + eval_results = est.evaluate(input_fn=input_fn, steps=1) + print(eval_results) + + est.train(input_fn=input_fn, steps=20) + + def predict_input_fn(): + example = tf.train.Example() + example.features.feature['feature1'].bytes_list.value.extend(['yellow']) + example.features.feature['feature2'].float_list.value.extend([1.]) + return {'inputs':tf.constant([example.SerializeToString()])} + + predictions = est.predict(predict_input_fn) + print(next(predictions)) + ``` + """ + + def __init__(self, saved_model_dir, model_dir=None): + """Initialize a SavedModelEstimator. + + The SavedModelEstimator loads its model function and variable values from + the graphs defined in the SavedModel. There is no option to pass in + `RunConfig` or `params` arguments, because the model function graph is + defined statically in the SavedModel. + + Args: + saved_model_dir: Directory containing SavedModel protobuf and subfolders. + model_dir: Directory to save new checkpoints during training. + + Raises: + NotImplementedError: If a DistributionStrategy is defined in the config. + Unless the SavedModelEstimator is subclassed, this shouldn't happen. + """ + + super(SavedModelEstimator, self).__init__( + model_fn=self._model_fn_from_saved_model, model_dir=model_dir) + if self._train_distribution or self._eval_distribution: + raise NotImplementedError( + 'SavedModelEstimator currently does not support ' + 'DistributionStrategy.') + self.saved_model_dir = saved_model_dir + self.saved_model_loader = loader_impl.SavedModelLoader(saved_model_dir) + self._available_modes = self._extract_available_modes() + + def _extract_available_modes(self): + """Return list of modes found in SavedModel.""" + available_modes = [] + tf.compat.v1.logging.info( + 'Checking available modes for SavedModelEstimator.') + for mode in [ModeKeys.TRAIN, ModeKeys.EVAL, ModeKeys.PREDICT]: + try: + self._get_meta_graph_def_for_mode(mode) + except RuntimeError: + tf.compat.v1.logging.warn('%s mode not found in SavedModel.' % mode) + continue + + if self._get_signature_def_for_mode(mode) is not None: + available_modes.append(mode) + + tf.compat.v1.logging.info('Available modes for Estimator: %s' % + available_modes) + return available_modes + + def _validate_mode(self, mode): + """Make sure that mode can be run using the SavedModel.""" + if mode not in self._available_modes: + raise RuntimeError('%s mode is not available in the SavedModel. Use ' + 'saved_model_cli to check that the Metagraph for this ' + 'mode has been exported.' % mode) + + def _get_meta_graph_def_for_mode(self, mode): + tags = export_lib.EXPORT_TAG_MAP[mode] + return self.saved_model_loader.get_meta_graph_def_from_tags(tags) + + def _get_signature_def_for_mode(self, mode): + meta_graph_def = self._get_meta_graph_def_for_mode(mode) + if mode == ModeKeys.PREDICT: + sig_def_key = tf.saved_model.DEFAULT_SERVING_SIGNATURE_DEF_KEY + else: + sig_def_key = mode + if sig_def_key not in meta_graph_def.signature_def: + tf.compat.v1.logging.warn( + 'Metagraph for mode %s was found, but SignatureDef with' + ' key \"%s\" is missing.' % (mode, sig_def_key)) + return None + return meta_graph_def.signature_def[sig_def_key] + + def _get_saver_def_from_mode(self, mode): + meta_graph_def = self._get_meta_graph_def_for_mode(mode) + return meta_graph_def.saver_def + + def _create_and_assert_global_step(self, graph): + # Do nothing here. The global step variable will be created/loaded from the + # SavedModel. If a global step variable were created here, the result + # will be two duplicate global step variables, causing issues during + # the warm-start phase. + # Due to the global variable being created in the model function, this may + # cause issues when running DistributionStrategy. Thus, DistributionStrategy + # is not yet supported with SavedModelEstimator. + return None + + def _model_fn_from_saved_model(self, features, labels, mode): + """Load a SavedModel graph and return an EstimatorSpec.""" + # TODO(kathywu): Model function loads placeholders from the graph. Calling + # export_all_saved_models creates another placeholder for the inputs, on top + # of the original placeholders. There should be a way to avoid this. + self._validate_mode(mode) + + g = tf.compat.v1.get_default_graph() + if tf.compat.v1.train.get_global_step(g) is not None: + raise RuntimeError( + 'Graph must not contain a global step tensor before the SavedModel is' + ' loaded. Please make sure that the input function does not create a ' + 'global step.') + + # Extract SignatureDef for information about the input and output tensors. + signature_def = self._get_signature_def_for_mode(mode) + + # Generate input map for replacing the inputs in the SavedModel graph with + # the provided features and labels. + input_map = _generate_input_map(signature_def, features, labels) + + # Create a list of the names of output tensors. When the graph is loaded, + # names of the output tensors may be remapped. This ensures that the correct + # tensors are returned in the EstimatorSpec. + output_tensor_names = [ + value.name for value in six.itervalues(signature_def.outputs) + ] + + # Load the graph. `output_tensors` contains output `Tensors` in the same + # same order as the `output_tensor_names` list. + tags = export_lib.EXPORT_TAG_MAP[mode] + _, output_tensors = self.saved_model_loader.load_graph( + g, tags, input_map=input_map, return_elements=output_tensor_names) + + # Create saver object, and restore from the SavedModel `variables` directory + # if no checkpoints have been saved in the `model_dir`. + saver_obj = tf.compat.v1.train.Saver( + saver_def=self._get_saver_def_from_mode(mode)) + init_fn = None + if not super(SavedModelEstimator, self).latest_checkpoint(): + init_fn = self._restore_from_saver + + # Create a scaffold from the MetaGraphDef that contains ops to initialize + # the graph. This should mirror the steps from _add_meta_graph_for_mode(), + # which creates a MetaGraphDef from the EstimatorSpec's scaffold. + # Get asset tensors, if any. + meta_graph_def = self._get_meta_graph_def_for_mode(mode) + asset_tensors_dictionary = loader_impl.get_asset_tensors( + self.saved_model_loader.export_dir, meta_graph_def, import_scope=None) + # TODO(kathywu): switch to loader_impl._get_main_op + scaffold = tf.compat.v1.train.Scaffold( + local_init_op=loader_impl._get_main_op_tensor( # pylint: disable=protected-access + meta_graph_def), + local_init_feed_dict=asset_tensors_dictionary, + saver=saver_obj, + init_fn=init_fn) + + # Ensure that a global step tensor has been created. + global_step_tensor = tf.compat.v1.train.get_global_step(g) + tf.compat.v1.train.assert_global_step(global_step_tensor) + + # Extract values to return in the EstimatorSpec. + output_map = dict(zip(output_tensor_names, output_tensors)) + outputs = { + key: output_map[value.name] + for key, value in six.iteritems(signature_def.outputs) + } + + loss, predictions, metrics = _validate_and_extract_outputs( + mode, outputs, signature_def.method_name) + + train_op = tf.compat.v1.get_collection(constants.TRAIN_OP_KEY) + if len(train_op) > 1: + raise RuntimeError('Multiple ops found in the train_op collection.') + train_op = None if not train_op else train_op[0] + + _clear_saved_model_collections() + return model_fn_lib.EstimatorSpec( + scaffold=scaffold, + mode=mode, + loss=loss, + train_op=train_op, + predictions=predictions, + eval_metric_ops=metrics) + + def _restore_from_saver(self, scaffold, session): + return scaffold.saver.restore(session, + _get_saved_model_ckpt(self.saved_model_dir)) + + def latest_checkpoint(self): + """Returns the filename of the latest saved checkpoint. + + Returns: + Filename of latest checkpoint in `model_dir`. If no checkpoints are found + in `model_dir`, then the path to the SavedModel checkpoint is returned. + """ + return (super(SavedModelEstimator, self).latest_checkpoint() or + _get_saved_model_ckpt(self.saved_model_dir)) + + +def _get_saved_model_ckpt(saved_model_dir): + """Return path to variables checkpoint in a `SavedModel` directory.""" + if not tf.compat.v1.gfile.Exists( + os.path.join( + path_helpers.get_variables_dir(saved_model_dir), + tf.compat.as_text('variables.index'))): + raise ValueError('Directory provided has an invalid SavedModel format: %s' % + saved_model_dir) + return path_helpers.get_variables_path(saved_model_dir) + + +def _clear_saved_model_collections(): + """Clear collections that are expected empty when exporting a SavedModel. + + The SavedModel builder uses these collections to track ops necessary to + restore the graph state. These collections are expected to be empty before + MetaGraphs are added to the builder. + """ + del tf.compat.v1.get_collection_ref(tf.saved_model.ASSETS_KEY)[:] + del tf.compat.v1.get_collection_ref( + tf.compat.v1.saved_model.LEGACY_INIT_OP_KEY)[:] + del tf.compat.v1.get_collection_ref(tf.compat.v1.saved_model.MAIN_OP_KEY)[:] + del tf.compat.v1.get_collection_ref(constants.TRAIN_OP_KEY)[:] + + +def _generate_input_map(signature_def, features, labels): + """Return dict mapping an input tensor name to a feature or label tensor. + + Args: + signature_def: SignatureDef loaded from SavedModel + features: A `Tensor`, `SparseTensor`, or dict of string to `Tensor` or + `SparseTensor`, specifying the features to be passed to the model. + labels: A `Tensor`, `SparseTensor`, or dict of string to `Tensor` or + `SparseTensor`, specifying the labels to be passed to the model. May be + `None`. + + Returns: + dict mapping string names of inputs to features or labels tensors + + Raises: + ValueError: if SignatureDef inputs are not completely mapped by the input + features and labels. + """ + # Ensure that features and labels are dictionaries. If not, convert each to + # a dictionary with a single item. The default keys are different for features + # and labels. + features = export_lib.wrap_and_check_input_tensors(features, 'feature') + if labels is not None: + # Unlike features, labels may be None (in prediction mode) + labels = export_lib.wrap_and_check_input_tensors(labels, 'label') + + inputs = signature_def.inputs + input_map = {} + for key, tensor_info in six.iteritems(inputs): + input_name = tensor_info.name + if ':' in input_name: + input_name = input_name[:input_name.find(':')] + + # When tensors are used as control inputs for operations, their names are + # prepended with a '^' character in the GraphDef. To handle possible control + # flow edge cases, control input names must be included in the input map. + control_dependency_name = '^' + input_name + + if key in features: + _check_same_dtype_and_shape(features[key], tensor_info, key) + input_map[input_name] = input_map[control_dependency_name] = features[key] + elif labels is not None and key in labels: + _check_same_dtype_and_shape(labels[key], tensor_info, key) + input_map[input_name] = input_map[control_dependency_name] = labels[key] + else: + raise ValueError( + 'Key \"%s\" not found in features or labels passed in to the model ' + 'function. All required keys: %s' % (key, inputs.keys())) + + return input_map + + +def _check_same_dtype_and_shape(tensor, tensor_info, name): + """Validate that tensor has the same properties as the TensorInfo proto. + + Args: + tensor: a `Tensor` object. + tensor_info: a `TensorInfo` proto. + name: Name of the input (to identify Tensor if an error is raised). + + Raises: + ValueError: If the tensor shape or dtype don't match the TensorInfo + """ + dtype_error = (tensor.dtype != tf.dtypes.DType(tensor_info.dtype)) + shape_error = not tensor.shape.is_compatible_with(tensor_info.tensor_shape) + + if dtype_error or shape_error: + msg = 'Tensor shape and/or dtype validation failed for input %s:' % name + if dtype_error: + msg += ('\n\tExpected dtype: %s, Got: %s' % + (tf.dtypes.DType(tensor_info.dtype), tensor.dtype)) + if shape_error: + msg += ('\n\tExpected shape: %s, Got: %s' % + (tf.TensorShape(tensor_info.tensor_shape), tensor.shape)) + + raise ValueError(msg) + + +def _extract_eval_metrics(output_dict): + """Return a eval metric dict extracted from the output_dict. + + Eval metrics consist of a value tensor and an update op. Both must be in the + passed-in tensor dictionary for an eval metric to be added to the returned + dictionary. + + Args: + output_dict: a dict that maps strings to tensors. + + Returns: + dict mapping strings to (value, update_op) tuples. + """ + # pylint: disable=protected-access + metric_ops = {} + separator_char = export_lib._SupervisedOutput._SEPARATOR_CHAR + + for key, tensor in six.iteritems(output_dict): + split_key = key.split(separator_char) + + # The metric name may contain the separator character, so recreate its name. + metric_name = separator_char.join(split_key[:-1]) + + if split_key[0] == export_lib._SupervisedOutput.METRICS_NAME: + # If the key ends with the value suffix, and there is a corresponding + # key ending with the update_op suffix, then add tensors to metrics dict. + if split_key[-1] == export_lib._SupervisedOutput.METRIC_VALUE_SUFFIX: + update_op = ''.join([ + metric_name, separator_char, + export_lib._SupervisedOutput.METRIC_UPDATE_SUFFIX + ]) + if update_op in output_dict: + update_op_tensor = output_dict[update_op] + metric_ops[metric_name] = (tensor, update_op_tensor) + + # pylint: enable=protected-access + return metric_ops + + +def _validate_and_extract_outputs(mode, output_dict, method_name): + """Extract values from SignatureDef output dictionary. + + Args: + mode: One of the modes enumerated in `tf.estimator.ModeKeys`. + output_dict: dict of string SignatureDef keys to `Tensor`. + method_name: Method name of the SignatureDef as a string. + + Returns: + Tuple of ( + loss: `Tensor` object, + predictions: dictionary mapping string keys to `Tensor` objects, + metrics: dictionary mapping string keys to a tuple of two `Tensor` objects + ) + + Raises: + RuntimeError: raised if SignatureDef has an invalid method name for the mode + """ + # pylint: disable=protected-access + loss, predictions, metrics = None, None, None + + if mode == ModeKeys.PREDICT: + predictions = output_dict + else: + # Validate that the SignatureDef's method name matches the expected name for + # the given mode. + expected_method_name = signature_constants.SUPERVISED_TRAIN_METHOD_NAME + if mode == ModeKeys.EVAL: + expected_method_name = signature_constants.SUPERVISED_EVAL_METHOD_NAME + if method_name != expected_method_name: + raise RuntimeError( + 'Invalid SignatureDef method name for mode %s.\n\tExpected: %s\n\t' + 'Got: %s\nPlease ensure that the SavedModel was exported with ' + '`tf.estimator.experimental_export_all_saved_models()`.' % + (mode, expected_method_name, method_name)) + + # Extract loss, metrics and predictions from the output dict. + loss = output_dict[export_lib._SupervisedOutput.LOSS_NAME] + metrics = _extract_eval_metrics(output_dict) + predictions = { + key: value + for key, value in six.iteritems(output_dict) + if key.split(export_lib._SupervisedOutput._SEPARATOR_CHAR)[0] == ( + export_lib._SupervisedOutput.PREDICTIONS_NAME) + } + + # pylint: enable=protected-access + return loss, predictions, metrics diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/timeseries/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/timeseries/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/timeseries/ar_model.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/timeseries/ar_model.py new file mode 100644 index 0000000000000000000000000000000000000000..3c080cefb566fe72e5a54859b5e9823733ac0a52 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/timeseries/ar_model.py @@ -0,0 +1,806 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Auto-Regressive models for time series data.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import tensorflow as tf +from tensorflow.python.framework import ops +from tensorflow.python.ops import distributions +from tensorflow.python.ops import gen_math_ops +from tensorflow_estimator.python.estimator import estimator_lib +from tensorflow_estimator.python.estimator.canned.timeseries import model +from tensorflow_estimator.python.estimator.canned.timeseries import model_utils +from tensorflow_estimator.python.estimator.canned.timeseries.feature_keys import PredictionFeatures +from tensorflow_estimator.python.estimator.canned.timeseries.feature_keys import TrainEvalFeatures + + +class LSTMPredictionModel(tf.keras.models.Model): + """A simple encoder/decoder model using an LSTM. + + This model does not operate on its own, but rather is a plugin to + `ARModel`. See `ARModel`'s constructor documentation + (`prediction_model_factory`) for a usage example. + """ + + def __init__(self, + num_features, + input_window_size, + output_window_size, + num_units=128): + """Construct the LSTM prediction model. + + Args: + num_features: number of input features per time step. + input_window_size: Number of past time steps of data to look at when doing + the regression. + output_window_size: Number of future time steps to predict. Note that + setting it to > 1 empirically seems to give a better fit. + num_units: The number of units in the encoder and decoder LSTM cells. + """ + super(LSTMPredictionModel, self).__init__() + self._encoder = tf.keras.layers.LSTM( + num_units, name="encoder", dtype=self.dtype, return_state=True) + self._decoder = tf.keras.layers.LSTM( + num_units, name="decoder", dtype=self.dtype, return_sequences=True) + self._mean_transform = tf.keras.layers.Dense(num_features, name="mean_transform") + self._covariance_transform = tf.keras.layers.Dense( + num_features, name="covariance_transform") + + def call(self, input_window_features, output_window_features): + """Compute predictions from input and output windows.""" + _, state_h, state_c = self._encoder(input_window_features) + encoder_states = [state_h, state_c] + decoder_output = self._decoder( + output_window_features, initial_state=encoder_states) + predicted_mean = self._mean_transform(decoder_output) + predicted_covariance = gen_math_ops.exp( + self._covariance_transform(decoder_output)) + return {"mean": predicted_mean, "covariance": predicted_covariance} + + +class ARModel(model.TimeSeriesModel): + """Auto-regressive model, both linear and non-linear. + + Features to the model include time and values of input_window_size timesteps, + and times for output_window_size timesteps. These are passed through a + configurable prediction model, and then fed to a loss function (e.g. squared + loss). + + Note that this class can also be used to regress against time only by setting + the input_window_size to zero. + + Each periodicity in the `periodicities` arg is divided by the + `num_time_buckets` into time buckets that are represented as features added + to the model. + + A good heuristic for picking an appropriate periodicity for a given data set + would be the length of cycles in the data. For example, energy usage in a + home is typically cyclic each day. If the time feature in a home energy + usage dataset is in the unit of hours, then 24 would be an appropriate + periodicity. Similarly, a good heuristic for `num_time_buckets` is how often + the data is expected to change within the cycle. For the aforementioned home + energy usage dataset and periodicity of 24, then 48 would be a reasonable + value if usage is expected to change every half hour. + + Each feature's value for a given example with time t is the difference + between t and the start of the time bucket it falls under. If it doesn't fall + under a feature's associated time bucket, then that feature's value is zero. + + For example: if `periodicities` = (9, 12) and `num_time_buckets` = 3, then 6 + features would be added to the model, 3 for periodicity 9 and 3 for + periodicity 12. + + For an example data point where t = 17: + - It's in the 3rd time bucket for periodicity 9 (2nd period is 9-18 and 3rd + time bucket is 15-18) + - It's in the 2nd time bucket for periodicity 12 (2nd period is 12-24 and + 2nd time bucket is between 16-20). + + Therefore the 6 added features for this row with t = 17 would be: + + # Feature name (periodicity#_timebucket#), feature value + P9_T1, 0 # not in first time bucket + P9_T2, 0 # not in second time bucket + P9_T3, 2 # 17 - 15 since 15 is the start of the 3rd time bucket + P12_T1, 0 # not in first time bucket + P12_T2, 1 # 17 - 16 since 16 is the start of the 2nd time bucket + P12_T3, 0 # not in third time bucket + """ + SQUARED_LOSS = "squared_loss" + NORMAL_LIKELIHOOD_LOSS = "normal_likelihood_loss" + + def __init__(self, + periodicities, + input_window_size, + output_window_size, + num_features, + prediction_model_factory=LSTMPredictionModel, + num_time_buckets=10, + loss=NORMAL_LIKELIHOOD_LOSS, + exogenous_feature_columns=None): + """Constructs an auto-regressive model. + + Args: + periodicities: periodicities of the input data, in the same units as the + time feature (for example 24 if feeding hourly data with a daily + periodicity, or 60 * 24 if feeding minute-level data with daily + periodicity). Note this can be a single value or a list of values for + multiple periodicities. + input_window_size: Number of past time steps of data to look at when doing + the regression. + output_window_size: Number of future time steps to predict. Note that + setting it to > 1 empirically seems to give a better fit. + num_features: number of input features per time step. + prediction_model_factory: A callable taking arguments `num_features`, + `input_window_size`, and `output_window_size` and returning a + `tf.keras.Model`. The `Model`'s `call()` takes two arguments: an input + window and an output window, and returns a dictionary of predictions. + See `LSTMPredictionModel` for an example. The default model computes + predictions as a linear function of flattened input and output windows. + num_time_buckets: Number of buckets into which to divide (time % + periodicity). This value multiplied by the number of periodicities is + the number of time features added to the model. + loss: Loss function to use for training. Currently supported values are + SQUARED_LOSS and NORMAL_LIKELIHOOD_LOSS. Note that for + NORMAL_LIKELIHOOD_LOSS, we train the covariance term as well. For + SQUARED_LOSS, the evaluation loss is reported based on un-scaled + observations and predictions, while the training loss is computed on + normalized data (if input statistics are available). + exogenous_feature_columns: A list of `tf.feature_column`s (for example + `tf.feature_column.embedding_column`) corresponding to features which + provide extra information to the model but are not part of the series to + be predicted. + + Example usage: + + >>> model = ar_model.ARModel( + ... periodicities=2, num_features=3, + ... prediction_model_factory=functools.partial( + ... LSTMPredictionModel, hidden_layer_sizes=[10, 10])) + """ + self._model_factory = prediction_model_factory + self.input_window_size = input_window_size + self.output_window_size = output_window_size + self.window_size = self.input_window_size + self.output_window_size + self.loss = loss + super(ARModel, self).__init__( + num_features=num_features, + exogenous_feature_columns=exogenous_feature_columns) + if exogenous_feature_columns is not None: + self.exogenous_size = self._get_exogenous_embedding_shape()[-1] + else: + self.exogenous_size = 0 + assert num_time_buckets > 0 + self._buckets = int(num_time_buckets) + if periodicities is None or not periodicities: + periodicities = [] + elif (not isinstance(periodicities, list) and + not isinstance(periodicities, tuple)): + periodicities = [periodicities] + self._periodicities = [int(p) for p in periodicities] + for p in self._periodicities: + assert p > 0 + assert len(self._periodicities) or self.input_window_size + assert output_window_size > 0 + + def initialize_graph(self, input_statistics=None): + super(ARModel, self).initialize_graph(input_statistics=input_statistics) + self._model_scope = tf.compat.v1.variable_scope( + # The trailing slash means we strip all enclosing variable_scopes, which + # unfortunately is necessary because the model gets called inside and + # outside a "while" scope (for prediction and training respectively), + # and the variables names need to match. + "model/", + use_resource=True) + self._model_instance = self._model_factory( + num_features=self.num_features, + input_window_size=self.input_window_size, + output_window_size=self.output_window_size) + + def get_start_state(self): + # State which matches the format we'll return later. Typically this will not + # be used by the model directly, but the shapes and dtypes should match so + # that the serving input_receiver_fn gets placeholder shapes correct. + return (tf.zeros([self.input_window_size], dtype=tf.dtypes.int64), + tf.zeros([self.input_window_size, self.num_features], + dtype=self.dtype), + tf.zeros([self.input_window_size, self.exogenous_size], + dtype=self.dtype)) + + # TODO(allenl,agarwal): Support sampling for AR. + def random_model_parameters(self, seed=None): + pass + + def generate(self, + number_of_series, + series_length, + model_parameters=None, + seed=None): + pass + + def _predicted_covariance_op(self, activations, num_values): + activation, activation_size = activations[-1] + if self.loss == ARModel.NORMAL_LIKELIHOOD_LOSS: + log_sigma_square = model_utils.fully_connected( + activation, + activation_size, + self.output_window_size * num_values, + name="log_sigma_square", + activation=None) + predicted_covariance = gen_math_ops.exp(log_sigma_square) + predicted_covariance = tf.reshape( + predicted_covariance, [-1, self.output_window_size, num_values]) + else: + shape = tf.stack([ + tf.compat.v1.shape(activation)[0], + tf.constant(self.output_window_size), + tf.constant(num_values) + ]) + predicted_covariance = tf.ones(shape=shape, dtype=activation.dtype) + return predicted_covariance + + def _predicted_mean_op(self, activations): + activation, activation_size = activations[-1] + predicted_mean = model_utils.fully_connected( + activation, + activation_size, + self.output_window_size * self.num_features, + name="predicted_mean", + activation=None) + return tf.reshape(predicted_mean, + [-1, self.output_window_size, self.num_features]) + + def prediction_ops(self, times, values, exogenous_regressors): + """Compute model predictions given input data. + + Args: + times: A [batch size, self.window_size] integer Tensor, the first + self.input_window_size times in each part of the batch indicating input + features, and the last self.output_window_size times indicating + prediction times. + values: A [batch size, self.input_window_size, self.num_features] Tensor + with input features. + exogenous_regressors: A [batch size, self.window_size, + self.exogenous_size] Tensor with exogenous features. + + Returns: + Tuple (predicted_mean, predicted_covariance), where each element is a + Tensor with shape [batch size, self.output_window_size, + self.num_features]. + """ + times.get_shape().assert_is_compatible_with([None, self.window_size]) + batch_size = tf.compat.v1.shape(times)[0] + if self.input_window_size: + values.get_shape().assert_is_compatible_with( + [None, self.input_window_size, self.num_features]) + if exogenous_regressors is not None: + exogenous_regressors.get_shape().assert_is_compatible_with( + [None, self.window_size, self.exogenous_size]) + # Create input features. + input_window_features = [] + input_feature_size = 0 + output_window_features = [] + output_feature_size = 0 + if self._periodicities: + _, time_features = self._compute_time_features(times) + num_time_features = self._buckets * len(self._periodicities) + time_features = tf.reshape( + time_features, [batch_size, self.window_size, num_time_features]) + input_time_features, output_time_features = tf.split( + time_features, (self.input_window_size, self.output_window_size), + axis=1) + input_feature_size += num_time_features + output_feature_size += num_time_features + input_window_features.append(input_time_features) + output_window_features.append(output_time_features) + if self.input_window_size: + inp = tf.slice(values, [0, 0, 0], [-1, self.input_window_size, -1]) + input_window_features.append( + tf.reshape(inp, + [batch_size, self.input_window_size, self.num_features])) + input_feature_size += self.num_features + if self.exogenous_size: + input_exogenous_features, output_exogenous_features = tf.split( + exogenous_regressors, + (self.input_window_size, self.output_window_size), + axis=1) + input_feature_size += self.exogenous_size + output_feature_size += self.exogenous_size + input_window_features.append(input_exogenous_features) + output_window_features.append(output_exogenous_features) + assert input_window_features + input_window_features = tf.concat(input_window_features, axis=2) + if output_window_features: + output_window_features = tf.concat(output_window_features, axis=2) + else: + output_window_features = tf.zeros( + [batch_size, self.output_window_size, 0], dtype=self.dtype) + static_batch_size = times.get_shape().dims[0].value + input_window_features.set_shape( + [static_batch_size, self.input_window_size, input_feature_size]) + output_window_features.set_shape( + [static_batch_size, self.output_window_size, output_feature_size]) + return self._output_window_predictions(input_window_features, + output_window_features) + + def _output_window_predictions(self, input_window_features, + output_window_features): + with self._model_scope: + predictions = self._model_instance(input_window_features, + output_window_features) + result_shape = [None, self.output_window_size, self.num_features] + for v in predictions.values(): + v.set_shape(result_shape) + return predictions + + def loss_op(self, targets, prediction_ops): + """Create loss_op.""" + prediction = prediction_ops["mean"] + if self.loss == ARModel.NORMAL_LIKELIHOOD_LOSS: + covariance = prediction_ops["covariance"] + sigma = tf.math.sqrt(tf.math.maximum(covariance, 1e-5)) + normal = distributions.normal.Normal(loc=targets, scale=sigma) + loss_op = -tf.math.reduce_sum(normal.log_prob(prediction)) + else: + assert self.loss == ARModel.SQUARED_LOSS, self.loss + loss_op = tf.math.reduce_sum(tf.math.square(prediction - targets)) + loss_op /= tf.cast( + tf.math.reduce_prod(tf.compat.v1.shape(targets)), loss_op.dtype) + return loss_op + + def _process_exogenous_features(self, times, features): + embedded = super(ARModel, self)._process_exogenous_features( + times=times, features=features) + if embedded is None: + assert self.exogenous_size == 0 + # No embeddings. Return a zero-size [batch, times, 0] array so we don't + # have to special case it downstream. + return tf.zeros( + tf.concat([tf.compat.v1.shape(times), + tf.constant([0])], axis=0)) + else: + return embedded + + # TODO(allenl, agarwal): Consider better ways of warm-starting predictions. + def predict(self, features): + """Computes predictions multiple steps into the future. + + Args: + features: A dictionary with the following key/value pairs: + PredictionFeatures.TIMES: A [batch size, predict window size] integer + Tensor of times, after the window of data indicated by `STATE_TUPLE`, + to make predictions for. + PredictionFeatures.STATE_TUPLE: A tuple of (times, values), times with + shape [batch size, self.input_window_size], values with shape [batch + size, self.input_window_size, self.num_features] representing a + segment of the time series before `TIMES`. This data is used to start + of the autoregressive computation. This should have data for at least + self.input_window_size timesteps. And any exogenous features, with + shapes prefixed by shape of `TIMES`. + + Returns: + A dictionary with keys, "mean", "covariance". The + values are Tensors of shape [batch_size, predict window size, + num_features] and correspond to the values passed in `TIMES`. + """ + if not self._graph_initialized: + self.initialize_graph() + predict_times = tf.cast( + ops.convert_to_tensor(features[PredictionFeatures.TIMES]), + tf.dtypes.int32) + exogenous_regressors = self._process_exogenous_features( + times=predict_times, + features={ + key: value for key, value in features.items() if key not in [ + TrainEvalFeatures.TIMES, TrainEvalFeatures.VALUES, + PredictionFeatures.STATE_TUPLE + ] + }) + with tf.control_dependencies([ + tf.compat.v1.debugging.assert_equal( + tf.compat.v1.shape(predict_times)[1], + tf.compat.v1.shape(exogenous_regressors)[1]) + ]): + exogenous_regressors = tf.identity(exogenous_regressors) + batch_size = tf.compat.v1.shape(predict_times)[0] + num_predict_values = tf.compat.v1.shape(predict_times)[1] + prediction_iterations = ( + (num_predict_values + self.output_window_size - 1) // + self.output_window_size) + # Pad predict_times and exogenous regressors so as to have exact multiple of + # self.output_window_size values per example. + padding_size = ( + prediction_iterations * self.output_window_size - num_predict_values) + predict_times = tf.compat.v1.pad(predict_times, [[0, 0], [0, padding_size]]) + exogenous_regressors = tf.compat.v1.pad(exogenous_regressors, + [[0, 0], [0, padding_size], [0, 0]]) + state = features[PredictionFeatures.STATE_TUPLE] + (state_times, state_values, state_exogenous_regressors) = state + state_times = tf.cast(ops.convert_to_tensor(state_times), tf.dtypes.int32) + state_values = ops.convert_to_tensor(state_values, dtype=self.dtype) + state_exogenous_regressors = ops.convert_to_tensor( + state_exogenous_regressors, dtype=self.dtype) + + initial_input_times = predict_times[:, :self.output_window_size] + initial_input_exogenous_regressors = ( + exogenous_regressors[:, :self.output_window_size, :]) + if self.input_window_size > 0: + initial_input_times = tf.concat( + [state_times[:, -self.input_window_size:], initial_input_times], 1) + values_size = tf.compat.v1.shape(state_values)[1] + times_size = tf.compat.v1.shape(state_times)[1] + with tf.control_dependencies([ + tf.compat.v1.debugging.assert_greater_equal(values_size, + self.input_window_size), + tf.compat.v1.debugging.assert_equal(values_size, times_size) + ]): + initial_input_values = state_values[:, -self.input_window_size:, :] + initial_input_exogenous_regressors = tf.concat([ + state_exogenous_regressors[:, -self.input_window_size:, :], + initial_input_exogenous_regressors[:, :self.output_window_size, :] + ], + axis=1) + else: + initial_input_values = 0 + + # Iterate over the predict_times, predicting self.output_window_size values + # in each iteration. + def _while_condition(iteration_number, *unused_args): + return tf.math.less(iteration_number, prediction_iterations) + + def _while_body(iteration_number, input_times, input_values, + input_exogenous_regressors, mean_ta, covariance_ta): + """Predict self.output_window_size values.""" + prediction_ops = self.prediction_ops(input_times, input_values, + input_exogenous_regressors) + predicted_mean = prediction_ops["mean"] + predicted_covariance = prediction_ops["covariance"] + offset = self.output_window_size * tf.math.minimum( + iteration_number + 1, prediction_iterations - 1) + if self.input_window_size > 0: + if self.output_window_size < self.input_window_size: + new_input_values = tf.concat( + [input_values[:, self.output_window_size:, :], predicted_mean], 1) + new_input_exogenous_regressors = tf.concat([ + input_exogenous_regressors[:, -self.input_window_size:, :], + exogenous_regressors[ + :, offset:offset + self.output_window_size, :] + ], axis=1) + new_input_times = tf.concat([ + input_times[:, -self.input_window_size:], + predict_times[:, offset:offset + self.output_window_size] + ], 1) + else: + new_input_values = predicted_mean[:, -self.input_window_size:, :] + new_input_exogenous_regressors = exogenous_regressors[ + :, + offset - self.input_window_size:offset + self.output_window_size, + :] + new_input_times = predict_times[ + :, + offset - self.input_window_size:offset + self.output_window_size] + else: + new_input_values = input_values + new_input_exogenous_regressors = exogenous_regressors[ + :, offset:offset + self.output_window_size, :] + new_input_times = predict_times[:, + offset:offset + self.output_window_size] + new_input_times.set_shape(initial_input_times.get_shape()) + new_input_exogenous_regressors.set_shape( + initial_input_exogenous_regressors.get_shape()) + new_mean_ta = mean_ta.write(iteration_number, predicted_mean) + if isinstance(covariance_ta, tf.TensorArray): + new_covariance_ta = covariance_ta.write(iteration_number, + predicted_covariance) + else: + new_covariance_ta = covariance_ta + return (iteration_number + 1, new_input_times, new_input_values, + new_input_exogenous_regressors, new_mean_ta, new_covariance_ta) + + # Note that control_flow_ops.while_loop doesn't seem happy with None. Hence + # using 0 for cases where we don't want to predict covariance. + covariance_ta_init = ( + tf.TensorArray(dtype=self.dtype, size=prediction_iterations) + if self.loss != ARModel.SQUARED_LOSS else 0.) + mean_ta_init = tf.TensorArray(dtype=self.dtype, size=prediction_iterations) + _, _, _, _, mean_ta, covariance_ta = tf.compat.v1.while_loop( + _while_condition, _while_body, [ + 0, initial_input_times, initial_input_values, + initial_input_exogenous_regressors, mean_ta_init, covariance_ta_init + ]) + + def _parse_ta(values_ta): + """Helper function to parse the returned TensorArrays.""" + + if not isinstance(values_ta, tf.TensorArray): + return None + predictions_length = prediction_iterations * self.output_window_size + # Shape [prediction_iterations, batch_size, self.output_window_size, + # self.num_features] + values_packed = values_ta.stack() + # Transpose to move batch dimension outside. + output_values = tf.reshape( + tf.compat.v1.transpose(values_packed, [1, 0, 2, 3]), + tf.stack([batch_size, predictions_length, -1])) + # Clip to desired size + return output_values[:, :num_predict_values, :] + + predicted_mean = _parse_ta(mean_ta) + predicted_covariance = _parse_ta(covariance_ta) + if predicted_covariance is None: + predicted_covariance = tf.compat.v1.ones_like(predicted_mean) + + # Transform and scale the mean and covariance appropriately. + predicted_mean = self._scale_back_data(predicted_mean) + predicted_covariance = self._scale_back_variance(predicted_covariance) + + return {"mean": predicted_mean, "covariance": predicted_covariance} + + def _process_window(self, features, mode, exogenous_regressors): + """Compute model outputs on a single window of data.""" + times = tf.cast(features[TrainEvalFeatures.TIMES], tf.dtypes.int64) + values = tf.cast(features[TrainEvalFeatures.VALUES], dtype=self.dtype) + exogenous_regressors = tf.cast(exogenous_regressors, dtype=self.dtype) + original_values = values + + # Extra shape checking for the window size (above that in + # `head.create_estimator_spec`). + expected_times_shape = [None, self.window_size] + if not times.get_shape().is_compatible_with(expected_times_shape): + raise ValueError( + ("ARModel with input_window_size={input_window_size} " + "and output_window_size={output_window_size} expects " + "feature '{times_feature}' to have shape (batch_size, " + "{window_size}) (for any batch_size), but got shape {times_shape}. " + "If you are using RandomWindowInputFn, set " + "window_size={window_size} or adjust the input_window_size and " + "output_window_size arguments to ARModel.").format( + input_window_size=self.input_window_size, + output_window_size=self.output_window_size, + times_feature=TrainEvalFeatures.TIMES, + window_size=self.window_size, + times_shape=times.get_shape())) + values = self._scale_data(values) + if self.input_window_size > 0: + input_values = values[:, :self.input_window_size, :] + else: + input_values = None + prediction_ops = self.prediction_ops(times, input_values, + exogenous_regressors) + prediction = prediction_ops["mean"] + covariance = prediction_ops["covariance"] + targets = tf.slice(values, [0, self.input_window_size, 0], [-1, -1, -1]) + targets.get_shape().assert_is_compatible_with(prediction.get_shape()) + if (mode == estimator_lib.ModeKeys.EVAL and + self.loss == ARModel.SQUARED_LOSS): + # Report an evaluation loss which matches the expected + # (observed - predicted) ** 2. + # Note that this affects only evaluation; the training loss is unaffected. + loss = self.loss_op( + self._scale_back_data(targets), + {"mean": self._scale_back_data(prediction_ops["mean"])}) + else: + loss = self.loss_op(targets, prediction_ops) + + # Scale back the prediction. + prediction = self._scale_back_data(prediction) + covariance = self._scale_back_variance(covariance) + + return model.ModelOutputs( + loss=loss, + end_state=(times[:, -self.input_window_size:], + values[:, -self.input_window_size:, :], + exogenous_regressors[:, -self.input_window_size:, :]), + predictions={ + "mean": prediction, + "covariance": covariance, + "observed": original_values[:, -self.output_window_size:] + }, + prediction_times=times[:, -self.output_window_size:]) + + def get_batch_loss(self, features, mode, state): + """Computes predictions and a loss. + + Args: + features: A dictionary (such as is produced by a chunker) with the + following key/value pairs (shapes are given as required for training): + TrainEvalFeatures.TIMES: A [batch size, self.window_size] integer + Tensor with times for each observation. To train on longer + sequences, the data should first be chunked. + TrainEvalFeatures.VALUES: A [batch size, self.window_size, + self.num_features] Tensor with values for each observation. When + evaluating, `TIMES` and `VALUES` must have a window size of at least + self.window_size, but it may be longer, in which case the last + window_size - self.input_window_size times (or fewer if this is not + divisible by self.output_window_size) will be evaluated on with + non-overlapping output windows (and will have associated + predictions). This is primarily to support qualitative + evaluation/plotting, and is not a recommended way to compute + evaluation losses (since there is no overlap in the output windows, + which for window-based models is an undesirable bias). + mode: The tf.estimator.ModeKeys mode to use (TRAIN or EVAL). + state: Unused + + Returns: + A model.ModelOutputs object. + Raises: + ValueError: If `mode` is not TRAIN or EVAL, or if static shape information + is incorrect. + """ + features = { + feature_name: ops.convert_to_tensor(feature_value) + for feature_name, feature_value in features.items() + } + times = features[TrainEvalFeatures.TIMES] + exogenous_regressors = self._process_exogenous_features( + times=times, + features={ + key: value for key, value in features.items() if key not in [ + TrainEvalFeatures.TIMES, TrainEvalFeatures.VALUES, + PredictionFeatures.STATE_TUPLE + ] + }) + if mode == estimator_lib.ModeKeys.TRAIN: + # For training, we require the window size to be self.window_size as + # iterating sequentially on larger windows could introduce a bias. + return self._process_window( + features, mode=mode, exogenous_regressors=exogenous_regressors) + elif mode == estimator_lib.ModeKeys.EVAL: + # For evaluation, we allow the user to pass in a larger window, in which + # case we try to cover as much of the window as possible without + # overlap. Quantitative evaluation is more efficient/correct with fixed + # windows matching self.window_size (as with training), but this looping + # allows easy plotting of "in-sample" predictions. + times.get_shape().assert_has_rank(2) + static_window_size = times.get_shape().dims[1].value + if (static_window_size is not None and + static_window_size < self.window_size): + raise ValueError( + ("ARModel requires a window of at least input_window_size + " + "output_window_size to evaluate on (input_window_size={}, " + "output_window_size={}, and got shape {} for feature '{}' (batch " + "size, window size)).").format(self.input_window_size, + self.output_window_size, + times.get_shape(), + TrainEvalFeatures.TIMES)) + num_iterations = ( + (tf.compat.v1.shape(times)[1] - self.input_window_size) // + self.output_window_size) + output_size = num_iterations * self.output_window_size + # Rather than dealing with overlapping windows of output, discard a bit at + # the beginning if output windows don't cover evenly. + crop_length = output_size + self.input_window_size + features = { + feature_name: feature_value[:, -crop_length:] + for feature_name, feature_value in features.items() + } + + # Note that, unlike the ARModel's predict() while_loop, each iteration + # here can run in parallel, since we are not feeding predictions or state + # from previous iterations. + def _while_condition(iteration_number, loss_ta, mean_ta, covariance_ta): + del loss_ta, mean_ta, covariance_ta # unused + return iteration_number < num_iterations + + def _while_body(iteration_number, loss_ta, mean_ta, covariance_ta): + """Perform a processing step on a single window of data.""" + base_offset = iteration_number * self.output_window_size + model_outputs = self._process_window( + features={ + feature_name: + feature_value[:, base_offset:base_offset + self.window_size] + for feature_name, feature_value in features.items() + }, + mode=mode, + exogenous_regressors=exogenous_regressors[:, + base_offset:base_offset + + self.window_size]) + # This code needs to be updated if new predictions are added in + # self._process_window + assert len(model_outputs.predictions) == 3 + assert "mean" in model_outputs.predictions + assert "covariance" in model_outputs.predictions + assert "observed" in model_outputs.predictions + return (iteration_number + 1, + loss_ta.write(iteration_number, model_outputs.loss), + mean_ta.write(iteration_number, + model_outputs.predictions["mean"]), + covariance_ta.write(iteration_number, + model_outputs.predictions["covariance"])) + + _, loss_ta, mean_ta, covariance_ta = tf.compat.v1.while_loop( + _while_condition, _while_body, [ + 0, + tf.TensorArray(dtype=self.dtype, size=num_iterations), + tf.TensorArray(dtype=self.dtype, size=num_iterations), + tf.TensorArray(dtype=self.dtype, size=num_iterations) + ]) + values = tf.cast(features[TrainEvalFeatures.VALUES], dtype=self.dtype) + batch_size = tf.compat.v1.shape(times)[0] + prediction_shape = [ + batch_size, self.output_window_size * num_iterations, + self.num_features + ] + (previous_state_times, previous_state_values, + previous_state_exogenous_regressors) = state + # Make sure returned state always has windows of self.input_window_size, + # even if we were passed fewer than self.input_window_size points this + # time. + if self.input_window_size > 0: + new_state_times = tf.concat( + [previous_state_times, + tf.cast(times, dtype=tf.dtypes.int64)], + axis=1)[:, -self.input_window_size:] + new_state_times.set_shape((None, self.input_window_size)) + new_state_values = tf.concat( + [previous_state_values, + self._scale_data(values)], axis=1)[:, -self.input_window_size:, :] + new_state_values.set_shape( + (None, self.input_window_size, self.num_features)) + new_exogenous_regressors = tf.concat( + [previous_state_exogenous_regressors, exogenous_regressors], + axis=1)[:, -self.input_window_size:, :] + new_exogenous_regressors.set_shape( + (None, self.input_window_size, self.exogenous_size)) + else: + # There is no state to keep, and the strided slices above do not handle + # input_window_size=0. + new_state_times = previous_state_times + new_state_values = previous_state_values + new_exogenous_regressors = previous_state_exogenous_regressors + return model.ModelOutputs( + loss=tf.math.reduce_mean(loss_ta.stack(), axis=0), + end_state=(new_state_times, new_state_values, + new_exogenous_regressors), + predictions={ + "mean": + tf.reshape( + tf.compat.v1.transpose(mean_ta.stack(), [1, 0, 2, 3]), + prediction_shape), + "covariance": + tf.reshape( + tf.compat.v1.transpose(covariance_ta.stack(), + [1, 0, 2, 3]), prediction_shape), + "observed": + values[:, -output_size:] + }, + prediction_times=times[:, -output_size:]) + else: + raise ValueError( + "Unknown mode '{}' passed to get_batch_loss.".format(mode)) + + def _compute_time_features(self, time): + """Compute some features on the time value.""" + batch_size = tf.compat.v1.shape(time)[0] + num_periods = len(self._periodicities) + # Reshape to 3D. + periods = tf.constant( + self._periodicities, shape=[1, 1, num_periods, 1], dtype=time.dtype) + time = tf.reshape(time, [batch_size, -1, 1, 1]) + window_offset = time / self._periodicities + # Cast to appropriate type and scale to [0, 1) range + mod = ( + tf.cast(time % periods, self.dtype) * self._buckets / + tf.cast(periods, self.dtype)) + # Bucketize based on some fixed width intervals. For a value t and interval + # [a, b), we return (t - a) if a <= t < b, else 0. + intervals = tf.reshape( + tf.range(self._buckets, dtype=self.dtype), [1, 1, 1, self._buckets]) + mod = tf.nn.relu(mod - intervals) + mod = tf.where(mod < 1.0, mod, tf.compat.v1.zeros_like(mod)) + return window_offset, mod diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/timeseries/estimators.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/timeseries/estimators.py new file mode 100644 index 0000000000000000000000000000000000000000..bfc44cbf2a9dd5c38179ea1fc7a372ecdd15b9be --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/timeseries/estimators.py @@ -0,0 +1,441 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Estimators for time series models.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import functools +import tensorflow as tf +from tensorflow_estimator.python.estimator import estimator_lib +from tensorflow_estimator.python.estimator.canned import optimizers +from tensorflow_estimator.python.estimator.canned.timeseries import ar_model +from tensorflow_estimator.python.estimator.canned.timeseries import feature_keys +from tensorflow_estimator.python.estimator.canned.timeseries import head as ts_head_lib +from tensorflow_estimator.python.estimator.canned.timeseries import math_utils +from tensorflow_estimator.python.estimator.canned.timeseries import state_management +from tensorflow_estimator.python.estimator.export import export_lib + + +class TimeSeriesRegressor(estimator_lib.Estimator): + """An Estimator to fit and evaluate a time series model.""" + + def __init__(self, + model, + state_manager=None, + optimizer=None, + model_dir=None, + config=None, + head_type=ts_head_lib.TimeSeriesRegressionHead): + """Initialize the Estimator. + + Args: + model: The time series model to wrap (inheriting from TimeSeriesModel). + state_manager: The state manager to use, or (by default) + PassthroughStateManager if none is needed. + optimizer: The optimization algorithm to use when training, inheriting + from tf.train.Optimizer. Defaults to Adam with step size 0.02. + model_dir: See `Estimator`. + config: See `Estimator`. + head_type: The kind of head to use for the model (inheriting from + `TimeSeriesRegressionHead`). + """ + input_statistics_generator = math_utils.InputStatisticsFromMiniBatch( + dtype=model.dtype, num_features=model.num_features) + if state_manager is None: + if isinstance(model, ar_model.ARModel): + state_manager = state_management.FilteringOnlyStateManager() + else: + state_manager = state_management.PassthroughStateManager() + if optimizer is None: + optimizer = tf.compat.v1.train.AdamOptimizer(0.02) + self._model = model + ts_regression_head = head_type( + model=model, + state_manager=state_manager, + optimizer=optimizer, + input_statistics_generator=input_statistics_generator) + model_fn = ts_regression_head.create_estimator_spec + super(TimeSeriesRegressor, self).__init__( + model_fn=model_fn, model_dir=model_dir, config=config) + + def _model_start_state_placeholders(self, + batch_size_tensor, + static_batch_size=None): + """Creates placeholders with zeroed start state for the current model.""" + gathered_state = {} + # Models may not know the shape of their state without creating some + # variables/ops. Avoid polluting the default graph by making a new one. We + # use only static metadata from the returned Tensors. + with tf.Graph().as_default(): + self._model.initialize_graph() + + # Evaluate the initial state as same-dtype "zero" values. These zero + # constants aren't used, but are necessary for feeding to + # placeholder_with_default for the "cold start" case where state is not + # fed to the model. + def _zeros_like_constant(tensor): + return tf.get_static_value(tf.compat.v1.zeros_like(tensor)) + + start_state = tf.nest.map_structure(_zeros_like_constant, + self._model.get_start_state()) + for prefixed_state_name, state in ts_head_lib.state_to_dictionary( + start_state).items(): + state_shape_with_batch = tf.TensorShape( + (static_batch_size,)).concatenate(state.shape) + default_state_broadcast = tf.tile( + state[None, ...], + multiples=tf.concat( + [batch_size_tensor[None], + tf.ones(len(state.shape), dtype=tf.dtypes.int32)], + axis=0)) + gathered_state[ + prefixed_state_name] = tf.compat.v1.placeholder_with_default( + input=default_state_broadcast, + name=prefixed_state_name, + shape=state_shape_with_batch) + return gathered_state + + def build_one_shot_parsing_serving_input_receiver_fn(self, + filtering_length, + prediction_length, + default_batch_size=None, + values_input_dtype=None, + truncate_values=False): + """Build an input_receiver_fn for export_saved_model accepting tf.Examples. + + Only compatible with `OneShotPredictionHead` (see `head`). + + Args: + filtering_length: The number of time steps used as input to the model, for + which values are provided. If more than `filtering_length` values are + provided (via `truncate_values`), only the first `filtering_length` + values are used. + prediction_length: The number of time steps requested as predictions from + the model. Times and all exogenous features must be provided for these + steps. + default_batch_size: If specified, must be a scalar integer. Sets the batch + size in the static shape information of all feature Tensors, which means + only this batch size will be accepted by the exported model. If None + (default), static shape information for batch sizes is omitted. + values_input_dtype: An optional dtype specification for values in the + tf.Example protos (either float32 or int64, since these are the numeric + types supported by tf.Example). After parsing, values are cast to the + model's dtype (float32 or float64). + truncate_values: If True, expects `filtering_length + prediction_length` + values to be provided, but only uses the first `filtering_length`. If + False (default), exactly `filtering_length` values must be provided. + + Returns: + An input_receiver_fn which may be passed to the Estimator's + export_saved_model. + + Expects features contained in a vector of serialized tf.Examples with + shape [batch size] (dtype `tf.string`), each tf.Example containing + features with the following shapes: + times: [filtering_length + prediction_length] integer + values: [filtering_length, num features] floating point. If + `truncate_values` is True, expects `filtering_length + + prediction_length` values but only uses the first `filtering_length`. + all exogenous features: [filtering_length + prediction_length, ...] + (various dtypes) + """ + if values_input_dtype is None: + values_input_dtype = tf.dtypes.float32 + if truncate_values: + values_proto_length = filtering_length + prediction_length + else: + values_proto_length = filtering_length + + def _serving_input_receiver_fn(): + """A receiver function to be passed to export_saved_model.""" + times_column = tf.feature_column.numeric_column( + key=feature_keys.TrainEvalFeatures.TIMES, dtype=tf.dtypes.int64) + values_column = tf.feature_column.numeric_column( + key=feature_keys.TrainEvalFeatures.VALUES, + dtype=values_input_dtype, + shape=(self._model.num_features,)) + parsed_features_no_sequence = ( + tf.compat.v1.feature_column.make_parse_example_spec( + list(self._model.exogenous_feature_columns) + + [times_column, values_column])) + parsed_features = {} + for key, feature_spec in parsed_features_no_sequence.items(): + if isinstance(feature_spec, tf.io.FixedLenFeature): + if key == feature_keys.TrainEvalFeatures.VALUES: + parsed_features[key] = feature_spec._replace( + shape=((values_proto_length,) + feature_spec.shape)) + else: + parsed_features[key] = feature_spec._replace( + shape=((filtering_length + prediction_length,) + + feature_spec.shape)) + elif feature_spec.dtype == tf.dtypes.string: + parsed_features[key] = tf.io.FixedLenFeature( + shape=(filtering_length + prediction_length,), + dtype=tf.dtypes.string) + else: # VarLenFeature + raise ValueError("VarLenFeatures not supported, got %s for key %s" % + (feature_spec, key)) + tfexamples = tf.compat.v1.placeholder( + shape=[default_batch_size], dtype=tf.dtypes.string, name="input") + features = tf.compat.v1.io.parse_example( + serialized=tfexamples, features=parsed_features) + features[feature_keys.TrainEvalFeatures.TIMES] = tf.compat.v1.squeeze( + features[feature_keys.TrainEvalFeatures.TIMES], axis=-1) + features[feature_keys.TrainEvalFeatures.VALUES] = tf.cast( + features[feature_keys.TrainEvalFeatures.VALUES], + dtype=self._model.dtype)[:, :filtering_length] + features.update( + self._model_start_state_placeholders( + batch_size_tensor=tf.compat.v1.shape( + features[feature_keys.TrainEvalFeatures.TIMES])[0], + static_batch_size=default_batch_size)) + return export_lib.ServingInputReceiver(features, {"examples": tfexamples}) + + return _serving_input_receiver_fn + + def build_raw_serving_input_receiver_fn(self, + default_batch_size=None, + default_series_length=None): + """Build an input_receiver_fn for export_saved_model which accepts arrays. + + Automatically creates placeholders for exogenous `FeatureColumn`s passed to + the model. + + Args: + default_batch_size: If specified, must be a scalar integer. Sets the batch + size in the static shape information of all feature Tensors, which means + only this batch size will be accepted by the exported model. If None + (default), static shape information for batch sizes is omitted. + default_series_length: If specified, must be a scalar integer. Sets the + series length in the static shape information of all feature Tensors, + which means only this series length will be accepted by the exported + model. If None (default), static shape information for series length is + omitted. + + Returns: + An input_receiver_fn which may be passed to the Estimator's + export_saved_model. + """ + + def _serving_input_receiver_fn(): + """A receiver function to be passed to export_saved_model.""" + placeholders = {} + time_placeholder = tf.compat.v1.placeholder( + name=feature_keys.TrainEvalFeatures.TIMES, + dtype=tf.dtypes.int64, + shape=[default_batch_size, default_series_length]) + placeholders[feature_keys.TrainEvalFeatures.TIMES] = time_placeholder + # Values are only necessary when filtering. For prediction the default + # value will be ignored. + placeholders[feature_keys.TrainEvalFeatures.VALUES] = ( + tf.compat.v1.placeholder_with_default( + name=feature_keys.TrainEvalFeatures.VALUES, + input=tf.zeros( + shape=[ + default_batch_size if default_batch_size else 0, + default_series_length if default_series_length else 0, + self._model.num_features + ], + dtype=self._model.dtype), + shape=(default_batch_size, default_series_length, + self._model.num_features))) + if self._model.exogenous_feature_columns: + with tf.Graph().as_default(): + # Default placeholders have only an unknown batch dimension. Make them + # in a separate graph, then splice in the series length to the shapes + # and re-create them in the outer graph. + parsed_features = ( + tf.compat.v1.feature_column.make_parse_example_spec( + self._model.exogenous_feature_columns)) + placeholder_features = tf.compat.v1.io.parse_example( + serialized=tf.compat.v1.placeholder( + shape=[None], dtype=tf.dtypes.string), + features=parsed_features) + exogenous_feature_shapes = { + key: (value.get_shape(), value.dtype) + for key, value in placeholder_features.items() + } + for feature_key, (batch_only_feature_shape, + value_dtype) in (exogenous_feature_shapes.items()): + batch_only_feature_shape = ( + batch_only_feature_shape.with_rank_at_least(1).as_list()) + feature_shape = ([default_batch_size, default_series_length] + + batch_only_feature_shape[1:]) + placeholders[feature_key] = tf.compat.v1.placeholder( + dtype=value_dtype, name=feature_key, shape=feature_shape) + batch_size_tensor = tf.compat.v1.shape(time_placeholder)[0] + placeholders.update( + self._model_start_state_placeholders( + batch_size_tensor, static_batch_size=default_batch_size)) + return export_lib.ServingInputReceiver(placeholders, placeholders) + + return _serving_input_receiver_fn + + +# TODO(b/113684821): Add detailed documentation on what the input_fn should do. +# Add an example of making and returning a Dataset object. Determine if +# endogenous features can be passed in as FeatureColumns. Move ARModel's loss +# functions into a more general location. +class LSTMAutoRegressor(TimeSeriesRegressor): + """An Estimator for an LSTM autoregressive model. + + LSTMAutoRegressor is a window-based model, inputting fixed windows of length + `input_window_size` and outputting fixed windows of length + `output_window_size`. These two parameters must add up to the window_size + of data returned by the `input_fn`. + + Each periodicity in the `periodicities` arg is divided by the `num_timesteps` + into timesteps that are represented as time features added to the model. + + A good heuristic for picking an appropriate periodicity for a given data set + would be the length of cycles in the data. For example, energy usage in a + home is typically cyclic each day. If the time feature in a home energy + usage dataset is in the unit of hours, then 24 would be an appropriate + periodicity. Similarly, a good heuristic for `num_timesteps` is how often the + data is expected to change within the cycle. For the aforementioned home + energy usage dataset and periodicity of 24, then 48 would be a reasonable + value if usage is expected to change every half hour. + + Each feature's value for a given example with time t is the difference + between t and the start of the timestep it falls under. If it doesn't fall + under a feature's associated timestep, then that feature's value is zero. + + For example: if `periodicities` = (9, 12) and `num_timesteps` = 3, then 6 + features would be added to the model, 3 for periodicity 9 and 3 for + periodicity 12. + + For an example data point where t = 17: + - It's in the 3rd timestep for periodicity 9 (2nd period is 9-18 and 3rd + timestep is 15-18) + - It's in the 2nd timestep for periodicity 12 (2nd period is 12-24 and + 2nd timestep is between 16-20). + + Therefore the 6 added features for this row with t = 17 would be: + + # Feature name (periodicity#_timestep#), feature value + P9_T1, 0 # not in first timestep + P9_T2, 0 # not in second timestep + P9_T3, 2 # 17 - 15 since 15 is the start of the 3rd timestep + P12_T1, 0 # not in first timestep + P12_T2, 1 # 17 - 16 since 16 is the start of the 2nd timestep + P12_T3, 0 # not in third timestep + + Example Code: + + ```python + extra_feature_columns = ( + feature_column.numeric_column("exogenous_variable"), + ) + + estimator = LSTMAutoRegressor( + periodicities=10, + input_window_size=10, + output_window_size=5, + model_dir="/path/to/model/dir", + num_features=1, + extra_feature_columns=extra_feature_columns, + num_timesteps=50, + num_units=10, + optimizer=tf.train.ProximalAdagradOptimizer(...)) + + # Input builders + def input_fn_train(): + return { + "times": tf.range(15)[None, :], + "values": tf.random_normal(shape=[1, 15, 1]) + } + estimator.train(input_fn=input_fn_train, steps=100) + + def input_fn_eval(): + pass + metrics = estimator.evaluate(input_fn=input_fn_eval, steps=10) + + def input_fn_predict(): + pass + predictions = estimator.predict(input_fn=input_fn_predict) + ``` + """ + + def __init__(self, + periodicities, + input_window_size, + output_window_size, + model_dir=None, + num_features=1, + extra_feature_columns=None, + num_timesteps=10, + loss=ar_model.ARModel.NORMAL_LIKELIHOOD_LOSS, + num_units=128, + optimizer="Adam", + config=None): + """Initialize the Estimator. + + Args: + periodicities: periodicities of the input data, in the same units as the + time feature (for example 24 if feeding hourly data with a daily + periodicity, or 60 * 24 if feeding minute-level data with daily + periodicity). Note this can be a single value or a list of values for + multiple periodicities. + input_window_size: Number of past time steps of data to look at when doing + the regression. + output_window_size: Number of future time steps to predict. Note that + setting this value to > 1 empirically seems to give a better fit. + model_dir: Directory to save model parameters, graph and etc. This can + also be used to load checkpoints from the directory into a estimator to + continue training a previously saved model. + num_features: The dimensionality of the time series (default value is one + for univariate, more than one for multivariate). + extra_feature_columns: A list of `tf.feature_column`s (for example + `tf.feature_column.embedding_column`) corresponding to features which + provide extra information to the model but are not part of the series to + be predicted. + num_timesteps: Number of buckets into which to divide (time % + periodicity). This value multiplied by the number of periodicities is + the number of time features added to the model. + loss: Loss function to use for training. Currently supported values are + SQUARED_LOSS and NORMAL_LIKELIHOOD_LOSS. Note that for + NORMAL_LIKELIHOOD_LOSS, we train the covariance term as well. For + SQUARED_LOSS, the evaluation loss is reported based on un-scaled + observations and predictions, while the training loss is computed on + normalized data. + num_units: The size of the hidden state in the encoder and decoder LSTM + cells. + optimizer: string, `tf.train.Optimizer` object, or callable that defines + the optimizer algorithm to use for training. Defaults to the Adam + optimizer with a learning rate of 0.01. + config: Optional `estimator.RunConfig` object to configure the runtime + settings. + """ + optimizer = optimizers.get_optimizer_instance(optimizer, learning_rate=0.01) + model = ar_model.ARModel( + periodicities=periodicities, + input_window_size=input_window_size, + output_window_size=output_window_size, + num_features=num_features, + exogenous_feature_columns=extra_feature_columns, + num_time_buckets=num_timesteps, + loss=loss, + prediction_model_factory=functools.partial( + ar_model.LSTMPredictionModel, num_units=num_units)) + state_manager = state_management.FilteringOnlyStateManager() + super(LSTMAutoRegressor, self).__init__( + model=model, + state_manager=state_manager, + optimizer=optimizer, + model_dir=model_dir, + config=config, + head_type=ts_head_lib.OneShotPredictionHead) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/timeseries/feature_keys.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/timeseries/feature_keys.py new file mode 100644 index 0000000000000000000000000000000000000000..ea13f852891a146a1491e294fd5dc4625ce20146 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/timeseries/feature_keys.py @@ -0,0 +1,75 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Commonly used special feature names for time series models.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import tensorflow as tf + + +class State(object): + """Key formats for accepting/returning state.""" + # The model-dependent state to start from, as a single tuple. + STATE_TUPLE = "start_tuple" + # Same meaning as STATE_TUPLE, but prefixes keys representing flattened model + # state rather than mapping to a nested tuple containing model state, + # primarily for use with export_saved_model. + STATE_PREFIX = "model_state" + + +class Times(object): + """Key formats for accepting/returning times.""" + # An increasing vector of integers. + TIMES = "times" + + +class Values(object): + """Key formats for accepting/returning values.""" + # Floating point, with one or more values corresponding to each time in TIMES. + VALUES = "values" + + +class TrainEvalFeatures(Times, Values): + """Feature names used during training and evaluation.""" + pass + + +class PredictionFeatures(Times, State): + """Feature names used during prediction.""" + pass + + +class FilteringFeatures(Times, Values, State): + """Special feature names for filtering.""" + pass + + +class PredictionResults(Times): + """Keys returned when predicting (not comprehensive).""" + pass + + +class FilteringResults(Times, State): + """Keys returned from evaluation/filtering.""" + pass + + +class SavedModelLabels(object): + """Names of signatures exported with export_saved_model.""" + PREDICT = tf.saved_model.DEFAULT_SERVING_SIGNATURE_DEF_KEY + FILTER = "filter" + COLD_START_FILTER = "cold_start_filter" diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/timeseries/head.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/timeseries/head.py new file mode 100644 index 0000000000000000000000000000000000000000..d5b0b490a61576505e7c6acad034fe9784dc73ab --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/timeseries/head.py @@ -0,0 +1,473 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Timeseries head.""" +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import re +import tensorflow as tf +from tensorflow.python.framework import ops +from tensorflow_estimator.python.estimator import estimator_lib +from tensorflow_estimator.python.estimator.canned import head as head_lib +from tensorflow_estimator.python.estimator.canned import metric_keys +from tensorflow_estimator.python.estimator.canned.timeseries import feature_keys +from tensorflow_estimator.python.estimator.export import export_lib + + +class _NoStatePredictOutput(export_lib.PredictOutput): + + def as_signature_def(self, receiver_tensors): + no_state_receiver_tensors = { + key: value + for key, value in receiver_tensors.items() + if not key.startswith(feature_keys.State.STATE_PREFIX) + } + return super( + _NoStatePredictOutput, + self).as_signature_def(receiver_tensors=no_state_receiver_tensors) + + +class TimeSeriesRegressionHead(head_lib._Head): # pylint:disable=protected-access + """Determines input and output signatures for a time series model.""" + + def __init__(self, + model, + state_manager, + optimizer, + input_statistics_generator=None, + name=None): + """Creates a `_Head` for time series regression. + + Args: + model: A model for time series regression. + state_manager: A state manager. + optimizer: An optimizer. + input_statistics_generator: A input statistics generator. + name: An optional name for the model. + """ + self.model = model + self.state_manager = state_manager + self.optimizer = optimizer + self.input_statistics_generator = input_statistics_generator + self._name = name + + @property + def name(self): + return self._name + + # TODO(terrytangyuan): consolidate `model_outputs` and `_Head.LossSpec` + # once `_Head.create_loss` becomes extendable + def create_loss(self, features, mode, logits=None, labels=None): + """See `_Head`.""" + model_outputs = self.state_manager.define_loss(self.model, features, mode) + tf.compat.v1.summary.scalar( + head_lib._summary_key(self._name, metric_keys.MetricKeys.LOSS), + model_outputs.loss) + return model_outputs + + @property + def logits_dimension(self): + """See `_Head`.""" + return 1 + + def _train_ops(self, features): + """Add training ops to the graph.""" + mode = estimator_lib.ModeKeys.TRAIN + with tf.compat.v1.variable_scope( + "model", + # Use ResourceVariables to avoid race conditions. + use_resource=True): + model_outputs = self.create_loss(features, mode) + + train_op = self.optimizer.minimize( + model_outputs.loss, global_step=tf.compat.v1.train.get_global_step()) + return estimator_lib.EstimatorSpec( + loss=model_outputs.loss, mode=mode, train_op=train_op) + + def _evaluate_ops(self, features): + """Add ops for evaluation (aka filtering) to the graph.""" + mode = estimator_lib.ModeKeys.EVAL + with tf.compat.v1.variable_scope("model", use_resource=True): + model_outputs = self.create_loss(features, mode) + metrics = {} + # Just output in-sample predictions for the last chunk seen + for prediction_key, prediction_value in model_outputs.predictions.items(): + metrics[prediction_key] = _identity_metric_single(prediction_key, + prediction_value) + metrics[feature_keys.FilteringResults.TIMES] = _identity_metric_single( + feature_keys.FilteringResults.TIMES, model_outputs.prediction_times) + metrics[feature_keys.FilteringResults.STATE_TUPLE] = ( + _identity_metric_nested(feature_keys.FilteringResults.STATE_TUPLE, + model_outputs.end_state)) + metrics[metric_keys.MetricKeys.LOSS_MEAN] = tf.compat.v1.metrics.mean( + model_outputs.loss, name="average_loss") + return estimator_lib.EstimatorSpec( + loss=model_outputs.loss, + mode=mode, + eval_metric_ops=metrics, + # needed for custom metrics. + predictions=model_outputs.predictions) + + def _predict_ops(self, features): + """Add ops for prediction to the graph.""" + with tf.compat.v1.variable_scope("model", use_resource=True): + prediction = self.model.predict(features=features) + prediction[feature_keys.PredictionResults.TIMES] = features[ + feature_keys.PredictionFeatures.TIMES] + return estimator_lib.EstimatorSpec( + predictions=prediction, mode=estimator_lib.ModeKeys.PREDICT) + + def _serving_ops(self, features): + """Add ops for serving to the graph.""" + with tf.compat.v1.variable_scope("model", use_resource=True): + prediction_outputs = self.model.predict(features=features) + with tf.compat.v1.variable_scope("model", reuse=True): + filtering_outputs = self.create_loss(features, + estimator_lib.ModeKeys.EVAL) + with tf.compat.v1.variable_scope("model", reuse=True): + no_state_features = { + k: v + for k, v in features.items() + if not k.startswith(feature_keys.State.STATE_PREFIX) + } + # Ignore any state management when cold-starting. The model's default + # start state is replicated across the batch. + cold_filtering_outputs = self.model.define_loss( + features=no_state_features, mode=estimator_lib.ModeKeys.EVAL) + return estimator_lib.EstimatorSpec( + mode=estimator_lib.ModeKeys.PREDICT, + export_outputs={ + feature_keys.SavedModelLabels.PREDICT: + export_lib.PredictOutput(prediction_outputs), + feature_keys.SavedModelLabels.FILTER: + export_lib.PredictOutput( + state_to_dictionary(filtering_outputs.end_state)), + feature_keys.SavedModelLabels.COLD_START_FILTER: + _NoStatePredictOutput( + state_to_dictionary(cold_filtering_outputs.end_state)) + }, + # Likely unused, but it is necessary to return `predictions` to satisfy + # the Estimator's error checking. + predictions={}) + + def _convert_feature_to_tensor(self, name, value): + """Casts features to the correct dtype based on their name.""" + if name in [ + feature_keys.TrainEvalFeatures.TIMES, + feature_keys.PredictionFeatures.TIMES + ]: + return tf.cast(value, tf.dtypes.int64) + if name == feature_keys.TrainEvalFeatures.VALUES: + return tf.cast(value, self.model.dtype) + if name == feature_keys.PredictionFeatures.STATE_TUPLE: + return value # Correct dtypes are model-dependent + return tf.compat.v1.convert_to_tensor_or_sparse_tensor(value) + + def _gather_state(self, features): + """Returns `features` with state packed, indicates if packing was done.""" + prefixed_state_re = re.compile(r"^" + feature_keys.State.STATE_PREFIX + + r"_(\d+)$") + numbered_state = [] + for key, tensor in features.items(): + search_result = prefixed_state_re.search(key) + if search_result: + numbered_state.append((int(search_result.group(1)), key, tensor)) + if not numbered_state: + return features, False + features = features.copy() + for _, key, _ in numbered_state: + del features[key] + numbered_state.sort(key=lambda number, *_: number) + features[feature_keys.State.STATE_TUPLE] = tf.nest.pack_sequence_as( + structure=self.model.get_start_state(), + flat_sequence=[tensor for _, _, tensor in numbered_state]) + return features, True + + def _check_predict_features(self, features): + """Raises errors if features are not suitable for prediction.""" + if feature_keys.PredictionFeatures.TIMES not in features: + raise ValueError("Expected a '{}' feature for prediction.".format( + feature_keys.PredictionFeatures.TIMES)) + if feature_keys.PredictionFeatures.STATE_TUPLE not in features: + raise ValueError("Expected a '{}' feature for prediction.".format( + feature_keys.PredictionFeatures.STATE_TUPLE)) + times_feature = features[feature_keys.PredictionFeatures.TIMES] + if not times_feature.get_shape().is_compatible_with([None, None]): + raise ValueError( + ("Expected shape (batch dimension, window size) for feature '{}' " + "(got shape {})").format(feature_keys.PredictionFeatures.TIMES, + times_feature.get_shape())) + _check_feature_shapes_compatible_with( + features=features, + compatible_with_name=feature_keys.PredictionFeatures.TIMES, + compatible_with_value=times_feature, + ignore=set([ + # Model-dependent shapes + feature_keys.PredictionFeatures.STATE_TUPLE + ])) + + def create_estimator_spec(self, features, mode, labels=None): + """Performs basic error checking and returns an EstimatorSpec.""" + with ops.name_scope(self._name, "head"): + # for better error messages. + if labels is not None and not (isinstance(labels, dict) and labels == {}): # pylint: disable=g-explicit-bool-comparison + raise ValueError( + "The model received a `labels`, which is not supported. " + "Pass '{}' and '{}' as features.".format( + feature_keys.TrainEvalFeatures.TIMES, + feature_keys.TrainEvalFeatures.VALUES)) + del labels + features = { + name: self._convert_feature_to_tensor(name=name, value=value) + for name, value in features.items() + } + if self.input_statistics_generator is not None: + input_statistics = self.input_statistics_generator.initialize_graph( + features, update_statistics=(mode == estimator_lib.ModeKeys.TRAIN)) + else: + input_statistics = None + self.model.initialize_graph(input_statistics=input_statistics) + + # _gather_state requires the model to have its graph initialized (so it + # has access to the structure of the model's state) + features, passed_flat_state = self._gather_state(features) + if (mode == estimator_lib.ModeKeys.TRAIN or + mode == estimator_lib.ModeKeys.EVAL): + _check_train_eval_features(features, self.model) + elif mode == estimator_lib.ModeKeys.PREDICT: + self._check_predict_features(features) + else: + raise ValueError("Unknown mode '{}' passed to model_fn.".format(mode)) + + self.state_manager.initialize_graph( + model=self.model, input_statistics=input_statistics) + + if mode == estimator_lib.ModeKeys.TRAIN: + return self._train_ops(features) + elif mode == estimator_lib.ModeKeys.EVAL: + return self._evaluate_ops(features) + elif mode == estimator_lib.ModeKeys.PREDICT and not passed_flat_state: + return self._predict_ops(features) + elif mode == estimator_lib.ModeKeys.PREDICT and passed_flat_state: + # The mode is PREDICT, but we're actually in export_saved_model for + # serving. We want to return two graphs: one for filtering (state + data + # -> state) and one for predicting (state -> prediction). + return self._serving_ops(features) + + +class OneShotPredictionHead(TimeSeriesRegressionHead): + """A time series head which exports a single stateless serving signature. + + The serving default signature exported by this head expects `times`, `values`, + and any exogenous features, but no state. `values` has shape `[batch_size, + filter_length, num_features]` and `times` has shape `[batch_size, + total_length]`, where `total_length > filter_length`. Any exogenous features + must have their shapes prefixed by the shape of the `times` feature. + + When serving, first performs filtering on the series up to `filter_length` + starting from the default start state for the model, then computes predictions + on the remainder of the series, returning them. + + Model state is neither accepted nor returned, so filtering must be performed + each time predictions are requested when using this head. + """ + + def _check_predict_features(self, features): + """Raises errors if features are not suitable for one-shot prediction.""" + if feature_keys.PredictionFeatures.TIMES not in features: + raise ValueError("Expected a '{}' feature for prediction.".format( + feature_keys.PredictionFeatures.TIMES)) + if feature_keys.TrainEvalFeatures.VALUES not in features: + raise ValueError("Expected a '{}' feature for prediction.".format( + feature_keys.TrainEvalFeatures.VALUES)) + if feature_keys.PredictionFeatures.STATE_TUPLE not in features: + raise ValueError("Expected a '{}' feature for prediction.".format( + feature_keys.PredictionFeatures.STATE_TUPLE)) + times_feature = features[feature_keys.PredictionFeatures.TIMES] + if not times_feature.get_shape().is_compatible_with([None, None]): + raise ValueError( + ("Expected shape (batch dimension, window size) for feature '{}' " + "(got shape {})").format(feature_keys.PredictionFeatures.TIMES, + times_feature.get_shape())) + _check_feature_shapes_compatible_with( + features=features, + compatible_with_name=feature_keys.PredictionFeatures.TIMES, + compatible_with_value=times_feature, + ignore=set([ + # Model-dependent shapes + feature_keys.PredictionFeatures.STATE_TUPLE, + # One shot prediction head relies on values being shorter than + # times. Even though we're predicting eventually, we need values for + # the filtering phase. + feature_keys.TrainEvalFeatures.VALUES, + ])) + + def _evaluate_ops(self, features): + """Add ops for evaluation (aka filtering) to the graph.""" + spec = super(OneShotPredictionHead, self)._evaluate_ops(features) + # No state is fed to OneShotPredictionHead, so we don't return it; it being + # a tuple can cause issues for downstream infrastructure. + del spec.eval_metric_ops[feature_keys.State.STATE_TUPLE] + return spec + + def _serving_ops(self, features): + """Add ops for serving to the graph.""" + with tf.compat.v1.variable_scope("model", use_resource=True): + filtering_features = {} + prediction_features = {} + values_length = tf.compat.v1.shape( + features[feature_keys.FilteringFeatures.VALUES])[1] + for key, value in features.items(): + if key == feature_keys.State.STATE_TUPLE: + # Ignore state input. The model's default start state is replicated + # across the batch. + continue + if key == feature_keys.FilteringFeatures.VALUES: + filtering_features[key] = value + else: + filtering_features[key] = value[:, :values_length] + prediction_features[key] = value[:, values_length:] + cold_filtering_outputs = self.model.define_loss( + features=filtering_features, mode=estimator_lib.ModeKeys.EVAL) + prediction_features[feature_keys.State.STATE_TUPLE] = ( + cold_filtering_outputs.end_state) + with tf.compat.v1.variable_scope("model", reuse=True): + prediction_outputs = self.model.predict(features=prediction_features) + return estimator_lib.EstimatorSpec( + mode=estimator_lib.ModeKeys.PREDICT, + export_outputs={ + feature_keys.SavedModelLabels.PREDICT: + _NoStatePredictOutput(prediction_outputs), + }, + # Likely unused, but it is necessary to return `predictions` to satisfy + # the Estimator's error checking. + predictions={}) + + +def _check_feature_shapes_compatible_with(features, + compatible_with_name, + compatible_with_value, + ignore=None): + """Checks all features are compatible with the given time-like feature.""" + if ignore is None: + ignore = set() + for name, value in features.items(): + if name in ignore: + continue + feature_shape = value.get_shape() + if feature_shape.ndims is None: + continue + if feature_shape.ndims < 2: + raise ValueError( + ("Features must have shape (batch dimension, window size, ...) " + "(got rank {} for feature '{}')").format(feature_shape.ndims, name)) + if not feature_shape[:2].is_compatible_with( + compatible_with_value.get_shape()): + raise ValueError( + ("Features must have shape (batch dimension, window size, ...) " + "where batch dimension and window size match the " + "'{times_feature}' feature (got shape {feature_shape} for " + "feature '{feature_name}' but shape {times_shape} for feature " + "'{times_feature}')").format( + times_feature=compatible_with_name, + feature_shape=feature_shape, + feature_name=name, + times_shape=compatible_with_value.get_shape())) + + +def _check_train_eval_features(features, model): + """Raise errors if features are not suitable for training/evaluation.""" + if feature_keys.TrainEvalFeatures.TIMES not in features: + raise ValueError("Expected a '{}' feature for training/evaluation.".format( + feature_keys.TrainEvalFeatures.TIMES)) + if feature_keys.TrainEvalFeatures.VALUES not in features: + raise ValueError("Expected a '{}' feature for training/evaluation.".format( + feature_keys.TrainEvalFeatures.VALUES)) + times_feature = features[feature_keys.TrainEvalFeatures.TIMES] + if not times_feature.get_shape().is_compatible_with([None, None]): + raise ValueError( + ("Expected shape (batch dimension, window size) for feature '{}' " + "(got shape {})").format(feature_keys.TrainEvalFeatures.TIMES, + times_feature.get_shape())) + values_feature = features[feature_keys.TrainEvalFeatures.VALUES] + if not values_feature.get_shape().is_compatible_with( + [None, None, model.num_features]): + raise ValueError( + ("Expected shape (batch dimension, window size, {num_features}) " + "for feature '{feature_name}', since the model was configured " + "with num_features={num_features} (got shape {got_shape})").format( + num_features=model.num_features, + feature_name=feature_keys.TrainEvalFeatures.VALUES, + got_shape=times_feature.get_shape())) + _check_feature_shapes_compatible_with( + features=features, + compatible_with_name=feature_keys.TrainEvalFeatures.TIMES, + compatible_with_value=times_feature, + ignore=set([ + feature_keys.State.STATE_TUPLE # Model-dependent shapes + ])) + + +def _identity_metric_single(name, input_tensor): + """A metric which takes on its last updated value. + + This keeps evaluation metrics in sync with one another, since update ops are + run separately from their result Tensors. Simply returning (input_tensor, + no_op) as a metric with a value but no update means that a metric will come + from a different batch of data than metrics which cache values in a Variable + (e.g. the default loss metric). + + Args: + name: A name for the metric. + input_tensor: Any Tensor. + + Returns: + A tuple of (value, update_op). + """ + metric_variable = tf.compat.v1.Variable( + name="{}_identity_metric".format(name), + initial_value=tf.zeros([], dtype=input_tensor.dtype), + collections=[tf.compat.v1.GraphKeys.LOCAL_VARIABLES], + validate_shape=False) + update_op = tf.compat.v1.assign( + metric_variable, input_tensor, validate_shape=False) + # This shape will be correct once the first update runs (but may be + # incomplete, so is not helpful for initializing the variable). + metric_variable.set_shape(input_tensor.get_shape()) + return (metric_variable.value(), update_op) + + +def _identity_metric_nested(name, input_tensors): + """Create identity metrics for a nested tuple of Tensors.""" + update_ops = [] + value_tensors = [] + for tensor_number, tensor in enumerate(tf.nest.flatten(input_tensors)): + value_tensor, update_op = _identity_metric_single( + name="{}_{}".format(name, tensor_number), input_tensor=tensor) + update_ops.append(update_op) + value_tensors.append(value_tensor) + return (tf.nest.pack_sequence_as(input_tensors, value_tensors), + tf.group(*update_ops)) + + +def state_to_dictionary(state_tuple): + """Flatten model state into a dictionary with string keys.""" + flattened = {} + for state_number, state_value in enumerate(tf.nest.flatten(state_tuple)): + prefixed_state_name = "{}_{:02d}".format(feature_keys.State.STATE_PREFIX, + state_number) + flattened[prefixed_state_name] = state_value + return flattened diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/timeseries/math_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/timeseries/math_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..3e92a76b6099d81a14fca03f730f21f7b0f61445 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/timeseries/math_utils.py @@ -0,0 +1,400 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Miscellaneous utilities used by time series models.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import collections +import tensorflow as tf +from tensorflow.python.ops import gen_math_ops +from tensorflow_estimator.python.estimator.canned.timeseries.feature_keys import TrainEvalFeatures + + +def replicate_state(start_state, batch_size): + """Create batch versions of state. + + Takes a list of Tensors, adds a batch dimension, and replicates + batch_size times across that batch dimension. Used to replicate the + non-batch state returned by get_start_state in define_loss. + + Args: + start_state: Model-defined state to replicate. + batch_size: Batch dimension for data. + + Returns: + Replicated versions of the state. + """ + flattened_state = tf.nest.flatten(start_state) + replicated_state = [ + tf.tile( + tf.compat.v1.expand_dims(state_nonbatch, 0), + tf.concat([[batch_size], + tf.ones([tf.rank(state_nonbatch)], dtype=tf.dtypes.int32)], + 0)) for state_nonbatch in flattened_state + ] + return tf.nest.pack_sequence_as(start_state, replicated_state) + + +Moments = collections.namedtuple("Moments", ["mean", "variance"]) + +# Currently all of these statistics are computed incrementally (i.e. are updated +# every time a new mini-batch of training data is presented) when this object is +# created in InputStatisticsFromMiniBatch. +InputStatistics = collections.namedtuple( + "InputStatistics", + [ + # The mean and variance of each feature in a chunk (with a size + # configured in the statistics object) at the start of the series. A + # tuple of (mean, variance), each with shape [number of features], + # floating point. One use is in state space models, to keep priors + # calibrated even as earlier parts of the series are presented. If this + # object was created by InputStatisticsFromMiniBatch, these moments are + # computed based on the earliest chunk of data presented so far. + # However, there is a race condition in the update, so these may reflect + # statistics later in the series, but should eventually reflect + # statistics in a chunk at the series start. + "series_start_moments", + # The mean and variance of each feature over the entire series. A tuple + # of (mean, variance), each with shape [number of features]. If this + # object was created by InputStatisticsFromMiniBatch, these moments are + # estimates based on the data seen so far. + "overall_feature_moments", + # The first (lowest) time in the series, a scalar integer. If this + # object was created by InputStatisticsFromMiniBatch, this is the lowest + # time seen so far rather than the lowest time that will ever be seen + # (guaranteed to be at least as low as the lowest time presented in the + # current minibatch). + "start_time", + # Count of data points, a scalar integer. If this object was created by + # InputStatisticsFromMiniBatch, this is an estimate of the total number + # of observations in the whole dataset computed based on the density of + # the series and the minimum and maximum times seen. + "total_observation_count", + ]) + + +# TODO(allenl): It would be nice to do something with full series statistics +# when the user provides that. +class InputStatisticsFromMiniBatch(object): + """Generate statistics from mini-batch input.""" + + def __init__(self, num_features, dtype, starting_variance_window_size=16): + """Configure the input statistics object. + + Args: + num_features: Number of features for the time series + dtype: The floating point data type to use. + starting_variance_window_size: The number of datapoints to use when + computing the mean and variance at the start of the series. + """ + self._starting_variance_window_size = starting_variance_window_size + self._num_features = num_features + self._dtype = dtype + + def initialize_graph(self, features, update_statistics=True): + """Create any ops needed to provide input statistics. + + Should be called before statistics are requested. + + Args: + features: A dictionary, the output of a `TimeSeriesInputFn` (with keys + TrainEvalFeatures.TIMES and TrainEvalFeatures.VALUES). + update_statistics: Whether `features` should be used to update adaptive + statistics. Typically True for training and false for evaluation. + + Returns: + An InputStatistics object composed of Variables, which will be updated + based on mini-batches of data if requested. + """ + if (TrainEvalFeatures.TIMES in features and + TrainEvalFeatures.VALUES in features): + times = features[TrainEvalFeatures.TIMES] + values = features[TrainEvalFeatures.VALUES] + else: + # times and values may not be available, for example during prediction. We + # still need to retrieve our variables so that they can be read from, even + # if we're not going to update them. + times = None + values = None + # Create/retrieve variables representing input statistics, initialized + # without data to avoid deadlocking if variables are initialized before + # queue runners are started. + with tf.compat.v1.variable_scope("input_statistics", use_resource=True): + statistics = self._create_variable_statistics_object() + with tf.compat.v1.variable_scope( + "input_statistics_auxiliary", use_resource=True): + # Secondary statistics, necessary for the incremental computation of the + # primary statistics (e.g. counts and sums for computing a mean + # incrementally). + auxiliary_variables = self._AdaptiveInputAuxiliaryStatistics( + num_features=self._num_features, dtype=self._dtype) + if update_statistics and times is not None and values is not None: + # If we have times and values from mini-batch input, create update ops to + # take the new data into account. + assign_op = self._update_statistics_from_mini_batch( + statistics, auxiliary_variables, times, values) + with tf.control_dependencies([assign_op]): + stat_variables = tf.nest.pack_sequence_as( + statistics, + [tf.identity(tensor) for tensor in tf.nest.flatten(statistics)]) + # Since start time updates have a race condition, ensure that the + # reported start time is at least as low as the lowest time in this + # mini-batch. The start time should converge on the correct value + # eventually even with the race condition, but for example state space + # models have an assertion which could fail without this + # post-processing. + min_time = tf.cast(tf.math.reduce_min(times), tf.dtypes.int64) + start_time = tf.math.minimum(stat_variables.start_time, min_time) + return stat_variables._replace(start_time=start_time) + else: + return statistics + + class _AdaptiveInputAuxiliaryStatistics( + collections.namedtuple( + "_AdaptiveInputAuxiliaryStatistics", + [ + # The maximum time seen (best effort if updated from multiple + # workers; see notes about race condition below). + "max_time_seen", + # The number of chunks seen. + "chunk_count", + # The sum across chunks of their "time density" (number of times + # per example). + "inter_observation_duration_sum", + # The number of examples seen (each example has a single time + # associated with it and one or more real-valued features). + "example_count", + # The sum of values for each feature. Shape [number of features]. + "overall_feature_sum", + # The sum of squared values for each feature. + # Shape [number of features]. + "overall_feature_sum_of_squares", + ])): + """Extra statistics used to incrementally update InputStatistics.""" + + def __new__(cls, num_features, dtype): + return super( + InputStatisticsFromMiniBatch # pylint: disable=protected-access + ._AdaptiveInputAuxiliaryStatistics, + cls).__new__( + cls, + max_time_seen=tf.compat.v1.get_variable( + name="max_time_seen", + initializer=tf.dtypes.int64.min, + dtype=tf.dtypes.int64, + trainable=False), + chunk_count=tf.compat.v1.get_variable( + name="chunk_count", + initializer=tf.compat.v1.initializers.zeros(), + shape=[], + dtype=tf.dtypes.int64, + trainable=False), + inter_observation_duration_sum=tf.compat.v1.get_variable( + name="inter_observation_duration_sum", + initializer=tf.compat.v1.initializers.zeros(), + shape=[], + dtype=dtype, + trainable=False), + example_count=tf.compat.v1.get_variable( + name="example_count", + shape=[], + dtype=tf.dtypes.int64, + trainable=False), + overall_feature_sum=tf.compat.v1.get_variable( + name="overall_feature_sum", + shape=[num_features], + dtype=dtype, + initializer=tf.compat.v1.initializers.zeros(), + trainable=False), + overall_feature_sum_of_squares=tf.compat.v1.get_variable( + name="overall_feature_sum_of_squares", + shape=[num_features], + dtype=dtype, + initializer=tf.compat.v1.initializers.zeros(), + trainable=False)) + + def _update_statistics_from_mini_batch(self, statistics, auxiliary_variables, + times, values): + """Given mini-batch input, update `statistics` and `auxiliary_variables`.""" + values = tf.cast(values, self._dtype) + # The density (measured in times per observation) that we see in each part + # of the mini-batch. + batch_inter_observation_duration = ( + tf.cast( + tf.math.reduce_max(times, axis=1) - + tf.math.reduce_min(times, axis=1), self._dtype) / + tf.cast(tf.compat.v1.shape(times)[1] - 1, self._dtype)) + # Co-locate updates with their variables to minimize race conditions when + # updating statistics. + with tf.compat.v1.device(auxiliary_variables.max_time_seen.device): + # There is a race condition if this value is being updated from multiple + # workers. However, it should eventually reach the correct value if the + # last chunk is presented enough times. + latest_time = tf.cast(tf.math.reduce_max(times), tf.dtypes.int64) + max_time_seen = tf.math.maximum(auxiliary_variables.max_time_seen, + latest_time) + max_time_seen_assign = tf.compat.v1.assign( + auxiliary_variables.max_time_seen, max_time_seen) + with tf.compat.v1.device(auxiliary_variables.chunk_count.device): + chunk_count_assign = tf.compat.v1.assign_add( + auxiliary_variables.chunk_count, + tf.compat.v1.shape(times, out_type=tf.dtypes.int64)[0]) + with tf.compat.v1.device( + auxiliary_variables.inter_observation_duration_sum.device): + inter_observation_duration_assign = tf.compat.v1.assign_add( + auxiliary_variables.inter_observation_duration_sum, + tf.math.reduce_sum(batch_inter_observation_duration)) + with tf.compat.v1.device(auxiliary_variables.example_count.device): + example_count_assign = tf.compat.v1.assign_add( + auxiliary_variables.example_count, + tf.compat.v1.size(times, out_type=tf.dtypes.int64)) + # Note: These mean/variance updates assume that all points are equally + # likely, which is not true if _chunks_ are sampled uniformly from the space + # of all possible contiguous chunks, since points at the start and end of + # the series are then members of fewer chunks. For series which are much + # longer than the chunk size (the usual/expected case), this effect becomes + # irrelevant. + with tf.compat.v1.device(auxiliary_variables.overall_feature_sum.device): + overall_feature_sum_assign = tf.compat.v1.assign_add( + auxiliary_variables.overall_feature_sum, + tf.math.reduce_sum(values, axis=[0, 1])) + with tf.compat.v1.device( + auxiliary_variables.overall_feature_sum_of_squares.device): + overall_feature_sum_of_squares_assign = tf.compat.v1.assign_add( + auxiliary_variables.overall_feature_sum_of_squares, + tf.math.reduce_sum(values**2, axis=[0, 1])) + per_chunk_aux_updates = tf.group(max_time_seen_assign, chunk_count_assign, + inter_observation_duration_assign, + example_count_assign, + overall_feature_sum_assign, + overall_feature_sum_of_squares_assign) + with tf.control_dependencies([per_chunk_aux_updates]): + example_count_float = tf.cast(auxiliary_variables.example_count, + self._dtype) + new_feature_mean = ( + auxiliary_variables.overall_feature_sum / example_count_float) + overall_feature_mean_update = tf.compat.v1.assign( + statistics.overall_feature_moments.mean, new_feature_mean) + overall_feature_var_update = tf.compat.v1.assign( + statistics.overall_feature_moments.variance, + # De-biased n / (n - 1) variance correction + example_count_float / (example_count_float - 1.) * + (auxiliary_variables.overall_feature_sum_of_squares / + example_count_float - new_feature_mean**2)) + # TODO(b/35675805): Remove this cast + min_time_batch = tf.cast( + tf.compat.v1.math.argmin(times[:, 0]), tf.dtypes.int32) + + def series_start_updates(): + # If this is the lowest-time chunk that we have seen so far, update + # series start moments to reflect that. Note that these statistics are + # "best effort", as there are race conditions in the update (however, + # they should eventually converge if the start of the series is + # presented enough times). + mean, variance = tf.compat.v1.nn.moments( + values[min_time_batch, :self._starting_variance_window_size], + axes=[0]) + return tf.group( + tf.compat.v1.assign(statistics.series_start_moments.mean, mean), + tf.compat.v1.assign(statistics.series_start_moments.variance, + variance)) + + with tf.compat.v1.device(statistics.start_time.device): + series_start_update = tf.compat.v1.cond( + # Update moments whenever we even match the lowest time seen so far, + # to ensure that series start statistics are eventually updated to + # their correct values, despite race conditions (i.e. eventually + # statistics.start_time will reflect the global lowest time, and + # given that we will eventually update the series start moments to + # their correct values). + tf.math.less_equal(times[min_time_batch, 0], + tf.cast(statistics.start_time, times.dtype)), + series_start_updates, + tf.no_op) + with tf.control_dependencies([series_start_update]): + # There is a race condition if this update is performed in parallel on + # multiple workers. Since models may be sensitive to being presented + # with times before the putative start time, the value of this + # variable is post-processed above to guarantee that each worker is + # presented with a start time which is at least as low as the lowest + # time in its current mini-batch. + min_time = tf.cast(tf.math.reduce_min(times), tf.dtypes.int64) + start_time = tf.math.minimum(statistics.start_time, min_time) + start_time_update = tf.compat.v1.assign(statistics.start_time, + start_time) + inter_observation_duration_estimate = ( + auxiliary_variables.inter_observation_duration_sum / + tf.cast(auxiliary_variables.chunk_count, self._dtype)) + # Estimate the total number of observations as: + # (end time - start time + 1) * average intra-chunk time density + total_observation_count_update = tf.compat.v1.assign( + statistics.total_observation_count, + tf.cast( + gen_math_ops.round( + tf.cast(max_time_seen_assign - start_time_update + 1, + self._dtype) / inter_observation_duration_estimate), + tf.dtypes.int64)) + per_chunk_stat_updates = tf.group(overall_feature_mean_update, + overall_feature_var_update, + series_start_update, start_time_update, + total_observation_count_update) + return per_chunk_stat_updates + + def _create_variable_statistics_object(self): + """Creates non-trainable variables representing input statistics.""" + series_start_moments = Moments( + mean=tf.compat.v1.get_variable( + name="series_start_mean", + shape=[self._num_features], + dtype=self._dtype, + initializer=tf.compat.v1.initializers.zeros(), + trainable=False), + variance=tf.compat.v1.get_variable( + name="series_start_variance", + shape=[self._num_features], + dtype=self._dtype, + initializer=tf.compat.v1.initializers.ones(), + trainable=False)) + overall_feature_moments = Moments( + mean=tf.compat.v1.get_variable( + name="overall_feature_mean", + shape=[self._num_features], + dtype=self._dtype, + initializer=tf.compat.v1.initializers.zeros(), + trainable=False), + variance=tf.compat.v1.get_variable( + name="overall_feature_var", + shape=[self._num_features], + dtype=self._dtype, + initializer=tf.compat.v1.initializers.ones(), + trainable=False)) + start_time = tf.compat.v1.get_variable( + name="start_time", + dtype=tf.dtypes.int64, + initializer=tf.dtypes.int64.max, + trainable=False) + total_observation_count = tf.compat.v1.get_variable( + name="total_observation_count", + shape=[], + dtype=tf.dtypes.int64, + initializer=tf.compat.v1.initializers.ones(), + trainable=False) + return InputStatistics( + series_start_moments=series_start_moments, + overall_feature_moments=overall_feature_moments, + start_time=start_time, + total_observation_count=total_observation_count) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/timeseries/model.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/timeseries/model.py new file mode 100644 index 0000000000000000000000000000000000000000..7217e09259bf488ebe91e353d31076048ae9800e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/timeseries/model.py @@ -0,0 +1,333 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Base class for time series models.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import abc +import collections + +import six +import tensorflow as tf +from tensorflow_estimator.python.estimator.canned.timeseries import math_utils +from tensorflow_estimator.python.estimator.canned.timeseries.feature_keys import TrainEvalFeatures + +ModelOutputs = collections.namedtuple( # pylint: disable=invalid-name + typename="ModelOutputs", + field_names=[ + "loss", # The scalar value to be minimized during training. + "end_state", # A nested tuple specifying the model's state after + # running on the specified data + "predictions", # A dictionary of predictions, each with shape prefixed + # by the shape of `prediction_times`. + "prediction_times" # A [batch size x window size] integer Tensor + # indicating times for which values in `predictions` + # were computed. + ]) + + +@six.add_metaclass(abc.ABCMeta) +class TimeSeriesModel(object): + """Base class for creating generative time series models.""" + + def __init__(self, + num_features, + exogenous_feature_columns=None, + dtype=tf.dtypes.float32): + """Constructor for generative models. + + Args: + num_features: Number of features for the time series + exogenous_feature_columns: A list of `tf.feature_column`s (for example + `tf.feature_column.embedding_column`) corresponding to exogenous + features which provide extra information to the model but are not part + of the series to be predicted. Passed to + `tf.feature_column.input_layer`. + dtype: The floating point datatype to use. + """ + if exogenous_feature_columns: + self._exogenous_feature_columns = exogenous_feature_columns + else: + self._exogenous_feature_columns = [] + self.num_features = num_features + self.dtype = dtype + self._input_statistics = None + self._graph_initialized = False + self._stats_means = None + self._stats_sigmas = None + + @property + def exogenous_feature_columns(self): + """`tf.feature_colum`s for features which are not predicted.""" + return self._exogenous_feature_columns + + # TODO(allenl): Move more of the generic machinery for generating and + # predicting into TimeSeriesModel, and possibly share it between generate() + # and predict() + def generate(self, + number_of_series, + series_length, + model_parameters=None, + seed=None): + """Sample synthetic data from model parameters, with optional substitutions. + + Returns `number_of_series` possible sequences of future values, sampled from + the generative model with each conditioned on the previous. Samples are + based on trained parameters, except for those parameters explicitly + overridden in `model_parameters`. + + For distributions over future observations, see predict(). + + Args: + number_of_series: Number of time series to create. + series_length: Length of each time series. + model_parameters: A dictionary mapping model parameters to values, which + replace trained parameters when generating data. + seed: If specified, return deterministic time series according to this + value. + + Returns: + A dictionary with keys TrainEvalFeatures.TIMES (mapping to an array with + shape [number_of_series, series_length]) and TrainEvalFeatures.VALUES + (mapping to an array with shape [number_of_series, series_length, + num_features]). + """ + raise NotImplementedError("This model does not support generation.") + + def initialize_graph(self, input_statistics=None): + """Define ops for the model, not depending on any previously defined ops. + + Args: + input_statistics: A math_utils.InputStatistics object containing input + statistics. If None, data-independent defaults are used, which may + result in longer or unstable training. + """ + self._graph_initialized = True + self._input_statistics = input_statistics + if self._input_statistics: + self._stats_means, variances = ( + self._input_statistics.overall_feature_moments) + self._stats_sigmas = tf.math.sqrt(variances) + + def _scale_data(self, data): + """Scale data according to stats (input scale -> model scale).""" + if self._input_statistics is not None: + return (data - self._stats_means) / self._stats_sigmas + else: + return data + + def _scale_variance(self, variance): + """Scale variances according to stats (input scale -> model scale).""" + if self._input_statistics is not None: + return variance / self._input_statistics.overall_feature_moments.variance + else: + return variance + + def _scale_back_data(self, data): + """Scale back data according to stats (model scale -> input scale).""" + if self._input_statistics is not None: + return (data * self._stats_sigmas) + self._stats_means + else: + return data + + def _scale_back_variance(self, variance): + """Scale back variances according to stats (model scale -> input scale).""" + if self._input_statistics is not None: + return variance * self._input_statistics.overall_feature_moments.variance + else: + return variance + + def _check_graph_initialized(self): + if not self._graph_initialized: + raise ValueError( + "TimeSeriesModels require initialize_graph() to be called before " + "use. This defines variables and ops in the default graph, and " + "allows Tensor-valued input statistics to be specified.") + + def define_loss(self, features, mode): + """Default loss definition with state replicated across a batch. + + Time series passed to this model have a batch dimension, and each series in + a batch can be operated on in parallel. This loss definition assumes that + each element of the batch represents an independent sample conditioned on + the same initial state (i.e. it is simply replicated across the batch). A + batch size of one provides sequential operations on a single time series. + + More complex processing may operate instead on get_start_state() and + get_batch_loss() directly. + + Args: + features: A dictionary (such as is produced by a chunker) with at minimum + the following key/value pairs (others corresponding to the + `exogenous_feature_columns` argument to `__init__` may be included + representing exogenous regressors): + TrainEvalFeatures.TIMES: A [batch size x window size] integer Tensor + with times for each observation. If there is no artificial chunking, + the window size is simply the length of the time series. + TrainEvalFeatures.VALUES: A [batch size x window size x num features] + Tensor with values for each observation. + mode: The tf.estimator.ModeKeys mode to use (TRAIN, EVAL). For INFER, see + predict(). + + Returns: + A ModelOutputs object. + """ + self._check_graph_initialized() + start_state = math_utils.replicate_state( + start_state=self.get_start_state(), + batch_size=tf.compat.v1.shape(features[TrainEvalFeatures.TIMES])[0]) + return self.get_batch_loss(features=features, mode=mode, state=start_state) + + # TODO(vitalyk,allenl): Better documentation surrounding options for chunking, + # references to papers, etc. + @abc.abstractmethod + def get_start_state(self): + """Returns a tuple of state for the start of the time series. + + For example, a mean and covariance. State should not have a batch + dimension, and will often be TensorFlow Variables to be learned along with + the rest of the model parameters. + """ + pass + + @abc.abstractmethod + def get_batch_loss(self, features, mode, state): + """Return predictions, losses, and end state for a time series. + + Args: + features: A dictionary with times, values, and (optionally) exogenous + regressors. See `define_loss`. + mode: The tf.estimator.ModeKeys mode to use (TRAIN, EVAL, INFER). + state: Model-dependent state, each with size [batch size x ...]. The + number and type will typically be fixed by the model (for example a mean + and variance). + + Returns: + A ModelOutputs object. + """ + pass + + @abc.abstractmethod + def predict(self, features): + """Returns predictions of future observations given an initial state. + + Computes distributions for future observations. For sampled draws from the + model where each is conditioned on the previous, see generate(). + + Args: + features: A dictionary with at minimum the following key/value pairs + (others corresponding to the `exogenous_feature_columns` argument to + `__init__` may be included representing exogenous regressors): + PredictionFeatures.TIMES: A [batch size x window size] Tensor with times + to make predictions for. Times must be increasing within each part of + the batch, and must be greater than the last time `state` was updated. + PredictionFeatures.STATE_TUPLE: Model-dependent state, each with size + [batch size x ...]. The number and type will typically be fixed by the + model (for example a mean and variance). Typically these will be the + end state returned by get_batch_loss, predicting beyond that data. + + Returns: + A dictionary with model-dependent predictions corresponding to the + requested times. Keys indicate the type of prediction, and values have + shape [batch size x window size x ...]. For example state space models + return a "predicted_mean" and "predicted_covariance". + """ + pass + + def _get_exogenous_embedding_shape(self): + """Computes the shape of the vector returned by _process_exogenous_features. + + Returns: + The shape as a list. Does not include a batch dimension. + """ + if not self._exogenous_feature_columns: + return (0,) + with tf.Graph().as_default(): + parsed_features = ( + tf.compat.v1.feature_column.make_parse_example_spec( + self._exogenous_feature_columns)) + placeholder_features = tf.compat.v1.io.parse_example( + serialized=tf.compat.v1.placeholder( + shape=[None], dtype=tf.dtypes.string), + features=parsed_features) + embedded = tf.compat.v1.feature_column.input_layer( + features=placeholder_features, + feature_columns=self._exogenous_feature_columns) + return embedded.get_shape().as_list()[1:] + + def _process_exogenous_features(self, times, features): + """Create a single vector from exogenous features. + + Args: + times: A [batch size, window size] vector of times for this batch, + primarily used to check the shape information of exogenous features. + features: A dictionary of exogenous features corresponding to the columns + in self._exogenous_feature_columns. Each value should have a shape + prefixed by [batch size, window size]. + + Returns: + A Tensor with shape [batch size, window size, exogenous dimension], where + the size of the exogenous dimension depends on the exogenous feature + columns passed to the model's constructor. + Raises: + ValueError: If an exogenous feature has an unknown rank. + """ + if self._exogenous_feature_columns: + exogenous_features_single_batch_dimension = {} + for name, tensor in features.items(): + if tensor.get_shape().ndims is None: + # input_from_feature_columns does not support completely unknown + # feature shapes, so we save on a bit of logic and provide a better + # error message by checking that here. + raise ValueError( + ("Features with unknown rank are not supported. Got shape {} for " + "feature {}.").format(tensor.get_shape(), name)) + tensor_shape_dynamic = tf.compat.v1.shape(tensor) + tensor = tf.reshape( + tensor, + tf.concat([[tensor_shape_dynamic[0] * tensor_shape_dynamic[1]], + tensor_shape_dynamic[2:]], + axis=0)) + # Avoid shape warnings when embedding "scalar" exogenous features (those + # with only batch and window dimensions); input_from_feature_columns + # expects input ranks to match the embedded rank. + if tensor.get_shape().ndims == 1 and tensor.dtype != tf.dtypes.string: + exogenous_features_single_batch_dimension[name] = tensor[:, None] + else: + exogenous_features_single_batch_dimension[name] = tensor + embedded_exogenous_features_single_batch_dimension = ( + tf.compat.v1.feature_column.input_layer( + features=exogenous_features_single_batch_dimension, + feature_columns=self._exogenous_feature_columns, + trainable=True)) + exogenous_regressors = tf.reshape( + embedded_exogenous_features_single_batch_dimension, + tf.concat([ + tf.compat.v1.shape(times), + tf.compat.v1.shape( + embedded_exogenous_features_single_batch_dimension)[1:] + ], + axis=0)) + exogenous_regressors.set_shape(times.get_shape().concatenate( + embedded_exogenous_features_single_batch_dimension.get_shape()[1:])) + exogenous_regressors = tf.cast(exogenous_regressors, dtype=self.dtype) + else: + # Not having any exogenous features is a special case so that models can + # avoid superfluous updates, which may not be free of side effects due to + # bias terms in transformations. + exogenous_regressors = None + return exogenous_regressors diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/timeseries/model_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/timeseries/model_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..8ad20c9cfd5747040ea8552b45b0e120f226000e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/timeseries/model_utils.py @@ -0,0 +1,76 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Helper functions for training and constructing time series Models.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import numpy +import tensorflow as tf +from tensorflow_estimator.python.estimator.canned.timeseries import feature_keys + + +# TODO(agarwal): Remove and replace with functionality from tf.slim +def fully_connected(inp, + inp_size, + layer_size, + name, + activation=tf.nn.relu, + dtype=tf.dtypes.float32): + """Helper method to create a fully connected hidden layer.""" + wt = tf.compat.v1.get_variable( + name="{}_weight".format(name), shape=[inp_size, layer_size], dtype=dtype) + bias = tf.compat.v1.get_variable( + name="{}_bias".format(name), + shape=[layer_size], + initializer=tf.compat.v1.initializers.zeros()) + output = tf.compat.v1.nn.xw_plus_b(inp, wt, bias) + if activation is not None: + assert callable(activation) + output = activation(output) + return output + + +def canonicalize_times_or_steps_from_output(times, steps, + previous_model_output): + """Canonicalizes either relative or absolute times, with error checking.""" + if steps is not None and times is not None: + raise ValueError("Only one of `steps` and `times` may be specified.") + if steps is None and times is None: + raise ValueError("One of `steps` and `times` must be specified.") + if times is not None: + times = numpy.array(times) + if len(times.shape) != 2: + times = times[None, ...] + if (previous_model_output[feature_keys.FilteringResults.TIMES].shape[0] != + times.shape[0]): + raise ValueError( + ("`times` must have a batch dimension matching" + " the previous model output (got a batch dimension of {} for `times`" + " and {} for the previous model output).").format( + times.shape[0], previous_model_output[ + feature_keys.FilteringResults.TIMES].shape[0])) + if not (previous_model_output[feature_keys.FilteringResults.TIMES][:, -1] < + times[:, 0]).all(): + raise ValueError("Prediction times must be after the corresponding " + "previous model output.") + if steps is not None: + predict_times = ( + previous_model_output[feature_keys.FilteringResults.TIMES][:, -1:] + 1 + + numpy.arange(steps)[None, ...]) + else: + predict_times = times + return predict_times diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/timeseries/saved_model_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/timeseries/saved_model_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..165735079a51c31db7ce4499c4b9dbb8cb849432 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/timeseries/saved_model_utils.py @@ -0,0 +1,299 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Convenience functions for working with time series saved_models. + +@@predict_continuation +@@cold_start_filter +@@filter_continuation +""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import numpy + +from tensorflow.python.util.all_util import remove_undocumented +from tensorflow_estimator.python.estimator.canned.timeseries import feature_keys as _feature_keys +from tensorflow_estimator.python.estimator.canned.timeseries import head as _head +from tensorflow_estimator.python.estimator.canned.timeseries import model_utils as _model_utils + + +def _canonicalize_numpy_data(data, require_single_batch): + """Do basic checking and reshaping for Numpy data. + + Args: + data: A dictionary mapping keys to Numpy arrays, with several possible + shapes (requires keys `TrainEvalFeatures.TIMES` and + `TrainEvalFeatures.VALUES`): Single example; `TIMES` is a scalar and + `VALUES` is either a scalar or a vector of length [number of features]. + Sequence; `TIMES` is a vector of shape [series length], `VALUES` either + has shape [series length] (univariate) or [series length x number of + features] (multivariate). Batch of sequences; `TIMES` is a vector of + shape [batch size x series length], `VALUES` has shape [batch size x + series length] or [batch size x series length x number of features]. In + any case, `VALUES` and any exogenous features must have their shapes + prefixed by the shape of the value corresponding to the `TIMES` key. + require_single_batch: If True, raises an error if the provided data has a + batch dimension > 1. + + Returns: + A dictionary with features normalized to have shapes prefixed with [batch + size x series length]. The sizes of dimensions which were omitted in the + inputs are 1. + Raises: + ValueError: If dimensions are incorrect or do not match, or required + features are missing. + """ + features = {key: numpy.array(value) for key, value in data.items()} + if (_feature_keys.TrainEvalFeatures.TIMES not in features or + _feature_keys.TrainEvalFeatures.VALUES not in features): + raise ValueError("{} and {} are required features.".format( + _feature_keys.TrainEvalFeatures.TIMES, + _feature_keys.TrainEvalFeatures.VALUES)) + times = features[_feature_keys.TrainEvalFeatures.TIMES] + for key, value in features.items(): + if value.shape[:len(times.shape)] != times.shape: + raise ValueError( + ("All features must have their shapes prefixed by the shape of the" + " times feature. Got shape {} for feature '{}', but shape {} for" + " '{}'").format(value.shape, key, times.shape, + _feature_keys.TrainEvalFeatures.TIMES)) + if not times.shape: # a single example + if not features[_feature_keys.TrainEvalFeatures.VALUES].shape: # univariate + # Add a feature dimension (with one feature) + features[_feature_keys.TrainEvalFeatures.VALUES] = features[ + _feature_keys.TrainEvalFeatures.VALUES][..., None] + elif len(features[_feature_keys.TrainEvalFeatures.VALUES].shape) > 1: + raise ValueError( + ("Got an unexpected number of dimensions for the '{}' feature." + " Was expecting at most 1 dimension" + " ([number of features]) since '{}' does not " + "have a batch or time dimension, but got shape {}").format( + _feature_keys.TrainEvalFeatures.VALUES, + _feature_keys.TrainEvalFeatures.TIMES, + features[_feature_keys.TrainEvalFeatures.VALUES].shape)) + # Add trivial batch and time dimensions for every feature + features = {key: value[None, None, ...] for key, value in features.items()} + if len(times.shape) == 1: # shape [series length] + if len(features[_feature_keys.TrainEvalFeatures.VALUES].shape + ) == 1: # shape [series length] + # Add a feature dimension (with one feature) + features[_feature_keys.TrainEvalFeatures.VALUES] = features[ + _feature_keys.TrainEvalFeatures.VALUES][..., None] + elif len(features[_feature_keys.TrainEvalFeatures.VALUES].shape) > 2: + raise ValueError( + ("Got an unexpected number of dimensions for the '{}' feature." + " Was expecting at most 2 dimensions" + " ([series length, number of features]) since '{}' does not " + "have a batch dimension, but got shape {}").format( + _feature_keys.TrainEvalFeatures.VALUES, + _feature_keys.TrainEvalFeatures.TIMES, + features[_feature_keys.TrainEvalFeatures.VALUES].shape)) + # Add trivial batch dimensions for every feature + features = {key: value[None, ...] for key, value in features.items()} + elif len(features[_feature_keys.TrainEvalFeatures.TIMES].shape + ) != 2: # shape [batch size, series length] + raise ValueError( + ("Got an unexpected number of dimensions for times. Was expecting at " + "most two ([batch size, series length]), but got shape {}.").format( + times.shape)) + if require_single_batch: + # We don't expect input to be already batched; batching is done later + if features[_feature_keys.TrainEvalFeatures.TIMES].shape[0] != 1: + raise ValueError("Got batch input, was expecting unbatched input.") + return features + + +def _colate_features_to_feeds_and_fetches(signature, + features, + graph, + continue_from=None): + """Uses a saved model signature to construct feed and fetch dictionaries.""" + if continue_from is None: + state_values = {} + elif _feature_keys.FilteringResults.STATE_TUPLE in continue_from: + # We're continuing from an evaluation, so we need to unpack/flatten state. + state_values = _head.state_to_dictionary( + continue_from[_feature_keys.FilteringResults.STATE_TUPLE]) + else: + state_values = continue_from + input_feed_tensors_by_name = { + input_key: graph.as_graph_element(input_value.name) + for input_key, input_value in signature.inputs.items() + } + output_tensors_by_name = { + output_key: graph.as_graph_element(output_value.name) + for output_key, output_value in signature.outputs.items() + } + feed_dict = {} + for state_key, state_value in state_values.items(): + feed_dict[input_feed_tensors_by_name[state_key]] = state_value + for feature_key, feature_value in features.items(): + feed_dict[input_feed_tensors_by_name[feature_key]] = feature_value + return output_tensors_by_name, feed_dict + + +def predict_continuation(continue_from, + signatures, + session, + steps=None, + times=None, + exogenous_features=None): + """Perform prediction using an exported saved model. + + Args: + continue_from: A dictionary containing the results of either an Estimator's + evaluate method or filter_continuation. Used to determine the model state + to make predictions starting from. + signatures: The `MetaGraphDef` protocol buffer returned from + `tf.saved_model.loader.load`. Used to determine the names of Tensors to + feed and fetch. Must be from the same model as `continue_from`. + session: The session to use. The session's graph must be the one into which + `tf.saved_model.loader.load` loaded the model. + steps: The number of steps to predict (scalar), starting after the + evaluation or filtering. If `times` is specified, `steps` must not be; one + is required. + times: A [batch_size x window_size] array of integers (not a Tensor) + indicating times to make predictions for. These times must be after the + corresponding evaluation or filtering. If `steps` is specified, `times` + must not be; one is required. If the batch dimension is omitted, it is + assumed to be 1. + exogenous_features: Optional dictionary. If specified, indicates exogenous + features for the model to use while making the predictions. Values must + have shape [batch_size x window_size x ...], where `batch_size` matches + the batch dimension used when creating `continue_from`, and `window_size` + is either the `steps` argument or the `window_size` of the `times` + argument (depending on which was specified). + + Returns: + A dictionary with model-specific predictions (typically having keys "mean" + and "covariance") and a _feature_keys.PredictionResults.TIMES key indicating + the times for which the predictions were computed. + Raises: + ValueError: If `times` or `steps` are misspecified. + """ + if exogenous_features is None: + exogenous_features = {} + predict_times = _model_utils.canonicalize_times_or_steps_from_output( + times=times, steps=steps, previous_model_output=continue_from) + features = {_feature_keys.PredictionFeatures.TIMES: predict_times} + features.update(exogenous_features) + predict_signature = signatures.signature_def[ + _feature_keys.SavedModelLabels.PREDICT] + output_tensors_by_name, feed_dict = _colate_features_to_feeds_and_fetches( + continue_from=continue_from, + signature=predict_signature, + features=features, + graph=session.graph) + output = session.run(output_tensors_by_name, feed_dict=feed_dict) + output[_feature_keys.PredictionResults.TIMES] = features[ + _feature_keys.PredictionFeatures.TIMES] + return output + + +def cold_start_filter(signatures, session, features): + """Perform filtering using an exported saved model. + + Filtering refers to updating model state based on new observations. + Predictions based on the returned model state will be conditioned on these + observations. + + Starts from the model's default/uninformed state. + + Args: + signatures: The `MetaGraphDef` protocol buffer returned from + `tf.saved_model.loader.load`. Used to determine the names of Tensors to + feed and fetch. Must be from the same model as `continue_from`. + session: The session to use. The session's graph must be the one into which + `tf.saved_model.loader.load` loaded the model. + features: A dictionary mapping keys to Numpy arrays, with several possible + shapes (requires keys `FilteringFeatures.TIMES` and + `FilteringFeatures.VALUES`): Single example; `TIMES` is a scalar and + `VALUES` is either a scalar or a vector of length [number of features]. + Sequence; `TIMES` is a vector of shape [series length], `VALUES` either + has shape [series length] (univariate) or [series length x number of + features] (multivariate). Batch of sequences; `TIMES` is a vector of + shape [batch size x series length], `VALUES` has shape [batch size x + series length] or [batch size x series length x number of features]. In + any case, `VALUES` and any exogenous features must have their shapes + prefixed by the shape of the value corresponding to the `TIMES` key. + + Returns: + A dictionary containing model state updated to account for the observations + in `features`. + """ + filter_signature = signatures.signature_def[ + _feature_keys.SavedModelLabels.COLD_START_FILTER] + features = _canonicalize_numpy_data(data=features, require_single_batch=False) + output_tensors_by_name, feed_dict = _colate_features_to_feeds_and_fetches( + signature=filter_signature, features=features, graph=session.graph) + output = session.run(output_tensors_by_name, feed_dict=feed_dict) + # Make it easier to chain filter -> predict by keeping track of the current + # time. + output[_feature_keys.FilteringResults.TIMES] = features[ + _feature_keys.FilteringFeatures.TIMES] + return output + + +def filter_continuation(continue_from, signatures, session, features): + """Perform filtering using an exported saved model. + + Filtering refers to updating model state based on new observations. + Predictions based on the returned model state will be conditioned on these + observations. + + Args: + continue_from: A dictionary containing the results of either an Estimator's + evaluate method or a previous filter step (cold start or continuation). + Used to determine the model state to start filtering from. + signatures: The `MetaGraphDef` protocol buffer returned from + `tf.saved_model.loader.load`. Used to determine the names of Tensors to + feed and fetch. Must be from the same model as `continue_from`. + session: The session to use. The session's graph must be the one into which + `tf.saved_model.loader.load` loaded the model. + features: A dictionary mapping keys to Numpy arrays, with several possible + shapes (requires keys `FilteringFeatures.TIMES` and + `FilteringFeatures.VALUES`): Single example; `TIMES` is a scalar and + `VALUES` is either a scalar or a vector of length [number of features]. + Sequence; `TIMES` is a vector of shape [series length], `VALUES` either + has shape [series length] (univariate) or [series length x number of + features] (multivariate). Batch of sequences; `TIMES` is a vector of + shape [batch size x series length], `VALUES` has shape [batch size x + series length] or [batch size x series length x number of features]. In + any case, `VALUES` and any exogenous features must have their shapes + prefixed by the shape of the value corresponding to the `TIMES` key. + + Returns: + A dictionary containing model state updated to account for the observations + in `features`. + """ + filter_signature = signatures.signature_def[ + _feature_keys.SavedModelLabels.FILTER] + features = _canonicalize_numpy_data(data=features, require_single_batch=False) + output_tensors_by_name, feed_dict = _colate_features_to_feeds_and_fetches( + continue_from=continue_from, + signature=filter_signature, + features=features, + graph=session.graph) + output = session.run(output_tensors_by_name, feed_dict=feed_dict) + # Make it easier to chain filter -> predict by keeping track of the current + # time. + output[_feature_keys.FilteringResults.TIMES] = features[ + _feature_keys.FilteringFeatures.TIMES] + return output + + +remove_undocumented(module_name=__name__) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/timeseries/state_management.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/timeseries/state_management.py new file mode 100644 index 0000000000000000000000000000000000000000..6cc08beae95e8c70ade5b8312bd53db76f732c6e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/timeseries/state_management.py @@ -0,0 +1,98 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Classes for wrapping a model to operate on different data shapes.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import abc +from tensorflow_estimator.python.estimator import estimator_lib +from tensorflow_estimator.python.estimator.canned.timeseries import feature_keys + + +class PassthroughStateManager(object): + """A minimal wrapper for models which do not need state management.""" + + def __init__(self): + self._input_statistics = None + self._graph_initialized = False + + def initialize_graph(self, model, input_statistics=None): + """Adds required operations to the graph.""" + del model # unused + self._graph_initialized = True + self._input_statistics = input_statistics + + def define_loss(self, model, features, mode): + """Wrap "model" with StateManager-specific operations. + + Args: + model: The model (inheriting from TimeSeriesModel) to manage state for. + features: A dictionary with the following key/value pairs: + feature_keys.TrainEvalFeatures.TIMES: A [batch size x window size] + Tensor with times for each observation. + feature_keys.TrainEvalFeatures.VALUES: A [batch size x window size x num + features] Tensor with values for each observation. + mode: The tf.estimator.ModeKeys mode to use (TRAIN or EVAL). + + Returns: + A ModelOutputs object. + Raises: + ValueError: If start state was specified. + """ + if feature_keys.State.STATE_TUPLE in features: + raise ValueError( + "Overriding start state is not supported for this model.") + return model.define_loss(features, mode) + + +class _OverridableStateManager(PassthroughStateManager): + """Base class for state managers which support overriding model state.""" + + @abc.abstractmethod + def _define_loss_with_saved_state(self, model, features, mode): + pass + + def define_loss(self, model, features, mode): + """Switches between explicit start state and managed state.""" + if feature_keys.FilteringFeatures.STATE_TUPLE in features: + # Explicit start state has been provided, so we should use that. + if mode == estimator_lib.ModeKeys.TRAIN: + raise ValueError( + "Overriding saved state for training is not supported (but a value " + "for feature {} was specified).".format( + feature_keys.FilteringFeatures.STATE_TUPLE)) + start_state = features[feature_keys.FilteringFeatures.STATE_TUPLE] + del features[feature_keys.FilteringFeatures.STATE_TUPLE] + return model.get_batch_loss( + features=features, mode=mode, state=start_state) + else: + # No explicit start state; use managed state. + return self._define_loss_with_saved_state( + model=model, features=features, mode=mode) + + +class FilteringOnlyStateManager(_OverridableStateManager): + """State manager for models which use state only for filtering. + + Window-based models (ARModel) do not require state to be fed during training + (instead requiring a specific window size). Rather than requiring a minimum + window size for filtering, these models maintain this window in their state, + and so need state to be fed. + """ + + def _define_loss_with_saved_state(self, model, features, mode): + return model.define_loss(features, mode) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/v1/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/v1/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/v1/dnn_testing_utils_v1.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/v1/dnn_testing_utils_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..7a1e64dc7c59a066ce0516dd01486c18c2ce638a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/v1/dnn_testing_utils_v1.py @@ -0,0 +1,2126 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Utils to be used in testing DNN estimators.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import os +import shutil +import tempfile + +import numpy as np +import six +import tensorflow as tf +from tensorflow.python.feature_column import feature_column +from tensorflow.python.framework import ops +from tensorflow_estimator.python.estimator import estimator +from tensorflow_estimator.python.estimator import model_fn +from tensorflow_estimator.python.estimator.canned import head as head_lib +from tensorflow_estimator.python.estimator.canned import metric_keys +from tensorflow_estimator.python.estimator.canned import prediction_keys +from tensorflow_estimator.python.estimator.inputs import numpy_io +from tensorflow_estimator.python.estimator.mode_keys import ModeKeys + +# pylint rules which are disabled by default for test files. +# pylint: disable=invalid-name,protected-access,missing-docstring + +# Names of variables created by model. +LEARNING_RATE_NAME = 'dnn/regression_head/dnn/learning_rate' +HIDDEN_WEIGHTS_NAME_PATTERN = 'dnn/hiddenlayer_%d/kernel' +HIDDEN_BIASES_NAME_PATTERN = 'dnn/hiddenlayer_%d/bias' +BATCH_NORM_BETA_NAME_PATTERN = 'dnn/hiddenlayer_%d/batchnorm_%d/beta' +BATCH_NORM_GAMMA_NAME_PATTERN = 'dnn/hiddenlayer_%d/batchnorm_%d/gamma' +BATCH_NORM_MEAN_NAME_PATTERN = 'dnn/hiddenlayer_%d/batchnorm_%d/moving_mean' +BATCH_NORM_VARIANCE_NAME_PATTERN = ( + 'dnn/hiddenlayer_%d/batchnorm_%d/moving_variance') +LOGITS_WEIGHTS_NAME = 'dnn/logits/kernel' +LOGITS_BIASES_NAME = 'dnn/logits/bias' +OCCUPATION_EMBEDDING_NAME = ('dnn/input_from_feature_columns/input_layer/' + 'occupation_embedding/embedding_weights') +CITY_EMBEDDING_NAME = ('dnn/input_from_feature_columns/input_layer/' + 'city_embedding/embedding_weights') + +# This is so that we can easily switch between feature_column and +# feature_column_v2 for testing. +feature_column.numeric_column = feature_column._numeric_column +feature_column.categorical_column_with_hash_bucket = feature_column._categorical_column_with_hash_bucket # pylint: disable=line-too-long +feature_column.categorical_column_with_vocabulary_list = feature_column._categorical_column_with_vocabulary_list # pylint: disable=line-too-long +feature_column.categorical_column_with_vocabulary_file = feature_column._categorical_column_with_vocabulary_file # pylint: disable=line-too-long +feature_column.embedding_column = feature_column._embedding_column + + +def assert_close(expected, actual, rtol=1e-04, message='', name='assert_close'): + with ops.name_scope(name, 'assert_close', (expected, actual, rtol)) as scope: + expected = ops.convert_to_tensor(expected, name='expected') + actual = ops.convert_to_tensor(actual, name='actual') + rdiff = tf.math.abs((expected - actual) / expected, 'diff') + rtol = ops.convert_to_tensor(rtol, name='rtol') + return tf.compat.v1.debugging.assert_less( + rdiff, + rtol, + data=(message, 'Condition expected =~ actual did not hold element-wise:' + 'expected = ', expected, 'actual = ', actual, 'rdiff = ', rdiff, + 'rtol = ', rtol,), + summarize=expected.get_shape().num_elements(), + name=scope) + + +def create_checkpoint(weights_and_biases, + global_step, + model_dir, + batch_norm_vars=None): + """Create checkpoint file with provided model weights. + + Args: + weights_and_biases: Iterable of tuples of weight and bias values. + global_step: Initial global step to save in checkpoint. + model_dir: Directory into which checkpoint is saved. + batch_norm_vars: Variables used for batch normalization. + """ + weights, biases = zip(*weights_and_biases) + if batch_norm_vars: + assert len(batch_norm_vars) == len(weights_and_biases) - 1 + (bn_betas, bn_gammas, bn_means, bn_variances) = zip(*batch_norm_vars) + model_weights = {} + + # Hidden layer weights. + for i in range(0, len(weights) - 1): + model_weights[HIDDEN_WEIGHTS_NAME_PATTERN % i] = weights[i] + model_weights[HIDDEN_BIASES_NAME_PATTERN % i] = biases[i] + if batch_norm_vars: + model_weights[BATCH_NORM_BETA_NAME_PATTERN % (i, i)] = bn_betas[i] + model_weights[BATCH_NORM_GAMMA_NAME_PATTERN % (i, i)] = bn_gammas[i] + model_weights[BATCH_NORM_MEAN_NAME_PATTERN % (i, i)] = bn_means[i] + model_weights[BATCH_NORM_VARIANCE_NAME_PATTERN % (i, i)] = bn_variances[i] + + # Output layer weights. + model_weights[LOGITS_WEIGHTS_NAME] = weights[-1] + model_weights[LOGITS_BIASES_NAME] = biases[-1] + + with tf.Graph().as_default(): + # Create model variables. + for k, v in six.iteritems(model_weights): + tf.Variable(v, name=k, dtype=tf.dtypes.float32) + + # Create non-model variables. + global_step_var = tf.compat.v1.train.create_global_step() + + # Initialize vars and save checkpoint. + with tf.compat.v1.Session() as sess: + tf.compat.v1.initializers.global_variables().run() + global_step_var.assign(global_step).eval() + tf.compat.v1.train.Saver().save(sess, + os.path.join(model_dir, 'model.ckpt')) + + +def mock_head(testcase, hidden_units, logits_dimension, expected_logits): + """Returns a mock head that validates logits values and variable names.""" + hidden_weights_names = [(HIDDEN_WEIGHTS_NAME_PATTERN + '/part_0:0') % i + for i in range(len(hidden_units))] + hidden_biases_names = [(HIDDEN_BIASES_NAME_PATTERN + '/part_0:0') % i + for i in range(len(hidden_units))] + expected_var_names = ( + hidden_weights_names + hidden_biases_names + + [LOGITS_WEIGHTS_NAME + '/part_0:0', LOGITS_BIASES_NAME + '/part_0:0']) + + def _create_tpu_estimator_spec(features, + mode, + logits, + labels, + train_op_fn=None, + optimizer=None): + del features, labels # Not used. + trainable_vars = tf.compat.v1.get_collection( + tf.compat.v1.GraphKeys.TRAINABLE_VARIABLES) + testcase.assertItemsEqual(expected_var_names, + [var.name for var in trainable_vars]) + loss = tf.constant(1.) + assert_logits = assert_close( + expected_logits, logits, message='Failed for mode={}. '.format(mode)) + with tf.control_dependencies([assert_logits]): + if mode == ModeKeys.TRAIN: + if train_op_fn is not None: + train_op = train_op_fn(loss) + elif optimizer is not None: + train_op = optimizer.minimize(loss, global_step=None) + return model_fn._TPUEstimatorSpec( + mode=mode, loss=loss, train_op=train_op) + elif mode == ModeKeys.EVAL: + return model_fn._TPUEstimatorSpec(mode=mode, loss=tf.identity(loss)) + elif mode == ModeKeys.PREDICT: + return model_fn._TPUEstimatorSpec( + mode=mode, predictions={'logits': tf.identity(logits)}) + else: + testcase.fail('Invalid mode: {}'.format(mode)) + + def _create_estimator_spec(features, + mode, + logits, + labels, + train_op_fn=None, + optimizer=None): + tpu_spec = _create_tpu_estimator_spec(features, mode, logits, labels, + train_op_fn, optimizer) + return tpu_spec.as_estimator_spec() + + head = tf.compat.v1.test.mock.NonCallableMagicMock(spec=head_lib._Head) + head.logits_dimension = logits_dimension + head._create_tpu_estimator_spec = tf.compat.v1.test.mock.MagicMock( + wraps=_create_tpu_estimator_spec) + head.create_estimator_spec = tf.compat.v1.test.mock.MagicMock( + wraps=_create_estimator_spec) + + return head + + +def mock_optimizer(testcase, hidden_units, expected_loss=None): + """Creates a mock optimizer to test the train method. + + Args: + testcase: A TestCase instance. + hidden_units: Iterable of integer sizes for the hidden layers. + expected_loss: If given, will assert the loss value. + + Returns: + A mock Optimizer. + """ + hidden_weights_names = [(HIDDEN_WEIGHTS_NAME_PATTERN + '/part_0:0') % i + for i in range(len(hidden_units))] + hidden_biases_names = [(HIDDEN_BIASES_NAME_PATTERN + '/part_0:0') % i + for i in range(len(hidden_units))] + expected_var_names = ( + hidden_weights_names + hidden_biases_names + + [LOGITS_WEIGHTS_NAME + '/part_0:0', LOGITS_BIASES_NAME + '/part_0:0']) + + def _minimize(loss, global_step=None, var_list=None): + """Mock of optimizer.minimize.""" + trainable_vars = var_list or tf.compat.v1.get_collection( + tf.compat.v1.GraphKeys.TRAINABLE_VARIABLES) + testcase.assertItemsEqual(expected_var_names, + [var.name for var in trainable_vars]) + + # Verify loss. We can't check the value directly, so we add an assert op. + testcase.assertEquals(0, loss.shape.ndims) + if expected_loss is None: + if global_step is not None: + return tf.compat.v1.assign_add(global_step, 1).op + return tf.no_op() + assert_loss = assert_close( + tf.cast(expected_loss, name='expected', dtype=tf.dtypes.float32), + loss, + name='assert_loss') + with tf.control_dependencies((assert_loss,)): + if global_step is not None: + return tf.compat.v1.assign_add(global_step, 1).op + return tf.no_op() + + optimizer_mock = tf.compat.v1.test.mock.NonCallableMagicMock( + spec=tf.compat.v1.train.Optimizer, + wraps=tf.compat.v1.train.Optimizer( + use_locking=False, name='my_optimizer')) + optimizer_mock.minimize = tf.compat.v1.test.mock.MagicMock(wraps=_minimize) + + return optimizer_mock + + +class BaseDNNModelFnTest(object): + """Tests that _dnn_model_fn passes expected logits to mock head.""" + + def __init__(self, dnn_model_fn, fc_impl=feature_column): + self._dnn_model_fn = dnn_model_fn + self._fc_impl = fc_impl + + def setUp(self): + self._model_dir = tempfile.mkdtemp() + + def tearDown(self): + if self._model_dir: + tf.compat.v1.summary.FileWriterCache.clear() + shutil.rmtree(self._model_dir) + + def _test_logits(self, mode, hidden_units, logits_dimension, inputs, + expected_logits): + """Tests that the expected logits are passed to mock head.""" + with tf.Graph().as_default(): + tf.compat.v1.train.create_global_step() + head = mock_head( + self, + hidden_units=hidden_units, + logits_dimension=logits_dimension, + expected_logits=expected_logits) + estimator_spec = self._dnn_model_fn( + features={'age': tf.constant(inputs)}, + labels=tf.constant([[1]]), + mode=mode, + head=head, + hidden_units=hidden_units, + feature_columns=[ + self._fc_impl.numeric_column( + 'age', shape=np.array(inputs).shape[1:]) + ], + optimizer=mock_optimizer(self, hidden_units)) + with tf.compat.v1.train.MonitoredTrainingSession( + checkpoint_dir=self._model_dir) as sess: + if mode == ModeKeys.TRAIN: + sess.run(estimator_spec.train_op) + elif mode == ModeKeys.EVAL: + sess.run(estimator_spec.loss) + elif mode == ModeKeys.PREDICT: + sess.run(estimator_spec.predictions) + else: + self.fail('Invalid mode: {}'.format(mode)) + + def test_one_dim_logits(self): + """Tests one-dimensional logits. + + input_layer = [[10]] + hidden_layer_0 = [[relu(0.6*10 +0.1), relu(0.5*10 -0.1)]] = [[6.1, 4.9]] + hidden_layer_1 = [[relu(1*6.1 -0.8*4.9 +0.2), relu(0.8*6.1 -1*4.9 -0.1)]] + = [[relu(2.38), relu(-0.12)]] = [[2.38, 0]] + logits = [[-1*2.38 +1*0 +0.3]] = [[-2.08]] + """ + base_global_step = 100 + create_checkpoint(( + ([[.6, .5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1.], [1.]], [.3]), + ), base_global_step, self._model_dir) + + for mode in [ModeKeys.TRAIN, ModeKeys.EVAL, ModeKeys.PREDICT]: + self._test_logits( + mode, + hidden_units=(2, 2), + logits_dimension=1, + inputs=[[10.]], + expected_logits=[[-2.08]]) + + def test_multi_dim_logits(self): + """Tests multi-dimensional logits. + + input_layer = [[10]] + hidden_layer_0 = [[relu(0.6*10 +0.1), relu(0.5*10 -0.1)]] = [[6.1, 4.9]] + hidden_layer_1 = [[relu(1*6.1 -0.8*4.9 +0.2), relu(0.8*6.1 -1*4.9 -0.1)]] + = [[relu(2.38), relu(-0.12)]] = [[2.38, 0]] + logits = [[-1*2.38 +0.3, 1*2.38 -0.3, 0.5*2.38]] + = [[-2.08, 2.08, 1.19]] + """ + base_global_step = 100 + create_checkpoint(( + ([[.6, .5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1., 1., .5], [-1., 1., .5]], [.3, -.3, .0]), + ), base_global_step, self._model_dir) + + for mode in [ModeKeys.TRAIN, ModeKeys.EVAL, ModeKeys.PREDICT]: + self._test_logits( + mode, + hidden_units=(2, 2), + logits_dimension=3, + inputs=[[10.]], + expected_logits=[[-2.08, 2.08, 1.19]]) + + def test_multi_example_multi_dim_logits(self): + """Tests multiple examples and multi-dimensional logits. + + input_layer = [[10], [5]] + hidden_layer_0 = [[relu(0.6*10 +0.1), relu(0.5*10 -0.1)], + [relu(0.6*5 +0.1), relu(0.5*5 -0.1)]] + = [[6.1, 4.9], [3.1, 2.4]] + hidden_layer_1 = [[relu(1*6.1 -0.8*4.9 +0.2), relu(0.8*6.1 -1*4.9 -0.1)], + [relu(1*3.1 -0.8*2.4 +0.2), relu(0.8*3.1 -1*2.4 -0.1)]] + = [[2.38, 0], [1.38, 0]] + logits = [[-1*2.38 +0.3, 1*2.38 -0.3, 0.5*2.38], + [-1*1.38 +0.3, 1*1.38 -0.3, 0.5*1.38]] + = [[-2.08, 2.08, 1.19], [-1.08, 1.08, 0.69]] + """ + base_global_step = 100 + create_checkpoint(( + ([[.6, .5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1., 1., .5], [-1., 1., .5]], [.3, -.3, .0]), + ), base_global_step, self._model_dir) + + for mode in [ModeKeys.TRAIN, ModeKeys.EVAL, ModeKeys.PREDICT]: + self._test_logits( + mode, + hidden_units=(2, 2), + logits_dimension=3, + inputs=[[10.], [5.]], + expected_logits=[[-2.08, 2.08, 1.19], [-1.08, 1.08, .69]]) + + def test_multi_dim_input_one_dim_logits(self): + """Tests multi-dimensional inputs and one-dimensional logits. + + input_layer = [[10, 8]] + hidden_layer_0 = [[relu(0.6*10 -0.6*8 +0.1), relu(0.5*10 -0.5*8 -0.1)]] + = [[1.3, 0.9]] + hidden_layer_1 = [[relu(1*1.3 -0.8*0.9 + 0.2), relu(0.8*1.3 -1*0.9 -0.2)]] + = [[0.78, relu(-0.06)]] = [[0.78, 0]] + logits = [[-1*0.78 +1*0 +0.3]] = [[-0.48]] + """ + base_global_step = 100 + create_checkpoint(( + ([[.6, .5], [-.6, -.5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1.], [1.]], [.3]), + ), base_global_step, self._model_dir) + + for mode in [ModeKeys.TRAIN, ModeKeys.EVAL, ModeKeys.PREDICT]: + self._test_logits( + mode, + hidden_units=(2, 2), + logits_dimension=1, + inputs=[[10., 8.]], + expected_logits=[[-0.48]]) + + def test_multi_dim_input_multi_dim_logits(self): + """Tests multi-dimensional inputs and multi-dimensional logits. + + input_layer = [[10, 8]] + hidden_layer_0 = [[relu(0.6*10 -0.6*8 +0.1), relu(0.5*10 -0.5*8 -0.1)]] + = [[1.3, 0.9]] + hidden_layer_1 = [[relu(1*1.3 -0.8*0.9 + 0.2), relu(0.8*1.3 -1*0.9 -0.2)]] + = [[0.78, relu(-0.06)]] = [[0.78, 0]] + logits = [[-1*0.78 + 0.3, 1*0.78 -0.3, 0.5*0.78]] = [[-0.48, 0.48, 0.39]] + """ + base_global_step = 100 + create_checkpoint(( + ([[.6, .5], [-.6, -.5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1., 1., .5], [-1., 1., .5]], [.3, -.3, .0]), + ), base_global_step, self._model_dir) + + for mode in [ModeKeys.TRAIN, ModeKeys.EVAL, ModeKeys.PREDICT]: + self._test_logits( + mode, + hidden_units=(2, 2), + logits_dimension=3, + inputs=[[10., 8.]], + expected_logits=[[-0.48, 0.48, 0.39]]) + + def test_multi_feature_column_multi_dim_logits(self): + """Tests multiple feature columns and multi-dimensional logits. + + All numbers are the same as test_multi_dim_input_multi_dim_logits. The only + difference is that the input consists of two 1D feature columns, instead of + one 2D feature column. + """ + base_global_step = 100 + create_checkpoint(( + ([[.6, .5], [-.6, -.5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1., 1., .5], [-1., 1., .5]], [.3, -.3, .0]), + ), base_global_step, self._model_dir) + hidden_units = (2, 2) + logits_dimension = 3 + inputs = ([[10.]], [[8.]]) + expected_logits = [[-0.48, 0.48, 0.39]] + + for mode in [ModeKeys.TRAIN, ModeKeys.EVAL, ModeKeys.PREDICT]: + with tf.Graph().as_default(): + tf.compat.v1.train.create_global_step() + head = mock_head( + self, + hidden_units=hidden_units, + logits_dimension=logits_dimension, + expected_logits=expected_logits) + estimator_spec = self._dnn_model_fn( + features={ + 'age': tf.constant(inputs[0]), + 'height': tf.constant(inputs[1]) + }, + labels=tf.constant([[1]]), + mode=mode, + head=head, + hidden_units=hidden_units, + feature_columns=[ + self._fc_impl.numeric_column('age'), + self._fc_impl.numeric_column('height') + ], + optimizer=mock_optimizer(self, hidden_units)) + with tf.compat.v1.train.MonitoredTrainingSession( + checkpoint_dir=self._model_dir) as sess: + if mode == ModeKeys.TRAIN: + sess.run(estimator_spec.train_op) + elif mode == ModeKeys.EVAL: + sess.run(estimator_spec.loss) + elif mode == ModeKeys.PREDICT: + sess.run(estimator_spec.predictions) + else: + self.fail('Invalid mode: {}'.format(mode)) + + def test_multi_feature_column_mix_multi_dim_logits(self): + """Tests multiple feature columns and multi-dimensional logits. + + All numbers are the same as test_multi_dim_input_multi_dim_logits. The only + difference is that the input consists of two 1D feature columns, instead of + one 2D feature column. + """ + base_global_step = 100 + create_checkpoint(( + ([[.6, .5], [-.6, -.5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1., 1., .5], [-1., 1., .5]], [.3, -.3, .0]), + ), base_global_step, self._model_dir) + hidden_units = (2, 2) + logits_dimension = 3 + inputs = ([[10.]], [[8.]]) + expected_logits = [[-0.48, 0.48, 0.39]] + + for mode in [ModeKeys.TRAIN, ModeKeys.EVAL, ModeKeys.PREDICT]: + with tf.Graph().as_default(): + tf.compat.v1.train.create_global_step() + head = mock_head( + self, + hidden_units=hidden_units, + logits_dimension=logits_dimension, + expected_logits=expected_logits) + estimator_spec = self._dnn_model_fn( + features={ + 'age': tf.constant(inputs[0]), + 'height': tf.constant(inputs[1]) + }, + labels=tf.constant([[1]]), + mode=mode, + head=head, + hidden_units=hidden_units, + feature_columns=[ + feature_column.numeric_column('age'), + tf.feature_column.numeric_column('height') + ], + optimizer=mock_optimizer(self, hidden_units)) + with tf.compat.v1.train.MonitoredTrainingSession( + checkpoint_dir=self._model_dir) as sess: + if mode == ModeKeys.TRAIN: + sess.run(estimator_spec.train_op) + elif mode == ModeKeys.EVAL: + sess.run(estimator_spec.loss) + elif mode == ModeKeys.PREDICT: + sess.run(estimator_spec.predictions) + else: + self.fail('Invalid mode: {}'.format(mode)) + + def test_features_tensor_raises_value_error(self): + """Tests that passing a Tensor for features raises a ValueError.""" + hidden_units = (2, 2) + logits_dimension = 3 + inputs = ([[10.]], [[8.]]) + expected_logits = [[0, 0, 0]] + + with tf.Graph().as_default(): + tf.compat.v1.train.create_global_step() + head = mock_head( + self, + hidden_units=hidden_units, + logits_dimension=logits_dimension, + expected_logits=expected_logits) + with self.assertRaisesRegexp(ValueError, 'features should be a dict'): + self._dnn_model_fn( + features=tf.constant(inputs), + labels=tf.constant([[1]]), + mode=ModeKeys.TRAIN, + head=head, + hidden_units=hidden_units, + feature_columns=[ + self._fc_impl.numeric_column( + 'age', shape=np.array(inputs).shape[1:]) + ], + optimizer=mock_optimizer(self, hidden_units)) + + +class BaseDNNLogitFnTest(object): + """Tests correctness of logits calculated from _dnn_logit_fn_builder.""" + + def __init__(self, dnn_logit_fn_builder, fc_impl=feature_column): + self._dnn_logit_fn_builder = dnn_logit_fn_builder + self._fc_impl = fc_impl + + def setUp(self): + self._model_dir = tempfile.mkdtemp() + + def tearDown(self): + if self._model_dir: + tf.compat.v1.summary.FileWriterCache.clear() + shutil.rmtree(self._model_dir) + + def _test_logits(self, + mode, + hidden_units, + logits_dimension, + inputs, + expected_logits, + batch_norm=False): + """Tests that the expected logits are calculated.""" + with tf.Graph().as_default(): + # Global step needed for MonitoredSession, which is in turn used to + # explicitly set variable weights through a checkpoint. + tf.compat.v1.train.create_global_step() + # Use a variable scope here with 'dnn', emulating the dnn model_fn, so + # the checkpoint naming is shared. + with tf.compat.v1.variable_scope('dnn'): + input_layer_partitioner = ( + tf.compat.v1.min_max_variable_partitioner( + max_partitions=0, min_slice_size=64 << 20)) + logit_fn = self._dnn_logit_fn_builder( + units=logits_dimension, + hidden_units=hidden_units, + feature_columns=[ + self._fc_impl.numeric_column( + 'age', shape=np.array(inputs).shape[1:]) + ], + activation_fn=tf.nn.relu, + dropout=None, + input_layer_partitioner=input_layer_partitioner, + batch_norm=batch_norm) + logits = logit_fn(features={'age': tf.constant(inputs)}, mode=mode) + with tf.compat.v1.train.MonitoredTrainingSession( + checkpoint_dir=self._model_dir) as sess: + self.assertAllClose(expected_logits, sess.run(logits)) + + def test_one_dim_logits(self): + """Tests one-dimensional logits. + + input_layer = [[10]] + hidden_layer_0 = [[relu(0.6*10 +0.1), relu(0.5*10 -0.1)]] = [[6.1, 4.9]] + hidden_layer_1 = [[relu(1*6.1 -0.8*4.9 +0.2), relu(0.8*6.1 -1*4.9 -0.1)]] + = [[relu(2.38), relu(-0.12)]] = [[2.38, 0]] + logits = [[-1*2.38 +1*0 +0.3]] = [[-2.08]] + """ + base_global_step = 100 + create_checkpoint(( + ([[.6, .5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1.], [1.]], [.3]), + ), base_global_step, self._model_dir) + for mode in [ModeKeys.TRAIN, ModeKeys.EVAL, ModeKeys.PREDICT]: + self._test_logits( + mode, + hidden_units=(2, 2), + logits_dimension=1, + inputs=[[10.]], + expected_logits=[[-2.08]]) + + def test_one_dim_logits_with_batch_norm(self): + """Tests one-dimensional logits. + + input_layer = [[10]] + hidden_layer_0 = [[relu(0.6*10 +1), relu(0.5*10 -1)]] = [[7, 4]] + hidden_layer_0 = [[relu(0.6*20 +1), relu(0.5*20 -1)]] = [[13, 9]] + + batch_norm_0, training (epsilon = 0.001): + mean1 = 1/2*(7+13) = 10, + variance1 = 1/2*(3^2+3^2) = 9 + x11 = (7-10)/sqrt(9+0.001) = -0.999944449, + x21 = (13-10)/sqrt(9+0.001) = 0.999944449, + + mean2 = 1/2*(4+9) = 6.5, + variance2 = 1/2*(2.5^2+.2.5^2) = 6.25 + x12 = (4-6.5)/sqrt(6.25+0.001) = -0.99992001, + x22 = (9-6.5)/sqrt(6.25+0.001) = 0.99992001, + + logits = [[-1*(-0.999944449) + 2*(-0.99992001) + 0.3], + [-1*0.999944449 + 2*0.99992001 + 0.3]] + = [[-0.699895571],[1.299895571]] + + batch_norm_0, not training (epsilon = 0.001): + moving_mean1 = 0, moving_variance1 = 1 + x11 = (7-0)/sqrt(1+0.001) = 6.996502623, + x21 = (13-0)/sqrt(1+0.001) = 12.993504871, + moving_mean2 = 0, moving_variance2 = 1 + x12 = (4-0)/sqrt(1+0.001) = 3.998001499, + x22 = (9-0)/sqrt(1+0.001) = 8.995503372, + + logits = [[-1*6.996502623 + 2*3.998001499 + 0.3], + [-1*12.993504871 + 2*8.995503372 + 0.3]] + = [[1.299500375],[5.297501873]] + """ + base_global_step = 100 + create_checkpoint( + ( + ([[.6, .5]], [1., -1.]), + ([[-1.], [2.]], [.3]), + ), + base_global_step, + self._model_dir, + batch_norm_vars=( + [ + [0, 0], # beta. + [1, 1], # gamma. + [0, 0], # moving mean. + [1, 1], # moving variance. + ],)) + self._test_logits( + ModeKeys.TRAIN, + hidden_units=[2], + logits_dimension=1, + inputs=[[10.], [20.]], + expected_logits=[[-0.699895571], [1.299895571]], + batch_norm=True) + for mode in [ModeKeys.EVAL, ModeKeys.PREDICT]: + self._test_logits( + mode, + hidden_units=[2], + logits_dimension=1, + inputs=[[10.], [20.]], + expected_logits=[[1.299500375], [5.297501873]], + batch_norm=True) + + def test_multi_dim_logits(self): + """Tests multi-dimensional logits. + + input_layer = [[10]] + hidden_layer_0 = [[relu(0.6*10 +0.1), relu(0.5*10 -0.1)]] = [[6.1, 4.9]] + hidden_layer_1 = [[relu(1*6.1 -0.8*4.9 +0.2), relu(0.8*6.1 -1*4.9 -0.1)]] + = [[relu(2.38), relu(-0.12)]] = [[2.38, 0]] + logits = [[-1*2.38 +0.3, 1*2.38 -0.3, 0.5*2.38]] + = [[-2.08, 2.08, 1.19]] + """ + base_global_step = 100 + create_checkpoint(( + ([[.6, .5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1., 1., .5], [-1., 1., .5]], [.3, -.3, .0]), + ), base_global_step, self._model_dir) + for mode in [ModeKeys.TRAIN, ModeKeys.EVAL, ModeKeys.PREDICT]: + self._test_logits( + mode, + hidden_units=(2, 2), + logits_dimension=3, + inputs=[[10.]], + expected_logits=[[-2.08, 2.08, 1.19]]) + + def test_multi_example_multi_dim_logits(self): + """Tests multiple examples and multi-dimensional logits. + + input_layer = [[10], [5]] + hidden_layer_0 = [[relu(0.6*10 +0.1), relu(0.5*10 -0.1)], + [relu(0.6*5 +0.1), relu(0.5*5 -0.1)]] + = [[6.1, 4.9], [3.1, 2.4]] + hidden_layer_1 = [[relu(1*6.1 -0.8*4.9 +0.2), relu(0.8*6.1 -1*4.9 -0.1)], + [relu(1*3.1 -0.8*2.4 +0.2), relu(0.8*3.1 -1*2.4 -0.1)]] + = [[2.38, 0], [1.38, 0]] + logits = [[-1*2.38 +0.3, 1*2.38 -0.3, 0.5*2.38], + [-1*1.38 +0.3, 1*1.38 -0.3, 0.5*1.38]] + = [[-2.08, 2.08, 1.19], [-1.08, 1.08, 0.69]] + """ + base_global_step = 100 + create_checkpoint(( + ([[.6, .5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1., 1., .5], [-1., 1., .5]], [.3, -.3, .0]), + ), base_global_step, self._model_dir) + for mode in [ModeKeys.TRAIN, ModeKeys.EVAL, ModeKeys.PREDICT]: + self._test_logits( + mode, + hidden_units=(2, 2), + logits_dimension=3, + inputs=[[10.], [5.]], + expected_logits=[[-2.08, 2.08, 1.19], [-1.08, 1.08, .69]]) + + def test_multi_dim_input_one_dim_logits(self): + """Tests multi-dimensional inputs and one-dimensional logits. + + input_layer = [[10, 8]] + hidden_layer_0 = [[relu(0.6*10 -0.6*8 +0.1), relu(0.5*10 -0.5*8 -0.1)]] + = [[1.3, 0.9]] + hidden_layer_1 = [[relu(1*1.3 -0.8*0.9 + 0.2), relu(0.8*1.3 -1*0.9 -0.2)]] + = [[0.78, relu(-0.06)]] = [[0.78, 0]] + logits = [[-1*0.78 +1*0 +0.3]] = [[-0.48]] + """ + base_global_step = 100 + create_checkpoint(( + ([[.6, .5], [-.6, -.5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1.], [1.]], [.3]), + ), base_global_step, self._model_dir) + + for mode in [ModeKeys.TRAIN, ModeKeys.EVAL, ModeKeys.PREDICT]: + self._test_logits( + mode, + hidden_units=(2, 2), + logits_dimension=1, + inputs=[[10., 8.]], + expected_logits=[[-0.48]]) + + def test_multi_dim_input_multi_dim_logits(self): + """Tests multi-dimensional inputs and multi-dimensional logits. + + input_layer = [[10, 8]] + hidden_layer_0 = [[relu(0.6*10 -0.6*8 +0.1), relu(0.5*10 -0.5*8 -0.1)]] + = [[1.3, 0.9]] + hidden_layer_1 = [[relu(1*1.3 -0.8*0.9 + 0.2), relu(0.8*1.3 -1*0.9 -0.2)]] + = [[0.78, relu(-0.06)]] = [[0.78, 0]] + logits = [[-1*0.78 + 0.3, 1*0.78 -0.3, 0.5*0.78]] = [[-0.48, 0.48, 0.39]] + """ + base_global_step = 100 + create_checkpoint(( + ([[.6, .5], [-.6, -.5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1., 1., .5], [-1., 1., .5]], [.3, -.3, .0]), + ), base_global_step, self._model_dir) + for mode in [ModeKeys.TRAIN, ModeKeys.EVAL, ModeKeys.PREDICT]: + self._test_logits( + mode, + hidden_units=(2, 2), + logits_dimension=3, + inputs=[[10., 8.]], + expected_logits=[[-0.48, 0.48, 0.39]]) + + def test_multi_feature_column_multi_dim_logits(self): + """Tests multiple feature columns and multi-dimensional logits. + + All numbers are the same as test_multi_dim_input_multi_dim_logits. The only + difference is that the input consists of two 1D feature columns, instead of + one 2D feature column. + """ + base_global_step = 100 + create_checkpoint(( + ([[.6, .5], [-.6, -.5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1., 1., .5], [-1., 1., .5]], [.3, -.3, .0]), + ), base_global_step, self._model_dir) + + hidden_units = (2, 2) + logits_dimension = 3 + inputs = ([[10.]], [[8.]]) + expected_logits = [[-0.48, 0.48, 0.39]] + + for mode in [ModeKeys.TRAIN, ModeKeys.EVAL, ModeKeys.PREDICT]: + with tf.Graph().as_default(): + # Global step needed for MonitoredSession, which is in turn used to + # explicitly set variable weights through a checkpoint. + tf.compat.v1.train.create_global_step() + # Use a variable scope here with 'dnn', emulating the dnn model_fn, so + # the checkpoint naming is shared. + with tf.compat.v1.variable_scope('dnn'): + input_layer_partitioner = ( + tf.compat.v1.min_max_variable_partitioner( + max_partitions=0, min_slice_size=64 << 20)) + logit_fn = self._dnn_logit_fn_builder( + units=logits_dimension, + hidden_units=hidden_units, + feature_columns=[ + self._fc_impl.numeric_column('age'), + self._fc_impl.numeric_column('height') + ], + activation_fn=tf.nn.relu, + dropout=None, + input_layer_partitioner=input_layer_partitioner, + batch_norm=False) + logits = logit_fn( + features={ + 'age': tf.constant(inputs[0]), + 'height': tf.constant(inputs[1]) + }, + mode=mode) + with tf.compat.v1.train.MonitoredTrainingSession( + checkpoint_dir=self._model_dir) as sess: + self.assertAllClose(expected_logits, sess.run(logits)) + + def test_multi_feature_column_mix_multi_dim_logits(self): + """Tests multiple feature columns and multi-dimensional logits. + + All numbers are the same as test_multi_dim_input_multi_dim_logits. The only + difference is that the input consists of two 1D feature columns, instead of + one 2D feature column. + """ + base_global_step = 100 + create_checkpoint(( + ([[.6, .5], [-.6, -.5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1., 1., .5], [-1., 1., .5]], [.3, -.3, .0]), + ), base_global_step, self._model_dir) + + hidden_units = (2, 2) + logits_dimension = 3 + inputs = ([[10.]], [[8.]]) + expected_logits = [[-0.48, 0.48, 0.39]] + + for mode in [ModeKeys.TRAIN, ModeKeys.EVAL, ModeKeys.PREDICT]: + with tf.Graph().as_default(): + # Global step needed for MonitoredSession, which is in turn used to + # explicitly set variable weights through a checkpoint. + tf.compat.v1.train.create_global_step() + # Use a variable scope here with 'dnn', emulating the dnn model_fn, so + # the checkpoint naming is shared. + with tf.compat.v1.variable_scope('dnn'): + input_layer_partitioner = ( + tf.compat.v1.min_max_variable_partitioner( + max_partitions=0, min_slice_size=64 << 20)) + logit_fn = self._dnn_logit_fn_builder( + units=logits_dimension, + hidden_units=hidden_units, + feature_columns=[ + feature_column.numeric_column('age'), + tf.feature_column.numeric_column('height') + ], + activation_fn=tf.nn.relu, + dropout=None, + input_layer_partitioner=input_layer_partitioner, + batch_norm=False) + logits = logit_fn( + features={ + 'age': tf.constant(inputs[0]), + 'height': tf.constant(inputs[1]) + }, + mode=mode) + with tf.compat.v1.train.MonitoredTrainingSession( + checkpoint_dir=self._model_dir) as sess: + self.assertAllClose(expected_logits, sess.run(logits)) + + +class BaseDNNWarmStartingTest(object): + + def __init__(self, + _dnn_classifier_fn, + _dnn_regressor_fn, + fc_impl=feature_column): + self._dnn_classifier_fn = _dnn_classifier_fn + self._dnn_regressor_fn = _dnn_regressor_fn + self._fc_impl = fc_impl + + def setUp(self): + # Create a directory to save our old checkpoint and vocabularies to. + self._ckpt_and_vocab_dir = tempfile.mkdtemp() + + # Make a dummy input_fn. + def _input_fn(): + features = { + 'city': [['Palo Alto'], ['Mountain View']], + 'locality': [['Palo Alto'], ['Mountain View']], + 'occupation': [['doctor'], ['consultant']] + } + return features, [0, 1] + + self._input_fn = _input_fn + + def tearDown(self): + # Clean up checkpoint / vocab dir. + tf.compat.v1.summary.FileWriterCache.clear() + shutil.rmtree(self._ckpt_and_vocab_dir) + + def assertAllNotClose(self, t1, t2): + """Helper assert for arrays.""" + sum_of_abs_diff = 0.0 + for x, y in zip(t1, t2): + try: + for a, b in zip(x, y): + sum_of_abs_diff += abs(b - a) + except TypeError: + sum_of_abs_diff += abs(y - x) + self.assertGreater(sum_of_abs_diff, 0) + + def test_classifier_basic_warm_starting(self): + """Tests correctness of DNNClassifier default warm-start.""" + city = self._fc_impl.embedding_column( + self._fc_impl.categorical_column_with_vocabulary_list( + 'city', vocabulary_list=['Mountain View', 'Palo Alto']), + dimension=5) + + # Create a DNNClassifier and train to save a checkpoint. + dnn_classifier = self._dnn_classifier_fn( + hidden_units=[256, 128], + feature_columns=[city], + model_dir=self._ckpt_and_vocab_dir, + n_classes=4, + optimizer='SGD') + dnn_classifier.train(input_fn=self._input_fn, max_steps=1) + + # Create a second DNNClassifier, warm-started from the first. Use a + # learning_rate = 0.0 optimizer to check values (use SGD so we don't have + # accumulator values that change). + warm_started_dnn_classifier = self._dnn_classifier_fn( + hidden_units=[256, 128], + feature_columns=[city], + n_classes=4, + optimizer=tf.compat.v1.train.GradientDescentOptimizer( + learning_rate=0.0), + warm_start_from=dnn_classifier.model_dir) + + warm_started_dnn_classifier.train(input_fn=self._input_fn, max_steps=1) + for variable_name in warm_started_dnn_classifier.get_variable_names(): + self.assertAllClose( + dnn_classifier.get_variable_value(variable_name), + warm_started_dnn_classifier.get_variable_value(variable_name)) + + def test_regressor_basic_warm_starting(self): + """Tests correctness of DNNRegressor default warm-start.""" + city = self._fc_impl.embedding_column( + self._fc_impl.categorical_column_with_vocabulary_list( + 'city', vocabulary_list=['Mountain View', 'Palo Alto']), + dimension=5) + + # Create a DNNRegressor and train to save a checkpoint. + dnn_regressor = self._dnn_regressor_fn( + hidden_units=[256, 128], + feature_columns=[city], + model_dir=self._ckpt_and_vocab_dir, + optimizer='SGD') + dnn_regressor.train(input_fn=self._input_fn, max_steps=1) + + # Create a second DNNRegressor, warm-started from the first. Use a + # learning_rate = 0.0 optimizer to check values (use SGD so we don't have + # accumulator values that change). + warm_started_dnn_regressor = self._dnn_regressor_fn( + hidden_units=[256, 128], + feature_columns=[city], + optimizer=tf.compat.v1.train.GradientDescentOptimizer( + learning_rate=0.0), + warm_start_from=dnn_regressor.model_dir) + + warm_started_dnn_regressor.train(input_fn=self._input_fn, max_steps=1) + for variable_name in warm_started_dnn_regressor.get_variable_names(): + self.assertAllClose( + dnn_regressor.get_variable_value(variable_name), + warm_started_dnn_regressor.get_variable_value(variable_name)) + + def test_warm_starting_selective_variables(self): + """Tests selecting variables to warm-start.""" + city = self._fc_impl.embedding_column( + self._fc_impl.categorical_column_with_vocabulary_list( + 'city', vocabulary_list=['Mountain View', 'Palo Alto']), + dimension=5) + + # Create a DNNClassifier and train to save a checkpoint. + dnn_classifier = self._dnn_classifier_fn( + hidden_units=[256, 128], + feature_columns=[city], + model_dir=self._ckpt_and_vocab_dir, + n_classes=4, + optimizer='SGD') + dnn_classifier.train(input_fn=self._input_fn, max_steps=1) + + # Create a second DNNClassifier, warm-started from the first. Use a + # learning_rate = 0.0 optimizer to check values (use SGD so we don't have + # accumulator values that change). + warm_started_dnn_classifier = self._dnn_classifier_fn( + hidden_units=[256, 128], + feature_columns=[city], + n_classes=4, + optimizer=tf.compat.v1.train.GradientDescentOptimizer( + learning_rate=0.0), + # The provided regular expression will only warm-start the city + # embedding, not the kernels and biases of the hidden weights. + warm_start_from=estimator.WarmStartSettings( + ckpt_to_initialize_from=dnn_classifier.model_dir, + vars_to_warm_start='.*(city).*')) + + warm_started_dnn_classifier.train(input_fn=self._input_fn, max_steps=1) + for variable_name in warm_started_dnn_classifier.get_variable_names(): + if 'city' in variable_name: + self.assertAllClose( + dnn_classifier.get_variable_value(variable_name), + warm_started_dnn_classifier.get_variable_value(variable_name)) + elif 'bias' in variable_name: + # Hidden layer biases are zero-initialized. + bias_values = warm_started_dnn_classifier.get_variable_value( + variable_name) + self.assertAllClose(np.zeros_like(bias_values), bias_values) + elif 'kernel' in variable_name: + # We can't override the glorot uniform initializer used for the kernels + # in the dense layers, so just make sure we're not getting the same + # values from the old checkpoint. + self.assertAllNotClose( + dnn_classifier.get_variable_value(variable_name), + warm_started_dnn_classifier.get_variable_value(variable_name)) + + def test_warm_starting_with_vocab_remapping_and_partitioning(self): + """Tests warm-starting with vocab remapping and partitioning.""" + vocab_list = ['doctor', 'lawyer', 'consultant'] + vocab_file = os.path.join(self._ckpt_and_vocab_dir, 'occupation_vocab') + with open(vocab_file, 'w') as f: + f.write('\n'.join(vocab_list)) + occupation = self._fc_impl.embedding_column( + self._fc_impl.categorical_column_with_vocabulary_file( + 'occupation', + vocabulary_file=vocab_file, + vocabulary_size=len(vocab_list)), + dimension=2) + + # Create a DNNClassifier and train to save a checkpoint. + partitioner = tf.compat.v1.fixed_size_partitioner(num_shards=2) + dnn_classifier = self._dnn_classifier_fn( + hidden_units=[256, 128], + feature_columns=[occupation], + model_dir=self._ckpt_and_vocab_dir, + n_classes=4, + optimizer='SGD', + input_layer_partitioner=partitioner) + dnn_classifier.train(input_fn=self._input_fn, max_steps=1) + + # Create a second DNNClassifier, warm-started from the first. Use a + # learning_rate = 0.0 optimizer to check values (use SGD so we don't have + # accumulator values that change). Use a new FeatureColumn with a + # different vocabulary for occupation. + new_vocab_list = ['doctor', 'consultant', 'engineer'] + new_vocab_file = os.path.join(self._ckpt_and_vocab_dir, + 'new_occupation_vocab') + with open(new_vocab_file, 'w') as f: + f.write('\n'.join(new_vocab_list)) + new_occupation = self._fc_impl.embedding_column( + self._fc_impl.categorical_column_with_vocabulary_file( + 'occupation', + vocabulary_file=new_vocab_file, + vocabulary_size=len(new_vocab_list)), + dimension=2) + # We can create our VocabInfo object from the new and old occupation + # FeatureColumn's. + occupation_vocab_info = estimator.VocabInfo( + new_vocab=new_occupation.categorical_column.vocabulary_file, + new_vocab_size=new_occupation.categorical_column.vocabulary_size, + num_oov_buckets=new_occupation.categorical_column.num_oov_buckets, + old_vocab=occupation.categorical_column.vocabulary_file, + old_vocab_size=occupation.categorical_column.vocabulary_size, + # Can't use constant_initializer with load_and_remap. In practice, + # use a truncated normal initializer. + backup_initializer=tf.compat.v1.initializers.random_uniform( + minval=0.39, maxval=0.39)) + warm_started_dnn_classifier = self._dnn_classifier_fn( + hidden_units=[256, 128], + feature_columns=[occupation], + n_classes=4, + optimizer=tf.compat.v1.train.GradientDescentOptimizer( + learning_rate=0.0), + warm_start_from=estimator.WarmStartSettings( + ckpt_to_initialize_from=dnn_classifier.model_dir, + var_name_to_vocab_info={ + OCCUPATION_EMBEDDING_NAME: occupation_vocab_info + }, + # Explicitly providing None here will only warm-start variables + # referenced in var_name_to_vocab_info (no hidden weights will be + # warmstarted). + vars_to_warm_start=None), + input_layer_partitioner=partitioner) + + warm_started_dnn_classifier.train(input_fn=self._input_fn, max_steps=1) + # 'doctor' was ID-0 and still ID-0. + self.assertAllClose( + dnn_classifier.get_variable_value(OCCUPATION_EMBEDDING_NAME)[0, :], + warm_started_dnn_classifier.get_variable_value( + OCCUPATION_EMBEDDING_NAME)[0, :]) + # 'consultant' was ID-2 and now ID-1. + self.assertAllClose( + dnn_classifier.get_variable_value(OCCUPATION_EMBEDDING_NAME)[2, :], + warm_started_dnn_classifier.get_variable_value( + OCCUPATION_EMBEDDING_NAME)[1, :]) + # 'engineer' is a new entry and should be initialized with the + # backup_initializer in VocabInfo. + self.assertAllClose([0.39] * 2, + warm_started_dnn_classifier.get_variable_value( + OCCUPATION_EMBEDDING_NAME)[2, :]) + for variable_name in warm_started_dnn_classifier.get_variable_names(): + if 'bias' in variable_name: + # Hidden layer biases are zero-initialized. + bias_values = warm_started_dnn_classifier.get_variable_value( + variable_name) + self.assertAllClose(np.zeros_like(bias_values), bias_values) + elif 'kernel' in variable_name: + # We can't override the glorot uniform initializer used for the kernels + # in the dense layers, so just make sure we're not getting the same + # values from the old checkpoint. + self.assertAllNotClose( + dnn_classifier.get_variable_value(variable_name), + warm_started_dnn_classifier.get_variable_value(variable_name)) + + def test_warm_starting_with_naming_change(self): + """Tests warm-starting with a Tensor name remapping.""" + locality = self._fc_impl.embedding_column( + self._fc_impl.categorical_column_with_vocabulary_list( + 'locality', vocabulary_list=['Mountain View', 'Palo Alto']), + dimension=5) + + # Create a DNNClassifier and train to save a checkpoint. + dnn_classifier = self._dnn_classifier_fn( + hidden_units=[256, 128], + feature_columns=[locality], + model_dir=self._ckpt_and_vocab_dir, + n_classes=4, + optimizer='SGD') + dnn_classifier.train(input_fn=self._input_fn, max_steps=1) + + # Create a second DNNClassifier, warm-started from the first. Use a + # learning_rate = 0.0 optimizer to check values (use SGD so we don't have + # accumulator values that change). + city = self._fc_impl.embedding_column( + self._fc_impl.categorical_column_with_vocabulary_list( + 'city', vocabulary_list=['Mountain View', 'Palo Alto']), + dimension=5) + warm_started_dnn_classifier = self._dnn_classifier_fn( + hidden_units=[256, 128], + feature_columns=[city], + n_classes=4, + optimizer=tf.compat.v1.train.GradientDescentOptimizer( + learning_rate=0.0), + # The 'city' variable correspond to the 'locality' variable in the + # previous model. + warm_start_from=estimator.WarmStartSettings( + ckpt_to_initialize_from=dnn_classifier.model_dir, + var_name_to_prev_var_name={ + CITY_EMBEDDING_NAME: + CITY_EMBEDDING_NAME.replace('city', 'locality') + })) + + warm_started_dnn_classifier.train(input_fn=self._input_fn, max_steps=1) + for variable_name in warm_started_dnn_classifier.get_variable_names(): + if 'city' in variable_name: + self.assertAllClose( + dnn_classifier.get_variable_value( + CITY_EMBEDDING_NAME.replace('city', 'locality')), + warm_started_dnn_classifier.get_variable_value(CITY_EMBEDDING_NAME)) + else: + self.assertAllClose( + dnn_classifier.get_variable_value(variable_name), + warm_started_dnn_classifier.get_variable_value(variable_name)) + + +class BaseDNNClassifierEvaluateTest(object): + + def __init__(self, dnn_classifier_fn, fc_impl=feature_column): + self._dnn_classifier_fn = dnn_classifier_fn + self._fc_impl = fc_impl + + def setUp(self): + self._model_dir = tempfile.mkdtemp() + + def tearDown(self): + if self._model_dir: + tf.compat.v1.summary.FileWriterCache.clear() + shutil.rmtree(self._model_dir) + + def test_one_dim(self): + """Asserts evaluation metrics for one-dimensional input and logits.""" + global_step = 100 + create_checkpoint(( + ([[.6, .5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1.], [1.]], [.3]), + ), global_step, self._model_dir) + + dnn_classifier = self._dnn_classifier_fn( + hidden_units=(2, 2), + feature_columns=[self._fc_impl.numeric_column('age')], + model_dir=self._model_dir) + + def _input_fn(): + # batch_size = 2, one false label, and one true. + return {'age': [[10.], [10.]]}, [[1], [0]] + + # Uses identical numbers as DNNModelTest.test_one_dim_logits. + # See that test for calculation of logits. + # logits = [[-2.08], [-2.08]] => + # logistic = 1/(1 + exp(-logits)) = [[0.11105597], [0.11105597]] + # loss = -1. * log(0.111) -1. * log(0.889) = 2.31544200 + expected_loss = 2.31544200 + self.assertAllClose( + { + metric_keys.MetricKeys.LOSS: expected_loss, + metric_keys.MetricKeys.LOSS_MEAN: expected_loss / 2., + metric_keys.MetricKeys.ACCURACY: 0.5, + metric_keys.MetricKeys.PRECISION: 0.0, + metric_keys.MetricKeys.RECALL: 0.0, + metric_keys.MetricKeys.PREDICTION_MEAN: 0.11105597, + metric_keys.MetricKeys.LABEL_MEAN: 0.5, + metric_keys.MetricKeys.ACCURACY_BASELINE: 0.5, + # There is no good way to calculate AUC for only two data points. + # But that is what the algorithm returns. + metric_keys.MetricKeys.AUC: 0.5, + metric_keys.MetricKeys.AUC_PR: 0.75, + tf.compat.v1.GraphKeys.GLOBAL_STEP: global_step + }, + dnn_classifier.evaluate(input_fn=_input_fn, steps=1)) + + def test_multi_dim(self): + """Asserts evaluation metrics for multi-dimensional input and logits.""" + global_step = 100 + create_checkpoint(( + ([[.6, .5], [-.6, -.5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1., 1., .5], [-1., 1., .5]], [.3, -.3, .0]), + ), global_step, self._model_dir) + n_classes = 3 + + dnn_classifier = self._dnn_classifier_fn( + hidden_units=(2, 2), + feature_columns=[self._fc_impl.numeric_column('age', shape=[2])], + n_classes=n_classes, + model_dir=self._model_dir) + + def _input_fn(): + # batch_size = 2, one false label, and one true. + return {'age': [[10., 8.], [10., 8.]]}, [[1], [0]] + + # Uses identical numbers as + # DNNModelFnTest.test_multi_dim_input_multi_dim_logits. + # See that test for calculation of logits. + # logits = [[-0.48, 0.48, 0.39], [-0.48, 0.48, 0.39]] + # probabilities = exp(logits)/sum(exp(logits)) + # = [[0.16670536, 0.43538380, 0.39791084], + # [0.16670536, 0.43538380, 0.39791084]] + # loss = -log(0.43538380) - log(0.16670536) + expected_loss = 2.62305466 + self.assertAllClose( + { + metric_keys.MetricKeys.LOSS: expected_loss, + metric_keys.MetricKeys.LOSS_MEAN: expected_loss / 2, + metric_keys.MetricKeys.ACCURACY: 0.5, + tf.compat.v1.GraphKeys.GLOBAL_STEP: global_step + }, dnn_classifier.evaluate(input_fn=_input_fn, steps=1)) + + def test_float_labels(self): + """Asserts evaluation metrics for float labels in binary classification.""" + global_step = 100 + create_checkpoint(( + ([[.6, .5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1.], [1.]], [.3]), + ), global_step, self._model_dir) + + dnn_classifier = self._dnn_classifier_fn( + hidden_units=(2, 2), + feature_columns=[self._fc_impl.numeric_column('age')], + model_dir=self._model_dir) + + def _input_fn(): + # batch_size = 2, one false label, and one true. + return {'age': [[10.], [10.]]}, [[0.8], [0.4]] + + # Uses identical numbers as DNNModelTest.test_one_dim_logits. + # See that test for calculation of logits. + # logits = [[-2.08], [-2.08]] => + # logistic = 1/(1 + exp(-logits)) = [[0.11105597], [0.11105597]] + # loss = -0.8 * log(0.111) -0.2 * log(0.889) + # -0.4 * log(0.111) -0.6 * log(0.889) = 2.7314420 + metrics = dnn_classifier.evaluate(input_fn=_input_fn, steps=1) + self.assertAlmostEqual(2.7314420, metrics[metric_keys.MetricKeys.LOSS]) + + def test_multi_dim_weights(self): + """Tests evaluation with weights.""" + # Uses same checkpoint with test_multi_dims + global_step = 100 + create_checkpoint(( + ([[.6, .5], [-.6, -.5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1., 1., .5], [-1., 1., .5]], [.3, -.3, .0]), + ), global_step, self._model_dir) + n_classes = 3 + + dnn_classifier = self._dnn_classifier_fn( + hidden_units=(2, 2), + feature_columns=[self._fc_impl.numeric_column('age', shape=[2])], + n_classes=n_classes, + weight_column='w', + model_dir=self._model_dir) + + def _input_fn(): + # batch_size = 2, one false label, and one true. + return {'age': [[10., 8.], [10., 8.]], 'w': [[10.], [100.]]}, [[1], [0]] + + # Uses identical numbers as test_multi_dims + # See that test for calculation of logits. + # loss = -log(0.43538380)*10 - log(0.16670536)*100 + expected_loss = 187.468007 + metrics = dnn_classifier.evaluate(input_fn=_input_fn, steps=1) + self.assertAlmostEqual( + expected_loss, metrics[metric_keys.MetricKeys.LOSS], places=3) + + +class BaseDNNRegressorEvaluateTest(object): + + def __init__(self, dnn_regressor_fn, fc_impl=feature_column): + self._dnn_regressor_fn = dnn_regressor_fn + self._fc_impl = fc_impl + + def setUp(self): + self._model_dir = tempfile.mkdtemp() + + def tearDown(self): + if self._model_dir: + tf.compat.v1.summary.FileWriterCache.clear() + shutil.rmtree(self._model_dir) + + def test_one_dim(self): + """Asserts evaluation metrics for one-dimensional input and logits.""" + # Create checkpoint: num_inputs=1, hidden_units=(2, 2), num_outputs=1. + global_step = 100 + create_checkpoint(( + ([[.6, .5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1.], [1.]], [.3]), + ), global_step, self._model_dir) + + dnn_regressor = self._dnn_regressor_fn( + hidden_units=(2, 2), + feature_columns=[self._fc_impl.numeric_column('age')], + model_dir=self._model_dir) + + def _input_fn(): + return {'age': [[10.]]}, [[1.]] + + # Uses identical numbers as DNNModelTest.test_one_dim_logits. + # See that test for calculation of logits. + # logits = [[-2.08]] => predictions = [-2.08]. + # loss = (1+2.08)^2 = 9.4864 + expected_loss = 9.4864 + self.assertAllClose( + { + metric_keys.MetricKeys.LOSS: expected_loss, + metric_keys.MetricKeys.LOSS_MEAN: expected_loss, + metric_keys.MetricKeys.PREDICTION_MEAN: -2.08, + metric_keys.MetricKeys.LABEL_MEAN: 1.0, + tf.compat.v1.GraphKeys.GLOBAL_STEP: global_step + }, dnn_regressor.evaluate(input_fn=_input_fn, steps=1)) + + def test_multi_dim(self): + """Asserts evaluation metrics for multi-dimensional input and logits.""" + # Create checkpoint: num_inputs=2, hidden_units=(2, 2), num_outputs=3. + global_step = 100 + create_checkpoint(( + ([[.6, .5], [-.6, -.5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1., 1., .5], [-1., 1., .5]], [.3, -.3, .0]), + ), global_step, self._model_dir) + label_dimension = 3 + + dnn_regressor = self._dnn_regressor_fn( + hidden_units=(2, 2), + feature_columns=[self._fc_impl.numeric_column('age', shape=[2])], + label_dimension=label_dimension, + model_dir=self._model_dir) + + def _input_fn(): + return {'age': [[10., 8.]]}, [[1., -1., 0.5]] + + # Uses identical numbers as + # DNNModelFnTest.test_multi_dim_input_multi_dim_logits. + # See that test for calculation of logits. + # logits = [[-0.48, 0.48, 0.39]] + # loss = (1+0.48)^2 + (-1-0.48)^2 + (0.5-0.39)^2 = 4.3929 + expected_loss = 4.3929 + self.assertAllClose( + { + metric_keys.MetricKeys.LOSS: expected_loss, + metric_keys.MetricKeys.LOSS_MEAN: expected_loss / label_dimension, + metric_keys.MetricKeys.PREDICTION_MEAN: 0.39 / 3.0, + metric_keys.MetricKeys.LABEL_MEAN: 0.5 / 3.0, + tf.compat.v1.GraphKeys.GLOBAL_STEP: global_step + }, dnn_regressor.evaluate(input_fn=_input_fn, steps=1)) + + def test_multi_dim_weights(self): + """Asserts evaluation metrics for multi-dimensional input and logits.""" + # same checkpoint with test_multi_dim. + global_step = 100 + create_checkpoint(( + ([[.6, .5], [-.6, -.5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1., 1., .5], [-1., 1., .5]], [.3, -.3, .0]), + ), global_step, self._model_dir) + label_dimension = 3 + + dnn_regressor = self._dnn_regressor_fn( + hidden_units=(2, 2), + feature_columns=[self._fc_impl.numeric_column('age', shape=[2])], + label_dimension=label_dimension, + weight_column='w', + model_dir=self._model_dir) + + def _input_fn(): + return {'age': [[10., 8.]], 'w': [10.]}, [[1., -1., 0.5]] + + # Uses identical numbers as test_multi_dim. + # See that test for calculation of logits. + # loss = 4.3929*10 + expected_loss = 43.929 + metrics = dnn_regressor.evaluate(input_fn=_input_fn, steps=1) + self.assertAlmostEqual( + expected_loss, metrics[metric_keys.MetricKeys.LOSS], places=3) + + +class BaseDNNClassifierPredictTest(object): + + def __init__(self, dnn_classifier_fn, fc_impl=feature_column): + self._dnn_classifier_fn = dnn_classifier_fn + self._fc_impl = fc_impl + + def setUp(self): + self._model_dir = tempfile.mkdtemp() + + def tearDown(self): + if self._model_dir: + tf.compat.v1.summary.FileWriterCache.clear() + shutil.rmtree(self._model_dir) + + def _test_one_dim(self, label_vocabulary, label_output_fn): + """Asserts predictions for one-dimensional input and logits.""" + create_checkpoint(( + ([[.6, .5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1.], [1.]], [.3]), + ), + global_step=0, + model_dir=self._model_dir) + + dnn_classifier = self._dnn_classifier_fn( + hidden_units=(2, 2), + label_vocabulary=label_vocabulary, + feature_columns=(self._fc_impl.numeric_column('x'),), + model_dir=self._model_dir) + input_fn = numpy_io.numpy_input_fn( + x={'x': np.array([[10.]])}, batch_size=1, shuffle=False) + # Uses identical numbers as DNNModelTest.test_one_dim_logits. + # See that test for calculation of logits. + # logits = [-2.08] => + # logistic = exp(-2.08)/(1 + exp(-2.08)) = 0.11105597 + # probabilities = [1-logistic, logistic] = [0.88894403, 0.11105597] + # class_ids = argmax(probabilities) = [0] + predictions = next(dnn_classifier.predict(input_fn=input_fn)) + self.assertAllClose([-2.08], + predictions[prediction_keys.PredictionKeys.LOGITS]) + self.assertAllClose([0.11105597], + predictions[prediction_keys.PredictionKeys.LOGISTIC]) + self.assertAllClose( + [0.88894403, 0.11105597], + predictions[prediction_keys.PredictionKeys.PROBABILITIES]) + self.assertAllClose([0], + predictions[prediction_keys.PredictionKeys.CLASS_IDS]) + self.assertAllEqual([label_output_fn(0)], + predictions[prediction_keys.PredictionKeys.CLASSES]) + + def test_one_dim_without_label_vocabulary(self): + self._test_one_dim( + label_vocabulary=None, label_output_fn=lambda x: ('%s' % x).encode()) + + def test_one_dim_with_label_vocabulary(self): + n_classes = 2 + self._test_one_dim( + label_vocabulary=['class_vocab_{}'.format(i) for i in range(n_classes)], + label_output_fn=lambda x: ('class_vocab_%s' % x).encode()) + + def _test_multi_dim_with_3_classes(self, label_vocabulary, label_output_fn): + """Asserts predictions for multi-dimensional input and logits.""" + create_checkpoint(( + ([[.6, .5], [-.6, -.5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1., 1., .5], [-1., 1., .5]], [.3, -.3, .0]), + ), + global_step=0, + model_dir=self._model_dir) + + dnn_classifier = self._dnn_classifier_fn( + hidden_units=(2, 2), + feature_columns=(self._fc_impl.numeric_column('x', shape=(2,)),), + label_vocabulary=label_vocabulary, + n_classes=3, + model_dir=self._model_dir) + input_fn = numpy_io.numpy_input_fn( + # Inputs shape is (batch_size, num_inputs). + x={'x': np.array([[10., 8.]])}, + batch_size=1, + shuffle=False) + # Uses identical numbers as + # DNNModelFnTest.test_multi_dim_input_multi_dim_logits. + # See that test for calculation of logits. + # logits = [-0.48, 0.48, 0.39] => + # probabilities[i] = exp(logits[i]) / sum_j exp(logits[j]) => + # probabilities = [0.16670536, 0.43538380, 0.39791084] + # class_ids = argmax(probabilities) = [1] + predictions = next(dnn_classifier.predict(input_fn=input_fn)) + self.assertItemsEqual([ + prediction_keys.PredictionKeys.LOGITS, + prediction_keys.PredictionKeys.PROBABILITIES, + prediction_keys.PredictionKeys.CLASS_IDS, + prediction_keys.PredictionKeys.CLASSES, + prediction_keys.PredictionKeys.ALL_CLASS_IDS, + prediction_keys.PredictionKeys.ALL_CLASSES + ], six.iterkeys(predictions)) + self.assertAllClose([-0.48, 0.48, 0.39], + predictions[prediction_keys.PredictionKeys.LOGITS]) + self.assertAllClose( + [0.16670536, 0.43538380, 0.39791084], + predictions[prediction_keys.PredictionKeys.PROBABILITIES]) + self.assertAllEqual([1], + predictions[prediction_keys.PredictionKeys.CLASS_IDS]) + self.assertAllEqual([label_output_fn(1)], + predictions[prediction_keys.PredictionKeys.CLASSES]) + + def test_multi_dim_with_3_classes_but_no_label_vocab(self): + self._test_multi_dim_with_3_classes( + label_vocabulary=None, label_output_fn=lambda x: ('%s' % x).encode()) + + def test_multi_dim_with_3_classes_and_label_vocab(self): + n_classes = 3 + self._test_multi_dim_with_3_classes( + label_vocabulary=['class_vocab_{}'.format(i) for i in range(n_classes)], + label_output_fn=lambda x: ('class_vocab_%s' % x).encode()) + + +class BaseDNNRegressorPredictTest(object): + + def __init__(self, dnn_regressor_fn, fc_impl=feature_column): + self._dnn_regressor_fn = dnn_regressor_fn + self._fc_impl = fc_impl + + def setUp(self): + self._model_dir = tempfile.mkdtemp() + + def tearDown(self): + if self._model_dir: + tf.compat.v1.summary.FileWriterCache.clear() + shutil.rmtree(self._model_dir) + + def test_one_dim(self): + """Asserts predictions for one-dimensional input and logits.""" + # Create checkpoint: num_inputs=1, hidden_units=(2, 2), num_outputs=1. + create_checkpoint(( + ([[.6, .5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1.], [1.]], [.3]), + ), + global_step=0, + model_dir=self._model_dir) + + dnn_regressor = self._dnn_regressor_fn( + hidden_units=(2, 2), + feature_columns=(self._fc_impl.numeric_column('x'),), + model_dir=self._model_dir) + input_fn = numpy_io.numpy_input_fn( + x={'x': np.array([[10.]])}, batch_size=1, shuffle=False) + # Uses identical numbers as DNNModelTest.test_one_dim_logits. + # See that test for calculation of logits. + # logits = [[-2.08]] => predictions = [-2.08]. + self.assertAllClose({ + prediction_keys.PredictionKeys.PREDICTIONS: [-2.08], + }, next(dnn_regressor.predict(input_fn=input_fn))) + + def test_multi_dim(self): + """Asserts predictions for multi-dimensional input and logits.""" + # Create checkpoint: num_inputs=2, hidden_units=(2, 2), num_outputs=3. + create_checkpoint(( + ([[.6, .5], [-.6, -.5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1., 1., .5], [-1., 1., .5]], [.3, -.3, .0]), + ), 100, self._model_dir) + + dnn_regressor = self._dnn_regressor_fn( + hidden_units=(2, 2), + feature_columns=(self._fc_impl.numeric_column('x', shape=(2,)),), + label_dimension=3, + model_dir=self._model_dir) + input_fn = numpy_io.numpy_input_fn( + # Inputs shape is (batch_size, num_inputs). + x={'x': np.array([[10., 8.]])}, + batch_size=1, + shuffle=False) + # Uses identical numbers as + # DNNModelFnTest.test_multi_dim_input_multi_dim_logits. + # See that test for calculation of logits. + # logits = [[-0.48, 0.48, 0.39]] => predictions = [-0.48, 0.48, 0.39] + self.assertAllClose( + { + prediction_keys.PredictionKeys.PREDICTIONS: [-0.48, 0.48, 0.39], + }, next(dnn_regressor.predict(input_fn=input_fn))) + + +class _SummaryHook(tf.compat.v1.train.SessionRunHook): + """Saves summaries every N steps.""" + + def __init__(self): + self._summaries = [] + + def begin(self): + self._summary_op = tf.compat.v1.summary.merge_all() + + def before_run(self, run_context): + return tf.compat.v1.train.SessionRunArgs({'summary': self._summary_op}) + + def after_run(self, run_context, run_values): + s = tf.compat.v1.summary.Summary() + s.ParseFromString(run_values.results['summary']) + self._summaries.append(s) + + def summaries(self): + return tuple(self._summaries) + + +def _assert_checkpoint(testcase, global_step, input_units, hidden_units, + output_units, model_dir): + """Asserts checkpoint contains expected variables with proper shapes. + + Args: + testcase: A TestCase instance. + global_step: Expected global step value. + input_units: The dimension of input layer. + hidden_units: Iterable of integer sizes for the hidden layers. + output_units: The dimension of output layer (logits). + model_dir: The model directory. + """ + shapes = {name: shape for (name, shape) in tf.train.list_variables(model_dir)} + + # Global step. + testcase.assertEqual([], shapes[tf.compat.v1.GraphKeys.GLOBAL_STEP]) + testcase.assertEqual( + global_step, + tf.train.load_variable(model_dir, tf.compat.v1.GraphKeys.GLOBAL_STEP)) + + # Hidden layer weights. + prev_layer_units = input_units + for i in range(len(hidden_units)): + layer_units = hidden_units[i] + testcase.assertAllEqual((prev_layer_units, layer_units), + shapes[HIDDEN_WEIGHTS_NAME_PATTERN % i]) + testcase.assertAllEqual((layer_units,), + shapes[HIDDEN_BIASES_NAME_PATTERN % i]) + prev_layer_units = layer_units + + # Output layer weights. + testcase.assertAllEqual((prev_layer_units, output_units), + shapes[LOGITS_WEIGHTS_NAME]) + testcase.assertAllEqual((output_units,), shapes[LOGITS_BIASES_NAME]) + + +def _assert_simple_summary(testcase, expected_values, actual_summary): + """Assert summary the specified simple values. + + Args: + testcase: A TestCase instance. + expected_values: Dict of expected tags and simple values. + actual_summary: `summary_pb2.Summary`. + """ + testcase.assertAllClose( + expected_values, { + v.tag: v.simple_value + for v in actual_summary.value + if (v.tag in expected_values) + }) + + +class BaseDNNClassifierTrainTest(object): + + def __init__(self, dnn_classifier_fn, fc_impl=feature_column): + self._dnn_classifier_fn = dnn_classifier_fn + self._fc_impl = fc_impl + + def setUp(self): + self._model_dir = tempfile.mkdtemp() + + def tearDown(self): + if self._model_dir: + tf.compat.v1.summary.FileWriterCache.clear() + shutil.rmtree(self._model_dir) + + def test_from_scratch_with_default_optimizer_binary(self): + hidden_units = (2, 2) + dnn_classifier = self._dnn_classifier_fn( + hidden_units=hidden_units, + feature_columns=(self._fc_impl.numeric_column('age'),), + model_dir=self._model_dir) + + # Train for a few steps, then validate final checkpoint. + num_steps = 5 + dnn_classifier.train( + input_fn=lambda: ({ + 'age': [[10.]] + }, [[1]]), steps=num_steps) + _assert_checkpoint( + self, + num_steps, + input_units=1, + hidden_units=hidden_units, + output_units=1, + model_dir=self._model_dir) + + def test_from_scratch_with_default_optimizer_multi_class(self): + hidden_units = (2, 2) + n_classes = 3 + dnn_classifier = self._dnn_classifier_fn( + hidden_units=hidden_units, + feature_columns=(self._fc_impl.numeric_column('age'),), + n_classes=n_classes, + model_dir=self._model_dir) + + # Train for a few steps, then validate final checkpoint. + num_steps = 5 + dnn_classifier.train( + input_fn=lambda: ({ + 'age': [[10.]] + }, [[2]]), steps=num_steps) + _assert_checkpoint( + self, + num_steps, + input_units=1, + hidden_units=hidden_units, + output_units=n_classes, + model_dir=self._model_dir) + + def test_from_scratch_validate_summary(self): + hidden_units = (2, 2) + opt = mock_optimizer(self, hidden_units=hidden_units) + dnn_classifier = self._dnn_classifier_fn( + hidden_units=hidden_units, + feature_columns=(self._fc_impl.numeric_column('age'),), + optimizer=opt, + model_dir=self._model_dir) + self.assertEqual(0, opt.minimize.call_count) + + # Train for a few steps, then validate optimizer, summaries, and + # checkpoint. + num_steps = 5 + summary_hook = _SummaryHook() + dnn_classifier.train( + input_fn=lambda: ({ + 'age': [[10.]] + }, [[1]]), + steps=num_steps, + hooks=(summary_hook,)) + self.assertEqual(1, opt.minimize.call_count) + _assert_checkpoint( + self, + num_steps, + input_units=1, + hidden_units=hidden_units, + output_units=1, + model_dir=self._model_dir) + summaries = summary_hook.summaries() + self.assertEqual(num_steps, len(summaries)) + for summary in summaries: + summary_keys = [v.tag for v in summary.value] + self.assertIn(metric_keys.MetricKeys.LOSS, summary_keys) + self.assertIn(metric_keys.MetricKeys.LOSS_MEAN, summary_keys) + + def test_binary_classification(self): + base_global_step = 100 + hidden_units = (2, 2) + create_checkpoint(( + ([[.6, .5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1.], [1.]], [.3]), + ), base_global_step, self._model_dir) + + # Uses identical numbers as DNNModelFnTest.test_one_dim_logits. + # See that test for calculation of logits. + # logits = [-2.08] => probabilities = [0.889, 0.111] + # loss = -1. * log(0.111) = 2.19772100 + expected_loss = 2.19772100 + opt = mock_optimizer( + self, hidden_units=hidden_units, expected_loss=expected_loss) + dnn_classifier = self._dnn_classifier_fn( + hidden_units=hidden_units, + feature_columns=(self._fc_impl.numeric_column('age'),), + optimizer=opt, + model_dir=self._model_dir) + self.assertEqual(0, opt.minimize.call_count) + + # Train for a few steps, then validate optimizer, summaries, and + # checkpoint. + num_steps = 5 + summary_hook = _SummaryHook() + dnn_classifier.train( + input_fn=lambda: ({ + 'age': [[10.]] + }, [[1]]), + steps=num_steps, + hooks=(summary_hook,)) + self.assertEqual(1, opt.minimize.call_count) + summaries = summary_hook.summaries() + self.assertEqual(num_steps, len(summaries)) + for summary in summaries: + _assert_simple_summary( + self, { + metric_keys.MetricKeys.LOSS_MEAN: expected_loss, + 'dnn/dnn/hiddenlayer_0/fraction_of_zero_values': 0., + 'dnn/dnn/hiddenlayer_1/fraction_of_zero_values': .5, + 'dnn/dnn/logits/fraction_of_zero_values': 0., + metric_keys.MetricKeys.LOSS: expected_loss, + }, summary) + _assert_checkpoint( + self, + base_global_step + num_steps, + input_units=1, + hidden_units=hidden_units, + output_units=1, + model_dir=self._model_dir) + + def test_binary_classification_float_labels(self): + base_global_step = 100 + hidden_units = (2, 2) + create_checkpoint(( + ([[.6, .5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1.], [1.]], [.3]), + ), base_global_step, self._model_dir) + + # Uses identical numbers as DNNModelFnTest.test_one_dim_logits. + # See that test for calculation of logits. + # logits = [-2.08] => probabilities = [0.889, 0.111] + # loss = -0.8 * log(0.111) -0.2 * log(0.889) = 1.7817210 + expected_loss = 1.7817210 + opt = mock_optimizer( + self, hidden_units=hidden_units, expected_loss=expected_loss) + dnn_classifier = self._dnn_classifier_fn( + hidden_units=hidden_units, + feature_columns=(self._fc_impl.numeric_column('age'),), + optimizer=opt, + model_dir=self._model_dir) + self.assertEqual(0, opt.minimize.call_count) + + # Train for a few steps, then validate optimizer, summaries, and + # checkpoint. + num_steps = 5 + dnn_classifier.train( + input_fn=lambda: ({ + 'age': [[10.]] + }, [[0.8]]), steps=num_steps) + self.assertEqual(1, opt.minimize.call_count) + + def test_multi_class(self): + n_classes = 3 + base_global_step = 100 + hidden_units = (2, 2) + create_checkpoint(( + ([[.6, .5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1., 1., .5], [-1., 1., .5]], [.3, -.3, .0]), + ), base_global_step, self._model_dir) + + # Uses identical numbers as DNNModelFnTest.test_multi_dim_logits. + # See that test for calculation of logits. + # logits = [-2.08, 2.08, 1.19] => probabilities = [0.0109, 0.7011, 0.2879] + # loss = -1. * log(0.7011) = 0.35505795 + expected_loss = 0.35505795 + opt = mock_optimizer( + self, hidden_units=hidden_units, expected_loss=expected_loss) + dnn_classifier = self._dnn_classifier_fn( + n_classes=n_classes, + hidden_units=hidden_units, + feature_columns=(self._fc_impl.numeric_column('age'),), + optimizer=opt, + model_dir=self._model_dir) + self.assertEqual(0, opt.minimize.call_count) + + # Train for a few steps, then validate optimizer, summaries, and + # checkpoint. + num_steps = 5 + summary_hook = _SummaryHook() + dnn_classifier.train( + input_fn=lambda: ({ + 'age': [[10.]] + }, [[1]]), + steps=num_steps, + hooks=(summary_hook,)) + self.assertEqual(1, opt.minimize.call_count) + summaries = summary_hook.summaries() + self.assertEqual(num_steps, len(summaries)) + for summary in summaries: + _assert_simple_summary( + self, { + metric_keys.MetricKeys.LOSS_MEAN: expected_loss, + 'dnn/dnn/hiddenlayer_0/fraction_of_zero_values': 0., + 'dnn/dnn/hiddenlayer_1/fraction_of_zero_values': .5, + 'dnn/dnn/logits/fraction_of_zero_values': 0., + metric_keys.MetricKeys.LOSS: expected_loss, + }, summary) + _assert_checkpoint( + self, + base_global_step + num_steps, + input_units=1, + hidden_units=hidden_units, + output_units=n_classes, + model_dir=self._model_dir) + + +class BaseDNNRegressorTrainTest(object): + + def __init__(self, dnn_regressor_fn, fc_impl=feature_column): + self._dnn_regressor_fn = dnn_regressor_fn + self._fc_impl = fc_impl + + def setUp(self): + self._model_dir = tempfile.mkdtemp() + + def tearDown(self): + if self._model_dir: + tf.compat.v1.summary.FileWriterCache.clear() + shutil.rmtree(self._model_dir) + + def test_from_scratch_with_default_optimizer(self): + hidden_units = (2, 2) + dnn_regressor = self._dnn_regressor_fn( + hidden_units=hidden_units, + feature_columns=(self._fc_impl.numeric_column('age'),), + model_dir=self._model_dir) + + # Train for a few steps, then validate final checkpoint. + num_steps = 5 + dnn_regressor.train( + input_fn=lambda: ({ + 'age': ((1,),) + }, ((10,),)), steps=num_steps) + _assert_checkpoint( + self, + num_steps, + input_units=1, + hidden_units=hidden_units, + output_units=1, + model_dir=self._model_dir) + + def test_from_scratch(self): + hidden_units = (2, 2) + opt = mock_optimizer(self, hidden_units=hidden_units) + dnn_regressor = self._dnn_regressor_fn( + hidden_units=hidden_units, + feature_columns=(self._fc_impl.numeric_column('age'),), + optimizer=opt, + model_dir=self._model_dir) + self.assertEqual(0, opt.minimize.call_count) + + # Train for a few steps, then validate optimizer, summaries, and + # checkpoint. + num_steps = 5 + summary_hook = _SummaryHook() + dnn_regressor.train( + input_fn=lambda: ({ + 'age': ((1,),) + }, ((5.,),)), + steps=num_steps, + hooks=(summary_hook,)) + self.assertEqual(1, opt.minimize.call_count) + _assert_checkpoint( + self, + num_steps, + input_units=1, + hidden_units=hidden_units, + output_units=1, + model_dir=self._model_dir) + summaries = summary_hook.summaries() + self.assertEqual(num_steps, len(summaries)) + for summary in summaries: + summary_keys = [v.tag for v in summary.value] + self.assertIn(metric_keys.MetricKeys.LOSS, summary_keys) + self.assertIn(metric_keys.MetricKeys.LOSS_MEAN, summary_keys) + + def test_one_dim(self): + """Asserts train loss for one-dimensional input and logits.""" + base_global_step = 100 + hidden_units = (2, 2) + create_checkpoint(( + ([[.6, .5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1.], [1.]], [.3]), + ), base_global_step, self._model_dir) + + # Uses identical numbers as DNNModelFnTest.test_one_dim_logits. + # See that test for calculation of logits. + # logits = [-2.08] => predictions = [-2.08] + # loss = (1 + 2.08)^2 = 9.4864 + expected_loss = 9.4864 + opt = mock_optimizer( + self, hidden_units=hidden_units, expected_loss=expected_loss) + dnn_regressor = self._dnn_regressor_fn( + hidden_units=hidden_units, + feature_columns=(self._fc_impl.numeric_column('age'),), + optimizer=opt, + model_dir=self._model_dir) + self.assertEqual(0, opt.minimize.call_count) + + # Train for a few steps, then validate optimizer, summaries, and + # checkpoint. + num_steps = 5 + summary_hook = _SummaryHook() + dnn_regressor.train( + input_fn=lambda: ({ + 'age': [[10.]] + }, [[1.]]), + steps=num_steps, + hooks=(summary_hook,)) + self.assertEqual(1, opt.minimize.call_count) + summaries = summary_hook.summaries() + self.assertEqual(num_steps, len(summaries)) + for summary in summaries: + _assert_simple_summary( + self, { + metric_keys.MetricKeys.LOSS_MEAN: expected_loss, + 'dnn/dnn/hiddenlayer_0/fraction_of_zero_values': 0., + 'dnn/dnn/hiddenlayer_1/fraction_of_zero_values': 0.5, + 'dnn/dnn/logits/fraction_of_zero_values': 0., + metric_keys.MetricKeys.LOSS: expected_loss, + }, summary) + _assert_checkpoint( + self, + base_global_step + num_steps, + input_units=1, + hidden_units=hidden_units, + output_units=1, + model_dir=self._model_dir) + + def test_multi_dim(self): + """Asserts train loss for multi-dimensional input and logits.""" + base_global_step = 100 + hidden_units = (2, 2) + create_checkpoint(( + ([[.6, .5], [-.6, -.5]], [.1, -.1]), + ([[1., .8], [-.8, -1.]], [.2, -.2]), + ([[-1., 1., .5], [-1., 1., .5]], [.3, -.3, .0]), + ), base_global_step, self._model_dir) + input_dimension = 2 + label_dimension = 3 + + # Uses identical numbers as + # DNNModelFnTest.test_multi_dim_input_multi_dim_logits. + # See that test for calculation of logits. + # logits = [[-0.48, 0.48, 0.39]] + # loss = (1+0.48)^2 + (-1-0.48)^2 + (0.5-0.39)^2 = 4.3929 + expected_loss = 4.3929 + opt = mock_optimizer( + self, hidden_units=hidden_units, expected_loss=expected_loss) + dnn_regressor = self._dnn_regressor_fn( + hidden_units=hidden_units, + feature_columns=[ + self._fc_impl.numeric_column('age', shape=[input_dimension]) + ], + label_dimension=label_dimension, + optimizer=opt, + model_dir=self._model_dir) + self.assertEqual(0, opt.minimize.call_count) + + # Train for a few steps, then validate optimizer, summaries, and + # checkpoint. + num_steps = 5 + summary_hook = _SummaryHook() + dnn_regressor.train( + input_fn=lambda: ({ + 'age': [[10., 8.]] + }, [[1., -1., 0.5]]), + steps=num_steps, + hooks=(summary_hook,)) + self.assertEqual(1, opt.minimize.call_count) + summaries = summary_hook.summaries() + self.assertEqual(num_steps, len(summaries)) + for summary in summaries: + _assert_simple_summary( + self, { + metric_keys.MetricKeys.LOSS_MEAN: expected_loss / label_dimension, + 'dnn/dnn/hiddenlayer_0/fraction_of_zero_values': 0., + 'dnn/dnn/hiddenlayer_1/fraction_of_zero_values': 0.5, + 'dnn/dnn/logits/fraction_of_zero_values': 0., + metric_keys.MetricKeys.LOSS: expected_loss, + }, summary) + _assert_checkpoint( + self, + base_global_step + num_steps, + input_units=input_dimension, + hidden_units=hidden_units, + output_units=label_dimension, + model_dir=self._model_dir) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/v1/linear_testing_utils_v1.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/v1/linear_testing_utils_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..5fde321f8bfc4ffcea339b0bc556110105901699 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/canned/v1/linear_testing_utils_v1.py @@ -0,0 +1,2409 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Utils for testing linear estimators.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import math +import os +import shutil +import tempfile + +import numpy as np +import six +import tensorflow as tf +from tensorflow.core.example import example_pb2 +from tensorflow.core.example import feature_pb2 +from tensorflow.python.feature_column import feature_column +from tensorflow.python.feature_column import feature_column_v2 +from tensorflow.python.framework import ops +from tensorflow.python.ops import variables as variables_lib +from tensorflow_estimator.python.estimator import estimator +from tensorflow_estimator.python.estimator import run_config +from tensorflow_estimator.python.estimator.canned import linear +from tensorflow_estimator.python.estimator.canned import metric_keys +from tensorflow_estimator.python.estimator.export import export +from tensorflow_estimator.python.estimator.inputs import numpy_io +from tensorflow_estimator.python.estimator.inputs import pandas_io + +try: + # pylint: disable=g-import-not-at-top + import pandas as pd + HAS_PANDAS = True +except IOError: + # Pandas writes a temporary file during import. If it fails, don't use pandas. + HAS_PANDAS = False +except ImportError: + HAS_PANDAS = False + +# pylint rules which are disabled by default for test files. +# pylint: disable=invalid-name,protected-access,missing-docstring + +# Names of variables created by model. +AGE_WEIGHT_NAME = 'linear/linear_model/age/weights' +HEIGHT_WEIGHT_NAME = 'linear/linear_model/height/weights' +OCCUPATION_WEIGHT_NAME = 'linear/linear_model/occupation/weights' +BIAS_NAME = 'linear/linear_model/bias_weights' +LANGUAGE_WEIGHT_NAME = 'linear/linear_model/language/weights' + +# This is so that we can easily switch between feature_column and +# feature_column_v2 for testing. +feature_column.numeric_column = feature_column._numeric_column +feature_column.categorical_column_with_hash_bucket = feature_column._categorical_column_with_hash_bucket # pylint: disable=line-too-long +feature_column.categorical_column_with_vocabulary_list = feature_column._categorical_column_with_vocabulary_list # pylint: disable=line-too-long +feature_column.categorical_column_with_vocabulary_file = feature_column._categorical_column_with_vocabulary_file # pylint: disable=line-too-long +feature_column.embedding_column = feature_column._embedding_column + + +def assert_close(expected, actual, rtol=1e-04, name='assert_close'): + with ops.name_scope(name, 'assert_close', (expected, actual, rtol)) as scope: + expected = ops.convert_to_tensor(expected, name='expected') + actual = ops.convert_to_tensor(actual, name='actual') + rdiff = tf.math.abs(expected - actual, 'diff') / tf.math.abs(expected) + rtol = ops.convert_to_tensor(rtol, name='rtol') + return tf.compat.v1.debugging.assert_less( + rdiff, + rtol, + data=('Condition expected =~ actual did not hold element-wise:' + 'expected = ', expected, 'actual = ', actual, 'rdiff = ', rdiff, + 'rtol = ', rtol,), + name=scope) + + +def save_variables_to_ckpt(model_dir): + init_all_op = [tf.compat.v1.initializers.global_variables()] + with tf.compat.v1.Session() as sess: + sess.run(init_all_op) + tf.compat.v1.train.Saver().save(sess, os.path.join(model_dir, 'model.ckpt')) + + +def queue_parsed_features(feature_map): + tensors_to_enqueue = [] + keys = [] + for key, tensor in six.iteritems(feature_map): + keys.append(key) + tensors_to_enqueue.append(tensor) + queue_dtypes = [x.dtype for x in tensors_to_enqueue] + input_queue = tf.queue.FIFOQueue(capacity=100, dtypes=queue_dtypes) + tf.compat.v1.train.queue_runner.add_queue_runner( + tf.compat.v1.train.queue_runner.QueueRunner( + input_queue, [input_queue.enqueue(tensors_to_enqueue)])) + dequeued_tensors = input_queue.dequeue() + return {keys[i]: dequeued_tensors[i] for i in range(len(dequeued_tensors))} + + +def sorted_key_dict(unsorted_dict): + return {k: unsorted_dict[k] for k in sorted(unsorted_dict)} + + +def sigmoid(x): + return 1 / (1 + np.exp(-1.0 * x)) + + +class CheckPartitionerVarHook(tf.compat.v1.train.SessionRunHook): + """A `SessionRunHook` to check a partitioned variable.""" + + def __init__(self, test_case, var_name, var_dim, partitions): + self._test_case = test_case + self._var_name = var_name + self._var_dim = var_dim + self._partitions = partitions + + def begin(self): + with tf.compat.v1.variable_scope( + tf.compat.v1.get_variable_scope()) as scope: + scope.reuse_variables() + partitioned_weight = tf.compat.v1.get_variable( + self._var_name, shape=(self._var_dim, 1)) + self._test_case.assertTrue( + isinstance(partitioned_weight, variables_lib.PartitionedVariable)) + for part in partitioned_weight: + self._test_case.assertEqual(self._var_dim // self._partitions, + part.get_shape()[0]) + + +class BaseLinearRegressorPartitionerTest(object): + + def __init__(self, linear_regressor_fn, fc_lib=feature_column): + self._linear_regressor_fn = linear_regressor_fn + self._fc_lib = fc_lib + + def setUp(self): + self._model_dir = tempfile.mkdtemp() + + def tearDown(self): + if self._model_dir: + tf.compat.v1.summary.FileWriterCache.clear() + shutil.rmtree(self._model_dir) + + def testPartitioner(self): + x_dim = 64 + partitions = 4 + + def _partitioner(shape, dtype): + del dtype # unused; required by Fn signature. + # Only partition the embedding tensor. + return [partitions, 1] if shape[0] == x_dim else [1] + + regressor = self._linear_regressor_fn( + feature_columns=(self._fc_lib.categorical_column_with_hash_bucket( + 'language', hash_bucket_size=x_dim),), + partitioner=_partitioner, + model_dir=self._model_dir) + + def _input_fn(): + return { + 'language': + tf.sparse.SparseTensor( + values=['english', 'spanish'], + indices=[[0, 0], [0, 1]], + dense_shape=[1, 2]) + }, [[10.]] + + hook = CheckPartitionerVarHook(self, LANGUAGE_WEIGHT_NAME, x_dim, + partitions) + regressor.train(input_fn=_input_fn, steps=1, hooks=[hook]) + + def testDefaultPartitionerWithMultiplePsReplicas(self): + partitions = 2 + # This results in weights larger than the default partition size of 64M, + # so partitioned weights are created (each weight uses 4 bytes). + x_dim = 32 << 20 + + class FakeRunConfig(run_config.RunConfig): + + @property + def num_ps_replicas(self): + return partitions + + # Mock the device setter as ps is not available on test machines. + with tf.compat.v1.test.mock.patch.object( + estimator, + '_get_replica_device_setter', + return_value=lambda _: '/cpu:0'): + linear_regressor = self._linear_regressor_fn( + feature_columns=(self._fc_lib.categorical_column_with_hash_bucket( + 'language', hash_bucket_size=x_dim),), + config=FakeRunConfig(), + model_dir=self._model_dir) + + def _input_fn(): + return { + 'language': + tf.sparse.SparseTensor( + values=['english', 'spanish'], + indices=[[0, 0], [0, 1]], + dense_shape=[1, 2]) + }, [[10.]] + + hook = CheckPartitionerVarHook(self, LANGUAGE_WEIGHT_NAME, x_dim, + partitions) + linear_regressor.train(input_fn=_input_fn, steps=1, hooks=[hook]) + + +# TODO(b/36813849): Add tests with dynamic shape inputs using placeholders. +class BaseLinearRegressorEvaluationTest(object): + + def __init__(self, linear_regressor_fn, fc_lib=feature_column): + self._linear_regressor_fn = linear_regressor_fn + self._fc_lib = fc_lib + + def setUp(self): + self._model_dir = tempfile.mkdtemp() + + def tearDown(self): + if self._model_dir: + tf.compat.v1.summary.FileWriterCache.clear() + shutil.rmtree(self._model_dir) + + def test_evaluation_for_simple_data(self): + with tf.Graph().as_default(): + tf.Variable([[11.0]], name=AGE_WEIGHT_NAME) + tf.Variable([2.0], name=BIAS_NAME) + tf.Variable( + 100, name=tf.compat.v1.GraphKeys.GLOBAL_STEP, dtype=tf.dtypes.int64) + save_variables_to_ckpt(self._model_dir) + + linear_regressor = self._linear_regressor_fn( + feature_columns=(self._fc_lib.numeric_column('age'),), + model_dir=self._model_dir) + eval_metrics = linear_regressor.evaluate( + input_fn=lambda: ({ + 'age': ((1,),) + }, ((10.,),)), steps=1) + + # Logit is (1. * 11.0 + 2.0) = 13, while label is 10. Loss is 3**2 = 9. + self.assertDictEqual( + { + metric_keys.MetricKeys.LOSS: 9., + metric_keys.MetricKeys.LOSS_MEAN: 9., + metric_keys.MetricKeys.PREDICTION_MEAN: 13., + metric_keys.MetricKeys.LABEL_MEAN: 10., + tf.compat.v1.GraphKeys.GLOBAL_STEP: 100 + }, eval_metrics) + + def test_evaluation_batch(self): + """Tests evaluation for batch_size==2.""" + with tf.Graph().as_default(): + tf.Variable([[11.0]], name=AGE_WEIGHT_NAME) + tf.Variable([2.0], name=BIAS_NAME) + tf.Variable( + 100, name=tf.compat.v1.GraphKeys.GLOBAL_STEP, dtype=tf.dtypes.int64) + save_variables_to_ckpt(self._model_dir) + + linear_regressor = self._linear_regressor_fn( + feature_columns=(self._fc_lib.numeric_column('age'),), + model_dir=self._model_dir) + eval_metrics = linear_regressor.evaluate( + input_fn=lambda: ({ + 'age': ((1,), (1,)) + }, ((10.,), (10.,))), steps=1) + + # Logit is (1. * 11.0 + 2.0) = 13, while label is 10. + # Loss per example is 3**2 = 9. + # Training loss is the sum over batch = 9 + 9 = 18 + # Average loss is the average over batch = 9 + self.assertDictEqual( + { + metric_keys.MetricKeys.LOSS: 18., + metric_keys.MetricKeys.LOSS_MEAN: 9., + metric_keys.MetricKeys.PREDICTION_MEAN: 13., + metric_keys.MetricKeys.LABEL_MEAN: 10., + tf.compat.v1.GraphKeys.GLOBAL_STEP: 100 + }, eval_metrics) + + def test_evaluation_weights(self): + """Tests evaluation with weights.""" + with tf.Graph().as_default(): + tf.Variable([[11.0]], name=AGE_WEIGHT_NAME) + tf.Variable([2.0], name=BIAS_NAME) + tf.Variable( + 100, name=tf.compat.v1.GraphKeys.GLOBAL_STEP, dtype=tf.dtypes.int64) + save_variables_to_ckpt(self._model_dir) + + def _input_fn(): + features = {'age': ((1,), (1,)), 'weights': ((1.,), (2.,))} + labels = ((10.,), (10.,)) + return features, labels + + linear_regressor = self._linear_regressor_fn( + feature_columns=(self._fc_lib.numeric_column('age'),), + weight_column='weights', + model_dir=self._model_dir) + eval_metrics = linear_regressor.evaluate(input_fn=_input_fn, steps=1) + + # Logit is (1. * 11.0 + 2.0) = 13, while label is 10. + # Loss per example is 3**2 = 9. + # Training loss is the weighted sum over batch = 9 + 2*9 = 27 + # average loss is the weighted average = 9 + 2*9 / (1 + 2) = 9 + self.assertDictEqual( + { + metric_keys.MetricKeys.LOSS: 27., + metric_keys.MetricKeys.LOSS_MEAN: 9., + metric_keys.MetricKeys.PREDICTION_MEAN: 13., + metric_keys.MetricKeys.LABEL_MEAN: 10., + tf.compat.v1.GraphKeys.GLOBAL_STEP: 100 + }, eval_metrics) + + def test_evaluation_for_multi_dimensions(self): + x_dim = 3 + label_dim = 2 + with tf.Graph().as_default(): + tf.Variable([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]], name=AGE_WEIGHT_NAME) + tf.Variable([7.0, 8.0], name=BIAS_NAME) + tf.Variable(100, name='global_step', dtype=tf.dtypes.int64) + save_variables_to_ckpt(self._model_dir) + + linear_regressor = self._linear_regressor_fn( + feature_columns=(self._fc_lib.numeric_column('age', shape=(x_dim,)),), + label_dimension=label_dim, + model_dir=self._model_dir) + input_fn = numpy_io.numpy_input_fn( + x={ + 'age': np.array([[2., 4., 5.]]), + }, + y=np.array([[46., 58.]]), + batch_size=1, + num_epochs=None, + shuffle=False) + eval_metrics = linear_regressor.evaluate(input_fn=input_fn, steps=1) + + self.assertItemsEqual( + (metric_keys.MetricKeys.LOSS, metric_keys.MetricKeys.LOSS_MEAN, + metric_keys.MetricKeys.PREDICTION_MEAN, + metric_keys.MetricKeys.LABEL_MEAN, tf.compat.v1.GraphKeys.GLOBAL_STEP), + eval_metrics.keys()) + + # Logit is + # [2., 4., 5.] * [1.0, 2.0] + [7.0, 8.0] = [39, 50] + [7.0, 8.0] + # [3.0, 4.0] + # [5.0, 6.0] + # which is [46, 58] + self.assertAlmostEqual(0, eval_metrics[metric_keys.MetricKeys.LOSS]) + + def test_evaluation_for_multiple_feature_columns(self): + with tf.Graph().as_default(): + tf.Variable([[10.0]], name=AGE_WEIGHT_NAME) + tf.Variable([[2.0]], name=HEIGHT_WEIGHT_NAME) + tf.Variable([5.0], name=BIAS_NAME) + tf.Variable( + 100, name=tf.compat.v1.GraphKeys.GLOBAL_STEP, dtype=tf.dtypes.int64) + save_variables_to_ckpt(self._model_dir) + + batch_size = 2 + feature_columns = [ + self._fc_lib.numeric_column('age'), + self._fc_lib.numeric_column('height') + ] + input_fn = numpy_io.numpy_input_fn( + x={ + 'age': np.array([20, 40]), + 'height': np.array([4, 8]) + }, + y=np.array([[213.], [421.]]), + batch_size=batch_size, + num_epochs=None, + shuffle=False) + + est = self._linear_regressor_fn( + feature_columns=feature_columns, model_dir=self._model_dir) + + eval_metrics = est.evaluate(input_fn=input_fn, steps=1) + self.assertItemsEqual( + (metric_keys.MetricKeys.LOSS, metric_keys.MetricKeys.LOSS_MEAN, + metric_keys.MetricKeys.PREDICTION_MEAN, + metric_keys.MetricKeys.LABEL_MEAN, tf.compat.v1.GraphKeys.GLOBAL_STEP), + eval_metrics.keys()) + + # Logit is [(20. * 10.0 + 4 * 2.0 + 5.0), (40. * 10.0 + 8 * 2.0 + 5.0)] = + # [213.0, 421.0], while label is [213., 421.]. Loss = 0. + self.assertAlmostEqual(0, eval_metrics[metric_keys.MetricKeys.LOSS]) + + def test_evaluation_for_multiple_feature_columns_mix(self): + with tf.Graph().as_default(): + tf.Variable([[10.0]], name=AGE_WEIGHT_NAME) + tf.Variable([[2.0]], name=HEIGHT_WEIGHT_NAME) + tf.Variable([5.0], name=BIAS_NAME) + tf.Variable( + 100, name=tf.compat.v1.GraphKeys.GLOBAL_STEP, dtype=tf.dtypes.int64) + save_variables_to_ckpt(self._model_dir) + + batch_size = 2 + feature_columns = [ + feature_column.numeric_column('age'), + tf.feature_column.numeric_column('height') + ] + + def _input_fn(): + features_ds = tf.compat.v1.data.Dataset.from_tensor_slices({ + 'age': np.array([20, 40]), + 'height': np.array([4, 8]) + }) + labels_ds = tf.compat.v1.data.Dataset.from_tensor_slices( + np.array([[213.], [421.]])) + return (tf.compat.v1.data.Dataset.zip( + (features_ds, labels_ds)).batch(batch_size).repeat(None)) + + est = self._linear_regressor_fn( + feature_columns=feature_columns, model_dir=self._model_dir) + + eval_metrics = est.evaluate(input_fn=_input_fn, steps=1) + self.assertItemsEqual( + (metric_keys.MetricKeys.LOSS, metric_keys.MetricKeys.LOSS_MEAN, + metric_keys.MetricKeys.PREDICTION_MEAN, + metric_keys.MetricKeys.LABEL_MEAN, tf.compat.v1.GraphKeys.GLOBAL_STEP), + eval_metrics.keys()) + + # Logit is [(20. * 10.0 + 4 * 2.0 + 5.0), (40. * 10.0 + 8 * 2.0 + 5.0)] = + # [213.0, 421.0], while label is [213., 421.]. Loss = 0. + self.assertAlmostEqual(0, eval_metrics[metric_keys.MetricKeys.LOSS]) + + +class BaseLinearRegressorPredictTest(object): + + def __init__(self, linear_regressor_fn, fc_lib=feature_column): + self._linear_regressor_fn = linear_regressor_fn + self._fc_lib = fc_lib + + def setUp(self): + self._model_dir = tempfile.mkdtemp() + + def tearDown(self): + if self._model_dir: + tf.compat.v1.summary.FileWriterCache.clear() + shutil.rmtree(self._model_dir) + + def test_1d(self): + """Tests predict when all variables are one-dimensional.""" + with tf.Graph().as_default(): + tf.Variable([[10.]], name='linear/linear_model/x/weights') + tf.Variable([.2], name=BIAS_NAME) + tf.Variable(100, name='global_step', dtype=tf.dtypes.int64) + save_variables_to_ckpt(self._model_dir) + + linear_regressor = self._linear_regressor_fn( + feature_columns=(self._fc_lib.numeric_column('x'),), + model_dir=self._model_dir) + + predict_input_fn = numpy_io.numpy_input_fn( + x={'x': np.array([[2.]])}, + y=None, + batch_size=1, + num_epochs=1, + shuffle=False) + predictions = linear_regressor.predict(input_fn=predict_input_fn) + predicted_scores = list([x['predictions'] for x in predictions]) + # x * weight + bias = 2. * 10. + .2 = 20.2 + self.assertAllClose([[20.2]], predicted_scores) + + def testMultiDim(self): + """Tests predict when all variables are multi-dimenstional.""" + batch_size = 2 + label_dimension = 3 + x_dim = 4 + feature_columns = (self._fc_lib.numeric_column('x', shape=(x_dim,)),) + with tf.Graph().as_default(): + tf.Variable( # shape=[x_dim, label_dimension] + [[1., 2., 3.], [2., 3., 4.], [3., 4., 5.], [4., 5., 6.]], + name='linear/linear_model/x/weights') + tf.Variable( # shape=[label_dimension] + [.2, .4, .6], name=BIAS_NAME) + tf.Variable(100, name='global_step', dtype=tf.dtypes.int64) + save_variables_to_ckpt(self._model_dir) + + linear_regressor = self._linear_regressor_fn( + feature_columns=feature_columns, + label_dimension=label_dimension, + model_dir=self._model_dir) + + predict_input_fn = numpy_io.numpy_input_fn( + # x shape=[batch_size, x_dim] + x={'x': np.array([[1., 2., 3., 4.], [5., 6., 7., 8.]])}, + y=None, + batch_size=batch_size, + num_epochs=1, + shuffle=False) + predictions = linear_regressor.predict(input_fn=predict_input_fn) + predicted_scores = list([x['predictions'] for x in predictions]) + # score = x * weight + bias, shape=[batch_size, label_dimension] + self.assertAllClose([[30.2, 40.4, 50.6], [70.2, 96.4, 122.6]], + predicted_scores) + + def testTwoFeatureColumns(self): + """Tests predict with two feature columns.""" + with tf.Graph().as_default(): + tf.Variable([[10.]], name='linear/linear_model/x0/weights') + tf.Variable([[20.]], name='linear/linear_model/x1/weights') + tf.Variable([.2], name=BIAS_NAME) + tf.Variable(100, name='global_step', dtype=tf.dtypes.int64) + save_variables_to_ckpt(self._model_dir) + + linear_regressor = self._linear_regressor_fn( + feature_columns=(self._fc_lib.numeric_column('x0'), + self._fc_lib.numeric_column('x1')), + model_dir=self._model_dir) + + predict_input_fn = numpy_io.numpy_input_fn( + x={ + 'x0': np.array([[2.]]), + 'x1': np.array([[3.]]) + }, + y=None, + batch_size=1, + num_epochs=1, + shuffle=False) + predictions = linear_regressor.predict(input_fn=predict_input_fn) + predicted_scores = list([x['predictions'] for x in predictions]) + # x0 * weight0 + x1 * weight1 + bias = 2. * 10. + 3. * 20 + .2 = 80.2 + self.assertAllClose([[80.2]], predicted_scores) + + def testTwoFeatureColumnsMix(self): + """Tests predict with two feature columns.""" + with tf.Graph().as_default(): + tf.Variable([[10.]], name='linear/linear_model/x0/weights') + tf.Variable([[20.]], name='linear/linear_model/x1/weights') + tf.Variable([.2], name=BIAS_NAME) + tf.Variable(100, name='global_step', dtype=tf.dtypes.int64) + save_variables_to_ckpt(self._model_dir) + + linear_regressor = self._linear_regressor_fn( + feature_columns=(feature_column.numeric_column('x0'), + tf.feature_column.numeric_column('x1')), + model_dir=self._model_dir) + + def _predict_input_fn(): + return tf.compat.v1.data.Dataset.from_tensor_slices({ + 'x0': np.array([[2.]]), + 'x1': np.array([[3.]]) + }).batch(1) + + predictions = linear_regressor.predict(input_fn=_predict_input_fn) + predicted_scores = list([x['predictions'] for x in predictions]) + # x0 * weight0 + x1 * weight1 + bias = 2. * 10. + 3. * 20 + .2 = 80.2 + self.assertAllClose([[80.2]], predicted_scores) + + def testSparseCombiner(self): + w_a = 2.0 + w_b = 3.0 + w_c = 5.0 + bias = 5.0 + with tf.Graph().as_default(): + tf.Variable([[w_a], [w_b], [w_c]], name=LANGUAGE_WEIGHT_NAME) + tf.Variable([bias], name=BIAS_NAME) + tf.Variable( + 1, name=tf.compat.v1.GraphKeys.GLOBAL_STEP, dtype=tf.dtypes.int64) + save_variables_to_ckpt(self._model_dir) + + def _input_fn(): + return tf.compat.v1.data.Dataset.from_tensors({ + 'language': + tf.sparse.SparseTensor( + values=['a', 'c', 'b', 'c'], + indices=[[0, 0], [0, 1], [1, 0], [1, 1]], + dense_shape=[2, 2]), + }) + + feature_columns = (self._fc_lib.categorical_column_with_vocabulary_list( + 'language', vocabulary_list=['a', 'b', 'c']),) + + # Check prediction for each sparse_combiner. + # With sparse_combiner = 'sum', we have + # logits_1 = w_a + w_c + bias + # = 2.0 + 5.0 + 5.0 = 12.0 + # logits_2 = w_b + w_c + bias + # = 3.0 + 5.0 + 5.0 = 13.0 + linear_regressor = self._linear_regressor_fn( + feature_columns=feature_columns, model_dir=self._model_dir) + predictions = linear_regressor.predict(input_fn=_input_fn) + predicted_scores = list([x['predictions'] for x in predictions]) + self.assertAllClose([[12.0], [13.0]], predicted_scores) + + # With sparse_combiner = 'mean', we have + # logits_1 = 1/2 * (w_a + w_c) + bias + # = 1/2 * (2.0 + 5.0) + 5.0 = 8.5 + # logits_2 = 1/2 * (w_b + w_c) + bias + # = 1/2 * (3.0 + 5.0) + 5.0 = 9.0 + linear_regressor = self._linear_regressor_fn( + feature_columns=feature_columns, + model_dir=self._model_dir, + sparse_combiner='mean') + predictions = linear_regressor.predict(input_fn=_input_fn) + predicted_scores = list([x['predictions'] for x in predictions]) + self.assertAllClose([[8.5], [9.0]], predicted_scores) + + # With sparse_combiner = 'sqrtn', we have + # logits_1 = sqrt(2)/2 * (w_a + w_c) + bias + # = sqrt(2)/2 * (2.0 + 5.0) + 5.0 = 9.94974 + # logits_2 = sqrt(2)/2 * (w_b + w_c) + bias + # = sqrt(2)/2 * (3.0 + 5.0) + 5.0 = 10.65685 + linear_regressor = self._linear_regressor_fn( + feature_columns=feature_columns, + model_dir=self._model_dir, + sparse_combiner='sqrtn') + predictions = linear_regressor.predict(input_fn=_input_fn) + predicted_scores = list([x['predictions'] for x in predictions]) + self.assertAllClose([[9.94974], [10.65685]], predicted_scores) + + +class BaseLinearRegressorIntegrationTest(object): + + def __init__(self, linear_regressor_fn, fc_lib=feature_column): + self._linear_regressor_fn = linear_regressor_fn + self._fc_lib = fc_lib + + def setUp(self): + self._model_dir = tempfile.mkdtemp() + + def tearDown(self): + if self._model_dir: + tf.compat.v1.summary.FileWriterCache.clear() + shutil.rmtree(self._model_dir) + + def _test_complete_flow(self, train_input_fn, eval_input_fn, predict_input_fn, + input_dimension, label_dimension, prediction_length): + feature_columns = [ + self._fc_lib.numeric_column('x', shape=(input_dimension,)) + ] + est = self._linear_regressor_fn( + feature_columns=feature_columns, + label_dimension=label_dimension, + model_dir=self._model_dir) + + # TRAIN + # learn y = x + est.train(train_input_fn, steps=200) + + # EVALUTE + scores = est.evaluate(eval_input_fn) + self.assertEqual(200, scores[tf.compat.v1.GraphKeys.GLOBAL_STEP]) + self.assertIn(metric_keys.MetricKeys.LOSS, six.iterkeys(scores)) + + # PREDICT + predictions = np.array( + [x['predictions'] for x in est.predict(predict_input_fn)]) + self.assertAllEqual((prediction_length, label_dimension), predictions.shape) + + # EXPORT + feature_spec = tf.compat.v1.feature_column.make_parse_example_spec( + feature_columns) + serving_input_receiver_fn = export.build_parsing_serving_input_receiver_fn( + feature_spec) + export_dir = est.export_saved_model(tempfile.mkdtemp(), + serving_input_receiver_fn) + self.assertTrue(tf.compat.v1.gfile.Exists(export_dir)) + + def test_numpy_input_fn(self): + """Tests complete flow with numpy_input_fn.""" + label_dimension = 2 + input_dimension = label_dimension + batch_size = 10 + prediction_length = batch_size + data = np.linspace(0., 2., batch_size * label_dimension, dtype=np.float32) + data = data.reshape(batch_size, label_dimension) + + train_input_fn = numpy_io.numpy_input_fn( + x={'x': data}, + y=data, + batch_size=batch_size, + num_epochs=None, + shuffle=True) + eval_input_fn = numpy_io.numpy_input_fn( + x={'x': data}, + y=data, + batch_size=batch_size, + num_epochs=1, + shuffle=False) + predict_input_fn = numpy_io.numpy_input_fn( + x={'x': data}, + y=None, + batch_size=batch_size, + num_epochs=1, + shuffle=False) + + self._test_complete_flow( + train_input_fn=train_input_fn, + eval_input_fn=eval_input_fn, + predict_input_fn=predict_input_fn, + input_dimension=input_dimension, + label_dimension=label_dimension, + prediction_length=prediction_length) + + def test_pandas_input_fn(self): + """Tests complete flow with pandas_input_fn.""" + if not HAS_PANDAS: + return + + # Pandas DataFrame natually supports 1 dim data only. + label_dimension = 1 + input_dimension = label_dimension + batch_size = 10 + data = np.array([1., 2., 3., 4.], dtype=np.float32) + x = pd.DataFrame({'x': data}) + y = pd.Series(data) + prediction_length = 4 + + train_input_fn = pandas_io.pandas_input_fn( + x=x, y=y, batch_size=batch_size, num_epochs=None, shuffle=True) + eval_input_fn = pandas_io.pandas_input_fn( + x=x, y=y, batch_size=batch_size, shuffle=False) + predict_input_fn = pandas_io.pandas_input_fn( + x=x, batch_size=batch_size, shuffle=False) + + self._test_complete_flow( + train_input_fn=train_input_fn, + eval_input_fn=eval_input_fn, + predict_input_fn=predict_input_fn, + input_dimension=input_dimension, + label_dimension=label_dimension, + prediction_length=prediction_length) + + def test_input_fn_from_parse_example(self): + """Tests complete flow with input_fn constructed from parse_example.""" + label_dimension = 2 + input_dimension = label_dimension + batch_size = 10 + prediction_length = batch_size + data = np.linspace(0., 2., batch_size * label_dimension, dtype=np.float32) + data = data.reshape(batch_size, label_dimension) + + serialized_examples = [] + for datum in data: + example = example_pb2.Example( + features=feature_pb2.Features( + feature={ + 'x': + feature_pb2.Feature( + float_list=feature_pb2.FloatList(value=datum)), + 'y': + feature_pb2.Feature( + float_list=feature_pb2.FloatList( + value=datum[:label_dimension])), + })) + serialized_examples.append(example.SerializeToString()) + + feature_spec = { + 'x': tf.io.FixedLenFeature([input_dimension], tf.dtypes.float32), + 'y': tf.io.FixedLenFeature([label_dimension], tf.dtypes.float32), + } + + def _train_input_fn(): + feature_map = tf.compat.v1.io.parse_example(serialized_examples, + feature_spec) + features = queue_parsed_features(feature_map) + labels = features.pop('y') + return features, labels + + def _eval_input_fn(): + feature_map = tf.compat.v1.io.parse_example( + tf.compat.v1.train.limit_epochs(serialized_examples, num_epochs=1), + feature_spec) + features = queue_parsed_features(feature_map) + labels = features.pop('y') + return features, labels + + def _predict_input_fn(): + feature_map = tf.compat.v1.io.parse_example( + tf.compat.v1.train.limit_epochs(serialized_examples, num_epochs=1), + feature_spec) + features = queue_parsed_features(feature_map) + features.pop('y') + return features, None + + self._test_complete_flow( + train_input_fn=_train_input_fn, + eval_input_fn=_eval_input_fn, + predict_input_fn=_predict_input_fn, + input_dimension=input_dimension, + label_dimension=label_dimension, + prediction_length=prediction_length) + + +class BaseLinearRegressorTrainingTest(object): + + def __init__(self, linear_regressor_fn, fc_lib=feature_column): + self._linear_regressor_fn = linear_regressor_fn + self._fc_lib = fc_lib + + def setUp(self): + self._model_dir = tempfile.mkdtemp() + + def tearDown(self): + if self._model_dir: + tf.compat.v1.summary.FileWriterCache.clear() + shutil.rmtree(self._model_dir) + + def _mock_optimizer(self, expected_loss=None): + expected_var_names = [ + '%s/part_0:0' % AGE_WEIGHT_NAME, + '%s/part_0:0' % BIAS_NAME + ] + + def _minimize(loss, global_step=None, var_list=None): + trainable_vars = var_list or tf.compat.v1.get_collection( + tf.compat.v1.GraphKeys.TRAINABLE_VARIABLES) + self.assertItemsEqual(expected_var_names, + [var.name for var in trainable_vars]) + + # Verify loss. We can't check the value directly, so we add an assert op. + self.assertEquals(0, loss.shape.ndims) + if expected_loss is None: + if global_step is not None: + return tf.compat.v1.assign_add(global_step, 1).op + return tf.no_op() + assert_loss = assert_close( + tf.cast(expected_loss, name='expected', dtype=tf.dtypes.float32), + loss, + name='assert_loss') + with tf.control_dependencies((assert_loss,)): + if global_step is not None: + return tf.compat.v1.assign_add(global_step, 1).op + return tf.no_op() + + mock_optimizer = tf.compat.v1.test.mock.NonCallableMock( + spec=tf.compat.v1.train.Optimizer, + wraps=tf.compat.v1.train.Optimizer( + use_locking=False, name='my_optimizer')) + mock_optimizer.minimize = tf.compat.v1.test.mock.MagicMock(wraps=_minimize) + + # NOTE: Estimator.params performs a deepcopy, which wreaks havoc with mocks. + # So, return mock_optimizer itself for deepcopy. + mock_optimizer.__deepcopy__ = lambda _: mock_optimizer + return mock_optimizer + + def _assert_checkpoint(self, + expected_global_step, + expected_age_weight=None, + expected_bias=None): + shapes = { + name: shape + for (name, shape) in tf.train.list_variables(self._model_dir) + } + + self.assertEqual([], shapes[tf.compat.v1.GraphKeys.GLOBAL_STEP]) + self.assertEqual( + expected_global_step, + tf.train.load_variable(self._model_dir, + tf.compat.v1.GraphKeys.GLOBAL_STEP)) + + self.assertEqual([1, 1], shapes[AGE_WEIGHT_NAME]) + if expected_age_weight is not None: + self.assertEqual(expected_age_weight, + tf.train.load_variable(self._model_dir, AGE_WEIGHT_NAME)) + + self.assertEqual([1], shapes[BIAS_NAME]) + if expected_bias is not None: + self.assertEqual(expected_bias, + tf.train.load_variable(self._model_dir, BIAS_NAME)) + + def testFromScratchWithDefaultOptimizer(self): + # Create LinearRegressor. + label = 5. + age = 17 + linear_regressor = self._linear_regressor_fn( + feature_columns=(self._fc_lib.numeric_column('age'),), + model_dir=self._model_dir) + + # Train for a few steps, and validate final checkpoint. + num_steps = 10 + linear_regressor.train( + input_fn=lambda: ({ + 'age': ((age,),) + }, ((label,),)), steps=num_steps) + self._assert_checkpoint(num_steps) + + def testTrainWithOneDimLabel(self): + label_dimension = 1 + batch_size = 20 + feature_columns = [self._fc_lib.numeric_column('age', shape=(1,))] + est = self._linear_regressor_fn( + feature_columns=feature_columns, + label_dimension=label_dimension, + model_dir=self._model_dir) + data_rank_1 = np.linspace(0., 2., batch_size, dtype=np.float32) + self.assertEqual((batch_size,), data_rank_1.shape) + + train_input_fn = numpy_io.numpy_input_fn( + x={'age': data_rank_1}, + y=data_rank_1, + batch_size=batch_size, + num_epochs=None, + shuffle=True) + est.train(train_input_fn, steps=200) + self._assert_checkpoint(200) + + def testTrainWithOneDimWeight(self): + label_dimension = 1 + batch_size = 20 + feature_columns = [self._fc_lib.numeric_column('age', shape=(1,))] + est = self._linear_regressor_fn( + feature_columns=feature_columns, + label_dimension=label_dimension, + weight_column='w', + model_dir=self._model_dir) + + data_rank_1 = np.linspace(0., 2., batch_size, dtype=np.float32) + self.assertEqual((batch_size,), data_rank_1.shape) + + train_input_fn = numpy_io.numpy_input_fn( + x={ + 'age': data_rank_1, + 'w': data_rank_1 + }, + y=data_rank_1, + batch_size=batch_size, + num_epochs=None, + shuffle=True) + est.train(train_input_fn, steps=200) + self._assert_checkpoint(200) + + def testFromScratch(self): + # Create LinearRegressor. + label = 5. + age = 17 + # loss = (logits - label)^2 = (0 - 5.)^2 = 25. + mock_optimizer = self._mock_optimizer(expected_loss=25.) + linear_regressor = self._linear_regressor_fn( + feature_columns=(self._fc_lib.numeric_column('age'),), + model_dir=self._model_dir, + optimizer=mock_optimizer) + self.assertEqual(0, mock_optimizer.minimize.call_count) + + # Train for a few steps, and validate optimizer and final checkpoint. + num_steps = 10 + linear_regressor.train( + input_fn=lambda: ({ + 'age': ((age,),) + }, ((label,),)), steps=num_steps) + self.assertEqual(1, mock_optimizer.minimize.call_count) + self._assert_checkpoint( + expected_global_step=num_steps, + expected_age_weight=0., + expected_bias=0.) + + def testFromCheckpoint(self): + # Create initial checkpoint. + age_weight = 10.0 + bias = 5.0 + initial_global_step = 100 + with tf.Graph().as_default(): + tf.Variable([[age_weight]], name=AGE_WEIGHT_NAME) + tf.Variable([bias], name=BIAS_NAME) + tf.Variable( + initial_global_step, + name=tf.compat.v1.GraphKeys.GLOBAL_STEP, + dtype=tf.dtypes.int64) + save_variables_to_ckpt(self._model_dir) + + # logits = age * age_weight + bias = 17 * 10. + 5. = 175 + # loss = (logits - label)^2 = (175 - 5)^2 = 28900 + mock_optimizer = self._mock_optimizer(expected_loss=28900.) + linear_regressor = self._linear_regressor_fn( + feature_columns=(self._fc_lib.numeric_column('age'),), + model_dir=self._model_dir, + optimizer=mock_optimizer) + self.assertEqual(0, mock_optimizer.minimize.call_count) + + # Train for a few steps, and validate optimizer and final checkpoint. + num_steps = 10 + linear_regressor.train( + input_fn=lambda: ({ + 'age': ((17,),) + }, ((5.,),)), steps=num_steps) + self.assertEqual(1, mock_optimizer.minimize.call_count) + self._assert_checkpoint( + expected_global_step=initial_global_step + num_steps, + expected_age_weight=age_weight, + expected_bias=bias) + + def testFromCheckpointMultiBatch(self): + # Create initial checkpoint. + age_weight = 10.0 + bias = 5.0 + initial_global_step = 100 + with tf.Graph().as_default(): + tf.Variable([[age_weight]], name=AGE_WEIGHT_NAME) + tf.Variable([bias], name=BIAS_NAME) + tf.Variable( + initial_global_step, + name=tf.compat.v1.GraphKeys.GLOBAL_STEP, + dtype=tf.dtypes.int64) + save_variables_to_ckpt(self._model_dir) + + # logits = age * age_weight + bias + # logits[0] = 17 * 10. + 5. = 175 + # logits[1] = 15 * 10. + 5. = 155 + # loss = sum(logits - label)^2 = (175 - 5)^2 + (155 - 3)^2 = 52004 + mock_optimizer = self._mock_optimizer(expected_loss=52004.) + linear_regressor = self._linear_regressor_fn( + feature_columns=(self._fc_lib.numeric_column('age'),), + model_dir=self._model_dir, + optimizer=mock_optimizer) + self.assertEqual(0, mock_optimizer.minimize.call_count) + + # Train for a few steps, and validate optimizer and final checkpoint. + num_steps = 10 + linear_regressor.train( + input_fn=lambda: ({ + 'age': ((17,), (15,)) + }, ((5.,), (3.,))), + steps=num_steps) + self.assertEqual(1, mock_optimizer.minimize.call_count) + self._assert_checkpoint( + expected_global_step=initial_global_step + num_steps, + expected_age_weight=age_weight, + expected_bias=bias) + + +class BaseLinearClassifierTrainingTest(object): + + def __init__(self, linear_classifier_fn, fc_lib=feature_column): + self._linear_classifier_fn = linear_classifier_fn + self._fc_lib = fc_lib + + def setUp(self): + self._model_dir = tempfile.mkdtemp() + + def tearDown(self): + if self._model_dir: + shutil.rmtree(self._model_dir) + + def _mock_optimizer(self, expected_loss=None): + expected_var_names = [ + '%s/part_0:0' % AGE_WEIGHT_NAME, + '%s/part_0:0' % BIAS_NAME + ] + + def _minimize(loss, global_step): + trainable_vars = tf.compat.v1.get_collection( + tf.compat.v1.GraphKeys.TRAINABLE_VARIABLES) + self.assertItemsEqual(expected_var_names, + [var.name for var in trainable_vars]) + + # Verify loss. We can't check the value directly, so we add an assert op. + self.assertEquals(0, loss.shape.ndims) + if expected_loss is None: + return tf.compat.v1.assign_add(global_step, 1).op + assert_loss = assert_close( + tf.cast(expected_loss, name='expected', dtype=tf.dtypes.float32), + loss, + name='assert_loss') + with tf.control_dependencies((assert_loss,)): + return tf.compat.v1.assign_add(global_step, 1).op + + mock_optimizer = tf.compat.v1.test.mock.NonCallableMock( + spec=tf.compat.v1.train.Optimizer, + wraps=tf.compat.v1.train.Optimizer( + use_locking=False, name='my_optimizer')) + mock_optimizer.minimize = tf.compat.v1.test.mock.MagicMock(wraps=_minimize) + + # NOTE: Estimator.params performs a deepcopy, which wreaks havoc with mocks. + # So, return mock_optimizer itself for deepcopy. + mock_optimizer.__deepcopy__ = lambda _: mock_optimizer + return mock_optimizer + + def _assert_checkpoint(self, + n_classes, + expected_global_step, + expected_age_weight=None, + expected_bias=None): + logits_dimension = n_classes if n_classes > 2 else 1 + + shapes = { + name: shape + for (name, shape) in tf.train.list_variables(self._model_dir) + } + + self.assertEqual([], shapes[tf.compat.v1.GraphKeys.GLOBAL_STEP]) + self.assertEqual( + expected_global_step, + tf.train.load_variable(self._model_dir, + tf.compat.v1.GraphKeys.GLOBAL_STEP)) + + self.assertEqual([1, logits_dimension], shapes[AGE_WEIGHT_NAME]) + if expected_age_weight is not None: + self.assertAllEqual( + expected_age_weight, + tf.train.load_variable(self._model_dir, AGE_WEIGHT_NAME)) + + self.assertEqual([logits_dimension], shapes[BIAS_NAME]) + if expected_bias is not None: + self.assertAllEqual(expected_bias, + tf.train.load_variable(self._model_dir, BIAS_NAME)) + + def _testFromScratchWithDefaultOptimizer(self, n_classes): + label = 0 + age = 17 + est = linear.LinearClassifier( + feature_columns=(self._fc_lib.numeric_column('age'),), + n_classes=n_classes, + model_dir=self._model_dir) + + # Train for a few steps, and validate final checkpoint. + num_steps = 10 + est.train( + input_fn=lambda: ({ + 'age': ((age,),) + }, ((label,),)), steps=num_steps) + self._assert_checkpoint(n_classes, num_steps) + + def testBinaryClassesFromScratchWithDefaultOptimizer(self): + self._testFromScratchWithDefaultOptimizer(n_classes=2) + + def testMultiClassesFromScratchWithDefaultOptimizer(self): + self._testFromScratchWithDefaultOptimizer(n_classes=4) + + def _testTrainWithTwoDimsLabel(self, n_classes): + batch_size = 20 + + est = linear.LinearClassifier( + feature_columns=(self._fc_lib.numeric_column('age'),), + n_classes=n_classes, + model_dir=self._model_dir) + data_rank_1 = np.array([0, 1]) + data_rank_2 = np.array([[0], [1]]) + self.assertEqual((2,), data_rank_1.shape) + self.assertEqual((2, 1), data_rank_2.shape) + + train_input_fn = numpy_io.numpy_input_fn( + x={'age': data_rank_1}, + y=data_rank_2, + batch_size=batch_size, + num_epochs=None, + shuffle=True) + est.train(train_input_fn, steps=200) + self._assert_checkpoint(n_classes, 200) + + def testBinaryClassesTrainWithTwoDimsLabel(self): + self._testTrainWithTwoDimsLabel(n_classes=2) + + def testMultiClassesTrainWithTwoDimsLabel(self): + self._testTrainWithTwoDimsLabel(n_classes=4) + + def _testTrainWithOneDimLabel(self, n_classes): + batch_size = 20 + + est = linear.LinearClassifier( + feature_columns=(self._fc_lib.numeric_column('age'),), + n_classes=n_classes, + model_dir=self._model_dir) + data_rank_1 = np.array([0, 1]) + self.assertEqual((2,), data_rank_1.shape) + + train_input_fn = numpy_io.numpy_input_fn( + x={'age': data_rank_1}, + y=data_rank_1, + batch_size=batch_size, + num_epochs=None, + shuffle=True) + est.train(train_input_fn, steps=200) + self._assert_checkpoint(n_classes, 200) + + def testBinaryClassesTrainWithOneDimLabel(self): + self._testTrainWithOneDimLabel(n_classes=2) + + def testMultiClassesTrainWithOneDimLabel(self): + self._testTrainWithOneDimLabel(n_classes=4) + + def _testTrainWithTwoDimsWeight(self, n_classes): + batch_size = 20 + + est = linear.LinearClassifier( + feature_columns=(self._fc_lib.numeric_column('age'),), + weight_column='w', + n_classes=n_classes, + model_dir=self._model_dir) + data_rank_1 = np.array([0, 1]) + data_rank_2 = np.array([[0], [1]]) + self.assertEqual((2,), data_rank_1.shape) + self.assertEqual((2, 1), data_rank_2.shape) + + train_input_fn = numpy_io.numpy_input_fn( + x={ + 'age': data_rank_1, + 'w': data_rank_2 + }, + y=data_rank_1, + batch_size=batch_size, + num_epochs=None, + shuffle=True) + est.train(train_input_fn, steps=200) + self._assert_checkpoint(n_classes, 200) + + def testBinaryClassesTrainWithTwoDimsWeight(self): + self._testTrainWithTwoDimsWeight(n_classes=2) + + def testMultiClassesTrainWithTwoDimsWeight(self): + self._testTrainWithTwoDimsWeight(n_classes=4) + + def _testTrainWithOneDimWeight(self, n_classes): + batch_size = 20 + + est = linear.LinearClassifier( + feature_columns=(self._fc_lib.numeric_column('age'),), + weight_column='w', + n_classes=n_classes, + model_dir=self._model_dir) + data_rank_1 = np.array([0, 1]) + self.assertEqual((2,), data_rank_1.shape) + + train_input_fn = numpy_io.numpy_input_fn( + x={ + 'age': data_rank_1, + 'w': data_rank_1 + }, + y=data_rank_1, + batch_size=batch_size, + num_epochs=None, + shuffle=True) + est.train(train_input_fn, steps=200) + self._assert_checkpoint(n_classes, 200) + + def testBinaryClassesTrainWithOneDimWeight(self): + self._testTrainWithOneDimWeight(n_classes=2) + + def testMultiClassesTrainWithOneDimWeight(self): + self._testTrainWithOneDimWeight(n_classes=4) + + def _testFromScratch(self, n_classes): + label = 1 + age = 17 + # For binary classifier: + # loss = sigmoid_cross_entropy(logits, label) where logits=0 (weights are + # all zero initially) and label = 1 so, + # loss = 1 * -log ( sigmoid(logits) ) = 0.69315 + # For multi class classifier: + # loss = cross_entropy(logits, label) where logits are all 0s (weights are + # all zero initially) and label = 1 so, + # loss = 1 * -log ( 1.0 / n_classes ) + # For this particular test case, as logits are same, the formular + # 1 * -log ( 1.0 / n_classes ) covers both binary and multi class cases. + mock_optimizer = self._mock_optimizer( + expected_loss=(-1 * math.log(1.0 / n_classes))) + + est = linear.LinearClassifier( + feature_columns=(self._fc_lib.numeric_column('age'),), + n_classes=n_classes, + optimizer=mock_optimizer, + model_dir=self._model_dir) + self.assertEqual(0, mock_optimizer.minimize.call_count) + + # Train for a few steps, and validate optimizer and final checkpoint. + num_steps = 10 + est.train( + input_fn=lambda: ({ + 'age': ((age,),) + }, ((label,),)), steps=num_steps) + self.assertEqual(1, mock_optimizer.minimize.call_count) + self._assert_checkpoint( + n_classes, + expected_global_step=num_steps, + expected_age_weight=[[0.]] if n_classes == 2 else [[0.] * n_classes], + expected_bias=[0.] if n_classes == 2 else [.0] * n_classes) + + def testBinaryClassesFromScratch(self): + self._testFromScratch(n_classes=2) + + def testMultiClassesFromScratch(self): + self._testFromScratch(n_classes=4) + + def _testFromCheckpoint(self, n_classes): + # Create initial checkpoint. + label = 1 + age = 17 + # For binary case, the expected weight has shape (1,1). For multi class + # case, the shape is (1, n_classes). In order to test the weights, set + # weights as 2.0 * range(n_classes). + age_weight = [[2.0]] if n_classes == 2 else (np.reshape( + 2.0 * np.array(list(range(n_classes)), dtype=np.float32), + (1, n_classes))) + bias = [-35.0] if n_classes == 2 else [-35.0] * n_classes + initial_global_step = 100 + with tf.Graph().as_default(): + tf.Variable(age_weight, name=AGE_WEIGHT_NAME) + tf.Variable(bias, name=BIAS_NAME) + tf.Variable( + initial_global_step, + name=tf.compat.v1.GraphKeys.GLOBAL_STEP, + dtype=tf.dtypes.int64) + save_variables_to_ckpt(self._model_dir) + + # For binary classifier: + # logits = age * age_weight + bias = 17 * 2. - 35. = -1. + # loss = sigmoid_cross_entropy(logits, label) + # so, loss = 1 * -log ( sigmoid(-1) ) = 1.3133 + # For multi class classifier: + # loss = cross_entropy(logits, label) + # where logits = 17 * age_weight + bias and label = 1 + # so, loss = 1 * -log ( soft_max(logits)[1] ) + if n_classes == 2: + expected_loss = 1.3133 + else: + logits = age_weight * age + bias + logits_exp = np.exp(logits) + softmax = logits_exp / logits_exp.sum() + expected_loss = -1 * math.log(softmax[0, label]) + + mock_optimizer = self._mock_optimizer(expected_loss=expected_loss) + + est = linear.LinearClassifier( + feature_columns=(self._fc_lib.numeric_column('age'),), + n_classes=n_classes, + optimizer=mock_optimizer, + model_dir=self._model_dir) + self.assertEqual(0, mock_optimizer.minimize.call_count) + + # Train for a few steps, and validate optimizer and final checkpoint. + num_steps = 10 + est.train( + input_fn=lambda: ({ + 'age': ((age,),) + }, ((label,),)), steps=num_steps) + self.assertEqual(1, mock_optimizer.minimize.call_count) + self._assert_checkpoint( + n_classes, + expected_global_step=initial_global_step + num_steps, + expected_age_weight=age_weight, + expected_bias=bias) + + def testBinaryClassesFromCheckpoint(self): + self._testFromCheckpoint(n_classes=2) + + def testMultiClassesFromCheckpoint(self): + self._testFromCheckpoint(n_classes=4) + + def _testFromCheckpointFloatLabels(self, n_classes): + """Tests float labels for binary classification.""" + # Create initial checkpoint. + if n_classes > 2: + return + label = 0.8 + age = 17 + age_weight = [[2.0]] + bias = [-35.0] + initial_global_step = 100 + with tf.Graph().as_default(): + tf.Variable(age_weight, name=AGE_WEIGHT_NAME) + tf.Variable(bias, name=BIAS_NAME) + tf.Variable( + initial_global_step, + name=tf.compat.v1.GraphKeys.GLOBAL_STEP, + dtype=tf.dtypes.int64) + save_variables_to_ckpt(self._model_dir) + + # logits = age * age_weight + bias = 17 * 2. - 35. = -1. + # loss = sigmoid_cross_entropy(logits, label) + # => loss = -0.8 * log(sigmoid(-1)) -0.2 * log(sigmoid(+1)) = 1.1132617 + mock_optimizer = self._mock_optimizer(expected_loss=1.1132617) + + est = linear.LinearClassifier( + feature_columns=(self._fc_lib.numeric_column('age'),), + n_classes=n_classes, + optimizer=mock_optimizer, + model_dir=self._model_dir) + self.assertEqual(0, mock_optimizer.minimize.call_count) + + # Train for a few steps, and validate optimizer and final checkpoint. + num_steps = 10 + est.train( + input_fn=lambda: ({ + 'age': ((age,),) + }, ((label,),)), steps=num_steps) + self.assertEqual(1, mock_optimizer.minimize.call_count) + + def testBinaryClassesFromCheckpointFloatLabels(self): + self._testFromCheckpointFloatLabels(n_classes=2) + + def testMultiClassesFromCheckpointFloatLabels(self): + self._testFromCheckpointFloatLabels(n_classes=4) + + def _testFromCheckpointMultiBatch(self, n_classes): + # Create initial checkpoint. + label = [1, 0] + age = [17.0, 18.5] + # For binary case, the expected weight has shape (1,1). For multi class + # case, the shape is (1, n_classes). In order to test the weights, set + # weights as 2.0 * range(n_classes). + age_weight = [[2.0]] if n_classes == 2 else (np.reshape( + 2.0 * np.array(list(range(n_classes)), dtype=np.float32), + (1, n_classes))) + bias = [-35.0] if n_classes == 2 else [-35.0] * n_classes + initial_global_step = 100 + with tf.Graph().as_default(): + tf.Variable(age_weight, name=AGE_WEIGHT_NAME) + tf.Variable(bias, name=BIAS_NAME) + tf.Variable( + initial_global_step, + name=tf.compat.v1.GraphKeys.GLOBAL_STEP, + dtype=tf.dtypes.int64) + save_variables_to_ckpt(self._model_dir) + + # For binary classifier: + # logits = age * age_weight + bias + # logits[0] = 17 * 2. - 35. = -1. + # logits[1] = 18.5 * 2. - 35. = 2. + # loss = sigmoid_cross_entropy(logits, label) + # so, loss[0] = 1 * -log ( sigmoid(-1) ) = 1.3133 + # loss[1] = (1 - 0) * -log ( 1- sigmoid(2) ) = 2.1269 + # expected_loss = loss[0] + loss[1] + # For multi class classifier: + # loss = cross_entropy(logits, label) + # where logits = [17, 18.5] * age_weight + bias and label = [1, 0] + # so, loss = 1 * -log ( soft_max(logits)[label] ) + # expected_loss = loss[0] + loss[1] + if n_classes == 2: + expected_loss = 1.3133 + 2.1269 + else: + logits = age_weight * np.reshape(age, (2, 1)) + bias + logits_exp = np.exp(logits) + softmax_row_0 = logits_exp[0] / logits_exp[0].sum() + softmax_row_1 = logits_exp[1] / logits_exp[1].sum() + expected_loss_0 = -1 * math.log(softmax_row_0[label[0]]) + expected_loss_1 = -1 * math.log(softmax_row_1[label[1]]) + expected_loss = expected_loss_0 + expected_loss_1 + + mock_optimizer = self._mock_optimizer(expected_loss=expected_loss) + + est = linear.LinearClassifier( + feature_columns=(self._fc_lib.numeric_column('age'),), + n_classes=n_classes, + optimizer=mock_optimizer, + model_dir=self._model_dir) + self.assertEqual(0, mock_optimizer.minimize.call_count) + + # Train for a few steps, and validate optimizer and final checkpoint. + num_steps = 10 + est.train(input_fn=lambda: ({'age': (age)}, (label)), steps=num_steps) + self.assertEqual(1, mock_optimizer.minimize.call_count) + self._assert_checkpoint( + n_classes, + expected_global_step=initial_global_step + num_steps, + expected_age_weight=age_weight, + expected_bias=bias) + + def testBinaryClassesFromCheckpointMultiBatch(self): + self._testFromCheckpointMultiBatch(n_classes=2) + + def testMultiClassesFromCheckpointMultiBatch(self): + self._testFromCheckpointMultiBatch(n_classes=4) + + +class BaseLinearClassifierEvaluationTest(object): + + def __init__(self, linear_classifier_fn, fc_lib=feature_column): + self._linear_classifier_fn = linear_classifier_fn + self._fc_lib = fc_lib + + def setUp(self): + self._model_dir = tempfile.mkdtemp() + + def tearDown(self): + if self._model_dir: + shutil.rmtree(self._model_dir) + + def _test_evaluation_for_simple_data(self, n_classes): + label = 1 + age = 1. + + # For binary case, the expected weight has shape (1,1). For multi class + # case, the shape is (1, n_classes). In order to test the weights, set + # weights as 2.0 * range(n_classes). + age_weight = [[-11.0]] if n_classes == 2 else (np.reshape( + -11.0 * np.array(list(range(n_classes)), dtype=np.float32), + (1, n_classes))) + bias = [-30.0] if n_classes == 2 else [-30.0] * n_classes + + with tf.Graph().as_default(): + tf.Variable(age_weight, name=AGE_WEIGHT_NAME) + tf.Variable(bias, name=BIAS_NAME) + tf.Variable( + 100, name=tf.compat.v1.GraphKeys.GLOBAL_STEP, dtype=tf.dtypes.int64) + save_variables_to_ckpt(self._model_dir) + + est = self._linear_classifier_fn( + feature_columns=(self._fc_lib.numeric_column('age'),), + n_classes=n_classes, + model_dir=self._model_dir) + eval_metrics = est.evaluate( + input_fn=lambda: ({ + 'age': ((age,),) + }, ((label,),)), steps=1) + + if n_classes == 2: + # Binary classes: loss = sum(corss_entropy(41)) = 41. + expected_metrics = { + metric_keys.MetricKeys.LOSS: 41., + tf.compat.v1.GraphKeys.GLOBAL_STEP: 100, + metric_keys.MetricKeys.LOSS_MEAN: 41., + metric_keys.MetricKeys.ACCURACY: 0., + metric_keys.MetricKeys.PRECISION: 0., + metric_keys.MetricKeys.RECALL: 0., + metric_keys.MetricKeys.PREDICTION_MEAN: 0., + metric_keys.MetricKeys.LABEL_MEAN: 1., + metric_keys.MetricKeys.ACCURACY_BASELINE: 1, + metric_keys.MetricKeys.AUC: 0., + metric_keys.MetricKeys.AUC_PR: 1., + } + else: + # Multi classes: loss = 1 * -log ( soft_max(logits)[label] ) + logits = age_weight * age + bias + logits_exp = np.exp(logits) + softmax = logits_exp / logits_exp.sum() + expected_loss = -1 * math.log(softmax[0, label]) + + expected_metrics = { + metric_keys.MetricKeys.LOSS: expected_loss, + metric_keys.MetricKeys.LOSS_MEAN: expected_loss, + tf.compat.v1.GraphKeys.GLOBAL_STEP: 100, + metric_keys.MetricKeys.ACCURACY: 0., + } + + self.assertAllClose( + sorted_key_dict(expected_metrics), + sorted_key_dict(eval_metrics), + rtol=1e-3) + + def test_binary_classes_evaluation_for_simple_data(self): + self._test_evaluation_for_simple_data(n_classes=2) + + def test_multi_classes_evaluation_for_simple_data(self): + self._test_evaluation_for_simple_data(n_classes=4) + + def _test_evaluation_batch(self, n_classes): + """Tests evaluation for batch_size==2.""" + label = [1, 0] + age = [17., 18.] + # For binary case, the expected weight has shape (1,1). For multi class + # case, the shape is (1, n_classes). In order to test the weights, set + # weights as 2.0 * range(n_classes). + age_weight = [[2.0]] if n_classes == 2 else (np.reshape( + 2.0 * np.array(list(range(n_classes)), dtype=np.float32), + (1, n_classes))) + bias = [-35.0] if n_classes == 2 else [-35.0] * n_classes + initial_global_step = 100 + with tf.Graph().as_default(): + tf.Variable(age_weight, name=AGE_WEIGHT_NAME) + tf.Variable(bias, name=BIAS_NAME) + tf.Variable( + initial_global_step, + name=tf.compat.v1.GraphKeys.GLOBAL_STEP, + dtype=tf.dtypes.int64) + save_variables_to_ckpt(self._model_dir) + + est = self._linear_classifier_fn( + feature_columns=(self._fc_lib.numeric_column('age'),), + n_classes=n_classes, + model_dir=self._model_dir) + eval_metrics = est.evaluate( + input_fn=lambda: ({ + 'age': (age) + }, (label)), steps=1) + + if n_classes == 2: + # Logits are (-1., 1.) labels are (1, 0). + # Loss is + # loss for row 1: 1 * -log(sigmoid(-1)) = 1.3133 + # loss for row 2: (1 - 0) * -log(1 - sigmoid(1)) = 1.3133 + expected_loss = 1.3133 * 2 + + expected_metrics = { + metric_keys.MetricKeys.LOSS: expected_loss, + tf.compat.v1.GraphKeys.GLOBAL_STEP: 100, + metric_keys.MetricKeys.LOSS_MEAN: expected_loss / 2, + metric_keys.MetricKeys.ACCURACY: 0., + metric_keys.MetricKeys.PRECISION: 0., + metric_keys.MetricKeys.RECALL: 0., + metric_keys.MetricKeys.PREDICTION_MEAN: 0.5, + metric_keys.MetricKeys.LABEL_MEAN: 0.5, + metric_keys.MetricKeys.ACCURACY_BASELINE: 0.5, + metric_keys.MetricKeys.AUC: 0., + metric_keys.MetricKeys.AUC_PR: 0.25, + } + else: + # Multi classes: loss = 1 * -log ( soft_max(logits)[label] ) + logits = age_weight * np.reshape(age, (2, 1)) + bias + logits_exp = np.exp(logits) + softmax_row_0 = logits_exp[0] / logits_exp[0].sum() + softmax_row_1 = logits_exp[1] / logits_exp[1].sum() + expected_loss_0 = -1 * math.log(softmax_row_0[label[0]]) + expected_loss_1 = -1 * math.log(softmax_row_1[label[1]]) + expected_loss = expected_loss_0 + expected_loss_1 + + expected_metrics = { + metric_keys.MetricKeys.LOSS: expected_loss, + metric_keys.MetricKeys.LOSS_MEAN: expected_loss / 2, + tf.compat.v1.GraphKeys.GLOBAL_STEP: 100, + metric_keys.MetricKeys.ACCURACY: 0., + } + + self.assertAllClose( + sorted_key_dict(expected_metrics), + sorted_key_dict(eval_metrics), + rtol=1e-3) + + def test_binary_classes_evaluation_batch(self): + self._test_evaluation_batch(n_classes=2) + + def test_multi_classes_evaluation_batch(self): + self._test_evaluation_batch(n_classes=4) + + def _test_evaluation_weights(self, n_classes): + """Tests evaluation with weights.""" + + label = [1, 0] + age = [17., 18.] + weights = [1., 2.] + # For binary case, the expected weight has shape (1,1). For multi class + # case, the shape is (1, n_classes). In order to test the weights, set + # weights as 2.0 * range(n_classes). + age_weight = [[2.0]] if n_classes == 2 else (np.reshape( + 2.0 * np.array(list(range(n_classes)), dtype=np.float32), + (1, n_classes))) + bias = [-35.0] if n_classes == 2 else [-35.0] * n_classes + initial_global_step = 100 + with tf.Graph().as_default(): + tf.Variable(age_weight, name=AGE_WEIGHT_NAME) + tf.Variable(bias, name=BIAS_NAME) + tf.Variable( + initial_global_step, + name=tf.compat.v1.GraphKeys.GLOBAL_STEP, + dtype=tf.dtypes.int64) + save_variables_to_ckpt(self._model_dir) + + est = self._linear_classifier_fn( + feature_columns=(self._fc_lib.numeric_column('age'),), + n_classes=n_classes, + weight_column='w', + model_dir=self._model_dir) + eval_metrics = est.evaluate( + input_fn=lambda: ({ + 'age': (age), + 'w': (weights) + }, (label)), steps=1) + + if n_classes == 2: + # Logits are (-1., 1.) labels are (1, 0). + # Loss is + # loss for row 1: 1 * -log(sigmoid(-1)) = 1.3133 + # loss for row 2: (1 - 0) * -log(1 - sigmoid(1)) = 1.3133 + # weights = [1., 2.] + expected_loss = 1.3133 * (1. + 2.) + loss_mean = expected_loss / (1.0 + 2.0) + label_mean = np.average(label, weights=weights) + logits = [-1, 1] + logistics = sigmoid(np.array(logits)) + predictions_mean = np.average(logistics, weights=weights) + + expected_metrics = { + metric_keys.MetricKeys.LOSS: expected_loss, + tf.compat.v1.GraphKeys.GLOBAL_STEP: 100, + metric_keys.MetricKeys.LOSS_MEAN: loss_mean, + metric_keys.MetricKeys.ACCURACY: 0., + metric_keys.MetricKeys.PRECISION: 0., + metric_keys.MetricKeys.RECALL: 0., + metric_keys.MetricKeys.PREDICTION_MEAN: predictions_mean, + metric_keys.MetricKeys.LABEL_MEAN: label_mean, + metric_keys.MetricKeys.ACCURACY_BASELINE: + (max(label_mean, 1 - label_mean)), + metric_keys.MetricKeys.AUC: 0., + metric_keys.MetricKeys.AUC_PR: 0.1668, + } + else: + # Multi classes: unweighted_loss = 1 * -log ( soft_max(logits)[label] ) + logits = age_weight * np.reshape(age, (2, 1)) + bias + logits_exp = np.exp(logits) + softmax_row_0 = logits_exp[0] / logits_exp[0].sum() + softmax_row_1 = logits_exp[1] / logits_exp[1].sum() + expected_loss_0 = -1 * math.log(softmax_row_0[label[0]]) + expected_loss_1 = -1 * math.log(softmax_row_1[label[1]]) + loss_mean = np.average([expected_loss_0, expected_loss_1], + weights=weights) + expected_loss = loss_mean * np.sum(weights) + + expected_metrics = { + metric_keys.MetricKeys.LOSS: expected_loss, + metric_keys.MetricKeys.LOSS_MEAN: loss_mean, + tf.compat.v1.GraphKeys.GLOBAL_STEP: 100, + metric_keys.MetricKeys.ACCURACY: 0., + } + + self.assertAllClose( + sorted_key_dict(expected_metrics), + sorted_key_dict(eval_metrics), + rtol=1e-3) + + def test_binary_classes_evaluation_weights(self): + self._test_evaluation_weights(n_classes=2) + + def test_multi_classes_evaluation_weights(self): + self._test_evaluation_weights(n_classes=4) + + +class BaseLinearClassifierPredictTest(object): + + def __init__(self, linear_classifier_fn, fc_lib=feature_column): + self._linear_classifier_fn = linear_classifier_fn + self._fc_lib = fc_lib + + def setUp(self): + self._model_dir = tempfile.mkdtemp() + + def tearDown(self): + if self._model_dir: + shutil.rmtree(self._model_dir) + + def _testPredictions(self, n_classes, label_vocabulary, label_output_fn): + """Tests predict when all variables are one-dimensional.""" + age = 1. + + # For binary case, the expected weight has shape (1,1). For multi class + # case, the shape is (1, n_classes). In order to test the weights, set + # weights as 2.0 * range(n_classes). + age_weight = [[-11.0]] if n_classes == 2 else (np.reshape( + -11.0 * np.array(list(range(n_classes)), dtype=np.float32), + (1, n_classes))) + bias = [10.0] if n_classes == 2 else [10.0] * n_classes + + with tf.Graph().as_default(): + tf.Variable(age_weight, name=AGE_WEIGHT_NAME) + tf.Variable(bias, name=BIAS_NAME) + tf.Variable(100, name='global_step', dtype=tf.dtypes.int64) + save_variables_to_ckpt(self._model_dir) + + est = self._linear_classifier_fn( + feature_columns=(self._fc_lib.numeric_column('age'),), + label_vocabulary=label_vocabulary, + n_classes=n_classes, + model_dir=self._model_dir) + + predict_input_fn = numpy_io.numpy_input_fn( + x={'age': np.array([[age]])}, + y=None, + batch_size=1, + num_epochs=1, + shuffle=False) + predictions = list(est.predict(input_fn=predict_input_fn)) + + if n_classes == 2: + scalar_logits = np.reshape(np.array(age_weight) * age + bias, (1,)).item() + two_classes_logits = [0, scalar_logits] + two_classes_logits_exp = np.exp(two_classes_logits) + softmax = two_classes_logits_exp / two_classes_logits_exp.sum() + + expected_predictions = { + 'class_ids': [0], + 'all_class_ids': [0, 1], + 'classes': [label_output_fn(0)], + 'all_classes': [label_output_fn(0), + label_output_fn(1)], + 'logistic': [sigmoid(np.array(scalar_logits))], + 'logits': [scalar_logits], + 'probabilities': softmax, + } + else: + onedim_logits = np.reshape(np.array(age_weight) * age + bias, (-1,)) + class_ids = onedim_logits.argmax() + all_class_ids = list(range(len(onedim_logits))) + logits_exp = np.exp(onedim_logits) + softmax = logits_exp / logits_exp.sum() + expected_predictions = { + 'class_ids': [class_ids], + 'all_class_ids': all_class_ids, + 'classes': [label_output_fn(class_ids)], + 'all_classes': [label_output_fn(i) for i in all_class_ids], + 'logits': onedim_logits, + 'probabilities': softmax, + } + + self.assertEqual(1, len(predictions)) + # assertAllClose cannot handle byte type. + self.assertEqual(expected_predictions['classes'], predictions[0]['classes']) + expected_predictions.pop('classes') + predictions[0].pop('classes') + self.assertAllEqual(expected_predictions['all_classes'], + predictions[0]['all_classes']) + expected_predictions.pop('all_classes') + predictions[0].pop('all_classes') + self.assertAllClose( + sorted_key_dict(expected_predictions), sorted_key_dict(predictions[0])) + + def testBinaryClassesWithoutLabelVocabulary(self): + n_classes = 2 + self._testPredictions( + n_classes, + label_vocabulary=None, + label_output_fn=lambda x: ('%s' % x).encode()) + + def testBinaryClassesWithLabelVocabulary(self): + n_classes = 2 + self._testPredictions( + n_classes, + label_vocabulary=['class_vocab_{}'.format(i) for i in range(n_classes)], + label_output_fn=lambda x: ('class_vocab_%s' % x).encode()) + + def testMultiClassesWithoutLabelVocabulary(self): + n_classes = 4 + self._testPredictions( + n_classes, + label_vocabulary=None, + label_output_fn=lambda x: ('%s' % x).encode()) + + def testMultiClassesWithLabelVocabulary(self): + n_classes = 4 + self._testPredictions( + n_classes, + label_vocabulary=['class_vocab_{}'.format(i) for i in range(n_classes)], + label_output_fn=lambda x: ('class_vocab_%s' % x).encode()) + + def testSparseCombiner(self): + w_a = 2.0 + w_b = 3.0 + w_c = 5.0 + bias = 5.0 + with tf.Graph().as_default(): + tf.Variable([[w_a], [w_b], [w_c]], name=LANGUAGE_WEIGHT_NAME) + tf.Variable([bias], name=BIAS_NAME) + tf.Variable( + 1, name=tf.compat.v1.GraphKeys.GLOBAL_STEP, dtype=tf.dtypes.int64) + save_variables_to_ckpt(self._model_dir) + + def _input_fn(): + return tf.compat.v1.data.Dataset.from_tensors({ + 'language': + tf.sparse.SparseTensor( + values=['a', 'c', 'b', 'c'], + indices=[[0, 0], [0, 1], [1, 0], [1, 1]], + dense_shape=[2, 2]), + }) + + feature_columns = (self._fc_lib.categorical_column_with_vocabulary_list( + 'language', vocabulary_list=['a', 'b', 'c']),) + + # Check prediction for each sparse_combiner. + # With sparse_combiner = 'sum', we have + # logits_1 = w_a + w_c + bias + # = 2.0 + 5.0 + 5.0 = 12.0 + # logits_2 = w_b + w_c + bias + # = 3.0 + 5.0 + 5.0 = 13.0 + linear_classifier = self._linear_classifier_fn( + feature_columns=feature_columns, model_dir=self._model_dir) + predictions = linear_classifier.predict(input_fn=_input_fn) + predicted_scores = list([x['logits'] for x in predictions]) + self.assertAllClose([[12.0], [13.0]], predicted_scores) + + # With sparse_combiner = 'mean', we have + # logits_1 = 1/2 * (w_a + w_c) + bias + # = 1/2 * (2.0 + 5.0) + 5.0 = 8.5 + # logits_2 = 1/2 * (w_b + w_c) + bias + # = 1/2 * (3.0 + 5.0) + 5.0 = 9.0 + linear_classifier = self._linear_classifier_fn( + feature_columns=feature_columns, + model_dir=self._model_dir, + sparse_combiner='mean') + predictions = linear_classifier.predict(input_fn=_input_fn) + predicted_scores = list([x['logits'] for x in predictions]) + self.assertAllClose([[8.5], [9.0]], predicted_scores) + + # With sparse_combiner = 'sqrtn', we have + # logits_1 = sqrt(2)/2 * (w_a + w_c) + bias + # = sqrt(2)/2 * (2.0 + 5.0) + 5.0 = 9.94974 + # logits_2 = sqrt(2)/2 * (w_b + w_c) + bias + # = sqrt(2)/2 * (3.0 + 5.0) + 5.0 = 10.65685 + linear_classifier = self._linear_classifier_fn( + feature_columns=feature_columns, + model_dir=self._model_dir, + sparse_combiner='sqrtn') + predictions = linear_classifier.predict(input_fn=_input_fn) + predicted_scores = list([x['logits'] for x in predictions]) + self.assertAllClose([[9.94974], [10.65685]], predicted_scores) + + +class BaseLinearClassifierIntegrationTest(object): + + def __init__(self, linear_classifier_fn, fc_lib=feature_column): + self._linear_classifier_fn = linear_classifier_fn + self._fc_lib = fc_lib + + def setUp(self): + self._model_dir = tempfile.mkdtemp() + + def tearDown(self): + if self._model_dir: + shutil.rmtree(self._model_dir) + + def _test_complete_flow(self, n_classes, train_input_fn, eval_input_fn, + predict_input_fn, input_dimension, prediction_length): + feature_columns = [ + self._fc_lib.numeric_column('x', shape=(input_dimension,)) + ] + est = self._linear_classifier_fn( + feature_columns=feature_columns, + n_classes=n_classes, + model_dir=self._model_dir) + + # TRAIN + # learn y = x + est.train(train_input_fn, steps=200) + + # EVALUTE + scores = est.evaluate(eval_input_fn) + self.assertEqual(200, scores[tf.compat.v1.GraphKeys.GLOBAL_STEP]) + self.assertIn(metric_keys.MetricKeys.LOSS, six.iterkeys(scores)) + + # PREDICT + predictions = np.array( + [x['classes'] for x in est.predict(predict_input_fn)]) + self.assertAllEqual((prediction_length, 1), predictions.shape) + + # EXPORT + feature_spec = tf.compat.v1.feature_column.make_parse_example_spec( + feature_columns) + serving_input_receiver_fn = export.build_parsing_serving_input_receiver_fn( + feature_spec) + export_dir = est.export_saved_model(tempfile.mkdtemp(), + serving_input_receiver_fn) + self.assertTrue(tf.compat.v1.gfile.Exists(export_dir)) + + def _test_numpy_input_fn(self, n_classes): + """Tests complete flow with numpy_input_fn.""" + input_dimension = 4 + batch_size = 10 + prediction_length = batch_size + data = np.linspace(0., 2., batch_size * input_dimension, dtype=np.float32) + data = data.reshape(batch_size, input_dimension) + target = np.array([1] * batch_size) + + train_input_fn = numpy_io.numpy_input_fn( + x={'x': data}, + y=target, + batch_size=batch_size, + num_epochs=None, + shuffle=True) + eval_input_fn = numpy_io.numpy_input_fn( + x={'x': data}, + y=target, + batch_size=batch_size, + num_epochs=1, + shuffle=False) + predict_input_fn = numpy_io.numpy_input_fn( + x={'x': data}, + y=None, + batch_size=batch_size, + num_epochs=1, + shuffle=False) + + self._test_complete_flow( + n_classes=n_classes, + train_input_fn=train_input_fn, + eval_input_fn=eval_input_fn, + predict_input_fn=predict_input_fn, + input_dimension=input_dimension, + prediction_length=prediction_length) + + def test_binary_classes_numpy_input_fn(self): + self._test_numpy_input_fn(n_classes=2) + + def test_multi_classes_numpy_input_fn(self): + self._test_numpy_input_fn(n_classes=4) + + def _test_pandas_input_fn(self, n_classes): + """Tests complete flow with pandas_input_fn.""" + if not HAS_PANDAS: + return + + # Pandas DataFrame natually supports 1 dim data only. + input_dimension = 1 + batch_size = 10 + data = np.array([1., 2., 3., 4.], dtype=np.float32) + target = np.array([1, 0, 1, 0], dtype=np.int32) + x = pd.DataFrame({'x': data}) + y = pd.Series(target) + prediction_length = 4 + + train_input_fn = pandas_io.pandas_input_fn( + x=x, y=y, batch_size=batch_size, num_epochs=None, shuffle=True) + eval_input_fn = pandas_io.pandas_input_fn( + x=x, y=y, batch_size=batch_size, shuffle=False) + predict_input_fn = pandas_io.pandas_input_fn( + x=x, batch_size=batch_size, shuffle=False) + + self._test_complete_flow( + n_classes=n_classes, + train_input_fn=train_input_fn, + eval_input_fn=eval_input_fn, + predict_input_fn=predict_input_fn, + input_dimension=input_dimension, + prediction_length=prediction_length) + + def test_binary_classes_pandas_input_fn(self): + self._test_pandas_input_fn(n_classes=2) + + def test_multi_classes_pandas_input_fn(self): + self._test_pandas_input_fn(n_classes=4) + + def _test_input_fn_from_parse_example(self, n_classes): + """Tests complete flow with input_fn constructed from parse_example.""" + input_dimension = 2 + batch_size = 10 + prediction_length = batch_size + data = np.linspace(0., 2., batch_size * input_dimension, dtype=np.float32) + data = data.reshape(batch_size, input_dimension) + target = np.array([1] * batch_size, dtype=np.int64) + + serialized_examples = [] + for x, y in zip(data, target): + example = example_pb2.Example( + features=feature_pb2.Features( + feature={ + 'x': + feature_pb2.Feature( + float_list=feature_pb2.FloatList(value=x)), + 'y': + feature_pb2.Feature( + int64_list=feature_pb2.Int64List(value=[y])), + })) + serialized_examples.append(example.SerializeToString()) + + feature_spec = { + 'x': tf.io.FixedLenFeature([input_dimension], tf.dtypes.float32), + 'y': tf.io.FixedLenFeature([1], tf.dtypes.int64), + } + + def _train_input_fn(): + feature_map = tf.compat.v1.io.parse_example(serialized_examples, + feature_spec) + features = queue_parsed_features(feature_map) + labels = features.pop('y') + return features, labels + + def _eval_input_fn(): + feature_map = tf.compat.v1.io.parse_example( + tf.compat.v1.train.limit_epochs(serialized_examples, num_epochs=1), + feature_spec) + features = queue_parsed_features(feature_map) + labels = features.pop('y') + return features, labels + + def _predict_input_fn(): + feature_map = tf.compat.v1.io.parse_example( + tf.compat.v1.train.limit_epochs(serialized_examples, num_epochs=1), + feature_spec) + features = queue_parsed_features(feature_map) + features.pop('y') + return features, None + + self._test_complete_flow( + n_classes=n_classes, + train_input_fn=_train_input_fn, + eval_input_fn=_eval_input_fn, + predict_input_fn=_predict_input_fn, + input_dimension=input_dimension, + prediction_length=prediction_length) + + def test_binary_classes_input_fn_from_parse_example(self): + self._test_input_fn_from_parse_example(n_classes=2) + + def test_multi_classes_input_fn_from_parse_example(self): + self._test_input_fn_from_parse_example(n_classes=4) + + +class BaseLinearLogitFnTest(object): + + def __init__(self, fc_lib=feature_column): + self._fc_lib = fc_lib + + def test_basic_logit_correctness(self): + """linear_logit_fn simply wraps feature_column_lib.linear_model.""" + age = self._fc_lib.numeric_column('age') + with tf.Graph().as_default(): + logit_fn = linear.linear_logit_fn_builder(units=2, feature_columns=[age]) + logits = logit_fn(features={'age': [[23.], [31.]]}) + bias_var = tf.compat.v1.get_collection( + tf.compat.v1.GraphKeys.GLOBAL_VARIABLES, + 'linear_model/bias_weights')[0] + age_var = tf.compat.v1.get_collection( + tf.compat.v1.GraphKeys.GLOBAL_VARIABLES, 'linear_model/age')[0] + with tf.compat.v1.Session() as sess: + sess.run([tf.compat.v1.initializers.global_variables()]) + self.assertAllClose([[0., 0.], [0., 0.]], logits.eval()) + sess.run(bias_var.assign([10., 5.])) + self.assertAllClose([[10., 5.], [10., 5.]], logits.eval()) + sess.run(age_var.assign([[2.0, 3.0]])) + # [2 * 23 + 10, 3 * 23 + 5] = [56, 74]. + # [2 * 31 + 10, 3 * 31 + 5] = [72, 98] + self.assertAllClose([[56., 74.], [72., 98.]], logits.eval()) + + def test_compute_fraction_of_zero(self): + """Tests the calculation of sparsity.""" + if self._fc_lib != feature_column: + return + age = tf.feature_column.numeric_column('age') + occupation = feature_column.categorical_column_with_hash_bucket( + 'occupation', hash_bucket_size=5) + with tf.Graph().as_default(): + cols_to_vars = {} + tf.compat.v1.feature_column.linear_model( + features={ + 'age': [[23.], [31.]], + 'occupation': [['doctor'], ['engineer']] + }, + feature_columns=[age, occupation], + units=3, + cols_to_vars=cols_to_vars) + cols_to_vars.pop('bias') + fraction_zero = linear._compute_fraction_of_zero( + list(cols_to_vars.values())) + age_var = tf.compat.v1.get_collection( + tf.compat.v1.GraphKeys.GLOBAL_VARIABLES, 'linear_model/age')[0] + with tf.compat.v1.Session() as sess: + sess.run([tf.compat.v1.initializers.global_variables()]) + # Upon initialization, all variables will be zero. + self.assertAllClose(1, fraction_zero.eval()) + + sess.run(age_var.assign([[2.0, 0.0, -1.0]])) + # 1 of the 3 age weights are zero, and all of the 15 (5 hash buckets + # x 3-dim output) are zero. + self.assertAllClose(16. / 18., fraction_zero.eval()) + + def test_compute_fraction_of_zero_v2(self): + """Tests the calculation of sparsity.""" + if self._fc_lib != feature_column_v2: + return + + age = tf.feature_column.numeric_column('age') + occupation = tf.feature_column.categorical_column_with_hash_bucket( + 'occupation', hash_bucket_size=5) + with tf.Graph().as_default(): + model = feature_column_v2.LinearModel( + feature_columns=[age, occupation], units=3, name='linear_model') + features = { + 'age': [[23.], [31.]], + 'occupation': [['doctor'], ['engineer']] + } + model(features) + variables = model.variables + variables.remove(model.bias) + fraction_zero = linear._compute_fraction_of_zero(variables) + age_var = tf.compat.v1.get_collection( + tf.compat.v1.GraphKeys.GLOBAL_VARIABLES, 'linear_model/age')[0] + with tf.compat.v1.Session() as sess: + sess.run([tf.compat.v1.initializers.global_variables()]) + # Upon initialization, all variables will be zero. + self.assertAllClose(1, fraction_zero.eval()) + + sess.run(age_var.assign([[2.0, 0.0, -1.0]])) + # 1 of the 3 age weights are zero, and all of the 15 (5 hash buckets + # x 3-dim output) are zero. + self.assertAllClose(16. / 18., fraction_zero.eval()) + + +class BaseLinearWarmStartingTest(object): + + def __init__(self, + _linear_classifier_fn, + _linear_regressor_fn, + fc_lib=feature_column): + self._linear_classifier_fn = _linear_classifier_fn + self._linear_regressor_fn = _linear_regressor_fn + self._fc_lib = fc_lib + + def setUp(self): + # Create a directory to save our old checkpoint and vocabularies to. + self._ckpt_and_vocab_dir = tempfile.mkdtemp() + + # Make a dummy input_fn. + def _input_fn(): + features = { + 'age': [[23.], [31.]], + 'age_in_years': [[23.], [31.]], + 'occupation': [['doctor'], ['consultant']] + } + return features, [0, 1] + + self._input_fn = _input_fn + + def tearDown(self): + # Clean up checkpoint / vocab dir. + tf.compat.v1.summary.FileWriterCache.clear() + shutil.rmtree(self._ckpt_and_vocab_dir) + + def test_classifier_basic_warm_starting(self): + """Tests correctness of LinearClassifier default warm-start.""" + age = self._fc_lib.numeric_column('age') + + # Create a LinearClassifier and train to save a checkpoint. + linear_classifier = self._linear_classifier_fn( + feature_columns=[age], + model_dir=self._ckpt_and_vocab_dir, + n_classes=4, + optimizer='SGD') + linear_classifier.train(input_fn=self._input_fn, max_steps=1) + + # Create a second LinearClassifier, warm-started from the first. Use a + # learning_rate = 0.0 optimizer to check values (use SGD so we don't have + # accumulator values that change). + warm_started_linear_classifier = self._linear_classifier_fn( + feature_columns=[age], + n_classes=4, + optimizer=tf.compat.v1.train.GradientDescentOptimizer( + learning_rate=0.0), + warm_start_from=linear_classifier.model_dir) + + warm_started_linear_classifier.train(input_fn=self._input_fn, max_steps=1) + for variable_name in warm_started_linear_classifier.get_variable_names(): + self.assertAllClose( + linear_classifier.get_variable_value(variable_name), + warm_started_linear_classifier.get_variable_value(variable_name)) + + def test_regressor_basic_warm_starting(self): + """Tests correctness of LinearRegressor default warm-start.""" + age = self._fc_lib.numeric_column('age') + + # Create a LinearRegressor and train to save a checkpoint. + linear_regressor = self._linear_regressor_fn( + feature_columns=[age], + model_dir=self._ckpt_and_vocab_dir, + optimizer='SGD') + linear_regressor.train(input_fn=self._input_fn, max_steps=1) + + # Create a second LinearRegressor, warm-started from the first. Use a + # learning_rate = 0.0 optimizer to check values (use SGD so we don't have + # accumulator values that change). + warm_started_linear_regressor = self._linear_regressor_fn( + feature_columns=[age], + optimizer=tf.compat.v1.train.GradientDescentOptimizer( + learning_rate=0.0), + warm_start_from=linear_regressor.model_dir) + + warm_started_linear_regressor.train(input_fn=self._input_fn, max_steps=1) + for variable_name in warm_started_linear_regressor.get_variable_names(): + self.assertAllClose( + linear_regressor.get_variable_value(variable_name), + warm_started_linear_regressor.get_variable_value(variable_name)) + + def test_warm_starting_selective_variables(self): + """Tests selecting variables to warm-start.""" + age = self._fc_lib.numeric_column('age') + + # Create a LinearClassifier and train to save a checkpoint. + linear_classifier = self._linear_classifier_fn( + feature_columns=[age], + model_dir=self._ckpt_and_vocab_dir, + n_classes=4, + optimizer='SGD') + linear_classifier.train(input_fn=self._input_fn, max_steps=1) + + # Create a second LinearClassifier, warm-started from the first. Use a + # learning_rate = 0.0 optimizer to check values (use SGD so we don't have + # accumulator values that change). + warm_started_linear_classifier = self._linear_classifier_fn( + feature_columns=[age], + n_classes=4, + optimizer=tf.compat.v1.train.GradientDescentOptimizer( + learning_rate=0.0), + # The provided regular expression will only warm-start the age variable + # and not the bias. + warm_start_from=estimator.WarmStartSettings( + ckpt_to_initialize_from=linear_classifier.model_dir, + vars_to_warm_start='.*(age).*')) + + warm_started_linear_classifier.train(input_fn=self._input_fn, max_steps=1) + self.assertAllClose( + linear_classifier.get_variable_value(AGE_WEIGHT_NAME), + warm_started_linear_classifier.get_variable_value(AGE_WEIGHT_NAME)) + # Bias should still be zero from initialization. + self.assertAllClose( + [0.0] * 4, warm_started_linear_classifier.get_variable_value(BIAS_NAME)) + + def test_warm_starting_with_vocab_remapping_and_partitioning(self): + """Tests warm-starting with vocab remapping and partitioning.""" + vocab_list = ['doctor', 'lawyer', 'consultant'] + vocab_file = os.path.join(self._ckpt_and_vocab_dir, 'occupation_vocab') + with open(vocab_file, 'w') as f: + f.write('\n'.join(vocab_list)) + occupation = self._fc_lib.categorical_column_with_vocabulary_file( + 'occupation', + vocabulary_file=vocab_file, + vocabulary_size=len(vocab_list)) + + # Create a LinearClassifier and train to save a checkpoint. + partitioner = tf.compat.v1.fixed_size_partitioner(num_shards=2) + linear_classifier = self._linear_classifier_fn( + feature_columns=[occupation], + model_dir=self._ckpt_and_vocab_dir, + n_classes=4, + optimizer='SGD', + partitioner=partitioner) + linear_classifier.train(input_fn=self._input_fn, max_steps=1) + + # Create a second LinearClassifier, warm-started from the first. Use a + # learning_rate = 0.0 optimizer to check values (use SGD so we don't have + # accumulator values that change). Use a new FeatureColumn with a + # different vocabulary for occupation. + new_vocab_list = ['doctor', 'consultant', 'engineer'] + new_vocab_file = os.path.join(self._ckpt_and_vocab_dir, + 'new_occupation_vocab') + with open(new_vocab_file, 'w') as f: + f.write('\n'.join(new_vocab_list)) + new_occupation = self._fc_lib.categorical_column_with_vocabulary_file( + 'occupation', + vocabulary_file=new_vocab_file, + vocabulary_size=len(new_vocab_list)) + # We can create our VocabInfo object from the new and old occupation + # FeatureColumn's. + occupation_vocab_info = estimator.VocabInfo( + new_vocab=new_occupation.vocabulary_file, + new_vocab_size=new_occupation.vocabulary_size, + num_oov_buckets=new_occupation.num_oov_buckets, + old_vocab=occupation.vocabulary_file, + old_vocab_size=occupation.vocabulary_size, + # Can't use constant_initializer with load_and_remap. In practice, + # use a truncated normal initializer. + backup_initializer=tf.compat.v1.initializers.random_uniform( + minval=0.39, maxval=0.39)) + warm_started_linear_classifier = self._linear_classifier_fn( + feature_columns=[occupation], + n_classes=4, + optimizer=tf.compat.v1.train.GradientDescentOptimizer( + learning_rate=0.0), + warm_start_from=estimator.WarmStartSettings( + ckpt_to_initialize_from=linear_classifier.model_dir, + var_name_to_vocab_info={ + OCCUPATION_WEIGHT_NAME: occupation_vocab_info + }, + # Explicitly providing None here will only warm-start variables + # referenced in var_name_to_vocab_info (the bias will not be + # warm-started). + vars_to_warm_start=None), + partitioner=partitioner) + + warm_started_linear_classifier.train(input_fn=self._input_fn, max_steps=1) + # 'doctor' was ID-0 and still ID-0. + self.assertAllClose( + linear_classifier.get_variable_value(OCCUPATION_WEIGHT_NAME)[0, :], + warm_started_linear_classifier.get_variable_value( + OCCUPATION_WEIGHT_NAME)[0, :]) + # 'consultant' was ID-2 and now ID-1. + self.assertAllClose( + linear_classifier.get_variable_value(OCCUPATION_WEIGHT_NAME)[2, :], + warm_started_linear_classifier.get_variable_value( + OCCUPATION_WEIGHT_NAME)[1, :]) + # 'engineer' is a new entry and should be initialized with the + # backup_initializer in VocabInfo. + self.assertAllClose([0.39] * 4, + warm_started_linear_classifier.get_variable_value( + OCCUPATION_WEIGHT_NAME)[2, :]) + # Bias should still be zero (from initialization logic). + self.assertAllClose( + [0.0] * 4, warm_started_linear_classifier.get_variable_value(BIAS_NAME)) + + def test_warm_starting_with_naming_change(self): + """Tests warm-starting with a Tensor name remapping.""" + age_in_years = self._fc_lib.numeric_column('age_in_years') + + # Create a LinearClassifier and train to save a checkpoint. + linear_classifier = self._linear_classifier_fn( + feature_columns=[age_in_years], + model_dir=self._ckpt_and_vocab_dir, + n_classes=4, + optimizer='SGD') + linear_classifier.train(input_fn=self._input_fn, max_steps=1) + + # Create a second LinearClassifier, warm-started from the first. Use a + # learning_rate = 0.0 optimizer to check values (use SGD so we don't have + # accumulator values that change). + warm_started_linear_classifier = self._linear_classifier_fn( + feature_columns=[self._fc_lib.numeric_column('age')], + n_classes=4, + optimizer=tf.compat.v1.train.GradientDescentOptimizer( + learning_rate=0.0), + # The 'age' variable correspond to the 'age_in_years' variable in the + # previous model. + warm_start_from=estimator.WarmStartSettings( + ckpt_to_initialize_from=linear_classifier.model_dir, + var_name_to_prev_var_name={ + AGE_WEIGHT_NAME: AGE_WEIGHT_NAME.replace('age', 'age_in_years') + })) + + warm_started_linear_classifier.train(input_fn=self._input_fn, max_steps=1) + self.assertAllClose( + linear_classifier.get_variable_value( + AGE_WEIGHT_NAME.replace('age', 'age_in_years')), + warm_started_linear_classifier.get_variable_value(AGE_WEIGHT_NAME)) + # The bias is also warm-started (with no name remapping). + self.assertAllClose( + linear_classifier.get_variable_value(BIAS_NAME), + warm_started_linear_classifier.get_variable_value(BIAS_NAME)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/early_stopping.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/early_stopping.py new file mode 100644 index 0000000000000000000000000000000000000000..731703636bec0d7982f92655973236c991115887 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/early_stopping.py @@ -0,0 +1,592 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Utilities for early stopping.""" + +import collections +import operator +import os + +import tensorflow as tf +from tensorflow_estimator.python.estimator import estimator as estimator_lib +from tensorflow_estimator.python.estimator.estimator_export import estimator_export + + +_EVENT_FILE_GLOB_PATTERN = 'events.out.tfevents.*' + + +@estimator_export('estimator.experimental.make_early_stopping_hook') +def make_early_stopping_hook(estimator, + should_stop_fn, + run_every_secs=60, + run_every_steps=None): + """Creates early-stopping hook. + + Returns a `SessionRunHook` that stops training when `should_stop_fn` returns + `True`. + + Usage example: + + ```python + estimator = ... + hook = early_stopping.make_early_stopping_hook( + estimator, should_stop_fn=make_stop_fn(...)) + train_spec = tf.estimator.TrainSpec(..., hooks=[hook]) + tf.estimator.train_and_evaluate(estimator, train_spec, ...) + ``` + + Caveat: Current implementation supports early-stopping both training and + evaluation in local mode. In distributed mode, training can be stopped but + evaluation (where it's a separate job) will indefinitely wait for new model + checkpoints to evaluate, so you will need other means to detect and stop it. + Early-stopping evaluation in distributed mode requires changes in + `train_and_evaluate` API and will be addressed in a future revision. + + Args: + estimator: A `tf.estimator.Estimator` instance. + should_stop_fn: `callable`, function that takes no arguments and returns a + `bool`. If the function returns `True`, stopping will be initiated by the + chief. + run_every_secs: If specified, calls `should_stop_fn` at an interval of + `run_every_secs` seconds. Defaults to 60 seconds. Either this or + `run_every_steps` must be set. + run_every_steps: If specified, calls `should_stop_fn` every + `run_every_steps` steps. Either this or `run_every_secs` must be set. + + Returns: + A `SessionRunHook` that periodically executes `should_stop_fn` and initiates + early stopping if the function returns `True`. + + Raises: + TypeError: If `estimator` is not of type `tf.estimator.Estimator`. + ValueError: If both `run_every_secs` and `run_every_steps` are set. + """ + if not isinstance(estimator, estimator_lib.Estimator): + raise TypeError('`estimator` must have type `tf.estimator.Estimator`. ' + 'Got: {}'.format(type(estimator))) + + if run_every_secs is not None and run_every_steps is not None: + raise ValueError('Only one of `run_every_secs` and `run_every_steps` must ' + 'be set.') + + train_distribute = estimator.config.train_distribute + mwms = ['CollectiveAllReduceStrategy', 'MultiWorkerMirroredStrategy'] + if train_distribute and (train_distribute.__class__.__name__.startswith( + strategy) for strategy in mwms): + if run_every_secs: + raise ValueError('run_every_secs should not be set when using ' + 'MultiWorkerMirroredStrategy.') + return _MultiWorkerEarlyStoppingHook(should_stop_fn, run_every_steps) + + if estimator.config.is_chief: + return _StopOnPredicateHook(should_stop_fn, run_every_secs, run_every_steps) + else: + return _CheckForStoppingHook() + + +@estimator_export('estimator.experimental.stop_if_higher_hook') +def stop_if_higher_hook(estimator, + metric_name, + threshold, + eval_dir=None, + min_steps=0, + run_every_secs=60, + run_every_steps=None): + """Creates hook to stop if the given metric is higher than the threshold. + + Usage example: + + ```python + estimator = ... + # Hook to stop training if accuracy becomes higher than 0.9. + hook = early_stopping.stop_if_higher_hook(estimator, "accuracy", 0.9) + train_spec = tf.estimator.TrainSpec(..., hooks=[hook]) + tf.estimator.train_and_evaluate(estimator, train_spec, ...) + ``` + + Caveat: Current implementation supports early-stopping both training and + evaluation in local mode. In distributed mode, training can be stopped but + evaluation (where it's a separate job) will indefinitely wait for new model + checkpoints to evaluate, so you will need other means to detect and stop it. + Early-stopping evaluation in distributed mode requires changes in + `train_and_evaluate` API and will be addressed in a future revision. + + Args: + estimator: A `tf.estimator.Estimator` instance. + metric_name: `str`, metric to track. "loss", "accuracy", etc. + threshold: Numeric threshold for the given metric. + eval_dir: If set, directory containing summary files with eval metrics. By + default, `estimator.eval_dir()` will be used. + min_steps: `int`, stop is never requested if global step is less than this + value. Defaults to 0. + run_every_secs: If specified, calls `should_stop_fn` at an interval of + `run_every_secs` seconds. Defaults to 60 seconds. Either this or + `run_every_steps` must be set. + run_every_steps: If specified, calls `should_stop_fn` every + `run_every_steps` steps. Either this or `run_every_secs` must be set. + + Returns: + An early-stopping hook of type `SessionRunHook` that periodically checks + if the given metric is higher than specified threshold and initiates + early stopping if true. + """ + return _stop_if_threshold_crossed_hook( + estimator=estimator, + metric_name=metric_name, + threshold=threshold, + higher_is_better=True, + eval_dir=eval_dir, + min_steps=min_steps, + run_every_secs=run_every_secs, + run_every_steps=run_every_steps) + + +@estimator_export('estimator.experimental.stop_if_lower_hook') +def stop_if_lower_hook(estimator, + metric_name, + threshold, + eval_dir=None, + min_steps=0, + run_every_secs=60, + run_every_steps=None): + """Creates hook to stop if the given metric is lower than the threshold. + + Usage example: + + ```python + estimator = ... + # Hook to stop training if loss becomes lower than 100. + hook = early_stopping.stop_if_lower_hook(estimator, "loss", 100) + train_spec = tf.estimator.TrainSpec(..., hooks=[hook]) + tf.estimator.train_and_evaluate(estimator, train_spec, ...) + ``` + + Caveat: Current implementation supports early-stopping both training and + evaluation in local mode. In distributed mode, training can be stopped but + evaluation (where it's a separate job) will indefinitely wait for new model + checkpoints to evaluate, so you will need other means to detect and stop it. + Early-stopping evaluation in distributed mode requires changes in + `train_and_evaluate` API and will be addressed in a future revision. + + Args: + estimator: A `tf.estimator.Estimator` instance. + metric_name: `str`, metric to track. "loss", "accuracy", etc. + threshold: Numeric threshold for the given metric. + eval_dir: If set, directory containing summary files with eval metrics. By + default, `estimator.eval_dir()` will be used. + min_steps: `int`, stop is never requested if global step is less than this + value. Defaults to 0. + run_every_secs: If specified, calls `should_stop_fn` at an interval of + `run_every_secs` seconds. Defaults to 60 seconds. Either this or + `run_every_steps` must be set. + run_every_steps: If specified, calls `should_stop_fn` every + `run_every_steps` steps. Either this or `run_every_secs` must be set. + + Returns: + An early-stopping hook of type `SessionRunHook` that periodically checks + if the given metric is lower than specified threshold and initiates + early stopping if true. + """ + return _stop_if_threshold_crossed_hook( + estimator=estimator, + metric_name=metric_name, + threshold=threshold, + higher_is_better=False, + eval_dir=eval_dir, + min_steps=min_steps, + run_every_secs=run_every_secs, + run_every_steps=run_every_steps) + + +@estimator_export('estimator.experimental.stop_if_no_increase_hook') +def stop_if_no_increase_hook(estimator, + metric_name, + max_steps_without_increase, + eval_dir=None, + min_steps=0, + run_every_secs=60, + run_every_steps=None): + """Creates hook to stop if metric does not increase within given max steps. + + Usage example: + + ```python + estimator = ... + # Hook to stop training if accuracy does not increase in over 100000 steps. + hook = early_stopping.stop_if_no_increase_hook(estimator, "accuracy", 100000) + train_spec = tf.estimator.TrainSpec(..., hooks=[hook]) + tf.estimator.train_and_evaluate(estimator, train_spec, ...) + ``` + + Caveat: Current implementation supports early-stopping both training and + evaluation in local mode. In distributed mode, training can be stopped but + evaluation (where it's a separate job) will indefinitely wait for new model + checkpoints to evaluate, so you will need other means to detect and stop it. + Early-stopping evaluation in distributed mode requires changes in + `train_and_evaluate` API and will be addressed in a future revision. + + Args: + estimator: A `tf.estimator.Estimator` instance. + metric_name: `str`, metric to track. "loss", "accuracy", etc. + max_steps_without_increase: `int`, maximum number of training steps with no + increase in the given metric. + eval_dir: If set, directory containing summary files with eval metrics. By + default, `estimator.eval_dir()` will be used. + min_steps: `int`, stop is never requested if global step is less than this + value. Defaults to 0. + run_every_secs: If specified, calls `should_stop_fn` at an interval of + `run_every_secs` seconds. Defaults to 60 seconds. Either this or + `run_every_steps` must be set. + run_every_steps: If specified, calls `should_stop_fn` every + `run_every_steps` steps. Either this or `run_every_secs` must be set. + + Returns: + An early-stopping hook of type `SessionRunHook` that periodically checks + if the given metric shows no increase over given maximum number of + training steps, and initiates early stopping if true. + """ + return _stop_if_no_metric_improvement_hook( + estimator=estimator, + metric_name=metric_name, + max_steps_without_improvement=max_steps_without_increase, + higher_is_better=True, + eval_dir=eval_dir, + min_steps=min_steps, + run_every_secs=run_every_secs, + run_every_steps=run_every_steps) + + +@estimator_export('estimator.experimental.stop_if_no_decrease_hook') +def stop_if_no_decrease_hook(estimator, + metric_name, + max_steps_without_decrease, + eval_dir=None, + min_steps=0, + run_every_secs=60, + run_every_steps=None): + """Creates hook to stop if metric does not decrease within given max steps. + + Usage example: + + ```python + estimator = ... + # Hook to stop training if loss does not decrease in over 100000 steps. + hook = early_stopping.stop_if_no_decrease_hook(estimator, "loss", 100000) + train_spec = tf.estimator.TrainSpec(..., hooks=[hook]) + tf.estimator.train_and_evaluate(estimator, train_spec, ...) + ``` + + Caveat: Current implementation supports early-stopping both training and + evaluation in local mode. In distributed mode, training can be stopped but + evaluation (where it's a separate job) will indefinitely wait for new model + checkpoints to evaluate, so you will need other means to detect and stop it. + Early-stopping evaluation in distributed mode requires changes in + `train_and_evaluate` API and will be addressed in a future revision. + + Args: + estimator: A `tf.estimator.Estimator` instance. + metric_name: `str`, metric to track. "loss", "accuracy", etc. + max_steps_without_decrease: `int`, maximum number of training steps with no + decrease in the given metric. + eval_dir: If set, directory containing summary files with eval metrics. By + default, `estimator.eval_dir()` will be used. + min_steps: `int`, stop is never requested if global step is less than this + value. Defaults to 0. + run_every_secs: If specified, calls `should_stop_fn` at an interval of + `run_every_secs` seconds. Defaults to 60 seconds. Either this or + `run_every_steps` must be set. + run_every_steps: If specified, calls `should_stop_fn` every + `run_every_steps` steps. Either this or `run_every_secs` must be set. + + Returns: + An early-stopping hook of type `SessionRunHook` that periodically checks + if the given metric shows no decrease over given maximum number of + training steps, and initiates early stopping if true. + """ + return _stop_if_no_metric_improvement_hook( + estimator=estimator, + metric_name=metric_name, + max_steps_without_improvement=max_steps_without_decrease, + higher_is_better=False, + eval_dir=eval_dir, + min_steps=min_steps, + run_every_secs=run_every_secs, + run_every_steps=run_every_steps) + + +def read_eval_metrics(eval_dir): + """Helper to read eval metrics from eval summary files. + + Args: + eval_dir: Directory containing summary files with eval metrics. + + Returns: + A `dict` with global steps mapping to `dict` of metric names and values. + """ + eval_metrics_dict = collections.defaultdict(dict) + for event in _summaries(eval_dir): + if not event.HasField('summary'): + continue + metrics = {} + for value in event.summary.value: + if value.HasField('simple_value'): + metrics[value.tag] = value.simple_value + if metrics: + eval_metrics_dict[event.step].update(metrics) + return collections.OrderedDict( + sorted(eval_metrics_dict.items(), key=lambda t: t[0])) + + +def _stop_if_threshold_crossed_hook(estimator, metric_name, threshold, + higher_is_better, eval_dir, min_steps, + run_every_secs, run_every_steps): + """Creates early-stopping hook to stop training if threshold is crossed.""" + + if eval_dir is None: + eval_dir = estimator.eval_dir() + + is_lhs_better = operator.gt if higher_is_better else operator.lt + greater_or_lesser = 'greater than' if higher_is_better else 'less than' + + def stop_if_threshold_crossed_fn(): + """Returns `True` if the given metric crosses specified threshold.""" + + eval_results = read_eval_metrics(eval_dir) + + for step, metrics in eval_results.items(): + if step < min_steps: + continue + val = metrics[metric_name] + if is_lhs_better(val, threshold): + tf.compat.v1.logging.info( + 'At step %s, metric "%s" has value %s which is %s the configured ' + 'threshold (%s) for early stopping.', step, metric_name, val, + greater_or_lesser, threshold) + return True + return False + + return make_early_stopping_hook( + estimator=estimator, + should_stop_fn=stop_if_threshold_crossed_fn, + run_every_secs=run_every_secs, + run_every_steps=run_every_steps) + + +def _stop_if_no_metric_improvement_hook(estimator, metric_name, + max_steps_without_improvement, + higher_is_better, eval_dir, min_steps, + run_every_secs, run_every_steps): + """Returns hook to stop training if given metric shows no improvement.""" + + if eval_dir is None: + eval_dir = estimator.eval_dir() + + is_lhs_better = operator.gt if higher_is_better else operator.lt + increase_or_decrease = 'increase' if higher_is_better else 'decrease' + + def stop_if_no_metric_improvement_fn(): + """Returns `True` if metric does not improve within max steps.""" + + eval_results = read_eval_metrics(eval_dir) + + best_val = None + best_val_step = None + for step, metrics in eval_results.items(): + if step < min_steps: + continue + val = metrics[metric_name] + if best_val is None or is_lhs_better(val, best_val): + best_val = val + best_val_step = step + if step - best_val_step >= max_steps_without_improvement: + tf.compat.v1.logging.info( + 'No %s in metric "%s" for %s steps, which is greater than or equal ' + 'to max steps (%s) configured for early stopping.', + increase_or_decrease, metric_name, step - best_val_step, + max_steps_without_improvement) + return True + return False + + return make_early_stopping_hook( + estimator=estimator, + should_stop_fn=stop_if_no_metric_improvement_fn, + run_every_secs=run_every_secs, + run_every_steps=run_every_steps) + + +def _summaries(eval_dir): + """Yields `tensorflow.Event` protos from event files in the eval dir. + + Args: + eval_dir: Directory containing summary files with eval metrics. + + Yields: + `tensorflow.Event` object read from the event files. + """ + if tf.compat.v1.gfile.Exists(eval_dir): + for event_file in tf.compat.v1.gfile.Glob( + os.path.join(eval_dir, _EVENT_FILE_GLOB_PATTERN)): + try: + for event in tf.compat.v1.train.summary_iterator(event_file): + yield event + except tf.errors.DataLossError as e: + # Upon DataLossError, we ignore the rest of the file and go to the next + # one. + tf.compat.v1.logging.warning( + 'Skipping rest of the file due to encountering data corruption ' + 'error; file path: %s; original error raised by ' + '`tf.train.summary_iterator`: %s', event_file, e) + + +def _get_or_create_stop_var(): + with tf.compat.v1.variable_scope( + name_or_scope='signal_early_stopping', + values=[], + reuse=tf.compat.v1.AUTO_REUSE): + return tf.compat.v1.get_variable( + name='STOP', + shape=[], + dtype=tf.dtypes.bool, + initializer=tf.compat.v1.initializers.constant(False), + collections=[tf.compat.v1.GraphKeys.GLOBAL_VARIABLES], + trainable=False) + + +class _StopOnPredicateHook(tf.compat.v1.train.SessionRunHook): + """Hook that requests stop when `should_stop_fn` returns `True`.""" + + def __init__(self, should_stop_fn, run_every_secs=60, run_every_steps=None): + if not callable(should_stop_fn): + raise TypeError('`should_stop_fn` must be callable.') + + self._should_stop_fn = should_stop_fn + self._timer = tf.compat.v1.train.SecondOrStepTimer( + every_secs=run_every_secs, every_steps=run_every_steps) + self._global_step_tensor = None + self._stop_var = None + self._stop_op = None + + def begin(self): + self._global_step_tensor = tf.compat.v1.train.get_global_step() + self._stop_var = _get_or_create_stop_var() + self._stop_op = tf.compat.v1.assign(self._stop_var, True) + + def before_run(self, run_context): + del run_context + return tf.compat.v1.train.SessionRunArgs(self._global_step_tensor) + + def after_run(self, run_context, run_values): + global_step = run_values.results + if self._timer.should_trigger_for_step(global_step): + self._timer.update_last_triggered_step(global_step) + if self._should_stop_fn(): + tf.compat.v1.logging.info('Requesting early stopping at global step %d', + global_step) + run_context.session.run(self._stop_op) + run_context.request_stop() + + +class _CheckForStoppingHook(tf.compat.v1.train.SessionRunHook): + """Hook that requests stop if stop is requested by `_StopOnPredicateHook`.""" + + def __init__(self): + self._stop_var = None + + def begin(self): + self._stop_var = _get_or_create_stop_var() + + def before_run(self, run_context): + del run_context + return tf.compat.v1.train.SessionRunArgs(self._stop_var) + + def after_run(self, run_context, run_values): + should_early_stop = run_values.results + if should_early_stop: + tf.compat.v1.logging.info('Early stopping requested, suspending run.') + run_context.request_stop() + + +class _MultiWorkerEarlyStoppingHook(tf.compat.v1.train.SessionRunHook): + """Hook that requests stop when `should_stop_fn` returns `True`.""" + + def _get_or_create_stop_var_with_aggregation(self): + with tf.compat.v1.variable_scope( + name_or_scope='signal_early_stopping', + values=[], + reuse=tf.compat.v1.AUTO_REUSE): + return tf.compat.v1.get_variable( + name='STOP', + shape=[], + dtype=tf.dtypes.int32, + initializer=tf.compat.v1.keras.initializers.constant(0), + collections=[tf.compat.v1.GraphKeys.GLOBAL_VARIABLES], + synchronization=tf.VariableSynchronization.ON_WRITE, + aggregation=tf.compat.v1.VariableAggregation.SUM, + trainable=False) + + def __init__(self, should_stop_fn, run_every_steps=None): + if not callable(should_stop_fn): + raise TypeError('`should_stop_fn` must be callable.') + + self._should_stop_fn = should_stop_fn + self._timer = tf.compat.v1.train.SecondOrStepTimer( + every_secs=None, every_steps=run_every_steps) + self._global_step_tensor = None + self._stop_var = None + self._stop_op = None + self._non_stop_op = None + + def begin(self): + self._global_step_tensor = tf.compat.v1.train.get_global_step() + self._stop_var = self._get_or_create_stop_var_with_aggregation() + assert tf.distribute.in_cross_replica_context() + + strategy = tf.distribute.get_strategy() + self._stop_placeholder = None + + def stop_op_fn(var): + placeholder = tf.compat.v1.placeholder_with_default( + 0, tuple(), name='stop_value') + if self._stop_placeholder is None: + self._stop_placeholder = placeholder + return var.assign_add(placeholder) + + self._stop_op = strategy.run( + stop_op_fn, args=(self._stop_var,)) + + def before_run(self, run_context): + del run_context + return tf.compat.v1.train.SessionRunArgs({ + 'global_step': self._global_step_tensor, + 'stop_var': self._stop_var + }) + + def after_run(self, run_context, run_values): + global_step = run_values.results['global_step'] + should_early_stop = run_values.results['stop_var'] + + if should_early_stop > 0: + tf.compat.v1.logging.info('Early stopping requested, suspending run.') + run_context.request_stop() + return + if self._timer.should_trigger_for_step(global_step): + self._timer.update_last_triggered_step(global_step) + if self._should_stop_fn(): + run_context.session.run( + self._stop_op, feed_dict={self._stop_placeholder: 1}) + tf.compat.v1.logging.info('Requesting early stopping at global step %d', + global_step) + else: + run_context.session.run( + self._stop_op, feed_dict={self._stop_placeholder: 0}) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/estimator.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/estimator.py new file mode 100644 index 0000000000000000000000000000000000000000..807a4c80a4c5856137952e68b996710ee26cb2b7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/estimator.py @@ -0,0 +1,2409 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Base Estimator class.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import collections +import copy +import os +import tempfile + +import numpy as np +import six +import tensorflow as tf +from google.protobuf import message +from tensorflow.core.framework import summary_pb2 +from tensorflow.python.checkpoint import checkpoint as trackable_util +from tensorflow.python.checkpoint import checkpoint_management +from tensorflow.python.checkpoint import graph_view +from tensorflow.python.distribute import estimator_training as distribute_coordinator_training +from tensorflow.python.eager import context +from tensorflow.python.eager import monitoring +from tensorflow.python.framework import ops +from tensorflow.python.profiler import trace +from tensorflow.python.saved_model import path_helpers +from tensorflow.python.summary import summary +from tensorflow.python.training import basic_session_run_hooks +from tensorflow.python.training import device_setter +from tensorflow.python.training import evaluation +from tensorflow.python.training import training +from tensorflow.python.training import training_util +from tensorflow.python.util import deprecation +from tensorflow.python.util import function_utils +from tensorflow.python.util import tf_contextlib +from tensorflow.tools.docs import doc_controls +from tensorflow_estimator.python.estimator import model_fn as model_fn_lib +from tensorflow_estimator.python.estimator import run_config +from tensorflow_estimator.python.estimator import util as estimator_util +from tensorflow_estimator.python.estimator.estimator_export import estimator_export +from tensorflow_estimator.python.estimator.export import export_lib +from tensorflow_estimator.python.estimator.mode_keys import ModeKeys + +_VALID_MODEL_FN_ARGS = set( + ['features', 'labels', 'mode', 'params', 'self', 'config']) +_estimator_api_gauge = monitoring.BoolGauge('/tensorflow/api/estimator', + 'estimator api usage', 'method') + +_canned_estimator_api_gauge = monitoring.StringGauge( + '/tensorflow/api/estimator/canned_estimator', + 'Gauge to track the type of canned estimator used', 'ClassType') + + +@estimator_export(v1=['estimator.Estimator']) +@doc_controls.inheritable_header("""\ + Warning: Estimators are not recommended for new code. Estimators run + `v1.Session`-style code which is more difficult to write correctly, and + can behave unexpectedly, especially when combined with TF 2 code. Estimators + do fall under our + [compatibility guarantees](https://tensorflow.org/guide/versions), but will + receive no fixes other than security vulnerabilities. See the + [migration guide](https://tensorflow.org/guide/migrate) for details. + """) +class Estimator(object): + """Estimator class to train and evaluate TensorFlow models. + + The `Estimator` object wraps a model which is specified by a `model_fn`, + which, given inputs and a number of other parameters, returns the ops + necessary to perform training, evaluation, or predictions. + + All outputs (checkpoints, event files, etc.) are written to `model_dir`, or a + subdirectory thereof. If `model_dir` is not set, a temporary directory is + used. + + The `config` argument can be passed `tf.estimator.RunConfig` object containing + information about the execution environment. It is passed on to the + `model_fn`, if the `model_fn` has a parameter named "config" (and input + functions in the same manner). If the `config` parameter is not passed, it is + instantiated by the `Estimator`. Not passing config means that defaults useful + for local execution are used. `Estimator` makes config available to the model + (for instance, to allow specialization based on the number of workers + available), and also uses some of its fields to control internals, especially + regarding checkpointing. + + The `params` argument contains hyperparameters. It is passed to the + `model_fn`, if the `model_fn` has a parameter named "params", and to the input + functions in the same manner. `Estimator` only passes params along, it does + not inspect it. The structure of `params` is therefore entirely up to the + developer. + + None of `Estimator`'s methods can be overridden in subclasses (its + constructor enforces this). Subclasses should use `model_fn` to configure + the base class, and may add methods implementing specialized functionality. + + See [estimators](https://tensorflow.org/guide/estimator) for more + information. + + To warm-start an `Estimator`: + + ```python + estimator = tf.estimator.DNNClassifier( + feature_columns=[categorical_feature_a_emb, categorical_feature_b_emb], + hidden_units=[1024, 512, 256], + warm_start_from="/path/to/checkpoint/dir") + ``` + + For more details on warm-start configuration, see + `tf.estimator.WarmStartSettings`. + + @compatibility(eager) + Calling methods of `Estimator` will work while eager execution is enabled. + However, the `model_fn` and `input_fn` is not executed eagerly, `Estimator` + will switch to graph mode before calling all user-provided functions (incl. + hooks), so their code has to be compatible with graph mode execution. Note + that `input_fn` code using `tf.data` generally works in both graph and eager + modes. + @end_compatibility + """ + + def __init__(self, + model_fn, + model_dir=None, + config=None, + params=None, + warm_start_from=None): + """Constructs an `Estimator` instance. + + + + Args: + model_fn: Model function. Follows the signature: + * `features` -- This is the first item returned from the `input_fn` + passed to `train`, `evaluate`, and `predict`. This should be a + single `tf.Tensor` or `dict` of same. + * `labels` -- This is the second item returned from the `input_fn` + passed to `train`, `evaluate`, and `predict`. This should be a + single `tf.Tensor` or `dict` of same (for multi-head models). If + mode is `tf.estimator.ModeKeys.PREDICT`, `labels=None` will be + passed. If the `model_fn`'s signature does not accept `mode`, the + `model_fn` must still be able to handle `labels=None`. + * `mode` -- Optional. Specifies if this is training, evaluation or + prediction. See `tf.estimator.ModeKeys`. + `params` -- Optional `dict` of hyperparameters. Will receive what is + passed to Estimator in `params` parameter. This allows to configure + Estimators from hyper parameter tuning. + * `config` -- Optional `estimator.RunConfig` object. Will receive what + is passed to Estimator as its `config` parameter, or a default + value. Allows setting up things in your `model_fn` based on + configuration such as `num_ps_replicas`, or `model_dir`. + * Returns -- `tf.estimator.EstimatorSpec` + model_dir: Directory to save model parameters, graph and etc. This can + also be used to load checkpoints from the directory into an estimator to + continue training a previously saved model. If `PathLike` object, the + path will be resolved. If `None`, the model_dir in `config` will be used + if set. If both are set, they must be same. If both are `None`, a + temporary directory will be used. + config: `estimator.RunConfig` configuration object. + params: `dict` of hyper parameters that will be passed into `model_fn`. + Keys are names of parameters, values are basic python types. + warm_start_from: Optional string filepath to a checkpoint or SavedModel to + warm-start from, or a `tf.estimator.WarmStartSettings` object to fully + configure warm-starting. If None, only TRAINABLE variables are + warm-started. If the string filepath is provided instead of a + `tf.estimator.WarmStartSettings`, then all variables are warm-started, + and it is assumed that vocabularies and `tf.Tensor` names are unchanged. + + Raises: + ValueError: parameters of `model_fn` don't match `params`. + ValueError: if this is called via a subclass and if that class overrides + a member of `Estimator`. + """ + _estimator_api_gauge.get_cell('init').set(True) + # We do not endorse Estimator child classes to override methods in + # Estimator, other than a select few. You're on your own if you cleverly + # override the method "_assert_members_are_not_overridden". + self.__class__._assert_members_are_not_overridden(self) # pylint: disable=protected-access + + self._config = maybe_overwrite_model_dir_and_session_config( + config, model_dir) + + # The distribute field contains an instance of tf.distribute.Strategy. + self._train_distribution = self._config.train_distribute + self._eval_distribution = self._config.eval_distribute + # Model directory. + self._model_dir = self._config.model_dir + self._session_config = self._config.session_config + tf.compat.v1.logging.info('Using config: %s', str(vars(self._config))) + + self._device_fn = ( + self._config.device_fn or _get_replica_device_setter(self._config)) + + if model_fn is None: + raise ValueError('model_fn must be provided to Estimator.') + model_fn_lib.verify_model_fn_args(model_fn, params) + self._model_fn = model_fn + self._params = copy.deepcopy(params or {}) + + # pylint: disable=protected-access + self._warm_start_settings = _get_default_warm_start_settings( + warm_start_from) + # pylint: enable=protected-access + + @property + def model_dir(self): + return self._model_dir + + @property + def config(self): + return copy.deepcopy(self._config) + + @property + def params(self): + return copy.deepcopy(self._params) + + @property + def model_fn(self): + """Returns the `model_fn` which is bound to `self.params`. + + Returns: + The `model_fn` with following signature: + `def model_fn(features, labels, mode, config)` + """ + + def public_model_fn(features, labels, mode, config): + return self._call_model_fn(features, labels, mode, config) + + return public_model_fn + + # TODO(ispir): support a list of names + def get_variable_value(self, name): + """Returns value of the variable given by name. + + Args: + name: string or a list of string, name of the tensor. + + Returns: + Numpy array - value of the tensor. + + Raises: + ValueError: If the `Estimator` has not produced a checkpoint yet. + """ + _check_checkpoint_available(self.model_dir) + with context.graph_mode(): + return tf.train.load_variable(self.model_dir, name) + + def get_variable_names(self): + """Returns list of all variable names in this model. + + Returns: + List of names. + + Raises: + ValueError: If the `Estimator` has not produced a checkpoint yet. + """ + _check_checkpoint_available(self.model_dir) + with context.graph_mode(): + return [name for name, _ in tf.train.list_variables(self.model_dir)] + + def latest_checkpoint(self): + """Finds the filename of the latest saved checkpoint file in `model_dir`. + + Returns: + The full path to the latest checkpoint or `None` if no checkpoint was + found. + """ + with context.graph_mode(): + return checkpoint_management.latest_checkpoint(self.model_dir) + + def train(self, + input_fn, + hooks=None, + steps=None, + max_steps=None, + saving_listeners=None): + """Trains a model given training data `input_fn`. + + Args: + input_fn: A function that provides input data for training as minibatches. + See [Premade Estimators]( + https://tensorflow.org/guide/premade_estimators#create_input_functions) + for more information. The function should construct and return one of + the following: + * A `tf.data.Dataset` object: Outputs of `Dataset` object must be a + tuple `(features, labels)` with same constraints as below. + * A tuple `(features, labels)`: Where `features` is a `tf.Tensor` or a + dictionary of string feature name to `Tensor` and `labels` is a + `Tensor` or a dictionary of string label name to `Tensor`. Both + `features` and `labels` are consumed by `model_fn`. They should + satisfy the expectation of `model_fn` from inputs. + hooks: List of `tf.train.SessionRunHook` subclass instances. Used for + callbacks inside the training loop. + steps: Number of steps for which to train the model. If `None`, train + forever or train until `input_fn` generates the `tf.errors.OutOfRange` + error or `StopIteration` exception. `steps` works incrementally. If you + call two times `train(steps=10)` then training occurs in total 20 steps. + If `OutOfRange` or `StopIteration` occurs in the middle, training stops + before 20 steps. If you don't want to have incremental behavior please + set `max_steps` instead. If set, `max_steps` must be `None`. + max_steps: Number of total steps for which to train model. If `None`, + train forever or train until `input_fn` generates the + `tf.errors.OutOfRange` error or `StopIteration` exception. If set, + `steps` must be `None`. If `OutOfRange` or `StopIteration` occurs in the + middle, training stops before `max_steps` steps. Two calls to + `train(steps=100)` means 200 training iterations. On the other hand, two + calls to `train(max_steps=100)` means that the second call will not do + any iteration since first call did all 100 steps. + saving_listeners: list of `CheckpointSaverListener` objects. Used for + callbacks that run immediately before or after checkpoint savings. + + Returns: + `self`, for chaining. + + Raises: + ValueError: If both `steps` and `max_steps` are not `None`. + ValueError: If either `steps` or `max_steps <= 0`. + """ + _estimator_api_gauge.get_cell('train').set(True) + if self.config.task_type in (run_config.TaskType.EVALUATOR, + run_config.TaskType.PS): + raise ValueError( + 'Train has been called wrong configuration. Please use ' + 'tf.estimator.train_and_evaluate which calls proper API according ' + 'to given configuration. Current configuration: {}.'.format( + self.config)) + + with context.graph_mode(): + if (steps is not None) and (max_steps is not None): + raise ValueError('Can not provide both steps and max_steps.') + if steps is not None and steps <= 0: + raise ValueError('Must specify steps > 0, given: {}'.format(steps)) + if max_steps is not None and max_steps <= 0: + raise ValueError( + 'Must specify max_steps > 0, given: {}'.format(max_steps)) + + if max_steps is not None: + start_step = _load_global_step_from_checkpoint_dir(self._model_dir) + if max_steps <= start_step: + tf.compat.v1.logging.info( + 'Skipping training since max_steps has already saved.' + ) + return self + + hooks = _check_hooks_type(hooks) + hooks.extend(self._convert_train_steps_to_hooks(steps, max_steps)) + + saving_listeners = _check_listeners_type(saving_listeners) + loss = self._train_model(input_fn, hooks, saving_listeners) + tf.compat.v1.logging.info('Loss for final step: %s.', loss) + return self + + def _convert_train_steps_to_hooks(self, steps, max_steps): + """Create hooks to run correct number of steps in training. + + Args: + steps: number of steps to run during training. + max_steps: maximum number of steps to be run during training. It'll be the + maximum number of steps the model will train to after restoring from + checkpoint even across multiple estimator.train calls. + + Returns: + List of hooks to be passed to the estimator. + """ + if steps is not None or max_steps is not None: + if self._train_distribution: + steps_per_run = getattr(self._train_distribution.extended, + 'steps_per_run', 1) + if steps_per_run > 1: + return [ + basic_session_run_hooks._MultiStepStopAtStepHook( # pylint: disable=protected-access + steps, max_steps, steps_per_run) + ] + return [tf.compat.v1.train.StopAtStepHook(steps, max_steps)] + else: + return [] + + def eval_dir(self, name=None): + """Shows the directory name where evaluation metrics are dumped. + + Args: + name: Name of the evaluation if user needs to run multiple evaluations on + different data sets, such as on training data vs test data. Metrics for + different evaluations are saved in separate folders, and appear + separately in tensorboard. + + Returns: + A string which is the path of directory contains evaluation metrics. + """ + return os.path.join(self._model_dir, 'eval' if not name else 'eval_' + name) + + def evaluate(self, + input_fn, + steps=None, + hooks=None, + checkpoint_path=None, + name=None): + """Evaluates the model given evaluation data `input_fn`. + + For each step, calls `input_fn`, which returns one batch of data. + Evaluates until: + - `steps` batches are processed, or + - `input_fn` raises an end-of-input exception (`tf.errors.OutOfRangeError` + or `StopIteration`). + + Args: + input_fn: A function that constructs the input data for evaluation. See + [Premade Estimators]( + https://tensorflow.org/guide/premade_estimators#create_input_functions) + for more information. The function should construct and return one of + the following: + * A `tf.data.Dataset` object: Outputs of `Dataset` object must be a + tuple `(features, labels)` with same constraints as below. + * A tuple `(features, labels)`: Where `features` is a `tf.Tensor` or a + dictionary of string feature name to `Tensor` and `labels` is a + `Tensor` or a dictionary of string label name to `Tensor`. Both + `features` and `labels` are consumed by `model_fn`. They should + satisfy the expectation of `model_fn` from inputs. + steps: Number of steps for which to evaluate model. If `None`, evaluates + until `input_fn` raises an end-of-input exception. + hooks: List of `tf.train.SessionRunHook` subclass instances. Used for + callbacks inside the evaluation call. + checkpoint_path: Path of a specific checkpoint to evaluate. If `None`, the + latest checkpoint in `model_dir` is used. If there are no checkpoints + in `model_dir`, evaluation is run with newly initialized `Variables` + instead of ones restored from checkpoint. + name: Name of the evaluation if user needs to run multiple evaluations on + different data sets, such as on training data vs test data. Metrics for + different evaluations are saved in separate folders, and appear + separately in tensorboard. + + Returns: + A dict containing the evaluation metrics specified in `model_fn` keyed by + name, as well as an entry `global_step` which contains the value of the + global step for which this evaluation was performed. For canned + estimators, the dict contains the `loss` (mean loss per mini-batch) and + the `average_loss` (mean loss per sample). Canned classifiers also return + the `accuracy`. Canned regressors also return the `label/mean` and the + `prediction/mean`. + + Raises: + ValueError: If `steps <= 0`. + """ + _estimator_api_gauge.get_cell('evaluate').set(True) + # pylint: disable=protected-access + if (self._eval_distribution and + hasattr(self._config, '_distribute_coordinator_mode') and + self._config._distribute_coordinator_mode): + return distribute_coordinator_training.estimator_evaluate( + self, + lambda est, s, eval_hooks: est._actual_eval( # pylint: disable=g-long-lambda + input_fn, + strategy=s, + steps=steps, + hooks=eval_hooks, + checkpoint_path=checkpoint_path, + name=name), + hooks) + # pylint: enable=protected-access + else: + return self._actual_eval( + input_fn, + strategy=self._eval_distribution, + steps=steps, + hooks=hooks, + checkpoint_path=checkpoint_path, + name=name) + + def _actual_eval(self, + input_fn, + strategy=None, + steps=None, + hooks=None, + checkpoint_path=None, + name=None): + """The method that does evaluation actually.""" + with context.graph_mode(): + hooks = _check_hooks_type(hooks) + hooks.extend(self._convert_eval_steps_to_hooks(steps)) + + # Check that model has been trained (if nothing has been set explicitly). + if not checkpoint_path: + latest_path = checkpoint_management.latest_checkpoint(self._model_dir) + if not latest_path: + tf.compat.v1.logging.info( + 'Could not find trained model in model_dir: {}, running ' + 'initialization to evaluate.'.format(self._model_dir)) + checkpoint_path = latest_path + + def _evaluate(): + (scaffold, update_op, eval_dict, all_hooks) = ( + self._evaluate_build_graph(input_fn, hooks, checkpoint_path)) + return self._evaluate_run( + checkpoint_path=checkpoint_path, + scaffold=scaffold, + update_op=update_op, + eval_dict=eval_dict, + all_hooks=all_hooks, + output_dir=self.eval_dir(name)) + + with tf.Graph().as_default(): + if strategy: + # We want to create the iterations variable outside the distribution + # scope as that is just stored on the host and mainly used to drive + # the loop and doesn't need to be a Mirrored/Device variable. + training.get_or_create_steps_per_run_variable() + with strategy.scope(): + return _evaluate() + else: + return _evaluate() + + def _convert_eval_steps_to_hooks(self, steps): + """Create hooks to run correct number of steps in evaluation. + + Args: + steps: number of steps to run during evaluation. + + Raises: + ValueError: if steps is less than or equal to zero. + + Returns: + List of hooks to be passed to the estimator. + """ + if steps is None: + return [] + + if steps <= 0: + raise ValueError('Must specify steps > 0, given: {}'.format(steps)) + + # The hooks are declared as private in evaluation.py discourage the use + # by other libraries or open source users. This should be the only usage + # of the estimator evaluation hooks. + if self._eval_distribution: + steps_per_run = getattr(self._eval_distribution.extended, 'steps_per_run', + 1) + if steps_per_run > 1: + return [ + evaluation._MultiStepStopAfterNEvalsHook( # pylint: disable=protected-access + num_evals=steps, + steps_per_run=steps_per_run) + ] + return [evaluation._StopAfterNEvalsHook(num_evals=steps)] # pylint: disable=protected-access + + def predict(self, + input_fn, + predict_keys=None, + hooks=None, + checkpoint_path=None, + yield_single_examples=True): + """Yields predictions for given features. + + Please note that interleaving two predict outputs does not work. See: + [issue/20506]( + https://github.com/tensorflow/tensorflow/issues/20506#issuecomment-422208517) + + Args: + input_fn: A function that constructs the features. Prediction continues + until `input_fn` raises an end-of-input exception + (`tf.errors.OutOfRangeError` or `StopIteration`). See [Premade + Estimators]( + https://tensorflow.org/guide/premade_estimators#create_input_functions) + for more information. The function should construct and return one of + the following: + * `tf.data.Dataset` object -- Outputs of `Dataset` object must have + same constraints as below. + * features -- A `tf.Tensor` or a dictionary of string feature name to + `Tensor`. features are consumed by `model_fn`. They should satisfy + the expectation of `model_fn` from inputs. + * A tuple, in which case + the first item is extracted as features. + predict_keys: list of `str`, name of the keys to predict. It is used if + the `tf.estimator.EstimatorSpec.predictions` is a `dict`. If + `predict_keys` is used then rest of the predictions will be filtered + from the dictionary. If `None`, returns all. + hooks: List of `tf.train.SessionRunHook` subclass instances. Used for + callbacks inside the prediction call. + checkpoint_path: Path of a specific checkpoint to predict. If `None`, the + latest checkpoint in `model_dir` is used. If there are no checkpoints + in `model_dir`, prediction is run with newly initialized `Variables` + instead of ones restored from checkpoint. + yield_single_examples: If `False`, yields the whole batch as returned by + the `model_fn` instead of decomposing the batch into individual + elements. This is useful if `model_fn` returns some tensors whose first + dimension is not equal to the batch size. + + Yields: + Evaluated values of `predictions` tensors. + + Raises: + ValueError: If batch length of predictions is not the same and + `yield_single_examples` is `True`. + ValueError: If there is a conflict between `predict_keys` and + `predictions`. For example if `predict_keys` is not `None` but + `tf.estimator.EstimatorSpec.predictions` is not a `dict`. + """ + _estimator_api_gauge.get_cell('predict').set(True) + with context.graph_mode(): + hooks = _check_hooks_type(hooks) + # Check that model has been trained. + if not checkpoint_path: + checkpoint_path = checkpoint_management.latest_checkpoint( + self._model_dir) + if not checkpoint_path: + tf.compat.v1.logging.info( + 'Could not find trained model in model_dir: {}, running ' + 'initialization to predict.'.format(self._model_dir)) + with tf.Graph().as_default() as g: + tf.compat.v1.random.set_random_seed(self._config.tf_random_seed) + self._create_and_assert_global_step(g) + features, input_hooks = self._get_features_from_input_fn( + input_fn, ModeKeys.PREDICT) + estimator_spec = self._call_model_fn(features, None, ModeKeys.PREDICT, + self.config) + + # Call to warm_start has to be after model_fn is called. + self._maybe_warm_start(checkpoint_path) + + predictions = self._extract_keys(estimator_spec.predictions, + predict_keys) + all_hooks = list(input_hooks) + all_hooks.extend(hooks) + all_hooks.extend(list(estimator_spec.prediction_hooks or [])) + with tf.compat.v1.train.MonitoredSession( + session_creator=tf.compat.v1.train.ChiefSessionCreator( + checkpoint_filename_with_path=checkpoint_path, + master=self._config.master, + scaffold=estimator_spec.scaffold, + config=self._session_config), + hooks=all_hooks) as mon_sess: + while not mon_sess.should_stop(): + preds_evaluated = mon_sess.run(predictions) + if not yield_single_examples: + yield preds_evaluated + elif not isinstance(predictions, dict): + for pred in preds_evaluated: + yield pred + else: + for i in range(self._extract_batch_length(preds_evaluated)): + yield { + key: value[i] + for key, value in six.iteritems(preds_evaluated) + } + + def _assert_members_are_not_overridden(self): + """Asserts members of `Estimator` are not overridden.""" + _assert_members_are_not_overridden(Estimator, self) + + def export_saved_model(self, + export_dir_base, + serving_input_receiver_fn, + assets_extra=None, + as_text=False, + checkpoint_path=None, + experimental_mode=ModeKeys.PREDICT): + # pylint: disable=line-too-long + """Exports inference graph as a `SavedModel` into the given dir. + + For a detailed guide on SavedModel, see + [Using the SavedModel format] + (https://tensorflow.org/guide/saved_model#savedmodels_from_estimators). + + This method builds a new graph by first calling the + `serving_input_receiver_fn` to obtain feature `Tensor`s, and then calling + this `Estimator`'s `model_fn` to generate the model graph based on those + features. It restores the given checkpoint (or, lacking that, the most + recent checkpoint) into this graph in a fresh session. Finally it creates + a timestamped export directory below the given `export_dir_base`, and writes + a `SavedModel` into it containing a single `tf.MetaGraphDef` saved from this + session. + + The exported `MetaGraphDef` will provide one `SignatureDef` for each + element of the `export_outputs` dict returned from the `model_fn`, named + using the same keys. One of these keys is always + `tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY`, + indicating which signature will be served when a serving request does not + specify one. For each signature, the outputs are provided by the + corresponding `tf.estimator.export.ExportOutput`s, and the inputs are always + the input receivers provided by the `serving_input_receiver_fn`. + + Extra assets may be written into the `SavedModel` via the `assets_extra` + argument. This should be a dict, where each key gives a destination path + (including the filename) relative to the assets.extra directory. The + corresponding value gives the full path of the source file to be copied. + For example, the simple case of copying a single file without renaming it + is specified as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`. + + The experimental_mode parameter can be used to export a single + train/eval/predict graph as a `SavedModel`. + See `experimental_export_all_saved_models` for full docs. + + Args: + export_dir_base: A string containing a directory in which to create + timestamped subdirectories containing exported `SavedModel`s. + serving_input_receiver_fn: A function that takes no argument and returns a + `tf.estimator.export.ServingInputReceiver` or + `tf.estimator.export.TensorServingInputReceiver`. + assets_extra: A dict specifying how to populate the assets.extra directory + within the exported `SavedModel`, or `None` if no extra assets are + needed. + as_text: whether to write the `SavedModel` proto in text format. + checkpoint_path: The checkpoint path to export. If `None` (the default), + the most recent checkpoint found within the model directory is chosen. + experimental_mode: `tf.estimator.ModeKeys` value indicating with mode will + be exported. Note that this feature is experimental. + + Returns: + The path to the exported directory as a bytes object. + + Raises: + ValueError: if no `serving_input_receiver_fn` is provided, no + `export_outputs` are provided, or no checkpoint can be found. + """ + # pylint: enable=line-too-long + if not serving_input_receiver_fn: + raise ValueError('An input_receiver_fn must be defined.') + + input_receiver_fn_map = {experimental_mode: serving_input_receiver_fn} + + return self._export_all_saved_models( + export_dir_base, + input_receiver_fn_map, + assets_extra=assets_extra, + as_text=as_text, + checkpoint_path=checkpoint_path, + strip_default_attrs=True) + + def experimental_export_all_saved_models(self, + export_dir_base, + input_receiver_fn_map, + assets_extra=None, + as_text=False, + checkpoint_path=None): + """Exports a `SavedModel` with `tf.MetaGraphDefs` for each requested mode. + + For each mode passed in via the `input_receiver_fn_map`, + this method builds a new graph by calling the `input_receiver_fn` to obtain + feature and label `Tensor`s. Next, this method calls the `Estimator`'s + `model_fn` in the passed mode to generate the model graph based on + those features and labels, and restores the given checkpoint + (or, lacking that, the most recent checkpoint) into the graph. + Only one of the modes is used for saving variables to the `SavedModel` + (order of preference: `tf.estimator.ModeKeys.TRAIN`, + `tf.estimator.ModeKeys.EVAL`, then + `tf.estimator.ModeKeys.PREDICT`), such that up to three + `tf.MetaGraphDefs` are saved with a single set of variables in a single + `SavedModel` directory. + + For the variables and `tf.MetaGraphDefs`, a timestamped export directory + below `export_dir_base`, and writes a `SavedModel` into it containing the + `tf.MetaGraphDef` for the given mode and its associated signatures. + + For prediction, the exported `MetaGraphDef` will provide one `SignatureDef` + for each element of the `export_outputs` dict returned from the `model_fn`, + named using the same keys. One of these keys is always + `tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY`, + indicating which signature will be served when a serving request does not + specify one. For each signature, the outputs are provided by the + corresponding `tf.estimator.export.ExportOutput`s, and the inputs are always + the input receivers provided by the `serving_input_receiver_fn`. + + For training and evaluation, the `train_op` is stored in an extra + collection, and loss, metrics, and predictions are included in a + `SignatureDef` for the mode in question. + + Extra assets may be written into the `SavedModel` via the `assets_extra` + argument. This should be a dict, where each key gives a destination path + (including the filename) relative to the assets.extra directory. The + corresponding value gives the full path of the source file to be copied. + For example, the simple case of copying a single file without renaming it + is specified as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`. + + Args: + export_dir_base: A string containing a directory in which to create + timestamped subdirectories containing exported `SavedModel`s. + input_receiver_fn_map: dict of `tf.estimator.ModeKeys` to + `input_receiver_fn` mappings, where the `input_receiver_fn` is a + function that takes no arguments and returns the appropriate subclass of + `InputReceiver`. + assets_extra: A dict specifying how to populate the assets.extra directory + within the exported `SavedModel`, or `None` if no extra assets are + needed. + as_text: whether to write the `SavedModel` proto in text format. + checkpoint_path: The checkpoint path to export. If `None` (the default), + the most recent checkpoint found within the model directory is chosen. + + Returns: + The path to the exported directory as a bytes object. + + Raises: + ValueError: if any `input_receiver_fn` is `None`, no `export_outputs` + are provided, or no checkpoint can be found. + """ + return self._export_all_saved_models( + export_dir_base, + input_receiver_fn_map, + assets_extra=assets_extra, + as_text=as_text, + checkpoint_path=checkpoint_path, + strip_default_attrs=True) + + def _export_all_saved_models(self, + export_dir_base, + input_receiver_fn_map, + assets_extra=None, + as_text=False, + checkpoint_path=None, + strip_default_attrs=True): + """Exports multiple modes in the model function to a SavedModel.""" + # TODO(b/65561022): Consider allowing multiple input_receiver_fns per mode. + with context.graph_mode(): + if not checkpoint_path: + # Locate the latest checkpoint + checkpoint_path = self.latest_checkpoint() + if not checkpoint_path: + if self._warm_start_settings: + checkpoint_path = self._warm_start_settings.ckpt_to_initialize_from + if tf.compat.v1.gfile.IsDirectory(checkpoint_path): + checkpoint_path = tf.train.latest_checkpoint(checkpoint_path) + else: + raise ValueError("Couldn't find trained model at {}.".format( + self._model_dir)) + + export_dir = export_lib.get_timestamped_export_dir(export_dir_base) + temp_export_dir = export_lib.get_temp_export_dir(export_dir) + + builder = tf.compat.v1.saved_model.Builder(temp_export_dir) + + save_variables = True + # Note that the order in which we run here matters, as the first + # mode we pass through will be used to save the variables. We run TRAIN + # first, as that is also the mode used for checkpoints, and therefore + # we are not likely to have vars in PREDICT that are not in the checkpoint + # created by TRAIN. + if input_receiver_fn_map.get(ModeKeys.TRAIN): + self._add_meta_graph_for_mode( + builder, + input_receiver_fn_map, + checkpoint_path, + save_variables, + mode=ModeKeys.TRAIN, + strip_default_attrs=strip_default_attrs) + save_variables = False + if input_receiver_fn_map.get(ModeKeys.EVAL): + self._add_meta_graph_for_mode( + builder, + input_receiver_fn_map, + checkpoint_path, + save_variables, + mode=ModeKeys.EVAL, + strip_default_attrs=strip_default_attrs) + save_variables = False + if input_receiver_fn_map.get(ModeKeys.PREDICT): + self._add_meta_graph_for_mode( + builder, + input_receiver_fn_map, + checkpoint_path, + save_variables, + mode=ModeKeys.PREDICT, + strip_default_attrs=strip_default_attrs) + save_variables = False + + if save_variables: + raise ValueError('No valid modes for exporting found. Got {}.'.format( + input_receiver_fn_map.keys())) + + builder.save(as_text) + + # Add the extra assets + if assets_extra: + assets_extra_path = os.path.join( + tf.compat.as_bytes(temp_export_dir), + tf.compat.as_bytes('assets.extra')) + for dest_relative, source in assets_extra.items(): + dest_absolute = os.path.join( + tf.compat.as_bytes(assets_extra_path), + tf.compat.as_bytes(dest_relative)) + dest_path = os.path.dirname(dest_absolute) + tf.compat.v1.gfile.MakeDirs(dest_path) + tf.compat.v1.gfile.Copy(source, dest_absolute) + + tf.compat.v1.gfile.Rename(temp_export_dir, export_dir) + return export_dir + + def _add_meta_graph_for_mode(self, + builder, + input_receiver_fn_map, + checkpoint_path, + save_variables=True, + mode=ModeKeys.PREDICT, + export_tags=None, + check_variables=True, + strip_default_attrs=True): + """Loads variables and adds them along with a `tf.MetaGraphDef` for saving. + + Args: + builder: instance of `tf.saved_modle.builder.SavedModelBuilder` that will + be used for saving. + input_receiver_fn_map: dict of `tf.estimator.ModeKeys` to + `input_receiver_fn` mappings, where the `input_receiver_fn` is a + function that takes no argument and returns the appropriate subclass of + `InputReceiver`. + checkpoint_path: The checkpoint path to export. + save_variables: bool, whether variables should be saved. If `False`, just + the `tf.MetaGraphDef` will be saved. Note that `save_variables` should + only be `True` for the first call to this function, and the + `SavedModelBuilder` will raise an error if that is not the case. + mode: `tf.estimator.ModeKeys` value indicating which mode will be + exported. + export_tags: The set of tags with which to save `tf.MetaGraphDef`. If + `None`, a default set will be selected to matched the passed mode. + check_variables: bool, whether to check the checkpoint has all variables. + strip_default_attrs: bool, whether to strip default attributes. This may + only be True when called from the deprecated V1 + Estimator.export_savedmodel. + + Raises: + ValueError: if `save_variables` is `True` and `check_variable` is `False`. + """ + if export_tags is None: + export_tags = export_lib.EXPORT_TAG_MAP[mode] + input_receiver_fn = input_receiver_fn_map[mode] + + with tf.Graph().as_default() as g: + self._create_and_assert_global_step(g) + tf.compat.v1.random.set_random_seed(self._config.tf_random_seed) + + input_receiver = input_receiver_fn() + + # Call the model_fn and collect the export_outputs. + estimator_spec = self._call_model_fn( + features=input_receiver.features, + labels=getattr(input_receiver, 'labels', None), + mode=mode, + config=self.config) + + export_outputs = export_lib.export_outputs_for_mode( + mode=estimator_spec.mode, + serving_export_outputs=estimator_spec.export_outputs, + predictions=estimator_spec.predictions, + loss=estimator_spec.loss, + metrics=estimator_spec.eval_metric_ops) + + # Build the SignatureDefs from receivers and all outputs + signature_def_map = export_lib.build_all_signature_defs( + input_receiver.receiver_tensors, + export_outputs, + getattr(input_receiver, 'receiver_tensors_alternatives', None), + serving_only=(mode == ModeKeys.PREDICT)) + + with tf.compat.v1.Session(config=self._session_config) as session: + + if estimator_spec.scaffold.local_init_op is not None: + local_init_op = estimator_spec.scaffold.local_init_op + else: + local_init_op = tf.compat.v1.train.Scaffold.default_local_init_op() + + # This saver will be used both for restoring variables now, + # and in saving out the metagraph below. This ensures that any + # Custom Savers stored with the Scaffold are passed through to the + # SavedModel for restore later. + if isinstance(estimator_spec.scaffold.saver, trackable_util.Checkpoint): + graph_saver = tf.compat.v1.train.Saver( + var_list=graph_view.ObjectGraphView( + estimator_spec.scaffold.saver).frozen_saveable_objects(), + sharded=True) + else: + graph_saver = ( + estimator_spec.scaffold.saver or + tf.compat.v1.train.Saver(sharded=True)) + + if save_variables and not check_variables: + raise ValueError('If `save_variables` is `True, `check_variables`' + 'must not be `False`.') + if check_variables: + try: + graph_saver.restore(session, checkpoint_path) + except tf.errors.NotFoundError as e: + msg = ('Could not load all requested variables from checkpoint. ' + 'Please make sure your model_fn does not expect variables ' + 'that were not saved in the checkpoint.\n\n' + 'Encountered error with mode `{}` while restoring ' + 'checkpoint from: `{}`. Full Traceback:\n\n{}').format( + mode, checkpoint_path, e) + raise ValueError(msg) + + # We add the train op explicitly for now, so that we don't have to + # change the Builder public interface. Note that this is a no-op + # for prediction, where train_op is None. + builder._add_train_op(estimator_spec.train_op) # pylint: disable=protected-access + + meta_graph_kwargs = dict( + tags=export_tags, + signature_def_map=signature_def_map, + assets_collection=tf.compat.v1.get_collection( + tf.compat.v1.GraphKeys.ASSET_FILEPATHS), + main_op=local_init_op, + saver=graph_saver, + strip_default_attrs=strip_default_attrs) + + if save_variables: + builder.add_meta_graph_and_variables(session, **meta_graph_kwargs) + else: + builder.add_meta_graph(**meta_graph_kwargs) + + def _get_features_from_input_fn(self, input_fn, mode): + """Extracts the `features` from return values of `input_fn`.""" + result = self._call_input_fn(input_fn, mode) + result, _, hooks = estimator_util.parse_input_fn_result(result) + self._validate_features_in_predict_input(result) + return result, hooks + + def _validate_features_in_predict_input(self, result): + if not _has_dataset_or_queue_runner(result): + tf.compat.v1.logging.warning( + 'Input graph does not use tf.data.Dataset or contain a ' + 'QueueRunner. That means predict yields forever. ' + 'This is probably a mistake.' + ) + + def _get_iterator_from_input_fn(self, input_fn, mode, distribution=None): + """Calls `input_fn` and returns an iterator.""" + if distribution is not None: + # pylint: disable=g-long-lambda + iterator = distribution.make_input_fn_iterator( + lambda input_context: self._call_input_fn(input_fn, mode, + input_context)) + input_hooks = [ + estimator_util.DistributedIteratorInitializerHook(iterator) + ] + else: + result = self._call_input_fn(input_fn, mode) + iterator = result.make_initializable_iterator() + input_hooks = [estimator_util._DatasetInitializerHook(iterator)] # pylint: disable=protected-access + return iterator, input_hooks + + def _get_features_and_labels_from_input_fn(self, input_fn, mode): + """Extracts the `features` and labels from return values of `input_fn`.""" + return estimator_util.parse_input_fn_result( + self._call_input_fn(input_fn, mode)) + + def _extract_batch_length(self, preds_evaluated): + """Extracts batch length of predictions.""" + batch_length = None + for key, value in six.iteritems(preds_evaluated): + batch_length = batch_length or value.shape[0] + if value.shape[0] != batch_length: + raise ValueError('Batch length of predictions should be same. %s has ' + 'different batch length than others.' % key) + return batch_length + + def _extract_keys(self, predictions, predict_keys): + """Extracts `predict_keys` from `predictions`.""" + if not predict_keys: + return predictions + if not isinstance(predictions, dict): + raise ValueError( + 'predict_keys argument is not valid in case of non-dict predictions.') + existing_keys = predictions.keys() + predictions = { + key: value + for key, value in six.iteritems(predictions) + if key in predict_keys + } + if not predictions: + raise ValueError('Expected to run at least one output from %s, ' + 'provided %s.' % (existing_keys, predict_keys)) + return predictions + + def _create_global_step(self, graph): + """Creates the global step tensor in graph. + + The global step tensor must be an integer type with name 'global_step' and + be added to the collection `tf.GraphKeys.GLOBAL_STEP`. + + Args: + graph: The graph in which to create the global step tensor. + + Returns: + The global step `tf.Tensor`. + """ + return tf.compat.v1.train.create_global_step(graph) + + def _create_and_assert_global_step(self, graph): + """Creates and asserts properties of the global step. + + Args: + graph: The graph in which to create the global step tensor. + + Returns: + The global step `tf.Tensor`. + """ + step = self._create_global_step(graph) + assert step is tf.compat.v1.train.get_global_step() + assert step.dtype.is_integer + return step + + def _call_input_fn(self, input_fn, mode, input_context=None): + """Calls the input function. + + Args: + input_fn: The input function. + mode: `tf.estimator.ModeKeys` + + Returns: + The return value of the passed `input_fn`, which should be one of: + + * A 'tf.data.Dataset' object: Outputs of `Dataset` object must be a + tuple `(features, labels)` with same constraints as below. + * A tuple `(features, labels)`: Where `features` is a `Tensor` or a + dictionary of string feature name to `Tensor` and `labels` is a + `Tensor` or a dictionary of string label name to `Tensor`. Both + `features` and `labels` are consumed by `model_fn`. They should + satisfy the expectation of `model_fn` from inputs. + + Raises: + ValueError: if `input_fn` takes invalid arguments. + """ + input_fn_args = function_utils.fn_args(input_fn) + kwargs = {} + if 'mode' in input_fn_args: + kwargs['mode'] = mode + if 'params' in input_fn_args: + kwargs['params'] = self.params + if 'config' in input_fn_args: + kwargs['config'] = self.config + if input_context and 'input_context' in input_fn_args: + tf.compat.v1.logging.info( + 'The `input_fn` accepts an `input_context` which will ' + 'be given by DistributionStrategy') + kwargs['input_context'] = input_context + with tf.compat.v1.device('/cpu:0'): + return input_fn(**kwargs) + + def _call_model_fn(self, features, labels, mode, config): + """Calls model function. + + Args: + features: features dict. + labels: labels dict. + mode: `tf.estimator.ModeKeys` + config: `tf.estimator.RunConfig` + + Returns: + An `tf.estimator.EstimatorSpec` object. + + Raises: + ValueError: if `model_fn` returns invalid objects. + """ + model_fn_args = function_utils.fn_args(self._model_fn) + kwargs = {} + if 'labels' in model_fn_args: + kwargs['labels'] = labels + else: + if labels is not None: + raise ValueError( + 'model_fn does not take labels, but input_fn returns labels.') + if 'mode' in model_fn_args: + kwargs['mode'] = mode + if 'params' in model_fn_args: + kwargs['params'] = self.params + if 'config' in model_fn_args: + kwargs['config'] = config + + tf.compat.v1.logging.info('Calling model_fn.') + model_fn_results = self._model_fn(features=features, **kwargs) + tf.compat.v1.logging.info('Done calling model_fn.') + + if not isinstance(model_fn_results, model_fn_lib.EstimatorSpec): + raise ValueError('model_fn should return an EstimatorSpec.') + + return model_fn_results + + def _train_model(self, input_fn, hooks, saving_listeners): + if self._train_distribution: + return self._train_model_distributed(input_fn, hooks, saving_listeners) + else: + return self._train_model_default(input_fn, hooks, saving_listeners) + + def _train_model_default(self, input_fn, hooks, saving_listeners): + """Initiate training with `input_fn`, without `DistributionStrategies`. + + Args: + input_fn: A function that provides input data for training as minibatches. + hooks: List of `tf.train.SessionRunHook` subclass instances. Used for + callbacks inside the training loop. + saving_listeners: list of `tf.train.CheckpointSaverListener` objects. Used + for callbacks that run immediately before or after checkpoint savings. + + Returns: + Loss from training + """ + worker_hooks = [] + with tf.Graph().as_default() as g, g.device(self._device_fn): + tf.compat.v1.random.set_random_seed(self._config.tf_random_seed) + global_step_tensor = self._create_and_assert_global_step(g) + + # Skip creating a read variable if _create_and_assert_global_step + # returns None (e.g. tf.contrib.estimator.SavedModelEstimator). + if global_step_tensor is not None: + training_util._get_or_create_global_step_read(g) # pylint: disable=protected-access + + features, labels, input_hooks = ( + self._get_features_and_labels_from_input_fn(input_fn, ModeKeys.TRAIN)) + worker_hooks.extend(input_hooks) + estimator_spec = self._call_model_fn(features, labels, ModeKeys.TRAIN, + self.config) + global_step_tensor = tf.compat.v1.train.get_global_step(g) + return self._train_with_estimator_spec(estimator_spec, worker_hooks, + hooks, global_step_tensor, + saving_listeners) + + def _train_model_distributed(self, input_fn, hooks, saving_listeners): + """Initiate training with `input_fn`, using `DistributionStrategies`. + + Args: + input_fn: A function that provides input data for training as minibatches. + hooks: List of `tf.train.SessionRunHook` subclass instances. Used for + callbacks inside the training loop. + saving_listeners: list of `tf.train.CheckpointSaverListener` objects. Used + for callbacks that run immediately before or after checkpoint savings. + + Returns: + Loss from training + """ + # pylint: disable=protected-access + if (hasattr(self._config, '_distribute_coordinator_mode') and + self._config._distribute_coordinator_mode): # pylint: disable=protected-access + distribute_coordinator_training.estimator_train( + self, + lambda est, s, train_hooks: est._actual_train_model_distributed( # pylint: disable=g-long-lambda + s, input_fn, train_hooks, saving_listeners), + hooks) + return self + else: + self._config._train_distribute.configure(self._config.session_config) + return self._actual_train_model_distributed( + self._config._train_distribute, input_fn, hooks, saving_listeners) + # pylint: enable=protected-access + + def _actual_train_model_distributed(self, strategy, input_fn, hooks, + saving_listeners): + """That method that does actual training with distribution strategy.""" + # TODO(sourabhbajaj): Remove this hack once we migrate the other strategies + # to use the new API + is_tpu_strategy = strategy.__class__.__name__.startswith('TPUStrategy') + + worker_hooks = [] + with tf.Graph().as_default() as g: + # We want to create the iterations variable outside the distribution scope + # as that is just stored on the host and mainly used to drive the loop + # and doesn't need to be a Mirrored/Device variable. + if is_tpu_strategy: + steps_per_run_variable = training.get_or_create_steps_per_run_variable() + + # Set flag on the distribution strategy so that optimizer v1 is + # distribution aware and scales the losses by number of replicas. + # This is required only for backward compatibility with estimator and + # V1 optimizer. TF2 will not do this scaling. + if hasattr(strategy, '_scale_loss_for_estimator_enabled'): + scale_ctx = strategy._scale_loss_for_estimator_enabled() # pylint: disable=protected-access + else: + # TODO(psv): Remove this clause after estimator repo gets the + # distribute library changes related to loss scaling. + @tf_contextlib.contextmanager + def nullcontextmanager(): + yield + + scale_ctx = nullcontextmanager() + + with strategy.scope(), scale_ctx: + tf.compat.v1.random.set_random_seed(self._config.tf_random_seed) + iterator, input_hooks = self._get_iterator_from_input_fn( + input_fn, ModeKeys.TRAIN, strategy) + worker_hooks.extend(input_hooks) + global_step_tensor = self._create_and_assert_global_step(g) + # we want to add to the global collection in the main thread not the + # replica threads. + tf.compat.v1.add_to_collection( + training_util.GLOBAL_STEP_READ_KEY, + strategy.extended.read_var(global_step_tensor)) + + if is_tpu_strategy: + # Create a step_fn from the train_op of grouped_estimator_spec + def step_fn(ctx, inputs): + """A single step that is passed to run_on_dataset.""" + if isinstance(inputs, tuple): + features, labels = inputs + else: + features = inputs + labels = None + estimator_spec = strategy.extended.call_for_each_replica( + self._call_model_fn, + args=(features, labels, ModeKeys.TRAIN, self.config)) + ctx.set_last_step_output( + name='loss', + output=estimator_spec.loss, + reduce_op=_get_loss_reduce_op_for_reporting()) + ctx.set_non_tensor_output( + name='estimator_spec', output=estimator_spec) + return estimator_spec.train_op + + # Create new train_op post graph rewrites + initial_training_loss = tf.constant(1e7) + ctx = strategy.extended.experimental_run_steps_on_iterator( + step_fn, + iterator, + iterations=steps_per_run_variable, + initial_loop_values={'loss': initial_training_loss}) + distributed_train_op = ctx.run_op + loss = ctx.last_step_outputs['loss'] + grouped_estimator_spec = ctx.non_tensor_outputs['estimator_spec'] + else: + features, labels = estimator_util.parse_iterator_result( + iterator.get_next()) + grouped_estimator_spec = strategy.extended.call_for_each_replica( + self._call_model_fn, + args=( + features, + labels, # although this will be None it seems + ModeKeys.TRAIN, + self.config)) + loss = strategy.reduce( + _get_loss_reduce_op_for_reporting(), + grouped_estimator_spec.loss, + axis=None) + distributed_train_op = grouped_estimator_spec.train_op + + scaffold = _combine_distributed_scaffold( + grouped_estimator_spec.scaffold, strategy) + + # TODO(yuefengz): add a test for unwrapping per_device_hooks. + def get_hooks_from_the_first_device(per_device_hooks): + return [ + self._train_distribution.experimental_local_results( + per_device_hook)[0] for per_device_hook in per_device_hooks + ] + + training_hooks = get_hooks_from_the_first_device( + grouped_estimator_spec.training_hooks) + training_chief_hooks = get_hooks_from_the_first_device( + grouped_estimator_spec.training_chief_hooks) + estimator_spec = model_fn_lib.EstimatorSpec( + mode=grouped_estimator_spec.mode, + loss=loss, + train_op=strategy.group(distributed_train_op), + training_hooks=training_hooks, + training_chief_hooks=training_chief_hooks, + scaffold=scaffold) + return self._train_with_estimator_spec(estimator_spec, worker_hooks, + hooks, global_step_tensor, + saving_listeners) + + def _train_with_estimator_spec_distributed(self, estimator_spec, worker_hooks, + saving_listener): + """Train a model with the given Estimator Spec and Distribution Strategy.""" + if saving_listener: + raise ValueError('Saving listenor is not supported by the current ' + 'Distribution Strategies.') + #TODO: consolidate code duplication in _train_with_estimator_spec + with training.MonitoredTrainingSession( + master=self._config.master, + is_chief=self._config.is_chief, + checkpoint_dir=self._model_dir, + scaffold=estimator_spec.scaffold, + hooks=worker_hooks, + chief_only_hooks=tuple(estimator_spec.training_chief_hooks), + save_checkpoint_secs=self._config.save_checkpoints_secs, + save_checkpoint_steps=self._config.save_checkpoints_steps, + save_summaries_steps=self._config.save_summary_steps, + config=self._session_config, + max_wait_secs=self._config.session_creation_timeout_secs, + log_step_count_steps=self._config.log_step_count_steps, + save_graph_def=self._config.checkpoint_save_graph_def) as mon_sess: + loss = None + current_step = 0 + while not mon_sess.should_stop(): + current_step += 1 + # just as keras(https://github.com/tensorflow/tensorflow/blob/v2.4.1/tensorflow/python/keras/engine/training.py#L1093), + # trace should be enabled for every step + with trace.Trace('train', step_num=current_step, _r=1): + _, loss = mon_sess.run([estimator_spec.train_op, estimator_spec.loss]) + if current_step == 0: + tf.compat.v1.logging.warn('Training with estimator made no steps. ' + 'Perhaps input is empty or misspecified.') + return loss + + def _train_with_estimator_spec(self, estimator_spec, worker_hooks, hooks, + global_step_tensor, saving_listeners): + """Train a model with the given Estimator Spec.""" + if (self._warm_start_settings and + not tf.train.latest_checkpoint(self._model_dir)): + tf.compat.v1.logging.info('Warm-starting with WarmStartSettings: %s' % + (self._warm_start_settings,)) + tf.compat.v1.train.warm_start(*self._warm_start_settings) + # Check if the user created a loss summary, and add one if they didn't. + # We assume here that the summary is called 'loss'. If it is not, we will + # make another one with the name 'loss' to ensure it shows up in the right + # graph in TensorBoard. + if not any([ + x.op.name == 'loss' for x in ops.get_collection(ops.GraphKeys.SUMMARIES) + ]): + summary.scalar('loss', estimator_spec.loss) + ops.add_to_collection(ops.GraphKeys.LOSSES, estimator_spec.loss) + worker_hooks.extend(hooks) + worker_hooks.append(tf.compat.v1.train.NanTensorHook(estimator_spec.loss)) + if self._config.log_step_count_steps is not None: + worker_hooks.append( + tf.compat.v1.train.LoggingTensorHook( + { + 'loss': estimator_spec.loss, + 'step': global_step_tensor + }, + every_n_iter=self._config.log_step_count_steps)) + worker_hooks.extend(estimator_spec.training_hooks) + + if not (estimator_spec.scaffold.saver or + tf.compat.v1.get_collection(tf.compat.v1.GraphKeys.SAVERS)): + tf.compat.v1.add_to_collection( + tf.compat.v1.GraphKeys.SAVERS, + tf.compat.v1.train.Saver( + sharded=True, + max_to_keep=self._config.keep_checkpoint_max, + keep_checkpoint_every_n_hours=( + self._config.keep_checkpoint_every_n_hours), + defer_build=True, + save_relative_paths=True)) + + if (self._config.cluster_spec and type( + self._train_distribution).__name__ in ('CollectiveAllReduceStrategy', + 'CollectiveAllReduceStrategyV1', + 'MultiWorkerMirroredStrategy')): + return self._train_with_estimator_spec_distributed( + estimator_spec, worker_hooks, saving_listeners) + + chief_hooks = [] + all_hooks = worker_hooks + list(estimator_spec.training_chief_hooks) + saver_hooks = [ + h for h in all_hooks + if isinstance(h, tf.compat.v1.train.CheckpointSaverHook) + ] + if (self._config.save_checkpoints_secs or + self._config.save_checkpoints_steps): + if not saver_hooks: + chief_hooks = [ + tf.compat.v1.train.CheckpointSaverHook( + self._model_dir, + save_secs=self._config.save_checkpoints_secs, + save_steps=self._config.save_checkpoints_steps, + scaffold=estimator_spec.scaffold, + save_graph_def=self._config.checkpoint_save_graph_def) + ] + saver_hooks = [chief_hooks[0]] + if saving_listeners: + if not saver_hooks: + raise ValueError( + 'There should be a CheckpointSaverHook to use saving_listeners. ' + 'Please set one of the RunConfig.save_checkpoints_steps or ' + 'RunConfig.save_checkpoints_secs.') + else: + # It is expected to have one CheckpointSaverHook. If multiple, we pick + # up the first one to add listener. + for listener in saving_listeners: + # pylint: disable=protected-access + if listener not in saver_hooks[0]._listeners: + saver_hooks[0]._listeners.append(listener) + # pylint: disable=protected-access + + # Add summary hooks to worker 0 if we are running with a master, to ensure + # that summaries are written at correct intervals even with long-running + # evaluations. + save_summary_steps = self._config.save_summary_steps + log_step_count_steps = self._config.log_step_count_steps + + # Check existence of appropriate cluster spec fields, as well as master and + # worker nodes. As master also performs evaluation, summary writing must + # occur on a different node. The presence of a worker is also checked to + # prevent reassigning hooks for single-replica jobs with just a master node. + if (self._config.cluster_spec and self._config.cluster_spec.jobs and + (run_config.TaskType.WORKER in self._config.cluster_spec.jobs) and + (run_config.TaskType.MASTER in self._config.cluster_spec.jobs)): + # Update config values to prevent the default hooks from being created on + # the master or other workers. + save_summary_steps = 0 + log_step_count_steps = None + + if (self._config.task_type == run_config.TaskType.WORKER and + self._config.task_id == 0): + if (self._config.save_summary_steps and + self._config.save_summary_steps > 0): + worker_hooks.append( + tf.compat.v1.train.SummarySaverHook( + save_steps=self._config.save_summary_steps, + output_dir=self._config.model_dir, + scaffold=estimator_spec.scaffold)) + + if (self._config.log_step_count_steps and + self._config.log_step_count_steps > 0): + worker_hooks.append( + tf.compat.v1.train.StepCounterHook( + every_n_steps=self._config.log_step_count_steps, + output_dir=self._config.model_dir)) + + with training.MonitoredTrainingSession( + master=self._config.master, + is_chief=self._config.is_chief, + checkpoint_dir=self._model_dir, + scaffold=estimator_spec.scaffold, + hooks=worker_hooks, + chief_only_hooks=(tuple(chief_hooks) + + tuple(estimator_spec.training_chief_hooks)), + save_checkpoint_secs=0, # Saving is handled by a hook. + save_summaries_steps=save_summary_steps, + config=self._session_config, + max_wait_secs=self._config.session_creation_timeout_secs, + log_step_count_steps=log_step_count_steps, + save_graph_def=self._config.checkpoint_save_graph_def) as mon_sess: + loss = None + current_step = 0 + while not mon_sess.should_stop(): + current_step += 1 + # just as keras(https://github.com/tensorflow/tensorflow/blob/v2.4.1/tensorflow/python/keras/engine/training.py#L1093), + # trace should be enabled for every step + with trace.Trace('train', step_num=current_step, _r=1): + _, loss = mon_sess.run([estimator_spec.train_op, estimator_spec.loss]) + if current_step == 0: + tf.compat.v1.logging.warn('Training with estimator made no steps. ' + 'Perhaps input is empty or misspecified.') + return loss + + def _evaluate_build_graph(self, input_fn, hooks=None, checkpoint_path=None): + """Builds the graph and related hooks to run evaluation.""" + tf.compat.v1.random.set_random_seed(self._config.tf_random_seed) + self._create_and_assert_global_step(tf.compat.v1.get_default_graph()) + + if self._eval_distribution: + (scaffold, evaluation_hooks, input_hooks, update_op, eval_dict) = ( + self._call_model_fn_eval_distributed(input_fn, self.config)) + else: + (scaffold, evaluation_hooks, input_hooks, update_op, eval_dict) = ( + self._call_model_fn_eval(input_fn, self.config)) + + global_step_tensor = tf.compat.v1.train.get_global_step( + tf.compat.v1.get_default_graph()) + # Call to warm_start has to be after model_fn is called. + self._maybe_warm_start(checkpoint_path) + + if tf.compat.v1.GraphKeys.GLOBAL_STEP in eval_dict: + raise ValueError( + 'Metric with name `global_step` is not allowed, because Estimator ' + 'already defines a default metric with the same name.') + eval_dict[tf.compat.v1.GraphKeys.GLOBAL_STEP] = global_step_tensor + + all_hooks = list(input_hooks) + all_hooks.extend(hooks) + all_hooks.extend(list(evaluation_hooks or [])) + # New local variables have been added, so update the estimator spec's + # local init op if it was defined. + if scaffold and scaffold.local_init_op: + # Ensure that eval step has been created before updating local init op. + evaluation._get_or_create_eval_step() # pylint: disable=protected-access + + scaffold = tf.compat.v1.train.Scaffold( + local_init_op=tf.group( + scaffold.local_init_op, + tf.compat.v1.train.Scaffold.default_local_init_op()), + copy_from_scaffold=scaffold) + + return scaffold, update_op, eval_dict, all_hooks + + def _call_model_fn_eval(self, input_fn, config): + """Call model_fn for evaluation and handle return values.""" + features, labels, input_hooks = self._get_features_and_labels_from_input_fn( + input_fn, ModeKeys.EVAL) + + estimator_spec = self._call_model_fn(features, labels, ModeKeys.EVAL, + config) + eval_metric_ops = _verify_and_create_loss_metric( + estimator_spec.eval_metric_ops, estimator_spec.loss) + update_op, eval_dict = _extract_metric_update_ops(eval_metric_ops) + return (estimator_spec.scaffold, estimator_spec.evaluation_hooks, + input_hooks, update_op, eval_dict) + + def _call_model_fn_eval_distributed(self, input_fn, config): + """Call model_fn in distribution mode and handle return values.""" + + iterator, input_hooks = self._get_iterator_from_input_fn( + input_fn, ModeKeys.EVAL, self._eval_distribution) + + is_tpu_strategy = ( + self._eval_distribution.__class__.__name__.startswith('TPUStrategy')) + + if is_tpu_strategy: + steps_per_run_variable = training.get_or_create_steps_per_run_variable() + + def step_fn(ctx, inputs): + """Runs one step of the eval computation and captures outputs.""" + if isinstance(inputs, tuple): + features, labels = inputs + else: + features = inputs + labels = None + estimator_spec = self._eval_distribution.extended.call_for_each_replica( + self._call_model_fn, args=(features, labels, ModeKeys.EVAL, config)) + eval_metric_ops = _verify_and_create_loss_metric( + estimator_spec.eval_metric_ops, estimator_spec.loss, + self._eval_distribution) + update_op, eval_dict = _extract_metric_update_ops( + eval_metric_ops, self._eval_distribution) + ctx.set_non_tensor_output(name='estimator_spec', output=estimator_spec) + ctx.set_non_tensor_output(name='eval_dict', output=eval_dict) + return update_op + + # TODO(priyag): Fix eval step hook to account for steps_per_run. + ctx = self._eval_distribution.extended.experimental_run_steps_on_iterator( + step_fn, iterator, iterations=steps_per_run_variable) + update_op = ctx.run_op + eval_dict = ctx.non_tensor_outputs['eval_dict'] + grouped_estimator_spec = ctx.non_tensor_outputs['estimator_spec'] + else: + features, labels = estimator_util.parse_iterator_result( + iterator.get_next()) + grouped_estimator_spec = ( + self._eval_distribution.extended.call_for_each_replica( + self._call_model_fn, + args=(features, labels, ModeKeys.EVAL, config))) + eval_metric_ops = _verify_and_create_loss_metric( + grouped_estimator_spec.eval_metric_ops, grouped_estimator_spec.loss, + self._eval_distribution) + update_op, eval_dict = _extract_metric_update_ops(eval_metric_ops, + self._eval_distribution) + + scaffold = _combine_distributed_scaffold(grouped_estimator_spec.scaffold, + self._eval_distribution) + + def get_hooks_from_the_first_device(per_device_hooks): + return [ + self._eval_distribution.experimental_local_results(per_device_hook)[0] + for per_device_hook in per_device_hooks + ] + + evaluation_hooks = get_hooks_from_the_first_device( + grouped_estimator_spec.evaluation_hooks) + + return (scaffold, evaluation_hooks, input_hooks, update_op, eval_dict) + + def _evaluate_run(self, checkpoint_path, scaffold, update_op, eval_dict, + all_hooks, output_dir): + """Run evaluation.""" + eval_results = evaluation._evaluate_once( # pylint: disable=protected-access + checkpoint_path=checkpoint_path, + master=self._config.evaluation_master, + scaffold=scaffold, + eval_ops=update_op, + final_ops=eval_dict, + hooks=all_hooks, + config=self._session_config) + + current_global_step = eval_results[tf.compat.v1.GraphKeys.GLOBAL_STEP] + + _write_dict_to_summary( + output_dir=output_dir, + dictionary=eval_results, + current_global_step=current_global_step) + + if checkpoint_path: + _write_checkpoint_path_to_summary( + output_dir=output_dir, + checkpoint_path=checkpoint_path, + current_global_step=current_global_step) + + return eval_results + + def _maybe_warm_start(self, checkpoint_path): + if not checkpoint_path and self._warm_start_settings: + tf.compat.v1.logging.info('Warm-starting with WarmStartSettings: %s' % + (self._warm_start_settings,)) + tf.compat.v1.train.warm_start(*self._warm_start_settings) + + @deprecation.deprecated( + None, 'This function has been renamed, use `export_saved_model` instead.') + def export_savedmodel(self, + export_dir_base, + serving_input_receiver_fn, + assets_extra=None, + as_text=False, + checkpoint_path=None, + strip_default_attrs=False): + # pylint: disable=line-too-long + """Exports inference graph as a `SavedModel` into the given dir. + + For a detailed guide, see + [SavedModel from + Estimators.](https://www.tensorflow.org/guide/estimator#savedmodels_from_estimators). + + This method builds a new graph by first calling the + `serving_input_receiver_fn` to obtain feature `Tensor`s, and then calling + this `Estimator`'s `model_fn` to generate the model graph based on those + features. It restores the given checkpoint (or, lacking that, the most + recent checkpoint) into this graph in a fresh session. Finally it creates + a timestamped export directory below the given `export_dir_base`, and writes + a `SavedModel` into it containing a single `tf.MetaGraphDef` saved from this + session. + + The exported `MetaGraphDef` will provide one `SignatureDef` for each + element of the `export_outputs` dict returned from the `model_fn`, named + using the same keys. One of these keys is always + `tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY`, + indicating which signature will be served when a serving request does not + specify one. For each signature, the outputs are provided by the + corresponding `tf.estimator.export.ExportOutput`s, and the inputs are always + the input receivers provided by the `serving_input_receiver_fn`. + + Extra assets may be written into the `SavedModel` via the `assets_extra` + argument. This should be a dict, where each key gives a destination path + (including the filename) relative to the assets.extra directory. The + corresponding value gives the full path of the source file to be copied. + For example, the simple case of copying a single file without renaming it + is specified as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`. + + Args: + export_dir_base: A string containing a directory in which to create + timestamped subdirectories containing exported `SavedModel`s. + serving_input_receiver_fn: A function that takes no argument and returns a + `tf.estimator.export.ServingInputReceiver` or + `tf.estimator.export.TensorServingInputReceiver`. + assets_extra: A dict specifying how to populate the assets.extra directory + within the exported `SavedModel`, or `None` if no extra assets are + needed. + as_text: whether to write the `SavedModel` proto in text format. + checkpoint_path: The checkpoint path to export. If `None` (the default), + the most recent checkpoint found within the model directory is chosen. + strip_default_attrs: Boolean. If `True`, default-valued attributes will be + removed from the `NodeDef`s. For a detailed guide, see [Stripping + Default-Valued Attributes]( + https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md#stripping-default-valued-attributes). + + Returns: + The path to the exported directory as a bytes object. + + Raises: + ValueError: if no `serving_input_receiver_fn` is provided, no + `export_outputs` are provided, or no checkpoint can be found. + """ + # pylint: enable=line-too-long + if not serving_input_receiver_fn: + raise ValueError('An input_receiver_fn must be defined.') + + return self._export_all_saved_models( + export_dir_base, {ModeKeys.PREDICT: serving_input_receiver_fn}, + assets_extra=assets_extra, + as_text=as_text, + checkpoint_path=checkpoint_path, + strip_default_attrs=strip_default_attrs) + + +@estimator_export('estimator.Estimator', v1=[]) # pylint: disable=missing-docstring +class EstimatorV2(Estimator): + __doc__ = Estimator.__doc__ + + export_savedmodel = deprecation.hide_attribute_from_api( + '`Estimator.export_savedmodel` has been deprecated. Please use ' + '`export_saved_model` instead.') + + def _assert_members_are_not_overridden(self): + """Asserts members of `Estimator` are not overridden.""" + _assert_members_are_not_overridden(EstimatorV2, self) + + +def _get_loss_reduce_op_for_reporting(): + graph = tf.compat.v1.get_default_graph() + if getattr(graph, '_is_loss_scaled_by_optimizer', False): # pylint: disable=protected-access + return tf.compat.v1.distribute.get_loss_reduction() + return tf.distribute.ReduceOp.SUM + + +def _assert_members_are_not_overridden(cls, obj): + """Assert Estimator methods are not overwritten.""" + # TPUEstimator is special cased (owned by TF). + if obj.__class__.__name__ == 'TPUEstimator': + return + + allowed_overrides = set([ + 'model_fn', '_create_and_assert_global_step', '_export_all_saved_models', + '_tf_api_names', '_tf_api_names_v1', '_estimator_api_names', + '_estimator_api_names_v1', '_estimator_api_constants', + '_estimator_api_constants_v1', 'latest_checkpoint' + ]) + + estimator_members = set([m for m in dir(cls) if not m.startswith('__')]) + subclass_members = set(obj.__class__.__dict__.keys()) + common_members = estimator_members & subclass_members - allowed_overrides + overridden_members = [ + m for m in common_members if getattr(cls, m) != getattr(obj.__class__, m) + ] + if overridden_members: + raise ValueError( + 'Subclasses of Estimator cannot override members of Estimator. ' + '{} does override {}'.format(obj.__class__, overridden_members)) + + +def _verify_and_create_loss_metric(eval_metric_ops, loss, distribution=None): + """Creates a metric for loss and throws an error if one already exists.""" + if model_fn_lib.LOSS_METRIC_KEY in eval_metric_ops: + raise ValueError( + 'Metric with name "%s" is not allowed, because Estimator ' % + (model_fn_lib.LOSS_METRIC_KEY) + + 'already defines a default metric with the same name.') + + if distribution is None: + loss_metric = tf.compat.v1.metrics.mean(loss) + else: + loss_metric = distribution.extended.call_for_each_replica( + tf.compat.v1.metrics.mean, args=(loss,)) + eval_metric_ops[model_fn_lib.LOSS_METRIC_KEY] = loss_metric + return eval_metric_ops + + +def maybe_overwrite_model_dir_and_session_config(config, model_dir): + """Overwrite estimator config by `model_dir` and `session_config` if needed. + + Args: + config: Original estimator config. + model_dir: Estimator model checkpoint directory. + + Returns: + Overwritten estimator config. + + Raises: + ValueError: Model directory inconsistent between `model_dir` and `config`. + """ + + if config is None: + config = run_config.RunConfig() + tf.compat.v1.logging.info('Using default config.') + if not isinstance(config, run_config.RunConfig): + raise ValueError( + 'config must be an instance of `RunConfig`, but provided %s.' % config) + + if config.session_config is None: + session_config = run_config.get_default_session_config() + config = run_config.RunConfig.replace(config, session_config=session_config) + + model_dir = run_config.path_to_str(model_dir) + if model_dir is not None: + if (getattr(config, 'model_dir', None) is not None and + config.model_dir != model_dir): + raise ValueError( + '`model_dir` are set both in constructor and `RunConfig`, but with ' + "different values. In constructor: '{}', in `RunConfig`: " + "'{}' ".format(model_dir, config.model_dir)) + if model_dir: + config = run_config.RunConfig.replace(config, model_dir=model_dir) + elif getattr(config, 'model_dir', None) is None: + model_dir = tempfile.mkdtemp() + tf.compat.v1.logging.warn('Using temporary folder as model directory: %s', + model_dir) + config = run_config.RunConfig.replace(config, model_dir=model_dir) + + return config + + +def create_per_replica_ready_for_local_init_op(scaffold): + """Create a `tf.train.Scaffold.ready_for_local_init_op` inside a replica.""" + if scaffold.ready_for_local_init_op: + return scaffold.ready_for_local_init_op + + def default_ready_for_local_init_op(): + return tf.compat.v1.report_uninitialized_variables( + tf.compat.v1.global_variables()) + + return tf.compat.v1.train.Scaffold.get_or_default( + 'ready_for_local_init_op', tf.compat.v1.GraphKeys.READY_FOR_LOCAL_INIT_OP, + default_ready_for_local_init_op) + + +def _combine_distributed_scaffold(grouped_scaffold, distribution): + """Combines scaffold(s) returned from `call_for_each_replica`.""" + + # TODO(anjalisridhar): Figure out how to resolve the following scaffold + # parameters: init_feed_dict, init_fn. + scaffold_list = distribution.experimental_local_results(grouped_scaffold) + init_feed_dict = [ + s.init_feed_dict for s in scaffold_list if s.init_feed_dict is not None + ] + if init_feed_dict: + init_feed_dict = distribution.group(init_feed_dict) + else: + init_feed_dict = None + + init_fn = [ + s._user_init_fn for s in scaffold_list if s._user_init_fn is not None # pylint: disable=protected-access + ] + if init_fn: + init_fn = init_fn[0] + else: + init_fn = None + + init_op = [s.init_op for s in scaffold_list if s.init_op is not None] + if init_op: + init_op = distribution.group(init_op) + else: + init_op = None + + def _unwrap_and_concat(value): + value = tf.nest.flatten(distribution.experimental_local_results(value)) + if len(value) != 1: + return tf.concat(value, 0) + return value[0] + + ready_op = distribution.extended.call_for_each_replica( + lambda scaffold: scaffold.ready_op, args=(grouped_scaffold,)) + if ready_op is not None: + ready_op = _unwrap_and_concat(ready_op) + + ready_for_local_init_op = distribution.extended.call_for_each_replica( + create_per_replica_ready_for_local_init_op, args=(grouped_scaffold,)) + if ready_for_local_init_op is not None: + ready_for_local_init_op = _unwrap_and_concat(ready_for_local_init_op) + else: + ready_for_local_init_op = None + + local_init_op = [ + s.local_init_op for s in scaffold_list if s.local_init_op is not None + ] + if local_init_op: + local_init_op = distribution.group(local_init_op) + else: + local_init_op = None + + summary_op = [s.summary_op for s in scaffold_list if s.summary_op is not None] + if summary_op: + summary_op = distribution.group(summary_op) + else: + summary_op = None + + savers = [s.saver for s in scaffold_list if s.saver is not None] + if savers: + saver = savers[0] + else: + saver = None + + scaffold = tf.compat.v1.train.Scaffold( + init_op=init_op, + ready_op=ready_op, + ready_for_local_init_op=ready_for_local_init_op, + local_init_op=local_init_op, + summary_op=summary_op, + saver=saver, + init_feed_dict=init_feed_dict, + init_fn=init_fn) + return scaffold + + +def _check_checkpoint_available(model_dir): + latest_path = tf.train.latest_checkpoint(model_dir) + if not latest_path: + raise ValueError( + 'Could not find trained model in model_dir: {}.'.format(model_dir)) + + +def _check_hooks_type(hooks): + """Returns hooks if all are `SessionRunHook`, raises TypeError otherwise.""" + hooks = list(hooks or []) + for h in hooks: + if not isinstance(h, tf.compat.v1.train.SessionRunHook): + raise TypeError('Hooks must be a SessionRunHook, given: {}'.format(h)) + return hooks + + +def _check_listeners_type(saving_listeners): + """Check listeners type.""" + listeners = list(saving_listeners or []) + for l in listeners: + if not isinstance(l, tf.compat.v1.train.CheckpointSaverListener): + raise TypeError( + 'saving_listeners must be a list of CheckpointSaverListener, ' + 'given: {}'.format(l)) + return listeners + + +def _get_replica_device_setter(config): + """Creates a replica device setter if required as a default `device_fn`. + + `Estimator` uses `tf.train.ReplicaDeviceSetter` as a default device placer. It + sets the distributed related arguments such as number of `ps_replicas` based + on given `config`. + + Args: + config: A `tf.estimator.RunConfig` instance. + + Returns: + A replica device setter, or `None`. + """ + if config.task_type: + worker_device = '/job:%s/task:%d' % (config.task_type, config.task_id) + else: + worker_device = '/job:worker' + + if config.num_ps_replicas > 0: + return tf.compat.v1.train.replica_device_setter( + ps_tasks=config.num_ps_replicas, + worker_device=worker_device, + merge_devices=True, + ps_ops=list(device_setter.STANDARD_PS_OPS), + cluster=config.cluster_spec) + else: + return None + + +def _verify_model_fn_args(model_fn, params): + """Verifies `model_fn` arguments.""" + args = set(function_utils.fn_args(model_fn)) + if 'features' not in args: + raise ValueError('model_fn (%s) must include features argument.' % model_fn) + if params is not None and 'params' not in args: + raise ValueError('model_fn (%s) does not include params argument, ' + 'but params (%s) is passed to Estimator.' % + (model_fn, params)) + if params is None and 'params' in args: + tf.compat.v1.logging.warn( + 'Estimator\'s model_fn (%s) includes params ' + 'argument, but params are not passed to Estimator.', model_fn) + non_valid_args = list(args - _VALID_MODEL_FN_ARGS) + if non_valid_args: + raise ValueError('model_fn (%s) has following not expected args: %s' % + (model_fn, non_valid_args)) + + +def _load_global_step_from_checkpoint_dir(checkpoint_dir): + try: + checkpoint_reader = tf.compat.v1.train.NewCheckpointReader( + tf.train.latest_checkpoint(checkpoint_dir)) + return checkpoint_reader.get_tensor(tf.compat.v1.GraphKeys.GLOBAL_STEP) + except: # pylint: disable=bare-except + return 0 + + +def _extract_metric_update_ops(eval_dict, distribution=None): + """Separate update operations from metric value operations.""" + update_ops = [] + value_ops = {} + # Sort metrics lexicographically so graph is identical every time. + for name, value in sorted(six.iteritems(eval_dict)): + value_ops[name] = value[0] + update_ops.append( + distribution.group(value[1]) if distribution else value[1]) + + update_op = tf.group(*update_ops) if update_ops else None + return update_op, value_ops + + +def _dict_to_str(dictionary): + """Get a `str` representation of a `dict`. + + Args: + dictionary: The `dict` to be represented as `str`. + + Returns: + A `str` representing the `dictionary`. + """ + return ', '.join('%s = %s' % (k, v) + for k, v in sorted(six.iteritems(dictionary)) + if not isinstance(v, six.binary_type)) + + +def _write_dict_to_summary(output_dir, dictionary, current_global_step): + """Writes a `dict` into summary file in given output directory. + + Args: + output_dir: `str`, directory to write the summary file in. + dictionary: the `dict` to be written to summary file. + current_global_step: `int`, the current global step. + """ + tf.compat.v1.logging.info('Saving dict for global step %d: %s', + current_global_step, _dict_to_str(dictionary)) + summary_writer = tf.compat.v1.summary.FileWriterCache.get(output_dir) + summary_proto = summary_pb2.Summary() + for key in dictionary: + if dictionary[key] is None: + continue + if key == 'global_step': + continue + if (isinstance(dictionary[key], np.float32) or + isinstance(dictionary[key], float)): + summary_proto.value.add(tag=key, simple_value=float(dictionary[key])) + elif (isinstance(dictionary[key], np.int64) or + isinstance(dictionary[key], np.int32) or + isinstance(dictionary[key], int)): + summary_proto.value.add(tag=key, simple_value=int(dictionary[key])) + elif isinstance(dictionary[key], six.binary_type): + try: + summ = summary_pb2.Summary.FromString(dictionary[key]) + for i, _ in enumerate(summ.value): + summ.value[i].tag = '%s/%d' % (key, i) + summary_proto.value.extend(summ.value) + except message.DecodeError: + tf.compat.v1.logging.warn( + 'Skipping summary for %s, cannot parse string to Summary.', key) + continue + elif isinstance(dictionary[key], np.ndarray): + value = summary_proto.value.add() + value.tag = key + value.node_name = key + tensor_proto = tf.make_tensor_proto(dictionary[key]) + value.tensor.CopyFrom(tensor_proto) + # pylint: disable=line-too-long + tf.compat.v1.logging.info( + 'Summary for np.ndarray is not visible in Tensorboard by default. ' + 'Consider using a Tensorboard plugin for visualization (see ' + 'https://github.com/tensorflow/tensorboard-plugin-example/blob/master/README.md' + ' for more information).') + # pylint: enable=line-too-long + else: + tf.compat.v1.logging.warn( + 'Skipping summary for %s, must be a float, np.float32, np.int64, ' + 'np.int32 or int or np.ndarray or a serialized string of Summary.', + key) + summary_writer.add_summary(summary_proto, current_global_step) + summary_writer.flush() + + +def _write_checkpoint_path_to_summary(output_dir, checkpoint_path, + current_global_step): + """Writes `checkpoint_path` into summary file in the given output directory. + + Args: + output_dir: `str`, directory to write the summary file in. + checkpoint_path: `str`, checkpoint file path to be written to summary file. + current_global_step: `int`, the current global step. + """ + + checkpoint_path_tag = 'checkpoint_path' + + tf.compat.v1.logging.info('Saving \'%s\' summary for global step %d: %s', + checkpoint_path_tag, current_global_step, + checkpoint_path) + summary_proto = summary_pb2.Summary() + summary_proto.value.add( + tag=checkpoint_path_tag, + tensor=tf.make_tensor_proto(checkpoint_path, dtype=tf.dtypes.string)) + summary_writer = tf.compat.v1.summary.FileWriterCache.get(output_dir) + summary_writer.add_summary(summary_proto, current_global_step) + summary_writer.flush() + + +def _has_dataset_or_queue_runner(maybe_tensor): + """Returns `True` if `Dataset` or `QueueRunner` has been used.""" + # Check TF dataset first. Here, we use a simple algorithm to check the top + # level Tensors only, which should be sufficient for most users. + tensors = [ + x for x in tf.nest.flatten(maybe_tensor) if isinstance(x, tf.Tensor) + ] + if any([t.op.type == 'IteratorGetNext' for t in tensors]): + return True + + # Now, check queue. + return tf.compat.v1.get_default_graph().get_collection( + tf.compat.v1.GraphKeys.QUEUE_RUNNERS) + + +VocabInfo = tf.compat.v1.train.VocabInfo # pylint: disable=invalid-name +estimator_export('estimator.VocabInfo')(VocabInfo) + + +@estimator_export('estimator.WarmStartSettings') +class WarmStartSettings( + collections.namedtuple('WarmStartSettings', [ + 'ckpt_to_initialize_from', + 'vars_to_warm_start', + 'var_name_to_vocab_info', + 'var_name_to_prev_var_name', + ])): + """Settings for warm-starting in `tf.estimator.Estimators`. + + Example Use with canned `tf.estimator.DNNEstimator`: + + ``` + emb_vocab_file = tf.feature_column.embedding_column( + tf.feature_column.categorical_column_with_vocabulary_file( + "sc_vocab_file", "new_vocab.txt", vocab_size=100), + dimension=8) + emb_vocab_list = tf.feature_column.embedding_column( + tf.feature_column.categorical_column_with_vocabulary_list( + "sc_vocab_list", vocabulary_list=["a", "b"]), + dimension=8) + estimator = tf.estimator.DNNClassifier( + hidden_units=[128, 64], feature_columns=[emb_vocab_file, emb_vocab_list], + warm_start_from=ws) + ``` + + where `ws` could be defined as: + + Warm-start all weights in the model (input layer and hidden weights). + Either the directory or a specific checkpoint can be provided (in the case + of the former, the latest checkpoint will be used): + + ``` + ws = WarmStartSettings(ckpt_to_initialize_from="/tmp") + ws = WarmStartSettings(ckpt_to_initialize_from="/tmp/model-1000") + ``` + + Warm-start only the embeddings (input layer): + + ``` + ws = WarmStartSettings(ckpt_to_initialize_from="/tmp", + vars_to_warm_start=".*input_layer.*") + ``` + + Warm-start all weights but the embedding parameters corresponding to + `sc_vocab_file` have a different vocab from the one used in the current + model: + + ``` + vocab_info = tf.estimator.VocabInfo( + new_vocab=sc_vocab_file.vocabulary_file, + new_vocab_size=sc_vocab_file.vocabulary_size, + num_oov_buckets=sc_vocab_file.num_oov_buckets, + old_vocab="old_vocab.txt" + ) + ws = WarmStartSettings( + ckpt_to_initialize_from="/tmp", + var_name_to_vocab_info={ + "input_layer/sc_vocab_file_embedding/embedding_weights": vocab_info + }) + ``` + + Warm-start only `sc_vocab_file` embeddings (and no other variables), which + have a different vocab from the one used in the current model: + + ``` + vocab_info = tf.estimator.VocabInfo( + new_vocab=sc_vocab_file.vocabulary_file, + new_vocab_size=sc_vocab_file.vocabulary_size, + num_oov_buckets=sc_vocab_file.num_oov_buckets, + old_vocab="old_vocab.txt" + ) + ws = WarmStartSettings( + ckpt_to_initialize_from="/tmp", + vars_to_warm_start=None, + var_name_to_vocab_info={ + "input_layer/sc_vocab_file_embedding/embedding_weights": vocab_info + }) + ``` + + Warm-start all weights but the parameters corresponding to `sc_vocab_file` + have a different vocab from the one used in current checkpoint, and only + 100 of those entries were used: + + ``` + vocab_info = tf.estimator.VocabInfo( + new_vocab=sc_vocab_file.vocabulary_file, + new_vocab_size=sc_vocab_file.vocabulary_size, + num_oov_buckets=sc_vocab_file.num_oov_buckets, + old_vocab="old_vocab.txt", + old_vocab_size=100 + ) + ws = WarmStartSettings( + ckpt_to_initialize_from="/tmp", + var_name_to_vocab_info={ + "input_layer/sc_vocab_file_embedding/embedding_weights": vocab_info + }) + ``` + + Warm-start all weights but the parameters corresponding to `sc_vocab_file` + have a different vocab from the one used in current checkpoint and the + parameters corresponding to `sc_vocab_list` have a different name from the + current checkpoint: + + ``` + vocab_info = tf.estimator.VocabInfo( + new_vocab=sc_vocab_file.vocabulary_file, + new_vocab_size=sc_vocab_file.vocabulary_size, + num_oov_buckets=sc_vocab_file.num_oov_buckets, + old_vocab="old_vocab.txt", + old_vocab_size=100 + ) + ws = WarmStartSettings( + ckpt_to_initialize_from="/tmp", + var_name_to_vocab_info={ + "input_layer/sc_vocab_file_embedding/embedding_weights": vocab_info + }, + var_name_to_prev_var_name={ + "input_layer/sc_vocab_list_embedding/embedding_weights": + "old_tensor_name" + }) + ``` + + Warm-start all TRAINABLE variables: + + ``` + ws = WarmStartSettings(ckpt_to_initialize_from="/tmp", + vars_to_warm_start=".*") + ``` + + Warm-start all variables (including non-TRAINABLE): + + ``` + ws = WarmStartSettings(ckpt_to_initialize_from="/tmp", + vars_to_warm_start=[".*"]) + ``` + + Warm-start non-TRAINABLE variables "v1", "v1/Momentum", and "v2" but not + "v2/momentum": + + ``` + ws = WarmStartSettings(ckpt_to_initialize_from="/tmp", + vars_to_warm_start=["v1", "v2[^/]"]) + ``` + + Attributes: + ckpt_to_initialize_from: [Required] A string specifying the directory with + checkpoint file(s) or path to checkpoint from which to warm-start the + model parameters. + vars_to_warm_start: [Optional] One of the following: + + * A regular expression (string) that captures which variables to + warm-start (see tf.compat.v1.get_collection). This expression will only + consider variables in the TRAINABLE_VARIABLES collection -- if you need + to warm-start non_TRAINABLE vars (such as optimizer accumulators or + batch norm statistics), please use the below option. + * A list of strings, each a regex scope provided to + tf.compat.v1.get_collection with GLOBAL_VARIABLES (please see + tf.compat.v1.get_collection). For backwards compatibility reasons, this + is separate from the single-string argument type. + * A list of Variables to warm-start. If you do not have access to the + `Variable` objects at the call site, please use the above option. + * `None`, in which case only TRAINABLE variables specified in + `var_name_to_vocab_info` will be warm-started. + + Defaults to `'.*'`, which warm-starts all variables in the + TRAINABLE_VARIABLES collection. Note that this excludes variables such as + accumulators and moving statistics from batch norm. + var_name_to_vocab_info: [Optional] Dict of variable names (strings) to + `tf.estimator.VocabInfo`. The variable names should be "full" variables, + not the names of the partitions. If not explicitly provided, the variable + is assumed to have no (changes to) vocabulary. + var_name_to_prev_var_name: [Optional] Dict of variable names (strings) to + name of the previously-trained variable in `ckpt_to_initialize_from`. If + not explicitly provided, the name of the variable is assumed to be same + between previous checkpoint and current model. Note that this has no + effect on the set of variables that is warm-started, and only controls + name mapping (use `vars_to_warm_start` for controlling what variables to + warm-start). + """ + + def __new__(cls, + ckpt_to_initialize_from, + vars_to_warm_start='.*', + var_name_to_vocab_info=None, + var_name_to_prev_var_name=None): + if not ckpt_to_initialize_from: + raise ValueError( + '`ckpt_to_initialize_from` MUST be set in WarmStartSettings') + return super(WarmStartSettings, cls).__new__( + cls, + ckpt_to_initialize_from, + vars_to_warm_start, + var_name_to_vocab_info or {}, + var_name_to_prev_var_name or {}, + ) + + +def _get_default_warm_start_settings(warm_start_from): + """Returns default `tf.estimator.WarmStartSettings`. + + Args: + warm_start_from: Either a string representing the filepath of a checkpoint + or `SavedModel` to initialize from, or an instance of + `tf.estimator.WarmStartSettings`. + + Returns: + Either None or an instance of `WarmStartSettings`. + + Raises: + ValueError: If `warm_start_from` is not `None` but is neither a string nor + an instance of `WarmStartSettings`. + """ + if warm_start_from is None: + return None + if isinstance(warm_start_from, (six.string_types, six.binary_type)): + # Infer that this is a SavedModel if export_path + + # 'variables/variables.index' exists, and if so, construct the + # WarmStartSettings pointing to the variables path + # (export_path + 'variables/variables'). + if tf.compat.v1.gfile.Exists( + os.path.join( + path_helpers.get_variables_dir(warm_start_from), + tf.compat.as_text('variables.index'))): + tf.compat.v1.logging.info('Warm-starting from a SavedModel') + return WarmStartSettings( + ckpt_to_initialize_from=path_helpers.get_variables_path( + warm_start_from)) + return WarmStartSettings(ckpt_to_initialize_from=warm_start_from) + elif isinstance(warm_start_from, WarmStartSettings): + return warm_start_from + else: + raise ValueError('warm_start_from must be a string or a WarmStartSettings, ' + 'instead got {}'.format(type(warm_start_from))) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/estimator_export.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/estimator_export.py new file mode 100644 index 0000000000000000000000000000000000000000..b6b309b409acf61356b1c10ff76bacf89e51447c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/estimator_export.py @@ -0,0 +1,76 @@ +# Copyright 2023 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Utilities for exporting TensorFlow Estimator symbols to the API. + +Exporting a function or a class: + +To export a function or a class use the estimator_export decorator. For e.g.: +```python +@estimator_export('foo', 'bar.foo') +def foo(...): + ... +``` + +If a function is assigned to a variable, you can export it by calling +estimator_export explicitly. For e.g.: +```python +foo = get_foo(...) +estimator_export('foo', 'bar.foo')(foo) +``` + + +Exporting a constant +```python +foo = 1 +estimator_export('consts.foo').export_constant(__name__, 'foo') +``` +""" +from collections.abc import Sequence +from typing import Any, Optional, TypeVar + +from tensorflow.python.util import deprecation +from tensorflow.python.util import tf_export + +T = TypeVar('T') + + +class estimator_export(tf_export.api_export): # pylint: disable=invalid-name + """Provides ways to export symbols to the TensorFlow Estimator API.""" + + def __init__(self, *args: str, v1: Optional[Sequence[str]] = None): + """Export under the names *args (first one is considered canonical). + + All symbols exported by this decorator are exported under the `estimator` + API name. + + Args: + *args: API names in dot delimited format. + v1: Names for the TensorFlow V1 API. If not set, we will use V2 API names + both for TensorFlow V1 and V2 APIs. + """ + super().__init__(*args, api_name=tf_export.ESTIMATOR_API_NAME, v1=v1) + + def __call__(self, func: T) -> T: + """Calls this decorator. + + Args: + func: decorated symbol (function or class). + + Returns: + The input function with _tf_api_names attribute set and marked as + deprecated. + """ + func = deprecation.deprecated(None, 'Use tf.keras instead.')(func) + return super().__call__(func) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/estimator_lib.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/estimator_lib.py new file mode 100644 index 0000000000000000000000000000000000000000..4fbc3bfaac5796f972220245c7f7bbb26497a6aa --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/estimator_lib.py @@ -0,0 +1,72 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Estimator: High level tools for working with models.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +# pylint: disable=unused-import,line-too-long,wildcard-import +from tensorflow_estimator.python.estimator.canned.baseline import BaselineClassifier +from tensorflow_estimator.python.estimator.canned.baseline import BaselineEstimator +from tensorflow_estimator.python.estimator.canned.baseline import BaselineRegressor +from tensorflow_estimator.python.estimator.canned.dnn import dnn_logit_fn_builder +from tensorflow_estimator.python.estimator.canned.dnn import DNNClassifier +from tensorflow_estimator.python.estimator.canned.dnn import DNNEstimator +from tensorflow_estimator.python.estimator.canned.dnn import DNNRegressor +from tensorflow_estimator.python.estimator.canned.dnn_linear_combined import DNNLinearCombinedClassifier +from tensorflow_estimator.python.estimator.canned.dnn_linear_combined import DNNLinearCombinedEstimator +from tensorflow_estimator.python.estimator.canned.dnn_linear_combined import DNNLinearCombinedRegressor +from tensorflow_estimator.python.estimator.canned.kmeans import KMeansClustering +from tensorflow_estimator.python.estimator.canned.linear import linear_logit_fn_builder +from tensorflow_estimator.python.estimator.canned.linear import LinearClassifier +from tensorflow_estimator.python.estimator.canned.linear import LinearEstimator +from tensorflow_estimator.python.estimator.canned.linear import LinearRegressor +from tensorflow_estimator.python.estimator.canned.parsing_utils import classifier_parse_example_spec +from tensorflow_estimator.python.estimator.canned.parsing_utils import regressor_parse_example_spec +from tensorflow_estimator.python.estimator.canned.rnn import RNNClassifier +from tensorflow_estimator.python.estimator.canned.rnn import RNNEstimator +from tensorflow_estimator.python.estimator.early_stopping import * +from tensorflow_estimator.python.estimator.estimator import Estimator +from tensorflow_estimator.python.estimator.estimator import VocabInfo +from tensorflow_estimator.python.estimator.estimator import WarmStartSettings +from tensorflow_estimator.python.estimator.export import export_lib as export +from tensorflow_estimator.python.estimator.exporter import Exporter +from tensorflow_estimator.python.estimator.exporter import FinalExporter +from tensorflow_estimator.python.estimator.exporter import LatestExporter +from tensorflow_estimator.python.estimator.extenders import add_metrics +from tensorflow_estimator.python.estimator.head.base_head import Head +from tensorflow_estimator.python.estimator.head.binary_class_head import BinaryClassHead +from tensorflow_estimator.python.estimator.head.multi_class_head import MultiClassHead +from tensorflow_estimator.python.estimator.head.multi_head import MultiHead +from tensorflow_estimator.python.estimator.head.multi_label_head import MultiLabelHead +from tensorflow_estimator.python.estimator.head.regression_head import LogisticRegressionHead +from tensorflow_estimator.python.estimator.head.regression_head import PoissonRegressionHead +from tensorflow_estimator.python.estimator.head.regression_head import RegressionHead +from tensorflow_estimator.python.estimator.hooks import basic_session_run_hooks +from tensorflow_estimator.python.estimator.hooks import hooks +from tensorflow_estimator.python.estimator.hooks import session_run_hook +from tensorflow_estimator.python.estimator.inputs import inputs +from tensorflow_estimator.python.estimator.keras_lib import model_to_estimator +from tensorflow_estimator.python.estimator.mode_keys import ModeKeys +from tensorflow_estimator.python.estimator.model_fn import call_logit_fn +from tensorflow_estimator.python.estimator.model_fn import EstimatorSpec +from tensorflow_estimator.python.estimator.run_config import RunConfig +from tensorflow_estimator.python.estimator.tpu.tpu_estimator import TPUEstimator +from tensorflow_estimator.python.estimator.training import EvalSpec +from tensorflow_estimator.python.estimator.training import train_and_evaluate +from tensorflow_estimator.python.estimator.training import TrainSpec + +# pylint: enable=unused-import,line-too-long,wildcard-import diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/export/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/export/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/export/export.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/export/export.py new file mode 100644 index 0000000000000000000000000000000000000000..641a868418ec312985e9adc8697bc570afefeff5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/export/export.py @@ -0,0 +1,484 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Configuration and utilities for receiving inputs at serving time. + +Extends the export utils defined in core TensorFlow. + +Please avoid importing this file directly, all of the public functions have +been exported to export_lib.py. +""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import collections + +import six +import tensorflow as tf +from tensorflow.python.framework import ops +from tensorflow.python.saved_model.model_utils import export_utils +from tensorflow.python.saved_model.model_utils.export_utils import SINGLE_FEATURE_DEFAULT_NAME +from tensorflow.python.saved_model.model_utils.export_utils import SINGLE_LABEL_DEFAULT_NAME +from tensorflow.python.saved_model.model_utils.export_utils import SINGLE_RECEIVER_DEFAULT_NAME +from tensorflow_estimator.python.estimator import util +from tensorflow_estimator.python.estimator.estimator_export import estimator_export + +_SINGLE_TENSOR_DEFAULT_NAMES = { + 'feature': SINGLE_FEATURE_DEFAULT_NAME, + 'label': SINGLE_LABEL_DEFAULT_NAME, + 'receiver_tensor': SINGLE_RECEIVER_DEFAULT_NAME, + 'receiver_tensors_alternative': SINGLE_RECEIVER_DEFAULT_NAME +} + + +def wrap_and_check_input_tensors(tensors, field_name, allow_int_keys=False): + """Ensure that tensors is a dict of str to Tensor mappings. + + Args: + tensors: dict of `str` (or `int`s if `allow_int_keys=True`) to `Tensors`, or + a single `Tensor`. + field_name: name of the member field of `ServingInputReceiver` whose value + is being passed to `tensors`. + allow_int_keys: If set to true, the `tensor` dict keys may also be `int`s. + + Returns: + dict of str to Tensors; this is the original dict if one was passed, or + the original tensor wrapped in a dictionary. + + Raises: + ValueError: if tensors is None, or has non-string keys, + or non-Tensor values + """ + if tensors is None: + raise ValueError('{}s must be defined.'.format(field_name)) + if not isinstance(tensors, dict): + tensors = {_SINGLE_TENSOR_DEFAULT_NAMES[field_name]: tensors} + for name, tensor in tensors.items(): + _check_tensor_key(name, error_label=field_name, allow_ints=allow_int_keys) + _check_tensor(tensor, name, error_label=field_name) + return tensors + + +def _check_tensor(tensor, name, error_label='feature'): + """Check that passed `tensor` is a Tensor or SparseTensor or RaggedTensor.""" + if not (isinstance(tensor, tf.Tensor) or + isinstance(tensor, tf.sparse.SparseTensor) or + isinstance(tensor, tf.RaggedTensor)): + fmt_name = ' {}'.format(name) if name else '' + value_error = ValueError('{}{} must be a Tensor, SparseTensor, or ' + 'RaggedTensor.'.format(error_label, fmt_name)) + # NOTE(ericmc): This if-else block is a specific carve-out for + # LabeledTensor, which has a `.tensor` attribute and which is + # convertible to tf.Tensor via ops.convert_to_tensor. + # Allowing all types convertible to tf.Tensor is considered by soergel@ + # to be too permissive. + # TODO(soergel): accept any type convertible to Tensor, + # as in cl/193238295 snapshot #6. + if hasattr(tensor, 'tensor'): + try: + ops.convert_to_tensor(tensor) + except TypeError: + raise value_error + else: + raise value_error + + +def _check_tensor_key(name, error_label='feature', allow_ints=False): + if not isinstance(name, six.string_types): + if not allow_ints: + raise ValueError('{} keys must be strings: {}.'.format(error_label, name)) + elif not isinstance(name, six.integer_types): + raise ValueError('{} keys must be strings or ints: {}.'.format( + error_label, name)) + + +@estimator_export('estimator.export.ServingInputReceiver') +class ServingInputReceiver( + collections.namedtuple( + 'ServingInputReceiver', + ['features', 'receiver_tensors', 'receiver_tensors_alternatives'])): + """A return type for a serving_input_receiver_fn. + + Attributes: + features: A `Tensor`, `SparseTensor`, or dict of string or int to `Tensor` + or `SparseTensor`, specifying the features to be passed to the model. + Note: if `features` passed is not a dict, it will be wrapped in a dict + with a single entry, using 'feature' as the key. Consequently, the + model + must accept a feature dict of the form {'feature': tensor}. You may use + `TensorServingInputReceiver` if you want the tensor to be passed as is. + receiver_tensors: A `Tensor`, `SparseTensor`, or dict of string to `Tensor` + or `SparseTensor`, specifying input nodes where this receiver expects to + be fed by default. Typically, this is a single placeholder expecting + serialized `tf.Example` protos. + receiver_tensors_alternatives: a dict of string to additional groups of + receiver tensors, each of which may be a `Tensor`, `SparseTensor`, or dict + of string to `Tensor` or`SparseTensor`. These named receiver tensor + alternatives generate additional serving signatures, which may be used to + feed inputs at different points within the input receiver subgraph. A + typical usage is to allow feeding raw feature `Tensor`s *downstream* of + the tf.parse_example() op. Defaults to None. + """ + + def __new__(cls, + features, + receiver_tensors, + receiver_tensors_alternatives=None): + features = wrap_and_check_input_tensors( + features, 'feature', allow_int_keys=True) + + receiver_tensors = wrap_and_check_input_tensors(receiver_tensors, + 'receiver_tensor') + + if receiver_tensors_alternatives is not None: + if not isinstance(receiver_tensors_alternatives, dict): + raise ValueError( + 'receiver_tensors_alternatives must be a dict: {}.'.format( + receiver_tensors_alternatives)) + for alternative_name, receiver_tensors_alt in ( + six.iteritems(receiver_tensors_alternatives)): + # Updating dict during iteration is OK in this case. + receiver_tensors_alternatives[alternative_name] = ( + wrap_and_check_input_tensors(receiver_tensors_alt, + 'receiver_tensors_alternative')) + + return super(ServingInputReceiver, cls).__new__( + cls, + features=features, + receiver_tensors=receiver_tensors, + receiver_tensors_alternatives=receiver_tensors_alternatives) + + +@estimator_export('estimator.export.TensorServingInputReceiver') +class TensorServingInputReceiver( + collections.namedtuple( + 'TensorServingInputReceiver', + ['features', 'receiver_tensors', 'receiver_tensors_alternatives'])): + """A return type for a serving_input_receiver_fn. + + This is for use with models that expect a single `Tensor` or `SparseTensor` + as an input feature, as opposed to a dict of features. + + The normal `ServingInputReceiver` always returns a feature dict, even if it + contains only one entry, and so can be used only with models that accept such + a dict. For models that accept only a single raw feature, the + `serving_input_receiver_fn` provided to `Estimator.export_saved_model()` + should return this `TensorServingInputReceiver` instead. See: + https://github.com/tensorflow/tensorflow/issues/11674 + + Note that the receiver_tensors and receiver_tensor_alternatives arguments + will be automatically converted to the dict representation in either case, + because the SavedModel format requires each input `Tensor` to have a name + (provided by the dict key). + + Attributes: + features: A single `Tensor` or `SparseTensor`, representing the feature to + be passed to the model. + receiver_tensors: A `Tensor`, `SparseTensor`, or dict of string to `Tensor` + or `SparseTensor`, specifying input nodes where this receiver expects to + be fed by default. Typically, this is a single placeholder expecting + serialized `tf.Example` protos. + receiver_tensors_alternatives: a dict of string to additional groups of + receiver tensors, each of which may be a `Tensor`, `SparseTensor`, or dict + of string to `Tensor` or`SparseTensor`. These named receiver tensor + alternatives generate additional serving signatures, which may be used to + feed inputs at different points within the input receiver subgraph. A + typical usage is to allow feeding raw feature `Tensor`s *downstream* of + the tf.parse_example() op. Defaults to None. + """ + + def __new__(cls, + features, + receiver_tensors, + receiver_tensors_alternatives=None): + if features is None: + raise ValueError('features must be defined.') + _check_tensor(features, None) + + receiver = ServingInputReceiver( + features=features, + receiver_tensors=receiver_tensors, + receiver_tensors_alternatives=receiver_tensors_alternatives) + + return super(TensorServingInputReceiver, cls).__new__( + cls, + features=receiver.features[SINGLE_FEATURE_DEFAULT_NAME], + receiver_tensors=receiver.receiver_tensors, + receiver_tensors_alternatives=receiver.receiver_tensors_alternatives) + + +class UnsupervisedInputReceiver(ServingInputReceiver): + """A return type for a training_input_receiver_fn or eval_input_receiver_fn. + + This differs from SupervisedInputReceiver in that it does not require a set + of labels. + + Attributes: + features: A `Tensor`, `SparseTensor`, or dict of string to `Tensor` or + `SparseTensor`, specifying the features to be passed to the model. + receiver_tensors: A `Tensor`, `SparseTensor`, or dict of string to `Tensor` + or `SparseTensor`, specifying input nodes where this receiver expects to + be fed by default. Typically, this is a single placeholder expecting + serialized `tf.Example` protos. + """ + + def __new__(cls, features, receiver_tensors): + return super(UnsupervisedInputReceiver, cls).__new__( + cls, + features=features, + receiver_tensors=receiver_tensors, + receiver_tensors_alternatives=None) + + +class SupervisedInputReceiver( + collections.namedtuple('SupervisedInputReceiver', + ['features', 'labels', 'receiver_tensors'])): + """A return type for a training_input_receiver_fn or eval_input_receiver_fn. + + This differs from a ServingInputReceiver in that (1) this receiver expects + a set of labels to be passed in with features, and (2) this receiver does + not support receiver_tensors_alternatives, which are primarily used for + serving. + + The expected return values are: + features: A `Tensor`, `SparseTensor`, or dict of string or int to `Tensor` + or `SparseTensor`, specifying the features to be passed to the model. + labels: A `Tensor`, `SparseTensor`, or dict of string or int to `Tensor` or + `SparseTensor`, specifying the labels to be passed to the model. + receiver_tensors: A `Tensor`, `SparseTensor`, or dict of string to `Tensor` + or `SparseTensor`, specifying input nodes where this receiver expects to + be fed by default. Typically, this is a single placeholder expecting + serialized `tf.Example` protos. + + """ + + def __new__(cls, features, labels, receiver_tensors): + # Both features and labels can be dicts or raw tensors. + # wrap_and_check_input_tensors is called here only to validate the tensors. + # The wrapped dict that is returned is deliberately discarded. + wrap_and_check_input_tensors(features, 'feature', allow_int_keys=True) + wrap_and_check_input_tensors(labels, 'label', allow_int_keys=True) + + receiver_tensors = wrap_and_check_input_tensors(receiver_tensors, + 'receiver_tensor') + + return super(SupervisedInputReceiver, cls).__new__( + cls, + features=features, + labels=labels, + receiver_tensors=receiver_tensors) + + +@estimator_export('estimator.export.build_parsing_serving_input_receiver_fn') +def build_parsing_serving_input_receiver_fn(feature_spec, + default_batch_size=None): + """Build a serving_input_receiver_fn expecting fed tf.Examples. + + Creates a serving_input_receiver_fn that expects a serialized tf.Example fed + into a string placeholder. The function parses the tf.Example according to + the provided feature_spec, and returns all parsed Tensors as features. + + Args: + feature_spec: a dict of string to `VarLenFeature`/`FixedLenFeature`. + default_batch_size: the number of query examples expected per batch. Leave + unset for variable batch size (recommended). + + Returns: + A serving_input_receiver_fn suitable for use in serving. + """ + + def serving_input_receiver_fn(): + """An input_fn that expects a serialized tf.Example.""" + serialized_tf_example = tf.compat.v1.placeholder( + dtype=tf.dtypes.string, + shape=[default_batch_size], + name='input_example_tensor') + receiver_tensors = {'examples': serialized_tf_example} + features = tf.compat.v1.io.parse_example(serialized_tf_example, + feature_spec) + return ServingInputReceiver(features, receiver_tensors) + + return serving_input_receiver_fn + + +def _placeholder_from_tensor(t, default_batch_size=None): + """Creates a placeholder that matches the dtype and shape of passed tensor. + + Args: + t: Tensor or EagerTensor + default_batch_size: the number of query examples expected per batch. Leave + unset for variable batch size (recommended). + + Returns: + Placeholder that matches the passed tensor. + """ + batch_shape = tf.TensorShape([default_batch_size]) + shape = batch_shape.concatenate(t.get_shape()[1:]) + + # Reuse the feature tensor's op name (t.op.name) for the placeholder, + # excluding the index from the tensor's name (t.name): + # t.name = "%s:%d" % (t.op.name, t._value_index) + try: + name = t.op.name + except AttributeError: + # In Eager mode, tensors don't have ops or names, and while they do have + # IDs, those are not maintained across runs. The name here is used + # primarily for debugging, and is not critical to the placeholder. + # So, in order to make this Eager-compatible, continue with an empty + # name if none is available. + name = None + + return tf.compat.v1.placeholder(dtype=t.dtype, shape=shape, name=name) + + +def _placeholders_from_receiver_tensors_dict(input_vals, + default_batch_size=None): + return { + name: _placeholder_from_tensor(t, default_batch_size) + for name, t in input_vals.items() + } + + +@estimator_export('estimator.export.build_raw_serving_input_receiver_fn') +def build_raw_serving_input_receiver_fn(features, default_batch_size=None): + """Build a serving_input_receiver_fn expecting feature Tensors. + + Creates an serving_input_receiver_fn that expects all features to be fed + directly. + + Args: + features: a dict of string to `Tensor`. + default_batch_size: the number of query examples expected per batch. Leave + unset for variable batch size (recommended). + + Returns: + A serving_input_receiver_fn. + """ + + def serving_input_receiver_fn(): + """A serving_input_receiver_fn that expects features to be fed directly.""" + receiver_tensors = _placeholders_from_receiver_tensors_dict( + features, default_batch_size) + return ServingInputReceiver(receiver_tensors, receiver_tensors) + + return serving_input_receiver_fn + + +@estimator_export( + 'estimator.experimental.build_raw_supervised_input_receiver_fn') +def build_raw_supervised_input_receiver_fn(features, + labels, + default_batch_size=None): + """Build a supervised_input_receiver_fn for raw features and labels. + + This function wraps tensor placeholders in a supervised_receiver_fn + with the expectation that the features and labels appear precisely as + the model_fn expects them. Features and labels can therefore be dicts of + tensors, or raw tensors. + + Args: + features: a dict of string to `Tensor` or `Tensor`. + labels: a dict of string to `Tensor` or `Tensor`. + default_batch_size: the number of query examples expected per batch. Leave + unset for variable batch size (recommended). + + Returns: + A supervised_input_receiver_fn. + + Raises: + ValueError: if features and labels have overlapping keys. + """ + # Check for overlapping keys before beginning. + try: + feat_keys = features.keys() + except AttributeError: + feat_keys = [SINGLE_RECEIVER_DEFAULT_NAME] + try: + label_keys = labels.keys() + except AttributeError: + label_keys = [SINGLE_LABEL_DEFAULT_NAME] + + overlap_keys = set(feat_keys) & set(label_keys) + if overlap_keys: + raise ValueError('Features and labels must have distinct keys. ' + 'Found overlapping keys: {}'.format(overlap_keys)) + + def supervised_input_receiver_fn(): + """A receiver_fn that expects pass-through features and labels.""" + if not isinstance(features, dict): + features_cp = _placeholder_from_tensor(features, default_batch_size) + receiver_features = {SINGLE_RECEIVER_DEFAULT_NAME: features_cp} + else: + receiver_features = _placeholders_from_receiver_tensors_dict( + features, default_batch_size) + features_cp = receiver_features + + if not isinstance(labels, dict): + labels_cp = _placeholder_from_tensor(labels, default_batch_size) + receiver_labels = {SINGLE_LABEL_DEFAULT_NAME: labels_cp} + else: + receiver_labels = _placeholders_from_receiver_tensors_dict( + labels, default_batch_size) + labels_cp = receiver_labels + + receiver_tensors = dict(receiver_features) + receiver_tensors.update(receiver_labels) + return SupervisedInputReceiver(features_cp, labels_cp, receiver_tensors) + + return supervised_input_receiver_fn + + +def build_supervised_input_receiver_fn_from_input_fn(input_fn, **input_fn_args): + """Get a function that returns a SupervisedInputReceiver matching an input_fn. + + Note that this function calls the input_fn in a local graph in order to + extract features and labels. Placeholders are then created from those + features and labels in the default graph. + + Args: + input_fn: An Estimator input_fn, which is a function that returns one of: + * A 'tf.data.Dataset' object: Outputs of `Dataset` object must be a tuple + (features, labels) with same constraints as below. + * A tuple (features, labels): Where `features` is a `Tensor` or a + dictionary of string feature name to `Tensor` and `labels` is a `Tensor` + or a dictionary of string label name to `Tensor`. Both `features` and + `labels` are consumed by `model_fn`. They should satisfy the expectation + of `model_fn` from inputs. + **input_fn_args: set of kwargs to be passed to the input_fn. Note that these + will not be checked or validated here, and any errors raised by the + input_fn will be thrown to the top. + + Returns: + A function taking no arguments that, when called, returns a + SupervisedInputReceiver. This function can be passed in as part of the + input_receiver_map when exporting SavedModels from Estimator with multiple + modes. + """ + # Wrap the input_fn call in a graph to prevent sullying the default namespace + with tf.Graph().as_default(): + result = input_fn(**input_fn_args) + features, labels, _ = util.parse_input_fn_result(result) + # Placeholders are created back in the default graph. + return build_raw_supervised_input_receiver_fn(features, labels) + + +### Below utilities are specific to SavedModel exports. +# TODO(kathywu): Rename all references to use the original definition in +# model_utils, or estimator/export/export_lib.py if other estimator export +# functions are used. +build_all_signature_defs = export_utils.build_all_signature_defs +get_temp_export_dir = export_utils.get_temp_export_dir +get_timestamped_export_dir = export_utils.get_timestamped_export_dir diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/export/export_lib.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/export/export_lib.py new file mode 100644 index 0000000000000000000000000000000000000000..167e6ece0ba2b0e5fb6bd20abc7f29eab0d87e7b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/export/export_lib.py @@ -0,0 +1,48 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""All public utility methods for exporting Estimator to SavedModel. + +This file includes functions and constants from core (model_utils) and export.py +""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +# pylint: disable=unused-import,line-too-long, wildcard-import +from tensorflow.python.saved_model.model_utils import build_all_signature_defs +from tensorflow.python.saved_model.model_utils import export_outputs_for_mode +from tensorflow.python.saved_model.model_utils import EXPORT_TAG_MAP +from tensorflow.python.saved_model.model_utils import get_export_outputs +from tensorflow.python.saved_model.model_utils import get_temp_export_dir +from tensorflow.python.saved_model.model_utils import get_timestamped_export_dir +from tensorflow.python.saved_model.model_utils import SIGNATURE_KEY_MAP +from tensorflow.python.saved_model.model_utils.export_output import _SupervisedOutput +from tensorflow.python.saved_model.model_utils.export_output import ClassificationOutput +from tensorflow.python.saved_model.model_utils.export_output import EvalOutput +from tensorflow.python.saved_model.model_utils.export_output import ExportOutput +from tensorflow.python.saved_model.model_utils.export_output import PredictOutput +from tensorflow.python.saved_model.model_utils.export_output import RegressionOutput +from tensorflow.python.saved_model.model_utils.export_output import TrainOutput +from tensorflow_estimator.python.estimator.export.export import build_parsing_serving_input_receiver_fn +from tensorflow_estimator.python.estimator.export.export import build_raw_serving_input_receiver_fn +from tensorflow_estimator.python.estimator.export.export import build_raw_supervised_input_receiver_fn +from tensorflow_estimator.python.estimator.export.export import build_supervised_input_receiver_fn_from_input_fn +from tensorflow_estimator.python.estimator.export.export import ServingInputReceiver +from tensorflow_estimator.python.estimator.export.export import SupervisedInputReceiver +from tensorflow_estimator.python.estimator.export.export import TensorServingInputReceiver +from tensorflow_estimator.python.estimator.export.export import UnsupervisedInputReceiver +from tensorflow_estimator.python.estimator.export.export import wrap_and_check_input_tensors +# pylint: enable=unused-import,line-too-long, wildcard-import diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/export/export_output.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/export/export_output.py new file mode 100644 index 0000000000000000000000000000000000000000..2279d9004f20b5e7352361e963c6aaff4597762e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/export/export_output.py @@ -0,0 +1,36 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Classes for different types of export output.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +# pylint: disable=unused-import +from tensorflow.python.saved_model.model_utils.export_output import _SupervisedOutput +from tensorflow.python.saved_model.model_utils.export_output import ClassificationOutput +from tensorflow.python.saved_model.model_utils.export_output import EvalOutput +from tensorflow.python.saved_model.model_utils.export_output import ExportOutput +from tensorflow.python.saved_model.model_utils.export_output import PredictOutput +from tensorflow.python.saved_model.model_utils.export_output import RegressionOutput +from tensorflow.python.saved_model.model_utils.export_output import TrainOutput +# pylint: enable=unused-import +from tensorflow_estimator.python.estimator.estimator_export import estimator_export + +estimator_export('estimator.export.ExportOutput')(ExportOutput) +estimator_export('estimator.export.ClassificationOutput')(ClassificationOutput) +estimator_export('estimator.export.RegressionOutput')(RegressionOutput) +estimator_export('estimator.export.PredictOutput')(PredictOutput) +estimator_export('estimator.export.EvalOutput')(EvalOutput) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/export/function.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/export/function.py new file mode 100644 index 0000000000000000000000000000000000000000..63beadfdea27e79c4291f7da8d2de58c35b625f4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/export/function.py @@ -0,0 +1,398 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Defines class for wrapping an Estimator model function.""" +# TODO(kathywu): support remaining outputs from the EstimatorSpec. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import six +import tensorflow as tf +from tensorflow.python.eager import function +from tensorflow.python.eager import wrap_function +from tensorflow.python.framework import func_graph +from tensorflow.python.saved_model.model_utils import export_utils +from tensorflow.python.util import function_utils +from tensorflow_estimator.python.estimator import model_fn as model_fn_lib +from tensorflow_estimator.python.estimator.mode_keys import ModeKeys + + +class ModelFunction(tf.compat.v2.__internal__.tracking.AutoTrackable): + """A checkpointable ModelFunction object. + + This object stores a global mapping of variables and functions for each mode. + """ + + def __init__(self, config=None, params=None): + self._config = config + self._params = params + self._functions = {} + + self._variable_holder = wrap_function.VariableHolder(share_variables=True) + + # Add reference to the variable holder's mapping of variables, which is a + # trackable object. + self._variables_by_name = self._variable_holder.variables + + @staticmethod + def from_function(model_fn, all_modes=None, config=None, params=None): + """Creates a new ModelFunction object from a model function.""" + if all_modes is None: + all_modes = [ModeKeys.TRAIN, ModeKeys.EVAL, ModeKeys.PREDICT] + else: + all_modes = list(all_modes) + + obj = ModelFunction(config=config, params=params) + for mode in all_modes: + obj.add_mode(model_fn, mode) + return obj + + @property + def variables(self): + return self._variables_by_name + + def add_mode(self, fn, mode, input_signature=None): + if mode in self._functions: + raise ValueError('ModelFunction object has multiple functions with name' + ' {}.'.format(mode)) + + spec_fn = EstimatorSpecFunction( + fn, + mode, + config=self._config, + params=self._params, + variable_holder=self._variable_holder, + input_signature=input_signature) + + self._functions[mode] = spec_fn + + def train(self, features, labels): + return self.call(ModeKeys.TRAIN, features, labels) + + def evaluate(self, features, labels): + return self.call(ModeKeys.EVAL, features, labels) + + def predict(self, features): + return self.call(ModeKeys.PREDICT, features) + + def call(self, mode, features, labels=None): + if mode not in self._functions: + raise ValueError( + 'Mode {} is not defined the ModelFunction. To add modes,' + ' use the `add_mode()` function. Available modes: {}'.format( + mode, self._functions.keys())) + fn = self._functions[mode] + if fn.expects_labels: + return fn(features, labels) + else: + return fn(features) + + +def _wrap_and_verify_model_fn(model_fn, + mode=None, + config=None, + params=None, + input_signature=None): + """Returns a function that only has only tensor arguments (features, labels). + + Args: + model_fn: Model function. Must follow the signature defined in + `tf.estimator.Estimator`. + mode: Optional string `tf.estimstor.ModeKey`. + config: Optional `estimator.RunConfig` object. + params: Optional `dict` of hyperparameters. + input_signature: Possibly nested TensorSpec of the tensor arguments. + + Returns: + tuple of ( + function that only accepts tensor arguments (features and/or labels), + whether the returned function expects a labels argument) + """ + model_fn_lib.verify_model_fn_args(model_fn, params) + args = function_utils.fn_args(model_fn) + kwargs = {} + if 'mode' in args: + kwargs['mode'] = mode + if 'params' in args: + kwargs['params'] = params + if 'config' in args: + kwargs['config'] = config + + if 'labels' in args: + if input_signature is None or len(input_signature) == 2: + + def wrapped_model_fn(features, labels=None): + return model_fn(features=features, labels=labels, **kwargs) + else: + + def wrapped_model_fn(features): + return model_fn(features=features, labels=None, **kwargs) + else: + + def wrapped_model_fn(features): + return model_fn(features=features, **kwargs) + + return wrapped_model_fn, 'labels' in args + + +class EstimatorSpecFunction(tf.compat.v2.__internal__.function.Function): + """Wraps graph functions defined for a function returning an EstimatorSpec. + + Instances of this class are revivable when attached to a checkpointable + object. + """ + + def __init__(self, + fn, + mode, + config=None, + params=None, + variable_holder=None, + **kwargs): + """Initializes an EstimatorSpecFunction. + + Args: + fn: Python model function. + mode: String mode to run the function. + config: RunConfig that is passed to the `config` arg in the function. + params: object that is passed to the `params` argument in the function. + variable_holder: Optional `wrap_function.VariableHolder` object. + **kwargs: Optional keyword arguments to pass to tf.function (e.g. + input_signature). + """ + python_function, self.expects_labels = _wrap_and_verify_model_fn( + fn, + mode=mode, + config=config, + params=params, + input_signature=kwargs.get('input_signature', None)) + super(EstimatorSpecFunction, self).__init__(python_function, mode, **kwargs) + self._variable_holder = variable_holder + + def _defun(self, fn): + return _EstimatorSpecFunction( + fn, + name=self._name, + variable_holder=self._variable_holder, + input_signature=self.input_signature, + autograph=self._autograph, + autograph_options=self._experimental_autograph_options) + + +class _EstimatorSpecFunction(tf.compat.v2.__internal__.function.Function): + """Wraps graph functions defined for a function returning an EstimatorSpec. + + This object handles creation of the graph functions. + """ + + def __init__(self, python_function, name, variable_holder=None, **kwargs): + super(_EstimatorSpecFunction, self).__init__(python_function, name, + **kwargs) + self._variable_holder = variable_holder + + def _create_graph_function(self, args, kwargs, **other_kwargs): + _ = other_kwargs + wrapped_graph = _EstimatorWrappedGraph(self._variable_holder) + return wrapped_graph.wrap_model_fn( + self._python_function, + self._name, + signature=self.input_signature, + args=args, + kwargs=kwargs) + + +class _EstimatorWrappedGraph(wrap_function.WrappedGraph): + """WrappedGraph that handles global step creation and wraps estimator fns.""" + + def __init__(self, *args, **kwargs): + super(_EstimatorWrappedGraph, self).__init__(*args, **kwargs) + # Create global step variable, which may be used by the input and model fns. + self._global_step_read_fn = self.wrap_function( + self._global_step, signature=[]) + + self._concrete_model_fn = None + + # Original EstimatorSpec object returned by the model function. Only tensors + # and ops are returned by the concrete model function. + self._estimator_spec = None + + def _global_step(self): + return tf.compat.v1.train.get_or_create_global_step() + + @property + def global_step(self): + return self._global_step_read_fn() + + @property + def model_fn(self): + return self._concrete_model_fn + + @property + def estimator_spec(self): + if self._concrete_model_fn is None: + raise ValueError('Please wrap a model function first.') + return self._estimator_spec + + def wrap_model_fn(self, + model_fn, + mode, + args=None, + kwargs=None, + signature=None): + """Wraps a model function, and stores the returned estimator spec.""" + if self._concrete_model_fn is not None: + raise ValueError('`wrap_model_fn` should be only called once per graph.') + + def fn(*args, **kwargs): + """Returns tensor and op outputs from the returned spec.""" + ret = model_fn(*args, **kwargs) + + if isinstance(ret, model_fn_lib.EstimatorSpec): + self._estimator_spec = ret + return _filter_estimator_spec_outputs(ret) + return ret + + name = 'model_fn_{}'.format(mode) + self._concrete_model_fn = self._wrap_function(fn, args, kwargs, signature, + name) + return self._concrete_model_fn + + def wrap_input_receiver_fn(self, input_receiver_fn): + """Converts an input receiver function to one or more concrete functions. + + Input receiver functions are python functions with no arguments. + Placeholders are created within the function and used to receive inputs to + the model. + + The function (or multiple functions) generated depends on the InputReceiver + object returned by `input_receiver_fn`. + + Generally, the returned function will have inputs and outputs: + input_receiver(**receiver_tensors) --> features + + or (if the InputReceiver returns labels): + input_receiver(**receiver_tensors) --> features, labels + + __Alternate Receiver Tensors__ + + The InputReceiver may have alternate receiver tensors, in which case + additional concrete functions are generated. Example: + InputReceiver.receiver_tensors_alternatives = { + 'alt_input_1': Tensor, + 'alt_input_2': { + 'tensor_1': Tensor, + 'tensor_2': Tensor + } + } + + This will generate concrete functions: + input_receiver_alt_input_1(input) --> features + input_receiver_alt_input_2(tensor_1, tensor_2) --> features + + Args: + input_receiver_fn: a no-argument function that returns an `InputReceiver` + object. + + Returns: + A list of tuples of (concrete function, receiver name). The name of the + default input receiver is `None`. + """ + ret = [None] + + def fn(): + ret[0] = input_receiver = input_receiver_fn() + features = input_receiver.features + labels = getattr(input_receiver, 'labels', None) + + if labels is None: + return features + return features, labels + + func_graph.func_graph_from_py_func( + None, # Name is unused. + self._variable_holder.call_with_variable_creator_scope(fn), + args=None, + kwargs=None, + signature=[], + add_control_dependencies=False, + func_graph=self.graph) + + functions = [] + input_receiver = ret[0] + + wrapped_input_receiver_fn = _prune_receiver_tensors( + self._wrapped_function, + receiver_tensors=input_receiver.receiver_tensors, + outputs=self.graph.structured_outputs, + name=_input_receiver_fn_name(None)) + functions.append((wrapped_input_receiver_fn, None)) + + receiver_tensors_alternatives = getattr(input_receiver, + 'receiver_tensors_alternatives', + None) + + if receiver_tensors_alternatives: + for receiver_name, receiver_tensors_alt in ( + six.iteritems(receiver_tensors_alternatives)): + receiver_tensors_alt = _canonicalize_receiver_tensors( + receiver_tensors_alt) + wrapped_input_receiver_fn = _prune_receiver_tensors( + self._wrapped_function, + receiver_tensors=receiver_tensors_alt, + outputs=self.graph.structured_outputs, + name=_input_receiver_fn_name(receiver_name)) + functions.append((wrapped_input_receiver_fn, receiver_name)) + return functions + + +def _filter_estimator_spec_outputs(spec): + """Filters tensors and ops from an EstimatorSpec and returns a dictionary.""" + # TODO(kathywu): Add loss, export outputs, eval metrics depending on the mode. + if spec.mode == ModeKeys.TRAIN: + return dict(predictions=spec.predictions, train_op=spec.train_op) + return dict(predictions=spec.predictions) + + +_RECEIVER_FN_NAME = '_input_receiver' + + +def _canonicalize_receiver_tensors(receiver_tensors): + """Converts receiver tensors to the expected format of `as_signature_def`.""" + # TODO(b/129646028): Wrap function doesn't support composite tensors. + for tensor in tf.nest.flatten(receiver_tensors): + if not isinstance(tensor, tf.Tensor): + raise ValueError('All receiver tensors must be tensors (composite ' + 'tensors are not yet supported).') + + if isinstance(receiver_tensors, dict): + return receiver_tensors + return {export_utils.SINGLE_RECEIVER_DEFAULT_NAME: receiver_tensors} + + +def _input_receiver_fn_name(name): + if name is None: + return _RECEIVER_FN_NAME + else: + return '{}_{}'.format(_RECEIVER_FN_NAME, name) + + +def _prune_receiver_tensors(wrapped_function, receiver_tensors, outputs, name): + inputs = _canonicalize_receiver_tensors(receiver_tensors) + return wrapped_function.prune( + inputs, + outputs, + name=name, + input_signature=(None, func_graph.convert_structure_to_signature(inputs))) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/exporter.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/exporter.py new file mode 100644 index 0000000000000000000000000000000000000000..0b73a8ed7d98d881776d175f3de1342a2dc10797 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/exporter.py @@ -0,0 +1,509 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""`Exporter` class represents different flavors of model export.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import abc +import os +import tensorflow as tf +from tensorflow_estimator.python.estimator import gc +from tensorflow_estimator.python.estimator import util +from tensorflow_estimator.python.estimator.canned import metric_keys +from tensorflow_estimator.python.estimator.estimator_export import estimator_export + + +@estimator_export('estimator.Exporter') +class Exporter(object): + """A class representing a type of model export.""" + + @abc.abstractproperty + def name(self): + """Directory name. + + A directory name under the export base directory where exports of + this type are written. Should not be `None` nor empty. + """ + pass + + @abc.abstractmethod + def export(self, estimator, export_path, checkpoint_path, eval_result, + is_the_final_export): + """Exports the given `Estimator` to a specific format. + + Args: + estimator: the `Estimator` to export. + export_path: A string containing a directory where to write the export. + checkpoint_path: The checkpoint path to export. + eval_result: The output of `Estimator.evaluate` on this checkpoint. + is_the_final_export: This boolean is True when this is an export in the + end of training. It is False for the intermediate exports during the + training. When passing `Exporter` to `tf.estimator.train_and_evaluate` + `is_the_final_export` is always False if `TrainSpec.max_steps` is + `None`. + + Returns: + The string path to the exported directory or `None` if export is skipped. + """ + pass + + +class _SavedModelExporter(Exporter): + """This class exports the serving graph and checkpoints. + + This class provides a basic exporting functionality and serves as a + foundation for specialized `Exporter`s. + """ + + def __init__(self, + name, + serving_input_receiver_fn, + assets_extra=None, + as_text=False): + """Create an `Exporter` to use with `tf.estimator.EvalSpec`. + + Args: + name: unique name of this `Exporter` that is going to be used in the + export path. + serving_input_receiver_fn: a function that takes no arguments and returns + a `ServingInputReceiver`. + assets_extra: An optional dict specifying how to populate the assets.extra + directory within the exported SavedModel. Each key should give the + destination path (including the filename) relative to the assets.extra + directory. The corresponding value gives the full path of the source + file to be copied. For example, the simple case of copying a single + file without renaming it is specified as + `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`. + as_text: whether to write the SavedModel proto in text format. Defaults to + `False`. + + Raises: + ValueError: if any arguments is invalid. + """ + self._name = name + self._serving_input_receiver_fn = serving_input_receiver_fn + self._assets_extra = assets_extra + self._as_text = as_text + + @property + def name(self): + return self._name + + def export(self, estimator, export_path, checkpoint_path, eval_result, + is_the_final_export): + del is_the_final_export + + export_result = estimator.export_saved_model( + export_path, + self._serving_input_receiver_fn, + assets_extra=self._assets_extra, + as_text=self._as_text, + checkpoint_path=checkpoint_path) + + return export_result + + +def _loss_smaller(best_eval_result, current_eval_result): + """Compares two evaluation results and returns true if the 2nd one is smaller. + + Both evaluation results should have the values for MetricKeys.LOSS, which are + used for comparison. + + Args: + best_eval_result: best eval metrics. + current_eval_result: current eval metrics. + + Returns: + True if the loss of current_eval_result is smaller; otherwise, False. + + Raises: + ValueError: If input eval result is None or no loss is available. + """ + default_key = metric_keys.MetricKeys.LOSS + if not best_eval_result or default_key not in best_eval_result: + raise ValueError( + 'best_eval_result cannot be empty or no loss is found in it.') + + if not current_eval_result or default_key not in current_eval_result: + raise ValueError( + 'current_eval_result cannot be empty or no loss is found in it.') + + return best_eval_result[default_key] > current_eval_result[default_key] + + +def _verify_compare_fn_args(compare_fn): + """Verifies compare_fn arguments.""" + args = set(util.fn_args(compare_fn)) + if 'best_eval_result' not in args: + raise ValueError('compare_fn (%s) must include best_eval_result argument.' % + compare_fn) + if 'current_eval_result' not in args: + raise ValueError( + 'compare_fn (%s) must include current_eval_result argument.' % + compare_fn) + non_valid_args = list(args - set(['best_eval_result', 'current_eval_result'])) + if non_valid_args: + raise ValueError('compare_fn (%s) has following not expected args: %s' % + (compare_fn, non_valid_args)) + + +@estimator_export('estimator.BestExporter') +class BestExporter(Exporter): + """This class exports the serving graph and checkpoints of the best models. + + This class performs a model export everytime the new model is better than any + existing model. + """ + + def __init__(self, + name='best_exporter', + serving_input_receiver_fn=None, + event_file_pattern='eval/*.tfevents.*', + compare_fn=_loss_smaller, + assets_extra=None, + as_text=False, + exports_to_keep=5): + """Create an `Exporter` to use with `tf.estimator.EvalSpec`. + + Example of creating a BestExporter for training and evaluation: + + ```python + def make_train_and_eval_fn(): + # Set up feature columns. + categorical_feature_a = ( + tf.feature_column.categorical_column_with_hash_bucket(...)) + categorical_feature_a_emb = embedding_column( + categorical_column=categorical_feature_a, ...) + ... # other feature columns + + estimator = tf.estimator.DNNClassifier( + config=tf.estimator.RunConfig( + model_dir='/my_model', save_summary_steps=100), + feature_columns=[categorical_feature_a_emb, ...], + hidden_units=[1024, 512, 256]) + + serving_feature_spec = tf.feature_column.make_parse_example_spec( + categorical_feature_a_emb) + serving_input_receiver_fn = ( + tf.estimator.export.build_parsing_serving_input_receiver_fn( + serving_feature_spec)) + + exporter = tf.estimator.BestExporter( + name="best_exporter", + serving_input_receiver_fn=serving_input_receiver_fn, + exports_to_keep=5) + + train_spec = tf.estimator.TrainSpec(...) + + eval_spec = [tf.estimator.EvalSpec( + input_fn=eval_input_fn, + steps=100, + exporters=exporter, + start_delay_secs=0, + throttle_secs=5)] + + tf.estimator.train_and_evaluate(estimator, train_spec, eval_spec) + + ``` + + Args: + name: unique name of this `Exporter` that is going to be used in the + export path. + serving_input_receiver_fn: a function that takes no arguments and returns + a `ServingInputReceiver`. + event_file_pattern: event file name pattern relative to model_dir. If + None, however, the exporter would not be preemption-safe. To be + preemption-safe, event_file_pattern must be specified. + compare_fn: a function that compares two evaluation results and returns + true if current evaluation result is better. Follows the signature: + * Args: + * `best_eval_result`: This is the evaluation result of the best model. + * `current_eval_result`: This is the evaluation result of current + candidate model. + * Returns: True if current evaluation result is better; otherwise, + False. + assets_extra: An optional dict specifying how to populate the assets.extra + directory within the exported SavedModel. Each key should give the + destination path (including the filename) relative to the assets.extra + directory. The corresponding value gives the full path of the source + file to be copied. For example, the simple case of copying a single + file without renaming it is specified as `{'my_asset_file.txt': + '/path/to/my_asset_file.txt'}`. + as_text: whether to write the SavedModel proto in text format. Defaults to + `False`. + exports_to_keep: Number of exports to keep. Older exports will be + garbage-collected. Defaults to 5. Set to `None` to disable garbage + collection. + + Raises: + ValueError: if any argument is invalid. + """ + self._compare_fn = compare_fn + if self._compare_fn is None: + raise ValueError('`compare_fn` must not be None.') + _verify_compare_fn_args(self._compare_fn) + + self._saved_model_exporter = _SavedModelExporter(name, + serving_input_receiver_fn, + assets_extra, as_text) + + self._event_file_pattern = event_file_pattern + self._model_dir = None + self._best_eval_result = None + self._has_exported = False + + self._exports_to_keep = exports_to_keep + if exports_to_keep is not None and exports_to_keep <= 0: + raise ValueError( + '`exports_to_keep`, if provided, must be a positive number. Got %s' % + exports_to_keep) + + @property + def name(self): + return self._saved_model_exporter.name + + def export(self, estimator, export_path, checkpoint_path, eval_result, + is_the_final_export): + export_result = None + + if self._model_dir != estimator.model_dir and self._event_file_pattern: + # Loads best metric from event files. + tf.compat.v1.logging.info('Loading best metric from event files.') + + self._model_dir = estimator.model_dir + full_event_file_pattern = os.path.join(self._model_dir, + self._event_file_pattern) + self._best_eval_result = self._get_best_eval_result( + full_event_file_pattern) + + if (self._best_eval_result is None or + # check if this is the first export. + not self._has_exported or self._compare_fn( + best_eval_result=self._best_eval_result, + current_eval_result=eval_result)): + tf.compat.v1.logging.info('Performing best model export.') + self._best_eval_result = eval_result + export_result = self._saved_model_exporter.export(estimator, export_path, + checkpoint_path, + eval_result, + is_the_final_export) + self._garbage_collect_exports(export_path) + self._has_exported = True + + return export_result + + def _garbage_collect_exports(self, export_dir_base): + """Deletes older exports, retaining only a given number of the most recent. + + Export subdirectories are assumed to be named with monotonically increasing + integers; the most recent are taken to be those with the largest values. + + Args: + export_dir_base: the base directory under which each export is in a + versioned subdirectory. + """ + if self._exports_to_keep is None: + return + + def _export_version_parser(path): + # create a simple parser that pulls the export_version from the directory. + filename = os.path.basename(path.path) + if not (len(filename) == 10 and filename.isdigit()): + return None + return path._replace(export_version=int(filename)) + + # pylint: disable=protected-access + keep_filter = gc._largest_export_versions(self._exports_to_keep) + delete_filter = gc._negation(keep_filter) + for p in delete_filter( + gc._get_paths(export_dir_base, parser=_export_version_parser)): + try: + tf.compat.v1.gfile.DeleteRecursively(p.path) + except tf.errors.NotFoundError as e: + tf.compat.v1.logging.warn('Can not delete %s recursively: %s', p.path, + e) + # pylint: enable=protected-access + + def _get_best_eval_result(self, event_files): + """Get the best eval result from event files. + + Args: + event_files: Absolute pattern of event files. + + Returns: + The best eval result. + """ + if not event_files: + return None + + best_eval_result = None + for event_file in tf.compat.v1.gfile.Glob(os.path.join(event_files)): + for event in tf.compat.v1.train.summary_iterator(event_file): + if event.HasField('summary'): + event_eval_result = {} + for value in event.summary.value: + if value.HasField('simple_value'): + event_eval_result[value.tag] = value.simple_value + if event_eval_result: + if best_eval_result is None or self._compare_fn( + best_eval_result, event_eval_result): + best_eval_result = event_eval_result + return best_eval_result + + +@estimator_export('estimator.FinalExporter') +class FinalExporter(Exporter): + """This class exports the serving graph and checkpoints at the end. + + This class performs a single export at the end of training. + """ + + def __init__(self, + name, + serving_input_receiver_fn, + assets_extra=None, + as_text=False): + """Create an `Exporter` to use with `tf.estimator.EvalSpec`. + + Args: + name: unique name of this `Exporter` that is going to be used in the + export path. + serving_input_receiver_fn: a function that takes no arguments and returns + a `ServingInputReceiver`. + assets_extra: An optional dict specifying how to populate the assets.extra + directory within the exported SavedModel. Each key should give the + destination path (including the filename) relative to the assets.extra + directory. The corresponding value gives the full path of the source + file to be copied. For example, the simple case of copying a single + file without renaming it is specified as + `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`. + as_text: whether to write the SavedModel proto in text format. Defaults to + `False`. + + Raises: + ValueError: if any arguments is invalid. + """ + self._saved_model_exporter = _SavedModelExporter(name, + serving_input_receiver_fn, + assets_extra, as_text) + + @property + def name(self): + return self._saved_model_exporter.name + + def export(self, estimator, export_path, checkpoint_path, eval_result, + is_the_final_export): + if not is_the_final_export: + return None + + tf.compat.v1.logging.info( + 'Performing the final export in the end of training.') + + return self._saved_model_exporter.export(estimator, export_path, + checkpoint_path, eval_result, + is_the_final_export) + + +@estimator_export('estimator.LatestExporter') +class LatestExporter(Exporter): + """This class regularly exports the serving graph and checkpoints. + + In addition to exporting, this class also garbage collects stale exports. + """ + + def __init__(self, + name, + serving_input_receiver_fn, + assets_extra=None, + as_text=False, + exports_to_keep=5): + """Create an `Exporter` to use with `tf.estimator.EvalSpec`. + + Args: + name: unique name of this `Exporter` that is going to be used in the + export path. + serving_input_receiver_fn: a function that takes no arguments and returns + a `ServingInputReceiver`. + assets_extra: An optional dict specifying how to populate the assets.extra + directory within the exported SavedModel. Each key should give the + destination path (including the filename) relative to the assets.extra + directory. The corresponding value gives the full path of the source + file to be copied. For example, the simple case of copying a single + file without renaming it is specified as + `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`. + as_text: whether to write the SavedModel proto in text format. Defaults to + `False`. + exports_to_keep: Number of exports to keep. Older exports will be + garbage-collected. Defaults to 5. Set to `None` to disable garbage + collection. + + Raises: + ValueError: if any arguments is invalid. + """ + self._saved_model_exporter = _SavedModelExporter(name, + serving_input_receiver_fn, + assets_extra, as_text) + self._exports_to_keep = exports_to_keep + if exports_to_keep is not None and exports_to_keep <= 0: + raise ValueError( + '`exports_to_keep`, if provided, must be positive number') + + @property + def name(self): + return self._saved_model_exporter.name + + def export(self, estimator, export_path, checkpoint_path, eval_result, + is_the_final_export): + export_result = self._saved_model_exporter.export(estimator, export_path, + checkpoint_path, + eval_result, + is_the_final_export) + + self._garbage_collect_exports(export_path) + return export_result + + def _garbage_collect_exports(self, export_dir_base): + """Deletes older exports, retaining only a given number of the most recent. + + Export subdirectories are assumed to be named with monotonically increasing + integers; the most recent are taken to be those with the largest values. + + Args: + export_dir_base: the base directory under which each export is in a + versioned subdirectory. + """ + if self._exports_to_keep is None: + return + + def _export_version_parser(path): + # create a simple parser that pulls the export_version from the directory. + filename = os.path.basename(path.path) + if not (len(filename) == 10 and filename.isdigit()): + return None + return path._replace(export_version=int(filename)) + + # pylint: disable=protected-access + keep_filter = gc._largest_export_versions(self._exports_to_keep) + delete_filter = gc._negation(keep_filter) + for p in delete_filter( + gc._get_paths(export_dir_base, parser=_export_version_parser)): + try: + tf.compat.v1.gfile.DeleteRecursively(p.path) + except tf.errors.NotFoundError as e: + tf.compat.v1.logging.warn('Can not delete %s recursively: %s', p.path, + e) + # pylint: enable=protected-access diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/extenders.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/extenders.py new file mode 100644 index 0000000000000000000000000000000000000000..618130154cd38657879e2289aedf337415ada8be --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/extenders.py @@ -0,0 +1,123 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Extenders of tf.estimator.Estimator.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +from tensorflow.python.util import function_utils +from tensorflow_estimator.python.estimator import estimator as estimator_lib +from tensorflow_estimator.python.estimator.estimator_export import estimator_export +from tensorflow_estimator.python.estimator.mode_keys import ModeKeys + +_VALID_METRIC_FN_ARGS = set(['features', 'labels', 'predictions', 'config']) + + +@estimator_export('estimator.add_metrics') +def add_metrics(estimator, metric_fn): + """Creates a new `tf.estimator.Estimator` which has given metrics. + + Example: + + ```python + def my_auc(labels, predictions): + auc_metric = tf.keras.metrics.AUC(name="my_auc") + auc_metric.update_state(y_true=labels, y_pred=predictions['logistic']) + return {'auc': auc_metric} + + estimator = tf.estimator.DNNClassifier(...) + estimator = tf.estimator.add_metrics(estimator, my_auc) + estimator.train(...) + estimator.evaluate(...) + ``` + Example usage of custom metric which uses features: + + ```python + def my_auc(labels, predictions, features): + auc_metric = tf.keras.metrics.AUC(name="my_auc") + auc_metric.update_state(y_true=labels, y_pred=predictions['logistic'], + sample_weight=features['weight']) + return {'auc': auc_metric} + + estimator = tf.estimator.DNNClassifier(...) + estimator = tf.estimator.add_metrics(estimator, my_auc) + estimator.train(...) + estimator.evaluate(...) + ``` + + Args: + estimator: A `tf.estimator.Estimator` object. + metric_fn: A function which should obey the following signature: + - Args: can only have following four arguments in any order: + * predictions: Predictions `Tensor` or dict of `Tensor` created by given + `estimator`. + * features: Input `dict` of `Tensor` objects created by `input_fn` which + is given to `estimator.evaluate` as an argument. + * labels: Labels `Tensor` or dict of `Tensor` created by `input_fn` + which is given to `estimator.evaluate` as an argument. + * config: config attribute of the `estimator`. + - Returns: Dict of metric results keyed by name. Final metrics are a + union of this and `estimator's` existing metrics. If there is a name + conflict between this and `estimator`s existing metrics, this will + override the existing one. The values of the dict are the results of + calling a metric function, namely a `(metric_tensor, update_op)` tuple. + + Returns: + A new `tf.estimator.Estimator` which has a union of original metrics with + given ones. + """ + _verify_metric_fn_args(metric_fn) + + def new_model_fn(features, labels, mode, config): + spec = estimator.model_fn(features, labels, mode, config) + if mode != ModeKeys.EVAL: + return spec + new_metrics = _call_metric_fn(metric_fn, features, labels, spec.predictions, + config) + all_metrics = spec.eval_metric_ops or {} + all_metrics.update(new_metrics) + return spec._replace(eval_metric_ops=all_metrics) + + return estimator_lib.Estimator( + model_fn=new_model_fn, + model_dir=estimator.model_dir, + config=estimator.config, + # pylint: disable=protected-access + warm_start_from=estimator._warm_start_settings) + # pylint: enable=protected-access + + +def _verify_metric_fn_args(metric_fn): + args = set(function_utils.fn_args(metric_fn)) + invalid_args = list(args - _VALID_METRIC_FN_ARGS) + if invalid_args: + raise ValueError('metric_fn (%s) has following not expected args: %s' % + (metric_fn, invalid_args)) + + +def _call_metric_fn(metric_fn, features, labels, predictions, config): + """Calls metric fn with proper arguments.""" + metric_fn_args = function_utils.fn_args(metric_fn) + kwargs = {} + if 'features' in metric_fn_args: + kwargs['features'] = features + if 'labels' in metric_fn_args: + kwargs['labels'] = labels + if 'predictions' in metric_fn_args: + kwargs['predictions'] = predictions + if 'config' in metric_fn_args: + kwargs['config'] = config + return metric_fn(**kwargs) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/gc.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/gc.py new file mode 100644 index 0000000000000000000000000000000000000000..891d9df774511e231b152e8fd0a7cfd6cf7a5630 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/gc.py @@ -0,0 +1,217 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +r"""System for specifying garbage collection (GC) of path based data. + +This framework allows for GC of data specified by path names, for example files +on disk. gc.Path objects each represent a single item stored at a path and may +be a base directory, + /tmp/exports/0/... + /tmp/exports/1/... + ... +or a fully qualified file, + /tmp/train-1.ckpt + /tmp/train-2.ckpt + ... + +A gc filter function takes and returns a list of gc.Path items. Filter +functions are responsible for selecting Path items for preservation or deletion. +Note that functions should always return a sorted list. + +For example, + base_dir = "/tmp" + # Create the directories. + for e in xrange(10): + os.mkdir("%s/%d" % (base_dir, e), 0o755) + + # Create a simple parser that pulls the export_version from the directory. + path_regex = "^" + re.escape(base_dir) + "/(\\d+)$" + def parser(path): + match = re.match(path_regex, path.path) + if not match: + return None + return path._replace(export_version=int(match.group(1))) + + path_list = gc._get_paths("/tmp", parser) # contains all ten Paths + + every_fifth = gc._mod_export_version(5) + print(every_fifth(path_list)) # shows ["/tmp/0", "/tmp/5"] + + largest_three = gc.largest_export_versions(3) + print(largest_three(all_paths)) # shows ["/tmp/7", "/tmp/8", "/tmp/9"] + + both = gc._union(every_fifth, largest_three) + print(both(all_paths)) # shows ["/tmp/0", "/tmp/5", + # "/tmp/7", "/tmp/8", "/tmp/9"] + # Delete everything not in 'both'. + to_delete = gc._negation(both) + for p in to_delete(all_paths): + gfile.DeleteRecursively(p.path) # deletes: "/tmp/1", "/tmp/2", + # "/tmp/3", "/tmp/4", "/tmp/6", +""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function +import collections +import heapq +import math +import os +import tensorflow as tf +from tensorflow.python.platform import gfile + +Path = collections.namedtuple('Path', 'path export_version') + + +def _largest_export_versions(n): + """Creates a filter that keeps the largest n export versions. + + Args: + n: number of versions to keep. + + Returns: + A filter function that keeps the n largest paths. + """ + + def keep(paths): + heap = [] + for idx, path in enumerate(paths): + if path.export_version is not None: + heapq.heappush(heap, (path.export_version, idx)) + keepers = [paths[i] for _, i in heapq.nlargest(n, heap)] + return sorted(keepers) + + return keep + + +def _one_of_every_n_export_versions(n): + """Creates a filter that keeps one of every n export versions. + + Args: + n: interval size. + + Returns: + A filter function that keeps exactly one path from each interval + [0, n], (n, 2n], (2n, 3n], etc... If more than one path exists in an + interval the largest is kept. + """ + + def keep(paths): + """A filter function that keeps exactly one out of every n paths.""" + + keeper_map = {} # map from interval to largest path seen in that interval + for p in paths: + if p.export_version is None: + # Skip missing export_versions. + continue + # Find the interval (with a special case to map export_version = 0 to + # interval 0. + interval = math.floor( + (p.export_version - 1) / n) if p.export_version else 0 + existing = keeper_map.get(interval, None) + if (not existing) or (existing.export_version < p.export_version): + keeper_map[interval] = p + return sorted(keeper_map.values()) + + return keep + + +def _mod_export_version(n): + """Creates a filter that keeps every export that is a multiple of n. + + Args: + n: step size. + + Returns: + A filter function that keeps paths where export_version % n == 0. + """ + + def keep(paths): + keepers = [] + for p in paths: + if p.export_version % n == 0: + keepers.append(p) + return sorted(keepers) + + return keep + + +def _union(lf, rf): + """Creates a filter that keeps the union of two filters. + + Args: + lf: first filter + rf: second filter + + Returns: + A filter function that keeps the n largest paths. + """ + + def keep(paths): + l = set(lf(paths)) + r = set(rf(paths)) + return sorted(list(l | r)) + + return keep + + +def _negation(f): + """Negate a filter. + + Args: + f: filter function to invert + + Returns: + A filter function that returns the negation of f. + """ + + def keep(paths): + l = set(paths) + r = set(f(paths)) + return sorted(list(l - r)) + + return keep + + +def _get_paths(base_dir, parser): + """Gets a list of Paths in a given directory. + + Args: + base_dir: directory. + parser: a function which gets the raw Path and can augment it with + information such as the export_version, or ignore the path by returning + None. An example parser may extract the export version from a path such + as "/tmp/exports/100" an another may extract from a full file name such as + "/tmp/checkpoint-99.out". + + Returns: + A list of Paths contained in the base directory with the parsing function + applied. + By default the following fields are populated, + - Path.path + The parsing function is responsible for populating, + - Path.export_version + """ + # We are mocking this in the test, hence we should not use public API + raw_paths = gfile.ListDirectory(base_dir) + paths = [] + for r in raw_paths: + # ListDirectory() return paths with "/" at the last if base_dir was GCS URL + r = tf.compat.as_str_any(r) + if r[-1] == '/': + r = r[0:len(r) - 1] + p = parser(Path(os.path.join(tf.compat.as_str_any(base_dir), r), None)) + if p: + paths.append(p) + return sorted(paths) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/head/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/head/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/head/base_head.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/head/base_head.py new file mode 100644 index 0000000000000000000000000000000000000000..c15b143c635a36b77e44907b22269ef69a02cd60 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/head/base_head.py @@ -0,0 +1,931 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Abstractions for the base head class.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import abc + +import six +import tensorflow as tf +from tensorflow.python.feature_column import feature_column_lib +from tensorflow.python.feature_column.feature_column import _LazyBuilder +from tensorflow.python.feature_column.feature_column import _NumericColumn +from tensorflow.python.framework import ops +from tensorflow.python.util import function_utils +from tensorflow_estimator.python.estimator.canned import metric_keys +from tensorflow_estimator.python.estimator.estimator_export import estimator_export +from tensorflow_estimator.python.estimator.export import export_output + +DEFAULT_SERVING_KEY = tf.saved_model.DEFAULT_SERVING_SIGNATURE_DEF_KEY + +# The above default is defined by TF Serving, but these next three are just +# a local convention without any special meaning. +CLASSIFY_SERVING_KEY = 'classification' +REGRESS_SERVING_KEY = 'regression' +PREDICT_SERVING_KEY = 'predict' + + +@estimator_export('estimator.Head') +@six.add_metaclass(abc.ABCMeta) +class Head(object): + """Interface for the head/top of a model. + + Head sits on top of the model network and handles computing the outputs of + the network. Given logits (or output of a hidden layer), a Head knows how to + compute predictions, loss, train_op, metrics and export outputs. It is meant + to: + + 1. Simplify writing model_fn and to make model_fn more configurable for + Estimator. + 2. Simpilfy creating loss and metrics for the train and test loop in Eager + execution. + 3. Support wide range of machine learning models. Since most heads can work + with logits, they can support DNN, RNN, Wide, Wide&Deep, + Global objectives, Gradient boosted trees and many other types + of machine learning models. + + Common usage: + Here is simplified model_fn to build a DNN regression model. + ```python + def _my_dnn_model_fn(features, labels, mode, params, config=None): + # Optionally your callers can pass head to model_fn as a param. + head = tf.estimator.RegressionHead(...) + + feature_columns = tf.feature_column.numeric_column(...) + feature_layer = tf.keras.layers.DenseFeatures(feature_columns) + inputs = feature_layer(features) + + # Compute logits with tf.keras.layers API + hidden_layer0 = tf.keras.layers.Dense( + units=1000, activation="relu")(inputs) + hidden_layer1 = tf.keras.layers.Dense( + units=500, activation="relu")(hidden_layer0) + logits = tf.keras.layers.Dense( + units=head.logits_dimension, activation=None)(hidden_layer1) + + # Or use Keras model for logits computation + model = tf.keras.Sequential() + model.add(tf.keras.layers.Dense(units=1000, activation="relu")) + model.add(tf.keras.layers.Dense(units=500, activation="relu")) + model.add(tf.keras.layers.Dense( + units=head.logits_dimension, activation=None)) + logits = model(inputs) + + return head.create_estimator_spec( + features=features, + labels=labels, + mode=mode, + logits=logits, + optimizer=optimizer) + ``` + """ + + @abc.abstractproperty + def name(self): + """The name of this head. + + Returns: + A string. + """ + raise NotImplementedError('Calling an abstract method.') + + @abc.abstractproperty + def logits_dimension(self): + """Size of the last dimension of the logits `Tensor`. + + Often is the number of classes, labels, or real values to be predicted. + Typically, logits is of shape `[batch_size, logits_dimension]`. + + Returns: + The expected size of the `logits` tensor. + """ + raise NotImplementedError('Calling an abstract method.') + + @abc.abstractproperty + def loss_reduction(self): + """One of `tf.losses.Reduction`. + + Describes how to reduce training loss over batch, such as mean or sum. + + Returns: + The type of loss reduction used in the head. + """ + raise NotImplementedError('Calling an abstract method.') + + @abc.abstractmethod + def loss(self, + labels, + logits, + features=None, + mode=None, + regularization_losses=None): + """Returns a loss `Tensor` from provided arguments. + + Note that, the args of `features` and `mode` are most likely not used, but + some Head implementations may require them. + + Args: + labels: Labels `Tensor`, or `dict` mapping string label names to `Tensor` + objects of the label values. + logits: Logits `Tensor` to be used for loss construction. + features: Input `dict` mapping string feature names to `Tensor` or + `SparseTensor` objects containing the values for that feature in a + minibatch. Often to be used to fetch example-weight tensor. + mode: Estimator's `ModeKeys`. To be used in case loss calculation is + different in Train and Eval mode. + regularization_losses: A list of additional scalar losses to be added to + the training loss, such as regularization losses. + + Returns: + A scalar `Tensor` representing regularized training loss used in train and + eval. + """ + raise NotImplementedError('Calling an abstract method.') + + @abc.abstractmethod + def predictions(self, logits, keys=None): + """Returns a `dict` of predictions from provided logits. + + Args: + logits: Logits `Tensor` to be used for prediction construction. + keys: A list of `string` for prediction keys. Defaults to `None`, meaning + if not specified, predictions will be created for all the pre-defined + valid keys in the head. + + Returns: + A `dict` of predicted `Tensor` keyed by prediction name. + """ + raise NotImplementedError('Calling an abstract method.') + + @abc.abstractmethod + def metrics(self, regularization_losses=None): + """Returns a `dict` of metric objects. + + Args: + regularization_losses: A list of additional scalar losses to be added to + the training loss, such as regularization losses. + + Returns: + A `dict` of metrics keyed by string name. The value is an instance of + `Metric` class. + """ + raise NotImplementedError('Calling an abstract method.') + + @abc.abstractmethod + def update_metrics(self, + eval_metrics, + features, + logits, + labels, + mode=None, + regularization_losses=None): + """Updates metric objects and returns a `dict` of the updated metrics. + + Args: + eval_metrics: A `dict` of metrics to be updated. + features: Input `dict` mapping string feature names to `Tensor` or + `SparseTensor` objects containing the values for that feature in a + minibatch. Often to be used to fetch example-weight tensor. + logits: logits `Tensor` to be used for metrics update. + labels: Labels `Tensor`, or `dict` mapping string label names to `Tensor` + objects of the label values. + mode: Estimator's `ModeKeys`. In most cases, this arg is not used and can + be removed in the method implementation. + regularization_losses: A list of additional scalar losses to be added to + the training and evaluation loss, such as regularization losses. Note + that, the `mode` arg is not used in the `tf.estimator.*Head`. If the + update of the metrics doesn't rely on `mode`, it can be safely ignored + in the method signature. + + Returns: + A `dict` of updated metrics keyed by name. The value is an instance of + `Metric` class. + """ + raise NotImplementedError('Calling an abstract method.') + + def _summary_key(self, key): + return '{}/{}'.format(key, self.name) if self.name else key + + def create_estimator_spec(self, + features, + mode, + logits, + labels=None, + optimizer=None, + trainable_variables=None, + train_op_fn=None, + update_ops=None, + regularization_losses=None): + """Returns `EstimatorSpec` that a model_fn can return. + + It is recommended to pass all args via name. + + Args: + features: Input `dict` mapping string feature names to `Tensor` or + `SparseTensor` objects containing the values for that feature in a + minibatch. Often to be used to fetch example-weight tensor. + mode: Estimator's `ModeKeys`. + logits: Logits `Tensor` to be used by the head. + labels: Labels `Tensor`, or `dict` mapping string label names to `Tensor` + objects of the label values. + optimizer: An `tf.keras.optimizers.Optimizer` instance to optimize the + loss in TRAIN mode. Namely, sets `train_op = optimizer.get_updates(loss, + trainable_variables)`, which updates variables to minimize `loss`. + trainable_variables: A list or tuple of `Variable` objects to update to + minimize `loss`. In Tensorflow 1.x, by default these are the list of + variables collected in the graph under the key + `GraphKeys.TRAINABLE_VARIABLES`. As Tensorflow 2.x doesn't have + collections and GraphKeys, trainable_variables need to be passed + explicitly here. + train_op_fn: Function that takes a scalar loss `Tensor` and returns an op + to optimize the model with the loss in TRAIN mode. Used if `optimizer` + is `None`. Exactly one of `train_op_fn` and `optimizer` must be set in + TRAIN mode. By default, it is `None` in other modes. If you want to + optimize loss yourself, you can pass `lambda _: tf.no_op()` and then use + `EstimatorSpec.loss` to compute and apply gradients. + update_ops: A list or tuple of update ops to be run at training time. For + example, layers such as BatchNormalization create mean and variance + update ops that need to be run at training time. In Tensorflow 1.x, + these are thrown into an UPDATE_OPS collection. As Tensorflow 2.x + doesn't have collections, update_ops need to be passed explicitly here. + regularization_losses: A list of additional scalar losses to be added to + the training loss, such as regularization losses. + + Returns: + `EstimatorSpec`. + """ + # Not all subclasses of Head will have implemented + # _create_tpu_estimator_spec. If it is implemented, we can convert it to + # the normal `EstimatorSpec` by calling the method of + # `_TPUEstimatorSpec.as_estimator_spec()`. + try: + tpu_estimator_spec = ( + self._create_tpu_estimator_spec( + features=features, + mode=mode, + logits=logits, + labels=labels, + optimizer=optimizer, + trainable_variables=trainable_variables, + train_op_fn=train_op_fn, + update_ops=update_ops, + regularization_losses=regularization_losses)) + return tpu_estimator_spec.as_estimator_spec() + except NotImplementedError: + raise NotImplementedError( + 'Subclasses of Head must implement `create_estimator_spec()` or ' + '_create_tpu_estimator_spec().') + + def _create_tpu_estimator_spec( + self, + features, + mode, + logits, + labels=None, + optimizer=None, + trainable_variables=None, + train_op_fn=None, + update_ops=None, + regularization_losses=None, + ): + """Returns `model_fn._TPUEstimatorSpec` that a model_fn can return. + + Args: + features: Input `dict` mapping string feature names to `Tensor` or + `SparseTensor` objects containing the values for that feature in a + minibatch. Often to be used to fetch example-weight tensor. + mode: Estimator's `ModeKeys`. + logits: Logits `Tensor` to be used by the head. + labels: Labels `Tensor`, or `dict` mapping string label names to `Tensor` + objects of the label values. + optimizer: An `tf.keras.optimizers.Optimizer` instance to optimize the + loss in TRAIN mode. Namely, sets `train_op = optimizer.get_updates(loss, + trainable_variables)`, which updates variables to minimize `loss`. + trainable_variables: A list or tuple of `Variable` objects to update to + minimize `loss`. In Tensorflow 1.x, by default these are the list of + variables collected in the graph under the key + `GraphKeys.TRAINABLE_VARIABLES`. As Tensorflow 2.x doesn't have + collections and GraphKeys, trainable_variables need to be passed + explicitly here. + train_op_fn: Function that takes a scalar loss `Tensor` and returns an op + to optimize the model with the loss in TRAIN mode. Used if `optimizer` + is `None`. Exactly one of `train_op_fn` and `optimizer` must be set in + TRAIN mode. By default, it is `None` in other modes. If you want to + optimize loss yourself, you can pass `lambda _: tf.no_op()` and then use + `EstimatorSpec.loss` to compute and apply gradients. + update_ops: A list or tuple of update ops to be run at training time. For + example, layers such as BatchNormalization create mean and variance + update ops that need to be run at training time. In Tensorflow 1.x, + these are thrown into an UPDATE_OPS collection. As Tensorflow 2.x + doesn't have collections, update_ops need to be passed explicitly here. + regularization_losses: A list of additional scalar losses to be added to + the training loss, such as regularization losses. + + Returns: + A `model_fn._TPUEstimatorSpec' instance. + """ + raise NotImplementedError( + 'TPUEstimatorSpec not available for this model head.') + + +# TODO(b/119617064): unify eager and graph implementations +# Note that, tensor shape checking is slow in Eager mode. To amend it, the +# tensor static shape is used for checking. The duplication of shape checking +# for eager mode in the following helper functions can be safely removed +# if there's some way to get around it in the future. + +# Label shape error messages. +_LABEL_NONE_ERR_MSG = ( + 'You must provide a labels Tensor. Given: None. ' + 'Suggested troubleshooting steps: Check that your data contains your label ' + 'feature. Check that your input_fn properly parses and returns labels.') + +_SPARSE_LABEL_ERR_MSG = ( + 'SparseTensor labels are not supported. Labels must be a Tensor of shape ' + '[D0, D1, ..., DN, {}], e.g. [batch_size, {}].Suggested Fix (1): Check the' + ' label feature in your data. Each example must contain {} value(s). If ' + 'not, your choice of label was probably incorrect. Suggested Fix (2): In ' + 'your input_fn, use tf.sparse_tensor_to_dense() to turn labels into a ' + 'Tensor.') + +_MISMATCHED_LABEL_DIM_ERR_MSG = ( + 'Mismatched label shape. Expected labels dimension={}. Received {}. ' + 'Suggested Fix: If your classifier expects one-hot encoding label, check ' + 'your n_classes argument to the estimator and/or the shape of your label. ' + 'Otherwise, check the shape of your label.') + +_LABEL_SHAPE_ERR_MSG = ( + 'labels shape must be [D0, D1, ... DN, {}]. Suggested Fix: check your ' + 'n_classes argument to the head and/or the shape of your label.') + +_VALIDATION_ERROR_MSG = '{} should be a list or a tuple. Given type: {}.' + + +def check_dense_labels_match_logits_and_reshape(labels, logits, + expected_labels_dimension): + """Checks labels shape matches logits, and reshapes if needed. + + Consider logits of shape [D0, D1, ... DN, logits_dimension]. Then labels + shape must be [D0, D1, ... DN, expected_labels_dimension]. + If expected_labels_dimension=1, labels could be [D0, D1, ... DN] and this + method reshapes them to [D0, D1, ... DN, 1]. + + Args: + labels: labels Tensor. + logits: logits Tensor. + expected_labels_dimension: Integer. + + Returns: + Validated and reshaped labels Tensor. + + Raises: + ValueError: If labels is a SparseTensor. + ValueError: If labels shape is statically defined and fails validation. + OpError: If labels shape is not statically defined and fails validation. + """ + if labels is None: + raise ValueError(_LABEL_NONE_ERR_MSG) + with ops.name_scope('labels', values=(labels, logits)) as scope: + labels = tf.compat.v1.convert_to_tensor_or_sparse_tensor(labels) + if isinstance(labels, tf.sparse.SparseTensor): + raise ValueError( + _SPARSE_LABEL_ERR_MSG.format(expected_labels_dimension, + expected_labels_dimension, + expected_labels_dimension)) + # Eager mode. + if tf.executing_eagerly(): + labels_rank = labels._rank() # pylint: disable=protected-access + logits_rank = logits._rank() # pylint: disable=protected-access + if (labels_rank is not None and logits_rank is not None and + labels_rank == logits_rank - 1): + labels = tf.compat.v1.expand_dims(labels, -1) + labels_rank += 1 + labels_shape = labels._shape_tuple() # pylint: disable=protected-access + if labels_rank < 2: + raise ValueError('labels must have rank at least 2. Received rank {}, ' + 'shape {}'.format(labels_rank, labels_shape)) + if labels_shape[-1] != expected_labels_dimension: + raise ValueError( + _MISMATCHED_LABEL_DIM_ERR_MSG.format(expected_labels_dimension, + labels_shape[-1])) + logits_shape = logits._shape_tuple() # pylint: disable=protected-access + expected_labels_shape = logits_shape[:-1] + (expected_labels_dimension,) + if expected_labels_shape != labels_shape: + raise ValueError( + '{}, expected_labels_shape: {}. labels_shape: {}.'.format( + _LABEL_SHAPE_ERR_MSG.format(expected_labels_dimension), + expected_labels_shape, labels_shape)) + return labels + + # Graph mode. + if (labels.shape.ndims is not None and logits.shape.ndims is not None and + labels.shape.ndims == logits.shape.ndims - 1): + labels = tf.compat.v1.expand_dims(labels, -1) + assert_rank = tf.compat.v1.debugging.assert_rank_at_least( + labels, + 2, + message=_LABEL_SHAPE_ERR_MSG.format(expected_labels_dimension)) + with tf.control_dependencies([assert_rank]): + static_shape = labels.shape + if static_shape.ndims is not None: + final_dim = static_shape[-1] + if (final_dim is not None) and (final_dim != expected_labels_dimension): + raise ValueError( + _MISMATCHED_LABEL_DIM_ERR_MSG.format(expected_labels_dimension, + final_dim)) + logits_shape = tf.compat.v1.shape(logits) + expected_labels_shape = tf.concat( + [logits_shape[:-1], [expected_labels_dimension]], axis=0) + labels_shape = tf.compat.v1.shape(labels) + assert_dimension = tf.compat.v1.debugging.assert_equal( + expected_labels_shape, + labels_shape, + message=_LABEL_SHAPE_ERR_MSG.format(expected_labels_dimension), + data=[ + 'expected_labels_shape: ', expected_labels_shape, + 'labels_shape: ', labels_shape + ]) + with tf.control_dependencies([assert_dimension]): + return tf.identity(labels, name=scope) + + +def get_weights_and_check_match_logits(features, + weight_column, + logits, + allow_per_logit_weights=False): + """Fetches weights from features and checks that the shape matches logits. + + Consider logits of shape [D0, D1, ... DN, logits_dimension]. Weights shape + can be either: + * [D0, D1, ... DN, logits_dimension] if `allow_per_logit_weights=True`. + * [D0, D1, ... DN, 1] + * [D0, D1, ... DN]: In this case, weights is reshaped into + [D0, D1, ... DN, 1] to work with weight broadcasting rules. + + Args: + features: The features dict that contains weights. + weight_column: The weight column. If not given, this method returns 1. + logits: logits Tensor. + allow_per_logit_weights: Boolean. Whether we allow weights along the logits + dimension, namely shape `[D0, D1, ... DN, logits_dimension]`. + + Returns: + Validated and reshaped weights Tensor. + + Raises: + ValueError: If the weights `Tensor` cannot be cast into float. + """ + if allow_per_logit_weights: + err_msg = ('weights shape must be [D0, D1, ... DN], [D0, D1, ... DN, 1] or ' + '[D0, D1, ... DN, logits_dimension]') + else: + err_msg = ('weights shape must be [D0, D1, ... DN] or [D0, D1, ... DN, 1]') + with ops.name_scope( + 'weights', values=tuple(six.itervalues(features)) + (logits,)) as scope: + # Fetch the weights. + if weight_column is None: + return 1. + # TODO(b/117839674): update feature_column + if isinstance(weight_column, six.string_types): + weight_column = tf.feature_column.numeric_column( + key=weight_column, shape=(1,)) + if not isinstance(weight_column, + (feature_column_lib.NumericColumn, _NumericColumn)): + raise TypeError('Weight column must be either a string or NumericColumn.' + ' Given type: {}.'.format(type(weight_column))) + weights = weight_column._get_dense_tensor( # pylint: disable=protected-access + _LazyBuilder(features)) + if not (weights.dtype.is_floating or weights.dtype.is_integer): + raise ValueError('Weight column should be castable to float. ' + 'Given dtype: {}'.format(weights.dtype)) + weights = tf.cast(weights, name='weights', dtype=tf.dtypes.float32) + # Validate the weights shape. + # Eager mode. + if tf.executing_eagerly(): + weights_shape = weights._shape_tuple() # pylint: disable=protected-access + logits_shape = logits._shape_tuple() # pylint: disable=protected-access + weights_rank = weights._rank() # pylint: disable=protected-access + logits_rank = logits._rank() # pylint: disable=protected-access + if (weights_rank is not None and logits_rank is not None and + weights_rank == logits_rank - 1): + if logits_shape[:-1] != weights_shape: + raise ValueError('{}, logits_shape: {}. weights_shape: {}.'.format( + err_msg, logits_shape, weights_shape)) + return tf.compat.v1.expand_dims(weights, -1, name=scope) + supported_weights_shape = logits_shape[:-1] + (1,) + if allow_per_logit_weights: + if (logits_shape != weights_shape and + supported_weights_shape != weights_shape): + raise ValueError('{}, logits_shape: {}. weights_shape: {}.'.format( + err_msg, logits_shape, weights_shape)) + else: + if supported_weights_shape != weights_shape: + raise ValueError('{}, logits_shape: {}. weights_shape: {}.'.format( + err_msg, logits_shape, weights_shape)) + return weights + + # Graph mode. + weights_shape = tf.compat.v1.shape(weights, name='weights_shape') + logits_shape = tf.compat.v1.shape(logits, name='logits_shape') + if (weights.shape.ndims is not None and logits.shape.ndims is not None and + weights.shape.ndims == logits.shape.ndims - 1): + assert_dimension = tf.compat.v1.debugging.assert_equal( + logits_shape[:-1], + weights_shape, + message=err_msg, + data=[ + 'logits_shape: ', logits_shape, 'weights_shape: ', weights_shape + ]) + with tf.control_dependencies([assert_dimension]): + return tf.compat.v1.expand_dims(weights, -1, name=scope) + supported_weights_shape = tf.concat([logits_shape[:-1], [1]], axis=0) + if allow_per_logit_weights: + condition = tf.math.reduce_any([ + tf.reduce_all(tf.math.equal(logits_shape, weights_shape)), + tf.reduce_all(tf.math.equal(supported_weights_shape, weights_shape)) + ]) + assert_dimension = tf.debugging.Assert( + condition=condition, + data=[ + err_msg, 'logits_shape: ', logits_shape, 'weights_shape: ', + weights_shape + ]) + else: + assert_dimension = tf.compat.v1.debugging.assert_equal( + supported_weights_shape, + weights_shape, + message=err_msg, + data=[ + 'logits_shape: ', logits_shape, 'weights_shape: ', weights_shape + ]) + with tf.control_dependencies([assert_dimension]): + return tf.identity(weights, name=scope) + + +def check_logits_final_dim(logits, expected_logits_dimension): + """Checks that logits shape is [D0, D1, ... DN, logits_dimension].""" + with ops.name_scope('logits', values=(logits,)) as scope: + logits = tf.cast(logits, tf.dtypes.float32) + # Eager mode + if tf.executing_eagerly(): + logits_shape = logits._shape_tuple() # pylint: disable=protected-access + logits_rank = logits._rank() # pylint: disable=protected-access + if logits_rank < 2: + raise ValueError('logits must have rank at least 2. Received rank {}, ' + 'shape {}'.format(logits_rank, logits_shape)) + if (isinstance(expected_logits_dimension, int) and + logits_shape[-1] != expected_logits_dimension): + raise ValueError( + 'logits shape must be [D0, D1, ... DN, logits_dimension], ' + 'got {}.'.format(logits_shape)) + return logits + # Graph mode + logits_shape = tf.compat.v1.shape(logits) + assert_rank = tf.compat.v1.debugging.assert_rank_at_least( + logits, + 2, + data=[logits_shape], + message='logits shape must be [D0, D1, ... DN, logits_dimension]') + with tf.control_dependencies([assert_rank]): + static_shape = logits.shape + if static_shape.ndims is not None and static_shape[-1] is not None: + if (isinstance(expected_logits_dimension, int) and + static_shape[-1] != expected_logits_dimension): + raise ValueError( + 'logits shape must be [D0, D1, ... DN, logits_dimension], ' + 'got {}.'.format(static_shape)) + return logits + assert_dimension = tf.compat.v1.debugging.assert_equal( + expected_logits_dimension, + logits_shape[-1], + data=[logits_shape], + message='logits shape must be [D0, D1, ... DN, logits_dimension]') + with tf.control_dependencies([assert_dimension]): + return tf.identity(logits, name=scope) + + +def validate_loss_fn_args(loss_fn): + """Validates loss_fn arguments. + + Required arguments: labels, logits. + Optional arguments: features, loss_reduction. + + Args: + loss_fn: The loss function. + + Raises: + ValueError: If the signature is unexpected. + """ + loss_fn_args = function_utils.fn_args(loss_fn) + for required_arg in ['labels', 'logits']: + if required_arg not in loss_fn_args: + raise ValueError('loss_fn must contain argument: {}. ' + 'Given arguments: {}'.format(required_arg, loss_fn_args)) + invalid_args = list( + set(loss_fn_args) - + set(['labels', 'logits', 'features', 'loss_reduction'])) + if invalid_args: + raise ValueError('loss_fn has unexpected args: {}'.format(invalid_args)) + + +def validate_loss_reduction(loss_reduction): + if (loss_reduction not in tf.losses.Reduction.all() or + loss_reduction == tf.losses.Reduction.NONE): + raise ValueError( + 'Invalid loss_reduction: {}. See `tf.losses.Reduction` for valid ' + 'options.'.format(loss_reduction)) + + +def validate_update_ops(update_ops=None): + if update_ops is not None and not isinstance(update_ops, (list, tuple)): + raise ValueError( + _VALIDATION_ERROR_MSG.format('update_ops', type(update_ops))) + + +def validate_v2_optimizer(optimizer): + if not isinstance( + optimizer, + (tf.keras.optimizers.Optimizer, tf.keras.optimizers.legacy.Optimizer)): + raise ValueError( + 'The given optimizer is not a tf.keras.optimizers.Optimizer ' + f'instance. Received optimizer of type {type(optimizer)}') + + +def validate_trainable_variables(trainable_variables=None): + if trainable_variables is None: + raise ValueError('trainable_variables cannot be None. Given {}'.format( + trainable_variables)) + if not isinstance(trainable_variables, (list, tuple)): + raise ValueError( + _VALIDATION_ERROR_MSG.format('trainable_variables', + type(trainable_variables))) + + +def validate_n_classes(n_classes): + """Validates n_classes argument. + + Required arguments: n_classes. + + Args: + n_classes: The number of classes. + + Raises: + ValueError: If n_classes is <= 2 and n_classes is a Python integer. + Returns: + n_classes in its original type. + """ + if isinstance(n_classes, int) and (n_classes <= 2): + raise ValueError('n_classes must be > 2: %s.' % n_classes) + + n_classes_as_tensor = ops.convert_to_tensor(n_classes) + assert_n_classes = tf.compat.v1.debugging.assert_greater( + n_classes_as_tensor, 2, message='n_classes must be greater than 2') + with tf.control_dependencies([assert_n_classes]): + tf.no_op() + # Return n_classes in its original type, so that any code + # using the accessor logits_dimension() has the original type. + return n_classes + + +def call_loss_fn(loss_fn, labels, logits, features, expected_loss_dim=1): + """Calls loss_fn and checks the returned shape. + + For shape checking, eager uses the static dimension to improve performance. + + Args: + loss_fn: The loss function. + labels: Processed labels Tensor. + logits: Logits Tensor of shape [D0, D1, ... DN, logits_dimension]. + features: Features dict. + expected_loss_dim: The expected last dimension of loss Tensor. + + Returns: + Loss Tensor with shape [D0, D1, ... DN, expected_loss_dim]. + + Raises: + ValueError: If the loss tensor shape is unexpected. + """ + loss_fn_args = function_utils.fn_args(loss_fn) + kwargs = {} + if 'features' in loss_fn_args: + kwargs['features'] = features + with ops.name_scope( + 'call_loss_fn', values=[labels, logits] + list(six.itervalues(features))): + unweighted_loss = loss_fn(labels=labels, logits=logits, **kwargs) + # Eager mode. + if tf.executing_eagerly(): + loss_shape = unweighted_loss._shape_tuple() # pylint: disable=protected-access + logits_shape = logits._shape_tuple() # pylint: disable=protected-access + expected_loss_shape = logits_shape[:-1] + (expected_loss_dim,) + if loss_shape != expected_loss_shape: + raise ValueError( + 'loss_fn must return Tensor of shape ' + '[D0, D1, ... DN, {}]. '.format(expected_loss_dim), + 'logits_shape: ', logits_shape, 'loss_shape: ', loss_shape) + return unweighted_loss + # Graph mode. + logits_shape = tf.compat.v1.shape(logits, name='logits_shape') + expected_loss_shape = tf.concat([logits_shape[:-1], [expected_loss_dim]], + axis=0, + name='expected_loss_shape') + loss_shape = tf.compat.v1.shape(unweighted_loss, name='loss_shape') + check_loss_shape_op = tf.debugging.Assert( + tf.reduce_all(tf.math.equal(loss_shape, expected_loss_shape)), + data=[ + 'loss_fn must return Tensor of shape ' + '[D0, D1, ... DN, {}]. '.format(expected_loss_dim), + 'logits_shape: ', logits_shape, 'loss_shape: ', loss_shape + ], + name='check_loss_shape') + with tf.control_dependencies([check_loss_shape_op]): + return tf.identity(unweighted_loss) + + +def check_prediction_keys(pred_keys, valid_keys): + for key in pred_keys: + if key not in valid_keys: + raise ValueError('Prediction key must be in PredictionKeys, given: {}.' + 'Valid prediction keys include {}.'.format( + key, valid_keys)) + + +def all_class_ids(logits, n_classes): + batch_size = tf.compat.v1.shape(logits)[0] + class_id_list = tf.range(n_classes) + return tf.tile( + input=tf.compat.v1.expand_dims(input=class_id_list, axis=0), + multiples=[batch_size, 1]) + + +def all_classes(logits, n_classes, label_vocabulary=None): + batch_size = tf.compat.v1.shape(logits)[0] + if label_vocabulary: + classes_list = tf.convert_to_tensor([label_vocabulary]) + else: + classes_list = tf.expand_dims(tf.range(n_classes), axis=0) + classes_list = tf.strings.as_string(classes_list) + return tf.tile(input=classes_list, multiples=[batch_size, 1]) + + +def classification_output(scores, n_classes, label_vocabulary=None): + return export_output.ClassificationOutput( + scores=scores, + # `ClassificationOutput` requires string classes. + classes=all_classes(scores, n_classes, label_vocabulary)) + + +def check_label_range(labels, n_classes, message=None): + """Check if labels are in the range of [0, n_classes).""" + with ops.name_scope('check_label_range', values=(labels,)): + # Eager mode + if tf.executing_eagerly(): + assert_less = tf.reduce_all(tf.math.less_equal(labels, n_classes - 1)) + if not assert_less: + raise ValueError(message or + 'Labels must be <= {} - 1'.format(n_classes)) + assert_greater = tf.reduce_all(tf.math.greater_equal(labels, 0)) + if not assert_greater: + raise ValueError(message or 'Labels must be >= 0') + return labels + # Graph mode + assert_less = tf.compat.v1.debugging.assert_less_equal( + labels, + ops.convert_to_tensor(n_classes - 1, dtype=labels.dtype), + message=message or 'Labels must be <= n_classes - 1') + assert_greater = tf.compat.v1.debugging.assert_non_negative( + labels, message=message or 'Labels must be >= 0') + with tf.control_dependencies((assert_less, assert_greater)): + return tf.identity(labels) + + +def update_metric_with_broadcast_weights(eval_metric, values, weights): + values = tf.cast(values, dtype=tf.dtypes.float32) + if weights is not None: + weights = tf.compat.v2.__internal__.ops.broadcast_weights(weights, values) + eval_metric.update_state(values=values, sample_weight=weights) + + +def create_eval_metrics_tuple(fn, kwargs): + """Creates TPU eval metrics tuple. + + Helper function to make eval_metric tuple (eval_metric_fn, fn_kwargs) used + by `TPUEstimator`. TPUEstimator requires that `eval_metric_fn` take + exclusively Tensor arguments. This helper can help create such a function from + a more generic function that can take both Tensor and non-Tensor arguments. + + Args: + fn: A eval_metric_fn that takes both Tensor and non-Tensor arguments. This + function must return a dict of form + {'metric name': (metric_tensor, eval_op)} + kwargs: Dict of arguments for `fn`. + + Returns: + `eval_metric` tuple that can be passed to a `model_fn._TPUEstimatorSpec`. + """ + tensor_kwargs = {} + nontensor_kwargs = {} + for k, v in six.iteritems(kwargs): + if tf.is_tensor(v): + tensor_kwargs[k] = v + else: + nontensor_kwargs[k] = v + + def _fn(**tensors): + return fn(**dict(nontensor_kwargs, **tensors)) + + return (_fn, tensor_kwargs) + + +def create_estimator_spec_train_op( + head_name, + optimizer=None, + trainable_variables=None, + train_op_fn=None, + update_ops=None, + regularized_training_loss=None, + loss_reduction=tf.losses.Reduction.SUM_OVER_BATCH_SIZE): + """Create train_op for estimator_spec. + + Args: + head_name: The name of the head. + optimizer: An `tf.keras.optimizers.Optimizer` instance to optimize the loss + in TRAIN mode. Namely, sets `train_op = optimizer.get_updates(loss, + trainable_variables)`, which updates variables to minimize `loss`. + trainable_variables: A list or tuple of `Variable` objects to update to + minimize `loss`. In Tensorflow 1.x, by default these are the list of + variables collected in the graph under the key + `GraphKeys.TRAINABLE_VARIABLES`. As Tensorflow 2.x doesn't have + collections and GraphKeys, trainable_variables need to be passed + explicitly here. + train_op_fn: Function that takes a scalar loss `Tensor` and returns + `train_op`. Used if `optimizer` is `None`. + update_ops: A list or tuple of update ops to be run at training time. For + example, layers such as BatchNormalization create mean and variance update + ops that need to be run at training time. In Tensorflow 1.x, these are + thrown into an UPDATE_OPS collection. As Tensorflow 2.x doesn't have + collections, update_ops need to be passed explicitly here. + regularized_training_loss: A scalar for total training loss that includes + all regularization losses. If you're not using optimizer to generate train + op, make sure to scale the loss correctly before passing it in. The loss + typically needs to be scaled down by the number of workers. + loss_reduction: One of `tf.keras.losses.Reduction` except `NONE`. Describes + how to reduce training loss over batch. Defaults to `SUM_OVER_BATCH_SIZE`. + + Returns: + A train op for EstimatorSpec. + """ + del head_name + validate_update_ops(update_ops) + with ops.name_scope(''): # Reset all previous name_scope. + # Add training as the name_scope to be compatible with Keras. + with ops.name_scope('training'): + if optimizer is not None: + if train_op_fn is not None: + raise ValueError('train_op_fn and optimizer cannot both be set.') + validate_v2_optimizer(optimizer) + validate_trainable_variables(trainable_variables) + # Scale loss by number of replicas. + if loss_reduction == tf.losses.Reduction.SUM_OVER_BATCH_SIZE: + num_replicas = tf.distribute.get_strategy().num_replicas_in_sync + if num_replicas > 1: + regularized_training_loss *= (1. / num_replicas) + train_op = optimizer.get_updates(regularized_training_loss, + trainable_variables)[0] + elif train_op_fn is not None: + train_op = train_op_fn(regularized_training_loss) + else: + raise ValueError('train_op_fn and optimizer cannot both be None.') + if update_ops is not None: + train_op = tf.group(train_op, *update_ops) + return train_op + + +def create_estimator_spec_summary(regularized_training_loss, + regularization_losses=None, + summary_key_fn=None): + """Create summary for estimator_spec.""" + with ops.name_scope(''): + keys = metric_keys.MetricKeys + loss_key = summary_key_fn(keys.LOSS) if summary_key_fn else keys.LOSS + tf.compat.v1.summary.scalar(loss_key, regularized_training_loss) + if regularization_losses is not None: + regularization_loss = tf.math.add_n(regularization_losses) + regularization_loss_key = ( + summary_key_fn(keys.LOSS_REGULARIZATION) + if summary_key_fn else keys.LOSS_REGULARIZATION) + tf.compat.v1.summary.scalar(regularization_loss_key, regularization_loss) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/head/binary_class_head.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/head/binary_class_head.py new file mode 100644 index 0000000000000000000000000000000000000000..4dba08bdefd030bc0e272485a27628373fe53a0d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/head/binary_class_head.py @@ -0,0 +1,604 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Binary class head.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import tensorflow as tf +from tensorflow.python.framework import ops +from tensorflow.python.ops import lookup_ops +from tensorflow_estimator.python.estimator import model_fn +from tensorflow_estimator.python.estimator.canned import metric_keys +from tensorflow_estimator.python.estimator.canned import prediction_keys +from tensorflow_estimator.python.estimator.estimator_export import estimator_export +from tensorflow_estimator.python.estimator.export import export_output +from tensorflow_estimator.python.estimator.head import base_head +from tensorflow_estimator.python.estimator.mode_keys import ModeKeys + + +@estimator_export('estimator.BinaryClassHead') +class BinaryClassHead(base_head.Head): + """Creates a `Head` for single label binary classification. + + Uses `sigmoid_cross_entropy_with_logits` loss. + + The head expects `logits` with shape `[D0, D1, ... DN, 1]`. + In many applications, the shape is `[batch_size, 1]`. + + `labels` must be a dense `Tensor` with shape matching `logits`, namely + `[D0, D1, ... DN, 1]`. If `label_vocabulary` given, `labels` must be a string + `Tensor` with values from the vocabulary. If `label_vocabulary` is not given, + `labels` must be float `Tensor` with values in the interval `[0, 1]`. + + If `weight_column` is specified, weights must be of shape + `[D0, D1, ... DN]`, or `[D0, D1, ... DN, 1]`. + + The loss is the weighted sum over the input dimensions. Namely, if the input + labels have shape `[batch_size, 1]`, the loss is the weighted sum over + `batch_size`. + + Also supports custom `loss_fn`. `loss_fn` takes `(labels, logits)` or + `(labels, logits, features, loss_reduction)` as arguments and returns loss + with shape `[D0, D1, ... DN, 1]`. `loss_fn` must support float `labels` with + shape `[D0, D1, ... DN, 1]`. Namely, the head applies `label_vocabulary` to + the input labels before passing them to `loss_fn`. + + Usage: + + >>> head = tf.estimator.BinaryClassHead() + >>> logits = np.array(((45,), (-41,),), dtype=np.float32) + >>> labels = np.array(((1,), (1,),), dtype=np.int32) + >>> features = {'x': np.array(((42,),), dtype=np.float32)} + >>> # expected_loss = sum(cross_entropy(labels, logits)) / batch_size + >>> # = sum(0, 41) / 2 = 41 / 2 = 20.50 + >>> loss = head.loss(labels, logits, features=features) + >>> print('{:.2f}'.format(loss.numpy())) + 20.50 + >>> eval_metrics = head.metrics() + >>> updated_metrics = head.update_metrics( + ... eval_metrics, features, logits, labels) + >>> for k in sorted(updated_metrics): + ... print('{} : {:.2f}'.format(k, updated_metrics[k].result().numpy())) + accuracy : 0.50 + accuracy_baseline : 1.00 + auc : 0.00 + auc_precision_recall : 1.00 + average_loss : 20.50 + label/mean : 1.00 + precision : 1.00 + prediction/mean : 0.50 + recall : 0.50 + >>> preds = head.predictions(logits) + >>> print(preds['logits']) + tf.Tensor( + [[ 45.] + [-41.]], shape=(2, 1), dtype=float32) + + Usage with a canned estimator: + + ```python + my_head = tf.estimator.BinaryClassHead() + my_estimator = tf.estimator.DNNEstimator( + head=my_head, + hidden_units=..., + feature_columns=...) + ``` + + It can also be used with a custom `model_fn`. Example: + + ```python + def _my_model_fn(features, labels, mode): + my_head = tf.estimator.BinaryClassHead() + logits = tf.keras.Model(...)(features) + + return my_head.create_estimator_spec( + features=features, + mode=mode, + labels=labels, + optimizer=tf.keras.optimizers.Adagrad(lr=0.1), + logits=logits) + + my_estimator = tf.estimator.Estimator(model_fn=_my_model_fn) + ``` + + Args: + weight_column: A string or a `NumericColumn` created by + `tf.feature_column.numeric_column` defining feature column representing + weights. It is used to down weight or boost examples during training. It + will be multiplied by the loss of the example. + thresholds: Iterable of floats in the range `(0, 1)`. For binary + classification metrics such as precision and recall, an eval metric is + generated for each threshold value. This threshold is applied to the + logistic values to determine the binary classification (i.e., above the + threshold is `true`, below is `false`. + label_vocabulary: A list or tuple of strings representing possible label + values. If it is not given, that means labels are already encoded within + [0, 1]. If given, labels must be string type and have any value in + `label_vocabulary`. Note that errors will be raised if `label_vocabulary` + is not provided but labels are strings. + loss_reduction: One of `tf.losses.Reduction` except `NONE`. Decides how to + reduce training loss over batch. Defaults to `SUM_OVER_BATCH_SIZE`, namely + weighted sum of losses divided by `batch size * label_dimension`. + loss_fn: Optional loss function. + name: Name of the head. If provided, summary and metrics keys will be + suffixed by `"/" + name`. Also used as `name_scope` when creating ops. + """ + + def __init__(self, + weight_column=None, + thresholds=None, + label_vocabulary=None, + loss_reduction=tf.losses.Reduction.SUM_OVER_BATCH_SIZE, + loss_fn=None, + name=None): + if label_vocabulary is not None and not isinstance(label_vocabulary, + (list, tuple)): + raise ValueError( + 'label_vocabulary should be a list or a tuple. Given type: {}'.format( + type(label_vocabulary))) + thresholds = tuple(thresholds) if thresholds else tuple() + for threshold in thresholds: + if (threshold <= 0.0) or (threshold >= 1.0): + raise ValueError('thresholds not in (0, 1): {}.'.format((thresholds,))) + base_head.validate_loss_reduction(loss_reduction) + if loss_fn: + base_head.validate_loss_fn_args(loss_fn) + self._weight_column = weight_column + self._thresholds = thresholds + self._label_vocabulary = label_vocabulary + self._loss_reduction = loss_reduction + self._loss_fn = loss_fn + self._name = name + # Metric keys. + keys = metric_keys.MetricKeys + self._loss_mean_key = self._summary_key(keys.LOSS_MEAN) + self._accuracy_key = self._summary_key(keys.ACCURACY) + self._precision_key = self._summary_key(keys.PRECISION) + self._recall_key = self._summary_key(keys.RECALL) + self._prediction_mean_key = self._summary_key(keys.PREDICTION_MEAN) + self._label_mean_key = self._summary_key(keys.LABEL_MEAN) + self._accuracy_baseline_key = self._summary_key(keys.ACCURACY_BASELINE) + self._auc_key = self._summary_key(keys.AUC) + self._auc_pr_key = self._summary_key(keys.AUC_PR) + self._loss_regularization_key = self._summary_key(keys.LOSS_REGULARIZATION) + accuracy_keys = [] + precision_keys = [] + recall_keys = [] + for threshold in self._thresholds: + accuracy_keys.append( + self._summary_key(keys.ACCURACY_AT_THRESHOLD % threshold)) + precision_keys.append( + self._summary_key(keys.PRECISION_AT_THRESHOLD % threshold)) + recall_keys.append( + self._summary_key(keys.RECALL_AT_THRESHOLD % threshold)) + self._accuracy_keys = tuple(accuracy_keys) + self._precision_keys = tuple(precision_keys) + self._recall_keys = tuple(recall_keys) + + @property + def name(self): + """See `base_head.Head` for details.""" + return self._name + + @property + def logits_dimension(self): + """See `base_head.Head` for details.""" + return 1 + + @property + def loss_reduction(self): + """See `base_head.Head` for details.""" + return self._loss_reduction + + # Attributes for lookup tables in Eager execution. Note that for Graph + # execution, the lookup tables are created on demand to make sure the lookup + # table is in the same graph as its input tensors for `train` and `eval` of + # Estimator (as Estimator recreates graphs for `train`, `eval` and + # `predict`). + _cached_class_id_table = None + _cached_class_string_table = None + + @property + def _class_id_table(self): + """Creates a lookup table for class_id. + + In eager execution, this lookup table will be lazily created on the first + call of `self._class_id_table`, and cached for later use; In graph + execution, it will be created on demand. + + Returns: + A hash table for lookup. + """ + if self._cached_class_id_table is None or not tf.executing_eagerly(): + self._cached_class_id_table = lookup_ops.index_table_from_tensor( + vocabulary_list=tuple(self._label_vocabulary), name='class_id_lookup') + return self._cached_class_id_table + + @property + def _class_string_table(self): + """Creates a lookup table for class_string. + + In eager execution, this lookup table will be lazily created on the first + call of `self._class_string_table` and cached for later use; In graph + execution, it will be created on demand. + + Returns: + A hash table for lookup. + """ + if (self._cached_class_string_table is None or not tf.executing_eagerly()): + self._cached_class_string_table = ( + lookup_ops.index_to_string_table_from_tensor( + vocabulary_list=self._label_vocabulary, + name='class_string_lookup')) + return self._cached_class_string_table + + def _processed_labels(self, logits, labels): + """Converts labels to integer id space.""" + labels = base_head.check_dense_labels_match_logits_and_reshape( + labels=labels, logits=logits, expected_labels_dimension=1) + if self._label_vocabulary is not None: + labels = self._class_id_table.lookup(labels) + labels = tf.cast(labels, dtype=tf.dtypes.float32) + return base_head.check_label_range(labels, n_classes=2) + + def _unweighted_loss_and_weights(self, logits, labels, features): + """Computes unweighted loss and weights.""" + if self._loss_fn: + unweighted_loss = base_head.call_loss_fn( + loss_fn=self._loss_fn, + labels=labels, + logits=logits, + features=features, + expected_loss_dim=1) + else: + unweighted_loss = tf.compat.v1.nn.sigmoid_cross_entropy_with_logits( + labels=labels, logits=logits) + weights = base_head.get_weights_and_check_match_logits( + features=features, weight_column=self._weight_column, logits=logits) + return unweighted_loss, weights + + def loss(self, + labels, + logits, + features=None, + mode=None, + regularization_losses=None): + """Returns regularized training loss. See `base_head.Head` for details.""" + del mode # Unused for this head. + with ops.name_scope( + 'losses', values=(logits, labels, regularization_losses, features)): + logits = base_head.check_logits_final_dim(logits, self.logits_dimension) + labels = self._processed_labels(logits, labels) + unweighted_loss, weights = self._unweighted_loss_and_weights( + logits, labels, features) + training_loss = tf.compat.v2.keras.__internal__.losses.compute_weighted_loss( + unweighted_loss, + sample_weight=weights, + reduction=self._loss_reduction) + regularization_loss = tf.math.add_n( + regularization_losses) if regularization_losses is not None else None + regularized_training_loss = ( + training_loss + regularization_loss + if regularization_loss is not None else training_loss) + return regularized_training_loss + + def predictions(self, logits, keys=None): + """Return predictions based on keys. + + See `base_head.Head` for details. + + Args: + logits: logits `Tensor` with shape `[D0, D1, ... DN, logits_dimension]`. + For many applications, the shape is `[batch_size, logits_dimension]`. + keys: a list or tuple of prediction keys. Each key can be either the class + variable of prediction_keys.PredictionKeys or its string value, such as: + prediction_keys.PredictionKeys.CLASSES or 'classes'. If not specified, + it will return the predictions for all valid keys. + + Returns: + A dict of predictions. + """ + pred_keys = prediction_keys.PredictionKeys + valid_keys = [ + pred_keys.LOGITS, pred_keys.LOGISTIC, pred_keys.PROBABILITIES, + pred_keys.CLASS_IDS, pred_keys.CLASSES, pred_keys.ALL_CLASS_IDS, + pred_keys.ALL_CLASSES + ] + + if keys: + base_head.check_prediction_keys(keys, valid_keys) + else: + keys = valid_keys + logits = base_head.check_logits_final_dim(logits, self.logits_dimension) + predictions = {} + with ops.name_scope('predictions', values=(logits,)): + if pred_keys.LOGITS in keys: + predictions[pred_keys.LOGITS] = logits + if pred_keys.LOGISTIC in keys: + logistic = tf.math.sigmoid(logits, name=pred_keys.LOGISTIC) + predictions[pred_keys.LOGISTIC] = logistic + two_class_logits = tf.concat((tf.compat.v1.zeros_like(logits), logits), + axis=-1, + name='two_class_logits') + if pred_keys.PROBABILITIES in keys: + probabilities = tf.compat.v1.nn.softmax( + two_class_logits, name=pred_keys.PROBABILITIES) + predictions[pred_keys.PROBABILITIES] = probabilities + if pred_keys.CLASS_IDS in keys or pred_keys.CLASSES in keys: + class_ids = tf.compat.v1.math.argmax( + two_class_logits, axis=-1, name=pred_keys.CLASS_IDS) + class_ids = tf.compat.v1.expand_dims(class_ids, axis=-1) + if pred_keys.CLASS_IDS in keys: + predictions[pred_keys.CLASS_IDS] = class_ids + if pred_keys.CLASSES in keys: + if self._label_vocabulary is not None: + classes = self._class_string_table.lookup(class_ids) + else: + classes = tf.strings.as_string(class_ids, name='str_classes') + predictions[pred_keys.CLASSES] = classes + if pred_keys.ALL_CLASS_IDS in keys: + predictions[pred_keys.ALL_CLASS_IDS] = base_head.all_class_ids( + logits, n_classes=2) + if pred_keys.ALL_CLASSES in keys: + predictions[pred_keys.ALL_CLASSES] = base_head.all_classes( + logits, n_classes=2, label_vocabulary=self._label_vocabulary) + return predictions + + def metrics(self, regularization_losses=None): + """Creates metrics. See `base_head.Head` for details.""" + keys = metric_keys.MetricKeys + with ops.name_scope('metrics', values=(regularization_losses,)): + # Mean metric. + eval_metrics = {} + eval_metrics[self._loss_mean_key] = tf.keras.metrics.Mean( + name=keys.LOSS_MEAN) + eval_metrics[self._accuracy_key] = tf.keras.metrics.Accuracy( + name=keys.ACCURACY) + eval_metrics[self._precision_key] = tf.keras.metrics.Precision( + name=keys.PRECISION) + eval_metrics[self._recall_key] = tf.keras.metrics.Recall( + name=keys.RECALL) + eval_metrics[self._prediction_mean_key] = tf.keras.metrics.Mean( + name=keys.PREDICTION_MEAN) + eval_metrics[self._label_mean_key] = tf.keras.metrics.Mean( + name=keys.LABEL_MEAN) + eval_metrics[self._accuracy_baseline_key] = tf.keras.metrics.Mean( + name=keys.ACCURACY_BASELINE) + # The default summation_method is "interpolation" in the AUC metric. + eval_metrics[self._auc_key] = tf.keras.metrics.AUC(name=keys.AUC) + eval_metrics[self._auc_pr_key] = tf.keras.metrics.AUC( + curve='PR', name=keys.AUC_PR) + if regularization_losses is not None: + eval_metrics[self._loss_regularization_key] = tf.keras.metrics.Mean( + name=keys.LOSS_REGULARIZATION) + for i, threshold in enumerate(self._thresholds): + eval_metrics[self._accuracy_keys[i]] = tf.keras.metrics.BinaryAccuracy( + name=self._accuracy_keys[i], threshold=threshold) + eval_metrics[self._precision_keys[i]] = tf.keras.metrics.Precision( + name=self._precision_keys[i], thresholds=threshold) + eval_metrics[self._recall_keys[i]] = tf.keras.metrics.Recall( + name=self._recall_keys[i], thresholds=threshold) + return eval_metrics + + def _update_accuracy_baseline(self, eval_metrics): + """Update accuracy baseline metric based on labels mean metric. + + This is the best the model could do by always predicting one class. + + For example, suppose the labels = [0, 1, 0, 1, 1]. So the + label_mean.total = 3, label_mean.count = 5, and + label_mean = label_mean.total / label_mean.count = 3 / 5 = 0.6 + By always predicting one class, there are two cases: + (1) predicted_labels_0 = [0, 0, 0, 0, 0], accuracy_0 = 2 / 5 = 0.4 + (2) predicted_labels_1 = [1, 1, 1, 1, 1], accuracy_1 = 3 / 5 = 0.6 + So the accuracy_baseline = max(accuracy_0, accuracy_1) = 0.6, + = max(label_mean, 1 - label_mean) + + To update the total and count of accuracy_baseline, + accuracy_baseline = max(label_mean, 1 - label_mean) + = max(label_mean.total / label_mean.count, + 1 - label_mean.total / label_mean.count) + = max(label_mean.total / label_mean.count, + (label_mean.count - label_mean.total) / label_mean.count) + So accuracy_baseline.total = max(label_mean.total, + (label_mean.count - label_mean.total)) + accuracy_baseline.count = label_mean.count + + Args: + eval_metrics: A `dict` of metrics to be updated. + """ + label_mean_metric = eval_metrics[self._label_mean_key] + accuracy_baseline_metric = eval_metrics[self._accuracy_baseline_key] + accuracy_baseline_metric.add_update(tf.no_op()) + accuracy_baseline_metric.total = tf.math.maximum( + label_mean_metric.total, + label_mean_metric.count - label_mean_metric.total) + accuracy_baseline_metric.count = label_mean_metric.count + + def _update_auc(self, auc_metric, labels, predictions, weights=None): + predictions = tf.cast(predictions, dtype=tf.dtypes.float32) + if weights is not None: + weights = tf.compat.v2.__internal__.ops.broadcast_weights(weights, predictions) + auc_metric.update_state( + y_true=labels, y_pred=predictions, sample_weight=weights) + + def update_metrics(self, + eval_metrics, + features, + logits, + labels, + regularization_losses=None): + """Updates eval metrics. See `base_head.Head` for details.""" + preds = self.predictions(logits) + class_ids = preds[prediction_keys.PredictionKeys.CLASS_IDS] + logits = base_head.check_logits_final_dim(logits, self.logits_dimension) + labels = self._processed_labels(logits, labels) + unweighted_loss, weights = self._unweighted_loss_and_weights( + logits, labels, features) + # Update metrics. + eval_metrics[self._loss_mean_key].update_state( + values=unweighted_loss, sample_weight=weights) + eval_metrics[self._accuracy_key].update_state( + y_true=labels, y_pred=class_ids, sample_weight=weights) + eval_metrics[self._precision_key].update_state( + y_true=labels, y_pred=class_ids, sample_weight=weights) + eval_metrics[self._recall_key].update_state( + y_true=labels, y_pred=class_ids, sample_weight=weights) + logistic_key = prediction_keys.PredictionKeys.LOGISTIC + predictions = self.predictions(logits, [logistic_key]) + logistic = predictions[logistic_key] + base_head.update_metric_with_broadcast_weights( + eval_metrics[self._prediction_mean_key], logistic, weights) + base_head.update_metric_with_broadcast_weights( + eval_metrics[self._label_mean_key], labels, weights) + self._update_accuracy_baseline(eval_metrics) + self._update_auc( + auc_metric=eval_metrics[self._auc_key], + labels=labels, + predictions=logistic, + weights=weights) + self._update_auc( + auc_metric=eval_metrics[self._auc_pr_key], + labels=labels, + predictions=logistic, + weights=weights) + if regularization_losses is not None: + regularization_loss = tf.math.add_n(regularization_losses) + eval_metrics[self._loss_regularization_key].update_state( + values=regularization_loss) + for i in range(len(self._thresholds)): + eval_metrics[self._accuracy_keys[i]].update_state( + y_true=labels, y_pred=logistic, sample_weight=weights) + eval_metrics[self._precision_keys[i]].update_state( + y_true=labels, y_pred=logistic, sample_weight=weights) + eval_metrics[self._recall_keys[i]].update_state( + y_true=labels, y_pred=logistic, sample_weight=weights) + return eval_metrics + + def _create_tpu_estimator_spec(self, + features, + mode, + logits, + labels=None, + optimizer=None, + trainable_variables=None, + train_op_fn=None, + update_ops=None, + regularization_losses=None): + """Returns an `EstimatorSpec`. + + Args: + features: Input `dict` mapping string feature names to `Tensor` or + `SparseTensor` objects containing the values for that feature in a + minibatch. Often to be used to fetch example-weight tensor. + mode: Estimator's `ModeKeys`. + logits: Logits `Tensor` with shape `[D0, D1, ... DN, 1]`. For many + applications, the shape is `[batch_size, 1]`. + labels: Labels integer or string `Tensor` with shape matching `logits`, + namely `[D0, D1, ... DN, 1]` or `[D0, D1, ... DN]`. `labels` is required + argument when `mode` equals `TRAIN` or `EVAL`. + optimizer: An `tf.keras.optimizers.Optimizer` instance to optimize the + loss in TRAIN mode. Namely, sets `train_op = optimizer.get_updates(loss, + trainable_variables)`, which updates variables to minimize `loss`. + trainable_variables: A list or tuple of `Variable` objects to update to + minimize `loss`. In Tensorflow 1.x, by default these are the list of + variables collected in the graph under the key + `GraphKeys.TRAINABLE_VARIABLES`. As Tensorflow 2.x doesn't have + collections and GraphKeys, trainable_variables need to be passed + explicitly here. + train_op_fn: Function that takes a scalar loss `Tensor` and returns + `train_op`. Used if `optimizer` is `None`. + update_ops: A list or tuple of update ops to be run at training time. For + example, layers such as BatchNormalization create mean and variance + update ops that need to be run at training time. In Tensorflow 1.x, + these are thrown into an UPDATE_OPS collection. As Tensorflow 2.x + doesn't have collections, update_ops need to be passed explicitly here. + regularization_losses: A list of additional scalar losses to be added to + the training loss, such as regularization losses. These losses are + usually expressed as a batch average, so for best results users need to + set `loss_reduction=SUM_OVER_BATCH_SIZE` when creating the head to avoid + scaling errors. + + Returns: + `EstimatorSpec`. + + Raises: + ValueError: If both `train_op_fn` and `optimizer` are `None` in TRAIN + mode, or if both are set. + """ + with ops.name_scope(self._name, 'head'): + # Predict. + pred_keys = prediction_keys.PredictionKeys + predictions = self.predictions(logits) + if mode == ModeKeys.PREDICT: + probabilities = predictions[pred_keys.PROBABILITIES] + logistic = predictions[pred_keys.LOGISTIC] + classifier_output = base_head.classification_output( + scores=probabilities, + n_classes=2, + label_vocabulary=self._label_vocabulary) + return model_fn._TPUEstimatorSpec( # pylint: disable=protected-access + mode=ModeKeys.PREDICT, + predictions=predictions, + export_outputs={ + base_head.DEFAULT_SERVING_KEY: classifier_output, + base_head.CLASSIFY_SERVING_KEY: classifier_output, + base_head.REGRESS_SERVING_KEY: + export_output.RegressionOutput(value=logistic), + base_head.PREDICT_SERVING_KEY: + export_output.PredictOutput(predictions) + }) + regularized_training_loss = self.loss( + logits=logits, + labels=labels, + features=features, + mode=mode, + regularization_losses=regularization_losses) + # Eval. + if mode == ModeKeys.EVAL: + eval_metrics = self.metrics(regularization_losses=regularization_losses) + return model_fn._TPUEstimatorSpec( # pylint: disable=protected-access + mode=ModeKeys.EVAL, + predictions=predictions, + loss=regularized_training_loss, + eval_metrics=base_head.create_eval_metrics_tuple( + self.update_metrics, { + 'eval_metrics': eval_metrics, + 'features': features, + 'logits': logits, + 'labels': labels, + 'regularization_losses': regularization_losses + })) + # Train. + train_op = base_head.create_estimator_spec_train_op( + head_name=self._name, + optimizer=optimizer, + train_op_fn=train_op_fn, + update_ops=update_ops, + trainable_variables=trainable_variables, + regularized_training_loss=regularized_training_loss, + loss_reduction=self._loss_reduction) + # Create summary. + base_head.create_estimator_spec_summary( + regularized_training_loss=regularized_training_loss, + regularization_losses=regularization_losses, + summary_key_fn=self._summary_key) + return model_fn._TPUEstimatorSpec( # pylint: disable=protected-access + mode=ModeKeys.TRAIN, + predictions=predictions, + loss=regularized_training_loss, + train_op=train_op) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/head/head_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/head/head_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..638ff5be77fa515a861663ef301bc57998b165dc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/head/head_utils.py @@ -0,0 +1,100 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Utilities for heads and unit tests.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import tensorflow as tf +from tensorflow_estimator.python.estimator.head import binary_class_head +from tensorflow_estimator.python.estimator.head import multi_class_head + +_DEFAULT_SERVING_KEY = tf.saved_model.DEFAULT_SERVING_SIGNATURE_DEF_KEY + + +def binary_or_multi_class_head(n_classes, weight_column, label_vocabulary, + loss_reduction): + """Creates either binary or multi-class head. + + Args: + n_classes: Number of label classes. + weight_column: A string or a `NumericColumn` created by + `tf.feature_column.numeric_column` defining feature column representing + weights. It is used to down weight or boost examples during training. It + will be multiplied by the loss of the example. If it is a string, it is + used as a key to fetch weight tensor from the `features`. If it is a + `NumericColumn`, raw tensor is fetched by key `weight_column.key`, then + weight_column.normalizer_fn is applied on it to get weight tensor. + label_vocabulary: A list of strings represents possible label values. If + given, labels must be string type and have any value in + `label_vocabulary`. If it is not given, that means labels are already + encoded as integer or float within [0, 1] for `n_classes=2` and encoded as + integer values in {0, 1,..., n_classes-1} for `n_classes`>2 . Also there + will be errors if vocabulary is not provided and labels are string. + loss_reduction: One of `tf.losses.Reduction` except `NONE`. Defines how to + reduce training loss over batch. Defaults to `SUM_OVER_BATCH_SIZE`. + + Returns: + A `Head` instance. + """ + if n_classes == 2: + head = binary_class_head.BinaryClassHead( + weight_column=weight_column, + label_vocabulary=label_vocabulary, + loss_reduction=loss_reduction) + else: + head = multi_class_head.MultiClassHead( + n_classes, + weight_column=weight_column, + label_vocabulary=label_vocabulary, + loss_reduction=loss_reduction) + return head + + +def _initialize_variables(test_case, scaffold): + scaffold.finalize() + test_case.assertIsNone(scaffold.init_feed_dict) + test_case.assertIsNone(scaffold.init_fn) + scaffold.init_op.run() + scaffold.ready_for_local_init_op.eval() + scaffold.local_init_op.run() + scaffold.ready_op.eval() + test_case.assertIsNotNone(scaffold.saver) + + +def _assert_simple_summaries(test_case, + expected_summaries, + summary_str, + tol=1e-6): + """Assert summary the specified simple values. + + Args: + test_case: test case. + expected_summaries: Dict of expected tags and simple values. + summary_str: Serialized `summary_pb2.Summary`. + tol: Tolerance for relative and absolute. + """ + summary = tf.compat.v1.summary.Summary() + summary.ParseFromString(summary_str) + test_case.assertAllClose( + expected_summaries, {v.tag: v.simple_value for v in summary.value}, + rtol=tol, + atol=tol) + + +def _assert_no_hooks(test_case, spec): + test_case.assertAllEqual([], spec.training_chief_hooks) + test_case.assertAllEqual([], spec.training_hooks) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/head/multi_class_head.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/head/multi_class_head.py new file mode 100644 index 0000000000000000000000000000000000000000..77f48717e853438fb160b272669e7a6c2e20c409 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/head/multi_class_head.py @@ -0,0 +1,496 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Multi class head.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import tensorflow as tf +from tensorflow.python.framework import ops +from tensorflow.python.ops import lookup_ops +from tensorflow_estimator.python.estimator import model_fn +from tensorflow_estimator.python.estimator.canned import metric_keys +from tensorflow_estimator.python.estimator.canned import prediction_keys +from tensorflow_estimator.python.estimator.estimator_export import estimator_export +from tensorflow_estimator.python.estimator.export import export_output +from tensorflow_estimator.python.estimator.head import base_head +from tensorflow_estimator.python.estimator.mode_keys import ModeKeys + + +@estimator_export('estimator.MultiClassHead') +class MultiClassHead(base_head.Head): + """Creates a `Head` for multi class classification. + + Uses `sparse_softmax_cross_entropy` loss. + + The head expects `logits` with shape `[D0, D1, ... DN, n_classes]`. + In many applications, the shape is `[batch_size, n_classes]`. + + `labels` must be a dense `Tensor` with shape matching `logits`, namely + `[D0, D1, ... DN, 1]`. If `label_vocabulary` given, `labels` must be a string + `Tensor` with values from the vocabulary. If `label_vocabulary` is not given, + `labels` must be an integer `Tensor` with values specifying the class index. + + If `weight_column` is specified, weights must be of shape + `[D0, D1, ... DN]`, or `[D0, D1, ... DN, 1]`. + + The loss is the weighted sum over the input dimensions. Namely, if the input + labels have shape `[batch_size, 1]`, the loss is the weighted sum over + `batch_size`. + + Also supports custom `loss_fn`. `loss_fn` takes `(labels, logits)` or + `(labels, logits, features, loss_reduction)` as arguments and returns + unreduced loss with shape `[D0, D1, ... DN, 1]`. `loss_fn` must support + integer `labels` with shape `[D0, D1, ... DN, 1]`. Namely, the head applies + `label_vocabulary` to the input labels before passing them to `loss_fn`. + + Usage: + + >>> n_classes = 3 + >>> head = tf.estimator.MultiClassHead(n_classes) + >>> logits = np.array(((10, 0, 0), (0, 10, 0),), dtype=np.float32) + >>> labels = np.array(((1,), (1,)), dtype=np.int64) + >>> features = {'x': np.array(((42,),), dtype=np.int32)} + >>> # expected_loss = sum(cross_entropy(labels, logits)) / batch_size + >>> # = sum(10, 0) / 2 = 5. + >>> loss = head.loss(labels, logits, features=features) + >>> print('{:.2f}'.format(loss.numpy())) + 5.00 + >>> eval_metrics = head.metrics() + >>> updated_metrics = head.update_metrics( + ... eval_metrics, features, logits, labels) + >>> for k in sorted(updated_metrics): + ... print('{} : {:.2f}'.format(k, updated_metrics[k].result().numpy())) + accuracy : 0.50 + average_loss : 5.00 + >>> preds = head.predictions(logits) + >>> print(preds['logits']) + tf.Tensor( + [[10. 0. 0.] + [ 0. 10. 0.]], shape=(2, 3), dtype=float32) + + Usage with a canned estimator: + + ```python + my_head = tf.estimator.MultiClassHead(n_classes=3) + my_estimator = tf.estimator.DNNEstimator( + head=my_head, + hidden_units=..., + feature_columns=...) + ``` + + It can also be used with a custom `model_fn`. Example: + + ```python + def _my_model_fn(features, labels, mode): + my_head = tf.estimator.MultiClassHead(n_classes=3) + logits = tf.keras.Model(...)(features) + + return my_head.create_estimator_spec( + features=features, + mode=mode, + labels=labels, + optimizer=tf.keras.optimizers.Adagrad(lr=0.1), + logits=logits) + + my_estimator = tf.estimator.Estimator(model_fn=_my_model_fn) + ``` + + Args: + n_classes: Number of classes, must be greater than 2 (for 2 classes, use + `BinaryClassHead`). + weight_column: A string or a `NumericColumn` created by + `tf.feature_column.numeric_column` defining feature column representing + weights. It is used to down weight or boost examples during training. It + will be multiplied by the loss of the example. + label_vocabulary: A list or tuple of strings representing possible label + values. If it is not given, that means labels are already encoded as an + integer within [0, n_classes). If given, labels must be of string type and + have any value in `label_vocabulary`. Note that errors will be raised if + `label_vocabulary` is not provided but labels are strings. If both + `n_classes` and `label_vocabulary` are provided, `label_vocabulary` should + contain exactly `n_classes` items. + loss_reduction: One of `tf.losses.Reduction` except `NONE`. Decides how to + reduce training loss over batch. Defaults to `SUM_OVER_BATCH_SIZE`, namely + weighted sum of losses divided by `batch size * label_dimension`. + loss_fn: Optional loss function. + name: Name of the head. If provided, summary and metrics keys will be + suffixed by `"/" + name`. Also used as `name_scope` when creating ops. + """ + + def __init__(self, + n_classes, + weight_column=None, + label_vocabulary=None, + loss_reduction=tf.losses.Reduction.SUM_OVER_BATCH_SIZE, + loss_fn=None, + name=None): + if n_classes is None: + raise ValueError('n_classes cannot be None') + if label_vocabulary is not None and not isinstance(label_vocabulary, + (list, tuple)): + raise ValueError( + 'label_vocabulary should be a list or a tuple. Given type: {}'.format( + type(label_vocabulary))) + if label_vocabulary is not None and len(label_vocabulary) != n_classes: + raise ValueError( + '"label_vocabulary" does not have "n_classes" items. ' + 'len(label_vocabulary)={}, n_classes={}, label_vocabulary={}'.format( + len(label_vocabulary), n_classes, label_vocabulary)) + base_head.validate_loss_reduction(loss_reduction) + if loss_fn: + base_head.validate_loss_fn_args(loss_fn) + self._n_classes = base_head.validate_n_classes(n_classes) + self._weight_column = weight_column + self._label_vocabulary = label_vocabulary + self._loss_reduction = loss_reduction + self._loss_fn = loss_fn + self._name = name + # Metric keys. + keys = metric_keys.MetricKeys + self._loss_mean_key = self._summary_key(keys.LOSS_MEAN) + self._accuracy_key = self._summary_key(keys.ACCURACY) + self._loss_regularization_key = self._summary_key(keys.LOSS_REGULARIZATION) + + @property + def name(self): + """See `base_head.Head` for details.""" + return self._name + + @property + def logits_dimension(self): + """See `base_head.Head` for details.""" + return self._n_classes + + @property + def loss_reduction(self): + """See `base_head.Head` for details.""" + return self._loss_reduction + + # Attributes for lookup tables in Eager execution. Note that for Graph + # execution, the lookup tables are created on demanded to make sure the + # lookup table is in the same graph as its input tensors for `train` and + # 'eval' of Estimator (as Estimator recreates graphs for `train`, `eval` and + # `predict`). + _cached_class_id_table = None + _cached_class_string_table = None + + @property + def _class_id_table(self): + """Creates a lookup table for class_id. + + In eager execution, this lookup table will be lazily created on the first + call of `self._class_id_table`, and cached for later use; In graph + execution, it will be created on demand. + + Returns: + A hash table for lookup. + """ + if self._cached_class_id_table is None or not tf.executing_eagerly(): + self._cached_class_id_table = lookup_ops.index_table_from_tensor( + vocabulary_list=tuple(self._label_vocabulary), name='class_id_lookup') + return self._cached_class_id_table + + @property + def _class_string_table(self): + """Creates a lookup table for class_string. + + In eager execution, this lookup table will be lazily created on the first + call of `self._class_string_table` and cached for later use; In graph + execution, it will be created on demand. + + Returns: + A hash table for lookup. + """ + if (self._cached_class_string_table is None or not tf.executing_eagerly()): + self._cached_class_string_table = ( + lookup_ops.index_to_string_table_from_tensor( + vocabulary_list=self._label_vocabulary, + name='class_string_lookup')) + return self._cached_class_string_table + + def _processed_labels(self, logits, labels): + """Converts labels to integer id space.""" + labels = base_head.check_dense_labels_match_logits_and_reshape( + labels=labels, logits=logits, expected_labels_dimension=1) + if self._label_vocabulary is None: + if not labels.dtype.is_integer: + raise ValueError( + 'Labels dtype should be integer. Instead got {}.'.format( + labels.dtype)) + label_ids = labels + else: + if labels.dtype != tf.dtypes.string: + raise ValueError('Labels dtype should be string if there is a ' + 'vocabulary. Instead got {}'.format(labels.dtype)) + label_ids = self._class_id_table.lookup(labels) + return base_head.check_label_range(label_ids, self._n_classes) + + def _unweighted_loss_and_weights(self, logits, label_ids, features): + """Computes loss spec.""" + if self._loss_fn: + unweighted_loss = base_head.call_loss_fn( + loss_fn=self._loss_fn, + labels=label_ids, + logits=logits, + features=features, + expected_loss_dim=1) + else: + unweighted_loss = tf.compat.v1.losses.sparse_softmax_cross_entropy( + labels=label_ids, + logits=logits, + reduction=tf.compat.v1.losses.Reduction.NONE) + # Restore the squeezed dim, so unweighted_loss matches the weights shape. + unweighted_loss = tf.compat.v1.expand_dims(unweighted_loss, axis=-1) + weights = base_head.get_weights_and_check_match_logits( + features=features, weight_column=self._weight_column, logits=logits) + return unweighted_loss, weights + + def loss(self, + labels, + logits, + features=None, + mode=None, + regularization_losses=None): + """Returns regularized training loss. See `base_head.Head` for details.""" + del mode # Unused for this head. + with ops.name_scope( + 'losses', values=(logits, labels, regularization_losses, features)): + logits = base_head.check_logits_final_dim(logits, self.logits_dimension) + label_ids = self._processed_labels(logits, labels) + unweighted_loss, weights = self._unweighted_loss_and_weights( + logits, label_ids, features) + training_loss = tf.compat.v2.keras.__internal__.losses.compute_weighted_loss( + unweighted_loss, + sample_weight=weights, + reduction=self._loss_reduction) + regularization_loss = tf.math.add_n( + regularization_losses) if regularization_losses is not None else None + regularized_training_loss = ( + training_loss + regularization_loss + if regularization_loss is not None else training_loss) + return regularized_training_loss + + def predictions(self, logits, keys=None): + """Return predictions based on keys. + + See `base_head.Head` for details. + + Args: + logits: logits `Tensor` with shape `[D0, D1, ... DN, logits_dimension]`. + For many applications, the shape is `[batch_size, logits_dimension]`. + keys: a list or tuple of prediction keys. Each key can be either the class + variable of prediction_keys.PredictionKeys or its string value, such as: + prediction_keys.PredictionKeys.CLASSES or 'classes'. If not specified, + it will return the predictions for all valid keys. + + Returns: + A dict of predictions. + """ + pred_keys = prediction_keys.PredictionKeys + valid_keys = [ + pred_keys.LOGITS, pred_keys.PROBABILITIES, pred_keys.CLASS_IDS, + pred_keys.CLASSES, pred_keys.ALL_CLASS_IDS, pred_keys.ALL_CLASSES + ] + if keys: + base_head.check_prediction_keys(keys, valid_keys) + else: + keys = valid_keys + logits = base_head.check_logits_final_dim(logits, self.logits_dimension) + predictions = {} + with ops.name_scope('predictions', values=(logits,)): + if pred_keys.LOGITS in keys: + predictions[pred_keys.LOGITS] = logits + if pred_keys.PROBABILITIES in keys: + probabilities = tf.compat.v1.nn.softmax( + logits, name=pred_keys.PROBABILITIES) + predictions[pred_keys.PROBABILITIES] = probabilities + if pred_keys.CLASS_IDS in keys or pred_keys.CLASSES in keys: + # class_ids's shape is [D0, D1, ... DN]. + class_ids = tf.compat.v1.math.argmax( + logits, axis=-1, name=pred_keys.CLASS_IDS) + # Expand to [batch_size, 1]. + class_ids = tf.compat.v1.expand_dims(class_ids, axis=-1) + if pred_keys.CLASS_IDS in keys: + predictions[pred_keys.CLASS_IDS] = class_ids + if pred_keys.CLASSES in keys: + if self._label_vocabulary: + classes = self._class_string_table.lookup(class_ids) + else: + classes = tf.strings.as_string(class_ids, name='str_classes') + predictions[pred_keys.CLASSES] = classes + if pred_keys.ALL_CLASS_IDS in keys: + predictions[pred_keys.ALL_CLASS_IDS] = base_head.all_class_ids( + logits, n_classes=self._n_classes) + if pred_keys.ALL_CLASSES in keys: + predictions[pred_keys.ALL_CLASSES] = base_head.all_classes( + logits, + n_classes=self._n_classes, + label_vocabulary=self._label_vocabulary) + return predictions + + def metrics(self, regularization_losses=None): + """Creates metrics. See `base_head.Head` for details.""" + keys = metric_keys.MetricKeys + with ops.name_scope('metrics', values=(regularization_losses,)): + # Mean metric. + eval_metrics = {} + eval_metrics[self._loss_mean_key] = tf.keras.metrics.Mean( + name=keys.LOSS_MEAN) + if regularization_losses is not None: + eval_metrics[self._loss_regularization_key] = tf.keras.metrics.Mean( + name=keys.LOSS_REGULARIZATION) + # Accuracy metric. + eval_metrics[self._accuracy_key] = tf.keras.metrics.Accuracy( + name=keys.ACCURACY) + return eval_metrics + + def update_metrics(self, + eval_metrics, + features, + logits, + labels, + regularization_losses=None): + """Updates eval metrics. See `base_head.Head` for details.""" + preds = self.predictions(logits) + class_ids = preds[prediction_keys.PredictionKeys.CLASS_IDS] + logits = base_head.check_logits_final_dim(logits, self.logits_dimension) + label_ids = self._processed_labels(logits, labels) + unweighted_loss, weights = self._unweighted_loss_and_weights( + logits, label_ids, features) + + # Update metrics. + eval_metrics[self._loss_mean_key].update_state( + values=unweighted_loss, sample_weight=weights) + eval_metrics[self._accuracy_key].update_state( + y_true=label_ids, y_pred=class_ids, sample_weight=weights) + + if regularization_losses is not None: + regularization_loss = tf.math.add_n(regularization_losses) + eval_metrics[self._loss_regularization_key].update_state( + values=regularization_loss) + return eval_metrics + + def _create_tpu_estimator_spec(self, + features, + mode, + logits, + labels=None, + optimizer=None, + trainable_variables=None, + train_op_fn=None, + update_ops=None, + regularization_losses=None): + """Returns a `model_fn._TPUEstimatorSpec`. + + Args: + features: Input `dict` of `Tensor` or `SparseTensor` objects. + mode: Estimator's `ModeKeys`. + logits: logits `Tensor` with shape `[D0, D1, ... DN, logits_dimension]`. + For many applications, the shape is `[batch_size, logits_dimension]`. + labels: Labels integer or string `Tensor` with shape matching `logits`, + namely `[D0, D1, ... DN, 1]` or `[D0, D1, ... DN]`. `labels` is required + argument when `mode` equals `TRAIN` or `EVAL`. + optimizer: An `tf.keras.optimizers.Optimizer` instance to optimize the + loss in TRAIN mode. Namely, sets `train_op = optimizer.get_updates(loss, + trainable_variables)`, which updates variables to minimize `loss`. + trainable_variables: A list or tuple of `Variable` objects to update to + minimize `loss`. In Tensorflow 1.x, by default these are the list of + variables collected in the graph under the key + `GraphKeys.TRAINABLE_VARIABLES`. As Tensorflow 2.x doesn't have + collections and GraphKeys, trainable_variables need to be passed + explicitly here. + train_op_fn: Function that takes a scalar loss `Tensor` and returns + `train_op`. Used if `optimizer` is `None`. + update_ops: A list or tuple of update ops to be run at training time. For + example, layers such as BatchNormalization create mean and variance + update ops that need to be run at training time. In Tensorflow 1.x, + these are thrown into an UPDATE_OPS collection. As Tensorflow 2.x + doesn't have collections, update_ops need to be passed explicitly here. + regularization_losses: A list of additional scalar losses to be added to + the training loss, such as regularization losses. These losses are + usually expressed as a batch average, so for best results users need to + use the default `loss_reduction=SUM_OVER_BATCH_SIZE` when creating the + head to avoid scaling errors. + + Returns: + A `model_fn._TPUEstimatorSpec` instance. + + Raises: + ValueError: If both `train_op_fn` and `optimizer` are `None` in TRAIN + mode, or if both are set. + """ + with ops.name_scope(self._name, 'head'): + # Predict. + pred_keys = prediction_keys.PredictionKeys + predictions = self.predictions(logits) + if mode == ModeKeys.PREDICT: + probabilities = predictions[pred_keys.PROBABILITIES] + classifier_output = base_head.classification_output( + scores=probabilities, + n_classes=self._n_classes, + label_vocabulary=self._label_vocabulary) + return model_fn._TPUEstimatorSpec( # pylint: disable=protected-access + mode=ModeKeys.PREDICT, + predictions=predictions, + export_outputs={ + base_head.DEFAULT_SERVING_KEY: + classifier_output, + base_head.CLASSIFY_SERVING_KEY: + classifier_output, + base_head.PREDICT_SERVING_KEY: + export_output.PredictOutput(predictions) + }) + regularized_training_loss = self.loss( + logits=logits, + labels=labels, + features=features, + mode=mode, + regularization_losses=regularization_losses) + # Eval. + if mode == ModeKeys.EVAL: + eval_metrics = self.metrics(regularization_losses=regularization_losses) + return model_fn._TPUEstimatorSpec( # pylint: disable=protected-access + mode=ModeKeys.EVAL, + predictions=predictions, + loss=regularized_training_loss, + eval_metrics=base_head.create_eval_metrics_tuple( + self.update_metrics, { + 'eval_metrics': eval_metrics, + 'features': features, + 'logits': logits, + 'labels': labels, + 'regularization_losses': regularization_losses + })) + # Train. + train_op = base_head.create_estimator_spec_train_op( + head_name=self._name, + optimizer=optimizer, + train_op_fn=train_op_fn, + update_ops=update_ops, + trainable_variables=trainable_variables, + regularized_training_loss=regularized_training_loss, + loss_reduction=self._loss_reduction) + # Create summary. + base_head.create_estimator_spec_summary( + regularized_training_loss=regularized_training_loss, + regularization_losses=regularization_losses, + summary_key_fn=self._summary_key) + return model_fn._TPUEstimatorSpec( # pylint: disable=protected-access + mode=ModeKeys.TRAIN, + predictions=predictions, + loss=regularized_training_loss, + train_op=train_op) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/head/multi_head.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/head/multi_head.py new file mode 100644 index 0000000000000000000000000000000000000000..5d6cb1d2710b4e28305ee358baf51abf6e831217 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/head/multi_head.py @@ -0,0 +1,547 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Multi head class.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import six +import tensorflow as tf +from tensorflow.python.framework import ops +from tensorflow_estimator.python.estimator import model_fn +from tensorflow_estimator.python.estimator.canned import metric_keys +from tensorflow_estimator.python.estimator.estimator_export import estimator_export +from tensorflow_estimator.python.estimator.export import export_output +from tensorflow_estimator.python.estimator.head import base_head +from tensorflow_estimator.python.estimator.mode_keys import ModeKeys + + +def _no_op_train_fn(loss): + del loss + return tf.no_op() + + +def _default_export_output(export_outputs, head_name): + """Extracts the default export output from the given export_outputs dict.""" + if len(export_outputs) == 1: + return next(six.itervalues(export_outputs)) + try: + return export_outputs[base_head.DEFAULT_SERVING_KEY] + except KeyError: + raise ValueError( + '{} did not specify default export_outputs. ' + 'Given: {} ' + 'Suggested fix: Use one of the heads in tf.estimator, or include ' + 'key {} in export_outputs.'.format(head_name, export_outputs, + base_head.DEFAULT_SERVING_KEY)) + + +@estimator_export('estimator.MultiHead') +class MultiHead(base_head.Head): + """Creates a `Head` for multi-objective learning. + + This class merges the output of multiple `Head` objects. Specifically: + + * For training, sums losses of each head, calls `train_op_fn` with this + final loss. + * For eval, merges metrics by adding `head.name` suffix to the keys in eval + metrics, such as `precision/head1.name`, `precision/head2.name`. + * For prediction, merges predictions and updates keys in prediction dict to a + 2-tuple, `(head.name, prediction_key)`. Merges `export_outputs` such that + by default the first head is served. + + Usage: + + >>> head1 = tf.estimator.MultiLabelHead(n_classes=2, name='head1') + >>> head2 = tf.estimator.MultiLabelHead(n_classes=3, name='head2') + >>> multi_head = tf.estimator.MultiHead([head1, head2]) + >>> logits = { + ... 'head1': np.array([[-10., 10.], [-15., 10.]], dtype=np.float32), + ... 'head2': np.array([[20., -20., 20.], [-30., 20., -20.]], + ... dtype=np.float32),} + >>> labels = { + ... 'head1': np.array([[1, 0], [1, 1]], dtype=np.int64), + ... 'head2': np.array([[0, 1, 0], [1, 1, 0]], dtype=np.int64),} + >>> features = {'x': np.array(((42,),), dtype=np.float32)} + >>> # For large logits, sigmoid cross entropy loss is approximated as: + >>> # loss = labels * (logits < 0) * (-logits) + + >>> # (1 - labels) * (logits > 0) * logits => + >>> # head1: expected_unweighted_loss = [[10., 10.], [15., 0.]] + >>> # loss1 = ((10 + 10) / 2 + (15 + 0) / 2) / 2 = 8.75 + >>> # head2: expected_unweighted_loss = [[20., 20., 20.], [30., 0., 0]] + >>> # loss2 = ((20 + 20 + 20) / 3 + (30 + 0 + 0) / 3) / 2 = 15.00 + >>> # loss = loss1 + loss2 = 8.75 + 15.00 = 23.75 + >>> loss = multi_head.loss(labels, logits, features=features) + >>> print('{:.2f}'.format(loss.numpy())) + 23.75 + >>> eval_metrics = multi_head.metrics() + >>> updated_metrics = multi_head.update_metrics( + ... eval_metrics, features, logits, labels) + >>> for k in sorted(updated_metrics): + ... print('{} : {:.2f}'.format(k, updated_metrics[k].result().numpy())) + auc/head1 : 0.17 + auc/head2 : 0.33 + auc_precision_recall/head1 : 0.60 + auc_precision_recall/head2 : 0.40 + average_loss/head1 : 8.75 + average_loss/head2 : 15.00 + loss/head1 : 8.75 + loss/head2 : 15.00 + >>> preds = multi_head.predictions(logits) + >>> print(preds[('head1', 'logits')]) + tf.Tensor( + [[-10. 10.] + [-15. 10.]], shape=(2, 2), dtype=float32) + + Usage with a canned estimator: + + ```python + # In `input_fn`, specify labels as a dict keyed by head name: + def input_fn(): + features = ... + labels1 = ... + labels2 = ... + return features, {'head1.name': labels1, 'head2.name': labels2} + + # In `model_fn`, specify logits as a dict keyed by head name: + def model_fn(features, labels, mode): + # Create simple heads and specify head name. + head1 = tf.estimator.MultiClassHead(n_classes=3, name='head1') + head2 = tf.estimator.BinaryClassHead(name='head2') + # Create MultiHead from two simple heads. + head = tf.estimator.MultiHead([head1, head2]) + # Create logits for each head, and combine them into a dict. + logits1, logits2 = logit_fn() + logits = {'head1.name': logits1, 'head2.name': logits2} + # Return the merged EstimatorSpec + return head.create_estimator_spec(..., logits=logits, ...) + + # Create an estimator with this model_fn. + estimator = tf.estimator.Estimator(model_fn=model_fn) + estimator.train(input_fn=input_fn) + ``` + + Also supports `logits` as a `Tensor` of shape + `[D0, D1, ... DN, logits_dimension]`. It will split the `Tensor` along the + last dimension and distribute it appropriately among the heads. E.g.: + + ```python + # Input logits. + logits = np.array([[-1., 1., 2., -2., 2.], [-1.5, 1., -3., 2., -2.]], + dtype=np.float32) + # Suppose head1 and head2 have the following logits dimension. + head1.logits_dimension = 2 + head2.logits_dimension = 3 + # After splitting, the result will be: + logits_dict = {'head1_name': [[-1., 1.], [-1.5, 1.]], + 'head2_name': [[2., -2., 2.], [-3., 2., -2.]]} + ``` + + Usage: + + ```python + def model_fn(features, labels, mode): + # Create simple heads and specify head name. + head1 = tf.estimator.MultiClassHead(n_classes=3, name='head1') + head2 = tf.estimator.BinaryClassHead(name='head2') + # Create multi-head from two simple heads. + head = tf.estimator.MultiHead([head1, head2]) + # Create logits for the multihead. The result of logits is a `Tensor`. + logits = logit_fn(logits_dimension=head.logits_dimension) + # Return the merged EstimatorSpec + return head.create_estimator_spec(..., logits=logits, ...) + ``` + + Args: + heads: List or tuple of `Head` instances. All heads must have `name` + specified. The first head in the list is the default used at serving time. + head_weights: Optional list of weights, same length as `heads`. Used when + merging losses to calculate the weighted sum of losses from each head. If + `None`, all losses are weighted equally. + """ + + def __init__(self, heads, head_weights=None): + if not heads: + raise ValueError('Must specify heads. Given: {}'.format(heads)) + if head_weights: + if len(head_weights) != len(heads): + raise ValueError( + 'heads and head_weights must have the same size. ' + 'Given len(heads): {}. Given len(head_weights): {}.'.format( + len(heads), len(head_weights))) + self._logits_dimension = 0 + for head in heads: + if head.name is None: + raise ValueError( + 'All given heads must have name specified. Given: {}'.format(head)) + self._logits_dimension += head.logits_dimension + self._heads = tuple(heads) + self._head_weights = tuple(head_weights) if head_weights else tuple() + # Metric keys. + keys = metric_keys.MetricKeys + self._loss_regularization_key = self._summary_key(keys.LOSS_REGULARIZATION) + loss_keys = [] + for head in self._heads: + loss_keys.append('{}/{}'.format(keys.LOSS, head.name)) + self._loss_keys = tuple(loss_keys) + + @property + def name(self): + """See `base_head.Head` for details.""" + return '_'.join([h.name for h in self._heads]) + + @property + def logits_dimension(self): + """See `base_head.Head` for details.""" + return self._logits_dimension + + @property + def loss_reduction(self): + """See `base_head.Head` for details.""" + loss_reductions = [head.loss_reduction for head in self._heads] + if len(set(loss_reductions)) > 1: + raise ValueError( + 'The loss_reduction must be the same for different heads. ' + 'Given: {}'.format(loss_reductions)) + return loss_reductions[0] + + def _split_logits(self, logits): + """Splits logits along the last dimension and returns a dict. + + If the input logits is not a dict, splitting is applied based on the logits + dimension of each head. + For example: + + ```python + # head1.logits_dimension = 2 + # head2.logits_dimension = 3 + head1 = tf.estimator.MultiLabelHead(n_classes=2, name='head1_name') + head2 = tf.estimator.MultiClassHead(n_classes=3, name='head2_name') + multi_head = tf.estimator.MultiHead([head1, head2]) + # Input logits + logits = np.array([[-1., 1., 2., -2., 2.], [-1.5, 1., -3., 2., -2.]], + dtype=np.float32) + # As logits is not a dict, _split_logits is applied and returns the + # logits_dict as + logits_dict = {'head1_name': [[-1., 1.], [-1.5, 1.]], + 'head2_name': [[2., -2., 2.], [-3., 2., -2.]]} + ``` + Args: + logits: logits `Tensor` with shape `[D0, D1, ... DN, logits_dimension]`. + For many applications, the shape is `[batch_size, logits_dimension]`. + + Returns: + logits_dict: A dict of logits for each head. + """ + logits_dict = {} + with ops.name_scope('split_logits', values=[logits]): + logits = ops.convert_to_tensor(logits) + logits_dimensions = [head.logits_dimension for head in self._heads] + total_logits_dimension = sum(logits_dimensions) + logits_tensor_shape = logits.shape.as_list() + last_dimension_size = logits_tensor_shape[-1] + if last_dimension_size is not None: + if last_dimension_size != total_logits_dimension: + raise ValueError( + 'Could not split logits of shape %r among the heads with ' + 'individual logits dimensions: %r. The last dimension of the ' + 'logits tensor should equal %d but is %d.' % + ((logits_tensor_shape, logits_dimensions, last_dimension_size, + total_logits_dimension))) + + # TODO(b/119617064): unify eager and graph implementations + if tf.executing_eagerly(): + logits_shape = logits._shape_tuple() # pylint: disable=protected-access + batch_shape = logits_shape[:-1] + else: + batch_shape = tf.compat.v1.shape(logits)[:-1] + zeros_like_batch_shape = tf.compat.v1.zeros_like(batch_shape) + minus_ones_like_batch_shape = -1 * tf.compat.v1.ones_like(batch_shape) + begin_idx = 0 + for head in self._heads: + begin_tensor = tf.concat([zeros_like_batch_shape, [begin_idx]], axis=0) + size_tensor = tf.concat( + [minus_ones_like_batch_shape, [head.logits_dimension]], axis=0) + logits_dict[head.name] = tf.slice( + logits, begin=begin_tensor, size=size_tensor) + begin_idx += head.logits_dimension + return logits_dict + + def _check_logits_and_labels(self, logits, labels=None): + """Validates the keys of logits and labels.""" + head_names = [] + for head in self._heads: + head_names.append(head.name) + # Checks logits keys and splits it if it's not a dict + if isinstance(logits, dict): + logits_missing_names = list(set(head_names) - set(list(logits))) + if logits_missing_names: + raise ValueError('logits has missing values for head(s): {}'.format( + logits_missing_names)) + logits_dict = logits + else: + logits_dict = self._split_logits(logits) + # Checks labels type and its keys + if labels is not None: + if not isinstance(labels, dict): + raise ValueError('labels must be a dict. Given: {}'.format(labels)) + labels_missing_names = list(set(head_names) - set(list(labels))) + if labels_missing_names: + raise ValueError('labels has missing values for head(s): {}'.format( + labels_missing_names)) + return logits_dict + + def loss(self, + labels, + logits, + features=None, + mode=None, + regularization_losses=None): + """Returns regularized training loss. See `base_head.Head` for details.""" + logits_dict = self._check_logits_and_labels(logits, labels) + training_losses = [] + for head in self._heads: + training_loss = head.loss( + logits=logits_dict[head.name], + labels=labels[head.name], + features=features, + mode=mode) + training_losses.append(training_loss) + + training_losses = tuple(training_losses) + with ops.name_scope( + 'merge_losses', + values=training_losses + (self._head_weights or tuple())): + if self._head_weights: + head_weighted_training_losses = [] + for training_loss, head_weight in zip(training_losses, + self._head_weights): + head_weighted_training_losses.append( + tf.math.multiply(training_loss, head_weight)) + training_losses = head_weighted_training_losses + merged_training_loss = tf.math.add_n(training_losses) + regularization_loss = tf.math.add_n( + regularization_losses) if regularization_losses is not None else None + regularized_training_loss = ( + merged_training_loss + regularization_loss + if regularization_loss is not None else merged_training_loss) + return regularized_training_loss + + def predictions(self, logits, keys=None): + """Create predictions. See `base_head.Head` for details.""" + logits_dict = self._check_logits_and_labels(logits) + predictions = {} + with ops.name_scope('merge_pred'): + for head in self._heads: + head_preds = head.predictions(logits=logits_dict[head.name]) + for k, v in six.iteritems(head_preds): + predictions[(head.name, k)] = v + return predictions + + def metrics(self, regularization_losses=None): + """Creates metrics. See `base_head.Head` for details.""" + eval_metrics = {} + keys = metric_keys.MetricKeys + # Add regularization loss metric for multi_head. + if regularization_losses is not None: + eval_metrics[self._loss_regularization_key] = tf.keras.metrics.Mean( + name=keys.LOSS_REGULARIZATION) + with ops.name_scope('merge_eval'): + # Loss metric is not added by default in each head. + for loss_key in self._loss_keys: + eval_metrics[loss_key] = tf.keras.metrics.Mean(name=loss_key) + return eval_metrics + + def update_metrics(self, + eval_metrics, + features, + logits, + labels, + regularization_losses=None): + """Updates eval metrics. See `base_head.Head` for details.""" + logits_dict = self._check_logits_and_labels(logits, labels) + # Update regularization loss metric + if regularization_losses is not None: + regularization_loss = tf.math.add_n(regularization_losses) + eval_metrics[self._loss_regularization_key].update_state( + values=regularization_loss) + # Update metrics for each head + for i, head in enumerate(self._heads): + head_logits = logits_dict[head.name] + head_labels = labels[head.name] + # Update loss metrics + training_loss = head.loss( + logits=head_logits, labels=head_labels, features=features) + eval_metrics[self._loss_keys[i]].update_state(values=training_loss) + # Update existing metrics in each head + head_metrics = head.metrics() + updated_metrics = head.update_metrics(head_metrics, features, head_logits, + head_labels) + eval_metrics.update(updated_metrics or {}) + return eval_metrics + + def create_estimator_spec(self, + features, + mode, + logits, + labels=None, + optimizer=None, + trainable_variables=None, + train_op_fn=None, + update_ops=None, + regularization_losses=None): + """Returns a `model_fn.EstimatorSpec`. + + Args: + features: Input `dict` of `Tensor` or `SparseTensor` objects. + mode: Estimator's `ModeKeys`. + logits: Input `dict` keyed by head name, or logits `Tensor` with shape + `[D0, D1, ... DN, logits_dimension]`. For many applications, the + `Tensor` shape is `[batch_size, logits_dimension]`. If logits is a + `Tensor`, it will split the `Tensor` along the last dimension and + distribute it appropriately among the heads. Check `MultiHead` for + examples. + labels: Input `dict` keyed by head name. For each head, the label value + can be integer or string `Tensor` with shape matching its corresponding + `logits`.`labels` is a required argument when `mode` equals `TRAIN` or + `EVAL`. + optimizer: An `tf.keras.optimizers.Optimizer` instance to optimize the + loss in TRAIN mode. Namely, sets `train_op = optimizer.get_updates(loss, + trainable_variables)`, which updates variables to minimize `loss`. + trainable_variables: A list or tuple of `Variable` objects to update to + minimize `loss`. In Tensorflow 1.x, by default these are the list of + variables collected in the graph under the key + `GraphKeys.TRAINABLE_VARIABLES`. As Tensorflow 2.x doesn't have + collections and GraphKeys, trainable_variables need to be passed + explicitly here. + train_op_fn: Function that takes a scalar loss `Tensor` and returns + `train_op`. Used if `optimizer` is `None`. + update_ops: A list or tuple of update ops to be run at training time. For + example, layers such as BatchNormalization create mean and variance + update ops that need to be run at training time. In Tensorflow 1.x, + these are thrown into an UPDATE_OPS collection. As Tensorflow 2.x + doesn't have collections, update_ops need to be passed explicitly here. + regularization_losses: A list of additional scalar losses to be added to + the training loss, such as regularization losses. These losses are + usually expressed as a batch average, so for best results, in each head, + users need to use the default `loss_reduction=SUM_OVER_BATCH_SIZE` to + avoid scaling errors. Compared to the regularization losses for each + head, this loss is to regularize the merged loss of all heads in multi + head, and will be added to the overall training loss of multi head. + + Returns: + A `model_fn.EstimatorSpec` instance. + + Raises: + ValueError: If both `train_op_fn` and `optimizer` are `None` in TRAIN + mode, or if both are set. + If `mode` is not in Estimator's `ModeKeys`. + """ + with ops.name_scope(self.name, 'multi_head'): + logits_dict = self._check_logits_and_labels(logits, labels) + # Get all estimator spec. + all_estimator_spec = [] + for head in self._heads: + all_estimator_spec.append( + head.create_estimator_spec( + features=features, + mode=mode, + logits=logits_dict[head.name], + labels=labels[head.name] if labels else None, + train_op_fn=_no_op_train_fn)) + # Predict. + predictions = self.predictions(logits) + if mode == ModeKeys.PREDICT: + export_outputs = self._merge_predict_export_outputs(all_estimator_spec) + return model_fn.EstimatorSpec( + mode=ModeKeys.PREDICT, + predictions=predictions, + export_outputs=export_outputs) + loss = self.loss(labels, logits, features, mode, regularization_losses) + # Eval. + if mode == ModeKeys.EVAL: + eval_metrics = self.metrics(regularization_losses=regularization_losses) + updated_metrics = self.update_metrics( + eval_metrics, + features, + logits, + labels, + regularization_losses=regularization_losses) + return model_fn.EstimatorSpec( + mode=ModeKeys.EVAL, + predictions=predictions, + loss=loss, + eval_metric_ops=updated_metrics) + # Train. + if mode == ModeKeys.TRAIN: + train_op = base_head.create_estimator_spec_train_op( + head_name=self.name, + optimizer=optimizer, + train_op_fn=train_op_fn, + update_ops=update_ops, + trainable_variables=trainable_variables, + regularized_training_loss=loss, + loss_reduction=self.loss_reduction) + # Create summary. + base_head.create_estimator_spec_summary(loss, regularization_losses) + # eval_metrics. + eval_metrics = {} + for spec in all_estimator_spec: + eval_metrics.update(spec.eval_metric_ops or {}) + # predictions can be used to access the logits in `TRAIN` mode + return model_fn.EstimatorSpec( + mode=ModeKeys.TRAIN, + loss=loss, + train_op=train_op, + predictions=predictions, + eval_metric_ops=eval_metrics) + raise ValueError('mode={} unrecognized'.format(mode)) + + def _merge_predict_export_outputs(self, all_estimator_spec): + """Merges list of `EstimatorSpec` export_outputs for PREDICT. + + For each individual head, its DEFAULT_SERVING_KEY and PREDICT_SERVING_KEY + are extracted and merged for `export_outputs` in PREDICT mode of + `EstimatorSpec`. By default, the first head is served. + + Args: + all_estimator_spec: list of `EstimatorSpec` for the individual heads. + + Returns: + A dict of merged export_outputs from all heads for PREDICT. + """ + # The first head is used for serving by default. + export_outputs = { + base_head.DEFAULT_SERVING_KEY: + _default_export_output(all_estimator_spec[0].export_outputs, + self._heads[0].name), + } + merged_predict_outputs = {} + for head, spec in zip(self._heads, all_estimator_spec): + for k, v in six.iteritems(spec.export_outputs): + # Collect default serving key for export_outputs + key = ( + head.name if k == base_head.DEFAULT_SERVING_KEY else '{}/{}'.format( + head.name, k)) + export_outputs[key] = v + # Collect predict serving key for merged_predict_outputs + if (k == base_head.PREDICT_SERVING_KEY and + isinstance(v, export_output.PredictOutput)): + for kp, vp in six.iteritems(v.outputs): + merged_predict_outputs['{}/{}'.format(head.name, kp)] = vp + export_outputs[base_head.PREDICT_SERVING_KEY] = ( + export_output.PredictOutput(merged_predict_outputs)) + return export_outputs diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/head/multi_label_head.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/head/multi_label_head.py new file mode 100644 index 0000000000000000000000000000000000000000..1cd1326635ecf6515ee234d4334ae2ef5b32c741 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/head/multi_label_head.py @@ -0,0 +1,593 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Multi label head.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import six +import tensorflow as tf +from tensorflow.python.framework import ops +from tensorflow.python.ops import lookup_ops +from tensorflow_estimator.python.estimator import model_fn +from tensorflow_estimator.python.estimator.canned import metric_keys +from tensorflow_estimator.python.estimator.canned import prediction_keys +from tensorflow_estimator.python.estimator.estimator_export import estimator_export +from tensorflow_estimator.python.estimator.export import export_output +from tensorflow_estimator.python.estimator.head import base_head +from tensorflow_estimator.python.estimator.mode_keys import ModeKeys + + +@estimator_export('estimator.MultiLabelHead') +class MultiLabelHead(base_head.Head): + """Creates a `Head` for multi-label classification. + + Multi-label classification handles the case where each example may have zero + or more associated labels, from a discrete set. This is distinct from + `MultiClassHead` which has exactly one label per example. + + Uses `sigmoid_cross_entropy` loss average over classes and weighted sum over + the batch. Namely, if the input logits have shape `[batch_size, n_classes]`, + the loss is the average over `n_classes` and the weighted sum over + `batch_size`. + + The head expects `logits` with shape `[D0, D1, ... DN, n_classes]`. In many + applications, the shape is `[batch_size, n_classes]`. + + Labels can be: + + * A multi-hot tensor of shape `[D0, D1, ... DN, n_classes]` + * An integer `SparseTensor` of class indices. The `dense_shape` must be + `[D0, D1, ... DN, ?]` and the values within `[0, n_classes)`. + * If `label_vocabulary` is given, a string `SparseTensor`. The `dense_shape` + must be `[D0, D1, ... DN, ?]` and the values within `label_vocabulary` or a + multi-hot tensor of shape `[D0, D1, ... DN, n_classes]`. + + If `weight_column` is specified, weights must be of shape + `[D0, D1, ... DN]`, or `[D0, D1, ... DN, 1]`. + + Also supports custom `loss_fn`. `loss_fn` takes `(labels, logits)` or + `(labels, logits, features)` as arguments and returns unreduced loss with + shape `[D0, D1, ... DN, 1]`. `loss_fn` must support indicator `labels` with + shape `[D0, D1, ... DN, n_classes]`. Namely, the head applies + `label_vocabulary` to the input labels before passing them to `loss_fn`. + + Usage: + + >>> n_classes = 2 + >>> head = tf.estimator.MultiLabelHead(n_classes) + >>> logits = np.array([[-1., 1.], [-1.5, 1.5]], dtype=np.float32) + >>> labels = np.array([[1, 0], [1, 1]], dtype=np.int64) + >>> features = {'x': np.array([[41], [42]], dtype=np.int32)} + >>> # expected_loss = sum(_sigmoid_cross_entropy(labels, logits)) / batch_size + >>> # = sum(1.31326169, 0.9514133) / 2 = 1.13 + >>> loss = head.loss(labels, logits, features=features) + >>> print('{:.2f}'.format(loss.numpy())) + 1.13 + >>> eval_metrics = head.metrics() + >>> updated_metrics = head.update_metrics( + ... eval_metrics, features, logits, labels) + >>> for k in sorted(updated_metrics): + ... print('{} : {:.2f}'.format(k, updated_metrics[k].result().numpy())) + auc : 0.33 + auc_precision_recall : 0.77 + average_loss : 1.13 + >>> preds = head.predictions(logits) + >>> print(preds['logits']) + tf.Tensor( + [[-1. 1. ] + [-1.5 1.5]], shape=(2, 2), dtype=float32) + + Usage with a canned estimator: + + ```python + my_head = tf.estimator.MultiLabelHead(n_classes=3) + my_estimator = tf.estimator.DNNEstimator( + head=my_head, + hidden_units=..., + feature_columns=...) + ``` + + It can also be used with a custom `model_fn`. Example: + + ```python + def _my_model_fn(features, labels, mode): + my_head = tf.estimator.MultiLabelHead(n_classes=3) + logits = tf.keras.Model(...)(features) + + return my_head.create_estimator_spec( + features=features, + mode=mode, + labels=labels, + optimizer=tf.keras.optimizers.Adagrad(lr=0.1), + logits=logits) + + my_estimator = tf.estimator.Estimator(model_fn=_my_model_fn) + ``` + + Args: + n_classes: Number of classes, must be greater than 1 (for 1 class, use + `BinaryClassHead`). + weight_column: A string or a `NumericColumn` created by + `tf.feature_column.numeric_column` defining feature column representing + weights. It is used to down weight or boost examples during training. It + will be multiplied by the loss of the example. Per-class weighting is not + supported. + thresholds: Iterable of floats in the range `(0, 1)`. Accuracy, precision + and recall metrics are evaluated for each threshold value. The threshold + is applied to the predicted probabilities, i.e. above the threshold is + `true`, below is `false`. + label_vocabulary: A list of strings represents possible label values. If it + is not given, that means labels are already encoded as integer within [0, + n_classes) or multi-hot Tensor. If given, labels must be SparseTensor + `string` type and have any value in `label_vocabulary`. Also there will be + errors if vocabulary is not provided and labels are string. + loss_reduction: One of `tf.losses.Reduction` except `NONE`. Decides how to + reduce training loss over batch. Defaults to `SUM_OVER_BATCH_SIZE`, namely + weighted sum of losses divided by batch size. + loss_fn: Optional loss function. + classes_for_class_based_metrics: List of integer class IDs or string class + names for which per-class metrics are evaluated. If integers, all must be + in the range `[0, n_classes - 1]`. If strings, all must be in + `label_vocabulary`. + name: Name of the head. If provided, summary and metrics keys will be + suffixed by `"/" + name`. Also used as `name_scope` when creating ops. + """ + + def __init__(self, + n_classes, + weight_column=None, + thresholds=None, + label_vocabulary=None, + loss_reduction=tf.losses.Reduction.SUM_OVER_BATCH_SIZE, + loss_fn=None, + classes_for_class_based_metrics=None, + name=None): + if n_classes is None or n_classes < 2: + raise ValueError('n_classes must be > 1 for multi-label classification. ' + 'Given: {}'.format(n_classes)) + thresholds = tuple(thresholds) if thresholds else tuple() + for threshold in thresholds: + if (threshold <= 0.0) or (threshold >= 1.0): + raise ValueError( + 'thresholds must be in (0, 1) range. Given: {}'.format(threshold)) + if label_vocabulary is not None: + if not isinstance(label_vocabulary, (list, tuple)): + raise ValueError('label_vocabulary must be a list or tuple. ' + 'Given type: {}'.format(type(label_vocabulary))) + if len(label_vocabulary) != n_classes: + raise ValueError('Length of label_vocabulary must be n_classes ({}). ' + 'Given: {}'.format(n_classes, len(label_vocabulary))) + + if loss_fn: + base_head.validate_loss_fn_args(loss_fn) + base_head.validate_loss_reduction(loss_reduction) + if classes_for_class_based_metrics: + classes_for_class_based_metrics = tuple(classes_for_class_based_metrics) + if isinstance(classes_for_class_based_metrics[0], six.string_types): + if not label_vocabulary: + raise ValueError('label_vocabulary must be provided when ' + 'classes_for_class_based_metrics are strings.') + class_ids = [] + for class_string in classes_for_class_based_metrics: + class_ids.append(label_vocabulary.index(class_string)) + classes_for_class_based_metrics = tuple(class_ids) + else: + for class_id in classes_for_class_based_metrics: + if (class_id < 0) or (class_id >= n_classes): + raise ValueError( + 'All classes_for_class_based_metrics must be in range [0, {}]. ' + 'Given: {}'.format(n_classes - 1, class_id)) + else: + classes_for_class_based_metrics = tuple() + self._n_classes = n_classes + self._weight_column = weight_column + self._thresholds = thresholds + self._label_vocabulary = label_vocabulary + self._loss_reduction = loss_reduction + self._loss_fn = loss_fn + self._classes_for_class_based_metrics = classes_for_class_based_metrics + self._name = name + # Metric keys. + keys = metric_keys.MetricKeys + self._loss_mean_key = self._summary_key(keys.LOSS_MEAN) + self._auc_key = self._summary_key(keys.AUC) + self._auc_pr_key = self._summary_key(keys.AUC_PR) + self._loss_regularization_key = self._summary_key(keys.LOSS_REGULARIZATION) + accuracy_keys = [] + precision_keys = [] + recall_keys = [] + for threshold in self._thresholds: + accuracy_keys.append( + self._summary_key(keys.ACCURACY_AT_THRESHOLD % threshold)) + precision_keys.append( + self._summary_key(keys.PRECISION_AT_THRESHOLD % threshold)) + recall_keys.append( + self._summary_key(keys.RECALL_AT_THRESHOLD % threshold)) + self._accuracy_keys = tuple(accuracy_keys) + self._precision_keys = tuple(precision_keys) + self._recall_keys = tuple(recall_keys) + prob_keys = [] + auc_keys = [] + auc_pr_keys = [] + for class_id in self._classes_for_class_based_metrics: + if self._label_vocabulary is None: + prob_key = keys.PROBABILITY_MEAN_AT_CLASS % class_id + auc_key = keys.AUC_AT_CLASS % class_id + auc_pr_key = keys.AUC_PR_AT_CLASS % class_id + else: + prob_key = ( + keys.PROBABILITY_MEAN_AT_NAME % self._label_vocabulary[class_id]) + auc_key = keys.AUC_AT_NAME % self._label_vocabulary[class_id] + auc_pr_key = keys.AUC_PR_AT_NAME % self._label_vocabulary[class_id] + prob_keys.append(self._summary_key(prob_key)) + auc_keys.append(self._summary_key(auc_key)) + auc_pr_keys.append(self._summary_key(auc_pr_key)) + self._prob_keys = tuple(prob_keys) + self._auc_keys = tuple(auc_keys) + self._auc_pr_keys = tuple(auc_pr_keys) + + @property + def name(self): + """See `base_head.Head` for details.""" + return self._name + + @property + def logits_dimension(self): + """See `base_head.Head` for details.""" + return self._n_classes + + @property + def loss_reduction(self): + """See `base_head.Head` for details.""" + return self._loss_reduction + + # An attribute for lookup table. Note that for Graph execution, the lookup + # table is created on demand to make sure the lookup table is in the same + # graph as its input tensors for `train` and `eval` of Estimator (as Estimator + # re-creates graphs for `train`, `eval` and `predict`). + _cached_class_id_table = None + + @property + def _class_id_table(self): + """Creates a lookup table for class_id. + + In eager execution, this lookup table will be lazily created on the first + call of `self._class_id_table`, and cached for later use; In graph + execution, it will be created on demand. + + Returns: + A hash table for lookup. + """ + if self._cached_class_id_table is None or not tf.executing_eagerly(): + self._cached_class_id_table = lookup_ops.index_table_from_tensor( + vocabulary_list=tuple(self._label_vocabulary), name='class_id_lookup') + return self._cached_class_id_table + + def _processed_labels(self, logits, labels): + """Converts labels to integer id space.""" + if labels is None: + raise ValueError(base_head._LABEL_NONE_ERR_MSG) # pylint:disable=protected-access + if isinstance(labels, tf.sparse.SparseTensor): + label_values = labels.values + if labels.dtype == tf.dtypes.string: + label_ids_values = self._class_id_table.lookup(label_values) + label_ids = tf.sparse.SparseTensor( + indices=labels.indices, + values=label_ids_values, + dense_shape=labels.dense_shape) + processed_labels = tf.sparse.to_indicator(label_ids, self._n_classes) + else: + if not label_values.dtype.is_integer: + raise ValueError( + 'Labels dtype should be integer. Instead got {}.'.format( + label_values.dtype)) + err_msg = (r'labels must be an integer SparseTensor with values in ' + r'[0, {})'.format(self._n_classes)) + label_values = base_head.check_label_range( + labels.values, self._n_classes, message=err_msg) + if tf.executing_eagerly(): + processed_labels = tf.sparse.to_indicator(labels, self._n_classes) + else: + with tf.control_dependencies([label_values]): + processed_labels = tf.sparse.to_indicator(labels, self._n_classes) + processed_labels = tf.cast(processed_labels, dtype=tf.dtypes.int64) + else: + err_msg = ( + r'labels must be an integer indicator Tensor with values in [0, 1]') + processed_labels = base_head.check_label_range(labels, 2, message=err_msg) + + return base_head.check_dense_labels_match_logits_and_reshape( + labels=processed_labels, + logits=logits, + expected_labels_dimension=self.logits_dimension) + + def _unweighted_loss_and_weights(self, logits, processed_labels, features): + """Computes loss spec.""" + if self._loss_fn: + unweighted_loss = base_head.call_loss_fn( + loss_fn=self._loss_fn, + labels=processed_labels, + logits=logits, + features=features, + expected_loss_dim=1) + else: + unweighted_loss = tf.compat.v1.losses.sigmoid_cross_entropy( + multi_class_labels=processed_labels, + logits=logits, + reduction=tf.compat.v1.losses.Reduction.NONE) + # Averages loss over classes. + unweighted_loss = tf.math.reduce_mean( + unweighted_loss, axis=-1, keepdims=True) + weights = base_head.get_weights_and_check_match_logits( + features=features, weight_column=self._weight_column, logits=logits) + return unweighted_loss, weights + + def loss(self, + labels, + logits, + features=None, + mode=None, + regularization_losses=None): + """Returns regularized training loss. See `base_head.Head` for details.""" + del mode # Unused for this head. + with ops.name_scope( + 'losses', values=(logits, labels, regularization_losses, features)): + logits = base_head.check_logits_final_dim(logits, self.logits_dimension) + processed_labels = self._processed_labels(logits, labels) + unweighted_loss, weights = self._unweighted_loss_and_weights( + logits, processed_labels, features) + training_loss = tf.compat.v2.keras.__internal__.losses.compute_weighted_loss( + unweighted_loss, + sample_weight=weights, + reduction=self._loss_reduction) + regularization_loss = tf.math.add_n( + regularization_losses) if regularization_losses is not None else None + regularized_training_loss = ( + training_loss + regularization_loss + if regularization_loss is not None else training_loss) + return regularized_training_loss + + def predictions(self, logits, keys=None): + """Return predictions based on keys. + + See `base_head.Head` for details. + + Args: + logits: logits `Tensor` with shape `[D0, D1, ... DN, logits_dimension]`. + For many applications, the shape is `[batch_size, logits_dimension]`. + keys: a list of prediction keys. Key can be either the class variable + of prediction_keys.PredictionKeys or its string value, such as: + prediction_keys.PredictionKeys.LOGITS or 'logits'. + + Returns: + A dict of predictions. + """ + pred_keys = prediction_keys.PredictionKeys + valid_keys = [pred_keys.LOGITS, pred_keys.PROBABILITIES, pred_keys.CLASSES] + if keys: + base_head.check_prediction_keys(keys, valid_keys) + else: + keys = valid_keys + logits = base_head.check_logits_final_dim(logits, self.logits_dimension) + predictions = {} + with ops.name_scope('predictions', values=(logits,)): + if pred_keys.LOGITS in keys: + predictions[pred_keys.LOGITS] = logits + if pred_keys.PROBABILITIES in keys: + probabilities = tf.math.sigmoid(logits, name=pred_keys.PROBABILITIES) + predictions[pred_keys.PROBABILITIES] = probabilities + if pred_keys.CLASSES in keys: + predictions[pred_keys.CLASSES] = base_head.all_classes( + logits, self._n_classes, self._label_vocabulary) + + return predictions + + def metrics(self, regularization_losses=None): + """Creates metrics. See `base_head.Head` for details.""" + keys = metric_keys.MetricKeys + with ops.name_scope(None, 'metrics', (regularization_losses,)): + # Mean metric. + eval_metrics = {} + eval_metrics[self._loss_mean_key] = tf.keras.metrics.Mean( + name=keys.LOSS_MEAN) + # The default summation_method is "interpolation" in the AUC metric. + eval_metrics[self._auc_key] = tf.keras.metrics.AUC(name=keys.AUC) + eval_metrics[self._auc_pr_key] = tf.keras.metrics.AUC( + curve='PR', name=keys.AUC_PR) + if regularization_losses is not None: + eval_metrics[self._loss_regularization_key] = tf.keras.metrics.Mean( + name=keys.LOSS_REGULARIZATION) + for i, threshold in enumerate(self._thresholds): + eval_metrics[self._accuracy_keys[i]] = tf.keras.metrics.BinaryAccuracy( + name=self._accuracy_keys[i], threshold=threshold) + eval_metrics[self._precision_keys[i]] = ( + tf.keras.metrics.Precision( + name=self._precision_keys[i], thresholds=threshold)) + eval_metrics[self._recall_keys[i]] = tf.keras.metrics.Recall( + name=self._recall_keys[i], thresholds=threshold) + for i in range(len(self._classes_for_class_based_metrics)): + eval_metrics[self._prob_keys[i]] = tf.keras.metrics.Mean( + name=self._prob_keys[i]) + eval_metrics[self._auc_keys[i]] = tf.keras.metrics.AUC( + name=self._auc_keys[i]) + eval_metrics[self._auc_pr_keys[i]] = tf.keras.metrics.AUC( + curve='PR', name=self._auc_pr_keys[i]) + return eval_metrics + + def update_metrics(self, + eval_metrics, + features, + logits, + labels, + regularization_losses=None): + """Updates eval metrics. See `base_head.Head` for details.""" + logits = base_head.check_logits_final_dim(logits, self.logits_dimension) + processed_labels = self._processed_labels(logits, labels) + unweighted_loss, weights = self._unweighted_loss_and_weights( + logits, processed_labels, features) + prob_key = prediction_keys.PredictionKeys.PROBABILITIES + predictions = self.predictions(logits, [prob_key]) + probabilities = predictions[prob_key] + + # Update metrics. + eval_metrics[self._loss_mean_key].update_state( + values=unweighted_loss, sample_weight=weights) + eval_metrics[self._auc_key].update_state( + y_true=processed_labels, y_pred=probabilities, sample_weight=weights) + eval_metrics[self._auc_pr_key].update_state( + y_true=processed_labels, y_pred=probabilities, sample_weight=weights) + if regularization_losses is not None: + regularization_loss = tf.math.add_n(regularization_losses) + eval_metrics[self._loss_regularization_key].update_state( + values=regularization_loss) + for i in range(len(self._thresholds)): + eval_metrics[self._accuracy_keys[i]].update_state( + y_true=processed_labels, y_pred=probabilities, sample_weight=weights) + eval_metrics[self._precision_keys[i]].update_state( + y_true=processed_labels, y_pred=probabilities, sample_weight=weights) + eval_metrics[self._recall_keys[i]].update_state( + y_true=processed_labels, y_pred=probabilities, sample_weight=weights) + for i, class_id in enumerate(self._classes_for_class_based_metrics): + batch_rank = tf.rank(probabilities) - 1 + begin = tf.concat( + [tf.zeros([batch_rank], dtype=tf.dtypes.int32), [class_id]], axis=0) + size = tf.concat([-1 * tf.ones([batch_rank], dtype=tf.dtypes.int32), [1]], + axis=0) + class_probabilities = tf.slice(probabilities, begin=begin, size=size) + class_labels = tf.slice(processed_labels, begin=begin, size=size) + base_head.update_metric_with_broadcast_weights( + eval_metrics[self._prob_keys[i]], class_probabilities, weights) + eval_metrics[self._auc_keys[i]].update_state( + y_true=class_labels, + y_pred=class_probabilities, + sample_weight=weights) + eval_metrics[self._auc_pr_keys[i]].update_state( + y_true=class_labels, + y_pred=class_probabilities, + sample_weight=weights) + return eval_metrics + + def _create_tpu_estimator_spec(self, + features, + mode, + logits, + labels=None, + optimizer=None, + trainable_variables=None, + train_op_fn=None, + update_ops=None, + regularization_losses=None): + """Returns an `model_fn._TPUEstimatorSpec`. + + Args: + features: Input `dict` of `Tensor` or `SparseTensor` objects. + mode: Estimator's `ModeKeys`. + logits: logits `Tensor` with shape `[D0, D1, ... DN, n_classes]`. For many + applications, the shape is `[batch_size, n_classes]`. + labels: Labels with shape matching `logits`. Can be multi-hot `Tensor` + with shape `[D0, D1, ... DN, n_classes]` or `SparseTensor` with + `dense_shape` `[D0, D1, ... DN, ?]`. `labels` is required argument when + `mode` equals `TRAIN` or `EVAL`. + optimizer: An `tf.keras.optimizers.Optimizer` instance to optimize the + loss in TRAIN mode. Namely, sets `train_op = optimizer.get_updates(loss, + trainable_variables)`, which updates variables to minimize + `loss`.able_variables)`, which updates variables to minimize `loss`. + trainable_variables: A list or tuple of `Variable` objects to update to + minimize `loss`. In Tensorflow 1.x, by default these are the list of + variables collected in the graph under the key + `GraphKeys.TRAINABLE_VARIABLES`. As Tensorflow 2.x doesn't have + collections and GraphKeys, trainable_variables need to be passed + explicitly here. + train_op_fn: Function that takes a scalar loss `Tensor` and returns + `train_op`. Used if `optimizer` is `None`. + update_ops: A list or tuple of update ops to be run at training time. For + example, layers such as BatchNormalization create mean and variance + update ops that need to be run at training time. In Tensorflow 1.x, + these are thrown into an UPDATE_OPS collection. As Tensorflow 2.x + doesn't have collections, update_ops need to be passed explicitly here. + regularization_losses: A list of additional scalar losses to be added to + the training loss, such as regularization losses. These losses are + usually expressed as a batch average, so for best results users need to + set `loss_reduction=SUM_OVER_BATCH_SIZE` when creating the head to avoid + scaling errors. + + Returns: + `model_fn._TPUEstimatorSpec`. + Raises: + ValueError: If both `train_op_fn` and `optimizer` are `None` in TRAIN + mode, or if both are set. + """ + with ops.name_scope(self._name, 'head'): + # Predict. + pred_keys = prediction_keys.PredictionKeys + predictions = self.predictions(logits) + if mode == ModeKeys.PREDICT: + probabilities = predictions[pred_keys.PROBABILITIES] + classifier_output = base_head.classification_output( + scores=probabilities, + n_classes=self._n_classes, + label_vocabulary=self._label_vocabulary) + return model_fn._TPUEstimatorSpec( # pylint:disable=protected-access + mode=ModeKeys.PREDICT, + predictions=predictions, + export_outputs={ + base_head.DEFAULT_SERVING_KEY: classifier_output, + base_head.CLASSIFY_SERVING_KEY: classifier_output, + base_head.PREDICT_SERVING_KEY: ( + export_output.PredictOutput(predictions)) + }) + + regularized_training_loss = self.loss( + logits=logits, + labels=labels, + features=features, + mode=mode, + regularization_losses=regularization_losses) + # Eval. + if mode == ModeKeys.EVAL: + eval_metrics = self.metrics(regularization_losses=regularization_losses) + return model_fn._TPUEstimatorSpec( # pylint:disable=protected-access + mode=ModeKeys.EVAL, + predictions=predictions, + loss=regularized_training_loss, + eval_metrics=base_head.create_eval_metrics_tuple( + self.update_metrics, { + 'eval_metrics': eval_metrics, + 'features': features, + 'logits': logits, + 'labels': labels, + 'regularization_losses': regularization_losses + })) + # Train. + train_op = base_head.create_estimator_spec_train_op( + head_name=self._name, + optimizer=optimizer, + train_op_fn=train_op_fn, + update_ops=update_ops, + trainable_variables=trainable_variables, + regularized_training_loss=regularized_training_loss, + loss_reduction=self._loss_reduction) + # Create summary. + base_head.create_estimator_spec_summary( + regularized_training_loss=regularized_training_loss, + regularization_losses=regularization_losses, + summary_key_fn=self._summary_key) + return model_fn._TPUEstimatorSpec( # pylint: disable=protected-access + mode=ModeKeys.TRAIN, + predictions=predictions, + loss=regularized_training_loss, + train_op=train_op) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/head/regression_head.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/head/regression_head.py new file mode 100644 index 0000000000000000000000000000000000000000..25818932aa9c46e423c050d4c6359e9d0187f93b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/head/regression_head.py @@ -0,0 +1,583 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Regression head.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import tensorflow as tf + +from tensorflow.python.framework import ops +from tensorflow_estimator.python.estimator import model_fn +from tensorflow_estimator.python.estimator.canned import metric_keys +from tensorflow_estimator.python.estimator.canned import prediction_keys +from tensorflow_estimator.python.estimator.estimator_export import estimator_export +from tensorflow_estimator.python.estimator.export import export_output +from tensorflow_estimator.python.estimator.head import base_head +from tensorflow_estimator.python.estimator.mode_keys import ModeKeys + + +@estimator_export('estimator.RegressionHead') +class RegressionHead(base_head.Head): + """Creates a `Head` for regression using the `mean_squared_error` loss. + + The loss is the weighted sum over all input dimensions. Namely, if the input + labels have shape `[batch_size, label_dimension]`, the loss is the weighted + sum over both `batch_size` and `label_dimension`. + + The head expects `logits` with shape `[D0, D1, ... DN, label_dimension]`. + In many applications, the shape is `[batch_size, label_dimension]`. + + The `labels` shape must match `logits`, namely + `[D0, D1, ... DN, label_dimension]`. If `label_dimension=1`, shape + `[D0, D1, ... DN]` is also supported. + + If `weight_column` is specified, weights must be of shape + `[D0, D1, ... DN]`, `[D0, D1, ... DN, 1]` or + `[D0, D1, ... DN, label_dimension]`. + + Supports custom `loss_fn`. `loss_fn` takes `(labels, logits)` or + `(labels, logits, features, loss_reduction)` as arguments and returns + unreduced loss with shape `[D0, D1, ... DN, label_dimension]`. + + Also supports custom `inverse_link_fn`, also known as 'mean function'. + `inverse_link_fn` is only used in `PREDICT` mode. It takes `logits` as + argument and returns predicted values. This function is the inverse of the + link function defined in + https://en.wikipedia.org/wiki/Generalized_linear_model#Link_function + Namely, for poisson regression, set `inverse_link_fn=tf.exp`. + + Usage: + + >>> head = tf.estimator.RegressionHead() + >>> logits = np.array(((45,), (41,),), dtype=np.float32) + >>> labels = np.array(((43,), (44,),), dtype=np.int32) + >>> features = {'x': np.array(((42,),), dtype=np.float32)} + >>> # expected_loss = weighted_loss / batch_size + >>> # = (43-45)^2 + (44-41)^2 / 2 = 6.50 + >>> loss = head.loss(labels, logits, features=features) + >>> print('{:.2f}'.format(loss.numpy())) + 6.50 + >>> eval_metrics = head.metrics() + >>> updated_metrics = head.update_metrics( + ... eval_metrics, features, logits, labels) + >>> for k in sorted(updated_metrics): + ... print('{} : {:.2f}'.format(k, updated_metrics[k].result().numpy())) + average_loss : 6.50 + label/mean : 43.50 + prediction/mean : 43.00 + >>> preds = head.predictions(logits) + >>> print(preds['predictions']) + tf.Tensor( + [[45.] + [41.]], shape=(2, 1), dtype=float32) + + Usage with a canned estimator: + + ```python + my_head = tf.estimator.RegressionHead() + my_estimator = tf.estimator.DNNEstimator( + head=my_head, + hidden_units=..., + feature_columns=...) + ``` + + It can also be used with a custom `model_fn`. Example: + + ```python + def _my_model_fn(features, labels, mode): + my_head = tf.estimator.RegressionHead() + logits = tf.keras.Model(...)(features) + + return my_head.create_estimator_spec( + features=features, + mode=mode, + labels=labels, + optimizer=tf.keras.optimizers.Adagrad(lr=0.1), + logits=logits) + + my_estimator = tf.estimator.Estimator(model_fn=_my_model_fn) + ``` + + Args: + weight_column: A string or a `NumericColumn` created by + `tf.feature_column.numeric_column` defining feature column representing + weights. It is used to down weight or boost examples during training. It + will be multiplied by the loss of the example. + label_dimension: Number of regression labels per example. This is the size + of the last dimension of the labels `Tensor` (typically, this has shape + `[batch_size, label_dimension]`). + loss_reduction: One of `tf.losses.Reduction` except `NONE`. Decides how to + reduce training loss over batch and label dimension. Defaults to + `SUM_OVER_BATCH_SIZE`, namely weighted sum of losses divided by + `batch_size * label_dimension`. + loss_fn: Optional loss function. Defaults to `mean_squared_error`. + inverse_link_fn: Optional inverse link function, also known as 'mean + function'. Defaults to identity. + name: name of the head. If provided, summary and metrics keys will be + suffixed by `"/" + name`. Also used as `name_scope` when creating ops. + """ + + def __init__(self, + label_dimension=1, + weight_column=None, + loss_reduction=tf.losses.Reduction.SUM_OVER_BATCH_SIZE, + loss_fn=None, + inverse_link_fn=None, + name=None): + if label_dimension < 1: + raise ValueError('Invalid label_dimension {}.'.format(label_dimension)) + base_head.validate_loss_reduction(loss_reduction) + if loss_fn: + base_head.validate_loss_fn_args(loss_fn) + self._logits_dimension = label_dimension + self._weight_column = weight_column + self._loss_reduction = loss_reduction + self._loss_fn = loss_fn + self._inverse_link_fn = inverse_link_fn + self._name = name + # Metric keys. + keys = metric_keys.MetricKeys + self._loss_mean_key = self._summary_key(keys.LOSS_MEAN) + self._prediction_mean_key = self._summary_key(keys.PREDICTION_MEAN) + self._label_mean_key = self._summary_key(keys.LABEL_MEAN) + self._loss_regularization_key = self._summary_key(keys.LOSS_REGULARIZATION) + + @property + def name(self): + """See `base_head.Head` for details.""" + return self._name + + @property + def logits_dimension(self): + """See `base_head.Head` for details.""" + return self._logits_dimension + + @property + def loss_reduction(self): + """See `base_head.Head` for details.""" + return self._loss_reduction + + def _processed_labels(self, logits, labels): + labels = base_head.check_dense_labels_match_logits_and_reshape( + labels=labels, + logits=logits, + expected_labels_dimension=self._logits_dimension) + labels = tf.cast(labels, dtype=tf.dtypes.float32) + return labels + + def _unweighted_loss_and_weights(self, logits, labels, features): + """Computes unweighted loss and weights.""" + if self._loss_fn: + unweighted_loss = base_head.call_loss_fn( + loss_fn=self._loss_fn, + labels=labels, + logits=logits, + features=features, + expected_loss_dim=self._logits_dimension) + else: + unweighted_loss = tf.compat.v1.losses.mean_squared_error( + labels=labels, + predictions=logits, + reduction=tf.compat.v1.losses.Reduction.NONE) + weights = base_head.get_weights_and_check_match_logits( + features=features, + weight_column=self._weight_column, + logits=logits, + allow_per_logit_weights=True) + return unweighted_loss, weights + + def loss(self, + labels, + logits, + features=None, + mode=None, + regularization_losses=None): + """Return predictions based on keys. See `base_head.Head` for details.""" + del mode # Unused for this head. + with ops.name_scope( + 'losses', values=(logits, labels, regularization_losses, features)): + logits = base_head.check_logits_final_dim(logits, self._logits_dimension) + labels = self._processed_labels(logits, labels) + unweighted_loss, weights = self._unweighted_loss_and_weights( + logits, labels, features) + training_loss = tf.compat.v2.keras.__internal__.losses.compute_weighted_loss( + unweighted_loss, + sample_weight=weights, + reduction=self._loss_reduction) + regularization_loss = tf.math.add_n( + regularization_losses) if regularization_losses is not None else None + regularized_training_loss = ( + training_loss + regularization_loss + if regularization_loss is not None else training_loss) + return regularized_training_loss + + def predictions(self, logits): + """Return predictions based on keys. + + See `base_head.Head` for details. + + Args: + logits: logits `Tensor` with shape `[D0, D1, ... DN, logits_dimension]`. + For many applications, the shape is `[batch_size, logits_dimension]`. + + Returns: + A dict of predictions. + """ + logits = base_head.check_logits_final_dim(logits, self._logits_dimension) + pred_keys = prediction_keys.PredictionKeys + with ops.name_scope('predictions', values=(logits,)): + if self._inverse_link_fn: + predicted_value = self._inverse_link_fn(logits) + predictions = { + pred_keys.PREDICTIONS: predicted_value, + pred_keys.LOGITS: logits, + } + else: + predicted_value = logits + predictions = {pred_keys.PREDICTIONS: predicted_value} + return predictions + + def metrics(self, regularization_losses=None): + """Creates metrics. See `base_head.Head` for details.""" + with ops.name_scope('metrics', values=(regularization_losses,)): + keys = metric_keys.MetricKeys + eval_metrics = {} + eval_metrics[self._loss_mean_key] = tf.keras.metrics.Mean( + name=keys.LOSS_MEAN) + eval_metrics[self._prediction_mean_key] = tf.keras.metrics.Mean( + name=keys.PREDICTION_MEAN) + eval_metrics[self._label_mean_key] = tf.keras.metrics.Mean( + name=keys.LABEL_MEAN) + + if regularization_losses is not None: + eval_metrics[self._loss_regularization_key] = tf.keras.metrics.Mean( + name=keys.LOSS_REGULARIZATION) + return eval_metrics + + def update_metrics(self, + eval_metrics, + features, + logits, + labels, + regularization_losses=None): + """Updates eval metrics. See `base_head.Head` for details.""" + # Compute predictions. + predictions = self.predictions(logits) + predicted_value = predictions[prediction_keys.PredictionKeys.PREDICTIONS] + logits = base_head.check_logits_final_dim(logits, self.logits_dimension) + label_ids = self._processed_labels(logits, labels) + unweighted_loss, weights = self._unweighted_loss_and_weights( + logits, label_ids, features) + + # Update metrics. + eval_metrics[self._loss_mean_key].update_state( + values=unweighted_loss, sample_weight=weights) + eval_metrics[self._label_mean_key].update_state( + values=labels, sample_weight=weights) + base_head.update_metric_with_broadcast_weights( + eval_metrics[self._prediction_mean_key], predicted_value, weights) + if regularization_losses is not None: + regularization_loss = tf.math.add_n(regularization_losses) + eval_metrics[self._loss_regularization_key].update_state( + values=regularization_loss) + return eval_metrics + + def _create_tpu_estimator_spec(self, + features, + mode, + logits, + labels=None, + optimizer=None, + trainable_variables=None, + train_op_fn=None, + update_ops=None, + regularization_losses=None): + """Returns an `EstimatorSpec`. + + Args: + features: Input `dict` mapping string feature names to `Tensor` or + `SparseTensor` objects containing the values for that feature in a + minibatch. Often to be used to fetch example-weight tensor. + mode: Estimator's `ModeKeys`. + logits: logits `Tensor` with shape `[D0, D1, ... DN, logits_dimension]`. + For many applications, the shape is `[batch_size, logits_dimension]`. + labels: Labels `Tensor` with shape matching `logits`, namely `[D0, D1, ... + DN, logits_dimension]`. When `logits_dimension=1`, shape `[D0, D1, ... + DN]` is also supported. `labels` is a required argument when `mode` + equals `TRAIN` or `EVAL`. + optimizer: An `tf.keras.optimizers.Optimizer` instance to optimize the + loss in TRAIN mode. Namely, sets `train_op = optimizer.get_updates(loss, + trainable_variables)`, which updates variables to minimize `loss`. + trainable_variables: A list or tuple of `Variable` objects to update to + minimize `loss`. In Tensorflow 1.x, by default these are the list of + variables collected in the graph under the key + `GraphKeys.TRAINABLE_VARIABLES`. As Tensorflow 2.x doesn't have + collections and GraphKeys, trainable_variables need to be passed + explicitly here. + train_op_fn: Function that takes a scalar loss `Tensor` and returns + `train_op`. Used if `optimizer` is `None`. + update_ops: A list or tuple of update ops to be run at training time. For + example, layers such as BatchNormalization create mean and variance + update ops that need to be run at training time. In Tensorflow 1.x, + these are thrown into an UPDATE_OPS collection. As Tensorflow 2.x + doesn't have collections, update_ops need to be passed explicitly here. + regularization_losses: A list of additional scalar losses to be added to + the training loss, such as regularization losses. These losses are + usually expressed as a batch average, so for best results users need to + set `loss_reduction=SUM_OVER_BATCH_SIZE` when creating the head to avoid + scaling errors. + + Returns: + A `model_fn._TPUEstimatorSpec` instance. + + Raises: + ValueError: If both `train_op_fn` and `optimizer` are `None` in TRAIN + mode, or if both are set. + """ + with ops.name_scope(self._name, 'head'): + # Predict. + predictions = self.predictions(logits) + if mode == ModeKeys.PREDICT: + keys = prediction_keys.PredictionKeys + regression_output = export_output.RegressionOutput( + value=predictions[keys.PREDICTIONS]) + return model_fn._TPUEstimatorSpec( # pylint: disable=protected-access + mode=ModeKeys.PREDICT, + predictions=predictions, + export_outputs={ + base_head.DEFAULT_SERVING_KEY: regression_output, + base_head.REGRESS_SERVING_KEY: regression_output, + base_head.PREDICT_SERVING_KEY: export_output.PredictOutput( + predictions) + }) + regularized_training_loss = self.loss( + logits=logits, + labels=labels, + features=features, + mode=mode, + regularization_losses=regularization_losses) + # Eval. + if mode == ModeKeys.EVAL: + eval_metrics = self.metrics(regularization_losses=regularization_losses) + return model_fn._TPUEstimatorSpec( # pylint: disable=protected-access + mode=ModeKeys.EVAL, + predictions=predictions, + loss=regularized_training_loss, + eval_metrics=base_head.create_eval_metrics_tuple( + self.update_metrics, { + 'eval_metrics': eval_metrics, + 'features': features, + 'logits': logits, + 'labels': labels, + 'regularization_losses': regularization_losses + })) + # Train. + train_op = base_head.create_estimator_spec_train_op( + head_name=self._name, + optimizer=optimizer, + train_op_fn=train_op_fn, + update_ops=update_ops, + trainable_variables=trainable_variables, + regularized_training_loss=regularized_training_loss, + loss_reduction=self._loss_reduction) + # Create summary. + base_head.create_estimator_spec_summary( + regularized_training_loss=regularized_training_loss, + regularization_losses=regularization_losses, + summary_key_fn=self._summary_key) + return model_fn._TPUEstimatorSpec( # pylint: disable=protected-access + mode=ModeKeys.TRAIN, + predictions=predictions, + loss=regularized_training_loss, + train_op=train_op) + + +@estimator_export('estimator.PoissonRegressionHead') +class PoissonRegressionHead(RegressionHead): + """Creates a `Head` for poisson regression using `tf.nn.log_poisson_loss`. + + The loss is the weighted sum over all input dimensions. Namely, if the input + labels have shape `[batch_size, label_dimension]`, the loss is the weighted + sum over both `batch_size` and `label_dimension`. + + The head expects `logits` with shape `[D0, D1, ... DN, label_dimension]`. + In many applications, the shape is `[batch_size, label_dimension]`. + + The `labels` shape must match `logits`, namely + `[D0, D1, ... DN, label_dimension]`. If `label_dimension=1`, shape + `[D0, D1, ... DN]` is also supported. + + If `weight_column` is specified, weights must be of shape + `[D0, D1, ... DN]`, `[D0, D1, ... DN, 1]` or + `[D0, D1, ... DN, label_dimension]`. + + This is implemented as a generalized linear model, see + https://en.wikipedia.org/wiki/Generalized_linear_model. + + The head can be used with a canned estimator. Example: + + ```python + my_head = tf.estimator.PoissonRegressionHead() + my_estimator = tf.estimator.DNNEstimator( + head=my_head, + hidden_units=..., + feature_columns=...) + ``` + + It can also be used with a custom `model_fn`. Example: + + ```python + def _my_model_fn(features, labels, mode): + my_head = tf.estimator.PoissonRegressionHead() + logits = tf.keras.Model(...)(features) + + return my_head.create_estimator_spec( + features=features, + mode=mode, + labels=labels, + optimizer=tf.keras.optimizers.Adagrad(lr=0.1), + logits=logits) + + my_estimator = tf.estimator.Estimator(model_fn=_my_model_fn) + ``` + + Args: + weight_column: A string or a `NumericColumn` created by + `tf.feature_column.numeric_column` defining feature column representing + weights. It is used to down weight or boost examples during training. It + will be multiplied by the loss of the example. + label_dimension: Number of regression labels per example. This is the size + of the last dimension of the labels `Tensor` (typically, this has shape + `[batch_size, label_dimension]`). + loss_reduction: One of `tf.losses.Reduction` except `NONE`. Decides how to + reduce training loss over batch and label dimension. Defaults to + `SUM_OVER_BATCH_SIZE`, namely weighted sum of losses divided by `batch + size * label_dimension`. + compute_full_loss: Whether to include the constant `log(z!)` term in + computing the poisson loss. See `tf.nn.log_poisson_loss` for the full + documentation. + name: name of the head. If provided, summary and metrics keys will be + suffixed by `"/" + name`. Also used as `name_scope` when creating ops. + """ + + def __init__(self, + label_dimension=1, + weight_column=None, + loss_reduction=tf.losses.Reduction.SUM_OVER_BATCH_SIZE, + compute_full_loss=True, + name=None): + self._compute_full_loss = compute_full_loss + super(PoissonRegressionHead, self).__init__( + label_dimension=label_dimension, + weight_column=weight_column, + loss_reduction=loss_reduction, + loss_fn=self._poisson_loss, + inverse_link_fn=tf.math.exp, + name=name) + + def _poisson_loss(self, labels, logits): + return tf.nn.log_poisson_loss( + targets=labels, + log_input=logits, + compute_full_loss=self._compute_full_loss) + + +@estimator_export('estimator.LogisticRegressionHead') +class LogisticRegressionHead(RegressionHead): + """Creates a `Head` for logistic regression. + + Uses `sigmoid_cross_entropy_with_logits` loss, which is the same as + `BinaryClassHead`. The differences compared to `BinaryClassHead` are: + + * Does not support `label_vocabulary`. Instead, labels must be float in the + range [0, 1]. + * Does not calculate some metrics that do not make sense, such as AUC. + * In `PREDICT` mode, only returns logits and predictions + (`=tf.sigmoid(logits)`), whereas `BinaryClassHead` also returns + probabilities, classes, and class_ids. + * Export output defaults to `RegressionOutput`, whereas `BinaryClassHead` + defaults to `PredictOutput`. + + The head expects `logits` with shape `[D0, D1, ... DN, 1]`. + In many applications, the shape is `[batch_size, 1]`. + + The `labels` shape must match `logits`, namely + `[D0, D1, ... DN]` or `[D0, D1, ... DN, 1]`. + + If `weight_column` is specified, weights must be of shape + `[D0, D1, ... DN]` or `[D0, D1, ... DN, 1]`. + + This is implemented as a generalized linear model, see + https://en.wikipedia.org/wiki/Generalized_linear_model. + + The head can be used with a canned estimator. Example: + + ```python + my_head = tf.estimator.LogisticRegressionHead() + my_estimator = tf.estimator.DNNEstimator( + head=my_head, + hidden_units=..., + feature_columns=...) + ``` + + It can also be used with a custom `model_fn`. Example: + + ```python + def _my_model_fn(features, labels, mode): + my_head = tf.estimator.LogisticRegressionHead() + logits = tf.keras.Model(...)(features) + + return my_head.create_estimator_spec( + features=features, + mode=mode, + labels=labels, + optimizer=tf.keras.optimizers.Adagrad(lr=0.1), + logits=logits) + + my_estimator = tf.estimator.Estimator(model_fn=_my_model_fn) + ``` + + Args: + weight_column: A string or a `NumericColumn` created by + `tf.feature_column.numeric_column` defining feature column representing + weights. It is used to down weight or boost examples during training. It + will be multiplied by the loss of the example. + loss_reduction: One of `tf.losses.Reduction` except `NONE`. Decides how to + reduce training loss over batch and label dimension. Defaults to + `SUM_OVER_BATCH_SIZE`, namely weighted sum of losses divided by `batch + size * label_dimension`. + name: name of the head. If provided, summary and metrics keys will be + suffixed by `"/" + name`. Also used as `name_scope` when creating ops. + """ + + def _logistic_loss(self, labels, logits): + labels = base_head.check_label_range( + labels, n_classes=2, message='Labels must be in range [0, 1]') + return tf.compat.v1.nn.sigmoid_cross_entropy_with_logits( + labels=labels, logits=logits) + + def __init__(self, + weight_column=None, + loss_reduction=tf.losses.Reduction.SUM_OVER_BATCH_SIZE, + name=None): + super(LogisticRegressionHead, self).__init__( + label_dimension=1, + weight_column=weight_column, + loss_reduction=loss_reduction, + loss_fn=self._logistic_loss, + inverse_link_fn=tf.math.sigmoid, + name=name) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/head/sequential_head.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/head/sequential_head.py new file mode 100644 index 0000000000000000000000000000000000000000..40f4fdb8ce74fdf4f178a97414bc9f9469a2a7a3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/head/sequential_head.py @@ -0,0 +1,494 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Defines a head for sequential models.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import abc + +import six +import tensorflow as tf + +if six.PY3: + from collections.abc import Iterable +else: + from collections import Iterable + +from tensorflow.python.framework import ops +from tensorflow_estimator.python.estimator.head import base_head +from tensorflow_estimator.python.estimator.head import multi_head +from tensorflow_estimator.python.estimator.mode_keys import ModeKeys + + +class _SequentialHead(base_head.Head): + """Interface for the head of a sequential model. + + A sequential head handles input sequences of different lengths to compute the + output of a model. It requires a sequence mask tensor, to indicate which steps + of the sequences are padded and ensure proper aggregation for loss and metrics + computation. It has a `input_sequence_mask_key` property that specifies which + tensor of the feature dictionary to use as the sequence mask tensor. + + Such a head can for instance be used with `RNNEstimator` for sequential + predictions. + + Example of usage: + ```python + def _my_model_fn(features, labels, mode, params, config=None): + feature_layer = tf.feature_column.SequenceFeatureLayer(columns) + input_layer, sequence_length = feature_layer(features) + sequence_length_mask = tf.sequence_mask(sequence_length) + rnn_layer = tf.keras.layers.RNN(cell=tf.keras.layers.SimpleRNNCell(units), + return_sequences=True) + logits = rnn_layer(input_layer, mask=sequence_length_mask) + features[sequential_head.input_sequence_mask_key] = sequence_length_mask + return sequential_head.create_estimator_spec( + features=features, + labels=labels, + mode=mode, + logits=logits, + optimizer=optimizer) + ``` + """ + __metaclass__ = abc.ABCMeta + + @abc.abstractproperty + def input_sequence_mask_key(self): + """Key of the sequence mask tensor in the feature dictionary. + + Returns: + A string. + """ + raise NotImplementedError('Calling an abstract method.') + + +class SequentialHeadWrapper(_SequentialHead): + """Sequential head wrapping a Head object. + + Wraps a `Head` object and applies a sequential mask to: + - Loss aggregation: To only account for masked steps. Used for + `create_estimator_spec` and `loss` methods. + - Metrics: The sequence mask is used to only account for mask steps in + metrics computation with the `update_metrics` method. + - Predictions: To add a sequence length mask tensor to the predictions + dictionary. + """ + + def __init__(self, + static_head, + sequence_length_mask='sequence_length_mask', + feature_columns=None): + """Initializes a `SequentialHeadWrapper` instance. + + Example of usage: + ```python + # Define a sequential head. + static_head = tf.estimator.BinaryClassHead(weight_column='weights') + sequential_head = head_lib.SequentialHeadWrapper( + static_head=static_head, sequence_length_mask='mask', + feature_columns='weights') + + # Define feature columns and parsing spec. + feature_columns = [ + tf.feature_column.sequence_numeric_column('sequential-feature') + ] + label_column = tf.feature_column.sequence_numeric_column( + 'label', dtype=tf.int32), + weight_column = tf.feature_column.sequence_numeric_column('weights') + parsing_spec = tf.feature_column.make_parse_example_spec( + feature_columns + [label_column, weight_column]) + + # Use the head in a model function. + def _my_model_fn(features, labels, mode, params, config=None): + feature_layer = tf.feature_column.SequenceFeatureLayer(feature_columns) + input_layer, sequence_length = feature_layer(features) + sequence_length_mask = tf.sequence_mask(sequence_length) + rnn_layer = tf.keras.layers.RNN( + cell=tf.keras.layers.SimpleRNNCell(units), + return_sequences=True) + logits = rnn_layer(input_layer, mask=sequence_length_mask) + features['mask'] = sequence_length_mask + return sequential_head.create_estimator_spec( + features=features, + labels=labels, + mode=mode, + logits=logits, + optimizer=optimizer) + ``` + + Args: + static_head: `Head` object, static head to wrap. + sequence_length_mask: `str`, name of sequence length mask tensor in + features dictionary. Tensor must be a dense tensor of shape [batch_size, + seq_length]. + feature_columns: `str` or list of the former. Specifies the features of + the features dictionary to which the sequence length mask must be + applied, and which are passed to the static head's methods when calling + `create_estimator_spec`, `loss` or `update_metrics`. This is typically a + weight tensor. + + Raises: + TypeError: If `sequence_length_mask` is not of string type. + TypeError: If provided features columns are not of string type. + """ + # Verify and set sequence mask column. + # TODO(aarg): Add support for `NumericColumn`. + if not isinstance(sequence_length_mask, six.string_types): + raise TypeError('`sequence_mask` column must be a string. ' + 'Given type: {}.'.format(type(sequence_length_mask))) + self._sequence_length_mask = sequence_length_mask + + # Verify and set feature columns (to be flattened). + feature_columns = feature_columns or [] + if not isinstance(feature_columns, Iterable): + raise TypeError('`feature_columns` must be either a string or an ' + 'iterable of strings got {} instead.'.format( + type(feature_columns))) + if isinstance(feature_columns, six.string_types): + self._feature_columns = [feature_columns] + else: + self._feature_columns = feature_columns + + for column in self._feature_columns: + # TODO(aarg): Add support for `NumericColumn` and `SequenceNumericColumn`. + if not isinstance(column, six.string_types): + raise TypeError('Column must a string. Given type: {}.'.format( + type(column))) + + # Set other variables. + if isinstance(static_head, multi_head.MultiHead): + # TODO(aarg): Add support for MultiHead. + raise ValueError( + '`MultiHead` is not supported with `SequentialHeadWrapper`.') + self._static_head = static_head + + super(SequentialHeadWrapper, self).__init__() + + def _flatten(self, labels, logits, features): + """Flattens labels, logits, and features tensors. + + Provided tensors need to have at least two dimensions. The two first + dimensions of the provided tensors are flattened to one single dimension. + If a tensor is dense, the sequence mask in the features dictionary is used + to flatten it. + + Note: If indices of a sparse tensor are not sorted, they will be reordered. + + Args: + labels: `Tensor` or `SparseTensor` to flatten. + logits: `Tensor` or `SparseTensor` to flatten. + features: Dictionary of `Tensor` or `SparseTensor` objects to flatten. + + Returns: + - Dense `Tensor` with flattened labels. + - Dense `Tensor` with flattened logits. + - Dictionary of flattened dense `Tensor` objects. + + Raises: + ValueError: If the sequence mask is not found in `features`. + ValueError: If one of the provided tensors to flatten has not at least two + dimensions. + """ + # Retrieve sequence_mask from features dictionary. + if self.input_sequence_mask_key not in features: + raise ValueError('The provided sequence_length_mask key `{}` should be ' + 'included in the features dictionary, but was not ' + 'found. Found keys: {}.'.format( + self.input_sequence_mask_key, list(features.keys()))) + sequence_mask = features[self.input_sequence_mask_key] + if sequence_mask.get_shape().ndims != 2: + raise ValueError('Mask is expected to have two dimensions, got ' + '{} instead.'.format(sequence_mask.get_shape().ndims)) + + with ops.name_scope('flatten'): + expected_length = tf.math.reduce_sum( + tf.cast(sequence_mask, tf.dtypes.int32)) + # Flatten logits and labels. + flat_logits = _flatten_tensor(logits, sequence_mask, expected_length) + flat_labels = _flatten_tensor(labels, sequence_mask, expected_length) + + # Flatten features. + flat_features = {} + for column in self._feature_columns: + if column not in features: + raise ValueError('`{}` column expected in features ' + 'dictionary.'.format(column)) + flat_features[column] = _flatten_tensor(features[column], sequence_mask, + expected_length) + + return flat_labels, flat_logits, flat_features + + def loss(self, + logits, + labels, + features=None, + mode=None, + regularization_losses=None): + """Flattens input and returns regularized training loss. + + Flattens `logits`, `labels`, and `features` tensors that are specified by + the head's `feature_columns` before calling the static head's `loss` method. + + Args: + logits: Logits `Tensor` of rank >= 2 and shape [batch_size, seq_length, + D2, ... DN]. + labels: Labels `Tensor` or `SparseTensor` or rank >= 2 and shape + [batch_size, seq_length, D2, ... DN]. + features: Input `dict` mapping string feature names to `Tensor` or + `SparseTensor` objects containing the values for that feature in a + minibatch. Must contain the sequence length mask tensor. Features + corresponding to the sequential's head `feature_columns` are flattened + and passed to the static head's `loss` method. + mode: Estimator's `ModeKeys`. To be used in case loss calculation is + different in Train and Eval mode. + regularization_losses: A list of additional scalar losses to be added to + the training loss, such as regularization losses. + + Returns: + A scalar `Tensor` representing regularized training loss used in train and + eval. + """ + flat_labels, flat_logits, flat_features = self._flatten( + labels, logits, features) + return self._static_head.loss( + logits=flat_logits, + labels=flat_labels, + features=flat_features, + mode=mode, + regularization_losses=regularization_losses) + + def create_estimator_spec(self, + features, + mode, + logits, + labels=None, + optimizer=None, + trainable_variables=None, + train_op_fn=None, + update_ops=None, + regularization_losses=None): + """Returns `EstimatorSpec` that a model_fn can return. + + If in TRAIN or EVAL mode, `logits`, `labels`, and `features` tensors + corresponding to the head's `feature_columns` are flattened before calling + the static head's `create_estimator_spec` method. + If in PREDICT mode, no flattening is done. The `EstimatatorSpec` is computed + using the static head's `create_estimator_spec` method. The sequence length + mask tensor is added to the predictions dictionary. + + Args: + features: Input `dict` mapping string feature names to `Tensor` or + `SparseTensor` objects containing the values for that feature in a + minibatch. If in TRAIN or EVAL mode, only specified features are + flattened and passed to the static head's method. + mode: Estimator's `ModeKeys`. + logits: Logits `Tensor` of rank >= 2 and shape [batch_size, seq_length, + D2, ... DN]. + labels: Labels `Tensor` or `SparseTensor` or rank >= 2 and shape + [batch_size, seq_length, D2, ... DN]. + optimizer: An `tf.keras.optimizers.Optimizer` instance to optimize the + loss in TRAIN mode. Namely, sets + `train_op = optimizer.get_updates(loss, trainable_variables)`, which + updates variables to minimize `loss`. + trainable_variables: A list or tuple of `Variable` objects to update to + minimize `loss`. In Tensorflow 1.x, by default these are the list of + variables collected in the graph under the key + `GraphKeys.TRAINABLE_VARIABLES`. As Tensorflow 2.x doesn't have + collections and GraphKeys, trainable_variables need to be passed + explicitly here. + train_op_fn: Function that takes a scalar loss `Tensor` and returns an op + to optimize the model with the loss in TRAIN mode. Used if `optimizer` + is `None`. Exactly one of `train_op_fn` and `optimizer` must be set in + TRAIN mode. By default, it is `None` in other modes. If you want to + optimize loss yourself, you can pass `lambda _: tf.no_op()` and then use + `EstimatorSpec.loss` to compute and apply gradients. + update_ops: A list or tuple of update ops to be run at training time. For + example, layers such as BatchNormalization create mean and variance + update ops that need to be run at training time. In Tensorflow 1.x, + these are thrown into an UPDATE_OPS collection. As Tensorflow 2.x + doesn't have collections, update_ops need to be passed explicitly here. + regularization_losses: A list of additional scalar losses to be added to + the training loss, such as regularization losses. + + Returns: + `EstimatorSpec`. + """ + if mode == ModeKeys.PREDICT: + spec = self._static_head.create_estimator_spec( + features=features, mode=mode, logits=logits) + spec.predictions[self.input_sequence_mask_key] = features[ + self.input_sequence_mask_key] + return spec._replace(predictions=spec.predictions) + + flat_labels, flat_logits, flat_features = self._flatten( + labels, logits, features) + + return self._static_head.create_estimator_spec( + features=flat_features, + mode=mode, + logits=flat_logits, + trainable_variables=trainable_variables, + labels=flat_labels, + optimizer=optimizer, + train_op_fn=train_op_fn, + regularization_losses=regularization_losses, + update_ops=update_ops) + + def update_metrics(self, + eval_metrics, + features, + logits, + labels, + regularization_losses=None): + """Updates metric objects and returns a `dict` of the updated metrics. + + Flattens `logits`, `labels`, and `features` tensors that are specified by + the head's feature_columns` before calling the static head's + `update_metrics` method. + + Args: + eval_metrics: A `dict` of metrics to be updated. + features: Input `dict` mapping string feature names to `Tensor` or + `SparseTensor` objects containing the values for that feature in a + minibatch. Only specified features are flattened and passed to the + static head's method. + logits: Logits `Tensor` of rank >= 2 and shape [batch_size, seq_length, + D2, ... DN]. + labels: Labels `Tensor` or `SparseTensor` or rank >= 2 and shape + [batch_size, seq_length, D2, ... DN]. + regularization_losses: A list of additional scalar losses to be added to + the training and evaluation loss, such as regularization losses. + + Returns: + A `dict` of updated metrics keyed by name. The value is an instance of + `Metric` class. + """ + flat_labels, flat_logits, flat_features = self._flatten( + labels, logits, features) + return self._static_head.update_metrics( + eval_metrics=eval_metrics, + features=flat_features, + logits=flat_logits, + labels=flat_labels, + regularization_losses=regularization_losses) + + def _create_tpu_estimator_spec(self, + features, + mode, + logits, + labels=None, + optimizer=None, + trainable_variables=None, + train_op_fn=None, + update_ops=None, + regularization_losses=None): + raise NotImplementedError + + def predictions(self, logits, keys=None): + """Calls the static head's `predictions` method.""" + return self._static_head.predictions(logits, keys=keys) + + def metrics(self, regularization_losses=None): + """Calls the static head's `metrics` method.""" + return self._static_head.metrics(regularization_losses) + + @property + def input_sequence_mask_key(self): + """Returns the key for the sequence mask feature.""" + return self._sequence_length_mask + + @property + def logits_dimension(self): + """Returns the logits dimension of the static head.""" + return self._static_head.logits_dimension + + @property + def loss_reduction(self): + """Returns the loss reduction of the static head.""" + return self._static_head.loss_reduction + + @property + def name(self): + """Returns the name of the static head.""" + if self._static_head.name: + return '{}_sequential'.format(self._static_head.name) + return None + + @property + def static_head(self): + """Returns the wrapped static head.""" + return self._static_head + + +def _flatten_tensor(tensor, sequence_mask, expected_length): + """Flattens the two first dimensions and reshapes a tensor or sparse tensor. + + If `tensor` is a dense tensor, the sequence_mask is used to infer valid + inputs. + + Note: If `tensor` is a `SparseTensor` and the indices are not sorted, they + will be reordered. + + Args: + tensor: A `Tensor` or `SparseTensor` of dimension at least 2, of shape + [batch_size, seq_length, D0, D1, ..., DN]. + sequence_mask: A boolean `Tensor` of shape [batch_size, seq_length]. + expected_length: A integer scalar `Tensor` with the expected length of the + resulting flattenned Tensor. + + Returns: + A `Tensor` object of shape [expected_length, D0, D1, ..., DN]. + + Raises: + ValueError: If `tensor` has not at least 2 dimensions. + ValueError: If `tensor` is not a `Tensor` or `SparseTensor` object. + InvalidArgumentError: If the resulting `Tensor` doesn't have the expected + length. + """ + shape = tensor.get_shape() + if shape.ndims < 2: + raise ValueError('Input tensor expected to have at least 2 dimensions, ' + 'got {} instead.'.format(shape.ndims)) + if isinstance(tensor, tf.sparse.SparseTensor): + # What follows depends on the indices ordering. Hence we reorder the indices + # to ensure correctness. + flat_tensor = tf.sparse.reorder(tensor).values + if shape.ndims > 2: + new_shape = tf.concat([[-1], shape[2:]], axis=0) + flat_tensor = tf.reshape(tensor.values, new_shape) + elif isinstance(tensor, tf.Tensor): + flat_tensor = tf.boolean_mask(tensor, sequence_mask) + else: + raise ValueError('`tensor` expected to be a `Tensor` or `SparseTensor` ' + 'got `{}` instead.'.format(tensor)) + if shape.ndims == 2: + flat_tensor = tf.compat.v1.expand_dims(flat_tensor, -1) + expected_shape = tf.concat([[expected_length], [1]], axis=0) + else: + expected_shape = tf.concat([[expected_length], shape[2:]], axis=0) + + # TODO(b/119617064): Unify eager and graph implementations. + err_message = 'Tensor shape is incompatible with provided mask.' + if tf.executing_eagerly(): + if flat_tensor._shape_tuple() != tuple(expected_shape.numpy()): # pylint: disable=protected-access + raise ValueError(err_message) + return flat_tensor + with tf.control_dependencies([ + tf.compat.v1.debugging.assert_equal( + tf.compat.v1.shape(flat_tensor), expected_shape, message=err_message) + ]): + return tf.identity(flat_tensor) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/hooks/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/hooks/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/hooks/basic_session_run_hooks.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/hooks/basic_session_run_hooks.py new file mode 100644 index 0000000000000000000000000000000000000000..b20f43f974a780438034b9729994e7317a157b53 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/hooks/basic_session_run_hooks.py @@ -0,0 +1,49 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Some common SessionRunHook classes.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +from tensorflow.python.training.basic_session_run_hooks import CheckpointSaverHook +from tensorflow.python.training.basic_session_run_hooks import CheckpointSaverListener +from tensorflow.python.training.basic_session_run_hooks import FeedFnHook +from tensorflow.python.training.basic_session_run_hooks import FinalOpsHook +from tensorflow.python.training.basic_session_run_hooks import GlobalStepWaiterHook +from tensorflow.python.training.basic_session_run_hooks import LoggingTensorHook +from tensorflow.python.training.basic_session_run_hooks import NanLossDuringTrainingError +from tensorflow.python.training.basic_session_run_hooks import NanTensorHook +from tensorflow.python.training.basic_session_run_hooks import ProfilerHook +from tensorflow.python.training.basic_session_run_hooks import SecondOrStepTimer +from tensorflow.python.training.basic_session_run_hooks import StepCounterHook +from tensorflow.python.training.basic_session_run_hooks import StopAtStepHook +from tensorflow.python.training.basic_session_run_hooks import SummarySaverHook +from tensorflow_estimator.python.estimator.estimator_export import estimator_export + +estimator_export("estimator.SecondOrStepTimer")(SecondOrStepTimer) +estimator_export("estimator.LoggingTensorHook")(LoggingTensorHook) +estimator_export("estimator.StopAtStepHook")(StopAtStepHook) +estimator_export("estimator.CheckpointSaverListener")(CheckpointSaverListener) +estimator_export("estimator.CheckpointSaverHook")(CheckpointSaverHook) +estimator_export("estimator.StepCounterHook")(StepCounterHook) +estimator_export("estimator.NanLossDuringTrainingError")( + NanLossDuringTrainingError) +estimator_export("estimator.NanTensorHook")(NanTensorHook) +estimator_export("estimator.SummarySaverHook")(SummarySaverHook) +estimator_export("estimator.GlobalStepWaiterHook")(GlobalStepWaiterHook) +estimator_export("estimator.FinalOpsHook")(FinalOpsHook) +estimator_export("estimator.FeedFnHook")(FeedFnHook) +estimator_export("estimator.ProfilerHook")(ProfilerHook) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/hooks/fake_summary_writer.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/hooks/fake_summary_writer.py new file mode 100644 index 0000000000000000000000000000000000000000..c04755ae7704f5e1886d8ada284d2218bc07f0f5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/hooks/fake_summary_writer.py @@ -0,0 +1,143 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Fake summary writer for unit tests.""" +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +from tensorflow.core.framework import summary_pb2 +from tensorflow.python.framework import test_util +from tensorflow.python.summary.writer import writer +from tensorflow.python.summary.writer import writer_cache + + +# TODO(ptucker): Replace with mock framework. +class FakeSummaryWriter(object): + """Fake summary writer.""" + + _replaced_summary_writer = None + + @classmethod + def install(cls): + if cls._replaced_summary_writer: + raise ValueError('FakeSummaryWriter already installed.') + cls._replaced_summary_writer = writer.FileWriter + writer.FileWriter = FakeSummaryWriter + writer_cache.FileWriter = FakeSummaryWriter + + @classmethod + def uninstall(cls): + if not cls._replaced_summary_writer: + raise ValueError('FakeSummaryWriter not installed.') + writer.FileWriter = cls._replaced_summary_writer + writer_cache.FileWriter = cls._replaced_summary_writer + cls._replaced_summary_writer = None + + def __init__(self, logdir, graph=None): + self._logdir = logdir + self._graph = graph + self._summaries = {} + self._added_graphs = [] + self._added_meta_graphs = [] + self._added_session_logs = [] + self._added_run_metadata = {} + + @property + def summaries(self): + return self._summaries + + def assert_summaries(self, + test_case, + expected_logdir=None, + expected_graph=None, + expected_summaries=None, + expected_added_graphs=None, + expected_added_meta_graphs=None, + expected_session_logs=None): + """Assert expected items have been added to summary writer.""" + if expected_logdir is not None: + test_case.assertEqual(expected_logdir, self._logdir) + if expected_graph is not None: + test_case.assertTrue(expected_graph is self._graph) + expected_summaries = expected_summaries or {} + for step in expected_summaries: + test_case.assertTrue( + step in self._summaries, + msg='Missing step %s from %s.' % (step, self._summaries.keys())) + actual_simple_values = {} + for step_summary in self._summaries[step]: + for v in step_summary.value: + # Ignore global_step/sec since it's written by Supervisor in a + # separate thread, so it's non-deterministic how many get written. + if 'global_step/sec' != v.tag: + actual_simple_values[v.tag] = v.simple_value + test_case.assertEqual(expected_summaries[step], actual_simple_values) + if expected_added_graphs is not None: + test_case.assertEqual(expected_added_graphs, self._added_graphs) + if expected_added_meta_graphs is not None: + test_case.assertEqual( + len(expected_added_meta_graphs), len(self._added_meta_graphs)) + for expected, actual in zip(expected_added_meta_graphs, + self._added_meta_graphs): + test_util.assert_meta_graph_protos_equal(test_case, expected, actual) + if expected_session_logs is not None: + test_case.assertEqual(expected_session_logs, self._added_session_logs) + + def add_summary(self, summ, current_global_step): + """Add summary.""" + if isinstance(summ, bytes): + summary_proto = summary_pb2.Summary() + summary_proto.ParseFromString(summ) + summ = summary_proto + if current_global_step in self._summaries: + step_summaries = self._summaries[current_global_step] + else: + step_summaries = [] + self._summaries[current_global_step] = step_summaries + step_summaries.append(summ) + + # NOTE: Ignore global_step since its value is non-deterministic. + def add_graph(self, graph, global_step=None, graph_def=None): + """Add graph.""" + if (global_step is not None) and (global_step < 0): + raise ValueError('Invalid global_step %s.' % global_step) + if graph_def is not None: + raise ValueError('Unexpected graph_def %s.' % graph_def) + self._added_graphs.append(graph) + + def add_meta_graph(self, meta_graph_def, global_step=None): + """Add metagraph.""" + if (global_step is not None) and (global_step < 0): + raise ValueError('Invalid global_step %s.' % global_step) + self._added_meta_graphs.append(meta_graph_def) + + # NOTE: Ignore global_step since its value is non-deterministic. + def add_session_log(self, session_log, global_step=None): + # pylint: disable=unused-argument + self._added_session_logs.append(session_log) + + def add_run_metadata(self, run_metadata, tag, global_step=None): + if (global_step is not None) and (global_step < 0): + raise ValueError('Invalid global_step %s.' % global_step) + self._added_run_metadata[tag] = run_metadata + + def flush(self): + pass + + def reopen(self): + pass + + def close(self): + pass diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/hooks/hooks.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/hooks/hooks.py new file mode 100644 index 0000000000000000000000000000000000000000..7aa5d4d521ed527582086141fc1aee6f5a1e31ee --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/hooks/hooks.py @@ -0,0 +1,283 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Some useful session run hooks.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import os +import time +import tensorflow as tf +from tensorflow.python.training import training_util +from tensorflow_estimator.python.estimator import estimator as estimator_lib +from tensorflow_estimator.python.estimator.estimator_export import estimator_export + + +# pylint: disable=protected-access +@estimator_export('estimator.experimental.InMemoryEvaluatorHook') +class InMemoryEvaluatorHook(tf.compat.v1.train.SessionRunHook): + """Hook to run evaluation in training without a checkpoint. + + Example: + + ```python + def train_input_fn(): + ... + return train_dataset + + def eval_input_fn(): + ... + return eval_dataset + + estimator = tf.estimator.DNNClassifier(...) + + evaluator = tf.estimator.experimental.InMemoryEvaluatorHook( + estimator, eval_input_fn) + estimator.train(train_input_fn, hooks=[evaluator]) + ``` + + Current limitations of this approach are: + + * It doesn't support multi-node distributed mode. + * It doesn't support saveable objects other than variables (such as boosted + tree support) + * It doesn't support custom saver logic (such as ExponentialMovingAverage + support) + + """ + + def __init__(self, + estimator, + input_fn, + steps=None, + hooks=None, + name=None, + every_n_iter=100): + """Initializes a `InMemoryEvaluatorHook`. + + Args: + estimator: A `tf.estimator.Estimator` instance to call evaluate. + input_fn: Equivalent to the `input_fn` arg to `estimator.evaluate`. A + function that constructs the input data for evaluation. See [Creating + input functions]( + https://tensorflow.org/guide/premade_estimators#create_input_functions) + for more information. The function should construct and return one of + the following: + * A 'tf.data.Dataset' object: Outputs of `Dataset` object must be a + tuple (features, labels) with same constraints as below. + * A tuple (features, labels): Where `features` is a `Tensor` or a + dictionary of string feature name to `Tensor` and `labels` is a + `Tensor` or a dictionary of string label name to `Tensor`. Both + `features` and `labels` are consumed by `model_fn`. They should + satisfy the expectation of `model_fn` from inputs. + steps: Equivalent to the `steps` arg to `estimator.evaluate`. Number of + steps for which to evaluate model. If `None`, evaluates until `input_fn` + raises an end-of-input exception. + hooks: Equivalent to the `hooks` arg to `estimator.evaluate`. List of + `SessionRunHook` subclass instances. Used for callbacks inside the + evaluation call. + name: Equivalent to the `name` arg to `estimator.evaluate`. Name of the + evaluation if user needs to run multiple evaluations on different data + sets, such as on training data vs test data. Metrics for different + evaluations are saved in separate folders, and appear separately in + tensorboard. + every_n_iter: `int`, runs the evaluator once every N training iteration. + + Raises: + ValueError: if `every_n_iter` is non-positive or it's not a single machine + training + """ + if every_n_iter is None or every_n_iter <= 0: + raise ValueError('invalid every_n_iter=%s.' % every_n_iter) + if (estimator.config.num_ps_replicas > 0 or + estimator.config.num_worker_replicas > 1): + raise ValueError( + 'InMemoryEvaluator supports only single machine (aka Local) setting.') + self._estimator = estimator + self._input_fn = input_fn + self._steps = steps + self._name = name + self._every_n_iter = every_n_iter + self._eval_dir = os.path.join(self._estimator.model_dir, + 'eval' if not name else 'eval_' + name) + + self._graph = None + self._hooks = estimator_lib._check_hooks_type(hooks) + self._hooks.extend(self._estimator._convert_eval_steps_to_hooks(steps)) + self._timer = tf.compat.v1.train.SecondOrStepTimer(every_steps=every_n_iter) + + def begin(self): + """Build eval graph and restoring op.""" + self._timer.reset() + self._iter_count = 0 + self._graph = tf.Graph() + with self._graph.as_default(): + (self._scaffold, self._update_op, self._eval_dict, + self._all_hooks) = self._estimator._evaluate_build_graph( + self._input_fn, self._hooks, checkpoint_path=None) + + if self._scaffold.saver is not None: + raise ValueError('InMemoryEvaluator does not support custom saver') + if self._scaffold.init_fn is not None: + raise ValueError('InMemoryEvaluator does not support custom init_fn') + + self._var_name_to_eval_var = { + v.name: v for v in tf.compat.v1.get_collection( + tf.compat.v1.GraphKeys.GLOBAL_VARIABLES) + } + self._var_name_to_placeholder = { + v.name: tf.compat.v1.placeholder(v.dtype) for v in + tf.compat.v1.get_collection(tf.compat.v1.GraphKeys.GLOBAL_VARIABLES) + } + + def after_create_session(self, session, coord): # pylint: disable=unused-argument + """Does first run which shows the eval metrics before training.""" + if tf.compat.v1.get_collection(tf.compat.v1.GraphKeys.SAVEABLE_OBJECTS): + raise ValueError( + 'InMemoryEvaluator does not support saveables other than global ' + 'variables.') + self._var_name_to_train_var = { + v.name: v for v in tf.compat.v1.get_collection( + tf.compat.v1.GraphKeys.GLOBAL_VARIABLES) + } + var_names_to_transfer = set(self._var_name_to_placeholder.keys()) & set( + self._var_name_to_train_var.keys()) + # Filter training var names that are not exist in evaluation + self._var_name_to_train_var = { + v_name: self._var_name_to_train_var[v_name] + for v_name in var_names_to_transfer + } + # Filter eval var names that are not exist in training + self._var_name_to_eval_var = { + v_name: self._var_name_to_eval_var[v_name] + for v_name in var_names_to_transfer + } + + with self._graph.as_default(): + self._var_feed_op = tf.group([ + tf.compat.v1.assign(self._var_name_to_eval_var[v_name], + self._var_name_to_placeholder[v_name]) + for v_name in var_names_to_transfer + ]) + + self._evaluate(session) + + def _evaluate(self, train_session): + var_name_to_value = train_session.run(self._var_name_to_train_var) + placeholder_to_value = { + self._var_name_to_placeholder[v_name]: var_name_to_value[v_name] + for v_name in var_name_to_value + } + + def feed_variables(scaffold, session): + del scaffold + session.run(self._var_feed_op, feed_dict=placeholder_to_value) + + scaffold = tf.compat.v1.train.Scaffold( + init_fn=feed_variables, copy_from_scaffold=self._scaffold) + + with self._graph.as_default(): + self._estimator._evaluate_run( + checkpoint_path=None, + scaffold=scaffold, + update_op=self._update_op, + eval_dict=self._eval_dict, + all_hooks=self._all_hooks, + output_dir=self._eval_dir) + + self._timer.update_last_triggered_step(self._iter_count) + + def after_run(self, run_context, run_values): # pylint: disable=unused-argument + """Runs evaluator.""" + self._iter_count += 1 + if self._timer.should_trigger_for_step(self._iter_count): + self._evaluate(run_context.session) + + def end(self, session): # pylint: disable=unused-argument + """Runs evaluator for final model.""" + self._evaluate(session) + + +class _StopAtCheckpointStepHook(tf.compat.v1.train.SessionRunHook): + """Hook that requests stop at a specified step based on checkpoint. + + Note: We recommend using 'make_stop_at_checkpoint_step_hook` to get the proper + hook. + """ + + def __init__(self, model_dir, last_step, wait_after_file_check_secs=30): + """Initializes a `StopAtCheckpointStepHook`. + + This hook requests stop after a last step has been reached. It checks latest + checkpoint to verify last step is written on disk or not. + + Args: + model_dir: Directory to read global step from latest checkpoint. + last_step: Step after which to stop. + wait_after_file_check_secs: Reading same file by many workers may create + I/O issues. To throttle that we will wait given secs after each read of + the file. + + Raises: + ValueError: If one of the arguments is invalid. + """ + if last_step is None: + raise ValueError('last_step must be specified.') + if model_dir is None: + raise ValueError('model_dir must be specified.') + + self._model_dir = model_dir + self._last_step = last_step + self._wait_after_file_check_secs = wait_after_file_check_secs + + def begin(self): + self._global_step_tensor = training_util._get_or_create_global_step_read() # pylint: disable=protected-access + if self._global_step_tensor is None: + raise RuntimeError( + 'Global step should be created to use StopAtCheckpointStepHook.') + + def before_run(self, run_context): # pylint: disable=unused-argument + return tf.compat.v1.train.SessionRunArgs(self._global_step_tensor) + + def after_run(self, run_context, run_values): + global_step = run_values.results + 1 + if global_step >= self._last_step: + # Check latest global step in the checkpoint to ensure that the targeted + # last step is written on disk. + + step = estimator_lib._load_global_step_from_checkpoint_dir( + self._model_dir) + if step >= self._last_step: + run_context.request_stop() + else: + time.sleep(self._wait_after_file_check_secs) + + +@estimator_export('estimator.experimental.make_stop_at_checkpoint_step_hook') +def make_stop_at_checkpoint_step_hook(estimator, + last_step, + wait_after_file_check_secs=30): + """Creates a proper StopAtCheckpointStepHook based on chief status.""" + + if estimator.config.is_chief: + return tf.compat.v1.train.StopAtStepHook(last_step=last_step) + return _StopAtCheckpointStepHook( + model_dir=estimator.model_dir, + last_step=last_step, + wait_after_file_check_secs=wait_after_file_check_secs) + + +# pylint: enable=protected-access diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/hooks/session_run_hook.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/hooks/session_run_hook.py new file mode 100644 index 0000000000000000000000000000000000000000..f2be3e8959e069001921f60820b3bc4cf4e44cd2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/hooks/session_run_hook.py @@ -0,0 +1,101 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""A SessionRunHook extends `session.run()` calls for the `MonitoredSession`. + +SessionRunHooks are useful to track training, report progress, request early +stopping and more. SessionRunHooks use the observer pattern and notify at the +following points: + - when a session starts being used + - before a call to the `session.run()` + - after a call to the `session.run()` + - when the session closed + +A SessionRunHook encapsulates a piece of reusable/composable computation that +can piggyback a call to `MonitoredSession.run()`. A hook can add any +ops-or-tensor/feeds to the run call, and when the run call finishes with success +gets the outputs it requested. Hooks are allowed to add ops to the graph in +`hook.begin()`. The graph is finalized after the `begin()` method is called. + +There are a few pre-defined hooks: + - StopAtStepHook: Request stop based on global_step + - CheckpointSaverHook: saves checkpoint + - LoggingTensorHook: outputs one or more tensor values to log + - NanTensorHook: Request stop if given `Tensor` contains Nans. + - SummarySaverHook: saves summaries to a summary writer + +For more specific needs, you can create custom hooks: + class ExampleHook(SessionRunHook): + def begin(self): + # You can add ops to the graph here. + print('Starting the session.') + self.your_tensor = ... + + def after_create_session(self, session, coord): + # When this is called, the graph is finalized and + # ops can no longer be added to the graph. + print('Session created.') + + def before_run(self, run_context): + print('Before calling session.run().') + return SessionRunArgs(self.your_tensor) + + def after_run(self, run_context, run_values): + print('Done running one step. The value of my tensor: %s', + run_values.results) + if you-need-to-stop-loop: + run_context.request_stop() + + def end(self, session): + print('Done with the session.') + +To understand how hooks interact with calls to `MonitoredSession.run()`, +look at following code: + with MonitoredTrainingSession(hooks=your_hooks, ...) as sess: + while not sess.should_stop(): + sess.run(your_fetches) + +Above user code leads to following execution: + call hooks.begin() + sess = tf.Session() + call hooks.after_create_session() + while not stop is requested: + call hooks.before_run() + try: + results = sess.run(merged_fetches, feed_dict=merged_feeds) + except (errors.OutOfRangeError, StopIteration): + break + call hooks.after_run() + call hooks.end() + sess.close() + +Note that if sess.run() raises OutOfRangeError or StopIteration then +hooks.after_run() will not be called but hooks.end() will still be called. +If sess.run() raises any other exception then neither hooks.after_run() nor +hooks.end() will be called. +""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function +from tensorflow.python.training.session_run_hook import SessionRunArgs +from tensorflow.python.training.session_run_hook import SessionRunContext +from tensorflow.python.training.session_run_hook import SessionRunHook +from tensorflow.python.training.session_run_hook import SessionRunValues +from tensorflow_estimator.python.estimator.estimator_export import estimator_export + +estimator_export("estimator.SessionRunHook")(SessionRunHook) +estimator_export("estimator.SessionRunArgs")(SessionRunArgs) +estimator_export("estimator.SessionRunContext")(SessionRunContext) +estimator_export("estimator.SessionRunValues")(SessionRunValues) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/inputs/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/inputs/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/inputs/inputs.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/inputs/inputs.py new file mode 100644 index 0000000000000000000000000000000000000000..c5a52547f75359d784def3c2b0e712a707fa1ee1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/inputs/inputs.py @@ -0,0 +1,25 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Utility methods to create simple input_fns.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +# pylint: disable=unused-import,line-too-long +from tensorflow_estimator.python.estimator.inputs.numpy_io import numpy_input_fn +from tensorflow_estimator.python.estimator.inputs.pandas_io import pandas_input_fn + +# pylint: enable=unused-import,line-too-long diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/inputs/numpy_io.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/inputs/numpy_io.py new file mode 100644 index 0000000000000000000000000000000000000000..e18bc4478cfc5f785fcb0e9ed11602a62ed38461 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/inputs/numpy_io.py @@ -0,0 +1,224 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Methods to allow dict of numpy arrays.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import collections + +import numpy as np +from six import string_types +from tensorflow_estimator.python.estimator.estimator_export import estimator_export +from tensorflow_estimator.python.estimator.inputs.queues import feeding_functions + +# Key name to pack the target into dict of `features`. See +# `_get_unique_target_key` for details. +_TARGET_KEY = '__target_key__' + + +def _get_unique_target_key(features): + """Returns a key not existed in the input dict `features`. + + Caller of `input_fn` usually provides `features` (dict of numpy arrays) and + `target`, but the underlying feeding module expects a single dict of numpy + arrays as input. So, the `target` needs to be packed into the `features` + temporarily and unpacked after calling the feeding function. Toward this goal, + this function returns a key not existed in the `features` to pack the + `target`. + + Args: + features: OrderedDict of numpy arrays + + Returns: + A unique key that can be used to insert the subsequent target into + features dict. + """ + target_key = _TARGET_KEY + while target_key in features: + target_key += '_n' + return target_key + + +def _validate_and_convert_features(x): + """Type check input data and make a shadow copy as an ordered dict. + + Args: + x: numpy array object or dict of numpy array objects. If an array, the array + will be treated as a single feature. + + Returns: + OrderedDict copy of x. + + Raises: + ValueError: if x is empty + TypeError: if x is an unknown type. + """ + if isinstance(x, dict): + if not x: + raise ValueError('x cannot be an empty dict') + # Make a shadow copy and also ensure the order of iteration is consistent. + ordered_dict_data = collections.OrderedDict( + sorted(x.items(), key=lambda t: t[0])) + elif isinstance(x, np.ndarray): + if x.size == 0: + raise ValueError('x cannot be an empty array') + + # Make a shadow copy and convert to dict to align with dict processing. + ordered_dict_data = collections.OrderedDict({'__direct_np_input__': x}) + else: + x_type = type(x).__name__ + raise TypeError('x must be a dict or array; got {}'.format(x_type)) + + return ordered_dict_data + + +@estimator_export(v1=['estimator.inputs.numpy_input_fn']) +def numpy_input_fn(x, + y=None, + batch_size=128, + num_epochs=1, + shuffle=None, + queue_capacity=1000, + num_threads=1): + """Returns input function that would feed dict of numpy arrays into the model. + + This returns a function outputting `features` and `targets` based on the dict + of numpy arrays. The dict `features` has the same keys as the `x`. The dict + `targets` has the same keys as the `y` if `y` is a dict. + + Example: + + ```python + age = np.arange(4) * 1.0 + height = np.arange(32, 36) + x = {'age': age, 'height': height} + y = np.arange(-32, -28) + + with tf.Session() as session: + input_fn = numpy_io.numpy_input_fn( + x, y, batch_size=2, shuffle=False, num_epochs=1) + ``` + + Args: + x: numpy array object or dict of numpy array objects. If an array, the array + will be treated as a single feature. + y: numpy array object or dict of numpy array object. `None` if absent. + batch_size: Integer, size of batches to return. + num_epochs: Integer, number of epochs to iterate over data. If `None` will + run forever. + shuffle: Boolean, if True shuffles the queue. Avoid shuffle at prediction + time. + queue_capacity: Integer, size of queue to accumulate. + num_threads: Integer, number of threads used for reading and enqueueing. In + order to have predicted and repeatable order of reading and enqueueing, + such as in prediction and evaluation mode, `num_threads` should be 1. + + Returns: + Function, that has signature of ()->(dict of `features`, `targets`) + + Raises: + ValueError: if the shape of `y` mismatches the shape of values in `x` (i.e., + values in `x` have same shape). + ValueError: if duplicate keys are in both `x` and `y` when `y` is a dict. + ValueError: if x or y is an empty dict. + TypeError: `x` is not a dict or array. + ValueError: if 'shuffle' is not provided or a bool. + """ + if not isinstance(shuffle, bool): + raise ValueError('shuffle must be provided and explicitly set as boolean ' + '(it is recommended to set it as True for training); ' + 'got {}'.format(shuffle)) + + def input_fn(): + """Numpy input function.""" + + # Note that `x` should not be used after conversion to ordered_dict_data, + # as type could be either dict or array. + ordered_dict_data = _validate_and_convert_features(x) + + # Deep copy keys which is a view in python 3 + feature_keys = list(ordered_dict_data.keys()) + + if y is None: + target_keys = None + elif isinstance(y, dict): + if not y: + raise ValueError('y cannot be empty dict, use None instead.') + + ordered_dict_y = collections.OrderedDict( + sorted(y.items(), key=lambda t: t[0])) + target_keys = list(ordered_dict_y.keys()) + + duplicate_keys = set(feature_keys).intersection(set(target_keys)) + if duplicate_keys: + raise ValueError('{} duplicate keys are found in both x and y: ' + '{}'.format(len(duplicate_keys), duplicate_keys)) + + ordered_dict_data.update(ordered_dict_y) + else: + target_keys = _get_unique_target_key(ordered_dict_data) + ordered_dict_data[target_keys] = y + + if len(set(v.shape[0] for v in ordered_dict_data.values())) != 1: + shape_dict_of_x = {k: ordered_dict_data[k].shape for k in feature_keys} + + if target_keys is None: + shape_of_y = None + elif isinstance(target_keys, string_types): + shape_of_y = y.shape + else: + shape_of_y = {k: ordered_dict_data[k].shape for k in target_keys} + + raise ValueError('Length of tensors in x and y is mismatched. All ' + 'elements in x and y must have the same length.\n' + 'Shapes in x: {}\n' + 'Shapes in y: {}\n'.format(shape_dict_of_x, shape_of_y)) + + queue = feeding_functions._enqueue_data( # pylint: disable=protected-access + ordered_dict_data, + queue_capacity, + shuffle=shuffle, + num_threads=num_threads, + enqueue_size=batch_size, + num_epochs=num_epochs) + + batch = ( + queue.dequeue_many(batch_size) + if num_epochs is None else queue.dequeue_up_to(batch_size)) + + # Remove the first `Tensor` in `batch`, which is the row number. + if batch: + batch.pop(0) + + if isinstance(x, np.ndarray): + # Return as the same type as original array. + features = batch[0] + else: + # Return as the original dict type + features = dict(zip(feature_keys, batch[:len(feature_keys)])) + + if target_keys is None: + # TODO(martinwicke), return consistent result + return features + elif isinstance(target_keys, string_types): + target = batch[-1] + return features, target + else: + target = dict(zip(target_keys, batch[-len(target_keys):])) + return features, target + + return input_fn diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/inputs/pandas_io.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/inputs/pandas_io.py new file mode 100644 index 0000000000000000000000000000000000000000..4e5f3c9f7d753761fd243d10e77c831f0766c1a3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/inputs/pandas_io.py @@ -0,0 +1,158 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Methods to allow pandas.DataFrame.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import uuid +import numpy as np +import six +from tensorflow_estimator.python.estimator.estimator_export import estimator_export +from tensorflow_estimator.python.estimator.inputs.queues import feeding_functions + +try: + # pylint: disable=g-import-not-at-top + # pylint: disable=unused-import + import pandas as pd + HAS_PANDAS = True +except IOError: + # Pandas writes a temporary file during import. If it fails, don't use pandas. + HAS_PANDAS = False +except ImportError: + HAS_PANDAS = False + + +def _get_unique_target_key(features, target_column_name): + """Returns a key that does not exist in the input DataFrame `features`. + + Args: + features: DataFrame + target_column_name: Name of the target column as a `str` + + Returns: + A unique key that can be used to insert the target into + features. + """ + if target_column_name in features: + target_column_name += '_' + str(uuid.uuid4()) + return target_column_name + + +@estimator_export(v1=['estimator.inputs.pandas_input_fn']) +def pandas_input_fn(x, + y=None, + batch_size=128, + num_epochs=1, + shuffle=None, + queue_capacity=1000, + num_threads=1, + target_column='target'): + """Returns input function that would feed Pandas DataFrame into the model. + + Note: `y`'s index must match `x`'s index. + + Args: + x: pandas `DataFrame` object. + y: pandas `Series` object or `DataFrame`. `None` if absent. + batch_size: int, size of batches to return. + num_epochs: int, number of epochs to iterate over data. If not `None`, read + attempts that would exceed this value will raise `OutOfRangeError`. + shuffle: bool, whether to read the records in random order. + queue_capacity: int, size of the read queue. If `None`, it will be set + roughly to the size of `x`. + num_threads: Integer, number of threads used for reading and enqueueing. In + order to have predicted and repeatable order of reading and enqueueing, + such as in prediction and evaluation mode, `num_threads` should be 1. + target_column: str, name to give the target column `y`. This parameter is + not used when `y` is a `DataFrame`. + + Returns: + Function, that has signature of ()->(dict of `features`, `target`) + + Raises: + ValueError: if `x` already contains a column with the same name as `y`, or + if the indexes of `x` and `y` don't match. + ValueError: if 'shuffle' is not provided or a bool. + """ + if not HAS_PANDAS: + raise TypeError( + 'pandas_input_fn should not be called without pandas installed') + + if not isinstance(shuffle, bool): + raise ValueError('shuffle must be provided and explicitly set as boolean ' + '(it is recommended to set it as True for training); ' + 'got {}'.format(shuffle)) + + if not isinstance(target_column, six.string_types): + raise TypeError('target_column must be a string type') + + x = x.copy() + if y is not None: + if target_column in x: + raise ValueError( + 'Cannot use name %s for target column: DataFrame already has a ' + 'column with that name: %s' % (target_column, x.columns)) + if not np.array_equal(x.index, y.index): + raise ValueError('Index for x and y are mismatched.\nIndex for x: %s\n' + 'Index for y: %s\n' % (x.index, y.index)) + if isinstance(y, pd.DataFrame): + y_columns = [ + (column, _get_unique_target_key(x, column)) for column in list(y) + ] + target_column = [v for _, v in y_columns] + x[target_column] = y + else: + x[target_column] = y + + # TODO(mdan): These are memory copies. We probably don't need 4x slack space. + # The sizes below are consistent with what I've seen elsewhere. + if queue_capacity is None: + if shuffle: + queue_capacity = 4 * len(x) + else: + queue_capacity = len(x) + min_after_dequeue = max(queue_capacity / 4, 1) + + def input_fn(): + """Pandas input function.""" + queue = feeding_functions._enqueue_data( # pylint: disable=protected-access + x, + queue_capacity, + shuffle=shuffle, + min_after_dequeue=min_after_dequeue, + num_threads=num_threads, + enqueue_size=batch_size, + num_epochs=num_epochs) + if num_epochs is None: + features = queue.dequeue_many(batch_size) + else: + features = queue.dequeue_up_to(batch_size) + assert len(features) == len(x.columns) + 1, ('Features should have one ' + 'extra element for the index.') + features = features[1:] + features = dict(zip(list(x.columns), features)) + if y is not None: + if isinstance(target_column, list): + keys = [k for k, _ in y_columns] + values = [features.pop(column) for column in target_column] + target = {k: v for k, v in zip(keys, values)} + else: + target = features.pop(target_column) + return features, target + return features + + return input_fn diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/inputs/queues/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/inputs/queues/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/inputs/queues/feeding_functions.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/inputs/queues/feeding_functions.py new file mode 100644 index 0000000000000000000000000000000000000000..54e346ae4f101ddf946c10161e1d8c8cb2cc0536 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/inputs/queues/feeding_functions.py @@ -0,0 +1,504 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Helper functions for enqueuing data from arrays and pandas `DataFrame`s.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import collections +import random +import types as tp +import numpy as np +import six +import tensorflow as tf +from tensorflow.python.framework import ops +from tensorflow_estimator.python.estimator.inputs.queues import feeding_queue_runner as fqr + +try: + # pylint: disable=g-import-not-at-top + import pandas as pd + HAS_PANDAS = True +except IOError: + # Pandas writes a temporary file during import. If it fails, don't use pandas. + HAS_PANDAS = False +except ImportError: + HAS_PANDAS = False + + +def _fill_array(arr, seq, fillvalue=0): + """Recursively fills padded arr with elements from seq. + + If length of seq is less than arr padded length, fillvalue used. + Args: + arr: Padded tensor of shape [batch_size, ..., max_padded_dim_len]. + seq: Non-padded list of data samples of shape + [batch_size, ..., padded_dim(None)] + fillvalue: Default fillvalue to use. + """ + if arr.ndim == 1: + try: + len_ = len(seq) + except TypeError: + len_ = 0 + arr[:len_] = seq + arr[len_:] = fillvalue + else: + for subarr, subseq in six.moves.zip_longest(arr, seq, fillvalue=()): + _fill_array(subarr, subseq, fillvalue) + + +def _pad_if_needed(batch_key_item, fillvalue=0): + """ Returns padded batch. + + Args: + batch_key_item: List of data samples of any type with shape + [batch_size, ..., padded_dim(None)]. + fillvalue: Default fillvalue to use. + + Returns: + Padded with zeros tensor of same type and shape + [batch_size, ..., max_padded_dim_len]. + + Raises: + ValueError if data samples have different shapes (except last padded dim). + """ + shapes = [ + seq.shape[:-1] if len(seq.shape) > 0 else -1 for seq in batch_key_item + ] + if not all(shapes[0] == x for x in shapes): + raise ValueError("Array shapes must match.") + + last_length = [ + seq.shape[-1] if len(seq.shape) > 0 else 0 for seq in batch_key_item + ] + if all([x == last_length[0] for x in last_length]): + return batch_key_item + + batch_size = len(batch_key_item) + max_sequence_length = max(last_length) + result_batch = np.zeros( + shape=[batch_size] + list(shapes[0]) + [max_sequence_length], + dtype=batch_key_item[0].dtype) + _fill_array(result_batch, batch_key_item, fillvalue) + return result_batch + + +def _get_integer_indices_for_next_batch(batch_indices_start, batch_size, + epoch_end, array_length, current_epoch, + total_epochs): + """Returns the integer indices for next batch. + + If total epochs is not None and current epoch is the final epoch, the end + index of the next batch should not exceed the `epoch_end` (i.e., the final + batch might not have size `batch_size` to avoid overshooting the last epoch). + + Args: + batch_indices_start: Integer, the index to start next batch. + batch_size: Integer, size of batches to return. + epoch_end: Integer, the end index of the epoch. The epoch could start from a + random position, so `epoch_end` provides the end index for that. + array_length: Integer, the length of the array. + current_epoch: Integer, the epoch number has been emitted. + total_epochs: Integer or `None`, the total number of epochs to emit. If + `None` will run forever. + + Returns: + A tuple of a list with integer indices for next batch and `current_epoch` + value after the next batch. + + Raises: + OutOfRangeError if `current_epoch` is not less than `total_epochs`. + + """ + if total_epochs is not None and current_epoch >= total_epochs: + raise tf.errors.OutOfRangeError( + None, None, "Already emitted %s epochs." % current_epoch) + + batch_indices_end = batch_indices_start + batch_size + batch_indices = [ + j % array_length for j in range(batch_indices_start, batch_indices_end) + ] + epoch_end_indices = [i for i, x in enumerate(batch_indices) if x == epoch_end] + current_epoch += len(epoch_end_indices) + + if total_epochs is None or current_epoch < total_epochs: + return (batch_indices, current_epoch) + + # Now we might have emitted more data for expected epochs. Need to trim. + final_epoch_end_inclusive = epoch_end_indices[-(current_epoch - total_epochs + + 1)] + batch_indices = batch_indices[:final_epoch_end_inclusive + 1] + + return (batch_indices, total_epochs) + + +class _ArrayFeedFn(object): + """Creates feed dictionaries from numpy arrays.""" + + def __init__(self, + placeholders, + array, + batch_size, + random_start=False, + seed=None, + num_epochs=None): + if len(placeholders) != 2: + raise ValueError("_array_feed_fn expects 2 placeholders; got {}.".format( + len(placeholders))) + self._placeholders = placeholders + self._array = array + self._max = len(array) + self._batch_size = batch_size + self._num_epochs = num_epochs + self._epoch = 0 + random.seed(seed) + self._trav = random.randrange(self._max) if random_start else 0 + self._epoch_end = (self._trav - 1) % self._max + + def __call__(self): + integer_indexes, self._epoch = _get_integer_indices_for_next_batch( + batch_indices_start=self._trav, + batch_size=self._batch_size, + epoch_end=self._epoch_end, + array_length=self._max, + current_epoch=self._epoch, + total_epochs=self._num_epochs) + + self._trav = (integer_indexes[-1] + 1) % self._max + return { + self._placeholders[0]: integer_indexes, + self._placeholders[1]: self._array[integer_indexes] + } + + +class _OrderedDictNumpyFeedFn(object): + """Creates feed dictionaries from `OrderedDict`s of numpy arrays.""" + + def __init__(self, + placeholders, + ordered_dict_of_arrays, + batch_size, + random_start=False, + seed=None, + num_epochs=None): + if len(placeholders) != len(ordered_dict_of_arrays) + 1: + raise ValueError("Expected {} placeholders; got {}.".format( + len(ordered_dict_of_arrays), len(placeholders))) + self._index_placeholder = placeholders[0] + self._col_placeholders = placeholders[1:] + self._ordered_dict_of_arrays = ordered_dict_of_arrays + self._max = len(next(iter(ordered_dict_of_arrays.values()))) + for _, v in ordered_dict_of_arrays.items(): + if len(v) != self._max: + raise ValueError("Array lengths must match.") + self._batch_size = batch_size + self._num_epochs = num_epochs + self._epoch = 0 + random.seed(seed) + self._trav = random.randrange(self._max) if random_start else 0 + self._epoch_end = (self._trav - 1) % self._max + + def __call__(self): + integer_indexes, self._epoch = _get_integer_indices_for_next_batch( + batch_indices_start=self._trav, + batch_size=self._batch_size, + epoch_end=self._epoch_end, + array_length=self._max, + current_epoch=self._epoch, + total_epochs=self._num_epochs) + + self._trav = (integer_indexes[-1] + 1) % self._max + feed_dict = {self._index_placeholder: integer_indexes} + cols = [ + column[integer_indexes] + for column in self._ordered_dict_of_arrays.values() + ] + feed_dict.update(dict(zip(self._col_placeholders, cols))) + return feed_dict + + +class _PandasFeedFn(object): + """Creates feed dictionaries from pandas `DataFrames`.""" + + def __init__(self, + placeholders, + dataframe, + batch_size, + random_start=False, + seed=None, + num_epochs=None): + if len(placeholders) != len(dataframe.columns) + 1: + raise ValueError("Expected {} placeholders; got {}.".format( + len(dataframe.columns) + 1, len(placeholders))) + self._index_placeholder = placeholders[0] + self._col_placeholders = placeholders[1:] + self._dataframe = dataframe + self._max = len(dataframe) + self._batch_size = batch_size + self._num_epochs = num_epochs + self._epoch = 0 + random.seed(seed) + self._trav = random.randrange(self._max) if random_start else 0 + self._epoch_end = (self._trav - 1) % self._max + + def __call__(self): + integer_indexes, self._epoch = _get_integer_indices_for_next_batch( + batch_indices_start=self._trav, + batch_size=self._batch_size, + epoch_end=self._epoch_end, + array_length=self._max, + current_epoch=self._epoch, + total_epochs=self._num_epochs) + + self._trav = (integer_indexes[-1] + 1) % self._max + result = self._dataframe.iloc[integer_indexes] + cols = [result[col].values for col in result.columns] + feed_dict = dict(zip(self._col_placeholders, cols)) + feed_dict[self._index_placeholder] = result.index.values + return feed_dict + + +class _GeneratorFeedFn(object): + """Creates feed dictionaries from `Generator` of `dicts` of numpy arrays.""" + + def __init__(self, + placeholders, + generator, + batch_size, + random_start=False, + seed=None, + num_epochs=None, + pad_value=None): + first_sample = next(generator()) + if len(placeholders) != len(first_sample): + raise ValueError("Expected {} placeholders; got {}.".format( + len(first_sample), len(placeholders))) + self._keys = sorted(list(first_sample.keys())) + self._col_placeholders = placeholders + self._generator_function = generator + self._iterator = generator() + self._batch_size = batch_size + self._num_epochs = num_epochs + self._epoch = 0 + self._pad_value = pad_value + random.seed(seed) + + def __call__(self): + if self._num_epochs and self._epoch >= self._num_epochs: + raise tf.errors.OutOfRangeError( + None, None, "Already emitted %s epochs." % self._epoch) + list_dict = {} + list_dict_size = 0 + while list_dict_size < self._batch_size: + try: + data_row = next(self._iterator) + except StopIteration: + self._epoch += 1 + self._iterator = self._generator_function() + data_row = next(self._iterator) + for index, key in enumerate(self._keys): + if key not in data_row.keys(): + raise KeyError("key mismatch between dicts emitted by GenFun " + "Expected {} keys; got {}".format( + self._keys, data_row.keys())) + list_dict.setdefault(self._col_placeholders[index], + list()).append(data_row[key]) + list_dict_size += 1 + + if self._pad_value is not None: + feed_dict = { + key: np.asarray(_pad_if_needed(item, self._pad_value)) + for key, item in list(list_dict.items()) + } + else: + feed_dict = { + key: np.asarray(item) for key, item in list(list_dict.items()) + } + return feed_dict + + +def _enqueue_data(data, + capacity, + shuffle=False, + min_after_dequeue=None, + num_threads=1, + seed=None, + name="enqueue_input", + enqueue_size=1, + num_epochs=None, + pad_value=None): + """Creates a queue filled from a numpy array or pandas `DataFrame`. + + Returns a queue filled with the rows of the given (`OrderedDict` of) array + or `DataFrame`. In the case of a pandas `DataFrame`, the first enqueued + `Tensor` corresponds to the index of the `DataFrame`. For (`OrderedDict` of) + numpy arrays, the first enqueued `Tensor` contains the row number. + + Args: + data: a numpy `ndarray`, `OrderedDict` of numpy arrays, or a generator + yielding `dict`s of numpy arrays or pandas `DataFrame` that will be read + into the queue. + capacity: the capacity of the queue. + shuffle: whether or not to shuffle the rows of the array. + min_after_dequeue: minimum number of elements that can remain in the queue + after a dequeue operation. Only used when `shuffle` is true. If not set, + defaults to `capacity` / 4. + num_threads: number of threads used for reading and enqueueing. + seed: used to seed shuffling and reader starting points. + name: a scope name identifying the data. + enqueue_size: the number of rows to enqueue per step. + num_epochs: limit enqueuing to a specified number of epochs, if provided. + pad_value: default value for dynamic padding of data samples, if provided. + + Returns: + A queue filled with the rows of the given (`OrderedDict` of) array or + `DataFrame`. + + Raises: + TypeError: `data` is not a Pandas `DataFrame`, an `OrderedDict` of numpy + arrays, a numpy `ndarray`, or a generator producing these. + NotImplementedError: padding and shuffling data at the same time. + NotImplementedError: padding usage with non generator data type. + """ + with ops.name_scope(name): + if isinstance(data, np.ndarray): + types = [tf.dtypes.int64, tf.dtypes.as_dtype(data.dtype)] + queue_shapes = [(), data.shape[1:]] + get_feed_fn = _ArrayFeedFn + elif isinstance(data, collections.OrderedDict): + types = [tf.dtypes.int64 + ] + [tf.dtypes.as_dtype(col.dtype) for col in data.values()] + queue_shapes = [()] + [col.shape[1:] for col in data.values()] + get_feed_fn = _OrderedDictNumpyFeedFn + elif isinstance(data, tp.FunctionType): + x_first_el = six.next(data()) + x_first_keys = sorted(x_first_el.keys()) + x_first_values = [x_first_el[key] for key in x_first_keys] + types = [tf.dtypes.as_dtype(col.dtype) for col in x_first_values] + queue_shapes = [col.shape for col in x_first_values] + get_feed_fn = _GeneratorFeedFn + elif HAS_PANDAS and isinstance(data, pd.DataFrame): + types = [ + tf.dtypes.as_dtype(dt) + for dt in [data.index.dtype] + list(data.dtypes) + ] + queue_shapes = [() for _ in types] + get_feed_fn = _PandasFeedFn + else: + raise TypeError( + "data must be either a numpy array or pandas DataFrame if pandas is " + "installed; got {}".format(type(data).__name__)) + + pad_data = pad_value is not None + if pad_data and get_feed_fn is not _GeneratorFeedFn: + raise NotImplementedError( + "padding is only available with generator usage") + if shuffle and pad_data: + raise NotImplementedError( + "padding and shuffling data at the same time is not implemented") + + # TODO(jamieas): TensorBoard warnings for all warnings below once available. + + if num_threads > 1 and num_epochs is not None: + tf.compat.v1.logging.warn( + "enqueue_data was called with num_epochs and num_threads > 1. " + "num_epochs is applied per thread, so this will produce more " + "epochs than you probably intend. " + "If you want to limit epochs, use one thread.") + + if shuffle and num_threads > 1 and num_epochs is not None: + tf.compat.v1.logging.warn( + "enqueue_data was called with shuffle=True, num_threads > 1, and " + "num_epochs. This will create multiple threads, all reading the " + "array/dataframe in order adding to the same shuffling queue; the " + "results will likely not be sufficiently shuffled.") + + if not shuffle and num_threads > 1: + tf.compat.v1.logging.warn( + "enqueue_data was called with shuffle=False and num_threads > 1. " + "This will create multiple threads, all reading the " + "array/dataframe in order. If you want examples read in order, use" + " one thread; if you want multiple threads, enable shuffling.") + + if shuffle: + min_after_dequeue = int( + capacity / 4 if min_after_dequeue is None else min_after_dequeue) + queue = tf.queue.RandomShuffleQueue( + capacity, + min_after_dequeue, + dtypes=types, + shapes=queue_shapes, + seed=seed) + elif pad_data: + min_after_dequeue = 0 # just for the summary text + queue_shapes = list( + map(lambda x: tuple(list(x[:-1]) + [None]) + if len(x) > 0 else x, queue_shapes)) + queue = tf.queue.PaddingFIFOQueue( + capacity, dtypes=types, shapes=queue_shapes) + else: + min_after_dequeue = 0 # just for the summary text + queue = tf.queue.FIFOQueue(capacity, dtypes=types, shapes=queue_shapes) + + enqueue_ops = [] + feed_fns = [] + + for i in range(num_threads): + # Note the placeholders have no shapes, so they will accept any + # enqueue_size. enqueue_many below will break them up. + placeholders = [tf.compat.v1.placeholder(t) for t in types] + + enqueue_ops.append(queue.enqueue_many(placeholders)) + seed_i = None if seed is None else (i + 1) * seed + + if not pad_data: + feed_fns.append( + get_feed_fn( + placeholders, + data, + enqueue_size, + random_start=shuffle, + seed=seed_i, + num_epochs=num_epochs)) + else: + feed_fns.append( + get_feed_fn( + placeholders, + data, + enqueue_size, + random_start=shuffle, + seed=seed_i, + num_epochs=num_epochs, + pad_value=pad_value)) + + runner = fqr._FeedingQueueRunner( # pylint: disable=protected-access + queue=queue, + enqueue_ops=enqueue_ops, + feed_fns=feed_fns) + tf.compat.v1.train.queue_runner.add_queue_runner(runner) + + full = ( + tf.cast( + tf.math.maximum(0, + queue.size() - min_after_dequeue), + tf.dtypes.float32) * (1. / (capacity - min_after_dequeue))) + # Note that name contains a '/' at the end so we intentionally do not place + # a '/' after %s below. + summary_name = ( + "queue/%sfraction_over_%d_of_%d_full" % + (queue.name, min_after_dequeue, capacity - min_after_dequeue)) + tf.compat.v1.summary.scalar(summary_name, full) + return queue diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/inputs/queues/feeding_queue_runner.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/inputs/queues/feeding_queue_runner.py new file mode 100644 index 0000000000000000000000000000000000000000..fbab7a2ee05cac8ec5f29cc8ab25b0799f5788b4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/inputs/queues/feeding_queue_runner.py @@ -0,0 +1,184 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""A `QueueRunner` that takes a feed function as an argument.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import threading +import tensorflow as tf + + +class _FeedingQueueRunner(tf.compat.v1.train.queue_runner.QueueRunner): + """A queue runner that allows the feeding of values such as numpy arrays.""" + + def __init__(self, + queue=None, + enqueue_ops=None, + close_op=None, + cancel_op=None, + feed_fns=None, + queue_closed_exception_types=None): + """Initialize the queue runner. + + For further documentation, see `queue_runner.py`. Note that + `FeedingQueueRunner` does not support construction from protobuffer nor + serialization to protobuffer. + + Args: + queue: A `Queue`. + enqueue_ops: List of enqueue ops to run in threads later. + close_op: Op to close the queue. Pending enqueue ops are preserved. + cancel_op: Op to close the queue and cancel pending enqueue ops. + feed_fns: a list of functions that return a dictionary mapping fed + `Tensor`s to values. Must be the same length as `enqueue_ops`. + queue_closed_exception_types: Optional tuple of Exception types that + indicate that the queue has been closed when raised during an enqueue + operation. Defaults to `(tf.errors.OutOfRangeError, + tf.errors.CancelledError)`. + + Raises: + ValueError: `feed_fns` is not `None` and has different length than + `enqueue_ops`. + """ + if queue_closed_exception_types is None: + queue_closed_exception_types = (tf.errors.OutOfRangeError, + tf.errors.CancelledError) + super(_FeedingQueueRunner, self).__init__( + queue, + enqueue_ops, + close_op, + cancel_op, + queue_closed_exception_types=queue_closed_exception_types) + if feed_fns is None: + self._feed_fns = [None for _ in enqueue_ops] + else: + if len(feed_fns) != len(enqueue_ops): + raise ValueError( + "If feed_fns is not None, it must have the same length as " + "enqueue_ops.") + self._feed_fns = feed_fns + + # pylint: disable=broad-except + def _run(self, sess, enqueue_op, feed_fn, coord=None): + """Execute the enqueue op in a loop, close the queue in case of error. + + Args: + sess: A `Session`. + enqueue_op: The `Operation` to run. + feed_fn: the feed function to pass to `sess.run`. + coord: Optional `Coordinator` object for reporting errors and checking for + stop conditions. + """ + # TODO(jamieas): Reduce code duplication with `QueueRunner`. + if coord: + coord.register_thread(threading.current_thread()) + decremented = False + try: + while True: + if coord and coord.should_stop(): + break + try: + feed_dict = None if feed_fn is None else feed_fn() + sess.run(enqueue_op, feed_dict=feed_dict) + except (tf.errors.OutOfRangeError, tf.errors.CancelledError): + # This exception indicates that a queue was closed. + with self._lock: + self._runs_per_session[sess] -= 1 + decremented = True + if self._runs_per_session[sess] == 0: + try: + sess.run(self._close_op) + except Exception as e: + # Intentionally ignore errors from close_op. + tf.compat.v1.logging.vlog(1, "Ignored exception: %s", str(e)) + return + except Exception as e: + # This catches all other exceptions. + if coord: + coord.request_stop(e) + else: + tf.compat.v1.logging.error("Exception in QueueRunner: %s", str(e)) + with self._lock: + self._exceptions_raised.append(e) + raise + finally: + # Make sure we account for all terminations: normal or errors. + if not decremented: + with self._lock: + self._runs_per_session[sess] -= 1 + + def create_threads(self, sess, coord=None, daemon=False, start=False): + """Create threads to run the enqueue ops for the given session. + + This method requires a session in which the graph was launched. It creates + a list of threads, optionally starting them. There is one thread for each + op passed in `enqueue_ops`. + + The `coord` argument is an optional coordinator, that the threads will use + to terminate together and report exceptions. If a coordinator is given, + this method starts an additional thread to close the queue when the + coordinator requests a stop. + + If previously created threads for the given session are still running, no + new threads will be created. + + Args: + sess: A `Session`. + coord: Optional `Coordinator` object for reporting errors and checking + stop conditions. + daemon: Boolean. If `True` make the threads daemon threads. + start: Boolean. If `True` starts the threads. If `False` the caller must + call the `start()` method of the returned threads. + + Returns: + A list of threads. + """ + with self._lock: + try: + if self._runs_per_session[sess] > 0: + # Already started: no new threads to return. + return [] + except KeyError: + # We haven't seen this session yet. + pass + self._runs_per_session[sess] = len(self._enqueue_ops) + self._exceptions_raised = [] + + ret_threads = [ + threading.Thread(target=self._run, args=(sess, op, feed_fn, coord)) + for op, feed_fn in zip(self._enqueue_ops, self._feed_fns) + ] + if coord: + ret_threads.append( + threading.Thread( + target=self._close_on_stop, args=(sess, self._cancel_op, coord))) + for t in ret_threads: + if daemon: + t.daemon = True + if start: + t.start() + return ret_threads + + def _init_from_proto(self, queue_runner_def): + raise NotImplementedError( + "{} does not support initialization from proto.".format( + type(self).__name__)) + + def to_proto(self): + raise NotImplementedError( + "{} does not support serialization to proto.".format( + type(self).__name__)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/keras_lib.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/keras_lib.py new file mode 100644 index 0000000000000000000000000000000000000000..5406868ffb96b4cf8843ac32f2031457d484dbdf --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/keras_lib.py @@ -0,0 +1,806 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +# pylint: disable=protected-access +"""Home of estimator related functions.""" +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import collections +import os +import re +from absl import logging +import tensorflow as tf +from tensorflow.python.checkpoint import checkpoint as trackable_util +from tensorflow_estimator.python.estimator import estimator as estimator_lib +from tensorflow_estimator.python.estimator import model_fn as model_fn_lib +from tensorflow_estimator.python.estimator.export import export_lib +from tensorflow_estimator.python.estimator.mode_keys import ModeKeys + +_DEFAULT_SERVING_KEY = tf.saved_model.DEFAULT_SERVING_SIGNATURE_DEF_KEY + + +class FormattedKeyError(KeyError): + """KeyError with formatted error message. + + Python's `KeyError` has special casing around formatting + (see https://bugs.python.org/issue2651). Use this class when the error + message has newlines and other special format characters. + + Needed by https://github.com/tensorflow/tensorflow/issues/36857. + """ + + def __init__(self, message): + self.message = message + + def __str__(self): + return self.message + + +def _cast_tensor_to_floatx(x): + """Cast tensor to keras's floatx dtype if it is not already the same dtype.""" + if x.dtype == tf.keras.backend.floatx(): + return x + else: + return tf.cast(x, tf.keras.backend.floatx()) + + +def _convert_tensor(x): + """Create or cast tensor if needed.""" + if not tf.is_tensor(x): + # x is a numpy array + x = tf.compat.v1.convert_to_tensor_or_sparse_tensor(x) + return x + + +def _any_weight_initialized(keras_model): + """Check if any weights has been initialized in the Keras model. + + Args: + keras_model: An instance of compiled keras model. + + Returns: + boolean, True if at least one weight has been initialized, else False. + Currently keras initialize all weights at get_session(). + """ + if keras_model is None: + return False + if tf.compat.v1.executing_eagerly_outside_functions(): + return True + for layer in keras_model.layers: + for weight in layer.weights: + if hasattr(weight, '_keras_initialized'): + return True + return False + + +def _convert_estimator_io_to_keras(keras_model, features, labels): + """Converts estimator features and labels to keras input and target tensors. + + Args: + keras_model: a compiled `tf.keras.Model` instance, used to determine the + order of the returned lists. + features: Dict of tensors or `None`. + labels: Dict of tensors, a single tensor, or `None`. + + Returns: + Tuple of ( + list of input tensors or `None`, + list of target tensors or `None`, + list of sample weight tensors or `None`) + The order of tensors is determined by the order set in the keras model. + """ + + def _to_ordered_tensor_list(obj, key_order, obj_name, order_name): + """Convert obj to an ordered list of tensors. + + Args: + obj: List, dict, or single tensor. May be `None`. + key_order: List of strings with the order to return (used if obj is a + dict). + obj_name: String name of object (e.g. "features" or "labels") + order_name: String name of the key order (e.g. "inputs" or "outputs") + + Returns: + List of tensors, or `None` + + Raises: + KeyError: If obj has invalid keys. + """ + if obj is None: + return None + elif isinstance(obj, (list, tuple)): + return [_convert_tensor(x) for x in obj] + elif isinstance(obj, dict): + # Ensure that keys in key_order are contained in obj keys. + # One can provide more data keys described in obj, as long as the keys + # requested by model are provided. + different_keys = set(key_order) - set(obj.keys()) + + if different_keys: + raise FormattedKeyError( + 'The dictionary passed into {obj_name} does not cover requested ' + '{order_name} keys defined in the keras model.' + '\n\tExpected keys: {order_keys}' + '\n\t{obj_name} keys: {obj_keys}' + '\n\tMissed keys: {different_keys}'.format( + order_name=order_name, + order_keys=set(key_order), + obj_name=obj_name, + obj_keys=set(obj.keys()), + different_keys=different_keys)) + + return [_convert_tensor(obj[key]) for key in key_order] + else: # Assume obj is a tensor. + return [_convert_tensor(obj)] + + features, sample_weight_tensors = _extract_sample_weight_tensors(features) + input_names = None + output_names = None + if isinstance(features, dict): + input_names = ( + keras_model.input_names if keras_model._is_graph_network else + ['input_%d' % i for i in range(1, + len(features) + 1)]) + if isinstance(labels, dict): + output_names = ( + keras_model.output_names if keras_model._is_graph_network else + ['output_%d' % i for i in range(1, + len(labels) + 1)]) + + if isinstance(keras_model.inputs, dict): + # Keep input tensors as a dict if keras_model is built with dict input. + input_tensors = { + k: _convert_tensor(features[k]) + for (k, v) in keras_model.inputs.items() + } + elif keras_model.inputs is None and isinstance(features, dict): + # Keep input tensors as a dict if keras_model input structure is unknown. + input_tensors = {k: _convert_tensor(v) for (k, v) in features.items()} + else: + # converting input tensors into sorted list. + input_tensors = _to_ordered_tensor_list(features, input_names, 'features', + 'inputs') + target_tensors = _to_ordered_tensor_list(labels, output_names, 'labels', + 'outputs') + + return input_tensors, target_tensors, sample_weight_tensors + + +def _extract_sample_weight_tensors(features): + if isinstance(features, dict) and set( + features.keys()) == {'features', 'sample_weights'}: + feature_tensor = features['features'] + sample_weight_tensors = features['sample_weights'] + else: + feature_tensor = features + sample_weight_tensors = None + return feature_tensor, sample_weight_tensors + + +def _clone_and_build_model(mode, + keras_model, + custom_objects, + features=None, + labels=None, + optimizer_config=None): + """Clone and build the given keras_model. + + Args: + mode: training mode. + keras_model: an instance of compiled keras model. + custom_objects: Dictionary for custom objects. + features: Dict of tensors. + labels: Dict of tensors, or single tensor instance. + optimizer_config: Optimizer config dictionary, returned by + `optimizer.get_config()`. This is used when cloning a model with an + optimizer. Since `_clone_and_build_model` is called in a different graph + and session from the model, `optimizer.get_config()` may raise an error + during the attempt to serialize the optimizer hyperparameter values. + + Returns: + The newly built model. + """ + # Set to True during training, False for inference or testing. + tf.keras.backend.set_learning_phase(mode == ModeKeys.TRAIN) + input_tensors, target_tensors, sample_weight_tensors = ( + _convert_estimator_io_to_keras(keras_model, features, labels)) + + compile_clone = (mode != ModeKeys.PREDICT) + + global_step = None + if compile_clone: + # Set iterations to the global step created by tf.train.create_global_step() + # which is automatically run in the estimator framework. + global_step = tf.compat.v1.train.get_or_create_global_step() + tf.compat.v2.keras.__internal__.backend.track_variable(global_step) + + clone = tf.compat.v2.keras.__internal__.models.clone_and_build_model( + keras_model, + input_tensors, + target_tensors, + custom_objects, + compile_clone=compile_clone, + in_place_reset=(not keras_model._is_graph_network), + optimizer_iterations=global_step, + optimizer_config=optimizer_config) + + if sample_weight_tensors is not None: + sample_weight_tensors = standardize_sample_weights( + sample_weight_tensors, clone.output_names) + # Update calculated loss (model.total_loss) to include sample weights. + clone._compile_weights_loss_and_weighted_metrics(sample_weight_tensors) + return clone + + +def _convert_keras_metrics_to_estimator(model, metric_names_map=None): + """Convert metrics from a Keras model to ops used by the Estimator framework. + + Args: + model: A `tf.keras.Model` object. + metric_names_map: Optional dictionary mapping Keras model output metric + names to custom names. + + Returns: + Dictionary mapping metric names to tuples of (value, update) ops. May return + `None` if the model does not contain any metrics. + """ + if not getattr(model, '_compile_metrics', None): + return None + + # We are not using model.metrics here because we want to exclude the metrics + # added using `add_metric` API. + compiled_metrics = model._compile_metric_functions + + if metric_names_map: + custom_map_keys = set(metric_names_map.keys()) + expected_keys = {m.name for m in compiled_metrics} + unknown = expected_keys.difference(custom_map_keys) + if unknown: + raise ValueError( + 'Invalid `metric_names_map`. ' + 'The following keras model metric names:"{}" do not exist in ' + 'the `metric_names_map` dictionary'.format(list(unknown))) + + extra = custom_map_keys.difference(expected_keys) + if extra: + raise ValueError('Invalid `metric_names_map`. ' + 'There are unexpected keys in the `metric_names_map` ' + 'dictionary. Expected keys: {}, Received: {}'.format( + list(expected_keys), list(extra))) + + return {metric_names_map[m.name]: m for m in compiled_metrics} + else: + return {m.name: m for m in compiled_metrics} + + +def _create_keras_model_fn(keras_model, + custom_objects=None, + save_object_ckpt=False, + metric_names_map=None, + export_outputs=None): + """Creates model_fn for keras Estimator. + + Args: + keras_model: an instance of compiled keras model. + custom_objects: Dictionary for custom objects. + save_object_ckpt: Whether to save an object-based checkpoint. + metric_names_map: Optional dictionary mapping Keras model output metric + names to custom names. + export_outputs: Optional dictionary mapping custom names to a subclass of + `tf.estimator.export.ExportOutput`. + + Returns: + The model_fn for a keras Estimator. + """ + if isinstance(keras_model.optimizer, + tf.keras.optimizers.experimental.Optimizer): + # Experimental optimizer cannot work with estimator, so we convert it to + # legacy optimizer. + if tf.executing_eagerly(): + logging.warning( + 'You are using `tf.keras.optimizers.experimental.Optimizer` in TF ' + 'estimator, which only supports ' + '`tf.keras.optimizers.legacy.Optimizer`. Automatically converting ' + 'your optimizer to `tf.keras.optimizers.legacy.Optimizer`.') + opt = tf.keras.__internal__.optimizers.convert_to_legacy_optimizer( + keras_model.optimizer) + keras_model.optimizer = opt + else: + raise ValueError('Please set your optimizer as an instance of ' + '`tf.keras.optimizers.legacy.Optimizer`, e.g., ' + '`tf.keras.optimizers.legacy.Adam`. Received optimizer ' + f'type: {type(keras_model.optimizer)}.') + # Get optimizer config in the current context (since model_fn is called in the + # estimator graph and session). OptimizerV2 objects serialize variable/tensor + # hyperparameters in their configs, resulting to wrong-session errors during + # model cloning. + try: + if isinstance(keras_model.optimizer, (tuple, list)): + optimizer_config = [opt.get_config() for opt in keras_model.optimizer] + else: + optimizer_config = keras_model.optimizer.get_config() + except (NotImplementedError, AttributeError): + # TFOptimizers and other custom optimizers do not have a config. + optimizer_config = None + + def model_fn(features, labels, mode): + """model_fn for keras Estimator.""" + model = _clone_and_build_model( + mode=mode, + keras_model=keras_model, + custom_objects=custom_objects, + features=features, + labels=labels, + optimizer_config=optimizer_config) + model_output_names = [] + # We need to make sure that the output names of the last layer in the model + # is the same for each of the cloned models. This is required for mirrored + # strategy when we call regroup. + if tf.distribute.has_strategy(): + for name in model.output_names: + name = re.compile(r'_\d$').sub('', name) + model_output_names.append(name) + else: + model_output_names = model.output_names + + # Get inputs to EstimatorSpec + predictions = dict(zip(model_output_names, model.outputs)) + + loss = None + train_op = None + eval_metric_ops = None + + # Set loss and metric only during train and evaluate. + if mode is not ModeKeys.PREDICT: + if mode is ModeKeys.TRAIN: + model._make_train_function() # pylint: disable=protected-access + else: + model._make_test_function() # pylint: disable=protected-access + loss = model.total_loss + + eval_metric_ops = _convert_keras_metrics_to_estimator( + model, metric_names_map) + + # Set train_op only during train. + if mode is ModeKeys.TRAIN: + train_op = model.train_function.updates_op + + if (not model._is_graph_network and + hasattr(keras_model, '_original_attributes_cache') and + keras_model._original_attributes_cache is not None): + # To avoid `model_fn` being destructive for the initial model argument. + (tf.compat.v2.keras.__internal__.models. + in_place_subclassed_model_state_restoration(keras_model)) + + scaffold = None + if save_object_ckpt: + model._track_trackable(tf.compat.v1.train.get_global_step(), + 'estimator_global_step') + # Create saver that maps variable names to object-checkpoint keys. + object_graph = tf.compat.v2.__internal__.tracking.ObjectGraphView(model) + var_list = object_graph.frozen_saveable_objects() + saver = tf.compat.v1.train.Saver(var_list=var_list, sharded=True) + saver._object_restore_saver = trackable_util.frozen_saver(model) + scaffold = tf.compat.v1.train.Scaffold(saver=saver) + + final_export_outputs = { + _DEFAULT_SERVING_KEY: export_lib.PredictOutput(predictions) + } + if export_outputs is not None: + different_keys = set(export_outputs.keys()) - set(model.output_names) + if different_keys: + raise FormattedKeyError( + 'The list passed into {obj_name} does not cover requested ' + '{order_name} keys defined in the keras model.' + '\n\tExpected keys: {order_keys}' + '\n\t{obj_name} keys: {obj_keys}' + '\n\tMissed keys: {different_keys}'.format( + order_name=export_outputs, + order_keys=set(export_outputs.keys()), + obj_name=model.output_names, + obj_keys=set(model.output_names), + different_keys=different_keys)) + for key, export_output_cls in export_outputs.items(): + final_export_outputs[key] = export_output_cls(predictions[key]) + + return model_fn_lib.EstimatorSpec( + mode=mode, + predictions=predictions, + loss=loss, + train_op=train_op, + eval_metric_ops=eval_metric_ops, + export_outputs=final_export_outputs, + scaffold=scaffold) + + return model_fn + + +def _save_first_checkpoint(keras_model, custom_objects, config, + save_object_ckpt): + """Save first checkpoint for the keras Estimator. + + Args: + keras_model: an instance of compiled keras model. + custom_objects: Dictionary for custom objects. + config: Estimator config. + save_object_ckpt: Whether to save an object-based checkpoint. + + Returns: + The path where keras model checkpoint is saved. + """ + # save checkpoint into subdirectory to allow warm start + keras_model_dir = os.path.join(config.model_dir, 'keras') + # Load weights and save to checkpoint if there is no checkpoint + latest_path = tf.train.latest_checkpoint(keras_model_dir) + if not latest_path: + keras_weights = None + if _any_weight_initialized(keras_model): + keras_weights = keras_model.get_weights() + if not tf.compat.v1.gfile.IsDirectory(keras_model_dir): + tf.compat.v1.gfile.MakeDirs(keras_model_dir) + with tf.Graph().as_default(): + tf.compat.v1.random.set_random_seed(config.tf_random_seed) + tf.compat.v1.train.create_global_step() + model = _clone_and_build_model(ModeKeys.TRAIN, keras_model, + custom_objects) + + # Init the train_function outside of the context of session. This is due + # to the fact that train function will update the graph by adding backprop + # parts. This will potentially trying to update the node in forward graph + # which will fail if it is done within same session. + # Always create the train_function here since the model is just cloned. + # See https://github.com/tensorflow/tensorflow/issues/27750 for details. + model._make_train_function() # pylint: disable=protected-access + + # save to checkpoint + with tf.compat.v1.Session(config=config.session_config) as sess: + if keras_weights: + model.set_weights(keras_weights) + # model._make_train_function() will potentially create the optimizer + # variable, which will require another variable initialization. + tf.compat.v2.keras.__internal__.backend.initialize_variables(sess) + + if save_object_ckpt: + model._track_trackable( # pylint: disable=protected-access + tf.compat.v1.train.get_global_step(), 'estimator_global_step') + latest_path = os.path.join(keras_model_dir, 'keras_model.ckpt') + model.save_weights(latest_path) + else: + saver = tf.compat.v1.train.Saver() + latest_path = os.path.join(keras_model_dir, 'keras_model.ckpt') + saver.save(sess, latest_path) + + return latest_path + + +def _get_file_from_google_storage(keras_model_path, model_dir): + """Get file from google storage and download to local file. + + Args: + keras_model_path: a google storage path for compiled keras model. + model_dir: the directory from estimator config. + + Returns: + The path where keras model is saved. + + Raises: + ValueError: if storage object name does not end with .h5. + """ + try: + from google.cloud import storage # pylint:disable=g-import-not-at-top + except ImportError: + raise TypeError('Could not save model to Google cloud storage; please ' + 'install `google-cloud-storage` via ' + '`pip install google-cloud-storage`.') + storage_client = storage.Client() + path, blob_name = os.path.split(keras_model_path) + _, bucket_name = os.path.split(path) + keras_model_dir = os.path.join(model_dir, 'keras') + if not tf.compat.v1.gfile.Exists(keras_model_dir): + tf.compat.v1.gfile.MakeDirs(keras_model_dir) + file_name = os.path.join(keras_model_dir, 'keras_model.h5') + try: + blob = storage_client.get_bucket(bucket_name).blob(blob_name) + blob.download_to_filename(file_name) + except: + raise ValueError('Failed to download keras model, please check ' + 'environment variable GOOGLE_APPLICATION_CREDENTIALS ' + 'and model path storage.googleapis.com/{bucket}/{object}.') + tf.compat.v1.logging.info('Saving model to {}'.format(file_name)) + del storage_client + return file_name + + +def model_to_estimator(keras_model=None, + keras_model_path=None, + custom_objects=None, + model_dir=None, + config=None, + checkpoint_format=None, + use_v2_estimator=False, + metric_names_map=None, + export_outputs=None): + """Constructs an `Estimator` instance from given keras model. + + If you use infrastructure or other tooling that relies on Estimators, you can + still build a Keras model and use model_to_estimator to convert the Keras + model to an Estimator for use with downstream systems. + + For usage example, please see: + [Creating estimators from Keras + Models](https://www.tensorflow.org/guide/estimator#create_an_estimator_from_a_keras_model). + + Sample Weights: + Estimators returned by `model_to_estimator` are configured so that they can + handle sample weights (similar to `keras_model.fit(x, y, sample_weights)`). + + To pass sample weights when training or evaluating the Estimator, the first + item returned by the input function should be a dictionary with keys + `features` and `sample_weights`. Example below: + + ```python + keras_model = tf.keras.Model(...) + keras_model.compile(...) + + estimator = tf.keras.estimator.model_to_estimator(keras_model) + + def input_fn(): + return dataset_ops.Dataset.from_tensors( + ({'features': features, 'sample_weights': sample_weights}, + targets)) + + estimator.train(input_fn, steps=1) + ``` + + Example with customized export signature: + ```python + inputs = {'a': tf.keras.Input(..., name='a'), + 'b': tf.keras.Input(..., name='b')} + outputs = {'c': tf.keras.layers.Dense(..., name='c')(inputs['a']), + 'd': tf.keras.layers.Dense(..., name='d')(inputs['b'])} + keras_model = tf.keras.Model(inputs, outputs) + keras_model.compile(...) + export_outputs = {'c': tf.estimator.export.RegressionOutput, + 'd': tf.estimator.export.ClassificationOutput} + + estimator = tf.keras.estimator.model_to_estimator( + keras_model, export_outputs=export_outputs) + + def input_fn(): + return dataset_ops.Dataset.from_tensors( + ({'features': features, 'sample_weights': sample_weights}, + targets)) + + estimator.train(input_fn, steps=1) + ``` + + Note: We do not support creating weighted metrics in Keras and converting them + to weighted metrics in the Estimator API using `model_to_estimator`. + You will have to create these metrics directly on the estimator spec using the + `add_metrics` function. + + Args: + keras_model: A compiled Keras model object. This argument is mutually + exclusive with `keras_model_path`. Estimator's `model_fn` uses the + structure of the model to clone the model. Defaults to `None`. + keras_model_path: Path to a compiled Keras model saved on disk, in HDF5 + format, which can be generated with the `save()` method of a Keras model. + This argument is mutually exclusive with `keras_model`. + Defaults to `None`. + custom_objects: Dictionary for cloning customized objects. This is + used with classes that is not part of this pip package. For example, if + user maintains a `relu6` class that inherits from `tf.keras.layers.Layer`, + then pass `custom_objects={'relu6': relu6}`. Defaults to `None`. + model_dir: Directory to save `Estimator` model parameters, graph, summary + files for TensorBoard, etc. If unset a directory will be created with + `tempfile.mkdtemp` + config: `RunConfig` to config `Estimator`. Allows setting up things in + `model_fn` based on configuration such as `num_ps_replicas`, or + `model_dir`. Defaults to `None`. If both `config.model_dir` and the + `model_dir` argument (above) are specified the `model_dir` **argument** + takes precedence. + checkpoint_format: Sets the format of the checkpoint saved by the estimator + when training. May be `saver` or `checkpoint`, depending on whether to + save checkpoints from `tf.compat.v1.train.Saver` or `tf.train.Checkpoint`. + The default is `checkpoint`. Estimators use name-based `tf.train.Saver` + checkpoints, while Keras models use object-based checkpoints from + `tf.train.Checkpoint`. Currently, saving object-based checkpoints from + `model_to_estimator` is only supported by Functional and Sequential + models. + use_v2_estimator: Whether to convert the model to a V2 Estimator or V1 + Estimator. Defaults to `False`. + metric_names_map: Optional dictionary mapping Keras model output metric + names to custom names. This can be used to override the default Keras + model output metrics names in a multi IO model use case and provide custom + names for the `eval_metric_ops` in Estimator. + The Keras model metric names can be obtained using `model.metrics_names` + excluding any loss metrics such as total loss and output losses. + For example, if your Keras model has two outputs `out_1` and `out_2`, + with `mse` loss and `acc` metric, then `model.metrics_names` will be + `['loss', 'out_1_loss', 'out_2_loss', 'out_1_acc', 'out_2_acc']`. + The model metric names excluding the loss metrics will be + `['out_1_acc', 'out_2_acc']`. + export_outputs: Optional dictionary. This can be used to override the + default Keras model output exports in a multi IO model use case and + provide custom names for the `export_outputs` in + `tf.estimator.EstimatorSpec`. Default is None, which is equivalent to + {'serving_default': `tf.estimator.export.PredictOutput`}. + A dict `{name: output}` where: + * name: An arbitrary name for this output. This becomes the signature + name in the SavedModel. + * output: an `ExportOutput` object such as `ClassificationOutput`, + `RegressionOutput`, or `PredictOutput`. Single-headed models only need + to specify one entry in this dictionary. Multi-headed models should + specify one entry for each head, one of which must be named using + `tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY`. + If no entry is provided, a default `PredictOutput` mapping to + `predictions` will be created. + + Returns: + An Estimator from given keras model. + + Raises: + ValueError: If neither keras_model nor keras_model_path was given. + ValueError: If both keras_model and keras_model_path was given. + ValueError: If the keras_model_path is a GCS URI. + ValueError: If keras_model has not been compiled. + ValueError: If an invalid checkpoint_format was given. + """ + + if not (keras_model or keras_model_path): + raise ValueError( + 'Either `keras_model` or `keras_model_path` needs to be provided.') + if keras_model and keras_model_path: + raise ValueError( + 'Please specity either `keras_model` or `keras_model_path`, ' + 'but not both.') + + if keras_model: + _assert_valid_model(keras_model, custom_objects) + + config = estimator_lib.maybe_overwrite_model_dir_and_session_config( + config, model_dir) + if not keras_model: + if keras_model_path.startswith( + 'gs://') or 'storage.googleapis.com' in keras_model_path: + keras_model_path = _get_file_from_google_storage(keras_model_path, + config.model_dir) + tf.compat.v1.logging.info('Loading models from %s', keras_model_path) + keras_model = tf.keras.models.load_model(keras_model_path) + else: + tf.compat.v1.logging.info('Using the Keras model provided.') + keras_model = keras_model + + if checkpoint_format is None or checkpoint_format == 'checkpoint': + if not (keras_model._is_graph_network or + isinstance(keras_model, tf.keras.models.Sequential)): + raise ValueError('Object-based checkpoints are currently not supported ' + 'with subclassed models.') + save_object_ckpt = True + elif checkpoint_format == 'saver': + save_object_ckpt = False + else: + raise ValueError( + 'Checkpoint format must be one of "checkpoint" or "saver". Got {}' + .format(checkpoint_format)) + + if not hasattr(keras_model, 'optimizer') or not keras_model.optimizer: + raise ValueError('The given keras model has not been compiled yet. ' + 'Please compile the model with `model.compile()` ' + 'before calling `model_to_estimator()`.') + keras_model_fn = _create_keras_model_fn( + keras_model, custom_objects, save_object_ckpt, metric_names_map, + export_outputs) + if _any_weight_initialized(keras_model): + # Warn if config passed to estimator tries to update GPUOptions. If a + # session has already been created, the GPUOptions passed to the first + # session sticks. + if config.session_config.HasField('gpu_options'): + tf.compat.v1.logging.warn( + 'The Keras backend session has already been set. ' + 'The _session_config passed to model_to_estimator will not be used.') + else: + # Pass the config into keras backend's default session. + sess = tf.compat.v1.Session(config=config.session_config) + tf.compat.v1.keras.backend.set_session(sess) + + warm_start_path = None + if keras_model._is_graph_network and config.is_chief: + warm_start_path = _save_first_checkpoint(keras_model, custom_objects, + config, save_object_ckpt) + elif keras_model.built: + tf.compat.v1.logging.warn( + 'You are creating an Estimator from a Keras model manually ' + 'subclassed from `Model`, that was already called on some ' + 'inputs (and thus already had weights). We are currently ' + 'unable to preserve the model\'s state (its weights) as ' + 'part of the estimator in this case. Be warned that the ' + 'estimator has been created using a freshly initialized ' + 'version of your model.\n' + 'Note that this doesn\'t affect the state of the model ' + 'instance you passed as `keras_model` argument.') + if use_v2_estimator: + estimator_cls = estimator_lib.EstimatorV2 + else: + estimator_cls = estimator_lib.Estimator + + estimator = estimator_cls( + keras_model_fn, config=config, warm_start_from=warm_start_path) + + return estimator + + +def _assert_valid_model(model, custom_objects=None): + is_subclass = (not model._is_graph_network and + not isinstance(model, tf.keras.models.Sequential)) + if is_subclass: + try: + custom_objects = custom_objects or {} + with tf.keras.utils.CustomObjectScope(custom_objects): + model.__class__.from_config(model.get_config()) + except NotImplementedError: + raise ValueError( + 'Subclassed `Model`s passed to `model_to_estimator` must ' + 'implement `Model.get_config` and `Model.from_config`.') + + +def standardize_sample_weights(x_weight, output_names): + """Maps `sample_weight` or `class_weight` to model outputs. + + Args: + x_weight: User-provided `sample_weight` or `class_weight` argument. + output_names: List of output names (strings) in the model. + + Returns: + A list of `sample_weight` or `class_weight` where there are exactly + one element per model output. + + Raises: + ValueError: In case of invalid user-provided argument. + """ + if x_weight is None or (isinstance(x_weight, (list, tuple)) and + len(x_weight) == 0): # pylint: disable=g-explicit-length-test + return [None for _ in output_names] + if len(output_names) == 1: + if isinstance(x_weight, (list, tuple)) and len(x_weight) == 1: + return x_weight + if isinstance(x_weight, dict) and output_names[0] in x_weight: + return [x_weight[output_names[0]]] + else: + return [x_weight] + if isinstance(x_weight, (list, tuple)): + if len(x_weight) != len(output_names): + raise ValueError('Provided `sample_weights` was a list of ' + + str(len(x_weight)) + ' elements, but the model has ' + + str(len(output_names)) + ' outputs. ' + 'You should provide one `sample_weights`' + 'array per model output.') + return x_weight + if isinstance(x_weight, collections.abc.Mapping): + unknown = set(x_weight.keys()).difference(output_names) + if unknown: + raise ValueError('Unknown entries in sample_weights dictionary: {}. ' + 'Only expected following keys: {}'.format( + list(unknown), output_names)) + x_weights = [] + for name in output_names: + x_weights.append(x_weight.get(name)) + return x_weights + else: + raise TypeError('The model has multiple outputs, so `sample_weights` ' + 'should be either a list or a dict. ' + 'Provided `sample_weights` type not understood: ' + + str(x_weight)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/mode_keys.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/mode_keys.py new file mode 100644 index 0000000000000000000000000000000000000000..5c9f13118761f829178b92941175a1b73902fa96 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/mode_keys.py @@ -0,0 +1,24 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Exporting ModeKeys to tf.estimator namespace.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +from tensorflow.python.saved_model.model_utils.mode_keys import EstimatorModeKeys as ModeKeys +from tensorflow_estimator.python.estimator.estimator_export import estimator_export + +estimator_export('estimator.ModeKeys')(ModeKeys) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/model_fn.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/model_fn.py new file mode 100644 index 0000000000000000000000000000000000000000..6b221c04ac10ad14f4a52b753ad0c2e121236e31 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/model_fn.py @@ -0,0 +1,630 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Classes and methods related to model_fn.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import collections + +import six +import tensorflow as tf +from tensorflow.python.saved_model import model_utils as export_utils +from tensorflow.python.tpu import tensor_tracer +from tensorflow.python.util import function_utils +from tensorflow_estimator.python.estimator.estimator_export import estimator_export +from tensorflow_estimator.python.estimator.mode_keys import ModeKeys + +LOSS_METRIC_KEY = 'loss' +AVERAGE_LOSS_METRIC_KEY = 'average_loss' + + +@estimator_export('estimator.EstimatorSpec') +class EstimatorSpec( + collections.namedtuple('EstimatorSpec', [ + 'mode', 'predictions', 'loss', 'train_op', 'eval_metric_ops', + 'export_outputs', 'training_chief_hooks', 'training_hooks', 'scaffold', + 'evaluation_hooks', 'prediction_hooks' + ])): + """Ops and objects returned from a `model_fn` and passed to an `Estimator`. + + `EstimatorSpec` fully defines the model to be run by an `Estimator`. + """ + + def __new__(cls, + mode, + predictions=None, + loss=None, + train_op=None, + eval_metric_ops=None, + export_outputs=None, + training_chief_hooks=None, + training_hooks=None, + scaffold=None, + evaluation_hooks=None, + prediction_hooks=None): + """Creates a validated `EstimatorSpec` instance. + + Depending on the value of `mode`, different arguments are required. Namely + + * For `mode == ModeKeys.TRAIN`: required fields are `loss` and `train_op`. + * For `mode == ModeKeys.EVAL`: required field is `loss`. + * For `mode == ModeKeys.PREDICT`: required fields are `predictions`. + + model_fn can populate all arguments independent of mode. In this case, some + arguments will be ignored by an `Estimator`. E.g. `train_op` will be + ignored in eval and infer modes. Example: + + ```python + def my_model_fn(features, labels, mode): + predictions = ... + loss = ... + train_op = ... + return tf.estimator.EstimatorSpec( + mode=mode, + predictions=predictions, + loss=loss, + train_op=train_op) + ``` + + Alternatively, model_fn can just populate the arguments appropriate to the + given mode. Example: + + ```python + def my_model_fn(features, labels, mode): + if (mode == tf.estimator.ModeKeys.TRAIN or + mode == tf.estimator.ModeKeys.EVAL): + loss = ... + else: + loss = None + if mode == tf.estimator.ModeKeys.TRAIN: + train_op = ... + else: + train_op = None + if mode == tf.estimator.ModeKeys.PREDICT: + predictions = ... + else: + predictions = None + + return tf.estimator.EstimatorSpec( + mode=mode, + predictions=predictions, + loss=loss, + train_op=train_op) + ``` + + Args: + mode: A `ModeKeys`. Specifies if this is training, evaluation or + prediction. + predictions: Predictions `Tensor` or dict of `Tensor`. + loss: Training loss `Tensor`. Must be either scalar, or with shape `[1]`. + train_op: Op for the training step. + eval_metric_ops: Dict of metric results keyed by name. + The values of the dict can be one of the following: (1) instance of + `Metric` class. (2) Results of calling a metric function, namely a + `(metric_tensor, update_op)` tuple. `metric_tensor` should be + evaluated without any impact on state (typically is a pure computation + results based on variables.). For example, it should not trigger the + `update_op` or requires any input fetching. + export_outputs: Describes the output signatures to be exported to + `SavedModel` and used during serving. + A dict `{name: output}` where: + * name: An arbitrary name for this output. + * output: an `ExportOutput` object such as `ClassificationOutput`, + `RegressionOutput`, or `PredictOutput`. Single-headed models only need + to specify one entry in this dictionary. Multi-headed models should + specify one entry for each head, one of which must be named using + `tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY`. + If no entry is provided, a default `PredictOutput` mapping to + `predictions` will be created. + training_chief_hooks: Iterable of `tf.train.SessionRunHook` objects to run + on the chief worker during training. + training_hooks: Iterable of `tf.train.SessionRunHook` objects to run on + all workers during training. + scaffold: A `tf.train.Scaffold` object that can be used to set + initialization, saver, and more to be used in training. + evaluation_hooks: Iterable of `tf.train.SessionRunHook` objects to run + during evaluation. + prediction_hooks: Iterable of `tf.train.SessionRunHook` objects to run + during predictions. + + Returns: + A validated `EstimatorSpec` object. + + Raises: + ValueError: If validation fails. + TypeError: If any of the arguments is not the expected type. + """ + train_op = _validate_estimator_spec_train_op(train_op, mode) + loss = _validate_estimator_spec_loss(loss, mode) + predictions = _validate_estimator_spec_predictions(predictions, mode) + export_outputs = _validate_estimator_spec_export_outputs( + export_outputs, predictions, mode) + training_hooks = _validate_estimator_spec_hooks(training_hooks) + evaluation_hooks = _validate_estimator_spec_hooks(evaluation_hooks) + prediction_hooks = _validate_estimator_spec_hooks(prediction_hooks) + training_chief_hooks = _validate_estimator_spec_hooks(training_chief_hooks) + eval_metric_ops = _validate_eval_metric_ops(eval_metric_ops) + scaffold = _validate_scaffold(scaffold) + + # By default, Tensor Tracer is not enabled and the block below is an no-op. + if tensor_tracer.TensorTracer.is_enabled() and train_op is not None: + # If Tensor Tracer is enabled via environment flags, loss and train_op + # will be used to determine the execution path that will be traced. A + # `tf.identity` of loss that enforces the execution of tracing ops will be + # returned. + tt = tensor_tracer.TensorTracer() + loss = tt.trace_cpu(tf.compat.v1.get_default_graph(), loss, train_op) + + return super(EstimatorSpec, cls).__new__( + cls, + mode=mode, + predictions=predictions, + loss=loss, + train_op=train_op, + eval_metric_ops=eval_metric_ops, + export_outputs=export_outputs, + training_chief_hooks=training_chief_hooks, + training_hooks=training_hooks, + scaffold=scaffold, + evaluation_hooks=evaluation_hooks, + prediction_hooks=prediction_hooks) + + def _replace(self, **kwds): + """Return a new EstimatorSpec replacing specified fields with new values.""" + if 'mode' in kwds: + if self.mode != kwds['mode']: + raise ValueError('mode of EstimatorSpec cannot be changed.') + new_fields = map(kwds.pop, self._fields, list(self)) + return EstimatorSpec(*new_fields) + + +class _TPUEstimatorSpec( + collections.namedtuple('TPUEstimatorSpec', [ + 'mode', 'predictions', 'loss', 'train_op', 'eval_metrics', + 'export_outputs', 'scaffold_fn', 'host_call', 'training_hooks', + 'evaluation_hooks', 'prediction_hooks' + ])): + """Ops and objects returned from a `model_fn` and passed to `TPUEstimator`. + + This is a simplified implementation of `tf.contrib.tpu.EstimatorSpec`. See + tensorflow/contrib/tpu/python/tpu/tpu_estimator.py for more detailed + documentation. + """ + + def __new__(cls, + mode, + predictions=None, + loss=None, + train_op=None, + eval_metrics=None, + export_outputs=None, + scaffold_fn=None, + host_call=None, + training_hooks=None, + evaluation_hooks=None, + prediction_hooks=None): + """Creates a `_TPUEstimatorSpec` instance.""" + train_op = _validate_estimator_spec_train_op(train_op, mode) + loss = _validate_estimator_spec_loss(loss, mode) + predictions = _validate_estimator_spec_predictions(predictions, mode) + export_outputs = _validate_estimator_spec_export_outputs( + export_outputs, predictions, mode) + training_hooks = _validate_estimator_spec_hooks(training_hooks) + evaluation_hooks = _validate_estimator_spec_hooks(evaluation_hooks) + prediction_hooks = _validate_estimator_spec_hooks(prediction_hooks) + return super(_TPUEstimatorSpec, cls).__new__( + cls, + mode=mode, + predictions=predictions, + loss=loss, + train_op=train_op, + eval_metrics=eval_metrics, + export_outputs=export_outputs, + scaffold_fn=scaffold_fn, + host_call=host_call, + training_hooks=training_hooks, + evaluation_hooks=evaluation_hooks, + prediction_hooks=prediction_hooks) + + def as_estimator_spec(self): + """Creates an equivalent `EstimatorSpec` used by CPU train/eval.""" + if not self.eval_metrics: + eval_metric_ops = None + else: + metric_fn, tensors = self.eval_metrics + eval_metric_ops = metric_fn(**tensors) + return EstimatorSpec( + mode=self.mode, + predictions=self.predictions, + loss=self.loss, + train_op=self.train_op, + eval_metric_ops=eval_metric_ops, + export_outputs=self.export_outputs, + training_hooks=self.training_hooks, + evaluation_hooks=self.evaluation_hooks, + prediction_hooks=self.prediction_hooks) + + +# Used to generate possible error causes if the user provides a `Tensor` to an +# EstimatorSpec that is not in the default graph. +_default_graph_error_message_template = ( + '{0} with "{1}" must be from the default graph. ' + 'Possible causes of this error include: \n\n' + '1) {0} was created outside the context of the default graph.' + '\n\n' + '2) The object passed through to EstimatorSpec was not created ' + 'in the most recent call to "model_fn".') + + +def _validate_estimator_spec_train_op(train_op, mode): + """Validate train_op inputs for EstimatorSpec or TPUEstimatorSpec. + + Args: + train_op: Op for the training step. + mode: A `ModeKeys`. Used to determine whether the train_op is acceptable for + use in the current mode; for example, if we are not training, this can be + None. + + Returns: + train_op: Op for the training step. + + Raises: + ValueError: If no train_op is passed during training. + TypeError: If: + - train_op is neither a `Tensor` nor an Op. + - train_op is not part of the default graph. + """ + if train_op is None: + if mode == ModeKeys.TRAIN: + raise ValueError('Missing train_op.') + else: + default_graph = tf.compat.v1.get_default_graph() + _check_is_tensor_or_operation(train_op, 'train_op') + if isinstance(train_op, tf.Variable): + train_op = train_op.op + if not (tf.executing_eagerly() or train_op.graph is default_graph): + raise ValueError( + _default_graph_error_message_template.format('train_op', + train_op.name)) + return train_op + + +def _validate_estimator_spec_loss(loss, mode): + """Validate loss inputs for EstimatorSpec or TPUEstimatorSpec. + + Args: + loss: Training loss `Tensor`. Must either be scalar, or with shape `[1]`. + mode: A `ModeKeys`. Used to determine whether the loss is acceptable for use + in the current mode; for example, None is acceptable if we are not + training or evaluating. + + Returns: + loss: Training loss `Tensor`. + + Raises: + ValueError: If the loss `Tensor` is not appropriately formatted. + TypeError: If: + - a non-`Tensor`, non-None input is passed. + - the loss `Tensor` is not part of the default graph. + """ + if loss is None: + if mode in (ModeKeys.TRAIN, ModeKeys.EVAL): + raise ValueError('Missing loss.') + else: + default_graph = tf.compat.v1.get_default_graph() + # Loss must be a tensor. + loss = _check_is_tensor(loss, 'loss') + loss_shape = loss.get_shape() + if loss_shape.num_elements() not in (None, 1): + raise ValueError('Loss must be scalar, given: {}'.format(loss)) + if not loss_shape.is_compatible_with(tf.TensorShape([])): + loss = tf.reshape(loss, []) + if not (tf.executing_eagerly() or loss.graph is default_graph): + raise ValueError( + _default_graph_error_message_template.format('loss', loss.name)) + return loss + + +def _validate_estimator_spec_predictions(predictions, mode): + """Validate predictions inputs for EstimatorSpec or TPUEstimatorSpec. + + Args: + predictions: Predictions `Tensor` or dict of `Tensor`. + mode: A `ModeKeys`. Used to determine whether the predictions are acceptable + for use in the current mode; None is acceptable if we are not making + predictions. + + Returns: + predictions: Predictions `Tensor` or dict of `Tensor`. + + Raises: + ValueError: If: + - predictions is None and we are in predict mode. + - predictions `Tensor` is not in default_graph or else it is a dict of + `Tensor` where at least one is not in default_graph. + TypeError: If predictions is not a `Tensor` or dict of `Tensor`. + """ + if predictions is None: + if mode == ModeKeys.PREDICT: + raise ValueError('Missing predictions.') + predictions = {} + else: + default_graph = tf.compat.v1.get_default_graph() + if isinstance(predictions, dict): + predictions = { + k: _check_is_tensor(v, 'predictions[{}]'.format(k)) + for k, v in six.iteritems(predictions) + } + if not tf.executing_eagerly(): + for key, value in six.iteritems(predictions): + if value.graph is not default_graph: + raise ValueError( + _default_graph_error_message_template.format( + 'prediction values', '{0}: {1}'.format(key, value.name))) + else: + # Predictions should be a tensor. + predictions = _check_is_tensor(predictions, 'predictions') + if not (tf.executing_eagerly() or predictions.graph is default_graph): + raise ValueError( + _default_graph_error_message_template.format( + 'prediction values', predictions.name)) + return predictions + + +def _validate_estimator_spec_export_outputs(export_outputs, predictions, mode): + """Validate export_outputs inputs for EstimatorSpec or TPUEstimatorSpec. + + Args: + export_outputs: Describes the output signatures to be exported to + `SavedModel` and used during serving. + A dict `{name: output}` where: + * name: An arbitrary name for this output. + * output: an `ExportOutput` object such as `ClassificationOutput` + `RegressionOutput`, or `PredictOutput`. Single-headed models should only + need to specify one entry in this dictionary. Multi-headed models should + specify one entry for each head, one of which must be named using + `tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY`. + If no entry is provided, a default `PredictOutput` mapping to + predictions will be created. + predictions: Predictions `Tensor` or dict of `Tensor`. Used in generation of + default outputs. + mode: A `ModeKeys`. Used to determine whether to validate at all; if the + EstimatorSpec is not for making predictions we can skip validation. + + Returns: + ValueError: If validation fails. + TypeError: If the export_outputs is not a dict or the values of the dict are + not instances of type `ExportOutput`. + """ + if mode == ModeKeys.PREDICT: + export_outputs = export_utils.get_export_outputs(export_outputs, + predictions) + return export_outputs + + +def _validate_estimator_spec_hooks(hooks): + """Validate SessionRunHooks for use in EstimatorSpec or TPUEstimatorSpec. + + Args: + hooks: Iterable of `tf.train.SessionRunHook` objects to run on all workers. + + Returns: + hooks: Iterable of `tf.train.SessionRunHook` objects. + + Raises: + ValueError: If validation fails. + TypeError: If any element of the iterable is not a SessionRunHook. + """ + hooks = tuple(hooks or []) + + for hook in hooks: + if not isinstance(hook, tf.compat.v1.train.SessionRunHook): + raise TypeError( + 'All hooks must be SessionRunHook instances, given: {}'.format(hook)) + return hooks + + +def _validate_eval_metric_ops(eval_metric_ops): + """Validate eval_metric_ops for use in EstimatorSpec. + + Args: + eval_metric_ops: Dict of metric results keyed by name. + The values of the dict can be one of the following: (1) instance of + `Metric` class. (2) Results of calling a metric_function, namely a + `(metric_tensor, update_op)` tuple. `metric_tensor` should be evaluated + without any impact on state (typically it is a pure computation based on + variables.). For example, it should not trigger the `update_op` or + require any input fetching. + + Returns: + eval_metric_ops: Dict of metric results keyed by name. + + Raises: + ValueError: If: + - one of the eval_metric_ops `Metric` objects has no updates. + - there is at least one `Metric` update or result, `Tensor`, or Op that is + not in the default graph. + TypeError: If: + - eval_metric_ops is not a dict or None. + - an element of eval_metric_ops is not a `Metric` or a 2-tuple. + - an element of eval_metric_ops has a sub-element that is not a `Tensor` or + an Op. + """ + if eval_metric_ops is None: + eval_metric_ops = {} + else: + if not isinstance(eval_metric_ops, dict): + raise TypeError( + 'eval_metric_ops must be a dict, given: {}'.format(eval_metric_ops)) + for key, value in six.iteritems(eval_metric_ops): + # TODO(psv): When we deprecate the old metrics, throw an error here if + # the value is not an instance of `Metric` class. + if isinstance(value, tf.keras.metrics.Metric): + if not value.updates: # Check if metric updates are available. + raise ValueError( + 'Please call update_state(...) on the "{metric_name}" metric' + .format(metric_name=value.name)) + else: + if not isinstance(value, tuple) or len(value) != 2: + raise TypeError( + 'Values of eval_metric_ops must be (metric_value, update_op) ' + 'tuples, given: {} for key: {}'.format(value, key)) + # Verify all tensors and ops are from default graph. + default_graph = tf.compat.v1.get_default_graph() + for key, value in list(six.iteritems(eval_metric_ops)): + if isinstance(value, tf.keras.metrics.Metric): + values_to_check = value.updates[:] + values_to_check.append(value.result()) + else: + values_to_check = tf.nest.flatten(value) + for val in values_to_check: + if not (tf.executing_eagerly() or val.graph is default_graph): + raise ValueError( + _default_graph_error_message_template.format( + 'eval_metric_ops', '{0}: {1}'.format(key, val.name))) + # Metric variables are by default not added to any collections. The variables + # are appended to the LOCAL_VARIABLES collection for initialization, and + # METRIC_VARIABLES for TFMA compatibility. Note that although collections are + # officially deprecated in TensorFlow 2, Estimators will continue using + # collections as long as it supports V1 graph mode. + vars_to_add = set() + for key, value in six.iteritems(eval_metric_ops): + if isinstance(value, tf.keras.metrics.Metric): + vars_to_add.update(value.variables) + # Convert Metric instances to (value_tensor, update_op) tuple. + eval_metric_ops[key] = (value.result(), value.updates[0]) + _update_variable_collection(tf.compat.v1.GraphKeys.LOCAL_VARIABLES, + vars_to_add) + _update_variable_collection(tf.compat.v1.GraphKeys.METRIC_VARIABLES, + vars_to_add) + + return eval_metric_ops + + +def _update_variable_collection(collection_name, vars_to_add): + """Add variables to collection.""" + collection = set(tf.compat.v1.get_collection(collection_name)) + # Skip variables that are in the collection already. + vars_to_add = vars_to_add.difference(collection) + for v in vars_to_add: + tf.compat.v1.add_to_collection(collection_name, v) + + +def _validate_scaffold(scaffold): + """Validate scaffold input for EstimatorSpec. + + Args: + scaffold: A `tf.train.Scaffold` object that can be used to set + initialization, saver, and more to be used in training. + + Returns: + scaffold: A `tf.train.Scaffold` object. If no scaffold is provided, then a + default is generated. + + Raises: + TypeError: If the scaffold is not of type `monitored_session.Scaffold` + or None. + """ + scaffold = scaffold or tf.compat.v1.train.Scaffold() + if not isinstance(scaffold, tf.compat.v1.train.Scaffold): + raise TypeError( + 'scaffold must be tf.train.Scaffold. Given: {}'.format(scaffold)) + return scaffold + + +def _check_is_tensor_or_operation(x, name): + # TODO(b/154650521): Use tf.Tensor instead of core.Tensor. + if not isinstance(x, (tf.Operation, tf.compat.v2.__internal__.types.Tensor)): + raise TypeError('{} must be Operation or Tensor, given: {}'.format(name, x)) + + +def _check_is_tensor(x, tensor_name): + """Returns `x` if it is a `Tensor`, raises TypeError otherwise.""" + if not isinstance(x, tf.compat.v2.__internal__.types.Tensor): + raise TypeError('{} must be Tensor, given: {}'.format(tensor_name, x)) + return x + + +@estimator_export('estimator.experimental.call_logit_fn') +def call_logit_fn(logit_fn, features, mode, params, config): + """Calls logit_fn (experimental). + + THIS FUNCTION IS EXPERIMENTAL. Keras layers/models are the recommended APIs + for logit and model composition. + + A utility function that calls the provided logit_fn with the relevant subset + of provided arguments. Similar to tf.estimator._call_model_fn(). + + Args: + logit_fn: A logit_fn as defined above. + features: The features dict. + mode: TRAIN / EVAL / PREDICT ModeKeys. + params: The hyperparameter dict. + config: The configuration object. + + Returns: + A logit Tensor, the output of logit_fn. + + Raises: + ValueError: if logit_fn does not return a Tensor or a dictionary mapping + strings to Tensors. + """ + logit_fn_args = function_utils.fn_args(logit_fn) + kwargs = {} + if 'mode' in logit_fn_args: + kwargs['mode'] = mode + if 'params' in logit_fn_args: + kwargs['params'] = params + if 'config' in logit_fn_args: + kwargs['config'] = config + logit_fn_results = logit_fn(features=features, **kwargs) + + result_is_valid_dictionary = ( + isinstance(logit_fn_results, dict) and + all([(isinstance(k, six.string_types) and isinstance(v, tf.Tensor)) + for k, v in six.iteritems(logit_fn_results)])) + result_is_tensor = isinstance(logit_fn_results, tf.Tensor) + + if not (result_is_valid_dictionary or result_is_tensor): + raise ValueError('logit_fn should return a Tensor or a dictionary mapping ' + 'strings to Tensors. logit_fn returned: %s' % + logit_fn_results) + + return logit_fn_results + + +_VALID_MODEL_FN_ARGS = set( + ['features', 'labels', 'mode', 'params', 'self', 'config']) + + +def verify_model_fn_args(model_fn, params): + """Verifies `model_fn` arguments.""" + args = set(function_utils.fn_args(model_fn)) + if 'features' not in args: + raise ValueError('model_fn (%s) must include features argument.' % model_fn) + if params is not None and 'params' not in args: + raise ValueError('model_fn (%s) does not include params argument, ' + 'but params (%s) is passed to Estimator.' % + (model_fn, params)) + if params is None and 'params' in args: + tf.compat.v1.logging.warn( + 'Estimator\'s model_fn (%s) includes params ' + 'argument, but params are not passed to Estimator.', model_fn) + non_valid_args = list(args - _VALID_MODEL_FN_ARGS) + if non_valid_args: + raise ValueError('model_fn (%s) has following not expected args: %s' % + (model_fn, non_valid_args)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/run_config.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/run_config.py new file mode 100644 index 0000000000000000000000000000000000000000..1b5f18826dc9dee86c611de46908e90a2aa767a9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/run_config.py @@ -0,0 +1,1000 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Environment configuration object for Estimators.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import copy +import json +import os + +import six +import tensorflow as tf +from tensorflow.core.protobuf import rewriter_config_pb2 +from tensorflow.python.distribute import estimator_training as distribute_coordinator_training +from tensorflow.python.util import function_utils +from tensorflow_estimator.python.estimator.estimator_export import estimator_export + + +_USE_DEFAULT = object() +_VALID_DEVICE_FN_ARGS = set(['op']) + +# A list of the property names in RunConfig that the user is allowed to change. +_DEFAULT_REPLACEABLE_LIST = [ + 'model_dir', 'tf_random_seed', 'save_summary_steps', + 'save_checkpoints_steps', 'save_checkpoints_secs', 'session_config', + 'keep_checkpoint_max', 'keep_checkpoint_every_n_hours', + 'log_step_count_steps', 'train_distribute', 'device_fn', 'protocol', + 'eval_distribute', 'experimental_distribute', + 'experimental_max_worker_delay_secs', 'session_creation_timeout_secs', + 'checkpoint_save_graph_def' +] + +_SAVE_CKPT_ERR = ( + '`save_checkpoints_steps` and `save_checkpoints_secs` cannot be both set.') + +_TF_CONFIG_ENV = 'TF_CONFIG' +_TASK_ENV_KEY = 'task' +_TASK_TYPE_KEY = 'type' +_TASK_ID_KEY = 'index' +_CLUSTER_KEY = 'cluster' +_SERVICE_KEY = 'service' +_SESSION_MASTER_KEY = 'session_master' +_EVAL_SESSION_MASTER_KEY = 'eval_session_master' +_MODEL_DIR_KEY = 'model_dir' +_LOCAL_MASTER = '' +_GRPC_SCHEME = 'grpc://' + + +def _get_session_master(cluster_spec, task_type, task_id, tf_config): + """Returns the appropriate address for TensorFlow master. + + The order of precedence to determine the TF session master is as follows: + 1. If `tf_session_master` is set in TF_CONFIG environment variable, takes it. + 2. If the cluster has only one node, returns empty string ''. + 3. Returns the grpc address according to the task type and id in the cluster. + This is between-graph replication. + + Note: task_type and task_id must be validated. Typically, validated using + `_validate_task_type_and_task_id`. + + Args: + cluster_spec: A `ClusterSpec` instance. + task_type: String. Task type for current node. + task_id: Int. Task id for current node. + tf_config: Dict. Python dict for the TF_CONFIG environment variable. + + Raises: + RuntimeError: If `cluster_spec` is not set. + + """ + if _SESSION_MASTER_KEY in tf_config: + return tf_config[_SESSION_MASTER_KEY] + + if not cluster_spec: + raise RuntimeError('Internal error: `_get_session_master` ' + 'does not expect empty cluster_spec.') + + jobs = cluster_spec.jobs + + # If there is only one node in the cluster, do things locally by setting + # master to ''. If a service or user sets TF_CONFIG with a single node, it's + # more performant to use a direct master rather than an RPC service. + if len(jobs) == 1 and len(cluster_spec.job_tasks(jobs[0])) == 1: + return _LOCAL_MASTER + + # Lookup the master in cluster_spec using task_type and task_id, + # if possible. + addresses = cluster_spec.job_tasks(task_type) + return _GRPC_SCHEME + addresses[task_id] + + +def _get_eval_session_master(task_type, tf_config): + """Returns the appropriate address for TensorFlow evaluation master.""" + if task_type == TaskType.EVALUATOR: + return tf_config.get(_EVAL_SESSION_MASTER_KEY, _LOCAL_MASTER) + + return _LOCAL_MASTER + + +def _count_ps(cluster_spec): + """Counts the number of parameter servers in cluster_spec.""" + if not cluster_spec: + raise RuntimeError( + 'Internal error: `_count_ps` does not expect empty cluster_spec.') + + return len(cluster_spec.as_dict().get(TaskType.PS, [])) + + +def _count_worker(cluster_spec, chief_task_type): + """Counts the number of workers (including chief) in cluster_spec.""" + if not cluster_spec: + raise RuntimeError( + 'Internal error: `_count_worker` does not expect empty cluster_spec.') + + return (len(cluster_spec.as_dict().get(TaskType.WORKER, [])) + + len(cluster_spec.as_dict().get(chief_task_type, []))) + + +def _validate_service(service): + """Validates the service key.""" + if service is not None and not isinstance(service, dict): + raise TypeError( + 'If "service" is set in TF_CONFIG, it must be a dict. Given %s' % + type(service)) + return service + + +def _validate_task_type_and_task_id(cluster_spec, task_env, chief_task_type): + """Validates the task type and index in `task_env` according to cluster.""" + if chief_task_type not in cluster_spec.jobs: + raise ValueError( + 'If "cluster" is set in TF_CONFIG, it must have one "%s" node.' % + chief_task_type) + if len(cluster_spec.job_tasks(chief_task_type)) > 1: + raise ValueError( + 'The "cluster" in TF_CONFIG must have only one "%s" node.' % + chief_task_type) + + task_type = task_env.get(_TASK_TYPE_KEY, None) + task_id = task_env.get(_TASK_ID_KEY, None) + + if not task_type: + raise ValueError('If "cluster" is set in TF_CONFIG, task type must be set.') + if task_id is None: + raise ValueError( + 'If "cluster" is set in TF_CONFIG, task index must be set.') + + task_id = int(task_id) + + # Check the task id bounds. Upper bound is not necessary as + # - for evaluator, there is no upper bound. + # - for non-evaluator, task id is upper bounded by the number of jobs in + # cluster spec, which will be checked later (when retrieving the `master`) + if task_id < 0: + raise ValueError('Task index must be non-negative number.') + + # Evaluator is not part of the training cluster. + if task_type == TaskType.EVALUATOR: + return task_type, task_id + + if task_type not in cluster_spec.jobs: + raise ValueError( + '%s is not a valid task_type in the cluster_spec:\n' + '%s\n\n' + 'Note that these values may be coming from the TF_CONFIG environment ' + 'variable.' % (task_type, cluster_spec)) + addresses = cluster_spec.job_tasks(task_type) + if not 0 <= task_id < len(addresses): + raise ValueError( + '%d is not a valid task_id for task_type %s in the cluster_spec:\n' + '%s\n\n' + 'Note that these values may be coming from the TF_CONFIG environment ' + 'variable.' % (task_id, task_type, cluster_spec)) + + return task_type, task_id + + +def _get_global_id_in_cluster(cluster_spec, task_type, task_id, + chief_task_type): + """Returns the global id in cluster.""" + # Note: This is implementation details, which user should not rely on. + # The first id is 0, which is always for the `chief` node. All other nodes, + # except `ps`, are ordered alphabetical based on task type (alphabetically) + # and task id (ascendingly). `ps` are ordered last. + + # Sort task names in cluster + task_type_ordered_list = [chief_task_type] + task_type_ordered_list.extend([ + t for t in sorted(cluster_spec.jobs) + if t != chief_task_type and t != TaskType.PS + ]) + if TaskType.PS in cluster_spec.jobs: + task_type_ordered_list.append(TaskType.PS) + + next_global_id = 0 + for t in task_type_ordered_list: + if t == task_type: + return next_global_id + task_id + next_global_id += len(cluster_spec.job_tasks(t)) + + # This should never happen. + raise RuntimeError('Internal Error: `task_type` ({}) is not in ' + 'cluster_spec ({}).'.format(task_type, cluster_spec)) + + +def _validate_save_ckpt_with_replaced_keys(new_copy, replaced_keys): + """Validates the save ckpt properties.""" + # Ensure one (and only one) of save_steps and save_secs is not None. + # Also, if user sets one save ckpt property, say steps, the other one (secs) + # should be set as None to improve usability. + + save_steps = new_copy.save_checkpoints_steps + save_secs = new_copy.save_checkpoints_secs + + if ('save_checkpoints_steps' in replaced_keys and + 'save_checkpoints_secs' in replaced_keys): + # If user sets both properties explicitly, we need to error out if both + # are set or neither of them are set. + if save_steps is not None and save_secs is not None: + raise ValueError(_SAVE_CKPT_ERR) + elif 'save_checkpoints_steps' in replaced_keys and save_steps is not None: + new_copy._save_checkpoints_secs = None # pylint: disable=protected-access + elif 'save_checkpoints_secs' in replaced_keys and save_secs is not None: + new_copy._save_checkpoints_steps = None # pylint: disable=protected-access + + +def _validate_properties(run_config): + """Validates the properties.""" + + def _validate(property_name, cond, message): + property_value = getattr(run_config, property_name) + if property_value is not None and not cond(property_value): + raise ValueError(message) + + def _validate_delay(delay): + """Check that delay is an integer value. + + Since this has to work for both Python2 and Python3 and PEP237 defines long + to be basically int, we cannot just use a lambda function. + """ + try: + return isinstance(delay, (int, long)) + except NameError: + # PEP237 redefines long to int for Python3 + return isinstance(delay, int) + + _validate( + 'model_dir', lambda dir: dir, message='model_dir should be non-empty') + + _validate( + 'save_summary_steps', + lambda steps: steps >= 0, + message='save_summary_steps should be >= 0') + + _validate( + 'save_checkpoints_steps', + lambda steps: steps >= 0, + message='save_checkpoints_steps should be >= 0') + _validate( + 'save_checkpoints_secs', + lambda secs: secs >= 0, + message='save_checkpoints_secs should be >= 0') + + _validate( + 'session_config', + lambda sc: isinstance(sc, tf.compat.v1.ConfigProto), + message='session_config must be instance of ConfigProto') + + _validate( + 'keep_checkpoint_max', + lambda keep_max: keep_max >= 0, + message='keep_checkpoint_max should be >= 0') + _validate( + 'keep_checkpoint_every_n_hours', + lambda keep_hours: keep_hours > 0, + message='keep_checkpoint_every_n_hours should be > 0') + _validate( + 'log_step_count_steps', + lambda num_steps: num_steps > 0, + message='log_step_count_steps should be > 0') + + _validate( + 'tf_random_seed', + lambda seed: isinstance(seed, six.integer_types), + message='tf_random_seed must be integer.') + + _validate( + 'experimental_max_worker_delay_secs', + _validate_delay, + message='experimental_max_worker_delay_secs must be an integer if' + ' set.') + _validate( + 'session_creation_timeout_secs', + lambda timeout_secs: timeout_secs > 0, + message='session_creation_timeout_secs should be > 0') + + _validate( + 'device_fn', + lambda device_fn: six.callable(device_fn) and set( + function_utils.fn_args(device_fn)) == _VALID_DEVICE_FN_ARGS, + message='device_fn must be callable with exactly' + ' one argument "op".') + + _validate( + 'protocol', + lambda protocol: protocol in (None, 'grpc', 'grpc+verbs'), + message='protocol should be grpc or grpc+verbs') + + +def get_default_session_config(): + """Returns tf.ConfigProto instance.""" + + rewrite_opts = rewriter_config_pb2.RewriterConfig( + meta_optimizer_iterations=rewriter_config_pb2.RewriterConfig.ONE) + graph_opts = tf.compat.v1.GraphOptions(rewrite_options=rewrite_opts) + + return tf.compat.v1.ConfigProto( + allow_soft_placement=True, graph_options=graph_opts) + + +class TaskType(object): + MASTER = 'master' + PS = 'ps' + WORKER = 'worker' + CHIEF = 'chief' + EVALUATOR = 'evaluator' + + +@estimator_export('estimator.RunConfig') +class RunConfig(object): + """This class specifies the configurations for an `Estimator` run.""" + + def __init__(self, + model_dir=None, + tf_random_seed=None, + save_summary_steps=100, + save_checkpoints_steps=_USE_DEFAULT, + save_checkpoints_secs=_USE_DEFAULT, + session_config=None, + keep_checkpoint_max=5, + keep_checkpoint_every_n_hours=10000, + log_step_count_steps=100, + train_distribute=None, + device_fn=None, + protocol=None, + eval_distribute=None, + experimental_distribute=None, + experimental_max_worker_delay_secs=None, + session_creation_timeout_secs=7200, + checkpoint_save_graph_def=True): + """Constructs a RunConfig. + + All distributed training related properties `cluster_spec`, `is_chief`, + `master` , `num_worker_replicas`, `num_ps_replicas`, `task_id`, and + `task_type` are set based on the `TF_CONFIG` environment variable, if the + pertinent information is present. The `TF_CONFIG` environment variable is a + JSON object with attributes: `cluster` and `task`. + + `cluster` is a JSON serialized version of `ClusterSpec`'s Python dict from + `server_lib.py`, mapping task types (usually one of the `TaskType` enums) to + a list of task addresses. + + `task` has two attributes: `type` and `index`, where `type` can be any of + the task types in `cluster`. When `TF_CONFIG` contains said information, + the following properties are set on this class: + + * `cluster_spec` is parsed from `TF_CONFIG['cluster']`. Defaults to {}. If + present, must have one and only one node in the `chief` attribute of + `cluster_spec`. + * `task_type` is set to `TF_CONFIG['task']['type']`. Must set if + `cluster_spec` is present; must be `worker` (the default value) if + `cluster_spec` is not set. + * `task_id` is set to `TF_CONFIG['task']['index']`. Must set if + `cluster_spec` is present; must be 0 (the default value) if + `cluster_spec` is not set. + * `master` is determined by looking up `task_type` and `task_id` in the + `cluster_spec`. Defaults to ''. + * `num_ps_replicas` is set by counting the number of nodes listed + in the `ps` attribute of `cluster_spec`. Defaults to 0. + * `num_worker_replicas` is set by counting the number of nodes listed + in the `worker` and `chief` attributes of `cluster_spec`. Defaults to 1. + * `is_chief` is determined based on `task_type` and `cluster`. + + There is a special node with `task_type` as `evaluator`, which is not part + of the (training) `cluster_spec`. It handles the distributed evaluation job. + + Example of non-chief node: + ``` + cluster = {'chief': ['host0:2222'], + 'ps': ['host1:2222', 'host2:2222'], + 'worker': ['host3:2222', 'host4:2222', 'host5:2222']} + os.environ['TF_CONFIG'] = json.dumps( + {'cluster': cluster, + 'task': {'type': 'worker', 'index': 1}}) + config = RunConfig() + assert config.master == 'host4:2222' + assert config.task_id == 1 + assert config.num_ps_replicas == 2 + assert config.num_worker_replicas == 4 + assert config.cluster_spec == server_lib.ClusterSpec(cluster) + assert config.task_type == 'worker' + assert not config.is_chief + ``` + + Example of chief node: + ``` + cluster = {'chief': ['host0:2222'], + 'ps': ['host1:2222', 'host2:2222'], + 'worker': ['host3:2222', 'host4:2222', 'host5:2222']} + os.environ['TF_CONFIG'] = json.dumps( + {'cluster': cluster, + 'task': {'type': 'chief', 'index': 0}}) + config = RunConfig() + assert config.master == 'host0:2222' + assert config.task_id == 0 + assert config.num_ps_replicas == 2 + assert config.num_worker_replicas == 4 + assert config.cluster_spec == server_lib.ClusterSpec(cluster) + assert config.task_type == 'chief' + assert config.is_chief + ``` + + Example of evaluator node (evaluator is not part of training cluster): + ``` + cluster = {'chief': ['host0:2222'], + 'ps': ['host1:2222', 'host2:2222'], + 'worker': ['host3:2222', 'host4:2222', 'host5:2222']} + os.environ['TF_CONFIG'] = json.dumps( + {'cluster': cluster, + 'task': {'type': 'evaluator', 'index': 0}}) + config = RunConfig() + assert config.master == '' + assert config.evaluator_master == '' + assert config.task_id == 0 + assert config.num_ps_replicas == 0 + assert config.num_worker_replicas == 0 + assert config.cluster_spec == {} + assert config.task_type == 'evaluator' + assert not config.is_chief + ``` + + N.B.: If `save_checkpoints_steps` or `save_checkpoints_secs` is set, + `keep_checkpoint_max` might need to be adjusted accordingly, especially in + distributed training. For example, setting `save_checkpoints_secs` as 60 + without adjusting `keep_checkpoint_max` (defaults to 5) leads to situation + that checkpoint would be garbage collected after 5 minutes. In distributed + training, the evaluation job starts asynchronously and might fail to load or + find the checkpoint due to race condition. + + Args: + model_dir: directory where model parameters, graph, etc are saved. If + `PathLike` object, the path will be resolved. If `None`, will use a + default value set by the Estimator. + tf_random_seed: Random seed for TensorFlow initializers. Setting this + value allows consistency between reruns. + save_summary_steps: Save summaries every this many steps. + save_checkpoints_steps: Save checkpoints every this many steps. Can not be + specified with `save_checkpoints_secs`. + save_checkpoints_secs: Save checkpoints every this many seconds. Can not + be specified with `save_checkpoints_steps`. Defaults to 600 seconds if + both `save_checkpoints_steps` and `save_checkpoints_secs` are not set in + constructor. If both `save_checkpoints_steps` and + `save_checkpoints_secs` are `None`, then checkpoints are disabled. + session_config: a ConfigProto used to set session parameters, or `None`. + keep_checkpoint_max: The maximum number of recent checkpoint files to + keep. As new files are created, older files are deleted. If `None` or 0, + all checkpoint files are kept. Defaults to 5 (that is, the 5 most recent + checkpoint files are kept). If a saver is passed to the estimator, this + argument will be ignored. + keep_checkpoint_every_n_hours: Number of hours between each checkpoint to + be saved. The default value of 10,000 hours effectively disables the + feature. + log_step_count_steps: The frequency, in number of global steps, that the + global step and the loss will be logged during training. Also controls + the frequency that the global steps / s will be logged (and written to + summary) during training. + train_distribute: An optional instance of `tf.distribute.Strategy`. If + specified, then Estimator will distribute the user's model during + training, according to the policy specified by that strategy. Setting + `experimental_distribute.train_distribute` is preferred. + device_fn: A callable invoked for every `Operation` that takes the + `Operation` and returns the device string. If `None`, defaults to the + device function returned by `tf.train.replica_device_setter` with + round-robin strategy. + protocol: An optional argument which specifies the protocol used when + starting server. `None` means default to grpc. + eval_distribute: An optional instance of `tf.distribute.Strategy`. If + specified, then Estimator will distribute the user's model during + evaluation, according to the policy specified by that strategy. Setting + `experimental_distribute.eval_distribute` is preferred. + experimental_distribute: An optional + `tf.contrib.distribute.DistributeConfig` object specifying + DistributionStrategy-related configuration. The `train_distribute` and + `eval_distribute` can be passed as parameters to `RunConfig` or set in + `experimental_distribute` but not both. + experimental_max_worker_delay_secs: An optional integer specifying the + maximum time a worker should wait before starting. By default, workers + are started at staggered times, with each worker being delayed by up to + 60 seconds. This is intended to reduce the risk of divergence, which can + occur when many workers simultaneously update the weights of a randomly + initialized model. Users who warm-start their models and train them for + short durations (a few minutes or less) should consider reducing this + default to improve training times. + session_creation_timeout_secs: Max time workers should wait for a session + to become available (on initialization or when recovering a session) + with MonitoredTrainingSession. Defaults to 7200 seconds, but users may + want to set a lower value to detect problems with variable / session + (re)-initialization more quickly. + checkpoint_save_graph_def: Whether to save the GraphDef and MetaGraphDef + to `checkpoint_dir`. The GraphDef is saved after the session is created + as `graph.pbtxt`. MetaGraphDefs are saved out for every checkpoint as + `model.ckpt-*.meta`. + + Raises: + ValueError: If both `save_checkpoints_steps` and `save_checkpoints_secs` + are set. + """ + if (save_checkpoints_steps == _USE_DEFAULT and + save_checkpoints_secs == _USE_DEFAULT): + save_checkpoints_steps = None + save_checkpoints_secs = 600 + elif save_checkpoints_secs == _USE_DEFAULT: + save_checkpoints_secs = None + elif save_checkpoints_steps == _USE_DEFAULT: + save_checkpoints_steps = None + elif (save_checkpoints_steps is not None and + save_checkpoints_secs is not None): + raise ValueError(_SAVE_CKPT_ERR) + + self._verify_strategy_compatibility(train_distribute, eval_distribute) + + tf_config = json.loads(os.environ.get(_TF_CONFIG_ENV, '{}')) + if tf_config: + tf.compat.v1.logging.info('TF_CONFIG environment variable: %s', tf_config) + + model_dir = _get_model_dir(tf_config, path_to_str(model_dir)) + + RunConfig._replace( + self, + allowed_properties_list=_DEFAULT_REPLACEABLE_LIST, + model_dir=model_dir, + tf_random_seed=tf_random_seed, + save_summary_steps=save_summary_steps, + save_checkpoints_steps=save_checkpoints_steps, + save_checkpoints_secs=save_checkpoints_secs, + session_config=session_config, + keep_checkpoint_max=keep_checkpoint_max, + keep_checkpoint_every_n_hours=keep_checkpoint_every_n_hours, + log_step_count_steps=log_step_count_steps, + train_distribute=train_distribute, + device_fn=device_fn, + protocol=protocol, + eval_distribute=eval_distribute, + experimental_distribute=experimental_distribute, + experimental_max_worker_delay_secs=experimental_max_worker_delay_secs, + session_creation_timeout_secs=session_creation_timeout_secs, + checkpoint_save_graph_def=checkpoint_save_graph_def) + + # TODO(frankchn,priyag): Eventually use distributed coordinator for TPUs. + if ((train_distribute and + not train_distribute.__class__.__name__.startswith('TPUStrategy')) or + (eval_distribute and + not eval_distribute.__class__.__name__.startswith('TPUStrategy')) or + experimental_distribute): + tf.compat.v1.logging.info( + 'Initializing RunConfig with distribution strategies.') + distribute_coordinator_training.init_run_config(self, tf_config) + else: + self._init_distributed_setting_from_environment_var(tf_config) + self._maybe_overwrite_session_config_for_distributed_training() + + def _verify_strategy_compatibility(self, train_distribute, eval_distribute): + if ((train_distribute is not None and train_distribute.__class__ == + tf.compat.v2.distribute.experimental.ParameterServerStrategy) or + (eval_distribute is not None and eval_distribute.__class__ == + tf.compat.v2.distribute.experimental.ParameterServerStrategy)): + raise ValueError('Please use `tf.compat.v1.distribute.experimental.Param' + 'eterServerStrategy` for parameter server strategy with ' + 'estimator.') + + def _maybe_overwrite_session_config_for_distributed_training(self): + """Overwrites the session_config for distributed training. + + The default overwrite is optimized for between-graph training. Subclass + should override this method if necessary. + """ + # Get session_config only for between-graph distributed mode (cluster_spec + # is present). + if not self._session_config and self._cluster_spec: + RunConfig._replace( + self, + allowed_properties_list=_DEFAULT_REPLACEABLE_LIST, + session_config=self._get_default_session_config_distributed()) + + def _get_default_session_config_distributed(self): + """Returns None or tf.ConfigProto instance with default device_filters set. + + Device filters are set such that chief/master and worker communicates with + only ps. session_config=None for evaluators or any other TaskType. + """ + + rewrite_opts = rewriter_config_pb2.RewriterConfig( + meta_optimizer_iterations=rewriter_config_pb2.RewriterConfig.ONE) + graph_opts = tf.compat.v1.GraphOptions(rewrite_options=rewrite_opts) + + device_filters = None + if self._task_type == TaskType.MASTER: + device_filters = ['/job:ps', '/job:master'] + elif self._task_type == TaskType.CHIEF: + device_filters = ['/job:ps', '/job:chief'] + elif self._task_type == TaskType.WORKER: + device_filters = ['/job:ps', '/job:worker/task:%d' % self._task_id] + elif self._task_type == TaskType.PS: + device_filters = ['/job:ps', '/job:worker', '/job:chief', '/job:master'] + else: + # If the task_type is `EVALUATOR` or something other than the ones in + # TaskType then don't set any device filters. + return None + + return tf.compat.v1.ConfigProto( + allow_soft_placement=True, + graph_options=graph_opts, + device_filters=device_filters) + + def _init_distributed_setting_from_environment_var(self, tf_config): + """Initialize distributed properties based on `tf_config`.""" + + self._service = _validate_service(tf_config.get(_SERVICE_KEY)) + self._cluster_spec = tf.train.ClusterSpec(tf_config.get(_CLUSTER_KEY, {})) + task_env = tf_config.get(_TASK_ENV_KEY, {}) + + if self._cluster_spec and TaskType.MASTER in self._cluster_spec.jobs: + return self._init_distributed_setting_from_environment_var_with_master( + tf_config) + + if self._cluster_spec: + # Distributed mode. + self._task_type, self._task_id = _validate_task_type_and_task_id( + self._cluster_spec, task_env, TaskType.CHIEF) + + self._evaluation_master = _get_eval_session_master( + self._task_type, tf_config) + + if self._task_type != TaskType.EVALUATOR: + self._master = _get_session_master(self._cluster_spec, self._task_type, + self._task_id, tf_config) + self._num_ps_replicas = _count_ps(self._cluster_spec) + self._num_worker_replicas = _count_worker( + self._cluster_spec, chief_task_type=TaskType.CHIEF) + self._global_id_in_cluster = _get_global_id_in_cluster( + self._cluster_spec, + self._task_type, + self._task_id, + chief_task_type=TaskType.CHIEF) + else: + # Evaluator is not part of the training cluster. + self._cluster_spec = tf.train.ClusterSpec({}) + self._master = _LOCAL_MASTER + self._num_ps_replicas = 0 + self._num_worker_replicas = 0 + self._global_id_in_cluster = None # undefined + + self._is_chief = self._task_type == TaskType.CHIEF + else: + # Local mode. + self._task_type = task_env.get(_TASK_TYPE_KEY, TaskType.WORKER) + self._task_id = int(task_env.get(_TASK_ID_KEY, 0)) + self._global_id_in_cluster = 0 + + if self._task_type != TaskType.WORKER: + raise ValueError( + 'If "cluster" is not set in TF_CONFIG, task type must be WORKER.') + if self._task_id != 0: + raise ValueError( + 'If "cluster" is not set in TF_CONFIG, task index must be 0.') + + self._master = tf_config.get(_SESSION_MASTER_KEY, _LOCAL_MASTER) + self._evaluation_master = tf_config.get(_EVAL_SESSION_MASTER_KEY, + _LOCAL_MASTER) + self._is_chief = True + self._num_ps_replicas = 0 + self._num_worker_replicas = 1 + + def _init_distributed_setting_from_environment_var_with_master( + self, tf_config): + """Initialize distributed properties for legacy cluster with `master`.""" + # There is no tech reason, why user cannot have chief and master in the same + # cluster, but it is super confusing (which is really the chief?). So, block + # this case. + if TaskType.CHIEF in self._cluster_spec.jobs: + raise ValueError('If `master` node exists in `cluster`, job ' + '`chief` is not supported.') + + task_env = tf_config.get(_TASK_ENV_KEY, {}) + + self._task_type, self._task_id = _validate_task_type_and_task_id( + self._cluster_spec, task_env, TaskType.MASTER) + + if self._task_type == TaskType.EVALUATOR: + raise ValueError('If `master` node exists in `cluster`, task_type ' + '`evaluator` is not supported.') + + self._global_id_in_cluster = _get_global_id_in_cluster( + self._cluster_spec, + self._task_type, + self._task_id, + chief_task_type=TaskType.MASTER) + + self._master = _get_session_master(self._cluster_spec, self._task_type, + self._task_id, tf_config) + self._evaluation_master = _get_eval_session_master(self._task_type, + tf_config) + self._num_ps_replicas = _count_ps(self._cluster_spec) + self._num_worker_replicas = _count_worker( + self._cluster_spec, chief_task_type=TaskType.MASTER) + + self._is_chief = self._task_type == TaskType.MASTER + + @property + def cluster_spec(self): + return self._cluster_spec + + @property + def device_fn(self): + """Returns the device_fn. + + If device_fn is not `None`, it overrides the default + device function used in `Estimator`. + Otherwise the default one is used. + """ + return self._device_fn + + @property + def evaluation_master(self): + return self._evaluation_master + + @property + def is_chief(self): + return self._is_chief + + @property + def master(self): + return self._master + + @property + def num_ps_replicas(self): + return self._num_ps_replicas + + @property + def num_worker_replicas(self): + return self._num_worker_replicas + + @property + def task_id(self): + return self._task_id + + @property + def global_id_in_cluster(self): + """The global id in the training cluster. + + All global ids in the training cluster are assigned from an increasing + sequence of consecutive integers. The first id is 0. + + Note: Task id (the property field `task_id`) is tracking the index of the + node among all nodes with the SAME task type. For example, given the cluster + definition as follows: + + ``` + cluster = {'chief': ['host0:2222'], + 'ps': ['host1:2222', 'host2:2222'], + 'worker': ['host3:2222', 'host4:2222', 'host5:2222']} + ``` + + Nodes with task type `worker` can have id 0, 1, 2. Nodes with task type + `ps` can have id, 0, 1. So, `task_id` is not unique, but the pair + (`task_type`, `task_id`) can uniquely determine a node in the cluster. + + Global id, i.e., this field, is tracking the index of the node among ALL + nodes in the cluster. It is uniquely assigned. For example, for the cluster + spec given above, the global ids are assigned as: + ``` + task_type | task_id | global_id + -------------------------------- + chief | 0 | 0 + worker | 0 | 1 + worker | 1 | 2 + worker | 2 | 3 + ps | 0 | 4 + ps | 1 | 5 + ``` + + Returns: + An integer id. + """ + return self._global_id_in_cluster + + @property + def experimental_max_worker_delay_secs(self): + return self._experimental_max_worker_delay_secs + + @property + def task_type(self): + return self._task_type + + @property + def tf_random_seed(self): + return self._tf_random_seed + + @property + def save_summary_steps(self): + return self._save_summary_steps + + @property + def save_checkpoints_secs(self): + return self._save_checkpoints_secs + + @property + def session_config(self): + return self._session_config + + @property + def save_checkpoints_steps(self): + return self._save_checkpoints_steps + + @property + def checkpoint_save_graph_def(self): + return self._checkpoint_save_graph_def + + @property + def keep_checkpoint_max(self): + return self._keep_checkpoint_max + + @property + def session_creation_timeout_secs(self): + return self._session_creation_timeout_secs + + @property + def keep_checkpoint_every_n_hours(self): + return self._keep_checkpoint_every_n_hours + + @property + def log_step_count_steps(self): + return self._log_step_count_steps + + @property + def model_dir(self): + return self._model_dir + + @property + def service(self): + """Returns the platform defined (in TF_CONFIG) service dict.""" + return self._service + + @property + def train_distribute(self): + """Optional `tf.distribute.Strategy` for training.""" + return self._train_distribute + + @property + def eval_distribute(self): + """Optional `tf.distribute.Strategy` for evaluation.""" + return self._eval_distribute + + @property + def protocol(self): + """Returns the optional protocol value.""" + return self._protocol + + def replace(self, **kwargs): + """Returns a new instance of `RunConfig` replacing specified properties. + + Only the properties in the following list are allowed to be replaced: + + - `model_dir`, + - `tf_random_seed`, + - `save_summary_steps`, + - `save_checkpoints_steps`, + - `save_checkpoints_secs`, + - `session_config`, + - `keep_checkpoint_max`, + - `keep_checkpoint_every_n_hours`, + - `log_step_count_steps`, + - `train_distribute`, + - `device_fn`, + - `protocol`. + - `eval_distribute`, + - `experimental_distribute`, + - `experimental_max_worker_delay_secs`, + + In addition, either `save_checkpoints_steps` or `save_checkpoints_secs` + can be set (should not be both). + + Args: + **kwargs: keyword named properties with new values. + + Raises: + ValueError: If any property name in `kwargs` does not exist or is not + allowed to be replaced, or both `save_checkpoints_steps` and + `save_checkpoints_secs` are set. + + Returns: + a new instance of `RunConfig`. + """ + return RunConfig._replace( + copy.deepcopy(self), + allowed_properties_list=_DEFAULT_REPLACEABLE_LIST, + **kwargs) + + @staticmethod + def _replace(config, allowed_properties_list=None, **kwargs): + """See `replace`. + + N.B.: This implementation assumes that for key named "foo", the underlying + property the RunConfig holds is "_foo" (with one leading underscore). + + Args: + config: The RunConfig to replace the values of. + allowed_properties_list: The property name list allowed to be replaced. + **kwargs: keyword named properties with new values. + + Raises: + ValueError: If any property name in `kwargs` does not exist or is not + allowed to be replaced, or both `save_checkpoints_steps` and + `save_checkpoints_secs` are set. + + Returns: + a new instance of `RunConfig`. + """ + + allowed_properties_list = allowed_properties_list or [] + + for key, new_value in six.iteritems(kwargs): + if key in allowed_properties_list: + setattr(config, '_' + key, new_value) + continue + + raise ValueError( + 'Replacing {} is not supported. Allowed properties are {}.'.format( + key, allowed_properties_list)) + + _validate_save_ckpt_with_replaced_keys(config, kwargs.keys()) + _validate_properties(config) + return config + + +def _get_model_dir(tf_config, model_dir): + """Returns `model_dir` based user provided `tf_config` or `model_dir`.""" + # pylint: disable=g-explicit-bool-comparison + + # Empty string is treated as False in Python condition check, which triggers + # some confusing error messages. For example, 'a or b' returns None if a is '' + # and b is None. `None` is allowed for model_dir but '' is not allowed. Here, + # explicitly check empty string to provide clear error message. + if model_dir == '': + raise ValueError('model_dir should be non-empty.') + + model_dir_in_tf_config = tf_config.get('model_dir') + if model_dir_in_tf_config == '': + raise ValueError('model_dir in TF_CONFIG should be non-empty.') + + if model_dir_in_tf_config: + if model_dir and model_dir_in_tf_config != model_dir: + raise ValueError( + '`model_dir` provided in RunConfig construct, if set, ' + 'must have the same value as the model_dir in TF_CONFIG. ' + 'model_dir: {}\nTF_CONFIG["model_dir"]: {}.\n'.format( + model_dir, model_dir_in_tf_config)) + + tf.compat.v1.logging.info('Using model_dir in TF_CONFIG: %s', + model_dir_in_tf_config) + + return model_dir or model_dir_in_tf_config + + +def path_to_str(path): + """Returns the file system path representation of a `PathLike` object, else as it is. + + Args: + path: An object that can be converted to path representation. + + Returns: + A `str` object. + """ + if hasattr(path, '__fspath__'): + path = tf.compat.as_str_any(path.__fspath__()) + return path diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/tools/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/tools/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/tools/analytics.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/tools/analytics.py new file mode 100644 index 0000000000000000000000000000000000000000..ac78b1edd116cd55e8101621f9173c97bdc21526 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/tools/analytics.py @@ -0,0 +1,37 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Analytics helpers library.""" +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + + +def track_usage(tool_id, tags): + """No usage tracking for external library. + + Args: + tool_id: A string identifier for tool to be tracked. + tags: list of string tags that will be added to the tracking. + """ + del tool_id, tags # Unused externally. + + +def track_numerical_issues(exc_info): + """No tracking for external library. + + Args: + exc_info: Output from `sys.exc_info` (type, value, traceback) + """ + del exc_info diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/tools/checkpoint_converter.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/tools/checkpoint_converter.py new file mode 100644 index 0000000000000000000000000000000000000000..15514992d20a3399b13aefa6602595f6cfd3ff02 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/tools/checkpoint_converter.py @@ -0,0 +1,362 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +r"""Checkpoint converter for Canned Estimators in TF 1.x. + +This checkpoint converter tool is mainly for Canned Estimators, including DNN +Linear and DNNLinearCombined estimators. The allowed optimizers to be converted +include Adam, Adagrad, Ftrl, RMSProp, and SGD. + +Note that, this converter is not suitable for the case where 'dnn_optimizer' +and 'linear_optimizer' in DNNLinearCombined model are the same. + +If your current canned estimators and checkpoints are from TF 1.x, after you +migrate the canned estimator to v2 with `tf.keras.optimizers.*`, the converted +checkpoint allow you to restore and retrain the model in TF 2.0. + +Usage: + python checkpoint_convert.py '/path/to/checkpoint' '/path/to/graph.pbtxt' \ + '/path/to/new_checkpoint' + +For example, if there is a V1 checkpoint to be converted and the files include: + /tmp/my_checkpoint/model.ckpt-100.data-00000-of-00001 + /tmp/my_checkpoint/model.ckpt-100.index + /tmp/my_checkpoint/model.ckpt-100.meta + /tmp/my_checkpoint/graph.pbtxt + +use the following command: + mkdir /tmp/my_converted_checkpoint && + python checkpoint_convert.py \ + /tmp/my_checkpoint/model.ckpt-100 /tmp/my_checkpoint/graph.pbtxt \ + /tmp/my_converted_checkpoint/model.ckpt-100 + +This will generate three converted checkpoint files corresponding to the three +old checkpoint files in the new directory: + /tmp/my_converted_checkpoint/model.ckpt-100.data-00000-of-00001 + /tmp/my_converted_checkpoint/model.ckpt-100.index + /tmp/my_converted_checkpoint/model.ckpt-100.meta +""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import argparse +import sys +import tensorflow as tf +from google.protobuf import text_format + +# Optimizer name mapping from v1 to v2. +OPT_NAME_V1_TO_V2 = { + 'Adagrad': 'Adagrad', + 'RMSProp': 'RMSprop', + 'Ftrl': 'Ftrl', + 'Adam': 'Adam', + 'SGD': 'SGD', +} + +# Hyper-paratmeters of optimizer in checkpoint. +HP_IN_CKPT = { + 'Adam': { + 'beta1_power': 'training/Adam/beta_1', + 'beta2_power': 'training/Adam/beta_2', + }, +} + +# Optimzier variable name mapping from v1 to v2. +OPT_VAR_NAME_V1_TO_V2 = { + 'Adam': { + 'Adam': 'm', + 'Adam_1': 'v', + }, + 'Ftrl': { + 'Ftrl': 'accumulator', + 'Ftrl_1': 'linear', + }, + 'RMSProp': { + 'RMSProp': 'rms', + 'RMSProp_1': None, + }, + 'Adagrad': { + 'Adagrad': 'accumulator', + }, +} + +# Hyper-paratmeters of optimizer in graph. +HP_IN_GRAPH = { + 'Adam': ['decay', 'learning_rate'], + 'Ftrl': [ + 'decay', 'l1_regularization_strength', 'l2_regularization_strength', + 'beta', 'learning_rate', 'learning_rate_power' + ], + 'RMSProp': ['decay', 'learning_rate', 'momentum', 'rho'], + 'Adagrad': ['decay', 'learning_rate'], + 'SGD': ['decay', 'learning_rate', 'momentum'], +} + +# optimizer v2 instance. +OPT_V2_INSTANCE = { + 'Adagrad': tf.keras.optimizers.legacy.Adagrad(), + 'Adam': tf.keras.optimizers.legacy.Adam(), + 'Ftrl': tf.keras.optimizers.legacy.Ftrl(), + 'RMSProp': tf.keras.optimizers.legacy.RMSprop(), + 'SGD': tf.keras.optimizers.legacy.SGD(), +} + + +def _add_new_variable(initial_value, var_name_v2, var_name_v1, var_map, + var_names_map): + """Creates a new variable and add it to the variable maps.""" + var = tf.Variable(initial_value, name=var_name_v2) + var_map[var_name_v2] = var + var_names_map[var_name_v2] = var_name_v1 + + +def _add_opt_variable(opt_name_v2, var_name_v1, idx, suffix_v2, reader, var_map, + var_names_map): + """Adds a new optimizer v2 variable.""" + var_name_v2 = 'training/' + opt_name_v2 + '/' + var_name_v1[:idx] + suffix_v2 + tensor = reader.get_tensor(var_name_v1) + _add_new_variable(tensor, var_name_v2, var_name_v1, var_map, var_names_map) + + +def _convert_variables_in_ckpt(opt_name_v1, reader, variable_names, var_map, + var_names_map, est_type): + """Converts all variables in checkpoint from v1 to v2.""" + global_step = None + hp_ckpt = None + # Global step is needed for Adam for hyper parameter conversion. + if opt_name_v1 == 'Adam': + global_step = reader.get_tensor('global_step') + if opt_name_v1 in HP_IN_CKPT: + hp_ckpt = HP_IN_CKPT[opt_name_v1] + opt_name_v2 = OPT_NAME_V1_TO_V2[opt_name_v1] + + # For variables with equivalent mapping in checkpoint. There are three types: + # 1) Hyper parameters. This is mainly for Adam optimizer. + # 2) Optimizer variables. + # 3) Model variables. + for var_name in variable_names: + # If a hyper parameter variable is in the checkpoint. + if hp_ckpt and any(hp_name in var_name for hp_name in hp_ckpt): + for hp_name in hp_ckpt: + if hp_name in var_name: + var_name_v2 = hp_ckpt[hp_name] + tensor = reader.get_tensor(var_name) + # For Adam optimizer, in the old checkpoint, the optimizer variables + # are beta1_power and beta2_power. The corresponding variables in the + # new checkpoint are beta_1 and beta_2, and + # beta_1 = pow(beta1_power, 1/global_step) + # beta_2 = pow(beta2_power, 1/global_step) + tensor = tf.math.pow(tensor, 1.0 / global_step) + _add_new_variable(tensor, var_name_v2, var_name, var_map, + var_names_map) + break + # If it's an optimizer variable. + elif opt_name_v1 in var_name: + suffix_mapping = OPT_VAR_NAME_V1_TO_V2[opt_name_v1] + suffix_v1 = var_name.rsplit('/')[-1] + suffix_v2 = suffix_mapping[suffix_v1] + if suffix_v2: + # For DNN model. + if est_type == 'dnn': + # The optimizer variable of DNN model in TF 1.x has 't_0' in its + # name (b/131719899). This is amended in TF 2.0. + idx = var_name.rfind('t_0') + _add_opt_variable(opt_name_v2, var_name, idx, suffix_v2, reader, + var_map, var_names_map) + # for Linear model. + elif est_type == 'linear': + # The optimizer variable of Linear model in TF 1.x has 'part_0' in its + # name (b/131719899). This is amended in TF 2.0. + idx = var_name.rfind('part_0') + _add_opt_variable(opt_name_v2, var_name, idx, suffix_v2, reader, + var_map, var_names_map) + # for DNNLinearCombined model. + else: + idx = var_name.rfind(suffix_v1) + _add_opt_variable(opt_name_v2, var_name, idx, suffix_v2, reader, + var_map, var_names_map) + # If it's a model variable which is already backward compatible. + else: + tensor = reader.get_tensor(var_name) + _add_new_variable(tensor, var_name, var_name, var_map, var_names_map) + + +def _convert_hyper_params_in_graph(graph_from_path, opt_name_v1, var_map, + var_names_map): + """Generates hyper parameters for optimizer v2 from graph.pbtxt.""" + with tf.io.gfile.GFile(graph_from_path) as f: + graph_def = text_format.Parse(f.read(), tf.compat.v1.GraphDef()) + + # In keras optimizer, the hyper parameters are also stored in the checkpoint, + # while v1 checkpoint doesn't contain any hyper parameters. For the + # hyper parameter variables, there are two cases: + # 1) The hyper parameter exist in the graph. + # If so, the hyper parameter value needs to be extracted from the graph + # node. + # 2) The hyper parameter doesn't exist in the graph. + # The value of the hyper parameter is set as the default value from the + # config. + nodes_full = HP_IN_GRAPH[opt_name_v1] + nodes_in_graph = [] + opt_name_v2 = OPT_NAME_V1_TO_V2[opt_name_v1] + tf.compat.v1.logging.info('For hyper parameter variables that are in Graph:') + for node in graph_def.node: + node_name = node.name.rsplit('/')[-1] + # For case 1), if the hyper parameter of the keras optimizer can be found + # in the graph, the graph node value is extracted as the hyper parameter + # variable value, and added to the new variable list. + if opt_name_v1 + '/' + node_name in nodes_full: + hp_value = node.attr.get('value').tensor.float_val[0] + hp_name_v2 = 'training/' + opt_name_v2 + '/' + node_name + tf.compat.v1.logging.info( + 'Hyper parameter {} with value {} found in Graph.'.format( + hp_name_v2, hp_value)) + _add_new_variable(hp_value, hp_name_v2, node_name, var_map, var_names_map) + # Adds this node to nodes_in_graph + nodes_in_graph.append(node_name) + + # For case 2), if the hyper parameter is not in graph, we need to add it + # manually. The tensor value is its default value from optimizer v2 config. + nodes_not_in_graph = sorted(list(set(nodes_full) - set(nodes_in_graph))) + opt_v2_config = OPT_V2_INSTANCE[opt_name_v1].get_config() + tf.compat.v1.logging.info( + 'For hyper parameter variables that are NOT in Graph:') + for node_name in nodes_not_in_graph: + hp_name_v2 = 'training/' + opt_name_v2 + '/' + node_name + tf.compat.v1.logging.info( + 'Hyper parameter {} with default value {} is added.'.format( + hp_name_v2, opt_v2_config[node_name])) + _add_new_variable(opt_v2_config[node_name], hp_name_v2, node_name, var_map, + var_names_map) + + +def convert_checkpoint(estimator_type, source_checkpoint, source_graph, + target_checkpoint): + """Converts checkpoint from TF 1.x to TF 2.0 for CannedEstimator. + + Args: + estimator_type: The type of estimator to be converted. So far, the allowed + args include 'dnn', 'linear', and 'combined'. + source_checkpoint: Path to the source checkpoint file to be read in. + source_graph: Path to the source graph file to be read in. + target_checkpoint: Path to the target checkpoint to be written out. + """ + with tf.Graph().as_default(): + # Get v1 optimizer names and it's corresponding variable name + reader = tf.compat.v1.train.NewCheckpointReader(source_checkpoint) + variable_names = sorted(reader.get_variable_to_shape_map()) + opt_names_v1 = {} + for var_name in variable_names: + for opt_name in OPT_NAME_V1_TO_V2: + if opt_name in var_name: + opt_names_v1[opt_name] = var_name + + # SGD doesn't appear in optimizer variables, so we need to add it manually + # if no optimizer is found in checkpoint for DNN or Linear model. + if not opt_names_v1: + if estimator_type == 'dnn' or estimator_type == 'linear': + opt_names_v1['SGD'] = '' + # As the case is not handled in the converter if dnn_optimizer and + # linear_optimizer in DNNLinearCombined model are the same, an error is + # is raised if two SGD optimizers are used in DNNLinearCombined model. + elif estimator_type == 'combined': + raise ValueError('Two `SGD` optimizers are used in DNNLinearCombined ' + 'model, and this is not handled by the checkpoint ' + 'converter.') + + # A dict mapping from v2 variable name to the v2 variable. + var_map = {} + # A dict mapping from v2 variable name to v1 variable name. + var_names_map = {} + + # Determine the names of dnn_optimizer and linear_optimizer in + # DNNLinearCombined model. + if estimator_type == 'combined': + linear_opt_v1 = None + if len(opt_names_v1) == 1: # When one of the optimizer is 'SGD'. + key = list(opt_names_v1.keys())[0] + # Case 1: linear_optimizer is non-SGD, and dnn_optimizer is SGD. + if opt_names_v1[key].startswith('linear/linear_model/'): + linear_opt_v1 = key + # Case 2: linear_optimizer is SGD, and dnn_optimizer is non-SGD. + if not linear_opt_v1: + linear_opt_v1 = 'SGD' + opt_names_v1['SGD'] = '' + else: # two non-SGD optimizers + for key in opt_names_v1: + if opt_names_v1[key].startswith('linear/linear_model/'): + linear_opt_v1 = key + # Add the 'iter' hyper parameter to the new checkpoint for + # linear_optimizer. Note dnn_optimizer uses global_step. + tensor = reader.get_tensor('global_step') + var_name_v2 = 'training/' + OPT_NAME_V1_TO_V2[linear_opt_v1] + '/iter' + var_name_v1 = 'global_step' + _add_new_variable(tensor, var_name_v2, var_name_v1, var_map, + var_names_map) + + for opt_name_v1 in opt_names_v1: + # Convert all existing variables from checkpoint. + _convert_variables_in_ckpt(opt_name_v1, reader, variable_names, var_map, + var_names_map, estimator_type) + # Convert hyper parameters for optimizer v2 from the graph. + _convert_hyper_params_in_graph(source_graph, opt_name_v1, var_map, + var_names_map) + + # Log the variable mapping from opt v1 to v2. + tf.compat.v1.logging.info( + '<----- Variable names converted (v1 --> v2): ----->') + for name_v2 in var_names_map: + tf.compat.v1.logging.info('%s --> %s' % (var_names_map[name_v2], name_v2)) + + # Save to checkpoint v2. + saver = tf.compat.v1.train.Saver(var_list=var_map) + with tf.compat.v1.Session() as sess: + sess.run(tf.compat.v1.initializers.global_variables()) + tf.compat.v1.logging.info('Writing checkpoint_to_path %s' % + target_checkpoint) + saver.save(sess, target_checkpoint) + + +def main(_): + convert_checkpoint( + FLAGS.estimator_type, + FLAGS.source_checkpoint, + FLAGS.source_graph, + FLAGS.target_checkpoint, + ) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument( + 'estimator_type', + type=str, + choices=['dnn', 'linear', 'combined'], + help='The type of estimator to be converted. So far, the checkpoint ' + 'converter only supports Canned Estimator. So the allowed types ' + 'include linear, dnn and combined.') + parser.add_argument( + 'source_checkpoint', + type=str, + help='Path to source checkpoint file to be read in.') + parser.add_argument( + 'source_graph', type=str, help='Path to source graph file to be read in.') + parser.add_argument( + 'target_checkpoint', + type=str, + help='Path to checkpoint file to be written out.') + FLAGS, unparsed = parser.parse_known_args() + tf.compat.v1.app.run(main=main, argv=[sys.argv[0]] + unparsed) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/tpu/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/tpu/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/tpu/_tpu_estimator_embedding.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/tpu/_tpu_estimator_embedding.py new file mode 100644 index 0000000000000000000000000000000000000000..6981d28abcb1d244269726c58a539762a028a800 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/tpu/_tpu_estimator_embedding.py @@ -0,0 +1,640 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# =================================================================== +"""Tooling for support TPU embedding in TPUEstimator.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import collections +import tensorflow as tf + +from tensorflow.python.feature_column import feature_column as core_fc +from tensorflow.python.feature_column import feature_column_lib as core_fc_lib +from tensorflow.python.feature_column import utils as fc_utils +from tensorflow.python.framework import ops +from tensorflow.python.tpu import feature_column as tpu_fc +from tensorflow.python.tpu import feature_column_v2 as tpu_fc_v2 +from tensorflow.python.tpu import tpu_embedding +from tensorflow.python.tpu.tpu_embedding import AdagradParameters +from tensorflow.python.tpu.tpu_embedding import AdamParameters +from tensorflow.python.tpu.tpu_embedding import FtrlParameters +from tensorflow.python.tpu.tpu_embedding import MomentumParameters +from tensorflow.python.tpu.tpu_embedding import ProximalAdagradParameters +from tensorflow.python.tpu.tpu_embedding import RMSPropParameters +from tensorflow.python.tpu.tpu_embedding import StochasticGradientDescentParameters +from tensorflow_estimator.python.estimator import model_fn as model_fn_lib +from tensorflow_estimator.python.estimator.estimator_export import estimator_export + +# pylint: disable=protected-access +_TPU_EMBEDDING_COLUMN_CLASSES = (tpu_fc._TPUEmbeddingColumn, + tpu_fc._TPUSharedEmbeddingColumn, + tpu_fc_v2._TPUEmbeddingColumnV2, + tpu_fc_v2._TPUSharedEmbeddingColumnV2) +_TPU_DEVICE_SPECIFIC_EMBEDDING_COLUMNS = ( + tpu_fc_v2._TPUDeviceSpecificEmbeddingColumnV2, + tpu_fc_v2._TPUSharedDeviceSpecificEmbeddingColumnV2) +_EMBEDDING_COLUMN_CLASSES = (core_fc._EmbeddingColumn, + core_fc_lib.EmbeddingColumn, + core_fc._SharedEmbeddingColumn) +_SUPPORTED_FEATURE_COLUMNS = (core_fc._NumericColumn, core_fc_lib.NumericColumn) + +_SUPPORTED_OPTIMIZERS = ( + ProximalAdagradParameters, + AdagradParameters, + AdamParameters, + FtrlParameters, + StochasticGradientDescentParameters, + MomentumParameters, + RMSPropParameters, +) + +# pylint: enable=protected-access + +_TABLE_NAME_PREFIX = 'tbl_' +_LEN_TABLE_NAME_PREFIX = len(_TABLE_NAME_PREFIX) + + +def _get_table_name_from_embedding_var_name(embedding_var_name): + return '{}{}'.format(_TABLE_NAME_PREFIX, embedding_var_name) + + +def _get_embedding_var_name_from_table_name(table_name): + return table_name[_LEN_TABLE_NAME_PREFIX:] + + +def _get_embedding_variable_name(scope_name, var_name): + if scope_name: + scope_name = scope_name + '/' + return '{}{}'.format(scope_name, var_name) + + +def _get_slot_variable_names(scope_name, var_name, optimization_parameters): + """Return embedding variable names which are consistent with CPU runs.""" + if scope_name: + scope_name = scope_name + '/' + if isinstance(optimization_parameters, + tf.compat.v1.tpu.experimental.AdagradParameters): + return tpu_embedding.AdagradSlotVariableNames('{}{}/Adagrad'.format( + scope_name, var_name)) + elif isinstance(optimization_parameters, + tf.compat.v1.tpu.experimental.AdamParameters): + return tpu_embedding.AdamSlotVariableNames( + '{}{}/Adam/m'.format(scope_name, var_name), + '{}{}/Adam/v'.format(scope_name, var_name)) + elif isinstance(optimization_parameters, + tf.compat.v1.tpu.experimental.FtrlParameters): + return tpu_embedding.FtrlSlotVariableNames( + '{}{}/Ftrl'.format(scope_name, var_name), # accumulator + '{}{}/Ftrl_1'.format(scope_name, var_name)) # linear + elif isinstance(optimization_parameters, MomentumParameters): + return tpu_embedding.MomentumSlotVariableNames('{}{}/Momentum'.format( + scope_name, var_name)) + elif isinstance(optimization_parameters, RMSPropParameters): + return tpu_embedding.RMSPropSlotVariableNames( + ms='{}{}/RMSProp/ms'.format(scope_name, var_name), + mom='{}{}/RMSProp/mom'.format(scope_name, var_name), + ) + elif isinstance(optimization_parameters, ProximalAdagradParameters): + return tpu_embedding.ProximalAdagradSlotVariableNames( + '{}{}/ProximalAdagrad'.format(scope_name, var_name)) + elif isinstance( + optimization_parameters, + tf.compat.v1.tpu.experimental.StochasticGradientDescentParameters): + return None + else: + raise ValueError('Support to infer full variable name ' + 'for optimization_parameter {} has not been added.'.format( + optimization_parameters)) + + +def get_full_variable_names(graph, + table_to_config_dict, + optimization_parameters=None): + """Return embedding variable names and slot variables which are consistent with CPU runs.""" + collection = graph.get_collection_ref(tpu_fc._TPU_FC_TO_SCOPE) # pylint: disable=protected-access + if not collection: + raise RuntimeError( + 'Embedding feature column did not capture any thing. Make sure the ' + 'feature columns passed to TPUEstimator constructor is properly ' + 'used in model_fn.') + + embedding_variable_name_by_table = {} + slot_variable_names_by_table = {} + for table_name in table_to_config_dict: + embedding_var_name = _get_embedding_var_name_from_table_name(table_name) + (scope_name, var_name) = collection[0][embedding_var_name] + embedding_variable_name_by_table[table_name] = ( + _get_embedding_variable_name(scope_name, var_name)) + if optimization_parameters: + slot_variable_names_by_table[table_name] = _get_slot_variable_names( + scope_name, var_name, optimization_parameters) + + graph.clear_collection(tpu_fc._TPU_FC_TO_SCOPE) # pylint: disable=protected-access + return embedding_variable_name_by_table, slot_variable_names_by_table + + +def get_configs_from_feature_columns(feature_columns): + """Create configs for TPUEmbedding etc from a list of feature columns. + + Args: + feature_columns: a list of supported feature columns. + + Returns: + A tuple of dicts, the first maps tables to their config, the second maps + features to their config, the third maps learning rate key to callback that + takes global step and outputs dynamic learning rate. + """ + + allowed = ( + tpu_fc_v2._TPUEmbeddingColumnV2, # pylint: disable=protected-access + tpu_fc_v2._TPUSharedEmbeddingColumnV2) # pylint: disable=protected-access + warn = (tpu_fc._TPUEmbeddingColumn, tpu_fc._TPUSharedEmbeddingColumn) # pylint: disable=protected-access + + for column in feature_columns: + if not isinstance(column, allowed + warn): + raise TypeError( + 'Unsupported feature column {}. Supported types are {}.'.format( + type(column), allowed)) + if isinstance(column, warn): + tf.compat.v1.logging.warn( + 'Columns of type {} are deprecated. Supported types are {}.'.format( + type(column), allowed)) + + table_to_config = {} + feature_to_config = {} + for column in feature_columns: + feature_name = column.get_feature_key_name() + table_name = _get_table_name_from_embedding_var_name( + column.get_embedding_var_name()) + if feature_name in feature_to_config: + raise ValueError( + 'Feature column {} is used with multiple embeddings and this is ' + 'not supported.'.format(feature_name)) + feature_to_config[feature_name] = tpu_embedding.FeatureConfig( + table_id=table_name, + max_sequence_length=column.get_max_sequence_length(), + weight_key=column.get_weight_key_name()) + vocabulary_size, dimension = column.get_embedding_table_size() + table_to_config[table_name] = tpu_embedding.TableConfig( + vocabulary_size=vocabulary_size, + dimension=dimension, + initializer=column.get_initializer(), + combiner=column.get_combiner(), + learning_rate_fn=column.get_learning_rate_fn()) + + return table_to_config, feature_to_config + + +@estimator_export(v1=['estimator.tpu.experimental.EmbeddingConfigSpec']) +class EmbeddingConfigSpec( + collections.namedtuple('EmbeddingConfigSpec', [ + 'feature_columns', 'tensor_core_feature_columns', + 'optimization_parameters', 'clipping_limit', + 'pipeline_execution_with_tensor_core', + 'experimental_gradient_multiplier_fn', 'feature_to_config_dict', + 'table_to_config_dict', 'partition_strategy', 'profile_data_directory' + ])): + """Class to keep track of the specification for TPU embeddings. + + Pass this class to `tf.estimator.tpu.TPUEstimator` via the + `embedding_config_spec` parameter. At minimum you need to specify + `feature_columns` and `optimization_parameters`. The feature columns passed + should be created with some combination of + `tf.tpu.experimental.embedding_column` and + `tf.tpu.experimental.shared_embedding_columns`. + + TPU embeddings do not support arbitrary Tensorflow optimizers and the + main optimizer you use for your model will be ignored for the embedding table + variables. Instead TPU embeddigns support a fixed set of predefined optimizers + that you can select from and set the parameters of. These include adagrad, + adam and stochastic gradient descent. Each supported optimizer has a + `Parameters` class in the `tf.tpu.experimental` namespace. + + ``` + column_a = tf.feature_column.categorical_column_with_identity(...) + column_b = tf.feature_column.categorical_column_with_identity(...) + column_c = tf.feature_column.categorical_column_with_identity(...) + tpu_shared_columns = tf.tpu.experimental.shared_embedding_columns( + [column_a, column_b], 10) + tpu_non_shared_column = tf.tpu.experimental.embedding_column( + column_c, 10) + tpu_columns = [tpu_non_shared_column] + tpu_shared_columns + ... + def model_fn(features): + dense_features = tf.keras.layers.DenseFeature(tpu_columns) + embedded_feature = dense_features(features) + ... + + estimator = tf.estimator.tpu.TPUEstimator( + model_fn=model_fn, + ... + embedding_config_spec=tf.estimator.tpu.experimental.EmbeddingConfigSpec( + column=tpu_columns, + optimization_parameters=( + tf.estimator.tpu.experimental.AdagradParameters(0.1)))) + ``` + + @compatibility(TF2) + TPU Estimator manages its own TensorFlow graph and session, so it is not + compatible with TF2 behaviors. We recommend that you migrate to the newer + `tf.distribute.TPUStrategy`. See the + [TPU guide](https://www.tensorflow.org/guide/tpu) for details. + @end_compatibility + """ + + def __new__(cls, + feature_columns=None, + optimization_parameters=None, + clipping_limit=None, + pipeline_execution_with_tensor_core=False, + experimental_gradient_multiplier_fn=None, + feature_to_config_dict=None, + table_to_config_dict=None, + partition_strategy='div', + profile_data_directory=None): + """Creates an `EmbeddingConfigSpec` instance. + + Args: + feature_columns: All embedding `FeatureColumn`s used by model. + optimization_parameters: An instance of `AdagradParameters`, + `AdamParameters` or `StochasticGradientDescentParameters`. This + optimizer will be applied to all embedding variables specified by + `feature_columns`. + clipping_limit: (Optional) Clipping limit (absolute value). + pipeline_execution_with_tensor_core: setting this to `True` makes training + faster, but trained model will be different if step N and step N+1 + involve the same set of embedding IDs. Please see + `tpu_embedding_configuration.proto` for details. + experimental_gradient_multiplier_fn: (Optional) A Fn taking global step as + input returning the current multiplier for all embedding gradients. + feature_to_config_dict: A dictionary mapping feature names to instances of + the class `FeatureConfig`. Either features_columns or the pair of + `feature_to_config_dict` and `table_to_config_dict` must be specified. + table_to_config_dict: A dictionary mapping feature names to instances of + the class `TableConfig`. Either features_columns or the pair of + `feature_to_config_dict` and `table_to_config_dict` must be specified. + partition_strategy: A string, determining how tensors are sharded to the + tpu hosts. See `tf.nn.safe_embedding_lookup_sparse` for more details. + Allowed value are `"div"` and `"mod"'. If `"mod"` is used, evaluation + and exporting the model to CPU will not work as expected. + profile_data_directory: Directory where embedding lookup statistics are + stored. These statistics summarize information about the inputs to the + embedding lookup operation, in particular, the average number of + embedding IDs per example and how well the embedding IDs are load + balanced across the system. The lookup statistics are used during TPU + initialization for embedding table partitioning. Collection of lookup + statistics is done at runtime by profiling the embedding inputs, only a + small fraction of input samples are profiled to minimize host CPU + overhead. Once a suitable number of samples are profiled, the lookup + statistics are saved to table-specific files in the profile data + directory generally at the end of a TPU training loop. The filename + corresponding to each table is obtained by hashing table specific + parameters (e.g., table name and number of features) and global + configuration parameters (e.g., sharding strategy and task count). The + same profile data directory can be shared among several models to reuse + embedding lookup statistics. + + Returns: + An `EmbeddingConfigSpec` instance. + + Raises: + ValueError: If the feature_columns are not specified. + TypeError: If the feature columns are not of ths correct type (one of + _SUPPORTED_FEATURE_COLUMNS, _TPU_EMBEDDING_COLUMN_CLASSES OR + _EMBEDDING_COLUMN_CLASSES). + ValueError: If `optimization_parameters` is not one of the required types. + """ + if (not feature_columns and + not (feature_to_config_dict and table_to_config_dict) or + (feature_columns and + (feature_to_config_dict and table_to_config_dict))): + raise ValueError('Exactly one of `feature_columns` and the pair ' + '`feature_to_config_dict` and `table_to_config_dict` ' + 'must be be specified.') + + if partition_strategy not in ('div', 'mod'): + raise ValueError('Invalid partition_strategy {}. Must be one of "mod" or ' + '"div".'.format(partition_strategy)) + + tensor_core_feature_columns = None + embedding_core_feature_columns = None + if feature_columns: + tensor_core_feature_columns = [] + embedding_core_feature_columns = [] + # It is unknown at this moment, whether the TPUEstimator is running in CPU + # or TPU mode. So allow non-TPU embedding columns also. + supported_classes = tuple( + list(_SUPPORTED_FEATURE_COLUMNS) + + list(_TPU_EMBEDDING_COLUMN_CLASSES) + list(_EMBEDDING_COLUMN_CLASSES)) + + for column in feature_columns: + if (isinstance(column, _TPU_DEVICE_SPECIFIC_EMBEDDING_COLUMNS) and + (column._embedding_lookup_device == # pylint: disable=protected-access + tpu_fc_v2.EmbeddingDevice.TPU_TENSOR_CORE)): + tensor_core_feature_columns.append(column) + else: + embedding_core_feature_columns.append(column) + if not isinstance(column, supported_classes): + raise TypeError( + 'All feature columns must be supported types in {}. Got {}' + .format(supported_classes, type(column))) + + if not isinstance(optimization_parameters, _SUPPORTED_OPTIMIZERS): + raise ValueError('optimization_parameters must be an instance of type ' + '{}. Got {}.'.format(_SUPPORTED_OPTIMIZERS, + type(optimization_parameters))) + else: + for feature, config in feature_to_config_dict.items(): + if not isinstance(config, tpu_embedding.FeatureConfig): + raise TypeError( + 'Config for feature {} must be of type `FeatureConfig`. Got {}' + .format(feature, type(config))) + if config.table_id not in table_to_config_dict: + raise ValueError('Feature {} refers to table {} which is not in the ' + 'table_to_config_dict.'.format( + feature, config.table_id)) + for table, config in table_to_config_dict.items(): + if not isinstance(config, tpu_embedding.TableConfig): + raise TypeError( + 'Config for table {} must be of type `TableConfig`. Got ' + '{}'.format(table, type(config))) + + return super(EmbeddingConfigSpec, cls).__new__( + cls, + feature_columns=embedding_core_feature_columns, + tensor_core_feature_columns=tensor_core_feature_columns, + optimization_parameters=optimization_parameters, + clipping_limit=clipping_limit, + pipeline_execution_with_tensor_core=pipeline_execution_with_tensor_core, + experimental_gradient_multiplier_fn=experimental_gradient_multiplier_fn, + feature_to_config_dict=feature_to_config_dict, + table_to_config_dict=table_to_config_dict, + partition_strategy=partition_strategy, + profile_data_directory=profile_data_directory) + + +class EmbeddingConfig(object): + """This is the internal immutable object for embedding config. + + `_EmbeddingConfig` is responsible to _translate_ user provided + `EmbeddingConfigSpec` to internal data structures, mostly constructor + arguments of `TPUEmbedding`. + """ + + def __init__(self, embedding_config_spec, train_batch_size, eval_batch_size, + num_hosts, num_cores, run_config): + if not embedding_config_spec: + raise ValueError('embedding_config_spec cannot be None.') + + self._embedding_config_spec = embedding_config_spec + self._train_batch_size = train_batch_size + self._eval_batch_size = eval_batch_size + self._num_hosts = num_hosts + self._num_cores = num_cores + self._run_config = run_config + + if embedding_config_spec.feature_columns: + self._table_to_config_dict, self._feature_to_config_dict = ( + get_configs_from_feature_columns( + embedding_config_spec.feature_columns)) + else: + self._table_to_config_dict = embedding_config_spec.table_to_config_dict + self._feature_to_config_dict = embedding_config_spec.feature_to_config_dict + self._partition_strategy = embedding_config_spec.partition_strategy + self._mode_to_tpu_embedding_dict = {} + self.dummy_table_variables = None + + self._grad_multiplier_fn = ( + embedding_config_spec.experimental_gradient_multiplier_fn) + + def get_grad_multiplier(self): + if self._grad_multiplier_fn: + return ops.convert_to_tensor( + self._grad_multiplier_fn(tf.compat.v1.train.get_global_step()), + dtype=tf.dtypes.float32) + + def has_embedding_tables(self): + return bool(self._table_to_config_dict) + + def _create_tpu_embedding(self, mode): + """Create tpu_embedding.TPUEmbedding based on mode.""" + if mode == model_fn_lib.ModeKeys.TRAIN: + batch_size = self._train_batch_size + else: + batch_size = self._eval_batch_size + + if mode == model_fn_lib.ModeKeys.TRAIN: + tpu_embedding_mode = tpu_embedding.TRAINING + optimization_parameters = ( + self._embedding_config_spec.optimization_parameters) + elif (mode == model_fn_lib.ModeKeys.EVAL or + mode == model_fn_lib.ModeKeys.PREDICT): + tpu_embedding_mode = tpu_embedding.INFERENCE + optimization_parameters = None + else: + raise ValueError('Mode {} is not supported.'.format(mode)) + + if self._run_config.cluster: + master = self._run_config.cluster.master() + cluster_spec = self._run_config.cluster.cluster_spec() + cluster_def = cluster_spec.as_cluster_def() if cluster_spec else None + else: + master = ( + self._run_config.evaluation_master + if mode == model_fn_lib.ModeKeys.EVAL else self._run_config.master) + cluster_def = None + master_job_name = None + if self._run_config.tpu_config.tpu_job_name is not None: + master_job_name = self._run_config.tpu_config.tpu_job_name + tpu_embedding_ = tpu_embedding.TPUEmbedding( + self._table_to_config_dict, + self._feature_to_config_dict, + batch_size, + tpu_embedding_mode, + master, + optimization_parameters, + cluster_def, + pipeline_execution_with_tensor_core=self._embedding_config_spec + .pipeline_execution_with_tensor_core, + partition_strategy=self._partition_strategy, + profile_data_directory=self._embedding_config_spec + .profile_data_directory, + master_job_name=master_job_name) + return tpu_embedding_ + + def get_tpu_embedding(self, mode): + if mode not in self._mode_to_tpu_embedding_dict: + self._mode_to_tpu_embedding_dict[mode] = ( + self._create_tpu_embedding(mode)) + return self._mode_to_tpu_embedding_dict[mode] + + +def _maybe_dense_to_sparse(tensor): + """Possibly convert a dense (rank 1 or 2) tensor to a SparseTensor.""" + # If already sparse, return as is. + if isinstance(tensor, tf.sparse.SparseTensor): + return tensor + indices = tf.compat.v1.where(tensor) + values = tf.compat.v1.gather_nd(tensor, indices) + shape = tf.compat.v1.shape(tensor, out_type=tf.dtypes.int64) + return tf.sparse.SparseTensor(indices, values, shape) + + +def split_inputs(ctx, features, labels, num_cores_per_batch=1): + """Splits the dense and sparse tensors inside the features and labels.""" + enqueue_datas = collections.OrderedDict() + + if ctx.embedding_config: + tpu_embedding_ = ctx.embedding_config.tpu_embedding + for feature_key in tpu_embedding_.feature_to_config_dict: + sparse_feature = _get_sparse_feature_from_feature(feature_key, features) + max_sequence_length = tpu_embedding_.feature_to_config_dict[ + feature_key].max_sequence_length + combiner = tpu_embedding_._table_to_config_dict[ + tpu_embedding_._feature_to_config_dict[feature_key].table_id].combiner + if max_sequence_length > 0: + length_feature_name = ( + tpu_fc.get_sequence_length_feature_key_name_from_feature_key_name( + feature_key)) + length_feature = tf.math.minimum( + fc_utils.sequence_length_from_sparse_tensor(sparse_feature), + max_sequence_length) + length_feature.set_shape(ctx.batch_size_for_input_fn) + features[length_feature_name] = length_feature + weight_key = tpu_embedding_.feature_to_config_dict[feature_key].weight_key + sparse_feature_split = _split_tensor(sparse_feature, num_cores_per_batch) + if combiner is None and not isinstance(sparse_feature, + tf.sparse.SparseTensor): + # A dense tensor with no combiner was provided so we assume that each + # of the embedding_indices belongs to a different sample (setting + # sample_indices to None). + if weight_key is not None: + raise ValueError( + 'Found weights {} for weighted_categorical_column, which is not' + 'compatible with sparse feature {} enqueued as dense tensor.' + .format(weight_key, feature_key)) + enqueue_data = [] + for i in range(num_cores_per_batch): + enqueue_data.append( + tpu_embedding.EnqueueData(sparse_feature_split[i])) + else: + weights = None + if isinstance(sparse_feature, tf.sparse.SparseTensor): + weights = _get_weights_from_features(weight_key, features) + weights_split = _split_tensor(weights, num_cores_per_batch) + enqueue_data = [] + for i in range(num_cores_per_batch): + split_weights = weights_split[i] if weights else None + enqueue_data.append( + tpu_embedding.EnqueueData.from_sparse_tensor( + _maybe_dense_to_sparse(sparse_feature_split[i]), + weights=split_weights)) + enqueue_datas[feature_key] = enqueue_data + if ctx.tensor_core_embedding_columns: + # pylint: disable=protected-access + for column in ctx.tensor_core_embedding_columns: + feature_key = column.categorical_column.key + sparse_feature = _get_sparse_feature_from_feature(feature_key, features) + padded_values, padded_mask = ( + tpu_fc_v2.pad_sparse_embedding_lookup_indices( + sparse_feature, column._tensor_core_shape[1])) + padded_values.set_shape( + [ctx.batch_size_for_input_fn, column._tensor_core_shape[1]]) + padded_mask.set_shape( + [ctx.batch_size_for_input_fn, column._tensor_core_shape[1]]) + features[feature_key] = padded_values + mask_key = feature_key + tpu_fc_v2._TENSOR_CORE_MASK_KEY_SUFFIX + if mask_key in features: + raise ValueError('Mask key {} for Tensor Core embedding is ' + 'already in use.'.format(mask_key)) + features[mask_key] = padded_mask + # pylint: enable=protected-access + + # Transpose the enqueue_datas dict into a list of dicts + enqueue_datas_list = [] + for i in range(num_cores_per_batch): + enqueue_data = {} + for key, value in enqueue_datas.items(): + enqueue_data[key] = value[i] + enqueue_datas_list.append(enqueue_data) + return features, labels, enqueue_datas_list + + +def _split_tensor(tensor, num_splits): + """Splits tensor into num_splits pieces, returns a list of pieces.""" + if tensor is None: + return [None] * num_splits + elif num_splits <= 0: + return ValueError( + 'Tensors cannot be split into {} pieces.'.format(num_splits)) + elif num_splits == 1: + return [tensor] + elif isinstance(tensor, tf.sparse.SparseTensor): + return tf.compat.v2.sparse.split(tensor, num_splits, axis=0) + else: + return tf.split(tensor, num_splits) + + +def _get_sparse_feature_from_feature(feature_key, features): + """Pop and return sparse feature.""" + sparse_feature = features.pop(feature_key) + if not sparse_feature.dtype.is_integer: + raise ValueError('SparseTensor with string as values are not supported. ' + 'If you are using categorical_column_with_vocabulary_file ' + 'or categorical_column_with_vocabulary_list, please call ' + 'your_column.categorical_column._transform_feature({{' + 'your_column.key: features[your_column.key]}}) in ' + 'your input_fn() to convert string to int. ' + 'feature_key = {}.'.format(feature_key)) + return sparse_feature + + +def _get_weights_from_features(weight_key_name, features): + """Pop and return feature for weights, possibly None.""" + weights = None + if weight_key_name is not None: + if weight_key_name in features: + weights = features.pop(weight_key_name) + else: + raise ValueError( + 'Cannot find weights {} for weighted_categorical_column.' + ' Please check if the weights are present in feature dict. Also' + ' note weight-sharing among weighted_categorical_column is not ' + 'supported on TPU.'.format(weight_key_name)) + if not isinstance(weights, tf.sparse.SparseTensor): + raise ValueError( + 'weighted_categorical_column with weight key name {} has dense ' + 'weights. Dense weights are not supported on TPU. Please use ' + 'sparse weights instead.'.format(weight_key_name)) + if weights.dtype is not tf.dtypes.float32: + weights = tf.cast(weights, dtype=tf.dtypes.float32) + return weights + + +def get_tpu_embedding_columns(feature_columns): + """Get feature columns meant to use TPU embedding. + + Args: + feature_columns: a list of feature columns. + + Returns: + A list of feature columns which can be placed on TPU embedding. + """ + tpu_embedding_columns = [] + for column in feature_columns: + if isinstance(column, _TPU_EMBEDDING_COLUMN_CLASSES): + tpu_embedding_columns.append(column) + return tpu_embedding_columns diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/tpu/error_handling.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/tpu/error_handling.py new file mode 100644 index 0000000000000000000000000000000000000000..97e0e27d3c49d1cce3c619793abc4e3a3e1a495b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/tpu/error_handling.py @@ -0,0 +1,154 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# =================================================================== +"""ErrorRendezvous handler for collecting errors from multiple threads.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import contextlib +import sys +import threading +import time + +import six +import tensorflow as tf +from tensorflow_estimator.python.estimator.tools import analytics + +_UNINTERESTING_ERRORS = (tf.errors.CancelledError,) +_IGNORED_ERRORS = ( + tf.errors.AbortedError, + tf.errors.UnavailableError, +) + +_CHECK_NUMERIC_OP_NAME = 'CheckNumerics' + + +class ErrorRendezvous(object): + """Resolve errors from multiple threads during TPU execution. + + TPU errors can occur on the infeed or outfeed threads as well as the main + training thread. + + Depending on which thread "wins" and receives the session error first, we may + end up showing users a confusing and non-actionable error message (session + cancelled) instead of a root cause (e.g. a bad filename). + + The rendezvous object provides a location to capture these errors until all + threads terminate. At that point we can choose the most informative error + to report. + """ + + def __init__(self, num_sources): + # string -> (message, traceback) + self._errors = {} + self._num_sources = num_sources + self._session_cancel_timer = None + + def record_error(self, source, exc_info, session=None): + """Report an exception from the given source. + + If a session is passed, a timer will be registered to close it after a few + seconds. This is necessary to ensure the main training loop does not hang + if an infeed/oufeed error occurs. We sleep a few seconds to allow a more + interesting error from another thread to propagate. + + Args: + source: string, source of the error + exc_info: Output from `sys.exc_info` (type, value, traceback) + session: Session to close after delay. + """ + _, value, _ = exc_info + # Ignore errors already handled by MonitoredSession + if isinstance(value, _IGNORED_ERRORS): + return + + self._errors[source] = exc_info + + # If the error is a numeric type, e.g., NaN error, we can assume that the + # loop execution completed successfully. In this case, we can skip the + # `session.close()` logic and wait for the infeed/outfeed threads to + # complete as normal. + try: + if value.op.type == _CHECK_NUMERIC_OP_NAME: + analytics.track_numerical_issues(exc_info) + return + except AttributeError as _: + pass + + if session is not None and self._session_cancel_timer is None: + + def _cancel_session(): + time.sleep(5) + tf.compat.v1.logging.error('Closing session due to error %s' % value) + try: + session.close() + except: # pylint: disable=bare-except + tf.compat.v1.logging.error( + '\n\n\nFailed to close session after error.' + 'Other threads may hang.\n\n\n') + + self._session_cancel_timer = threading.Thread(target=_cancel_session,) + self._session_cancel_timer.daemon = True + self._session_cancel_timer.start() + + def record_done(self, source): + """Mark execution source `source` as done. + + If an error was originally reported from `source` it is left intact. + + Args: + source: `str`, source being recorded + """ + tf.compat.v1.logging.info('%s marked as finished', source) + if source not in self._errors: + self._errors[source] = None + + @contextlib.contextmanager + def catch_errors(self, source, session=None): + """Context manager to report any errors within a block.""" + try: + yield + except Exception: # pylint: disable=broad-except + self.record_error(source, sys.exc_info(), session) + + def raise_errors(self, timeout_sec=0): + """Wait for up to `timeout` seconds for all error sources to finish. + + Preferentially raise "interesting" errors (errors not in the + _UNINTERESTING_ERRORS) set. + + Args: + timeout_sec: Seconds to wait for other error sources. + """ + for _ in range(timeout_sec): + if len(self._errors) == self._num_sources: + break + time.sleep(1) + + kept_errors = [(k, v) for (k, v) in self._errors.items() if v is not None] + + # First check for any interesting errors, then fall back on the session + # cancelled errors etc. + for k, (typ, value, traceback) in kept_errors: + if isinstance(value, _UNINTERESTING_ERRORS): + continue + else: + tf.compat.v1.logging.warn('Reraising captured error') + six.reraise(typ, value, traceback) + + for k, (typ, value, traceback) in kept_errors: + tf.compat.v1.logging.warn('Reraising captured error') + six.reraise(typ, value, traceback) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/tpu/iteration_count_estimator.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/tpu/iteration_count_estimator.py new file mode 100644 index 0000000000000000000000000000000000000000..ea231fb16afb6ec4cd11b014d7fc7b210cdf53cb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/tpu/iteration_count_estimator.py @@ -0,0 +1,201 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================= +"""Estimator that uses past runtime samples to estimate iterations count. + +The estimator helps simplify determining the number of iterations count to spend +on a given alloted time budget. The estimate will get adjusted over time as the +estimator learns more from collecting per iteration runtime samples. +""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import collections + +import numpy as np +import tensorflow as tf + +RuntimeCounter = collections.namedtuple( + "RuntimeCounter", ["runtime_secs", "steps", "step_time_secs"]) + + +class IterationCountEstimator(object): + """Estimates iterations count using past iterations runtime. + + The estimator collects iterations elapsed time (in seconds) and store it into + a circular buffer. As it learns enough samples, it computes the mean value of + the past observed iterations elapsed time to estimate the number of iterations + count to run within the alloted time budget in seconds. + + To keep the buffer from growing indefinitely, we limit the size by the virtue + of using circular buffer. As it uses the mean of iterations runtime to compute + the iterations count estimate, setting a larger buffer size will smooth out + the estimation. Once the buffer is getting filled up, older values will be + dequeued in FIFO order. Setting larger buffer size will make the estimator + less sensitive to runtime fluctuations but will result in slower convergence. + For faster convergence buffer size can be set smaller but more prone to + runtime fluctuations. + + As a safety feature, the estimator will return default iterations value, + when: + 1. The circular buffer is empty (initially). + 2. The user input is invalid. + """ + + def __init__(self, capacity=20): + """Constructs a new `IterationsEstimator` instance. + + Args: + capacity: Size of circular buffer to hold timer values. Each timer value + represents the time spent on the last iterations. + + Raises: + ValueError: If one or more parameters specified is invalid. + """ + self._reset(capacity=capacity) + + def _reset(self, capacity=20): + """Resets internal variables.""" + if capacity <= 0: + raise ValueError("IterationCountEstimator `capacity` must be positive. " + "Actual:%d." % capacity) + # A circular buffer with fixed capacity to store the observation time values + # and once the buffer is full, the oldest value will be evicted. + self._buffer_wheel = collections.deque([]) + self._capacity = capacity + self._min_iterations = 1 + self._last_iterations = self._min_iterations + self._sample_count = 0 + + def _mean_runtime_secs(self): + return np.mean(self._buffer_wheel, axis=0)[0] if self._buffer_wheel else 0 + + def _mean_step_time_secs(self): + return np.mean(self._buffer_wheel, axis=0)[2] if self._buffer_wheel else 0 + + def _std_step_time_secs(self): + return np.std(self._buffer_wheel, axis=0)[2] if self._buffer_wheel else 0 + + def _diff_less_than_percentage(self, actual, target, percentage): + """Checks if `actual` value is within a `percentage` to `target` value. + + Args: + actual: Actual value. + target: Target value. + percentage: Max percentage threshold. + + Returns: + True if the ABS(`actual` - `target`) is less than or equal to `percentage` + , otherwise False. + + Raise: + ValueError: If `total_secs` value is not positive. + """ + if actual == 0: + raise ValueError("Invalid `actual` value. Value must not be zero.") + if target == 0: + raise ValueError("Invalid `target` value. Value must not be zero.") + return (float(abs(target - actual)) / target) <= percentage * 0.01 + + def _is_step_time_stable(self): + """Checks if the step time has stabilized. + + We define stability a function of small stdev and after running for some + time. + + Returns: + True if stability is reached, False otherwise. + """ + std = self._std_step_time_secs() + return std < 0.03 and self._sample_count > self._capacity + + def update(self, runtime_secs, count): + """Updates the unit time spent per iteration. + + Args: + runtime_secs: The total elapsed time in seconds. + count: The number of iterations. + """ + if runtime_secs <= 0.0: + tf.compat.v1.logging.debug( + "Invalid `runtime_secs`. Value must be positive. Actual:%.3f.", + runtime_secs) + return + if count <= 0.0: + tf.compat.v1.logging.debug( + "Invalid samples `count`. Value must be positive. Actual:%d.", count) + return + + if len(self._buffer_wheel) >= self._capacity: + self._buffer_wheel.popleft() + step_time_secs = float(runtime_secs) / count + self._buffer_wheel.append( + RuntimeCounter( + runtime_secs=runtime_secs, + steps=count, + step_time_secs=step_time_secs)) + self._sample_count += 1 + + def get(self, total_secs): + """Gets the iterations count estimate. + + If recent predicted iterations are stable, re-use the previous value. + Otherwise, update the prediction value based on the delta between the + current prediction and the expected number of iterations as determined by + the per-step runtime. + + Args: + total_secs: The target runtime in seconds. + + Returns: + The number of iterations as estimate. + + Raise: + ValueError: If `total_secs` value is not positive. + """ + if total_secs <= 0: + raise ValueError( + "Invalid `total_secs`. It must be positive number. Actual:%d" % + total_secs) + if not self._buffer_wheel: + tf.compat.v1.logging.debug( + "IterationCountEstimator has no sample(s). Returns min iterations:%d.", + self._min_iterations) + return self._min_iterations + + mean_runtime_secs = self._mean_runtime_secs() + mean_step_time_secs = self._mean_step_time_secs() + std_step_time_secs = self._std_step_time_secs() + projected_iterations = total_secs / mean_step_time_secs + last_runtime_secs = self._buffer_wheel[-1].runtime_secs + delta_iterations = projected_iterations - self._last_iterations + # Stabilizes the search once it is close enough to the target runtime and + # the step time is stable within range bound. + if ((self._diff_less_than_percentage(last_runtime_secs, total_secs, 10) or + self._diff_less_than_percentage(mean_runtime_secs, total_secs, 5)) and + self._is_step_time_stable()): + delta_iterations = 0 + self._last_iterations += delta_iterations + self._last_iterations = max(self._last_iterations, self._min_iterations) + tf.compat.v1.logging.info( + "IterationCountEstimator -- target_runtime:%.3fs. last_runtime:%.3fs. " + "mean_runtime:%.3fs. last_step_time:%.3f. std_step_time:%.3f. " + "mean_step_time:%.3fs. delta_steps:%.2f. prev_steps:%.2f. " + "next_steps:%.2f.", total_secs, last_runtime_secs, mean_runtime_secs, + self._buffer_wheel[-1].step_time_secs, std_step_time_secs, + mean_step_time_secs, delta_iterations, self._buffer_wheel[-1].steps, + self._last_iterations) + return int(self._last_iterations + 0.5) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/tpu/tpu_config.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/tpu/tpu_config.py new file mode 100644 index 0000000000000000000000000000000000000000..7c5dfdb2c82d5c41eb561111815cec57e1006532 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/tpu/tpu_config.py @@ -0,0 +1,350 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# =================================================================== +"""A RunConfig subclass with TPU support.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import collections +import json +import os +import tensorflow as tf +from tensorflow_estimator.python.estimator import run_config as run_config_lib +from tensorflow_estimator.python.estimator.estimator_export import estimator_export +from tensorflow_estimator.python.estimator.tpu import util as util_lib + +# pylint: disable=protected-access +_TF_CONFIG_ENV = run_config_lib._TF_CONFIG_ENV +_SERVICE_KEY = run_config_lib._SERVICE_KEY +_TPU_WORKER_JOB_NAME = 'tpu_worker_job_name' +# pylint: enable=protected-access + + +@estimator_export(v1=['estimator.tpu.InputPipelineConfig']) +class InputPipelineConfig(object): + r"""Please see the definition of these values in TPUConfig. + + @compatibility(TF2) + TPU Estimator manages its own TensorFlow graph and session, so it is not + compatible with TF2 behaviors. We recommend that you migrate to the newer + `tf.distribute.TPUStrategy`. See the + [TPU guide](https://www.tensorflow.org/guide/tpu) for details. + @end_compatibility + """ + PER_SHARD_V1 = 1 + PER_HOST_V1 = 2 + PER_HOST_V2 = 3 + BROADCAST = 4 + SLICED = 5 + + +@estimator_export(v1=['estimator.tpu.TPUConfig']) +class TPUConfig( + collections.namedtuple('TPUConfig', [ + 'iterations_per_loop', + 'num_shards', + 'num_cores_per_replica', + 'per_host_input_for_training', + 'tpu_job_name', + 'initial_infeed_sleep_secs', + 'input_partition_dims', + 'eval_training_input_configuration', + 'experimental_host_call_every_n_steps', + 'experimental_allow_per_host_v2_parallel_get_next', + 'experimental_feed_hook', + ])): + r"""TPU related configuration required by `TPUEstimator`. + + Args: + iterations_per_loop: This is the number of train steps running in TPU system + before returning to CPU host for each `Session.run`. This means global + step is increased `iterations_per_loop` times in one `Session.run`. It is + recommended to be set as number of global steps for next checkpoint. Note + that in evaluation don't use this value, instead we run total eval `steps` + on TPU for a single `Session.run`. + [Experimental]: `iterations_per_loop` can be specified as a time interval. + To specify N seconds in one `Session.run`, one can specify it as `Ns` + and substitute the N with the N with the number of desired seconds. + Alternatively, the unit of time can also be specified in minutes or + hours, e.g. `3600s` or `60m` or `1h`. + num_shards: (Deprecated, ignored by TPUEstimator). The number of model + replicas in the system. For non-model-parallelism case, this number equals + the total number of TPU cores. For model-parallelism, the total number of + TPU cores equals num_cores_per_replica * num_shards. + num_cores_per_replica: Defaults to `None`, which disables model parallelism. + An integer which describes the number of TPU cores per model replica. This + is required by model-parallelism which enables partitioning the model to + multiple cores. Currently num_cores_per_replica must be 1, 2, 4, or 8. + per_host_input_for_training: If `True`, for `PER_HOST_V1`, the `input_fn` is + invoked once on each host, and the number of hosts must be smaller or + equal to the number of replicas. For PER_HOST_V2, the `input_fn` is + invoked once for each host (if the number of hosts is less than the number + of replicas) or replica (if the number of replicas is less than the number + of hosts. With the per-core input pipeline configuration, it is invoked + once for each core. With a global batch size `train_batch_size` in + `TPUEstimator` constructor, the batch size for each shard is + `train_batch_size` // #hosts in the `True` or `PER_HOST_V1` mode. In + `PER_HOST_V2` mode, it is `train_batch_size` // #cores. In `BROADCAST` + mode, `input_fn` is only invoked once on host 0 and the tensors are + broadcasted to all other replicas. The batch size equals to + `train_batch_size`. With the per-core input pipeline configuration, the + shard batch size is also `train_batch_size` // #cores. + Note: per_host_input_for_training==PER_SHARD_V1 only supports mode.TRAIN. + tpu_job_name: The name of the TPU job. Typically, this name is auto-inferred + within TPUEstimator, however when using ClusterSpec propagation in more + esoteric cluster configurations, you may need to specify the job name as a + string. + initial_infeed_sleep_secs: The number of seconds the infeed thread should + wait before enqueueing the first batch. This helps avoid timeouts for + models that require a long compilation time. + input_partition_dims: A nested list to describe the partition dims for all + the tensors from input_fn(). The structure of input_partition_dims must + match the structure of `features` and `labels` from input_fn(). The total + number of partitions must match + `num_cores_per_replica`. For example, if input_fn() returns two tensors: + images with shape [N, H, W, C] and labels [N]. input_partition_dims = + [[1, 2, 2, 1], None] will split the images to 4 pieces and feed into 4 + TPU cores. labels tensor are directly broadcasted to all the TPU cores + since the partition dims is `None`. + Current limitations: This feature is only supported with the PER_HOST_V2 + input mode. + eval_training_input_configuration: If `SLICED`, `input_fn` is only invoked + once on host 0 and the tensors are broadcasted to all other replicas. + Unlike per_host_input_for_training=BROADCAST, each replica will only get a + slice of the data instead of a whole copy. If `PER_HOST_V1`, the behaviour + is determined by per_host_input_for_training. + experimental_host_call_every_n_steps: Within a training loop, this argument + sets how often host calls are performed during training. Host calls will + be evaluated every n steps within a training loop where n is the value of + this argument. + experimental_allow_per_host_v2_parallel_get_next: When enabled, allows + concurrent execution of dataset get next calls when using PER_HOST_V2 + input. May result in a performance increase for models with a small step + time, but as a consequence TPUEstimator may non-deterministically + distribute batches to different cores, rather than guaranteeing round + robin behavior. + experimental_feed_hook: This is a class which user can provide to the TPU + estimator to override the default TPUInfeedOutfeedSessionHook implementation + and add customized implementatioin to handle infeed outfeed logic. If + given class is None, TPU estimator uses default TPUInfeedOutfeedSessionHook + implementation in tpu_estimator.py. If not None, TPU estimator uses this + customized tpu infeed outfeed session hook class rather to override the + default one. + + Raises: + ValueError: If `num_cores_per_replica` is not 1, 2, 4, 8, ..., 128. + + @compatibility(TF2) + TPU Estimator manages its own TensorFlow graph and session, so it is not + compatible with TF2 behaviors. We recommend that you migrate to the newer + `tf.distribute.TPUStrategy`. See the + [TPU guide](https://www.tensorflow.org/guide/tpu) for details. + @end_compatibility + """ + + def __new__(cls, + iterations_per_loop=2, + num_shards=None, + num_cores_per_replica=None, + per_host_input_for_training=True, + tpu_job_name=None, + initial_infeed_sleep_secs=None, + input_partition_dims=None, + eval_training_input_configuration=InputPipelineConfig.PER_HOST_V1, + experimental_host_call_every_n_steps=1, + experimental_allow_per_host_v2_parallel_get_next=False, + experimental_feed_hook=None): + + # Check iterations_per_loop. + util_lib.parse_iterations_per_loop(iterations_per_loop) + + # Check num_shards. + if num_shards is not None: + util_lib.check_positive_integer(num_shards, 'TPUConfig num_shards') + + if input_partition_dims is not None: + if len(input_partition_dims) != 1 and len(input_partition_dims) != 2: + raise ValueError( + 'input_partition_dims must be a list/tuple with one or two' + ' elements.') + + if per_host_input_for_training is not InputPipelineConfig.PER_HOST_V2: + raise ValueError( + 'input_partition_dims is only supported in PER_HOST_V2 mode.') + + if num_cores_per_replica is None: + raise ValueError( + 'input_partition_dims requires setting num_cores_per_replica.') + + # Check num_cores_per_replica + if num_cores_per_replica is not None: + if num_cores_per_replica not in ([1, 2, 4, 8, 16, 32, 64, 128]): + raise ValueError( + 'num_cores_per_replica must be 1, 2, 4, 8, 16, 32, 64, 128; ' + 'got {}'.format(str(num_cores_per_replica))) + + if eval_training_input_configuration not in [ + InputPipelineConfig.PER_HOST_V1, InputPipelineConfig.SLICED + ]: + raise ValueError( + 'eval_training_input_configuration must be PER_HOST_V1 or SLICED;' + ' got {}'.format(str(eval_training_input_configuration))) + + # per_host_input_for_training may be True, False, or integer in [1..3]. + # Map legacy values (True, False) to numeric values. + if per_host_input_for_training is False: + per_host_input_for_training = InputPipelineConfig.PER_SHARD_V1 + elif per_host_input_for_training is True: + per_host_input_for_training = InputPipelineConfig.PER_HOST_V1 + + # Check initial_infeed_sleep_secs. + if initial_infeed_sleep_secs: + util_lib.check_positive_integer(initial_infeed_sleep_secs, + 'TPUConfig initial_infeed_sleep_secs') + + tpu_job_name = tpu_job_name or _get_tpu_job_name_from_tf_config() + + return super(TPUConfig, cls).__new__( + cls, + iterations_per_loop=iterations_per_loop, + num_shards=num_shards, + num_cores_per_replica=num_cores_per_replica, + per_host_input_for_training=per_host_input_for_training, + tpu_job_name=tpu_job_name, + initial_infeed_sleep_secs=initial_infeed_sleep_secs, + input_partition_dims=input_partition_dims, + eval_training_input_configuration=eval_training_input_configuration, + experimental_host_call_every_n_steps=( + experimental_host_call_every_n_steps), + experimental_allow_per_host_v2_parallel_get_next=( + experimental_allow_per_host_v2_parallel_get_next), + experimental_feed_hook=(experimental_feed_hook)) + + +@estimator_export(v1=['estimator.tpu.RunConfig']) +class RunConfig(run_config_lib.RunConfig): + """RunConfig with TPU support.""" + + def __init__(self, + tpu_config=None, + evaluation_master=None, + master=None, + cluster=None, + **kwargs): + """Constructs a RunConfig. + + Args: + tpu_config: the TPUConfig that specifies TPU-specific configuration. + evaluation_master: a string. The address of the master to use for eval. + Defaults to master if not set. + master: a string. The address of the master to use for training. + cluster: a ClusterResolver + **kwargs: keyword config parameters. + + Raises: + ValueError: if cluster is not None and the provided session_config has a + cluster_def already. + + @compatibility(TF2) + TPU Estimator manages its own TensorFlow graph and session, so it is not + compatible with TF2 behaviors. We recommend that you migrate to the newer + `tf.distribute.TPUStrategy`. See the + [TPU guide](https://www.tensorflow.org/guide/tpu) for details. + @end_compatibility + """ + super(RunConfig, self).__init__(**kwargs) + self._tpu_config = tpu_config or TPUConfig() + self._cluster = cluster + + # If user sets master and/or evaluation_master explicitly, including empty + # string '', take it. Otherwise, take the values set by parent class. + if master is not None: + if cluster is not None: + raise ValueError('Both master and cluster are set.') + self._master = master + else: + if cluster: + self._master = cluster.master() + + if evaluation_master is not None: + self._evaluation_master = evaluation_master + elif (not self._evaluation_master and + self.task_type != run_config_lib.TaskType.EVALUATOR): + # If the task type is EVALUATOR, it means some cluster manager sets the + # TF_CONFIG. In that case, we respect the configuration in TF_CONFIG. + # + # Otherwise, it means user executes the code without external cluster + # manager. For that, we optimize the user experience by setting + # evaluation_master to master, unless user overwrites it. + self._evaluation_master = self._master + + # Set the ClusterSpec to use + if cluster: + self._cluster_spec = cluster.cluster_spec() + + # Merge the cluster_def into the ConfigProto. + if self._session_config is None: # pylint: disable=access-member-before-definition + self._session_config = tf.compat.v1.ConfigProto( + allow_soft_placement=True, isolate_session_state=True) + if self._session_config.HasField('cluster_def'): + raise ValueError('You cannot provide a ClusterResolver and ' + 'session_config.cluster_def.') + if self._cluster_spec: + self._session_config.cluster_def.CopyFrom( + self._cluster_spec.as_cluster_def()) + + def _maybe_overwrite_session_config_for_distributed_training(self): + # Overrides the parent class session_config overwrite for between-graph. TPU + # runs with in-graph, which should not have device filter. Doing nothing + # ("pass") basically disables it. + pass + + @property + def evaluation_master(self): + return self._evaluation_master + + @property + def master(self): + return self._master + + @property + def tpu_config(self): + return self._tpu_config + + @property + def cluster(self): + return self._cluster + + def replace(self, **kwargs): + if 'tpu_config' not in kwargs: + return super(RunConfig, self).replace(**kwargs) + + tpu_config = kwargs.pop('tpu_config') + new_instance = super(RunConfig, self).replace(**kwargs) + new_instance._tpu_config = tpu_config # pylint: disable=protected-access + return new_instance + + +def _get_tpu_job_name_from_tf_config(): + """Extracts the TPU job name from TF_CONFIG env variable.""" + # TODO(xiejw): Extends this to support both TF_CONFIG env variable and cluster + # spec propagation. + tf_config = json.loads(os.environ.get(_TF_CONFIG_ENV, '{}')) + tpu_job_name = tf_config.get(_SERVICE_KEY, {}).get(_TPU_WORKER_JOB_NAME) + if tpu_job_name: + tf.compat.v1.logging.info('Load TPU job name from TF_CONFIG: %s', + tpu_job_name) + return tpu_job_name diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/tpu/tpu_context.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/tpu/tpu_context.py new file mode 100644 index 0000000000000000000000000000000000000000..7c528c77e87ade84fe1b7fbc01d5a82b7919a7a5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/tpu/tpu_context.py @@ -0,0 +1,911 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# =================================================================== +"""TPU system metadata and associated tooling.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +from contextlib import contextmanager +import copy +import tensorflow as tf +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.ops import summary_ops_v2 +from tensorflow.python.tpu import device_assignment as tpu_device_assignment +from tensorflow.python.tpu import tpu_system_metadata as tpu_system_metadata_lib +from tensorflow_estimator.python.estimator import model_fn as model_fn_lib +from tensorflow_estimator.python.estimator.tpu import _tpu_estimator_embedding +from tensorflow_estimator.python.estimator.tpu import tpu_config + +_DEFAULT_JOB_NAME = 'tpu_worker' +_DEFAULT_COORDINATOR_JOB_NAME = 'coordinator' +_LOCAL_MASTERS = ('', 'local') +# TODO(pgavin): support PF 3D mesh +_NUM_CORES_TO_COMPUTATION_SHAPE = { + 1: [1, 1, 1, 1], + 2: [1, 1, 1, 2], + 4: [1, 2, 1, 2], + 8: [2, 2, 1, 2], + 16: [4, 2, 1, 2], + 32: [4, 4, 1, 2], + 64: [8, 4, 1, 2], + 128: [8, 8, 1, 2], +} + + +class TPUContext(object): + """A context that holds the current configuration of the TPU computation. + + TPUContext was designed for getting TPU context information when calling + input_fn. It can be called in model_fn as well. + + User is not expected to construct the instance from constructor. The only + legitimate way to get the instance is either in `input_fn`: + + ``` + def input_fn(params): + batch_size = params['batch_size'] + context = params['context'] + # ... + ``` + + or in `model_fn` + + ``` + def model_fn(params): + batch_size = params['batch_size'] + context = params['context'] + # ... + ``` + + Most of the fields of TPUContext are useful for both `input_fn` and + `model_fn`. Exceptions are: + + 1. `input_fn` only: + + current_input_fn_deployment + current_host + + 2. `model_fn` only: + + device_assignment + + """ + + def __init__(self, + internal_ctx, + input_device=None, + invocation_index=None, + call_from_input_fn=True, + host_id=None): + self._internal_ctx = internal_ctx + self._input_device = input_device + self._invocation_index = invocation_index + self._call_from_input_fn = call_from_input_fn + self._host_id = host_id + + def current_input_fn_deployment(self): + """The configuration of the current input_fn invocation. + + The configuration depends on `TPUConfig.per_host_input_for_training`. See + `TPUConfig` for details. + + Only set in params dict of input_fn + + Returns: + A tuple of + 1. Device spec string: String, is the current CPU host where the + input_fn is invoked. + 2. Current invocation index: Int, 0-based index of the input_fn + invocation. See next item for details. + 3. Total invocation count: Int, the total number of times to invoke the + input_fn on all CPU hosts. Each invocation will be passed with a new + `TPUContext` instance with current invocation index set properly. + 4. Total number of replicas consumed by current_invocation: Int, the + number of replicas fed by the data returned by current input_fn. For + example, for per_core input pipeline deployment + and non-model-parallelism, total invocation count is equal to + the number of cores in the system and num replicas consumed by + current invocation is 1. For per-host v2 input pipeline deployment, + total invocation count is equal to the number of hosts in the system + and num replicas consumed by current invocation is equal to number of + replicas per host. + + Raises: + RuntimeError: If this method is not be called from input_fn. + """ + if not self._call_from_input_fn: + raise RuntimeError('This TPUContext instance must not be called from' + ' model_fn.') + + if self._internal_ctx.is_input_sharded_per_core(): + total_invocation_count = ( + self._internal_ctx.num_hosts * + self._internal_ctx.num_of_replicas_per_host) + replicas_consumed = 1 + elif self._internal_ctx.is_input_broadcast_with_iterators(): + total_invocation_count = 1 + replicas_consumed = self._internal_ctx.num_replicas + elif self._internal_ctx.is_replica_across_hosts(): + total_invocation_count = self._internal_ctx.num_replicas + replicas_consumed = 1 + else: + total_invocation_count = self._internal_ctx.num_hosts + replicas_consumed = self._internal_ctx.num_of_replicas_per_host + return (self._input_device, self._invocation_index, total_invocation_count, + replicas_consumed) + + @property + def num_replicas(self): + """The total number of replicas. + + For non-model-parallelism, num_replicas should be the total num of TPU + cores in the system. + + Returns: + The number of replicas. + """ + return self._internal_ctx.num_replicas + + @property + def num_hosts(self): + """The number of hosts for the TPU system.""" + return self._internal_ctx.num_hosts + + @property + def current_host(self): + """The current host index for the TPU system. + + Returns: + The host index (int). + + Raises: + RuntimeError: If this method is not be called from input_fn. + """ + + if not self._call_from_input_fn: + raise RuntimeError('This TPUContext instance must not be called from' + ' model_fn.') + + return self._host_id + + @property + def num_of_replicas_per_host(self): + """The number of replicas for each host.""" + if self._internal_ctx.model_parallelism_enabled: + raise ValueError( + 'num_of_replicas_per_host is not supported for model_parallelism') + return self._internal_ctx.num_of_replicas_per_host + + @property + def device_assignment(self): + """Returns device_assignment object. + + Raises: + RuntimeError: If this method is not be called from model_fn. + """ + if self._call_from_input_fn: + raise RuntimeError('This TPUContext instance must not be called from' + ' input_fn.') + return self._internal_ctx.device_assignment + + def device_for_replica(self, replica_id): + """Returns the tuple of (CPU device and device ordinal) for replica. + + This should be used for full replicate for non-model-parallelism. + + Args: + replica_id: Int, the replica index. + + Returns: + A tuple of device spec for CPU device and int device ordinal. + """ + # Note that: For the non-model parallelism, the mapping could be + # a random permutation. The order should not matter in most cases + # as far as model is replicated to all cores in the system. + return self._internal_ctx.device_for_replica(replica_id) + + @property + def tpu_host_placement_function(self): + """Returns the TPU host place function. + + The place function takes host_id as the input and returns the TF device + for the correspoding host. + """ + + def _placement_function(host_id): + """Return the host device given host_id.""" + return self._internal_ctx.tpu_host_placement_function(host_id=host_id) + + return _placement_function + + +class _InternalTPUContext(object): + """A context holds immutable states of TPU computation. + + This immutable object holds TPUEstimator config, train/eval batch size, and + `TPUEstimator.use_tpu`, which is expected to be passed around. It also + provides utility functions, based on the current state, to determine other + information commonly required by TPU computation, such as TPU device names, + TPU hosts, shard batch size, etc. + + if eval_on_tpu is False, then execution of eval on TPU is disabled. + if eval_on_tpu is True, but use_tpu is False, a warning is issued, + and TPU execution is disabled for all modes. + + N.B. As `mode` is not immutable state in Estimator, but essential to + distinguish between TPU training and evaluation, a common usage for + _InternalTPUContext with `mode` is as follows: + ``` + with _ctx.with_mode(mode) as ctx: + if ctx.is_running_on_cpu(): + ... + ``` + """ + + def __init__(self, + config, + train_batch_size, + eval_batch_size, + predict_batch_size, + use_tpu, + eval_on_tpu=True, + embedding_config_spec=None): + self._config = config + self._train_batch_size = train_batch_size + self._eval_batch_size = eval_batch_size + self._predict_batch_size = predict_batch_size + self._use_tpu = use_tpu + tf.compat.v1.logging.info('_TPUContext: eval_on_tpu %s', eval_on_tpu) + if not use_tpu and eval_on_tpu: + tf.compat.v1.logging.warn('eval_on_tpu ignored because use_tpu is False.') + + self._eval_on_tpu = eval_on_tpu + self._model_parallelism_enabled = ( + use_tpu and config.tpu_config.num_cores_per_replica) + self._mode = None + num_cores_per_replica = config.tpu_config.num_cores_per_replica + if self._model_parallelism_enabled: + self._computation_shape = _NUM_CORES_TO_COMPUTATION_SHAPE[ + num_cores_per_replica] + else: + self._computation_shape = None + self._lazy_tpu_system_metadata_dict = {} # key by master address + self._lazy_device_assignment_dict = {} # key by master address + self._lazy_validation_dict = {} # key by ModeKeys + self._embedding_config_spec = embedding_config_spec + self._lazy_embedding_config_dict = {} # key by master address + + def _assert_mode(self): + if self._mode is None: + raise RuntimeError( + '`mode` needs to be set via contextmanager `with_mode`.') + return self._mode + + @contextmanager + def with_mode(self, mode): + # NOTE(xiejw): Shallow copy is enough. It will share he lazy dictionaries, + # such as _lazy_tpu_system_metadata_dict between new copy and the original + # one. Note that all lazy states stored in properties _lazy_foo are sort of + # immutable as they should be same for the process lifetime. + new_ctx = copy.copy(self) + new_ctx._mode = mode # pylint: disable=protected-access + yield new_ctx + + @property + def mode(self): + return self._assert_mode() + + def _get_master_address(self): + mode = self._assert_mode() + config = self._config + master = ( + config.master + if mode != model_fn_lib.ModeKeys.EVAL else config.evaluation_master) + return master + + def _get_tpu_system_metadata(self): + """Gets the (maybe cached) TPU system metadata.""" + master = self._get_master_address() + tpu_system_metadata = self._lazy_tpu_system_metadata_dict.get(master) + if tpu_system_metadata is not None: + return tpu_system_metadata + + cluster_def = None + if (self._config.session_config and + self._config.session_config.cluster_def.job): + cluster_def = self._config.session_config.cluster_def + + # pylint: disable=protected-access + tpu_system_metadata = ( + tpu_system_metadata_lib._query_tpu_system_metadata( + master, + cluster_def=cluster_def, + query_topology=self.model_parallelism_enabled)) + + self._lazy_tpu_system_metadata_dict[master] = tpu_system_metadata + return tpu_system_metadata + + def _get_device_assignment(self): + """Gets the (maybe cached) TPU device assignment.""" + master = self._get_master_address() + device_assignment = self._lazy_device_assignment_dict.get(master) + if device_assignment is not None: + return device_assignment + + tpu_system_metadata = self._get_tpu_system_metadata() + + device_assignment = tpu_device_assignment.device_assignment( + tpu_system_metadata.topology, + computation_shape=self._computation_shape, + num_replicas=self.num_replicas) + + tf.compat.v1.logging.info( + 'num_cores_per_replica: %s', + str(self._config.tpu_config.num_cores_per_replica)) + tf.compat.v1.logging.info('computation_shape: %s', + str(self._computation_shape)) + tf.compat.v1.logging.info('num_replicas: %d', self.num_replicas) + tf.compat.v1.logging.info( + 'device_assignment.topology.device_coordinates: %s', + str(device_assignment.topology.device_coordinates)) + tf.compat.v1.logging.info('device_assignment.core_assignment: %s', + str(device_assignment.core_assignment)) + + self._lazy_device_assignment_dict[master] = device_assignment + return device_assignment + + @property + def tensor_core_embedding_columns(self): + if self._embedding_config_spec: + return self._embedding_config_spec.tensor_core_feature_columns + return None + + @property + def embedding_config(self): + """Returns the embedding config based on current mode.""" + master = self._get_master_address() + if master in self._lazy_embedding_config_dict: + embedding_config = self._lazy_embedding_config_dict[master] + else: + embedding_config = None + if self._use_tpu and self._embedding_config_spec: + embedding_config = _tpu_estimator_embedding.EmbeddingConfig( + self._embedding_config_spec, self._train_batch_size, + self._eval_batch_size, self.num_hosts, self.num_cores, self.config) + if not embedding_config.has_embedding_tables(): + embedding_config = None + self._lazy_embedding_config_dict[master] = embedding_config + + if embedding_config is not None: + mode = self._assert_mode() + # Dynamically attach tpu_embedding based on mode. With + # this, we could keep embedding_config immutable but call site always + # accesses the unified API '.tpu_embedding'. + embedding_config.tpu_embedding = embedding_config.get_tpu_embedding(mode) + return embedding_config + + @property + def allow_per_host_v2_parallel_get_next(self): + return (self._config.tpu_config + .experimental_allow_per_host_v2_parallel_get_next) + + @property + def feed_hook(self): + return (self._config.tpu_config.experimental_feed_hook) + + @property + def model_parallelism_enabled(self): + return self._model_parallelism_enabled + + @property + def input_partition_dims(self): + return self._config.tpu_config.input_partition_dims + + @property + def device_assignment(self): + return (self._get_device_assignment() + if self._model_parallelism_enabled else None) + + @property + def num_of_cores_per_host(self): + metadata = self._get_tpu_system_metadata() + return metadata.num_of_cores_per_host + + @property + def num_cores(self): + metadata = self._get_tpu_system_metadata() + return metadata.num_cores + + @property + def num_of_replicas_per_host(self): + """Return the number of replicas per host.""" + if self.model_parallelism_enabled: + # There can be fewer replicas. This might return 0! + return self.num_replicas // self.num_hosts + else: + return self.num_of_cores_per_host + + @property + def num_replicas(self): + """Compute the total number of replicas.""" + num_cores_in_system = self.num_cores + + if self.model_parallelism_enabled: + num_cores_per_replica = self._config.tpu_config.num_cores_per_replica + if num_cores_per_replica > num_cores_in_system: + raise ValueError( + 'The num of cores required by the model parallelism, specified by ' + 'TPUConfig.num_cores_per_replica, is larger than the total num of ' + 'TPU cores in the system. num_cores_per_replica: {}, num cores ' + 'in the system: {}'.format(num_cores_per_replica, + num_cores_in_system)) + + if num_cores_in_system % num_cores_per_replica != 0: + raise RuntimeError( + 'The num of cores in the system ({}) is not divisible by the num ' + 'of cores ({}) required by the model parallelism, specified by ' + 'TPUConfig.num_cores_per_replica. This should never happen!'.format( + num_cores_in_system, num_cores_per_replica)) + + return num_cores_in_system // num_cores_per_replica + else: + return num_cores_in_system + + @property + def num_hosts(self): + metadata = self._get_tpu_system_metadata() + return metadata.num_hosts + + @property + def config(self): + return self._config + + def is_input_sharded_per_core(self): + """Return true if input_fn is invoked per-core (other than per-host).""" + mode = self._assert_mode() + return (mode == model_fn_lib.ModeKeys.TRAIN and + (self._config.tpu_config.per_host_input_for_training is + tpu_config.InputPipelineConfig.PER_SHARD_V1)) + + def is_input_per_host_with_iterators(self): + """Return true if input_fn should be run in the per-host v2 config.""" + return (self._config.tpu_config.per_host_input_for_training is + tpu_config.InputPipelineConfig.PER_HOST_V2) + + def is_input_broadcast_with_iterators(self): + """Return true if input_fn should be run in the full_replicae config.""" + return ((self._config.tpu_config.per_host_input_for_training is + tpu_config.InputPipelineConfig.BROADCAST) or + (self.is_input_slice_broadcast_to_all_cores())) + + def is_input_slice_broadcast_to_all_cores(self): + """Return true if input_fn is invoked once and broadcast to other hosts.""" + mode = self._assert_mode() + return (mode != model_fn_lib.ModeKeys.TRAIN and + self._config.tpu_config.eval_training_input_configuration is + tpu_config.InputPipelineConfig.SLICED) + + def is_replica_across_hosts(self): + """Return true if single replica is across multiple hosts.""" + # For example, when num_cores_per_replica > num_cores_per_host. + num_cores_per_replica = self._config.tpu_config.num_cores_per_replica + num_cores_per_host = self._get_tpu_system_metadata().num_of_cores_per_host + return (num_cores_per_replica is not None and + num_cores_per_replica > num_cores_per_host) + + def is_running_on_cpu(self, is_export_mode=False): + """Determines whether the input_fn and model_fn should be invoked on CPU. + + This API also validates user provided configuration, such as batch size, + according the lazy initialized TPU system metadata. + + Args: + is_export_mode: Indicates whether the current mode is for exporting the + model, when mode == PREDICT. Only with this bool, we could tell whether + user is calling the Estimator.predict or Estimator.export_savedmodel, + which are running on TPU and CPU respectively. Parent class Estimator + does not distinguish these two. + + Returns: + bool, whether current input_fn or model_fn should be running on CPU. + + Raises: + ValueError: any configuration is invalid. + """ + + is_running_on_cpu = self._is_running_on_cpu(is_export_mode) + if not is_running_on_cpu: + self._validate_tpu_configuration() + return is_running_on_cpu + + def _is_running_on_cpu(self, is_export_mode): + """Determines whether the input_fn and model_fn should be invoked on CPU.""" + mode = self._assert_mode() + + if not self._use_tpu: + return True + + if mode == model_fn_lib.ModeKeys.EVAL and not self._eval_on_tpu: + tf.compat.v1.logging.info('_is_running_on_cpu: eval_on_tpu disabled') + return True + + if is_export_mode: + return True + + return False + + @property + def global_batch_size(self): + mode = self._assert_mode() + if mode == model_fn_lib.ModeKeys.TRAIN: + return self._train_batch_size + elif mode == model_fn_lib.ModeKeys.EVAL: + return self._eval_batch_size + elif mode == model_fn_lib.ModeKeys.PREDICT: + return self._predict_batch_size + else: + return None + + @property + def batch_size_for_input_fn(self): + """Returns the shard batch size for `input_fn`.""" + global_batch_size = self.global_batch_size + if (self.is_running_on_cpu() or self.is_input_broadcast_with_iterators()): + return global_batch_size + + # On TPU + if self.is_input_sharded_per_core() or ( + self.is_input_per_host_with_iterators()) or ( + self.is_replica_across_hosts()): + return global_batch_size // self.num_replicas + else: + return global_batch_size // self.num_hosts + + @property + def batch_size_for_model_fn(self): + """Returns the shard batch size for `model_fn`.""" + global_batch_size = self.global_batch_size + + if (self.is_running_on_cpu() or self.is_input_broadcast_with_iterators() and + not self.is_input_slice_broadcast_to_all_cores()): + return global_batch_size + + # On TPU. always sharded per shard. + return global_batch_size // self.num_replicas + + @property + def master_job(self): + """Returns the job name to use to place TPU computations on. + + Returns: + A string containing the job name, or None if no job should be specified. + + Raises: + ValueError: If the user needs to specify a tpu_job_name, because we are + unable to infer the job name automatically, or if the user-specified job + names are inappropriate. + """ + run_config = self._config + # If the user specifies the tpu_job_name, use that. + if run_config.tpu_config.tpu_job_name: + return run_config.tpu_config.tpu_job_name + + # The tpu job is determined by the run_config. Right now, this method is + # required as tpu_config is not part of the RunConfig. + mode = self._assert_mode() + master = ( + run_config.evaluation_master + if mode == model_fn_lib.ModeKeys.EVAL else run_config.master) + cluster_def = ( + run_config.session_config.cluster_def + if run_config.session_config else None) + + try: + master_job = tpu_system_metadata_lib.master_job(master, cluster_def) + except ValueError as e: + raise ValueError( + str(e) + ' Please specify a tpu_job_name as part of ' + 'your TPUConfig.') + return master_job + + @property + def tpu_host_placement_function(self): + """Returns the TPU host place function.""" + + master = self.master_job + + def _placement_function(_sentinal=None, replica_id=None, host_id=None): # pylint: disable=invalid-name + """Return the host device given replica_id or host_id.""" + assert _sentinal is None + if replica_id is not None and host_id is not None: + raise RuntimeError( + 'replica_id and host_id can have only one non-None value.') + + if master is None: + return '/replica:0/task:0/device:CPU:0' + else: + if replica_id is not None: + if self.model_parallelism_enabled: + return self.device_assignment.host_device( + replica=replica_id, job=master) + else: + host_id = replica_id / self.num_of_cores_per_host + + return '/job:%s/task:%d/device:CPU:0' % (master, host_id) + + return _placement_function + + @property + def tpu_device_placement_function(self): + """Returns a TPU device placement Fn.""" + master = self.master_job + job_device = '' if master is None else ('/job:%s' % master) + + def _placement_function(i): + if self.model_parallelism_enabled: + return self.device_assignment.tpu_device(replica=i, job=master) + else: + num_of_cores_per_host = self.num_of_cores_per_host + host_id = i / num_of_cores_per_host + ordinal_id = i % num_of_cores_per_host + return '%s/task:%d/device:TPU:%d' % (job_device, host_id, ordinal_id) + + return _placement_function + + def tpu_ordinal_function(self, host_id): + """Returns the TPU ordinal fn.""" + + def _tpu_ordinal_function(shard_index_in_host): + """Return the TPU ordinal associated with a shard. + + Required because the enqueue ops are placed on CPU. + + Args: + shard_index_in_host: the shard index + + Returns: + The ordinal of the TPU device the shard's infeed should be placed on. + """ + if self.model_parallelism_enabled: + # We put both enqueue/dequeue ops at tpu.core(0) in each replica. + replica = self.device_assignment.lookup_replicas(host_id, + 0)[shard_index_in_host] + return self.device_assignment.tpu_ordinal(replica=replica) + else: + return shard_index_in_host % self.num_of_cores_per_host + + return _tpu_ordinal_function + + def _validate_tpu_configuration(self): + """Validates the configuration based on the TPU system metadata.""" + mode = self._assert_mode() + if self._lazy_validation_dict.get(mode): + return + + # All following information is obtained from TPU system metadata. + num_cores = self.num_cores + num_replicas = self.num_replicas + num_hosts = self.num_hosts + + if not num_cores: + tpu_system_metadata = self._get_tpu_system_metadata() + raise RuntimeError( + 'Cannot find any TPU cores in the system. Please double check ' + 'Tensorflow master address and TPU worker(s). Available devices ' + 'are {}.'.format(tpu_system_metadata.devices)) + + if self._config.tpu_config.num_shards: + user_provided_num_replicas = self._config.tpu_config.num_shards + if user_provided_num_replicas != num_replicas: + message = ( + 'TPUConfig.num_shards is not set correctly. According to TPU ' + 'system metadata for Tensorflow master ({}): num_replicas should ' + 'be ({}), got ({}). For non-model-parallelism, num_replicas should ' + 'be the total num of TPU cores in the system. For ' + 'model-parallelism, the total number of TPU cores should be ' + 'num_cores_per_replica * num_replicas. Please set it ' + 'accordingly or leave it as `None`'.format( + self._get_master_address(), num_replicas, + user_provided_num_replicas)) + + raise ValueError(message) + + if self._config.tpu_config.num_cores_per_replica and ( + not self.is_input_per_host_with_iterators()): + num_cores_per_replica = self._config.tpu_config.num_cores_per_replica + num_cores_per_host = self._get_tpu_system_metadata().num_of_cores_per_host + if num_cores_per_replica > num_cores_per_host: + raise ValueError( + 'Except the PER_HOST_V2 mode, the num of cores required by ' + 'model parallelism specified by TPUConfig.num_cores_per_replica ' + 'should be less than or equal to the num_cores_per_host. ' + 'num_cores_per_replica: {}, num_cores_per_host: {}'.format( + num_cores_per_replica, num_cores_per_host)) + + if mode == model_fn_lib.ModeKeys.TRAIN: + if (self._train_batch_size % num_replicas != 0 and + not self.is_input_broadcast_with_iterators()): + raise ValueError( + 'train batch size {} must be divisible by number of replicas {}' + .format(self._train_batch_size, num_replicas)) + + elif mode == model_fn_lib.ModeKeys.EVAL: + if self._eval_batch_size is None: + raise ValueError( + 'eval_batch_size in TPUEstimator constructor cannot be `None` ' + 'if .evaluate is running on TPU.') + if (self._eval_batch_size % num_replicas != 0 and + not self.is_input_broadcast_with_iterators()): + raise ValueError( + 'eval batch size {} must be divisible by number of replicas {}' + .format(self._eval_batch_size, num_replicas)) + if (num_hosts != 1 and + not self.is_input_broadcast_with_iterators() and + not self.is_input_per_host_with_iterators()): + raise ValueError( + 'TPUEstimator.evaluate is only supported under three conditions: ' + '1. num_hosts=1; 2. BROADCAST mode; ' + '3. PER_HOST_V2 mode. ' + 'mode: {}; num_hosts: {}; num_replicas=1:{}'.format( + self._config.tpu_config.per_host_input_for_training, num_hosts, + num_replicas)) + if num_hosts > 1 and self.is_input_per_host_with_iterators(): + tf.compat.v1.logging.warn('Running TPUEstimator.evaluate for input mode' + ' PER_HOST_V2 and num_hosts %d', num_hosts) + else: + assert mode == model_fn_lib.ModeKeys.PREDICT + if self._predict_batch_size is None: + raise ValueError( + 'predict_batch_size in TPUEstimator constructor cannot be `None` ' + 'if .predict is running on TPU.') + if (self._predict_batch_size % num_replicas != 0 and + not self.is_input_broadcast_with_iterators()): + raise ValueError( + 'predict batch size {} must be divisible by number of replicas {}' + .format(self._predict_batch_size, num_replicas)) + if num_hosts != 1 and not ( + self.is_input_broadcast_with_iterators()) and not ( + num_replicas == 1 and self.is_input_per_host_with_iterators()): + raise ValueError( + 'TPUEstimator.predict is only supported under three conditions: ' + '1. num_hosts=1; 2. BROADCAST mode; ' + '3. PER_HOST_V2 mode with num_replicas=1. ' + 'mode: {}; num_hosts: {}; num_replicas=1:{}'.format( + self._config.tpu_config.per_host_input_for_training, num_hosts, + num_replicas)) + + # Record the state "validated" into lazy dictionary. + self._lazy_validation_dict[mode] = True + + def device_for_replica(self, replica_id): + """Returns the tuple of (CPU device and device ordinal) for replica. + + This should be used for full replicate for non-model-parallelism. + + Args: + replica_id: Int, the replica index. + + Returns: + A tuple of device spec for CPU device and int device ordinal. + """ + master = self.master_job + + if self.model_parallelism_enabled: + return (self.device_assignment.host_device( + replica=replica_id, + job=master), self.device_assignment.tpu_ordinal(replica=replica_id)) + + job_device = '' if master is None else ('/job:%s' % master) + + num_of_replicas_per_host = self.num_of_replicas_per_host + assert num_of_replicas_per_host > 0, ( + 'Got num_of_replicas_per_host: {}'.format(num_of_replicas_per_host)) + host_id = replica_id / num_of_replicas_per_host + ordinal_id = replica_id % num_of_replicas_per_host + + host_device = '%s/task:%d/device:CPU:0' % (job_device, host_id) + return (host_device, ordinal_id) + + +class _OneCoreTPUContext(_InternalTPUContext): + """Special _InternalTPUContext for one core usage.""" + + def __init__(self, config, train_batch_size, eval_batch_size, + predict_batch_size, use_tpu): + + super(_OneCoreTPUContext, + self).__init__(config, train_batch_size, eval_batch_size, + predict_batch_size, use_tpu) + + def _get_tpu_system_metadata(self): + """Gets the (maybe cached) TPU system metadata.""" + master = self._get_master_address() + tpu_system_metadata = self._lazy_tpu_system_metadata_dict.get(master) + if tpu_system_metadata is not None: + return tpu_system_metadata + + tpu_system_metadata = ( + tf.tpu.experimental.TPUSystemMetadata( # pylint: disable=protected-access + num_cores=1, + num_hosts=1, + num_of_cores_per_host=1, + topology=None, + devices=[])) + + self._lazy_tpu_system_metadata_dict[master] = tpu_system_metadata + return tpu_system_metadata + + +class _TPUEstimatorReplicaContext(tf.distribute.ReplicaContext): + """Internal context for storing replica id. + + This is to set eager.context.Context() so that only summary ops from + 0th replica is executed. + """ + + def __init__(self, replica_id_in_sync): + """Creates internal replica context for TPUEstimator. + + Args: + replica_id_in_sync: Zero indexed integer id of replica that is running the + TPU compuation. + """ + super(_TPUEstimatorReplicaContext, self).__init__(None, replica_id_in_sync) + # Use default strategy and replica context when variables are + # accessed/watched for backpropagation. + # pylint: disable=protected-access + self._thread_context = distribute_lib._DefaultReplicaThreadMode( + ) + self._strategy = self._thread_context.strategy + # pylint: enable=protected-access + + def __enter__(self): + + def replica_id_is_zero(): + return tf.math.equal(self.replica_id_in_sync_group, tf.constant(0)) + + if hasattr(summary_ops_v2, '_summary_state'): + summary_state = summary_ops_v2._summary_state # pylint: disable=protected-access + self._summary_recording_distribution_strategy = ( + summary_state.is_recording_distribution_strategy) + summary_state.is_recording_distribution_strategy = replica_id_is_zero + + def __exit__(self, exception_type, exception_value, traceback): + if hasattr(summary_ops_v2, '_summary_state'): + summary_state = summary_ops_v2._summary_state # pylint: disable=protected-access + summary_state.is_recording_distribution_strategy = ( + self._summary_recording_distribution_strategy) + + +def _get_tpu_context(config, train_batch_size, eval_batch_size, + predict_batch_size, use_tpu, eval_on_tpu, + embedding_config_spec): + """Returns an instance of `_InternalTPUContext`.""" + + if (config.tpu_config.num_shards == 1 and + config.tpu_config.num_cores_per_replica is None): + if embedding_config_spec is not None: + raise ValueError('Setting TPUConfig.num_shards==1 is unsupported ' + 'when embedding_config_spec is not None.') + tf.compat.v1.logging.warn( + 'Setting TPUConfig.num_shards==1 is an unsupported behavior. ' + 'Please fix as soon as possible (leaving num_shards as None.)') + return _OneCoreTPUContext(config, train_batch_size, eval_batch_size, + predict_batch_size, use_tpu) + + return _InternalTPUContext(config, train_batch_size, eval_batch_size, + predict_batch_size, use_tpu, eval_on_tpu, + embedding_config_spec) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/tpu/tpu_estimator.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/tpu/tpu_estimator.py new file mode 100644 index 0000000000000000000000000000000000000000..b069fa303cb2fc025055e9f02506bce76b41a578 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/tpu/tpu_estimator.py @@ -0,0 +1,4542 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# =================================================================== +"""TPUEstimator class.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import collections +import copy +import enum +import math +import os +import signal +import sys +import threading +import time + +import tensorflow as tf +import numpy as np +import six +from six.moves import queue as Queue # pylint: disable=redefined-builtin +from six.moves import xrange # pylint: disable=redefined-builtin + +from tensorflow.core.framework import variable_pb2 +from tensorflow.core.framework.summary_pb2 import Summary +from tensorflow.core.protobuf.tpu import compilation_result_pb2 as tpu_compilation_result +from tensorflow.python.data.util import nest as data_nest +from tensorflow.python.distribute.cluster_resolver import tpu_cluster_resolver +from tensorflow.python.framework import function +from tensorflow.python.framework import ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import control_flow_util +from tensorflow.python.ops import ref_variable +from tensorflow.python.ops import summary_ops_v2 +from tensorflow.python.ops import variable_scope +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.tpu import functional as tpu_functional +from tensorflow.python.tpu import preempted_hook +from tensorflow.python.tpu import session_support +from tensorflow.python.tpu import tensor_tracer +from tensorflow.python.tpu import tpu +from tensorflow.python.tpu import tpu_embedding_gradient +from tensorflow.python.tpu import tpu_feed +from tensorflow.python.tpu import tpu_function +from tensorflow.python.tpu import tpu_replication +from tensorflow.python.tpu import training_loop +from tensorflow.python.tpu.ops import tpu_ops +from tensorflow.python.training import evaluation +from tensorflow.python.util import function_utils +from tensorflow.python.util import tf_inspect +from tensorflow_estimator.python.estimator import estimator as estimator_lib +from tensorflow_estimator.python.estimator import model_fn as model_fn_lib +from tensorflow_estimator.python.estimator.estimator_export import estimator_export +from tensorflow_estimator.python.estimator.export import export_output as export_output_lib +from tensorflow_estimator.python.estimator.tpu import _tpu_estimator_embedding +from tensorflow_estimator.python.estimator.tpu import error_handling +from tensorflow_estimator.python.estimator.tpu import iteration_count_estimator +from tensorflow_estimator.python.estimator.tpu import tpu_config +from tensorflow_estimator.python.estimator.tpu import tpu_context +from tensorflow_estimator.python.estimator.tpu import util as util_lib +from tensorflow_estimator.python.estimator.tpu._tpu_estimator_embedding import AdagradParameters # pylint: disable=unused-import +from tensorflow_estimator.python.estimator.tpu._tpu_estimator_embedding import AdamParameters # pylint: disable=unused-import +from tensorflow_estimator.python.estimator.tpu._tpu_estimator_embedding import EmbeddingConfigSpec # pylint: disable=unused-import +from tensorflow_estimator.python.estimator.tpu._tpu_estimator_embedding import StochasticGradientDescentParameters # pylint: disable=unused-import + +_INITIAL_LOSS = 1e7 +_ZERO_LOSS = 0. +_TPU_ESTIMATOR = 'tpu_estimator' +_ITERATIONS_PER_LOOP_VAR = 'iterations_per_loop' +_BATCH_SIZE_KEY = 'batch_size' +_CTX_KEY = 'context' +_USE_TPU_KEY = 'use_tpu' +_CROSS_REPLICA_SUM_OP = 'CrossReplicaSum' +_ONE_GIGABYTE = 1024 * 1024 * 1024 +_TPU_ENQUEUE_OPS = '_tpu_enqueue_ops' +_TPU_TRAIN_OP = '_tpu_train_op' +_INFERENCE_ON_TPU_MODE = '_inference_on_tpu' +_KEY_WHEN_PREDICTIONS_IS_A_TENSOR = '_key_when_predictions_is_a_tensor' +_TENSOR_PACKER_SMALL_FEATURE_DIM_SIZE = 1 +_TENSOR_PACKER_MINIMUM_NUM_SMALL_FEATURES_TO_GROUP = 5 +_TENSOR_PACKER_CONCATENATED_SMALL_FEATURES_KEY = '_concatenated_small_features' + +# Ideally _USE_TPU_KEY should be reserved as well. However there are already +# models that make use of this key, thus it can not be reserved now to prevent +# breakage. In the long run, we would like to mitigate this by migrating models +# off of using _USE_TPU_KEY. +_RESERVED_PARAMS_KEYS = [_BATCH_SIZE_KEY, _CTX_KEY] + +# TODO(b/65703635): Flip the value and remove all dead code. Currently, this is +# only used for per-core based deployments. For per-host based pipelines, if a +# user returns a Dataset instance it will be automatically wrapped in a +# tf.while_loop (This can be disabled by returning features and labels +# explicitly). +_WRAP_INPUT_FN_INTO_WHILE_LOOP = False + +# Track the adoption of TPUEstimator +_tpu_estimator_gauge = tf.compat.v2.__internal__.monitoring.BoolGauge( + '/tensorflow/api/tpu_estimator', + 'Whether the program uses tpu estimator or not.') + +if ops.get_to_proto_function('{}_{}'.format(_TPU_ESTIMATOR, + _ITERATIONS_PER_LOOP_VAR)) is None: + ops.register_proto_function( + '{}_{}'.format(_TPU_ESTIMATOR, _ITERATIONS_PER_LOOP_VAR), + proto_type=variable_pb2.VariableDef, + to_proto=ref_variable._to_proto_fn, # pylint: disable=protected-access + from_proto=ref_variable._from_proto_fn) # pylint: disable=protected-access + + +def _is_iterable(obj): + """A Python 2 and 3 compatible util to check whether `obj` is iterable.""" + try: + iter(obj) + return True + except TypeError: + return False + + +class CatchInvalidHostcallFunctions(control_flow_ops.XLAControlFlowContext): + + def AddOp(self, op): + if op.type in [ + 'AudioSummary', 'AudioSummaryV2', 'HistogramSummary', 'ImageSummary', + 'MergeSummary', 'ScalarSummary', 'TensorSummary', 'TensorSummaryV2' + ]: + raise ValueError('Please use tf.contrib.summary instead of tf.summary ' + 'inside of host_calls.') + + +def _create_global_step(graph): + graph = graph or tf.compat.v1.get_default_graph() + if tf.compat.v1.train.get_global_step(graph) is not None: + raise ValueError('"global_step" already exists.') + # Create in proper graph and base name_scope. + with graph.as_default() as g, g.name_scope(None): + return tf.compat.v1.get_variable( + tf.compat.v1.GraphKeys.GLOBAL_STEP, + shape=[], + dtype=tf.dtypes.int64, + initializer=tf.compat.v1.initializers.zeros(), + trainable=False, + use_resource=True, + collections=[ + tf.compat.v1.GraphKeys.GLOBAL_VARIABLES, + tf.compat.v1.GraphKeys.GLOBAL_STEP + ]) + + +def _create_or_get_iterations_per_loop(): + """Creates or gets the iterations_per_loop variable. + + In TPUEstimator, the user provided computation, the model_fn, is wrapped + inside a tf.while_loop for peak performance. The iterations of the loop are + specified by this variable, which adjusts its value on the CPU after each TPU + program execution and before the next TPU execution. + + The purpose of using a variable, rather then a constant, is to allow + TPUEstimator adapt the TPU training iterations according to the final steps + specified by users. For example, if the user sets the iterations_per_loop as 4 + in TPUConfig and steps as 10 in TPUEstimator.train(), the iterations_per_loop + variable will have the following value before each TPU training. + + - 1-th TPU execution: iterations_per_loop = 4 + - 2-th TPU execution: iterations_per_loop = 4 + - 3-th TPU execution: iterations_per_loop = 2 + + As model_fn increases the global step once per train_op invocation, the global + step is 10 after all TPU executions, matching the steps=10 inputs passed in by + users. + + Returns: + A TF non-trainable resource variable. + + Raises: + RuntimeError: If multi iterations_per_loop variables were found. + """ + graph = tf.compat.v1.get_default_graph() + collection_name = '{}_{}'.format(_TPU_ESTIMATOR, _ITERATIONS_PER_LOOP_VAR) + iter_vars = graph.get_collection(collection_name) + if len(iter_vars) == 1: + return iter_vars[0] + elif len(iter_vars) > 1: + raise RuntimeError('Multiple iterations_per_loop_var in collection.') + + with ops.colocate_with(tf.compat.v1.train.get_global_step()): + with tf.compat.v1.variable_scope( + _TPU_ESTIMATOR, reuse=tf.compat.v1.AUTO_REUSE): + return tf.compat.v1.get_variable( + _ITERATIONS_PER_LOOP_VAR, + initializer=tf.compat.v1.initializers.zeros(), + shape=[], + dtype=tf.dtypes.int32, + trainable=False, + collections=[collection_name, tf.compat.v1.GraphKeys.LOCAL_VARIABLES], + use_resource=True) + + +def _sync_variables_ops(ctx): + """Create varriables synchronization ops. + + Gets the variables back from TPU nodes. This means the variables updated + by TPU will now be *synced* to host memory. + In BROADCAST mode, we skip this sync since the variables are ususally too + big to transmit via RPC. + + Args: + ctx: A `_InternalTPUContext` instance with mode. + + Returns: + A list of sync ops. + """ + + if not ctx.is_input_broadcast_with_iterators(): + return [ + tf.debugging.check_numerics(v.read_value(), + 'Gradient for %s is NaN' % v.name).op + for v in tf.compat.v1.trainable_variables() + ] + else: + return [tf.no_op()] + + +def _increase_eval_step_op(iterations_per_loop): + """Returns an op to increase the eval step for TPU evaluation. + + Args: + iterations_per_loop: Tensor. The number of eval steps running in TPU system + before returning to CPU host for each `Session.run`. + + Returns: + An operation + """ + eval_step = evaluation._get_or_create_eval_step() # pylint: disable=protected-access + # Estimator evaluate increases 1 by default. So, we increase the difference. + return tf.compat.v1.assign_add( + eval_step, + tf.cast(iterations_per_loop - 1, dtype=eval_step.dtype), + use_locking=True) + + +def _extract_key_names(tensor_or_dict): + if isinstance(tensor_or_dict, dict): + return sorted(tensor_or_dict.keys()) + return [] + + +class PeriodicLogger(object): + + def __init__(self, seconds): + self._log_every_n_seconds = seconds + self._last_log_time = 0 + + def log(self, msg, *args, **kw): + if time.time() - self._last_log_time > self._log_every_n_seconds: + self._last_log_time = time.time() + tf.compat.v1.logging.info(msg, *args, **kw) + + +class _SIGNAL(object): + """Signal used to control the thread of infeed/outfeed. + + All preserved signals must be negative numbers. Positive numbers are used to + indicate the number of iterations for next training/evaluation loop. + """ + NEXT_BATCH = -1 + STOP = -2 + + +@estimator_export(v1=['estimator.tpu.TPUEstimatorSpec']) +class TPUEstimatorSpec(model_fn_lib._TPUEstimatorSpec): # pylint: disable=protected-access + """Ops and objects returned from a `model_fn` and passed to `TPUEstimator`. + + See `EstimatorSpec` for `mode`, `predictions`, `loss`, `train_op`, and + `export_outputs`. + + For evaluation, `eval_metrics `is a tuple of `metric_fn` and `tensors`, where + `metric_fn` runs on CPU to generate metrics and `tensors` represents the + `Tensor`s transferred from TPU system to CPU host and passed to `metric_fn`. + To be precise, TPU evaluation expects a slightly different signature from the + `tf.estimator.Estimator`. While `EstimatorSpec.eval_metric_ops` expects a + dict, `TPUEstimatorSpec.eval_metrics` is a tuple of `metric_fn` and `tensors`. + The `tensors` could be a list of `Tensor`s or dict of names to `Tensor`s. The + `tensors` usually specify the model logits, which are transferred back from + TPU system to CPU host. All tensors must have be batch-major, i.e., the batch + size is the first dimension. Once all tensors are available at CPU host from + all shards, they are concatenated (on CPU) and passed as positional arguments + to the `metric_fn` if `tensors` is list or keyword arguments if `tensors` is + a dict. `metric_fn` takes the `tensors` and returns a dict from metric string + name to the result of calling a metric function, namely a `(metric_tensor, + update_op)` tuple. See `TPUEstimator` for MNIST example how to specify the + `eval_metrics`. + + `scaffold_fn` is a function running on CPU to generate the `Scaffold`. This + function should not capture any Tensors in `model_fn`. + + `host_call` is a tuple of a `function` and a list or dictionary of `tensors` + to pass to that function and returns a list of Tensors. `host_call` currently + works for train() and evaluate(). The Tensors returned by the function is + executed on the CPU on every step, so there is communication overhead when + sending tensors from TPU to CPU. To reduce the overhead, try reducing the + size of the tensors. The `tensors` are concatenated along their major (batch) + dimension, and so must be >= rank 1. The `host_call` is useful for writing + summaries with `tf.summary.create_file_writer`. + + @compatibility(TF2) + TPU Estimator manages its own TensorFlow graph and session, so it is not + compatible with TF2 behaviors. We recommend that you migrate to the newer + `tf.distribute.TPUStrategy`. See the + [TPU guide](https://www.tensorflow.org/guide/tpu) for details. + @end_compatibility + """ + + def __new__(cls, + mode, + predictions=None, + loss=None, + train_op=None, + eval_metrics=None, + export_outputs=None, + scaffold_fn=None, + host_call=None, + training_hooks=None, + evaluation_hooks=None, + prediction_hooks=None): + """Creates a validated `TPUEstimatorSpec` instance.""" + cls._host_calls = {} + if eval_metrics is not None: + cls._host_calls['eval_metrics'] = eval_metrics + if host_call is not None: + cls._host_calls['host_call'] = host_call + _OutfeedHostCall.validate(cls._host_calls) + + training_hooks = tuple(training_hooks or []) + evaluation_hooks = tuple(evaluation_hooks or []) + prediction_hooks = tuple(prediction_hooks or []) + + for hook in training_hooks + evaluation_hooks + prediction_hooks: + if not isinstance(hook, tf.compat.v1.train.SessionRunHook): + raise TypeError( + 'All hooks must be SessionRunHook instances, given: {}'.format( + hook)) + + return super(TPUEstimatorSpec, cls).__new__( + cls, + mode=mode, + predictions=predictions, + loss=loss, + train_op=train_op, + eval_metrics=eval_metrics, + export_outputs=export_outputs, + scaffold_fn=scaffold_fn, + host_call=host_call, + training_hooks=training_hooks, + evaluation_hooks=evaluation_hooks, + prediction_hooks=prediction_hooks) + + def as_estimator_spec(self): + """Creates an equivalent `EstimatorSpec` used by CPU train/eval.""" + host_call_ret = _OutfeedHostCall.create_cpu_hostcall(self._host_calls) + eval_metric_ops = None + if self.eval_metrics is not None: + eval_metric_ops = host_call_ret['eval_metrics'] + hooks = None + if self.host_call is not None: + hooks = [_OutfeedHostCallHook(host_call_ret['host_call'])] + loss = self.loss + if tensor_tracer.TensorTracer.is_enabled() \ + and self.train_op is not None: + tt = tensor_tracer.TensorTracer() + loss = tt.trace_cpu(tf.compat.v1.get_default_graph(), loss, self.train_op) + + hooks = tuple(hooks or []) + scaffold = self.scaffold_fn() if self.scaffold_fn else None + return model_fn_lib.EstimatorSpec( + mode=self.mode, + predictions=self.predictions, + loss=loss, + train_op=self.train_op, + eval_metric_ops=eval_metric_ops, + export_outputs=self.export_outputs, + scaffold=scaffold, + training_hooks=self.training_hooks + hooks, + evaluation_hooks=self.evaluation_hooks + hooks, + prediction_hooks=self.prediction_hooks + hooks) + + +class _OpQueueContext(object): + """Manages work queue and thread for a infeed/outfeed thread.""" + + def __init__(self, name, target, args): + self._name = name + self._queue = Queue.Queue() + args = (self,) + args + self._thread = threading.Thread(name=name, target=target, args=args) + self._thread.daemon = True + self._thread.start() + + def stop(self): + self._queue.put(_SIGNAL.STOP) + + def send_next_batch_signal(self, iterations): + self._queue.put(iterations) + + def read_iteration_counts(self): + while True: + iterations = self._queue.get(block=True) + tf.compat.v1.logging.debug('%s read iterations %s', self._name, + iterations) + if iterations == _SIGNAL.STOP: + tf.compat.v1.logging.info('%s received shutdown signal, stopping.', + self._name) + return + yield iterations + + def join(self): + tf.compat.v1.logging.info('Shutting down %s thread.', self._name) + self.stop() + self._thread.join() + + +class _OpSignalOnceQueueContext(_OpQueueContext): + """Manages work queue and thread for a infeed/outfeed thread. + + This subclass only signals once. + """ + + def __init__(self, name, target, args): + super(_OpSignalOnceQueueContext, self).__init__(name, target, args) + self._has_signaled = False + + def send_next_batch_signal(self, iterations): + if not self._has_signaled: + self._queue.put(iterations) + self._has_signaled = True + + +class TPUInfeedOutfeedSessionHook(tf.compat.v1.train.SessionRunHook): + """A Session hook setting up the TPU initialization, infeed, and outfeed. + + This hook does two major things: + 1. initialize and shutdown TPU system. + 2. launch and join the threads for infeed enqueue and (optional) outfeed + dequeue. + """ + + def __init__(self, + ctx, + enqueue_ops, + dequeue_ops, + tpu_compile_op, + run_infeed_loop_on_coordinator=True, + rendezvous=None, + master=None, + session_config=None, + tpu_init_ops=None, + outfeed_every_n_steps=1): + self._master_job = ctx.master_job + self._enqueue_ops = enqueue_ops + self._dequeue_ops = dequeue_ops + self._rendezvous = rendezvous + self._master = master + self._session_config = session_config + self._init_ops = list(tpu_init_ops or []) + if ctx.embedding_config is None: + self._embedding_layer_config = None + else: + self._embedding_layer_config = ( + ctx.embedding_config.tpu_embedding.config_proto) + self._run_infeed_loop_on_coordinator = run_infeed_loop_on_coordinator + self._initial_infeed_sleep_secs = ( + ctx.config.tpu_config.initial_infeed_sleep_secs) + self._tpu_compile_op = tpu_compile_op + + # When using model parallelism, the TPU is pre-initialized at startup to + # fetch mesh information. We skip re-initializing it here for + # MeshTensorFlow since it places variables on TPU directly. Reinitialize tpu + # is causing the variable corruption since the previous allocated memory + # might be overwritten for other purpose. + if (ctx.model_parallelism_enabled and + (ctx.config.tpu_config.per_host_input_for_training is + tpu_config.InputPipelineConfig.BROADCAST)): + self._should_initialize_tpu = False + else: + self._should_initialize_tpu = True + self._outfeed_every_n_steps = outfeed_every_n_steps + + def begin(self): + tf.compat.v1.logging.info('TPU job name %s', self._master_job) + self._iterations_per_loop_var = _create_or_get_iterations_per_loop() + if self._should_initialize_tpu: + self._finalize_ops = [ + tf.compat.v1.tpu.shutdown_system(job=self._master_job) + ] + else: + self._finalize_ops = [] + + summary_writer_init_ops = summary_ops_v2.summary_writer_initializer_op() + self._init_ops.extend(summary_writer_init_ops) + # Get all the writer resources from the initializer, so we know what to + # flush. + for op in summary_writer_init_ops: + self._finalize_ops.append( + summary_ops_v2.legacy_raw_flush(writer=op.inputs[0])) + + def _run_infeed(self, queue_ctx, session): + tf.compat.v1.logging.info('Starting infeed thread controller.') + if self._initial_infeed_sleep_secs: + tf.compat.v1.logging.info('Infeed thread sleeping for %d seconds.', + self._initial_infeed_sleep_secs) + time.sleep(self._initial_infeed_sleep_secs) + tf.compat.v1.logging.info('Infeed thread starting after sleep') + + with self._rendezvous.catch_errors(source='infeed', session=session): + if self._run_infeed_loop_on_coordinator: + for count, steps in enumerate(queue_ctx.read_iteration_counts()): + for i in xrange(steps): + tf.compat.v1.logging.debug('Infeed enqueue for iteration (%d, %d)', + count, i) + session.run(self._enqueue_ops) + else: + for _ in queue_ctx.read_iteration_counts(): + session.run(self._enqueue_ops) + tf.compat.v1.logging.info('Infeed thread finished, shutting down.') + + def _run_outfeed(self, queue_ctx, session): + tf.compat.v1.logging.info('Starting outfeed thread controller.') + status_logger = PeriodicLogger(seconds=60) + with self._rendezvous.catch_errors(source='outfeed', session=session): + for count, steps in enumerate(queue_ctx.read_iteration_counts()): + step_counter = 0 + for i in xrange(steps): + tf.compat.v1.logging.debug('Outfeed dequeue for iteration (%d, %d)', + count, i) + if step_counter % self._outfeed_every_n_steps == 0: + session.run(self._dequeue_ops) + step_counter += 1 + status_logger.log('Outfeed finished for iteration (%d, %d)', count, i) + tf.compat.v1.logging.info('Outfeed thread finished, shutting down.') + + def _create_infeed_controller(self, name, target, args): + return _OpQueueContext(name=name, target=target, args=args) + + def _assertCompilationSucceeded(self, result, coord): + proto = tpu_compilation_result.CompilationResultProto() + proto.ParseFromString(result) + if proto.status_error_message: + tf.compat.v1.logging.error('Compilation failed: {}'.format( + proto.status_error_message)) + coord.request_stop() + else: + tf.compat.v1.logging.info('Compilation succeeded') + + def after_create_session(self, session, coord): + if self._should_initialize_tpu: + tf.compat.v1.logging.info('Init TPU system') + start = time.time() + with tf.Graph().as_default(): + with tf.compat.v1.Session( + self._master, config=self._session_config) as sess: + sess.run( + tf.compat.v1.tpu.initialize_system( + job=self._master_job, + embedding_config=self._embedding_layer_config)) + tf.compat.v1.logging.info('Initialized TPU in %d seconds', + time.time() - start) + + session.run( + self._init_ops, + options=tf.compat.v1.RunOptions(timeout_in_ms=30 * 60 * 1000)) + + if os.environ.get('TPU_SPLIT_COMPILE_AND_EXECUTE', '') == '1': + tf.compat.v1.logging.info( + 'Compiling user program: this may take a while...') + self._assertCompilationSucceeded(session.run(self._tpu_compile_op), coord) + + self._infeed_controller = self._create_infeed_controller( + name='InfeedController', target=self._run_infeed, args=(session,)) + + self._outfeed_controller = _OpQueueContext( + name='OutfeedController', target=self._run_outfeed, args=(session,)) + + # Enable the worker watchdog to terminate workers on coordinator exit. + watchdog_timeout = int(os.environ.get('TF_TPU_WATCHDOG_TIMEOUT', '0')) + if watchdog_timeout > 0: + session_support.start_worker_watchdog( + session, shutdown_timeout=watchdog_timeout) + + def before_run(self, run_context): + iterations = run_context.session.run(self._iterations_per_loop_var) + + tf.compat.v1.logging.info('Enqueue next (%d) batch(es) of data to infeed.', + iterations) + self._infeed_controller.send_next_batch_signal(iterations) + + tf.compat.v1.logging.info( + 'Dequeue next (%d) batch(es) of data from outfeed.', iterations) + self._outfeed_controller.send_next_batch_signal(iterations) + + def end(self, session): + tf.compat.v1.logging.info('Stop infeed thread controller') + self._infeed_controller.join() + self._rendezvous.record_done('infeed') + + tf.compat.v1.logging.info('Stop output thread controller') + self._outfeed_controller.join() + self._rendezvous.record_done('outfeed') + + tf.compat.v1.logging.info('Shutdown TPU system.') + session.run(self._finalize_ops) + + +class TPUInfeedOutfeedSessionHookForPrediction(TPUInfeedOutfeedSessionHook): + + def __init__(self, + ctx, + enqueue_ops, + dequeue_ops, + tpu_compile_op, + rendezvous=None, + master=None, + session_config=None): + super(TPUInfeedOutfeedSessionHookForPrediction, self).__init__( + ctx, + enqueue_ops, + dequeue_ops, + tpu_compile_op=tpu_compile_op, + run_infeed_loop_on_coordinator=False, + rendezvous=rendezvous, + master=master, + session_config=session_config) + + def _create_infeed_controller(self, name, target, args): + return _OpSignalOnceQueueContext(name=name, target=target, args=args) + + +class _TPUStopAtStepHook(tf.compat.v1.train.SessionRunHook): + """Hook that requests stop at a specified step. + + This hook is similar to the `session_run_hook._StopAfterNEvalsHook` with + following differences for TPU training: + + 1. This hook sets the variable for `iterations_per_loop`, which is used by + `TPUInfeedOutfeedSessionHook` to control the iterations for infeed/outfeed. + If the `iterations_per_loop` value is specified as time in seconds, the + number of iterations per `Session.run` will be estimated automatically + based on per iteration runtime. + + As the hook execution order is not guaranteed, the variable update is + handled in `after_create_session` and `after_run` as + `TPUInfeedOutfeedSessionHook` reads the variable value in `before_run`. + + 2. For each training loop (session.run), the global step could be increased + multiple times on TPU. The global step tensor value will be explicitly read + again in `after_run` to ensure the latest value is retrieved to avoid race + condition. + """ + + def __init__(self, + iterations_per_loop_counter, + num_steps=None, + final_step=None): + """Initializes a `TPUStopAtStepHook`. + + Args: + iterations_per_loop_counter: A namedtuple of [`value',`unit`] that + represents the number of 'iterations count' or 'time in seconds' to run + optimizer per loop, based on the `unit` specified, `count` or `seconds` + respectively. + num_steps: Number of steps to execute. + final_step: Step after which to stop. + + Raises: + ValueError: If one of the arguments is invalid. + """ + if num_steps is None and final_step is None: + raise ValueError('One of `num_steps` or `final_step` must be specified.') + if num_steps is not None and final_step is not None: + raise ValueError( + 'Only one of `num_steps` or `final_step` can be specified.') + self._iterations_per_loop_counter = iterations_per_loop_counter + if self._iterations_per_loop_counter.unit not in ['seconds', 'count']: + raise ValueError('Only `count` or `seconds` are accepted as the ' + '`iterations_per_loop_counter.unit') + self._num_steps = num_steps + self._final_step = final_step + self._next_iteration_count = 1 + self._iteration_count_estimator = None + if self._iterations_per_loop_counter.unit == 'seconds': + self._iteration_count_estimator = ( + iteration_count_estimator.IterationCountEstimator()) + self._start_time = time.time() + + def _next_iterations(self, global_step, final_step): + """Computes the next iterations count. + + The next iterations count is computed by choosing the smaller of the + remaining step count (`final_step` - `global_step`) and the estimated + iterations count returned by the estimator. + + Args: + global_step: The current step. + final_step: Step after which to stop. + + Returns: + The number of iterations count to run per loop. + """ + remaining_steps = final_step - global_step + + if self._iteration_count_estimator is not None: + estimated_iterations = self._iteration_count_estimator.get( + self._iterations_per_loop_counter.value) + else: + estimated_iterations = self._iterations_per_loop_counter.value + + self._next_iteration_count = min(remaining_steps, estimated_iterations) + return self._next_iteration_count + + def begin(self): + """Initializes variables. + + Initializes the global step and iterations per loop variables. + + Raises: + RuntimeError: An error occurred if global step variable does not exist. + """ + self._global_step_tensor = tf.compat.v1.train.get_global_step() + if self._global_step_tensor is None: + raise RuntimeError('Global step should be created.') + + self._iterations_per_loop_var = _create_or_get_iterations_per_loop() + + def after_create_session(self, session, coord): + """Computes and updates the first time iterations count. + + The iterations are computed by choosing the smaller of the (`final step` - + `global step`), and the initial estimated iterations returned by the + estimator (by default is 1). + + Args: + session: A TensorFlow Session that has been created. + coord: A Coordinator object which keeps track of all threads. + """ + global_step = session.run(self._global_step_tensor) + if self._final_step is None: + self._final_step = global_step + self._num_steps + + iterations = self._next_iterations(global_step, self._final_step) + self._iterations_per_loop_var.load(iterations, session=session) + + def before_run(self, run_context): + """Reset the timer.""" + if self._iteration_count_estimator is not None: + self._start_time = time.time() + + def after_run(self, run_context, run_values): + """Computes the next iterations per loop value or terminates. + + Computes the elapsed time to run the last optimizer loop and if the + `IterationCountEstimator` is used, records the elapsed time and iterations + count. If the final step count has been reached, terminates. Otherwise, + computes and updates the number of iterations to run the optimizer per loop. + + Args: + run_context: A `SessionRunContext` object. + run_values: A SessionRunValues object. + """ + if self._iteration_count_estimator is not None: + elapsed_time = time.time() - self._start_time + tf.compat.v1.logging.info('ElapsedTime: %.3f', elapsed_time) + self._iteration_count_estimator.update(elapsed_time, + self._next_iteration_count) + + # Global step cannot be retrieved via SessionRunArgs and before_run due to + # race condition. + global_step = run_context.session.run(self._global_step_tensor) + if global_step >= self._final_step: + run_context.request_stop() + else: + iterations = self._next_iterations(global_step, self._final_step) + self._iterations_per_loop_var.load( + iterations, session=run_context.session) + + +class _SetEvalIterationsHook(tf.compat.v1.train.SessionRunHook): + """Hook that requests stop at a specified step.""" + + def __init__(self, num_steps): + """Initializes a `_SetEvalIterationsHook`. + + Args: + num_steps: Number of steps to execute. + """ + self._num_steps = num_steps + + def begin(self): + self._iterations_per_loop_var = _create_or_get_iterations_per_loop() + + def after_create_session(self, session, coord): + self._iterations_per_loop_var.load(self._num_steps, session=session) + + +class _StoppingPredictHook(tf.compat.v1.train.SessionRunHook): + """Hook that requests stop according to the stopping signal in prediction.""" + + def __init__(self, scalar_stopping_signal): + self._scalar_stopping_signal = scalar_stopping_signal + + def begin(self): + self._iterations_per_loop_var = _create_or_get_iterations_per_loop() + + def after_create_session(self, session, coord): + # This is not necessary as we do not run infeed enqueue and outfeed dequeue + # in side threads for prediction model. But it makes the + # TPUInfeedOutfeedSessionHook prints nice message. + self._iterations_per_loop_var.load(1, session=session) + + def before_run(self, run_context): + return tf.compat.v1.train.SessionRunArgs(self._scalar_stopping_signal) + + def after_run(self, run_context, run_values): + _ = run_context + scalar_stopping_signal = run_values.results + if _StopSignals.should_stop(scalar_stopping_signal): + # NOTE(xiejw): In prediction, stopping signals are inserted for each + # batch. And we append one more batch to signal the system it should stop. + # The data flow might look like + # + # batch 0: images, labels, stop = 0 (user provided) + # batch 1: images, labels, stop = 0 (user provided) + # ... + # batch 99: images, labels, stop = 0 (user provided) + # batch 100: images, labels, stop = 1 (TPUEstimator appended) + # + # where the final batch (id = 100) is appended by TPUEstimator, so we + # should drop it before returning the predictions to user. + # To achieve that, we throw the OutOfRangeError in after_run. Once + # Monitored Session sees this error in SessionRunHook.after_run, the + # "current" prediction, i.e., batch with id=100, will be discarded + # immediately + raise tf.errors.OutOfRangeError(None, None, 'Stopped by stopping signal.') + + +def generate_per_core_enqueue_ops_fn_for_host(ctx, input_fn, + inputs_structure_recorder, + host_device, host_id): + """Generates infeed enqueue ops for per-core input_fn on a single host.""" + captured_infeed_queue = _CapturedObject() + tpu_ordinal_function_impl = ctx.tpu_ordinal_function(host_id) + + def enqueue_ops_fn(): + """A fn returns enqueue_ops.""" + num_cores_per_host = ctx.num_of_cores_per_host + per_host_sharded_inputs = [] + for core_ordinal in range(num_cores_per_host): + with ops.name_scope('ordinal_%d' % (core_ordinal)): + user_context = tpu_context.TPUContext( + internal_ctx=ctx, + input_device=host_device, + invocation_index=host_id * ctx.num_of_cores_per_host + core_ordinal, + host_id=host_id) + inputs = _Inputs.from_input_fn(input_fn(user_context)) + if inputs.is_dataset: + raise TypeError( + '`input_fn` returning `Dataset` is not yet supported in ' + 'per-Core input pipeline deployment yet. Please set ' + 'TPUConfig.per_host_input_for_training to True or return ' + '`features` and `labels` from `input_fn`') + features, labels = inputs.features_and_labels() + + inputs_structure_recorder.validate_and_record_structure( + features, labels) + flattened_inputs = ( + inputs_structure_recorder.flatten_features_and_labels( + features, labels)) + per_host_sharded_inputs.append(flattened_inputs) + + infeed_queue = tpu_feed.InfeedQueue( + number_of_tuple_elements=len(per_host_sharded_inputs[0])) + captured_infeed_queue.capture(infeed_queue) + + per_host_enqueue_ops = infeed_queue.generate_enqueue_ops( + per_host_sharded_inputs, tpu_ordinal_function=tpu_ordinal_function_impl) + return per_host_enqueue_ops + + return enqueue_ops_fn, captured_infeed_queue + + +def generate_per_host_enqueue_ops_fn_for_host(ctx, input_fn, + inputs_structure_recorder, + batch_axis, device, host_id): + """Generates infeed enqueue ops for per-host input_fn on a single host.""" + captured_infeed_queue = _CapturedObject() + + dataset_initializer = None + + with tf.compat.v1.device(device): + user_context = tpu_context.TPUContext( + internal_ctx=ctx, + input_device=device, + invocation_index=host_id, + host_id=host_id) + inputs = _Inputs.from_input_fn(input_fn(user_context)) + + is_dataset = inputs.is_dataset + if ctx.mode == model_fn_lib.ModeKeys.PREDICT: + if not is_dataset: + raise TypeError( + 'For mode PREDICT, `input_fn` must return `Dataset` instead of ' + '`features` and `labels`.') + if batch_axis is not None: + raise TypeError('For mode PREDICT, batch_axis is not supported yet.') + inputs = _InputsWithStoppingSignals( + dataset=inputs.dataset, + batch_size=ctx.batch_size_for_input_fn, + add_padding=True) + + if is_dataset: + dataset_initializer = inputs.dataset_initializer() + + tpu_ordinal_function_impl = ctx.tpu_ordinal_function(host_id) + + def enqueue_ops_fn(): + """A Fn returning the TPU infeed enqueue ops. + + By providing as a Fn, it can be invoked inside the tf.while_loop such that + the input pipeline for multiple iterations can be executed by one + Session.run call. + + Returns: + list of dict of ops. + """ + with tf.compat.v1.device(device): + num_of_replicas_per_host = ctx.num_of_replicas_per_host + # Convert user input to features and labels. If the user returns a + # dataset, it is initialized and the features and labels extracted via + # `dataset.iterator.get_next()` + features, labels = inputs.features_and_labels() + signals = inputs.signals() + + features, labels, enqueue_datas_list = ( + _tpu_estimator_embedding.split_inputs( + ctx, + features, + labels, + num_cores_per_batch=num_of_replicas_per_host)) + + inputs_structure_recorder.validate_and_record_structure(features, labels) + unsharded_tensor_list = ( + inputs_structure_recorder.flatten_features_and_labels( + features, labels, signals)) + + infeed_queue = tpu_feed.InfeedQueue( + tuple_types=[t.dtype for t in unsharded_tensor_list], + tuple_shapes=[t.shape for t in unsharded_tensor_list], + shard_dimensions=batch_axis) + captured_infeed_queue.capture(infeed_queue) + infeed_queue.set_number_of_shards(num_of_replicas_per_host) + per_host_enqueue_ops = ( + infeed_queue.split_inputs_and_generate_enqueue_ops( + unsharded_tensor_list, + placement_function=lambda x: device, + tpu_ordinal_function=tpu_ordinal_function_impl)) + + if ctx.embedding_config: + per_host_enqueue_ops.extend( + ctx.embedding_config.tpu_embedding.generate_enqueue_ops( + enqueue_datas_list)) + + if signals is None: + return per_host_enqueue_ops + else: + return { + 'ops': per_host_enqueue_ops, + 'signals': signals, + } + + return enqueue_ops_fn, captured_infeed_queue, dataset_initializer + + +def generate_per_host_v2_enqueue_ops_fn_for_host(ctx, input_fn, + inputs_structure_recorder, + device, host_id, + invocation_index): + """Generates infeed enqueue ops for per-host input_fn on a single host.""" + captured_infeed_queue = _CapturedObject() + dataset_initializer = None + + with tf.compat.v1.device(device): + user_context = tpu_context.TPUContext( + internal_ctx=ctx, + input_device=device, + invocation_index=invocation_index, + host_id=host_id) + inputs = _Inputs.from_input_fn(input_fn(user_context)) + + is_dataset = inputs.is_dataset + if not is_dataset: + raise TypeError('`input_fn` must return a `Dataset` for the PER_HOST_V2 ' + 'input pipeline configuration.') + + # Be aware that when num_cores_per_replica > num_cores_per_host, + # ctx.num_of_replicas_per_host is 0. + if ctx.mode == model_fn_lib.ModeKeys.PREDICT: + inputs = _InputsWithStoppingSignals( + dataset=inputs.dataset, + batch_size=ctx.batch_size_for_input_fn, + add_padding=True, + num_invocations_per_step=max(1, ctx.num_of_replicas_per_host)) + + dataset_initializer = inputs.dataset_initializer() + + tpu_ordinal_function_impl = ctx.tpu_ordinal_function(host_id) + + def device_function_impl(shard_id): + if ctx.device_assignment is not None: + # Find the replica_id of the host's logical core 0. + # The current host_id is guaranteed to contain the logical core 0, + # even when num_cores_per_replica > num_cores_per_host -- the function + # caller makes sure that this host_id will must be receiving data (calls + # input_fn). + replica_id = ctx.device_assignment.lookup_replicas( + task_id=host_id, logical_core=0)[shard_id] + return ctx.tpu_host_placement_function(replica_id=replica_id) + else: + return None + + def enqueue_ops_fn(): + """Generates the per_host enqueue ops.""" + control_deps = [] + per_host_sharded_inputs = [] + enqueue_datas_list = [] + # Be aware that when num_cores_per_replica > num_cores_per_host, + # ctx.num_of_replicas_per_host is 0. + num_replicas_per_host = max(1, ctx.num_of_replicas_per_host) + cached_signals = None + with tf.compat.v1.device(device): + if not inputs.is_dataset: + raise TypeError('`input_fn` must return a `Dataset` for this mode.') + for host in range(num_replicas_per_host): + # Use control dependencies to ensure a deterministic ordering. + if ctx.allow_per_host_v2_parallel_get_next: + features, labels = inputs.features_and_labels() # Calls get_next() + with tf.control_dependencies(control_deps): + if not ctx.allow_per_host_v2_parallel_get_next: + features, labels = inputs.features_and_labels() # Calls get_next() + signals = inputs.signals() + + # All the replicas share the replica 0's stopping signal. + # This avoids inconsistent state among different model replcias. + if cached_signals: + signals['stopping'] = cached_signals['stopping'] + else: + cached_signals = signals + + features, labels, enqueue_data = ( + _tpu_estimator_embedding.split_inputs(ctx, features, labels)) + if len(enqueue_data) != 1: + raise RuntimeError(('Missing or extra enqueue_data for host {}. ' + 'len(enqueue_data) = {}.').format( + host, len(enqueue_data))) + enqueue_datas_list.append(enqueue_data[0]) + + inputs_structure_recorder.validate_and_record_structure( + features, labels) + flattened_inputs = ( + inputs_structure_recorder.flatten_features_and_labels( + features, labels, signals)) + control_deps.extend(flattened_inputs) + per_host_sharded_inputs.append(flattened_inputs) + + if inputs_structure_recorder.flattened_input_dims: + input_partition_dims = inputs_structure_recorder.flattened_input_dims + if signals: + input_partition_dims += [None] * len(signals) + # pylint: disable=protected-access + infeed_queue = tpu_feed._PartitionedInfeedQueue( + number_of_tuple_elements=len(per_host_sharded_inputs[0]), + host_id=host_id, + input_partition_dims=input_partition_dims, + device_assignment=ctx.device_assignment) + per_host_enqueue_ops = infeed_queue.generate_enqueue_ops( + per_host_sharded_inputs) + else: + infeed_queue = tpu_feed.InfeedQueue( + number_of_tuple_elements=len(per_host_sharded_inputs[0])) + per_host_enqueue_ops = infeed_queue.generate_enqueue_ops( + per_host_sharded_inputs, + tpu_ordinal_function=tpu_ordinal_function_impl, + placement_function=device_function_impl) + + captured_infeed_queue.capture(infeed_queue) + + if ctx.embedding_config: + per_host_enqueue_ops.extend( + ctx.embedding_config.tpu_embedding.generate_enqueue_ops( + enqueue_datas_list)) + + if signals is None: + return per_host_enqueue_ops + else: + return { + 'ops': per_host_enqueue_ops, + 'signals': signals, + } + + return enqueue_ops_fn, captured_infeed_queue, dataset_initializer + + +def generate_broadcast_enqueue_ops_fn(ctx, input_fn, inputs_structure_recorder, + num_hosts): + """Generates infeed enqueue ops for one input_fn on all the hosts.""" + captured_infeed_queue = _CapturedObject() + dataset_initializer = None + device_0 = ctx.tpu_host_placement_function(host_id=0) + with tf.compat.v1.device(device_0): + user_context = tpu_context.TPUContext( + internal_ctx=ctx, input_device=device_0, invocation_index=0, host_id=0) + inputs = _Inputs.from_input_fn(input_fn(user_context)) + + is_dataset = inputs.is_dataset + if ctx.mode == model_fn_lib.ModeKeys.PREDICT: + if not is_dataset: + raise TypeError( + 'For mode PREDICT, `input_fn` must return `Dataset` instead of ' + '`features` and `labels`.') + + inputs = _InputsWithStoppingSignals( + dataset=inputs.dataset, + batch_size=ctx.batch_size_for_input_fn, + add_padding=True) + + if is_dataset: + dataset_initializer = inputs.dataset_initializer() + num_replicas_per_host = ctx.num_of_replicas_per_host + + def tpu_ordinal_function_impl(shard_id): + if ctx.device_assignment: + return ctx.device_assignment.tpu_ordinal(replica=shard_id) + else: + return shard_id % num_replicas_per_host + + def device_function_impl(shard_id): + # shard_id ranges from 0 to num_of_replicas_per_host - 1. + # A shard is a replica inside a host. + # In broadcast mode (generate_broadcast_enqueue_ops_fn), the enqueue ops + # are always executed on the first host. Thus shard_id equals to replica_id. + return ctx.tpu_host_placement_function(replica_id=shard_id) + + def enqueue_ops_fn(): + """Generates enqueue ops for all the hosts.""" + broadcasted_inputs = [] + flattened_inputs = None # Cache result from input_fn. + signals = None + num_replicas = ctx.num_replicas + core_id = 0 + for host_id in xrange(num_hosts): + with tf.compat.v1.device( + ctx.tpu_host_placement_function(host_id=host_id)): + for _ in xrange(ctx.num_of_replicas_per_host): + # Note: input_fn is only called once at host 0 for the first replica. + # The features and labels returned from that invocation are + # broadcasted to other replicas(including the replicas on other + # hosts). + if flattened_inputs is None: + features, labels = inputs.features_and_labels() # Calls get_next() + signals = inputs.signals() + + inputs_structure_recorder.validate_and_record_structure( + features, labels) + flattened_inputs = ( + inputs_structure_recorder.flatten_features_and_labels( + features, labels, signals)) + if (ctx.config.tpu_config.eval_training_input_configuration is + tpu_config.InputPipelineConfig.SLICED): + input_slices = [ + tf.split(x, num_replicas) for x in flattened_inputs + ] + if (ctx.config.tpu_config.eval_training_input_configuration is + tpu_config.InputPipelineConfig.SLICED): + # for each core, slice out the flattened_inputs for each core. + broadcasted_inputs.append([x[core_id] for x in input_slices]) + core_id += 1 + else: + broadcasted_inputs.append(flattened_inputs) + + infeed_queue = tpu_feed.InfeedQueue( + number_of_tuple_elements=len(broadcasted_inputs[0])) + captured_infeed_queue.capture(infeed_queue) + enqueue_ops = infeed_queue.generate_enqueue_ops( + broadcasted_inputs, + tpu_ordinal_function=tpu_ordinal_function_impl, + placement_function=device_function_impl) + + if signals is None: + return enqueue_ops + else: + return { + 'ops': enqueue_ops, + 'signals': signals, + } + + return enqueue_ops_fn, captured_infeed_queue, dataset_initializer + + +class TensorPacker(object): + """Pack and unpack small tensors into a big one for efficiency.""" + + def __init__(self, small_feature_dim_size, + minimum_num_small_features_to_group): + self._small_feature_dim_size = small_feature_dim_size + self._minimum_num_small_features_to_group = ( + minimum_num_small_features_to_group) + + def maybe_concatenate_features(self, features): + """If there are enough small tensors, concat them for performance.""" + self._small_feature_names = {} + self._small_feature_sizes = {} + feature_names = _extract_key_names(features) + if feature_names: # Not a single tensor. + # First pass: see if it is worth concatenating the small features. + for name in feature_names: + tensor = features[name] + # We do not handle nested inputs here. + if not isinstance(tensor, tf.Tensor): + return + shape = tensor.get_shape().as_list() + dtype = tensor.dtype + if (len(shape) == 2 and shape[1] is not None and + shape[1] <= self._small_feature_dim_size): + tf.compat.v1.logging.log_first_n( + tf.compat.v1.logging.INFO, + 'Found small feature: %s %s', 1, name, shape) + if tensor.dtype not in self._small_feature_names: + self._small_feature_names[dtype] = [] + self._small_feature_sizes[dtype] = [] + self._small_feature_names[dtype].append(name) + self._small_feature_sizes[dtype].append(shape[1]) + + dtypes_ = list(self._small_feature_names.keys()) + for dtype in dtypes_: + # If we could find 5 (or more) [batch_size, 1] dense features, + # we will group them. + if (len(self._small_feature_names[dtype]) < + self._minimum_num_small_features_to_group): + self._small_feature_names.pop(dtype) # reset + self._small_feature_sizes.pop(dtype) # reset + + # Second pass: separate small features out + small_feature_tensors = {} + for dtype in self._small_feature_names: + small_feature_tensors[dtype] = [] + for name in self._small_feature_names[dtype]: + small_feature_tensors[dtype].append(features.pop(name)) + + # Add the concat Tensor to features with a special key. + for dtype in self._small_feature_names: + key = self._get_small_feature_key(dtype) + if key in features: + raise ValueError('{} is reserved as feature key for concatenated' + 'small features.') + features[key] = (tf.concat(small_feature_tensors[dtype], axis=1)) + + def maybe_split_features(self, maybe_concatenated_features): + for dtype in self._small_feature_names: + key = self._get_small_feature_key(dtype) + concatenated_small_features = maybe_concatenated_features.pop(key) + splits = tf.split( + concatenated_small_features, self._small_feature_sizes[dtype], axis=1) + for name, split in zip(self._small_feature_names[dtype], splits): + maybe_concatenated_features[name] = split + + def _get_small_feature_key(self, dtype): + return _TENSOR_PACKER_CONCATENATED_SMALL_FEATURES_KEY + '_' + str(dtype) + + +class _InputPipeline(object): + """`_InputPipeline` handles invoking `input_fn` and piping to infeed queue. + + `_InputPipeline` abstracts the per-core/per-host `input_fn` invocation from + call site. To be precise, based on the configuration in + `_InternalTPUContext`, it invokes `input_fn` for all cores (usually + multi-host TPU training) or for one host (usually for single-host TPU + evaluation), and sends all `features` and `labels` returned by `input_fn` to + TPU infeed. For per-core invocation, `features` and `labels` are piped to + infeed directly, one tuple for each core. For per-host invocation, `features` + and `labels` are split at host (with respect to `batch_axis`) and piped to all + cores accordingly. + + In addition, flatten/unflatten are handled by `_InputPipeline` also. Model + inputs returned by the `input_fn` can have one of the following forms: + 1. features + 2. (features, labels) + 3. ((arbitrarily nested structure of features), labels) + + Internally, form 1 is reformed to `(features, None)` as features and labels + are passed separately to underlying methods. For TPU training, TPUEstimator + may expect multiple `features` and `labels` tuples one for each core. + + TPUEstimator allows various different structures for inputs (namely `features` + and `labels`). Both `features` and `labels` can be any nested sturcture + supported by TF nest (namely, dict, tuples, namedtuples or any nested + structure of such of Tensors). `labels` could be `None` as well. + + These are flattened before they are passed to the infeed/outfeed library + as that expectes flattend lists. + """ + + class InputsStructureRecorder(object): + """The recorder to record inputs structure.""" + + def __init__(self, input_partition_dims=None): + # Holds the structure of inputs + self._feature_structure = {} + self._flattened_input_dims = None + + if input_partition_dims: + # This should have been validated in TPUConfig. + assert len(input_partition_dims) <= 2, 'must have 1 or 2 elements.' + if len(input_partition_dims) == 2: + self._feature_dims, self._label_dims = input_partition_dims + else: + self._feature_dims = input_partition_dims[0] + self._label_dims = None + + assert self._feature_dims is not None, ('input_partition_dims[0] must ' + 'not be None') + else: + self._feature_dims = None + self._label_dims = None + + # Internal state. + self._initialized = False + + @property + def flattened_input_dims(self): + assert self._initialized, 'InputsStructureRecorder is not initialized.' + return self._flattened_input_dims + + def has_labels(self): + return 'labels' in self._feature_structure + + def _flatten_input_dims(self, features, labels, feature_dims, label_dims): + """Flatten input dims with the same order as flattened input tensors.""" + + try: + flattened_input_dims = data_nest.flatten_up_to(features, feature_dims) + except TypeError as e: + raise ValueError( + 'TPUConfig.input_partition_dims[0] mismatched the structure of' + ' features. input_partition_dims[0]: {}, features {}. {}'.format( + feature_dims, features, e)) + + if labels is not None: + if label_dims is not None: + try: + flattened_input_dims.extend( + data_nest.flatten_up_to(labels, self._label_dims)) + except TypeError as e: + raise ValueError( + 'TPUConfig.input_partition_dims[1] mismatched the structure of' + ' labels. input_partition_dims[1]: {}, labels: {}. {}'.format( + label_dims, labels, e)) + else: + num_label_tensors = len(data_nest.flatten(labels)) + flattened_input_dims.extend([None] * num_label_tensors) + return flattened_input_dims + + def validate_and_record_structure(self, features, labels): + """Validates and records the structure of `features` and `labels`.""" + # Extract structure. + feature_names = _extract_key_names(features) + label_names = _extract_key_names(labels) + + if not self._initialized: + # Record structure. + self._initialized = True + if self._feature_dims is not None: + feature_dims_names = _extract_key_names(self._feature_dims) + if feature_dims_names != feature_names: + raise ValueError( + 'TPUConfig.input_partition_dims[0] mismatched feature' + ' keys. Expected {}, got {}'.format(feature_names, + feature_dims_names)) + label_dims_names = _extract_key_names(self._label_dims) + if self._label_dims is not None and label_dims_names != label_names: + raise ValueError( + 'TPUConfig.input_partition_dims[1] mismatched label' + ' keys. Expected {}, got {}'.format(label_names, + label_dims_names)) + self._flattened_input_dims = self._flatten_input_dims( + features, labels, self._feature_dims, self._label_dims) + + def flatten_features_and_labels(self, features, labels, signals=None): + """Flattens the `features` and `labels` to a single tensor list.""" + self.tensor_packer = TensorPacker( + _TENSOR_PACKER_SMALL_FEATURE_DIM_SIZE, + _TENSOR_PACKER_MINIMUM_NUM_SMALL_FEATURES_TO_GROUP) + self.tensor_packer.maybe_concatenate_features(features) + self._feature_structure['features'] = features + if labels is not None: + self._feature_structure['labels'] = labels + if signals is not None: + self._feature_structure['signals'] = signals + return data_nest.flatten(self._feature_structure) + + def unflatten_features_and_labels(self, flattened_inputs): + """Restores the flattened inputs to original features and labels form. + + Args: + flattened_inputs: Flattened inputs for each shard. + + Returns: + A tuple of (`features`, `labels`), where `labels` could be None. + Each one, if present, should have identical structure (single tensor vs + dict) as the one returned by input_fn. + + Raises: + ValueError: If the number of expected tensors from `flattened_inputs` + mismatches the recorded structure. + """ + + unflattened_inputs = data_nest.pack_sequence_as(self._feature_structure, + flattened_inputs) + features = unflattened_inputs['features'] + self.tensor_packer.maybe_split_features(features) + return _Inputs( + features, + unflattened_inputs.get('labels'), + signals=unflattened_inputs.get('signals')) + + def __init__(self, input_fn, batch_axis, ctx): + """Constructor. + + Args: + input_fn: input fn for train or eval. + batch_axis: A python tuple of int values describing how each tensor + produced by the Estimator `input_fn` should be split across the TPU + compute shards. + ctx: A `_InternalTPUContext` instance with mode. + + Raises: + ValueError: If both `sharded_features` and `num_cores` are `None`. + """ + self._inputs_structure_recorder = _InputPipeline.InputsStructureRecorder( + ctx.input_partition_dims) + + self._sharded_per_core = ctx.is_input_sharded_per_core() + self._input_fn = input_fn + self._infeed_queue = None + self._ctx = ctx + self._batch_axis = batch_axis + + def generate_infeed_enqueue_ops_and_dequeue_fn(self): + """Generates infeed enqueue ops and dequeue_fn.""" + # While tf.while_loop is called, the body function, which invokes + # `enqueue_fn` passed in, is called to construct the graph. So, input_fn + # structure is recorded. + enqueue_ops, all_hooks, run_infeed_loop_on_coordinator = ( + self._invoke_input_fn_and_record_structure()) + + self._validate_input_pipeline() + + def dequeue_fn(): + """dequeue_fn is used by TPU to retrieve the tensors.""" + # In the model-parallel case, both the host-side and device-side + # computations must agree on the core on which infeed takes place. We + # choose to perform infeed on logical core 0 of each replica. + values = self._infeed_queue.generate_dequeue_op(tpu_device=0) + # The unflatten process uses the structure information recorded above. + return self._inputs_structure_recorder.unflatten_features_and_labels( + values) + + return (enqueue_ops, dequeue_fn, all_hooks, run_infeed_loop_on_coordinator) + + def _invoke_input_fn_and_record_structure(self): + """Deploys the input pipeline and record input structure.""" + enqueue_ops = [] + infeed_queues = [] + all_dataset_initializers = [] + num_hosts = self._ctx.num_hosts + tpu_host_placement_fn = self._ctx.tpu_host_placement_function + + run_infeed_loop_on_coordinator = True + + if self._sharded_per_core: + # Per-Core input pipeline deployment. + # Invoke input pipeline for each core and placed on the corresponding + # host. + for host_id in range(num_hosts): + host_device = tpu_host_placement_fn(host_id=host_id) + with tf.compat.v1.device(host_device): + with ops.name_scope('input_pipeline_task%d' % (host_id)): + enqueue_ops_fn, captured_infeed_queue = ( + generate_per_core_enqueue_ops_fn_for_host( + self._ctx, self._input_fn, self._inputs_structure_recorder, + host_device, host_id)) + + if _WRAP_INPUT_FN_INTO_WHILE_LOOP: + run_infeed_loop_on_coordinator = False + enqueue_ops.append( + _wrap_computation_in_while_loop( + device=host_device, op_fn=enqueue_ops_fn)) + else: + enqueue_ops.append(enqueue_ops_fn()) + # Infeed_queue_getter must be called after enqueue_ops_fn is called. + infeed_queues.append(captured_infeed_queue.get()) + + elif self._ctx.is_input_broadcast_with_iterators(): + # Only calls input_fn in host 0. + host_device = tpu_host_placement_fn(host_id=0) + enqueue_ops_fn, captured_infeed_queue, dataset_initializer = ( + generate_broadcast_enqueue_ops_fn(self._ctx, self._input_fn, + self._inputs_structure_recorder, + num_hosts)) + if dataset_initializer: + all_dataset_initializers.append(dataset_initializer) + run_infeed_loop_on_coordinator = False + wrap_fn = ( + _wrap_computation_in_while_loop + if self._ctx.mode != model_fn_lib.ModeKeys.PREDICT else + _wrap_computation_in_while_loop_with_stopping_signals) + enqueue_ops.append(wrap_fn(device=host_device, op_fn=enqueue_ops_fn)) + else: + enqueue_ops.append(enqueue_ops_fn()) + infeed_queues.append(captured_infeed_queue.get()) + + else: + # This branch handles two senarios: + # num_cores_per_replica > num_cores_per_host + # and num_cores_per_replica <= num_cores_per_host + # First, get the set of host_ids, by iterating replicas. + # We only want and will get the set of *unique* host_ids + # *that will call input_fn*. For each replica, we only call the input_fn + # from the CPU host that contains logical core 0. + + # Use a list here to ensure deterministic order. + host_id_with_invocation_id_pair = [] + + if not self._ctx.is_replica_across_hosts(): + for host_id in range(num_hosts): + invocation_index = host_id + host_id_with_invocation_id_pair.append((host_id, invocation_index)) + else: + for replica_id in xrange(self._ctx.num_replicas): + invocation_index = replica_id + host_device, _ = self._ctx.device_for_replica(replica_id) + # TODO(lehou): Get host_id in a better way. + host_id = int(host_device.split('/task:')[1].split('/device:')[0]) + host_id_with_invocation_id_pair.append((host_id, invocation_index)) + + for (host_id, invocation_index) in host_id_with_invocation_id_pair: + host_device = tpu_host_placement_fn(host_id=host_id) + with tf.compat.v1.device(host_device): + with ops.name_scope('input_pipeline_task%d' % (host_id)): + if self._ctx.is_input_per_host_with_iterators(): + enqueue_ops_fn, captured_infeed_queue, dataset_initializer = ( + generate_per_host_v2_enqueue_ops_fn_for_host( + self._ctx, self._input_fn, + self._inputs_structure_recorder, host_device, host_id, + invocation_index)) + else: + enqueue_ops_fn, captured_infeed_queue, dataset_initializer = ( + generate_per_host_enqueue_ops_fn_for_host( + self._ctx, self._input_fn, + self._inputs_structure_recorder, self._batch_axis, + host_device, host_id)) + + # NOTE(xiejw): We dispatch here based on the return type of the + # users `input_fn`. + # + # 1. If input_fn returns a Dataset instance, we initialize the + # iterator outside of tf.while_loop, and call the iterator.get_next + # inside tf.while_loop. This should be always safe. + # + # 2. If input_fn returns (features, labels), it is too late to wrap + # them inside tf.while_loop, as resource initialization cannot be + # handled in TF control flow properly. In this case, we will use + # python loop to enqueue the data into TPU system. This may be + # slow compared to the previous case. + if dataset_initializer: + all_dataset_initializers.append(dataset_initializer) + run_infeed_loop_on_coordinator = False + wrap_fn = ( + _wrap_computation_in_while_loop + if self._ctx.mode != model_fn_lib.ModeKeys.PREDICT else + _wrap_computation_in_while_loop_with_stopping_signals) + enqueue_ops.append( + wrap_fn(device=host_device, op_fn=enqueue_ops_fn)) + else: + enqueue_ops.append(enqueue_ops_fn()) + infeed_queues.append(captured_infeed_queue.get()) + + # infeed_queue is used to generate dequeue ops. The only thing it uses for + # dequeue is dtypes and types. So, any one can be used. Here, grab the + # first one. + self._infeed_queue = infeed_queues[0] + return enqueue_ops, [ + util_lib.MultiHostDatasetInitializerHook(all_dataset_initializers) + ], run_infeed_loop_on_coordinator + + def _validate_input_pipeline(self): + """Validates the input pipeline. + + Perform some sanity checks to log user friendly information. We should + error out to give users better error message. But, if + _WRAP_INPUT_FN_INTO_WHILE_LOOP is False (legacy behavior), we cannot break + user code, so, log a warning. + + Raises: + RuntimeError: If the validation failed. + """ + if tf.compat.v1.get_default_graph().get_collection( + tf.compat.v1.GraphKeys.QUEUE_RUNNERS): + err_msg = ('Input pipeline contains one or more QueueRunners. ' + 'It could be slow and not scalable. Please consider ' + 'converting your input pipeline to use `tf.data` instead (see ' + 'https://www.tensorflow.org/guide/datasets for ' + 'instructions.') + if _WRAP_INPUT_FN_INTO_WHILE_LOOP: + raise RuntimeError(err_msg) + else: + logging.warn(err_msg) + + +def call_computation(computation_inputs, computation, batch_config=None): + """Call computation. + + Args: + computation_inputs: A tensor or dict of tensors, the inputs to the + computation. + computation: A Python function that takes no inputs and builds computation + graph. If `computation` returns m outputs, this function will return a + list of m Tensors. + batch_config: A BatchConfig named tuple specifying the batching + configuration to use for inference batching. + + Returns: + A list of output tensors. + """ + + # Using `TPUPartitionedCall` makes it possible to target a different + # TPU core with every `Session.run()` call. Note that the entire inference + # graph executes on a single core, and that invocations of this graph + # will round-robin among the cores attached to a host. + def tpu_partitioned_call(partition_inputs): + + # capture_resource_var_by_value enables variables to be mirrored on TPU + # to avoid fetching from CPU, since variables do not change during + # inference. + @function.Defun(capture_resource_var_by_value=False) + def tpu_subgraph(): + return computation(partition_inputs) + + return tpu_functional.TPUPartitionedCall( + args=tpu_subgraph.captured_inputs, + device_ordinal=tpu_ops.tpu_ordinal_selector(), + Tout=[o.type for o in tpu_subgraph.definition.signature.output_arg], + f=tpu_subgraph) + + # Not using Batching Function but use TPUPartitionedCall/all cores. + if not batch_config: + return tpu_partitioned_call(computation_inputs) + + # Use Batching Function and TPUPartitionedCall/all cores. + # Note that BatchingFunction requires a list of tensors and doesn't support + # a dict of tensors. So we preserve the structure by deterministically + # flattening the dict before batching and then recomposing it after batching + # to feed into the computation. + ordered_inputs_list = tf.nest.flatten(computation_inputs) + + @tf.nondifferentiable_batch_function( + num_batch_threads=batch_config.num_batch_threads, + max_batch_size=batch_config.max_batch_size, + batch_timeout_micros=batch_config.batch_timeout_micros, + allowed_batch_sizes=batch_config.allowed_batch_sizes, + max_enqueued_batches=batch_config.max_enqueued_batches, + autograph=False) + def batched_tpu_computation(*tensor_args): + """Recompose the input feature dict and calls the TPU computation.""" + computation_feature_input = tf.nest.pack_sequence_as( + computation_inputs, tensor_args) + return tpu_partitioned_call(computation_feature_input) + + return batched_tpu_computation(*ordered_inputs_list) + + +class _ModelFnWrapper(object): + """A `model_fn` wrapper. + + This makes calling model_fn on CPU and TPU easier and more consistent and + performs necessary check and mutation required by TPU training and evaluation. + + In addition, this wrapper manages converting the `model_fn` to a single TPU + train and eval step. + """ + + def __init__(self, model_fn, config, params, ctx): + self._model_fn = model_fn + self._config = config + self._params = params + self._ctx = ctx + + def call_without_tpu(self, features, labels, is_export_mode): + return self._call_model_fn(features, labels, is_export_mode=is_export_mode) + + def _add_embedding_features(self, features, hook_dummy_table_variables): + """Add embedding features, optionally add hook to intercept gradient.""" + if self._ctx.embedding_config: + tpu_embedding_ = self._ctx.embedding_config.tpu_embedding + embedding_activations = tpu_embedding_.get_activations() + if hook_dummy_table_variables: + new_embedding_activations = ( + tpu_embedding_gradient.hook_dummy_table_variables_to_activations( + tpu_embedding_, embedding_activations, + self._ctx.embedding_config.dummy_table_variables)) + features.update(new_embedding_activations) + else: + features.update(embedding_activations) + + def convert_to_single_tpu_train_step(self, dequeue_fn): + """Converts user provided model_fn` as a single train step on TPU. + + The user provided `model_fn` takes input tuple + (features, labels) and produces the EstimatorSpec with train_op and loss for + train `mode`. This usually represents a single train computation on CPU. + + For TPU training, a train (computation) step is first wrapped in a + tf.while_loop control flow to repeat for many times and then replicated to + all TPU shards. Besides the input should be taken from TPU infeed rather + than input pipeline (input_fn) directly. To fit TPU loop and replicate + pattern, the original train computation should be reformed, which is the + returned `train_step`. + + Args: + dequeue_fn: The function to retrieve inputs, features and labels, from TPU + infeed dequeue channel. + + Returns: + A tuple of train_fn, host_calls, and captured scaffold_fn. The train_fn + representing the train step for TPU. + """ + + host_call = _OutfeedHostCall( + self._ctx, + outfeed_every_n_steps=self._config.tpu_config + .experimental_host_call_every_n_steps) + captured_scaffold_fn = _CapturedObject() + captured_training_hooks = _CapturedObject() + + def train_step(step): + """Training step function for use inside a while loop.""" + inputs = dequeue_fn() + features, labels = inputs.features_and_labels() + self._add_embedding_features(features, True) + + estimator_spec = self._verify_estimator_spec( + self._call_model_fn(features, labels)) + loss, train_op = estimator_spec.loss, estimator_spec.train_op + + if tensor_tracer.TensorTracer.is_enabled(): + tt = tensor_tracer.TensorTracer() + loss = tt.trace_tpu(tf.compat.v1.get_default_graph(), loss, train_op, + self._ctx.num_replicas) + tracer_host_call = tt.host_call_deps_and_fn() + else: + tracer_host_call = {} + + if isinstance(estimator_spec, model_fn_lib._TPUEstimatorSpec): # pylint: disable=protected-access + captured_scaffold_fn.capture(estimator_spec.scaffold_fn) + else: + captured_scaffold_fn.capture(None) + + captured_training_hooks.capture(estimator_spec.training_hooks) + + if self._ctx.embedding_config is None: + apply_sparse_grads = [] + else: + tpu_embedding_ = self._ctx.embedding_config.tpu_embedding + gradients = ( + tpu_embedding_gradient.get_gradients_through_dummy_table_variables( + tpu_embedding_)) + grad_multiplier = self._ctx.embedding_config.get_grad_multiplier() + if grad_multiplier is not None: + scaled_gradients = collections.OrderedDict( + (k, v * grad_multiplier) for k, v in six.iteritems(gradients)) + else: + scaled_gradients = gradients + apply_sparse_grads = [ + tpu_embedding_.generate_send_gradients_op( + scaled_gradients, tf.compat.v1.train.get_global_step()) + ] + + stopping_signals = None + user_provided_stopping_signals_name = None + if self._ctx.feed_hook is not None: + stopping_signals, user_provided_stopping_signals_name = \ + self._ctx.feed_hook.get_stopping_signals_and_name(features) + + # We must run train_op to update the variables prior to running the + # outfeed. + with tf.control_dependencies([train_op] + apply_sparse_grads): + host_call_outfeed_ops = [] + host_call_fn, host_call_args = None, [] + + if (isinstance(estimator_spec, model_fn_lib._TPUEstimatorSpec) # pylint: disable=protected-access + and estimator_spec.host_call is not None): + host_call_fn, host_call_args = estimator_spec.host_call + + if stopping_signals is not None: + identity_fn = lambda **kwargs: kwargs + tracer_host_call[user_provided_stopping_signals_name] = [ + identity_fn, stopping_signals + ] + + if host_call_fn: + # Ignore dummy hostcalls (no arguments) + if host_call_args: + tracer_host_call.update({'host_call': estimator_spec.host_call}) + host_call.record(tracer_host_call) + host_call_outfeed_ops = host_call.create_enqueue_op(step) + elif tracer_host_call: + host_call.record(tracer_host_call) + host_call_outfeed_ops = host_call.create_enqueue_op(step) + else: + # Create a host call for the loss to track execution progress + # Without this, we don't have any indication of the state of the + # TPU program. + tracer_host_call.update( + {'host_call': (lambda loss_t: loss_t, [tf.reshape(loss, [1])])}) + host_call.record(tracer_host_call) + host_call_outfeed_ops = host_call.create_enqueue_op(step) + + with tf.control_dependencies(host_call_outfeed_ops): + return tf.identity(loss) + + return (train_step, host_call, captured_scaffold_fn, + captured_training_hooks) + + def convert_to_single_tpu_eval_step(self, dequeue_fn): + """Converts user provided model_fn` as a single eval step on TPU. + + Similar to training, the user provided `model_fn` takes input tuple + (features, labels) and produces the TPUEstimatorSpec with eval_metrics for + eval `mode`. This usually represents a single evaluation computation on CPU. + + For TPU evaluation, a eval (computation) step is first wrapped in a + tf.while_loop control flow to repeat for many times and then replicated to + all TPU shards. Besides the input and output are slightly different. Input, + features and labels, should be taken from TPU infeed rather than input + pipeline (input_fn) directly. Output is managed in two stages. First, the + model outputs as the result of evaluation computation, usually model logits, + should be transferred from TPU system to CPU. Then, all model outputs are + concatenated first on CPU and sent to the metric_fn for metrics computation. + To fit TPU evaluation pattern, the original eval computation should be + reformed, which is the returned `eval_step`. + + Args: + dequeue_fn: The function to retrieve inputs, features and labels, from TPU + infeed dequeue channel. + + Returns: + A tuple of eval_fn, host_calls, and captured scaffold_fn. The eval_fn + representing the eval step for TPU. + """ + host_calls = _OutfeedHostCall(self._ctx) + captured_scaffold_fn = _CapturedObject() + captured_eval_hooks = _CapturedObject() + + def eval_step(total_loss): + """Evaluation step function for use inside a while loop.""" + inputs = dequeue_fn() + features, labels = inputs.features_and_labels() + self._add_embedding_features(features, False) + + tpu_estimator_spec = self._call_model_fn(features, labels) + if not isinstance(tpu_estimator_spec, model_fn_lib._TPUEstimatorSpec): # pylint: disable=protected-access + raise RuntimeError( + 'estimator_spec used by TPU evaluation must have type' + '`TPUEstimatorSpec`. Got {}'.format(type(tpu_estimator_spec))) + + loss = tpu_estimator_spec.loss + captured_scaffold_fn.capture(tpu_estimator_spec.scaffold_fn) + captured_eval_hooks.capture(tpu_estimator_spec.evaluation_hooks) + + to_record = {} + if tpu_estimator_spec.eval_metrics: + to_record['eval_metrics'] = tpu_estimator_spec.eval_metrics + if tpu_estimator_spec.host_call is not None: + # We assume that evaluate won't update global step, so we don't wrap + # this host_call. + to_record['host_call'] = tpu_estimator_spec.host_call + host_calls.record(to_record) + + with tf.control_dependencies(host_calls.create_enqueue_op()): + return tf.math.add(total_loss, loss) + + return eval_step, host_calls, captured_scaffold_fn, captured_eval_hooks + + def convert_to_single_tpu_predict_step(self, dequeue_fn): + """Converts user provided model_fn` as a single predict step on TPU. + + Args: + dequeue_fn: The function to retrieve inputs, features and labels, from TPU + infeed dequeue channel. + + Returns: + A tuple of predict_fn, host_calls, and captured scaffold_fn. The + predict_fn representing the predict step for TPU. + """ + host_calls = _OutfeedHostCall(self._ctx) + captured_scaffold_fn = _CapturedObject() + captured_predict_hooks = _CapturedObject() + + def predict_step(unused_scalar_stopping_signal): + """Evaluation step function for use inside a while loop.""" + inputs = dequeue_fn() + features, labels = inputs.features_and_labels() + stopping_signals = inputs.signals() + + assert stopping_signals is not None, ( + 'Internal Error: `signals` is missing.') + + tpu_estimator_spec = self._call_model_fn( + features, labels, is_export_mode=False) + if not isinstance(tpu_estimator_spec, model_fn_lib._TPUEstimatorSpec): # pylint: disable=protected-access + raise RuntimeError( + 'estimator_spec used by TPU prediction must have type' + '`TPUEstimatorSpec`. Got {}'.format(type(tpu_estimator_spec))) + + self._verify_tpu_spec_predictions(tpu_estimator_spec.predictions) + + captured_scaffold_fn.capture(tpu_estimator_spec.scaffold_fn) + captured_predict_hooks.capture(tpu_estimator_spec.prediction_hooks) + to_record = {} + identity_fn = lambda **kwargs: kwargs + to_record['predictions'] = [identity_fn, tpu_estimator_spec.predictions] + to_record['signals'] = [identity_fn, stopping_signals] + if tpu_estimator_spec.host_call is not None: + to_record['host_call'] = tpu_estimator_spec.host_call + host_calls.record(to_record) + + with tf.control_dependencies(host_calls.create_enqueue_op()): + return _StopSignals.as_scalar_stopping_signal(stopping_signals) + + return (predict_step, host_calls, captured_scaffold_fn, + captured_predict_hooks) + + def _verify_tpu_spec_predictions(self, predictions): + """Validates TPUEstimatorSpec.predictions dict.""" + # TODO(xiejw): Adds validation for prediction dictionrary. + # TODO(xiejw): Adds support for single tensor as predictions. + if not isinstance(predictions, dict): + raise TypeError('TPUEstimatorSpec.predictions must be dict of Tensors.') + + for (key, tensor) in predictions.items(): + if tensor.shape.dims[0].value is None: + raise ValueError( + 'The tensor with key ({}) in TPUEstimatorSpec.predictions has ' + 'dynamic shape (should be static). Tensor: {}'.format(key, tensor)) + return predictions + + def _validate_model_features_and_labels(self, features, labels, + is_export_mode): + """Validates that the features and labels for the model function are valid. + + A valid features/labels object is the one with: + - Type: A tensor or any nested structure of tensors supported by TF nest, + namely nested dictionary, tuple, namedtuple, or sequence of tensors. + - Static shape if is_export_mode is False. + + Args: + features: the features that would be input to the model function. + labels: the labels that would be input to the model function. + is_export_mode: boolean value specifying if in export mode. + + Raises: + TypeError: If features/labels are not of the correct type. + ValueError: If features/labels have dynamic shape. + """ + + def validate(obj, obj_name): + """Helper validate function.""" + if is_export_mode or self._ctx.is_running_on_cpu(is_export_mode): + return + if isinstance(obj, tf.Tensor): + if not obj.get_shape().is_fully_defined(): + raise ValueError( + 'The {} to the model returned by input_fn must have static shape.' + ' Tensor: {}'.format(obj_name, obj)) + else: + for tensor in data_nest.flatten(obj): + if not tensor.get_shape().is_fully_defined(): + raise ValueError( + ('The {} to the model returned by input_fn must have static ' + 'shape. Tensor: {}').format(obj_name, tensor)) + + validate(features, 'features') + if labels is not None: + validate(labels, 'labels') + + def _call_model_fn(self, features, labels, is_export_mode=False): + """Calls the model_fn with required parameters.""" + self._validate_model_features_and_labels(features, labels, is_export_mode) + model_fn_args = function_utils.fn_args(self._model_fn) + kwargs = {} + + # Makes deep copy with `config` and params` in case user mutates them. + config = copy.deepcopy(self._config) + params = copy.deepcopy(self._params) + + if 'labels' in model_fn_args: + kwargs['labels'] = labels + elif labels is not None: + raise ValueError( + 'model_fn does not take labels, but input_fn returns labels.') + if 'mode' in model_fn_args: + kwargs['mode'] = self._ctx.mode + if 'config' in model_fn_args: + kwargs['config'] = config + if 'params' in model_fn_args: + kwargs['params'] = params + + if 'params' not in model_fn_args: + raise ValueError('model_fn ({}) does not include params argument, ' + 'required by TPUEstimator to pass batch size as ' + 'params[\'batch_size\']'.format(self._model_fn)) + + if is_export_mode: + batch_size_for_model_fn = None + else: + batch_size_for_model_fn = self._ctx.batch_size_for_model_fn + + if batch_size_for_model_fn is not None: + _add_item_to_params(params, _BATCH_SIZE_KEY, batch_size_for_model_fn) + + running_on_cpu = self._ctx.is_running_on_cpu(is_export_mode) + # In export mode, params['use_tpu'] has already been set based on mode + # (i.e. True for _REWRITE_FOR_INFERENCE_MODE, False otherwise). + if not is_export_mode: + _add_item_to_params(params, _USE_TPU_KEY, not running_on_cpu) + + if not running_on_cpu: + user_context = tpu_context.TPUContext( + internal_ctx=self._ctx, call_from_input_fn=False) + _add_item_to_params(params, _CTX_KEY, user_context) + + estimator_spec = self._model_fn(features=features, **kwargs) + if (running_on_cpu and + isinstance(estimator_spec, model_fn_lib._TPUEstimatorSpec)): # pylint: disable=protected-access + # The estimator_spec will be passed to `Estimator` directly, which expects + # type `EstimatorSpec`. As we are running on the CPU, escape + # the TPUInferenceContext. + graph_context = tf.compat.v1.get_default_graph( + )._get_control_flow_context() + try: + if isinstance(graph_context, tpu._TPUInferenceContext): + tf.compat.v1.get_default_graph()._set_control_flow_context( + graph_context.outer_context) + return estimator_spec.as_estimator_spec() + finally: + tf.compat.v1.get_default_graph()._set_control_flow_context( + graph_context) + else: + return estimator_spec + + def _verify_estimator_spec(self, estimator_spec): + """Validates the estimator_spec.""" + if isinstance(estimator_spec, model_fn_lib._TPUEstimatorSpec): # pylint: disable=protected-access + return estimator_spec + + err_msg = '{} returned by EstimatorSpec is not supported in TPUEstimator.' + if estimator_spec.training_chief_hooks: + raise ValueError( + err_msg.format('training_chief_hooks') + 'If you want' + + ' to pass training hooks, please pass via training_hooks.') + + if estimator_spec.scaffold: + tf.compat.v1.logging.warn( + 'EstimatorSpec.Scaffold is ignored by TPU train/eval. ' + 'Please use TPUEstimatorSpec.') + return estimator_spec + + +class _OutfeedHostCall(object): + """Support for `eval_metrics` and `host_call` in TPUEstimatorSpec.""" + + def __init__(self, ctx, outfeed_every_n_steps=1): + self._ctx = ctx + self._names = [] + # All of these are dictionaries of lists keyed on the name. + self._host_fns = {} + self._tensor_keys = collections.defaultdict(list) + self._tensors = collections.defaultdict(list) + self._tensor_dtypes = collections.defaultdict(list) + self._tensor_shapes = collections.defaultdict(list) + self._outfeed_every_n_steps = outfeed_every_n_steps + + @staticmethod + def validate(host_calls): + """Validates the `eval_metrics` and `host_call` in `TPUEstimatorSpec`.""" + + for name, host_call in host_calls.items(): + if not isinstance(host_call, (tuple, list)): + raise ValueError('{} should be tuple or list'.format(name)) + if len(host_call) != 2: + raise ValueError('{} should have two elements.'.format(name)) + if not callable(host_call[0]): + raise TypeError('{}[0] should be callable.'.format(name)) + if not isinstance(host_call[1], (tuple, list, dict)): + raise ValueError('{}[1] should be tuple or list, or dict.'.format(name)) + + if isinstance(host_call[1], (tuple, list)): + fullargspec = tf_inspect.getfullargspec(host_call[0]) + fn_args = function_utils.fn_args(host_call[0]) + # wrapped_hostcall_with_global_step uses varargs, so we allow that. + if fullargspec.varargs is None and len(host_call[1]) != len(fn_args): + raise RuntimeError( + 'In TPUEstimatorSpec.{}, length of tensors {} does not match ' + 'method args of the function, which takes {}.'.format( + name, len(host_call[1]), len(fn_args))) + + @staticmethod + def create_cpu_hostcall(host_calls): + """Runs on the host_call on CPU instead of TPU when use_tpu=False.""" + + _OutfeedHostCall.validate(host_calls) + ret = {} + for name, host_call in host_calls.items(): + host_fn, tensors = host_call + if isinstance(tensors, (tuple, list)): + ret[name] = host_fn(*tensors) + else: + # Must be dict. + try: + ret[name] = host_fn(**tensors) + except TypeError as e: + tf.compat.v1.logging.warn( + 'Exception while calling %s: %s. It is likely the tensors ' + '(%s[1]) do not match the ' + 'function\'s arguments', name, e, name) + raise + return ret + + def record(self, host_calls): + """Records the host_call structure.""" + + for name, host_call in host_calls.items(): + host_fn, tensor_list_or_dict = host_call + self._names.append(name) + self._host_fns[name] = host_fn + + if isinstance(tensor_list_or_dict, dict): + for (key, tensor) in six.iteritems(tensor_list_or_dict): + self._tensor_keys[name].append(key) + self._tensors[name].append(tensor) + self._tensor_dtypes[name].append(tensor.dtype) + self._tensor_shapes[name].append(tensor.shape) + else: + # List or tuple. + self._tensor_keys[name] = None + for tensor in tensor_list_or_dict: + self._tensors[name].append(tensor) + self._tensor_dtypes[name].append(tensor.dtype) + self._tensor_shapes[name].append(tensor.shape) + + def create_enqueue_op(self, step=None): + """Create the op to enqueue the recorded host_calls. + + Returns: + A list of enqueue ops, which is empty if there are no host calls. + """ + if not self._names: + return [] + + tensors = [] + # TODO(jhseu): Consider deduping tensors. + for name in self._names: + tensors.extend(self._tensors[name]) + + if self._outfeed_every_n_steps > 1 and step is None: + raise ValueError('If outfeed is requested every n steps, you must pass ' + 'a tensor whose value is the step number within the ' + 'current training loop.') + with tf.compat.v1.device(tf.compat.v1.tpu.core(0)): + if self._outfeed_every_n_steps == 1: + return [tpu_ops.outfeed_enqueue_tuple(tensors)] + else: + return [ + tf.compat.v1.cond( + tf.math.equal( + tf.math.floormod(step, self._outfeed_every_n_steps), + 0), lambda: tpu_ops.outfeed_enqueue_tuple(tensors), + lambda: tf.no_op()) + ] + + def create_tpu_hostcall(self): + """Sends the tensors through outfeed and runs the host_fn on CPU. + + The tensors are concatenated along dimension 0 to form a global tensor + across all shards. The concatenated function is passed to the host_fn and + executed on the first host. + + Returns: + A dictionary mapping name to the return type of the host_call by that + name. + + Raises: + RuntimeError: If outfeed tensor is scalar. + """ + if not self._names: + return {} + + ret = {} + # For each i, dequeue_ops[i] is a list containing the tensors from all + # shards. This list is concatenated later. + dequeue_ops = [] + tensor_dtypes = [] + tensor_shapes = [] + for name in self._names: + for _ in self._tensors[name]: + dequeue_ops.append([]) + for dtype in self._tensor_dtypes[name]: + tensor_dtypes.append(dtype) + for shape in self._tensor_shapes[name]: + tensor_shapes.append(shape) + + # Outfeed ops execute on each replica's first logical core. Note: we must + # constraint it such that we have at most one outfeed dequeue and enqueue + # per replica. + for i in xrange(self._ctx.num_replicas): + host_device, ordinal_id = self._ctx.device_for_replica(i) + with tf.compat.v1.device(host_device): + outfeed_tensors = tpu_ops.outfeed_dequeue_tuple( + dtypes=tensor_dtypes, + shapes=tensor_shapes, + device_ordinal=ordinal_id) + for j, item in enumerate(outfeed_tensors): + dequeue_ops[j].append(item) + + # Deconstruct dequeue ops. + flat_dequeue_ops = [] + for l in dequeue_ops: + flat_dequeue_ops.extend(l) + + dequeue_ops_by_name = {} + pos = 0 + for name in self._names: + dequeue_ops_by_name[name] = dequeue_ops[pos:pos + + len(self._tensors[name])] + pos += len(self._tensors[name]) + + def _call_host_fn(fn, *args, **kw): + context = CatchInvalidHostcallFunctions() + context.Enter() + result = fn(*args, **kw) + context.Exit() + context.ExitResult(result) + return result + + # It is assumed evaluation always happens on single host TPU system. So, + # place all ops on tpu host if possible. + # + # TODO(jhseu): Evaluate whether this is right for summaries. + with tf.compat.v1.device( + self._ctx.tpu_host_placement_function(replica_id=0)): + for name in self._names: + dequeue_ops = dequeue_ops_by_name[name] + for i, item in enumerate(dequeue_ops): + # TODO(xiejw): Make the specification of the outfeed combinaton + # function more explicit and well-documented. We may want to give the + # user the option of concatenating along any axis. + if (self._ctx.config.tpu_config.per_host_input_for_training is + tpu_config.InputPipelineConfig.BROADCAST): + # If the infeed is in BROADCAST mode (each core recieving the same + # input), then we assume that the cores also produce identical + # copies of the same output, and we simply take the output from + # the first core. This mode is used by Mesh-TensorFlow. + with tf.control_dependencies(dequeue_ops[i]): + dequeue_ops[i] = tf.identity(dequeue_ops[i][0]) + else: + if dequeue_ops[i][0].shape.ndims == 0: + raise RuntimeError( + 'All tensors outfed from TPU should preserve batch size ' + 'dimension, but got scalar {}'.format(dequeue_ops[i][0])) + # Assume that the input has been batch-split and that axis 0 of the + # output tensors represents the batch size. Concatenate along + # the axis 0 to re-combine the batch. + dequeue_ops[i] = tf.concat(dequeue_ops[i], axis=0) + + if self._tensor_keys[name] is not None: + # The user-provided eval_metrics[1] is a dict. + dequeue_ops = dict(zip(self._tensor_keys[name], dequeue_ops)) + try: + ret[name] = _call_host_fn(self._host_fns[name], **dequeue_ops) + except TypeError as e: + tf.compat.v1.logging.warn( + 'Exception while calling %s: %s. It is likely the tensors ' + '(%s[1]) do not match the ' + 'function\'s arguments', name, e, name) + raise + else: + ret[name] = _call_host_fn(self._host_fns[name], *dequeue_ops) + + # force all dequeue operations to be run if not consumed by the host calls + ret['__force_dequeue'] = tf.group(*flat_dequeue_ops) + return ret + + +class _OutfeedHostCallHook(tf.compat.v1.train.SessionRunHook): + """Hook to run host calls when use_tpu=False.""" + + def __init__(self, tensors): + self._tensors = tensors + + def begin(self): + # We duplicate this code from the TPUInfeedOutfeedSessionHook rather than + # create a separate hook to guarantee execution order, because summaries + # need to be initialized before the outfeed thread starts. + # TODO(jhseu): Make a wrapper hook instead? + self._init_ops = summary_ops_v2.summary_writer_initializer_op() + # Get all the writer resources from the initializer, so we know what to + # flush. + self._finalize_ops = [] + for op in self._init_ops: + self._finalize_ops.append( + summary_ops_v2.legacy_raw_flush(writer=op.inputs[0])) + + def after_create_session(self, session, coord): + session.run(self._init_ops) + + def before_run(self, run_context): + return tf.compat.v1.train.SessionRunArgs(self._tensors) + + def end(self, session): + session.run(self._finalize_ops) + + +class _NotSaver(object): + """What to pass instead of a saver object if you don't want saving.""" + + def __init__(self, message): + self._message = message + + def save(self, *args, **kwargs): + del args, kwargs + tf.compat.v1.logging.info(self._message) + + +class ExamplesPerSecondHook(tf.compat.v1.train.StepCounterHook): + """Calculate and report global_step/sec and examples/sec during runtime.""" + + def __init__(self, + batch_size, + every_n_steps=100, + every_n_secs=None, + output_dir=None, + summary_writer=None): + self._batch_size = batch_size + super(ExamplesPerSecondHook, self).__init__( + every_n_steps=every_n_steps, + every_n_secs=every_n_secs, + output_dir=output_dir, + summary_writer=summary_writer) + + def _log_and_record(self, elapsed_steps, elapsed_time, global_step): + global_step_per_sec = elapsed_steps / elapsed_time + examples_per_sec = self._batch_size * global_step_per_sec + if self._summary_writer is not None: + global_step_summary = Summary(value=[ + Summary.Value( + tag='global_step/sec', simple_value=global_step_per_sec) + ]) + example_summary = Summary(value=[ + Summary.Value(tag='examples/sec', simple_value=examples_per_sec) + ]) + self._summary_writer.add_summary(global_step_summary, global_step) + self._summary_writer.add_summary(example_summary, global_step) + tf.compat.v1.logging.info('global_step/sec: %g', global_step_per_sec) + tf.compat.v1.logging.info('examples/sec: %g', examples_per_sec) + + +class InstallSignalHandlerHook(tf.compat.v1.train.SessionRunHook): + """Change SIGINT (CTRL^C) handler to force quit the process. + + The default behavior often results in hanging processes. + The original handler is restored after training/evaluation. + """ + + def __init__(self): + self._signal_fn = signal.getsignal(signal.SIGINT) + + def before_run(self, run_context): + signal.signal(signal.SIGINT, signal.SIG_DFL) + + def end(self, session): + signal.signal(signal.SIGINT, self._signal_fn) + + +class ExportSavedModelApiVersion(enum.Enum): + V1 = 1 + V2 = 2 + + +class BatchConfig( + collections.namedtuple('BatchConfig', [ + 'num_batch_threads', 'max_batch_size', 'batch_timeout_micros', + 'allowed_batch_sizes', 'max_enqueued_batches' + ])): + """Class to handle config inputs into the batching function.""" + + def __new__(cls, + num_batch_threads, + max_batch_size, + batch_timeout_micros, + allowed_batch_sizes, + max_enqueued_batches=100): + """Creates an BatchConfig instance. + + Args: + num_batch_threads: Number of scheduling threads for processing batches of + work. Determines the number of batches processed in parallel. + max_batch_size: Batch sizes will never be bigger than this. + batch_timeout_micros: Maximum number of microseconds to wait before + outputting an incomplete batch. + allowed_batch_sizes: Optional list of allowed batch sizes. If left empty, + does nothing. Otherwise, supplies a list of batch sizes, causing the op + to pad batches up to one of those sizes. The entries must increase + monotonically, and the final entry must equal max_batch_size. + max_enqueued_batches: The maximum depth of the batch queue. Defaults to + 100. + + Returns: + An BatchConfig instance. + """ + return super(BatchConfig, cls).__new__( + cls, + num_batch_threads=num_batch_threads, + max_batch_size=max_batch_size, + batch_timeout_micros=batch_timeout_micros, + allowed_batch_sizes=allowed_batch_sizes, + max_enqueued_batches=max_enqueued_batches) + + +@estimator_export(v1=['estimator.tpu.TPUEstimator']) +class TPUEstimator(estimator_lib.Estimator): + """Estimator with TPU support. + + TPUEstimator also supports training on CPU and GPU. You don't need to define + a separate `tf.estimator.Estimator`. + + TPUEstimator handles many of the details of running on TPU devices, such as + replicating inputs and models for each core, and returning to host + periodically to run hooks. + + TPUEstimator transforms a global batch size in params to a per-shard batch + size when calling the `input_fn` and `model_fn`. Users should specify + global batch size in constructor, and then get the batch size for each shard + in `input_fn` and `model_fn` by `params['batch_size']`. + + - For training, `model_fn` gets per-core batch size; `input_fn` may get + per-core or per-host batch size depending on `per_host_input_for_training` + in `TPUConfig` (See docstring for TPUConfig for details). + + - For evaluation and prediction, `model_fn` gets per-core batch size and + `input_fn` get per-host batch size. + + Evaluation + ========== + + `model_fn` should return `TPUEstimatorSpec`, which expects the `eval_metrics` + for TPU evaluation. If eval_on_tpu is False, the evaluation will execute on + CPU or GPU; in this case the following discussion on TPU evaluation does not + apply. + + `TPUEstimatorSpec.eval_metrics` is a tuple of `metric_fn` and `tensors`, where + `tensors` could be a list of any nested structure of `Tensor`s (See + `TPUEstimatorSpec` for details). `metric_fn` takes the `tensors` and returns + a dict from metric string name to the result of calling a metric function, + namely a `(metric_tensor, update_op)` tuple. + + One can set `use_tpu` to `False` for testing. All training, evaluation, and + predict will be executed on CPU. `input_fn` and `model_fn` will receive + `train_batch_size` or `eval_batch_size` unmodified as `params['batch_size']`. + + Current limitations: + -------------------- + + 1. TPU evaluation only works on a single host (one TPU worker) except + BROADCAST mode. + + 2. `input_fn` for evaluation should **NOT** raise an end-of-input exception + (`OutOfRangeError` or `StopIteration`). And all evaluation steps and all + batches should have the same size. + + Example (MNIST): + ---------------- + + ``` + # The metric Fn which runs on CPU. + def metric_fn(labels, logits): + predictions = tf.argmax(logits, 1) + return { + 'accuracy': tf.compat.v1.metrics.precision( + labels=labels, predictions=predictions), + } + + # Your model Fn which runs on TPU (eval_metrics is list in this example) + def model_fn(features, labels, mode, config, params): + ... + logits = ... + + if mode = tf.estimator.ModeKeys.EVAL: + return tpu_estimator.TPUEstimatorSpec( + mode=mode, + loss=loss, + eval_metrics=(metric_fn, [labels, logits])) + + # or specify the eval_metrics tensors as dict. + def model_fn(features, labels, mode, config, params): + ... + final_layer_output = ... + + if mode = tf.estimator.ModeKeys.EVAL: + return tpu_estimator.TPUEstimatorSpec( + mode=mode, + loss=loss, + eval_metrics=(metric_fn, { + 'labels': labels, + 'logits': final_layer_output, + })) + ``` + + Prediction + ========== + + Prediction on TPU is an experimental feature to support large batch inference. + It is not designed for latency-critical system. In addition, due to some + usability issues, for prediction with small dataset, CPU `.predict`, i.e., + creating a new `TPUEstimator` instance with `use_tpu=False`, might be more + convenient. + + Note: In contrast to TPU training/evaluation, the `input_fn` for prediction + *should* raise an end-of-input exception (`OutOfRangeError` or + `StopIteration`), which serves as the stopping signal to `TPUEstimator`. To be + precise, the ops created by `input_fn` produce one batch of the data. + The `predict()` API processes one batch at a time. When reaching the end of + the data source, an end-of-input exception should be raised by one of these + operations. The user usually does not need to do this manually. As long as the + dataset is not repeated forever, the `tf.data` API will raise an end-of-input + exception automatically after the last batch has been produced. + + Note: Estimator.predict returns a Python generator. Please consume all the + data from the generator so that TPUEstimator can shutdown the TPU system + properly for user. + + Current limitations: + -------------------- + 1. TPU prediction only works on a single host (one TPU worker). + + 2. `input_fn` must return a `Dataset` instance rather than `features`. In + fact, .train() and .evaluate() also support Dataset as return value. + + Example (MNIST): + ---------------- + ``` + height = 32 + width = 32 + total_examples = 100 + + def predict_input_fn(params): + batch_size = params['batch_size'] + + images = tf.random.uniform( + [total_examples, height, width, 3], minval=-1, maxval=1) + + dataset = tf.data.Dataset.from_tensor_slices(images) + dataset = dataset.map(lambda images: {'image': images}) + + dataset = dataset.batch(batch_size) + return dataset + + def model_fn(features, labels, params, mode): + # Generate predictions, called 'output', from features['image'] + + if mode == tf.estimator.ModeKeys.PREDICT: + return tf.contrib.tpu.TPUEstimatorSpec( + mode=mode, + predictions={ + 'predictions': output, + 'is_padding': features['is_padding'] + }) + + tpu_est = TPUEstimator( + model_fn=model_fn, + ..., + predict_batch_size=16) + + # Fully consume the generator so that TPUEstimator can shutdown the TPU + # system. + for item in tpu_est.predict(input_fn=input_fn): + # Filter out item if the `is_padding` is 1. + # Process the 'predictions' + ``` + + Exporting + ========= + + `export_saved_model` exports 2 metagraphs, one with `saved_model.SERVING`, and + another with `saved_model.SERVING` and `saved_model.TPU` tags. At serving + time, these tags are used to select the appropriate metagraph to load. + + Before running the graph on TPU, the TPU system needs to be initialized. If + TensorFlow Serving model-server is used, this is done automatically. If not, + please use `session.run(tpu.initialize_system())`. + + There are two versions of the API: 1 or 2. + + In V1, the exported CPU graph is `model_fn` as it is. The exported TPU graph + wraps `tpu.rewrite()` and `TPUPartitionedCallOp` around `model_fn` so + `model_fn` is on TPU by default. To place ops on CPU, + `tpu_replication.outside_compilation(host_call, logits)` can be used. + + Example: + ---------------- + + ``` + def model_fn(features, labels, mode, config, params): + ... + logits = ... + export_outputs = { + 'logits': export_output_lib.PredictOutput( + {'logits': logits}) + } + + def host_call(logits): + class_ids = math_ops.argmax(logits) + classes = string_ops.as_string(class_ids) + export_outputs['classes'] = + export_output_lib.ClassificationOutput(classes=classes) + + tpu_replication.outside_compilation(host_call, logits) + + ... + ``` + + In V2, `export_saved_model()` sets up `params['use_tpu']` flag to let the user + know if the code is exporting to TPU (or not). When `params['use_tpu']` is + `True`, users need to call `tpu.rewrite()`, `TPUPartitionedCallOp` and/or + `batch_function()`. + + TIP: V2 is recommended as it is more flexible (eg: batching, etc). + + @compatibility(TF2) + TPU Estimator manages its own TensorFlow graph and session, so it is not + compatible with TF2 behaviors. We recommend that you migrate to the newer + `tf.distribute.TPUStrategy`. See the + [TPU guide](https://www.tensorflow.org/guide/tpu) for details. + @end_compatibility + """ + + def __init__(self, + model_fn=None, + model_dir=None, + config=None, + params=None, + use_tpu=True, + train_batch_size=None, + eval_batch_size=None, + predict_batch_size=None, + batch_axis=None, + eval_on_tpu=True, + export_to_tpu=True, + export_to_cpu=True, + warm_start_from=None, + embedding_config_spec=None, + export_saved_model_api_version=ExportSavedModelApiVersion.V1): + """Constructs an `TPUEstimator` instance. + + Args: + model_fn: Model function as required by `Estimator` which returns + EstimatorSpec or TPUEstimatorSpec. `training_hooks`, 'evaluation_hooks', + and `prediction_hooks` must not capure any TPU Tensor inside the + model_fn. + model_dir: Directory to save model parameters, graph and etc. This can + also be used to load checkpoints from the directory into a estimator to + continue training a previously saved model. If `None`, the model_dir in + `config` will be used if set. If both are set, they must be same. If + both are `None`, a temporary directory will be used. + config: An `tpu_config.RunConfig` configuration object. Cannot be `None`. + params: An optional `dict` of hyper parameters that will be passed into + `input_fn` and `model_fn`. Keys are names of parameters, values are + basic python types. There are reserved keys for `TPUEstimator`, + including 'batch_size'. + use_tpu: A bool indicating whether TPU support is enabled. Currently, - + TPU training and evaluation respect this bit, but eval_on_tpu can + override execution of eval. See below. + train_batch_size: An int representing the global training batch size. + TPUEstimator transforms this global batch size to a per-shard batch + size, as params['batch_size'], when calling `input_fn` and `model_fn`. + Cannot be `None` if `use_tpu` is `True`. Must be divisible by total + number of replicas. + eval_batch_size: An int representing evaluation batch size. Must be + divisible by total number of replicas. + predict_batch_size: An int representing the prediction batch size. Must be + divisible by total number of replicas. + batch_axis: A python tuple of int values describing how each tensor + produced by the Estimator `input_fn` should be split across the TPU + compute shards. For example, if your input_fn produced (images, labels) + where the images tensor is in `HWCN` format, your shard dimensions would + be [3, 0], where 3 corresponds to the `N` dimension of your images + Tensor, and 0 corresponds to the dimension along which to split the + labels to match up with the corresponding images. If None is supplied, + and per_host_input_for_training is True, batches will be sharded based + on the major dimension. If tpu_config.per_host_input_for_training is + False or `PER_HOST_V2`, batch_axis is ignored. + eval_on_tpu: If False, evaluation runs on CPU or GPU. In this case, the + model_fn must return `EstimatorSpec` when called with `mode` as `EVAL`. + export_to_tpu: If True, `export_saved_model()` exports a metagraph for + serving on TPU. Note that unsupported export modes such as EVAL will be + ignored. For those modes, only a CPU model will be exported. Currently, + export_to_tpu only supports PREDICT. + export_to_cpu: If True, `export_saved_model()` exports a metagraph for + serving on CPU. + warm_start_from: Optional string filepath to a checkpoint or SavedModel to + warm-start from, or a `tf.estimator.WarmStartSettings` object to fully + configure warm-starting. If the string filepath is provided instead of + a `WarmStartSettings`, then all variables are warm-started, and it is + assumed that vocabularies and Tensor names are unchanged. + embedding_config_spec: Optional EmbeddingConfigSpec instance to support + using TPU embedding. + export_saved_model_api_version: an integer: 1 or 2. 1 corresponds to V1, + 2 corresponds to V2. (Defaults to V1). With + V1, `export_saved_model()` adds rewrite() and TPUPartitionedCallOp() for + user; while in v2, user is expected to add rewrite(), + TPUPartitionedCallOp() etc in their model_fn. + + Raises: + ValueError: `params` has reserved keys already. + """ + if config is None or not isinstance(config, tpu_config.RunConfig): + raise ValueError( + '`config` must be provided with type `tpu_config.RunConfig`') + + if params is not None and any(k in params for k in _RESERVED_PARAMS_KEYS): + raise ValueError('{} are reserved keys but existed in params {}.'.format( + _RESERVED_PARAMS_KEYS, params)) + + if use_tpu: + # Perform some very basic validations. More validations will be found in + # _InternalTPUContext. + if train_batch_size is None: + raise ValueError('`train_batch_size` cannot be `None`') + util_lib.check_positive_integer(train_batch_size, 'train_batch_size') + + if (config.tpu_config.per_host_input_for_training is + tpu_config.InputPipelineConfig.PER_SHARD_V1 and + config.tpu_config.num_cores_per_replica): + raise ValueError( + 'Model parallelism only supports per host input for training. ' + 'Please adjust TPURunconfig.per_host_input_for_training.') + + if eval_batch_size is not None: + util_lib.check_positive_integer(eval_batch_size, 'eval_batch_size') + + if predict_batch_size is not None: + util_lib.check_positive_integer(predict_batch_size, + 'predict_batch_size') + + if embedding_config_spec: + if (config.tpu_config.per_host_input_for_training not in ( + tpu_config.InputPipelineConfig.PER_HOST_V1, + tpu_config.InputPipelineConfig.PER_HOST_V2)): + raise ValueError('Only PER_HOST_V1 and PER_HOST_V2 is supported when ' + 'using TPU Embedding; got {}.'.format( + config.tpu_config.per_host_input_for_training)) + self._embedding_from_feature_columns = ( + embedding_config_spec.feature_columns is not None) + + if (not (use_tpu and eval_on_tpu) and embedding_config_spec and + embedding_config_spec.partition_strategy == 'mod'): + raise ValueError('Mod sharding of embedding tables not supported on ' + 'CPU.') + _tpu_estimator_gauge.get_cell().set(True) + # Verifies the model_fn signature according to Estimator framework. + estimator_lib._verify_model_fn_args(model_fn, params) # pylint: disable=protected-access + # We cannot store config and params in this constructor as parent + # constructor might change them, such as assigning a temp dir for + # config.model_dir. + model_function = self._augment_model_fn(model_fn, batch_axis) + + # Overwrite log_step_count_steps to disable TensorLoggingHook and + # StepCounterHook from being created in Estimator. TPUEstimator already + # added equivalent hooks in _augment_model_fn above. + self._log_every_n_steps = config.log_step_count_steps + config = config.replace(log_step_count_steps=None) + + # Passing non-None params as wrapped model_fn has it. + params = params or {} + super(TPUEstimator, self).__init__( + model_fn=model_function, + model_dir=model_dir, + config=config, + params=params, + warm_start_from=warm_start_from) + self._iterations_per_training_loop = util_lib.parse_iterations_per_loop( + self._config.tpu_config.iterations_per_loop) + # In absence of an explicit `log_every_n_secs` config, if the + # `iterations_per_loop` value is specified as time in seconds, enable + # logging every n secs based on the `iterations_per_loop` value. A trade-off + # avoiding API change on the current release. + # TODO(henrytan): add `log_every_n_secs` to RunConfig. + if self._iterations_per_training_loop.unit == 'seconds': + self._log_every_n_secs = self._iterations_per_training_loop.value + self._log_every_n_steps = None + elif self._iterations_per_training_loop.unit == 'count': + if self._log_every_n_steps is not None: + # Each session.run() lasts for iterations_per_loop. We can't log + # in-between a session.run(), and we can only log after the + # `iterations_per_loop` steps, so we can only approximate. If a user + # requests to log every N steps, we actually want to roughly log every + # N / `iterations_per_loop` steps to match the original intention. + self._log_every_n_steps = ( + int( + math.ceil( + float(self._log_every_n_steps) / + self._iterations_per_training_loop.value))) + self._log_every_n_secs = None + else: + assert False, ('Invalid TPUConfig `iterations_per_loop` value. ' + 'Indicates a bug in `iterations_per_loop` ' + 'parsing.') + + # All properties passed to _InternalTPUContext are immutable. + # pylint: disable=protected-access + self._ctx = tpu_context._get_tpu_context(self._config, train_batch_size, + eval_batch_size, + predict_batch_size, use_tpu, + eval_on_tpu, embedding_config_spec) + + self._export_to_cpu = export_to_cpu + self._export_to_tpu = export_to_tpu + + if not (isinstance(export_saved_model_api_version, + ExportSavedModelApiVersion) + or export_saved_model_api_version == 1 + or export_saved_model_api_version == 2): + raise ValueError('export_saved_model_api_version should be 1 or 2; ' + 'got {}.'.format( + export_saved_model_api_version)) + self._export_saved_model_api_version = export_saved_model_api_version + self._is_input_fn_invoked = None + + self._rendezvous = {} + + def _add_meta_graph_for_mode(self, + builder, + input_receiver_fn_map, + checkpoint_path, + save_variables=True, + mode=model_fn_lib.ModeKeys.PREDICT, + export_tags=None, + check_variables=True, + strip_default_attrs=True): + if self._export_to_tpu and mode != model_fn_lib.ModeKeys.PREDICT: + tf.compat.v1.logging.warn( + 'TPUEstimator only handles mode PREDICT for exporting ' + 'when `export_to_tpu` is `True`; Mode {} will be ignored ' + 'for TPU.'.format(mode)) + + if not self._export_to_cpu and not self._export_to_tpu: + raise ValueError('One of export_to_cpu and export_to_tpu must be true.') + + if self._export_to_cpu: + (super(TPUEstimator, self)._add_meta_graph_for_mode( + builder, + input_receiver_fn_map, + checkpoint_path, + save_variables, + mode=mode, + export_tags=export_tags, + check_variables=check_variables, + strip_default_attrs=strip_default_attrs)) + + if self._export_to_tpu and mode == model_fn_lib.ModeKeys.PREDICT: + input_receiver_fn_map = { + _INFERENCE_ON_TPU_MODE: input_receiver_fn_map[mode] + } + export_tags = [tf.saved_model.SERVING, tf.saved_model.TPU] + mode = _INFERENCE_ON_TPU_MODE + + # See b/110052256 for why `check_variables` is `False`. + if not self._export_to_cpu: + check_variables = save_variables = True + else: + check_variables = save_variables = False + (super(TPUEstimator, self)._add_meta_graph_for_mode( + builder, + input_receiver_fn_map, + checkpoint_path, + save_variables=save_variables, + mode=mode, + export_tags=export_tags, + check_variables=check_variables, + strip_default_attrs=strip_default_attrs)) + + def _call_model_fn(self, features, labels, mode, config): + if mode == _INFERENCE_ON_TPU_MODE: + context = tpu._TPUInferenceContext('tpu_inference', check_ops=False) + try: + context.Enter() + if ( + (self._export_saved_model_api_version == + ExportSavedModelApiVersion.V1) + or self._export_saved_model_api_version == 1): + result = self._call_model_fn_for_inference(features, labels, mode, + config) + else: + result = super(TPUEstimator, + self)._call_model_fn(features, labels, mode, config) + finally: + context.Exit() + return result + else: + return super(TPUEstimator, self)._call_model_fn(features, labels, mode, + config) + + def _call_model_fn_for_inference(self, features, labels, mode, config): + """Wraps `_call_model_fn` for `export_saved_model`.""" + if mode != _INFERENCE_ON_TPU_MODE: + raise ValueError('mode must be {}; ' + 'got {}.'.format(_INFERENCE_ON_TPU_MODE, mode)) + return model_fn_inference_on_tpu( + self._model_fn, + features, + labels, + config, + self._params, + batch_config=None) + + def _create_global_step(self, graph): + """Creates a global step suitable for TPUs. + + Args: + graph: The graph in which to create the global step. + + Returns: + A global step `Tensor`. + + Raises: + ValueError: if the global step tensor is already defined. + """ + return _create_global_step(graph) + + def _convert_train_steps_to_hooks(self, steps, max_steps): + with self._ctx.with_mode(model_fn_lib.ModeKeys.TRAIN) as ctx: + if ctx.is_running_on_cpu(): + return super(TPUEstimator, + self)._convert_train_steps_to_hooks(steps, max_steps) + + # On TPU. + if steps is None and max_steps is None: + raise ValueError( + 'For TPU training, one of `steps` or `max_steps` must be set. ' + 'Cannot be both `None`.') + + # Estimator.train has explicit positiveness check. + if steps is not None: + util_lib.check_positive_integer(steps, 'Train steps') + if max_steps is not None: + util_lib.check_positive_integer(max_steps, 'Train max_steps') + + return [ + _TPUStopAtStepHook(self._iterations_per_training_loop, steps, max_steps) + ] + + def _convert_eval_steps_to_hooks(self, steps): + with self._ctx.with_mode(model_fn_lib.ModeKeys.EVAL) as ctx: + if ctx.is_running_on_cpu(): + return super(TPUEstimator, self)._convert_eval_steps_to_hooks(steps) + + if steps is None: + raise ValueError('Evaluate `steps` must be set on TPU. Cannot be `None`.') + + util_lib.check_positive_integer(steps, 'Eval steps') + + return [ + evaluation._StopAfterNEvalsHook( # pylint: disable=protected-access + num_evals=steps), + _SetEvalIterationsHook(steps) + ] + + def _call_input_fn(self, input_fn, mode, input_context=None): + """Calls the input function. + + Args: + input_fn: The input function. + mode: ModeKeys + input_context: Optional instance of `tf.distribute.InputContext`. + + Returns: + In TPU mode, returns an input_fn to be called later in model_fn. + Otherwise, calls the input_fn and returns either fatures or + (features, labels). + + Raises: + ValueError: if input_fn takes invalid arguments or does not have `params`. + """ + input_fn_args = function_utils.fn_args(input_fn) + config = self.config # a deep copy. + kwargs = {} + if 'params' in input_fn_args: + kwargs['params'] = self.params # a deep copy. + else: + raise ValueError('input_fn ({}) does not include params argument, ' + 'required by TPUEstimator to pass batch size as ' + 'params["batch_size"]'.format(input_fn)) + if 'config' in input_fn_args: + kwargs['config'] = config + + if 'mode' in input_fn_args: + kwargs['mode'] = mode + + if 'input_context' in input_fn_args: + kwargs['input_context'] = input_context + + # Records the fact input_fn has been invoked. + self._is_input_fn_invoked = True + + with self._ctx.with_mode(mode) as ctx: + if (ctx.is_running_on_cpu() and + ctx.is_input_slice_broadcast_to_all_cores()): + raise ValueError('Invalid TPUConfig `eval_training_input_configuration`' + ' value. SLICED mode only works on use_tpu = True.') + # Setting the batch size in params first. This helps user to have same + # input_fn for use_tpu=True/False. + batch_size_for_input_fn = ctx.batch_size_for_input_fn + if batch_size_for_input_fn is not None: + _add_item_to_params(kwargs['params'], _BATCH_SIZE_KEY, + batch_size_for_input_fn) + + # For export_saved_model, input_fn is never passed to Estimator. So, + # `is_export_mode` must be False. + if ctx.is_running_on_cpu(is_export_mode=False): + with tf.compat.v1.device('/device:CPU:0'): + return input_fn(**kwargs) + + # For TPU computation, input_fn should be invoked in a tf.while_loop for + # performance. While constructing the tf.while_loop, the structure of + # inputs returned by the `input_fn` needs to be recorded. The structure + # includes whether features or labels is dict or single Tensor, dict keys, + # tensor shapes, and dtypes. The recorded structure is used to create the + # infeed dequeue ops, which must be wrapped and passed as a Fn, called + # inside the TPU computation, as the TPU computation is wrapped inside a + # tf.while_loop also. So, we either pass input_fn to model_fn or pass + # dequeue_fn to model_fn. Here, `input_fn` is passed directly as + # `features` in `model_fn` signature. + def _input_fn(ctx): + _add_item_to_params(kwargs['params'], _CTX_KEY, ctx) + return input_fn(**kwargs) + + return _input_fn + + def _validate_features_in_predict_input(self, result): + """Skip the validation. + + For TPUEstimator, we do not need to check the result type. `_InputPipeline` + has stronger check. Parent class's check generates confusing warning msg. + + Args: + result: `features` returned by input_fn. + """ + pass + + def train(self, + input_fn, + hooks=None, + steps=None, + max_steps=None, + saving_listeners=None): + rendezvous = error_handling.ErrorRendezvous(num_sources=3) + self._rendezvous[model_fn_lib.ModeKeys.TRAIN] = rendezvous + try: + return super(TPUEstimator, self).train( + input_fn=input_fn, + hooks=hooks, + steps=steps, + max_steps=max_steps, + saving_listeners=saving_listeners) + except Exception: # pylint: disable=broad-except + rendezvous.record_error('training_loop', sys.exc_info()) + finally: + rendezvous.record_done('training_loop') + rendezvous.raise_errors() + + def evaluate(self, + input_fn, + steps=None, + hooks=None, + checkpoint_path=None, + name=None): + rendezvous = error_handling.ErrorRendezvous(num_sources=3) + self._rendezvous[model_fn_lib.ModeKeys.EVAL] = rendezvous + try: + return super(TPUEstimator, self).evaluate( + input_fn, + steps=steps, + hooks=hooks, + checkpoint_path=checkpoint_path, + name=name) + except Exception: # pylint: disable=broad-except + rendezvous.record_error('evaluation_loop', sys.exc_info()) + finally: + rendezvous.record_done('evaluation_loop') + rendezvous.raise_errors() + + def predict(self, + input_fn, + predict_keys=None, + hooks=None, + checkpoint_path=None, + yield_single_examples=True): + rendezvous = error_handling.ErrorRendezvous(num_sources=3) + self._rendezvous[model_fn_lib.ModeKeys.PREDICT] = rendezvous + try: + for result in super(TPUEstimator, self).predict( + input_fn=input_fn, + predict_keys=predict_keys, + hooks=hooks, + checkpoint_path=checkpoint_path, + yield_single_examples=yield_single_examples): + yield result + except Exception: # pylint: disable=broad-except + rendezvous.record_error('prediction_loop', sys.exc_info()) + finally: + rendezvous.record_done('prediction_loop') + rendezvous.raise_errors() + + rendezvous.record_done('prediction_loop') + rendezvous.raise_errors() + + def _augment_model_fn(self, model_fn, batch_axis): + """Returns a new model_fn, which wraps the TPU support.""" + + def _model_fn(features, labels, mode, config, params): + """A Estimator `model_fn` for TPUEstimator.""" + + # `input_fn` is called in `train()`, `evaluate()`, and `predict()`, + # but not in `export_saved_model()`. + if self._is_input_fn_invoked: + is_export_mode = False + else: + is_export_mode = True + + # Clear the bit. + self._is_input_fn_invoked = None + + if is_export_mode: + if mode == _INFERENCE_ON_TPU_MODE: + _add_item_to_params(params, _USE_TPU_KEY, True) + mode = model_fn_lib.ModeKeys.PREDICT + else: + _add_item_to_params(params, _USE_TPU_KEY, False) + + with self._ctx.with_mode(mode) as ctx: + model_fn_wrapper = _ModelFnWrapper(model_fn, config, params, ctx) + + # examples_hook is added to training_hooks for both CPU and TPU + # execution. + if (self._log_every_n_steps is not None or + self._log_every_n_secs is not None): + examples_hook = ExamplesPerSecondHook( + ctx.global_batch_size, + # pylint:disable=g-long-ternary + output_dir=(self.model_dir + if not config or config.save_summary_steps else None), + # pylint:enable=g-long-ternary + every_n_steps=self._log_every_n_steps, + every_n_secs=self._log_every_n_secs) + + if ctx.is_running_on_cpu(is_export_mode=is_export_mode): + tf.compat.v1.logging.info('Running %s on CPU/GPU', mode) + estimator_spec = model_fn_wrapper.call_without_tpu( + features, labels, is_export_mode=is_export_mode) + if (self._log_every_n_steps is not None or + self._log_every_n_secs is not None): + estimator_spec = estimator_spec._replace( + training_hooks=estimator_spec.training_hooks + (examples_hook,)) + return estimator_spec + + assert labels is None, '`labels` passed to `model_fn` must be `None`.' + # TPUEstimator._call_input_fn passes `input_fn` as features to here. + assert callable(features), '`input_fn` is not callable.' + input_fn = features + + tpu_init_ops = [] + if ctx.embedding_config and mode == model_fn_lib.ModeKeys.TRAIN: + dummy_table_variables, dummy_table_variables_init = ( + tpu_embedding_gradient.create_dummy_table_variables( + ctx.embedding_config.tpu_embedding)) + ctx.embedding_config.dummy_table_variables = dummy_table_variables + tpu_init_ops.append(dummy_table_variables_init) + + input_holders = _InputPipeline(input_fn, batch_axis, ctx) + enqueue_ops, dequeue_fn, input_hooks, run_infeed_loop_on_coordinator = ( + input_holders.generate_infeed_enqueue_ops_and_dequeue_fn()) + + graph = tf.compat.v1.get_default_graph() + for enqueue_op in enqueue_ops: + if isinstance(enqueue_op, list): + graph.get_collection_ref(_TPU_ENQUEUE_OPS).extend(enqueue_op) + else: + graph.add_to_collection(_TPU_ENQUEUE_OPS, enqueue_op) + + if mode == model_fn_lib.ModeKeys.TRAIN: + compile_op, loss, host_call, scaffold_fn, training_hooks = ( + _train_on_tpu_system(ctx, model_fn_wrapper, dequeue_fn)) + has_saver_hook = training_hooks and any( + isinstance(hook, tf.compat.v1.train.CheckpointSaverHook) + for hook in training_hooks) + if ctx.embedding_config: + g = tf.compat.v1.get_default_graph() + table_to_config_dict = ( + ctx.embedding_config.tpu_embedding.table_to_config_dict) + optimization_parameters = ( + ctx.embedding_config.tpu_embedding.optimization_parameters) + if self._embedding_from_feature_columns: + embedding_variable_name_by_table, slot_variable_names_by_table = ( + _tpu_estimator_embedding.get_full_variable_names( + g, table_to_config_dict, optimization_parameters)) + else: + embedding_variable_name_by_table = None + slot_variable_names_by_table = None + embedding_variables_and_ops = ( + ctx.embedding_config.tpu_embedding.create_variables_and_ops( + embedding_variable_name_by_table, + slot_variable_names_by_table)) + tpu_init_ops.extend(embedding_variables_and_ops.load_ops()) + # scaffold_fn must be called after variables for TPU embedding has + # been created on CPU, as user might reinitialize those from some + # checkpoint within scaffold_fn. + scaffold = _get_scaffold(scaffold_fn) + + host_ops = host_call.create_tpu_hostcall() + + shutdown_hooks = [] + shutdown_mode = os.environ.get('TF_TPU_GRACEFUL_SHUTDOWN_MODE', + 'reset_computation') + if shutdown_mode: + if shutdown_mode == 'shutdown_worker': + finalizer_hooks = [ + session_support.ShutdownLameWorkers(), + ] + elif shutdown_mode == 'shutdown_all_workers': + finalizer_hooks = [ + session_support.ShutdownAllWorkers(), + ] + elif shutdown_mode == 'reset_computation': + finalizer_hooks = [ + session_support.ResetComputation(), + ] + elif not shutdown_mode: + finalizer_hooks = [] + else: + raise ValueError('Unknown TF_TPU_GRACEFUL_SHUTDOWN_MODE "%s"' % + shutdown_mode) + + if finalizer_hooks: + if has_saver_hook: + saver = _NotSaver( + 'No save on shutdown when there are user-defined ' + 'CheckpointSaverHooks') + else: + saver = None # Yes automatic save on shutdown. + shutdown_hooks.append( + session_support.GracefulShutdownHook( + checkpoint_prefix=self.model_dir + '/model.ckpt', + on_shutdown_hooks=finalizer_hooks, + saver=saver)) + + with tf.control_dependencies([loss]): + global_step = tf.identity(tf.compat.v1.train.get_global_step()) + hooks = input_hooks + shutdown_hooks + + if ctx.feed_hook is not None: + tf.compat.v1.logging.info( + 'Use user implemented tpu infeed outfeed session hook class.') + infeed_outfeed_session_hook_class = ctx.feed_hook + else: + infeed_outfeed_session_hook_class = TPUInfeedOutfeedSessionHook + + hooks.extend([ + infeed_outfeed_session_hook_class( + ctx, + enqueue_ops, + host_ops, + tpu_compile_op=compile_op, + run_infeed_loop_on_coordinator=( + run_infeed_loop_on_coordinator), + rendezvous=self._rendezvous[mode], + master=self._config.master, + session_config=self._session_config, + tpu_init_ops=tpu_init_ops, + outfeed_every_n_steps=self._config.tpu_config + .experimental_host_call_every_n_steps), + InstallSignalHandlerHook() + ]) + if _check_add_preemption_hook(self._config.cluster): + hooks.extend( + [preempted_hook.CloudTPUPreemptedHook(self._config.cluster)]) + if (self._log_every_n_steps is not None or + self._log_every_n_secs is not None): + if self._iterations_per_training_loop.unit == 'count': + examples_hook._set_steps_per_run( # pylint: disable=protected-access + self._iterations_per_training_loop.value) + hooks.append( + tf.compat.v1.train.LoggingTensorHook( + { + 'loss': tf.identity(loss), + 'step': global_step, + }, + every_n_iter=self._log_every_n_steps, + every_n_secs=self._log_every_n_secs)) + hooks.append(examples_hook) + + if training_hooks: + hooks.extend(training_hooks) + + chief_hooks = [] + if (not has_saver_hook and + (self._config.save_checkpoints_secs or + self._config.save_checkpoints_steps)): + checkpoint_hook = tf.compat.v1.train.CheckpointSaverHook( + self.model_dir, + save_secs=self._config.save_checkpoints_secs, + save_steps=self._config.save_checkpoints_steps, + scaffold=scaffold, + save_graph_def=self._config.checkpoint_save_graph_def) + if self._iterations_per_training_loop.unit == 'count': + checkpoint_hook._set_steps_per_run( # pylint: disable=protected-access + self._iterations_per_training_loop.value) + chief_hooks.append(checkpoint_hook) + else: + tf.compat.v1.logging.info('Bypassing TPUEstimator hook') + + tf.compat.v1.summary.scalar(model_fn_lib.LOSS_METRIC_KEY, loss) + with tf.control_dependencies([loss]): + update_ops = _sync_variables_ops(ctx) + if ctx.embedding_config: + update_ops.extend(embedding_variables_and_ops.retrieve_ops()) + + # Validate the TPU training graph to catch basic errors + _validate_tpu_training_graph(ctx) + + train_op = tf.group(*update_ops) + graph.add_to_collection(_TPU_TRAIN_OP, train_op) + + return model_fn_lib.EstimatorSpec( + mode, + loss=loss, + training_chief_hooks=chief_hooks, + training_hooks=hooks, + train_op=train_op, + scaffold=scaffold) + + if mode == model_fn_lib.ModeKeys.EVAL: + compile_op, total_loss, host_calls, scaffold_fn, eval_hooks = ( + _eval_on_tpu_system(ctx, model_fn_wrapper, dequeue_fn)) + if ctx.embedding_config: + g = tf.compat.v1.get_default_graph() + table_to_config_dict = ( + ctx.embedding_config.tpu_embedding.table_to_config_dict) + if self._embedding_from_feature_columns: + embedding_variable_name_by_table, _ = ( + _tpu_estimator_embedding.get_full_variable_names( + g, table_to_config_dict)) + else: + embedding_variable_name_by_table = None + embedding_variables_and_ops = ( + ctx.embedding_config.tpu_embedding.create_variables_and_ops( + embedding_variable_name_by_table)) + tpu_init_ops.extend(embedding_variables_and_ops.load_ops()) + # scaffold_fn must be called after variables for TPU embedding has + # been created on CPU, as user might reinitialize those from some + # checkpoint within scaffold_fn. + scaffold = _get_scaffold(scaffold_fn) + iterations_per_loop_var = _create_or_get_iterations_per_loop() + mean_loss = tf.compat.v1.div( + total_loss, + tf.cast(iterations_per_loop_var, dtype=total_loss.dtype)) + + with tf.control_dependencies([mean_loss]): + # After TPU evaluation computation is done (the mean_loss tensor), + # reads all variables back from TPU and updates the eval step + # counter properly + internal_ops_to_run = _sync_variables_ops(ctx) + internal_ops_to_run.append( + _increase_eval_step_op(iterations_per_loop_var)) + + host_call_ret = host_calls.create_tpu_hostcall() + eval_metric_ops = {} + eval_update_ops = [] + + eval_metrics = host_call_ret.get('eval_metrics', {}) + if eval_metrics: + # Creates a dummy metric update_op for all metrics. Estimator + # expects all metrics in `eval_metric_ops` have update_op and calls + # them one by one. The real metric update_ops are invoked in a + # separated thread. So, here give Estimator the dummy op for all + # metrics. + with tf.control_dependencies(internal_ops_to_run): + dummy_update_op = tf.no_op() + + for k, v in eval_metrics.items(): + eval_metric_ops[k] = (v[0], dummy_update_op) + eval_update_ops.append(v[1]) + else: + # If no eval metrics are passed, create an identity node for the + # loss and add `internal_ops_to_run` to its dependencies. So + # `internal_ops_to_run` can be executed. + with tf.control_dependencies(internal_ops_to_run): + mean_loss = tf.identity(mean_loss) + + if 'host_call' not in host_call_ret: + host_ops = [] + else: + host_ops = host_call_ret['host_call'] + hooks = [ + TPUInfeedOutfeedSessionHook( + ctx, + enqueue_ops, + eval_update_ops + host_ops, + tpu_compile_op=compile_op, + run_infeed_loop_on_coordinator=( + run_infeed_loop_on_coordinator), + rendezvous=self._rendezvous[mode], + master=self._config.evaluation_master, + session_config=self._session_config, + tpu_init_ops=tpu_init_ops) + ] + input_hooks + + if _check_add_preemption_hook(self._config.cluster): + hooks.extend( + [preempted_hook.CloudTPUPreemptedHook(self._config.cluster)]) + + if eval_hooks: + hooks.extend(eval_hooks) + + return model_fn_lib.EstimatorSpec( + mode, + loss=mean_loss, + evaluation_hooks=hooks, + eval_metric_ops=eval_metric_ops, + scaffold=scaffold) + + # Predict + assert mode == model_fn_lib.ModeKeys.PREDICT + + (compile_op, dummy_predict_op, host_calls, scaffold_fn, + prediction_hooks) = _predict_on_tpu_system(ctx, model_fn_wrapper, + dequeue_fn) + scaffold = _get_scaffold(scaffold_fn) + with tf.control_dependencies([dummy_predict_op]): + internal_ops_to_run = _sync_variables_ops(ctx) + with tf.control_dependencies(internal_ops_to_run): + dummy_predict_op = tf.no_op() + + # In train and evaluation, the main TPU program is passed to monitored + # training session to run. Infeed enqueue and outfeed dequeue are + # executed in side threads. This is not the configuration for + # prediction mode. + # + # For prediction, the Estimator executes the EstimatorSpec.predictions + # directly and yield the element (via generator) to call site. So, the + # outfeed based prediction must be passed to MonitoredSession directly. + # Other parts of the TPU execution are organized as follows. + # + # 1. All outfeed based Tensors must be grouped with predictions Tensors + # to form a single invocation. This avoid the issue we might trigger + # multiple outfeeds incorrectly. To achieve this, `host_call` is + # placed in control_dependencies of `stopping_signals`, and + # `stopping_signals` is passed into _StoppingPredictHook, which sets + # the `stopping_signals` as SessionRunArgs. MonitoredSession merges + # all SessionRunArgs with the fetch in session.run together. + # + # 2. The TPU program (dummy_predict_op) and enqueue_ops (infeed Enqueue) + # are grouped together. They will be launched once and only once in + # side threads and they quit naturally according to the SAME stopping + # condition. + enqueue_ops.append(dummy_predict_op) + + host_call_ret = host_calls.create_tpu_hostcall() + if 'host_call' not in host_call_ret: + host_ops = [] + else: + host_ops = host_call_ret['host_call'] + + predictions = host_call_ret['predictions'] + _verify_cross_hosts_transfer_size( + predictions, + message=( + 'The estimated size for TPUEstimatorSpec.predictions is too ' + 'large.')) + signals = host_call_ret['signals'] + + with tf.control_dependencies(host_ops): + host_ops = [] # Empty, we do do not need it anymore. + scalar_stopping_signal = _StopSignals.as_scalar_stopping_signal( + signals) + predictions = _PaddingSignals.slice_tensor_or_dict( + predictions, signals) + + hooks = [ + _StoppingPredictHook(scalar_stopping_signal), + TPUInfeedOutfeedSessionHookForPrediction( + ctx, + enqueue_ops, + host_ops, + rendezvous=self._rendezvous[mode], + tpu_compile_op=compile_op, + master=self._config.master, + session_config=self._session_config), + ] + input_hooks + + if prediction_hooks: + hooks.extend(prediction_hooks) + + return model_fn_lib.EstimatorSpec( + mode, + prediction_hooks=hooks, + predictions=predictions, + scaffold=scaffold) + + return _model_fn + + +def _check_add_preemption_hook(cluster): + return (tpu_cluster_resolver.is_running_in_gce() and cluster and isinstance( + cluster, tf.distribute.cluster_resolver.TPUClusterResolver) and + cluster._cloud_tpu_client.api_available()) + + +def _export_output_to_tensors(export_output): + """Get a list of `Tensors` used in `export_output`. + + Args: + export_output: an `ExportOutput` object such as `ClassificationOutput`, + `RegressionOutput`, or `PredictOutput`. + + Returns: + a list of tensors used in export_output. + + Raises: + ValueError: if `export_output` is not one of `ClassificationOutput`, + `RegressionOutput`, or `PredictOutput`. + """ + if isinstance(export_output, export_output_lib.ClassificationOutput): + return [export_output.scores, export_output.classes] + elif isinstance(export_output, export_output_lib.RegressionOutput): + return [export_output.value] + elif isinstance(export_output, export_output_lib.PredictOutput): + return list(export_output.outputs.values()) + else: + raise ValueError( + '`export_output` must be have type `ClassificationOutput`, ' + '`RegressionOutput`, or `PredictOutput`; got {}.'.format(export_output)) + + +def _clone_export_output_with_tensors(export_output, tensors): + """Clones `export_output` but with new `tensors`. + + Args: + export_output: an `ExportOutput` object such as `ClassificationOutput`, + `RegressionOutput`, or `PredictOutput`. + tensors: a list of `Tensors` used to construct a new `export_output`. + + Returns: + A dict similar to `export_output` but with `tensors`. + + Raises: + ValueError: if `export_output` is not one of `ClassificationOutput`, + `RegressionOutput`, or `PredictOutput`. + """ + if isinstance(export_output, export_output_lib.ClassificationOutput): + if len(tensors) != 2: + raise ValueError('tensors must be of length 2; ' + 'got {}.'.format(len(tensors))) + return export_output_lib.ClassificationOutput(*tensors) + elif isinstance(export_output, export_output_lib.RegressionOutput): + if len(tensors) != 1: + raise ValueError('tensors must be of length 1; ' + 'got {}'.format(len(tensors))) + return export_output_lib.RegressionOutput(*tensors) + elif isinstance(export_output, export_output_lib.PredictOutput): + return export_output_lib.PredictOutput( + dict(zip(export_output.outputs.keys(), tensors))) + else: + raise ValueError( + '`export_output` must be have type `ClassificationOutput`, ' + '`RegressionOutput`, or `PredictOutput`; got {}.'.format(export_output)) + + +def _eval_on_tpu_system(ctx, model_fn_wrapper, dequeue_fn): + """Executes `model_fn_wrapper` multiple times on all TPU shards.""" + iterations_per_loop_var = _create_or_get_iterations_per_loop() + + (single_tpu_eval_step, host_calls, captured_scaffold_fn, captured_eval_hooks + ) = model_fn_wrapper.convert_to_single_tpu_eval_step(dequeue_fn) + + @tpu_function.on_device_training_loop + def multi_tpu_eval_steps_on_single_shard(replica_id): + # `tpu.split_compile_and_shard()` splits and passes input for each + # replica as an array. As so, correctly reshape the input to be a + # scalar. + replica_id = tf.reshape(replica_id, []) + with tpu_context._TPUEstimatorReplicaContext(replica_id): # pylint: disable=protected-access + return training_loop.repeat(iterations_per_loop_var, single_tpu_eval_step, + [_ZERO_LOSS]) + + # Add input that represents id for each replica in sync so that + # _TPUEstimatorReplicaContext can be correctly entered during + # replicated computation. + replica_id_inputs = [] + replica_id_inputs.append([tf.constant(i) for i in range(ctx.num_replicas)]) + + ( + compile_op, + loss, + ) = tpu.split_compile_and_shard( + multi_tpu_eval_steps_on_single_shard, + inputs=replica_id_inputs, + num_shards=ctx.num_replicas, + outputs_from_all_shards=False, + device_assignment=ctx.device_assignment) + + loss = loss[0] + return (compile_op, loss, host_calls, captured_scaffold_fn, + captured_eval_hooks.get()) + + +def _train_on_tpu_system(ctx, model_fn_wrapper, dequeue_fn): + """Executes `model_fn_wrapper` multiple times on all TPU shards.""" + iterations_per_loop_var = _create_or_get_iterations_per_loop() + + (single_tpu_train_step, host_call, captured_scaffold_fn, + captured_training_hooks) = ( + model_fn_wrapper.convert_to_single_tpu_train_step(dequeue_fn)) + + @tpu_function.on_device_training_loop + def multi_tpu_train_steps_on_single_shard(replica_id): + # `tpu.split_compile_and_shard()` splits and passes input for each + # replica as an array. As so, correctly reshape the input to be a + # scalar. + replica_id = tf.reshape(replica_id, []) + with tpu_context._TPUEstimatorReplicaContext(replica_id): # pylint: disable=protected-access + outputs = training_loop.while_loop( + lambda i, loss: i < iterations_per_loop_var, + lambda i, loss: [i + 1, single_tpu_train_step(i)], + inputs=[0, _INITIAL_LOSS]) + return outputs[1:] + + # Add input that represents id for each replica in sync so that + # _TPUEstimatorReplicaContext can be correctly entered during + # replicated computation. + replica_id_inputs = [] + replica_id_inputs.append([tf.constant(i) for i in range(ctx.num_replicas)]) + + (compile_op, loss) = tpu.split_compile_and_shard( + multi_tpu_train_steps_on_single_shard, + inputs=replica_id_inputs, + num_shards=ctx.num_replicas, + outputs_from_all_shards=False, + device_assignment=ctx.device_assignment) + + loss = loss[0] + return (compile_op, loss, host_call, captured_scaffold_fn, + captured_training_hooks.get()) + + +def _predict_on_tpu_system(ctx, model_fn_wrapper, dequeue_fn): + """Executes `model_fn_wrapper` multiple times on all TPU shards.""" + (single_tpu_predict_step, host_calls, captured_scaffold_fn, + captured_predict_hooks + ) = model_fn_wrapper.convert_to_single_tpu_predict_step(dequeue_fn) + + @tpu_function.on_device_training_loop + def multi_tpu_predict_steps_on_single_shard(replica_id): + # `tpu.split_compile_and_shard()` splits and passes input for each + # replica as an array. As so, correctly reshape the input to be a + # scalar. + replica_id = tf.reshape(replica_id, []) + with tpu_context._TPUEstimatorReplicaContext(replica_id): # pylint: disable=protected-access + + def cond(scalar_stopping_signal): + return tf.math.logical_not( + _StopSignals.should_stop(scalar_stopping_signal)) + + inputs = [_StopSignals.NON_STOPPING_SIGNAL] + outputs = training_loop.while_loop( + cond, single_tpu_predict_step, inputs=inputs, name=b'loop') + return outputs + + # Add input that represents id for each replica in sync so that + # _TPUEstimatorReplicaContext can be correctly entered during + # replicated computation. + replica_id_inputs = [] + replica_id_inputs.append([tf.constant(i) for i in range(ctx.num_replicas)]) + ( + compile_op, + dummy_predict_op, + ) = tpu.split_compile_and_shard( + multi_tpu_predict_steps_on_single_shard, + inputs=replica_id_inputs, + num_shards=ctx.num_replicas, + outputs_from_all_shards=False, + device_assignment=ctx.device_assignment) + + dummy_predict_op = dummy_predict_op[0] + return (compile_op, dummy_predict_op, host_calls, captured_scaffold_fn, + captured_predict_hooks.get()) + + +def _wrap_computation_in_while_loop(device, op_fn): + """Wraps the ops generated by `op_fn` in tf.while_loop.""" + + def computation(i): + with tf.control_dependencies(op_fn()): + return i + 1 + + iterations_per_loop_var = _create_or_get_iterations_per_loop() + # By setting parallel_iterations=1, the parallel execution in while_loop is + # basically turned off. + with tf.compat.v1.device(device): + iterations = tf.identity(iterations_per_loop_var) + return tf.compat.v1.while_loop( + lambda i: i < iterations, + computation, [tf.constant(0)], + parallel_iterations=1) + + +def _wrap_computation_in_while_loop_with_stopping_signals(device, op_fn): + """Wraps the ops generated by `op_fn` in tf.while_loop.""" + + def cond(scalar_stopping_signal): + return tf.math.logical_not(_StopSignals.should_stop(scalar_stopping_signal)) + + def computation(unused_scalar_stopping_signal): + return_value = op_fn() + execute_ops = return_value['ops'] + signals = return_value['signals'] + with tf.control_dependencies(execute_ops): + return _StopSignals.as_scalar_stopping_signal(signals) + + # By setting parallel_iterations=1, the parallel execution in while_loop is + # basically turned off. + with tf.compat.v1.device(device): + return tf.compat.v1.while_loop( + cond, + computation, [_StopSignals.NON_STOPPING_SIGNAL], + parallel_iterations=1) + + +def _validate_tpu_training_graph(ctx): + """Validate graph before running distributed training. + + Args: + ctx: A `_InternalTPUContext` instance with mode. + + Raises: + ValueError: If the graph seems invalid for running on device + """ + if control_flow_util.ENABLE_CONTROL_FLOW_V2: + return # b/124241278 + + operations = tf.compat.v1.get_default_graph().get_operations() + + # Check if there is atleast one CrossReplicaSum operation in the graph + # This should be introduced by using the CrossShardOptimizer wrapper + cross_replica_sum_ops = [ + o for o in operations if o.type == _CROSS_REPLICA_SUM_OP + ] + if not cross_replica_sum_ops and ctx.num_replicas > 1: + raise ValueError( + 'CrossShardOptimizer must be used for model training on TPUs.') + + +class _CapturedObject(object): + """A placeholder to capture an object. + + This is useful when we need to capture a Python object in the Tensorflow + control flow body function and use it outside the control flow. + """ + + def __init__(self): + self._object = None + self._captured = False + + def capture(self, o): + if self._captured: + raise RuntimeError( + 'InternalError: Object can capture only once. Please file bug.') + + self._captured = True + self._object = o + + def get(self): + if not self._captured: + raise RuntimeError( + 'InternalError: Object is not captured properly before `get`. ' + 'Please file bug.') + return self._object + + +def _get_scaffold(captured_scaffold_fn): + """Retrieves the Scaffold from `captured_scaffold_fn`.""" + with _CapturingContext(message='Inside scaffold_fn'): + scaffold_fn = captured_scaffold_fn.get() + if scaffold_fn: + scaffold = scaffold_fn() + if scaffold is None: + raise ValueError( + 'TPUEstimatorSpec.scaffold_fn returns None, which is not allowed') + else: + scaffold = None + + if scaffold: + wrapped_finalize = scaffold.finalize + + def _finalize(): + with _CapturingContext('Inside Scaffold.finalize'): + wrapped_finalize() + + scaffold.finalize = _finalize + return scaffold + + +class _CapturingContext(control_flow_ops.ControlFlowContext): + """Tracks references to Tensors defined in TPU replication.""" + + def __init__(self, message): + control_flow_ops.ControlFlowContext.__init__(self) + self._message = message + + def to_control_flow_context_def(self, context_def, export_scope=None): + # pylint: disable=useless-super-delegation + # NOTE(slebedev): the method is required by `ControlFlowContext`. + super(_CapturingContext, + self).to_control_flow_context_def(context_def, export_scope) + + def AddOp(self, op): # pylint: disable=invalid-name + for c in op.inputs: + if tpu_replication._TPU_REPLICATE_ATTR in c.op.node_def.attr: # pylint: disable=protected-access + raise ValueError('{}: Op {} depends on TPU computation {}, ' + 'which is not allowed.'.format(self._message, op, c)) + + def AddValue(self, value): + self.AddOp(value.op) + return value + + def __enter__(self): + # pylint: disable=protected-access + self._g = tf.compat.v1.get_default_graph() + self._old = self._g._get_control_flow_context() + self._g._set_control_flow_context(self) + # pylint: enable=protected-access + + def __exit__(self, _, __, ___): # pylint: disable=invalid-name + self._g._set_control_flow_context(self._old) # pylint: disable=protected-access + + +class _Inputs(object): + """A data structure representing the input_fn returned values. + + This also supports the returned value from input_fn as `Dataset`. + """ + + def __init__(self, features=None, labels=None, dataset=None, signals=None): + if dataset is not None and (features is not None or labels is not None or + signals is not None): + raise RuntimeError('Internal Error: Either (features and labels) or ' + 'dataset should be provided, not both. Please file ' + 'bug') + + self._features = features + self._labels = labels + self._signals = signals + + self._dataset = dataset + self._iterator = None + + @staticmethod + def from_input_fn(return_values): + """Returns an `_Inputs` instance according to `input_fn` return value.""" + if isinstance(return_values, tf.compat.v2.data.Dataset): + dataset = return_values + return _Inputs(dataset=dataset) + + features, labels = _Inputs._parse_inputs(return_values) + return _Inputs(features, labels) + + @staticmethod + def _parse_inputs(return_values): + if isinstance(return_values, tuple): + features, labels = return_values + else: + features, labels = return_values, None + return features, labels + + @property + def is_dataset(self): + """Returns True if the return value from input_fn is Dataset.""" + return self._dataset is not None + + def dataset_initializer(self): + """Returns the dataset's initializer. + + The initializer must be run before calling `features_and_labels`. + """ + self._iterator = tf.compat.v1.data.make_initializable_iterator( + self._dataset) + return self._iterator.initializer + + def features_and_labels(self): + """Gets `features` and `labels`.""" + if self.is_dataset: + if self._iterator is None: + raise RuntimeError('Internal error: Must run dataset_initializer ' + 'before calling features_and_labels(). Please file ' + 'a bug!') + return _Inputs._parse_inputs(self._iterator.get_next()) + + return (self._features, self._labels) + + def signals(self): + return self._signals + + @property + def dataset(self): + return self._dataset + + +class _InputsWithStoppingSignals(_Inputs): + """Inputs with `_StopSignals` inserted into the dataset.""" + + def __init__(self, + dataset, + batch_size, + add_padding=False, + num_invocations_per_step=1): + + assert dataset is not None + user_provided_dataset = dataset.map( + _InputsWithStoppingSignals.insert_stopping_signal( + stop=False, batch_size=batch_size, add_padding=add_padding)) + if num_invocations_per_step == 1: + final_batch_dataset = dataset.take(1).map( + _InputsWithStoppingSignals.insert_stopping_signal( + stop=True, batch_size=batch_size, add_padding=add_padding)) + else: + # We append (2 * num_invocations_per_step - 1) batches for exhausting the + # user_provided_dataset and stop properly. + # For example, if num_invocations_per_step is 2, we append 3 additional + # padding batches: b1, b2, b3. + # If user_provided_dataset contains two batches: a1, a2 + # Step 1: [a1, a2] + # Step 2: [b1, b2] -> STOP + # If user_provided_dataset contains three batches: a1, a2, a3. + # The training loops: + # Step 1: [a1, a2] + # Step 2: [a3, b1] + # Step 3: [b2, b3] -> STOP. + final_batch_dataset = dataset.take(1).map( + _InputsWithStoppingSignals.insert_stopping_signal( + stop=True, batch_size=batch_size, add_padding=add_padding)) + final_batch_dataset = final_batch_dataset.repeat( + 2 * num_invocations_per_step - 1) + + def _set_mask(data_dict): + signals = data_dict['signals'] + signals['padding_mask'] = tf.compat.v1.ones_like( + signals['padding_mask']) + data_dict['signals'] = signals + return data_dict + + # Mask out the extra batch. + final_batch_dataset = final_batch_dataset.map(_set_mask) + + dataset = user_provided_dataset.concatenate(final_batch_dataset).prefetch(2) + + super(_InputsWithStoppingSignals, self).__init__(dataset=dataset) + self._current_inputs = None + + def features_and_labels(self): + if self._current_inputs is not None: + raise RuntimeError( + 'Internal Error: The previous inputs have not been properly ' + 'consumed. First call features_and_labels, then call signals.') + + inputs_with_signals = self._iterator.get_next() + features = inputs_with_signals['features'] + labels = inputs_with_signals.get('labels') + + self._current_inputs = inputs_with_signals + return features, labels + + def signals(self): + """Returns the `Signals` from `_Inputs`.""" + if self._current_inputs is None: + raise RuntimeError( + 'Internal Error: The current inputs have not been properly ' + 'generated. First call features_and_labels, then call signals.') + signals = self._current_inputs['signals'] + self._current_inputs = None + return signals + + @staticmethod + def insert_stopping_signal(stop, batch_size, add_padding=False): + """Inserts stopping_signal into dataset via _map_fn. + + Here we change the data structure in the dataset, such that the return value + is a dictionary now and `features`, `labels`, and `signals` are three + distinguished keys in that dict. This provides a better structure, which + eases the process to decompose the inputs (see `features_and_labels`). + + Args: + stop: bool, state of current stopping signals. + batch_size: int, batch size. + add_padding: bool, whether to pad the tensor to full batch size. + + Returns: + A map_fn passed to dataset.map API. + """ + + def _map_fn(*args): + """The map fn to insert signals.""" + if len(args) == 1: + # Unpack the single Tensor/dict argument as features. This is required + # for the input_fn returns no labels. + args = args[0] + features, labels = _Inputs._parse_inputs(args) + new_input_dict = {} + + if add_padding: + padding_mask, features, labels = ( + _PaddingSignals.pad_features_and_labels(features, labels, + batch_size)) + + new_input_dict['features'] = features + if labels is not None: + new_input_dict['labels'] = labels + + else: + new_input_dict['features'] = features + if labels is not None: + new_input_dict['labels'] = labels + padding_mask = None + + new_input_dict['signals'] = _StopSignals( + stop=stop, batch_size=batch_size, + padding_mask=padding_mask).as_dict() + + return new_input_dict + + return _map_fn + + +class _StopSignals(object): + """Signals class holding all logic to handle TPU stopping condition.""" + + NON_STOPPING_SIGNAL = False + STOPPING_SIGNAL = True + + def __init__(self, stop, batch_size, padding_mask=None): + self._stop = stop + self._batch_size = batch_size + self._padding_mask = padding_mask + + def as_dict(self): + """Returns the signals as Python dict.""" + shape = [self._batch_size, 1] + dtype = tf.dtypes.bool + + if self._stop: + stopping = tf.ones(shape=shape, dtype=dtype) + else: + stopping = tf.zeros(shape=shape, dtype=dtype) + + signals = {'stopping': stopping} + if self._padding_mask is not None: + signals['padding_mask'] = self._padding_mask + return signals + + @staticmethod + def as_scalar_stopping_signal(signals): + return tf.identity(signals['stopping'][0][0]) + + @staticmethod + def should_stop(scalar_stopping_signal): + """Detects whether scalar_stopping_signal indicates stopping.""" + if isinstance(scalar_stopping_signal, tf.Tensor): + # STOPPING_SIGNAL is a constant True. Here, the logical_and is just the TF + # way to express the bool check whether scalar_stopping_signal is True. + return tf.math.logical_and(scalar_stopping_signal, + _StopSignals.STOPPING_SIGNAL) + else: + # For non Tensor case, it is used in SessionRunHook. So, we cannot modify + # the graph anymore. Here, we use pure Python. + return bool(scalar_stopping_signal) + + +class _PaddingSignals(object): + """Signals class holding all logic to handle padding.""" + + @staticmethod + def pad_features_and_labels(features, labels, batch_size): + """Pads out the batch dimension of features and labels.""" + real_batch_size = tf.compat.v1.shape( + _PaddingSignals._find_any_tensor(features))[0] + + batch_size_tensor = tf.constant(batch_size, tf.dtypes.int32) + + check_greater = tf.compat.v1.debugging.assert_greater_equal( + batch_size_tensor, + real_batch_size, + data=(batch_size_tensor, real_batch_size), + message='The real batch size should not be greater than batch_size.') + + with tf.control_dependencies([check_greater]): + missing_count = batch_size_tensor - real_batch_size + + def pad_single_tensor(tensor): + """Pads out the batch dimension of a tensor to the complete batch_size.""" + rank = len(tensor.shape) + assert rank > 0 + padding = tf.stack([[0, missing_count]] + [[0, 0]] * (rank - 1)) + padded_shape = (batch_size,) + tuple(tensor.shape[1:]) + padded_tensor = tf.compat.v1.pad(tensor, padding) + padded_tensor.set_shape(padded_shape) + return padded_tensor + + def nest_pad(tensor_or_dict): + return tf.nest.map_structure(pad_single_tensor, tensor_or_dict) + + features = nest_pad(features) + if labels is not None: + labels = nest_pad(labels) + + padding_mask = _PaddingSignals._padding_mask(real_batch_size, missing_count, + batch_size) + + return padding_mask, features, labels + + @staticmethod + def slice_tensor_or_dict(tensor_or_dict, signals): + """Slice the real Tensors according to padding mask in signals.""" + + padding_mask = signals['padding_mask'] + batch_size = tf.compat.v1.shape(padding_mask)[0] + + def verify_batch_size(tensor): + check_batch_size = tf.math.equal(batch_size, tensor.shape[0]) + with tf.control_dependencies([check_batch_size]): + return tf.identity(tensor) + + def slice_single_tensor(tensor): + rank = len(tensor.shape) + assert rank > 0 + real_batch_size = batch_size - tf.math.reduce_sum(padding_mask) + return verify_batch_size(tensor)[0:real_batch_size] + + # As we split the Tensors to all TPU cores and concat them back, it is + # important to ensure the real data is placed before padded ones, i.e., + # order is preserved. By that, the sliced padding mask should have all 0's. + # If this assertion failed, # the slice logic here would not hold. + sliced_padding_mask = slice_single_tensor(padding_mask) + assert_padding_mask = tf.math.equal( + tf.math.reduce_sum(sliced_padding_mask), 0) + + with tf.control_dependencies([assert_padding_mask]): + should_stop = _StopSignals.should_stop( + _StopSignals.as_scalar_stopping_signal(signals)) + + is_full_batch = tf.math.equal(tf.math.reduce_sum(padding_mask), 0) + + def slice_fn(tensor): + # If the current batch is full batch or part of stopping signals, we do + # not need to slice to save performance. + return tf.compat.v1.cond( + tf.math.logical_or(should_stop, is_full_batch), + (lambda: verify_batch_size(tensor)), + (lambda: slice_single_tensor(tensor))) + + return tf.nest.map_structure(slice_fn, tensor_or_dict) + + @staticmethod + def _find_any_tensor(batch_features): + tensors = [ + x for x in tf.nest.flatten(batch_features) if isinstance(x, tf.Tensor) + ] + if not tensors: + raise ValueError('Cannot find any Tensor in features dict.') + return tensors[0] + + @staticmethod + def _padding_mask(real_batch_size, missing_count, batch_size): + padding_mask = tf.concat([ + tf.zeros((real_batch_size,), dtype=tf.dtypes.int32), + tf.ones((missing_count,), dtype=tf.dtypes.int32) + ], + axis=0) + padding_mask.set_shape((batch_size,)) + return padding_mask + + +def _verify_cross_hosts_transfer_size(tensor_dict, message): + total_size = 0 + tensor_structure = {} + for key, tensor in tensor_dict.items(): + shape = tensor.shape + size = np.prod(shape) * tensor.dtype.size + tensor_structure[key] = shape + total_size += size + if total_size >= _ONE_GIGABYTE: + raise ValueError( + '{} The transfer size is larger than the protobuf limit. Please ' + 'consider to use Tensors with smaller shapes or reduce batch ' + 'size. Given:\n' + '{}'.format( + message, '\n'.join([ + ' -- Key: {}, Shape: {}'.format(k, v) + for k, v in tensor_structure.items() + ]))) + + +def _add_item_to_params(params, key, value): + """Adds a new item into `params`.""" + if hasattr(params, 'set_hparam'): + # For HParams, we need to use special API. + if key in params: + params.set_hparam(key, value) + else: + params.add_hparam(key, value) + else: + # Now params is Python dict. + params[key] = value + + +def export_estimator_savedmodel(estimator, + export_dir_base, + serving_input_receiver_fn, + assets_extra=None, + as_text=False, + checkpoint_path=None): + """Export `Estimator` trained model for TPU inference. + + Args: + estimator: `Estimator` with which model has been trained. + export_dir_base: A string containing a directory in which to create + timestamped subdirectories containing exported SavedModels. + serving_input_receiver_fn: A function that takes no argument and returns a + `ServingInputReceiver` or `TensorServingInputReceiver`. + assets_extra: A dict specifying how to populate the assets.extra directory + within the exported SavedModel, or `None` if no extra assets are needed. + as_text: whether to write the SavedModel proto in text format. + checkpoint_path: The checkpoint path to export. If `None` (the default), + the most recent checkpoint found within the model directory is chosen. + + Returns: + The string path to the exported directory. + """ + # `TPUEstimator` requires `tpu_config.RunConfig`, so we cannot use + # `estimator.config`. + config = tpu_config.RunConfig(model_dir=estimator.model_dir) + est = TPUEstimator( + estimator._model_fn, # pylint: disable=protected-access + config=config, + params=estimator.params, + use_tpu=True, + train_batch_size=2048, # Does not matter. + eval_batch_size=2048, # Does not matter. + ) + return est.export_saved_model(export_dir_base, serving_input_receiver_fn, + assets_extra, as_text, checkpoint_path) + + +def model_fn_inference_on_tpu(model_fn, + features, + labels=None, + config=None, + params=None, + batch_config=None): + """Convenience wrapper for export_saved_model API v2 for a model_fn. + WARNING:THIS METHOD IS DEPRECATED AND NOT PART OF THE APIS. + + Make sure to set + `export_saved_model_api_version=tpu_estimator.ExportSavedModelApiVersion.V2` + when initializing TPUEstimator (default API version is V1). This is because + 1) `tpu.rewrite` (or `tpu.compile`) shouldn't be called in a nested way + (otherwise validation will throw error like + "NotImplementedError: tpu_shard_context cannot be nested.") + 2) When using V1 API, Estimator calls `tpu.rewrite` so + using `model_fn_inference_on_tpu` will trigger a nested call. + When using V2 API, users of Estimator needs to call `tpu.rewrite` (which + the wrapper does). + + It attempts to execute the entire model function on the TPU for prediction. + Note that this does not support features which are SparseTensors. If you have + SparseTensor features, consider partitioning your model function further and + use inference_on_tpu. + + Args: + model_fn: the model_fn for which we want to inference on TPU. + features: a tensor or dict of tensors, serves as the feature inputs to the + model. + labels: a tensor or dict of tensors, serves as the labels inputs to the + model. + config: auxiliary config to the Estimator. + params: hparams that we want to pass to the model_fn. + batch_config: a named tuple to wrap the inference batching configuration + inputs. + + Returns: + An EstimatorSpec containing the outputs in export_outputs and predictions. + """ + computation, capture = _build_computation_for_inference( + model_fn, labels, config, params) + tensors = call_computation(features, computation, batch_config=batch_config) + estimator_spec, export_outputs_dict, predictions_dict, none_indices = ( + capture.get()) + predictions_list = tensors[:len(predictions_dict)] + export_outputs_list_without_none = tensors[len(predictions_dict):] + + # Reinsert `None`s which we've taken out in + # `_build_computation_for_inference()`. + export_outputs_list = [] + while none_indices or export_outputs_list_without_none: + if none_indices and none_indices[0] == len(export_outputs_list): + export_outputs_list.append(None) + none_indices.pop(0) + else: + export_outputs_list.append(export_outputs_list_without_none.pop(0)) + + # Reconstruct `export_outputs` with updated tensors. + new_export_outputs_dict = tf.nest.pack_sequence_as(export_outputs_dict, + export_outputs_list) + export_outputs = estimator_spec.export_outputs + new_export_outputs = collections.OrderedDict( + (k, _clone_export_output_with_tensors(export_outputs[k], v)) + for k, v in six.iteritems(new_export_outputs_dict)) + # Reconstruct `predictions` with updated tensors. + new_predictions = tf.nest.pack_sequence_as(predictions_dict, predictions_list) + if (len(new_predictions) == 1 and + _KEY_WHEN_PREDICTIONS_IS_A_TENSOR in new_predictions): + new_predictions = new_predictions[_KEY_WHEN_PREDICTIONS_IS_A_TENSOR] + + return estimator_spec._replace( + export_outputs=new_export_outputs, predictions=new_predictions) + + +def _build_computation_for_inference(model_fn, labels, config, params): + """Builds the computation with calls the model_fn for inference.""" + capture = _CapturedObject() + + def computation(computation_input): + """Computation to be passed to `TPUPartitionedCall()`.""" + tpu_computation, tpu_capture = _build_tpu_computation_for_inference( + model_fn, computation_input, labels, config, params) + + tensors_on_cpu = tf.compat.v1.tpu.rewrite(tpu_computation) + tpu.prune_unconnected_ops_from_xla(tf.compat.v1.get_default_graph()) + + (estimator_spec, export_outputs_dict, export_outputs_list, + predictions_dict) = ( + tpu_capture.get()) + predictions_list = tensors_on_cpu[:len(predictions_dict)] + export_outputs_tpu_on_cpu_list = tensors_on_cpu[len(predictions_dict):] + + # Reconstruct tensors used in export_outputs, with TPU tensors replaced + # with their CPU counterpart returned from `rewrite_for_inference()`. + # `function.Defun()` does not like `None`s in return values, so we leave + # `None`s out but record their positions for later reconstruction. + export_outputs_list_without_none = [] + none_indices = [] + for i, t in enumerate(export_outputs_list): + if t is None: + none_indices.append(i) + else: + export_outputs_list_without_none.append( + export_outputs_tpu_on_cpu_list.pop(0)) + + capture.capture( + (estimator_spec, export_outputs_dict, predictions_dict, none_indices)) + return predictions_list + export_outputs_list_without_none + + return computation, capture + + +def _build_tpu_computation_for_inference(model_fn, features, labels, config, + params): + """Builds the TPU computation for inference on TPU.""" + capture = _CapturedObject() + + def computation(): + """Compute tpu tensors used in export_outputs. + + Passed to rewrite_for_inference so that model_fn will be called under + the rewriting contexts. Only tpu tensors are returned, but export_outputs + and scaffold are captured. + + Returns: + A list of Tensors used in export_outputs and not marked for + outside_compilation. + """ + # We should only call model fn once and it should be inside `computation` + # so that building the graph will happen under `rewrite_for_inference`. + + model_fn_args = function_utils.fn_args(model_fn) + kwargs = {} + # Makes deep copy with `config` and params` in case user mutates them. + if 'labels' in model_fn_args: + kwargs['labels'] = labels + if 'mode' in model_fn_args: + kwargs['mode'] = model_fn_lib.ModeKeys.PREDICT + if 'config' in model_fn_args: + kwargs['config'] = config + if 'params' in model_fn_args: + kwargs['params'] = params + estimator_spec = model_fn(features, **kwargs) + + # We pick the TPU tensors out from `export_output` and later return them + # from `computation` for rewriting. + export_outputs_dict = collections.OrderedDict( + (k, _export_output_to_tensors(v)) + for k, v in six.iteritems(estimator_spec.export_outputs)) + export_outputs_list = tf.nest.flatten(export_outputs_dict) + export_outputs_tpu_list = [t for t in export_outputs_list if t is not None] + + if isinstance(estimator_spec.predictions, dict): + predictions_dict = collections.OrderedDict( + (k, v) for k, v in six.iteritems(estimator_spec.predictions)) + else: + predictions_dict = { + _KEY_WHEN_PREDICTIONS_IS_A_TENSOR: estimator_spec.predictions + } + predictions_list = tf.nest.flatten(predictions_dict) + + # We cannot return everything we want through the return values, so + # capture the rest here for later use. + capture.capture((estimator_spec, export_outputs_dict, export_outputs_list, + predictions_dict)) + return predictions_list + export_outputs_tpu_list + + return computation, capture + + +def inference_on_tpu(computation, + inputs_to_tpu, + num_batch_threads, + max_batch_size, + batch_timeout_micros, + allowed_batch_sizes=None, + max_enqueued_batches=100): + """Convenient wrapper for export_saved_model API v2 to wrap TPU computation. + + WARNING: THIS METHOD IS DEPRECATED AND NOT PART OF THE APIS. + + Make sure to set + `export_saved_model_api_version=tpu_estimator.ExportSavedModelApiVersion.V2` + when initializing TPUEstimator (default API version is V1). This is because + 1) `tpu.rewrite` (or `tpu.compile`) shouldn't be called in a nested way + (otherwise validation will throw error like + "NotImplementedError: tpu_shard_context cannot be nested.") + 2) When using V1 API, Estimator calls `tpu.rewrite` so + using `model_fn_inference_on_tpu` will trigger a nested call. + When using V2 API, users of Estimator needs to call `tpu.rewrite` (which + the wrapper does). + + It puts computation on TPU, add batching around it and round robin computation + between TPU cores. + + See tpu_estimator_test.py for an example. + + Args: + computation: computation to be put on TPU, which takes inputs_to_tpu as + arguments. + inputs_to_tpu: a list of tensors as input to computation. + num_batch_threads: Number of scheduling threads for processing batches of + work. Determines the number of batches processed in parallel. + max_batch_size: Batch sizes will never be bigger than this. If None or 0, + no batching will done. + batch_timeout_micros: Maximum number of microseconds to wait before + outputting an incomplete batch. + allowed_batch_sizes: Optional list of allowed batch sizes. If left empty, + does nothing. Otherwise, supplies a list of batch sizes, causing the op to + pad batches up to one of those sizes. The entries must increase + monotonically, and the final entry must equal max_batch_size. + max_enqueued_batches: The maximum depth of the batch queue. Defaults to 100. + + Returns: + The unbatched computation output Tensors. + """ + + def _tpu_call(args): + """Function to either call or feed into BatchFunction.""" + + @function.Defun(capture_resource_var_by_value=False) + def tpu_computation(): + """Function to feed into the TPUPartitionedCallOp.""" + tensors_on_cpu = tf.compat.v1.tpu.rewrite(computation, args) + tpu.prune_unconnected_ops_from_xla(tf.compat.v1.get_default_graph()) + return tensors_on_cpu + + return tpu_functional.TPUPartitionedCall( + args=tpu_computation.captured_inputs, + device_ordinal=tpu_ops.tpu_ordinal_selector(), + Tout=[o.type for o in tpu_computation.definition.signature.output_arg], + f=tpu_computation) + + if not max_batch_size: + return _tpu_call(inputs_to_tpu) + + @tf.nondifferentiable_batch_function(num_batch_threads, max_batch_size, + batch_timeout_micros, + allowed_batch_sizes, + max_enqueued_batches) + def batched_tpu_computation(*args): + """Function to feed into the BatchOp.""" + return _tpu_call(args) + + return batched_tpu_computation(*inputs_to_tpu) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/tpu/util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/tpu/util.py new file mode 100644 index 0000000000000000000000000000000000000000..9ca6feef0e1d4619604131167954f693563b73bb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/tpu/util.py @@ -0,0 +1,96 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# =================================================================== +"""Utilities for the functionalities.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import collections +import re +import time +import numpy as np +import six +import tensorflow as tf + +_ITERATIONS_PER_LOOP_VALUE_REGEX = re.compile( + r'^(?P[1-9]\d*)((?P[s|m|h])$|$)') + +IterationsPerLoopCounter = collections.namedtuple('IterationsPerLoopCounter', + ['value', 'unit']) + + +def check_positive_integer(value, name): + """Checks whether `value` is a positive integer.""" + if not isinstance(value, (six.integer_types, np.integer)): + raise TypeError('{} must be int, got {}'.format(name, type(value))) + + if value <= 0: + raise ValueError('{} must be positive, got {}'.format(name, value)) + + +def parse_iterations_per_loop(iterations_per_loop): + """Parses the `iterations_per_loop` value. + + The parser expects the value of the `iterations_per_loop` value to be a + positive integer value with unit:`count` or time-based value `` + where is any positive integer and `s`, `m`, `h` are unit of time in + seconds, minutes, hours respectively. Examples of valid values: `3600s`, `60m` + , `1h`. + + Args: + iterations_per_loop: Number of iterations or time alloted to spend on per + device loop. + + Returns: + A dictionary of `value` and `unit`. The `unit` value can be either a raw + `count`, or time in `seconds`. + { + "value": , + "unit": + } + """ + m = _ITERATIONS_PER_LOOP_VALUE_REGEX.match(str(iterations_per_loop)) + if m is None: + raise ValueError( + 'Invalid TPUConfig `iterations_per_loop` value. Value must be positive ' + 'integer value or time-based value `` where is any' + 'positive integer and `s`, `m`, `h` are unit of time in seconds, ' + 'minutes, hours respectively. Examples of valid values: `3600s`, `60m`,' + ' `1h`.') + unit_value = 'seconds' if m.group('suffix') in ['h', 'm', 's'] else 'count' + value = int(m.group('value')) + if m.group('suffix') == 'm': + value *= 60 + elif m.group('suffix') == 'h': + value *= 3600 + return IterationsPerLoopCounter(value, unit_value) + + +# TODO(b/118302029) Remove this copy of MultiHostDatasetInitializerHook after we +# release a tensorflow_estimator with MultiHostDatasetInitializerHook in +# python/estimator/util.py. +class MultiHostDatasetInitializerHook(tf.compat.v1.train.SessionRunHook): + """Creates a SessionRunHook that initializes all passed iterators.""" + + def __init__(self, dataset_initializers): + self._initializers = dataset_initializers + + def after_create_session(self, session, coord): + del coord + start = time.time() + session.run(self._initializers) + tf.compat.v1.logging.info('Initialized dataset iterators in %d seconds', + time.time() - start) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/training.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/training.py new file mode 100644 index 0000000000000000000000000000000000000000..0b2cd254402ccfb6134b69944bdd836b0f37d69c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/training.py @@ -0,0 +1,1118 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Classes and functions related to train_and_evaluate.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import collections +import json +import os +import time + +import six +import tensorflow as tf +from tensorflow.python.distribute import estimator_training as distribute_coordinator_training +from tensorflow.python.training import basic_session_run_hooks +from tensorflow.python.training import server_lib +from tensorflow_estimator.python.estimator import estimator as estimator_lib +from tensorflow_estimator.python.estimator import exporter as exporter_lib +from tensorflow_estimator.python.estimator import run_config as run_config_lib +from tensorflow_estimator.python.estimator.estimator_export import estimator_export + +_MAX_DELAY_SECS = 60 +_DELAY_SECS_PER_WORKER = 5 +_TF_CONFIG_ENV = 'TF_CONFIG' +_ENVIRONMENT_KEY = 'environment' +_ENVIRONMENT_GOOGLE_VALUE = 'google' +_TRAINER_JOBS = (run_config_lib.TaskType.CHIEF, run_config_lib.TaskType.MASTER, + run_config_lib.TaskType.WORKER) + + +def _validate_input_fn(input_fn): + """Validates the `input_fn`.""" + if not callable(input_fn): + raise TypeError('`input_fn` must be callable, given: {}'.format(input_fn)) + + +def _validate_hooks(hooks): + """Validates the `hooks`.""" + hooks = tuple(hooks or []) + for hook in hooks: + if not isinstance(hook, tf.compat.v1.train.SessionRunHook): + raise TypeError( + 'All hooks must be `SessionRunHook` instances, given: {}'.format( + hook)) + return hooks + + +def _validate_saving_listeners(saving_listeners): + """Validates the `saving_listeners`.""" + saving_listeners = tuple(saving_listeners or []) + for saving_listener in saving_listeners: + if not isinstance(saving_listener, + tf.compat.v1.train.CheckpointSaverListener): + raise TypeError( + 'All saving_listeners must be `CheckpointSaverListener` instances, ' + 'given: {}'.format(saving_listener)) + return saving_listeners + + +def _validate_exporters(exporters): + """Validates `exporters` and returns them as a tuple.""" + if not exporters: + return () + + if isinstance(exporters, exporter_lib.Exporter): + exporters = [exporters] + + unique_names = [] # `Exporter`s should have unique names. + try: + for exporter in exporters: + if not isinstance(exporter, exporter_lib.Exporter): + # Error message will be printed out by the outer try/except. + raise TypeError + + if not exporter.name: + full_list_of_names = [e.name for e in exporters] + raise ValueError('An Exporter cannot have a name that is `None` or' + ' empty. All exporter names:' + ' {}'.format(full_list_of_names)) + + if not isinstance(exporter.name, six.string_types): + raise ValueError('An Exporter must have a string name. Given: ' + '{}'.format(type(exporter.name))) + + if exporter.name in unique_names: + full_list_of_names = [e.name for e in exporters] + raise ValueError( + '`exporters` must have unique names. Such a name cannot be `None`.' + ' All exporter names: {}'.format(full_list_of_names)) + unique_names.append(exporter.name) + except TypeError: + # Two possibilities: + # - `exporters` is neither `Exporter` nor iterable. Python has + # raised a `TypeError` when iterating over `exporters`. + # - an `exporter` was None or not of type `Exporter`, so we raised a + # `TypeError`. + raise TypeError('`exporters` must be an Exporter,' + ' an iterable of Exporter, or `None`,' + ' found %s.' % exporters) + + return tuple(exporters) + + +def _is_google_env(): + """Detects whether current environment is google.""" + tf_config = json.loads(os.environ.get(_TF_CONFIG_ENV) or '{}') + if not tf_config: + tf.compat.v1.logging.warn( + 'TF_CONFIG should not be empty in distributed environment.') + return tf_config.get(_ENVIRONMENT_KEY) == _ENVIRONMENT_GOOGLE_VALUE + + +@estimator_export('estimator.TrainSpec') +class TrainSpec( + collections.namedtuple( + 'TrainSpec', ['input_fn', 'max_steps', 'hooks', 'saving_listeners'])): + """Configuration for the "train" part for the `train_and_evaluate` call. + + `TrainSpec` determines the input data for the training, as well as the + duration. Optional hooks run at various stages of training. + + Usage: + + >>> train_spec = tf.estimator.TrainSpec( + ... input_fn=lambda: 1, + ... max_steps=100, + ... hooks=[_StopAtSecsHook(stop_after_secs=10)], + ... saving_listeners=[_NewCheckpointListenerForEvaluate(None, 20, None)]) + >>> train_spec.saving_listeners[0]._eval_throttle_secs + 20 + >>> train_spec.hooks[0]._stop_after_secs + 10 + >>> train_spec.max_steps + 100 + """ + + def __new__(cls, input_fn, max_steps=None, hooks=None, saving_listeners=None): + """Creates a validated `TrainSpec` instance. + + Args: + input_fn: A function that provides input data for training as minibatches. + See [Premade Estimators]( + https://tensorflow.org/guide/premade_estimators#create_input_functions) + for more information. The function should construct and return one of + the following: + * A 'tf.data.Dataset' object: Outputs of `Dataset` object must be a + tuple (features, labels) with same constraints as below. + * A tuple (features, labels): Where features is a `Tensor` or a + dictionary of string feature name to `Tensor` and labels is a + `Tensor` or a dictionary of string label name to `Tensor`. + max_steps: Int. Positive number of total steps for which to train model. + If `None`, train forever. The training `input_fn` is not expected to + generate `OutOfRangeError` or `StopIteration` exceptions. See the + `train_and_evaluate` stop condition section for details. + hooks: Iterable of `tf.train.SessionRunHook` objects to run on all workers + (including chief) during training. + saving_listeners: Iterable of `tf.estimator.CheckpointSaverListener` + objects to run on chief during training. + + Returns: + A validated `TrainSpec` object. + + Raises: + ValueError: If any of the input arguments is invalid. + TypeError: If any of the arguments is not of the expected type. + """ + # Validate input_fn. + _validate_input_fn(input_fn) + + # Validate max_steps. + if max_steps is not None and max_steps <= 0: + raise ValueError( + 'Must specify max_steps > 0, given: {}'.format(max_steps)) + + # Validate hooks. + hooks = _validate_hooks(hooks) + + # Validate saving_listeners. + saving_listeners = _validate_saving_listeners(saving_listeners) + + return super(TrainSpec, cls).__new__( + cls, input_fn=input_fn, max_steps=max_steps, hooks=hooks, + saving_listeners=saving_listeners) + + +@estimator_export('estimator.EvalSpec') +class EvalSpec( + collections.namedtuple('EvalSpec', [ + 'input_fn', 'steps', 'name', 'hooks', 'exporters', 'start_delay_secs', + 'throttle_secs' + ])): + """Configuration for the "eval" part for the `train_and_evaluate` call. + + `EvalSpec` combines details of evaluation of the trained model as well as its + export. Evaluation consists of computing metrics to judge the performance of + the trained model. Export writes out the trained model on to external + storage. + """ + + def __new__(cls, + input_fn, + steps=100, + name=None, + hooks=None, + exporters=None, + start_delay_secs=120, + throttle_secs=600): + """Creates a validated `EvalSpec` instance. + + Args: + input_fn: A function that constructs the input data for evaluation. See + [Premade Estimators]( + https://tensorflow.org/guide/premade_estimators#create_input_functions) + for more information. The function should construct and return one of + the following: + * A 'tf.data.Dataset' object: Outputs of `Dataset` object must be a + tuple (features, labels) with same constraints as below. + * A tuple (features, labels): Where features is a `Tensor` or a + dictionary of string feature name to `Tensor` and labels is a + `Tensor` or a dictionary of string label name to `Tensor`. + steps: Int. Positive number of steps for which to evaluate model. If + `None`, evaluates until `input_fn` raises an end-of-input exception. See + `Estimator.evaluate` for details. + name: String. Name of the evaluation if user needs to run multiple + evaluations on different data sets. Metrics for different evaluations + are saved in separate folders, and appear separately in tensorboard. + hooks: Iterable of `tf.train.SessionRunHook` objects to run during + evaluation. + exporters: Iterable of `Exporter`s, or a single one, or `None`. + `exporters` will be invoked after each evaluation. + start_delay_secs: Int. Start evaluating after waiting for this many + seconds. + throttle_secs: Int. Do not re-evaluate unless the last evaluation was + started at least this many seconds ago. Of course, evaluation does not + occur if no new checkpoints are available, hence, this is the minimum. + + Returns: + A validated `EvalSpec` object. + + Raises: + ValueError: If any of the input arguments is invalid. + TypeError: If any of the arguments is not of the expected type. + """ + # Validate input_fn. + _validate_input_fn(input_fn) + + # Validate steps. + if steps is not None and steps <= 0: + raise ValueError('Must specify steps > 0, given: {}'.format(steps)) + + # Validate name. + if name is not None and not isinstance(name, six.string_types): + raise TypeError('`name` must be string, given: {}'.format(name)) + + # Validate hooks. + hooks = _validate_hooks(hooks) + + # Validate exporters. + exporters = _validate_exporters(exporters) + + # Validate start_delay_secs. + if start_delay_secs < 0: + raise ValueError('Must specify start_delay_secs >= 0, given: {}'.format( + start_delay_secs)) + + # Validate throttle_secs. + if throttle_secs < 0: + raise ValueError( + 'Must specify throttle_secs >= 0, given: {}'.format(throttle_secs)) + + return super(EvalSpec, cls).__new__( + cls, + input_fn=input_fn, + steps=steps, + name=name, + hooks=hooks, + exporters=exporters, + start_delay_secs=start_delay_secs, + throttle_secs=throttle_secs) + + +@estimator_export('estimator.train_and_evaluate') +def train_and_evaluate(estimator, train_spec, eval_spec): + """Train and evaluate the `estimator`. + + This utility function trains, evaluates, and (optionally) exports the model by + using the given `estimator`. All training related specification is held in + `train_spec`, including training `input_fn` and training max steps, etc. All + evaluation and export related specification is held in `eval_spec`, including + evaluation `input_fn`, steps, etc. + + This utility function provides consistent behavior for both local + (non-distributed) and distributed configurations. The default distribution + configuration is parameter server-based between-graph replication. For other + types of distribution configurations such as all-reduce training, please use + [DistributionStrategies](https://github.com/tensorflow/tensorflow/tree/master/tensorflow/python/distribute). + + Overfitting: In order to avoid overfitting, it is recommended to set up the + training `input_fn` to shuffle the training data properly. + + Stop condition: In order to support both distributed and non-distributed + configuration reliably, the only supported stop condition for model + training is `train_spec.max_steps`. If `train_spec.max_steps` is `None`, the + model is trained forever. *Use with care* if model stop condition is + different. For example, assume that the model is expected to be trained with + one epoch of training data, and the training `input_fn` is configured to throw + `OutOfRangeError` after going through one epoch, which stops the + `Estimator.train`. For a three-training-worker distributed configuration, each + training worker is likely to go through the whole epoch independently. So, the + model will be trained with three epochs of training data instead of one epoch. + + Example of local (non-distributed) training: + + ```python + # Set up feature columns. + categorial_feature_a = categorial_column_with_hash_bucket(...) + categorial_feature_a_emb = embedding_column( + categorical_column=categorial_feature_a, ...) + ... # other feature columns + + estimator = DNNClassifier( + feature_columns=[categorial_feature_a_emb, ...], + hidden_units=[1024, 512, 256]) + + # Or set up the model directory + # estimator = DNNClassifier( + # config=tf.estimator.RunConfig( + # model_dir='/my_model', save_summary_steps=100), + # feature_columns=[categorial_feature_a_emb, ...], + # hidden_units=[1024, 512, 256]) + + # Input pipeline for train and evaluate. + def train_input_fn(): # returns x, y + # please shuffle the data. + pass + def eval_input_fn(): # returns x, y + pass + + train_spec = tf.estimator.TrainSpec(input_fn=train_input_fn, max_steps=1000) + eval_spec = tf.estimator.EvalSpec(input_fn=eval_input_fn) + + tf.estimator.train_and_evaluate(estimator, train_spec, eval_spec) + ``` + Note that in current implementation `estimator.evaluate` will be called + multiple times. This means that evaluation graph (including eval_input_fn) + will be re-created for each `evaluate` call. `estimator.train` will be called + only once. + + Example of distributed training: + + Regarding the example of distributed training, the code above can be used + without a change (Please do make sure that the `RunConfig.model_dir` for all + workers is set to the same directory, i.e., a shared file system all workers + can read and write). The only extra work to do is setting the environment + variable `TF_CONFIG` properly for each worker correspondingly. + + Also see + [Distributed TensorFlow](https://www.tensorflow.org/deploy/distributed). + + Setting environment variable depends on the platform. For example, on Linux, + it can be done as follows (`$` is the shell prompt): + + ``` + $ TF_CONFIG='' python train_model.py + ``` + + For the content in `TF_CONFIG`, assume that the training cluster spec looks + like: + + ``` + cluster = {"chief": ["host0:2222"], + "worker": ["host1:2222", "host2:2222", "host3:2222"], + "ps": ["host4:2222", "host5:2222"]} + ``` + + Example of `TF_CONFIG` for chief training worker (must have one and only one): + + ``` + # This should be a JSON string, which is set as environment variable. Usually + # the cluster manager handles that. + TF_CONFIG='{ + "cluster": { + "chief": ["host0:2222"], + "worker": ["host1:2222", "host2:2222", "host3:2222"], + "ps": ["host4:2222", "host5:2222"] + }, + "task": {"type": "chief", "index": 0} + }' + ``` + Note that the chief worker also does the model training job, similar to other + non-chief training workers (see next paragraph). In addition to the model + training, it manages some extra work, e.g., checkpoint saving and restoring, + writing summaries, etc. + + Example of `TF_CONFIG` for non-chief training worker (optional, could be + multiple): + + ``` + # This should be a JSON string, which is set as environment variable. Usually + # the cluster manager handles that. + TF_CONFIG='{ + "cluster": { + "chief": ["host0:2222"], + "worker": ["host1:2222", "host2:2222", "host3:2222"], + "ps": ["host4:2222", "host5:2222"] + }, + "task": {"type": "worker", "index": 0} + }' + ``` + where the `task.index` should be set as 0, 1, 2, in this example, respectively + for non-chief training workers. + + Example of `TF_CONFIG` for parameter server, aka ps (could be multiple): + + ``` + # This should be a JSON string, which is set as environment variable. Usually + # the cluster manager handles that. + TF_CONFIG='{ + "cluster": { + "chief": ["host0:2222"], + "worker": ["host1:2222", "host2:2222", "host3:2222"], + "ps": ["host4:2222", "host5:2222"] + }, + "task": {"type": "ps", "index": 0} + }' + ``` + where the `task.index` should be set as 0 and 1, in this example, respectively + for parameter servers. + + Example of `TF_CONFIG` for evaluator task. Evaluator is a special task that is + not part of the training cluster. There could be only one. It is used for + model evaluation. + + ``` + # This should be a JSON string, which is set as environment variable. Usually + # the cluster manager handles that. + TF_CONFIG='{ + "cluster": { + "chief": ["host0:2222"], + "worker": ["host1:2222", "host2:2222", "host3:2222"], + "ps": ["host4:2222", "host5:2222"] + }, + "task": {"type": "evaluator", "index": 0} + }' + ``` + + When `distribute` or `experimental_distribute.train_distribute` and + `experimental_distribute.remote_cluster` is set, this method will start a + client running on the current host which connects to the `remote_cluster` for + training and evaluation. + + Args: + estimator: An `Estimator` instance to train and evaluate. + train_spec: A `TrainSpec` instance to specify the training specification. + eval_spec: A `EvalSpec` instance to specify the evaluation and export + specification. + + Returns: + A tuple of the result of the `evaluate` call to the `Estimator` and the + export results using the specified `Exporter`s. + Currently, the return value is undefined for distributed training mode. + + Raises: + ValueError: if environment variable `TF_CONFIG` is incorrectly set. + """ + _assert_eval_spec(eval_spec) # fail fast if eval_spec is invalid. + estimator_lib._estimator_api_gauge.get_cell('train_and_evaluate').set(True) # pylint: disable=protected-access + + executor = _TrainingExecutor( + estimator=estimator, train_spec=train_spec, eval_spec=eval_spec) + config = estimator.config + + # If `distribute_coordinator_mode` is set and running in distributed + # environment, we run `train_and_evaluate` via distribute coordinator. + if distribute_coordinator_training.should_run_distribute_coordinator(config): + tf.compat.v1.logging.info( + 'Running `train_and_evaluate` with Distribute Coordinator.') + distribute_coordinator_training.train_and_evaluate(estimator, train_spec, + eval_spec, + _TrainingExecutor) + return + + if (config.task_type == run_config_lib.TaskType.EVALUATOR and + config.task_id > 0): + raise ValueError( + 'For distributed training, there can only be one `evaluator` task ' + '(with task id 0). Given task id {}'.format(config.task_id)) + + return executor.run() + + +class _StopAtSecsHook(tf.compat.v1.train.SessionRunHook): + """Stops given secs after begin is called.""" + + def __init__(self, stop_after_secs): + self._stop_after_secs = stop_after_secs + self._start_time = None + + def begin(self): + self._start_time = time.time() + + def after_run(self, run_context, run_values): + del run_values + if time.time() - self._start_time >= self._stop_after_secs: + run_context.request_stop() + + +class _NewCheckpointListenerForEvaluate( + tf.compat.v1.train.CheckpointSaverListener): + """A saver listener to run evaluate with every checkpoint.""" + + def __init__(self, evaluator, eval_throttle_secs, continuous_eval_listener): + self._evaluator = evaluator + self._eval_throttle_secs = eval_throttle_secs + self._continuous_eval_listener = continuous_eval_listener + self.eval_result, self.export_results = None, None + + def begin(self): + self._timer = basic_session_run_hooks.SecondOrStepTimer( + every_secs=self._eval_throttle_secs) + self._is_first_run = True + + def after_save(self, session, global_step_value): + del session # unused; required by signature. + # skip first run model is not trained yet. + if self._is_first_run: + self._is_first_run = False + return + + if not self._continuous_eval_listener.before_eval(): + tf.compat.v1.logging.info( + 'Exiting training and evaluation loop, as requested by ' + '_ContinuousEvalListener.before_eval.') + return True + if self._timer.should_trigger_for_step(global_step_value): + self._evaluate(global_step_value) # updates self.eval_result + if not self._continuous_eval_listener.after_eval(self.eval_result): + tf.compat.v1.logging.info('Exiting evaluation, as requested by ' + '_ContinuousEvalListener.after_eval.') + return True + else: + # TODO(ispir): add remaining time in the log. + tf.compat.v1.logging.info( + 'Skip the current checkpoint eval due to throttle secs ' + '({} secs).'.format(self._eval_throttle_secs)) + + def end(self, session, global_step_value): + # Evaluate if the last step has not been evaluated, yet. + if global_step_value != self._timer.last_triggered_step(): + if self._continuous_eval_listener.before_eval(): + self._evaluate(global_step_value) + self._continuous_eval_listener.after_eval(self.eval_result) + + def _evaluate(self, global_step_value): + self._timer.update_last_triggered_step(global_step_value) + self.eval_result, self.export_results = ( + self._evaluator.evaluate_and_export()) + if self.eval_result.status != _EvalStatus.EVALUATED: + # This is unexpected; should never happen. + # Training should always end with a new checkpoint. + raise RuntimeError('There was no new checkpoint after the training. ' + 'Eval status: {}'.format(self.eval_result.status)) + + +class _TrainingExecutor(object): + """The executor to run `Estimator` training and evaluation. + + This implementation supports both distributed and non-distributed (aka local) + training and evaluation based on the setting in `tf.estimator.RunConfig`. + """ + + def __init__(self, + estimator, + train_spec, + eval_spec, + train_hooks=None, + continuous_eval_listener=None): + if not isinstance(estimator, + (estimator_lib.Estimator, estimator_lib.EstimatorV2)): + raise TypeError('`estimator` must have type `tf.estimator.Estimator`. ' + 'Got: {}'.format(type(estimator))) + self._estimator = estimator + + if not isinstance(train_spec, TrainSpec): + raise TypeError('`train_spec` must have type `tf.estimator.TrainSpec`. ' + 'Got: {}'.format(type(train_spec))) + self._train_spec = train_spec + + if eval_spec and not isinstance(eval_spec, EvalSpec): + raise TypeError('`eval_spec` must be either `None` or have type ' + '`tf.estimator.EvalSpec`. Got: {}'.format( + type(eval_spec))) + self._eval_spec = eval_spec + + self._train_hooks = _validate_hooks(train_hooks) + + if (continuous_eval_listener and + not isinstance(continuous_eval_listener, _ContinuousEvalListener)): + raise TypeError('`continuous_eval_listener` must have type ' + '`_ContinuousEvalListener`.') + self._continuous_eval_listener = ( + continuous_eval_listener or _ContinuousEvalListener()) + + @property + def estimator(self): + return self._estimator + + def run(self): + """Executes the run_foo for task type `foo`. + + `_TrainingExecutor` predefines the procedure for task type 'chief', + 'worker', 'ps', and 'evaluator'. For task type `foo`, the corresponding + procedure is `run_foo'. This `run` method invoke the procedure base on the + `RunConfig.task_type`. + + Returns: + A tuple of the result of the `evaluate` call to the `Estimator` and the + export results using the specified `ExportStrategy`. + Currently undefined for distributed training mode. + + Raises: + ValueError: if the estimator.config is mis-configured. + """ + config = self._estimator.config + + if (not config.cluster_spec and + config.task_type != run_config_lib.TaskType.EVALUATOR): + tf.compat.v1.logging.info( + 'Running training and evaluation locally (non-distributed).') + return self.run_local() + + # Distributed case. + if not config.task_type: + # TODO(xiejw): Improve the error message about how to set the TF_CONFIG + # correctly. + raise ValueError( + '`estimator.config` must have task_type set. This usually means ' + 'TF_CONFIG environment is not set correctly.') + + if config.task_type == 'local': + raise ValueError( + '`task.type` in TF_CONFIG cannot be `local`. Leaving `cluster` and ' + '`task` properties in TF_CONFIG absent triggers train and evaluate ' + '`Estimator` locally (non-distributed).') + + # For task type foo, call executor.run_foo. + available_tasks = [ + x for x in dir(self) if x.startswith('run_') and x != 'run_local' and + callable(getattr(self, x)) + ] + task_to_run = 'run_' + config.task_type + if task_to_run not in available_tasks: + raise ValueError( + 'Task type {} is not supported. Supported task types are {}'.format( + config.task_type, [x[len('run_'):] for x in available_tasks])) + getattr(self, task_to_run)() + + def run_chief(self): + """Runs task chief.""" + # TODO(xiejw): To allow execution framework to add train hooks. + return self._start_distributed_training( + saving_listeners=self._train_spec.saving_listeners) + + def run_worker(self): + """Runs task (training) worker.""" + # TODO(xiejw): To allow execution framework to add train hooks. + return self._start_distributed_training() + + def run_master(self): + """Runs task master.""" + _assert_eval_spec(self._eval_spec) + + # Final export signal: For any eval result with global_step >= train + # max_steps, the evaluator will send the final export signal. There is a + # small chance that the Estimator.train stopping logic sees a different + # global_step value (due to global step race condition and the fact the + # saver sees a larger value for checkpoint saving), which does not end + # the training. When the training ends, a new checkpoint is generated, which + # triggers the listener again. So, it could be the case the final export is + # triggered twice. + # + # But here, throttle_secs will skip the next intermediate checkpoint and, + # so, the double final export chance is very small. + evaluator = _TrainingExecutor._Evaluator(self._estimator, self._eval_spec, + self._train_spec.max_steps) + + # When the underlying `Estimator` object saves a new checkpoint, we would + # like this callback to be called so that evaluation and export can trigger. + saving_listeners = self._train_spec.saving_listeners + tuple( + [_NewCheckpointListenerForEvaluate(evaluator, + self._eval_spec.throttle_secs, + _ContinuousEvalListener())]) + self._start_distributed_training(saving_listeners=saving_listeners) + + def run_evaluator(self): + """Runs task evaluator.""" + # TODO(xiejw): To allow execution framework to add continuous eval listener. + return self._start_continuous_evaluation() + + def run_ps(self): + """Runs task parameter server (in training cluster spec).""" + config = self._estimator.config + server = self._start_std_server(config) + server.join() + + def run_local(self): + """Runs training and evaluation locally (non-distributed).""" + _assert_eval_spec(self._eval_spec) + + train_hooks = list(self._train_spec.hooks) + list(self._train_hooks) + tf.compat.v1.logging.info( + 'Start train and evaluate loop. The evaluate will happen ' + 'after every checkpoint. Checkpoint frequency is determined ' + 'based on RunConfig arguments: save_checkpoints_steps {} or ' + 'save_checkpoints_secs {}.'.format( + self._estimator.config.save_checkpoints_steps, + self._estimator.config.save_checkpoints_secs)) + + evaluator = _TrainingExecutor._Evaluator(self._estimator, self._eval_spec, + self._train_spec.max_steps) + + listener_for_eval = _NewCheckpointListenerForEvaluate( + evaluator, self._eval_spec.throttle_secs, + self._continuous_eval_listener) + saving_listeners = self._train_spec.saving_listeners + (listener_for_eval,) + + self._estimator.train( + input_fn=self._train_spec.input_fn, + max_steps=self._train_spec.max_steps, + hooks=train_hooks, + saving_listeners=saving_listeners) + + eval_result = listener_for_eval.eval_result or _EvalResult( + status=_EvalStatus.MISSING_CHECKPOINT) + return eval_result.metrics, listener_for_eval.export_results + + def _start_std_server(self, config): + """Creates, starts, and returns a server_lib.Server.""" + if (not config.cluster_spec or not config.task_type or + config.task_id is None): + raise RuntimeError('Could not start server; be sure to specify ' + 'cluster_spec, task_type, and task in ' + 'RunConfig or set the TF_CONFIG environment variable.') + + if not config.master: + jobs = config.cluster_spec.jobs + if (len(jobs) == 1 and + len(config.cluster_spec.job_tasks(jobs[0])) == 1 and + config.task_type in _TRAINER_JOBS): + # For distributed training, config.master is empty if and only if it has + # a single node in the cluster spec. In this case, we should not start + # the server. + tf.compat.v1.logging.info( + 'Skip starting Tensorflow server as there is only one ' + 'node in the cluster.') + return + else: + raise RuntimeError( + 'Could not start server; be sure to specify master in ' + 'RunConfig or set the TF_CONFIG environment variable.') + + tf.compat.v1.logging.info('Start Tensorflow server.') + + if config.session_config is None: + session_config = tf.compat.v1.ConfigProto(log_device_placement=False) + else: + session_config = tf.compat.v1.ConfigProto( + log_device_placement=False, + gpu_options=config.session_config.gpu_options) + + server = server_lib.Server( + config.cluster_spec, + job_name=config.task_type, + task_index=config.task_id, + config=session_config, + start=False, + protocol=config.protocol) + server.start() + return server + + def _start_distributed_training(self, saving_listeners=None): + """Calls `Estimator` train in a distributed setting.""" + config = self._estimator.config + + # Start in-process TensorFlow server if needed. It's important to start the + # server before we (optionally) sleep. Otherwise, the servers will wait to + # connect to each other before starting to train. + if not _is_google_env(): + self._start_std_server(config) + + # Delay worker to start. For asynchronous training, this usually helps model + # to converge faster. Chief starts the training immediately, so, worker + # with task id x (0-based) should wait (x+1) * _DELAY_SECS_PER_WORKER. + start_delay_secs = 0 + if config.task_type == run_config_lib.TaskType.WORKER: + # TODO(xiejw): Replace the hard code logic (task_id + 1) with unique id in + # training cluster. + + max_delay_secs = _MAX_DELAY_SECS + if config.experimental_max_worker_delay_secs is not None: + max_delay_secs = int(config.experimental_max_worker_delay_secs) + + start_delay_secs = min(max_delay_secs, + (config.task_id + 1) * _DELAY_SECS_PER_WORKER) + if start_delay_secs > 0: + tf.compat.v1.logging.info('Waiting %d secs before starting training.', + start_delay_secs) + time.sleep(start_delay_secs) + + self._estimator.train( + input_fn=self._train_spec.input_fn, + max_steps=self._train_spec.max_steps, + hooks=list(self._train_spec.hooks) + list(self._train_hooks), + saving_listeners=saving_listeners) + + def _start_continuous_evaluation(self): + """Repeatedly calls `Estimator` evaluate and export until training ends.""" + + _assert_eval_spec(self._eval_spec) + + start_delay_secs = self._eval_spec.start_delay_secs + if start_delay_secs: + tf.compat.v1.logging.info('Waiting %f secs before starting eval.', + start_delay_secs) + time.sleep(start_delay_secs) + + latest_eval_result = None + evaluator = _TrainingExecutor._Evaluator(self._estimator, self._eval_spec, + self._train_spec.max_steps) + + should_early_stop = False + while not should_early_stop: + if (latest_eval_result and + latest_eval_result.status == _EvalStatus.EVALUATED): + global_step = latest_eval_result.metrics.get( + tf.compat.v1.GraphKeys.GLOBAL_STEP) + if (global_step and self._train_spec.max_steps and + global_step >= self._train_spec.max_steps): + tf.compat.v1.logging.info( + 'Exiting evaluation, global_step=%s >= train max_steps=%s', + global_step, self._train_spec.max_steps) + return + + latest_eval_result, should_early_stop = self._execute_evaluator_once( + evaluator, self._continuous_eval_listener, + self._eval_spec.throttle_secs) + + def _execute_evaluator_once(self, evaluator, continuous_eval_listener, + throttle_secs): + """Executes the `evaluator`.""" + + _assert_eval_spec(self._eval_spec) + + start = time.time() + + eval_result = None + should_early_stop = False + + if not continuous_eval_listener.before_eval(): + tf.compat.v1.logging.info('Exiting evaluation, as requested by ' + '_ContinuousEvalListener.before_eval.') + should_early_stop = True + return (eval_result, should_early_stop) + + # Final export signal: For any eval result with global_step >= train + # max_steps, the evaluator will send the final export signal. The next + # iteration of while loop will end the continuous eval as the stopping + # condition is satisfied (both checks use the same global_step value, + # i.e., no race condition) + eval_result, _ = evaluator.evaluate_and_export() + + if not self._continuous_eval_listener.after_eval(eval_result): + tf.compat.v1.logging.info('Exiting evaluation, as requested by ' + '_ContinuousEvalListener.after_eval.') + should_early_stop = True + return (eval_result, should_early_stop) + + # Throttle if necessary. + elapsed_time = time.time() - start + difference = throttle_secs - elapsed_time + if difference > 0: + tf.compat.v1.logging.info( + 'Waiting %f secs before starting next eval run.', difference + ) + time.sleep(difference) + elif (throttle_secs == 0 and eval_result.status != _EvalStatus.EVALUATED): + # Prints a user-actionable warning to avoid unnecessary load on evaluator. + tf.compat.v1.logging.warning( + 'EvalSpec.throttle_secs is set as 0. This might overload the job ' + 'before finding (next) new checkpoint. Please consider to increase ' + 'it.') + + return (eval_result, should_early_stop) + + class _Evaluator(object): + """A helper class to call `Estimator.evaluate` and export model.""" + + def __init__(self, estimator, eval_spec, max_training_steps): + self._estimator = estimator + + _assert_eval_spec(eval_spec) + self._eval_spec = eval_spec + + self._is_final_export_triggered = False + self._previous_ckpt_path = None + self._last_warning_time = 0 + self._max_training_steps = max_training_steps + + @property + def is_final_export_triggered(self): + return self._is_final_export_triggered + + def evaluate_and_export(self): + """Evaluate and (maybe) export the current model. + + Returns: + A tuple of `EvalResult` instance and the export results. + + Raises: + RuntimeError: for any unexpected internal error. + TypeError: if evaluation result has wrong type. + """ + latest_ckpt_path = self._estimator.latest_checkpoint() + if not latest_ckpt_path: + self._log_err_msg('Estimator is not trained yet. Will start an ' + 'evaluation when a checkpoint is ready.') + return _EvalResult(status=_EvalStatus.MISSING_CHECKPOINT), [] + + if latest_ckpt_path == self._previous_ckpt_path: + self._log_err_msg( + 'No new checkpoint ready for evaluation. Skip the current ' + 'evaluation pass as evaluation results are expected to be same ' + 'for the same checkpoint.') + return _EvalResult(status=_EvalStatus.NO_NEW_CHECKPOINT), [] + + metrics = self._estimator.evaluate( + input_fn=self._eval_spec.input_fn, + steps=self._eval_spec.steps, + name=self._eval_spec.name, + checkpoint_path=latest_ckpt_path, + hooks=self._eval_spec.hooks) + + # _EvalResult validates the metrics. + eval_result = _EvalResult( + status=_EvalStatus.EVALUATED, + metrics=metrics, + checkpoint_path=latest_ckpt_path) + + is_the_final_export = ( + eval_result.metrics[tf.compat.v1.GraphKeys.GLOBAL_STEP] >= + self._max_training_steps if self._max_training_steps else False) + export_results = self._export_eval_result(eval_result, + is_the_final_export) + + if is_the_final_export: + tf.compat.v1.logging.debug( + 'Calling exporter with the `is_the_final_export=True`.') + self._is_final_export_triggered = True + + self._last_warning_time = 0 + self._previous_ckpt_path = latest_ckpt_path + return eval_result, export_results + + def _log_err_msg(self, message): + """Prints warning `message` every 10 mins.""" + current_time = time.time() + if current_time - self._last_warning_time > 600: + tf.compat.v1.logging.warning(message) + self._last_warning_time = current_time + + def _export_eval_result(self, eval_result, is_the_final_export): + """Export `eval_result` according to exporters in `EvalSpec`.""" + export_dir_base = os.path.join( + tf.compat.as_str_any(self._estimator.model_dir), + tf.compat.as_str_any('export')) + + export_results = [] + for exporter in self._eval_spec.exporters: + export_results.append( + exporter.export( + estimator=self._estimator, + export_path=os.path.join( + tf.compat.as_str_any(export_dir_base), + tf.compat.as_str_any(exporter.name)), + checkpoint_path=eval_result.checkpoint_path, + eval_result=eval_result.metrics, + is_the_final_export=is_the_final_export)) + return export_results + + +class _EvalStatus(object): + """The status of an evaluation event. + + For local training and evaluation, the status can only be `EVALUATED` as + `Estimator.train` always generates a new checkpoint. + + For distributed training and evaluation, a separated evaluator keeps looking + for new checkpoint. So, multiple situations might occur: + + - EVALUATED: A new checkpoint is found since last evaluation. + `Estimator.evaluate` will be invoked. + - MISSING_CHECKPOINT: No checkpoint can be found. Typically, this means + the trainer has not yet produced any checkpoint. + - NO_NEW_CHECKPOINT: No new checkpoint can be found since last evaluation. + Typically, this means the trainer has not yet produced any new checkpoint. + """ + + EVALUATED = 'evaluated' + MISSING_CHECKPOINT = 'missing checkpoint' + NO_NEW_CHECKPOINT = 'no new checkpoint' + + +class _EvalResult( + collections.namedtuple('EvalResult', + ['status', 'metrics', 'checkpoint_path'])): + """_EvalResult holds the result of an evaluation event.""" + + def __new__(cls, status, metrics=None, checkpoint_path=None): + """Creates a validated `_EvalResult`. + + Args: + status: See `_EvalStatus`. + metrics: The evaluation results returned by `Estimator.evaluate`. Only set + if status is `EVALUATED`. + checkpoint_path: The corresponding checkpoint path for the `metrics`. Only + set if status is `EVALUATED`. + + Returns: + A validated `_EvalResult` object. + + Raises: + ValueError: If validation fails. + TypeError: If any of the arguments is not the expected type. + """ + + if status != _EvalStatus.EVALUATED: + if metrics: + raise ValueError( + 'metrics must be `None` if status is not {}; got status {},' + ' metrics {}'.format(_EvalStatus.EVALUATED, status, metrics)) + if checkpoint_path: + raise ValueError( + 'checkpoint must be `None` if status is not {}; got status {}, ' + 'checkpoint_path {}'.format(_EvalStatus.EVALUATED, status, + checkpoint_path)) + return super(_EvalResult, cls).__new__(cls, status, metrics, + checkpoint_path) + + # Now, evaluated case. + assert status == _EvalStatus.EVALUATED + + # Validates metrics. + if not metrics: + raise ValueError( + 'Internal error: `Estimator.evaluate` should never return empty ' + 'metrics.') + if not isinstance(metrics, dict): + raise TypeError( + '`Estimator.evaluate` should return dict. Given {}.'.format( + type(metrics))) + if tf.compat.v1.GraphKeys.GLOBAL_STEP not in metrics: + raise ValueError( + 'Internal error: `Estimator.evaluate` result should have ' + '`global_step` in result. Given {}'.format(metrics)) + + # Validates checkpoint_path. + if not checkpoint_path: + raise ValueError( + 'Internal error: `checkpoint_path` should never be empty.') + + return super(_EvalResult, cls).__new__(cls, status, metrics, + checkpoint_path) + + +class _ContinuousEvalListener(object): + """Interface for listeners that take action before or after evaluation.""" + + def before_eval(self): + """Called before evaluation. + + Returns: + `False` if you want to skip the current evaluation and early stop the + continuous evaluation; `True` otherwise. + """ + return True + + def after_eval(self, eval_result): + """Called after the evaluation is executed. + + Args: + eval_result: An `_EvalResult` instance. + + Returns: + False if you want to early stop continuous evaluation; `True` otherwise. + """ + del eval_result + return True + + +def _assert_eval_spec(eval_spec): + """Raise error if `eval_spec` is not of the right type.""" + if not isinstance(eval_spec, EvalSpec): + raise TypeError('`eval_spec` must have type `tf.estimator.EvalSpec`. ' + 'Got: {}'.format(type(eval_spec))) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/util.py new file mode 100644 index 0000000000000000000000000000000000000000..c958473f00ef23400ffc646b0bf0ed78a6619d4c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_estimator/python/estimator/util.py @@ -0,0 +1,113 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Utilities for Estimators.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import time +import tensorflow as tf +from tensorflow.python.util import function_utils + +fn_args = function_utils.fn_args + +# When we create a timestamped directory, there is a small chance that the +# directory already exists because another process is also creating these +# directories. In this case we just wait one second to get a new timestamp and +# try again. If this fails several times in a row, then something is seriously +# wrong. +MAX_DIRECTORY_CREATION_ATTEMPTS = 10 + + +def parse_input_fn_result(result): + """Gets features, labels, and hooks from the result of an Estimator input_fn. + + Args: + result: output of an input_fn to an estimator, which should be one of: + * A 'tf.data.Dataset' object: Outputs of `Dataset` object must be a tuple + (features, labels) with same constraints as below. + * A tuple (features, labels): Where `features` is a `Tensor` or a + dictionary of string feature name to `Tensor` and `labels` is a `Tensor` + or a dictionary of string label name to `Tensor`. Both `features` and + `labels` are consumed by `model_fn`. They should satisfy the expectation + of `model_fn` from inputs. + + Returns: + Tuple of features, labels, and input_hooks, where features are as described + above, labels are as described above or None, and input_hooks are a list + of SessionRunHooks to be included when running. + + Raises: + ValueError: if the result is a list or tuple of length != 2. + """ + input_hooks = [] + if isinstance(result, tf.compat.v2.data.Dataset): + iterator = tf.compat.v1.data.make_initializable_iterator(result) + input_hooks.append(_DatasetInitializerHook(iterator)) + result = iterator.get_next() + return parse_iterator_result(result) + (input_hooks,) + + +def parse_iterator_result(result): + """Gets features, labels from result.""" + if isinstance(result, (list, tuple)): + if len(result) != 2: + raise ValueError( + 'input_fn should return (features, labels) as a len 2 tuple.') + return result[0], result[1] + return result, None + + +class _DatasetInitializerHook(tf.compat.v1.train.SessionRunHook): + """Creates a SessionRunHook that initializes the passed iterator.""" + + def __init__(self, iterator): + self._iterator = iterator + + def begin(self): + self._initializer = self._iterator.initializer + + def after_create_session(self, session, coord): + del coord + session.run(self._initializer) + + +class DistributedIteratorInitializerHook(tf.compat.v1.train.SessionRunHook): + """Creates a SessionRunHook that initializes the passed iterator.""" + + def __init__(self, iterator): + self._iterator = iterator + + def begin(self): + self._initializer = self._iterator.initialize() + + def after_create_session(self, session, coord): + del coord + session.run(self._initializer) + + +class MultiHostDatasetInitializerHook(tf.compat.v1.train.SessionRunHook): + """Creates a SessionRunHook that initializes all passed iterators.""" + + def __init__(self, dataset_initializers): + self._initializers = dataset_initializers + + def after_create_session(self, session, coord): + del coord + start = time.time() + session.run(self._initializers) + tf.compat.v1.logging.info('Initialized dataset iterators in %d seconds', + time.time() - start) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_io_gcs_filesystem-0.37.1.dist-info/INSTALLER b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_io_gcs_filesystem-0.37.1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_io_gcs_filesystem-0.37.1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_io_gcs_filesystem-0.37.1.dist-info/LICENSE b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_io_gcs_filesystem-0.37.1.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_io_gcs_filesystem-0.37.1.dist-info/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_io_gcs_filesystem-0.37.1.dist-info/METADATA b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_io_gcs_filesystem-0.37.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..ee5288e775936dfecc2c543d6a6d96059209142a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_io_gcs_filesystem-0.37.1.dist-info/METADATA @@ -0,0 +1,334 @@ +Metadata-Version: 2.1 +Name: tensorflow-io-gcs-filesystem +Version: 0.37.1 +Summary: TensorFlow IO +Home-page: https://github.com/tensorflow/io +Download-URL: https://github.com/tensorflow/io/tags +Author: Google Inc. +Author-email: opensource@google.com +Project-URL: Source, https://github.com/tensorflow/io +Project-URL: Bug Reports, https://github.com/tensorflow/io/issues +Project-URL: Documentation, https://tensorflow.org/io +Keywords: tensorflow io machine learning +Classifier: Development Status :: 4 - Beta +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: Education +Classifier: Intended Audience :: Science/Research +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Topic :: Scientific/Engineering +Classifier: Topic :: Scientific/Engineering :: Mathematics +Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence +Classifier: Topic :: Software Development +Classifier: Topic :: Software Development :: Libraries +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Requires-Python: >=3.7, <3.13 +Description-Content-Type: text/markdown +License-File: LICENSE +Provides-Extra: tensorflow +Requires-Dist: tensorflow <2.17.0,>=2.16.0 ; extra == 'tensorflow' +Provides-Extra: tensorflow-aarch64 +Requires-Dist: tensorflow-aarch64 <2.17.0,>=2.16.0 ; extra == 'tensorflow-aarch64' +Provides-Extra: tensorflow-cpu +Requires-Dist: tensorflow-cpu <2.17.0,>=2.16.0 ; extra == 'tensorflow-cpu' +Provides-Extra: tensorflow-gpu +Requires-Dist: tensorflow-gpu <2.17.0,>=2.16.0 ; extra == 'tensorflow-gpu' +Provides-Extra: tensorflow-rocm +Requires-Dist: tensorflow-rocm <2.17.0,>=2.16.0 ; extra == 'tensorflow-rocm' + +
+

+
+ +----------------- + +# TensorFlow I/O + +[![GitHub CI](https://github.com/tensorflow/io/workflows/GitHub%20CI/badge.svg?branch=master)](https://github.com/tensorflow/io/actions?query=branch%3Amaster) +[![PyPI](https://badge.fury.io/py/tensorflow-io.svg)](https://pypi.org/project/tensorflow-io/) +[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://github.com/tensorflow/io/blob/master/LICENSE) +[![Documentation](https://img.shields.io/badge/api-reference-blue.svg)](https://www.tensorflow.org/io) + +TensorFlow I/O is a collection of file systems and file formats that are not +available in TensorFlow's built-in support. A full list of supported file systems +and file formats by TensorFlow I/O can be found [here](https://www.tensorflow.org/io/api_docs/python/tfio). + +The use of tensorflow-io is straightforward with keras. Below is an example +to [Get Started with TensorFlow](https://www.tensorflow.org/tutorials/quickstart/beginner) with +the data processing aspect replaced by tensorflow-io: + +```python +import tensorflow as tf +import tensorflow_io as tfio + +# Read the MNIST data into the IODataset. +dataset_url = "https://storage.googleapis.com/cvdf-datasets/mnist/" +d_train = tfio.IODataset.from_mnist( + dataset_url + "train-images-idx3-ubyte.gz", + dataset_url + "train-labels-idx1-ubyte.gz", +) + +# Shuffle the elements of the dataset. +d_train = d_train.shuffle(buffer_size=1024) + +# By default image data is uint8, so convert to float32 using map(). +d_train = d_train.map(lambda x, y: (tf.image.convert_image_dtype(x, tf.float32), y)) + +# prepare batches the data just like any other tf.data.Dataset +d_train = d_train.batch(32) + +# Build the model. +model = tf.keras.models.Sequential( + [ + tf.keras.layers.Flatten(input_shape=(28, 28)), + tf.keras.layers.Dense(512, activation=tf.nn.relu), + tf.keras.layers.Dropout(0.2), + tf.keras.layers.Dense(10, activation=tf.nn.softmax), + ] +) + +# Compile the model. +model.compile( + optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"] +) + +# Fit the model. +model.fit(d_train, epochs=5, steps_per_epoch=200) +``` + +In the above [MNIST](http://yann.lecun.com/exdb/mnist/) example, the URL's +to access the dataset files are passed directly to the `tfio.IODataset.from_mnist` API call. +This is due to the inherent support that `tensorflow-io` provides for `HTTP`/`HTTPS` file system, +thus eliminating the need for downloading and saving datasets on a local directory. + +NOTE: Since `tensorflow-io` is able to detect and uncompress the MNIST dataset automatically if needed, +we can pass the URL's for the compressed files (gzip) to the API call as is. + +Please check the official [documentation](https://www.tensorflow.org/io) for more +detailed and interesting usages of the package. + +## Installation + +### Python Package + +The `tensorflow-io` Python package can be installed with pip directly using: +```sh +$ pip install tensorflow-io +``` + +People who are a little more adventurous can also try our nightly binaries: +```sh +$ pip install tensorflow-io-nightly +``` + +To ensure you have a version of TensorFlow that is compatible with TensorFlow-IO, +you can specify the `tensorflow` extra requirement during install: + +``` +pip install tensorflow-io[tensorflow] +``` + +Similar extras exist for the `tensorflow-gpu`, `tensorflow-cpu` and `tensorflow-rocm` +packages. + +### Docker Images + +In addition to the pip packages, the docker images can be used to quickly get started. + +For stable builds: +```sh +$ docker pull tfsigio/tfio:latest +$ docker run -it --rm --name tfio-latest tfsigio/tfio:latest +``` + +For nightly builds: +```sh +$ docker pull tfsigio/tfio:nightly +$ docker run -it --rm --name tfio-nightly tfsigio/tfio:nightly +``` + +### R Package + +Once the `tensorflow-io` Python package has been successfully installed, you +can install the development version of the R package from GitHub via the following: +```r +if (!require("remotes")) install.packages("remotes") +remotes::install_github("tensorflow/io", subdir = "R-package") +``` + +### TensorFlow Version Compatibility + +To ensure compatibility with TensorFlow, it is recommended to install a matching +version of TensorFlow I/O according to the table below. You can find the list +of releases [here](https://github.com/tensorflow/io/releases). + +| TensorFlow I/O Version | TensorFlow Compatibility | Release Date | +| --- | --- | --- | +| 0.37.1 | 2.16.x | Jul 01, 2024 | +| 0.37.0 | 2.16.x | Apr 25, 2024 | +| 0.36.0 | 2.15.x | Feb 02, 2024 | +| 0.35.0 | 2.14.x | Dec 18, 2023 | +| 0.34.0 | 2.13.x | Sep 08, 2023 | +| 0.33.0 | 2.13.x | Aug 01, 2023 | +| 0.32.0 | 2.12.x | Mar 28, 2023 | +| 0.31.0 | 2.11.x | Feb 25, 2023 | +| 0.30.0 | 2.11.x | Jan 20, 2023 | +| 0.29.0 | 2.11.x | Dec 18, 2022 | +| 0.28.0 | 2.11.x | Nov 21, 2022 | +| 0.27.0 | 2.10.x | Sep 08, 2022 | +| 0.26.0 | 2.9.x | May 17, 2022 | +| 0.25.0 | 2.8.x | Apr 19, 2022 | +| 0.24.0 | 2.8.x | Feb 04, 2022 | +| 0.23.1 | 2.7.x | Dec 15, 2021 | +| 0.23.0 | 2.7.x | Dec 14, 2021 | +| 0.22.0 | 2.7.x | Nov 10, 2021 | +| 0.21.0 | 2.6.x | Sep 12, 2021 | +| 0.20.0 | 2.6.x | Aug 11, 2021 | +| 0.19.1 | 2.5.x | Jul 25, 2021 | +| 0.19.0 | 2.5.x | Jun 25, 2021 | +| 0.18.0 | 2.5.x | May 13, 2021 | +| 0.17.1 | 2.4.x | Apr 16, 2021 | +| 0.17.0 | 2.4.x | Dec 14, 2020 | +| 0.16.0 | 2.3.x | Oct 23, 2020 | +| 0.15.0 | 2.3.x | Aug 03, 2020 | +| 0.14.0 | 2.2.x | Jul 08, 2020 | +| 0.13.0 | 2.2.x | May 10, 2020 | +| 0.12.0 | 2.1.x | Feb 28, 2020 | +| 0.11.0 | 2.1.x | Jan 10, 2020 | +| 0.10.0 | 2.0.x | Dec 05, 2019 | +| 0.9.1 | 2.0.x | Nov 15, 2019 | +| 0.9.0 | 2.0.x | Oct 18, 2019 | +| 0.8.1 | 1.15.x | Nov 15, 2019 | +| 0.8.0 | 1.15.x | Oct 17, 2019 | +| 0.7.2 | 1.14.x | Nov 15, 2019 | +| 0.7.1 | 1.14.x | Oct 18, 2019 | +| 0.7.0 | 1.14.x | Jul 14, 2019 | +| 0.6.0 | 1.13.x | May 29, 2019 | +| 0.5.0 | 1.13.x | Apr 12, 2019 | +| 0.4.0 | 1.13.x | Mar 01, 2019 | +| 0.3.0 | 1.12.0 | Feb 15, 2019 | +| 0.2.0 | 1.12.0 | Jan 29, 2019 | +| 0.1.0 | 1.12.0 | Dec 16, 2018 | + + +## Performance Benchmarking + +We use [github-pages](https://tensorflow.github.io/io/dev/bench/) to document the results of API performance benchmarks. The benchmark job is triggered on every commit to `master` branch and +facilitates tracking performance w.r.t commits. + +## Contributing + +Tensorflow I/O is a community led open source project. As such, the project +depends on public contributions, bug-fixes, and documentation. Please see: + +- [contribution guidelines](CONTRIBUTING.md) for a guide on how to contribute. +- [development doc](docs/development.md) for instructions on the development environment setup. +- [tutorials](docs/tutorials) for a list of tutorial notebooks and instructions on how to write one. + +### Build Status and CI + +| Build | Status | +| --- | --- | +| Linux CPU Python 2 | [![Status](https://storage.googleapis.com/tensorflow-kokoro-build-badges/io/ubuntu-py2.svg)](https://storage.googleapis.com/tensorflow-kokoro-build-badges/io/ubuntu-py2.html) | +| Linux CPU Python 3 | [![Status](https://storage.googleapis.com/tensorflow-kokoro-build-badges/io/ubuntu-py3.svg)](https://storage.googleapis.com/tensorflow-kokoro-build-badges/io/ubuntu-py3.html) | +| Linux GPU Python 2| [![Status](https://storage.googleapis.com/tensorflow-kokoro-build-badges/io/ubuntu-gpu-py2.svg)](https://storage.googleapis.com/tensorflow-kokoro-build-badges/io/ubuntu-gpu-py2.html) | +| Linux GPU Python 3| [![Status](https://storage.googleapis.com/tensorflow-kokoro-build-badges/io/ubuntu-gpu-py3.svg)](https://storage.googleapis.com/tensorflow-kokoro-build-badges/io/ubuntu-gpu-py3.html) | + +Because of manylinux2010 requirement, TensorFlow I/O is built with +Ubuntu:16.04 + Developer Toolset 7 (GCC 7.3) on Linux. Configuration +with Ubuntu 16.04 with Developer Toolset 7 is not exactly straightforward. +If the system have docker installed, then the following command +will automatically build manylinux2010 compatible whl package: + +```sh +#!/usr/bin/env bash + +ls dist/* +for f in dist/*.whl; do + docker run -i --rm -v $PWD:/v -w /v --net=host quay.io/pypa/manylinux2010_x86_64 bash -x -e /v/tools/build/auditwheel repair --plat manylinux2010_x86_64 $f +done +sudo chown -R $(id -nu):$(id -ng) . +ls wheelhouse/* +``` + +It takes some time to build, but once complete, there will be python +`3.5`, `3.6`, `3.7` compatible whl packages available in `wheelhouse` +directory. + +On macOS, the same command could be used. However, the script expects `python` in shell +and will only generate a whl package that matches the version of `python` in shell. If +you want to build a whl package for a specific python then you have to alias this version +of python to `python` in shell. See [.github/workflows/build.yml](.github/workflows/build.yml) +Auditwheel step for instructions how to do that. + +Note the above command is also the command we use when releasing packages for Linux and macOS. + +TensorFlow I/O uses both GitHub Workflows and Google CI (Kokoro) for continuous integration. +GitHub Workflows is used for macOS build and test. Kokoro is used for Linux build and test. +Again, because of the manylinux2010 requirement, on Linux whl packages are always +built with Ubuntu 16.04 + Developer Toolset 7. Tests are done on a variatiy of systems +with different python3 versions to ensure a good coverage: + +| Python | Ubuntu 18.04| Ubuntu 20.04 | macOS + osx9 | Windows-2019 | +| ------- | ----- | ------- | ------- | --------- | +| 2.7 | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | N/A | +| 3.7 | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | +| 3.8 | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | + + +TensorFlow I/O has integrations with many systems and cloud vendors such as +Prometheus, Apache Kafka, Apache Ignite, Google Cloud PubSub, AWS Kinesis, +Microsoft Azure Storage, Alibaba Cloud OSS etc. + +We tried our best to test against those systems in our continuous integration +whenever possible. Some tests such as Prometheus, Kafka, and Ignite +are done with live systems, meaning we install Prometheus/Kafka/Ignite on CI machine before +the test is run. Some tests such as Kinesis, PubSub, and Azure Storage are done +through official or non-official emulators. Offline tests are also performed whenever +possible, though systems covered through offine tests may not have the same +level of coverage as live systems or emulators. + + +| | Live System | Emulator| CI Integration | Offline | +| ------- | ----- | ----- | ----- | ----- | +| Apache Kafka | :heavy_check_mark: | | :heavy_check_mark:| | +| Apache Ignite | :heavy_check_mark: | |:heavy_check_mark:| | +| Prometheus | :heavy_check_mark: | |:heavy_check_mark:| | +| Google PubSub | | :heavy_check_mark: |:heavy_check_mark:| | +| Azure Storage | | :heavy_check_mark: |:heavy_check_mark:| | +| AWS Kinesis | | :heavy_check_mark: |:heavy_check_mark:| | +| Alibaba Cloud OSS | | | | :heavy_check_mark: | +| Google BigTable/BigQuery | | to be added | | | +| Elasticsearch (experimental) | :heavy_check_mark: | |:heavy_check_mark:| | +| MongoDB (experimental) | :heavy_check_mark: | |:heavy_check_mark:| | + + +References for emulators: +- Official [PubSub Emulator](https://cloud.google.com/sdk/gcloud/reference/beta/emulators/pubsub/) by Google Cloud for Cloud PubSub. +- Official [Azurite Emulator](https://github.com/Azure/Azurite) by Azure for Azure Storage. +- None-official [LocalStack emulator](https://github.com/localstack/localstack) by LocalStack for AWS Kinesis. + + +## Community + +* SIG IO [Google Group](https://groups.google.com/a/tensorflow.org/forum/#!forum/io) and mailing list: [io@tensorflow.org](io@tensorflow.org) +* SIG IO [Monthly Meeting Notes](https://docs.google.com/document/d/1CB51yJxns5WA4Ylv89D-a5qReiGTC0GYum6DU-9nKGo/edit) +* Gitter room: [tensorflow/sig-io](https://gitter.im/tensorflow/sig-io) + +## Additional Information + +* [Streaming Machine Learning with Tiered Storage and Without a Data Lake](https://www.confluent.io/blog/streaming-machine-learning-with-tiered-storage/) - [Kai Waehner](https://github.com/kaiwaehner) +* [TensorFlow with Apache Arrow Datasets](https://medium.com/tensorflow/tensorflow-with-apache-arrow-datasets-cdbcfe80a59f) - [Bryan Cutler](https://github.com/BryanCutler) +* [How to build a custom Dataset for Tensorflow](https://towardsdatascience.com/how-to-build-a-custom-dataset-for-tensorflow-1fe3967544d8) - [Ivelin Ivanov](https://github.com/ivelin) +* [TensorFlow on Apache Ignite](https://medium.com/tensorflow/tensorflow-on-apache-ignite-99f1fc60efeb) - [Anton Dmitriev](https://github.com/dmitrievanthony) + +## License + +[Apache License 2.0](LICENSE) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_io_gcs_filesystem-0.37.1.dist-info/RECORD b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_io_gcs_filesystem-0.37.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..2d0f0df1ee3793e48e591efdd611bbac5d07794f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_io_gcs_filesystem-0.37.1.dist-info/RECORD @@ -0,0 +1,15 @@ +tensorflow_io_gcs_filesystem-0.37.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +tensorflow_io_gcs_filesystem-0.37.1.dist-info/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357 +tensorflow_io_gcs_filesystem-0.37.1.dist-info/METADATA,sha256=bwKZdcG9RshdhrNz5Kt2wT9jOkTCT_rFGH1_5CqcbBU,14771 +tensorflow_io_gcs_filesystem-0.37.1.dist-info/RECORD,, +tensorflow_io_gcs_filesystem-0.37.1.dist-info/WHEEL,sha256=CzQQWV-lNyM92gr3iaBk8dvO35YDHRxgzkZ-dxumUIM,152 +tensorflow_io_gcs_filesystem-0.37.1.dist-info/top_level.txt,sha256=_D7B2mO0SFfak31jmeq5hQuWnU0EKPfSjC_DmAWGnMw,29 +tensorflow_io_gcs_filesystem/__init__.py,sha256=OPfiu9GzEKFL5sWrEOxTJA_65Pn-YMlQd4OTARJ-ej0,792 +tensorflow_io_gcs_filesystem/__pycache__/__init__.cpython-310.pyc,, +tensorflow_io_gcs_filesystem/core/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow_io_gcs_filesystem/core/__pycache__/__init__.cpython-310.pyc,, +tensorflow_io_gcs_filesystem/core/python/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tensorflow_io_gcs_filesystem/core/python/__pycache__/__init__.cpython-310.pyc,, +tensorflow_io_gcs_filesystem/core/python/ops/__init__.py,sha256=s09upE5CuuuGq7RdwDfPUWixnre5MSXA2x_hesrY_Bc,2502 +tensorflow_io_gcs_filesystem/core/python/ops/__pycache__/__init__.cpython-310.pyc,, +tensorflow_io_gcs_filesystem/core/python/ops/libtensorflow_io_gcs_filesystem.so,sha256=-hcjkVZ2bfpTts2p7kOE_1vdcvYBNCxy4MQrLYmanoE,20671000 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_io_gcs_filesystem-0.37.1.dist-info/WHEEL b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_io_gcs_filesystem-0.37.1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..9bb86cf30c63df9170e9af3dd246ce6f41270402 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_io_gcs_filesystem-0.37.1.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.43.0) +Root-Is-Purelib: false +Tag: cp310-cp310-manylinux_2_17_x86_64 +Tag: cp310-cp310-manylinux2014_x86_64 + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_io_gcs_filesystem-0.37.1.dist-info/top_level.txt b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_io_gcs_filesystem-0.37.1.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..c5940a4c4432aec8a8627e44d6d4755b346f09f4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_io_gcs_filesystem-0.37.1.dist-info/top_level.txt @@ -0,0 +1 @@ +tensorflow_io_gcs_filesystem diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_io_gcs_filesystem/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_io_gcs_filesystem/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e975da43ad13fbe6396aadbcca61b87c102b9ebb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_io_gcs_filesystem/__init__.py @@ -0,0 +1,17 @@ +# Copyright 2021 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""tensorflow_io_gcs_filesystem""" + +from tensorflow_io_gcs_filesystem.core.python.ops import plugin_gs diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_io_gcs_filesystem/core/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_io_gcs_filesystem/core/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_io_gcs_filesystem/core/python/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_io_gcs_filesystem/core/python/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_io_gcs_filesystem/core/python/ops/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_io_gcs_filesystem/core/python/ops/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f7c7ddcb62778398f54c0a96c8bb7cdf84e618af --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow_io_gcs_filesystem/core/python/ops/__init__.py @@ -0,0 +1,71 @@ +# Copyright 2021 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""GS""" + +import os +import ctypes +import sys +import inspect +import warnings +import types + +import tensorflow as tf + + +def _load_library(filename): + """_load_library""" + f = inspect.getfile(sys._getframe(1)) # pylint: disable=protected-access + + # Construct filename + f = os.path.join(os.path.dirname(f), filename) + filenames = [f] + + # Add datapath to load if en var is set, used for running tests where shared + # libraries are built in a different path + datapath = os.environ.get("TFIO_DATAPATH") + if datapath is not None: + # Build filename from: + # `datapath` + `tensorflow_io_package` + `package_name` + `relpath_to_library` + rootpath = os.path.dirname(sys.modules["tensorflow_io_gcs_filesystem"].__file__) + filename = sys.modules[__name__].__file__ + f = os.path.join( + datapath, + "tensorflow_io_gcs_filesystem", + os.path.relpath(os.path.dirname(filename), rootpath), + os.path.relpath(f, os.path.dirname(filename)), + ) + filenames.append(f) + # Function to load the library, return True if file system library is loaded + load_fn = lambda f: tf.experimental.register_filesystem_plugin(f) is None + + # Try to load all paths for file, fail if none succeed + errs = [] + for f in filenames: + try: + l = load_fn(f) + if l is not None: + return l + except (tf.errors.NotFoundError, OSError) as e: + errs.append(str(e)) + raise NotImplementedError( + "unable to open file: " + + f"{filename}, from paths: {filenames}\ncaused by: {errs}" + ) + + +try: + plugin_gs = _load_library("libtensorflow_io_gcs_filesystem.so") +except NotImplementedError as e: + warnings.warn(f"file system plugin for gs are not loaded: {e}") diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/termcolor-3.3.0.dist-info/INSTALLER b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/termcolor-3.3.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/termcolor-3.3.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/termcolor-3.3.0.dist-info/METADATA b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/termcolor-3.3.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..77c1c7eb63cda1075a4bb359980d331a5c56a46b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/termcolor-3.3.0.dist-info/METADATA @@ -0,0 +1,150 @@ +Metadata-Version: 2.4 +Name: termcolor +Version: 3.3.0 +Summary: ANSI color formatting for output in terminal +Project-URL: Changelog, https://github.com/termcolor/termcolor/releases +Project-URL: Homepage, https://github.com/termcolor/termcolor +Project-URL: Source, https://github.com/termcolor/termcolor +Author-email: Konstantin Lepa +Maintainer: Hugo van Kemenade +License-Expression: MIT +License-File: COPYING.txt +Keywords: ANSI,ANSI color,ANSI colour,color,colour,formatting,termcolor,terminal +Classifier: Development Status :: 5 - Production/Stable +Classifier: Environment :: Console +Classifier: Intended Audience :: Developers +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Programming Language :: Python :: 3.15 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Topic :: Terminals +Classifier: Typing :: Typed +Requires-Python: >=3.10 +Provides-Extra: tests +Requires-Dist: pytest; extra == 'tests' +Requires-Dist: pytest-cov; extra == 'tests' +Description-Content-Type: text/markdown + +# termcolor + +[![PyPI version](https://img.shields.io/pypi/v/termcolor.svg?logo=pypi&logoColor=FFE873)](https://pypi.org/project/termcolor) +[![Supported Python versions](https://img.shields.io/pypi/pyversions/termcolor.svg?logo=python&logoColor=FFE873)](https://pypi.org/project/termcolor) +[![PyPI downloads](https://img.shields.io/pypi/dm/termcolor.svg)](https://pypistats.org/packages/termcolor) +[![GitHub Actions status](https://github.com/termcolor/termcolor/workflows/Test/badge.svg)](https://github.com/termcolor/termcolor/actions) +[![Codecov](https://codecov.io/gh/termcolor/termcolor/branch/main/graph/badge.svg)](https://codecov.io/gh/termcolor/termcolor) +[![Licence](https://img.shields.io/github/license/termcolor/termcolor.svg)](COPYING.txt) +[![Code style: Black](https://img.shields.io/badge/code%20style-Black-000000.svg)](https://github.com/psf/black) +[![Tidelift](https://tidelift.com/badges/package/pypi/termcolor)](https://tidelift.com/subscription/pkg/pypi-termcolor?utm_source=pypi-termcolor&utm_medium=referral&utm_campaign=readme) + +## Installation + +### From PyPI + +```bash +python3 -m pip install --upgrade termcolor +``` + +### From source + +```bash +git clone https://github.com/termcolor/termcolor +cd termcolor +python3 -m pip install . +``` + +### Demo + +To see demo output, run: + +```bash +python3 -m termcolor +``` + +## Example + +```python +import sys + +from termcolor import colored, cprint + +text = colored("Hello, World!", "red", attrs=["reverse", "blink"]) +print(text) +cprint("Hello, World!", "green", "on_red") + +print_red_on_cyan = lambda x: cprint(x, "red", "on_cyan") +print_red_on_cyan("Hello, World!") +print_red_on_cyan("Hello, Universe!") + +for i in range(10): + cprint(i, "magenta", end=" ") + +cprint("Attention!", "red", attrs=["bold"], file=sys.stderr) + +# You can also specify 0-255 RGB ints via a tuple +cprint("Both foreground and background can use tuples", (100, 150, 250), (50, 60, 70)) +``` + +## Text properties + +| Text colors | Text highlights | Attributes | +| --------------- | ------------------ | ----------- | +| `black` | `on_black` | `bold` | +| `red` | `on_red` | `dark` | +| `green` | `on_green` | `italic` | +| `yellow` | `on_yellow` | `underline` | +| `blue` | `on_blue` | `blink` | +| `magenta` | `on_magenta` | `reverse` | +| `cyan` | `on_cyan` | `concealed` | +| `white` | `on_white` | `strike` | +| `light_grey` | `on_light_grey` | | +| `dark_grey` | `on_dark_grey` | | +| `light_red` | `on_light_red` | | +| `light_green` | `on_light_green` | | +| `light_yellow` | `on_light_yellow` | | +| `light_blue` | `on_light_blue` | | +| `light_magenta` | `on_light_magenta` | | +| `light_cyan` | `on_light_cyan` | | + +You can also use any arbitrary RGB color specified as a tuple of 0-255 integers, for +example, `(100, 150, 250)`. + +## Terminal properties + +| Terminal | bold | dark | italic | underline | blink | reverse | concealed | +| ------------ | ------- | ---- | ------ | --------- | ---------- | ------- | --------- | +| xterm | yes | no | yes | yes | bold | yes | yes | +| linux | yes | yes | color | bold | yes | yes | no | +| rxvt | yes | no | yes | yes | bold/black | yes | no | +| dtterm | yes | yes | ? | yes | reverse | yes | yes | +| teraterm | reverse | no | ? | yes | rev/red | yes | no | +| aixterm | normal | no | ? | yes | no | yes | yes | +| PuTTY | color | no | no | yes | no | yes | no | +| Windows | no | no | no | no | no | yes | no | +| Cygwin SSH | yes | no | ? | color | color | color | yes | +| Mac Terminal | yes | no | yes | yes | yes | yes | yes | + +## Overrides + +Terminal colour detection can be disabled or enabled in several ways. + +In order of precedence: + +1. Calling `colored` or `cprint` with a truthy `no_color` disables colour. +2. Calling `colored` or `cprint` with a truthy `force_color` forces colour. +3. Setting the `ANSI_COLORS_DISABLED` environment variable to any non-empty value + disables colour. +4. Setting the [`NO_COLOR`](https://no-color.org/) environment variable to any non-empty + value disables colour. +5. Setting the [`FORCE_COLOR`](https://force-color.org/) environment variable to any + non-empty value forces colour. +6. Setting the `TERM` environment variable to `dumb`, or using such a + [dumb terminal](https://en.wikipedia.org/wiki/Computer_terminal#Character-oriented_terminal), + disables colour. +7. Finally, termcolor will attempt to detect whether the terminal supports colour. diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/termcolor-3.3.0.dist-info/RECORD b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/termcolor-3.3.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..d37a9e594e5362f10ed96380a2d6f8588c304663 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/termcolor-3.3.0.dist-info/RECORD @@ -0,0 +1,12 @@ +termcolor-3.3.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +termcolor-3.3.0.dist-info/METADATA,sha256=iArqumMAZ31OzAIvtj-K3NV6dTtv0rXsF4Qfci-RAZY,6490 +termcolor-3.3.0.dist-info/RECORD,, +termcolor-3.3.0.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87 +termcolor-3.3.0.dist-info/licenses/COPYING.txt,sha256=55tr2CliwTMMqqfEInhWewhmd3dnP44jcaYk1XFdTA4,1072 +termcolor/__init__.py,sha256=oCqIPpywlruBk5YFDCVd7kSOdtXo0FHXjEXwnt_Pc0E,350 +termcolor/__main__.py,sha256=_-zbpu_lWx_v8uf8MDu-98NOwA0QZ6CUcWysIoHYRzM,3578 +termcolor/__pycache__/__init__.cpython-310.pyc,, +termcolor/__pycache__/__main__.cpython-310.pyc,, +termcolor/__pycache__/termcolor.cpython-310.pyc,, +termcolor/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +termcolor/termcolor.py,sha256=uqGaHvcIVMsXYZoi5CZaOfk4yRSlze-DSxy_fyQ9tI8,6315 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/termcolor-3.3.0.dist-info/WHEEL b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/termcolor-3.3.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..ae8ec1bdaa94d726ceb907542d76cbd5d38cafcd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/termcolor-3.3.0.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: hatchling 1.28.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/termcolor-3.3.0.dist-info/licenses/COPYING.txt b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/termcolor-3.3.0.dist-info/licenses/COPYING.txt new file mode 100644 index 0000000000000000000000000000000000000000..d0b79705c354418108635b67e17ee15443a4a130 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/termcolor-3.3.0.dist-info/licenses/COPYING.txt @@ -0,0 +1,19 @@ +Copyright (c) 2008-2011 Volvox Development Team + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/termcolor/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/termcolor/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c046c06f6b26aa0bd8c0c8ff320582194d9176e2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/termcolor/__init__.py @@ -0,0 +1,23 @@ +"""ANSI color formatting for output in terminal.""" + +from __future__ import annotations + +from termcolor.termcolor import ( + ATTRIBUTES, + COLORS, + HIGHLIGHTS, + RESET, + can_colorize, + colored, + cprint, +) + +__all__ = [ + "ATTRIBUTES", + "COLORS", + "HIGHLIGHTS", + "RESET", + "can_colorize", + "colored", + "cprint", +] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/termcolor/__main__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/termcolor/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..a7bf672227323f31f0e556b887eb7f6f46d4dbbf --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/termcolor/__main__.py @@ -0,0 +1,87 @@ +from __future__ import annotations + +import os + +from termcolor import cprint + +if __name__ == "__main__": + print(f"Current terminal type: {os.getenv('TERM')}") + print("Test basic colors:") + cprint("Black color", "black") + cprint("Red color", "red") + cprint("Green color", "green") + cprint("Yellow color", "yellow") + cprint("Blue color", "blue") + cprint("Magenta color", "magenta") + cprint("Cyan color", "cyan") + cprint("White color", "white") + cprint("Light grey color", "light_grey") + cprint("Dark grey color", "dark_grey") + cprint("Light red color", "light_red") + cprint("Light green color", "light_green") + cprint("Light yellow color", "light_yellow") + cprint("Light blue color", "light_blue") + cprint("Light magenta color", "light_magenta") + cprint("Light cyan color", "light_cyan") + print("-" * 78) + + print("Test highlights:") + cprint("On black color", on_color="on_black") + cprint("On red color", on_color="on_red") + cprint("On green color", on_color="on_green") + cprint("On yellow color", on_color="on_yellow") + cprint("On blue color", on_color="on_blue") + cprint("On magenta color", on_color="on_magenta") + cprint("On cyan color", on_color="on_cyan") + cprint("On white color", color="black", on_color="on_white") + cprint("On light grey color", on_color="on_light_grey") + cprint("On dark grey color", on_color="on_dark_grey") + cprint("On light red color", on_color="on_light_red") + cprint("On light green color", on_color="on_light_green") + cprint("On light yellow color", on_color="on_light_yellow") + cprint("On light blue color", on_color="on_light_blue") + cprint("On light magenta color", on_color="on_light_magenta") + cprint("On light cyan color", on_color="on_light_cyan") + print("-" * 78) + + print("Test attributes:") + cprint("Bold black color", "black", attrs=["bold"]) + cprint("Dark red color", "red", attrs=["dark"]) + cprint("Italic blue color", "blue", attrs=["italic"]) + cprint("Underline green color", "green", attrs=["underline"]) + cprint("Blink yellow color", "yellow", attrs=["blink"]) + cprint("Reversed blue color", "blue", attrs=["reverse"]) + cprint("Concealed magenta color", "magenta", attrs=["concealed"]) + cprint("Strike red color", "red", attrs=["strike"]) + cprint( + "Bold underline reverse cyan color", + "cyan", + attrs=["bold", "underline", "reverse"], + ) + cprint( + "Dark blink concealed white color", + "white", + attrs=["dark", "blink", "concealed"], + ) + print("-" * 78) + + print("Test mixing:") + cprint("Underline red on black color", "red", "on_black", ["underline"]) + cprint("Reversed green on red color", "green", "on_red", ["reverse"]) + print("-" * 78) + + print("Test RGB:") + cprint("Pure red text (255, 0, 0)", (255, 0, 0)) + cprint("Default red for comparison", "red") + cprint("Pure green text (0, 0, 0)", (0, 255, 0)) + cprint("Default green for comparison", "green") + cprint("Pure blue text (0, 0, 0)", (0, 0, 255)) + cprint("Default blue for comparison", "blue") + cprint("Pure yellow text (255, 255, 0)", (255, 255, 0)) + cprint("Default yellow for comparison", "yellow") + cprint("Pure cyan text (0, 255, 255)", (0, 255, 255)) + cprint("Default cyan for comparison", "cyan") + cprint("Pure magenta text (255, 0, 255)", (255, 0, 255)) + cprint("Default magenta for comparison", "magenta") + cprint("Light pink (255, 182, 193)", (255, 182, 193)) + cprint("Light pink (255, 105, 180)", (255, 105, 180)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/termcolor/py.typed b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/termcolor/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/termcolor/termcolor.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/termcolor/termcolor.py new file mode 100644 index 0000000000000000000000000000000000000000..e288b403b1163e17f81148f9b70fe34b0661b63f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/termcolor/termcolor.py @@ -0,0 +1,215 @@ +# Copyright (c) 2008-2011 Volvox Development Team +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# +# Author: Konstantin Lepa + +"""ANSI color formatting for output in terminal.""" + +from __future__ import annotations + +import os +import sys +from functools import cache + +TYPE_CHECKING = False +if TYPE_CHECKING: + from collections.abc import Iterable + from typing import Any + + +ATTRIBUTES: dict[str, int] = { + "bold": 1, + "dark": 2, + "italic": 3, + "underline": 4, + "blink": 5, + "reverse": 7, + "concealed": 8, + "strike": 9, +} + +HIGHLIGHTS: dict[str, int] = { + "on_black": 40, + "on_grey": 40, # Actually black but kept for backwards compatibility + "on_red": 41, + "on_green": 42, + "on_yellow": 43, + "on_blue": 44, + "on_magenta": 45, + "on_cyan": 46, + "on_light_grey": 47, + "on_dark_grey": 100, + "on_light_red": 101, + "on_light_green": 102, + "on_light_yellow": 103, + "on_light_blue": 104, + "on_light_magenta": 105, + "on_light_cyan": 106, + "on_white": 107, +} + +COLORS: dict[str, int] = { + "black": 30, + "grey": 30, # Actually black but kept for backwards compatibility + "red": 31, + "green": 32, + "yellow": 33, + "blue": 34, + "magenta": 35, + "cyan": 36, + "light_grey": 37, + "dark_grey": 90, + "light_red": 91, + "light_green": 92, + "light_yellow": 93, + "light_blue": 94, + "light_magenta": 95, + "light_cyan": 96, + "white": 97, +} + + +RESET = "\033[0m" + + +@cache +def can_colorize( + *, no_color: bool | None = None, force_color: bool | None = None +) -> bool: + """Check env vars and for tty/dumb terminal""" + # First check overrides: + # "User-level configuration files and per-instance command-line arguments should + # override $NO_COLOR. A user should be able to export $NO_COLOR in their shell + # configuration file as a default, but configure a specific program in its + # configuration file to specifically enable color." + # https://no-color.org + if no_color is not None and no_color: + return False + if force_color is not None and force_color: + return True + + # Then check env vars: + if os.environ.get("ANSI_COLORS_DISABLED"): + return False + if os.environ.get("NO_COLOR"): + return False + if os.environ.get("FORCE_COLOR"): + return True + + # Then check system: + if os.environ.get("TERM") == "dumb": + return False + if not hasattr(sys.stdout, "fileno"): + return False + + try: + return os.isatty(sys.stdout.fileno()) + except OSError: + return sys.stdout.isatty() + + +def colored( + text: object, + color: str | tuple[int, int, int] | None = None, + on_color: str | tuple[int, int, int] | None = None, + attrs: Iterable[str] | None = None, + *, + no_color: bool | None = None, + force_color: bool | None = None, +) -> str: + """Colorize text. + + Available text colors: + black, red, green, yellow, blue, magenta, cyan, white, + light_grey, dark_grey, light_red, light_green, light_yellow, light_blue, + light_magenta, light_cyan. + + Available text highlights: + on_black, on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan, on_white, + on_light_grey, on_dark_grey, on_light_red, on_light_green, on_light_yellow, + on_light_blue, on_light_magenta, on_light_cyan. + + Alternatively, both text colors (color) and highlights (on_color) may + be specified via a tuple of 0-255 ints (R, G, B). + + Available attributes: + bold, dark, italic, underline, blink, reverse, concealed, strike. + + Example: + colored('Hello, World!', 'red', 'on_black', ['bold', 'blink']) + colored('Hello, World!', 'green') + colored('Hello, World!', (255, 0, 255)) # Purple + """ + result = str(text) + if not can_colorize(no_color=no_color, force_color=force_color): + return result + + fmt_str = "\033[%dm%s" + rgb_fore_fmt_str = "\033[38;2;%d;%d;%dm%s" + rgb_back_fmt_str = "\033[48;2;%d;%d;%dm%s" + if color is not None: + if isinstance(color, str): + result = fmt_str % (COLORS[color], result) + elif isinstance(color, tuple): + result = rgb_fore_fmt_str % (color[0], color[1], color[2], result) + + if on_color is not None: + if isinstance(on_color, str): + result = fmt_str % (HIGHLIGHTS[on_color], result) + elif isinstance(on_color, tuple): + result = rgb_back_fmt_str % (on_color[0], on_color[1], on_color[2], result) + + if attrs is not None: + for attr in attrs: + result = fmt_str % (ATTRIBUTES[attr], result) + + result += RESET + + return result + + +def cprint( + text: object, + color: str | tuple[int, int, int] | None = None, + on_color: str | tuple[int, int, int] | None = None, + attrs: Iterable[str] | None = None, + *, + no_color: bool | None = None, + force_color: bool | None = None, + **kwargs: Any, +) -> None: + """Print colorized text. + + It accepts arguments of print function. + """ + + print( + ( + colored( + text, + color, + on_color, + attrs, + no_color=no_color, + force_color=force_color, + ) + ), + **kwargs, + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/test/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/test/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6a0a8de5827ad542590bcb70da98e73d298683c2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/test/__init__.py @@ -0,0 +1 @@ +"""Tests for unfoldNd.""" diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/test/fold_settings.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/test/fold_settings.py new file mode 100644 index 0000000000000000000000000000000000000000..e18f323a3888052a1253bc5809dc27692b63ecf3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/test/fold_settings.py @@ -0,0 +1,198 @@ +"""Problem settings for N-dimensional fold.""" + +from test.utils import get_available_devices, make_id + +import torch + +DEVICES = get_available_devices() +DEVICES_ID = [f"device={dev}" for dev in DEVICES] + +PROBLEMS_2D = [ + { + "seed": 0, + "input_fn": lambda: torch.rand(2, 3 * 2 * 2, 12), + "fold_kwargs": { + "output_size": (4, 5), + "kernel_size": (2, 2), + }, + }, + { + "seed": 0, + "input_fn": lambda: torch.rand(2, 3 * 2 * 2, 5 * 9), + "fold_kwargs": { + "output_size": (4, 8), + "kernel_size": 2, + "padding": 1, + }, + "id": "bug30-fold-with-padding", + }, +] +PROBLEMS_2D_IDS = [make_id(problem) for problem in PROBLEMS_2D] + +UNSUPPORTED_ARGS_PROBLEMS = [ + # output size is integer + { + "seed": 0, + "input_fn": lambda: torch.rand(2, 3 * 2 * 2, 12), + "fold_kwargs": { + "output_size": 4, + "kernel_size": (2, 2), + }, + }, +] +UNSUPPORTED_ARGS_PROBLEMS_IDS = [ + make_id(problem) for problem in UNSUPPORTED_ARGS_PROBLEMS +] + +PRECISION_PROBLEMS_2D = [ + # out-of-bounds error because float index is rounded up + { + "seed": 0, + "input_fn": lambda: torch.rand(1, 1 * 2 * 2, 25), + "fold_kwargs": { + # > smallest int which is exact as float32, 2 ** 24 = 116777217 + # (see https://stackoverflow.com/q/27207149 for details) + "output_size": (2**12 + 2, 2**12 + 2), + "kernel_size": (2, 2), + "stride": 2**10, + }, + }, + # wrong result due to wrong float → long conversion + { + "seed": 0, + "input_fn": lambda: torch.rand(1, 1 * 2 * 2, 25), + "fold_kwargs": { + # > smallest int which is exact as float32, 2 ** 24 = 116777217 + # (see https://stackoverflow.com/q/27207149 for details) + "output_size": (5000, 5000), + "kernel_size": (2, 2), + "stride": 1000, + }, + }, +] +PRECISION_PROBLEMS_2D_IDS = [make_id(problem) for problem in PRECISION_PROBLEMS_2D] + +# Settings must satisfy ``fold(unfold(input)) = input`` +PROBLEMS_INVERSE = [ + # 1d basic + { + "seed": 0, + "input_fn": lambda: torch.rand(2, 3, 50), + "unfold_kwargs": { + "kernel_size": 2, + "stride": 2, + }, + }, + # 1d with dilation + { + "seed": 1, + "input_fn": lambda: torch.rand(2, 3, 50), + "unfold_kwargs": { + "kernel_size": 5, + "dilation": 10, + "stride": 1, + }, + }, + # 1d with padding + { + "seed": 2, + "input_fn": lambda: torch.rand(2, 3, 50), + "unfold_kwargs": { + "kernel_size": 4, + "padding": 2, + "stride": 4, + }, + }, + # 1d with padding and dilation + { + "seed": 3, + "input_fn": lambda: torch.rand(2, 3, 50), + "unfold_kwargs": { + "kernel_size": 3, + "dilation": 18, + "stride": 1, + "padding": 2, + }, + }, + # 2d basic + { + "seed": 0, + "input_fn": lambda: torch.rand(2, 3, 50, 40), + "unfold_kwargs": { + "kernel_size": 2, + "stride": 2, + }, + }, + # 2d with dilation + { + "seed": 1, + "input_fn": lambda: torch.rand(2, 3, 50, 40), + "unfold_kwargs": { + "kernel_size": (5, 2), + "stride": (1, 1), + "dilation": (10, 20), + }, + }, + # 2d with padding + { + "seed": 2, + "input_fn": lambda: torch.rand(2, 3, 50, 40), + "unfold_kwargs": { + "kernel_size": (4, 3), + "padding": (2, 1), + "stride": (4, 3), + }, + }, + # 2d with padding and dilation + { + "seed": 3, + "input_fn": lambda: torch.rand(2, 3, 50, 40), + "unfold_kwargs": { + "kernel_size": (3, 2), + "dilation": (18, 21), + "stride": (1, 1), + "padding": (2, 1), + }, + }, + # 3d basic + { + "seed": 0, + "input_fn": lambda: torch.rand(2, 3, 50, 40, 30), + "unfold_kwargs": { + "kernel_size": 2, + "stride": 2, + }, + }, + # 3d with dilation + { + "seed": 1, + "input_fn": lambda: torch.rand(2, 3, 50, 40, 30), + "unfold_kwargs": { + "kernel_size": (5, 2, 6), + "stride": (1, 1, 1), + "dilation": (10, 20, 5), + }, + }, + # 3d with padding + { + "seed": 2, + "input_fn": lambda: torch.rand(2, 3, 50, 40, 30), + "unfold_kwargs": { + "kernel_size": (4, 3, 6), + "padding": (2, 1, 3), + "stride": (4, 3, 6), + }, + }, + # 3d with padding and dilation + { + "seed": 3, + "input_fn": lambda: torch.rand(2, 3, 50, 40, 30), + "unfold_kwargs": { + "kernel_size": (3, 2, 4), + "dilation": (18, 21, 9), + "stride": (1, 1, 1), + "padding": (2, 1, 3), + }, + }, +] +PROBLEMS_INVERSE_IDS = [make_id(problem) for problem in PROBLEMS_INVERSE] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/test/test_fold.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/test/test_fold.py new file mode 100644 index 0000000000000000000000000000000000000000..49c916a43d78137ea22a94b7071b91fb7165c321 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/test/test_fold.py @@ -0,0 +1,197 @@ +"""Tests for ``unfoldNd/fold.py.`` (fold functionality).""" + +from test.fold_settings import ( + DEVICES, + DEVICES_ID, + PRECISION_PROBLEMS_2D, + PRECISION_PROBLEMS_2D_IDS, + PROBLEMS_2D, + PROBLEMS_2D_IDS, + PROBLEMS_INVERSE, + PROBLEMS_INVERSE_IDS, + UNSUPPORTED_ARGS_PROBLEMS, + UNSUPPORTED_ARGS_PROBLEMS_IDS, +) +from test.unfold_settings import PROBLEMS_1D as UNFOLD_PROBLEMS_1D +from test.unfold_settings import PROBLEMS_1D_IDS as UNFOLD_PROBLEMS_1D_IDS +from test.unfold_settings import PROBLEMS_2D as UNFOLD_PROBLEMS_2D +from test.unfold_settings import PROBLEMS_2D_IDS as UNFOLD_PROBLEMS_2D_IDS +from test.unfold_settings import PROBLEMS_3D as UNFOLD_PROBLEMS_3D +from test.unfold_settings import PROBLEMS_3D_IDS as UNFOLD_PROBLEMS_3D_IDS +from test.utils import _add_dummy_dim + +import pytest +import torch + +import unfoldNd + + +@pytest.mark.parametrize("device", DEVICES, ids=DEVICES_ID) +@pytest.mark.parametrize( + "problem", UNSUPPORTED_ARGS_PROBLEMS, ids=UNSUPPORTED_ARGS_PROBLEMS_IDS +) +def test_FoldNd_unsupported_args(problem, device): + """Check unsupported arguments of ``FoldNd``.""" + seed = problem["seed"] + input_fn = problem["input_fn"] + fold_kwargs = problem["fold_kwargs"] + + torch.manual_seed(seed) + inputs = input_fn().to(device) + + with pytest.raises(ValueError): + _ = unfoldNd.FoldNd(**fold_kwargs).to(device)(inputs) + + +@pytest.mark.parametrize("device", DEVICES, ids=DEVICES_ID) +@pytest.mark.parametrize("problem", PROBLEMS_2D, ids=PROBLEMS_2D_IDS) +def test_Fold2d_vs_Fold(problem, device): + """Compare with ``torch.nn.Fold`` for a 4d input.""" + seed = problem["seed"] + input_fn = problem["input_fn"] + fold_kwargs = problem["fold_kwargs"] + + torch.manual_seed(seed) + inputs = input_fn().to(device) + + result_torch = torch.nn.Fold(**fold_kwargs).to(device)(inputs) + result_lib = unfoldNd.FoldNd(**fold_kwargs).to(device)(inputs) + + assert torch.allclose(result_lib, result_torch) + + +@pytest.mark.parametrize("device", DEVICES, ids=DEVICES_ID) +@pytest.mark.parametrize( + "problem", PRECISION_PROBLEMS_2D, ids=PRECISION_PROBLEMS_2D_IDS +) +def test_Fold2d_vs_Fold_precision(problem, device): + """Catch expected shortcomings of ``FoldNd`` caused by unfolding float indices.""" + seed = problem["seed"] + input_fn = problem["input_fn"] + fold_kwargs = problem["fold_kwargs"] + + torch.manual_seed(seed) + inputs = input_fn().to(device) + + _ = torch.nn.Fold(**fold_kwargs).to(device)(inputs) + + with pytest.raises(RuntimeError): + _ = unfoldNd.FoldNd(**fold_kwargs).to(device)(inputs) + + +@pytest.mark.parametrize("device", DEVICES, ids=DEVICES_ID) +@pytest.mark.parametrize("problem", UNFOLD_PROBLEMS_2D, ids=UNFOLD_PROBLEMS_2D_IDS) +def test_Fold2d_vs_Fold_after_Unfold(problem, device): + """Compare with ``torch.nn.Fold`` for a 4d input. + + Generate settings from unfold tests. + """ + seed = problem["seed"] + input_fn = problem["input_fn"] + unfold_kwargs = problem["unfold_kwargs"] + + torch.manual_seed(seed) + unfold_input = input_fn().to(device) + inputs = torch.nn.functional.unfold(unfold_input, **unfold_kwargs) + + fold_kwargs = problem["unfold_kwargs"] + output_size = unfold_input.shape[2:] + + result_torch = torch.nn.Fold(output_size, **fold_kwargs).to(device)(inputs) + result_lib = unfoldNd.FoldNd(output_size, **fold_kwargs).to(device)(inputs) + + assert torch.allclose(result_lib, result_torch) + + +@pytest.mark.parametrize("device", DEVICES, ids=DEVICES_ID) +@pytest.mark.parametrize("problem", UNFOLD_PROBLEMS_1D, ids=UNFOLD_PROBLEMS_1D_IDS) +def test_Fold1d_vs_Fold_after_dummy_dim_Unfold(problem, device): + """Compare with ``torch.nn.Fold`` for a 3d input. + + Generate settings from unfold tests and by adding a dummy dimension to achieve + compatibility with ``torch.nn.Unfold``. + """ + seed = problem["seed"] + input_fn = problem["input_fn"] + unfold_kwargs = problem["unfold_kwargs"] + + torch.manual_seed(seed) + unfold_inputs = input_fn().to(device) + + unfold_kwargs_dummy_dim, inputs_dummy_dim = _add_dummy_dim( + unfold_kwargs, unfold_inputs + ) + inputs = torch.nn.Unfold(**unfold_kwargs_dummy_dim).to(device)(inputs_dummy_dim) + + output_size_dummy_dim = tuple(inputs_dummy_dim.shape[2:]) + + result_torch = ( + torch.nn.Fold(output_size_dummy_dim, **unfold_kwargs_dummy_dim) + .to(device)(inputs) + .squeeze(-1) + ) + + fold_kwargs = problem["unfold_kwargs"] + output_size = unfold_inputs.shape[2:] + result_lib = unfoldNd.FoldNd(output_size, **fold_kwargs).to(device)(inputs) + + assert torch.allclose(result_lib, result_torch) + + +@pytest.mark.parametrize("device", DEVICES, ids=DEVICES_ID) +@pytest.mark.parametrize("problem", PROBLEMS_INVERSE, ids=PROBLEMS_INVERSE_IDS) +def test_Fold_inverse_of_Unfold(problem, device): + """Compare that folding is the inverse of unfolding on 3d/4d/5d inputs. + + This relation only holds if every pixel/voxel is used exactly once, i.e. + patches don't overlap and cover the entire image/volume. + """ + seed = problem["seed"] + input_fn = problem["input_fn"] + unfold_kwargs = problem["unfold_kwargs"] + + torch.manual_seed(seed) + inputs = input_fn().to(device) + unfolded = unfoldNd.unfoldNd(inputs, **unfold_kwargs) + + fold_kwargs = problem["unfold_kwargs"] + output_size = inputs.shape[2:] + + folded = unfoldNd.FoldNd(output_size, **fold_kwargs).to(device)(unfolded) + + assert torch.allclose(inputs, folded) + + +@pytest.mark.parametrize("device", DEVICES, ids=DEVICES_ID) +@pytest.mark.parametrize( + "problem", + UNFOLD_PROBLEMS_1D + UNFOLD_PROBLEMS_2D + UNFOLD_PROBLEMS_3D, + ids=UNFOLD_PROBLEMS_1D_IDS + UNFOLD_PROBLEMS_2D_IDS + UNFOLD_PROBLEMS_3D_IDS, +) +def test_FoldNd_divisor(problem, device): + """Test divisor tensor from ``fold-unfold`` composition. + + According to https://pytorch.org/docs/stable/generated/torch.nn.Fold.html the + divisor between an input tensor and the result of an unfold-fold composition + is satisfies ``fold(unfold(input)) == divisor * input`` with + ``input_ones = torch.ones(input.shape, dtype=input.dtype)`` and + ``divisor = fold(unfold(input_ones))`` + """ + seed = problem["seed"] + input_fn = problem["input_fn"] + unfold_kwargs = problem["unfold_kwargs"] + + torch.manual_seed(seed) + inputs = input_fn().to(device) + inputs_ones = torch.ones(inputs.shape, dtype=inputs.dtype).to(device) + + unfold_module = unfoldNd.UnfoldNd(**unfold_kwargs).to(device) + + fold_kwargs = problem["unfold_kwargs"] + output_size = inputs.shape[2:] + fold_module = unfoldNd.FoldNd(output_size, **fold_kwargs).to(device) + + divisor = fold_module(unfold_module(inputs_ones)) + outputs = fold_module(unfold_module(inputs)) + + assert torch.allclose(outputs, divisor * inputs) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/test/test_unfold.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/test/test_unfold.py new file mode 100644 index 0000000000000000000000000000000000000000..98a56c649fdfefad9827ad7bdf6b9f04b3fa8e78 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/test/test_unfold.py @@ -0,0 +1,82 @@ +"""Tests for ``unfoldNd/unfold.py.``""" + +from test.unfold_settings import ( + DEVICES, + DEVICES_ID, + PROBLEMS_1D, + PROBLEMS_1D_IDS, + PROBLEMS_2D, + PROBLEMS_2D_IDS, + PROBLEMS_3D, + PROBLEMS_3D_IDS, +) +from test.utils import _add_dummy_dim, _conv_unfold + +import pytest +import torch + +import unfoldNd + + +@pytest.mark.parametrize("device", DEVICES, ids=DEVICES_ID) +@pytest.mark.parametrize("problem", PROBLEMS_2D, ids=PROBLEMS_2D_IDS) +def test_Unfold2d_vs_Unfold(problem, device): + """Compare with ``torch.nn.Unfold`` for a 4d input.""" + seed = problem["seed"] + input_fn = problem["input_fn"] + unfold_kwargs = problem["unfold_kwargs"] + + torch.manual_seed(seed) + inputs = input_fn().to(device) + + result_torch = torch.nn.Unfold(**unfold_kwargs).to(device)(inputs) + result_lib = unfoldNd.UnfoldNd(**unfold_kwargs).to(device)(inputs) + + assert torch.allclose(result_lib, result_torch) + + +@pytest.mark.parametrize("device", DEVICES, ids=DEVICES_ID) +@pytest.mark.parametrize("problem", PROBLEMS_1D, ids=PROBLEMS_1D_IDS) +def test_Unfold1d_vs_dummy_dim_Unfold(problem, device): + """Compare with ``torch.nn.Unfold`` for a 3d input (adding a dummy dimension).""" + seed = problem["seed"] + input_fn = problem["input_fn"] + unfold_kwargs = problem["unfold_kwargs"] + + torch.manual_seed(seed) + inputs = input_fn().to(device) + + unfold_kwargs_dummy_dim, inputs_dummy_dim = _add_dummy_dim(unfold_kwargs, inputs) + result_torch = torch.nn.Unfold(**unfold_kwargs_dummy_dim).to(device)( + inputs_dummy_dim + ) + + result_lib = unfoldNd.UnfoldNd(**unfold_kwargs).to(device)(inputs) + + assert torch.allclose(result_lib, result_torch) + + +@pytest.mark.parametrize("device", DEVICES, ids=DEVICES_ID) +@pytest.mark.parametrize("problem", PROBLEMS_3D, ids=PROBLEMS_3D_IDS) +def test_Unfold3d_vs_Conv3d(problem, device): + """ + Use unfolded input in convolution with matrix-view kernel, compare with Conv3d. + """ + seed = problem["seed"] + input_fn = problem["input_fn"] + unfold_kwargs = problem["unfold_kwargs"] + out_channels = problem["out_channels"] + in_channels = input_fn().shape[1] + + torch.manual_seed(seed) + inputs = input_fn().to(device) + + conv3d_module = torch.nn.Conv3d( + in_channels, out_channels, **unfold_kwargs, bias=False + ).to(device) + torch_result = conv3d_module(inputs) + + unfolded_inputs = unfoldNd.UnfoldNd(**unfold_kwargs).to(device)(inputs) + result_lib = _conv_unfold(inputs, unfolded_inputs, conv3d_module) + + assert torch.allclose(torch_result, result_lib, atol=5e-7) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/test/test_unfold_transpose.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/test/test_unfold_transpose.py new file mode 100644 index 0000000000000000000000000000000000000000..9fb9bbcebe4de911f415534bb1052fd96eed8fb3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/test/test_unfold_transpose.py @@ -0,0 +1,59 @@ +"""Tests for ``unfoldNd/unfold_transpose.py.``""" + +from test.unfold_transpose_settings import ( + DEVICES, + DEVICES_ID, + PROBLEMS_1D, + PROBLEMS_1D_IDS, + PROBLEMS_2D, + PROBLEMS_2D_IDS, + PROBLEMS_3D, + PROBLEMS_3D_IDS, +) +from test.utils import _conv_transpose_unfold + +import pytest +import torch +from torch.nn import ConvTranspose1d, ConvTranspose2d, ConvTranspose3d + +import unfoldNd + + +@pytest.mark.parametrize("device", DEVICES, ids=DEVICES_ID) +@pytest.mark.parametrize( + "problem", + PROBLEMS_1D + PROBLEMS_2D + PROBLEMS_3D, + ids=PROBLEMS_1D_IDS + PROBLEMS_2D_IDS + PROBLEMS_3D_IDS, +) +def test_UnfoldTranspose_vs_ConvTransose(problem, device): + """Compare transpose convolution with matrix-multiplication via unfold.""" + seed = problem["seed"] + input_fn = problem["input_fn"] + unfold_transpose_kwargs = problem["unfold_transpose_kwargs"] + out_channels = problem["out_channels"] + in_channels = input_fn().shape[1] + groups = problem["groups"] + output_size = problem["output_size"] + + torch.manual_seed(seed) + inputs = input_fn().to(device) + + conv_transpose_module = { + 1: ConvTranspose1d, + 2: ConvTranspose2d, + 3: ConvTranspose3d, + }[inputs.dim() - 2] + + conv_transpose_module = conv_transpose_module( + in_channels, out_channels, **unfold_transpose_kwargs, bias=False, groups=groups + ).to(device) + torch_result = conv_transpose_module(inputs, output_size=output_size) + + unfolded_inputs = unfoldNd.UnfoldTransposeNd(**unfold_transpose_kwargs).to(device)( + inputs, output_size=output_size + ) + result_lib = _conv_transpose_unfold( + inputs, unfolded_inputs, conv_transpose_module, output_size=output_size + ) + + assert torch.allclose(torch_result, result_lib, atol=5e-7) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/test/test_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/test/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..482f16dee5b9db38b6aa1747ef381de3f06eb1cd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/test/test_utils.py @@ -0,0 +1,44 @@ +"""Tests for ``unfoldNd/utils.py.``""" + +from test.utils_settings import ( + UNSUPPORTED_KERNEL_SIZE, + UNSUPPORTED_KERNEL_SIZE_IDS, + UNSUPPORTED_N, + UNSUPPORTED_N_IDS, +) + +import pytest + +from unfoldNd import utils + + +@pytest.mark.parametrize("N", UNSUPPORTED_N, ids=UNSUPPORTED_N_IDS) +def test__tuple_raise_dimension_error(N): + """Only N=1,2,3 are supported.""" + dummy_kernel_size = None + + with pytest.raises(ValueError): + utils._tuple(dummy_kernel_size, N) + + +@pytest.mark.parametrize("N", UNSUPPORTED_N, ids=UNSUPPORTED_N_IDS) +def test__get_conv_raise_dimension_error(N): + """Only N=1,2,3 are supported.""" + with pytest.raises(ValueError): + utils._get_conv(N) + + +@pytest.mark.parametrize("N", UNSUPPORTED_N, ids=UNSUPPORTED_N_IDS) +def test__get_conv_transpose_raise_dimension_error(N): + """Only N=1,2,3 are supported.""" + with pytest.raises(ValueError): + utils._get_conv_transpose(N) + + +@pytest.mark.parametrize( + "kernel_size", UNSUPPORTED_KERNEL_SIZE, ids=UNSUPPORTED_KERNEL_SIZE_IDS +) +def test__get_kernel_size_numel_raise_value_error(kernel_size): + """``kernel_size`` must be an ``N``-tuple.""" + with pytest.raises(ValueError): + utils._get_kernel_size_numel(kernel_size) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/test/unfold_settings.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/test/unfold_settings.py new file mode 100644 index 0000000000000000000000000000000000000000..9aebf955dbcf4d238009b22a740fe5a831958397 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/test/unfold_settings.py @@ -0,0 +1,179 @@ +"""Problem settings for test.""" + +from test.utils import get_available_devices, make_id + +import torch + +DEVICES = get_available_devices() +DEVICES_ID = [f"device={dev}" for dev in DEVICES] + +PROBLEMS_1D = [ + { + "seed": 0, + "input_fn": lambda: torch.rand(2, 3, 50), + "unfold_kwargs": { + "kernel_size": 1, + }, + }, + { + "seed": 1, + "input_fn": lambda: torch.rand(2, 3, 50), + "unfold_kwargs": { + "kernel_size": 2, + }, + }, + { + "seed": 2, + "input_fn": lambda: torch.rand(2, 3, 50), + "unfold_kwargs": { + "kernel_size": 3, + }, + }, + { + "seed": 3, + "input_fn": lambda: torch.rand(2, 3, 50), + "unfold_kwargs": { + "kernel_size": 3, + "dilation": 2, + }, + }, + { + "seed": 4, + "input_fn": lambda: torch.rand(2, 3, 50), + "unfold_kwargs": { + "kernel_size": 3, + "dilation": 2, + "padding": 1, + }, + }, + { + "seed": 5, + "input_fn": lambda: torch.rand(2, 3, 50), + "unfold_kwargs": { + "kernel_size": 3, + "dilation": 2, + "padding": 1, + "stride": 2, + }, + }, +] +PROBLEMS_1D_IDS = [make_id(problem) for problem in PROBLEMS_1D] + +PROBLEMS_2D = [ + { + "seed": 0, + "input_fn": lambda: torch.rand(2, 3, 50, 40), + "unfold_kwargs": { + "kernel_size": 1, + }, + }, + { + "seed": 1, + "input_fn": lambda: torch.rand(2, 3, 50, 40), + "unfold_kwargs": { + "kernel_size": 2, + }, + }, + { + "seed": 2, + "input_fn": lambda: torch.rand(2, 3, 50, 40), + "unfold_kwargs": { + "kernel_size": (3, 2), + }, + }, + { + "seed": 3, + "input_fn": lambda: torch.rand(2, 3, 50, 40), + "unfold_kwargs": { + "kernel_size": (3, 2), + "dilation": 2, + }, + }, + { + "seed": 4, + "input_fn": lambda: torch.rand(2, 3, 50, 40), + "unfold_kwargs": { + "kernel_size": (3, 2), + "dilation": 2, + "padding": 1, + }, + }, + { + "seed": 5, + "input_fn": lambda: torch.rand(2, 3, 50, 40), + "unfold_kwargs": { + "kernel_size": (3, 2), + "dilation": 2, + "padding": 1, + "stride": 2, + }, + }, + { + "seed": 0, + "input_fn": lambda: torch.rand(2, 3, 50, 40, dtype=torch.float64), + "unfold_kwargs": { + "kernel_size": 1, + }, + "id": "bug-float-64-input", + }, +] +PROBLEMS_2D_IDS = [make_id(problem) for problem in PROBLEMS_2D] + + +PROBLEMS_3D = [ + { + "seed": 0, + "input_fn": lambda: torch.rand(2, 3, 50, 40, 30), + "unfold_kwargs": { + "kernel_size": 1, + }, + "out_channels": 1, + }, + { + "seed": 1, + "input_fn": lambda: torch.rand(2, 3, 50, 40, 30), + "unfold_kwargs": { + "kernel_size": 2, + }, + "out_channels": 2, + }, + { + "seed": 2, + "input_fn": lambda: torch.rand(2, 3, 50, 40, 30), + "unfold_kwargs": { + "kernel_size": (4, 3, 2), + }, + "out_channels": 4, + }, + { + "seed": 3, + "input_fn": lambda: torch.rand(2, 3, 50, 40, 30), + "unfold_kwargs": { + "kernel_size": (4, 3, 2), + "dilation": 2, + }, + "out_channels": 5, + }, + { + "seed": 4, + "input_fn": lambda: torch.rand(2, 3, 50, 40, 30), + "unfold_kwargs": { + "kernel_size": (4, 3, 2), + "dilation": 2, + "padding": 1, + }, + "out_channels": 10, + }, + { + "seed": 5, + "input_fn": lambda: torch.rand(2, 3, 50, 40, 30), + "unfold_kwargs": { + "kernel_size": (4, 3, 2), + "dilation": 2, + "padding": 1, + "stride": 2, + }, + "out_channels": 10, + }, +] +PROBLEMS_3D_IDS = [make_id(problem) for problem in PROBLEMS_3D] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/test/unfold_transpose_settings.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/test/unfold_transpose_settings.py new file mode 100644 index 0000000000000000000000000000000000000000..e83f3762ad5bff1dc47e768e51d8f336fa45e153 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/test/unfold_transpose_settings.py @@ -0,0 +1,170 @@ +"""Problem settings for transpose test.""" + +from test.utils import get_available_devices, make_id + +import torch + +DEVICES = get_available_devices() +DEVICES_ID = [f"device={dev}" for dev in DEVICES] + +PROBLEMS_1D = [ + { + "seed": 0, + "input_fn": lambda: torch.rand(3, 2, 20), + "out_channels": 3, + "groups": 1, + "output_size": None, + "unfold_transpose_kwargs": { + "kernel_size": 2, + "padding": 1, + }, + }, + { + "seed": 0, + "input_fn": lambda: torch.rand(3, 2, 111), + "out_channels": 3, + "groups": 1, + "output_size": None, + "unfold_transpose_kwargs": { + "kernel_size": 2, + "padding": 1, + "stride": 2, + "dilation": 2, + }, + }, + { + "seed": 0, + "input_fn": lambda: torch.rand(3, 3, 113), + "out_channels": 6, + "groups": 3, + "output_size": None, + "unfold_transpose_kwargs": { + "kernel_size": 2, + "padding": 2, + "stride": 4, + "dilation": 3, + }, + }, +] +PROBLEMS_1D_IDS = [make_id(problem) for problem in PROBLEMS_1D] + +PROBLEMS_2D = [ + { + "seed": 0, + "input_fn": lambda: torch.rand(2, 3, 50, 40), + "out_channels": 2, + "groups": 1, + "output_size": None, + "unfold_transpose_kwargs": { + "kernel_size": 1, + }, + }, + { + "seed": 0, + "input_fn": lambda: torch.rand(3, 2, 10, 10), + "out_channels": 3, + "groups": 1, + "output_size": None, + "unfold_transpose_kwargs": { + "kernel_size": 2, + "padding": 1, + "stride": 2, + "dilation": 2, + }, + }, + { + "seed": 0, + "input_fn": lambda: torch.rand(1, 3, 16, 16), + "out_channels": 6, + "groups": 1, + "output_size": None, + "unfold_transpose_kwargs": { + "kernel_size": 2, + "padding": 2, + "stride": 4, + "dilation": 3, + }, + }, + { + "seed": 0, + "input_fn": lambda: torch.rand(3, 2, 11, 13), + "out_channels": 6, + "groups": 2, + "output_size": None, + "unfold_transpose_kwargs": { + "kernel_size": 2, + "padding": 1, + "dilation": 2, + }, + }, + { + "seed": 0, + "input_fn": lambda: torch.rand(10, 8, 25, 50), + "out_channels": 15, + "groups": 1, + "output_size": None, + "unfold_transpose_kwargs": { + "kernel_size": (3, 5), + "padding": (4, 2), + "stride": (2, 1), + "dilation": (3, 1), + }, + }, + # with nontrivial output_size, taken from + # https://discuss.pytorch.org/t/the-output-size-of-convtranspose2d-differs-from-the-expected-output-size/1876/11 # noqa: B950 + { + "seed": 0, + "input_fn": lambda: torch.rand(1, 3, 10, 10), + "out_channels": 1, + "groups": 1, + "output_size": (21, 21), + "unfold_transpose_kwargs": { + "kernel_size": 2, + "stride": 2, + }, + }, +] +PROBLEMS_2D_IDS = [make_id(problem) for problem in PROBLEMS_2D] + +PROBLEMS_3D = [ + { + "seed": 0, + "input_fn": lambda: torch.rand(3, 2, 7, 9, 9), + "out_channels": 6, + "groups": 1, + "output_size": None, + "unfold_transpose_kwargs": { + "kernel_size": 2, + "padding": 2, + "stride": 2, + "dilation": 2, + }, + }, + { + "seed": 0, + "input_fn": lambda: torch.rand(3, 2, 5, 13, 17), + "out_channels": 3, + "groups": 1, + "output_size": None, + "unfold_transpose_kwargs": { + "kernel_size": 2, + "padding": 1, + "stride": 2, + "dilation": 2, + }, + }, + { + "seed": 0, + "input_fn": lambda: torch.rand(3, 2, 23, 34, 55), + "out_channels": 4, + "groups": 2, + "output_size": None, + "unfold_transpose_kwargs": { + "kernel_size": (2, 3, 4), + "padding": (0, 1, 1), + "stride": (1, 2, 2), + "dilation": (1, 2, 2), + }, + }, +] +PROBLEMS_3D_IDS = [make_id(problem) for problem in PROBLEMS_3D] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/test/utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/test/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..0a68a9f59507cd05b0460b565c3516fb975d0d84 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/test/utils.py @@ -0,0 +1,115 @@ +"""Utility functions for testing ``unfoldNd``.""" + +import torch +from torch.nn.modules.utils import _pair + + +def make_id(problem): + """Convert problem description in to human-readable id.""" + key_value_strs = [] + + for key, value in problem.items(): + if key == "input_fn": + key_value_strs.append(f"input_shape={value().shape}") + else: + key_value_strs.append(f"{key}={value}") + + return ",".join(key_value_strs).replace(" ", "") + + +def get_available_devices(): + """Return CPU and, if present, GPU device. + + Returns: + [torch.device]: Available devices for `torch`. + """ + devices = [torch.device("cpu")] + + if torch.cuda.is_available(): + devices.append(torch.device("cuda")) + + return devices + + +def _conv_unfold(inputs, unfolded_input, conv_module): + """Perform convolution with unfolded input via matrix multiplication. + + Copied and modified from: + https://github.com/f-dangel/backpack/blob/development/test/utils/test_conv.py#L23-L51 # noqa: B950 + """ + assert conv_module.bias is None + + def get_output_shape(inputs, module): + return module(inputs).shape + + N, C_in = inputs.shape[0], inputs.shape[1] + + output_shape = get_output_shape(inputs, conv_module) + C_out = output_shape[1] + spatial_out_size = output_shape[2:] + spatial_out_numel = spatial_out_size.numel() + + kernel_size = conv_module.kernel_size + kernel_size_numel = int(torch.prod(torch.Tensor(kernel_size))) + + G = conv_module.groups + + weight_matrix = conv_module.weight.data.reshape( + G, C_out // G, C_in // G, kernel_size_numel + ) + unfolded_input = unfolded_input.reshape( + N, G, C_in // G, kernel_size_numel, spatial_out_numel + ) + + result = torch.einsum("gocx,ngcxh->ngoh", weight_matrix, unfolded_input) + + return result.reshape(N, C_out, *spatial_out_size) + + +def _conv_transpose_unfold( + inputs, unfolded_input, conv_transpose_module, output_size=None +): + """Perform transpose convolution via matrix multiplication. + + Copied and modified from: + https://github.com/f-dangel/backpack/blob/development/test/utils/test_conv_transpose.py#L17-L43 # noqa: B950 + """ + assert conv_transpose_module.bias is None + + def get_output_shape(input, module, output_size): + return module(input, output_size=output_size).shape + + N, C_in = inputs.shape[0], inputs.shape[1] + + output_shape = get_output_shape(inputs, conv_transpose_module, output_size) + C_out = output_shape[1] + spatial_out_size = output_shape[2:] + spatial_out_numel = spatial_out_size.numel() + kernel_size_numel = conv_transpose_module.weight.shape[2:].numel() + + G = conv_transpose_module.groups + + weight_matrix = conv_transpose_module.weight.data.reshape( + C_in // G, G, C_out // G, kernel_size_numel + ) + unfolded_input = unfolded_input.reshape( + N, C_in // G, G, kernel_size_numel, spatial_out_numel + ) + + result = torch.einsum("cgox,ncgxh->ngoh", weight_matrix, unfolded_input) + + return result.reshape(N, C_out, *spatial_out_size) + + +def _add_dummy_dim(unfold_kwargs, inputs): + """Add dummy dimension to unfold hyperparameters and input.""" + new_inputs = inputs.unsqueeze(-1) + + new_kwargs = {} + + for key, value in unfold_kwargs.items(): + dummy = (0,) if key == "padding" else (1,) + new_value = _pair(value)[:-1] + dummy + new_kwargs[key] = new_value + + return new_kwargs, new_inputs diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/test/utils_settings.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/test/utils_settings.py new file mode 100644 index 0000000000000000000000000000000000000000..e8cd09eced63ed3e8dc89cfb704f16440a68a2fe --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/test/utils_settings.py @@ -0,0 +1,7 @@ +"""Problem settings for utils test.""" + +UNSUPPORTED_N = [4, -1] +UNSUPPORTED_N_IDS = [f"N={n}" for n in UNSUPPORTED_N] + +UNSUPPORTED_KERNEL_SIZE = [[1, 2], 1] +UNSUPPORTED_KERNEL_SIZE_IDS = [f"kernel_size={s}" for s in UNSUPPORTED_KERNEL_SIZE] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/threadpoolctl-3.6.0.dist-info/INSTALLER b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/threadpoolctl-3.6.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/threadpoolctl-3.6.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/threadpoolctl-3.6.0.dist-info/METADATA b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/threadpoolctl-3.6.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..2410f166f31a21271d0728d19ba083cd37d24206 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/threadpoolctl-3.6.0.dist-info/METADATA @@ -0,0 +1,400 @@ +Metadata-Version: 2.4 +Name: threadpoolctl +Version: 3.6.0 +Summary: threadpoolctl +Home-page: https://github.com/joblib/threadpoolctl +Author: Thomas Moreau +Author-email: thomas.moreau.2010@gmail.com +Requires-Python: >=3.9 +Description-Content-Type: text/markdown +License: BSD-3-Clause +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: BSD License +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Topic :: Software Development :: Libraries :: Python Modules +License-File: LICENSE + +# Thread-pool Controls [![Build Status](https://github.com/joblib/threadpoolctl/actions/workflows/test.yml/badge.svg?branch=master)](https://github.com/joblib/threadpoolctl/actions?query=branch%3Amaster) [![codecov](https://codecov.io/gh/joblib/threadpoolctl/branch/master/graph/badge.svg)](https://codecov.io/gh/joblib/threadpoolctl) + +Python helpers to limit the number of threads used in the +threadpool-backed of common native libraries used for scientific +computing and data science (e.g. BLAS and OpenMP). + +Fine control of the underlying thread-pool size can be useful in +workloads that involve nested parallelism so as to mitigate +oversubscription issues. + +## Installation + +- For users, install the last published version from PyPI: + + ```bash + pip install threadpoolctl + ``` + +- For contributors, install from the source repository in developer + mode: + + ```bash + pip install -r dev-requirements.txt + flit install --symlink + ``` + + then you run the tests with pytest: + + ```bash + pytest + ``` + +## Usage + +### Command Line Interface + +Get a JSON description of thread-pools initialized when importing python +packages such as numpy or scipy for instance: + +``` +python -m threadpoolctl -i numpy scipy.linalg +[ + { + "filepath": "/home/ogrisel/miniconda3/envs/tmp/lib/libmkl_rt.so", + "prefix": "libmkl_rt", + "user_api": "blas", + "internal_api": "mkl", + "version": "2019.0.4", + "num_threads": 2, + "threading_layer": "intel" + }, + { + "filepath": "/home/ogrisel/miniconda3/envs/tmp/lib/libiomp5.so", + "prefix": "libiomp", + "user_api": "openmp", + "internal_api": "openmp", + "version": null, + "num_threads": 4 + } +] +``` + +The JSON information is written on STDOUT. If some of the packages are missing, +a warning message is displayed on STDERR. + +### Python Runtime Programmatic Introspection + +Introspect the current state of the threadpool-enabled runtime libraries +that are loaded when importing Python packages: + +```python +>>> from threadpoolctl import threadpool_info +>>> from pprint import pprint +>>> pprint(threadpool_info()) +[] + +>>> import numpy +>>> pprint(threadpool_info()) +[{'filepath': '/home/ogrisel/miniconda3/envs/tmp/lib/libmkl_rt.so', + 'internal_api': 'mkl', + 'num_threads': 2, + 'prefix': 'libmkl_rt', + 'threading_layer': 'intel', + 'user_api': 'blas', + 'version': '2019.0.4'}, + {'filepath': '/home/ogrisel/miniconda3/envs/tmp/lib/libiomp5.so', + 'internal_api': 'openmp', + 'num_threads': 4, + 'prefix': 'libiomp', + 'user_api': 'openmp', + 'version': None}] + +>>> import xgboost +>>> pprint(threadpool_info()) +[{'filepath': '/home/ogrisel/miniconda3/envs/tmp/lib/libmkl_rt.so', + 'internal_api': 'mkl', + 'num_threads': 2, + 'prefix': 'libmkl_rt', + 'threading_layer': 'intel', + 'user_api': 'blas', + 'version': '2019.0.4'}, + {'filepath': '/home/ogrisel/miniconda3/envs/tmp/lib/libiomp5.so', + 'internal_api': 'openmp', + 'num_threads': 4, + 'prefix': 'libiomp', + 'user_api': 'openmp', + 'version': None}, + {'filepath': '/home/ogrisel/miniconda3/envs/tmp/lib/libgomp.so.1.0.0', + 'internal_api': 'openmp', + 'num_threads': 4, + 'prefix': 'libgomp', + 'user_api': 'openmp', + 'version': None}] +``` + +In the above example, `numpy` was installed from the default anaconda channel and comes +with MKL and its Intel OpenMP (`libiomp5`) implementation while `xgboost` was installed +from pypi.org and links against GNU OpenMP (`libgomp`) so both OpenMP runtimes are +loaded in the same Python program. + +The state of these libraries is also accessible through the object oriented API: + +```python +>>> from threadpoolctl import ThreadpoolController, threadpool_info +>>> from pprint import pprint +>>> import numpy +>>> controller = ThreadpoolController() +>>> pprint(controller.info()) +[{'architecture': 'Haswell', + 'filepath': '/home/jeremie/miniconda/envs/dev/lib/libopenblasp-r0.3.17.so', + 'internal_api': 'openblas', + 'num_threads': 4, + 'prefix': 'libopenblas', + 'threading_layer': 'pthreads', + 'user_api': 'blas', + 'version': '0.3.17'}] + +>>> controller.info() == threadpool_info() +True +``` + +### Setting the Maximum Size of Thread-Pools + +Control the number of threads used by the underlying runtime libraries +in specific sections of your Python program: + +```python +>>> from threadpoolctl import threadpool_limits +>>> import numpy as np + +>>> with threadpool_limits(limits=1, user_api='blas'): +... # In this block, calls to blas implementation (like openblas or MKL) +... # will be limited to use only one thread. They can thus be used jointly +... # with thread-parallelism. +... a = np.random.randn(1000, 1000) +... a_squared = a @ a +``` + +The threadpools can also be controlled via the object oriented API, which is especially +useful to avoid searching through all the loaded shared libraries each time. It will +however not act on libraries loaded after the instantiation of the +`ThreadpoolController`: + +```python +>>> from threadpoolctl import ThreadpoolController +>>> import numpy as np +>>> controller = ThreadpoolController() + +>>> with controller.limit(limits=1, user_api='blas'): +... a = np.random.randn(1000, 1000) +... a_squared = a @ a +``` + +### Restricting the limits to the scope of a function + +`threadpool_limits` and `ThreadpoolController` can also be used as decorators to set +the maximum number of threads used by the supported libraries at a function level. The +decorators are accessible through their `wrap` method: + +```python +>>> from threadpoolctl import ThreadpoolController, threadpool_limits +>>> import numpy as np +>>> controller = ThreadpoolController() + +>>> @controller.wrap(limits=1, user_api='blas') +... # or @threadpool_limits.wrap(limits=1, user_api='blas') +... def my_func(): +... # Inside this function, calls to blas implementation (like openblas or MKL) +... # will be limited to use only one thread. +... a = np.random.randn(1000, 1000) +... a_squared = a @ a +... +``` + +### Switching the FlexiBLAS backend + +`FlexiBLAS` is a BLAS wrapper for which the BLAS backend can be switched at runtime. +`threadpoolctl` exposes python bindings for this feature. Here's an example but note +that this part of the API is experimental and subject to change without deprecation: + +```python +>>> from threadpoolctl import ThreadpoolController +>>> import numpy as np +>>> controller = ThreadpoolController() + +>>> controller.info() +[{'user_api': 'blas', + 'internal_api': 'flexiblas', + 'num_threads': 1, + 'prefix': 'libflexiblas', + 'filepath': '/usr/local/lib/libflexiblas.so.3.3', + 'version': '3.3.1', + 'available_backends': ['NETLIB', 'OPENBLASPTHREAD', 'ATLAS'], + 'loaded_backends': ['NETLIB'], + 'current_backend': 'NETLIB'}] + +# Retrieve the flexiblas controller +>>> flexiblas_ct = controller.select(internal_api="flexiblas").lib_controllers[0] + +# Switch the backend with one predefined at build time (listed in "available_backends") +>>> flexiblas_ct.switch_backend("OPENBLASPTHREAD") +>>> controller.info() +[{'user_api': 'blas', + 'internal_api': 'flexiblas', + 'num_threads': 4, + 'prefix': 'libflexiblas', + 'filepath': '/usr/local/lib/libflexiblas.so.3.3', + 'version': '3.3.1', + 'available_backends': ['NETLIB', 'OPENBLASPTHREAD', 'ATLAS'], + 'loaded_backends': ['NETLIB', 'OPENBLASPTHREAD'], + 'current_backend': 'OPENBLASPTHREAD'}, + {'user_api': 'blas', + 'internal_api': 'openblas', + 'num_threads': 4, + 'prefix': 'libopenblas', + 'filepath': '/usr/lib/x86_64-linux-gnu/openblas-pthread/libopenblasp-r0.3.8.so', + 'version': '0.3.8', + 'threading_layer': 'pthreads', + 'architecture': 'Haswell'}] + +# It's also possible to directly give the path to a shared library +>>> flexiblas_controller.switch_backend("/home/jeremie/miniforge/envs/flexiblas_threadpoolctl/lib/libmkl_rt.so") +>>> controller.info() +[{'user_api': 'blas', + 'internal_api': 'flexiblas', + 'num_threads': 2, + 'prefix': 'libflexiblas', + 'filepath': '/usr/local/lib/libflexiblas.so.3.3', + 'version': '3.3.1', + 'available_backends': ['NETLIB', 'OPENBLASPTHREAD', 'ATLAS'], + 'loaded_backends': ['NETLIB', + 'OPENBLASPTHREAD', + '/home/jeremie/miniforge/envs/flexiblas_threadpoolctl/lib/libmkl_rt.so'], + 'current_backend': '/home/jeremie/miniforge/envs/flexiblas_threadpoolctl/lib/libmkl_rt.so'}, + {'user_api': 'openmp', + 'internal_api': 'openmp', + 'num_threads': 4, + 'prefix': 'libomp', + 'filepath': '/home/jeremie/miniforge/envs/flexiblas_threadpoolctl/lib/libomp.so', + 'version': None}, + {'user_api': 'blas', + 'internal_api': 'openblas', + 'num_threads': 4, + 'prefix': 'libopenblas', + 'filepath': '/usr/lib/x86_64-linux-gnu/openblas-pthread/libopenblasp-r0.3.8.so', + 'version': '0.3.8', + 'threading_layer': 'pthreads', + 'architecture': 'Haswell'}, + {'user_api': 'blas', + 'internal_api': 'mkl', + 'num_threads': 2, + 'prefix': 'libmkl_rt', + 'filepath': '/home/jeremie/miniforge/envs/flexiblas_threadpoolctl/lib/libmkl_rt.so.2', + 'version': '2024.0-Product', + 'threading_layer': 'gnu'}] +``` + +You can observe that the previously linked OpenBLAS shared object stays loaded by +the Python program indefinitely, but FlexiBLAS itself no longer delegates BLAS calls +to OpenBLAS as indicated by the `current_backend` attribute. +### Writing a custom library controller + +Currently, `threadpoolctl` has support for `OpenMP` and the main `BLAS` libraries. +However it can also be used to control the threadpool of other native libraries, +provided that they expose an API to get and set the limit on the number of threads. +For that, one must implement a controller for this library and register it to +`threadpoolctl`. + +A custom controller must be a subclass of the `LibController` class and implement +the attributes and methods described in the docstring of `LibController`. Then this +new controller class must be registered using the `threadpoolctl.register` function. +An complete example can be found [here]( + https://github.com/joblib/threadpoolctl/blob/master/tests/_pyMylib/__init__.py). + +### Sequential BLAS within OpenMP parallel region + +When one wants to have sequential BLAS calls within an OpenMP parallel region, it's +safer to set `limits="sequential_blas_under_openmp"` since setting `limits=1` and +`user_api="blas"` might not lead to the expected behavior in some configurations +(e.g. OpenBLAS with the OpenMP threading layer +https://github.com/xianyi/OpenBLAS/issues/2985). + +### Known Limitations + +- `threadpool_limits` can fail to limit the number of inner threads when nesting + parallel loops managed by distinct OpenMP runtime implementations (for instance + libgomp from GCC and libomp from clang/llvm or libiomp from ICC). + + See the `test_openmp_nesting` function in [tests/test_threadpoolctl.py]( + https://github.com/joblib/threadpoolctl/blob/master/tests/test_threadpoolctl.py) + for an example. More information can be found at: + https://github.com/jeremiedbb/Nested_OpenMP + + Note however that this problem does not happen when `threadpool_limits` is + used to limit the number of threads used internally by BLAS calls that are + themselves nested under OpenMP parallel loops. `threadpool_limits` works as + expected, even if the inner BLAS implementation relies on a distinct OpenMP + implementation. + +- Using Intel OpenMP (ICC) and LLVM OpenMP (clang) in the same Python program + under Linux is known to cause problems. See the following guide for more details + and workarounds: + https://github.com/joblib/threadpoolctl/blob/master/multiple_openmp.md + +- Setting the maximum number of threads of the OpenMP and BLAS libraries has a global + effect and impacts the whole Python process. There is no thread level isolation as + these libraries do not offer thread-local APIs to configure the number of threads to + use in nested parallel calls. + + +## Maintainers + +To make a release: + +- Bump the version number (`__version__`) in `threadpoolctl.py` and update the + release date in `CHANGES.md`. + +- Build the distribution archives: + +```bash +pip install flit +flit build +``` + +and check the contents of `dist/`. + +- If everything is fine, make a commit for the release, tag it and push the +tag to github: + +```bash +git tag -a X.Y.Z +git push git@github.com:joblib/threadpoolctl.git X.Y.Z +``` + +- Upload the wheels and source distribution to PyPI using flit. Since PyPI doesn't + allow password authentication anymore, the username needs to be changed to the + generic name `__token__`: + +```bash +FLIT_USERNAME=__token__ flit publish +``` + + and a PyPI token has to be passed in place of the password. + +- Create a PR for the release on the [conda-forge feedstock](https://github.com/conda-forge/threadpoolctl-feedstock) (or wait for the bot to make it). + +- Publish the release on github. + +### Credits + +The initial dynamic library introspection code was written by @anton-malakhov +for the smp package available at https://github.com/IntelPython/smp . + +threadpoolctl extends this for other operating systems. Contrary to smp, +threadpoolctl does not attempt to limit the size of Python multiprocessing +pools (threads or processes) or set operating system-level CPU affinity +constraints: threadpoolctl only interacts with native libraries via their +public runtime APIs. + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/threadpoolctl-3.6.0.dist-info/RECORD b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/threadpoolctl-3.6.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..f8697dae6e04d8c1c68479174dbce9e117abe5f7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/threadpoolctl-3.6.0.dist-info/RECORD @@ -0,0 +1,7 @@ +__pycache__/threadpoolctl.cpython-310.pyc,, +threadpoolctl-3.6.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +threadpoolctl-3.6.0.dist-info/METADATA,sha256=pF340H6hiD13IYOlAdfVJgdqpw38_dsnaiy9wE3vU0E,13843 +threadpoolctl-3.6.0.dist-info/RECORD,, +threadpoolctl-3.6.0.dist-info/WHEEL,sha256=_2ozNFCLWc93bK4WKHCO-eDUENDlo-dgc9cU3qokYO4,82 +threadpoolctl-3.6.0.dist-info/licenses/LICENSE,sha256=gaxhkHUkiwblNmC2UtEOSF9GdfXQrg-X6iI3DaH34js,1507 +threadpoolctl.py,sha256=EvuVJranTS5oa37BSNwWXDWHmZsU-oaYSqGA4QgCQAs,50722 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/threadpoolctl-3.6.0.dist-info/WHEEL b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/threadpoolctl-3.6.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..23d2d7e9a5d381ef8a375db09f82052144d1fd96 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/threadpoolctl-3.6.0.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: flit 3.11.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/threadpoolctl-3.6.0.dist-info/licenses/LICENSE b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/threadpoolctl-3.6.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..f2927f5f8147f137783bb5072794999e04655cfd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/threadpoolctl-3.6.0.dist-info/licenses/LICENSE @@ -0,0 +1,24 @@ +Copyright (c) 2019, threadpoolctl contributors + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of copyright holder nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2-0.6.0.dist-info/INSTALLER b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2-0.6.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2-0.6.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2-0.6.0.dist-info/METADATA b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2-0.6.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..ca2f41190debafb0b4cb109a52858629ea0053c2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2-0.6.0.dist-info/METADATA @@ -0,0 +1,258 @@ +Metadata-Version: 2.4 +Name: thriftpy2 +Version: 0.6.0 +Summary: Pure python implementation of Apache Thrift. +Author-email: ThriftPy Organization +License: The MIT License (MIT) + + Copyright (c) <2014> + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + +Project-URL: Homepage, https://thriftpy2.readthedocs.io/ +Project-URL: Source, https://github.com/Thriftpy/thriftpy2 +Keywords: thrift python thriftpy thriftpy2 +Classifier: Development Status :: 4 - Beta +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: MIT License +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Topic :: Software Development +Requires-Python: >=3.7 +Description-Content-Type: text/x-rst +License-File: LICENSE +Requires-Dist: ply<4.0,>=3.4 +Requires-Dist: six~=1.15 +Requires-Dist: typing_extensions>=3.7.4; python_version < "3.8" +Provides-Extra: dev +Requires-Dist: flake8>=4.0; extra == "dev" +Requires-Dist: sphinx-rtd-theme>=0.1.9; extra == "dev" +Requires-Dist: sphinx>=1.3; extra == "dev" +Requires-Dist: pytest-asyncio; extra == "dev" +Requires-Dist: pytest-reraise; extra == "dev" +Requires-Dist: pytest<8.2.0,>=6.1.1; extra == "dev" +Requires-Dist: tornado<7.0,>=4.0; python_version >= "3.12" and extra == "dev" +Requires-Dist: tornado<6.0,>=4.0; python_version < "3.12" and extra == "dev" +Requires-Dist: aiohttp<4.0.0,>=3.8.0; extra == "dev" +Provides-Extra: tornado +Requires-Dist: tornado<7.0,>=4.0; python_version >= "3.12" and extra == "tornado" +Requires-Dist: tornado<6.0,>=4.0; python_version < "3.12" and extra == "tornado" +Provides-Extra: aiohttp +Requires-Dist: aiohttp<4.0.0,>=3.8.0; extra == "aiohttp" +Dynamic: license-file + +========= +ThriftPy2 +========= + +.. image:: https://img.shields.io/codecov/c/github/Thriftpy/thriftpy2.svg + :target: https://codecov.io/gh/Thriftpy/thriftpy2 + +.. image:: https://img.shields.io/pypi/dm/thriftpy2.svg + :target: https://pypi.org/project/thriftpy2/ + +.. image:: https://img.shields.io/pypi/v/thriftpy2.svg + :target: https://pypi.org/project/thriftpy2/ + +.. image:: https://img.shields.io/pypi/pyversions/thriftpy2.svg + :target: https://pypi.org/project/thriftpy2/ + +.. image:: https://img.shields.io/pypi/implementation/thriftpy2.svg + :target: https://pypi.org/project/thriftpy2/ + + +ThriftPy2 is a pure Python implementation of the `Apache Thrift `_ +protocol. It allows you to parse Thrift IDL files and create RPC clients/servers +without code generation or compilation. + + +Installation +============ + +Install with pip: + +.. code:: bash + + $ pip install thriftpy2 + + +Features +======== + +- Python 3.7+ and PyPy3. + +- Pure Python implementation. No need to compile or install the ``thrift`` package. + All you need is thriftpy2 and a thrift file. + +- Dynamically load thrift files as Python modules, with code generated on the fly. + +- Compatible with Apache Thrift. You can use ThriftPy2 together with the + official implementation servers and clients. + +- Easy RPC server/client setup. + +- Supported protocols and transports: + + * binary protocol (Python and Cython) + * compact protocol (Python and Cython) + * JSON protocol + * Apache JSON protocol + * buffered transport (Python and Cython) + * framed transport + * HTTP server and client + * asyncio support + + +Quick Start +=========== + +Define a ``pingpong.thrift`` file: + +:: + + service PingPong { + string ping(), + } + +Server +------ + +.. code:: python + + import thriftpy2 + from thriftpy2.rpc import make_server + + pingpong_thrift = thriftpy2.load("pingpong.thrift", module_name="pingpong_thrift") + + + class Dispatcher(object): + def ping(self): + return "pong" + + + server = make_server(pingpong_thrift.PingPong, Dispatcher(), '127.0.0.1', 6000) + server.serve() + +Client +------ + +.. code:: python + + import thriftpy2 + from thriftpy2.rpc import make_client + + pingpong_thrift = thriftpy2.load("pingpong.thrift", module_name="pingpong_thrift") + + client = make_client(pingpong_thrift.PingPong, '127.0.0.1', 6000) + print(client.ping()) # prints "pong" + +Async Server +------------ + +.. code:: python + + import thriftpy2 + from thriftpy2.rpc import make_aio_server + + pingpong_thrift = thriftpy2.load("pingpong.thrift", module_name="pingpong_thrift") + + + class Dispatcher(object): + async def ping(self): + return "pong" + + + server = make_aio_server(pingpong_thrift.PingPong, Dispatcher(), '127.0.0.1', 6000) + server.serve() + +Async Client +------------ + +.. code:: python + + import asyncio + import thriftpy2 + from thriftpy2.rpc import make_aio_client + + pingpong_thrift = thriftpy2.load("pingpong.thrift", module_name="pingpong_thrift") + + + async def main(): + client = await make_aio_client(pingpong_thrift.PingPong, '127.0.0.1', 6000) + print(await client.ping()) # prints "pong" + client.close() + + + if __name__ == '__main__': + asyncio.run(main()) + +See the ``examples`` and ``tests`` directories for more usage examples. + + +Migrate from ThriftPy +===================== + +ThriftPy (https://github.com/eleme/thriftpy) has been deprecated. +ThriftPy2 is fully compatible, just change your import: + +.. code:: python + + import thriftpy2 as thriftpy + + +Contribute +========== + +1. Fork the repo and make changes. + +2. Write a test that shows a bug was fixed or the feature works as expected. + +3. Make sure ``tox`` tests succeed. + +4. Send a pull request. + + +Contributors +============ + +https://github.com/Thriftpy/thriftpy2/graphs/contributors + + +Sponsors +======== + +.. image:: ./docs/jetbrains.svg + :target: https://www.jetbrains.com/?from=ThriftPy + + +Changelog +========= + +https://github.com/Thriftpy/thriftpy2/releases diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2-0.6.0.dist-info/RECORD b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2-0.6.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..04c1f647d82656fc4f26bc211fc15495c6d14551 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2-0.6.0.dist-info/RECORD @@ -0,0 +1,126 @@ +thriftpy2-0.6.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +thriftpy2-0.6.0.dist-info/METADATA,sha256=WS-IeAC4l419rQ9qmq-dbzJl6ibHcpiaTD1PSOI9c8I,7476 +thriftpy2-0.6.0.dist-info/RECORD,, +thriftpy2-0.6.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +thriftpy2-0.6.0.dist-info/WHEEL,sha256=UFqd87IJYwCmgtMlgjUURxWx6rDewA9R16SpGKS_n-s,190 +thriftpy2-0.6.0.dist-info/licenses/LICENSE,sha256=Au5_tZpe5Sgc_DKFaOwo7xiAjTyM5CTgb-KVS24zPok,1081 +thriftpy2-0.6.0.dist-info/top_level.txt,sha256=0vwXtTK15CZdPSGs5grdY0x5L-b6Saxt80QL16EtLtg,10 +thriftpy2/__init__.py,sha256=hbckPfRk9D7CRlrCjYPNXBSkyfh1UNjXGAe8Skgd05w,296 +thriftpy2/__pycache__/__init__.cpython-310.pyc,, +thriftpy2/__pycache__/_compat.cpython-310.pyc,, +thriftpy2/__pycache__/hook.cpython-310.pyc,, +thriftpy2/__pycache__/http.cpython-310.pyc,, +thriftpy2/__pycache__/rpc.cpython-310.pyc,, +thriftpy2/__pycache__/server.cpython-310.pyc,, +thriftpy2/__pycache__/thrift.cpython-310.pyc,, +thriftpy2/__pycache__/tornado.cpython-310.pyc,, +thriftpy2/__pycache__/utils.cpython-310.pyc,, +thriftpy2/_compat.py,sha256=jvVmbBRzm8HQabbq_L0YB6rR_MwjWE69_4ZkufnnCqo,312 +thriftpy2/contrib/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +thriftpy2/contrib/__pycache__/__init__.cpython-310.pyc,, +thriftpy2/contrib/aio/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +thriftpy2/contrib/aio/__pycache__/__init__.cpython-310.pyc,, +thriftpy2/contrib/aio/__pycache__/client.cpython-310.pyc,, +thriftpy2/contrib/aio/__pycache__/http.cpython-310.pyc,, +thriftpy2/contrib/aio/__pycache__/processor.cpython-310.pyc,, +thriftpy2/contrib/aio/__pycache__/rpc.cpython-310.pyc,, +thriftpy2/contrib/aio/__pycache__/server.cpython-310.pyc,, +thriftpy2/contrib/aio/__pycache__/socket.cpython-310.pyc,, +thriftpy2/contrib/aio/client.py,sha256=ozx0S9phxBvTYnjeKHRy0mgjCf22EsHrK6NJ7bCE7-w,3008 +thriftpy2/contrib/aio/http.py,sha256=zKNeHMeUMtyWMCO3qxzKu0ePGg35Ze_0rBgP6og8wSc,12939 +thriftpy2/contrib/aio/processor.py,sha256=caR7OX3xhxLWe-yGquVlF3K1sSliRoreBL2rFsJ0OUQ,2415 +thriftpy2/contrib/aio/protocol/__init__.py,sha256=T4bJpG2vPilxx0tX71hZT9vJQ2ecFU3s22pCi2PJGDA,414 +thriftpy2/contrib/aio/protocol/__pycache__/__init__.cpython-310.pyc,, +thriftpy2/contrib/aio/protocol/__pycache__/base.cpython-310.pyc,, +thriftpy2/contrib/aio/protocol/__pycache__/binary.cpython-310.pyc,, +thriftpy2/contrib/aio/protocol/__pycache__/compact.cpython-310.pyc,, +thriftpy2/contrib/aio/protocol/base.py,sha256=zVAbMz9xTvZI-ynJuKJyeBnHMCaZB1Gc1CBiop_l714,682 +thriftpy2/contrib/aio/protocol/binary.py,sha256=a_bODpOkceiZTFhnZYd6uvWN48ZzjKjNfmHEc-JcPGM,8706 +thriftpy2/contrib/aio/protocol/compact.py,sha256=U2tpSRQyitSkwC-aqA0t3XGDl-i_RlB02v4VJWVnOt8,9678 +thriftpy2/contrib/aio/rpc.py,sha256=NAUWnDEtz4UIkdAO1es9SELaNCdn_QWNtTo0V4jGFRY,3588 +thriftpy2/contrib/aio/server.py,sha256=FfN5pT0opIUFcr2ItB2kxkotOXBwf6DQTnNEyZ822E0,2025 +thriftpy2/contrib/aio/socket.py,sha256=xdftBLEeo_6N8RWPUsfMIfWHFOpFDZj6YwLXmDNaUDY,13681 +thriftpy2/contrib/aio/transport/__init__.py,sha256=HAhbKzsIyu8carLjVBtHTL6X4U3YsfcuKUn6qGUDgeA,429 +thriftpy2/contrib/aio/transport/__pycache__/__init__.cpython-310.pyc,, +thriftpy2/contrib/aio/transport/__pycache__/base.cpython-310.pyc,, +thriftpy2/contrib/aio/transport/__pycache__/buffered.cpython-310.pyc,, +thriftpy2/contrib/aio/transport/__pycache__/framed.cpython-310.pyc,, +thriftpy2/contrib/aio/transport/base.py,sha256=RQ6M6ZkFnpMy9Ls6czZyCR662X1CstjfBZBRHuZ3mpM,1048 +thriftpy2/contrib/aio/transport/buffered.py,sha256=ULOWZ0DfEZ7jK2HA-3BOvRRMKQe-_j5T-eqaVtalJGc,1557 +thriftpy2/contrib/aio/transport/framed.py,sha256=drSma_W_XDCLi38F5Bp6LIBZ9fSW5w2bchl8iNUMOTU,2048 +thriftpy2/contrib/tracking/__init__.py,sha256=A3fqkiJi_DgUggluyRvW3E8BIU9Xw8uj2-xegcJvW7I,7722 +thriftpy2/contrib/tracking/__pycache__/__init__.cpython-310.pyc,, +thriftpy2/contrib/tracking/__pycache__/tracker.cpython-310.pyc,, +thriftpy2/contrib/tracking/tracker.py,sha256=_oW4OR_EYjxOjJwdMSaoN16bz2LSfmLuh7E3qCUNQh4,3877 +thriftpy2/contrib/tracking/tracking.thrift,sha256=oW7jEISaN559Ob4Segkaz5psozk4QWIu6zenS5sNtIE,404 +thriftpy2/hook.py,sha256=TZ4z-y7fDeTmfVsUR4HciAVL-FEduBoQOg8NGICieCg,1245 +thriftpy2/http.py,sha256=gps4rCemQk3UDlAGOKxups1pyPehbcG6GeLeVSdpri4,13343 +thriftpy2/parser/__init__.py,sha256=NSDtxdJ2GxHP3L51KUmyPcobGZs9IK7-OiZPuM_72VA,8687 +thriftpy2/parser/__pycache__/__init__.cpython-310.pyc,, +thriftpy2/parser/__pycache__/exc.cpython-310.pyc,, +thriftpy2/parser/__pycache__/lexer.cpython-310.pyc,, +thriftpy2/parser/__pycache__/parser.cpython-310.pyc,, +thriftpy2/parser/exc.py,sha256=THX1ldeeEuH9W-JC4BcsF3peEbzDHoDmaaozr1AAqCY,687 +thriftpy2/parser/lexer.py,sha256=4jTQpWul5clEG0KjK4hvB1Hrg268WkG1KJ6agn6QoXo,4165 +thriftpy2/parser/parser.py,sha256=JewekQG6C_E7QKJOE-L7WA3Nw4bZhQlkba9rwJ6CcNg,30289 +thriftpy2/protocol/__init__.py,sha256=5iUMUIX-NK8Z6wsAILXkFNLs1N86qs3qgjHgNa6dQXo,1271 +thriftpy2/protocol/__pycache__/__init__.cpython-310.pyc,, +thriftpy2/protocol/__pycache__/apache_json.cpython-310.pyc,, +thriftpy2/protocol/__pycache__/base.cpython-310.pyc,, +thriftpy2/protocol/__pycache__/binary.cpython-310.pyc,, +thriftpy2/protocol/__pycache__/compact.cpython-310.pyc,, +thriftpy2/protocol/__pycache__/exc.cpython-310.pyc,, +thriftpy2/protocol/__pycache__/json.cpython-310.pyc,, +thriftpy2/protocol/__pycache__/multiplex.cpython-310.pyc,, +thriftpy2/protocol/apache_json.py,sha256=cV0PeszJ314rgTV_gEDfv4_1zTvErj42Fj0GXWEg8iI,12197 +thriftpy2/protocol/base.py,sha256=m9Ip8SCgPSiAq5U1lABRDQv0FvHitz0lzClcMnixjOA,1034 +thriftpy2/protocol/binary.py,sha256=XoFtN2mciY8rOsBwxhXFzokSGgLjDP84yIw3rxm_7Ns,11803 +thriftpy2/protocol/compact.py,sha256=LJP35ZYuBxHQNkVJkLKu1v8EdCWARtRGEixhTcjM4PY,16965 +thriftpy2/protocol/cybin/__init__.py,sha256=d0VD-fPAwqmXO8ifaZ9zXSAGi_mXUcVugqrvI9uz34w,21 +thriftpy2/protocol/cybin/__pycache__/__init__.cpython-310.pyc,, +thriftpy2/protocol/cybin/cybin.c,sha256=bZV2qFe381AtIvxTaOS0ovixB77E_s5Nphacr_ceQ4g,921877 +thriftpy2/protocol/cybin/cybin.cpython-310-x86_64-linux-gnu.so,sha256=xsNnGU-ehcmhFUhlNjL-4wk9RJdxCDEdsNtcYe2SzRc,1271656 +thriftpy2/protocol/cybin/cybin.pyx,sha256=VxR2h6JWobkw2zGGf9m-8hWpmFalr_PgkOR7ipu9FCQ,14057 +thriftpy2/protocol/cybin/endian_port.h,sha256=k2lXa_tm-0uzcvy9gE-UjxT3x-An_k7eIIop7pXbf3Q,4154 +thriftpy2/protocol/exc.py,sha256=K_lJymamb2raWcycSG502TQbUb5e5QAOTrCKuaWOtBc,939 +thriftpy2/protocol/json.py,sha256=gZhgU-vH1ICDoWJZj2LcLqF9F6kj7Z30vYTEz0-aCU0,6856 +thriftpy2/protocol/multiplex.py,sha256=kbuy9_OWRVdQR958AGUgFIGTcX0SGB3Kz2MU-EXJHiI,1217 +thriftpy2/rpc.py,sha256=1h0kHjwRF8yd0BknLwfmY3CGEXzPO1ua_2j1H-AJ9ww,6510 +thriftpy2/server.py,sha256=0PNXHyDjxNIeDXnHvTVuSucfkApUZykkn_YTjRAh5Dc,3563 +thriftpy2/thrift.py,sha256=6V4dNKAqJa_JYRCiU3feh6wviuVn5ulXQC-dd_OF-v0,14825 +thriftpy2/tornado.py,sha256=yMMa1phsaCZEMuzTnvctdVc_X-o32p3vgCZXUEkC1rM,9922 +thriftpy2/transport/__init__.py,sha256=eTArYMX4zqB1ldl97FTHfFSIRjQrKc56jBQIMxD6W4A,1958 +thriftpy2/transport/__pycache__/__init__.cpython-310.pyc,, +thriftpy2/transport/__pycache__/_ssl.cpython-310.pyc,, +thriftpy2/transport/__pycache__/base.cpython-310.pyc,, +thriftpy2/transport/__pycache__/socket.cpython-310.pyc,, +thriftpy2/transport/__pycache__/sslsocket.cpython-310.pyc,, +thriftpy2/transport/_ssl.py,sha256=ztoxJy8HaI1CBKwPYnnO3-sr5nlnlWLYs3uc1LoTWEA,2342 +thriftpy2/transport/base.py,sha256=9DKJLV6xN1vN_XQ5XxUQx6S1iq0WbeUIiPODIba_5F4,2909 +thriftpy2/transport/buffered/__init__.py,sha256=D3vXn8st5aZ_syJBLEMNRb7Zu4soEFY5iT-wXMpzyeE,1673 +thriftpy2/transport/buffered/__pycache__/__init__.cpython-310.pyc,, +thriftpy2/transport/buffered/cybuffered.c,sha256=9JQJz6qaTETjeAEgPoSEOUnOFmDhFEMr6kBCbedn1Mg,538410 +thriftpy2/transport/buffered/cybuffered.cpython-310-x86_64-linux-gnu.so,sha256=sTJ_MlvzPMr8ZAxef_YmzPjod6ViZY2m4YKjeItwpIM,620336 +thriftpy2/transport/buffered/cybuffered.pyx,sha256=hrYhKA-Wip1o64eHRWleahJ6DEc3zhpW-tY_Kz4KpNo,2326 +thriftpy2/transport/cybase.c,sha256=LN2cpTNZN7D_qc_ZrfueCLL2zIrVPx9UxqV39u_uZTk,500605 +thriftpy2/transport/cybase.cpython-310-x86_64-linux-gnu.so,sha256=-7W1sAecUY8TixxYJkuvvPO4rXmtWuE94ymtgSfw1Sk,528104 +thriftpy2/transport/cybase.pxd,sha256=19CfCq4C4gk63qQpgyP1DycJd5jVUv1I_hhcUxAfeR4,605 +thriftpy2/transport/cybase.pyx,sha256=dDFe2Ds5iFeufOjNPdZGu_7wnPPNsTHnqu1zcLDuMpg,3582 +thriftpy2/transport/framed/__init__.py,sha256=LJpTzEEllt9My3NiqjHLXrqu4-J02Oil7Uar2EVui50,2091 +thriftpy2/transport/framed/__pycache__/__init__.cpython-310.pyc,, +thriftpy2/transport/framed/cyframed.c,sha256=lOxZ0pY8ZZWbnhdM2sahXzwozLJErKmbGdpfnaxppKU,557579 +thriftpy2/transport/framed/cyframed.cpython-310-x86_64-linux-gnu.so,sha256=esoDOljzWNVIMoix-yrnxEmpp2t3TS3ETtODJE91Ebw,656352 +thriftpy2/transport/framed/cyframed.pyx,sha256=3n5Ch7X91cf35IcUlQlEjiabbPCYzTQhQNT3FUMMaXo,3596 +thriftpy2/transport/memory/__init__.py,sha256=71VxKW9KLIVso8BlY0SACYBkHSNIuG2quqn0tYAu4xc,1264 +thriftpy2/transport/memory/__pycache__/__init__.cpython-310.pyc,, +thriftpy2/transport/memory/cymemory.c,sha256=FHLwv1YFn-5p0NHNaYDdJnEOuEKhGFfqcQkJquTlWEg,508566 +thriftpy2/transport/memory/cymemory.cpython-310-x86_64-linux-gnu.so,sha256=n2nhN8lQJJV1R4wWimDgTDFao1_Uz0Ko7ADAKygdhU0,537968 +thriftpy2/transport/memory/cymemory.pyx,sha256=vUbY-KdvBiTTsBbX2UpQzCUiYWQMa9X1nc638BcduDs,2051 +thriftpy2/transport/sasl/__init__.py,sha256=cgN0HH3qqavM2sCUZqgQFPz98UEGfTQJhmtjuAKOV8E,7576 +thriftpy2/transport/sasl/__pycache__/__init__.cpython-310.pyc,, +thriftpy2/transport/sasl/cysasl.c,sha256=CaZ8JIP-w8xK074AEJTyVE3oAR6etzmBM8C34cyGymw,671930 +thriftpy2/transport/sasl/cysasl.cpython-310-x86_64-linux-gnu.so,sha256=Zv-vCV5QFeRqgZthH3In44vZZG3T7QsEtUbnnGUcl2A,994976 +thriftpy2/transport/sasl/cysasl.pyx,sha256=8jDUkcrANJSKEaa9HbxF1INsIlP_j9fc9jG4CfjSZMM,7519 +thriftpy2/transport/socket.py,sha256=9gCmBo9cumZqla93VkZnKIRI0lpacmEYvbApdv_EcjI,7879 +thriftpy2/transport/sslsocket.py,sha256=3dfM2if6_wN99eOQMthPO1YdjyrG6zmr8SLolEJChNA,4945 +thriftpy2/utils.py,sha256=3rvzimVjyRpyDpd0SVqQ0LUl5gT0GVi5R-JHRYVGtQg,1157 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2-0.6.0.dist-info/REQUESTED b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2-0.6.0.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2-0.6.0.dist-info/WHEEL b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2-0.6.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..204fb1e311d94a456743e507a14db9c0785cd812 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2-0.6.0.dist-info/WHEEL @@ -0,0 +1,7 @@ +Wheel-Version: 1.0 +Generator: setuptools (82.0.0) +Root-Is-Purelib: false +Tag: cp310-cp310-manylinux_2_17_x86_64 +Tag: cp310-cp310-manylinux2014_x86_64 +Tag: cp310-cp310-manylinux_2_28_x86_64 + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2-0.6.0.dist-info/licenses/LICENSE b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2-0.6.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..91f57ef02437e8dded6828c58b3b8aa8e4fa1ae2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2-0.6.0.dist-info/licenses/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) <2014> + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2-0.6.0.dist-info/top_level.txt b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2-0.6.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..39a40d84842811f4599a93be534cae72d829d113 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2-0.6.0.dist-info/top_level.txt @@ -0,0 +1 @@ +thriftpy2 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d37b01c4f941a20097b91e4dd05d56ce8820793f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/__init__.py @@ -0,0 +1,11 @@ +# -*- coding: utf-8 -*- + +import sys + +from .hook import install_import_hook, remove_import_hook +from .parser import load, load_module, load_fp + +__version__ = '0.6.0' +__python__ = sys.version_info +__all__ = ["install_import_hook", "remove_import_hook", "load", "load_module", + "load_fp"] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/_compat.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..d107842608f82385299b7339c34815b65ea810c1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/_compat.py @@ -0,0 +1,18 @@ +# -*- coding: utf-8 -*- + +""" + thriftpy2._compat + ~~~~~~~~~~~~~ + + py2/py3 compatibility support. +""" + +from __future__ import absolute_import + +import platform +import sys + +PYPY = "__pypy__" in sys.modules + +UNIX = platform.system() in ("Linux", "Darwin") +CYTHON = not PYPY # Cython always disabled in pypy diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/contrib/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/contrib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/contrib/aio/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/contrib/aio/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/contrib/aio/client.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/contrib/aio/client.py new file mode 100644 index 0000000000000000000000000000000000000000..2e2136ddc37de7542d5c5d9d00979ecec126bf00 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/contrib/aio/client.py @@ -0,0 +1,83 @@ +# -*- coding: utf-8 -*- +import functools +from thriftpy2.thrift import args_to_kwargs +from thriftpy2.thrift import TApplicationException, TMessageType + + +class TAsyncClient: + + def __init__(self, service, iprot, oprot=None): + self._service = service + self._iprot = self._oprot = iprot + if oprot is not None: + self._oprot = oprot + self._seqid = 0 + + def __getattr__(self, _api): + if _api in self._service.thrift_services: + return functools.partial(self._req, _api) + + raise AttributeError("{} instance has no attribute '{}'".format( + self.__class__.__name__, _api)) + + def __dir__(self): + return self._service.thrift_services + + async def _req(self, _api, *args, **kwargs): + try: + service_args = getattr(self._service, _api + "_args") + kwargs = args_to_kwargs(service_args.thrift_spec, *args, **kwargs) + except ValueError as e: + raise TApplicationException( + TApplicationException.UNKNOWN_METHOD, + 'missing required argument {arg} for {service}.{api}'.format( + arg=e.args[0], service=self._service.__name__, api=_api)) + result_cls = getattr(self._service, _api + "_result") + + await self._send(_api, **kwargs) + # wait result only if non-oneway + if not getattr(result_cls, "oneway"): + return await self._recv(_api) + + async def _send(self, _api, **kwargs): + oneway = getattr(getattr(self._service, _api + "_result"), "oneway") + msg_type = TMessageType.ONEWAY if oneway else TMessageType.CALL + self._oprot.write_message_begin(_api, msg_type, self._seqid) + args = getattr(self._service, _api + "_args")() + for k, v in kwargs.items(): + setattr(args, k, v) + self._oprot.write_struct(args) + self._oprot.write_message_end() + await self._oprot.trans.flush() + + async def _recv(self, _api): + fname, mtype, rseqid = await self._iprot.read_message_begin() + if mtype == TMessageType.EXCEPTION: + x = TApplicationException() + await self._iprot.read_struct(x) + await self._iprot.read_message_end() + raise x + result = getattr(self._service, _api + "_result")() + await self._iprot.read_struct(result) + await self._iprot.read_message_end() + + if hasattr(result, "success") and result.success is not None: + return result.success + + # void api without throws + if len(result.thrift_spec) == 0: + return + + # check throws + for k, v in result.__dict__.items(): + if k != "success" and v: + raise v + + # no throws & not void api + if hasattr(result, "success"): + raise TApplicationException(TApplicationException.MISSING_RESULT) + + def close(self): + self._iprot.trans.close() + if self._iprot != self._oprot: + self._oprot.trans.close() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/contrib/aio/http.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/contrib/aio/http.py new file mode 100644 index 0000000000000000000000000000000000000000..529613486deba5d9409018f1f2f76c6075f0f988 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/contrib/aio/http.py @@ -0,0 +1,417 @@ +""" +Async HTTP transport for thriftpy2. + +# Run server: +>>> import asyncio +>>> import thriftpy2 +>>> from thriftpy2.contrib.aio.http import make_server +>>> pingpong = thriftpy2.load("pingpong.thrift") +>>> +>>> class Dispatcher: +>>> async def ping(self): +>>> return "pong" +>>> +>>> server = make_server(pingpong.PingService, Dispatcher(), + host='127.0.0.1', port=6000) +>>> asyncio.run(server.serve()) + +# Run client: +>>> import asyncio +>>> import thriftpy2 +>>> from thriftpy2.contrib.aio.http import make_client +>>> pingpong = thriftpy2.load("pingpong.thrift") +>>> async def main(): +... client = await make_client(pingpong.PingService, +... host='127.0.0.1', port=6000) +... print(await client.ping()) +... client.close() +>>> asyncio.run(main()) +""" + +import asyncio +import urllib.parse +from contextlib import asynccontextmanager +from io import BytesIO + +import aiohttp +from aiohttp import web + +from thriftpy2.contrib.aio.client import TAsyncClient +from thriftpy2.contrib.aio.processor import TAsyncProcessor +from thriftpy2.contrib.aio.protocol import TAsyncBinaryProtocolFactory +from thriftpy2.contrib.aio.transport.base import TAsyncTransportBase +from thriftpy2.transport import TTransportException + +HTTP_URI = '{scheme}://{host}:{port}{path}' +DEFAULT_HTTP_CLIENT_TIMEOUT_MS = 30000 # 30 seconds + + +class TAsyncHttpHeaderFactory: + """Default header factory that returns custom headers.""" + + def __init__(self, headers=None): + """Initialize a header factory. + + @param headers(dict): A dictionary of static headers the factory generates + """ + self._headers = headers if headers else {} + + def get_headers(self): + return self._headers + + +class TAsyncMemoryBuffer(TAsyncTransportBase): + """Async memory buffer transport.""" + + def __init__(self, value=b''): + self._buffer = BytesIO(value) + + def is_open(self): + return True + + async def open(self): + pass + + def close(self): + self._buffer.close() + + async def _read(self, sz): + return self._buffer.read(sz) + + def write(self, buf): + self._buffer.write(buf) + + async def flush(self): + pass + + def getvalue(self): + return self._buffer.getvalue() + + def setvalue(self, value): + self._buffer = BytesIO(value) + + +class TAsyncHttpClient(TAsyncTransportBase): + """Async HTTP implementation of TTransport.""" + + def __init__(self, uri, timeout=None, ssl_context=None, + http_header_factory=None): + """Initialize an async HTTP transport. + + @param uri(str): The http_scheme://host:port/path to connect to. + @param timeout: Timeout in milliseconds. + @param ssl_context: SSL context for HTTPS connections. + @param http_header_factory: Factory for custom HTTP headers. + """ + parsed = urllib.parse.urlparse(uri) + self.scheme = parsed.scheme + assert self.scheme in ('http', 'https') + + if self.scheme == 'http': + self.port = parsed.port or 80 + elif self.scheme == 'https': + self.port = parsed.port or 443 + + self.host = parsed.hostname + self.path = parsed.path or '/' + if parsed.query: + self.path += '?%s' % parsed.query + + self._wbuf = BytesIO() + self._rbuf = BytesIO() + self._session = None + self._http_header_factory = http_header_factory or TAsyncHttpHeaderFactory() + self._timeout = None + self._ssl_context = ssl_context + if timeout: + self.set_timeout(timeout) + + def is_open(self): + return self._session is not None and not self._session.closed + + async def open(self): + if self._session is not None and not self._session.closed: + return + + timeout = aiohttp.ClientTimeout( + total=self._timeout + ) if self._timeout else None + + connector = aiohttp.TCPConnector(ssl=self._ssl_context) + self._session = aiohttp.ClientSession( + timeout=timeout, + connector=connector + ) + + def close(self): + """Synchronous close - marks session as closed. + + For proper async cleanup, use aclose() instead. + """ + if self._session is not None: + # Just mark as None, the session will be cleaned up by GC + # For proper cleanup, use aclose() or client_context + self._session = None + + async def aclose(self): + """Async close method.""" + if self._session is not None and not self._session.closed: + await self._session.close() + self._session = None + + def set_timeout(self, ms): + """Set timeout in milliseconds.""" + self._timeout = ms / 1000.0 if (ms and ms > 0) else None + + def set_custom_headers(self, headers): + self._http_header_factory = TAsyncHttpHeaderFactory(headers) + + async def _read(self, sz): + return self._rbuf.read(sz) + + def write(self, buf): + self._wbuf.write(buf) + + async def flush(self): + """Send buffered data as HTTP POST request.""" + data = self._wbuf.getvalue() + self._wbuf = BytesIO() + + if not data: + return + + if not self.is_open(): + await self.open() + + url = HTTP_URI.format( + scheme=self.scheme, + host=self.host, + port=self.port, + path=self.path + ) + + headers = { + 'Content-Type': 'application/x-thrift', + 'Accept': 'application/x-thrift', + } + + custom_headers = self._http_header_factory.get_headers() + if custom_headers: + headers.update(custom_headers) + + if 'User-Agent' not in headers: + headers['User-Agent'] = 'Python/TAsyncHttpClient' + + async with self._session.post(url, data=data, headers=headers) as resp: + self.code = resp.status + self.message = resp.reason + self.headers = resp.headers + + if resp.status != 200: + raise TTransportException( + type=TTransportException.UNKNOWN, + message='HTTP request failed with status %d: %s' % ( + resp.status, resp.reason + ) + ) + + response_data = await resp.read() + self._rbuf = BytesIO(response_data) + + +class TAsyncHttpServer: + """Async HTTP server based on aiohttp.web.""" + + def __init__(self, processor, host, port, iprot_factory, + ssl_context=None): + """Initialize the async HTTP server. + + @param processor: The TAsyncProcessor to handle requests. + @param host: The host to bind to. + @param port: The port to bind to. + @param iprot_factory: The protocol factory for incoming requests. + @param ssl_context: SSL context for HTTPS. + """ + self.processor = processor + self.host = host + self.port = port + self.iprot_factory = iprot_factory + self.ssl_context = ssl_context + self._app = None + self._runner = None + self._site = None + + async def _handle_request(self, request): + """Handle incoming HTTP POST request.""" + if request.method != 'POST': + return web.Response(status=405, text='Method Not Allowed') + + try: + data = await request.read() + + # Create input transport and protocol + itrans = TAsyncMemoryBuffer(data) + iprot = self.iprot_factory.get_protocol(itrans) + + # Create output transport and protocol + otrans = TAsyncMemoryBuffer() + oprot = self.iprot_factory.get_protocol(otrans) + + # Process the request + await self.processor.process(iprot, oprot) + + # Return response + response_data = otrans.getvalue() + return web.Response( + body=response_data, + content_type='application/x-thrift' + ) + + except Exception as e: + return web.Response( + status=500, + text='Internal Server Error: %s' % str(e) + ) + + async def serve(self): + """Start the HTTP server.""" + self._app = web.Application() + self._app.router.add_post('/{path:.*}', self._handle_request) + self._app.router.add_post('', self._handle_request) + + self._runner = web.AppRunner(self._app) + await self._runner.setup() + + self._site = web.TCPSite( + self._runner, + self.host, + self.port, + ssl_context=self.ssl_context + ) + await self._site.start() + + # Keep running until closed + try: + while True: + await asyncio.sleep(3600) + except asyncio.CancelledError: + pass + + async def close(self): + """Close the HTTP server.""" + if self._runner: + await self._runner.cleanup() + self._runner = None + self._site = None + self._app = None + + +async def make_client(service, host='localhost', port=9090, path='', + scheme='http', proto_factory=None, + ssl_context=None, http_header_factory=None, + timeout=DEFAULT_HTTP_CLIENT_TIMEOUT_MS, url=''): + """Create an async HTTP client. + + @param service: The Thrift service class. + @param host: The host to connect to. + @param port: The port to connect to. + @param path: The URL path. + @param scheme: The URL scheme (http or https). + @param proto_factory: The protocol factory. + @param ssl_context: SSL context for HTTPS. + @param http_header_factory: Factory for custom HTTP headers. + @param timeout: Timeout in milliseconds. + @param url: Full URL (overrides host, port, scheme, path). + @return: TAsyncClient instance. + """ + if proto_factory is None: + proto_factory = TAsyncBinaryProtocolFactory() + + if url: + parsed_url = urllib.parse.urlparse(url) + host = parsed_url.hostname or host + port = parsed_url.port or port + scheme = parsed_url.scheme or scheme + path = parsed_url.path or path + + if path and path[0] != '/': + path = '/' + path + + uri = HTTP_URI.format(scheme=scheme, host=host, port=port, path=path) + http_client = TAsyncHttpClient( + uri, timeout, ssl_context, http_header_factory + ) + + await http_client.open() + iprot = proto_factory.get_protocol(http_client) + + return TAsyncClient(service, iprot) + + +@asynccontextmanager +async def client_context(service, host='localhost', port=9090, path='', + scheme='http', proto_factory=None, + ssl_context=None, http_header_factory=None, + timeout=DEFAULT_HTTP_CLIENT_TIMEOUT_MS, url=''): + """Async context manager for HTTP client. + + @param service: The Thrift service class. + @param host: The host to connect to. + @param port: The port to connect to. + @param path: The URL path. + @param scheme: The URL scheme (http or https). + @param proto_factory: The protocol factory. + @param ssl_context: SSL context for HTTPS. + @param http_header_factory: Factory for custom HTTP headers. + @param timeout: Timeout in milliseconds. + @param url: Full URL (overrides host, port, scheme, path). + @return: TAsyncClient instance. + """ + if proto_factory is None: + proto_factory = TAsyncBinaryProtocolFactory() + + if url: + parsed_url = urllib.parse.urlparse(url) + host = parsed_url.hostname or host + port = parsed_url.port or port + scheme = parsed_url.scheme or scheme + path = parsed_url.path or path + + if path and path[0] != '/': + path = '/' + path + + uri = HTTP_URI.format(scheme=scheme, host=host, port=port, path=path) + http_client = TAsyncHttpClient( + uri, timeout, ssl_context, http_header_factory + ) + + try: + await http_client.open() + iprot = proto_factory.get_protocol(http_client) + yield TAsyncClient(service, iprot) + finally: + await http_client.aclose() + + +def make_server(service, handler, host, port, + proto_factory=None, ssl_context=None): + """Create an async HTTP server. + + @param service: The Thrift service class. + @param handler: The handler implementing the service methods. + @param host: The host to bind to. + @param port: The port to bind to. + @param proto_factory: The protocol factory. + @param ssl_context: SSL context for HTTPS. + @return: TAsyncHttpServer instance. + """ + if proto_factory is None: + proto_factory = TAsyncBinaryProtocolFactory() + + processor = TAsyncProcessor(service, handler) + server = TAsyncHttpServer( + processor, host, port, + iprot_factory=proto_factory, + ssl_context=ssl_context + ) + return server diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/contrib/aio/processor.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/contrib/aio/processor.py new file mode 100644 index 0000000000000000000000000000000000000000..76e3b1be2b42d40bd671a4e36ea74b0c89847c00 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/contrib/aio/processor.py @@ -0,0 +1,69 @@ +# -*- coding: utf-8 -*- +from thriftpy2.thrift import TApplicationException, TType, TMessageType + + +class TAsyncProcessor(object): + + def __init__(self, service, handler): + self._service = service + self._handler = handler + + async def process_in(self, iprot): + api, type, seqid = await iprot.read_message_begin() + if api not in self._service.thrift_services: + await iprot.skip(TType.STRUCT) + await iprot.read_message_end() + return api, seqid, TApplicationException(TApplicationException.UNKNOWN_METHOD), None # noqa + + args = getattr(self._service, api + "_args")() + await iprot.read_struct(args) + await iprot.read_message_end() + result = getattr(self._service, api + "_result")() + + # convert kwargs to args + api_args = [args.thrift_spec[k][1] for k in sorted(args.thrift_spec)] + + async def call(): + f = getattr(self._handler, api) + return await f(*(args.__dict__[k] for k in api_args)) + + return api, seqid, result, call + + async def send_exception(self, oprot, api, exc, seqid): + oprot.write_message_begin(api, TMessageType.EXCEPTION, seqid) + exc.write(oprot) + oprot.write_message_end() + await oprot.trans.flush() + + async def send_result(self, oprot, api, result, seqid): + oprot.write_message_begin(api, TMessageType.REPLY, seqid) + oprot.write_struct(result) + oprot.write_message_end() + await oprot.trans.flush() + + def handle_exception(self, e, result): + for k in sorted(result.thrift_spec): + if result.thrift_spec[k][1] == "success": + continue + + _, exc_name, exc_cls, _ = result.thrift_spec[k] + if isinstance(e, exc_cls): + setattr(result, exc_name, e) + return True + return False + + async def process(self, iprot, oprot): + api, seqid, result, call = await self.process_in(iprot) + + if isinstance(result, TApplicationException): + return (await self.send_exception(oprot, api, result, seqid)) + + try: + result.success = await call() + except Exception as e: + # raise if api don't have throws + if not self.handle_exception(e, result): + raise + + if not result.oneway: + await self.send_result(oprot, api, result, seqid) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/contrib/aio/protocol/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/contrib/aio/protocol/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..75634158cb71836979055576801fc2326482c718 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/contrib/aio/protocol/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- + +from __future__ import absolute_import + +__all__ = [ + 'TAsyncProtocolBase', + 'TAsyncBinaryProtocol', + 'TAsyncBinaryProtocolFactory', + 'TAsyncCompactProtocol', + 'TAsyncCompactProtocolFactory', +] + +from .base import TAsyncProtocolBase +from .binary import TAsyncBinaryProtocol, TAsyncBinaryProtocolFactory +from .compact import TAsyncCompactProtocol, TAsyncCompactProtocolFactory diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/contrib/aio/protocol/base.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/contrib/aio/protocol/base.py new file mode 100644 index 0000000000000000000000000000000000000000..487ec7bdd997a5e4983bd11e95986f93126cecaf --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/contrib/aio/protocol/base.py @@ -0,0 +1,28 @@ +# -*- coding: utf-8 -*- + +from thriftpy2.protocol import TProtocolBase + + +class TAsyncProtocolBase(TProtocolBase): + """Base class for Thrift async protocol layer.""" + + async def skip(self, ttype): + raise NotImplementedError + + async def read_message_begin(self): + raise NotImplementedError + + async def read_message_end(self): + raise NotImplementedError + + def write_message_begin(self, name, ttype, seqid): + raise NotImplementedError + + def write_message_end(self): + raise NotImplementedError + + async def read_struct(self, obj): + raise NotImplementedError + + def write_struct(self, obj): + raise NotImplementedError diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/contrib/aio/protocol/binary.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/contrib/aio/protocol/binary.py new file mode 100644 index 0000000000000000000000000000000000000000..421eb70249975fbbac9939e71bd0562abe399457 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/contrib/aio/protocol/binary.py @@ -0,0 +1,297 @@ +# -*- coding: utf-8 -*- + +from __future__ import absolute_import + +from thriftpy2.thrift import TType + +from thriftpy2.protocol.exc import TProtocolException +from thriftpy2.protocol.binary import ( + VERSION_MASK, + VERSION_1, + TYPE_MASK, + unpack_i8, + unpack_i16, + unpack_i32, + unpack_i64, + unpack_double, + write_message_begin, + write_val +) + +from .base import TAsyncProtocolBase + +BIN_TYPES = (TType.STRING, TType.BINARY) + + +async def read_message_begin(inbuf, strict=True): + sz = unpack_i32(await inbuf.read(4)) + if sz < 0: + version = sz & VERSION_MASK + if version != VERSION_1: + raise TProtocolException( + type=TProtocolException.BAD_VERSION, + message='Bad version in read_message_begin: %d' % (sz)) + name_sz = unpack_i32(await inbuf.read(4)) + name = await inbuf.read(name_sz) + name = name.decode('utf-8') + + type_ = sz & TYPE_MASK + else: + if strict: + raise TProtocolException(type=TProtocolException.BAD_VERSION, + message='No protocol version header') + + name = await inbuf.read(sz) + type_ = unpack_i8(await inbuf.read(1)) + + seqid = unpack_i32(await inbuf.read(4)) + + return name, type_, seqid + + +async def read_field_begin(inbuf): + f_type = unpack_i8(await inbuf.read(1)) + if f_type == TType.STOP: + return f_type, 0 + + return f_type, unpack_i16(await inbuf.read(2)) + + +async def read_list_begin(inbuf): + e_type = unpack_i8(await inbuf.read(1)) + sz = unpack_i32(await inbuf.read(4)) + return e_type, sz + + +async def read_map_begin(inbuf): + k_type = unpack_i8(await inbuf.read(1)) + v_type = unpack_i8(await inbuf.read(1)) + sz = unpack_i32(await inbuf.read(4)) + return k_type, v_type, sz + + +async def read_val(inbuf, ttype, spec=None, decode_response=True, + strict_decode=False): + if ttype == TType.BOOL: + return bool(unpack_i8(await inbuf.read(1))) + + elif ttype == TType.BYTE: + return unpack_i8(await inbuf.read(1)) + + elif ttype == TType.I16: + return unpack_i16(await inbuf.read(2)) + + elif ttype == TType.I32: + return unpack_i32(await inbuf.read(4)) + + elif ttype == TType.I64: + return unpack_i64(await inbuf.read(8)) + + elif ttype == TType.DOUBLE: + return unpack_double(await inbuf.read(8)) + + elif ttype == TType.BINARY: + sz = unpack_i32(await inbuf.read(4)) + return await inbuf.read(sz) + + elif ttype == TType.STRING: + sz = unpack_i32(await inbuf.read(4)) + byte_payload = await inbuf.read(sz) + + # Since we cannot tell if we're getting STRING or BINARY + # if not asked not to decode, try both + if decode_response: + try: + return byte_payload.decode('utf-8') + except UnicodeDecodeError: + if strict_decode: + raise + return byte_payload + + elif ttype == TType.SET or ttype == TType.LIST: + if isinstance(spec, tuple): + v_type, v_spec = spec[0], spec[1] + else: + v_type, v_spec = spec, None + + result = [] + r_type, sz = await read_list_begin(inbuf) + # the v_type is useless here since we already get it from spec + if (r_type != v_type + and not (r_type in BIN_TYPES and v_type in BIN_TYPES)): + for _ in range(sz): + await skip(inbuf, r_type) + return [] + + for i in range(sz): + result.append( + await read_val(inbuf, v_type, v_spec, decode_response, + strict_decode) + ) + return result + + elif ttype == TType.MAP: + if isinstance(spec[0], int): + k_type = spec[0] + k_spec = None + else: + k_type, k_spec = spec[0] + + if isinstance(spec[1], int): + v_type = spec[1] + v_spec = None + else: + v_type, v_spec = spec[1] + + result = {} + sk_type, sv_type, sz = await read_map_begin(inbuf) + if sk_type in BIN_TYPES: + sk_type = k_type + if sv_type in BIN_TYPES: + sv_type = v_type + if sk_type != k_type or sv_type != v_type: + for _ in range(sz): + await skip(inbuf, sk_type) + await skip(inbuf, sv_type) + return {} + + for i in range(sz): + k_val = await read_val(inbuf, k_type, k_spec, decode_response, + strict_decode) + v_val = await read_val(inbuf, v_type, v_spec, decode_response, + strict_decode) + result[k_val] = v_val + + return result + + elif ttype == TType.STRUCT: + obj = spec() + await read_struct(inbuf, obj, decode_response, strict_decode) + return obj + + +async def read_struct(inbuf, obj, decode_response=True, strict_decode=False): + while True: + f_type, fid = await read_field_begin(inbuf) + if f_type == TType.STOP: + break + + if fid not in obj.thrift_spec: + await skip(inbuf, f_type) + continue + + if len(obj.thrift_spec[fid]) == 3: + sf_type, f_name, f_req = obj.thrift_spec[fid] + f_container_spec = None + else: + sf_type, f_name, f_container_spec, f_req = obj.thrift_spec[fid] + + # it really should equal here. but since we already wasted + # space storing the duplicate info, let's check it. + if f_type != sf_type: + if f_type in BIN_TYPES: + f_type = sf_type + else: + await skip(inbuf, f_type) + continue + + _buf = await read_val( + inbuf, f_type, f_container_spec, decode_response, strict_decode) + setattr(obj, f_name, _buf) + + +async def skip(inbuf, ftype): + if ftype == TType.BOOL or ftype == TType.BYTE: + await inbuf.read(1) + + elif ftype == TType.I16: + await inbuf.read(2) + + elif ftype == TType.I32: + await inbuf.read(4) + + elif ftype == TType.I64: + await inbuf.read(8) + + elif ftype == TType.DOUBLE: + await inbuf.read(8) + + elif ftype in BIN_TYPES: + _size = await inbuf.read(4) + await inbuf.read(unpack_i32(_size)) + + elif ftype == TType.SET or ftype == TType.LIST: + v_type, sz = await read_list_begin(inbuf) + for i in range(sz): + await skip(inbuf, v_type) + + elif ftype == TType.MAP: + k_type, v_type, sz = await read_map_begin(inbuf) + for i in range(sz): + await skip(inbuf, k_type) + await skip(inbuf, v_type) + + elif ftype == TType.STRUCT: + while True: + f_type, fid = await read_field_begin(inbuf) + if f_type == TType.STOP: + break + await skip(inbuf, f_type) + + +class TAsyncBinaryProtocol(TAsyncProtocolBase): + """Binary implementation of the Thrift protocol driver.""" + + def __init__(self, trans, + strict_read=True, strict_write=True, + decode_response=True, strict_decode=False): + TAsyncProtocolBase.__init__(self, trans) + self.strict_read = strict_read + self.strict_write = strict_write + self.decode_response = decode_response + self.strict_decode = strict_decode + + async def skip(self, ttype): + await skip(self.trans, ttype) + + async def read_message_begin(self): + api, ttype, seqid = await read_message_begin( + self.trans, strict=self.strict_read) + return api, ttype, seqid + + async def read_message_end(self): + pass + + def write_message_begin(self, name, ttype, seqid): + write_message_begin( + self.trans, name, ttype, + seqid, strict=self.strict_write + ) + + def write_message_end(self): + pass + + async def read_struct(self, obj): + return await read_struct(self.trans, obj, self.decode_response, + self.strict_decode) + + def write_struct(self, obj): + write_val(self.trans, TType.STRUCT, obj) + + +class TAsyncBinaryProtocolFactory(object): + def __init__(self, strict_read=True, strict_write=True, + decode_response=True, strict_decode=False): + self.strict_read = strict_read + self.strict_write = strict_write + self.decode_response = decode_response + self.strict_decode = strict_decode + + def get_protocol(self, trans): + return TAsyncBinaryProtocol( + trans, + self.strict_read, + self.strict_write, + self.decode_response, + self.strict_decode, + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/contrib/aio/protocol/compact.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/contrib/aio/protocol/compact.py new file mode 100644 index 0000000000000000000000000000000000000000..1ce1489297dccd96c81963b59b2c834d86b869e2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/contrib/aio/protocol/compact.py @@ -0,0 +1,318 @@ +# -*- coding: utf-8 -*- + +from __future__ import absolute_import + +from struct import unpack + +from thriftpy2.protocol.exc import TProtocolException +from thriftpy2.thrift import TException, TType +from thriftpy2.protocol.compact import ( + from_zig_zag, + CompactType, + TCompactProtocol, +) + +from .base import TAsyncProtocolBase + +BIN_TYPES = (TType.STRING, TType.BINARY) + + +async def read_varint(trans): + result = 0 + shift = 0 + + while True: + x = await trans.read(1) + byte = ord(x) + result |= (byte & 0x7f) << shift + if byte >> 7 == 0: + return result + shift += 7 + + +class TAsyncCompactProtocol(TCompactProtocol, # Inherit all of the writing + TAsyncProtocolBase): + """Compact implementation of the Thrift protocol driver.""" + PROTOCOL_ID = 0x82 + VERSION = 1 + VERSION_MASK = 0x1f + TYPE_MASK = 0xe0 + TYPE_BITS = 0x07 + TYPE_SHIFT_AMOUNT = 5 + + async def _read_size(self): + result = await read_varint(self.trans) + if result < 0: + raise TException("Length < 0") + return result + + async def read_message_begin(self): + proto_id = await self._read_ubyte() + if proto_id != self.PROTOCOL_ID: + raise TProtocolException(TProtocolException.BAD_VERSION, + 'Bad protocol id in the message: %d' + % proto_id) + + ver_type = await self._read_ubyte() + type = (ver_type >> self.TYPE_SHIFT_AMOUNT) & self.TYPE_BITS + version = ver_type & self.VERSION_MASK + if version != self.VERSION: + raise TProtocolException(TProtocolException.BAD_VERSION, + 'Bad version: %d (expect %d)' + % (version, self.VERSION)) + seqid = await read_varint(self.trans) + name = await self._read_string() + return name, type, seqid + + async def read_message_end(self): # TAsyncClient expects coroutine + assert len(self._structs) == 0 + + async def _read_field_begin(self): + type = await self._read_ubyte() + if type & 0x0f == TType.STOP: + return None, 0, 0 + + delta = type >> 4 + if delta == 0: + fid = from_zig_zag(await read_varint(self.trans)) + else: + fid = self._last_fid + delta + self._last_fid = fid + + type = type & 0x0f + if type == CompactType.TRUE: + self._bool_value = True + elif type == CompactType.FALSE: + self._bool_value = False + + return None, self._get_ttype(type), fid + + def _read_field_end(self): + pass + + def _read_struct_begin(self): + self._structs.append(self._last_fid) + self._last_fid = 0 + + def _read_struct_end(self): + self._last_fid = self._structs.pop() + + async def _read_map_begin(self): + size = await self._read_size() + types = 0 + if size > 0: + types = await self._read_ubyte() + vtype = self._get_ttype(types) + ktype = self._get_ttype(types >> 4) + return ktype, vtype, size + + async def _read_collection_begin(self): + size_type = await self._read_ubyte() + size = size_type >> 4 + type = self._get_ttype(size_type) + if size == 15: + size = await self._read_size() + return type, size + + def _read_collection_end(self): + pass + + async def _read_byte(self): + result, = unpack('!b', await self.trans.read(1)) + return result + + async def _read_ubyte(self): + result, = unpack('!B', await self.trans.read(1)) + return result + + async def _read_int(self): + return from_zig_zag(await read_varint(self.trans)) + + async def _read_double(self): + buff = await self.trans.read(8) + val, = unpack('= (3, 7, 0): + from asyncio import get_running_loop +else: + from asyncio import _get_running_loop as get_running_loop + +from thriftpy2.transport import TTransportException +from thriftpy2.transport._ssl import ( + create_thriftpy_context, + RESTRICTED_SERVER_CIPHERS, + DEFAULT_CIPHERS +) + + +MAC_OR_BSD = sys.platform == 'darwin' or sys.platform.startswith('freebsd') + + +class TAsyncSocket(object): + """Socket implementation for client side.""" + + def __init__(self, host=None, port=None, unix_socket=None, + sock=None, socket_family=socket.AF_INET, + socket_timeout=3000, connect_timeout=None, + ssl_context=None, validate=True, + cafile=None, capath=None, certfile=None, keyfile=None, + ciphers=DEFAULT_CIPHERS): + """Initialize a TSocket + + TSocket can be initialized in 3 ways: + * host + port. can configure to use AF_INET/AF_INET6 + * unix_socket + * socket. should pass already opened socket here. + + @param host(str) The host to connect to. + @param port(int) The (TCP) port to connect to. + @param unix_socket(str) The filename of a unix socket to connect to. + @param sock(socket) Initialize with opened socket directly. + If this param used, the host, port and unix_socket params will + be ignored. + @param socket_family(str) socket.AF_INET or socket.AF_INET6. only + take effect when using host/port + @param socket_timeout socket timeout in ms + @param connect_timeout connect timeout in ms, only used in + connection, will be set to socket_timeout if not set. + @param validate(bool) Set to False to disable SSL certificate + validation and hostname validation. Default enabled. + @param cafile(str) Path to a file of concatenated CA + certificates in PEM format. + @param capath(str) path to a directory containing several CA + certificates in PEM format, following an OpenSSL specific layout. + @param certfile(str) The certfile string must be the path to a + single file in PEM format containing the certificate as well as + any number of CA certificates needed to establish the + certificate’s authenticity. + @param keyfile(str) The keyfile string, if not present, + the private key will be taken from certfile as well. + @param ciphers(list) The cipher suites to allow + @param ssl_context(SSLContext) Customize the SSLContext, can be used + to persist SSLContext object. Caution it's easy to get wrong, only + use if you know what you're doing. + """ + if sock: + self.raw_sock = sock + elif unix_socket: + self.unix_socket = unix_socket + self.host = None + self.port = None + self.raw_sock = None + self.sock_factory = asyncio.open_unix_connection + else: + self.unix_socket = None + self.host = host + self.port = port + self.raw_sock = None + self.sock_factory = asyncio.open_connection + + self.socket_family = socket_family + self.socket_timeout = socket_timeout / 1000 if socket_timeout else None + self.connect_timeout = connect_timeout / 1000 if connect_timeout \ + else self.socket_timeout + + if ssl_context: + self.ssl_context = ssl_context + self.server_hostname = host + elif certfile or keyfile: + self.server_hostname = host + self.ssl_context = create_thriftpy_context(server_side=False, + ciphers=ciphers) + + if cafile or capath: + self.ssl_context.load_verify_locations(cafile=cafile, + capath=capath) + + if certfile: + self.ssl_context.load_cert_chain(certfile, keyfile=keyfile) + + if not validate: + self.ssl_context.check_hostname = False + self.ssl_context.verify_mode = ssl.CERT_NONE + else: + self.ssl_context = None + self.server_hostname = None + + def _init_sock(self): + if self.unix_socket: + _sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + else: + _sock = socket.socket(self.socket_family, socket.SOCK_STREAM) + _sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) + + # socket options + linger = struct.pack('ii', 0, 0) + _sock.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, linger) + _sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) + + self.raw_sock = _sock + + def set_handle(self, sock): + self.raw_sock = sock + + def set_timeout(self, ms): + """Backward compat api, will bind the timeout to both connect_timeout + and socket_timeout. + """ + self.socket_timeout = ms / 1000 if (ms and ms > 0) else None + self.connect_timeout = self.socket_timeout + + if self.raw_sock is not None: + self.raw_sock.settimeout(self.socket_timeout) + + def is_open(self): + return bool(self.raw_sock) + + async def open(self): + self._init_sock() + + addr = self.unix_socket or (self.host, self.port) + + try: + if self.connect_timeout: + self.raw_sock.settimeout(self.connect_timeout) + + loop = get_running_loop() + # The raw_sock.connect may block the event loop if the target + # server is slow or unreachable. Using a thread pool to solve it + # as a quick and dirty way. See #270. + await loop.run_in_executor(None, lambda: self.raw_sock.connect(addr)) + + if self.socket_timeout: + self.raw_sock.settimeout(self.socket_timeout) + + kwargs = {'sock': self.raw_sock, 'ssl': self.ssl_context} + if self.server_hostname: + kwargs['server_hostname'] = self.server_hostname + + self.reader, self.writer = await asyncio.wait_for( + self.sock_factory(**kwargs), + self.socket_timeout + ) + + except (socket.error, OSError): + raise TTransportException( + type=TTransportException.NOT_OPEN, + message="Could not connect to %s" % str(addr)) + + async def read(self, sz): + try: + buff = await asyncio.wait_for( + self.reader.read(sz), + self.connect_timeout + ) + except socket.error as e: + if e.errno == errno.ECONNRESET and MAC_OR_BSD: + # freebsd and Mach don't follow POSIX semantic of recv + # and fail with ECONNRESET if peer performed shutdown. + # See corresponding comment and code in TSocket::read() + # in lib/cpp/src/transport/TSocket.cpp. + self.close() + # Trigger the check to raise the END_OF_FILE exception below. + buff = '' + else: + raise + + if len(buff) == 0: + raise TTransportException(type=TTransportException.END_OF_FILE, + message='TSocket read 0 bytes') + return buff + + def write(self, buff): + self.writer.write(buff) + + async def flush(self): + await asyncio.wait_for(self.writer.drain(), self.connect_timeout) + + def close(self): + if not self.raw_sock: + return + + try: + self.writer.close() + self.raw_sock.close() + self.raw_sock = None + except (socket.error, OSError): + pass + + +class TAsyncServerSocket(object): + """Socket implementation for server side.""" + + def __init__(self, host=None, port=None, unix_socket=None, + socket_family=socket.AF_INET, client_timeout=3000, + backlog=128, ssl_context=None, certfile=None, keyfile=None, + ciphers=RESTRICTED_SERVER_CIPHERS): + """Initialize a TServerSocket + + TSocket can be initialized in 2 ways: + * host + port. can configure to use AF_INET/AF_INET6 + * unix_socket + + @param host(str) The host to connect to + @param port(int) The (TCP) port to connect to + @param unix_socket(str) The filename of a unix socket to connect to + @param socket_family(str) socket.AF_INET or socket.AF_INET6. only + take effect when using host/port + @param client_timeout client socket timeout + @param backlog backlog for server socket + @param certfile(str) The server cert pem filename + @param keyfile(str) The server cert key filename + @param ciphers(list) The cipher suites to allow + @param ssl_context(SSLContext) Customize the SSLContext, can be used + to persist SSLContext object. Caution it's easy to get wrong, only + use if you know what you're doing. + """ + if unix_socket: + self.unix_socket = unix_socket + self.host = None + self.port = None + self.sock_factory = asyncio.start_unix_server + else: + self.unix_socket = None + self.host = host + self.port = port + self.sock_factory = asyncio.start_server + + self.socket_family = socket_family + self.client_timeout = client_timeout / 1000 if client_timeout else None + self.backlog = backlog + + if ssl_context: + self.ssl_context = ssl_context + elif certfile: + if not os.access(certfile, os.R_OK): + raise IOError('No such certfile found: %s' % certfile) + + self.ssl_context = create_thriftpy_context(server_side=True, + ciphers=ciphers) + self.ssl_context.load_cert_chain(certfile, keyfile=keyfile) + else: + self.ssl_context = None + + def _init_sock(self): + if self.unix_socket: + # try remove the sock file it already exists + _sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + try: + _sock.connect(self.unix_socket) + except (socket.error, OSError) as err: + if err.errno == errno.ECONNREFUSED: + os.unlink(self.unix_socket) + else: + _sock = socket.socket(self.socket_family, socket.SOCK_STREAM) + + _sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + # valid socket https://github.com/python/cpython/issues/128916 + valid_family = (socket.AF_INET, socket.AF_INET6) + if _sock.family in valid_family and hasattr(socket, "SO_REUSEPORT"): + try: + _sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) + except socket.error as err: + if err[0] in (errno.ENOPROTOOPT, errno.EINVAL): + pass + else: + raise + _sock.settimeout(None) + self.raw_sock = _sock + + def listen(self): + self._init_sock() + + addr = self.unix_socket or (self.host, self.port) + self.raw_sock.bind(addr) + self.raw_sock.listen(self.backlog) + + async def accept(self, callback): + server = await self.sock_factory( + self._create_client_connected_cb(callback), + sock=self.raw_sock, + ssl=self.ssl_context + ) + return server + + def _create_client_connected_cb(self, callback): + + async def client_connected_cb(reader, writer): + try: + await asyncio.wait_for( + callback(StreamHandler(reader, writer)), + self.client_timeout + ) + except asyncio.exceptions.TimeoutError: + writer.close() + + return client_connected_cb + + def close(self): + if not self.raw_sock: + return + + try: + self.raw_sock.shutdown(socket.SHUT_RDWR) + self.raw_sock.close() + except (socket.error, OSError): + pass + + +class StreamHandler(object): + def __init__(self, reader, writer): + self.reader, self.writer = reader, writer + + async def read(self, sz): + try: + buff = await self.reader.read(sz) + except socket.error as e: + if e.errno == errno.ECONNRESET and MAC_OR_BSD: + # freebsd and Mach don't follow POSIX semantic of recv + # and fail with ECONNRESET if peer performed shutdown. + # See corresponding comment and code in TSocket::read() + # in lib/cpp/src/transport/TSocket.cpp. + self.close() + # Trigger the check to raise the END_OF_FILE exception below. + buff = '' + else: + raise + + if len(buff) == 0: + raise TTransportException(type=TTransportException.END_OF_FILE, + message='TSocket read 0 bytes') + return buff + + def write(self, buff): + self.writer.write(buff) + + async def flush(self): + await self.writer.drain() + + def close(self): + try: + self.writer.close() + except (socket.error, OSError): + pass + + async def open(self): + pass diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/contrib/aio/transport/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/contrib/aio/transport/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fd5d80fad889fe96febd5e7cc7f312ddffd78e49 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/contrib/aio/transport/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- + +from __future__ import absolute_import + +__all__ = [ + 'TAsyncTransportBase', + 'TAsyncBufferedTransport', + 'TAsyncBufferedTransportFactory', + 'TAsyncFramedTransport', + 'TAsyncFramedTransportFactory', +] + +from .base import TAsyncTransportBase +from .buffered import TAsyncBufferedTransport, TAsyncBufferedTransportFactory +from .framed import TAsyncFramedTransport, TAsyncFramedTransportFactory diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/contrib/aio/transport/base.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/contrib/aio/transport/base.py new file mode 100644 index 0000000000000000000000000000000000000000..1ac5e0dfb797c433ed1bdb62bdbf51f5dc7f7180 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/contrib/aio/transport/base.py @@ -0,0 +1,47 @@ +# -*- coding: utf-8 -*- + +from __future__ import absolute_import + +from thriftpy2.transport import TTransportBase, TTransportException + + +async def readall(read_fn, sz): + buff = b'' + have = 0 + while have < sz: + chunk = await read_fn(sz - have) + have += len(chunk) + buff += chunk + + if len(chunk) == 0: + raise TTransportException( + TTransportException.END_OF_FILE, + "End of file reading from transport", + ) + + return buff + + +class TAsyncTransportBase(TTransportBase): + """Base class for Thrift async transport layer.""" + + def is_open(self): + raise NotImplementedError + + async def open(self): + raise NotImplementedError + + def close(self): + raise NotImplementedError + + async def _read(self, sz): + raise NotImplementedError + + async def read(self, sz): + return await readall(self._read, sz) + + def write(self, buf): + raise NotImplementedError + + async def flush(self): + raise NotImplementedError diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/contrib/aio/transport/buffered.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/contrib/aio/transport/buffered.py new file mode 100644 index 0000000000000000000000000000000000000000..5b5180b236cfc547369fef28ef2ea1ea7f29fdaa --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/contrib/aio/transport/buffered.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +from io import BytesIO + +from .base import TAsyncTransportBase + + +class TAsyncBufferedTransport(TAsyncTransportBase): + """Class that wraps another transport and buffers its I/O. + + The implementation uses a (configurable) fixed-size read buffer + but buffers all writes until a flush is performed. + """ + DEFAULT_BUFFER = 4096 + + def __init__(self, trans, buf_size=DEFAULT_BUFFER): + self._trans = trans + self._wbuf = BytesIO() + self._rbuf = BytesIO(b"") + self._buf_size = buf_size + + def is_open(self): + return self._trans.is_open() + + async def open(self): + return await self._trans.open() + + def close(self): + return self._trans.close() + + async def _read(self, sz): + ret = self._rbuf.read(sz) + + rest_len = sz - len(ret) + if rest_len == 0: + return ret + + buf = await self._trans.read(max(rest_len, self._buf_size)) + + ret = ret + buf[:rest_len] + buf = buf[rest_len:] + + self._rbuf = BytesIO(buf) + return ret + + def write(self, buf): + self._wbuf.write(buf) + + async def flush(self): + out = self._wbuf.getvalue() + # reset wbuf before write/flush to preserve state on underlying failure + self._wbuf = BytesIO() + self._trans.write(out) + await self._trans.flush() + + def getvalue(self): + return self._trans.getvalue() + + +class TAsyncBufferedTransportFactory(object): + def get_transport(self, trans): + return TAsyncBufferedTransport(trans) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/contrib/aio/transport/framed.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/contrib/aio/transport/framed.py new file mode 100644 index 0000000000000000000000000000000000000000..5cd873f98cbacc21ab6c2108e4dd026c23f33796 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/contrib/aio/transport/framed.py @@ -0,0 +1,69 @@ +# -*- coding: utf-8 -*- + +from __future__ import absolute_import + +import struct +from io import BytesIO + +from .base import TAsyncTransportBase, readall +from .buffered import TAsyncBufferedTransport + + +class TAsyncFramedTransport(TAsyncTransportBase): + """Class that wraps another transport and frames its I/O when writing.""" + def __init__(self, trans): + self._trans = trans + self._rbuf = BytesIO() + self._wbuf = BytesIO() + + def is_open(self): + return self._trans.is_open() + + async def open(self): + return await self._trans.open() + + def close(self): + return self._trans.close() + + async def read(self, sz): + # Important: don't attempt to read the next frame if the caller + # doesn't actually need any data. + if sz == 0: + return b'' + + ret = self._rbuf.read(sz) + if len(ret) != 0: + return ret + + await self.read_frame() + return self._rbuf.read(sz) + + async def read_frame(self): + buff = await readall(self._trans.read, 4) + sz, = struct.unpack('!i', buff) + frame = await readall(self._trans.read, sz) + self._rbuf = BytesIO(frame) + + def write(self, buf): + self._wbuf.write(buf) + + async def flush(self): + # reset wbuf before write/flush to preserve state on underlying failure + out = self._wbuf.getvalue() + self._wbuf = BytesIO() + + # N.B.: Doing this string concatenation is WAY cheaper than making + # two separate calls to the underlying socket object. Socket writes in + # Python turn out to be REALLY expensive, but it seems to do a pretty + # good job of managing string buffer operations without excessive + # copies + self._trans.write(struct.pack("!i", len(out)) + out) + await self._trans.flush() + + def getvalue(self): + return self._trans.getvalue() + + +class TAsyncFramedTransportFactory(object): + def get_transport(self, trans): + return TAsyncBufferedTransport(TAsyncFramedTransport(trans)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/contrib/tracking/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/contrib/tracking/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2dc710624d261f476559fe8e90a66833c3215539 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/contrib/tracking/__init__.py @@ -0,0 +1,230 @@ +# -*- coding: utf-8 -*- + +""" +Tracking support similar to twitter finagle-thrift. + +Note: When using tracking, every client should have a corresponding +server processor. +""" + +from __future__ import absolute_import + +import os.path +import time + +from ...thrift import TClient, TApplicationException, TMessageType, \ + TProcessor, TType +from ...parser import load +from .tracker import VersionMixin + +track_method = "__thriftpy_tracing_method_name__v2" +track_thrift = load(os.path.join(os.path.dirname(__file__), "tracking.thrift")) + +__all__ = ["TTrackedClient", "TTrackedProcessor", "TrackerBase", + "ConsoleTracker"] + + +class RequestInfo(object): + def __init__(self, request_id, api, seq, client, server, status, start, + end, annotation, meta): + """Used to store call info. + + :request_id: used to identity a request + :api: api name + :seq: sequence number + :client: client name + :server: server name + :status: request status + :start: start timestamp + :end: end timestamp + :annotation: application-level key-value data + """ + self.request_id = request_id + self.api = api + self.seq = seq + self.client = client + self.server = server + self.status = status + self.start = start + self.end = end + self.annotation = annotation + self.meta = meta + + +class TTrackedClient(TClient, VersionMixin): + def __init__(self, tracker_handler, *args, **kwargs): + super(TTrackedClient, self).__init__(*args, **kwargs) + + self.init_version_mixin() + self.tracker = tracker_handler + + try: + self._negotiation() + except TApplicationException as e: + if e.type != TApplicationException.UNKNOWN_METHOD: + raise + + def _negotiation(self): + self._oprot.write_message_begin(track_method, TMessageType.CALL, + self._seqid) + args = track_thrift.UpgradeArgs() + args.version = VersionMixin.CURRENT + self.tracker.init_handshake_info(args) + args.write(self._oprot) + self._oprot.write_message_end() + self._oprot.trans.flush() + + api, msg_type, seqid = self._iprot.read_message_begin() + + if msg_type == TMessageType.EXCEPTION: + x = TApplicationException() + x.read(self._iprot) + self._iprot.read_message_end() + raise x + else: + result = track_thrift.UpgradeReply() + result.read(self._iprot) + self._iprot.read_message_end() + self.upgrade_version(VersionMixin.VERSION_SUPPORT_REQUEST_HEADER) + if result.version: + self.upgrade_version(result.version) + + def _send(self, _api, **kwargs): + if self.check_version(VersionMixin.VERSION_SUPPORT_REQUEST_HEADER): + self._header = track_thrift.RequestHeader() + self.tracker.gen_header(self._header) + self._header.write(self._oprot) + + self.send_start = int(time.time() * 1000) + super(TTrackedClient, self)._send(_api, **kwargs) + + def _recv(self, _api): + if self.check_version(VersionMixin.VERSION_SUPPORT_RESPONSE_HEADER): + response_header = track_thrift.ResponseHeader() + response_header.read(self._iprot) + self.tracker.handle_response_header(response_header) + + return super(TTrackedClient, self)._recv(_api) + + def _req(self, _api, *args, **kwargs): + if not self.check_version(VersionMixin.VERSION_SUPPORT_REQUEST_HEADER): + return super(TTrackedClient, self)._req(_api, *args, **kwargs) + + exception = None + status = False + try: + res = super(TTrackedClient, self)._req(_api, *args, **kwargs) + status = True + return res + except BaseException as e: + exception = e + raise + finally: + header_info = RequestInfo( + request_id=self._header.request_id, + seq=self._header.seq, + client=self.tracker.client, + server=self.tracker.server, + api=_api, + status=status, + start=self.send_start, + end=int(time.time() * 1000), + annotation=self.tracker.annotation, + meta=self._header.meta, + ) + self.tracker.record(header_info, exception) + + +class TTrackedProcessor(TProcessor, VersionMixin): + def __init__(self, tracker_handler, *args, **kwargs): + super(TTrackedProcessor, self).__init__(*args, **kwargs) + self.init_version_mixin() + self.tracker = tracker_handler + self.during_handshake = False + + def process(self, iprot, oprot): + if self.is_upgraded is False: + res = self._try_upgrade(iprot) + else: + request_header = track_thrift.RequestHeader() + request_header.read(iprot) + self.tracker.handle(request_header) + res = super(TTrackedProcessor, self).process_in(iprot) + + self._do_process(iprot, oprot, *res) + + def _try_upgrade(self, iprot): + api, msg_type, seqid = iprot.read_message_begin() + if msg_type == TMessageType.CALL and api == track_method: + self.during_handshake = True + + args = track_thrift.UpgradeArgs() + args.read(iprot) + self.tracker.handle_handshake_info(args) + self.upgrade_version(VersionMixin.VERSION_SUPPORT_REQUEST_HEADER) + result = track_thrift.UpgradeReply() + + # If client hasn't told us its version, we also don't tell it ours. + if args.version: + self.upgrade_version(args.version) + result.version = self.CURRENT + + result.oneway = False + + def call(): + pass + + iprot.read_message_end() + else: + result, call = self._process_in(api, iprot) + + return api, seqid, result, call + + def _process_in(self, api, iprot): + if api not in self._service.thrift_services: + iprot.skip(TType.STRUCT) + iprot.read_message_end() + return TApplicationException( + TApplicationException.UNKNOWN_METHOD), None + + args = getattr(self._service, api + "_args")() + args.read(iprot) + iprot.read_message_end() + result = getattr(self._service, api + "_result")() + + # convert kwargs to args + api_args = [args.thrift_spec[k][1] + for k in sorted(args.thrift_spec)] + + def call(): + return getattr(self._handler, api)( + *(args.__dict__[k] for k in api_args) + ) + + return result, call + + def _do_process(self, iprot, oprot, api, seqid, result, call): + if isinstance(result, TApplicationException): + return self.send_exception(oprot, api, result, seqid) + + try: + result.success = call() + except Exception as e: + # raise if api don't have throws + if not self.handle_exception(e, result): + raise + + if not result.oneway: + if self.check_version( + VersionMixin.VERSION_SUPPORT_RESPONSE_HEADER): + if self.during_handshake: + self.during_handshake = False + else: + response_header = track_thrift.ResponseHeader() + self.tracker.gen_response_header(response_header) + response_header.write(oprot) + + self.send_result(oprot, api, result, seqid) + + +from .tracker import TrackerBase, ConsoleTracker # noqa diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/contrib/tracking/tracker.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/contrib/tracking/tracker.py new file mode 100644 index 0000000000000000000000000000000000000000..3b64bbd5a95bf60e470ffbbf03f8eb34303a8709 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/contrib/tracking/tracker.py @@ -0,0 +1,152 @@ +# -*- coding: utf-8 -*- + +from __future__ import absolute_import + +import copy +import contextlib +import threading +import uuid + +ctx = threading.local() + + +class VersionMixin(object): + """Mixin class to handle version compatibilities""" + DEFAULT_VERSION = 0 # support only request header + VERSION_SUPPORT_REQUEST_HEADER = 1 # add request header + VERSION_SUPPORT_RESPONSE_HEADER = 2 # add response header + + CURRENT = VERSION_SUPPORT_RESPONSE_HEADER + + def init_version_mixin(self): + self.current_version = self.DEFAULT_VERSION + self.is_upgraded = False + + def check_version(self, feature_version): + return self.current_version >= feature_version + + def upgrade_version(self, target_version): + self.is_upgraded = True + if VersionMixin.CURRENT >= target_version > self.current_version: + self.current_version = target_version + + +class TrackerBase(object): + def __init__(self, client=None, server=None): + self.client = client + self.server = server + + def handle(self, header): + ctx.header = header + ctx.counter = 0 + + def handle_response_header(self, response_header): + pass + + def gen_header(self, header): + header.request_id = self.get_request_id() + + if not hasattr(ctx, "counter"): + ctx.counter = 0 + + ctx.counter += 1 + + if hasattr(ctx, "header"): + header.seq = "{prev_seq}.{cur_counter}".format( + prev_seq=ctx.header.seq, cur_counter=ctx.counter) + header.meta = ctx.header.meta + else: + header.meta = {} + header.seq = str(ctx.counter) + + if hasattr(ctx, "meta"): + header.meta.update(ctx.meta) + + def gen_response_header(self, response_header): + if hasattr(ctx, "response_meta"): + response_header.meta = ctx.response_meta + del ctx.response_meta + + def record(self, header, exception): + pass + + @classmethod + @contextlib.contextmanager + def counter(cls, init=0): + """Context for manually setting counter of seq number. + + :init: init value + """ + if not hasattr(ctx, "counter"): + ctx.counter = 0 + + old = ctx.counter + ctx.counter = init + + try: + yield + finally: + ctx.counter = old + + @classmethod + @contextlib.contextmanager + def annotate(cls, **kwargs): + ctx.annotation = kwargs + try: + yield ctx.annotation + finally: + del ctx.annotation + + @classmethod + @contextlib.contextmanager + def add_meta(cls, **kwds): + if hasattr(ctx, 'meta'): + old_dict = copy.copy(ctx.meta) + ctx.meta.update(kwds) + try: + yield ctx.meta + finally: + ctx.meta = old_dict + else: + ctx.meta = kwds + try: + yield ctx.meta + finally: + del ctx.meta + + @classmethod + def add_response_meta(cls, **kwds): + if hasattr(ctx, 'response_meta'): + ctx.response_meta.update(kwds) + + else: + ctx.response_meta = kwds + + return ctx.response_meta + + @property + def meta(self): + meta = ctx.header.meta if hasattr(ctx, "header") else {} + if hasattr(ctx, "meta"): + meta.update(ctx.meta) + return meta + + @property + def annotation(self): + return ctx.annotation if hasattr(ctx, "annotation") else {} + + def get_request_id(self): + if hasattr(ctx, "header"): + return ctx.header.request_id + return str(uuid.uuid4()) + + def init_handshake_info(self, handshake_obj): + pass + + def handle_handshake_info(self, handshake_obj): + pass + + +class ConsoleTracker(TrackerBase): + def record(self, header, exception): + print(header) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/contrib/tracking/tracking.thrift b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/contrib/tracking/tracking.thrift new file mode 100644 index 0000000000000000000000000000000000000000..6c1181c51cb76507d8c9747ccedb0820b655cd7b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/contrib/tracking/tracking.thrift @@ -0,0 +1,24 @@ +/* + * This is the structure used to send call info to server. + */ +struct RequestHeader { + 1: string request_id + 2: string seq + 3: map meta +} + +struct ResponseHeader { + 1: map meta +} + +/** + * This is the struct that a successful upgrade will reply with. + */ +struct UpgradeReply { + 1:i32 version +} + +struct UpgradeArgs { + 1: string app_id + 2: i32 version +} \ No newline at end of file diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/hook.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/hook.py new file mode 100644 index 0000000000000000000000000000000000000000..aaa8489a06c6cd63a9ce5f31c20c0d76b0a8856b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/hook.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- + +from __future__ import absolute_import, annotations + +import importlib.abc +import importlib.util +import sys + +from .parser import load_module + + +# TODO: The load process does not compatible with Python standard, e.g., if the +# specified thrift file does not exists, it raises FileNotFoundError, and skipped +# the other meta finders in the sys.meta_path. +class ThriftImporter(importlib.abc.MetaPathFinder): + def __init__(self, extension="_thrift"): + self.extension = extension + + def find_spec(self, fullname, path, target=None): + if not fullname.endswith(self.extension): + return None + return importlib.util.spec_from_loader(fullname, + ThriftLoader(fullname)) + + +class ThriftLoader(importlib.abc.Loader): + def __init__(self, fullname): + self.fullname = fullname + + def create_module(self, spec): + return load_module(self.fullname) + + def exec_module(self, module): + pass + + +_imp = ThriftImporter() + + +def install_import_hook() -> None: + sys.meta_path[:] = [x for x in sys.meta_path if _imp is not x] + [_imp] + + +def remove_import_hook() -> None: + sys.meta_path[:] = [x for x in sys.meta_path if _imp is not x] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/http.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/http.py new file mode 100644 index 0000000000000000000000000000000000000000..a020d45d488fbc7f2b1155e97e02f142a6de5c87 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/http.py @@ -0,0 +1,359 @@ +# -*- coding: utf-8 -*- + +""" +# Run server: +>>> import thriftpy2 +>>> from thriftpy2.http import make_server +>>> pingpong = thriftpy2.load("pingpong.thrift") +>>> +>>> class Dispatcher(object): +>>> def ping(self): +>>> return "pong" + +>>> server = make_server(pingpong.PingService, Dispatcher(), + host='127.0.0.1', port=6000) +>>> server.serve() + +# Run client: +>>> import thriftpy2 +>>> from thriftpy2.http import make_client +>>> pingpong = thriftpy2.load("pingpong.thrift") +>>> client = make_client(pingpong.PingService, host='127.0.0.1', port=6000) +>>> client.ping() + +# Run HTTPS client with unverified SSL context for TESTING ONLY purpose: +>>> import ssl +>>> ssl_context_factory = ssl._create_unverified_context +>>> client = make_client(pingpong.PingService, host='example.com', port=443, +... scheme="https", +... ssl_context_factory=ssl_context_factory) +>>> client.ping() +""" + +from __future__ import absolute_import + +import http.client as http_client +import http.server as http_server +import os +import socket +import ssl +import sys +import types +import urllib +from contextlib import contextmanager +from io import BytesIO +from typing import (BinaryIO, Callable, Dict, Generator, Optional, + Tuple, Type) + +from thriftpy2.protocol import TBinaryProtocolFactory +from thriftpy2.protocol.base import TProtocolFactory +from thriftpy2.server import TServer +from thriftpy2.thrift import TClient, TProcessor +from thriftpy2.transport import TBufferedTransportFactory, TMemoryBuffer +from thriftpy2.transport.base import TTransportFactory, TTransportBase + +HTTP_URI = '{scheme}://{host}:{port}{path}' +DEFAULT_HTTP_CLIENT_TIMEOUT_MS = 30000 # 30 seconds + + +class TFileObjectTransport(TTransportBase): + """Wraps a file-like object to make it work as a Thrift transport.""" + + def __init__(self, fileobj: BinaryIO) -> None: + self.fileobj = fileobj + + def isOpen(self) -> bool: + return True + + def close(self) -> None: + self.fileobj.close() + + def read(self, sz: int) -> bytes: + return self.fileobj.read(sz) + + def write(self, buf: bytes) -> None: + self.fileobj.write(buf) + + def flush(self) -> None: + self.fileobj.flush() + + +class ResponseException(Exception): + """Allows handlers to override the HTTP response + + Normally, THttpServer always sends a 200 response. If a handler wants + to override this behavior (e.g., to simulate a misconfigured or + overloaded web server during testing), it can raise a ResponseException. + The function passed to the constructor will be called with the + RequestHandler as its only argument. + """ + def __init__(self, handler: Callable) -> None: + self.handler = handler + + +class THttpHeaderFactory(object): + """Default header factory return no custom headers + """ + def __init__(self, headers: Optional[Dict[str, str]] = None) -> None: + """Initialize a header factory + @param headers(dict) + A dictionary of static headers the factory generates + """ + if headers: + self.__headers = headers + else: + self.__headers = dict() + + def get_headers(self) -> Dict[str, str]: + return self.__headers + + +class THttpServer(TServer): + """A simple HTTP-based Thrift server + This class is not very performant, but it is useful (for example) for + acting as a mock version of an Apache-based PHP Thrift endpoint. + """ + def __init__(self, + processor: TProcessor, + server_address: Tuple[str, int], + itrans_factory: TTransportFactory, + iprot_factory: TProtocolFactory, + server_class: Type[http_server.HTTPServer] = http_server.HTTPServer + ) -> None: + """Set up protocol factories and HTTP server. + See http.server for server_address. + See TServer for protocol factories. + """ + TServer.__init__(self, processor, trans=None, + itrans_factory=itrans_factory, + iprot_factory=iprot_factory, + otrans_factory=None, oprot_factory=None) + + thttpserver = self + + class RequestHandler(http_server.BaseHTTPRequestHandler): + # Don't care about the request path. + + def do_POST(self): + # Don't care about the request path. + # Pre-read all of the data into a BytesIO. Buffered transport + # was previously configured to read everything on the first + # consumption, but that was a hack relying on the internal + # mechanism and prevents other transports from working, so + # replicate that properly to prevent timeout issues + content_len = int(self.headers['Content-Length']) + buf = BytesIO(self.rfile.read(content_len)) + itrans = TFileObjectTransport(buf) + itrans = thttpserver.itrans_factory.get_transport(itrans) + iprot = thttpserver.iprot_factory.get_protocol(itrans) + + otrans = TMemoryBuffer() + oprot = thttpserver.oprot_factory.get_protocol(otrans) + try: + thttpserver.processor.process(iprot, oprot) + except ResponseException as exn: + exn.handler(self) + else: + self.send_response(200) + self.send_header("content-type", "application/x-thrift") + self.end_headers() + self.wfile.write(otrans.getvalue()) + + self.httpd = server_class(server_address, RequestHandler) + + def serve(self) -> None: + self.httpd.serve_forever() + + +class THttpClient(object): + """Http implementation of TTransport base. + """ + + def __init__(self, uri: str, timeout: Optional[int] = None, + ssl_context_factory: Optional[Callable[[], ssl.SSLContext]] = None, + http_header_factory: Optional[THttpHeaderFactory] = None + ) -> None: + """Initialize a HTTP Socket. + + @param uri(str) The http_scheme:://host:port/path to connect to. + @param timeout timeout in ms + """ + parsed = urllib.parse.urlparse(uri) + self.scheme = parsed.scheme + assert self.scheme in ('http', 'https') + if self.scheme == 'http': + self.port = parsed.port or http_client.HTTP_PORT + elif self.scheme == 'https': + self.port = parsed.port or http_client.HTTPS_PORT + self.host = parsed.hostname + self.path = parsed.path + if parsed.query: + self.path += '?%s' % parsed.query + self.__wbuf = BytesIO() + self.__http = None + self._http_header_factory = http_header_factory or THttpHeaderFactory() + self.__timeout = None + if timeout: + self.setTimeout(timeout) + self._ssl_context_factory = ssl_context_factory + + def open(self) -> None: + if self.scheme == "https": + ssl_context = self._ssl_context_factory() \ + if self._ssl_context_factory else None + self.__http = http_client.HTTPSConnection(self.host, self.port, + context=ssl_context) + else: + self.__http = http_client.HTTPConnection(self.host, self.port) + + def close(self) -> None: + self.__http.close() + self.__http = None + + def isOpen(self) -> bool: + return self.__http is not None + + def setTimeout(self, ms: int) -> None: + if not hasattr(socket, 'getdefaulttimeout'): + raise NotImplementedError + + self.__timeout = ms / 1000.0 if (ms and ms > 0) else None + + def setCustomHeaders(self, headers: Dict[str, str]) -> None: + self._http_header_factory = THttpHeaderFactory(headers) + + def read(self, sz: int) -> bytes: + content = self.response.read(sz) + return content + + def write(self, buf: bytes) -> None: + self.__wbuf.write(buf) + + def flush(self) -> None: + # Pull data out of buffer + # Do this before opening a new connection in case there isn't data + data = self.__wbuf.getvalue() + self.__wbuf = BytesIO() + if not data: # No data to flush, ignore + return + + if self.isOpen(): + self.close() + self.open() + + # HTTP request + self.__http.putrequest('POST', self.path, skip_host=True) + + # Write headers + self.__http.putheader('Host', self.host) + self.__http.putheader('Content-Type', 'application/x-thrift') + self.__http.putheader('Content-Length', str(len(data))) + custom_headers = self._http_header_factory.get_headers() + if (not custom_headers + or 'User-Agent' not in custom_headers): + user_agent = 'Python/THttpClient' + script = os.path.basename(sys.argv[0]) + if script: + user_agent = '%s (%s)' % ( + user_agent, urllib.parse.quote(script)) + self.__http.putheader('User-Agent', user_agent) + + if custom_headers: + for key, val in self._http_header_factory.get_headers().items(): + self.__http.putheader(key, val) + + self.__http.endheaders() + + # Write payload + self.__http.send(data) + + # Get reply to flush the request + response = self.__http.getresponse() + self.code, self.message, self.headers = ( + response.status, response.msg, response.getheaders()) + self.response = response + + def __with_timeout(f): + + def _f(*args, **kwargs): + orig_timeout = socket.getdefaulttimeout() + socket.setdefaulttimeout(args[0].__timeout) + result = None + try: + result = f(*args, **kwargs) + finally: + socket.setdefaulttimeout(orig_timeout) + return result + return _f + + # Decorate if we know how to timeout + if hasattr(socket, 'getdefaulttimeout'): + flush = __with_timeout(flush) + + +def make_client(service: types.ModuleType, host: str = 'localhost', + port: int = 9090, path: str = '', scheme: str = 'http', + proto_factory: TProtocolFactory = TBinaryProtocolFactory(), + trans_factory: TTransportFactory = TBufferedTransportFactory(), + ssl_context_factory: Optional[Callable[[], ssl.SSLContext]] = None, + http_header_factory: Optional[THttpHeaderFactory] = None, + timeout: int = DEFAULT_HTTP_CLIENT_TIMEOUT_MS, + url: str = '') -> TClient: + if url: + parsed_url = urllib.parse.urlparse(url) + host = parsed_url.hostname or host + port = parsed_url.port or port + scheme = parsed_url.scheme or scheme + path = parsed_url.path or path + if path and path[0] != "/": + # path should have `/` prefix, but we can make a compatible here. + path = "/" + path + uri = HTTP_URI.format(scheme=scheme, host=host, port=port, path=path) + http_socket = THttpClient(uri, timeout, ssl_context_factory, + http_header_factory) + transport = trans_factory.get_transport(http_socket) + iprot = proto_factory.get_protocol(transport) + transport.open() + return TClient(service, iprot) + + +@contextmanager +def client_context(service: types.ModuleType, host: str = 'localhost', + port: int = 9090, path: str = '', scheme: str = 'http', + proto_factory: TProtocolFactory = TBinaryProtocolFactory(), + trans_factory: TTransportFactory = TBufferedTransportFactory(), + ssl_context_factory: Optional[Callable[[], ssl.SSLContext]] = None, + http_header_factory: Optional[THttpHeaderFactory] = None, + timeout: int = DEFAULT_HTTP_CLIENT_TIMEOUT_MS, + url: str = '') -> Generator[TClient, None, None]: + if url: + parsed_url = urllib.parse.urlparse(url) + host = parsed_url.hostname or host + port = parsed_url.port or port + scheme = parsed_url.scheme or scheme + path = parsed_url.path or path + if path and path[0] != "/": + # path should have `/` prefix, but we can make a compatible here. + path = "/" + path + uri = HTTP_URI.format(scheme=scheme, host=host, port=port, path=path) + http_socket = THttpClient(uri, timeout, ssl_context_factory, + http_header_factory) + transport = trans_factory.get_transport(http_socket) + try: + iprot = proto_factory.get_protocol(transport) + transport.open() + yield TClient(service, iprot) + finally: + transport.close() + + +def make_server(service: types.ModuleType, handler: object, + host: str, port: int, + proto_factory: TProtocolFactory = TBinaryProtocolFactory(), + trans_factory: TTransportFactory = TBufferedTransportFactory() + ) -> THttpServer: + processor = TProcessor(service, handler) + server = THttpServer(processor, (host, port), + itrans_factory=trans_factory, + iprot_factory=proto_factory) + return server diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/parser/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/parser/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3c14bd11e2740fe4699a98e64d87ab67902c46c2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/parser/__init__.py @@ -0,0 +1,220 @@ +# -*- coding: utf-8 -*- + +""" + thriftpy2.parser + ~~~~~~~~~~~~~~~ + + Thrift parser using ply +""" + +from __future__ import absolute_import, annotations + +import os +import sys +import types +from typing import List, Optional, TextIO + +from .parser import parse, parse_fp, threadlocal, _cast +from .exc import ThriftParserError, ThriftModuleNameConflict +from ..thrift import TPayloadMeta + + +def load( + path: str, + module_name: Optional[str] = None, + include_dirs: Optional[List[str]] = None, + include_dir: Optional[str] = None, + encoding: str = 'utf-8', +) -> types.ModuleType: + """Load thrift file as a module. + + The module loaded and objects inside may only be pickled if module_name + was provided. + + Note: `include_dir` will be depreacated in the future, use `include_dirs` + instead. If `include_dir` was provided (not None), it will be appended to + `include_dirs`. + """ + real_module = bool(module_name) + thrift = parse(path, module_name, include_dirs=include_dirs, + include_dir=include_dir, encoding=encoding) + if threadlocal.incomplete_type: + fill_incomplete_ttype(thrift, thrift) + + # add sub modules to sys.modules recursively + if real_module: + sys.modules[module_name] = thrift + include_thrifts = thrift.__thrift_meta__["includes"][:] + while include_thrifts: + include_thrift = include_thrifts.pop() + registered_thrift = sys.modules.get(include_thrift.__thrift_module_name__) + if registered_thrift is None: + sys.modules[include_thrift.__thrift_module_name__] = include_thrift + if hasattr(include_thrift, "__thrift_meta__"): + include_thrifts.extend( + include_thrift.__thrift_meta__["includes"][:]) + else: + if registered_thrift.__thrift_file__ != include_thrift.__thrift_file__: + raise ThriftModuleNameConflict( + 'Module name conflict between "%s" and "%s"' % + (registered_thrift.__thrift_file__, include_thrift.__thrift_file__) + ) + return thrift + + +def fill_incomplete_ttype(tmodule, definition): + """Second pass of parser to handle out-of-order definitions. + """ + # construct incomplete types' thrift_spec + if isinstance(definition, tuple): + # construct const value + if definition[0] == 'UNKNOWN_CONST': + ttype = get_definition( + tmodule, threadlocal.incomplete_type[definition[1]][0], definition[3]) + return _cast(ttype)(definition[2]) + # construct incomplete alias type + elif definition[1] in threadlocal.incomplete_type: + return ( + definition[0], + get_definition(tmodule, *threadlocal.incomplete_type[definition[1]]) + ) + # construct incomplete type which is contained in service method's args + elif definition[0] in threadlocal.incomplete_type: + real_type = get_definition( + tmodule, *threadlocal.incomplete_type[definition[0]] + ) + return (real_type[0], definition[1], real_type[1], definition[2]) + # construct incomplete compound type + elif isinstance(definition[1], tuple): + return ( + definition[0], + fill_incomplete_ttype(tmodule, definition[1]) + ) + # if type is a thrift module, search it if there are incomplete types + elif isinstance(definition, types.ModuleType): + for name, attr in definition.__dict__.items(): + if name.startswith('__'): # skip inner attribute + continue + setattr(definition, name, fill_incomplete_ttype(definition, attr)) + # if type is a struct, search it if there are incomplete types + elif isinstance(definition, TPayloadMeta): + for index, value in definition.thrift_spec.items(): + # if the ttype of the field is a single type and it is incompleted + if value[0] in threadlocal.incomplete_type: + real_type = fill_incomplete_ttype( + tmodule, get_definition( + tmodule, *threadlocal.incomplete_type[value[0]] + ) + ) + # if the incomplete ttype is a compound type + if isinstance(real_type, tuple): + definition.thrift_spec[index] = ( + real_type[0], + value[1], + real_type[1], + value[2] + ) + # if the incomplete ttype is a built-in ttype + else: + definition.thrift_spec[index] = ( + fill_incomplete_ttype( + tmodule, get_definition( + tmodule, *threadlocal.incomplete_type[value[0]] + ) + ), + ) + tuple(value[1:]) + # if the field's ttype is a compound type + # and it contains incomplete types + elif value[2] in threadlocal.incomplete_type: + definition.thrift_spec[index] = ( + value[0], + value[1], + fill_incomplete_ttype( + tmodule, get_definition( + tmodule, *threadlocal.incomplete_type[value[2]] + ) + ), + value[3]) + # if the field's ttype is a nest compound type + # and it contains incomplete type + elif isinstance(value[2], tuple): + def walk(part): + if isinstance(part, tuple): + return tuple(walk(x) for x in part) + if part in threadlocal.incomplete_type: + return get_definition(tmodule, *threadlocal.incomplete_type[part]) + return part + definition.thrift_spec[index] = ( + value[0], + value[1], + tuple(walk(value[2])), + value[3]) + # if it is a service method definition + elif hasattr(definition, "thrift_services"): + for name, attr in definition.__dict__.items(): + if not hasattr(attr, "thrift_spec"): + continue + for index, value in attr.thrift_spec.items(): + attr.thrift_spec[index] = fill_incomplete_ttype(tmodule, value) + return definition + + +def get_definition(thrift, name, lineno): + """Get definition from thrift module and incomplete type map. + """ + ref_type = thrift + for n in name.split('.'): + ref_type = getattr(thrift, n, None) + if ref_type is None: + raise ThriftParserError('No type found: %r, at line %d' % + (name, lineno)) + if isinstance(ref_type, int) and ref_type < 0: + raise ThriftParserError('No type found: %r, at line %d' % + threadlocal.incomplete_type[ref_type]) + if hasattr(ref_type, '_ttype'): + return (getattr(ref_type, '_ttype'), ref_type) + else: + return ref_type + + +def load_fp(source: TextIO, module_name: str) -> types.ModuleType: + """Load thrift file like object as a module. + """ + thrift = parse_fp(source, module_name) + sys.modules[module_name] = thrift + return thrift + + +def _import_module(import_name): + if '.' in import_name: + module, obj = import_name.rsplit('.', 1) + return getattr(__import__(module, None, None, [obj]), obj) + else: + return __import__(import_name) + + +def load_module(fullname: str) -> types.ModuleType: + """Load thrift_file by fullname, fullname should have '_thrift' as + suffix. + The loader will replace the '_thrift' with '.thrift' and use it as + filename to locate the real thrift file. + """ + if not fullname.endswith("_thrift"): + raise ImportError( + "thriftpy2 can only load module with '_thrift' suffix") + + if fullname in sys.modules: + return sys.modules[fullname] + + if '.' in fullname: + module_name, thrift_module_name = fullname.rsplit('.', 1) + module = _import_module(module_name) + path_prefix = os.path.dirname(os.path.abspath(module.__file__)) + path = os.path.join(path_prefix, thrift_module_name) + else: + path = fullname + thrift_file = "{}.thrift".format(path[:-7]) + + module = load(thrift_file, module_name=fullname) + sys.modules[fullname] = module + return sys.modules[fullname] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/parser/exc.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/parser/exc.py new file mode 100644 index 0000000000000000000000000000000000000000..7c80c72c17450b0ce82e39b57282808b5fc748a4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/parser/exc.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- + +from __future__ import absolute_import + +import sys +from warnings import warn + + +class ThriftParserError(Exception): + pass + + +class ThriftModuleNameConflict(ThriftParserError): + pass + + +class ThriftLexerError(ThriftParserError): + pass + + +class ThriftGrammarError(ThriftParserError): + pass + + +if sys.version_info >= (3, 7): + def __getattr__(name): + if name == "ThriftGrammerError": + warn("'ThriftGrammerError' is a typo of 'ThriftGrammarError'", DeprecationWarning) + return ThriftGrammarError + + raise AttributeError("module %r has no attribute %r" % (__name__, name)) +else: + ThriftGrammerError = ThriftGrammarError diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/parser/lexer.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/parser/lexer.py new file mode 100644 index 0000000000000000000000000000000000000000..581cd6e2de04b33747829f45678f7fd4de9238fd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/parser/lexer.py @@ -0,0 +1,261 @@ +# -*- coding: utf-8 -*- + +from __future__ import absolute_import + +from .exc import ThriftLexerError + + +literals = ':;,=*{}()<>[]' + + +thrift_reserved_keywords = ( + 'BEGIN', + 'END', + '__CLASS__', + '__DIR__', + '__FILE__', + '__FUNCTION__', + '__LINE__', + '__METHOD__', + '__NAMESPACE__', + 'abstract', + 'alias', + 'and', + 'args', + 'as', + 'assert', + 'begin', + 'break', + 'case', + 'catch', + 'class', + 'clone', + 'continue', + 'declare', + 'def', + 'default', + 'del', + 'delete', + 'do', + 'dynamic', + 'elif', + 'else', + 'elseif', + 'elsif', + 'end', + 'enddeclare', + 'endfor', + 'endforeach', + 'endif', + 'endswitch', + 'endwhile', + 'ensure', + 'except', + 'exec', + 'finally', + 'float', + 'for', + 'foreach', + 'from', + 'function', + 'global', + 'goto', + 'if', + 'implements', + 'import', + 'in', + 'inline', + 'instanceof', + 'interface', + 'is', + 'lambda', + 'module', + 'native', + 'new', + 'next', + 'nil', + 'not', + 'or', + 'pass', + 'public', + 'print', + 'private', + 'protected', + 'public', + 'raise', + 'redo', + 'rescue', + 'retry', + 'register', + 'return', + 'self', + 'sizeof', + 'static', + 'super', + 'switch', + 'synchronized', + 'then', + 'this', + 'throw', + 'transient', + 'try', + 'undef', + 'union', + 'unless', + 'unsigned', + 'until', + 'use', + 'var', + 'virtual', + 'volatile', + 'when', + 'while', + 'with', + 'xor', + 'yield' +) + + +keywords = ( + 'namespace', + 'include', + 'cpp_include', + 'void', + 'bool', + 'byte', + 'i8', + 'i16', + 'i32', + 'i64', + 'double', + 'string', + 'binary', + 'map', + 'list', + 'set', + 'oneway', + 'typedef', + 'struct', + 'union', + 'exception', + 'extends', + 'throws', + 'service', + 'enum', + 'const', + 'required', + 'optional', +) + + +tokens = ( + 'BOOLCONSTANT', + 'INTCONSTANT', + 'DUBCONSTANT', + 'LITERAL', + 'IDENTIFIER', +) + tuple(map(lambda kw: kw.upper(), keywords)) + + +t_ignore = ' \t\r' # whitespace + + +def t_error(t): + raise ThriftLexerError('Illegal character %r at line %d' % + (t.value[0], t.lineno)) + + +def t_newline(t): + r'\n+' + t.lexer.lineno += len(t.value) + + +def t_ignore_SILLYCOMM(t): + r'\/\*\**\*\/' + t.lexer.lineno += t.value.count('\n') + + +def t_ignore_MULTICOMM(t): + r'\/\*[^*]\/*([^*/]|[^*]\/|\*[^/])*\**\*\/' + t.lexer.lineno += t.value.count('\n') + + +def t_ignore_DOCTEXT(t): + r'\/\*\*([^*/]|[^*]\/|\*[^/])*\**\*\/' + t.lexer.lineno += t.value.count('\n') + + +def t_ignore_UNIXCOMMENT(t): + r'\#[^\n]*' + + +def t_ignore_COMMENT(t): + r'\/\/[^\n]*' + + +def t_BOOLCONSTANT(t): + r'\btrue\b|\bfalse\b' + t.value = t.value == 'true' + return t + + +def t_DUBCONSTANT(t): + r'[+-]?((\d+(?=\.|[Ee])(\.\d*)?)|(\.\d+))([Ee][+-]?\d+)?' + t.value = float(t.value) + return t + + +def t_HEXCONSTANT(t): + r'0x[0-9A-Fa-f]+' + t.value = int(t.value, 16) + t.type = 'INTCONSTANT' + return t + + +def t_INTCONSTANT(t): + r'[+-]?[0-9]+' + t.value = int(t.value) + return t + + +def t_LITERAL(t): + r'(\"([^\\\n]|(\\.))*?\")|\'([^\\\n]|(\\.))*?\'' + s = t.value[1:-1] + maps = { + 't': '\t', + 'r': '\r', + 'n': '\n', + '\\': '\\', + '\'': '\'', + '"': '\"' + } + i = 0 + length = len(s) + val = '' + while i < length: + if s[i] == '\\': + i += 1 + if s[i] in maps: + val += maps[s[i]] + else: + msg = 'Unexpected escaping character: %s' % s[i] + raise ThriftLexerError(msg) + else: + val += s[i] + + i += 1 + + t.value = val + return t + + +def t_IDENTIFIER(t): + r'[a-zA-Z_](\.[a-zA-Z_0-9]|[a-zA-Z_0-9])*' + + if t.value in keywords: + t.type = t.value.upper() + return t + if t.value in thrift_reserved_keywords: + raise ThriftLexerError('Cannot use reserved language keyword: %r' + ' at line %d' % (t.value, t.lineno)) + return t diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/parser/parser.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/parser/parser.py new file mode 100644 index 0000000000000000000000000000000000000000..8f97977a981bb7caa576647638af5e129f844c55 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/parser/parser.py @@ -0,0 +1,1008 @@ +# -*- coding: utf-8 -*- + +""" +IDL Ref: + https://thrift.apache.org/docs/idl +""" + +from __future__ import absolute_import + +import collections +import itertools +import os +import threading +import types +from urllib.parse import urlparse +from urllib.request import urlopen + +from ply import lex, yacc + +from ..thrift import TException, TPayload, TType, gen_init +from .exc import ThriftGrammarError, ThriftParserError +from .lexer import * # noqa + + +threadlocal = threading.local() + + +def _annotations_to_dict(annotations): + return {} if annotations is None else dict(annotations) + +def p_error(p): + thrift = threadlocal.thrift_stack[-1] + if p is None: + raise ThriftGrammarError("Grammar error at EOF of the file '%s'" % thrift.__thrift_file__) + + raise ThriftGrammarError("Grammar error %r at line %d of the file '%s'" % + (p.value, p.lineno, thrift.__thrift_file__)) + + +def p_start(p): + '''start : header definition''' + + +def p_header(p): + '''header : header_unit_ header + |''' + + +def p_header_unit_(p): + '''header_unit_ : header_unit ';' + | header_unit''' + + +def p_header_unit(p): + '''header_unit : include + | cpp_include + | namespace''' + + +def p_include(p): + '''include : INCLUDE LITERAL''' + thrift = threadlocal.thrift_stack[-1] + if thrift.__thrift_file__ is None: + raise ThriftParserError('Unexpected include statement while loading ' + 'from file like object.') + replace_include_dirs = [os.path.dirname(thrift.__thrift_file__)] \ + + threadlocal.include_dirs_ + for include_dir in replace_include_dirs: + path = os.path.join(include_dir, p[2]) + if os.path.exists(path): + thrift_file_name_module = os.path.basename(thrift.__thrift_file__) + if thrift_file_name_module.endswith(".thrift"): + thrift_file_name_module = thrift_file_name_module[:-7] + "_thrift" + module_prefix = str(thrift.__name__).rstrip(thrift_file_name_module) + + child_rel_path = os.path.relpath(str(path), os.path.dirname(thrift.__thrift_file__)) + child_module_name = str(child_rel_path).replace(os.sep, ".").replace(".thrift", "_thrift") + child_module_name = module_prefix + child_module_name + + child = parse(path, module_name=child_module_name) + child_include_module_name = os.path.basename(path) + if child_include_module_name.endswith(".thrift"): + child_include_module_name = child_include_module_name[:-7] + setattr(child, '__name__', child_include_module_name) + setattr(child, '__thrift_module_name__', child_module_name) + setattr(thrift, child.__name__, child) + _add_thrift_meta('includes', child) + return + raise ThriftParserError(('Couldn\'t include thrift %s in any ' + 'directories provided') % p[2]) + + +def p_cpp_include(p): + '''cpp_include : CPP_INCLUDE LITERAL''' + + +def p_namespace(p): + '''namespace : NAMESPACE namespace_scope IDENTIFIER''' + # namespace is useless in thriftpy2 + # if p[2] == 'py' or p[2] == '*': + # setattr(threadlocal.thrift_stack[-1], '__name__', p[3]) + + +def p_namespace_scope(p): + '''namespace_scope : '*' + | IDENTIFIER''' + p[0] = p[1] + + +def p_sep(p): + '''sep : ',' + | ';' + ''' + + +def p_definition(p): + '''definition : definition definition_unit_ + |''' + + +def p_definition_unit_(p): + '''definition_unit_ : definition_unit ';' + | definition_unit''' + + +def p_definition_unit(p): + '''definition_unit : const + | ttype + ''' + + +def p_const(p): + '''const : CONST field_type IDENTIFIER '=' const_value type_annotations + | CONST field_type IDENTIFIER '=' const_value type_annotations sep''' + + try: + val = _cast(p[2], p.lineno(3))(p[5]) + except AssertionError: + raise ThriftParserError('Type error for constant %s at line %d' % + (p[3], p.lineno(3))) + thrift = threadlocal.thrift_stack[-1] + setattr(thrift, p[3], val) + _add_thrift_meta('consts', val) + if p[6]: + if not hasattr(thrift, '__thrift_const_annotations__'): + thrift.__thrift_const_annotations__ = {} + thrift.__thrift_const_annotations__[p[3]] = _annotations_to_dict(p[6]) + + +def p_const_value(p): + '''const_value : INTCONSTANT + | DUBCONSTANT + | LITERAL + | BOOLCONSTANT + | const_list + | const_map + | const_ref''' + p[0] = p[1] + + +def p_const_list(p): + '''const_list : '[' const_list_seq ']' ''' + p[0] = p[2] + + +def p_const_list_seq(p): + '''const_list_seq : const_value sep const_list_seq + | const_value const_list_seq + |''' + _parse_seq(p) + + +def p_const_map(p): + '''const_map : '{' const_map_seq '}' ''' + p[0] = dict(p[2]) + + +def p_const_map_seq(p): + '''const_map_seq : const_map_item sep const_map_seq + | const_map_item const_map_seq + |''' + _parse_seq(p) + + +def p_const_map_item(p): + '''const_map_item : const_value ':' const_value ''' + p[0] = [p[1], p[3]] + + +def p_const_ref(p): + '''const_ref : IDENTIFIER''' + child = threadlocal.thrift_stack[-1] + for name in p[1].split('.'): + father = child + child = getattr(child, name, None) + if child is None: + raise ThriftParserError('Can\'t find name %r at line %d' + % (p[1], p.lineno(1))) + + if _get_ttype(child) is None or _get_ttype(father) == TType.I32: + # child is a constant or enum value + p[0] = child + else: + raise ThriftParserError('No enum value or constant found ' + 'named %r' % p[1]) + + +def p_ttype(p): + '''ttype : typedef + | enum + | struct + | union + | exception + | service''' + + +def p_typedef(p): + '''typedef : TYPEDEF field_type IDENTIFIER type_annotations''' + thrift = threadlocal.thrift_stack[-1] + setattr(thrift, p[3], p[2]) + if p[4]: + if not hasattr(thrift, '__thrift_typedef_annotations__'): + thrift.__thrift_typedef_annotations__ = {} + thrift.__thrift_typedef_annotations__[p[3]] = _annotations_to_dict(p[4]) + + +def p_enum(p): # noqa + '''enum : ENUM IDENTIFIER '{' enum_seq '}' type_annotations''' + val = _make_enum(p[2], p[4], p[6]) + setattr(threadlocal.thrift_stack[-1], p[2], val) + _add_thrift_meta('enums', val) + + +def p_enum_seq(p): + '''enum_seq : enum_item sep enum_seq + | enum_item enum_seq + |''' + _parse_seq(p) + + +def p_enum_item(p): + '''enum_item : IDENTIFIER '=' INTCONSTANT type_annotations + | IDENTIFIER type_annotations + |''' + if len(p) == 5: + p[0] = [p[1], p[3], p[4]] + elif len(p) == 3: + p[0] = [p[1], None, p[2]] + + +def p_struct(p): + '''struct : seen_struct '{' field_seq '}' type_annotations''' + val = _fill_in_struct(p[1], p[3]) + val.__thrift_annotations__ = _annotations_to_dict(p[5]) + _add_thrift_meta('structs', val) + + +def p_seen_struct(p): + '''seen_struct : STRUCT IDENTIFIER ''' + val = _make_empty_struct(p[2]) + setattr(threadlocal.thrift_stack[-1], p[2], val) + p[0] = val + + +def p_union(p): + '''union : seen_union '{' field_seq '}' type_annotations''' + val = _fill_in_struct(p[1], p[3]) + val.__thrift_annotations__ = _annotations_to_dict(p[5]) + _add_thrift_meta('unions', val) + + +def p_seen_union(p): + '''seen_union : UNION IDENTIFIER ''' + val = _make_empty_struct(p[2]) + setattr(threadlocal.thrift_stack[-1], p[2], val) + p[0] = val + + +def p_exception(p): + '''exception : EXCEPTION IDENTIFIER '{' field_seq '}' type_annotations ''' + val = _make_struct(p[2], p[4], base_cls=TException) + val.__thrift_annotations__ = _annotations_to_dict(p[6]) + setattr(threadlocal.thrift_stack[-1], p[2], val) + _add_thrift_meta('exceptions', val) + + +def p_simple_service(p): + '''simple_service : SERVICE IDENTIFIER '{' function_seq '}' + | SERVICE IDENTIFIER EXTENDS IDENTIFIER '{' function_seq '}' + ''' + thrift = threadlocal.thrift_stack[-1] + + if len(p) == 8: + extends = thrift + for name in p[4].split('.'): + extends = getattr(extends, name, None) + if extends is None: + raise ThriftParserError('Can\'t find service %r for ' + 'service %r to extend' % + (p[4], p[2])) + + if not hasattr(extends, 'thrift_services'): + raise ThriftParserError('Can\'t extends %r, not a service' + % p[4]) + + else: + extends = None + + p[0] = (p[2], p[len(p) - 2], extends) + + +def p_service(p): + '''service : simple_service type_annotations''' + name, funcs, extends = p[1] + thrift = threadlocal.thrift_stack[-1] + val = _make_service(name, funcs, extends, p[2]) + setattr(thrift, name, val) + _add_thrift_meta('services', val) + + +def p_simple_function(p): + '''simple_function : ONEWAY function_type IDENTIFIER '(' field_seq ')' + | ONEWAY function_type IDENTIFIER '(' field_seq ')' throws + | function_type IDENTIFIER '(' field_seq ')' throws + | function_type IDENTIFIER '(' field_seq ')' ''' + + if p[1] == 'oneway': + oneway = True + base = 1 + else: + oneway = False + base = 0 + + if p[len(p) - 1] == ')': + throws = [] + else: + throws = p[len(p) - 1] + + p[0] = [oneway, p[base + 1], p[base + 2], p[base + 4], throws] + + +def p_function(p): + '''function : simple_function type_annotations''' + p[0] = p[1] + [p[2]] + + +def p_function_seq(p): + '''function_seq : function sep function_seq + | function function_seq + |''' + _parse_seq(p) + + +def p_throws(p): + '''throws : THROWS '(' field_seq ')' ''' + p[0] = p[3] + + +def p_function_type(p): + '''function_type : field_type + | VOID''' + if p[1] == 'void': + p[0] = TType.VOID + else: + p[0] = p[1] + + +def p_field_seq(p): + '''field_seq : field sep field_seq + | field field_seq + |''' + threadlocal.field_seq_implicit_id = itertools.count(start=-1, step=-1) + _parse_seq(p) + + +def p_simple_field(p): + '''simple_field : field_id field_req field_type IDENTIFIER + | field_id field_req field_type IDENTIFIER '=' const_value + ''' + + if len(p) == 7: + try: + val = _cast(p[3])(p[6]) + except AssertionError: + raise ThriftParserError( + 'Type error for field %s ' + 'at line %d' % (p[4], p.lineno(4))) + else: + val = None + + p[0] = [p[1], p[2], p[3], p[4], val] + + +def p_field(p): + '''field : simple_field type_annotations''' + p[0] = p[1] + [p[2]] + + +def p_field_id(p): + '''field_id : INTCONSTANT ':' + |''' + if len(p) == 1: + p[0] = next(threadlocal.field_seq_implicit_id) + else: + p[0] = p[1] + + +def p_field_req(p): + '''field_req : REQUIRED + | OPTIONAL + |''' + if len(p) == 2: + p[0] = p[1] == 'required' + elif len(p) == 1: + p[0] = False # default: required=False + + +def p_field_type(p): + '''field_type : ref_type + | definition_type''' + p[0] = p[1] + + +class CurrentIncompleteType(dict): + index = -1 + + def set_info(self, info): + self[self.index] = info + self.index -= 1 + return self.index + 1 + + +def p_ref_type(p): + '''ref_type : IDENTIFIER''' + ref_type = threadlocal.thrift_stack[-1] + + for attr in dir(ref_type): + if attr in {'__doc__', '__loader__', '__name__', '__package__', + '__spec__', '__thrift_file__', '__thrift_meta__'}: + continue + if p[1].startswith(attr + '.'): + name = p[1][len(attr) + 1:] + included_ref_type = getattr(ref_type, attr) + resolved_ref_type = getattr(included_ref_type, name, None) + if resolved_ref_type is not None: + ref_type = resolved_ref_type + break + else: + for index, name in enumerate(p[1].split('.')): + ref_type = getattr(ref_type, name, None) + if ref_type is None: + if index != len(p[1].split('.')) - 1: + raise ThriftParserError('No type found: %r, at line %d' % + (p[1], p.lineno(1))) + p[0] = threadlocal.incomplete_type.set_info((p[1], p.lineno(1))) + return + + if hasattr(ref_type, '_ttype'): + p[0] = getattr(ref_type, '_ttype'), ref_type + else: + p[0] = ref_type + + +def p_simple_base_type(p): # noqa + '''simple_base_type : BOOL + | BYTE + | I8 + | I16 + | I32 + | I64 + | DOUBLE + | STRING + | BINARY''' + if p[1] == 'bool': + p[0] = TType.BOOL + if p[1] == 'byte' or p[1] == 'i8': + p[0] = TType.BYTE + if p[1] == 'i16': + p[0] = TType.I16 + if p[1] == 'i32': + p[0] = TType.I32 + if p[1] == 'i64': + p[0] = TType.I64 + if p[1] == 'double': + p[0] = TType.DOUBLE + if p[1] == 'string': + p[0] = TType.STRING + if p[1] == 'binary': + p[0] = TType.BINARY + + +def p_base_type(p): + '''base_type : simple_base_type type_annotations''' + p[0] = p[1] + + +def p_simple_container_type(p): + '''simple_container_type : map_type + | list_type + | set_type''' + p[0] = p[1] + + +def p_container_type(p): + '''container_type : simple_container_type type_annotations''' + p[0] = p[1] + + +def p_map_type(p): + '''map_type : MAP '<' field_type ',' field_type '>' ''' + p[0] = TType.MAP, (p[3], p[5]) + + +def p_list_type(p): + '''list_type : LIST '<' field_type '>' ''' + p[0] = TType.LIST, p[3] + + +def p_set_type(p): + '''set_type : SET '<' field_type '>' ''' + p[0] = TType.SET, p[3] + + +def p_definition_type(p): + '''definition_type : base_type + | container_type''' + p[0] = p[1] + + +def p_type_annotations(p): + '''type_annotations : '(' type_annotation_seq ')' + |''' + if len(p) == 4: + p[0] = p[2] + else: + p[0] = None + + +def p_type_annotation_seq(p): + '''type_annotation_seq : type_annotation sep type_annotation_seq + | type_annotation type_annotation_seq + |''' + _parse_seq(p) + + +def p_type_annotation(p): + '''type_annotation : IDENTIFIER '=' LITERAL + | IDENTIFIER ''' + if len(p) == 4: + p[0] = p[1], p[3] + else: + p[0] = p[1], None # Without Value + + +def parse(path, module_name=None, include_dirs=None, include_dir=None, + lexer=None, parser=None, enable_cache=True, encoding='utf-8'): + """Parse a single thrift file to module object, e.g.:: + + >>> from thriftpy2.parser.parser import parse + >>> note_thrift = parse("path/to/note.thrift") + + + :param path: file path to parse, should be a string ending with '.thrift'. + :param module_name: the name for parsed module, the default is the basename + without extension of `path`. + :param include_dirs: directories to find thrift files while processing + the `include` directive, by default: ['.']. + :param include_dir: directory to find child thrift files. Note this keyword + parameter will be deprecated in the future, it exists + for compatible reason. If it's provided (not `None`), + it will be appended to `include_dirs`. + :param lexer: ply lexer to use, if not provided, `parse` will new one. + :param parser: ply parser to use, if not provided, `parse` will new one. + :param enable_cache: if this is set to be `True`, parsed module will be + cached, this is enabled by default. If `module_name` + is provided, use it as cache key, else use the `path`. + """ + # threadlocal should be initialized in every threads + initialized = getattr(threadlocal, 'initialized', None) + if initialized is None: + threadlocal.thrift_stack = [] + threadlocal.include_dirs_ = ['.'] + threadlocal.thrift_cache = {} + threadlocal.incomplete_type = CurrentIncompleteType() + threadlocal.field_seq_implicit_id = itertools.count(start=-1, step=-1) + threadlocal.initialized = True + + # dead include checking on current stack + for thrift in threadlocal.thrift_stack: + if thrift.__thrift_file__ is not None and \ + os.path.samefile(path, thrift.__thrift_file__): + raise ThriftParserError('Dead including on %s' % path) + + cache_key = module_name or os.path.normpath(path) + + if enable_cache and cache_key in threadlocal.thrift_cache: + return threadlocal.thrift_cache[cache_key] + + if lexer is None: + lexer = lex.lex() + if parser is None: + parser = yacc.yacc(debug=False, write_tables=0) + + if include_dirs is not None: + threadlocal.include_dirs_ = include_dirs + if include_dir is not None: + threadlocal.include_dirs_.append(include_dir) + + if not path.endswith('.thrift'): + raise ThriftParserError('Path should end with .thrift') + + url_scheme = urlparse(path).scheme + if url_scheme == 'file': + with open(urlparse(path).netloc + urlparse(path).path) as fh: + data = fh.read() + elif len(url_scheme) <= 1: + with open(path, encoding=encoding) as fh: + data = fh.read() + elif url_scheme in ('http', 'https'): + data = urlopen(path).read() + else: + raise ThriftParserError('thriftpy2 does not support generating module ' + 'with path in protocol \'{}\''.format( + url_scheme)) + + if isinstance(data, bytes): + data = data.decode(encoding) + + if module_name is not None and not module_name.endswith('_thrift'): + raise ThriftParserError('thriftpy2 can only generate module with ' + '\'_thrift\' suffix') + + if module_name is None: + basename = os.path.basename(path) + module_name = os.path.splitext(basename)[0] + + thrift = types.ModuleType(module_name) + setattr(thrift, '__thrift_file__', path) + threadlocal.thrift_stack.append(thrift) + lexer.lineno = 1 + parser.parse(data) + threadlocal.thrift_stack.pop() + + if enable_cache: + threadlocal.thrift_cache[cache_key] = thrift + return thrift + + +def parse_fp(source, module_name, lexer=None, parser=None, enable_cache=True): + """Parse a file-like object to thrift module object, e.g.:: + + >>> from thriftpy2.parser.parser import parse_fp + >>> with open("path/to/note.thrift") as fp: + parse_fp(fp, "note_thrift") + + + :param source: file-like object, expected to have a method named `read`. + :param module_name: the name for parsed module, should be endswith + '_thrift'. + :param lexer: ply lexer to use, if not provided, `parse` will new one. + :param parser: ply parser to use, if not provided, `parse` will new one. + :param enable_cache: if this is set to be `True`, parsed module will be + cached by `module_name`, this is enabled by default. + """ + # threadlocal should be initialized in every threads + initialized = getattr(threadlocal, 'initialized', None) + if initialized is None: + threadlocal.thrift_stack = [] + threadlocal.include_dirs_ = ['.'] + threadlocal.thrift_cache = {} + threadlocal.incomplete_type = CurrentIncompleteType() + threadlocal.field_seq_implicit_id = itertools.count(start=-1, step=-1) + threadlocal.initialized = True + + if not module_name.endswith('_thrift'): + raise ThriftParserError('thriftpy2 can only generate module with ' + '\'_thrift\' suffix') + + if enable_cache and module_name in threadlocal.thrift_cache: + return threadlocal.thrift_cache[module_name] + + if not hasattr(source, 'read'): + raise ThriftParserError('Expected `source` to be a file-like object ' + 'with a method named \'read\'') + + if lexer is None: + lexer = lex.lex() + if parser is None: + parser = yacc.yacc(debug=False, write_tables=0) + + data = source.read() + + thrift = types.ModuleType(module_name) + setattr(thrift, '__thrift_file__', None) + threadlocal.thrift_stack.append(thrift) + lexer.lineno = 1 + parser.parse(data) + threadlocal.thrift_stack.pop() + + if enable_cache: + threadlocal.thrift_cache[module_name] = thrift + return thrift + + +def _add_thrift_meta(key, val): + thrift = threadlocal.thrift_stack[-1] + + if not hasattr(thrift, '__thrift_meta__'): + meta = collections.defaultdict(list) + setattr(thrift, '__thrift_meta__', meta) + else: + meta = getattr(thrift, '__thrift_meta__') + + if key != 'consts' and val.__name__ in [x.__name__ for x in meta[key]]: + raise ThriftGrammarError(('\'%s\' type is already defined in ' + '\'%s\'') % (val.__name__, key)) + + meta[key].append(val) + + +def _parse_seq(p): + if len(p) == 4: + p[0] = [p[1]] + p[3] + elif len(p) == 3: + p[0] = [p[1]] + p[2] + elif len(p) == 1: + p[0] = [] + + +def _cast(t, linno=0): # noqa + if isinstance(t, int) and t < 0: + return _lazy_cast_const(t, linno) + if t == TType.BOOL: + return _cast_bool + if t == TType.BYTE: + return _cast_byte + if t == TType.I16: + return _cast_i16 + if t == TType.I32: + return _cast_i32 + if t == TType.I64: + return _cast_i64 + if t == TType.DOUBLE: + return _cast_double + if t == TType.STRING: + return _cast_string + if t == TType.BINARY: + return _cast_binary + if t[0] == TType.LIST: + return _cast_list(t) + if t[0] == TType.SET: + return _cast_set(t) + if t[0] == TType.MAP: + return _cast_map(t) + if t[0] == TType.I32: + return _cast_enum(t) + if t[0] == TType.STRUCT: + return _cast_struct(t) + + +def _lazy_cast_const(t, linno): + def _inner_cast(v): + return ('UNKNOWN_CONST', t, v, linno) + return _inner_cast + + +def _cast_bool(v): + assert isinstance(v, (bool, int)) + return bool(v) + + +def _cast_byte(v): + assert isinstance(v, int) + return v + + +def _cast_i16(v): + assert isinstance(v, int) + return v + + +def _cast_i32(v): + assert isinstance(v, int) + return v + + +def _cast_i64(v): + assert isinstance(v, int) + return v + + +def _cast_double(v): + assert isinstance(v, (float, int)) + return float(v) + + +def _cast_string(v): + assert isinstance(v, str) + return v + + +def _cast_binary(v): + assert isinstance(v, str) + return v + + +def _cast_list(t): + assert t[0] == TType.LIST + + def __cast_list(v): + assert isinstance(v, list) + map(_cast(t[1]), v) + return v + return __cast_list + + +def _cast_set(t): + assert t[0] == TType.SET + + def __cast_set(v): + if len(v) == 0 and isinstance(v, dict): + v = set() + assert isinstance(v, (list, set)) + map(_cast(t[1]), v) + if not isinstance(v, set): + return set(v) + return v + return __cast_set + + +def _cast_map(t): + assert t[0] == TType.MAP + + def __cast_map(v): + assert isinstance(v, dict) + for key in v: + v[_cast(t[1][0])(key)] = \ + _cast(t[1][1])(v[key]) + return v + return __cast_map + + +def _cast_enum(t): + assert t[0] == TType.I32 + + def __cast_enum(v): + assert isinstance(v, int) + if v in t[1]._VALUES_TO_NAMES: + return v + raise ThriftParserError('Couldn\'t find a named value in enum ' + '%s for value %d' % (t[1].__name__, v)) + return __cast_enum + + +def _cast_struct(t): # struct/exception/union + assert t[0] == TType.STRUCT + + def __cast_struct(v): + if isinstance(v, t[1]): + return v # already cast + + assert isinstance(v, dict) + tspec = getattr(t[1], '_tspec') + + for key in tspec: # requirement check + if tspec[key][0] and key not in v: + raise ThriftParserError('Field %r was required to create ' + 'constant for type %r' % + (key, t[1].__name__)) + + for key in v: # cast values + if key not in tspec: + raise ThriftParserError('No field named %r was ' + 'found in struct of type %r' % + (key, t[1].__name__)) + v[key] = _cast(tspec[key][1])(v[key]) + return t[1](**v) + return __cast_struct + + +def _make_enum(name, kvs, annotations=None): + attrs = { + '__module__': threadlocal.thrift_stack[-1].__name__, + '_ttype': TType.I32 + } + cls = type(name, (object, ), attrs) + + _values_to_names = {} + _names_to_values = {} + item_annotations = {} + + if kvs: + val = kvs[0][1] + if val is None: + val = -1 + for item in kvs: + if item[1] is None: + item[1] = val + 1 + val = item[1] + for key, val, *annotation in kvs: + setattr(cls, key, val) + _values_to_names[val] = key + _names_to_values[key] = val + # Store item annotations if present (index 2) + if annotation and annotation[0]: + item_annotations[key] = _annotations_to_dict(annotation[0]) + setattr(cls, '_VALUES_TO_NAMES', _values_to_names) + setattr(cls, '_NAMES_TO_VALUES', _names_to_values) + setattr(cls, '__thrift_annotations__', _annotations_to_dict(annotations)) + setattr(cls, '__thrift_item_annotations__', item_annotations) + return cls + + +def _make_empty_struct(name, ttype=TType.STRUCT, base_cls=TPayload): + attrs = { + '__module__': threadlocal.thrift_stack[-1].__name__, + '_ttype': ttype + } + return type(name, (base_cls, ), attrs) + + +def _fill_in_struct(cls, fields, _gen_init=True): + thrift_spec = {} + default_spec = [] + _tspec = {} + field_annotations = {} + + for field in fields: + if field[0] in thrift_spec or field[3] in _tspec: + raise ThriftGrammarError(('\'%d:%s\' field identifier/name has ' + 'already been used') % (field[0], + field[3])) + ttype = field[2] + thrift_spec[field[0]] = _ttype_spec(ttype, field[3], field[1]) + default_spec.append((field[3], field[4])) + _tspec[field[3]] = field[1], ttype + if len(field) > 5 and field[5]: + field_annotations[field[3]] = _annotations_to_dict(field[5]) + setattr(cls, 'thrift_spec', thrift_spec) + setattr(cls, 'default_spec', default_spec) + setattr(cls, '_tspec', _tspec) + setattr(cls, '__thrift_field_annotations__', field_annotations) + if _gen_init: + gen_init(cls, thrift_spec, default_spec) + return cls + + +def _make_struct(name, fields, ttype=TType.STRUCT, base_cls=TPayload, + _gen_init=True): + cls = _make_empty_struct(name, ttype=ttype, base_cls=base_cls) + return _fill_in_struct(cls, fields, _gen_init=_gen_init) + + +def _make_service(name, funcs, extends, annotations=None): + if extends is None: + extends = object + + attrs = {'__module__': threadlocal.thrift_stack[-1].__name__} + cls = type(name, (extends, ), attrs) + thrift_services = [] + function_annotations = {} + + for func in funcs: + func_name = func[2] + if func_name in thrift_services: + raise ThriftGrammarError(('\'%s\' function is already defined in ' + 'service \'%s\'') % (func_name, + name)) + # args payload cls + args_name = '%s_args' % func_name + args_fields = func[3] + args_cls = _make_struct(args_name, args_fields) + setattr(cls, args_name, args_cls) + # result payload cls + result_name = '%s_result' % func_name + result_type = func[1] + result_throws = func[4] + result_oneway = func[0] + result_cls = _make_struct(result_name, result_throws, + _gen_init=False) + setattr(result_cls, 'oneway', result_oneway) + if result_type != TType.VOID: + result_cls.thrift_spec[0] = _ttype_spec(result_type, 'success') + result_cls.default_spec.insert(0, ('success', None)) + gen_init(result_cls, result_cls.thrift_spec, result_cls.default_spec) + setattr(cls, result_name, result_cls) + thrift_services.append(func_name) + if len(func) > 5 and func[5]: + function_annotations[func_name] = _annotations_to_dict(func[5]) + if extends is not None and hasattr(extends, 'thrift_services'): + thrift_services.extend(extends.thrift_services) + setattr(cls, 'thrift_services', thrift_services) + setattr(cls, '__thrift_annotations__', _annotations_to_dict(annotations)) + setattr(cls, '__thrift_function_annotations__', function_annotations) + return cls + + +def _ttype_spec(ttype, name, required=False): + if isinstance(ttype, int): + return ttype, name, required + else: + return ttype[0], name, ttype[1], required + + +def _get_ttype(inst, default_ttype=None): + if hasattr(inst, '__dict__') and '_ttype' in inst.__dict__: + return inst.__dict__['_ttype'] + return default_ttype diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/protocol/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/protocol/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..452186f9a14812bf6e89c1444548d60fc75b4879 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/protocol/__init__.py @@ -0,0 +1,29 @@ +# -*- coding: utf-8 -*- + +from __future__ import absolute_import + +from .base import TProtocolBase +from .binary import TBinaryProtocol, TBinaryProtocolFactory +from .json import TJSONProtocol, TJSONProtocolFactory +from .apache_json import TApacheJSONProtocol, TApacheJSONProtocolFactory +from .compact import TCompactProtocol, TCompactProtocolFactory +from .multiplex import TMultiplexedProtocol, TMultiplexedProtocolFactory + +from thriftpy2._compat import PYPY, CYTHON +if not PYPY: + # enable cython binary by default for CPython. + if CYTHON: + from .cybin import TCyBinaryProtocol, TCyBinaryProtocolFactory + TBinaryProtocol = TCyBinaryProtocol # noqa + TBinaryProtocolFactory = TCyBinaryProtocolFactory # noqa +else: + # disable cython binary protocol for PYPY since it's slower. + TCyBinaryProtocol = TBinaryProtocol + TCyBinaryProtocolFactory = TBinaryProtocolFactory + +__all__ = ['TProtocolBase', 'TBinaryProtocol', 'TBinaryProtocolFactory', + 'TCyBinaryProtocol', 'TCyBinaryProtocolFactory', + 'TJSONProtocol', 'TJSONProtocolFactory', + 'TApacheJSONProtocol', 'TApacheJSONProtocolFactory', + 'TMultiplexedProtocol', 'TMultiplexedProtocolFactory', + 'TCompactProtocol', 'TCompactProtocolFactory'] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/protocol/apache_json.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/protocol/apache_json.py new file mode 100644 index 0000000000000000000000000000000000000000..625a628e9e92608e7c2c5885244dd1366a72368b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/protocol/apache_json.py @@ -0,0 +1,319 @@ +# -*- coding: utf-8 -*- + +""" +Transport for json protocol that apache thrift files will understand +unfortunately, thriftpy2's TJSONProtocol is not compatible with apache's +""" + +from __future__ import absolute_import +import json +import base64 +import sys + +import six + +from thriftpy2.protocol import TProtocolBase +from thriftpy2.thrift import TType + + +CTYPES = { + TType.BOOL: 'tf', + TType.BYTE: 'i8', + TType.I16: 'i16', + TType.I32: 'i32', + TType.I64: 'i64', + TType.DOUBLE: 'dbl', + TType.STRING: 'str', + TType.BINARY: 'str', # apache sends binary data as base64 encoded + TType.STRUCT: 'rec', + TType.LIST: 'lst', + TType.SET: 'set', + TType.MAP: 'map', +} + +JTYPES = {v: k for k, v in CTYPES.items()} + +VERSION = 1 + + +def flatten(suitable_for_isinstance): + """ + isinstance() can accept a bunch of really annoying different types: + * a single type + * a tuple of types + * an arbitrary nested tree of tuples + Return a flattened tuple of the given argument. + """ + + types = list() + + if not isinstance(suitable_for_isinstance, tuple): + suitable_for_isinstance = (suitable_for_isinstance,) + for thing in suitable_for_isinstance: + if isinstance(thing, tuple): + types.extend(flatten(thing)) + else: + types.append(thing) + return tuple(types) + + +def _ensure_b64_encode(val): + """ + Ensure that the variable is something that we can encode with b64encode + python3 needs bytes, python2 needs string + """ + if sys.version_info[0] > 2 and isinstance(val, str): + return val.encode() + return val + + +class TApacheJSONProtocolFactory(object): + def get_protocol(self, trans): + return TApacheJSONProtocol(trans) + + +class TApacheJSONProtocol(TProtocolBase): + """ + Protocol that implements the Apache JSON Protocol + """ + + def __init__(self, trans): + TProtocolBase.__init__(self, trans) + self._req = None + + def _load_data(self): + data = b"" + l_braces = 0 + in_string = False + while True: + # read(sz) will wait until it has read exactly sz bytes, + # so we must read until we get a balanced json list in absence of knowing + # how long the json string will be + if hasattr(self.trans, 'getvalue'): + try: + data = self.trans.getvalue() + break + except Exception: + pass + new_data = self.trans.read(1) + data += new_data + if new_data == b'"' and not data.endswith(b'\\"'): + in_string = not in_string + if not in_string: + if new_data == b"[": + l_braces += 1 + elif new_data == b"]": + l_braces -= 1 + if l_braces == 0: + break + if data: + self._req = json.loads(data.decode('utf8')) + else: + self._req = None + + def read_message_begin(self): + if not self._req: + self._load_data() + return self._req[1:4] + + def read_message_end(self): + pass + + def skip(self, ttype): + pass + + def write_message_end(self): + pass + + def write_message_begin(self, name, ttype, seqid): + self.api = name + self.ttype = ttype + self.seqid = seqid + + def write_struct(self, obj): + """ + Write json to self.trans following apache style jsonification of `obj` + + :param obj: A thriftpy2 object + :return: + """ + doc = [VERSION, self.api, self.ttype, self.seqid, self._thrift_to_dict(obj)] + json_str = json.dumps(doc, separators=(',', ':')) + self.trans.write(json_str.encode("utf8")) + + def _thrift_to_dict(self, thrift_obj, item_type=None): + """ + Convert a thriftpy2 into an apache conformant dict, eg: + + >>> {0: {'rec': {1: {'str': "304"}, 14: {'rec': {1: {'lst': ["rec", 0]}}}}}} + + >>> {"0":{"rec":{"1":{"str":"284"},"14":{"rec":{"1":{"lst": + >>> ["rec",2,{"1":{"i32":12345.0},"2":{"i32":2.0},"3":{"str":"Testing notifications"},"4":{"tf":1}}, + {"1":{"i32":567809.0},"2":{"i32":2.0},"3":{"str":"Other test"},"4":{"tf":0}}]}}}}}} + + :param thrift_obj: the thing we want to make into a dict + :param item_type: the type of the item we are to convert + :return: + """ + if not hasattr(thrift_obj, 'thrift_spec'): + # use item_type to render it + if item_type is not None: + if isinstance(item_type, tuple) and len(item_type) > 1: + to_type = item_type[1] + flat_key_val = [TType.STRUCT if hasattr(t, 'thrift_spec') else t for t in flatten(to_type)] + if flat_key_val[0] == TType.LIST or isinstance(thrift_obj, list): + return [CTYPES[flat_key_val[1]], len(thrift_obj)] + [self._thrift_to_dict(v, to_type[1]) for v + in thrift_obj] + elif flat_key_val[0] == TType.MAP or isinstance(thrift_obj, dict): + if to_type[0] == TType.MAP: + key_type = flat_key_val[1] + val_type = flat_key_val[2] + else: + key_type = flat_key_val[0] + val_type = flat_key_val[1] + return [CTYPES[key_type], CTYPES[val_type], len(thrift_obj), { + self._thrift_to_dict(k, key_type): + self._thrift_to_dict(v, to_type[1]) for k, v in thrift_obj.items() + }] + if (to_type == TType.BINARY or item_type[-1] == TType.BINARY) and TType.BINARY != TType.STRING: + return base64.b64encode(_ensure_b64_encode(thrift_obj)).decode('ascii') + if isinstance(thrift_obj, bool): + return int(thrift_obj) + if ( + item_type == TType.BINARY + or (isinstance(item_type, tuple) and item_type[0] == TType.BINARY) + ) and TType.BINARY != TType.STRING: + return base64.b64encode(_ensure_b64_encode(thrift_obj)).decode("ascii") + return thrift_obj + result = {} + for field_idx, thrift_spec in thrift_obj.thrift_spec.items(): + ttype, field_name, spec = thrift_spec[:3] + if isinstance(spec, int): + spec = (spec,) + val = getattr(thrift_obj, field_name) + if val is not None: + if ttype == TType.STRUCT: + result[field_idx] = { + CTYPES[ttype]: self._thrift_to_dict(val) + } + elif ttype in [TType.LIST, TType.SET]: + # format is [list_item_type, length, items] + result[field_idx] = { + CTYPES[ttype]: [CTYPES[spec[0]], len(val)] + [self._thrift_to_dict(v, spec) for v in val] + } + elif ttype == TType.MAP: + key_type = CTYPES[spec[0]] + val_type = CTYPES[spec[1][0] if isinstance(spec[1], tuple) else spec[1]] + # format is [key_type, value_type, length, dict] + result[field_idx] = { + CTYPES[ttype]: [key_type, val_type, len(val), + {self._thrift_to_dict(k, spec[0]): + self._thrift_to_dict(v, spec) for k, v in val.items()}] + } + elif ttype == TType.BINARY and TType.BINARY != TType.STRING: + result[field_idx] = { + CTYPES[ttype]: base64.b64encode(_ensure_b64_encode(val)).decode('ascii') + } + elif ttype == TType.BOOL: + result[field_idx] = { + CTYPES[ttype]: int(val) + } + else: + result[field_idx] = { + CTYPES[ttype]: val + } + return result + + def _dict_to_thrift(self, data, base_type): + """ + Convert an apache thrift dict (where key is the type, value is the data) + + :param data: the dict data + :param base_type: the type we are going to convert data to + :return: + """ + # if the result is a python type, return it: + if isinstance(data, (str, int, float, bool, six.string_types, six.binary_type)) or data is None: + if base_type in (TType.I08, TType.I16, TType.I32, TType.I64): + return int(data) + if base_type == TType.BINARY and TType.BINARY != TType.STRING: + return base64.b64decode(data) + if base_type == TType.BOOL: + return { + 'true': True, + 'false': False, + '1': True, + '0': False + }[data.lower()] + if isinstance(data, bool): + return int(data) + return data + + if isinstance(base_type, tuple): + container_type = base_type[0] + item_type = base_type[1] + if container_type == TType.STRUCT: + return self._dict_to_thrift(data, item_type) + elif container_type in (TType.LIST, TType.SET): + return [self._dict_to_thrift(v, item_type) for v in data[2:]] + elif container_type == TType.MAP: + return { + self._dict_to_thrift(k, item_type[0]): + self._dict_to_thrift(v, item_type[1]) for k, v in data[3].items() + } + result = {} + base_spec = base_type.thrift_spec + for field_idx, val in data.items(): + thrift_spec = base_spec[int(field_idx)] + # spec has field type, field name, (sub spec), False + field_name = thrift_spec[1] + for ftype, value in val.items(): + ttype = JTYPES[ftype] + if thrift_spec[0] == TType.BINARY and TType.BINARY != TType.STRING: + bin_data = val.get('str', '') + m = len(bin_data) % 4 + if m != 0: + bin_data += '=' * (4-m) + result[field_name] = base64.b64decode(bin_data) + + elif ttype == TType.STRUCT: + result[field_name] = self._dict_to_thrift(value, thrift_spec[2]) + elif ttype in (TType.LIST, TType.SET): + result[field_name] = [self._dict_to_thrift(v, thrift_spec[2]) for v in value[2:]] + elif ttype == TType.MAP: + key_spec = thrift_spec[2][0] + val_spec = thrift_spec[2][1] + result[field_name] = { + self._dict_to_thrift(k, key_spec): self._dict_to_thrift(v, val_spec) + for k, v in value[3].items() + } + else: + result[field_name] = { + 'tf': bool, + 'i8': int, + 'i16': int, + 'i32': int, + 'i64': int, + 'dbl': float, + 'str': str, + }[ftype](value) + if hasattr(base_type, '__call__'): + return base_type(**result) + else: + for k, v in result.items(): + setattr(base_type, k, v) + return base_type + + def read_struct(self, obj): + """ + Read the next struct into obj, usually the argument from an incoming request + Only really used to read the arguments off a request into whatever we want + see thriftpy2.thrift.TProcessor.process_in for how this class will be used + + Will turn the contents of self.req[4] into the args of obj, + ie. self.req[4]["1"] must be rendered into obj.thrift_spec + + :param obj: + :return: + """ + return self._dict_to_thrift(self._req[4], obj) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/protocol/base.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/protocol/base.py new file mode 100644 index 0000000000000000000000000000000000000000..d7fac64c812e8c9f91a8efe8c71df447b024e80d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/protocol/base.py @@ -0,0 +1,42 @@ +from __future__ import annotations + +try: + from typing import Protocol +except ImportError: + from typing_extensions import Protocol + + +class TProtocolFactory(Protocol): + """Protocol factory interface for type annotations.""" + + def get_protocol(self, trans) -> TProtocolBase: + """Return a protocol instance for the given transport.""" + ... + + +class TProtocolBase(object): + """Base class for Thrift protocol layer.""" + + def __init__(self, trans): + self.trans = trans # transport is public and used by TClient + + def skip(self, ttype): + raise NotImplementedError + + def read_message_begin(self): + raise NotImplementedError + + def read_message_end(self): + raise NotImplementedError + + def write_message_begin(self, name, ttype, seqid): + raise NotImplementedError + + def write_message_end(self): + raise NotImplementedError + + def read_struct(self, obj): + raise NotImplementedError + + def write_struct(self, obj): + raise NotImplementedError diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/protocol/binary.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/protocol/binary.py new file mode 100644 index 0000000000000000000000000000000000000000..fbffa291c6275c37ff64fa786f3b25f3654ae96a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/protocol/binary.py @@ -0,0 +1,433 @@ +# -*- coding: utf-8 -*- + +from __future__ import absolute_import + +import struct + +from ..thrift import TType + +from .exc import TProtocolException +from .base import TProtocolBase + +# VERSION_MASK = 0xffff0000 +VERSION_MASK = -65536 +# VERSION_1 = 0x80010000 +VERSION_1 = -2147418112 +TYPE_MASK = 0x000000ff +BIN_TYPES = (TType.STRING, TType.BINARY) + + +def pack_i8(byte): + return struct.pack("!b", byte) + + +def pack_i16(i16): + return struct.pack("!h", i16) + + +def pack_i32(i32): + return struct.pack("!i", i32) + + +def pack_i64(i64): + return struct.pack("!q", i64) + + +def pack_double(dub): + return struct.pack("!d", dub) + + +def pack_string(string): + return struct.pack("!i%ds" % len(string), len(string), string) + + +def unpack_i8(buf): + return struct.unpack("!b", buf)[0] + + +def unpack_i16(buf): + return struct.unpack("!h", buf)[0] + + +def unpack_i32(buf): + return struct.unpack("!i", buf)[0] + + +def unpack_i64(buf): + return struct.unpack("!q", buf)[0] + + +def unpack_double(buf): + return struct.unpack("!d", buf)[0] + + +def write_message_begin(outbuf, name, ttype, seqid, strict=True): + if strict: + outbuf.write(pack_i32(VERSION_1 | ttype)) + outbuf.write(pack_string(name.encode('utf-8'))) + else: + outbuf.write(pack_string(name.encode('utf-8'))) + outbuf.write(pack_i8(ttype)) + + outbuf.write(pack_i32(seqid)) + + +def write_field_begin(outbuf, ttype, fid): + if ttype == TType.BINARY: + ttype = TType.STRING + outbuf.write(pack_i8(ttype) + pack_i16(fid)) + + +def write_field_stop(outbuf): + outbuf.write(pack_i8(TType.STOP)) + + +def write_list_begin(outbuf, etype, size): + if etype == TType.BINARY: + etype = TType.STRING + outbuf.write(pack_i8(etype) + pack_i32(size)) + + +def write_map_begin(outbuf, ktype, vtype, size): + if ktype == TType.BINARY: + ktype = TType.STRING + if vtype == TType.BINARY: + vtype = TType.STRING + outbuf.write(pack_i8(ktype) + pack_i8(vtype) + pack_i32(size)) + + +def write_val(outbuf, ttype, val, spec=None): + if ttype == TType.BOOL: + if val: + outbuf.write(pack_i8(1)) + else: + outbuf.write(pack_i8(0)) + + elif ttype == TType.BYTE: + outbuf.write(pack_i8(val)) + + elif ttype == TType.I16: + outbuf.write(pack_i16(val)) + + elif ttype == TType.I32: + outbuf.write(pack_i32(val)) + + elif ttype == TType.I64: + outbuf.write(pack_i64(val)) + + elif ttype == TType.DOUBLE: + outbuf.write(pack_double(val)) + + elif ttype in BIN_TYPES: + if not isinstance(val, bytes): + val = val.encode('utf-8') + outbuf.write(pack_string(val)) + + elif ttype == TType.SET or ttype == TType.LIST: + if isinstance(spec, tuple): + e_type, t_spec = spec[0], spec[1] + else: + e_type, t_spec = spec, None + + val_len = len(val) + write_list_begin(outbuf, e_type, val_len) + for e_val in val: + write_val(outbuf, e_type, e_val, t_spec) + + elif ttype == TType.MAP: + if isinstance(spec[0], int): + k_type = spec[0] + k_spec = None + else: + k_type, k_spec = spec[0] + + if isinstance(spec[1], int): + v_type = spec[1] + v_spec = None + else: + v_type, v_spec = spec[1] + + write_map_begin(outbuf, k_type, v_type, len(val)) + for k in iter(val): + write_val(outbuf, k_type, k, k_spec) + write_val(outbuf, v_type, val[k], v_spec) + + elif ttype == TType.STRUCT: + for fid in iter(val.thrift_spec): + f_spec = val.thrift_spec[fid] + if len(f_spec) == 3: + f_type, f_name, f_req = f_spec + f_container_spec = None + else: + f_type, f_name, f_container_spec, f_req = f_spec + + v = getattr(val, f_name, None) + if v is None: + continue + + write_field_begin(outbuf, f_type, fid) + write_val(outbuf, f_type, v, f_container_spec) + write_field_stop(outbuf) + + +def read_message_begin(inbuf, strict=True): + sz = unpack_i32(inbuf.read(4)) + if sz < 0: + version = sz & VERSION_MASK + if version != VERSION_1: + raise TProtocolException( + type=TProtocolException.BAD_VERSION, + message='Bad version in read_message_begin: %d' % (sz)) + name_sz = unpack_i32(inbuf.read(4)) + name = inbuf.read(name_sz).decode('utf-8') + + type_ = sz & TYPE_MASK + else: + if strict: + raise TProtocolException(type=TProtocolException.BAD_VERSION, + message='No protocol version header') + + name = inbuf.read(sz).decode('utf-8') + type_ = unpack_i8(inbuf.read(1)) + + seqid = unpack_i32(inbuf.read(4)) + + return name, type_, seqid + + +def read_field_begin(inbuf): + f_type = unpack_i8(inbuf.read(1)) + if f_type == TType.STOP: + return f_type, 0 + + return f_type, unpack_i16(inbuf.read(2)) + + +def read_list_begin(inbuf): + e_type = unpack_i8(inbuf.read(1)) + sz = unpack_i32(inbuf.read(4)) + return e_type, sz + + +def read_map_begin(inbuf): + k_type, v_type = unpack_i8(inbuf.read(1)), unpack_i8(inbuf.read(1)) + sz = unpack_i32(inbuf.read(4)) + return k_type, v_type, sz + + +def read_val(inbuf, ttype, spec=None, decode_response=True, + strict_decode=False): + if ttype == TType.BOOL: + return bool(unpack_i8(inbuf.read(1))) + + elif ttype == TType.BYTE: + return unpack_i8(inbuf.read(1)) + + elif ttype == TType.I16: + return unpack_i16(inbuf.read(2)) + + elif ttype == TType.I32: + return unpack_i32(inbuf.read(4)) + + elif ttype == TType.I64: + return unpack_i64(inbuf.read(8)) + + elif ttype == TType.DOUBLE: + return unpack_double(inbuf.read(8)) + + elif ttype == TType.BINARY: + sz = unpack_i32(inbuf.read(4)) + return inbuf.read(sz) + + elif ttype == TType.STRING: + sz = unpack_i32(inbuf.read(4)) + byte_payload = inbuf.read(sz) + + # Since we cannot tell if we're getting STRING or BINARY + # if not asked not to decode, try both + if decode_response: + try: + return byte_payload.decode('utf-8') + except UnicodeDecodeError: + if strict_decode: + raise + return byte_payload + + elif ttype == TType.SET or ttype == TType.LIST: + if isinstance(spec, tuple): + v_type, v_spec = spec[0], spec[1] + else: + v_type, v_spec = spec, None + + result = [] + r_type, sz = read_list_begin(inbuf) + # the v_type is useless here since we already get it from spec + if (r_type != v_type + and not (r_type in BIN_TYPES and v_type in BIN_TYPES)): + for _ in range(sz): + skip(inbuf, r_type) + return [] + + for i in range(sz): + result.append(read_val(inbuf, v_type, v_spec, decode_response, + strict_decode)) + return result + + elif ttype == TType.MAP: + if isinstance(spec[0], int): + k_type = spec[0] + k_spec = None + else: + k_type, k_spec = spec[0] + + if isinstance(spec[1], int): + v_type = spec[1] + v_spec = None + else: + v_type, v_spec = spec[1] + + result = {} + sk_type, sv_type, sz = read_map_begin(inbuf) + if sk_type in BIN_TYPES: + sk_type = k_type + if sv_type in BIN_TYPES: + sv_type = v_type + if sk_type != k_type or sv_type != v_type: + for _ in range(sz): + skip(inbuf, sk_type) + skip(inbuf, sv_type) + return {} + + for i in range(sz): + k_val = read_val(inbuf, k_type, k_spec, decode_response, + strict_decode) + v_val = read_val(inbuf, v_type, v_spec, decode_response, + strict_decode) + result[k_val] = v_val + + return result + + elif ttype == TType.STRUCT: + obj = spec() + read_struct(inbuf, obj, decode_response, strict_decode) + return obj + + +def read_struct(inbuf, obj, decode_response=True, strict_decode=False): + while True: + f_type, fid = read_field_begin(inbuf) + if f_type == TType.STOP: + break + + if fid not in obj.thrift_spec: + skip(inbuf, f_type) + continue + + if len(obj.thrift_spec[fid]) == 3: + sf_type, f_name, f_req = obj.thrift_spec[fid] + f_container_spec = None + else: + sf_type, f_name, f_container_spec, f_req = obj.thrift_spec[fid] + + # it really should equal here. but since we already wasted + # space storing the duplicate info, let's check it. + if f_type != sf_type: + if f_type in BIN_TYPES: + f_type = sf_type + else: + skip(inbuf, f_type) + continue + + setattr(obj, f_name, + read_val(inbuf, f_type, f_container_spec, decode_response, + strict_decode)) + + +def skip(inbuf, ftype): + if ftype == TType.BOOL or ftype == TType.BYTE: + inbuf.read(1) + + elif ftype == TType.I16: + inbuf.read(2) + + elif ftype == TType.I32: + inbuf.read(4) + + elif ftype == TType.I64: + inbuf.read(8) + + elif ftype == TType.DOUBLE: + inbuf.read(8) + + elif ftype in BIN_TYPES: + inbuf.read(unpack_i32(inbuf.read(4))) + + elif ftype == TType.SET or ftype == TType.LIST: + v_type, sz = read_list_begin(inbuf) + for i in range(sz): + skip(inbuf, v_type) + + elif ftype == TType.MAP: + k_type, v_type, sz = read_map_begin(inbuf) + for i in range(sz): + skip(inbuf, k_type) + skip(inbuf, v_type) + + elif ftype == TType.STRUCT: + while True: + f_type, fid = read_field_begin(inbuf) + if f_type == TType.STOP: + break + skip(inbuf, f_type) + + +class TBinaryProtocol(TProtocolBase): + """Binary implementation of the Thrift protocol driver.""" + + def __init__(self, trans, + strict_read=True, strict_write=True, + decode_response=True, strict_decode=False): + TProtocolBase.__init__(self, trans) + self.strict_read = strict_read + self.strict_write = strict_write + self.decode_response = decode_response + self.strict_decode = strict_decode + + def skip(self, ttype): + skip(self.trans, ttype) + + def read_message_begin(self): + api, ttype, seqid = read_message_begin( + self.trans, strict=self.strict_read) + return api, ttype, seqid + + def read_message_end(self): + pass + + def write_message_begin(self, name, ttype, seqid): + write_message_begin(self.trans, name, ttype, seqid, + strict=self.strict_write) + + def write_message_end(self): + pass + + def read_struct(self, obj): + return read_struct(self.trans, obj, self.decode_response, + self.strict_decode) + + def write_struct(self, obj): + write_val(self.trans, TType.STRUCT, obj) + + +class TBinaryProtocolFactory(object): + def __init__(self, strict_read=True, strict_write=True, + decode_response=True, strict_decode=False): + self.strict_read = strict_read + self.strict_write = strict_write + self.decode_response = decode_response + self.strict_decode = strict_decode + + def get_protocol(self, trans): + return TBinaryProtocol(trans, + self.strict_read, self.strict_write, + self.decode_response, self.strict_decode) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/protocol/compact.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/protocol/compact.py new file mode 100644 index 0000000000000000000000000000000000000000..8823236ff0a8552735119246056c121197aa28da --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/protocol/compact.py @@ -0,0 +1,591 @@ +# -*- coding: utf-8 -*- + +from __future__ import absolute_import + +import array +import sys +from struct import pack, unpack + +import six + +from ..thrift import TException, TType +from .base import TProtocolBase +from .exc import TProtocolException + +CLEAR = 0 +FIELD_WRITE = 1 +VALUE_WRITE = 2 +CONTAINER_WRITE = 3 +BOOL_WRITE = 4 +FIELD_READ = 5 +CONTAINER_READ = 6 +VALUE_READ = 7 +BOOL_READ = 8 + +BIN_TYPES = (TType.STRING, TType.BINARY) + + +def check_integer_limits(i, bits): + if bits == 8 and (i < -128 or i > 127): + raise TProtocolException(TProtocolException.INVALID_DATA, + "i8 requires -128 <= number <= 127") + elif bits == 16 and (i < -32768 or i > 32767): + raise TProtocolException(TProtocolException.INVALID_DATA, + "i16 requires -32768 <= number <= 32767") + elif bits == 32 and (i < -2147483648 or i > 2147483647): + raise TProtocolException( + TProtocolException.INVALID_DATA, + "i32 requires -2147483648 <= number <= 2147483647") + elif bits == 64 and (i < -9223372036854775808 or i > 9223372036854775807): + raise TProtocolException( + TProtocolException.INVALID_DATA, + "i64 requires -9223372036854775808 <= number <= \ + 9223372036854775807") + + +def make_zig_zag(n, bits): + check_integer_limits(n, bits) + return (n << 1) ^ (n >> (bits - 1)) + + +def from_zig_zag(n): + return (n >> 1) ^ -(n & 1) + + +def write_varint(trans, n): + out = [] + while True: + if n & ~0x7f == 0: + out.append(n) + break + else: + out.append((n & 0xff) | 0x80) + n = n >> 7 + data = array.array('B', out) + + trans.write(data.tobytes()) + + +def read_varint(trans): + result = 0 + shift = 0 + + while True: + x = trans.read(1) + byte = ord(x) + result |= (byte & 0x7f) << shift + if byte >> 7 == 0: + return result + shift += 7 + + +class CompactType(object): + STOP = 0x00 + TRUE = 0x01 + FALSE = 0x02 + BYTE = 0x03 + I16 = 0x04 + I32 = 0x05 + I64 = 0x06 + DOUBLE = 0x07 + BINARY = 0x08 + LIST = 0x09 + SET = 0x0A + MAP = 0x0B + STRUCT = 0x0C + + +CTYPES = { + TType.STOP: CompactType.STOP, + TType.BOOL: CompactType.TRUE, + TType.BYTE: CompactType.BYTE, + TType.I16: CompactType.I16, + TType.I32: CompactType.I32, + TType.I64: CompactType.I64, + TType.DOUBLE: CompactType.DOUBLE, + TType.STRING: CompactType.BINARY, + TType.STRUCT: CompactType.STRUCT, + TType.LIST: CompactType.LIST, + TType.SET: CompactType.SET, + TType.MAP: CompactType.MAP, + TType.BINARY: CompactType.BINARY, +} +TTYPES = dict((v, k) for k, v in CTYPES.items()) +TTYPES[CompactType.FALSE] = TType.BOOL + + +class TCompactProtocol(TProtocolBase): + """Compact implementation of the Thrift protocol driver.""" + PROTOCOL_ID = 0x82 + VERSION = 1 + VERSION_MASK = 0x1f + TYPE_MASK = 0xe0 + TYPE_BITS = 0x07 + TYPE_SHIFT_AMOUNT = 5 + + def __init__(self, trans, decode_response=True, strict_decode=False): + TProtocolBase.__init__(self, trans) + self._last_fid = 0 + self._bool_fid = None + self._bool_value = None + self._structs = [] + self.decode_response = decode_response + self.strict_decode = strict_decode + + def _get_ttype(self, byte): + return TTYPES[byte & 0x0f] + + def _read_size(self): + result = read_varint(self.trans) + if result < 0: + raise TException("Length < 0") + return result + + def read_message_begin(self): + proto_id = self._read_ubyte() + if proto_id != self.PROTOCOL_ID: + raise TProtocolException(TProtocolException.BAD_VERSION, + 'Bad protocol id in the message: %d' + % proto_id) + + ver_type = self._read_ubyte() + type = (ver_type >> self.TYPE_SHIFT_AMOUNT) & self.TYPE_BITS + version = ver_type & self.VERSION_MASK + if version != self.VERSION: + raise TProtocolException(TProtocolException.BAD_VERSION, + 'Bad version: %d (expect %d)' + % (version, self.VERSION)) + seqid = read_varint(self.trans) + name = self._read_string() + return name, type, seqid + + def read_message_end(self): + assert len(self._structs) == 0 + + def _read_field_begin(self): + type = self._read_ubyte() + if type & 0x0f == TType.STOP: + return None, 0, 0 + + delta = type >> 4 + if delta == 0: + fid = from_zig_zag(read_varint(self.trans)) + else: + fid = self._last_fid + delta + self._last_fid = fid + + type = type & 0x0f + if type == CompactType.TRUE: + self._bool_value = True + elif type == CompactType.FALSE: + self._bool_value = False + + return None, self._get_ttype(type), fid + + def _read_field_end(self): + pass + + def _read_struct_begin(self): + self._structs.append(self._last_fid) + self._last_fid = 0 + + def _read_struct_end(self): + self._last_fid = self._structs.pop() + + def _read_map_begin(self): + size = self._read_size() + types = 0 + if size > 0: + types = self._read_ubyte() + vtype = self._get_ttype(types) + ktype = self._get_ttype(types >> 4) + return (ktype, vtype, size) + + def _read_collection_begin(self): + size_type = self._read_ubyte() + size = size_type >> 4 + type = self._get_ttype(size_type) + if size == 15: + size = self._read_size() + return type, size + + def _read_collection_end(self): + pass + + def _read_byte(self): + result, = unpack('!b', self.trans.read(1)) + return result + + def _read_ubyte(self): + result, = unpack('!B', self.trans.read(1)) + return result + + def _read_int(self): + return from_zig_zag(read_varint(self.trans)) + + def _read_double(self): + buff = self.trans.read(8) + val, = unpack(' 2: + b = b.encode() + self.trans.write(b) + + def _write_string(self, s): + if not isinstance(s, bytes): + s = s.encode('utf-8') + self._write_size(len(s)) + self.trans.write(s) + + def write_struct(self, obj): + self._write_struct_begin() + + for field in obj.thrift_spec: + if field is None: + continue + fspec = obj.thrift_spec[field] + if len(fspec) == 3: + ftype, fname, freq = fspec + f_container_spec = None + else: + ftype, fname, f_container_spec, f_req = fspec + val = getattr(obj, fname, None) + if val is None: + continue + + self._write_field_begin(fname, ftype, field) + self._write_val(ftype, val, f_container_spec) + self._write_field_end() + self._write_field_stop() + self._write_struct_end() + + def _write_val(self, ttype, val, spec=None): + + if ttype == TType.BOOL: + self._write_bool(val) + + elif ttype == TType.BYTE: + self._write_byte(val) + + elif ttype == TType.I16: + self._write_i16(val) + + elif ttype == TType.I32: + self._write_i32(val) + + elif ttype == TType.I64: + self._write_i64(val) + + elif ttype == TType.DOUBLE: + self._write_double(val) + + elif ttype == TType.BINARY: + self._write_binary(val) + + elif ttype == TType.STRING: + self._write_string(val) + + elif ttype == TType.LIST or ttype == TType.SET: + if isinstance(spec, tuple): + e_type, t_spec = spec[0], spec[1] + else: + e_type, t_spec = spec, None + + val_len = len(val) + self._write_collection_begin(e_type, val_len) + for e_val in val: + self._write_val(e_type, e_val, t_spec) + self._write_collection_end() + + elif ttype == TType.MAP: + if isinstance(spec[0], int): + k_type = spec[0] + k_spec = None + else: + k_type, k_spec = spec[0] + + if isinstance(spec[1], int): + v_type = spec[1] + v_spec = None + else: + v_type, v_spec = spec[1] + + self._write_map_begin(k_type, v_type, len(val)) + for k in iter(val): + self._write_val(k_type, k, k_spec) + self._write_val(v_type, val[k], v_spec) + self._write_collection_end() + + elif ttype == TType.STRUCT: + self.write_struct(val) + + def skip(self, ttype): + if ttype == TType.STOP: + return + + elif ttype == TType.BOOL: + self._read_bool() + + elif ttype == TType.BYTE: + self._read_byte() + + elif ttype in (TType.I16, TType.I32, TType.I64): + from_zig_zag(read_varint(self.trans)) + + elif ttype == TType.DOUBLE: + self._read_double() + + elif ttype == TType.BINARY: + self._read_binary() + + elif ttype == TType.STRING: + self._read_string() + + elif ttype == TType.STRUCT: + name = self._read_struct_begin() + while True: + (name, ttype, id) = self._read_field_begin() + if ttype == TType.STOP: + break + self.skip(ttype) + self._read_field_end() + self._read_struct_end() + + elif ttype == TType.MAP: + ktype, vtype, size = self._read_map_begin() + for i in range(size): + self.skip(ktype) + self.skip(vtype) + self._read_collection_end() + + elif ttype == TType.SET: + etype, size = self._read_collection_begin() + for i in range(size): + self.skip(etype) + self._read_collection_end() + + elif ttype == TType.LIST: + etype, size = self._read_collection_begin() + for i in range(size): + self.skip(etype) + self._read_collection_end() + + +class TCompactProtocolFactory(object): + def __init__(self, decode_response=True, strict_decode=False): + self.decode_response = decode_response + self.strict_decode = strict_decode + + def get_protocol(self, trans): + return TCompactProtocol(trans, decode_response=self.decode_response, + strict_decode=self.strict_decode) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/protocol/cybin/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/protocol/cybin/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..82a0121943c0df947e4b291deab287deed02a507 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/protocol/cybin/__init__.py @@ -0,0 +1 @@ +from .cybin import * diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/protocol/cybin/cybin.c b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/protocol/cybin/cybin.c new file mode 100644 index 0000000000000000000000000000000000000000..47ee0fad38e260ed39ca66f716d8824f41a72db5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/protocol/cybin/cybin.c @@ -0,0 +1,21855 @@ +/* Generated by Cython 3.2.4 */ + +/* BEGIN: Cython Metadata +{ + "distutils": { + "depends": [ + "thriftpy2/protocol/cybin/endian_port.h" + ], + "include_dirs": [ + "thriftpy2/protocol/cybin" + ], + "name": "thriftpy2.protocol.cybin.cybin", + "sources": [ + "thriftpy2/protocol/cybin/cybin.pyx" + ] + }, + "module_name": "thriftpy2.protocol.cybin.cybin" +} +END: Cython Metadata */ + +#ifndef PY_SSIZE_T_CLEAN +#define PY_SSIZE_T_CLEAN +#endif /* PY_SSIZE_T_CLEAN */ +/* InitLimitedAPI */ +#if defined(Py_LIMITED_API) + #if !defined(CYTHON_LIMITED_API) + #define CYTHON_LIMITED_API 1 + #endif +#elif defined(CYTHON_LIMITED_API) + #ifdef _MSC_VER + #pragma message ("Limited API usage is enabled with 'CYTHON_LIMITED_API' but 'Py_LIMITED_API' does not define a Python target version. Consider setting 'Py_LIMITED_API' instead.") + #else + #warning Limited API usage is enabled with 'CYTHON_LIMITED_API' but 'Py_LIMITED_API' does not define a Python target version. Consider setting 'Py_LIMITED_API' instead. + #endif +#endif + +#include "Python.h" +#ifndef Py_PYTHON_H + #error Python headers needed to compile C extensions, please install development version of Python. +#elif PY_VERSION_HEX < 0x03080000 + #error Cython requires Python 3.8+. +#else +#define __PYX_ABI_VERSION "3_2_4" +#define CYTHON_HEX_VERSION 0x030204F0 +#define CYTHON_FUTURE_DIVISION 1 +/* CModulePreamble */ +#include +#ifndef offsetof + #define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) +#endif +#if !defined(_WIN32) && !defined(WIN32) && !defined(MS_WINDOWS) + #ifndef __stdcall + #define __stdcall + #endif + #ifndef __cdecl + #define __cdecl + #endif + #ifndef __fastcall + #define __fastcall + #endif +#endif +#ifndef DL_IMPORT + #define DL_IMPORT(t) t +#endif +#ifndef DL_EXPORT + #define DL_EXPORT(t) t +#endif +#define __PYX_COMMA , +#ifndef PY_LONG_LONG + #define PY_LONG_LONG LONG_LONG +#endif +#ifndef Py_HUGE_VAL + #define Py_HUGE_VAL HUGE_VAL +#endif +#define __PYX_LIMITED_VERSION_HEX PY_VERSION_HEX +#if defined(GRAALVM_PYTHON) + /* For very preliminary testing purposes. Most variables are set the same as PyPy. + The existence of this section does not imply that anything works or is even tested */ + #define CYTHON_COMPILING_IN_PYPY 0 + #define CYTHON_COMPILING_IN_CPYTHON 0 + #define CYTHON_COMPILING_IN_LIMITED_API 0 + #define CYTHON_COMPILING_IN_GRAAL 1 + #define CYTHON_COMPILING_IN_CPYTHON_FREETHREADING 0 + #undef CYTHON_USE_TYPE_SLOTS + #define CYTHON_USE_TYPE_SLOTS 0 + #undef CYTHON_USE_TYPE_SPECS + #define CYTHON_USE_TYPE_SPECS 0 + #undef CYTHON_USE_PYTYPE_LOOKUP + #define CYTHON_USE_PYTYPE_LOOKUP 0 + #undef CYTHON_USE_PYLIST_INTERNALS + #define CYTHON_USE_PYLIST_INTERNALS 0 + #undef CYTHON_USE_UNICODE_INTERNALS + #define CYTHON_USE_UNICODE_INTERNALS 0 + #undef CYTHON_USE_UNICODE_WRITER + #define CYTHON_USE_UNICODE_WRITER 0 + #undef CYTHON_USE_PYLONG_INTERNALS + #define CYTHON_USE_PYLONG_INTERNALS 0 + #undef CYTHON_AVOID_BORROWED_REFS + #define CYTHON_AVOID_BORROWED_REFS 1 + #undef CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + #define CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS 0 + #undef CYTHON_ASSUME_SAFE_MACROS + #define CYTHON_ASSUME_SAFE_MACROS 0 + #undef CYTHON_ASSUME_SAFE_SIZE + #define CYTHON_ASSUME_SAFE_SIZE 0 + #undef CYTHON_UNPACK_METHODS + #define CYTHON_UNPACK_METHODS 0 + #undef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 0 + #undef CYTHON_FAST_GIL + #define CYTHON_FAST_GIL 0 + #undef CYTHON_METH_FASTCALL + #define CYTHON_METH_FASTCALL 0 + #undef CYTHON_FAST_PYCALL + #define CYTHON_FAST_PYCALL 0 + #ifndef CYTHON_PEP487_INIT_SUBCLASS + #define CYTHON_PEP487_INIT_SUBCLASS 1 + #endif + #undef CYTHON_PEP489_MULTI_PHASE_INIT + #define CYTHON_PEP489_MULTI_PHASE_INIT 1 + #undef CYTHON_USE_MODULE_STATE + #define CYTHON_USE_MODULE_STATE 0 + #undef CYTHON_USE_SYS_MONITORING + #define CYTHON_USE_SYS_MONITORING 0 + #undef CYTHON_USE_TP_FINALIZE + #define CYTHON_USE_TP_FINALIZE 0 + #undef CYTHON_USE_AM_SEND + #define CYTHON_USE_AM_SEND 0 + #undef CYTHON_USE_DICT_VERSIONS + #define CYTHON_USE_DICT_VERSIONS 0 + #undef CYTHON_USE_EXC_INFO_STACK + #define CYTHON_USE_EXC_INFO_STACK 1 + #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC + #define CYTHON_UPDATE_DESCRIPTOR_DOC 0 + #endif + #undef CYTHON_USE_FREELISTS + #define CYTHON_USE_FREELISTS 0 + #undef CYTHON_IMMORTAL_CONSTANTS + #define CYTHON_IMMORTAL_CONSTANTS 0 +#elif defined(PYPY_VERSION) + #define CYTHON_COMPILING_IN_PYPY 1 + #define CYTHON_COMPILING_IN_CPYTHON 0 + #define CYTHON_COMPILING_IN_LIMITED_API 0 + #define CYTHON_COMPILING_IN_GRAAL 0 + #define CYTHON_COMPILING_IN_CPYTHON_FREETHREADING 0 + #undef CYTHON_USE_TYPE_SLOTS + #define CYTHON_USE_TYPE_SLOTS 1 + #ifndef CYTHON_USE_TYPE_SPECS + #define CYTHON_USE_TYPE_SPECS 0 + #endif + #undef CYTHON_USE_PYTYPE_LOOKUP + #define CYTHON_USE_PYTYPE_LOOKUP 0 + #undef CYTHON_USE_PYLIST_INTERNALS + #define CYTHON_USE_PYLIST_INTERNALS 0 + #undef CYTHON_USE_UNICODE_INTERNALS + #define CYTHON_USE_UNICODE_INTERNALS 0 + #undef CYTHON_USE_UNICODE_WRITER + #define CYTHON_USE_UNICODE_WRITER 0 + #undef CYTHON_USE_PYLONG_INTERNALS + #define CYTHON_USE_PYLONG_INTERNALS 0 + #undef CYTHON_AVOID_BORROWED_REFS + #define CYTHON_AVOID_BORROWED_REFS 1 + #undef CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + #define CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS 1 + #undef CYTHON_ASSUME_SAFE_MACROS + #define CYTHON_ASSUME_SAFE_MACROS 0 + #ifndef CYTHON_ASSUME_SAFE_SIZE + #define CYTHON_ASSUME_SAFE_SIZE 1 + #endif + #undef CYTHON_UNPACK_METHODS + #define CYTHON_UNPACK_METHODS 0 + #undef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 0 + #undef CYTHON_FAST_GIL + #define CYTHON_FAST_GIL 0 + #undef CYTHON_METH_FASTCALL + #define CYTHON_METH_FASTCALL 0 + #undef CYTHON_FAST_PYCALL + #define CYTHON_FAST_PYCALL 0 + #ifndef CYTHON_PEP487_INIT_SUBCLASS + #define CYTHON_PEP487_INIT_SUBCLASS 1 + #endif + #if PY_VERSION_HEX < 0x03090000 + #undef CYTHON_PEP489_MULTI_PHASE_INIT + #define CYTHON_PEP489_MULTI_PHASE_INIT 0 + #elif !defined(CYTHON_PEP489_MULTI_PHASE_INIT) + #define CYTHON_PEP489_MULTI_PHASE_INIT 1 + #endif + #undef CYTHON_USE_MODULE_STATE + #define CYTHON_USE_MODULE_STATE 0 + #undef CYTHON_USE_SYS_MONITORING + #define CYTHON_USE_SYS_MONITORING 0 + #ifndef CYTHON_USE_TP_FINALIZE + #define CYTHON_USE_TP_FINALIZE (PYPY_VERSION_NUM >= 0x07030C00) + #endif + #undef CYTHON_USE_AM_SEND + #define CYTHON_USE_AM_SEND 0 + #undef CYTHON_USE_DICT_VERSIONS + #define CYTHON_USE_DICT_VERSIONS 0 + #undef CYTHON_USE_EXC_INFO_STACK + #define CYTHON_USE_EXC_INFO_STACK 0 + #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC + #define CYTHON_UPDATE_DESCRIPTOR_DOC (PYPY_VERSION_NUM >= 0x07031100) + #endif + #undef CYTHON_USE_FREELISTS + #define CYTHON_USE_FREELISTS 0 + #undef CYTHON_IMMORTAL_CONSTANTS + #define CYTHON_IMMORTAL_CONSTANTS 0 +#elif defined(CYTHON_LIMITED_API) + #ifdef Py_LIMITED_API + #undef __PYX_LIMITED_VERSION_HEX + #define __PYX_LIMITED_VERSION_HEX Py_LIMITED_API + #endif + #define CYTHON_COMPILING_IN_PYPY 0 + #define CYTHON_COMPILING_IN_CPYTHON 0 + #define CYTHON_COMPILING_IN_LIMITED_API 1 + #define CYTHON_COMPILING_IN_GRAAL 0 + #define CYTHON_COMPILING_IN_CPYTHON_FREETHREADING 0 + #undef CYTHON_USE_TYPE_SLOTS + #define CYTHON_USE_TYPE_SLOTS 0 + #undef CYTHON_USE_TYPE_SPECS + #define CYTHON_USE_TYPE_SPECS 1 + #undef CYTHON_USE_PYTYPE_LOOKUP + #define CYTHON_USE_PYTYPE_LOOKUP 0 + #undef CYTHON_USE_PYLIST_INTERNALS + #define CYTHON_USE_PYLIST_INTERNALS 0 + #undef CYTHON_USE_UNICODE_INTERNALS + #define CYTHON_USE_UNICODE_INTERNALS 0 + #ifndef CYTHON_USE_UNICODE_WRITER + #define CYTHON_USE_UNICODE_WRITER 0 + #endif + #undef CYTHON_USE_PYLONG_INTERNALS + #define CYTHON_USE_PYLONG_INTERNALS 0 + #ifndef CYTHON_AVOID_BORROWED_REFS + #define CYTHON_AVOID_BORROWED_REFS 0 + #endif + #ifndef CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + #define CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS 0 + #endif + #undef CYTHON_ASSUME_SAFE_MACROS + #define CYTHON_ASSUME_SAFE_MACROS 0 + #undef CYTHON_ASSUME_SAFE_SIZE + #define CYTHON_ASSUME_SAFE_SIZE 0 + #undef CYTHON_UNPACK_METHODS + #define CYTHON_UNPACK_METHODS 0 + #undef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 0 + #undef CYTHON_FAST_GIL + #define CYTHON_FAST_GIL 0 + #undef CYTHON_METH_FASTCALL + #define CYTHON_METH_FASTCALL (__PYX_LIMITED_VERSION_HEX >= 0x030C0000) + #undef CYTHON_FAST_PYCALL + #define CYTHON_FAST_PYCALL 0 + #ifndef CYTHON_PEP487_INIT_SUBCLASS + #define CYTHON_PEP487_INIT_SUBCLASS 1 + #endif + #ifndef CYTHON_PEP489_MULTI_PHASE_INIT + #define CYTHON_PEP489_MULTI_PHASE_INIT 1 + #endif + #ifndef CYTHON_USE_MODULE_STATE + #define CYTHON_USE_MODULE_STATE 0 + #endif + #undef CYTHON_USE_SYS_MONITORING + #define CYTHON_USE_SYS_MONITORING 0 + #ifndef CYTHON_USE_TP_FINALIZE + #define CYTHON_USE_TP_FINALIZE 0 + #endif + #ifndef CYTHON_USE_AM_SEND + #define CYTHON_USE_AM_SEND (__PYX_LIMITED_VERSION_HEX >= 0x030A0000) + #endif + #undef CYTHON_USE_DICT_VERSIONS + #define CYTHON_USE_DICT_VERSIONS 0 + #undef CYTHON_USE_EXC_INFO_STACK + #define CYTHON_USE_EXC_INFO_STACK 0 + #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC + #define CYTHON_UPDATE_DESCRIPTOR_DOC 0 + #endif + #ifndef CYTHON_USE_FREELISTS + #define CYTHON_USE_FREELISTS 1 + #endif + #undef CYTHON_IMMORTAL_CONSTANTS + #define CYTHON_IMMORTAL_CONSTANTS 0 +#else + #define CYTHON_COMPILING_IN_PYPY 0 + #define CYTHON_COMPILING_IN_CPYTHON 1 + #define CYTHON_COMPILING_IN_LIMITED_API 0 + #define CYTHON_COMPILING_IN_GRAAL 0 + #ifdef Py_GIL_DISABLED + #define CYTHON_COMPILING_IN_CPYTHON_FREETHREADING 1 + #else + #define CYTHON_COMPILING_IN_CPYTHON_FREETHREADING 0 + #endif + #if PY_VERSION_HEX < 0x030A0000 + #undef CYTHON_USE_TYPE_SLOTS + #define CYTHON_USE_TYPE_SLOTS 1 + #elif !defined(CYTHON_USE_TYPE_SLOTS) + #define CYTHON_USE_TYPE_SLOTS 1 + #endif + #ifndef CYTHON_USE_TYPE_SPECS + #define CYTHON_USE_TYPE_SPECS 0 + #endif + #ifndef CYTHON_USE_PYTYPE_LOOKUP + #define CYTHON_USE_PYTYPE_LOOKUP 1 + #endif + #ifndef CYTHON_USE_PYLONG_INTERNALS + #define CYTHON_USE_PYLONG_INTERNALS 1 + #endif + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + #undef CYTHON_USE_PYLIST_INTERNALS + #define CYTHON_USE_PYLIST_INTERNALS 0 + #elif !defined(CYTHON_USE_PYLIST_INTERNALS) + #define CYTHON_USE_PYLIST_INTERNALS 1 + #endif + #ifndef CYTHON_USE_UNICODE_INTERNALS + #define CYTHON_USE_UNICODE_INTERNALS 1 + #endif + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING || PY_VERSION_HEX >= 0x030B00A2 + #undef CYTHON_USE_UNICODE_WRITER + #define CYTHON_USE_UNICODE_WRITER 0 + #elif !defined(CYTHON_USE_UNICODE_WRITER) + #define CYTHON_USE_UNICODE_WRITER 1 + #endif + #ifndef CYTHON_AVOID_BORROWED_REFS + #define CYTHON_AVOID_BORROWED_REFS 0 + #endif + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + #undef CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + #define CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS 1 + #elif !defined(CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS) + #define CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS 0 + #endif + #ifndef CYTHON_ASSUME_SAFE_MACROS + #define CYTHON_ASSUME_SAFE_MACROS 1 + #endif + #ifndef CYTHON_ASSUME_SAFE_SIZE + #define CYTHON_ASSUME_SAFE_SIZE 1 + #endif + #ifndef CYTHON_UNPACK_METHODS + #define CYTHON_UNPACK_METHODS 1 + #endif + #ifndef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 1 + #endif + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + #undef CYTHON_FAST_GIL + #define CYTHON_FAST_GIL 0 + #elif !defined(CYTHON_FAST_GIL) + #define CYTHON_FAST_GIL (PY_VERSION_HEX < 0x030C00A6) + #endif + #ifndef CYTHON_METH_FASTCALL + #define CYTHON_METH_FASTCALL 1 + #endif + #ifndef CYTHON_FAST_PYCALL + #define CYTHON_FAST_PYCALL 1 + #endif + #ifndef CYTHON_PEP487_INIT_SUBCLASS + #define CYTHON_PEP487_INIT_SUBCLASS 1 + #endif + #ifndef CYTHON_PEP489_MULTI_PHASE_INIT + #define CYTHON_PEP489_MULTI_PHASE_INIT 1 + #endif + #ifndef CYTHON_USE_MODULE_STATE + #define CYTHON_USE_MODULE_STATE 0 + #endif + #ifndef CYTHON_USE_SYS_MONITORING + #define CYTHON_USE_SYS_MONITORING (PY_VERSION_HEX >= 0x030d00B1) + #endif + #ifndef CYTHON_USE_TP_FINALIZE + #define CYTHON_USE_TP_FINALIZE 1 + #endif + #ifndef CYTHON_USE_AM_SEND + #define CYTHON_USE_AM_SEND 1 + #endif + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + #undef CYTHON_USE_DICT_VERSIONS + #define CYTHON_USE_DICT_VERSIONS 0 + #elif !defined(CYTHON_USE_DICT_VERSIONS) + #define CYTHON_USE_DICT_VERSIONS (PY_VERSION_HEX < 0x030C00A5 && !CYTHON_USE_MODULE_STATE) + #endif + #ifndef CYTHON_USE_EXC_INFO_STACK + #define CYTHON_USE_EXC_INFO_STACK 1 + #endif + #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC + #define CYTHON_UPDATE_DESCRIPTOR_DOC 1 + #endif + #ifndef CYTHON_USE_FREELISTS + #define CYTHON_USE_FREELISTS (!CYTHON_COMPILING_IN_CPYTHON_FREETHREADING) + #endif + #if defined(CYTHON_IMMORTAL_CONSTANTS) && PY_VERSION_HEX < 0x030C0000 + #undef CYTHON_IMMORTAL_CONSTANTS + #define CYTHON_IMMORTAL_CONSTANTS 0 // definitely won't work + #elif !defined(CYTHON_IMMORTAL_CONSTANTS) + #define CYTHON_IMMORTAL_CONSTANTS (PY_VERSION_HEX >= 0x030C0000 && !CYTHON_USE_MODULE_STATE && CYTHON_COMPILING_IN_CPYTHON_FREETHREADING) + #endif +#endif +#ifndef CYTHON_COMPRESS_STRINGS + #define CYTHON_COMPRESS_STRINGS 1 +#endif +#ifndef CYTHON_FAST_PYCCALL +#define CYTHON_FAST_PYCCALL CYTHON_FAST_PYCALL +#endif +#ifndef CYTHON_VECTORCALL +#if CYTHON_COMPILING_IN_LIMITED_API +#define CYTHON_VECTORCALL (__PYX_LIMITED_VERSION_HEX >= 0x030C0000) +#else +#define CYTHON_VECTORCALL (CYTHON_FAST_PYCCALL) +#endif +#endif +#if CYTHON_USE_PYLONG_INTERNALS + #undef SHIFT + #undef BASE + #undef MASK + #ifdef SIZEOF_VOID_P + enum { __pyx_check_sizeof_voidp = 1 / (int)(SIZEOF_VOID_P == sizeof(void*)) }; + #endif +#endif +#ifndef __has_attribute + #define __has_attribute(x) 0 +#endif +#ifndef __has_cpp_attribute + #define __has_cpp_attribute(x) 0 +#endif +#ifndef CYTHON_RESTRICT + #if defined(__GNUC__) + #define CYTHON_RESTRICT __restrict__ + #elif defined(_MSC_VER) && _MSC_VER >= 1400 + #define CYTHON_RESTRICT __restrict + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_RESTRICT restrict + #else + #define CYTHON_RESTRICT + #endif +#endif +#ifndef CYTHON_UNUSED + #if defined(__cplusplus) + /* for clang __has_cpp_attribute(maybe_unused) is true even before C++17 + * but leads to warnings with -pedantic, since it is a C++17 feature */ + #if ((defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) || __cplusplus >= 201703L) + #if __has_cpp_attribute(maybe_unused) + #define CYTHON_UNUSED [[maybe_unused]] + #endif + #endif + #endif +#endif +#ifndef CYTHON_UNUSED +# if defined(__GNUC__) +# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) +# define CYTHON_UNUSED __attribute__ ((__unused__)) +# else +# define CYTHON_UNUSED +# endif +# elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) +# define CYTHON_UNUSED __attribute__ ((__unused__)) +# else +# define CYTHON_UNUSED +# endif +#endif +#ifndef CYTHON_UNUSED_VAR +# if defined(__cplusplus) + template void CYTHON_UNUSED_VAR( const T& ) { } +# else +# define CYTHON_UNUSED_VAR(x) (void)(x) +# endif +#endif +#ifndef CYTHON_MAYBE_UNUSED_VAR + #define CYTHON_MAYBE_UNUSED_VAR(x) CYTHON_UNUSED_VAR(x) +#endif +#ifndef CYTHON_NCP_UNUSED +# if CYTHON_COMPILING_IN_CPYTHON && !CYTHON_COMPILING_IN_CPYTHON_FREETHREADING +# define CYTHON_NCP_UNUSED +# else +# define CYTHON_NCP_UNUSED CYTHON_UNUSED +# endif +#endif +#ifndef CYTHON_USE_CPP_STD_MOVE + #if defined(__cplusplus) && (\ + __cplusplus >= 201103L || (defined(_MSC_VER) && _MSC_VER >= 1600)) + #define CYTHON_USE_CPP_STD_MOVE 1 + #else + #define CYTHON_USE_CPP_STD_MOVE 0 + #endif +#endif +#define __Pyx_void_to_None(void_result) ((void)(void_result), Py_INCREF(Py_None), Py_None) +#include +typedef uintptr_t __pyx_uintptr_t; +#ifndef CYTHON_FALLTHROUGH + #if defined(__cplusplus) + /* for clang __has_cpp_attribute(fallthrough) is true even before C++17 + * but leads to warnings with -pedantic, since it is a C++17 feature */ + #if ((defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) || __cplusplus >= 201703L) + #if __has_cpp_attribute(fallthrough) + #define CYTHON_FALLTHROUGH [[fallthrough]] + #endif + #endif + #ifndef CYTHON_FALLTHROUGH + #if __has_cpp_attribute(clang::fallthrough) + #define CYTHON_FALLTHROUGH [[clang::fallthrough]] + #elif __has_cpp_attribute(gnu::fallthrough) + #define CYTHON_FALLTHROUGH [[gnu::fallthrough]] + #endif + #endif + #endif + #ifndef CYTHON_FALLTHROUGH + #if __has_attribute(fallthrough) + #define CYTHON_FALLTHROUGH __attribute__((fallthrough)) + #else + #define CYTHON_FALLTHROUGH + #endif + #endif + #if defined(__clang__) && defined(__apple_build_version__) + #if __apple_build_version__ < 7000000 + #undef CYTHON_FALLTHROUGH + #define CYTHON_FALLTHROUGH + #endif + #endif +#endif +#ifndef Py_UNREACHABLE + #define Py_UNREACHABLE() assert(0); abort() +#endif +#ifdef __cplusplus + template + struct __PYX_IS_UNSIGNED_IMPL {static const bool value = T(0) < T(-1);}; + #define __PYX_IS_UNSIGNED(type) (__PYX_IS_UNSIGNED_IMPL::value) +#else + #define __PYX_IS_UNSIGNED(type) (((type)-1) > 0) +#endif +#if CYTHON_COMPILING_IN_PYPY == 1 + #define __PYX_NEED_TP_PRINT_SLOT (PY_VERSION_HEX < 0x030A0000) +#else + #define __PYX_NEED_TP_PRINT_SLOT (PY_VERSION_HEX < 0x03090000) +#endif +#define __PYX_REINTERPRET_FUNCION(func_pointer, other_pointer) ((func_pointer)(void(*)(void))(other_pointer)) + +/* CInitCode */ +#ifndef CYTHON_INLINE + #if defined(__clang__) + #define CYTHON_INLINE __inline__ __attribute__ ((__unused__)) + #elif defined(__GNUC__) + #define CYTHON_INLINE __inline__ + #elif defined(_MSC_VER) + #define CYTHON_INLINE __inline + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_INLINE inline + #else + #define CYTHON_INLINE + #endif +#endif + +/* PythonCompatibility */ +#define __PYX_BUILD_PY_SSIZE_T "n" +#define CYTHON_FORMAT_SSIZE_T "z" +#define __Pyx_BUILTIN_MODULE_NAME "builtins" +#define __Pyx_DefaultClassType PyType_Type +#if CYTHON_COMPILING_IN_LIMITED_API + #ifndef CO_OPTIMIZED + static int CO_OPTIMIZED; + #endif + #ifndef CO_NEWLOCALS + static int CO_NEWLOCALS; + #endif + #ifndef CO_VARARGS + static int CO_VARARGS; + #endif + #ifndef CO_VARKEYWORDS + static int CO_VARKEYWORDS; + #endif + #ifndef CO_ASYNC_GENERATOR + static int CO_ASYNC_GENERATOR; + #endif + #ifndef CO_GENERATOR + static int CO_GENERATOR; + #endif + #ifndef CO_COROUTINE + static int CO_COROUTINE; + #endif +#else + #ifndef CO_COROUTINE + #define CO_COROUTINE 0x80 + #endif + #ifndef CO_ASYNC_GENERATOR + #define CO_ASYNC_GENERATOR 0x200 + #endif +#endif +static int __Pyx_init_co_variables(void); +#if PY_VERSION_HEX >= 0x030900A4 || defined(Py_IS_TYPE) + #define __Pyx_IS_TYPE(ob, type) Py_IS_TYPE(ob, type) +#else + #define __Pyx_IS_TYPE(ob, type) (((const PyObject*)ob)->ob_type == (type)) +#endif +#if PY_VERSION_HEX >= 0x030A00B1 || defined(Py_Is) + #define __Pyx_Py_Is(x, y) Py_Is(x, y) +#else + #define __Pyx_Py_Is(x, y) ((x) == (y)) +#endif +#if PY_VERSION_HEX >= 0x030A00B1 || defined(Py_IsNone) + #define __Pyx_Py_IsNone(ob) Py_IsNone(ob) +#else + #define __Pyx_Py_IsNone(ob) __Pyx_Py_Is((ob), Py_None) +#endif +#if PY_VERSION_HEX >= 0x030A00B1 || defined(Py_IsTrue) + #define __Pyx_Py_IsTrue(ob) Py_IsTrue(ob) +#else + #define __Pyx_Py_IsTrue(ob) __Pyx_Py_Is((ob), Py_True) +#endif +#if PY_VERSION_HEX >= 0x030A00B1 || defined(Py_IsFalse) + #define __Pyx_Py_IsFalse(ob) Py_IsFalse(ob) +#else + #define __Pyx_Py_IsFalse(ob) __Pyx_Py_Is((ob), Py_False) +#endif +#define __Pyx_NoneAsNull(obj) (__Pyx_Py_IsNone(obj) ? NULL : (obj)) +#if PY_VERSION_HEX >= 0x030900F0 && !CYTHON_COMPILING_IN_PYPY + #define __Pyx_PyObject_GC_IsFinalized(o) PyObject_GC_IsFinalized(o) +#else + #define __Pyx_PyObject_GC_IsFinalized(o) _PyGC_FINALIZED(o) +#endif +#ifndef Py_TPFLAGS_CHECKTYPES + #define Py_TPFLAGS_CHECKTYPES 0 +#endif +#ifndef Py_TPFLAGS_HAVE_INDEX + #define Py_TPFLAGS_HAVE_INDEX 0 +#endif +#ifndef Py_TPFLAGS_HAVE_NEWBUFFER + #define Py_TPFLAGS_HAVE_NEWBUFFER 0 +#endif +#ifndef Py_TPFLAGS_HAVE_FINALIZE + #define Py_TPFLAGS_HAVE_FINALIZE 0 +#endif +#ifndef Py_TPFLAGS_SEQUENCE + #define Py_TPFLAGS_SEQUENCE 0 +#endif +#ifndef Py_TPFLAGS_MAPPING + #define Py_TPFLAGS_MAPPING 0 +#endif +#ifndef Py_TPFLAGS_IMMUTABLETYPE + #define Py_TPFLAGS_IMMUTABLETYPE (1UL << 8) +#endif +#ifndef Py_TPFLAGS_DISALLOW_INSTANTIATION + #define Py_TPFLAGS_DISALLOW_INSTANTIATION (1UL << 7) +#endif +#ifndef METH_STACKLESS + #define METH_STACKLESS 0 +#endif +#ifndef METH_FASTCALL + #ifndef METH_FASTCALL + #define METH_FASTCALL 0x80 + #endif + typedef PyObject *(*__Pyx_PyCFunctionFast) (PyObject *self, PyObject *const *args, Py_ssize_t nargs); + typedef PyObject *(*__Pyx_PyCFunctionFastWithKeywords) (PyObject *self, PyObject *const *args, + Py_ssize_t nargs, PyObject *kwnames); +#else + #if PY_VERSION_HEX >= 0x030d00A4 + # define __Pyx_PyCFunctionFast PyCFunctionFast + # define __Pyx_PyCFunctionFastWithKeywords PyCFunctionFastWithKeywords + #else + # define __Pyx_PyCFunctionFast _PyCFunctionFast + # define __Pyx_PyCFunctionFastWithKeywords _PyCFunctionFastWithKeywords + #endif +#endif +#if CYTHON_METH_FASTCALL + #define __Pyx_METH_FASTCALL METH_FASTCALL + #define __Pyx_PyCFunction_FastCall __Pyx_PyCFunctionFast + #define __Pyx_PyCFunction_FastCallWithKeywords __Pyx_PyCFunctionFastWithKeywords +#else + #define __Pyx_METH_FASTCALL METH_VARARGS + #define __Pyx_PyCFunction_FastCall PyCFunction + #define __Pyx_PyCFunction_FastCallWithKeywords PyCFunctionWithKeywords +#endif +#if CYTHON_VECTORCALL + #define __pyx_vectorcallfunc vectorcallfunc + #define __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET PY_VECTORCALL_ARGUMENTS_OFFSET + #define __Pyx_PyVectorcall_NARGS(n) PyVectorcall_NARGS((size_t)(n)) +#else + #define __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET 0 + #define __Pyx_PyVectorcall_NARGS(n) ((Py_ssize_t)(n)) +#endif +#if PY_VERSION_HEX >= 0x030900B1 +#define __Pyx_PyCFunction_CheckExact(func) PyCFunction_CheckExact(func) +#else +#define __Pyx_PyCFunction_CheckExact(func) PyCFunction_Check(func) +#endif +#define __Pyx_CyOrPyCFunction_Check(func) PyCFunction_Check(func) +#if CYTHON_COMPILING_IN_CPYTHON +#define __Pyx_CyOrPyCFunction_GET_FUNCTION(func) (((PyCFunctionObject*)(func))->m_ml->ml_meth) +#elif !CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_CyOrPyCFunction_GET_FUNCTION(func) PyCFunction_GET_FUNCTION(func) +#endif +#if CYTHON_COMPILING_IN_CPYTHON +#define __Pyx_CyOrPyCFunction_GET_FLAGS(func) (((PyCFunctionObject*)(func))->m_ml->ml_flags) +static CYTHON_INLINE PyObject* __Pyx_CyOrPyCFunction_GET_SELF(PyObject *func) { + return (__Pyx_CyOrPyCFunction_GET_FLAGS(func) & METH_STATIC) ? NULL : ((PyCFunctionObject*)func)->m_self; +} +#endif +static CYTHON_INLINE int __Pyx__IsSameCFunction(PyObject *func, void (*cfunc)(void)) { +#if CYTHON_COMPILING_IN_LIMITED_API + return PyCFunction_Check(func) && PyCFunction_GetFunction(func) == (PyCFunction) cfunc; +#else + return PyCFunction_Check(func) && PyCFunction_GET_FUNCTION(func) == (PyCFunction) cfunc; +#endif +} +#define __Pyx_IsSameCFunction(func, cfunc) __Pyx__IsSameCFunction(func, cfunc) +#if PY_VERSION_HEX < 0x03090000 || (CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000) + #define __Pyx_PyType_FromModuleAndSpec(m, s, b) ((void)m, PyType_FromSpecWithBases(s, b)) + typedef PyObject *(*__Pyx_PyCMethod)(PyObject *, PyTypeObject *, PyObject *const *, size_t, PyObject *); +#else + #define __Pyx_PyType_FromModuleAndSpec(m, s, b) PyType_FromModuleAndSpec(m, s, b) + #define __Pyx_PyCMethod PyCMethod +#endif +#ifndef METH_METHOD + #define METH_METHOD 0x200 +#endif +#if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Malloc) + #define PyObject_Malloc(s) PyMem_Malloc(s) + #define PyObject_Free(p) PyMem_Free(p) + #define PyObject_Realloc(p) PyMem_Realloc(p) +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + #define __Pyx_PyFrame_SetLineNumber(frame, lineno) +#elif CYTHON_COMPILING_IN_GRAAL && defined(GRAALPY_VERSION_NUM) && GRAALPY_VERSION_NUM > 0x19000000 + #define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0) + #define __Pyx_PyFrame_SetLineNumber(frame, lineno) GraalPyFrame_SetLineNumber((frame), (lineno)) +#elif CYTHON_COMPILING_IN_GRAAL + #define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0) + #define __Pyx_PyFrame_SetLineNumber(frame, lineno) _PyFrame_SetLineNumber((frame), (lineno)) +#else + #define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0) + #define __Pyx_PyFrame_SetLineNumber(frame, lineno) (frame)->f_lineno = (lineno) +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + #define __Pyx_PyThreadState_Current PyThreadState_Get() +#elif !CYTHON_FAST_THREAD_STATE + #define __Pyx_PyThreadState_Current PyThreadState_GET() +#elif PY_VERSION_HEX >= 0x030d00A1 + #define __Pyx_PyThreadState_Current PyThreadState_GetUnchecked() +#else + #define __Pyx_PyThreadState_Current _PyThreadState_UncheckedGet() +#endif +#if CYTHON_USE_MODULE_STATE +static CYTHON_INLINE void *__Pyx__PyModule_GetState(PyObject *op) +{ + void *result; + result = PyModule_GetState(op); + if (!result) + Py_FatalError("Couldn't find the module state"); + return result; +} +#define __Pyx_PyModule_GetState(o) (__pyx_mstatetype *)__Pyx__PyModule_GetState(o) +#else +#define __Pyx_PyModule_GetState(op) ((void)op,__pyx_mstate_global) +#endif +#define __Pyx_PyObject_GetSlot(obj, name, func_ctype) __Pyx_PyType_GetSlot(Py_TYPE((PyObject *) obj), name, func_ctype) +#define __Pyx_PyObject_TryGetSlot(obj, name, func_ctype) __Pyx_PyType_TryGetSlot(Py_TYPE(obj), name, func_ctype) +#define __Pyx_PyObject_GetSubSlot(obj, sub, name, func_ctype) __Pyx_PyType_GetSubSlot(Py_TYPE(obj), sub, name, func_ctype) +#define __Pyx_PyObject_TryGetSubSlot(obj, sub, name, func_ctype) __Pyx_PyType_TryGetSubSlot(Py_TYPE(obj), sub, name, func_ctype) +#if CYTHON_USE_TYPE_SLOTS + #define __Pyx_PyType_GetSlot(type, name, func_ctype) ((type)->name) + #define __Pyx_PyType_TryGetSlot(type, name, func_ctype) __Pyx_PyType_GetSlot(type, name, func_ctype) + #define __Pyx_PyType_GetSubSlot(type, sub, name, func_ctype) (((type)->sub) ? ((type)->sub->name) : NULL) + #define __Pyx_PyType_TryGetSubSlot(type, sub, name, func_ctype) __Pyx_PyType_GetSubSlot(type, sub, name, func_ctype) +#else + #define __Pyx_PyType_GetSlot(type, name, func_ctype) ((func_ctype) PyType_GetSlot((type), Py_##name)) + #define __Pyx_PyType_TryGetSlot(type, name, func_ctype)\ + ((__PYX_LIMITED_VERSION_HEX >= 0x030A0000 ||\ + (PyType_GetFlags(type) & Py_TPFLAGS_HEAPTYPE) || __Pyx_get_runtime_version() >= 0x030A0000) ?\ + __Pyx_PyType_GetSlot(type, name, func_ctype) : NULL) + #define __Pyx_PyType_GetSubSlot(obj, sub, name, func_ctype) __Pyx_PyType_GetSlot(obj, name, func_ctype) + #define __Pyx_PyType_TryGetSubSlot(obj, sub, name, func_ctype) __Pyx_PyType_TryGetSlot(obj, name, func_ctype) +#endif +#if CYTHON_COMPILING_IN_CPYTHON || defined(_PyDict_NewPresized) +#define __Pyx_PyDict_NewPresized(n) ((n <= 8) ? PyDict_New() : _PyDict_NewPresized(n)) +#else +#define __Pyx_PyDict_NewPresized(n) PyDict_New() +#endif +#define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) +#define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) +#if CYTHON_COMPILING_IN_CPYTHON && CYTHON_USE_UNICODE_INTERNALS +#define __Pyx_PyDict_GetItemStrWithError(dict, name) _PyDict_GetItem_KnownHash(dict, name, ((PyASCIIObject *) name)->hash) +static CYTHON_INLINE PyObject * __Pyx_PyDict_GetItemStr(PyObject *dict, PyObject *name) { + PyObject *res = __Pyx_PyDict_GetItemStrWithError(dict, name); + if (res == NULL) PyErr_Clear(); + return res; +} +#elif !CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07020000 +#define __Pyx_PyDict_GetItemStrWithError PyDict_GetItemWithError +#define __Pyx_PyDict_GetItemStr PyDict_GetItem +#else +static CYTHON_INLINE PyObject * __Pyx_PyDict_GetItemStrWithError(PyObject *dict, PyObject *name) { +#if CYTHON_COMPILING_IN_PYPY + return PyDict_GetItem(dict, name); +#else + PyDictEntry *ep; + PyDictObject *mp = (PyDictObject*) dict; + long hash = ((PyStringObject *) name)->ob_shash; + assert(hash != -1); + ep = (mp->ma_lookup)(mp, name, hash); + if (ep == NULL) { + return NULL; + } + return ep->me_value; +#endif +} +#define __Pyx_PyDict_GetItemStr PyDict_GetItem +#endif +#if CYTHON_USE_TYPE_SLOTS + #define __Pyx_PyType_GetFlags(tp) (((PyTypeObject *)tp)->tp_flags) + #define __Pyx_PyType_HasFeature(type, feature) ((__Pyx_PyType_GetFlags(type) & (feature)) != 0) +#else + #define __Pyx_PyType_GetFlags(tp) (PyType_GetFlags((PyTypeObject *)tp)) + #define __Pyx_PyType_HasFeature(type, feature) PyType_HasFeature(type, feature) +#endif +#define __Pyx_PyObject_GetIterNextFunc(iterator) __Pyx_PyObject_GetSlot(iterator, tp_iternext, iternextfunc) +#if CYTHON_USE_TYPE_SPECS +#define __Pyx_PyHeapTypeObject_GC_Del(obj) {\ + PyTypeObject *type = Py_TYPE((PyObject*)obj);\ + assert(__Pyx_PyType_HasFeature(type, Py_TPFLAGS_HEAPTYPE));\ + PyObject_GC_Del(obj);\ + Py_DECREF(type);\ +} +#else +#define __Pyx_PyHeapTypeObject_GC_Del(obj) PyObject_GC_Del(obj) +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + #define __Pyx_PyUnicode_READY(op) (0) + #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_ReadChar(u, i) + #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) ((void)u, 1114111U) + #define __Pyx_PyUnicode_KIND(u) ((void)u, (0)) + #define __Pyx_PyUnicode_DATA(u) ((void*)u) + #define __Pyx_PyUnicode_READ(k, d, i) ((void)k, PyUnicode_ReadChar((PyObject*)(d), i)) + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GetLength(u)) +#else + #if PY_VERSION_HEX >= 0x030C0000 + #define __Pyx_PyUnicode_READY(op) (0) + #else + #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ?\ + 0 : _PyUnicode_Ready((PyObject *)(op))) + #endif + #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) + #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) PyUnicode_MAX_CHAR_VALUE(u) + #define __Pyx_PyUnicode_KIND(u) ((int)PyUnicode_KIND(u)) + #define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u) + #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) + #define __Pyx_PyUnicode_WRITE(k, d, i, ch) PyUnicode_WRITE(k, d, i, (Py_UCS4) ch) + #if PY_VERSION_HEX >= 0x030C0000 + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_LENGTH(u)) + #else + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x03090000 + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : ((PyCompactUnicodeObject *)(u))->wstr_length)) + #else + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : PyUnicode_GET_SIZE(u))) + #endif + #endif +#endif +#if CYTHON_COMPILING_IN_PYPY + #define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b) +#else + #define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ?\ + PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b)) +#endif +#if CYTHON_COMPILING_IN_PYPY + #if !defined(PyUnicode_DecodeUnicodeEscape) + #define PyUnicode_DecodeUnicodeEscape(s, size, errors) PyUnicode_Decode(s, size, "unicode_escape", errors) + #endif + #if !defined(PyUnicode_Contains) + #define PyUnicode_Contains(u, s) PySequence_Contains(u, s) + #endif + #if !defined(PyByteArray_Check) + #define PyByteArray_Check(obj) PyObject_TypeCheck(obj, &PyByteArray_Type) + #endif + #if !defined(PyObject_Format) + #define PyObject_Format(obj, fmt) PyObject_CallMethod(obj, "__format__", "O", fmt) + #endif +#endif +#define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None || (PyUnicode_Check(b) && !PyUnicode_CheckExact(b)))) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + #define __Pyx_PySequence_ListKeepNew(obj)\ + (likely(PyList_CheckExact(obj) && PyUnstable_Object_IsUniquelyReferenced(obj)) ? __Pyx_NewRef(obj) : PySequence_List(obj)) +#elif CYTHON_COMPILING_IN_CPYTHON + #define __Pyx_PySequence_ListKeepNew(obj)\ + (likely(PyList_CheckExact(obj) && Py_REFCNT(obj) == 1) ? __Pyx_NewRef(obj) : PySequence_List(obj)) +#else + #define __Pyx_PySequence_ListKeepNew(obj) PySequence_List(obj) +#endif +#ifndef PySet_CheckExact + #define PySet_CheckExact(obj) __Pyx_IS_TYPE(obj, &PySet_Type) +#endif +#if PY_VERSION_HEX >= 0x030900A4 + #define __Pyx_SET_REFCNT(obj, refcnt) Py_SET_REFCNT(obj, refcnt) + #define __Pyx_SET_SIZE(obj, size) Py_SET_SIZE(obj, size) +#else + #define __Pyx_SET_REFCNT(obj, refcnt) Py_REFCNT(obj) = (refcnt) + #define __Pyx_SET_SIZE(obj, size) Py_SIZE(obj) = (size) +#endif +enum __Pyx_ReferenceSharing { + __Pyx_ReferenceSharing_DefinitelyUnique, // We created it so we know it's unshared - no need to check + __Pyx_ReferenceSharing_OwnStrongReference, + __Pyx_ReferenceSharing_FunctionArgument, + __Pyx_ReferenceSharing_SharedReference, // Never trust it to be unshared because it's a global or similar +}; +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING && PY_VERSION_HEX >= 0x030E0000 +#define __Pyx_IS_UNIQUELY_REFERENCED(o, sharing)\ + (sharing == __Pyx_ReferenceSharing_DefinitelyUnique ? 1 :\ + (sharing == __Pyx_ReferenceSharing_FunctionArgument ? PyUnstable_Object_IsUniqueReferencedTemporary(o) :\ + (sharing == __Pyx_ReferenceSharing_OwnStrongReference ? PyUnstable_Object_IsUniquelyReferenced(o) : 0))) +#elif (CYTHON_COMPILING_IN_CPYTHON && !CYTHON_COMPILING_IN_CPYTHON_FREETHREADING) || CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_IS_UNIQUELY_REFERENCED(o, sharing) (((void)sharing), Py_REFCNT(o) == 1) +#else +#define __Pyx_IS_UNIQUELY_REFERENCED(o, sharing) (((void)o), ((void)sharing), 0) +#endif +#if CYTHON_AVOID_BORROWED_REFS || CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + #if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + #define __Pyx_PyList_GetItemRef(o, i) PyList_GetItemRef(o, i) + #elif CYTHON_COMPILING_IN_LIMITED_API || !CYTHON_ASSUME_SAFE_MACROS + #define __Pyx_PyList_GetItemRef(o, i) (likely((i) >= 0) ? PySequence_GetItem(o, i) : (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL)) + #else + #define __Pyx_PyList_GetItemRef(o, i) PySequence_ITEM(o, i) + #endif +#elif CYTHON_COMPILING_IN_LIMITED_API || !CYTHON_ASSUME_SAFE_MACROS + #if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + #define __Pyx_PyList_GetItemRef(o, i) PyList_GetItemRef(o, i) + #else + #define __Pyx_PyList_GetItemRef(o, i) __Pyx_XNewRef(PyList_GetItem(o, i)) + #endif +#else + #define __Pyx_PyList_GetItemRef(o, i) __Pyx_NewRef(PyList_GET_ITEM(o, i)) +#endif +#if CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS && !CYTHON_COMPILING_IN_LIMITED_API && CYTHON_ASSUME_SAFE_MACROS + #define __Pyx_PyList_GetItemRefFast(o, i, unsafe_shared) (__Pyx_IS_UNIQUELY_REFERENCED(o, unsafe_shared) ?\ + __Pyx_NewRef(PyList_GET_ITEM(o, i)) : __Pyx_PyList_GetItemRef(o, i)) +#else + #define __Pyx_PyList_GetItemRefFast(o, i, unsafe_shared) __Pyx_PyList_GetItemRef(o, i) +#endif +#if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 +#define __Pyx_PyDict_GetItemRef(dict, key, result) PyDict_GetItemRef(dict, key, result) +#elif CYTHON_AVOID_BORROWED_REFS || CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS +static CYTHON_INLINE int __Pyx_PyDict_GetItemRef(PyObject *dict, PyObject *key, PyObject **result) { + *result = PyObject_GetItem(dict, key); + if (*result == NULL) { + if (PyErr_ExceptionMatches(PyExc_KeyError)) { + PyErr_Clear(); + return 0; + } + return -1; + } + return 1; +} +#else +static CYTHON_INLINE int __Pyx_PyDict_GetItemRef(PyObject *dict, PyObject *key, PyObject **result) { + *result = PyDict_GetItemWithError(dict, key); + if (*result == NULL) { + return PyErr_Occurred() ? -1 : 0; + } + Py_INCREF(*result); + return 1; +} +#endif +#if defined(CYTHON_DEBUG_VISIT_CONST) && CYTHON_DEBUG_VISIT_CONST + #define __Pyx_VISIT_CONST(obj) Py_VISIT(obj) +#else + #define __Pyx_VISIT_CONST(obj) +#endif +#if CYTHON_ASSUME_SAFE_MACROS + #define __Pyx_PySequence_ITEM(o, i) PySequence_ITEM(o, i) + #define __Pyx_PySequence_SIZE(seq) Py_SIZE(seq) + #define __Pyx_PyTuple_SET_ITEM(o, i, v) (PyTuple_SET_ITEM(o, i, v), (0)) + #define __Pyx_PyTuple_GET_ITEM(o, i) PyTuple_GET_ITEM(o, i) + #define __Pyx_PyList_SET_ITEM(o, i, v) (PyList_SET_ITEM(o, i, v), (0)) + #define __Pyx_PyList_GET_ITEM(o, i) PyList_GET_ITEM(o, i) +#else + #define __Pyx_PySequence_ITEM(o, i) PySequence_GetItem(o, i) + #define __Pyx_PySequence_SIZE(seq) PySequence_Size(seq) + #define __Pyx_PyTuple_SET_ITEM(o, i, v) PyTuple_SetItem(o, i, v) + #define __Pyx_PyTuple_GET_ITEM(o, i) PyTuple_GetItem(o, i) + #define __Pyx_PyList_SET_ITEM(o, i, v) PyList_SetItem(o, i, v) + #define __Pyx_PyList_GET_ITEM(o, i) PyList_GetItem(o, i) +#endif +#if CYTHON_ASSUME_SAFE_SIZE + #define __Pyx_PyTuple_GET_SIZE(o) PyTuple_GET_SIZE(o) + #define __Pyx_PyList_GET_SIZE(o) PyList_GET_SIZE(o) + #define __Pyx_PySet_GET_SIZE(o) PySet_GET_SIZE(o) + #define __Pyx_PyBytes_GET_SIZE(o) PyBytes_GET_SIZE(o) + #define __Pyx_PyByteArray_GET_SIZE(o) PyByteArray_GET_SIZE(o) + #define __Pyx_PyUnicode_GET_LENGTH(o) PyUnicode_GET_LENGTH(o) +#else + #define __Pyx_PyTuple_GET_SIZE(o) PyTuple_Size(o) + #define __Pyx_PyList_GET_SIZE(o) PyList_Size(o) + #define __Pyx_PySet_GET_SIZE(o) PySet_Size(o) + #define __Pyx_PyBytes_GET_SIZE(o) PyBytes_Size(o) + #define __Pyx_PyByteArray_GET_SIZE(o) PyByteArray_Size(o) + #define __Pyx_PyUnicode_GET_LENGTH(o) PyUnicode_GetLength(o) +#endif +#if CYTHON_COMPILING_IN_PYPY && !defined(PyUnicode_InternFromString) + #define PyUnicode_InternFromString(s) PyUnicode_FromString(s) +#endif +#define __Pyx_PyLong_FromHash_t PyLong_FromSsize_t +#define __Pyx_PyLong_AsHash_t __Pyx_PyIndex_AsSsize_t +#if __PYX_LIMITED_VERSION_HEX >= 0x030A0000 + #define __Pyx_PySendResult PySendResult +#else + typedef enum { + PYGEN_RETURN = 0, + PYGEN_ERROR = -1, + PYGEN_NEXT = 1, + } __Pyx_PySendResult; +#endif +#if CYTHON_COMPILING_IN_LIMITED_API || PY_VERSION_HEX < 0x030A00A3 + typedef __Pyx_PySendResult (*__Pyx_pyiter_sendfunc)(PyObject *iter, PyObject *value, PyObject **result); +#else + #define __Pyx_pyiter_sendfunc sendfunc +#endif +#if !CYTHON_USE_AM_SEND +#define __PYX_HAS_PY_AM_SEND 0 +#elif __PYX_LIMITED_VERSION_HEX >= 0x030A0000 +#define __PYX_HAS_PY_AM_SEND 1 +#else +#define __PYX_HAS_PY_AM_SEND 2 // our own backported implementation +#endif +#if __PYX_HAS_PY_AM_SEND < 2 + #define __Pyx_PyAsyncMethodsStruct PyAsyncMethods +#else + typedef struct { + unaryfunc am_await; + unaryfunc am_aiter; + unaryfunc am_anext; + __Pyx_pyiter_sendfunc am_send; + } __Pyx_PyAsyncMethodsStruct; + #define __Pyx_SlotTpAsAsync(s) ((PyAsyncMethods*)(s)) +#endif +#if CYTHON_USE_AM_SEND && PY_VERSION_HEX < 0x030A00F0 + #define __Pyx_TPFLAGS_HAVE_AM_SEND (1UL << 21) +#else + #define __Pyx_TPFLAGS_HAVE_AM_SEND (0) +#endif +#if PY_VERSION_HEX >= 0x03090000 +#define __Pyx_PyInterpreterState_Get() PyInterpreterState_Get() +#else +#define __Pyx_PyInterpreterState_Get() PyThreadState_Get()->interp +#endif +#if CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030A0000 +#ifdef __cplusplus +extern "C" +#endif +PyAPI_FUNC(void *) PyMem_Calloc(size_t nelem, size_t elsize); +#endif +#if CYTHON_COMPILING_IN_LIMITED_API +static int __Pyx_init_co_variable(PyObject *inspect, const char* name, int *write_to) { + int value; + PyObject *py_value = PyObject_GetAttrString(inspect, name); + if (!py_value) return 0; + value = (int) PyLong_AsLong(py_value); + Py_DECREF(py_value); + *write_to = value; + return value != -1 || !PyErr_Occurred(); +} +static int __Pyx_init_co_variables(void) { + PyObject *inspect; + int result; + inspect = PyImport_ImportModule("inspect"); + result = +#if !defined(CO_OPTIMIZED) + __Pyx_init_co_variable(inspect, "CO_OPTIMIZED", &CO_OPTIMIZED) && +#endif +#if !defined(CO_NEWLOCALS) + __Pyx_init_co_variable(inspect, "CO_NEWLOCALS", &CO_NEWLOCALS) && +#endif +#if !defined(CO_VARARGS) + __Pyx_init_co_variable(inspect, "CO_VARARGS", &CO_VARARGS) && +#endif +#if !defined(CO_VARKEYWORDS) + __Pyx_init_co_variable(inspect, "CO_VARKEYWORDS", &CO_VARKEYWORDS) && +#endif +#if !defined(CO_ASYNC_GENERATOR) + __Pyx_init_co_variable(inspect, "CO_ASYNC_GENERATOR", &CO_ASYNC_GENERATOR) && +#endif +#if !defined(CO_GENERATOR) + __Pyx_init_co_variable(inspect, "CO_GENERATOR", &CO_GENERATOR) && +#endif +#if !defined(CO_COROUTINE) + __Pyx_init_co_variable(inspect, "CO_COROUTINE", &CO_COROUTINE) && +#endif + 1; + Py_DECREF(inspect); + return result ? 0 : -1; +} +#else +static int __Pyx_init_co_variables(void) { + return 0; // It's a limited API-only feature +} +#endif + +/* MathInitCode */ +#if defined(_WIN32) || defined(WIN32) || defined(MS_WINDOWS) + #ifndef _USE_MATH_DEFINES + #define _USE_MATH_DEFINES + #endif +#endif +#include +#if defined(__CYGWIN__) && defined(_LDBL_EQ_DBL) +#define __Pyx_truncl trunc +#else +#define __Pyx_truncl truncl +#endif + +#ifndef CYTHON_CLINE_IN_TRACEBACK_RUNTIME +#define CYTHON_CLINE_IN_TRACEBACK_RUNTIME 0 +#endif +#ifndef CYTHON_CLINE_IN_TRACEBACK +#define CYTHON_CLINE_IN_TRACEBACK CYTHON_CLINE_IN_TRACEBACK_RUNTIME +#endif +#if CYTHON_CLINE_IN_TRACEBACK +#define __PYX_MARK_ERR_POS(f_index, lineno) { __pyx_filename = __pyx_f[f_index]; (void) __pyx_filename; __pyx_lineno = lineno; (void) __pyx_lineno; __pyx_clineno = __LINE__; (void) __pyx_clineno; } +#else +#define __PYX_MARK_ERR_POS(f_index, lineno) { __pyx_filename = __pyx_f[f_index]; (void) __pyx_filename; __pyx_lineno = lineno; (void) __pyx_lineno; (void) __pyx_clineno; } +#endif +#define __PYX_ERR(f_index, lineno, Ln_error) \ + { __PYX_MARK_ERR_POS(f_index, lineno) goto Ln_error; } + +#ifdef CYTHON_EXTERN_C + #undef __PYX_EXTERN_C + #define __PYX_EXTERN_C CYTHON_EXTERN_C +#elif defined(__PYX_EXTERN_C) + #ifdef _MSC_VER + #pragma message ("Please do not define the '__PYX_EXTERN_C' macro externally. Use 'CYTHON_EXTERN_C' instead.") + #else + #warning Please do not define the '__PYX_EXTERN_C' macro externally. Use 'CYTHON_EXTERN_C' instead. + #endif +#else + #ifdef __cplusplus + #define __PYX_EXTERN_C extern "C" + #else + #define __PYX_EXTERN_C extern + #endif +#endif + +#define __PYX_HAVE__thriftpy2__protocol__cybin__cybin +#define __PYX_HAVE_API__thriftpy2__protocol__cybin__cybin +/* Early includes */ +#include +#include +#include +#include + + #if __PYX_LIMITED_VERSION_HEX < 0x030d0000 + static CYTHON_INLINE PyObject * + __Pyx_CAPI_PyList_GetItemRef(PyObject *list, Py_ssize_t index) + { + PyObject *item = PyList_GetItem(list, index); + Py_XINCREF(item); + return item; + } + #else + #define __Pyx_CAPI_PyList_GetItemRef PyList_GetItemRef + #endif + + #if CYTHON_COMPILING_IN_LIMITED_API || PY_VERSION_HEX < 0x030d0000 + static CYTHON_INLINE int + __Pyx_CAPI_PyList_Extend(PyObject *list, PyObject *iterable) + { + return PyList_SetSlice(list, PY_SSIZE_T_MAX, PY_SSIZE_T_MAX, iterable); + } + + static CYTHON_INLINE int + __Pyx_CAPI_PyList_Clear(PyObject *list) + { + return PyList_SetSlice(list, 0, PY_SSIZE_T_MAX, NULL); + } + #else + #define __Pyx_CAPI_PyList_Extend PyList_Extend + #define __Pyx_CAPI_PyList_Clear PyList_Clear + #endif + + + #if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyFloat_FromString(obj) PyFloat_FromString(obj) + #else + #define __Pyx_PyFloat_FromString(obj) PyFloat_FromString(obj, NULL) + #endif + +#include + + #if PY_MAJOR_VERSION <= 2 + #define PyDict_GetItemWithError _PyDict_GetItemWithError + #endif + + #if __PYX_LIMITED_VERSION_HEX < 0x030d0000 + static CYTHON_INLINE int + __Pyx_CAPI_PyDict_GetItemStringRef(PyObject *mp, const char *key, PyObject **result) + { + int res; + PyObject *key_obj = PyUnicode_FromString(key); + if (key_obj == NULL) { + *result = NULL; + return -1; + } + res = __Pyx_PyDict_GetItemRef(mp, key_obj, result); + Py_DECREF(key_obj); + return res; + } + #else + #define __Pyx_CAPI_PyDict_GetItemStringRef PyDict_GetItemStringRef + #endif + #if PY_VERSION_HEX < 0x030d0000 || (CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030F0000) + static CYTHON_INLINE int + __Pyx_CAPI_PyDict_SetDefaultRef(PyObject *d, PyObject *key, PyObject *default_value, + PyObject **result) + { + PyObject *value; + if (__Pyx_PyDict_GetItemRef(d, key, &value) < 0) { + // get error + if (result) { + *result = NULL; + } + return -1; + } + if (value != NULL) { + // present + if (result) { + *result = value; + } + else { + Py_DECREF(value); + } + return 1; + } + + // missing: set the item + if (PyDict_SetItem(d, key, default_value) < 0) { + // set error + if (result) { + *result = NULL; + } + return -1; + } + if (result) { + Py_INCREF(default_value); + *result = default_value; + } + return 0; + } + #else + #define __Pyx_CAPI_PyDict_SetDefaultRef PyDict_SetDefaultRef + #endif + + + #if PY_VERSION_HEX < 0x030d0000 + static CYTHON_INLINE int __Pyx_PyWeakref_GetRef(PyObject *ref, PyObject **pobj) + { + PyObject *obj = PyWeakref_GetObject(ref); + if (obj == NULL) { + // SystemError if ref is NULL + *pobj = NULL; + return -1; + } + if (obj == Py_None) { + *pobj = NULL; + return 0; + } + Py_INCREF(obj); + *pobj = obj; + return 1; + } + #else + #define __Pyx_PyWeakref_GetRef PyWeakref_GetRef + #endif + +#include "pythread.h" + + #if (CYTHON_COMPILING_IN_PYPY && PYPY_VERSION_NUM < 0x07030600) && !defined(PyContextVar_Get) + #define PyContextVar_Get(var, d, v) ((d) ? ((void)(var), Py_INCREF(d), (v)[0] = (d), 0) : ((v)[0] = NULL, 0) ) + #endif + +#include "endian_port.h" +#ifdef _OPENMP +#include +#endif /* _OPENMP */ + +#if defined(PYREX_WITHOUT_ASSERTIONS) && !defined(CYTHON_WITHOUT_ASSERTIONS) +#define CYTHON_WITHOUT_ASSERTIONS +#endif + +#ifdef CYTHON_FREETHREADING_COMPATIBLE +#if CYTHON_FREETHREADING_COMPATIBLE +#define __Pyx_FREETHREADING_COMPATIBLE Py_MOD_GIL_NOT_USED +#else +#define __Pyx_FREETHREADING_COMPATIBLE Py_MOD_GIL_USED +#endif +#else +#define __Pyx_FREETHREADING_COMPATIBLE Py_MOD_GIL_NOT_USED +#endif +#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 +#define __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 0 +#define __PYX_DEFAULT_STRING_ENCODING "" +#define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString +#define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#define __Pyx_uchar_cast(c) ((unsigned char)c) +#define __Pyx_long_cast(x) ((long)x) +#define __Pyx_fits_Py_ssize_t(v, type, is_signed) (\ + (sizeof(type) < sizeof(Py_ssize_t)) ||\ + (sizeof(type) > sizeof(Py_ssize_t) &&\ + likely(v < (type)PY_SSIZE_T_MAX ||\ + v == (type)PY_SSIZE_T_MAX) &&\ + (!is_signed || likely(v > (type)PY_SSIZE_T_MIN ||\ + v == (type)PY_SSIZE_T_MIN))) ||\ + (sizeof(type) == sizeof(Py_ssize_t) &&\ + (is_signed || likely(v < (type)PY_SSIZE_T_MAX ||\ + v == (type)PY_SSIZE_T_MAX))) ) +static CYTHON_INLINE int __Pyx_is_valid_index(Py_ssize_t i, Py_ssize_t limit) { + return (size_t) i < (size_t) limit; +} +#if defined (__cplusplus) && __cplusplus >= 201103L + #include + #define __Pyx_sst_abs(value) std::abs(value) +#elif SIZEOF_INT >= SIZEOF_SIZE_T + #define __Pyx_sst_abs(value) abs(value) +#elif SIZEOF_LONG >= SIZEOF_SIZE_T + #define __Pyx_sst_abs(value) labs(value) +#elif defined (_MSC_VER) + #define __Pyx_sst_abs(value) ((Py_ssize_t)_abs64(value)) +#elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define __Pyx_sst_abs(value) llabs(value) +#elif defined (__GNUC__) + #define __Pyx_sst_abs(value) __builtin_llabs(value) +#else + #define __Pyx_sst_abs(value) ((value<0) ? -value : value) +#endif +static CYTHON_INLINE Py_ssize_t __Pyx_ssize_strlen(const char *s); +static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject*); +static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); +static CYTHON_INLINE PyObject* __Pyx_PyByteArray_FromString(const char*); +#define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l) +#define __Pyx_PyBytes_FromString PyBytes_FromString +#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char*); +#if CYTHON_ASSUME_SAFE_MACROS + #define __Pyx_PyBytes_AsWritableString(s) ((char*) PyBytes_AS_STRING(s)) + #define __Pyx_PyBytes_AsWritableSString(s) ((signed char*) PyBytes_AS_STRING(s)) + #define __Pyx_PyBytes_AsWritableUString(s) ((unsigned char*) PyBytes_AS_STRING(s)) + #define __Pyx_PyBytes_AsString(s) ((const char*) PyBytes_AS_STRING(s)) + #define __Pyx_PyBytes_AsSString(s) ((const signed char*) PyBytes_AS_STRING(s)) + #define __Pyx_PyBytes_AsUString(s) ((const unsigned char*) PyBytes_AS_STRING(s)) + #define __Pyx_PyByteArray_AsString(s) PyByteArray_AS_STRING(s) +#else + #define __Pyx_PyBytes_AsWritableString(s) ((char*) PyBytes_AsString(s)) + #define __Pyx_PyBytes_AsWritableSString(s) ((signed char*) PyBytes_AsString(s)) + #define __Pyx_PyBytes_AsWritableUString(s) ((unsigned char*) PyBytes_AsString(s)) + #define __Pyx_PyBytes_AsString(s) ((const char*) PyBytes_AsString(s)) + #define __Pyx_PyBytes_AsSString(s) ((const signed char*) PyBytes_AsString(s)) + #define __Pyx_PyBytes_AsUString(s) ((const unsigned char*) PyBytes_AsString(s)) + #define __Pyx_PyByteArray_AsString(s) PyByteArray_AsString(s) +#endif +#define __Pyx_PyObject_AsWritableString(s) ((char*)(__pyx_uintptr_t) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsWritableSString(s) ((signed char*)(__pyx_uintptr_t) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsWritableUString(s) ((unsigned char*)(__pyx_uintptr_t) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsSString(s) ((const signed char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsUString(s) ((const unsigned char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_FromCString(s) __Pyx_PyObject_FromString((const char*)s) +#define __Pyx_PyBytes_FromCString(s) __Pyx_PyBytes_FromString((const char*)s) +#define __Pyx_PyByteArray_FromCString(s) __Pyx_PyByteArray_FromString((const char*)s) +#define __Pyx_PyUnicode_FromCString(s) __Pyx_PyUnicode_FromString((const char*)s) +#define __Pyx_PyUnicode_FromOrdinal(o) PyUnicode_FromOrdinal((int)o) +#define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode +static CYTHON_INLINE PyObject *__Pyx_NewRef(PyObject *obj) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030a0000 || defined(Py_NewRef) + return Py_NewRef(obj); +#else + Py_INCREF(obj); + return obj; +#endif +} +static CYTHON_INLINE PyObject *__Pyx_XNewRef(PyObject *obj) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030a0000 || defined(Py_XNewRef) + return Py_XNewRef(obj); +#else + Py_XINCREF(obj); + return obj; +#endif +} +static CYTHON_INLINE PyObject *__Pyx_Owned_Py_None(int b); +static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b); +static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); +static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject*); +static CYTHON_INLINE PyObject* __Pyx_PyNumber_Long(PyObject* x); +#define __Pyx_PySequence_Tuple(obj)\ + (likely(PyTuple_CheckExact(obj)) ? __Pyx_NewRef(obj) : PySequence_Tuple(obj)) +static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); +static CYTHON_INLINE PyObject * __Pyx_PyLong_FromSize_t(size_t); +static CYTHON_INLINE Py_hash_t __Pyx_PyIndex_AsHash_t(PyObject*); +#if CYTHON_ASSUME_SAFE_MACROS +#define __Pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) +#define __Pyx_PyFloat_AS_DOUBLE(x) PyFloat_AS_DOUBLE(x) +#else +#define __Pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) +#define __Pyx_PyFloat_AS_DOUBLE(x) PyFloat_AsDouble(x) +#endif +#define __Pyx_PyFloat_AsFloat(x) ((float) __Pyx_PyFloat_AsDouble(x)) +#define __Pyx_PyNumber_Int(x) (PyLong_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Long(x)) +#if CYTHON_USE_PYLONG_INTERNALS + #if PY_VERSION_HEX >= 0x030C00A7 + #ifndef _PyLong_SIGN_MASK + #define _PyLong_SIGN_MASK 3 + #endif + #ifndef _PyLong_NON_SIZE_BITS + #define _PyLong_NON_SIZE_BITS 3 + #endif + #define __Pyx_PyLong_Sign(x) (((PyLongObject*)x)->long_value.lv_tag & _PyLong_SIGN_MASK) + #define __Pyx_PyLong_IsNeg(x) ((__Pyx_PyLong_Sign(x) & 2) != 0) + #define __Pyx_PyLong_IsNonNeg(x) (!__Pyx_PyLong_IsNeg(x)) + #define __Pyx_PyLong_IsZero(x) (__Pyx_PyLong_Sign(x) & 1) + #define __Pyx_PyLong_IsPos(x) (__Pyx_PyLong_Sign(x) == 0) + #define __Pyx_PyLong_CompactValueUnsigned(x) (__Pyx_PyLong_Digits(x)[0]) + #define __Pyx_PyLong_DigitCount(x) ((Py_ssize_t) (((PyLongObject*)x)->long_value.lv_tag >> _PyLong_NON_SIZE_BITS)) + #define __Pyx_PyLong_SignedDigitCount(x)\ + ((1 - (Py_ssize_t) __Pyx_PyLong_Sign(x)) * __Pyx_PyLong_DigitCount(x)) + #if defined(PyUnstable_Long_IsCompact) && defined(PyUnstable_Long_CompactValue) + #define __Pyx_PyLong_IsCompact(x) PyUnstable_Long_IsCompact((PyLongObject*) x) + #define __Pyx_PyLong_CompactValue(x) PyUnstable_Long_CompactValue((PyLongObject*) x) + #else + #define __Pyx_PyLong_IsCompact(x) (((PyLongObject*)x)->long_value.lv_tag < (2 << _PyLong_NON_SIZE_BITS)) + #define __Pyx_PyLong_CompactValue(x) ((1 - (Py_ssize_t) __Pyx_PyLong_Sign(x)) * (Py_ssize_t) __Pyx_PyLong_Digits(x)[0]) + #endif + typedef Py_ssize_t __Pyx_compact_pylong; + typedef size_t __Pyx_compact_upylong; + #else + #define __Pyx_PyLong_IsNeg(x) (Py_SIZE(x) < 0) + #define __Pyx_PyLong_IsNonNeg(x) (Py_SIZE(x) >= 0) + #define __Pyx_PyLong_IsZero(x) (Py_SIZE(x) == 0) + #define __Pyx_PyLong_IsPos(x) (Py_SIZE(x) > 0) + #define __Pyx_PyLong_CompactValueUnsigned(x) ((Py_SIZE(x) == 0) ? 0 : __Pyx_PyLong_Digits(x)[0]) + #define __Pyx_PyLong_DigitCount(x) __Pyx_sst_abs(Py_SIZE(x)) + #define __Pyx_PyLong_SignedDigitCount(x) Py_SIZE(x) + #define __Pyx_PyLong_IsCompact(x) (Py_SIZE(x) == 0 || Py_SIZE(x) == 1 || Py_SIZE(x) == -1) + #define __Pyx_PyLong_CompactValue(x)\ + ((Py_SIZE(x) == 0) ? (sdigit) 0 : ((Py_SIZE(x) < 0) ? -(sdigit)__Pyx_PyLong_Digits(x)[0] : (sdigit)__Pyx_PyLong_Digits(x)[0])) + typedef sdigit __Pyx_compact_pylong; + typedef digit __Pyx_compact_upylong; + #endif + #if PY_VERSION_HEX >= 0x030C00A5 + #define __Pyx_PyLong_Digits(x) (((PyLongObject*)x)->long_value.ob_digit) + #else + #define __Pyx_PyLong_Digits(x) (((PyLongObject*)x)->ob_digit) + #endif +#endif +#if __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 + #define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) +#elif __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + #define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeASCII(c_str, size, NULL) +#else + #define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) +#endif + + +/* Test for GCC > 2.95 */ +#if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))) + #define likely(x) __builtin_expect(!!(x), 1) + #define unlikely(x) __builtin_expect(!!(x), 0) +#else /* !__GNUC__ or GCC < 2.95 */ + #define likely(x) (x) + #define unlikely(x) (x) +#endif /* __GNUC__ */ +/* PretendToInitialize */ +#ifdef __cplusplus +#if __cplusplus > 201103L +#include +#endif +template +static void __Pyx_pretend_to_initialize(T* ptr) { +#if __cplusplus > 201103L + if ((std::is_trivially_default_constructible::value)) +#endif + *ptr = T(); + (void)ptr; +} +#else +static CYTHON_INLINE void __Pyx_pretend_to_initialize(void* ptr) { (void)ptr; } +#endif + + +#if !CYTHON_USE_MODULE_STATE +static PyObject *__pyx_m = NULL; +#endif +static int __pyx_lineno; +static int __pyx_clineno = 0; +static const char * const __pyx_cfilenm = __FILE__; +static const char *__pyx_filename; + +/* #### Code section: filename_table ### */ + +static const char* const __pyx_f[] = { + "thriftpy2/protocol/cybin/cybin.pyx", + "cpython/contextvars.pxd", + "", + "cpython/type.pxd", + "cpython/bool.pxd", + "cpython/complex.pxd", + "thriftpy2/transport/cybase.pxd", +}; +/* #### Code section: utility_code_proto_before_types ### */ +/* Atomics.proto (used by UnpackUnboundCMethod) */ +#include +#ifndef CYTHON_ATOMICS + #define CYTHON_ATOMICS 1 +#endif +#define __PYX_CYTHON_ATOMICS_ENABLED() CYTHON_ATOMICS +#define __PYX_GET_CYTHON_COMPILING_IN_CPYTHON_FREETHREADING() CYTHON_COMPILING_IN_CPYTHON_FREETHREADING +#define __pyx_atomic_int_type int +#define __pyx_nonatomic_int_type int +#if CYTHON_ATOMICS && (defined(__STDC_VERSION__) &&\ + (__STDC_VERSION__ >= 201112L) &&\ + !defined(__STDC_NO_ATOMICS__)) + #include +#elif CYTHON_ATOMICS && (defined(__cplusplus) && (\ + (__cplusplus >= 201103L) ||\ + (defined(_MSC_VER) && _MSC_VER >= 1700))) + #include +#endif +#if CYTHON_ATOMICS && (defined(__STDC_VERSION__) &&\ + (__STDC_VERSION__ >= 201112L) &&\ + !defined(__STDC_NO_ATOMICS__) &&\ + ATOMIC_INT_LOCK_FREE == 2) + #undef __pyx_atomic_int_type + #define __pyx_atomic_int_type atomic_int + #define __pyx_atomic_ptr_type atomic_uintptr_t + #define __pyx_nonatomic_ptr_type uintptr_t + #define __pyx_atomic_incr_relaxed(value) atomic_fetch_add_explicit(value, 1, memory_order_relaxed) + #define __pyx_atomic_incr_acq_rel(value) atomic_fetch_add_explicit(value, 1, memory_order_acq_rel) + #define __pyx_atomic_decr_acq_rel(value) atomic_fetch_sub_explicit(value, 1, memory_order_acq_rel) + #define __pyx_atomic_sub(value, arg) atomic_fetch_sub(value, arg) + #define __pyx_atomic_int_cmp_exchange(value, expected, desired) atomic_compare_exchange_strong(value, expected, desired) + #define __pyx_atomic_load(value) atomic_load(value) + #define __pyx_atomic_store(value, new_value) atomic_store(value, new_value) + #define __pyx_atomic_pointer_load_relaxed(value) atomic_load_explicit(value, memory_order_relaxed) + #define __pyx_atomic_pointer_load_acquire(value) atomic_load_explicit(value, memory_order_acquire) + #define __pyx_atomic_pointer_exchange(value, new_value) atomic_exchange(value, (__pyx_nonatomic_ptr_type)new_value) + #define __pyx_atomic_pointer_cmp_exchange(value, expected, desired) atomic_compare_exchange_strong(value, expected, desired) + #if defined(__PYX_DEBUG_ATOMICS) && defined(_MSC_VER) + #pragma message ("Using standard C atomics") + #elif defined(__PYX_DEBUG_ATOMICS) + #warning "Using standard C atomics" + #endif +#elif CYTHON_ATOMICS && (defined(__cplusplus) && (\ + (__cplusplus >= 201103L) ||\ +\ + (defined(_MSC_VER) && _MSC_VER >= 1700)) &&\ + ATOMIC_INT_LOCK_FREE == 2) + #undef __pyx_atomic_int_type + #define __pyx_atomic_int_type std::atomic_int + #define __pyx_atomic_ptr_type std::atomic_uintptr_t + #define __pyx_nonatomic_ptr_type uintptr_t + #define __pyx_atomic_incr_relaxed(value) std::atomic_fetch_add_explicit(value, 1, std::memory_order_relaxed) + #define __pyx_atomic_incr_acq_rel(value) std::atomic_fetch_add_explicit(value, 1, std::memory_order_acq_rel) + #define __pyx_atomic_decr_acq_rel(value) std::atomic_fetch_sub_explicit(value, 1, std::memory_order_acq_rel) + #define __pyx_atomic_sub(value, arg) std::atomic_fetch_sub(value, arg) + #define __pyx_atomic_int_cmp_exchange(value, expected, desired) std::atomic_compare_exchange_strong(value, expected, desired) + #define __pyx_atomic_load(value) std::atomic_load(value) + #define __pyx_atomic_store(value, new_value) std::atomic_store(value, new_value) + #define __pyx_atomic_pointer_load_relaxed(value) std::atomic_load_explicit(value, std::memory_order_relaxed) + #define __pyx_atomic_pointer_load_acquire(value) std::atomic_load_explicit(value, std::memory_order_acquire) + #define __pyx_atomic_pointer_exchange(value, new_value) std::atomic_exchange(value, (__pyx_nonatomic_ptr_type)new_value) + #define __pyx_atomic_pointer_cmp_exchange(value, expected, desired) std::atomic_compare_exchange_strong(value, expected, desired) + #if defined(__PYX_DEBUG_ATOMICS) && defined(_MSC_VER) + #pragma message ("Using standard C++ atomics") + #elif defined(__PYX_DEBUG_ATOMICS) + #warning "Using standard C++ atomics" + #endif +#elif CYTHON_ATOMICS && (__GNUC__ >= 5 || (__GNUC__ == 4 &&\ + (__GNUC_MINOR__ > 1 ||\ + (__GNUC_MINOR__ == 1 && __GNUC_PATCHLEVEL__ >= 2)))) + #define __pyx_atomic_ptr_type void* + #define __pyx_nonatomic_ptr_type void* + #define __pyx_atomic_incr_relaxed(value) __sync_fetch_and_add(value, 1) + #define __pyx_atomic_incr_acq_rel(value) __sync_fetch_and_add(value, 1) + #define __pyx_atomic_decr_acq_rel(value) __sync_fetch_and_sub(value, 1) + #define __pyx_atomic_sub(value, arg) __sync_fetch_and_sub(value, arg) + static CYTHON_INLINE int __pyx_atomic_int_cmp_exchange(__pyx_atomic_int_type* value, __pyx_nonatomic_int_type* expected, __pyx_nonatomic_int_type desired) { + __pyx_nonatomic_int_type old = __sync_val_compare_and_swap(value, *expected, desired); + int result = old == *expected; + *expected = old; + return result; + } + #define __pyx_atomic_load(value) __sync_fetch_and_add(value, 0) + #define __pyx_atomic_store(value, new_value) __sync_lock_test_and_set(value, new_value) + #define __pyx_atomic_pointer_load_relaxed(value) __sync_fetch_and_add(value, 0) + #define __pyx_atomic_pointer_load_acquire(value) __sync_fetch_and_add(value, 0) + #define __pyx_atomic_pointer_exchange(value, new_value) __sync_lock_test_and_set(value, (__pyx_atomic_ptr_type)new_value) + static CYTHON_INLINE int __pyx_atomic_pointer_cmp_exchange(__pyx_atomic_ptr_type* value, __pyx_nonatomic_ptr_type* expected, __pyx_nonatomic_ptr_type desired) { + __pyx_nonatomic_ptr_type old = __sync_val_compare_and_swap(value, *expected, desired); + int result = old == *expected; + *expected = old; + return result; + } + #ifdef __PYX_DEBUG_ATOMICS + #warning "Using GNU atomics" + #endif +#elif CYTHON_ATOMICS && defined(_MSC_VER) + #include + #undef __pyx_atomic_int_type + #define __pyx_atomic_int_type long + #define __pyx_atomic_ptr_type void* + #undef __pyx_nonatomic_int_type + #define __pyx_nonatomic_int_type long + #define __pyx_nonatomic_ptr_type void* + #pragma intrinsic (_InterlockedExchangeAdd, _InterlockedExchange, _InterlockedCompareExchange, _InterlockedCompareExchangePointer, _InterlockedExchangePointer) + #define __pyx_atomic_incr_relaxed(value) _InterlockedExchangeAdd(value, 1) + #define __pyx_atomic_incr_acq_rel(value) _InterlockedExchangeAdd(value, 1) + #define __pyx_atomic_decr_acq_rel(value) _InterlockedExchangeAdd(value, -1) + #define __pyx_atomic_sub(value, arg) _InterlockedExchangeAdd(value, -arg) + static CYTHON_INLINE int __pyx_atomic_int_cmp_exchange(__pyx_atomic_int_type* value, __pyx_nonatomic_int_type* expected, __pyx_nonatomic_int_type desired) { + __pyx_nonatomic_int_type old = _InterlockedCompareExchange(value, desired, *expected); + int result = old == *expected; + *expected = old; + return result; + } + #define __pyx_atomic_load(value) _InterlockedExchangeAdd(value, 0) + #define __pyx_atomic_store(value, new_value) _InterlockedExchange(value, new_value) + #define __pyx_atomic_pointer_load_relaxed(value) *(void * volatile *)value + #define __pyx_atomic_pointer_load_acquire(value) _InterlockedCompareExchangePointer(value, 0, 0) + #define __pyx_atomic_pointer_exchange(value, new_value) _InterlockedExchangePointer(value, (__pyx_atomic_ptr_type)new_value) + static CYTHON_INLINE int __pyx_atomic_pointer_cmp_exchange(__pyx_atomic_ptr_type* value, __pyx_nonatomic_ptr_type* expected, __pyx_nonatomic_ptr_type desired) { + __pyx_atomic_ptr_type old = _InterlockedCompareExchangePointer(value, desired, *expected); + int result = old == *expected; + *expected = old; + return result; + } + #ifdef __PYX_DEBUG_ATOMICS + #pragma message ("Using MSVC atomics") + #endif +#else + #undef CYTHON_ATOMICS + #define CYTHON_ATOMICS 0 + #ifdef __PYX_DEBUG_ATOMICS + #warning "Not using atomics" + #endif +#endif + +/* CriticalSectionsDefinition.proto (used by CriticalSections) */ +#if !CYTHON_COMPILING_IN_CPYTHON_FREETHREADING +#define __Pyx_PyCriticalSection void* +#define __Pyx_PyCriticalSection2 void* +#define __Pyx_PyCriticalSection_End(cs) +#define __Pyx_PyCriticalSection2_End(cs) +#else +#define __Pyx_PyCriticalSection PyCriticalSection +#define __Pyx_PyCriticalSection2 PyCriticalSection2 +#define __Pyx_PyCriticalSection_End PyCriticalSection_End +#define __Pyx_PyCriticalSection2_End PyCriticalSection2_End +#endif + +/* CriticalSections.proto (used by ParseKeywordsImpl) */ +#if !CYTHON_COMPILING_IN_CPYTHON_FREETHREADING +#define __Pyx_PyCriticalSection_Begin(cs, arg) (void)(cs) +#define __Pyx_PyCriticalSection2_Begin(cs, arg1, arg2) (void)(cs) +#else +#define __Pyx_PyCriticalSection_Begin PyCriticalSection_Begin +#define __Pyx_PyCriticalSection2_Begin PyCriticalSection2_Begin +#endif +#if PY_VERSION_HEX < 0x030d0000 || CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_BEGIN_CRITICAL_SECTION(o) { +#define __Pyx_END_CRITICAL_SECTION() } +#else +#define __Pyx_BEGIN_CRITICAL_SECTION Py_BEGIN_CRITICAL_SECTION +#define __Pyx_END_CRITICAL_SECTION Py_END_CRITICAL_SECTION +#endif + +/* IncludeStructmemberH.proto (used by FixUpExtensionType) */ +#include + +/* #### Code section: numeric_typedefs ### */ +/* #### Code section: complex_type_declarations ### */ +/* #### Code section: type_declarations ### */ + +/*--- Type declarations ---*/ +struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer; +struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase; +struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol; +struct __pyx_opt_args_7cpython_11contextvars_get_value; +struct __pyx_opt_args_7cpython_11contextvars_get_value_no_default; + +/* "cpython/contextvars.pxd":116 + * + * @_cython.c_compile_guard("!CYTHON_COMPILING_IN_LIMITED_API") + * cdef inline object get_value(var, default_value=None): # <<<<<<<<<<<<<< + * """Return a new reference to the value of the context variable, + * or the default value of the context variable, +*/ +struct __pyx_opt_args_7cpython_11contextvars_get_value { + int __pyx_n; + PyObject *default_value; +}; + +/* "cpython/contextvars.pxd":134 + * + * @_cython.c_compile_guard("!CYTHON_COMPILING_IN_LIMITED_API") + * cdef inline object get_value_no_default(var, default_value=None): # <<<<<<<<<<<<<< + * """Return a new reference to the value of the context variable, + * or the provided default value if no such value was found. +*/ +struct __pyx_opt_args_7cpython_11contextvars_get_value_no_default { + int __pyx_n; + PyObject *default_value; +}; + +/* "thriftpy2/transport/cybase.pxd":3 + * # cython: freethreading_compatible = True + * + * cdef enum: # <<<<<<<<<<<<<< + * DEFAULT_BUFFER = 4096 + * STACK_STRING_LEN = 4096 +*/ +enum { + __pyx_e_9thriftpy2_9transport_6cybase_DEFAULT_BUFFER = 0x1000, + __pyx_e_9thriftpy2_9transport_6cybase_STACK_STRING_LEN = 0x1000 +}; +struct __pyx_opt_args_9thriftpy2_8protocol_5cybin_5cybin_read_struct; +struct __pyx_opt_args_9thriftpy2_8protocol_5cybin_5cybin_c_read_string; +struct __pyx_opt_args_9thriftpy2_8protocol_5cybin_5cybin_c_read_val; +struct __pyx_opt_args_9thriftpy2_8protocol_5cybin_5cybin_c_write_val; + +/* "thriftpy2/protocol/cybin/cybin.pyx":27 + * DEF TYPE_MASK = 0x000000ff + * + * ctypedef enum TType: # <<<<<<<<<<<<<< + * T_STOP = 0, + * T_VOID = 1, +*/ +enum __pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType { + __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_STOP = 0, + __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_VOID = 1, + __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_BOOL = 2, + __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_BYTE = 3, + __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_I08 = 3, + __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_I16 = 6, + __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_I32 = 8, + __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_U64 = 9, + __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_I64 = 10, + __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_DOUBLE = 4, + __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_STRING = 11, + __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_UTF7 = 11, + __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_NARY = 11, + __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_STRUCT = 12, + __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_MAP = 13, + __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_SET = 14, + __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_LIST = 15, + __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_UTF8 = 16, + __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_UTF16 = 17, + __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_BINARY = 18 +}; +typedef enum __pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType __pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType; + +/* "thriftpy2/protocol/cybin/cybin.pyx":177 + * + * + * cdef inline read_struct(CyTransportBase buf, obj, decode_response=True, # <<<<<<<<<<<<<< + * strict_decode=False): + * cdef dict field_specs = obj.thrift_spec +*/ +struct __pyx_opt_args_9thriftpy2_8protocol_5cybin_5cybin_read_struct { + int __pyx_n; + PyObject *decode_response; + PyObject *strict_decode; +}; + +/* "thriftpy2/protocol/cybin/cybin.pyx":262 + * + * + * cdef inline c_read_string(CyTransportBase buf, int32_t size, # <<<<<<<<<<<<<< + * strict_decode=False): + * py_data = c_read_binary(buf, size) +*/ +struct __pyx_opt_args_9thriftpy2_8protocol_5cybin_5cybin_c_read_string { + int __pyx_n; + PyObject *strict_decode; +}; + +/* "thriftpy2/protocol/cybin/cybin.pyx":273 + * + * + * cdef c_read_val(CyTransportBase buf, TType ttype, spec=None, # <<<<<<<<<<<<<< + * decode_response=True, strict_decode=False): + * cdef int size +*/ +struct __pyx_opt_args_9thriftpy2_8protocol_5cybin_5cybin_c_read_val { + int __pyx_n; + PyObject *spec; + PyObject *decode_response; + PyObject *strict_decode; +}; + +/* "thriftpy2/protocol/cybin/cybin.pyx":370 + * + * + * cdef c_write_val(CyTransportBase buf, TType ttype, val, spec=None): # <<<<<<<<<<<<<< + * if ttype == T_BOOL: + * write_i08(buf, 1 if val else 0) +*/ +struct __pyx_opt_args_9thriftpy2_8protocol_5cybin_5cybin_c_write_val { + int __pyx_n; + PyObject *spec; +}; + +/* "thriftpy2/transport/cybase.pxd":7 + * STACK_STRING_LEN = 4096 + * + * cdef class TCyBuffer(object): # <<<<<<<<<<<<<< + * cdef: + * char *buf +*/ +struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer { + PyObject_HEAD + struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_TCyBuffer *__pyx_vtab; + char *buf; + int cur; + int buf_size; + int data_size; +}; + + +/* "thriftpy2/transport/cybase.pxd":19 + * + * + * cdef class CyTransportBase(object): # <<<<<<<<<<<<<< + * cdef object trans + * +*/ +struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase { + PyObject_HEAD + struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_CyTransportBase *__pyx_vtab; + PyObject *trans; +}; + + +/* "thriftpy2/protocol/cybin/cybin.pyx":457 + * + * + * cdef class TCyBinaryProtocol(object): # <<<<<<<<<<<<<< + * cdef public CyTransportBase trans + * cdef public bool strict_read +*/ +struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol { + PyObject_HEAD + struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *trans; + PyLongObject *strict_read; + PyLongObject *strict_write; + PyLongObject *decode_response; + PyLongObject *strict_decode; +}; + + + +/* "thriftpy2/transport/cybase.pxd":7 + * STACK_STRING_LEN = 4096 + * + * cdef class TCyBuffer(object): # <<<<<<<<<<<<<< + * cdef: + * char *buf +*/ + +struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_TCyBuffer { + void (*move_to_start)(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *); + void (*clean)(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *); + int (*write)(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *, int, char const *); + int (*grow)(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *, int); + PyObject *(*read_trans)(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *, PyObject *, int, char *); +}; +static struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_TCyBuffer *__pyx_vtabptr_9thriftpy2_9transport_6cybase_TCyBuffer; + + +/* "thriftpy2/transport/cybase.pxd":19 + * + * + * cdef class CyTransportBase(object): # <<<<<<<<<<<<<< + * cdef object trans + * +*/ + +struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_CyTransportBase { + PyObject *(*c_read)(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *, int, char *); + PyObject *(*c_write)(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *, char *, int); + PyObject *(*c_flush)(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *); + PyObject *(*get_string)(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *, int); +}; +static struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_CyTransportBase *__pyx_vtabptr_9thriftpy2_9transport_6cybase_CyTransportBase; +/* #### Code section: utility_code_proto ### */ + +/* --- Runtime support code (head) --- */ +/* Refnanny.proto */ +#ifndef CYTHON_REFNANNY + #define CYTHON_REFNANNY 0 +#endif +#if CYTHON_REFNANNY + typedef struct { + void (*INCREF)(void*, PyObject*, Py_ssize_t); + void (*DECREF)(void*, PyObject*, Py_ssize_t); + void (*GOTREF)(void*, PyObject*, Py_ssize_t); + void (*GIVEREF)(void*, PyObject*, Py_ssize_t); + void* (*SetupContext)(const char*, Py_ssize_t, const char*); + void (*FinishContext)(void**); + } __Pyx_RefNannyAPIStruct; + static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; + static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); + #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; + #define __Pyx_RefNannySetupContext(name, acquire_gil)\ + if (acquire_gil) {\ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), (__LINE__), (__FILE__));\ + PyGILState_Release(__pyx_gilstate_save);\ + } else {\ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), (__LINE__), (__FILE__));\ + } + #define __Pyx_RefNannyFinishContextNogil() {\ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ + __Pyx_RefNannyFinishContext();\ + PyGILState_Release(__pyx_gilstate_save);\ + } + #define __Pyx_RefNannyFinishContextNogil() {\ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ + __Pyx_RefNannyFinishContext();\ + PyGILState_Release(__pyx_gilstate_save);\ + } + #define __Pyx_RefNannyFinishContext()\ + __Pyx_RefNanny->FinishContext(&__pyx_refnanny) + #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), (__LINE__)) + #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), (__LINE__)) + #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), (__LINE__)) + #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), (__LINE__)) + #define __Pyx_XINCREF(r) do { if((r) == NULL); else {__Pyx_INCREF(r); }} while(0) + #define __Pyx_XDECREF(r) do { if((r) == NULL); else {__Pyx_DECREF(r); }} while(0) + #define __Pyx_XGOTREF(r) do { if((r) == NULL); else {__Pyx_GOTREF(r); }} while(0) + #define __Pyx_XGIVEREF(r) do { if((r) == NULL); else {__Pyx_GIVEREF(r);}} while(0) +#else + #define __Pyx_RefNannyDeclarations + #define __Pyx_RefNannySetupContext(name, acquire_gil) + #define __Pyx_RefNannyFinishContextNogil() + #define __Pyx_RefNannyFinishContext() + #define __Pyx_INCREF(r) Py_INCREF(r) + #define __Pyx_DECREF(r) Py_DECREF(r) + #define __Pyx_GOTREF(r) + #define __Pyx_GIVEREF(r) + #define __Pyx_XINCREF(r) Py_XINCREF(r) + #define __Pyx_XDECREF(r) Py_XDECREF(r) + #define __Pyx_XGOTREF(r) + #define __Pyx_XGIVEREF(r) +#endif +#define __Pyx_Py_XDECREF_SET(r, v) do {\ + PyObject *tmp = (PyObject *) r;\ + r = v; Py_XDECREF(tmp);\ + } while (0) +#define __Pyx_XDECREF_SET(r, v) do {\ + PyObject *tmp = (PyObject *) r;\ + r = v; __Pyx_XDECREF(tmp);\ + } while (0) +#define __Pyx_DECREF_SET(r, v) do {\ + PyObject *tmp = (PyObject *) r;\ + r = v; __Pyx_DECREF(tmp);\ + } while (0) +#define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) +#define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) + +/* PyErrExceptionMatches.proto (used by PyObjectGetAttrStrNoError) */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_PyErr_ExceptionMatches(err) __Pyx_PyErr_ExceptionMatchesInState(__pyx_tstate, err) +static CYTHON_INLINE int __Pyx_PyErr_ExceptionMatchesInState(PyThreadState* tstate, PyObject* err); +#else +#define __Pyx_PyErr_ExceptionMatches(err) PyErr_ExceptionMatches(err) +#endif + +/* PyThreadStateGet.proto (used by PyErrFetchRestore) */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_PyThreadState_declare PyThreadState *__pyx_tstate; +#define __Pyx_PyThreadState_assign __pyx_tstate = __Pyx_PyThreadState_Current; +#if PY_VERSION_HEX >= 0x030C00A6 +#define __Pyx_PyErr_Occurred() (__pyx_tstate->current_exception != NULL) +#define __Pyx_PyErr_CurrentExceptionType() (__pyx_tstate->current_exception ? (PyObject*) Py_TYPE(__pyx_tstate->current_exception) : (PyObject*) NULL) +#else +#define __Pyx_PyErr_Occurred() (__pyx_tstate->curexc_type != NULL) +#define __Pyx_PyErr_CurrentExceptionType() (__pyx_tstate->curexc_type) +#endif +#else +#define __Pyx_PyThreadState_declare +#define __Pyx_PyThreadState_assign +#define __Pyx_PyErr_Occurred() (PyErr_Occurred() != NULL) +#define __Pyx_PyErr_CurrentExceptionType() PyErr_Occurred() +#endif + +/* PyErrFetchRestore.proto (used by PyObjectGetAttrStrNoError) */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_PyErr_Clear() __Pyx_ErrRestore(NULL, NULL, NULL) +#define __Pyx_ErrRestoreWithState(type, value, tb) __Pyx_ErrRestoreInState(PyThreadState_GET(), type, value, tb) +#define __Pyx_ErrFetchWithState(type, value, tb) __Pyx_ErrFetchInState(PyThreadState_GET(), type, value, tb) +#define __Pyx_ErrRestore(type, value, tb) __Pyx_ErrRestoreInState(__pyx_tstate, type, value, tb) +#define __Pyx_ErrFetch(type, value, tb) __Pyx_ErrFetchInState(__pyx_tstate, type, value, tb) +static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); +static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030C00A6 +#define __Pyx_PyErr_SetNone(exc) (Py_INCREF(exc), __Pyx_ErrRestore((exc), NULL, NULL)) +#else +#define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) +#endif +#else +#define __Pyx_PyErr_Clear() PyErr_Clear() +#define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) +#define __Pyx_ErrRestoreWithState(type, value, tb) PyErr_Restore(type, value, tb) +#define __Pyx_ErrFetchWithState(type, value, tb) PyErr_Fetch(type, value, tb) +#define __Pyx_ErrRestoreInState(tstate, type, value, tb) PyErr_Restore(type, value, tb) +#define __Pyx_ErrFetchInState(tstate, type, value, tb) PyErr_Fetch(type, value, tb) +#define __Pyx_ErrRestore(type, value, tb) PyErr_Restore(type, value, tb) +#define __Pyx_ErrFetch(type, value, tb) PyErr_Fetch(type, value, tb) +#endif + +/* PyObjectGetAttrStr.proto (used by PyObjectGetAttrStrNoError) */ +#if CYTHON_USE_TYPE_SLOTS +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name); +#else +#define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) +#endif + +/* PyObjectGetAttrStrNoError.proto (used by GetBuiltinName) */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStrNoError(PyObject* obj, PyObject* attr_name); + +/* GetBuiltinName.proto */ +static PyObject *__Pyx_GetBuiltinName(PyObject *name); + +/* GetItemInt.proto */ +#define __Pyx_GetItemInt(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck, has_gil, unsafe_shared)\ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ + __Pyx_GetItemInt_Fast(o, (Py_ssize_t)i, is_list, wraparound, boundscheck, unsafe_shared) :\ + (is_list ? (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL) :\ + __Pyx_GetItemInt_Generic(o, to_py_func(i)))) +#define __Pyx_GetItemInt_List(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck, has_gil, unsafe_shared)\ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ + __Pyx_GetItemInt_List_Fast(o, (Py_ssize_t)i, wraparound, boundscheck, unsafe_shared) :\ + (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL)) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck, int unsafe_shared); +#define __Pyx_GetItemInt_Tuple(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck, has_gil, unsafe_shared)\ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ + __Pyx_GetItemInt_Tuple_Fast(o, (Py_ssize_t)i, wraparound, boundscheck, unsafe_shared) :\ + (PyErr_SetString(PyExc_IndexError, "tuple index out of range"), (PyObject*)NULL)) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck, int unsafe_shared); +static PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j); +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, + int is_list, int wraparound, int boundscheck, int unsafe_shared); + +/* IterFinish.proto (used by dict_iter) */ +static CYTHON_INLINE int __Pyx_IterFinish(void); + +/* PyObjectCall.proto (used by PyObjectFastCall) */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw); +#else +#define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw) +#endif + +/* PyObjectCallMethO.proto (used by PyObjectFastCall) */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg); +#endif + +/* PyObjectFastCall.proto (used by PyObjectCallNoArg) */ +#define __Pyx_PyObject_FastCall(func, args, nargs) __Pyx_PyObject_FastCallDict(func, args, (size_t)(nargs), NULL) +static CYTHON_INLINE PyObject* __Pyx_PyObject_FastCallDict(PyObject *func, PyObject * const*args, size_t nargs, PyObject *kwargs); + +/* PyObjectCallNoArg.proto (used by PyObjectCallMethod0) */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func); + +/* PyObjectCallOneArg.proto (used by PyObjectCallMethod0) */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg); + +/* PyObjectGetMethod.proto (used by PyObjectCallMethod0) */ +#if !(CYTHON_VECTORCALL && (__PYX_LIMITED_VERSION_HEX >= 0x030C0000 || (!CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x03090000))) +static int __Pyx_PyObject_GetMethod(PyObject *obj, PyObject *name, PyObject **method); +#endif + +/* PyObjectCallMethod0.proto (used by dict_iter) */ +static PyObject* __Pyx_PyObject_CallMethod0(PyObject* obj, PyObject* method_name); + +/* RaiseNeedMoreValuesToUnpack.proto (used by UnpackTuple2) */ +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); + +/* RaiseTooManyValuesToUnpack.proto (used by UnpackItemEndCheck) */ +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); + +/* UnpackItemEndCheck.proto (used by UnpackTuple2) */ +static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected); + +/* RaiseNoneIterError.proto (used by UnpackTupleError) */ +static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); + +/* UnpackTupleError.proto (used by UnpackTuple2) */ +static void __Pyx_UnpackTupleError(PyObject *, Py_ssize_t index); + +/* UnpackTuple2.proto (used by dict_iter) */ +static CYTHON_INLINE int __Pyx_unpack_tuple2( + PyObject* tuple, PyObject** value1, PyObject** value2, int is_tuple, int has_known_size, int decref_tuple); +static CYTHON_INLINE int __Pyx_unpack_tuple2_exact( + PyObject* tuple, PyObject** value1, PyObject** value2, int decref_tuple); +static int __Pyx_unpack_tuple2_generic( + PyObject* tuple, PyObject** value1, PyObject** value2, int has_known_size, int decref_tuple); + +/* dict_iter.proto */ +static CYTHON_INLINE PyObject* __Pyx_dict_iterator(PyObject* dict, int is_dict, PyObject* method_name, + Py_ssize_t* p_orig_length, int* p_is_dict); +static CYTHON_INLINE int __Pyx_dict_iter_next(PyObject* dict_or_iter, Py_ssize_t orig_length, Py_ssize_t* ppos, + PyObject** pkey, PyObject** pvalue, PyObject** pitem, int is_dict); + +/* RaiseUnexpectedTypeError.proto */ +static int __Pyx_RaiseUnexpectedTypeError(const char *expected, PyObject *obj); + +/* PyDictContains.proto */ +static CYTHON_INLINE int __Pyx_PyDict_ContainsTF(PyObject* item, PyObject* dict, int eq) { + int result = PyDict_Contains(dict, item); + return unlikely(result < 0) ? result : (result == (eq == Py_EQ)); +} + +/* DictGetItem.proto */ +#if !CYTHON_COMPILING_IN_PYPY +static PyObject *__Pyx_PyDict_GetItem(PyObject *d, PyObject* key); +#define __Pyx_PyObject_Dict_GetItem(obj, name)\ + (likely(PyDict_CheckExact(obj)) ?\ + __Pyx_PyDict_GetItem(obj, name) : PyObject_GetItem(obj, name)) +#else +#define __Pyx_PyDict_GetItem(d, key) PyObject_GetItem(d, key) +#define __Pyx_PyObject_Dict_GetItem(obj, name) PyObject_GetItem(obj, name) +#endif + +/* PyDictVersioning.proto (used by GetModuleGlobalName) */ +#if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_TYPE_SLOTS +#define __PYX_DICT_VERSION_INIT ((PY_UINT64_T) -1) +#define __PYX_GET_DICT_VERSION(dict) (((PyDictObject*)(dict))->ma_version_tag) +#define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var)\ + (version_var) = __PYX_GET_DICT_VERSION(dict);\ + (cache_var) = (value); +#define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) {\ + static PY_UINT64_T __pyx_dict_version = 0;\ + static PyObject *__pyx_dict_cached_value = NULL;\ + if (likely(__PYX_GET_DICT_VERSION(DICT) == __pyx_dict_version)) {\ + (VAR) = __Pyx_XNewRef(__pyx_dict_cached_value);\ + } else {\ + (VAR) = __pyx_dict_cached_value = (LOOKUP);\ + __pyx_dict_version = __PYX_GET_DICT_VERSION(DICT);\ + }\ +} +static CYTHON_INLINE PY_UINT64_T __Pyx_get_tp_dict_version(PyObject *obj); +static CYTHON_INLINE PY_UINT64_T __Pyx_get_object_dict_version(PyObject *obj); +static CYTHON_INLINE int __Pyx_object_dict_version_matches(PyObject* obj, PY_UINT64_T tp_dict_version, PY_UINT64_T obj_dict_version); +#else +#define __PYX_GET_DICT_VERSION(dict) (0) +#define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var) +#define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) (VAR) = (LOOKUP); +#endif + +/* GetModuleGlobalName.proto */ +#if CYTHON_USE_DICT_VERSIONS +#define __Pyx_GetModuleGlobalName(var, name) do {\ + static PY_UINT64_T __pyx_dict_version = 0;\ + static PyObject *__pyx_dict_cached_value = NULL;\ + (var) = (likely(__pyx_dict_version == __PYX_GET_DICT_VERSION(__pyx_mstate_global->__pyx_d))) ?\ + (likely(__pyx_dict_cached_value) ? __Pyx_NewRef(__pyx_dict_cached_value) : __Pyx_GetBuiltinName(name)) :\ + __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\ +} while(0) +#define __Pyx_GetModuleGlobalNameUncached(var, name) do {\ + PY_UINT64_T __pyx_dict_version;\ + PyObject *__pyx_dict_cached_value;\ + (var) = __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\ +} while(0) +static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_version, PyObject **dict_cached_value); +#else +#define __Pyx_GetModuleGlobalName(var, name) (var) = __Pyx__GetModuleGlobalName(name) +#define __Pyx_GetModuleGlobalNameUncached(var, name) (var) = __Pyx__GetModuleGlobalName(name) +static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name); +#endif + +/* PySequenceContains.proto */ +static CYTHON_INLINE int __Pyx_PySequence_ContainsTF(PyObject* item, PyObject* seq, int eq) { + int result = PySequence_Contains(seq, item); + return unlikely(result < 0) ? result : (result == (eq == Py_EQ)); +} + +/* GetAttr3.proto */ +static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *, PyObject *, PyObject *); + +/* GetTopmostException.proto (used by SaveResetException) */ +#if CYTHON_USE_EXC_INFO_STACK && CYTHON_FAST_THREAD_STATE +static _PyErr_StackItem * __Pyx_PyErr_GetTopmostException(PyThreadState *tstate); +#endif + +/* SaveResetException.proto */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_ExceptionSave(type, value, tb) __Pyx__ExceptionSave(__pyx_tstate, type, value, tb) +static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); +#define __Pyx_ExceptionReset(type, value, tb) __Pyx__ExceptionReset(__pyx_tstate, type, value, tb) +static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); +#else +#define __Pyx_ExceptionSave(type, value, tb) PyErr_GetExcInfo(type, value, tb) +#define __Pyx_ExceptionReset(type, value, tb) PyErr_SetExcInfo(type, value, tb) +#endif + +/* PyTypeError_Check.proto */ +#define __Pyx_PyExc_TypeError_Check(obj) __Pyx_TypeCheck(obj, PyExc_TypeError) + +/* PyAttributeError_Check.proto */ +#define __Pyx_PyExc_AttributeError_Check(obj) __Pyx_TypeCheck(obj, PyExc_AttributeError) + +/* PyAssertionError_Check.proto */ +#define __Pyx_PyExc_AssertionError_Check(obj) __Pyx_TypeCheck(obj, PyExc_AssertionError) + +/* PyOverflowError_Check.proto */ +#define __Pyx_PyExc_OverflowError_Check(obj) __Pyx_TypeCheck(obj, PyExc_OverflowError) + +/* GetException.proto */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_GetException(type, value, tb) __Pyx__GetException(__pyx_tstate, type, value, tb) +static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); +#else +static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb); +#endif + +/* RaiseException.export */ +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); + +/* SwapException.proto */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_ExceptionSwap(type, value, tb) __Pyx__ExceptionSwap(__pyx_tstate, type, value, tb) +static CYTHON_INLINE void __Pyx__ExceptionSwap(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); +#else +static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb); +#endif + +/* IncludeStringH.proto (used by decode_c_string) */ +#include + +/* decode_c_string_utf16.proto (used by decode_c_string) */ +static CYTHON_INLINE PyObject *__Pyx_PyUnicode_DecodeUTF16(const char *s, Py_ssize_t size, const char *errors) { + int byteorder = 0; + return PyUnicode_DecodeUTF16(s, size, errors, &byteorder); +} +static CYTHON_INLINE PyObject *__Pyx_PyUnicode_DecodeUTF16LE(const char *s, Py_ssize_t size, const char *errors) { + int byteorder = -1; + return PyUnicode_DecodeUTF16(s, size, errors, &byteorder); +} +static CYTHON_INLINE PyObject *__Pyx_PyUnicode_DecodeUTF16BE(const char *s, Py_ssize_t size, const char *errors) { + int byteorder = 1; + return PyUnicode_DecodeUTF16(s, size, errors, &byteorder); +} + +/* decode_c_string.proto */ +static CYTHON_INLINE PyObject* __Pyx_decode_c_string( + const char* cstring, Py_ssize_t start, Py_ssize_t stop, + const char* encoding, const char* errors, + PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)); + +/* ListCompAppend.proto */ +#if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS +static CYTHON_INLINE int __Pyx_ListComp_Append(PyObject* list, PyObject* x) { + PyListObject* L = (PyListObject*) list; + Py_ssize_t len = Py_SIZE(list); + if (likely(L->allocated > len)) { + Py_INCREF(x); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030d0000 + L->ob_item[len] = x; + #else + PyList_SET_ITEM(list, len, x); + #endif + __Pyx_SET_SIZE(list, len + 1); + return 0; + } + return PyList_Append(list, x); +} +#else +#define __Pyx_ListComp_Append(L,x) PyList_Append(L,x) +#endif + +/* PyObjectFastCallMethod.proto */ +#if CYTHON_VECTORCALL && PY_VERSION_HEX >= 0x03090000 +#define __Pyx_PyObject_FastCallMethod(name, args, nargsf) PyObject_VectorcallMethod(name, args, nargsf, NULL) +#else +static PyObject *__Pyx_PyObject_FastCallMethod(PyObject *name, PyObject *const *args, size_t nargsf); +#endif + +/* TupleAndListFromArray.proto (used by fastcall) */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyList_FromArray(PyObject *const *src, Py_ssize_t n); +#endif +#if CYTHON_COMPILING_IN_CPYTHON || CYTHON_METH_FASTCALL +static CYTHON_INLINE PyObject* __Pyx_PyTuple_FromArray(PyObject *const *src, Py_ssize_t n); +#endif + +/* BytesEquals.proto (used by UnicodeEquals) */ +static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals); + +/* UnicodeEquals.proto (used by fastcall) */ +static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals); + +/* fastcall.proto */ +#if CYTHON_AVOID_BORROWED_REFS + #define __Pyx_ArgRef_VARARGS(args, i) __Pyx_PySequence_ITEM(args, i) +#elif CYTHON_ASSUME_SAFE_MACROS + #define __Pyx_ArgRef_VARARGS(args, i) __Pyx_NewRef(__Pyx_PyTuple_GET_ITEM(args, i)) +#else + #define __Pyx_ArgRef_VARARGS(args, i) __Pyx_XNewRef(PyTuple_GetItem(args, i)) +#endif +#define __Pyx_NumKwargs_VARARGS(kwds) PyDict_Size(kwds) +#define __Pyx_KwValues_VARARGS(args, nargs) NULL +#define __Pyx_GetKwValue_VARARGS(kw, kwvalues, s) __Pyx_PyDict_GetItemStrWithError(kw, s) +#define __Pyx_KwargsAsDict_VARARGS(kw, kwvalues) PyDict_Copy(kw) +#if CYTHON_METH_FASTCALL + #define __Pyx_ArgRef_FASTCALL(args, i) __Pyx_NewRef(args[i]) + #define __Pyx_NumKwargs_FASTCALL(kwds) __Pyx_PyTuple_GET_SIZE(kwds) + #define __Pyx_KwValues_FASTCALL(args, nargs) ((args) + (nargs)) + static CYTHON_INLINE PyObject * __Pyx_GetKwValue_FASTCALL(PyObject *kwnames, PyObject *const *kwvalues, PyObject *s); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030d0000 || CYTHON_COMPILING_IN_LIMITED_API + CYTHON_UNUSED static PyObject *__Pyx_KwargsAsDict_FASTCALL(PyObject *kwnames, PyObject *const *kwvalues); + #else + #define __Pyx_KwargsAsDict_FASTCALL(kw, kwvalues) _PyStack_AsDict(kwvalues, kw) + #endif +#else + #define __Pyx_ArgRef_FASTCALL __Pyx_ArgRef_VARARGS + #define __Pyx_NumKwargs_FASTCALL __Pyx_NumKwargs_VARARGS + #define __Pyx_KwValues_FASTCALL __Pyx_KwValues_VARARGS + #define __Pyx_GetKwValue_FASTCALL __Pyx_GetKwValue_VARARGS + #define __Pyx_KwargsAsDict_FASTCALL __Pyx_KwargsAsDict_VARARGS +#endif +#define __Pyx_ArgsSlice_VARARGS(args, start, stop) PyTuple_GetSlice(args, start, stop) +#if CYTHON_METH_FASTCALL || (CYTHON_COMPILING_IN_CPYTHON && CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS) +#define __Pyx_ArgsSlice_FASTCALL(args, start, stop) __Pyx_PyTuple_FromArray(args + start, stop - start) +#else +#define __Pyx_ArgsSlice_FASTCALL(args, start, stop) PyTuple_GetSlice(args, start, stop) +#endif + +/* py_dict_items.proto (used by OwnedDictNext) */ +static CYTHON_INLINE PyObject* __Pyx_PyDict_Items(PyObject* d); + +/* CallCFunction.proto (used by CallUnboundCMethod0) */ +#define __Pyx_CallCFunction(cfunc, self, args)\ + ((PyCFunction)(void(*)(void))(cfunc)->func)(self, args) +#define __Pyx_CallCFunctionWithKeywords(cfunc, self, args, kwargs)\ + ((PyCFunctionWithKeywords)(void(*)(void))(cfunc)->func)(self, args, kwargs) +#define __Pyx_CallCFunctionFast(cfunc, self, args, nargs)\ + ((__Pyx_PyCFunctionFast)(void(*)(void))(PyCFunction)(cfunc)->func)(self, args, nargs) +#define __Pyx_CallCFunctionFastWithKeywords(cfunc, self, args, nargs, kwnames)\ + ((__Pyx_PyCFunctionFastWithKeywords)(void(*)(void))(PyCFunction)(cfunc)->func)(self, args, nargs, kwnames) + +/* UnpackUnboundCMethod.proto (used by CallUnboundCMethod0) */ +typedef struct { + PyObject *type; + PyObject **method_name; +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING && CYTHON_ATOMICS + __pyx_atomic_int_type initialized; +#endif + PyCFunction func; + PyObject *method; + int flag; +} __Pyx_CachedCFunction; +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING +static CYTHON_INLINE int __Pyx_CachedCFunction_GetAndSetInitializing(__Pyx_CachedCFunction *cfunc) { +#if !CYTHON_ATOMICS + return 1; +#else + __pyx_nonatomic_int_type expected = 0; + if (__pyx_atomic_int_cmp_exchange(&cfunc->initialized, &expected, 1)) { + return 0; + } + return expected; +#endif +} +static CYTHON_INLINE void __Pyx_CachedCFunction_SetFinishedInitializing(__Pyx_CachedCFunction *cfunc) { +#if CYTHON_ATOMICS + __pyx_atomic_store(&cfunc->initialized, 2); +#endif +} +#else +#define __Pyx_CachedCFunction_GetAndSetInitializing(cfunc) 2 +#define __Pyx_CachedCFunction_SetFinishedInitializing(cfunc) +#endif + +/* CallUnboundCMethod0.proto */ +CYTHON_UNUSED +static PyObject* __Pyx__CallUnboundCMethod0(__Pyx_CachedCFunction* cfunc, PyObject* self); +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_CallUnboundCMethod0(__Pyx_CachedCFunction* cfunc, PyObject* self); +#else +#define __Pyx_CallUnboundCMethod0(cfunc, self) __Pyx__CallUnboundCMethod0(cfunc, self) +#endif + +/* py_dict_values.proto (used by OwnedDictNext) */ +static CYTHON_INLINE PyObject* __Pyx_PyDict_Values(PyObject* d); + +/* OwnedDictNext.proto (used by ParseKeywordsImpl) */ +#if CYTHON_AVOID_BORROWED_REFS +static int __Pyx_PyDict_NextRef(PyObject *p, PyObject **ppos, PyObject **pkey, PyObject **pvalue); +#else +CYTHON_INLINE +static int __Pyx_PyDict_NextRef(PyObject *p, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue); +#endif + +/* RaiseDoubleKeywords.proto (used by ParseKeywordsImpl) */ +static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); + +/* ParseKeywordsImpl.export */ +static int __Pyx_ParseKeywordsTuple( + PyObject *kwds, + PyObject * const *kwvalues, + PyObject ** const argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + Py_ssize_t num_kwargs, + const char* function_name, + int ignore_unknown_kwargs +); +static int __Pyx_ParseKeywordDictToDict( + PyObject *kwds, + PyObject ** const argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + const char* function_name +); +static int __Pyx_ParseKeywordDict( + PyObject *kwds, + PyObject ** const argnames[], + PyObject *values[], + Py_ssize_t num_pos_args, + Py_ssize_t num_kwargs, + const char* function_name, + int ignore_unknown_kwargs +); + +/* CallUnboundCMethod2.proto */ +CYTHON_UNUSED +static PyObject* __Pyx__CallUnboundCMethod2(__Pyx_CachedCFunction* cfunc, PyObject* self, PyObject* arg1, PyObject* arg2); +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject *__Pyx_CallUnboundCMethod2(__Pyx_CachedCFunction *cfunc, PyObject *self, PyObject *arg1, PyObject *arg2); +#else +#define __Pyx_CallUnboundCMethod2(cfunc, self, arg1, arg2) __Pyx__CallUnboundCMethod2(cfunc, self, arg1, arg2) +#endif + +/* ParseKeywords.proto */ +static CYTHON_INLINE int __Pyx_ParseKeywords( + PyObject *kwds, PyObject *const *kwvalues, PyObject ** const argnames[], + PyObject *kwds2, PyObject *values[], + Py_ssize_t num_pos_args, Py_ssize_t num_kwargs, + const char* function_name, + int ignore_unknown_kwargs +); + +/* RaiseArgTupleInvalid.proto */ +static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, + Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); + +/* ArgTypeTestFunc.export */ +static int __Pyx__ArgTypeTest(PyObject *obj, PyTypeObject *type, const char *name, int exact); + +/* ArgTypeTest.proto */ +#define __Pyx_ArgTypeTest(obj, type, none_allowed, name, exact)\ + ((likely(__Pyx_IS_TYPE(obj, type) | (none_allowed && (obj == Py_None)))) ? 1 :\ + __Pyx__ArgTypeTest(obj, type, name, exact)) + +/* ExtTypeTest.proto */ +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); + +/* RejectKeywords.export */ +static void __Pyx_RejectKeywords(const char* function_name, PyObject *kwds); + +/* PyObjectDelAttr.proto (used by PyObjectSetAttrStr) */ +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030d0000 +#define __Pyx_PyObject_DelAttr(o, n) PyObject_SetAttr(o, n, NULL) +#else +#define __Pyx_PyObject_DelAttr(o, n) PyObject_DelAttr(o, n) +#endif + +/* PyObjectSetAttrStr.proto */ +#if CYTHON_USE_TYPE_SLOTS +#define __Pyx_PyObject_DelAttrStr(o,n) __Pyx_PyObject_SetAttrStr(o, n, NULL) +static CYTHON_INLINE int __Pyx_PyObject_SetAttrStr(PyObject* obj, PyObject* attr_name, PyObject* value); +#else +#define __Pyx_PyObject_DelAttrStr(o,n) __Pyx_PyObject_DelAttr(o,n) +#define __Pyx_PyObject_SetAttrStr(o,n,v) PyObject_SetAttr(o,n,v) +#endif + +/* AllocateExtensionType.proto */ +static PyObject *__Pyx_AllocateExtensionType(PyTypeObject *t, int is_final); + +/* CallTypeTraverse.proto */ +#if !CYTHON_USE_TYPE_SPECS || (!CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x03090000) +#define __Pyx_call_type_traverse(o, always_call, visit, arg) 0 +#else +static int __Pyx_call_type_traverse(PyObject *o, int always_call, visitproc visit, void *arg); +#endif + +/* LimitedApiGetTypeDict.proto (used by SetItemOnTypeDict) */ +#if CYTHON_COMPILING_IN_LIMITED_API +static PyObject *__Pyx_GetTypeDict(PyTypeObject *tp); +#endif + +/* SetItemOnTypeDict.proto (used by FixUpExtensionType) */ +static int __Pyx__SetItemOnTypeDict(PyTypeObject *tp, PyObject *k, PyObject *v); +#define __Pyx_SetItemOnTypeDict(tp, k, v) __Pyx__SetItemOnTypeDict((PyTypeObject*)tp, k, v) + +/* FixUpExtensionType.proto */ +static CYTHON_INLINE int __Pyx_fix_up_extension_type_from_spec(PyType_Spec *spec, PyTypeObject *type); + +/* ValidateBasesTuple.proto (used by PyType_Ready) */ +#if CYTHON_COMPILING_IN_CPYTHON || CYTHON_COMPILING_IN_LIMITED_API || CYTHON_USE_TYPE_SPECS +static int __Pyx_validate_bases_tuple(const char *type_name, Py_ssize_t dictoffset, PyObject *bases); +#endif + +/* PyType_Ready.proto */ +CYTHON_UNUSED static int __Pyx_PyType_Ready(PyTypeObject *t); + +/* DelItemOnTypeDict.proto (used by SetupReduce) */ +static int __Pyx__DelItemOnTypeDict(PyTypeObject *tp, PyObject *k); +#define __Pyx_DelItemOnTypeDict(tp, k) __Pyx__DelItemOnTypeDict((PyTypeObject*)tp, k) + +/* SetupReduce.proto */ +static int __Pyx_setup_reduce(PyObject* type_obj); + +/* TypeImport.proto */ +#ifndef __PYX_HAVE_RT_ImportType_proto_3_2_4 +#define __PYX_HAVE_RT_ImportType_proto_3_2_4 +#if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 201112L +#include +#endif +#if (defined (__STDC_VERSION__) && __STDC_VERSION__ >= 201112L) || __cplusplus >= 201103L +#define __PYX_GET_STRUCT_ALIGNMENT_3_2_4(s) alignof(s) +#else +#define __PYX_GET_STRUCT_ALIGNMENT_3_2_4(s) sizeof(void*) +#endif +enum __Pyx_ImportType_CheckSize_3_2_4 { + __Pyx_ImportType_CheckSize_Error_3_2_4 = 0, + __Pyx_ImportType_CheckSize_Warn_3_2_4 = 1, + __Pyx_ImportType_CheckSize_Ignore_3_2_4 = 2 +}; +static PyTypeObject *__Pyx_ImportType_3_2_4(PyObject* module, const char *module_name, const char *class_name, size_t size, size_t alignment, enum __Pyx_ImportType_CheckSize_3_2_4 check_size); +#endif + +/* GetVTable.proto */ +static void* __Pyx_GetVtable(PyTypeObject *type); + +/* HasAttr.proto (used by ImportImpl) */ +#if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 +#define __Pyx_HasAttr(o, n) PyObject_HasAttrWithError(o, n) +#else +static CYTHON_INLINE int __Pyx_HasAttr(PyObject *, PyObject *); +#endif + +/* ImportImpl.export */ +static PyObject *__Pyx__Import(PyObject *name, PyObject *const *imported_names, Py_ssize_t len_imported_names, PyObject *qualname, PyObject *moddict, int level); + +/* Import.proto */ +static CYTHON_INLINE PyObject *__Pyx_Import(PyObject *name, PyObject *const *imported_names, Py_ssize_t len_imported_names, PyObject *qualname, int level); + +/* ImportFrom.proto */ +static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name); + +/* Py3UpdateBases.proto */ +static PyObject* __Pyx_PEP560_update_bases(PyObject *bases); + +/* CalculateMetaclass.proto */ +static PyObject *__Pyx_CalculateMetaclass(PyTypeObject *metaclass, PyObject *bases); + +/* PyObjectCall2Args.proto (used by Py3ClassCreate) */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call2Args(PyObject* function, PyObject* arg1, PyObject* arg2); + +/* PyObjectLookupSpecial.proto (used by Py3ClassCreate) */ +#if CYTHON_USE_PYTYPE_LOOKUP && CYTHON_USE_TYPE_SLOTS +#define __Pyx_PyObject_LookupSpecialNoError(obj, attr_name) __Pyx__PyObject_LookupSpecial(obj, attr_name, 0) +#define __Pyx_PyObject_LookupSpecial(obj, attr_name) __Pyx__PyObject_LookupSpecial(obj, attr_name, 1) +static CYTHON_INLINE PyObject* __Pyx__PyObject_LookupSpecial(PyObject* obj, PyObject* attr_name, int with_error); +#else +#define __Pyx_PyObject_LookupSpecialNoError(o,n) __Pyx_PyObject_GetAttrStrNoError(o,n) +#define __Pyx_PyObject_LookupSpecial(o,n) __Pyx_PyObject_GetAttrStr(o,n) +#endif + +/* Py3ClassCreate.proto */ +static PyObject *__Pyx_Py3MetaclassPrepare(PyObject *metaclass, PyObject *bases, PyObject *name, PyObject *qualname, + PyObject *mkw, PyObject *modname, PyObject *doc); +static PyObject *__Pyx_Py3ClassCreate(PyObject *metaclass, PyObject *name, PyObject *bases, PyObject *dict, + PyObject *mkw, int calculate_metaclass, int allow_py2_metaclass); + +/* dict_setdefault.proto (used by FetchCommonType) */ +static CYTHON_INLINE PyObject *__Pyx_PyDict_SetDefault(PyObject *d, PyObject *key, PyObject *default_value); + +/* AddModuleRef.proto (used by FetchSharedCythonModule) */ +#if ((CYTHON_COMPILING_IN_CPYTHON_FREETHREADING ) ||\ + __PYX_LIMITED_VERSION_HEX < 0x030d0000) + static PyObject *__Pyx_PyImport_AddModuleRef(const char *name); +#else + #define __Pyx_PyImport_AddModuleRef(name) PyImport_AddModuleRef(name) +#endif + +/* FetchSharedCythonModule.proto (used by FetchCommonType) */ +static PyObject *__Pyx_FetchSharedCythonABIModule(void); + +/* FetchCommonType.proto (used by CommonTypesMetaclass) */ +static PyTypeObject* __Pyx_FetchCommonTypeFromSpec(PyTypeObject *metaclass, PyObject *module, PyType_Spec *spec, PyObject *bases); + +/* CommonTypesMetaclass.proto (used by CythonFunctionShared) */ +static int __pyx_CommonTypesMetaclass_init(PyObject *module); +#define __Pyx_CommonTypesMetaclass_USED + +/* PyMethodNew.proto (used by CythonFunctionShared) */ +static PyObject *__Pyx_PyMethod_New(PyObject *func, PyObject *self, PyObject *typ); + +/* PyVectorcallFastCallDict.proto (used by CythonFunctionShared) */ +#if CYTHON_METH_FASTCALL && CYTHON_VECTORCALL +static CYTHON_INLINE PyObject *__Pyx_PyVectorcall_FastCallDict(PyObject *func, __pyx_vectorcallfunc vc, PyObject *const *args, size_t nargs, PyObject *kw); +#endif + +/* CythonFunctionShared.proto (used by CythonFunction) */ +#define __Pyx_CyFunction_USED +#define __Pyx_CYFUNCTION_STATICMETHOD 0x01 +#define __Pyx_CYFUNCTION_CLASSMETHOD 0x02 +#define __Pyx_CYFUNCTION_CCLASS 0x04 +#define __Pyx_CYFUNCTION_COROUTINE 0x08 +#define __Pyx_CyFunction_GetClosure(f)\ + (((__pyx_CyFunctionObject *) (f))->func_closure) +#if PY_VERSION_HEX < 0x030900B1 || CYTHON_COMPILING_IN_LIMITED_API + #define __Pyx_CyFunction_GetClassObj(f)\ + (((__pyx_CyFunctionObject *) (f))->func_classobj) +#else + #define __Pyx_CyFunction_GetClassObj(f)\ + ((PyObject*) ((PyCMethodObject *) (f))->mm_class) +#endif +#define __Pyx_CyFunction_SetClassObj(f, classobj)\ + __Pyx__CyFunction_SetClassObj((__pyx_CyFunctionObject *) (f), (classobj)) +#define __Pyx_CyFunction_Defaults(type, f)\ + ((type *)(((__pyx_CyFunctionObject *) (f))->defaults)) +#define __Pyx_CyFunction_SetDefaultsGetter(f, g)\ + ((__pyx_CyFunctionObject *) (f))->defaults_getter = (g) +typedef struct { +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject_HEAD + PyObject *func; +#elif PY_VERSION_HEX < 0x030900B1 + PyCFunctionObject func; +#else + PyCMethodObject func; +#endif +#if CYTHON_COMPILING_IN_LIMITED_API && CYTHON_METH_FASTCALL + __pyx_vectorcallfunc func_vectorcall; +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *func_weakreflist; +#endif +#if PY_VERSION_HEX < 0x030C0000 || CYTHON_COMPILING_IN_LIMITED_API + PyObject *func_dict; +#endif + PyObject *func_name; + PyObject *func_qualname; + PyObject *func_doc; + PyObject *func_globals; + PyObject *func_code; + PyObject *func_closure; +#if PY_VERSION_HEX < 0x030900B1 || CYTHON_COMPILING_IN_LIMITED_API + PyObject *func_classobj; +#endif + PyObject *defaults; + int flags; + PyObject *defaults_tuple; + PyObject *defaults_kwdict; + PyObject *(*defaults_getter)(PyObject *); + PyObject *func_annotations; + PyObject *func_is_coroutine; +} __pyx_CyFunctionObject; +#undef __Pyx_CyOrPyCFunction_Check +#define __Pyx_CyFunction_Check(obj) __Pyx_TypeCheck(obj, __pyx_mstate_global->__pyx_CyFunctionType) +#define __Pyx_CyOrPyCFunction_Check(obj) __Pyx_TypeCheck2(obj, __pyx_mstate_global->__pyx_CyFunctionType, &PyCFunction_Type) +#define __Pyx_CyFunction_CheckExact(obj) __Pyx_IS_TYPE(obj, __pyx_mstate_global->__pyx_CyFunctionType) +static CYTHON_INLINE int __Pyx__IsSameCyOrCFunction(PyObject *func, void (*cfunc)(void)); +#undef __Pyx_IsSameCFunction +#define __Pyx_IsSameCFunction(func, cfunc) __Pyx__IsSameCyOrCFunction(func, cfunc) +static PyObject *__Pyx_CyFunction_Init(__pyx_CyFunctionObject* op, PyMethodDef *ml, + int flags, PyObject* qualname, + PyObject *closure, + PyObject *module, PyObject *globals, + PyObject* code); +static CYTHON_INLINE void __Pyx__CyFunction_SetClassObj(__pyx_CyFunctionObject* f, PyObject* classobj); +static CYTHON_INLINE PyObject *__Pyx_CyFunction_InitDefaults(PyObject *func, + PyTypeObject *defaults_type); +static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsTuple(PyObject *m, + PyObject *tuple); +static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsKwDict(PyObject *m, + PyObject *dict); +static CYTHON_INLINE void __Pyx_CyFunction_SetAnnotationsDict(PyObject *m, + PyObject *dict); +static int __pyx_CyFunction_init(PyObject *module); +#if CYTHON_METH_FASTCALL +static PyObject * __Pyx_CyFunction_Vectorcall_NOARGS(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames); +static PyObject * __Pyx_CyFunction_Vectorcall_O(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames); +static PyObject * __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames); +static PyObject * __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS_METHOD(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames); +#if CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_CyFunction_func_vectorcall(f) (((__pyx_CyFunctionObject*)f)->func_vectorcall) +#else +#define __Pyx_CyFunction_func_vectorcall(f) (((PyCFunctionObject*)f)->vectorcall) +#endif +#endif + +/* CythonFunction.proto */ +static PyObject *__Pyx_CyFunction_New(PyMethodDef *ml, + int flags, PyObject* qualname, + PyObject *closure, + PyObject *module, PyObject *globals, + PyObject* code); + +/* SetNameInClass.proto */ +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030d0000 +#define __Pyx_SetNameInClass(ns, name, value)\ + (likely(PyDict_CheckExact(ns)) ? _PyDict_SetItem_KnownHash(ns, name, value, ((PyASCIIObject *) name)->hash) : PyObject_SetItem(ns, name, value)) +#elif CYTHON_COMPILING_IN_CPYTHON +#define __Pyx_SetNameInClass(ns, name, value)\ + (likely(PyDict_CheckExact(ns)) ? PyDict_SetItem(ns, name, value) : PyObject_SetItem(ns, name, value)) +#else +#define __Pyx_SetNameInClass(ns, name, value) PyObject_SetItem(ns, name, value) +#endif + +/* CLineInTraceback.proto (used by AddTraceback) */ +#if CYTHON_CLINE_IN_TRACEBACK && CYTHON_CLINE_IN_TRACEBACK_RUNTIME +static int __Pyx_CLineForTraceback(PyThreadState *tstate, int c_line); +#else +#define __Pyx_CLineForTraceback(tstate, c_line) (((CYTHON_CLINE_IN_TRACEBACK)) ? c_line : 0) +#endif + +/* CodeObjectCache.proto (used by AddTraceback) */ +#if CYTHON_COMPILING_IN_LIMITED_API +typedef PyObject __Pyx_CachedCodeObjectType; +#else +typedef PyCodeObject __Pyx_CachedCodeObjectType; +#endif +typedef struct { + __Pyx_CachedCodeObjectType* code_object; + int code_line; +} __Pyx_CodeObjectCacheEntry; +struct __Pyx_CodeObjectCache { + int count; + int max_count; + __Pyx_CodeObjectCacheEntry* entries; + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + __pyx_atomic_int_type accessor_count; + #endif +}; +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); +static __Pyx_CachedCodeObjectType *__pyx_find_code_object(int code_line); +static void __pyx_insert_code_object(int code_line, __Pyx_CachedCodeObjectType* code_object); + +/* AddTraceback.proto */ +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename); + +/* CheckUnpickleChecksum.proto */ +static CYTHON_INLINE int __Pyx_CheckUnpickleChecksum(long checksum, long checksum1, long checksum2, long checksum3, const char *members); + +/* GCCDiagnostics.proto */ +#if !defined(__INTEL_COMPILER) && defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) +#define __Pyx_HAS_GCC_DIAGNOSTIC +#endif + +/* PyObjectVectorCallKwBuilder.proto (used by CIntToPy) */ +CYTHON_UNUSED static int __Pyx_VectorcallBuilder_AddArg_Check(PyObject *key, PyObject *value, PyObject *builder, PyObject **args, int n); +#if CYTHON_VECTORCALL +#if PY_VERSION_HEX >= 0x03090000 +#define __Pyx_Object_Vectorcall_CallFromBuilder PyObject_Vectorcall +#else +#define __Pyx_Object_Vectorcall_CallFromBuilder _PyObject_Vectorcall +#endif +#define __Pyx_MakeVectorcallBuilderKwds(n) PyTuple_New(n) +static int __Pyx_VectorcallBuilder_AddArg(PyObject *key, PyObject *value, PyObject *builder, PyObject **args, int n); +static int __Pyx_VectorcallBuilder_AddArgStr(const char *key, PyObject *value, PyObject *builder, PyObject **args, int n); +#else +#define __Pyx_Object_Vectorcall_CallFromBuilder __Pyx_PyObject_FastCallDict +#define __Pyx_MakeVectorcallBuilderKwds(n) __Pyx_PyDict_NewPresized(n) +#define __Pyx_VectorcallBuilder_AddArg(key, value, builder, args, n) PyDict_SetItem(builder, key, value) +#define __Pyx_VectorcallBuilder_AddArgStr(key, value, builder, args, n) PyDict_SetItemString(builder, key, value) +#endif + +/* CIntToPy.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyLong_From___pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType(__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType value); + +/* CIntFromPy.proto */ +static CYTHON_INLINE __pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType __Pyx_PyLong_As___pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType(PyObject *); + +/* CIntFromPy.proto */ +static CYTHON_INLINE int32_t __Pyx_PyLong_As_int32_t(PyObject *); + +/* CIntFromPy.proto */ +static CYTHON_INLINE long __Pyx_PyLong_As_long(PyObject *); + +/* CIntToPy.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyLong_From_long(long value); + +/* CIntToPy.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyLong_From_int(int value); + +/* CIntFromPy.proto */ +static CYTHON_INLINE int __Pyx_PyLong_As_int(PyObject *); + +/* CIntToPy.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyLong_From_char(char value); + +/* CIntToPy.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyLong_From_int16_t(int16_t value); + +/* CIntToPy.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyLong_From_int32_t(int32_t value); + +/* CIntToPy.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyLong_From_int64_t(int64_t value); + +/* CIntFromPy.proto */ +static CYTHON_INLINE char __Pyx_PyLong_As_char(PyObject *); + +/* CIntFromPy.proto */ +static CYTHON_INLINE int16_t __Pyx_PyLong_As_int16_t(PyObject *); + +/* CIntFromPy.proto */ +static CYTHON_INLINE int64_t __Pyx_PyLong_As_int64_t(PyObject *); + +/* PyObjectCallMethod1.proto */ +static PyObject* __Pyx_PyObject_CallMethod1(PyObject* obj, PyObject* method_name, PyObject* arg); + +/* UpdateUnpickledDict.proto */ +static int __Pyx_UpdateUnpickledDict(PyObject *obj, PyObject *state, Py_ssize_t index); + +/* FormatTypeName.proto */ +#if CYTHON_COMPILING_IN_LIMITED_API +typedef PyObject *__Pyx_TypeName; +#define __Pyx_FMT_TYPENAME "%U" +#define __Pyx_DECREF_TypeName(obj) Py_XDECREF(obj) +#if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 +#define __Pyx_PyType_GetFullyQualifiedName PyType_GetFullyQualifiedName +#else +static __Pyx_TypeName __Pyx_PyType_GetFullyQualifiedName(PyTypeObject* tp); +#endif +#else // !LIMITED_API +typedef const char *__Pyx_TypeName; +#define __Pyx_FMT_TYPENAME "%.200s" +#define __Pyx_PyType_GetFullyQualifiedName(tp) ((tp)->tp_name) +#define __Pyx_DECREF_TypeName(obj) +#endif + +/* FastTypeChecks.proto */ +#if CYTHON_COMPILING_IN_CPYTHON +#define __Pyx_TypeCheck(obj, type) __Pyx_IsSubtype(Py_TYPE(obj), (PyTypeObject *)type) +#define __Pyx_TypeCheck2(obj, type1, type2) __Pyx_IsAnySubtype2(Py_TYPE(obj), (PyTypeObject *)type1, (PyTypeObject *)type2) +static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b); +static CYTHON_INLINE int __Pyx_IsAnySubtype2(PyTypeObject *cls, PyTypeObject *a, PyTypeObject *b); +static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches(PyObject *err, PyObject *type); +static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches2(PyObject *err, PyObject *type1, PyObject *type2); +#else +#define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) +#define __Pyx_TypeCheck2(obj, type1, type2) (PyObject_TypeCheck(obj, (PyTypeObject *)type1) || PyObject_TypeCheck(obj, (PyTypeObject *)type2)) +#define __Pyx_PyErr_GivenExceptionMatches(err, type) PyErr_GivenExceptionMatches(err, type) +static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches2(PyObject *err, PyObject *type1, PyObject *type2) { + return PyErr_GivenExceptionMatches(err, type1) || PyErr_GivenExceptionMatches(err, type2); +} +#endif +#define __Pyx_PyErr_ExceptionMatches2(err1, err2) __Pyx_PyErr_GivenExceptionMatches2(__Pyx_PyErr_CurrentExceptionType(), err1, err2) +#define __Pyx_PyException_Check(obj) __Pyx_TypeCheck(obj, PyExc_Exception) +#ifdef PyExceptionInstance_Check + #define __Pyx_PyBaseException_Check(obj) PyExceptionInstance_Check(obj) +#else + #define __Pyx_PyBaseException_Check(obj) __Pyx_TypeCheck(obj, PyExc_BaseException) +#endif + +/* GetRuntimeVersion.proto */ +#if __PYX_LIMITED_VERSION_HEX < 0x030b0000 +static unsigned long __Pyx_cached_runtime_version = 0; +static void __Pyx_init_runtime_version(void); +#else +#define __Pyx_init_runtime_version() +#endif +static unsigned long __Pyx_get_runtime_version(void); + +/* CheckBinaryVersion.proto */ +static int __Pyx_check_binary_version(unsigned long ct_version, unsigned long rt_version, int allow_newer); + +/* DecompressString.proto */ +static PyObject *__Pyx_DecompressString(const char *s, Py_ssize_t length, int algo); + +/* MultiPhaseInitModuleState.proto */ +#if CYTHON_PEP489_MULTI_PHASE_INIT && CYTHON_USE_MODULE_STATE +static PyObject *__Pyx_State_FindModule(void*); +static int __Pyx_State_AddModule(PyObject* module, void*); +static int __Pyx_State_RemoveModule(void*); +#elif CYTHON_USE_MODULE_STATE +#define __Pyx_State_FindModule PyState_FindModule +#define __Pyx_State_AddModule PyState_AddModule +#define __Pyx_State_RemoveModule PyState_RemoveModule +#endif + +/* #### Code section: module_declarations ### */ +/* CythonABIVersion.proto */ +#if CYTHON_COMPILING_IN_LIMITED_API + #if CYTHON_METH_FASTCALL + #define __PYX_FASTCALL_ABI_SUFFIX "_fastcall" + #else + #define __PYX_FASTCALL_ABI_SUFFIX + #endif + #define __PYX_LIMITED_ABI_SUFFIX "limited" __PYX_FASTCALL_ABI_SUFFIX __PYX_AM_SEND_ABI_SUFFIX +#else + #define __PYX_LIMITED_ABI_SUFFIX +#endif +#if __PYX_HAS_PY_AM_SEND == 1 + #define __PYX_AM_SEND_ABI_SUFFIX +#elif __PYX_HAS_PY_AM_SEND == 2 + #define __PYX_AM_SEND_ABI_SUFFIX "amsendbackport" +#else + #define __PYX_AM_SEND_ABI_SUFFIX "noamsend" +#endif +#ifndef __PYX_MONITORING_ABI_SUFFIX + #define __PYX_MONITORING_ABI_SUFFIX +#endif +#if CYTHON_USE_TP_FINALIZE + #define __PYX_TP_FINALIZE_ABI_SUFFIX +#else + #define __PYX_TP_FINALIZE_ABI_SUFFIX "nofinalize" +#endif +#if CYTHON_USE_FREELISTS || !defined(__Pyx_AsyncGen_USED) + #define __PYX_FREELISTS_ABI_SUFFIX +#else + #define __PYX_FREELISTS_ABI_SUFFIX "nofreelists" +#endif +#define CYTHON_ABI __PYX_ABI_VERSION __PYX_LIMITED_ABI_SUFFIX __PYX_MONITORING_ABI_SUFFIX __PYX_TP_FINALIZE_ABI_SUFFIX __PYX_FREELISTS_ABI_SUFFIX __PYX_AM_SEND_ABI_SUFFIX +#define __PYX_ABI_MODULE_NAME "_cython_" CYTHON_ABI +#define __PYX_TYPE_MODULE_PREFIX __PYX_ABI_MODULE_NAME "." + +#if !CYTHON_COMPILING_IN_LIMITED_API +static CYTHON_INLINE double __pyx_f_7cpython_7complex_7complex_4real_real(PyComplexObject *__pyx_v_self); /* proto*/ +#endif +#if !CYTHON_COMPILING_IN_LIMITED_API +static CYTHON_INLINE double __pyx_f_7cpython_7complex_7complex_4imag_imag(PyComplexObject *__pyx_v_self); /* proto*/ +#endif + +/* Module declarations from "libc.string" */ + +/* Module declarations from "libc.stdlib" */ + +/* Module declarations from "libc.stdint" */ + +/* Module declarations from "cpython.version" */ + +/* Module declarations from "__builtin__" */ + +/* Module declarations from "cpython.type" */ + +/* Module declarations from "libc.stdio" */ + +/* Module declarations from "cpython.object" */ + +/* Module declarations from "cpython.ref" */ + +/* Module declarations from "cpython.exc" */ + +/* Module declarations from "cpython.module" */ + +/* Module declarations from "cpython.mem" */ + +/* Module declarations from "cpython.tuple" */ + +/* Module declarations from "cpython.list" */ + +/* Module declarations from "cpython.sequence" */ + +/* Module declarations from "cpython.mapping" */ + +/* Module declarations from "cpython.iterator" */ + +/* Module declarations from "cpython.number" */ + +/* Module declarations from "__builtin__" */ + +/* Module declarations from "cpython.bool" */ + +/* Module declarations from "cpython.long" */ + +/* Module declarations from "cpython.float" */ + +/* Module declarations from "cython" */ + +/* Module declarations from "__builtin__" */ + +/* Module declarations from "cpython.complex" */ + +/* Module declarations from "libc.stddef" */ + +/* Module declarations from "cpython.unicode" */ + +/* Module declarations from "cpython.pyport" */ + +/* Module declarations from "cpython.dict" */ + +/* Module declarations from "cpython.instance" */ + +/* Module declarations from "cpython.function" */ + +/* Module declarations from "cpython.method" */ + +/* Module declarations from "cpython.weakref" */ + +/* Module declarations from "cpython.getargs" */ + +/* Module declarations from "cpython.pythread" */ + +/* Module declarations from "cpython.pystate" */ + +/* Module declarations from "cpython.set" */ + +/* Module declarations from "cpython.buffer" */ + +/* Module declarations from "cpython.bytes" */ + +/* Module declarations from "cpython.pycapsule" */ + +/* Module declarations from "cpython.contextvars" */ + +/* Module declarations from "cpython" */ + +/* Module declarations from "thriftpy2.transport.cybase" */ + +/* Module declarations from "thriftpy2.protocol.cybin.cybin" */ +static CYTHON_INLINE char __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_read_i08(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *); /*proto*/ +static CYTHON_INLINE int16_t __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_read_i16(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *); /*proto*/ +static CYTHON_INLINE int32_t __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_read_i32(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *); /*proto*/ +static CYTHON_INLINE int64_t __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_read_i64(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *); /*proto*/ +static CYTHON_INLINE int __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_write_i08(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *, char); /*proto*/ +static CYTHON_INLINE int __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_write_i16(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *, int16_t); /*proto*/ +static CYTHON_INLINE int __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_write_i32(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *, int32_t); /*proto*/ +static CYTHON_INLINE int __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_write_i64(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *, int64_t); /*proto*/ +static CYTHON_INLINE int __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_write_double(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *, double); /*proto*/ +static CYTHON_INLINE PyObject *__pyx_f_9thriftpy2_8protocol_5cybin_5cybin_write_list(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *, PyObject *, PyObject *); /*proto*/ +static CYTHON_INLINE PyObject *__pyx_f_9thriftpy2_8protocol_5cybin_5cybin_write_string(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *, PyObject *); /*proto*/ +static CYTHON_INLINE PyObject *__pyx_f_9thriftpy2_8protocol_5cybin_5cybin_write_dict(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *, PyObject *, PyObject *); /*proto*/ +static CYTHON_INLINE PyObject *__pyx_f_9thriftpy2_8protocol_5cybin_5cybin_read_struct(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *, PyObject *, struct __pyx_opt_args_9thriftpy2_8protocol_5cybin_5cybin_read_struct *__pyx_optional_args); /*proto*/ +static CYTHON_INLINE PyObject *__pyx_f_9thriftpy2_8protocol_5cybin_5cybin_write_struct(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *, PyObject *); /*proto*/ +static CYTHON_INLINE PyObject *__pyx_f_9thriftpy2_8protocol_5cybin_5cybin_c_read_binary(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *, int32_t); /*proto*/ +static CYTHON_INLINE PyObject *__pyx_f_9thriftpy2_8protocol_5cybin_5cybin_c_read_string(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *, int32_t, struct __pyx_opt_args_9thriftpy2_8protocol_5cybin_5cybin_c_read_string *__pyx_optional_args); /*proto*/ +static PyObject *__pyx_f_9thriftpy2_8protocol_5cybin_5cybin_c_read_val(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *, __pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType, struct __pyx_opt_args_9thriftpy2_8protocol_5cybin_5cybin_c_read_val *__pyx_optional_args); /*proto*/ +static PyObject *__pyx_f_9thriftpy2_8protocol_5cybin_5cybin_c_write_val(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *, __pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType, PyObject *, struct __pyx_opt_args_9thriftpy2_8protocol_5cybin_5cybin_c_write_val *__pyx_optional_args); /*proto*/ +static PyObject *__pyx_f_9thriftpy2_8protocol_5cybin_5cybin_skip(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *, __pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType, int __pyx_skip_dispatch); /*proto*/ +static PyObject *__pyx_f_9thriftpy2_8protocol_5cybin_5cybin___pyx_unpickle_TCyBinaryProtocol__set_state(struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *, PyObject *); /*proto*/ +/* #### Code section: typeinfo ### */ +/* #### Code section: before_global_var ### */ +#define __Pyx_MODULE_NAME "thriftpy2.protocol.cybin.cybin" +extern int __pyx_module_is_main_thriftpy2__protocol__cybin__cybin; +int __pyx_module_is_main_thriftpy2__protocol__cybin__cybin = 0; + +/* Implementation of "thriftpy2.protocol.cybin.cybin" */ +/* #### Code section: global_var ### */ +static PyObject *__pyx_builtin_object; +/* #### Code section: string_decls ### */ +static const char __pyx_k_decode_response_strict_decode_st[] = "decode_response, strict_decode, strict_read, strict_write, trans"; +/* #### Code section: decls ### */ +static PyObject *__pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_skip(CYTHON_UNUSED PyObject *__pyx_self, struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *__pyx_v_buf, __pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType __pyx_v_ttype); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_2read_val(CYTHON_UNUSED PyObject *__pyx_self, struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *__pyx_v_buf, __pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType __pyx_v_ttype, PyObject *__pyx_v_decode_response, PyObject *__pyx_v_strict_decode); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_4write_val(CYTHON_UNUSED PyObject *__pyx_self, struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *__pyx_v_buf, __pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType __pyx_v_ttype, PyObject *__pyx_v_val, PyObject *__pyx_v_spec); /* proto */ +static int __pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol___init__(struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *__pyx_v_self, PyObject *__pyx_v_trans, PyObject *__pyx_v_strict_read, PyObject *__pyx_v_strict_write, PyObject *__pyx_v_decode_response, PyObject *__pyx_v_strict_decode); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_2skip(struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *__pyx_v_self, PyObject *__pyx_v_ttype); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_4read_message_begin(struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_6read_message_end(CYTHON_UNUSED struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_8write_message_begin(struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *__pyx_v_self, PyObject *__pyx_v_name, __pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType __pyx_v_ttype, int32_t __pyx_v_seqid); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_10write_message_end(CYTHON_UNUSED struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_12read_struct(struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *__pyx_v_self, PyObject *__pyx_v_obj); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_14write_struct(struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *__pyx_v_self, PyObject *__pyx_v_obj); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_5trans___get__(struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *__pyx_v_self); /* proto */ +static int __pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_5trans_2__set__(struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *__pyx_v_self, PyObject *__pyx_v_value); /* proto */ +static int __pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_5trans_4__del__(struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_11strict_read___get__(struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *__pyx_v_self); /* proto */ +static int __pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_11strict_read_2__set__(struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *__pyx_v_self, PyObject *__pyx_v_value); /* proto */ +static int __pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_11strict_read_4__del__(struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_12strict_write___get__(struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *__pyx_v_self); /* proto */ +static int __pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_12strict_write_2__set__(struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *__pyx_v_self, PyObject *__pyx_v_value); /* proto */ +static int __pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_12strict_write_4__del__(struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_15decode_response___get__(struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *__pyx_v_self); /* proto */ +static int __pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_15decode_response_2__set__(struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *__pyx_v_self, PyObject *__pyx_v_value); /* proto */ +static int __pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_15decode_response_4__del__(struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_13strict_decode___get__(struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *__pyx_v_self); /* proto */ +static int __pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_13strict_decode_2__set__(struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *__pyx_v_self, PyObject *__pyx_v_value); /* proto */ +static int __pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_13strict_decode_4__del__(struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_16__reduce_cython__(struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_18__setstate_cython__(struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *__pyx_v_self, PyObject *__pyx_v___pyx_state); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_24TCyBinaryProtocolFactory___init__(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_self, PyObject *__pyx_v_strict_read, PyObject *__pyx_v_strict_write, PyObject *__pyx_v_decode_response, PyObject *__pyx_v_strict_decode); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_24TCyBinaryProtocolFactory_2get_protocol(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_self, PyObject *__pyx_v_trans); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_6__pyx_unpickle_TCyBinaryProtocol(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v___pyx_type, long __pyx_v___pyx_checksum, PyObject *__pyx_v___pyx_state); /* proto */ +static PyObject *__pyx_tp_new_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +/* #### Code section: late_includes ### */ +/* #### Code section: module_state ### */ +/* SmallCodeConfig */ +#ifndef CYTHON_SMALL_CODE +#if defined(__clang__) + #define CYTHON_SMALL_CODE +#elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) + #define CYTHON_SMALL_CODE __attribute__((cold)) +#else + #define CYTHON_SMALL_CODE +#endif +#endif + +typedef struct { + PyObject *__pyx_d; + PyObject *__pyx_b; + PyObject *__pyx_cython_runtime; + PyObject *__pyx_empty_tuple; + PyObject *__pyx_empty_bytes; + PyObject *__pyx_empty_unicode; + PyTypeObject *__pyx_ptype_7cpython_4type_type; + PyTypeObject *__pyx_ptype_7cpython_4bool_bool; + PyTypeObject *__pyx_ptype_7cpython_7complex_complex; + PyTypeObject *__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer; + PyTypeObject *__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase; + PyObject *__pyx_type_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol; + PyTypeObject *__pyx_ptype_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol; + __Pyx_CachedCFunction __pyx_umethod_PyDict_Type_items; + __Pyx_CachedCFunction __pyx_umethod_PyDict_Type_pop; + __Pyx_CachedCFunction __pyx_umethod_PyDict_Type_values; + PyObject *__pyx_tuple[5]; + PyObject *__pyx_codeobj_tab[15]; + PyObject *__pyx_string_tab[118]; + PyObject *__pyx_number_tab[2]; +/* #### Code section: module_state_contents ### */ +/* CommonTypesMetaclass.module_state_decls */ +PyTypeObject *__pyx_CommonTypesMetaclassType; + +/* CachedMethodType.module_state_decls */ +#if CYTHON_COMPILING_IN_LIMITED_API +PyObject *__Pyx_CachedMethodType; +#endif + +/* CythonFunctionShared.module_state_decls */ +PyTypeObject *__pyx_CyFunctionType; + +/* CodeObjectCache.module_state_decls */ +struct __Pyx_CodeObjectCache __pyx_code_cache; + +/* #### Code section: module_state_end ### */ +} __pyx_mstatetype; + +#if CYTHON_USE_MODULE_STATE +#ifdef __cplusplus +namespace { +extern struct PyModuleDef __pyx_moduledef; +} /* anonymous namespace */ +#else +static struct PyModuleDef __pyx_moduledef; +#endif + +#define __pyx_mstate_global (__Pyx_PyModule_GetState(__Pyx_State_FindModule(&__pyx_moduledef))) + +#define __pyx_m (__Pyx_State_FindModule(&__pyx_moduledef)) +#else +static __pyx_mstatetype __pyx_mstate_global_static = +#ifdef __cplusplus + {}; +#else + {0}; +#endif +static __pyx_mstatetype * const __pyx_mstate_global = &__pyx_mstate_global_static; +#endif +/* #### Code section: constant_name_defines ### */ +#define __pyx_kp_u_ __pyx_string_tab[0] +#define __pyx_kp_u_No_protocol_version_header __pyx_string_tab[1] +#define __pyx_kp_u_Note_that_Cython_is_deliberately __pyx_string_tab[2] +#define __pyx_kp_u__2 __pyx_string_tab[3] +#define __pyx_kp_u_add_note __pyx_string_tab[4] +#define __pyx_kp_u_disable __pyx_string_tab[5] +#define __pyx_kp_u_enable __pyx_string_tab[6] +#define __pyx_kp_u_gc __pyx_string_tab[7] +#define __pyx_kp_u_invalid_version_d __pyx_string_tab[8] +#define __pyx_kp_u_isenabled __pyx_string_tab[9] +#define __pyx_kp_u_stringsource __pyx_string_tab[10] +#define __pyx_kp_u_thriftpy2_protocol_cybin_cybin_p __pyx_string_tab[11] +#define __pyx_kp_u_utf_8 __pyx_string_tab[12] +#define __pyx_n_u_BIN_TYPES __pyx_string_tab[13] +#define __pyx_n_u_ProtocolError __pyx_string_tab[14] +#define __pyx_n_u_Pyx_PyDict_NextRef __pyx_string_tab[15] +#define __pyx_n_u_TCyBinaryProtocol __pyx_string_tab[16] +#define __pyx_n_u_TCyBinaryProtocolFactory __pyx_string_tab[17] +#define __pyx_n_u_TCyBinaryProtocolFactory___init __pyx_string_tab[18] +#define __pyx_n_u_TCyBinaryProtocolFactory_get_pro __pyx_string_tab[19] +#define __pyx_n_u_TCyBinaryProtocol___reduce_cytho __pyx_string_tab[20] +#define __pyx_n_u_TCyBinaryProtocol___setstate_cyt __pyx_string_tab[21] +#define __pyx_n_u_TCyBinaryProtocol_read_message_b __pyx_string_tab[22] +#define __pyx_n_u_TCyBinaryProtocol_read_message_e __pyx_string_tab[23] +#define __pyx_n_u_TCyBinaryProtocol_read_struct __pyx_string_tab[24] +#define __pyx_n_u_TCyBinaryProtocol_skip __pyx_string_tab[25] +#define __pyx_n_u_TCyBinaryProtocol_write_message __pyx_string_tab[26] +#define __pyx_n_u_TCyBinaryProtocol_write_message_2 __pyx_string_tab[27] +#define __pyx_n_u_TCyBinaryProtocol_write_struct __pyx_string_tab[28] +#define __pyx_n_u_TDecodeException __pyx_string_tab[29] +#define __pyx_n_u_asyncio_coroutines __pyx_string_tab[30] +#define __pyx_n_u_binary_type __pyx_string_tab[31] +#define __pyx_n_u_buf __pyx_string_tab[32] +#define __pyx_n_u_class __pyx_string_tab[33] +#define __pyx_n_u_clean __pyx_string_tab[34] +#define __pyx_n_u_cline_in_traceback __pyx_string_tab[35] +#define __pyx_n_u_decode_response __pyx_string_tab[36] +#define __pyx_n_u_dict __pyx_string_tab[37] +#define __pyx_n_u_dict_2 __pyx_string_tab[38] +#define __pyx_n_u_doc __pyx_string_tab[39] +#define __pyx_n_u_encode __pyx_string_tab[40] +#define __pyx_n_u_func __pyx_string_tab[41] +#define __pyx_n_u_get_protocol __pyx_string_tab[42] +#define __pyx_n_u_getstate __pyx_string_tab[43] +#define __pyx_n_u_init __pyx_string_tab[44] +#define __pyx_n_u_is_coroutine __pyx_string_tab[45] +#define __pyx_n_u_items __pyx_string_tab[46] +#define __pyx_n_u_main __pyx_string_tab[47] +#define __pyx_n_u_metaclass __pyx_string_tab[48] +#define __pyx_n_u_module __pyx_string_tab[49] +#define __pyx_n_u_mro_entries __pyx_string_tab[50] +#define __pyx_n_u_name __pyx_string_tab[51] +#define __pyx_n_u_name_2 __pyx_string_tab[52] +#define __pyx_n_u_new __pyx_string_tab[53] +#define __pyx_n_u_obj __pyx_string_tab[54] +#define __pyx_n_u_object __pyx_string_tab[55] +#define __pyx_n_u_pop __pyx_string_tab[56] +#define __pyx_n_u_prepare __pyx_string_tab[57] +#define __pyx_n_u_pyx_checksum __pyx_string_tab[58] +#define __pyx_n_u_pyx_result __pyx_string_tab[59] +#define __pyx_n_u_pyx_state __pyx_string_tab[60] +#define __pyx_n_u_pyx_type __pyx_string_tab[61] +#define __pyx_n_u_pyx_unpickle_TCyBinaryProtocol __pyx_string_tab[62] +#define __pyx_n_u_pyx_vtable __pyx_string_tab[63] +#define __pyx_n_u_qualname __pyx_string_tab[64] +#define __pyx_n_u_read_message_begin __pyx_string_tab[65] +#define __pyx_n_u_read_message_end __pyx_string_tab[66] +#define __pyx_n_u_read_struct __pyx_string_tab[67] +#define __pyx_n_u_read_val __pyx_string_tab[68] +#define __pyx_n_u_reduce __pyx_string_tab[69] +#define __pyx_n_u_reduce_cython __pyx_string_tab[70] +#define __pyx_n_u_reduce_ex __pyx_string_tab[71] +#define __pyx_n_u_self __pyx_string_tab[72] +#define __pyx_n_u_seqid __pyx_string_tab[73] +#define __pyx_n_u_set_name __pyx_string_tab[74] +#define __pyx_n_u_setdefault __pyx_string_tab[75] +#define __pyx_n_u_setstate __pyx_string_tab[76] +#define __pyx_n_u_setstate_cython __pyx_string_tab[77] +#define __pyx_n_u_six __pyx_string_tab[78] +#define __pyx_n_u_size __pyx_string_tab[79] +#define __pyx_n_u_skip __pyx_string_tab[80] +#define __pyx_n_u_spec __pyx_string_tab[81] +#define __pyx_n_u_state __pyx_string_tab[82] +#define __pyx_n_u_strict_decode __pyx_string_tab[83] +#define __pyx_n_u_strict_read __pyx_string_tab[84] +#define __pyx_n_u_strict_write __pyx_string_tab[85] +#define __pyx_n_u_string_types __pyx_string_tab[86] +#define __pyx_n_u_sys __pyx_string_tab[87] +#define __pyx_n_u_test __pyx_string_tab[88] +#define __pyx_n_u_thrift_spec __pyx_string_tab[89] +#define __pyx_n_u_thriftpy2_protocol_cybin_cybin __pyx_string_tab[90] +#define __pyx_n_u_thriftpy2_thrift __pyx_string_tab[91] +#define __pyx_n_u_trans __pyx_string_tab[92] +#define __pyx_n_u_ttype __pyx_string_tab[93] +#define __pyx_n_u_update __pyx_string_tab[94] +#define __pyx_n_u_use_setstate __pyx_string_tab[95] +#define __pyx_n_u_val __pyx_string_tab[96] +#define __pyx_n_u_values __pyx_string_tab[97] +#define __pyx_n_u_version __pyx_string_tab[98] +#define __pyx_n_u_version_info __pyx_string_tab[99] +#define __pyx_n_u_write_message_begin __pyx_string_tab[100] +#define __pyx_n_u_write_message_end __pyx_string_tab[101] +#define __pyx_n_u_write_struct __pyx_string_tab[102] +#define __pyx_n_u_write_val __pyx_string_tab[103] +#define __pyx_kp_b_iso88591_5Q_q_WE __pyx_string_tab[104] +#define __pyx_kp_b_iso88591_A __pyx_string_tab[105] +#define __pyx_kp_b_iso88591_A_4_T_A __pyx_string_tab[106] +#define __pyx_kp_b_iso88591_A_AT __pyx_string_tab[107] +#define __pyx_kp_b_iso88591_A_XQ_fA __pyx_string_tab[108] +#define __pyx_kp_b_iso88591_A_at85_A_1_fA __pyx_string_tab[109] +#define __pyx_kp_b_iso88591_A_xq_A_5_e2Q_xs_m1_9_1_Qd_HE_1_t __pyx_string_tab[110] +#define __pyx_kp_b_iso88591_A_z_1_4q_Qd_q_HJa_q_HJa_Qd_ha __pyx_string_tab[111] +#define __pyx_kp_b_iso88591_T_4_7t___a_G1F_a_vWE_Q_q_t_G5_4 __pyx_string_tab[112] +#define __pyx_kp_b_iso88591_q_0_kQR_HAQ_7_314H_VW_1 __pyx_string_tab[113] +#define __pyx_kp_b_iso88591_q_O1_A_q_Q __pyx_string_tab[114] +#define __pyx_kp_b_iso88591_q_Qe7_9 __pyx_string_tab[115] +#define __pyx_kp_b_iso88591_q_a __pyx_string_tab[116] +#define __pyx_kp_b_iso88591_vS_s_1_s_s_s_6_A_s_3fCq_xq_Qe1 __pyx_string_tab[117] +#define __pyx_int_2 __pyx_number_tab[0] +#define __pyx_int_257176801 __pyx_number_tab[1] +/* #### Code section: module_state_clear ### */ +#if CYTHON_USE_MODULE_STATE +static CYTHON_SMALL_CODE int __pyx_m_clear(PyObject *m) { + __pyx_mstatetype *clear_module_state = __Pyx_PyModule_GetState(m); + if (!clear_module_state) return 0; + Py_CLEAR(clear_module_state->__pyx_d); + Py_CLEAR(clear_module_state->__pyx_b); + Py_CLEAR(clear_module_state->__pyx_cython_runtime); + Py_CLEAR(clear_module_state->__pyx_empty_tuple); + Py_CLEAR(clear_module_state->__pyx_empty_bytes); + Py_CLEAR(clear_module_state->__pyx_empty_unicode); + #if CYTHON_PEP489_MULTI_PHASE_INIT + __Pyx_State_RemoveModule(NULL); + #endif + Py_CLEAR(clear_module_state->__pyx_ptype_7cpython_4type_type); + Py_CLEAR(clear_module_state->__pyx_ptype_7cpython_4bool_bool); + Py_CLEAR(clear_module_state->__pyx_ptype_7cpython_7complex_complex); + Py_CLEAR(clear_module_state->__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer); + Py_CLEAR(clear_module_state->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase); + Py_CLEAR(clear_module_state->__pyx_ptype_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol); + Py_CLEAR(clear_module_state->__pyx_type_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol); + for (int i=0; i<5; ++i) { Py_CLEAR(clear_module_state->__pyx_tuple[i]); } + for (int i=0; i<15; ++i) { Py_CLEAR(clear_module_state->__pyx_codeobj_tab[i]); } + for (int i=0; i<118; ++i) { Py_CLEAR(clear_module_state->__pyx_string_tab[i]); } + for (int i=0; i<2; ++i) { Py_CLEAR(clear_module_state->__pyx_number_tab[i]); } +/* #### Code section: module_state_clear_contents ### */ +/* CommonTypesMetaclass.module_state_clear */ +Py_CLEAR(clear_module_state->__pyx_CommonTypesMetaclassType); + +/* CythonFunctionShared.module_state_clear */ +Py_CLEAR(clear_module_state->__pyx_CyFunctionType); + +/* #### Code section: module_state_clear_end ### */ +return 0; +} +#endif +/* #### Code section: module_state_traverse ### */ +#if CYTHON_USE_MODULE_STATE +static CYTHON_SMALL_CODE int __pyx_m_traverse(PyObject *m, visitproc visit, void *arg) { + __pyx_mstatetype *traverse_module_state = __Pyx_PyModule_GetState(m); + if (!traverse_module_state) return 0; + Py_VISIT(traverse_module_state->__pyx_d); + Py_VISIT(traverse_module_state->__pyx_b); + Py_VISIT(traverse_module_state->__pyx_cython_runtime); + __Pyx_VISIT_CONST(traverse_module_state->__pyx_empty_tuple); + __Pyx_VISIT_CONST(traverse_module_state->__pyx_empty_bytes); + __Pyx_VISIT_CONST(traverse_module_state->__pyx_empty_unicode); + Py_VISIT(traverse_module_state->__pyx_ptype_7cpython_4type_type); + Py_VISIT(traverse_module_state->__pyx_ptype_7cpython_4bool_bool); + Py_VISIT(traverse_module_state->__pyx_ptype_7cpython_7complex_complex); + Py_VISIT(traverse_module_state->__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer); + Py_VISIT(traverse_module_state->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase); + Py_VISIT(traverse_module_state->__pyx_ptype_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol); + Py_VISIT(traverse_module_state->__pyx_type_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol); + for (int i=0; i<5; ++i) { __Pyx_VISIT_CONST(traverse_module_state->__pyx_tuple[i]); } + for (int i=0; i<15; ++i) { __Pyx_VISIT_CONST(traverse_module_state->__pyx_codeobj_tab[i]); } + for (int i=0; i<118; ++i) { __Pyx_VISIT_CONST(traverse_module_state->__pyx_string_tab[i]); } + for (int i=0; i<2; ++i) { __Pyx_VISIT_CONST(traverse_module_state->__pyx_number_tab[i]); } +/* #### Code section: module_state_traverse_contents ### */ +/* CommonTypesMetaclass.module_state_traverse */ +Py_VISIT(traverse_module_state->__pyx_CommonTypesMetaclassType); + +/* CythonFunctionShared.module_state_traverse */ +Py_VISIT(traverse_module_state->__pyx_CyFunctionType); + +/* #### Code section: module_state_traverse_end ### */ +return 0; +} +#endif +/* #### Code section: module_code ### */ + +/* "cpython/complex.pxd":20 + * + * # unavailable in limited API + * @property # <<<<<<<<<<<<<< + * @_cython.c_compile_guard("!CYTHON_COMPILING_IN_LIMITED_API") + * cdef inline double real(self) noexcept: +*/ + +#if !CYTHON_COMPILING_IN_LIMITED_API +static CYTHON_INLINE double __pyx_f_7cpython_7complex_7complex_4real_real(PyComplexObject *__pyx_v_self) { + double __pyx_r; + + /* "cpython/complex.pxd":23 + * @_cython.c_compile_guard("!CYTHON_COMPILING_IN_LIMITED_API") + * cdef inline double real(self) noexcept: + * return self.cval.real # <<<<<<<<<<<<<< + * + * # unavailable in limited API +*/ + __pyx_r = __pyx_v_self->cval.real; + goto __pyx_L0; + + /* "cpython/complex.pxd":20 + * + * # unavailable in limited API + * @property # <<<<<<<<<<<<<< + * @_cython.c_compile_guard("!CYTHON_COMPILING_IN_LIMITED_API") + * cdef inline double real(self) noexcept: +*/ + + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} +#endif /*!(#if !CYTHON_COMPILING_IN_LIMITED_API)*/ + +/* "cpython/complex.pxd":26 + * + * # unavailable in limited API + * @property # <<<<<<<<<<<<<< + * @_cython.c_compile_guard("!CYTHON_COMPILING_IN_LIMITED_API") + * cdef inline double imag(self) noexcept: +*/ + +#if !CYTHON_COMPILING_IN_LIMITED_API +static CYTHON_INLINE double __pyx_f_7cpython_7complex_7complex_4imag_imag(PyComplexObject *__pyx_v_self) { + double __pyx_r; + + /* "cpython/complex.pxd":29 + * @_cython.c_compile_guard("!CYTHON_COMPILING_IN_LIMITED_API") + * cdef inline double imag(self) noexcept: + * return self.cval.imag # <<<<<<<<<<<<<< + * + * # PyTypeObject PyComplex_Type +*/ + __pyx_r = __pyx_v_self->cval.imag; + goto __pyx_L0; + + /* "cpython/complex.pxd":26 + * + * # unavailable in limited API + * @property # <<<<<<<<<<<<<< + * @_cython.c_compile_guard("!CYTHON_COMPILING_IN_LIMITED_API") + * cdef inline double imag(self) noexcept: +*/ + + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} +#endif /*!(#if !CYTHON_COMPILING_IN_LIMITED_API)*/ + +/* "cpython/contextvars.pxd":115 + * + * + * @_cython.c_compile_guard("!CYTHON_COMPILING_IN_LIMITED_API") # <<<<<<<<<<<<<< + * cdef inline object get_value(var, default_value=None): + * """Return a new reference to the value of the context variable, +*/ + +#if !CYTHON_COMPILING_IN_LIMITED_API +static CYTHON_INLINE PyObject *__pyx_f_7cpython_11contextvars_get_value(PyObject *__pyx_v_var, struct __pyx_opt_args_7cpython_11contextvars_get_value *__pyx_optional_args) { + + /* "cpython/contextvars.pxd":116 + * + * @_cython.c_compile_guard("!CYTHON_COMPILING_IN_LIMITED_API") + * cdef inline object get_value(var, default_value=None): # <<<<<<<<<<<<<< + * """Return a new reference to the value of the context variable, + * or the default value of the context variable, +*/ + PyObject *__pyx_v_default_value = ((PyObject *)Py_None); + PyObject *__pyx_v_value; + PyObject *__pyx_v_pyvalue = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("get_value", 0); + if (__pyx_optional_args) { + if (__pyx_optional_args->__pyx_n > 0) { + __pyx_v_default_value = __pyx_optional_args->default_value; + } + } + + /* "cpython/contextvars.pxd":121 + * or None if no such value or default was found. + * """ + * cdef PyObject *value = NULL # <<<<<<<<<<<<<< + * PyContextVar_Get(var, NULL, &value) + * if value is NULL: +*/ + __pyx_v_value = NULL; + + /* "cpython/contextvars.pxd":122 + * """ + * cdef PyObject *value = NULL + * PyContextVar_Get(var, NULL, &value) # <<<<<<<<<<<<<< + * if value is NULL: + * # context variable does not have a default +*/ + __pyx_t_1 = PyContextVar_Get(__pyx_v_var, NULL, (&__pyx_v_value)); if (unlikely(__pyx_t_1 == ((int)-1))) __PYX_ERR(1, 122, __pyx_L1_error) + + /* "cpython/contextvars.pxd":123 + * cdef PyObject *value = NULL + * PyContextVar_Get(var, NULL, &value) + * if value is NULL: # <<<<<<<<<<<<<< + * # context variable does not have a default + * pyvalue = default_value +*/ + __pyx_t_2 = (__pyx_v_value == NULL); + if (__pyx_t_2) { + + /* "cpython/contextvars.pxd":125 + * if value is NULL: + * # context variable does not have a default + * pyvalue = default_value # <<<<<<<<<<<<<< + * else: + * # value or default value of context variable +*/ + __Pyx_INCREF(__pyx_v_default_value); + __pyx_v_pyvalue = __pyx_v_default_value; + + /* "cpython/contextvars.pxd":123 + * cdef PyObject *value = NULL + * PyContextVar_Get(var, NULL, &value) + * if value is NULL: # <<<<<<<<<<<<<< + * # context variable does not have a default + * pyvalue = default_value +*/ + goto __pyx_L3; + } + + /* "cpython/contextvars.pxd":128 + * else: + * # value or default value of context variable + * pyvalue = value # <<<<<<<<<<<<<< + * Py_XDECREF(value) # PyContextVar_Get() returned an owned reference as 'PyObject*' + * return pyvalue +*/ + /*else*/ { + __pyx_t_3 = ((PyObject *)__pyx_v_value); + __Pyx_INCREF(__pyx_t_3); + __pyx_v_pyvalue = __pyx_t_3; + __pyx_t_3 = 0; + + /* "cpython/contextvars.pxd":129 + * # value or default value of context variable + * pyvalue = value + * Py_XDECREF(value) # PyContextVar_Get() returned an owned reference as 'PyObject*' # <<<<<<<<<<<<<< + * return pyvalue + * +*/ + Py_XDECREF(__pyx_v_value); + } + __pyx_L3:; + + /* "cpython/contextvars.pxd":130 + * pyvalue = value + * Py_XDECREF(value) # PyContextVar_Get() returned an owned reference as 'PyObject*' + * return pyvalue # <<<<<<<<<<<<<< + * + * +*/ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_pyvalue); + __pyx_r = __pyx_v_pyvalue; + goto __pyx_L0; + + /* "cpython/contextvars.pxd":115 + * + * + * @_cython.c_compile_guard("!CYTHON_COMPILING_IN_LIMITED_API") # <<<<<<<<<<<<<< + * cdef inline object get_value(var, default_value=None): + * """Return a new reference to the value of the context variable, +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("cpython.contextvars.get_value", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_pyvalue); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} +#endif /*!(#if !CYTHON_COMPILING_IN_LIMITED_API)*/ + +/* "cpython/contextvars.pxd":133 + * + * + * @_cython.c_compile_guard("!CYTHON_COMPILING_IN_LIMITED_API") # <<<<<<<<<<<<<< + * cdef inline object get_value_no_default(var, default_value=None): + * """Return a new reference to the value of the context variable, +*/ + +#if !CYTHON_COMPILING_IN_LIMITED_API +static CYTHON_INLINE PyObject *__pyx_f_7cpython_11contextvars_get_value_no_default(PyObject *__pyx_v_var, struct __pyx_opt_args_7cpython_11contextvars_get_value_no_default *__pyx_optional_args) { + + /* "cpython/contextvars.pxd":134 + * + * @_cython.c_compile_guard("!CYTHON_COMPILING_IN_LIMITED_API") + * cdef inline object get_value_no_default(var, default_value=None): # <<<<<<<<<<<<<< + * """Return a new reference to the value of the context variable, + * or the provided default value if no such value was found. +*/ + PyObject *__pyx_v_default_value = ((PyObject *)Py_None); + PyObject *__pyx_v_value; + PyObject *__pyx_v_pyvalue = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("get_value_no_default", 0); + if (__pyx_optional_args) { + if (__pyx_optional_args->__pyx_n > 0) { + __pyx_v_default_value = __pyx_optional_args->default_value; + } + } + + /* "cpython/contextvars.pxd":140 + * Ignores the default value of the context variable, if any. + * """ + * cdef PyObject *value = NULL # <<<<<<<<<<<<<< + * PyContextVar_Get(var, default_value, &value) + * # value of context variable or 'default_value' +*/ + __pyx_v_value = NULL; + + /* "cpython/contextvars.pxd":141 + * """ + * cdef PyObject *value = NULL + * PyContextVar_Get(var, default_value, &value) # <<<<<<<<<<<<<< + * # value of context variable or 'default_value' + * pyvalue = value +*/ + __pyx_t_1 = PyContextVar_Get(__pyx_v_var, ((PyObject *)__pyx_v_default_value), (&__pyx_v_value)); if (unlikely(__pyx_t_1 == ((int)-1))) __PYX_ERR(1, 141, __pyx_L1_error) + + /* "cpython/contextvars.pxd":143 + * PyContextVar_Get(var, default_value, &value) + * # value of context variable or 'default_value' + * pyvalue = value # <<<<<<<<<<<<<< + * Py_XDECREF(value) # PyContextVar_Get() returned an owned reference as 'PyObject*' + * return pyvalue +*/ + __pyx_t_2 = ((PyObject *)__pyx_v_value); + __Pyx_INCREF(__pyx_t_2); + __pyx_v_pyvalue = __pyx_t_2; + __pyx_t_2 = 0; + + /* "cpython/contextvars.pxd":144 + * # value of context variable or 'default_value' + * pyvalue = value + * Py_XDECREF(value) # PyContextVar_Get() returned an owned reference as 'PyObject*' # <<<<<<<<<<<<<< + * return pyvalue +*/ + Py_XDECREF(__pyx_v_value); + + /* "cpython/contextvars.pxd":145 + * pyvalue = value + * Py_XDECREF(value) # PyContextVar_Get() returned an owned reference as 'PyObject*' + * return pyvalue # <<<<<<<<<<<<<< +*/ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_pyvalue); + __pyx_r = __pyx_v_pyvalue; + goto __pyx_L0; + + /* "cpython/contextvars.pxd":133 + * + * + * @_cython.c_compile_guard("!CYTHON_COMPILING_IN_LIMITED_API") # <<<<<<<<<<<<<< + * cdef inline object get_value_no_default(var, default_value=None): + * """Return a new reference to the value of the context variable, +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("cpython.contextvars.get_value_no_default", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_pyvalue); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} +#endif /*!(#if !CYTHON_COMPILING_IN_LIMITED_API)*/ + +/* "thriftpy2/protocol/cybin/cybin.pyx":56 + * + * + * cdef inline char read_i08(CyTransportBase buf) except? -1: # <<<<<<<<<<<<<< + * cdef char data = 0 + * buf.c_read(1, &data) +*/ + +static CYTHON_INLINE char __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_read_i08(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *__pyx_v_buf) { + char __pyx_v_data; + char __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("read_i08", 0); + + /* "thriftpy2/protocol/cybin/cybin.pyx":57 + * + * cdef inline char read_i08(CyTransportBase buf) except? -1: + * cdef char data = 0 # <<<<<<<<<<<<<< + * buf.c_read(1, &data) + * return data +*/ + __pyx_v_data = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":58 + * cdef inline char read_i08(CyTransportBase buf) except? -1: + * cdef char data = 0 + * buf.c_read(1, &data) # <<<<<<<<<<<<<< + * return data + * +*/ + __pyx_t_1 = ((struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_CyTransportBase *)__pyx_v_buf->__pyx_vtab)->c_read(__pyx_v_buf, 1, (&__pyx_v_data)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 58, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":59 + * cdef char data = 0 + * buf.c_read(1, &data) + * return data # <<<<<<<<<<<<<< + * + * +*/ + __pyx_r = __pyx_v_data; + goto __pyx_L0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":56 + * + * + * cdef inline char read_i08(CyTransportBase buf) except? -1: # <<<<<<<<<<<<<< + * cdef char data = 0 + * buf.c_read(1, &data) +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("thriftpy2.protocol.cybin.cybin.read_i08", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/protocol/cybin/cybin.pyx":62 + * + * + * cdef inline int16_t read_i16(CyTransportBase buf) except? -1: # <<<<<<<<<<<<<< + * cdef char data[2] + * buf.c_read(2, data) +*/ + +static CYTHON_INLINE int16_t __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_read_i16(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *__pyx_v_buf) { + char __pyx_v_data[2]; + int16_t __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("read_i16", 0); + + /* "thriftpy2/protocol/cybin/cybin.pyx":64 + * cdef inline int16_t read_i16(CyTransportBase buf) except? -1: + * cdef char data[2] + * buf.c_read(2, data) # <<<<<<<<<<<<<< + * return be16toh((data)[0]) + * +*/ + __pyx_t_1 = ((struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_CyTransportBase *)__pyx_v_buf->__pyx_vtab)->c_read(__pyx_v_buf, 2, __pyx_v_data); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 64, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":65 + * cdef char data[2] + * buf.c_read(2, data) + * return be16toh((data)[0]) # <<<<<<<<<<<<<< + * + * +*/ + __pyx_r = be16toh((((int16_t *)__pyx_v_data)[0])); + goto __pyx_L0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":62 + * + * + * cdef inline int16_t read_i16(CyTransportBase buf) except? -1: # <<<<<<<<<<<<<< + * cdef char data[2] + * buf.c_read(2, data) +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("thriftpy2.protocol.cybin.cybin.read_i16", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/protocol/cybin/cybin.pyx":68 + * + * + * cdef inline int32_t read_i32(CyTransportBase buf) except? -1: # <<<<<<<<<<<<<< + * cdef char data[4] + * buf.c_read(4, data) +*/ + +static CYTHON_INLINE int32_t __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_read_i32(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *__pyx_v_buf) { + char __pyx_v_data[4]; + int32_t __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("read_i32", 0); + + /* "thriftpy2/protocol/cybin/cybin.pyx":70 + * cdef inline int32_t read_i32(CyTransportBase buf) except? -1: + * cdef char data[4] + * buf.c_read(4, data) # <<<<<<<<<<<<<< + * return be32toh((data)[0]) + * +*/ + __pyx_t_1 = ((struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_CyTransportBase *)__pyx_v_buf->__pyx_vtab)->c_read(__pyx_v_buf, 4, __pyx_v_data); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 70, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":71 + * cdef char data[4] + * buf.c_read(4, data) + * return be32toh((data)[0]) # <<<<<<<<<<<<<< + * + * +*/ + __pyx_r = be32toh((((int32_t *)__pyx_v_data)[0])); + goto __pyx_L0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":68 + * + * + * cdef inline int32_t read_i32(CyTransportBase buf) except? -1: # <<<<<<<<<<<<<< + * cdef char data[4] + * buf.c_read(4, data) +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("thriftpy2.protocol.cybin.cybin.read_i32", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/protocol/cybin/cybin.pyx":74 + * + * + * cdef inline int64_t read_i64(CyTransportBase buf) except? -1: # <<<<<<<<<<<<<< + * cdef char data[8] + * buf.c_read(8, data) +*/ + +static CYTHON_INLINE int64_t __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_read_i64(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *__pyx_v_buf) { + char __pyx_v_data[8]; + int64_t __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("read_i64", 0); + + /* "thriftpy2/protocol/cybin/cybin.pyx":76 + * cdef inline int64_t read_i64(CyTransportBase buf) except? -1: + * cdef char data[8] + * buf.c_read(8, data) # <<<<<<<<<<<<<< + * return be64toh((data)[0]) + * +*/ + __pyx_t_1 = ((struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_CyTransportBase *)__pyx_v_buf->__pyx_vtab)->c_read(__pyx_v_buf, 8, __pyx_v_data); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 76, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":77 + * cdef char data[8] + * buf.c_read(8, data) + * return be64toh((data)[0]) # <<<<<<<<<<<<<< + * + * +*/ + __pyx_r = be64toh((((int64_t *)__pyx_v_data)[0])); + goto __pyx_L0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":74 + * + * + * cdef inline int64_t read_i64(CyTransportBase buf) except? -1: # <<<<<<<<<<<<<< + * cdef char data[8] + * buf.c_read(8, data) +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("thriftpy2.protocol.cybin.cybin.read_i64", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1L; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/protocol/cybin/cybin.pyx":80 + * + * + * cdef inline int write_i08(CyTransportBase buf, char val) except -1: # <<<<<<<<<<<<<< + * buf.c_write(&val, 1) + * return 0 +*/ + +static CYTHON_INLINE int __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_write_i08(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *__pyx_v_buf, char __pyx_v_val) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("write_i08", 0); + + /* "thriftpy2/protocol/cybin/cybin.pyx":81 + * + * cdef inline int write_i08(CyTransportBase buf, char val) except -1: + * buf.c_write(&val, 1) # <<<<<<<<<<<<<< + * return 0 + * +*/ + __pyx_t_1 = ((struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_CyTransportBase *)__pyx_v_buf->__pyx_vtab)->c_write(__pyx_v_buf, (&__pyx_v_val), 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 81, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":82 + * cdef inline int write_i08(CyTransportBase buf, char val) except -1: + * buf.c_write(&val, 1) + * return 0 # <<<<<<<<<<<<<< + * + * +*/ + __pyx_r = 0; + goto __pyx_L0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":80 + * + * + * cdef inline int write_i08(CyTransportBase buf, char val) except -1: # <<<<<<<<<<<<<< + * buf.c_write(&val, 1) + * return 0 +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("thriftpy2.protocol.cybin.cybin.write_i08", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/protocol/cybin/cybin.pyx":85 + * + * + * cdef inline int write_i16(CyTransportBase buf, int16_t val) except -1: # <<<<<<<<<<<<<< + * val = htobe16(val) + * buf.c_write((&val), 2) +*/ + +static CYTHON_INLINE int __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_write_i16(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *__pyx_v_buf, int16_t __pyx_v_val) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("write_i16", 0); + + /* "thriftpy2/protocol/cybin/cybin.pyx":86 + * + * cdef inline int write_i16(CyTransportBase buf, int16_t val) except -1: + * val = htobe16(val) # <<<<<<<<<<<<<< + * buf.c_write((&val), 2) + * return 0 +*/ + __pyx_v_val = htobe16(__pyx_v_val); + + /* "thriftpy2/protocol/cybin/cybin.pyx":87 + * cdef inline int write_i16(CyTransportBase buf, int16_t val) except -1: + * val = htobe16(val) + * buf.c_write((&val), 2) # <<<<<<<<<<<<<< + * return 0 + * +*/ + __pyx_t_1 = ((struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_CyTransportBase *)__pyx_v_buf->__pyx_vtab)->c_write(__pyx_v_buf, ((char *)(&__pyx_v_val)), 2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 87, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":88 + * val = htobe16(val) + * buf.c_write((&val), 2) + * return 0 # <<<<<<<<<<<<<< + * + * +*/ + __pyx_r = 0; + goto __pyx_L0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":85 + * + * + * cdef inline int write_i16(CyTransportBase buf, int16_t val) except -1: # <<<<<<<<<<<<<< + * val = htobe16(val) + * buf.c_write((&val), 2) +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("thriftpy2.protocol.cybin.cybin.write_i16", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/protocol/cybin/cybin.pyx":91 + * + * + * cdef inline int write_i32(CyTransportBase buf, int32_t val) except -1: # <<<<<<<<<<<<<< + * val = htobe32(val) + * buf.c_write((&val), 4) +*/ + +static CYTHON_INLINE int __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_write_i32(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *__pyx_v_buf, int32_t __pyx_v_val) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("write_i32", 0); + + /* "thriftpy2/protocol/cybin/cybin.pyx":92 + * + * cdef inline int write_i32(CyTransportBase buf, int32_t val) except -1: + * val = htobe32(val) # <<<<<<<<<<<<<< + * buf.c_write((&val), 4) + * return 0 +*/ + __pyx_v_val = htobe32(__pyx_v_val); + + /* "thriftpy2/protocol/cybin/cybin.pyx":93 + * cdef inline int write_i32(CyTransportBase buf, int32_t val) except -1: + * val = htobe32(val) + * buf.c_write((&val), 4) # <<<<<<<<<<<<<< + * return 0 + * +*/ + __pyx_t_1 = ((struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_CyTransportBase *)__pyx_v_buf->__pyx_vtab)->c_write(__pyx_v_buf, ((char *)(&__pyx_v_val)), 4); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 93, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":94 + * val = htobe32(val) + * buf.c_write((&val), 4) + * return 0 # <<<<<<<<<<<<<< + * + * +*/ + __pyx_r = 0; + goto __pyx_L0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":91 + * + * + * cdef inline int write_i32(CyTransportBase buf, int32_t val) except -1: # <<<<<<<<<<<<<< + * val = htobe32(val) + * buf.c_write((&val), 4) +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("thriftpy2.protocol.cybin.cybin.write_i32", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/protocol/cybin/cybin.pyx":97 + * + * + * cdef inline int write_i64(CyTransportBase buf, int64_t val) except -1: # <<<<<<<<<<<<<< + * val = htobe64(val) + * buf.c_write((&val), 8) +*/ + +static CYTHON_INLINE int __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_write_i64(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *__pyx_v_buf, int64_t __pyx_v_val) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("write_i64", 0); + + /* "thriftpy2/protocol/cybin/cybin.pyx":98 + * + * cdef inline int write_i64(CyTransportBase buf, int64_t val) except -1: + * val = htobe64(val) # <<<<<<<<<<<<<< + * buf.c_write((&val), 8) + * return 0 +*/ + __pyx_v_val = htobe64(__pyx_v_val); + + /* "thriftpy2/protocol/cybin/cybin.pyx":99 + * cdef inline int write_i64(CyTransportBase buf, int64_t val) except -1: + * val = htobe64(val) + * buf.c_write((&val), 8) # <<<<<<<<<<<<<< + * return 0 + * +*/ + __pyx_t_1 = ((struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_CyTransportBase *)__pyx_v_buf->__pyx_vtab)->c_write(__pyx_v_buf, ((char *)(&__pyx_v_val)), 8); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 99, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":100 + * val = htobe64(val) + * buf.c_write((&val), 8) + * return 0 # <<<<<<<<<<<<<< + * + * +*/ + __pyx_r = 0; + goto __pyx_L0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":97 + * + * + * cdef inline int write_i64(CyTransportBase buf, int64_t val) except -1: # <<<<<<<<<<<<<< + * val = htobe64(val) + * buf.c_write((&val), 8) +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("thriftpy2.protocol.cybin.cybin.write_i64", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/protocol/cybin/cybin.pyx":103 + * + * + * cdef inline int write_double(CyTransportBase buf, double val) except -1: # <<<<<<<<<<<<<< + * cdef int64_t v + * memcpy(&v, &val, 8) +*/ + +static CYTHON_INLINE int __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_write_double(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *__pyx_v_buf, double __pyx_v_val) { + int64_t __pyx_v_v; + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("write_double", 0); + + /* "thriftpy2/protocol/cybin/cybin.pyx":105 + * cdef inline int write_double(CyTransportBase buf, double val) except -1: + * cdef int64_t v + * memcpy(&v, &val, 8) # <<<<<<<<<<<<<< + * v = htobe64(v) + * buf.c_write((&v), 8) +*/ + (void)(memcpy((&__pyx_v_v), (&__pyx_v_val), 8)); + + /* "thriftpy2/protocol/cybin/cybin.pyx":106 + * cdef int64_t v + * memcpy(&v, &val, 8) + * v = htobe64(v) # <<<<<<<<<<<<<< + * buf.c_write((&v), 8) + * return 0 +*/ + __pyx_v_v = htobe64(__pyx_v_v); + + /* "thriftpy2/protocol/cybin/cybin.pyx":107 + * memcpy(&v, &val, 8) + * v = htobe64(v) + * buf.c_write((&v), 8) # <<<<<<<<<<<<<< + * return 0 + * +*/ + __pyx_t_1 = ((struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_CyTransportBase *)__pyx_v_buf->__pyx_vtab)->c_write(__pyx_v_buf, ((char *)(&__pyx_v_v)), 8); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 107, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":108 + * v = htobe64(v) + * buf.c_write((&v), 8) + * return 0 # <<<<<<<<<<<<<< + * + * +*/ + __pyx_r = 0; + goto __pyx_L0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":103 + * + * + * cdef inline int write_double(CyTransportBase buf, double val) except -1: # <<<<<<<<<<<<<< + * cdef int64_t v + * memcpy(&v, &val, 8) +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("thriftpy2.protocol.cybin.cybin.write_double", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/protocol/cybin/cybin.pyx":111 + * + * + * cdef inline write_list(CyTransportBase buf, object val, spec): # <<<<<<<<<<<<<< + * cdef TType e_type + * cdef int val_len +*/ + +static CYTHON_INLINE PyObject *__pyx_f_9thriftpy2_8protocol_5cybin_5cybin_write_list(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *__pyx_v_buf, PyObject *__pyx_v_val, PyObject *__pyx_v_spec) { + __pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType __pyx_v_e_type; + int __pyx_v_val_len; + PyObject *__pyx_v_e_spec = NULL; + PyObject *__pyx_v_e_val = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + Py_ssize_t __pyx_t_4; + int __pyx_t_5; + PyObject *(*__pyx_t_6)(PyObject *); + PyObject *__pyx_t_7 = NULL; + struct __pyx_opt_args_9thriftpy2_8protocol_5cybin_5cybin_c_write_val __pyx_t_8; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("write_list", 0); + + /* "thriftpy2/protocol/cybin/cybin.pyx":115 + * cdef int val_len + * + * if isinstance(spec, int): # <<<<<<<<<<<<<< + * e_type = spec + * e_spec = None +*/ + __pyx_t_1 = PyLong_Check(__pyx_v_spec); + if (__pyx_t_1) { + + /* "thriftpy2/protocol/cybin/cybin.pyx":116 + * + * if isinstance(spec, int): + * e_type = spec # <<<<<<<<<<<<<< + * e_spec = None + * else: +*/ + __pyx_t_2 = ((__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)__Pyx_PyLong_As___pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType(__pyx_v_spec)); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 116, __pyx_L1_error) + __pyx_v_e_type = __pyx_t_2; + + /* "thriftpy2/protocol/cybin/cybin.pyx":117 + * if isinstance(spec, int): + * e_type = spec + * e_spec = None # <<<<<<<<<<<<<< + * else: + * e_type = spec[0] +*/ + __Pyx_INCREF(Py_None); + __pyx_v_e_spec = Py_None; + + /* "thriftpy2/protocol/cybin/cybin.pyx":115 + * cdef int val_len + * + * if isinstance(spec, int): # <<<<<<<<<<<<<< + * e_type = spec + * e_spec = None +*/ + goto __pyx_L3; + } + + /* "thriftpy2/protocol/cybin/cybin.pyx":119 + * e_spec = None + * else: + * e_type = spec[0] # <<<<<<<<<<<<<< + * e_spec = spec[1] + * +*/ + /*else*/ { + __pyx_t_3 = __Pyx_GetItemInt(__pyx_v_spec, 0, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1, __Pyx_ReferenceSharing_FunctionArgument); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 119, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = ((__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)__Pyx_PyLong_As___pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType(__pyx_t_3)); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 119, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_e_type = __pyx_t_2; + + /* "thriftpy2/protocol/cybin/cybin.pyx":120 + * else: + * e_type = spec[0] + * e_spec = spec[1] # <<<<<<<<<<<<<< + * + * if e_type == T_BINARY: +*/ + __pyx_t_3 = __Pyx_GetItemInt(__pyx_v_spec, 1, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1, __Pyx_ReferenceSharing_FunctionArgument); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 120, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_v_e_spec = __pyx_t_3; + __pyx_t_3 = 0; + } + __pyx_L3:; + + /* "thriftpy2/protocol/cybin/cybin.pyx":122 + * e_spec = spec[1] + * + * if e_type == T_BINARY: # <<<<<<<<<<<<<< + * e_type = T_STRING + * +*/ + __pyx_t_1 = (__pyx_v_e_type == __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_BINARY); + if (__pyx_t_1) { + + /* "thriftpy2/protocol/cybin/cybin.pyx":123 + * + * if e_type == T_BINARY: + * e_type = T_STRING # <<<<<<<<<<<<<< + * + * val_len = len(val) +*/ + __pyx_v_e_type = __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_STRING; + + /* "thriftpy2/protocol/cybin/cybin.pyx":122 + * e_spec = spec[1] + * + * if e_type == T_BINARY: # <<<<<<<<<<<<<< + * e_type = T_STRING + * +*/ + } + + /* "thriftpy2/protocol/cybin/cybin.pyx":125 + * e_type = T_STRING + * + * val_len = len(val) # <<<<<<<<<<<<<< + * write_i08(buf, e_type) + * write_i32(buf, val_len) +*/ + __pyx_t_4 = PyObject_Length(__pyx_v_val); if (unlikely(__pyx_t_4 == ((Py_ssize_t)-1))) __PYX_ERR(0, 125, __pyx_L1_error) + __pyx_v_val_len = __pyx_t_4; + + /* "thriftpy2/protocol/cybin/cybin.pyx":126 + * + * val_len = len(val) + * write_i08(buf, e_type) # <<<<<<<<<<<<<< + * write_i32(buf, val_len) + * +*/ + __pyx_t_5 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_write_i08(__pyx_v_buf, __pyx_v_e_type); if (unlikely(__pyx_t_5 == ((int)-1))) __PYX_ERR(0, 126, __pyx_L1_error) + + /* "thriftpy2/protocol/cybin/cybin.pyx":127 + * val_len = len(val) + * write_i08(buf, e_type) + * write_i32(buf, val_len) # <<<<<<<<<<<<<< + * + * for e_val in val: +*/ + __pyx_t_5 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_write_i32(__pyx_v_buf, __pyx_v_val_len); if (unlikely(__pyx_t_5 == ((int)-1))) __PYX_ERR(0, 127, __pyx_L1_error) + + /* "thriftpy2/protocol/cybin/cybin.pyx":129 + * write_i32(buf, val_len) + * + * for e_val in val: # <<<<<<<<<<<<<< + * c_write_val(buf, e_type, e_val, e_spec) + * +*/ + if (likely(PyList_CheckExact(__pyx_v_val)) || PyTuple_CheckExact(__pyx_v_val)) { + __pyx_t_3 = __pyx_v_val; __Pyx_INCREF(__pyx_t_3); + __pyx_t_4 = 0; + __pyx_t_6 = NULL; + } else { + __pyx_t_4 = -1; __pyx_t_3 = PyObject_GetIter(__pyx_v_val); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 129, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_6 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_3); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 129, __pyx_L1_error) + } + for (;;) { + if (likely(!__pyx_t_6)) { + if (likely(PyList_CheckExact(__pyx_t_3))) { + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_3); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 129, __pyx_L1_error) + #endif + if (__pyx_t_4 >= __pyx_temp) break; + } + __pyx_t_7 = __Pyx_PyList_GetItemRefFast(__pyx_t_3, __pyx_t_4, __Pyx_ReferenceSharing_OwnStrongReference); + ++__pyx_t_4; + } else { + { + Py_ssize_t __pyx_temp = __Pyx_PyTuple_GET_SIZE(__pyx_t_3); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 129, __pyx_L1_error) + #endif + if (__pyx_t_4 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_7 = __Pyx_NewRef(PyTuple_GET_ITEM(__pyx_t_3, __pyx_t_4)); + #else + __pyx_t_7 = __Pyx_PySequence_ITEM(__pyx_t_3, __pyx_t_4); + #endif + ++__pyx_t_4; + } + if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 129, __pyx_L1_error) + } else { + __pyx_t_7 = __pyx_t_6(__pyx_t_3); + if (unlikely(!__pyx_t_7)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (unlikely(!__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) __PYX_ERR(0, 129, __pyx_L1_error) + PyErr_Clear(); + } + break; + } + } + __Pyx_GOTREF(__pyx_t_7); + __Pyx_XDECREF_SET(__pyx_v_e_val, __pyx_t_7); + __pyx_t_7 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":130 + * + * for e_val in val: + * c_write_val(buf, e_type, e_val, e_spec) # <<<<<<<<<<<<<< + * + * +*/ + __pyx_t_8.__pyx_n = 1; + __pyx_t_8.spec = __pyx_v_e_spec; + __pyx_t_7 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_c_write_val(__pyx_v_buf, __pyx_v_e_type, __pyx_v_e_val, &__pyx_t_8); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 130, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":129 + * write_i32(buf, val_len) + * + * for e_val in val: # <<<<<<<<<<<<<< + * c_write_val(buf, e_type, e_val, e_spec) + * +*/ + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":111 + * + * + * cdef inline write_list(CyTransportBase buf, object val, spec): # <<<<<<<<<<<<<< + * cdef TType e_type + * cdef int val_len +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_AddTraceback("thriftpy2.protocol.cybin.cybin.write_list", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_e_spec); + __Pyx_XDECREF(__pyx_v_e_val); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/protocol/cybin/cybin.pyx":133 + * + * + * cdef inline write_string(CyTransportBase buf, bytes val): # <<<<<<<<<<<<<< + * cdef int val_len = len(val) + * write_i32(buf, val_len) +*/ + +static CYTHON_INLINE PyObject *__pyx_f_9thriftpy2_8protocol_5cybin_5cybin_write_string(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *__pyx_v_buf, PyObject *__pyx_v_val) { + int __pyx_v_val_len; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + int __pyx_t_2; + char *__pyx_t_3; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("write_string", 0); + + /* "thriftpy2/protocol/cybin/cybin.pyx":134 + * + * cdef inline write_string(CyTransportBase buf, bytes val): + * cdef int val_len = len(val) # <<<<<<<<<<<<<< + * write_i32(buf, val_len) + * +*/ + if (unlikely(__pyx_v_val == Py_None)) { + PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); + __PYX_ERR(0, 134, __pyx_L1_error) + } + __pyx_t_1 = __Pyx_PyBytes_GET_SIZE(__pyx_v_val); if (unlikely(__pyx_t_1 == ((Py_ssize_t)-1))) __PYX_ERR(0, 134, __pyx_L1_error) + __pyx_v_val_len = __pyx_t_1; + + /* "thriftpy2/protocol/cybin/cybin.pyx":135 + * cdef inline write_string(CyTransportBase buf, bytes val): + * cdef int val_len = len(val) + * write_i32(buf, val_len) # <<<<<<<<<<<<<< + * + * buf.c_write(val, val_len) +*/ + __pyx_t_2 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_write_i32(__pyx_v_buf, __pyx_v_val_len); if (unlikely(__pyx_t_2 == ((int)-1))) __PYX_ERR(0, 135, __pyx_L1_error) + + /* "thriftpy2/protocol/cybin/cybin.pyx":137 + * write_i32(buf, val_len) + * + * buf.c_write(val, val_len) # <<<<<<<<<<<<<< + * + * +*/ + if (unlikely(__pyx_v_val == Py_None)) { + PyErr_SetString(PyExc_TypeError, "expected bytes, NoneType found"); + __PYX_ERR(0, 137, __pyx_L1_error) + } + __pyx_t_3 = __Pyx_PyBytes_AsWritableString(__pyx_v_val); if (unlikely((!__pyx_t_3) && PyErr_Occurred())) __PYX_ERR(0, 137, __pyx_L1_error) + __pyx_t_4 = ((struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_CyTransportBase *)__pyx_v_buf->__pyx_vtab)->c_write(__pyx_v_buf, ((char *)__pyx_t_3), __pyx_v_val_len); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 137, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":133 + * + * + * cdef inline write_string(CyTransportBase buf, bytes val): # <<<<<<<<<<<<<< + * cdef int val_len = len(val) + * write_i32(buf, val_len) +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("thriftpy2.protocol.cybin.cybin.write_string", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/protocol/cybin/cybin.pyx":140 + * + * + * cdef inline write_dict(CyTransportBase buf, object val, spec): # <<<<<<<<<<<<<< + * cdef int val_len + * cdef TType v_type, k_type +*/ + +static CYTHON_INLINE PyObject *__pyx_f_9thriftpy2_8protocol_5cybin_5cybin_write_dict(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *__pyx_v_buf, PyObject *__pyx_v_val, PyObject *__pyx_v_spec) { + int __pyx_v_val_len; + __pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType __pyx_v_v_type; + __pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType __pyx_v_k_type; + PyObject *__pyx_v_key = NULL; + PyObject *__pyx_v_k_spec = NULL; + PyObject *__pyx_v_value = NULL; + PyObject *__pyx_v_v_spec = NULL; + PyObject *__pyx_v_k = NULL; + PyObject *__pyx_v_v = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + __pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType __pyx_t_3; + Py_ssize_t __pyx_t_4; + int __pyx_t_5; + Py_ssize_t __pyx_t_6; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + int __pyx_t_9; + struct __pyx_opt_args_9thriftpy2_8protocol_5cybin_5cybin_c_write_val __pyx_t_10; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("write_dict", 0); + + /* "thriftpy2/protocol/cybin/cybin.pyx":144 + * cdef TType v_type, k_type + * + * key = spec[0] # <<<<<<<<<<<<<< + * if isinstance(key, int): + * k_type = key +*/ + __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_spec, 0, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1, __Pyx_ReferenceSharing_FunctionArgument); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 144, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_key = __pyx_t_1; + __pyx_t_1 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":145 + * + * key = spec[0] + * if isinstance(key, int): # <<<<<<<<<<<<<< + * k_type = key + * k_spec = None +*/ + __pyx_t_2 = PyLong_Check(__pyx_v_key); + if (__pyx_t_2) { + + /* "thriftpy2/protocol/cybin/cybin.pyx":146 + * key = spec[0] + * if isinstance(key, int): + * k_type = key # <<<<<<<<<<<<<< + * k_spec = None + * else: +*/ + __pyx_t_3 = ((__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)__Pyx_PyLong_As___pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType(__pyx_v_key)); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 146, __pyx_L1_error) + __pyx_v_k_type = __pyx_t_3; + + /* "thriftpy2/protocol/cybin/cybin.pyx":147 + * if isinstance(key, int): + * k_type = key + * k_spec = None # <<<<<<<<<<<<<< + * else: + * k_type = key[0] +*/ + __Pyx_INCREF(Py_None); + __pyx_v_k_spec = Py_None; + + /* "thriftpy2/protocol/cybin/cybin.pyx":145 + * + * key = spec[0] + * if isinstance(key, int): # <<<<<<<<<<<<<< + * k_type = key + * k_spec = None +*/ + goto __pyx_L3; + } + + /* "thriftpy2/protocol/cybin/cybin.pyx":149 + * k_spec = None + * else: + * k_type = key[0] # <<<<<<<<<<<<<< + * k_spec = key[1] + * +*/ + /*else*/ { + __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_key, 0, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1, __Pyx_ReferenceSharing_OwnStrongReference); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 149, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = ((__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)__Pyx_PyLong_As___pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType(__pyx_t_1)); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 149, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_k_type = __pyx_t_3; + + /* "thriftpy2/protocol/cybin/cybin.pyx":150 + * else: + * k_type = key[0] + * k_spec = key[1] # <<<<<<<<<<<<<< + * + * if k_type == T_BINARY: +*/ + __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_key, 1, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1, __Pyx_ReferenceSharing_OwnStrongReference); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 150, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_k_spec = __pyx_t_1; + __pyx_t_1 = 0; + } + __pyx_L3:; + + /* "thriftpy2/protocol/cybin/cybin.pyx":152 + * k_spec = key[1] + * + * if k_type == T_BINARY: # <<<<<<<<<<<<<< + * k_type = T_STRING + * +*/ + __pyx_t_2 = (__pyx_v_k_type == __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_BINARY); + if (__pyx_t_2) { + + /* "thriftpy2/protocol/cybin/cybin.pyx":153 + * + * if k_type == T_BINARY: + * k_type = T_STRING # <<<<<<<<<<<<<< + * + * value = spec[1] +*/ + __pyx_v_k_type = __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_STRING; + + /* "thriftpy2/protocol/cybin/cybin.pyx":152 + * k_spec = key[1] + * + * if k_type == T_BINARY: # <<<<<<<<<<<<<< + * k_type = T_STRING + * +*/ + } + + /* "thriftpy2/protocol/cybin/cybin.pyx":155 + * k_type = T_STRING + * + * value = spec[1] # <<<<<<<<<<<<<< + * if isinstance(value, int): + * v_type = value +*/ + __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_spec, 1, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1, __Pyx_ReferenceSharing_FunctionArgument); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 155, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_value = __pyx_t_1; + __pyx_t_1 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":156 + * + * value = spec[1] + * if isinstance(value, int): # <<<<<<<<<<<<<< + * v_type = value + * v_spec = None +*/ + __pyx_t_2 = PyLong_Check(__pyx_v_value); + if (__pyx_t_2) { + + /* "thriftpy2/protocol/cybin/cybin.pyx":157 + * value = spec[1] + * if isinstance(value, int): + * v_type = value # <<<<<<<<<<<<<< + * v_spec = None + * else: +*/ + __pyx_t_3 = ((__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)__Pyx_PyLong_As___pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType(__pyx_v_value)); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 157, __pyx_L1_error) + __pyx_v_v_type = __pyx_t_3; + + /* "thriftpy2/protocol/cybin/cybin.pyx":158 + * if isinstance(value, int): + * v_type = value + * v_spec = None # <<<<<<<<<<<<<< + * else: + * v_type = value[0] +*/ + __Pyx_INCREF(Py_None); + __pyx_v_v_spec = Py_None; + + /* "thriftpy2/protocol/cybin/cybin.pyx":156 + * + * value = spec[1] + * if isinstance(value, int): # <<<<<<<<<<<<<< + * v_type = value + * v_spec = None +*/ + goto __pyx_L5; + } + + /* "thriftpy2/protocol/cybin/cybin.pyx":160 + * v_spec = None + * else: + * v_type = value[0] # <<<<<<<<<<<<<< + * v_spec = value[1] + * +*/ + /*else*/ { + __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_value, 0, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1, __Pyx_ReferenceSharing_OwnStrongReference); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 160, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = ((__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)__Pyx_PyLong_As___pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType(__pyx_t_1)); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 160, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_v_type = __pyx_t_3; + + /* "thriftpy2/protocol/cybin/cybin.pyx":161 + * else: + * v_type = value[0] + * v_spec = value[1] # <<<<<<<<<<<<<< + * + * if v_type == T_BINARY: +*/ + __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_value, 1, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1, __Pyx_ReferenceSharing_OwnStrongReference); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 161, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_v_spec = __pyx_t_1; + __pyx_t_1 = 0; + } + __pyx_L5:; + + /* "thriftpy2/protocol/cybin/cybin.pyx":163 + * v_spec = value[1] + * + * if v_type == T_BINARY: # <<<<<<<<<<<<<< + * v_type = T_STRING + * +*/ + __pyx_t_2 = (__pyx_v_v_type == __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_BINARY); + if (__pyx_t_2) { + + /* "thriftpy2/protocol/cybin/cybin.pyx":164 + * + * if v_type == T_BINARY: + * v_type = T_STRING # <<<<<<<<<<<<<< + * + * val_len = len(val) +*/ + __pyx_v_v_type = __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_STRING; + + /* "thriftpy2/protocol/cybin/cybin.pyx":163 + * v_spec = value[1] + * + * if v_type == T_BINARY: # <<<<<<<<<<<<<< + * v_type = T_STRING + * +*/ + } + + /* "thriftpy2/protocol/cybin/cybin.pyx":166 + * v_type = T_STRING + * + * val_len = len(val) # <<<<<<<<<<<<<< + * + * write_i08(buf, k_type) +*/ + __pyx_t_4 = PyObject_Length(__pyx_v_val); if (unlikely(__pyx_t_4 == ((Py_ssize_t)-1))) __PYX_ERR(0, 166, __pyx_L1_error) + __pyx_v_val_len = __pyx_t_4; + + /* "thriftpy2/protocol/cybin/cybin.pyx":168 + * val_len = len(val) + * + * write_i08(buf, k_type) # <<<<<<<<<<<<<< + * write_i08(buf, v_type) + * write_i32(buf, val_len) +*/ + __pyx_t_5 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_write_i08(__pyx_v_buf, __pyx_v_k_type); if (unlikely(__pyx_t_5 == ((int)-1))) __PYX_ERR(0, 168, __pyx_L1_error) + + /* "thriftpy2/protocol/cybin/cybin.pyx":169 + * + * write_i08(buf, k_type) + * write_i08(buf, v_type) # <<<<<<<<<<<<<< + * write_i32(buf, val_len) + * +*/ + __pyx_t_5 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_write_i08(__pyx_v_buf, __pyx_v_v_type); if (unlikely(__pyx_t_5 == ((int)-1))) __PYX_ERR(0, 169, __pyx_L1_error) + + /* "thriftpy2/protocol/cybin/cybin.pyx":170 + * write_i08(buf, k_type) + * write_i08(buf, v_type) + * write_i32(buf, val_len) # <<<<<<<<<<<<<< + * + * for k, v in val.items(): +*/ + __pyx_t_5 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_write_i32(__pyx_v_buf, __pyx_v_val_len); if (unlikely(__pyx_t_5 == ((int)-1))) __PYX_ERR(0, 170, __pyx_L1_error) + + /* "thriftpy2/protocol/cybin/cybin.pyx":172 + * write_i32(buf, val_len) + * + * for k, v in val.items(): # <<<<<<<<<<<<<< + * c_write_val(buf, k_type, k, k_spec) + * c_write_val(buf, v_type, v, v_spec) +*/ + __pyx_t_4 = 0; + if (unlikely(__pyx_v_val == Py_None)) { + PyErr_Format(PyExc_AttributeError, "'NoneType' object has no attribute '%.30s'", "items"); + __PYX_ERR(0, 172, __pyx_L1_error) + } + __pyx_t_7 = __Pyx_dict_iterator(__pyx_v_val, 0, __pyx_mstate_global->__pyx_n_u_items, (&__pyx_t_6), (&__pyx_t_5)); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 172, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_1); + __pyx_t_1 = __pyx_t_7; + __pyx_t_7 = 0; + while (1) { + __pyx_t_9 = __Pyx_dict_iter_next(__pyx_t_1, __pyx_t_6, &__pyx_t_4, &__pyx_t_7, &__pyx_t_8, NULL, __pyx_t_5); + if (unlikely(__pyx_t_9 == 0)) break; + if (unlikely(__pyx_t_9 == -1)) __PYX_ERR(0, 172, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __Pyx_GOTREF(__pyx_t_8); + __Pyx_XDECREF_SET(__pyx_v_k, __pyx_t_7); + __pyx_t_7 = 0; + __Pyx_XDECREF_SET(__pyx_v_v, __pyx_t_8); + __pyx_t_8 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":173 + * + * for k, v in val.items(): + * c_write_val(buf, k_type, k, k_spec) # <<<<<<<<<<<<<< + * c_write_val(buf, v_type, v, v_spec) + * +*/ + __pyx_t_10.__pyx_n = 1; + __pyx_t_10.spec = __pyx_v_k_spec; + __pyx_t_8 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_c_write_val(__pyx_v_buf, __pyx_v_k_type, __pyx_v_k, &__pyx_t_10); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 173, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":174 + * for k, v in val.items(): + * c_write_val(buf, k_type, k, k_spec) + * c_write_val(buf, v_type, v, v_spec) # <<<<<<<<<<<<<< + * + * +*/ + __pyx_t_10.__pyx_n = 1; + __pyx_t_10.spec = __pyx_v_v_spec; + __pyx_t_8 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_c_write_val(__pyx_v_buf, __pyx_v_v_type, __pyx_v_v, &__pyx_t_10); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 174, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":140 + * + * + * cdef inline write_dict(CyTransportBase buf, object val, spec): # <<<<<<<<<<<<<< + * cdef int val_len + * cdef TType v_type, k_type +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_AddTraceback("thriftpy2.protocol.cybin.cybin.write_dict", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_key); + __Pyx_XDECREF(__pyx_v_k_spec); + __Pyx_XDECREF(__pyx_v_value); + __Pyx_XDECREF(__pyx_v_v_spec); + __Pyx_XDECREF(__pyx_v_k); + __Pyx_XDECREF(__pyx_v_v); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/protocol/cybin/cybin.pyx":177 + * + * + * cdef inline read_struct(CyTransportBase buf, obj, decode_response=True, # <<<<<<<<<<<<<< + * strict_decode=False): + * cdef dict field_specs = obj.thrift_spec +*/ + +static CYTHON_INLINE PyObject *__pyx_f_9thriftpy2_8protocol_5cybin_5cybin_read_struct(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *__pyx_v_buf, PyObject *__pyx_v_obj, struct __pyx_opt_args_9thriftpy2_8protocol_5cybin_5cybin_read_struct *__pyx_optional_args) { + PyObject *__pyx_v_decode_response = ((PyObject *)Py_True); + + /* "thriftpy2/protocol/cybin/cybin.pyx":178 + * + * cdef inline read_struct(CyTransportBase buf, obj, decode_response=True, + * strict_decode=False): # <<<<<<<<<<<<<< + * cdef dict field_specs = obj.thrift_spec + * cdef int fid +*/ + PyObject *__pyx_v_strict_decode = ((PyObject *)Py_False); + PyObject *__pyx_v_field_specs = 0; + int __pyx_v_fid; + __pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType __pyx_v_field_type; + __pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType __pyx_v_ttype; + PyObject *__pyx_v_field_spec = 0; + PyObject *__pyx_v_name = 0; + PyObject *__pyx_v_spec = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + char __pyx_t_2; + int __pyx_t_3; + int16_t __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + __pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType __pyx_t_6; + int __pyx_t_7; + int __pyx_t_8; + Py_ssize_t __pyx_t_9; + struct __pyx_opt_args_9thriftpy2_8protocol_5cybin_5cybin_c_read_val __pyx_t_10; + int __pyx_t_11; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("read_struct", 0); + if (__pyx_optional_args) { + if (__pyx_optional_args->__pyx_n > 0) { + __pyx_v_decode_response = __pyx_optional_args->decode_response; + if (__pyx_optional_args->__pyx_n > 1) { + __pyx_v_strict_decode = __pyx_optional_args->strict_decode; + } + } + } + + /* "thriftpy2/protocol/cybin/cybin.pyx":179 + * cdef inline read_struct(CyTransportBase buf, obj, decode_response=True, + * strict_decode=False): + * cdef dict field_specs = obj.thrift_spec # <<<<<<<<<<<<<< + * cdef int fid + * cdef TType field_type, ttype +*/ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_obj, __pyx_mstate_global->__pyx_n_u_thrift_spec); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 179, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(PyDict_CheckExact(__pyx_t_1))||((__pyx_t_1) == Py_None) || __Pyx_RaiseUnexpectedTypeError("dict", __pyx_t_1))) __PYX_ERR(0, 179, __pyx_L1_error) + __pyx_v_field_specs = ((PyObject*)__pyx_t_1); + __pyx_t_1 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":185 + * cdef str name + * + * while True: # <<<<<<<<<<<<<< + * field_type = read_i08(buf) + * if field_type == T_STOP: +*/ + while (1) { + + /* "thriftpy2/protocol/cybin/cybin.pyx":186 + * + * while True: + * field_type = read_i08(buf) # <<<<<<<<<<<<<< + * if field_type == T_STOP: + * break +*/ + __pyx_t_2 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_read_i08(__pyx_v_buf); if (unlikely(__pyx_t_2 == ((char)-1) && PyErr_Occurred())) __PYX_ERR(0, 186, __pyx_L1_error) + __pyx_v_field_type = ((__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)__pyx_t_2); + + /* "thriftpy2/protocol/cybin/cybin.pyx":187 + * while True: + * field_type = read_i08(buf) + * if field_type == T_STOP: # <<<<<<<<<<<<<< + * break + * +*/ + __pyx_t_3 = (__pyx_v_field_type == __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_STOP); + if (__pyx_t_3) { + + /* "thriftpy2/protocol/cybin/cybin.pyx":188 + * field_type = read_i08(buf) + * if field_type == T_STOP: + * break # <<<<<<<<<<<<<< + * + * fid = read_i16(buf) +*/ + goto __pyx_L4_break; + + /* "thriftpy2/protocol/cybin/cybin.pyx":187 + * while True: + * field_type = read_i08(buf) + * if field_type == T_STOP: # <<<<<<<<<<<<<< + * break + * +*/ + } + + /* "thriftpy2/protocol/cybin/cybin.pyx":190 + * break + * + * fid = read_i16(buf) # <<<<<<<<<<<<<< + * if fid not in field_specs: + * skip(buf, field_type) +*/ + __pyx_t_4 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_read_i16(__pyx_v_buf); if (unlikely(__pyx_t_4 == ((int16_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 190, __pyx_L1_error) + __pyx_v_fid = __pyx_t_4; + + /* "thriftpy2/protocol/cybin/cybin.pyx":191 + * + * fid = read_i16(buf) + * if fid not in field_specs: # <<<<<<<<<<<<<< + * skip(buf, field_type) + * continue +*/ + __pyx_t_1 = __Pyx_PyLong_From_int(__pyx_v_fid); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 191, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + if (unlikely(__pyx_v_field_specs == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); + __PYX_ERR(0, 191, __pyx_L1_error) + } + __pyx_t_3 = (__Pyx_PyDict_ContainsTF(__pyx_t_1, __pyx_v_field_specs, Py_NE)); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 191, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (__pyx_t_3) { + + /* "thriftpy2/protocol/cybin/cybin.pyx":192 + * fid = read_i16(buf) + * if fid not in field_specs: + * skip(buf, field_type) # <<<<<<<<<<<<<< + * continue + * +*/ + __pyx_t_1 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_skip(__pyx_v_buf, __pyx_v_field_type, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 192, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":193 + * if fid not in field_specs: + * skip(buf, field_type) + * continue # <<<<<<<<<<<<<< + * + * field_spec = field_specs[fid] +*/ + goto __pyx_L3_continue; + + /* "thriftpy2/protocol/cybin/cybin.pyx":191 + * + * fid = read_i16(buf) + * if fid not in field_specs: # <<<<<<<<<<<<<< + * skip(buf, field_type) + * continue +*/ + } + + /* "thriftpy2/protocol/cybin/cybin.pyx":195 + * continue + * + * field_spec = field_specs[fid] # <<<<<<<<<<<<<< + * ttype = field_spec[0] + * if field_type != ttype and not (ttype in BIN_TYPES and field_type in BIN_TYPES): +*/ + if (unlikely(__pyx_v_field_specs == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); + __PYX_ERR(0, 195, __pyx_L1_error) + } + __pyx_t_1 = __Pyx_PyLong_From_int(__pyx_v_fid); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 195, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_5 = __Pyx_PyDict_GetItem(__pyx_v_field_specs, __pyx_t_1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 195, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (!(likely(PyTuple_CheckExact(__pyx_t_5))||((__pyx_t_5) == Py_None) || __Pyx_RaiseUnexpectedTypeError("tuple", __pyx_t_5))) __PYX_ERR(0, 195, __pyx_L1_error) + __Pyx_XDECREF_SET(__pyx_v_field_spec, ((PyObject*)__pyx_t_5)); + __pyx_t_5 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":196 + * + * field_spec = field_specs[fid] + * ttype = field_spec[0] # <<<<<<<<<<<<<< + * if field_type != ttype and not (ttype in BIN_TYPES and field_type in BIN_TYPES): + * skip(buf, field_type) +*/ + if (unlikely(__pyx_v_field_spec == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); + __PYX_ERR(0, 196, __pyx_L1_error) + } + __pyx_t_5 = __Pyx_GetItemInt_Tuple(__pyx_v_field_spec, 0, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1, __Pyx_ReferenceSharing_OwnStrongReference); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 196, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = ((__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)__Pyx_PyLong_As___pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType(__pyx_t_5)); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 196, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_v_ttype = __pyx_t_6; + + /* "thriftpy2/protocol/cybin/cybin.pyx":197 + * field_spec = field_specs[fid] + * ttype = field_spec[0] + * if field_type != ttype and not (ttype in BIN_TYPES and field_type in BIN_TYPES): # <<<<<<<<<<<<<< + * skip(buf, field_type) + * continue +*/ + __pyx_t_7 = (__pyx_v_field_type != __pyx_v_ttype); + if (__pyx_t_7) { + } else { + __pyx_t_3 = __pyx_t_7; + goto __pyx_L8_bool_binop_done; + } + __pyx_t_5 = __Pyx_PyLong_From___pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType(__pyx_v_ttype); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 197, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_mstate_global->__pyx_n_u_BIN_TYPES); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 197, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_8 = (__Pyx_PySequence_ContainsTF(__pyx_t_5, __pyx_t_1, Py_EQ)); if (unlikely((__pyx_t_8 < 0))) __PYX_ERR(0, 197, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (__pyx_t_8) { + } else { + __pyx_t_7 = __pyx_t_8; + goto __pyx_L10_bool_binop_done; + } + __pyx_t_1 = __Pyx_PyLong_From___pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType(__pyx_v_field_type); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 197, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_GetModuleGlobalName(__pyx_t_5, __pyx_mstate_global->__pyx_n_u_BIN_TYPES); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 197, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_8 = (__Pyx_PySequence_ContainsTF(__pyx_t_1, __pyx_t_5, Py_EQ)); if (unlikely((__pyx_t_8 < 0))) __PYX_ERR(0, 197, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_7 = __pyx_t_8; + __pyx_L10_bool_binop_done:; + __pyx_t_8 = (!__pyx_t_7); + __pyx_t_3 = __pyx_t_8; + __pyx_L8_bool_binop_done:; + if (__pyx_t_3) { + + /* "thriftpy2/protocol/cybin/cybin.pyx":198 + * ttype = field_spec[0] + * if field_type != ttype and not (ttype in BIN_TYPES and field_type in BIN_TYPES): + * skip(buf, field_type) # <<<<<<<<<<<<<< + * continue + * +*/ + __pyx_t_5 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_skip(__pyx_v_buf, __pyx_v_field_type, 0); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 198, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":199 + * if field_type != ttype and not (ttype in BIN_TYPES and field_type in BIN_TYPES): + * skip(buf, field_type) + * continue # <<<<<<<<<<<<<< + * + * name = field_spec[1] +*/ + goto __pyx_L3_continue; + + /* "thriftpy2/protocol/cybin/cybin.pyx":197 + * field_spec = field_specs[fid] + * ttype = field_spec[0] + * if field_type != ttype and not (ttype in BIN_TYPES and field_type in BIN_TYPES): # <<<<<<<<<<<<<< + * skip(buf, field_type) + * continue +*/ + } + + /* "thriftpy2/protocol/cybin/cybin.pyx":201 + * continue + * + * name = field_spec[1] # <<<<<<<<<<<<<< + * if len(field_spec) <= 3: + * spec = None +*/ + if (unlikely(__pyx_v_field_spec == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); + __PYX_ERR(0, 201, __pyx_L1_error) + } + __pyx_t_5 = __Pyx_GetItemInt_Tuple(__pyx_v_field_spec, 1, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1, __Pyx_ReferenceSharing_OwnStrongReference); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 201, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + if (!(likely(PyUnicode_CheckExact(__pyx_t_5))||((__pyx_t_5) == Py_None) || __Pyx_RaiseUnexpectedTypeError("str", __pyx_t_5))) __PYX_ERR(0, 201, __pyx_L1_error) + __Pyx_XDECREF_SET(__pyx_v_name, ((PyObject*)__pyx_t_5)); + __pyx_t_5 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":202 + * + * name = field_spec[1] + * if len(field_spec) <= 3: # <<<<<<<<<<<<<< + * spec = None + * else: +*/ + if (unlikely(__pyx_v_field_spec == Py_None)) { + PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); + __PYX_ERR(0, 202, __pyx_L1_error) + } + __pyx_t_9 = __Pyx_PyTuple_GET_SIZE(__pyx_v_field_spec); if (unlikely(__pyx_t_9 == ((Py_ssize_t)-1))) __PYX_ERR(0, 202, __pyx_L1_error) + __pyx_t_3 = (__pyx_t_9 <= 3); + if (__pyx_t_3) { + + /* "thriftpy2/protocol/cybin/cybin.pyx":203 + * name = field_spec[1] + * if len(field_spec) <= 3: + * spec = None # <<<<<<<<<<<<<< + * else: + * spec = field_spec[2] +*/ + __Pyx_INCREF(Py_None); + __Pyx_XDECREF_SET(__pyx_v_spec, Py_None); + + /* "thriftpy2/protocol/cybin/cybin.pyx":202 + * + * name = field_spec[1] + * if len(field_spec) <= 3: # <<<<<<<<<<<<<< + * spec = None + * else: +*/ + goto __pyx_L12; + } + + /* "thriftpy2/protocol/cybin/cybin.pyx":205 + * spec = None + * else: + * spec = field_spec[2] # <<<<<<<<<<<<<< + * + * setattr(obj, name, c_read_val(buf, ttype, spec, decode_response, +*/ + /*else*/ { + if (unlikely(__pyx_v_field_spec == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); + __PYX_ERR(0, 205, __pyx_L1_error) + } + __pyx_t_5 = __Pyx_GetItemInt_Tuple(__pyx_v_field_spec, 2, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1, __Pyx_ReferenceSharing_OwnStrongReference); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 205, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_XDECREF_SET(__pyx_v_spec, __pyx_t_5); + __pyx_t_5 = 0; + } + __pyx_L12:; + + /* "thriftpy2/protocol/cybin/cybin.pyx":207 + * spec = field_spec[2] + * + * setattr(obj, name, c_read_val(buf, ttype, spec, decode_response, # <<<<<<<<<<<<<< + * strict_decode)) + * +*/ + __pyx_t_10.__pyx_n = 3; + __pyx_t_10.spec = __pyx_v_spec; + __pyx_t_10.decode_response = __pyx_v_decode_response; + __pyx_t_10.strict_decode = __pyx_v_strict_decode; + __pyx_t_5 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_c_read_val(__pyx_v_buf, __pyx_v_ttype, &__pyx_t_10); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 207, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_11 = PyObject_SetAttr(__pyx_v_obj, __pyx_v_name, __pyx_t_5); if (unlikely(__pyx_t_11 == ((int)-1))) __PYX_ERR(0, 207, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_L3_continue:; + } + __pyx_L4_break:; + + /* "thriftpy2/protocol/cybin/cybin.pyx":210 + * strict_decode)) + * + * return obj # <<<<<<<<<<<<<< + * + * +*/ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_obj); + __pyx_r = __pyx_v_obj; + goto __pyx_L0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":177 + * + * + * cdef inline read_struct(CyTransportBase buf, obj, decode_response=True, # <<<<<<<<<<<<<< + * strict_decode=False): + * cdef dict field_specs = obj.thrift_spec +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("thriftpy2.protocol.cybin.cybin.read_struct", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_field_specs); + __Pyx_XDECREF(__pyx_v_field_spec); + __Pyx_XDECREF(__pyx_v_name); + __Pyx_XDECREF(__pyx_v_spec); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/protocol/cybin/cybin.pyx":213 + * + * + * cdef inline write_struct(CyTransportBase buf, obj): # <<<<<<<<<<<<<< + * cdef int fid + * cdef TType f_type +*/ + +static CYTHON_INLINE PyObject *__pyx_f_9thriftpy2_8protocol_5cybin_5cybin_write_struct(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *__pyx_v_buf, PyObject *__pyx_v_obj) { + int __pyx_v_fid; + __pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType __pyx_v_f_type; + PyObject *__pyx_v_thrift_spec = 0; + PyObject *__pyx_v_field_spec = 0; + PyObject *__pyx_v_f_name = 0; + PyObject *__pyx_v_container_spec = NULL; + PyObject *__pyx_v_v = NULL; + CYTHON_UNUSED PyObject *__pyx_v_e = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + Py_ssize_t __pyx_t_2; + Py_ssize_t __pyx_t_3; + int __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + int __pyx_t_7; + __pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType __pyx_t_8; + Py_ssize_t __pyx_t_9; + int __pyx_t_10; + PyObject *__pyx_t_11 = NULL; + PyObject *__pyx_t_12 = NULL; + PyObject *__pyx_t_13 = NULL; + struct __pyx_opt_args_9thriftpy2_8protocol_5cybin_5cybin_c_write_val __pyx_t_14; + PyObject *__pyx_t_15 = NULL; + PyObject *__pyx_t_16 = NULL; + PyObject *__pyx_t_17 = NULL; + PyObject *__pyx_t_18 = NULL; + PyObject *__pyx_t_19 = NULL; + PyObject *__pyx_t_20 = NULL; + PyObject *__pyx_t_21 = NULL; + size_t __pyx_t_22; + int __pyx_t_23; + char const *__pyx_t_24; + PyObject *__pyx_t_25 = NULL; + PyObject *__pyx_t_26 = NULL; + PyObject *__pyx_t_27 = NULL; + PyObject *__pyx_t_28 = NULL; + PyObject *__pyx_t_29 = NULL; + PyObject *__pyx_t_30 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("write_struct", 0); + + /* "thriftpy2/protocol/cybin/cybin.pyx":216 + * cdef int fid + * cdef TType f_type + * cdef dict thrift_spec = obj.thrift_spec # <<<<<<<<<<<<<< + * cdef tuple field_spec + * cdef str f_name +*/ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_obj, __pyx_mstate_global->__pyx_n_u_thrift_spec); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 216, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(PyDict_CheckExact(__pyx_t_1))||((__pyx_t_1) == Py_None) || __Pyx_RaiseUnexpectedTypeError("dict", __pyx_t_1))) __PYX_ERR(0, 216, __pyx_L1_error) + __pyx_v_thrift_spec = ((PyObject*)__pyx_t_1); + __pyx_t_1 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":220 + * cdef str f_name + * + * for fid, field_spec in thrift_spec.items(): # <<<<<<<<<<<<<< + * f_type = field_spec[0] + * f_name = field_spec[1] +*/ + __pyx_t_2 = 0; + if (unlikely(__pyx_v_thrift_spec == Py_None)) { + PyErr_Format(PyExc_AttributeError, "'NoneType' object has no attribute '%.30s'", "items"); + __PYX_ERR(0, 220, __pyx_L1_error) + } + __pyx_t_5 = __Pyx_dict_iterator(__pyx_v_thrift_spec, 1, __pyx_mstate_global->__pyx_n_u_items, (&__pyx_t_3), (&__pyx_t_4)); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 220, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_1); + __pyx_t_1 = __pyx_t_5; + __pyx_t_5 = 0; + while (1) { + __pyx_t_7 = __Pyx_dict_iter_next(__pyx_t_1, __pyx_t_3, &__pyx_t_2, &__pyx_t_5, &__pyx_t_6, NULL, __pyx_t_4); + if (unlikely(__pyx_t_7 == 0)) break; + if (unlikely(__pyx_t_7 == -1)) __PYX_ERR(0, 220, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = __Pyx_PyLong_As_int(__pyx_t_5); if (unlikely((__pyx_t_7 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 220, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (!(likely(PyTuple_CheckExact(__pyx_t_6))||((__pyx_t_6) == Py_None) || __Pyx_RaiseUnexpectedTypeError("tuple", __pyx_t_6))) __PYX_ERR(0, 220, __pyx_L1_error) + __pyx_v_fid = __pyx_t_7; + __Pyx_XDECREF_SET(__pyx_v_field_spec, ((PyObject*)__pyx_t_6)); + __pyx_t_6 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":221 + * + * for fid, field_spec in thrift_spec.items(): + * f_type = field_spec[0] # <<<<<<<<<<<<<< + * f_name = field_spec[1] + * if len(field_spec) <= 3: +*/ + if (unlikely(__pyx_v_field_spec == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); + __PYX_ERR(0, 221, __pyx_L1_error) + } + __pyx_t_6 = __Pyx_GetItemInt_Tuple(__pyx_v_field_spec, 0, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1, __Pyx_ReferenceSharing_OwnStrongReference); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 221, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_8 = ((__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)__Pyx_PyLong_As___pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType(__pyx_t_6)); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 221, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_v_f_type = __pyx_t_8; + + /* "thriftpy2/protocol/cybin/cybin.pyx":222 + * for fid, field_spec in thrift_spec.items(): + * f_type = field_spec[0] + * f_name = field_spec[1] # <<<<<<<<<<<<<< + * if len(field_spec) <= 3: + * container_spec = None +*/ + if (unlikely(__pyx_v_field_spec == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); + __PYX_ERR(0, 222, __pyx_L1_error) + } + __pyx_t_6 = __Pyx_GetItemInt_Tuple(__pyx_v_field_spec, 1, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1, __Pyx_ReferenceSharing_OwnStrongReference); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 222, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + if (!(likely(PyUnicode_CheckExact(__pyx_t_6))||((__pyx_t_6) == Py_None) || __Pyx_RaiseUnexpectedTypeError("str", __pyx_t_6))) __PYX_ERR(0, 222, __pyx_L1_error) + __Pyx_XDECREF_SET(__pyx_v_f_name, ((PyObject*)__pyx_t_6)); + __pyx_t_6 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":223 + * f_type = field_spec[0] + * f_name = field_spec[1] + * if len(field_spec) <= 3: # <<<<<<<<<<<<<< + * container_spec = None + * else: +*/ + if (unlikely(__pyx_v_field_spec == Py_None)) { + PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); + __PYX_ERR(0, 223, __pyx_L1_error) + } + __pyx_t_9 = __Pyx_PyTuple_GET_SIZE(__pyx_v_field_spec); if (unlikely(__pyx_t_9 == ((Py_ssize_t)-1))) __PYX_ERR(0, 223, __pyx_L1_error) + __pyx_t_10 = (__pyx_t_9 <= 3); + if (__pyx_t_10) { + + /* "thriftpy2/protocol/cybin/cybin.pyx":224 + * f_name = field_spec[1] + * if len(field_spec) <= 3: + * container_spec = None # <<<<<<<<<<<<<< + * else: + * container_spec = field_spec[2] +*/ + __Pyx_INCREF(Py_None); + __Pyx_XDECREF_SET(__pyx_v_container_spec, Py_None); + + /* "thriftpy2/protocol/cybin/cybin.pyx":223 + * f_type = field_spec[0] + * f_name = field_spec[1] + * if len(field_spec) <= 3: # <<<<<<<<<<<<<< + * container_spec = None + * else: +*/ + goto __pyx_L5; + } + + /* "thriftpy2/protocol/cybin/cybin.pyx":226 + * container_spec = None + * else: + * container_spec = field_spec[2] # <<<<<<<<<<<<<< + * + * v = getattr(obj, f_name, None) +*/ + /*else*/ { + if (unlikely(__pyx_v_field_spec == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); + __PYX_ERR(0, 226, __pyx_L1_error) + } + __pyx_t_6 = __Pyx_GetItemInt_Tuple(__pyx_v_field_spec, 2, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1, __Pyx_ReferenceSharing_OwnStrongReference); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 226, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_XDECREF_SET(__pyx_v_container_spec, __pyx_t_6); + __pyx_t_6 = 0; + } + __pyx_L5:; + + /* "thriftpy2/protocol/cybin/cybin.pyx":228 + * container_spec = field_spec[2] + * + * v = getattr(obj, f_name, None) # <<<<<<<<<<<<<< + * if v is None: + * continue +*/ + __pyx_t_6 = __Pyx_GetAttr3(__pyx_v_obj, __pyx_v_f_name, Py_None); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 228, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_XDECREF_SET(__pyx_v_v, __pyx_t_6); + __pyx_t_6 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":229 + * + * v = getattr(obj, f_name, None) + * if v is None: # <<<<<<<<<<<<<< + * continue + * if f_type == T_BINARY: +*/ + __pyx_t_10 = (__pyx_v_v == Py_None); + if (__pyx_t_10) { + + /* "thriftpy2/protocol/cybin/cybin.pyx":230 + * v = getattr(obj, f_name, None) + * if v is None: + * continue # <<<<<<<<<<<<<< + * if f_type == T_BINARY: + * write_i08(buf, T_STRING) +*/ + goto __pyx_L3_continue; + + /* "thriftpy2/protocol/cybin/cybin.pyx":229 + * + * v = getattr(obj, f_name, None) + * if v is None: # <<<<<<<<<<<<<< + * continue + * if f_type == T_BINARY: +*/ + } + + /* "thriftpy2/protocol/cybin/cybin.pyx":231 + * if v is None: + * continue + * if f_type == T_BINARY: # <<<<<<<<<<<<<< + * write_i08(buf, T_STRING) + * else: +*/ + __pyx_t_10 = (__pyx_v_f_type == __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_BINARY); + if (__pyx_t_10) { + + /* "thriftpy2/protocol/cybin/cybin.pyx":232 + * continue + * if f_type == T_BINARY: + * write_i08(buf, T_STRING) # <<<<<<<<<<<<<< + * else: + * write_i08(buf, f_type) +*/ + __pyx_t_7 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_write_i08(__pyx_v_buf, __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_STRING); if (unlikely(__pyx_t_7 == ((int)-1))) __PYX_ERR(0, 232, __pyx_L1_error) + + /* "thriftpy2/protocol/cybin/cybin.pyx":231 + * if v is None: + * continue + * if f_type == T_BINARY: # <<<<<<<<<<<<<< + * write_i08(buf, T_STRING) + * else: +*/ + goto __pyx_L7; + } + + /* "thriftpy2/protocol/cybin/cybin.pyx":234 + * write_i08(buf, T_STRING) + * else: + * write_i08(buf, f_type) # <<<<<<<<<<<<<< + * write_i16(buf, fid) + * try: +*/ + /*else*/ { + __pyx_t_7 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_write_i08(__pyx_v_buf, __pyx_v_f_type); if (unlikely(__pyx_t_7 == ((int)-1))) __PYX_ERR(0, 234, __pyx_L1_error) + } + __pyx_L7:; + + /* "thriftpy2/protocol/cybin/cybin.pyx":235 + * else: + * write_i08(buf, f_type) + * write_i16(buf, fid) # <<<<<<<<<<<<<< + * try: + * c_write_val(buf, f_type, v, container_spec) +*/ + __pyx_t_7 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_write_i16(__pyx_v_buf, __pyx_v_fid); if (unlikely(__pyx_t_7 == ((int)-1))) __PYX_ERR(0, 235, __pyx_L1_error) + + /* "thriftpy2/protocol/cybin/cybin.pyx":236 + * write_i08(buf, f_type) + * write_i16(buf, fid) + * try: # <<<<<<<<<<<<<< + * c_write_val(buf, f_type, v, container_spec) + * except (TypeError, AttributeError, AssertionError, OverflowError) as e: +*/ + { + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + __Pyx_ExceptionSave(&__pyx_t_11, &__pyx_t_12, &__pyx_t_13); + __Pyx_XGOTREF(__pyx_t_11); + __Pyx_XGOTREF(__pyx_t_12); + __Pyx_XGOTREF(__pyx_t_13); + /*try:*/ { + + /* "thriftpy2/protocol/cybin/cybin.pyx":237 + * write_i16(buf, fid) + * try: + * c_write_val(buf, f_type, v, container_spec) # <<<<<<<<<<<<<< + * except (TypeError, AttributeError, AssertionError, OverflowError) as e: + * raise TDecodeException(obj.__class__.__name__, fid, f_name, v, +*/ + __pyx_t_14.__pyx_n = 1; + __pyx_t_14.spec = __pyx_v_container_spec; + __pyx_t_6 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_c_write_val(__pyx_v_buf, __pyx_v_f_type, __pyx_v_v, &__pyx_t_14); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 237, __pyx_L8_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":236 + * write_i08(buf, f_type) + * write_i16(buf, fid) + * try: # <<<<<<<<<<<<<< + * c_write_val(buf, f_type, v, container_spec) + * except (TypeError, AttributeError, AssertionError, OverflowError) as e: +*/ + } + __Pyx_XDECREF(__pyx_t_11); __pyx_t_11 = 0; + __Pyx_XDECREF(__pyx_t_12); __pyx_t_12 = 0; + __Pyx_XDECREF(__pyx_t_13); __pyx_t_13 = 0; + goto __pyx_L15_try_end; + __pyx_L8_error:; + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":238 + * try: + * c_write_val(buf, f_type, v, container_spec) + * except (TypeError, AttributeError, AssertionError, OverflowError) as e: # <<<<<<<<<<<<<< + * raise TDecodeException(obj.__class__.__name__, fid, f_name, v, + * f_type, container_spec) +*/ + __pyx_t_7 = __Pyx_PyErr_ExceptionMatches(((PyObject *)(((PyTypeObject*)PyExc_TypeError)))) || __Pyx_PyErr_ExceptionMatches(((PyObject *)(((PyTypeObject*)PyExc_AttributeError)))) || __Pyx_PyErr_ExceptionMatches(((PyObject *)(((PyTypeObject*)PyExc_AssertionError)))) || __Pyx_PyErr_ExceptionMatches(((PyObject *)(((PyTypeObject*)PyExc_OverflowError)))); + if (__pyx_t_7) { + __Pyx_AddTraceback("thriftpy2.protocol.cybin.cybin.write_struct", __pyx_clineno, __pyx_lineno, __pyx_filename); + if (__Pyx_GetException(&__pyx_t_6, &__pyx_t_5, &__pyx_t_15) < 0) __PYX_ERR(0, 238, __pyx_L10_except_error) + __Pyx_XGOTREF(__pyx_t_6); + __Pyx_XGOTREF(__pyx_t_5); + __Pyx_XGOTREF(__pyx_t_15); + __Pyx_INCREF(__pyx_t_5); + __pyx_v_e = __pyx_t_5; + /*try:*/ { + + /* "thriftpy2/protocol/cybin/cybin.pyx":239 + * c_write_val(buf, f_type, v, container_spec) + * except (TypeError, AttributeError, AssertionError, OverflowError) as e: + * raise TDecodeException(obj.__class__.__name__, fid, f_name, v, # <<<<<<<<<<<<<< + * f_type, container_spec) + * +*/ + __pyx_t_17 = NULL; + __Pyx_GetModuleGlobalName(__pyx_t_18, __pyx_mstate_global->__pyx_n_u_TDecodeException); if (unlikely(!__pyx_t_18)) __PYX_ERR(0, 239, __pyx_L21_error) + __Pyx_GOTREF(__pyx_t_18); + __pyx_t_19 = __Pyx_PyObject_GetAttrStr(__pyx_v_obj, __pyx_mstate_global->__pyx_n_u_class); if (unlikely(!__pyx_t_19)) __PYX_ERR(0, 239, __pyx_L21_error) + __Pyx_GOTREF(__pyx_t_19); + __pyx_t_20 = __Pyx_PyObject_GetAttrStr(__pyx_t_19, __pyx_mstate_global->__pyx_n_u_name); if (unlikely(!__pyx_t_20)) __PYX_ERR(0, 239, __pyx_L21_error) + __Pyx_GOTREF(__pyx_t_20); + __Pyx_DECREF(__pyx_t_19); __pyx_t_19 = 0; + __pyx_t_19 = __Pyx_PyLong_From_int(__pyx_v_fid); if (unlikely(!__pyx_t_19)) __PYX_ERR(0, 239, __pyx_L21_error) + __Pyx_GOTREF(__pyx_t_19); + + /* "thriftpy2/protocol/cybin/cybin.pyx":240 + * except (TypeError, AttributeError, AssertionError, OverflowError) as e: + * raise TDecodeException(obj.__class__.__name__, fid, f_name, v, + * f_type, container_spec) # <<<<<<<<<<<<<< + * + * write_i08(buf, T_STOP) +*/ + __pyx_t_21 = __Pyx_PyLong_From___pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType(__pyx_v_f_type); if (unlikely(!__pyx_t_21)) __PYX_ERR(0, 240, __pyx_L21_error) + __Pyx_GOTREF(__pyx_t_21); + __pyx_t_22 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_18))) { + __pyx_t_17 = PyMethod_GET_SELF(__pyx_t_18); + assert(__pyx_t_17); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_18); + __Pyx_INCREF(__pyx_t_17); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_18, __pyx__function); + __pyx_t_22 = 0; + } + #endif + { + PyObject *__pyx_callargs[7] = {__pyx_t_17, __pyx_t_20, __pyx_t_19, __pyx_v_f_name, __pyx_v_v, __pyx_t_21, __pyx_v_container_spec}; + __pyx_t_16 = __Pyx_PyObject_FastCall((PyObject*)__pyx_t_18, __pyx_callargs+__pyx_t_22, (7-__pyx_t_22) | (__pyx_t_22*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_17); __pyx_t_17 = 0; + __Pyx_DECREF(__pyx_t_20); __pyx_t_20 = 0; + __Pyx_DECREF(__pyx_t_19); __pyx_t_19 = 0; + __Pyx_DECREF(__pyx_t_21); __pyx_t_21 = 0; + __Pyx_DECREF(__pyx_t_18); __pyx_t_18 = 0; + if (unlikely(!__pyx_t_16)) __PYX_ERR(0, 239, __pyx_L21_error) + __Pyx_GOTREF(__pyx_t_16); + } + __Pyx_Raise(__pyx_t_16, 0, 0, 0); + __Pyx_DECREF(__pyx_t_16); __pyx_t_16 = 0; + __PYX_ERR(0, 239, __pyx_L21_error) + } + + /* "thriftpy2/protocol/cybin/cybin.pyx":238 + * try: + * c_write_val(buf, f_type, v, container_spec) + * except (TypeError, AttributeError, AssertionError, OverflowError) as e: # <<<<<<<<<<<<<< + * raise TDecodeException(obj.__class__.__name__, fid, f_name, v, + * f_type, container_spec) +*/ + /*finally:*/ { + __pyx_L21_error:; + /*exception exit:*/{ + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + __pyx_t_25 = 0; __pyx_t_26 = 0; __pyx_t_27 = 0; __pyx_t_28 = 0; __pyx_t_29 = 0; __pyx_t_30 = 0; + __Pyx_XDECREF(__pyx_t_16); __pyx_t_16 = 0; + __Pyx_XDECREF(__pyx_t_17); __pyx_t_17 = 0; + __Pyx_XDECREF(__pyx_t_18); __pyx_t_18 = 0; + __Pyx_XDECREF(__pyx_t_19); __pyx_t_19 = 0; + __Pyx_XDECREF(__pyx_t_20); __pyx_t_20 = 0; + __Pyx_XDECREF(__pyx_t_21); __pyx_t_21 = 0; + __Pyx_ExceptionSwap(&__pyx_t_28, &__pyx_t_29, &__pyx_t_30); + if ( unlikely(__Pyx_GetException(&__pyx_t_25, &__pyx_t_26, &__pyx_t_27) < 0)) __Pyx_ErrFetch(&__pyx_t_25, &__pyx_t_26, &__pyx_t_27); + __Pyx_XGOTREF(__pyx_t_25); + __Pyx_XGOTREF(__pyx_t_26); + __Pyx_XGOTREF(__pyx_t_27); + __Pyx_XGOTREF(__pyx_t_28); + __Pyx_XGOTREF(__pyx_t_29); + __Pyx_XGOTREF(__pyx_t_30); + __pyx_t_7 = __pyx_lineno; __pyx_t_23 = __pyx_clineno; __pyx_t_24 = __pyx_filename; + { + __Pyx_DECREF(__pyx_v_e); __pyx_v_e = 0; + } + __Pyx_XGIVEREF(__pyx_t_28); + __Pyx_XGIVEREF(__pyx_t_29); + __Pyx_XGIVEREF(__pyx_t_30); + __Pyx_ExceptionReset(__pyx_t_28, __pyx_t_29, __pyx_t_30); + __Pyx_XGIVEREF(__pyx_t_25); + __Pyx_XGIVEREF(__pyx_t_26); + __Pyx_XGIVEREF(__pyx_t_27); + __Pyx_ErrRestore(__pyx_t_25, __pyx_t_26, __pyx_t_27); + __pyx_t_25 = 0; __pyx_t_26 = 0; __pyx_t_27 = 0; __pyx_t_28 = 0; __pyx_t_29 = 0; __pyx_t_30 = 0; + __pyx_lineno = __pyx_t_7; __pyx_clineno = __pyx_t_23; __pyx_filename = __pyx_t_24; + goto __pyx_L10_except_error; + } + } + } + goto __pyx_L10_except_error; + + /* "thriftpy2/protocol/cybin/cybin.pyx":236 + * write_i08(buf, f_type) + * write_i16(buf, fid) + * try: # <<<<<<<<<<<<<< + * c_write_val(buf, f_type, v, container_spec) + * except (TypeError, AttributeError, AssertionError, OverflowError) as e: +*/ + __pyx_L10_except_error:; + __Pyx_XGIVEREF(__pyx_t_11); + __Pyx_XGIVEREF(__pyx_t_12); + __Pyx_XGIVEREF(__pyx_t_13); + __Pyx_ExceptionReset(__pyx_t_11, __pyx_t_12, __pyx_t_13); + goto __pyx_L1_error; + __pyx_L15_try_end:; + } + __pyx_L3_continue:; + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":242 + * f_type, container_spec) + * + * write_i08(buf, T_STOP) # <<<<<<<<<<<<<< + * + * +*/ + __pyx_t_4 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_write_i08(__pyx_v_buf, __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_STOP); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(0, 242, __pyx_L1_error) + + /* "thriftpy2/protocol/cybin/cybin.pyx":213 + * + * + * cdef inline write_struct(CyTransportBase buf, obj): # <<<<<<<<<<<<<< + * cdef int fid + * cdef TType f_type +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_15); + __Pyx_XDECREF(__pyx_t_16); + __Pyx_XDECREF(__pyx_t_17); + __Pyx_XDECREF(__pyx_t_18); + __Pyx_XDECREF(__pyx_t_19); + __Pyx_XDECREF(__pyx_t_20); + __Pyx_XDECREF(__pyx_t_21); + __Pyx_AddTraceback("thriftpy2.protocol.cybin.cybin.write_struct", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_thrift_spec); + __Pyx_XDECREF(__pyx_v_field_spec); + __Pyx_XDECREF(__pyx_v_f_name); + __Pyx_XDECREF(__pyx_v_container_spec); + __Pyx_XDECREF(__pyx_v_v); + __Pyx_XDECREF(__pyx_v_e); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/protocol/cybin/cybin.pyx":245 + * + * + * cdef inline c_read_binary(CyTransportBase buf, int32_t size): # <<<<<<<<<<<<<< + * cdef char string_val[STACK_STRING_LEN] + * +*/ + +static CYTHON_INLINE PyObject *__pyx_f_9thriftpy2_8protocol_5cybin_5cybin_c_read_binary(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *__pyx_v_buf, int32_t __pyx_v_size) { + char __pyx_v_string_val[__pyx_e_9thriftpy2_9transport_6cybase_STACK_STRING_LEN]; + char *__pyx_v_data; + PyObject *__pyx_v_py_data = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_t_3; + int __pyx_t_4; + char const *__pyx_t_5; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + PyObject *__pyx_t_9 = NULL; + PyObject *__pyx_t_10 = NULL; + PyObject *__pyx_t_11 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("c_read_binary", 0); + + /* "thriftpy2/protocol/cybin/cybin.pyx":248 + * cdef char string_val[STACK_STRING_LEN] + * + * if size > STACK_STRING_LEN: # <<<<<<<<<<<<<< + * data = malloc(size) + * try: +*/ + __pyx_t_1 = (__pyx_v_size > __pyx_e_9thriftpy2_9transport_6cybase_STACK_STRING_LEN); + if (__pyx_t_1) { + + /* "thriftpy2/protocol/cybin/cybin.pyx":249 + * + * if size > STACK_STRING_LEN: + * data = malloc(size) # <<<<<<<<<<<<<< + * try: + * buf.c_read(size, data) +*/ + __pyx_v_data = ((char *)malloc(__pyx_v_size)); + + /* "thriftpy2/protocol/cybin/cybin.pyx":250 + * if size > STACK_STRING_LEN: + * data = malloc(size) + * try: # <<<<<<<<<<<<<< + * buf.c_read(size, data) + * py_data = data[:size] +*/ + /*try:*/ { + + /* "thriftpy2/protocol/cybin/cybin.pyx":251 + * data = malloc(size) + * try: + * buf.c_read(size, data) # <<<<<<<<<<<<<< + * py_data = data[:size] + * finally: +*/ + __pyx_t_2 = ((struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_CyTransportBase *)__pyx_v_buf->__pyx_vtab)->c_read(__pyx_v_buf, __pyx_v_size, __pyx_v_data); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 251, __pyx_L5_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":252 + * try: + * buf.c_read(size, data) + * py_data = data[:size] # <<<<<<<<<<<<<< + * finally: + * free(data) +*/ + __pyx_t_2 = __Pyx_PyBytes_FromStringAndSize(__pyx_v_data + 0, __pyx_v_size - 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 252, __pyx_L5_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_v_py_data = ((PyObject*)__pyx_t_2); + __pyx_t_2 = 0; + } + + /* "thriftpy2/protocol/cybin/cybin.pyx":254 + * py_data = data[:size] + * finally: + * free(data) # <<<<<<<<<<<<<< + * else: + * buf.c_read(size, string_val) +*/ + /*finally:*/ { + /*normal exit:*/{ + free(__pyx_v_data); + goto __pyx_L6; + } + __pyx_L5_error:; + /*exception exit:*/{ + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + __pyx_t_6 = 0; __pyx_t_7 = 0; __pyx_t_8 = 0; __pyx_t_9 = 0; __pyx_t_10 = 0; __pyx_t_11 = 0; + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_ExceptionSwap(&__pyx_t_9, &__pyx_t_10, &__pyx_t_11); + if ( unlikely(__Pyx_GetException(&__pyx_t_6, &__pyx_t_7, &__pyx_t_8) < 0)) __Pyx_ErrFetch(&__pyx_t_6, &__pyx_t_7, &__pyx_t_8); + __Pyx_XGOTREF(__pyx_t_6); + __Pyx_XGOTREF(__pyx_t_7); + __Pyx_XGOTREF(__pyx_t_8); + __Pyx_XGOTREF(__pyx_t_9); + __Pyx_XGOTREF(__pyx_t_10); + __Pyx_XGOTREF(__pyx_t_11); + __pyx_t_3 = __pyx_lineno; __pyx_t_4 = __pyx_clineno; __pyx_t_5 = __pyx_filename; + { + free(__pyx_v_data); + } + __Pyx_XGIVEREF(__pyx_t_9); + __Pyx_XGIVEREF(__pyx_t_10); + __Pyx_XGIVEREF(__pyx_t_11); + __Pyx_ExceptionReset(__pyx_t_9, __pyx_t_10, __pyx_t_11); + __Pyx_XGIVEREF(__pyx_t_6); + __Pyx_XGIVEREF(__pyx_t_7); + __Pyx_XGIVEREF(__pyx_t_8); + __Pyx_ErrRestore(__pyx_t_6, __pyx_t_7, __pyx_t_8); + __pyx_t_6 = 0; __pyx_t_7 = 0; __pyx_t_8 = 0; __pyx_t_9 = 0; __pyx_t_10 = 0; __pyx_t_11 = 0; + __pyx_lineno = __pyx_t_3; __pyx_clineno = __pyx_t_4; __pyx_filename = __pyx_t_5; + goto __pyx_L1_error; + } + __pyx_L6:; + } + + /* "thriftpy2/protocol/cybin/cybin.pyx":248 + * cdef char string_val[STACK_STRING_LEN] + * + * if size > STACK_STRING_LEN: # <<<<<<<<<<<<<< + * data = malloc(size) + * try: +*/ + goto __pyx_L3; + } + + /* "thriftpy2/protocol/cybin/cybin.pyx":256 + * free(data) + * else: + * buf.c_read(size, string_val) # <<<<<<<<<<<<<< + * py_data = string_val[:size] + * +*/ + /*else*/ { + __pyx_t_2 = ((struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_CyTransportBase *)__pyx_v_buf->__pyx_vtab)->c_read(__pyx_v_buf, __pyx_v_size, __pyx_v_string_val); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 256, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":257 + * else: + * buf.c_read(size, string_val) + * py_data = string_val[:size] # <<<<<<<<<<<<<< + * + * return py_data +*/ + __pyx_t_2 = __Pyx_PyBytes_FromStringAndSize(__pyx_v_string_val + 0, __pyx_v_size - 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 257, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_v_py_data = ((PyObject*)__pyx_t_2); + __pyx_t_2 = 0; + } + __pyx_L3:; + + /* "thriftpy2/protocol/cybin/cybin.pyx":259 + * py_data = string_val[:size] + * + * return py_data # <<<<<<<<<<<<<< + * + * +*/ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_py_data); + __pyx_r = __pyx_v_py_data; + goto __pyx_L0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":245 + * + * + * cdef inline c_read_binary(CyTransportBase buf, int32_t size): # <<<<<<<<<<<<<< + * cdef char string_val[STACK_STRING_LEN] + * +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("thriftpy2.protocol.cybin.cybin.c_read_binary", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_py_data); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/protocol/cybin/cybin.pyx":262 + * + * + * cdef inline c_read_string(CyTransportBase buf, int32_t size, # <<<<<<<<<<<<<< + * strict_decode=False): + * py_data = c_read_binary(buf, size) +*/ + +static CYTHON_INLINE PyObject *__pyx_f_9thriftpy2_8protocol_5cybin_5cybin_c_read_string(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *__pyx_v_buf, int32_t __pyx_v_size, struct __pyx_opt_args_9thriftpy2_8protocol_5cybin_5cybin_c_read_string *__pyx_optional_args) { + + /* "thriftpy2/protocol/cybin/cybin.pyx":263 + * + * cdef inline c_read_string(CyTransportBase buf, int32_t size, + * strict_decode=False): # <<<<<<<<<<<<<< + * py_data = c_read_binary(buf, size) + * try: +*/ + PyObject *__pyx_v_strict_decode = ((PyObject *)Py_False); + PyObject *__pyx_v_py_data = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + char *__pyx_t_5; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + int __pyx_t_8; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("c_read_string", 0); + if (__pyx_optional_args) { + if (__pyx_optional_args->__pyx_n > 0) { + __pyx_v_strict_decode = __pyx_optional_args->strict_decode; + } + } + + /* "thriftpy2/protocol/cybin/cybin.pyx":264 + * cdef inline c_read_string(CyTransportBase buf, int32_t size, + * strict_decode=False): + * py_data = c_read_binary(buf, size) # <<<<<<<<<<<<<< + * try: + * return (py_data)[:size].decode("utf-8") +*/ + __pyx_t_1 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_c_read_binary(__pyx_v_buf, __pyx_v_size); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 264, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_py_data = __pyx_t_1; + __pyx_t_1 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":265 + * strict_decode=False): + * py_data = c_read_binary(buf, size) + * try: # <<<<<<<<<<<<<< + * return (py_data)[:size].decode("utf-8") + * except: # noqa +*/ + { + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + __Pyx_ExceptionSave(&__pyx_t_2, &__pyx_t_3, &__pyx_t_4); + __Pyx_XGOTREF(__pyx_t_2); + __Pyx_XGOTREF(__pyx_t_3); + __Pyx_XGOTREF(__pyx_t_4); + /*try:*/ { + + /* "thriftpy2/protocol/cybin/cybin.pyx":266 + * py_data = c_read_binary(buf, size) + * try: + * return (py_data)[:size].decode("utf-8") # <<<<<<<<<<<<<< + * except: # noqa + * if strict_decode: +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_5 = __Pyx_PyObject_AsWritableString(__pyx_v_py_data); if (unlikely((!__pyx_t_5) && PyErr_Occurred())) __PYX_ERR(0, 266, __pyx_L3_error) + __pyx_t_1 = __Pyx_decode_c_string(((char *)__pyx_t_5), 0, __pyx_v_size, NULL, NULL, PyUnicode_DecodeUTF8); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 266, __pyx_L3_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L7_try_return; + + /* "thriftpy2/protocol/cybin/cybin.pyx":265 + * strict_decode=False): + * py_data = c_read_binary(buf, size) + * try: # <<<<<<<<<<<<<< + * return (py_data)[:size].decode("utf-8") + * except: # noqa +*/ + } + __pyx_L3_error:; + __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":267 + * try: + * return (py_data)[:size].decode("utf-8") + * except: # noqa # <<<<<<<<<<<<<< + * if strict_decode: + * raise +*/ + /*except:*/ { + __Pyx_AddTraceback("thriftpy2.protocol.cybin.cybin.c_read_string", __pyx_clineno, __pyx_lineno, __pyx_filename); + if (__Pyx_GetException(&__pyx_t_1, &__pyx_t_6, &__pyx_t_7) < 0) __PYX_ERR(0, 267, __pyx_L5_except_error) + __Pyx_XGOTREF(__pyx_t_1); + __Pyx_XGOTREF(__pyx_t_6); + __Pyx_XGOTREF(__pyx_t_7); + + /* "thriftpy2/protocol/cybin/cybin.pyx":268 + * return (py_data)[:size].decode("utf-8") + * except: # noqa + * if strict_decode: # <<<<<<<<<<<<<< + * raise + * return py_data +*/ + __pyx_t_8 = __Pyx_PyObject_IsTrue(__pyx_v_strict_decode); if (unlikely((__pyx_t_8 < 0))) __PYX_ERR(0, 268, __pyx_L5_except_error) + if (unlikely(__pyx_t_8)) { + + /* "thriftpy2/protocol/cybin/cybin.pyx":269 + * except: # noqa + * if strict_decode: + * raise # <<<<<<<<<<<<<< + * return py_data + * +*/ + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GIVEREF(__pyx_t_6); + __Pyx_XGIVEREF(__pyx_t_7); + __Pyx_ErrRestoreWithState(__pyx_t_1, __pyx_t_6, __pyx_t_7); + __pyx_t_1 = 0; __pyx_t_6 = 0; __pyx_t_7 = 0; + __PYX_ERR(0, 269, __pyx_L5_except_error) + + /* "thriftpy2/protocol/cybin/cybin.pyx":268 + * return (py_data)[:size].decode("utf-8") + * except: # noqa + * if strict_decode: # <<<<<<<<<<<<<< + * raise + * return py_data +*/ + } + + /* "thriftpy2/protocol/cybin/cybin.pyx":270 + * if strict_decode: + * raise + * return py_data # <<<<<<<<<<<<<< + * + * +*/ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_py_data); + __pyx_r = __pyx_v_py_data; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + goto __pyx_L6_except_return; + } + + /* "thriftpy2/protocol/cybin/cybin.pyx":265 + * strict_decode=False): + * py_data = c_read_binary(buf, size) + * try: # <<<<<<<<<<<<<< + * return (py_data)[:size].decode("utf-8") + * except: # noqa +*/ + __pyx_L5_except_error:; + __Pyx_XGIVEREF(__pyx_t_2); + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); + goto __pyx_L1_error; + __pyx_L7_try_return:; + __Pyx_XGIVEREF(__pyx_t_2); + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); + goto __pyx_L0; + __pyx_L6_except_return:; + __Pyx_XGIVEREF(__pyx_t_2); + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); + goto __pyx_L0; + } + + /* "thriftpy2/protocol/cybin/cybin.pyx":262 + * + * + * cdef inline c_read_string(CyTransportBase buf, int32_t size, # <<<<<<<<<<<<<< + * strict_decode=False): + * py_data = c_read_binary(buf, size) +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_AddTraceback("thriftpy2.protocol.cybin.cybin.c_read_string", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_py_data); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/protocol/cybin/cybin.pyx":273 + * + * + * cdef c_read_val(CyTransportBase buf, TType ttype, spec=None, # <<<<<<<<<<<<<< + * decode_response=True, strict_decode=False): + * cdef int size +*/ + +static PyObject *__pyx_f_9thriftpy2_8protocol_5cybin_5cybin_c_read_val(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *__pyx_v_buf, __pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType __pyx_v_ttype, struct __pyx_opt_args_9thriftpy2_8protocol_5cybin_5cybin_c_read_val *__pyx_optional_args) { + PyObject *__pyx_v_spec = ((PyObject *)Py_None); + + /* "thriftpy2/protocol/cybin/cybin.pyx":274 + * + * cdef c_read_val(CyTransportBase buf, TType ttype, spec=None, + * decode_response=True, strict_decode=False): # <<<<<<<<<<<<<< + * cdef int size + * cdef int64_t n +*/ + PyObject *__pyx_v_decode_response = ((PyObject *)Py_True); + PyObject *__pyx_v_strict_decode = ((PyObject *)Py_False); + int __pyx_v_size; + int64_t __pyx_v_n; + __pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType __pyx_v_v_type; + __pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType __pyx_v_k_type; + __pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType __pyx_v_orig_type; + __pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType __pyx_v_orig_key_type; + double __pyx_v_double_value; + PyObject *__pyx_v_v_spec = NULL; + CYTHON_UNUSED int __pyx_v__; + PyObject *__pyx_v_key = NULL; + PyObject *__pyx_v_k_spec = NULL; + PyObject *__pyx_v_value = NULL; + CYTHON_UNUSED int __pyx_7genexpr__pyx_v__; + CYTHON_UNUSED int __pyx_8genexpr1__pyx_v__; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + char __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int16_t __pyx_t_3; + int32_t __pyx_t_4; + int64_t __pyx_t_5; + int __pyx_t_6; + struct __pyx_opt_args_9thriftpy2_8protocol_5cybin_5cybin_c_read_string __pyx_t_7; + __pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType __pyx_t_8; + int __pyx_t_9; + PyObject *__pyx_t_10 = NULL; + int __pyx_t_11; + int __pyx_t_12; + int __pyx_t_13; + int __pyx_t_14; + struct __pyx_opt_args_9thriftpy2_8protocol_5cybin_5cybin_c_read_val __pyx_t_15; + PyObject *__pyx_t_16 = NULL; + size_t __pyx_t_17; + struct __pyx_opt_args_9thriftpy2_8protocol_5cybin_5cybin_read_struct __pyx_t_18; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("c_read_val", 0); + if (__pyx_optional_args) { + if (__pyx_optional_args->__pyx_n > 0) { + __pyx_v_spec = __pyx_optional_args->spec; + if (__pyx_optional_args->__pyx_n > 1) { + __pyx_v_decode_response = __pyx_optional_args->decode_response; + if (__pyx_optional_args->__pyx_n > 2) { + __pyx_v_strict_decode = __pyx_optional_args->strict_decode; + } + } + } + } + + /* "thriftpy2/protocol/cybin/cybin.pyx":280 + * cdef double double_value + * + * if ttype == T_BOOL: # <<<<<<<<<<<<<< + * return read_i08(buf) + * +*/ + switch (__pyx_v_ttype) { + case __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_BOOL: + + /* "thriftpy2/protocol/cybin/cybin.pyx":281 + * + * if ttype == T_BOOL: + * return read_i08(buf) # <<<<<<<<<<<<<< + * + * elif ttype == T_I08: +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_read_i08(__pyx_v_buf); if (unlikely(__pyx_t_1 == ((char)-1) && PyErr_Occurred())) __PYX_ERR(0, 281, __pyx_L1_error) + __pyx_t_2 = __Pyx_PyBool_FromLong((__pyx_t_1 != 0)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 281, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":280 + * cdef double double_value + * + * if ttype == T_BOOL: # <<<<<<<<<<<<<< + * return read_i08(buf) + * +*/ + break; + case __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_I08: + + /* "thriftpy2/protocol/cybin/cybin.pyx":284 + * + * elif ttype == T_I08: + * return read_i08(buf) # <<<<<<<<<<<<<< + * + * elif ttype == T_I16: +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_read_i08(__pyx_v_buf); if (unlikely(__pyx_t_1 == ((char)-1) && PyErr_Occurred())) __PYX_ERR(0, 284, __pyx_L1_error) + __pyx_t_2 = __Pyx_PyLong_From_char(__pyx_t_1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 284, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":283 + * return read_i08(buf) + * + * elif ttype == T_I08: # <<<<<<<<<<<<<< + * return read_i08(buf) + * +*/ + break; + case __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_I16: + + /* "thriftpy2/protocol/cybin/cybin.pyx":287 + * + * elif ttype == T_I16: + * return read_i16(buf) # <<<<<<<<<<<<<< + * + * elif ttype == T_I32: +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_3 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_read_i16(__pyx_v_buf); if (unlikely(__pyx_t_3 == ((int16_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 287, __pyx_L1_error) + __pyx_t_2 = __Pyx_PyLong_From_int16_t(__pyx_t_3); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 287, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":286 + * return read_i08(buf) + * + * elif ttype == T_I16: # <<<<<<<<<<<<<< + * return read_i16(buf) + * +*/ + break; + case __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_I32: + + /* "thriftpy2/protocol/cybin/cybin.pyx":290 + * + * elif ttype == T_I32: + * return read_i32(buf) # <<<<<<<<<<<<<< + * + * elif ttype == T_I64: +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_4 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_read_i32(__pyx_v_buf); if (unlikely(__pyx_t_4 == ((int32_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 290, __pyx_L1_error) + __pyx_t_2 = __Pyx_PyLong_From_int32_t(__pyx_t_4); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 290, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":289 + * return read_i16(buf) + * + * elif ttype == T_I32: # <<<<<<<<<<<<<< + * return read_i32(buf) + * +*/ + break; + case __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_I64: + + /* "thriftpy2/protocol/cybin/cybin.pyx":293 + * + * elif ttype == T_I64: + * return read_i64(buf) # <<<<<<<<<<<<<< + * + * elif ttype == T_DOUBLE: +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_5 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_read_i64(__pyx_v_buf); if (unlikely(__pyx_t_5 == ((int64_t)-1L) && PyErr_Occurred())) __PYX_ERR(0, 293, __pyx_L1_error) + __pyx_t_2 = __Pyx_PyLong_From_int64_t(__pyx_t_5); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 293, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":292 + * return read_i32(buf) + * + * elif ttype == T_I64: # <<<<<<<<<<<<<< + * return read_i64(buf) + * +*/ + break; + case __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_DOUBLE: + + /* "thriftpy2/protocol/cybin/cybin.pyx":296 + * + * elif ttype == T_DOUBLE: + * n = read_i64(buf) # <<<<<<<<<<<<<< + * memcpy(&double_value, &n, 8) + * return double_value +*/ + __pyx_t_5 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_read_i64(__pyx_v_buf); if (unlikely(__pyx_t_5 == ((int64_t)-1L) && PyErr_Occurred())) __PYX_ERR(0, 296, __pyx_L1_error) + __pyx_v_n = __pyx_t_5; + + /* "thriftpy2/protocol/cybin/cybin.pyx":297 + * elif ttype == T_DOUBLE: + * n = read_i64(buf) + * memcpy(&double_value, &n, 8) # <<<<<<<<<<<<<< + * return double_value + * +*/ + (void)(memcpy((&__pyx_v_double_value), (&__pyx_v_n), 8)); + + /* "thriftpy2/protocol/cybin/cybin.pyx":298 + * n = read_i64(buf) + * memcpy(&double_value, &n, 8) + * return double_value # <<<<<<<<<<<<<< + * + * elif ttype == T_BINARY: +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = PyFloat_FromDouble(__pyx_v_double_value); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 298, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":295 + * return read_i64(buf) + * + * elif ttype == T_DOUBLE: # <<<<<<<<<<<<<< + * n = read_i64(buf) + * memcpy(&double_value, &n, 8) +*/ + break; + case __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_BINARY: + + /* "thriftpy2/protocol/cybin/cybin.pyx":301 + * + * elif ttype == T_BINARY: + * size = read_i32(buf) # <<<<<<<<<<<<<< + * return c_read_binary(buf, size) + * +*/ + __pyx_t_4 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_read_i32(__pyx_v_buf); if (unlikely(__pyx_t_4 == ((int32_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 301, __pyx_L1_error) + __pyx_v_size = __pyx_t_4; + + /* "thriftpy2/protocol/cybin/cybin.pyx":302 + * elif ttype == T_BINARY: + * size = read_i32(buf) + * return c_read_binary(buf, size) # <<<<<<<<<<<<<< + * + * elif ttype == T_STRING: +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_c_read_binary(__pyx_v_buf, __pyx_v_size); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 302, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":300 + * return double_value + * + * elif ttype == T_BINARY: # <<<<<<<<<<<<<< + * size = read_i32(buf) + * return c_read_binary(buf, size) +*/ + break; + case __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_STRING: + + /* "thriftpy2/protocol/cybin/cybin.pyx":305 + * + * elif ttype == T_STRING: + * size = read_i32(buf) # <<<<<<<<<<<<<< + * if decode_response: + * return c_read_string(buf, size, strict_decode) +*/ + __pyx_t_4 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_read_i32(__pyx_v_buf); if (unlikely(__pyx_t_4 == ((int32_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 305, __pyx_L1_error) + __pyx_v_size = __pyx_t_4; + + /* "thriftpy2/protocol/cybin/cybin.pyx":306 + * elif ttype == T_STRING: + * size = read_i32(buf) + * if decode_response: # <<<<<<<<<<<<<< + * return c_read_string(buf, size, strict_decode) + * else: +*/ + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_v_decode_response); if (unlikely((__pyx_t_6 < 0))) __PYX_ERR(0, 306, __pyx_L1_error) + if (__pyx_t_6) { + + /* "thriftpy2/protocol/cybin/cybin.pyx":307 + * size = read_i32(buf) + * if decode_response: + * return c_read_string(buf, size, strict_decode) # <<<<<<<<<<<<<< + * else: + * return c_read_binary(buf, size) +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_7.__pyx_n = 1; + __pyx_t_7.strict_decode = __pyx_v_strict_decode; + __pyx_t_2 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_c_read_string(__pyx_v_buf, __pyx_v_size, &__pyx_t_7); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 307, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":306 + * elif ttype == T_STRING: + * size = read_i32(buf) + * if decode_response: # <<<<<<<<<<<<<< + * return c_read_string(buf, size, strict_decode) + * else: +*/ + } + + /* "thriftpy2/protocol/cybin/cybin.pyx":309 + * return c_read_string(buf, size, strict_decode) + * else: + * return c_read_binary(buf, size) # <<<<<<<<<<<<<< + * + * elif ttype == T_SET or ttype == T_LIST: +*/ + /*else*/ { + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_c_read_binary(__pyx_v_buf, __pyx_v_size); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 309, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + } + + /* "thriftpy2/protocol/cybin/cybin.pyx":304 + * return c_read_binary(buf, size) + * + * elif ttype == T_STRING: # <<<<<<<<<<<<<< + * size = read_i32(buf) + * if decode_response: +*/ + break; + case __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_SET: + + /* "thriftpy2/protocol/cybin/cybin.pyx":311 + * return c_read_binary(buf, size) + * + * elif ttype == T_SET or ttype == T_LIST: # <<<<<<<<<<<<<< + * if isinstance(spec, int): + * v_type = spec +*/ + case __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_LIST: + + /* "thriftpy2/protocol/cybin/cybin.pyx":312 + * + * elif ttype == T_SET or ttype == T_LIST: + * if isinstance(spec, int): # <<<<<<<<<<<<<< + * v_type = spec + * v_spec = None +*/ + __pyx_t_6 = PyLong_Check(__pyx_v_spec); + if (__pyx_t_6) { + + /* "thriftpy2/protocol/cybin/cybin.pyx":313 + * elif ttype == T_SET or ttype == T_LIST: + * if isinstance(spec, int): + * v_type = spec # <<<<<<<<<<<<<< + * v_spec = None + * else: +*/ + __pyx_t_8 = ((__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)__Pyx_PyLong_As___pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType(__pyx_v_spec)); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 313, __pyx_L1_error) + __pyx_v_v_type = __pyx_t_8; + + /* "thriftpy2/protocol/cybin/cybin.pyx":314 + * if isinstance(spec, int): + * v_type = spec + * v_spec = None # <<<<<<<<<<<<<< + * else: + * v_type = spec[0] +*/ + __Pyx_INCREF(Py_None); + __pyx_v_v_spec = Py_None; + + /* "thriftpy2/protocol/cybin/cybin.pyx":312 + * + * elif ttype == T_SET or ttype == T_LIST: + * if isinstance(spec, int): # <<<<<<<<<<<<<< + * v_type = spec + * v_spec = None +*/ + goto __pyx_L4; + } + + /* "thriftpy2/protocol/cybin/cybin.pyx":316 + * v_spec = None + * else: + * v_type = spec[0] # <<<<<<<<<<<<<< + * v_spec = spec[1] + * +*/ + /*else*/ { + __pyx_t_2 = __Pyx_GetItemInt(__pyx_v_spec, 0, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1, __Pyx_ReferenceSharing_FunctionArgument); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 316, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_8 = ((__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)__Pyx_PyLong_As___pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType(__pyx_t_2)); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 316, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_v_v_type = __pyx_t_8; + + /* "thriftpy2/protocol/cybin/cybin.pyx":317 + * else: + * v_type = spec[0] + * v_spec = spec[1] # <<<<<<<<<<<<<< + * + * orig_type = read_i08(buf) +*/ + __pyx_t_2 = __Pyx_GetItemInt(__pyx_v_spec, 1, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1, __Pyx_ReferenceSharing_FunctionArgument); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 317, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_v_v_spec = __pyx_t_2; + __pyx_t_2 = 0; + } + __pyx_L4:; + + /* "thriftpy2/protocol/cybin/cybin.pyx":319 + * v_spec = spec[1] + * + * orig_type = read_i08(buf) # <<<<<<<<<<<<<< + * size = read_i32(buf) + * +*/ + __pyx_t_1 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_read_i08(__pyx_v_buf); if (unlikely(__pyx_t_1 == ((char)-1) && PyErr_Occurred())) __PYX_ERR(0, 319, __pyx_L1_error) + __pyx_v_orig_type = ((__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)__pyx_t_1); + + /* "thriftpy2/protocol/cybin/cybin.pyx":320 + * + * orig_type = read_i08(buf) + * size = read_i32(buf) # <<<<<<<<<<<<<< + * + * if orig_type != v_type and not (orig_type in BIN_TYPES and v_type in BIN_TYPES): +*/ + __pyx_t_4 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_read_i32(__pyx_v_buf); if (unlikely(__pyx_t_4 == ((int32_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 320, __pyx_L1_error) + __pyx_v_size = __pyx_t_4; + + /* "thriftpy2/protocol/cybin/cybin.pyx":322 + * size = read_i32(buf) + * + * if orig_type != v_type and not (orig_type in BIN_TYPES and v_type in BIN_TYPES): # <<<<<<<<<<<<<< + * for _ in range(size): + * skip(buf, orig_type) +*/ + __pyx_t_9 = (__pyx_v_orig_type != __pyx_v_v_type); + if (__pyx_t_9) { + } else { + __pyx_t_6 = __pyx_t_9; + goto __pyx_L6_bool_binop_done; + } + __pyx_t_2 = __Pyx_PyLong_From___pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType(__pyx_v_orig_type); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 322, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_GetModuleGlobalName(__pyx_t_10, __pyx_mstate_global->__pyx_n_u_BIN_TYPES); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 322, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + __pyx_t_11 = (__Pyx_PySequence_ContainsTF(__pyx_t_2, __pyx_t_10, Py_EQ)); if (unlikely((__pyx_t_11 < 0))) __PYX_ERR(0, 322, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + if (__pyx_t_11) { + } else { + __pyx_t_9 = __pyx_t_11; + goto __pyx_L8_bool_binop_done; + } + __pyx_t_10 = __Pyx_PyLong_From___pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType(__pyx_v_v_type); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 322, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_mstate_global->__pyx_n_u_BIN_TYPES); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 322, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_11 = (__Pyx_PySequence_ContainsTF(__pyx_t_10, __pyx_t_2, Py_EQ)); if (unlikely((__pyx_t_11 < 0))) __PYX_ERR(0, 322, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_9 = __pyx_t_11; + __pyx_L8_bool_binop_done:; + __pyx_t_11 = (!__pyx_t_9); + __pyx_t_6 = __pyx_t_11; + __pyx_L6_bool_binop_done:; + if (__pyx_t_6) { + + /* "thriftpy2/protocol/cybin/cybin.pyx":323 + * + * if orig_type != v_type and not (orig_type in BIN_TYPES and v_type in BIN_TYPES): + * for _ in range(size): # <<<<<<<<<<<<<< + * skip(buf, orig_type) + * return [] +*/ + __pyx_t_12 = __pyx_v_size; + __pyx_t_13 = __pyx_t_12; + for (__pyx_t_14 = 0; __pyx_t_14 < __pyx_t_13; __pyx_t_14+=1) { + __pyx_v__ = __pyx_t_14; + + /* "thriftpy2/protocol/cybin/cybin.pyx":324 + * if orig_type != v_type and not (orig_type in BIN_TYPES and v_type in BIN_TYPES): + * for _ in range(size): + * skip(buf, orig_type) # <<<<<<<<<<<<<< + * return [] + * +*/ + __pyx_t_2 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_skip(__pyx_v_buf, __pyx_v_orig_type, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 324, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } + + /* "thriftpy2/protocol/cybin/cybin.pyx":325 + * for _ in range(size): + * skip(buf, orig_type) + * return [] # <<<<<<<<<<<<<< + * + * return [c_read_val(buf, v_type, v_spec, decode_response, strict_decode) +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = PyList_New(0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 325, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":322 + * size = read_i32(buf) + * + * if orig_type != v_type and not (orig_type in BIN_TYPES and v_type in BIN_TYPES): # <<<<<<<<<<<<<< + * for _ in range(size): + * skip(buf, orig_type) +*/ + } + + /* "thriftpy2/protocol/cybin/cybin.pyx":327 + * return [] + * + * return [c_read_val(buf, v_type, v_spec, decode_response, strict_decode) # <<<<<<<<<<<<<< + * for _ in range(size)] + * +*/ + __Pyx_XDECREF(__pyx_r); + { /* enter inner scope */ + __pyx_t_2 = PyList_New(0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 327, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + + /* "thriftpy2/protocol/cybin/cybin.pyx":328 + * + * return [c_read_val(buf, v_type, v_spec, decode_response, strict_decode) + * for _ in range(size)] # <<<<<<<<<<<<<< + * + * elif ttype == T_MAP: +*/ + __pyx_t_12 = __pyx_v_size; + __pyx_t_13 = __pyx_t_12; + for (__pyx_t_14 = 0; __pyx_t_14 < __pyx_t_13; __pyx_t_14+=1) { + __pyx_7genexpr__pyx_v__ = __pyx_t_14; + + /* "thriftpy2/protocol/cybin/cybin.pyx":327 + * return [] + * + * return [c_read_val(buf, v_type, v_spec, decode_response, strict_decode) # <<<<<<<<<<<<<< + * for _ in range(size)] + * +*/ + __pyx_t_15.__pyx_n = 3; + __pyx_t_15.spec = __pyx_v_v_spec; + __pyx_t_15.decode_response = __pyx_v_decode_response; + __pyx_t_15.strict_decode = __pyx_v_strict_decode; + __pyx_t_10 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_c_read_val(__pyx_v_buf, __pyx_v_v_type, &__pyx_t_15); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 327, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + if (unlikely(__Pyx_ListComp_Append(__pyx_t_2, (PyObject*)__pyx_t_10))) __PYX_ERR(0, 327, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + } + } /* exit inner scope */ + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":311 + * return c_read_binary(buf, size) + * + * elif ttype == T_SET or ttype == T_LIST: # <<<<<<<<<<<<<< + * if isinstance(spec, int): + * v_type = spec +*/ + break; + case __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_MAP: + + /* "thriftpy2/protocol/cybin/cybin.pyx":331 + * + * elif ttype == T_MAP: + * key = spec[0] # <<<<<<<<<<<<<< + * if isinstance(key, int): + * k_type = key +*/ + __pyx_t_2 = __Pyx_GetItemInt(__pyx_v_spec, 0, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1, __Pyx_ReferenceSharing_FunctionArgument); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 331, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_v_key = __pyx_t_2; + __pyx_t_2 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":332 + * elif ttype == T_MAP: + * key = spec[0] + * if isinstance(key, int): # <<<<<<<<<<<<<< + * k_type = key + * k_spec = None +*/ + __pyx_t_6 = PyLong_Check(__pyx_v_key); + if (__pyx_t_6) { + + /* "thriftpy2/protocol/cybin/cybin.pyx":333 + * key = spec[0] + * if isinstance(key, int): + * k_type = key # <<<<<<<<<<<<<< + * k_spec = None + * else: +*/ + __pyx_t_8 = ((__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)__Pyx_PyLong_As___pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType(__pyx_v_key)); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 333, __pyx_L1_error) + __pyx_v_k_type = __pyx_t_8; + + /* "thriftpy2/protocol/cybin/cybin.pyx":334 + * if isinstance(key, int): + * k_type = key + * k_spec = None # <<<<<<<<<<<<<< + * else: + * k_type = key[0] +*/ + __Pyx_INCREF(Py_None); + __pyx_v_k_spec = Py_None; + + /* "thriftpy2/protocol/cybin/cybin.pyx":332 + * elif ttype == T_MAP: + * key = spec[0] + * if isinstance(key, int): # <<<<<<<<<<<<<< + * k_type = key + * k_spec = None +*/ + goto __pyx_L14; + } + + /* "thriftpy2/protocol/cybin/cybin.pyx":336 + * k_spec = None + * else: + * k_type = key[0] # <<<<<<<<<<<<<< + * k_spec = key[1] + * +*/ + /*else*/ { + __pyx_t_2 = __Pyx_GetItemInt(__pyx_v_key, 0, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1, __Pyx_ReferenceSharing_OwnStrongReference); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 336, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_8 = ((__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)__Pyx_PyLong_As___pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType(__pyx_t_2)); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 336, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_v_k_type = __pyx_t_8; + + /* "thriftpy2/protocol/cybin/cybin.pyx":337 + * else: + * k_type = key[0] + * k_spec = key[1] # <<<<<<<<<<<<<< + * + * value = spec[1] +*/ + __pyx_t_2 = __Pyx_GetItemInt(__pyx_v_key, 1, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1, __Pyx_ReferenceSharing_OwnStrongReference); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 337, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_v_k_spec = __pyx_t_2; + __pyx_t_2 = 0; + } + __pyx_L14:; + + /* "thriftpy2/protocol/cybin/cybin.pyx":339 + * k_spec = key[1] + * + * value = spec[1] # <<<<<<<<<<<<<< + * if isinstance(value, int): + * v_type = value +*/ + __pyx_t_2 = __Pyx_GetItemInt(__pyx_v_spec, 1, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1, __Pyx_ReferenceSharing_FunctionArgument); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 339, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_v_value = __pyx_t_2; + __pyx_t_2 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":340 + * + * value = spec[1] + * if isinstance(value, int): # <<<<<<<<<<<<<< + * v_type = value + * v_spec = None +*/ + __pyx_t_6 = PyLong_Check(__pyx_v_value); + if (__pyx_t_6) { + + /* "thriftpy2/protocol/cybin/cybin.pyx":341 + * value = spec[1] + * if isinstance(value, int): + * v_type = value # <<<<<<<<<<<<<< + * v_spec = None + * else: +*/ + __pyx_t_8 = ((__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)__Pyx_PyLong_As___pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType(__pyx_v_value)); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 341, __pyx_L1_error) + __pyx_v_v_type = __pyx_t_8; + + /* "thriftpy2/protocol/cybin/cybin.pyx":342 + * if isinstance(value, int): + * v_type = value + * v_spec = None # <<<<<<<<<<<<<< + * else: + * v_type = value[0] +*/ + __Pyx_INCREF(Py_None); + __pyx_v_v_spec = Py_None; + + /* "thriftpy2/protocol/cybin/cybin.pyx":340 + * + * value = spec[1] + * if isinstance(value, int): # <<<<<<<<<<<<<< + * v_type = value + * v_spec = None +*/ + goto __pyx_L15; + } + + /* "thriftpy2/protocol/cybin/cybin.pyx":344 + * v_spec = None + * else: + * v_type = value[0] # <<<<<<<<<<<<<< + * v_spec = value[1] + * +*/ + /*else*/ { + __pyx_t_2 = __Pyx_GetItemInt(__pyx_v_value, 0, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1, __Pyx_ReferenceSharing_OwnStrongReference); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 344, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_8 = ((__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)__Pyx_PyLong_As___pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType(__pyx_t_2)); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 344, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_v_v_type = __pyx_t_8; + + /* "thriftpy2/protocol/cybin/cybin.pyx":345 + * else: + * v_type = value[0] + * v_spec = value[1] # <<<<<<<<<<<<<< + * + * orig_key_type = read_i08(buf) +*/ + __pyx_t_2 = __Pyx_GetItemInt(__pyx_v_value, 1, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1, __Pyx_ReferenceSharing_OwnStrongReference); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 345, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_v_v_spec = __pyx_t_2; + __pyx_t_2 = 0; + } + __pyx_L15:; + + /* "thriftpy2/protocol/cybin/cybin.pyx":347 + * v_spec = value[1] + * + * orig_key_type = read_i08(buf) # <<<<<<<<<<<<<< + * orig_type = read_i08(buf) + * size = read_i32(buf) +*/ + __pyx_t_1 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_read_i08(__pyx_v_buf); if (unlikely(__pyx_t_1 == ((char)-1) && PyErr_Occurred())) __PYX_ERR(0, 347, __pyx_L1_error) + __pyx_v_orig_key_type = ((__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)__pyx_t_1); + + /* "thriftpy2/protocol/cybin/cybin.pyx":348 + * + * orig_key_type = read_i08(buf) + * orig_type = read_i08(buf) # <<<<<<<<<<<<<< + * size = read_i32(buf) + * if orig_key_type in BIN_TYPES: +*/ + __pyx_t_1 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_read_i08(__pyx_v_buf); if (unlikely(__pyx_t_1 == ((char)-1) && PyErr_Occurred())) __PYX_ERR(0, 348, __pyx_L1_error) + __pyx_v_orig_type = ((__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)__pyx_t_1); + + /* "thriftpy2/protocol/cybin/cybin.pyx":349 + * orig_key_type = read_i08(buf) + * orig_type = read_i08(buf) + * size = read_i32(buf) # <<<<<<<<<<<<<< + * if orig_key_type in BIN_TYPES: + * orig_key_type = k_type +*/ + __pyx_t_4 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_read_i32(__pyx_v_buf); if (unlikely(__pyx_t_4 == ((int32_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 349, __pyx_L1_error) + __pyx_v_size = __pyx_t_4; + + /* "thriftpy2/protocol/cybin/cybin.pyx":350 + * orig_type = read_i08(buf) + * size = read_i32(buf) + * if orig_key_type in BIN_TYPES: # <<<<<<<<<<<<<< + * orig_key_type = k_type + * if orig_type in BIN_TYPES: +*/ + __pyx_t_2 = __Pyx_PyLong_From___pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType(__pyx_v_orig_key_type); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 350, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_GetModuleGlobalName(__pyx_t_10, __pyx_mstate_global->__pyx_n_u_BIN_TYPES); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 350, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + __pyx_t_6 = (__Pyx_PySequence_ContainsTF(__pyx_t_2, __pyx_t_10, Py_EQ)); if (unlikely((__pyx_t_6 < 0))) __PYX_ERR(0, 350, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + if (__pyx_t_6) { + + /* "thriftpy2/protocol/cybin/cybin.pyx":351 + * size = read_i32(buf) + * if orig_key_type in BIN_TYPES: + * orig_key_type = k_type # <<<<<<<<<<<<<< + * if orig_type in BIN_TYPES: + * orig_type = v_type +*/ + __pyx_v_orig_key_type = __pyx_v_k_type; + + /* "thriftpy2/protocol/cybin/cybin.pyx":350 + * orig_type = read_i08(buf) + * size = read_i32(buf) + * if orig_key_type in BIN_TYPES: # <<<<<<<<<<<<<< + * orig_key_type = k_type + * if orig_type in BIN_TYPES: +*/ + } + + /* "thriftpy2/protocol/cybin/cybin.pyx":352 + * if orig_key_type in BIN_TYPES: + * orig_key_type = k_type + * if orig_type in BIN_TYPES: # <<<<<<<<<<<<<< + * orig_type = v_type + * if orig_key_type != k_type or orig_type != v_type: +*/ + __pyx_t_10 = __Pyx_PyLong_From___pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType(__pyx_v_orig_type); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 352, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_mstate_global->__pyx_n_u_BIN_TYPES); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 352, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_6 = (__Pyx_PySequence_ContainsTF(__pyx_t_10, __pyx_t_2, Py_EQ)); if (unlikely((__pyx_t_6 < 0))) __PYX_ERR(0, 352, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (__pyx_t_6) { + + /* "thriftpy2/protocol/cybin/cybin.pyx":353 + * orig_key_type = k_type + * if orig_type in BIN_TYPES: + * orig_type = v_type # <<<<<<<<<<<<<< + * if orig_key_type != k_type or orig_type != v_type: + * for _ in range(size): +*/ + __pyx_v_orig_type = __pyx_v_v_type; + + /* "thriftpy2/protocol/cybin/cybin.pyx":352 + * if orig_key_type in BIN_TYPES: + * orig_key_type = k_type + * if orig_type in BIN_TYPES: # <<<<<<<<<<<<<< + * orig_type = v_type + * if orig_key_type != k_type or orig_type != v_type: +*/ + } + + /* "thriftpy2/protocol/cybin/cybin.pyx":354 + * if orig_type in BIN_TYPES: + * orig_type = v_type + * if orig_key_type != k_type or orig_type != v_type: # <<<<<<<<<<<<<< + * for _ in range(size): + * skip(buf, orig_key_type) +*/ + __pyx_t_11 = (__pyx_v_orig_key_type != __pyx_v_k_type); + if (!__pyx_t_11) { + } else { + __pyx_t_6 = __pyx_t_11; + goto __pyx_L19_bool_binop_done; + } + __pyx_t_11 = (__pyx_v_orig_type != __pyx_v_v_type); + __pyx_t_6 = __pyx_t_11; + __pyx_L19_bool_binop_done:; + if (__pyx_t_6) { + + /* "thriftpy2/protocol/cybin/cybin.pyx":355 + * orig_type = v_type + * if orig_key_type != k_type or orig_type != v_type: + * for _ in range(size): # <<<<<<<<<<<<<< + * skip(buf, orig_key_type) + * skip(buf, orig_type) +*/ + __pyx_t_12 = __pyx_v_size; + __pyx_t_13 = __pyx_t_12; + for (__pyx_t_14 = 0; __pyx_t_14 < __pyx_t_13; __pyx_t_14+=1) { + __pyx_v__ = __pyx_t_14; + + /* "thriftpy2/protocol/cybin/cybin.pyx":356 + * if orig_key_type != k_type or orig_type != v_type: + * for _ in range(size): + * skip(buf, orig_key_type) # <<<<<<<<<<<<<< + * skip(buf, orig_type) + * return {} +*/ + __pyx_t_2 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_skip(__pyx_v_buf, __pyx_v_orig_key_type, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 356, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":357 + * for _ in range(size): + * skip(buf, orig_key_type) + * skip(buf, orig_type) # <<<<<<<<<<<<<< + * return {} + * +*/ + __pyx_t_2 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_skip(__pyx_v_buf, __pyx_v_orig_type, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 357, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } + + /* "thriftpy2/protocol/cybin/cybin.pyx":358 + * skip(buf, orig_key_type) + * skip(buf, orig_type) + * return {} # <<<<<<<<<<<<<< + * + * return { +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __Pyx_PyDict_NewPresized(0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 358, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":354 + * if orig_type in BIN_TYPES: + * orig_type = v_type + * if orig_key_type != k_type or orig_type != v_type: # <<<<<<<<<<<<<< + * for _ in range(size): + * skip(buf, orig_key_type) +*/ + } + + /* "thriftpy2/protocol/cybin/cybin.pyx":360 + * return {} + * + * return { # <<<<<<<<<<<<<< + * c_read_val(buf, k_type, k_spec, decode_response, strict_decode): + * c_read_val(buf, v_type, v_spec, decode_response, strict_decode) +*/ + __Pyx_XDECREF(__pyx_r); + { /* enter inner scope */ + __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 360, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + + /* "thriftpy2/protocol/cybin/cybin.pyx":363 + * c_read_val(buf, k_type, k_spec, decode_response, strict_decode): + * c_read_val(buf, v_type, v_spec, decode_response, strict_decode) + * for _ in range(size) # <<<<<<<<<<<<<< + * } + * +*/ + __pyx_t_12 = __pyx_v_size; + __pyx_t_13 = __pyx_t_12; + for (__pyx_t_14 = 0; __pyx_t_14 < __pyx_t_13; __pyx_t_14+=1) { + __pyx_8genexpr1__pyx_v__ = __pyx_t_14; + + /* "thriftpy2/protocol/cybin/cybin.pyx":361 + * + * return { + * c_read_val(buf, k_type, k_spec, decode_response, strict_decode): # <<<<<<<<<<<<<< + * c_read_val(buf, v_type, v_spec, decode_response, strict_decode) + * for _ in range(size) +*/ + __pyx_t_15.__pyx_n = 3; + __pyx_t_15.spec = __pyx_v_k_spec; + __pyx_t_15.decode_response = __pyx_v_decode_response; + __pyx_t_15.strict_decode = __pyx_v_strict_decode; + __pyx_t_10 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_c_read_val(__pyx_v_buf, __pyx_v_k_type, &__pyx_t_15); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 361, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + + /* "thriftpy2/protocol/cybin/cybin.pyx":362 + * return { + * c_read_val(buf, k_type, k_spec, decode_response, strict_decode): + * c_read_val(buf, v_type, v_spec, decode_response, strict_decode) # <<<<<<<<<<<<<< + * for _ in range(size) + * } +*/ + __pyx_t_15.__pyx_n = 3; + __pyx_t_15.spec = __pyx_v_v_spec; + __pyx_t_15.decode_response = __pyx_v_decode_response; + __pyx_t_15.strict_decode = __pyx_v_strict_decode; + __pyx_t_16 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_c_read_val(__pyx_v_buf, __pyx_v_v_type, &__pyx_t_15); if (unlikely(!__pyx_t_16)) __PYX_ERR(0, 362, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_16); + if (unlikely(PyDict_SetItem(__pyx_t_2, (PyObject*)__pyx_t_10, (PyObject*)__pyx_t_16))) __PYX_ERR(0, 361, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + __Pyx_DECREF(__pyx_t_16); __pyx_t_16 = 0; + } + } /* exit inner scope */ + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":330 + * for _ in range(size)] + * + * elif ttype == T_MAP: # <<<<<<<<<<<<<< + * key = spec[0] + * if isinstance(key, int): +*/ + break; + case __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_STRUCT: + + /* "thriftpy2/protocol/cybin/cybin.pyx":367 + * + * elif ttype == T_STRUCT: + * return read_struct(buf, spec(), decode_response, strict_decode) # <<<<<<<<<<<<<< + * + * +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_16 = NULL; + __Pyx_INCREF(__pyx_v_spec); + __pyx_t_10 = __pyx_v_spec; + __pyx_t_17 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_10))) { + __pyx_t_16 = PyMethod_GET_SELF(__pyx_t_10); + assert(__pyx_t_16); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_10); + __Pyx_INCREF(__pyx_t_16); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_10, __pyx__function); + __pyx_t_17 = 0; + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_16, NULL}; + __pyx_t_2 = __Pyx_PyObject_FastCall((PyObject*)__pyx_t_10, __pyx_callargs+__pyx_t_17, (1-__pyx_t_17) | (__pyx_t_17*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_16); __pyx_t_16 = 0; + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 367, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __pyx_t_18.__pyx_n = 2; + __pyx_t_18.decode_response = __pyx_v_decode_response; + __pyx_t_18.strict_decode = __pyx_v_strict_decode; + __pyx_t_10 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_read_struct(__pyx_v_buf, __pyx_t_2, &__pyx_t_18); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 367, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_10; + __pyx_t_10 = 0; + goto __pyx_L0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":366 + * } + * + * elif ttype == T_STRUCT: # <<<<<<<<<<<<<< + * return read_struct(buf, spec(), decode_response, strict_decode) + * +*/ + break; + default: break; + } + + /* "thriftpy2/protocol/cybin/cybin.pyx":273 + * + * + * cdef c_read_val(CyTransportBase buf, TType ttype, spec=None, # <<<<<<<<<<<<<< + * decode_response=True, strict_decode=False): + * cdef int size +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_10); + __Pyx_XDECREF(__pyx_t_16); + __Pyx_AddTraceback("thriftpy2.protocol.cybin.cybin.c_read_val", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_v_spec); + __Pyx_XDECREF(__pyx_v_key); + __Pyx_XDECREF(__pyx_v_k_spec); + __Pyx_XDECREF(__pyx_v_value); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/protocol/cybin/cybin.pyx":370 + * + * + * cdef c_write_val(CyTransportBase buf, TType ttype, val, spec=None): # <<<<<<<<<<<<<< + * if ttype == T_BOOL: + * write_i08(buf, 1 if val else 0) +*/ + +static PyObject *__pyx_f_9thriftpy2_8protocol_5cybin_5cybin_c_write_val(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *__pyx_v_buf, __pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType __pyx_v_ttype, PyObject *__pyx_v_val, struct __pyx_opt_args_9thriftpy2_8protocol_5cybin_5cybin_c_write_val *__pyx_optional_args) { + PyObject *__pyx_v_spec = ((PyObject *)Py_None); + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + char __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + int16_t __pyx_t_4; + int32_t __pyx_t_5; + int64_t __pyx_t_6; + double __pyx_t_7; + PyObject *__pyx_t_8 = NULL; + PyObject *__pyx_t_9 = NULL; + int __pyx_t_10; + size_t __pyx_t_11; + PyObject *__pyx_t_12 = NULL; + PyObject *__pyx_t_13 = NULL; + PyObject *__pyx_t_14 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("c_write_val", 0); + if (__pyx_optional_args) { + if (__pyx_optional_args->__pyx_n > 0) { + __pyx_v_spec = __pyx_optional_args->spec; + } + } + __Pyx_INCREF(__pyx_v_val); + + /* "thriftpy2/protocol/cybin/cybin.pyx":371 + * + * cdef c_write_val(CyTransportBase buf, TType ttype, val, spec=None): + * if ttype == T_BOOL: # <<<<<<<<<<<<<< + * write_i08(buf, 1 if val else 0) + * +*/ + switch (__pyx_v_ttype) { + case __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_BOOL: + + /* "thriftpy2/protocol/cybin/cybin.pyx":372 + * cdef c_write_val(CyTransportBase buf, TType ttype, val, spec=None): + * if ttype == T_BOOL: + * write_i08(buf, 1 if val else 0) # <<<<<<<<<<<<<< + * + * elif ttype == T_I08: +*/ + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_v_val); if (unlikely((__pyx_t_2 < 0))) __PYX_ERR(0, 372, __pyx_L1_error) + if (__pyx_t_2) { + __pyx_t_1 = 1; + } else { + __pyx_t_1 = 0; + } + __pyx_t_3 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_write_i08(__pyx_v_buf, __pyx_t_1); if (unlikely(__pyx_t_3 == ((int)-1))) __PYX_ERR(0, 372, __pyx_L1_error) + + /* "thriftpy2/protocol/cybin/cybin.pyx":371 + * + * cdef c_write_val(CyTransportBase buf, TType ttype, val, spec=None): + * if ttype == T_BOOL: # <<<<<<<<<<<<<< + * write_i08(buf, 1 if val else 0) + * +*/ + break; + case __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_I08: + + /* "thriftpy2/protocol/cybin/cybin.pyx":375 + * + * elif ttype == T_I08: + * write_i08(buf, val) # <<<<<<<<<<<<<< + * + * elif ttype == T_I16: +*/ + __pyx_t_1 = __Pyx_PyLong_As_char(__pyx_v_val); if (unlikely((__pyx_t_1 == (char)-1) && PyErr_Occurred())) __PYX_ERR(0, 375, __pyx_L1_error) + __pyx_t_3 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_write_i08(__pyx_v_buf, __pyx_t_1); if (unlikely(__pyx_t_3 == ((int)-1))) __PYX_ERR(0, 375, __pyx_L1_error) + + /* "thriftpy2/protocol/cybin/cybin.pyx":374 + * write_i08(buf, 1 if val else 0) + * + * elif ttype == T_I08: # <<<<<<<<<<<<<< + * write_i08(buf, val) + * +*/ + break; + case __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_I16: + + /* "thriftpy2/protocol/cybin/cybin.pyx":378 + * + * elif ttype == T_I16: + * write_i16(buf, val) # <<<<<<<<<<<<<< + * + * elif ttype == T_I32: +*/ + __pyx_t_4 = __Pyx_PyLong_As_int16_t(__pyx_v_val); if (unlikely((__pyx_t_4 == ((int16_t)-1)) && PyErr_Occurred())) __PYX_ERR(0, 378, __pyx_L1_error) + __pyx_t_3 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_write_i16(__pyx_v_buf, __pyx_t_4); if (unlikely(__pyx_t_3 == ((int)-1))) __PYX_ERR(0, 378, __pyx_L1_error) + + /* "thriftpy2/protocol/cybin/cybin.pyx":377 + * write_i08(buf, val) + * + * elif ttype == T_I16: # <<<<<<<<<<<<<< + * write_i16(buf, val) + * +*/ + break; + case __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_I32: + + /* "thriftpy2/protocol/cybin/cybin.pyx":381 + * + * elif ttype == T_I32: + * write_i32(buf, val) # <<<<<<<<<<<<<< + * + * elif ttype == T_I64: +*/ + __pyx_t_5 = __Pyx_PyLong_As_int32_t(__pyx_v_val); if (unlikely((__pyx_t_5 == ((int32_t)-1)) && PyErr_Occurred())) __PYX_ERR(0, 381, __pyx_L1_error) + __pyx_t_3 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_write_i32(__pyx_v_buf, __pyx_t_5); if (unlikely(__pyx_t_3 == ((int)-1))) __PYX_ERR(0, 381, __pyx_L1_error) + + /* "thriftpy2/protocol/cybin/cybin.pyx":380 + * write_i16(buf, val) + * + * elif ttype == T_I32: # <<<<<<<<<<<<<< + * write_i32(buf, val) + * +*/ + break; + case __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_I64: + + /* "thriftpy2/protocol/cybin/cybin.pyx":384 + * + * elif ttype == T_I64: + * write_i64(buf, val) # <<<<<<<<<<<<<< + * + * elif ttype == T_DOUBLE: +*/ + __pyx_t_6 = __Pyx_PyLong_As_int64_t(__pyx_v_val); if (unlikely((__pyx_t_6 == ((int64_t)-1)) && PyErr_Occurred())) __PYX_ERR(0, 384, __pyx_L1_error) + __pyx_t_3 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_write_i64(__pyx_v_buf, __pyx_t_6); if (unlikely(__pyx_t_3 == ((int)-1))) __PYX_ERR(0, 384, __pyx_L1_error) + + /* "thriftpy2/protocol/cybin/cybin.pyx":383 + * write_i32(buf, val) + * + * elif ttype == T_I64: # <<<<<<<<<<<<<< + * write_i64(buf, val) + * +*/ + break; + case __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_DOUBLE: + + /* "thriftpy2/protocol/cybin/cybin.pyx":387 + * + * elif ttype == T_DOUBLE: + * write_double(buf, val) # <<<<<<<<<<<<<< + * + * elif ttype == T_BINARY: +*/ + __pyx_t_7 = __Pyx_PyFloat_AsDouble(__pyx_v_val); if (unlikely((__pyx_t_7 == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 387, __pyx_L1_error) + __pyx_t_3 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_write_double(__pyx_v_buf, __pyx_t_7); if (unlikely(__pyx_t_3 == ((int)-1))) __PYX_ERR(0, 387, __pyx_L1_error) + + /* "thriftpy2/protocol/cybin/cybin.pyx":386 + * write_i64(buf, val) + * + * elif ttype == T_DOUBLE: # <<<<<<<<<<<<<< + * write_double(buf, val) + * +*/ + break; + case __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_BINARY: + + /* "thriftpy2/protocol/cybin/cybin.pyx":390 + * + * elif ttype == T_BINARY: + * if isinstance(val, six.string_types) and sys.version_info[0] > 2: # <<<<<<<<<<<<<< + * val = val.encode() + * write_string(buf, val) +*/ + __Pyx_GetModuleGlobalName(__pyx_t_8, __pyx_mstate_global->__pyx_n_u_six); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 390, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_t_8, __pyx_mstate_global->__pyx_n_u_string_types); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 390, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_10 = PyObject_IsInstance(__pyx_v_val, __pyx_t_9); if (unlikely(__pyx_t_10 == ((int)-1))) __PYX_ERR(0, 390, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + if (__pyx_t_10) { + } else { + __pyx_t_2 = __pyx_t_10; + goto __pyx_L4_bool_binop_done; + } + __Pyx_GetModuleGlobalName(__pyx_t_9, __pyx_mstate_global->__pyx_n_u_sys); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 390, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_t_9, __pyx_mstate_global->__pyx_n_u_version_info); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 390, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_t_9 = __Pyx_GetItemInt(__pyx_t_8, 0, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1, __Pyx_ReferenceSharing_OwnStrongReference); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 390, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_8 = PyObject_RichCompare(__pyx_t_9, __pyx_mstate_global->__pyx_int_2, Py_GT); __Pyx_XGOTREF(__pyx_t_8); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 390, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_t_10 = __Pyx_PyObject_IsTrue(__pyx_t_8); if (unlikely((__pyx_t_10 < 0))) __PYX_ERR(0, 390, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_2 = __pyx_t_10; + __pyx_L4_bool_binop_done:; + if (__pyx_t_2) { + + /* "thriftpy2/protocol/cybin/cybin.pyx":391 + * elif ttype == T_BINARY: + * if isinstance(val, six.string_types) and sys.version_info[0] > 2: + * val = val.encode() # <<<<<<<<<<<<<< + * write_string(buf, val) + * +*/ + __pyx_t_9 = __pyx_v_val; + __Pyx_INCREF(__pyx_t_9); + __pyx_t_11 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_9, NULL}; + __pyx_t_8 = __Pyx_PyObject_FastCallMethod((PyObject*)__pyx_mstate_global->__pyx_n_u_encode, __pyx_callargs+__pyx_t_11, (1-__pyx_t_11) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; + if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 391, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + } + __Pyx_DECREF_SET(__pyx_v_val, __pyx_t_8); + __pyx_t_8 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":390 + * + * elif ttype == T_BINARY: + * if isinstance(val, six.string_types) and sys.version_info[0] > 2: # <<<<<<<<<<<<<< + * val = val.encode() + * write_string(buf, val) +*/ + } + + /* "thriftpy2/protocol/cybin/cybin.pyx":392 + * if isinstance(val, six.string_types) and sys.version_info[0] > 2: + * val = val.encode() + * write_string(buf, val) # <<<<<<<<<<<<<< + * + * elif ttype == T_STRING: +*/ + __pyx_t_8 = __pyx_v_val; + __Pyx_INCREF(__pyx_t_8); + if (!(likely(PyBytes_CheckExact(__pyx_t_8))||((__pyx_t_8) == Py_None) || __Pyx_RaiseUnexpectedTypeError("bytes", __pyx_t_8))) __PYX_ERR(0, 392, __pyx_L1_error) + __pyx_t_9 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_write_string(__pyx_v_buf, ((PyObject*)__pyx_t_8)); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 392, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":389 + * write_double(buf, val) + * + * elif ttype == T_BINARY: # <<<<<<<<<<<<<< + * if isinstance(val, six.string_types) and sys.version_info[0] > 2: + * val = val.encode() +*/ + break; + case __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_STRING: + + /* "thriftpy2/protocol/cybin/cybin.pyx":395 + * + * elif ttype == T_STRING: + * if not isinstance(val, six.binary_type): # <<<<<<<<<<<<<< + * try: + * val = val.encode("utf-8") +*/ + __Pyx_GetModuleGlobalName(__pyx_t_9, __pyx_mstate_global->__pyx_n_u_six); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 395, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_t_9, __pyx_mstate_global->__pyx_n_u_binary_type); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 395, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_t_2 = PyObject_IsInstance(__pyx_v_val, __pyx_t_8); if (unlikely(__pyx_t_2 == ((int)-1))) __PYX_ERR(0, 395, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_10 = (!__pyx_t_2); + if (__pyx_t_10) { + + /* "thriftpy2/protocol/cybin/cybin.pyx":396 + * elif ttype == T_STRING: + * if not isinstance(val, six.binary_type): + * try: # <<<<<<<<<<<<<< + * val = val.encode("utf-8") + * except Exception: +*/ + { + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + __Pyx_ExceptionSave(&__pyx_t_12, &__pyx_t_13, &__pyx_t_14); + __Pyx_XGOTREF(__pyx_t_12); + __Pyx_XGOTREF(__pyx_t_13); + __Pyx_XGOTREF(__pyx_t_14); + /*try:*/ { + + /* "thriftpy2/protocol/cybin/cybin.pyx":397 + * if not isinstance(val, six.binary_type): + * try: + * val = val.encode("utf-8") # <<<<<<<<<<<<<< + * except Exception: + * pass +*/ + __pyx_t_9 = __pyx_v_val; + __Pyx_INCREF(__pyx_t_9); + __pyx_t_11 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_9, __pyx_mstate_global->__pyx_kp_u_utf_8}; + __pyx_t_8 = __Pyx_PyObject_FastCallMethod((PyObject*)__pyx_mstate_global->__pyx_n_u_encode, __pyx_callargs+__pyx_t_11, (2-__pyx_t_11) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; + if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 397, __pyx_L7_error) + __Pyx_GOTREF(__pyx_t_8); + } + __Pyx_DECREF_SET(__pyx_v_val, __pyx_t_8); + __pyx_t_8 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":396 + * elif ttype == T_STRING: + * if not isinstance(val, six.binary_type): + * try: # <<<<<<<<<<<<<< + * val = val.encode("utf-8") + * except Exception: +*/ + } + __Pyx_XDECREF(__pyx_t_12); __pyx_t_12 = 0; + __Pyx_XDECREF(__pyx_t_13); __pyx_t_13 = 0; + __Pyx_XDECREF(__pyx_t_14); __pyx_t_14 = 0; + goto __pyx_L12_try_end; + __pyx_L7_error:; + __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":398 + * try: + * val = val.encode("utf-8") + * except Exception: # <<<<<<<<<<<<<< + * pass + * write_string(buf, val) +*/ + __pyx_t_3 = __Pyx_PyErr_ExceptionMatches(((PyObject *)(((PyTypeObject*)PyExc_Exception)))); + if (__pyx_t_3) { + __Pyx_ErrRestore(0,0,0); + goto __pyx_L8_exception_handled; + } + goto __pyx_L9_except_error; + + /* "thriftpy2/protocol/cybin/cybin.pyx":396 + * elif ttype == T_STRING: + * if not isinstance(val, six.binary_type): + * try: # <<<<<<<<<<<<<< + * val = val.encode("utf-8") + * except Exception: +*/ + __pyx_L9_except_error:; + __Pyx_XGIVEREF(__pyx_t_12); + __Pyx_XGIVEREF(__pyx_t_13); + __Pyx_XGIVEREF(__pyx_t_14); + __Pyx_ExceptionReset(__pyx_t_12, __pyx_t_13, __pyx_t_14); + goto __pyx_L1_error; + __pyx_L8_exception_handled:; + __Pyx_XGIVEREF(__pyx_t_12); + __Pyx_XGIVEREF(__pyx_t_13); + __Pyx_XGIVEREF(__pyx_t_14); + __Pyx_ExceptionReset(__pyx_t_12, __pyx_t_13, __pyx_t_14); + __pyx_L12_try_end:; + } + + /* "thriftpy2/protocol/cybin/cybin.pyx":395 + * + * elif ttype == T_STRING: + * if not isinstance(val, six.binary_type): # <<<<<<<<<<<<<< + * try: + * val = val.encode("utf-8") +*/ + } + + /* "thriftpy2/protocol/cybin/cybin.pyx":400 + * except Exception: + * pass + * write_string(buf, val) # <<<<<<<<<<<<<< + * + * elif ttype == T_SET or ttype == T_LIST: +*/ + __pyx_t_8 = __pyx_v_val; + __Pyx_INCREF(__pyx_t_8); + if (!(likely(PyBytes_CheckExact(__pyx_t_8))||((__pyx_t_8) == Py_None) || __Pyx_RaiseUnexpectedTypeError("bytes", __pyx_t_8))) __PYX_ERR(0, 400, __pyx_L1_error) + __pyx_t_9 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_write_string(__pyx_v_buf, ((PyObject*)__pyx_t_8)); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 400, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":394 + * write_string(buf, val) + * + * elif ttype == T_STRING: # <<<<<<<<<<<<<< + * if not isinstance(val, six.binary_type): + * try: +*/ + break; + case __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_SET: + + /* "thriftpy2/protocol/cybin/cybin.pyx":402 + * write_string(buf, val) + * + * elif ttype == T_SET or ttype == T_LIST: # <<<<<<<<<<<<<< + * write_list(buf, val, spec) + * +*/ + case __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_LIST: + + /* "thriftpy2/protocol/cybin/cybin.pyx":403 + * + * elif ttype == T_SET or ttype == T_LIST: + * write_list(buf, val, spec) # <<<<<<<<<<<<<< + * + * elif ttype == T_MAP: +*/ + __pyx_t_9 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_write_list(__pyx_v_buf, __pyx_v_val, __pyx_v_spec); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 403, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":402 + * write_string(buf, val) + * + * elif ttype == T_SET or ttype == T_LIST: # <<<<<<<<<<<<<< + * write_list(buf, val, spec) + * +*/ + break; + case __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_MAP: + + /* "thriftpy2/protocol/cybin/cybin.pyx":406 + * + * elif ttype == T_MAP: + * write_dict(buf, val, spec) # <<<<<<<<<<<<<< + * + * elif ttype == T_STRUCT: +*/ + __pyx_t_9 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_write_dict(__pyx_v_buf, __pyx_v_val, __pyx_v_spec); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 406, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":405 + * write_list(buf, val, spec) + * + * elif ttype == T_MAP: # <<<<<<<<<<<<<< + * write_dict(buf, val, spec) + * +*/ + break; + case __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_STRUCT: + + /* "thriftpy2/protocol/cybin/cybin.pyx":409 + * + * elif ttype == T_STRUCT: + * write_struct(buf, val) # <<<<<<<<<<<<<< + * + * +*/ + __pyx_t_9 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_write_struct(__pyx_v_buf, __pyx_v_val); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 409, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":408 + * write_dict(buf, val, spec) + * + * elif ttype == T_STRUCT: # <<<<<<<<<<<<<< + * write_struct(buf, val) + * +*/ + break; + default: break; + } + + /* "thriftpy2/protocol/cybin/cybin.pyx":370 + * + * + * cdef c_write_val(CyTransportBase buf, TType ttype, val, spec=None): # <<<<<<<<<<<<<< + * if ttype == T_BOOL: + * write_i08(buf, 1 if val else 0) +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_8); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_AddTraceback("thriftpy2.protocol.cybin.cybin.c_write_val", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_val); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/protocol/cybin/cybin.pyx":412 + * + * + * cpdef skip(CyTransportBase buf, TType ttype): # <<<<<<<<<<<<<< + * cdef TType v_type, k_type, f_type + * cdef int size +*/ + +static PyObject *__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_1skip(PyObject *__pyx_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyObject *__pyx_f_9thriftpy2_8protocol_5cybin_5cybin_skip(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *__pyx_v_buf, __pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType __pyx_v_ttype, CYTHON_UNUSED int __pyx_skip_dispatch) { + __pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType __pyx_v_v_type; + __pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType __pyx_v_k_type; + __pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType __pyx_v_f_type; + int __pyx_v_size; + CYTHON_UNUSED int __pyx_v__; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + char __pyx_t_1; + int16_t __pyx_t_2; + int32_t __pyx_t_3; + int64_t __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + int __pyx_t_6; + int __pyx_t_7; + int __pyx_t_8; + int __pyx_t_9; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("skip", 0); + + /* "thriftpy2/protocol/cybin/cybin.pyx":416 + * cdef int size + * + * if ttype == T_BOOL or ttype == T_I08: # <<<<<<<<<<<<<< + * read_i08(buf) + * elif ttype == T_I16: +*/ + switch (__pyx_v_ttype) { + case __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_BOOL: + case __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_I08: + + /* "thriftpy2/protocol/cybin/cybin.pyx":417 + * + * if ttype == T_BOOL or ttype == T_I08: + * read_i08(buf) # <<<<<<<<<<<<<< + * elif ttype == T_I16: + * read_i16(buf) +*/ + __pyx_t_1 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_read_i08(__pyx_v_buf); if (unlikely(__pyx_t_1 == ((char)-1) && PyErr_Occurred())) __PYX_ERR(0, 417, __pyx_L1_error) + + /* "thriftpy2/protocol/cybin/cybin.pyx":416 + * cdef int size + * + * if ttype == T_BOOL or ttype == T_I08: # <<<<<<<<<<<<<< + * read_i08(buf) + * elif ttype == T_I16: +*/ + break; + case __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_I16: + + /* "thriftpy2/protocol/cybin/cybin.pyx":419 + * read_i08(buf) + * elif ttype == T_I16: + * read_i16(buf) # <<<<<<<<<<<<<< + * elif ttype == T_I32: + * read_i32(buf) +*/ + __pyx_t_2 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_read_i16(__pyx_v_buf); if (unlikely(__pyx_t_2 == ((int16_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 419, __pyx_L1_error) + + /* "thriftpy2/protocol/cybin/cybin.pyx":418 + * if ttype == T_BOOL or ttype == T_I08: + * read_i08(buf) + * elif ttype == T_I16: # <<<<<<<<<<<<<< + * read_i16(buf) + * elif ttype == T_I32: +*/ + break; + case __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_I32: + + /* "thriftpy2/protocol/cybin/cybin.pyx":421 + * read_i16(buf) + * elif ttype == T_I32: + * read_i32(buf) # <<<<<<<<<<<<<< + * elif ttype == T_I64 or ttype == T_DOUBLE: + * read_i64(buf) +*/ + __pyx_t_3 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_read_i32(__pyx_v_buf); if (unlikely(__pyx_t_3 == ((int32_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 421, __pyx_L1_error) + + /* "thriftpy2/protocol/cybin/cybin.pyx":420 + * elif ttype == T_I16: + * read_i16(buf) + * elif ttype == T_I32: # <<<<<<<<<<<<<< + * read_i32(buf) + * elif ttype == T_I64 or ttype == T_DOUBLE: +*/ + break; + case __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_I64: + + /* "thriftpy2/protocol/cybin/cybin.pyx":422 + * elif ttype == T_I32: + * read_i32(buf) + * elif ttype == T_I64 or ttype == T_DOUBLE: # <<<<<<<<<<<<<< + * read_i64(buf) + * elif ttype == T_STRING or ttype == T_BINARY: +*/ + case __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_DOUBLE: + + /* "thriftpy2/protocol/cybin/cybin.pyx":423 + * read_i32(buf) + * elif ttype == T_I64 or ttype == T_DOUBLE: + * read_i64(buf) # <<<<<<<<<<<<<< + * elif ttype == T_STRING or ttype == T_BINARY: + * size = read_i32(buf) +*/ + __pyx_t_4 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_read_i64(__pyx_v_buf); if (unlikely(__pyx_t_4 == ((int64_t)-1L) && PyErr_Occurred())) __PYX_ERR(0, 423, __pyx_L1_error) + + /* "thriftpy2/protocol/cybin/cybin.pyx":422 + * elif ttype == T_I32: + * read_i32(buf) + * elif ttype == T_I64 or ttype == T_DOUBLE: # <<<<<<<<<<<<<< + * read_i64(buf) + * elif ttype == T_STRING or ttype == T_BINARY: +*/ + break; + case __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_STRING: + + /* "thriftpy2/protocol/cybin/cybin.pyx":424 + * elif ttype == T_I64 or ttype == T_DOUBLE: + * read_i64(buf) + * elif ttype == T_STRING or ttype == T_BINARY: # <<<<<<<<<<<<<< + * size = read_i32(buf) + * c_read_binary(buf, size) +*/ + case __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_BINARY: + + /* "thriftpy2/protocol/cybin/cybin.pyx":425 + * read_i64(buf) + * elif ttype == T_STRING or ttype == T_BINARY: + * size = read_i32(buf) # <<<<<<<<<<<<<< + * c_read_binary(buf, size) + * elif ttype == T_SET or ttype == T_LIST: +*/ + __pyx_t_3 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_read_i32(__pyx_v_buf); if (unlikely(__pyx_t_3 == ((int32_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 425, __pyx_L1_error) + __pyx_v_size = __pyx_t_3; + + /* "thriftpy2/protocol/cybin/cybin.pyx":426 + * elif ttype == T_STRING or ttype == T_BINARY: + * size = read_i32(buf) + * c_read_binary(buf, size) # <<<<<<<<<<<<<< + * elif ttype == T_SET or ttype == T_LIST: + * v_type = read_i08(buf) +*/ + __pyx_t_5 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_c_read_binary(__pyx_v_buf, __pyx_v_size); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 426, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":424 + * elif ttype == T_I64 or ttype == T_DOUBLE: + * read_i64(buf) + * elif ttype == T_STRING or ttype == T_BINARY: # <<<<<<<<<<<<<< + * size = read_i32(buf) + * c_read_binary(buf, size) +*/ + break; + case __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_SET: + + /* "thriftpy2/protocol/cybin/cybin.pyx":427 + * size = read_i32(buf) + * c_read_binary(buf, size) + * elif ttype == T_SET or ttype == T_LIST: # <<<<<<<<<<<<<< + * v_type = read_i08(buf) + * size = read_i32(buf) +*/ + case __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_LIST: + + /* "thriftpy2/protocol/cybin/cybin.pyx":428 + * c_read_binary(buf, size) + * elif ttype == T_SET or ttype == T_LIST: + * v_type = read_i08(buf) # <<<<<<<<<<<<<< + * size = read_i32(buf) + * for _ in range(size): +*/ + __pyx_t_1 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_read_i08(__pyx_v_buf); if (unlikely(__pyx_t_1 == ((char)-1) && PyErr_Occurred())) __PYX_ERR(0, 428, __pyx_L1_error) + __pyx_v_v_type = ((__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)__pyx_t_1); + + /* "thriftpy2/protocol/cybin/cybin.pyx":429 + * elif ttype == T_SET or ttype == T_LIST: + * v_type = read_i08(buf) + * size = read_i32(buf) # <<<<<<<<<<<<<< + * for _ in range(size): + * skip(buf, v_type) +*/ + __pyx_t_3 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_read_i32(__pyx_v_buf); if (unlikely(__pyx_t_3 == ((int32_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 429, __pyx_L1_error) + __pyx_v_size = __pyx_t_3; + + /* "thriftpy2/protocol/cybin/cybin.pyx":430 + * v_type = read_i08(buf) + * size = read_i32(buf) + * for _ in range(size): # <<<<<<<<<<<<<< + * skip(buf, v_type) + * elif ttype == T_MAP: +*/ + __pyx_t_6 = __pyx_v_size; + __pyx_t_7 = __pyx_t_6; + for (__pyx_t_8 = 0; __pyx_t_8 < __pyx_t_7; __pyx_t_8+=1) { + __pyx_v__ = __pyx_t_8; + + /* "thriftpy2/protocol/cybin/cybin.pyx":431 + * size = read_i32(buf) + * for _ in range(size): + * skip(buf, v_type) # <<<<<<<<<<<<<< + * elif ttype == T_MAP: + * k_type = read_i08(buf) +*/ + __pyx_t_5 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_skip(__pyx_v_buf, __pyx_v_v_type, 0); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 431, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + } + + /* "thriftpy2/protocol/cybin/cybin.pyx":427 + * size = read_i32(buf) + * c_read_binary(buf, size) + * elif ttype == T_SET or ttype == T_LIST: # <<<<<<<<<<<<<< + * v_type = read_i08(buf) + * size = read_i32(buf) +*/ + break; + case __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_MAP: + + /* "thriftpy2/protocol/cybin/cybin.pyx":433 + * skip(buf, v_type) + * elif ttype == T_MAP: + * k_type = read_i08(buf) # <<<<<<<<<<<<<< + * v_type = read_i08(buf) + * size = read_i32(buf) +*/ + __pyx_t_1 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_read_i08(__pyx_v_buf); if (unlikely(__pyx_t_1 == ((char)-1) && PyErr_Occurred())) __PYX_ERR(0, 433, __pyx_L1_error) + __pyx_v_k_type = ((__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)__pyx_t_1); + + /* "thriftpy2/protocol/cybin/cybin.pyx":434 + * elif ttype == T_MAP: + * k_type = read_i08(buf) + * v_type = read_i08(buf) # <<<<<<<<<<<<<< + * size = read_i32(buf) + * for _ in range(size): +*/ + __pyx_t_1 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_read_i08(__pyx_v_buf); if (unlikely(__pyx_t_1 == ((char)-1) && PyErr_Occurred())) __PYX_ERR(0, 434, __pyx_L1_error) + __pyx_v_v_type = ((__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)__pyx_t_1); + + /* "thriftpy2/protocol/cybin/cybin.pyx":435 + * k_type = read_i08(buf) + * v_type = read_i08(buf) + * size = read_i32(buf) # <<<<<<<<<<<<<< + * for _ in range(size): + * skip(buf, k_type) +*/ + __pyx_t_3 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_read_i32(__pyx_v_buf); if (unlikely(__pyx_t_3 == ((int32_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 435, __pyx_L1_error) + __pyx_v_size = __pyx_t_3; + + /* "thriftpy2/protocol/cybin/cybin.pyx":436 + * v_type = read_i08(buf) + * size = read_i32(buf) + * for _ in range(size): # <<<<<<<<<<<<<< + * skip(buf, k_type) + * skip(buf, v_type) +*/ + __pyx_t_6 = __pyx_v_size; + __pyx_t_7 = __pyx_t_6; + for (__pyx_t_8 = 0; __pyx_t_8 < __pyx_t_7; __pyx_t_8+=1) { + __pyx_v__ = __pyx_t_8; + + /* "thriftpy2/protocol/cybin/cybin.pyx":437 + * size = read_i32(buf) + * for _ in range(size): + * skip(buf, k_type) # <<<<<<<<<<<<<< + * skip(buf, v_type) + * elif ttype == T_STRUCT: +*/ + __pyx_t_5 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_skip(__pyx_v_buf, __pyx_v_k_type, 0); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 437, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":438 + * for _ in range(size): + * skip(buf, k_type) + * skip(buf, v_type) # <<<<<<<<<<<<<< + * elif ttype == T_STRUCT: + * while 1: +*/ + __pyx_t_5 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_skip(__pyx_v_buf, __pyx_v_v_type, 0); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 438, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + } + + /* "thriftpy2/protocol/cybin/cybin.pyx":432 + * for _ in range(size): + * skip(buf, v_type) + * elif ttype == T_MAP: # <<<<<<<<<<<<<< + * k_type = read_i08(buf) + * v_type = read_i08(buf) +*/ + break; + case __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_STRUCT: + + /* "thriftpy2/protocol/cybin/cybin.pyx":440 + * skip(buf, v_type) + * elif ttype == T_STRUCT: + * while 1: # <<<<<<<<<<<<<< + * f_type = read_i08(buf) + * if f_type == T_STOP: +*/ + while (1) { + + /* "thriftpy2/protocol/cybin/cybin.pyx":441 + * elif ttype == T_STRUCT: + * while 1: + * f_type = read_i08(buf) # <<<<<<<<<<<<<< + * if f_type == T_STOP: + * break +*/ + __pyx_t_1 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_read_i08(__pyx_v_buf); if (unlikely(__pyx_t_1 == ((char)-1) && PyErr_Occurred())) __PYX_ERR(0, 441, __pyx_L1_error) + __pyx_v_f_type = ((__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)__pyx_t_1); + + /* "thriftpy2/protocol/cybin/cybin.pyx":442 + * while 1: + * f_type = read_i08(buf) + * if f_type == T_STOP: # <<<<<<<<<<<<<< + * break + * read_i16(buf) +*/ + __pyx_t_9 = (__pyx_v_f_type == __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_STOP); + if (__pyx_t_9) { + + /* "thriftpy2/protocol/cybin/cybin.pyx":443 + * f_type = read_i08(buf) + * if f_type == T_STOP: + * break # <<<<<<<<<<<<<< + * read_i16(buf) + * skip(buf, f_type) +*/ + goto __pyx_L8_break; + + /* "thriftpy2/protocol/cybin/cybin.pyx":442 + * while 1: + * f_type = read_i08(buf) + * if f_type == T_STOP: # <<<<<<<<<<<<<< + * break + * read_i16(buf) +*/ + } + + /* "thriftpy2/protocol/cybin/cybin.pyx":444 + * if f_type == T_STOP: + * break + * read_i16(buf) # <<<<<<<<<<<<<< + * skip(buf, f_type) + * +*/ + __pyx_t_2 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_read_i16(__pyx_v_buf); if (unlikely(__pyx_t_2 == ((int16_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 444, __pyx_L1_error) + + /* "thriftpy2/protocol/cybin/cybin.pyx":445 + * break + * read_i16(buf) + * skip(buf, f_type) # <<<<<<<<<<<<<< + * + * +*/ + __pyx_t_5 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_skip(__pyx_v_buf, __pyx_v_f_type, 0); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 445, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + } + __pyx_L8_break:; + + /* "thriftpy2/protocol/cybin/cybin.pyx":439 + * skip(buf, k_type) + * skip(buf, v_type) + * elif ttype == T_STRUCT: # <<<<<<<<<<<<<< + * while 1: + * f_type = read_i08(buf) +*/ + break; + default: break; + } + + /* "thriftpy2/protocol/cybin/cybin.pyx":412 + * + * + * cpdef skip(CyTransportBase buf, TType ttype): # <<<<<<<<<<<<<< + * cdef TType v_type, k_type, f_type + * cdef int size +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("thriftpy2.protocol.cybin.cybin.skip", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_1skip(PyObject *__pyx_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_8protocol_5cybin_5cybin_1skip = {"skip", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_1skip, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_1skip(PyObject *__pyx_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *__pyx_v_buf = 0; + __pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType __pyx_v_ttype; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[2] = {0,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("skip (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_buf,&__pyx_mstate_global->__pyx_n_u_ttype,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 412, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 2: + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 412, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 412, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "skip", 0) < (0)) __PYX_ERR(0, 412, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 2; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("skip", 1, 2, 2, i); __PYX_ERR(0, 412, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 2)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 412, __pyx_L3_error) + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 412, __pyx_L3_error) + } + __pyx_v_buf = ((struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *)values[0]); + __pyx_v_ttype = ((__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)__Pyx_PyLong_As___pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType(values[1])); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 412, __pyx_L3_error) + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("skip", 1, 2, 2, __pyx_nargs); __PYX_ERR(0, 412, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("thriftpy2.protocol.cybin.cybin.skip", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_buf), __pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase, 1, "buf", 0))) __PYX_ERR(0, 412, __pyx_L1_error) + __pyx_r = __pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_skip(__pyx_self, __pyx_v_buf, __pyx_v_ttype); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + goto __pyx_L7_cleaned_up; + __pyx_L0:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __pyx_L7_cleaned_up:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_skip(CYTHON_UNUSED PyObject *__pyx_self, struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *__pyx_v_buf, __pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType __pyx_v_ttype) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("skip", 0); + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_skip(__pyx_v_buf, __pyx_v_ttype, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 412, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("thriftpy2.protocol.cybin.cybin.skip", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/protocol/cybin/cybin.pyx":448 + * + * + * def read_val(CyTransportBase buf, TType ttype, decode_response=True, # <<<<<<<<<<<<<< + * strict_decode=False): + * return c_read_val(buf, ttype, None, decode_response, strict_decode) +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_3read_val(PyObject *__pyx_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_8protocol_5cybin_5cybin_3read_val = {"read_val", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_3read_val, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_3read_val(PyObject *__pyx_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *__pyx_v_buf = 0; + __pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType __pyx_v_ttype; + PyObject *__pyx_v_decode_response = 0; + PyObject *__pyx_v_strict_decode = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[4] = {0,0,0,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("read_val (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_buf,&__pyx_mstate_global->__pyx_n_u_ttype,&__pyx_mstate_global->__pyx_n_u_decode_response,&__pyx_mstate_global->__pyx_n_u_strict_decode,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 448, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 4: + values[3] = __Pyx_ArgRef_FASTCALL(__pyx_args, 3); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[3])) __PYX_ERR(0, 448, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 3: + values[2] = __Pyx_ArgRef_FASTCALL(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(0, 448, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 2: + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 448, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 448, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "read_val", 0) < (0)) __PYX_ERR(0, 448, __pyx_L3_error) + if (!values[2]) values[2] = __Pyx_NewRef(((PyObject *)((PyObject*)Py_True))); + + /* "thriftpy2/protocol/cybin/cybin.pyx":449 + * + * def read_val(CyTransportBase buf, TType ttype, decode_response=True, + * strict_decode=False): # <<<<<<<<<<<<<< + * return c_read_val(buf, ttype, None, decode_response, strict_decode) + * +*/ + if (!values[3]) values[3] = __Pyx_NewRef(((PyObject *)((PyObject*)Py_False))); + for (Py_ssize_t i = __pyx_nargs; i < 2; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("read_val", 0, 2, 4, i); __PYX_ERR(0, 448, __pyx_L3_error) } + } + } else { + switch (__pyx_nargs) { + case 4: + values[3] = __Pyx_ArgRef_FASTCALL(__pyx_args, 3); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[3])) __PYX_ERR(0, 448, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 3: + values[2] = __Pyx_ArgRef_FASTCALL(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(0, 448, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 2: + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 448, __pyx_L3_error) + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 448, __pyx_L3_error) + break; + default: goto __pyx_L5_argtuple_error; + } + if (!values[2]) values[2] = __Pyx_NewRef(((PyObject *)((PyObject*)Py_True))); + if (!values[3]) values[3] = __Pyx_NewRef(((PyObject *)((PyObject*)Py_False))); + } + __pyx_v_buf = ((struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *)values[0]); + __pyx_v_ttype = ((__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)__Pyx_PyLong_As___pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType(values[1])); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 448, __pyx_L3_error) + __pyx_v_decode_response = values[2]; + __pyx_v_strict_decode = values[3]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("read_val", 0, 2, 4, __pyx_nargs); __PYX_ERR(0, 448, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("thriftpy2.protocol.cybin.cybin.read_val", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_buf), __pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase, 1, "buf", 0))) __PYX_ERR(0, 448, __pyx_L1_error) + __pyx_r = __pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_2read_val(__pyx_self, __pyx_v_buf, __pyx_v_ttype, __pyx_v_decode_response, __pyx_v_strict_decode); + + /* "thriftpy2/protocol/cybin/cybin.pyx":448 + * + * + * def read_val(CyTransportBase buf, TType ttype, decode_response=True, # <<<<<<<<<<<<<< + * strict_decode=False): + * return c_read_val(buf, ttype, None, decode_response, strict_decode) +*/ + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + goto __pyx_L7_cleaned_up; + __pyx_L0:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __pyx_L7_cleaned_up:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_2read_val(CYTHON_UNUSED PyObject *__pyx_self, struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *__pyx_v_buf, __pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType __pyx_v_ttype, PyObject *__pyx_v_decode_response, PyObject *__pyx_v_strict_decode) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + struct __pyx_opt_args_9thriftpy2_8protocol_5cybin_5cybin_c_read_val __pyx_t_2; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("read_val", 0); + + /* "thriftpy2/protocol/cybin/cybin.pyx":450 + * def read_val(CyTransportBase buf, TType ttype, decode_response=True, + * strict_decode=False): + * return c_read_val(buf, ttype, None, decode_response, strict_decode) # <<<<<<<<<<<<<< + * + * +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2.__pyx_n = 3; + __pyx_t_2.spec = Py_None; + __pyx_t_2.decode_response = __pyx_v_decode_response; + __pyx_t_2.strict_decode = __pyx_v_strict_decode; + __pyx_t_1 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_c_read_val(__pyx_v_buf, __pyx_v_ttype, &__pyx_t_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 450, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":448 + * + * + * def read_val(CyTransportBase buf, TType ttype, decode_response=True, # <<<<<<<<<<<<<< + * strict_decode=False): + * return c_read_val(buf, ttype, None, decode_response, strict_decode) +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("thriftpy2.protocol.cybin.cybin.read_val", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/protocol/cybin/cybin.pyx":453 + * + * + * def write_val(CyTransportBase buf, TType ttype, val, spec=None): # <<<<<<<<<<<<<< + * c_write_val(buf, ttype, val, spec) + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_5write_val(PyObject *__pyx_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_8protocol_5cybin_5cybin_5write_val = {"write_val", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_5write_val, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_5write_val(PyObject *__pyx_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *__pyx_v_buf = 0; + __pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType __pyx_v_ttype; + PyObject *__pyx_v_val = 0; + PyObject *__pyx_v_spec = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[4] = {0,0,0,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("write_val (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_buf,&__pyx_mstate_global->__pyx_n_u_ttype,&__pyx_mstate_global->__pyx_n_u_val,&__pyx_mstate_global->__pyx_n_u_spec,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 453, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 4: + values[3] = __Pyx_ArgRef_FASTCALL(__pyx_args, 3); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[3])) __PYX_ERR(0, 453, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 3: + values[2] = __Pyx_ArgRef_FASTCALL(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(0, 453, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 2: + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 453, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 453, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "write_val", 0) < (0)) __PYX_ERR(0, 453, __pyx_L3_error) + if (!values[3]) values[3] = __Pyx_NewRef(((PyObject *)Py_None)); + for (Py_ssize_t i = __pyx_nargs; i < 3; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("write_val", 0, 3, 4, i); __PYX_ERR(0, 453, __pyx_L3_error) } + } + } else { + switch (__pyx_nargs) { + case 4: + values[3] = __Pyx_ArgRef_FASTCALL(__pyx_args, 3); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[3])) __PYX_ERR(0, 453, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 3: + values[2] = __Pyx_ArgRef_FASTCALL(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(0, 453, __pyx_L3_error) + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 453, __pyx_L3_error) + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 453, __pyx_L3_error) + break; + default: goto __pyx_L5_argtuple_error; + } + if (!values[3]) values[3] = __Pyx_NewRef(((PyObject *)Py_None)); + } + __pyx_v_buf = ((struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *)values[0]); + __pyx_v_ttype = ((__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)__Pyx_PyLong_As___pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType(values[1])); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 453, __pyx_L3_error) + __pyx_v_val = values[2]; + __pyx_v_spec = values[3]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("write_val", 0, 3, 4, __pyx_nargs); __PYX_ERR(0, 453, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("thriftpy2.protocol.cybin.cybin.write_val", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_buf), __pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase, 1, "buf", 0))) __PYX_ERR(0, 453, __pyx_L1_error) + __pyx_r = __pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_4write_val(__pyx_self, __pyx_v_buf, __pyx_v_ttype, __pyx_v_val, __pyx_v_spec); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + goto __pyx_L7_cleaned_up; + __pyx_L0:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __pyx_L7_cleaned_up:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_4write_val(CYTHON_UNUSED PyObject *__pyx_self, struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *__pyx_v_buf, __pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType __pyx_v_ttype, PyObject *__pyx_v_val, PyObject *__pyx_v_spec) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + struct __pyx_opt_args_9thriftpy2_8protocol_5cybin_5cybin_c_write_val __pyx_t_2; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("write_val", 0); + + /* "thriftpy2/protocol/cybin/cybin.pyx":454 + * + * def write_val(CyTransportBase buf, TType ttype, val, spec=None): + * c_write_val(buf, ttype, val, spec) # <<<<<<<<<<<<<< + * + * +*/ + __pyx_t_2.__pyx_n = 1; + __pyx_t_2.spec = __pyx_v_spec; + __pyx_t_1 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_c_write_val(__pyx_v_buf, __pyx_v_ttype, __pyx_v_val, &__pyx_t_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 454, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":453 + * + * + * def write_val(CyTransportBase buf, TType ttype, val, spec=None): # <<<<<<<<<<<<<< + * c_write_val(buf, ttype, val, spec) + * +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("thriftpy2.protocol.cybin.cybin.write_val", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/protocol/cybin/cybin.pyx":464 + * cdef public bool strict_decode + * + * def __init__(self, trans, strict_read=True, strict_write=True, # <<<<<<<<<<<<<< + * decode_response=True, strict_decode=False): + * self.trans = trans +*/ + +/* Python wrapper */ +static int __pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_trans = 0; + PyObject *__pyx_v_strict_read = 0; + PyObject *__pyx_v_strict_write = 0; + PyObject *__pyx_v_decode_response = 0; + PyObject *__pyx_v_strict_decode = 0; + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[5] = {0,0,0,0,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return -1; + #endif + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_trans,&__pyx_mstate_global->__pyx_n_u_strict_read,&__pyx_mstate_global->__pyx_n_u_strict_write,&__pyx_mstate_global->__pyx_n_u_decode_response,&__pyx_mstate_global->__pyx_n_u_strict_decode,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_VARARGS(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 464, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 5: + values[4] = __Pyx_ArgRef_VARARGS(__pyx_args, 4); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[4])) __PYX_ERR(0, 464, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 4: + values[3] = __Pyx_ArgRef_VARARGS(__pyx_args, 3); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[3])) __PYX_ERR(0, 464, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 3: + values[2] = __Pyx_ArgRef_VARARGS(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(0, 464, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 2: + values[1] = __Pyx_ArgRef_VARARGS(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 464, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_VARARGS(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 464, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "__init__", 0) < (0)) __PYX_ERR(0, 464, __pyx_L3_error) + if (!values[1]) values[1] = __Pyx_NewRef(((PyObject *)Py_True)); + if (!values[2]) values[2] = __Pyx_NewRef(((PyObject *)Py_True)); + + /* "thriftpy2/protocol/cybin/cybin.pyx":465 + * + * def __init__(self, trans, strict_read=True, strict_write=True, + * decode_response=True, strict_decode=False): # <<<<<<<<<<<<<< + * self.trans = trans + * self.strict_read = strict_read +*/ + if (!values[3]) values[3] = __Pyx_NewRef(((PyObject *)Py_True)); + if (!values[4]) values[4] = __Pyx_NewRef(((PyObject *)Py_False)); + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("__init__", 0, 1, 5, i); __PYX_ERR(0, 464, __pyx_L3_error) } + } + } else { + switch (__pyx_nargs) { + case 5: + values[4] = __Pyx_ArgRef_VARARGS(__pyx_args, 4); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[4])) __PYX_ERR(0, 464, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 4: + values[3] = __Pyx_ArgRef_VARARGS(__pyx_args, 3); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[3])) __PYX_ERR(0, 464, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 3: + values[2] = __Pyx_ArgRef_VARARGS(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(0, 464, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 2: + values[1] = __Pyx_ArgRef_VARARGS(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 464, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_VARARGS(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 464, __pyx_L3_error) + break; + default: goto __pyx_L5_argtuple_error; + } + + /* "thriftpy2/protocol/cybin/cybin.pyx":464 + * cdef public bool strict_decode + * + * def __init__(self, trans, strict_read=True, strict_write=True, # <<<<<<<<<<<<<< + * decode_response=True, strict_decode=False): + * self.trans = trans +*/ + if (!values[1]) values[1] = __Pyx_NewRef(((PyObject *)Py_True)); + if (!values[2]) values[2] = __Pyx_NewRef(((PyObject *)Py_True)); + + /* "thriftpy2/protocol/cybin/cybin.pyx":465 + * + * def __init__(self, trans, strict_read=True, strict_write=True, + * decode_response=True, strict_decode=False): # <<<<<<<<<<<<<< + * self.trans = trans + * self.strict_read = strict_read +*/ + if (!values[3]) values[3] = __Pyx_NewRef(((PyObject *)Py_True)); + if (!values[4]) values[4] = __Pyx_NewRef(((PyObject *)Py_False)); + } + __pyx_v_trans = values[0]; + __pyx_v_strict_read = values[1]; + __pyx_v_strict_write = values[2]; + __pyx_v_decode_response = values[3]; + __pyx_v_strict_decode = values[4]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__init__", 0, 1, 5, __pyx_nargs); __PYX_ERR(0, 464, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("thriftpy2.protocol.cybin.cybin.TCyBinaryProtocol.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol___init__(((struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *)__pyx_v_self), __pyx_v_trans, __pyx_v_strict_read, __pyx_v_strict_write, __pyx_v_decode_response, __pyx_v_strict_decode); + + /* "thriftpy2/protocol/cybin/cybin.pyx":464 + * cdef public bool strict_decode + * + * def __init__(self, trans, strict_read=True, strict_write=True, # <<<<<<<<<<<<<< + * decode_response=True, strict_decode=False): + * self.trans = trans +*/ + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol___init__(struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *__pyx_v_self, PyObject *__pyx_v_trans, PyObject *__pyx_v_strict_read, PyObject *__pyx_v_strict_write, PyObject *__pyx_v_decode_response, PyObject *__pyx_v_strict_decode) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__init__", 0); + + /* "thriftpy2/protocol/cybin/cybin.pyx":466 + * def __init__(self, trans, strict_read=True, strict_write=True, + * decode_response=True, strict_decode=False): + * self.trans = trans # <<<<<<<<<<<<<< + * self.strict_read = strict_read + * self.strict_write = strict_write +*/ + __pyx_t_1 = __pyx_v_trans; + __Pyx_INCREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase))))) __PYX_ERR(0, 466, __pyx_L1_error) + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF((PyObject *)__pyx_v_self->trans); + __Pyx_DECREF((PyObject *)__pyx_v_self->trans); + __pyx_v_self->trans = ((struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":467 + * decode_response=True, strict_decode=False): + * self.trans = trans + * self.strict_read = strict_read # <<<<<<<<<<<<<< + * self.strict_write = strict_write + * self.decode_response = decode_response +*/ + __pyx_t_1 = __pyx_v_strict_read; + __Pyx_INCREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_mstate_global->__pyx_ptype_7cpython_4bool_bool))))) __PYX_ERR(0, 467, __pyx_L1_error) + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF((PyObject *)__pyx_v_self->strict_read); + __Pyx_DECREF((PyObject *)__pyx_v_self->strict_read); + __pyx_v_self->strict_read = ((PyLongObject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":468 + * self.trans = trans + * self.strict_read = strict_read + * self.strict_write = strict_write # <<<<<<<<<<<<<< + * self.decode_response = decode_response + * self.strict_decode = strict_decode +*/ + __pyx_t_1 = __pyx_v_strict_write; + __Pyx_INCREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_mstate_global->__pyx_ptype_7cpython_4bool_bool))))) __PYX_ERR(0, 468, __pyx_L1_error) + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF((PyObject *)__pyx_v_self->strict_write); + __Pyx_DECREF((PyObject *)__pyx_v_self->strict_write); + __pyx_v_self->strict_write = ((PyLongObject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":469 + * self.strict_read = strict_read + * self.strict_write = strict_write + * self.decode_response = decode_response # <<<<<<<<<<<<<< + * self.strict_decode = strict_decode + * +*/ + __pyx_t_1 = __pyx_v_decode_response; + __Pyx_INCREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_mstate_global->__pyx_ptype_7cpython_4bool_bool))))) __PYX_ERR(0, 469, __pyx_L1_error) + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF((PyObject *)__pyx_v_self->decode_response); + __Pyx_DECREF((PyObject *)__pyx_v_self->decode_response); + __pyx_v_self->decode_response = ((PyLongObject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":470 + * self.strict_write = strict_write + * self.decode_response = decode_response + * self.strict_decode = strict_decode # <<<<<<<<<<<<<< + * + * def skip(self, ttype): +*/ + __pyx_t_1 = __pyx_v_strict_decode; + __Pyx_INCREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_mstate_global->__pyx_ptype_7cpython_4bool_bool))))) __PYX_ERR(0, 470, __pyx_L1_error) + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF((PyObject *)__pyx_v_self->strict_decode); + __Pyx_DECREF((PyObject *)__pyx_v_self->strict_decode); + __pyx_v_self->strict_decode = ((PyLongObject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":464 + * cdef public bool strict_decode + * + * def __init__(self, trans, strict_read=True, strict_write=True, # <<<<<<<<<<<<<< + * decode_response=True, strict_decode=False): + * self.trans = trans +*/ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("thriftpy2.protocol.cybin.cybin.TCyBinaryProtocol.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/protocol/cybin/cybin.pyx":472 + * self.strict_decode = strict_decode + * + * def skip(self, ttype): # <<<<<<<<<<<<<< + * skip(self.trans, (ttype)) + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_3skip(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_3skip = {"skip", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_3skip, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_3skip(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_ttype = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("skip (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_ttype,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 472, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 472, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "skip", 0) < (0)) __PYX_ERR(0, 472, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("skip", 1, 1, 1, i); __PYX_ERR(0, 472, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 472, __pyx_L3_error) + } + __pyx_v_ttype = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("skip", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 472, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("thriftpy2.protocol.cybin.cybin.TCyBinaryProtocol.skip", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_2skip(((struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *)__pyx_v_self), __pyx_v_ttype); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_2skip(struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *__pyx_v_self, PyObject *__pyx_v_ttype) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + __pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("skip", 0); + + /* "thriftpy2/protocol/cybin/cybin.pyx":473 + * + * def skip(self, ttype): + * skip(self.trans, (ttype)) # <<<<<<<<<<<<<< + * + * def read_message_begin(self): +*/ + __pyx_t_1 = ((PyObject *)__pyx_v_self->trans); + __Pyx_INCREF(__pyx_t_1); + __pyx_t_2 = ((__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)__Pyx_PyLong_As___pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType(__pyx_v_ttype)); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 473, __pyx_L1_error) + __pyx_t_3 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_skip(((struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *)__pyx_t_1), ((__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)__pyx_t_2), 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 473, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":472 + * self.strict_decode = strict_decode + * + * def skip(self, ttype): # <<<<<<<<<<<<<< + * skip(self.trans, (ttype)) + * +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("thriftpy2.protocol.cybin.cybin.TCyBinaryProtocol.skip", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/protocol/cybin/cybin.pyx":475 + * skip(self.trans, (ttype)) + * + * def read_message_begin(self): # <<<<<<<<<<<<<< + * cdef int32_t size, version, seqid + * cdef TType ttype +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_5read_message_begin(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_5read_message_begin = {"read_message_begin", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_5read_message_begin, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_5read_message_begin(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("read_message_begin (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("read_message_begin", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("read_message_begin", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_4read_message_begin(((struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_4read_message_begin(struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *__pyx_v_self) { + int32_t __pyx_v_size; + int32_t __pyx_v_version; + int32_t __pyx_v_seqid; + __pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType __pyx_v_ttype; + PyObject *__pyx_v_name = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int32_t __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + size_t __pyx_t_8; + char __pyx_t_9; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("read_message_begin", 0); + + /* "thriftpy2/protocol/cybin/cybin.pyx":479 + * cdef TType ttype + * + * size = read_i32(self.trans) # <<<<<<<<<<<<<< + * if size < 0: + * version = size & VERSION_MASK +*/ + __pyx_t_1 = ((PyObject *)__pyx_v_self->trans); + __Pyx_INCREF(__pyx_t_1); + __pyx_t_2 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_read_i32(((struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *)__pyx_t_1)); if (unlikely(__pyx_t_2 == ((int32_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 479, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_size = __pyx_t_2; + + /* "thriftpy2/protocol/cybin/cybin.pyx":480 + * + * size = read_i32(self.trans) + * if size < 0: # <<<<<<<<<<<<<< + * version = size & VERSION_MASK + * if version != VERSION_1: +*/ + __pyx_t_3 = (__pyx_v_size < 0); + if (__pyx_t_3) { + + /* "thriftpy2/protocol/cybin/cybin.pyx":481 + * size = read_i32(self.trans) + * if size < 0: + * version = size & VERSION_MASK # <<<<<<<<<<<<<< + * if version != VERSION_1: + * raise ProtocolError('invalid version %d' % version) +*/ + __pyx_v_version = (__pyx_v_size & -65536L); + + /* "thriftpy2/protocol/cybin/cybin.pyx":482 + * if size < 0: + * version = size & VERSION_MASK + * if version != VERSION_1: # <<<<<<<<<<<<<< + * raise ProtocolError('invalid version %d' % version) + * +*/ + __pyx_t_3 = (__pyx_v_version != -2147418112L); + if (unlikely(__pyx_t_3)) { + + /* "thriftpy2/protocol/cybin/cybin.pyx":483 + * version = size & VERSION_MASK + * if version != VERSION_1: + * raise ProtocolError('invalid version %d' % version) # <<<<<<<<<<<<<< + * + * name = c_read_val(self.trans, T_STRING) +*/ + __pyx_t_4 = NULL; + __Pyx_GetModuleGlobalName(__pyx_t_5, __pyx_mstate_global->__pyx_n_u_ProtocolError); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 483, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = __Pyx_PyLong_From_int32_t(__pyx_v_version); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 483, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = PyUnicode_Format(__pyx_mstate_global->__pyx_kp_u_invalid_version_d, __pyx_t_6); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 483, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_8 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_5))) { + __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_5); + assert(__pyx_t_4); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_5); + __Pyx_INCREF(__pyx_t_4); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_5, __pyx__function); + __pyx_t_8 = 0; + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_4, __pyx_t_7}; + __pyx_t_1 = __Pyx_PyObject_FastCall((PyObject*)__pyx_t_5, __pyx_callargs+__pyx_t_8, (2-__pyx_t_8) | (__pyx_t_8*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 483, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_ERR(0, 483, __pyx_L1_error) + + /* "thriftpy2/protocol/cybin/cybin.pyx":482 + * if size < 0: + * version = size & VERSION_MASK + * if version != VERSION_1: # <<<<<<<<<<<<<< + * raise ProtocolError('invalid version %d' % version) + * +*/ + } + + /* "thriftpy2/protocol/cybin/cybin.pyx":485 + * raise ProtocolError('invalid version %d' % version) + * + * name = c_read_val(self.trans, T_STRING) # <<<<<<<<<<<<<< + * ttype = (size & TYPE_MASK) + * else: +*/ + __pyx_t_1 = ((PyObject *)__pyx_v_self->trans); + __Pyx_INCREF(__pyx_t_1); + __pyx_t_5 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_c_read_val(((struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *)__pyx_t_1), __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_STRING, NULL); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 485, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_name = __pyx_t_5; + __pyx_t_5 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":486 + * + * name = c_read_val(self.trans, T_STRING) + * ttype = (size & TYPE_MASK) # <<<<<<<<<<<<<< + * else: + * if self.strict_read: +*/ + __pyx_v_ttype = ((__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)(__pyx_v_size & 0xFF)); + + /* "thriftpy2/protocol/cybin/cybin.pyx":480 + * + * size = read_i32(self.trans) + * if size < 0: # <<<<<<<<<<<<<< + * version = size & VERSION_MASK + * if version != VERSION_1: +*/ + goto __pyx_L3; + } + + /* "thriftpy2/protocol/cybin/cybin.pyx":488 + * ttype = (size & TYPE_MASK) + * else: + * if self.strict_read: # <<<<<<<<<<<<<< + * raise ProtocolError('No protocol version header') + * +*/ + /*else*/ { + __pyx_t_3 = __Pyx_PyObject_IsTrue(((PyObject *)__pyx_v_self->strict_read)); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 488, __pyx_L1_error) + if (unlikely(__pyx_t_3)) { + + /* "thriftpy2/protocol/cybin/cybin.pyx":489 + * else: + * if self.strict_read: + * raise ProtocolError('No protocol version header') # <<<<<<<<<<<<<< + * + * name = c_read_string(self.trans, size) +*/ + __pyx_t_1 = NULL; + __Pyx_GetModuleGlobalName(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_ProtocolError); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 489, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_8 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_7))) { + __pyx_t_1 = PyMethod_GET_SELF(__pyx_t_7); + assert(__pyx_t_1); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_7); + __Pyx_INCREF(__pyx_t_1); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_7, __pyx__function); + __pyx_t_8 = 0; + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_1, __pyx_mstate_global->__pyx_kp_u_No_protocol_version_header}; + __pyx_t_5 = __Pyx_PyObject_FastCall((PyObject*)__pyx_t_7, __pyx_callargs+__pyx_t_8, (2-__pyx_t_8) | (__pyx_t_8*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 489, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + } + __Pyx_Raise(__pyx_t_5, 0, 0, 0); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __PYX_ERR(0, 489, __pyx_L1_error) + + /* "thriftpy2/protocol/cybin/cybin.pyx":488 + * ttype = (size & TYPE_MASK) + * else: + * if self.strict_read: # <<<<<<<<<<<<<< + * raise ProtocolError('No protocol version header') + * +*/ + } + + /* "thriftpy2/protocol/cybin/cybin.pyx":491 + * raise ProtocolError('No protocol version header') + * + * name = c_read_string(self.trans, size) # <<<<<<<<<<<<<< + * ttype = (read_i08(self.trans)) + * +*/ + __pyx_t_5 = ((PyObject *)__pyx_v_self->trans); + __Pyx_INCREF(__pyx_t_5); + __pyx_t_7 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_c_read_string(((struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *)__pyx_t_5), __pyx_v_size, NULL); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 491, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_v_name = __pyx_t_7; + __pyx_t_7 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":492 + * + * name = c_read_string(self.trans, size) + * ttype = (read_i08(self.trans)) # <<<<<<<<<<<<<< + * + * seqid = read_i32(self.trans) +*/ + __pyx_t_7 = ((PyObject *)__pyx_v_self->trans); + __Pyx_INCREF(__pyx_t_7); + __pyx_t_9 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_read_i08(((struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *)__pyx_t_7)); if (unlikely(__pyx_t_9 == ((char)-1) && PyErr_Occurred())) __PYX_ERR(0, 492, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_v_ttype = ((__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)__pyx_t_9); + } + __pyx_L3:; + + /* "thriftpy2/protocol/cybin/cybin.pyx":494 + * ttype = (read_i08(self.trans)) + * + * seqid = read_i32(self.trans) # <<<<<<<<<<<<<< + * + * return name, ttype, seqid +*/ + __pyx_t_7 = ((PyObject *)__pyx_v_self->trans); + __Pyx_INCREF(__pyx_t_7); + __pyx_t_2 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_read_i32(((struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *)__pyx_t_7)); if (unlikely(__pyx_t_2 == ((int32_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 494, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_v_seqid = __pyx_t_2; + + /* "thriftpy2/protocol/cybin/cybin.pyx":496 + * seqid = read_i32(self.trans) + * + * return name, ttype, seqid # <<<<<<<<<<<<<< + * + * def read_message_end(self): +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_7 = __Pyx_PyLong_From___pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType(__pyx_v_ttype); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 496, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_5 = __Pyx_PyLong_From_int32_t(__pyx_v_seqid); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 496, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_1 = PyTuple_New(3); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 496, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_v_name); + __Pyx_GIVEREF(__pyx_v_name); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_name) != (0)) __PYX_ERR(0, 496, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_7); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_t_7) != (0)) __PYX_ERR(0, 496, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_5); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 2, __pyx_t_5) != (0)) __PYX_ERR(0, 496, __pyx_L1_error); + __pyx_t_7 = 0; + __pyx_t_5 = 0; + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":475 + * skip(self.trans, (ttype)) + * + * def read_message_begin(self): # <<<<<<<<<<<<<< + * cdef int32_t size, version, seqid + * cdef TType ttype +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_AddTraceback("thriftpy2.protocol.cybin.cybin.TCyBinaryProtocol.read_message_begin", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_name); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/protocol/cybin/cybin.pyx":498 + * return name, ttype, seqid + * + * def read_message_end(self): # <<<<<<<<<<<<<< + * pass + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_7read_message_end(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_7read_message_end = {"read_message_end", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_7read_message_end, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_7read_message_end(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("read_message_end (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("read_message_end", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("read_message_end", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_6read_message_end(((struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_6read_message_end(CYTHON_UNUSED struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("read_message_end", 0); + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/protocol/cybin/cybin.pyx":501 + * pass + * + * def write_message_begin(self, name, TType ttype, int32_t seqid): # <<<<<<<<<<<<<< + * cdef int32_t version = VERSION_1 | ttype + * if self.strict_write: +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_9write_message_begin(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_9write_message_begin = {"write_message_begin", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_9write_message_begin, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_9write_message_begin(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_name = 0; + __pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType __pyx_v_ttype; + int32_t __pyx_v_seqid; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[3] = {0,0,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("write_message_begin (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_name_2,&__pyx_mstate_global->__pyx_n_u_ttype,&__pyx_mstate_global->__pyx_n_u_seqid,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 501, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 3: + values[2] = __Pyx_ArgRef_FASTCALL(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(0, 501, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 2: + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 501, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 501, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "write_message_begin", 0) < (0)) __PYX_ERR(0, 501, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 3; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("write_message_begin", 1, 3, 3, i); __PYX_ERR(0, 501, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 3)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 501, __pyx_L3_error) + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 501, __pyx_L3_error) + values[2] = __Pyx_ArgRef_FASTCALL(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(0, 501, __pyx_L3_error) + } + __pyx_v_name = values[0]; + __pyx_v_ttype = ((__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)__Pyx_PyLong_As___pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType(values[1])); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 501, __pyx_L3_error) + __pyx_v_seqid = __Pyx_PyLong_As_int32_t(values[2]); if (unlikely((__pyx_v_seqid == ((int32_t)-1)) && PyErr_Occurred())) __PYX_ERR(0, 501, __pyx_L3_error) + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("write_message_begin", 1, 3, 3, __pyx_nargs); __PYX_ERR(0, 501, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("thriftpy2.protocol.cybin.cybin.TCyBinaryProtocol.write_message_begin", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_8write_message_begin(((struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *)__pyx_v_self), __pyx_v_name, __pyx_v_ttype, __pyx_v_seqid); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_8write_message_begin(struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *__pyx_v_self, PyObject *__pyx_v_name, __pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType __pyx_v_ttype, int32_t __pyx_v_seqid) { + int32_t __pyx_v_version; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("write_message_begin", 0); + + /* "thriftpy2/protocol/cybin/cybin.pyx":502 + * + * def write_message_begin(self, name, TType ttype, int32_t seqid): + * cdef int32_t version = VERSION_1 | ttype # <<<<<<<<<<<<<< + * if self.strict_write: + * write_i32(self.trans, version) +*/ + __pyx_v_version = (-2147418112L | __pyx_v_ttype); + + /* "thriftpy2/protocol/cybin/cybin.pyx":503 + * def write_message_begin(self, name, TType ttype, int32_t seqid): + * cdef int32_t version = VERSION_1 | ttype + * if self.strict_write: # <<<<<<<<<<<<<< + * write_i32(self.trans, version) + * c_write_val(self.trans, T_STRING, name) +*/ + __pyx_t_1 = __Pyx_PyObject_IsTrue(((PyObject *)__pyx_v_self->strict_write)); if (unlikely((__pyx_t_1 < 0))) __PYX_ERR(0, 503, __pyx_L1_error) + if (__pyx_t_1) { + + /* "thriftpy2/protocol/cybin/cybin.pyx":504 + * cdef int32_t version = VERSION_1 | ttype + * if self.strict_write: + * write_i32(self.trans, version) # <<<<<<<<<<<<<< + * c_write_val(self.trans, T_STRING, name) + * else: +*/ + __pyx_t_2 = ((PyObject *)__pyx_v_self->trans); + __Pyx_INCREF(__pyx_t_2); + __pyx_t_3 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_write_i32(((struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *)__pyx_t_2), __pyx_v_version); if (unlikely(__pyx_t_3 == ((int)-1))) __PYX_ERR(0, 504, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":505 + * if self.strict_write: + * write_i32(self.trans, version) + * c_write_val(self.trans, T_STRING, name) # <<<<<<<<<<<<<< + * else: + * c_write_val(self.trans, T_STRING, name) +*/ + __pyx_t_2 = ((PyObject *)__pyx_v_self->trans); + __Pyx_INCREF(__pyx_t_2); + __pyx_t_4 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_c_write_val(((struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *)__pyx_t_2), __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_STRING, __pyx_v_name, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 505, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":503 + * def write_message_begin(self, name, TType ttype, int32_t seqid): + * cdef int32_t version = VERSION_1 | ttype + * if self.strict_write: # <<<<<<<<<<<<<< + * write_i32(self.trans, version) + * c_write_val(self.trans, T_STRING, name) +*/ + goto __pyx_L3; + } + + /* "thriftpy2/protocol/cybin/cybin.pyx":507 + * c_write_val(self.trans, T_STRING, name) + * else: + * c_write_val(self.trans, T_STRING, name) # <<<<<<<<<<<<<< + * write_i08(self.trans, ttype) + * +*/ + /*else*/ { + __pyx_t_4 = ((PyObject *)__pyx_v_self->trans); + __Pyx_INCREF(__pyx_t_4); + __pyx_t_2 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_c_write_val(((struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *)__pyx_t_4), __pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_STRING, __pyx_v_name, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 507, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":508 + * else: + * c_write_val(self.trans, T_STRING, name) + * write_i08(self.trans, ttype) # <<<<<<<<<<<<<< + * + * write_i32(self.trans, seqid) +*/ + __pyx_t_2 = ((PyObject *)__pyx_v_self->trans); + __Pyx_INCREF(__pyx_t_2); + __pyx_t_3 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_write_i08(((struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *)__pyx_t_2), __pyx_v_ttype); if (unlikely(__pyx_t_3 == ((int)-1))) __PYX_ERR(0, 508, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } + __pyx_L3:; + + /* "thriftpy2/protocol/cybin/cybin.pyx":510 + * write_i08(self.trans, ttype) + * + * write_i32(self.trans, seqid) # <<<<<<<<<<<<<< + * + * def write_message_end(self): +*/ + __pyx_t_2 = ((PyObject *)__pyx_v_self->trans); + __Pyx_INCREF(__pyx_t_2); + __pyx_t_3 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_write_i32(((struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *)__pyx_t_2), __pyx_v_seqid); if (unlikely(__pyx_t_3 == ((int)-1))) __PYX_ERR(0, 510, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":501 + * pass + * + * def write_message_begin(self, name, TType ttype, int32_t seqid): # <<<<<<<<<<<<<< + * cdef int32_t version = VERSION_1 | ttype + * if self.strict_write: +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("thriftpy2.protocol.cybin.cybin.TCyBinaryProtocol.write_message_begin", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/protocol/cybin/cybin.pyx":512 + * write_i32(self.trans, seqid) + * + * def write_message_end(self): # <<<<<<<<<<<<<< + * pass + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_11write_message_end(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_11write_message_end = {"write_message_end", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_11write_message_end, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_11write_message_end(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("write_message_end (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("write_message_end", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("write_message_end", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_10write_message_end(((struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_10write_message_end(CYTHON_UNUSED struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("write_message_end", 0); + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/protocol/cybin/cybin.pyx":515 + * pass + * + * def read_struct(self, obj): # <<<<<<<<<<<<<< + * try: + * return read_struct(self.trans, obj, self.decode_response, +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_13read_struct(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_13read_struct = {"read_struct", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_13read_struct, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_13read_struct(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_obj = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("read_struct (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_obj,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 515, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 515, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "read_struct", 0) < (0)) __PYX_ERR(0, 515, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("read_struct", 1, 1, 1, i); __PYX_ERR(0, 515, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 515, __pyx_L3_error) + } + __pyx_v_obj = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("read_struct", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 515, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("thriftpy2.protocol.cybin.cybin.TCyBinaryProtocol.read_struct", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_12read_struct(((struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *)__pyx_v_self), __pyx_v_obj); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_12read_struct(struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *__pyx_v_self, PyObject *__pyx_v_obj) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + struct __pyx_opt_args_9thriftpy2_8protocol_5cybin_5cybin_read_struct __pyx_t_8; + int __pyx_t_9; + PyObject *__pyx_t_10 = NULL; + size_t __pyx_t_11; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("read_struct", 0); + + /* "thriftpy2/protocol/cybin/cybin.pyx":516 + * + * def read_struct(self, obj): + * try: # <<<<<<<<<<<<<< + * return read_struct(self.trans, obj, self.decode_response, + * self.strict_decode) +*/ + { + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + __Pyx_ExceptionSave(&__pyx_t_1, &__pyx_t_2, &__pyx_t_3); + __Pyx_XGOTREF(__pyx_t_1); + __Pyx_XGOTREF(__pyx_t_2); + __Pyx_XGOTREF(__pyx_t_3); + /*try:*/ { + + /* "thriftpy2/protocol/cybin/cybin.pyx":517 + * def read_struct(self, obj): + * try: + * return read_struct(self.trans, obj, self.decode_response, # <<<<<<<<<<<<<< + * self.strict_decode) + * except Exception: +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_4 = ((PyObject *)__pyx_v_self->trans); + __Pyx_INCREF(__pyx_t_4); + __pyx_t_5 = ((PyObject *)__pyx_v_self->decode_response); + __Pyx_INCREF(__pyx_t_5); + + /* "thriftpy2/protocol/cybin/cybin.pyx":518 + * try: + * return read_struct(self.trans, obj, self.decode_response, + * self.strict_decode) # <<<<<<<<<<<<<< + * except Exception: + * self.trans.clean() +*/ + __pyx_t_6 = ((PyObject *)__pyx_v_self->strict_decode); + __Pyx_INCREF(__pyx_t_6); + + /* "thriftpy2/protocol/cybin/cybin.pyx":517 + * def read_struct(self, obj): + * try: + * return read_struct(self.trans, obj, self.decode_response, # <<<<<<<<<<<<<< + * self.strict_decode) + * except Exception: +*/ + __pyx_t_8.__pyx_n = 2; + __pyx_t_8.decode_response = __pyx_t_5; + __pyx_t_8.strict_decode = __pyx_t_6; + __pyx_t_7 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_read_struct(((struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *)__pyx_t_4), __pyx_v_obj, &__pyx_t_8); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 517, __pyx_L3_error) + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_r = __pyx_t_7; + __pyx_t_7 = 0; + goto __pyx_L7_try_return; + + /* "thriftpy2/protocol/cybin/cybin.pyx":516 + * + * def read_struct(self, obj): + * try: # <<<<<<<<<<<<<< + * return read_struct(self.trans, obj, self.decode_response, + * self.strict_decode) +*/ + } + __pyx_L3_error:; + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":519 + * return read_struct(self.trans, obj, self.decode_response, + * self.strict_decode) + * except Exception: # <<<<<<<<<<<<<< + * self.trans.clean() + * raise +*/ + __pyx_t_9 = __Pyx_PyErr_ExceptionMatches(((PyObject *)(((PyTypeObject*)PyExc_Exception)))); + if (__pyx_t_9) { + __Pyx_AddTraceback("thriftpy2.protocol.cybin.cybin.TCyBinaryProtocol.read_struct", __pyx_clineno, __pyx_lineno, __pyx_filename); + if (__Pyx_GetException(&__pyx_t_7, &__pyx_t_6, &__pyx_t_5) < 0) __PYX_ERR(0, 519, __pyx_L5_except_error) + __Pyx_XGOTREF(__pyx_t_7); + __Pyx_XGOTREF(__pyx_t_6); + __Pyx_XGOTREF(__pyx_t_5); + + /* "thriftpy2/protocol/cybin/cybin.pyx":520 + * self.strict_decode) + * except Exception: + * self.trans.clean() # <<<<<<<<<<<<<< + * raise + * +*/ + __pyx_t_10 = ((PyObject *)__pyx_v_self->trans); + __Pyx_INCREF(__pyx_t_10); + __pyx_t_11 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_10, NULL}; + __pyx_t_4 = __Pyx_PyObject_FastCallMethod((PyObject*)__pyx_mstate_global->__pyx_n_u_clean, __pyx_callargs+__pyx_t_11, (1-__pyx_t_11) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_10); __pyx_t_10 = 0; + if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 520, __pyx_L5_except_error) + __Pyx_GOTREF(__pyx_t_4); + } + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":521 + * except Exception: + * self.trans.clean() + * raise # <<<<<<<<<<<<<< + * + * def write_struct(self, obj): +*/ + __Pyx_GIVEREF(__pyx_t_7); + __Pyx_GIVEREF(__pyx_t_6); + __Pyx_XGIVEREF(__pyx_t_5); + __Pyx_ErrRestoreWithState(__pyx_t_7, __pyx_t_6, __pyx_t_5); + __pyx_t_7 = 0; __pyx_t_6 = 0; __pyx_t_5 = 0; + __PYX_ERR(0, 521, __pyx_L5_except_error) + } + goto __pyx_L5_except_error; + + /* "thriftpy2/protocol/cybin/cybin.pyx":516 + * + * def read_struct(self, obj): + * try: # <<<<<<<<<<<<<< + * return read_struct(self.trans, obj, self.decode_response, + * self.strict_decode) +*/ + __pyx_L5_except_error:; + __Pyx_XGIVEREF(__pyx_t_1); + __Pyx_XGIVEREF(__pyx_t_2); + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_ExceptionReset(__pyx_t_1, __pyx_t_2, __pyx_t_3); + goto __pyx_L1_error; + __pyx_L7_try_return:; + __Pyx_XGIVEREF(__pyx_t_1); + __Pyx_XGIVEREF(__pyx_t_2); + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_ExceptionReset(__pyx_t_1, __pyx_t_2, __pyx_t_3); + goto __pyx_L0; + } + + /* "thriftpy2/protocol/cybin/cybin.pyx":515 + * pass + * + * def read_struct(self, obj): # <<<<<<<<<<<<<< + * try: + * return read_struct(self.trans, obj, self.decode_response, +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_10); + __Pyx_AddTraceback("thriftpy2.protocol.cybin.cybin.TCyBinaryProtocol.read_struct", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/protocol/cybin/cybin.pyx":523 + * raise + * + * def write_struct(self, obj): # <<<<<<<<<<<<<< + * try: + * write_struct(self.trans, obj) +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_15write_struct(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_15write_struct = {"write_struct", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_15write_struct, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_15write_struct(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_obj = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("write_struct (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_obj,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 523, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 523, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "write_struct", 0) < (0)) __PYX_ERR(0, 523, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("write_struct", 1, 1, 1, i); __PYX_ERR(0, 523, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 523, __pyx_L3_error) + } + __pyx_v_obj = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("write_struct", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 523, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("thriftpy2.protocol.cybin.cybin.TCyBinaryProtocol.write_struct", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_14write_struct(((struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *)__pyx_v_self), __pyx_v_obj); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_14write_struct(struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *__pyx_v_self, PyObject *__pyx_v_obj) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + int __pyx_t_6; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + PyObject *__pyx_t_9 = NULL; + size_t __pyx_t_10; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("write_struct", 0); + + /* "thriftpy2/protocol/cybin/cybin.pyx":524 + * + * def write_struct(self, obj): + * try: # <<<<<<<<<<<<<< + * write_struct(self.trans, obj) + * except Exception: +*/ + { + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + __Pyx_ExceptionSave(&__pyx_t_1, &__pyx_t_2, &__pyx_t_3); + __Pyx_XGOTREF(__pyx_t_1); + __Pyx_XGOTREF(__pyx_t_2); + __Pyx_XGOTREF(__pyx_t_3); + /*try:*/ { + + /* "thriftpy2/protocol/cybin/cybin.pyx":525 + * def write_struct(self, obj): + * try: + * write_struct(self.trans, obj) # <<<<<<<<<<<<<< + * except Exception: + * self.trans.clean() +*/ + __pyx_t_4 = ((PyObject *)__pyx_v_self->trans); + __Pyx_INCREF(__pyx_t_4); + __pyx_t_5 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin_write_struct(((struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *)__pyx_t_4), __pyx_v_obj); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 525, __pyx_L3_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":524 + * + * def write_struct(self, obj): + * try: # <<<<<<<<<<<<<< + * write_struct(self.trans, obj) + * except Exception: +*/ + } + __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + goto __pyx_L8_try_end; + __pyx_L3_error:; + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":526 + * try: + * write_struct(self.trans, obj) + * except Exception: # <<<<<<<<<<<<<< + * self.trans.clean() + * raise +*/ + __pyx_t_6 = __Pyx_PyErr_ExceptionMatches(((PyObject *)(((PyTypeObject*)PyExc_Exception)))); + if (__pyx_t_6) { + __Pyx_AddTraceback("thriftpy2.protocol.cybin.cybin.TCyBinaryProtocol.write_struct", __pyx_clineno, __pyx_lineno, __pyx_filename); + if (__Pyx_GetException(&__pyx_t_5, &__pyx_t_4, &__pyx_t_7) < 0) __PYX_ERR(0, 526, __pyx_L5_except_error) + __Pyx_XGOTREF(__pyx_t_5); + __Pyx_XGOTREF(__pyx_t_4); + __Pyx_XGOTREF(__pyx_t_7); + + /* "thriftpy2/protocol/cybin/cybin.pyx":527 + * write_struct(self.trans, obj) + * except Exception: + * self.trans.clean() # <<<<<<<<<<<<<< + * raise + * +*/ + __pyx_t_9 = ((PyObject *)__pyx_v_self->trans); + __Pyx_INCREF(__pyx_t_9); + __pyx_t_10 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_9, NULL}; + __pyx_t_8 = __Pyx_PyObject_FastCallMethod((PyObject*)__pyx_mstate_global->__pyx_n_u_clean, __pyx_callargs+__pyx_t_10, (1-__pyx_t_10) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; + if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 527, __pyx_L5_except_error) + __Pyx_GOTREF(__pyx_t_8); + } + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":528 + * except Exception: + * self.trans.clean() + * raise # <<<<<<<<<<<<<< + * + * +*/ + __Pyx_GIVEREF(__pyx_t_5); + __Pyx_GIVEREF(__pyx_t_4); + __Pyx_XGIVEREF(__pyx_t_7); + __Pyx_ErrRestoreWithState(__pyx_t_5, __pyx_t_4, __pyx_t_7); + __pyx_t_5 = 0; __pyx_t_4 = 0; __pyx_t_7 = 0; + __PYX_ERR(0, 528, __pyx_L5_except_error) + } + goto __pyx_L5_except_error; + + /* "thriftpy2/protocol/cybin/cybin.pyx":524 + * + * def write_struct(self, obj): + * try: # <<<<<<<<<<<<<< + * write_struct(self.trans, obj) + * except Exception: +*/ + __pyx_L5_except_error:; + __Pyx_XGIVEREF(__pyx_t_1); + __Pyx_XGIVEREF(__pyx_t_2); + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_ExceptionReset(__pyx_t_1, __pyx_t_2, __pyx_t_3); + goto __pyx_L1_error; + __pyx_L8_try_end:; + } + + /* "thriftpy2/protocol/cybin/cybin.pyx":523 + * raise + * + * def write_struct(self, obj): # <<<<<<<<<<<<<< + * try: + * write_struct(self.trans, obj) +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_AddTraceback("thriftpy2.protocol.cybin.cybin.TCyBinaryProtocol.write_struct", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/protocol/cybin/cybin.pyx":458 + * + * cdef class TCyBinaryProtocol(object): + * cdef public CyTransportBase trans # <<<<<<<<<<<<<< + * cdef public bool strict_read + * cdef public bool strict_write +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_5trans_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_5trans_1__get__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_5trans___get__(((struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_5trans___get__(struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__", 0); + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF((PyObject *)__pyx_v_self->trans); + __pyx_r = ((PyObject *)__pyx_v_self->trans); + goto __pyx_L0; + + /* function exit code */ + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static int __pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_5trans_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value); /*proto*/ +static int __pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_5trans_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__set__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_5trans_2__set__(((struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *)__pyx_v_self), ((PyObject *)__pyx_v_value)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_5trans_2__set__(struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *__pyx_v_self, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__set__", 0); + __pyx_t_1 = __pyx_v_value; + __Pyx_INCREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase))))) __PYX_ERR(0, 458, __pyx_L1_error) + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF((PyObject *)__pyx_v_self->trans); + __Pyx_DECREF((PyObject *)__pyx_v_self->trans); + __pyx_v_self->trans = ((struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *)__pyx_t_1); + __pyx_t_1 = 0; + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("thriftpy2.protocol.cybin.cybin.TCyBinaryProtocol.trans.__set__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static int __pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_5trans_5__del__(PyObject *__pyx_v_self); /*proto*/ +static int __pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_5trans_5__del__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__del__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_5trans_4__del__(((struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_5trans_4__del__(struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *__pyx_v_self) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__del__", 0); + __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(Py_None); + __Pyx_GOTREF((PyObject *)__pyx_v_self->trans); + __Pyx_DECREF((PyObject *)__pyx_v_self->trans); + __pyx_v_self->trans = ((struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *)Py_None); + + /* function exit code */ + __pyx_r = 0; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/protocol/cybin/cybin.pyx":459 + * cdef class TCyBinaryProtocol(object): + * cdef public CyTransportBase trans + * cdef public bool strict_read # <<<<<<<<<<<<<< + * cdef public bool strict_write + * cdef public bool decode_response +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_11strict_read_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_11strict_read_1__get__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_11strict_read___get__(((struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_11strict_read___get__(struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__", 0); + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF((PyObject *)__pyx_v_self->strict_read); + __pyx_r = ((PyObject *)__pyx_v_self->strict_read); + goto __pyx_L0; + + /* function exit code */ + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static int __pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_11strict_read_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value); /*proto*/ +static int __pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_11strict_read_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__set__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_11strict_read_2__set__(((struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *)__pyx_v_self), ((PyObject *)__pyx_v_value)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_11strict_read_2__set__(struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *__pyx_v_self, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__set__", 0); + __pyx_t_1 = __pyx_v_value; + __Pyx_INCREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_mstate_global->__pyx_ptype_7cpython_4bool_bool))))) __PYX_ERR(0, 459, __pyx_L1_error) + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF((PyObject *)__pyx_v_self->strict_read); + __Pyx_DECREF((PyObject *)__pyx_v_self->strict_read); + __pyx_v_self->strict_read = ((PyLongObject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("thriftpy2.protocol.cybin.cybin.TCyBinaryProtocol.strict_read.__set__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static int __pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_11strict_read_5__del__(PyObject *__pyx_v_self); /*proto*/ +static int __pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_11strict_read_5__del__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__del__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_11strict_read_4__del__(((struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_11strict_read_4__del__(struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *__pyx_v_self) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__del__", 0); + __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(Py_None); + __Pyx_GOTREF((PyObject *)__pyx_v_self->strict_read); + __Pyx_DECREF((PyObject *)__pyx_v_self->strict_read); + __pyx_v_self->strict_read = ((PyLongObject *)Py_None); + + /* function exit code */ + __pyx_r = 0; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/protocol/cybin/cybin.pyx":460 + * cdef public CyTransportBase trans + * cdef public bool strict_read + * cdef public bool strict_write # <<<<<<<<<<<<<< + * cdef public bool decode_response + * cdef public bool strict_decode +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_12strict_write_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_12strict_write_1__get__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_12strict_write___get__(((struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_12strict_write___get__(struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__", 0); + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF((PyObject *)__pyx_v_self->strict_write); + __pyx_r = ((PyObject *)__pyx_v_self->strict_write); + goto __pyx_L0; + + /* function exit code */ + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static int __pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_12strict_write_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value); /*proto*/ +static int __pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_12strict_write_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__set__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_12strict_write_2__set__(((struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *)__pyx_v_self), ((PyObject *)__pyx_v_value)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_12strict_write_2__set__(struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *__pyx_v_self, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__set__", 0); + __pyx_t_1 = __pyx_v_value; + __Pyx_INCREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_mstate_global->__pyx_ptype_7cpython_4bool_bool))))) __PYX_ERR(0, 460, __pyx_L1_error) + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF((PyObject *)__pyx_v_self->strict_write); + __Pyx_DECREF((PyObject *)__pyx_v_self->strict_write); + __pyx_v_self->strict_write = ((PyLongObject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("thriftpy2.protocol.cybin.cybin.TCyBinaryProtocol.strict_write.__set__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static int __pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_12strict_write_5__del__(PyObject *__pyx_v_self); /*proto*/ +static int __pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_12strict_write_5__del__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__del__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_12strict_write_4__del__(((struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_12strict_write_4__del__(struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *__pyx_v_self) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__del__", 0); + __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(Py_None); + __Pyx_GOTREF((PyObject *)__pyx_v_self->strict_write); + __Pyx_DECREF((PyObject *)__pyx_v_self->strict_write); + __pyx_v_self->strict_write = ((PyLongObject *)Py_None); + + /* function exit code */ + __pyx_r = 0; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/protocol/cybin/cybin.pyx":461 + * cdef public bool strict_read + * cdef public bool strict_write + * cdef public bool decode_response # <<<<<<<<<<<<<< + * cdef public bool strict_decode + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_15decode_response_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_15decode_response_1__get__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_15decode_response___get__(((struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_15decode_response___get__(struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__", 0); + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF((PyObject *)__pyx_v_self->decode_response); + __pyx_r = ((PyObject *)__pyx_v_self->decode_response); + goto __pyx_L0; + + /* function exit code */ + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static int __pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_15decode_response_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value); /*proto*/ +static int __pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_15decode_response_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__set__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_15decode_response_2__set__(((struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *)__pyx_v_self), ((PyObject *)__pyx_v_value)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_15decode_response_2__set__(struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *__pyx_v_self, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__set__", 0); + __pyx_t_1 = __pyx_v_value; + __Pyx_INCREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_mstate_global->__pyx_ptype_7cpython_4bool_bool))))) __PYX_ERR(0, 461, __pyx_L1_error) + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF((PyObject *)__pyx_v_self->decode_response); + __Pyx_DECREF((PyObject *)__pyx_v_self->decode_response); + __pyx_v_self->decode_response = ((PyLongObject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("thriftpy2.protocol.cybin.cybin.TCyBinaryProtocol.decode_response.__set__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static int __pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_15decode_response_5__del__(PyObject *__pyx_v_self); /*proto*/ +static int __pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_15decode_response_5__del__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__del__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_15decode_response_4__del__(((struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_15decode_response_4__del__(struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *__pyx_v_self) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__del__", 0); + __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(Py_None); + __Pyx_GOTREF((PyObject *)__pyx_v_self->decode_response); + __Pyx_DECREF((PyObject *)__pyx_v_self->decode_response); + __pyx_v_self->decode_response = ((PyLongObject *)Py_None); + + /* function exit code */ + __pyx_r = 0; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/protocol/cybin/cybin.pyx":462 + * cdef public bool strict_write + * cdef public bool decode_response + * cdef public bool strict_decode # <<<<<<<<<<<<<< + * + * def __init__(self, trans, strict_read=True, strict_write=True, +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_13strict_decode_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_13strict_decode_1__get__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_13strict_decode___get__(((struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_13strict_decode___get__(struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__", 0); + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF((PyObject *)__pyx_v_self->strict_decode); + __pyx_r = ((PyObject *)__pyx_v_self->strict_decode); + goto __pyx_L0; + + /* function exit code */ + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static int __pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_13strict_decode_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value); /*proto*/ +static int __pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_13strict_decode_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__set__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_13strict_decode_2__set__(((struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *)__pyx_v_self), ((PyObject *)__pyx_v_value)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_13strict_decode_2__set__(struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *__pyx_v_self, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__set__", 0); + __pyx_t_1 = __pyx_v_value; + __Pyx_INCREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_mstate_global->__pyx_ptype_7cpython_4bool_bool))))) __PYX_ERR(0, 462, __pyx_L1_error) + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF((PyObject *)__pyx_v_self->strict_decode); + __Pyx_DECREF((PyObject *)__pyx_v_self->strict_decode); + __pyx_v_self->strict_decode = ((PyLongObject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("thriftpy2.protocol.cybin.cybin.TCyBinaryProtocol.strict_decode.__set__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static int __pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_13strict_decode_5__del__(PyObject *__pyx_v_self); /*proto*/ +static int __pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_13strict_decode_5__del__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__del__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_13strict_decode_4__del__(((struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_13strict_decode_4__del__(struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *__pyx_v_self) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__del__", 0); + __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(Py_None); + __Pyx_GOTREF((PyObject *)__pyx_v_self->strict_decode); + __Pyx_DECREF((PyObject *)__pyx_v_self->strict_decode); + __pyx_v_self->strict_decode = ((PyLongObject *)Py_None); + + /* function exit code */ + __pyx_r = 0; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * cdef tuple state + * cdef object _dict +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_17__reduce_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_17__reduce_cython__ = {"__reduce_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_17__reduce_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_17__reduce_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("__reduce_cython__", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("__reduce_cython__", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_16__reduce_cython__(((struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_16__reduce_cython__(struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *__pyx_v_self) { + PyObject *__pyx_v_state = 0; + PyObject *__pyx_v__dict = 0; + int __pyx_v_use_setstate; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__reduce_cython__", 0); + + /* "(tree fragment)":5 + * cdef object _dict + * cdef bint use_setstate + * state = (self.decode_response, self.strict_decode, self.strict_read, self.strict_write, self.trans) # <<<<<<<<<<<<<< + * _dict = getattr(self, '__dict__', None) + * if _dict is not None and _dict: +*/ + __pyx_t_1 = PyTuple_New(5); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 5, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF((PyObject *)__pyx_v_self->decode_response); + __Pyx_GIVEREF((PyObject *)__pyx_v_self->decode_response); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_v_self->decode_response)) != (0)) __PYX_ERR(2, 5, __pyx_L1_error); + __Pyx_INCREF((PyObject *)__pyx_v_self->strict_decode); + __Pyx_GIVEREF((PyObject *)__pyx_v_self->strict_decode); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 1, ((PyObject *)__pyx_v_self->strict_decode)) != (0)) __PYX_ERR(2, 5, __pyx_L1_error); + __Pyx_INCREF((PyObject *)__pyx_v_self->strict_read); + __Pyx_GIVEREF((PyObject *)__pyx_v_self->strict_read); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 2, ((PyObject *)__pyx_v_self->strict_read)) != (0)) __PYX_ERR(2, 5, __pyx_L1_error); + __Pyx_INCREF((PyObject *)__pyx_v_self->strict_write); + __Pyx_GIVEREF((PyObject *)__pyx_v_self->strict_write); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 3, ((PyObject *)__pyx_v_self->strict_write)) != (0)) __PYX_ERR(2, 5, __pyx_L1_error); + __Pyx_INCREF((PyObject *)__pyx_v_self->trans); + __Pyx_GIVEREF((PyObject *)__pyx_v_self->trans); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 4, ((PyObject *)__pyx_v_self->trans)) != (0)) __PYX_ERR(2, 5, __pyx_L1_error); + __pyx_v_state = ((PyObject*)__pyx_t_1); + __pyx_t_1 = 0; + + /* "(tree fragment)":6 + * cdef bint use_setstate + * state = (self.decode_response, self.strict_decode, self.strict_read, self.strict_write, self.trans) + * _dict = getattr(self, '__dict__', None) # <<<<<<<<<<<<<< + * if _dict is not None and _dict: + * state += (_dict,) +*/ + __pyx_t_1 = __Pyx_GetAttr3(((PyObject *)__pyx_v_self), __pyx_mstate_global->__pyx_n_u_dict, Py_None); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 6, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v__dict = __pyx_t_1; + __pyx_t_1 = 0; + + /* "(tree fragment)":7 + * state = (self.decode_response, self.strict_decode, self.strict_read, self.strict_write, self.trans) + * _dict = getattr(self, '__dict__', None) + * if _dict is not None and _dict: # <<<<<<<<<<<<<< + * state += (_dict,) + * use_setstate = True +*/ + __pyx_t_3 = (__pyx_v__dict != Py_None); + if (__pyx_t_3) { + } else { + __pyx_t_2 = __pyx_t_3; + goto __pyx_L4_bool_binop_done; + } + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_v__dict); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(2, 7, __pyx_L1_error) + __pyx_t_2 = __pyx_t_3; + __pyx_L4_bool_binop_done:; + if (__pyx_t_2) { + + /* "(tree fragment)":8 + * _dict = getattr(self, '__dict__', None) + * if _dict is not None and _dict: + * state += (_dict,) # <<<<<<<<<<<<<< + * use_setstate = True + * else: +*/ + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 8, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_v__dict); + __Pyx_GIVEREF(__pyx_v__dict); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v__dict) != (0)) __PYX_ERR(2, 8, __pyx_L1_error); + __pyx_t_4 = PyNumber_InPlaceAdd(__pyx_v_state, __pyx_t_1); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 8, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF_SET(__pyx_v_state, ((PyObject*)__pyx_t_4)); + __pyx_t_4 = 0; + + /* "(tree fragment)":9 + * if _dict is not None and _dict: + * state += (_dict,) + * use_setstate = True # <<<<<<<<<<<<<< + * else: + * use_setstate = self.decode_response is not None or self.strict_decode is not None or self.strict_read is not None or self.strict_write is not None or self.trans is not None +*/ + __pyx_v_use_setstate = 1; + + /* "(tree fragment)":7 + * state = (self.decode_response, self.strict_decode, self.strict_read, self.strict_write, self.trans) + * _dict = getattr(self, '__dict__', None) + * if _dict is not None and _dict: # <<<<<<<<<<<<<< + * state += (_dict,) + * use_setstate = True +*/ + goto __pyx_L3; + } + + /* "(tree fragment)":11 + * use_setstate = True + * else: + * use_setstate = self.decode_response is not None or self.strict_decode is not None or self.strict_read is not None or self.strict_write is not None or self.trans is not None # <<<<<<<<<<<<<< + * if use_setstate: + * return __pyx_unpickle_TCyBinaryProtocol, (type(self), 0xf5434e1, None), state +*/ + /*else*/ { + __pyx_t_3 = (((PyObject *)__pyx_v_self->decode_response) != Py_None); + if (!__pyx_t_3) { + } else { + __pyx_t_2 = __pyx_t_3; + goto __pyx_L6_bool_binop_done; + } + __pyx_t_3 = (((PyObject *)__pyx_v_self->strict_decode) != Py_None); + if (!__pyx_t_3) { + } else { + __pyx_t_2 = __pyx_t_3; + goto __pyx_L6_bool_binop_done; + } + __pyx_t_3 = (((PyObject *)__pyx_v_self->strict_read) != Py_None); + if (!__pyx_t_3) { + } else { + __pyx_t_2 = __pyx_t_3; + goto __pyx_L6_bool_binop_done; + } + __pyx_t_3 = (((PyObject *)__pyx_v_self->strict_write) != Py_None); + if (!__pyx_t_3) { + } else { + __pyx_t_2 = __pyx_t_3; + goto __pyx_L6_bool_binop_done; + } + __pyx_t_3 = (((PyObject *)__pyx_v_self->trans) != Py_None); + __pyx_t_2 = __pyx_t_3; + __pyx_L6_bool_binop_done:; + __pyx_v_use_setstate = __pyx_t_2; + } + __pyx_L3:; + + /* "(tree fragment)":12 + * else: + * use_setstate = self.decode_response is not None or self.strict_decode is not None or self.strict_read is not None or self.strict_write is not None or self.trans is not None + * if use_setstate: # <<<<<<<<<<<<<< + * return __pyx_unpickle_TCyBinaryProtocol, (type(self), 0xf5434e1, None), state + * else: +*/ + if (__pyx_v_use_setstate) { + + /* "(tree fragment)":13 + * use_setstate = self.decode_response is not None or self.strict_decode is not None or self.strict_read is not None or self.strict_write is not None or self.trans is not None + * if use_setstate: + * return __pyx_unpickle_TCyBinaryProtocol, (type(self), 0xf5434e1, None), state # <<<<<<<<<<<<<< + * else: + * return __pyx_unpickle_TCyBinaryProtocol, (type(self), 0xf5434e1, state) +*/ + __Pyx_XDECREF(__pyx_r); + __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_mstate_global->__pyx_n_u_pyx_unpickle_TCyBinaryProtocol); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 13, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_1 = PyTuple_New(3); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 13, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); + __Pyx_GIVEREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))) != (0)) __PYX_ERR(2, 13, __pyx_L1_error); + __Pyx_INCREF(__pyx_mstate_global->__pyx_int_257176801); + __Pyx_GIVEREF(__pyx_mstate_global->__pyx_int_257176801); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_mstate_global->__pyx_int_257176801) != (0)) __PYX_ERR(2, 13, __pyx_L1_error); + __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(Py_None); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 2, Py_None) != (0)) __PYX_ERR(2, 13, __pyx_L1_error); + __pyx_t_5 = PyTuple_New(3); if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 13, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_GIVEREF(__pyx_t_4); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4) != (0)) __PYX_ERR(2, 13, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_1); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_1) != (0)) __PYX_ERR(2, 13, __pyx_L1_error); + __Pyx_INCREF(__pyx_v_state); + __Pyx_GIVEREF(__pyx_v_state); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_5, 2, __pyx_v_state) != (0)) __PYX_ERR(2, 13, __pyx_L1_error); + __pyx_t_4 = 0; + __pyx_t_1 = 0; + __pyx_r = __pyx_t_5; + __pyx_t_5 = 0; + goto __pyx_L0; + + /* "(tree fragment)":12 + * else: + * use_setstate = self.decode_response is not None or self.strict_decode is not None or self.strict_read is not None or self.strict_write is not None or self.trans is not None + * if use_setstate: # <<<<<<<<<<<<<< + * return __pyx_unpickle_TCyBinaryProtocol, (type(self), 0xf5434e1, None), state + * else: +*/ + } + + /* "(tree fragment)":15 + * return __pyx_unpickle_TCyBinaryProtocol, (type(self), 0xf5434e1, None), state + * else: + * return __pyx_unpickle_TCyBinaryProtocol, (type(self), 0xf5434e1, state) # <<<<<<<<<<<<<< + * def __setstate_cython__(self, __pyx_state): + * __pyx_unpickle_TCyBinaryProtocol__set_state(self, __pyx_state) +*/ + /*else*/ { + __Pyx_XDECREF(__pyx_r); + __Pyx_GetModuleGlobalName(__pyx_t_5, __pyx_mstate_global->__pyx_n_u_pyx_unpickle_TCyBinaryProtocol); if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 15, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_1 = PyTuple_New(3); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 15, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); + __Pyx_GIVEREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))) != (0)) __PYX_ERR(2, 15, __pyx_L1_error); + __Pyx_INCREF(__pyx_mstate_global->__pyx_int_257176801); + __Pyx_GIVEREF(__pyx_mstate_global->__pyx_int_257176801); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_mstate_global->__pyx_int_257176801) != (0)) __PYX_ERR(2, 15, __pyx_L1_error); + __Pyx_INCREF(__pyx_v_state); + __Pyx_GIVEREF(__pyx_v_state); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 2, __pyx_v_state) != (0)) __PYX_ERR(2, 15, __pyx_L1_error); + __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 15, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_GIVEREF(__pyx_t_5); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_5) != (0)) __PYX_ERR(2, 15, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_1); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_1) != (0)) __PYX_ERR(2, 15, __pyx_L1_error); + __pyx_t_5 = 0; + __pyx_t_1 = 0; + __pyx_r = __pyx_t_4; + __pyx_t_4 = 0; + goto __pyx_L0; + } + + /* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * cdef tuple state + * cdef object _dict +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("thriftpy2.protocol.cybin.cybin.TCyBinaryProtocol.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_state); + __Pyx_XDECREF(__pyx_v__dict); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":16 + * else: + * return __pyx_unpickle_TCyBinaryProtocol, (type(self), 0xf5434e1, state) + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * __pyx_unpickle_TCyBinaryProtocol__set_state(self, __pyx_state) +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_19__setstate_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_19__setstate_cython__ = {"__setstate_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_19__setstate_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_19__setstate_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v___pyx_state = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_pyx_state,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(2, 16, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(2, 16, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "__setstate_cython__", 0) < (0)) __PYX_ERR(2, 16, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("__setstate_cython__", 1, 1, 1, i); __PYX_ERR(2, 16, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(2, 16, __pyx_L3_error) + } + __pyx_v___pyx_state = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__setstate_cython__", 1, 1, 1, __pyx_nargs); __PYX_ERR(2, 16, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("thriftpy2.protocol.cybin.cybin.TCyBinaryProtocol.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_18__setstate_cython__(((struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *)__pyx_v_self), __pyx_v___pyx_state); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_18__setstate_cython__(struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *__pyx_v_self, PyObject *__pyx_v___pyx_state) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__setstate_cython__", 0); + + /* "(tree fragment)":17 + * return __pyx_unpickle_TCyBinaryProtocol, (type(self), 0xf5434e1, state) + * def __setstate_cython__(self, __pyx_state): + * __pyx_unpickle_TCyBinaryProtocol__set_state(self, __pyx_state) # <<<<<<<<<<<<<< +*/ + __pyx_t_1 = __pyx_v___pyx_state; + __Pyx_INCREF(__pyx_t_1); + if (!(likely(PyTuple_CheckExact(__pyx_t_1))||((__pyx_t_1) == Py_None) || __Pyx_RaiseUnexpectedTypeError("tuple", __pyx_t_1))) __PYX_ERR(2, 17, __pyx_L1_error) + if (unlikely(__pyx_t_1 == Py_None)) { + PyErr_SetString(PyExc_TypeError, "cannot pass None into a C function argument that is declared 'not None'"); + __PYX_ERR(2, 17, __pyx_L1_error) + } + __pyx_t_2 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin___pyx_unpickle_TCyBinaryProtocol__set_state(__pyx_v_self, ((PyObject*)__pyx_t_1)); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 17, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "(tree fragment)":16 + * else: + * return __pyx_unpickle_TCyBinaryProtocol, (type(self), 0xf5434e1, state) + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * __pyx_unpickle_TCyBinaryProtocol__set_state(self, __pyx_state) +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("thriftpy2.protocol.cybin.cybin.TCyBinaryProtocol.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/protocol/cybin/cybin.pyx":532 + * + * class TCyBinaryProtocolFactory(object): + * def __init__(self, strict_read=True, strict_write=True, # <<<<<<<<<<<<<< + * decode_response=True, strict_decode=False): + * self.strict_read = strict_read +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_24TCyBinaryProtocolFactory_1__init__(PyObject *__pyx_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_8protocol_5cybin_5cybin_24TCyBinaryProtocolFactory_1__init__ = {"__init__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_24TCyBinaryProtocolFactory_1__init__, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_24TCyBinaryProtocolFactory_1__init__(PyObject *__pyx_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_self = 0; + PyObject *__pyx_v_strict_read = 0; + PyObject *__pyx_v_strict_write = 0; + PyObject *__pyx_v_decode_response = 0; + PyObject *__pyx_v_strict_decode = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[5] = {0,0,0,0,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_self,&__pyx_mstate_global->__pyx_n_u_strict_read,&__pyx_mstate_global->__pyx_n_u_strict_write,&__pyx_mstate_global->__pyx_n_u_decode_response,&__pyx_mstate_global->__pyx_n_u_strict_decode,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 532, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 5: + values[4] = __Pyx_ArgRef_FASTCALL(__pyx_args, 4); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[4])) __PYX_ERR(0, 532, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 4: + values[3] = __Pyx_ArgRef_FASTCALL(__pyx_args, 3); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[3])) __PYX_ERR(0, 532, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 3: + values[2] = __Pyx_ArgRef_FASTCALL(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(0, 532, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 2: + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 532, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 532, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "__init__", 0) < (0)) __PYX_ERR(0, 532, __pyx_L3_error) + if (!values[1]) values[1] = __Pyx_NewRef(((PyObject *)((PyObject*)Py_True))); + if (!values[2]) values[2] = __Pyx_NewRef(((PyObject *)((PyObject*)Py_True))); + + /* "thriftpy2/protocol/cybin/cybin.pyx":533 + * class TCyBinaryProtocolFactory(object): + * def __init__(self, strict_read=True, strict_write=True, + * decode_response=True, strict_decode=False): # <<<<<<<<<<<<<< + * self.strict_read = strict_read + * self.strict_write = strict_write +*/ + if (!values[3]) values[3] = __Pyx_NewRef(((PyObject *)((PyObject*)Py_True))); + if (!values[4]) values[4] = __Pyx_NewRef(((PyObject *)((PyObject*)Py_False))); + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("__init__", 0, 1, 5, i); __PYX_ERR(0, 532, __pyx_L3_error) } + } + } else { + switch (__pyx_nargs) { + case 5: + values[4] = __Pyx_ArgRef_FASTCALL(__pyx_args, 4); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[4])) __PYX_ERR(0, 532, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 4: + values[3] = __Pyx_ArgRef_FASTCALL(__pyx_args, 3); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[3])) __PYX_ERR(0, 532, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 3: + values[2] = __Pyx_ArgRef_FASTCALL(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(0, 532, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 2: + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 532, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 532, __pyx_L3_error) + break; + default: goto __pyx_L5_argtuple_error; + } + if (!values[1]) values[1] = __Pyx_NewRef(((PyObject *)((PyObject*)Py_True))); + if (!values[2]) values[2] = __Pyx_NewRef(((PyObject *)((PyObject*)Py_True))); + if (!values[3]) values[3] = __Pyx_NewRef(((PyObject *)((PyObject*)Py_True))); + if (!values[4]) values[4] = __Pyx_NewRef(((PyObject *)((PyObject*)Py_False))); + } + __pyx_v_self = values[0]; + __pyx_v_strict_read = values[1]; + __pyx_v_strict_write = values[2]; + __pyx_v_decode_response = values[3]; + __pyx_v_strict_decode = values[4]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__init__", 0, 1, 5, __pyx_nargs); __PYX_ERR(0, 532, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("thriftpy2.protocol.cybin.cybin.TCyBinaryProtocolFactory.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_24TCyBinaryProtocolFactory___init__(__pyx_self, __pyx_v_self, __pyx_v_strict_read, __pyx_v_strict_write, __pyx_v_decode_response, __pyx_v_strict_decode); + + /* "thriftpy2/protocol/cybin/cybin.pyx":532 + * + * class TCyBinaryProtocolFactory(object): + * def __init__(self, strict_read=True, strict_write=True, # <<<<<<<<<<<<<< + * decode_response=True, strict_decode=False): + * self.strict_read = strict_read +*/ + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_24TCyBinaryProtocolFactory___init__(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_self, PyObject *__pyx_v_strict_read, PyObject *__pyx_v_strict_write, PyObject *__pyx_v_decode_response, PyObject *__pyx_v_strict_decode) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__init__", 0); + + /* "thriftpy2/protocol/cybin/cybin.pyx":534 + * def __init__(self, strict_read=True, strict_write=True, + * decode_response=True, strict_decode=False): + * self.strict_read = strict_read # <<<<<<<<<<<<<< + * self.strict_write = strict_write + * self.decode_response = decode_response +*/ + if (__Pyx_PyObject_SetAttrStr(__pyx_v_self, __pyx_mstate_global->__pyx_n_u_strict_read, __pyx_v_strict_read) < (0)) __PYX_ERR(0, 534, __pyx_L1_error) + + /* "thriftpy2/protocol/cybin/cybin.pyx":535 + * decode_response=True, strict_decode=False): + * self.strict_read = strict_read + * self.strict_write = strict_write # <<<<<<<<<<<<<< + * self.decode_response = decode_response + * self.strict_decode = strict_decode +*/ + if (__Pyx_PyObject_SetAttrStr(__pyx_v_self, __pyx_mstate_global->__pyx_n_u_strict_write, __pyx_v_strict_write) < (0)) __PYX_ERR(0, 535, __pyx_L1_error) + + /* "thriftpy2/protocol/cybin/cybin.pyx":536 + * self.strict_read = strict_read + * self.strict_write = strict_write + * self.decode_response = decode_response # <<<<<<<<<<<<<< + * self.strict_decode = strict_decode + * +*/ + if (__Pyx_PyObject_SetAttrStr(__pyx_v_self, __pyx_mstate_global->__pyx_n_u_decode_response, __pyx_v_decode_response) < (0)) __PYX_ERR(0, 536, __pyx_L1_error) + + /* "thriftpy2/protocol/cybin/cybin.pyx":537 + * self.strict_write = strict_write + * self.decode_response = decode_response + * self.strict_decode = strict_decode # <<<<<<<<<<<<<< + * + * def get_protocol(self, trans): +*/ + if (__Pyx_PyObject_SetAttrStr(__pyx_v_self, __pyx_mstate_global->__pyx_n_u_strict_decode, __pyx_v_strict_decode) < (0)) __PYX_ERR(0, 537, __pyx_L1_error) + + /* "thriftpy2/protocol/cybin/cybin.pyx":532 + * + * class TCyBinaryProtocolFactory(object): + * def __init__(self, strict_read=True, strict_write=True, # <<<<<<<<<<<<<< + * decode_response=True, strict_decode=False): + * self.strict_read = strict_read +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_AddTraceback("thriftpy2.protocol.cybin.cybin.TCyBinaryProtocolFactory.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/protocol/cybin/cybin.pyx":539 + * self.strict_decode = strict_decode + * + * def get_protocol(self, trans): # <<<<<<<<<<<<<< + * return TCyBinaryProtocol( + * trans, self.strict_read, self.strict_write, self.decode_response, +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_24TCyBinaryProtocolFactory_3get_protocol(PyObject *__pyx_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_8protocol_5cybin_5cybin_24TCyBinaryProtocolFactory_3get_protocol = {"get_protocol", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_24TCyBinaryProtocolFactory_3get_protocol, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_24TCyBinaryProtocolFactory_3get_protocol(PyObject *__pyx_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_self = 0; + PyObject *__pyx_v_trans = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[2] = {0,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("get_protocol (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_self,&__pyx_mstate_global->__pyx_n_u_trans,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 539, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 2: + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 539, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 539, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "get_protocol", 0) < (0)) __PYX_ERR(0, 539, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 2; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("get_protocol", 1, 2, 2, i); __PYX_ERR(0, 539, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 2)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 539, __pyx_L3_error) + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 539, __pyx_L3_error) + } + __pyx_v_self = values[0]; + __pyx_v_trans = values[1]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("get_protocol", 1, 2, 2, __pyx_nargs); __PYX_ERR(0, 539, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("thriftpy2.protocol.cybin.cybin.TCyBinaryProtocolFactory.get_protocol", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_24TCyBinaryProtocolFactory_2get_protocol(__pyx_self, __pyx_v_self, __pyx_v_trans); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_24TCyBinaryProtocolFactory_2get_protocol(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_self, PyObject *__pyx_v_trans) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + size_t __pyx_t_7; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("get_protocol", 0); + + /* "thriftpy2/protocol/cybin/cybin.pyx":540 + * + * def get_protocol(self, trans): + * return TCyBinaryProtocol( # <<<<<<<<<<<<<< + * trans, self.strict_read, self.strict_write, self.decode_response, + * self.strict_decode) +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = NULL; + + /* "thriftpy2/protocol/cybin/cybin.pyx":541 + * def get_protocol(self, trans): + * return TCyBinaryProtocol( + * trans, self.strict_read, self.strict_write, self.decode_response, # <<<<<<<<<<<<<< + * self.strict_decode) +*/ + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_mstate_global->__pyx_n_u_strict_read); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 541, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_mstate_global->__pyx_n_u_strict_write); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 541, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_mstate_global->__pyx_n_u_decode_response); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 541, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + + /* "thriftpy2/protocol/cybin/cybin.pyx":542 + * return TCyBinaryProtocol( + * trans, self.strict_read, self.strict_write, self.decode_response, + * self.strict_decode) # <<<<<<<<<<<<<< +*/ + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_mstate_global->__pyx_n_u_strict_decode); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 542, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = 1; + { + PyObject *__pyx_callargs[6] = {__pyx_t_2, __pyx_v_trans, __pyx_t_3, __pyx_t_4, __pyx_t_5, __pyx_t_6}; + __pyx_t_1 = __Pyx_PyObject_FastCall((PyObject*)__pyx_mstate_global->__pyx_ptype_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol, __pyx_callargs+__pyx_t_7, (6-__pyx_t_7) | (__pyx_t_7*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 540, __pyx_L1_error) + __Pyx_GOTREF((PyObject *)__pyx_t_1); + } + __pyx_r = ((PyObject *)__pyx_t_1); + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":539 + * self.strict_decode = strict_decode + * + * def get_protocol(self, trans): # <<<<<<<<<<<<<< + * return TCyBinaryProtocol( + * trans, self.strict_read, self.strict_write, self.decode_response, +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_AddTraceback("thriftpy2.protocol.cybin.cybin.TCyBinaryProtocolFactory.get_protocol", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":4 + * int __Pyx_CheckUnpickleChecksum(long, long, long, long, const char*) except -1 + * int __Pyx_UpdateUnpickledDict(object, object, Py_ssize_t) except -1 + * def __pyx_unpickle_TCyBinaryProtocol(__pyx_type, long __pyx_checksum, tuple __pyx_state): # <<<<<<<<<<<<<< + * cdef object __pyx_result + * __Pyx_CheckUnpickleChecksum(__pyx_checksum, 0xf5434e1, 0xee67e8e, 0x44df354, b'decode_response, strict_decode, strict_read, strict_write, trans') +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_7__pyx_unpickle_TCyBinaryProtocol(PyObject *__pyx_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_8protocol_5cybin_5cybin_7__pyx_unpickle_TCyBinaryProtocol = {"__pyx_unpickle_TCyBinaryProtocol", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_7__pyx_unpickle_TCyBinaryProtocol, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_7__pyx_unpickle_TCyBinaryProtocol(PyObject *__pyx_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v___pyx_type = 0; + long __pyx_v___pyx_checksum; + PyObject *__pyx_v___pyx_state = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[3] = {0,0,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__pyx_unpickle_TCyBinaryProtocol (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_pyx_type,&__pyx_mstate_global->__pyx_n_u_pyx_checksum,&__pyx_mstate_global->__pyx_n_u_pyx_state,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(2, 4, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 3: + values[2] = __Pyx_ArgRef_FASTCALL(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(2, 4, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 2: + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(2, 4, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(2, 4, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "__pyx_unpickle_TCyBinaryProtocol", 0) < (0)) __PYX_ERR(2, 4, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 3; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("__pyx_unpickle_TCyBinaryProtocol", 1, 3, 3, i); __PYX_ERR(2, 4, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 3)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(2, 4, __pyx_L3_error) + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(2, 4, __pyx_L3_error) + values[2] = __Pyx_ArgRef_FASTCALL(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(2, 4, __pyx_L3_error) + } + __pyx_v___pyx_type = values[0]; + __pyx_v___pyx_checksum = __Pyx_PyLong_As_long(values[1]); if (unlikely((__pyx_v___pyx_checksum == (long)-1) && PyErr_Occurred())) __PYX_ERR(2, 4, __pyx_L3_error) + __pyx_v___pyx_state = ((PyObject*)values[2]); + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__pyx_unpickle_TCyBinaryProtocol", 1, 3, 3, __pyx_nargs); __PYX_ERR(2, 4, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("thriftpy2.protocol.cybin.cybin.__pyx_unpickle_TCyBinaryProtocol", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v___pyx_state), (&PyTuple_Type), 1, "__pyx_state", 1))) __PYX_ERR(2, 4, __pyx_L1_error) + __pyx_r = __pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_6__pyx_unpickle_TCyBinaryProtocol(__pyx_self, __pyx_v___pyx_type, __pyx_v___pyx_checksum, __pyx_v___pyx_state); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + goto __pyx_L7_cleaned_up; + __pyx_L0:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __pyx_L7_cleaned_up:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_8protocol_5cybin_5cybin_6__pyx_unpickle_TCyBinaryProtocol(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v___pyx_type, long __pyx_v___pyx_checksum, PyObject *__pyx_v___pyx_state) { + PyObject *__pyx_v___pyx_result = 0; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + size_t __pyx_t_4; + int __pyx_t_5; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__pyx_unpickle_TCyBinaryProtocol", 0); + + /* "(tree fragment)":6 + * def __pyx_unpickle_TCyBinaryProtocol(__pyx_type, long __pyx_checksum, tuple __pyx_state): + * cdef object __pyx_result + * __Pyx_CheckUnpickleChecksum(__pyx_checksum, 0xf5434e1, 0xee67e8e, 0x44df354, b'decode_response, strict_decode, strict_read, strict_write, trans') # <<<<<<<<<<<<<< + * __pyx_result = TCyBinaryProtocol.__new__(__pyx_type) + * if __pyx_state is not None: +*/ + __pyx_t_1 = __Pyx_CheckUnpickleChecksum(__pyx_v___pyx_checksum, 0xf5434e1, 0xee67e8e, 0x44df354, __pyx_k_decode_response_strict_decode_st); if (unlikely(__pyx_t_1 == ((int)-1))) __PYX_ERR(2, 6, __pyx_L1_error) + + /* "(tree fragment)":7 + * cdef object __pyx_result + * __Pyx_CheckUnpickleChecksum(__pyx_checksum, 0xf5434e1, 0xee67e8e, 0x44df354, b'decode_response, strict_decode, strict_read, strict_write, trans') + * __pyx_result = TCyBinaryProtocol.__new__(__pyx_type) # <<<<<<<<<<<<<< + * if __pyx_state is not None: + * __pyx_unpickle_TCyBinaryProtocol__set_state( __pyx_result, __pyx_state) +*/ + __pyx_t_3 = ((PyObject *)__pyx_mstate_global->__pyx_ptype_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol); + __Pyx_INCREF(__pyx_t_3); + __pyx_t_4 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_v___pyx_type}; + __pyx_t_2 = __Pyx_PyObject_FastCallMethod((PyObject*)__pyx_mstate_global->__pyx_n_u_new, __pyx_callargs+__pyx_t_4, (2-__pyx_t_4) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 7, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __pyx_v___pyx_result = __pyx_t_2; + __pyx_t_2 = 0; + + /* "(tree fragment)":8 + * __Pyx_CheckUnpickleChecksum(__pyx_checksum, 0xf5434e1, 0xee67e8e, 0x44df354, b'decode_response, strict_decode, strict_read, strict_write, trans') + * __pyx_result = TCyBinaryProtocol.__new__(__pyx_type) + * if __pyx_state is not None: # <<<<<<<<<<<<<< + * __pyx_unpickle_TCyBinaryProtocol__set_state( __pyx_result, __pyx_state) + * return __pyx_result +*/ + __pyx_t_5 = (__pyx_v___pyx_state != ((PyObject*)Py_None)); + if (__pyx_t_5) { + + /* "(tree fragment)":9 + * __pyx_result = TCyBinaryProtocol.__new__(__pyx_type) + * if __pyx_state is not None: + * __pyx_unpickle_TCyBinaryProtocol__set_state( __pyx_result, __pyx_state) # <<<<<<<<<<<<<< + * return __pyx_result + * cdef __pyx_unpickle_TCyBinaryProtocol__set_state(TCyBinaryProtocol __pyx_result, __pyx_state: tuple): +*/ + if (unlikely(__pyx_v___pyx_state == Py_None)) { + PyErr_SetString(PyExc_TypeError, "cannot pass None into a C function argument that is declared 'not None'"); + __PYX_ERR(2, 9, __pyx_L1_error) + } + __pyx_t_2 = __pyx_f_9thriftpy2_8protocol_5cybin_5cybin___pyx_unpickle_TCyBinaryProtocol__set_state(((struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *)__pyx_v___pyx_result), __pyx_v___pyx_state); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 9, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "(tree fragment)":8 + * __Pyx_CheckUnpickleChecksum(__pyx_checksum, 0xf5434e1, 0xee67e8e, 0x44df354, b'decode_response, strict_decode, strict_read, strict_write, trans') + * __pyx_result = TCyBinaryProtocol.__new__(__pyx_type) + * if __pyx_state is not None: # <<<<<<<<<<<<<< + * __pyx_unpickle_TCyBinaryProtocol__set_state( __pyx_result, __pyx_state) + * return __pyx_result +*/ + } + + /* "(tree fragment)":10 + * if __pyx_state is not None: + * __pyx_unpickle_TCyBinaryProtocol__set_state( __pyx_result, __pyx_state) + * return __pyx_result # <<<<<<<<<<<<<< + * cdef __pyx_unpickle_TCyBinaryProtocol__set_state(TCyBinaryProtocol __pyx_result, __pyx_state: tuple): + * __pyx_result.decode_response = __pyx_state[0]; __pyx_result.strict_decode = __pyx_state[1]; __pyx_result.strict_read = __pyx_state[2]; __pyx_result.strict_write = __pyx_state[3]; __pyx_result.trans = __pyx_state[4] +*/ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v___pyx_result); + __pyx_r = __pyx_v___pyx_result; + goto __pyx_L0; + + /* "(tree fragment)":4 + * int __Pyx_CheckUnpickleChecksum(long, long, long, long, const char*) except -1 + * int __Pyx_UpdateUnpickledDict(object, object, Py_ssize_t) except -1 + * def __pyx_unpickle_TCyBinaryProtocol(__pyx_type, long __pyx_checksum, tuple __pyx_state): # <<<<<<<<<<<<<< + * cdef object __pyx_result + * __Pyx_CheckUnpickleChecksum(__pyx_checksum, 0xf5434e1, 0xee67e8e, 0x44df354, b'decode_response, strict_decode, strict_read, strict_write, trans') +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("thriftpy2.protocol.cybin.cybin.__pyx_unpickle_TCyBinaryProtocol", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v___pyx_result); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":11 + * __pyx_unpickle_TCyBinaryProtocol__set_state( __pyx_result, __pyx_state) + * return __pyx_result + * cdef __pyx_unpickle_TCyBinaryProtocol__set_state(TCyBinaryProtocol __pyx_result, __pyx_state: tuple): # <<<<<<<<<<<<<< + * __pyx_result.decode_response = __pyx_state[0]; __pyx_result.strict_decode = __pyx_state[1]; __pyx_result.strict_read = __pyx_state[2]; __pyx_result.strict_write = __pyx_state[3]; __pyx_result.trans = __pyx_state[4] + * __Pyx_UpdateUnpickledDict(__pyx_result, __pyx_state, 5) +*/ + +static PyObject *__pyx_f_9thriftpy2_8protocol_5cybin_5cybin___pyx_unpickle_TCyBinaryProtocol__set_state(struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *__pyx_v___pyx_result, PyObject *__pyx_v___pyx_state) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__pyx_unpickle_TCyBinaryProtocol__set_state", 0); + + /* "(tree fragment)":12 + * return __pyx_result + * cdef __pyx_unpickle_TCyBinaryProtocol__set_state(TCyBinaryProtocol __pyx_result, __pyx_state: tuple): + * __pyx_result.decode_response = __pyx_state[0]; __pyx_result.strict_decode = __pyx_state[1]; __pyx_result.strict_read = __pyx_state[2]; __pyx_result.strict_write = __pyx_state[3]; __pyx_result.trans = __pyx_state[4] # <<<<<<<<<<<<<< + * __Pyx_UpdateUnpickledDict(__pyx_result, __pyx_state, 5) +*/ + __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 0, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1, __Pyx_ReferenceSharing_FunctionArgument); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 12, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_mstate_global->__pyx_ptype_7cpython_4bool_bool))))) __PYX_ERR(2, 12, __pyx_L1_error) + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF((PyObject *)__pyx_v___pyx_result->decode_response); + __Pyx_DECREF((PyObject *)__pyx_v___pyx_result->decode_response); + __pyx_v___pyx_result->decode_response = ((PyLongObject *)__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 1, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1, __Pyx_ReferenceSharing_FunctionArgument); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 12, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_mstate_global->__pyx_ptype_7cpython_4bool_bool))))) __PYX_ERR(2, 12, __pyx_L1_error) + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF((PyObject *)__pyx_v___pyx_result->strict_decode); + __Pyx_DECREF((PyObject *)__pyx_v___pyx_result->strict_decode); + __pyx_v___pyx_result->strict_decode = ((PyLongObject *)__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 2, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1, __Pyx_ReferenceSharing_FunctionArgument); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 12, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_mstate_global->__pyx_ptype_7cpython_4bool_bool))))) __PYX_ERR(2, 12, __pyx_L1_error) + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF((PyObject *)__pyx_v___pyx_result->strict_read); + __Pyx_DECREF((PyObject *)__pyx_v___pyx_result->strict_read); + __pyx_v___pyx_result->strict_read = ((PyLongObject *)__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 3, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1, __Pyx_ReferenceSharing_FunctionArgument); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 12, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_mstate_global->__pyx_ptype_7cpython_4bool_bool))))) __PYX_ERR(2, 12, __pyx_L1_error) + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF((PyObject *)__pyx_v___pyx_result->strict_write); + __Pyx_DECREF((PyObject *)__pyx_v___pyx_result->strict_write); + __pyx_v___pyx_result->strict_write = ((PyLongObject *)__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 4, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1, __Pyx_ReferenceSharing_FunctionArgument); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 12, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase))))) __PYX_ERR(2, 12, __pyx_L1_error) + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF((PyObject *)__pyx_v___pyx_result->trans); + __Pyx_DECREF((PyObject *)__pyx_v___pyx_result->trans); + __pyx_v___pyx_result->trans = ((struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "(tree fragment)":13 + * cdef __pyx_unpickle_TCyBinaryProtocol__set_state(TCyBinaryProtocol __pyx_result, __pyx_state: tuple): + * __pyx_result.decode_response = __pyx_state[0]; __pyx_result.strict_decode = __pyx_state[1]; __pyx_result.strict_read = __pyx_state[2]; __pyx_result.strict_write = __pyx_state[3]; __pyx_result.trans = __pyx_state[4] + * __Pyx_UpdateUnpickledDict(__pyx_result, __pyx_state, 5) # <<<<<<<<<<<<<< +*/ + __pyx_t_2 = __Pyx_UpdateUnpickledDict(((PyObject *)__pyx_v___pyx_result), __pyx_v___pyx_state, 5); if (unlikely(__pyx_t_2 == ((int)-1))) __PYX_ERR(2, 13, __pyx_L1_error) + + /* "(tree fragment)":11 + * __pyx_unpickle_TCyBinaryProtocol__set_state( __pyx_result, __pyx_state) + * return __pyx_result + * cdef __pyx_unpickle_TCyBinaryProtocol__set_state(TCyBinaryProtocol __pyx_result, __pyx_state: tuple): # <<<<<<<<<<<<<< + * __pyx_result.decode_response = __pyx_state[0]; __pyx_result.strict_decode = __pyx_state[1]; __pyx_result.strict_read = __pyx_state[2]; __pyx_result.strict_write = __pyx_state[3]; __pyx_result.trans = __pyx_state[4] + * __Pyx_UpdateUnpickledDict(__pyx_result, __pyx_state, 5) +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("thriftpy2.protocol.cybin.cybin.__pyx_unpickle_TCyBinaryProtocol__set_state", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} +/* #### Code section: module_exttypes ### */ + +static PyObject *__pyx_tp_new_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { + struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *p; + PyObject *o; + o = __Pyx_AllocateExtensionType(t, 0); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *)o); + p->trans = ((struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *)Py_None); Py_INCREF(Py_None); + p->strict_read = ((PyLongObject *)Py_None); Py_INCREF(Py_None); + p->strict_write = ((PyLongObject *)Py_None); Py_INCREF(Py_None); + p->decode_response = ((PyLongObject *)Py_None); Py_INCREF(Py_None); + p->strict_decode = ((PyLongObject *)Py_None); Py_INCREF(Py_None); + return o; +} + +static void __pyx_tp_dealloc_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol(PyObject *o) { + struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *p = (struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *)o; + #if CYTHON_USE_TP_FINALIZE + if (unlikely(__Pyx_PyObject_GetSlot(o, tp_finalize, destructor)) && !__Pyx_PyObject_GC_IsFinalized(o)) { + if (__Pyx_PyObject_GetSlot(o, tp_dealloc, destructor) == __pyx_tp_dealloc_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + } + #endif + PyObject_GC_UnTrack(o); + Py_CLEAR(p->trans); + Py_CLEAR(p->strict_read); + Py_CLEAR(p->strict_write); + Py_CLEAR(p->decode_response); + Py_CLEAR(p->strict_decode); + PyTypeObject *tp = Py_TYPE(o); + #if CYTHON_USE_TYPE_SLOTS + (*tp->tp_free)(o); + #else + { + freefunc tp_free = (freefunc)PyType_GetSlot(tp, Py_tp_free); + if (tp_free) tp_free(o); + } + #endif + #if CYTHON_USE_TYPE_SPECS + Py_DECREF(tp); + #endif +} + +static int __pyx_tp_traverse_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *p = (struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *)o; + { + e = __Pyx_call_type_traverse(o, 1, v, a); + if (e) return e; + } + if (p->trans) { + e = (*v)(((PyObject *)p->trans), a); if (e) return e; + } + if (p->strict_read) { + e = (*v)(((PyObject *)p->strict_read), a); if (e) return e; + } + if (p->strict_write) { + e = (*v)(((PyObject *)p->strict_write), a); if (e) return e; + } + if (p->decode_response) { + e = (*v)(((PyObject *)p->decode_response), a); if (e) return e; + } + if (p->strict_decode) { + e = (*v)(((PyObject *)p->strict_decode), a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol(PyObject *o) { + PyObject* tmp; + struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *p = (struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol *)o; + tmp = ((PyObject*)p->trans); + p->trans = ((struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->strict_read); + p->strict_read = ((PyLongObject *)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->strict_write); + p->strict_write = ((PyLongObject *)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->decode_response); + p->decode_response = ((PyLongObject *)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->strict_decode); + p->strict_decode = ((PyLongObject *)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); + return 0; +} + +static PyObject *__pyx_getprop_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_trans(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_5trans_1__get__(o); +} + +static int __pyx_setprop_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_trans(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) { + if (v) { + return __pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_5trans_3__set__(o, v); + } + else { + return __pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_5trans_5__del__(o); + } +} + +static PyObject *__pyx_getprop_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_strict_read(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_11strict_read_1__get__(o); +} + +static int __pyx_setprop_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_strict_read(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) { + if (v) { + return __pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_11strict_read_3__set__(o, v); + } + else { + return __pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_11strict_read_5__del__(o); + } +} + +static PyObject *__pyx_getprop_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_strict_write(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_12strict_write_1__get__(o); +} + +static int __pyx_setprop_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_strict_write(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) { + if (v) { + return __pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_12strict_write_3__set__(o, v); + } + else { + return __pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_12strict_write_5__del__(o); + } +} + +static PyObject *__pyx_getprop_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_decode_response(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_15decode_response_1__get__(o); +} + +static int __pyx_setprop_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_decode_response(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) { + if (v) { + return __pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_15decode_response_3__set__(o, v); + } + else { + return __pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_15decode_response_5__del__(o); + } +} + +static PyObject *__pyx_getprop_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_strict_decode(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_13strict_decode_1__get__(o); +} + +static int __pyx_setprop_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_strict_decode(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) { + if (v) { + return __pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_13strict_decode_3__set__(o, v); + } + else { + return __pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_13strict_decode_5__del__(o); + } +} + +static PyMethodDef __pyx_methods_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol[] = { + {"skip", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_3skip, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, + {"read_message_begin", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_5read_message_begin, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, + {"read_message_end", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_7read_message_end, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, + {"write_message_begin", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_9write_message_begin, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, + {"write_message_end", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_11write_message_end, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, + {"read_struct", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_13read_struct, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, + {"write_struct", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_15write_struct, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, + {"__reduce_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_17__reduce_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, + {"__setstate_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_19__setstate_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, + {0, 0, 0, 0} +}; + +static struct PyGetSetDef __pyx_getsets_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol[] = { + {"trans", __pyx_getprop_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_trans, __pyx_setprop_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_trans, 0, 0}, + {"strict_read", __pyx_getprop_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_strict_read, __pyx_setprop_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_strict_read, 0, 0}, + {"strict_write", __pyx_getprop_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_strict_write, __pyx_setprop_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_strict_write, 0, 0}, + {"decode_response", __pyx_getprop_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_decode_response, __pyx_setprop_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_decode_response, 0, 0}, + {"strict_decode", __pyx_getprop_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_strict_decode, __pyx_setprop_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_strict_decode, 0, 0}, + {0, 0, 0, 0, 0} +}; +#if CYTHON_USE_TYPE_SPECS +static PyType_Slot __pyx_type_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol_slots[] = { + {Py_tp_dealloc, (void *)__pyx_tp_dealloc_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol}, + {Py_tp_traverse, (void *)__pyx_tp_traverse_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol}, + {Py_tp_clear, (void *)__pyx_tp_clear_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol}, + {Py_tp_methods, (void *)__pyx_methods_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol}, + {Py_tp_getset, (void *)__pyx_getsets_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol}, + {Py_tp_init, (void *)__pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_1__init__}, + {Py_tp_new, (void *)__pyx_tp_new_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol}, + {0, 0}, +}; +static PyType_Spec __pyx_type_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol_spec = { + "thriftpy2.protocol.cybin.cybin.TCyBinaryProtocol", + sizeof(struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol), + 0, + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, + __pyx_type_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol_slots, +}; +#else + +static PyTypeObject __pyx_type_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol = { + PyVarObject_HEAD_INIT(0, 0) + "thriftpy2.protocol.cybin.cybin.""TCyBinaryProtocol", /*tp_name*/ + sizeof(struct __pyx_obj_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol, /*tp_dealloc*/ + 0, /*tp_vectorcall_offset*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_as_async*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + 0, /*tp_doc*/ + __pyx_tp_traverse_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol, /*tp_traverse*/ + __pyx_tp_clear_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol, /*tp_methods*/ + 0, /*tp_members*/ + __pyx_getsets_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + #if !CYTHON_USE_TYPE_SPECS + 0, /*tp_dictoffset*/ + #endif + __pyx_pw_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_1__init__, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if CYTHON_USE_TP_FINALIZE + 0, /*tp_finalize*/ + #else + NULL, /*tp_finalize*/ + #endif + #if !CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800 + 0, /*tp_vectorcall*/ + #endif + #if __PYX_NEED_TP_PRINT_SLOT == 1 + 0, /*tp_print*/ + #endif + #if PY_VERSION_HEX >= 0x030C0000 + 0, /*tp_watched*/ + #endif + #if PY_VERSION_HEX >= 0x030d00A4 + 0, /*tp_versions_used*/ + #endif + #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX >= 0x03090000 && PY_VERSION_HEX < 0x030a0000 + 0, /*tp_pypy_flags*/ + #endif +}; +#endif + +static PyMethodDef __pyx_methods[] = { + {0, 0, 0, 0} +}; +/* #### Code section: initfunc_declarations ### */ +static CYTHON_SMALL_CODE int __Pyx_InitCachedBuiltins(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_InitCachedConstants(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_InitGlobals(void); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_InitConstants(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_global_init_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_variable_export_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_function_export_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_type_init_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_type_import_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_variable_import_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_function_import_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_CreateCodeObjects(__pyx_mstatetype *__pyx_mstate); /*proto*/ +/* #### Code section: init_module ### */ + +static int __Pyx_modinit_global_init_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_modinit_global_init_code", 0); + /*--- Global init code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_modinit_variable_export_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_modinit_variable_export_code", 0); + /*--- Variable export code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_modinit_function_export_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_modinit_function_export_code", 0); + /*--- Function export code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_modinit_type_init_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__Pyx_modinit_type_init_code", 0); + /*--- Type init code ---*/ + #if CYTHON_USE_TYPE_SPECS + __pyx_mstate->__pyx_ptype_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol = (PyTypeObject *) __Pyx_PyType_FromModuleAndSpec(__pyx_m, &__pyx_type_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol_spec, NULL); if (unlikely(!__pyx_mstate->__pyx_ptype_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol)) __PYX_ERR(0, 457, __pyx_L1_error) + if (__Pyx_fix_up_extension_type_from_spec(&__pyx_type_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol_spec, __pyx_mstate->__pyx_ptype_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol) < (0)) __PYX_ERR(0, 457, __pyx_L1_error) + #else + __pyx_mstate->__pyx_ptype_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol = &__pyx_type_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol; + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + #endif + #if !CYTHON_USE_TYPE_SPECS + if (__Pyx_PyType_Ready(__pyx_mstate->__pyx_ptype_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol) < (0)) __PYX_ERR(0, 457, __pyx_L1_error) + #endif + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount((PyObject*)__pyx_mstate->__pyx_ptype_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol); + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_mstate->__pyx_ptype_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol->tp_dictoffset && __pyx_mstate->__pyx_ptype_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol->tp_getattro == PyObject_GenericGetAttr)) { + __pyx_mstate->__pyx_ptype_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol->tp_getattro = PyObject_GenericGetAttr; + } + #endif + if (PyObject_SetAttr(__pyx_m, __pyx_mstate_global->__pyx_n_u_TCyBinaryProtocol, (PyObject *) __pyx_mstate->__pyx_ptype_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol) < (0)) __PYX_ERR(0, 457, __pyx_L1_error) + if (__Pyx_setup_reduce((PyObject *) __pyx_mstate->__pyx_ptype_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol) < (0)) __PYX_ERR(0, 457, __pyx_L1_error) + __Pyx_RefNannyFinishContext(); + return 0; + __pyx_L1_error:; + __Pyx_RefNannyFinishContext(); + return -1; +} + +static int __Pyx_modinit_type_import_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__Pyx_modinit_type_import_code", 0); + /*--- Type import code ---*/ + __pyx_t_1 = PyImport_ImportModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 9, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_mstate->__pyx_ptype_7cpython_4type_type = __Pyx_ImportType_3_2_4(__pyx_t_1, __Pyx_BUILTIN_MODULE_NAME, "type", + #if defined(PYPY_VERSION_NUM) && PYPY_VERSION_NUM < 0x050B0000 + sizeof(PyTypeObject), __PYX_GET_STRUCT_ALIGNMENT_3_2_4(PyTypeObject), + #elif CYTHON_COMPILING_IN_LIMITED_API + 0, 0, + #else + sizeof(PyHeapTypeObject), __PYX_GET_STRUCT_ALIGNMENT_3_2_4(PyHeapTypeObject), + #endif + __Pyx_ImportType_CheckSize_Warn_3_2_4); if (!__pyx_mstate->__pyx_ptype_7cpython_4type_type) __PYX_ERR(3, 9, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyImport_ImportModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_t_1)) __PYX_ERR(4, 8, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_mstate->__pyx_ptype_7cpython_4bool_bool = __Pyx_ImportType_3_2_4(__pyx_t_1, __Pyx_BUILTIN_MODULE_NAME, "bool", + #if defined(PYPY_VERSION_NUM) && PYPY_VERSION_NUM < 0x050B0000 + sizeof(PyLongObject), __PYX_GET_STRUCT_ALIGNMENT_3_2_4(PyLongObject), + #elif CYTHON_COMPILING_IN_LIMITED_API + 0, 0, + #else + sizeof(PyLongObject), __PYX_GET_STRUCT_ALIGNMENT_3_2_4(PyLongObject), + #endif + __Pyx_ImportType_CheckSize_Warn_3_2_4); if (!__pyx_mstate->__pyx_ptype_7cpython_4bool_bool) __PYX_ERR(4, 8, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyImport_ImportModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 16, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_mstate->__pyx_ptype_7cpython_7complex_complex = __Pyx_ImportType_3_2_4(__pyx_t_1, __Pyx_BUILTIN_MODULE_NAME, "complex", + #if defined(PYPY_VERSION_NUM) && PYPY_VERSION_NUM < 0x050B0000 + sizeof(PyComplexObject), __PYX_GET_STRUCT_ALIGNMENT_3_2_4(PyComplexObject), + #elif CYTHON_COMPILING_IN_LIMITED_API + 0, 0, + #else + sizeof(PyComplexObject), __PYX_GET_STRUCT_ALIGNMENT_3_2_4(PyComplexObject), + #endif + __Pyx_ImportType_CheckSize_Warn_3_2_4); if (!__pyx_mstate->__pyx_ptype_7cpython_7complex_complex) __PYX_ERR(5, 16, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyImport_ImportModule("thriftpy2.transport.cybase"); if (unlikely(!__pyx_t_1)) __PYX_ERR(6, 7, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer = __Pyx_ImportType_3_2_4(__pyx_t_1, "thriftpy2.transport.cybase", "TCyBuffer", + #if defined(PYPY_VERSION_NUM) && PYPY_VERSION_NUM < 0x050B0000 + sizeof(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer), __PYX_GET_STRUCT_ALIGNMENT_3_2_4(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer), + #elif CYTHON_COMPILING_IN_LIMITED_API + sizeof(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer), __PYX_GET_STRUCT_ALIGNMENT_3_2_4(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer), + #else + sizeof(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer), __PYX_GET_STRUCT_ALIGNMENT_3_2_4(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer), + #endif + __Pyx_ImportType_CheckSize_Warn_3_2_4); if (!__pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer) __PYX_ERR(6, 7, __pyx_L1_error) + __pyx_vtabptr_9thriftpy2_9transport_6cybase_TCyBuffer = (struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_TCyBuffer*)__Pyx_GetVtable(__pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer); if (unlikely(!__pyx_vtabptr_9thriftpy2_9transport_6cybase_TCyBuffer)) __PYX_ERR(6, 7, __pyx_L1_error) + __pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase = __Pyx_ImportType_3_2_4(__pyx_t_1, "thriftpy2.transport.cybase", "CyTransportBase", + #if defined(PYPY_VERSION_NUM) && PYPY_VERSION_NUM < 0x050B0000 + sizeof(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase), __PYX_GET_STRUCT_ALIGNMENT_3_2_4(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase), + #elif CYTHON_COMPILING_IN_LIMITED_API + sizeof(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase), __PYX_GET_STRUCT_ALIGNMENT_3_2_4(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase), + #else + sizeof(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase), __PYX_GET_STRUCT_ALIGNMENT_3_2_4(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase), + #endif + __Pyx_ImportType_CheckSize_Warn_3_2_4); if (!__pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase) __PYX_ERR(6, 19, __pyx_L1_error) + __pyx_vtabptr_9thriftpy2_9transport_6cybase_CyTransportBase = (struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_CyTransportBase*)__Pyx_GetVtable(__pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase); if (unlikely(!__pyx_vtabptr_9thriftpy2_9transport_6cybase_CyTransportBase)) __PYX_ERR(6, 19, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_RefNannyFinishContext(); + return 0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_RefNannyFinishContext(); + return -1; +} + +static int __Pyx_modinit_variable_import_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_modinit_variable_import_code", 0); + /*--- Variable import code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_modinit_function_import_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_modinit_function_import_code", 0); + /*--- Function import code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +#if CYTHON_PEP489_MULTI_PHASE_INIT +static PyObject* __pyx_pymod_create(PyObject *spec, PyModuleDef *def); /*proto*/ +static int __pyx_pymod_exec_cybin(PyObject* module); /*proto*/ +static PyModuleDef_Slot __pyx_moduledef_slots[] = { + {Py_mod_create, (void*)__pyx_pymod_create}, + {Py_mod_exec, (void*)__pyx_pymod_exec_cybin}, + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + {Py_mod_gil, __Pyx_FREETHREADING_COMPATIBLE}, + #endif + #if PY_VERSION_HEX >= 0x030C0000 && CYTHON_USE_MODULE_STATE + {Py_mod_multiple_interpreters, Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED}, + #endif + {0, NULL} +}; +#endif + +#ifdef __cplusplus +namespace { + struct PyModuleDef __pyx_moduledef = + #else + static struct PyModuleDef __pyx_moduledef = + #endif + { + PyModuleDef_HEAD_INIT, + "cybin", + 0, /* m_doc */ + #if CYTHON_USE_MODULE_STATE + sizeof(__pyx_mstatetype), /* m_size */ + #else + (CYTHON_PEP489_MULTI_PHASE_INIT) ? 0 : -1, /* m_size */ + #endif + __pyx_methods /* m_methods */, + #if CYTHON_PEP489_MULTI_PHASE_INIT + __pyx_moduledef_slots, /* m_slots */ + #else + NULL, /* m_reload */ + #endif + #if CYTHON_USE_MODULE_STATE + __pyx_m_traverse, /* m_traverse */ + __pyx_m_clear, /* m_clear */ + NULL /* m_free */ + #else + NULL, /* m_traverse */ + NULL, /* m_clear */ + NULL /* m_free */ + #endif + }; + #ifdef __cplusplus +} /* anonymous namespace */ +#endif + +/* PyModInitFuncType */ +#ifndef CYTHON_NO_PYINIT_EXPORT + #define __Pyx_PyMODINIT_FUNC PyMODINIT_FUNC +#else + #ifdef __cplusplus + #define __Pyx_PyMODINIT_FUNC extern "C" PyObject * + #else + #define __Pyx_PyMODINIT_FUNC PyObject * + #endif +#endif + +__Pyx_PyMODINIT_FUNC PyInit_cybin(void) CYTHON_SMALL_CODE; /*proto*/ +__Pyx_PyMODINIT_FUNC PyInit_cybin(void) +#if CYTHON_PEP489_MULTI_PHASE_INIT +{ + return PyModuleDef_Init(&__pyx_moduledef); +} +/* ModuleCreationPEP489 */ +#if CYTHON_COMPILING_IN_LIMITED_API && (__PYX_LIMITED_VERSION_HEX < 0x03090000\ + || ((defined(_WIN32) || defined(WIN32) || defined(MS_WINDOWS)) && __PYX_LIMITED_VERSION_HEX < 0x030A0000)) +static PY_INT64_T __Pyx_GetCurrentInterpreterId(void) { + { + PyObject *module = PyImport_ImportModule("_interpreters"); // 3.13+ I think + if (!module) { + PyErr_Clear(); // just try the 3.8-3.12 version + module = PyImport_ImportModule("_xxsubinterpreters"); + if (!module) goto bad; + } + PyObject *current = PyObject_CallMethod(module, "get_current", NULL); + Py_DECREF(module); + if (!current) goto bad; + if (PyTuple_Check(current)) { + PyObject *new_current = PySequence_GetItem(current, 0); + Py_DECREF(current); + current = new_current; + if (!new_current) goto bad; + } + long long as_c_int = PyLong_AsLongLong(current); + Py_DECREF(current); + return as_c_int; + } + bad: + PySys_WriteStderr("__Pyx_GetCurrentInterpreterId failed. Try setting the C define CYTHON_PEP489_MULTI_PHASE_INIT=0\n"); + return -1; +} +#endif +#if !CYTHON_USE_MODULE_STATE +static CYTHON_SMALL_CODE int __Pyx_check_single_interpreter(void) { + static PY_INT64_T main_interpreter_id = -1; +#if CYTHON_COMPILING_IN_GRAAL && defined(GRAALPY_VERSION_NUM) && GRAALPY_VERSION_NUM > 0x19000000 + PY_INT64_T current_id = GraalPyInterpreterState_GetIDFromThreadState(PyThreadState_Get()); +#elif CYTHON_COMPILING_IN_GRAAL + PY_INT64_T current_id = PyInterpreterState_GetIDFromThreadState(PyThreadState_Get()); +#elif CYTHON_COMPILING_IN_LIMITED_API && (__PYX_LIMITED_VERSION_HEX < 0x03090000\ + || ((defined(_WIN32) || defined(WIN32) || defined(MS_WINDOWS)) && __PYX_LIMITED_VERSION_HEX < 0x030A0000)) + PY_INT64_T current_id = __Pyx_GetCurrentInterpreterId(); +#elif CYTHON_COMPILING_IN_LIMITED_API + PY_INT64_T current_id = PyInterpreterState_GetID(PyInterpreterState_Get()); +#else + PY_INT64_T current_id = PyInterpreterState_GetID(PyThreadState_Get()->interp); +#endif + if (unlikely(current_id == -1)) { + return -1; + } + if (main_interpreter_id == -1) { + main_interpreter_id = current_id; + return 0; + } else if (unlikely(main_interpreter_id != current_id)) { + PyErr_SetString( + PyExc_ImportError, + "Interpreter change detected - this module can only be loaded into one interpreter per process."); + return -1; + } + return 0; +} +#endif +static CYTHON_SMALL_CODE int __Pyx_copy_spec_to_module(PyObject *spec, PyObject *moddict, const char* from_name, const char* to_name, int allow_none) +{ + PyObject *value = PyObject_GetAttrString(spec, from_name); + int result = 0; + if (likely(value)) { + if (allow_none || value != Py_None) { + result = PyDict_SetItemString(moddict, to_name, value); + } + Py_DECREF(value); + } else if (PyErr_ExceptionMatches(PyExc_AttributeError)) { + PyErr_Clear(); + } else { + result = -1; + } + return result; +} +static CYTHON_SMALL_CODE PyObject* __pyx_pymod_create(PyObject *spec, PyModuleDef *def) { + PyObject *module = NULL, *moddict, *modname; + CYTHON_UNUSED_VAR(def); + #if !CYTHON_USE_MODULE_STATE + if (__Pyx_check_single_interpreter()) + return NULL; + #endif + if (__pyx_m) + return __Pyx_NewRef(__pyx_m); + modname = PyObject_GetAttrString(spec, "name"); + if (unlikely(!modname)) goto bad; + module = PyModule_NewObject(modname); + Py_DECREF(modname); + if (unlikely(!module)) goto bad; + moddict = PyModule_GetDict(module); + if (unlikely(!moddict)) goto bad; + if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "loader", "__loader__", 1) < 0)) goto bad; + if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "origin", "__file__", 1) < 0)) goto bad; + if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "parent", "__package__", 1) < 0)) goto bad; + if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "submodule_search_locations", "__path__", 0) < 0)) goto bad; + return module; +bad: + Py_XDECREF(module); + return NULL; +} + + +static CYTHON_SMALL_CODE int __pyx_pymod_exec_cybin(PyObject *__pyx_pyinit_module) +#endif +{ + int stringtab_initialized = 0; + #if CYTHON_USE_MODULE_STATE + int pystate_addmodule_run = 0; + #endif + __pyx_mstatetype *__pyx_mstate = NULL; + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + Py_ssize_t __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannyDeclarations + #if CYTHON_PEP489_MULTI_PHASE_INIT + if (__pyx_m) { + if (__pyx_m == __pyx_pyinit_module) return 0; + PyErr_SetString(PyExc_RuntimeError, "Module 'cybin' has already been imported. Re-initialisation is not supported."); + return -1; + } + #else + if (__pyx_m) return __Pyx_NewRef(__pyx_m); + #endif + /*--- Module creation code ---*/ + #if CYTHON_PEP489_MULTI_PHASE_INIT + __pyx_t_1 = __pyx_pyinit_module; + Py_INCREF(__pyx_t_1); + #else + __pyx_t_1 = PyModule_Create(&__pyx_moduledef); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1, __pyx_L1_error) + #endif + #if CYTHON_USE_MODULE_STATE + { + int add_module_result = __Pyx_State_AddModule(__pyx_t_1, &__pyx_moduledef); + __pyx_t_1 = 0; /* transfer ownership from __pyx_t_1 to "cybin" pseudovariable */ + if (unlikely((add_module_result < 0))) __PYX_ERR(0, 1, __pyx_L1_error) + pystate_addmodule_run = 1; + } + #else + __pyx_m = __pyx_t_1; + #endif + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + PyUnstable_Module_SetGIL(__pyx_m, Py_MOD_GIL_NOT_USED); + #endif + __pyx_mstate = __pyx_mstate_global; + CYTHON_UNUSED_VAR(__pyx_t_1); + __pyx_mstate->__pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_mstate->__pyx_d)) __PYX_ERR(0, 1, __pyx_L1_error) + Py_INCREF(__pyx_mstate->__pyx_d); + __pyx_mstate->__pyx_b = __Pyx_PyImport_AddModuleRef(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_mstate->__pyx_b)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_mstate->__pyx_cython_runtime = __Pyx_PyImport_AddModuleRef("cython_runtime"); if (unlikely(!__pyx_mstate->__pyx_cython_runtime)) __PYX_ERR(0, 1, __pyx_L1_error) + if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_mstate->__pyx_b) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + /* ImportRefnannyAPI */ + #if CYTHON_REFNANNY + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); + if (!__Pyx_RefNanny) { + PyErr_Clear(); + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); + if (!__Pyx_RefNanny) + Py_FatalError("failed to import 'refnanny' module"); + } + #endif + +__Pyx_RefNannySetupContext("PyInit_cybin", 0); + __Pyx_init_runtime_version(); + if (__Pyx_check_binary_version(__PYX_LIMITED_VERSION_HEX, __Pyx_get_runtime_version(), CYTHON_COMPILING_IN_LIMITED_API) < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_mstate->__pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_mstate->__pyx_empty_tuple)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_mstate->__pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_mstate->__pyx_empty_bytes)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_mstate->__pyx_empty_unicode = PyUnicode_FromStringAndSize("", 0); if (unlikely(!__pyx_mstate->__pyx_empty_unicode)) __PYX_ERR(0, 1, __pyx_L1_error) + /*--- Library function declarations ---*/ + /*--- Initialize various global constants etc. ---*/ + if (__Pyx_InitConstants(__pyx_mstate) < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + stringtab_initialized = 1; + if (__Pyx_InitGlobals() < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + if (__pyx_module_is_main_thriftpy2__protocol__cybin__cybin) { + if (PyObject_SetAttr(__pyx_m, __pyx_mstate_global->__pyx_n_u_name, __pyx_mstate_global->__pyx_n_u_main) < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + } + { + PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) __PYX_ERR(0, 1, __pyx_L1_error) + if (!PyDict_GetItemString(modules, "thriftpy2.protocol.cybin.cybin")) { + if (unlikely((PyDict_SetItemString(modules, "thriftpy2.protocol.cybin.cybin", __pyx_m) < 0))) __PYX_ERR(0, 1, __pyx_L1_error) + } + } + /*--- Builtin init code ---*/ + if (__Pyx_InitCachedBuiltins(__pyx_mstate) < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + /*--- Constants init code ---*/ + if (__Pyx_InitCachedConstants(__pyx_mstate) < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + if (__Pyx_CreateCodeObjects(__pyx_mstate) < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + /*--- Global type/function init code ---*/ + (void)__Pyx_modinit_global_init_code(__pyx_mstate); + (void)__Pyx_modinit_variable_export_code(__pyx_mstate); + (void)__Pyx_modinit_function_export_code(__pyx_mstate); + if (unlikely((__Pyx_modinit_type_init_code(__pyx_mstate) < 0))) __PYX_ERR(0, 1, __pyx_L1_error) + if (unlikely((__Pyx_modinit_type_import_code(__pyx_mstate) < 0))) __PYX_ERR(0, 1, __pyx_L1_error) + (void)__Pyx_modinit_variable_import_code(__pyx_mstate); + (void)__Pyx_modinit_function_import_code(__pyx_mstate); + /*--- Execution code ---*/ + + /* "thriftpy2/protocol/cybin/cybin.pyx":3 + * # cython: freethreading_compatible = True + * + * import sys # <<<<<<<<<<<<<< + * + * from libc.stdlib cimport free, malloc +*/ + __pyx_t_1 = __Pyx_Import(__pyx_mstate_global->__pyx_n_u_sys, 0, 0, NULL, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 3, __pyx_L1_error) + __pyx_t_2 = __pyx_t_1; + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_sys, __pyx_t_2) < (0)) __PYX_ERR(0, 3, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":10 + * from cpython cimport bool + * + * import six # <<<<<<<<<<<<<< + * + * from thriftpy2.thrift import TDecodeException +*/ + __pyx_t_1 = __Pyx_Import(__pyx_mstate_global->__pyx_n_u_six, 0, 0, NULL, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 10, __pyx_L1_error) + __pyx_t_2 = __pyx_t_1; + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_six, __pyx_t_2) < (0)) __PYX_ERR(0, 10, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":12 + * import six + * + * from thriftpy2.thrift import TDecodeException # <<<<<<<<<<<<<< + * from thriftpy2.transport.cybase cimport CyTransportBase, STACK_STRING_LEN + * +*/ + { + PyObject* const __pyx_imported_names[] = {__pyx_mstate_global->__pyx_n_u_TDecodeException}; + __pyx_t_1 = __Pyx_Import(__pyx_mstate_global->__pyx_n_u_thriftpy2_thrift, __pyx_imported_names, 1, NULL, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 12, __pyx_L1_error) + } + __pyx_t_2 = __pyx_t_1; + __Pyx_GOTREF(__pyx_t_2); + { + PyObject* const __pyx_imported_names[] = {__pyx_mstate_global->__pyx_n_u_TDecodeException}; + __pyx_t_3 = 0; { + __pyx_t_4 = __Pyx_ImportFrom(__pyx_t_2, __pyx_imported_names[__pyx_t_3]); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 12, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_imported_names[__pyx_t_3], __pyx_t_4) < (0)) __PYX_ERR(0, 12, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + } + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":49 + * T_BINARY = 18 + * + * BIN_TYPES = (T_BINARY, T_STRING) # <<<<<<<<<<<<<< + * + * +*/ + __pyx_t_2 = __Pyx_PyLong_From___pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType(__pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_BINARY); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 49, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = __Pyx_PyLong_From___pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType(__pyx_e_9thriftpy2_8protocol_5cybin_5cybin_T_STRING); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 49, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = PyTuple_Pack(2, __pyx_t_2, __pyx_t_4); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 49, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_BIN_TYPES, __pyx_t_5) < (0)) __PYX_ERR(0, 49, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":52 + * + * + * class ProtocolError(Exception): # <<<<<<<<<<<<<< + * pass + * +*/ + __pyx_t_5 = PyTuple_Pack(1, ((PyObject *)(((PyTypeObject*)PyExc_Exception)))); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 52, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = __Pyx_PEP560_update_bases(__pyx_t_5); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 52, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_2 = __Pyx_CalculateMetaclass(NULL, __pyx_t_4); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 52, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_6 = __Pyx_Py3MetaclassPrepare(__pyx_t_2, __pyx_t_4, __pyx_mstate_global->__pyx_n_u_ProtocolError, __pyx_mstate_global->__pyx_n_u_ProtocolError, (PyObject *) NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_protocol_cybin_cybin, (PyObject *) NULL); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 52, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + if (__pyx_t_4 != __pyx_t_5) { + if (unlikely((PyDict_SetItemString(__pyx_t_6, "__orig_bases__", __pyx_t_5) < 0))) __PYX_ERR(0, 52, __pyx_L1_error) + } + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = __Pyx_Py3ClassCreate(__pyx_t_2, __pyx_mstate_global->__pyx_n_u_ProtocolError, __pyx_t_4, __pyx_t_6, NULL, 0, 0); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 52, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_5); + #endif + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_ProtocolError, __pyx_t_5) < (0)) __PYX_ERR(0, 52, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":412 + * + * + * cpdef skip(CyTransportBase buf, TType ttype): # <<<<<<<<<<<<<< + * cdef TType v_type, k_type, f_type + * cdef int size +*/ + __pyx_t_4 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_8protocol_5cybin_5cybin_1skip, 0, __pyx_mstate_global->__pyx_n_u_skip, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_protocol_cybin_cybin, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[0])); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 412, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_4); + #endif + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_skip, __pyx_t_4) < (0)) __PYX_ERR(0, 412, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":448 + * + * + * def read_val(CyTransportBase buf, TType ttype, decode_response=True, # <<<<<<<<<<<<<< + * strict_decode=False): + * return c_read_val(buf, ttype, None, decode_response, strict_decode) +*/ + __pyx_t_4 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_8protocol_5cybin_5cybin_3read_val, 0, __pyx_mstate_global->__pyx_n_u_read_val, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_protocol_cybin_cybin, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[1])); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 448, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_4); + #endif + __Pyx_CyFunction_SetDefaultsTuple(__pyx_t_4, __pyx_mstate_global->__pyx_tuple[0]); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_read_val, __pyx_t_4) < (0)) __PYX_ERR(0, 448, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":453 + * + * + * def write_val(CyTransportBase buf, TType ttype, val, spec=None): # <<<<<<<<<<<<<< + * c_write_val(buf, ttype, val, spec) + * +*/ + __pyx_t_4 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_8protocol_5cybin_5cybin_5write_val, 0, __pyx_mstate_global->__pyx_n_u_write_val, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_protocol_cybin_cybin, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[2])); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 453, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_4); + #endif + __Pyx_CyFunction_SetDefaultsTuple(__pyx_t_4, __pyx_mstate_global->__pyx_tuple[1]); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_write_val, __pyx_t_4) < (0)) __PYX_ERR(0, 453, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":472 + * self.strict_decode = strict_decode + * + * def skip(self, ttype): # <<<<<<<<<<<<<< + * skip(self.trans, (ttype)) + * +*/ + __pyx_t_4 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_3skip, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_TCyBinaryProtocol_skip, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_protocol_cybin_cybin, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[3])); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 472, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_4); + #endif + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol, __pyx_mstate_global->__pyx_n_u_skip, __pyx_t_4) < (0)) __PYX_ERR(0, 472, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":475 + * skip(self.trans, (ttype)) + * + * def read_message_begin(self): # <<<<<<<<<<<<<< + * cdef int32_t size, version, seqid + * cdef TType ttype +*/ + __pyx_t_4 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_5read_message_begin, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_TCyBinaryProtocol_read_message_b, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_protocol_cybin_cybin, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[4])); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 475, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_4); + #endif + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol, __pyx_mstate_global->__pyx_n_u_read_message_begin, __pyx_t_4) < (0)) __PYX_ERR(0, 475, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":498 + * return name, ttype, seqid + * + * def read_message_end(self): # <<<<<<<<<<<<<< + * pass + * +*/ + __pyx_t_4 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_7read_message_end, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_TCyBinaryProtocol_read_message_e, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_protocol_cybin_cybin, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[5])); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 498, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_4); + #endif + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol, __pyx_mstate_global->__pyx_n_u_read_message_end, __pyx_t_4) < (0)) __PYX_ERR(0, 498, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":501 + * pass + * + * def write_message_begin(self, name, TType ttype, int32_t seqid): # <<<<<<<<<<<<<< + * cdef int32_t version = VERSION_1 | ttype + * if self.strict_write: +*/ + __pyx_t_4 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_9write_message_begin, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_TCyBinaryProtocol_write_message, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_protocol_cybin_cybin, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[6])); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 501, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_4); + #endif + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol, __pyx_mstate_global->__pyx_n_u_write_message_begin, __pyx_t_4) < (0)) __PYX_ERR(0, 501, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":512 + * write_i32(self.trans, seqid) + * + * def write_message_end(self): # <<<<<<<<<<<<<< + * pass + * +*/ + __pyx_t_4 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_11write_message_end, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_TCyBinaryProtocol_write_message_2, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_protocol_cybin_cybin, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[7])); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 512, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_4); + #endif + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol, __pyx_mstate_global->__pyx_n_u_write_message_end, __pyx_t_4) < (0)) __PYX_ERR(0, 512, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":515 + * pass + * + * def read_struct(self, obj): # <<<<<<<<<<<<<< + * try: + * return read_struct(self.trans, obj, self.decode_response, +*/ + __pyx_t_4 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_13read_struct, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_TCyBinaryProtocol_read_struct, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_protocol_cybin_cybin, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[8])); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 515, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_4); + #endif + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol, __pyx_mstate_global->__pyx_n_u_read_struct, __pyx_t_4) < (0)) __PYX_ERR(0, 515, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":523 + * raise + * + * def write_struct(self, obj): # <<<<<<<<<<<<<< + * try: + * write_struct(self.trans, obj) +*/ + __pyx_t_4 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_15write_struct, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_TCyBinaryProtocol_write_struct, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_protocol_cybin_cybin, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[9])); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 523, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_4); + #endif + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol, __pyx_mstate_global->__pyx_n_u_write_struct, __pyx_t_4) < (0)) __PYX_ERR(0, 523, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * cdef tuple state + * cdef object _dict +*/ + __pyx_t_4 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_17__reduce_cython__, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_TCyBinaryProtocol___reduce_cytho, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_protocol_cybin_cybin, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[10])); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 1, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_4); + #endif + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol, __pyx_mstate_global->__pyx_n_u_reduce_cython, __pyx_t_4) < (0)) __PYX_ERR(2, 1, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "(tree fragment)":16 + * else: + * return __pyx_unpickle_TCyBinaryProtocol, (type(self), 0xf5434e1, state) + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * __pyx_unpickle_TCyBinaryProtocol__set_state(self, __pyx_state) +*/ + __pyx_t_4 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_8protocol_5cybin_5cybin_17TCyBinaryProtocol_19__setstate_cython__, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_TCyBinaryProtocol___setstate_cyt, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_protocol_cybin_cybin, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[11])); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 16, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_4); + #endif + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_8protocol_5cybin_5cybin_TCyBinaryProtocol, __pyx_mstate_global->__pyx_n_u_setstate_cython, __pyx_t_4) < (0)) __PYX_ERR(2, 16, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":531 + * + * + * class TCyBinaryProtocolFactory(object): # <<<<<<<<<<<<<< + * def __init__(self, strict_read=True, strict_write=True, + * decode_response=True, strict_decode=False): +*/ + __pyx_t_4 = __Pyx_PEP560_update_bases(__pyx_mstate_global->__pyx_tuple[3]); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 531, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_2 = __Pyx_CalculateMetaclass(NULL, __pyx_t_4); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 531, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_6 = __Pyx_Py3MetaclassPrepare(__pyx_t_2, __pyx_t_4, __pyx_mstate_global->__pyx_n_u_TCyBinaryProtocolFactory, __pyx_mstate_global->__pyx_n_u_TCyBinaryProtocolFactory, (PyObject *) NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_protocol_cybin_cybin, (PyObject *) NULL); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 531, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + if (__pyx_t_4 != __pyx_mstate_global->__pyx_tuple[3]) { + if (unlikely((PyDict_SetItemString(__pyx_t_6, "__orig_bases__", __pyx_mstate_global->__pyx_tuple[3]) < 0))) __PYX_ERR(0, 531, __pyx_L1_error) + } + + /* "thriftpy2/protocol/cybin/cybin.pyx":532 + * + * class TCyBinaryProtocolFactory(object): + * def __init__(self, strict_read=True, strict_write=True, # <<<<<<<<<<<<<< + * decode_response=True, strict_decode=False): + * self.strict_read = strict_read +*/ + __pyx_t_5 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_8protocol_5cybin_5cybin_24TCyBinaryProtocolFactory_1__init__, 0, __pyx_mstate_global->__pyx_n_u_TCyBinaryProtocolFactory___init, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_protocol_cybin_cybin, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[12])); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 532, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_5); + #endif + __Pyx_CyFunction_SetDefaultsTuple(__pyx_t_5, __pyx_mstate_global->__pyx_tuple[4]); + if (__Pyx_SetNameInClass(__pyx_t_6, __pyx_mstate_global->__pyx_n_u_init, __pyx_t_5) < (0)) __PYX_ERR(0, 532, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":539 + * self.strict_decode = strict_decode + * + * def get_protocol(self, trans): # <<<<<<<<<<<<<< + * return TCyBinaryProtocol( + * trans, self.strict_read, self.strict_write, self.decode_response, +*/ + __pyx_t_5 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_8protocol_5cybin_5cybin_24TCyBinaryProtocolFactory_3get_protocol, 0, __pyx_mstate_global->__pyx_n_u_TCyBinaryProtocolFactory_get_pro, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_protocol_cybin_cybin, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[13])); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 539, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_5); + #endif + if (__Pyx_SetNameInClass(__pyx_t_6, __pyx_mstate_global->__pyx_n_u_get_protocol, __pyx_t_5) < (0)) __PYX_ERR(0, 539, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":531 + * + * + * class TCyBinaryProtocolFactory(object): # <<<<<<<<<<<<<< + * def __init__(self, strict_read=True, strict_write=True, + * decode_response=True, strict_decode=False): +*/ + __pyx_t_5 = __Pyx_Py3ClassCreate(__pyx_t_2, __pyx_mstate_global->__pyx_n_u_TCyBinaryProtocolFactory, __pyx_t_4, __pyx_t_6, NULL, 0, 0); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 531, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_5); + #endif + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_TCyBinaryProtocolFactory, __pyx_t_5) < (0)) __PYX_ERR(0, 531, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "(tree fragment)":4 + * int __Pyx_CheckUnpickleChecksum(long, long, long, long, const char*) except -1 + * int __Pyx_UpdateUnpickledDict(object, object, Py_ssize_t) except -1 + * def __pyx_unpickle_TCyBinaryProtocol(__pyx_type, long __pyx_checksum, tuple __pyx_state): # <<<<<<<<<<<<<< + * cdef object __pyx_result + * __Pyx_CheckUnpickleChecksum(__pyx_checksum, 0xf5434e1, 0xee67e8e, 0x44df354, b'decode_response, strict_decode, strict_read, strict_write, trans') +*/ + __pyx_t_4 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_8protocol_5cybin_5cybin_7__pyx_unpickle_TCyBinaryProtocol, 0, __pyx_mstate_global->__pyx_n_u_pyx_unpickle_TCyBinaryProtocol, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_protocol_cybin_cybin, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[14])); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 4, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_4); + #endif + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_pyx_unpickle_TCyBinaryProtocol, __pyx_t_4) < (0)) __PYX_ERR(2, 4, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "thriftpy2/protocol/cybin/cybin.pyx":1 + * # cython: freethreading_compatible = True # <<<<<<<<<<<<<< + * + * import sys +*/ + __pyx_t_4 = __Pyx_PyDict_NewPresized(0); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_test, __pyx_t_4) < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /*--- Wrapped vars code ---*/ + + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + if (__pyx_m) { + if (__pyx_mstate->__pyx_d && stringtab_initialized) { + __Pyx_AddTraceback("init thriftpy2.protocol.cybin.cybin", __pyx_clineno, __pyx_lineno, __pyx_filename); + } + #if !CYTHON_USE_MODULE_STATE + Py_CLEAR(__pyx_m); + #else + Py_DECREF(__pyx_m); + if (pystate_addmodule_run) { + PyObject *tp, *value, *tb; + PyErr_Fetch(&tp, &value, &tb); + PyState_RemoveModule(&__pyx_moduledef); + PyErr_Restore(tp, value, tb); + } + #endif + } else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_ImportError, "init thriftpy2.protocol.cybin.cybin"); + } + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + #if CYTHON_PEP489_MULTI_PHASE_INIT + return (__pyx_m != NULL) ? 0 : -1; + #else + return __pyx_m; + #endif +} +/* #### Code section: pystring_table ### */ +/* #### Code section: cached_builtins ### */ + +static int __Pyx_InitCachedBuiltins(__pyx_mstatetype *__pyx_mstate) { + CYTHON_UNUSED_VAR(__pyx_mstate); + __pyx_builtin_object = __Pyx_GetBuiltinName(__pyx_mstate->__pyx_n_u_object); if (!__pyx_builtin_object) __PYX_ERR(0, 531, __pyx_L1_error) + + /* Cached unbound methods */ + __pyx_mstate->__pyx_umethod_PyDict_Type_items.type = (PyObject*)&PyDict_Type; + __pyx_mstate->__pyx_umethod_PyDict_Type_items.method_name = &__pyx_mstate->__pyx_n_u_items; + __pyx_mstate->__pyx_umethod_PyDict_Type_pop.type = (PyObject*)&PyDict_Type; + __pyx_mstate->__pyx_umethod_PyDict_Type_pop.method_name = &__pyx_mstate->__pyx_n_u_pop; + __pyx_mstate->__pyx_umethod_PyDict_Type_values.type = (PyObject*)&PyDict_Type; + __pyx_mstate->__pyx_umethod_PyDict_Type_values.method_name = &__pyx_mstate->__pyx_n_u_values; + return 0; + __pyx_L1_error:; + return -1; +} +/* #### Code section: cached_constants ### */ + +static int __Pyx_InitCachedConstants(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); + + /* "thriftpy2/protocol/cybin/cybin.pyx":448 + * + * + * def read_val(CyTransportBase buf, TType ttype, decode_response=True, # <<<<<<<<<<<<<< + * strict_decode=False): + * return c_read_val(buf, ttype, None, decode_response, strict_decode) +*/ + __pyx_mstate_global->__pyx_tuple[0] = PyTuple_Pack(2, ((PyObject*)Py_True), ((PyObject*)Py_False)); if (unlikely(!__pyx_mstate_global->__pyx_tuple[0])) __PYX_ERR(0, 448, __pyx_L1_error) + __Pyx_GOTREF(__pyx_mstate_global->__pyx_tuple[0]); + __Pyx_GIVEREF(__pyx_mstate_global->__pyx_tuple[0]); + + /* "thriftpy2/protocol/cybin/cybin.pyx":453 + * + * + * def write_val(CyTransportBase buf, TType ttype, val, spec=None): # <<<<<<<<<<<<<< + * c_write_val(buf, ttype, val, spec) + * +*/ + __pyx_mstate_global->__pyx_tuple[1] = PyTuple_Pack(1, Py_None); if (unlikely(!__pyx_mstate_global->__pyx_tuple[1])) __PYX_ERR(0, 453, __pyx_L1_error) + __Pyx_GOTREF(__pyx_mstate_global->__pyx_tuple[1]); + __Pyx_GIVEREF(__pyx_mstate_global->__pyx_tuple[1]); + + /* "thriftpy2/protocol/cybin/cybin.pyx":531 + * + * + * class TCyBinaryProtocolFactory(object): # <<<<<<<<<<<<<< + * def __init__(self, strict_read=True, strict_write=True, + * decode_response=True, strict_decode=False): +*/ + __pyx_mstate_global->__pyx_tuple[2] = PyTuple_Pack(1, __pyx_builtin_object); if (unlikely(!__pyx_mstate_global->__pyx_tuple[2])) __PYX_ERR(0, 531, __pyx_L1_error) + __Pyx_GOTREF(__pyx_mstate_global->__pyx_tuple[2]); + __Pyx_GIVEREF(__pyx_mstate_global->__pyx_tuple[2]); + __pyx_mstate_global->__pyx_tuple[3] = PyTuple_Pack(1, __pyx_builtin_object); if (unlikely(!__pyx_mstate_global->__pyx_tuple[3])) __PYX_ERR(0, 531, __pyx_L1_error) + __Pyx_GOTREF(__pyx_mstate_global->__pyx_tuple[3]); + __Pyx_GIVEREF(__pyx_mstate_global->__pyx_tuple[3]); + + /* "thriftpy2/protocol/cybin/cybin.pyx":532 + * + * class TCyBinaryProtocolFactory(object): + * def __init__(self, strict_read=True, strict_write=True, # <<<<<<<<<<<<<< + * decode_response=True, strict_decode=False): + * self.strict_read = strict_read +*/ + __pyx_mstate_global->__pyx_tuple[4] = PyTuple_Pack(4, ((PyObject*)Py_True), ((PyObject*)Py_True), ((PyObject*)Py_True), ((PyObject*)Py_False)); if (unlikely(!__pyx_mstate_global->__pyx_tuple[4])) __PYX_ERR(0, 532, __pyx_L1_error) + __Pyx_GOTREF(__pyx_mstate_global->__pyx_tuple[4]); + __Pyx_GIVEREF(__pyx_mstate_global->__pyx_tuple[4]); + #if CYTHON_IMMORTAL_CONSTANTS + { + PyObject **table = __pyx_mstate->__pyx_tuple; + for (Py_ssize_t i=0; i<5; ++i) { + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + #if PY_VERSION_HEX < 0x030E0000 + if (_Py_IsOwnedByCurrentThread(table[i]) && Py_REFCNT(table[i]) == 1) + #else + if (PyUnstable_Object_IsUniquelyReferenced(table[i])) + #endif + { + Py_SET_REFCNT(table[i], _Py_IMMORTAL_REFCNT_LOCAL); + } + #else + Py_SET_REFCNT(table[i], _Py_IMMORTAL_INITIAL_REFCNT); + #endif + } + } + #endif + __Pyx_RefNannyFinishContext(); + return 0; + __pyx_L1_error:; + __Pyx_RefNannyFinishContext(); + return -1; +} +/* #### Code section: init_constants ### */ + +static int __Pyx_InitConstants(__pyx_mstatetype *__pyx_mstate) { + CYTHON_UNUSED_VAR(__pyx_mstate); + { + const struct { const unsigned int length: 9; } index[] = {{1},{26},{179},{1},{8},{7},{6},{2},{18},{9},{14},{34},{5},{9},{13},{20},{17},{24},{33},{37},{35},{37},{36},{34},{29},{22},{37},{35},{30},{16},{18},{11},{3},{9},{5},{18},{15},{8},{5},{7},{6},{8},{12},{12},{8},{13},{5},{8},{13},{10},{15},{8},{4},{7},{3},{6},{3},{11},{14},{12},{11},{10},{32},{14},{12},{18},{16},{11},{8},{10},{17},{13},{4},{5},{12},{10},{12},{19},{3},{4},{4},{4},{5},{13},{11},{12},{12},{3},{8},{11},{30},{16},{5},{5},{6},{12},{3},{6},{7},{12},{19},{17},{12},{9},{18},{2},{30},{15},{31},{42},{142},{77},{211},{58},{44},{26},{11},{282}}; + #if (CYTHON_COMPRESS_STRINGS) == 2 /* compression: bz2 (1474 bytes) */ +const char* const cstring = "BZh91AY&SY\333\313\335]\000\000\305\377\377\377\357\377\316\357\347\377\377\277\361\377\366\377\377\377\367\300@@@@@@@@@@@@\000@\000P\005>\034\341\265H\330\326\202\234\034\032\232$A\246\2001\014O\024\310i\240i\210\014\232h\006\200\032\003\324\006\236\2202\031= \323\032\200\324\310\023\021\033U?\322hiLL\324=Cj4\000\332\215\000\000\000\000\000\006\200\000\000\032\232a4I\245\032xQ\344\020\320\323@\000\001\221\240h\000\000\000\000\r\003\324\036\220\0100\000L\000\004\300\000\000\000\000\000\000\000\000\000\000\000\001\"\2042\215)\346S&\2154&L\215@\362\206\215\003@\000\036\2404\320\000\000\017P\007\244\031\251\314\202\213\262D]f\320\330?\333\372A\312v\003\226\n\020^W\037[\335\301\361}?\206\037\306\224\245)JR\322\337\367\264\005\334\320\251vj\324.Q\327P\325V\002\233\006\320\306&\315\022\242\212S\316\246\307I\023b\033m&\314*\245S\010\355\2309\267$X\254\347\245d\333M\252\224c\020b}\002\272\262R\342\260\311\004\303z\356\321UP\262\230@\202\270\302P:\030r\240\201P\3562KD\035\0214\241\010W\2161f\2660\327EU\335\374\353c\231L\366`-\004@2,9\343\22011C\"+\214k&\354yw\272\232\266\360\3404\006\220K<%R*h\213\312\303\031\365,\240\304\331P[\325\210T\333\360&\225\272\346m\301\201\304\021\235\316\214jF<\306\205\312%\275\020\r!\251\227\030\241\\\202\273\022\2676\235\234\375=\355\276/X\333\037]\371\374\244~N6|\241\327Go_\315\017c\215\241{\315\240\375x`z\257\0364tF\240\266\323\001|\324\220jo\226d\215\340\273\007\036F\373t\346jF4\236cN)\303\251\003@\005\306\000#\276:\217\347\250j \214\320\321\024P5\372z$\005\253H\024\250\003\247\343FPER$\202\254>\236B]Ei\320\n\023\323U\330M\343\267\206=@z\002\371\3578wO,\242^\210b\035\366*B\033%M\355OM\370\021\345\023\213zM\354,\233\262\027\032\221kA\030Rq\332\306t\024\202\022\202\310\271WeV\322\004hWs&\025\377\364E\240n\233p\317\3614\255\223\256\265\212v\226sw\276;Xa9\253B\226\223\235V\310G\274|""\237\322\270 \200\341\004\2160s\222\032\003\t\0314P\235A\023\022\006\004I!\331\017\373\224\344\322T\004i6%\214\335A\2430g\254\001\376\230O\370\273\222)\302\204\206\336^\352\350"; + PyObject *data = __Pyx_DecompressString(cstring, 1474, 2); + if (unlikely(!data)) __PYX_ERR(0, 1, __pyx_L1_error) + const char* const bytes = __Pyx_PyBytes_AsString(data); + #if !CYTHON_ASSUME_SAFE_MACROS + if (likely(bytes)); else { Py_DECREF(data); __PYX_ERR(0, 1, __pyx_L1_error) } + #endif + #elif (CYTHON_COMPRESS_STRINGS) != 0 /* compression: zlib (1352 bytes) */ +const char* const cstring = "x\332\215TMs\323F\030\216\215)\312`p\234\004\302L\333\211\030R\0023`jp\312WK\307\001C\350!\265!m(\003\263\254\245\265\255\304\226d\355*\2613-\315Q\307=\356QG\037}\364\261\307\034u\324\321?\201\237\320w%\30755)\3158\373\356\356\373\274\037\373\354\263\312mZ\252\355X\314\322\254\246\272G\034jX\246\332 X'\316\246\305\210\312\032\230\251\217\273\254\001\333\006Uu\3224\252\304\301\2144\273*e\216\2411\342H\220\251\226K\345\233\205{\005\025\233\272\352\220\035\2421\252R\267\25251\245\204\252VM\255\272F\223\031\246\312\2726\2419\365yM\355Z\256j\022\242\253\014\272\000\334d\000k\020S\245\204\311\211\272\212M\323b\230Aw\010\302\r\263\276\252\352\206\003E\214=\"\243\237\342&%\271\037\261\256#\000\022\335\240\270\332$\304\224c]3\314=\3344\364\361\001\277\001\177\354\323\277\227\2470\353\324r\035\215S\371c\320'K\307\220Q\355'D\263tR\352h\304\226\232\302\264kj\206\225\323,\307rA\242\204V\243`\2515Ruk\010E\252\224\206`Sk\002\002n\0051\007k\244\212\265]=J\007LS\3332)AH\227\02286\272\245!\350)\202\240\232k\302j\362\316\242UL?:\276ldP4n\006\372nA\355\026\206\222\360\327\"\014\217\332\201\205\245\273\315(\260\345XP\004\304L\"\207\211[d<\222}\204\254\352\016\374\340\305\330\226\215\2408\261\261\023\005\202\250\221\326 \332.u[\361\n\316\3416Y<\0375&\247\222\214x\346\232\266\241\355B\335)\232c\377\036\223oK&o\273\270\03171-\240\177\313eB\034\321\024\336\354X\275hJ\307\343\r\322\221\002n\326(i\033z\244\345\321\261a\246\223\032\216\216B'(\236R;5:\3248 R\177\324&Z\344\214?n(\276\331\321Bv5\232Fj\212?\035\021/\224v\201v\271\005c\364\021A2\325\370{\222;\276\355\\\374%\211\306\177\274""\361\014\364dR&\323\271\266\016=\270 \245\343f\201\014\370\271\204\216\276a#\003z\251Y\237x\"S\017bR\376\361\034\322\0053k\375J\230\312xm~\232o\213\222\237=,\036\026C%\023dT?\021\246\027x\201\277\367\267z\313\203\324\240\030\246\347xBz\323^\321\333\342\227\304%\t\017\225\3310}I$\304\242x\345W\302\314\234\204}\301k\002\360\347F\356\005\376P`\301\374{\275\265~\252_\014\227\257\370\371)\344\007efv\316\353\360\266H\301\216r\326[\343I~9L_\344D\334\026\2250\235\001'\025\227\303\271\213\274\345\347\203\225\373\203\371A~\010\311\037\210\212\320\375k=\000/\362\r8\305\274\017\373\031\217\361\374\010\354\027%\356\007?\341/\372\257z\225\030\267\341\027\341h\331\2412\307\225\250\377\312P\311x{\300C\304\301\2628\350\315\367\362\262\223\202\327\016\323\027x\205\353\342\232\017U\226\242&7\374\237zx8\271\230\000\r\225,\317\362\025\336\020\3700\001G;}\336\333\n\262W\374B\260z\267\317\006\217\216\026\217P\360\346]\360\016\207\251\264\367\214\347\371Sq\303\207\305\231\303=o\233\227d;\2412\017\004(P`\010\003\013\276\274\321{\326_\033\234\032\024\006\177\036\325\203_^\007\257\337\006oq\200\315\300t\003\367 8\370\343\303\314\314\373\304z\022\314z\262,M9\271-\315v\362\2154o\222H\032\224\324\244\321\222;\322\354$\333\322\264\223NR\226oG\327\177\273\277\322\307\375\375\301\356\321RP\226\304Lne\017\023\303\324\262h\007\352\267\375\263\203\207\177\355\006\225\027aj!XX\3617zE\340\027\322\374\316\357\302])w\372\371\240\260qt>\370u;L\235\365\362Aj)X\272\336\313\206\331U\277-\245\364\263\000\212\323A\372+y\351`!md\277\026\225`\346V\257\035\236;/\003\037\000\261D\334\365\257\006\327\356\017\240~\230\002_\377\213\376\210]\005X{\311\317\200>\256\372\247@\\p\247\t\236\rg3\036\225\024\236\270\272*N\211\357\374\005\277\370\321\356uqG\324\374\307\262\301L\244\310D\250\\\210\032\310O\205e\371\222P@X\331\tl\332+\361\013\034\363v\364d\344t\\{\002\376?#\247R\314J\231mG\362\215^\305>\327D6\234\313JU\027ye\034\3607M\006\330q"; + PyObject *data = __Pyx_DecompressString(cstring, 1352, 1); + if (unlikely(!data)) __PYX_ERR(0, 1, __pyx_L1_error) + const char* const bytes = __Pyx_PyBytes_AsString(data); + #if !CYTHON_ASSUME_SAFE_MACROS + if (likely(bytes)); else { Py_DECREF(data); __PYX_ERR(0, 1, __pyx_L1_error) } + #endif + #else /* compression: none (2523 bytes) */ +const char* const bytes = ".No protocol version headerNote that Cython is deliberately stricter than PEP-484 and rejects subclasses of builtin types. If you need to pass subclasses then set the 'annotation_typing' directive to False.?add_notedisableenablegcinvalid version %disenabledthriftpy2/protocol/cybin/cybin.pyxutf-8BIN_TYPESProtocolError__Pyx_PyDict_NextRefTCyBinaryProtocolTCyBinaryProtocolFactoryTCyBinaryProtocolFactory.__init__TCyBinaryProtocolFactory.get_protocolTCyBinaryProtocol.__reduce_cython__TCyBinaryProtocol.__setstate_cython__TCyBinaryProtocol.read_message_beginTCyBinaryProtocol.read_message_endTCyBinaryProtocol.read_structTCyBinaryProtocol.skipTCyBinaryProtocol.write_message_beginTCyBinaryProtocol.write_message_endTCyBinaryProtocol.write_structTDecodeExceptionasyncio.coroutinesbinary_typebuf__class__cleancline_in_tracebackdecode_response__dict___dict__doc__encode__func__get_protocol__getstate____init___is_coroutineitems__main____metaclass____module____mro_entries____name__name__new__objobjectpop__prepare____pyx_checksum__pyx_result__pyx_state__pyx_type__pyx_unpickle_TCyBinaryProtocol__pyx_vtable____qualname__read_message_beginread_message_endread_structread_val__reduce____reduce_cython____reduce_ex__selfseqid__set_name__setdefault__setstate____setstate_cython__sixsizeskipspecstatestrict_decodestrict_readstrict_writestring_typessys__test__thrift_specthriftpy2.protocol.cybin.cybinthriftpy2.thrifttransttypeupdateuse_setstatevalvaluesversionversion_infowrite_message_beginwrite_message_endwrite_structwrite_val\320\0005\260Q\330\004\017\210q\220\005\220W\230E\240\021\200A\200A\330\010\017\320\017 \240\001\330\014\023\2204\220~\240T\250\037\270\004\270A\330\014\020\220\001\200A\330\010\014\210A\210T\220\030\230\030\240\021\200A\330\010\t\330\014\030\230\001\230\024\230X\240Q\330\017\020\330\014\020\220\006\220f\230A\330\014\r\200A\330\010\t\330\014\023\220;\230a\230t\2408\2505\260\004\260A\330\037#\2401\330\017\020\330\014\020\220\006\220f\230A\330\014\r\200A\360\010""\000\t\020\210x\220q\230\004\230A\330\010\013\2105\220\002\220!\330\014\026\220e\2302\230Q\330\014\017\210x\220s\230!\330\020\026\220m\2401\320$9\270\022\2701\340\014\023\220:\230Q\230d\240(\250!\330\014\024\220H\230E\240\022\2401\340\014\017\210t\2201\330\020\026\220m\2401\240A\340\014\023\220=\240\001\240\024\240X\250Q\330\014\024\220H\230H\240A\240T\250\021\340\010\020\220\010\230\001\230\024\230Q\340\010\017\210v\220W\230A\200A\330\010\037\230z\250\022\2501\330\010\013\2104\210q\330\014\025\220Q\220d\230(\240!\330\014\027\220q\230\004\230H\240J\250a\340\014\027\220q\230\004\230H\240J\250a\330\014\025\220Q\220d\230(\240!\340\010\021\220\021\220$\220h\230a\200\001\360\010\000\005\016\210T\320\021#\2404\320'7\260t\270>\310\024\310_\320\\`\320`a\330\004\014\210G\2201\220F\230,\240a\330\004\007\200v\210W\220E\230\024\230Q\330\010\022\220!\330\010\027\220q\340\010\027\220t\320\033,\250G\2605\270\003\2704\270\177\310g\320UZ\320Z]\320]a\320an\320nu\320uz\320z}\360\000\000~\001B\002\360\000\000B\002P\002\360\000\000P\002W\002\360\000\000W\002\\\002\360\000\000\\\002_\002\360\000\000_\002c\002\360\000\000c\002j\002\360\000\000j\002q\002\360\000\000q\002r\002\330\004\007\200q\330\010\017\320\0172\260$\260a\260w\270k\310\027\320PQ\340\010\017\320\0172\260$\260a\260w\270k\310\021\200\001\340\004\037\230q\320 0\260\013\270;\300k\320QR\330\004\023\320\023$\240H\250A\250Q\330\004\007\200|\2207\230!\330\0103\2601\3204H\310\016\320VW\330\004\013\2101\320\004\027\320\027)\250\021\330\021'\240q\330\010\014\210O\2301\330\010\014\320\014\034\230A\330\010\014\320\014\037\230q\330\010\014\320\014\035\230Q\320\000/\250q\330\r\016\330\004\013\210:\220Q\220e\2307\240&\320(9\270\021\200\001\330\004/\250q\260\006\260a\200\001\360\010\000\005\010\200v\210S\220\007\220s\230&\240\003\2401\330\010\020\220\001\220\021\330\t\017\210s\220!\330\010\020\220\001\220\021\330\t\017\210s\220!\330\010\020\220\001\220\021\330\t\017\210s\220&\230\003\2306\240\023\240A\330\010\020\220\001\220\021\330\t\017""\210s\220)\2303\230f\240C\240q\330\010\017\210x\220q\230\001\330\010\025\220Q\220e\2301\330\t\017\210s\220&\230\003\2306\240\023\240A\330\010\021\220\027\230\010\240\001\240\021\330\010\017\210x\220q\230\001\330\010\014\210E\220\025\220a\220q\330\014\020\220\001\220\025\220a\330\t\017\210s\220!\330\010\021\220\027\230\010\240\001\240\021\330\010\021\220\027\230\010\240\001\240\021\330\010\017\210x\220q\230\001\330\010\014\210E\220\025\220a\220q\330\014\020\220\001\220\025\220a\330\014\020\220\001\220\025\220a\330\t\017\210s\220!\330\010\t\330\014\025\220W\230H\240A\240Q\330\014\017\210w\220c\230\021\330\020\021\330\014\024\220A\220Q\330\014\020\220\001\220\025\220a"; + PyObject *data = NULL; + CYTHON_UNUSED_VAR(__Pyx_DecompressString); + #endif + PyObject **stringtab = __pyx_mstate->__pyx_string_tab; + Py_ssize_t pos = 0; + for (int i = 0; i < 104; i++) { + Py_ssize_t bytes_length = index[i].length; + PyObject *string = PyUnicode_DecodeUTF8(bytes + pos, bytes_length, NULL); + if (likely(string) && i >= 13) PyUnicode_InternInPlace(&string); + if (unlikely(!string)) { + Py_XDECREF(data); + __PYX_ERR(0, 1, __pyx_L1_error) + } + stringtab[i] = string; + pos += bytes_length; + } + for (int i = 104; i < 118; i++) { + Py_ssize_t bytes_length = index[i].length; + PyObject *string = PyBytes_FromStringAndSize(bytes + pos, bytes_length); + stringtab[i] = string; + pos += bytes_length; + if (unlikely(!string)) { + Py_XDECREF(data); + __PYX_ERR(0, 1, __pyx_L1_error) + } + } + Py_XDECREF(data); + for (Py_ssize_t i = 0; i < 118; i++) { + if (unlikely(PyObject_Hash(stringtab[i]) == -1)) { + __PYX_ERR(0, 1, __pyx_L1_error) + } + } + #if CYTHON_IMMORTAL_CONSTANTS + { + PyObject **table = stringtab + 104; + for (Py_ssize_t i=0; i<14; ++i) { + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + #if PY_VERSION_HEX < 0x030E0000 + if (_Py_IsOwnedByCurrentThread(table[i]) && Py_REFCNT(table[i]) == 1) + #else + if (PyUnstable_Object_IsUniquelyReferenced(table[i])) + #endif + { + Py_SET_REFCNT(table[i], _Py_IMMORTAL_REFCNT_LOCAL); + } + #else + Py_SET_REFCNT(table[i], _Py_IMMORTAL_INITIAL_REFCNT); + #endif + } + } + #endif + } + { + PyObject **numbertab = __pyx_mstate->__pyx_number_tab + 0; + int8_t const cint_constants_1[] = {2}; + int32_t const cint_constants_4[] = {257176801L}; + for (int i = 0; i < 2; i++) { + numbertab[i] = PyLong_FromLong((i < 1 ? cint_constants_1[i - 0] : cint_constants_4[i - 1])); + if (unlikely(!numbertab[i])) __PYX_ERR(0, 1, __pyx_L1_error) + } + } + #if CYTHON_IMMORTAL_CONSTANTS + { + PyObject **table = __pyx_mstate->__pyx_number_tab; + for (Py_ssize_t i=0; i<2; ++i) { + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + #if PY_VERSION_HEX < 0x030E0000 + if (_Py_IsOwnedByCurrentThread(table[i]) && Py_REFCNT(table[i]) == 1) + #else + if (PyUnstable_Object_IsUniquelyReferenced(table[i])) + #endif + { + Py_SET_REFCNT(table[i], _Py_IMMORTAL_REFCNT_LOCAL); + } + #else + Py_SET_REFCNT(table[i], _Py_IMMORTAL_INITIAL_REFCNT); + #endif + } + } + #endif + return 0; + __pyx_L1_error:; + return -1; +} +/* #### Code section: init_codeobjects ### */ +typedef struct { + unsigned int argcount : 3; + unsigned int num_posonly_args : 1; + unsigned int num_kwonly_args : 1; + unsigned int nlocals : 3; + unsigned int flags : 10; + unsigned int first_line : 10; +} __Pyx_PyCode_New_function_description; +/* NewCodeObj.proto */ +static PyObject* __Pyx_PyCode_New( + const __Pyx_PyCode_New_function_description descr, + PyObject * const *varnames, + PyObject *filename, + PyObject *funcname, + PyObject *line_table, + PyObject *tuple_dedup_map +); + + +static int __Pyx_CreateCodeObjects(__pyx_mstatetype *__pyx_mstate) { + PyObject* tuple_dedup_map = PyDict_New(); + if (unlikely(!tuple_dedup_map)) return -1; + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 412}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_buf, __pyx_mstate->__pyx_n_u_ttype}; + __pyx_mstate_global->__pyx_codeobj_tab[0] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_thriftpy2_protocol_cybin_cybin_p, __pyx_mstate->__pyx_n_u_skip, __pyx_mstate->__pyx_kp_b_iso88591_vS_s_1_s_s_s_6_A_s_3fCq_xq_Qe1, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[0])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {4, 0, 0, 4, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 448}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_buf, __pyx_mstate->__pyx_n_u_ttype, __pyx_mstate->__pyx_n_u_decode_response, __pyx_mstate->__pyx_n_u_strict_decode}; + __pyx_mstate_global->__pyx_codeobj_tab[1] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_thriftpy2_protocol_cybin_cybin_p, __pyx_mstate->__pyx_n_u_read_val, __pyx_mstate->__pyx_kp_b_iso88591_q_Qe7_9, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[1])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {4, 0, 0, 4, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 453}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_buf, __pyx_mstate->__pyx_n_u_ttype, __pyx_mstate->__pyx_n_u_val, __pyx_mstate->__pyx_n_u_spec}; + __pyx_mstate_global->__pyx_codeobj_tab[2] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_thriftpy2_protocol_cybin_cybin_p, __pyx_mstate->__pyx_n_u_write_val, __pyx_mstate->__pyx_kp_b_iso88591_5Q_q_WE, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[2])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 472}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_ttype}; + __pyx_mstate_global->__pyx_codeobj_tab[3] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_thriftpy2_protocol_cybin_cybin_p, __pyx_mstate->__pyx_n_u_skip, __pyx_mstate->__pyx_kp_b_iso88591_A_AT, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[3])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 6, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 475}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_size, __pyx_mstate->__pyx_n_u_version, __pyx_mstate->__pyx_n_u_seqid, __pyx_mstate->__pyx_n_u_ttype, __pyx_mstate->__pyx_n_u_name_2}; + __pyx_mstate_global->__pyx_codeobj_tab[4] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_thriftpy2_protocol_cybin_cybin_p, __pyx_mstate->__pyx_n_u_read_message_begin, __pyx_mstate->__pyx_kp_b_iso88591_A_xq_A_5_e2Q_xs_m1_9_1_Qd_HE_1_t, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[4])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 498}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[5] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_thriftpy2_protocol_cybin_cybin_p, __pyx_mstate->__pyx_n_u_read_message_end, __pyx_mstate->__pyx_kp_b_iso88591_A, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[5])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {4, 0, 0, 5, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 501}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_name_2, __pyx_mstate->__pyx_n_u_ttype, __pyx_mstate->__pyx_n_u_seqid, __pyx_mstate->__pyx_n_u_version}; + __pyx_mstate_global->__pyx_codeobj_tab[6] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_thriftpy2_protocol_cybin_cybin_p, __pyx_mstate->__pyx_n_u_write_message_begin, __pyx_mstate->__pyx_kp_b_iso88591_A_z_1_4q_Qd_q_HJa_q_HJa_Qd_ha, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[6])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 512}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[7] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_thriftpy2_protocol_cybin_cybin_p, __pyx_mstate->__pyx_n_u_write_message_end, __pyx_mstate->__pyx_kp_b_iso88591_A, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[7])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 515}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_obj}; + __pyx_mstate_global->__pyx_codeobj_tab[8] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_thriftpy2_protocol_cybin_cybin_p, __pyx_mstate->__pyx_n_u_read_struct, __pyx_mstate->__pyx_kp_b_iso88591_A_at85_A_1_fA, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[8])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 523}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_obj}; + __pyx_mstate_global->__pyx_codeobj_tab[9] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_thriftpy2_protocol_cybin_cybin_p, __pyx_mstate->__pyx_n_u_write_struct, __pyx_mstate->__pyx_kp_b_iso88591_A_XQ_fA, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[9])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 4, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 1}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_state, __pyx_mstate->__pyx_n_u_dict_2, __pyx_mstate->__pyx_n_u_use_setstate}; + __pyx_mstate_global->__pyx_codeobj_tab[10] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_stringsource, __pyx_mstate->__pyx_n_u_reduce_cython, __pyx_mstate->__pyx_kp_b_iso88591_T_4_7t___a_G1F_a_vWE_Q_q_t_G5_4, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[10])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 16}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_pyx_state}; + __pyx_mstate_global->__pyx_codeobj_tab[11] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_stringsource, __pyx_mstate->__pyx_n_u_setstate_cython, __pyx_mstate->__pyx_kp_b_iso88591_q_a, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[11])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {5, 0, 0, 5, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 532}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_strict_read, __pyx_mstate->__pyx_n_u_strict_write, __pyx_mstate->__pyx_n_u_decode_response, __pyx_mstate->__pyx_n_u_strict_decode}; + __pyx_mstate_global->__pyx_codeobj_tab[12] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_thriftpy2_protocol_cybin_cybin_p, __pyx_mstate->__pyx_n_u_init, __pyx_mstate->__pyx_kp_b_iso88591_q_O1_A_q_Q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[12])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 539}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_trans}; + __pyx_mstate_global->__pyx_codeobj_tab[13] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_thriftpy2_protocol_cybin_cybin_p, __pyx_mstate->__pyx_n_u_get_protocol, __pyx_mstate->__pyx_kp_b_iso88591_A_4_T_A, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[13])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {3, 0, 0, 4, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 4}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_pyx_type, __pyx_mstate->__pyx_n_u_pyx_checksum, __pyx_mstate->__pyx_n_u_pyx_state, __pyx_mstate->__pyx_n_u_pyx_result}; + __pyx_mstate_global->__pyx_codeobj_tab[14] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_stringsource, __pyx_mstate->__pyx_n_u_pyx_unpickle_TCyBinaryProtocol, __pyx_mstate->__pyx_kp_b_iso88591_q_0_kQR_HAQ_7_314H_VW_1, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[14])) goto bad; + } + Py_DECREF(tuple_dedup_map); + return 0; + bad: + Py_DECREF(tuple_dedup_map); + return -1; +} +/* #### Code section: init_globals ### */ + +static int __Pyx_InitGlobals(void) { + /* PythonCompatibility.init */ + if (likely(__Pyx_init_co_variables() == 0)); else + + if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 1, __pyx_L1_error) + + /* CommonTypesMetaclass.init */ + if (likely(__pyx_CommonTypesMetaclass_init(__pyx_m) == 0)); else + + if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 1, __pyx_L1_error) + + /* CachedMethodType.init */ + #if CYTHON_COMPILING_IN_LIMITED_API + { + PyObject *typesModule=NULL; + typesModule = PyImport_ImportModule("types"); + if (typesModule) { + __pyx_mstate_global->__Pyx_CachedMethodType = PyObject_GetAttrString(typesModule, "MethodType"); + Py_DECREF(typesModule); + } + } // error handling follows + #endif + + if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 1, __pyx_L1_error) + + /* CythonFunctionShared.init */ + if (likely(__pyx_CyFunction_init(__pyx_m) == 0)); else + + if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 1, __pyx_L1_error) + + return 0; + __pyx_L1_error:; + return -1; +} +/* #### Code section: cleanup_globals ### */ +/* #### Code section: cleanup_module ### */ +/* #### Code section: main_method ### */ +/* #### Code section: utility_code_pragmas ### */ +#ifdef _MSC_VER +#pragma warning( push ) +/* Warning 4127: conditional expression is constant + * Cython uses constant conditional expressions to allow in inline functions to be optimized at + * compile-time, so this warning is not useful + */ +#pragma warning( disable : 4127 ) +#endif + + + +/* #### Code section: utility_code_def ### */ + +/* --- Runtime support code --- */ +/* Refnanny */ +#if CYTHON_REFNANNY +static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { + PyObject *m = NULL, *p = NULL; + void *r = NULL; + m = PyImport_ImportModule(modname); + if (!m) goto end; + p = PyObject_GetAttrString(m, "RefNannyAPI"); + if (!p) goto end; + r = PyLong_AsVoidPtr(p); +end: + Py_XDECREF(p); + Py_XDECREF(m); + return (__Pyx_RefNannyAPIStruct *)r; +} +#endif + +/* PyErrExceptionMatches (used by PyObjectGetAttrStrNoError) */ +#if CYTHON_FAST_THREAD_STATE +static int __Pyx_PyErr_ExceptionMatchesTuple(PyObject *exc_type, PyObject *tuple) { + Py_ssize_t i, n; + n = PyTuple_GET_SIZE(tuple); + for (i=0; i= 0x030C00A6 + PyObject *current_exception = tstate->current_exception; + if (unlikely(!current_exception)) return 0; + exc_type = (PyObject*) Py_TYPE(current_exception); + if (exc_type == err) return 1; +#else + exc_type = tstate->curexc_type; + if (exc_type == err) return 1; + if (unlikely(!exc_type)) return 0; +#endif + #if CYTHON_AVOID_BORROWED_REFS + Py_INCREF(exc_type); + #endif + if (unlikely(PyTuple_Check(err))) { + result = __Pyx_PyErr_ExceptionMatchesTuple(exc_type, err); + } else { + result = __Pyx_PyErr_GivenExceptionMatches(exc_type, err); + } + #if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(exc_type); + #endif + return result; +} +#endif + +/* PyErrFetchRestore (used by PyObjectGetAttrStrNoError) */ +#if CYTHON_FAST_THREAD_STATE +static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { +#if PY_VERSION_HEX >= 0x030C00A6 + PyObject *tmp_value; + assert(type == NULL || (value != NULL && type == (PyObject*) Py_TYPE(value))); + if (value) { + #if CYTHON_COMPILING_IN_CPYTHON + if (unlikely(((PyBaseExceptionObject*) value)->traceback != tb)) + #endif + PyException_SetTraceback(value, tb); + } + tmp_value = tstate->current_exception; + tstate->current_exception = value; + Py_XDECREF(tmp_value); + Py_XDECREF(type); + Py_XDECREF(tb); +#else + PyObject *tmp_type, *tmp_value, *tmp_tb; + tmp_type = tstate->curexc_type; + tmp_value = tstate->curexc_value; + tmp_tb = tstate->curexc_traceback; + tstate->curexc_type = type; + tstate->curexc_value = value; + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#endif +} +static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { +#if PY_VERSION_HEX >= 0x030C00A6 + PyObject* exc_value; + exc_value = tstate->current_exception; + tstate->current_exception = 0; + *value = exc_value; + *type = NULL; + *tb = NULL; + if (exc_value) { + *type = (PyObject*) Py_TYPE(exc_value); + Py_INCREF(*type); + #if CYTHON_COMPILING_IN_CPYTHON + *tb = ((PyBaseExceptionObject*) exc_value)->traceback; + Py_XINCREF(*tb); + #else + *tb = PyException_GetTraceback(exc_value); + #endif + } +#else + *type = tstate->curexc_type; + *value = tstate->curexc_value; + *tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; +#endif +} +#endif + +/* PyObjectGetAttrStr (used by PyObjectGetAttrStrNoError) */ +#if CYTHON_USE_TYPE_SLOTS +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { + PyTypeObject* tp = Py_TYPE(obj); + if (likely(tp->tp_getattro)) + return tp->tp_getattro(obj, attr_name); + return PyObject_GetAttr(obj, attr_name); +} +#endif + +/* PyObjectGetAttrStrNoError (used by GetBuiltinName) */ +#if __PYX_LIMITED_VERSION_HEX < 0x030d0000 +static void __Pyx_PyObject_GetAttrStr_ClearAttributeError(void) { + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + if (likely(__Pyx_PyErr_ExceptionMatches(PyExc_AttributeError))) + __Pyx_PyErr_Clear(); +} +#endif +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStrNoError(PyObject* obj, PyObject* attr_name) { + PyObject *result; +#if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + (void) PyObject_GetOptionalAttr(obj, attr_name, &result); + return result; +#else +#if CYTHON_COMPILING_IN_CPYTHON && CYTHON_USE_TYPE_SLOTS + PyTypeObject* tp = Py_TYPE(obj); + if (likely(tp->tp_getattro == PyObject_GenericGetAttr)) { + return _PyObject_GenericGetAttrWithDict(obj, attr_name, NULL, 1); + } +#endif + result = __Pyx_PyObject_GetAttrStr(obj, attr_name); + if (unlikely(!result)) { + __Pyx_PyObject_GetAttrStr_ClearAttributeError(); + } + return result; +#endif +} + +/* GetBuiltinName */ +static PyObject *__Pyx_GetBuiltinName(PyObject *name) { + PyObject* result = __Pyx_PyObject_GetAttrStrNoError(__pyx_mstate_global->__pyx_b, name); + if (unlikely(!result) && !PyErr_Occurred()) { + PyErr_Format(PyExc_NameError, + "name '%U' is not defined", name); + } + return result; +} + +/* GetItemInt */ +static PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) { + PyObject *r; + if (unlikely(!j)) return NULL; + r = PyObject_GetItem(o, j); + Py_DECREF(j); + return r; +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck, int unsafe_shared) { + CYTHON_MAYBE_UNUSED_VAR(unsafe_shared); +#if CYTHON_ASSUME_SAFE_SIZE + Py_ssize_t wrapped_i = i; + if (wraparound & unlikely(i < 0)) { + wrapped_i += PyList_GET_SIZE(o); + } + if ((CYTHON_AVOID_BORROWED_REFS || CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS || !CYTHON_ASSUME_SAFE_MACROS)) { + return __Pyx_PyList_GetItemRefFast(o, wrapped_i, unsafe_shared); + } else + if ((!boundscheck) || likely(__Pyx_is_valid_index(wrapped_i, PyList_GET_SIZE(o)))) { + return __Pyx_NewRef(PyList_GET_ITEM(o, wrapped_i)); + } + return __Pyx_GetItemInt_Generic(o, PyLong_FromSsize_t(i)); +#else + (void)wraparound; + (void)boundscheck; + return PySequence_GetItem(o, i); +#endif +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck, int unsafe_shared) { + CYTHON_MAYBE_UNUSED_VAR(unsafe_shared); +#if CYTHON_ASSUME_SAFE_SIZE && CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + Py_ssize_t wrapped_i = i; + if (wraparound & unlikely(i < 0)) { + wrapped_i += PyTuple_GET_SIZE(o); + } + if ((!boundscheck) || likely(__Pyx_is_valid_index(wrapped_i, PyTuple_GET_SIZE(o)))) { + return __Pyx_NewRef(PyTuple_GET_ITEM(o, wrapped_i)); + } + return __Pyx_GetItemInt_Generic(o, PyLong_FromSsize_t(i)); +#else + (void)wraparound; + (void)boundscheck; + return PySequence_GetItem(o, i); +#endif +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, int is_list, + int wraparound, int boundscheck, int unsafe_shared) { + CYTHON_MAYBE_UNUSED_VAR(unsafe_shared); +#if CYTHON_ASSUME_SAFE_MACROS && CYTHON_ASSUME_SAFE_SIZE + if (is_list || PyList_CheckExact(o)) { + Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyList_GET_SIZE(o); + if ((CYTHON_AVOID_BORROWED_REFS || CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS)) { + return __Pyx_PyList_GetItemRefFast(o, n, unsafe_shared); + } else if ((!boundscheck) || (likely(__Pyx_is_valid_index(n, PyList_GET_SIZE(o))))) { + return __Pyx_NewRef(PyList_GET_ITEM(o, n)); + } + } else + #if !CYTHON_AVOID_BORROWED_REFS + if (PyTuple_CheckExact(o)) { + Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyTuple_GET_SIZE(o); + if ((!boundscheck) || likely(__Pyx_is_valid_index(n, PyTuple_GET_SIZE(o)))) { + return __Pyx_NewRef(PyTuple_GET_ITEM(o, n)); + } + } else + #endif +#endif +#if CYTHON_USE_TYPE_SLOTS && !CYTHON_COMPILING_IN_PYPY + { + PyMappingMethods *mm = Py_TYPE(o)->tp_as_mapping; + PySequenceMethods *sm = Py_TYPE(o)->tp_as_sequence; + if (!is_list && mm && mm->mp_subscript) { + PyObject *r, *key = PyLong_FromSsize_t(i); + if (unlikely(!key)) return NULL; + r = mm->mp_subscript(o, key); + Py_DECREF(key); + return r; + } + if (is_list || likely(sm && sm->sq_item)) { + if (wraparound && unlikely(i < 0) && likely(sm->sq_length)) { + Py_ssize_t l = sm->sq_length(o); + if (likely(l >= 0)) { + i += l; + } else { + if (!PyErr_ExceptionMatches(PyExc_OverflowError)) + return NULL; + PyErr_Clear(); + } + } + return sm->sq_item(o, i); + } + } +#else + if (is_list || !PyMapping_Check(o)) { + return PySequence_GetItem(o, i); + } +#endif + (void)wraparound; + (void)boundscheck; + return __Pyx_GetItemInt_Generic(o, PyLong_FromSsize_t(i)); +} + +/* IterFinish (used by dict_iter) */ +static CYTHON_INLINE int __Pyx_IterFinish(void) { + PyObject* exc_type; + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + exc_type = __Pyx_PyErr_CurrentExceptionType(); + if (unlikely(exc_type)) { + if (unlikely(!__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) + return -1; + __Pyx_PyErr_Clear(); + return 0; + } + return 0; +} + +/* PyObjectCall (used by PyObjectFastCall) */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) { + PyObject *result; + ternaryfunc call = Py_TYPE(func)->tp_call; + if (unlikely(!call)) + return PyObject_Call(func, arg, kw); + if (unlikely(Py_EnterRecursiveCall(" while calling a Python object"))) + return NULL; + result = (*call)(func, arg, kw); + Py_LeaveRecursiveCall(); + if (unlikely(!result) && unlikely(!PyErr_Occurred())) { + PyErr_SetString( + PyExc_SystemError, + "NULL result without error in PyObject_Call"); + } + return result; +} +#endif + +/* PyObjectCallMethO (used by PyObjectFastCall) */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg) { + PyObject *self, *result; + PyCFunction cfunc; + cfunc = __Pyx_CyOrPyCFunction_GET_FUNCTION(func); + self = __Pyx_CyOrPyCFunction_GET_SELF(func); + if (unlikely(Py_EnterRecursiveCall(" while calling a Python object"))) + return NULL; + result = cfunc(self, arg); + Py_LeaveRecursiveCall(); + if (unlikely(!result) && unlikely(!PyErr_Occurred())) { + PyErr_SetString( + PyExc_SystemError, + "NULL result without error in PyObject_Call"); + } + return result; +} +#endif + +/* PyObjectFastCall (used by PyObjectCallNoArg) */ +#if PY_VERSION_HEX < 0x03090000 || CYTHON_COMPILING_IN_LIMITED_API +static PyObject* __Pyx_PyObject_FastCall_fallback(PyObject *func, PyObject * const*args, size_t nargs, PyObject *kwargs) { + PyObject *argstuple; + PyObject *result = 0; + size_t i; + argstuple = PyTuple_New((Py_ssize_t)nargs); + if (unlikely(!argstuple)) return NULL; + for (i = 0; i < nargs; i++) { + Py_INCREF(args[i]); + if (__Pyx_PyTuple_SET_ITEM(argstuple, (Py_ssize_t)i, args[i]) != (0)) goto bad; + } + result = __Pyx_PyObject_Call(func, argstuple, kwargs); + bad: + Py_DECREF(argstuple); + return result; +} +#endif +#if CYTHON_VECTORCALL && !CYTHON_COMPILING_IN_LIMITED_API + #if PY_VERSION_HEX < 0x03090000 + #define __Pyx_PyVectorcall_Function(callable) _PyVectorcall_Function(callable) + #elif CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE vectorcallfunc __Pyx_PyVectorcall_Function(PyObject *callable) { + PyTypeObject *tp = Py_TYPE(callable); + #if defined(__Pyx_CyFunction_USED) + if (__Pyx_CyFunction_CheckExact(callable)) { + return __Pyx_CyFunction_func_vectorcall(callable); + } + #endif + if (!PyType_HasFeature(tp, Py_TPFLAGS_HAVE_VECTORCALL)) { + return NULL; + } + assert(PyCallable_Check(callable)); + Py_ssize_t offset = tp->tp_vectorcall_offset; + assert(offset > 0); + vectorcallfunc ptr; + memcpy(&ptr, (char *) callable + offset, sizeof(ptr)); + return ptr; +} + #else + #define __Pyx_PyVectorcall_Function(callable) PyVectorcall_Function(callable) + #endif +#endif +static CYTHON_INLINE PyObject* __Pyx_PyObject_FastCallDict(PyObject *func, PyObject *const *args, size_t _nargs, PyObject *kwargs) { + Py_ssize_t nargs = __Pyx_PyVectorcall_NARGS(_nargs); +#if CYTHON_COMPILING_IN_CPYTHON + if (nargs == 0 && kwargs == NULL) { + if (__Pyx_CyOrPyCFunction_Check(func) && likely( __Pyx_CyOrPyCFunction_GET_FLAGS(func) & METH_NOARGS)) + return __Pyx_PyObject_CallMethO(func, NULL); + } + else if (nargs == 1 && kwargs == NULL) { + if (__Pyx_CyOrPyCFunction_Check(func) && likely( __Pyx_CyOrPyCFunction_GET_FLAGS(func) & METH_O)) + return __Pyx_PyObject_CallMethO(func, args[0]); + } +#endif + if (kwargs == NULL) { + #if CYTHON_VECTORCALL + #if CYTHON_COMPILING_IN_LIMITED_API + return PyObject_Vectorcall(func, args, _nargs, NULL); + #else + vectorcallfunc f = __Pyx_PyVectorcall_Function(func); + if (f) { + return f(func, args, _nargs, NULL); + } + #endif + #endif + } + if (nargs == 0) { + return __Pyx_PyObject_Call(func, __pyx_mstate_global->__pyx_empty_tuple, kwargs); + } + #if PY_VERSION_HEX >= 0x03090000 && !CYTHON_COMPILING_IN_LIMITED_API + return PyObject_VectorcallDict(func, args, (size_t)nargs, kwargs); + #else + return __Pyx_PyObject_FastCall_fallback(func, args, (size_t)nargs, kwargs); + #endif +} + +/* PyObjectCallNoArg (used by PyObjectCallMethod0) */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func) { + PyObject *arg[2] = {NULL, NULL}; + return __Pyx_PyObject_FastCall(func, arg + 1, 0 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET); +} + +/* PyObjectCallOneArg (used by PyObjectCallMethod0) */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { + PyObject *args[2] = {NULL, arg}; + return __Pyx_PyObject_FastCall(func, args+1, 1 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET); +} + +/* PyObjectGetMethod (used by PyObjectCallMethod0) */ +#if !(CYTHON_VECTORCALL && (__PYX_LIMITED_VERSION_HEX >= 0x030C0000 || (!CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x03090000))) +static int __Pyx_PyObject_GetMethod(PyObject *obj, PyObject *name, PyObject **method) { + PyObject *attr; +#if CYTHON_UNPACK_METHODS && CYTHON_COMPILING_IN_CPYTHON && CYTHON_USE_PYTYPE_LOOKUP + __Pyx_TypeName type_name; + PyTypeObject *tp = Py_TYPE(obj); + PyObject *descr; + descrgetfunc f = NULL; + PyObject **dictptr, *dict; + int meth_found = 0; + assert (*method == NULL); + if (unlikely(tp->tp_getattro != PyObject_GenericGetAttr)) { + attr = __Pyx_PyObject_GetAttrStr(obj, name); + goto try_unpack; + } + if (unlikely(tp->tp_dict == NULL) && unlikely(PyType_Ready(tp) < 0)) { + return 0; + } + descr = _PyType_Lookup(tp, name); + if (likely(descr != NULL)) { + Py_INCREF(descr); +#if defined(Py_TPFLAGS_METHOD_DESCRIPTOR) && Py_TPFLAGS_METHOD_DESCRIPTOR + if (__Pyx_PyType_HasFeature(Py_TYPE(descr), Py_TPFLAGS_METHOD_DESCRIPTOR)) +#else + #ifdef __Pyx_CyFunction_USED + if (likely(PyFunction_Check(descr) || __Pyx_IS_TYPE(descr, &PyMethodDescr_Type) || __Pyx_CyFunction_Check(descr))) + #else + if (likely(PyFunction_Check(descr) || __Pyx_IS_TYPE(descr, &PyMethodDescr_Type))) + #endif +#endif + { + meth_found = 1; + } else { + f = Py_TYPE(descr)->tp_descr_get; + if (f != NULL && PyDescr_IsData(descr)) { + attr = f(descr, obj, (PyObject *)Py_TYPE(obj)); + Py_DECREF(descr); + goto try_unpack; + } + } + } + dictptr = _PyObject_GetDictPtr(obj); + if (dictptr != NULL && (dict = *dictptr) != NULL) { + Py_INCREF(dict); + attr = __Pyx_PyDict_GetItemStr(dict, name); + if (attr != NULL) { + Py_INCREF(attr); + Py_DECREF(dict); + Py_XDECREF(descr); + goto try_unpack; + } + Py_DECREF(dict); + } + if (meth_found) { + *method = descr; + return 1; + } + if (f != NULL) { + attr = f(descr, obj, (PyObject *)Py_TYPE(obj)); + Py_DECREF(descr); + goto try_unpack; + } + if (likely(descr != NULL)) { + *method = descr; + return 0; + } + type_name = __Pyx_PyType_GetFullyQualifiedName(tp); + PyErr_Format(PyExc_AttributeError, + "'" __Pyx_FMT_TYPENAME "' object has no attribute '%U'", + type_name, name); + __Pyx_DECREF_TypeName(type_name); + return 0; +#else + attr = __Pyx_PyObject_GetAttrStr(obj, name); + goto try_unpack; +#endif +try_unpack: +#if CYTHON_UNPACK_METHODS + if (likely(attr) && PyMethod_Check(attr) && likely(PyMethod_GET_SELF(attr) == obj)) { + PyObject *function = PyMethod_GET_FUNCTION(attr); + Py_INCREF(function); + Py_DECREF(attr); + *method = function; + return 1; + } +#endif + *method = attr; + return 0; +} +#endif + +/* PyObjectCallMethod0 (used by dict_iter) */ +static PyObject* __Pyx_PyObject_CallMethod0(PyObject* obj, PyObject* method_name) { +#if CYTHON_VECTORCALL && (__PYX_LIMITED_VERSION_HEX >= 0x030C0000 || (!CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x03090000)) + PyObject *args[1] = {obj}; + (void) __Pyx_PyObject_CallOneArg; + (void) __Pyx_PyObject_CallNoArg; + return PyObject_VectorcallMethod(method_name, args, 1 | PY_VECTORCALL_ARGUMENTS_OFFSET, NULL); +#else + PyObject *method = NULL, *result = NULL; + int is_method = __Pyx_PyObject_GetMethod(obj, method_name, &method); + if (likely(is_method)) { + result = __Pyx_PyObject_CallOneArg(method, obj); + Py_DECREF(method); + return result; + } + if (unlikely(!method)) goto bad; + result = __Pyx_PyObject_CallNoArg(method); + Py_DECREF(method); +bad: + return result; +#endif +} + +/* RaiseNeedMoreValuesToUnpack (used by UnpackTuple2) */ +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { + PyErr_Format(PyExc_ValueError, + "need more than %" CYTHON_FORMAT_SSIZE_T "d value%.1s to unpack", + index, (index == 1) ? "" : "s"); +} + +/* RaiseTooManyValuesToUnpack (used by UnpackItemEndCheck) */ +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { + PyErr_Format(PyExc_ValueError, + "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); +} + +/* UnpackItemEndCheck (used by UnpackTuple2) */ +static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected) { + if (unlikely(retval)) { + Py_DECREF(retval); + __Pyx_RaiseTooManyValuesError(expected); + return -1; + } + return __Pyx_IterFinish(); +} + +/* RaiseNoneIterError (used by UnpackTupleError) */ +static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); +} + +/* UnpackTupleError (used by UnpackTuple2) */ +static void __Pyx_UnpackTupleError(PyObject *t, Py_ssize_t index) { + if (t == Py_None) { + __Pyx_RaiseNoneNotIterableError(); + } else { + Py_ssize_t size = __Pyx_PyTuple_GET_SIZE(t); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(size < 0)) return; + #endif + if (size < index) { + __Pyx_RaiseNeedMoreValuesError(size); + } else { + __Pyx_RaiseTooManyValuesError(index); + } + } +} + +/* UnpackTuple2 (used by dict_iter) */ +static CYTHON_INLINE int __Pyx_unpack_tuple2( + PyObject* tuple, PyObject** value1, PyObject** value2, int is_tuple, int has_known_size, int decref_tuple) { + if (likely(is_tuple || PyTuple_Check(tuple))) { + Py_ssize_t size; + if (has_known_size) { + return __Pyx_unpack_tuple2_exact(tuple, value1, value2, decref_tuple); + } + size = __Pyx_PyTuple_GET_SIZE(tuple); + if (likely(size == 2)) { + return __Pyx_unpack_tuple2_exact(tuple, value1, value2, decref_tuple); + } + if (size >= 0) { + __Pyx_UnpackTupleError(tuple, 2); + } + return -1; + } else { + return __Pyx_unpack_tuple2_generic(tuple, value1, value2, has_known_size, decref_tuple); + } +} +static CYTHON_INLINE int __Pyx_unpack_tuple2_exact( + PyObject* tuple, PyObject** pvalue1, PyObject** pvalue2, int decref_tuple) { + PyObject *value1 = NULL, *value2 = NULL; +#if CYTHON_AVOID_BORROWED_REFS || !CYTHON_ASSUME_SAFE_MACROS + value1 = __Pyx_PySequence_ITEM(tuple, 0); if (unlikely(!value1)) goto bad; + value2 = __Pyx_PySequence_ITEM(tuple, 1); if (unlikely(!value2)) goto bad; +#else + value1 = PyTuple_GET_ITEM(tuple, 0); Py_INCREF(value1); + value2 = PyTuple_GET_ITEM(tuple, 1); Py_INCREF(value2); +#endif + if (decref_tuple) { + Py_DECREF(tuple); + } + *pvalue1 = value1; + *pvalue2 = value2; + return 0; +#if CYTHON_AVOID_BORROWED_REFS || !CYTHON_ASSUME_SAFE_MACROS +bad: + Py_XDECREF(value1); + Py_XDECREF(value2); + if (decref_tuple) { Py_XDECREF(tuple); } + return -1; +#endif +} +static int __Pyx_unpack_tuple2_generic(PyObject* tuple, PyObject** pvalue1, PyObject** pvalue2, + int has_known_size, int decref_tuple) { + Py_ssize_t index; + PyObject *value1 = NULL, *value2 = NULL, *iter = NULL; + iternextfunc iternext; + iter = PyObject_GetIter(tuple); + if (unlikely(!iter)) goto bad; + if (decref_tuple) { Py_DECREF(tuple); tuple = NULL; } + iternext = __Pyx_PyObject_GetIterNextFunc(iter); + value1 = iternext(iter); if (unlikely(!value1)) { index = 0; goto unpacking_failed; } + value2 = iternext(iter); if (unlikely(!value2)) { index = 1; goto unpacking_failed; } + if (!has_known_size && unlikely(__Pyx_IternextUnpackEndCheck(iternext(iter), 2))) goto bad; + Py_DECREF(iter); + *pvalue1 = value1; + *pvalue2 = value2; + return 0; +unpacking_failed: + if (!has_known_size && __Pyx_IterFinish() == 0) + __Pyx_RaiseNeedMoreValuesError(index); +bad: + Py_XDECREF(iter); + Py_XDECREF(value1); + Py_XDECREF(value2); + if (decref_tuple) { Py_XDECREF(tuple); } + return -1; +} + +/* dict_iter */ +#if CYTHON_COMPILING_IN_PYPY +#include +#endif +static CYTHON_INLINE PyObject* __Pyx_dict_iterator(PyObject* iterable, int is_dict, PyObject* method_name, + Py_ssize_t* p_orig_length, int* p_source_is_dict) { + is_dict = is_dict || likely(PyDict_CheckExact(iterable)); + *p_source_is_dict = is_dict; + if (is_dict) { +#if !CYTHON_COMPILING_IN_PYPY + *p_orig_length = PyDict_Size(iterable); + Py_INCREF(iterable); + return iterable; +#else + static PyObject *py_items = NULL, *py_keys = NULL, *py_values = NULL; + PyObject **pp = NULL; + if (method_name) { + const char *name = PyUnicode_AsUTF8(method_name); + if (strcmp(name, "iteritems") == 0) pp = &py_items; + else if (strcmp(name, "iterkeys") == 0) pp = &py_keys; + else if (strcmp(name, "itervalues") == 0) pp = &py_values; + if (pp) { + if (!*pp) { + *pp = PyUnicode_FromString(name + 4); + if (!*pp) + return NULL; + } + method_name = *pp; + } + } +#endif + } + *p_orig_length = 0; + if (method_name) { + PyObject* iter; + iterable = __Pyx_PyObject_CallMethod0(iterable, method_name); + if (!iterable) + return NULL; +#if !CYTHON_COMPILING_IN_PYPY + if (PyTuple_CheckExact(iterable) || PyList_CheckExact(iterable)) + return iterable; +#endif + iter = PyObject_GetIter(iterable); + Py_DECREF(iterable); + return iter; + } + return PyObject_GetIter(iterable); +} +#if !CYTHON_AVOID_BORROWED_REFS +static CYTHON_INLINE int __Pyx_dict_iter_next_source_is_dict( + PyObject* iter_obj, CYTHON_NCP_UNUSED Py_ssize_t orig_length, CYTHON_NCP_UNUSED Py_ssize_t* ppos, + PyObject** pkey, PyObject** pvalue, PyObject** pitem) { + PyObject *key, *value; + if (unlikely(orig_length != PyDict_Size(iter_obj))) { + PyErr_SetString(PyExc_RuntimeError, "dictionary changed size during iteration"); + return -1; + } + if (unlikely(!PyDict_Next(iter_obj, ppos, &key, &value))) { + return 0; + } + if (pitem) { + PyObject* tuple = PyTuple_New(2); + if (unlikely(!tuple)) { + return -1; + } + Py_INCREF(key); + Py_INCREF(value); + #if CYTHON_ASSUME_SAFE_MACROS + PyTuple_SET_ITEM(tuple, 0, key); + PyTuple_SET_ITEM(tuple, 1, value); + #else + if (unlikely(PyTuple_SetItem(tuple, 0, key) < 0)) { + Py_DECREF(value); + Py_DECREF(tuple); + return -1; + } + if (unlikely(PyTuple_SetItem(tuple, 1, value) < 0)) { + Py_DECREF(tuple); + return -1; + } + #endif + *pitem = tuple; + } else { + if (pkey) { + Py_INCREF(key); + *pkey = key; + } + if (pvalue) { + Py_INCREF(value); + *pvalue = value; + } + } + return 1; +} +#endif +static CYTHON_INLINE int __Pyx_dict_iter_next( + PyObject* iter_obj, CYTHON_NCP_UNUSED Py_ssize_t orig_length, CYTHON_NCP_UNUSED Py_ssize_t* ppos, + PyObject** pkey, PyObject** pvalue, PyObject** pitem, int source_is_dict) { + PyObject* next_item; +#if !CYTHON_AVOID_BORROWED_REFS + if (source_is_dict) { + int result; +#if PY_VERSION_HEX >= 0x030d0000 && !CYTHON_COMPILING_IN_LIMITED_API + Py_BEGIN_CRITICAL_SECTION(iter_obj); +#endif + result = __Pyx_dict_iter_next_source_is_dict(iter_obj, orig_length, ppos, pkey, pvalue, pitem); +#if PY_VERSION_HEX >= 0x030d0000 && !CYTHON_COMPILING_IN_LIMITED_API + Py_END_CRITICAL_SECTION(); +#endif + return result; + } else if (PyTuple_CheckExact(iter_obj)) { + Py_ssize_t pos = *ppos; + Py_ssize_t tuple_size = __Pyx_PyTuple_GET_SIZE(iter_obj); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(tuple_size < 0)) return -1; + #endif + if (unlikely(pos >= tuple_size)) return 0; + *ppos = pos + 1; + #if CYTHON_ASSUME_SAFE_MACROS + next_item = PyTuple_GET_ITEM(iter_obj, pos); + #else + next_item = PyTuple_GetItem(iter_obj, pos); + if (unlikely(!next_item)) return -1; + #endif + Py_INCREF(next_item); + } else if (PyList_CheckExact(iter_obj)) { + Py_ssize_t pos = *ppos; + Py_ssize_t list_size = __Pyx_PyList_GET_SIZE(iter_obj); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(list_size < 0)) return -1; + #endif + if (unlikely(pos >= list_size)) return 0; + *ppos = pos + 1; + next_item = __Pyx_PyList_GetItemRef(iter_obj, pos); + if (unlikely(!next_item)) return -1; + } else +#endif + { + next_item = PyIter_Next(iter_obj); + if (unlikely(!next_item)) { + return __Pyx_IterFinish(); + } + } + if (pitem) { + *pitem = next_item; + } else if (pkey && pvalue) { + if (__Pyx_unpack_tuple2(next_item, pkey, pvalue, source_is_dict, source_is_dict, 1)) + return -1; + } else if (pkey) { + *pkey = next_item; + } else { + *pvalue = next_item; + } + return 1; +} + +/* RaiseUnexpectedTypeError */ +static int +__Pyx_RaiseUnexpectedTypeError(const char *expected, PyObject *obj) +{ + __Pyx_TypeName obj_type_name = __Pyx_PyType_GetFullyQualifiedName(Py_TYPE(obj)); + PyErr_Format(PyExc_TypeError, "Expected %s, got " __Pyx_FMT_TYPENAME, + expected, obj_type_name); + __Pyx_DECREF_TypeName(obj_type_name); + return 0; +} + +/* DictGetItem */ +#if !CYTHON_COMPILING_IN_PYPY +static PyObject *__Pyx_PyDict_GetItem(PyObject *d, PyObject* key) { + PyObject *value; + if (unlikely(__Pyx_PyDict_GetItemRef(d, key, &value) == 0)) { // no value, no error + if (unlikely(PyTuple_Check(key))) { + PyObject* args = PyTuple_Pack(1, key); + if (likely(args)) { + PyErr_SetObject(PyExc_KeyError, args); + Py_DECREF(args); + } + } else { + PyErr_SetObject(PyExc_KeyError, key); + } + } + return value; +} +#endif + +/* PyDictVersioning (used by GetModuleGlobalName) */ +#if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_TYPE_SLOTS +static CYTHON_INLINE PY_UINT64_T __Pyx_get_tp_dict_version(PyObject *obj) { + PyObject *dict = Py_TYPE(obj)->tp_dict; + return likely(dict) ? __PYX_GET_DICT_VERSION(dict) : 0; +} +static CYTHON_INLINE PY_UINT64_T __Pyx_get_object_dict_version(PyObject *obj) { + PyObject **dictptr = NULL; + Py_ssize_t offset = Py_TYPE(obj)->tp_dictoffset; + if (offset) { +#if CYTHON_COMPILING_IN_CPYTHON + dictptr = (likely(offset > 0)) ? (PyObject **) ((char *)obj + offset) : _PyObject_GetDictPtr(obj); +#else + dictptr = _PyObject_GetDictPtr(obj); +#endif + } + return (dictptr && *dictptr) ? __PYX_GET_DICT_VERSION(*dictptr) : 0; +} +static CYTHON_INLINE int __Pyx_object_dict_version_matches(PyObject* obj, PY_UINT64_T tp_dict_version, PY_UINT64_T obj_dict_version) { + PyObject *dict = Py_TYPE(obj)->tp_dict; + if (unlikely(!dict) || unlikely(tp_dict_version != __PYX_GET_DICT_VERSION(dict))) + return 0; + return obj_dict_version == __Pyx_get_object_dict_version(obj); +} +#endif + +/* GetModuleGlobalName */ +#if CYTHON_USE_DICT_VERSIONS +static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_version, PyObject **dict_cached_value) +#else +static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name) +#endif +{ + PyObject *result; +#if CYTHON_COMPILING_IN_LIMITED_API + if (unlikely(!__pyx_m)) { + if (!PyErr_Occurred()) + PyErr_SetNone(PyExc_NameError); + return NULL; + } + result = PyObject_GetAttr(__pyx_m, name); + if (likely(result)) { + return result; + } + PyErr_Clear(); +#elif CYTHON_AVOID_BORROWED_REFS || CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + if (unlikely(__Pyx_PyDict_GetItemRef(__pyx_mstate_global->__pyx_d, name, &result) == -1)) PyErr_Clear(); + __PYX_UPDATE_DICT_CACHE(__pyx_mstate_global->__pyx_d, result, *dict_cached_value, *dict_version) + if (likely(result)) { + return result; + } +#else + result = _PyDict_GetItem_KnownHash(__pyx_mstate_global->__pyx_d, name, ((PyASCIIObject *) name)->hash); + __PYX_UPDATE_DICT_CACHE(__pyx_mstate_global->__pyx_d, result, *dict_cached_value, *dict_version) + if (likely(result)) { + return __Pyx_NewRef(result); + } + PyErr_Clear(); +#endif + return __Pyx_GetBuiltinName(name); +} + +/* GetAttr3 */ +#if __PYX_LIMITED_VERSION_HEX < 0x030d0000 +static PyObject *__Pyx_GetAttr3Default(PyObject *d) { + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + if (unlikely(!__Pyx_PyErr_ExceptionMatches(PyExc_AttributeError))) + return NULL; + __Pyx_PyErr_Clear(); + Py_INCREF(d); + return d; +} +#endif +static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *o, PyObject *n, PyObject *d) { + PyObject *r; +#if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + int res = PyObject_GetOptionalAttr(o, n, &r); + return (res != 0) ? r : __Pyx_NewRef(d); +#else + #if CYTHON_USE_TYPE_SLOTS + if (likely(PyUnicode_Check(n))) { + r = __Pyx_PyObject_GetAttrStrNoError(o, n); + if (unlikely(!r) && likely(!PyErr_Occurred())) { + r = __Pyx_NewRef(d); + } + return r; + } + #endif + r = PyObject_GetAttr(o, n); + return (likely(r)) ? r : __Pyx_GetAttr3Default(d); +#endif +} + +/* GetTopmostException (used by SaveResetException) */ +#if CYTHON_USE_EXC_INFO_STACK && CYTHON_FAST_THREAD_STATE +static _PyErr_StackItem * +__Pyx_PyErr_GetTopmostException(PyThreadState *tstate) +{ + _PyErr_StackItem *exc_info = tstate->exc_info; + while ((exc_info->exc_value == NULL || exc_info->exc_value == Py_None) && + exc_info->previous_item != NULL) + { + exc_info = exc_info->previous_item; + } + return exc_info; +} +#endif + +/* SaveResetException */ +#if CYTHON_FAST_THREAD_STATE +static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { + #if CYTHON_USE_EXC_INFO_STACK && PY_VERSION_HEX >= 0x030B00a4 + _PyErr_StackItem *exc_info = __Pyx_PyErr_GetTopmostException(tstate); + PyObject *exc_value = exc_info->exc_value; + if (exc_value == NULL || exc_value == Py_None) { + *value = NULL; + *type = NULL; + *tb = NULL; + } else { + *value = exc_value; + Py_INCREF(*value); + *type = (PyObject*) Py_TYPE(exc_value); + Py_INCREF(*type); + *tb = PyException_GetTraceback(exc_value); + } + #elif CYTHON_USE_EXC_INFO_STACK + _PyErr_StackItem *exc_info = __Pyx_PyErr_GetTopmostException(tstate); + *type = exc_info->exc_type; + *value = exc_info->exc_value; + *tb = exc_info->exc_traceback; + Py_XINCREF(*type); + Py_XINCREF(*value); + Py_XINCREF(*tb); + #else + *type = tstate->exc_type; + *value = tstate->exc_value; + *tb = tstate->exc_traceback; + Py_XINCREF(*type); + Py_XINCREF(*value); + Py_XINCREF(*tb); + #endif +} +static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { + #if CYTHON_USE_EXC_INFO_STACK && PY_VERSION_HEX >= 0x030B00a4 + _PyErr_StackItem *exc_info = tstate->exc_info; + PyObject *tmp_value = exc_info->exc_value; + exc_info->exc_value = value; + Py_XDECREF(tmp_value); + Py_XDECREF(type); + Py_XDECREF(tb); + #else + PyObject *tmp_type, *tmp_value, *tmp_tb; + #if CYTHON_USE_EXC_INFO_STACK + _PyErr_StackItem *exc_info = tstate->exc_info; + tmp_type = exc_info->exc_type; + tmp_value = exc_info->exc_value; + tmp_tb = exc_info->exc_traceback; + exc_info->exc_type = type; + exc_info->exc_value = value; + exc_info->exc_traceback = tb; + #else + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = type; + tstate->exc_value = value; + tstate->exc_traceback = tb; + #endif + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); + #endif +} +#endif + +/* GetException */ +#if CYTHON_FAST_THREAD_STATE +static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) +#else +static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb) +#endif +{ + PyObject *local_type = NULL, *local_value, *local_tb = NULL; +#if CYTHON_FAST_THREAD_STATE + PyObject *tmp_type, *tmp_value, *tmp_tb; + #if PY_VERSION_HEX >= 0x030C0000 + local_value = tstate->current_exception; + tstate->current_exception = 0; + #else + local_type = tstate->curexc_type; + local_value = tstate->curexc_value; + local_tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; + #endif +#elif __PYX_LIMITED_VERSION_HEX > 0x030C0000 + local_value = PyErr_GetRaisedException(); +#else + PyErr_Fetch(&local_type, &local_value, &local_tb); +#endif +#if __PYX_LIMITED_VERSION_HEX > 0x030C0000 + if (likely(local_value)) { + local_type = (PyObject*) Py_TYPE(local_value); + Py_INCREF(local_type); + local_tb = PyException_GetTraceback(local_value); + } +#else + PyErr_NormalizeException(&local_type, &local_value, &local_tb); +#if CYTHON_FAST_THREAD_STATE + if (unlikely(tstate->curexc_type)) +#else + if (unlikely(PyErr_Occurred())) +#endif + goto bad; + if (local_tb) { + if (unlikely(PyException_SetTraceback(local_value, local_tb) < 0)) + goto bad; + } +#endif // __PYX_LIMITED_VERSION_HEX > 0x030C0000 + Py_XINCREF(local_tb); + Py_XINCREF(local_type); + Py_XINCREF(local_value); + *type = local_type; + *value = local_value; + *tb = local_tb; +#if CYTHON_FAST_THREAD_STATE + #if CYTHON_USE_EXC_INFO_STACK + { + _PyErr_StackItem *exc_info = tstate->exc_info; + #if PY_VERSION_HEX >= 0x030B00a4 + tmp_value = exc_info->exc_value; + exc_info->exc_value = local_value; + tmp_type = NULL; + tmp_tb = NULL; + Py_XDECREF(local_type); + Py_XDECREF(local_tb); + #else + tmp_type = exc_info->exc_type; + tmp_value = exc_info->exc_value; + tmp_tb = exc_info->exc_traceback; + exc_info->exc_type = local_type; + exc_info->exc_value = local_value; + exc_info->exc_traceback = local_tb; + #endif + } + #else + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = local_type; + tstate->exc_value = local_value; + tstate->exc_traceback = local_tb; + #endif + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#elif __PYX_LIMITED_VERSION_HEX >= 0x030b0000 + PyErr_SetHandledException(local_value); + Py_XDECREF(local_value); + Py_XDECREF(local_type); + Py_XDECREF(local_tb); +#else + PyErr_SetExcInfo(local_type, local_value, local_tb); +#endif + return 0; +#if __PYX_LIMITED_VERSION_HEX <= 0x030C0000 +bad: + *type = 0; + *value = 0; + *tb = 0; + Py_XDECREF(local_type); + Py_XDECREF(local_value); + Py_XDECREF(local_tb); + return -1; +#endif +} + +/* RaiseException */ +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { + PyObject* owned_instance = NULL; + if (tb == Py_None) { + tb = 0; + } else if (tb && !PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto bad; + } + if (value == Py_None) + value = 0; + if (PyExceptionInstance_Check(type)) { + if (value) { + PyErr_SetString(PyExc_TypeError, + "instance exception may not have a separate value"); + goto bad; + } + value = type; + type = (PyObject*) Py_TYPE(value); + } else if (PyExceptionClass_Check(type)) { + PyObject *instance_class = NULL; + if (value && PyExceptionInstance_Check(value)) { + instance_class = (PyObject*) Py_TYPE(value); + if (instance_class != type) { + int is_subclass = PyObject_IsSubclass(instance_class, type); + if (!is_subclass) { + instance_class = NULL; + } else if (unlikely(is_subclass == -1)) { + goto bad; + } else { + type = instance_class; + } + } + } + if (!instance_class) { + PyObject *args; + if (!value) + args = PyTuple_New(0); + else if (PyTuple_Check(value)) { + Py_INCREF(value); + args = value; + } else + args = PyTuple_Pack(1, value); + if (!args) + goto bad; + owned_instance = PyObject_Call(type, args, NULL); + Py_DECREF(args); + if (!owned_instance) + goto bad; + value = owned_instance; + if (!PyExceptionInstance_Check(value)) { + PyErr_Format(PyExc_TypeError, + "calling %R should have returned an instance of " + "BaseException, not %R", + type, Py_TYPE(value)); + goto bad; + } + } + } else { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto bad; + } + if (cause) { + PyObject *fixed_cause; + if (cause == Py_None) { + fixed_cause = NULL; + } else if (PyExceptionClass_Check(cause)) { + fixed_cause = PyObject_CallObject(cause, NULL); + if (fixed_cause == NULL) + goto bad; + } else if (PyExceptionInstance_Check(cause)) { + fixed_cause = cause; + Py_INCREF(fixed_cause); + } else { + PyErr_SetString(PyExc_TypeError, + "exception causes must derive from " + "BaseException"); + goto bad; + } + PyException_SetCause(value, fixed_cause); + } + PyErr_SetObject(type, value); + if (tb) { +#if PY_VERSION_HEX >= 0x030C00A6 + PyException_SetTraceback(value, tb); +#elif CYTHON_FAST_THREAD_STATE + PyThreadState *tstate = __Pyx_PyThreadState_Current; + PyObject* tmp_tb = tstate->curexc_traceback; + if (tb != tmp_tb) { + Py_INCREF(tb); + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_tb); + } +#else + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyErr_Fetch(&tmp_type, &tmp_value, &tmp_tb); + Py_INCREF(tb); + PyErr_Restore(tmp_type, tmp_value, tb); + Py_XDECREF(tmp_tb); +#endif + } +bad: + Py_XDECREF(owned_instance); + return; +} + +/* SwapException */ +#if CYTHON_FAST_THREAD_STATE +static CYTHON_INLINE void __Pyx__ExceptionSwap(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { + PyObject *tmp_type, *tmp_value, *tmp_tb; + #if CYTHON_USE_EXC_INFO_STACK && PY_VERSION_HEX >= 0x030B00a4 + _PyErr_StackItem *exc_info = tstate->exc_info; + tmp_value = exc_info->exc_value; + exc_info->exc_value = *value; + if (tmp_value == NULL || tmp_value == Py_None) { + Py_XDECREF(tmp_value); + tmp_value = NULL; + tmp_type = NULL; + tmp_tb = NULL; + } else { + tmp_type = (PyObject*) Py_TYPE(tmp_value); + Py_INCREF(tmp_type); + #if CYTHON_COMPILING_IN_CPYTHON + tmp_tb = ((PyBaseExceptionObject*) tmp_value)->traceback; + Py_XINCREF(tmp_tb); + #else + tmp_tb = PyException_GetTraceback(tmp_value); + #endif + } + #elif CYTHON_USE_EXC_INFO_STACK + _PyErr_StackItem *exc_info = tstate->exc_info; + tmp_type = exc_info->exc_type; + tmp_value = exc_info->exc_value; + tmp_tb = exc_info->exc_traceback; + exc_info->exc_type = *type; + exc_info->exc_value = *value; + exc_info->exc_traceback = *tb; + #else + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = *type; + tstate->exc_value = *value; + tstate->exc_traceback = *tb; + #endif + *type = tmp_type; + *value = tmp_value; + *tb = tmp_tb; +} +#else +static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb) { + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyErr_GetExcInfo(&tmp_type, &tmp_value, &tmp_tb); + PyErr_SetExcInfo(*type, *value, *tb); + *type = tmp_type; + *value = tmp_value; + *tb = tmp_tb; +} +#endif + +/* decode_c_string */ +static CYTHON_INLINE PyObject* __Pyx_decode_c_string( + const char* cstring, Py_ssize_t start, Py_ssize_t stop, + const char* encoding, const char* errors, + PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)) { + Py_ssize_t length; + if (unlikely((start < 0) | (stop < 0))) { + size_t slen = strlen(cstring); + if (unlikely(slen > (size_t) PY_SSIZE_T_MAX)) { + PyErr_SetString(PyExc_OverflowError, + "c-string too long to convert to Python"); + return NULL; + } + length = (Py_ssize_t) slen; + if (start < 0) { + start += length; + if (start < 0) + start = 0; + } + if (stop < 0) + stop += length; + } + if (unlikely(stop <= start)) + return __Pyx_NewRef(__pyx_mstate_global->__pyx_empty_unicode); + length = stop - start; + cstring += start; + if (decode_func) { + return decode_func(cstring, length, errors); + } else { + return PyUnicode_Decode(cstring, length, encoding, errors); + } +} + +/* PyObjectFastCallMethod */ +#if !CYTHON_VECTORCALL || PY_VERSION_HEX < 0x03090000 +static PyObject *__Pyx_PyObject_FastCallMethod(PyObject *name, PyObject *const *args, size_t nargsf) { + PyObject *result; + PyObject *attr = PyObject_GetAttr(args[0], name); + if (unlikely(!attr)) + return NULL; + result = __Pyx_PyObject_FastCall(attr, args+1, nargsf - 1); + Py_DECREF(attr); + return result; +} +#endif + +/* TupleAndListFromArray (used by fastcall) */ +#if !CYTHON_COMPILING_IN_CPYTHON && CYTHON_METH_FASTCALL +static CYTHON_INLINE PyObject * +__Pyx_PyTuple_FromArray(PyObject *const *src, Py_ssize_t n) +{ + PyObject *res; + Py_ssize_t i; + if (n <= 0) { + return __Pyx_NewRef(__pyx_mstate_global->__pyx_empty_tuple); + } + res = PyTuple_New(n); + if (unlikely(res == NULL)) return NULL; + for (i = 0; i < n; i++) { + if (unlikely(__Pyx_PyTuple_SET_ITEM(res, i, src[i]) < (0))) { + Py_DECREF(res); + return NULL; + } + Py_INCREF(src[i]); + } + return res; +} +#elif CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE void __Pyx_copy_object_array(PyObject *const *CYTHON_RESTRICT src, PyObject** CYTHON_RESTRICT dest, Py_ssize_t length) { + PyObject *v; + Py_ssize_t i; + for (i = 0; i < length; i++) { + v = dest[i] = src[i]; + Py_INCREF(v); + } +} +static CYTHON_INLINE PyObject * +__Pyx_PyTuple_FromArray(PyObject *const *src, Py_ssize_t n) +{ + PyObject *res; + if (n <= 0) { + return __Pyx_NewRef(__pyx_mstate_global->__pyx_empty_tuple); + } + res = PyTuple_New(n); + if (unlikely(res == NULL)) return NULL; + __Pyx_copy_object_array(src, ((PyTupleObject*)res)->ob_item, n); + return res; +} +static CYTHON_INLINE PyObject * +__Pyx_PyList_FromArray(PyObject *const *src, Py_ssize_t n) +{ + PyObject *res; + if (n <= 0) { + return PyList_New(0); + } + res = PyList_New(n); + if (unlikely(res == NULL)) return NULL; + __Pyx_copy_object_array(src, ((PyListObject*)res)->ob_item, n); + return res; +} +#endif + +/* BytesEquals (used by UnicodeEquals) */ +static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals) { +#if CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_GRAAL ||\ + !(CYTHON_ASSUME_SAFE_SIZE && CYTHON_ASSUME_SAFE_MACROS) + return PyObject_RichCompareBool(s1, s2, equals); +#else + if (s1 == s2) { + return (equals == Py_EQ); + } else if (PyBytes_CheckExact(s1) & PyBytes_CheckExact(s2)) { + const char *ps1, *ps2; + Py_ssize_t length = PyBytes_GET_SIZE(s1); + if (length != PyBytes_GET_SIZE(s2)) + return (equals == Py_NE); + ps1 = PyBytes_AS_STRING(s1); + ps2 = PyBytes_AS_STRING(s2); + if (ps1[0] != ps2[0]) { + return (equals == Py_NE); + } else if (length == 1) { + return (equals == Py_EQ); + } else { + int result; +#if CYTHON_USE_UNICODE_INTERNALS && (PY_VERSION_HEX < 0x030B0000) + Py_hash_t hash1, hash2; + hash1 = ((PyBytesObject*)s1)->ob_shash; + hash2 = ((PyBytesObject*)s2)->ob_shash; + if (hash1 != hash2 && hash1 != -1 && hash2 != -1) { + return (equals == Py_NE); + } +#endif + result = memcmp(ps1, ps2, (size_t)length); + return (equals == Py_EQ) ? (result == 0) : (result != 0); + } + } else if ((s1 == Py_None) & PyBytes_CheckExact(s2)) { + return (equals == Py_NE); + } else if ((s2 == Py_None) & PyBytes_CheckExact(s1)) { + return (equals == Py_NE); + } else { + int result; + PyObject* py_result = PyObject_RichCompare(s1, s2, equals); + if (!py_result) + return -1; + result = __Pyx_PyObject_IsTrue(py_result); + Py_DECREF(py_result); + return result; + } +#endif +} + +/* UnicodeEquals (used by fastcall) */ +static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals) { +#if CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_GRAAL + return PyObject_RichCompareBool(s1, s2, equals); +#else + int s1_is_unicode, s2_is_unicode; + if (s1 == s2) { + goto return_eq; + } + s1_is_unicode = PyUnicode_CheckExact(s1); + s2_is_unicode = PyUnicode_CheckExact(s2); + if (s1_is_unicode & s2_is_unicode) { + Py_ssize_t length, length2; + int kind; + void *data1, *data2; + #if !CYTHON_COMPILING_IN_LIMITED_API + if (unlikely(__Pyx_PyUnicode_READY(s1) < 0) || unlikely(__Pyx_PyUnicode_READY(s2) < 0)) + return -1; + #endif + length = __Pyx_PyUnicode_GET_LENGTH(s1); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(length < 0)) return -1; + #endif + length2 = __Pyx_PyUnicode_GET_LENGTH(s2); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(length2 < 0)) return -1; + #endif + if (length != length2) { + goto return_ne; + } +#if CYTHON_USE_UNICODE_INTERNALS + { + Py_hash_t hash1, hash2; + hash1 = ((PyASCIIObject*)s1)->hash; + hash2 = ((PyASCIIObject*)s2)->hash; + if (hash1 != hash2 && hash1 != -1 && hash2 != -1) { + goto return_ne; + } + } +#endif + kind = __Pyx_PyUnicode_KIND(s1); + if (kind != __Pyx_PyUnicode_KIND(s2)) { + goto return_ne; + } + data1 = __Pyx_PyUnicode_DATA(s1); + data2 = __Pyx_PyUnicode_DATA(s2); + if (__Pyx_PyUnicode_READ(kind, data1, 0) != __Pyx_PyUnicode_READ(kind, data2, 0)) { + goto return_ne; + } else if (length == 1) { + goto return_eq; + } else { + int result = memcmp(data1, data2, (size_t)(length * kind)); + return (equals == Py_EQ) ? (result == 0) : (result != 0); + } + } else if ((s1 == Py_None) & s2_is_unicode) { + goto return_ne; + } else if ((s2 == Py_None) & s1_is_unicode) { + goto return_ne; + } else { + int result; + PyObject* py_result = PyObject_RichCompare(s1, s2, equals); + if (!py_result) + return -1; + result = __Pyx_PyObject_IsTrue(py_result); + Py_DECREF(py_result); + return result; + } +return_eq: + return (equals == Py_EQ); +return_ne: + return (equals == Py_NE); +#endif +} + +/* fastcall */ +#if CYTHON_METH_FASTCALL +static CYTHON_INLINE PyObject * __Pyx_GetKwValue_FASTCALL(PyObject *kwnames, PyObject *const *kwvalues, PyObject *s) +{ + Py_ssize_t i, n = __Pyx_PyTuple_GET_SIZE(kwnames); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(n == -1)) return NULL; + #endif + for (i = 0; i < n; i++) + { + PyObject *namei = __Pyx_PyTuple_GET_ITEM(kwnames, i); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(!namei)) return NULL; + #endif + if (s == namei) return kwvalues[i]; + } + for (i = 0; i < n; i++) + { + PyObject *namei = __Pyx_PyTuple_GET_ITEM(kwnames, i); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(!namei)) return NULL; + #endif + int eq = __Pyx_PyUnicode_Equals(s, namei, Py_EQ); + if (unlikely(eq != 0)) { + if (unlikely(eq < 0)) return NULL; + return kwvalues[i]; + } + } + return NULL; +} +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030d0000 || CYTHON_COMPILING_IN_LIMITED_API +CYTHON_UNUSED static PyObject *__Pyx_KwargsAsDict_FASTCALL(PyObject *kwnames, PyObject *const *kwvalues) { + Py_ssize_t i, nkwargs; + PyObject *dict; +#if !CYTHON_ASSUME_SAFE_SIZE + nkwargs = PyTuple_Size(kwnames); + if (unlikely(nkwargs < 0)) return NULL; +#else + nkwargs = PyTuple_GET_SIZE(kwnames); +#endif + dict = PyDict_New(); + if (unlikely(!dict)) + return NULL; + for (i=0; itype, *target->method_name); + if (unlikely(!method)) + return -1; + result = method; +#if CYTHON_COMPILING_IN_CPYTHON + if (likely(__Pyx_TypeCheck(method, &PyMethodDescr_Type))) + { + PyMethodDescrObject *descr = (PyMethodDescrObject*) method; + target->func = descr->d_method->ml_meth; + target->flag = descr->d_method->ml_flags & ~(METH_CLASS | METH_STATIC | METH_COEXIST | METH_STACKLESS); + } else +#endif +#if CYTHON_COMPILING_IN_PYPY +#else + if (PyCFunction_Check(method)) +#endif + { + PyObject *self; + int self_found; +#if CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_PYPY + self = PyObject_GetAttrString(method, "__self__"); + if (!self) { + PyErr_Clear(); + } +#else + self = PyCFunction_GET_SELF(method); +#endif + self_found = (self && self != Py_None); +#if CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_PYPY + Py_XDECREF(self); +#endif + if (self_found) { + PyObject *unbound_method = PyCFunction_New(&__Pyx_UnboundCMethod_Def, method); + if (unlikely(!unbound_method)) return -1; + Py_DECREF(method); + result = unbound_method; + } + } +#if !CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + if (unlikely(target->method)) { + Py_DECREF(result); + } else +#endif + target->method = result; + return 0; +} + +/* CallUnboundCMethod0 */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_CallUnboundCMethod0(__Pyx_CachedCFunction* cfunc, PyObject* self) { + int was_initialized = __Pyx_CachedCFunction_GetAndSetInitializing(cfunc); + if (likely(was_initialized == 2 && cfunc->func)) { + if (likely(cfunc->flag == METH_NOARGS)) + return __Pyx_CallCFunction(cfunc, self, NULL); + if (likely(cfunc->flag == METH_FASTCALL)) + return __Pyx_CallCFunctionFast(cfunc, self, NULL, 0); + if (cfunc->flag == (METH_FASTCALL | METH_KEYWORDS)) + return __Pyx_CallCFunctionFastWithKeywords(cfunc, self, NULL, 0, NULL); + if (likely(cfunc->flag == (METH_VARARGS | METH_KEYWORDS))) + return __Pyx_CallCFunctionWithKeywords(cfunc, self, __pyx_mstate_global->__pyx_empty_tuple, NULL); + if (cfunc->flag == METH_VARARGS) + return __Pyx_CallCFunction(cfunc, self, __pyx_mstate_global->__pyx_empty_tuple); + return __Pyx__CallUnboundCMethod0(cfunc, self); + } +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + else if (unlikely(was_initialized == 1)) { + __Pyx_CachedCFunction tmp_cfunc = { +#ifndef __cplusplus + 0 +#endif + }; + tmp_cfunc.type = cfunc->type; + tmp_cfunc.method_name = cfunc->method_name; + return __Pyx__CallUnboundCMethod0(&tmp_cfunc, self); + } +#endif + PyObject *result = __Pyx__CallUnboundCMethod0(cfunc, self); + __Pyx_CachedCFunction_SetFinishedInitializing(cfunc); + return result; +} +#endif +static PyObject* __Pyx__CallUnboundCMethod0(__Pyx_CachedCFunction* cfunc, PyObject* self) { + PyObject *result; + if (unlikely(!cfunc->method) && unlikely(__Pyx_TryUnpackUnboundCMethod(cfunc) < 0)) return NULL; + result = __Pyx_PyObject_CallOneArg(cfunc->method, self); + return result; +} + +/* py_dict_items (used by OwnedDictNext) */ +static CYTHON_INLINE PyObject* __Pyx_PyDict_Items(PyObject* d) { + return __Pyx_CallUnboundCMethod0(&__pyx_mstate_global->__pyx_umethod_PyDict_Type_items, d); +} + +/* py_dict_values (used by OwnedDictNext) */ +static CYTHON_INLINE PyObject* __Pyx_PyDict_Values(PyObject* d) { + return __Pyx_CallUnboundCMethod0(&__pyx_mstate_global->__pyx_umethod_PyDict_Type_values, d); +} + +/* OwnedDictNext (used by ParseKeywordsImpl) */ +#if CYTHON_AVOID_BORROWED_REFS +static int __Pyx_PyDict_NextRef(PyObject *p, PyObject **ppos, PyObject **pkey, PyObject **pvalue) { + PyObject *next = NULL; + if (!*ppos) { + if (pvalue) { + PyObject *dictview = pkey ? __Pyx_PyDict_Items(p) : __Pyx_PyDict_Values(p); + if (unlikely(!dictview)) goto bad; + *ppos = PyObject_GetIter(dictview); + Py_DECREF(dictview); + } else { + *ppos = PyObject_GetIter(p); + } + if (unlikely(!*ppos)) goto bad; + } + next = PyIter_Next(*ppos); + if (!next) { + if (PyErr_Occurred()) goto bad; + return 0; + } + if (pkey && pvalue) { + *pkey = __Pyx_PySequence_ITEM(next, 0); + if (unlikely(*pkey)) goto bad; + *pvalue = __Pyx_PySequence_ITEM(next, 1); + if (unlikely(*pvalue)) goto bad; + Py_DECREF(next); + } else if (pkey) { + *pkey = next; + } else { + assert(pvalue); + *pvalue = next; + } + return 1; + bad: + Py_XDECREF(next); +#if !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d0000 + PyErr_FormatUnraisable("Exception ignored in __Pyx_PyDict_NextRef"); +#else + PyErr_WriteUnraisable(__pyx_mstate_global->__pyx_n_u_Pyx_PyDict_NextRef); +#endif + if (pkey) *pkey = NULL; + if (pvalue) *pvalue = NULL; + return 0; +} +#else // !CYTHON_AVOID_BORROWED_REFS +static int __Pyx_PyDict_NextRef(PyObject *p, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue) { + int result = PyDict_Next(p, ppos, pkey, pvalue); + if (likely(result == 1)) { + if (pkey) Py_INCREF(*pkey); + if (pvalue) Py_INCREF(*pvalue); + } + return result; +} +#endif + +/* RaiseDoubleKeywords (used by ParseKeywordsImpl) */ +static void __Pyx_RaiseDoubleKeywordsError( + const char* func_name, + PyObject* kw_name) +{ + PyErr_Format(PyExc_TypeError, + "%s() got multiple values for keyword argument '%U'", func_name, kw_name); +} + +/* CallUnboundCMethod2 */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject *__Pyx_CallUnboundCMethod2(__Pyx_CachedCFunction *cfunc, PyObject *self, PyObject *arg1, PyObject *arg2) { + int was_initialized = __Pyx_CachedCFunction_GetAndSetInitializing(cfunc); + if (likely(was_initialized == 2 && cfunc->func)) { + PyObject *args[2] = {arg1, arg2}; + if (cfunc->flag == METH_FASTCALL) { + return __Pyx_CallCFunctionFast(cfunc, self, args, 2); + } + if (cfunc->flag == (METH_FASTCALL | METH_KEYWORDS)) + return __Pyx_CallCFunctionFastWithKeywords(cfunc, self, args, 2, NULL); + } +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + else if (unlikely(was_initialized == 1)) { + __Pyx_CachedCFunction tmp_cfunc = { +#ifndef __cplusplus + 0 +#endif + }; + tmp_cfunc.type = cfunc->type; + tmp_cfunc.method_name = cfunc->method_name; + return __Pyx__CallUnboundCMethod2(&tmp_cfunc, self, arg1, arg2); + } +#endif + PyObject *result = __Pyx__CallUnboundCMethod2(cfunc, self, arg1, arg2); + __Pyx_CachedCFunction_SetFinishedInitializing(cfunc); + return result; +} +#endif +static PyObject* __Pyx__CallUnboundCMethod2(__Pyx_CachedCFunction* cfunc, PyObject* self, PyObject* arg1, PyObject* arg2){ + if (unlikely(!cfunc->func && !cfunc->method) && unlikely(__Pyx_TryUnpackUnboundCMethod(cfunc) < 0)) return NULL; +#if CYTHON_COMPILING_IN_CPYTHON + if (cfunc->func && (cfunc->flag & METH_VARARGS)) { + PyObject *result = NULL; + PyObject *args = PyTuple_New(2); + if (unlikely(!args)) return NULL; + Py_INCREF(arg1); + PyTuple_SET_ITEM(args, 0, arg1); + Py_INCREF(arg2); + PyTuple_SET_ITEM(args, 1, arg2); + if (cfunc->flag & METH_KEYWORDS) + result = __Pyx_CallCFunctionWithKeywords(cfunc, self, args, NULL); + else + result = __Pyx_CallCFunction(cfunc, self, args); + Py_DECREF(args); + return result; + } +#endif + { + PyObject *args[4] = {NULL, self, arg1, arg2}; + return __Pyx_PyObject_FastCall(cfunc->method, args+1, 3 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET); + } +} + +/* ParseKeywordsImpl (used by ParseKeywords) */ +static int __Pyx_ValidateDuplicatePosArgs( + PyObject *kwds, + PyObject ** const argnames[], + PyObject ** const *first_kw_arg, + const char* function_name) +{ + PyObject ** const *name = argnames; + while (name != first_kw_arg) { + PyObject *key = **name; + int found = PyDict_Contains(kwds, key); + if (unlikely(found)) { + if (found == 1) __Pyx_RaiseDoubleKeywordsError(function_name, key); + goto bad; + } + name++; + } + return 0; +bad: + return -1; +} +#if CYTHON_USE_UNICODE_INTERNALS +static CYTHON_INLINE int __Pyx_UnicodeKeywordsEqual(PyObject *s1, PyObject *s2) { + int kind; + Py_ssize_t len = PyUnicode_GET_LENGTH(s1); + if (len != PyUnicode_GET_LENGTH(s2)) return 0; + kind = PyUnicode_KIND(s1); + if (kind != PyUnicode_KIND(s2)) return 0; + const void *data1 = PyUnicode_DATA(s1); + const void *data2 = PyUnicode_DATA(s2); + return (memcmp(data1, data2, (size_t) len * (size_t) kind) == 0); +} +#endif +static int __Pyx_MatchKeywordArg_str( + PyObject *key, + PyObject ** const argnames[], + PyObject ** const *first_kw_arg, + size_t *index_found, + const char *function_name) +{ + PyObject ** const *name; + #if CYTHON_USE_UNICODE_INTERNALS + Py_hash_t key_hash = ((PyASCIIObject*)key)->hash; + if (unlikely(key_hash == -1)) { + key_hash = PyObject_Hash(key); + if (unlikely(key_hash == -1)) + goto bad; + } + #endif + name = first_kw_arg; + while (*name) { + PyObject *name_str = **name; + #if CYTHON_USE_UNICODE_INTERNALS + if (key_hash == ((PyASCIIObject*)name_str)->hash && __Pyx_UnicodeKeywordsEqual(name_str, key)) { + *index_found = (size_t) (name - argnames); + return 1; + } + #else + #if CYTHON_ASSUME_SAFE_SIZE + if (PyUnicode_GET_LENGTH(name_str) == PyUnicode_GET_LENGTH(key)) + #endif + { + int cmp = PyUnicode_Compare(name_str, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) { + *index_found = (size_t) (name - argnames); + return 1; + } + } + #endif + name++; + } + name = argnames; + while (name != first_kw_arg) { + PyObject *name_str = **name; + #if CYTHON_USE_UNICODE_INTERNALS + if (unlikely(key_hash == ((PyASCIIObject*)name_str)->hash)) { + if (__Pyx_UnicodeKeywordsEqual(name_str, key)) + goto arg_passed_twice; + } + #else + #if CYTHON_ASSUME_SAFE_SIZE + if (PyUnicode_GET_LENGTH(name_str) == PyUnicode_GET_LENGTH(key)) + #endif + { + if (unlikely(name_str == key)) goto arg_passed_twice; + int cmp = PyUnicode_Compare(name_str, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) goto arg_passed_twice; + } + #endif + name++; + } + return 0; +arg_passed_twice: + __Pyx_RaiseDoubleKeywordsError(function_name, key); + goto bad; +bad: + return -1; +} +static int __Pyx_MatchKeywordArg_nostr( + PyObject *key, + PyObject ** const argnames[], + PyObject ** const *first_kw_arg, + size_t *index_found, + const char *function_name) +{ + PyObject ** const *name; + if (unlikely(!PyUnicode_Check(key))) goto invalid_keyword_type; + name = first_kw_arg; + while (*name) { + int cmp = PyObject_RichCompareBool(**name, key, Py_EQ); + if (cmp == 1) { + *index_found = (size_t) (name - argnames); + return 1; + } + if (unlikely(cmp == -1)) goto bad; + name++; + } + name = argnames; + while (name != first_kw_arg) { + int cmp = PyObject_RichCompareBool(**name, key, Py_EQ); + if (unlikely(cmp != 0)) { + if (cmp == 1) goto arg_passed_twice; + else goto bad; + } + name++; + } + return 0; +arg_passed_twice: + __Pyx_RaiseDoubleKeywordsError(function_name, key); + goto bad; +invalid_keyword_type: + PyErr_Format(PyExc_TypeError, + "%.200s() keywords must be strings", function_name); + goto bad; +bad: + return -1; +} +static CYTHON_INLINE int __Pyx_MatchKeywordArg( + PyObject *key, + PyObject ** const argnames[], + PyObject ** const *first_kw_arg, + size_t *index_found, + const char *function_name) +{ + return likely(PyUnicode_CheckExact(key)) ? + __Pyx_MatchKeywordArg_str(key, argnames, first_kw_arg, index_found, function_name) : + __Pyx_MatchKeywordArg_nostr(key, argnames, first_kw_arg, index_found, function_name); +} +static void __Pyx_RejectUnknownKeyword( + PyObject *kwds, + PyObject ** const argnames[], + PyObject ** const *first_kw_arg, + const char *function_name) +{ + #if CYTHON_AVOID_BORROWED_REFS + PyObject *pos = NULL; + #else + Py_ssize_t pos = 0; + #endif + PyObject *key = NULL; + __Pyx_BEGIN_CRITICAL_SECTION(kwds); + while ( + #if CYTHON_AVOID_BORROWED_REFS + __Pyx_PyDict_NextRef(kwds, &pos, &key, NULL) + #else + PyDict_Next(kwds, &pos, &key, NULL) + #endif + ) { + PyObject** const *name = first_kw_arg; + while (*name && (**name != key)) name++; + if (!*name) { + size_t index_found = 0; + int cmp = __Pyx_MatchKeywordArg(key, argnames, first_kw_arg, &index_found, function_name); + if (cmp != 1) { + if (cmp == 0) { + PyErr_Format(PyExc_TypeError, + "%s() got an unexpected keyword argument '%U'", + function_name, key); + } + #if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(key); + #endif + break; + } + } + #if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(key); + #endif + } + __Pyx_END_CRITICAL_SECTION(); + #if CYTHON_AVOID_BORROWED_REFS + Py_XDECREF(pos); + #endif + assert(PyErr_Occurred()); +} +static int __Pyx_ParseKeywordDict( + PyObject *kwds, + PyObject ** const argnames[], + PyObject *values[], + Py_ssize_t num_pos_args, + Py_ssize_t num_kwargs, + const char* function_name, + int ignore_unknown_kwargs) +{ + PyObject** const *name; + PyObject** const *first_kw_arg = argnames + num_pos_args; + Py_ssize_t extracted = 0; +#if !CYTHON_COMPILING_IN_PYPY || defined(PyArg_ValidateKeywordArguments) + if (unlikely(!PyArg_ValidateKeywordArguments(kwds))) return -1; +#endif + name = first_kw_arg; + while (*name && num_kwargs > extracted) { + PyObject * key = **name; + PyObject *value; + int found = 0; + #if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + found = PyDict_GetItemRef(kwds, key, &value); + #else + value = PyDict_GetItemWithError(kwds, key); + if (value) { + Py_INCREF(value); + found = 1; + } else { + if (unlikely(PyErr_Occurred())) goto bad; + } + #endif + if (found) { + if (unlikely(found < 0)) goto bad; + values[name-argnames] = value; + extracted++; + } + name++; + } + if (num_kwargs > extracted) { + if (ignore_unknown_kwargs) { + if (unlikely(__Pyx_ValidateDuplicatePosArgs(kwds, argnames, first_kw_arg, function_name) == -1)) + goto bad; + } else { + __Pyx_RejectUnknownKeyword(kwds, argnames, first_kw_arg, function_name); + goto bad; + } + } + return 0; +bad: + return -1; +} +static int __Pyx_ParseKeywordDictToDict( + PyObject *kwds, + PyObject ** const argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + const char* function_name) +{ + PyObject** const *name; + PyObject** const *first_kw_arg = argnames + num_pos_args; + Py_ssize_t len; +#if !CYTHON_COMPILING_IN_PYPY || defined(PyArg_ValidateKeywordArguments) + if (unlikely(!PyArg_ValidateKeywordArguments(kwds))) return -1; +#endif + if (PyDict_Update(kwds2, kwds) < 0) goto bad; + name = first_kw_arg; + while (*name) { + PyObject *key = **name; + PyObject *value; +#if !CYTHON_COMPILING_IN_LIMITED_API && (PY_VERSION_HEX >= 0x030d00A2 || defined(PyDict_Pop)) + int found = PyDict_Pop(kwds2, key, &value); + if (found) { + if (unlikely(found < 0)) goto bad; + values[name-argnames] = value; + } +#elif __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + int found = PyDict_GetItemRef(kwds2, key, &value); + if (found) { + if (unlikely(found < 0)) goto bad; + values[name-argnames] = value; + if (unlikely(PyDict_DelItem(kwds2, key) < 0)) goto bad; + } +#else + #if CYTHON_COMPILING_IN_CPYTHON + value = _PyDict_Pop(kwds2, key, kwds2); + #else + value = __Pyx_CallUnboundCMethod2(&__pyx_mstate_global->__pyx_umethod_PyDict_Type_pop, kwds2, key, kwds2); + #endif + if (value == kwds2) { + Py_DECREF(value); + } else { + if (unlikely(!value)) goto bad; + values[name-argnames] = value; + } +#endif + name++; + } + len = PyDict_Size(kwds2); + if (len > 0) { + return __Pyx_ValidateDuplicatePosArgs(kwds, argnames, first_kw_arg, function_name); + } else if (unlikely(len == -1)) { + goto bad; + } + return 0; +bad: + return -1; +} +static int __Pyx_ParseKeywordsTuple( + PyObject *kwds, + PyObject * const *kwvalues, + PyObject ** const argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + Py_ssize_t num_kwargs, + const char* function_name, + int ignore_unknown_kwargs) +{ + PyObject *key = NULL; + PyObject** const * name; + PyObject** const *first_kw_arg = argnames + num_pos_args; + for (Py_ssize_t pos = 0; pos < num_kwargs; pos++) { +#if CYTHON_AVOID_BORROWED_REFS + key = __Pyx_PySequence_ITEM(kwds, pos); +#else + key = __Pyx_PyTuple_GET_ITEM(kwds, pos); +#endif +#if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(!key)) goto bad; +#endif + name = first_kw_arg; + while (*name && (**name != key)) name++; + if (*name) { + PyObject *value = kwvalues[pos]; + values[name-argnames] = __Pyx_NewRef(value); + } else { + size_t index_found = 0; + int cmp = __Pyx_MatchKeywordArg(key, argnames, first_kw_arg, &index_found, function_name); + if (cmp == 1) { + PyObject *value = kwvalues[pos]; + values[index_found] = __Pyx_NewRef(value); + } else { + if (unlikely(cmp == -1)) goto bad; + if (kwds2) { + PyObject *value = kwvalues[pos]; + if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; + } else if (!ignore_unknown_kwargs) { + goto invalid_keyword; + } + } + } + #if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(key); + key = NULL; + #endif + } + return 0; +invalid_keyword: + PyErr_Format(PyExc_TypeError, + "%s() got an unexpected keyword argument '%U'", + function_name, key); + goto bad; +bad: + #if CYTHON_AVOID_BORROWED_REFS + Py_XDECREF(key); + #endif + return -1; +} + +/* ParseKeywords */ +static int __Pyx_ParseKeywords( + PyObject *kwds, + PyObject * const *kwvalues, + PyObject ** const argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + Py_ssize_t num_kwargs, + const char* function_name, + int ignore_unknown_kwargs) +{ + if (CYTHON_METH_FASTCALL && likely(PyTuple_Check(kwds))) + return __Pyx_ParseKeywordsTuple(kwds, kwvalues, argnames, kwds2, values, num_pos_args, num_kwargs, function_name, ignore_unknown_kwargs); + else if (kwds2) + return __Pyx_ParseKeywordDictToDict(kwds, argnames, kwds2, values, num_pos_args, function_name); + else + return __Pyx_ParseKeywordDict(kwds, argnames, values, num_pos_args, num_kwargs, function_name, ignore_unknown_kwargs); +} + +/* RaiseArgTupleInvalid */ +static void __Pyx_RaiseArgtupleInvalid( + const char* func_name, + int exact, + Py_ssize_t num_min, + Py_ssize_t num_max, + Py_ssize_t num_found) +{ + Py_ssize_t num_expected; + const char *more_or_less; + if (num_found < num_min) { + num_expected = num_min; + more_or_less = "at least"; + } else { + num_expected = num_max; + more_or_less = "at most"; + } + if (exact) { + more_or_less = "exactly"; + } + PyErr_Format(PyExc_TypeError, + "%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)", + func_name, more_or_less, num_expected, + (num_expected == 1) ? "" : "s", num_found); +} + +/* ArgTypeTestFunc (used by ArgTypeTest) */ +static int __Pyx__ArgTypeTest(PyObject *obj, PyTypeObject *type, const char *name, int exact) +{ + __Pyx_TypeName type_name; + __Pyx_TypeName obj_type_name; + PyObject *extra_info = __pyx_mstate_global->__pyx_empty_unicode; + int from_annotation_subclass = 0; + if (unlikely(!type)) { + PyErr_SetString(PyExc_SystemError, "Missing type object"); + return 0; + } + else if (!exact) { + if (likely(__Pyx_TypeCheck(obj, type))) return 1; + } else if (exact == 2) { + if (__Pyx_TypeCheck(obj, type)) { + from_annotation_subclass = 1; + extra_info = __pyx_mstate_global->__pyx_kp_u_Note_that_Cython_is_deliberately; + } + } + type_name = __Pyx_PyType_GetFullyQualifiedName(type); + obj_type_name = __Pyx_PyType_GetFullyQualifiedName(Py_TYPE(obj)); + PyErr_Format(PyExc_TypeError, + "Argument '%.200s' has incorrect type (expected " __Pyx_FMT_TYPENAME + ", got " __Pyx_FMT_TYPENAME ")" +#if __PYX_LIMITED_VERSION_HEX < 0x030C0000 + "%s%U" +#endif + , name, type_name, obj_type_name +#if __PYX_LIMITED_VERSION_HEX < 0x030C0000 + , (from_annotation_subclass ? ". " : ""), extra_info +#endif + ); +#if __PYX_LIMITED_VERSION_HEX >= 0x030C0000 + if (exact == 2 && from_annotation_subclass) { + PyObject *res; + PyObject *vargs[2]; + vargs[0] = PyErr_GetRaisedException(); + vargs[1] = extra_info; + res = PyObject_VectorcallMethod(__pyx_mstate_global->__pyx_kp_u_add_note, vargs, 2, NULL); + Py_XDECREF(res); + PyErr_SetRaisedException(vargs[0]); + } +#endif + __Pyx_DECREF_TypeName(type_name); + __Pyx_DECREF_TypeName(obj_type_name); + return 0; +} + +/* ExtTypeTest */ +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { + __Pyx_TypeName obj_type_name; + __Pyx_TypeName type_name; + if (unlikely(!type)) { + PyErr_SetString(PyExc_SystemError, "Missing type object"); + return 0; + } + if (likely(__Pyx_TypeCheck(obj, type))) + return 1; + obj_type_name = __Pyx_PyType_GetFullyQualifiedName(Py_TYPE(obj)); + type_name = __Pyx_PyType_GetFullyQualifiedName(type); + PyErr_Format(PyExc_TypeError, + "Cannot convert " __Pyx_FMT_TYPENAME " to " __Pyx_FMT_TYPENAME, + obj_type_name, type_name); + __Pyx_DECREF_TypeName(obj_type_name); + __Pyx_DECREF_TypeName(type_name); + return 0; +} + +/* RejectKeywords */ +static void __Pyx_RejectKeywords(const char* function_name, PyObject *kwds) { + PyObject *key = NULL; + if (CYTHON_METH_FASTCALL && likely(PyTuple_Check(kwds))) { + key = __Pyx_PySequence_ITEM(kwds, 0); + } else { +#if CYTHON_AVOID_BORROWED_REFS + PyObject *pos = NULL; +#else + Py_ssize_t pos = 0; +#endif +#if !CYTHON_COMPILING_IN_PYPY || defined(PyArg_ValidateKeywordArguments) + if (unlikely(!PyArg_ValidateKeywordArguments(kwds))) return; +#endif + __Pyx_PyDict_NextRef(kwds, &pos, &key, NULL); +#if CYTHON_AVOID_BORROWED_REFS + Py_XDECREF(pos); +#endif + } + if (likely(key)) { + PyErr_Format(PyExc_TypeError, + "%s() got an unexpected keyword argument '%U'", + function_name, key); + Py_DECREF(key); + } +} + +/* PyObjectSetAttrStr */ +#if CYTHON_USE_TYPE_SLOTS +static CYTHON_INLINE int __Pyx_PyObject_SetAttrStr(PyObject* obj, PyObject* attr_name, PyObject* value) { + PyTypeObject* tp = Py_TYPE(obj); + if (likely(tp->tp_setattro)) + return tp->tp_setattro(obj, attr_name, value); + return PyObject_SetAttr(obj, attr_name, value); +} +#endif + +/* AllocateExtensionType */ +static PyObject *__Pyx_AllocateExtensionType(PyTypeObject *t, int is_final) { + if (is_final || likely(!__Pyx_PyType_HasFeature(t, Py_TPFLAGS_IS_ABSTRACT))) { + allocfunc alloc_func = __Pyx_PyType_GetSlot(t, tp_alloc, allocfunc); + return alloc_func(t, 0); + } else { + newfunc tp_new = __Pyx_PyType_TryGetSlot(&PyBaseObject_Type, tp_new, newfunc); + #if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000 + if (!tp_new) { + PyObject *new_str = PyUnicode_FromString("__new__"); + if (likely(new_str)) { + PyObject *o = PyObject_CallMethodObjArgs((PyObject *)&PyBaseObject_Type, new_str, t, NULL); + Py_DECREF(new_str); + return o; + } else + return NULL; + } else + #endif + return tp_new(t, __pyx_mstate_global->__pyx_empty_tuple, 0); + } +} + +/* CallTypeTraverse */ +#if !CYTHON_USE_TYPE_SPECS || (!CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x03090000) +#else +static int __Pyx_call_type_traverse(PyObject *o, int always_call, visitproc visit, void *arg) { + #if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x03090000 + if (__Pyx_get_runtime_version() < 0x03090000) return 0; + #endif + if (!always_call) { + PyTypeObject *base = __Pyx_PyObject_GetSlot(o, tp_base, PyTypeObject*); + unsigned long flags = PyType_GetFlags(base); + if (flags & Py_TPFLAGS_HEAPTYPE) { + return 0; + } + } + Py_VISIT((PyObject*)Py_TYPE(o)); + return 0; +} +#endif + +/* LimitedApiGetTypeDict (used by SetItemOnTypeDict) */ +#if CYTHON_COMPILING_IN_LIMITED_API +static Py_ssize_t __Pyx_GetTypeDictOffset(void) { + PyObject *tp_dictoffset_o; + Py_ssize_t tp_dictoffset; + tp_dictoffset_o = PyObject_GetAttrString((PyObject*)(&PyType_Type), "__dictoffset__"); + if (unlikely(!tp_dictoffset_o)) return -1; + tp_dictoffset = PyLong_AsSsize_t(tp_dictoffset_o); + Py_DECREF(tp_dictoffset_o); + if (unlikely(tp_dictoffset == 0)) { + PyErr_SetString( + PyExc_TypeError, + "'type' doesn't have a dictoffset"); + return -1; + } else if (unlikely(tp_dictoffset < 0)) { + PyErr_SetString( + PyExc_TypeError, + "'type' has an unexpected negative dictoffset. " + "Please report this as Cython bug"); + return -1; + } + return tp_dictoffset; +} +static PyObject *__Pyx_GetTypeDict(PyTypeObject *tp) { + static Py_ssize_t tp_dictoffset = 0; + if (unlikely(tp_dictoffset == 0)) { + tp_dictoffset = __Pyx_GetTypeDictOffset(); + if (unlikely(tp_dictoffset == -1 && PyErr_Occurred())) { + tp_dictoffset = 0; // try again next time? + return NULL; + } + } + return *(PyObject**)((char*)tp + tp_dictoffset); +} +#endif + +/* SetItemOnTypeDict (used by FixUpExtensionType) */ +static int __Pyx__SetItemOnTypeDict(PyTypeObject *tp, PyObject *k, PyObject *v) { + int result; + PyObject *tp_dict; +#if CYTHON_COMPILING_IN_LIMITED_API + tp_dict = __Pyx_GetTypeDict(tp); + if (unlikely(!tp_dict)) return -1; +#else + tp_dict = tp->tp_dict; +#endif + result = PyDict_SetItem(tp_dict, k, v); + if (likely(!result)) { + PyType_Modified(tp); + if (unlikely(PyObject_HasAttr(v, __pyx_mstate_global->__pyx_n_u_set_name))) { + PyObject *setNameResult = PyObject_CallMethodObjArgs(v, __pyx_mstate_global->__pyx_n_u_set_name, (PyObject *) tp, k, NULL); + if (!setNameResult) return -1; + Py_DECREF(setNameResult); + } + } + return result; +} + +/* FixUpExtensionType */ +static int __Pyx_fix_up_extension_type_from_spec(PyType_Spec *spec, PyTypeObject *type) { +#if __PYX_LIMITED_VERSION_HEX > 0x030900B1 + CYTHON_UNUSED_VAR(spec); + CYTHON_UNUSED_VAR(type); + CYTHON_UNUSED_VAR(__Pyx__SetItemOnTypeDict); +#else + const PyType_Slot *slot = spec->slots; + int changed = 0; +#if !CYTHON_COMPILING_IN_LIMITED_API + while (slot && slot->slot && slot->slot != Py_tp_members) + slot++; + if (slot && slot->slot == Py_tp_members) { +#if !CYTHON_COMPILING_IN_CPYTHON + const +#endif // !CYTHON_COMPILING_IN_CPYTHON) + PyMemberDef *memb = (PyMemberDef*) slot->pfunc; + while (memb && memb->name) { + if (memb->name[0] == '_' && memb->name[1] == '_') { + if (strcmp(memb->name, "__weaklistoffset__") == 0) { + assert(memb->type == T_PYSSIZET); + assert(memb->flags == READONLY); + type->tp_weaklistoffset = memb->offset; + changed = 1; + } + else if (strcmp(memb->name, "__dictoffset__") == 0) { + assert(memb->type == T_PYSSIZET); + assert(memb->flags == READONLY); + type->tp_dictoffset = memb->offset; + changed = 1; + } +#if CYTHON_METH_FASTCALL + else if (strcmp(memb->name, "__vectorcalloffset__") == 0) { + assert(memb->type == T_PYSSIZET); + assert(memb->flags == READONLY); + type->tp_vectorcall_offset = memb->offset; + changed = 1; + } +#endif // CYTHON_METH_FASTCALL +#if !CYTHON_COMPILING_IN_PYPY + else if (strcmp(memb->name, "__module__") == 0) { + PyObject *descr; + assert(memb->type == T_OBJECT); + assert(memb->flags == 0 || memb->flags == READONLY); + descr = PyDescr_NewMember(type, memb); + if (unlikely(!descr)) + return -1; + int set_item_result = PyDict_SetItem(type->tp_dict, PyDescr_NAME(descr), descr); + Py_DECREF(descr); + if (unlikely(set_item_result < 0)) { + return -1; + } + changed = 1; + } +#endif // !CYTHON_COMPILING_IN_PYPY + } + memb++; + } + } +#endif // !CYTHON_COMPILING_IN_LIMITED_API +#if !CYTHON_COMPILING_IN_PYPY + slot = spec->slots; + while (slot && slot->slot && slot->slot != Py_tp_getset) + slot++; + if (slot && slot->slot == Py_tp_getset) { + PyGetSetDef *getset = (PyGetSetDef*) slot->pfunc; + while (getset && getset->name) { + if (getset->name[0] == '_' && getset->name[1] == '_' && strcmp(getset->name, "__module__") == 0) { + PyObject *descr = PyDescr_NewGetSet(type, getset); + if (unlikely(!descr)) + return -1; + #if CYTHON_COMPILING_IN_LIMITED_API + PyObject *pyname = PyUnicode_FromString(getset->name); + if (unlikely(!pyname)) { + Py_DECREF(descr); + return -1; + } + int set_item_result = __Pyx_SetItemOnTypeDict(type, pyname, descr); + Py_DECREF(pyname); + #else + CYTHON_UNUSED_VAR(__Pyx__SetItemOnTypeDict); + int set_item_result = PyDict_SetItem(type->tp_dict, PyDescr_NAME(descr), descr); + #endif + Py_DECREF(descr); + if (unlikely(set_item_result < 0)) { + return -1; + } + changed = 1; + } + ++getset; + } + } +#else + CYTHON_UNUSED_VAR(__Pyx__SetItemOnTypeDict); +#endif // !CYTHON_COMPILING_IN_PYPY + if (changed) + PyType_Modified(type); +#endif // PY_VERSION_HEX > 0x030900B1 + return 0; +} + +/* ValidateBasesTuple (used by PyType_Ready) */ +#if CYTHON_COMPILING_IN_CPYTHON || CYTHON_COMPILING_IN_LIMITED_API || CYTHON_USE_TYPE_SPECS +static int __Pyx_validate_bases_tuple(const char *type_name, Py_ssize_t dictoffset, PyObject *bases) { + Py_ssize_t i, n; +#if CYTHON_ASSUME_SAFE_SIZE + n = PyTuple_GET_SIZE(bases); +#else + n = PyTuple_Size(bases); + if (unlikely(n < 0)) return -1; +#endif + for (i = 1; i < n; i++) + { + PyTypeObject *b; +#if CYTHON_AVOID_BORROWED_REFS + PyObject *b0 = PySequence_GetItem(bases, i); + if (!b0) return -1; +#elif CYTHON_ASSUME_SAFE_MACROS + PyObject *b0 = PyTuple_GET_ITEM(bases, i); +#else + PyObject *b0 = PyTuple_GetItem(bases, i); + if (!b0) return -1; +#endif + b = (PyTypeObject*) b0; + if (!__Pyx_PyType_HasFeature(b, Py_TPFLAGS_HEAPTYPE)) + { + __Pyx_TypeName b_name = __Pyx_PyType_GetFullyQualifiedName(b); + PyErr_Format(PyExc_TypeError, + "base class '" __Pyx_FMT_TYPENAME "' is not a heap type", b_name); + __Pyx_DECREF_TypeName(b_name); +#if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(b0); +#endif + return -1; + } + if (dictoffset == 0) + { + Py_ssize_t b_dictoffset = 0; +#if CYTHON_USE_TYPE_SLOTS + b_dictoffset = b->tp_dictoffset; +#else + PyObject *py_b_dictoffset = PyObject_GetAttrString((PyObject*)b, "__dictoffset__"); + if (!py_b_dictoffset) goto dictoffset_return; + b_dictoffset = PyLong_AsSsize_t(py_b_dictoffset); + Py_DECREF(py_b_dictoffset); + if (b_dictoffset == -1 && PyErr_Occurred()) goto dictoffset_return; +#endif + if (b_dictoffset) { + { + __Pyx_TypeName b_name = __Pyx_PyType_GetFullyQualifiedName(b); + PyErr_Format(PyExc_TypeError, + "extension type '%.200s' has no __dict__ slot, " + "but base type '" __Pyx_FMT_TYPENAME "' has: " + "either add 'cdef dict __dict__' to the extension type " + "or add '__slots__ = [...]' to the base type", + type_name, b_name); + __Pyx_DECREF_TypeName(b_name); + } +#if !CYTHON_USE_TYPE_SLOTS + dictoffset_return: +#endif +#if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(b0); +#endif + return -1; + } + } +#if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(b0); +#endif + } + return 0; +} +#endif + +/* PyType_Ready */ +CYTHON_UNUSED static int __Pyx_PyType_HasMultipleInheritance(PyTypeObject *t) { + while (t) { + PyObject *bases = __Pyx_PyType_GetSlot(t, tp_bases, PyObject*); + if (bases) { + return 1; + } + t = __Pyx_PyType_GetSlot(t, tp_base, PyTypeObject*); + } + return 0; +} +static int __Pyx_PyType_Ready(PyTypeObject *t) { +#if CYTHON_USE_TYPE_SPECS || !CYTHON_COMPILING_IN_CPYTHON || defined(PYSTON_MAJOR_VERSION) + (void)__Pyx_PyObject_CallMethod0; +#if CYTHON_USE_TYPE_SPECS + (void)__Pyx_validate_bases_tuple; +#endif + return PyType_Ready(t); +#else + int r; + if (!__Pyx_PyType_HasMultipleInheritance(t)) { + return PyType_Ready(t); + } + PyObject *bases = __Pyx_PyType_GetSlot(t, tp_bases, PyObject*); + if (bases && unlikely(__Pyx_validate_bases_tuple(t->tp_name, t->tp_dictoffset, bases) == -1)) + return -1; +#if !defined(PYSTON_MAJOR_VERSION) + { + int gc_was_enabled; + #if PY_VERSION_HEX >= 0x030A00b1 + gc_was_enabled = PyGC_Disable(); + (void)__Pyx_PyObject_CallMethod0; + #else + PyObject *ret, *py_status; + PyObject *gc = NULL; + #if (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM+0 >= 0x07030400) &&\ + !CYTHON_COMPILING_IN_GRAAL + gc = PyImport_GetModule(__pyx_mstate_global->__pyx_kp_u_gc); + #endif + if (unlikely(!gc)) gc = PyImport_Import(__pyx_mstate_global->__pyx_kp_u_gc); + if (unlikely(!gc)) return -1; + py_status = __Pyx_PyObject_CallMethod0(gc, __pyx_mstate_global->__pyx_kp_u_isenabled); + if (unlikely(!py_status)) { + Py_DECREF(gc); + return -1; + } + gc_was_enabled = __Pyx_PyObject_IsTrue(py_status); + Py_DECREF(py_status); + if (gc_was_enabled > 0) { + ret = __Pyx_PyObject_CallMethod0(gc, __pyx_mstate_global->__pyx_kp_u_disable); + if (unlikely(!ret)) { + Py_DECREF(gc); + return -1; + } + Py_DECREF(ret); + } else if (unlikely(gc_was_enabled == -1)) { + Py_DECREF(gc); + return -1; + } + #endif + t->tp_flags |= Py_TPFLAGS_HEAPTYPE; +#if PY_VERSION_HEX >= 0x030A0000 + t->tp_flags |= Py_TPFLAGS_IMMUTABLETYPE; +#endif +#else + (void)__Pyx_PyObject_CallMethod0; +#endif + r = PyType_Ready(t); +#if !defined(PYSTON_MAJOR_VERSION) + t->tp_flags &= ~Py_TPFLAGS_HEAPTYPE; + #if PY_VERSION_HEX >= 0x030A00b1 + if (gc_was_enabled) + PyGC_Enable(); + #else + if (gc_was_enabled) { + PyObject *tp, *v, *tb; + PyErr_Fetch(&tp, &v, &tb); + ret = __Pyx_PyObject_CallMethod0(gc, __pyx_mstate_global->__pyx_kp_u_enable); + if (likely(ret || r == -1)) { + Py_XDECREF(ret); + PyErr_Restore(tp, v, tb); + } else { + Py_XDECREF(tp); + Py_XDECREF(v); + Py_XDECREF(tb); + r = -1; + } + } + Py_DECREF(gc); + #endif + } +#endif + return r; +#endif +} + +/* DelItemOnTypeDict (used by SetupReduce) */ +static int __Pyx__DelItemOnTypeDict(PyTypeObject *tp, PyObject *k) { + int result; + PyObject *tp_dict; +#if CYTHON_COMPILING_IN_LIMITED_API + tp_dict = __Pyx_GetTypeDict(tp); + if (unlikely(!tp_dict)) return -1; +#else + tp_dict = tp->tp_dict; +#endif + result = PyDict_DelItem(tp_dict, k); + if (likely(!result)) PyType_Modified(tp); + return result; +} + +/* SetupReduce */ +static int __Pyx_setup_reduce_is_named(PyObject* meth, PyObject* name) { + int ret; + PyObject *name_attr; + name_attr = __Pyx_PyObject_GetAttrStrNoError(meth, __pyx_mstate_global->__pyx_n_u_name); + if (likely(name_attr)) { + ret = PyObject_RichCompareBool(name_attr, name, Py_EQ); + } else { + ret = -1; + } + if (unlikely(ret < 0)) { + PyErr_Clear(); + ret = 0; + } + Py_XDECREF(name_attr); + return ret; +} +static int __Pyx_setup_reduce(PyObject* type_obj) { + int ret = 0; + PyObject *object_reduce = NULL; + PyObject *object_getstate = NULL; + PyObject *object_reduce_ex = NULL; + PyObject *reduce = NULL; + PyObject *reduce_ex = NULL; + PyObject *reduce_cython = NULL; + PyObject *setstate = NULL; + PyObject *setstate_cython = NULL; + PyObject *getstate = NULL; +#if CYTHON_USE_PYTYPE_LOOKUP + getstate = _PyType_Lookup((PyTypeObject*)type_obj, __pyx_mstate_global->__pyx_n_u_getstate); +#else + getstate = __Pyx_PyObject_GetAttrStrNoError(type_obj, __pyx_mstate_global->__pyx_n_u_getstate); + if (!getstate && PyErr_Occurred()) { + goto __PYX_BAD; + } +#endif + if (getstate) { +#if CYTHON_USE_PYTYPE_LOOKUP + object_getstate = _PyType_Lookup(&PyBaseObject_Type, __pyx_mstate_global->__pyx_n_u_getstate); +#else + object_getstate = __Pyx_PyObject_GetAttrStrNoError((PyObject*)&PyBaseObject_Type, __pyx_mstate_global->__pyx_n_u_getstate); + if (!object_getstate && PyErr_Occurred()) { + goto __PYX_BAD; + } +#endif + if (object_getstate != getstate) { + goto __PYX_GOOD; + } + } +#if CYTHON_USE_PYTYPE_LOOKUP + object_reduce_ex = _PyType_Lookup(&PyBaseObject_Type, __pyx_mstate_global->__pyx_n_u_reduce_ex); if (!object_reduce_ex) goto __PYX_BAD; +#else + object_reduce_ex = __Pyx_PyObject_GetAttrStr((PyObject*)&PyBaseObject_Type, __pyx_mstate_global->__pyx_n_u_reduce_ex); if (!object_reduce_ex) goto __PYX_BAD; +#endif + reduce_ex = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_mstate_global->__pyx_n_u_reduce_ex); if (unlikely(!reduce_ex)) goto __PYX_BAD; + if (reduce_ex == object_reduce_ex) { +#if CYTHON_USE_PYTYPE_LOOKUP + object_reduce = _PyType_Lookup(&PyBaseObject_Type, __pyx_mstate_global->__pyx_n_u_reduce); if (!object_reduce) goto __PYX_BAD; +#else + object_reduce = __Pyx_PyObject_GetAttrStr((PyObject*)&PyBaseObject_Type, __pyx_mstate_global->__pyx_n_u_reduce); if (!object_reduce) goto __PYX_BAD; +#endif + reduce = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_mstate_global->__pyx_n_u_reduce); if (unlikely(!reduce)) goto __PYX_BAD; + if (reduce == object_reduce || __Pyx_setup_reduce_is_named(reduce, __pyx_mstate_global->__pyx_n_u_reduce_cython)) { + reduce_cython = __Pyx_PyObject_GetAttrStrNoError(type_obj, __pyx_mstate_global->__pyx_n_u_reduce_cython); + if (likely(reduce_cython)) { + ret = __Pyx_SetItemOnTypeDict((PyTypeObject*)type_obj, __pyx_mstate_global->__pyx_n_u_reduce, reduce_cython); if (unlikely(ret < 0)) goto __PYX_BAD; + ret = __Pyx_DelItemOnTypeDict((PyTypeObject*)type_obj, __pyx_mstate_global->__pyx_n_u_reduce_cython); if (unlikely(ret < 0)) goto __PYX_BAD; + } else if (reduce == object_reduce || PyErr_Occurred()) { + goto __PYX_BAD; + } + setstate = __Pyx_PyObject_GetAttrStrNoError(type_obj, __pyx_mstate_global->__pyx_n_u_setstate); + if (!setstate) PyErr_Clear(); + if (!setstate || __Pyx_setup_reduce_is_named(setstate, __pyx_mstate_global->__pyx_n_u_setstate_cython)) { + setstate_cython = __Pyx_PyObject_GetAttrStrNoError(type_obj, __pyx_mstate_global->__pyx_n_u_setstate_cython); + if (likely(setstate_cython)) { + ret = __Pyx_SetItemOnTypeDict((PyTypeObject*)type_obj, __pyx_mstate_global->__pyx_n_u_setstate, setstate_cython); if (unlikely(ret < 0)) goto __PYX_BAD; + ret = __Pyx_DelItemOnTypeDict((PyTypeObject*)type_obj, __pyx_mstate_global->__pyx_n_u_setstate_cython); if (unlikely(ret < 0)) goto __PYX_BAD; + } else if (!setstate || PyErr_Occurred()) { + goto __PYX_BAD; + } + } + PyType_Modified((PyTypeObject*)type_obj); + } + } + goto __PYX_GOOD; +__PYX_BAD: + if (!PyErr_Occurred()) { + __Pyx_TypeName type_obj_name = + __Pyx_PyType_GetFullyQualifiedName((PyTypeObject*)type_obj); + PyErr_Format(PyExc_RuntimeError, + "Unable to initialize pickling for " __Pyx_FMT_TYPENAME, type_obj_name); + __Pyx_DECREF_TypeName(type_obj_name); + } + ret = -1; +__PYX_GOOD: +#if !CYTHON_USE_PYTYPE_LOOKUP + Py_XDECREF(object_reduce); + Py_XDECREF(object_reduce_ex); + Py_XDECREF(object_getstate); + Py_XDECREF(getstate); +#endif + Py_XDECREF(reduce); + Py_XDECREF(reduce_ex); + Py_XDECREF(reduce_cython); + Py_XDECREF(setstate); + Py_XDECREF(setstate_cython); + return ret; +} + +/* TypeImport */ +#ifndef __PYX_HAVE_RT_ImportType_3_2_4 +#define __PYX_HAVE_RT_ImportType_3_2_4 +static PyTypeObject *__Pyx_ImportType_3_2_4(PyObject *module, const char *module_name, const char *class_name, + size_t size, size_t alignment, enum __Pyx_ImportType_CheckSize_3_2_4 check_size) +{ + PyObject *result = 0; + Py_ssize_t basicsize; + Py_ssize_t itemsize; +#if defined(Py_LIMITED_API) || (defined(CYTHON_COMPILING_IN_LIMITED_API) && CYTHON_COMPILING_IN_LIMITED_API) + PyObject *py_basicsize; + PyObject *py_itemsize; +#endif + result = PyObject_GetAttrString(module, class_name); + if (!result) + goto bad; + if (!PyType_Check(result)) { + PyErr_Format(PyExc_TypeError, + "%.200s.%.200s is not a type object", + module_name, class_name); + goto bad; + } +#if !( defined(Py_LIMITED_API) || (defined(CYTHON_COMPILING_IN_LIMITED_API) && CYTHON_COMPILING_IN_LIMITED_API) ) + basicsize = ((PyTypeObject *)result)->tp_basicsize; + itemsize = ((PyTypeObject *)result)->tp_itemsize; +#else + if (size == 0) { + return (PyTypeObject *)result; + } + py_basicsize = PyObject_GetAttrString(result, "__basicsize__"); + if (!py_basicsize) + goto bad; + basicsize = PyLong_AsSsize_t(py_basicsize); + Py_DECREF(py_basicsize); + py_basicsize = 0; + if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred()) + goto bad; + py_itemsize = PyObject_GetAttrString(result, "__itemsize__"); + if (!py_itemsize) + goto bad; + itemsize = PyLong_AsSsize_t(py_itemsize); + Py_DECREF(py_itemsize); + py_itemsize = 0; + if (itemsize == (Py_ssize_t)-1 && PyErr_Occurred()) + goto bad; +#endif + if (itemsize) { + if (size % alignment) { + alignment = size % alignment; + } + if (itemsize < (Py_ssize_t)alignment) + itemsize = (Py_ssize_t)alignment; + } + if ((size_t)(basicsize + itemsize) < size) { + PyErr_Format(PyExc_ValueError, + "%.200s.%.200s size changed, may indicate binary incompatibility. " + "Expected %zd from C header, got %zd from PyObject", + module_name, class_name, size, basicsize+itemsize); + goto bad; + } + if (check_size == __Pyx_ImportType_CheckSize_Error_3_2_4 && + ((size_t)basicsize > size || (size_t)(basicsize + itemsize) < size)) { + PyErr_Format(PyExc_ValueError, + "%.200s.%.200s size changed, may indicate binary incompatibility. " + "Expected %zd from C header, got %zd-%zd from PyObject", + module_name, class_name, size, basicsize, basicsize+itemsize); + goto bad; + } + else if (check_size == __Pyx_ImportType_CheckSize_Warn_3_2_4 && (size_t)basicsize > size) { + if (PyErr_WarnFormat(NULL, 0, + "%.200s.%.200s size changed, may indicate binary incompatibility. " + "Expected %zd from C header, got %zd from PyObject", + module_name, class_name, size, basicsize) < 0) { + goto bad; + } + } + return (PyTypeObject *)result; +bad: + Py_XDECREF(result); + return NULL; +} +#endif + +/* GetVTable */ +static void* __Pyx_GetVtable(PyTypeObject *type) { + void* ptr; +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *ob = PyObject_GetAttr((PyObject *)type, __pyx_mstate_global->__pyx_n_u_pyx_vtable); +#else + PyObject *ob = PyObject_GetItem(type->tp_dict, __pyx_mstate_global->__pyx_n_u_pyx_vtable); +#endif + if (!ob) + goto bad; + ptr = PyCapsule_GetPointer(ob, 0); + if (!ptr && !PyErr_Occurred()) + PyErr_SetString(PyExc_RuntimeError, "invalid vtable found for imported type"); + Py_DECREF(ob); + return ptr; +bad: + Py_XDECREF(ob); + return NULL; +} + +/* HasAttr (used by ImportImpl) */ +#if __PYX_LIMITED_VERSION_HEX < 0x030d0000 +static CYTHON_INLINE int __Pyx_HasAttr(PyObject *o, PyObject *n) { + PyObject *r; + if (unlikely(!PyUnicode_Check(n))) { + PyErr_SetString(PyExc_TypeError, + "hasattr(): attribute name must be string"); + return -1; + } + r = __Pyx_PyObject_GetAttrStrNoError(o, n); + if (!r) { + return (unlikely(PyErr_Occurred())) ? -1 : 0; + } else { + Py_DECREF(r); + return 1; + } +} +#endif + +/* ImportImpl (used by Import) */ +static int __Pyx__Import_GetModule(PyObject *qualname, PyObject **module) { + PyObject *imported_module = PyImport_GetModule(qualname); + if (unlikely(!imported_module)) { + *module = NULL; + if (PyErr_Occurred()) { + return -1; + } + return 0; + } + *module = imported_module; + return 1; +} +static int __Pyx__Import_Lookup(PyObject *qualname, PyObject *const *imported_names, Py_ssize_t len_imported_names, PyObject **module) { + PyObject *imported_module; + PyObject *top_level_package_name; + Py_ssize_t i; + int status, module_found; + Py_ssize_t dot_index; + module_found = __Pyx__Import_GetModule(qualname, &imported_module); + if (unlikely(!module_found || module_found == -1)) { + *module = NULL; + return module_found; + } + if (imported_names) { + for (i = 0; i < len_imported_names; i++) { + PyObject *imported_name = imported_names[i]; +#if __PYX_LIMITED_VERSION_HEX < 0x030d0000 + int has_imported_attribute = PyObject_HasAttr(imported_module, imported_name); +#else + int has_imported_attribute = PyObject_HasAttrWithError(imported_module, imported_name); + if (unlikely(has_imported_attribute == -1)) goto error; +#endif + if (!has_imported_attribute) { + goto not_found; + } + } + *module = imported_module; + return 1; + } + dot_index = PyUnicode_FindChar(qualname, '.', 0, PY_SSIZE_T_MAX, 1); + if (dot_index == -1) { + *module = imported_module; + return 1; + } + if (unlikely(dot_index == -2)) goto error; + top_level_package_name = PyUnicode_Substring(qualname, 0, dot_index); + if (unlikely(!top_level_package_name)) goto error; + Py_DECREF(imported_module); + status = __Pyx__Import_GetModule(top_level_package_name, module); + Py_DECREF(top_level_package_name); + return status; +error: + Py_DECREF(imported_module); + *module = NULL; + return -1; +not_found: + Py_DECREF(imported_module); + *module = NULL; + return 0; +} +static PyObject *__Pyx__Import(PyObject *name, PyObject *const *imported_names, Py_ssize_t len_imported_names, PyObject *qualname, PyObject *moddict, int level) { + PyObject *module = 0; + PyObject *empty_dict = 0; + PyObject *from_list = 0; + int module_found; + if (!qualname) { + qualname = name; + } + module_found = __Pyx__Import_Lookup(qualname, imported_names, len_imported_names, &module); + if (likely(module_found == 1)) { + return module; + } else if (unlikely(module_found == -1)) { + return NULL; + } + empty_dict = PyDict_New(); + if (unlikely(!empty_dict)) + goto bad; + if (imported_names) { +#if CYTHON_COMPILING_IN_CPYTHON + from_list = __Pyx_PyList_FromArray(imported_names, len_imported_names); + if (unlikely(!from_list)) + goto bad; +#else + from_list = PyList_New(len_imported_names); + if (unlikely(!from_list)) goto bad; + for (Py_ssize_t i=0; i__pyx_d, level); +} + +/* ImportFrom */ +static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name) { + PyObject* value = __Pyx_PyObject_GetAttrStr(module, name); + if (unlikely(!value) && PyErr_ExceptionMatches(PyExc_AttributeError)) { + const char* module_name_str = 0; + PyObject* module_name = 0; + PyObject* module_dot = 0; + PyObject* full_name = 0; + PyErr_Clear(); + module_name_str = PyModule_GetName(module); + if (unlikely(!module_name_str)) { goto modbad; } + module_name = PyUnicode_FromString(module_name_str); + if (unlikely(!module_name)) { goto modbad; } + module_dot = PyUnicode_Concat(module_name, __pyx_mstate_global->__pyx_kp_u_); + if (unlikely(!module_dot)) { goto modbad; } + full_name = PyUnicode_Concat(module_dot, name); + if (unlikely(!full_name)) { goto modbad; } + #if (CYTHON_COMPILING_IN_PYPY && PYPY_VERSION_NUM < 0x07030400) ||\ + CYTHON_COMPILING_IN_GRAAL + { + PyObject *modules = PyImport_GetModuleDict(); + if (unlikely(!modules)) + goto modbad; + value = PyObject_GetItem(modules, full_name); + } + #else + value = PyImport_GetModule(full_name); + #endif + modbad: + Py_XDECREF(full_name); + Py_XDECREF(module_dot); + Py_XDECREF(module_name); + } + if (unlikely(!value)) { + PyErr_Format(PyExc_ImportError, "cannot import name %S", name); + } + return value; +} + +/* Py3UpdateBases */ +static PyObject* +__Pyx_PEP560_update_bases(PyObject *bases) +{ + Py_ssize_t i, j, size_bases; + PyObject *base = NULL, *meth, *new_base, *result, *new_bases = NULL; +#if CYTHON_ASSUME_SAFE_SIZE + size_bases = PyTuple_GET_SIZE(bases); +#else + size_bases = PyTuple_Size(bases); + if (size_bases < 0) return NULL; +#endif + for (i = 0; i < size_bases; i++) { +#if CYTHON_AVOID_BORROWED_REFS + Py_CLEAR(base); +#endif +#if CYTHON_ASSUME_SAFE_MACROS + base = PyTuple_GET_ITEM(bases, i); +#else + base = PyTuple_GetItem(bases, i); + if (!base) goto error; +#endif +#if CYTHON_AVOID_BORROWED_REFS + Py_INCREF(base); +#endif + if (PyType_Check(base)) { + if (new_bases) { + if (PyList_Append(new_bases, base) < 0) { + goto error; + } + } + continue; + } + meth = __Pyx_PyObject_GetAttrStrNoError(base, __pyx_mstate_global->__pyx_n_u_mro_entries); + if (!meth && PyErr_Occurred()) { + goto error; + } + if (!meth) { + if (new_bases) { + if (PyList_Append(new_bases, base) < 0) { + goto error; + } + } + continue; + } + new_base = __Pyx_PyObject_CallOneArg(meth, bases); + Py_DECREF(meth); + if (!new_base) { + goto error; + } + if (!PyTuple_Check(new_base)) { + PyErr_SetString(PyExc_TypeError, + "__mro_entries__ must return a tuple"); + Py_DECREF(new_base); + goto error; + } + if (!new_bases) { + if (!(new_bases = PyList_New(i))) { + goto error; + } + for (j = 0; j < i; j++) { + PyObject *base_from_list; +#if CYTHON_ASSUME_SAFE_MACROS + base_from_list = PyTuple_GET_ITEM(bases, j); + PyList_SET_ITEM(new_bases, j, base_from_list); + Py_INCREF(base_from_list); +#else + base_from_list = PyTuple_GetItem(bases, j); + if (!base_from_list) goto error; + Py_INCREF(base_from_list); + if (PyList_SetItem(new_bases, j, base_from_list) < 0) goto error; +#endif + } + } +#if CYTHON_ASSUME_SAFE_SIZE + j = PyList_GET_SIZE(new_bases); +#else + j = PyList_Size(new_bases); + if (j < 0) goto error; +#endif + if (PyList_SetSlice(new_bases, j, j, new_base) < 0) { + goto error; + } + Py_DECREF(new_base); + } + if (!new_bases) { + Py_INCREF(bases); + return bases; + } + result = PyList_AsTuple(new_bases); + Py_DECREF(new_bases); +#if CYTHON_AVOID_BORROWED_REFS + Py_XDECREF(base); +#endif + return result; +error: + Py_XDECREF(new_bases); +#if CYTHON_AVOID_BORROWED_REFS + Py_XDECREF(base); +#endif + return NULL; +} + +/* CalculateMetaclass */ +static PyObject *__Pyx_CalculateMetaclass(PyTypeObject *metaclass, PyObject *bases) { + Py_ssize_t i, nbases; +#if CYTHON_ASSUME_SAFE_SIZE + nbases = PyTuple_GET_SIZE(bases); +#else + nbases = PyTuple_Size(bases); + if (nbases < 0) return NULL; +#endif + for (i=0; i < nbases; i++) { + PyTypeObject *tmptype; +#if CYTHON_ASSUME_SAFE_MACROS + PyObject *tmp = PyTuple_GET_ITEM(bases, i); +#else + PyObject *tmp = PyTuple_GetItem(bases, i); + if (!tmp) return NULL; +#endif + tmptype = Py_TYPE(tmp); + if (!metaclass) { + metaclass = tmptype; + continue; + } + if (PyType_IsSubtype(metaclass, tmptype)) + continue; + if (PyType_IsSubtype(tmptype, metaclass)) { + metaclass = tmptype; + continue; + } + PyErr_SetString(PyExc_TypeError, + "metaclass conflict: " + "the metaclass of a derived class " + "must be a (non-strict) subclass " + "of the metaclasses of all its bases"); + return NULL; + } + if (!metaclass) { + metaclass = &PyType_Type; + } + Py_INCREF((PyObject*) metaclass); + return (PyObject*) metaclass; +} + +/* PyObjectCall2Args (used by Py3ClassCreate) */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call2Args(PyObject* function, PyObject* arg1, PyObject* arg2) { + PyObject *args[3] = {NULL, arg1, arg2}; + return __Pyx_PyObject_FastCall(function, args+1, 2 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET); +} + +/* PyObjectLookupSpecial (used by Py3ClassCreate) */ +#if CYTHON_USE_PYTYPE_LOOKUP && CYTHON_USE_TYPE_SLOTS +static CYTHON_INLINE PyObject* __Pyx__PyObject_LookupSpecial(PyObject* obj, PyObject* attr_name, int with_error) { + PyObject *res; + PyTypeObject *tp = Py_TYPE(obj); + res = _PyType_Lookup(tp, attr_name); + if (likely(res)) { + descrgetfunc f = Py_TYPE(res)->tp_descr_get; + if (!f) { + Py_INCREF(res); + } else { + res = f(res, obj, (PyObject *)tp); + } + } else if (with_error) { + PyErr_SetObject(PyExc_AttributeError, attr_name); + } + return res; +} +#endif + +/* Py3ClassCreate */ +static PyObject *__Pyx_Py3MetaclassPrepare(PyObject *metaclass, PyObject *bases, PyObject *name, + PyObject *qualname, PyObject *mkw, PyObject *modname, PyObject *doc) { + PyObject *ns; + if (metaclass) { + PyObject *prep = __Pyx_PyObject_GetAttrStrNoError(metaclass, __pyx_mstate_global->__pyx_n_u_prepare); + if (prep) { + PyObject *pargs[3] = {NULL, name, bases}; + ns = __Pyx_PyObject_FastCallDict(prep, pargs+1, 2 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET, mkw); + Py_DECREF(prep); + } else { + if (unlikely(PyErr_Occurred())) + return NULL; + ns = PyDict_New(); + } + } else { + ns = PyDict_New(); + } + if (unlikely(!ns)) + return NULL; + if (unlikely(PyObject_SetItem(ns, __pyx_mstate_global->__pyx_n_u_module, modname) < 0)) goto bad; + if (unlikely(PyObject_SetItem(ns, __pyx_mstate_global->__pyx_n_u_qualname, qualname) < 0)) goto bad; + if (unlikely(doc && PyObject_SetItem(ns, __pyx_mstate_global->__pyx_n_u_doc, doc) < 0)) goto bad; + return ns; +bad: + Py_DECREF(ns); + return NULL; +} +static PyObject *__Pyx_Py3ClassCreate(PyObject *metaclass, PyObject *name, PyObject *bases, + PyObject *dict, PyObject *mkw, + int calculate_metaclass, int allow_py2_metaclass) { + PyObject *result; + PyObject *owned_metaclass = NULL; + PyObject *margs[4] = {NULL, name, bases, dict}; + if (allow_py2_metaclass) { + owned_metaclass = PyObject_GetItem(dict, __pyx_mstate_global->__pyx_n_u_metaclass); + if (owned_metaclass) { + metaclass = owned_metaclass; + } else if (likely(PyErr_ExceptionMatches(PyExc_KeyError))) { + PyErr_Clear(); + } else { + return NULL; + } + } + if (calculate_metaclass && (!metaclass || PyType_Check(metaclass))) { + metaclass = __Pyx_CalculateMetaclass((PyTypeObject*) metaclass, bases); + Py_XDECREF(owned_metaclass); + if (unlikely(!metaclass)) + return NULL; + owned_metaclass = metaclass; + } + result = __Pyx_PyObject_FastCallDict(metaclass, margs+1, 3 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET, mkw); + Py_XDECREF(owned_metaclass); + return result; +} + +/* dict_setdefault (used by FetchCommonType) */ +static CYTHON_INLINE PyObject *__Pyx_PyDict_SetDefault(PyObject *d, PyObject *key, PyObject *default_value) { + PyObject* value; +#if __PYX_LIMITED_VERSION_HEX >= 0x030F0000 || (!CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d00A4) + PyDict_SetDefaultRef(d, key, default_value, &value); +#elif CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX >= 0x030C0000 + PyObject *args[] = {d, key, default_value}; + value = PyObject_VectorcallMethod(__pyx_mstate_global->__pyx_n_u_setdefault, args, 3 | PY_VECTORCALL_ARGUMENTS_OFFSET, NULL); +#elif CYTHON_COMPILING_IN_LIMITED_API + value = PyObject_CallMethodObjArgs(d, __pyx_mstate_global->__pyx_n_u_setdefault, key, default_value, NULL); +#else + value = PyDict_SetDefault(d, key, default_value); + if (unlikely(!value)) return NULL; + Py_INCREF(value); +#endif + return value; +} + +/* AddModuleRef (used by FetchSharedCythonModule) */ +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + static PyObject *__Pyx_PyImport_AddModuleObjectRef(PyObject *name) { + PyObject *module_dict = PyImport_GetModuleDict(); + PyObject *m; + if (PyMapping_GetOptionalItem(module_dict, name, &m) < 0) { + return NULL; + } + if (m != NULL && PyModule_Check(m)) { + return m; + } + Py_XDECREF(m); + m = PyModule_NewObject(name); + if (m == NULL) + return NULL; + if (PyDict_CheckExact(module_dict)) { + PyObject *new_m; + (void)PyDict_SetDefaultRef(module_dict, name, m, &new_m); + Py_DECREF(m); + return new_m; + } else { + if (PyObject_SetItem(module_dict, name, m) != 0) { + Py_DECREF(m); + return NULL; + } + return m; + } + } + static PyObject *__Pyx_PyImport_AddModuleRef(const char *name) { + PyObject *py_name = PyUnicode_FromString(name); + if (!py_name) return NULL; + PyObject *module = __Pyx_PyImport_AddModuleObjectRef(py_name); + Py_DECREF(py_name); + return module; + } +#elif __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + #define __Pyx_PyImport_AddModuleRef(name) PyImport_AddModuleRef(name) +#else + static PyObject *__Pyx_PyImport_AddModuleRef(const char *name) { + PyObject *module = PyImport_AddModule(name); + Py_XINCREF(module); + return module; + } +#endif + +/* FetchSharedCythonModule (used by FetchCommonType) */ +static PyObject *__Pyx_FetchSharedCythonABIModule(void) { + return __Pyx_PyImport_AddModuleRef(__PYX_ABI_MODULE_NAME); +} + +/* FetchCommonType (used by CommonTypesMetaclass) */ +#if __PYX_LIMITED_VERSION_HEX < 0x030C0000 +static PyObject* __Pyx_PyType_FromMetaclass(PyTypeObject *metaclass, PyObject *module, PyType_Spec *spec, PyObject *bases) { + PyObject *result = __Pyx_PyType_FromModuleAndSpec(module, spec, bases); + if (result && metaclass) { + PyObject *old_tp = (PyObject*)Py_TYPE(result); + Py_INCREF((PyObject*)metaclass); +#if __PYX_LIMITED_VERSION_HEX >= 0x03090000 + Py_SET_TYPE(result, metaclass); +#else + result->ob_type = metaclass; +#endif + Py_DECREF(old_tp); + } + return result; +} +#else +#define __Pyx_PyType_FromMetaclass(me, mo, s, b) PyType_FromMetaclass(me, mo, s, b) +#endif +static int __Pyx_VerifyCachedType(PyObject *cached_type, + const char *name, + Py_ssize_t expected_basicsize) { + Py_ssize_t basicsize; + if (!PyType_Check(cached_type)) { + PyErr_Format(PyExc_TypeError, + "Shared Cython type %.200s is not a type object", name); + return -1; + } + if (expected_basicsize == 0) { + return 0; // size is inherited, nothing useful to check + } +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *py_basicsize; + py_basicsize = PyObject_GetAttrString(cached_type, "__basicsize__"); + if (unlikely(!py_basicsize)) return -1; + basicsize = PyLong_AsSsize_t(py_basicsize); + Py_DECREF(py_basicsize); + py_basicsize = NULL; + if (unlikely(basicsize == (Py_ssize_t)-1) && PyErr_Occurred()) return -1; +#else + basicsize = ((PyTypeObject*) cached_type)->tp_basicsize; +#endif + if (basicsize != expected_basicsize) { + PyErr_Format(PyExc_TypeError, + "Shared Cython type %.200s has the wrong size, try recompiling", + name); + return -1; + } + return 0; +} +static PyTypeObject *__Pyx_FetchCommonTypeFromSpec(PyTypeObject *metaclass, PyObject *module, PyType_Spec *spec, PyObject *bases) { + PyObject *abi_module = NULL, *cached_type = NULL, *abi_module_dict, *new_cached_type, *py_object_name; + int get_item_ref_result; + const char* object_name = strrchr(spec->name, '.'); + object_name = object_name ? object_name+1 : spec->name; + py_object_name = PyUnicode_FromString(object_name); + if (!py_object_name) return NULL; + abi_module = __Pyx_FetchSharedCythonABIModule(); + if (!abi_module) goto done; + abi_module_dict = PyModule_GetDict(abi_module); + if (!abi_module_dict) goto done; + get_item_ref_result = __Pyx_PyDict_GetItemRef(abi_module_dict, py_object_name, &cached_type); + if (get_item_ref_result == 1) { + if (__Pyx_VerifyCachedType( + cached_type, + object_name, + spec->basicsize) < 0) { + goto bad; + } + goto done; + } else if (unlikely(get_item_ref_result == -1)) { + goto bad; + } + cached_type = __Pyx_PyType_FromMetaclass( + metaclass, + CYTHON_USE_MODULE_STATE ? module : abi_module, + spec, bases); + if (unlikely(!cached_type)) goto bad; + if (unlikely(__Pyx_fix_up_extension_type_from_spec(spec, (PyTypeObject *) cached_type) < 0)) goto bad; + new_cached_type = __Pyx_PyDict_SetDefault(abi_module_dict, py_object_name, cached_type); + if (unlikely(new_cached_type != cached_type)) { + if (unlikely(!new_cached_type)) goto bad; + Py_DECREF(cached_type); + cached_type = new_cached_type; + if (__Pyx_VerifyCachedType( + cached_type, + object_name, + spec->basicsize) < 0) { + goto bad; + } + goto done; + } else { + Py_DECREF(new_cached_type); + } +done: + Py_XDECREF(abi_module); + Py_DECREF(py_object_name); + assert(cached_type == NULL || PyType_Check(cached_type)); + return (PyTypeObject *) cached_type; +bad: + Py_XDECREF(cached_type); + cached_type = NULL; + goto done; +} + +/* CommonTypesMetaclass (used by CythonFunctionShared) */ +static PyObject* __pyx_CommonTypesMetaclass_get_module(CYTHON_UNUSED PyObject *self, CYTHON_UNUSED void* context) { + return PyUnicode_FromString(__PYX_ABI_MODULE_NAME); +} +#if __PYX_LIMITED_VERSION_HEX < 0x030A0000 +static PyObject* __pyx_CommonTypesMetaclass_call(CYTHON_UNUSED PyObject *self, CYTHON_UNUSED PyObject *args, CYTHON_UNUSED PyObject *kwds) { + PyErr_SetString(PyExc_TypeError, "Cannot instantiate Cython internal types"); + return NULL; +} +static int __pyx_CommonTypesMetaclass_setattr(CYTHON_UNUSED PyObject *self, CYTHON_UNUSED PyObject *attr, CYTHON_UNUSED PyObject *value) { + PyErr_SetString(PyExc_TypeError, "Cython internal types are immutable"); + return -1; +} +#endif +static PyGetSetDef __pyx_CommonTypesMetaclass_getset[] = { + {"__module__", __pyx_CommonTypesMetaclass_get_module, NULL, NULL, NULL}, + {0, 0, 0, 0, 0} +}; +static PyType_Slot __pyx_CommonTypesMetaclass_slots[] = { + {Py_tp_getset, (void *)__pyx_CommonTypesMetaclass_getset}, + #if __PYX_LIMITED_VERSION_HEX < 0x030A0000 + {Py_tp_call, (void*)__pyx_CommonTypesMetaclass_call}, + {Py_tp_new, (void*)__pyx_CommonTypesMetaclass_call}, + {Py_tp_setattro, (void*)__pyx_CommonTypesMetaclass_setattr}, + #endif + {0, 0} +}; +static PyType_Spec __pyx_CommonTypesMetaclass_spec = { + __PYX_TYPE_MODULE_PREFIX "_common_types_metatype", + 0, + 0, + Py_TPFLAGS_IMMUTABLETYPE | + Py_TPFLAGS_DISALLOW_INSTANTIATION | + Py_TPFLAGS_DEFAULT, + __pyx_CommonTypesMetaclass_slots +}; +static int __pyx_CommonTypesMetaclass_init(PyObject *module) { + __pyx_mstatetype *mstate = __Pyx_PyModule_GetState(module); + PyObject *bases = PyTuple_Pack(1, &PyType_Type); + if (unlikely(!bases)) { + return -1; + } + mstate->__pyx_CommonTypesMetaclassType = __Pyx_FetchCommonTypeFromSpec(NULL, module, &__pyx_CommonTypesMetaclass_spec, bases); + Py_DECREF(bases); + if (unlikely(mstate->__pyx_CommonTypesMetaclassType == NULL)) { + return -1; + } + return 0; +} + +/* PyMethodNew (used by CythonFunctionShared) */ +#if CYTHON_COMPILING_IN_LIMITED_API +static PyObject *__Pyx_PyMethod_New(PyObject *func, PyObject *self, PyObject *typ) { + PyObject *result; + CYTHON_UNUSED_VAR(typ); + if (!self) + return __Pyx_NewRef(func); + #if __PYX_LIMITED_VERSION_HEX >= 0x030C0000 + { + PyObject *args[] = {func, self}; + result = PyObject_Vectorcall(__pyx_mstate_global->__Pyx_CachedMethodType, args, 2, NULL); + } + #else + result = PyObject_CallFunctionObjArgs(__pyx_mstate_global->__Pyx_CachedMethodType, func, self, NULL); + #endif + return result; +} +#else +static PyObject *__Pyx_PyMethod_New(PyObject *func, PyObject *self, PyObject *typ) { + CYTHON_UNUSED_VAR(typ); + if (!self) + return __Pyx_NewRef(func); + return PyMethod_New(func, self); +} +#endif + +/* PyVectorcallFastCallDict (used by CythonFunctionShared) */ +#if CYTHON_METH_FASTCALL && CYTHON_VECTORCALL +static PyObject *__Pyx_PyVectorcall_FastCallDict_kw(PyObject *func, __pyx_vectorcallfunc vc, PyObject *const *args, size_t nargs, PyObject *kw) +{ + PyObject *res = NULL; + PyObject *kwnames; + PyObject **newargs; + PyObject **kwvalues; + Py_ssize_t i; + #if CYTHON_AVOID_BORROWED_REFS + PyObject *pos; + #else + Py_ssize_t pos; + #endif + size_t j; + PyObject *key, *value; + unsigned long keys_are_strings; + #if !CYTHON_ASSUME_SAFE_SIZE + Py_ssize_t nkw = PyDict_Size(kw); + if (unlikely(nkw == -1)) return NULL; + #else + Py_ssize_t nkw = PyDict_GET_SIZE(kw); + #endif + newargs = (PyObject **)PyMem_Malloc((nargs + (size_t)nkw) * sizeof(args[0])); + if (unlikely(newargs == NULL)) { + PyErr_NoMemory(); + return NULL; + } + for (j = 0; j < nargs; j++) newargs[j] = args[j]; + kwnames = PyTuple_New(nkw); + if (unlikely(kwnames == NULL)) { + PyMem_Free(newargs); + return NULL; + } + kwvalues = newargs + nargs; + pos = 0; + i = 0; + keys_are_strings = Py_TPFLAGS_UNICODE_SUBCLASS; + while (__Pyx_PyDict_NextRef(kw, &pos, &key, &value)) { + keys_are_strings &= + #if CYTHON_COMPILING_IN_LIMITED_API + PyType_GetFlags(Py_TYPE(key)); + #else + Py_TYPE(key)->tp_flags; + #endif + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(PyTuple_SetItem(kwnames, i, key) < 0)) goto cleanup; + #else + PyTuple_SET_ITEM(kwnames, i, key); + #endif + kwvalues[i] = value; + i++; + } + if (unlikely(!keys_are_strings)) { + PyErr_SetString(PyExc_TypeError, "keywords must be strings"); + goto cleanup; + } + res = vc(func, newargs, nargs, kwnames); +cleanup: + #if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(pos); + #endif + Py_DECREF(kwnames); + for (i = 0; i < nkw; i++) + Py_DECREF(kwvalues[i]); + PyMem_Free(newargs); + return res; +} +static CYTHON_INLINE PyObject *__Pyx_PyVectorcall_FastCallDict(PyObject *func, __pyx_vectorcallfunc vc, PyObject *const *args, size_t nargs, PyObject *kw) +{ + Py_ssize_t kw_size = + likely(kw == NULL) ? + 0 : +#if !CYTHON_ASSUME_SAFE_SIZE + PyDict_Size(kw); +#else + PyDict_GET_SIZE(kw); +#endif + if (kw_size == 0) { + return vc(func, args, nargs, NULL); + } +#if !CYTHON_ASSUME_SAFE_SIZE + else if (unlikely(kw_size == -1)) { + return NULL; + } +#endif + return __Pyx_PyVectorcall_FastCallDict_kw(func, vc, args, nargs, kw); +} +#endif + +/* CythonFunctionShared (used by CythonFunction) */ +#if CYTHON_COMPILING_IN_LIMITED_API +static CYTHON_INLINE int __Pyx__IsSameCyOrCFunctionNoMethod(PyObject *func, void (*cfunc)(void)) { + if (__Pyx_CyFunction_Check(func)) { + return PyCFunction_GetFunction(((__pyx_CyFunctionObject*)func)->func) == (PyCFunction) cfunc; + } else if (PyCFunction_Check(func)) { + return PyCFunction_GetFunction(func) == (PyCFunction) cfunc; + } + return 0; +} +static CYTHON_INLINE int __Pyx__IsSameCyOrCFunction(PyObject *func, void (*cfunc)(void)) { + if ((PyObject*)Py_TYPE(func) == __pyx_mstate_global->__Pyx_CachedMethodType) { + int result; + PyObject *newFunc = PyObject_GetAttr(func, __pyx_mstate_global->__pyx_n_u_func); + if (unlikely(!newFunc)) { + PyErr_Clear(); // It's only an optimization, so don't throw an error + return 0; + } + result = __Pyx__IsSameCyOrCFunctionNoMethod(newFunc, cfunc); + Py_DECREF(newFunc); + return result; + } + return __Pyx__IsSameCyOrCFunctionNoMethod(func, cfunc); +} +#else +static CYTHON_INLINE int __Pyx__IsSameCyOrCFunction(PyObject *func, void (*cfunc)(void)) { + if (PyMethod_Check(func)) { + func = PyMethod_GET_FUNCTION(func); + } + return __Pyx_CyOrPyCFunction_Check(func) && __Pyx_CyOrPyCFunction_GET_FUNCTION(func) == (PyCFunction) cfunc; +} +#endif +static CYTHON_INLINE void __Pyx__CyFunction_SetClassObj(__pyx_CyFunctionObject* f, PyObject* classobj) { +#if PY_VERSION_HEX < 0x030900B1 || CYTHON_COMPILING_IN_LIMITED_API + __Pyx_Py_XDECREF_SET( + __Pyx_CyFunction_GetClassObj(f), + ((classobj) ? __Pyx_NewRef(classobj) : NULL)); +#else + __Pyx_Py_XDECREF_SET( + ((PyCMethodObject *) (f))->mm_class, + (PyTypeObject*)((classobj) ? __Pyx_NewRef(classobj) : NULL)); +#endif +} +static PyObject * +__Pyx_CyFunction_get_doc_locked(__pyx_CyFunctionObject *op) +{ + if (unlikely(op->func_doc == NULL)) { +#if CYTHON_COMPILING_IN_LIMITED_API + op->func_doc = PyObject_GetAttrString(op->func, "__doc__"); + if (unlikely(!op->func_doc)) return NULL; +#else + if (((PyCFunctionObject*)op)->m_ml->ml_doc) { + op->func_doc = PyUnicode_FromString(((PyCFunctionObject*)op)->m_ml->ml_doc); + if (unlikely(op->func_doc == NULL)) + return NULL; + } else { + Py_INCREF(Py_None); + return Py_None; + } +#endif + } + Py_INCREF(op->func_doc); + return op->func_doc; +} +static PyObject * +__Pyx_CyFunction_get_doc(__pyx_CyFunctionObject *op, void *closure) { + PyObject *result; + CYTHON_UNUSED_VAR(closure); + __Pyx_BEGIN_CRITICAL_SECTION(op); + result = __Pyx_CyFunction_get_doc_locked(op); + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static int +__Pyx_CyFunction_set_doc(__pyx_CyFunctionObject *op, PyObject *value, void *context) +{ + CYTHON_UNUSED_VAR(context); + if (value == NULL) { + value = Py_None; + } + Py_INCREF(value); + __Pyx_BEGIN_CRITICAL_SECTION(op); + __Pyx_Py_XDECREF_SET(op->func_doc, value); + __Pyx_END_CRITICAL_SECTION(); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_name_locked(__pyx_CyFunctionObject *op) +{ + if (unlikely(op->func_name == NULL)) { +#if CYTHON_COMPILING_IN_LIMITED_API + op->func_name = PyObject_GetAttrString(op->func, "__name__"); +#else + op->func_name = PyUnicode_InternFromString(((PyCFunctionObject*)op)->m_ml->ml_name); +#endif + if (unlikely(op->func_name == NULL)) + return NULL; + } + Py_INCREF(op->func_name); + return op->func_name; +} +static PyObject * +__Pyx_CyFunction_get_name(__pyx_CyFunctionObject *op, void *context) +{ + PyObject *result = NULL; + CYTHON_UNUSED_VAR(context); + __Pyx_BEGIN_CRITICAL_SECTION(op); + result = __Pyx_CyFunction_get_name_locked(op); + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static int +__Pyx_CyFunction_set_name(__pyx_CyFunctionObject *op, PyObject *value, void *context) +{ + CYTHON_UNUSED_VAR(context); + if (unlikely(value == NULL || !PyUnicode_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "__name__ must be set to a string object"); + return -1; + } + Py_INCREF(value); + __Pyx_BEGIN_CRITICAL_SECTION(op); + __Pyx_Py_XDECREF_SET(op->func_name, value); + __Pyx_END_CRITICAL_SECTION(); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_qualname(__pyx_CyFunctionObject *op, void *context) +{ + CYTHON_UNUSED_VAR(context); + PyObject *result; + __Pyx_BEGIN_CRITICAL_SECTION(op); + Py_INCREF(op->func_qualname); + result = op->func_qualname; + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static int +__Pyx_CyFunction_set_qualname(__pyx_CyFunctionObject *op, PyObject *value, void *context) +{ + CYTHON_UNUSED_VAR(context); + if (unlikely(value == NULL || !PyUnicode_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "__qualname__ must be set to a string object"); + return -1; + } + Py_INCREF(value); + __Pyx_BEGIN_CRITICAL_SECTION(op); + __Pyx_Py_XDECREF_SET(op->func_qualname, value); + __Pyx_END_CRITICAL_SECTION(); + return 0; +} +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000 +static PyObject * +__Pyx_CyFunction_get_dict(__pyx_CyFunctionObject *op, void *context) +{ + CYTHON_UNUSED_VAR(context); + if (unlikely(op->func_dict == NULL)) { + op->func_dict = PyDict_New(); + if (unlikely(op->func_dict == NULL)) + return NULL; + } + Py_INCREF(op->func_dict); + return op->func_dict; +} +#endif +static PyObject * +__Pyx_CyFunction_get_globals(__pyx_CyFunctionObject *op, void *context) +{ + CYTHON_UNUSED_VAR(context); + Py_INCREF(op->func_globals); + return op->func_globals; +} +static PyObject * +__Pyx_CyFunction_get_closure(__pyx_CyFunctionObject *op, void *context) +{ + CYTHON_UNUSED_VAR(op); + CYTHON_UNUSED_VAR(context); + Py_INCREF(Py_None); + return Py_None; +} +static PyObject * +__Pyx_CyFunction_get_code(__pyx_CyFunctionObject *op, void *context) +{ + PyObject* result = (op->func_code) ? op->func_code : Py_None; + CYTHON_UNUSED_VAR(context); + Py_INCREF(result); + return result; +} +static int +__Pyx_CyFunction_init_defaults(__pyx_CyFunctionObject *op) { + int result = 0; + PyObject *res = op->defaults_getter((PyObject *) op); + if (unlikely(!res)) + return -1; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + op->defaults_tuple = PyTuple_GET_ITEM(res, 0); + Py_INCREF(op->defaults_tuple); + op->defaults_kwdict = PyTuple_GET_ITEM(res, 1); + Py_INCREF(op->defaults_kwdict); + #else + op->defaults_tuple = __Pyx_PySequence_ITEM(res, 0); + if (unlikely(!op->defaults_tuple)) result = -1; + else { + op->defaults_kwdict = __Pyx_PySequence_ITEM(res, 1); + if (unlikely(!op->defaults_kwdict)) result = -1; + } + #endif + Py_DECREF(res); + return result; +} +static int +__Pyx_CyFunction_set_defaults(__pyx_CyFunctionObject *op, PyObject* value, void *context) { + CYTHON_UNUSED_VAR(context); + if (!value) { + value = Py_None; + } else if (unlikely(value != Py_None && !PyTuple_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "__defaults__ must be set to a tuple object"); + return -1; + } + PyErr_WarnEx(PyExc_RuntimeWarning, "changes to cyfunction.__defaults__ will not " + "currently affect the values used in function calls", 1); + Py_INCREF(value); + __Pyx_BEGIN_CRITICAL_SECTION(op); + __Pyx_Py_XDECREF_SET(op->defaults_tuple, value); + __Pyx_END_CRITICAL_SECTION(); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_defaults_locked(__pyx_CyFunctionObject *op) { + PyObject* result = op->defaults_tuple; + if (unlikely(!result)) { + if (op->defaults_getter) { + if (unlikely(__Pyx_CyFunction_init_defaults(op) < 0)) return NULL; + result = op->defaults_tuple; + } else { + result = Py_None; + } + } + Py_INCREF(result); + return result; +} +static PyObject * +__Pyx_CyFunction_get_defaults(__pyx_CyFunctionObject *op, void *context) { + PyObject* result = NULL; + CYTHON_UNUSED_VAR(context); + __Pyx_BEGIN_CRITICAL_SECTION(op); + result = __Pyx_CyFunction_get_defaults_locked(op); + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static int +__Pyx_CyFunction_set_kwdefaults(__pyx_CyFunctionObject *op, PyObject* value, void *context) { + CYTHON_UNUSED_VAR(context); + if (!value) { + value = Py_None; + } else if (unlikely(value != Py_None && !PyDict_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "__kwdefaults__ must be set to a dict object"); + return -1; + } + PyErr_WarnEx(PyExc_RuntimeWarning, "changes to cyfunction.__kwdefaults__ will not " + "currently affect the values used in function calls", 1); + Py_INCREF(value); + __Pyx_BEGIN_CRITICAL_SECTION(op); + __Pyx_Py_XDECREF_SET(op->defaults_kwdict, value); + __Pyx_END_CRITICAL_SECTION(); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_kwdefaults_locked(__pyx_CyFunctionObject *op) { + PyObject* result = op->defaults_kwdict; + if (unlikely(!result)) { + if (op->defaults_getter) { + if (unlikely(__Pyx_CyFunction_init_defaults(op) < 0)) return NULL; + result = op->defaults_kwdict; + } else { + result = Py_None; + } + } + Py_INCREF(result); + return result; +} +static PyObject * +__Pyx_CyFunction_get_kwdefaults(__pyx_CyFunctionObject *op, void *context) { + PyObject* result; + CYTHON_UNUSED_VAR(context); + __Pyx_BEGIN_CRITICAL_SECTION(op); + result = __Pyx_CyFunction_get_kwdefaults_locked(op); + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static int +__Pyx_CyFunction_set_annotations(__pyx_CyFunctionObject *op, PyObject* value, void *context) { + CYTHON_UNUSED_VAR(context); + if (!value || value == Py_None) { + value = NULL; + } else if (unlikely(!PyDict_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "__annotations__ must be set to a dict object"); + return -1; + } + Py_XINCREF(value); + __Pyx_BEGIN_CRITICAL_SECTION(op); + __Pyx_Py_XDECREF_SET(op->func_annotations, value); + __Pyx_END_CRITICAL_SECTION(); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_annotations_locked(__pyx_CyFunctionObject *op) { + PyObject* result = op->func_annotations; + if (unlikely(!result)) { + result = PyDict_New(); + if (unlikely(!result)) return NULL; + op->func_annotations = result; + } + Py_INCREF(result); + return result; +} +static PyObject * +__Pyx_CyFunction_get_annotations(__pyx_CyFunctionObject *op, void *context) { + PyObject *result; + CYTHON_UNUSED_VAR(context); + __Pyx_BEGIN_CRITICAL_SECTION(op); + result = __Pyx_CyFunction_get_annotations_locked(op); + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static PyObject * +__Pyx_CyFunction_get_is_coroutine_value(__pyx_CyFunctionObject *op) { + int is_coroutine = op->flags & __Pyx_CYFUNCTION_COROUTINE; + if (is_coroutine) { + PyObject *is_coroutine_value, *module, *fromlist, *marker = __pyx_mstate_global->__pyx_n_u_is_coroutine; + fromlist = PyList_New(1); + if (unlikely(!fromlist)) return NULL; + Py_INCREF(marker); +#if CYTHON_ASSUME_SAFE_MACROS + PyList_SET_ITEM(fromlist, 0, marker); +#else + if (unlikely(PyList_SetItem(fromlist, 0, marker) < 0)) { + Py_DECREF(marker); + Py_DECREF(fromlist); + return NULL; + } +#endif + module = PyImport_ImportModuleLevelObject(__pyx_mstate_global->__pyx_n_u_asyncio_coroutines, NULL, NULL, fromlist, 0); + Py_DECREF(fromlist); + if (unlikely(!module)) goto ignore; + is_coroutine_value = __Pyx_PyObject_GetAttrStr(module, marker); + Py_DECREF(module); + if (likely(is_coroutine_value)) { + return is_coroutine_value; + } +ignore: + PyErr_Clear(); + } + return __Pyx_PyBool_FromLong(is_coroutine); +} +static PyObject * +__Pyx_CyFunction_get_is_coroutine(__pyx_CyFunctionObject *op, void *context) { + PyObject *result; + CYTHON_UNUSED_VAR(context); + if (op->func_is_coroutine) { + return __Pyx_NewRef(op->func_is_coroutine); + } + result = __Pyx_CyFunction_get_is_coroutine_value(op); + if (unlikely(!result)) + return NULL; + __Pyx_BEGIN_CRITICAL_SECTION(op); + if (op->func_is_coroutine) { + Py_DECREF(result); + result = __Pyx_NewRef(op->func_is_coroutine); + } else { + op->func_is_coroutine = __Pyx_NewRef(result); + } + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static void __Pyx_CyFunction_raise_argument_count_error(__pyx_CyFunctionObject *func, const char* message, Py_ssize_t size) { +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *py_name = __Pyx_CyFunction_get_name(func, NULL); + if (!py_name) return; + PyErr_Format(PyExc_TypeError, + "%.200S() %s (%" CYTHON_FORMAT_SSIZE_T "d given)", + py_name, message, size); + Py_DECREF(py_name); +#else + const char* name = ((PyCFunctionObject*)func)->m_ml->ml_name; + PyErr_Format(PyExc_TypeError, + "%.200s() %s (%" CYTHON_FORMAT_SSIZE_T "d given)", + name, message, size); +#endif +} +static void __Pyx_CyFunction_raise_type_error(__pyx_CyFunctionObject *func, const char* message) { +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *py_name = __Pyx_CyFunction_get_name(func, NULL); + if (!py_name) return; + PyErr_Format(PyExc_TypeError, + "%.200S() %s", + py_name, message); + Py_DECREF(py_name); +#else + const char* name = ((PyCFunctionObject*)func)->m_ml->ml_name; + PyErr_Format(PyExc_TypeError, + "%.200s() %s", + name, message); +#endif +} +#if CYTHON_COMPILING_IN_LIMITED_API +static PyObject * +__Pyx_CyFunction_get_module(__pyx_CyFunctionObject *op, void *context) { + CYTHON_UNUSED_VAR(context); + return PyObject_GetAttrString(op->func, "__module__"); +} +static int +__Pyx_CyFunction_set_module(__pyx_CyFunctionObject *op, PyObject* value, void *context) { + CYTHON_UNUSED_VAR(context); + return PyObject_SetAttrString(op->func, "__module__", value); +} +#endif +static PyGetSetDef __pyx_CyFunction_getsets[] = { + {"func_doc", (getter)__Pyx_CyFunction_get_doc, (setter)__Pyx_CyFunction_set_doc, 0, 0}, + {"__doc__", (getter)__Pyx_CyFunction_get_doc, (setter)__Pyx_CyFunction_set_doc, 0, 0}, + {"func_name", (getter)__Pyx_CyFunction_get_name, (setter)__Pyx_CyFunction_set_name, 0, 0}, + {"__name__", (getter)__Pyx_CyFunction_get_name, (setter)__Pyx_CyFunction_set_name, 0, 0}, + {"__qualname__", (getter)__Pyx_CyFunction_get_qualname, (setter)__Pyx_CyFunction_set_qualname, 0, 0}, +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000 + {"func_dict", (getter)__Pyx_CyFunction_get_dict, (setter)PyObject_GenericSetDict, 0, 0}, + {"__dict__", (getter)__Pyx_CyFunction_get_dict, (setter)PyObject_GenericSetDict, 0, 0}, +#else + {"func_dict", (getter)PyObject_GenericGetDict, (setter)PyObject_GenericSetDict, 0, 0}, + {"__dict__", (getter)PyObject_GenericGetDict, (setter)PyObject_GenericSetDict, 0, 0}, +#endif + {"func_globals", (getter)__Pyx_CyFunction_get_globals, 0, 0, 0}, + {"__globals__", (getter)__Pyx_CyFunction_get_globals, 0, 0, 0}, + {"func_closure", (getter)__Pyx_CyFunction_get_closure, 0, 0, 0}, + {"__closure__", (getter)__Pyx_CyFunction_get_closure, 0, 0, 0}, + {"func_code", (getter)__Pyx_CyFunction_get_code, 0, 0, 0}, + {"__code__", (getter)__Pyx_CyFunction_get_code, 0, 0, 0}, + {"func_defaults", (getter)__Pyx_CyFunction_get_defaults, (setter)__Pyx_CyFunction_set_defaults, 0, 0}, + {"__defaults__", (getter)__Pyx_CyFunction_get_defaults, (setter)__Pyx_CyFunction_set_defaults, 0, 0}, + {"__kwdefaults__", (getter)__Pyx_CyFunction_get_kwdefaults, (setter)__Pyx_CyFunction_set_kwdefaults, 0, 0}, + {"__annotations__", (getter)__Pyx_CyFunction_get_annotations, (setter)__Pyx_CyFunction_set_annotations, 0, 0}, + {"_is_coroutine", (getter)__Pyx_CyFunction_get_is_coroutine, 0, 0, 0}, +#if CYTHON_COMPILING_IN_LIMITED_API + {"__module__", (getter)__Pyx_CyFunction_get_module, (setter)__Pyx_CyFunction_set_module, 0, 0}, +#endif + {0, 0, 0, 0, 0} +}; +static PyMemberDef __pyx_CyFunction_members[] = { +#if !CYTHON_COMPILING_IN_LIMITED_API + {"__module__", T_OBJECT, offsetof(PyCFunctionObject, m_module), 0, 0}, +#endif +#if PY_VERSION_HEX < 0x030C0000 || CYTHON_COMPILING_IN_LIMITED_API + {"__dictoffset__", T_PYSSIZET, offsetof(__pyx_CyFunctionObject, func_dict), READONLY, 0}, +#endif +#if CYTHON_METH_FASTCALL +#if CYTHON_COMPILING_IN_LIMITED_API + {"__vectorcalloffset__", T_PYSSIZET, offsetof(__pyx_CyFunctionObject, func_vectorcall), READONLY, 0}, +#else + {"__vectorcalloffset__", T_PYSSIZET, offsetof(PyCFunctionObject, vectorcall), READONLY, 0}, +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + {"__weaklistoffset__", T_PYSSIZET, offsetof(__pyx_CyFunctionObject, func_weakreflist), READONLY, 0}, +#else + {"__weaklistoffset__", T_PYSSIZET, offsetof(PyCFunctionObject, m_weakreflist), READONLY, 0}, +#endif +#endif + {0, 0, 0, 0, 0} +}; +static PyObject * +__Pyx_CyFunction_reduce(__pyx_CyFunctionObject *m, PyObject *args) +{ + PyObject *result = NULL; + CYTHON_UNUSED_VAR(args); + __Pyx_BEGIN_CRITICAL_SECTION(m); + Py_INCREF(m->func_qualname); + result = m->func_qualname; + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static PyMethodDef __pyx_CyFunction_methods[] = { + {"__reduce__", (PyCFunction)__Pyx_CyFunction_reduce, METH_VARARGS, 0}, + {0, 0, 0, 0} +}; +#if CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_CyFunction_weakreflist(cyfunc) ((cyfunc)->func_weakreflist) +#else +#define __Pyx_CyFunction_weakreflist(cyfunc) (((PyCFunctionObject*)cyfunc)->m_weakreflist) +#endif +static PyObject *__Pyx_CyFunction_Init(__pyx_CyFunctionObject *op, PyMethodDef *ml, int flags, PyObject* qualname, + PyObject *closure, PyObject *module, PyObject* globals, PyObject* code) { +#if !CYTHON_COMPILING_IN_LIMITED_API + PyCFunctionObject *cf = (PyCFunctionObject*) op; +#endif + if (unlikely(op == NULL)) + return NULL; +#if CYTHON_COMPILING_IN_LIMITED_API + op->func = PyCFunction_NewEx(ml, (PyObject*)op, module); + if (unlikely(!op->func)) return NULL; +#endif + op->flags = flags; + __Pyx_CyFunction_weakreflist(op) = NULL; +#if !CYTHON_COMPILING_IN_LIMITED_API + cf->m_ml = ml; + cf->m_self = (PyObject *) op; +#endif + Py_XINCREF(closure); + op->func_closure = closure; +#if !CYTHON_COMPILING_IN_LIMITED_API + Py_XINCREF(module); + cf->m_module = module; +#endif +#if PY_VERSION_HEX < 0x030C0000 || CYTHON_COMPILING_IN_LIMITED_API + op->func_dict = NULL; +#endif + op->func_name = NULL; + Py_INCREF(qualname); + op->func_qualname = qualname; + op->func_doc = NULL; +#if PY_VERSION_HEX < 0x030900B1 || CYTHON_COMPILING_IN_LIMITED_API + op->func_classobj = NULL; +#else + ((PyCMethodObject*)op)->mm_class = NULL; +#endif + op->func_globals = globals; + Py_INCREF(op->func_globals); + Py_XINCREF(code); + op->func_code = code; + op->defaults = NULL; + op->defaults_tuple = NULL; + op->defaults_kwdict = NULL; + op->defaults_getter = NULL; + op->func_annotations = NULL; + op->func_is_coroutine = NULL; +#if CYTHON_METH_FASTCALL + switch (ml->ml_flags & (METH_VARARGS | METH_FASTCALL | METH_NOARGS | METH_O | METH_KEYWORDS | METH_METHOD)) { + case METH_NOARGS: + __Pyx_CyFunction_func_vectorcall(op) = __Pyx_CyFunction_Vectorcall_NOARGS; + break; + case METH_O: + __Pyx_CyFunction_func_vectorcall(op) = __Pyx_CyFunction_Vectorcall_O; + break; + case METH_METHOD | METH_FASTCALL | METH_KEYWORDS: + __Pyx_CyFunction_func_vectorcall(op) = __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS_METHOD; + break; + case METH_FASTCALL | METH_KEYWORDS: + __Pyx_CyFunction_func_vectorcall(op) = __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS; + break; + case METH_VARARGS | METH_KEYWORDS: + __Pyx_CyFunction_func_vectorcall(op) = NULL; + break; + default: + PyErr_SetString(PyExc_SystemError, "Bad call flags for CyFunction"); + Py_DECREF(op); + return NULL; + } +#endif + return (PyObject *) op; +} +static int +__Pyx_CyFunction_clear(__pyx_CyFunctionObject *m) +{ + Py_CLEAR(m->func_closure); +#if CYTHON_COMPILING_IN_LIMITED_API + Py_CLEAR(m->func); +#else + Py_CLEAR(((PyCFunctionObject*)m)->m_module); +#endif +#if PY_VERSION_HEX < 0x030C0000 || CYTHON_COMPILING_IN_LIMITED_API + Py_CLEAR(m->func_dict); +#elif PY_VERSION_HEX < 0x030d0000 + _PyObject_ClearManagedDict((PyObject*)m); +#else + PyObject_ClearManagedDict((PyObject*)m); +#endif + Py_CLEAR(m->func_name); + Py_CLEAR(m->func_qualname); + Py_CLEAR(m->func_doc); + Py_CLEAR(m->func_globals); + Py_CLEAR(m->func_code); +#if !CYTHON_COMPILING_IN_LIMITED_API +#if PY_VERSION_HEX < 0x030900B1 + Py_CLEAR(__Pyx_CyFunction_GetClassObj(m)); +#else + { + PyObject *cls = (PyObject*) ((PyCMethodObject *) (m))->mm_class; + ((PyCMethodObject *) (m))->mm_class = NULL; + Py_XDECREF(cls); + } +#endif +#endif + Py_CLEAR(m->defaults_tuple); + Py_CLEAR(m->defaults_kwdict); + Py_CLEAR(m->func_annotations); + Py_CLEAR(m->func_is_coroutine); + Py_CLEAR(m->defaults); + return 0; +} +static void __Pyx__CyFunction_dealloc(__pyx_CyFunctionObject *m) +{ + if (__Pyx_CyFunction_weakreflist(m) != NULL) + PyObject_ClearWeakRefs((PyObject *) m); + __Pyx_CyFunction_clear(m); + __Pyx_PyHeapTypeObject_GC_Del(m); +} +static void __Pyx_CyFunction_dealloc(__pyx_CyFunctionObject *m) +{ + PyObject_GC_UnTrack(m); + __Pyx__CyFunction_dealloc(m); +} +static int __Pyx_CyFunction_traverse(__pyx_CyFunctionObject *m, visitproc visit, void *arg) +{ + { + int e = __Pyx_call_type_traverse((PyObject*)m, 1, visit, arg); + if (e) return e; + } + Py_VISIT(m->func_closure); +#if CYTHON_COMPILING_IN_LIMITED_API + Py_VISIT(m->func); +#else + Py_VISIT(((PyCFunctionObject*)m)->m_module); +#endif +#if PY_VERSION_HEX < 0x030C0000 || CYTHON_COMPILING_IN_LIMITED_API + Py_VISIT(m->func_dict); +#else + { + int e = +#if PY_VERSION_HEX < 0x030d0000 + _PyObject_VisitManagedDict +#else + PyObject_VisitManagedDict +#endif + ((PyObject*)m, visit, arg); + if (e != 0) return e; + } +#endif + __Pyx_VISIT_CONST(m->func_name); + __Pyx_VISIT_CONST(m->func_qualname); + Py_VISIT(m->func_doc); + Py_VISIT(m->func_globals); + __Pyx_VISIT_CONST(m->func_code); +#if !CYTHON_COMPILING_IN_LIMITED_API + Py_VISIT(__Pyx_CyFunction_GetClassObj(m)); +#endif + Py_VISIT(m->defaults_tuple); + Py_VISIT(m->defaults_kwdict); + Py_VISIT(m->func_is_coroutine); + Py_VISIT(m->defaults); + return 0; +} +static PyObject* +__Pyx_CyFunction_repr(__pyx_CyFunctionObject *op) +{ + PyObject *repr; + __Pyx_BEGIN_CRITICAL_SECTION(op); + repr = PyUnicode_FromFormat("", + op->func_qualname, (void *)op); + __Pyx_END_CRITICAL_SECTION(); + return repr; +} +static PyObject * __Pyx_CyFunction_CallMethod(PyObject *func, PyObject *self, PyObject *arg, PyObject *kw) { +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *f = ((__pyx_CyFunctionObject*)func)->func; + PyCFunction meth; + int flags; + meth = PyCFunction_GetFunction(f); + if (unlikely(!meth)) return NULL; + flags = PyCFunction_GetFlags(f); + if (unlikely(flags < 0)) return NULL; +#else + PyCFunctionObject* f = (PyCFunctionObject*)func; + PyCFunction meth = f->m_ml->ml_meth; + int flags = f->m_ml->ml_flags; +#endif + Py_ssize_t size; + switch (flags & (METH_VARARGS | METH_KEYWORDS | METH_NOARGS | METH_O)) { + case METH_VARARGS: + if (likely(kw == NULL || PyDict_Size(kw) == 0)) + return (*meth)(self, arg); + break; + case METH_VARARGS | METH_KEYWORDS: + return (*(PyCFunctionWithKeywords)(void(*)(void))meth)(self, arg, kw); + case METH_NOARGS: + if (likely(kw == NULL || PyDict_Size(kw) == 0)) { +#if CYTHON_ASSUME_SAFE_SIZE + size = PyTuple_GET_SIZE(arg); +#else + size = PyTuple_Size(arg); + if (unlikely(size < 0)) return NULL; +#endif + if (likely(size == 0)) + return (*meth)(self, NULL); + __Pyx_CyFunction_raise_argument_count_error( + (__pyx_CyFunctionObject*)func, + "takes no arguments", size); + return NULL; + } + break; + case METH_O: + if (likely(kw == NULL || PyDict_Size(kw) == 0)) { +#if CYTHON_ASSUME_SAFE_SIZE + size = PyTuple_GET_SIZE(arg); +#else + size = PyTuple_Size(arg); + if (unlikely(size < 0)) return NULL; +#endif + if (likely(size == 1)) { + PyObject *result, *arg0; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + arg0 = PyTuple_GET_ITEM(arg, 0); + #else + arg0 = __Pyx_PySequence_ITEM(arg, 0); if (unlikely(!arg0)) return NULL; + #endif + result = (*meth)(self, arg0); + #if !(CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS) + Py_DECREF(arg0); + #endif + return result; + } + __Pyx_CyFunction_raise_argument_count_error( + (__pyx_CyFunctionObject*)func, + "takes exactly one argument", size); + return NULL; + } + break; + default: + PyErr_SetString(PyExc_SystemError, "Bad call flags for CyFunction"); + return NULL; + } + __Pyx_CyFunction_raise_type_error( + (__pyx_CyFunctionObject*)func, "takes no keyword arguments"); + return NULL; +} +static CYTHON_INLINE PyObject *__Pyx_CyFunction_Call(PyObject *func, PyObject *arg, PyObject *kw) { + PyObject *self, *result; +#if CYTHON_COMPILING_IN_LIMITED_API + self = PyCFunction_GetSelf(((__pyx_CyFunctionObject*)func)->func); + if (unlikely(!self) && PyErr_Occurred()) return NULL; +#else + self = ((PyCFunctionObject*)func)->m_self; +#endif + result = __Pyx_CyFunction_CallMethod(func, self, arg, kw); + return result; +} +static PyObject *__Pyx_CyFunction_CallAsMethod(PyObject *func, PyObject *args, PyObject *kw) { + PyObject *result; + __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *) func; +#if CYTHON_METH_FASTCALL && CYTHON_VECTORCALL + __pyx_vectorcallfunc vc = __Pyx_CyFunction_func_vectorcall(cyfunc); + if (vc) { +#if CYTHON_ASSUME_SAFE_MACROS && CYTHON_ASSUME_SAFE_SIZE + return __Pyx_PyVectorcall_FastCallDict(func, vc, &PyTuple_GET_ITEM(args, 0), (size_t)PyTuple_GET_SIZE(args), kw); +#else + (void) &__Pyx_PyVectorcall_FastCallDict; + return PyVectorcall_Call(func, args, kw); +#endif + } +#endif + if ((cyfunc->flags & __Pyx_CYFUNCTION_CCLASS) && !(cyfunc->flags & __Pyx_CYFUNCTION_STATICMETHOD)) { + Py_ssize_t argc; + PyObject *new_args; + PyObject *self; +#if CYTHON_ASSUME_SAFE_SIZE + argc = PyTuple_GET_SIZE(args); +#else + argc = PyTuple_Size(args); + if (unlikely(argc < 0)) return NULL; +#endif + new_args = PyTuple_GetSlice(args, 1, argc); + if (unlikely(!new_args)) + return NULL; + self = PyTuple_GetItem(args, 0); + if (unlikely(!self)) { + Py_DECREF(new_args); + PyErr_Format(PyExc_TypeError, + "unbound method %.200S() needs an argument", + cyfunc->func_qualname); + return NULL; + } + result = __Pyx_CyFunction_CallMethod(func, self, new_args, kw); + Py_DECREF(new_args); + } else { + result = __Pyx_CyFunction_Call(func, args, kw); + } + return result; +} +#if CYTHON_METH_FASTCALL && CYTHON_VECTORCALL +static CYTHON_INLINE int __Pyx_CyFunction_Vectorcall_CheckArgs(__pyx_CyFunctionObject *cyfunc, Py_ssize_t nargs, PyObject *kwnames) +{ + int ret = 0; + if ((cyfunc->flags & __Pyx_CYFUNCTION_CCLASS) && !(cyfunc->flags & __Pyx_CYFUNCTION_STATICMETHOD)) { + if (unlikely(nargs < 1)) { + __Pyx_CyFunction_raise_type_error( + cyfunc, "needs an argument"); + return -1; + } + ret = 1; + } + if (unlikely(kwnames) && unlikely(__Pyx_PyTuple_GET_SIZE(kwnames))) { + __Pyx_CyFunction_raise_type_error( + cyfunc, "takes no keyword arguments"); + return -1; + } + return ret; +} +static PyObject * __Pyx_CyFunction_Vectorcall_NOARGS(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames) +{ + __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *)func; + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); + PyObject *self; +#if CYTHON_COMPILING_IN_LIMITED_API + PyCFunction meth = PyCFunction_GetFunction(cyfunc->func); + if (unlikely(!meth)) return NULL; +#else + PyCFunction meth = ((PyCFunctionObject*)cyfunc)->m_ml->ml_meth; +#endif + switch (__Pyx_CyFunction_Vectorcall_CheckArgs(cyfunc, nargs, kwnames)) { + case 1: + self = args[0]; + args += 1; + nargs -= 1; + break; + case 0: +#if CYTHON_COMPILING_IN_LIMITED_API + self = PyCFunction_GetSelf(((__pyx_CyFunctionObject*)cyfunc)->func); + if (unlikely(!self) && PyErr_Occurred()) return NULL; +#else + self = ((PyCFunctionObject*)cyfunc)->m_self; +#endif + break; + default: + return NULL; + } + if (unlikely(nargs != 0)) { + __Pyx_CyFunction_raise_argument_count_error( + cyfunc, "takes no arguments", nargs); + return NULL; + } + return meth(self, NULL); +} +static PyObject * __Pyx_CyFunction_Vectorcall_O(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames) +{ + __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *)func; + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); + PyObject *self; +#if CYTHON_COMPILING_IN_LIMITED_API + PyCFunction meth = PyCFunction_GetFunction(cyfunc->func); + if (unlikely(!meth)) return NULL; +#else + PyCFunction meth = ((PyCFunctionObject*)cyfunc)->m_ml->ml_meth; +#endif + switch (__Pyx_CyFunction_Vectorcall_CheckArgs(cyfunc, nargs, kwnames)) { + case 1: + self = args[0]; + args += 1; + nargs -= 1; + break; + case 0: +#if CYTHON_COMPILING_IN_LIMITED_API + self = PyCFunction_GetSelf(((__pyx_CyFunctionObject*)cyfunc)->func); + if (unlikely(!self) && PyErr_Occurred()) return NULL; +#else + self = ((PyCFunctionObject*)cyfunc)->m_self; +#endif + break; + default: + return NULL; + } + if (unlikely(nargs != 1)) { + __Pyx_CyFunction_raise_argument_count_error( + cyfunc, "takes exactly one argument", nargs); + return NULL; + } + return meth(self, args[0]); +} +static PyObject * __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames) +{ + __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *)func; + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); + PyObject *self; +#if CYTHON_COMPILING_IN_LIMITED_API + PyCFunction meth = PyCFunction_GetFunction(cyfunc->func); + if (unlikely(!meth)) return NULL; +#else + PyCFunction meth = ((PyCFunctionObject*)cyfunc)->m_ml->ml_meth; +#endif + switch (__Pyx_CyFunction_Vectorcall_CheckArgs(cyfunc, nargs, NULL)) { + case 1: + self = args[0]; + args += 1; + nargs -= 1; + break; + case 0: +#if CYTHON_COMPILING_IN_LIMITED_API + self = PyCFunction_GetSelf(((__pyx_CyFunctionObject*)cyfunc)->func); + if (unlikely(!self) && PyErr_Occurred()) return NULL; +#else + self = ((PyCFunctionObject*)cyfunc)->m_self; +#endif + break; + default: + return NULL; + } + return ((__Pyx_PyCFunctionFastWithKeywords)(void(*)(void))meth)(self, args, nargs, kwnames); +} +static PyObject * __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS_METHOD(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames) +{ + __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *)func; + PyTypeObject *cls = (PyTypeObject *) __Pyx_CyFunction_GetClassObj(cyfunc); + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); + PyObject *self; +#if CYTHON_COMPILING_IN_LIMITED_API + PyCFunction meth = PyCFunction_GetFunction(cyfunc->func); + if (unlikely(!meth)) return NULL; +#else + PyCFunction meth = ((PyCFunctionObject*)cyfunc)->m_ml->ml_meth; +#endif + switch (__Pyx_CyFunction_Vectorcall_CheckArgs(cyfunc, nargs, NULL)) { + case 1: + self = args[0]; + args += 1; + nargs -= 1; + break; + case 0: +#if CYTHON_COMPILING_IN_LIMITED_API + self = PyCFunction_GetSelf(((__pyx_CyFunctionObject*)cyfunc)->func); + if (unlikely(!self) && PyErr_Occurred()) return NULL; +#else + self = ((PyCFunctionObject*)cyfunc)->m_self; +#endif + break; + default: + return NULL; + } + #if PY_VERSION_HEX < 0x030e00A6 + size_t nargs_value = (size_t) nargs; + #else + Py_ssize_t nargs_value = nargs; + #endif + return ((__Pyx_PyCMethod)(void(*)(void))meth)(self, cls, args, nargs_value, kwnames); +} +#endif +static PyType_Slot __pyx_CyFunctionType_slots[] = { + {Py_tp_dealloc, (void *)__Pyx_CyFunction_dealloc}, + {Py_tp_repr, (void *)__Pyx_CyFunction_repr}, + {Py_tp_call, (void *)__Pyx_CyFunction_CallAsMethod}, + {Py_tp_traverse, (void *)__Pyx_CyFunction_traverse}, + {Py_tp_clear, (void *)__Pyx_CyFunction_clear}, + {Py_tp_methods, (void *)__pyx_CyFunction_methods}, + {Py_tp_members, (void *)__pyx_CyFunction_members}, + {Py_tp_getset, (void *)__pyx_CyFunction_getsets}, + {Py_tp_descr_get, (void *)__Pyx_PyMethod_New}, + {0, 0}, +}; +static PyType_Spec __pyx_CyFunctionType_spec = { + __PYX_TYPE_MODULE_PREFIX "cython_function_or_method", + sizeof(__pyx_CyFunctionObject), + 0, +#ifdef Py_TPFLAGS_METHOD_DESCRIPTOR + Py_TPFLAGS_METHOD_DESCRIPTOR | +#endif +#if CYTHON_METH_FASTCALL +#if defined(Py_TPFLAGS_HAVE_VECTORCALL) + Py_TPFLAGS_HAVE_VECTORCALL | +#elif defined(_Py_TPFLAGS_HAVE_VECTORCALL) + _Py_TPFLAGS_HAVE_VECTORCALL | +#endif +#endif // CYTHON_METH_FASTCALL +#if PY_VERSION_HEX >= 0x030C0000 && !CYTHON_COMPILING_IN_LIMITED_API + Py_TPFLAGS_MANAGED_DICT | +#endif + Py_TPFLAGS_IMMUTABLETYPE | Py_TPFLAGS_DISALLOW_INSTANTIATION | + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, + __pyx_CyFunctionType_slots +}; +static int __pyx_CyFunction_init(PyObject *module) { + __pyx_mstatetype *mstate = __Pyx_PyModule_GetState(module); + mstate->__pyx_CyFunctionType = __Pyx_FetchCommonTypeFromSpec( + mstate->__pyx_CommonTypesMetaclassType, module, &__pyx_CyFunctionType_spec, NULL); + if (unlikely(mstate->__pyx_CyFunctionType == NULL)) { + return -1; + } + return 0; +} +static CYTHON_INLINE PyObject *__Pyx_CyFunction_InitDefaults(PyObject *func, PyTypeObject *defaults_type) { + __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; + m->defaults = PyObject_CallObject((PyObject*)defaults_type, NULL); // _PyObject_New(defaults_type); + if (unlikely(!m->defaults)) + return NULL; + return m->defaults; +} +static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsTuple(PyObject *func, PyObject *tuple) { + __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; + m->defaults_tuple = tuple; + Py_INCREF(tuple); +} +static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsKwDict(PyObject *func, PyObject *dict) { + __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; + m->defaults_kwdict = dict; + Py_INCREF(dict); +} +static CYTHON_INLINE void __Pyx_CyFunction_SetAnnotationsDict(PyObject *func, PyObject *dict) { + __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; + m->func_annotations = dict; + Py_INCREF(dict); +} + +/* CythonFunction */ +static PyObject *__Pyx_CyFunction_New(PyMethodDef *ml, int flags, PyObject* qualname, + PyObject *closure, PyObject *module, PyObject* globals, PyObject* code) { + PyObject *op = __Pyx_CyFunction_Init( + PyObject_GC_New(__pyx_CyFunctionObject, __pyx_mstate_global->__pyx_CyFunctionType), + ml, flags, qualname, closure, module, globals, code + ); + if (likely(op)) { + PyObject_GC_Track(op); + } + return op; +} + +/* CLineInTraceback (used by AddTraceback) */ +#if CYTHON_CLINE_IN_TRACEBACK && CYTHON_CLINE_IN_TRACEBACK_RUNTIME +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000 +#define __Pyx_PyProbablyModule_GetDict(o) __Pyx_XNewRef(PyModule_GetDict(o)) +#elif !CYTHON_COMPILING_IN_CPYTHON || CYTHON_COMPILING_IN_CPYTHON_FREETHREADING +#define __Pyx_PyProbablyModule_GetDict(o) PyObject_GenericGetDict(o, NULL); +#else +PyObject* __Pyx_PyProbablyModule_GetDict(PyObject *o) { + PyObject **dict_ptr = _PyObject_GetDictPtr(o); + return dict_ptr ? __Pyx_XNewRef(*dict_ptr) : NULL; +} +#endif +static int __Pyx_CLineForTraceback(PyThreadState *tstate, int c_line) { + PyObject *use_cline = NULL; + PyObject *ptype, *pvalue, *ptraceback; + PyObject *cython_runtime_dict; + CYTHON_MAYBE_UNUSED_VAR(tstate); + if (unlikely(!__pyx_mstate_global->__pyx_cython_runtime)) { + return c_line; + } + __Pyx_ErrFetchInState(tstate, &ptype, &pvalue, &ptraceback); + cython_runtime_dict = __Pyx_PyProbablyModule_GetDict(__pyx_mstate_global->__pyx_cython_runtime); + if (likely(cython_runtime_dict)) { + __PYX_PY_DICT_LOOKUP_IF_MODIFIED( + use_cline, cython_runtime_dict, + __Pyx_PyDict_SetDefault(cython_runtime_dict, __pyx_mstate_global->__pyx_n_u_cline_in_traceback, Py_False)) + } + if (use_cline == NULL || use_cline == Py_False || (use_cline != Py_True && PyObject_Not(use_cline) != 0)) { + c_line = 0; + } + Py_XDECREF(use_cline); + Py_XDECREF(cython_runtime_dict); + __Pyx_ErrRestoreInState(tstate, ptype, pvalue, ptraceback); + return c_line; +} +#endif + +/* CodeObjectCache (used by AddTraceback) */ +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { + int start = 0, mid = 0, end = count - 1; + if (end >= 0 && code_line > entries[end].code_line) { + return count; + } + while (start < end) { + mid = start + (end - start) / 2; + if (code_line < entries[mid].code_line) { + end = mid; + } else if (code_line > entries[mid].code_line) { + start = mid + 1; + } else { + return mid; + } + } + if (code_line <= entries[mid].code_line) { + return mid; + } else { + return mid + 1; + } +} +static __Pyx_CachedCodeObjectType *__pyx__find_code_object(struct __Pyx_CodeObjectCache *code_cache, int code_line) { + __Pyx_CachedCodeObjectType* code_object; + int pos; + if (unlikely(!code_line) || unlikely(!code_cache->entries)) { + return NULL; + } + pos = __pyx_bisect_code_objects(code_cache->entries, code_cache->count, code_line); + if (unlikely(pos >= code_cache->count) || unlikely(code_cache->entries[pos].code_line != code_line)) { + return NULL; + } + code_object = code_cache->entries[pos].code_object; + Py_INCREF(code_object); + return code_object; +} +static __Pyx_CachedCodeObjectType *__pyx_find_code_object(int code_line) { +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING && !CYTHON_ATOMICS + (void)__pyx__find_code_object; + return NULL; // Most implementation should have atomics. But otherwise, don't make it thread-safe, just miss. +#else + struct __Pyx_CodeObjectCache *code_cache = &__pyx_mstate_global->__pyx_code_cache; +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + __pyx_nonatomic_int_type old_count = __pyx_atomic_incr_acq_rel(&code_cache->accessor_count); + if (old_count < 0) { + __pyx_atomic_decr_acq_rel(&code_cache->accessor_count); + return NULL; + } +#endif + __Pyx_CachedCodeObjectType *result = __pyx__find_code_object(code_cache, code_line); +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + __pyx_atomic_decr_acq_rel(&code_cache->accessor_count); +#endif + return result; +#endif +} +static void __pyx__insert_code_object(struct __Pyx_CodeObjectCache *code_cache, int code_line, __Pyx_CachedCodeObjectType* code_object) +{ + int pos, i; + __Pyx_CodeObjectCacheEntry* entries = code_cache->entries; + if (unlikely(!code_line)) { + return; + } + if (unlikely(!entries)) { + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); + if (likely(entries)) { + code_cache->entries = entries; + code_cache->max_count = 64; + code_cache->count = 1; + entries[0].code_line = code_line; + entries[0].code_object = code_object; + Py_INCREF(code_object); + } + return; + } + pos = __pyx_bisect_code_objects(code_cache->entries, code_cache->count, code_line); + if ((pos < code_cache->count) && unlikely(code_cache->entries[pos].code_line == code_line)) { + __Pyx_CachedCodeObjectType* tmp = entries[pos].code_object; + entries[pos].code_object = code_object; + Py_INCREF(code_object); + Py_DECREF(tmp); + return; + } + if (code_cache->count == code_cache->max_count) { + int new_max = code_cache->max_count + 64; + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( + code_cache->entries, ((size_t)new_max) * sizeof(__Pyx_CodeObjectCacheEntry)); + if (unlikely(!entries)) { + return; + } + code_cache->entries = entries; + code_cache->max_count = new_max; + } + for (i=code_cache->count; i>pos; i--) { + entries[i] = entries[i-1]; + } + entries[pos].code_line = code_line; + entries[pos].code_object = code_object; + code_cache->count++; + Py_INCREF(code_object); +} +static void __pyx_insert_code_object(int code_line, __Pyx_CachedCodeObjectType* code_object) { +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING && !CYTHON_ATOMICS + (void)__pyx__insert_code_object; + return; // Most implementation should have atomics. But otherwise, don't make it thread-safe, just fail. +#else + struct __Pyx_CodeObjectCache *code_cache = &__pyx_mstate_global->__pyx_code_cache; +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + __pyx_nonatomic_int_type expected = 0; + if (!__pyx_atomic_int_cmp_exchange(&code_cache->accessor_count, &expected, INT_MIN)) { + return; + } +#endif + __pyx__insert_code_object(code_cache, code_line, code_object); +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + __pyx_atomic_sub(&code_cache->accessor_count, INT_MIN); +#endif +#endif +} + +/* AddTraceback */ +#include "compile.h" +#include "frameobject.h" +#include "traceback.h" +#if PY_VERSION_HEX >= 0x030b00a6 && !CYTHON_COMPILING_IN_LIMITED_API && !defined(PYPY_VERSION) + #ifndef Py_BUILD_CORE + #define Py_BUILD_CORE 1 + #endif + #include "internal/pycore_frame.h" +#endif +#if CYTHON_COMPILING_IN_LIMITED_API +static PyObject *__Pyx_PyCode_Replace_For_AddTraceback(PyObject *code, PyObject *scratch_dict, + PyObject *firstlineno, PyObject *name) { + PyObject *replace = NULL; + if (unlikely(PyDict_SetItemString(scratch_dict, "co_firstlineno", firstlineno))) return NULL; + if (unlikely(PyDict_SetItemString(scratch_dict, "co_name", name))) return NULL; + replace = PyObject_GetAttrString(code, "replace"); + if (likely(replace)) { + PyObject *result = PyObject_Call(replace, __pyx_mstate_global->__pyx_empty_tuple, scratch_dict); + Py_DECREF(replace); + return result; + } + PyErr_Clear(); + return NULL; +} +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename) { + PyObject *code_object = NULL, *py_py_line = NULL, *py_funcname = NULL, *dict = NULL; + PyObject *replace = NULL, *getframe = NULL, *frame = NULL; + PyObject *exc_type, *exc_value, *exc_traceback; + int success = 0; + if (c_line) { + c_line = __Pyx_CLineForTraceback(__Pyx_PyThreadState_Current, c_line); + } + PyErr_Fetch(&exc_type, &exc_value, &exc_traceback); + code_object = __pyx_find_code_object(c_line ? -c_line : py_line); + if (!code_object) { + code_object = Py_CompileString("_getframe()", filename, Py_eval_input); + if (unlikely(!code_object)) goto bad; + py_py_line = PyLong_FromLong(py_line); + if (unlikely(!py_py_line)) goto bad; + if (c_line) { + py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + } else { + py_funcname = PyUnicode_FromString(funcname); + } + if (unlikely(!py_funcname)) goto bad; + dict = PyDict_New(); + if (unlikely(!dict)) goto bad; + { + PyObject *old_code_object = code_object; + code_object = __Pyx_PyCode_Replace_For_AddTraceback(code_object, dict, py_py_line, py_funcname); + Py_DECREF(old_code_object); + } + if (unlikely(!code_object)) goto bad; + __pyx_insert_code_object(c_line ? -c_line : py_line, code_object); + } else { + dict = PyDict_New(); + } + getframe = PySys_GetObject("_getframe"); + if (unlikely(!getframe)) goto bad; + if (unlikely(PyDict_SetItemString(dict, "_getframe", getframe))) goto bad; + frame = PyEval_EvalCode(code_object, dict, dict); + if (unlikely(!frame) || frame == Py_None) goto bad; + success = 1; + bad: + PyErr_Restore(exc_type, exc_value, exc_traceback); + Py_XDECREF(code_object); + Py_XDECREF(py_py_line); + Py_XDECREF(py_funcname); + Py_XDECREF(dict); + Py_XDECREF(replace); + if (success) { + PyTraceBack_Here( + (struct _frame*)frame); + } + Py_XDECREF(frame); +} +#else +static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( + const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = NULL; + PyObject *py_funcname = NULL; + if (c_line) { + py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + if (!py_funcname) goto bad; + funcname = PyUnicode_AsUTF8(py_funcname); + if (!funcname) goto bad; + } + py_code = PyCode_NewEmpty(filename, funcname, py_line); + Py_XDECREF(py_funcname); + return py_code; +bad: + Py_XDECREF(py_funcname); + return NULL; +} +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyFrameObject *py_frame = 0; + PyThreadState *tstate = __Pyx_PyThreadState_Current; + PyObject *ptype, *pvalue, *ptraceback; + if (c_line) { + c_line = __Pyx_CLineForTraceback(tstate, c_line); + } + py_code = __pyx_find_code_object(c_line ? -c_line : py_line); + if (!py_code) { + __Pyx_ErrFetchInState(tstate, &ptype, &pvalue, &ptraceback); + py_code = __Pyx_CreateCodeObjectForTraceback( + funcname, c_line, py_line, filename); + if (!py_code) { + /* If the code object creation fails, then we should clear the + fetched exception references and propagate the new exception */ + Py_XDECREF(ptype); + Py_XDECREF(pvalue); + Py_XDECREF(ptraceback); + goto bad; + } + __Pyx_ErrRestoreInState(tstate, ptype, pvalue, ptraceback); + __pyx_insert_code_object(c_line ? -c_line : py_line, py_code); + } + py_frame = PyFrame_New( + tstate, /*PyThreadState *tstate,*/ + py_code, /*PyCodeObject *code,*/ + __pyx_mstate_global->__pyx_d, /*PyObject *globals,*/ + 0 /*PyObject *locals*/ + ); + if (!py_frame) goto bad; + __Pyx_PyFrame_SetLineNumber(py_frame, py_line); + PyTraceBack_Here(py_frame); +bad: + Py_XDECREF(py_code); + Py_XDECREF(py_frame); +} +#endif + +/* CheckUnpickleChecksum */ +static void __Pyx_RaiseUnpickleChecksumError(long checksum, long checksum1, long checksum2, long checksum3, const char *members) { + PyObject *pickle_module = PyImport_ImportModule("pickle"); + if (unlikely(!pickle_module)) return; + PyObject *pickle_error = PyObject_GetAttrString(pickle_module, "PickleError"); + Py_DECREF(pickle_module); + if (unlikely(!pickle_error)) return; + if (checksum2 == checksum1) { + PyErr_Format(pickle_error, "Incompatible checksums (0x%x vs (0x%x) = (%s))", + checksum, checksum1, members); + } else if (checksum3 == checksum2) { + PyErr_Format(pickle_error, "Incompatible checksums (0x%x vs (0x%x, 0x%x) = (%s))", + checksum, checksum1, checksum2, members); + } else { + PyErr_Format(pickle_error, "Incompatible checksums (0x%x vs (0x%x, 0x%x, 0x%x) = (%s))", + checksum, checksum1, checksum2, checksum3, members); + } + Py_DECREF(pickle_error); +} +static int __Pyx_CheckUnpickleChecksum(long checksum, long checksum1, long checksum2, long checksum3, const char *members) { + int found = 0; + found |= checksum1 == checksum; + found |= checksum2 == checksum; + found |= checksum3 == checksum; + if (likely(found)) + return 0; + __Pyx_RaiseUnpickleChecksumError(checksum, checksum1, checksum2, checksum3, members); + return -1; +} + +/* CIntFromPyVerify */ +#define __PYX_VERIFY_RETURN_INT(target_type, func_type, func_value)\ + __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 0) +#define __PYX_VERIFY_RETURN_INT_EXC(target_type, func_type, func_value)\ + __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 1) +#define __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, exc)\ + {\ + func_type value = func_value;\ + if (sizeof(target_type) < sizeof(func_type)) {\ + if (unlikely(value != (func_type) (target_type) value)) {\ + func_type zero = 0;\ + if (exc && unlikely(value == (func_type)-1 && PyErr_Occurred()))\ + return (target_type) -1;\ + if (is_unsigned && unlikely(value < zero))\ + goto raise_neg_overflow;\ + else\ + goto raise_overflow;\ + }\ + }\ + return (target_type) value;\ + } + +/* PyObjectVectorCallKwBuilder (used by CIntToPy) */ +#if CYTHON_VECTORCALL +static int __Pyx_VectorcallBuilder_AddArg(PyObject *key, PyObject *value, PyObject *builder, PyObject **args, int n) { + (void)__Pyx_PyObject_FastCallDict; + if (__Pyx_PyTuple_SET_ITEM(builder, n, key) != (0)) return -1; + Py_INCREF(key); + args[n] = value; + return 0; +} +CYTHON_UNUSED static int __Pyx_VectorcallBuilder_AddArg_Check(PyObject *key, PyObject *value, PyObject *builder, PyObject **args, int n) { + (void)__Pyx_VectorcallBuilder_AddArgStr; + if (unlikely(!PyUnicode_Check(key))) { + PyErr_SetString(PyExc_TypeError, "keywords must be strings"); + return -1; + } + return __Pyx_VectorcallBuilder_AddArg(key, value, builder, args, n); +} +static int __Pyx_VectorcallBuilder_AddArgStr(const char *key, PyObject *value, PyObject *builder, PyObject **args, int n) { + PyObject *pyKey = PyUnicode_FromString(key); + if (!pyKey) return -1; + return __Pyx_VectorcallBuilder_AddArg(pyKey, value, builder, args, n); +} +#else // CYTHON_VECTORCALL +CYTHON_UNUSED static int __Pyx_VectorcallBuilder_AddArg_Check(PyObject *key, PyObject *value, PyObject *builder, CYTHON_UNUSED PyObject **args, CYTHON_UNUSED int n) { + if (unlikely(!PyUnicode_Check(key))) { + PyErr_SetString(PyExc_TypeError, "keywords must be strings"); + return -1; + } + return PyDict_SetItem(builder, key, value); +} +#endif + +/* CIntToPy */ +static CYTHON_INLINE PyObject* __Pyx_PyLong_From___pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType(__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType value) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const __pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType neg_one = (__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType) -1, const_zero = (__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType) < sizeof(long)) { + return PyLong_FromLong((long) value); + } else if (sizeof(__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); +#if !CYTHON_COMPILING_IN_PYPY + } else if (sizeof(__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType) <= sizeof(unsigned PY_LONG_LONG)) { + return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); +#endif + } + } else { + if (sizeof(__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType) <= sizeof(long)) { + return PyLong_FromLong((long) value); + } else if (sizeof(__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType) <= sizeof(PY_LONG_LONG)) { + return PyLong_FromLongLong((PY_LONG_LONG) value); + } + } + { + unsigned char *bytes = (unsigned char *)&value; +#if !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d00A4 + if (is_unsigned) { + return PyLong_FromUnsignedNativeBytes(bytes, sizeof(value), -1); + } else { + return PyLong_FromNativeBytes(bytes, sizeof(value), -1); + } +#elif !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030d0000 + int one = 1; int little = (int)*(unsigned char *)&one; + return _PyLong_FromByteArray(bytes, sizeof(__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType), + little, !is_unsigned); +#else + int one = 1; int little = (int)*(unsigned char *)&one; + PyObject *from_bytes, *result = NULL, *kwds = NULL; + PyObject *py_bytes = NULL, *order_str = NULL; + from_bytes = PyObject_GetAttrString((PyObject*)&PyLong_Type, "from_bytes"); + if (!from_bytes) return NULL; + py_bytes = PyBytes_FromStringAndSize((char*)bytes, sizeof(__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)); + if (!py_bytes) goto limited_bad; + order_str = PyUnicode_FromString(little ? "little" : "big"); + if (!order_str) goto limited_bad; + { + PyObject *args[3+(CYTHON_VECTORCALL ? 1 : 0)] = { NULL, py_bytes, order_str }; + if (!is_unsigned) { + kwds = __Pyx_MakeVectorcallBuilderKwds(1); + if (!kwds) goto limited_bad; + if (__Pyx_VectorcallBuilder_AddArgStr("signed", __Pyx_NewRef(Py_True), kwds, args+3, 0) < 0) goto limited_bad; + } + result = __Pyx_Object_Vectorcall_CallFromBuilder(from_bytes, args+1, 2 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET, kwds); + } + limited_bad: + Py_XDECREF(kwds); + Py_XDECREF(order_str); + Py_XDECREF(py_bytes); + Py_XDECREF(from_bytes); + return result; +#endif + } +} + +/* CIntFromPy */ +static CYTHON_INLINE __pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType __Pyx_PyLong_As___pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType(PyObject *x) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const __pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType neg_one = (__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType) -1, const_zero = (__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (unlikely(!PyLong_Check(x))) { + __pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType val; + PyObject *tmp = __Pyx_PyNumber_Long(x); + if (!tmp) return (__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType) -1; + val = __Pyx_PyLong_As___pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType(tmp); + Py_DECREF(tmp); + return val; + } + if (is_unsigned) { +#if CYTHON_USE_PYLONG_INTERNALS + if (unlikely(__Pyx_PyLong_IsNeg(x))) { + goto raise_neg_overflow; + } else if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType, __Pyx_compact_upylong, __Pyx_PyLong_CompactValueUnsigned(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_DigitCount(x)) { + case 2: + if ((8 * sizeof(__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType) >= 2 * PyLong_SHIFT)) { + return (__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType) (((((__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)digits[1]) << PyLong_SHIFT) | (__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)digits[0])); + } + } + break; + case 3: + if ((8 * sizeof(__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType) >= 3 * PyLong_SHIFT)) { + return (__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType) (((((((__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)digits[2]) << PyLong_SHIFT) | (__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)digits[1]) << PyLong_SHIFT) | (__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)digits[0])); + } + } + break; + case 4: + if ((8 * sizeof(__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType) >= 4 * PyLong_SHIFT)) { + return (__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType) (((((((((__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)digits[3]) << PyLong_SHIFT) | (__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)digits[2]) << PyLong_SHIFT) | (__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)digits[1]) << PyLong_SHIFT) | (__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)digits[0])); + } + } + break; + } + } +#endif +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030C00A7 + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } +#else + { + int result = PyObject_RichCompareBool(x, Py_False, Py_LT); + if (unlikely(result < 0)) + return (__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType) -1; + if (unlikely(result == 1)) + goto raise_neg_overflow; + } +#endif + if ((sizeof(__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType) <= sizeof(unsigned long))) { + __PYX_VERIFY_RETURN_INT_EXC(__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType, unsigned long, PyLong_AsUnsignedLong(x)) + } else if ((sizeof(__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType) <= sizeof(unsigned PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) + } + } else { +#if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType, __Pyx_compact_pylong, __Pyx_PyLong_CompactValue(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_SignedDigitCount(x)) { + case -2: + if ((8 * sizeof(__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType) - 1 > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType) - 1 > 2 * PyLong_SHIFT)) { + return (__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType) (((__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)-1)*(((((__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)digits[1]) << PyLong_SHIFT) | (__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)digits[0]))); + } + } + break; + case 2: + if ((8 * sizeof(__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType) - 1 > 2 * PyLong_SHIFT)) { + return (__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType) ((((((__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)digits[1]) << PyLong_SHIFT) | (__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)digits[0]))); + } + } + break; + case -3: + if ((8 * sizeof(__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType) - 1 > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType) - 1 > 3 * PyLong_SHIFT)) { + return (__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType) (((__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)-1)*(((((((__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)digits[2]) << PyLong_SHIFT) | (__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)digits[1]) << PyLong_SHIFT) | (__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)digits[0]))); + } + } + break; + case 3: + if ((8 * sizeof(__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType) - 1 > 3 * PyLong_SHIFT)) { + return (__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType) ((((((((__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)digits[2]) << PyLong_SHIFT) | (__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)digits[1]) << PyLong_SHIFT) | (__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)digits[0]))); + } + } + break; + case -4: + if ((8 * sizeof(__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType) - 1 > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType) - 1 > 4 * PyLong_SHIFT)) { + return (__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType) (((__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)-1)*(((((((((__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)digits[3]) << PyLong_SHIFT) | (__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)digits[2]) << PyLong_SHIFT) | (__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)digits[1]) << PyLong_SHIFT) | (__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)digits[0]))); + } + } + break; + case 4: + if ((8 * sizeof(__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType) - 1 > 4 * PyLong_SHIFT)) { + return (__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType) ((((((((((__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)digits[3]) << PyLong_SHIFT) | (__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)digits[2]) << PyLong_SHIFT) | (__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)digits[1]) << PyLong_SHIFT) | (__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType)digits[0]))); + } + } + break; + } + } +#endif + if ((sizeof(__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType) <= sizeof(long))) { + __PYX_VERIFY_RETURN_INT_EXC(__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType, long, PyLong_AsLong(x)) + } else if ((sizeof(__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType) <= sizeof(PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType, PY_LONG_LONG, PyLong_AsLongLong(x)) + } + } + { + __pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType val; + int ret = -1; +#if PY_VERSION_HEX >= 0x030d00A6 && !CYTHON_COMPILING_IN_LIMITED_API + Py_ssize_t bytes_copied = PyLong_AsNativeBytes( + x, &val, sizeof(val), Py_ASNATIVEBYTES_NATIVE_ENDIAN | (is_unsigned ? Py_ASNATIVEBYTES_UNSIGNED_BUFFER | Py_ASNATIVEBYTES_REJECT_NEGATIVE : 0)); + if (unlikely(bytes_copied == -1)) { + } else if (unlikely(bytes_copied > (Py_ssize_t) sizeof(val))) { + goto raise_overflow; + } else { + ret = 0; + } +#elif PY_VERSION_HEX < 0x030d0000 && !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API) || defined(_PyLong_AsByteArray) + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + ret = _PyLong_AsByteArray((PyLongObject *)x, + bytes, sizeof(val), + is_little, !is_unsigned); +#else + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() or PyLong_AsNativeBytes() not available, cannot convert large enums"); + val = (__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType) -1; +#endif + if (unlikely(ret)) + return (__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType) -1; + return val; + } +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to __pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType"); + return (__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to __pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType"); + return (__pyx_t_9thriftpy2_8protocol_5cybin_5cybin_TType) -1; +} + +/* CIntFromPy */ +static CYTHON_INLINE int32_t __Pyx_PyLong_As_int32_t(PyObject *x) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const int32_t neg_one = (int32_t) -1, const_zero = (int32_t) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (unlikely(!PyLong_Check(x))) { + int32_t val; + PyObject *tmp = __Pyx_PyNumber_Long(x); + if (!tmp) return (int32_t) -1; + val = __Pyx_PyLong_As_int32_t(tmp); + Py_DECREF(tmp); + return val; + } + if (is_unsigned) { +#if CYTHON_USE_PYLONG_INTERNALS + if (unlikely(__Pyx_PyLong_IsNeg(x))) { + goto raise_neg_overflow; + } else if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(int32_t, __Pyx_compact_upylong, __Pyx_PyLong_CompactValueUnsigned(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_DigitCount(x)) { + case 2: + if ((8 * sizeof(int32_t) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int32_t, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int32_t) >= 2 * PyLong_SHIFT)) { + return (int32_t) (((((int32_t)digits[1]) << PyLong_SHIFT) | (int32_t)digits[0])); + } + } + break; + case 3: + if ((8 * sizeof(int32_t) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int32_t, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int32_t) >= 3 * PyLong_SHIFT)) { + return (int32_t) (((((((int32_t)digits[2]) << PyLong_SHIFT) | (int32_t)digits[1]) << PyLong_SHIFT) | (int32_t)digits[0])); + } + } + break; + case 4: + if ((8 * sizeof(int32_t) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int32_t, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int32_t) >= 4 * PyLong_SHIFT)) { + return (int32_t) (((((((((int32_t)digits[3]) << PyLong_SHIFT) | (int32_t)digits[2]) << PyLong_SHIFT) | (int32_t)digits[1]) << PyLong_SHIFT) | (int32_t)digits[0])); + } + } + break; + } + } +#endif +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030C00A7 + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } +#else + { + int result = PyObject_RichCompareBool(x, Py_False, Py_LT); + if (unlikely(result < 0)) + return (int32_t) -1; + if (unlikely(result == 1)) + goto raise_neg_overflow; + } +#endif + if ((sizeof(int32_t) <= sizeof(unsigned long))) { + __PYX_VERIFY_RETURN_INT_EXC(int32_t, unsigned long, PyLong_AsUnsignedLong(x)) + } else if ((sizeof(int32_t) <= sizeof(unsigned PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(int32_t, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) + } + } else { +#if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(int32_t, __Pyx_compact_pylong, __Pyx_PyLong_CompactValue(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_SignedDigitCount(x)) { + case -2: + if ((8 * sizeof(int32_t) - 1 > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int32_t, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int32_t) - 1 > 2 * PyLong_SHIFT)) { + return (int32_t) (((int32_t)-1)*(((((int32_t)digits[1]) << PyLong_SHIFT) | (int32_t)digits[0]))); + } + } + break; + case 2: + if ((8 * sizeof(int32_t) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int32_t, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int32_t) - 1 > 2 * PyLong_SHIFT)) { + return (int32_t) ((((((int32_t)digits[1]) << PyLong_SHIFT) | (int32_t)digits[0]))); + } + } + break; + case -3: + if ((8 * sizeof(int32_t) - 1 > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int32_t, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int32_t) - 1 > 3 * PyLong_SHIFT)) { + return (int32_t) (((int32_t)-1)*(((((((int32_t)digits[2]) << PyLong_SHIFT) | (int32_t)digits[1]) << PyLong_SHIFT) | (int32_t)digits[0]))); + } + } + break; + case 3: + if ((8 * sizeof(int32_t) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int32_t, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int32_t) - 1 > 3 * PyLong_SHIFT)) { + return (int32_t) ((((((((int32_t)digits[2]) << PyLong_SHIFT) | (int32_t)digits[1]) << PyLong_SHIFT) | (int32_t)digits[0]))); + } + } + break; + case -4: + if ((8 * sizeof(int32_t) - 1 > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int32_t, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int32_t) - 1 > 4 * PyLong_SHIFT)) { + return (int32_t) (((int32_t)-1)*(((((((((int32_t)digits[3]) << PyLong_SHIFT) | (int32_t)digits[2]) << PyLong_SHIFT) | (int32_t)digits[1]) << PyLong_SHIFT) | (int32_t)digits[0]))); + } + } + break; + case 4: + if ((8 * sizeof(int32_t) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int32_t, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int32_t) - 1 > 4 * PyLong_SHIFT)) { + return (int32_t) ((((((((((int32_t)digits[3]) << PyLong_SHIFT) | (int32_t)digits[2]) << PyLong_SHIFT) | (int32_t)digits[1]) << PyLong_SHIFT) | (int32_t)digits[0]))); + } + } + break; + } + } +#endif + if ((sizeof(int32_t) <= sizeof(long))) { + __PYX_VERIFY_RETURN_INT_EXC(int32_t, long, PyLong_AsLong(x)) + } else if ((sizeof(int32_t) <= sizeof(PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(int32_t, PY_LONG_LONG, PyLong_AsLongLong(x)) + } + } + { + int32_t val; + int ret = -1; +#if PY_VERSION_HEX >= 0x030d00A6 && !CYTHON_COMPILING_IN_LIMITED_API + Py_ssize_t bytes_copied = PyLong_AsNativeBytes( + x, &val, sizeof(val), Py_ASNATIVEBYTES_NATIVE_ENDIAN | (is_unsigned ? Py_ASNATIVEBYTES_UNSIGNED_BUFFER | Py_ASNATIVEBYTES_REJECT_NEGATIVE : 0)); + if (unlikely(bytes_copied == -1)) { + } else if (unlikely(bytes_copied > (Py_ssize_t) sizeof(val))) { + goto raise_overflow; + } else { + ret = 0; + } +#elif PY_VERSION_HEX < 0x030d0000 && !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API) || defined(_PyLong_AsByteArray) + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + ret = _PyLong_AsByteArray((PyLongObject *)x, + bytes, sizeof(val), + is_little, !is_unsigned); +#else + PyObject *v; + PyObject *stepval = NULL, *mask = NULL, *shift = NULL; + int bits, remaining_bits, is_negative = 0; + int chunk_size = (sizeof(long) < 8) ? 30 : 62; + if (likely(PyLong_CheckExact(x))) { + v = __Pyx_NewRef(x); + } else { + v = PyNumber_Long(x); + if (unlikely(!v)) return (int32_t) -1; + assert(PyLong_CheckExact(v)); + } + { + int result = PyObject_RichCompareBool(v, Py_False, Py_LT); + if (unlikely(result < 0)) { + Py_DECREF(v); + return (int32_t) -1; + } + is_negative = result == 1; + } + if (is_unsigned && unlikely(is_negative)) { + Py_DECREF(v); + goto raise_neg_overflow; + } else if (is_negative) { + stepval = PyNumber_Invert(v); + Py_DECREF(v); + if (unlikely(!stepval)) + return (int32_t) -1; + } else { + stepval = v; + } + v = NULL; + val = (int32_t) 0; + mask = PyLong_FromLong((1L << chunk_size) - 1); if (unlikely(!mask)) goto done; + shift = PyLong_FromLong(chunk_size); if (unlikely(!shift)) goto done; + for (bits = 0; bits < (int) sizeof(int32_t) * 8 - chunk_size; bits += chunk_size) { + PyObject *tmp, *digit; + long idigit; + digit = PyNumber_And(stepval, mask); + if (unlikely(!digit)) goto done; + idigit = PyLong_AsLong(digit); + Py_DECREF(digit); + if (unlikely(idigit < 0)) goto done; + val |= ((int32_t) idigit) << bits; + tmp = PyNumber_Rshift(stepval, shift); + if (unlikely(!tmp)) goto done; + Py_DECREF(stepval); stepval = tmp; + } + Py_DECREF(shift); shift = NULL; + Py_DECREF(mask); mask = NULL; + { + long idigit = PyLong_AsLong(stepval); + if (unlikely(idigit < 0)) goto done; + remaining_bits = ((int) sizeof(int32_t) * 8) - bits - (is_unsigned ? 0 : 1); + if (unlikely(idigit >= (1L << remaining_bits))) + goto raise_overflow; + val |= ((int32_t) idigit) << bits; + } + if (!is_unsigned) { + if (unlikely(val & (((int32_t) 1) << (sizeof(int32_t) * 8 - 1)))) + goto raise_overflow; + if (is_negative) + val = ~val; + } + ret = 0; + done: + Py_XDECREF(shift); + Py_XDECREF(mask); + Py_XDECREF(stepval); +#endif + if (unlikely(ret)) + return (int32_t) -1; + return val; + } +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to int32_t"); + return (int32_t) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to int32_t"); + return (int32_t) -1; +} + +/* CIntFromPy */ +static CYTHON_INLINE long __Pyx_PyLong_As_long(PyObject *x) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const long neg_one = (long) -1, const_zero = (long) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (unlikely(!PyLong_Check(x))) { + long val; + PyObject *tmp = __Pyx_PyNumber_Long(x); + if (!tmp) return (long) -1; + val = __Pyx_PyLong_As_long(tmp); + Py_DECREF(tmp); + return val; + } + if (is_unsigned) { +#if CYTHON_USE_PYLONG_INTERNALS + if (unlikely(__Pyx_PyLong_IsNeg(x))) { + goto raise_neg_overflow; + } else if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(long, __Pyx_compact_upylong, __Pyx_PyLong_CompactValueUnsigned(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_DigitCount(x)) { + case 2: + if ((8 * sizeof(long) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) >= 2 * PyLong_SHIFT)) { + return (long) (((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); + } + } + break; + case 3: + if ((8 * sizeof(long) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) >= 3 * PyLong_SHIFT)) { + return (long) (((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); + } + } + break; + case 4: + if ((8 * sizeof(long) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) >= 4 * PyLong_SHIFT)) { + return (long) (((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); + } + } + break; + } + } +#endif +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030C00A7 + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } +#else + { + int result = PyObject_RichCompareBool(x, Py_False, Py_LT); + if (unlikely(result < 0)) + return (long) -1; + if (unlikely(result == 1)) + goto raise_neg_overflow; + } +#endif + if ((sizeof(long) <= sizeof(unsigned long))) { + __PYX_VERIFY_RETURN_INT_EXC(long, unsigned long, PyLong_AsUnsignedLong(x)) + } else if ((sizeof(long) <= sizeof(unsigned PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(long, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) + } + } else { +#if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(long, __Pyx_compact_pylong, __Pyx_PyLong_CompactValue(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_SignedDigitCount(x)) { + case -2: + if ((8 * sizeof(long) - 1 > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 2 * PyLong_SHIFT)) { + return (long) (((long)-1)*(((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case 2: + if ((8 * sizeof(long) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 2 * PyLong_SHIFT)) { + return (long) ((((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case -3: + if ((8 * sizeof(long) - 1 > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 3 * PyLong_SHIFT)) { + return (long) (((long)-1)*(((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case 3: + if ((8 * sizeof(long) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 3 * PyLong_SHIFT)) { + return (long) ((((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case -4: + if ((8 * sizeof(long) - 1 > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 4 * PyLong_SHIFT)) { + return (long) (((long)-1)*(((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case 4: + if ((8 * sizeof(long) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 4 * PyLong_SHIFT)) { + return (long) ((((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + } + } +#endif + if ((sizeof(long) <= sizeof(long))) { + __PYX_VERIFY_RETURN_INT_EXC(long, long, PyLong_AsLong(x)) + } else if ((sizeof(long) <= sizeof(PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(long, PY_LONG_LONG, PyLong_AsLongLong(x)) + } + } + { + long val; + int ret = -1; +#if PY_VERSION_HEX >= 0x030d00A6 && !CYTHON_COMPILING_IN_LIMITED_API + Py_ssize_t bytes_copied = PyLong_AsNativeBytes( + x, &val, sizeof(val), Py_ASNATIVEBYTES_NATIVE_ENDIAN | (is_unsigned ? Py_ASNATIVEBYTES_UNSIGNED_BUFFER | Py_ASNATIVEBYTES_REJECT_NEGATIVE : 0)); + if (unlikely(bytes_copied == -1)) { + } else if (unlikely(bytes_copied > (Py_ssize_t) sizeof(val))) { + goto raise_overflow; + } else { + ret = 0; + } +#elif PY_VERSION_HEX < 0x030d0000 && !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API) || defined(_PyLong_AsByteArray) + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + ret = _PyLong_AsByteArray((PyLongObject *)x, + bytes, sizeof(val), + is_little, !is_unsigned); +#else + PyObject *v; + PyObject *stepval = NULL, *mask = NULL, *shift = NULL; + int bits, remaining_bits, is_negative = 0; + int chunk_size = (sizeof(long) < 8) ? 30 : 62; + if (likely(PyLong_CheckExact(x))) { + v = __Pyx_NewRef(x); + } else { + v = PyNumber_Long(x); + if (unlikely(!v)) return (long) -1; + assert(PyLong_CheckExact(v)); + } + { + int result = PyObject_RichCompareBool(v, Py_False, Py_LT); + if (unlikely(result < 0)) { + Py_DECREF(v); + return (long) -1; + } + is_negative = result == 1; + } + if (is_unsigned && unlikely(is_negative)) { + Py_DECREF(v); + goto raise_neg_overflow; + } else if (is_negative) { + stepval = PyNumber_Invert(v); + Py_DECREF(v); + if (unlikely(!stepval)) + return (long) -1; + } else { + stepval = v; + } + v = NULL; + val = (long) 0; + mask = PyLong_FromLong((1L << chunk_size) - 1); if (unlikely(!mask)) goto done; + shift = PyLong_FromLong(chunk_size); if (unlikely(!shift)) goto done; + for (bits = 0; bits < (int) sizeof(long) * 8 - chunk_size; bits += chunk_size) { + PyObject *tmp, *digit; + long idigit; + digit = PyNumber_And(stepval, mask); + if (unlikely(!digit)) goto done; + idigit = PyLong_AsLong(digit); + Py_DECREF(digit); + if (unlikely(idigit < 0)) goto done; + val |= ((long) idigit) << bits; + tmp = PyNumber_Rshift(stepval, shift); + if (unlikely(!tmp)) goto done; + Py_DECREF(stepval); stepval = tmp; + } + Py_DECREF(shift); shift = NULL; + Py_DECREF(mask); mask = NULL; + { + long idigit = PyLong_AsLong(stepval); + if (unlikely(idigit < 0)) goto done; + remaining_bits = ((int) sizeof(long) * 8) - bits - (is_unsigned ? 0 : 1); + if (unlikely(idigit >= (1L << remaining_bits))) + goto raise_overflow; + val |= ((long) idigit) << bits; + } + if (!is_unsigned) { + if (unlikely(val & (((long) 1) << (sizeof(long) * 8 - 1)))) + goto raise_overflow; + if (is_negative) + val = ~val; + } + ret = 0; + done: + Py_XDECREF(shift); + Py_XDECREF(mask); + Py_XDECREF(stepval); +#endif + if (unlikely(ret)) + return (long) -1; + return val; + } +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to long"); + return (long) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to long"); + return (long) -1; +} + +/* CIntToPy */ +static CYTHON_INLINE PyObject* __Pyx_PyLong_From_long(long value) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const long neg_one = (long) -1, const_zero = (long) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(long) < sizeof(long)) { + return PyLong_FromLong((long) value); + } else if (sizeof(long) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); +#if !CYTHON_COMPILING_IN_PYPY + } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { + return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); +#endif + } + } else { + if (sizeof(long) <= sizeof(long)) { + return PyLong_FromLong((long) value); + } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { + return PyLong_FromLongLong((PY_LONG_LONG) value); + } + } + { + unsigned char *bytes = (unsigned char *)&value; +#if !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d00A4 + if (is_unsigned) { + return PyLong_FromUnsignedNativeBytes(bytes, sizeof(value), -1); + } else { + return PyLong_FromNativeBytes(bytes, sizeof(value), -1); + } +#elif !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030d0000 + int one = 1; int little = (int)*(unsigned char *)&one; + return _PyLong_FromByteArray(bytes, sizeof(long), + little, !is_unsigned); +#else + int one = 1; int little = (int)*(unsigned char *)&one; + PyObject *from_bytes, *result = NULL, *kwds = NULL; + PyObject *py_bytes = NULL, *order_str = NULL; + from_bytes = PyObject_GetAttrString((PyObject*)&PyLong_Type, "from_bytes"); + if (!from_bytes) return NULL; + py_bytes = PyBytes_FromStringAndSize((char*)bytes, sizeof(long)); + if (!py_bytes) goto limited_bad; + order_str = PyUnicode_FromString(little ? "little" : "big"); + if (!order_str) goto limited_bad; + { + PyObject *args[3+(CYTHON_VECTORCALL ? 1 : 0)] = { NULL, py_bytes, order_str }; + if (!is_unsigned) { + kwds = __Pyx_MakeVectorcallBuilderKwds(1); + if (!kwds) goto limited_bad; + if (__Pyx_VectorcallBuilder_AddArgStr("signed", __Pyx_NewRef(Py_True), kwds, args+3, 0) < 0) goto limited_bad; + } + result = __Pyx_Object_Vectorcall_CallFromBuilder(from_bytes, args+1, 2 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET, kwds); + } + limited_bad: + Py_XDECREF(kwds); + Py_XDECREF(order_str); + Py_XDECREF(py_bytes); + Py_XDECREF(from_bytes); + return result; +#endif + } +} + +/* CIntToPy */ +static CYTHON_INLINE PyObject* __Pyx_PyLong_From_int(int value) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const int neg_one = (int) -1, const_zero = (int) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(int) < sizeof(long)) { + return PyLong_FromLong((long) value); + } else if (sizeof(int) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); +#if !CYTHON_COMPILING_IN_PYPY + } else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) { + return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); +#endif + } + } else { + if (sizeof(int) <= sizeof(long)) { + return PyLong_FromLong((long) value); + } else if (sizeof(int) <= sizeof(PY_LONG_LONG)) { + return PyLong_FromLongLong((PY_LONG_LONG) value); + } + } + { + unsigned char *bytes = (unsigned char *)&value; +#if !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d00A4 + if (is_unsigned) { + return PyLong_FromUnsignedNativeBytes(bytes, sizeof(value), -1); + } else { + return PyLong_FromNativeBytes(bytes, sizeof(value), -1); + } +#elif !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030d0000 + int one = 1; int little = (int)*(unsigned char *)&one; + return _PyLong_FromByteArray(bytes, sizeof(int), + little, !is_unsigned); +#else + int one = 1; int little = (int)*(unsigned char *)&one; + PyObject *from_bytes, *result = NULL, *kwds = NULL; + PyObject *py_bytes = NULL, *order_str = NULL; + from_bytes = PyObject_GetAttrString((PyObject*)&PyLong_Type, "from_bytes"); + if (!from_bytes) return NULL; + py_bytes = PyBytes_FromStringAndSize((char*)bytes, sizeof(int)); + if (!py_bytes) goto limited_bad; + order_str = PyUnicode_FromString(little ? "little" : "big"); + if (!order_str) goto limited_bad; + { + PyObject *args[3+(CYTHON_VECTORCALL ? 1 : 0)] = { NULL, py_bytes, order_str }; + if (!is_unsigned) { + kwds = __Pyx_MakeVectorcallBuilderKwds(1); + if (!kwds) goto limited_bad; + if (__Pyx_VectorcallBuilder_AddArgStr("signed", __Pyx_NewRef(Py_True), kwds, args+3, 0) < 0) goto limited_bad; + } + result = __Pyx_Object_Vectorcall_CallFromBuilder(from_bytes, args+1, 2 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET, kwds); + } + limited_bad: + Py_XDECREF(kwds); + Py_XDECREF(order_str); + Py_XDECREF(py_bytes); + Py_XDECREF(from_bytes); + return result; +#endif + } +} + +/* CIntFromPy */ +static CYTHON_INLINE int __Pyx_PyLong_As_int(PyObject *x) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const int neg_one = (int) -1, const_zero = (int) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (unlikely(!PyLong_Check(x))) { + int val; + PyObject *tmp = __Pyx_PyNumber_Long(x); + if (!tmp) return (int) -1; + val = __Pyx_PyLong_As_int(tmp); + Py_DECREF(tmp); + return val; + } + if (is_unsigned) { +#if CYTHON_USE_PYLONG_INTERNALS + if (unlikely(__Pyx_PyLong_IsNeg(x))) { + goto raise_neg_overflow; + } else if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(int, __Pyx_compact_upylong, __Pyx_PyLong_CompactValueUnsigned(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_DigitCount(x)) { + case 2: + if ((8 * sizeof(int) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) >= 2 * PyLong_SHIFT)) { + return (int) (((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); + } + } + break; + case 3: + if ((8 * sizeof(int) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) >= 3 * PyLong_SHIFT)) { + return (int) (((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); + } + } + break; + case 4: + if ((8 * sizeof(int) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) >= 4 * PyLong_SHIFT)) { + return (int) (((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); + } + } + break; + } + } +#endif +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030C00A7 + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } +#else + { + int result = PyObject_RichCompareBool(x, Py_False, Py_LT); + if (unlikely(result < 0)) + return (int) -1; + if (unlikely(result == 1)) + goto raise_neg_overflow; + } +#endif + if ((sizeof(int) <= sizeof(unsigned long))) { + __PYX_VERIFY_RETURN_INT_EXC(int, unsigned long, PyLong_AsUnsignedLong(x)) + } else if ((sizeof(int) <= sizeof(unsigned PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(int, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) + } + } else { +#if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(int, __Pyx_compact_pylong, __Pyx_PyLong_CompactValue(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_SignedDigitCount(x)) { + case -2: + if ((8 * sizeof(int) - 1 > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 2 * PyLong_SHIFT)) { + return (int) (((int)-1)*(((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case 2: + if ((8 * sizeof(int) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 2 * PyLong_SHIFT)) { + return (int) ((((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case -3: + if ((8 * sizeof(int) - 1 > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 3 * PyLong_SHIFT)) { + return (int) (((int)-1)*(((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case 3: + if ((8 * sizeof(int) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 3 * PyLong_SHIFT)) { + return (int) ((((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case -4: + if ((8 * sizeof(int) - 1 > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 4 * PyLong_SHIFT)) { + return (int) (((int)-1)*(((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case 4: + if ((8 * sizeof(int) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 4 * PyLong_SHIFT)) { + return (int) ((((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + } + } +#endif + if ((sizeof(int) <= sizeof(long))) { + __PYX_VERIFY_RETURN_INT_EXC(int, long, PyLong_AsLong(x)) + } else if ((sizeof(int) <= sizeof(PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(int, PY_LONG_LONG, PyLong_AsLongLong(x)) + } + } + { + int val; + int ret = -1; +#if PY_VERSION_HEX >= 0x030d00A6 && !CYTHON_COMPILING_IN_LIMITED_API + Py_ssize_t bytes_copied = PyLong_AsNativeBytes( + x, &val, sizeof(val), Py_ASNATIVEBYTES_NATIVE_ENDIAN | (is_unsigned ? Py_ASNATIVEBYTES_UNSIGNED_BUFFER | Py_ASNATIVEBYTES_REJECT_NEGATIVE : 0)); + if (unlikely(bytes_copied == -1)) { + } else if (unlikely(bytes_copied > (Py_ssize_t) sizeof(val))) { + goto raise_overflow; + } else { + ret = 0; + } +#elif PY_VERSION_HEX < 0x030d0000 && !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API) || defined(_PyLong_AsByteArray) + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + ret = _PyLong_AsByteArray((PyLongObject *)x, + bytes, sizeof(val), + is_little, !is_unsigned); +#else + PyObject *v; + PyObject *stepval = NULL, *mask = NULL, *shift = NULL; + int bits, remaining_bits, is_negative = 0; + int chunk_size = (sizeof(long) < 8) ? 30 : 62; + if (likely(PyLong_CheckExact(x))) { + v = __Pyx_NewRef(x); + } else { + v = PyNumber_Long(x); + if (unlikely(!v)) return (int) -1; + assert(PyLong_CheckExact(v)); + } + { + int result = PyObject_RichCompareBool(v, Py_False, Py_LT); + if (unlikely(result < 0)) { + Py_DECREF(v); + return (int) -1; + } + is_negative = result == 1; + } + if (is_unsigned && unlikely(is_negative)) { + Py_DECREF(v); + goto raise_neg_overflow; + } else if (is_negative) { + stepval = PyNumber_Invert(v); + Py_DECREF(v); + if (unlikely(!stepval)) + return (int) -1; + } else { + stepval = v; + } + v = NULL; + val = (int) 0; + mask = PyLong_FromLong((1L << chunk_size) - 1); if (unlikely(!mask)) goto done; + shift = PyLong_FromLong(chunk_size); if (unlikely(!shift)) goto done; + for (bits = 0; bits < (int) sizeof(int) * 8 - chunk_size; bits += chunk_size) { + PyObject *tmp, *digit; + long idigit; + digit = PyNumber_And(stepval, mask); + if (unlikely(!digit)) goto done; + idigit = PyLong_AsLong(digit); + Py_DECREF(digit); + if (unlikely(idigit < 0)) goto done; + val |= ((int) idigit) << bits; + tmp = PyNumber_Rshift(stepval, shift); + if (unlikely(!tmp)) goto done; + Py_DECREF(stepval); stepval = tmp; + } + Py_DECREF(shift); shift = NULL; + Py_DECREF(mask); mask = NULL; + { + long idigit = PyLong_AsLong(stepval); + if (unlikely(idigit < 0)) goto done; + remaining_bits = ((int) sizeof(int) * 8) - bits - (is_unsigned ? 0 : 1); + if (unlikely(idigit >= (1L << remaining_bits))) + goto raise_overflow; + val |= ((int) idigit) << bits; + } + if (!is_unsigned) { + if (unlikely(val & (((int) 1) << (sizeof(int) * 8 - 1)))) + goto raise_overflow; + if (is_negative) + val = ~val; + } + ret = 0; + done: + Py_XDECREF(shift); + Py_XDECREF(mask); + Py_XDECREF(stepval); +#endif + if (unlikely(ret)) + return (int) -1; + return val; + } +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to int"); + return (int) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to int"); + return (int) -1; +} + +/* CIntToPy */ +static CYTHON_INLINE PyObject* __Pyx_PyLong_From_char(char value) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const char neg_one = (char) -1, const_zero = (char) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(char) < sizeof(long)) { + return PyLong_FromLong((long) value); + } else if (sizeof(char) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); +#if !CYTHON_COMPILING_IN_PYPY + } else if (sizeof(char) <= sizeof(unsigned PY_LONG_LONG)) { + return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); +#endif + } + } else { + if (sizeof(char) <= sizeof(long)) { + return PyLong_FromLong((long) value); + } else if (sizeof(char) <= sizeof(PY_LONG_LONG)) { + return PyLong_FromLongLong((PY_LONG_LONG) value); + } + } + { + unsigned char *bytes = (unsigned char *)&value; +#if !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d00A4 + if (is_unsigned) { + return PyLong_FromUnsignedNativeBytes(bytes, sizeof(value), -1); + } else { + return PyLong_FromNativeBytes(bytes, sizeof(value), -1); + } +#elif !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030d0000 + int one = 1; int little = (int)*(unsigned char *)&one; + return _PyLong_FromByteArray(bytes, sizeof(char), + little, !is_unsigned); +#else + int one = 1; int little = (int)*(unsigned char *)&one; + PyObject *from_bytes, *result = NULL, *kwds = NULL; + PyObject *py_bytes = NULL, *order_str = NULL; + from_bytes = PyObject_GetAttrString((PyObject*)&PyLong_Type, "from_bytes"); + if (!from_bytes) return NULL; + py_bytes = PyBytes_FromStringAndSize((char*)bytes, sizeof(char)); + if (!py_bytes) goto limited_bad; + order_str = PyUnicode_FromString(little ? "little" : "big"); + if (!order_str) goto limited_bad; + { + PyObject *args[3+(CYTHON_VECTORCALL ? 1 : 0)] = { NULL, py_bytes, order_str }; + if (!is_unsigned) { + kwds = __Pyx_MakeVectorcallBuilderKwds(1); + if (!kwds) goto limited_bad; + if (__Pyx_VectorcallBuilder_AddArgStr("signed", __Pyx_NewRef(Py_True), kwds, args+3, 0) < 0) goto limited_bad; + } + result = __Pyx_Object_Vectorcall_CallFromBuilder(from_bytes, args+1, 2 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET, kwds); + } + limited_bad: + Py_XDECREF(kwds); + Py_XDECREF(order_str); + Py_XDECREF(py_bytes); + Py_XDECREF(from_bytes); + return result; +#endif + } +} + +/* CIntToPy */ +static CYTHON_INLINE PyObject* __Pyx_PyLong_From_int16_t(int16_t value) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const int16_t neg_one = (int16_t) -1, const_zero = (int16_t) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(int16_t) < sizeof(long)) { + return PyLong_FromLong((long) value); + } else if (sizeof(int16_t) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); +#if !CYTHON_COMPILING_IN_PYPY + } else if (sizeof(int16_t) <= sizeof(unsigned PY_LONG_LONG)) { + return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); +#endif + } + } else { + if (sizeof(int16_t) <= sizeof(long)) { + return PyLong_FromLong((long) value); + } else if (sizeof(int16_t) <= sizeof(PY_LONG_LONG)) { + return PyLong_FromLongLong((PY_LONG_LONG) value); + } + } + { + unsigned char *bytes = (unsigned char *)&value; +#if !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d00A4 + if (is_unsigned) { + return PyLong_FromUnsignedNativeBytes(bytes, sizeof(value), -1); + } else { + return PyLong_FromNativeBytes(bytes, sizeof(value), -1); + } +#elif !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030d0000 + int one = 1; int little = (int)*(unsigned char *)&one; + return _PyLong_FromByteArray(bytes, sizeof(int16_t), + little, !is_unsigned); +#else + int one = 1; int little = (int)*(unsigned char *)&one; + PyObject *from_bytes, *result = NULL, *kwds = NULL; + PyObject *py_bytes = NULL, *order_str = NULL; + from_bytes = PyObject_GetAttrString((PyObject*)&PyLong_Type, "from_bytes"); + if (!from_bytes) return NULL; + py_bytes = PyBytes_FromStringAndSize((char*)bytes, sizeof(int16_t)); + if (!py_bytes) goto limited_bad; + order_str = PyUnicode_FromString(little ? "little" : "big"); + if (!order_str) goto limited_bad; + { + PyObject *args[3+(CYTHON_VECTORCALL ? 1 : 0)] = { NULL, py_bytes, order_str }; + if (!is_unsigned) { + kwds = __Pyx_MakeVectorcallBuilderKwds(1); + if (!kwds) goto limited_bad; + if (__Pyx_VectorcallBuilder_AddArgStr("signed", __Pyx_NewRef(Py_True), kwds, args+3, 0) < 0) goto limited_bad; + } + result = __Pyx_Object_Vectorcall_CallFromBuilder(from_bytes, args+1, 2 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET, kwds); + } + limited_bad: + Py_XDECREF(kwds); + Py_XDECREF(order_str); + Py_XDECREF(py_bytes); + Py_XDECREF(from_bytes); + return result; +#endif + } +} + +/* CIntToPy */ +static CYTHON_INLINE PyObject* __Pyx_PyLong_From_int32_t(int32_t value) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const int32_t neg_one = (int32_t) -1, const_zero = (int32_t) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(int32_t) < sizeof(long)) { + return PyLong_FromLong((long) value); + } else if (sizeof(int32_t) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); +#if !CYTHON_COMPILING_IN_PYPY + } else if (sizeof(int32_t) <= sizeof(unsigned PY_LONG_LONG)) { + return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); +#endif + } + } else { + if (sizeof(int32_t) <= sizeof(long)) { + return PyLong_FromLong((long) value); + } else if (sizeof(int32_t) <= sizeof(PY_LONG_LONG)) { + return PyLong_FromLongLong((PY_LONG_LONG) value); + } + } + { + unsigned char *bytes = (unsigned char *)&value; +#if !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d00A4 + if (is_unsigned) { + return PyLong_FromUnsignedNativeBytes(bytes, sizeof(value), -1); + } else { + return PyLong_FromNativeBytes(bytes, sizeof(value), -1); + } +#elif !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030d0000 + int one = 1; int little = (int)*(unsigned char *)&one; + return _PyLong_FromByteArray(bytes, sizeof(int32_t), + little, !is_unsigned); +#else + int one = 1; int little = (int)*(unsigned char *)&one; + PyObject *from_bytes, *result = NULL, *kwds = NULL; + PyObject *py_bytes = NULL, *order_str = NULL; + from_bytes = PyObject_GetAttrString((PyObject*)&PyLong_Type, "from_bytes"); + if (!from_bytes) return NULL; + py_bytes = PyBytes_FromStringAndSize((char*)bytes, sizeof(int32_t)); + if (!py_bytes) goto limited_bad; + order_str = PyUnicode_FromString(little ? "little" : "big"); + if (!order_str) goto limited_bad; + { + PyObject *args[3+(CYTHON_VECTORCALL ? 1 : 0)] = { NULL, py_bytes, order_str }; + if (!is_unsigned) { + kwds = __Pyx_MakeVectorcallBuilderKwds(1); + if (!kwds) goto limited_bad; + if (__Pyx_VectorcallBuilder_AddArgStr("signed", __Pyx_NewRef(Py_True), kwds, args+3, 0) < 0) goto limited_bad; + } + result = __Pyx_Object_Vectorcall_CallFromBuilder(from_bytes, args+1, 2 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET, kwds); + } + limited_bad: + Py_XDECREF(kwds); + Py_XDECREF(order_str); + Py_XDECREF(py_bytes); + Py_XDECREF(from_bytes); + return result; +#endif + } +} + +/* CIntToPy */ +static CYTHON_INLINE PyObject* __Pyx_PyLong_From_int64_t(int64_t value) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const int64_t neg_one = (int64_t) -1, const_zero = (int64_t) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(int64_t) < sizeof(long)) { + return PyLong_FromLong((long) value); + } else if (sizeof(int64_t) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); +#if !CYTHON_COMPILING_IN_PYPY + } else if (sizeof(int64_t) <= sizeof(unsigned PY_LONG_LONG)) { + return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); +#endif + } + } else { + if (sizeof(int64_t) <= sizeof(long)) { + return PyLong_FromLong((long) value); + } else if (sizeof(int64_t) <= sizeof(PY_LONG_LONG)) { + return PyLong_FromLongLong((PY_LONG_LONG) value); + } + } + { + unsigned char *bytes = (unsigned char *)&value; +#if !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d00A4 + if (is_unsigned) { + return PyLong_FromUnsignedNativeBytes(bytes, sizeof(value), -1); + } else { + return PyLong_FromNativeBytes(bytes, sizeof(value), -1); + } +#elif !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030d0000 + int one = 1; int little = (int)*(unsigned char *)&one; + return _PyLong_FromByteArray(bytes, sizeof(int64_t), + little, !is_unsigned); +#else + int one = 1; int little = (int)*(unsigned char *)&one; + PyObject *from_bytes, *result = NULL, *kwds = NULL; + PyObject *py_bytes = NULL, *order_str = NULL; + from_bytes = PyObject_GetAttrString((PyObject*)&PyLong_Type, "from_bytes"); + if (!from_bytes) return NULL; + py_bytes = PyBytes_FromStringAndSize((char*)bytes, sizeof(int64_t)); + if (!py_bytes) goto limited_bad; + order_str = PyUnicode_FromString(little ? "little" : "big"); + if (!order_str) goto limited_bad; + { + PyObject *args[3+(CYTHON_VECTORCALL ? 1 : 0)] = { NULL, py_bytes, order_str }; + if (!is_unsigned) { + kwds = __Pyx_MakeVectorcallBuilderKwds(1); + if (!kwds) goto limited_bad; + if (__Pyx_VectorcallBuilder_AddArgStr("signed", __Pyx_NewRef(Py_True), kwds, args+3, 0) < 0) goto limited_bad; + } + result = __Pyx_Object_Vectorcall_CallFromBuilder(from_bytes, args+1, 2 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET, kwds); + } + limited_bad: + Py_XDECREF(kwds); + Py_XDECREF(order_str); + Py_XDECREF(py_bytes); + Py_XDECREF(from_bytes); + return result; +#endif + } +} + +/* CIntFromPy */ +static CYTHON_INLINE char __Pyx_PyLong_As_char(PyObject *x) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const char neg_one = (char) -1, const_zero = (char) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (unlikely(!PyLong_Check(x))) { + char val; + PyObject *tmp = __Pyx_PyNumber_Long(x); + if (!tmp) return (char) -1; + val = __Pyx_PyLong_As_char(tmp); + Py_DECREF(tmp); + return val; + } + if (is_unsigned) { +#if CYTHON_USE_PYLONG_INTERNALS + if (unlikely(__Pyx_PyLong_IsNeg(x))) { + goto raise_neg_overflow; + } else if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(char, __Pyx_compact_upylong, __Pyx_PyLong_CompactValueUnsigned(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_DigitCount(x)) { + case 2: + if ((8 * sizeof(char) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(char) >= 2 * PyLong_SHIFT)) { + return (char) (((((char)digits[1]) << PyLong_SHIFT) | (char)digits[0])); + } + } + break; + case 3: + if ((8 * sizeof(char) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(char) >= 3 * PyLong_SHIFT)) { + return (char) (((((((char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0])); + } + } + break; + case 4: + if ((8 * sizeof(char) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(char) >= 4 * PyLong_SHIFT)) { + return (char) (((((((((char)digits[3]) << PyLong_SHIFT) | (char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0])); + } + } + break; + } + } +#endif +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030C00A7 + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } +#else + { + int result = PyObject_RichCompareBool(x, Py_False, Py_LT); + if (unlikely(result < 0)) + return (char) -1; + if (unlikely(result == 1)) + goto raise_neg_overflow; + } +#endif + if ((sizeof(char) <= sizeof(unsigned long))) { + __PYX_VERIFY_RETURN_INT_EXC(char, unsigned long, PyLong_AsUnsignedLong(x)) + } else if ((sizeof(char) <= sizeof(unsigned PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(char, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) + } + } else { +#if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(char, __Pyx_compact_pylong, __Pyx_PyLong_CompactValue(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_SignedDigitCount(x)) { + case -2: + if ((8 * sizeof(char) - 1 > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(char, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(char) - 1 > 2 * PyLong_SHIFT)) { + return (char) (((char)-1)*(((((char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); + } + } + break; + case 2: + if ((8 * sizeof(char) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(char) - 1 > 2 * PyLong_SHIFT)) { + return (char) ((((((char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); + } + } + break; + case -3: + if ((8 * sizeof(char) - 1 > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(char, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(char) - 1 > 3 * PyLong_SHIFT)) { + return (char) (((char)-1)*(((((((char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); + } + } + break; + case 3: + if ((8 * sizeof(char) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(char) - 1 > 3 * PyLong_SHIFT)) { + return (char) ((((((((char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); + } + } + break; + case -4: + if ((8 * sizeof(char) - 1 > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(char, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(char) - 1 > 4 * PyLong_SHIFT)) { + return (char) (((char)-1)*(((((((((char)digits[3]) << PyLong_SHIFT) | (char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); + } + } + break; + case 4: + if ((8 * sizeof(char) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(char) - 1 > 4 * PyLong_SHIFT)) { + return (char) ((((((((((char)digits[3]) << PyLong_SHIFT) | (char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); + } + } + break; + } + } +#endif + if ((sizeof(char) <= sizeof(long))) { + __PYX_VERIFY_RETURN_INT_EXC(char, long, PyLong_AsLong(x)) + } else if ((sizeof(char) <= sizeof(PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(char, PY_LONG_LONG, PyLong_AsLongLong(x)) + } + } + { + char val; + int ret = -1; +#if PY_VERSION_HEX >= 0x030d00A6 && !CYTHON_COMPILING_IN_LIMITED_API + Py_ssize_t bytes_copied = PyLong_AsNativeBytes( + x, &val, sizeof(val), Py_ASNATIVEBYTES_NATIVE_ENDIAN | (is_unsigned ? Py_ASNATIVEBYTES_UNSIGNED_BUFFER | Py_ASNATIVEBYTES_REJECT_NEGATIVE : 0)); + if (unlikely(bytes_copied == -1)) { + } else if (unlikely(bytes_copied > (Py_ssize_t) sizeof(val))) { + goto raise_overflow; + } else { + ret = 0; + } +#elif PY_VERSION_HEX < 0x030d0000 && !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API) || defined(_PyLong_AsByteArray) + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + ret = _PyLong_AsByteArray((PyLongObject *)x, + bytes, sizeof(val), + is_little, !is_unsigned); +#else + PyObject *v; + PyObject *stepval = NULL, *mask = NULL, *shift = NULL; + int bits, remaining_bits, is_negative = 0; + int chunk_size = (sizeof(long) < 8) ? 30 : 62; + if (likely(PyLong_CheckExact(x))) { + v = __Pyx_NewRef(x); + } else { + v = PyNumber_Long(x); + if (unlikely(!v)) return (char) -1; + assert(PyLong_CheckExact(v)); + } + { + int result = PyObject_RichCompareBool(v, Py_False, Py_LT); + if (unlikely(result < 0)) { + Py_DECREF(v); + return (char) -1; + } + is_negative = result == 1; + } + if (is_unsigned && unlikely(is_negative)) { + Py_DECREF(v); + goto raise_neg_overflow; + } else if (is_negative) { + stepval = PyNumber_Invert(v); + Py_DECREF(v); + if (unlikely(!stepval)) + return (char) -1; + } else { + stepval = v; + } + v = NULL; + val = (char) 0; + mask = PyLong_FromLong((1L << chunk_size) - 1); if (unlikely(!mask)) goto done; + shift = PyLong_FromLong(chunk_size); if (unlikely(!shift)) goto done; + for (bits = 0; bits < (int) sizeof(char) * 8 - chunk_size; bits += chunk_size) { + PyObject *tmp, *digit; + long idigit; + digit = PyNumber_And(stepval, mask); + if (unlikely(!digit)) goto done; + idigit = PyLong_AsLong(digit); + Py_DECREF(digit); + if (unlikely(idigit < 0)) goto done; + val |= ((char) idigit) << bits; + tmp = PyNumber_Rshift(stepval, shift); + if (unlikely(!tmp)) goto done; + Py_DECREF(stepval); stepval = tmp; + } + Py_DECREF(shift); shift = NULL; + Py_DECREF(mask); mask = NULL; + { + long idigit = PyLong_AsLong(stepval); + if (unlikely(idigit < 0)) goto done; + remaining_bits = ((int) sizeof(char) * 8) - bits - (is_unsigned ? 0 : 1); + if (unlikely(idigit >= (1L << remaining_bits))) + goto raise_overflow; + val |= ((char) idigit) << bits; + } + if (!is_unsigned) { + if (unlikely(val & (((char) 1) << (sizeof(char) * 8 - 1)))) + goto raise_overflow; + if (is_negative) + val = ~val; + } + ret = 0; + done: + Py_XDECREF(shift); + Py_XDECREF(mask); + Py_XDECREF(stepval); +#endif + if (unlikely(ret)) + return (char) -1; + return val; + } +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to char"); + return (char) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to char"); + return (char) -1; +} + +/* CIntFromPy */ +static CYTHON_INLINE int16_t __Pyx_PyLong_As_int16_t(PyObject *x) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const int16_t neg_one = (int16_t) -1, const_zero = (int16_t) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (unlikely(!PyLong_Check(x))) { + int16_t val; + PyObject *tmp = __Pyx_PyNumber_Long(x); + if (!tmp) return (int16_t) -1; + val = __Pyx_PyLong_As_int16_t(tmp); + Py_DECREF(tmp); + return val; + } + if (is_unsigned) { +#if CYTHON_USE_PYLONG_INTERNALS + if (unlikely(__Pyx_PyLong_IsNeg(x))) { + goto raise_neg_overflow; + } else if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(int16_t, __Pyx_compact_upylong, __Pyx_PyLong_CompactValueUnsigned(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_DigitCount(x)) { + case 2: + if ((8 * sizeof(int16_t) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int16_t, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int16_t) >= 2 * PyLong_SHIFT)) { + return (int16_t) (((((int16_t)digits[1]) << PyLong_SHIFT) | (int16_t)digits[0])); + } + } + break; + case 3: + if ((8 * sizeof(int16_t) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int16_t, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int16_t) >= 3 * PyLong_SHIFT)) { + return (int16_t) (((((((int16_t)digits[2]) << PyLong_SHIFT) | (int16_t)digits[1]) << PyLong_SHIFT) | (int16_t)digits[0])); + } + } + break; + case 4: + if ((8 * sizeof(int16_t) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int16_t, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int16_t) >= 4 * PyLong_SHIFT)) { + return (int16_t) (((((((((int16_t)digits[3]) << PyLong_SHIFT) | (int16_t)digits[2]) << PyLong_SHIFT) | (int16_t)digits[1]) << PyLong_SHIFT) | (int16_t)digits[0])); + } + } + break; + } + } +#endif +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030C00A7 + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } +#else + { + int result = PyObject_RichCompareBool(x, Py_False, Py_LT); + if (unlikely(result < 0)) + return (int16_t) -1; + if (unlikely(result == 1)) + goto raise_neg_overflow; + } +#endif + if ((sizeof(int16_t) <= sizeof(unsigned long))) { + __PYX_VERIFY_RETURN_INT_EXC(int16_t, unsigned long, PyLong_AsUnsignedLong(x)) + } else if ((sizeof(int16_t) <= sizeof(unsigned PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(int16_t, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) + } + } else { +#if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(int16_t, __Pyx_compact_pylong, __Pyx_PyLong_CompactValue(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_SignedDigitCount(x)) { + case -2: + if ((8 * sizeof(int16_t) - 1 > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int16_t, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int16_t) - 1 > 2 * PyLong_SHIFT)) { + return (int16_t) (((int16_t)-1)*(((((int16_t)digits[1]) << PyLong_SHIFT) | (int16_t)digits[0]))); + } + } + break; + case 2: + if ((8 * sizeof(int16_t) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int16_t, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int16_t) - 1 > 2 * PyLong_SHIFT)) { + return (int16_t) ((((((int16_t)digits[1]) << PyLong_SHIFT) | (int16_t)digits[0]))); + } + } + break; + case -3: + if ((8 * sizeof(int16_t) - 1 > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int16_t, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int16_t) - 1 > 3 * PyLong_SHIFT)) { + return (int16_t) (((int16_t)-1)*(((((((int16_t)digits[2]) << PyLong_SHIFT) | (int16_t)digits[1]) << PyLong_SHIFT) | (int16_t)digits[0]))); + } + } + break; + case 3: + if ((8 * sizeof(int16_t) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int16_t, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int16_t) - 1 > 3 * PyLong_SHIFT)) { + return (int16_t) ((((((((int16_t)digits[2]) << PyLong_SHIFT) | (int16_t)digits[1]) << PyLong_SHIFT) | (int16_t)digits[0]))); + } + } + break; + case -4: + if ((8 * sizeof(int16_t) - 1 > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int16_t, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int16_t) - 1 > 4 * PyLong_SHIFT)) { + return (int16_t) (((int16_t)-1)*(((((((((int16_t)digits[3]) << PyLong_SHIFT) | (int16_t)digits[2]) << PyLong_SHIFT) | (int16_t)digits[1]) << PyLong_SHIFT) | (int16_t)digits[0]))); + } + } + break; + case 4: + if ((8 * sizeof(int16_t) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int16_t, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int16_t) - 1 > 4 * PyLong_SHIFT)) { + return (int16_t) ((((((((((int16_t)digits[3]) << PyLong_SHIFT) | (int16_t)digits[2]) << PyLong_SHIFT) | (int16_t)digits[1]) << PyLong_SHIFT) | (int16_t)digits[0]))); + } + } + break; + } + } +#endif + if ((sizeof(int16_t) <= sizeof(long))) { + __PYX_VERIFY_RETURN_INT_EXC(int16_t, long, PyLong_AsLong(x)) + } else if ((sizeof(int16_t) <= sizeof(PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(int16_t, PY_LONG_LONG, PyLong_AsLongLong(x)) + } + } + { + int16_t val; + int ret = -1; +#if PY_VERSION_HEX >= 0x030d00A6 && !CYTHON_COMPILING_IN_LIMITED_API + Py_ssize_t bytes_copied = PyLong_AsNativeBytes( + x, &val, sizeof(val), Py_ASNATIVEBYTES_NATIVE_ENDIAN | (is_unsigned ? Py_ASNATIVEBYTES_UNSIGNED_BUFFER | Py_ASNATIVEBYTES_REJECT_NEGATIVE : 0)); + if (unlikely(bytes_copied == -1)) { + } else if (unlikely(bytes_copied > (Py_ssize_t) sizeof(val))) { + goto raise_overflow; + } else { + ret = 0; + } +#elif PY_VERSION_HEX < 0x030d0000 && !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API) || defined(_PyLong_AsByteArray) + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + ret = _PyLong_AsByteArray((PyLongObject *)x, + bytes, sizeof(val), + is_little, !is_unsigned); +#else + PyObject *v; + PyObject *stepval = NULL, *mask = NULL, *shift = NULL; + int bits, remaining_bits, is_negative = 0; + int chunk_size = (sizeof(long) < 8) ? 30 : 62; + if (likely(PyLong_CheckExact(x))) { + v = __Pyx_NewRef(x); + } else { + v = PyNumber_Long(x); + if (unlikely(!v)) return (int16_t) -1; + assert(PyLong_CheckExact(v)); + } + { + int result = PyObject_RichCompareBool(v, Py_False, Py_LT); + if (unlikely(result < 0)) { + Py_DECREF(v); + return (int16_t) -1; + } + is_negative = result == 1; + } + if (is_unsigned && unlikely(is_negative)) { + Py_DECREF(v); + goto raise_neg_overflow; + } else if (is_negative) { + stepval = PyNumber_Invert(v); + Py_DECREF(v); + if (unlikely(!stepval)) + return (int16_t) -1; + } else { + stepval = v; + } + v = NULL; + val = (int16_t) 0; + mask = PyLong_FromLong((1L << chunk_size) - 1); if (unlikely(!mask)) goto done; + shift = PyLong_FromLong(chunk_size); if (unlikely(!shift)) goto done; + for (bits = 0; bits < (int) sizeof(int16_t) * 8 - chunk_size; bits += chunk_size) { + PyObject *tmp, *digit; + long idigit; + digit = PyNumber_And(stepval, mask); + if (unlikely(!digit)) goto done; + idigit = PyLong_AsLong(digit); + Py_DECREF(digit); + if (unlikely(idigit < 0)) goto done; + val |= ((int16_t) idigit) << bits; + tmp = PyNumber_Rshift(stepval, shift); + if (unlikely(!tmp)) goto done; + Py_DECREF(stepval); stepval = tmp; + } + Py_DECREF(shift); shift = NULL; + Py_DECREF(mask); mask = NULL; + { + long idigit = PyLong_AsLong(stepval); + if (unlikely(idigit < 0)) goto done; + remaining_bits = ((int) sizeof(int16_t) * 8) - bits - (is_unsigned ? 0 : 1); + if (unlikely(idigit >= (1L << remaining_bits))) + goto raise_overflow; + val |= ((int16_t) idigit) << bits; + } + if (!is_unsigned) { + if (unlikely(val & (((int16_t) 1) << (sizeof(int16_t) * 8 - 1)))) + goto raise_overflow; + if (is_negative) + val = ~val; + } + ret = 0; + done: + Py_XDECREF(shift); + Py_XDECREF(mask); + Py_XDECREF(stepval); +#endif + if (unlikely(ret)) + return (int16_t) -1; + return val; + } +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to int16_t"); + return (int16_t) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to int16_t"); + return (int16_t) -1; +} + +/* CIntFromPy */ +static CYTHON_INLINE int64_t __Pyx_PyLong_As_int64_t(PyObject *x) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const int64_t neg_one = (int64_t) -1, const_zero = (int64_t) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (unlikely(!PyLong_Check(x))) { + int64_t val; + PyObject *tmp = __Pyx_PyNumber_Long(x); + if (!tmp) return (int64_t) -1; + val = __Pyx_PyLong_As_int64_t(tmp); + Py_DECREF(tmp); + return val; + } + if (is_unsigned) { +#if CYTHON_USE_PYLONG_INTERNALS + if (unlikely(__Pyx_PyLong_IsNeg(x))) { + goto raise_neg_overflow; + } else if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(int64_t, __Pyx_compact_upylong, __Pyx_PyLong_CompactValueUnsigned(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_DigitCount(x)) { + case 2: + if ((8 * sizeof(int64_t) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int64_t, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int64_t) >= 2 * PyLong_SHIFT)) { + return (int64_t) (((((int64_t)digits[1]) << PyLong_SHIFT) | (int64_t)digits[0])); + } + } + break; + case 3: + if ((8 * sizeof(int64_t) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int64_t, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int64_t) >= 3 * PyLong_SHIFT)) { + return (int64_t) (((((((int64_t)digits[2]) << PyLong_SHIFT) | (int64_t)digits[1]) << PyLong_SHIFT) | (int64_t)digits[0])); + } + } + break; + case 4: + if ((8 * sizeof(int64_t) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int64_t, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int64_t) >= 4 * PyLong_SHIFT)) { + return (int64_t) (((((((((int64_t)digits[3]) << PyLong_SHIFT) | (int64_t)digits[2]) << PyLong_SHIFT) | (int64_t)digits[1]) << PyLong_SHIFT) | (int64_t)digits[0])); + } + } + break; + } + } +#endif +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030C00A7 + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } +#else + { + int result = PyObject_RichCompareBool(x, Py_False, Py_LT); + if (unlikely(result < 0)) + return (int64_t) -1; + if (unlikely(result == 1)) + goto raise_neg_overflow; + } +#endif + if ((sizeof(int64_t) <= sizeof(unsigned long))) { + __PYX_VERIFY_RETURN_INT_EXC(int64_t, unsigned long, PyLong_AsUnsignedLong(x)) + } else if ((sizeof(int64_t) <= sizeof(unsigned PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(int64_t, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) + } + } else { +#if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(int64_t, __Pyx_compact_pylong, __Pyx_PyLong_CompactValue(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_SignedDigitCount(x)) { + case -2: + if ((8 * sizeof(int64_t) - 1 > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int64_t, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int64_t) - 1 > 2 * PyLong_SHIFT)) { + return (int64_t) (((int64_t)-1)*(((((int64_t)digits[1]) << PyLong_SHIFT) | (int64_t)digits[0]))); + } + } + break; + case 2: + if ((8 * sizeof(int64_t) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int64_t, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int64_t) - 1 > 2 * PyLong_SHIFT)) { + return (int64_t) ((((((int64_t)digits[1]) << PyLong_SHIFT) | (int64_t)digits[0]))); + } + } + break; + case -3: + if ((8 * sizeof(int64_t) - 1 > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int64_t, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int64_t) - 1 > 3 * PyLong_SHIFT)) { + return (int64_t) (((int64_t)-1)*(((((((int64_t)digits[2]) << PyLong_SHIFT) | (int64_t)digits[1]) << PyLong_SHIFT) | (int64_t)digits[0]))); + } + } + break; + case 3: + if ((8 * sizeof(int64_t) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int64_t, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int64_t) - 1 > 3 * PyLong_SHIFT)) { + return (int64_t) ((((((((int64_t)digits[2]) << PyLong_SHIFT) | (int64_t)digits[1]) << PyLong_SHIFT) | (int64_t)digits[0]))); + } + } + break; + case -4: + if ((8 * sizeof(int64_t) - 1 > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int64_t, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int64_t) - 1 > 4 * PyLong_SHIFT)) { + return (int64_t) (((int64_t)-1)*(((((((((int64_t)digits[3]) << PyLong_SHIFT) | (int64_t)digits[2]) << PyLong_SHIFT) | (int64_t)digits[1]) << PyLong_SHIFT) | (int64_t)digits[0]))); + } + } + break; + case 4: + if ((8 * sizeof(int64_t) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int64_t, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int64_t) - 1 > 4 * PyLong_SHIFT)) { + return (int64_t) ((((((((((int64_t)digits[3]) << PyLong_SHIFT) | (int64_t)digits[2]) << PyLong_SHIFT) | (int64_t)digits[1]) << PyLong_SHIFT) | (int64_t)digits[0]))); + } + } + break; + } + } +#endif + if ((sizeof(int64_t) <= sizeof(long))) { + __PYX_VERIFY_RETURN_INT_EXC(int64_t, long, PyLong_AsLong(x)) + } else if ((sizeof(int64_t) <= sizeof(PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(int64_t, PY_LONG_LONG, PyLong_AsLongLong(x)) + } + } + { + int64_t val; + int ret = -1; +#if PY_VERSION_HEX >= 0x030d00A6 && !CYTHON_COMPILING_IN_LIMITED_API + Py_ssize_t bytes_copied = PyLong_AsNativeBytes( + x, &val, sizeof(val), Py_ASNATIVEBYTES_NATIVE_ENDIAN | (is_unsigned ? Py_ASNATIVEBYTES_UNSIGNED_BUFFER | Py_ASNATIVEBYTES_REJECT_NEGATIVE : 0)); + if (unlikely(bytes_copied == -1)) { + } else if (unlikely(bytes_copied > (Py_ssize_t) sizeof(val))) { + goto raise_overflow; + } else { + ret = 0; + } +#elif PY_VERSION_HEX < 0x030d0000 && !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API) || defined(_PyLong_AsByteArray) + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + ret = _PyLong_AsByteArray((PyLongObject *)x, + bytes, sizeof(val), + is_little, !is_unsigned); +#else + PyObject *v; + PyObject *stepval = NULL, *mask = NULL, *shift = NULL; + int bits, remaining_bits, is_negative = 0; + int chunk_size = (sizeof(long) < 8) ? 30 : 62; + if (likely(PyLong_CheckExact(x))) { + v = __Pyx_NewRef(x); + } else { + v = PyNumber_Long(x); + if (unlikely(!v)) return (int64_t) -1; + assert(PyLong_CheckExact(v)); + } + { + int result = PyObject_RichCompareBool(v, Py_False, Py_LT); + if (unlikely(result < 0)) { + Py_DECREF(v); + return (int64_t) -1; + } + is_negative = result == 1; + } + if (is_unsigned && unlikely(is_negative)) { + Py_DECREF(v); + goto raise_neg_overflow; + } else if (is_negative) { + stepval = PyNumber_Invert(v); + Py_DECREF(v); + if (unlikely(!stepval)) + return (int64_t) -1; + } else { + stepval = v; + } + v = NULL; + val = (int64_t) 0; + mask = PyLong_FromLong((1L << chunk_size) - 1); if (unlikely(!mask)) goto done; + shift = PyLong_FromLong(chunk_size); if (unlikely(!shift)) goto done; + for (bits = 0; bits < (int) sizeof(int64_t) * 8 - chunk_size; bits += chunk_size) { + PyObject *tmp, *digit; + long idigit; + digit = PyNumber_And(stepval, mask); + if (unlikely(!digit)) goto done; + idigit = PyLong_AsLong(digit); + Py_DECREF(digit); + if (unlikely(idigit < 0)) goto done; + val |= ((int64_t) idigit) << bits; + tmp = PyNumber_Rshift(stepval, shift); + if (unlikely(!tmp)) goto done; + Py_DECREF(stepval); stepval = tmp; + } + Py_DECREF(shift); shift = NULL; + Py_DECREF(mask); mask = NULL; + { + long idigit = PyLong_AsLong(stepval); + if (unlikely(idigit < 0)) goto done; + remaining_bits = ((int) sizeof(int64_t) * 8) - bits - (is_unsigned ? 0 : 1); + if (unlikely(idigit >= (1L << remaining_bits))) + goto raise_overflow; + val |= ((int64_t) idigit) << bits; + } + if (!is_unsigned) { + if (unlikely(val & (((int64_t) 1) << (sizeof(int64_t) * 8 - 1)))) + goto raise_overflow; + if (is_negative) + val = ~val; + } + ret = 0; + done: + Py_XDECREF(shift); + Py_XDECREF(mask); + Py_XDECREF(stepval); +#endif + if (unlikely(ret)) + return (int64_t) -1; + return val; + } +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to int64_t"); + return (int64_t) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to int64_t"); + return (int64_t) -1; +} + +/* PyObjectCallMethod1 */ +#if !(CYTHON_VECTORCALL && (__PYX_LIMITED_VERSION_HEX >= 0x030C0000 || (!CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x03090000))) +static PyObject* __Pyx__PyObject_CallMethod1(PyObject* method, PyObject* arg) { + PyObject *result = __Pyx_PyObject_CallOneArg(method, arg); + Py_DECREF(method); + return result; +} +#endif +static PyObject* __Pyx_PyObject_CallMethod1(PyObject* obj, PyObject* method_name, PyObject* arg) { +#if CYTHON_VECTORCALL && (__PYX_LIMITED_VERSION_HEX >= 0x030C0000 || (!CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x03090000)) + PyObject *args[2] = {obj, arg}; + (void) __Pyx_PyObject_CallOneArg; + (void) __Pyx_PyObject_Call2Args; + return PyObject_VectorcallMethod(method_name, args, 2 | PY_VECTORCALL_ARGUMENTS_OFFSET, NULL); +#else + PyObject *method = NULL, *result; + int is_method = __Pyx_PyObject_GetMethod(obj, method_name, &method); + if (likely(is_method)) { + result = __Pyx_PyObject_Call2Args(method, obj, arg); + Py_DECREF(method); + return result; + } + if (unlikely(!method)) return NULL; + return __Pyx__PyObject_CallMethod1(method, arg); +#endif +} + +/* UpdateUnpickledDict */ +static int __Pyx__UpdateUnpickledDict(PyObject *obj, PyObject *state, Py_ssize_t index) { + PyObject *state_dict = __Pyx_PySequence_ITEM(state, index); + if (unlikely(!state_dict)) { + return -1; + } + int non_empty = PyObject_IsTrue(state_dict); + if (non_empty == 0) { + Py_DECREF(state_dict); + return 0; + } else if (unlikely(non_empty == -1)) { + return -1; + } + PyObject *dict; + #if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000 + dict = PyObject_GetAttrString(obj, "__dict__"); + #else + dict = PyObject_GenericGetDict(obj, NULL); + #endif + if (unlikely(!dict)) { + Py_DECREF(state_dict); + return -1; + } + int result; + if (likely(PyDict_CheckExact(dict))) { + result = PyDict_Update(dict, state_dict); + } else { + PyObject *obj_result = __Pyx_PyObject_CallMethod1(dict, __pyx_mstate_global->__pyx_n_u_update, state_dict); + if (likely(obj_result)) { + Py_DECREF(obj_result); + result = 0; + } else { + result = -1; + } + } + Py_DECREF(state_dict); + Py_DECREF(dict); + return result; +} +static int __Pyx_UpdateUnpickledDict(PyObject *obj, PyObject *state, Py_ssize_t index) { + Py_ssize_t state_size = __Pyx_PyTuple_GET_SIZE(state); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(state_size == -1)) return -1; + #endif + if (state_size <= index) { + return 0; + } + return __Pyx__UpdateUnpickledDict(obj, state, index); +} + +/* FormatTypeName */ +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030d0000 +static __Pyx_TypeName +__Pyx_PyType_GetFullyQualifiedName(PyTypeObject* tp) +{ + PyObject *module = NULL, *name = NULL, *result = NULL; + #if __PYX_LIMITED_VERSION_HEX < 0x030b0000 + name = __Pyx_PyObject_GetAttrStr((PyObject *)tp, + __pyx_mstate_global->__pyx_n_u_qualname); + #else + name = PyType_GetQualName(tp); + #endif + if (unlikely(name == NULL) || unlikely(!PyUnicode_Check(name))) goto bad; + module = __Pyx_PyObject_GetAttrStr((PyObject *)tp, + __pyx_mstate_global->__pyx_n_u_module); + if (unlikely(module == NULL) || unlikely(!PyUnicode_Check(module))) goto bad; + if (PyUnicode_CompareWithASCIIString(module, "builtins") == 0) { + result = name; + name = NULL; + goto done; + } + result = PyUnicode_FromFormat("%U.%U", module, name); + if (unlikely(result == NULL)) goto bad; + done: + Py_XDECREF(name); + Py_XDECREF(module); + return result; + bad: + PyErr_Clear(); + if (name) { + result = name; + name = NULL; + } else { + result = __Pyx_NewRef(__pyx_mstate_global->__pyx_kp_u__2); + } + goto done; +} +#endif + +/* FastTypeChecks */ +#if CYTHON_COMPILING_IN_CPYTHON +static int __Pyx_InBases(PyTypeObject *a, PyTypeObject *b) { + while (a) { + a = __Pyx_PyType_GetSlot(a, tp_base, PyTypeObject*); + if (a == b) + return 1; + } + return b == &PyBaseObject_Type; +} +static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b) { + PyObject *mro; + if (a == b) return 1; + mro = a->tp_mro; + if (likely(mro)) { + Py_ssize_t i, n; + n = PyTuple_GET_SIZE(mro); + for (i = 0; i < n; i++) { + if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b) + return 1; + } + return 0; + } + return __Pyx_InBases(a, b); +} +static CYTHON_INLINE int __Pyx_IsAnySubtype2(PyTypeObject *cls, PyTypeObject *a, PyTypeObject *b) { + PyObject *mro; + if (cls == a || cls == b) return 1; + mro = cls->tp_mro; + if (likely(mro)) { + Py_ssize_t i, n; + n = PyTuple_GET_SIZE(mro); + for (i = 0; i < n; i++) { + PyObject *base = PyTuple_GET_ITEM(mro, i); + if (base == (PyObject *)a || base == (PyObject *)b) + return 1; + } + return 0; + } + return __Pyx_InBases(cls, a) || __Pyx_InBases(cls, b); +} +static CYTHON_INLINE int __Pyx_inner_PyErr_GivenExceptionMatches2(PyObject *err, PyObject* exc_type1, PyObject *exc_type2) { + if (exc_type1) { + return __Pyx_IsAnySubtype2((PyTypeObject*)err, (PyTypeObject*)exc_type1, (PyTypeObject*)exc_type2); + } else { + return __Pyx_IsSubtype((PyTypeObject*)err, (PyTypeObject*)exc_type2); + } +} +static int __Pyx_PyErr_GivenExceptionMatchesTuple(PyObject *exc_type, PyObject *tuple) { + Py_ssize_t i, n; + assert(PyExceptionClass_Check(exc_type)); + n = PyTuple_GET_SIZE(tuple); + for (i=0; i>= 8; + ++i; + } + __Pyx_cached_runtime_version = version; + } +} +#endif +static unsigned long __Pyx_get_runtime_version(void) { +#if __PYX_LIMITED_VERSION_HEX >= 0x030b0000 + return Py_Version & ~0xFFUL; +#else + return __Pyx_cached_runtime_version; +#endif +} + +/* CheckBinaryVersion */ +static int __Pyx_check_binary_version(unsigned long ct_version, unsigned long rt_version, int allow_newer) { + const unsigned long MAJOR_MINOR = 0xFFFF0000UL; + if ((rt_version & MAJOR_MINOR) == (ct_version & MAJOR_MINOR)) + return 0; + if (likely(allow_newer && (rt_version & MAJOR_MINOR) > (ct_version & MAJOR_MINOR))) + return 1; + { + char message[200]; + PyOS_snprintf(message, sizeof(message), + "compile time Python version %d.%d " + "of module '%.100s' " + "%s " + "runtime version %d.%d", + (int) (ct_version >> 24), (int) ((ct_version >> 16) & 0xFF), + __Pyx_MODULE_NAME, + (allow_newer) ? "was newer than" : "does not match", + (int) (rt_version >> 24), (int) ((rt_version >> 16) & 0xFF) + ); + return PyErr_WarnEx(NULL, message, 1); + } +} + +/* NewCodeObj */ +#if CYTHON_COMPILING_IN_LIMITED_API + static PyObject* __Pyx__PyCode_New(int a, int p, int k, int l, int s, int f, + PyObject *code, PyObject *c, PyObject* n, PyObject *v, + PyObject *fv, PyObject *cell, PyObject* fn, + PyObject *name, int fline, PyObject *lnos) { + PyObject *exception_table = NULL; + PyObject *types_module=NULL, *code_type=NULL, *result=NULL; + #if __PYX_LIMITED_VERSION_HEX < 0x030b0000 + PyObject *version_info; + PyObject *py_minor_version = NULL; + #endif + long minor_version = 0; + PyObject *type, *value, *traceback; + PyErr_Fetch(&type, &value, &traceback); + #if __PYX_LIMITED_VERSION_HEX >= 0x030b0000 + minor_version = 11; + #else + if (!(version_info = PySys_GetObject("version_info"))) goto end; + if (!(py_minor_version = PySequence_GetItem(version_info, 1))) goto end; + minor_version = PyLong_AsLong(py_minor_version); + Py_DECREF(py_minor_version); + if (minor_version == -1 && PyErr_Occurred()) goto end; + #endif + if (!(types_module = PyImport_ImportModule("types"))) goto end; + if (!(code_type = PyObject_GetAttrString(types_module, "CodeType"))) goto end; + if (minor_version <= 7) { + (void)p; + result = PyObject_CallFunction(code_type, "iiiiiOOOOOOiOOO", a, k, l, s, f, code, + c, n, v, fn, name, fline, lnos, fv, cell); + } else if (minor_version <= 10) { + result = PyObject_CallFunction(code_type, "iiiiiiOOOOOOiOOO", a,p, k, l, s, f, code, + c, n, v, fn, name, fline, lnos, fv, cell); + } else { + if (!(exception_table = PyBytes_FromStringAndSize(NULL, 0))) goto end; + result = PyObject_CallFunction(code_type, "iiiiiiOOOOOOOiOOOO", a,p, k, l, s, f, code, + c, n, v, fn, name, name, fline, lnos, exception_table, fv, cell); + } + end: + Py_XDECREF(code_type); + Py_XDECREF(exception_table); + Py_XDECREF(types_module); + if (type) { + PyErr_Restore(type, value, traceback); + } + return result; + } +#elif PY_VERSION_HEX >= 0x030B0000 + static PyCodeObject* __Pyx__PyCode_New(int a, int p, int k, int l, int s, int f, + PyObject *code, PyObject *c, PyObject* n, PyObject *v, + PyObject *fv, PyObject *cell, PyObject* fn, + PyObject *name, int fline, PyObject *lnos) { + PyCodeObject *result; + result = + #if PY_VERSION_HEX >= 0x030C0000 + PyUnstable_Code_NewWithPosOnlyArgs + #else + PyCode_NewWithPosOnlyArgs + #endif + (a, p, k, l, s, f, code, c, n, v, fv, cell, fn, name, name, fline, lnos, __pyx_mstate_global->__pyx_empty_bytes); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030c00A1 + if (likely(result)) + result->_co_firsttraceable = 0; + #endif + return result; + } +#elif !CYTHON_COMPILING_IN_PYPY + #define __Pyx__PyCode_New(a, p, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ + PyCode_NewWithPosOnlyArgs(a, p, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) +#else + #define __Pyx__PyCode_New(a, p, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ + PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) +#endif +static PyObject* __Pyx_PyCode_New( + const __Pyx_PyCode_New_function_description descr, + PyObject * const *varnames, + PyObject *filename, + PyObject *funcname, + PyObject *line_table, + PyObject *tuple_dedup_map +) { + PyObject *code_obj = NULL, *varnames_tuple_dedup = NULL, *code_bytes = NULL; + Py_ssize_t var_count = (Py_ssize_t) descr.nlocals; + PyObject *varnames_tuple = PyTuple_New(var_count); + if (unlikely(!varnames_tuple)) return NULL; + for (Py_ssize_t i=0; i < var_count; i++) { + Py_INCREF(varnames[i]); + if (__Pyx_PyTuple_SET_ITEM(varnames_tuple, i, varnames[i]) != (0)) goto done; + } + #if CYTHON_COMPILING_IN_LIMITED_API + varnames_tuple_dedup = PyDict_GetItem(tuple_dedup_map, varnames_tuple); + if (!varnames_tuple_dedup) { + if (unlikely(PyDict_SetItem(tuple_dedup_map, varnames_tuple, varnames_tuple) < 0)) goto done; + varnames_tuple_dedup = varnames_tuple; + } + #else + varnames_tuple_dedup = PyDict_SetDefault(tuple_dedup_map, varnames_tuple, varnames_tuple); + if (unlikely(!varnames_tuple_dedup)) goto done; + #endif + #if CYTHON_AVOID_BORROWED_REFS + Py_INCREF(varnames_tuple_dedup); + #endif + if (__PYX_LIMITED_VERSION_HEX >= (0x030b0000) && line_table != NULL && !CYTHON_COMPILING_IN_GRAAL) { + Py_ssize_t line_table_length = __Pyx_PyBytes_GET_SIZE(line_table); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(line_table_length == -1)) goto done; + #endif + Py_ssize_t code_len = (line_table_length * 2 + 4) & ~3LL; + code_bytes = PyBytes_FromStringAndSize(NULL, code_len); + if (unlikely(!code_bytes)) goto done; + char* c_code_bytes = PyBytes_AsString(code_bytes); + if (unlikely(!c_code_bytes)) goto done; + memset(c_code_bytes, 0, (size_t) code_len); + } + code_obj = (PyObject*) __Pyx__PyCode_New( + (int) descr.argcount, + (int) descr.num_posonly_args, + (int) descr.num_kwonly_args, + (int) descr.nlocals, + 0, + (int) descr.flags, + code_bytes ? code_bytes : __pyx_mstate_global->__pyx_empty_bytes, + __pyx_mstate_global->__pyx_empty_tuple, + __pyx_mstate_global->__pyx_empty_tuple, + varnames_tuple_dedup, + __pyx_mstate_global->__pyx_empty_tuple, + __pyx_mstate_global->__pyx_empty_tuple, + filename, + funcname, + (int) descr.first_line, + (__PYX_LIMITED_VERSION_HEX >= (0x030b0000) && line_table) ? line_table : __pyx_mstate_global->__pyx_empty_bytes + ); +done: + Py_XDECREF(code_bytes); + #if CYTHON_AVOID_BORROWED_REFS + Py_XDECREF(varnames_tuple_dedup); + #endif + Py_DECREF(varnames_tuple); + return code_obj; +} + +/* DecompressString */ +static PyObject *__Pyx_DecompressString(const char *s, Py_ssize_t length, int algo) { + PyObject *module = NULL, *decompress, *compressed_bytes, *decompressed; + const char* module_name = algo == 3 ? "compression.zstd" : algo == 2 ? "bz2" : "zlib"; + PyObject *methodname = PyUnicode_FromString("decompress"); + if (unlikely(!methodname)) return NULL; + #if __PYX_LIMITED_VERSION_HEX >= 0x030e0000 + if (algo == 3) { + PyObject *fromlist = Py_BuildValue("[O]", methodname); + if (unlikely(!fromlist)) goto bad; + module = PyImport_ImportModuleLevel("compression.zstd", NULL, NULL, fromlist, 0); + Py_DECREF(fromlist); + } else + #endif + module = PyImport_ImportModule(module_name); + if (unlikely(!module)) goto import_failed; + decompress = PyObject_GetAttr(module, methodname); + if (unlikely(!decompress)) goto import_failed; + { + #ifdef __cplusplus + char *memview_bytes = const_cast(s); + #else + #if defined(__clang__) + #pragma clang diagnostic push + #pragma clang diagnostic ignored "-Wcast-qual" + #elif !defined(__INTEL_COMPILER) && defined(__GNUC__) + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wcast-qual" + #endif + char *memview_bytes = (char*) s; + #if defined(__clang__) + #pragma clang diagnostic pop + #elif !defined(__INTEL_COMPILER) && defined(__GNUC__) + #pragma GCC diagnostic pop + #endif + #endif + #if CYTHON_COMPILING_IN_LIMITED_API && !defined(PyBUF_READ) + int memview_flags = 0x100; + #else + int memview_flags = PyBUF_READ; + #endif + compressed_bytes = PyMemoryView_FromMemory(memview_bytes, length, memview_flags); + } + if (unlikely(!compressed_bytes)) { + Py_DECREF(decompress); + goto bad; + } + decompressed = PyObject_CallFunctionObjArgs(decompress, compressed_bytes, NULL); + Py_DECREF(compressed_bytes); + Py_DECREF(decompress); + Py_DECREF(module); + Py_DECREF(methodname); + return decompressed; +import_failed: + PyErr_Format(PyExc_ImportError, + "Failed to import '%.20s.decompress' - cannot initialise module strings. " + "String compression was configured with the C macro 'CYTHON_COMPRESS_STRINGS=%d'.", + module_name, algo); +bad: + Py_XDECREF(module); + Py_DECREF(methodname); + return NULL; +} + +#include +static CYTHON_INLINE Py_ssize_t __Pyx_ssize_strlen(const char *s) { + size_t len = strlen(s); + if (unlikely(len > (size_t) PY_SSIZE_T_MAX)) { + PyErr_SetString(PyExc_OverflowError, "byte string is too long"); + return -1; + } + return (Py_ssize_t) len; +} +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char* c_str) { + Py_ssize_t len = __Pyx_ssize_strlen(c_str); + if (unlikely(len < 0)) return NULL; + return __Pyx_PyUnicode_FromStringAndSize(c_str, len); +} +static CYTHON_INLINE PyObject* __Pyx_PyByteArray_FromString(const char* c_str) { + Py_ssize_t len = __Pyx_ssize_strlen(c_str); + if (unlikely(len < 0)) return NULL; + return PyByteArray_FromStringAndSize(c_str, len); +} +static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject* o) { + Py_ssize_t ignore; + return __Pyx_PyObject_AsStringAndSize(o, &ignore); +} +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 +static CYTHON_INLINE const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *length) { + if (unlikely(__Pyx_PyUnicode_READY(o) == -1)) return NULL; +#if CYTHON_COMPILING_IN_LIMITED_API + { + const char* result; + Py_ssize_t unicode_length; + CYTHON_MAYBE_UNUSED_VAR(unicode_length); // only for __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + #if __PYX_LIMITED_VERSION_HEX < 0x030A0000 + if (unlikely(PyArg_Parse(o, "s#", &result, length) < 0)) return NULL; + #else + result = PyUnicode_AsUTF8AndSize(o, length); + #endif + #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + unicode_length = PyUnicode_GetLength(o); + if (unlikely(unicode_length < 0)) return NULL; + if (unlikely(unicode_length != *length)) { + PyUnicode_AsASCIIString(o); + return NULL; + } + #endif + return result; + } +#else +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + if (likely(PyUnicode_IS_ASCII(o))) { + *length = PyUnicode_GET_LENGTH(o); + return PyUnicode_AsUTF8(o); + } else { + PyUnicode_AsASCIIString(o); + return NULL; + } +#else + return PyUnicode_AsUTF8AndSize(o, length); +#endif +#endif +} +#endif +static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 + if (PyUnicode_Check(o)) { + return __Pyx_PyUnicode_AsStringAndSize(o, length); + } else +#endif + if (PyByteArray_Check(o)) { +#if (CYTHON_ASSUME_SAFE_SIZE && CYTHON_ASSUME_SAFE_MACROS) || (CYTHON_COMPILING_IN_PYPY && (defined(PyByteArray_AS_STRING) && defined(PyByteArray_GET_SIZE))) + *length = PyByteArray_GET_SIZE(o); + return PyByteArray_AS_STRING(o); +#else + *length = PyByteArray_Size(o); + if (*length == -1) return NULL; + return PyByteArray_AsString(o); +#endif + } else + { + char* result; + int r = PyBytes_AsStringAndSize(o, &result, length); + if (unlikely(r < 0)) { + return NULL; + } else { + return result; + } + } +} +static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { + int is_true = x == Py_True; + if (is_true | (x == Py_False) | (x == Py_None)) return is_true; + else return PyObject_IsTrue(x); +} +static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject* x) { + int retval; + if (unlikely(!x)) return -1; + retval = __Pyx_PyObject_IsTrue(x); + Py_DECREF(x); + return retval; +} +static PyObject* __Pyx_PyNumber_LongWrongResultType(PyObject* result) { + __Pyx_TypeName result_type_name = __Pyx_PyType_GetFullyQualifiedName(Py_TYPE(result)); + if (PyLong_Check(result)) { + if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1, + "__int__ returned non-int (type " __Pyx_FMT_TYPENAME "). " + "The ability to return an instance of a strict subclass of int is deprecated, " + "and may be removed in a future version of Python.", + result_type_name)) { + __Pyx_DECREF_TypeName(result_type_name); + Py_DECREF(result); + return NULL; + } + __Pyx_DECREF_TypeName(result_type_name); + return result; + } + PyErr_Format(PyExc_TypeError, + "__int__ returned non-int (type " __Pyx_FMT_TYPENAME ")", + result_type_name); + __Pyx_DECREF_TypeName(result_type_name); + Py_DECREF(result); + return NULL; +} +static CYTHON_INLINE PyObject* __Pyx_PyNumber_Long(PyObject* x) { +#if CYTHON_USE_TYPE_SLOTS + PyNumberMethods *m; +#endif + PyObject *res = NULL; + if (likely(PyLong_Check(x))) + return __Pyx_NewRef(x); +#if CYTHON_USE_TYPE_SLOTS + m = Py_TYPE(x)->tp_as_number; + if (likely(m && m->nb_int)) { + res = m->nb_int(x); + } +#else + if (!PyBytes_CheckExact(x) && !PyUnicode_CheckExact(x)) { + res = PyNumber_Long(x); + } +#endif + if (likely(res)) { + if (unlikely(!PyLong_CheckExact(res))) { + return __Pyx_PyNumber_LongWrongResultType(res); + } + } + else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_TypeError, + "an integer is required"); + } + return res; +} +static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { + Py_ssize_t ival; + PyObject *x; + if (likely(PyLong_CheckExact(b))) { + #if CYTHON_USE_PYLONG_INTERNALS + if (likely(__Pyx_PyLong_IsCompact(b))) { + return __Pyx_PyLong_CompactValue(b); + } else { + const digit* digits = __Pyx_PyLong_Digits(b); + const Py_ssize_t size = __Pyx_PyLong_SignedDigitCount(b); + switch (size) { + case 2: + if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { + return (Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case -2: + if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { + return -(Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case 3: + if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { + return (Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case -3: + if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { + return -(Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case 4: + if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { + return (Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case -4: + if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { + return -(Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + } + } + #endif + return PyLong_AsSsize_t(b); + } + x = PyNumber_Index(b); + if (!x) return -1; + ival = PyLong_AsSsize_t(x); + Py_DECREF(x); + return ival; +} +static CYTHON_INLINE Py_hash_t __Pyx_PyIndex_AsHash_t(PyObject* o) { + if (sizeof(Py_hash_t) == sizeof(Py_ssize_t)) { + return (Py_hash_t) __Pyx_PyIndex_AsSsize_t(o); + } else { + Py_ssize_t ival; + PyObject *x; + x = PyNumber_Index(o); + if (!x) return -1; + ival = PyLong_AsLong(x); + Py_DECREF(x); + return ival; + } +} +static CYTHON_INLINE PyObject *__Pyx_Owned_Py_None(int b) { + CYTHON_UNUSED_VAR(b); + return __Pyx_NewRef(Py_None); +} +static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b) { + return __Pyx_NewRef(b ? Py_True: Py_False); +} +static CYTHON_INLINE PyObject * __Pyx_PyLong_FromSize_t(size_t ival) { + return PyLong_FromSize_t(ival); +} + + +/* MultiPhaseInitModuleState */ +#if CYTHON_PEP489_MULTI_PHASE_INIT && CYTHON_USE_MODULE_STATE +#ifndef CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE +#if (CYTHON_COMPILING_IN_LIMITED_API || PY_VERSION_HEX >= 0x030C0000) + #define CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE 1 +#else + #define CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE 0 +#endif +#endif +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE && !CYTHON_ATOMICS +#error "Module state with PEP489 requires atomics. Currently that's one of\ + C11, C++11, gcc atomic intrinsics or MSVC atomic intrinsics" +#endif +#if !CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE +#define __Pyx_ModuleStateLookup_Lock() +#define __Pyx_ModuleStateLookup_Unlock() +#elif !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d0000 +static PyMutex __Pyx_ModuleStateLookup_mutex = {0}; +#define __Pyx_ModuleStateLookup_Lock() PyMutex_Lock(&__Pyx_ModuleStateLookup_mutex) +#define __Pyx_ModuleStateLookup_Unlock() PyMutex_Unlock(&__Pyx_ModuleStateLookup_mutex) +#elif defined(__cplusplus) && __cplusplus >= 201103L +#include +static std::mutex __Pyx_ModuleStateLookup_mutex; +#define __Pyx_ModuleStateLookup_Lock() __Pyx_ModuleStateLookup_mutex.lock() +#define __Pyx_ModuleStateLookup_Unlock() __Pyx_ModuleStateLookup_mutex.unlock() +#elif defined(__STDC_VERSION__) && (__STDC_VERSION__ > 201112L) && !defined(__STDC_NO_THREADS__) +#include +static mtx_t __Pyx_ModuleStateLookup_mutex; +static once_flag __Pyx_ModuleStateLookup_mutex_once_flag = ONCE_FLAG_INIT; +static void __Pyx_ModuleStateLookup_initialize_mutex(void) { + mtx_init(&__Pyx_ModuleStateLookup_mutex, mtx_plain); +} +#define __Pyx_ModuleStateLookup_Lock()\ + call_once(&__Pyx_ModuleStateLookup_mutex_once_flag, __Pyx_ModuleStateLookup_initialize_mutex);\ + mtx_lock(&__Pyx_ModuleStateLookup_mutex) +#define __Pyx_ModuleStateLookup_Unlock() mtx_unlock(&__Pyx_ModuleStateLookup_mutex) +#elif defined(HAVE_PTHREAD_H) +#include +static pthread_mutex_t __Pyx_ModuleStateLookup_mutex = PTHREAD_MUTEX_INITIALIZER; +#define __Pyx_ModuleStateLookup_Lock() pthread_mutex_lock(&__Pyx_ModuleStateLookup_mutex) +#define __Pyx_ModuleStateLookup_Unlock() pthread_mutex_unlock(&__Pyx_ModuleStateLookup_mutex) +#elif defined(_WIN32) +#include // synchapi.h on its own doesn't work +static SRWLOCK __Pyx_ModuleStateLookup_mutex = SRWLOCK_INIT; +#define __Pyx_ModuleStateLookup_Lock() AcquireSRWLockExclusive(&__Pyx_ModuleStateLookup_mutex) +#define __Pyx_ModuleStateLookup_Unlock() ReleaseSRWLockExclusive(&__Pyx_ModuleStateLookup_mutex) +#else +#error "No suitable lock available for CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE.\ + Requires C standard >= C11, or C++ standard >= C++11,\ + or pthreads, or the Windows 32 API, or Python >= 3.13." +#endif +typedef struct { + int64_t id; + PyObject *module; +} __Pyx_InterpreterIdAndModule; +typedef struct { + char interpreter_id_as_index; + Py_ssize_t count; + Py_ssize_t allocated; + __Pyx_InterpreterIdAndModule table[1]; +} __Pyx_ModuleStateLookupData; +#define __PYX_MODULE_STATE_LOOKUP_SMALL_SIZE 32 +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE +static __pyx_atomic_int_type __Pyx_ModuleStateLookup_read_counter = 0; +#endif +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE +static __pyx_atomic_ptr_type __Pyx_ModuleStateLookup_data = 0; +#else +static __Pyx_ModuleStateLookupData* __Pyx_ModuleStateLookup_data = NULL; +#endif +static __Pyx_InterpreterIdAndModule* __Pyx_State_FindModuleStateLookupTableLowerBound( + __Pyx_InterpreterIdAndModule* table, + Py_ssize_t count, + int64_t interpreterId) { + __Pyx_InterpreterIdAndModule* begin = table; + __Pyx_InterpreterIdAndModule* end = begin + count; + if (begin->id == interpreterId) { + return begin; + } + while ((end - begin) > __PYX_MODULE_STATE_LOOKUP_SMALL_SIZE) { + __Pyx_InterpreterIdAndModule* halfway = begin + (end - begin)/2; + if (halfway->id == interpreterId) { + return halfway; + } + if (halfway->id < interpreterId) { + begin = halfway; + } else { + end = halfway; + } + } + for (; begin < end; ++begin) { + if (begin->id >= interpreterId) return begin; + } + return begin; +} +static PyObject *__Pyx_State_FindModule(CYTHON_UNUSED void* dummy) { + int64_t interpreter_id = PyInterpreterState_GetID(__Pyx_PyInterpreterState_Get()); + if (interpreter_id == -1) return NULL; +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE + __Pyx_ModuleStateLookupData* data = (__Pyx_ModuleStateLookupData*)__pyx_atomic_pointer_load_relaxed(&__Pyx_ModuleStateLookup_data); + { + __pyx_atomic_incr_acq_rel(&__Pyx_ModuleStateLookup_read_counter); + if (likely(data)) { + __Pyx_ModuleStateLookupData* new_data = (__Pyx_ModuleStateLookupData*)__pyx_atomic_pointer_load_acquire(&__Pyx_ModuleStateLookup_data); + if (likely(data == new_data)) { + goto read_finished; + } + } + __pyx_atomic_decr_acq_rel(&__Pyx_ModuleStateLookup_read_counter); + __Pyx_ModuleStateLookup_Lock(); + __pyx_atomic_incr_relaxed(&__Pyx_ModuleStateLookup_read_counter); + data = (__Pyx_ModuleStateLookupData*)__pyx_atomic_pointer_load_relaxed(&__Pyx_ModuleStateLookup_data); + __Pyx_ModuleStateLookup_Unlock(); + } + read_finished:; +#else + __Pyx_ModuleStateLookupData* data = __Pyx_ModuleStateLookup_data; +#endif + __Pyx_InterpreterIdAndModule* found = NULL; + if (unlikely(!data)) goto end; + if (data->interpreter_id_as_index) { + if (interpreter_id < data->count) { + found = data->table+interpreter_id; + } + } else { + found = __Pyx_State_FindModuleStateLookupTableLowerBound( + data->table, data->count, interpreter_id); + } + end: + { + PyObject *result=NULL; + if (found && found->id == interpreter_id) { + result = found->module; + } +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE + __pyx_atomic_decr_acq_rel(&__Pyx_ModuleStateLookup_read_counter); +#endif + return result; + } +} +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE +static void __Pyx_ModuleStateLookup_wait_until_no_readers(void) { + while (__pyx_atomic_load(&__Pyx_ModuleStateLookup_read_counter) != 0); +} +#else +#define __Pyx_ModuleStateLookup_wait_until_no_readers() +#endif +static int __Pyx_State_AddModuleInterpIdAsIndex(__Pyx_ModuleStateLookupData **old_data, PyObject* module, int64_t interpreter_id) { + Py_ssize_t to_allocate = (*old_data)->allocated; + while (to_allocate <= interpreter_id) { + if (to_allocate == 0) to_allocate = 1; + else to_allocate *= 2; + } + __Pyx_ModuleStateLookupData *new_data = *old_data; + if (to_allocate != (*old_data)->allocated) { + new_data = (__Pyx_ModuleStateLookupData *)realloc( + *old_data, + sizeof(__Pyx_ModuleStateLookupData)+(to_allocate-1)*sizeof(__Pyx_InterpreterIdAndModule)); + if (!new_data) { + PyErr_NoMemory(); + return -1; + } + for (Py_ssize_t i = new_data->allocated; i < to_allocate; ++i) { + new_data->table[i].id = i; + new_data->table[i].module = NULL; + } + new_data->allocated = to_allocate; + } + new_data->table[interpreter_id].module = module; + if (new_data->count < interpreter_id+1) { + new_data->count = interpreter_id+1; + } + *old_data = new_data; + return 0; +} +static void __Pyx_State_ConvertFromInterpIdAsIndex(__Pyx_ModuleStateLookupData *data) { + __Pyx_InterpreterIdAndModule *read = data->table; + __Pyx_InterpreterIdAndModule *write = data->table; + __Pyx_InterpreterIdAndModule *end = read + data->count; + for (; readmodule) { + write->id = read->id; + write->module = read->module; + ++write; + } + } + data->count = write - data->table; + for (; writeid = 0; + write->module = NULL; + } + data->interpreter_id_as_index = 0; +} +static int __Pyx_State_AddModule(PyObject* module, CYTHON_UNUSED void* dummy) { + int64_t interpreter_id = PyInterpreterState_GetID(__Pyx_PyInterpreterState_Get()); + if (interpreter_id == -1) return -1; + int result = 0; + __Pyx_ModuleStateLookup_Lock(); +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE + __Pyx_ModuleStateLookupData *old_data = (__Pyx_ModuleStateLookupData *) + __pyx_atomic_pointer_exchange(&__Pyx_ModuleStateLookup_data, 0); +#else + __Pyx_ModuleStateLookupData *old_data = __Pyx_ModuleStateLookup_data; +#endif + __Pyx_ModuleStateLookupData *new_data = old_data; + if (!new_data) { + new_data = (__Pyx_ModuleStateLookupData *)calloc(1, sizeof(__Pyx_ModuleStateLookupData)); + if (!new_data) { + result = -1; + PyErr_NoMemory(); + goto end; + } + new_data->allocated = 1; + new_data->interpreter_id_as_index = 1; + } + __Pyx_ModuleStateLookup_wait_until_no_readers(); + if (new_data->interpreter_id_as_index) { + if (interpreter_id < __PYX_MODULE_STATE_LOOKUP_SMALL_SIZE) { + result = __Pyx_State_AddModuleInterpIdAsIndex(&new_data, module, interpreter_id); + goto end; + } + __Pyx_State_ConvertFromInterpIdAsIndex(new_data); + } + { + Py_ssize_t insert_at = 0; + { + __Pyx_InterpreterIdAndModule* lower_bound = __Pyx_State_FindModuleStateLookupTableLowerBound( + new_data->table, new_data->count, interpreter_id); + assert(lower_bound); + insert_at = lower_bound - new_data->table; + if (unlikely(insert_at < new_data->count && lower_bound->id == interpreter_id)) { + lower_bound->module = module; + goto end; // already in table, nothing more to do + } + } + if (new_data->count+1 >= new_data->allocated) { + Py_ssize_t to_allocate = (new_data->count+1)*2; + new_data = + (__Pyx_ModuleStateLookupData*)realloc( + new_data, + sizeof(__Pyx_ModuleStateLookupData) + + (to_allocate-1)*sizeof(__Pyx_InterpreterIdAndModule)); + if (!new_data) { + result = -1; + new_data = old_data; + PyErr_NoMemory(); + goto end; + } + new_data->allocated = to_allocate; + } + ++new_data->count; + int64_t last_id = interpreter_id; + PyObject *last_module = module; + for (Py_ssize_t i=insert_at; icount; ++i) { + int64_t current_id = new_data->table[i].id; + new_data->table[i].id = last_id; + last_id = current_id; + PyObject *current_module = new_data->table[i].module; + new_data->table[i].module = last_module; + last_module = current_module; + } + } + end: +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE + __pyx_atomic_pointer_exchange(&__Pyx_ModuleStateLookup_data, new_data); +#else + __Pyx_ModuleStateLookup_data = new_data; +#endif + __Pyx_ModuleStateLookup_Unlock(); + return result; +} +static int __Pyx_State_RemoveModule(CYTHON_UNUSED void* dummy) { + int64_t interpreter_id = PyInterpreterState_GetID(__Pyx_PyInterpreterState_Get()); + if (interpreter_id == -1) return -1; + __Pyx_ModuleStateLookup_Lock(); +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE + __Pyx_ModuleStateLookupData *data = (__Pyx_ModuleStateLookupData *) + __pyx_atomic_pointer_exchange(&__Pyx_ModuleStateLookup_data, 0); +#else + __Pyx_ModuleStateLookupData *data = __Pyx_ModuleStateLookup_data; +#endif + if (data->interpreter_id_as_index) { + if (interpreter_id < data->count) { + data->table[interpreter_id].module = NULL; + } + goto done; + } + { + __Pyx_ModuleStateLookup_wait_until_no_readers(); + __Pyx_InterpreterIdAndModule* lower_bound = __Pyx_State_FindModuleStateLookupTableLowerBound( + data->table, data->count, interpreter_id); + if (!lower_bound) goto done; + if (lower_bound->id != interpreter_id) goto done; + __Pyx_InterpreterIdAndModule *end = data->table+data->count; + for (;lower_boundid = (lower_bound+1)->id; + lower_bound->module = (lower_bound+1)->module; + } + } + --data->count; + if (data->count == 0) { + free(data); + data = NULL; + } + done: +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE + __pyx_atomic_pointer_exchange(&__Pyx_ModuleStateLookup_data, data); +#else + __Pyx_ModuleStateLookup_data = data; +#endif + __Pyx_ModuleStateLookup_Unlock(); + return 0; +} +#endif + +/* #### Code section: utility_code_pragmas_end ### */ +#ifdef _MSC_VER +#pragma warning( pop ) +#endif + + + +/* #### Code section: end ### */ +#endif /* Py_PYTHON_H */ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/protocol/cybin/cybin.pyx b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/protocol/cybin/cybin.pyx new file mode 100644 index 0000000000000000000000000000000000000000..c122ec4496dd5d4ee579009c0539a999a6945b01 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/protocol/cybin/cybin.pyx @@ -0,0 +1,542 @@ +# cython: freethreading_compatible = True + +import sys + +from libc.stdlib cimport free, malloc +from libc.stdint cimport int16_t, int32_t, int64_t +from libc.string cimport memcpy +from cpython cimport bool + +import six + +from thriftpy2.thrift import TDecodeException +from thriftpy2.transport.cybase cimport CyTransportBase, STACK_STRING_LEN + +cdef extern from "endian_port.h": + int16_t htobe16(int16_t n) + int32_t htobe32(int32_t n) + int64_t htobe64(int64_t n) + int16_t be16toh(int16_t n) + int32_t be32toh(int32_t n) + int64_t be64toh(int64_t n) + +DEF VERSION_MASK = -65536 +DEF VERSION_1 = -2147418112 +DEF TYPE_MASK = 0x000000ff + +ctypedef enum TType: + T_STOP = 0, + T_VOID = 1, + T_BOOL = 2, + T_BYTE = 3, + T_I08 = 3, + T_I16 = 6, + T_I32 = 8, + T_U64 = 9, + T_I64 = 10, + T_DOUBLE = 4, + T_STRING = 11, + T_UTF7 = 11, + T_NARY = 11 + T_STRUCT = 12, + T_MAP = 13, + T_SET = 14, + T_LIST = 15, + T_UTF8 = 16, + T_UTF16 = 17, + T_BINARY = 18 + +BIN_TYPES = (T_BINARY, T_STRING) + + +class ProtocolError(Exception): + pass + + +cdef inline char read_i08(CyTransportBase buf) except? -1: + cdef char data = 0 + buf.c_read(1, &data) + return data + + +cdef inline int16_t read_i16(CyTransportBase buf) except? -1: + cdef char data[2] + buf.c_read(2, data) + return be16toh((data)[0]) + + +cdef inline int32_t read_i32(CyTransportBase buf) except? -1: + cdef char data[4] + buf.c_read(4, data) + return be32toh((data)[0]) + + +cdef inline int64_t read_i64(CyTransportBase buf) except? -1: + cdef char data[8] + buf.c_read(8, data) + return be64toh((data)[0]) + + +cdef inline int write_i08(CyTransportBase buf, char val) except -1: + buf.c_write(&val, 1) + return 0 + + +cdef inline int write_i16(CyTransportBase buf, int16_t val) except -1: + val = htobe16(val) + buf.c_write((&val), 2) + return 0 + + +cdef inline int write_i32(CyTransportBase buf, int32_t val) except -1: + val = htobe32(val) + buf.c_write((&val), 4) + return 0 + + +cdef inline int write_i64(CyTransportBase buf, int64_t val) except -1: + val = htobe64(val) + buf.c_write((&val), 8) + return 0 + + +cdef inline int write_double(CyTransportBase buf, double val) except -1: + cdef int64_t v + memcpy(&v, &val, 8) + v = htobe64(v) + buf.c_write((&v), 8) + return 0 + + +cdef inline write_list(CyTransportBase buf, object val, spec): + cdef TType e_type + cdef int val_len + + if isinstance(spec, int): + e_type = spec + e_spec = None + else: + e_type = spec[0] + e_spec = spec[1] + + if e_type == T_BINARY: + e_type = T_STRING + + val_len = len(val) + write_i08(buf, e_type) + write_i32(buf, val_len) + + for e_val in val: + c_write_val(buf, e_type, e_val, e_spec) + + +cdef inline write_string(CyTransportBase buf, bytes val): + cdef int val_len = len(val) + write_i32(buf, val_len) + + buf.c_write(val, val_len) + + +cdef inline write_dict(CyTransportBase buf, object val, spec): + cdef int val_len + cdef TType v_type, k_type + + key = spec[0] + if isinstance(key, int): + k_type = key + k_spec = None + else: + k_type = key[0] + k_spec = key[1] + + if k_type == T_BINARY: + k_type = T_STRING + + value = spec[1] + if isinstance(value, int): + v_type = value + v_spec = None + else: + v_type = value[0] + v_spec = value[1] + + if v_type == T_BINARY: + v_type = T_STRING + + val_len = len(val) + + write_i08(buf, k_type) + write_i08(buf, v_type) + write_i32(buf, val_len) + + for k, v in val.items(): + c_write_val(buf, k_type, k, k_spec) + c_write_val(buf, v_type, v, v_spec) + + +cdef inline read_struct(CyTransportBase buf, obj, decode_response=True, + strict_decode=False): + cdef dict field_specs = obj.thrift_spec + cdef int fid + cdef TType field_type, ttype + cdef tuple field_spec + cdef str name + + while True: + field_type = read_i08(buf) + if field_type == T_STOP: + break + + fid = read_i16(buf) + if fid not in field_specs: + skip(buf, field_type) + continue + + field_spec = field_specs[fid] + ttype = field_spec[0] + if field_type != ttype and not (ttype in BIN_TYPES and field_type in BIN_TYPES): + skip(buf, field_type) + continue + + name = field_spec[1] + if len(field_spec) <= 3: + spec = None + else: + spec = field_spec[2] + + setattr(obj, name, c_read_val(buf, ttype, spec, decode_response, + strict_decode)) + + return obj + + +cdef inline write_struct(CyTransportBase buf, obj): + cdef int fid + cdef TType f_type + cdef dict thrift_spec = obj.thrift_spec + cdef tuple field_spec + cdef str f_name + + for fid, field_spec in thrift_spec.items(): + f_type = field_spec[0] + f_name = field_spec[1] + if len(field_spec) <= 3: + container_spec = None + else: + container_spec = field_spec[2] + + v = getattr(obj, f_name, None) + if v is None: + continue + if f_type == T_BINARY: + write_i08(buf, T_STRING) + else: + write_i08(buf, f_type) + write_i16(buf, fid) + try: + c_write_val(buf, f_type, v, container_spec) + except (TypeError, AttributeError, AssertionError, OverflowError) as e: + raise TDecodeException(obj.__class__.__name__, fid, f_name, v, + f_type, container_spec) + + write_i08(buf, T_STOP) + + +cdef inline c_read_binary(CyTransportBase buf, int32_t size): + cdef char string_val[STACK_STRING_LEN] + + if size > STACK_STRING_LEN: + data = malloc(size) + try: + buf.c_read(size, data) + py_data = data[:size] + finally: + free(data) + else: + buf.c_read(size, string_val) + py_data = string_val[:size] + + return py_data + + +cdef inline c_read_string(CyTransportBase buf, int32_t size, + strict_decode=False): + py_data = c_read_binary(buf, size) + try: + return (py_data)[:size].decode("utf-8") + except: # noqa + if strict_decode: + raise + return py_data + + +cdef c_read_val(CyTransportBase buf, TType ttype, spec=None, + decode_response=True, strict_decode=False): + cdef int size + cdef int64_t n + cdef TType v_type, k_type, orig_type, orig_key_type + cdef double double_value + + if ttype == T_BOOL: + return read_i08(buf) + + elif ttype == T_I08: + return read_i08(buf) + + elif ttype == T_I16: + return read_i16(buf) + + elif ttype == T_I32: + return read_i32(buf) + + elif ttype == T_I64: + return read_i64(buf) + + elif ttype == T_DOUBLE: + n = read_i64(buf) + memcpy(&double_value, &n, 8) + return double_value + + elif ttype == T_BINARY: + size = read_i32(buf) + return c_read_binary(buf, size) + + elif ttype == T_STRING: + size = read_i32(buf) + if decode_response: + return c_read_string(buf, size, strict_decode) + else: + return c_read_binary(buf, size) + + elif ttype == T_SET or ttype == T_LIST: + if isinstance(spec, int): + v_type = spec + v_spec = None + else: + v_type = spec[0] + v_spec = spec[1] + + orig_type = read_i08(buf) + size = read_i32(buf) + + if orig_type != v_type and not (orig_type in BIN_TYPES and v_type in BIN_TYPES): + for _ in range(size): + skip(buf, orig_type) + return [] + + return [c_read_val(buf, v_type, v_spec, decode_response, strict_decode) + for _ in range(size)] + + elif ttype == T_MAP: + key = spec[0] + if isinstance(key, int): + k_type = key + k_spec = None + else: + k_type = key[0] + k_spec = key[1] + + value = spec[1] + if isinstance(value, int): + v_type = value + v_spec = None + else: + v_type = value[0] + v_spec = value[1] + + orig_key_type = read_i08(buf) + orig_type = read_i08(buf) + size = read_i32(buf) + if orig_key_type in BIN_TYPES: + orig_key_type = k_type + if orig_type in BIN_TYPES: + orig_type = v_type + if orig_key_type != k_type or orig_type != v_type: + for _ in range(size): + skip(buf, orig_key_type) + skip(buf, orig_type) + return {} + + return { + c_read_val(buf, k_type, k_spec, decode_response, strict_decode): + c_read_val(buf, v_type, v_spec, decode_response, strict_decode) + for _ in range(size) + } + + elif ttype == T_STRUCT: + return read_struct(buf, spec(), decode_response, strict_decode) + + +cdef c_write_val(CyTransportBase buf, TType ttype, val, spec=None): + if ttype == T_BOOL: + write_i08(buf, 1 if val else 0) + + elif ttype == T_I08: + write_i08(buf, val) + + elif ttype == T_I16: + write_i16(buf, val) + + elif ttype == T_I32: + write_i32(buf, val) + + elif ttype == T_I64: + write_i64(buf, val) + + elif ttype == T_DOUBLE: + write_double(buf, val) + + elif ttype == T_BINARY: + if isinstance(val, six.string_types) and sys.version_info[0] > 2: + val = val.encode() + write_string(buf, val) + + elif ttype == T_STRING: + if not isinstance(val, six.binary_type): + try: + val = val.encode("utf-8") + except Exception: + pass + write_string(buf, val) + + elif ttype == T_SET or ttype == T_LIST: + write_list(buf, val, spec) + + elif ttype == T_MAP: + write_dict(buf, val, spec) + + elif ttype == T_STRUCT: + write_struct(buf, val) + + +cpdef skip(CyTransportBase buf, TType ttype): + cdef TType v_type, k_type, f_type + cdef int size + + if ttype == T_BOOL or ttype == T_I08: + read_i08(buf) + elif ttype == T_I16: + read_i16(buf) + elif ttype == T_I32: + read_i32(buf) + elif ttype == T_I64 or ttype == T_DOUBLE: + read_i64(buf) + elif ttype == T_STRING or ttype == T_BINARY: + size = read_i32(buf) + c_read_binary(buf, size) + elif ttype == T_SET or ttype == T_LIST: + v_type = read_i08(buf) + size = read_i32(buf) + for _ in range(size): + skip(buf, v_type) + elif ttype == T_MAP: + k_type = read_i08(buf) + v_type = read_i08(buf) + size = read_i32(buf) + for _ in range(size): + skip(buf, k_type) + skip(buf, v_type) + elif ttype == T_STRUCT: + while 1: + f_type = read_i08(buf) + if f_type == T_STOP: + break + read_i16(buf) + skip(buf, f_type) + + +def read_val(CyTransportBase buf, TType ttype, decode_response=True, + strict_decode=False): + return c_read_val(buf, ttype, None, decode_response, strict_decode) + + +def write_val(CyTransportBase buf, TType ttype, val, spec=None): + c_write_val(buf, ttype, val, spec) + + +cdef class TCyBinaryProtocol(object): + cdef public CyTransportBase trans + cdef public bool strict_read + cdef public bool strict_write + cdef public bool decode_response + cdef public bool strict_decode + + def __init__(self, trans, strict_read=True, strict_write=True, + decode_response=True, strict_decode=False): + self.trans = trans + self.strict_read = strict_read + self.strict_write = strict_write + self.decode_response = decode_response + self.strict_decode = strict_decode + + def skip(self, ttype): + skip(self.trans, (ttype)) + + def read_message_begin(self): + cdef int32_t size, version, seqid + cdef TType ttype + + size = read_i32(self.trans) + if size < 0: + version = size & VERSION_MASK + if version != VERSION_1: + raise ProtocolError('invalid version %d' % version) + + name = c_read_val(self.trans, T_STRING) + ttype = (size & TYPE_MASK) + else: + if self.strict_read: + raise ProtocolError('No protocol version header') + + name = c_read_string(self.trans, size) + ttype = (read_i08(self.trans)) + + seqid = read_i32(self.trans) + + return name, ttype, seqid + + def read_message_end(self): + pass + + def write_message_begin(self, name, TType ttype, int32_t seqid): + cdef int32_t version = VERSION_1 | ttype + if self.strict_write: + write_i32(self.trans, version) + c_write_val(self.trans, T_STRING, name) + else: + c_write_val(self.trans, T_STRING, name) + write_i08(self.trans, ttype) + + write_i32(self.trans, seqid) + + def write_message_end(self): + pass + + def read_struct(self, obj): + try: + return read_struct(self.trans, obj, self.decode_response, + self.strict_decode) + except Exception: + self.trans.clean() + raise + + def write_struct(self, obj): + try: + write_struct(self.trans, obj) + except Exception: + self.trans.clean() + raise + + +class TCyBinaryProtocolFactory(object): + def __init__(self, strict_read=True, strict_write=True, + decode_response=True, strict_decode=False): + self.strict_read = strict_read + self.strict_write = strict_write + self.decode_response = decode_response + self.strict_decode = strict_decode + + def get_protocol(self, trans): + return TCyBinaryProtocol( + trans, self.strict_read, self.strict_write, self.decode_response, + self.strict_decode) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/protocol/cybin/endian_port.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/protocol/cybin/endian_port.h new file mode 100644 index 0000000000000000000000000000000000000000..9d826d2d80f64b526934e55a1206ae73fb7d6788 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/protocol/cybin/endian_port.h @@ -0,0 +1,172 @@ +// Copied from https://gist.github.com/PkmX/63dd23f28ba885be53a5 + +// "License": Public Domain +// I, Mathias Panzenböck, place this file hereby into the public domain. Use it at your own risk for whatever you like. +// In case there are jurisdictions that don't support putting things in the public domain you can also consider it to +// be "dual licensed" under the BSD, MIT and Apache licenses, if you want to. This code is trivial anyway. Consider it +// an example on how to get the endian conversion functions on different platforms. + +#ifndef PORTABLE_ENDIAN_H__ +#define PORTABLE_ENDIAN_H__ + +#if (defined(_WIN16) || defined(_WIN32) || defined(_WIN64)) && !defined(__WINDOWS__) + +# define __WINDOWS__ + +#endif + +#if defined(__linux__) || defined(__CYGWIN__) + +# include + +#elif defined(__APPLE__) + +# include + +# define htobe16(x) OSSwapHostToBigInt16(x) +# define htole16(x) OSSwapHostToLittleInt16(x) +# define be16toh(x) OSSwapBigToHostInt16(x) +# define le16toh(x) OSSwapLittleToHostInt16(x) + +# define htobe32(x) OSSwapHostToBigInt32(x) +# define htole32(x) OSSwapHostToLittleInt32(x) +# define be32toh(x) OSSwapBigToHostInt32(x) +# define le32toh(x) OSSwapLittleToHostInt32(x) + +# define htobe64(x) OSSwapHostToBigInt64(x) +# define htole64(x) OSSwapHostToLittleInt64(x) +# define be64toh(x) OSSwapBigToHostInt64(x) +# define le64toh(x) OSSwapLittleToHostInt64(x) + +# define __BYTE_ORDER BYTE_ORDER +# define __BIG_ENDIAN BIG_ENDIAN +# define __LITTLE_ENDIAN LITTLE_ENDIAN +# define __PDP_ENDIAN PDP_ENDIAN + +#elif defined(__OpenBSD__) + +# include + +# define __BYTE_ORDER BYTE_ORDER +# define __BIG_ENDIAN BIG_ENDIAN +# define __LITTLE_ENDIAN LITTLE_ENDIAN +# define __PDP_ENDIAN PDP_ENDIAN + +#elif defined(__NetBSD__) || defined(__FreeBSD__) || defined(__DragonFly__) + +# include + +# define be16toh(x) betoh16(x) +# define le16toh(x) letoh16(x) + +# define be32toh(x) betoh32(x) +# define le32toh(x) letoh32(x) + +# define be64toh(x) betoh64(x) +# define le64toh(x) letoh64(x) + +#elif defined(__WINDOWS__) + +# include +# ifdef __GNUC__ +# include +# endif + +# if BYTE_ORDER == LITTLE_ENDIAN + +# define htobe16(x) htons(x) +# define htole16(x) (x) +# define be16toh(x) ntohs(x) +# define le16toh(x) (x) + +# define htobe32(x) htonl(x) +# define htole32(x) (x) +# define be32toh(x) ntohl(x) +# define le32toh(x) (x) + +# define htobe64(x) htonll(x) +# define htole64(x) (x) +# define be64toh(x) ntohll(x) +# define le64toh(x) (x) + +# elif BYTE_ORDER == BIG_ENDIAN + + /* that would be xbox 360 */ +# define htobe16(x) (x) +# define htole16(x) __builtin_bswap16(x) +# define be16toh(x) (x) +# define le16toh(x) __builtin_bswap16(x) + +# define htobe32(x) (x) +# define htole32(x) __builtin_bswap32(x) +# define be32toh(x) (x) +# define le32toh(x) __builtin_bswap32(x) + +# define htobe64(x) (x) +# define htole64(x) __builtin_bswap64(x) +# define be64toh(x) (x) +# define le64toh(x) __builtin_bswap64(x) + +# else + +# error byte order not supported + +# endif + +# define __BYTE_ORDER BYTE_ORDER +# define __BIG_ENDIAN BIG_ENDIAN +# define __LITTLE_ENDIAN LITTLE_ENDIAN +# define __PDP_ENDIAN PDP_ENDIAN + +#elif defined(__QNXNTO__) + +# include + +# define __LITTLE_ENDIAN 1234 +# define __BIG_ENDIAN 4321 +# define __PDP_ENDIAN 3412 + +# if defined(__BIGENDIAN__) + +# define __BYTE_ORDER __BIG_ENDIAN + +# define htobe16(x) (x) +# define htobe32(x) (x) +# define htobe64(x) (x) + +# define htole16(x) ENDIAN_SWAP16(x) +# define htole32(x) ENDIAN_SWAP32(x) +# define htole64(x) ENDIAN_SWAP64(x) + +# elif defined(__LITTLEENDIAN__) + +# define __BYTE_ORDER __LITTLE_ENDIAN + +# define htole16(x) (x) +# define htole32(x) (x) +# define htole64(x) (x) + +# define htobe16(x) ENDIAN_SWAP16(x) +# define htobe32(x) ENDIAN_SWAP32(x) +# define htobe64(x) ENDIAN_SWAP64(x) + +# else + +# error byte order not supported + +# endif + +# define be16toh(x) ENDIAN_BE16(x) +# define be32toh(x) ENDIAN_BE32(x) +# define be64toh(x) ENDIAN_BE64(x) +# define le16toh(x) ENDIAN_LE16(x) +# define le32toh(x) ENDIAN_LE32(x) +# define le64toh(x) ENDIAN_LE64(x) + +#else + +# error platform not supported + +#endif + +#endif diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/protocol/exc.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/protocol/exc.py new file mode 100644 index 0000000000000000000000000000000000000000..9aa37943d58793f0fe1fd320579d152c1df075e0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/protocol/exc.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- + +from __future__ import absolute_import + +from ..thrift import TException + + +class TProtocolException(TException): + """Custom Protocol Exception class""" + + UNKNOWN = 0 + INVALID_DATA = 1 + NEGATIVE_SIZE = 2 + SIZE_LIMIT = 3 + BAD_VERSION = 4 + + def __init__(self, type=UNKNOWN, message=None): + self.type = type + self.message = message + + def __str__(self): + if self.message: + return self.message + + if self.type == self.UNKNOWN: + return 'Unknown protocol exception' + elif self.type == self.INVALID_DATA: + return 'Invalid data' + elif self.type == self.NEGATIVE_SIZE: + return 'Negative size' + elif self.type == self.SIZE_LIMIT: + return 'Size limit' + elif self.type == self.BAD_VERSION: + return 'Bad version' + else: + return 'Default (unknown) TProtocolException' diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/protocol/json.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/protocol/json.py new file mode 100644 index 0000000000000000000000000000000000000000..521882f8f3e1c0dddc8e5ec338a0e7f5d1afa8e5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/protocol/json.py @@ -0,0 +1,246 @@ +# -*- coding: utf-8 -*- + +from __future__ import absolute_import + +import base64 +import json +import struct +import sys +from warnings import warn + +import six + +from thriftpy2.thrift import TType + +from .base import TProtocolBase +from .exc import TProtocolException + +VERSION = 1 + + +def encode_binary(data): + if isinstance(data, six.string_types) and sys.version_info[0] > 2: + data = data.encode() + return base64.b64encode(data).decode('ascii') + + +def json_value(ttype, val, spec=None): + TTYPE_TO_JSONFUNC_MAP = { + TType.BYTE: (int, (val,)), + TType.I16: (int, (val,)), + TType.I32: (int, (val,)), + TType.I64: (int, (val,)), + TType.DOUBLE: (float, (val,)), + TType.STRING: (str, (val,)), + TType.BOOL: (bool, (val,)), + TType.STRUCT: (struct_to_json, (val,)), + TType.SET: (list_to_json, (val, spec)), + TType.LIST: (list_to_json, (val, spec)), + TType.MAP: (map_to_json, (val, spec)), + TType.BINARY: (encode_binary, (val, )), + } + result = TTYPE_TO_JSONFUNC_MAP.get(ttype) + if result: + func, args = result + return func(*args) + raise TProtocolException( + type=TProtocolException.INVALID_DATA, + message=f"Unknown TType {ttype} for JSON serialization" + ) + + +def obj_value(ttype, val, spec=None): + # Special case: since `spec` needs to get called if TType is STRUCT, + # if we initialize inside `TTYPE_TO_OBJFUNC_MAP` it will get called + # everytime the function gets called and incur in exception as + # `TypeError: 'NoneType' object is not callable`. + if ttype == TType.STRUCT: + return struct_to_obj(val, spec()) + else: + TTYPE_TO_OBJFUNC_MAP = { + TType.BYTE: (int, (val,)), + TType.I16: (int, (val,)), + TType.I32: (int, (val,)), + TType.I64: (int, (val,)), + TType.DOUBLE: (float, (val,)), + TType.STRING: (str, (val,)), + TType.BOOL: (bool, (val,)), + TType.SET: (list_to_obj, (val, spec)), + TType.LIST: (list_to_obj, (val, spec)), + TType.MAP: (map_to_obj, (val, spec)), + TType.BINARY: (base64.b64decode, (val, )), + } + result = TTYPE_TO_OBJFUNC_MAP.get(ttype) + if result: + func, args = result + return func(*args) + raise TProtocolException( + type=TProtocolException.INVALID_DATA, + message=f"Unknown TType {ttype} for JSON deserialization" + ) + + +def map_to_obj(val, spec): + res = {} + if isinstance(spec[0], int): + key_type, key_spec = spec[0], None + else: + key_type, key_spec = spec[0] + + if isinstance(spec[1], int): + value_type, value_spec = spec[1], None + else: + value_type, value_spec = spec[1] + + for v in val: + res[obj_value(key_type, v["key"], key_spec)] = obj_value( + value_type, v["value"], value_spec) + + return res + + +def map_to_json(val, spec): + res = [] + if isinstance(spec[0], int): + key_type = spec[0] + key_spec = None + else: + key_type, key_spec = spec[0] + + if isinstance(spec[1], int): + value_type = spec[1] + value_spec = None + else: + value_type, value_spec = spec[1] + + for k, v in val.items(): + res.append({"key": json_value(key_type, k, key_spec), + "value": json_value(value_type, v, value_spec)}) + + return res + + +def list_to_obj(val, spec): + if isinstance(spec, tuple): + elem_type, type_spec = spec + else: + elem_type, type_spec = spec, None + + return [obj_value(elem_type, i, type_spec) for i in val] + + +def list_to_json(val, spec): + if isinstance(spec, tuple): + elem_type, type_spec = spec + else: + elem_type, type_spec = spec, None + + return [json_value(elem_type, i, type_spec) for i in val] + + +def struct_to_json(val): + outobj = {} + for fid, field_spec in val.thrift_spec.items(): + field_type, field_name = field_spec[:2] + + if len(field_spec) <= 3: + field_type_spec = None + else: + field_type_spec = field_spec[2] + + v = getattr(val, field_name) + if v is None: + continue + + outobj[field_name] = json_value(field_type, v, field_type_spec) + + return outobj + + +def struct_to_obj(val, obj): + for fid, field_spec in obj.thrift_spec.items(): + field_type, field_name = field_spec[:2] + + if len(field_spec) <= 3: + field_type_spec = None + else: + field_type_spec = field_spec[2] + + if field_name in val: + setattr(obj, field_name, + obj_value(field_type, val[field_name], field_type_spec)) + + return obj + + +class TJSONProtocol(TProtocolBase): + """A JSON protocol. + + The message in the transport are encoded as this: 4 bytes represents + the length of the json object and immediately followed by the json object. + + '\x00\x00\x00+' '{"payload": {}, "metadata": {"version": 1}}' + + the 4 bytes are the bytes representation of an integer and is encoded in + big-endian. + """ + + def __init__(self, trans): + TProtocolBase.__init__(self, trans) + self._meta = {"version": VERSION} + self._data = None + + def _write_len(self, x): + self.trans.write(struct.pack('!I', int(x))) + + def _read_len(self): + l = self.trans.read(4) + return struct.unpack('!I', l)[0] + + def read_message_begin(self): + size = self._read_len() + self._data = json.loads(self.trans.read(size).decode("utf-8")) + metadata = self._data["metadata"] + + version = int(metadata["version"]) + if version != VERSION: + raise TProtocolException( + type=TProtocolException.BAD_VERSION, + message="Bad version in read_message_begin:{}".format(version)) + + return metadata["name"], metadata["ttype"], metadata["seqid"] + + def read_message_end(self): + pass + + def write_message_begin(self, name, ttype, seqid): + self._meta.update({"name": name, "ttype": ttype, "seqid": seqid}) + + def write_message_end(self): + pass + + def read_struct(self, obj): + if not self._data: + size = self._read_len() + self._data = json.loads(self.trans.read(size).decode("utf-8")) + + res = struct_to_obj(self._data["payload"], obj) + self._data = None + return res + + def write_struct(self, obj): + data = json.dumps({ + "metadata": self._meta, + "payload": struct_to_json(obj) + }) + + self._write_len(len(data)) + self.trans.write(data.encode("utf-8")) + + def skip(self, ttype): + warn("TJsonProtocol doesn't support skipping. Ignoring.") + + +class TJSONProtocolFactory(object): + def get_protocol(self, trans): + return TJSONProtocol(trans) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/protocol/multiplex.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/protocol/multiplex.py new file mode 100644 index 0000000000000000000000000000000000000000..191ffa488125cc9a9baf4f900fbf282c3611fc79 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/protocol/multiplex.py @@ -0,0 +1,35 @@ +# -*- coding: utf-8 -*- + +from thriftpy2.protocol.base import TProtocolFactory +from thriftpy2.thrift import TMultiplexedProcessor, TMessageType + + +class TMultiplexedProtocol(object): + """Multiplex the protocol by prepend service name to api for every api call. + Can be used together with all original protocols. + """ + + def __init__(self, proto, service_name): + self.service_name = service_name + self._proto = proto + + def __getattr__(self, name): + return getattr(self._proto, name) + + def write_message_begin(self, name, ttype, seqid): + if ttype in (TMessageType.CALL, TMessageType.ONEWAY): + self._proto.write_message_begin( + self.service_name + TMultiplexedProcessor.SEPARATOR + name, + ttype, seqid) + else: + self._proto.write_message_begin(name, ttype, seqid) + + +class TMultiplexedProtocolFactory(object): + def __init__(self, proto_factory: TProtocolFactory, service_name): + self._proto_factory = proto_factory + self.service_name = service_name + + def get_protocol(self, trans): + proto = self._proto_factory.get_protocol(trans) + return TMultiplexedProtocol(proto, self.service_name) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/rpc.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/rpc.py new file mode 100644 index 0000000000000000000000000000000000000000..72767a9662efbeee3035f7ad5b7b284e3b1fd164 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/rpc.py @@ -0,0 +1,167 @@ +# -*- coding: utf-8 -*- + +from __future__ import absolute_import + +import contextlib +import socket +import ssl +import types +import urllib +import warnings +from typing import Generator, Optional + +from thriftpy2.contrib.aio.rpc import make_client as make_aio_client # noqa +from thriftpy2.contrib.aio.rpc import make_server as make_aio_server # noqa +from thriftpy2.protocol import TBinaryProtocolFactory +from thriftpy2.protocol.base import TProtocolFactory +from thriftpy2.server import TThreadedServer +from thriftpy2.thrift import TClient, TProcessor +from thriftpy2.transport import (TBufferedTransportFactory, TServerSocket, + TSocket, TSSLServerSocket, TSSLSocket) +from thriftpy2.transport.base import TTransportFactory + + +def make_client(service: types.ModuleType, host: str = "localhost", + port: int = 9090, unix_socket: Optional[str] = None, + proto_factory: TProtocolFactory = TBinaryProtocolFactory(), + trans_factory: TTransportFactory = TBufferedTransportFactory(), + timeout: int = 3000, cafile: Optional[str] = None, + ssl_context: Optional[ssl.SSLContext] = None, + certfile: Optional[str] = None, + keyfile: Optional[str] = None, + url: str = "", + socket_family: socket.AddressFamily = socket.AF_INET + ) -> TClient: + if url: + parsed_url = urllib.parse.urlparse(url) + host = parsed_url.hostname or host + port = parsed_url.port or port + if unix_socket: + client_socket = TSocket(unix_socket=unix_socket, socket_timeout=timeout) + if certfile: + warnings.warn("SSL only works with host:port, not unix_socket.") + elif host and port: + if cafile or ssl_context: + client_socket = TSSLSocket( + host, + port, + socket_timeout=timeout, + socket_family=socket_family, + cafile=cafile, + certfile=certfile, + keyfile=keyfile, + ssl_context=ssl_context, + ) + else: + client_socket = TSocket( + host, port, socket_family=socket_family, socket_timeout=timeout + ) + else: + raise ValueError("Either host/port or unix_socket" + " or url must be provided.") + + transport = trans_factory.get_transport(client_socket) + protocol = proto_factory.get_protocol(transport) + transport.open() + return TClient(service, protocol) + + +def make_server(service: types.ModuleType, handler: object, + host: str = "localhost", port: int = 9090, + unix_socket: Optional[str] = None, + proto_factory: TProtocolFactory = TBinaryProtocolFactory(), + trans_factory: TTransportFactory = TBufferedTransportFactory(), + client_timeout: int = 3000, + certfile: Optional[str] = None, + socket_family: socket.AddressFamily = socket.AF_INET + ) -> TThreadedServer: + processor = TProcessor(service, handler) + + if unix_socket: + server_socket = TServerSocket(unix_socket=unix_socket) + if certfile: + warnings.warn("SSL only works with host:port, not unix_socket.") + elif host and port: + if certfile: + server_socket = TSSLServerSocket( + host=host, port=port, client_timeout=client_timeout, + certfile=certfile, socket_family=socket_family) + else: + server_socket = TServerSocket( + host=host, port=port, client_timeout=client_timeout, + socket_family=socket_family) + else: + raise ValueError("Either host/port or unix_socket must be provided.") + + server = TThreadedServer(processor, server_socket, + iprot_factory=proto_factory, + itrans_factory=trans_factory) + return server + + +@contextlib.contextmanager +def client_context(service: types.ModuleType, host: str = "localhost", + port: int = 9090, unix_socket: Optional[str] = None, + proto_factory: TProtocolFactory = TBinaryProtocolFactory(), + trans_factory: TTransportFactory = TBufferedTransportFactory(), + timeout: Optional[int] = None, + socket_timeout: int = 3000, + connect_timeout: int = 3000, + cafile: Optional[str] = None, + ssl_context: Optional[ssl.SSLContext] = None, + certfile: Optional[str] = None, + keyfile: Optional[str] = None, + url: str = "", + socket_family: socket.AddressFamily = socket.AF_INET + ) -> Generator[TClient, None, None]: + if url: + parsed_url = urllib.parse.urlparse(url) + host = parsed_url.hostname or host + port = parsed_url.port or port + + if timeout: + warnings.warn("`timeout` deprecated, use `socket_timeout` and " + "`connect_timeout` instead.") + socket_timeout = connect_timeout = timeout + + if unix_socket: + client_socket = TSocket( + unix_socket=unix_socket, + connect_timeout=connect_timeout, + socket_timeout=socket_timeout, + ) + if certfile: + warnings.warn("SSL only works with host:port, not unix_socket.") + elif host and port: + if cafile or ssl_context: + client_socket = TSSLSocket( + host, + port, + connect_timeout=connect_timeout, + socket_timeout=socket_timeout, + cafile=cafile, + certfile=certfile, + keyfile=keyfile, + ssl_context=ssl_context, + socket_family=socket_family, + ) + else: + client_socket = TSocket( + host, + port, + connect_timeout=connect_timeout, + socket_timeout=socket_timeout, + socket_family=socket_family, + ) + else: + raise ValueError("Either host/port or unix_socket" + " or url must be provided.") + + try: + transport = trans_factory.get_transport(client_socket) + protocol = proto_factory.get_protocol(transport) + transport.open() + yield TClient(service, protocol) + + finally: + transport.close() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/server.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/server.py new file mode 100644 index 0000000000000000000000000000000000000000..947f8ddf5dfec53de13c5126e38fbf7c0bcae57b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/server.py @@ -0,0 +1,112 @@ +# -*- coding: utf-8 -*- + +from __future__ import absolute_import + +import logging +import threading +from typing import Optional + +from thriftpy2.protocol import TBinaryProtocolFactory +from thriftpy2.protocol.base import TProtocolFactory +from thriftpy2.thrift import TProcessor +from thriftpy2.transport import ( + TBufferedTransportFactory, + TServerSocket, + TTransportException, +) +from thriftpy2.transport.base import TTransportBase, TTransportFactory + + +logger = logging.getLogger(__name__) + + +class TServer(object): + def __init__(self, processor: TProcessor, trans: TServerSocket, + itrans_factory: Optional[TTransportFactory] = None, + iprot_factory: Optional[TProtocolFactory] = None, + otrans_factory: Optional[TTransportFactory] = None, + oprot_factory: Optional[TProtocolFactory] = None) -> None: + self.processor = processor + self.trans = trans + + self.itrans_factory = itrans_factory or TBufferedTransportFactory() + self.iprot_factory = iprot_factory or TBinaryProtocolFactory() + self.otrans_factory = otrans_factory or self.itrans_factory + self.oprot_factory = oprot_factory or self.iprot_factory + + def serve(self) -> None: + pass + + def close(self) -> None: + pass + + +class TSimpleServer(TServer): + """Simple single-threaded server that just pumps around one transport.""" + + def __init__(self, *args, **kwargs) -> None: + TServer.__init__(self, *args, **kwargs) + self.closed = False + + def serve(self) -> None: + self.trans.listen() + while not self.closed: + client = self.trans.accept() + itrans = self.itrans_factory.get_transport(client) + otrans = self.otrans_factory.get_transport(client) + iprot = self.iprot_factory.get_protocol(itrans) + oprot = self.oprot_factory.get_protocol(otrans) + try: + while not self.closed: + self.processor.process(iprot, oprot) + except TTransportException: + pass + except Exception as x: + logger.exception(x) + + itrans.close() + otrans.close() + + def close(self) -> None: + self.closed = True + + +class TThreadedServer(TServer): + """Threaded server that spawns a new thread per each connection.""" + + def __init__(self, *args, **kwargs) -> None: + self.daemon = kwargs.pop("daemon", False) + TServer.__init__(self, *args, **kwargs) + self.closed = False + + def serve(self) -> None: + self.trans.listen() + while not self.closed: + try: + client = self.trans.accept() + t = threading.Thread(target=self.handle, args=(client,)) + t.daemon = self.daemon + t.start() + except KeyboardInterrupt: + raise + except Exception as x: + logger.exception(x) + + def handle(self, client: TTransportBase) -> None: + itrans = self.itrans_factory.get_transport(client) + otrans = self.otrans_factory.get_transport(client) + iprot = self.iprot_factory.get_protocol(itrans) + oprot = self.oprot_factory.get_protocol(otrans) + try: + while True: + self.processor.process(iprot, oprot) + except TTransportException: + pass + except Exception as x: + logger.exception(x) + + itrans.close() + otrans.close() + + def close(self) -> None: + self.closed = True diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/thrift.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/thrift.py new file mode 100644 index 0000000000000000000000000000000000000000..1199d59a0db66f3e49e115081e5ad01eeb70128b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/thrift.py @@ -0,0 +1,472 @@ +# -*- coding: utf-8 -*- + +""" + thriftpy2.thrift + ~~~~~~~~~~~~~~~~~~ + + Thrift simplified. +""" + +from __future__ import absolute_import + +import functools +import linecache +import types +from itertools import zip_longest +from typing import (Any, Callable, Dict, List, Optional, Tuple, Type, + TYPE_CHECKING) + +if TYPE_CHECKING: + from thriftpy2.protocol.base import TProtocolBase + + +def args_to_kwargs(thrift_spec: Dict[int, tuple], *args: Any, + **kwargs: Any) -> Dict[str, Any]: + for item, value in zip_longest(sorted(thrift_spec.items()), args): + arg_name = item[1][1] + required = item[1][-1] + if value is not None: + kwargs[item[1][1]] = value + if required and arg_name not in kwargs: + raise ValueError(arg_name) + return kwargs + + +def parse_spec(ttype: int, spec: Any = None) -> Optional[str]: + name_map = TType._VALUES_TO_NAMES + + def _type(s): + return parse_spec(*s) if isinstance(s, tuple) else name_map[s] + + if spec is None: + return name_map[ttype] + + if ttype == TType.STRUCT: + return spec.__name__ + + if ttype in (TType.LIST, TType.SET): + return "%s<%s>" % (name_map[ttype], _type(spec)) + + if ttype == TType.MAP: + return "MAP<%s, %s>" % (_type(spec[0]), _type(spec[1])) + + +def init_func_generator(cls: type, + spec: Optional[List[Tuple[str, Any]]] + ) -> Callable[..., None]: + """Generate `__init__` function based on TPayload.default_spec + + For example:: + + spec = [('name', 'Alice'), ('number', None)] + + will generate a types.FunctionType object representing:: + + def __init__(self, name='Alice', number=None): + self.name = name + self.number = number + """ + if not spec: + def __init__(self): + pass + return __init__ + + varnames, defaults = zip(*spec) + + args = ', '.join(map('{0[0]}={0[1]!r}'.format, spec)) + init = "def __init__(self, {}):\n".format(args) + init += "\n".join(map(' self.{0} = {0}'.format, varnames)) + + name = ''.format(cls.__name__) + code = compile(init, name, 'exec') + func = next(c for c in code.co_consts if isinstance(c, types.CodeType)) + + # Add a fake linecache entry so debuggers and the traceback module can + # better understand our generated code. + linecache.cache[name] = (len(init), None, init.splitlines(True), name) + + return types.FunctionType(func, {}, argdefs=defaults) + + +class TType(object): + STOP = 0 + VOID = 1 + BOOL = 2 + BYTE = 3 + I08 = 3 + DOUBLE = 4 + I16 = 6 + I32 = 8 + I64 = 10 + STRING = 11 + UTF7 = 11 + STRUCT = 12 + MAP = 13 + SET = 14 + LIST = 15 + UTF8 = 16 + UTF16 = 17 + BINARY = 18 + + _VALUES_TO_NAMES = { + STOP: 'STOP', + VOID: 'VOID', + BOOL: 'BOOL', + BYTE: 'BYTE', + I08: 'BYTE', + DOUBLE: 'DOUBLE', + I16: 'I16', + I32: 'I32', + I64: 'I64', + STRING: 'STRING', + UTF7: 'STRING', + STRUCT: 'STRUCT', + MAP: 'MAP', + SET: 'SET', + LIST: 'LIST', + UTF8: 'UTF8', + UTF16: 'UTF16', + BINARY: 'BINARY' + } + + +class TMessageType(object): + CALL = 1 + REPLY = 2 + EXCEPTION = 3 + ONEWAY = 4 + + +class TPayloadMeta(type): + + def __new__(cls, name: str, bases: Tuple[type, ...], + attrs: Dict[str, Any]) -> 'TPayloadMeta': + if "default_spec" in attrs: + spec = attrs.pop("default_spec") + attrs["__init__"] = init_func_generator(cls, spec) + return super(TPayloadMeta, cls).__new__(cls, name, bases, attrs) + + +def gen_init(cls: type, thrift_spec: Optional[Dict[int, tuple]] = None, + default_spec: Optional[List[Tuple[str, Any]]] = None) -> type: + if thrift_spec is not None: + cls.thrift_spec = thrift_spec + + if default_spec is not None: + cls.__init__ = init_func_generator(cls, default_spec) + return cls + + +class TPayload(metaclass=TPayloadMeta): + + __hash__ = None + + def read(self, iprot: 'TProtocolBase') -> None: + iprot.read_struct(self) + + def write(self, oprot: 'TProtocolBase') -> None: + oprot.write_struct(self) + + def __repr__(self) -> str: + l = ['%s=%r' % (key, value) for key, value in self.__dict__.items()] + return '%s(%s)' % (self.__class__.__name__, ', '.join(l)) + + def __str__(self) -> str: + return repr(self) + + def __eq__(self, other: object) -> bool: + return isinstance(other, self.__class__) and \ + self.__dict__ == other.__dict__ + + def __ne__(self, other: object) -> bool: + return not self.__eq__(other) + + +class TClient(object): + + def __init__(self, service: types.ModuleType, + iprot: 'TProtocolBase', + oprot: Optional['TProtocolBase'] = None) -> None: + self._service = service + self._iprot = self._oprot = iprot + if oprot is not None: + self._oprot = oprot + self._seqid = 0 + + def __getattr__(self, _api: str) -> functools.partial: + if _api in self._service.thrift_services: + return functools.partial(self._req, _api) + + # close method is a reserved method name defined as below + # so we need to handle it alone + if _api == 'tclose': + return functools.partial(self._req, 'close') + + raise AttributeError("{} instance has no attribute '{}'".format( + self.__class__.__name__, _api)) + + def __dir__(self) -> List[str]: + return self._service.thrift_services + + def _req(self, _api: str, *args: Any, **kwargs: Any) -> Any: + try: + service_args = getattr(self._service, _api + "_args") + kwargs = args_to_kwargs(service_args.thrift_spec, *args, **kwargs) + except ValueError as e: + raise TApplicationException( + TApplicationException.UNKNOWN_METHOD, + '{arg} is required argument for {service}.{api}'.format( + arg=e.args[0], service=self._service.__name__, api=_api)) + + result_cls = getattr(self._service, _api + "_result") + + self._send(_api, **kwargs) + # wait result only if non-oneway + if not getattr(result_cls, "oneway"): + return self._recv(_api) + + def _send(self, _api: str, **kwargs: Any) -> None: + oneway = getattr(getattr(self._service, _api + "_result"), "oneway") + msg_type = TMessageType.ONEWAY if oneway else TMessageType.CALL + self._oprot.write_message_begin(_api, msg_type, self._seqid) + args = getattr(self._service, _api + "_args")() + for k, v in kwargs.items(): + setattr(args, k, v) + args.write(self._oprot) + self._oprot.write_message_end() + self._oprot.trans.flush() + + def _recv(self, _api: str) -> Any: + fname, mtype, rseqid = self._iprot.read_message_begin() + if mtype == TMessageType.EXCEPTION: + x = TApplicationException() + x.read(self._iprot) + self._iprot.read_message_end() + raise x + result = getattr(self._service, _api + "_result")() + result.read(self._iprot) + self._iprot.read_message_end() + + if hasattr(result, "success") and result.success is not None: + return result.success + + # void api without throws + if len(result.thrift_spec) == 0: + return + + # check throws + for k, v in result.__dict__.items(): + if k != "success" and v: + raise v + + # no throws & not void api + if hasattr(result, "success"): + raise TApplicationException(TApplicationException.MISSING_RESULT) + + def close(self) -> None: + self._iprot.trans.close() + if self._iprot != self._oprot: + self._oprot.trans.close() + + +class TProcessor(object): + """Base class for processor, which works on two streams.""" + + def __init__(self, service: types.ModuleType, handler: object) -> None: + self._service = service + self._handler = handler + + def process_in(self, iprot: 'TProtocolBase' + ) -> Tuple[str, int, Any, Optional[Callable]]: + api, type, seqid = iprot.read_message_begin() + if api not in self._service.thrift_services: + iprot.skip(TType.STRUCT) + iprot.read_message_end() + return api, seqid, TApplicationException(TApplicationException.UNKNOWN_METHOD), None # noqa + + args = getattr(self._service, api + "_args")() + args.read(iprot) + iprot.read_message_end() + result = getattr(self._service, api + "_result")() + + # convert kwargs to args + api_args = [args.thrift_spec[k][1] for k in sorted(args.thrift_spec)] + + def call(): + f = getattr(self._handler, api) + return f(*(args.__dict__[k] for k in api_args)) + + return api, seqid, result, call + + def send_exception(self, oprot: 'TProtocolBase', api: str, + exc: 'TApplicationException', seqid: int) -> None: + oprot.write_message_begin(api, TMessageType.EXCEPTION, seqid) + exc.write(oprot) + oprot.write_message_end() + oprot.trans.flush() + + def send_result(self, oprot: 'TProtocolBase', api: str, + result: TPayload, seqid: int) -> None: + oprot.write_message_begin(api, TMessageType.REPLY, seqid) + result.write(oprot) + oprot.write_message_end() + oprot.trans.flush() + + def handle_exception(self, e: Exception, result: TPayload) -> bool: + for k in sorted(result.thrift_spec): + if result.thrift_spec[k][1] == "success": + continue + + _, exc_name, exc_cls, _ = result.thrift_spec[k] + if isinstance(e, exc_cls): + setattr(result, exc_name, e) + return True + return False + + def process(self, iprot: 'TProtocolBase', + oprot: 'TProtocolBase') -> None: + api, seqid, result, call = self.process_in(iprot) + + if isinstance(result, TApplicationException): + return self.send_exception(oprot, api, result, seqid) + + try: + result.success = call() + except TApplicationException as e: + return self.send_exception(oprot, api, e, seqid) + except Exception as e: + # raise if api don't have throws + if not self.handle_exception(e, result): + raise + + if not result.oneway: + self.send_result(oprot, api, result, seqid) + + +class TMultiplexedProcessor(TProcessor): + SEPARATOR = ":" + + def __init__(self) -> None: + self.processors = {} # type: Dict[str, TProcessor] + + def register_processor(self, service_name: str, + processor: 'TProcessor') -> None: + if service_name in self.processors: + raise TApplicationException( + type=TApplicationException.INTERNAL_ERROR, + message='processor for `{}` already registered' + .format(service_name)) + self.processors[service_name] = processor + + def process_in(self, iprot: 'TProtocolBase' + ) -> Tuple[str, int, Any, Optional[Callable]]: + api, type, seqid = iprot.read_message_begin() + if type not in (TMessageType.CALL, TMessageType.ONEWAY): + raise TException("TMultiplexed protocol only supports CALL & ONEWAY") # noqa + if TMultiplexedProcessor.SEPARATOR not in api: + raise TException("Service name not found in message. " + "You should use TMultiplexedProtocol in client.") + + service_name, api = api.split(TMultiplexedProcessor.SEPARATOR) + if service_name not in self.processors: + iprot.skip(TType.STRUCT) + iprot.read_message_end() + e = TApplicationException(TApplicationException.UNKNOWN_METHOD) + return api, seqid, e, None + + proc = self.processors[service_name] + args = getattr(proc._service, api + "_args")() + args.read(iprot) + iprot.read_message_end() + result = getattr(proc._service, api + "_result")() + + # convert kwargs to args + api_args = [args.thrift_spec[k][1] for k in sorted(args.thrift_spec)] + + def call(): + f = getattr(proc._handler, api) + return f(*(args.__dict__[k] for k in api_args)) + + return api, seqid, result, call + + +class TProcessorFactory(object): + + def __init__(self, processor_class: Type[TProcessor], + *args: Any, **kwargs: Any) -> None: + self.args = args + self.kwargs = kwargs + + self.processor_class = processor_class + + def get_processor(self) -> TProcessor: + return self.processor_class(*self.args, **self.kwargs) + + +class TException(TPayload, Exception): + """Base class for all thrift exceptions.""" + + def __hash__(self) -> int: + return id(self) + + def __eq__(self, other: object) -> bool: + return id(self) == id(other) + + +class TDecodeException(TException): + def __init__(self, name: str, fid: int, field: str, value: Any, + ttype: int, spec: Any = None) -> None: + self.struct_name = name + self.fid = fid + self.field = field + self.value = value + + self.type_repr = parse_spec(ttype, spec) + + def __str__(self) -> str: + return ( + "Field '%s(%s)' of '%s' needs type '%s', " + "but the value is `%r`" + ) % (self.field, self.fid, self.struct_name, self.type_repr, + self.value) + + +class TApplicationException(TException): + """Application level thrift exceptions.""" + + thrift_spec = { + 1: (TType.STRING, 'message', False), + 2: (TType.I32, 'type', False), + } + + UNKNOWN = 0 + UNKNOWN_METHOD = 1 + INVALID_MESSAGE_TYPE = 2 + WRONG_METHOD_NAME = 3 + BAD_SEQUENCE_ID = 4 + MISSING_RESULT = 5 + INTERNAL_ERROR = 6 + PROTOCOL_ERROR = 7 + + def __init__(self, type: int = UNKNOWN, + message: Optional[str] = None) -> None: + super(TApplicationException, self).__init__() + self.type = type + self.message = message + + def __str__(self) -> str: + if self.message: + return self.message + + if self.type == self.UNKNOWN_METHOD: + return 'Unknown method' + elif self.type == self.INVALID_MESSAGE_TYPE: + return 'Invalid message type' + elif self.type == self.WRONG_METHOD_NAME: + return 'Wrong method name' + elif self.type == self.BAD_SEQUENCE_ID: + return 'Bad sequence ID' + elif self.type == self.MISSING_RESULT: + return 'Missing result' + else: + return 'Default (unknown) TApplicationException' diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/tornado.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/tornado.py new file mode 100644 index 0000000000000000000000000000000000000000..3dbdc87bf2a8ac37dec8fc0b09e30319e91f4a5e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/tornado.py @@ -0,0 +1,274 @@ +# -*- coding: utf-8 -*- + +""" +>>> pingpong = thriftpy2.load("pingpong.thrift") +>>> +>>> class Dispatcher(object): +>>> def ping(self): +>>> return "pong" + +>>> server = make_server(pingpong.PingPong, Dispatcher()) +>>> server.listen(6000) +>>> client = ioloop.IOLoop.current().run_sync( + lambda: make_client(pingpong.PingPong, '127.0.0.1', 6000)) +>>> ioloop.IOLoop.current().run_sync(client.ping) +'pong' +""" + +from __future__ import absolute_import + +import logging +import socket +import struct +import urllib +import warnings +from contextlib import contextmanager +from datetime import timedelta +from io import BytesIO + +from tornado import gen, iostream, tcpserver +from tornado import version as tornado_version + +# TODO need TCyTornadoStreamTransport to work with cython binary protocol +from .protocol.binary import TBinaryProtocolFactory +from .thrift import TApplicationException, TClient, TProcessor +from .transport import TTransportBase, TTransportException +from .transport.memory import TMemoryBuffer + +try: + from tornado.locks import Lock +except ImportError: + try: + from toro import Lock + except ImportError: + raise RuntimeError('With tornado {}, you need to install ' + '"toro"'.format(tornado_version)) + +logger = logging.getLogger(__name__) + + +warnings.warn( + "tornado support is deprecated and will be removed in a future version. " + "Consider using asyncio-based alternatives instead.", + DeprecationWarning, + stacklevel=2 +) + + +class TTornadoStreamTransport(TTransportBase): + """a framed, buffered transport over a Tornado stream""" + DEFAULT_CONNECT_TIMEOUT = timedelta(seconds=1) + DEFAULT_READ_TIMEOUT = timedelta(seconds=1) + + def __init__(self, host, port, stream=None, io_loop=None, ssl_options=None, + read_timeout=DEFAULT_READ_TIMEOUT): + self.host = host + self.port = port + self.io_loop = io_loop + self.read_timeout = read_timeout + self.is_queuing_reads = False + self.read_queue = [] + self.__wbuf = BytesIO() + self._read_lock = Lock() + self.ssl_options = ssl_options + + # servers provide a ready-to-go stream + self.stream = stream + if self.stream is not None: + self._set_close_callback() + + if tornado_version >= '5.0': + def with_timeout(self, timeout, future): + return gen.with_timeout(timeout, future) + else: + def with_timeout(self, timeout, future): + return gen.with_timeout(timeout, future, self.io_loop) + + @gen.coroutine + def open(self, timeout=DEFAULT_CONNECT_TIMEOUT): + logger.debug('socket connecting') + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) + if self.ssl_options is None: + self.stream = iostream.IOStream(sock) + else: + self.stream = iostream.SSLIOStream( + sock, ssl_options=self.ssl_options) + + try: + yield self.with_timeout(timeout, self.stream.connect( + (self.host, self.port))) + except (socket.error, OSError, IOError): + message = 'could not connect to {}:{}'.format(self.host, self.port) + raise TTransportException( + type=TTransportException.NOT_OPEN, + message=message) + + self._set_close_callback() + raise gen.Return(self) + + def _set_close_callback(self): + self.stream.set_close_callback(self.close) + + def close(self): + # don't raise if we intend to close + self.stream.set_close_callback(None) + self.stream.close() + + def read(self, _): + # The generated code for Tornado shouldn't do individual reads -- only + # frames at a time + assert False, "you're doing it wrong" + + @contextmanager + def io_exception_context(self): + try: + yield + except (socket.error, OSError, IOError) as e: + raise TTransportException( + type=TTransportException.END_OF_FILE, + message=str(e)) + except iostream.StreamBufferFullError as e: + raise TTransportException( + type=TTransportException.UNKNOWN, + message=str(e)) + except gen.TimeoutError as e: + raise TTransportException( + type=TTransportException.TIMED_OUT, + message=str(e)) + + @gen.coroutine + def read_frame(self): + # IOStream processes reads one at a time + with (yield self._read_lock.acquire()): + with self.io_exception_context(): + frame_header = yield self._read_bytes(4) + if len(frame_header) == 0: + raise iostream.StreamClosedError( + 'Read zero bytes from stream') + frame_length, = struct.unpack('!i', frame_header) + logger.debug('received frame header, frame length = %d', + frame_length) + frame = yield self._read_bytes(frame_length) + logger.debug('received frame payload: %r', frame) + raise gen.Return(frame) + + def _read_bytes(self, n): + return self.with_timeout(self.read_timeout, self.stream.read_bytes(n)) + + def write(self, buf): + self.__wbuf.write(buf) + + def flush(self): + frame = self.__wbuf.getvalue() + # reset wbuf before write/flush to preserve state on underlying failure + frame_length = struct.pack('!i', len(frame)) + self.__wbuf = BytesIO() + with self.io_exception_context(): + return self.stream.write(frame_length + frame) + + +class TTornadoServer(tcpserver.TCPServer): + def __init__( + self, processor, iprot_factory, oprot_factory=None, + transport_read_timeout=TTornadoStreamTransport.DEFAULT_READ_TIMEOUT, + *args, **kwargs): + super(TTornadoServer, self).__init__(*args, **kwargs) + + self._processor = processor + self._iprot_factory = iprot_factory + self._oprot_factory = (oprot_factory if oprot_factory is not None + else iprot_factory) + self.transport_read_timeout = transport_read_timeout + + # `io_loop` has been deprecated since tornado 4.1 and removed in 5.0 + self.__io_loop = getattr(self, 'io_loop', None) + + @gen.coroutine + def handle_stream(self, stream, address): + host, port = address + trans = TTornadoStreamTransport( + host=host, port=port, stream=stream, + io_loop=self.__io_loop, read_timeout=self.transport_read_timeout) + try: + oprot = self._oprot_factory.get_protocol(trans) + iprot = self._iprot_factory.get_protocol(TMemoryBuffer()) + + while not trans.stream.closed(): + # TODO: maybe read multiple frames in advance for concurrency + try: + frame = yield trans.read_frame() + except TTransportException as e: + if e.type == TTransportException.END_OF_FILE: + break + else: + raise + + iprot.trans.setvalue(frame) + api, seqid, result, call = self._processor.process_in(iprot) + if isinstance(result, TApplicationException): + self._processor.send_exception(oprot, api, result, seqid) + else: + try: + result.success = yield gen.maybe_future(call()) + except Exception as e: + # raise if api don't have throws + if not self._processor.handle_exception(e, result): + raise + + self._processor.send_result(oprot, api, result, seqid) + except Exception: + logger.exception('thrift exception in handle_stream') + trans.close() + + logger.info('client disconnected %s:%d', host, port) + + +class TTornadoClient(TClient): + @gen.coroutine + def _recv(self, api): + frame = yield self._oprot.trans.read_frame() + self._iprot.trans.setvalue(frame) + result = super(TTornadoClient, self)._recv(api) + raise gen.Return(result) + + def close(self): + self._oprot.trans.close() + + +def make_server( + service, handler, proto_factory=TBinaryProtocolFactory(), + io_loop=None, ssl_options=None, + transport_read_timeout=TTornadoStreamTransport.DEFAULT_READ_TIMEOUT): + processor = TProcessor(service, handler) + if tornado_version >= '5.0': + server = TTornadoServer(processor, iprot_factory=proto_factory, + transport_read_timeout=transport_read_timeout, + ssl_options=ssl_options) + else: + server = TTornadoServer(processor, iprot_factory=proto_factory, + transport_read_timeout=transport_read_timeout, + io_loop=io_loop, ssl_options=ssl_options) + return server + + +@gen.coroutine +def make_client(service, + host='localhost', + port=9090, + proto_factory=TBinaryProtocolFactory(), io_loop=None, + ssl_options=None, + connect_timeout=TTornadoStreamTransport.DEFAULT_CONNECT_TIMEOUT, + read_timeout=TTornadoStreamTransport.DEFAULT_READ_TIMEOUT, + url=''): + if url: + parsed_url = urllib.parse.urlparse(url) + host = parsed_url.hostname or host + port = parsed_url.port or port + transport = TTornadoStreamTransport( + host, port, io_loop=io_loop, + ssl_options=ssl_options, read_timeout=read_timeout) + iprot = proto_factory.get_protocol(TMemoryBuffer()) + oprot = proto_factory.get_protocol(transport) + yield transport.open(connect_timeout) + client = TTornadoClient(service, iprot, oprot) + raise gen.Return(client) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8c6c59aad768473e1ddec1d34755bb4c3d0566e0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/__init__.py @@ -0,0 +1,47 @@ +# -*- coding: utf-8 -*- + +from __future__ import absolute_import + +from thriftpy2._compat import CYTHON + +from .base import TTransportBase, TTransportException +from .socket import TSocket, TServerSocket +from .sslsocket import TSSLSocket, TSSLServerSocket +from ._ssl import create_thriftpy_context +from .buffered import TBufferedTransport, TBufferedTransportFactory +from .framed import TFramedTransport, TFramedTransportFactory +from .memory import TMemoryBuffer +from .sasl import TSaslClientTransport + +if CYTHON: + from .buffered import TCyBufferedTransport, TCyBufferedTransportFactory + from .framed import TCyFramedTransport, TCyFramedTransportFactory + from .memory import TCyMemoryBuffer + from .sasl import TCySaslClientTransport + + # enable cython binary by default for CPython. + TMemoryBuffer = TCyMemoryBuffer # noqa + TBufferedTransport = TCyBufferedTransport # noqa + TBufferedTransportFactory = TCyBufferedTransportFactory # noqa + TFramedTransport = TCyFramedTransport # noqa + TFramedTransportFactory = TCyFramedTransportFactory # noqa + TSaslClientTransport = TCySaslClientTransport # noqa +else: + # disable cython binary protocol for PYPY since it's slower. + TCyMemoryBuffer = TMemoryBuffer + TCyBufferedTransport = TBufferedTransport + TCyBufferedTransportFactory = TBufferedTransportFactory + TCyFramedTransport = TFramedTransport + TCyFramedTransportFactory = TFramedTransportFactory + TCySaslClientTransport = TSaslClientTransport + +__all__ = [ + "TSocket", "TServerSocket", + "TSSLSocket", "TSSLServerSocket", "create_thriftpy_context", + "TTransportBase", "TTransportException", + "TMemoryBuffer", "TFramedTransport", "TFramedTransportFactory", + "TBufferedTransport", "TBufferedTransportFactory", "TCyMemoryBuffer", + "TCyBufferedTransport", "TCyBufferedTransportFactory", + "TCyFramedTransport", "TCyFramedTransportFactory", + "TSaslClientTransport", "TCySaslClientTransport", +] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/_ssl.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/_ssl.py new file mode 100644 index 0000000000000000000000000000000000000000..358f0c17444d332f9d76b47897ff3f45ba632333 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/_ssl.py @@ -0,0 +1,66 @@ +# -*- coding: utf-8 -*- + +""" +The codes in this ssl compat lib were inspired by urllib3.utils.ssl_ module. +""" + +import ssl +from ssl import SSLContext + +# Disable weak or insecure ciphers by default +# (OpenSSL's default setting is 'DEFAULT:!aNULL:!eNULL') +# Enable a better set of ciphers by default +# This list has been explicitly chosen to: +# * Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE) +# * Prefer ECDHE over DHE for better performance +# * Prefer any AES-GCM over any AES-CBC for better performance and security +# * Then Use HIGH cipher suites as a fallback +# * Then Use 3DES as fallback which is secure but slow +# * Disable NULL authentication, NULL encryption, and MD5 MACs for security +# reasons +DEFAULT_CIPHERS = ( + 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:' + 'DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:!aNULL:' + '!eNULL:!MD5' +) + +# Restricted and more secure ciphers for the server side +# This list has been explicitly chosen to: +# * Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE) +# * Prefer ECDHE over DHE for better performance +# * Prefer any AES-GCM over any AES-CBC for better performance and security +# * Then Use HIGH cipher suites as a fallback +# * Then Use 3DES as fallback which is secure but slow +# * Disable NULL authentication, NULL encryption, MD5 MACs, DSS, and RC4 for +# security reasons +RESTRICTED_SERVER_CIPHERS = ( + 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:' + 'DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:!aNULL:' + '!eNULL:!MD5:!DSS:!RC4' +) + + +def create_thriftpy_context(server_side=False, ciphers=None): + """ + The SSLContext has some default security options, you can disable them + manually, for example:: + + from thriftpy2.transport import _ssl + import ssl + context = _ssl.create_thriftpy_context() + context.options &= ~ssl.OP_NO_SSLv3 + + You can do the same to enable compression. + """ + + # server/client default options + if server_side: + context = SSLContext(ssl.PROTOCOL_TLS_SERVER) + else: + context = SSLContext(ssl.PROTOCOL_TLS_CLIENT) + context.check_hostname = False + + if ciphers: + context.set_ciphers(ciphers) + + return context diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/base.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/base.py new file mode 100644 index 0000000000000000000000000000000000000000..eb3ddb83aa9d5c17756bc9aa0cd21335a25f2695 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/base.py @@ -0,0 +1,102 @@ +from __future__ import absolute_import, annotations + +try: + from typing import Protocol +except ImportError: + from typing_extensions import Protocol + +from ..thrift import TType, TException + + +def readall(read_fn, sz): + buff = b'' + have = 0 + while have < sz: + chunk = read_fn(sz - have) + have += len(chunk) + buff += chunk + + if len(chunk) == 0: + raise TTransportException(TTransportException.END_OF_FILE, + "End of file reading from transport") + + return buff + + +class TTransportFactory(Protocol): + """Transport factory interface for type annotations.""" + + def get_transport(self, trans) -> TTransportBase: + """Return a transport instance wrapping the given transport.""" + ... + + +class TTransportBase(object): + """Base class for Thrift transport layer.""" + + def is_open(self): + """Check if this transport is open.""" + raise NotImplementedError + + def open(self): + """ + Prepare this transport for usage and allocate any necessary resources + like sockets or sessions. + """ + raise NotImplementedError + + def close(self): + """Clean up and deallocate any resources allocated in open().""" + raise NotImplementedError + + def _read(self, sz): + """ + Internal read method which can read up to `sz` bytes but doesn't + need to return them all. + """ + raise NotImplementedError + + def read(self, sz): + """ + Get exactly `sz` bytes from the underlying connection. + + When implementing a custom transport, this method must return exactly + `sz` bytes if it is expected to be called from the protocol layer. If + it intends to wrapped by another transport, like TBufferedTransport, + it should return whatever the underlying connection/transport can get. + The wrapping transport will take care of ensuring `sz` bytes are + returned. For a more in depth discussion, see: + https://github.com/Thriftpy/thriftpy2/pull/108#discussion_r355131677 + """ + return readall(self._read, sz) + + def write(self, buf): + """ + Submit some data to be written to the connection. May be + buffered until flush is called. + """ + raise NotImplementedError + + def flush(self): + """Ensure that all internal buffers are emptied into the connection.""" + raise NotImplementedError + + +class TTransportException(TException): + """Custom Transport Exception class""" + + thrift_spec = { + 1: (TType.STRING, 'message'), + 2: (TType.I32, 'type'), + } + + UNKNOWN = 0 + NOT_OPEN = 1 + ALREADY_OPEN = 2 + TIMED_OUT = 3 + END_OF_FILE = 4 + + def __init__(self, type=UNKNOWN, message=None): + super(TTransportException, self).__init__() + self.type = type + self.message = message diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/buffered/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/buffered/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..121695dbb3aa13ad9bf0039f1d9be3faedb1d813 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/buffered/__init__.py @@ -0,0 +1,68 @@ +# -*- coding: utf-8 -*- + +from __future__ import absolute_import + +from io import BytesIO + +from thriftpy2._compat import CYTHON +from ..base import TTransportBase + + +class TBufferedTransport(TTransportBase): + """Class that wraps another transport and buffers its I/O. + + The implementation uses a (configurable) fixed-size read buffer + but buffers all writes until a flush is performed. + """ + DEFAULT_BUFFER = 4096 + + def __init__(self, trans, buf_size=DEFAULT_BUFFER): + self._trans = trans + self._wbuf = BytesIO() + self._rbuf = BytesIO(b"") + self._buf_size = buf_size + + def is_open(self): + return self._trans.is_open() + + def open(self): + return self._trans.open() + + def close(self): + return self._trans.close() + + def _read(self, sz): + ret = self._rbuf.read(sz) + + rest_len = sz - len(ret) + if rest_len == 0: + return ret + + buf = self._trans.read(max(rest_len, self._buf_size)) + ret = ret + buf[:rest_len] + buf = buf[rest_len:] + + self._rbuf = BytesIO(buf) + return ret + + def write(self, buf): + self._wbuf.write(buf) + + def flush(self): + out = self._wbuf.getvalue() + # reset wbuf before write/flush to preserve state on underlying failure + self._wbuf = BytesIO() + self._trans.write(out) + self._trans.flush() + + def getvalue(self): + return self._trans.getvalue() + + +class TBufferedTransportFactory(object): + def get_transport(self, trans): + return TBufferedTransport(trans) + + +if CYTHON: + from .cybuffered import TCyBufferedTransport, TCyBufferedTransportFactory # noqa diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/buffered/cybuffered.c b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/buffered/cybuffered.c new file mode 100644 index 0000000000000000000000000000000000000000..f5289ea8d16c6ce0e7d14463f97f496936f754f6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/buffered/cybuffered.c @@ -0,0 +1,12827 @@ +/* Generated by Cython 3.2.4 */ + +/* BEGIN: Cython Metadata +{ + "distutils": { + "name": "thriftpy2.transport.buffered.cybuffered", + "sources": [ + "thriftpy2/transport/buffered/cybuffered.pyx" + ] + }, + "module_name": "thriftpy2.transport.buffered.cybuffered" +} +END: Cython Metadata */ + +#ifndef PY_SSIZE_T_CLEAN +#define PY_SSIZE_T_CLEAN +#endif /* PY_SSIZE_T_CLEAN */ +/* InitLimitedAPI */ +#if defined(Py_LIMITED_API) + #if !defined(CYTHON_LIMITED_API) + #define CYTHON_LIMITED_API 1 + #endif +#elif defined(CYTHON_LIMITED_API) + #ifdef _MSC_VER + #pragma message ("Limited API usage is enabled with 'CYTHON_LIMITED_API' but 'Py_LIMITED_API' does not define a Python target version. Consider setting 'Py_LIMITED_API' instead.") + #else + #warning Limited API usage is enabled with 'CYTHON_LIMITED_API' but 'Py_LIMITED_API' does not define a Python target version. Consider setting 'Py_LIMITED_API' instead. + #endif +#endif + +#include "Python.h" +#ifndef Py_PYTHON_H + #error Python headers needed to compile C extensions, please install development version of Python. +#elif PY_VERSION_HEX < 0x03080000 + #error Cython requires Python 3.8+. +#else +#define __PYX_ABI_VERSION "3_2_4" +#define CYTHON_HEX_VERSION 0x030204F0 +#define CYTHON_FUTURE_DIVISION 1 +/* CModulePreamble */ +#include +#ifndef offsetof + #define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) +#endif +#if !defined(_WIN32) && !defined(WIN32) && !defined(MS_WINDOWS) + #ifndef __stdcall + #define __stdcall + #endif + #ifndef __cdecl + #define __cdecl + #endif + #ifndef __fastcall + #define __fastcall + #endif +#endif +#ifndef DL_IMPORT + #define DL_IMPORT(t) t +#endif +#ifndef DL_EXPORT + #define DL_EXPORT(t) t +#endif +#define __PYX_COMMA , +#ifndef PY_LONG_LONG + #define PY_LONG_LONG LONG_LONG +#endif +#ifndef Py_HUGE_VAL + #define Py_HUGE_VAL HUGE_VAL +#endif +#define __PYX_LIMITED_VERSION_HEX PY_VERSION_HEX +#if defined(GRAALVM_PYTHON) + /* For very preliminary testing purposes. Most variables are set the same as PyPy. + The existence of this section does not imply that anything works or is even tested */ + #define CYTHON_COMPILING_IN_PYPY 0 + #define CYTHON_COMPILING_IN_CPYTHON 0 + #define CYTHON_COMPILING_IN_LIMITED_API 0 + #define CYTHON_COMPILING_IN_GRAAL 1 + #define CYTHON_COMPILING_IN_CPYTHON_FREETHREADING 0 + #undef CYTHON_USE_TYPE_SLOTS + #define CYTHON_USE_TYPE_SLOTS 0 + #undef CYTHON_USE_TYPE_SPECS + #define CYTHON_USE_TYPE_SPECS 0 + #undef CYTHON_USE_PYTYPE_LOOKUP + #define CYTHON_USE_PYTYPE_LOOKUP 0 + #undef CYTHON_USE_PYLIST_INTERNALS + #define CYTHON_USE_PYLIST_INTERNALS 0 + #undef CYTHON_USE_UNICODE_INTERNALS + #define CYTHON_USE_UNICODE_INTERNALS 0 + #undef CYTHON_USE_UNICODE_WRITER + #define CYTHON_USE_UNICODE_WRITER 0 + #undef CYTHON_USE_PYLONG_INTERNALS + #define CYTHON_USE_PYLONG_INTERNALS 0 + #undef CYTHON_AVOID_BORROWED_REFS + #define CYTHON_AVOID_BORROWED_REFS 1 + #undef CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + #define CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS 0 + #undef CYTHON_ASSUME_SAFE_MACROS + #define CYTHON_ASSUME_SAFE_MACROS 0 + #undef CYTHON_ASSUME_SAFE_SIZE + #define CYTHON_ASSUME_SAFE_SIZE 0 + #undef CYTHON_UNPACK_METHODS + #define CYTHON_UNPACK_METHODS 0 + #undef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 0 + #undef CYTHON_FAST_GIL + #define CYTHON_FAST_GIL 0 + #undef CYTHON_METH_FASTCALL + #define CYTHON_METH_FASTCALL 0 + #undef CYTHON_FAST_PYCALL + #define CYTHON_FAST_PYCALL 0 + #ifndef CYTHON_PEP487_INIT_SUBCLASS + #define CYTHON_PEP487_INIT_SUBCLASS 1 + #endif + #undef CYTHON_PEP489_MULTI_PHASE_INIT + #define CYTHON_PEP489_MULTI_PHASE_INIT 1 + #undef CYTHON_USE_MODULE_STATE + #define CYTHON_USE_MODULE_STATE 0 + #undef CYTHON_USE_SYS_MONITORING + #define CYTHON_USE_SYS_MONITORING 0 + #undef CYTHON_USE_TP_FINALIZE + #define CYTHON_USE_TP_FINALIZE 0 + #undef CYTHON_USE_AM_SEND + #define CYTHON_USE_AM_SEND 0 + #undef CYTHON_USE_DICT_VERSIONS + #define CYTHON_USE_DICT_VERSIONS 0 + #undef CYTHON_USE_EXC_INFO_STACK + #define CYTHON_USE_EXC_INFO_STACK 1 + #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC + #define CYTHON_UPDATE_DESCRIPTOR_DOC 0 + #endif + #undef CYTHON_USE_FREELISTS + #define CYTHON_USE_FREELISTS 0 + #undef CYTHON_IMMORTAL_CONSTANTS + #define CYTHON_IMMORTAL_CONSTANTS 0 +#elif defined(PYPY_VERSION) + #define CYTHON_COMPILING_IN_PYPY 1 + #define CYTHON_COMPILING_IN_CPYTHON 0 + #define CYTHON_COMPILING_IN_LIMITED_API 0 + #define CYTHON_COMPILING_IN_GRAAL 0 + #define CYTHON_COMPILING_IN_CPYTHON_FREETHREADING 0 + #undef CYTHON_USE_TYPE_SLOTS + #define CYTHON_USE_TYPE_SLOTS 1 + #ifndef CYTHON_USE_TYPE_SPECS + #define CYTHON_USE_TYPE_SPECS 0 + #endif + #undef CYTHON_USE_PYTYPE_LOOKUP + #define CYTHON_USE_PYTYPE_LOOKUP 0 + #undef CYTHON_USE_PYLIST_INTERNALS + #define CYTHON_USE_PYLIST_INTERNALS 0 + #undef CYTHON_USE_UNICODE_INTERNALS + #define CYTHON_USE_UNICODE_INTERNALS 0 + #undef CYTHON_USE_UNICODE_WRITER + #define CYTHON_USE_UNICODE_WRITER 0 + #undef CYTHON_USE_PYLONG_INTERNALS + #define CYTHON_USE_PYLONG_INTERNALS 0 + #undef CYTHON_AVOID_BORROWED_REFS + #define CYTHON_AVOID_BORROWED_REFS 1 + #undef CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + #define CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS 1 + #undef CYTHON_ASSUME_SAFE_MACROS + #define CYTHON_ASSUME_SAFE_MACROS 0 + #ifndef CYTHON_ASSUME_SAFE_SIZE + #define CYTHON_ASSUME_SAFE_SIZE 1 + #endif + #undef CYTHON_UNPACK_METHODS + #define CYTHON_UNPACK_METHODS 0 + #undef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 0 + #undef CYTHON_FAST_GIL + #define CYTHON_FAST_GIL 0 + #undef CYTHON_METH_FASTCALL + #define CYTHON_METH_FASTCALL 0 + #undef CYTHON_FAST_PYCALL + #define CYTHON_FAST_PYCALL 0 + #ifndef CYTHON_PEP487_INIT_SUBCLASS + #define CYTHON_PEP487_INIT_SUBCLASS 1 + #endif + #if PY_VERSION_HEX < 0x03090000 + #undef CYTHON_PEP489_MULTI_PHASE_INIT + #define CYTHON_PEP489_MULTI_PHASE_INIT 0 + #elif !defined(CYTHON_PEP489_MULTI_PHASE_INIT) + #define CYTHON_PEP489_MULTI_PHASE_INIT 1 + #endif + #undef CYTHON_USE_MODULE_STATE + #define CYTHON_USE_MODULE_STATE 0 + #undef CYTHON_USE_SYS_MONITORING + #define CYTHON_USE_SYS_MONITORING 0 + #ifndef CYTHON_USE_TP_FINALIZE + #define CYTHON_USE_TP_FINALIZE (PYPY_VERSION_NUM >= 0x07030C00) + #endif + #undef CYTHON_USE_AM_SEND + #define CYTHON_USE_AM_SEND 0 + #undef CYTHON_USE_DICT_VERSIONS + #define CYTHON_USE_DICT_VERSIONS 0 + #undef CYTHON_USE_EXC_INFO_STACK + #define CYTHON_USE_EXC_INFO_STACK 0 + #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC + #define CYTHON_UPDATE_DESCRIPTOR_DOC (PYPY_VERSION_NUM >= 0x07031100) + #endif + #undef CYTHON_USE_FREELISTS + #define CYTHON_USE_FREELISTS 0 + #undef CYTHON_IMMORTAL_CONSTANTS + #define CYTHON_IMMORTAL_CONSTANTS 0 +#elif defined(CYTHON_LIMITED_API) + #ifdef Py_LIMITED_API + #undef __PYX_LIMITED_VERSION_HEX + #define __PYX_LIMITED_VERSION_HEX Py_LIMITED_API + #endif + #define CYTHON_COMPILING_IN_PYPY 0 + #define CYTHON_COMPILING_IN_CPYTHON 0 + #define CYTHON_COMPILING_IN_LIMITED_API 1 + #define CYTHON_COMPILING_IN_GRAAL 0 + #define CYTHON_COMPILING_IN_CPYTHON_FREETHREADING 0 + #undef CYTHON_USE_TYPE_SLOTS + #define CYTHON_USE_TYPE_SLOTS 0 + #undef CYTHON_USE_TYPE_SPECS + #define CYTHON_USE_TYPE_SPECS 1 + #undef CYTHON_USE_PYTYPE_LOOKUP + #define CYTHON_USE_PYTYPE_LOOKUP 0 + #undef CYTHON_USE_PYLIST_INTERNALS + #define CYTHON_USE_PYLIST_INTERNALS 0 + #undef CYTHON_USE_UNICODE_INTERNALS + #define CYTHON_USE_UNICODE_INTERNALS 0 + #ifndef CYTHON_USE_UNICODE_WRITER + #define CYTHON_USE_UNICODE_WRITER 0 + #endif + #undef CYTHON_USE_PYLONG_INTERNALS + #define CYTHON_USE_PYLONG_INTERNALS 0 + #ifndef CYTHON_AVOID_BORROWED_REFS + #define CYTHON_AVOID_BORROWED_REFS 0 + #endif + #ifndef CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + #define CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS 0 + #endif + #undef CYTHON_ASSUME_SAFE_MACROS + #define CYTHON_ASSUME_SAFE_MACROS 0 + #undef CYTHON_ASSUME_SAFE_SIZE + #define CYTHON_ASSUME_SAFE_SIZE 0 + #undef CYTHON_UNPACK_METHODS + #define CYTHON_UNPACK_METHODS 0 + #undef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 0 + #undef CYTHON_FAST_GIL + #define CYTHON_FAST_GIL 0 + #undef CYTHON_METH_FASTCALL + #define CYTHON_METH_FASTCALL (__PYX_LIMITED_VERSION_HEX >= 0x030C0000) + #undef CYTHON_FAST_PYCALL + #define CYTHON_FAST_PYCALL 0 + #ifndef CYTHON_PEP487_INIT_SUBCLASS + #define CYTHON_PEP487_INIT_SUBCLASS 1 + #endif + #ifndef CYTHON_PEP489_MULTI_PHASE_INIT + #define CYTHON_PEP489_MULTI_PHASE_INIT 1 + #endif + #ifndef CYTHON_USE_MODULE_STATE + #define CYTHON_USE_MODULE_STATE 0 + #endif + #undef CYTHON_USE_SYS_MONITORING + #define CYTHON_USE_SYS_MONITORING 0 + #ifndef CYTHON_USE_TP_FINALIZE + #define CYTHON_USE_TP_FINALIZE 0 + #endif + #ifndef CYTHON_USE_AM_SEND + #define CYTHON_USE_AM_SEND (__PYX_LIMITED_VERSION_HEX >= 0x030A0000) + #endif + #undef CYTHON_USE_DICT_VERSIONS + #define CYTHON_USE_DICT_VERSIONS 0 + #undef CYTHON_USE_EXC_INFO_STACK + #define CYTHON_USE_EXC_INFO_STACK 0 + #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC + #define CYTHON_UPDATE_DESCRIPTOR_DOC 0 + #endif + #ifndef CYTHON_USE_FREELISTS + #define CYTHON_USE_FREELISTS 1 + #endif + #undef CYTHON_IMMORTAL_CONSTANTS + #define CYTHON_IMMORTAL_CONSTANTS 0 +#else + #define CYTHON_COMPILING_IN_PYPY 0 + #define CYTHON_COMPILING_IN_CPYTHON 1 + #define CYTHON_COMPILING_IN_LIMITED_API 0 + #define CYTHON_COMPILING_IN_GRAAL 0 + #ifdef Py_GIL_DISABLED + #define CYTHON_COMPILING_IN_CPYTHON_FREETHREADING 1 + #else + #define CYTHON_COMPILING_IN_CPYTHON_FREETHREADING 0 + #endif + #if PY_VERSION_HEX < 0x030A0000 + #undef CYTHON_USE_TYPE_SLOTS + #define CYTHON_USE_TYPE_SLOTS 1 + #elif !defined(CYTHON_USE_TYPE_SLOTS) + #define CYTHON_USE_TYPE_SLOTS 1 + #endif + #ifndef CYTHON_USE_TYPE_SPECS + #define CYTHON_USE_TYPE_SPECS 0 + #endif + #ifndef CYTHON_USE_PYTYPE_LOOKUP + #define CYTHON_USE_PYTYPE_LOOKUP 1 + #endif + #ifndef CYTHON_USE_PYLONG_INTERNALS + #define CYTHON_USE_PYLONG_INTERNALS 1 + #endif + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + #undef CYTHON_USE_PYLIST_INTERNALS + #define CYTHON_USE_PYLIST_INTERNALS 0 + #elif !defined(CYTHON_USE_PYLIST_INTERNALS) + #define CYTHON_USE_PYLIST_INTERNALS 1 + #endif + #ifndef CYTHON_USE_UNICODE_INTERNALS + #define CYTHON_USE_UNICODE_INTERNALS 1 + #endif + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING || PY_VERSION_HEX >= 0x030B00A2 + #undef CYTHON_USE_UNICODE_WRITER + #define CYTHON_USE_UNICODE_WRITER 0 + #elif !defined(CYTHON_USE_UNICODE_WRITER) + #define CYTHON_USE_UNICODE_WRITER 1 + #endif + #ifndef CYTHON_AVOID_BORROWED_REFS + #define CYTHON_AVOID_BORROWED_REFS 0 + #endif + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + #undef CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + #define CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS 1 + #elif !defined(CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS) + #define CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS 0 + #endif + #ifndef CYTHON_ASSUME_SAFE_MACROS + #define CYTHON_ASSUME_SAFE_MACROS 1 + #endif + #ifndef CYTHON_ASSUME_SAFE_SIZE + #define CYTHON_ASSUME_SAFE_SIZE 1 + #endif + #ifndef CYTHON_UNPACK_METHODS + #define CYTHON_UNPACK_METHODS 1 + #endif + #ifndef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 1 + #endif + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + #undef CYTHON_FAST_GIL + #define CYTHON_FAST_GIL 0 + #elif !defined(CYTHON_FAST_GIL) + #define CYTHON_FAST_GIL (PY_VERSION_HEX < 0x030C00A6) + #endif + #ifndef CYTHON_METH_FASTCALL + #define CYTHON_METH_FASTCALL 1 + #endif + #ifndef CYTHON_FAST_PYCALL + #define CYTHON_FAST_PYCALL 1 + #endif + #ifndef CYTHON_PEP487_INIT_SUBCLASS + #define CYTHON_PEP487_INIT_SUBCLASS 1 + #endif + #ifndef CYTHON_PEP489_MULTI_PHASE_INIT + #define CYTHON_PEP489_MULTI_PHASE_INIT 1 + #endif + #ifndef CYTHON_USE_MODULE_STATE + #define CYTHON_USE_MODULE_STATE 0 + #endif + #ifndef CYTHON_USE_SYS_MONITORING + #define CYTHON_USE_SYS_MONITORING (PY_VERSION_HEX >= 0x030d00B1) + #endif + #ifndef CYTHON_USE_TP_FINALIZE + #define CYTHON_USE_TP_FINALIZE 1 + #endif + #ifndef CYTHON_USE_AM_SEND + #define CYTHON_USE_AM_SEND 1 + #endif + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + #undef CYTHON_USE_DICT_VERSIONS + #define CYTHON_USE_DICT_VERSIONS 0 + #elif !defined(CYTHON_USE_DICT_VERSIONS) + #define CYTHON_USE_DICT_VERSIONS (PY_VERSION_HEX < 0x030C00A5 && !CYTHON_USE_MODULE_STATE) + #endif + #ifndef CYTHON_USE_EXC_INFO_STACK + #define CYTHON_USE_EXC_INFO_STACK 1 + #endif + #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC + #define CYTHON_UPDATE_DESCRIPTOR_DOC 1 + #endif + #ifndef CYTHON_USE_FREELISTS + #define CYTHON_USE_FREELISTS (!CYTHON_COMPILING_IN_CPYTHON_FREETHREADING) + #endif + #if defined(CYTHON_IMMORTAL_CONSTANTS) && PY_VERSION_HEX < 0x030C0000 + #undef CYTHON_IMMORTAL_CONSTANTS + #define CYTHON_IMMORTAL_CONSTANTS 0 // definitely won't work + #elif !defined(CYTHON_IMMORTAL_CONSTANTS) + #define CYTHON_IMMORTAL_CONSTANTS (PY_VERSION_HEX >= 0x030C0000 && !CYTHON_USE_MODULE_STATE && CYTHON_COMPILING_IN_CPYTHON_FREETHREADING) + #endif +#endif +#ifndef CYTHON_COMPRESS_STRINGS + #define CYTHON_COMPRESS_STRINGS 1 +#endif +#ifndef CYTHON_FAST_PYCCALL +#define CYTHON_FAST_PYCCALL CYTHON_FAST_PYCALL +#endif +#ifndef CYTHON_VECTORCALL +#if CYTHON_COMPILING_IN_LIMITED_API +#define CYTHON_VECTORCALL (__PYX_LIMITED_VERSION_HEX >= 0x030C0000) +#else +#define CYTHON_VECTORCALL (CYTHON_FAST_PYCCALL) +#endif +#endif +#if CYTHON_USE_PYLONG_INTERNALS + #undef SHIFT + #undef BASE + #undef MASK + #ifdef SIZEOF_VOID_P + enum { __pyx_check_sizeof_voidp = 1 / (int)(SIZEOF_VOID_P == sizeof(void*)) }; + #endif +#endif +#ifndef __has_attribute + #define __has_attribute(x) 0 +#endif +#ifndef __has_cpp_attribute + #define __has_cpp_attribute(x) 0 +#endif +#ifndef CYTHON_RESTRICT + #if defined(__GNUC__) + #define CYTHON_RESTRICT __restrict__ + #elif defined(_MSC_VER) && _MSC_VER >= 1400 + #define CYTHON_RESTRICT __restrict + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_RESTRICT restrict + #else + #define CYTHON_RESTRICT + #endif +#endif +#ifndef CYTHON_UNUSED + #if defined(__cplusplus) + /* for clang __has_cpp_attribute(maybe_unused) is true even before C++17 + * but leads to warnings with -pedantic, since it is a C++17 feature */ + #if ((defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) || __cplusplus >= 201703L) + #if __has_cpp_attribute(maybe_unused) + #define CYTHON_UNUSED [[maybe_unused]] + #endif + #endif + #endif +#endif +#ifndef CYTHON_UNUSED +# if defined(__GNUC__) +# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) +# define CYTHON_UNUSED __attribute__ ((__unused__)) +# else +# define CYTHON_UNUSED +# endif +# elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) +# define CYTHON_UNUSED __attribute__ ((__unused__)) +# else +# define CYTHON_UNUSED +# endif +#endif +#ifndef CYTHON_UNUSED_VAR +# if defined(__cplusplus) + template void CYTHON_UNUSED_VAR( const T& ) { } +# else +# define CYTHON_UNUSED_VAR(x) (void)(x) +# endif +#endif +#ifndef CYTHON_MAYBE_UNUSED_VAR + #define CYTHON_MAYBE_UNUSED_VAR(x) CYTHON_UNUSED_VAR(x) +#endif +#ifndef CYTHON_NCP_UNUSED +# if CYTHON_COMPILING_IN_CPYTHON && !CYTHON_COMPILING_IN_CPYTHON_FREETHREADING +# define CYTHON_NCP_UNUSED +# else +# define CYTHON_NCP_UNUSED CYTHON_UNUSED +# endif +#endif +#ifndef CYTHON_USE_CPP_STD_MOVE + #if defined(__cplusplus) && (\ + __cplusplus >= 201103L || (defined(_MSC_VER) && _MSC_VER >= 1600)) + #define CYTHON_USE_CPP_STD_MOVE 1 + #else + #define CYTHON_USE_CPP_STD_MOVE 0 + #endif +#endif +#define __Pyx_void_to_None(void_result) ((void)(void_result), Py_INCREF(Py_None), Py_None) +#include +typedef uintptr_t __pyx_uintptr_t; +#ifndef CYTHON_FALLTHROUGH + #if defined(__cplusplus) + /* for clang __has_cpp_attribute(fallthrough) is true even before C++17 + * but leads to warnings with -pedantic, since it is a C++17 feature */ + #if ((defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) || __cplusplus >= 201703L) + #if __has_cpp_attribute(fallthrough) + #define CYTHON_FALLTHROUGH [[fallthrough]] + #endif + #endif + #ifndef CYTHON_FALLTHROUGH + #if __has_cpp_attribute(clang::fallthrough) + #define CYTHON_FALLTHROUGH [[clang::fallthrough]] + #elif __has_cpp_attribute(gnu::fallthrough) + #define CYTHON_FALLTHROUGH [[gnu::fallthrough]] + #endif + #endif + #endif + #ifndef CYTHON_FALLTHROUGH + #if __has_attribute(fallthrough) + #define CYTHON_FALLTHROUGH __attribute__((fallthrough)) + #else + #define CYTHON_FALLTHROUGH + #endif + #endif + #if defined(__clang__) && defined(__apple_build_version__) + #if __apple_build_version__ < 7000000 + #undef CYTHON_FALLTHROUGH + #define CYTHON_FALLTHROUGH + #endif + #endif +#endif +#ifndef Py_UNREACHABLE + #define Py_UNREACHABLE() assert(0); abort() +#endif +#ifdef __cplusplus + template + struct __PYX_IS_UNSIGNED_IMPL {static const bool value = T(0) < T(-1);}; + #define __PYX_IS_UNSIGNED(type) (__PYX_IS_UNSIGNED_IMPL::value) +#else + #define __PYX_IS_UNSIGNED(type) (((type)-1) > 0) +#endif +#if CYTHON_COMPILING_IN_PYPY == 1 + #define __PYX_NEED_TP_PRINT_SLOT (PY_VERSION_HEX < 0x030A0000) +#else + #define __PYX_NEED_TP_PRINT_SLOT (PY_VERSION_HEX < 0x03090000) +#endif +#define __PYX_REINTERPRET_FUNCION(func_pointer, other_pointer) ((func_pointer)(void(*)(void))(other_pointer)) + +/* CInitCode */ +#ifndef CYTHON_INLINE + #if defined(__clang__) + #define CYTHON_INLINE __inline__ __attribute__ ((__unused__)) + #elif defined(__GNUC__) + #define CYTHON_INLINE __inline__ + #elif defined(_MSC_VER) + #define CYTHON_INLINE __inline + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_INLINE inline + #else + #define CYTHON_INLINE + #endif +#endif + +/* PythonCompatibility */ +#define __PYX_BUILD_PY_SSIZE_T "n" +#define CYTHON_FORMAT_SSIZE_T "z" +#define __Pyx_BUILTIN_MODULE_NAME "builtins" +#define __Pyx_DefaultClassType PyType_Type +#if CYTHON_COMPILING_IN_LIMITED_API + #ifndef CO_OPTIMIZED + static int CO_OPTIMIZED; + #endif + #ifndef CO_NEWLOCALS + static int CO_NEWLOCALS; + #endif + #ifndef CO_VARARGS + static int CO_VARARGS; + #endif + #ifndef CO_VARKEYWORDS + static int CO_VARKEYWORDS; + #endif + #ifndef CO_ASYNC_GENERATOR + static int CO_ASYNC_GENERATOR; + #endif + #ifndef CO_GENERATOR + static int CO_GENERATOR; + #endif + #ifndef CO_COROUTINE + static int CO_COROUTINE; + #endif +#else + #ifndef CO_COROUTINE + #define CO_COROUTINE 0x80 + #endif + #ifndef CO_ASYNC_GENERATOR + #define CO_ASYNC_GENERATOR 0x200 + #endif +#endif +static int __Pyx_init_co_variables(void); +#if PY_VERSION_HEX >= 0x030900A4 || defined(Py_IS_TYPE) + #define __Pyx_IS_TYPE(ob, type) Py_IS_TYPE(ob, type) +#else + #define __Pyx_IS_TYPE(ob, type) (((const PyObject*)ob)->ob_type == (type)) +#endif +#if PY_VERSION_HEX >= 0x030A00B1 || defined(Py_Is) + #define __Pyx_Py_Is(x, y) Py_Is(x, y) +#else + #define __Pyx_Py_Is(x, y) ((x) == (y)) +#endif +#if PY_VERSION_HEX >= 0x030A00B1 || defined(Py_IsNone) + #define __Pyx_Py_IsNone(ob) Py_IsNone(ob) +#else + #define __Pyx_Py_IsNone(ob) __Pyx_Py_Is((ob), Py_None) +#endif +#if PY_VERSION_HEX >= 0x030A00B1 || defined(Py_IsTrue) + #define __Pyx_Py_IsTrue(ob) Py_IsTrue(ob) +#else + #define __Pyx_Py_IsTrue(ob) __Pyx_Py_Is((ob), Py_True) +#endif +#if PY_VERSION_HEX >= 0x030A00B1 || defined(Py_IsFalse) + #define __Pyx_Py_IsFalse(ob) Py_IsFalse(ob) +#else + #define __Pyx_Py_IsFalse(ob) __Pyx_Py_Is((ob), Py_False) +#endif +#define __Pyx_NoneAsNull(obj) (__Pyx_Py_IsNone(obj) ? NULL : (obj)) +#if PY_VERSION_HEX >= 0x030900F0 && !CYTHON_COMPILING_IN_PYPY + #define __Pyx_PyObject_GC_IsFinalized(o) PyObject_GC_IsFinalized(o) +#else + #define __Pyx_PyObject_GC_IsFinalized(o) _PyGC_FINALIZED(o) +#endif +#ifndef Py_TPFLAGS_CHECKTYPES + #define Py_TPFLAGS_CHECKTYPES 0 +#endif +#ifndef Py_TPFLAGS_HAVE_INDEX + #define Py_TPFLAGS_HAVE_INDEX 0 +#endif +#ifndef Py_TPFLAGS_HAVE_NEWBUFFER + #define Py_TPFLAGS_HAVE_NEWBUFFER 0 +#endif +#ifndef Py_TPFLAGS_HAVE_FINALIZE + #define Py_TPFLAGS_HAVE_FINALIZE 0 +#endif +#ifndef Py_TPFLAGS_SEQUENCE + #define Py_TPFLAGS_SEQUENCE 0 +#endif +#ifndef Py_TPFLAGS_MAPPING + #define Py_TPFLAGS_MAPPING 0 +#endif +#ifndef Py_TPFLAGS_IMMUTABLETYPE + #define Py_TPFLAGS_IMMUTABLETYPE (1UL << 8) +#endif +#ifndef Py_TPFLAGS_DISALLOW_INSTANTIATION + #define Py_TPFLAGS_DISALLOW_INSTANTIATION (1UL << 7) +#endif +#ifndef METH_STACKLESS + #define METH_STACKLESS 0 +#endif +#ifndef METH_FASTCALL + #ifndef METH_FASTCALL + #define METH_FASTCALL 0x80 + #endif + typedef PyObject *(*__Pyx_PyCFunctionFast) (PyObject *self, PyObject *const *args, Py_ssize_t nargs); + typedef PyObject *(*__Pyx_PyCFunctionFastWithKeywords) (PyObject *self, PyObject *const *args, + Py_ssize_t nargs, PyObject *kwnames); +#else + #if PY_VERSION_HEX >= 0x030d00A4 + # define __Pyx_PyCFunctionFast PyCFunctionFast + # define __Pyx_PyCFunctionFastWithKeywords PyCFunctionFastWithKeywords + #else + # define __Pyx_PyCFunctionFast _PyCFunctionFast + # define __Pyx_PyCFunctionFastWithKeywords _PyCFunctionFastWithKeywords + #endif +#endif +#if CYTHON_METH_FASTCALL + #define __Pyx_METH_FASTCALL METH_FASTCALL + #define __Pyx_PyCFunction_FastCall __Pyx_PyCFunctionFast + #define __Pyx_PyCFunction_FastCallWithKeywords __Pyx_PyCFunctionFastWithKeywords +#else + #define __Pyx_METH_FASTCALL METH_VARARGS + #define __Pyx_PyCFunction_FastCall PyCFunction + #define __Pyx_PyCFunction_FastCallWithKeywords PyCFunctionWithKeywords +#endif +#if CYTHON_VECTORCALL + #define __pyx_vectorcallfunc vectorcallfunc + #define __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET PY_VECTORCALL_ARGUMENTS_OFFSET + #define __Pyx_PyVectorcall_NARGS(n) PyVectorcall_NARGS((size_t)(n)) +#else + #define __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET 0 + #define __Pyx_PyVectorcall_NARGS(n) ((Py_ssize_t)(n)) +#endif +#if PY_VERSION_HEX >= 0x030900B1 +#define __Pyx_PyCFunction_CheckExact(func) PyCFunction_CheckExact(func) +#else +#define __Pyx_PyCFunction_CheckExact(func) PyCFunction_Check(func) +#endif +#define __Pyx_CyOrPyCFunction_Check(func) PyCFunction_Check(func) +#if CYTHON_COMPILING_IN_CPYTHON +#define __Pyx_CyOrPyCFunction_GET_FUNCTION(func) (((PyCFunctionObject*)(func))->m_ml->ml_meth) +#elif !CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_CyOrPyCFunction_GET_FUNCTION(func) PyCFunction_GET_FUNCTION(func) +#endif +#if CYTHON_COMPILING_IN_CPYTHON +#define __Pyx_CyOrPyCFunction_GET_FLAGS(func) (((PyCFunctionObject*)(func))->m_ml->ml_flags) +static CYTHON_INLINE PyObject* __Pyx_CyOrPyCFunction_GET_SELF(PyObject *func) { + return (__Pyx_CyOrPyCFunction_GET_FLAGS(func) & METH_STATIC) ? NULL : ((PyCFunctionObject*)func)->m_self; +} +#endif +static CYTHON_INLINE int __Pyx__IsSameCFunction(PyObject *func, void (*cfunc)(void)) { +#if CYTHON_COMPILING_IN_LIMITED_API + return PyCFunction_Check(func) && PyCFunction_GetFunction(func) == (PyCFunction) cfunc; +#else + return PyCFunction_Check(func) && PyCFunction_GET_FUNCTION(func) == (PyCFunction) cfunc; +#endif +} +#define __Pyx_IsSameCFunction(func, cfunc) __Pyx__IsSameCFunction(func, cfunc) +#if PY_VERSION_HEX < 0x03090000 || (CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000) + #define __Pyx_PyType_FromModuleAndSpec(m, s, b) ((void)m, PyType_FromSpecWithBases(s, b)) + typedef PyObject *(*__Pyx_PyCMethod)(PyObject *, PyTypeObject *, PyObject *const *, size_t, PyObject *); +#else + #define __Pyx_PyType_FromModuleAndSpec(m, s, b) PyType_FromModuleAndSpec(m, s, b) + #define __Pyx_PyCMethod PyCMethod +#endif +#ifndef METH_METHOD + #define METH_METHOD 0x200 +#endif +#if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Malloc) + #define PyObject_Malloc(s) PyMem_Malloc(s) + #define PyObject_Free(p) PyMem_Free(p) + #define PyObject_Realloc(p) PyMem_Realloc(p) +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + #define __Pyx_PyFrame_SetLineNumber(frame, lineno) +#elif CYTHON_COMPILING_IN_GRAAL && defined(GRAALPY_VERSION_NUM) && GRAALPY_VERSION_NUM > 0x19000000 + #define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0) + #define __Pyx_PyFrame_SetLineNumber(frame, lineno) GraalPyFrame_SetLineNumber((frame), (lineno)) +#elif CYTHON_COMPILING_IN_GRAAL + #define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0) + #define __Pyx_PyFrame_SetLineNumber(frame, lineno) _PyFrame_SetLineNumber((frame), (lineno)) +#else + #define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0) + #define __Pyx_PyFrame_SetLineNumber(frame, lineno) (frame)->f_lineno = (lineno) +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + #define __Pyx_PyThreadState_Current PyThreadState_Get() +#elif !CYTHON_FAST_THREAD_STATE + #define __Pyx_PyThreadState_Current PyThreadState_GET() +#elif PY_VERSION_HEX >= 0x030d00A1 + #define __Pyx_PyThreadState_Current PyThreadState_GetUnchecked() +#else + #define __Pyx_PyThreadState_Current _PyThreadState_UncheckedGet() +#endif +#if CYTHON_USE_MODULE_STATE +static CYTHON_INLINE void *__Pyx__PyModule_GetState(PyObject *op) +{ + void *result; + result = PyModule_GetState(op); + if (!result) + Py_FatalError("Couldn't find the module state"); + return result; +} +#define __Pyx_PyModule_GetState(o) (__pyx_mstatetype *)__Pyx__PyModule_GetState(o) +#else +#define __Pyx_PyModule_GetState(op) ((void)op,__pyx_mstate_global) +#endif +#define __Pyx_PyObject_GetSlot(obj, name, func_ctype) __Pyx_PyType_GetSlot(Py_TYPE((PyObject *) obj), name, func_ctype) +#define __Pyx_PyObject_TryGetSlot(obj, name, func_ctype) __Pyx_PyType_TryGetSlot(Py_TYPE(obj), name, func_ctype) +#define __Pyx_PyObject_GetSubSlot(obj, sub, name, func_ctype) __Pyx_PyType_GetSubSlot(Py_TYPE(obj), sub, name, func_ctype) +#define __Pyx_PyObject_TryGetSubSlot(obj, sub, name, func_ctype) __Pyx_PyType_TryGetSubSlot(Py_TYPE(obj), sub, name, func_ctype) +#if CYTHON_USE_TYPE_SLOTS + #define __Pyx_PyType_GetSlot(type, name, func_ctype) ((type)->name) + #define __Pyx_PyType_TryGetSlot(type, name, func_ctype) __Pyx_PyType_GetSlot(type, name, func_ctype) + #define __Pyx_PyType_GetSubSlot(type, sub, name, func_ctype) (((type)->sub) ? ((type)->sub->name) : NULL) + #define __Pyx_PyType_TryGetSubSlot(type, sub, name, func_ctype) __Pyx_PyType_GetSubSlot(type, sub, name, func_ctype) +#else + #define __Pyx_PyType_GetSlot(type, name, func_ctype) ((func_ctype) PyType_GetSlot((type), Py_##name)) + #define __Pyx_PyType_TryGetSlot(type, name, func_ctype)\ + ((__PYX_LIMITED_VERSION_HEX >= 0x030A0000 ||\ + (PyType_GetFlags(type) & Py_TPFLAGS_HEAPTYPE) || __Pyx_get_runtime_version() >= 0x030A0000) ?\ + __Pyx_PyType_GetSlot(type, name, func_ctype) : NULL) + #define __Pyx_PyType_GetSubSlot(obj, sub, name, func_ctype) __Pyx_PyType_GetSlot(obj, name, func_ctype) + #define __Pyx_PyType_TryGetSubSlot(obj, sub, name, func_ctype) __Pyx_PyType_TryGetSlot(obj, name, func_ctype) +#endif +#if CYTHON_COMPILING_IN_CPYTHON || defined(_PyDict_NewPresized) +#define __Pyx_PyDict_NewPresized(n) ((n <= 8) ? PyDict_New() : _PyDict_NewPresized(n)) +#else +#define __Pyx_PyDict_NewPresized(n) PyDict_New() +#endif +#define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) +#define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) +#if CYTHON_COMPILING_IN_CPYTHON && CYTHON_USE_UNICODE_INTERNALS +#define __Pyx_PyDict_GetItemStrWithError(dict, name) _PyDict_GetItem_KnownHash(dict, name, ((PyASCIIObject *) name)->hash) +static CYTHON_INLINE PyObject * __Pyx_PyDict_GetItemStr(PyObject *dict, PyObject *name) { + PyObject *res = __Pyx_PyDict_GetItemStrWithError(dict, name); + if (res == NULL) PyErr_Clear(); + return res; +} +#elif !CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07020000 +#define __Pyx_PyDict_GetItemStrWithError PyDict_GetItemWithError +#define __Pyx_PyDict_GetItemStr PyDict_GetItem +#else +static CYTHON_INLINE PyObject * __Pyx_PyDict_GetItemStrWithError(PyObject *dict, PyObject *name) { +#if CYTHON_COMPILING_IN_PYPY + return PyDict_GetItem(dict, name); +#else + PyDictEntry *ep; + PyDictObject *mp = (PyDictObject*) dict; + long hash = ((PyStringObject *) name)->ob_shash; + assert(hash != -1); + ep = (mp->ma_lookup)(mp, name, hash); + if (ep == NULL) { + return NULL; + } + return ep->me_value; +#endif +} +#define __Pyx_PyDict_GetItemStr PyDict_GetItem +#endif +#if CYTHON_USE_TYPE_SLOTS + #define __Pyx_PyType_GetFlags(tp) (((PyTypeObject *)tp)->tp_flags) + #define __Pyx_PyType_HasFeature(type, feature) ((__Pyx_PyType_GetFlags(type) & (feature)) != 0) +#else + #define __Pyx_PyType_GetFlags(tp) (PyType_GetFlags((PyTypeObject *)tp)) + #define __Pyx_PyType_HasFeature(type, feature) PyType_HasFeature(type, feature) +#endif +#define __Pyx_PyObject_GetIterNextFunc(iterator) __Pyx_PyObject_GetSlot(iterator, tp_iternext, iternextfunc) +#if CYTHON_USE_TYPE_SPECS +#define __Pyx_PyHeapTypeObject_GC_Del(obj) {\ + PyTypeObject *type = Py_TYPE((PyObject*)obj);\ + assert(__Pyx_PyType_HasFeature(type, Py_TPFLAGS_HEAPTYPE));\ + PyObject_GC_Del(obj);\ + Py_DECREF(type);\ +} +#else +#define __Pyx_PyHeapTypeObject_GC_Del(obj) PyObject_GC_Del(obj) +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + #define __Pyx_PyUnicode_READY(op) (0) + #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_ReadChar(u, i) + #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) ((void)u, 1114111U) + #define __Pyx_PyUnicode_KIND(u) ((void)u, (0)) + #define __Pyx_PyUnicode_DATA(u) ((void*)u) + #define __Pyx_PyUnicode_READ(k, d, i) ((void)k, PyUnicode_ReadChar((PyObject*)(d), i)) + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GetLength(u)) +#else + #if PY_VERSION_HEX >= 0x030C0000 + #define __Pyx_PyUnicode_READY(op) (0) + #else + #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ?\ + 0 : _PyUnicode_Ready((PyObject *)(op))) + #endif + #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) + #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) PyUnicode_MAX_CHAR_VALUE(u) + #define __Pyx_PyUnicode_KIND(u) ((int)PyUnicode_KIND(u)) + #define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u) + #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) + #define __Pyx_PyUnicode_WRITE(k, d, i, ch) PyUnicode_WRITE(k, d, i, (Py_UCS4) ch) + #if PY_VERSION_HEX >= 0x030C0000 + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_LENGTH(u)) + #else + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x03090000 + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : ((PyCompactUnicodeObject *)(u))->wstr_length)) + #else + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : PyUnicode_GET_SIZE(u))) + #endif + #endif +#endif +#if CYTHON_COMPILING_IN_PYPY + #define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b) +#else + #define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ?\ + PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b)) +#endif +#if CYTHON_COMPILING_IN_PYPY + #if !defined(PyUnicode_DecodeUnicodeEscape) + #define PyUnicode_DecodeUnicodeEscape(s, size, errors) PyUnicode_Decode(s, size, "unicode_escape", errors) + #endif + #if !defined(PyUnicode_Contains) + #define PyUnicode_Contains(u, s) PySequence_Contains(u, s) + #endif + #if !defined(PyByteArray_Check) + #define PyByteArray_Check(obj) PyObject_TypeCheck(obj, &PyByteArray_Type) + #endif + #if !defined(PyObject_Format) + #define PyObject_Format(obj, fmt) PyObject_CallMethod(obj, "__format__", "O", fmt) + #endif +#endif +#define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None || (PyUnicode_Check(b) && !PyUnicode_CheckExact(b)))) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + #define __Pyx_PySequence_ListKeepNew(obj)\ + (likely(PyList_CheckExact(obj) && PyUnstable_Object_IsUniquelyReferenced(obj)) ? __Pyx_NewRef(obj) : PySequence_List(obj)) +#elif CYTHON_COMPILING_IN_CPYTHON + #define __Pyx_PySequence_ListKeepNew(obj)\ + (likely(PyList_CheckExact(obj) && Py_REFCNT(obj) == 1) ? __Pyx_NewRef(obj) : PySequence_List(obj)) +#else + #define __Pyx_PySequence_ListKeepNew(obj) PySequence_List(obj) +#endif +#ifndef PySet_CheckExact + #define PySet_CheckExact(obj) __Pyx_IS_TYPE(obj, &PySet_Type) +#endif +#if PY_VERSION_HEX >= 0x030900A4 + #define __Pyx_SET_REFCNT(obj, refcnt) Py_SET_REFCNT(obj, refcnt) + #define __Pyx_SET_SIZE(obj, size) Py_SET_SIZE(obj, size) +#else + #define __Pyx_SET_REFCNT(obj, refcnt) Py_REFCNT(obj) = (refcnt) + #define __Pyx_SET_SIZE(obj, size) Py_SIZE(obj) = (size) +#endif +enum __Pyx_ReferenceSharing { + __Pyx_ReferenceSharing_DefinitelyUnique, // We created it so we know it's unshared - no need to check + __Pyx_ReferenceSharing_OwnStrongReference, + __Pyx_ReferenceSharing_FunctionArgument, + __Pyx_ReferenceSharing_SharedReference, // Never trust it to be unshared because it's a global or similar +}; +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING && PY_VERSION_HEX >= 0x030E0000 +#define __Pyx_IS_UNIQUELY_REFERENCED(o, sharing)\ + (sharing == __Pyx_ReferenceSharing_DefinitelyUnique ? 1 :\ + (sharing == __Pyx_ReferenceSharing_FunctionArgument ? PyUnstable_Object_IsUniqueReferencedTemporary(o) :\ + (sharing == __Pyx_ReferenceSharing_OwnStrongReference ? PyUnstable_Object_IsUniquelyReferenced(o) : 0))) +#elif (CYTHON_COMPILING_IN_CPYTHON && !CYTHON_COMPILING_IN_CPYTHON_FREETHREADING) || CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_IS_UNIQUELY_REFERENCED(o, sharing) (((void)sharing), Py_REFCNT(o) == 1) +#else +#define __Pyx_IS_UNIQUELY_REFERENCED(o, sharing) (((void)o), ((void)sharing), 0) +#endif +#if CYTHON_AVOID_BORROWED_REFS || CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + #if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + #define __Pyx_PyList_GetItemRef(o, i) PyList_GetItemRef(o, i) + #elif CYTHON_COMPILING_IN_LIMITED_API || !CYTHON_ASSUME_SAFE_MACROS + #define __Pyx_PyList_GetItemRef(o, i) (likely((i) >= 0) ? PySequence_GetItem(o, i) : (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL)) + #else + #define __Pyx_PyList_GetItemRef(o, i) PySequence_ITEM(o, i) + #endif +#elif CYTHON_COMPILING_IN_LIMITED_API || !CYTHON_ASSUME_SAFE_MACROS + #if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + #define __Pyx_PyList_GetItemRef(o, i) PyList_GetItemRef(o, i) + #else + #define __Pyx_PyList_GetItemRef(o, i) __Pyx_XNewRef(PyList_GetItem(o, i)) + #endif +#else + #define __Pyx_PyList_GetItemRef(o, i) __Pyx_NewRef(PyList_GET_ITEM(o, i)) +#endif +#if CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS && !CYTHON_COMPILING_IN_LIMITED_API && CYTHON_ASSUME_SAFE_MACROS + #define __Pyx_PyList_GetItemRefFast(o, i, unsafe_shared) (__Pyx_IS_UNIQUELY_REFERENCED(o, unsafe_shared) ?\ + __Pyx_NewRef(PyList_GET_ITEM(o, i)) : __Pyx_PyList_GetItemRef(o, i)) +#else + #define __Pyx_PyList_GetItemRefFast(o, i, unsafe_shared) __Pyx_PyList_GetItemRef(o, i) +#endif +#if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 +#define __Pyx_PyDict_GetItemRef(dict, key, result) PyDict_GetItemRef(dict, key, result) +#elif CYTHON_AVOID_BORROWED_REFS || CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS +static CYTHON_INLINE int __Pyx_PyDict_GetItemRef(PyObject *dict, PyObject *key, PyObject **result) { + *result = PyObject_GetItem(dict, key); + if (*result == NULL) { + if (PyErr_ExceptionMatches(PyExc_KeyError)) { + PyErr_Clear(); + return 0; + } + return -1; + } + return 1; +} +#else +static CYTHON_INLINE int __Pyx_PyDict_GetItemRef(PyObject *dict, PyObject *key, PyObject **result) { + *result = PyDict_GetItemWithError(dict, key); + if (*result == NULL) { + return PyErr_Occurred() ? -1 : 0; + } + Py_INCREF(*result); + return 1; +} +#endif +#if defined(CYTHON_DEBUG_VISIT_CONST) && CYTHON_DEBUG_VISIT_CONST + #define __Pyx_VISIT_CONST(obj) Py_VISIT(obj) +#else + #define __Pyx_VISIT_CONST(obj) +#endif +#if CYTHON_ASSUME_SAFE_MACROS + #define __Pyx_PySequence_ITEM(o, i) PySequence_ITEM(o, i) + #define __Pyx_PySequence_SIZE(seq) Py_SIZE(seq) + #define __Pyx_PyTuple_SET_ITEM(o, i, v) (PyTuple_SET_ITEM(o, i, v), (0)) + #define __Pyx_PyTuple_GET_ITEM(o, i) PyTuple_GET_ITEM(o, i) + #define __Pyx_PyList_SET_ITEM(o, i, v) (PyList_SET_ITEM(o, i, v), (0)) + #define __Pyx_PyList_GET_ITEM(o, i) PyList_GET_ITEM(o, i) +#else + #define __Pyx_PySequence_ITEM(o, i) PySequence_GetItem(o, i) + #define __Pyx_PySequence_SIZE(seq) PySequence_Size(seq) + #define __Pyx_PyTuple_SET_ITEM(o, i, v) PyTuple_SetItem(o, i, v) + #define __Pyx_PyTuple_GET_ITEM(o, i) PyTuple_GetItem(o, i) + #define __Pyx_PyList_SET_ITEM(o, i, v) PyList_SetItem(o, i, v) + #define __Pyx_PyList_GET_ITEM(o, i) PyList_GetItem(o, i) +#endif +#if CYTHON_ASSUME_SAFE_SIZE + #define __Pyx_PyTuple_GET_SIZE(o) PyTuple_GET_SIZE(o) + #define __Pyx_PyList_GET_SIZE(o) PyList_GET_SIZE(o) + #define __Pyx_PySet_GET_SIZE(o) PySet_GET_SIZE(o) + #define __Pyx_PyBytes_GET_SIZE(o) PyBytes_GET_SIZE(o) + #define __Pyx_PyByteArray_GET_SIZE(o) PyByteArray_GET_SIZE(o) + #define __Pyx_PyUnicode_GET_LENGTH(o) PyUnicode_GET_LENGTH(o) +#else + #define __Pyx_PyTuple_GET_SIZE(o) PyTuple_Size(o) + #define __Pyx_PyList_GET_SIZE(o) PyList_Size(o) + #define __Pyx_PySet_GET_SIZE(o) PySet_Size(o) + #define __Pyx_PyBytes_GET_SIZE(o) PyBytes_Size(o) + #define __Pyx_PyByteArray_GET_SIZE(o) PyByteArray_Size(o) + #define __Pyx_PyUnicode_GET_LENGTH(o) PyUnicode_GetLength(o) +#endif +#if CYTHON_COMPILING_IN_PYPY && !defined(PyUnicode_InternFromString) + #define PyUnicode_InternFromString(s) PyUnicode_FromString(s) +#endif +#define __Pyx_PyLong_FromHash_t PyLong_FromSsize_t +#define __Pyx_PyLong_AsHash_t __Pyx_PyIndex_AsSsize_t +#if __PYX_LIMITED_VERSION_HEX >= 0x030A0000 + #define __Pyx_PySendResult PySendResult +#else + typedef enum { + PYGEN_RETURN = 0, + PYGEN_ERROR = -1, + PYGEN_NEXT = 1, + } __Pyx_PySendResult; +#endif +#if CYTHON_COMPILING_IN_LIMITED_API || PY_VERSION_HEX < 0x030A00A3 + typedef __Pyx_PySendResult (*__Pyx_pyiter_sendfunc)(PyObject *iter, PyObject *value, PyObject **result); +#else + #define __Pyx_pyiter_sendfunc sendfunc +#endif +#if !CYTHON_USE_AM_SEND +#define __PYX_HAS_PY_AM_SEND 0 +#elif __PYX_LIMITED_VERSION_HEX >= 0x030A0000 +#define __PYX_HAS_PY_AM_SEND 1 +#else +#define __PYX_HAS_PY_AM_SEND 2 // our own backported implementation +#endif +#if __PYX_HAS_PY_AM_SEND < 2 + #define __Pyx_PyAsyncMethodsStruct PyAsyncMethods +#else + typedef struct { + unaryfunc am_await; + unaryfunc am_aiter; + unaryfunc am_anext; + __Pyx_pyiter_sendfunc am_send; + } __Pyx_PyAsyncMethodsStruct; + #define __Pyx_SlotTpAsAsync(s) ((PyAsyncMethods*)(s)) +#endif +#if CYTHON_USE_AM_SEND && PY_VERSION_HEX < 0x030A00F0 + #define __Pyx_TPFLAGS_HAVE_AM_SEND (1UL << 21) +#else + #define __Pyx_TPFLAGS_HAVE_AM_SEND (0) +#endif +#if PY_VERSION_HEX >= 0x03090000 +#define __Pyx_PyInterpreterState_Get() PyInterpreterState_Get() +#else +#define __Pyx_PyInterpreterState_Get() PyThreadState_Get()->interp +#endif +#if CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030A0000 +#ifdef __cplusplus +extern "C" +#endif +PyAPI_FUNC(void *) PyMem_Calloc(size_t nelem, size_t elsize); +#endif +#if CYTHON_COMPILING_IN_LIMITED_API +static int __Pyx_init_co_variable(PyObject *inspect, const char* name, int *write_to) { + int value; + PyObject *py_value = PyObject_GetAttrString(inspect, name); + if (!py_value) return 0; + value = (int) PyLong_AsLong(py_value); + Py_DECREF(py_value); + *write_to = value; + return value != -1 || !PyErr_Occurred(); +} +static int __Pyx_init_co_variables(void) { + PyObject *inspect; + int result; + inspect = PyImport_ImportModule("inspect"); + result = +#if !defined(CO_OPTIMIZED) + __Pyx_init_co_variable(inspect, "CO_OPTIMIZED", &CO_OPTIMIZED) && +#endif +#if !defined(CO_NEWLOCALS) + __Pyx_init_co_variable(inspect, "CO_NEWLOCALS", &CO_NEWLOCALS) && +#endif +#if !defined(CO_VARARGS) + __Pyx_init_co_variable(inspect, "CO_VARARGS", &CO_VARARGS) && +#endif +#if !defined(CO_VARKEYWORDS) + __Pyx_init_co_variable(inspect, "CO_VARKEYWORDS", &CO_VARKEYWORDS) && +#endif +#if !defined(CO_ASYNC_GENERATOR) + __Pyx_init_co_variable(inspect, "CO_ASYNC_GENERATOR", &CO_ASYNC_GENERATOR) && +#endif +#if !defined(CO_GENERATOR) + __Pyx_init_co_variable(inspect, "CO_GENERATOR", &CO_GENERATOR) && +#endif +#if !defined(CO_COROUTINE) + __Pyx_init_co_variable(inspect, "CO_COROUTINE", &CO_COROUTINE) && +#endif + 1; + Py_DECREF(inspect); + return result ? 0 : -1; +} +#else +static int __Pyx_init_co_variables(void) { + return 0; // It's a limited API-only feature +} +#endif + +/* MathInitCode */ +#if defined(_WIN32) || defined(WIN32) || defined(MS_WINDOWS) + #ifndef _USE_MATH_DEFINES + #define _USE_MATH_DEFINES + #endif +#endif +#include +#if defined(__CYGWIN__) && defined(_LDBL_EQ_DBL) +#define __Pyx_truncl trunc +#else +#define __Pyx_truncl truncl +#endif + +#ifndef CYTHON_CLINE_IN_TRACEBACK_RUNTIME +#define CYTHON_CLINE_IN_TRACEBACK_RUNTIME 0 +#endif +#ifndef CYTHON_CLINE_IN_TRACEBACK +#define CYTHON_CLINE_IN_TRACEBACK CYTHON_CLINE_IN_TRACEBACK_RUNTIME +#endif +#if CYTHON_CLINE_IN_TRACEBACK +#define __PYX_MARK_ERR_POS(f_index, lineno) { __pyx_filename = __pyx_f[f_index]; (void) __pyx_filename; __pyx_lineno = lineno; (void) __pyx_lineno; __pyx_clineno = __LINE__; (void) __pyx_clineno; } +#else +#define __PYX_MARK_ERR_POS(f_index, lineno) { __pyx_filename = __pyx_f[f_index]; (void) __pyx_filename; __pyx_lineno = lineno; (void) __pyx_lineno; (void) __pyx_clineno; } +#endif +#define __PYX_ERR(f_index, lineno, Ln_error) \ + { __PYX_MARK_ERR_POS(f_index, lineno) goto Ln_error; } + +#ifdef CYTHON_EXTERN_C + #undef __PYX_EXTERN_C + #define __PYX_EXTERN_C CYTHON_EXTERN_C +#elif defined(__PYX_EXTERN_C) + #ifdef _MSC_VER + #pragma message ("Please do not define the '__PYX_EXTERN_C' macro externally. Use 'CYTHON_EXTERN_C' instead.") + #else + #warning Please do not define the '__PYX_EXTERN_C' macro externally. Use 'CYTHON_EXTERN_C' instead. + #endif +#else + #ifdef __cplusplus + #define __PYX_EXTERN_C extern "C" + #else + #define __PYX_EXTERN_C extern + #endif +#endif + +#define __PYX_HAVE__thriftpy2__transport__buffered__cybuffered +#define __PYX_HAVE_API__thriftpy2__transport__buffered__cybuffered +/* Early includes */ +#ifdef _OPENMP +#include +#endif /* _OPENMP */ + +#if defined(PYREX_WITHOUT_ASSERTIONS) && !defined(CYTHON_WITHOUT_ASSERTIONS) +#define CYTHON_WITHOUT_ASSERTIONS +#endif + +#ifdef CYTHON_FREETHREADING_COMPATIBLE +#if CYTHON_FREETHREADING_COMPATIBLE +#define __Pyx_FREETHREADING_COMPATIBLE Py_MOD_GIL_NOT_USED +#else +#define __Pyx_FREETHREADING_COMPATIBLE Py_MOD_GIL_USED +#endif +#else +#define __Pyx_FREETHREADING_COMPATIBLE Py_MOD_GIL_NOT_USED +#endif +#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 +#define __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 0 +#define __PYX_DEFAULT_STRING_ENCODING "" +#define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString +#define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#define __Pyx_uchar_cast(c) ((unsigned char)c) +#define __Pyx_long_cast(x) ((long)x) +#define __Pyx_fits_Py_ssize_t(v, type, is_signed) (\ + (sizeof(type) < sizeof(Py_ssize_t)) ||\ + (sizeof(type) > sizeof(Py_ssize_t) &&\ + likely(v < (type)PY_SSIZE_T_MAX ||\ + v == (type)PY_SSIZE_T_MAX) &&\ + (!is_signed || likely(v > (type)PY_SSIZE_T_MIN ||\ + v == (type)PY_SSIZE_T_MIN))) ||\ + (sizeof(type) == sizeof(Py_ssize_t) &&\ + (is_signed || likely(v < (type)PY_SSIZE_T_MAX ||\ + v == (type)PY_SSIZE_T_MAX))) ) +static CYTHON_INLINE int __Pyx_is_valid_index(Py_ssize_t i, Py_ssize_t limit) { + return (size_t) i < (size_t) limit; +} +#if defined (__cplusplus) && __cplusplus >= 201103L + #include + #define __Pyx_sst_abs(value) std::abs(value) +#elif SIZEOF_INT >= SIZEOF_SIZE_T + #define __Pyx_sst_abs(value) abs(value) +#elif SIZEOF_LONG >= SIZEOF_SIZE_T + #define __Pyx_sst_abs(value) labs(value) +#elif defined (_MSC_VER) + #define __Pyx_sst_abs(value) ((Py_ssize_t)_abs64(value)) +#elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define __Pyx_sst_abs(value) llabs(value) +#elif defined (__GNUC__) + #define __Pyx_sst_abs(value) __builtin_llabs(value) +#else + #define __Pyx_sst_abs(value) ((value<0) ? -value : value) +#endif +static CYTHON_INLINE Py_ssize_t __Pyx_ssize_strlen(const char *s); +static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject*); +static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); +static CYTHON_INLINE PyObject* __Pyx_PyByteArray_FromString(const char*); +#define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l) +#define __Pyx_PyBytes_FromString PyBytes_FromString +#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char*); +#if CYTHON_ASSUME_SAFE_MACROS + #define __Pyx_PyBytes_AsWritableString(s) ((char*) PyBytes_AS_STRING(s)) + #define __Pyx_PyBytes_AsWritableSString(s) ((signed char*) PyBytes_AS_STRING(s)) + #define __Pyx_PyBytes_AsWritableUString(s) ((unsigned char*) PyBytes_AS_STRING(s)) + #define __Pyx_PyBytes_AsString(s) ((const char*) PyBytes_AS_STRING(s)) + #define __Pyx_PyBytes_AsSString(s) ((const signed char*) PyBytes_AS_STRING(s)) + #define __Pyx_PyBytes_AsUString(s) ((const unsigned char*) PyBytes_AS_STRING(s)) + #define __Pyx_PyByteArray_AsString(s) PyByteArray_AS_STRING(s) +#else + #define __Pyx_PyBytes_AsWritableString(s) ((char*) PyBytes_AsString(s)) + #define __Pyx_PyBytes_AsWritableSString(s) ((signed char*) PyBytes_AsString(s)) + #define __Pyx_PyBytes_AsWritableUString(s) ((unsigned char*) PyBytes_AsString(s)) + #define __Pyx_PyBytes_AsString(s) ((const char*) PyBytes_AsString(s)) + #define __Pyx_PyBytes_AsSString(s) ((const signed char*) PyBytes_AsString(s)) + #define __Pyx_PyBytes_AsUString(s) ((const unsigned char*) PyBytes_AsString(s)) + #define __Pyx_PyByteArray_AsString(s) PyByteArray_AsString(s) +#endif +#define __Pyx_PyObject_AsWritableString(s) ((char*)(__pyx_uintptr_t) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsWritableSString(s) ((signed char*)(__pyx_uintptr_t) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsWritableUString(s) ((unsigned char*)(__pyx_uintptr_t) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsSString(s) ((const signed char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsUString(s) ((const unsigned char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_FromCString(s) __Pyx_PyObject_FromString((const char*)s) +#define __Pyx_PyBytes_FromCString(s) __Pyx_PyBytes_FromString((const char*)s) +#define __Pyx_PyByteArray_FromCString(s) __Pyx_PyByteArray_FromString((const char*)s) +#define __Pyx_PyUnicode_FromCString(s) __Pyx_PyUnicode_FromString((const char*)s) +#define __Pyx_PyUnicode_FromOrdinal(o) PyUnicode_FromOrdinal((int)o) +#define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode +static CYTHON_INLINE PyObject *__Pyx_NewRef(PyObject *obj) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030a0000 || defined(Py_NewRef) + return Py_NewRef(obj); +#else + Py_INCREF(obj); + return obj; +#endif +} +static CYTHON_INLINE PyObject *__Pyx_XNewRef(PyObject *obj) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030a0000 || defined(Py_XNewRef) + return Py_XNewRef(obj); +#else + Py_XINCREF(obj); + return obj; +#endif +} +static CYTHON_INLINE PyObject *__Pyx_Owned_Py_None(int b); +static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b); +static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); +static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject*); +static CYTHON_INLINE PyObject* __Pyx_PyNumber_Long(PyObject* x); +#define __Pyx_PySequence_Tuple(obj)\ + (likely(PyTuple_CheckExact(obj)) ? __Pyx_NewRef(obj) : PySequence_Tuple(obj)) +static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); +static CYTHON_INLINE PyObject * __Pyx_PyLong_FromSize_t(size_t); +static CYTHON_INLINE Py_hash_t __Pyx_PyIndex_AsHash_t(PyObject*); +#if CYTHON_ASSUME_SAFE_MACROS +#define __Pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) +#define __Pyx_PyFloat_AS_DOUBLE(x) PyFloat_AS_DOUBLE(x) +#else +#define __Pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) +#define __Pyx_PyFloat_AS_DOUBLE(x) PyFloat_AsDouble(x) +#endif +#define __Pyx_PyFloat_AsFloat(x) ((float) __Pyx_PyFloat_AsDouble(x)) +#define __Pyx_PyNumber_Int(x) (PyLong_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Long(x)) +#if CYTHON_USE_PYLONG_INTERNALS + #if PY_VERSION_HEX >= 0x030C00A7 + #ifndef _PyLong_SIGN_MASK + #define _PyLong_SIGN_MASK 3 + #endif + #ifndef _PyLong_NON_SIZE_BITS + #define _PyLong_NON_SIZE_BITS 3 + #endif + #define __Pyx_PyLong_Sign(x) (((PyLongObject*)x)->long_value.lv_tag & _PyLong_SIGN_MASK) + #define __Pyx_PyLong_IsNeg(x) ((__Pyx_PyLong_Sign(x) & 2) != 0) + #define __Pyx_PyLong_IsNonNeg(x) (!__Pyx_PyLong_IsNeg(x)) + #define __Pyx_PyLong_IsZero(x) (__Pyx_PyLong_Sign(x) & 1) + #define __Pyx_PyLong_IsPos(x) (__Pyx_PyLong_Sign(x) == 0) + #define __Pyx_PyLong_CompactValueUnsigned(x) (__Pyx_PyLong_Digits(x)[0]) + #define __Pyx_PyLong_DigitCount(x) ((Py_ssize_t) (((PyLongObject*)x)->long_value.lv_tag >> _PyLong_NON_SIZE_BITS)) + #define __Pyx_PyLong_SignedDigitCount(x)\ + ((1 - (Py_ssize_t) __Pyx_PyLong_Sign(x)) * __Pyx_PyLong_DigitCount(x)) + #if defined(PyUnstable_Long_IsCompact) && defined(PyUnstable_Long_CompactValue) + #define __Pyx_PyLong_IsCompact(x) PyUnstable_Long_IsCompact((PyLongObject*) x) + #define __Pyx_PyLong_CompactValue(x) PyUnstable_Long_CompactValue((PyLongObject*) x) + #else + #define __Pyx_PyLong_IsCompact(x) (((PyLongObject*)x)->long_value.lv_tag < (2 << _PyLong_NON_SIZE_BITS)) + #define __Pyx_PyLong_CompactValue(x) ((1 - (Py_ssize_t) __Pyx_PyLong_Sign(x)) * (Py_ssize_t) __Pyx_PyLong_Digits(x)[0]) + #endif + typedef Py_ssize_t __Pyx_compact_pylong; + typedef size_t __Pyx_compact_upylong; + #else + #define __Pyx_PyLong_IsNeg(x) (Py_SIZE(x) < 0) + #define __Pyx_PyLong_IsNonNeg(x) (Py_SIZE(x) >= 0) + #define __Pyx_PyLong_IsZero(x) (Py_SIZE(x) == 0) + #define __Pyx_PyLong_IsPos(x) (Py_SIZE(x) > 0) + #define __Pyx_PyLong_CompactValueUnsigned(x) ((Py_SIZE(x) == 0) ? 0 : __Pyx_PyLong_Digits(x)[0]) + #define __Pyx_PyLong_DigitCount(x) __Pyx_sst_abs(Py_SIZE(x)) + #define __Pyx_PyLong_SignedDigitCount(x) Py_SIZE(x) + #define __Pyx_PyLong_IsCompact(x) (Py_SIZE(x) == 0 || Py_SIZE(x) == 1 || Py_SIZE(x) == -1) + #define __Pyx_PyLong_CompactValue(x)\ + ((Py_SIZE(x) == 0) ? (sdigit) 0 : ((Py_SIZE(x) < 0) ? -(sdigit)__Pyx_PyLong_Digits(x)[0] : (sdigit)__Pyx_PyLong_Digits(x)[0])) + typedef sdigit __Pyx_compact_pylong; + typedef digit __Pyx_compact_upylong; + #endif + #if PY_VERSION_HEX >= 0x030C00A5 + #define __Pyx_PyLong_Digits(x) (((PyLongObject*)x)->long_value.ob_digit) + #else + #define __Pyx_PyLong_Digits(x) (((PyLongObject*)x)->ob_digit) + #endif +#endif +#if __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 + #define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) +#elif __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + #define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeASCII(c_str, size, NULL) +#else + #define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) +#endif + + +/* Test for GCC > 2.95 */ +#if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))) + #define likely(x) __builtin_expect(!!(x), 1) + #define unlikely(x) __builtin_expect(!!(x), 0) +#else /* !__GNUC__ or GCC < 2.95 */ + #define likely(x) (x) + #define unlikely(x) (x) +#endif /* __GNUC__ */ +/* PretendToInitialize */ +#ifdef __cplusplus +#if __cplusplus > 201103L +#include +#endif +template +static void __Pyx_pretend_to_initialize(T* ptr) { +#if __cplusplus > 201103L + if ((std::is_trivially_default_constructible::value)) +#endif + *ptr = T(); + (void)ptr; +} +#else +static CYTHON_INLINE void __Pyx_pretend_to_initialize(void* ptr) { (void)ptr; } +#endif + + +#if !CYTHON_USE_MODULE_STATE +static PyObject *__pyx_m = NULL; +#endif +static int __pyx_lineno; +static int __pyx_clineno = 0; +static const char * const __pyx_cfilenm = __FILE__; +static const char *__pyx_filename; + +/* #### Code section: filename_table ### */ + +static const char* const __pyx_f[] = { + "thriftpy2/transport/buffered/cybuffered.pyx", + "", + "thriftpy2/transport/cybase.pxd", +}; +/* #### Code section: utility_code_proto_before_types ### */ +/* Atomics.proto (used by UnpackUnboundCMethod) */ +#include +#ifndef CYTHON_ATOMICS + #define CYTHON_ATOMICS 1 +#endif +#define __PYX_CYTHON_ATOMICS_ENABLED() CYTHON_ATOMICS +#define __PYX_GET_CYTHON_COMPILING_IN_CPYTHON_FREETHREADING() CYTHON_COMPILING_IN_CPYTHON_FREETHREADING +#define __pyx_atomic_int_type int +#define __pyx_nonatomic_int_type int +#if CYTHON_ATOMICS && (defined(__STDC_VERSION__) &&\ + (__STDC_VERSION__ >= 201112L) &&\ + !defined(__STDC_NO_ATOMICS__)) + #include +#elif CYTHON_ATOMICS && (defined(__cplusplus) && (\ + (__cplusplus >= 201103L) ||\ + (defined(_MSC_VER) && _MSC_VER >= 1700))) + #include +#endif +#if CYTHON_ATOMICS && (defined(__STDC_VERSION__) &&\ + (__STDC_VERSION__ >= 201112L) &&\ + !defined(__STDC_NO_ATOMICS__) &&\ + ATOMIC_INT_LOCK_FREE == 2) + #undef __pyx_atomic_int_type + #define __pyx_atomic_int_type atomic_int + #define __pyx_atomic_ptr_type atomic_uintptr_t + #define __pyx_nonatomic_ptr_type uintptr_t + #define __pyx_atomic_incr_relaxed(value) atomic_fetch_add_explicit(value, 1, memory_order_relaxed) + #define __pyx_atomic_incr_acq_rel(value) atomic_fetch_add_explicit(value, 1, memory_order_acq_rel) + #define __pyx_atomic_decr_acq_rel(value) atomic_fetch_sub_explicit(value, 1, memory_order_acq_rel) + #define __pyx_atomic_sub(value, arg) atomic_fetch_sub(value, arg) + #define __pyx_atomic_int_cmp_exchange(value, expected, desired) atomic_compare_exchange_strong(value, expected, desired) + #define __pyx_atomic_load(value) atomic_load(value) + #define __pyx_atomic_store(value, new_value) atomic_store(value, new_value) + #define __pyx_atomic_pointer_load_relaxed(value) atomic_load_explicit(value, memory_order_relaxed) + #define __pyx_atomic_pointer_load_acquire(value) atomic_load_explicit(value, memory_order_acquire) + #define __pyx_atomic_pointer_exchange(value, new_value) atomic_exchange(value, (__pyx_nonatomic_ptr_type)new_value) + #define __pyx_atomic_pointer_cmp_exchange(value, expected, desired) atomic_compare_exchange_strong(value, expected, desired) + #if defined(__PYX_DEBUG_ATOMICS) && defined(_MSC_VER) + #pragma message ("Using standard C atomics") + #elif defined(__PYX_DEBUG_ATOMICS) + #warning "Using standard C atomics" + #endif +#elif CYTHON_ATOMICS && (defined(__cplusplus) && (\ + (__cplusplus >= 201103L) ||\ +\ + (defined(_MSC_VER) && _MSC_VER >= 1700)) &&\ + ATOMIC_INT_LOCK_FREE == 2) + #undef __pyx_atomic_int_type + #define __pyx_atomic_int_type std::atomic_int + #define __pyx_atomic_ptr_type std::atomic_uintptr_t + #define __pyx_nonatomic_ptr_type uintptr_t + #define __pyx_atomic_incr_relaxed(value) std::atomic_fetch_add_explicit(value, 1, std::memory_order_relaxed) + #define __pyx_atomic_incr_acq_rel(value) std::atomic_fetch_add_explicit(value, 1, std::memory_order_acq_rel) + #define __pyx_atomic_decr_acq_rel(value) std::atomic_fetch_sub_explicit(value, 1, std::memory_order_acq_rel) + #define __pyx_atomic_sub(value, arg) std::atomic_fetch_sub(value, arg) + #define __pyx_atomic_int_cmp_exchange(value, expected, desired) std::atomic_compare_exchange_strong(value, expected, desired) + #define __pyx_atomic_load(value) std::atomic_load(value) + #define __pyx_atomic_store(value, new_value) std::atomic_store(value, new_value) + #define __pyx_atomic_pointer_load_relaxed(value) std::atomic_load_explicit(value, std::memory_order_relaxed) + #define __pyx_atomic_pointer_load_acquire(value) std::atomic_load_explicit(value, std::memory_order_acquire) + #define __pyx_atomic_pointer_exchange(value, new_value) std::atomic_exchange(value, (__pyx_nonatomic_ptr_type)new_value) + #define __pyx_atomic_pointer_cmp_exchange(value, expected, desired) std::atomic_compare_exchange_strong(value, expected, desired) + #if defined(__PYX_DEBUG_ATOMICS) && defined(_MSC_VER) + #pragma message ("Using standard C++ atomics") + #elif defined(__PYX_DEBUG_ATOMICS) + #warning "Using standard C++ atomics" + #endif +#elif CYTHON_ATOMICS && (__GNUC__ >= 5 || (__GNUC__ == 4 &&\ + (__GNUC_MINOR__ > 1 ||\ + (__GNUC_MINOR__ == 1 && __GNUC_PATCHLEVEL__ >= 2)))) + #define __pyx_atomic_ptr_type void* + #define __pyx_nonatomic_ptr_type void* + #define __pyx_atomic_incr_relaxed(value) __sync_fetch_and_add(value, 1) + #define __pyx_atomic_incr_acq_rel(value) __sync_fetch_and_add(value, 1) + #define __pyx_atomic_decr_acq_rel(value) __sync_fetch_and_sub(value, 1) + #define __pyx_atomic_sub(value, arg) __sync_fetch_and_sub(value, arg) + static CYTHON_INLINE int __pyx_atomic_int_cmp_exchange(__pyx_atomic_int_type* value, __pyx_nonatomic_int_type* expected, __pyx_nonatomic_int_type desired) { + __pyx_nonatomic_int_type old = __sync_val_compare_and_swap(value, *expected, desired); + int result = old == *expected; + *expected = old; + return result; + } + #define __pyx_atomic_load(value) __sync_fetch_and_add(value, 0) + #define __pyx_atomic_store(value, new_value) __sync_lock_test_and_set(value, new_value) + #define __pyx_atomic_pointer_load_relaxed(value) __sync_fetch_and_add(value, 0) + #define __pyx_atomic_pointer_load_acquire(value) __sync_fetch_and_add(value, 0) + #define __pyx_atomic_pointer_exchange(value, new_value) __sync_lock_test_and_set(value, (__pyx_atomic_ptr_type)new_value) + static CYTHON_INLINE int __pyx_atomic_pointer_cmp_exchange(__pyx_atomic_ptr_type* value, __pyx_nonatomic_ptr_type* expected, __pyx_nonatomic_ptr_type desired) { + __pyx_nonatomic_ptr_type old = __sync_val_compare_and_swap(value, *expected, desired); + int result = old == *expected; + *expected = old; + return result; + } + #ifdef __PYX_DEBUG_ATOMICS + #warning "Using GNU atomics" + #endif +#elif CYTHON_ATOMICS && defined(_MSC_VER) + #include + #undef __pyx_atomic_int_type + #define __pyx_atomic_int_type long + #define __pyx_atomic_ptr_type void* + #undef __pyx_nonatomic_int_type + #define __pyx_nonatomic_int_type long + #define __pyx_nonatomic_ptr_type void* + #pragma intrinsic (_InterlockedExchangeAdd, _InterlockedExchange, _InterlockedCompareExchange, _InterlockedCompareExchangePointer, _InterlockedExchangePointer) + #define __pyx_atomic_incr_relaxed(value) _InterlockedExchangeAdd(value, 1) + #define __pyx_atomic_incr_acq_rel(value) _InterlockedExchangeAdd(value, 1) + #define __pyx_atomic_decr_acq_rel(value) _InterlockedExchangeAdd(value, -1) + #define __pyx_atomic_sub(value, arg) _InterlockedExchangeAdd(value, -arg) + static CYTHON_INLINE int __pyx_atomic_int_cmp_exchange(__pyx_atomic_int_type* value, __pyx_nonatomic_int_type* expected, __pyx_nonatomic_int_type desired) { + __pyx_nonatomic_int_type old = _InterlockedCompareExchange(value, desired, *expected); + int result = old == *expected; + *expected = old; + return result; + } + #define __pyx_atomic_load(value) _InterlockedExchangeAdd(value, 0) + #define __pyx_atomic_store(value, new_value) _InterlockedExchange(value, new_value) + #define __pyx_atomic_pointer_load_relaxed(value) *(void * volatile *)value + #define __pyx_atomic_pointer_load_acquire(value) _InterlockedCompareExchangePointer(value, 0, 0) + #define __pyx_atomic_pointer_exchange(value, new_value) _InterlockedExchangePointer(value, (__pyx_atomic_ptr_type)new_value) + static CYTHON_INLINE int __pyx_atomic_pointer_cmp_exchange(__pyx_atomic_ptr_type* value, __pyx_nonatomic_ptr_type* expected, __pyx_nonatomic_ptr_type desired) { + __pyx_atomic_ptr_type old = _InterlockedCompareExchangePointer(value, desired, *expected); + int result = old == *expected; + *expected = old; + return result; + } + #ifdef __PYX_DEBUG_ATOMICS + #pragma message ("Using MSVC atomics") + #endif +#else + #undef CYTHON_ATOMICS + #define CYTHON_ATOMICS 0 + #ifdef __PYX_DEBUG_ATOMICS + #warning "Not using atomics" + #endif +#endif + +/* CriticalSectionsDefinition.proto (used by CriticalSections) */ +#if !CYTHON_COMPILING_IN_CPYTHON_FREETHREADING +#define __Pyx_PyCriticalSection void* +#define __Pyx_PyCriticalSection2 void* +#define __Pyx_PyCriticalSection_End(cs) +#define __Pyx_PyCriticalSection2_End(cs) +#else +#define __Pyx_PyCriticalSection PyCriticalSection +#define __Pyx_PyCriticalSection2 PyCriticalSection2 +#define __Pyx_PyCriticalSection_End PyCriticalSection_End +#define __Pyx_PyCriticalSection2_End PyCriticalSection2_End +#endif + +/* CriticalSections.proto (used by ParseKeywordsImpl) */ +#if !CYTHON_COMPILING_IN_CPYTHON_FREETHREADING +#define __Pyx_PyCriticalSection_Begin(cs, arg) (void)(cs) +#define __Pyx_PyCriticalSection2_Begin(cs, arg1, arg2) (void)(cs) +#else +#define __Pyx_PyCriticalSection_Begin PyCriticalSection_Begin +#define __Pyx_PyCriticalSection2_Begin PyCriticalSection2_Begin +#endif +#if PY_VERSION_HEX < 0x030d0000 || CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_BEGIN_CRITICAL_SECTION(o) { +#define __Pyx_END_CRITICAL_SECTION() } +#else +#define __Pyx_BEGIN_CRITICAL_SECTION Py_BEGIN_CRITICAL_SECTION +#define __Pyx_END_CRITICAL_SECTION Py_END_CRITICAL_SECTION +#endif + +/* IncludeStructmemberH.proto (used by FixUpExtensionType) */ +#include + +/* #### Code section: numeric_typedefs ### */ +/* #### Code section: complex_type_declarations ### */ +/* #### Code section: type_declarations ### */ + +/*--- Type declarations ---*/ +struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer; +struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase; +struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport; + +/* "thriftpy2/transport/cybase.pxd":3 + * # cython: freethreading_compatible = True + * + * cdef enum: # <<<<<<<<<<<<<< + * DEFAULT_BUFFER = 4096 + * STACK_STRING_LEN = 4096 +*/ +enum { + __pyx_e_9thriftpy2_9transport_6cybase_DEFAULT_BUFFER = 0x1000, + __pyx_e_9thriftpy2_9transport_6cybase_STACK_STRING_LEN = 0x1000 +}; + +/* "thriftpy2/transport/cybase.pxd":7 + * STACK_STRING_LEN = 4096 + * + * cdef class TCyBuffer(object): # <<<<<<<<<<<<<< + * cdef: + * char *buf +*/ +struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer { + PyObject_HEAD + struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_TCyBuffer *__pyx_vtab; + char *buf; + int cur; + int buf_size; + int data_size; +}; + + +/* "thriftpy2/transport/cybase.pxd":19 + * + * + * cdef class CyTransportBase(object): # <<<<<<<<<<<<<< + * cdef object trans + * +*/ +struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase { + PyObject_HEAD + struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_CyTransportBase *__pyx_vtab; + PyObject *trans; +}; + + +/* "thriftpy2/transport/buffered/cybuffered.pyx":14 + * + * + * cdef class TCyBufferedTransport(CyTransportBase): # <<<<<<<<<<<<<< + * """binary reader/writer""" + * +*/ +struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport { + struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase __pyx_base; + struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *rbuf; + struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *wbuf; +}; + + + +/* "thriftpy2/transport/cybase.pxd":7 + * STACK_STRING_LEN = 4096 + * + * cdef class TCyBuffer(object): # <<<<<<<<<<<<<< + * cdef: + * char *buf +*/ + +struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_TCyBuffer { + void (*move_to_start)(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *); + void (*clean)(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *); + int (*write)(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *, int, char const *); + int (*grow)(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *, int); + PyObject *(*read_trans)(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *, PyObject *, int, char *); +}; +static struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_TCyBuffer *__pyx_vtabptr_9thriftpy2_9transport_6cybase_TCyBuffer; + + +/* "thriftpy2/transport/cybase.pxd":19 + * + * + * cdef class CyTransportBase(object): # <<<<<<<<<<<<<< + * cdef object trans + * +*/ + +struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_CyTransportBase { + PyObject *(*c_read)(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *, int, char *); + PyObject *(*c_write)(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *, char *, int); + PyObject *(*c_flush)(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *); + PyObject *(*get_string)(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *, int); +}; +static struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_CyTransportBase *__pyx_vtabptr_9thriftpy2_9transport_6cybase_CyTransportBase; + + +/* "thriftpy2/transport/buffered/cybuffered.pyx":14 + * + * + * cdef class TCyBufferedTransport(CyTransportBase): # <<<<<<<<<<<<<< + * """binary reader/writer""" + * +*/ + +struct __pyx_vtabstruct_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport { + struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_CyTransportBase __pyx_base; + PyObject *(*read_trans)(struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *, int, char *); + PyObject *(*c_dump_wbuf)(struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *); +}; +static struct __pyx_vtabstruct_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *__pyx_vtabptr_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport; +/* #### Code section: utility_code_proto ### */ + +/* --- Runtime support code (head) --- */ +/* Refnanny.proto */ +#ifndef CYTHON_REFNANNY + #define CYTHON_REFNANNY 0 +#endif +#if CYTHON_REFNANNY + typedef struct { + void (*INCREF)(void*, PyObject*, Py_ssize_t); + void (*DECREF)(void*, PyObject*, Py_ssize_t); + void (*GOTREF)(void*, PyObject*, Py_ssize_t); + void (*GIVEREF)(void*, PyObject*, Py_ssize_t); + void* (*SetupContext)(const char*, Py_ssize_t, const char*); + void (*FinishContext)(void**); + } __Pyx_RefNannyAPIStruct; + static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; + static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); + #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; + #define __Pyx_RefNannySetupContext(name, acquire_gil)\ + if (acquire_gil) {\ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), (__LINE__), (__FILE__));\ + PyGILState_Release(__pyx_gilstate_save);\ + } else {\ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), (__LINE__), (__FILE__));\ + } + #define __Pyx_RefNannyFinishContextNogil() {\ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ + __Pyx_RefNannyFinishContext();\ + PyGILState_Release(__pyx_gilstate_save);\ + } + #define __Pyx_RefNannyFinishContextNogil() {\ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ + __Pyx_RefNannyFinishContext();\ + PyGILState_Release(__pyx_gilstate_save);\ + } + #define __Pyx_RefNannyFinishContext()\ + __Pyx_RefNanny->FinishContext(&__pyx_refnanny) + #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), (__LINE__)) + #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), (__LINE__)) + #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), (__LINE__)) + #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), (__LINE__)) + #define __Pyx_XINCREF(r) do { if((r) == NULL); else {__Pyx_INCREF(r); }} while(0) + #define __Pyx_XDECREF(r) do { if((r) == NULL); else {__Pyx_DECREF(r); }} while(0) + #define __Pyx_XGOTREF(r) do { if((r) == NULL); else {__Pyx_GOTREF(r); }} while(0) + #define __Pyx_XGIVEREF(r) do { if((r) == NULL); else {__Pyx_GIVEREF(r);}} while(0) +#else + #define __Pyx_RefNannyDeclarations + #define __Pyx_RefNannySetupContext(name, acquire_gil) + #define __Pyx_RefNannyFinishContextNogil() + #define __Pyx_RefNannyFinishContext() + #define __Pyx_INCREF(r) Py_INCREF(r) + #define __Pyx_DECREF(r) Py_DECREF(r) + #define __Pyx_GOTREF(r) + #define __Pyx_GIVEREF(r) + #define __Pyx_XINCREF(r) Py_XINCREF(r) + #define __Pyx_XDECREF(r) Py_XDECREF(r) + #define __Pyx_XGOTREF(r) + #define __Pyx_XGIVEREF(r) +#endif +#define __Pyx_Py_XDECREF_SET(r, v) do {\ + PyObject *tmp = (PyObject *) r;\ + r = v; Py_XDECREF(tmp);\ + } while (0) +#define __Pyx_XDECREF_SET(r, v) do {\ + PyObject *tmp = (PyObject *) r;\ + r = v; __Pyx_XDECREF(tmp);\ + } while (0) +#define __Pyx_DECREF_SET(r, v) do {\ + PyObject *tmp = (PyObject *) r;\ + r = v; __Pyx_DECREF(tmp);\ + } while (0) +#define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) +#define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) + +/* PyErrExceptionMatches.proto (used by PyObjectGetAttrStrNoError) */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_PyErr_ExceptionMatches(err) __Pyx_PyErr_ExceptionMatchesInState(__pyx_tstate, err) +static CYTHON_INLINE int __Pyx_PyErr_ExceptionMatchesInState(PyThreadState* tstate, PyObject* err); +#else +#define __Pyx_PyErr_ExceptionMatches(err) PyErr_ExceptionMatches(err) +#endif + +/* PyThreadStateGet.proto (used by PyErrFetchRestore) */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_PyThreadState_declare PyThreadState *__pyx_tstate; +#define __Pyx_PyThreadState_assign __pyx_tstate = __Pyx_PyThreadState_Current; +#if PY_VERSION_HEX >= 0x030C00A6 +#define __Pyx_PyErr_Occurred() (__pyx_tstate->current_exception != NULL) +#define __Pyx_PyErr_CurrentExceptionType() (__pyx_tstate->current_exception ? (PyObject*) Py_TYPE(__pyx_tstate->current_exception) : (PyObject*) NULL) +#else +#define __Pyx_PyErr_Occurred() (__pyx_tstate->curexc_type != NULL) +#define __Pyx_PyErr_CurrentExceptionType() (__pyx_tstate->curexc_type) +#endif +#else +#define __Pyx_PyThreadState_declare +#define __Pyx_PyThreadState_assign +#define __Pyx_PyErr_Occurred() (PyErr_Occurred() != NULL) +#define __Pyx_PyErr_CurrentExceptionType() PyErr_Occurred() +#endif + +/* PyErrFetchRestore.proto (used by PyObjectGetAttrStrNoError) */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_PyErr_Clear() __Pyx_ErrRestore(NULL, NULL, NULL) +#define __Pyx_ErrRestoreWithState(type, value, tb) __Pyx_ErrRestoreInState(PyThreadState_GET(), type, value, tb) +#define __Pyx_ErrFetchWithState(type, value, tb) __Pyx_ErrFetchInState(PyThreadState_GET(), type, value, tb) +#define __Pyx_ErrRestore(type, value, tb) __Pyx_ErrRestoreInState(__pyx_tstate, type, value, tb) +#define __Pyx_ErrFetch(type, value, tb) __Pyx_ErrFetchInState(__pyx_tstate, type, value, tb) +static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); +static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030C00A6 +#define __Pyx_PyErr_SetNone(exc) (Py_INCREF(exc), __Pyx_ErrRestore((exc), NULL, NULL)) +#else +#define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) +#endif +#else +#define __Pyx_PyErr_Clear() PyErr_Clear() +#define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) +#define __Pyx_ErrRestoreWithState(type, value, tb) PyErr_Restore(type, value, tb) +#define __Pyx_ErrFetchWithState(type, value, tb) PyErr_Fetch(type, value, tb) +#define __Pyx_ErrRestoreInState(tstate, type, value, tb) PyErr_Restore(type, value, tb) +#define __Pyx_ErrFetchInState(tstate, type, value, tb) PyErr_Fetch(type, value, tb) +#define __Pyx_ErrRestore(type, value, tb) PyErr_Restore(type, value, tb) +#define __Pyx_ErrFetch(type, value, tb) PyErr_Fetch(type, value, tb) +#endif + +/* PyObjectGetAttrStr.proto (used by PyObjectGetAttrStrNoError) */ +#if CYTHON_USE_TYPE_SLOTS +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name); +#else +#define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) +#endif + +/* PyObjectGetAttrStrNoError.proto (used by GetBuiltinName) */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStrNoError(PyObject* obj, PyObject* attr_name); + +/* GetBuiltinName.proto */ +static PyObject *__Pyx_GetBuiltinName(PyObject *name); + +/* TupleAndListFromArray.proto (used by fastcall) */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyList_FromArray(PyObject *const *src, Py_ssize_t n); +#endif +#if CYTHON_COMPILING_IN_CPYTHON || CYTHON_METH_FASTCALL +static CYTHON_INLINE PyObject* __Pyx_PyTuple_FromArray(PyObject *const *src, Py_ssize_t n); +#endif + +/* IncludeStringH.proto (used by BytesEquals) */ +#include + +/* BytesEquals.proto (used by UnicodeEquals) */ +static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals); + +/* UnicodeEquals.proto (used by fastcall) */ +static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals); + +/* fastcall.proto */ +#if CYTHON_AVOID_BORROWED_REFS + #define __Pyx_ArgRef_VARARGS(args, i) __Pyx_PySequence_ITEM(args, i) +#elif CYTHON_ASSUME_SAFE_MACROS + #define __Pyx_ArgRef_VARARGS(args, i) __Pyx_NewRef(__Pyx_PyTuple_GET_ITEM(args, i)) +#else + #define __Pyx_ArgRef_VARARGS(args, i) __Pyx_XNewRef(PyTuple_GetItem(args, i)) +#endif +#define __Pyx_NumKwargs_VARARGS(kwds) PyDict_Size(kwds) +#define __Pyx_KwValues_VARARGS(args, nargs) NULL +#define __Pyx_GetKwValue_VARARGS(kw, kwvalues, s) __Pyx_PyDict_GetItemStrWithError(kw, s) +#define __Pyx_KwargsAsDict_VARARGS(kw, kwvalues) PyDict_Copy(kw) +#if CYTHON_METH_FASTCALL + #define __Pyx_ArgRef_FASTCALL(args, i) __Pyx_NewRef(args[i]) + #define __Pyx_NumKwargs_FASTCALL(kwds) __Pyx_PyTuple_GET_SIZE(kwds) + #define __Pyx_KwValues_FASTCALL(args, nargs) ((args) + (nargs)) + static CYTHON_INLINE PyObject * __Pyx_GetKwValue_FASTCALL(PyObject *kwnames, PyObject *const *kwvalues, PyObject *s); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030d0000 || CYTHON_COMPILING_IN_LIMITED_API + CYTHON_UNUSED static PyObject *__Pyx_KwargsAsDict_FASTCALL(PyObject *kwnames, PyObject *const *kwvalues); + #else + #define __Pyx_KwargsAsDict_FASTCALL(kw, kwvalues) _PyStack_AsDict(kwvalues, kw) + #endif +#else + #define __Pyx_ArgRef_FASTCALL __Pyx_ArgRef_VARARGS + #define __Pyx_NumKwargs_FASTCALL __Pyx_NumKwargs_VARARGS + #define __Pyx_KwValues_FASTCALL __Pyx_KwValues_VARARGS + #define __Pyx_GetKwValue_FASTCALL __Pyx_GetKwValue_VARARGS + #define __Pyx_KwargsAsDict_FASTCALL __Pyx_KwargsAsDict_VARARGS +#endif +#define __Pyx_ArgsSlice_VARARGS(args, start, stop) PyTuple_GetSlice(args, start, stop) +#if CYTHON_METH_FASTCALL || (CYTHON_COMPILING_IN_CPYTHON && CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS) +#define __Pyx_ArgsSlice_FASTCALL(args, start, stop) __Pyx_PyTuple_FromArray(args + start, stop - start) +#else +#define __Pyx_ArgsSlice_FASTCALL(args, start, stop) PyTuple_GetSlice(args, start, stop) +#endif + +/* py_dict_items.proto (used by OwnedDictNext) */ +static CYTHON_INLINE PyObject* __Pyx_PyDict_Items(PyObject* d); + +/* CallCFunction.proto (used by CallUnboundCMethod0) */ +#define __Pyx_CallCFunction(cfunc, self, args)\ + ((PyCFunction)(void(*)(void))(cfunc)->func)(self, args) +#define __Pyx_CallCFunctionWithKeywords(cfunc, self, args, kwargs)\ + ((PyCFunctionWithKeywords)(void(*)(void))(cfunc)->func)(self, args, kwargs) +#define __Pyx_CallCFunctionFast(cfunc, self, args, nargs)\ + ((__Pyx_PyCFunctionFast)(void(*)(void))(PyCFunction)(cfunc)->func)(self, args, nargs) +#define __Pyx_CallCFunctionFastWithKeywords(cfunc, self, args, nargs, kwnames)\ + ((__Pyx_PyCFunctionFastWithKeywords)(void(*)(void))(PyCFunction)(cfunc)->func)(self, args, nargs, kwnames) + +/* PyObjectCall.proto (used by PyObjectFastCall) */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw); +#else +#define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw) +#endif + +/* PyObjectCallMethO.proto (used by PyObjectFastCall) */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg); +#endif + +/* PyObjectFastCall.proto (used by PyObjectCallOneArg) */ +#define __Pyx_PyObject_FastCall(func, args, nargs) __Pyx_PyObject_FastCallDict(func, args, (size_t)(nargs), NULL) +static CYTHON_INLINE PyObject* __Pyx_PyObject_FastCallDict(PyObject *func, PyObject * const*args, size_t nargs, PyObject *kwargs); + +/* PyObjectCallOneArg.proto (used by CallUnboundCMethod0) */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg); + +/* UnpackUnboundCMethod.proto (used by CallUnboundCMethod0) */ +typedef struct { + PyObject *type; + PyObject **method_name; +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING && CYTHON_ATOMICS + __pyx_atomic_int_type initialized; +#endif + PyCFunction func; + PyObject *method; + int flag; +} __Pyx_CachedCFunction; +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING +static CYTHON_INLINE int __Pyx_CachedCFunction_GetAndSetInitializing(__Pyx_CachedCFunction *cfunc) { +#if !CYTHON_ATOMICS + return 1; +#else + __pyx_nonatomic_int_type expected = 0; + if (__pyx_atomic_int_cmp_exchange(&cfunc->initialized, &expected, 1)) { + return 0; + } + return expected; +#endif +} +static CYTHON_INLINE void __Pyx_CachedCFunction_SetFinishedInitializing(__Pyx_CachedCFunction *cfunc) { +#if CYTHON_ATOMICS + __pyx_atomic_store(&cfunc->initialized, 2); +#endif +} +#else +#define __Pyx_CachedCFunction_GetAndSetInitializing(cfunc) 2 +#define __Pyx_CachedCFunction_SetFinishedInitializing(cfunc) +#endif + +/* CallUnboundCMethod0.proto */ +CYTHON_UNUSED +static PyObject* __Pyx__CallUnboundCMethod0(__Pyx_CachedCFunction* cfunc, PyObject* self); +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_CallUnboundCMethod0(__Pyx_CachedCFunction* cfunc, PyObject* self); +#else +#define __Pyx_CallUnboundCMethod0(cfunc, self) __Pyx__CallUnboundCMethod0(cfunc, self) +#endif + +/* py_dict_values.proto (used by OwnedDictNext) */ +static CYTHON_INLINE PyObject* __Pyx_PyDict_Values(PyObject* d); + +/* OwnedDictNext.proto (used by ParseKeywordsImpl) */ +#if CYTHON_AVOID_BORROWED_REFS +static int __Pyx_PyDict_NextRef(PyObject *p, PyObject **ppos, PyObject **pkey, PyObject **pvalue); +#else +CYTHON_INLINE +static int __Pyx_PyDict_NextRef(PyObject *p, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue); +#endif + +/* RaiseDoubleKeywords.proto (used by ParseKeywordsImpl) */ +static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); + +/* ParseKeywordsImpl.export */ +static int __Pyx_ParseKeywordsTuple( + PyObject *kwds, + PyObject * const *kwvalues, + PyObject ** const argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + Py_ssize_t num_kwargs, + const char* function_name, + int ignore_unknown_kwargs +); +static int __Pyx_ParseKeywordDictToDict( + PyObject *kwds, + PyObject ** const argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + const char* function_name +); +static int __Pyx_ParseKeywordDict( + PyObject *kwds, + PyObject ** const argnames[], + PyObject *values[], + Py_ssize_t num_pos_args, + Py_ssize_t num_kwargs, + const char* function_name, + int ignore_unknown_kwargs +); + +/* CallUnboundCMethod2.proto */ +CYTHON_UNUSED +static PyObject* __Pyx__CallUnboundCMethod2(__Pyx_CachedCFunction* cfunc, PyObject* self, PyObject* arg1, PyObject* arg2); +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject *__Pyx_CallUnboundCMethod2(__Pyx_CachedCFunction *cfunc, PyObject *self, PyObject *arg1, PyObject *arg2); +#else +#define __Pyx_CallUnboundCMethod2(cfunc, self, arg1, arg2) __Pyx__CallUnboundCMethod2(cfunc, self, arg1, arg2) +#endif + +/* ParseKeywords.proto */ +static CYTHON_INLINE int __Pyx_ParseKeywords( + PyObject *kwds, PyObject *const *kwvalues, PyObject ** const argnames[], + PyObject *kwds2, PyObject *values[], + Py_ssize_t num_pos_args, Py_ssize_t num_kwargs, + const char* function_name, + int ignore_unknown_kwargs +); + +/* RaiseArgTupleInvalid.proto */ +static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, + Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); + +/* RaiseException.export */ +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); + +/* RejectKeywords.export */ +static void __Pyx_RejectKeywords(const char* function_name, PyObject *kwds); + +/* PyObjectFastCallMethod.proto */ +#if CYTHON_VECTORCALL && PY_VERSION_HEX >= 0x03090000 +#define __Pyx_PyObject_FastCallMethod(name, args, nargsf) PyObject_VectorcallMethod(name, args, nargsf, NULL) +#else +static PyObject *__Pyx_PyObject_FastCallMethod(PyObject *name, PyObject *const *args, size_t nargsf); +#endif + +/* ArgTypeTestFunc.export */ +static int __Pyx__ArgTypeTest(PyObject *obj, PyTypeObject *type, const char *name, int exact); + +/* ArgTypeTest.proto */ +#define __Pyx_ArgTypeTest(obj, type, none_allowed, name, exact)\ + ((likely(__Pyx_IS_TYPE(obj, type) | (none_allowed && (obj == Py_None)))) ? 1 :\ + __Pyx__ArgTypeTest(obj, type, name, exact)) + +/* PyMemoryError_Check.proto */ +#define __Pyx_PyExc_MemoryError_Check(obj) __Pyx_TypeCheck(obj, PyExc_MemoryError) + +/* PyDictVersioning.proto (used by GetModuleGlobalName) */ +#if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_TYPE_SLOTS +#define __PYX_DICT_VERSION_INIT ((PY_UINT64_T) -1) +#define __PYX_GET_DICT_VERSION(dict) (((PyDictObject*)(dict))->ma_version_tag) +#define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var)\ + (version_var) = __PYX_GET_DICT_VERSION(dict);\ + (cache_var) = (value); +#define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) {\ + static PY_UINT64_T __pyx_dict_version = 0;\ + static PyObject *__pyx_dict_cached_value = NULL;\ + if (likely(__PYX_GET_DICT_VERSION(DICT) == __pyx_dict_version)) {\ + (VAR) = __Pyx_XNewRef(__pyx_dict_cached_value);\ + } else {\ + (VAR) = __pyx_dict_cached_value = (LOOKUP);\ + __pyx_dict_version = __PYX_GET_DICT_VERSION(DICT);\ + }\ +} +static CYTHON_INLINE PY_UINT64_T __Pyx_get_tp_dict_version(PyObject *obj); +static CYTHON_INLINE PY_UINT64_T __Pyx_get_object_dict_version(PyObject *obj); +static CYTHON_INLINE int __Pyx_object_dict_version_matches(PyObject* obj, PY_UINT64_T tp_dict_version, PY_UINT64_T obj_dict_version); +#else +#define __PYX_GET_DICT_VERSION(dict) (0) +#define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var) +#define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) (VAR) = (LOOKUP); +#endif + +/* GetModuleGlobalName.proto */ +#if CYTHON_USE_DICT_VERSIONS +#define __Pyx_GetModuleGlobalName(var, name) do {\ + static PY_UINT64_T __pyx_dict_version = 0;\ + static PyObject *__pyx_dict_cached_value = NULL;\ + (var) = (likely(__pyx_dict_version == __PYX_GET_DICT_VERSION(__pyx_mstate_global->__pyx_d))) ?\ + (likely(__pyx_dict_cached_value) ? __Pyx_NewRef(__pyx_dict_cached_value) : __Pyx_GetBuiltinName(name)) :\ + __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\ +} while(0) +#define __Pyx_GetModuleGlobalNameUncached(var, name) do {\ + PY_UINT64_T __pyx_dict_version;\ + PyObject *__pyx_dict_cached_value;\ + (var) = __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\ +} while(0) +static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_version, PyObject **dict_cached_value); +#else +#define __Pyx_GetModuleGlobalName(var, name) (var) = __Pyx__GetModuleGlobalName(name) +#define __Pyx_GetModuleGlobalNameUncached(var, name) (var) = __Pyx__GetModuleGlobalName(name) +static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name); +#endif + +/* GetAttr3.proto */ +static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *, PyObject *, PyObject *); + +/* RaiseUnexpectedTypeError.proto */ +static int __Pyx_RaiseUnexpectedTypeError(const char *expected, PyObject *obj); + +/* GetItemInt.proto */ +#define __Pyx_GetItemInt(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck, has_gil, unsafe_shared)\ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ + __Pyx_GetItemInt_Fast(o, (Py_ssize_t)i, is_list, wraparound, boundscheck, unsafe_shared) :\ + (is_list ? (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL) :\ + __Pyx_GetItemInt_Generic(o, to_py_func(i)))) +#define __Pyx_GetItemInt_List(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck, has_gil, unsafe_shared)\ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ + __Pyx_GetItemInt_List_Fast(o, (Py_ssize_t)i, wraparound, boundscheck, unsafe_shared) :\ + (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL)) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck, int unsafe_shared); +#define __Pyx_GetItemInt_Tuple(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck, has_gil, unsafe_shared)\ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ + __Pyx_GetItemInt_Tuple_Fast(o, (Py_ssize_t)i, wraparound, boundscheck, unsafe_shared) :\ + (PyErr_SetString(PyExc_IndexError, "tuple index out of range"), (PyObject*)NULL)) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck, int unsafe_shared); +static PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j); +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, + int is_list, int wraparound, int boundscheck, int unsafe_shared); + +/* ExtTypeTest.proto */ +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); + +/* CallNextTpDealloc.proto */ +static void __Pyx_call_next_tp_dealloc(PyObject* obj, destructor current_tp_dealloc); + +/* CallNextTpTraverse.proto */ +static int __Pyx_call_next_tp_traverse(PyObject* obj, visitproc v, void *a, traverseproc current_tp_traverse); + +/* CallTypeTraverse.proto */ +#if !CYTHON_USE_TYPE_SPECS || (!CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x03090000) +#define __Pyx_call_type_traverse(o, always_call, visit, arg) 0 +#else +static int __Pyx_call_type_traverse(PyObject *o, int always_call, visitproc visit, void *arg); +#endif + +/* CallNextTpClear.proto */ +static void __Pyx_call_next_tp_clear(PyObject* obj, inquiry current_tp_clear); + +/* TypeImport.proto */ +#ifndef __PYX_HAVE_RT_ImportType_proto_3_2_4 +#define __PYX_HAVE_RT_ImportType_proto_3_2_4 +#if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 201112L +#include +#endif +#if (defined (__STDC_VERSION__) && __STDC_VERSION__ >= 201112L) || __cplusplus >= 201103L +#define __PYX_GET_STRUCT_ALIGNMENT_3_2_4(s) alignof(s) +#else +#define __PYX_GET_STRUCT_ALIGNMENT_3_2_4(s) sizeof(void*) +#endif +enum __Pyx_ImportType_CheckSize_3_2_4 { + __Pyx_ImportType_CheckSize_Error_3_2_4 = 0, + __Pyx_ImportType_CheckSize_Warn_3_2_4 = 1, + __Pyx_ImportType_CheckSize_Ignore_3_2_4 = 2 +}; +static PyTypeObject *__Pyx_ImportType_3_2_4(PyObject* module, const char *module_name, const char *class_name, size_t size, size_t alignment, enum __Pyx_ImportType_CheckSize_3_2_4 check_size); +#endif + +/* GetVTable.proto */ +static void* __Pyx_GetVtable(PyTypeObject *type); + +/* LimitedApiGetTypeDict.proto (used by SetItemOnTypeDict) */ +#if CYTHON_COMPILING_IN_LIMITED_API +static PyObject *__Pyx_GetTypeDict(PyTypeObject *tp); +#endif + +/* SetItemOnTypeDict.proto (used by FixUpExtensionType) */ +static int __Pyx__SetItemOnTypeDict(PyTypeObject *tp, PyObject *k, PyObject *v); +#define __Pyx_SetItemOnTypeDict(tp, k, v) __Pyx__SetItemOnTypeDict((PyTypeObject*)tp, k, v) + +/* FixUpExtensionType.proto */ +static CYTHON_INLINE int __Pyx_fix_up_extension_type_from_spec(PyType_Spec *spec, PyTypeObject *type); + +/* PyObjectCallNoArg.proto (used by PyObjectCallMethod0) */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func); + +/* PyObjectGetMethod.proto (used by PyObjectCallMethod0) */ +#if !(CYTHON_VECTORCALL && (__PYX_LIMITED_VERSION_HEX >= 0x030C0000 || (!CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x03090000))) +static int __Pyx_PyObject_GetMethod(PyObject *obj, PyObject *name, PyObject **method); +#endif + +/* PyObjectCallMethod0.proto (used by PyType_Ready) */ +static PyObject* __Pyx_PyObject_CallMethod0(PyObject* obj, PyObject* method_name); + +/* ValidateBasesTuple.proto (used by PyType_Ready) */ +#if CYTHON_COMPILING_IN_CPYTHON || CYTHON_COMPILING_IN_LIMITED_API || CYTHON_USE_TYPE_SPECS +static int __Pyx_validate_bases_tuple(const char *type_name, Py_ssize_t dictoffset, PyObject *bases); +#endif + +/* PyType_Ready.proto */ +CYTHON_UNUSED static int __Pyx_PyType_Ready(PyTypeObject *t); + +/* SetVTable.proto */ +static int __Pyx_SetVtable(PyTypeObject* typeptr , void* vtable); + +/* MergeVTables.proto */ +static int __Pyx_MergeVtables(PyTypeObject *type); + +/* DelItemOnTypeDict.proto (used by SetupReduce) */ +static int __Pyx__DelItemOnTypeDict(PyTypeObject *tp, PyObject *k); +#define __Pyx_DelItemOnTypeDict(tp, k) __Pyx__DelItemOnTypeDict((PyTypeObject*)tp, k) + +/* SetupReduce.proto */ +static int __Pyx_setup_reduce(PyObject* type_obj); + +/* HasAttr.proto (used by ImportImpl) */ +#if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 +#define __Pyx_HasAttr(o, n) PyObject_HasAttrWithError(o, n) +#else +static CYTHON_INLINE int __Pyx_HasAttr(PyObject *, PyObject *); +#endif + +/* ImportImpl.export */ +static PyObject *__Pyx__Import(PyObject *name, PyObject *const *imported_names, Py_ssize_t len_imported_names, PyObject *qualname, PyObject *moddict, int level); + +/* Import.proto */ +static CYTHON_INLINE PyObject *__Pyx_Import(PyObject *name, PyObject *const *imported_names, Py_ssize_t len_imported_names, PyObject *qualname, int level); + +/* ImportFrom.proto */ +static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name); + +/* dict_setdefault.proto (used by FetchCommonType) */ +static CYTHON_INLINE PyObject *__Pyx_PyDict_SetDefault(PyObject *d, PyObject *key, PyObject *default_value); + +/* AddModuleRef.proto (used by FetchSharedCythonModule) */ +#if ((CYTHON_COMPILING_IN_CPYTHON_FREETHREADING ) ||\ + __PYX_LIMITED_VERSION_HEX < 0x030d0000) + static PyObject *__Pyx_PyImport_AddModuleRef(const char *name); +#else + #define __Pyx_PyImport_AddModuleRef(name) PyImport_AddModuleRef(name) +#endif + +/* FetchSharedCythonModule.proto (used by FetchCommonType) */ +static PyObject *__Pyx_FetchSharedCythonABIModule(void); + +/* FetchCommonType.proto (used by CommonTypesMetaclass) */ +static PyTypeObject* __Pyx_FetchCommonTypeFromSpec(PyTypeObject *metaclass, PyObject *module, PyType_Spec *spec, PyObject *bases); + +/* CommonTypesMetaclass.proto (used by CythonFunctionShared) */ +static int __pyx_CommonTypesMetaclass_init(PyObject *module); +#define __Pyx_CommonTypesMetaclass_USED + +/* PyMethodNew.proto (used by CythonFunctionShared) */ +static PyObject *__Pyx_PyMethod_New(PyObject *func, PyObject *self, PyObject *typ); + +/* PyVectorcallFastCallDict.proto (used by CythonFunctionShared) */ +#if CYTHON_METH_FASTCALL && CYTHON_VECTORCALL +static CYTHON_INLINE PyObject *__Pyx_PyVectorcall_FastCallDict(PyObject *func, __pyx_vectorcallfunc vc, PyObject *const *args, size_t nargs, PyObject *kw); +#endif + +/* CythonFunctionShared.proto (used by CythonFunction) */ +#define __Pyx_CyFunction_USED +#define __Pyx_CYFUNCTION_STATICMETHOD 0x01 +#define __Pyx_CYFUNCTION_CLASSMETHOD 0x02 +#define __Pyx_CYFUNCTION_CCLASS 0x04 +#define __Pyx_CYFUNCTION_COROUTINE 0x08 +#define __Pyx_CyFunction_GetClosure(f)\ + (((__pyx_CyFunctionObject *) (f))->func_closure) +#if PY_VERSION_HEX < 0x030900B1 || CYTHON_COMPILING_IN_LIMITED_API + #define __Pyx_CyFunction_GetClassObj(f)\ + (((__pyx_CyFunctionObject *) (f))->func_classobj) +#else + #define __Pyx_CyFunction_GetClassObj(f)\ + ((PyObject*) ((PyCMethodObject *) (f))->mm_class) +#endif +#define __Pyx_CyFunction_SetClassObj(f, classobj)\ + __Pyx__CyFunction_SetClassObj((__pyx_CyFunctionObject *) (f), (classobj)) +#define __Pyx_CyFunction_Defaults(type, f)\ + ((type *)(((__pyx_CyFunctionObject *) (f))->defaults)) +#define __Pyx_CyFunction_SetDefaultsGetter(f, g)\ + ((__pyx_CyFunctionObject *) (f))->defaults_getter = (g) +typedef struct { +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject_HEAD + PyObject *func; +#elif PY_VERSION_HEX < 0x030900B1 + PyCFunctionObject func; +#else + PyCMethodObject func; +#endif +#if CYTHON_COMPILING_IN_LIMITED_API && CYTHON_METH_FASTCALL + __pyx_vectorcallfunc func_vectorcall; +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *func_weakreflist; +#endif +#if PY_VERSION_HEX < 0x030C0000 || CYTHON_COMPILING_IN_LIMITED_API + PyObject *func_dict; +#endif + PyObject *func_name; + PyObject *func_qualname; + PyObject *func_doc; + PyObject *func_globals; + PyObject *func_code; + PyObject *func_closure; +#if PY_VERSION_HEX < 0x030900B1 || CYTHON_COMPILING_IN_LIMITED_API + PyObject *func_classobj; +#endif + PyObject *defaults; + int flags; + PyObject *defaults_tuple; + PyObject *defaults_kwdict; + PyObject *(*defaults_getter)(PyObject *); + PyObject *func_annotations; + PyObject *func_is_coroutine; +} __pyx_CyFunctionObject; +#undef __Pyx_CyOrPyCFunction_Check +#define __Pyx_CyFunction_Check(obj) __Pyx_TypeCheck(obj, __pyx_mstate_global->__pyx_CyFunctionType) +#define __Pyx_CyOrPyCFunction_Check(obj) __Pyx_TypeCheck2(obj, __pyx_mstate_global->__pyx_CyFunctionType, &PyCFunction_Type) +#define __Pyx_CyFunction_CheckExact(obj) __Pyx_IS_TYPE(obj, __pyx_mstate_global->__pyx_CyFunctionType) +static CYTHON_INLINE int __Pyx__IsSameCyOrCFunction(PyObject *func, void (*cfunc)(void)); +#undef __Pyx_IsSameCFunction +#define __Pyx_IsSameCFunction(func, cfunc) __Pyx__IsSameCyOrCFunction(func, cfunc) +static PyObject *__Pyx_CyFunction_Init(__pyx_CyFunctionObject* op, PyMethodDef *ml, + int flags, PyObject* qualname, + PyObject *closure, + PyObject *module, PyObject *globals, + PyObject* code); +static CYTHON_INLINE void __Pyx__CyFunction_SetClassObj(__pyx_CyFunctionObject* f, PyObject* classobj); +static CYTHON_INLINE PyObject *__Pyx_CyFunction_InitDefaults(PyObject *func, + PyTypeObject *defaults_type); +static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsTuple(PyObject *m, + PyObject *tuple); +static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsKwDict(PyObject *m, + PyObject *dict); +static CYTHON_INLINE void __Pyx_CyFunction_SetAnnotationsDict(PyObject *m, + PyObject *dict); +static int __pyx_CyFunction_init(PyObject *module); +#if CYTHON_METH_FASTCALL +static PyObject * __Pyx_CyFunction_Vectorcall_NOARGS(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames); +static PyObject * __Pyx_CyFunction_Vectorcall_O(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames); +static PyObject * __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames); +static PyObject * __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS_METHOD(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames); +#if CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_CyFunction_func_vectorcall(f) (((__pyx_CyFunctionObject*)f)->func_vectorcall) +#else +#define __Pyx_CyFunction_func_vectorcall(f) (((PyCFunctionObject*)f)->vectorcall) +#endif +#endif + +/* CythonFunction.proto */ +static PyObject *__Pyx_CyFunction_New(PyMethodDef *ml, + int flags, PyObject* qualname, + PyObject *closure, + PyObject *module, PyObject *globals, + PyObject* code); + +/* Py3UpdateBases.proto */ +static PyObject* __Pyx_PEP560_update_bases(PyObject *bases); + +/* CalculateMetaclass.proto */ +static PyObject *__Pyx_CalculateMetaclass(PyTypeObject *metaclass, PyObject *bases); + +/* SetNameInClass.proto */ +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030d0000 +#define __Pyx_SetNameInClass(ns, name, value)\ + (likely(PyDict_CheckExact(ns)) ? _PyDict_SetItem_KnownHash(ns, name, value, ((PyASCIIObject *) name)->hash) : PyObject_SetItem(ns, name, value)) +#elif CYTHON_COMPILING_IN_CPYTHON +#define __Pyx_SetNameInClass(ns, name, value)\ + (likely(PyDict_CheckExact(ns)) ? PyDict_SetItem(ns, name, value) : PyObject_SetItem(ns, name, value)) +#else +#define __Pyx_SetNameInClass(ns, name, value) PyObject_SetItem(ns, name, value) +#endif + +/* PyObjectCall2Args.proto (used by Py3ClassCreate) */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call2Args(PyObject* function, PyObject* arg1, PyObject* arg2); + +/* PyObjectLookupSpecial.proto (used by Py3ClassCreate) */ +#if CYTHON_USE_PYTYPE_LOOKUP && CYTHON_USE_TYPE_SLOTS +#define __Pyx_PyObject_LookupSpecialNoError(obj, attr_name) __Pyx__PyObject_LookupSpecial(obj, attr_name, 0) +#define __Pyx_PyObject_LookupSpecial(obj, attr_name) __Pyx__PyObject_LookupSpecial(obj, attr_name, 1) +static CYTHON_INLINE PyObject* __Pyx__PyObject_LookupSpecial(PyObject* obj, PyObject* attr_name, int with_error); +#else +#define __Pyx_PyObject_LookupSpecialNoError(o,n) __Pyx_PyObject_GetAttrStrNoError(o,n) +#define __Pyx_PyObject_LookupSpecial(o,n) __Pyx_PyObject_GetAttrStr(o,n) +#endif + +/* Py3ClassCreate.proto */ +static PyObject *__Pyx_Py3MetaclassPrepare(PyObject *metaclass, PyObject *bases, PyObject *name, PyObject *qualname, + PyObject *mkw, PyObject *modname, PyObject *doc); +static PyObject *__Pyx_Py3ClassCreate(PyObject *metaclass, PyObject *name, PyObject *bases, PyObject *dict, + PyObject *mkw, int calculate_metaclass, int allow_py2_metaclass); + +/* CLineInTraceback.proto (used by AddTraceback) */ +#if CYTHON_CLINE_IN_TRACEBACK && CYTHON_CLINE_IN_TRACEBACK_RUNTIME +static int __Pyx_CLineForTraceback(PyThreadState *tstate, int c_line); +#else +#define __Pyx_CLineForTraceback(tstate, c_line) (((CYTHON_CLINE_IN_TRACEBACK)) ? c_line : 0) +#endif + +/* CodeObjectCache.proto (used by AddTraceback) */ +#if CYTHON_COMPILING_IN_LIMITED_API +typedef PyObject __Pyx_CachedCodeObjectType; +#else +typedef PyCodeObject __Pyx_CachedCodeObjectType; +#endif +typedef struct { + __Pyx_CachedCodeObjectType* code_object; + int code_line; +} __Pyx_CodeObjectCacheEntry; +struct __Pyx_CodeObjectCache { + int count; + int max_count; + __Pyx_CodeObjectCacheEntry* entries; + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + __pyx_atomic_int_type accessor_count; + #endif +}; +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); +static __Pyx_CachedCodeObjectType *__pyx_find_code_object(int code_line); +static void __pyx_insert_code_object(int code_line, __Pyx_CachedCodeObjectType* code_object); + +/* AddTraceback.proto */ +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename); + +/* CheckUnpickleChecksum.proto */ +static CYTHON_INLINE int __Pyx_CheckUnpickleChecksum(long checksum, long checksum1, long checksum2, long checksum3, const char *members); + +/* GCCDiagnostics.proto */ +#if !defined(__INTEL_COMPILER) && defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) +#define __Pyx_HAS_GCC_DIAGNOSTIC +#endif + +/* CIntFromPy.proto */ +static CYTHON_INLINE int __Pyx_PyLong_As_int(PyObject *); + +/* CIntFromPy.proto */ +static CYTHON_INLINE long __Pyx_PyLong_As_long(PyObject *); + +/* PyObjectVectorCallKwBuilder.proto (used by CIntToPy) */ +CYTHON_UNUSED static int __Pyx_VectorcallBuilder_AddArg_Check(PyObject *key, PyObject *value, PyObject *builder, PyObject **args, int n); +#if CYTHON_VECTORCALL +#if PY_VERSION_HEX >= 0x03090000 +#define __Pyx_Object_Vectorcall_CallFromBuilder PyObject_Vectorcall +#else +#define __Pyx_Object_Vectorcall_CallFromBuilder _PyObject_Vectorcall +#endif +#define __Pyx_MakeVectorcallBuilderKwds(n) PyTuple_New(n) +static int __Pyx_VectorcallBuilder_AddArg(PyObject *key, PyObject *value, PyObject *builder, PyObject **args, int n); +static int __Pyx_VectorcallBuilder_AddArgStr(const char *key, PyObject *value, PyObject *builder, PyObject **args, int n); +#else +#define __Pyx_Object_Vectorcall_CallFromBuilder __Pyx_PyObject_FastCallDict +#define __Pyx_MakeVectorcallBuilderKwds(n) __Pyx_PyDict_NewPresized(n) +#define __Pyx_VectorcallBuilder_AddArg(key, value, builder, args, n) PyDict_SetItem(builder, key, value) +#define __Pyx_VectorcallBuilder_AddArgStr(key, value, builder, args, n) PyDict_SetItemString(builder, key, value) +#endif + +/* CIntToPy.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyLong_From_int(int value); + +/* CIntToPy.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyLong_From_long(long value); + +/* PyObjectCallMethod1.proto */ +static PyObject* __Pyx_PyObject_CallMethod1(PyObject* obj, PyObject* method_name, PyObject* arg); + +/* UpdateUnpickledDict.proto */ +static int __Pyx_UpdateUnpickledDict(PyObject *obj, PyObject *state, Py_ssize_t index); + +/* FormatTypeName.proto */ +#if CYTHON_COMPILING_IN_LIMITED_API +typedef PyObject *__Pyx_TypeName; +#define __Pyx_FMT_TYPENAME "%U" +#define __Pyx_DECREF_TypeName(obj) Py_XDECREF(obj) +#if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 +#define __Pyx_PyType_GetFullyQualifiedName PyType_GetFullyQualifiedName +#else +static __Pyx_TypeName __Pyx_PyType_GetFullyQualifiedName(PyTypeObject* tp); +#endif +#else // !LIMITED_API +typedef const char *__Pyx_TypeName; +#define __Pyx_FMT_TYPENAME "%.200s" +#define __Pyx_PyType_GetFullyQualifiedName(tp) ((tp)->tp_name) +#define __Pyx_DECREF_TypeName(obj) +#endif + +/* FastTypeChecks.proto */ +#if CYTHON_COMPILING_IN_CPYTHON +#define __Pyx_TypeCheck(obj, type) __Pyx_IsSubtype(Py_TYPE(obj), (PyTypeObject *)type) +#define __Pyx_TypeCheck2(obj, type1, type2) __Pyx_IsAnySubtype2(Py_TYPE(obj), (PyTypeObject *)type1, (PyTypeObject *)type2) +static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b); +static CYTHON_INLINE int __Pyx_IsAnySubtype2(PyTypeObject *cls, PyTypeObject *a, PyTypeObject *b); +static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches(PyObject *err, PyObject *type); +static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches2(PyObject *err, PyObject *type1, PyObject *type2); +#else +#define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) +#define __Pyx_TypeCheck2(obj, type1, type2) (PyObject_TypeCheck(obj, (PyTypeObject *)type1) || PyObject_TypeCheck(obj, (PyTypeObject *)type2)) +#define __Pyx_PyErr_GivenExceptionMatches(err, type) PyErr_GivenExceptionMatches(err, type) +static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches2(PyObject *err, PyObject *type1, PyObject *type2) { + return PyErr_GivenExceptionMatches(err, type1) || PyErr_GivenExceptionMatches(err, type2); +} +#endif +#define __Pyx_PyErr_ExceptionMatches2(err1, err2) __Pyx_PyErr_GivenExceptionMatches2(__Pyx_PyErr_CurrentExceptionType(), err1, err2) +#define __Pyx_PyException_Check(obj) __Pyx_TypeCheck(obj, PyExc_Exception) +#ifdef PyExceptionInstance_Check + #define __Pyx_PyBaseException_Check(obj) PyExceptionInstance_Check(obj) +#else + #define __Pyx_PyBaseException_Check(obj) __Pyx_TypeCheck(obj, PyExc_BaseException) +#endif + +/* GetRuntimeVersion.proto */ +#if __PYX_LIMITED_VERSION_HEX < 0x030b0000 +static unsigned long __Pyx_cached_runtime_version = 0; +static void __Pyx_init_runtime_version(void); +#else +#define __Pyx_init_runtime_version() +#endif +static unsigned long __Pyx_get_runtime_version(void); + +/* CheckBinaryVersion.proto */ +static int __Pyx_check_binary_version(unsigned long ct_version, unsigned long rt_version, int allow_newer); + +/* DecompressString.proto */ +static PyObject *__Pyx_DecompressString(const char *s, Py_ssize_t length, int algo); + +/* MultiPhaseInitModuleState.proto */ +#if CYTHON_PEP489_MULTI_PHASE_INIT && CYTHON_USE_MODULE_STATE +static PyObject *__Pyx_State_FindModule(void*); +static int __Pyx_State_AddModule(PyObject* module, void*); +static int __Pyx_State_RemoveModule(void*); +#elif CYTHON_USE_MODULE_STATE +#define __Pyx_State_FindModule PyState_FindModule +#define __Pyx_State_AddModule PyState_AddModule +#define __Pyx_State_RemoveModule PyState_RemoveModule +#endif + +/* #### Code section: module_declarations ### */ +/* CythonABIVersion.proto */ +#if CYTHON_COMPILING_IN_LIMITED_API + #if CYTHON_METH_FASTCALL + #define __PYX_FASTCALL_ABI_SUFFIX "_fastcall" + #else + #define __PYX_FASTCALL_ABI_SUFFIX + #endif + #define __PYX_LIMITED_ABI_SUFFIX "limited" __PYX_FASTCALL_ABI_SUFFIX __PYX_AM_SEND_ABI_SUFFIX +#else + #define __PYX_LIMITED_ABI_SUFFIX +#endif +#if __PYX_HAS_PY_AM_SEND == 1 + #define __PYX_AM_SEND_ABI_SUFFIX +#elif __PYX_HAS_PY_AM_SEND == 2 + #define __PYX_AM_SEND_ABI_SUFFIX "amsendbackport" +#else + #define __PYX_AM_SEND_ABI_SUFFIX "noamsend" +#endif +#ifndef __PYX_MONITORING_ABI_SUFFIX + #define __PYX_MONITORING_ABI_SUFFIX +#endif +#if CYTHON_USE_TP_FINALIZE + #define __PYX_TP_FINALIZE_ABI_SUFFIX +#else + #define __PYX_TP_FINALIZE_ABI_SUFFIX "nofinalize" +#endif +#if CYTHON_USE_FREELISTS || !defined(__Pyx_AsyncGen_USED) + #define __PYX_FREELISTS_ABI_SUFFIX +#else + #define __PYX_FREELISTS_ABI_SUFFIX "nofreelists" +#endif +#define CYTHON_ABI __PYX_ABI_VERSION __PYX_LIMITED_ABI_SUFFIX __PYX_MONITORING_ABI_SUFFIX __PYX_TP_FINALIZE_ABI_SUFFIX __PYX_FREELISTS_ABI_SUFFIX __PYX_AM_SEND_ABI_SUFFIX +#define __PYX_ABI_MODULE_NAME "_cython_" CYTHON_ABI +#define __PYX_TYPE_MODULE_PREFIX __PYX_ABI_MODULE_NAME "." + +static PyObject *__pyx_f_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_c_write(struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *__pyx_v_self, char const *__pyx_v_data, int __pyx_v_sz); /* proto*/ +static PyObject *__pyx_f_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_c_read(struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *__pyx_v_self, int __pyx_v_sz, char *__pyx_v_out); /* proto*/ +static PyObject *__pyx_f_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_read_trans(struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *__pyx_v_self, int __pyx_v_sz, char *__pyx_v_out); /* proto*/ +static PyObject *__pyx_f_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_c_flush(struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *__pyx_v_self); /* proto*/ +static PyObject *__pyx_f_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_c_dump_wbuf(struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *__pyx_v_self); /* proto*/ + +/* Module declarations from "thriftpy2.transport.cybase" */ + +/* Module declarations from "thriftpy2.transport.buffered.cybuffered" */ +static PyObject *__pyx_f_9thriftpy2_9transport_8buffered_10cybuffered___pyx_unpickle_TCyBufferedTransport__set_state(struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *, PyObject *); /*proto*/ +/* #### Code section: typeinfo ### */ +/* #### Code section: before_global_var ### */ +#define __Pyx_MODULE_NAME "thriftpy2.transport.buffered.cybuffered" +extern int __pyx_module_is_main_thriftpy2__transport__buffered__cybuffered; +int __pyx_module_is_main_thriftpy2__transport__buffered__cybuffered = 0; + +/* Implementation of "thriftpy2.transport.buffered.cybuffered" */ +/* #### Code section: global_var ### */ +static PyObject *__pyx_builtin_object; +/* #### Code section: string_decls ### */ +static const char __pyx_k_rbuf_trans_wbuf[] = "rbuf, trans, wbuf"; +/* #### Code section: decls ### */ +static int __pyx_pf_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport___init__(struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *__pyx_v_self, PyObject *__pyx_v_trans, int __pyx_v_buf_size); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_2clean(struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_4is_open(struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_6open(struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_8close(struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_10write(struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *__pyx_v_self, PyObject *__pyx_v_data); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_12read(struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *__pyx_v_self, int __pyx_v_sz); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_14flush(struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_16getvalue(struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_18__reduce_cython__(struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_20__setstate_cython__(struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *__pyx_v_self, PyObject *__pyx_v___pyx_state); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_9transport_8buffered_10cybuffered_27TCyBufferedTransportFactory_get_transport(CYTHON_UNUSED PyObject *__pyx_self, CYTHON_UNUSED PyObject *__pyx_v_self, PyObject *__pyx_v_trans); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_9transport_8buffered_10cybuffered___pyx_unpickle_TCyBufferedTransport(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v___pyx_type, long __pyx_v___pyx_checksum, PyObject *__pyx_v___pyx_state); /* proto */ +static PyObject *__pyx_tp_new_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +/* #### Code section: late_includes ### */ +/* #### Code section: module_state ### */ +/* SmallCodeConfig */ +#ifndef CYTHON_SMALL_CODE +#if defined(__clang__) + #define CYTHON_SMALL_CODE +#elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) + #define CYTHON_SMALL_CODE __attribute__((cold)) +#else + #define CYTHON_SMALL_CODE +#endif +#endif + +typedef struct { + PyObject *__pyx_d; + PyObject *__pyx_b; + PyObject *__pyx_cython_runtime; + PyObject *__pyx_empty_tuple; + PyObject *__pyx_empty_bytes; + PyObject *__pyx_empty_unicode; + PyTypeObject *__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer; + PyTypeObject *__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase; + PyObject *__pyx_type_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport; + PyTypeObject *__pyx_ptype_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport; + __Pyx_CachedCFunction __pyx_umethod_PyDict_Type_items; + __Pyx_CachedCFunction __pyx_umethod_PyDict_Type_pop; + __Pyx_CachedCFunction __pyx_umethod_PyDict_Type_values; + int __pyx_k_; + PyObject *__pyx_tuple[2]; + PyObject *__pyx_codeobj_tab[12]; + PyObject *__pyx_string_tab[96]; + PyObject *__pyx_number_tab[2]; +/* #### Code section: module_state_contents ### */ +/* CommonTypesMetaclass.module_state_decls */ +PyTypeObject *__pyx_CommonTypesMetaclassType; + +/* CachedMethodType.module_state_decls */ +#if CYTHON_COMPILING_IN_LIMITED_API +PyObject *__Pyx_CachedMethodType; +#endif + +/* CythonFunctionShared.module_state_decls */ +PyTypeObject *__pyx_CyFunctionType; + +/* CodeObjectCache.module_state_decls */ +struct __Pyx_CodeObjectCache __pyx_code_cache; + +/* #### Code section: module_state_end ### */ +} __pyx_mstatetype; + +#if CYTHON_USE_MODULE_STATE +#ifdef __cplusplus +namespace { +extern struct PyModuleDef __pyx_moduledef; +} /* anonymous namespace */ +#else +static struct PyModuleDef __pyx_moduledef; +#endif + +#define __pyx_mstate_global (__Pyx_PyModule_GetState(__Pyx_State_FindModule(&__pyx_moduledef))) + +#define __pyx_m (__Pyx_State_FindModule(&__pyx_moduledef)) +#else +static __pyx_mstatetype __pyx_mstate_global_static = +#ifdef __cplusplus + {}; +#else + {0}; +#endif +static __pyx_mstatetype * const __pyx_mstate_global = &__pyx_mstate_global_static; +#endif +/* #### Code section: constant_name_defines ### */ +#define __pyx_kp_u_End_of_file_reading_from_transpo __pyx_string_tab[0] +#define __pyx_kp_u_Note_that_Cython_is_deliberately __pyx_string_tab[1] +#define __pyx_kp_u_Write_to_buffer_error __pyx_string_tab[2] +#define __pyx_kp_u__3 __pyx_string_tab[3] +#define __pyx_kp_u__4 __pyx_string_tab[4] +#define __pyx_kp_u_add_note __pyx_string_tab[5] +#define __pyx_kp_u_buffer_too_small __pyx_string_tab[6] +#define __pyx_kp_u_disable __pyx_string_tab[7] +#define __pyx_kp_u_enable __pyx_string_tab[8] +#define __pyx_kp_u_gc __pyx_string_tab[9] +#define __pyx_kp_u_grow_read_buffer_fail __pyx_string_tab[10] +#define __pyx_kp_u_isenabled __pyx_string_tab[11] +#define __pyx_kp_u_stringsource __pyx_string_tab[12] +#define __pyx_kp_u_thriftpy2_transport __pyx_string_tab[13] +#define __pyx_kp_u_thriftpy2_transport_buffered_cyb_2 __pyx_string_tab[14] +#define __pyx_n_u_END_OF_FILE __pyx_string_tab[15] +#define __pyx_n_u_Pyx_PyDict_NextRef __pyx_string_tab[16] +#define __pyx_n_u_TCyBufferedTransport __pyx_string_tab[17] +#define __pyx_n_u_TCyBufferedTransportFactory __pyx_string_tab[18] +#define __pyx_n_u_TCyBufferedTransportFactory_get __pyx_string_tab[19] +#define __pyx_n_u_TCyBufferedTransport___reduce_cy __pyx_string_tab[20] +#define __pyx_n_u_TCyBufferedTransport___setstate __pyx_string_tab[21] +#define __pyx_n_u_TCyBufferedTransport_clean __pyx_string_tab[22] +#define __pyx_n_u_TCyBufferedTransport_close __pyx_string_tab[23] +#define __pyx_n_u_TCyBufferedTransport_flush __pyx_string_tab[24] +#define __pyx_n_u_TCyBufferedTransport_getvalue __pyx_string_tab[25] +#define __pyx_n_u_TCyBufferedTransport_is_open __pyx_string_tab[26] +#define __pyx_n_u_TCyBufferedTransport_open __pyx_string_tab[27] +#define __pyx_n_u_TCyBufferedTransport_read __pyx_string_tab[28] +#define __pyx_n_u_TCyBufferedTransport_write __pyx_string_tab[29] +#define __pyx_n_u_TTransportException __pyx_string_tab[30] +#define __pyx_n_u__2 __pyx_string_tab[31] +#define __pyx_n_u_asyncio_coroutines __pyx_string_tab[32] +#define __pyx_n_u_buf_size __pyx_string_tab[33] +#define __pyx_n_u_clean __pyx_string_tab[34] +#define __pyx_n_u_cline_in_traceback __pyx_string_tab[35] +#define __pyx_n_u_close __pyx_string_tab[36] +#define __pyx_n_u_data __pyx_string_tab[37] +#define __pyx_n_u_dict __pyx_string_tab[38] +#define __pyx_n_u_dict_2 __pyx_string_tab[39] +#define __pyx_n_u_doc __pyx_string_tab[40] +#define __pyx_n_u_flush __pyx_string_tab[41] +#define __pyx_n_u_func __pyx_string_tab[42] +#define __pyx_n_u_get_transport __pyx_string_tab[43] +#define __pyx_n_u_getstate __pyx_string_tab[44] +#define __pyx_n_u_getvalue __pyx_string_tab[45] +#define __pyx_n_u_is_coroutine __pyx_string_tab[46] +#define __pyx_n_u_is_open __pyx_string_tab[47] +#define __pyx_n_u_items __pyx_string_tab[48] +#define __pyx_n_u_main __pyx_string_tab[49] +#define __pyx_n_u_metaclass __pyx_string_tab[50] +#define __pyx_n_u_module __pyx_string_tab[51] +#define __pyx_n_u_mro_entries __pyx_string_tab[52] +#define __pyx_n_u_name __pyx_string_tab[53] +#define __pyx_n_u_new __pyx_string_tab[54] +#define __pyx_n_u_object __pyx_string_tab[55] +#define __pyx_n_u_open __pyx_string_tab[56] +#define __pyx_n_u_pop __pyx_string_tab[57] +#define __pyx_n_u_prepare __pyx_string_tab[58] +#define __pyx_n_u_pyx_checksum __pyx_string_tab[59] +#define __pyx_n_u_pyx_result __pyx_string_tab[60] +#define __pyx_n_u_pyx_state __pyx_string_tab[61] +#define __pyx_n_u_pyx_type __pyx_string_tab[62] +#define __pyx_n_u_pyx_unpickle_TCyBufferedTransp __pyx_string_tab[63] +#define __pyx_n_u_pyx_vtable __pyx_string_tab[64] +#define __pyx_n_u_qualname __pyx_string_tab[65] +#define __pyx_n_u_read __pyx_string_tab[66] +#define __pyx_n_u_reduce __pyx_string_tab[67] +#define __pyx_n_u_reduce_cython __pyx_string_tab[68] +#define __pyx_n_u_reduce_ex __pyx_string_tab[69] +#define __pyx_n_u_self __pyx_string_tab[70] +#define __pyx_n_u_set_name __pyx_string_tab[71] +#define __pyx_n_u_setdefault __pyx_string_tab[72] +#define __pyx_n_u_setstate __pyx_string_tab[73] +#define __pyx_n_u_setstate_cython __pyx_string_tab[74] +#define __pyx_n_u_state __pyx_string_tab[75] +#define __pyx_n_u_sz __pyx_string_tab[76] +#define __pyx_n_u_test __pyx_string_tab[77] +#define __pyx_n_u_thriftpy2_transport_buffered_cyb __pyx_string_tab[78] +#define __pyx_n_u_trans __pyx_string_tab[79] +#define __pyx_n_u_update __pyx_string_tab[80] +#define __pyx_n_u_use_setstate __pyx_string_tab[81] +#define __pyx_n_u_values __pyx_string_tab[82] +#define __pyx_n_u_write __pyx_string_tab[83] +#define __pyx_kp_b_iso88591_2_6 __pyx_string_tab[84] +#define __pyx_kp_b_iso88591_A_1A __pyx_string_tab[85] +#define __pyx_kp_b_iso88591_A_E_q_E_q __pyx_string_tab[86] +#define __pyx_kp_b_iso88591_A_c_t81F __pyx_string_tab[87] +#define __pyx_kp_b_iso88591_A_t6 __pyx_string_tab[88] +#define __pyx_kp_b_iso88591_A_t6_2 __pyx_string_tab[89] +#define __pyx_kp_b_iso88591_A_t6_a __pyx_string_tab[90] +#define __pyx_kp_b_iso88591_A_t6_q __pyx_string_tab[91] +#define __pyx_kp_b_iso88591_A_t81 __pyx_string_tab[92] +#define __pyx_kp_b_iso88591_A_t_aq __pyx_string_tab[93] +#define __pyx_kp_b_iso88591_T_HD_G1F_a_vWE_Q_q_t6_S_G7_s_fT __pyx_string_tab[94] +#define __pyx_kp_b_iso88591_q_0_kQR_xq_7_6a7Nn_1 __pyx_string_tab[95] +#define __pyx_int_0 __pyx_number_tab[0] +#define __pyx_int_166623181 __pyx_number_tab[1] +/* #### Code section: module_state_clear ### */ +#if CYTHON_USE_MODULE_STATE +static CYTHON_SMALL_CODE int __pyx_m_clear(PyObject *m) { + __pyx_mstatetype *clear_module_state = __Pyx_PyModule_GetState(m); + if (!clear_module_state) return 0; + Py_CLEAR(clear_module_state->__pyx_d); + Py_CLEAR(clear_module_state->__pyx_b); + Py_CLEAR(clear_module_state->__pyx_cython_runtime); + Py_CLEAR(clear_module_state->__pyx_empty_tuple); + Py_CLEAR(clear_module_state->__pyx_empty_bytes); + Py_CLEAR(clear_module_state->__pyx_empty_unicode); + #if CYTHON_PEP489_MULTI_PHASE_INIT + __Pyx_State_RemoveModule(NULL); + #endif + Py_CLEAR(clear_module_state->__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer); + Py_CLEAR(clear_module_state->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase); + Py_CLEAR(clear_module_state->__pyx_ptype_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport); + Py_CLEAR(clear_module_state->__pyx_type_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport); + for (int i=0; i<2; ++i) { Py_CLEAR(clear_module_state->__pyx_tuple[i]); } + for (int i=0; i<12; ++i) { Py_CLEAR(clear_module_state->__pyx_codeobj_tab[i]); } + for (int i=0; i<96; ++i) { Py_CLEAR(clear_module_state->__pyx_string_tab[i]); } + for (int i=0; i<2; ++i) { Py_CLEAR(clear_module_state->__pyx_number_tab[i]); } +/* #### Code section: module_state_clear_contents ### */ +/* CommonTypesMetaclass.module_state_clear */ +Py_CLEAR(clear_module_state->__pyx_CommonTypesMetaclassType); + +/* CythonFunctionShared.module_state_clear */ +Py_CLEAR(clear_module_state->__pyx_CyFunctionType); + +/* #### Code section: module_state_clear_end ### */ +return 0; +} +#endif +/* #### Code section: module_state_traverse ### */ +#if CYTHON_USE_MODULE_STATE +static CYTHON_SMALL_CODE int __pyx_m_traverse(PyObject *m, visitproc visit, void *arg) { + __pyx_mstatetype *traverse_module_state = __Pyx_PyModule_GetState(m); + if (!traverse_module_state) return 0; + Py_VISIT(traverse_module_state->__pyx_d); + Py_VISIT(traverse_module_state->__pyx_b); + Py_VISIT(traverse_module_state->__pyx_cython_runtime); + __Pyx_VISIT_CONST(traverse_module_state->__pyx_empty_tuple); + __Pyx_VISIT_CONST(traverse_module_state->__pyx_empty_bytes); + __Pyx_VISIT_CONST(traverse_module_state->__pyx_empty_unicode); + Py_VISIT(traverse_module_state->__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer); + Py_VISIT(traverse_module_state->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase); + Py_VISIT(traverse_module_state->__pyx_ptype_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport); + Py_VISIT(traverse_module_state->__pyx_type_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport); + for (int i=0; i<2; ++i) { __Pyx_VISIT_CONST(traverse_module_state->__pyx_tuple[i]); } + for (int i=0; i<12; ++i) { __Pyx_VISIT_CONST(traverse_module_state->__pyx_codeobj_tab[i]); } + for (int i=0; i<96; ++i) { __Pyx_VISIT_CONST(traverse_module_state->__pyx_string_tab[i]); } + for (int i=0; i<2; ++i) { __Pyx_VISIT_CONST(traverse_module_state->__pyx_number_tab[i]); } +/* #### Code section: module_state_traverse_contents ### */ +/* CommonTypesMetaclass.module_state_traverse */ +Py_VISIT(traverse_module_state->__pyx_CommonTypesMetaclassType); + +/* CythonFunctionShared.module_state_traverse */ +Py_VISIT(traverse_module_state->__pyx_CyFunctionType); + +/* #### Code section: module_state_traverse_end ### */ +return 0; +} +#endif +/* #### Code section: module_code ### */ + +/* "thriftpy2/transport/buffered/cybuffered.pyx":20 + * TCyBuffer rbuf, wbuf + * + * def __init__(self, trans, int buf_size=DEFAULT_BUFFER): # <<<<<<<<<<<<<< + * if buf_size < MIN_BUFFER_SIZE: + * raise Exception("buffer too small") +*/ + +/* Python wrapper */ +static int __pyx_pw_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_trans = 0; + int __pyx_v_buf_size; + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[2] = {0,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return -1; + #endif + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_trans,&__pyx_mstate_global->__pyx_n_u_buf_size,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_VARARGS(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 20, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 2: + values[1] = __Pyx_ArgRef_VARARGS(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 20, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_VARARGS(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 20, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "__init__", 0) < (0)) __PYX_ERR(0, 20, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("__init__", 0, 1, 2, i); __PYX_ERR(0, 20, __pyx_L3_error) } + } + } else { + switch (__pyx_nargs) { + case 2: + values[1] = __Pyx_ArgRef_VARARGS(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 20, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_VARARGS(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 20, __pyx_L3_error) + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_trans = values[0]; + if (values[1]) { + __pyx_v_buf_size = __Pyx_PyLong_As_int(values[1]); if (unlikely((__pyx_v_buf_size == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 20, __pyx_L3_error) + } else { + __pyx_v_buf_size = __pyx_mstate_global->__pyx_k_; + } + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__init__", 0, 1, 2, __pyx_nargs); __PYX_ERR(0, 20, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("thriftpy2.transport.buffered.cybuffered.TCyBufferedTransport.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport___init__(((struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *)__pyx_v_self), __pyx_v_trans, __pyx_v_buf_size); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport___init__(struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *__pyx_v_self, PyObject *__pyx_v_trans, int __pyx_v_buf_size) { + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + size_t __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__init__", 0); + + /* "thriftpy2/transport/buffered/cybuffered.pyx":21 + * + * def __init__(self, trans, int buf_size=DEFAULT_BUFFER): + * if buf_size < MIN_BUFFER_SIZE: # <<<<<<<<<<<<<< + * raise Exception("buffer too small") + * +*/ + __pyx_t_1 = (__pyx_v_buf_size < 0x400); + if (unlikely(__pyx_t_1)) { + + /* "thriftpy2/transport/buffered/cybuffered.pyx":22 + * def __init__(self, trans, int buf_size=DEFAULT_BUFFER): + * if buf_size < MIN_BUFFER_SIZE: + * raise Exception("buffer too small") # <<<<<<<<<<<<<< + * + * self.trans = trans +*/ + __pyx_t_3 = NULL; + __pyx_t_4 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_mstate_global->__pyx_kp_u_buffer_too_small}; + __pyx_t_2 = __Pyx_PyObject_FastCall((PyObject*)(((PyTypeObject*)PyExc_Exception)), __pyx_callargs+__pyx_t_4, (2-__pyx_t_4) | (__pyx_t_4*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 22, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __PYX_ERR(0, 22, __pyx_L1_error) + + /* "thriftpy2/transport/buffered/cybuffered.pyx":21 + * + * def __init__(self, trans, int buf_size=DEFAULT_BUFFER): + * if buf_size < MIN_BUFFER_SIZE: # <<<<<<<<<<<<<< + * raise Exception("buffer too small") + * +*/ + } + + /* "thriftpy2/transport/buffered/cybuffered.pyx":24 + * raise Exception("buffer too small") + * + * self.trans = trans # <<<<<<<<<<<<<< + * self.rbuf = TCyBuffer(buf_size) + * self.wbuf = TCyBuffer(buf_size) +*/ + __Pyx_INCREF(__pyx_v_trans); + __Pyx_GIVEREF(__pyx_v_trans); + __Pyx_GOTREF(__pyx_v_self->__pyx_base.trans); + __Pyx_DECREF(__pyx_v_self->__pyx_base.trans); + __pyx_v_self->__pyx_base.trans = __pyx_v_trans; + + /* "thriftpy2/transport/buffered/cybuffered.pyx":25 + * + * self.trans = trans + * self.rbuf = TCyBuffer(buf_size) # <<<<<<<<<<<<<< + * self.wbuf = TCyBuffer(buf_size) + * +*/ + __pyx_t_3 = NULL; + __pyx_t_5 = __Pyx_PyLong_From_int(__pyx_v_buf_size); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 25, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_t_5}; + __pyx_t_2 = __Pyx_PyObject_FastCall((PyObject*)__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer, __pyx_callargs+__pyx_t_4, (2-__pyx_t_4) | (__pyx_t_4*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 25, __pyx_L1_error) + __Pyx_GOTREF((PyObject *)__pyx_t_2); + } + __Pyx_GIVEREF((PyObject *)__pyx_t_2); + __Pyx_GOTREF((PyObject *)__pyx_v_self->rbuf); + __Pyx_DECREF((PyObject *)__pyx_v_self->rbuf); + __pyx_v_self->rbuf = ((struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *)__pyx_t_2); + __pyx_t_2 = 0; + + /* "thriftpy2/transport/buffered/cybuffered.pyx":26 + * self.trans = trans + * self.rbuf = TCyBuffer(buf_size) + * self.wbuf = TCyBuffer(buf_size) # <<<<<<<<<<<<<< + * + * def clean(self): +*/ + __pyx_t_5 = NULL; + __pyx_t_3 = __Pyx_PyLong_From_int(__pyx_v_buf_size); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 26, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_5, __pyx_t_3}; + __pyx_t_2 = __Pyx_PyObject_FastCall((PyObject*)__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer, __pyx_callargs+__pyx_t_4, (2-__pyx_t_4) | (__pyx_t_4*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 26, __pyx_L1_error) + __Pyx_GOTREF((PyObject *)__pyx_t_2); + } + __Pyx_GIVEREF((PyObject *)__pyx_t_2); + __Pyx_GOTREF((PyObject *)__pyx_v_self->wbuf); + __Pyx_DECREF((PyObject *)__pyx_v_self->wbuf); + __pyx_v_self->wbuf = ((struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *)__pyx_t_2); + __pyx_t_2 = 0; + + /* "thriftpy2/transport/buffered/cybuffered.pyx":20 + * TCyBuffer rbuf, wbuf + * + * def __init__(self, trans, int buf_size=DEFAULT_BUFFER): # <<<<<<<<<<<<<< + * if buf_size < MIN_BUFFER_SIZE: + * raise Exception("buffer too small") +*/ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("thriftpy2.transport.buffered.cybuffered.TCyBufferedTransport.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/buffered/cybuffered.pyx":28 + * self.wbuf = TCyBuffer(buf_size) + * + * def clean(self): # <<<<<<<<<<<<<< + * self.rbuf.clean() + * self.wbuf.clean() +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_3clean(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_3clean = {"clean", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_3clean, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_3clean(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("clean (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("clean", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("clean", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_2clean(((struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_2clean(struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("clean", 0); + + /* "thriftpy2/transport/buffered/cybuffered.pyx":29 + * + * def clean(self): + * self.rbuf.clean() # <<<<<<<<<<<<<< + * self.wbuf.clean() + * +*/ + ((struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_TCyBuffer *)__pyx_v_self->rbuf->__pyx_vtab)->clean(__pyx_v_self->rbuf); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 29, __pyx_L1_error) + + /* "thriftpy2/transport/buffered/cybuffered.pyx":30 + * def clean(self): + * self.rbuf.clean() + * self.wbuf.clean() # <<<<<<<<<<<<<< + * + * def is_open(self): +*/ + ((struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_TCyBuffer *)__pyx_v_self->wbuf->__pyx_vtab)->clean(__pyx_v_self->wbuf); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 30, __pyx_L1_error) + + /* "thriftpy2/transport/buffered/cybuffered.pyx":28 + * self.wbuf = TCyBuffer(buf_size) + * + * def clean(self): # <<<<<<<<<<<<<< + * self.rbuf.clean() + * self.wbuf.clean() +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_AddTraceback("thriftpy2.transport.buffered.cybuffered.TCyBufferedTransport.clean", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/buffered/cybuffered.pyx":32 + * self.wbuf.clean() + * + * def is_open(self): # <<<<<<<<<<<<<< + * return self.trans.is_open() + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_5is_open(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_5is_open = {"is_open", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_5is_open, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_5is_open(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("is_open (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("is_open", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("is_open", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_4is_open(((struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_4is_open(struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + size_t __pyx_t_3; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("is_open", 0); + + /* "thriftpy2/transport/buffered/cybuffered.pyx":33 + * + * def is_open(self): + * return self.trans.is_open() # <<<<<<<<<<<<<< + * + * def open(self): +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __pyx_v_self->__pyx_base.trans; + __Pyx_INCREF(__pyx_t_2); + __pyx_t_3 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, NULL}; + __pyx_t_1 = __Pyx_PyObject_FastCallMethod((PyObject*)__pyx_mstate_global->__pyx_n_u_is_open, __pyx_callargs+__pyx_t_3, (1-__pyx_t_3) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 33, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "thriftpy2/transport/buffered/cybuffered.pyx":32 + * self.wbuf.clean() + * + * def is_open(self): # <<<<<<<<<<<<<< + * return self.trans.is_open() + * +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("thriftpy2.transport.buffered.cybuffered.TCyBufferedTransport.is_open", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/buffered/cybuffered.pyx":35 + * return self.trans.is_open() + * + * def open(self): # <<<<<<<<<<<<<< + * return self.trans.open() + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_7open(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_7open = {"open", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_7open, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_7open(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("open (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("open", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("open", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_6open(((struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_6open(struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + size_t __pyx_t_3; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("open", 0); + + /* "thriftpy2/transport/buffered/cybuffered.pyx":36 + * + * def open(self): + * return self.trans.open() # <<<<<<<<<<<<<< + * + * def close(self): +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __pyx_v_self->__pyx_base.trans; + __Pyx_INCREF(__pyx_t_2); + __pyx_t_3 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, NULL}; + __pyx_t_1 = __Pyx_PyObject_FastCallMethod((PyObject*)__pyx_mstate_global->__pyx_n_u_open, __pyx_callargs+__pyx_t_3, (1-__pyx_t_3) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 36, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "thriftpy2/transport/buffered/cybuffered.pyx":35 + * return self.trans.is_open() + * + * def open(self): # <<<<<<<<<<<<<< + * return self.trans.open() + * +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("thriftpy2.transport.buffered.cybuffered.TCyBufferedTransport.open", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/buffered/cybuffered.pyx":38 + * return self.trans.open() + * + * def close(self): # <<<<<<<<<<<<<< + * return self.trans.close() + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_9close(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_9close = {"close", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_9close, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_9close(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("close (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("close", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("close", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_8close(((struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_8close(struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + size_t __pyx_t_3; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("close", 0); + + /* "thriftpy2/transport/buffered/cybuffered.pyx":39 + * + * def close(self): + * return self.trans.close() # <<<<<<<<<<<<<< + * + * def write(self, bytes data): +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __pyx_v_self->__pyx_base.trans; + __Pyx_INCREF(__pyx_t_2); + __pyx_t_3 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, NULL}; + __pyx_t_1 = __Pyx_PyObject_FastCallMethod((PyObject*)__pyx_mstate_global->__pyx_n_u_close, __pyx_callargs+__pyx_t_3, (1-__pyx_t_3) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 39, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "thriftpy2/transport/buffered/cybuffered.pyx":38 + * return self.trans.open() + * + * def close(self): # <<<<<<<<<<<<<< + * return self.trans.close() + * +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("thriftpy2.transport.buffered.cybuffered.TCyBufferedTransport.close", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/buffered/cybuffered.pyx":41 + * return self.trans.close() + * + * def write(self, bytes data): # <<<<<<<<<<<<<< + * cdef int sz = len(data) + * return self.c_write(data, sz) +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_11write(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_11write = {"write", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_11write, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_11write(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_data = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("write (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_data,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 41, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 41, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "write", 0) < (0)) __PYX_ERR(0, 41, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("write", 1, 1, 1, i); __PYX_ERR(0, 41, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 41, __pyx_L3_error) + } + __pyx_v_data = ((PyObject*)values[0]); + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("write", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 41, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("thriftpy2.transport.buffered.cybuffered.TCyBufferedTransport.write", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_data), (&PyBytes_Type), 1, "data", 1))) __PYX_ERR(0, 41, __pyx_L1_error) + __pyx_r = __pyx_pf_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_10write(((struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *)__pyx_v_self), __pyx_v_data); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + goto __pyx_L7_cleaned_up; + __pyx_L0:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __pyx_L7_cleaned_up:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_10write(struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *__pyx_v_self, PyObject *__pyx_v_data) { + int __pyx_v_sz; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + char *__pyx_t_2; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("write", 0); + + /* "thriftpy2/transport/buffered/cybuffered.pyx":42 + * + * def write(self, bytes data): + * cdef int sz = len(data) # <<<<<<<<<<<<<< + * return self.c_write(data, sz) + * +*/ + if (unlikely(__pyx_v_data == Py_None)) { + PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); + __PYX_ERR(0, 42, __pyx_L1_error) + } + __pyx_t_1 = __Pyx_PyBytes_GET_SIZE(__pyx_v_data); if (unlikely(__pyx_t_1 == ((Py_ssize_t)-1))) __PYX_ERR(0, 42, __pyx_L1_error) + __pyx_v_sz = __pyx_t_1; + + /* "thriftpy2/transport/buffered/cybuffered.pyx":43 + * def write(self, bytes data): + * cdef int sz = len(data) + * return self.c_write(data, sz) # <<<<<<<<<<<<<< + * + * def read(self, int sz): +*/ + __Pyx_XDECREF(__pyx_r); + if (unlikely(__pyx_v_data == Py_None)) { + PyErr_SetString(PyExc_TypeError, "expected bytes, NoneType found"); + __PYX_ERR(0, 43, __pyx_L1_error) + } + __pyx_t_2 = __Pyx_PyBytes_AsWritableString(__pyx_v_data); if (unlikely((!__pyx_t_2) && PyErr_Occurred())) __PYX_ERR(0, 43, __pyx_L1_error) + __pyx_t_3 = ((struct __pyx_vtabstruct_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *)__pyx_v_self->__pyx_base.__pyx_vtab)->__pyx_base.c_write(((struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *)__pyx_v_self), __pyx_t_2, __pyx_v_sz); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 43, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + + /* "thriftpy2/transport/buffered/cybuffered.pyx":41 + * return self.trans.close() + * + * def write(self, bytes data): # <<<<<<<<<<<<<< + * cdef int sz = len(data) + * return self.c_write(data, sz) +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("thriftpy2.transport.buffered.cybuffered.TCyBufferedTransport.write", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/buffered/cybuffered.pyx":45 + * return self.c_write(data, sz) + * + * def read(self, int sz): # <<<<<<<<<<<<<< + * return self.get_string(sz) + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_13read(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_13read = {"read", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_13read, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_13read(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + int __pyx_v_sz; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("read (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_sz,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 45, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 45, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "read", 0) < (0)) __PYX_ERR(0, 45, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("read", 1, 1, 1, i); __PYX_ERR(0, 45, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 45, __pyx_L3_error) + } + __pyx_v_sz = __Pyx_PyLong_As_int(values[0]); if (unlikely((__pyx_v_sz == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 45, __pyx_L3_error) + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("read", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 45, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("thriftpy2.transport.buffered.cybuffered.TCyBufferedTransport.read", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_12read(((struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *)__pyx_v_self), __pyx_v_sz); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_12read(struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *__pyx_v_self, int __pyx_v_sz) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("read", 0); + + /* "thriftpy2/transport/buffered/cybuffered.pyx":46 + * + * def read(self, int sz): + * return self.get_string(sz) # <<<<<<<<<<<<<< + * + * def flush(self): +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = ((struct __pyx_vtabstruct_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *)__pyx_v_self->__pyx_base.__pyx_vtab)->__pyx_base.get_string(((struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *)__pyx_v_self), __pyx_v_sz); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 46, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "thriftpy2/transport/buffered/cybuffered.pyx":45 + * return self.c_write(data, sz) + * + * def read(self, int sz): # <<<<<<<<<<<<<< + * return self.get_string(sz) + * +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("thriftpy2.transport.buffered.cybuffered.TCyBufferedTransport.read", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/buffered/cybuffered.pyx":48 + * return self.get_string(sz) + * + * def flush(self): # <<<<<<<<<<<<<< + * return self.c_flush() + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_15flush(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_15flush = {"flush", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_15flush, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_15flush(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("flush (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("flush", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("flush", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_14flush(((struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_14flush(struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("flush", 0); + + /* "thriftpy2/transport/buffered/cybuffered.pyx":49 + * + * def flush(self): + * return self.c_flush() # <<<<<<<<<<<<<< + * + * cdef c_write(self, const char *data, int sz): +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = ((struct __pyx_vtabstruct_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *)__pyx_v_self->__pyx_base.__pyx_vtab)->__pyx_base.c_flush(((struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *)__pyx_v_self)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 49, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "thriftpy2/transport/buffered/cybuffered.pyx":48 + * return self.get_string(sz) + * + * def flush(self): # <<<<<<<<<<<<<< + * return self.c_flush() + * +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("thriftpy2.transport.buffered.cybuffered.TCyBufferedTransport.flush", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/buffered/cybuffered.pyx":51 + * return self.c_flush() + * + * cdef c_write(self, const char *data, int sz): # <<<<<<<<<<<<<< + * cdef: + * int cap = self.wbuf.buf_size - self.wbuf.data_size +*/ + +static PyObject *__pyx_f_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_c_write(struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *__pyx_v_self, char const *__pyx_v_data, int __pyx_v_sz) { + int __pyx_v_cap; + int __pyx_v_r; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + size_t __pyx_t_5; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("c_write", 0); + + /* "thriftpy2/transport/buffered/cybuffered.pyx":53 + * cdef c_write(self, const char *data, int sz): + * cdef: + * int cap = self.wbuf.buf_size - self.wbuf.data_size # <<<<<<<<<<<<<< + * int r + * +*/ + __pyx_v_cap = (__pyx_v_self->wbuf->buf_size - __pyx_v_self->wbuf->data_size); + + /* "thriftpy2/transport/buffered/cybuffered.pyx":56 + * int r + * + * if cap < sz: # <<<<<<<<<<<<<< + * self.c_dump_wbuf() + * +*/ + __pyx_t_1 = (__pyx_v_cap < __pyx_v_sz); + if (__pyx_t_1) { + + /* "thriftpy2/transport/buffered/cybuffered.pyx":57 + * + * if cap < sz: + * self.c_dump_wbuf() # <<<<<<<<<<<<<< + * + * r = self.wbuf.write(sz, data) +*/ + __pyx_t_2 = ((struct __pyx_vtabstruct_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *)__pyx_v_self->__pyx_base.__pyx_vtab)->c_dump_wbuf(__pyx_v_self); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 57, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/transport/buffered/cybuffered.pyx":56 + * int r + * + * if cap < sz: # <<<<<<<<<<<<<< + * self.c_dump_wbuf() + * +*/ + } + + /* "thriftpy2/transport/buffered/cybuffered.pyx":59 + * self.c_dump_wbuf() + * + * r = self.wbuf.write(sz, data) # <<<<<<<<<<<<<< + * if r == -1: + * raise MemoryError("Write to buffer error") +*/ + __pyx_t_3 = ((struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_TCyBuffer *)__pyx_v_self->wbuf->__pyx_vtab)->write(__pyx_v_self->wbuf, __pyx_v_sz, __pyx_v_data); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 59, __pyx_L1_error) + __pyx_v_r = __pyx_t_3; + + /* "thriftpy2/transport/buffered/cybuffered.pyx":60 + * + * r = self.wbuf.write(sz, data) + * if r == -1: # <<<<<<<<<<<<<< + * raise MemoryError("Write to buffer error") + * +*/ + __pyx_t_1 = (__pyx_v_r == -1L); + if (unlikely(__pyx_t_1)) { + + /* "thriftpy2/transport/buffered/cybuffered.pyx":61 + * r = self.wbuf.write(sz, data) + * if r == -1: + * raise MemoryError("Write to buffer error") # <<<<<<<<<<<<<< + * + * cdef c_read(self, int sz, char* out): +*/ + __pyx_t_4 = NULL; + __pyx_t_5 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_4, __pyx_mstate_global->__pyx_kp_u_Write_to_buffer_error}; + __pyx_t_2 = __Pyx_PyObject_FastCall((PyObject*)(((PyTypeObject*)PyExc_MemoryError)), __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 61, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __PYX_ERR(0, 61, __pyx_L1_error) + + /* "thriftpy2/transport/buffered/cybuffered.pyx":60 + * + * r = self.wbuf.write(sz, data) + * if r == -1: # <<<<<<<<<<<<<< + * raise MemoryError("Write to buffer error") + * +*/ + } + + /* "thriftpy2/transport/buffered/cybuffered.pyx":51 + * return self.c_flush() + * + * cdef c_write(self, const char *data, int sz): # <<<<<<<<<<<<<< + * cdef: + * int cap = self.wbuf.buf_size - self.wbuf.data_size +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("thriftpy2.transport.buffered.cybuffered.TCyBufferedTransport.c_write", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/buffered/cybuffered.pyx":63 + * raise MemoryError("Write to buffer error") + * + * cdef c_read(self, int sz, char* out): # <<<<<<<<<<<<<< + * if sz <= 0: + * return 0 +*/ + +static PyObject *__pyx_f_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_c_read(struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *__pyx_v_self, int __pyx_v_sz, char *__pyx_v_out) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("c_read", 0); + + /* "thriftpy2/transport/buffered/cybuffered.pyx":64 + * + * cdef c_read(self, int sz, char* out): + * if sz <= 0: # <<<<<<<<<<<<<< + * return 0 + * +*/ + __pyx_t_1 = (__pyx_v_sz <= 0); + if (__pyx_t_1) { + + /* "thriftpy2/transport/buffered/cybuffered.pyx":65 + * cdef c_read(self, int sz, char* out): + * if sz <= 0: + * return 0 # <<<<<<<<<<<<<< + * + * self.read_trans(sz, out) +*/ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_mstate_global->__pyx_int_0); + __pyx_r = __pyx_mstate_global->__pyx_int_0; + goto __pyx_L0; + + /* "thriftpy2/transport/buffered/cybuffered.pyx":64 + * + * cdef c_read(self, int sz, char* out): + * if sz <= 0: # <<<<<<<<<<<<<< + * return 0 + * +*/ + } + + /* "thriftpy2/transport/buffered/cybuffered.pyx":67 + * return 0 + * + * self.read_trans(sz, out) # <<<<<<<<<<<<<< + * return sz + * +*/ + __pyx_t_2 = ((struct __pyx_vtabstruct_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *)__pyx_v_self->__pyx_base.__pyx_vtab)->read_trans(__pyx_v_self, __pyx_v_sz, __pyx_v_out); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 67, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/transport/buffered/cybuffered.pyx":68 + * + * self.read_trans(sz, out) + * return sz # <<<<<<<<<<<<<< + * + * cdef read_trans(self, int sz, char *out): +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __Pyx_PyLong_From_int(__pyx_v_sz); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 68, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "thriftpy2/transport/buffered/cybuffered.pyx":63 + * raise MemoryError("Write to buffer error") + * + * cdef c_read(self, int sz, char* out): # <<<<<<<<<<<<<< + * if sz <= 0: + * return 0 +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("thriftpy2.transport.buffered.cybuffered.TCyBufferedTransport.c_read", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/buffered/cybuffered.pyx":70 + * return sz + * + * cdef read_trans(self, int sz, char *out): # <<<<<<<<<<<<<< + * cdef int i = self.rbuf.read_trans(self.trans, sz, out) + * if i == -1: +*/ + +static PyObject *__pyx_f_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_read_trans(struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *__pyx_v_self, int __pyx_v_sz, char *__pyx_v_out) { + int __pyx_v_i; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + size_t __pyx_t_7; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("read_trans", 0); + + /* "thriftpy2/transport/buffered/cybuffered.pyx":71 + * + * cdef read_trans(self, int sz, char *out): + * cdef int i = self.rbuf.read_trans(self.trans, sz, out) # <<<<<<<<<<<<<< + * if i == -1: + * raise TTransportException(TTransportException.END_OF_FILE, +*/ + __pyx_t_1 = __pyx_v_self->__pyx_base.trans; + __Pyx_INCREF(__pyx_t_1); + __pyx_t_2 = ((struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_TCyBuffer *)__pyx_v_self->rbuf->__pyx_vtab)->read_trans(__pyx_v_self->rbuf, __pyx_t_1, __pyx_v_sz, __pyx_v_out); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 71, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_3 = __Pyx_PyLong_As_int(__pyx_t_2); if (unlikely((__pyx_t_3 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 71, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_v_i = __pyx_t_3; + + /* "thriftpy2/transport/buffered/cybuffered.pyx":72 + * cdef read_trans(self, int sz, char *out): + * cdef int i = self.rbuf.read_trans(self.trans, sz, out) + * if i == -1: # <<<<<<<<<<<<<< + * raise TTransportException(TTransportException.END_OF_FILE, + * "End of file reading from transport") +*/ + switch (__pyx_v_i) { + case -1L: + + /* "thriftpy2/transport/buffered/cybuffered.pyx":73 + * cdef int i = self.rbuf.read_trans(self.trans, sz, out) + * if i == -1: + * raise TTransportException(TTransportException.END_OF_FILE, # <<<<<<<<<<<<<< + * "End of file reading from transport") + * elif i == -2: +*/ + __pyx_t_1 = NULL; + __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_mstate_global->__pyx_n_u_TTransportException); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 73, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_GetModuleGlobalName(__pyx_t_5, __pyx_mstate_global->__pyx_n_u_TTransportException); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 73, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_mstate_global->__pyx_n_u_END_OF_FILE); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 73, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_7 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_4))) { + __pyx_t_1 = PyMethod_GET_SELF(__pyx_t_4); + assert(__pyx_t_1); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_4); + __Pyx_INCREF(__pyx_t_1); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_4, __pyx__function); + __pyx_t_7 = 0; + } + #endif + { + PyObject *__pyx_callargs[3] = {__pyx_t_1, __pyx_t_6, __pyx_mstate_global->__pyx_kp_u_End_of_file_reading_from_transpo}; + __pyx_t_2 = __Pyx_PyObject_FastCall((PyObject*)__pyx_t_4, __pyx_callargs+__pyx_t_7, (3-__pyx_t_7) | (__pyx_t_7*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 73, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __PYX_ERR(0, 73, __pyx_L1_error) + + /* "thriftpy2/transport/buffered/cybuffered.pyx":72 + * cdef read_trans(self, int sz, char *out): + * cdef int i = self.rbuf.read_trans(self.trans, sz, out) + * if i == -1: # <<<<<<<<<<<<<< + * raise TTransportException(TTransportException.END_OF_FILE, + * "End of file reading from transport") +*/ + break; + case -2L: + + /* "thriftpy2/transport/buffered/cybuffered.pyx":76 + * "End of file reading from transport") + * elif i == -2: + * raise MemoryError("grow read buffer fail") # <<<<<<<<<<<<<< + * + * cdef c_flush(self): +*/ + __pyx_t_4 = NULL; + __pyx_t_7 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_4, __pyx_mstate_global->__pyx_kp_u_grow_read_buffer_fail}; + __pyx_t_2 = __Pyx_PyObject_FastCall((PyObject*)(((PyTypeObject*)PyExc_MemoryError)), __pyx_callargs+__pyx_t_7, (2-__pyx_t_7) | (__pyx_t_7*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 76, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __PYX_ERR(0, 76, __pyx_L1_error) + + /* "thriftpy2/transport/buffered/cybuffered.pyx":75 + * raise TTransportException(TTransportException.END_OF_FILE, + * "End of file reading from transport") + * elif i == -2: # <<<<<<<<<<<<<< + * raise MemoryError("grow read buffer fail") + * +*/ + break; + default: break; + } + + /* "thriftpy2/transport/buffered/cybuffered.pyx":70 + * return sz + * + * cdef read_trans(self, int sz, char *out): # <<<<<<<<<<<<<< + * cdef int i = self.rbuf.read_trans(self.trans, sz, out) + * if i == -1: +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_AddTraceback("thriftpy2.transport.buffered.cybuffered.TCyBufferedTransport.read_trans", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/buffered/cybuffered.pyx":78 + * raise MemoryError("grow read buffer fail") + * + * cdef c_flush(self): # <<<<<<<<<<<<<< + * self.c_dump_wbuf() + * self.trans.flush() +*/ + +static PyObject *__pyx_f_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_c_flush(struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + size_t __pyx_t_3; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("c_flush", 0); + + /* "thriftpy2/transport/buffered/cybuffered.pyx":79 + * + * cdef c_flush(self): + * self.c_dump_wbuf() # <<<<<<<<<<<<<< + * self.trans.flush() + * +*/ + __pyx_t_1 = ((struct __pyx_vtabstruct_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *)__pyx_v_self->__pyx_base.__pyx_vtab)->c_dump_wbuf(__pyx_v_self); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 79, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "thriftpy2/transport/buffered/cybuffered.pyx":80 + * cdef c_flush(self): + * self.c_dump_wbuf() + * self.trans.flush() # <<<<<<<<<<<<<< + * + * cdef c_dump_wbuf(self): +*/ + __pyx_t_2 = __pyx_v_self->__pyx_base.trans; + __Pyx_INCREF(__pyx_t_2); + __pyx_t_3 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, NULL}; + __pyx_t_1 = __Pyx_PyObject_FastCallMethod((PyObject*)__pyx_mstate_global->__pyx_n_u_flush, __pyx_callargs+__pyx_t_3, (1-__pyx_t_3) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 80, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "thriftpy2/transport/buffered/cybuffered.pyx":78 + * raise MemoryError("grow read buffer fail") + * + * cdef c_flush(self): # <<<<<<<<<<<<<< + * self.c_dump_wbuf() + * self.trans.flush() +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("thriftpy2.transport.buffered.cybuffered.TCyBufferedTransport.c_flush", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/buffered/cybuffered.pyx":82 + * self.trans.flush() + * + * cdef c_dump_wbuf(self): # <<<<<<<<<<<<<< + * cdef bytes data + * if self.wbuf.data_size > 0: +*/ + +static PyObject *__pyx_f_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_c_dump_wbuf(struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *__pyx_v_self) { + PyObject *__pyx_v_data = 0; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + size_t __pyx_t_4; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("c_dump_wbuf", 0); + + /* "thriftpy2/transport/buffered/cybuffered.pyx":84 + * cdef c_dump_wbuf(self): + * cdef bytes data + * if self.wbuf.data_size > 0: # <<<<<<<<<<<<<< + * data = self.wbuf.buf[:self.wbuf.data_size] + * self.trans.write(data) +*/ + __pyx_t_1 = (__pyx_v_self->wbuf->data_size > 0); + if (__pyx_t_1) { + + /* "thriftpy2/transport/buffered/cybuffered.pyx":85 + * cdef bytes data + * if self.wbuf.data_size > 0: + * data = self.wbuf.buf[:self.wbuf.data_size] # <<<<<<<<<<<<<< + * self.trans.write(data) + * self.wbuf.clean() +*/ + __pyx_t_2 = __Pyx_PyBytes_FromStringAndSize(__pyx_v_self->wbuf->buf + 0, __pyx_v_self->wbuf->data_size - 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 85, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_v_data = ((PyObject*)__pyx_t_2); + __pyx_t_2 = 0; + + /* "thriftpy2/transport/buffered/cybuffered.pyx":86 + * if self.wbuf.data_size > 0: + * data = self.wbuf.buf[:self.wbuf.data_size] + * self.trans.write(data) # <<<<<<<<<<<<<< + * self.wbuf.clean() + * +*/ + __pyx_t_3 = __pyx_v_self->__pyx_base.trans; + __Pyx_INCREF(__pyx_t_3); + __pyx_t_4 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_v_data}; + __pyx_t_2 = __Pyx_PyObject_FastCallMethod((PyObject*)__pyx_mstate_global->__pyx_n_u_write, __pyx_callargs+__pyx_t_4, (2-__pyx_t_4) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 86, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/transport/buffered/cybuffered.pyx":87 + * data = self.wbuf.buf[:self.wbuf.data_size] + * self.trans.write(data) + * self.wbuf.clean() # <<<<<<<<<<<<<< + * + * def getvalue(self): +*/ + ((struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_TCyBuffer *)__pyx_v_self->wbuf->__pyx_vtab)->clean(__pyx_v_self->wbuf); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 87, __pyx_L1_error) + + /* "thriftpy2/transport/buffered/cybuffered.pyx":84 + * cdef c_dump_wbuf(self): + * cdef bytes data + * if self.wbuf.data_size > 0: # <<<<<<<<<<<<<< + * data = self.wbuf.buf[:self.wbuf.data_size] + * self.trans.write(data) +*/ + } + + /* "thriftpy2/transport/buffered/cybuffered.pyx":82 + * self.trans.flush() + * + * cdef c_dump_wbuf(self): # <<<<<<<<<<<<<< + * cdef bytes data + * if self.wbuf.data_size > 0: +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("thriftpy2.transport.buffered.cybuffered.TCyBufferedTransport.c_dump_wbuf", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_data); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/buffered/cybuffered.pyx":89 + * self.wbuf.clean() + * + * def getvalue(self): # <<<<<<<<<<<<<< + * return self.trans.getvalue() + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_17getvalue(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_17getvalue = {"getvalue", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_17getvalue, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_17getvalue(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("getvalue (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("getvalue", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("getvalue", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_16getvalue(((struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_16getvalue(struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + size_t __pyx_t_3; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("getvalue", 0); + + /* "thriftpy2/transport/buffered/cybuffered.pyx":90 + * + * def getvalue(self): + * return self.trans.getvalue() # <<<<<<<<<<<<<< + * + * +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __pyx_v_self->__pyx_base.trans; + __Pyx_INCREF(__pyx_t_2); + __pyx_t_3 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, NULL}; + __pyx_t_1 = __Pyx_PyObject_FastCallMethod((PyObject*)__pyx_mstate_global->__pyx_n_u_getvalue, __pyx_callargs+__pyx_t_3, (1-__pyx_t_3) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 90, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "thriftpy2/transport/buffered/cybuffered.pyx":89 + * self.wbuf.clean() + * + * def getvalue(self): # <<<<<<<<<<<<<< + * return self.trans.getvalue() + * +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("thriftpy2.transport.buffered.cybuffered.TCyBufferedTransport.getvalue", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * cdef tuple state + * cdef object _dict +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_19__reduce_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_19__reduce_cython__ = {"__reduce_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_19__reduce_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_19__reduce_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("__reduce_cython__", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("__reduce_cython__", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_18__reduce_cython__(((struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_18__reduce_cython__(struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *__pyx_v_self) { + PyObject *__pyx_v_state = 0; + PyObject *__pyx_v__dict = 0; + int __pyx_v_use_setstate; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__reduce_cython__", 0); + + /* "(tree fragment)":5 + * cdef object _dict + * cdef bint use_setstate + * state = (self.rbuf, self.trans, self.wbuf) # <<<<<<<<<<<<<< + * _dict = getattr(self, '__dict__', None) + * if _dict is not None and _dict: +*/ + __pyx_t_1 = PyTuple_New(3); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 5, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF((PyObject *)__pyx_v_self->rbuf); + __Pyx_GIVEREF((PyObject *)__pyx_v_self->rbuf); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_v_self->rbuf)) != (0)) __PYX_ERR(1, 5, __pyx_L1_error); + __Pyx_INCREF(__pyx_v_self->__pyx_base.trans); + __Pyx_GIVEREF(__pyx_v_self->__pyx_base.trans); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_self->__pyx_base.trans) != (0)) __PYX_ERR(1, 5, __pyx_L1_error); + __Pyx_INCREF((PyObject *)__pyx_v_self->wbuf); + __Pyx_GIVEREF((PyObject *)__pyx_v_self->wbuf); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 2, ((PyObject *)__pyx_v_self->wbuf)) != (0)) __PYX_ERR(1, 5, __pyx_L1_error); + __pyx_v_state = ((PyObject*)__pyx_t_1); + __pyx_t_1 = 0; + + /* "(tree fragment)":6 + * cdef bint use_setstate + * state = (self.rbuf, self.trans, self.wbuf) + * _dict = getattr(self, '__dict__', None) # <<<<<<<<<<<<<< + * if _dict is not None and _dict: + * state += (_dict,) +*/ + __pyx_t_1 = __Pyx_GetAttr3(((PyObject *)__pyx_v_self), __pyx_mstate_global->__pyx_n_u_dict, Py_None); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 6, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v__dict = __pyx_t_1; + __pyx_t_1 = 0; + + /* "(tree fragment)":7 + * state = (self.rbuf, self.trans, self.wbuf) + * _dict = getattr(self, '__dict__', None) + * if _dict is not None and _dict: # <<<<<<<<<<<<<< + * state += (_dict,) + * use_setstate = True +*/ + __pyx_t_3 = (__pyx_v__dict != Py_None); + if (__pyx_t_3) { + } else { + __pyx_t_2 = __pyx_t_3; + goto __pyx_L4_bool_binop_done; + } + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_v__dict); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(1, 7, __pyx_L1_error) + __pyx_t_2 = __pyx_t_3; + __pyx_L4_bool_binop_done:; + if (__pyx_t_2) { + + /* "(tree fragment)":8 + * _dict = getattr(self, '__dict__', None) + * if _dict is not None and _dict: + * state += (_dict,) # <<<<<<<<<<<<<< + * use_setstate = True + * else: +*/ + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 8, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_v__dict); + __Pyx_GIVEREF(__pyx_v__dict); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v__dict) != (0)) __PYX_ERR(1, 8, __pyx_L1_error); + __pyx_t_4 = PyNumber_InPlaceAdd(__pyx_v_state, __pyx_t_1); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 8, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF_SET(__pyx_v_state, ((PyObject*)__pyx_t_4)); + __pyx_t_4 = 0; + + /* "(tree fragment)":9 + * if _dict is not None and _dict: + * state += (_dict,) + * use_setstate = True # <<<<<<<<<<<<<< + * else: + * use_setstate = self.rbuf is not None or self.trans is not None or self.wbuf is not None +*/ + __pyx_v_use_setstate = 1; + + /* "(tree fragment)":7 + * state = (self.rbuf, self.trans, self.wbuf) + * _dict = getattr(self, '__dict__', None) + * if _dict is not None and _dict: # <<<<<<<<<<<<<< + * state += (_dict,) + * use_setstate = True +*/ + goto __pyx_L3; + } + + /* "(tree fragment)":11 + * use_setstate = True + * else: + * use_setstate = self.rbuf is not None or self.trans is not None or self.wbuf is not None # <<<<<<<<<<<<<< + * if use_setstate: + * return __pyx_unpickle_TCyBufferedTransport, (type(self), 0x9ee77cd, None), state +*/ + /*else*/ { + __pyx_t_3 = (((PyObject *)__pyx_v_self->rbuf) != Py_None); + if (!__pyx_t_3) { + } else { + __pyx_t_2 = __pyx_t_3; + goto __pyx_L6_bool_binop_done; + } + __pyx_t_3 = (__pyx_v_self->__pyx_base.trans != Py_None); + if (!__pyx_t_3) { + } else { + __pyx_t_2 = __pyx_t_3; + goto __pyx_L6_bool_binop_done; + } + __pyx_t_3 = (((PyObject *)__pyx_v_self->wbuf) != Py_None); + __pyx_t_2 = __pyx_t_3; + __pyx_L6_bool_binop_done:; + __pyx_v_use_setstate = __pyx_t_2; + } + __pyx_L3:; + + /* "(tree fragment)":12 + * else: + * use_setstate = self.rbuf is not None or self.trans is not None or self.wbuf is not None + * if use_setstate: # <<<<<<<<<<<<<< + * return __pyx_unpickle_TCyBufferedTransport, (type(self), 0x9ee77cd, None), state + * else: +*/ + if (__pyx_v_use_setstate) { + + /* "(tree fragment)":13 + * use_setstate = self.rbuf is not None or self.trans is not None or self.wbuf is not None + * if use_setstate: + * return __pyx_unpickle_TCyBufferedTransport, (type(self), 0x9ee77cd, None), state # <<<<<<<<<<<<<< + * else: + * return __pyx_unpickle_TCyBufferedTransport, (type(self), 0x9ee77cd, state) +*/ + __Pyx_XDECREF(__pyx_r); + __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_mstate_global->__pyx_n_u_pyx_unpickle_TCyBufferedTransp); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 13, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_1 = PyTuple_New(3); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 13, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); + __Pyx_GIVEREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))) != (0)) __PYX_ERR(1, 13, __pyx_L1_error); + __Pyx_INCREF(__pyx_mstate_global->__pyx_int_166623181); + __Pyx_GIVEREF(__pyx_mstate_global->__pyx_int_166623181); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_mstate_global->__pyx_int_166623181) != (0)) __PYX_ERR(1, 13, __pyx_L1_error); + __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(Py_None); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 2, Py_None) != (0)) __PYX_ERR(1, 13, __pyx_L1_error); + __pyx_t_5 = PyTuple_New(3); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 13, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_GIVEREF(__pyx_t_4); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4) != (0)) __PYX_ERR(1, 13, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_1); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_1) != (0)) __PYX_ERR(1, 13, __pyx_L1_error); + __Pyx_INCREF(__pyx_v_state); + __Pyx_GIVEREF(__pyx_v_state); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_5, 2, __pyx_v_state) != (0)) __PYX_ERR(1, 13, __pyx_L1_error); + __pyx_t_4 = 0; + __pyx_t_1 = 0; + __pyx_r = __pyx_t_5; + __pyx_t_5 = 0; + goto __pyx_L0; + + /* "(tree fragment)":12 + * else: + * use_setstate = self.rbuf is not None or self.trans is not None or self.wbuf is not None + * if use_setstate: # <<<<<<<<<<<<<< + * return __pyx_unpickle_TCyBufferedTransport, (type(self), 0x9ee77cd, None), state + * else: +*/ + } + + /* "(tree fragment)":15 + * return __pyx_unpickle_TCyBufferedTransport, (type(self), 0x9ee77cd, None), state + * else: + * return __pyx_unpickle_TCyBufferedTransport, (type(self), 0x9ee77cd, state) # <<<<<<<<<<<<<< + * def __setstate_cython__(self, __pyx_state): + * __pyx_unpickle_TCyBufferedTransport__set_state(self, __pyx_state) +*/ + /*else*/ { + __Pyx_XDECREF(__pyx_r); + __Pyx_GetModuleGlobalName(__pyx_t_5, __pyx_mstate_global->__pyx_n_u_pyx_unpickle_TCyBufferedTransp); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 15, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_1 = PyTuple_New(3); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 15, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); + __Pyx_GIVEREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))) != (0)) __PYX_ERR(1, 15, __pyx_L1_error); + __Pyx_INCREF(__pyx_mstate_global->__pyx_int_166623181); + __Pyx_GIVEREF(__pyx_mstate_global->__pyx_int_166623181); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_mstate_global->__pyx_int_166623181) != (0)) __PYX_ERR(1, 15, __pyx_L1_error); + __Pyx_INCREF(__pyx_v_state); + __Pyx_GIVEREF(__pyx_v_state); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 2, __pyx_v_state) != (0)) __PYX_ERR(1, 15, __pyx_L1_error); + __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 15, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_GIVEREF(__pyx_t_5); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_5) != (0)) __PYX_ERR(1, 15, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_1); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_1) != (0)) __PYX_ERR(1, 15, __pyx_L1_error); + __pyx_t_5 = 0; + __pyx_t_1 = 0; + __pyx_r = __pyx_t_4; + __pyx_t_4 = 0; + goto __pyx_L0; + } + + /* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * cdef tuple state + * cdef object _dict +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("thriftpy2.transport.buffered.cybuffered.TCyBufferedTransport.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_state); + __Pyx_XDECREF(__pyx_v__dict); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":16 + * else: + * return __pyx_unpickle_TCyBufferedTransport, (type(self), 0x9ee77cd, state) + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * __pyx_unpickle_TCyBufferedTransport__set_state(self, __pyx_state) +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_21__setstate_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_21__setstate_cython__ = {"__setstate_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_21__setstate_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_21__setstate_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v___pyx_state = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_pyx_state,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(1, 16, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(1, 16, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "__setstate_cython__", 0) < (0)) __PYX_ERR(1, 16, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("__setstate_cython__", 1, 1, 1, i); __PYX_ERR(1, 16, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(1, 16, __pyx_L3_error) + } + __pyx_v___pyx_state = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__setstate_cython__", 1, 1, 1, __pyx_nargs); __PYX_ERR(1, 16, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("thriftpy2.transport.buffered.cybuffered.TCyBufferedTransport.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_20__setstate_cython__(((struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *)__pyx_v_self), __pyx_v___pyx_state); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_20__setstate_cython__(struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *__pyx_v_self, PyObject *__pyx_v___pyx_state) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__setstate_cython__", 0); + + /* "(tree fragment)":17 + * return __pyx_unpickle_TCyBufferedTransport, (type(self), 0x9ee77cd, state) + * def __setstate_cython__(self, __pyx_state): + * __pyx_unpickle_TCyBufferedTransport__set_state(self, __pyx_state) # <<<<<<<<<<<<<< +*/ + __pyx_t_1 = __pyx_v___pyx_state; + __Pyx_INCREF(__pyx_t_1); + if (!(likely(PyTuple_CheckExact(__pyx_t_1))||((__pyx_t_1) == Py_None) || __Pyx_RaiseUnexpectedTypeError("tuple", __pyx_t_1))) __PYX_ERR(1, 17, __pyx_L1_error) + if (unlikely(__pyx_t_1 == Py_None)) { + PyErr_SetString(PyExc_TypeError, "cannot pass None into a C function argument that is declared 'not None'"); + __PYX_ERR(1, 17, __pyx_L1_error) + } + __pyx_t_2 = __pyx_f_9thriftpy2_9transport_8buffered_10cybuffered___pyx_unpickle_TCyBufferedTransport__set_state(__pyx_v_self, ((PyObject*)__pyx_t_1)); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 17, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "(tree fragment)":16 + * else: + * return __pyx_unpickle_TCyBufferedTransport, (type(self), 0x9ee77cd, state) + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * __pyx_unpickle_TCyBufferedTransport__set_state(self, __pyx_state) +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("thriftpy2.transport.buffered.cybuffered.TCyBufferedTransport.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/buffered/cybuffered.pyx":94 + * + * class TCyBufferedTransportFactory(object): + * def get_transport(self, trans): # <<<<<<<<<<<<<< + * return TCyBufferedTransport(trans) +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_9transport_8buffered_10cybuffered_27TCyBufferedTransportFactory_1get_transport(PyObject *__pyx_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_9transport_8buffered_10cybuffered_27TCyBufferedTransportFactory_1get_transport = {"get_transport", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_8buffered_10cybuffered_27TCyBufferedTransportFactory_1get_transport, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_9transport_8buffered_10cybuffered_27TCyBufferedTransportFactory_1get_transport(PyObject *__pyx_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + CYTHON_UNUSED PyObject *__pyx_v_self = 0; + PyObject *__pyx_v_trans = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[2] = {0,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("get_transport (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_self,&__pyx_mstate_global->__pyx_n_u_trans,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 94, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 2: + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 94, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 94, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "get_transport", 0) < (0)) __PYX_ERR(0, 94, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 2; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("get_transport", 1, 2, 2, i); __PYX_ERR(0, 94, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 2)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 94, __pyx_L3_error) + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 94, __pyx_L3_error) + } + __pyx_v_self = values[0]; + __pyx_v_trans = values[1]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("get_transport", 1, 2, 2, __pyx_nargs); __PYX_ERR(0, 94, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("thriftpy2.transport.buffered.cybuffered.TCyBufferedTransportFactory.get_transport", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_9thriftpy2_9transport_8buffered_10cybuffered_27TCyBufferedTransportFactory_get_transport(__pyx_self, __pyx_v_self, __pyx_v_trans); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_9transport_8buffered_10cybuffered_27TCyBufferedTransportFactory_get_transport(CYTHON_UNUSED PyObject *__pyx_self, CYTHON_UNUSED PyObject *__pyx_v_self, PyObject *__pyx_v_trans) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + size_t __pyx_t_3; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("get_transport", 0); + + /* "thriftpy2/transport/buffered/cybuffered.pyx":95 + * class TCyBufferedTransportFactory(object): + * def get_transport(self, trans): + * return TCyBufferedTransport(trans) # <<<<<<<<<<<<<< +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = NULL; + __pyx_t_3 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, __pyx_v_trans}; + __pyx_t_1 = __Pyx_PyObject_FastCall((PyObject*)__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport, __pyx_callargs+__pyx_t_3, (2-__pyx_t_3) | (__pyx_t_3*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 95, __pyx_L1_error) + __Pyx_GOTREF((PyObject *)__pyx_t_1); + } + __pyx_r = ((PyObject *)__pyx_t_1); + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "thriftpy2/transport/buffered/cybuffered.pyx":94 + * + * class TCyBufferedTransportFactory(object): + * def get_transport(self, trans): # <<<<<<<<<<<<<< + * return TCyBufferedTransport(trans) +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("thriftpy2.transport.buffered.cybuffered.TCyBufferedTransportFactory.get_transport", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":4 + * int __Pyx_CheckUnpickleChecksum(long, long, long, long, const char*) except -1 + * int __Pyx_UpdateUnpickledDict(object, object, Py_ssize_t) except -1 + * def __pyx_unpickle_TCyBufferedTransport(__pyx_type, long __pyx_checksum, tuple __pyx_state): # <<<<<<<<<<<<<< + * cdef object __pyx_result + * __Pyx_CheckUnpickleChecksum(__pyx_checksum, 0x9ee77cd, 0x79d98b4, 0x551bc31, b'rbuf, trans, wbuf') +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_9transport_8buffered_10cybuffered_1__pyx_unpickle_TCyBufferedTransport(PyObject *__pyx_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_9transport_8buffered_10cybuffered_1__pyx_unpickle_TCyBufferedTransport = {"__pyx_unpickle_TCyBufferedTransport", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_8buffered_10cybuffered_1__pyx_unpickle_TCyBufferedTransport, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_9transport_8buffered_10cybuffered_1__pyx_unpickle_TCyBufferedTransport(PyObject *__pyx_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v___pyx_type = 0; + long __pyx_v___pyx_checksum; + PyObject *__pyx_v___pyx_state = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[3] = {0,0,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__pyx_unpickle_TCyBufferedTransport (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_pyx_type,&__pyx_mstate_global->__pyx_n_u_pyx_checksum,&__pyx_mstate_global->__pyx_n_u_pyx_state,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(1, 4, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 3: + values[2] = __Pyx_ArgRef_FASTCALL(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(1, 4, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 2: + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(1, 4, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(1, 4, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "__pyx_unpickle_TCyBufferedTransport", 0) < (0)) __PYX_ERR(1, 4, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 3; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("__pyx_unpickle_TCyBufferedTransport", 1, 3, 3, i); __PYX_ERR(1, 4, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 3)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(1, 4, __pyx_L3_error) + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(1, 4, __pyx_L3_error) + values[2] = __Pyx_ArgRef_FASTCALL(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(1, 4, __pyx_L3_error) + } + __pyx_v___pyx_type = values[0]; + __pyx_v___pyx_checksum = __Pyx_PyLong_As_long(values[1]); if (unlikely((__pyx_v___pyx_checksum == (long)-1) && PyErr_Occurred())) __PYX_ERR(1, 4, __pyx_L3_error) + __pyx_v___pyx_state = ((PyObject*)values[2]); + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__pyx_unpickle_TCyBufferedTransport", 1, 3, 3, __pyx_nargs); __PYX_ERR(1, 4, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("thriftpy2.transport.buffered.cybuffered.__pyx_unpickle_TCyBufferedTransport", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v___pyx_state), (&PyTuple_Type), 1, "__pyx_state", 1))) __PYX_ERR(1, 4, __pyx_L1_error) + __pyx_r = __pyx_pf_9thriftpy2_9transport_8buffered_10cybuffered___pyx_unpickle_TCyBufferedTransport(__pyx_self, __pyx_v___pyx_type, __pyx_v___pyx_checksum, __pyx_v___pyx_state); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + goto __pyx_L7_cleaned_up; + __pyx_L0:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __pyx_L7_cleaned_up:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_9transport_8buffered_10cybuffered___pyx_unpickle_TCyBufferedTransport(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v___pyx_type, long __pyx_v___pyx_checksum, PyObject *__pyx_v___pyx_state) { + PyObject *__pyx_v___pyx_result = 0; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + size_t __pyx_t_4; + int __pyx_t_5; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__pyx_unpickle_TCyBufferedTransport", 0); + + /* "(tree fragment)":6 + * def __pyx_unpickle_TCyBufferedTransport(__pyx_type, long __pyx_checksum, tuple __pyx_state): + * cdef object __pyx_result + * __Pyx_CheckUnpickleChecksum(__pyx_checksum, 0x9ee77cd, 0x79d98b4, 0x551bc31, b'rbuf, trans, wbuf') # <<<<<<<<<<<<<< + * __pyx_result = TCyBufferedTransport.__new__(__pyx_type) + * if __pyx_state is not None: +*/ + __pyx_t_1 = __Pyx_CheckUnpickleChecksum(__pyx_v___pyx_checksum, 0x9ee77cd, 0x79d98b4, 0x551bc31, __pyx_k_rbuf_trans_wbuf); if (unlikely(__pyx_t_1 == ((int)-1))) __PYX_ERR(1, 6, __pyx_L1_error) + + /* "(tree fragment)":7 + * cdef object __pyx_result + * __Pyx_CheckUnpickleChecksum(__pyx_checksum, 0x9ee77cd, 0x79d98b4, 0x551bc31, b'rbuf, trans, wbuf') + * __pyx_result = TCyBufferedTransport.__new__(__pyx_type) # <<<<<<<<<<<<<< + * if __pyx_state is not None: + * __pyx_unpickle_TCyBufferedTransport__set_state( __pyx_result, __pyx_state) +*/ + __pyx_t_3 = ((PyObject *)__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport); + __Pyx_INCREF(__pyx_t_3); + __pyx_t_4 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_v___pyx_type}; + __pyx_t_2 = __Pyx_PyObject_FastCallMethod((PyObject*)__pyx_mstate_global->__pyx_n_u_new, __pyx_callargs+__pyx_t_4, (2-__pyx_t_4) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 7, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __pyx_v___pyx_result = __pyx_t_2; + __pyx_t_2 = 0; + + /* "(tree fragment)":8 + * __Pyx_CheckUnpickleChecksum(__pyx_checksum, 0x9ee77cd, 0x79d98b4, 0x551bc31, b'rbuf, trans, wbuf') + * __pyx_result = TCyBufferedTransport.__new__(__pyx_type) + * if __pyx_state is not None: # <<<<<<<<<<<<<< + * __pyx_unpickle_TCyBufferedTransport__set_state( __pyx_result, __pyx_state) + * return __pyx_result +*/ + __pyx_t_5 = (__pyx_v___pyx_state != ((PyObject*)Py_None)); + if (__pyx_t_5) { + + /* "(tree fragment)":9 + * __pyx_result = TCyBufferedTransport.__new__(__pyx_type) + * if __pyx_state is not None: + * __pyx_unpickle_TCyBufferedTransport__set_state( __pyx_result, __pyx_state) # <<<<<<<<<<<<<< + * return __pyx_result + * cdef __pyx_unpickle_TCyBufferedTransport__set_state(TCyBufferedTransport __pyx_result, __pyx_state: tuple): +*/ + if (unlikely(__pyx_v___pyx_state == Py_None)) { + PyErr_SetString(PyExc_TypeError, "cannot pass None into a C function argument that is declared 'not None'"); + __PYX_ERR(1, 9, __pyx_L1_error) + } + __pyx_t_2 = __pyx_f_9thriftpy2_9transport_8buffered_10cybuffered___pyx_unpickle_TCyBufferedTransport__set_state(((struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *)__pyx_v___pyx_result), __pyx_v___pyx_state); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 9, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "(tree fragment)":8 + * __Pyx_CheckUnpickleChecksum(__pyx_checksum, 0x9ee77cd, 0x79d98b4, 0x551bc31, b'rbuf, trans, wbuf') + * __pyx_result = TCyBufferedTransport.__new__(__pyx_type) + * if __pyx_state is not None: # <<<<<<<<<<<<<< + * __pyx_unpickle_TCyBufferedTransport__set_state( __pyx_result, __pyx_state) + * return __pyx_result +*/ + } + + /* "(tree fragment)":10 + * if __pyx_state is not None: + * __pyx_unpickle_TCyBufferedTransport__set_state( __pyx_result, __pyx_state) + * return __pyx_result # <<<<<<<<<<<<<< + * cdef __pyx_unpickle_TCyBufferedTransport__set_state(TCyBufferedTransport __pyx_result, __pyx_state: tuple): + * __pyx_result.rbuf = __pyx_state[0]; __pyx_result.trans = __pyx_state[1]; __pyx_result.wbuf = __pyx_state[2] +*/ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v___pyx_result); + __pyx_r = __pyx_v___pyx_result; + goto __pyx_L0; + + /* "(tree fragment)":4 + * int __Pyx_CheckUnpickleChecksum(long, long, long, long, const char*) except -1 + * int __Pyx_UpdateUnpickledDict(object, object, Py_ssize_t) except -1 + * def __pyx_unpickle_TCyBufferedTransport(__pyx_type, long __pyx_checksum, tuple __pyx_state): # <<<<<<<<<<<<<< + * cdef object __pyx_result + * __Pyx_CheckUnpickleChecksum(__pyx_checksum, 0x9ee77cd, 0x79d98b4, 0x551bc31, b'rbuf, trans, wbuf') +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("thriftpy2.transport.buffered.cybuffered.__pyx_unpickle_TCyBufferedTransport", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v___pyx_result); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":11 + * __pyx_unpickle_TCyBufferedTransport__set_state( __pyx_result, __pyx_state) + * return __pyx_result + * cdef __pyx_unpickle_TCyBufferedTransport__set_state(TCyBufferedTransport __pyx_result, __pyx_state: tuple): # <<<<<<<<<<<<<< + * __pyx_result.rbuf = __pyx_state[0]; __pyx_result.trans = __pyx_state[1]; __pyx_result.wbuf = __pyx_state[2] + * __Pyx_UpdateUnpickledDict(__pyx_result, __pyx_state, 3) +*/ + +static PyObject *__pyx_f_9thriftpy2_9transport_8buffered_10cybuffered___pyx_unpickle_TCyBufferedTransport__set_state(struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *__pyx_v___pyx_result, PyObject *__pyx_v___pyx_state) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__pyx_unpickle_TCyBufferedTransport__set_state", 0); + + /* "(tree fragment)":12 + * return __pyx_result + * cdef __pyx_unpickle_TCyBufferedTransport__set_state(TCyBufferedTransport __pyx_result, __pyx_state: tuple): + * __pyx_result.rbuf = __pyx_state[0]; __pyx_result.trans = __pyx_state[1]; __pyx_result.wbuf = __pyx_state[2] # <<<<<<<<<<<<<< + * __Pyx_UpdateUnpickledDict(__pyx_result, __pyx_state, 3) +*/ + __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 0, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1, __Pyx_ReferenceSharing_FunctionArgument); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 12, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer))))) __PYX_ERR(1, 12, __pyx_L1_error) + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF((PyObject *)__pyx_v___pyx_result->rbuf); + __Pyx_DECREF((PyObject *)__pyx_v___pyx_result->rbuf); + __pyx_v___pyx_result->rbuf = ((struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *)__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 1, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1, __Pyx_ReferenceSharing_FunctionArgument); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 12, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF(__pyx_v___pyx_result->__pyx_base.trans); + __Pyx_DECREF(__pyx_v___pyx_result->__pyx_base.trans); + __pyx_v___pyx_result->__pyx_base.trans = __pyx_t_1; + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 2, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1, __Pyx_ReferenceSharing_FunctionArgument); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 12, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer))))) __PYX_ERR(1, 12, __pyx_L1_error) + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF((PyObject *)__pyx_v___pyx_result->wbuf); + __Pyx_DECREF((PyObject *)__pyx_v___pyx_result->wbuf); + __pyx_v___pyx_result->wbuf = ((struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "(tree fragment)":13 + * cdef __pyx_unpickle_TCyBufferedTransport__set_state(TCyBufferedTransport __pyx_result, __pyx_state: tuple): + * __pyx_result.rbuf = __pyx_state[0]; __pyx_result.trans = __pyx_state[1]; __pyx_result.wbuf = __pyx_state[2] + * __Pyx_UpdateUnpickledDict(__pyx_result, __pyx_state, 3) # <<<<<<<<<<<<<< +*/ + __pyx_t_2 = __Pyx_UpdateUnpickledDict(((PyObject *)__pyx_v___pyx_result), __pyx_v___pyx_state, 3); if (unlikely(__pyx_t_2 == ((int)-1))) __PYX_ERR(1, 13, __pyx_L1_error) + + /* "(tree fragment)":11 + * __pyx_unpickle_TCyBufferedTransport__set_state( __pyx_result, __pyx_state) + * return __pyx_result + * cdef __pyx_unpickle_TCyBufferedTransport__set_state(TCyBufferedTransport __pyx_result, __pyx_state: tuple): # <<<<<<<<<<<<<< + * __pyx_result.rbuf = __pyx_state[0]; __pyx_result.trans = __pyx_state[1]; __pyx_result.wbuf = __pyx_state[2] + * __Pyx_UpdateUnpickledDict(__pyx_result, __pyx_state, 3) +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("thriftpy2.transport.buffered.cybuffered.__pyx_unpickle_TCyBufferedTransport__set_state", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} +/* #### Code section: module_exttypes ### */ +static struct __pyx_vtabstruct_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport __pyx_vtable_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport; + +static PyObject *__pyx_tp_new_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *p; + PyObject *o = __Pyx_PyType_GetSlot(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase, tp_new, newfunc)(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *)o); + p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_CyTransportBase*)__pyx_vtabptr_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport; + p->rbuf = ((struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *)Py_None); Py_INCREF(Py_None); + p->wbuf = ((struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *)Py_None); Py_INCREF(Py_None); + return o; +} + +static void __pyx_tp_dealloc_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport(PyObject *o) { + struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *p = (struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *)o; + #if CYTHON_USE_TP_FINALIZE + if (unlikely(__Pyx_PyObject_GetSlot(o, tp_finalize, destructor)) && !__Pyx_PyObject_GC_IsFinalized(o)) { + if (__Pyx_PyObject_GetSlot(o, tp_dealloc, destructor) == __pyx_tp_dealloc_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + } + #endif + PyObject_GC_UnTrack(o); + Py_CLEAR(p->rbuf); + Py_CLEAR(p->wbuf); + if (PyType_IS_GC(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase)) PyObject_GC_Track(o); + #if !CYTHON_USE_MODULE_STATE + if (likely(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase)) __Pyx_PyType_GetSlot(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase, tp_dealloc, destructor)(o); else + #endif + __Pyx_call_next_tp_dealloc(o, __pyx_tp_dealloc_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport); +} + +static int __pyx_tp_traverse_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *p = (struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *)o; + #if !CYTHON_USE_MODULE_STATE + e = 0; + if (likely(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase)) { + traverseproc traverse = __Pyx_PyType_GetSlot(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase, tp_traverse, traverseproc); + if (traverse) { e = traverse(o, v, a); } + } else + #endif + { e = __Pyx_call_next_tp_traverse(o, v, a, __pyx_tp_traverse_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport); } + if (e) return e; + { + e = __Pyx_call_type_traverse(o, 0, v, a); + if (e) return e; + } + if (p->rbuf) { + e = (*v)(((PyObject *)p->rbuf), a); if (e) return e; + } + if (p->wbuf) { + e = (*v)(((PyObject *)p->wbuf), a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport(PyObject *o) { + PyObject* tmp; + struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *p = (struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *)o; + #if !CYTHON_USE_MODULE_STATE + if (likely(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase)) { + inquiry clear = __Pyx_PyType_GetSlot(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase, tp_clear, inquiry); + if (clear) clear(o); + } else + #endif + { __Pyx_call_next_tp_clear(o, __pyx_tp_clear_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport); } + tmp = ((PyObject*)p->rbuf); + p->rbuf = ((struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->wbuf); + p->wbuf = ((struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); + return 0; +} + +static PyMethodDef __pyx_methods_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport[] = { + {"clean", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_3clean, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, + {"is_open", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_5is_open, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, + {"open", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_7open, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, + {"close", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_9close, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, + {"write", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_11write, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, + {"read", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_13read, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, + {"flush", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_15flush, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, + {"getvalue", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_17getvalue, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, + {"__reduce_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_19__reduce_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, + {"__setstate_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_21__setstate_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, + {0, 0, 0, 0} +}; +#if CYTHON_USE_TYPE_SPECS +static PyType_Slot __pyx_type_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport_slots[] = { + {Py_tp_dealloc, (void *)__pyx_tp_dealloc_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport}, + {Py_tp_doc, (void *)PyDoc_STR("binary reader/writer")}, + {Py_tp_traverse, (void *)__pyx_tp_traverse_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport}, + {Py_tp_clear, (void *)__pyx_tp_clear_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport}, + {Py_tp_methods, (void *)__pyx_methods_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport}, + {Py_tp_init, (void *)__pyx_pw_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_1__init__}, + {Py_tp_new, (void *)__pyx_tp_new_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport}, + {0, 0}, +}; +static PyType_Spec __pyx_type_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport_spec = { + "thriftpy2.transport.buffered.cybuffered.TCyBufferedTransport", + sizeof(struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport), + 0, + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, + __pyx_type_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport_slots, +}; +#else + +static PyTypeObject __pyx_type_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport = { + PyVarObject_HEAD_INIT(0, 0) + "thriftpy2.transport.buffered.cybuffered.""TCyBufferedTransport", /*tp_name*/ + sizeof(struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport, /*tp_dealloc*/ + 0, /*tp_vectorcall_offset*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_as_async*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + PyDoc_STR("binary reader/writer"), /*tp_doc*/ + __pyx_tp_traverse_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport, /*tp_traverse*/ + __pyx_tp_clear_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + #if !CYTHON_USE_TYPE_SPECS + 0, /*tp_dictoffset*/ + #endif + __pyx_pw_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_1__init__, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if CYTHON_USE_TP_FINALIZE + 0, /*tp_finalize*/ + #else + NULL, /*tp_finalize*/ + #endif + #if !CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800 + 0, /*tp_vectorcall*/ + #endif + #if __PYX_NEED_TP_PRINT_SLOT == 1 + 0, /*tp_print*/ + #endif + #if PY_VERSION_HEX >= 0x030C0000 + 0, /*tp_watched*/ + #endif + #if PY_VERSION_HEX >= 0x030d00A4 + 0, /*tp_versions_used*/ + #endif + #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX >= 0x03090000 && PY_VERSION_HEX < 0x030a0000 + 0, /*tp_pypy_flags*/ + #endif +}; +#endif + +static PyMethodDef __pyx_methods[] = { + {0, 0, 0, 0} +}; +/* #### Code section: initfunc_declarations ### */ +static CYTHON_SMALL_CODE int __Pyx_InitCachedBuiltins(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_InitCachedConstants(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_InitGlobals(void); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_InitConstants(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_global_init_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_variable_export_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_function_export_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_type_init_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_type_import_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_variable_import_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_function_import_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_CreateCodeObjects(__pyx_mstatetype *__pyx_mstate); /*proto*/ +/* #### Code section: init_module ### */ + +static int __Pyx_modinit_global_init_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_modinit_global_init_code", 0); + /*--- Global init code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_modinit_variable_export_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_modinit_variable_export_code", 0); + /*--- Variable export code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_modinit_function_export_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_modinit_function_export_code", 0); + /*--- Function export code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_modinit_type_init_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__Pyx_modinit_type_init_code", 0); + /*--- Type init code ---*/ + __pyx_t_1 = PyImport_ImportModule("thriftpy2.transport.cybase"); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase = __Pyx_ImportType_3_2_4(__pyx_t_1, "thriftpy2.transport.cybase", "CyTransportBase", + #if defined(PYPY_VERSION_NUM) && PYPY_VERSION_NUM < 0x050B0000 + sizeof(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase), __PYX_GET_STRUCT_ALIGNMENT_3_2_4(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase), + #elif CYTHON_COMPILING_IN_LIMITED_API + sizeof(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase), __PYX_GET_STRUCT_ALIGNMENT_3_2_4(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase), + #else + sizeof(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase), __PYX_GET_STRUCT_ALIGNMENT_3_2_4(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase), + #endif + __Pyx_ImportType_CheckSize_Warn_3_2_4); if (!__pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_vtabptr_9thriftpy2_9transport_6cybase_CyTransportBase = (struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_CyTransportBase*)__Pyx_GetVtable(__pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase); if (unlikely(!__pyx_vtabptr_9thriftpy2_9transport_6cybase_CyTransportBase)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_vtabptr_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport = &__pyx_vtable_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport; + __pyx_vtable_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport.__pyx_base = *__pyx_vtabptr_9thriftpy2_9transport_6cybase_CyTransportBase; + __pyx_vtable_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport.__pyx_base.c_read = (PyObject *(*)(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *, int, char *))__pyx_f_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_c_read; + __pyx_vtable_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport.__pyx_base.c_write = (PyObject *(*)(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *, char *, int))__pyx_f_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_c_write; + __pyx_vtable_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport.__pyx_base.c_flush = (PyObject *(*)(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *))__pyx_f_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_c_flush; + __pyx_vtable_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport.read_trans = (PyObject *(*)(struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *, int, char *))__pyx_f_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_read_trans; + __pyx_vtable_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport.c_dump_wbuf = (PyObject *(*)(struct __pyx_obj_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport *))__pyx_f_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_c_dump_wbuf; + #if CYTHON_USE_TYPE_SPECS + __pyx_t_2 = PyTuple_Pack(1, (PyObject *)__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_mstate->__pyx_ptype_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport = (PyTypeObject *) __Pyx_PyType_FromModuleAndSpec(__pyx_m, &__pyx_type_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport_spec, __pyx_t_2); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_mstate->__pyx_ptype_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport)) __PYX_ERR(0, 14, __pyx_L1_error) + if (__Pyx_fix_up_extension_type_from_spec(&__pyx_type_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport_spec, __pyx_mstate->__pyx_ptype_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport) < (0)) __PYX_ERR(0, 14, __pyx_L1_error) + #else + __pyx_mstate->__pyx_ptype_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport = &__pyx_type_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport; + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + __pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport->tp_base = __pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase; + #endif + #if !CYTHON_USE_TYPE_SPECS + if (__Pyx_PyType_Ready(__pyx_mstate->__pyx_ptype_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport) < (0)) __PYX_ERR(0, 14, __pyx_L1_error) + #endif + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount((PyObject*)__pyx_mstate->__pyx_ptype_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport); + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_mstate->__pyx_ptype_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport->tp_dictoffset && __pyx_mstate->__pyx_ptype_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport->tp_getattro == PyObject_GenericGetAttr)) { + __pyx_mstate->__pyx_ptype_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport->tp_getattro = PyObject_GenericGetAttr; + } + #endif + if (__Pyx_SetVtable(__pyx_mstate->__pyx_ptype_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport, __pyx_vtabptr_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport) < (0)) __PYX_ERR(0, 14, __pyx_L1_error) + if (__Pyx_MergeVtables(__pyx_mstate->__pyx_ptype_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport) < (0)) __PYX_ERR(0, 14, __pyx_L1_error) + if (PyObject_SetAttr(__pyx_m, __pyx_mstate_global->__pyx_n_u_TCyBufferedTransport, (PyObject *) __pyx_mstate->__pyx_ptype_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport) < (0)) __PYX_ERR(0, 14, __pyx_L1_error) + if (__Pyx_setup_reduce((PyObject *) __pyx_mstate->__pyx_ptype_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport) < (0)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_RefNannyFinishContext(); + return 0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_RefNannyFinishContext(); + return -1; +} + +static int __Pyx_modinit_type_import_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__Pyx_modinit_type_import_code", 0); + /*--- Type import code ---*/ + __pyx_t_1 = PyImport_ImportModule("thriftpy2.transport.cybase"); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 7, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer = __Pyx_ImportType_3_2_4(__pyx_t_1, "thriftpy2.transport.cybase", "TCyBuffer", + #if defined(PYPY_VERSION_NUM) && PYPY_VERSION_NUM < 0x050B0000 + sizeof(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer), __PYX_GET_STRUCT_ALIGNMENT_3_2_4(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer), + #elif CYTHON_COMPILING_IN_LIMITED_API + sizeof(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer), __PYX_GET_STRUCT_ALIGNMENT_3_2_4(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer), + #else + sizeof(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer), __PYX_GET_STRUCT_ALIGNMENT_3_2_4(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer), + #endif + __Pyx_ImportType_CheckSize_Warn_3_2_4); if (!__pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer) __PYX_ERR(2, 7, __pyx_L1_error) + __pyx_vtabptr_9thriftpy2_9transport_6cybase_TCyBuffer = (struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_TCyBuffer*)__Pyx_GetVtable(__pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer); if (unlikely(!__pyx_vtabptr_9thriftpy2_9transport_6cybase_TCyBuffer)) __PYX_ERR(2, 7, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_RefNannyFinishContext(); + return 0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_RefNannyFinishContext(); + return -1; +} + +static int __Pyx_modinit_variable_import_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_modinit_variable_import_code", 0); + /*--- Variable import code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_modinit_function_import_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_modinit_function_import_code", 0); + /*--- Function import code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +#if CYTHON_PEP489_MULTI_PHASE_INIT +static PyObject* __pyx_pymod_create(PyObject *spec, PyModuleDef *def); /*proto*/ +static int __pyx_pymod_exec_cybuffered(PyObject* module); /*proto*/ +static PyModuleDef_Slot __pyx_moduledef_slots[] = { + {Py_mod_create, (void*)__pyx_pymod_create}, + {Py_mod_exec, (void*)__pyx_pymod_exec_cybuffered}, + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + {Py_mod_gil, __Pyx_FREETHREADING_COMPATIBLE}, + #endif + #if PY_VERSION_HEX >= 0x030C0000 && CYTHON_USE_MODULE_STATE + {Py_mod_multiple_interpreters, Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED}, + #endif + {0, NULL} +}; +#endif + +#ifdef __cplusplus +namespace { + struct PyModuleDef __pyx_moduledef = + #else + static struct PyModuleDef __pyx_moduledef = + #endif + { + PyModuleDef_HEAD_INIT, + "cybuffered", + 0, /* m_doc */ + #if CYTHON_USE_MODULE_STATE + sizeof(__pyx_mstatetype), /* m_size */ + #else + (CYTHON_PEP489_MULTI_PHASE_INIT) ? 0 : -1, /* m_size */ + #endif + __pyx_methods /* m_methods */, + #if CYTHON_PEP489_MULTI_PHASE_INIT + __pyx_moduledef_slots, /* m_slots */ + #else + NULL, /* m_reload */ + #endif + #if CYTHON_USE_MODULE_STATE + __pyx_m_traverse, /* m_traverse */ + __pyx_m_clear, /* m_clear */ + NULL /* m_free */ + #else + NULL, /* m_traverse */ + NULL, /* m_clear */ + NULL /* m_free */ + #endif + }; + #ifdef __cplusplus +} /* anonymous namespace */ +#endif + +/* PyModInitFuncType */ +#ifndef CYTHON_NO_PYINIT_EXPORT + #define __Pyx_PyMODINIT_FUNC PyMODINIT_FUNC +#else + #ifdef __cplusplus + #define __Pyx_PyMODINIT_FUNC extern "C" PyObject * + #else + #define __Pyx_PyMODINIT_FUNC PyObject * + #endif +#endif + +__Pyx_PyMODINIT_FUNC PyInit_cybuffered(void) CYTHON_SMALL_CODE; /*proto*/ +__Pyx_PyMODINIT_FUNC PyInit_cybuffered(void) +#if CYTHON_PEP489_MULTI_PHASE_INIT +{ + return PyModuleDef_Init(&__pyx_moduledef); +} +/* ModuleCreationPEP489 */ +#if CYTHON_COMPILING_IN_LIMITED_API && (__PYX_LIMITED_VERSION_HEX < 0x03090000\ + || ((defined(_WIN32) || defined(WIN32) || defined(MS_WINDOWS)) && __PYX_LIMITED_VERSION_HEX < 0x030A0000)) +static PY_INT64_T __Pyx_GetCurrentInterpreterId(void) { + { + PyObject *module = PyImport_ImportModule("_interpreters"); // 3.13+ I think + if (!module) { + PyErr_Clear(); // just try the 3.8-3.12 version + module = PyImport_ImportModule("_xxsubinterpreters"); + if (!module) goto bad; + } + PyObject *current = PyObject_CallMethod(module, "get_current", NULL); + Py_DECREF(module); + if (!current) goto bad; + if (PyTuple_Check(current)) { + PyObject *new_current = PySequence_GetItem(current, 0); + Py_DECREF(current); + current = new_current; + if (!new_current) goto bad; + } + long long as_c_int = PyLong_AsLongLong(current); + Py_DECREF(current); + return as_c_int; + } + bad: + PySys_WriteStderr("__Pyx_GetCurrentInterpreterId failed. Try setting the C define CYTHON_PEP489_MULTI_PHASE_INIT=0\n"); + return -1; +} +#endif +#if !CYTHON_USE_MODULE_STATE +static CYTHON_SMALL_CODE int __Pyx_check_single_interpreter(void) { + static PY_INT64_T main_interpreter_id = -1; +#if CYTHON_COMPILING_IN_GRAAL && defined(GRAALPY_VERSION_NUM) && GRAALPY_VERSION_NUM > 0x19000000 + PY_INT64_T current_id = GraalPyInterpreterState_GetIDFromThreadState(PyThreadState_Get()); +#elif CYTHON_COMPILING_IN_GRAAL + PY_INT64_T current_id = PyInterpreterState_GetIDFromThreadState(PyThreadState_Get()); +#elif CYTHON_COMPILING_IN_LIMITED_API && (__PYX_LIMITED_VERSION_HEX < 0x03090000\ + || ((defined(_WIN32) || defined(WIN32) || defined(MS_WINDOWS)) && __PYX_LIMITED_VERSION_HEX < 0x030A0000)) + PY_INT64_T current_id = __Pyx_GetCurrentInterpreterId(); +#elif CYTHON_COMPILING_IN_LIMITED_API + PY_INT64_T current_id = PyInterpreterState_GetID(PyInterpreterState_Get()); +#else + PY_INT64_T current_id = PyInterpreterState_GetID(PyThreadState_Get()->interp); +#endif + if (unlikely(current_id == -1)) { + return -1; + } + if (main_interpreter_id == -1) { + main_interpreter_id = current_id; + return 0; + } else if (unlikely(main_interpreter_id != current_id)) { + PyErr_SetString( + PyExc_ImportError, + "Interpreter change detected - this module can only be loaded into one interpreter per process."); + return -1; + } + return 0; +} +#endif +static CYTHON_SMALL_CODE int __Pyx_copy_spec_to_module(PyObject *spec, PyObject *moddict, const char* from_name, const char* to_name, int allow_none) +{ + PyObject *value = PyObject_GetAttrString(spec, from_name); + int result = 0; + if (likely(value)) { + if (allow_none || value != Py_None) { + result = PyDict_SetItemString(moddict, to_name, value); + } + Py_DECREF(value); + } else if (PyErr_ExceptionMatches(PyExc_AttributeError)) { + PyErr_Clear(); + } else { + result = -1; + } + return result; +} +static CYTHON_SMALL_CODE PyObject* __pyx_pymod_create(PyObject *spec, PyModuleDef *def) { + PyObject *module = NULL, *moddict, *modname; + CYTHON_UNUSED_VAR(def); + #if !CYTHON_USE_MODULE_STATE + if (__Pyx_check_single_interpreter()) + return NULL; + #endif + if (__pyx_m) + return __Pyx_NewRef(__pyx_m); + modname = PyObject_GetAttrString(spec, "name"); + if (unlikely(!modname)) goto bad; + module = PyModule_NewObject(modname); + Py_DECREF(modname); + if (unlikely(!module)) goto bad; + moddict = PyModule_GetDict(module); + if (unlikely(!moddict)) goto bad; + if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "loader", "__loader__", 1) < 0)) goto bad; + if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "origin", "__file__", 1) < 0)) goto bad; + if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "parent", "__package__", 1) < 0)) goto bad; + if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "submodule_search_locations", "__path__", 0) < 0)) goto bad; + return module; +bad: + Py_XDECREF(module); + return NULL; +} + + +static CYTHON_SMALL_CODE int __pyx_pymod_exec_cybuffered(PyObject *__pyx_pyinit_module) +#endif +{ + int stringtab_initialized = 0; + #if CYTHON_USE_MODULE_STATE + int pystate_addmodule_run = 0; + #endif + __pyx_mstatetype *__pyx_mstate = NULL; + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + Py_ssize_t __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannyDeclarations + #if CYTHON_PEP489_MULTI_PHASE_INIT + if (__pyx_m) { + if (__pyx_m == __pyx_pyinit_module) return 0; + PyErr_SetString(PyExc_RuntimeError, "Module 'cybuffered' has already been imported. Re-initialisation is not supported."); + return -1; + } + #else + if (__pyx_m) return __Pyx_NewRef(__pyx_m); + #endif + /*--- Module creation code ---*/ + #if CYTHON_PEP489_MULTI_PHASE_INIT + __pyx_t_1 = __pyx_pyinit_module; + Py_INCREF(__pyx_t_1); + #else + __pyx_t_1 = PyModule_Create(&__pyx_moduledef); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1, __pyx_L1_error) + #endif + #if CYTHON_USE_MODULE_STATE + { + int add_module_result = __Pyx_State_AddModule(__pyx_t_1, &__pyx_moduledef); + __pyx_t_1 = 0; /* transfer ownership from __pyx_t_1 to "cybuffered" pseudovariable */ + if (unlikely((add_module_result < 0))) __PYX_ERR(0, 1, __pyx_L1_error) + pystate_addmodule_run = 1; + } + #else + __pyx_m = __pyx_t_1; + #endif + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + PyUnstable_Module_SetGIL(__pyx_m, Py_MOD_GIL_NOT_USED); + #endif + __pyx_mstate = __pyx_mstate_global; + CYTHON_UNUSED_VAR(__pyx_t_1); + __pyx_mstate->__pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_mstate->__pyx_d)) __PYX_ERR(0, 1, __pyx_L1_error) + Py_INCREF(__pyx_mstate->__pyx_d); + __pyx_mstate->__pyx_b = __Pyx_PyImport_AddModuleRef(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_mstate->__pyx_b)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_mstate->__pyx_cython_runtime = __Pyx_PyImport_AddModuleRef("cython_runtime"); if (unlikely(!__pyx_mstate->__pyx_cython_runtime)) __PYX_ERR(0, 1, __pyx_L1_error) + if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_mstate->__pyx_b) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + /* ImportRefnannyAPI */ + #if CYTHON_REFNANNY + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); + if (!__Pyx_RefNanny) { + PyErr_Clear(); + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); + if (!__Pyx_RefNanny) + Py_FatalError("failed to import 'refnanny' module"); + } + #endif + +__Pyx_RefNannySetupContext("PyInit_cybuffered", 0); + __Pyx_init_runtime_version(); + if (__Pyx_check_binary_version(__PYX_LIMITED_VERSION_HEX, __Pyx_get_runtime_version(), CYTHON_COMPILING_IN_LIMITED_API) < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_mstate->__pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_mstate->__pyx_empty_tuple)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_mstate->__pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_mstate->__pyx_empty_bytes)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_mstate->__pyx_empty_unicode = PyUnicode_FromStringAndSize("", 0); if (unlikely(!__pyx_mstate->__pyx_empty_unicode)) __PYX_ERR(0, 1, __pyx_L1_error) + /*--- Library function declarations ---*/ + /*--- Initialize various global constants etc. ---*/ + if (__Pyx_InitConstants(__pyx_mstate) < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + stringtab_initialized = 1; + if (__Pyx_InitGlobals() < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + if (__pyx_module_is_main_thriftpy2__transport__buffered__cybuffered) { + if (PyObject_SetAttr(__pyx_m, __pyx_mstate_global->__pyx_n_u_name, __pyx_mstate_global->__pyx_n_u_main) < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + } + { + PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) __PYX_ERR(0, 1, __pyx_L1_error) + if (!PyDict_GetItemString(modules, "thriftpy2.transport.buffered.cybuffered")) { + if (unlikely((PyDict_SetItemString(modules, "thriftpy2.transport.buffered.cybuffered", __pyx_m) < 0))) __PYX_ERR(0, 1, __pyx_L1_error) + } + } + /*--- Builtin init code ---*/ + if (__Pyx_InitCachedBuiltins(__pyx_mstate) < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + /*--- Constants init code ---*/ + if (__Pyx_InitCachedConstants(__pyx_mstate) < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + if (__Pyx_CreateCodeObjects(__pyx_mstate) < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + /*--- Global type/function init code ---*/ + (void)__Pyx_modinit_global_init_code(__pyx_mstate); + (void)__Pyx_modinit_variable_export_code(__pyx_mstate); + (void)__Pyx_modinit_function_export_code(__pyx_mstate); + if (unlikely((__Pyx_modinit_type_init_code(__pyx_mstate) < 0))) __PYX_ERR(0, 1, __pyx_L1_error) + if (unlikely((__Pyx_modinit_type_import_code(__pyx_mstate) < 0))) __PYX_ERR(0, 1, __pyx_L1_error) + (void)__Pyx_modinit_variable_import_code(__pyx_mstate); + (void)__Pyx_modinit_function_import_code(__pyx_mstate); + /*--- Execution code ---*/ + + /* "thriftpy2/transport/buffered/cybuffered.pyx":9 + * ) + * + * from .. import TTransportException # <<<<<<<<<<<<<< + * + * DEF MIN_BUFFER_SIZE = 1024 +*/ + { + PyObject* const __pyx_imported_names[] = {__pyx_mstate_global->__pyx_n_u_TTransportException}; + __pyx_t_1 = __Pyx_Import(__pyx_mstate_global->__pyx_n_u__2, __pyx_imported_names, 1, __pyx_mstate_global->__pyx_kp_u_thriftpy2_transport, 2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 9, __pyx_L1_error) + } + __pyx_t_2 = __pyx_t_1; + __Pyx_GOTREF(__pyx_t_2); + { + PyObject* const __pyx_imported_names[] = {__pyx_mstate_global->__pyx_n_u_TTransportException}; + __pyx_t_3 = 0; { + __pyx_t_4 = __Pyx_ImportFrom(__pyx_t_2, __pyx_imported_names[__pyx_t_3]); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 9, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_imported_names[__pyx_t_3], __pyx_t_4) < (0)) __PYX_ERR(0, 9, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + } + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/transport/buffered/cybuffered.pyx":20 + * TCyBuffer rbuf, wbuf + * + * def __init__(self, trans, int buf_size=DEFAULT_BUFFER): # <<<<<<<<<<<<<< + * if buf_size < MIN_BUFFER_SIZE: + * raise Exception("buffer too small") +*/ + __pyx_mstate_global->__pyx_k_ = __pyx_e_9thriftpy2_9transport_6cybase_DEFAULT_BUFFER; + + /* "thriftpy2/transport/buffered/cybuffered.pyx":28 + * self.wbuf = TCyBuffer(buf_size) + * + * def clean(self): # <<<<<<<<<<<<<< + * self.rbuf.clean() + * self.wbuf.clean() +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_3clean, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_TCyBufferedTransport_clean, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_transport_buffered_cyb, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[0])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 28, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_2); + #endif + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport, __pyx_mstate_global->__pyx_n_u_clean, __pyx_t_2) < (0)) __PYX_ERR(0, 28, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/transport/buffered/cybuffered.pyx":32 + * self.wbuf.clean() + * + * def is_open(self): # <<<<<<<<<<<<<< + * return self.trans.is_open() + * +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_5is_open, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_TCyBufferedTransport_is_open, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_transport_buffered_cyb, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[1])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 32, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_2); + #endif + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport, __pyx_mstate_global->__pyx_n_u_is_open, __pyx_t_2) < (0)) __PYX_ERR(0, 32, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/transport/buffered/cybuffered.pyx":35 + * return self.trans.is_open() + * + * def open(self): # <<<<<<<<<<<<<< + * return self.trans.open() + * +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_7open, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_TCyBufferedTransport_open, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_transport_buffered_cyb, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[2])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 35, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_2); + #endif + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport, __pyx_mstate_global->__pyx_n_u_open, __pyx_t_2) < (0)) __PYX_ERR(0, 35, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/transport/buffered/cybuffered.pyx":38 + * return self.trans.open() + * + * def close(self): # <<<<<<<<<<<<<< + * return self.trans.close() + * +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_9close, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_TCyBufferedTransport_close, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_transport_buffered_cyb, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[3])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 38, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_2); + #endif + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport, __pyx_mstate_global->__pyx_n_u_close, __pyx_t_2) < (0)) __PYX_ERR(0, 38, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/transport/buffered/cybuffered.pyx":41 + * return self.trans.close() + * + * def write(self, bytes data): # <<<<<<<<<<<<<< + * cdef int sz = len(data) + * return self.c_write(data, sz) +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_11write, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_TCyBufferedTransport_write, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_transport_buffered_cyb, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[4])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 41, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_2); + #endif + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport, __pyx_mstate_global->__pyx_n_u_write, __pyx_t_2) < (0)) __PYX_ERR(0, 41, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/transport/buffered/cybuffered.pyx":45 + * return self.c_write(data, sz) + * + * def read(self, int sz): # <<<<<<<<<<<<<< + * return self.get_string(sz) + * +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_13read, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_TCyBufferedTransport_read, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_transport_buffered_cyb, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[5])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 45, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_2); + #endif + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport, __pyx_mstate_global->__pyx_n_u_read, __pyx_t_2) < (0)) __PYX_ERR(0, 45, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/transport/buffered/cybuffered.pyx":48 + * return self.get_string(sz) + * + * def flush(self): # <<<<<<<<<<<<<< + * return self.c_flush() + * +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_15flush, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_TCyBufferedTransport_flush, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_transport_buffered_cyb, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[6])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 48, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_2); + #endif + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport, __pyx_mstate_global->__pyx_n_u_flush, __pyx_t_2) < (0)) __PYX_ERR(0, 48, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/transport/buffered/cybuffered.pyx":89 + * self.wbuf.clean() + * + * def getvalue(self): # <<<<<<<<<<<<<< + * return self.trans.getvalue() + * +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_17getvalue, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_TCyBufferedTransport_getvalue, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_transport_buffered_cyb, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[7])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 89, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_2); + #endif + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport, __pyx_mstate_global->__pyx_n_u_getvalue, __pyx_t_2) < (0)) __PYX_ERR(0, 89, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * cdef tuple state + * cdef object _dict +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_19__reduce_cython__, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_TCyBufferedTransport___reduce_cy, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_transport_buffered_cyb, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[8])); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 1, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_2); + #endif + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport, __pyx_mstate_global->__pyx_n_u_reduce_cython, __pyx_t_2) < (0)) __PYX_ERR(1, 1, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "(tree fragment)":16 + * else: + * return __pyx_unpickle_TCyBufferedTransport, (type(self), 0x9ee77cd, state) + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * __pyx_unpickle_TCyBufferedTransport__set_state(self, __pyx_state) +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_9transport_8buffered_10cybuffered_20TCyBufferedTransport_21__setstate_cython__, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_TCyBufferedTransport___setstate, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_transport_buffered_cyb, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[9])); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 16, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_2); + #endif + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_8buffered_10cybuffered_TCyBufferedTransport, __pyx_mstate_global->__pyx_n_u_setstate_cython, __pyx_t_2) < (0)) __PYX_ERR(1, 16, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/transport/buffered/cybuffered.pyx":93 + * + * + * class TCyBufferedTransportFactory(object): # <<<<<<<<<<<<<< + * def get_transport(self, trans): + * return TCyBufferedTransport(trans) +*/ + __pyx_t_2 = __Pyx_PEP560_update_bases(__pyx_mstate_global->__pyx_tuple[1]); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 93, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = __Pyx_CalculateMetaclass(NULL, __pyx_t_2); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 93, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = __Pyx_Py3MetaclassPrepare(__pyx_t_4, __pyx_t_2, __pyx_mstate_global->__pyx_n_u_TCyBufferedTransportFactory, __pyx_mstate_global->__pyx_n_u_TCyBufferedTransportFactory, (PyObject *) NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_transport_buffered_cyb, (PyObject *) NULL); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 93, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + if (__pyx_t_2 != __pyx_mstate_global->__pyx_tuple[1]) { + if (unlikely((PyDict_SetItemString(__pyx_t_5, "__orig_bases__", __pyx_mstate_global->__pyx_tuple[1]) < 0))) __PYX_ERR(0, 93, __pyx_L1_error) + } + + /* "thriftpy2/transport/buffered/cybuffered.pyx":94 + * + * class TCyBufferedTransportFactory(object): + * def get_transport(self, trans): # <<<<<<<<<<<<<< + * return TCyBufferedTransport(trans) +*/ + __pyx_t_6 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_9transport_8buffered_10cybuffered_27TCyBufferedTransportFactory_1get_transport, 0, __pyx_mstate_global->__pyx_n_u_TCyBufferedTransportFactory_get, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_transport_buffered_cyb, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[10])); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 94, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_6); + #endif + if (__Pyx_SetNameInClass(__pyx_t_5, __pyx_mstate_global->__pyx_n_u_get_transport, __pyx_t_6) < (0)) __PYX_ERR(0, 94, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + + /* "thriftpy2/transport/buffered/cybuffered.pyx":93 + * + * + * class TCyBufferedTransportFactory(object): # <<<<<<<<<<<<<< + * def get_transport(self, trans): + * return TCyBufferedTransport(trans) +*/ + __pyx_t_6 = __Pyx_Py3ClassCreate(__pyx_t_4, __pyx_mstate_global->__pyx_n_u_TCyBufferedTransportFactory, __pyx_t_2, __pyx_t_5, NULL, 0, 0); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 93, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_6); + #endif + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_TCyBufferedTransportFactory, __pyx_t_6) < (0)) __PYX_ERR(0, 93, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "(tree fragment)":4 + * int __Pyx_CheckUnpickleChecksum(long, long, long, long, const char*) except -1 + * int __Pyx_UpdateUnpickledDict(object, object, Py_ssize_t) except -1 + * def __pyx_unpickle_TCyBufferedTransport(__pyx_type, long __pyx_checksum, tuple __pyx_state): # <<<<<<<<<<<<<< + * cdef object __pyx_result + * __Pyx_CheckUnpickleChecksum(__pyx_checksum, 0x9ee77cd, 0x79d98b4, 0x551bc31, b'rbuf, trans, wbuf') +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_9transport_8buffered_10cybuffered_1__pyx_unpickle_TCyBufferedTransport, 0, __pyx_mstate_global->__pyx_n_u_pyx_unpickle_TCyBufferedTransp, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_transport_buffered_cyb, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[11])); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 4, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_2); + #endif + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_pyx_unpickle_TCyBufferedTransp, __pyx_t_2) < (0)) __PYX_ERR(1, 4, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/transport/buffered/cybuffered.pyx":1 + * # cython: freethreading_compatible = True # <<<<<<<<<<<<<< + * + * from thriftpy2.transport.cybase cimport ( +*/ + __pyx_t_2 = __Pyx_PyDict_NewPresized(0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_test, __pyx_t_2) < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /*--- Wrapped vars code ---*/ + + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + if (__pyx_m) { + if (__pyx_mstate->__pyx_d && stringtab_initialized) { + __Pyx_AddTraceback("init thriftpy2.transport.buffered.cybuffered", __pyx_clineno, __pyx_lineno, __pyx_filename); + } + #if !CYTHON_USE_MODULE_STATE + Py_CLEAR(__pyx_m); + #else + Py_DECREF(__pyx_m); + if (pystate_addmodule_run) { + PyObject *tp, *value, *tb; + PyErr_Fetch(&tp, &value, &tb); + PyState_RemoveModule(&__pyx_moduledef); + PyErr_Restore(tp, value, tb); + } + #endif + } else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_ImportError, "init thriftpy2.transport.buffered.cybuffered"); + } + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + #if CYTHON_PEP489_MULTI_PHASE_INIT + return (__pyx_m != NULL) ? 0 : -1; + #else + return __pyx_m; + #endif +} +/* #### Code section: pystring_table ### */ +/* #### Code section: cached_builtins ### */ + +static int __Pyx_InitCachedBuiltins(__pyx_mstatetype *__pyx_mstate) { + CYTHON_UNUSED_VAR(__pyx_mstate); + __pyx_builtin_object = __Pyx_GetBuiltinName(__pyx_mstate->__pyx_n_u_object); if (!__pyx_builtin_object) __PYX_ERR(0, 93, __pyx_L1_error) + + /* Cached unbound methods */ + __pyx_mstate->__pyx_umethod_PyDict_Type_items.type = (PyObject*)&PyDict_Type; + __pyx_mstate->__pyx_umethod_PyDict_Type_items.method_name = &__pyx_mstate->__pyx_n_u_items; + __pyx_mstate->__pyx_umethod_PyDict_Type_pop.type = (PyObject*)&PyDict_Type; + __pyx_mstate->__pyx_umethod_PyDict_Type_pop.method_name = &__pyx_mstate->__pyx_n_u_pop; + __pyx_mstate->__pyx_umethod_PyDict_Type_values.type = (PyObject*)&PyDict_Type; + __pyx_mstate->__pyx_umethod_PyDict_Type_values.method_name = &__pyx_mstate->__pyx_n_u_values; + return 0; + __pyx_L1_error:; + return -1; +} +/* #### Code section: cached_constants ### */ + +static int __Pyx_InitCachedConstants(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); + + /* "thriftpy2/transport/buffered/cybuffered.pyx":93 + * + * + * class TCyBufferedTransportFactory(object): # <<<<<<<<<<<<<< + * def get_transport(self, trans): + * return TCyBufferedTransport(trans) +*/ + __pyx_mstate_global->__pyx_tuple[0] = PyTuple_Pack(1, __pyx_builtin_object); if (unlikely(!__pyx_mstate_global->__pyx_tuple[0])) __PYX_ERR(0, 93, __pyx_L1_error) + __Pyx_GOTREF(__pyx_mstate_global->__pyx_tuple[0]); + __Pyx_GIVEREF(__pyx_mstate_global->__pyx_tuple[0]); + __pyx_mstate_global->__pyx_tuple[1] = PyTuple_Pack(1, __pyx_builtin_object); if (unlikely(!__pyx_mstate_global->__pyx_tuple[1])) __PYX_ERR(0, 93, __pyx_L1_error) + __Pyx_GOTREF(__pyx_mstate_global->__pyx_tuple[1]); + __Pyx_GIVEREF(__pyx_mstate_global->__pyx_tuple[1]); + #if CYTHON_IMMORTAL_CONSTANTS + { + PyObject **table = __pyx_mstate->__pyx_tuple; + for (Py_ssize_t i=0; i<2; ++i) { + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + #if PY_VERSION_HEX < 0x030E0000 + if (_Py_IsOwnedByCurrentThread(table[i]) && Py_REFCNT(table[i]) == 1) + #else + if (PyUnstable_Object_IsUniquelyReferenced(table[i])) + #endif + { + Py_SET_REFCNT(table[i], _Py_IMMORTAL_REFCNT_LOCAL); + } + #else + Py_SET_REFCNT(table[i], _Py_IMMORTAL_INITIAL_REFCNT); + #endif + } + } + #endif + __Pyx_RefNannyFinishContext(); + return 0; + __pyx_L1_error:; + __Pyx_RefNannyFinishContext(); + return -1; +} +/* #### Code section: init_constants ### */ + +static int __Pyx_InitConstants(__pyx_mstatetype *__pyx_mstate) { + CYTHON_UNUSED_VAR(__pyx_mstate); + { + const struct { const unsigned int length: 8; } index[] = {{34},{179},{21},{1},{1},{8},{16},{7},{6},{2},{21},{9},{14},{20},{43},{11},{20},{20},{27},{41},{38},{40},{26},{26},{26},{29},{28},{25},{25},{26},{19},{0},{18},{8},{5},{18},{5},{4},{8},{5},{7},{5},{8},{13},{12},{8},{13},{7},{5},{8},{13},{10},{15},{8},{7},{6},{4},{3},{11},{14},{12},{11},{10},{35},{14},{12},{4},{10},{17},{13},{4},{12},{10},{12},{19},{5},{2},{8},{39},{5},{6},{12},{6},{5},{11},{12},{20},{24},{13},{13},{13},{13},{11},{13},{128},{58}}; + #if (CYTHON_COMPRESS_STRINGS) == 2 /* compression: bz2 (1000 bytes) */ +const char* const cstring = "BZh91AY&SY\261\324\301p\000\000|\377\377\346\315\277\350\356\207\367\315\277\345\374\216\277\377\377\364@@@@@@@@@@@@@\000@\000P\003Y\266\365vf\330\0070\322\2424\311\2462OSM\251\262\231\224\310m@\304\300C \006OS\021\344C\032\217D\306j\006\246\224\365Od\2310\310\247\244f\240\017P\000\006A\240\000\003\010\000\000\032\r\004\310\251\351\252~\243H\314\247\246\200\0204\006\000\000\000@\r\001\246\237\250\017H8b4\323A\240\r\000\000\000\r\006A\246\201\240\003F\2001\r\000\304\211\210\214\247\221\220\324i\0322\006@\310\r\000\000\000\000\001\240\321\241\266A\016\236\236r\250\025\303\352i<\305\334\340\204L\0035y\202O\334J\010v\3259\205\203\300-A\020#\250\270\033\351\032y\275\\\331\213\367\345\247\333H_\324\272\0362\352\241^\035\216&z\025\002Q\356\247b\027Q\334\224\326\350\263C\"\230M\225\300\266\030G\021\343#\034\206\300 s\273m\305\224J)>67C\360\037\252\212\272\361\224zOOAT\217\232@E\004_`\213q\235g\316\247\177\311)\002/F\010\t\341e\354W_\253\362\375\253M\310\212\3100$\377\205\314V\031X\024\232\014\037\033\372b\367N\010[0-\264|w\356\204\027\317\351@#-?\r\373\315H\021\227\020`B\344= \031G\3553ndH\321\315\354\316f\006v/\250\263\006\205\027\025\3538\024\026Z!\003\006\323#\003 \034\3105\016q\236!\314\203\006\202\346~_p\234\374\225\032\003nm\343A\272#[\247H$\\?\2461c\346\r\021\310=0\301\314\241\000\373\243(\022,5Jn\322BW\013\200O\245ZV\220\365\003\312\036\234\311TR 0\210;\2700\036\306\220r\010`\210\354%\245\263{ \251i\\\207\206\324#l\354c\035\372\260\303\262\217\002\241\202\251\231\336FR\002A\236lV\250P\205\023\004R2\024;w\0339\363>\201EA\363\260\2624\352\t-\024\010\026\316%}1\237\023@i\013X2(8B\236{\262\215\233-\301\240\352\310!\304\020\355*\032\262\333T\211A\341+_X\250\270\214\003\254\306\220Fa\0058Tw[\234\022\332\247\240\"\024\274\372\033P|\224\374\211p\333de2\372\274X\031D#W\010\r\202\241^\206\277j\363\271o\223\243\244\225\002\2050f\202\023\305\362\325\226\302\236\344'F\207\343\242w\274\022\026lg\014\255\225\331\351\017\323\"\002W\312\364\350d\023\020C\205\242\314\352\354\2225""\342\320\266\017\001E(\220E1\300j\271\344. \325\332f\333R\003\014\373!\"RH\240\222N\253F\272il\220\004\007\n\203\356t\343)_\316P\321\337f\260kR\304\221SO\225\202Rx\r\245\014j\251\242+p\026(\004\354\027\220E\240`\244A\004\241\270\203\3701h\255Vk\010\003a\rB\261%\\\306\032\354\342q\262\306&!\223J\267\027T\006\241\017\374g\303p\226z'\001\033\314\362\034y\2345\253\271J\302f\202\347\023\300\307\275!@\026\0361?\260J\016~%f\006\236\231\303\r0\354\260\341L\373e\2309\003\256\334\274\031\357;\240\236\273\257\024_a\203\300\214P0\262\274;\271\227\327\"\366?\262\315\351&\031+\374^\304[\303\247\003\210\201\245\341R;\021c$\240\270\002\013\371\2606\240\263\215\247S;+q2C\377\204g>\027\216\337w\017\323\255\254\211\206\330\230$\211k\036\024L\323\335\006c\224\263\306\226\274N\366\2555\260m/1\034\332@\255\230JQD-2w\213\271\"\234(HX\352`\270\000"; + PyObject *data = __Pyx_DecompressString(cstring, 1000, 2); + if (unlikely(!data)) __PYX_ERR(0, 1, __pyx_L1_error) + const char* const bytes = __Pyx_PyBytes_AsString(data); + #if !CYTHON_ASSUME_SAFE_MACROS + if (likely(bytes)); else { Py_DECREF(data); __PYX_ERR(0, 1, __pyx_L1_error) } + #endif + #elif (CYTHON_COMPRESS_STRINGS) != 0 /* compression: zlib (866 bytes) */ +const char* const cstring = "x\332\205S\275o\0337\024\257\001\0051\220\240\201\233\326N\321!4\332\302K{\256\203\324\016\220\242\205\023Kn\200\302u\022\001\031\222\200\240x\357$\306'\362D\362l]\220\301\243\306\033o\324\350Q\243F\217\0365j\364\237\320?\241\217\224tN\320s*@\274\367\375\371{u\031\022\025\221H\304@4\260P\3106\211\264\352\022\253\2314\211\322\366@Y \266\303,y\232\331\216\222D\030\022B,Z\240\231\2058#\306j\301-hg$\311a\375\360\347\207\217\036\022\206\2015\274\003n\r1i\213\307\314\0300.W+\025\261\025\222\330,\001\023\220g\021\311TJ$@H\254\"\t\332}\354`; \211\001\353\010\262\301\244T\226Y\241$Ew,v\203\204Bc\022q\014\316\273\301b\003\301+-\254g[i\024aa\240\265\322\301\037,\014)\272\303\\j\225\"\246\313\3428\024\206\265b\000\351\3366oku\342g\261p\217\230\210\205\231\251\303\337\\\273\262mT\2529\374n;ZD6\311\036\004\345\274\202R\266Y\3126g\221 \334\344\331\202\014\222\254_?\330\243\1777h\343\331_uJ\017\263>\376\367p\226\364\000\372\366\005D\315\247\331\223\271us\021\252J\326`\334*\235}F\025\264\301R\373\271\030\001\245\310\246\034(\367k\246\364\032+\334\205\301\025\374\217\035\217\201\311k4\312@\245&\212S\323\251\324`\365\307,N\253\335\204\241*\201\352d\327*\334~+\025'\016;\315\222\257\3679$\016o\314d\222\013\025p\245U\212\360\005\203\213\244F\274\007\337*\217QD\205tC\346\320b\374\310\367\0312\313(\r\335N\027\237PqJ}\253\370I%2\237\354\306\263\263\001\323E\333\024[,\363\316\333\305*\273\206\322.\303\234\370\353\202e\376d<\243\3024\006OiEA\"b\301+$\353z\261\204\023JU\313]\247\213\225\250\204\322DC\302\264W#2)\357\000?2iw\306i0ilg\364\2748G\272\023\236Q\251L\004?\302\244UC\235\231\034[w@.~/e\361\254\024\267\206\022x\364?\020,\005\320w\300\213#\017\277y\033H\205\0201_W\tJZ\001P\317\231\367\224\342\213\266U7[\036\345\325}ze\232\340\006!5PF\365\0131\036%\247K\323\332\203\321\372h{\274r\272;]\2763\271\363\375pk\270\353\350\333\203z\276\232\367J\302\311Vs^\254\024\353h8\260\371\243b\253h\014\327\275\037\262\333\305\275\341\312\025\363\355\307\232o\nv\305\254\026\275\005\203!\026\344\343\202\241|""\351\237\345/n|9h\346kE\255\370s\270w\206\365\335\036\354\347[y\243\370i\310\246\265\233\247\307\203Wy\275\370\272x>]\376*\307R\326\362\336%>\266\330\036\256\235\3358{9\252\215\366\307;\347?\236\233\213\037.\242I\363\365\344\365\033\347\327\363\355\375:j\216W\306\033\347\337]\354O^6/?\025\355\236.]\326\356\027\275\t\371etk\374\370\374h\362\374\305\264vwrwc\330?\353\215\226\\\230\017\371\216\033\300\366\210Mv\016.\344\344\315\333i\355\326`\353_\007r\2247"; + PyObject *data = __Pyx_DecompressString(cstring, 866, 1); + if (unlikely(!data)) __PYX_ERR(0, 1, __pyx_L1_error) + const char* const bytes = __Pyx_PyBytes_AsString(data); + #if !CYTHON_ASSUME_SAFE_MACROS + if (likely(bytes)); else { Py_DECREF(data); __PYX_ERR(0, 1, __pyx_L1_error) } + #endif + #else /* compression: none (1669 bytes) */ +const char* const bytes = "End of file reading from transportNote that Cython is deliberately stricter than PEP-484 and rejects subclasses of builtin types. If you need to pass subclasses then set the 'annotation_typing' directive to False.Write to buffer error.?add_notebuffer too smalldisableenablegcgrow read buffer failisenabledthriftpy2.transport.thriftpy2/transport/buffered/cybuffered.pyxEND_OF_FILE__Pyx_PyDict_NextRefTCyBufferedTransportTCyBufferedTransportFactoryTCyBufferedTransportFactory.get_transportTCyBufferedTransport.__reduce_cython__TCyBufferedTransport.__setstate_cython__TCyBufferedTransport.cleanTCyBufferedTransport.closeTCyBufferedTransport.flushTCyBufferedTransport.getvalueTCyBufferedTransport.is_openTCyBufferedTransport.openTCyBufferedTransport.readTCyBufferedTransport.writeTTransportExceptionasyncio.coroutinesbuf_sizecleancline_in_tracebackclosedata__dict___dict__doc__flush__func__get_transport__getstate__getvalue_is_coroutineis_openitems__main____metaclass____module____mro_entries____name____new__objectopenpop__prepare____pyx_checksum__pyx_result__pyx_state__pyx_type__pyx_unpickle_TCyBufferedTransport__pyx_vtable____qualname__read__reduce____reduce_cython____reduce_ex__self__set_name__setdefault__setstate____setstate_cython__statesz__test__thriftpy2.transport.buffered.cybufferedtransupdateuse_setstatevalueswrite\200\001\330\0042\260!\2606\270\021\200A\330\010\017\320\017#\2401\240A\200A\330\010\014\210E\220\026\220q\330\010\014\210E\220\026\220q\200A\330\010\026\220c\230\021\230!\330\010\017\210t\2208\2301\230F\240!\200A\330\010\017\210t\2206\230\030\240\021\200A\330\010\017\210t\2206\230\031\240!\200A\330\010\017\210t\2206\230\025\230a\200A\330\010\017\210t\2206\230\026\230q\200A\330\010\017\210t\2208\2301\200A\330\010\017\210t\220;\230a\230q\200\001\360\010\000\005\016\210T\220\027\230\004\230H\240D\250\001\330\004\014\210G\2201\220F\230,\240a\330\004\007\200v\210W\220E\230\024\230Q\330\010\022\220!\330\010\027\220q\340\010\027\220t\2306\240\027\250\005""\250S\260\004\260G\2707\300%\300s\310$\310f\320T[\320[\\\330\004\007\200q\330\010\017\320\0175\260T\270\021\270'\300\033\310G\320ST\340\010\017\320\0175\260T\270\021\270'\300\033\310A\200\001\340\004\037\230q\320 0\260\013\270;\300k\320QR\330\004\023\320\023'\240x\250q\260\001\330\004\007\200|\2207\230!\330\0106\260a\3207N\310n\320\\]\330\004\013\2101"; + PyObject *data = NULL; + CYTHON_UNUSED_VAR(__Pyx_DecompressString); + #endif + PyObject **stringtab = __pyx_mstate->__pyx_string_tab; + Py_ssize_t pos = 0; + for (int i = 0; i < 84; i++) { + Py_ssize_t bytes_length = index[i].length; + PyObject *string = PyUnicode_DecodeUTF8(bytes + pos, bytes_length, NULL); + if (likely(string) && i >= 15) PyUnicode_InternInPlace(&string); + if (unlikely(!string)) { + Py_XDECREF(data); + __PYX_ERR(0, 1, __pyx_L1_error) + } + stringtab[i] = string; + pos += bytes_length; + } + for (int i = 84; i < 96; i++) { + Py_ssize_t bytes_length = index[i].length; + PyObject *string = PyBytes_FromStringAndSize(bytes + pos, bytes_length); + stringtab[i] = string; + pos += bytes_length; + if (unlikely(!string)) { + Py_XDECREF(data); + __PYX_ERR(0, 1, __pyx_L1_error) + } + } + Py_XDECREF(data); + for (Py_ssize_t i = 0; i < 96; i++) { + if (unlikely(PyObject_Hash(stringtab[i]) == -1)) { + __PYX_ERR(0, 1, __pyx_L1_error) + } + } + #if CYTHON_IMMORTAL_CONSTANTS + { + PyObject **table = stringtab + 84; + for (Py_ssize_t i=0; i<12; ++i) { + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + #if PY_VERSION_HEX < 0x030E0000 + if (_Py_IsOwnedByCurrentThread(table[i]) && Py_REFCNT(table[i]) == 1) + #else + if (PyUnstable_Object_IsUniquelyReferenced(table[i])) + #endif + { + Py_SET_REFCNT(table[i], _Py_IMMORTAL_REFCNT_LOCAL); + } + #else + Py_SET_REFCNT(table[i], _Py_IMMORTAL_INITIAL_REFCNT); + #endif + } + } + #endif + } + { + PyObject **numbertab = __pyx_mstate->__pyx_number_tab + 0; + int8_t const cint_constants_1[] = {0}; + int32_t const cint_constants_4[] = {166623181L}; + for (int i = 0; i < 2; i++) { + numbertab[i] = PyLong_FromLong((i < 1 ? cint_constants_1[i - 0] : cint_constants_4[i - 1])); + if (unlikely(!numbertab[i])) __PYX_ERR(0, 1, __pyx_L1_error) + } + } + #if CYTHON_IMMORTAL_CONSTANTS + { + PyObject **table = __pyx_mstate->__pyx_number_tab; + for (Py_ssize_t i=0; i<2; ++i) { + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + #if PY_VERSION_HEX < 0x030E0000 + if (_Py_IsOwnedByCurrentThread(table[i]) && Py_REFCNT(table[i]) == 1) + #else + if (PyUnstable_Object_IsUniquelyReferenced(table[i])) + #endif + { + Py_SET_REFCNT(table[i], _Py_IMMORTAL_REFCNT_LOCAL); + } + #else + Py_SET_REFCNT(table[i], _Py_IMMORTAL_INITIAL_REFCNT); + #endif + } + } + #endif + return 0; + __pyx_L1_error:; + return -1; +} +/* #### Code section: init_codeobjects ### */ +typedef struct { + unsigned int argcount : 2; + unsigned int num_posonly_args : 1; + unsigned int num_kwonly_args : 1; + unsigned int nlocals : 3; + unsigned int flags : 10; + unsigned int first_line : 7; +} __Pyx_PyCode_New_function_description; +/* NewCodeObj.proto */ +static PyObject* __Pyx_PyCode_New( + const __Pyx_PyCode_New_function_description descr, + PyObject * const *varnames, + PyObject *filename, + PyObject *funcname, + PyObject *line_table, + PyObject *tuple_dedup_map +); + + +static int __Pyx_CreateCodeObjects(__pyx_mstatetype *__pyx_mstate) { + PyObject* tuple_dedup_map = PyDict_New(); + if (unlikely(!tuple_dedup_map)) return -1; + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 28}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[0] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_thriftpy2_transport_buffered_cyb_2, __pyx_mstate->__pyx_n_u_clean, __pyx_mstate->__pyx_kp_b_iso88591_A_E_q_E_q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[0])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 32}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[1] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_thriftpy2_transport_buffered_cyb_2, __pyx_mstate->__pyx_n_u_is_open, __pyx_mstate->__pyx_kp_b_iso88591_A_t6, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[1])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 35}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[2] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_thriftpy2_transport_buffered_cyb_2, __pyx_mstate->__pyx_n_u_open, __pyx_mstate->__pyx_kp_b_iso88591_A_t6_a, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[2])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 38}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[3] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_thriftpy2_transport_buffered_cyb_2, __pyx_mstate->__pyx_n_u_close, __pyx_mstate->__pyx_kp_b_iso88591_A_t6_q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[3])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 3, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 41}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_data, __pyx_mstate->__pyx_n_u_sz}; + __pyx_mstate_global->__pyx_codeobj_tab[4] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_thriftpy2_transport_buffered_cyb_2, __pyx_mstate->__pyx_n_u_write, __pyx_mstate->__pyx_kp_b_iso88591_A_c_t81F, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[4])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 45}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_sz}; + __pyx_mstate_global->__pyx_codeobj_tab[5] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_thriftpy2_transport_buffered_cyb_2, __pyx_mstate->__pyx_n_u_read, __pyx_mstate->__pyx_kp_b_iso88591_A_t_aq, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[5])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 48}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[6] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_thriftpy2_transport_buffered_cyb_2, __pyx_mstate->__pyx_n_u_flush, __pyx_mstate->__pyx_kp_b_iso88591_A_t81, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[6])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 89}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[7] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_thriftpy2_transport_buffered_cyb_2, __pyx_mstate->__pyx_n_u_getvalue, __pyx_mstate->__pyx_kp_b_iso88591_A_t6_2, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[7])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 4, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 1}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_state, __pyx_mstate->__pyx_n_u_dict_2, __pyx_mstate->__pyx_n_u_use_setstate}; + __pyx_mstate_global->__pyx_codeobj_tab[8] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_stringsource, __pyx_mstate->__pyx_n_u_reduce_cython, __pyx_mstate->__pyx_kp_b_iso88591_T_HD_G1F_a_vWE_Q_q_t6_S_G7_s_fT, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[8])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 16}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_pyx_state}; + __pyx_mstate_global->__pyx_codeobj_tab[9] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_stringsource, __pyx_mstate->__pyx_n_u_setstate_cython, __pyx_mstate->__pyx_kp_b_iso88591_2_6, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[9])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 94}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_trans}; + __pyx_mstate_global->__pyx_codeobj_tab[10] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_thriftpy2_transport_buffered_cyb_2, __pyx_mstate->__pyx_n_u_get_transport, __pyx_mstate->__pyx_kp_b_iso88591_A_1A, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[10])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {3, 0, 0, 4, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 4}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_pyx_type, __pyx_mstate->__pyx_n_u_pyx_checksum, __pyx_mstate->__pyx_n_u_pyx_state, __pyx_mstate->__pyx_n_u_pyx_result}; + __pyx_mstate_global->__pyx_codeobj_tab[11] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_stringsource, __pyx_mstate->__pyx_n_u_pyx_unpickle_TCyBufferedTransp, __pyx_mstate->__pyx_kp_b_iso88591_q_0_kQR_xq_7_6a7Nn_1, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[11])) goto bad; + } + Py_DECREF(tuple_dedup_map); + return 0; + bad: + Py_DECREF(tuple_dedup_map); + return -1; +} +/* #### Code section: init_globals ### */ + +static int __Pyx_InitGlobals(void) { + /* PythonCompatibility.init */ + if (likely(__Pyx_init_co_variables() == 0)); else + + if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 1, __pyx_L1_error) + + /* CommonTypesMetaclass.init */ + if (likely(__pyx_CommonTypesMetaclass_init(__pyx_m) == 0)); else + + if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 1, __pyx_L1_error) + + /* CachedMethodType.init */ + #if CYTHON_COMPILING_IN_LIMITED_API + { + PyObject *typesModule=NULL; + typesModule = PyImport_ImportModule("types"); + if (typesModule) { + __pyx_mstate_global->__Pyx_CachedMethodType = PyObject_GetAttrString(typesModule, "MethodType"); + Py_DECREF(typesModule); + } + } // error handling follows + #endif + + if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 1, __pyx_L1_error) + + /* CythonFunctionShared.init */ + if (likely(__pyx_CyFunction_init(__pyx_m) == 0)); else + + if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 1, __pyx_L1_error) + + return 0; + __pyx_L1_error:; + return -1; +} +/* #### Code section: cleanup_globals ### */ +/* #### Code section: cleanup_module ### */ +/* #### Code section: main_method ### */ +/* #### Code section: utility_code_pragmas ### */ +#ifdef _MSC_VER +#pragma warning( push ) +/* Warning 4127: conditional expression is constant + * Cython uses constant conditional expressions to allow in inline functions to be optimized at + * compile-time, so this warning is not useful + */ +#pragma warning( disable : 4127 ) +#endif + + + +/* #### Code section: utility_code_def ### */ + +/* --- Runtime support code --- */ +/* Refnanny */ +#if CYTHON_REFNANNY +static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { + PyObject *m = NULL, *p = NULL; + void *r = NULL; + m = PyImport_ImportModule(modname); + if (!m) goto end; + p = PyObject_GetAttrString(m, "RefNannyAPI"); + if (!p) goto end; + r = PyLong_AsVoidPtr(p); +end: + Py_XDECREF(p); + Py_XDECREF(m); + return (__Pyx_RefNannyAPIStruct *)r; +} +#endif + +/* PyErrExceptionMatches (used by PyObjectGetAttrStrNoError) */ +#if CYTHON_FAST_THREAD_STATE +static int __Pyx_PyErr_ExceptionMatchesTuple(PyObject *exc_type, PyObject *tuple) { + Py_ssize_t i, n; + n = PyTuple_GET_SIZE(tuple); + for (i=0; i= 0x030C00A6 + PyObject *current_exception = tstate->current_exception; + if (unlikely(!current_exception)) return 0; + exc_type = (PyObject*) Py_TYPE(current_exception); + if (exc_type == err) return 1; +#else + exc_type = tstate->curexc_type; + if (exc_type == err) return 1; + if (unlikely(!exc_type)) return 0; +#endif + #if CYTHON_AVOID_BORROWED_REFS + Py_INCREF(exc_type); + #endif + if (unlikely(PyTuple_Check(err))) { + result = __Pyx_PyErr_ExceptionMatchesTuple(exc_type, err); + } else { + result = __Pyx_PyErr_GivenExceptionMatches(exc_type, err); + } + #if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(exc_type); + #endif + return result; +} +#endif + +/* PyErrFetchRestore (used by PyObjectGetAttrStrNoError) */ +#if CYTHON_FAST_THREAD_STATE +static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { +#if PY_VERSION_HEX >= 0x030C00A6 + PyObject *tmp_value; + assert(type == NULL || (value != NULL && type == (PyObject*) Py_TYPE(value))); + if (value) { + #if CYTHON_COMPILING_IN_CPYTHON + if (unlikely(((PyBaseExceptionObject*) value)->traceback != tb)) + #endif + PyException_SetTraceback(value, tb); + } + tmp_value = tstate->current_exception; + tstate->current_exception = value; + Py_XDECREF(tmp_value); + Py_XDECREF(type); + Py_XDECREF(tb); +#else + PyObject *tmp_type, *tmp_value, *tmp_tb; + tmp_type = tstate->curexc_type; + tmp_value = tstate->curexc_value; + tmp_tb = tstate->curexc_traceback; + tstate->curexc_type = type; + tstate->curexc_value = value; + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#endif +} +static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { +#if PY_VERSION_HEX >= 0x030C00A6 + PyObject* exc_value; + exc_value = tstate->current_exception; + tstate->current_exception = 0; + *value = exc_value; + *type = NULL; + *tb = NULL; + if (exc_value) { + *type = (PyObject*) Py_TYPE(exc_value); + Py_INCREF(*type); + #if CYTHON_COMPILING_IN_CPYTHON + *tb = ((PyBaseExceptionObject*) exc_value)->traceback; + Py_XINCREF(*tb); + #else + *tb = PyException_GetTraceback(exc_value); + #endif + } +#else + *type = tstate->curexc_type; + *value = tstate->curexc_value; + *tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; +#endif +} +#endif + +/* PyObjectGetAttrStr (used by PyObjectGetAttrStrNoError) */ +#if CYTHON_USE_TYPE_SLOTS +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { + PyTypeObject* tp = Py_TYPE(obj); + if (likely(tp->tp_getattro)) + return tp->tp_getattro(obj, attr_name); + return PyObject_GetAttr(obj, attr_name); +} +#endif + +/* PyObjectGetAttrStrNoError (used by GetBuiltinName) */ +#if __PYX_LIMITED_VERSION_HEX < 0x030d0000 +static void __Pyx_PyObject_GetAttrStr_ClearAttributeError(void) { + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + if (likely(__Pyx_PyErr_ExceptionMatches(PyExc_AttributeError))) + __Pyx_PyErr_Clear(); +} +#endif +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStrNoError(PyObject* obj, PyObject* attr_name) { + PyObject *result; +#if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + (void) PyObject_GetOptionalAttr(obj, attr_name, &result); + return result; +#else +#if CYTHON_COMPILING_IN_CPYTHON && CYTHON_USE_TYPE_SLOTS + PyTypeObject* tp = Py_TYPE(obj); + if (likely(tp->tp_getattro == PyObject_GenericGetAttr)) { + return _PyObject_GenericGetAttrWithDict(obj, attr_name, NULL, 1); + } +#endif + result = __Pyx_PyObject_GetAttrStr(obj, attr_name); + if (unlikely(!result)) { + __Pyx_PyObject_GetAttrStr_ClearAttributeError(); + } + return result; +#endif +} + +/* GetBuiltinName */ +static PyObject *__Pyx_GetBuiltinName(PyObject *name) { + PyObject* result = __Pyx_PyObject_GetAttrStrNoError(__pyx_mstate_global->__pyx_b, name); + if (unlikely(!result) && !PyErr_Occurred()) { + PyErr_Format(PyExc_NameError, + "name '%U' is not defined", name); + } + return result; +} + +/* TupleAndListFromArray (used by fastcall) */ +#if !CYTHON_COMPILING_IN_CPYTHON && CYTHON_METH_FASTCALL +static CYTHON_INLINE PyObject * +__Pyx_PyTuple_FromArray(PyObject *const *src, Py_ssize_t n) +{ + PyObject *res; + Py_ssize_t i; + if (n <= 0) { + return __Pyx_NewRef(__pyx_mstate_global->__pyx_empty_tuple); + } + res = PyTuple_New(n); + if (unlikely(res == NULL)) return NULL; + for (i = 0; i < n; i++) { + if (unlikely(__Pyx_PyTuple_SET_ITEM(res, i, src[i]) < (0))) { + Py_DECREF(res); + return NULL; + } + Py_INCREF(src[i]); + } + return res; +} +#elif CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE void __Pyx_copy_object_array(PyObject *const *CYTHON_RESTRICT src, PyObject** CYTHON_RESTRICT dest, Py_ssize_t length) { + PyObject *v; + Py_ssize_t i; + for (i = 0; i < length; i++) { + v = dest[i] = src[i]; + Py_INCREF(v); + } +} +static CYTHON_INLINE PyObject * +__Pyx_PyTuple_FromArray(PyObject *const *src, Py_ssize_t n) +{ + PyObject *res; + if (n <= 0) { + return __Pyx_NewRef(__pyx_mstate_global->__pyx_empty_tuple); + } + res = PyTuple_New(n); + if (unlikely(res == NULL)) return NULL; + __Pyx_copy_object_array(src, ((PyTupleObject*)res)->ob_item, n); + return res; +} +static CYTHON_INLINE PyObject * +__Pyx_PyList_FromArray(PyObject *const *src, Py_ssize_t n) +{ + PyObject *res; + if (n <= 0) { + return PyList_New(0); + } + res = PyList_New(n); + if (unlikely(res == NULL)) return NULL; + __Pyx_copy_object_array(src, ((PyListObject*)res)->ob_item, n); + return res; +} +#endif + +/* BytesEquals (used by UnicodeEquals) */ +static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals) { +#if CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_GRAAL ||\ + !(CYTHON_ASSUME_SAFE_SIZE && CYTHON_ASSUME_SAFE_MACROS) + return PyObject_RichCompareBool(s1, s2, equals); +#else + if (s1 == s2) { + return (equals == Py_EQ); + } else if (PyBytes_CheckExact(s1) & PyBytes_CheckExact(s2)) { + const char *ps1, *ps2; + Py_ssize_t length = PyBytes_GET_SIZE(s1); + if (length != PyBytes_GET_SIZE(s2)) + return (equals == Py_NE); + ps1 = PyBytes_AS_STRING(s1); + ps2 = PyBytes_AS_STRING(s2); + if (ps1[0] != ps2[0]) { + return (equals == Py_NE); + } else if (length == 1) { + return (equals == Py_EQ); + } else { + int result; +#if CYTHON_USE_UNICODE_INTERNALS && (PY_VERSION_HEX < 0x030B0000) + Py_hash_t hash1, hash2; + hash1 = ((PyBytesObject*)s1)->ob_shash; + hash2 = ((PyBytesObject*)s2)->ob_shash; + if (hash1 != hash2 && hash1 != -1 && hash2 != -1) { + return (equals == Py_NE); + } +#endif + result = memcmp(ps1, ps2, (size_t)length); + return (equals == Py_EQ) ? (result == 0) : (result != 0); + } + } else if ((s1 == Py_None) & PyBytes_CheckExact(s2)) { + return (equals == Py_NE); + } else if ((s2 == Py_None) & PyBytes_CheckExact(s1)) { + return (equals == Py_NE); + } else { + int result; + PyObject* py_result = PyObject_RichCompare(s1, s2, equals); + if (!py_result) + return -1; + result = __Pyx_PyObject_IsTrue(py_result); + Py_DECREF(py_result); + return result; + } +#endif +} + +/* UnicodeEquals (used by fastcall) */ +static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals) { +#if CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_GRAAL + return PyObject_RichCompareBool(s1, s2, equals); +#else + int s1_is_unicode, s2_is_unicode; + if (s1 == s2) { + goto return_eq; + } + s1_is_unicode = PyUnicode_CheckExact(s1); + s2_is_unicode = PyUnicode_CheckExact(s2); + if (s1_is_unicode & s2_is_unicode) { + Py_ssize_t length, length2; + int kind; + void *data1, *data2; + #if !CYTHON_COMPILING_IN_LIMITED_API + if (unlikely(__Pyx_PyUnicode_READY(s1) < 0) || unlikely(__Pyx_PyUnicode_READY(s2) < 0)) + return -1; + #endif + length = __Pyx_PyUnicode_GET_LENGTH(s1); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(length < 0)) return -1; + #endif + length2 = __Pyx_PyUnicode_GET_LENGTH(s2); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(length2 < 0)) return -1; + #endif + if (length != length2) { + goto return_ne; + } +#if CYTHON_USE_UNICODE_INTERNALS + { + Py_hash_t hash1, hash2; + hash1 = ((PyASCIIObject*)s1)->hash; + hash2 = ((PyASCIIObject*)s2)->hash; + if (hash1 != hash2 && hash1 != -1 && hash2 != -1) { + goto return_ne; + } + } +#endif + kind = __Pyx_PyUnicode_KIND(s1); + if (kind != __Pyx_PyUnicode_KIND(s2)) { + goto return_ne; + } + data1 = __Pyx_PyUnicode_DATA(s1); + data2 = __Pyx_PyUnicode_DATA(s2); + if (__Pyx_PyUnicode_READ(kind, data1, 0) != __Pyx_PyUnicode_READ(kind, data2, 0)) { + goto return_ne; + } else if (length == 1) { + goto return_eq; + } else { + int result = memcmp(data1, data2, (size_t)(length * kind)); + return (equals == Py_EQ) ? (result == 0) : (result != 0); + } + } else if ((s1 == Py_None) & s2_is_unicode) { + goto return_ne; + } else if ((s2 == Py_None) & s1_is_unicode) { + goto return_ne; + } else { + int result; + PyObject* py_result = PyObject_RichCompare(s1, s2, equals); + if (!py_result) + return -1; + result = __Pyx_PyObject_IsTrue(py_result); + Py_DECREF(py_result); + return result; + } +return_eq: + return (equals == Py_EQ); +return_ne: + return (equals == Py_NE); +#endif +} + +/* fastcall */ +#if CYTHON_METH_FASTCALL +static CYTHON_INLINE PyObject * __Pyx_GetKwValue_FASTCALL(PyObject *kwnames, PyObject *const *kwvalues, PyObject *s) +{ + Py_ssize_t i, n = __Pyx_PyTuple_GET_SIZE(kwnames); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(n == -1)) return NULL; + #endif + for (i = 0; i < n; i++) + { + PyObject *namei = __Pyx_PyTuple_GET_ITEM(kwnames, i); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(!namei)) return NULL; + #endif + if (s == namei) return kwvalues[i]; + } + for (i = 0; i < n; i++) + { + PyObject *namei = __Pyx_PyTuple_GET_ITEM(kwnames, i); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(!namei)) return NULL; + #endif + int eq = __Pyx_PyUnicode_Equals(s, namei, Py_EQ); + if (unlikely(eq != 0)) { + if (unlikely(eq < 0)) return NULL; + return kwvalues[i]; + } + } + return NULL; +} +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030d0000 || CYTHON_COMPILING_IN_LIMITED_API +CYTHON_UNUSED static PyObject *__Pyx_KwargsAsDict_FASTCALL(PyObject *kwnames, PyObject *const *kwvalues) { + Py_ssize_t i, nkwargs; + PyObject *dict; +#if !CYTHON_ASSUME_SAFE_SIZE + nkwargs = PyTuple_Size(kwnames); + if (unlikely(nkwargs < 0)) return NULL; +#else + nkwargs = PyTuple_GET_SIZE(kwnames); +#endif + dict = PyDict_New(); + if (unlikely(!dict)) + return NULL; + for (i=0; itp_call; + if (unlikely(!call)) + return PyObject_Call(func, arg, kw); + if (unlikely(Py_EnterRecursiveCall(" while calling a Python object"))) + return NULL; + result = (*call)(func, arg, kw); + Py_LeaveRecursiveCall(); + if (unlikely(!result) && unlikely(!PyErr_Occurred())) { + PyErr_SetString( + PyExc_SystemError, + "NULL result without error in PyObject_Call"); + } + return result; +} +#endif + +/* PyObjectCallMethO (used by PyObjectFastCall) */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg) { + PyObject *self, *result; + PyCFunction cfunc; + cfunc = __Pyx_CyOrPyCFunction_GET_FUNCTION(func); + self = __Pyx_CyOrPyCFunction_GET_SELF(func); + if (unlikely(Py_EnterRecursiveCall(" while calling a Python object"))) + return NULL; + result = cfunc(self, arg); + Py_LeaveRecursiveCall(); + if (unlikely(!result) && unlikely(!PyErr_Occurred())) { + PyErr_SetString( + PyExc_SystemError, + "NULL result without error in PyObject_Call"); + } + return result; +} +#endif + +/* PyObjectFastCall (used by PyObjectCallOneArg) */ +#if PY_VERSION_HEX < 0x03090000 || CYTHON_COMPILING_IN_LIMITED_API +static PyObject* __Pyx_PyObject_FastCall_fallback(PyObject *func, PyObject * const*args, size_t nargs, PyObject *kwargs) { + PyObject *argstuple; + PyObject *result = 0; + size_t i; + argstuple = PyTuple_New((Py_ssize_t)nargs); + if (unlikely(!argstuple)) return NULL; + for (i = 0; i < nargs; i++) { + Py_INCREF(args[i]); + if (__Pyx_PyTuple_SET_ITEM(argstuple, (Py_ssize_t)i, args[i]) != (0)) goto bad; + } + result = __Pyx_PyObject_Call(func, argstuple, kwargs); + bad: + Py_DECREF(argstuple); + return result; +} +#endif +#if CYTHON_VECTORCALL && !CYTHON_COMPILING_IN_LIMITED_API + #if PY_VERSION_HEX < 0x03090000 + #define __Pyx_PyVectorcall_Function(callable) _PyVectorcall_Function(callable) + #elif CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE vectorcallfunc __Pyx_PyVectorcall_Function(PyObject *callable) { + PyTypeObject *tp = Py_TYPE(callable); + #if defined(__Pyx_CyFunction_USED) + if (__Pyx_CyFunction_CheckExact(callable)) { + return __Pyx_CyFunction_func_vectorcall(callable); + } + #endif + if (!PyType_HasFeature(tp, Py_TPFLAGS_HAVE_VECTORCALL)) { + return NULL; + } + assert(PyCallable_Check(callable)); + Py_ssize_t offset = tp->tp_vectorcall_offset; + assert(offset > 0); + vectorcallfunc ptr; + memcpy(&ptr, (char *) callable + offset, sizeof(ptr)); + return ptr; +} + #else + #define __Pyx_PyVectorcall_Function(callable) PyVectorcall_Function(callable) + #endif +#endif +static CYTHON_INLINE PyObject* __Pyx_PyObject_FastCallDict(PyObject *func, PyObject *const *args, size_t _nargs, PyObject *kwargs) { + Py_ssize_t nargs = __Pyx_PyVectorcall_NARGS(_nargs); +#if CYTHON_COMPILING_IN_CPYTHON + if (nargs == 0 && kwargs == NULL) { + if (__Pyx_CyOrPyCFunction_Check(func) && likely( __Pyx_CyOrPyCFunction_GET_FLAGS(func) & METH_NOARGS)) + return __Pyx_PyObject_CallMethO(func, NULL); + } + else if (nargs == 1 && kwargs == NULL) { + if (__Pyx_CyOrPyCFunction_Check(func) && likely( __Pyx_CyOrPyCFunction_GET_FLAGS(func) & METH_O)) + return __Pyx_PyObject_CallMethO(func, args[0]); + } +#endif + if (kwargs == NULL) { + #if CYTHON_VECTORCALL + #if CYTHON_COMPILING_IN_LIMITED_API + return PyObject_Vectorcall(func, args, _nargs, NULL); + #else + vectorcallfunc f = __Pyx_PyVectorcall_Function(func); + if (f) { + return f(func, args, _nargs, NULL); + } + #endif + #endif + } + if (nargs == 0) { + return __Pyx_PyObject_Call(func, __pyx_mstate_global->__pyx_empty_tuple, kwargs); + } + #if PY_VERSION_HEX >= 0x03090000 && !CYTHON_COMPILING_IN_LIMITED_API + return PyObject_VectorcallDict(func, args, (size_t)nargs, kwargs); + #else + return __Pyx_PyObject_FastCall_fallback(func, args, (size_t)nargs, kwargs); + #endif +} + +/* PyObjectCallOneArg (used by CallUnboundCMethod0) */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { + PyObject *args[2] = {NULL, arg}; + return __Pyx_PyObject_FastCall(func, args+1, 1 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET); +} + +/* UnpackUnboundCMethod (used by CallUnboundCMethod0) */ +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030C0000 +static PyObject *__Pyx_SelflessCall(PyObject *method, PyObject *args, PyObject *kwargs) { + PyObject *result; + PyObject *selfless_args = PyTuple_GetSlice(args, 1, PyTuple_Size(args)); + if (unlikely(!selfless_args)) return NULL; + result = PyObject_Call(method, selfless_args, kwargs); + Py_DECREF(selfless_args); + return result; +} +#elif CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX < 0x03090000 +static PyObject *__Pyx_SelflessCall(PyObject *method, PyObject **args, Py_ssize_t nargs, PyObject *kwnames) { + return _PyObject_Vectorcall + (method, args ? args+1 : NULL, nargs ? nargs-1 : 0, kwnames); +} +#else +static PyObject *__Pyx_SelflessCall(PyObject *method, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames) { + return +#if PY_VERSION_HEX < 0x03090000 + _PyObject_Vectorcall +#else + PyObject_Vectorcall +#endif + (method, args ? args+1 : NULL, nargs ? (size_t) nargs-1 : 0, kwnames); +} +#endif +static PyMethodDef __Pyx_UnboundCMethod_Def = { + "CythonUnboundCMethod", + __PYX_REINTERPRET_FUNCION(PyCFunction, __Pyx_SelflessCall), +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030C0000 + METH_VARARGS | METH_KEYWORDS, +#else + METH_FASTCALL | METH_KEYWORDS, +#endif + NULL +}; +static int __Pyx_TryUnpackUnboundCMethod(__Pyx_CachedCFunction* target) { + PyObject *method, *result=NULL; + method = __Pyx_PyObject_GetAttrStr(target->type, *target->method_name); + if (unlikely(!method)) + return -1; + result = method; +#if CYTHON_COMPILING_IN_CPYTHON + if (likely(__Pyx_TypeCheck(method, &PyMethodDescr_Type))) + { + PyMethodDescrObject *descr = (PyMethodDescrObject*) method; + target->func = descr->d_method->ml_meth; + target->flag = descr->d_method->ml_flags & ~(METH_CLASS | METH_STATIC | METH_COEXIST | METH_STACKLESS); + } else +#endif +#if CYTHON_COMPILING_IN_PYPY +#else + if (PyCFunction_Check(method)) +#endif + { + PyObject *self; + int self_found; +#if CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_PYPY + self = PyObject_GetAttrString(method, "__self__"); + if (!self) { + PyErr_Clear(); + } +#else + self = PyCFunction_GET_SELF(method); +#endif + self_found = (self && self != Py_None); +#if CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_PYPY + Py_XDECREF(self); +#endif + if (self_found) { + PyObject *unbound_method = PyCFunction_New(&__Pyx_UnboundCMethod_Def, method); + if (unlikely(!unbound_method)) return -1; + Py_DECREF(method); + result = unbound_method; + } + } +#if !CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + if (unlikely(target->method)) { + Py_DECREF(result); + } else +#endif + target->method = result; + return 0; +} + +/* CallUnboundCMethod0 */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_CallUnboundCMethod0(__Pyx_CachedCFunction* cfunc, PyObject* self) { + int was_initialized = __Pyx_CachedCFunction_GetAndSetInitializing(cfunc); + if (likely(was_initialized == 2 && cfunc->func)) { + if (likely(cfunc->flag == METH_NOARGS)) + return __Pyx_CallCFunction(cfunc, self, NULL); + if (likely(cfunc->flag == METH_FASTCALL)) + return __Pyx_CallCFunctionFast(cfunc, self, NULL, 0); + if (cfunc->flag == (METH_FASTCALL | METH_KEYWORDS)) + return __Pyx_CallCFunctionFastWithKeywords(cfunc, self, NULL, 0, NULL); + if (likely(cfunc->flag == (METH_VARARGS | METH_KEYWORDS))) + return __Pyx_CallCFunctionWithKeywords(cfunc, self, __pyx_mstate_global->__pyx_empty_tuple, NULL); + if (cfunc->flag == METH_VARARGS) + return __Pyx_CallCFunction(cfunc, self, __pyx_mstate_global->__pyx_empty_tuple); + return __Pyx__CallUnboundCMethod0(cfunc, self); + } +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + else if (unlikely(was_initialized == 1)) { + __Pyx_CachedCFunction tmp_cfunc = { +#ifndef __cplusplus + 0 +#endif + }; + tmp_cfunc.type = cfunc->type; + tmp_cfunc.method_name = cfunc->method_name; + return __Pyx__CallUnboundCMethod0(&tmp_cfunc, self); + } +#endif + PyObject *result = __Pyx__CallUnboundCMethod0(cfunc, self); + __Pyx_CachedCFunction_SetFinishedInitializing(cfunc); + return result; +} +#endif +static PyObject* __Pyx__CallUnboundCMethod0(__Pyx_CachedCFunction* cfunc, PyObject* self) { + PyObject *result; + if (unlikely(!cfunc->method) && unlikely(__Pyx_TryUnpackUnboundCMethod(cfunc) < 0)) return NULL; + result = __Pyx_PyObject_CallOneArg(cfunc->method, self); + return result; +} + +/* py_dict_items (used by OwnedDictNext) */ +static CYTHON_INLINE PyObject* __Pyx_PyDict_Items(PyObject* d) { + return __Pyx_CallUnboundCMethod0(&__pyx_mstate_global->__pyx_umethod_PyDict_Type_items, d); +} + +/* py_dict_values (used by OwnedDictNext) */ +static CYTHON_INLINE PyObject* __Pyx_PyDict_Values(PyObject* d) { + return __Pyx_CallUnboundCMethod0(&__pyx_mstate_global->__pyx_umethod_PyDict_Type_values, d); +} + +/* OwnedDictNext (used by ParseKeywordsImpl) */ +#if CYTHON_AVOID_BORROWED_REFS +static int __Pyx_PyDict_NextRef(PyObject *p, PyObject **ppos, PyObject **pkey, PyObject **pvalue) { + PyObject *next = NULL; + if (!*ppos) { + if (pvalue) { + PyObject *dictview = pkey ? __Pyx_PyDict_Items(p) : __Pyx_PyDict_Values(p); + if (unlikely(!dictview)) goto bad; + *ppos = PyObject_GetIter(dictview); + Py_DECREF(dictview); + } else { + *ppos = PyObject_GetIter(p); + } + if (unlikely(!*ppos)) goto bad; + } + next = PyIter_Next(*ppos); + if (!next) { + if (PyErr_Occurred()) goto bad; + return 0; + } + if (pkey && pvalue) { + *pkey = __Pyx_PySequence_ITEM(next, 0); + if (unlikely(*pkey)) goto bad; + *pvalue = __Pyx_PySequence_ITEM(next, 1); + if (unlikely(*pvalue)) goto bad; + Py_DECREF(next); + } else if (pkey) { + *pkey = next; + } else { + assert(pvalue); + *pvalue = next; + } + return 1; + bad: + Py_XDECREF(next); +#if !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d0000 + PyErr_FormatUnraisable("Exception ignored in __Pyx_PyDict_NextRef"); +#else + PyErr_WriteUnraisable(__pyx_mstate_global->__pyx_n_u_Pyx_PyDict_NextRef); +#endif + if (pkey) *pkey = NULL; + if (pvalue) *pvalue = NULL; + return 0; +} +#else // !CYTHON_AVOID_BORROWED_REFS +static int __Pyx_PyDict_NextRef(PyObject *p, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue) { + int result = PyDict_Next(p, ppos, pkey, pvalue); + if (likely(result == 1)) { + if (pkey) Py_INCREF(*pkey); + if (pvalue) Py_INCREF(*pvalue); + } + return result; +} +#endif + +/* RaiseDoubleKeywords (used by ParseKeywordsImpl) */ +static void __Pyx_RaiseDoubleKeywordsError( + const char* func_name, + PyObject* kw_name) +{ + PyErr_Format(PyExc_TypeError, + "%s() got multiple values for keyword argument '%U'", func_name, kw_name); +} + +/* CallUnboundCMethod2 */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject *__Pyx_CallUnboundCMethod2(__Pyx_CachedCFunction *cfunc, PyObject *self, PyObject *arg1, PyObject *arg2) { + int was_initialized = __Pyx_CachedCFunction_GetAndSetInitializing(cfunc); + if (likely(was_initialized == 2 && cfunc->func)) { + PyObject *args[2] = {arg1, arg2}; + if (cfunc->flag == METH_FASTCALL) { + return __Pyx_CallCFunctionFast(cfunc, self, args, 2); + } + if (cfunc->flag == (METH_FASTCALL | METH_KEYWORDS)) + return __Pyx_CallCFunctionFastWithKeywords(cfunc, self, args, 2, NULL); + } +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + else if (unlikely(was_initialized == 1)) { + __Pyx_CachedCFunction tmp_cfunc = { +#ifndef __cplusplus + 0 +#endif + }; + tmp_cfunc.type = cfunc->type; + tmp_cfunc.method_name = cfunc->method_name; + return __Pyx__CallUnboundCMethod2(&tmp_cfunc, self, arg1, arg2); + } +#endif + PyObject *result = __Pyx__CallUnboundCMethod2(cfunc, self, arg1, arg2); + __Pyx_CachedCFunction_SetFinishedInitializing(cfunc); + return result; +} +#endif +static PyObject* __Pyx__CallUnboundCMethod2(__Pyx_CachedCFunction* cfunc, PyObject* self, PyObject* arg1, PyObject* arg2){ + if (unlikely(!cfunc->func && !cfunc->method) && unlikely(__Pyx_TryUnpackUnboundCMethod(cfunc) < 0)) return NULL; +#if CYTHON_COMPILING_IN_CPYTHON + if (cfunc->func && (cfunc->flag & METH_VARARGS)) { + PyObject *result = NULL; + PyObject *args = PyTuple_New(2); + if (unlikely(!args)) return NULL; + Py_INCREF(arg1); + PyTuple_SET_ITEM(args, 0, arg1); + Py_INCREF(arg2); + PyTuple_SET_ITEM(args, 1, arg2); + if (cfunc->flag & METH_KEYWORDS) + result = __Pyx_CallCFunctionWithKeywords(cfunc, self, args, NULL); + else + result = __Pyx_CallCFunction(cfunc, self, args); + Py_DECREF(args); + return result; + } +#endif + { + PyObject *args[4] = {NULL, self, arg1, arg2}; + return __Pyx_PyObject_FastCall(cfunc->method, args+1, 3 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET); + } +} + +/* ParseKeywordsImpl (used by ParseKeywords) */ +static int __Pyx_ValidateDuplicatePosArgs( + PyObject *kwds, + PyObject ** const argnames[], + PyObject ** const *first_kw_arg, + const char* function_name) +{ + PyObject ** const *name = argnames; + while (name != first_kw_arg) { + PyObject *key = **name; + int found = PyDict_Contains(kwds, key); + if (unlikely(found)) { + if (found == 1) __Pyx_RaiseDoubleKeywordsError(function_name, key); + goto bad; + } + name++; + } + return 0; +bad: + return -1; +} +#if CYTHON_USE_UNICODE_INTERNALS +static CYTHON_INLINE int __Pyx_UnicodeKeywordsEqual(PyObject *s1, PyObject *s2) { + int kind; + Py_ssize_t len = PyUnicode_GET_LENGTH(s1); + if (len != PyUnicode_GET_LENGTH(s2)) return 0; + kind = PyUnicode_KIND(s1); + if (kind != PyUnicode_KIND(s2)) return 0; + const void *data1 = PyUnicode_DATA(s1); + const void *data2 = PyUnicode_DATA(s2); + return (memcmp(data1, data2, (size_t) len * (size_t) kind) == 0); +} +#endif +static int __Pyx_MatchKeywordArg_str( + PyObject *key, + PyObject ** const argnames[], + PyObject ** const *first_kw_arg, + size_t *index_found, + const char *function_name) +{ + PyObject ** const *name; + #if CYTHON_USE_UNICODE_INTERNALS + Py_hash_t key_hash = ((PyASCIIObject*)key)->hash; + if (unlikely(key_hash == -1)) { + key_hash = PyObject_Hash(key); + if (unlikely(key_hash == -1)) + goto bad; + } + #endif + name = first_kw_arg; + while (*name) { + PyObject *name_str = **name; + #if CYTHON_USE_UNICODE_INTERNALS + if (key_hash == ((PyASCIIObject*)name_str)->hash && __Pyx_UnicodeKeywordsEqual(name_str, key)) { + *index_found = (size_t) (name - argnames); + return 1; + } + #else + #if CYTHON_ASSUME_SAFE_SIZE + if (PyUnicode_GET_LENGTH(name_str) == PyUnicode_GET_LENGTH(key)) + #endif + { + int cmp = PyUnicode_Compare(name_str, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) { + *index_found = (size_t) (name - argnames); + return 1; + } + } + #endif + name++; + } + name = argnames; + while (name != first_kw_arg) { + PyObject *name_str = **name; + #if CYTHON_USE_UNICODE_INTERNALS + if (unlikely(key_hash == ((PyASCIIObject*)name_str)->hash)) { + if (__Pyx_UnicodeKeywordsEqual(name_str, key)) + goto arg_passed_twice; + } + #else + #if CYTHON_ASSUME_SAFE_SIZE + if (PyUnicode_GET_LENGTH(name_str) == PyUnicode_GET_LENGTH(key)) + #endif + { + if (unlikely(name_str == key)) goto arg_passed_twice; + int cmp = PyUnicode_Compare(name_str, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) goto arg_passed_twice; + } + #endif + name++; + } + return 0; +arg_passed_twice: + __Pyx_RaiseDoubleKeywordsError(function_name, key); + goto bad; +bad: + return -1; +} +static int __Pyx_MatchKeywordArg_nostr( + PyObject *key, + PyObject ** const argnames[], + PyObject ** const *first_kw_arg, + size_t *index_found, + const char *function_name) +{ + PyObject ** const *name; + if (unlikely(!PyUnicode_Check(key))) goto invalid_keyword_type; + name = first_kw_arg; + while (*name) { + int cmp = PyObject_RichCompareBool(**name, key, Py_EQ); + if (cmp == 1) { + *index_found = (size_t) (name - argnames); + return 1; + } + if (unlikely(cmp == -1)) goto bad; + name++; + } + name = argnames; + while (name != first_kw_arg) { + int cmp = PyObject_RichCompareBool(**name, key, Py_EQ); + if (unlikely(cmp != 0)) { + if (cmp == 1) goto arg_passed_twice; + else goto bad; + } + name++; + } + return 0; +arg_passed_twice: + __Pyx_RaiseDoubleKeywordsError(function_name, key); + goto bad; +invalid_keyword_type: + PyErr_Format(PyExc_TypeError, + "%.200s() keywords must be strings", function_name); + goto bad; +bad: + return -1; +} +static CYTHON_INLINE int __Pyx_MatchKeywordArg( + PyObject *key, + PyObject ** const argnames[], + PyObject ** const *first_kw_arg, + size_t *index_found, + const char *function_name) +{ + return likely(PyUnicode_CheckExact(key)) ? + __Pyx_MatchKeywordArg_str(key, argnames, first_kw_arg, index_found, function_name) : + __Pyx_MatchKeywordArg_nostr(key, argnames, first_kw_arg, index_found, function_name); +} +static void __Pyx_RejectUnknownKeyword( + PyObject *kwds, + PyObject ** const argnames[], + PyObject ** const *first_kw_arg, + const char *function_name) +{ + #if CYTHON_AVOID_BORROWED_REFS + PyObject *pos = NULL; + #else + Py_ssize_t pos = 0; + #endif + PyObject *key = NULL; + __Pyx_BEGIN_CRITICAL_SECTION(kwds); + while ( + #if CYTHON_AVOID_BORROWED_REFS + __Pyx_PyDict_NextRef(kwds, &pos, &key, NULL) + #else + PyDict_Next(kwds, &pos, &key, NULL) + #endif + ) { + PyObject** const *name = first_kw_arg; + while (*name && (**name != key)) name++; + if (!*name) { + size_t index_found = 0; + int cmp = __Pyx_MatchKeywordArg(key, argnames, first_kw_arg, &index_found, function_name); + if (cmp != 1) { + if (cmp == 0) { + PyErr_Format(PyExc_TypeError, + "%s() got an unexpected keyword argument '%U'", + function_name, key); + } + #if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(key); + #endif + break; + } + } + #if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(key); + #endif + } + __Pyx_END_CRITICAL_SECTION(); + #if CYTHON_AVOID_BORROWED_REFS + Py_XDECREF(pos); + #endif + assert(PyErr_Occurred()); +} +static int __Pyx_ParseKeywordDict( + PyObject *kwds, + PyObject ** const argnames[], + PyObject *values[], + Py_ssize_t num_pos_args, + Py_ssize_t num_kwargs, + const char* function_name, + int ignore_unknown_kwargs) +{ + PyObject** const *name; + PyObject** const *first_kw_arg = argnames + num_pos_args; + Py_ssize_t extracted = 0; +#if !CYTHON_COMPILING_IN_PYPY || defined(PyArg_ValidateKeywordArguments) + if (unlikely(!PyArg_ValidateKeywordArguments(kwds))) return -1; +#endif + name = first_kw_arg; + while (*name && num_kwargs > extracted) { + PyObject * key = **name; + PyObject *value; + int found = 0; + #if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + found = PyDict_GetItemRef(kwds, key, &value); + #else + value = PyDict_GetItemWithError(kwds, key); + if (value) { + Py_INCREF(value); + found = 1; + } else { + if (unlikely(PyErr_Occurred())) goto bad; + } + #endif + if (found) { + if (unlikely(found < 0)) goto bad; + values[name-argnames] = value; + extracted++; + } + name++; + } + if (num_kwargs > extracted) { + if (ignore_unknown_kwargs) { + if (unlikely(__Pyx_ValidateDuplicatePosArgs(kwds, argnames, first_kw_arg, function_name) == -1)) + goto bad; + } else { + __Pyx_RejectUnknownKeyword(kwds, argnames, first_kw_arg, function_name); + goto bad; + } + } + return 0; +bad: + return -1; +} +static int __Pyx_ParseKeywordDictToDict( + PyObject *kwds, + PyObject ** const argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + const char* function_name) +{ + PyObject** const *name; + PyObject** const *first_kw_arg = argnames + num_pos_args; + Py_ssize_t len; +#if !CYTHON_COMPILING_IN_PYPY || defined(PyArg_ValidateKeywordArguments) + if (unlikely(!PyArg_ValidateKeywordArguments(kwds))) return -1; +#endif + if (PyDict_Update(kwds2, kwds) < 0) goto bad; + name = first_kw_arg; + while (*name) { + PyObject *key = **name; + PyObject *value; +#if !CYTHON_COMPILING_IN_LIMITED_API && (PY_VERSION_HEX >= 0x030d00A2 || defined(PyDict_Pop)) + int found = PyDict_Pop(kwds2, key, &value); + if (found) { + if (unlikely(found < 0)) goto bad; + values[name-argnames] = value; + } +#elif __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + int found = PyDict_GetItemRef(kwds2, key, &value); + if (found) { + if (unlikely(found < 0)) goto bad; + values[name-argnames] = value; + if (unlikely(PyDict_DelItem(kwds2, key) < 0)) goto bad; + } +#else + #if CYTHON_COMPILING_IN_CPYTHON + value = _PyDict_Pop(kwds2, key, kwds2); + #else + value = __Pyx_CallUnboundCMethod2(&__pyx_mstate_global->__pyx_umethod_PyDict_Type_pop, kwds2, key, kwds2); + #endif + if (value == kwds2) { + Py_DECREF(value); + } else { + if (unlikely(!value)) goto bad; + values[name-argnames] = value; + } +#endif + name++; + } + len = PyDict_Size(kwds2); + if (len > 0) { + return __Pyx_ValidateDuplicatePosArgs(kwds, argnames, first_kw_arg, function_name); + } else if (unlikely(len == -1)) { + goto bad; + } + return 0; +bad: + return -1; +} +static int __Pyx_ParseKeywordsTuple( + PyObject *kwds, + PyObject * const *kwvalues, + PyObject ** const argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + Py_ssize_t num_kwargs, + const char* function_name, + int ignore_unknown_kwargs) +{ + PyObject *key = NULL; + PyObject** const * name; + PyObject** const *first_kw_arg = argnames + num_pos_args; + for (Py_ssize_t pos = 0; pos < num_kwargs; pos++) { +#if CYTHON_AVOID_BORROWED_REFS + key = __Pyx_PySequence_ITEM(kwds, pos); +#else + key = __Pyx_PyTuple_GET_ITEM(kwds, pos); +#endif +#if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(!key)) goto bad; +#endif + name = first_kw_arg; + while (*name && (**name != key)) name++; + if (*name) { + PyObject *value = kwvalues[pos]; + values[name-argnames] = __Pyx_NewRef(value); + } else { + size_t index_found = 0; + int cmp = __Pyx_MatchKeywordArg(key, argnames, first_kw_arg, &index_found, function_name); + if (cmp == 1) { + PyObject *value = kwvalues[pos]; + values[index_found] = __Pyx_NewRef(value); + } else { + if (unlikely(cmp == -1)) goto bad; + if (kwds2) { + PyObject *value = kwvalues[pos]; + if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; + } else if (!ignore_unknown_kwargs) { + goto invalid_keyword; + } + } + } + #if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(key); + key = NULL; + #endif + } + return 0; +invalid_keyword: + PyErr_Format(PyExc_TypeError, + "%s() got an unexpected keyword argument '%U'", + function_name, key); + goto bad; +bad: + #if CYTHON_AVOID_BORROWED_REFS + Py_XDECREF(key); + #endif + return -1; +} + +/* ParseKeywords */ +static int __Pyx_ParseKeywords( + PyObject *kwds, + PyObject * const *kwvalues, + PyObject ** const argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + Py_ssize_t num_kwargs, + const char* function_name, + int ignore_unknown_kwargs) +{ + if (CYTHON_METH_FASTCALL && likely(PyTuple_Check(kwds))) + return __Pyx_ParseKeywordsTuple(kwds, kwvalues, argnames, kwds2, values, num_pos_args, num_kwargs, function_name, ignore_unknown_kwargs); + else if (kwds2) + return __Pyx_ParseKeywordDictToDict(kwds, argnames, kwds2, values, num_pos_args, function_name); + else + return __Pyx_ParseKeywordDict(kwds, argnames, values, num_pos_args, num_kwargs, function_name, ignore_unknown_kwargs); +} + +/* RaiseArgTupleInvalid */ +static void __Pyx_RaiseArgtupleInvalid( + const char* func_name, + int exact, + Py_ssize_t num_min, + Py_ssize_t num_max, + Py_ssize_t num_found) +{ + Py_ssize_t num_expected; + const char *more_or_less; + if (num_found < num_min) { + num_expected = num_min; + more_or_less = "at least"; + } else { + num_expected = num_max; + more_or_less = "at most"; + } + if (exact) { + more_or_less = "exactly"; + } + PyErr_Format(PyExc_TypeError, + "%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)", + func_name, more_or_less, num_expected, + (num_expected == 1) ? "" : "s", num_found); +} + +/* RaiseException */ +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { + PyObject* owned_instance = NULL; + if (tb == Py_None) { + tb = 0; + } else if (tb && !PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto bad; + } + if (value == Py_None) + value = 0; + if (PyExceptionInstance_Check(type)) { + if (value) { + PyErr_SetString(PyExc_TypeError, + "instance exception may not have a separate value"); + goto bad; + } + value = type; + type = (PyObject*) Py_TYPE(value); + } else if (PyExceptionClass_Check(type)) { + PyObject *instance_class = NULL; + if (value && PyExceptionInstance_Check(value)) { + instance_class = (PyObject*) Py_TYPE(value); + if (instance_class != type) { + int is_subclass = PyObject_IsSubclass(instance_class, type); + if (!is_subclass) { + instance_class = NULL; + } else if (unlikely(is_subclass == -1)) { + goto bad; + } else { + type = instance_class; + } + } + } + if (!instance_class) { + PyObject *args; + if (!value) + args = PyTuple_New(0); + else if (PyTuple_Check(value)) { + Py_INCREF(value); + args = value; + } else + args = PyTuple_Pack(1, value); + if (!args) + goto bad; + owned_instance = PyObject_Call(type, args, NULL); + Py_DECREF(args); + if (!owned_instance) + goto bad; + value = owned_instance; + if (!PyExceptionInstance_Check(value)) { + PyErr_Format(PyExc_TypeError, + "calling %R should have returned an instance of " + "BaseException, not %R", + type, Py_TYPE(value)); + goto bad; + } + } + } else { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto bad; + } + if (cause) { + PyObject *fixed_cause; + if (cause == Py_None) { + fixed_cause = NULL; + } else if (PyExceptionClass_Check(cause)) { + fixed_cause = PyObject_CallObject(cause, NULL); + if (fixed_cause == NULL) + goto bad; + } else if (PyExceptionInstance_Check(cause)) { + fixed_cause = cause; + Py_INCREF(fixed_cause); + } else { + PyErr_SetString(PyExc_TypeError, + "exception causes must derive from " + "BaseException"); + goto bad; + } + PyException_SetCause(value, fixed_cause); + } + PyErr_SetObject(type, value); + if (tb) { +#if PY_VERSION_HEX >= 0x030C00A6 + PyException_SetTraceback(value, tb); +#elif CYTHON_FAST_THREAD_STATE + PyThreadState *tstate = __Pyx_PyThreadState_Current; + PyObject* tmp_tb = tstate->curexc_traceback; + if (tb != tmp_tb) { + Py_INCREF(tb); + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_tb); + } +#else + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyErr_Fetch(&tmp_type, &tmp_value, &tmp_tb); + Py_INCREF(tb); + PyErr_Restore(tmp_type, tmp_value, tb); + Py_XDECREF(tmp_tb); +#endif + } +bad: + Py_XDECREF(owned_instance); + return; +} + +/* RejectKeywords */ +static void __Pyx_RejectKeywords(const char* function_name, PyObject *kwds) { + PyObject *key = NULL; + if (CYTHON_METH_FASTCALL && likely(PyTuple_Check(kwds))) { + key = __Pyx_PySequence_ITEM(kwds, 0); + } else { +#if CYTHON_AVOID_BORROWED_REFS + PyObject *pos = NULL; +#else + Py_ssize_t pos = 0; +#endif +#if !CYTHON_COMPILING_IN_PYPY || defined(PyArg_ValidateKeywordArguments) + if (unlikely(!PyArg_ValidateKeywordArguments(kwds))) return; +#endif + __Pyx_PyDict_NextRef(kwds, &pos, &key, NULL); +#if CYTHON_AVOID_BORROWED_REFS + Py_XDECREF(pos); +#endif + } + if (likely(key)) { + PyErr_Format(PyExc_TypeError, + "%s() got an unexpected keyword argument '%U'", + function_name, key); + Py_DECREF(key); + } +} + +/* PyObjectFastCallMethod */ +#if !CYTHON_VECTORCALL || PY_VERSION_HEX < 0x03090000 +static PyObject *__Pyx_PyObject_FastCallMethod(PyObject *name, PyObject *const *args, size_t nargsf) { + PyObject *result; + PyObject *attr = PyObject_GetAttr(args[0], name); + if (unlikely(!attr)) + return NULL; + result = __Pyx_PyObject_FastCall(attr, args+1, nargsf - 1); + Py_DECREF(attr); + return result; +} +#endif + +/* ArgTypeTestFunc (used by ArgTypeTest) */ +static int __Pyx__ArgTypeTest(PyObject *obj, PyTypeObject *type, const char *name, int exact) +{ + __Pyx_TypeName type_name; + __Pyx_TypeName obj_type_name; + PyObject *extra_info = __pyx_mstate_global->__pyx_empty_unicode; + int from_annotation_subclass = 0; + if (unlikely(!type)) { + PyErr_SetString(PyExc_SystemError, "Missing type object"); + return 0; + } + else if (!exact) { + if (likely(__Pyx_TypeCheck(obj, type))) return 1; + } else if (exact == 2) { + if (__Pyx_TypeCheck(obj, type)) { + from_annotation_subclass = 1; + extra_info = __pyx_mstate_global->__pyx_kp_u_Note_that_Cython_is_deliberately; + } + } + type_name = __Pyx_PyType_GetFullyQualifiedName(type); + obj_type_name = __Pyx_PyType_GetFullyQualifiedName(Py_TYPE(obj)); + PyErr_Format(PyExc_TypeError, + "Argument '%.200s' has incorrect type (expected " __Pyx_FMT_TYPENAME + ", got " __Pyx_FMT_TYPENAME ")" +#if __PYX_LIMITED_VERSION_HEX < 0x030C0000 + "%s%U" +#endif + , name, type_name, obj_type_name +#if __PYX_LIMITED_VERSION_HEX < 0x030C0000 + , (from_annotation_subclass ? ". " : ""), extra_info +#endif + ); +#if __PYX_LIMITED_VERSION_HEX >= 0x030C0000 + if (exact == 2 && from_annotation_subclass) { + PyObject *res; + PyObject *vargs[2]; + vargs[0] = PyErr_GetRaisedException(); + vargs[1] = extra_info; + res = PyObject_VectorcallMethod(__pyx_mstate_global->__pyx_kp_u_add_note, vargs, 2, NULL); + Py_XDECREF(res); + PyErr_SetRaisedException(vargs[0]); + } +#endif + __Pyx_DECREF_TypeName(type_name); + __Pyx_DECREF_TypeName(obj_type_name); + return 0; +} + +/* PyDictVersioning (used by GetModuleGlobalName) */ +#if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_TYPE_SLOTS +static CYTHON_INLINE PY_UINT64_T __Pyx_get_tp_dict_version(PyObject *obj) { + PyObject *dict = Py_TYPE(obj)->tp_dict; + return likely(dict) ? __PYX_GET_DICT_VERSION(dict) : 0; +} +static CYTHON_INLINE PY_UINT64_T __Pyx_get_object_dict_version(PyObject *obj) { + PyObject **dictptr = NULL; + Py_ssize_t offset = Py_TYPE(obj)->tp_dictoffset; + if (offset) { +#if CYTHON_COMPILING_IN_CPYTHON + dictptr = (likely(offset > 0)) ? (PyObject **) ((char *)obj + offset) : _PyObject_GetDictPtr(obj); +#else + dictptr = _PyObject_GetDictPtr(obj); +#endif + } + return (dictptr && *dictptr) ? __PYX_GET_DICT_VERSION(*dictptr) : 0; +} +static CYTHON_INLINE int __Pyx_object_dict_version_matches(PyObject* obj, PY_UINT64_T tp_dict_version, PY_UINT64_T obj_dict_version) { + PyObject *dict = Py_TYPE(obj)->tp_dict; + if (unlikely(!dict) || unlikely(tp_dict_version != __PYX_GET_DICT_VERSION(dict))) + return 0; + return obj_dict_version == __Pyx_get_object_dict_version(obj); +} +#endif + +/* GetModuleGlobalName */ +#if CYTHON_USE_DICT_VERSIONS +static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_version, PyObject **dict_cached_value) +#else +static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name) +#endif +{ + PyObject *result; +#if CYTHON_COMPILING_IN_LIMITED_API + if (unlikely(!__pyx_m)) { + if (!PyErr_Occurred()) + PyErr_SetNone(PyExc_NameError); + return NULL; + } + result = PyObject_GetAttr(__pyx_m, name); + if (likely(result)) { + return result; + } + PyErr_Clear(); +#elif CYTHON_AVOID_BORROWED_REFS || CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + if (unlikely(__Pyx_PyDict_GetItemRef(__pyx_mstate_global->__pyx_d, name, &result) == -1)) PyErr_Clear(); + __PYX_UPDATE_DICT_CACHE(__pyx_mstate_global->__pyx_d, result, *dict_cached_value, *dict_version) + if (likely(result)) { + return result; + } +#else + result = _PyDict_GetItem_KnownHash(__pyx_mstate_global->__pyx_d, name, ((PyASCIIObject *) name)->hash); + __PYX_UPDATE_DICT_CACHE(__pyx_mstate_global->__pyx_d, result, *dict_cached_value, *dict_version) + if (likely(result)) { + return __Pyx_NewRef(result); + } + PyErr_Clear(); +#endif + return __Pyx_GetBuiltinName(name); +} + +/* GetAttr3 */ +#if __PYX_LIMITED_VERSION_HEX < 0x030d0000 +static PyObject *__Pyx_GetAttr3Default(PyObject *d) { + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + if (unlikely(!__Pyx_PyErr_ExceptionMatches(PyExc_AttributeError))) + return NULL; + __Pyx_PyErr_Clear(); + Py_INCREF(d); + return d; +} +#endif +static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *o, PyObject *n, PyObject *d) { + PyObject *r; +#if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + int res = PyObject_GetOptionalAttr(o, n, &r); + return (res != 0) ? r : __Pyx_NewRef(d); +#else + #if CYTHON_USE_TYPE_SLOTS + if (likely(PyUnicode_Check(n))) { + r = __Pyx_PyObject_GetAttrStrNoError(o, n); + if (unlikely(!r) && likely(!PyErr_Occurred())) { + r = __Pyx_NewRef(d); + } + return r; + } + #endif + r = PyObject_GetAttr(o, n); + return (likely(r)) ? r : __Pyx_GetAttr3Default(d); +#endif +} + +/* RaiseUnexpectedTypeError */ +static int +__Pyx_RaiseUnexpectedTypeError(const char *expected, PyObject *obj) +{ + __Pyx_TypeName obj_type_name = __Pyx_PyType_GetFullyQualifiedName(Py_TYPE(obj)); + PyErr_Format(PyExc_TypeError, "Expected %s, got " __Pyx_FMT_TYPENAME, + expected, obj_type_name); + __Pyx_DECREF_TypeName(obj_type_name); + return 0; +} + +/* GetItemInt */ +static PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) { + PyObject *r; + if (unlikely(!j)) return NULL; + r = PyObject_GetItem(o, j); + Py_DECREF(j); + return r; +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck, int unsafe_shared) { + CYTHON_MAYBE_UNUSED_VAR(unsafe_shared); +#if CYTHON_ASSUME_SAFE_SIZE + Py_ssize_t wrapped_i = i; + if (wraparound & unlikely(i < 0)) { + wrapped_i += PyList_GET_SIZE(o); + } + if ((CYTHON_AVOID_BORROWED_REFS || CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS || !CYTHON_ASSUME_SAFE_MACROS)) { + return __Pyx_PyList_GetItemRefFast(o, wrapped_i, unsafe_shared); + } else + if ((!boundscheck) || likely(__Pyx_is_valid_index(wrapped_i, PyList_GET_SIZE(o)))) { + return __Pyx_NewRef(PyList_GET_ITEM(o, wrapped_i)); + } + return __Pyx_GetItemInt_Generic(o, PyLong_FromSsize_t(i)); +#else + (void)wraparound; + (void)boundscheck; + return PySequence_GetItem(o, i); +#endif +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck, int unsafe_shared) { + CYTHON_MAYBE_UNUSED_VAR(unsafe_shared); +#if CYTHON_ASSUME_SAFE_SIZE && CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + Py_ssize_t wrapped_i = i; + if (wraparound & unlikely(i < 0)) { + wrapped_i += PyTuple_GET_SIZE(o); + } + if ((!boundscheck) || likely(__Pyx_is_valid_index(wrapped_i, PyTuple_GET_SIZE(o)))) { + return __Pyx_NewRef(PyTuple_GET_ITEM(o, wrapped_i)); + } + return __Pyx_GetItemInt_Generic(o, PyLong_FromSsize_t(i)); +#else + (void)wraparound; + (void)boundscheck; + return PySequence_GetItem(o, i); +#endif +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, int is_list, + int wraparound, int boundscheck, int unsafe_shared) { + CYTHON_MAYBE_UNUSED_VAR(unsafe_shared); +#if CYTHON_ASSUME_SAFE_MACROS && CYTHON_ASSUME_SAFE_SIZE + if (is_list || PyList_CheckExact(o)) { + Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyList_GET_SIZE(o); + if ((CYTHON_AVOID_BORROWED_REFS || CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS)) { + return __Pyx_PyList_GetItemRefFast(o, n, unsafe_shared); + } else if ((!boundscheck) || (likely(__Pyx_is_valid_index(n, PyList_GET_SIZE(o))))) { + return __Pyx_NewRef(PyList_GET_ITEM(o, n)); + } + } else + #if !CYTHON_AVOID_BORROWED_REFS + if (PyTuple_CheckExact(o)) { + Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyTuple_GET_SIZE(o); + if ((!boundscheck) || likely(__Pyx_is_valid_index(n, PyTuple_GET_SIZE(o)))) { + return __Pyx_NewRef(PyTuple_GET_ITEM(o, n)); + } + } else + #endif +#endif +#if CYTHON_USE_TYPE_SLOTS && !CYTHON_COMPILING_IN_PYPY + { + PyMappingMethods *mm = Py_TYPE(o)->tp_as_mapping; + PySequenceMethods *sm = Py_TYPE(o)->tp_as_sequence; + if (!is_list && mm && mm->mp_subscript) { + PyObject *r, *key = PyLong_FromSsize_t(i); + if (unlikely(!key)) return NULL; + r = mm->mp_subscript(o, key); + Py_DECREF(key); + return r; + } + if (is_list || likely(sm && sm->sq_item)) { + if (wraparound && unlikely(i < 0) && likely(sm->sq_length)) { + Py_ssize_t l = sm->sq_length(o); + if (likely(l >= 0)) { + i += l; + } else { + if (!PyErr_ExceptionMatches(PyExc_OverflowError)) + return NULL; + PyErr_Clear(); + } + } + return sm->sq_item(o, i); + } + } +#else + if (is_list || !PyMapping_Check(o)) { + return PySequence_GetItem(o, i); + } +#endif + (void)wraparound; + (void)boundscheck; + return __Pyx_GetItemInt_Generic(o, PyLong_FromSsize_t(i)); +} + +/* ExtTypeTest */ +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { + __Pyx_TypeName obj_type_name; + __Pyx_TypeName type_name; + if (unlikely(!type)) { + PyErr_SetString(PyExc_SystemError, "Missing type object"); + return 0; + } + if (likely(__Pyx_TypeCheck(obj, type))) + return 1; + obj_type_name = __Pyx_PyType_GetFullyQualifiedName(Py_TYPE(obj)); + type_name = __Pyx_PyType_GetFullyQualifiedName(type); + PyErr_Format(PyExc_TypeError, + "Cannot convert " __Pyx_FMT_TYPENAME " to " __Pyx_FMT_TYPENAME, + obj_type_name, type_name); + __Pyx_DECREF_TypeName(obj_type_name); + __Pyx_DECREF_TypeName(type_name); + return 0; +} + +/* CallNextTpDealloc */ +static void __Pyx_call_next_tp_dealloc(PyObject* obj, destructor current_tp_dealloc) { + PyTypeObject* type = Py_TYPE(obj); + destructor tp_dealloc = NULL; + while (type && __Pyx_PyType_GetSlot(type, tp_dealloc, destructor) != current_tp_dealloc) + type = __Pyx_PyType_GetSlot(type, tp_base, PyTypeObject*); + while (type && (tp_dealloc = __Pyx_PyType_GetSlot(type, tp_dealloc, destructor)) == current_tp_dealloc) + type = __Pyx_PyType_GetSlot(type, tp_base, PyTypeObject*); + if (type) + tp_dealloc(obj); +} + +/* CallNextTpTraverse */ +static int __Pyx_call_next_tp_traverse(PyObject* obj, visitproc v, void *a, traverseproc current_tp_traverse) { + PyTypeObject* type = Py_TYPE(obj); + traverseproc tp_traverse = NULL; + while (type && __Pyx_PyType_GetSlot(type, tp_traverse, traverseproc) != current_tp_traverse) + type = __Pyx_PyType_GetSlot(type, tp_base, PyTypeObject*); + while (type && (tp_traverse = __Pyx_PyType_GetSlot(type, tp_traverse, traverseproc)) == current_tp_traverse) + type = __Pyx_PyType_GetSlot(type, tp_base, PyTypeObject*); + if (type && tp_traverse) + return tp_traverse(obj, v, a); + return 0; +} + +/* CallTypeTraverse */ +#if !CYTHON_USE_TYPE_SPECS || (!CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x03090000) +#else +static int __Pyx_call_type_traverse(PyObject *o, int always_call, visitproc visit, void *arg) { + #if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x03090000 + if (__Pyx_get_runtime_version() < 0x03090000) return 0; + #endif + if (!always_call) { + PyTypeObject *base = __Pyx_PyObject_GetSlot(o, tp_base, PyTypeObject*); + unsigned long flags = PyType_GetFlags(base); + if (flags & Py_TPFLAGS_HEAPTYPE) { + return 0; + } + } + Py_VISIT((PyObject*)Py_TYPE(o)); + return 0; +} +#endif + +/* CallNextTpClear */ +static void __Pyx_call_next_tp_clear(PyObject* obj, inquiry current_tp_clear) { + PyTypeObject* type = Py_TYPE(obj); + inquiry tp_clear = NULL; + while (type && __Pyx_PyType_GetSlot(type, tp_clear, inquiry) != current_tp_clear) + type = __Pyx_PyType_GetSlot(type, tp_base, PyTypeObject*); + while (type && (tp_clear = __Pyx_PyType_GetSlot(type, tp_clear, inquiry)) == current_tp_clear) + type = __Pyx_PyType_GetSlot(type, tp_base, PyTypeObject*); + if (type && tp_clear) + tp_clear(obj); +} + +/* TypeImport */ +#ifndef __PYX_HAVE_RT_ImportType_3_2_4 +#define __PYX_HAVE_RT_ImportType_3_2_4 +static PyTypeObject *__Pyx_ImportType_3_2_4(PyObject *module, const char *module_name, const char *class_name, + size_t size, size_t alignment, enum __Pyx_ImportType_CheckSize_3_2_4 check_size) +{ + PyObject *result = 0; + Py_ssize_t basicsize; + Py_ssize_t itemsize; +#if defined(Py_LIMITED_API) || (defined(CYTHON_COMPILING_IN_LIMITED_API) && CYTHON_COMPILING_IN_LIMITED_API) + PyObject *py_basicsize; + PyObject *py_itemsize; +#endif + result = PyObject_GetAttrString(module, class_name); + if (!result) + goto bad; + if (!PyType_Check(result)) { + PyErr_Format(PyExc_TypeError, + "%.200s.%.200s is not a type object", + module_name, class_name); + goto bad; + } +#if !( defined(Py_LIMITED_API) || (defined(CYTHON_COMPILING_IN_LIMITED_API) && CYTHON_COMPILING_IN_LIMITED_API) ) + basicsize = ((PyTypeObject *)result)->tp_basicsize; + itemsize = ((PyTypeObject *)result)->tp_itemsize; +#else + if (size == 0) { + return (PyTypeObject *)result; + } + py_basicsize = PyObject_GetAttrString(result, "__basicsize__"); + if (!py_basicsize) + goto bad; + basicsize = PyLong_AsSsize_t(py_basicsize); + Py_DECREF(py_basicsize); + py_basicsize = 0; + if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred()) + goto bad; + py_itemsize = PyObject_GetAttrString(result, "__itemsize__"); + if (!py_itemsize) + goto bad; + itemsize = PyLong_AsSsize_t(py_itemsize); + Py_DECREF(py_itemsize); + py_itemsize = 0; + if (itemsize == (Py_ssize_t)-1 && PyErr_Occurred()) + goto bad; +#endif + if (itemsize) { + if (size % alignment) { + alignment = size % alignment; + } + if (itemsize < (Py_ssize_t)alignment) + itemsize = (Py_ssize_t)alignment; + } + if ((size_t)(basicsize + itemsize) < size) { + PyErr_Format(PyExc_ValueError, + "%.200s.%.200s size changed, may indicate binary incompatibility. " + "Expected %zd from C header, got %zd from PyObject", + module_name, class_name, size, basicsize+itemsize); + goto bad; + } + if (check_size == __Pyx_ImportType_CheckSize_Error_3_2_4 && + ((size_t)basicsize > size || (size_t)(basicsize + itemsize) < size)) { + PyErr_Format(PyExc_ValueError, + "%.200s.%.200s size changed, may indicate binary incompatibility. " + "Expected %zd from C header, got %zd-%zd from PyObject", + module_name, class_name, size, basicsize, basicsize+itemsize); + goto bad; + } + else if (check_size == __Pyx_ImportType_CheckSize_Warn_3_2_4 && (size_t)basicsize > size) { + if (PyErr_WarnFormat(NULL, 0, + "%.200s.%.200s size changed, may indicate binary incompatibility. " + "Expected %zd from C header, got %zd from PyObject", + module_name, class_name, size, basicsize) < 0) { + goto bad; + } + } + return (PyTypeObject *)result; +bad: + Py_XDECREF(result); + return NULL; +} +#endif + +/* GetVTable */ +static void* __Pyx_GetVtable(PyTypeObject *type) { + void* ptr; +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *ob = PyObject_GetAttr((PyObject *)type, __pyx_mstate_global->__pyx_n_u_pyx_vtable); +#else + PyObject *ob = PyObject_GetItem(type->tp_dict, __pyx_mstate_global->__pyx_n_u_pyx_vtable); +#endif + if (!ob) + goto bad; + ptr = PyCapsule_GetPointer(ob, 0); + if (!ptr && !PyErr_Occurred()) + PyErr_SetString(PyExc_RuntimeError, "invalid vtable found for imported type"); + Py_DECREF(ob); + return ptr; +bad: + Py_XDECREF(ob); + return NULL; +} + +/* LimitedApiGetTypeDict (used by SetItemOnTypeDict) */ +#if CYTHON_COMPILING_IN_LIMITED_API +static Py_ssize_t __Pyx_GetTypeDictOffset(void) { + PyObject *tp_dictoffset_o; + Py_ssize_t tp_dictoffset; + tp_dictoffset_o = PyObject_GetAttrString((PyObject*)(&PyType_Type), "__dictoffset__"); + if (unlikely(!tp_dictoffset_o)) return -1; + tp_dictoffset = PyLong_AsSsize_t(tp_dictoffset_o); + Py_DECREF(tp_dictoffset_o); + if (unlikely(tp_dictoffset == 0)) { + PyErr_SetString( + PyExc_TypeError, + "'type' doesn't have a dictoffset"); + return -1; + } else if (unlikely(tp_dictoffset < 0)) { + PyErr_SetString( + PyExc_TypeError, + "'type' has an unexpected negative dictoffset. " + "Please report this as Cython bug"); + return -1; + } + return tp_dictoffset; +} +static PyObject *__Pyx_GetTypeDict(PyTypeObject *tp) { + static Py_ssize_t tp_dictoffset = 0; + if (unlikely(tp_dictoffset == 0)) { + tp_dictoffset = __Pyx_GetTypeDictOffset(); + if (unlikely(tp_dictoffset == -1 && PyErr_Occurred())) { + tp_dictoffset = 0; // try again next time? + return NULL; + } + } + return *(PyObject**)((char*)tp + tp_dictoffset); +} +#endif + +/* SetItemOnTypeDict (used by FixUpExtensionType) */ +static int __Pyx__SetItemOnTypeDict(PyTypeObject *tp, PyObject *k, PyObject *v) { + int result; + PyObject *tp_dict; +#if CYTHON_COMPILING_IN_LIMITED_API + tp_dict = __Pyx_GetTypeDict(tp); + if (unlikely(!tp_dict)) return -1; +#else + tp_dict = tp->tp_dict; +#endif + result = PyDict_SetItem(tp_dict, k, v); + if (likely(!result)) { + PyType_Modified(tp); + if (unlikely(PyObject_HasAttr(v, __pyx_mstate_global->__pyx_n_u_set_name))) { + PyObject *setNameResult = PyObject_CallMethodObjArgs(v, __pyx_mstate_global->__pyx_n_u_set_name, (PyObject *) tp, k, NULL); + if (!setNameResult) return -1; + Py_DECREF(setNameResult); + } + } + return result; +} + +/* FixUpExtensionType */ +static int __Pyx_fix_up_extension_type_from_spec(PyType_Spec *spec, PyTypeObject *type) { +#if __PYX_LIMITED_VERSION_HEX > 0x030900B1 + CYTHON_UNUSED_VAR(spec); + CYTHON_UNUSED_VAR(type); + CYTHON_UNUSED_VAR(__Pyx__SetItemOnTypeDict); +#else + const PyType_Slot *slot = spec->slots; + int changed = 0; +#if !CYTHON_COMPILING_IN_LIMITED_API + while (slot && slot->slot && slot->slot != Py_tp_members) + slot++; + if (slot && slot->slot == Py_tp_members) { +#if !CYTHON_COMPILING_IN_CPYTHON + const +#endif // !CYTHON_COMPILING_IN_CPYTHON) + PyMemberDef *memb = (PyMemberDef*) slot->pfunc; + while (memb && memb->name) { + if (memb->name[0] == '_' && memb->name[1] == '_') { + if (strcmp(memb->name, "__weaklistoffset__") == 0) { + assert(memb->type == T_PYSSIZET); + assert(memb->flags == READONLY); + type->tp_weaklistoffset = memb->offset; + changed = 1; + } + else if (strcmp(memb->name, "__dictoffset__") == 0) { + assert(memb->type == T_PYSSIZET); + assert(memb->flags == READONLY); + type->tp_dictoffset = memb->offset; + changed = 1; + } +#if CYTHON_METH_FASTCALL + else if (strcmp(memb->name, "__vectorcalloffset__") == 0) { + assert(memb->type == T_PYSSIZET); + assert(memb->flags == READONLY); + type->tp_vectorcall_offset = memb->offset; + changed = 1; + } +#endif // CYTHON_METH_FASTCALL +#if !CYTHON_COMPILING_IN_PYPY + else if (strcmp(memb->name, "__module__") == 0) { + PyObject *descr; + assert(memb->type == T_OBJECT); + assert(memb->flags == 0 || memb->flags == READONLY); + descr = PyDescr_NewMember(type, memb); + if (unlikely(!descr)) + return -1; + int set_item_result = PyDict_SetItem(type->tp_dict, PyDescr_NAME(descr), descr); + Py_DECREF(descr); + if (unlikely(set_item_result < 0)) { + return -1; + } + changed = 1; + } +#endif // !CYTHON_COMPILING_IN_PYPY + } + memb++; + } + } +#endif // !CYTHON_COMPILING_IN_LIMITED_API +#if !CYTHON_COMPILING_IN_PYPY + slot = spec->slots; + while (slot && slot->slot && slot->slot != Py_tp_getset) + slot++; + if (slot && slot->slot == Py_tp_getset) { + PyGetSetDef *getset = (PyGetSetDef*) slot->pfunc; + while (getset && getset->name) { + if (getset->name[0] == '_' && getset->name[1] == '_' && strcmp(getset->name, "__module__") == 0) { + PyObject *descr = PyDescr_NewGetSet(type, getset); + if (unlikely(!descr)) + return -1; + #if CYTHON_COMPILING_IN_LIMITED_API + PyObject *pyname = PyUnicode_FromString(getset->name); + if (unlikely(!pyname)) { + Py_DECREF(descr); + return -1; + } + int set_item_result = __Pyx_SetItemOnTypeDict(type, pyname, descr); + Py_DECREF(pyname); + #else + CYTHON_UNUSED_VAR(__Pyx__SetItemOnTypeDict); + int set_item_result = PyDict_SetItem(type->tp_dict, PyDescr_NAME(descr), descr); + #endif + Py_DECREF(descr); + if (unlikely(set_item_result < 0)) { + return -1; + } + changed = 1; + } + ++getset; + } + } +#else + CYTHON_UNUSED_VAR(__Pyx__SetItemOnTypeDict); +#endif // !CYTHON_COMPILING_IN_PYPY + if (changed) + PyType_Modified(type); +#endif // PY_VERSION_HEX > 0x030900B1 + return 0; +} + +/* PyObjectCallNoArg (used by PyObjectCallMethod0) */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func) { + PyObject *arg[2] = {NULL, NULL}; + return __Pyx_PyObject_FastCall(func, arg + 1, 0 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET); +} + +/* PyObjectGetMethod (used by PyObjectCallMethod0) */ +#if !(CYTHON_VECTORCALL && (__PYX_LIMITED_VERSION_HEX >= 0x030C0000 || (!CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x03090000))) +static int __Pyx_PyObject_GetMethod(PyObject *obj, PyObject *name, PyObject **method) { + PyObject *attr; +#if CYTHON_UNPACK_METHODS && CYTHON_COMPILING_IN_CPYTHON && CYTHON_USE_PYTYPE_LOOKUP + __Pyx_TypeName type_name; + PyTypeObject *tp = Py_TYPE(obj); + PyObject *descr; + descrgetfunc f = NULL; + PyObject **dictptr, *dict; + int meth_found = 0; + assert (*method == NULL); + if (unlikely(tp->tp_getattro != PyObject_GenericGetAttr)) { + attr = __Pyx_PyObject_GetAttrStr(obj, name); + goto try_unpack; + } + if (unlikely(tp->tp_dict == NULL) && unlikely(PyType_Ready(tp) < 0)) { + return 0; + } + descr = _PyType_Lookup(tp, name); + if (likely(descr != NULL)) { + Py_INCREF(descr); +#if defined(Py_TPFLAGS_METHOD_DESCRIPTOR) && Py_TPFLAGS_METHOD_DESCRIPTOR + if (__Pyx_PyType_HasFeature(Py_TYPE(descr), Py_TPFLAGS_METHOD_DESCRIPTOR)) +#else + #ifdef __Pyx_CyFunction_USED + if (likely(PyFunction_Check(descr) || __Pyx_IS_TYPE(descr, &PyMethodDescr_Type) || __Pyx_CyFunction_Check(descr))) + #else + if (likely(PyFunction_Check(descr) || __Pyx_IS_TYPE(descr, &PyMethodDescr_Type))) + #endif +#endif + { + meth_found = 1; + } else { + f = Py_TYPE(descr)->tp_descr_get; + if (f != NULL && PyDescr_IsData(descr)) { + attr = f(descr, obj, (PyObject *)Py_TYPE(obj)); + Py_DECREF(descr); + goto try_unpack; + } + } + } + dictptr = _PyObject_GetDictPtr(obj); + if (dictptr != NULL && (dict = *dictptr) != NULL) { + Py_INCREF(dict); + attr = __Pyx_PyDict_GetItemStr(dict, name); + if (attr != NULL) { + Py_INCREF(attr); + Py_DECREF(dict); + Py_XDECREF(descr); + goto try_unpack; + } + Py_DECREF(dict); + } + if (meth_found) { + *method = descr; + return 1; + } + if (f != NULL) { + attr = f(descr, obj, (PyObject *)Py_TYPE(obj)); + Py_DECREF(descr); + goto try_unpack; + } + if (likely(descr != NULL)) { + *method = descr; + return 0; + } + type_name = __Pyx_PyType_GetFullyQualifiedName(tp); + PyErr_Format(PyExc_AttributeError, + "'" __Pyx_FMT_TYPENAME "' object has no attribute '%U'", + type_name, name); + __Pyx_DECREF_TypeName(type_name); + return 0; +#else + attr = __Pyx_PyObject_GetAttrStr(obj, name); + goto try_unpack; +#endif +try_unpack: +#if CYTHON_UNPACK_METHODS + if (likely(attr) && PyMethod_Check(attr) && likely(PyMethod_GET_SELF(attr) == obj)) { + PyObject *function = PyMethod_GET_FUNCTION(attr); + Py_INCREF(function); + Py_DECREF(attr); + *method = function; + return 1; + } +#endif + *method = attr; + return 0; +} +#endif + +/* PyObjectCallMethod0 (used by PyType_Ready) */ +static PyObject* __Pyx_PyObject_CallMethod0(PyObject* obj, PyObject* method_name) { +#if CYTHON_VECTORCALL && (__PYX_LIMITED_VERSION_HEX >= 0x030C0000 || (!CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x03090000)) + PyObject *args[1] = {obj}; + (void) __Pyx_PyObject_CallOneArg; + (void) __Pyx_PyObject_CallNoArg; + return PyObject_VectorcallMethod(method_name, args, 1 | PY_VECTORCALL_ARGUMENTS_OFFSET, NULL); +#else + PyObject *method = NULL, *result = NULL; + int is_method = __Pyx_PyObject_GetMethod(obj, method_name, &method); + if (likely(is_method)) { + result = __Pyx_PyObject_CallOneArg(method, obj); + Py_DECREF(method); + return result; + } + if (unlikely(!method)) goto bad; + result = __Pyx_PyObject_CallNoArg(method); + Py_DECREF(method); +bad: + return result; +#endif +} + +/* ValidateBasesTuple (used by PyType_Ready) */ +#if CYTHON_COMPILING_IN_CPYTHON || CYTHON_COMPILING_IN_LIMITED_API || CYTHON_USE_TYPE_SPECS +static int __Pyx_validate_bases_tuple(const char *type_name, Py_ssize_t dictoffset, PyObject *bases) { + Py_ssize_t i, n; +#if CYTHON_ASSUME_SAFE_SIZE + n = PyTuple_GET_SIZE(bases); +#else + n = PyTuple_Size(bases); + if (unlikely(n < 0)) return -1; +#endif + for (i = 1; i < n; i++) + { + PyTypeObject *b; +#if CYTHON_AVOID_BORROWED_REFS + PyObject *b0 = PySequence_GetItem(bases, i); + if (!b0) return -1; +#elif CYTHON_ASSUME_SAFE_MACROS + PyObject *b0 = PyTuple_GET_ITEM(bases, i); +#else + PyObject *b0 = PyTuple_GetItem(bases, i); + if (!b0) return -1; +#endif + b = (PyTypeObject*) b0; + if (!__Pyx_PyType_HasFeature(b, Py_TPFLAGS_HEAPTYPE)) + { + __Pyx_TypeName b_name = __Pyx_PyType_GetFullyQualifiedName(b); + PyErr_Format(PyExc_TypeError, + "base class '" __Pyx_FMT_TYPENAME "' is not a heap type", b_name); + __Pyx_DECREF_TypeName(b_name); +#if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(b0); +#endif + return -1; + } + if (dictoffset == 0) + { + Py_ssize_t b_dictoffset = 0; +#if CYTHON_USE_TYPE_SLOTS + b_dictoffset = b->tp_dictoffset; +#else + PyObject *py_b_dictoffset = PyObject_GetAttrString((PyObject*)b, "__dictoffset__"); + if (!py_b_dictoffset) goto dictoffset_return; + b_dictoffset = PyLong_AsSsize_t(py_b_dictoffset); + Py_DECREF(py_b_dictoffset); + if (b_dictoffset == -1 && PyErr_Occurred()) goto dictoffset_return; +#endif + if (b_dictoffset) { + { + __Pyx_TypeName b_name = __Pyx_PyType_GetFullyQualifiedName(b); + PyErr_Format(PyExc_TypeError, + "extension type '%.200s' has no __dict__ slot, " + "but base type '" __Pyx_FMT_TYPENAME "' has: " + "either add 'cdef dict __dict__' to the extension type " + "or add '__slots__ = [...]' to the base type", + type_name, b_name); + __Pyx_DECREF_TypeName(b_name); + } +#if !CYTHON_USE_TYPE_SLOTS + dictoffset_return: +#endif +#if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(b0); +#endif + return -1; + } + } +#if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(b0); +#endif + } + return 0; +} +#endif + +/* PyType_Ready */ +CYTHON_UNUSED static int __Pyx_PyType_HasMultipleInheritance(PyTypeObject *t) { + while (t) { + PyObject *bases = __Pyx_PyType_GetSlot(t, tp_bases, PyObject*); + if (bases) { + return 1; + } + t = __Pyx_PyType_GetSlot(t, tp_base, PyTypeObject*); + } + return 0; +} +static int __Pyx_PyType_Ready(PyTypeObject *t) { +#if CYTHON_USE_TYPE_SPECS || !CYTHON_COMPILING_IN_CPYTHON || defined(PYSTON_MAJOR_VERSION) + (void)__Pyx_PyObject_CallMethod0; +#if CYTHON_USE_TYPE_SPECS + (void)__Pyx_validate_bases_tuple; +#endif + return PyType_Ready(t); +#else + int r; + if (!__Pyx_PyType_HasMultipleInheritance(t)) { + return PyType_Ready(t); + } + PyObject *bases = __Pyx_PyType_GetSlot(t, tp_bases, PyObject*); + if (bases && unlikely(__Pyx_validate_bases_tuple(t->tp_name, t->tp_dictoffset, bases) == -1)) + return -1; +#if !defined(PYSTON_MAJOR_VERSION) + { + int gc_was_enabled; + #if PY_VERSION_HEX >= 0x030A00b1 + gc_was_enabled = PyGC_Disable(); + (void)__Pyx_PyObject_CallMethod0; + #else + PyObject *ret, *py_status; + PyObject *gc = NULL; + #if (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM+0 >= 0x07030400) &&\ + !CYTHON_COMPILING_IN_GRAAL + gc = PyImport_GetModule(__pyx_mstate_global->__pyx_kp_u_gc); + #endif + if (unlikely(!gc)) gc = PyImport_Import(__pyx_mstate_global->__pyx_kp_u_gc); + if (unlikely(!gc)) return -1; + py_status = __Pyx_PyObject_CallMethod0(gc, __pyx_mstate_global->__pyx_kp_u_isenabled); + if (unlikely(!py_status)) { + Py_DECREF(gc); + return -1; + } + gc_was_enabled = __Pyx_PyObject_IsTrue(py_status); + Py_DECREF(py_status); + if (gc_was_enabled > 0) { + ret = __Pyx_PyObject_CallMethod0(gc, __pyx_mstate_global->__pyx_kp_u_disable); + if (unlikely(!ret)) { + Py_DECREF(gc); + return -1; + } + Py_DECREF(ret); + } else if (unlikely(gc_was_enabled == -1)) { + Py_DECREF(gc); + return -1; + } + #endif + t->tp_flags |= Py_TPFLAGS_HEAPTYPE; +#if PY_VERSION_HEX >= 0x030A0000 + t->tp_flags |= Py_TPFLAGS_IMMUTABLETYPE; +#endif +#else + (void)__Pyx_PyObject_CallMethod0; +#endif + r = PyType_Ready(t); +#if !defined(PYSTON_MAJOR_VERSION) + t->tp_flags &= ~Py_TPFLAGS_HEAPTYPE; + #if PY_VERSION_HEX >= 0x030A00b1 + if (gc_was_enabled) + PyGC_Enable(); + #else + if (gc_was_enabled) { + PyObject *tp, *v, *tb; + PyErr_Fetch(&tp, &v, &tb); + ret = __Pyx_PyObject_CallMethod0(gc, __pyx_mstate_global->__pyx_kp_u_enable); + if (likely(ret || r == -1)) { + Py_XDECREF(ret); + PyErr_Restore(tp, v, tb); + } else { + Py_XDECREF(tp); + Py_XDECREF(v); + Py_XDECREF(tb); + r = -1; + } + } + Py_DECREF(gc); + #endif + } +#endif + return r; +#endif +} + +/* SetVTable */ +static int __Pyx_SetVtable(PyTypeObject *type, void *vtable) { + PyObject *ob = PyCapsule_New(vtable, 0, 0); + if (unlikely(!ob)) + goto bad; +#if CYTHON_COMPILING_IN_LIMITED_API + if (unlikely(PyObject_SetAttr((PyObject *) type, __pyx_mstate_global->__pyx_n_u_pyx_vtable, ob) < 0)) +#else + if (unlikely(PyDict_SetItem(type->tp_dict, __pyx_mstate_global->__pyx_n_u_pyx_vtable, ob) < 0)) +#endif + goto bad; + Py_DECREF(ob); + return 0; +bad: + Py_XDECREF(ob); + return -1; +} + +/* MergeVTables */ +static int __Pyx_MergeVtables(PyTypeObject *type) { + int i=0; + Py_ssize_t size; + void** base_vtables; + __Pyx_TypeName tp_base_name = NULL; + __Pyx_TypeName base_name = NULL; + void* unknown = (void*)-1; + PyObject* bases = __Pyx_PyType_GetSlot(type, tp_bases, PyObject*); + int base_depth = 0; + { + PyTypeObject* base = __Pyx_PyType_GetSlot(type, tp_base, PyTypeObject*); + while (base) { + base_depth += 1; + base = __Pyx_PyType_GetSlot(base, tp_base, PyTypeObject*); + } + } + base_vtables = (void**) PyMem_Malloc(sizeof(void*) * (size_t)(base_depth + 1)); + base_vtables[0] = unknown; +#if CYTHON_COMPILING_IN_LIMITED_API + size = PyTuple_Size(bases); + if (size < 0) goto other_failure; +#else + size = PyTuple_GET_SIZE(bases); +#endif + for (i = 1; i < size; i++) { + PyObject *basei; + void* base_vtable; +#if CYTHON_AVOID_BORROWED_REFS + basei = PySequence_GetItem(bases, i); + if (unlikely(!basei)) goto other_failure; +#elif !CYTHON_ASSUME_SAFE_MACROS + basei = PyTuple_GetItem(bases, i); + if (unlikely(!basei)) goto other_failure; +#else + basei = PyTuple_GET_ITEM(bases, i); +#endif + base_vtable = __Pyx_GetVtable((PyTypeObject*)basei); +#if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(basei); +#endif + if (base_vtable != NULL) { + int j; + PyTypeObject* base = __Pyx_PyType_GetSlot(type, tp_base, PyTypeObject*); + for (j = 0; j < base_depth; j++) { + if (base_vtables[j] == unknown) { + base_vtables[j] = __Pyx_GetVtable(base); + base_vtables[j + 1] = unknown; + } + if (base_vtables[j] == base_vtable) { + break; + } else if (base_vtables[j] == NULL) { + goto bad; + } + base = __Pyx_PyType_GetSlot(base, tp_base, PyTypeObject*); + } + } + } + PyErr_Clear(); + PyMem_Free(base_vtables); + return 0; +bad: + { + PyTypeObject* basei = NULL; + PyTypeObject* tp_base = __Pyx_PyType_GetSlot(type, tp_base, PyTypeObject*); + tp_base_name = __Pyx_PyType_GetFullyQualifiedName(tp_base); +#if CYTHON_AVOID_BORROWED_REFS + basei = (PyTypeObject*)PySequence_GetItem(bases, i); + if (unlikely(!basei)) goto really_bad; +#elif !CYTHON_ASSUME_SAFE_MACROS + basei = (PyTypeObject*)PyTuple_GetItem(bases, i); + if (unlikely(!basei)) goto really_bad; +#else + basei = (PyTypeObject*)PyTuple_GET_ITEM(bases, i); +#endif + base_name = __Pyx_PyType_GetFullyQualifiedName(basei); +#if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(basei); +#endif + } + PyErr_Format(PyExc_TypeError, + "multiple bases have vtable conflict: '" __Pyx_FMT_TYPENAME "' and '" __Pyx_FMT_TYPENAME "'", tp_base_name, base_name); +#if CYTHON_AVOID_BORROWED_REFS || !CYTHON_ASSUME_SAFE_MACROS +really_bad: // bad has failed! +#endif + __Pyx_DECREF_TypeName(tp_base_name); + __Pyx_DECREF_TypeName(base_name); +#if CYTHON_COMPILING_IN_LIMITED_API || CYTHON_AVOID_BORROWED_REFS || !CYTHON_ASSUME_SAFE_MACROS +other_failure: +#endif + PyMem_Free(base_vtables); + return -1; +} + +/* DelItemOnTypeDict (used by SetupReduce) */ +static int __Pyx__DelItemOnTypeDict(PyTypeObject *tp, PyObject *k) { + int result; + PyObject *tp_dict; +#if CYTHON_COMPILING_IN_LIMITED_API + tp_dict = __Pyx_GetTypeDict(tp); + if (unlikely(!tp_dict)) return -1; +#else + tp_dict = tp->tp_dict; +#endif + result = PyDict_DelItem(tp_dict, k); + if (likely(!result)) PyType_Modified(tp); + return result; +} + +/* SetupReduce */ +static int __Pyx_setup_reduce_is_named(PyObject* meth, PyObject* name) { + int ret; + PyObject *name_attr; + name_attr = __Pyx_PyObject_GetAttrStrNoError(meth, __pyx_mstate_global->__pyx_n_u_name); + if (likely(name_attr)) { + ret = PyObject_RichCompareBool(name_attr, name, Py_EQ); + } else { + ret = -1; + } + if (unlikely(ret < 0)) { + PyErr_Clear(); + ret = 0; + } + Py_XDECREF(name_attr); + return ret; +} +static int __Pyx_setup_reduce(PyObject* type_obj) { + int ret = 0; + PyObject *object_reduce = NULL; + PyObject *object_getstate = NULL; + PyObject *object_reduce_ex = NULL; + PyObject *reduce = NULL; + PyObject *reduce_ex = NULL; + PyObject *reduce_cython = NULL; + PyObject *setstate = NULL; + PyObject *setstate_cython = NULL; + PyObject *getstate = NULL; +#if CYTHON_USE_PYTYPE_LOOKUP + getstate = _PyType_Lookup((PyTypeObject*)type_obj, __pyx_mstate_global->__pyx_n_u_getstate); +#else + getstate = __Pyx_PyObject_GetAttrStrNoError(type_obj, __pyx_mstate_global->__pyx_n_u_getstate); + if (!getstate && PyErr_Occurred()) { + goto __PYX_BAD; + } +#endif + if (getstate) { +#if CYTHON_USE_PYTYPE_LOOKUP + object_getstate = _PyType_Lookup(&PyBaseObject_Type, __pyx_mstate_global->__pyx_n_u_getstate); +#else + object_getstate = __Pyx_PyObject_GetAttrStrNoError((PyObject*)&PyBaseObject_Type, __pyx_mstate_global->__pyx_n_u_getstate); + if (!object_getstate && PyErr_Occurred()) { + goto __PYX_BAD; + } +#endif + if (object_getstate != getstate) { + goto __PYX_GOOD; + } + } +#if CYTHON_USE_PYTYPE_LOOKUP + object_reduce_ex = _PyType_Lookup(&PyBaseObject_Type, __pyx_mstate_global->__pyx_n_u_reduce_ex); if (!object_reduce_ex) goto __PYX_BAD; +#else + object_reduce_ex = __Pyx_PyObject_GetAttrStr((PyObject*)&PyBaseObject_Type, __pyx_mstate_global->__pyx_n_u_reduce_ex); if (!object_reduce_ex) goto __PYX_BAD; +#endif + reduce_ex = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_mstate_global->__pyx_n_u_reduce_ex); if (unlikely(!reduce_ex)) goto __PYX_BAD; + if (reduce_ex == object_reduce_ex) { +#if CYTHON_USE_PYTYPE_LOOKUP + object_reduce = _PyType_Lookup(&PyBaseObject_Type, __pyx_mstate_global->__pyx_n_u_reduce); if (!object_reduce) goto __PYX_BAD; +#else + object_reduce = __Pyx_PyObject_GetAttrStr((PyObject*)&PyBaseObject_Type, __pyx_mstate_global->__pyx_n_u_reduce); if (!object_reduce) goto __PYX_BAD; +#endif + reduce = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_mstate_global->__pyx_n_u_reduce); if (unlikely(!reduce)) goto __PYX_BAD; + if (reduce == object_reduce || __Pyx_setup_reduce_is_named(reduce, __pyx_mstate_global->__pyx_n_u_reduce_cython)) { + reduce_cython = __Pyx_PyObject_GetAttrStrNoError(type_obj, __pyx_mstate_global->__pyx_n_u_reduce_cython); + if (likely(reduce_cython)) { + ret = __Pyx_SetItemOnTypeDict((PyTypeObject*)type_obj, __pyx_mstate_global->__pyx_n_u_reduce, reduce_cython); if (unlikely(ret < 0)) goto __PYX_BAD; + ret = __Pyx_DelItemOnTypeDict((PyTypeObject*)type_obj, __pyx_mstate_global->__pyx_n_u_reduce_cython); if (unlikely(ret < 0)) goto __PYX_BAD; + } else if (reduce == object_reduce || PyErr_Occurred()) { + goto __PYX_BAD; + } + setstate = __Pyx_PyObject_GetAttrStrNoError(type_obj, __pyx_mstate_global->__pyx_n_u_setstate); + if (!setstate) PyErr_Clear(); + if (!setstate || __Pyx_setup_reduce_is_named(setstate, __pyx_mstate_global->__pyx_n_u_setstate_cython)) { + setstate_cython = __Pyx_PyObject_GetAttrStrNoError(type_obj, __pyx_mstate_global->__pyx_n_u_setstate_cython); + if (likely(setstate_cython)) { + ret = __Pyx_SetItemOnTypeDict((PyTypeObject*)type_obj, __pyx_mstate_global->__pyx_n_u_setstate, setstate_cython); if (unlikely(ret < 0)) goto __PYX_BAD; + ret = __Pyx_DelItemOnTypeDict((PyTypeObject*)type_obj, __pyx_mstate_global->__pyx_n_u_setstate_cython); if (unlikely(ret < 0)) goto __PYX_BAD; + } else if (!setstate || PyErr_Occurred()) { + goto __PYX_BAD; + } + } + PyType_Modified((PyTypeObject*)type_obj); + } + } + goto __PYX_GOOD; +__PYX_BAD: + if (!PyErr_Occurred()) { + __Pyx_TypeName type_obj_name = + __Pyx_PyType_GetFullyQualifiedName((PyTypeObject*)type_obj); + PyErr_Format(PyExc_RuntimeError, + "Unable to initialize pickling for " __Pyx_FMT_TYPENAME, type_obj_name); + __Pyx_DECREF_TypeName(type_obj_name); + } + ret = -1; +__PYX_GOOD: +#if !CYTHON_USE_PYTYPE_LOOKUP + Py_XDECREF(object_reduce); + Py_XDECREF(object_reduce_ex); + Py_XDECREF(object_getstate); + Py_XDECREF(getstate); +#endif + Py_XDECREF(reduce); + Py_XDECREF(reduce_ex); + Py_XDECREF(reduce_cython); + Py_XDECREF(setstate); + Py_XDECREF(setstate_cython); + return ret; +} + +/* HasAttr (used by ImportImpl) */ +#if __PYX_LIMITED_VERSION_HEX < 0x030d0000 +static CYTHON_INLINE int __Pyx_HasAttr(PyObject *o, PyObject *n) { + PyObject *r; + if (unlikely(!PyUnicode_Check(n))) { + PyErr_SetString(PyExc_TypeError, + "hasattr(): attribute name must be string"); + return -1; + } + r = __Pyx_PyObject_GetAttrStrNoError(o, n); + if (!r) { + return (unlikely(PyErr_Occurred())) ? -1 : 0; + } else { + Py_DECREF(r); + return 1; + } +} +#endif + +/* ImportImpl (used by Import) */ +static int __Pyx__Import_GetModule(PyObject *qualname, PyObject **module) { + PyObject *imported_module = PyImport_GetModule(qualname); + if (unlikely(!imported_module)) { + *module = NULL; + if (PyErr_Occurred()) { + return -1; + } + return 0; + } + *module = imported_module; + return 1; +} +static int __Pyx__Import_Lookup(PyObject *qualname, PyObject *const *imported_names, Py_ssize_t len_imported_names, PyObject **module) { + PyObject *imported_module; + PyObject *top_level_package_name; + Py_ssize_t i; + int status, module_found; + Py_ssize_t dot_index; + module_found = __Pyx__Import_GetModule(qualname, &imported_module); + if (unlikely(!module_found || module_found == -1)) { + *module = NULL; + return module_found; + } + if (imported_names) { + for (i = 0; i < len_imported_names; i++) { + PyObject *imported_name = imported_names[i]; +#if __PYX_LIMITED_VERSION_HEX < 0x030d0000 + int has_imported_attribute = PyObject_HasAttr(imported_module, imported_name); +#else + int has_imported_attribute = PyObject_HasAttrWithError(imported_module, imported_name); + if (unlikely(has_imported_attribute == -1)) goto error; +#endif + if (!has_imported_attribute) { + goto not_found; + } + } + *module = imported_module; + return 1; + } + dot_index = PyUnicode_FindChar(qualname, '.', 0, PY_SSIZE_T_MAX, 1); + if (dot_index == -1) { + *module = imported_module; + return 1; + } + if (unlikely(dot_index == -2)) goto error; + top_level_package_name = PyUnicode_Substring(qualname, 0, dot_index); + if (unlikely(!top_level_package_name)) goto error; + Py_DECREF(imported_module); + status = __Pyx__Import_GetModule(top_level_package_name, module); + Py_DECREF(top_level_package_name); + return status; +error: + Py_DECREF(imported_module); + *module = NULL; + return -1; +not_found: + Py_DECREF(imported_module); + *module = NULL; + return 0; +} +static PyObject *__Pyx__Import(PyObject *name, PyObject *const *imported_names, Py_ssize_t len_imported_names, PyObject *qualname, PyObject *moddict, int level) { + PyObject *module = 0; + PyObject *empty_dict = 0; + PyObject *from_list = 0; + int module_found; + if (!qualname) { + qualname = name; + } + module_found = __Pyx__Import_Lookup(qualname, imported_names, len_imported_names, &module); + if (likely(module_found == 1)) { + return module; + } else if (unlikely(module_found == -1)) { + return NULL; + } + empty_dict = PyDict_New(); + if (unlikely(!empty_dict)) + goto bad; + if (imported_names) { +#if CYTHON_COMPILING_IN_CPYTHON + from_list = __Pyx_PyList_FromArray(imported_names, len_imported_names); + if (unlikely(!from_list)) + goto bad; +#else + from_list = PyList_New(len_imported_names); + if (unlikely(!from_list)) goto bad; + for (Py_ssize_t i=0; i__pyx_d, level); +} + +/* ImportFrom */ +static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name) { + PyObject* value = __Pyx_PyObject_GetAttrStr(module, name); + if (unlikely(!value) && PyErr_ExceptionMatches(PyExc_AttributeError)) { + const char* module_name_str = 0; + PyObject* module_name = 0; + PyObject* module_dot = 0; + PyObject* full_name = 0; + PyErr_Clear(); + module_name_str = PyModule_GetName(module); + if (unlikely(!module_name_str)) { goto modbad; } + module_name = PyUnicode_FromString(module_name_str); + if (unlikely(!module_name)) { goto modbad; } + module_dot = PyUnicode_Concat(module_name, __pyx_mstate_global->__pyx_kp_u__3); + if (unlikely(!module_dot)) { goto modbad; } + full_name = PyUnicode_Concat(module_dot, name); + if (unlikely(!full_name)) { goto modbad; } + #if (CYTHON_COMPILING_IN_PYPY && PYPY_VERSION_NUM < 0x07030400) ||\ + CYTHON_COMPILING_IN_GRAAL + { + PyObject *modules = PyImport_GetModuleDict(); + if (unlikely(!modules)) + goto modbad; + value = PyObject_GetItem(modules, full_name); + } + #else + value = PyImport_GetModule(full_name); + #endif + modbad: + Py_XDECREF(full_name); + Py_XDECREF(module_dot); + Py_XDECREF(module_name); + } + if (unlikely(!value)) { + PyErr_Format(PyExc_ImportError, "cannot import name %S", name); + } + return value; +} + +/* dict_setdefault (used by FetchCommonType) */ +static CYTHON_INLINE PyObject *__Pyx_PyDict_SetDefault(PyObject *d, PyObject *key, PyObject *default_value) { + PyObject* value; +#if __PYX_LIMITED_VERSION_HEX >= 0x030F0000 || (!CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d00A4) + PyDict_SetDefaultRef(d, key, default_value, &value); +#elif CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX >= 0x030C0000 + PyObject *args[] = {d, key, default_value}; + value = PyObject_VectorcallMethod(__pyx_mstate_global->__pyx_n_u_setdefault, args, 3 | PY_VECTORCALL_ARGUMENTS_OFFSET, NULL); +#elif CYTHON_COMPILING_IN_LIMITED_API + value = PyObject_CallMethodObjArgs(d, __pyx_mstate_global->__pyx_n_u_setdefault, key, default_value, NULL); +#else + value = PyDict_SetDefault(d, key, default_value); + if (unlikely(!value)) return NULL; + Py_INCREF(value); +#endif + return value; +} + +/* AddModuleRef (used by FetchSharedCythonModule) */ +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + static PyObject *__Pyx_PyImport_AddModuleObjectRef(PyObject *name) { + PyObject *module_dict = PyImport_GetModuleDict(); + PyObject *m; + if (PyMapping_GetOptionalItem(module_dict, name, &m) < 0) { + return NULL; + } + if (m != NULL && PyModule_Check(m)) { + return m; + } + Py_XDECREF(m); + m = PyModule_NewObject(name); + if (m == NULL) + return NULL; + if (PyDict_CheckExact(module_dict)) { + PyObject *new_m; + (void)PyDict_SetDefaultRef(module_dict, name, m, &new_m); + Py_DECREF(m); + return new_m; + } else { + if (PyObject_SetItem(module_dict, name, m) != 0) { + Py_DECREF(m); + return NULL; + } + return m; + } + } + static PyObject *__Pyx_PyImport_AddModuleRef(const char *name) { + PyObject *py_name = PyUnicode_FromString(name); + if (!py_name) return NULL; + PyObject *module = __Pyx_PyImport_AddModuleObjectRef(py_name); + Py_DECREF(py_name); + return module; + } +#elif __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + #define __Pyx_PyImport_AddModuleRef(name) PyImport_AddModuleRef(name) +#else + static PyObject *__Pyx_PyImport_AddModuleRef(const char *name) { + PyObject *module = PyImport_AddModule(name); + Py_XINCREF(module); + return module; + } +#endif + +/* FetchSharedCythonModule (used by FetchCommonType) */ +static PyObject *__Pyx_FetchSharedCythonABIModule(void) { + return __Pyx_PyImport_AddModuleRef(__PYX_ABI_MODULE_NAME); +} + +/* FetchCommonType (used by CommonTypesMetaclass) */ +#if __PYX_LIMITED_VERSION_HEX < 0x030C0000 +static PyObject* __Pyx_PyType_FromMetaclass(PyTypeObject *metaclass, PyObject *module, PyType_Spec *spec, PyObject *bases) { + PyObject *result = __Pyx_PyType_FromModuleAndSpec(module, spec, bases); + if (result && metaclass) { + PyObject *old_tp = (PyObject*)Py_TYPE(result); + Py_INCREF((PyObject*)metaclass); +#if __PYX_LIMITED_VERSION_HEX >= 0x03090000 + Py_SET_TYPE(result, metaclass); +#else + result->ob_type = metaclass; +#endif + Py_DECREF(old_tp); + } + return result; +} +#else +#define __Pyx_PyType_FromMetaclass(me, mo, s, b) PyType_FromMetaclass(me, mo, s, b) +#endif +static int __Pyx_VerifyCachedType(PyObject *cached_type, + const char *name, + Py_ssize_t expected_basicsize) { + Py_ssize_t basicsize; + if (!PyType_Check(cached_type)) { + PyErr_Format(PyExc_TypeError, + "Shared Cython type %.200s is not a type object", name); + return -1; + } + if (expected_basicsize == 0) { + return 0; // size is inherited, nothing useful to check + } +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *py_basicsize; + py_basicsize = PyObject_GetAttrString(cached_type, "__basicsize__"); + if (unlikely(!py_basicsize)) return -1; + basicsize = PyLong_AsSsize_t(py_basicsize); + Py_DECREF(py_basicsize); + py_basicsize = NULL; + if (unlikely(basicsize == (Py_ssize_t)-1) && PyErr_Occurred()) return -1; +#else + basicsize = ((PyTypeObject*) cached_type)->tp_basicsize; +#endif + if (basicsize != expected_basicsize) { + PyErr_Format(PyExc_TypeError, + "Shared Cython type %.200s has the wrong size, try recompiling", + name); + return -1; + } + return 0; +} +static PyTypeObject *__Pyx_FetchCommonTypeFromSpec(PyTypeObject *metaclass, PyObject *module, PyType_Spec *spec, PyObject *bases) { + PyObject *abi_module = NULL, *cached_type = NULL, *abi_module_dict, *new_cached_type, *py_object_name; + int get_item_ref_result; + const char* object_name = strrchr(spec->name, '.'); + object_name = object_name ? object_name+1 : spec->name; + py_object_name = PyUnicode_FromString(object_name); + if (!py_object_name) return NULL; + abi_module = __Pyx_FetchSharedCythonABIModule(); + if (!abi_module) goto done; + abi_module_dict = PyModule_GetDict(abi_module); + if (!abi_module_dict) goto done; + get_item_ref_result = __Pyx_PyDict_GetItemRef(abi_module_dict, py_object_name, &cached_type); + if (get_item_ref_result == 1) { + if (__Pyx_VerifyCachedType( + cached_type, + object_name, + spec->basicsize) < 0) { + goto bad; + } + goto done; + } else if (unlikely(get_item_ref_result == -1)) { + goto bad; + } + cached_type = __Pyx_PyType_FromMetaclass( + metaclass, + CYTHON_USE_MODULE_STATE ? module : abi_module, + spec, bases); + if (unlikely(!cached_type)) goto bad; + if (unlikely(__Pyx_fix_up_extension_type_from_spec(spec, (PyTypeObject *) cached_type) < 0)) goto bad; + new_cached_type = __Pyx_PyDict_SetDefault(abi_module_dict, py_object_name, cached_type); + if (unlikely(new_cached_type != cached_type)) { + if (unlikely(!new_cached_type)) goto bad; + Py_DECREF(cached_type); + cached_type = new_cached_type; + if (__Pyx_VerifyCachedType( + cached_type, + object_name, + spec->basicsize) < 0) { + goto bad; + } + goto done; + } else { + Py_DECREF(new_cached_type); + } +done: + Py_XDECREF(abi_module); + Py_DECREF(py_object_name); + assert(cached_type == NULL || PyType_Check(cached_type)); + return (PyTypeObject *) cached_type; +bad: + Py_XDECREF(cached_type); + cached_type = NULL; + goto done; +} + +/* CommonTypesMetaclass (used by CythonFunctionShared) */ +static PyObject* __pyx_CommonTypesMetaclass_get_module(CYTHON_UNUSED PyObject *self, CYTHON_UNUSED void* context) { + return PyUnicode_FromString(__PYX_ABI_MODULE_NAME); +} +#if __PYX_LIMITED_VERSION_HEX < 0x030A0000 +static PyObject* __pyx_CommonTypesMetaclass_call(CYTHON_UNUSED PyObject *self, CYTHON_UNUSED PyObject *args, CYTHON_UNUSED PyObject *kwds) { + PyErr_SetString(PyExc_TypeError, "Cannot instantiate Cython internal types"); + return NULL; +} +static int __pyx_CommonTypesMetaclass_setattr(CYTHON_UNUSED PyObject *self, CYTHON_UNUSED PyObject *attr, CYTHON_UNUSED PyObject *value) { + PyErr_SetString(PyExc_TypeError, "Cython internal types are immutable"); + return -1; +} +#endif +static PyGetSetDef __pyx_CommonTypesMetaclass_getset[] = { + {"__module__", __pyx_CommonTypesMetaclass_get_module, NULL, NULL, NULL}, + {0, 0, 0, 0, 0} +}; +static PyType_Slot __pyx_CommonTypesMetaclass_slots[] = { + {Py_tp_getset, (void *)__pyx_CommonTypesMetaclass_getset}, + #if __PYX_LIMITED_VERSION_HEX < 0x030A0000 + {Py_tp_call, (void*)__pyx_CommonTypesMetaclass_call}, + {Py_tp_new, (void*)__pyx_CommonTypesMetaclass_call}, + {Py_tp_setattro, (void*)__pyx_CommonTypesMetaclass_setattr}, + #endif + {0, 0} +}; +static PyType_Spec __pyx_CommonTypesMetaclass_spec = { + __PYX_TYPE_MODULE_PREFIX "_common_types_metatype", + 0, + 0, + Py_TPFLAGS_IMMUTABLETYPE | + Py_TPFLAGS_DISALLOW_INSTANTIATION | + Py_TPFLAGS_DEFAULT, + __pyx_CommonTypesMetaclass_slots +}; +static int __pyx_CommonTypesMetaclass_init(PyObject *module) { + __pyx_mstatetype *mstate = __Pyx_PyModule_GetState(module); + PyObject *bases = PyTuple_Pack(1, &PyType_Type); + if (unlikely(!bases)) { + return -1; + } + mstate->__pyx_CommonTypesMetaclassType = __Pyx_FetchCommonTypeFromSpec(NULL, module, &__pyx_CommonTypesMetaclass_spec, bases); + Py_DECREF(bases); + if (unlikely(mstate->__pyx_CommonTypesMetaclassType == NULL)) { + return -1; + } + return 0; +} + +/* PyMethodNew (used by CythonFunctionShared) */ +#if CYTHON_COMPILING_IN_LIMITED_API +static PyObject *__Pyx_PyMethod_New(PyObject *func, PyObject *self, PyObject *typ) { + PyObject *result; + CYTHON_UNUSED_VAR(typ); + if (!self) + return __Pyx_NewRef(func); + #if __PYX_LIMITED_VERSION_HEX >= 0x030C0000 + { + PyObject *args[] = {func, self}; + result = PyObject_Vectorcall(__pyx_mstate_global->__Pyx_CachedMethodType, args, 2, NULL); + } + #else + result = PyObject_CallFunctionObjArgs(__pyx_mstate_global->__Pyx_CachedMethodType, func, self, NULL); + #endif + return result; +} +#else +static PyObject *__Pyx_PyMethod_New(PyObject *func, PyObject *self, PyObject *typ) { + CYTHON_UNUSED_VAR(typ); + if (!self) + return __Pyx_NewRef(func); + return PyMethod_New(func, self); +} +#endif + +/* PyVectorcallFastCallDict (used by CythonFunctionShared) */ +#if CYTHON_METH_FASTCALL && CYTHON_VECTORCALL +static PyObject *__Pyx_PyVectorcall_FastCallDict_kw(PyObject *func, __pyx_vectorcallfunc vc, PyObject *const *args, size_t nargs, PyObject *kw) +{ + PyObject *res = NULL; + PyObject *kwnames; + PyObject **newargs; + PyObject **kwvalues; + Py_ssize_t i; + #if CYTHON_AVOID_BORROWED_REFS + PyObject *pos; + #else + Py_ssize_t pos; + #endif + size_t j; + PyObject *key, *value; + unsigned long keys_are_strings; + #if !CYTHON_ASSUME_SAFE_SIZE + Py_ssize_t nkw = PyDict_Size(kw); + if (unlikely(nkw == -1)) return NULL; + #else + Py_ssize_t nkw = PyDict_GET_SIZE(kw); + #endif + newargs = (PyObject **)PyMem_Malloc((nargs + (size_t)nkw) * sizeof(args[0])); + if (unlikely(newargs == NULL)) { + PyErr_NoMemory(); + return NULL; + } + for (j = 0; j < nargs; j++) newargs[j] = args[j]; + kwnames = PyTuple_New(nkw); + if (unlikely(kwnames == NULL)) { + PyMem_Free(newargs); + return NULL; + } + kwvalues = newargs + nargs; + pos = 0; + i = 0; + keys_are_strings = Py_TPFLAGS_UNICODE_SUBCLASS; + while (__Pyx_PyDict_NextRef(kw, &pos, &key, &value)) { + keys_are_strings &= + #if CYTHON_COMPILING_IN_LIMITED_API + PyType_GetFlags(Py_TYPE(key)); + #else + Py_TYPE(key)->tp_flags; + #endif + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(PyTuple_SetItem(kwnames, i, key) < 0)) goto cleanup; + #else + PyTuple_SET_ITEM(kwnames, i, key); + #endif + kwvalues[i] = value; + i++; + } + if (unlikely(!keys_are_strings)) { + PyErr_SetString(PyExc_TypeError, "keywords must be strings"); + goto cleanup; + } + res = vc(func, newargs, nargs, kwnames); +cleanup: + #if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(pos); + #endif + Py_DECREF(kwnames); + for (i = 0; i < nkw; i++) + Py_DECREF(kwvalues[i]); + PyMem_Free(newargs); + return res; +} +static CYTHON_INLINE PyObject *__Pyx_PyVectorcall_FastCallDict(PyObject *func, __pyx_vectorcallfunc vc, PyObject *const *args, size_t nargs, PyObject *kw) +{ + Py_ssize_t kw_size = + likely(kw == NULL) ? + 0 : +#if !CYTHON_ASSUME_SAFE_SIZE + PyDict_Size(kw); +#else + PyDict_GET_SIZE(kw); +#endif + if (kw_size == 0) { + return vc(func, args, nargs, NULL); + } +#if !CYTHON_ASSUME_SAFE_SIZE + else if (unlikely(kw_size == -1)) { + return NULL; + } +#endif + return __Pyx_PyVectorcall_FastCallDict_kw(func, vc, args, nargs, kw); +} +#endif + +/* CythonFunctionShared (used by CythonFunction) */ +#if CYTHON_COMPILING_IN_LIMITED_API +static CYTHON_INLINE int __Pyx__IsSameCyOrCFunctionNoMethod(PyObject *func, void (*cfunc)(void)) { + if (__Pyx_CyFunction_Check(func)) { + return PyCFunction_GetFunction(((__pyx_CyFunctionObject*)func)->func) == (PyCFunction) cfunc; + } else if (PyCFunction_Check(func)) { + return PyCFunction_GetFunction(func) == (PyCFunction) cfunc; + } + return 0; +} +static CYTHON_INLINE int __Pyx__IsSameCyOrCFunction(PyObject *func, void (*cfunc)(void)) { + if ((PyObject*)Py_TYPE(func) == __pyx_mstate_global->__Pyx_CachedMethodType) { + int result; + PyObject *newFunc = PyObject_GetAttr(func, __pyx_mstate_global->__pyx_n_u_func); + if (unlikely(!newFunc)) { + PyErr_Clear(); // It's only an optimization, so don't throw an error + return 0; + } + result = __Pyx__IsSameCyOrCFunctionNoMethod(newFunc, cfunc); + Py_DECREF(newFunc); + return result; + } + return __Pyx__IsSameCyOrCFunctionNoMethod(func, cfunc); +} +#else +static CYTHON_INLINE int __Pyx__IsSameCyOrCFunction(PyObject *func, void (*cfunc)(void)) { + if (PyMethod_Check(func)) { + func = PyMethod_GET_FUNCTION(func); + } + return __Pyx_CyOrPyCFunction_Check(func) && __Pyx_CyOrPyCFunction_GET_FUNCTION(func) == (PyCFunction) cfunc; +} +#endif +static CYTHON_INLINE void __Pyx__CyFunction_SetClassObj(__pyx_CyFunctionObject* f, PyObject* classobj) { +#if PY_VERSION_HEX < 0x030900B1 || CYTHON_COMPILING_IN_LIMITED_API + __Pyx_Py_XDECREF_SET( + __Pyx_CyFunction_GetClassObj(f), + ((classobj) ? __Pyx_NewRef(classobj) : NULL)); +#else + __Pyx_Py_XDECREF_SET( + ((PyCMethodObject *) (f))->mm_class, + (PyTypeObject*)((classobj) ? __Pyx_NewRef(classobj) : NULL)); +#endif +} +static PyObject * +__Pyx_CyFunction_get_doc_locked(__pyx_CyFunctionObject *op) +{ + if (unlikely(op->func_doc == NULL)) { +#if CYTHON_COMPILING_IN_LIMITED_API + op->func_doc = PyObject_GetAttrString(op->func, "__doc__"); + if (unlikely(!op->func_doc)) return NULL; +#else + if (((PyCFunctionObject*)op)->m_ml->ml_doc) { + op->func_doc = PyUnicode_FromString(((PyCFunctionObject*)op)->m_ml->ml_doc); + if (unlikely(op->func_doc == NULL)) + return NULL; + } else { + Py_INCREF(Py_None); + return Py_None; + } +#endif + } + Py_INCREF(op->func_doc); + return op->func_doc; +} +static PyObject * +__Pyx_CyFunction_get_doc(__pyx_CyFunctionObject *op, void *closure) { + PyObject *result; + CYTHON_UNUSED_VAR(closure); + __Pyx_BEGIN_CRITICAL_SECTION(op); + result = __Pyx_CyFunction_get_doc_locked(op); + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static int +__Pyx_CyFunction_set_doc(__pyx_CyFunctionObject *op, PyObject *value, void *context) +{ + CYTHON_UNUSED_VAR(context); + if (value == NULL) { + value = Py_None; + } + Py_INCREF(value); + __Pyx_BEGIN_CRITICAL_SECTION(op); + __Pyx_Py_XDECREF_SET(op->func_doc, value); + __Pyx_END_CRITICAL_SECTION(); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_name_locked(__pyx_CyFunctionObject *op) +{ + if (unlikely(op->func_name == NULL)) { +#if CYTHON_COMPILING_IN_LIMITED_API + op->func_name = PyObject_GetAttrString(op->func, "__name__"); +#else + op->func_name = PyUnicode_InternFromString(((PyCFunctionObject*)op)->m_ml->ml_name); +#endif + if (unlikely(op->func_name == NULL)) + return NULL; + } + Py_INCREF(op->func_name); + return op->func_name; +} +static PyObject * +__Pyx_CyFunction_get_name(__pyx_CyFunctionObject *op, void *context) +{ + PyObject *result = NULL; + CYTHON_UNUSED_VAR(context); + __Pyx_BEGIN_CRITICAL_SECTION(op); + result = __Pyx_CyFunction_get_name_locked(op); + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static int +__Pyx_CyFunction_set_name(__pyx_CyFunctionObject *op, PyObject *value, void *context) +{ + CYTHON_UNUSED_VAR(context); + if (unlikely(value == NULL || !PyUnicode_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "__name__ must be set to a string object"); + return -1; + } + Py_INCREF(value); + __Pyx_BEGIN_CRITICAL_SECTION(op); + __Pyx_Py_XDECREF_SET(op->func_name, value); + __Pyx_END_CRITICAL_SECTION(); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_qualname(__pyx_CyFunctionObject *op, void *context) +{ + CYTHON_UNUSED_VAR(context); + PyObject *result; + __Pyx_BEGIN_CRITICAL_SECTION(op); + Py_INCREF(op->func_qualname); + result = op->func_qualname; + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static int +__Pyx_CyFunction_set_qualname(__pyx_CyFunctionObject *op, PyObject *value, void *context) +{ + CYTHON_UNUSED_VAR(context); + if (unlikely(value == NULL || !PyUnicode_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "__qualname__ must be set to a string object"); + return -1; + } + Py_INCREF(value); + __Pyx_BEGIN_CRITICAL_SECTION(op); + __Pyx_Py_XDECREF_SET(op->func_qualname, value); + __Pyx_END_CRITICAL_SECTION(); + return 0; +} +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000 +static PyObject * +__Pyx_CyFunction_get_dict(__pyx_CyFunctionObject *op, void *context) +{ + CYTHON_UNUSED_VAR(context); + if (unlikely(op->func_dict == NULL)) { + op->func_dict = PyDict_New(); + if (unlikely(op->func_dict == NULL)) + return NULL; + } + Py_INCREF(op->func_dict); + return op->func_dict; +} +#endif +static PyObject * +__Pyx_CyFunction_get_globals(__pyx_CyFunctionObject *op, void *context) +{ + CYTHON_UNUSED_VAR(context); + Py_INCREF(op->func_globals); + return op->func_globals; +} +static PyObject * +__Pyx_CyFunction_get_closure(__pyx_CyFunctionObject *op, void *context) +{ + CYTHON_UNUSED_VAR(op); + CYTHON_UNUSED_VAR(context); + Py_INCREF(Py_None); + return Py_None; +} +static PyObject * +__Pyx_CyFunction_get_code(__pyx_CyFunctionObject *op, void *context) +{ + PyObject* result = (op->func_code) ? op->func_code : Py_None; + CYTHON_UNUSED_VAR(context); + Py_INCREF(result); + return result; +} +static int +__Pyx_CyFunction_init_defaults(__pyx_CyFunctionObject *op) { + int result = 0; + PyObject *res = op->defaults_getter((PyObject *) op); + if (unlikely(!res)) + return -1; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + op->defaults_tuple = PyTuple_GET_ITEM(res, 0); + Py_INCREF(op->defaults_tuple); + op->defaults_kwdict = PyTuple_GET_ITEM(res, 1); + Py_INCREF(op->defaults_kwdict); + #else + op->defaults_tuple = __Pyx_PySequence_ITEM(res, 0); + if (unlikely(!op->defaults_tuple)) result = -1; + else { + op->defaults_kwdict = __Pyx_PySequence_ITEM(res, 1); + if (unlikely(!op->defaults_kwdict)) result = -1; + } + #endif + Py_DECREF(res); + return result; +} +static int +__Pyx_CyFunction_set_defaults(__pyx_CyFunctionObject *op, PyObject* value, void *context) { + CYTHON_UNUSED_VAR(context); + if (!value) { + value = Py_None; + } else if (unlikely(value != Py_None && !PyTuple_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "__defaults__ must be set to a tuple object"); + return -1; + } + PyErr_WarnEx(PyExc_RuntimeWarning, "changes to cyfunction.__defaults__ will not " + "currently affect the values used in function calls", 1); + Py_INCREF(value); + __Pyx_BEGIN_CRITICAL_SECTION(op); + __Pyx_Py_XDECREF_SET(op->defaults_tuple, value); + __Pyx_END_CRITICAL_SECTION(); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_defaults_locked(__pyx_CyFunctionObject *op) { + PyObject* result = op->defaults_tuple; + if (unlikely(!result)) { + if (op->defaults_getter) { + if (unlikely(__Pyx_CyFunction_init_defaults(op) < 0)) return NULL; + result = op->defaults_tuple; + } else { + result = Py_None; + } + } + Py_INCREF(result); + return result; +} +static PyObject * +__Pyx_CyFunction_get_defaults(__pyx_CyFunctionObject *op, void *context) { + PyObject* result = NULL; + CYTHON_UNUSED_VAR(context); + __Pyx_BEGIN_CRITICAL_SECTION(op); + result = __Pyx_CyFunction_get_defaults_locked(op); + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static int +__Pyx_CyFunction_set_kwdefaults(__pyx_CyFunctionObject *op, PyObject* value, void *context) { + CYTHON_UNUSED_VAR(context); + if (!value) { + value = Py_None; + } else if (unlikely(value != Py_None && !PyDict_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "__kwdefaults__ must be set to a dict object"); + return -1; + } + PyErr_WarnEx(PyExc_RuntimeWarning, "changes to cyfunction.__kwdefaults__ will not " + "currently affect the values used in function calls", 1); + Py_INCREF(value); + __Pyx_BEGIN_CRITICAL_SECTION(op); + __Pyx_Py_XDECREF_SET(op->defaults_kwdict, value); + __Pyx_END_CRITICAL_SECTION(); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_kwdefaults_locked(__pyx_CyFunctionObject *op) { + PyObject* result = op->defaults_kwdict; + if (unlikely(!result)) { + if (op->defaults_getter) { + if (unlikely(__Pyx_CyFunction_init_defaults(op) < 0)) return NULL; + result = op->defaults_kwdict; + } else { + result = Py_None; + } + } + Py_INCREF(result); + return result; +} +static PyObject * +__Pyx_CyFunction_get_kwdefaults(__pyx_CyFunctionObject *op, void *context) { + PyObject* result; + CYTHON_UNUSED_VAR(context); + __Pyx_BEGIN_CRITICAL_SECTION(op); + result = __Pyx_CyFunction_get_kwdefaults_locked(op); + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static int +__Pyx_CyFunction_set_annotations(__pyx_CyFunctionObject *op, PyObject* value, void *context) { + CYTHON_UNUSED_VAR(context); + if (!value || value == Py_None) { + value = NULL; + } else if (unlikely(!PyDict_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "__annotations__ must be set to a dict object"); + return -1; + } + Py_XINCREF(value); + __Pyx_BEGIN_CRITICAL_SECTION(op); + __Pyx_Py_XDECREF_SET(op->func_annotations, value); + __Pyx_END_CRITICAL_SECTION(); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_annotations_locked(__pyx_CyFunctionObject *op) { + PyObject* result = op->func_annotations; + if (unlikely(!result)) { + result = PyDict_New(); + if (unlikely(!result)) return NULL; + op->func_annotations = result; + } + Py_INCREF(result); + return result; +} +static PyObject * +__Pyx_CyFunction_get_annotations(__pyx_CyFunctionObject *op, void *context) { + PyObject *result; + CYTHON_UNUSED_VAR(context); + __Pyx_BEGIN_CRITICAL_SECTION(op); + result = __Pyx_CyFunction_get_annotations_locked(op); + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static PyObject * +__Pyx_CyFunction_get_is_coroutine_value(__pyx_CyFunctionObject *op) { + int is_coroutine = op->flags & __Pyx_CYFUNCTION_COROUTINE; + if (is_coroutine) { + PyObject *is_coroutine_value, *module, *fromlist, *marker = __pyx_mstate_global->__pyx_n_u_is_coroutine; + fromlist = PyList_New(1); + if (unlikely(!fromlist)) return NULL; + Py_INCREF(marker); +#if CYTHON_ASSUME_SAFE_MACROS + PyList_SET_ITEM(fromlist, 0, marker); +#else + if (unlikely(PyList_SetItem(fromlist, 0, marker) < 0)) { + Py_DECREF(marker); + Py_DECREF(fromlist); + return NULL; + } +#endif + module = PyImport_ImportModuleLevelObject(__pyx_mstate_global->__pyx_n_u_asyncio_coroutines, NULL, NULL, fromlist, 0); + Py_DECREF(fromlist); + if (unlikely(!module)) goto ignore; + is_coroutine_value = __Pyx_PyObject_GetAttrStr(module, marker); + Py_DECREF(module); + if (likely(is_coroutine_value)) { + return is_coroutine_value; + } +ignore: + PyErr_Clear(); + } + return __Pyx_PyBool_FromLong(is_coroutine); +} +static PyObject * +__Pyx_CyFunction_get_is_coroutine(__pyx_CyFunctionObject *op, void *context) { + PyObject *result; + CYTHON_UNUSED_VAR(context); + if (op->func_is_coroutine) { + return __Pyx_NewRef(op->func_is_coroutine); + } + result = __Pyx_CyFunction_get_is_coroutine_value(op); + if (unlikely(!result)) + return NULL; + __Pyx_BEGIN_CRITICAL_SECTION(op); + if (op->func_is_coroutine) { + Py_DECREF(result); + result = __Pyx_NewRef(op->func_is_coroutine); + } else { + op->func_is_coroutine = __Pyx_NewRef(result); + } + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static void __Pyx_CyFunction_raise_argument_count_error(__pyx_CyFunctionObject *func, const char* message, Py_ssize_t size) { +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *py_name = __Pyx_CyFunction_get_name(func, NULL); + if (!py_name) return; + PyErr_Format(PyExc_TypeError, + "%.200S() %s (%" CYTHON_FORMAT_SSIZE_T "d given)", + py_name, message, size); + Py_DECREF(py_name); +#else + const char* name = ((PyCFunctionObject*)func)->m_ml->ml_name; + PyErr_Format(PyExc_TypeError, + "%.200s() %s (%" CYTHON_FORMAT_SSIZE_T "d given)", + name, message, size); +#endif +} +static void __Pyx_CyFunction_raise_type_error(__pyx_CyFunctionObject *func, const char* message) { +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *py_name = __Pyx_CyFunction_get_name(func, NULL); + if (!py_name) return; + PyErr_Format(PyExc_TypeError, + "%.200S() %s", + py_name, message); + Py_DECREF(py_name); +#else + const char* name = ((PyCFunctionObject*)func)->m_ml->ml_name; + PyErr_Format(PyExc_TypeError, + "%.200s() %s", + name, message); +#endif +} +#if CYTHON_COMPILING_IN_LIMITED_API +static PyObject * +__Pyx_CyFunction_get_module(__pyx_CyFunctionObject *op, void *context) { + CYTHON_UNUSED_VAR(context); + return PyObject_GetAttrString(op->func, "__module__"); +} +static int +__Pyx_CyFunction_set_module(__pyx_CyFunctionObject *op, PyObject* value, void *context) { + CYTHON_UNUSED_VAR(context); + return PyObject_SetAttrString(op->func, "__module__", value); +} +#endif +static PyGetSetDef __pyx_CyFunction_getsets[] = { + {"func_doc", (getter)__Pyx_CyFunction_get_doc, (setter)__Pyx_CyFunction_set_doc, 0, 0}, + {"__doc__", (getter)__Pyx_CyFunction_get_doc, (setter)__Pyx_CyFunction_set_doc, 0, 0}, + {"func_name", (getter)__Pyx_CyFunction_get_name, (setter)__Pyx_CyFunction_set_name, 0, 0}, + {"__name__", (getter)__Pyx_CyFunction_get_name, (setter)__Pyx_CyFunction_set_name, 0, 0}, + {"__qualname__", (getter)__Pyx_CyFunction_get_qualname, (setter)__Pyx_CyFunction_set_qualname, 0, 0}, +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000 + {"func_dict", (getter)__Pyx_CyFunction_get_dict, (setter)PyObject_GenericSetDict, 0, 0}, + {"__dict__", (getter)__Pyx_CyFunction_get_dict, (setter)PyObject_GenericSetDict, 0, 0}, +#else + {"func_dict", (getter)PyObject_GenericGetDict, (setter)PyObject_GenericSetDict, 0, 0}, + {"__dict__", (getter)PyObject_GenericGetDict, (setter)PyObject_GenericSetDict, 0, 0}, +#endif + {"func_globals", (getter)__Pyx_CyFunction_get_globals, 0, 0, 0}, + {"__globals__", (getter)__Pyx_CyFunction_get_globals, 0, 0, 0}, + {"func_closure", (getter)__Pyx_CyFunction_get_closure, 0, 0, 0}, + {"__closure__", (getter)__Pyx_CyFunction_get_closure, 0, 0, 0}, + {"func_code", (getter)__Pyx_CyFunction_get_code, 0, 0, 0}, + {"__code__", (getter)__Pyx_CyFunction_get_code, 0, 0, 0}, + {"func_defaults", (getter)__Pyx_CyFunction_get_defaults, (setter)__Pyx_CyFunction_set_defaults, 0, 0}, + {"__defaults__", (getter)__Pyx_CyFunction_get_defaults, (setter)__Pyx_CyFunction_set_defaults, 0, 0}, + {"__kwdefaults__", (getter)__Pyx_CyFunction_get_kwdefaults, (setter)__Pyx_CyFunction_set_kwdefaults, 0, 0}, + {"__annotations__", (getter)__Pyx_CyFunction_get_annotations, (setter)__Pyx_CyFunction_set_annotations, 0, 0}, + {"_is_coroutine", (getter)__Pyx_CyFunction_get_is_coroutine, 0, 0, 0}, +#if CYTHON_COMPILING_IN_LIMITED_API + {"__module__", (getter)__Pyx_CyFunction_get_module, (setter)__Pyx_CyFunction_set_module, 0, 0}, +#endif + {0, 0, 0, 0, 0} +}; +static PyMemberDef __pyx_CyFunction_members[] = { +#if !CYTHON_COMPILING_IN_LIMITED_API + {"__module__", T_OBJECT, offsetof(PyCFunctionObject, m_module), 0, 0}, +#endif +#if PY_VERSION_HEX < 0x030C0000 || CYTHON_COMPILING_IN_LIMITED_API + {"__dictoffset__", T_PYSSIZET, offsetof(__pyx_CyFunctionObject, func_dict), READONLY, 0}, +#endif +#if CYTHON_METH_FASTCALL +#if CYTHON_COMPILING_IN_LIMITED_API + {"__vectorcalloffset__", T_PYSSIZET, offsetof(__pyx_CyFunctionObject, func_vectorcall), READONLY, 0}, +#else + {"__vectorcalloffset__", T_PYSSIZET, offsetof(PyCFunctionObject, vectorcall), READONLY, 0}, +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + {"__weaklistoffset__", T_PYSSIZET, offsetof(__pyx_CyFunctionObject, func_weakreflist), READONLY, 0}, +#else + {"__weaklistoffset__", T_PYSSIZET, offsetof(PyCFunctionObject, m_weakreflist), READONLY, 0}, +#endif +#endif + {0, 0, 0, 0, 0} +}; +static PyObject * +__Pyx_CyFunction_reduce(__pyx_CyFunctionObject *m, PyObject *args) +{ + PyObject *result = NULL; + CYTHON_UNUSED_VAR(args); + __Pyx_BEGIN_CRITICAL_SECTION(m); + Py_INCREF(m->func_qualname); + result = m->func_qualname; + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static PyMethodDef __pyx_CyFunction_methods[] = { + {"__reduce__", (PyCFunction)__Pyx_CyFunction_reduce, METH_VARARGS, 0}, + {0, 0, 0, 0} +}; +#if CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_CyFunction_weakreflist(cyfunc) ((cyfunc)->func_weakreflist) +#else +#define __Pyx_CyFunction_weakreflist(cyfunc) (((PyCFunctionObject*)cyfunc)->m_weakreflist) +#endif +static PyObject *__Pyx_CyFunction_Init(__pyx_CyFunctionObject *op, PyMethodDef *ml, int flags, PyObject* qualname, + PyObject *closure, PyObject *module, PyObject* globals, PyObject* code) { +#if !CYTHON_COMPILING_IN_LIMITED_API + PyCFunctionObject *cf = (PyCFunctionObject*) op; +#endif + if (unlikely(op == NULL)) + return NULL; +#if CYTHON_COMPILING_IN_LIMITED_API + op->func = PyCFunction_NewEx(ml, (PyObject*)op, module); + if (unlikely(!op->func)) return NULL; +#endif + op->flags = flags; + __Pyx_CyFunction_weakreflist(op) = NULL; +#if !CYTHON_COMPILING_IN_LIMITED_API + cf->m_ml = ml; + cf->m_self = (PyObject *) op; +#endif + Py_XINCREF(closure); + op->func_closure = closure; +#if !CYTHON_COMPILING_IN_LIMITED_API + Py_XINCREF(module); + cf->m_module = module; +#endif +#if PY_VERSION_HEX < 0x030C0000 || CYTHON_COMPILING_IN_LIMITED_API + op->func_dict = NULL; +#endif + op->func_name = NULL; + Py_INCREF(qualname); + op->func_qualname = qualname; + op->func_doc = NULL; +#if PY_VERSION_HEX < 0x030900B1 || CYTHON_COMPILING_IN_LIMITED_API + op->func_classobj = NULL; +#else + ((PyCMethodObject*)op)->mm_class = NULL; +#endif + op->func_globals = globals; + Py_INCREF(op->func_globals); + Py_XINCREF(code); + op->func_code = code; + op->defaults = NULL; + op->defaults_tuple = NULL; + op->defaults_kwdict = NULL; + op->defaults_getter = NULL; + op->func_annotations = NULL; + op->func_is_coroutine = NULL; +#if CYTHON_METH_FASTCALL + switch (ml->ml_flags & (METH_VARARGS | METH_FASTCALL | METH_NOARGS | METH_O | METH_KEYWORDS | METH_METHOD)) { + case METH_NOARGS: + __Pyx_CyFunction_func_vectorcall(op) = __Pyx_CyFunction_Vectorcall_NOARGS; + break; + case METH_O: + __Pyx_CyFunction_func_vectorcall(op) = __Pyx_CyFunction_Vectorcall_O; + break; + case METH_METHOD | METH_FASTCALL | METH_KEYWORDS: + __Pyx_CyFunction_func_vectorcall(op) = __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS_METHOD; + break; + case METH_FASTCALL | METH_KEYWORDS: + __Pyx_CyFunction_func_vectorcall(op) = __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS; + break; + case METH_VARARGS | METH_KEYWORDS: + __Pyx_CyFunction_func_vectorcall(op) = NULL; + break; + default: + PyErr_SetString(PyExc_SystemError, "Bad call flags for CyFunction"); + Py_DECREF(op); + return NULL; + } +#endif + return (PyObject *) op; +} +static int +__Pyx_CyFunction_clear(__pyx_CyFunctionObject *m) +{ + Py_CLEAR(m->func_closure); +#if CYTHON_COMPILING_IN_LIMITED_API + Py_CLEAR(m->func); +#else + Py_CLEAR(((PyCFunctionObject*)m)->m_module); +#endif +#if PY_VERSION_HEX < 0x030C0000 || CYTHON_COMPILING_IN_LIMITED_API + Py_CLEAR(m->func_dict); +#elif PY_VERSION_HEX < 0x030d0000 + _PyObject_ClearManagedDict((PyObject*)m); +#else + PyObject_ClearManagedDict((PyObject*)m); +#endif + Py_CLEAR(m->func_name); + Py_CLEAR(m->func_qualname); + Py_CLEAR(m->func_doc); + Py_CLEAR(m->func_globals); + Py_CLEAR(m->func_code); +#if !CYTHON_COMPILING_IN_LIMITED_API +#if PY_VERSION_HEX < 0x030900B1 + Py_CLEAR(__Pyx_CyFunction_GetClassObj(m)); +#else + { + PyObject *cls = (PyObject*) ((PyCMethodObject *) (m))->mm_class; + ((PyCMethodObject *) (m))->mm_class = NULL; + Py_XDECREF(cls); + } +#endif +#endif + Py_CLEAR(m->defaults_tuple); + Py_CLEAR(m->defaults_kwdict); + Py_CLEAR(m->func_annotations); + Py_CLEAR(m->func_is_coroutine); + Py_CLEAR(m->defaults); + return 0; +} +static void __Pyx__CyFunction_dealloc(__pyx_CyFunctionObject *m) +{ + if (__Pyx_CyFunction_weakreflist(m) != NULL) + PyObject_ClearWeakRefs((PyObject *) m); + __Pyx_CyFunction_clear(m); + __Pyx_PyHeapTypeObject_GC_Del(m); +} +static void __Pyx_CyFunction_dealloc(__pyx_CyFunctionObject *m) +{ + PyObject_GC_UnTrack(m); + __Pyx__CyFunction_dealloc(m); +} +static int __Pyx_CyFunction_traverse(__pyx_CyFunctionObject *m, visitproc visit, void *arg) +{ + { + int e = __Pyx_call_type_traverse((PyObject*)m, 1, visit, arg); + if (e) return e; + } + Py_VISIT(m->func_closure); +#if CYTHON_COMPILING_IN_LIMITED_API + Py_VISIT(m->func); +#else + Py_VISIT(((PyCFunctionObject*)m)->m_module); +#endif +#if PY_VERSION_HEX < 0x030C0000 || CYTHON_COMPILING_IN_LIMITED_API + Py_VISIT(m->func_dict); +#else + { + int e = +#if PY_VERSION_HEX < 0x030d0000 + _PyObject_VisitManagedDict +#else + PyObject_VisitManagedDict +#endif + ((PyObject*)m, visit, arg); + if (e != 0) return e; + } +#endif + __Pyx_VISIT_CONST(m->func_name); + __Pyx_VISIT_CONST(m->func_qualname); + Py_VISIT(m->func_doc); + Py_VISIT(m->func_globals); + __Pyx_VISIT_CONST(m->func_code); +#if !CYTHON_COMPILING_IN_LIMITED_API + Py_VISIT(__Pyx_CyFunction_GetClassObj(m)); +#endif + Py_VISIT(m->defaults_tuple); + Py_VISIT(m->defaults_kwdict); + Py_VISIT(m->func_is_coroutine); + Py_VISIT(m->defaults); + return 0; +} +static PyObject* +__Pyx_CyFunction_repr(__pyx_CyFunctionObject *op) +{ + PyObject *repr; + __Pyx_BEGIN_CRITICAL_SECTION(op); + repr = PyUnicode_FromFormat("", + op->func_qualname, (void *)op); + __Pyx_END_CRITICAL_SECTION(); + return repr; +} +static PyObject * __Pyx_CyFunction_CallMethod(PyObject *func, PyObject *self, PyObject *arg, PyObject *kw) { +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *f = ((__pyx_CyFunctionObject*)func)->func; + PyCFunction meth; + int flags; + meth = PyCFunction_GetFunction(f); + if (unlikely(!meth)) return NULL; + flags = PyCFunction_GetFlags(f); + if (unlikely(flags < 0)) return NULL; +#else + PyCFunctionObject* f = (PyCFunctionObject*)func; + PyCFunction meth = f->m_ml->ml_meth; + int flags = f->m_ml->ml_flags; +#endif + Py_ssize_t size; + switch (flags & (METH_VARARGS | METH_KEYWORDS | METH_NOARGS | METH_O)) { + case METH_VARARGS: + if (likely(kw == NULL || PyDict_Size(kw) == 0)) + return (*meth)(self, arg); + break; + case METH_VARARGS | METH_KEYWORDS: + return (*(PyCFunctionWithKeywords)(void(*)(void))meth)(self, arg, kw); + case METH_NOARGS: + if (likely(kw == NULL || PyDict_Size(kw) == 0)) { +#if CYTHON_ASSUME_SAFE_SIZE + size = PyTuple_GET_SIZE(arg); +#else + size = PyTuple_Size(arg); + if (unlikely(size < 0)) return NULL; +#endif + if (likely(size == 0)) + return (*meth)(self, NULL); + __Pyx_CyFunction_raise_argument_count_error( + (__pyx_CyFunctionObject*)func, + "takes no arguments", size); + return NULL; + } + break; + case METH_O: + if (likely(kw == NULL || PyDict_Size(kw) == 0)) { +#if CYTHON_ASSUME_SAFE_SIZE + size = PyTuple_GET_SIZE(arg); +#else + size = PyTuple_Size(arg); + if (unlikely(size < 0)) return NULL; +#endif + if (likely(size == 1)) { + PyObject *result, *arg0; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + arg0 = PyTuple_GET_ITEM(arg, 0); + #else + arg0 = __Pyx_PySequence_ITEM(arg, 0); if (unlikely(!arg0)) return NULL; + #endif + result = (*meth)(self, arg0); + #if !(CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS) + Py_DECREF(arg0); + #endif + return result; + } + __Pyx_CyFunction_raise_argument_count_error( + (__pyx_CyFunctionObject*)func, + "takes exactly one argument", size); + return NULL; + } + break; + default: + PyErr_SetString(PyExc_SystemError, "Bad call flags for CyFunction"); + return NULL; + } + __Pyx_CyFunction_raise_type_error( + (__pyx_CyFunctionObject*)func, "takes no keyword arguments"); + return NULL; +} +static CYTHON_INLINE PyObject *__Pyx_CyFunction_Call(PyObject *func, PyObject *arg, PyObject *kw) { + PyObject *self, *result; +#if CYTHON_COMPILING_IN_LIMITED_API + self = PyCFunction_GetSelf(((__pyx_CyFunctionObject*)func)->func); + if (unlikely(!self) && PyErr_Occurred()) return NULL; +#else + self = ((PyCFunctionObject*)func)->m_self; +#endif + result = __Pyx_CyFunction_CallMethod(func, self, arg, kw); + return result; +} +static PyObject *__Pyx_CyFunction_CallAsMethod(PyObject *func, PyObject *args, PyObject *kw) { + PyObject *result; + __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *) func; +#if CYTHON_METH_FASTCALL && CYTHON_VECTORCALL + __pyx_vectorcallfunc vc = __Pyx_CyFunction_func_vectorcall(cyfunc); + if (vc) { +#if CYTHON_ASSUME_SAFE_MACROS && CYTHON_ASSUME_SAFE_SIZE + return __Pyx_PyVectorcall_FastCallDict(func, vc, &PyTuple_GET_ITEM(args, 0), (size_t)PyTuple_GET_SIZE(args), kw); +#else + (void) &__Pyx_PyVectorcall_FastCallDict; + return PyVectorcall_Call(func, args, kw); +#endif + } +#endif + if ((cyfunc->flags & __Pyx_CYFUNCTION_CCLASS) && !(cyfunc->flags & __Pyx_CYFUNCTION_STATICMETHOD)) { + Py_ssize_t argc; + PyObject *new_args; + PyObject *self; +#if CYTHON_ASSUME_SAFE_SIZE + argc = PyTuple_GET_SIZE(args); +#else + argc = PyTuple_Size(args); + if (unlikely(argc < 0)) return NULL; +#endif + new_args = PyTuple_GetSlice(args, 1, argc); + if (unlikely(!new_args)) + return NULL; + self = PyTuple_GetItem(args, 0); + if (unlikely(!self)) { + Py_DECREF(new_args); + PyErr_Format(PyExc_TypeError, + "unbound method %.200S() needs an argument", + cyfunc->func_qualname); + return NULL; + } + result = __Pyx_CyFunction_CallMethod(func, self, new_args, kw); + Py_DECREF(new_args); + } else { + result = __Pyx_CyFunction_Call(func, args, kw); + } + return result; +} +#if CYTHON_METH_FASTCALL && CYTHON_VECTORCALL +static CYTHON_INLINE int __Pyx_CyFunction_Vectorcall_CheckArgs(__pyx_CyFunctionObject *cyfunc, Py_ssize_t nargs, PyObject *kwnames) +{ + int ret = 0; + if ((cyfunc->flags & __Pyx_CYFUNCTION_CCLASS) && !(cyfunc->flags & __Pyx_CYFUNCTION_STATICMETHOD)) { + if (unlikely(nargs < 1)) { + __Pyx_CyFunction_raise_type_error( + cyfunc, "needs an argument"); + return -1; + } + ret = 1; + } + if (unlikely(kwnames) && unlikely(__Pyx_PyTuple_GET_SIZE(kwnames))) { + __Pyx_CyFunction_raise_type_error( + cyfunc, "takes no keyword arguments"); + return -1; + } + return ret; +} +static PyObject * __Pyx_CyFunction_Vectorcall_NOARGS(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames) +{ + __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *)func; + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); + PyObject *self; +#if CYTHON_COMPILING_IN_LIMITED_API + PyCFunction meth = PyCFunction_GetFunction(cyfunc->func); + if (unlikely(!meth)) return NULL; +#else + PyCFunction meth = ((PyCFunctionObject*)cyfunc)->m_ml->ml_meth; +#endif + switch (__Pyx_CyFunction_Vectorcall_CheckArgs(cyfunc, nargs, kwnames)) { + case 1: + self = args[0]; + args += 1; + nargs -= 1; + break; + case 0: +#if CYTHON_COMPILING_IN_LIMITED_API + self = PyCFunction_GetSelf(((__pyx_CyFunctionObject*)cyfunc)->func); + if (unlikely(!self) && PyErr_Occurred()) return NULL; +#else + self = ((PyCFunctionObject*)cyfunc)->m_self; +#endif + break; + default: + return NULL; + } + if (unlikely(nargs != 0)) { + __Pyx_CyFunction_raise_argument_count_error( + cyfunc, "takes no arguments", nargs); + return NULL; + } + return meth(self, NULL); +} +static PyObject * __Pyx_CyFunction_Vectorcall_O(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames) +{ + __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *)func; + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); + PyObject *self; +#if CYTHON_COMPILING_IN_LIMITED_API + PyCFunction meth = PyCFunction_GetFunction(cyfunc->func); + if (unlikely(!meth)) return NULL; +#else + PyCFunction meth = ((PyCFunctionObject*)cyfunc)->m_ml->ml_meth; +#endif + switch (__Pyx_CyFunction_Vectorcall_CheckArgs(cyfunc, nargs, kwnames)) { + case 1: + self = args[0]; + args += 1; + nargs -= 1; + break; + case 0: +#if CYTHON_COMPILING_IN_LIMITED_API + self = PyCFunction_GetSelf(((__pyx_CyFunctionObject*)cyfunc)->func); + if (unlikely(!self) && PyErr_Occurred()) return NULL; +#else + self = ((PyCFunctionObject*)cyfunc)->m_self; +#endif + break; + default: + return NULL; + } + if (unlikely(nargs != 1)) { + __Pyx_CyFunction_raise_argument_count_error( + cyfunc, "takes exactly one argument", nargs); + return NULL; + } + return meth(self, args[0]); +} +static PyObject * __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames) +{ + __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *)func; + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); + PyObject *self; +#if CYTHON_COMPILING_IN_LIMITED_API + PyCFunction meth = PyCFunction_GetFunction(cyfunc->func); + if (unlikely(!meth)) return NULL; +#else + PyCFunction meth = ((PyCFunctionObject*)cyfunc)->m_ml->ml_meth; +#endif + switch (__Pyx_CyFunction_Vectorcall_CheckArgs(cyfunc, nargs, NULL)) { + case 1: + self = args[0]; + args += 1; + nargs -= 1; + break; + case 0: +#if CYTHON_COMPILING_IN_LIMITED_API + self = PyCFunction_GetSelf(((__pyx_CyFunctionObject*)cyfunc)->func); + if (unlikely(!self) && PyErr_Occurred()) return NULL; +#else + self = ((PyCFunctionObject*)cyfunc)->m_self; +#endif + break; + default: + return NULL; + } + return ((__Pyx_PyCFunctionFastWithKeywords)(void(*)(void))meth)(self, args, nargs, kwnames); +} +static PyObject * __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS_METHOD(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames) +{ + __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *)func; + PyTypeObject *cls = (PyTypeObject *) __Pyx_CyFunction_GetClassObj(cyfunc); + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); + PyObject *self; +#if CYTHON_COMPILING_IN_LIMITED_API + PyCFunction meth = PyCFunction_GetFunction(cyfunc->func); + if (unlikely(!meth)) return NULL; +#else + PyCFunction meth = ((PyCFunctionObject*)cyfunc)->m_ml->ml_meth; +#endif + switch (__Pyx_CyFunction_Vectorcall_CheckArgs(cyfunc, nargs, NULL)) { + case 1: + self = args[0]; + args += 1; + nargs -= 1; + break; + case 0: +#if CYTHON_COMPILING_IN_LIMITED_API + self = PyCFunction_GetSelf(((__pyx_CyFunctionObject*)cyfunc)->func); + if (unlikely(!self) && PyErr_Occurred()) return NULL; +#else + self = ((PyCFunctionObject*)cyfunc)->m_self; +#endif + break; + default: + return NULL; + } + #if PY_VERSION_HEX < 0x030e00A6 + size_t nargs_value = (size_t) nargs; + #else + Py_ssize_t nargs_value = nargs; + #endif + return ((__Pyx_PyCMethod)(void(*)(void))meth)(self, cls, args, nargs_value, kwnames); +} +#endif +static PyType_Slot __pyx_CyFunctionType_slots[] = { + {Py_tp_dealloc, (void *)__Pyx_CyFunction_dealloc}, + {Py_tp_repr, (void *)__Pyx_CyFunction_repr}, + {Py_tp_call, (void *)__Pyx_CyFunction_CallAsMethod}, + {Py_tp_traverse, (void *)__Pyx_CyFunction_traverse}, + {Py_tp_clear, (void *)__Pyx_CyFunction_clear}, + {Py_tp_methods, (void *)__pyx_CyFunction_methods}, + {Py_tp_members, (void *)__pyx_CyFunction_members}, + {Py_tp_getset, (void *)__pyx_CyFunction_getsets}, + {Py_tp_descr_get, (void *)__Pyx_PyMethod_New}, + {0, 0}, +}; +static PyType_Spec __pyx_CyFunctionType_spec = { + __PYX_TYPE_MODULE_PREFIX "cython_function_or_method", + sizeof(__pyx_CyFunctionObject), + 0, +#ifdef Py_TPFLAGS_METHOD_DESCRIPTOR + Py_TPFLAGS_METHOD_DESCRIPTOR | +#endif +#if CYTHON_METH_FASTCALL +#if defined(Py_TPFLAGS_HAVE_VECTORCALL) + Py_TPFLAGS_HAVE_VECTORCALL | +#elif defined(_Py_TPFLAGS_HAVE_VECTORCALL) + _Py_TPFLAGS_HAVE_VECTORCALL | +#endif +#endif // CYTHON_METH_FASTCALL +#if PY_VERSION_HEX >= 0x030C0000 && !CYTHON_COMPILING_IN_LIMITED_API + Py_TPFLAGS_MANAGED_DICT | +#endif + Py_TPFLAGS_IMMUTABLETYPE | Py_TPFLAGS_DISALLOW_INSTANTIATION | + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, + __pyx_CyFunctionType_slots +}; +static int __pyx_CyFunction_init(PyObject *module) { + __pyx_mstatetype *mstate = __Pyx_PyModule_GetState(module); + mstate->__pyx_CyFunctionType = __Pyx_FetchCommonTypeFromSpec( + mstate->__pyx_CommonTypesMetaclassType, module, &__pyx_CyFunctionType_spec, NULL); + if (unlikely(mstate->__pyx_CyFunctionType == NULL)) { + return -1; + } + return 0; +} +static CYTHON_INLINE PyObject *__Pyx_CyFunction_InitDefaults(PyObject *func, PyTypeObject *defaults_type) { + __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; + m->defaults = PyObject_CallObject((PyObject*)defaults_type, NULL); // _PyObject_New(defaults_type); + if (unlikely(!m->defaults)) + return NULL; + return m->defaults; +} +static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsTuple(PyObject *func, PyObject *tuple) { + __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; + m->defaults_tuple = tuple; + Py_INCREF(tuple); +} +static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsKwDict(PyObject *func, PyObject *dict) { + __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; + m->defaults_kwdict = dict; + Py_INCREF(dict); +} +static CYTHON_INLINE void __Pyx_CyFunction_SetAnnotationsDict(PyObject *func, PyObject *dict) { + __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; + m->func_annotations = dict; + Py_INCREF(dict); +} + +/* CythonFunction */ +static PyObject *__Pyx_CyFunction_New(PyMethodDef *ml, int flags, PyObject* qualname, + PyObject *closure, PyObject *module, PyObject* globals, PyObject* code) { + PyObject *op = __Pyx_CyFunction_Init( + PyObject_GC_New(__pyx_CyFunctionObject, __pyx_mstate_global->__pyx_CyFunctionType), + ml, flags, qualname, closure, module, globals, code + ); + if (likely(op)) { + PyObject_GC_Track(op); + } + return op; +} + +/* Py3UpdateBases */ +static PyObject* +__Pyx_PEP560_update_bases(PyObject *bases) +{ + Py_ssize_t i, j, size_bases; + PyObject *base = NULL, *meth, *new_base, *result, *new_bases = NULL; +#if CYTHON_ASSUME_SAFE_SIZE + size_bases = PyTuple_GET_SIZE(bases); +#else + size_bases = PyTuple_Size(bases); + if (size_bases < 0) return NULL; +#endif + for (i = 0; i < size_bases; i++) { +#if CYTHON_AVOID_BORROWED_REFS + Py_CLEAR(base); +#endif +#if CYTHON_ASSUME_SAFE_MACROS + base = PyTuple_GET_ITEM(bases, i); +#else + base = PyTuple_GetItem(bases, i); + if (!base) goto error; +#endif +#if CYTHON_AVOID_BORROWED_REFS + Py_INCREF(base); +#endif + if (PyType_Check(base)) { + if (new_bases) { + if (PyList_Append(new_bases, base) < 0) { + goto error; + } + } + continue; + } + meth = __Pyx_PyObject_GetAttrStrNoError(base, __pyx_mstate_global->__pyx_n_u_mro_entries); + if (!meth && PyErr_Occurred()) { + goto error; + } + if (!meth) { + if (new_bases) { + if (PyList_Append(new_bases, base) < 0) { + goto error; + } + } + continue; + } + new_base = __Pyx_PyObject_CallOneArg(meth, bases); + Py_DECREF(meth); + if (!new_base) { + goto error; + } + if (!PyTuple_Check(new_base)) { + PyErr_SetString(PyExc_TypeError, + "__mro_entries__ must return a tuple"); + Py_DECREF(new_base); + goto error; + } + if (!new_bases) { + if (!(new_bases = PyList_New(i))) { + goto error; + } + for (j = 0; j < i; j++) { + PyObject *base_from_list; +#if CYTHON_ASSUME_SAFE_MACROS + base_from_list = PyTuple_GET_ITEM(bases, j); + PyList_SET_ITEM(new_bases, j, base_from_list); + Py_INCREF(base_from_list); +#else + base_from_list = PyTuple_GetItem(bases, j); + if (!base_from_list) goto error; + Py_INCREF(base_from_list); + if (PyList_SetItem(new_bases, j, base_from_list) < 0) goto error; +#endif + } + } +#if CYTHON_ASSUME_SAFE_SIZE + j = PyList_GET_SIZE(new_bases); +#else + j = PyList_Size(new_bases); + if (j < 0) goto error; +#endif + if (PyList_SetSlice(new_bases, j, j, new_base) < 0) { + goto error; + } + Py_DECREF(new_base); + } + if (!new_bases) { + Py_INCREF(bases); + return bases; + } + result = PyList_AsTuple(new_bases); + Py_DECREF(new_bases); +#if CYTHON_AVOID_BORROWED_REFS + Py_XDECREF(base); +#endif + return result; +error: + Py_XDECREF(new_bases); +#if CYTHON_AVOID_BORROWED_REFS + Py_XDECREF(base); +#endif + return NULL; +} + +/* CalculateMetaclass */ +static PyObject *__Pyx_CalculateMetaclass(PyTypeObject *metaclass, PyObject *bases) { + Py_ssize_t i, nbases; +#if CYTHON_ASSUME_SAFE_SIZE + nbases = PyTuple_GET_SIZE(bases); +#else + nbases = PyTuple_Size(bases); + if (nbases < 0) return NULL; +#endif + for (i=0; i < nbases; i++) { + PyTypeObject *tmptype; +#if CYTHON_ASSUME_SAFE_MACROS + PyObject *tmp = PyTuple_GET_ITEM(bases, i); +#else + PyObject *tmp = PyTuple_GetItem(bases, i); + if (!tmp) return NULL; +#endif + tmptype = Py_TYPE(tmp); + if (!metaclass) { + metaclass = tmptype; + continue; + } + if (PyType_IsSubtype(metaclass, tmptype)) + continue; + if (PyType_IsSubtype(tmptype, metaclass)) { + metaclass = tmptype; + continue; + } + PyErr_SetString(PyExc_TypeError, + "metaclass conflict: " + "the metaclass of a derived class " + "must be a (non-strict) subclass " + "of the metaclasses of all its bases"); + return NULL; + } + if (!metaclass) { + metaclass = &PyType_Type; + } + Py_INCREF((PyObject*) metaclass); + return (PyObject*) metaclass; +} + +/* PyObjectCall2Args (used by Py3ClassCreate) */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call2Args(PyObject* function, PyObject* arg1, PyObject* arg2) { + PyObject *args[3] = {NULL, arg1, arg2}; + return __Pyx_PyObject_FastCall(function, args+1, 2 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET); +} + +/* PyObjectLookupSpecial (used by Py3ClassCreate) */ +#if CYTHON_USE_PYTYPE_LOOKUP && CYTHON_USE_TYPE_SLOTS +static CYTHON_INLINE PyObject* __Pyx__PyObject_LookupSpecial(PyObject* obj, PyObject* attr_name, int with_error) { + PyObject *res; + PyTypeObject *tp = Py_TYPE(obj); + res = _PyType_Lookup(tp, attr_name); + if (likely(res)) { + descrgetfunc f = Py_TYPE(res)->tp_descr_get; + if (!f) { + Py_INCREF(res); + } else { + res = f(res, obj, (PyObject *)tp); + } + } else if (with_error) { + PyErr_SetObject(PyExc_AttributeError, attr_name); + } + return res; +} +#endif + +/* Py3ClassCreate */ +static PyObject *__Pyx_Py3MetaclassPrepare(PyObject *metaclass, PyObject *bases, PyObject *name, + PyObject *qualname, PyObject *mkw, PyObject *modname, PyObject *doc) { + PyObject *ns; + if (metaclass) { + PyObject *prep = __Pyx_PyObject_GetAttrStrNoError(metaclass, __pyx_mstate_global->__pyx_n_u_prepare); + if (prep) { + PyObject *pargs[3] = {NULL, name, bases}; + ns = __Pyx_PyObject_FastCallDict(prep, pargs+1, 2 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET, mkw); + Py_DECREF(prep); + } else { + if (unlikely(PyErr_Occurred())) + return NULL; + ns = PyDict_New(); + } + } else { + ns = PyDict_New(); + } + if (unlikely(!ns)) + return NULL; + if (unlikely(PyObject_SetItem(ns, __pyx_mstate_global->__pyx_n_u_module, modname) < 0)) goto bad; + if (unlikely(PyObject_SetItem(ns, __pyx_mstate_global->__pyx_n_u_qualname, qualname) < 0)) goto bad; + if (unlikely(doc && PyObject_SetItem(ns, __pyx_mstate_global->__pyx_n_u_doc, doc) < 0)) goto bad; + return ns; +bad: + Py_DECREF(ns); + return NULL; +} +static PyObject *__Pyx_Py3ClassCreate(PyObject *metaclass, PyObject *name, PyObject *bases, + PyObject *dict, PyObject *mkw, + int calculate_metaclass, int allow_py2_metaclass) { + PyObject *result; + PyObject *owned_metaclass = NULL; + PyObject *margs[4] = {NULL, name, bases, dict}; + if (allow_py2_metaclass) { + owned_metaclass = PyObject_GetItem(dict, __pyx_mstate_global->__pyx_n_u_metaclass); + if (owned_metaclass) { + metaclass = owned_metaclass; + } else if (likely(PyErr_ExceptionMatches(PyExc_KeyError))) { + PyErr_Clear(); + } else { + return NULL; + } + } + if (calculate_metaclass && (!metaclass || PyType_Check(metaclass))) { + metaclass = __Pyx_CalculateMetaclass((PyTypeObject*) metaclass, bases); + Py_XDECREF(owned_metaclass); + if (unlikely(!metaclass)) + return NULL; + owned_metaclass = metaclass; + } + result = __Pyx_PyObject_FastCallDict(metaclass, margs+1, 3 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET, mkw); + Py_XDECREF(owned_metaclass); + return result; +} + +/* CLineInTraceback (used by AddTraceback) */ +#if CYTHON_CLINE_IN_TRACEBACK && CYTHON_CLINE_IN_TRACEBACK_RUNTIME +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000 +#define __Pyx_PyProbablyModule_GetDict(o) __Pyx_XNewRef(PyModule_GetDict(o)) +#elif !CYTHON_COMPILING_IN_CPYTHON || CYTHON_COMPILING_IN_CPYTHON_FREETHREADING +#define __Pyx_PyProbablyModule_GetDict(o) PyObject_GenericGetDict(o, NULL); +#else +PyObject* __Pyx_PyProbablyModule_GetDict(PyObject *o) { + PyObject **dict_ptr = _PyObject_GetDictPtr(o); + return dict_ptr ? __Pyx_XNewRef(*dict_ptr) : NULL; +} +#endif +static int __Pyx_CLineForTraceback(PyThreadState *tstate, int c_line) { + PyObject *use_cline = NULL; + PyObject *ptype, *pvalue, *ptraceback; + PyObject *cython_runtime_dict; + CYTHON_MAYBE_UNUSED_VAR(tstate); + if (unlikely(!__pyx_mstate_global->__pyx_cython_runtime)) { + return c_line; + } + __Pyx_ErrFetchInState(tstate, &ptype, &pvalue, &ptraceback); + cython_runtime_dict = __Pyx_PyProbablyModule_GetDict(__pyx_mstate_global->__pyx_cython_runtime); + if (likely(cython_runtime_dict)) { + __PYX_PY_DICT_LOOKUP_IF_MODIFIED( + use_cline, cython_runtime_dict, + __Pyx_PyDict_SetDefault(cython_runtime_dict, __pyx_mstate_global->__pyx_n_u_cline_in_traceback, Py_False)) + } + if (use_cline == NULL || use_cline == Py_False || (use_cline != Py_True && PyObject_Not(use_cline) != 0)) { + c_line = 0; + } + Py_XDECREF(use_cline); + Py_XDECREF(cython_runtime_dict); + __Pyx_ErrRestoreInState(tstate, ptype, pvalue, ptraceback); + return c_line; +} +#endif + +/* CodeObjectCache (used by AddTraceback) */ +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { + int start = 0, mid = 0, end = count - 1; + if (end >= 0 && code_line > entries[end].code_line) { + return count; + } + while (start < end) { + mid = start + (end - start) / 2; + if (code_line < entries[mid].code_line) { + end = mid; + } else if (code_line > entries[mid].code_line) { + start = mid + 1; + } else { + return mid; + } + } + if (code_line <= entries[mid].code_line) { + return mid; + } else { + return mid + 1; + } +} +static __Pyx_CachedCodeObjectType *__pyx__find_code_object(struct __Pyx_CodeObjectCache *code_cache, int code_line) { + __Pyx_CachedCodeObjectType* code_object; + int pos; + if (unlikely(!code_line) || unlikely(!code_cache->entries)) { + return NULL; + } + pos = __pyx_bisect_code_objects(code_cache->entries, code_cache->count, code_line); + if (unlikely(pos >= code_cache->count) || unlikely(code_cache->entries[pos].code_line != code_line)) { + return NULL; + } + code_object = code_cache->entries[pos].code_object; + Py_INCREF(code_object); + return code_object; +} +static __Pyx_CachedCodeObjectType *__pyx_find_code_object(int code_line) { +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING && !CYTHON_ATOMICS + (void)__pyx__find_code_object; + return NULL; // Most implementation should have atomics. But otherwise, don't make it thread-safe, just miss. +#else + struct __Pyx_CodeObjectCache *code_cache = &__pyx_mstate_global->__pyx_code_cache; +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + __pyx_nonatomic_int_type old_count = __pyx_atomic_incr_acq_rel(&code_cache->accessor_count); + if (old_count < 0) { + __pyx_atomic_decr_acq_rel(&code_cache->accessor_count); + return NULL; + } +#endif + __Pyx_CachedCodeObjectType *result = __pyx__find_code_object(code_cache, code_line); +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + __pyx_atomic_decr_acq_rel(&code_cache->accessor_count); +#endif + return result; +#endif +} +static void __pyx__insert_code_object(struct __Pyx_CodeObjectCache *code_cache, int code_line, __Pyx_CachedCodeObjectType* code_object) +{ + int pos, i; + __Pyx_CodeObjectCacheEntry* entries = code_cache->entries; + if (unlikely(!code_line)) { + return; + } + if (unlikely(!entries)) { + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); + if (likely(entries)) { + code_cache->entries = entries; + code_cache->max_count = 64; + code_cache->count = 1; + entries[0].code_line = code_line; + entries[0].code_object = code_object; + Py_INCREF(code_object); + } + return; + } + pos = __pyx_bisect_code_objects(code_cache->entries, code_cache->count, code_line); + if ((pos < code_cache->count) && unlikely(code_cache->entries[pos].code_line == code_line)) { + __Pyx_CachedCodeObjectType* tmp = entries[pos].code_object; + entries[pos].code_object = code_object; + Py_INCREF(code_object); + Py_DECREF(tmp); + return; + } + if (code_cache->count == code_cache->max_count) { + int new_max = code_cache->max_count + 64; + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( + code_cache->entries, ((size_t)new_max) * sizeof(__Pyx_CodeObjectCacheEntry)); + if (unlikely(!entries)) { + return; + } + code_cache->entries = entries; + code_cache->max_count = new_max; + } + for (i=code_cache->count; i>pos; i--) { + entries[i] = entries[i-1]; + } + entries[pos].code_line = code_line; + entries[pos].code_object = code_object; + code_cache->count++; + Py_INCREF(code_object); +} +static void __pyx_insert_code_object(int code_line, __Pyx_CachedCodeObjectType* code_object) { +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING && !CYTHON_ATOMICS + (void)__pyx__insert_code_object; + return; // Most implementation should have atomics. But otherwise, don't make it thread-safe, just fail. +#else + struct __Pyx_CodeObjectCache *code_cache = &__pyx_mstate_global->__pyx_code_cache; +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + __pyx_nonatomic_int_type expected = 0; + if (!__pyx_atomic_int_cmp_exchange(&code_cache->accessor_count, &expected, INT_MIN)) { + return; + } +#endif + __pyx__insert_code_object(code_cache, code_line, code_object); +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + __pyx_atomic_sub(&code_cache->accessor_count, INT_MIN); +#endif +#endif +} + +/* AddTraceback */ +#include "compile.h" +#include "frameobject.h" +#include "traceback.h" +#if PY_VERSION_HEX >= 0x030b00a6 && !CYTHON_COMPILING_IN_LIMITED_API && !defined(PYPY_VERSION) + #ifndef Py_BUILD_CORE + #define Py_BUILD_CORE 1 + #endif + #include "internal/pycore_frame.h" +#endif +#if CYTHON_COMPILING_IN_LIMITED_API +static PyObject *__Pyx_PyCode_Replace_For_AddTraceback(PyObject *code, PyObject *scratch_dict, + PyObject *firstlineno, PyObject *name) { + PyObject *replace = NULL; + if (unlikely(PyDict_SetItemString(scratch_dict, "co_firstlineno", firstlineno))) return NULL; + if (unlikely(PyDict_SetItemString(scratch_dict, "co_name", name))) return NULL; + replace = PyObject_GetAttrString(code, "replace"); + if (likely(replace)) { + PyObject *result = PyObject_Call(replace, __pyx_mstate_global->__pyx_empty_tuple, scratch_dict); + Py_DECREF(replace); + return result; + } + PyErr_Clear(); + return NULL; +} +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename) { + PyObject *code_object = NULL, *py_py_line = NULL, *py_funcname = NULL, *dict = NULL; + PyObject *replace = NULL, *getframe = NULL, *frame = NULL; + PyObject *exc_type, *exc_value, *exc_traceback; + int success = 0; + if (c_line) { + c_line = __Pyx_CLineForTraceback(__Pyx_PyThreadState_Current, c_line); + } + PyErr_Fetch(&exc_type, &exc_value, &exc_traceback); + code_object = __pyx_find_code_object(c_line ? -c_line : py_line); + if (!code_object) { + code_object = Py_CompileString("_getframe()", filename, Py_eval_input); + if (unlikely(!code_object)) goto bad; + py_py_line = PyLong_FromLong(py_line); + if (unlikely(!py_py_line)) goto bad; + if (c_line) { + py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + } else { + py_funcname = PyUnicode_FromString(funcname); + } + if (unlikely(!py_funcname)) goto bad; + dict = PyDict_New(); + if (unlikely(!dict)) goto bad; + { + PyObject *old_code_object = code_object; + code_object = __Pyx_PyCode_Replace_For_AddTraceback(code_object, dict, py_py_line, py_funcname); + Py_DECREF(old_code_object); + } + if (unlikely(!code_object)) goto bad; + __pyx_insert_code_object(c_line ? -c_line : py_line, code_object); + } else { + dict = PyDict_New(); + } + getframe = PySys_GetObject("_getframe"); + if (unlikely(!getframe)) goto bad; + if (unlikely(PyDict_SetItemString(dict, "_getframe", getframe))) goto bad; + frame = PyEval_EvalCode(code_object, dict, dict); + if (unlikely(!frame) || frame == Py_None) goto bad; + success = 1; + bad: + PyErr_Restore(exc_type, exc_value, exc_traceback); + Py_XDECREF(code_object); + Py_XDECREF(py_py_line); + Py_XDECREF(py_funcname); + Py_XDECREF(dict); + Py_XDECREF(replace); + if (success) { + PyTraceBack_Here( + (struct _frame*)frame); + } + Py_XDECREF(frame); +} +#else +static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( + const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = NULL; + PyObject *py_funcname = NULL; + if (c_line) { + py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + if (!py_funcname) goto bad; + funcname = PyUnicode_AsUTF8(py_funcname); + if (!funcname) goto bad; + } + py_code = PyCode_NewEmpty(filename, funcname, py_line); + Py_XDECREF(py_funcname); + return py_code; +bad: + Py_XDECREF(py_funcname); + return NULL; +} +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyFrameObject *py_frame = 0; + PyThreadState *tstate = __Pyx_PyThreadState_Current; + PyObject *ptype, *pvalue, *ptraceback; + if (c_line) { + c_line = __Pyx_CLineForTraceback(tstate, c_line); + } + py_code = __pyx_find_code_object(c_line ? -c_line : py_line); + if (!py_code) { + __Pyx_ErrFetchInState(tstate, &ptype, &pvalue, &ptraceback); + py_code = __Pyx_CreateCodeObjectForTraceback( + funcname, c_line, py_line, filename); + if (!py_code) { + /* If the code object creation fails, then we should clear the + fetched exception references and propagate the new exception */ + Py_XDECREF(ptype); + Py_XDECREF(pvalue); + Py_XDECREF(ptraceback); + goto bad; + } + __Pyx_ErrRestoreInState(tstate, ptype, pvalue, ptraceback); + __pyx_insert_code_object(c_line ? -c_line : py_line, py_code); + } + py_frame = PyFrame_New( + tstate, /*PyThreadState *tstate,*/ + py_code, /*PyCodeObject *code,*/ + __pyx_mstate_global->__pyx_d, /*PyObject *globals,*/ + 0 /*PyObject *locals*/ + ); + if (!py_frame) goto bad; + __Pyx_PyFrame_SetLineNumber(py_frame, py_line); + PyTraceBack_Here(py_frame); +bad: + Py_XDECREF(py_code); + Py_XDECREF(py_frame); +} +#endif + +/* CheckUnpickleChecksum */ +static void __Pyx_RaiseUnpickleChecksumError(long checksum, long checksum1, long checksum2, long checksum3, const char *members) { + PyObject *pickle_module = PyImport_ImportModule("pickle"); + if (unlikely(!pickle_module)) return; + PyObject *pickle_error = PyObject_GetAttrString(pickle_module, "PickleError"); + Py_DECREF(pickle_module); + if (unlikely(!pickle_error)) return; + if (checksum2 == checksum1) { + PyErr_Format(pickle_error, "Incompatible checksums (0x%x vs (0x%x) = (%s))", + checksum, checksum1, members); + } else if (checksum3 == checksum2) { + PyErr_Format(pickle_error, "Incompatible checksums (0x%x vs (0x%x, 0x%x) = (%s))", + checksum, checksum1, checksum2, members); + } else { + PyErr_Format(pickle_error, "Incompatible checksums (0x%x vs (0x%x, 0x%x, 0x%x) = (%s))", + checksum, checksum1, checksum2, checksum3, members); + } + Py_DECREF(pickle_error); +} +static int __Pyx_CheckUnpickleChecksum(long checksum, long checksum1, long checksum2, long checksum3, const char *members) { + int found = 0; + found |= checksum1 == checksum; + found |= checksum2 == checksum; + found |= checksum3 == checksum; + if (likely(found)) + return 0; + __Pyx_RaiseUnpickleChecksumError(checksum, checksum1, checksum2, checksum3, members); + return -1; +} + +/* CIntFromPyVerify */ +#define __PYX_VERIFY_RETURN_INT(target_type, func_type, func_value)\ + __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 0) +#define __PYX_VERIFY_RETURN_INT_EXC(target_type, func_type, func_value)\ + __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 1) +#define __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, exc)\ + {\ + func_type value = func_value;\ + if (sizeof(target_type) < sizeof(func_type)) {\ + if (unlikely(value != (func_type) (target_type) value)) {\ + func_type zero = 0;\ + if (exc && unlikely(value == (func_type)-1 && PyErr_Occurred()))\ + return (target_type) -1;\ + if (is_unsigned && unlikely(value < zero))\ + goto raise_neg_overflow;\ + else\ + goto raise_overflow;\ + }\ + }\ + return (target_type) value;\ + } + +/* CIntFromPy */ +static CYTHON_INLINE int __Pyx_PyLong_As_int(PyObject *x) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const int neg_one = (int) -1, const_zero = (int) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (unlikely(!PyLong_Check(x))) { + int val; + PyObject *tmp = __Pyx_PyNumber_Long(x); + if (!tmp) return (int) -1; + val = __Pyx_PyLong_As_int(tmp); + Py_DECREF(tmp); + return val; + } + if (is_unsigned) { +#if CYTHON_USE_PYLONG_INTERNALS + if (unlikely(__Pyx_PyLong_IsNeg(x))) { + goto raise_neg_overflow; + } else if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(int, __Pyx_compact_upylong, __Pyx_PyLong_CompactValueUnsigned(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_DigitCount(x)) { + case 2: + if ((8 * sizeof(int) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) >= 2 * PyLong_SHIFT)) { + return (int) (((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); + } + } + break; + case 3: + if ((8 * sizeof(int) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) >= 3 * PyLong_SHIFT)) { + return (int) (((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); + } + } + break; + case 4: + if ((8 * sizeof(int) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) >= 4 * PyLong_SHIFT)) { + return (int) (((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); + } + } + break; + } + } +#endif +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030C00A7 + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } +#else + { + int result = PyObject_RichCompareBool(x, Py_False, Py_LT); + if (unlikely(result < 0)) + return (int) -1; + if (unlikely(result == 1)) + goto raise_neg_overflow; + } +#endif + if ((sizeof(int) <= sizeof(unsigned long))) { + __PYX_VERIFY_RETURN_INT_EXC(int, unsigned long, PyLong_AsUnsignedLong(x)) + } else if ((sizeof(int) <= sizeof(unsigned PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(int, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) + } + } else { +#if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(int, __Pyx_compact_pylong, __Pyx_PyLong_CompactValue(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_SignedDigitCount(x)) { + case -2: + if ((8 * sizeof(int) - 1 > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 2 * PyLong_SHIFT)) { + return (int) (((int)-1)*(((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case 2: + if ((8 * sizeof(int) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 2 * PyLong_SHIFT)) { + return (int) ((((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case -3: + if ((8 * sizeof(int) - 1 > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 3 * PyLong_SHIFT)) { + return (int) (((int)-1)*(((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case 3: + if ((8 * sizeof(int) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 3 * PyLong_SHIFT)) { + return (int) ((((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case -4: + if ((8 * sizeof(int) - 1 > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 4 * PyLong_SHIFT)) { + return (int) (((int)-1)*(((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case 4: + if ((8 * sizeof(int) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 4 * PyLong_SHIFT)) { + return (int) ((((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + } + } +#endif + if ((sizeof(int) <= sizeof(long))) { + __PYX_VERIFY_RETURN_INT_EXC(int, long, PyLong_AsLong(x)) + } else if ((sizeof(int) <= sizeof(PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(int, PY_LONG_LONG, PyLong_AsLongLong(x)) + } + } + { + int val; + int ret = -1; +#if PY_VERSION_HEX >= 0x030d00A6 && !CYTHON_COMPILING_IN_LIMITED_API + Py_ssize_t bytes_copied = PyLong_AsNativeBytes( + x, &val, sizeof(val), Py_ASNATIVEBYTES_NATIVE_ENDIAN | (is_unsigned ? Py_ASNATIVEBYTES_UNSIGNED_BUFFER | Py_ASNATIVEBYTES_REJECT_NEGATIVE : 0)); + if (unlikely(bytes_copied == -1)) { + } else if (unlikely(bytes_copied > (Py_ssize_t) sizeof(val))) { + goto raise_overflow; + } else { + ret = 0; + } +#elif PY_VERSION_HEX < 0x030d0000 && !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API) || defined(_PyLong_AsByteArray) + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + ret = _PyLong_AsByteArray((PyLongObject *)x, + bytes, sizeof(val), + is_little, !is_unsigned); +#else + PyObject *v; + PyObject *stepval = NULL, *mask = NULL, *shift = NULL; + int bits, remaining_bits, is_negative = 0; + int chunk_size = (sizeof(long) < 8) ? 30 : 62; + if (likely(PyLong_CheckExact(x))) { + v = __Pyx_NewRef(x); + } else { + v = PyNumber_Long(x); + if (unlikely(!v)) return (int) -1; + assert(PyLong_CheckExact(v)); + } + { + int result = PyObject_RichCompareBool(v, Py_False, Py_LT); + if (unlikely(result < 0)) { + Py_DECREF(v); + return (int) -1; + } + is_negative = result == 1; + } + if (is_unsigned && unlikely(is_negative)) { + Py_DECREF(v); + goto raise_neg_overflow; + } else if (is_negative) { + stepval = PyNumber_Invert(v); + Py_DECREF(v); + if (unlikely(!stepval)) + return (int) -1; + } else { + stepval = v; + } + v = NULL; + val = (int) 0; + mask = PyLong_FromLong((1L << chunk_size) - 1); if (unlikely(!mask)) goto done; + shift = PyLong_FromLong(chunk_size); if (unlikely(!shift)) goto done; + for (bits = 0; bits < (int) sizeof(int) * 8 - chunk_size; bits += chunk_size) { + PyObject *tmp, *digit; + long idigit; + digit = PyNumber_And(stepval, mask); + if (unlikely(!digit)) goto done; + idigit = PyLong_AsLong(digit); + Py_DECREF(digit); + if (unlikely(idigit < 0)) goto done; + val |= ((int) idigit) << bits; + tmp = PyNumber_Rshift(stepval, shift); + if (unlikely(!tmp)) goto done; + Py_DECREF(stepval); stepval = tmp; + } + Py_DECREF(shift); shift = NULL; + Py_DECREF(mask); mask = NULL; + { + long idigit = PyLong_AsLong(stepval); + if (unlikely(idigit < 0)) goto done; + remaining_bits = ((int) sizeof(int) * 8) - bits - (is_unsigned ? 0 : 1); + if (unlikely(idigit >= (1L << remaining_bits))) + goto raise_overflow; + val |= ((int) idigit) << bits; + } + if (!is_unsigned) { + if (unlikely(val & (((int) 1) << (sizeof(int) * 8 - 1)))) + goto raise_overflow; + if (is_negative) + val = ~val; + } + ret = 0; + done: + Py_XDECREF(shift); + Py_XDECREF(mask); + Py_XDECREF(stepval); +#endif + if (unlikely(ret)) + return (int) -1; + return val; + } +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to int"); + return (int) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to int"); + return (int) -1; +} + +/* CIntFromPy */ +static CYTHON_INLINE long __Pyx_PyLong_As_long(PyObject *x) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const long neg_one = (long) -1, const_zero = (long) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (unlikely(!PyLong_Check(x))) { + long val; + PyObject *tmp = __Pyx_PyNumber_Long(x); + if (!tmp) return (long) -1; + val = __Pyx_PyLong_As_long(tmp); + Py_DECREF(tmp); + return val; + } + if (is_unsigned) { +#if CYTHON_USE_PYLONG_INTERNALS + if (unlikely(__Pyx_PyLong_IsNeg(x))) { + goto raise_neg_overflow; + } else if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(long, __Pyx_compact_upylong, __Pyx_PyLong_CompactValueUnsigned(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_DigitCount(x)) { + case 2: + if ((8 * sizeof(long) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) >= 2 * PyLong_SHIFT)) { + return (long) (((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); + } + } + break; + case 3: + if ((8 * sizeof(long) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) >= 3 * PyLong_SHIFT)) { + return (long) (((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); + } + } + break; + case 4: + if ((8 * sizeof(long) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) >= 4 * PyLong_SHIFT)) { + return (long) (((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); + } + } + break; + } + } +#endif +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030C00A7 + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } +#else + { + int result = PyObject_RichCompareBool(x, Py_False, Py_LT); + if (unlikely(result < 0)) + return (long) -1; + if (unlikely(result == 1)) + goto raise_neg_overflow; + } +#endif + if ((sizeof(long) <= sizeof(unsigned long))) { + __PYX_VERIFY_RETURN_INT_EXC(long, unsigned long, PyLong_AsUnsignedLong(x)) + } else if ((sizeof(long) <= sizeof(unsigned PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(long, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) + } + } else { +#if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(long, __Pyx_compact_pylong, __Pyx_PyLong_CompactValue(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_SignedDigitCount(x)) { + case -2: + if ((8 * sizeof(long) - 1 > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 2 * PyLong_SHIFT)) { + return (long) (((long)-1)*(((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case 2: + if ((8 * sizeof(long) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 2 * PyLong_SHIFT)) { + return (long) ((((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case -3: + if ((8 * sizeof(long) - 1 > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 3 * PyLong_SHIFT)) { + return (long) (((long)-1)*(((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case 3: + if ((8 * sizeof(long) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 3 * PyLong_SHIFT)) { + return (long) ((((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case -4: + if ((8 * sizeof(long) - 1 > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 4 * PyLong_SHIFT)) { + return (long) (((long)-1)*(((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case 4: + if ((8 * sizeof(long) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 4 * PyLong_SHIFT)) { + return (long) ((((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + } + } +#endif + if ((sizeof(long) <= sizeof(long))) { + __PYX_VERIFY_RETURN_INT_EXC(long, long, PyLong_AsLong(x)) + } else if ((sizeof(long) <= sizeof(PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(long, PY_LONG_LONG, PyLong_AsLongLong(x)) + } + } + { + long val; + int ret = -1; +#if PY_VERSION_HEX >= 0x030d00A6 && !CYTHON_COMPILING_IN_LIMITED_API + Py_ssize_t bytes_copied = PyLong_AsNativeBytes( + x, &val, sizeof(val), Py_ASNATIVEBYTES_NATIVE_ENDIAN | (is_unsigned ? Py_ASNATIVEBYTES_UNSIGNED_BUFFER | Py_ASNATIVEBYTES_REJECT_NEGATIVE : 0)); + if (unlikely(bytes_copied == -1)) { + } else if (unlikely(bytes_copied > (Py_ssize_t) sizeof(val))) { + goto raise_overflow; + } else { + ret = 0; + } +#elif PY_VERSION_HEX < 0x030d0000 && !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API) || defined(_PyLong_AsByteArray) + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + ret = _PyLong_AsByteArray((PyLongObject *)x, + bytes, sizeof(val), + is_little, !is_unsigned); +#else + PyObject *v; + PyObject *stepval = NULL, *mask = NULL, *shift = NULL; + int bits, remaining_bits, is_negative = 0; + int chunk_size = (sizeof(long) < 8) ? 30 : 62; + if (likely(PyLong_CheckExact(x))) { + v = __Pyx_NewRef(x); + } else { + v = PyNumber_Long(x); + if (unlikely(!v)) return (long) -1; + assert(PyLong_CheckExact(v)); + } + { + int result = PyObject_RichCompareBool(v, Py_False, Py_LT); + if (unlikely(result < 0)) { + Py_DECREF(v); + return (long) -1; + } + is_negative = result == 1; + } + if (is_unsigned && unlikely(is_negative)) { + Py_DECREF(v); + goto raise_neg_overflow; + } else if (is_negative) { + stepval = PyNumber_Invert(v); + Py_DECREF(v); + if (unlikely(!stepval)) + return (long) -1; + } else { + stepval = v; + } + v = NULL; + val = (long) 0; + mask = PyLong_FromLong((1L << chunk_size) - 1); if (unlikely(!mask)) goto done; + shift = PyLong_FromLong(chunk_size); if (unlikely(!shift)) goto done; + for (bits = 0; bits < (int) sizeof(long) * 8 - chunk_size; bits += chunk_size) { + PyObject *tmp, *digit; + long idigit; + digit = PyNumber_And(stepval, mask); + if (unlikely(!digit)) goto done; + idigit = PyLong_AsLong(digit); + Py_DECREF(digit); + if (unlikely(idigit < 0)) goto done; + val |= ((long) idigit) << bits; + tmp = PyNumber_Rshift(stepval, shift); + if (unlikely(!tmp)) goto done; + Py_DECREF(stepval); stepval = tmp; + } + Py_DECREF(shift); shift = NULL; + Py_DECREF(mask); mask = NULL; + { + long idigit = PyLong_AsLong(stepval); + if (unlikely(idigit < 0)) goto done; + remaining_bits = ((int) sizeof(long) * 8) - bits - (is_unsigned ? 0 : 1); + if (unlikely(idigit >= (1L << remaining_bits))) + goto raise_overflow; + val |= ((long) idigit) << bits; + } + if (!is_unsigned) { + if (unlikely(val & (((long) 1) << (sizeof(long) * 8 - 1)))) + goto raise_overflow; + if (is_negative) + val = ~val; + } + ret = 0; + done: + Py_XDECREF(shift); + Py_XDECREF(mask); + Py_XDECREF(stepval); +#endif + if (unlikely(ret)) + return (long) -1; + return val; + } +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to long"); + return (long) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to long"); + return (long) -1; +} + +/* PyObjectVectorCallKwBuilder (used by CIntToPy) */ +#if CYTHON_VECTORCALL +static int __Pyx_VectorcallBuilder_AddArg(PyObject *key, PyObject *value, PyObject *builder, PyObject **args, int n) { + (void)__Pyx_PyObject_FastCallDict; + if (__Pyx_PyTuple_SET_ITEM(builder, n, key) != (0)) return -1; + Py_INCREF(key); + args[n] = value; + return 0; +} +CYTHON_UNUSED static int __Pyx_VectorcallBuilder_AddArg_Check(PyObject *key, PyObject *value, PyObject *builder, PyObject **args, int n) { + (void)__Pyx_VectorcallBuilder_AddArgStr; + if (unlikely(!PyUnicode_Check(key))) { + PyErr_SetString(PyExc_TypeError, "keywords must be strings"); + return -1; + } + return __Pyx_VectorcallBuilder_AddArg(key, value, builder, args, n); +} +static int __Pyx_VectorcallBuilder_AddArgStr(const char *key, PyObject *value, PyObject *builder, PyObject **args, int n) { + PyObject *pyKey = PyUnicode_FromString(key); + if (!pyKey) return -1; + return __Pyx_VectorcallBuilder_AddArg(pyKey, value, builder, args, n); +} +#else // CYTHON_VECTORCALL +CYTHON_UNUSED static int __Pyx_VectorcallBuilder_AddArg_Check(PyObject *key, PyObject *value, PyObject *builder, CYTHON_UNUSED PyObject **args, CYTHON_UNUSED int n) { + if (unlikely(!PyUnicode_Check(key))) { + PyErr_SetString(PyExc_TypeError, "keywords must be strings"); + return -1; + } + return PyDict_SetItem(builder, key, value); +} +#endif + +/* CIntToPy */ +static CYTHON_INLINE PyObject* __Pyx_PyLong_From_int(int value) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const int neg_one = (int) -1, const_zero = (int) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(int) < sizeof(long)) { + return PyLong_FromLong((long) value); + } else if (sizeof(int) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); +#if !CYTHON_COMPILING_IN_PYPY + } else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) { + return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); +#endif + } + } else { + if (sizeof(int) <= sizeof(long)) { + return PyLong_FromLong((long) value); + } else if (sizeof(int) <= sizeof(PY_LONG_LONG)) { + return PyLong_FromLongLong((PY_LONG_LONG) value); + } + } + { + unsigned char *bytes = (unsigned char *)&value; +#if !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d00A4 + if (is_unsigned) { + return PyLong_FromUnsignedNativeBytes(bytes, sizeof(value), -1); + } else { + return PyLong_FromNativeBytes(bytes, sizeof(value), -1); + } +#elif !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030d0000 + int one = 1; int little = (int)*(unsigned char *)&one; + return _PyLong_FromByteArray(bytes, sizeof(int), + little, !is_unsigned); +#else + int one = 1; int little = (int)*(unsigned char *)&one; + PyObject *from_bytes, *result = NULL, *kwds = NULL; + PyObject *py_bytes = NULL, *order_str = NULL; + from_bytes = PyObject_GetAttrString((PyObject*)&PyLong_Type, "from_bytes"); + if (!from_bytes) return NULL; + py_bytes = PyBytes_FromStringAndSize((char*)bytes, sizeof(int)); + if (!py_bytes) goto limited_bad; + order_str = PyUnicode_FromString(little ? "little" : "big"); + if (!order_str) goto limited_bad; + { + PyObject *args[3+(CYTHON_VECTORCALL ? 1 : 0)] = { NULL, py_bytes, order_str }; + if (!is_unsigned) { + kwds = __Pyx_MakeVectorcallBuilderKwds(1); + if (!kwds) goto limited_bad; + if (__Pyx_VectorcallBuilder_AddArgStr("signed", __Pyx_NewRef(Py_True), kwds, args+3, 0) < 0) goto limited_bad; + } + result = __Pyx_Object_Vectorcall_CallFromBuilder(from_bytes, args+1, 2 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET, kwds); + } + limited_bad: + Py_XDECREF(kwds); + Py_XDECREF(order_str); + Py_XDECREF(py_bytes); + Py_XDECREF(from_bytes); + return result; +#endif + } +} + +/* CIntToPy */ +static CYTHON_INLINE PyObject* __Pyx_PyLong_From_long(long value) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const long neg_one = (long) -1, const_zero = (long) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(long) < sizeof(long)) { + return PyLong_FromLong((long) value); + } else if (sizeof(long) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); +#if !CYTHON_COMPILING_IN_PYPY + } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { + return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); +#endif + } + } else { + if (sizeof(long) <= sizeof(long)) { + return PyLong_FromLong((long) value); + } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { + return PyLong_FromLongLong((PY_LONG_LONG) value); + } + } + { + unsigned char *bytes = (unsigned char *)&value; +#if !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d00A4 + if (is_unsigned) { + return PyLong_FromUnsignedNativeBytes(bytes, sizeof(value), -1); + } else { + return PyLong_FromNativeBytes(bytes, sizeof(value), -1); + } +#elif !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030d0000 + int one = 1; int little = (int)*(unsigned char *)&one; + return _PyLong_FromByteArray(bytes, sizeof(long), + little, !is_unsigned); +#else + int one = 1; int little = (int)*(unsigned char *)&one; + PyObject *from_bytes, *result = NULL, *kwds = NULL; + PyObject *py_bytes = NULL, *order_str = NULL; + from_bytes = PyObject_GetAttrString((PyObject*)&PyLong_Type, "from_bytes"); + if (!from_bytes) return NULL; + py_bytes = PyBytes_FromStringAndSize((char*)bytes, sizeof(long)); + if (!py_bytes) goto limited_bad; + order_str = PyUnicode_FromString(little ? "little" : "big"); + if (!order_str) goto limited_bad; + { + PyObject *args[3+(CYTHON_VECTORCALL ? 1 : 0)] = { NULL, py_bytes, order_str }; + if (!is_unsigned) { + kwds = __Pyx_MakeVectorcallBuilderKwds(1); + if (!kwds) goto limited_bad; + if (__Pyx_VectorcallBuilder_AddArgStr("signed", __Pyx_NewRef(Py_True), kwds, args+3, 0) < 0) goto limited_bad; + } + result = __Pyx_Object_Vectorcall_CallFromBuilder(from_bytes, args+1, 2 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET, kwds); + } + limited_bad: + Py_XDECREF(kwds); + Py_XDECREF(order_str); + Py_XDECREF(py_bytes); + Py_XDECREF(from_bytes); + return result; +#endif + } +} + +/* PyObjectCallMethod1 */ +#if !(CYTHON_VECTORCALL && (__PYX_LIMITED_VERSION_HEX >= 0x030C0000 || (!CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x03090000))) +static PyObject* __Pyx__PyObject_CallMethod1(PyObject* method, PyObject* arg) { + PyObject *result = __Pyx_PyObject_CallOneArg(method, arg); + Py_DECREF(method); + return result; +} +#endif +static PyObject* __Pyx_PyObject_CallMethod1(PyObject* obj, PyObject* method_name, PyObject* arg) { +#if CYTHON_VECTORCALL && (__PYX_LIMITED_VERSION_HEX >= 0x030C0000 || (!CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x03090000)) + PyObject *args[2] = {obj, arg}; + (void) __Pyx_PyObject_CallOneArg; + (void) __Pyx_PyObject_Call2Args; + return PyObject_VectorcallMethod(method_name, args, 2 | PY_VECTORCALL_ARGUMENTS_OFFSET, NULL); +#else + PyObject *method = NULL, *result; + int is_method = __Pyx_PyObject_GetMethod(obj, method_name, &method); + if (likely(is_method)) { + result = __Pyx_PyObject_Call2Args(method, obj, arg); + Py_DECREF(method); + return result; + } + if (unlikely(!method)) return NULL; + return __Pyx__PyObject_CallMethod1(method, arg); +#endif +} + +/* UpdateUnpickledDict */ +static int __Pyx__UpdateUnpickledDict(PyObject *obj, PyObject *state, Py_ssize_t index) { + PyObject *state_dict = __Pyx_PySequence_ITEM(state, index); + if (unlikely(!state_dict)) { + return -1; + } + int non_empty = PyObject_IsTrue(state_dict); + if (non_empty == 0) { + Py_DECREF(state_dict); + return 0; + } else if (unlikely(non_empty == -1)) { + return -1; + } + PyObject *dict; + #if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000 + dict = PyObject_GetAttrString(obj, "__dict__"); + #else + dict = PyObject_GenericGetDict(obj, NULL); + #endif + if (unlikely(!dict)) { + Py_DECREF(state_dict); + return -1; + } + int result; + if (likely(PyDict_CheckExact(dict))) { + result = PyDict_Update(dict, state_dict); + } else { + PyObject *obj_result = __Pyx_PyObject_CallMethod1(dict, __pyx_mstate_global->__pyx_n_u_update, state_dict); + if (likely(obj_result)) { + Py_DECREF(obj_result); + result = 0; + } else { + result = -1; + } + } + Py_DECREF(state_dict); + Py_DECREF(dict); + return result; +} +static int __Pyx_UpdateUnpickledDict(PyObject *obj, PyObject *state, Py_ssize_t index) { + Py_ssize_t state_size = __Pyx_PyTuple_GET_SIZE(state); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(state_size == -1)) return -1; + #endif + if (state_size <= index) { + return 0; + } + return __Pyx__UpdateUnpickledDict(obj, state, index); +} + +/* FormatTypeName */ +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030d0000 +static __Pyx_TypeName +__Pyx_PyType_GetFullyQualifiedName(PyTypeObject* tp) +{ + PyObject *module = NULL, *name = NULL, *result = NULL; + #if __PYX_LIMITED_VERSION_HEX < 0x030b0000 + name = __Pyx_PyObject_GetAttrStr((PyObject *)tp, + __pyx_mstate_global->__pyx_n_u_qualname); + #else + name = PyType_GetQualName(tp); + #endif + if (unlikely(name == NULL) || unlikely(!PyUnicode_Check(name))) goto bad; + module = __Pyx_PyObject_GetAttrStr((PyObject *)tp, + __pyx_mstate_global->__pyx_n_u_module); + if (unlikely(module == NULL) || unlikely(!PyUnicode_Check(module))) goto bad; + if (PyUnicode_CompareWithASCIIString(module, "builtins") == 0) { + result = name; + name = NULL; + goto done; + } + result = PyUnicode_FromFormat("%U.%U", module, name); + if (unlikely(result == NULL)) goto bad; + done: + Py_XDECREF(name); + Py_XDECREF(module); + return result; + bad: + PyErr_Clear(); + if (name) { + result = name; + name = NULL; + } else { + result = __Pyx_NewRef(__pyx_mstate_global->__pyx_kp_u__4); + } + goto done; +} +#endif + +/* FastTypeChecks */ +#if CYTHON_COMPILING_IN_CPYTHON +static int __Pyx_InBases(PyTypeObject *a, PyTypeObject *b) { + while (a) { + a = __Pyx_PyType_GetSlot(a, tp_base, PyTypeObject*); + if (a == b) + return 1; + } + return b == &PyBaseObject_Type; +} +static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b) { + PyObject *mro; + if (a == b) return 1; + mro = a->tp_mro; + if (likely(mro)) { + Py_ssize_t i, n; + n = PyTuple_GET_SIZE(mro); + for (i = 0; i < n; i++) { + if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b) + return 1; + } + return 0; + } + return __Pyx_InBases(a, b); +} +static CYTHON_INLINE int __Pyx_IsAnySubtype2(PyTypeObject *cls, PyTypeObject *a, PyTypeObject *b) { + PyObject *mro; + if (cls == a || cls == b) return 1; + mro = cls->tp_mro; + if (likely(mro)) { + Py_ssize_t i, n; + n = PyTuple_GET_SIZE(mro); + for (i = 0; i < n; i++) { + PyObject *base = PyTuple_GET_ITEM(mro, i); + if (base == (PyObject *)a || base == (PyObject *)b) + return 1; + } + return 0; + } + return __Pyx_InBases(cls, a) || __Pyx_InBases(cls, b); +} +static CYTHON_INLINE int __Pyx_inner_PyErr_GivenExceptionMatches2(PyObject *err, PyObject* exc_type1, PyObject *exc_type2) { + if (exc_type1) { + return __Pyx_IsAnySubtype2((PyTypeObject*)err, (PyTypeObject*)exc_type1, (PyTypeObject*)exc_type2); + } else { + return __Pyx_IsSubtype((PyTypeObject*)err, (PyTypeObject*)exc_type2); + } +} +static int __Pyx_PyErr_GivenExceptionMatchesTuple(PyObject *exc_type, PyObject *tuple) { + Py_ssize_t i, n; + assert(PyExceptionClass_Check(exc_type)); + n = PyTuple_GET_SIZE(tuple); + for (i=0; i>= 8; + ++i; + } + __Pyx_cached_runtime_version = version; + } +} +#endif +static unsigned long __Pyx_get_runtime_version(void) { +#if __PYX_LIMITED_VERSION_HEX >= 0x030b0000 + return Py_Version & ~0xFFUL; +#else + return __Pyx_cached_runtime_version; +#endif +} + +/* CheckBinaryVersion */ +static int __Pyx_check_binary_version(unsigned long ct_version, unsigned long rt_version, int allow_newer) { + const unsigned long MAJOR_MINOR = 0xFFFF0000UL; + if ((rt_version & MAJOR_MINOR) == (ct_version & MAJOR_MINOR)) + return 0; + if (likely(allow_newer && (rt_version & MAJOR_MINOR) > (ct_version & MAJOR_MINOR))) + return 1; + { + char message[200]; + PyOS_snprintf(message, sizeof(message), + "compile time Python version %d.%d " + "of module '%.100s' " + "%s " + "runtime version %d.%d", + (int) (ct_version >> 24), (int) ((ct_version >> 16) & 0xFF), + __Pyx_MODULE_NAME, + (allow_newer) ? "was newer than" : "does not match", + (int) (rt_version >> 24), (int) ((rt_version >> 16) & 0xFF) + ); + return PyErr_WarnEx(NULL, message, 1); + } +} + +/* NewCodeObj */ +#if CYTHON_COMPILING_IN_LIMITED_API + static PyObject* __Pyx__PyCode_New(int a, int p, int k, int l, int s, int f, + PyObject *code, PyObject *c, PyObject* n, PyObject *v, + PyObject *fv, PyObject *cell, PyObject* fn, + PyObject *name, int fline, PyObject *lnos) { + PyObject *exception_table = NULL; + PyObject *types_module=NULL, *code_type=NULL, *result=NULL; + #if __PYX_LIMITED_VERSION_HEX < 0x030b0000 + PyObject *version_info; + PyObject *py_minor_version = NULL; + #endif + long minor_version = 0; + PyObject *type, *value, *traceback; + PyErr_Fetch(&type, &value, &traceback); + #if __PYX_LIMITED_VERSION_HEX >= 0x030b0000 + minor_version = 11; + #else + if (!(version_info = PySys_GetObject("version_info"))) goto end; + if (!(py_minor_version = PySequence_GetItem(version_info, 1))) goto end; + minor_version = PyLong_AsLong(py_minor_version); + Py_DECREF(py_minor_version); + if (minor_version == -1 && PyErr_Occurred()) goto end; + #endif + if (!(types_module = PyImport_ImportModule("types"))) goto end; + if (!(code_type = PyObject_GetAttrString(types_module, "CodeType"))) goto end; + if (minor_version <= 7) { + (void)p; + result = PyObject_CallFunction(code_type, "iiiiiOOOOOOiOOO", a, k, l, s, f, code, + c, n, v, fn, name, fline, lnos, fv, cell); + } else if (minor_version <= 10) { + result = PyObject_CallFunction(code_type, "iiiiiiOOOOOOiOOO", a,p, k, l, s, f, code, + c, n, v, fn, name, fline, lnos, fv, cell); + } else { + if (!(exception_table = PyBytes_FromStringAndSize(NULL, 0))) goto end; + result = PyObject_CallFunction(code_type, "iiiiiiOOOOOOOiOOOO", a,p, k, l, s, f, code, + c, n, v, fn, name, name, fline, lnos, exception_table, fv, cell); + } + end: + Py_XDECREF(code_type); + Py_XDECREF(exception_table); + Py_XDECREF(types_module); + if (type) { + PyErr_Restore(type, value, traceback); + } + return result; + } +#elif PY_VERSION_HEX >= 0x030B0000 + static PyCodeObject* __Pyx__PyCode_New(int a, int p, int k, int l, int s, int f, + PyObject *code, PyObject *c, PyObject* n, PyObject *v, + PyObject *fv, PyObject *cell, PyObject* fn, + PyObject *name, int fline, PyObject *lnos) { + PyCodeObject *result; + result = + #if PY_VERSION_HEX >= 0x030C0000 + PyUnstable_Code_NewWithPosOnlyArgs + #else + PyCode_NewWithPosOnlyArgs + #endif + (a, p, k, l, s, f, code, c, n, v, fv, cell, fn, name, name, fline, lnos, __pyx_mstate_global->__pyx_empty_bytes); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030c00A1 + if (likely(result)) + result->_co_firsttraceable = 0; + #endif + return result; + } +#elif !CYTHON_COMPILING_IN_PYPY + #define __Pyx__PyCode_New(a, p, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ + PyCode_NewWithPosOnlyArgs(a, p, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) +#else + #define __Pyx__PyCode_New(a, p, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ + PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) +#endif +static PyObject* __Pyx_PyCode_New( + const __Pyx_PyCode_New_function_description descr, + PyObject * const *varnames, + PyObject *filename, + PyObject *funcname, + PyObject *line_table, + PyObject *tuple_dedup_map +) { + PyObject *code_obj = NULL, *varnames_tuple_dedup = NULL, *code_bytes = NULL; + Py_ssize_t var_count = (Py_ssize_t) descr.nlocals; + PyObject *varnames_tuple = PyTuple_New(var_count); + if (unlikely(!varnames_tuple)) return NULL; + for (Py_ssize_t i=0; i < var_count; i++) { + Py_INCREF(varnames[i]); + if (__Pyx_PyTuple_SET_ITEM(varnames_tuple, i, varnames[i]) != (0)) goto done; + } + #if CYTHON_COMPILING_IN_LIMITED_API + varnames_tuple_dedup = PyDict_GetItem(tuple_dedup_map, varnames_tuple); + if (!varnames_tuple_dedup) { + if (unlikely(PyDict_SetItem(tuple_dedup_map, varnames_tuple, varnames_tuple) < 0)) goto done; + varnames_tuple_dedup = varnames_tuple; + } + #else + varnames_tuple_dedup = PyDict_SetDefault(tuple_dedup_map, varnames_tuple, varnames_tuple); + if (unlikely(!varnames_tuple_dedup)) goto done; + #endif + #if CYTHON_AVOID_BORROWED_REFS + Py_INCREF(varnames_tuple_dedup); + #endif + if (__PYX_LIMITED_VERSION_HEX >= (0x030b0000) && line_table != NULL && !CYTHON_COMPILING_IN_GRAAL) { + Py_ssize_t line_table_length = __Pyx_PyBytes_GET_SIZE(line_table); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(line_table_length == -1)) goto done; + #endif + Py_ssize_t code_len = (line_table_length * 2 + 4) & ~3LL; + code_bytes = PyBytes_FromStringAndSize(NULL, code_len); + if (unlikely(!code_bytes)) goto done; + char* c_code_bytes = PyBytes_AsString(code_bytes); + if (unlikely(!c_code_bytes)) goto done; + memset(c_code_bytes, 0, (size_t) code_len); + } + code_obj = (PyObject*) __Pyx__PyCode_New( + (int) descr.argcount, + (int) descr.num_posonly_args, + (int) descr.num_kwonly_args, + (int) descr.nlocals, + 0, + (int) descr.flags, + code_bytes ? code_bytes : __pyx_mstate_global->__pyx_empty_bytes, + __pyx_mstate_global->__pyx_empty_tuple, + __pyx_mstate_global->__pyx_empty_tuple, + varnames_tuple_dedup, + __pyx_mstate_global->__pyx_empty_tuple, + __pyx_mstate_global->__pyx_empty_tuple, + filename, + funcname, + (int) descr.first_line, + (__PYX_LIMITED_VERSION_HEX >= (0x030b0000) && line_table) ? line_table : __pyx_mstate_global->__pyx_empty_bytes + ); +done: + Py_XDECREF(code_bytes); + #if CYTHON_AVOID_BORROWED_REFS + Py_XDECREF(varnames_tuple_dedup); + #endif + Py_DECREF(varnames_tuple); + return code_obj; +} + +/* DecompressString */ +static PyObject *__Pyx_DecompressString(const char *s, Py_ssize_t length, int algo) { + PyObject *module = NULL, *decompress, *compressed_bytes, *decompressed; + const char* module_name = algo == 3 ? "compression.zstd" : algo == 2 ? "bz2" : "zlib"; + PyObject *methodname = PyUnicode_FromString("decompress"); + if (unlikely(!methodname)) return NULL; + #if __PYX_LIMITED_VERSION_HEX >= 0x030e0000 + if (algo == 3) { + PyObject *fromlist = Py_BuildValue("[O]", methodname); + if (unlikely(!fromlist)) goto bad; + module = PyImport_ImportModuleLevel("compression.zstd", NULL, NULL, fromlist, 0); + Py_DECREF(fromlist); + } else + #endif + module = PyImport_ImportModule(module_name); + if (unlikely(!module)) goto import_failed; + decompress = PyObject_GetAttr(module, methodname); + if (unlikely(!decompress)) goto import_failed; + { + #ifdef __cplusplus + char *memview_bytes = const_cast(s); + #else + #if defined(__clang__) + #pragma clang diagnostic push + #pragma clang diagnostic ignored "-Wcast-qual" + #elif !defined(__INTEL_COMPILER) && defined(__GNUC__) + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wcast-qual" + #endif + char *memview_bytes = (char*) s; + #if defined(__clang__) + #pragma clang diagnostic pop + #elif !defined(__INTEL_COMPILER) && defined(__GNUC__) + #pragma GCC diagnostic pop + #endif + #endif + #if CYTHON_COMPILING_IN_LIMITED_API && !defined(PyBUF_READ) + int memview_flags = 0x100; + #else + int memview_flags = PyBUF_READ; + #endif + compressed_bytes = PyMemoryView_FromMemory(memview_bytes, length, memview_flags); + } + if (unlikely(!compressed_bytes)) { + Py_DECREF(decompress); + goto bad; + } + decompressed = PyObject_CallFunctionObjArgs(decompress, compressed_bytes, NULL); + Py_DECREF(compressed_bytes); + Py_DECREF(decompress); + Py_DECREF(module); + Py_DECREF(methodname); + return decompressed; +import_failed: + PyErr_Format(PyExc_ImportError, + "Failed to import '%.20s.decompress' - cannot initialise module strings. " + "String compression was configured with the C macro 'CYTHON_COMPRESS_STRINGS=%d'.", + module_name, algo); +bad: + Py_XDECREF(module); + Py_DECREF(methodname); + return NULL; +} + +#include +static CYTHON_INLINE Py_ssize_t __Pyx_ssize_strlen(const char *s) { + size_t len = strlen(s); + if (unlikely(len > (size_t) PY_SSIZE_T_MAX)) { + PyErr_SetString(PyExc_OverflowError, "byte string is too long"); + return -1; + } + return (Py_ssize_t) len; +} +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char* c_str) { + Py_ssize_t len = __Pyx_ssize_strlen(c_str); + if (unlikely(len < 0)) return NULL; + return __Pyx_PyUnicode_FromStringAndSize(c_str, len); +} +static CYTHON_INLINE PyObject* __Pyx_PyByteArray_FromString(const char* c_str) { + Py_ssize_t len = __Pyx_ssize_strlen(c_str); + if (unlikely(len < 0)) return NULL; + return PyByteArray_FromStringAndSize(c_str, len); +} +static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject* o) { + Py_ssize_t ignore; + return __Pyx_PyObject_AsStringAndSize(o, &ignore); +} +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 +static CYTHON_INLINE const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *length) { + if (unlikely(__Pyx_PyUnicode_READY(o) == -1)) return NULL; +#if CYTHON_COMPILING_IN_LIMITED_API + { + const char* result; + Py_ssize_t unicode_length; + CYTHON_MAYBE_UNUSED_VAR(unicode_length); // only for __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + #if __PYX_LIMITED_VERSION_HEX < 0x030A0000 + if (unlikely(PyArg_Parse(o, "s#", &result, length) < 0)) return NULL; + #else + result = PyUnicode_AsUTF8AndSize(o, length); + #endif + #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + unicode_length = PyUnicode_GetLength(o); + if (unlikely(unicode_length < 0)) return NULL; + if (unlikely(unicode_length != *length)) { + PyUnicode_AsASCIIString(o); + return NULL; + } + #endif + return result; + } +#else +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + if (likely(PyUnicode_IS_ASCII(o))) { + *length = PyUnicode_GET_LENGTH(o); + return PyUnicode_AsUTF8(o); + } else { + PyUnicode_AsASCIIString(o); + return NULL; + } +#else + return PyUnicode_AsUTF8AndSize(o, length); +#endif +#endif +} +#endif +static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 + if (PyUnicode_Check(o)) { + return __Pyx_PyUnicode_AsStringAndSize(o, length); + } else +#endif + if (PyByteArray_Check(o)) { +#if (CYTHON_ASSUME_SAFE_SIZE && CYTHON_ASSUME_SAFE_MACROS) || (CYTHON_COMPILING_IN_PYPY && (defined(PyByteArray_AS_STRING) && defined(PyByteArray_GET_SIZE))) + *length = PyByteArray_GET_SIZE(o); + return PyByteArray_AS_STRING(o); +#else + *length = PyByteArray_Size(o); + if (*length == -1) return NULL; + return PyByteArray_AsString(o); +#endif + } else + { + char* result; + int r = PyBytes_AsStringAndSize(o, &result, length); + if (unlikely(r < 0)) { + return NULL; + } else { + return result; + } + } +} +static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { + int is_true = x == Py_True; + if (is_true | (x == Py_False) | (x == Py_None)) return is_true; + else return PyObject_IsTrue(x); +} +static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject* x) { + int retval; + if (unlikely(!x)) return -1; + retval = __Pyx_PyObject_IsTrue(x); + Py_DECREF(x); + return retval; +} +static PyObject* __Pyx_PyNumber_LongWrongResultType(PyObject* result) { + __Pyx_TypeName result_type_name = __Pyx_PyType_GetFullyQualifiedName(Py_TYPE(result)); + if (PyLong_Check(result)) { + if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1, + "__int__ returned non-int (type " __Pyx_FMT_TYPENAME "). " + "The ability to return an instance of a strict subclass of int is deprecated, " + "and may be removed in a future version of Python.", + result_type_name)) { + __Pyx_DECREF_TypeName(result_type_name); + Py_DECREF(result); + return NULL; + } + __Pyx_DECREF_TypeName(result_type_name); + return result; + } + PyErr_Format(PyExc_TypeError, + "__int__ returned non-int (type " __Pyx_FMT_TYPENAME ")", + result_type_name); + __Pyx_DECREF_TypeName(result_type_name); + Py_DECREF(result); + return NULL; +} +static CYTHON_INLINE PyObject* __Pyx_PyNumber_Long(PyObject* x) { +#if CYTHON_USE_TYPE_SLOTS + PyNumberMethods *m; +#endif + PyObject *res = NULL; + if (likely(PyLong_Check(x))) + return __Pyx_NewRef(x); +#if CYTHON_USE_TYPE_SLOTS + m = Py_TYPE(x)->tp_as_number; + if (likely(m && m->nb_int)) { + res = m->nb_int(x); + } +#else + if (!PyBytes_CheckExact(x) && !PyUnicode_CheckExact(x)) { + res = PyNumber_Long(x); + } +#endif + if (likely(res)) { + if (unlikely(!PyLong_CheckExact(res))) { + return __Pyx_PyNumber_LongWrongResultType(res); + } + } + else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_TypeError, + "an integer is required"); + } + return res; +} +static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { + Py_ssize_t ival; + PyObject *x; + if (likely(PyLong_CheckExact(b))) { + #if CYTHON_USE_PYLONG_INTERNALS + if (likely(__Pyx_PyLong_IsCompact(b))) { + return __Pyx_PyLong_CompactValue(b); + } else { + const digit* digits = __Pyx_PyLong_Digits(b); + const Py_ssize_t size = __Pyx_PyLong_SignedDigitCount(b); + switch (size) { + case 2: + if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { + return (Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case -2: + if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { + return -(Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case 3: + if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { + return (Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case -3: + if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { + return -(Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case 4: + if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { + return (Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case -4: + if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { + return -(Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + } + } + #endif + return PyLong_AsSsize_t(b); + } + x = PyNumber_Index(b); + if (!x) return -1; + ival = PyLong_AsSsize_t(x); + Py_DECREF(x); + return ival; +} +static CYTHON_INLINE Py_hash_t __Pyx_PyIndex_AsHash_t(PyObject* o) { + if (sizeof(Py_hash_t) == sizeof(Py_ssize_t)) { + return (Py_hash_t) __Pyx_PyIndex_AsSsize_t(o); + } else { + Py_ssize_t ival; + PyObject *x; + x = PyNumber_Index(o); + if (!x) return -1; + ival = PyLong_AsLong(x); + Py_DECREF(x); + return ival; + } +} +static CYTHON_INLINE PyObject *__Pyx_Owned_Py_None(int b) { + CYTHON_UNUSED_VAR(b); + return __Pyx_NewRef(Py_None); +} +static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b) { + return __Pyx_NewRef(b ? Py_True: Py_False); +} +static CYTHON_INLINE PyObject * __Pyx_PyLong_FromSize_t(size_t ival) { + return PyLong_FromSize_t(ival); +} + + +/* MultiPhaseInitModuleState */ +#if CYTHON_PEP489_MULTI_PHASE_INIT && CYTHON_USE_MODULE_STATE +#ifndef CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE +#if (CYTHON_COMPILING_IN_LIMITED_API || PY_VERSION_HEX >= 0x030C0000) + #define CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE 1 +#else + #define CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE 0 +#endif +#endif +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE && !CYTHON_ATOMICS +#error "Module state with PEP489 requires atomics. Currently that's one of\ + C11, C++11, gcc atomic intrinsics or MSVC atomic intrinsics" +#endif +#if !CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE +#define __Pyx_ModuleStateLookup_Lock() +#define __Pyx_ModuleStateLookup_Unlock() +#elif !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d0000 +static PyMutex __Pyx_ModuleStateLookup_mutex = {0}; +#define __Pyx_ModuleStateLookup_Lock() PyMutex_Lock(&__Pyx_ModuleStateLookup_mutex) +#define __Pyx_ModuleStateLookup_Unlock() PyMutex_Unlock(&__Pyx_ModuleStateLookup_mutex) +#elif defined(__cplusplus) && __cplusplus >= 201103L +#include +static std::mutex __Pyx_ModuleStateLookup_mutex; +#define __Pyx_ModuleStateLookup_Lock() __Pyx_ModuleStateLookup_mutex.lock() +#define __Pyx_ModuleStateLookup_Unlock() __Pyx_ModuleStateLookup_mutex.unlock() +#elif defined(__STDC_VERSION__) && (__STDC_VERSION__ > 201112L) && !defined(__STDC_NO_THREADS__) +#include +static mtx_t __Pyx_ModuleStateLookup_mutex; +static once_flag __Pyx_ModuleStateLookup_mutex_once_flag = ONCE_FLAG_INIT; +static void __Pyx_ModuleStateLookup_initialize_mutex(void) { + mtx_init(&__Pyx_ModuleStateLookup_mutex, mtx_plain); +} +#define __Pyx_ModuleStateLookup_Lock()\ + call_once(&__Pyx_ModuleStateLookup_mutex_once_flag, __Pyx_ModuleStateLookup_initialize_mutex);\ + mtx_lock(&__Pyx_ModuleStateLookup_mutex) +#define __Pyx_ModuleStateLookup_Unlock() mtx_unlock(&__Pyx_ModuleStateLookup_mutex) +#elif defined(HAVE_PTHREAD_H) +#include +static pthread_mutex_t __Pyx_ModuleStateLookup_mutex = PTHREAD_MUTEX_INITIALIZER; +#define __Pyx_ModuleStateLookup_Lock() pthread_mutex_lock(&__Pyx_ModuleStateLookup_mutex) +#define __Pyx_ModuleStateLookup_Unlock() pthread_mutex_unlock(&__Pyx_ModuleStateLookup_mutex) +#elif defined(_WIN32) +#include // synchapi.h on its own doesn't work +static SRWLOCK __Pyx_ModuleStateLookup_mutex = SRWLOCK_INIT; +#define __Pyx_ModuleStateLookup_Lock() AcquireSRWLockExclusive(&__Pyx_ModuleStateLookup_mutex) +#define __Pyx_ModuleStateLookup_Unlock() ReleaseSRWLockExclusive(&__Pyx_ModuleStateLookup_mutex) +#else +#error "No suitable lock available for CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE.\ + Requires C standard >= C11, or C++ standard >= C++11,\ + or pthreads, or the Windows 32 API, or Python >= 3.13." +#endif +typedef struct { + int64_t id; + PyObject *module; +} __Pyx_InterpreterIdAndModule; +typedef struct { + char interpreter_id_as_index; + Py_ssize_t count; + Py_ssize_t allocated; + __Pyx_InterpreterIdAndModule table[1]; +} __Pyx_ModuleStateLookupData; +#define __PYX_MODULE_STATE_LOOKUP_SMALL_SIZE 32 +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE +static __pyx_atomic_int_type __Pyx_ModuleStateLookup_read_counter = 0; +#endif +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE +static __pyx_atomic_ptr_type __Pyx_ModuleStateLookup_data = 0; +#else +static __Pyx_ModuleStateLookupData* __Pyx_ModuleStateLookup_data = NULL; +#endif +static __Pyx_InterpreterIdAndModule* __Pyx_State_FindModuleStateLookupTableLowerBound( + __Pyx_InterpreterIdAndModule* table, + Py_ssize_t count, + int64_t interpreterId) { + __Pyx_InterpreterIdAndModule* begin = table; + __Pyx_InterpreterIdAndModule* end = begin + count; + if (begin->id == interpreterId) { + return begin; + } + while ((end - begin) > __PYX_MODULE_STATE_LOOKUP_SMALL_SIZE) { + __Pyx_InterpreterIdAndModule* halfway = begin + (end - begin)/2; + if (halfway->id == interpreterId) { + return halfway; + } + if (halfway->id < interpreterId) { + begin = halfway; + } else { + end = halfway; + } + } + for (; begin < end; ++begin) { + if (begin->id >= interpreterId) return begin; + } + return begin; +} +static PyObject *__Pyx_State_FindModule(CYTHON_UNUSED void* dummy) { + int64_t interpreter_id = PyInterpreterState_GetID(__Pyx_PyInterpreterState_Get()); + if (interpreter_id == -1) return NULL; +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE + __Pyx_ModuleStateLookupData* data = (__Pyx_ModuleStateLookupData*)__pyx_atomic_pointer_load_relaxed(&__Pyx_ModuleStateLookup_data); + { + __pyx_atomic_incr_acq_rel(&__Pyx_ModuleStateLookup_read_counter); + if (likely(data)) { + __Pyx_ModuleStateLookupData* new_data = (__Pyx_ModuleStateLookupData*)__pyx_atomic_pointer_load_acquire(&__Pyx_ModuleStateLookup_data); + if (likely(data == new_data)) { + goto read_finished; + } + } + __pyx_atomic_decr_acq_rel(&__Pyx_ModuleStateLookup_read_counter); + __Pyx_ModuleStateLookup_Lock(); + __pyx_atomic_incr_relaxed(&__Pyx_ModuleStateLookup_read_counter); + data = (__Pyx_ModuleStateLookupData*)__pyx_atomic_pointer_load_relaxed(&__Pyx_ModuleStateLookup_data); + __Pyx_ModuleStateLookup_Unlock(); + } + read_finished:; +#else + __Pyx_ModuleStateLookupData* data = __Pyx_ModuleStateLookup_data; +#endif + __Pyx_InterpreterIdAndModule* found = NULL; + if (unlikely(!data)) goto end; + if (data->interpreter_id_as_index) { + if (interpreter_id < data->count) { + found = data->table+interpreter_id; + } + } else { + found = __Pyx_State_FindModuleStateLookupTableLowerBound( + data->table, data->count, interpreter_id); + } + end: + { + PyObject *result=NULL; + if (found && found->id == interpreter_id) { + result = found->module; + } +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE + __pyx_atomic_decr_acq_rel(&__Pyx_ModuleStateLookup_read_counter); +#endif + return result; + } +} +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE +static void __Pyx_ModuleStateLookup_wait_until_no_readers(void) { + while (__pyx_atomic_load(&__Pyx_ModuleStateLookup_read_counter) != 0); +} +#else +#define __Pyx_ModuleStateLookup_wait_until_no_readers() +#endif +static int __Pyx_State_AddModuleInterpIdAsIndex(__Pyx_ModuleStateLookupData **old_data, PyObject* module, int64_t interpreter_id) { + Py_ssize_t to_allocate = (*old_data)->allocated; + while (to_allocate <= interpreter_id) { + if (to_allocate == 0) to_allocate = 1; + else to_allocate *= 2; + } + __Pyx_ModuleStateLookupData *new_data = *old_data; + if (to_allocate != (*old_data)->allocated) { + new_data = (__Pyx_ModuleStateLookupData *)realloc( + *old_data, + sizeof(__Pyx_ModuleStateLookupData)+(to_allocate-1)*sizeof(__Pyx_InterpreterIdAndModule)); + if (!new_data) { + PyErr_NoMemory(); + return -1; + } + for (Py_ssize_t i = new_data->allocated; i < to_allocate; ++i) { + new_data->table[i].id = i; + new_data->table[i].module = NULL; + } + new_data->allocated = to_allocate; + } + new_data->table[interpreter_id].module = module; + if (new_data->count < interpreter_id+1) { + new_data->count = interpreter_id+1; + } + *old_data = new_data; + return 0; +} +static void __Pyx_State_ConvertFromInterpIdAsIndex(__Pyx_ModuleStateLookupData *data) { + __Pyx_InterpreterIdAndModule *read = data->table; + __Pyx_InterpreterIdAndModule *write = data->table; + __Pyx_InterpreterIdAndModule *end = read + data->count; + for (; readmodule) { + write->id = read->id; + write->module = read->module; + ++write; + } + } + data->count = write - data->table; + for (; writeid = 0; + write->module = NULL; + } + data->interpreter_id_as_index = 0; +} +static int __Pyx_State_AddModule(PyObject* module, CYTHON_UNUSED void* dummy) { + int64_t interpreter_id = PyInterpreterState_GetID(__Pyx_PyInterpreterState_Get()); + if (interpreter_id == -1) return -1; + int result = 0; + __Pyx_ModuleStateLookup_Lock(); +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE + __Pyx_ModuleStateLookupData *old_data = (__Pyx_ModuleStateLookupData *) + __pyx_atomic_pointer_exchange(&__Pyx_ModuleStateLookup_data, 0); +#else + __Pyx_ModuleStateLookupData *old_data = __Pyx_ModuleStateLookup_data; +#endif + __Pyx_ModuleStateLookupData *new_data = old_data; + if (!new_data) { + new_data = (__Pyx_ModuleStateLookupData *)calloc(1, sizeof(__Pyx_ModuleStateLookupData)); + if (!new_data) { + result = -1; + PyErr_NoMemory(); + goto end; + } + new_data->allocated = 1; + new_data->interpreter_id_as_index = 1; + } + __Pyx_ModuleStateLookup_wait_until_no_readers(); + if (new_data->interpreter_id_as_index) { + if (interpreter_id < __PYX_MODULE_STATE_LOOKUP_SMALL_SIZE) { + result = __Pyx_State_AddModuleInterpIdAsIndex(&new_data, module, interpreter_id); + goto end; + } + __Pyx_State_ConvertFromInterpIdAsIndex(new_data); + } + { + Py_ssize_t insert_at = 0; + { + __Pyx_InterpreterIdAndModule* lower_bound = __Pyx_State_FindModuleStateLookupTableLowerBound( + new_data->table, new_data->count, interpreter_id); + assert(lower_bound); + insert_at = lower_bound - new_data->table; + if (unlikely(insert_at < new_data->count && lower_bound->id == interpreter_id)) { + lower_bound->module = module; + goto end; // already in table, nothing more to do + } + } + if (new_data->count+1 >= new_data->allocated) { + Py_ssize_t to_allocate = (new_data->count+1)*2; + new_data = + (__Pyx_ModuleStateLookupData*)realloc( + new_data, + sizeof(__Pyx_ModuleStateLookupData) + + (to_allocate-1)*sizeof(__Pyx_InterpreterIdAndModule)); + if (!new_data) { + result = -1; + new_data = old_data; + PyErr_NoMemory(); + goto end; + } + new_data->allocated = to_allocate; + } + ++new_data->count; + int64_t last_id = interpreter_id; + PyObject *last_module = module; + for (Py_ssize_t i=insert_at; icount; ++i) { + int64_t current_id = new_data->table[i].id; + new_data->table[i].id = last_id; + last_id = current_id; + PyObject *current_module = new_data->table[i].module; + new_data->table[i].module = last_module; + last_module = current_module; + } + } + end: +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE + __pyx_atomic_pointer_exchange(&__Pyx_ModuleStateLookup_data, new_data); +#else + __Pyx_ModuleStateLookup_data = new_data; +#endif + __Pyx_ModuleStateLookup_Unlock(); + return result; +} +static int __Pyx_State_RemoveModule(CYTHON_UNUSED void* dummy) { + int64_t interpreter_id = PyInterpreterState_GetID(__Pyx_PyInterpreterState_Get()); + if (interpreter_id == -1) return -1; + __Pyx_ModuleStateLookup_Lock(); +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE + __Pyx_ModuleStateLookupData *data = (__Pyx_ModuleStateLookupData *) + __pyx_atomic_pointer_exchange(&__Pyx_ModuleStateLookup_data, 0); +#else + __Pyx_ModuleStateLookupData *data = __Pyx_ModuleStateLookup_data; +#endif + if (data->interpreter_id_as_index) { + if (interpreter_id < data->count) { + data->table[interpreter_id].module = NULL; + } + goto done; + } + { + __Pyx_ModuleStateLookup_wait_until_no_readers(); + __Pyx_InterpreterIdAndModule* lower_bound = __Pyx_State_FindModuleStateLookupTableLowerBound( + data->table, data->count, interpreter_id); + if (!lower_bound) goto done; + if (lower_bound->id != interpreter_id) goto done; + __Pyx_InterpreterIdAndModule *end = data->table+data->count; + for (;lower_boundid = (lower_bound+1)->id; + lower_bound->module = (lower_bound+1)->module; + } + } + --data->count; + if (data->count == 0) { + free(data); + data = NULL; + } + done: +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE + __pyx_atomic_pointer_exchange(&__Pyx_ModuleStateLookup_data, data); +#else + __Pyx_ModuleStateLookup_data = data; +#endif + __Pyx_ModuleStateLookup_Unlock(); + return 0; +} +#endif + +/* #### Code section: utility_code_pragmas_end ### */ +#ifdef _MSC_VER +#pragma warning( pop ) +#endif + + + +/* #### Code section: end ### */ +#endif /* Py_PYTHON_H */ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/buffered/cybuffered.pyx b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/buffered/cybuffered.pyx new file mode 100644 index 0000000000000000000000000000000000000000..1d79b5987b6db51c97b77640b006d1cc026945cf --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/buffered/cybuffered.pyx @@ -0,0 +1,95 @@ +# cython: freethreading_compatible = True + +from thriftpy2.transport.cybase cimport ( + TCyBuffer, + CyTransportBase, + DEFAULT_BUFFER +) + +from .. import TTransportException + +DEF MIN_BUFFER_SIZE = 1024 + + +cdef class TCyBufferedTransport(CyTransportBase): + """binary reader/writer""" + + cdef: + TCyBuffer rbuf, wbuf + + def __init__(self, trans, int buf_size=DEFAULT_BUFFER): + if buf_size < MIN_BUFFER_SIZE: + raise Exception("buffer too small") + + self.trans = trans + self.rbuf = TCyBuffer(buf_size) + self.wbuf = TCyBuffer(buf_size) + + def clean(self): + self.rbuf.clean() + self.wbuf.clean() + + def is_open(self): + return self.trans.is_open() + + def open(self): + return self.trans.open() + + def close(self): + return self.trans.close() + + def write(self, bytes data): + cdef int sz = len(data) + return self.c_write(data, sz) + + def read(self, int sz): + return self.get_string(sz) + + def flush(self): + return self.c_flush() + + cdef c_write(self, const char *data, int sz): + cdef: + int cap = self.wbuf.buf_size - self.wbuf.data_size + int r + + if cap < sz: + self.c_dump_wbuf() + + r = self.wbuf.write(sz, data) + if r == -1: + raise MemoryError("Write to buffer error") + + cdef c_read(self, int sz, char* out): + if sz <= 0: + return 0 + + self.read_trans(sz, out) + return sz + + cdef read_trans(self, int sz, char *out): + cdef int i = self.rbuf.read_trans(self.trans, sz, out) + if i == -1: + raise TTransportException(TTransportException.END_OF_FILE, + "End of file reading from transport") + elif i == -2: + raise MemoryError("grow read buffer fail") + + cdef c_flush(self): + self.c_dump_wbuf() + self.trans.flush() + + cdef c_dump_wbuf(self): + cdef bytes data + if self.wbuf.data_size > 0: + data = self.wbuf.buf[:self.wbuf.data_size] + self.trans.write(data) + self.wbuf.clean() + + def getvalue(self): + return self.trans.getvalue() + + +class TCyBufferedTransportFactory(object): + def get_transport(self, trans): + return TCyBufferedTransport(trans) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/cybase.c b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/cybase.c new file mode 100644 index 0000000000000000000000000000000000000000..43e1351441fe16c1a7495f7f1aa847fe734a4702 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/cybase.c @@ -0,0 +1,12453 @@ +/* Generated by Cython 3.2.4 */ + +/* BEGIN: Cython Metadata +{ + "distutils": { + "depends": [], + "name": "thriftpy2.transport.cybase", + "sources": [ + "thriftpy2/transport/cybase.pyx" + ] + }, + "module_name": "thriftpy2.transport.cybase" +} +END: Cython Metadata */ + +#ifndef PY_SSIZE_T_CLEAN +#define PY_SSIZE_T_CLEAN +#endif /* PY_SSIZE_T_CLEAN */ +/* InitLimitedAPI */ +#if defined(Py_LIMITED_API) + #if !defined(CYTHON_LIMITED_API) + #define CYTHON_LIMITED_API 1 + #endif +#elif defined(CYTHON_LIMITED_API) + #ifdef _MSC_VER + #pragma message ("Limited API usage is enabled with 'CYTHON_LIMITED_API' but 'Py_LIMITED_API' does not define a Python target version. Consider setting 'Py_LIMITED_API' instead.") + #else + #warning Limited API usage is enabled with 'CYTHON_LIMITED_API' but 'Py_LIMITED_API' does not define a Python target version. Consider setting 'Py_LIMITED_API' instead. + #endif +#endif + +#include "Python.h" +#ifndef Py_PYTHON_H + #error Python headers needed to compile C extensions, please install development version of Python. +#elif PY_VERSION_HEX < 0x03080000 + #error Cython requires Python 3.8+. +#else +#define __PYX_ABI_VERSION "3_2_4" +#define CYTHON_HEX_VERSION 0x030204F0 +#define CYTHON_FUTURE_DIVISION 1 +/* CModulePreamble */ +#include +#ifndef offsetof + #define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) +#endif +#if !defined(_WIN32) && !defined(WIN32) && !defined(MS_WINDOWS) + #ifndef __stdcall + #define __stdcall + #endif + #ifndef __cdecl + #define __cdecl + #endif + #ifndef __fastcall + #define __fastcall + #endif +#endif +#ifndef DL_IMPORT + #define DL_IMPORT(t) t +#endif +#ifndef DL_EXPORT + #define DL_EXPORT(t) t +#endif +#define __PYX_COMMA , +#ifndef PY_LONG_LONG + #define PY_LONG_LONG LONG_LONG +#endif +#ifndef Py_HUGE_VAL + #define Py_HUGE_VAL HUGE_VAL +#endif +#define __PYX_LIMITED_VERSION_HEX PY_VERSION_HEX +#if defined(GRAALVM_PYTHON) + /* For very preliminary testing purposes. Most variables are set the same as PyPy. + The existence of this section does not imply that anything works or is even tested */ + #define CYTHON_COMPILING_IN_PYPY 0 + #define CYTHON_COMPILING_IN_CPYTHON 0 + #define CYTHON_COMPILING_IN_LIMITED_API 0 + #define CYTHON_COMPILING_IN_GRAAL 1 + #define CYTHON_COMPILING_IN_CPYTHON_FREETHREADING 0 + #undef CYTHON_USE_TYPE_SLOTS + #define CYTHON_USE_TYPE_SLOTS 0 + #undef CYTHON_USE_TYPE_SPECS + #define CYTHON_USE_TYPE_SPECS 0 + #undef CYTHON_USE_PYTYPE_LOOKUP + #define CYTHON_USE_PYTYPE_LOOKUP 0 + #undef CYTHON_USE_PYLIST_INTERNALS + #define CYTHON_USE_PYLIST_INTERNALS 0 + #undef CYTHON_USE_UNICODE_INTERNALS + #define CYTHON_USE_UNICODE_INTERNALS 0 + #undef CYTHON_USE_UNICODE_WRITER + #define CYTHON_USE_UNICODE_WRITER 0 + #undef CYTHON_USE_PYLONG_INTERNALS + #define CYTHON_USE_PYLONG_INTERNALS 0 + #undef CYTHON_AVOID_BORROWED_REFS + #define CYTHON_AVOID_BORROWED_REFS 1 + #undef CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + #define CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS 0 + #undef CYTHON_ASSUME_SAFE_MACROS + #define CYTHON_ASSUME_SAFE_MACROS 0 + #undef CYTHON_ASSUME_SAFE_SIZE + #define CYTHON_ASSUME_SAFE_SIZE 0 + #undef CYTHON_UNPACK_METHODS + #define CYTHON_UNPACK_METHODS 0 + #undef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 0 + #undef CYTHON_FAST_GIL + #define CYTHON_FAST_GIL 0 + #undef CYTHON_METH_FASTCALL + #define CYTHON_METH_FASTCALL 0 + #undef CYTHON_FAST_PYCALL + #define CYTHON_FAST_PYCALL 0 + #ifndef CYTHON_PEP487_INIT_SUBCLASS + #define CYTHON_PEP487_INIT_SUBCLASS 1 + #endif + #undef CYTHON_PEP489_MULTI_PHASE_INIT + #define CYTHON_PEP489_MULTI_PHASE_INIT 1 + #undef CYTHON_USE_MODULE_STATE + #define CYTHON_USE_MODULE_STATE 0 + #undef CYTHON_USE_SYS_MONITORING + #define CYTHON_USE_SYS_MONITORING 0 + #undef CYTHON_USE_TP_FINALIZE + #define CYTHON_USE_TP_FINALIZE 0 + #undef CYTHON_USE_AM_SEND + #define CYTHON_USE_AM_SEND 0 + #undef CYTHON_USE_DICT_VERSIONS + #define CYTHON_USE_DICT_VERSIONS 0 + #undef CYTHON_USE_EXC_INFO_STACK + #define CYTHON_USE_EXC_INFO_STACK 1 + #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC + #define CYTHON_UPDATE_DESCRIPTOR_DOC 0 + #endif + #undef CYTHON_USE_FREELISTS + #define CYTHON_USE_FREELISTS 0 + #undef CYTHON_IMMORTAL_CONSTANTS + #define CYTHON_IMMORTAL_CONSTANTS 0 +#elif defined(PYPY_VERSION) + #define CYTHON_COMPILING_IN_PYPY 1 + #define CYTHON_COMPILING_IN_CPYTHON 0 + #define CYTHON_COMPILING_IN_LIMITED_API 0 + #define CYTHON_COMPILING_IN_GRAAL 0 + #define CYTHON_COMPILING_IN_CPYTHON_FREETHREADING 0 + #undef CYTHON_USE_TYPE_SLOTS + #define CYTHON_USE_TYPE_SLOTS 1 + #ifndef CYTHON_USE_TYPE_SPECS + #define CYTHON_USE_TYPE_SPECS 0 + #endif + #undef CYTHON_USE_PYTYPE_LOOKUP + #define CYTHON_USE_PYTYPE_LOOKUP 0 + #undef CYTHON_USE_PYLIST_INTERNALS + #define CYTHON_USE_PYLIST_INTERNALS 0 + #undef CYTHON_USE_UNICODE_INTERNALS + #define CYTHON_USE_UNICODE_INTERNALS 0 + #undef CYTHON_USE_UNICODE_WRITER + #define CYTHON_USE_UNICODE_WRITER 0 + #undef CYTHON_USE_PYLONG_INTERNALS + #define CYTHON_USE_PYLONG_INTERNALS 0 + #undef CYTHON_AVOID_BORROWED_REFS + #define CYTHON_AVOID_BORROWED_REFS 1 + #undef CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + #define CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS 1 + #undef CYTHON_ASSUME_SAFE_MACROS + #define CYTHON_ASSUME_SAFE_MACROS 0 + #ifndef CYTHON_ASSUME_SAFE_SIZE + #define CYTHON_ASSUME_SAFE_SIZE 1 + #endif + #undef CYTHON_UNPACK_METHODS + #define CYTHON_UNPACK_METHODS 0 + #undef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 0 + #undef CYTHON_FAST_GIL + #define CYTHON_FAST_GIL 0 + #undef CYTHON_METH_FASTCALL + #define CYTHON_METH_FASTCALL 0 + #undef CYTHON_FAST_PYCALL + #define CYTHON_FAST_PYCALL 0 + #ifndef CYTHON_PEP487_INIT_SUBCLASS + #define CYTHON_PEP487_INIT_SUBCLASS 1 + #endif + #if PY_VERSION_HEX < 0x03090000 + #undef CYTHON_PEP489_MULTI_PHASE_INIT + #define CYTHON_PEP489_MULTI_PHASE_INIT 0 + #elif !defined(CYTHON_PEP489_MULTI_PHASE_INIT) + #define CYTHON_PEP489_MULTI_PHASE_INIT 1 + #endif + #undef CYTHON_USE_MODULE_STATE + #define CYTHON_USE_MODULE_STATE 0 + #undef CYTHON_USE_SYS_MONITORING + #define CYTHON_USE_SYS_MONITORING 0 + #ifndef CYTHON_USE_TP_FINALIZE + #define CYTHON_USE_TP_FINALIZE (PYPY_VERSION_NUM >= 0x07030C00) + #endif + #undef CYTHON_USE_AM_SEND + #define CYTHON_USE_AM_SEND 0 + #undef CYTHON_USE_DICT_VERSIONS + #define CYTHON_USE_DICT_VERSIONS 0 + #undef CYTHON_USE_EXC_INFO_STACK + #define CYTHON_USE_EXC_INFO_STACK 0 + #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC + #define CYTHON_UPDATE_DESCRIPTOR_DOC (PYPY_VERSION_NUM >= 0x07031100) + #endif + #undef CYTHON_USE_FREELISTS + #define CYTHON_USE_FREELISTS 0 + #undef CYTHON_IMMORTAL_CONSTANTS + #define CYTHON_IMMORTAL_CONSTANTS 0 +#elif defined(CYTHON_LIMITED_API) + #ifdef Py_LIMITED_API + #undef __PYX_LIMITED_VERSION_HEX + #define __PYX_LIMITED_VERSION_HEX Py_LIMITED_API + #endif + #define CYTHON_COMPILING_IN_PYPY 0 + #define CYTHON_COMPILING_IN_CPYTHON 0 + #define CYTHON_COMPILING_IN_LIMITED_API 1 + #define CYTHON_COMPILING_IN_GRAAL 0 + #define CYTHON_COMPILING_IN_CPYTHON_FREETHREADING 0 + #undef CYTHON_USE_TYPE_SLOTS + #define CYTHON_USE_TYPE_SLOTS 0 + #undef CYTHON_USE_TYPE_SPECS + #define CYTHON_USE_TYPE_SPECS 1 + #undef CYTHON_USE_PYTYPE_LOOKUP + #define CYTHON_USE_PYTYPE_LOOKUP 0 + #undef CYTHON_USE_PYLIST_INTERNALS + #define CYTHON_USE_PYLIST_INTERNALS 0 + #undef CYTHON_USE_UNICODE_INTERNALS + #define CYTHON_USE_UNICODE_INTERNALS 0 + #ifndef CYTHON_USE_UNICODE_WRITER + #define CYTHON_USE_UNICODE_WRITER 0 + #endif + #undef CYTHON_USE_PYLONG_INTERNALS + #define CYTHON_USE_PYLONG_INTERNALS 0 + #ifndef CYTHON_AVOID_BORROWED_REFS + #define CYTHON_AVOID_BORROWED_REFS 0 + #endif + #ifndef CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + #define CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS 0 + #endif + #undef CYTHON_ASSUME_SAFE_MACROS + #define CYTHON_ASSUME_SAFE_MACROS 0 + #undef CYTHON_ASSUME_SAFE_SIZE + #define CYTHON_ASSUME_SAFE_SIZE 0 + #undef CYTHON_UNPACK_METHODS + #define CYTHON_UNPACK_METHODS 0 + #undef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 0 + #undef CYTHON_FAST_GIL + #define CYTHON_FAST_GIL 0 + #undef CYTHON_METH_FASTCALL + #define CYTHON_METH_FASTCALL (__PYX_LIMITED_VERSION_HEX >= 0x030C0000) + #undef CYTHON_FAST_PYCALL + #define CYTHON_FAST_PYCALL 0 + #ifndef CYTHON_PEP487_INIT_SUBCLASS + #define CYTHON_PEP487_INIT_SUBCLASS 1 + #endif + #ifndef CYTHON_PEP489_MULTI_PHASE_INIT + #define CYTHON_PEP489_MULTI_PHASE_INIT 1 + #endif + #ifndef CYTHON_USE_MODULE_STATE + #define CYTHON_USE_MODULE_STATE 0 + #endif + #undef CYTHON_USE_SYS_MONITORING + #define CYTHON_USE_SYS_MONITORING 0 + #ifndef CYTHON_USE_TP_FINALIZE + #define CYTHON_USE_TP_FINALIZE 0 + #endif + #ifndef CYTHON_USE_AM_SEND + #define CYTHON_USE_AM_SEND (__PYX_LIMITED_VERSION_HEX >= 0x030A0000) + #endif + #undef CYTHON_USE_DICT_VERSIONS + #define CYTHON_USE_DICT_VERSIONS 0 + #undef CYTHON_USE_EXC_INFO_STACK + #define CYTHON_USE_EXC_INFO_STACK 0 + #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC + #define CYTHON_UPDATE_DESCRIPTOR_DOC 0 + #endif + #ifndef CYTHON_USE_FREELISTS + #define CYTHON_USE_FREELISTS 1 + #endif + #undef CYTHON_IMMORTAL_CONSTANTS + #define CYTHON_IMMORTAL_CONSTANTS 0 +#else + #define CYTHON_COMPILING_IN_PYPY 0 + #define CYTHON_COMPILING_IN_CPYTHON 1 + #define CYTHON_COMPILING_IN_LIMITED_API 0 + #define CYTHON_COMPILING_IN_GRAAL 0 + #ifdef Py_GIL_DISABLED + #define CYTHON_COMPILING_IN_CPYTHON_FREETHREADING 1 + #else + #define CYTHON_COMPILING_IN_CPYTHON_FREETHREADING 0 + #endif + #if PY_VERSION_HEX < 0x030A0000 + #undef CYTHON_USE_TYPE_SLOTS + #define CYTHON_USE_TYPE_SLOTS 1 + #elif !defined(CYTHON_USE_TYPE_SLOTS) + #define CYTHON_USE_TYPE_SLOTS 1 + #endif + #ifndef CYTHON_USE_TYPE_SPECS + #define CYTHON_USE_TYPE_SPECS 0 + #endif + #ifndef CYTHON_USE_PYTYPE_LOOKUP + #define CYTHON_USE_PYTYPE_LOOKUP 1 + #endif + #ifndef CYTHON_USE_PYLONG_INTERNALS + #define CYTHON_USE_PYLONG_INTERNALS 1 + #endif + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + #undef CYTHON_USE_PYLIST_INTERNALS + #define CYTHON_USE_PYLIST_INTERNALS 0 + #elif !defined(CYTHON_USE_PYLIST_INTERNALS) + #define CYTHON_USE_PYLIST_INTERNALS 1 + #endif + #ifndef CYTHON_USE_UNICODE_INTERNALS + #define CYTHON_USE_UNICODE_INTERNALS 1 + #endif + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING || PY_VERSION_HEX >= 0x030B00A2 + #undef CYTHON_USE_UNICODE_WRITER + #define CYTHON_USE_UNICODE_WRITER 0 + #elif !defined(CYTHON_USE_UNICODE_WRITER) + #define CYTHON_USE_UNICODE_WRITER 1 + #endif + #ifndef CYTHON_AVOID_BORROWED_REFS + #define CYTHON_AVOID_BORROWED_REFS 0 + #endif + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + #undef CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + #define CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS 1 + #elif !defined(CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS) + #define CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS 0 + #endif + #ifndef CYTHON_ASSUME_SAFE_MACROS + #define CYTHON_ASSUME_SAFE_MACROS 1 + #endif + #ifndef CYTHON_ASSUME_SAFE_SIZE + #define CYTHON_ASSUME_SAFE_SIZE 1 + #endif + #ifndef CYTHON_UNPACK_METHODS + #define CYTHON_UNPACK_METHODS 1 + #endif + #ifndef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 1 + #endif + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + #undef CYTHON_FAST_GIL + #define CYTHON_FAST_GIL 0 + #elif !defined(CYTHON_FAST_GIL) + #define CYTHON_FAST_GIL (PY_VERSION_HEX < 0x030C00A6) + #endif + #ifndef CYTHON_METH_FASTCALL + #define CYTHON_METH_FASTCALL 1 + #endif + #ifndef CYTHON_FAST_PYCALL + #define CYTHON_FAST_PYCALL 1 + #endif + #ifndef CYTHON_PEP487_INIT_SUBCLASS + #define CYTHON_PEP487_INIT_SUBCLASS 1 + #endif + #ifndef CYTHON_PEP489_MULTI_PHASE_INIT + #define CYTHON_PEP489_MULTI_PHASE_INIT 1 + #endif + #ifndef CYTHON_USE_MODULE_STATE + #define CYTHON_USE_MODULE_STATE 0 + #endif + #ifndef CYTHON_USE_SYS_MONITORING + #define CYTHON_USE_SYS_MONITORING (PY_VERSION_HEX >= 0x030d00B1) + #endif + #ifndef CYTHON_USE_TP_FINALIZE + #define CYTHON_USE_TP_FINALIZE 1 + #endif + #ifndef CYTHON_USE_AM_SEND + #define CYTHON_USE_AM_SEND 1 + #endif + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + #undef CYTHON_USE_DICT_VERSIONS + #define CYTHON_USE_DICT_VERSIONS 0 + #elif !defined(CYTHON_USE_DICT_VERSIONS) + #define CYTHON_USE_DICT_VERSIONS (PY_VERSION_HEX < 0x030C00A5 && !CYTHON_USE_MODULE_STATE) + #endif + #ifndef CYTHON_USE_EXC_INFO_STACK + #define CYTHON_USE_EXC_INFO_STACK 1 + #endif + #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC + #define CYTHON_UPDATE_DESCRIPTOR_DOC 1 + #endif + #ifndef CYTHON_USE_FREELISTS + #define CYTHON_USE_FREELISTS (!CYTHON_COMPILING_IN_CPYTHON_FREETHREADING) + #endif + #if defined(CYTHON_IMMORTAL_CONSTANTS) && PY_VERSION_HEX < 0x030C0000 + #undef CYTHON_IMMORTAL_CONSTANTS + #define CYTHON_IMMORTAL_CONSTANTS 0 // definitely won't work + #elif !defined(CYTHON_IMMORTAL_CONSTANTS) + #define CYTHON_IMMORTAL_CONSTANTS (PY_VERSION_HEX >= 0x030C0000 && !CYTHON_USE_MODULE_STATE && CYTHON_COMPILING_IN_CPYTHON_FREETHREADING) + #endif +#endif +#ifndef CYTHON_COMPRESS_STRINGS + #define CYTHON_COMPRESS_STRINGS 1 +#endif +#ifndef CYTHON_FAST_PYCCALL +#define CYTHON_FAST_PYCCALL CYTHON_FAST_PYCALL +#endif +#ifndef CYTHON_VECTORCALL +#if CYTHON_COMPILING_IN_LIMITED_API +#define CYTHON_VECTORCALL (__PYX_LIMITED_VERSION_HEX >= 0x030C0000) +#else +#define CYTHON_VECTORCALL (CYTHON_FAST_PYCCALL) +#endif +#endif +#if CYTHON_USE_PYLONG_INTERNALS + #undef SHIFT + #undef BASE + #undef MASK + #ifdef SIZEOF_VOID_P + enum { __pyx_check_sizeof_voidp = 1 / (int)(SIZEOF_VOID_P == sizeof(void*)) }; + #endif +#endif +#ifndef __has_attribute + #define __has_attribute(x) 0 +#endif +#ifndef __has_cpp_attribute + #define __has_cpp_attribute(x) 0 +#endif +#ifndef CYTHON_RESTRICT + #if defined(__GNUC__) + #define CYTHON_RESTRICT __restrict__ + #elif defined(_MSC_VER) && _MSC_VER >= 1400 + #define CYTHON_RESTRICT __restrict + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_RESTRICT restrict + #else + #define CYTHON_RESTRICT + #endif +#endif +#ifndef CYTHON_UNUSED + #if defined(__cplusplus) + /* for clang __has_cpp_attribute(maybe_unused) is true even before C++17 + * but leads to warnings with -pedantic, since it is a C++17 feature */ + #if ((defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) || __cplusplus >= 201703L) + #if __has_cpp_attribute(maybe_unused) + #define CYTHON_UNUSED [[maybe_unused]] + #endif + #endif + #endif +#endif +#ifndef CYTHON_UNUSED +# if defined(__GNUC__) +# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) +# define CYTHON_UNUSED __attribute__ ((__unused__)) +# else +# define CYTHON_UNUSED +# endif +# elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) +# define CYTHON_UNUSED __attribute__ ((__unused__)) +# else +# define CYTHON_UNUSED +# endif +#endif +#ifndef CYTHON_UNUSED_VAR +# if defined(__cplusplus) + template void CYTHON_UNUSED_VAR( const T& ) { } +# else +# define CYTHON_UNUSED_VAR(x) (void)(x) +# endif +#endif +#ifndef CYTHON_MAYBE_UNUSED_VAR + #define CYTHON_MAYBE_UNUSED_VAR(x) CYTHON_UNUSED_VAR(x) +#endif +#ifndef CYTHON_NCP_UNUSED +# if CYTHON_COMPILING_IN_CPYTHON && !CYTHON_COMPILING_IN_CPYTHON_FREETHREADING +# define CYTHON_NCP_UNUSED +# else +# define CYTHON_NCP_UNUSED CYTHON_UNUSED +# endif +#endif +#ifndef CYTHON_USE_CPP_STD_MOVE + #if defined(__cplusplus) && (\ + __cplusplus >= 201103L || (defined(_MSC_VER) && _MSC_VER >= 1600)) + #define CYTHON_USE_CPP_STD_MOVE 1 + #else + #define CYTHON_USE_CPP_STD_MOVE 0 + #endif +#endif +#define __Pyx_void_to_None(void_result) ((void)(void_result), Py_INCREF(Py_None), Py_None) +#include +typedef uintptr_t __pyx_uintptr_t; +#ifndef CYTHON_FALLTHROUGH + #if defined(__cplusplus) + /* for clang __has_cpp_attribute(fallthrough) is true even before C++17 + * but leads to warnings with -pedantic, since it is a C++17 feature */ + #if ((defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) || __cplusplus >= 201703L) + #if __has_cpp_attribute(fallthrough) + #define CYTHON_FALLTHROUGH [[fallthrough]] + #endif + #endif + #ifndef CYTHON_FALLTHROUGH + #if __has_cpp_attribute(clang::fallthrough) + #define CYTHON_FALLTHROUGH [[clang::fallthrough]] + #elif __has_cpp_attribute(gnu::fallthrough) + #define CYTHON_FALLTHROUGH [[gnu::fallthrough]] + #endif + #endif + #endif + #ifndef CYTHON_FALLTHROUGH + #if __has_attribute(fallthrough) + #define CYTHON_FALLTHROUGH __attribute__((fallthrough)) + #else + #define CYTHON_FALLTHROUGH + #endif + #endif + #if defined(__clang__) && defined(__apple_build_version__) + #if __apple_build_version__ < 7000000 + #undef CYTHON_FALLTHROUGH + #define CYTHON_FALLTHROUGH + #endif + #endif +#endif +#ifndef Py_UNREACHABLE + #define Py_UNREACHABLE() assert(0); abort() +#endif +#ifdef __cplusplus + template + struct __PYX_IS_UNSIGNED_IMPL {static const bool value = T(0) < T(-1);}; + #define __PYX_IS_UNSIGNED(type) (__PYX_IS_UNSIGNED_IMPL::value) +#else + #define __PYX_IS_UNSIGNED(type) (((type)-1) > 0) +#endif +#if CYTHON_COMPILING_IN_PYPY == 1 + #define __PYX_NEED_TP_PRINT_SLOT (PY_VERSION_HEX < 0x030A0000) +#else + #define __PYX_NEED_TP_PRINT_SLOT (PY_VERSION_HEX < 0x03090000) +#endif +#define __PYX_REINTERPRET_FUNCION(func_pointer, other_pointer) ((func_pointer)(void(*)(void))(other_pointer)) + +/* CInitCode */ +#ifndef CYTHON_INLINE + #if defined(__clang__) + #define CYTHON_INLINE __inline__ __attribute__ ((__unused__)) + #elif defined(__GNUC__) + #define CYTHON_INLINE __inline__ + #elif defined(_MSC_VER) + #define CYTHON_INLINE __inline + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_INLINE inline + #else + #define CYTHON_INLINE + #endif +#endif + +/* PythonCompatibility */ +#define __PYX_BUILD_PY_SSIZE_T "n" +#define CYTHON_FORMAT_SSIZE_T "z" +#define __Pyx_BUILTIN_MODULE_NAME "builtins" +#define __Pyx_DefaultClassType PyType_Type +#if CYTHON_COMPILING_IN_LIMITED_API + #ifndef CO_OPTIMIZED + static int CO_OPTIMIZED; + #endif + #ifndef CO_NEWLOCALS + static int CO_NEWLOCALS; + #endif + #ifndef CO_VARARGS + static int CO_VARARGS; + #endif + #ifndef CO_VARKEYWORDS + static int CO_VARKEYWORDS; + #endif + #ifndef CO_ASYNC_GENERATOR + static int CO_ASYNC_GENERATOR; + #endif + #ifndef CO_GENERATOR + static int CO_GENERATOR; + #endif + #ifndef CO_COROUTINE + static int CO_COROUTINE; + #endif +#else + #ifndef CO_COROUTINE + #define CO_COROUTINE 0x80 + #endif + #ifndef CO_ASYNC_GENERATOR + #define CO_ASYNC_GENERATOR 0x200 + #endif +#endif +static int __Pyx_init_co_variables(void); +#if PY_VERSION_HEX >= 0x030900A4 || defined(Py_IS_TYPE) + #define __Pyx_IS_TYPE(ob, type) Py_IS_TYPE(ob, type) +#else + #define __Pyx_IS_TYPE(ob, type) (((const PyObject*)ob)->ob_type == (type)) +#endif +#if PY_VERSION_HEX >= 0x030A00B1 || defined(Py_Is) + #define __Pyx_Py_Is(x, y) Py_Is(x, y) +#else + #define __Pyx_Py_Is(x, y) ((x) == (y)) +#endif +#if PY_VERSION_HEX >= 0x030A00B1 || defined(Py_IsNone) + #define __Pyx_Py_IsNone(ob) Py_IsNone(ob) +#else + #define __Pyx_Py_IsNone(ob) __Pyx_Py_Is((ob), Py_None) +#endif +#if PY_VERSION_HEX >= 0x030A00B1 || defined(Py_IsTrue) + #define __Pyx_Py_IsTrue(ob) Py_IsTrue(ob) +#else + #define __Pyx_Py_IsTrue(ob) __Pyx_Py_Is((ob), Py_True) +#endif +#if PY_VERSION_HEX >= 0x030A00B1 || defined(Py_IsFalse) + #define __Pyx_Py_IsFalse(ob) Py_IsFalse(ob) +#else + #define __Pyx_Py_IsFalse(ob) __Pyx_Py_Is((ob), Py_False) +#endif +#define __Pyx_NoneAsNull(obj) (__Pyx_Py_IsNone(obj) ? NULL : (obj)) +#if PY_VERSION_HEX >= 0x030900F0 && !CYTHON_COMPILING_IN_PYPY + #define __Pyx_PyObject_GC_IsFinalized(o) PyObject_GC_IsFinalized(o) +#else + #define __Pyx_PyObject_GC_IsFinalized(o) _PyGC_FINALIZED(o) +#endif +#ifndef Py_TPFLAGS_CHECKTYPES + #define Py_TPFLAGS_CHECKTYPES 0 +#endif +#ifndef Py_TPFLAGS_HAVE_INDEX + #define Py_TPFLAGS_HAVE_INDEX 0 +#endif +#ifndef Py_TPFLAGS_HAVE_NEWBUFFER + #define Py_TPFLAGS_HAVE_NEWBUFFER 0 +#endif +#ifndef Py_TPFLAGS_HAVE_FINALIZE + #define Py_TPFLAGS_HAVE_FINALIZE 0 +#endif +#ifndef Py_TPFLAGS_SEQUENCE + #define Py_TPFLAGS_SEQUENCE 0 +#endif +#ifndef Py_TPFLAGS_MAPPING + #define Py_TPFLAGS_MAPPING 0 +#endif +#ifndef Py_TPFLAGS_IMMUTABLETYPE + #define Py_TPFLAGS_IMMUTABLETYPE (1UL << 8) +#endif +#ifndef Py_TPFLAGS_DISALLOW_INSTANTIATION + #define Py_TPFLAGS_DISALLOW_INSTANTIATION (1UL << 7) +#endif +#ifndef METH_STACKLESS + #define METH_STACKLESS 0 +#endif +#ifndef METH_FASTCALL + #ifndef METH_FASTCALL + #define METH_FASTCALL 0x80 + #endif + typedef PyObject *(*__Pyx_PyCFunctionFast) (PyObject *self, PyObject *const *args, Py_ssize_t nargs); + typedef PyObject *(*__Pyx_PyCFunctionFastWithKeywords) (PyObject *self, PyObject *const *args, + Py_ssize_t nargs, PyObject *kwnames); +#else + #if PY_VERSION_HEX >= 0x030d00A4 + # define __Pyx_PyCFunctionFast PyCFunctionFast + # define __Pyx_PyCFunctionFastWithKeywords PyCFunctionFastWithKeywords + #else + # define __Pyx_PyCFunctionFast _PyCFunctionFast + # define __Pyx_PyCFunctionFastWithKeywords _PyCFunctionFastWithKeywords + #endif +#endif +#if CYTHON_METH_FASTCALL + #define __Pyx_METH_FASTCALL METH_FASTCALL + #define __Pyx_PyCFunction_FastCall __Pyx_PyCFunctionFast + #define __Pyx_PyCFunction_FastCallWithKeywords __Pyx_PyCFunctionFastWithKeywords +#else + #define __Pyx_METH_FASTCALL METH_VARARGS + #define __Pyx_PyCFunction_FastCall PyCFunction + #define __Pyx_PyCFunction_FastCallWithKeywords PyCFunctionWithKeywords +#endif +#if CYTHON_VECTORCALL + #define __pyx_vectorcallfunc vectorcallfunc + #define __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET PY_VECTORCALL_ARGUMENTS_OFFSET + #define __Pyx_PyVectorcall_NARGS(n) PyVectorcall_NARGS((size_t)(n)) +#else + #define __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET 0 + #define __Pyx_PyVectorcall_NARGS(n) ((Py_ssize_t)(n)) +#endif +#if PY_VERSION_HEX >= 0x030900B1 +#define __Pyx_PyCFunction_CheckExact(func) PyCFunction_CheckExact(func) +#else +#define __Pyx_PyCFunction_CheckExact(func) PyCFunction_Check(func) +#endif +#define __Pyx_CyOrPyCFunction_Check(func) PyCFunction_Check(func) +#if CYTHON_COMPILING_IN_CPYTHON +#define __Pyx_CyOrPyCFunction_GET_FUNCTION(func) (((PyCFunctionObject*)(func))->m_ml->ml_meth) +#elif !CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_CyOrPyCFunction_GET_FUNCTION(func) PyCFunction_GET_FUNCTION(func) +#endif +#if CYTHON_COMPILING_IN_CPYTHON +#define __Pyx_CyOrPyCFunction_GET_FLAGS(func) (((PyCFunctionObject*)(func))->m_ml->ml_flags) +static CYTHON_INLINE PyObject* __Pyx_CyOrPyCFunction_GET_SELF(PyObject *func) { + return (__Pyx_CyOrPyCFunction_GET_FLAGS(func) & METH_STATIC) ? NULL : ((PyCFunctionObject*)func)->m_self; +} +#endif +static CYTHON_INLINE int __Pyx__IsSameCFunction(PyObject *func, void (*cfunc)(void)) { +#if CYTHON_COMPILING_IN_LIMITED_API + return PyCFunction_Check(func) && PyCFunction_GetFunction(func) == (PyCFunction) cfunc; +#else + return PyCFunction_Check(func) && PyCFunction_GET_FUNCTION(func) == (PyCFunction) cfunc; +#endif +} +#define __Pyx_IsSameCFunction(func, cfunc) __Pyx__IsSameCFunction(func, cfunc) +#if PY_VERSION_HEX < 0x03090000 || (CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000) + #define __Pyx_PyType_FromModuleAndSpec(m, s, b) ((void)m, PyType_FromSpecWithBases(s, b)) + typedef PyObject *(*__Pyx_PyCMethod)(PyObject *, PyTypeObject *, PyObject *const *, size_t, PyObject *); +#else + #define __Pyx_PyType_FromModuleAndSpec(m, s, b) PyType_FromModuleAndSpec(m, s, b) + #define __Pyx_PyCMethod PyCMethod +#endif +#ifndef METH_METHOD + #define METH_METHOD 0x200 +#endif +#if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Malloc) + #define PyObject_Malloc(s) PyMem_Malloc(s) + #define PyObject_Free(p) PyMem_Free(p) + #define PyObject_Realloc(p) PyMem_Realloc(p) +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + #define __Pyx_PyFrame_SetLineNumber(frame, lineno) +#elif CYTHON_COMPILING_IN_GRAAL && defined(GRAALPY_VERSION_NUM) && GRAALPY_VERSION_NUM > 0x19000000 + #define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0) + #define __Pyx_PyFrame_SetLineNumber(frame, lineno) GraalPyFrame_SetLineNumber((frame), (lineno)) +#elif CYTHON_COMPILING_IN_GRAAL + #define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0) + #define __Pyx_PyFrame_SetLineNumber(frame, lineno) _PyFrame_SetLineNumber((frame), (lineno)) +#else + #define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0) + #define __Pyx_PyFrame_SetLineNumber(frame, lineno) (frame)->f_lineno = (lineno) +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + #define __Pyx_PyThreadState_Current PyThreadState_Get() +#elif !CYTHON_FAST_THREAD_STATE + #define __Pyx_PyThreadState_Current PyThreadState_GET() +#elif PY_VERSION_HEX >= 0x030d00A1 + #define __Pyx_PyThreadState_Current PyThreadState_GetUnchecked() +#else + #define __Pyx_PyThreadState_Current _PyThreadState_UncheckedGet() +#endif +#if CYTHON_USE_MODULE_STATE +static CYTHON_INLINE void *__Pyx__PyModule_GetState(PyObject *op) +{ + void *result; + result = PyModule_GetState(op); + if (!result) + Py_FatalError("Couldn't find the module state"); + return result; +} +#define __Pyx_PyModule_GetState(o) (__pyx_mstatetype *)__Pyx__PyModule_GetState(o) +#else +#define __Pyx_PyModule_GetState(op) ((void)op,__pyx_mstate_global) +#endif +#define __Pyx_PyObject_GetSlot(obj, name, func_ctype) __Pyx_PyType_GetSlot(Py_TYPE((PyObject *) obj), name, func_ctype) +#define __Pyx_PyObject_TryGetSlot(obj, name, func_ctype) __Pyx_PyType_TryGetSlot(Py_TYPE(obj), name, func_ctype) +#define __Pyx_PyObject_GetSubSlot(obj, sub, name, func_ctype) __Pyx_PyType_GetSubSlot(Py_TYPE(obj), sub, name, func_ctype) +#define __Pyx_PyObject_TryGetSubSlot(obj, sub, name, func_ctype) __Pyx_PyType_TryGetSubSlot(Py_TYPE(obj), sub, name, func_ctype) +#if CYTHON_USE_TYPE_SLOTS + #define __Pyx_PyType_GetSlot(type, name, func_ctype) ((type)->name) + #define __Pyx_PyType_TryGetSlot(type, name, func_ctype) __Pyx_PyType_GetSlot(type, name, func_ctype) + #define __Pyx_PyType_GetSubSlot(type, sub, name, func_ctype) (((type)->sub) ? ((type)->sub->name) : NULL) + #define __Pyx_PyType_TryGetSubSlot(type, sub, name, func_ctype) __Pyx_PyType_GetSubSlot(type, sub, name, func_ctype) +#else + #define __Pyx_PyType_GetSlot(type, name, func_ctype) ((func_ctype) PyType_GetSlot((type), Py_##name)) + #define __Pyx_PyType_TryGetSlot(type, name, func_ctype)\ + ((__PYX_LIMITED_VERSION_HEX >= 0x030A0000 ||\ + (PyType_GetFlags(type) & Py_TPFLAGS_HEAPTYPE) || __Pyx_get_runtime_version() >= 0x030A0000) ?\ + __Pyx_PyType_GetSlot(type, name, func_ctype) : NULL) + #define __Pyx_PyType_GetSubSlot(obj, sub, name, func_ctype) __Pyx_PyType_GetSlot(obj, name, func_ctype) + #define __Pyx_PyType_TryGetSubSlot(obj, sub, name, func_ctype) __Pyx_PyType_TryGetSlot(obj, name, func_ctype) +#endif +#if CYTHON_COMPILING_IN_CPYTHON || defined(_PyDict_NewPresized) +#define __Pyx_PyDict_NewPresized(n) ((n <= 8) ? PyDict_New() : _PyDict_NewPresized(n)) +#else +#define __Pyx_PyDict_NewPresized(n) PyDict_New() +#endif +#define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) +#define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) +#if CYTHON_COMPILING_IN_CPYTHON && CYTHON_USE_UNICODE_INTERNALS +#define __Pyx_PyDict_GetItemStrWithError(dict, name) _PyDict_GetItem_KnownHash(dict, name, ((PyASCIIObject *) name)->hash) +static CYTHON_INLINE PyObject * __Pyx_PyDict_GetItemStr(PyObject *dict, PyObject *name) { + PyObject *res = __Pyx_PyDict_GetItemStrWithError(dict, name); + if (res == NULL) PyErr_Clear(); + return res; +} +#elif !CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07020000 +#define __Pyx_PyDict_GetItemStrWithError PyDict_GetItemWithError +#define __Pyx_PyDict_GetItemStr PyDict_GetItem +#else +static CYTHON_INLINE PyObject * __Pyx_PyDict_GetItemStrWithError(PyObject *dict, PyObject *name) { +#if CYTHON_COMPILING_IN_PYPY + return PyDict_GetItem(dict, name); +#else + PyDictEntry *ep; + PyDictObject *mp = (PyDictObject*) dict; + long hash = ((PyStringObject *) name)->ob_shash; + assert(hash != -1); + ep = (mp->ma_lookup)(mp, name, hash); + if (ep == NULL) { + return NULL; + } + return ep->me_value; +#endif +} +#define __Pyx_PyDict_GetItemStr PyDict_GetItem +#endif +#if CYTHON_USE_TYPE_SLOTS + #define __Pyx_PyType_GetFlags(tp) (((PyTypeObject *)tp)->tp_flags) + #define __Pyx_PyType_HasFeature(type, feature) ((__Pyx_PyType_GetFlags(type) & (feature)) != 0) +#else + #define __Pyx_PyType_GetFlags(tp) (PyType_GetFlags((PyTypeObject *)tp)) + #define __Pyx_PyType_HasFeature(type, feature) PyType_HasFeature(type, feature) +#endif +#define __Pyx_PyObject_GetIterNextFunc(iterator) __Pyx_PyObject_GetSlot(iterator, tp_iternext, iternextfunc) +#if CYTHON_USE_TYPE_SPECS +#define __Pyx_PyHeapTypeObject_GC_Del(obj) {\ + PyTypeObject *type = Py_TYPE((PyObject*)obj);\ + assert(__Pyx_PyType_HasFeature(type, Py_TPFLAGS_HEAPTYPE));\ + PyObject_GC_Del(obj);\ + Py_DECREF(type);\ +} +#else +#define __Pyx_PyHeapTypeObject_GC_Del(obj) PyObject_GC_Del(obj) +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + #define __Pyx_PyUnicode_READY(op) (0) + #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_ReadChar(u, i) + #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) ((void)u, 1114111U) + #define __Pyx_PyUnicode_KIND(u) ((void)u, (0)) + #define __Pyx_PyUnicode_DATA(u) ((void*)u) + #define __Pyx_PyUnicode_READ(k, d, i) ((void)k, PyUnicode_ReadChar((PyObject*)(d), i)) + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GetLength(u)) +#else + #if PY_VERSION_HEX >= 0x030C0000 + #define __Pyx_PyUnicode_READY(op) (0) + #else + #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ?\ + 0 : _PyUnicode_Ready((PyObject *)(op))) + #endif + #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) + #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) PyUnicode_MAX_CHAR_VALUE(u) + #define __Pyx_PyUnicode_KIND(u) ((int)PyUnicode_KIND(u)) + #define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u) + #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) + #define __Pyx_PyUnicode_WRITE(k, d, i, ch) PyUnicode_WRITE(k, d, i, (Py_UCS4) ch) + #if PY_VERSION_HEX >= 0x030C0000 + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_LENGTH(u)) + #else + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x03090000 + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : ((PyCompactUnicodeObject *)(u))->wstr_length)) + #else + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : PyUnicode_GET_SIZE(u))) + #endif + #endif +#endif +#if CYTHON_COMPILING_IN_PYPY + #define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b) +#else + #define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ?\ + PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b)) +#endif +#if CYTHON_COMPILING_IN_PYPY + #if !defined(PyUnicode_DecodeUnicodeEscape) + #define PyUnicode_DecodeUnicodeEscape(s, size, errors) PyUnicode_Decode(s, size, "unicode_escape", errors) + #endif + #if !defined(PyUnicode_Contains) + #define PyUnicode_Contains(u, s) PySequence_Contains(u, s) + #endif + #if !defined(PyByteArray_Check) + #define PyByteArray_Check(obj) PyObject_TypeCheck(obj, &PyByteArray_Type) + #endif + #if !defined(PyObject_Format) + #define PyObject_Format(obj, fmt) PyObject_CallMethod(obj, "__format__", "O", fmt) + #endif +#endif +#define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None || (PyUnicode_Check(b) && !PyUnicode_CheckExact(b)))) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + #define __Pyx_PySequence_ListKeepNew(obj)\ + (likely(PyList_CheckExact(obj) && PyUnstable_Object_IsUniquelyReferenced(obj)) ? __Pyx_NewRef(obj) : PySequence_List(obj)) +#elif CYTHON_COMPILING_IN_CPYTHON + #define __Pyx_PySequence_ListKeepNew(obj)\ + (likely(PyList_CheckExact(obj) && Py_REFCNT(obj) == 1) ? __Pyx_NewRef(obj) : PySequence_List(obj)) +#else + #define __Pyx_PySequence_ListKeepNew(obj) PySequence_List(obj) +#endif +#ifndef PySet_CheckExact + #define PySet_CheckExact(obj) __Pyx_IS_TYPE(obj, &PySet_Type) +#endif +#if PY_VERSION_HEX >= 0x030900A4 + #define __Pyx_SET_REFCNT(obj, refcnt) Py_SET_REFCNT(obj, refcnt) + #define __Pyx_SET_SIZE(obj, size) Py_SET_SIZE(obj, size) +#else + #define __Pyx_SET_REFCNT(obj, refcnt) Py_REFCNT(obj) = (refcnt) + #define __Pyx_SET_SIZE(obj, size) Py_SIZE(obj) = (size) +#endif +enum __Pyx_ReferenceSharing { + __Pyx_ReferenceSharing_DefinitelyUnique, // We created it so we know it's unshared - no need to check + __Pyx_ReferenceSharing_OwnStrongReference, + __Pyx_ReferenceSharing_FunctionArgument, + __Pyx_ReferenceSharing_SharedReference, // Never trust it to be unshared because it's a global or similar +}; +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING && PY_VERSION_HEX >= 0x030E0000 +#define __Pyx_IS_UNIQUELY_REFERENCED(o, sharing)\ + (sharing == __Pyx_ReferenceSharing_DefinitelyUnique ? 1 :\ + (sharing == __Pyx_ReferenceSharing_FunctionArgument ? PyUnstable_Object_IsUniqueReferencedTemporary(o) :\ + (sharing == __Pyx_ReferenceSharing_OwnStrongReference ? PyUnstable_Object_IsUniquelyReferenced(o) : 0))) +#elif (CYTHON_COMPILING_IN_CPYTHON && !CYTHON_COMPILING_IN_CPYTHON_FREETHREADING) || CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_IS_UNIQUELY_REFERENCED(o, sharing) (((void)sharing), Py_REFCNT(o) == 1) +#else +#define __Pyx_IS_UNIQUELY_REFERENCED(o, sharing) (((void)o), ((void)sharing), 0) +#endif +#if CYTHON_AVOID_BORROWED_REFS || CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + #if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + #define __Pyx_PyList_GetItemRef(o, i) PyList_GetItemRef(o, i) + #elif CYTHON_COMPILING_IN_LIMITED_API || !CYTHON_ASSUME_SAFE_MACROS + #define __Pyx_PyList_GetItemRef(o, i) (likely((i) >= 0) ? PySequence_GetItem(o, i) : (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL)) + #else + #define __Pyx_PyList_GetItemRef(o, i) PySequence_ITEM(o, i) + #endif +#elif CYTHON_COMPILING_IN_LIMITED_API || !CYTHON_ASSUME_SAFE_MACROS + #if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + #define __Pyx_PyList_GetItemRef(o, i) PyList_GetItemRef(o, i) + #else + #define __Pyx_PyList_GetItemRef(o, i) __Pyx_XNewRef(PyList_GetItem(o, i)) + #endif +#else + #define __Pyx_PyList_GetItemRef(o, i) __Pyx_NewRef(PyList_GET_ITEM(o, i)) +#endif +#if CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS && !CYTHON_COMPILING_IN_LIMITED_API && CYTHON_ASSUME_SAFE_MACROS + #define __Pyx_PyList_GetItemRefFast(o, i, unsafe_shared) (__Pyx_IS_UNIQUELY_REFERENCED(o, unsafe_shared) ?\ + __Pyx_NewRef(PyList_GET_ITEM(o, i)) : __Pyx_PyList_GetItemRef(o, i)) +#else + #define __Pyx_PyList_GetItemRefFast(o, i, unsafe_shared) __Pyx_PyList_GetItemRef(o, i) +#endif +#if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 +#define __Pyx_PyDict_GetItemRef(dict, key, result) PyDict_GetItemRef(dict, key, result) +#elif CYTHON_AVOID_BORROWED_REFS || CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS +static CYTHON_INLINE int __Pyx_PyDict_GetItemRef(PyObject *dict, PyObject *key, PyObject **result) { + *result = PyObject_GetItem(dict, key); + if (*result == NULL) { + if (PyErr_ExceptionMatches(PyExc_KeyError)) { + PyErr_Clear(); + return 0; + } + return -1; + } + return 1; +} +#else +static CYTHON_INLINE int __Pyx_PyDict_GetItemRef(PyObject *dict, PyObject *key, PyObject **result) { + *result = PyDict_GetItemWithError(dict, key); + if (*result == NULL) { + return PyErr_Occurred() ? -1 : 0; + } + Py_INCREF(*result); + return 1; +} +#endif +#if defined(CYTHON_DEBUG_VISIT_CONST) && CYTHON_DEBUG_VISIT_CONST + #define __Pyx_VISIT_CONST(obj) Py_VISIT(obj) +#else + #define __Pyx_VISIT_CONST(obj) +#endif +#if CYTHON_ASSUME_SAFE_MACROS + #define __Pyx_PySequence_ITEM(o, i) PySequence_ITEM(o, i) + #define __Pyx_PySequence_SIZE(seq) Py_SIZE(seq) + #define __Pyx_PyTuple_SET_ITEM(o, i, v) (PyTuple_SET_ITEM(o, i, v), (0)) + #define __Pyx_PyTuple_GET_ITEM(o, i) PyTuple_GET_ITEM(o, i) + #define __Pyx_PyList_SET_ITEM(o, i, v) (PyList_SET_ITEM(o, i, v), (0)) + #define __Pyx_PyList_GET_ITEM(o, i) PyList_GET_ITEM(o, i) +#else + #define __Pyx_PySequence_ITEM(o, i) PySequence_GetItem(o, i) + #define __Pyx_PySequence_SIZE(seq) PySequence_Size(seq) + #define __Pyx_PyTuple_SET_ITEM(o, i, v) PyTuple_SetItem(o, i, v) + #define __Pyx_PyTuple_GET_ITEM(o, i) PyTuple_GetItem(o, i) + #define __Pyx_PyList_SET_ITEM(o, i, v) PyList_SetItem(o, i, v) + #define __Pyx_PyList_GET_ITEM(o, i) PyList_GetItem(o, i) +#endif +#if CYTHON_ASSUME_SAFE_SIZE + #define __Pyx_PyTuple_GET_SIZE(o) PyTuple_GET_SIZE(o) + #define __Pyx_PyList_GET_SIZE(o) PyList_GET_SIZE(o) + #define __Pyx_PySet_GET_SIZE(o) PySet_GET_SIZE(o) + #define __Pyx_PyBytes_GET_SIZE(o) PyBytes_GET_SIZE(o) + #define __Pyx_PyByteArray_GET_SIZE(o) PyByteArray_GET_SIZE(o) + #define __Pyx_PyUnicode_GET_LENGTH(o) PyUnicode_GET_LENGTH(o) +#else + #define __Pyx_PyTuple_GET_SIZE(o) PyTuple_Size(o) + #define __Pyx_PyList_GET_SIZE(o) PyList_Size(o) + #define __Pyx_PySet_GET_SIZE(o) PySet_Size(o) + #define __Pyx_PyBytes_GET_SIZE(o) PyBytes_Size(o) + #define __Pyx_PyByteArray_GET_SIZE(o) PyByteArray_Size(o) + #define __Pyx_PyUnicode_GET_LENGTH(o) PyUnicode_GetLength(o) +#endif +#if CYTHON_COMPILING_IN_PYPY && !defined(PyUnicode_InternFromString) + #define PyUnicode_InternFromString(s) PyUnicode_FromString(s) +#endif +#define __Pyx_PyLong_FromHash_t PyLong_FromSsize_t +#define __Pyx_PyLong_AsHash_t __Pyx_PyIndex_AsSsize_t +#if __PYX_LIMITED_VERSION_HEX >= 0x030A0000 + #define __Pyx_PySendResult PySendResult +#else + typedef enum { + PYGEN_RETURN = 0, + PYGEN_ERROR = -1, + PYGEN_NEXT = 1, + } __Pyx_PySendResult; +#endif +#if CYTHON_COMPILING_IN_LIMITED_API || PY_VERSION_HEX < 0x030A00A3 + typedef __Pyx_PySendResult (*__Pyx_pyiter_sendfunc)(PyObject *iter, PyObject *value, PyObject **result); +#else + #define __Pyx_pyiter_sendfunc sendfunc +#endif +#if !CYTHON_USE_AM_SEND +#define __PYX_HAS_PY_AM_SEND 0 +#elif __PYX_LIMITED_VERSION_HEX >= 0x030A0000 +#define __PYX_HAS_PY_AM_SEND 1 +#else +#define __PYX_HAS_PY_AM_SEND 2 // our own backported implementation +#endif +#if __PYX_HAS_PY_AM_SEND < 2 + #define __Pyx_PyAsyncMethodsStruct PyAsyncMethods +#else + typedef struct { + unaryfunc am_await; + unaryfunc am_aiter; + unaryfunc am_anext; + __Pyx_pyiter_sendfunc am_send; + } __Pyx_PyAsyncMethodsStruct; + #define __Pyx_SlotTpAsAsync(s) ((PyAsyncMethods*)(s)) +#endif +#if CYTHON_USE_AM_SEND && PY_VERSION_HEX < 0x030A00F0 + #define __Pyx_TPFLAGS_HAVE_AM_SEND (1UL << 21) +#else + #define __Pyx_TPFLAGS_HAVE_AM_SEND (0) +#endif +#if PY_VERSION_HEX >= 0x03090000 +#define __Pyx_PyInterpreterState_Get() PyInterpreterState_Get() +#else +#define __Pyx_PyInterpreterState_Get() PyThreadState_Get()->interp +#endif +#if CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030A0000 +#ifdef __cplusplus +extern "C" +#endif +PyAPI_FUNC(void *) PyMem_Calloc(size_t nelem, size_t elsize); +#endif +#if CYTHON_COMPILING_IN_LIMITED_API +static int __Pyx_init_co_variable(PyObject *inspect, const char* name, int *write_to) { + int value; + PyObject *py_value = PyObject_GetAttrString(inspect, name); + if (!py_value) return 0; + value = (int) PyLong_AsLong(py_value); + Py_DECREF(py_value); + *write_to = value; + return value != -1 || !PyErr_Occurred(); +} +static int __Pyx_init_co_variables(void) { + PyObject *inspect; + int result; + inspect = PyImport_ImportModule("inspect"); + result = +#if !defined(CO_OPTIMIZED) + __Pyx_init_co_variable(inspect, "CO_OPTIMIZED", &CO_OPTIMIZED) && +#endif +#if !defined(CO_NEWLOCALS) + __Pyx_init_co_variable(inspect, "CO_NEWLOCALS", &CO_NEWLOCALS) && +#endif +#if !defined(CO_VARARGS) + __Pyx_init_co_variable(inspect, "CO_VARARGS", &CO_VARARGS) && +#endif +#if !defined(CO_VARKEYWORDS) + __Pyx_init_co_variable(inspect, "CO_VARKEYWORDS", &CO_VARKEYWORDS) && +#endif +#if !defined(CO_ASYNC_GENERATOR) + __Pyx_init_co_variable(inspect, "CO_ASYNC_GENERATOR", &CO_ASYNC_GENERATOR) && +#endif +#if !defined(CO_GENERATOR) + __Pyx_init_co_variable(inspect, "CO_GENERATOR", &CO_GENERATOR) && +#endif +#if !defined(CO_COROUTINE) + __Pyx_init_co_variable(inspect, "CO_COROUTINE", &CO_COROUTINE) && +#endif + 1; + Py_DECREF(inspect); + return result ? 0 : -1; +} +#else +static int __Pyx_init_co_variables(void) { + return 0; // It's a limited API-only feature +} +#endif + +/* MathInitCode */ +#if defined(_WIN32) || defined(WIN32) || defined(MS_WINDOWS) + #ifndef _USE_MATH_DEFINES + #define _USE_MATH_DEFINES + #endif +#endif +#include +#if defined(__CYGWIN__) && defined(_LDBL_EQ_DBL) +#define __Pyx_truncl trunc +#else +#define __Pyx_truncl truncl +#endif + +#ifndef CYTHON_CLINE_IN_TRACEBACK_RUNTIME +#define CYTHON_CLINE_IN_TRACEBACK_RUNTIME 0 +#endif +#ifndef CYTHON_CLINE_IN_TRACEBACK +#define CYTHON_CLINE_IN_TRACEBACK CYTHON_CLINE_IN_TRACEBACK_RUNTIME +#endif +#if CYTHON_CLINE_IN_TRACEBACK +#define __PYX_MARK_ERR_POS(f_index, lineno) { __pyx_filename = __pyx_f[f_index]; (void) __pyx_filename; __pyx_lineno = lineno; (void) __pyx_lineno; __pyx_clineno = __LINE__; (void) __pyx_clineno; } +#else +#define __PYX_MARK_ERR_POS(f_index, lineno) { __pyx_filename = __pyx_f[f_index]; (void) __pyx_filename; __pyx_lineno = lineno; (void) __pyx_lineno; (void) __pyx_clineno; } +#endif +#define __PYX_ERR(f_index, lineno, Ln_error) \ + { __PYX_MARK_ERR_POS(f_index, lineno) goto Ln_error; } + +#ifdef CYTHON_EXTERN_C + #undef __PYX_EXTERN_C + #define __PYX_EXTERN_C CYTHON_EXTERN_C +#elif defined(__PYX_EXTERN_C) + #ifdef _MSC_VER + #pragma message ("Please do not define the '__PYX_EXTERN_C' macro externally. Use 'CYTHON_EXTERN_C' instead.") + #else + #warning Please do not define the '__PYX_EXTERN_C' macro externally. Use 'CYTHON_EXTERN_C' instead. + #endif +#else + #ifdef __cplusplus + #define __PYX_EXTERN_C extern "C" + #else + #define __PYX_EXTERN_C extern + #endif +#endif + +#define __PYX_HAVE__thriftpy2__transport__cybase +#define __PYX_HAVE_API__thriftpy2__transport__cybase +/* Early includes */ +#include +#include +#ifdef _OPENMP +#include +#endif /* _OPENMP */ + +#if defined(PYREX_WITHOUT_ASSERTIONS) && !defined(CYTHON_WITHOUT_ASSERTIONS) +#define CYTHON_WITHOUT_ASSERTIONS +#endif + +#ifdef CYTHON_FREETHREADING_COMPATIBLE +#if CYTHON_FREETHREADING_COMPATIBLE +#define __Pyx_FREETHREADING_COMPATIBLE Py_MOD_GIL_NOT_USED +#else +#define __Pyx_FREETHREADING_COMPATIBLE Py_MOD_GIL_USED +#endif +#else +#define __Pyx_FREETHREADING_COMPATIBLE Py_MOD_GIL_NOT_USED +#endif +#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 +#define __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 0 +#define __PYX_DEFAULT_STRING_ENCODING "" +#define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString +#define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#define __Pyx_uchar_cast(c) ((unsigned char)c) +#define __Pyx_long_cast(x) ((long)x) +#define __Pyx_fits_Py_ssize_t(v, type, is_signed) (\ + (sizeof(type) < sizeof(Py_ssize_t)) ||\ + (sizeof(type) > sizeof(Py_ssize_t) &&\ + likely(v < (type)PY_SSIZE_T_MAX ||\ + v == (type)PY_SSIZE_T_MAX) &&\ + (!is_signed || likely(v > (type)PY_SSIZE_T_MIN ||\ + v == (type)PY_SSIZE_T_MIN))) ||\ + (sizeof(type) == sizeof(Py_ssize_t) &&\ + (is_signed || likely(v < (type)PY_SSIZE_T_MAX ||\ + v == (type)PY_SSIZE_T_MAX))) ) +static CYTHON_INLINE int __Pyx_is_valid_index(Py_ssize_t i, Py_ssize_t limit) { + return (size_t) i < (size_t) limit; +} +#if defined (__cplusplus) && __cplusplus >= 201103L + #include + #define __Pyx_sst_abs(value) std::abs(value) +#elif SIZEOF_INT >= SIZEOF_SIZE_T + #define __Pyx_sst_abs(value) abs(value) +#elif SIZEOF_LONG >= SIZEOF_SIZE_T + #define __Pyx_sst_abs(value) labs(value) +#elif defined (_MSC_VER) + #define __Pyx_sst_abs(value) ((Py_ssize_t)_abs64(value)) +#elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define __Pyx_sst_abs(value) llabs(value) +#elif defined (__GNUC__) + #define __Pyx_sst_abs(value) __builtin_llabs(value) +#else + #define __Pyx_sst_abs(value) ((value<0) ? -value : value) +#endif +static CYTHON_INLINE Py_ssize_t __Pyx_ssize_strlen(const char *s); +static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject*); +static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); +static CYTHON_INLINE PyObject* __Pyx_PyByteArray_FromString(const char*); +#define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l) +#define __Pyx_PyBytes_FromString PyBytes_FromString +#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char*); +#if CYTHON_ASSUME_SAFE_MACROS + #define __Pyx_PyBytes_AsWritableString(s) ((char*) PyBytes_AS_STRING(s)) + #define __Pyx_PyBytes_AsWritableSString(s) ((signed char*) PyBytes_AS_STRING(s)) + #define __Pyx_PyBytes_AsWritableUString(s) ((unsigned char*) PyBytes_AS_STRING(s)) + #define __Pyx_PyBytes_AsString(s) ((const char*) PyBytes_AS_STRING(s)) + #define __Pyx_PyBytes_AsSString(s) ((const signed char*) PyBytes_AS_STRING(s)) + #define __Pyx_PyBytes_AsUString(s) ((const unsigned char*) PyBytes_AS_STRING(s)) + #define __Pyx_PyByteArray_AsString(s) PyByteArray_AS_STRING(s) +#else + #define __Pyx_PyBytes_AsWritableString(s) ((char*) PyBytes_AsString(s)) + #define __Pyx_PyBytes_AsWritableSString(s) ((signed char*) PyBytes_AsString(s)) + #define __Pyx_PyBytes_AsWritableUString(s) ((unsigned char*) PyBytes_AsString(s)) + #define __Pyx_PyBytes_AsString(s) ((const char*) PyBytes_AsString(s)) + #define __Pyx_PyBytes_AsSString(s) ((const signed char*) PyBytes_AsString(s)) + #define __Pyx_PyBytes_AsUString(s) ((const unsigned char*) PyBytes_AsString(s)) + #define __Pyx_PyByteArray_AsString(s) PyByteArray_AsString(s) +#endif +#define __Pyx_PyObject_AsWritableString(s) ((char*)(__pyx_uintptr_t) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsWritableSString(s) ((signed char*)(__pyx_uintptr_t) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsWritableUString(s) ((unsigned char*)(__pyx_uintptr_t) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsSString(s) ((const signed char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsUString(s) ((const unsigned char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_FromCString(s) __Pyx_PyObject_FromString((const char*)s) +#define __Pyx_PyBytes_FromCString(s) __Pyx_PyBytes_FromString((const char*)s) +#define __Pyx_PyByteArray_FromCString(s) __Pyx_PyByteArray_FromString((const char*)s) +#define __Pyx_PyUnicode_FromCString(s) __Pyx_PyUnicode_FromString((const char*)s) +#define __Pyx_PyUnicode_FromOrdinal(o) PyUnicode_FromOrdinal((int)o) +#define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode +static CYTHON_INLINE PyObject *__Pyx_NewRef(PyObject *obj) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030a0000 || defined(Py_NewRef) + return Py_NewRef(obj); +#else + Py_INCREF(obj); + return obj; +#endif +} +static CYTHON_INLINE PyObject *__Pyx_XNewRef(PyObject *obj) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030a0000 || defined(Py_XNewRef) + return Py_XNewRef(obj); +#else + Py_XINCREF(obj); + return obj; +#endif +} +static CYTHON_INLINE PyObject *__Pyx_Owned_Py_None(int b); +static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b); +static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); +static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject*); +static CYTHON_INLINE PyObject* __Pyx_PyNumber_Long(PyObject* x); +#define __Pyx_PySequence_Tuple(obj)\ + (likely(PyTuple_CheckExact(obj)) ? __Pyx_NewRef(obj) : PySequence_Tuple(obj)) +static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); +static CYTHON_INLINE PyObject * __Pyx_PyLong_FromSize_t(size_t); +static CYTHON_INLINE Py_hash_t __Pyx_PyIndex_AsHash_t(PyObject*); +#if CYTHON_ASSUME_SAFE_MACROS +#define __Pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) +#define __Pyx_PyFloat_AS_DOUBLE(x) PyFloat_AS_DOUBLE(x) +#else +#define __Pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) +#define __Pyx_PyFloat_AS_DOUBLE(x) PyFloat_AsDouble(x) +#endif +#define __Pyx_PyFloat_AsFloat(x) ((float) __Pyx_PyFloat_AsDouble(x)) +#define __Pyx_PyNumber_Int(x) (PyLong_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Long(x)) +#if CYTHON_USE_PYLONG_INTERNALS + #if PY_VERSION_HEX >= 0x030C00A7 + #ifndef _PyLong_SIGN_MASK + #define _PyLong_SIGN_MASK 3 + #endif + #ifndef _PyLong_NON_SIZE_BITS + #define _PyLong_NON_SIZE_BITS 3 + #endif + #define __Pyx_PyLong_Sign(x) (((PyLongObject*)x)->long_value.lv_tag & _PyLong_SIGN_MASK) + #define __Pyx_PyLong_IsNeg(x) ((__Pyx_PyLong_Sign(x) & 2) != 0) + #define __Pyx_PyLong_IsNonNeg(x) (!__Pyx_PyLong_IsNeg(x)) + #define __Pyx_PyLong_IsZero(x) (__Pyx_PyLong_Sign(x) & 1) + #define __Pyx_PyLong_IsPos(x) (__Pyx_PyLong_Sign(x) == 0) + #define __Pyx_PyLong_CompactValueUnsigned(x) (__Pyx_PyLong_Digits(x)[0]) + #define __Pyx_PyLong_DigitCount(x) ((Py_ssize_t) (((PyLongObject*)x)->long_value.lv_tag >> _PyLong_NON_SIZE_BITS)) + #define __Pyx_PyLong_SignedDigitCount(x)\ + ((1 - (Py_ssize_t) __Pyx_PyLong_Sign(x)) * __Pyx_PyLong_DigitCount(x)) + #if defined(PyUnstable_Long_IsCompact) && defined(PyUnstable_Long_CompactValue) + #define __Pyx_PyLong_IsCompact(x) PyUnstable_Long_IsCompact((PyLongObject*) x) + #define __Pyx_PyLong_CompactValue(x) PyUnstable_Long_CompactValue((PyLongObject*) x) + #else + #define __Pyx_PyLong_IsCompact(x) (((PyLongObject*)x)->long_value.lv_tag < (2 << _PyLong_NON_SIZE_BITS)) + #define __Pyx_PyLong_CompactValue(x) ((1 - (Py_ssize_t) __Pyx_PyLong_Sign(x)) * (Py_ssize_t) __Pyx_PyLong_Digits(x)[0]) + #endif + typedef Py_ssize_t __Pyx_compact_pylong; + typedef size_t __Pyx_compact_upylong; + #else + #define __Pyx_PyLong_IsNeg(x) (Py_SIZE(x) < 0) + #define __Pyx_PyLong_IsNonNeg(x) (Py_SIZE(x) >= 0) + #define __Pyx_PyLong_IsZero(x) (Py_SIZE(x) == 0) + #define __Pyx_PyLong_IsPos(x) (Py_SIZE(x) > 0) + #define __Pyx_PyLong_CompactValueUnsigned(x) ((Py_SIZE(x) == 0) ? 0 : __Pyx_PyLong_Digits(x)[0]) + #define __Pyx_PyLong_DigitCount(x) __Pyx_sst_abs(Py_SIZE(x)) + #define __Pyx_PyLong_SignedDigitCount(x) Py_SIZE(x) + #define __Pyx_PyLong_IsCompact(x) (Py_SIZE(x) == 0 || Py_SIZE(x) == 1 || Py_SIZE(x) == -1) + #define __Pyx_PyLong_CompactValue(x)\ + ((Py_SIZE(x) == 0) ? (sdigit) 0 : ((Py_SIZE(x) < 0) ? -(sdigit)__Pyx_PyLong_Digits(x)[0] : (sdigit)__Pyx_PyLong_Digits(x)[0])) + typedef sdigit __Pyx_compact_pylong; + typedef digit __Pyx_compact_upylong; + #endif + #if PY_VERSION_HEX >= 0x030C00A5 + #define __Pyx_PyLong_Digits(x) (((PyLongObject*)x)->long_value.ob_digit) + #else + #define __Pyx_PyLong_Digits(x) (((PyLongObject*)x)->ob_digit) + #endif +#endif +#if __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 + #define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) +#elif __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + #define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeASCII(c_str, size, NULL) +#else + #define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) +#endif + + +/* Test for GCC > 2.95 */ +#if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))) + #define likely(x) __builtin_expect(!!(x), 1) + #define unlikely(x) __builtin_expect(!!(x), 0) +#else /* !__GNUC__ or GCC < 2.95 */ + #define likely(x) (x) + #define unlikely(x) (x) +#endif /* __GNUC__ */ +/* PretendToInitialize */ +#ifdef __cplusplus +#if __cplusplus > 201103L +#include +#endif +template +static void __Pyx_pretend_to_initialize(T* ptr) { +#if __cplusplus > 201103L + if ((std::is_trivially_default_constructible::value)) +#endif + *ptr = T(); + (void)ptr; +} +#else +static CYTHON_INLINE void __Pyx_pretend_to_initialize(void* ptr) { (void)ptr; } +#endif + + +#if !CYTHON_USE_MODULE_STATE +static PyObject *__pyx_m = NULL; +#endif +static int __pyx_lineno; +static int __pyx_clineno = 0; +static const char * const __pyx_cfilenm = __FILE__; +static const char *__pyx_filename; + +/* #### Code section: filename_table ### */ + +static const char* const __pyx_f[] = { + "thriftpy2/transport/cybase.pyx", + "", +}; +/* #### Code section: utility_code_proto_before_types ### */ +/* Atomics.proto (used by UnpackUnboundCMethod) */ +#include +#ifndef CYTHON_ATOMICS + #define CYTHON_ATOMICS 1 +#endif +#define __PYX_CYTHON_ATOMICS_ENABLED() CYTHON_ATOMICS +#define __PYX_GET_CYTHON_COMPILING_IN_CPYTHON_FREETHREADING() CYTHON_COMPILING_IN_CPYTHON_FREETHREADING +#define __pyx_atomic_int_type int +#define __pyx_nonatomic_int_type int +#if CYTHON_ATOMICS && (defined(__STDC_VERSION__) &&\ + (__STDC_VERSION__ >= 201112L) &&\ + !defined(__STDC_NO_ATOMICS__)) + #include +#elif CYTHON_ATOMICS && (defined(__cplusplus) && (\ + (__cplusplus >= 201103L) ||\ + (defined(_MSC_VER) && _MSC_VER >= 1700))) + #include +#endif +#if CYTHON_ATOMICS && (defined(__STDC_VERSION__) &&\ + (__STDC_VERSION__ >= 201112L) &&\ + !defined(__STDC_NO_ATOMICS__) &&\ + ATOMIC_INT_LOCK_FREE == 2) + #undef __pyx_atomic_int_type + #define __pyx_atomic_int_type atomic_int + #define __pyx_atomic_ptr_type atomic_uintptr_t + #define __pyx_nonatomic_ptr_type uintptr_t + #define __pyx_atomic_incr_relaxed(value) atomic_fetch_add_explicit(value, 1, memory_order_relaxed) + #define __pyx_atomic_incr_acq_rel(value) atomic_fetch_add_explicit(value, 1, memory_order_acq_rel) + #define __pyx_atomic_decr_acq_rel(value) atomic_fetch_sub_explicit(value, 1, memory_order_acq_rel) + #define __pyx_atomic_sub(value, arg) atomic_fetch_sub(value, arg) + #define __pyx_atomic_int_cmp_exchange(value, expected, desired) atomic_compare_exchange_strong(value, expected, desired) + #define __pyx_atomic_load(value) atomic_load(value) + #define __pyx_atomic_store(value, new_value) atomic_store(value, new_value) + #define __pyx_atomic_pointer_load_relaxed(value) atomic_load_explicit(value, memory_order_relaxed) + #define __pyx_atomic_pointer_load_acquire(value) atomic_load_explicit(value, memory_order_acquire) + #define __pyx_atomic_pointer_exchange(value, new_value) atomic_exchange(value, (__pyx_nonatomic_ptr_type)new_value) + #define __pyx_atomic_pointer_cmp_exchange(value, expected, desired) atomic_compare_exchange_strong(value, expected, desired) + #if defined(__PYX_DEBUG_ATOMICS) && defined(_MSC_VER) + #pragma message ("Using standard C atomics") + #elif defined(__PYX_DEBUG_ATOMICS) + #warning "Using standard C atomics" + #endif +#elif CYTHON_ATOMICS && (defined(__cplusplus) && (\ + (__cplusplus >= 201103L) ||\ +\ + (defined(_MSC_VER) && _MSC_VER >= 1700)) &&\ + ATOMIC_INT_LOCK_FREE == 2) + #undef __pyx_atomic_int_type + #define __pyx_atomic_int_type std::atomic_int + #define __pyx_atomic_ptr_type std::atomic_uintptr_t + #define __pyx_nonatomic_ptr_type uintptr_t + #define __pyx_atomic_incr_relaxed(value) std::atomic_fetch_add_explicit(value, 1, std::memory_order_relaxed) + #define __pyx_atomic_incr_acq_rel(value) std::atomic_fetch_add_explicit(value, 1, std::memory_order_acq_rel) + #define __pyx_atomic_decr_acq_rel(value) std::atomic_fetch_sub_explicit(value, 1, std::memory_order_acq_rel) + #define __pyx_atomic_sub(value, arg) std::atomic_fetch_sub(value, arg) + #define __pyx_atomic_int_cmp_exchange(value, expected, desired) std::atomic_compare_exchange_strong(value, expected, desired) + #define __pyx_atomic_load(value) std::atomic_load(value) + #define __pyx_atomic_store(value, new_value) std::atomic_store(value, new_value) + #define __pyx_atomic_pointer_load_relaxed(value) std::atomic_load_explicit(value, std::memory_order_relaxed) + #define __pyx_atomic_pointer_load_acquire(value) std::atomic_load_explicit(value, std::memory_order_acquire) + #define __pyx_atomic_pointer_exchange(value, new_value) std::atomic_exchange(value, (__pyx_nonatomic_ptr_type)new_value) + #define __pyx_atomic_pointer_cmp_exchange(value, expected, desired) std::atomic_compare_exchange_strong(value, expected, desired) + #if defined(__PYX_DEBUG_ATOMICS) && defined(_MSC_VER) + #pragma message ("Using standard C++ atomics") + #elif defined(__PYX_DEBUG_ATOMICS) + #warning "Using standard C++ atomics" + #endif +#elif CYTHON_ATOMICS && (__GNUC__ >= 5 || (__GNUC__ == 4 &&\ + (__GNUC_MINOR__ > 1 ||\ + (__GNUC_MINOR__ == 1 && __GNUC_PATCHLEVEL__ >= 2)))) + #define __pyx_atomic_ptr_type void* + #define __pyx_nonatomic_ptr_type void* + #define __pyx_atomic_incr_relaxed(value) __sync_fetch_and_add(value, 1) + #define __pyx_atomic_incr_acq_rel(value) __sync_fetch_and_add(value, 1) + #define __pyx_atomic_decr_acq_rel(value) __sync_fetch_and_sub(value, 1) + #define __pyx_atomic_sub(value, arg) __sync_fetch_and_sub(value, arg) + static CYTHON_INLINE int __pyx_atomic_int_cmp_exchange(__pyx_atomic_int_type* value, __pyx_nonatomic_int_type* expected, __pyx_nonatomic_int_type desired) { + __pyx_nonatomic_int_type old = __sync_val_compare_and_swap(value, *expected, desired); + int result = old == *expected; + *expected = old; + return result; + } + #define __pyx_atomic_load(value) __sync_fetch_and_add(value, 0) + #define __pyx_atomic_store(value, new_value) __sync_lock_test_and_set(value, new_value) + #define __pyx_atomic_pointer_load_relaxed(value) __sync_fetch_and_add(value, 0) + #define __pyx_atomic_pointer_load_acquire(value) __sync_fetch_and_add(value, 0) + #define __pyx_atomic_pointer_exchange(value, new_value) __sync_lock_test_and_set(value, (__pyx_atomic_ptr_type)new_value) + static CYTHON_INLINE int __pyx_atomic_pointer_cmp_exchange(__pyx_atomic_ptr_type* value, __pyx_nonatomic_ptr_type* expected, __pyx_nonatomic_ptr_type desired) { + __pyx_nonatomic_ptr_type old = __sync_val_compare_and_swap(value, *expected, desired); + int result = old == *expected; + *expected = old; + return result; + } + #ifdef __PYX_DEBUG_ATOMICS + #warning "Using GNU atomics" + #endif +#elif CYTHON_ATOMICS && defined(_MSC_VER) + #include + #undef __pyx_atomic_int_type + #define __pyx_atomic_int_type long + #define __pyx_atomic_ptr_type void* + #undef __pyx_nonatomic_int_type + #define __pyx_nonatomic_int_type long + #define __pyx_nonatomic_ptr_type void* + #pragma intrinsic (_InterlockedExchangeAdd, _InterlockedExchange, _InterlockedCompareExchange, _InterlockedCompareExchangePointer, _InterlockedExchangePointer) + #define __pyx_atomic_incr_relaxed(value) _InterlockedExchangeAdd(value, 1) + #define __pyx_atomic_incr_acq_rel(value) _InterlockedExchangeAdd(value, 1) + #define __pyx_atomic_decr_acq_rel(value) _InterlockedExchangeAdd(value, -1) + #define __pyx_atomic_sub(value, arg) _InterlockedExchangeAdd(value, -arg) + static CYTHON_INLINE int __pyx_atomic_int_cmp_exchange(__pyx_atomic_int_type* value, __pyx_nonatomic_int_type* expected, __pyx_nonatomic_int_type desired) { + __pyx_nonatomic_int_type old = _InterlockedCompareExchange(value, desired, *expected); + int result = old == *expected; + *expected = old; + return result; + } + #define __pyx_atomic_load(value) _InterlockedExchangeAdd(value, 0) + #define __pyx_atomic_store(value, new_value) _InterlockedExchange(value, new_value) + #define __pyx_atomic_pointer_load_relaxed(value) *(void * volatile *)value + #define __pyx_atomic_pointer_load_acquire(value) _InterlockedCompareExchangePointer(value, 0, 0) + #define __pyx_atomic_pointer_exchange(value, new_value) _InterlockedExchangePointer(value, (__pyx_atomic_ptr_type)new_value) + static CYTHON_INLINE int __pyx_atomic_pointer_cmp_exchange(__pyx_atomic_ptr_type* value, __pyx_nonatomic_ptr_type* expected, __pyx_nonatomic_ptr_type desired) { + __pyx_atomic_ptr_type old = _InterlockedCompareExchangePointer(value, desired, *expected); + int result = old == *expected; + *expected = old; + return result; + } + #ifdef __PYX_DEBUG_ATOMICS + #pragma message ("Using MSVC atomics") + #endif +#else + #undef CYTHON_ATOMICS + #define CYTHON_ATOMICS 0 + #ifdef __PYX_DEBUG_ATOMICS + #warning "Not using atomics" + #endif +#endif + +/* CriticalSectionsDefinition.proto (used by CriticalSections) */ +#if !CYTHON_COMPILING_IN_CPYTHON_FREETHREADING +#define __Pyx_PyCriticalSection void* +#define __Pyx_PyCriticalSection2 void* +#define __Pyx_PyCriticalSection_End(cs) +#define __Pyx_PyCriticalSection2_End(cs) +#else +#define __Pyx_PyCriticalSection PyCriticalSection +#define __Pyx_PyCriticalSection2 PyCriticalSection2 +#define __Pyx_PyCriticalSection_End PyCriticalSection_End +#define __Pyx_PyCriticalSection2_End PyCriticalSection2_End +#endif + +/* CriticalSections.proto (used by ParseKeywordsImpl) */ +#if !CYTHON_COMPILING_IN_CPYTHON_FREETHREADING +#define __Pyx_PyCriticalSection_Begin(cs, arg) (void)(cs) +#define __Pyx_PyCriticalSection2_Begin(cs, arg1, arg2) (void)(cs) +#else +#define __Pyx_PyCriticalSection_Begin PyCriticalSection_Begin +#define __Pyx_PyCriticalSection2_Begin PyCriticalSection2_Begin +#endif +#if PY_VERSION_HEX < 0x030d0000 || CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_BEGIN_CRITICAL_SECTION(o) { +#define __Pyx_END_CRITICAL_SECTION() } +#else +#define __Pyx_BEGIN_CRITICAL_SECTION Py_BEGIN_CRITICAL_SECTION +#define __Pyx_END_CRITICAL_SECTION Py_END_CRITICAL_SECTION +#endif + +/* IncludeStructmemberH.proto (used by FixUpExtensionType) */ +#include + +/* #### Code section: numeric_typedefs ### */ +/* #### Code section: complex_type_declarations ### */ +/* #### Code section: type_declarations ### */ + +/*--- Type declarations ---*/ +struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer; +struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase; + +/* "thriftpy2/transport/cybase.pxd":3 + * # cython: freethreading_compatible = True + * + * cdef enum: # <<<<<<<<<<<<<< + * DEFAULT_BUFFER = 4096 + * STACK_STRING_LEN = 4096 +*/ +enum { + __pyx_e_9thriftpy2_9transport_6cybase_DEFAULT_BUFFER = 0x1000, + __pyx_e_9thriftpy2_9transport_6cybase_STACK_STRING_LEN = 0x1000 +}; + +/* "thriftpy2/transport/cybase.pxd":7 + * STACK_STRING_LEN = 4096 + * + * cdef class TCyBuffer(object): # <<<<<<<<<<<<<< + * cdef: + * char *buf +*/ +struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer { + PyObject_HEAD + struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_TCyBuffer *__pyx_vtab; + char *buf; + int cur; + int buf_size; + int data_size; +}; + + +/* "thriftpy2/transport/cybase.pxd":19 + * + * + * cdef class CyTransportBase(object): # <<<<<<<<<<<<<< + * cdef object trans + * +*/ +struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase { + PyObject_HEAD + struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_CyTransportBase *__pyx_vtab; + PyObject *trans; +}; + + + +/* "thriftpy2/transport/cybase.pyx":7 + * + * + * cdef class TCyBuffer(object): # <<<<<<<<<<<<<< + * def __cinit__(self, buf_size): + * self.buf = malloc(buf_size) +*/ + +struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_TCyBuffer { + void (*move_to_start)(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *); + void (*clean)(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *); + int (*write)(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *, int, char const *); + int (*grow)(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *, int); + PyObject *(*read_trans)(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *, PyObject *, int, char *); +}; +static struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_TCyBuffer *__pyx_vtabptr_9thriftpy2_9transport_6cybase_TCyBuffer; + + +/* "thriftpy2/transport/cybase.pyx":107 + * + * + * cdef class CyTransportBase(object): # <<<<<<<<<<<<<< + * cdef c_read(self, int sz, char* out): + * pass +*/ + +struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_CyTransportBase { + PyObject *(*c_read)(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *, int, char *); + PyObject *(*c_write)(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *, char *, int); + PyObject *(*c_flush)(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *); + PyObject *(*get_string)(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *, int); +}; +static struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_CyTransportBase *__pyx_vtabptr_9thriftpy2_9transport_6cybase_CyTransportBase; +/* #### Code section: utility_code_proto ### */ + +/* --- Runtime support code (head) --- */ +/* Refnanny.proto */ +#ifndef CYTHON_REFNANNY + #define CYTHON_REFNANNY 0 +#endif +#if CYTHON_REFNANNY + typedef struct { + void (*INCREF)(void*, PyObject*, Py_ssize_t); + void (*DECREF)(void*, PyObject*, Py_ssize_t); + void (*GOTREF)(void*, PyObject*, Py_ssize_t); + void (*GIVEREF)(void*, PyObject*, Py_ssize_t); + void* (*SetupContext)(const char*, Py_ssize_t, const char*); + void (*FinishContext)(void**); + } __Pyx_RefNannyAPIStruct; + static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; + static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); + #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; + #define __Pyx_RefNannySetupContext(name, acquire_gil)\ + if (acquire_gil) {\ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), (__LINE__), (__FILE__));\ + PyGILState_Release(__pyx_gilstate_save);\ + } else {\ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), (__LINE__), (__FILE__));\ + } + #define __Pyx_RefNannyFinishContextNogil() {\ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ + __Pyx_RefNannyFinishContext();\ + PyGILState_Release(__pyx_gilstate_save);\ + } + #define __Pyx_RefNannyFinishContextNogil() {\ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ + __Pyx_RefNannyFinishContext();\ + PyGILState_Release(__pyx_gilstate_save);\ + } + #define __Pyx_RefNannyFinishContext()\ + __Pyx_RefNanny->FinishContext(&__pyx_refnanny) + #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), (__LINE__)) + #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), (__LINE__)) + #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), (__LINE__)) + #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), (__LINE__)) + #define __Pyx_XINCREF(r) do { if((r) == NULL); else {__Pyx_INCREF(r); }} while(0) + #define __Pyx_XDECREF(r) do { if((r) == NULL); else {__Pyx_DECREF(r); }} while(0) + #define __Pyx_XGOTREF(r) do { if((r) == NULL); else {__Pyx_GOTREF(r); }} while(0) + #define __Pyx_XGIVEREF(r) do { if((r) == NULL); else {__Pyx_GIVEREF(r);}} while(0) +#else + #define __Pyx_RefNannyDeclarations + #define __Pyx_RefNannySetupContext(name, acquire_gil) + #define __Pyx_RefNannyFinishContextNogil() + #define __Pyx_RefNannyFinishContext() + #define __Pyx_INCREF(r) Py_INCREF(r) + #define __Pyx_DECREF(r) Py_DECREF(r) + #define __Pyx_GOTREF(r) + #define __Pyx_GIVEREF(r) + #define __Pyx_XINCREF(r) Py_XINCREF(r) + #define __Pyx_XDECREF(r) Py_XDECREF(r) + #define __Pyx_XGOTREF(r) + #define __Pyx_XGIVEREF(r) +#endif +#define __Pyx_Py_XDECREF_SET(r, v) do {\ + PyObject *tmp = (PyObject *) r;\ + r = v; Py_XDECREF(tmp);\ + } while (0) +#define __Pyx_XDECREF_SET(r, v) do {\ + PyObject *tmp = (PyObject *) r;\ + r = v; __Pyx_XDECREF(tmp);\ + } while (0) +#define __Pyx_DECREF_SET(r, v) do {\ + PyObject *tmp = (PyObject *) r;\ + r = v; __Pyx_DECREF(tmp);\ + } while (0) +#define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) +#define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) + +/* TupleAndListFromArray.proto (used by fastcall) */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyList_FromArray(PyObject *const *src, Py_ssize_t n); +#endif +#if CYTHON_COMPILING_IN_CPYTHON || CYTHON_METH_FASTCALL +static CYTHON_INLINE PyObject* __Pyx_PyTuple_FromArray(PyObject *const *src, Py_ssize_t n); +#endif + +/* IncludeStringH.proto (used by BytesEquals) */ +#include + +/* BytesEquals.proto (used by UnicodeEquals) */ +static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals); + +/* UnicodeEquals.proto (used by fastcall) */ +static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals); + +/* fastcall.proto */ +#if CYTHON_AVOID_BORROWED_REFS + #define __Pyx_ArgRef_VARARGS(args, i) __Pyx_PySequence_ITEM(args, i) +#elif CYTHON_ASSUME_SAFE_MACROS + #define __Pyx_ArgRef_VARARGS(args, i) __Pyx_NewRef(__Pyx_PyTuple_GET_ITEM(args, i)) +#else + #define __Pyx_ArgRef_VARARGS(args, i) __Pyx_XNewRef(PyTuple_GetItem(args, i)) +#endif +#define __Pyx_NumKwargs_VARARGS(kwds) PyDict_Size(kwds) +#define __Pyx_KwValues_VARARGS(args, nargs) NULL +#define __Pyx_GetKwValue_VARARGS(kw, kwvalues, s) __Pyx_PyDict_GetItemStrWithError(kw, s) +#define __Pyx_KwargsAsDict_VARARGS(kw, kwvalues) PyDict_Copy(kw) +#if CYTHON_METH_FASTCALL + #define __Pyx_ArgRef_FASTCALL(args, i) __Pyx_NewRef(args[i]) + #define __Pyx_NumKwargs_FASTCALL(kwds) __Pyx_PyTuple_GET_SIZE(kwds) + #define __Pyx_KwValues_FASTCALL(args, nargs) ((args) + (nargs)) + static CYTHON_INLINE PyObject * __Pyx_GetKwValue_FASTCALL(PyObject *kwnames, PyObject *const *kwvalues, PyObject *s); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030d0000 || CYTHON_COMPILING_IN_LIMITED_API + CYTHON_UNUSED static PyObject *__Pyx_KwargsAsDict_FASTCALL(PyObject *kwnames, PyObject *const *kwvalues); + #else + #define __Pyx_KwargsAsDict_FASTCALL(kw, kwvalues) _PyStack_AsDict(kwvalues, kw) + #endif +#else + #define __Pyx_ArgRef_FASTCALL __Pyx_ArgRef_VARARGS + #define __Pyx_NumKwargs_FASTCALL __Pyx_NumKwargs_VARARGS + #define __Pyx_KwValues_FASTCALL __Pyx_KwValues_VARARGS + #define __Pyx_GetKwValue_FASTCALL __Pyx_GetKwValue_VARARGS + #define __Pyx_KwargsAsDict_FASTCALL __Pyx_KwargsAsDict_VARARGS +#endif +#define __Pyx_ArgsSlice_VARARGS(args, start, stop) PyTuple_GetSlice(args, start, stop) +#if CYTHON_METH_FASTCALL || (CYTHON_COMPILING_IN_CPYTHON && CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS) +#define __Pyx_ArgsSlice_FASTCALL(args, start, stop) __Pyx_PyTuple_FromArray(args + start, stop - start) +#else +#define __Pyx_ArgsSlice_FASTCALL(args, start, stop) PyTuple_GetSlice(args, start, stop) +#endif + +/* py_dict_items.proto (used by OwnedDictNext) */ +static CYTHON_INLINE PyObject* __Pyx_PyDict_Items(PyObject* d); + +/* CallCFunction.proto (used by CallUnboundCMethod0) */ +#define __Pyx_CallCFunction(cfunc, self, args)\ + ((PyCFunction)(void(*)(void))(cfunc)->func)(self, args) +#define __Pyx_CallCFunctionWithKeywords(cfunc, self, args, kwargs)\ + ((PyCFunctionWithKeywords)(void(*)(void))(cfunc)->func)(self, args, kwargs) +#define __Pyx_CallCFunctionFast(cfunc, self, args, nargs)\ + ((__Pyx_PyCFunctionFast)(void(*)(void))(PyCFunction)(cfunc)->func)(self, args, nargs) +#define __Pyx_CallCFunctionFastWithKeywords(cfunc, self, args, nargs, kwnames)\ + ((__Pyx_PyCFunctionFastWithKeywords)(void(*)(void))(PyCFunction)(cfunc)->func)(self, args, nargs, kwnames) + +/* PyObjectCall.proto (used by PyObjectFastCall) */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw); +#else +#define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw) +#endif + +/* PyObjectCallMethO.proto (used by PyObjectFastCall) */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg); +#endif + +/* PyObjectFastCall.proto (used by PyObjectCallOneArg) */ +#define __Pyx_PyObject_FastCall(func, args, nargs) __Pyx_PyObject_FastCallDict(func, args, (size_t)(nargs), NULL) +static CYTHON_INLINE PyObject* __Pyx_PyObject_FastCallDict(PyObject *func, PyObject * const*args, size_t nargs, PyObject *kwargs); + +/* PyObjectCallOneArg.proto (used by CallUnboundCMethod0) */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg); + +/* PyObjectGetAttrStr.proto (used by UnpackUnboundCMethod) */ +#if CYTHON_USE_TYPE_SLOTS +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name); +#else +#define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) +#endif + +/* UnpackUnboundCMethod.proto (used by CallUnboundCMethod0) */ +typedef struct { + PyObject *type; + PyObject **method_name; +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING && CYTHON_ATOMICS + __pyx_atomic_int_type initialized; +#endif + PyCFunction func; + PyObject *method; + int flag; +} __Pyx_CachedCFunction; +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING +static CYTHON_INLINE int __Pyx_CachedCFunction_GetAndSetInitializing(__Pyx_CachedCFunction *cfunc) { +#if !CYTHON_ATOMICS + return 1; +#else + __pyx_nonatomic_int_type expected = 0; + if (__pyx_atomic_int_cmp_exchange(&cfunc->initialized, &expected, 1)) { + return 0; + } + return expected; +#endif +} +static CYTHON_INLINE void __Pyx_CachedCFunction_SetFinishedInitializing(__Pyx_CachedCFunction *cfunc) { +#if CYTHON_ATOMICS + __pyx_atomic_store(&cfunc->initialized, 2); +#endif +} +#else +#define __Pyx_CachedCFunction_GetAndSetInitializing(cfunc) 2 +#define __Pyx_CachedCFunction_SetFinishedInitializing(cfunc) +#endif + +/* CallUnboundCMethod0.proto */ +CYTHON_UNUSED +static PyObject* __Pyx__CallUnboundCMethod0(__Pyx_CachedCFunction* cfunc, PyObject* self); +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_CallUnboundCMethod0(__Pyx_CachedCFunction* cfunc, PyObject* self); +#else +#define __Pyx_CallUnboundCMethod0(cfunc, self) __Pyx__CallUnboundCMethod0(cfunc, self) +#endif + +/* py_dict_values.proto (used by OwnedDictNext) */ +static CYTHON_INLINE PyObject* __Pyx_PyDict_Values(PyObject* d); + +/* OwnedDictNext.proto (used by ParseKeywordsImpl) */ +#if CYTHON_AVOID_BORROWED_REFS +static int __Pyx_PyDict_NextRef(PyObject *p, PyObject **ppos, PyObject **pkey, PyObject **pvalue); +#else +CYTHON_INLINE +static int __Pyx_PyDict_NextRef(PyObject *p, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue); +#endif + +/* RaiseDoubleKeywords.proto (used by ParseKeywordsImpl) */ +static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); + +/* ParseKeywordsImpl.export */ +static int __Pyx_ParseKeywordsTuple( + PyObject *kwds, + PyObject * const *kwvalues, + PyObject ** const argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + Py_ssize_t num_kwargs, + const char* function_name, + int ignore_unknown_kwargs +); +static int __Pyx_ParseKeywordDictToDict( + PyObject *kwds, + PyObject ** const argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + const char* function_name +); +static int __Pyx_ParseKeywordDict( + PyObject *kwds, + PyObject ** const argnames[], + PyObject *values[], + Py_ssize_t num_pos_args, + Py_ssize_t num_kwargs, + const char* function_name, + int ignore_unknown_kwargs +); + +/* CallUnboundCMethod2.proto */ +CYTHON_UNUSED +static PyObject* __Pyx__CallUnboundCMethod2(__Pyx_CachedCFunction* cfunc, PyObject* self, PyObject* arg1, PyObject* arg2); +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject *__Pyx_CallUnboundCMethod2(__Pyx_CachedCFunction *cfunc, PyObject *self, PyObject *arg1, PyObject *arg2); +#else +#define __Pyx_CallUnboundCMethod2(cfunc, self, arg1, arg2) __Pyx__CallUnboundCMethod2(cfunc, self, arg1, arg2) +#endif + +/* ParseKeywords.proto */ +static CYTHON_INLINE int __Pyx_ParseKeywords( + PyObject *kwds, PyObject *const *kwvalues, PyObject ** const argnames[], + PyObject *kwds2, PyObject *values[], + Py_ssize_t num_pos_args, Py_ssize_t num_kwargs, + const char* function_name, + int ignore_unknown_kwargs +); + +/* RaiseArgTupleInvalid.proto */ +static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, + Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); + +/* PyObjectFastCallMethod.proto */ +#if CYTHON_VECTORCALL && PY_VERSION_HEX >= 0x03090000 +#define __Pyx_PyObject_FastCallMethod(name, args, nargsf) PyObject_VectorcallMethod(name, args, nargsf, NULL) +#else +static PyObject *__Pyx_PyObject_FastCallMethod(PyObject *name, PyObject *const *args, size_t nargsf); +#endif + +/* DivInt[int].proto */ +static CYTHON_INLINE int __Pyx_div_int(int, int, int b_is_constant); + +/* UnaryNegOverflows.proto */ +#define __Pyx_UNARY_NEG_WOULD_OVERFLOW(x)\ + (((x) < 0) & ((unsigned long)(x) == 0-(unsigned long)(x))) + +/* ModInt[int].proto */ +static CYTHON_INLINE int __Pyx_mod_int(int, int, int b_is_constant); + +/* RejectKeywords.export */ +static void __Pyx_RejectKeywords(const char* function_name, PyObject *kwds); + +/* PyTypeError_Check.proto */ +#define __Pyx_PyExc_TypeError_Check(obj) __Pyx_TypeCheck(obj, PyExc_TypeError) + +/* PyThreadStateGet.proto (used by PyErrFetchRestore) */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_PyThreadState_declare PyThreadState *__pyx_tstate; +#define __Pyx_PyThreadState_assign __pyx_tstate = __Pyx_PyThreadState_Current; +#if PY_VERSION_HEX >= 0x030C00A6 +#define __Pyx_PyErr_Occurred() (__pyx_tstate->current_exception != NULL) +#define __Pyx_PyErr_CurrentExceptionType() (__pyx_tstate->current_exception ? (PyObject*) Py_TYPE(__pyx_tstate->current_exception) : (PyObject*) NULL) +#else +#define __Pyx_PyErr_Occurred() (__pyx_tstate->curexc_type != NULL) +#define __Pyx_PyErr_CurrentExceptionType() (__pyx_tstate->curexc_type) +#endif +#else +#define __Pyx_PyThreadState_declare +#define __Pyx_PyThreadState_assign +#define __Pyx_PyErr_Occurred() (PyErr_Occurred() != NULL) +#define __Pyx_PyErr_CurrentExceptionType() PyErr_Occurred() +#endif + +/* PyErrFetchRestore.proto (used by RaiseException) */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_PyErr_Clear() __Pyx_ErrRestore(NULL, NULL, NULL) +#define __Pyx_ErrRestoreWithState(type, value, tb) __Pyx_ErrRestoreInState(PyThreadState_GET(), type, value, tb) +#define __Pyx_ErrFetchWithState(type, value, tb) __Pyx_ErrFetchInState(PyThreadState_GET(), type, value, tb) +#define __Pyx_ErrRestore(type, value, tb) __Pyx_ErrRestoreInState(__pyx_tstate, type, value, tb) +#define __Pyx_ErrFetch(type, value, tb) __Pyx_ErrFetchInState(__pyx_tstate, type, value, tb) +static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); +static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030C00A6 +#define __Pyx_PyErr_SetNone(exc) (Py_INCREF(exc), __Pyx_ErrRestore((exc), NULL, NULL)) +#else +#define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) +#endif +#else +#define __Pyx_PyErr_Clear() PyErr_Clear() +#define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) +#define __Pyx_ErrRestoreWithState(type, value, tb) PyErr_Restore(type, value, tb) +#define __Pyx_ErrFetchWithState(type, value, tb) PyErr_Fetch(type, value, tb) +#define __Pyx_ErrRestoreInState(tstate, type, value, tb) PyErr_Restore(type, value, tb) +#define __Pyx_ErrFetchInState(tstate, type, value, tb) PyErr_Fetch(type, value, tb) +#define __Pyx_ErrRestore(type, value, tb) PyErr_Restore(type, value, tb) +#define __Pyx_ErrFetch(type, value, tb) PyErr_Fetch(type, value, tb) +#endif + +/* RaiseException.export */ +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); + +/* PyErrExceptionMatches.proto (used by GetAttr3) */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_PyErr_ExceptionMatches(err) __Pyx_PyErr_ExceptionMatchesInState(__pyx_tstate, err) +static CYTHON_INLINE int __Pyx_PyErr_ExceptionMatchesInState(PyThreadState* tstate, PyObject* err); +#else +#define __Pyx_PyErr_ExceptionMatches(err) PyErr_ExceptionMatches(err) +#endif + +/* GetAttr3.proto */ +static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *, PyObject *, PyObject *); + +/* GetException.proto */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_GetException(type, value, tb) __Pyx__GetException(__pyx_tstate, type, value, tb) +static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); +#else +static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb); +#endif + +/* SwapException.proto */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_ExceptionSwap(type, value, tb) __Pyx__ExceptionSwap(__pyx_tstate, type, value, tb) +static CYTHON_INLINE void __Pyx__ExceptionSwap(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); +#else +static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb); +#endif + +/* GetTopmostException.proto (used by SaveResetException) */ +#if CYTHON_USE_EXC_INFO_STACK && CYTHON_FAST_THREAD_STATE +static _PyErr_StackItem * __Pyx_PyErr_GetTopmostException(PyThreadState *tstate); +#endif + +/* SaveResetException.proto */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_ExceptionSave(type, value, tb) __Pyx__ExceptionSave(__pyx_tstate, type, value, tb) +static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); +#define __Pyx_ExceptionReset(type, value, tb) __Pyx__ExceptionReset(__pyx_tstate, type, value, tb) +static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); +#else +#define __Pyx_ExceptionSave(type, value, tb) PyErr_GetExcInfo(type, value, tb) +#define __Pyx_ExceptionReset(type, value, tb) PyErr_SetExcInfo(type, value, tb) +#endif + +/* PyObjectGetAttrStrNoError.proto (used by GetBuiltinName) */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStrNoError(PyObject* obj, PyObject* attr_name); + +/* GetBuiltinName.proto (used by GetModuleGlobalName) */ +static PyObject *__Pyx_GetBuiltinName(PyObject *name); + +/* PyDictVersioning.proto (used by GetModuleGlobalName) */ +#if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_TYPE_SLOTS +#define __PYX_DICT_VERSION_INIT ((PY_UINT64_T) -1) +#define __PYX_GET_DICT_VERSION(dict) (((PyDictObject*)(dict))->ma_version_tag) +#define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var)\ + (version_var) = __PYX_GET_DICT_VERSION(dict);\ + (cache_var) = (value); +#define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) {\ + static PY_UINT64_T __pyx_dict_version = 0;\ + static PyObject *__pyx_dict_cached_value = NULL;\ + if (likely(__PYX_GET_DICT_VERSION(DICT) == __pyx_dict_version)) {\ + (VAR) = __Pyx_XNewRef(__pyx_dict_cached_value);\ + } else {\ + (VAR) = __pyx_dict_cached_value = (LOOKUP);\ + __pyx_dict_version = __PYX_GET_DICT_VERSION(DICT);\ + }\ +} +static CYTHON_INLINE PY_UINT64_T __Pyx_get_tp_dict_version(PyObject *obj); +static CYTHON_INLINE PY_UINT64_T __Pyx_get_object_dict_version(PyObject *obj); +static CYTHON_INLINE int __Pyx_object_dict_version_matches(PyObject* obj, PY_UINT64_T tp_dict_version, PY_UINT64_T obj_dict_version); +#else +#define __PYX_GET_DICT_VERSION(dict) (0) +#define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var) +#define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) (VAR) = (LOOKUP); +#endif + +/* GetModuleGlobalName.proto */ +#if CYTHON_USE_DICT_VERSIONS +#define __Pyx_GetModuleGlobalName(var, name) do {\ + static PY_UINT64_T __pyx_dict_version = 0;\ + static PyObject *__pyx_dict_cached_value = NULL;\ + (var) = (likely(__pyx_dict_version == __PYX_GET_DICT_VERSION(__pyx_mstate_global->__pyx_d))) ?\ + (likely(__pyx_dict_cached_value) ? __Pyx_NewRef(__pyx_dict_cached_value) : __Pyx_GetBuiltinName(name)) :\ + __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\ +} while(0) +#define __Pyx_GetModuleGlobalNameUncached(var, name) do {\ + PY_UINT64_T __pyx_dict_version;\ + PyObject *__pyx_dict_cached_value;\ + (var) = __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\ +} while(0) +static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_version, PyObject **dict_cached_value); +#else +#define __Pyx_GetModuleGlobalName(var, name) (var) = __Pyx__GetModuleGlobalName(name) +#define __Pyx_GetModuleGlobalNameUncached(var, name) (var) = __Pyx__GetModuleGlobalName(name) +static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name); +#endif + +/* RaiseUnexpectedTypeError.proto */ +static int __Pyx_RaiseUnexpectedTypeError(const char *expected, PyObject *obj); + +/* ArgTypeTestFunc.export */ +static int __Pyx__ArgTypeTest(PyObject *obj, PyTypeObject *type, const char *name, int exact); + +/* ArgTypeTest.proto */ +#define __Pyx_ArgTypeTest(obj, type, none_allowed, name, exact)\ + ((likely(__Pyx_IS_TYPE(obj, type) | (none_allowed && (obj == Py_None)))) ? 1 :\ + __Pyx__ArgTypeTest(obj, type, name, exact)) + +/* GetItemInt.proto */ +#define __Pyx_GetItemInt(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck, has_gil, unsafe_shared)\ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ + __Pyx_GetItemInt_Fast(o, (Py_ssize_t)i, is_list, wraparound, boundscheck, unsafe_shared) :\ + (is_list ? (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL) :\ + __Pyx_GetItemInt_Generic(o, to_py_func(i)))) +#define __Pyx_GetItemInt_List(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck, has_gil, unsafe_shared)\ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ + __Pyx_GetItemInt_List_Fast(o, (Py_ssize_t)i, wraparound, boundscheck, unsafe_shared) :\ + (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL)) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck, int unsafe_shared); +#define __Pyx_GetItemInt_Tuple(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck, has_gil, unsafe_shared)\ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ + __Pyx_GetItemInt_Tuple_Fast(o, (Py_ssize_t)i, wraparound, boundscheck, unsafe_shared) :\ + (PyErr_SetString(PyExc_IndexError, "tuple index out of range"), (PyObject*)NULL)) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck, int unsafe_shared); +static PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j); +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, + int is_list, int wraparound, int boundscheck, int unsafe_shared); + +/* AllocateExtensionType.proto */ +static PyObject *__Pyx_AllocateExtensionType(PyTypeObject *t, int is_final); + +/* CallTypeTraverse.proto */ +#if !CYTHON_USE_TYPE_SPECS || (!CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x03090000) +#define __Pyx_call_type_traverse(o, always_call, visit, arg) 0 +#else +static int __Pyx_call_type_traverse(PyObject *o, int always_call, visitproc visit, void *arg); +#endif + +/* LimitedApiGetTypeDict.proto (used by SetItemOnTypeDict) */ +#if CYTHON_COMPILING_IN_LIMITED_API +static PyObject *__Pyx_GetTypeDict(PyTypeObject *tp); +#endif + +/* SetItemOnTypeDict.proto (used by FixUpExtensionType) */ +static int __Pyx__SetItemOnTypeDict(PyTypeObject *tp, PyObject *k, PyObject *v); +#define __Pyx_SetItemOnTypeDict(tp, k, v) __Pyx__SetItemOnTypeDict((PyTypeObject*)tp, k, v) + +/* FixUpExtensionType.proto */ +static CYTHON_INLINE int __Pyx_fix_up_extension_type_from_spec(PyType_Spec *spec, PyTypeObject *type); + +/* PyObjectCallNoArg.proto (used by PyObjectCallMethod0) */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func); + +/* PyObjectGetMethod.proto (used by PyObjectCallMethod0) */ +#if !(CYTHON_VECTORCALL && (__PYX_LIMITED_VERSION_HEX >= 0x030C0000 || (!CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x03090000))) +static int __Pyx_PyObject_GetMethod(PyObject *obj, PyObject *name, PyObject **method); +#endif + +/* PyObjectCallMethod0.proto (used by PyType_Ready) */ +static PyObject* __Pyx_PyObject_CallMethod0(PyObject* obj, PyObject* method_name); + +/* ValidateBasesTuple.proto (used by PyType_Ready) */ +#if CYTHON_COMPILING_IN_CPYTHON || CYTHON_COMPILING_IN_LIMITED_API || CYTHON_USE_TYPE_SPECS +static int __Pyx_validate_bases_tuple(const char *type_name, Py_ssize_t dictoffset, PyObject *bases); +#endif + +/* PyType_Ready.proto */ +CYTHON_UNUSED static int __Pyx_PyType_Ready(PyTypeObject *t); + +/* SetVTable.proto */ +static int __Pyx_SetVtable(PyTypeObject* typeptr , void* vtable); + +/* GetVTable.proto (used by MergeVTables) */ +static void* __Pyx_GetVtable(PyTypeObject *type); + +/* MergeVTables.proto */ +static int __Pyx_MergeVtables(PyTypeObject *type); + +/* DelItemOnTypeDict.proto (used by SetupReduce) */ +static int __Pyx__DelItemOnTypeDict(PyTypeObject *tp, PyObject *k); +#define __Pyx_DelItemOnTypeDict(tp, k) __Pyx__DelItemOnTypeDict((PyTypeObject*)tp, k) + +/* SetupReduce.proto */ +static int __Pyx_setup_reduce(PyObject* type_obj); + +/* dict_setdefault.proto (used by FetchCommonType) */ +static CYTHON_INLINE PyObject *__Pyx_PyDict_SetDefault(PyObject *d, PyObject *key, PyObject *default_value); + +/* AddModuleRef.proto (used by FetchSharedCythonModule) */ +#if ((CYTHON_COMPILING_IN_CPYTHON_FREETHREADING ) ||\ + __PYX_LIMITED_VERSION_HEX < 0x030d0000) + static PyObject *__Pyx_PyImport_AddModuleRef(const char *name); +#else + #define __Pyx_PyImport_AddModuleRef(name) PyImport_AddModuleRef(name) +#endif + +/* FetchSharedCythonModule.proto (used by FetchCommonType) */ +static PyObject *__Pyx_FetchSharedCythonABIModule(void); + +/* FetchCommonType.proto (used by CommonTypesMetaclass) */ +static PyTypeObject* __Pyx_FetchCommonTypeFromSpec(PyTypeObject *metaclass, PyObject *module, PyType_Spec *spec, PyObject *bases); + +/* CommonTypesMetaclass.proto (used by CythonFunctionShared) */ +static int __pyx_CommonTypesMetaclass_init(PyObject *module); +#define __Pyx_CommonTypesMetaclass_USED + +/* PyMethodNew.proto (used by CythonFunctionShared) */ +static PyObject *__Pyx_PyMethod_New(PyObject *func, PyObject *self, PyObject *typ); + +/* PyVectorcallFastCallDict.proto (used by CythonFunctionShared) */ +#if CYTHON_METH_FASTCALL && CYTHON_VECTORCALL +static CYTHON_INLINE PyObject *__Pyx_PyVectorcall_FastCallDict(PyObject *func, __pyx_vectorcallfunc vc, PyObject *const *args, size_t nargs, PyObject *kw); +#endif + +/* CythonFunctionShared.proto (used by CythonFunction) */ +#define __Pyx_CyFunction_USED +#define __Pyx_CYFUNCTION_STATICMETHOD 0x01 +#define __Pyx_CYFUNCTION_CLASSMETHOD 0x02 +#define __Pyx_CYFUNCTION_CCLASS 0x04 +#define __Pyx_CYFUNCTION_COROUTINE 0x08 +#define __Pyx_CyFunction_GetClosure(f)\ + (((__pyx_CyFunctionObject *) (f))->func_closure) +#if PY_VERSION_HEX < 0x030900B1 || CYTHON_COMPILING_IN_LIMITED_API + #define __Pyx_CyFunction_GetClassObj(f)\ + (((__pyx_CyFunctionObject *) (f))->func_classobj) +#else + #define __Pyx_CyFunction_GetClassObj(f)\ + ((PyObject*) ((PyCMethodObject *) (f))->mm_class) +#endif +#define __Pyx_CyFunction_SetClassObj(f, classobj)\ + __Pyx__CyFunction_SetClassObj((__pyx_CyFunctionObject *) (f), (classobj)) +#define __Pyx_CyFunction_Defaults(type, f)\ + ((type *)(((__pyx_CyFunctionObject *) (f))->defaults)) +#define __Pyx_CyFunction_SetDefaultsGetter(f, g)\ + ((__pyx_CyFunctionObject *) (f))->defaults_getter = (g) +typedef struct { +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject_HEAD + PyObject *func; +#elif PY_VERSION_HEX < 0x030900B1 + PyCFunctionObject func; +#else + PyCMethodObject func; +#endif +#if CYTHON_COMPILING_IN_LIMITED_API && CYTHON_METH_FASTCALL + __pyx_vectorcallfunc func_vectorcall; +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *func_weakreflist; +#endif +#if PY_VERSION_HEX < 0x030C0000 || CYTHON_COMPILING_IN_LIMITED_API + PyObject *func_dict; +#endif + PyObject *func_name; + PyObject *func_qualname; + PyObject *func_doc; + PyObject *func_globals; + PyObject *func_code; + PyObject *func_closure; +#if PY_VERSION_HEX < 0x030900B1 || CYTHON_COMPILING_IN_LIMITED_API + PyObject *func_classobj; +#endif + PyObject *defaults; + int flags; + PyObject *defaults_tuple; + PyObject *defaults_kwdict; + PyObject *(*defaults_getter)(PyObject *); + PyObject *func_annotations; + PyObject *func_is_coroutine; +} __pyx_CyFunctionObject; +#undef __Pyx_CyOrPyCFunction_Check +#define __Pyx_CyFunction_Check(obj) __Pyx_TypeCheck(obj, __pyx_mstate_global->__pyx_CyFunctionType) +#define __Pyx_CyOrPyCFunction_Check(obj) __Pyx_TypeCheck2(obj, __pyx_mstate_global->__pyx_CyFunctionType, &PyCFunction_Type) +#define __Pyx_CyFunction_CheckExact(obj) __Pyx_IS_TYPE(obj, __pyx_mstate_global->__pyx_CyFunctionType) +static CYTHON_INLINE int __Pyx__IsSameCyOrCFunction(PyObject *func, void (*cfunc)(void)); +#undef __Pyx_IsSameCFunction +#define __Pyx_IsSameCFunction(func, cfunc) __Pyx__IsSameCyOrCFunction(func, cfunc) +static PyObject *__Pyx_CyFunction_Init(__pyx_CyFunctionObject* op, PyMethodDef *ml, + int flags, PyObject* qualname, + PyObject *closure, + PyObject *module, PyObject *globals, + PyObject* code); +static CYTHON_INLINE void __Pyx__CyFunction_SetClassObj(__pyx_CyFunctionObject* f, PyObject* classobj); +static CYTHON_INLINE PyObject *__Pyx_CyFunction_InitDefaults(PyObject *func, + PyTypeObject *defaults_type); +static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsTuple(PyObject *m, + PyObject *tuple); +static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsKwDict(PyObject *m, + PyObject *dict); +static CYTHON_INLINE void __Pyx_CyFunction_SetAnnotationsDict(PyObject *m, + PyObject *dict); +static int __pyx_CyFunction_init(PyObject *module); +#if CYTHON_METH_FASTCALL +static PyObject * __Pyx_CyFunction_Vectorcall_NOARGS(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames); +static PyObject * __Pyx_CyFunction_Vectorcall_O(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames); +static PyObject * __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames); +static PyObject * __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS_METHOD(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames); +#if CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_CyFunction_func_vectorcall(f) (((__pyx_CyFunctionObject*)f)->func_vectorcall) +#else +#define __Pyx_CyFunction_func_vectorcall(f) (((PyCFunctionObject*)f)->vectorcall) +#endif +#endif + +/* CythonFunction.proto */ +static PyObject *__Pyx_CyFunction_New(PyMethodDef *ml, + int flags, PyObject* qualname, + PyObject *closure, + PyObject *module, PyObject *globals, + PyObject* code); + +/* CLineInTraceback.proto (used by AddTraceback) */ +#if CYTHON_CLINE_IN_TRACEBACK && CYTHON_CLINE_IN_TRACEBACK_RUNTIME +static int __Pyx_CLineForTraceback(PyThreadState *tstate, int c_line); +#else +#define __Pyx_CLineForTraceback(tstate, c_line) (((CYTHON_CLINE_IN_TRACEBACK)) ? c_line : 0) +#endif + +/* CodeObjectCache.proto (used by AddTraceback) */ +#if CYTHON_COMPILING_IN_LIMITED_API +typedef PyObject __Pyx_CachedCodeObjectType; +#else +typedef PyCodeObject __Pyx_CachedCodeObjectType; +#endif +typedef struct { + __Pyx_CachedCodeObjectType* code_object; + int code_line; +} __Pyx_CodeObjectCacheEntry; +struct __Pyx_CodeObjectCache { + int count; + int max_count; + __Pyx_CodeObjectCacheEntry* entries; + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + __pyx_atomic_int_type accessor_count; + #endif +}; +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); +static __Pyx_CachedCodeObjectType *__pyx_find_code_object(int code_line); +static void __pyx_insert_code_object(int code_line, __Pyx_CachedCodeObjectType* code_object); + +/* AddTraceback.proto */ +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename); + +/* CheckUnpickleChecksum.proto */ +static CYTHON_INLINE int __Pyx_CheckUnpickleChecksum(long checksum, long checksum1, long checksum2, long checksum3, const char *members); + +/* GCCDiagnostics.proto */ +#if !defined(__INTEL_COMPILER) && defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) +#define __Pyx_HAS_GCC_DIAGNOSTIC +#endif + +/* CIntFromPy.proto */ +static CYTHON_INLINE long __Pyx_PyLong_As_long(PyObject *); + +/* CIntFromPy.proto */ +static CYTHON_INLINE size_t __Pyx_PyLong_As_size_t(PyObject *); + +/* CIntFromPy.proto */ +static CYTHON_INLINE int __Pyx_PyLong_As_int(PyObject *); + +/* PyObjectVectorCallKwBuilder.proto (used by CIntToPy) */ +CYTHON_UNUSED static int __Pyx_VectorcallBuilder_AddArg_Check(PyObject *key, PyObject *value, PyObject *builder, PyObject **args, int n); +#if CYTHON_VECTORCALL +#if PY_VERSION_HEX >= 0x03090000 +#define __Pyx_Object_Vectorcall_CallFromBuilder PyObject_Vectorcall +#else +#define __Pyx_Object_Vectorcall_CallFromBuilder _PyObject_Vectorcall +#endif +#define __Pyx_MakeVectorcallBuilderKwds(n) PyTuple_New(n) +static int __Pyx_VectorcallBuilder_AddArg(PyObject *key, PyObject *value, PyObject *builder, PyObject **args, int n); +static int __Pyx_VectorcallBuilder_AddArgStr(const char *key, PyObject *value, PyObject *builder, PyObject **args, int n); +#else +#define __Pyx_Object_Vectorcall_CallFromBuilder __Pyx_PyObject_FastCallDict +#define __Pyx_MakeVectorcallBuilderKwds(n) __Pyx_PyDict_NewPresized(n) +#define __Pyx_VectorcallBuilder_AddArg(key, value, builder, args, n) PyDict_SetItem(builder, key, value) +#define __Pyx_VectorcallBuilder_AddArgStr(key, value, builder, args, n) PyDict_SetItemString(builder, key, value) +#endif + +/* CIntToPy.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyLong_From_int(int value); + +/* CIntToPy.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyLong_From_long(long value); + +/* PyObjectCall2Args.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call2Args(PyObject* function, PyObject* arg1, PyObject* arg2); + +/* PyObjectCallMethod1.proto */ +static PyObject* __Pyx_PyObject_CallMethod1(PyObject* obj, PyObject* method_name, PyObject* arg); + +/* UpdateUnpickledDict.proto */ +static int __Pyx_UpdateUnpickledDict(PyObject *obj, PyObject *state, Py_ssize_t index); + +/* FormatTypeName.proto */ +#if CYTHON_COMPILING_IN_LIMITED_API +typedef PyObject *__Pyx_TypeName; +#define __Pyx_FMT_TYPENAME "%U" +#define __Pyx_DECREF_TypeName(obj) Py_XDECREF(obj) +#if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 +#define __Pyx_PyType_GetFullyQualifiedName PyType_GetFullyQualifiedName +#else +static __Pyx_TypeName __Pyx_PyType_GetFullyQualifiedName(PyTypeObject* tp); +#endif +#else // !LIMITED_API +typedef const char *__Pyx_TypeName; +#define __Pyx_FMT_TYPENAME "%.200s" +#define __Pyx_PyType_GetFullyQualifiedName(tp) ((tp)->tp_name) +#define __Pyx_DECREF_TypeName(obj) +#endif + +/* FastTypeChecks.proto */ +#if CYTHON_COMPILING_IN_CPYTHON +#define __Pyx_TypeCheck(obj, type) __Pyx_IsSubtype(Py_TYPE(obj), (PyTypeObject *)type) +#define __Pyx_TypeCheck2(obj, type1, type2) __Pyx_IsAnySubtype2(Py_TYPE(obj), (PyTypeObject *)type1, (PyTypeObject *)type2) +static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b); +static CYTHON_INLINE int __Pyx_IsAnySubtype2(PyTypeObject *cls, PyTypeObject *a, PyTypeObject *b); +static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches(PyObject *err, PyObject *type); +static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches2(PyObject *err, PyObject *type1, PyObject *type2); +#else +#define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) +#define __Pyx_TypeCheck2(obj, type1, type2) (PyObject_TypeCheck(obj, (PyTypeObject *)type1) || PyObject_TypeCheck(obj, (PyTypeObject *)type2)) +#define __Pyx_PyErr_GivenExceptionMatches(err, type) PyErr_GivenExceptionMatches(err, type) +static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches2(PyObject *err, PyObject *type1, PyObject *type2) { + return PyErr_GivenExceptionMatches(err, type1) || PyErr_GivenExceptionMatches(err, type2); +} +#endif +#define __Pyx_PyErr_ExceptionMatches2(err1, err2) __Pyx_PyErr_GivenExceptionMatches2(__Pyx_PyErr_CurrentExceptionType(), err1, err2) +#define __Pyx_PyException_Check(obj) __Pyx_TypeCheck(obj, PyExc_Exception) +#ifdef PyExceptionInstance_Check + #define __Pyx_PyBaseException_Check(obj) PyExceptionInstance_Check(obj) +#else + #define __Pyx_PyBaseException_Check(obj) __Pyx_TypeCheck(obj, PyExc_BaseException) +#endif + +/* GetRuntimeVersion.proto */ +#if __PYX_LIMITED_VERSION_HEX < 0x030b0000 +static unsigned long __Pyx_cached_runtime_version = 0; +static void __Pyx_init_runtime_version(void); +#else +#define __Pyx_init_runtime_version() +#endif +static unsigned long __Pyx_get_runtime_version(void); + +/* CheckBinaryVersion.proto */ +static int __Pyx_check_binary_version(unsigned long ct_version, unsigned long rt_version, int allow_newer); + +/* DecompressString.proto */ +static PyObject *__Pyx_DecompressString(const char *s, Py_ssize_t length, int algo); + +/* MultiPhaseInitModuleState.proto */ +#if CYTHON_PEP489_MULTI_PHASE_INIT && CYTHON_USE_MODULE_STATE +static PyObject *__Pyx_State_FindModule(void*); +static int __Pyx_State_AddModule(PyObject* module, void*); +static int __Pyx_State_RemoveModule(void*); +#elif CYTHON_USE_MODULE_STATE +#define __Pyx_State_FindModule PyState_FindModule +#define __Pyx_State_AddModule PyState_AddModule +#define __Pyx_State_RemoveModule PyState_RemoveModule +#endif + +/* #### Code section: module_declarations ### */ +/* CythonABIVersion.proto */ +#if CYTHON_COMPILING_IN_LIMITED_API + #if CYTHON_METH_FASTCALL + #define __PYX_FASTCALL_ABI_SUFFIX "_fastcall" + #else + #define __PYX_FASTCALL_ABI_SUFFIX + #endif + #define __PYX_LIMITED_ABI_SUFFIX "limited" __PYX_FASTCALL_ABI_SUFFIX __PYX_AM_SEND_ABI_SUFFIX +#else + #define __PYX_LIMITED_ABI_SUFFIX +#endif +#if __PYX_HAS_PY_AM_SEND == 1 + #define __PYX_AM_SEND_ABI_SUFFIX +#elif __PYX_HAS_PY_AM_SEND == 2 + #define __PYX_AM_SEND_ABI_SUFFIX "amsendbackport" +#else + #define __PYX_AM_SEND_ABI_SUFFIX "noamsend" +#endif +#ifndef __PYX_MONITORING_ABI_SUFFIX + #define __PYX_MONITORING_ABI_SUFFIX +#endif +#if CYTHON_USE_TP_FINALIZE + #define __PYX_TP_FINALIZE_ABI_SUFFIX +#else + #define __PYX_TP_FINALIZE_ABI_SUFFIX "nofinalize" +#endif +#if CYTHON_USE_FREELISTS || !defined(__Pyx_AsyncGen_USED) + #define __PYX_FREELISTS_ABI_SUFFIX +#else + #define __PYX_FREELISTS_ABI_SUFFIX "nofreelists" +#endif +#define CYTHON_ABI __PYX_ABI_VERSION __PYX_LIMITED_ABI_SUFFIX __PYX_MONITORING_ABI_SUFFIX __PYX_TP_FINALIZE_ABI_SUFFIX __PYX_FREELISTS_ABI_SUFFIX __PYX_AM_SEND_ABI_SUFFIX +#define __PYX_ABI_MODULE_NAME "_cython_" CYTHON_ABI +#define __PYX_TYPE_MODULE_PREFIX __PYX_ABI_MODULE_NAME "." + +static void __pyx_f_9thriftpy2_9transport_6cybase_9TCyBuffer_move_to_start(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *__pyx_v_self); /* proto*/ +static void __pyx_f_9thriftpy2_9transport_6cybase_9TCyBuffer_clean(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *__pyx_v_self); /* proto*/ +static int __pyx_f_9thriftpy2_9transport_6cybase_9TCyBuffer_write(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *__pyx_v_self, int __pyx_v_sz, char const *__pyx_v_value); /* proto*/ +static PyObject *__pyx_f_9thriftpy2_9transport_6cybase_9TCyBuffer_read_trans(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *__pyx_v_self, PyObject *__pyx_v_trans, int __pyx_v_sz, char *__pyx_v_out); /* proto*/ +static int __pyx_f_9thriftpy2_9transport_6cybase_9TCyBuffer_grow(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *__pyx_v_self, int __pyx_v_min_size); /* proto*/ +static PyObject *__pyx_f_9thriftpy2_9transport_6cybase_15CyTransportBase_c_read(CYTHON_UNUSED struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *__pyx_v_self, CYTHON_UNUSED int __pyx_v_sz, CYTHON_UNUSED char *__pyx_v_out); /* proto*/ +static PyObject *__pyx_f_9thriftpy2_9transport_6cybase_15CyTransportBase_c_write(CYTHON_UNUSED struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *__pyx_v_self, CYTHON_UNUSED char *__pyx_v_data, CYTHON_UNUSED int __pyx_v_sz); /* proto*/ +static PyObject *__pyx_f_9thriftpy2_9transport_6cybase_15CyTransportBase_c_flush(CYTHON_UNUSED struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *__pyx_v_self); /* proto*/ +static PyObject *__pyx_f_9thriftpy2_9transport_6cybase_15CyTransportBase_get_string(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *__pyx_v_self, int __pyx_v_sz); /* proto*/ + +/* Module declarations from "libc.string" */ + +/* Module declarations from "libc.stdlib" */ + +/* Module declarations from "thriftpy2.transport.cybase" */ +static PyObject *__pyx_f_9thriftpy2_9transport_6cybase___pyx_unpickle_CyTransportBase__set_state(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *, PyObject *); /*proto*/ +/* #### Code section: typeinfo ### */ +/* #### Code section: before_global_var ### */ +#define __Pyx_MODULE_NAME "thriftpy2.transport.cybase" +extern int __pyx_module_is_main_thriftpy2__transport__cybase; +int __pyx_module_is_main_thriftpy2__transport__cybase = 0; + +/* Implementation of "thriftpy2.transport.cybase" */ +/* #### Code section: global_var ### */ +/* #### Code section: string_decls ### */ +static const char __pyx_k_trans[] = "trans"; +/* #### Code section: decls ### */ +static int __pyx_pf_9thriftpy2_9transport_6cybase_9TCyBuffer___cinit__(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *__pyx_v_self, PyObject *__pyx_v_buf_size); /* proto */ +static void __pyx_pf_9thriftpy2_9transport_6cybase_9TCyBuffer_2__dealloc__(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_9transport_6cybase_9TCyBuffer_4__reduce_cython__(CYTHON_UNUSED struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_9transport_6cybase_9TCyBuffer_6__setstate_cython__(CYTHON_UNUSED struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_9transport_6cybase_15CyTransportBase_clean(CYTHON_UNUSED struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_9transport_6cybase_15CyTransportBase_4sock___get__(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_9transport_6cybase_15CyTransportBase_2__reduce_cython__(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_9transport_6cybase_15CyTransportBase_4__setstate_cython__(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *__pyx_v_self, PyObject *__pyx_v___pyx_state); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_9transport_6cybase___pyx_unpickle_CyTransportBase(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v___pyx_type, long __pyx_v___pyx_checksum, PyObject *__pyx_v___pyx_state); /* proto */ +static PyObject *__pyx_tp_new_9thriftpy2_9transport_6cybase_TCyBuffer(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_9thriftpy2_9transport_6cybase_CyTransportBase(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +/* #### Code section: late_includes ### */ +/* #### Code section: module_state ### */ +/* SmallCodeConfig */ +#ifndef CYTHON_SMALL_CODE +#if defined(__clang__) + #define CYTHON_SMALL_CODE +#elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) + #define CYTHON_SMALL_CODE __attribute__((cold)) +#else + #define CYTHON_SMALL_CODE +#endif +#endif + +typedef struct { + PyObject *__pyx_d; + PyObject *__pyx_b; + PyObject *__pyx_cython_runtime; + PyObject *__pyx_empty_tuple; + PyObject *__pyx_empty_bytes; + PyObject *__pyx_empty_unicode; + PyObject *__pyx_type_9thriftpy2_9transport_6cybase_TCyBuffer; + PyObject *__pyx_type_9thriftpy2_9transport_6cybase_CyTransportBase; + PyTypeObject *__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer; + PyTypeObject *__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase; + __Pyx_CachedCFunction __pyx_umethod_PyDict_Type_items; + __Pyx_CachedCFunction __pyx_umethod_PyDict_Type_pop; + __Pyx_CachedCFunction __pyx_umethod_PyDict_Type_values; + PyObject *__pyx_codeobj_tab[6]; + PyObject *__pyx_string_tab[61]; + PyObject *__pyx_number_tab[4]; +/* #### Code section: module_state_contents ### */ +/* CommonTypesMetaclass.module_state_decls */ +PyTypeObject *__pyx_CommonTypesMetaclassType; + +/* CachedMethodType.module_state_decls */ +#if CYTHON_COMPILING_IN_LIMITED_API +PyObject *__Pyx_CachedMethodType; +#endif + +/* CythonFunctionShared.module_state_decls */ +PyTypeObject *__pyx_CyFunctionType; + +/* CodeObjectCache.module_state_decls */ +struct __Pyx_CodeObjectCache __pyx_code_cache; + +/* #### Code section: module_state_end ### */ +} __pyx_mstatetype; + +#if CYTHON_USE_MODULE_STATE +#ifdef __cplusplus +namespace { +extern struct PyModuleDef __pyx_moduledef; +} /* anonymous namespace */ +#else +static struct PyModuleDef __pyx_moduledef; +#endif + +#define __pyx_mstate_global (__Pyx_PyModule_GetState(__Pyx_State_FindModule(&__pyx_moduledef))) + +#define __pyx_m (__Pyx_State_FindModule(&__pyx_moduledef)) +#else +static __pyx_mstatetype __pyx_mstate_global_static = +#ifdef __cplusplus + {}; +#else + {0}; +#endif +static __pyx_mstatetype * const __pyx_mstate_global = &__pyx_mstate_global_static; +#endif +/* #### Code section: constant_name_defines ### */ +#define __pyx_kp_u_ __pyx_string_tab[0] +#define __pyx_kp_u_Note_that_Cython_is_deliberately __pyx_string_tab[1] +#define __pyx_kp_u_add_note __pyx_string_tab[2] +#define __pyx_kp_u_disable __pyx_string_tab[3] +#define __pyx_kp_u_enable __pyx_string_tab[4] +#define __pyx_kp_u_gc __pyx_string_tab[5] +#define __pyx_kp_u_isenabled __pyx_string_tab[6] +#define __pyx_kp_u_no_default___reduce___due_to_non __pyx_string_tab[7] +#define __pyx_kp_u_stringsource __pyx_string_tab[8] +#define __pyx_kp_u_thriftpy2_transport_cybase_pyx __pyx_string_tab[9] +#define __pyx_n_u_CyTransportBase __pyx_string_tab[10] +#define __pyx_n_u_CyTransportBase___reduce_cython __pyx_string_tab[11] +#define __pyx_n_u_CyTransportBase___setstate_cytho __pyx_string_tab[12] +#define __pyx_n_u_CyTransportBase_clean __pyx_string_tab[13] +#define __pyx_n_u_Pyx_PyDict_NextRef __pyx_string_tab[14] +#define __pyx_n_u_TCyBuffer __pyx_string_tab[15] +#define __pyx_n_u_TCyBuffer___reduce_cython __pyx_string_tab[16] +#define __pyx_n_u_TCyBuffer___setstate_cython __pyx_string_tab[17] +#define __pyx_n_u_asyncio_coroutines __pyx_string_tab[18] +#define __pyx_n_u_buf_size __pyx_string_tab[19] +#define __pyx_n_u_clean __pyx_string_tab[20] +#define __pyx_n_u_cline_in_traceback __pyx_string_tab[21] +#define __pyx_n_u_dict __pyx_string_tab[22] +#define __pyx_n_u_dict_2 __pyx_string_tab[23] +#define __pyx_n_u_func __pyx_string_tab[24] +#define __pyx_n_u_getstate __pyx_string_tab[25] +#define __pyx_n_u_is_coroutine __pyx_string_tab[26] +#define __pyx_n_u_items __pyx_string_tab[27] +#define __pyx_n_u_main __pyx_string_tab[28] +#define __pyx_n_u_module __pyx_string_tab[29] +#define __pyx_n_u_name __pyx_string_tab[30] +#define __pyx_n_u_new __pyx_string_tab[31] +#define __pyx_n_u_pop __pyx_string_tab[32] +#define __pyx_n_u_pyx_checksum __pyx_string_tab[33] +#define __pyx_n_u_pyx_result __pyx_string_tab[34] +#define __pyx_n_u_pyx_state __pyx_string_tab[35] +#define __pyx_n_u_pyx_type __pyx_string_tab[36] +#define __pyx_n_u_pyx_unpickle_CyTransportBase __pyx_string_tab[37] +#define __pyx_n_u_pyx_vtable __pyx_string_tab[38] +#define __pyx_n_u_qualname __pyx_string_tab[39] +#define __pyx_n_u_read __pyx_string_tab[40] +#define __pyx_n_u_reduce __pyx_string_tab[41] +#define __pyx_n_u_reduce_cython __pyx_string_tab[42] +#define __pyx_n_u_reduce_ex __pyx_string_tab[43] +#define __pyx_n_u_self __pyx_string_tab[44] +#define __pyx_n_u_set_name __pyx_string_tab[45] +#define __pyx_n_u_setdefault __pyx_string_tab[46] +#define __pyx_n_u_setstate __pyx_string_tab[47] +#define __pyx_n_u_setstate_cython __pyx_string_tab[48] +#define __pyx_n_u_sock __pyx_string_tab[49] +#define __pyx_n_u_state __pyx_string_tab[50] +#define __pyx_n_u_test __pyx_string_tab[51] +#define __pyx_n_u_thriftpy2_transport_cybase __pyx_string_tab[52] +#define __pyx_n_u_update __pyx_string_tab[53] +#define __pyx_n_u_use_setstate __pyx_string_tab[54] +#define __pyx_n_u_values __pyx_string_tab[55] +#define __pyx_kp_b_iso88591_A __pyx_string_tab[56] +#define __pyx_kp_b_iso88591_Q __pyx_string_tab[57] +#define __pyx_kp_b_iso88591_QfA __pyx_string_tab[58] +#define __pyx_kp_b_iso88591_T_G1F_a_vWE_Q_q_t7_q_0_AWKwa_0 __pyx_string_tab[59] +#define __pyx_kp_b_iso88591_q_0_kQR_1_7_1_2DNRS_1 __pyx_string_tab[60] +#define __pyx_int_0 __pyx_number_tab[0] +#define __pyx_int_neg_1 __pyx_number_tab[1] +#define __pyx_int_neg_2 __pyx_number_tab[2] +#define __pyx_int_213725694 __pyx_number_tab[3] +/* #### Code section: module_state_clear ### */ +#if CYTHON_USE_MODULE_STATE +static CYTHON_SMALL_CODE int __pyx_m_clear(PyObject *m) { + __pyx_mstatetype *clear_module_state = __Pyx_PyModule_GetState(m); + if (!clear_module_state) return 0; + Py_CLEAR(clear_module_state->__pyx_d); + Py_CLEAR(clear_module_state->__pyx_b); + Py_CLEAR(clear_module_state->__pyx_cython_runtime); + Py_CLEAR(clear_module_state->__pyx_empty_tuple); + Py_CLEAR(clear_module_state->__pyx_empty_bytes); + Py_CLEAR(clear_module_state->__pyx_empty_unicode); + #if CYTHON_PEP489_MULTI_PHASE_INIT + __Pyx_State_RemoveModule(NULL); + #endif + Py_CLEAR(clear_module_state->__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer); + Py_CLEAR(clear_module_state->__pyx_type_9thriftpy2_9transport_6cybase_TCyBuffer); + Py_CLEAR(clear_module_state->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase); + Py_CLEAR(clear_module_state->__pyx_type_9thriftpy2_9transport_6cybase_CyTransportBase); + for (int i=0; i<6; ++i) { Py_CLEAR(clear_module_state->__pyx_codeobj_tab[i]); } + for (int i=0; i<61; ++i) { Py_CLEAR(clear_module_state->__pyx_string_tab[i]); } + for (int i=0; i<4; ++i) { Py_CLEAR(clear_module_state->__pyx_number_tab[i]); } +/* #### Code section: module_state_clear_contents ### */ +/* CommonTypesMetaclass.module_state_clear */ +Py_CLEAR(clear_module_state->__pyx_CommonTypesMetaclassType); + +/* CythonFunctionShared.module_state_clear */ +Py_CLEAR(clear_module_state->__pyx_CyFunctionType); + +/* #### Code section: module_state_clear_end ### */ +return 0; +} +#endif +/* #### Code section: module_state_traverse ### */ +#if CYTHON_USE_MODULE_STATE +static CYTHON_SMALL_CODE int __pyx_m_traverse(PyObject *m, visitproc visit, void *arg) { + __pyx_mstatetype *traverse_module_state = __Pyx_PyModule_GetState(m); + if (!traverse_module_state) return 0; + Py_VISIT(traverse_module_state->__pyx_d); + Py_VISIT(traverse_module_state->__pyx_b); + Py_VISIT(traverse_module_state->__pyx_cython_runtime); + __Pyx_VISIT_CONST(traverse_module_state->__pyx_empty_tuple); + __Pyx_VISIT_CONST(traverse_module_state->__pyx_empty_bytes); + __Pyx_VISIT_CONST(traverse_module_state->__pyx_empty_unicode); + Py_VISIT(traverse_module_state->__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer); + Py_VISIT(traverse_module_state->__pyx_type_9thriftpy2_9transport_6cybase_TCyBuffer); + Py_VISIT(traverse_module_state->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase); + Py_VISIT(traverse_module_state->__pyx_type_9thriftpy2_9transport_6cybase_CyTransportBase); + for (int i=0; i<6; ++i) { __Pyx_VISIT_CONST(traverse_module_state->__pyx_codeobj_tab[i]); } + for (int i=0; i<61; ++i) { __Pyx_VISIT_CONST(traverse_module_state->__pyx_string_tab[i]); } + for (int i=0; i<4; ++i) { __Pyx_VISIT_CONST(traverse_module_state->__pyx_number_tab[i]); } +/* #### Code section: module_state_traverse_contents ### */ +/* CommonTypesMetaclass.module_state_traverse */ +Py_VISIT(traverse_module_state->__pyx_CommonTypesMetaclassType); + +/* CythonFunctionShared.module_state_traverse */ +Py_VISIT(traverse_module_state->__pyx_CyFunctionType); + +/* #### Code section: module_state_traverse_end ### */ +return 0; +} +#endif +/* #### Code section: module_code ### */ + +/* "thriftpy2/transport/cybase.pyx":8 + * + * cdef class TCyBuffer(object): + * def __cinit__(self, buf_size): # <<<<<<<<<<<<<< + * self.buf = malloc(buf_size) + * self.buf_size = buf_size +*/ + +/* Python wrapper */ +static int __pyx_pw_9thriftpy2_9transport_6cybase_9TCyBuffer_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_9thriftpy2_9transport_6cybase_9TCyBuffer_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_buf_size = 0; + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return -1; + #endif + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_buf_size,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_VARARGS(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 8, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_VARARGS(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 8, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "__cinit__", 0) < (0)) __PYX_ERR(0, 8, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 1, 1, i); __PYX_ERR(0, 8, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_VARARGS(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 8, __pyx_L3_error) + } + __pyx_v_buf_size = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 8, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("thriftpy2.transport.cybase.TCyBuffer.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_9thriftpy2_9transport_6cybase_9TCyBuffer___cinit__(((struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *)__pyx_v_self), __pyx_v_buf_size); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_9thriftpy2_9transport_6cybase_9TCyBuffer___cinit__(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *__pyx_v_self, PyObject *__pyx_v_buf_size) { + int __pyx_r; + size_t __pyx_t_1; + int __pyx_t_2; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + + /* "thriftpy2/transport/cybase.pyx":9 + * cdef class TCyBuffer(object): + * def __cinit__(self, buf_size): + * self.buf = malloc(buf_size) # <<<<<<<<<<<<<< + * self.buf_size = buf_size + * self.cur = 0 +*/ + __pyx_t_1 = __Pyx_PyLong_As_size_t(__pyx_v_buf_size); if (unlikely((__pyx_t_1 == (size_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 9, __pyx_L1_error) + __pyx_v_self->buf = ((char *)malloc(__pyx_t_1)); + + /* "thriftpy2/transport/cybase.pyx":10 + * def __cinit__(self, buf_size): + * self.buf = malloc(buf_size) + * self.buf_size = buf_size # <<<<<<<<<<<<<< + * self.cur = 0 + * self.data_size = 0 +*/ + __pyx_t_2 = __Pyx_PyLong_As_int(__pyx_v_buf_size); if (unlikely((__pyx_t_2 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 10, __pyx_L1_error) + __pyx_v_self->buf_size = __pyx_t_2; + + /* "thriftpy2/transport/cybase.pyx":11 + * self.buf = malloc(buf_size) + * self.buf_size = buf_size + * self.cur = 0 # <<<<<<<<<<<<<< + * self.data_size = 0 + * +*/ + __pyx_v_self->cur = 0; + + /* "thriftpy2/transport/cybase.pyx":12 + * self.buf_size = buf_size + * self.cur = 0 + * self.data_size = 0 # <<<<<<<<<<<<<< + * + * def __dealloc__(self): +*/ + __pyx_v_self->data_size = 0; + + /* "thriftpy2/transport/cybase.pyx":8 + * + * cdef class TCyBuffer(object): + * def __cinit__(self, buf_size): # <<<<<<<<<<<<<< + * self.buf = malloc(buf_size) + * self.buf_size = buf_size +*/ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_AddTraceback("thriftpy2.transport.cybase.TCyBuffer.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + return __pyx_r; +} + +/* "thriftpy2/transport/cybase.pyx":14 + * self.data_size = 0 + * + * def __dealloc__(self): # <<<<<<<<<<<<<< + * if self.buf != NULL: + * free(self.buf) +*/ + +/* Python wrapper */ +static void __pyx_pw_9thriftpy2_9transport_6cybase_9TCyBuffer_3__dealloc__(PyObject *__pyx_v_self); /*proto*/ +static void __pyx_pw_9thriftpy2_9transport_6cybase_9TCyBuffer_3__dealloc__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_pf_9thriftpy2_9transport_6cybase_9TCyBuffer_2__dealloc__(((struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +static void __pyx_pf_9thriftpy2_9transport_6cybase_9TCyBuffer_2__dealloc__(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *__pyx_v_self) { + int __pyx_t_1; + + /* "thriftpy2/transport/cybase.pyx":15 + * + * def __dealloc__(self): + * if self.buf != NULL: # <<<<<<<<<<<<<< + * free(self.buf) + * self.buf = NULL +*/ + __pyx_t_1 = (__pyx_v_self->buf != NULL); + if (__pyx_t_1) { + + /* "thriftpy2/transport/cybase.pyx":16 + * def __dealloc__(self): + * if self.buf != NULL: + * free(self.buf) # <<<<<<<<<<<<<< + * self.buf = NULL + * +*/ + free(__pyx_v_self->buf); + + /* "thriftpy2/transport/cybase.pyx":17 + * if self.buf != NULL: + * free(self.buf) + * self.buf = NULL # <<<<<<<<<<<<<< + * + * cdef void move_to_start(self): +*/ + __pyx_v_self->buf = NULL; + + /* "thriftpy2/transport/cybase.pyx":15 + * + * def __dealloc__(self): + * if self.buf != NULL: # <<<<<<<<<<<<<< + * free(self.buf) + * self.buf = NULL +*/ + } + + /* "thriftpy2/transport/cybase.pyx":14 + * self.data_size = 0 + * + * def __dealloc__(self): # <<<<<<<<<<<<<< + * if self.buf != NULL: + * free(self.buf) +*/ + + /* function exit code */ +} + +/* "thriftpy2/transport/cybase.pyx":19 + * self.buf = NULL + * + * cdef void move_to_start(self): # <<<<<<<<<<<<<< + * memmove(self.buf, self.buf + self.cur, self.data_size) + * self.cur = 0 +*/ + +static void __pyx_f_9thriftpy2_9transport_6cybase_9TCyBuffer_move_to_start(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *__pyx_v_self) { + + /* "thriftpy2/transport/cybase.pyx":20 + * + * cdef void move_to_start(self): + * memmove(self.buf, self.buf + self.cur, self.data_size) # <<<<<<<<<<<<<< + * self.cur = 0 + * +*/ + (void)(memmove(__pyx_v_self->buf, (__pyx_v_self->buf + __pyx_v_self->cur), __pyx_v_self->data_size)); + + /* "thriftpy2/transport/cybase.pyx":21 + * cdef void move_to_start(self): + * memmove(self.buf, self.buf + self.cur, self.data_size) + * self.cur = 0 # <<<<<<<<<<<<<< + * + * cdef void clean(self): +*/ + __pyx_v_self->cur = 0; + + /* "thriftpy2/transport/cybase.pyx":19 + * self.buf = NULL + * + * cdef void move_to_start(self): # <<<<<<<<<<<<<< + * memmove(self.buf, self.buf + self.cur, self.data_size) + * self.cur = 0 +*/ + + /* function exit code */ +} + +/* "thriftpy2/transport/cybase.pyx":23 + * self.cur = 0 + * + * cdef void clean(self): # <<<<<<<<<<<<<< + * self.cur = 0 + * self.data_size = 0 +*/ + +static void __pyx_f_9thriftpy2_9transport_6cybase_9TCyBuffer_clean(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *__pyx_v_self) { + + /* "thriftpy2/transport/cybase.pyx":24 + * + * cdef void clean(self): + * self.cur = 0 # <<<<<<<<<<<<<< + * self.data_size = 0 + * +*/ + __pyx_v_self->cur = 0; + + /* "thriftpy2/transport/cybase.pyx":25 + * cdef void clean(self): + * self.cur = 0 + * self.data_size = 0 # <<<<<<<<<<<<<< + * + * cdef int write(self, int sz, const char *value): +*/ + __pyx_v_self->data_size = 0; + + /* "thriftpy2/transport/cybase.pyx":23 + * self.cur = 0 + * + * cdef void clean(self): # <<<<<<<<<<<<<< + * self.cur = 0 + * self.data_size = 0 +*/ + + /* function exit code */ +} + +/* "thriftpy2/transport/cybase.pyx":27 + * self.data_size = 0 + * + * cdef int write(self, int sz, const char *value): # <<<<<<<<<<<<<< + * cdef: + * int cap = self.buf_size - self.data_size +*/ + +static int __pyx_f_9thriftpy2_9transport_6cybase_9TCyBuffer_write(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *__pyx_v_self, int __pyx_v_sz, char const *__pyx_v_value) { + int __pyx_v_cap; + int __pyx_v_remain; + int __pyx_r; + int __pyx_t_1; + int __pyx_t_2; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + + /* "thriftpy2/transport/cybase.pyx":29 + * cdef int write(self, int sz, const char *value): + * cdef: + * int cap = self.buf_size - self.data_size # <<<<<<<<<<<<<< + * int remain = cap - self.cur + * +*/ + __pyx_v_cap = (__pyx_v_self->buf_size - __pyx_v_self->data_size); + + /* "thriftpy2/transport/cybase.pyx":30 + * cdef: + * int cap = self.buf_size - self.data_size + * int remain = cap - self.cur # <<<<<<<<<<<<<< + * + * if sz <= 0: +*/ + __pyx_v_remain = (__pyx_v_cap - __pyx_v_self->cur); + + /* "thriftpy2/transport/cybase.pyx":32 + * int remain = cap - self.cur + * + * if sz <= 0: # <<<<<<<<<<<<<< + * return 0 + * +*/ + __pyx_t_1 = (__pyx_v_sz <= 0); + if (__pyx_t_1) { + + /* "thriftpy2/transport/cybase.pyx":33 + * + * if sz <= 0: + * return 0 # <<<<<<<<<<<<<< + * + * if remain < sz: +*/ + __pyx_r = 0; + goto __pyx_L0; + + /* "thriftpy2/transport/cybase.pyx":32 + * int remain = cap - self.cur + * + * if sz <= 0: # <<<<<<<<<<<<<< + * return 0 + * +*/ + } + + /* "thriftpy2/transport/cybase.pyx":35 + * return 0 + * + * if remain < sz: # <<<<<<<<<<<<<< + * self.move_to_start() + * +*/ + __pyx_t_1 = (__pyx_v_remain < __pyx_v_sz); + if (__pyx_t_1) { + + /* "thriftpy2/transport/cybase.pyx":36 + * + * if remain < sz: + * self.move_to_start() # <<<<<<<<<<<<<< + * + * # recompute remain spaces +*/ + ((struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_TCyBuffer *)__pyx_v_self->__pyx_vtab)->move_to_start(__pyx_v_self); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 36, __pyx_L1_error) + + /* "thriftpy2/transport/cybase.pyx":35 + * return 0 + * + * if remain < sz: # <<<<<<<<<<<<<< + * self.move_to_start() + * +*/ + } + + /* "thriftpy2/transport/cybase.pyx":39 + * + * # recompute remain spaces + * remain = cap - self.cur # <<<<<<<<<<<<<< + * + * if remain < sz: +*/ + __pyx_v_remain = (__pyx_v_cap - __pyx_v_self->cur); + + /* "thriftpy2/transport/cybase.pyx":41 + * remain = cap - self.cur + * + * if remain < sz: # <<<<<<<<<<<<<< + * if self.grow(sz - remain + self.buf_size) != 0: + * return -1 +*/ + __pyx_t_1 = (__pyx_v_remain < __pyx_v_sz); + if (__pyx_t_1) { + + /* "thriftpy2/transport/cybase.pyx":42 + * + * if remain < sz: + * if self.grow(sz - remain + self.buf_size) != 0: # <<<<<<<<<<<<<< + * return -1 + * +*/ + __pyx_t_2 = ((struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_TCyBuffer *)__pyx_v_self->__pyx_vtab)->grow(__pyx_v_self, ((__pyx_v_sz - __pyx_v_remain) + __pyx_v_self->buf_size)); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 42, __pyx_L1_error) + __pyx_t_1 = (__pyx_t_2 != 0); + if (__pyx_t_1) { + + /* "thriftpy2/transport/cybase.pyx":43 + * if remain < sz: + * if self.grow(sz - remain + self.buf_size) != 0: + * return -1 # <<<<<<<<<<<<<< + * + * memcpy(self.buf + self.cur + self.data_size, value, sz) +*/ + __pyx_r = -1; + goto __pyx_L0; + + /* "thriftpy2/transport/cybase.pyx":42 + * + * if remain < sz: + * if self.grow(sz - remain + self.buf_size) != 0: # <<<<<<<<<<<<<< + * return -1 + * +*/ + } + + /* "thriftpy2/transport/cybase.pyx":41 + * remain = cap - self.cur + * + * if remain < sz: # <<<<<<<<<<<<<< + * if self.grow(sz - remain + self.buf_size) != 0: + * return -1 +*/ + } + + /* "thriftpy2/transport/cybase.pyx":45 + * return -1 + * + * memcpy(self.buf + self.cur + self.data_size, value, sz) # <<<<<<<<<<<<<< + * self.data_size += sz + * +*/ + (void)(memcpy(((__pyx_v_self->buf + __pyx_v_self->cur) + __pyx_v_self->data_size), __pyx_v_value, __pyx_v_sz)); + + /* "thriftpy2/transport/cybase.pyx":46 + * + * memcpy(self.buf + self.cur + self.data_size, value, sz) + * self.data_size += sz # <<<<<<<<<<<<<< + * + * return sz +*/ + __pyx_v_self->data_size = (__pyx_v_self->data_size + __pyx_v_sz); + + /* "thriftpy2/transport/cybase.pyx":48 + * self.data_size += sz + * + * return sz # <<<<<<<<<<<<<< + * + * cdef read_trans(self, trans, int sz, char *out): +*/ + __pyx_r = __pyx_v_sz; + goto __pyx_L0; + + /* "thriftpy2/transport/cybase.pyx":27 + * self.data_size = 0 + * + * cdef int write(self, int sz, const char *value): # <<<<<<<<<<<<<< + * cdef: + * int cap = self.buf_size - self.data_size +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_AddTraceback("thriftpy2.transport.cybase.TCyBuffer.write", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + return __pyx_r; +} + +/* "thriftpy2/transport/cybase.pyx":50 + * return sz + * + * cdef read_trans(self, trans, int sz, char *out): # <<<<<<<<<<<<<< + * cdef int cap, new_data_len + * +*/ + +static PyObject *__pyx_f_9thriftpy2_9transport_6cybase_9TCyBuffer_read_trans(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *__pyx_v_self, PyObject *__pyx_v_trans, int __pyx_v_sz, char *__pyx_v_out) { + int __pyx_v_cap; + int __pyx_v_new_data_len; + PyObject *__pyx_v_new_data = NULL; + PyObject *__pyx_v_more = NULL; + PyObject *__pyx_v_more_len = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + size_t __pyx_t_6; + Py_ssize_t __pyx_t_7; + char *__pyx_t_8; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("read_trans", 0); + + /* "thriftpy2/transport/cybase.pyx":53 + * cdef int cap, new_data_len + * + * if sz <= 0: # <<<<<<<<<<<<<< + * return 0 + * +*/ + __pyx_t_1 = (__pyx_v_sz <= 0); + if (__pyx_t_1) { + + /* "thriftpy2/transport/cybase.pyx":54 + * + * if sz <= 0: + * return 0 # <<<<<<<<<<<<<< + * + * if self.data_size < sz: +*/ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_mstate_global->__pyx_int_0); + __pyx_r = __pyx_mstate_global->__pyx_int_0; + goto __pyx_L0; + + /* "thriftpy2/transport/cybase.pyx":53 + * cdef int cap, new_data_len + * + * if sz <= 0: # <<<<<<<<<<<<<< + * return 0 + * +*/ + } + + /* "thriftpy2/transport/cybase.pyx":56 + * return 0 + * + * if self.data_size < sz: # <<<<<<<<<<<<<< + * if self.buf_size < sz: + * if self.grow(sz) != 0: +*/ + __pyx_t_1 = (__pyx_v_self->data_size < __pyx_v_sz); + if (__pyx_t_1) { + + /* "thriftpy2/transport/cybase.pyx":57 + * + * if self.data_size < sz: + * if self.buf_size < sz: # <<<<<<<<<<<<<< + * if self.grow(sz) != 0: + * return -2 # grow buffer error +*/ + __pyx_t_1 = (__pyx_v_self->buf_size < __pyx_v_sz); + if (__pyx_t_1) { + + /* "thriftpy2/transport/cybase.pyx":58 + * if self.data_size < sz: + * if self.buf_size < sz: + * if self.grow(sz) != 0: # <<<<<<<<<<<<<< + * return -2 # grow buffer error + * +*/ + __pyx_t_2 = ((struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_TCyBuffer *)__pyx_v_self->__pyx_vtab)->grow(__pyx_v_self, __pyx_v_sz); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 58, __pyx_L1_error) + __pyx_t_1 = (__pyx_t_2 != 0); + if (__pyx_t_1) { + + /* "thriftpy2/transport/cybase.pyx":59 + * if self.buf_size < sz: + * if self.grow(sz) != 0: + * return -2 # grow buffer error # <<<<<<<<<<<<<< + * + * cap = self.buf_size - self.data_size +*/ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_mstate_global->__pyx_int_neg_2); + __pyx_r = __pyx_mstate_global->__pyx_int_neg_2; + goto __pyx_L0; + + /* "thriftpy2/transport/cybase.pyx":58 + * if self.data_size < sz: + * if self.buf_size < sz: + * if self.grow(sz) != 0: # <<<<<<<<<<<<<< + * return -2 # grow buffer error + * +*/ + } + + /* "thriftpy2/transport/cybase.pyx":57 + * + * if self.data_size < sz: + * if self.buf_size < sz: # <<<<<<<<<<<<<< + * if self.grow(sz) != 0: + * return -2 # grow buffer error +*/ + } + + /* "thriftpy2/transport/cybase.pyx":61 + * return -2 # grow buffer error + * + * cap = self.buf_size - self.data_size # <<<<<<<<<<<<<< + * + * new_data = trans.read(cap) +*/ + __pyx_v_cap = (__pyx_v_self->buf_size - __pyx_v_self->data_size); + + /* "thriftpy2/transport/cybase.pyx":63 + * cap = self.buf_size - self.data_size + * + * new_data = trans.read(cap) # <<<<<<<<<<<<<< + * new_data_len = len(new_data) + * +*/ + __pyx_t_4 = __pyx_v_trans; + __Pyx_INCREF(__pyx_t_4); + __pyx_t_5 = __Pyx_PyLong_From_int(__pyx_v_cap); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 63, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_4, __pyx_t_5}; + __pyx_t_3 = __Pyx_PyObject_FastCallMethod((PyObject*)__pyx_mstate_global->__pyx_n_u_read, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 63, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + } + __pyx_v_new_data = __pyx_t_3; + __pyx_t_3 = 0; + + /* "thriftpy2/transport/cybase.pyx":64 + * + * new_data = trans.read(cap) + * new_data_len = len(new_data) # <<<<<<<<<<<<<< + * + * while new_data_len + self.data_size < sz: +*/ + __pyx_t_7 = PyObject_Length(__pyx_v_new_data); if (unlikely(__pyx_t_7 == ((Py_ssize_t)-1))) __PYX_ERR(0, 64, __pyx_L1_error) + __pyx_v_new_data_len = __pyx_t_7; + + /* "thriftpy2/transport/cybase.pyx":66 + * new_data_len = len(new_data) + * + * while new_data_len + self.data_size < sz: # <<<<<<<<<<<<<< + * more = trans.read(cap - new_data_len) + * more_len = len(more) +*/ + while (1) { + __pyx_t_1 = ((__pyx_v_new_data_len + __pyx_v_self->data_size) < __pyx_v_sz); + if (!__pyx_t_1) break; + + /* "thriftpy2/transport/cybase.pyx":67 + * + * while new_data_len + self.data_size < sz: + * more = trans.read(cap - new_data_len) # <<<<<<<<<<<<<< + * more_len = len(more) + * if more_len <= 0: +*/ + __pyx_t_5 = __pyx_v_trans; + __Pyx_INCREF(__pyx_t_5); + __pyx_t_4 = __Pyx_PyLong_From_int((__pyx_v_cap - __pyx_v_new_data_len)); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 67, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_6 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_5, __pyx_t_4}; + __pyx_t_3 = __Pyx_PyObject_FastCallMethod((PyObject*)__pyx_mstate_global->__pyx_n_u_read, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 67, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + } + __Pyx_XDECREF_SET(__pyx_v_more, __pyx_t_3); + __pyx_t_3 = 0; + + /* "thriftpy2/transport/cybase.pyx":68 + * while new_data_len + self.data_size < sz: + * more = trans.read(cap - new_data_len) + * more_len = len(more) # <<<<<<<<<<<<<< + * if more_len <= 0: + * return -1 # end of file error +*/ + __pyx_t_7 = PyObject_Length(__pyx_v_more); if (unlikely(__pyx_t_7 == ((Py_ssize_t)-1))) __PYX_ERR(0, 68, __pyx_L1_error) + __pyx_t_3 = PyLong_FromSsize_t(__pyx_t_7); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 68, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_XDECREF_SET(__pyx_v_more_len, __pyx_t_3); + __pyx_t_3 = 0; + + /* "thriftpy2/transport/cybase.pyx":69 + * more = trans.read(cap - new_data_len) + * more_len = len(more) + * if more_len <= 0: # <<<<<<<<<<<<<< + * return -1 # end of file error + * +*/ + __pyx_t_3 = PyObject_RichCompare(__pyx_v_more_len, __pyx_mstate_global->__pyx_int_0, Py_LE); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 69, __pyx_L1_error) + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely((__pyx_t_1 < 0))) __PYX_ERR(0, 69, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_1) { + + /* "thriftpy2/transport/cybase.pyx":70 + * more_len = len(more) + * if more_len <= 0: + * return -1 # end of file error # <<<<<<<<<<<<<< + * + * new_data += more +*/ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_mstate_global->__pyx_int_neg_1); + __pyx_r = __pyx_mstate_global->__pyx_int_neg_1; + goto __pyx_L0; + + /* "thriftpy2/transport/cybase.pyx":69 + * more = trans.read(cap - new_data_len) + * more_len = len(more) + * if more_len <= 0: # <<<<<<<<<<<<<< + * return -1 # end of file error + * +*/ + } + + /* "thriftpy2/transport/cybase.pyx":72 + * return -1 # end of file error + * + * new_data += more # <<<<<<<<<<<<<< + * new_data_len += more_len + * +*/ + __pyx_t_3 = PyNumber_InPlaceAdd(__pyx_v_new_data, __pyx_v_more); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 72, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF_SET(__pyx_v_new_data, __pyx_t_3); + __pyx_t_3 = 0; + + /* "thriftpy2/transport/cybase.pyx":73 + * + * new_data += more + * new_data_len += more_len # <<<<<<<<<<<<<< + * + * if cap - self.cur < new_data_len: +*/ + __pyx_t_3 = __Pyx_PyLong_From_int(__pyx_v_new_data_len); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 73, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyNumber_InPlaceAdd(__pyx_t_3, __pyx_v_more_len); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 73, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_2 = __Pyx_PyLong_As_int(__pyx_t_4); if (unlikely((__pyx_t_2 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 73, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_v_new_data_len = __pyx_t_2; + } + + /* "thriftpy2/transport/cybase.pyx":75 + * new_data_len += more_len + * + * if cap - self.cur < new_data_len: # <<<<<<<<<<<<<< + * self.move_to_start() + * +*/ + __pyx_t_1 = ((__pyx_v_cap - __pyx_v_self->cur) < __pyx_v_new_data_len); + if (__pyx_t_1) { + + /* "thriftpy2/transport/cybase.pyx":76 + * + * if cap - self.cur < new_data_len: + * self.move_to_start() # <<<<<<<<<<<<<< + * + * memcpy(self.buf + self.cur + self.data_size, new_data, +*/ + ((struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_TCyBuffer *)__pyx_v_self->__pyx_vtab)->move_to_start(__pyx_v_self); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 76, __pyx_L1_error) + + /* "thriftpy2/transport/cybase.pyx":75 + * new_data_len += more_len + * + * if cap - self.cur < new_data_len: # <<<<<<<<<<<<<< + * self.move_to_start() + * +*/ + } + + /* "thriftpy2/transport/cybase.pyx":78 + * self.move_to_start() + * + * memcpy(self.buf + self.cur + self.data_size, new_data, # <<<<<<<<<<<<<< + * new_data_len) + * self.data_size += new_data_len +*/ + __pyx_t_8 = __Pyx_PyObject_AsWritableString(__pyx_v_new_data); if (unlikely((!__pyx_t_8) && PyErr_Occurred())) __PYX_ERR(0, 78, __pyx_L1_error) + + /* "thriftpy2/transport/cybase.pyx":79 + * + * memcpy(self.buf + self.cur + self.data_size, new_data, + * new_data_len) # <<<<<<<<<<<<<< + * self.data_size += new_data_len + * +*/ + (void)(memcpy(((__pyx_v_self->buf + __pyx_v_self->cur) + __pyx_v_self->data_size), ((char *)__pyx_t_8), __pyx_v_new_data_len)); + + /* "thriftpy2/transport/cybase.pyx":80 + * memcpy(self.buf + self.cur + self.data_size, new_data, + * new_data_len) + * self.data_size += new_data_len # <<<<<<<<<<<<<< + * + * memcpy(out, self.buf + self.cur, sz) +*/ + __pyx_v_self->data_size = (__pyx_v_self->data_size + __pyx_v_new_data_len); + + /* "thriftpy2/transport/cybase.pyx":56 + * return 0 + * + * if self.data_size < sz: # <<<<<<<<<<<<<< + * if self.buf_size < sz: + * if self.grow(sz) != 0: +*/ + } + + /* "thriftpy2/transport/cybase.pyx":82 + * self.data_size += new_data_len + * + * memcpy(out, self.buf + self.cur, sz) # <<<<<<<<<<<<<< + * self.cur += sz + * self.data_size -= sz +*/ + (void)(memcpy(__pyx_v_out, (__pyx_v_self->buf + __pyx_v_self->cur), __pyx_v_sz)); + + /* "thriftpy2/transport/cybase.pyx":83 + * + * memcpy(out, self.buf + self.cur, sz) + * self.cur += sz # <<<<<<<<<<<<<< + * self.data_size -= sz + * +*/ + __pyx_v_self->cur = (__pyx_v_self->cur + __pyx_v_sz); + + /* "thriftpy2/transport/cybase.pyx":84 + * memcpy(out, self.buf + self.cur, sz) + * self.cur += sz + * self.data_size -= sz # <<<<<<<<<<<<<< + * + * return sz +*/ + __pyx_v_self->data_size = (__pyx_v_self->data_size - __pyx_v_sz); + + /* "thriftpy2/transport/cybase.pyx":86 + * self.data_size -= sz + * + * return sz # <<<<<<<<<<<<<< + * + * cdef int grow(self, int min_size): +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_4 = __Pyx_PyLong_From_int(__pyx_v_sz); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 86, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_r = __pyx_t_4; + __pyx_t_4 = 0; + goto __pyx_L0; + + /* "thriftpy2/transport/cybase.pyx":50 + * return sz + * + * cdef read_trans(self, trans, int sz, char *out): # <<<<<<<<<<<<<< + * cdef int cap, new_data_len + * +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("thriftpy2.transport.cybase.TCyBuffer.read_trans", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_new_data); + __Pyx_XDECREF(__pyx_v_more); + __Pyx_XDECREF(__pyx_v_more_len); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/cybase.pyx":88 + * return sz + * + * cdef int grow(self, int min_size): # <<<<<<<<<<<<<< + * if min_size <= self.buf_size: + * return 0 +*/ + +static int __pyx_f_9thriftpy2_9transport_6cybase_9TCyBuffer_grow(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *__pyx_v_self, int __pyx_v_min_size) { + int __pyx_v_multiples; + int __pyx_v_new_size; + char *__pyx_v_new_buf; + int __pyx_r; + int __pyx_t_1; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + + /* "thriftpy2/transport/cybase.pyx":89 + * + * cdef int grow(self, int min_size): + * if min_size <= self.buf_size: # <<<<<<<<<<<<<< + * return 0 + * +*/ + __pyx_t_1 = (__pyx_v_min_size <= __pyx_v_self->buf_size); + if (__pyx_t_1) { + + /* "thriftpy2/transport/cybase.pyx":90 + * cdef int grow(self, int min_size): + * if min_size <= self.buf_size: + * return 0 # <<<<<<<<<<<<<< + * + * cdef int multiples = min_size // self.buf_size +*/ + __pyx_r = 0; + goto __pyx_L0; + + /* "thriftpy2/transport/cybase.pyx":89 + * + * cdef int grow(self, int min_size): + * if min_size <= self.buf_size: # <<<<<<<<<<<<<< + * return 0 + * +*/ + } + + /* "thriftpy2/transport/cybase.pyx":92 + * return 0 + * + * cdef int multiples = min_size // self.buf_size # <<<<<<<<<<<<<< + * if min_size % self.buf_size != 0: + * multiples += 1 +*/ + if (unlikely(__pyx_v_self->buf_size == 0)) { + PyErr_SetString(PyExc_ZeroDivisionError, "integer division or modulo by zero"); + __PYX_ERR(0, 92, __pyx_L1_error) + } + else if (sizeof(int) == sizeof(long) && (!(((int)-1) > 0)) && unlikely(__pyx_v_self->buf_size == (int)-1) && unlikely(__Pyx_UNARY_NEG_WOULD_OVERFLOW(__pyx_v_min_size))) { + PyErr_SetString(PyExc_OverflowError, "value too large to perform division"); + __PYX_ERR(0, 92, __pyx_L1_error) + } + __pyx_v_multiples = __Pyx_div_int(__pyx_v_min_size, __pyx_v_self->buf_size, 0); + + /* "thriftpy2/transport/cybase.pyx":93 + * + * cdef int multiples = min_size // self.buf_size + * if min_size % self.buf_size != 0: # <<<<<<<<<<<<<< + * multiples += 1 + * +*/ + if (unlikely(__pyx_v_self->buf_size == 0)) { + PyErr_SetString(PyExc_ZeroDivisionError, "integer division or modulo by zero"); + __PYX_ERR(0, 93, __pyx_L1_error) + } + __pyx_t_1 = (__Pyx_mod_int(__pyx_v_min_size, __pyx_v_self->buf_size, 0) != 0); + if (__pyx_t_1) { + + /* "thriftpy2/transport/cybase.pyx":94 + * cdef int multiples = min_size // self.buf_size + * if min_size % self.buf_size != 0: + * multiples += 1 # <<<<<<<<<<<<<< + * + * cdef int new_size = self.buf_size * multiples +*/ + __pyx_v_multiples = (__pyx_v_multiples + 1); + + /* "thriftpy2/transport/cybase.pyx":93 + * + * cdef int multiples = min_size // self.buf_size + * if min_size % self.buf_size != 0: # <<<<<<<<<<<<<< + * multiples += 1 + * +*/ + } + + /* "thriftpy2/transport/cybase.pyx":96 + * multiples += 1 + * + * cdef int new_size = self.buf_size * multiples # <<<<<<<<<<<<<< + * cdef char *new_buf = malloc(new_size) + * if new_buf == NULL: +*/ + __pyx_v_new_size = (__pyx_v_self->buf_size * __pyx_v_multiples); + + /* "thriftpy2/transport/cybase.pyx":97 + * + * cdef int new_size = self.buf_size * multiples + * cdef char *new_buf = malloc(new_size) # <<<<<<<<<<<<<< + * if new_buf == NULL: + * return -1 +*/ + __pyx_v_new_buf = ((char *)malloc(__pyx_v_new_size)); + + /* "thriftpy2/transport/cybase.pyx":98 + * cdef int new_size = self.buf_size * multiples + * cdef char *new_buf = malloc(new_size) + * if new_buf == NULL: # <<<<<<<<<<<<<< + * return -1 + * memcpy(new_buf + self.cur, self.buf + self.cur, self.data_size) +*/ + __pyx_t_1 = (__pyx_v_new_buf == NULL); + if (__pyx_t_1) { + + /* "thriftpy2/transport/cybase.pyx":99 + * cdef char *new_buf = malloc(new_size) + * if new_buf == NULL: + * return -1 # <<<<<<<<<<<<<< + * memcpy(new_buf + self.cur, self.buf + self.cur, self.data_size) + * free(self.buf) +*/ + __pyx_r = -1; + goto __pyx_L0; + + /* "thriftpy2/transport/cybase.pyx":98 + * cdef int new_size = self.buf_size * multiples + * cdef char *new_buf = malloc(new_size) + * if new_buf == NULL: # <<<<<<<<<<<<<< + * return -1 + * memcpy(new_buf + self.cur, self.buf + self.cur, self.data_size) +*/ + } + + /* "thriftpy2/transport/cybase.pyx":100 + * if new_buf == NULL: + * return -1 + * memcpy(new_buf + self.cur, self.buf + self.cur, self.data_size) # <<<<<<<<<<<<<< + * free(self.buf) + * self.buf_size = new_size +*/ + (void)(memcpy((__pyx_v_new_buf + __pyx_v_self->cur), (__pyx_v_self->buf + __pyx_v_self->cur), __pyx_v_self->data_size)); + + /* "thriftpy2/transport/cybase.pyx":101 + * return -1 + * memcpy(new_buf + self.cur, self.buf + self.cur, self.data_size) + * free(self.buf) # <<<<<<<<<<<<<< + * self.buf_size = new_size + * self.buf = new_buf +*/ + free(__pyx_v_self->buf); + + /* "thriftpy2/transport/cybase.pyx":102 + * memcpy(new_buf + self.cur, self.buf + self.cur, self.data_size) + * free(self.buf) + * self.buf_size = new_size # <<<<<<<<<<<<<< + * self.buf = new_buf + * return 0 +*/ + __pyx_v_self->buf_size = __pyx_v_new_size; + + /* "thriftpy2/transport/cybase.pyx":103 + * free(self.buf) + * self.buf_size = new_size + * self.buf = new_buf # <<<<<<<<<<<<<< + * return 0 + * +*/ + __pyx_v_self->buf = __pyx_v_new_buf; + + /* "thriftpy2/transport/cybase.pyx":104 + * self.buf_size = new_size + * self.buf = new_buf + * return 0 # <<<<<<<<<<<<<< + * + * +*/ + __pyx_r = 0; + goto __pyx_L0; + + /* "thriftpy2/transport/cybase.pyx":88 + * return sz + * + * cdef int grow(self, int min_size): # <<<<<<<<<<<<<< + * if min_size <= self.buf_size: + * return 0 +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_AddTraceback("thriftpy2.transport.cybase.TCyBuffer.grow", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + return __pyx_r; +} + +/* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" + * def __setstate_cython__(self, __pyx_state): +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_9transport_6cybase_9TCyBuffer_5__reduce_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_9transport_6cybase_9TCyBuffer_5__reduce_cython__ = {"__reduce_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_6cybase_9TCyBuffer_5__reduce_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_9transport_6cybase_9TCyBuffer_5__reduce_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("__reduce_cython__", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("__reduce_cython__", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_9thriftpy2_9transport_6cybase_9TCyBuffer_4__reduce_cython__(((struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_9transport_6cybase_9TCyBuffer_4__reduce_cython__(CYTHON_UNUSED struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__reduce_cython__", 0); + + /* "(tree fragment)":2 + * def __reduce_cython__(self): + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" # <<<<<<<<<<<<<< + * def __setstate_cython__(self, __pyx_state): + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" +*/ + __Pyx_Raise(((PyObject *)(((PyTypeObject*)PyExc_TypeError))), __pyx_mstate_global->__pyx_kp_u_no_default___reduce___due_to_non, 0, 0); + __PYX_ERR(1, 2, __pyx_L1_error) + + /* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" + * def __setstate_cython__(self, __pyx_state): +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_AddTraceback("thriftpy2.transport.cybase.TCyBuffer.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":3 + * def __reduce_cython__(self): + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_9transport_6cybase_9TCyBuffer_7__setstate_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_9transport_6cybase_9TCyBuffer_7__setstate_cython__ = {"__setstate_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_6cybase_9TCyBuffer_7__setstate_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_9transport_6cybase_9TCyBuffer_7__setstate_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + CYTHON_UNUSED PyObject *__pyx_v___pyx_state = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_pyx_state,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(1, 3, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(1, 3, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "__setstate_cython__", 0) < (0)) __PYX_ERR(1, 3, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("__setstate_cython__", 1, 1, 1, i); __PYX_ERR(1, 3, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(1, 3, __pyx_L3_error) + } + __pyx_v___pyx_state = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__setstate_cython__", 1, 1, 1, __pyx_nargs); __PYX_ERR(1, 3, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("thriftpy2.transport.cybase.TCyBuffer.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_9thriftpy2_9transport_6cybase_9TCyBuffer_6__setstate_cython__(((struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *)__pyx_v_self), __pyx_v___pyx_state); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_9transport_6cybase_9TCyBuffer_6__setstate_cython__(CYTHON_UNUSED struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__setstate_cython__", 0); + + /* "(tree fragment)":4 + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" + * def __setstate_cython__(self, __pyx_state): + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" # <<<<<<<<<<<<<< +*/ + __Pyx_Raise(((PyObject *)(((PyTypeObject*)PyExc_TypeError))), __pyx_mstate_global->__pyx_kp_u_no_default___reduce___due_to_non, 0, 0); + __PYX_ERR(1, 4, __pyx_L1_error) + + /* "(tree fragment)":3 + * def __reduce_cython__(self): + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_AddTraceback("thriftpy2.transport.cybase.TCyBuffer.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/cybase.pyx":108 + * + * cdef class CyTransportBase(object): + * cdef c_read(self, int sz, char* out): # <<<<<<<<<<<<<< + * pass + * +*/ + +static PyObject *__pyx_f_9thriftpy2_9transport_6cybase_15CyTransportBase_c_read(CYTHON_UNUSED struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *__pyx_v_self, CYTHON_UNUSED int __pyx_v_sz, CYTHON_UNUSED char *__pyx_v_out) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("c_read", 0); + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/cybase.pyx":111 + * pass + * + * cdef c_write(self, char* data, int sz): # <<<<<<<<<<<<<< + * pass + * +*/ + +static PyObject *__pyx_f_9thriftpy2_9transport_6cybase_15CyTransportBase_c_write(CYTHON_UNUSED struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *__pyx_v_self, CYTHON_UNUSED char *__pyx_v_data, CYTHON_UNUSED int __pyx_v_sz) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("c_write", 0); + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/cybase.pyx":114 + * pass + * + * cdef c_flush(self): # <<<<<<<<<<<<<< + * pass + * +*/ + +static PyObject *__pyx_f_9thriftpy2_9transport_6cybase_15CyTransportBase_c_flush(CYTHON_UNUSED struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("c_flush", 0); + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/cybase.pyx":117 + * pass + * + * def clean(self): # <<<<<<<<<<<<<< + * pass + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_9transport_6cybase_15CyTransportBase_1clean(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_9transport_6cybase_15CyTransportBase_1clean = {"clean", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_6cybase_15CyTransportBase_1clean, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_9transport_6cybase_15CyTransportBase_1clean(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("clean (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("clean", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("clean", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_9thriftpy2_9transport_6cybase_15CyTransportBase_clean(((struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_9transport_6cybase_15CyTransportBase_clean(CYTHON_UNUSED struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("clean", 0); + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/cybase.pyx":120 + * pass + * + * @property # <<<<<<<<<<<<<< + * def sock(self): + * if not self.trans: +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_9transport_6cybase_15CyTransportBase_4sock_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_9thriftpy2_9transport_6cybase_15CyTransportBase_4sock_1__get__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_9thriftpy2_9transport_6cybase_15CyTransportBase_4sock___get__(((struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_9transport_6cybase_15CyTransportBase_4sock___get__(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "thriftpy2/transport/cybase.pyx":122 + * @property + * def sock(self): + * if not self.trans: # <<<<<<<<<<<<<< + * return + * return getattr(self.trans, 'sock', None) +*/ + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_v_self->trans); if (unlikely((__pyx_t_1 < 0))) __PYX_ERR(0, 122, __pyx_L1_error) + __pyx_t_2 = (!__pyx_t_1); + if (__pyx_t_2) { + + /* "thriftpy2/transport/cybase.pyx":123 + * def sock(self): + * if not self.trans: + * return # <<<<<<<<<<<<<< + * return getattr(self.trans, 'sock', None) + * +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + + /* "thriftpy2/transport/cybase.pyx":122 + * @property + * def sock(self): + * if not self.trans: # <<<<<<<<<<<<<< + * return + * return getattr(self.trans, 'sock', None) +*/ + } + + /* "thriftpy2/transport/cybase.pyx":124 + * if not self.trans: + * return + * return getattr(self.trans, 'sock', None) # <<<<<<<<<<<<<< + * + * cdef get_string(self, int sz): +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_3 = __pyx_v_self->trans; + __Pyx_INCREF(__pyx_t_3); + __pyx_t_4 = __Pyx_GetAttr3(__pyx_t_3, __pyx_mstate_global->__pyx_n_u_sock, Py_None); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 124, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_r = __pyx_t_4; + __pyx_t_4 = 0; + goto __pyx_L0; + + /* "thriftpy2/transport/cybase.pyx":120 + * pass + * + * @property # <<<<<<<<<<<<<< + * def sock(self): + * if not self.trans: +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("thriftpy2.transport.cybase.CyTransportBase.sock.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/cybase.pyx":126 + * return getattr(self.trans, 'sock', None) + * + * cdef get_string(self, int sz): # <<<<<<<<<<<<<< + * cdef: + * char out[STACK_STRING_LEN] +*/ + +static PyObject *__pyx_f_9thriftpy2_9transport_6cybase_15CyTransportBase_get_string(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *__pyx_v_self, int __pyx_v_sz) { + char __pyx_v_out[__pyx_e_9thriftpy2_9transport_6cybase_STACK_STRING_LEN]; + char *__pyx_v_dy_out; + PyObject *__pyx_v_size = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + Py_ssize_t __pyx_t_3; + Py_ssize_t __pyx_t_4; + int __pyx_t_5; + int __pyx_t_6; + char const *__pyx_t_7; + PyObject *__pyx_t_8 = NULL; + PyObject *__pyx_t_9 = NULL; + PyObject *__pyx_t_10 = NULL; + PyObject *__pyx_t_11 = NULL; + PyObject *__pyx_t_12 = NULL; + PyObject *__pyx_t_13 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("get_string", 0); + + /* "thriftpy2/transport/cybase.pyx":131 + * char *dy_out + * + * if sz > STACK_STRING_LEN: # <<<<<<<<<<<<<< + * dy_out = malloc(sz) + * try: +*/ + __pyx_t_1 = (__pyx_v_sz > __pyx_e_9thriftpy2_9transport_6cybase_STACK_STRING_LEN); + if (__pyx_t_1) { + + /* "thriftpy2/transport/cybase.pyx":132 + * + * if sz > STACK_STRING_LEN: + * dy_out = malloc(sz) # <<<<<<<<<<<<<< + * try: + * size = self.c_read(sz, dy_out) +*/ + __pyx_v_dy_out = ((char *)malloc(__pyx_v_sz)); + + /* "thriftpy2/transport/cybase.pyx":133 + * if sz > STACK_STRING_LEN: + * dy_out = malloc(sz) + * try: # <<<<<<<<<<<<<< + * size = self.c_read(sz, dy_out) + * return dy_out[:size] +*/ + /*try:*/ { + + /* "thriftpy2/transport/cybase.pyx":134 + * dy_out = malloc(sz) + * try: + * size = self.c_read(sz, dy_out) # <<<<<<<<<<<<<< + * return dy_out[:size] + * finally: +*/ + __pyx_t_2 = ((struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_CyTransportBase *)__pyx_v_self->__pyx_vtab)->c_read(__pyx_v_self, __pyx_v_sz, __pyx_v_dy_out); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 134, __pyx_L5_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_v_size = __pyx_t_2; + __pyx_t_2 = 0; + + /* "thriftpy2/transport/cybase.pyx":135 + * try: + * size = self.c_read(sz, dy_out) + * return dy_out[:size] # <<<<<<<<<<<<<< + * finally: + * free(dy_out) +*/ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_size); + __pyx_t_2 = __pyx_v_size; + __pyx_t_1 = (__pyx_t_2 == Py_None); + if (__pyx_t_1) { + __pyx_t_3 = PY_SSIZE_T_MAX; + } else { + __pyx_t_4 = __Pyx_PyIndex_AsSsize_t(__pyx_t_2); if (unlikely((__pyx_t_4 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 135, __pyx_L5_error) + __pyx_t_3 = __pyx_t_4; + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyBytes_FromStringAndSize(__pyx_v_dy_out + 0, __pyx_t_3 - 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 135, __pyx_L5_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L4_return; + } + + /* "thriftpy2/transport/cybase.pyx":137 + * return dy_out[:size] + * finally: + * free(dy_out) # <<<<<<<<<<<<<< + * else: + * size = self.c_read(sz, out) +*/ + /*finally:*/ { + __pyx_L5_error:; + /*exception exit:*/{ + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + __pyx_t_8 = 0; __pyx_t_9 = 0; __pyx_t_10 = 0; __pyx_t_11 = 0; __pyx_t_12 = 0; __pyx_t_13 = 0; + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_ExceptionSwap(&__pyx_t_11, &__pyx_t_12, &__pyx_t_13); + if ( unlikely(__Pyx_GetException(&__pyx_t_8, &__pyx_t_9, &__pyx_t_10) < 0)) __Pyx_ErrFetch(&__pyx_t_8, &__pyx_t_9, &__pyx_t_10); + __Pyx_XGOTREF(__pyx_t_8); + __Pyx_XGOTREF(__pyx_t_9); + __Pyx_XGOTREF(__pyx_t_10); + __Pyx_XGOTREF(__pyx_t_11); + __Pyx_XGOTREF(__pyx_t_12); + __Pyx_XGOTREF(__pyx_t_13); + __pyx_t_5 = __pyx_lineno; __pyx_t_6 = __pyx_clineno; __pyx_t_7 = __pyx_filename; + { + free(__pyx_v_dy_out); + } + __Pyx_XGIVEREF(__pyx_t_11); + __Pyx_XGIVEREF(__pyx_t_12); + __Pyx_XGIVEREF(__pyx_t_13); + __Pyx_ExceptionReset(__pyx_t_11, __pyx_t_12, __pyx_t_13); + __Pyx_XGIVEREF(__pyx_t_8); + __Pyx_XGIVEREF(__pyx_t_9); + __Pyx_XGIVEREF(__pyx_t_10); + __Pyx_ErrRestore(__pyx_t_8, __pyx_t_9, __pyx_t_10); + __pyx_t_8 = 0; __pyx_t_9 = 0; __pyx_t_10 = 0; __pyx_t_11 = 0; __pyx_t_12 = 0; __pyx_t_13 = 0; + __pyx_lineno = __pyx_t_5; __pyx_clineno = __pyx_t_6; __pyx_filename = __pyx_t_7; + goto __pyx_L1_error; + } + __pyx_L4_return: { + __pyx_t_13 = __pyx_r; + __pyx_r = 0; + free(__pyx_v_dy_out); + __pyx_r = __pyx_t_13; + __pyx_t_13 = 0; + goto __pyx_L0; + } + } + + /* "thriftpy2/transport/cybase.pyx":131 + * char *dy_out + * + * if sz > STACK_STRING_LEN: # <<<<<<<<<<<<<< + * dy_out = malloc(sz) + * try: +*/ + } + + /* "thriftpy2/transport/cybase.pyx":139 + * free(dy_out) + * else: + * size = self.c_read(sz, out) # <<<<<<<<<<<<<< + * return out[:size] +*/ + /*else*/ { + __pyx_t_2 = ((struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_CyTransportBase *)__pyx_v_self->__pyx_vtab)->c_read(__pyx_v_self, __pyx_v_sz, __pyx_v_out); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 139, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_v_size = __pyx_t_2; + __pyx_t_2 = 0; + + /* "thriftpy2/transport/cybase.pyx":140 + * else: + * size = self.c_read(sz, out) + * return out[:size] # <<<<<<<<<<<<<< +*/ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_size); + __pyx_t_2 = __pyx_v_size; + __pyx_t_1 = (__pyx_t_2 == Py_None); + if (__pyx_t_1) { + __pyx_t_3 = PY_SSIZE_T_MAX; + } else { + __pyx_t_4 = __Pyx_PyIndex_AsSsize_t(__pyx_t_2); if (unlikely((__pyx_t_4 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 140, __pyx_L1_error) + __pyx_t_3 = __pyx_t_4; + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyBytes_FromStringAndSize(__pyx_v_out + 0, __pyx_t_3 - 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 140, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + } + + /* "thriftpy2/transport/cybase.pyx":126 + * return getattr(self.trans, 'sock', None) + * + * cdef get_string(self, int sz): # <<<<<<<<<<<<<< + * cdef: + * char out[STACK_STRING_LEN] +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("thriftpy2.transport.cybase.CyTransportBase.get_string", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_size); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * cdef tuple state + * cdef object _dict +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_9transport_6cybase_15CyTransportBase_3__reduce_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_9transport_6cybase_15CyTransportBase_3__reduce_cython__ = {"__reduce_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_6cybase_15CyTransportBase_3__reduce_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_9transport_6cybase_15CyTransportBase_3__reduce_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("__reduce_cython__", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("__reduce_cython__", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_9thriftpy2_9transport_6cybase_15CyTransportBase_2__reduce_cython__(((struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_9transport_6cybase_15CyTransportBase_2__reduce_cython__(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *__pyx_v_self) { + PyObject *__pyx_v_state = 0; + PyObject *__pyx_v__dict = 0; + int __pyx_v_use_setstate; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__reduce_cython__", 0); + + /* "(tree fragment)":5 + * cdef object _dict + * cdef bint use_setstate + * state = (self.trans,) # <<<<<<<<<<<<<< + * _dict = getattr(self, '__dict__', None) + * if _dict is not None and _dict: +*/ + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 5, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_v_self->trans); + __Pyx_GIVEREF(__pyx_v_self->trans); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_self->trans) != (0)) __PYX_ERR(1, 5, __pyx_L1_error); + __pyx_v_state = ((PyObject*)__pyx_t_1); + __pyx_t_1 = 0; + + /* "(tree fragment)":6 + * cdef bint use_setstate + * state = (self.trans,) + * _dict = getattr(self, '__dict__', None) # <<<<<<<<<<<<<< + * if _dict is not None and _dict: + * state += (_dict,) +*/ + __pyx_t_1 = __Pyx_GetAttr3(((PyObject *)__pyx_v_self), __pyx_mstate_global->__pyx_n_u_dict, Py_None); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 6, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v__dict = __pyx_t_1; + __pyx_t_1 = 0; + + /* "(tree fragment)":7 + * state = (self.trans,) + * _dict = getattr(self, '__dict__', None) + * if _dict is not None and _dict: # <<<<<<<<<<<<<< + * state += (_dict,) + * use_setstate = True +*/ + __pyx_t_3 = (__pyx_v__dict != Py_None); + if (__pyx_t_3) { + } else { + __pyx_t_2 = __pyx_t_3; + goto __pyx_L4_bool_binop_done; + } + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_v__dict); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(1, 7, __pyx_L1_error) + __pyx_t_2 = __pyx_t_3; + __pyx_L4_bool_binop_done:; + if (__pyx_t_2) { + + /* "(tree fragment)":8 + * _dict = getattr(self, '__dict__', None) + * if _dict is not None and _dict: + * state += (_dict,) # <<<<<<<<<<<<<< + * use_setstate = True + * else: +*/ + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 8, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_v__dict); + __Pyx_GIVEREF(__pyx_v__dict); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v__dict) != (0)) __PYX_ERR(1, 8, __pyx_L1_error); + __pyx_t_4 = PyNumber_InPlaceAdd(__pyx_v_state, __pyx_t_1); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 8, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF_SET(__pyx_v_state, ((PyObject*)__pyx_t_4)); + __pyx_t_4 = 0; + + /* "(tree fragment)":9 + * if _dict is not None and _dict: + * state += (_dict,) + * use_setstate = True # <<<<<<<<<<<<<< + * else: + * use_setstate = self.trans is not None +*/ + __pyx_v_use_setstate = 1; + + /* "(tree fragment)":7 + * state = (self.trans,) + * _dict = getattr(self, '__dict__', None) + * if _dict is not None and _dict: # <<<<<<<<<<<<<< + * state += (_dict,) + * use_setstate = True +*/ + goto __pyx_L3; + } + + /* "(tree fragment)":11 + * use_setstate = True + * else: + * use_setstate = self.trans is not None # <<<<<<<<<<<<<< + * if use_setstate: + * return __pyx_unpickle_CyTransportBase, (type(self), 0xcbd31fe, None), state +*/ + /*else*/ { + __pyx_t_2 = (__pyx_v_self->trans != Py_None); + __pyx_v_use_setstate = __pyx_t_2; + } + __pyx_L3:; + + /* "(tree fragment)":12 + * else: + * use_setstate = self.trans is not None + * if use_setstate: # <<<<<<<<<<<<<< + * return __pyx_unpickle_CyTransportBase, (type(self), 0xcbd31fe, None), state + * else: +*/ + if (__pyx_v_use_setstate) { + + /* "(tree fragment)":13 + * use_setstate = self.trans is not None + * if use_setstate: + * return __pyx_unpickle_CyTransportBase, (type(self), 0xcbd31fe, None), state # <<<<<<<<<<<<<< + * else: + * return __pyx_unpickle_CyTransportBase, (type(self), 0xcbd31fe, state) +*/ + __Pyx_XDECREF(__pyx_r); + __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_mstate_global->__pyx_n_u_pyx_unpickle_CyTransportBase); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 13, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_1 = PyTuple_New(3); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 13, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); + __Pyx_GIVEREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))) != (0)) __PYX_ERR(1, 13, __pyx_L1_error); + __Pyx_INCREF(__pyx_mstate_global->__pyx_int_213725694); + __Pyx_GIVEREF(__pyx_mstate_global->__pyx_int_213725694); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_mstate_global->__pyx_int_213725694) != (0)) __PYX_ERR(1, 13, __pyx_L1_error); + __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(Py_None); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 2, Py_None) != (0)) __PYX_ERR(1, 13, __pyx_L1_error); + __pyx_t_5 = PyTuple_New(3); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 13, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_GIVEREF(__pyx_t_4); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4) != (0)) __PYX_ERR(1, 13, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_1); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_1) != (0)) __PYX_ERR(1, 13, __pyx_L1_error); + __Pyx_INCREF(__pyx_v_state); + __Pyx_GIVEREF(__pyx_v_state); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_5, 2, __pyx_v_state) != (0)) __PYX_ERR(1, 13, __pyx_L1_error); + __pyx_t_4 = 0; + __pyx_t_1 = 0; + __pyx_r = __pyx_t_5; + __pyx_t_5 = 0; + goto __pyx_L0; + + /* "(tree fragment)":12 + * else: + * use_setstate = self.trans is not None + * if use_setstate: # <<<<<<<<<<<<<< + * return __pyx_unpickle_CyTransportBase, (type(self), 0xcbd31fe, None), state + * else: +*/ + } + + /* "(tree fragment)":15 + * return __pyx_unpickle_CyTransportBase, (type(self), 0xcbd31fe, None), state + * else: + * return __pyx_unpickle_CyTransportBase, (type(self), 0xcbd31fe, state) # <<<<<<<<<<<<<< + * def __setstate_cython__(self, __pyx_state): + * __pyx_unpickle_CyTransportBase__set_state(self, __pyx_state) +*/ + /*else*/ { + __Pyx_XDECREF(__pyx_r); + __Pyx_GetModuleGlobalName(__pyx_t_5, __pyx_mstate_global->__pyx_n_u_pyx_unpickle_CyTransportBase); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 15, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_1 = PyTuple_New(3); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 15, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); + __Pyx_GIVEREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))) != (0)) __PYX_ERR(1, 15, __pyx_L1_error); + __Pyx_INCREF(__pyx_mstate_global->__pyx_int_213725694); + __Pyx_GIVEREF(__pyx_mstate_global->__pyx_int_213725694); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_mstate_global->__pyx_int_213725694) != (0)) __PYX_ERR(1, 15, __pyx_L1_error); + __Pyx_INCREF(__pyx_v_state); + __Pyx_GIVEREF(__pyx_v_state); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 2, __pyx_v_state) != (0)) __PYX_ERR(1, 15, __pyx_L1_error); + __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 15, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_GIVEREF(__pyx_t_5); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_5) != (0)) __PYX_ERR(1, 15, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_1); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_1) != (0)) __PYX_ERR(1, 15, __pyx_L1_error); + __pyx_t_5 = 0; + __pyx_t_1 = 0; + __pyx_r = __pyx_t_4; + __pyx_t_4 = 0; + goto __pyx_L0; + } + + /* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * cdef tuple state + * cdef object _dict +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("thriftpy2.transport.cybase.CyTransportBase.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_state); + __Pyx_XDECREF(__pyx_v__dict); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":16 + * else: + * return __pyx_unpickle_CyTransportBase, (type(self), 0xcbd31fe, state) + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * __pyx_unpickle_CyTransportBase__set_state(self, __pyx_state) +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_9transport_6cybase_15CyTransportBase_5__setstate_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_9transport_6cybase_15CyTransportBase_5__setstate_cython__ = {"__setstate_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_6cybase_15CyTransportBase_5__setstate_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_9transport_6cybase_15CyTransportBase_5__setstate_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v___pyx_state = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_pyx_state,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(1, 16, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(1, 16, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "__setstate_cython__", 0) < (0)) __PYX_ERR(1, 16, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("__setstate_cython__", 1, 1, 1, i); __PYX_ERR(1, 16, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(1, 16, __pyx_L3_error) + } + __pyx_v___pyx_state = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__setstate_cython__", 1, 1, 1, __pyx_nargs); __PYX_ERR(1, 16, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("thriftpy2.transport.cybase.CyTransportBase.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_9thriftpy2_9transport_6cybase_15CyTransportBase_4__setstate_cython__(((struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *)__pyx_v_self), __pyx_v___pyx_state); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_9transport_6cybase_15CyTransportBase_4__setstate_cython__(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *__pyx_v_self, PyObject *__pyx_v___pyx_state) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__setstate_cython__", 0); + + /* "(tree fragment)":17 + * return __pyx_unpickle_CyTransportBase, (type(self), 0xcbd31fe, state) + * def __setstate_cython__(self, __pyx_state): + * __pyx_unpickle_CyTransportBase__set_state(self, __pyx_state) # <<<<<<<<<<<<<< +*/ + __pyx_t_1 = __pyx_v___pyx_state; + __Pyx_INCREF(__pyx_t_1); + if (!(likely(PyTuple_CheckExact(__pyx_t_1))||((__pyx_t_1) == Py_None) || __Pyx_RaiseUnexpectedTypeError("tuple", __pyx_t_1))) __PYX_ERR(1, 17, __pyx_L1_error) + if (unlikely(__pyx_t_1 == Py_None)) { + PyErr_SetString(PyExc_TypeError, "cannot pass None into a C function argument that is declared 'not None'"); + __PYX_ERR(1, 17, __pyx_L1_error) + } + __pyx_t_2 = __pyx_f_9thriftpy2_9transport_6cybase___pyx_unpickle_CyTransportBase__set_state(__pyx_v_self, ((PyObject*)__pyx_t_1)); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 17, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "(tree fragment)":16 + * else: + * return __pyx_unpickle_CyTransportBase, (type(self), 0xcbd31fe, state) + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * __pyx_unpickle_CyTransportBase__set_state(self, __pyx_state) +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("thriftpy2.transport.cybase.CyTransportBase.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":4 + * int __Pyx_CheckUnpickleChecksum(long, long, long, long, const char*) except -1 + * int __Pyx_UpdateUnpickledDict(object, object, Py_ssize_t) except -1 + * def __pyx_unpickle_CyTransportBase(__pyx_type, long __pyx_checksum, tuple __pyx_state): # <<<<<<<<<<<<<< + * cdef object __pyx_result + * __Pyx_CheckUnpickleChecksum(__pyx_checksum, 0xcbd31fe, 0x2c17e4d, 0x4738019, b'trans') +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_9transport_6cybase_1__pyx_unpickle_CyTransportBase(PyObject *__pyx_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_9transport_6cybase_1__pyx_unpickle_CyTransportBase = {"__pyx_unpickle_CyTransportBase", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_6cybase_1__pyx_unpickle_CyTransportBase, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_9transport_6cybase_1__pyx_unpickle_CyTransportBase(PyObject *__pyx_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v___pyx_type = 0; + long __pyx_v___pyx_checksum; + PyObject *__pyx_v___pyx_state = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[3] = {0,0,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__pyx_unpickle_CyTransportBase (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_pyx_type,&__pyx_mstate_global->__pyx_n_u_pyx_checksum,&__pyx_mstate_global->__pyx_n_u_pyx_state,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(1, 4, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 3: + values[2] = __Pyx_ArgRef_FASTCALL(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(1, 4, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 2: + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(1, 4, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(1, 4, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "__pyx_unpickle_CyTransportBase", 0) < (0)) __PYX_ERR(1, 4, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 3; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("__pyx_unpickle_CyTransportBase", 1, 3, 3, i); __PYX_ERR(1, 4, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 3)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(1, 4, __pyx_L3_error) + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(1, 4, __pyx_L3_error) + values[2] = __Pyx_ArgRef_FASTCALL(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(1, 4, __pyx_L3_error) + } + __pyx_v___pyx_type = values[0]; + __pyx_v___pyx_checksum = __Pyx_PyLong_As_long(values[1]); if (unlikely((__pyx_v___pyx_checksum == (long)-1) && PyErr_Occurred())) __PYX_ERR(1, 4, __pyx_L3_error) + __pyx_v___pyx_state = ((PyObject*)values[2]); + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__pyx_unpickle_CyTransportBase", 1, 3, 3, __pyx_nargs); __PYX_ERR(1, 4, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("thriftpy2.transport.cybase.__pyx_unpickle_CyTransportBase", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v___pyx_state), (&PyTuple_Type), 1, "__pyx_state", 1))) __PYX_ERR(1, 4, __pyx_L1_error) + __pyx_r = __pyx_pf_9thriftpy2_9transport_6cybase___pyx_unpickle_CyTransportBase(__pyx_self, __pyx_v___pyx_type, __pyx_v___pyx_checksum, __pyx_v___pyx_state); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + goto __pyx_L7_cleaned_up; + __pyx_L0:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __pyx_L7_cleaned_up:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_9transport_6cybase___pyx_unpickle_CyTransportBase(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v___pyx_type, long __pyx_v___pyx_checksum, PyObject *__pyx_v___pyx_state) { + PyObject *__pyx_v___pyx_result = 0; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + size_t __pyx_t_4; + int __pyx_t_5; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__pyx_unpickle_CyTransportBase", 0); + + /* "(tree fragment)":6 + * def __pyx_unpickle_CyTransportBase(__pyx_type, long __pyx_checksum, tuple __pyx_state): + * cdef object __pyx_result + * __Pyx_CheckUnpickleChecksum(__pyx_checksum, 0xcbd31fe, 0x2c17e4d, 0x4738019, b'trans') # <<<<<<<<<<<<<< + * __pyx_result = CyTransportBase.__new__(__pyx_type) + * if __pyx_state is not None: +*/ + __pyx_t_1 = __Pyx_CheckUnpickleChecksum(__pyx_v___pyx_checksum, 0xcbd31fe, 0x2c17e4d, 0x4738019, __pyx_k_trans); if (unlikely(__pyx_t_1 == ((int)-1))) __PYX_ERR(1, 6, __pyx_L1_error) + + /* "(tree fragment)":7 + * cdef object __pyx_result + * __Pyx_CheckUnpickleChecksum(__pyx_checksum, 0xcbd31fe, 0x2c17e4d, 0x4738019, b'trans') + * __pyx_result = CyTransportBase.__new__(__pyx_type) # <<<<<<<<<<<<<< + * if __pyx_state is not None: + * __pyx_unpickle_CyTransportBase__set_state( __pyx_result, __pyx_state) +*/ + __pyx_t_3 = ((PyObject *)__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase); + __Pyx_INCREF(__pyx_t_3); + __pyx_t_4 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_v___pyx_type}; + __pyx_t_2 = __Pyx_PyObject_FastCallMethod((PyObject*)__pyx_mstate_global->__pyx_n_u_new, __pyx_callargs+__pyx_t_4, (2-__pyx_t_4) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 7, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __pyx_v___pyx_result = __pyx_t_2; + __pyx_t_2 = 0; + + /* "(tree fragment)":8 + * __Pyx_CheckUnpickleChecksum(__pyx_checksum, 0xcbd31fe, 0x2c17e4d, 0x4738019, b'trans') + * __pyx_result = CyTransportBase.__new__(__pyx_type) + * if __pyx_state is not None: # <<<<<<<<<<<<<< + * __pyx_unpickle_CyTransportBase__set_state( __pyx_result, __pyx_state) + * return __pyx_result +*/ + __pyx_t_5 = (__pyx_v___pyx_state != ((PyObject*)Py_None)); + if (__pyx_t_5) { + + /* "(tree fragment)":9 + * __pyx_result = CyTransportBase.__new__(__pyx_type) + * if __pyx_state is not None: + * __pyx_unpickle_CyTransportBase__set_state( __pyx_result, __pyx_state) # <<<<<<<<<<<<<< + * return __pyx_result + * cdef __pyx_unpickle_CyTransportBase__set_state(CyTransportBase __pyx_result, __pyx_state: tuple): +*/ + if (unlikely(__pyx_v___pyx_state == Py_None)) { + PyErr_SetString(PyExc_TypeError, "cannot pass None into a C function argument that is declared 'not None'"); + __PYX_ERR(1, 9, __pyx_L1_error) + } + __pyx_t_2 = __pyx_f_9thriftpy2_9transport_6cybase___pyx_unpickle_CyTransportBase__set_state(((struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *)__pyx_v___pyx_result), __pyx_v___pyx_state); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 9, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "(tree fragment)":8 + * __Pyx_CheckUnpickleChecksum(__pyx_checksum, 0xcbd31fe, 0x2c17e4d, 0x4738019, b'trans') + * __pyx_result = CyTransportBase.__new__(__pyx_type) + * if __pyx_state is not None: # <<<<<<<<<<<<<< + * __pyx_unpickle_CyTransportBase__set_state( __pyx_result, __pyx_state) + * return __pyx_result +*/ + } + + /* "(tree fragment)":10 + * if __pyx_state is not None: + * __pyx_unpickle_CyTransportBase__set_state( __pyx_result, __pyx_state) + * return __pyx_result # <<<<<<<<<<<<<< + * cdef __pyx_unpickle_CyTransportBase__set_state(CyTransportBase __pyx_result, __pyx_state: tuple): + * __pyx_result.trans = __pyx_state[0] +*/ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v___pyx_result); + __pyx_r = __pyx_v___pyx_result; + goto __pyx_L0; + + /* "(tree fragment)":4 + * int __Pyx_CheckUnpickleChecksum(long, long, long, long, const char*) except -1 + * int __Pyx_UpdateUnpickledDict(object, object, Py_ssize_t) except -1 + * def __pyx_unpickle_CyTransportBase(__pyx_type, long __pyx_checksum, tuple __pyx_state): # <<<<<<<<<<<<<< + * cdef object __pyx_result + * __Pyx_CheckUnpickleChecksum(__pyx_checksum, 0xcbd31fe, 0x2c17e4d, 0x4738019, b'trans') +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("thriftpy2.transport.cybase.__pyx_unpickle_CyTransportBase", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v___pyx_result); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":11 + * __pyx_unpickle_CyTransportBase__set_state( __pyx_result, __pyx_state) + * return __pyx_result + * cdef __pyx_unpickle_CyTransportBase__set_state(CyTransportBase __pyx_result, __pyx_state: tuple): # <<<<<<<<<<<<<< + * __pyx_result.trans = __pyx_state[0] + * __Pyx_UpdateUnpickledDict(__pyx_result, __pyx_state, 1) +*/ + +static PyObject *__pyx_f_9thriftpy2_9transport_6cybase___pyx_unpickle_CyTransportBase__set_state(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *__pyx_v___pyx_result, PyObject *__pyx_v___pyx_state) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__pyx_unpickle_CyTransportBase__set_state", 0); + + /* "(tree fragment)":12 + * return __pyx_result + * cdef __pyx_unpickle_CyTransportBase__set_state(CyTransportBase __pyx_result, __pyx_state: tuple): + * __pyx_result.trans = __pyx_state[0] # <<<<<<<<<<<<<< + * __Pyx_UpdateUnpickledDict(__pyx_result, __pyx_state, 1) +*/ + __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 0, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1, __Pyx_ReferenceSharing_FunctionArgument); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 12, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF(__pyx_v___pyx_result->trans); + __Pyx_DECREF(__pyx_v___pyx_result->trans); + __pyx_v___pyx_result->trans = __pyx_t_1; + __pyx_t_1 = 0; + + /* "(tree fragment)":13 + * cdef __pyx_unpickle_CyTransportBase__set_state(CyTransportBase __pyx_result, __pyx_state: tuple): + * __pyx_result.trans = __pyx_state[0] + * __Pyx_UpdateUnpickledDict(__pyx_result, __pyx_state, 1) # <<<<<<<<<<<<<< +*/ + __pyx_t_2 = __Pyx_UpdateUnpickledDict(((PyObject *)__pyx_v___pyx_result), __pyx_v___pyx_state, 1); if (unlikely(__pyx_t_2 == ((int)-1))) __PYX_ERR(1, 13, __pyx_L1_error) + + /* "(tree fragment)":11 + * __pyx_unpickle_CyTransportBase__set_state( __pyx_result, __pyx_state) + * return __pyx_result + * cdef __pyx_unpickle_CyTransportBase__set_state(CyTransportBase __pyx_result, __pyx_state: tuple): # <<<<<<<<<<<<<< + * __pyx_result.trans = __pyx_state[0] + * __Pyx_UpdateUnpickledDict(__pyx_result, __pyx_state, 1) +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("thriftpy2.transport.cybase.__pyx_unpickle_CyTransportBase__set_state", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} +/* #### Code section: module_exttypes ### */ +static struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_TCyBuffer __pyx_vtable_9thriftpy2_9transport_6cybase_TCyBuffer; + +static PyObject *__pyx_tp_new_9thriftpy2_9transport_6cybase_TCyBuffer(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *p; + PyObject *o; + o = __Pyx_AllocateExtensionType(t, 0); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *)o); + p->__pyx_vtab = __pyx_vtabptr_9thriftpy2_9transport_6cybase_TCyBuffer; + if (unlikely(__pyx_pw_9thriftpy2_9transport_6cybase_9TCyBuffer_1__cinit__(o, a, k) < 0)) goto bad; + return o; + bad: + Py_DECREF(o); o = 0; + return NULL; +} + +static void __pyx_tp_dealloc_9thriftpy2_9transport_6cybase_TCyBuffer(PyObject *o) { + #if CYTHON_USE_TP_FINALIZE + if (unlikely(__Pyx_PyObject_GetSlot(o, tp_finalize, destructor)) && (!PyType_IS_GC(Py_TYPE(o)) || !__Pyx_PyObject_GC_IsFinalized(o))) { + if (__Pyx_PyObject_GetSlot(o, tp_dealloc, destructor) == __pyx_tp_dealloc_9thriftpy2_9transport_6cybase_TCyBuffer) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + } + #endif + { + PyObject *etype, *eval, *etb; + PyErr_Fetch(&etype, &eval, &etb); + __Pyx_SET_REFCNT(o, Py_REFCNT(o) + 1); + __pyx_pw_9thriftpy2_9transport_6cybase_9TCyBuffer_3__dealloc__(o); + __Pyx_SET_REFCNT(o, Py_REFCNT(o) - 1); + PyErr_Restore(etype, eval, etb); + } + PyTypeObject *tp = Py_TYPE(o); + #if CYTHON_USE_TYPE_SLOTS + (*tp->tp_free)(o); + #else + { + freefunc tp_free = (freefunc)PyType_GetSlot(tp, Py_tp_free); + if (tp_free) tp_free(o); + } + #endif + #if CYTHON_USE_TYPE_SPECS + Py_DECREF(tp); + #endif +} + +static PyMethodDef __pyx_methods_9thriftpy2_9transport_6cybase_TCyBuffer[] = { + {"__reduce_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_6cybase_9TCyBuffer_5__reduce_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, + {"__setstate_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_6cybase_9TCyBuffer_7__setstate_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, + {0, 0, 0, 0} +}; +#if CYTHON_USE_TYPE_SPECS +static PyType_Slot __pyx_type_9thriftpy2_9transport_6cybase_TCyBuffer_slots[] = { + {Py_tp_dealloc, (void *)__pyx_tp_dealloc_9thriftpy2_9transport_6cybase_TCyBuffer}, + {Py_tp_methods, (void *)__pyx_methods_9thriftpy2_9transport_6cybase_TCyBuffer}, + {Py_tp_new, (void *)__pyx_tp_new_9thriftpy2_9transport_6cybase_TCyBuffer}, + {0, 0}, +}; +static PyType_Spec __pyx_type_9thriftpy2_9transport_6cybase_TCyBuffer_spec = { + "thriftpy2.transport.cybase.TCyBuffer", + sizeof(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer), + 0, + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, + __pyx_type_9thriftpy2_9transport_6cybase_TCyBuffer_slots, +}; +#else + +static PyTypeObject __pyx_type_9thriftpy2_9transport_6cybase_TCyBuffer = { + PyVarObject_HEAD_INIT(0, 0) + "thriftpy2.transport.cybase.""TCyBuffer", /*tp_name*/ + sizeof(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_9thriftpy2_9transport_6cybase_TCyBuffer, /*tp_dealloc*/ + 0, /*tp_vectorcall_offset*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_as_async*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_9thriftpy2_9transport_6cybase_TCyBuffer, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + #if !CYTHON_USE_TYPE_SPECS + 0, /*tp_dictoffset*/ + #endif + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_9thriftpy2_9transport_6cybase_TCyBuffer, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if CYTHON_USE_TP_FINALIZE + 0, /*tp_finalize*/ + #else + NULL, /*tp_finalize*/ + #endif + #if !CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800 + 0, /*tp_vectorcall*/ + #endif + #if __PYX_NEED_TP_PRINT_SLOT == 1 + 0, /*tp_print*/ + #endif + #if PY_VERSION_HEX >= 0x030C0000 + 0, /*tp_watched*/ + #endif + #if PY_VERSION_HEX >= 0x030d00A4 + 0, /*tp_versions_used*/ + #endif + #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX >= 0x03090000 && PY_VERSION_HEX < 0x030a0000 + 0, /*tp_pypy_flags*/ + #endif +}; +#endif +static struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_CyTransportBase __pyx_vtable_9thriftpy2_9transport_6cybase_CyTransportBase; + +static PyObject *__pyx_tp_new_9thriftpy2_9transport_6cybase_CyTransportBase(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { + struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *p; + PyObject *o; + o = __Pyx_AllocateExtensionType(t, 0); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *)o); + p->__pyx_vtab = __pyx_vtabptr_9thriftpy2_9transport_6cybase_CyTransportBase; + p->trans = Py_None; Py_INCREF(Py_None); + return o; +} + +static void __pyx_tp_dealloc_9thriftpy2_9transport_6cybase_CyTransportBase(PyObject *o) { + struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *p = (struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *)o; + #if CYTHON_USE_TP_FINALIZE + if (unlikely(__Pyx_PyObject_GetSlot(o, tp_finalize, destructor)) && !__Pyx_PyObject_GC_IsFinalized(o)) { + if (__Pyx_PyObject_GetSlot(o, tp_dealloc, destructor) == __pyx_tp_dealloc_9thriftpy2_9transport_6cybase_CyTransportBase) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + } + #endif + PyObject_GC_UnTrack(o); + Py_CLEAR(p->trans); + PyTypeObject *tp = Py_TYPE(o); + #if CYTHON_USE_TYPE_SLOTS + (*tp->tp_free)(o); + #else + { + freefunc tp_free = (freefunc)PyType_GetSlot(tp, Py_tp_free); + if (tp_free) tp_free(o); + } + #endif + #if CYTHON_USE_TYPE_SPECS + Py_DECREF(tp); + #endif +} + +static int __pyx_tp_traverse_9thriftpy2_9transport_6cybase_CyTransportBase(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *p = (struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *)o; + { + e = __Pyx_call_type_traverse(o, 1, v, a); + if (e) return e; + } + if (p->trans) { + e = (*v)(p->trans, a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear_9thriftpy2_9transport_6cybase_CyTransportBase(PyObject *o) { + PyObject* tmp; + struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *p = (struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *)o; + tmp = ((PyObject*)p->trans); + p->trans = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + return 0; +} + +static PyObject *__pyx_getprop_9thriftpy2_9transport_6cybase_15CyTransportBase_sock(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_9thriftpy2_9transport_6cybase_15CyTransportBase_4sock_1__get__(o); +} + +static PyMethodDef __pyx_methods_9thriftpy2_9transport_6cybase_CyTransportBase[] = { + {"clean", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_6cybase_15CyTransportBase_1clean, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, + {"__reduce_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_6cybase_15CyTransportBase_3__reduce_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, + {"__setstate_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_6cybase_15CyTransportBase_5__setstate_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, + {0, 0, 0, 0} +}; + +static struct PyGetSetDef __pyx_getsets_9thriftpy2_9transport_6cybase_CyTransportBase[] = { + {"sock", __pyx_getprop_9thriftpy2_9transport_6cybase_15CyTransportBase_sock, 0, 0, 0}, + {0, 0, 0, 0, 0} +}; +#if CYTHON_USE_TYPE_SPECS +static PyType_Slot __pyx_type_9thriftpy2_9transport_6cybase_CyTransportBase_slots[] = { + {Py_tp_dealloc, (void *)__pyx_tp_dealloc_9thriftpy2_9transport_6cybase_CyTransportBase}, + {Py_tp_traverse, (void *)__pyx_tp_traverse_9thriftpy2_9transport_6cybase_CyTransportBase}, + {Py_tp_clear, (void *)__pyx_tp_clear_9thriftpy2_9transport_6cybase_CyTransportBase}, + {Py_tp_methods, (void *)__pyx_methods_9thriftpy2_9transport_6cybase_CyTransportBase}, + {Py_tp_getset, (void *)__pyx_getsets_9thriftpy2_9transport_6cybase_CyTransportBase}, + {Py_tp_new, (void *)__pyx_tp_new_9thriftpy2_9transport_6cybase_CyTransportBase}, + {0, 0}, +}; +static PyType_Spec __pyx_type_9thriftpy2_9transport_6cybase_CyTransportBase_spec = { + "thriftpy2.transport.cybase.CyTransportBase", + sizeof(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase), + 0, + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, + __pyx_type_9thriftpy2_9transport_6cybase_CyTransportBase_slots, +}; +#else + +static PyTypeObject __pyx_type_9thriftpy2_9transport_6cybase_CyTransportBase = { + PyVarObject_HEAD_INIT(0, 0) + "thriftpy2.transport.cybase.""CyTransportBase", /*tp_name*/ + sizeof(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_9thriftpy2_9transport_6cybase_CyTransportBase, /*tp_dealloc*/ + 0, /*tp_vectorcall_offset*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_as_async*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + 0, /*tp_doc*/ + __pyx_tp_traverse_9thriftpy2_9transport_6cybase_CyTransportBase, /*tp_traverse*/ + __pyx_tp_clear_9thriftpy2_9transport_6cybase_CyTransportBase, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_9thriftpy2_9transport_6cybase_CyTransportBase, /*tp_methods*/ + 0, /*tp_members*/ + __pyx_getsets_9thriftpy2_9transport_6cybase_CyTransportBase, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + #if !CYTHON_USE_TYPE_SPECS + 0, /*tp_dictoffset*/ + #endif + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_9thriftpy2_9transport_6cybase_CyTransportBase, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if CYTHON_USE_TP_FINALIZE + 0, /*tp_finalize*/ + #else + NULL, /*tp_finalize*/ + #endif + #if !CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800 + 0, /*tp_vectorcall*/ + #endif + #if __PYX_NEED_TP_PRINT_SLOT == 1 + 0, /*tp_print*/ + #endif + #if PY_VERSION_HEX >= 0x030C0000 + 0, /*tp_watched*/ + #endif + #if PY_VERSION_HEX >= 0x030d00A4 + 0, /*tp_versions_used*/ + #endif + #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX >= 0x03090000 && PY_VERSION_HEX < 0x030a0000 + 0, /*tp_pypy_flags*/ + #endif +}; +#endif + +static PyMethodDef __pyx_methods[] = { + {0, 0, 0, 0} +}; +/* #### Code section: initfunc_declarations ### */ +static CYTHON_SMALL_CODE int __Pyx_InitCachedBuiltins(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_InitCachedConstants(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_InitGlobals(void); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_InitConstants(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_global_init_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_variable_export_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_function_export_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_type_init_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_type_import_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_variable_import_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_function_import_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_CreateCodeObjects(__pyx_mstatetype *__pyx_mstate); /*proto*/ +/* #### Code section: init_module ### */ + +static int __Pyx_modinit_global_init_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_modinit_global_init_code", 0); + /*--- Global init code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_modinit_variable_export_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_modinit_variable_export_code", 0); + /*--- Variable export code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_modinit_function_export_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_modinit_function_export_code", 0); + /*--- Function export code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_modinit_type_init_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__Pyx_modinit_type_init_code", 0); + /*--- Type init code ---*/ + __pyx_vtabptr_9thriftpy2_9transport_6cybase_TCyBuffer = &__pyx_vtable_9thriftpy2_9transport_6cybase_TCyBuffer; + __pyx_vtable_9thriftpy2_9transport_6cybase_TCyBuffer.move_to_start = (void (*)(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *))__pyx_f_9thriftpy2_9transport_6cybase_9TCyBuffer_move_to_start; + __pyx_vtable_9thriftpy2_9transport_6cybase_TCyBuffer.clean = (void (*)(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *))__pyx_f_9thriftpy2_9transport_6cybase_9TCyBuffer_clean; + __pyx_vtable_9thriftpy2_9transport_6cybase_TCyBuffer.write = (int (*)(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *, int, char const *))__pyx_f_9thriftpy2_9transport_6cybase_9TCyBuffer_write; + __pyx_vtable_9thriftpy2_9transport_6cybase_TCyBuffer.grow = (int (*)(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *, int))__pyx_f_9thriftpy2_9transport_6cybase_9TCyBuffer_grow; + __pyx_vtable_9thriftpy2_9transport_6cybase_TCyBuffer.read_trans = (PyObject *(*)(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *, PyObject *, int, char *))__pyx_f_9thriftpy2_9transport_6cybase_9TCyBuffer_read_trans; + #if CYTHON_USE_TYPE_SPECS + __pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer = (PyTypeObject *) __Pyx_PyType_FromModuleAndSpec(__pyx_m, &__pyx_type_9thriftpy2_9transport_6cybase_TCyBuffer_spec, NULL); if (unlikely(!__pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer)) __PYX_ERR(0, 7, __pyx_L1_error) + if (__Pyx_fix_up_extension_type_from_spec(&__pyx_type_9thriftpy2_9transport_6cybase_TCyBuffer_spec, __pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer) < (0)) __PYX_ERR(0, 7, __pyx_L1_error) + #else + __pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer = &__pyx_type_9thriftpy2_9transport_6cybase_TCyBuffer; + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + #endif + #if !CYTHON_USE_TYPE_SPECS + if (__Pyx_PyType_Ready(__pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer) < (0)) __PYX_ERR(0, 7, __pyx_L1_error) + #endif + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount((PyObject*)__pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer); + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer->tp_dictoffset && __pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer->tp_getattro == PyObject_GenericGetAttr)) { + __pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer->tp_getattro = PyObject_GenericGetAttr; + } + #endif + if (__Pyx_SetVtable(__pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer, __pyx_vtabptr_9thriftpy2_9transport_6cybase_TCyBuffer) < (0)) __PYX_ERR(0, 7, __pyx_L1_error) + if (__Pyx_MergeVtables(__pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer) < (0)) __PYX_ERR(0, 7, __pyx_L1_error) + if (PyObject_SetAttr(__pyx_m, __pyx_mstate_global->__pyx_n_u_TCyBuffer, (PyObject *) __pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer) < (0)) __PYX_ERR(0, 7, __pyx_L1_error) + if (__Pyx_setup_reduce((PyObject *) __pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer) < (0)) __PYX_ERR(0, 7, __pyx_L1_error) + __pyx_vtabptr_9thriftpy2_9transport_6cybase_CyTransportBase = &__pyx_vtable_9thriftpy2_9transport_6cybase_CyTransportBase; + __pyx_vtable_9thriftpy2_9transport_6cybase_CyTransportBase.c_read = (PyObject *(*)(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *, int, char *))__pyx_f_9thriftpy2_9transport_6cybase_15CyTransportBase_c_read; + __pyx_vtable_9thriftpy2_9transport_6cybase_CyTransportBase.c_write = (PyObject *(*)(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *, char *, int))__pyx_f_9thriftpy2_9transport_6cybase_15CyTransportBase_c_write; + __pyx_vtable_9thriftpy2_9transport_6cybase_CyTransportBase.c_flush = (PyObject *(*)(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *))__pyx_f_9thriftpy2_9transport_6cybase_15CyTransportBase_c_flush; + __pyx_vtable_9thriftpy2_9transport_6cybase_CyTransportBase.get_string = (PyObject *(*)(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *, int))__pyx_f_9thriftpy2_9transport_6cybase_15CyTransportBase_get_string; + #if CYTHON_USE_TYPE_SPECS + __pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase = (PyTypeObject *) __Pyx_PyType_FromModuleAndSpec(__pyx_m, &__pyx_type_9thriftpy2_9transport_6cybase_CyTransportBase_spec, NULL); if (unlikely(!__pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase)) __PYX_ERR(0, 107, __pyx_L1_error) + if (__Pyx_fix_up_extension_type_from_spec(&__pyx_type_9thriftpy2_9transport_6cybase_CyTransportBase_spec, __pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase) < (0)) __PYX_ERR(0, 107, __pyx_L1_error) + #else + __pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase = &__pyx_type_9thriftpy2_9transport_6cybase_CyTransportBase; + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + #endif + #if !CYTHON_USE_TYPE_SPECS + if (__Pyx_PyType_Ready(__pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase) < (0)) __PYX_ERR(0, 107, __pyx_L1_error) + #endif + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount((PyObject*)__pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase); + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase->tp_dictoffset && __pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase->tp_getattro == PyObject_GenericGetAttr)) { + __pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase->tp_getattro = PyObject_GenericGetAttr; + } + #endif + if (__Pyx_SetVtable(__pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase, __pyx_vtabptr_9thriftpy2_9transport_6cybase_CyTransportBase) < (0)) __PYX_ERR(0, 107, __pyx_L1_error) + if (__Pyx_MergeVtables(__pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase) < (0)) __PYX_ERR(0, 107, __pyx_L1_error) + if (PyObject_SetAttr(__pyx_m, __pyx_mstate_global->__pyx_n_u_CyTransportBase, (PyObject *) __pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase) < (0)) __PYX_ERR(0, 107, __pyx_L1_error) + if (__Pyx_setup_reduce((PyObject *) __pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase) < (0)) __PYX_ERR(0, 107, __pyx_L1_error) + __Pyx_RefNannyFinishContext(); + return 0; + __pyx_L1_error:; + __Pyx_RefNannyFinishContext(); + return -1; +} + +static int __Pyx_modinit_type_import_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_modinit_type_import_code", 0); + /*--- Type import code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_modinit_variable_import_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_modinit_variable_import_code", 0); + /*--- Variable import code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_modinit_function_import_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_modinit_function_import_code", 0); + /*--- Function import code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +#if CYTHON_PEP489_MULTI_PHASE_INIT +static PyObject* __pyx_pymod_create(PyObject *spec, PyModuleDef *def); /*proto*/ +static int __pyx_pymod_exec_cybase(PyObject* module); /*proto*/ +static PyModuleDef_Slot __pyx_moduledef_slots[] = { + {Py_mod_create, (void*)__pyx_pymod_create}, + {Py_mod_exec, (void*)__pyx_pymod_exec_cybase}, + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + {Py_mod_gil, __Pyx_FREETHREADING_COMPATIBLE}, + #endif + #if PY_VERSION_HEX >= 0x030C0000 && CYTHON_USE_MODULE_STATE + {Py_mod_multiple_interpreters, Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED}, + #endif + {0, NULL} +}; +#endif + +#ifdef __cplusplus +namespace { + struct PyModuleDef __pyx_moduledef = + #else + static struct PyModuleDef __pyx_moduledef = + #endif + { + PyModuleDef_HEAD_INIT, + "cybase", + 0, /* m_doc */ + #if CYTHON_USE_MODULE_STATE + sizeof(__pyx_mstatetype), /* m_size */ + #else + (CYTHON_PEP489_MULTI_PHASE_INIT) ? 0 : -1, /* m_size */ + #endif + __pyx_methods /* m_methods */, + #if CYTHON_PEP489_MULTI_PHASE_INIT + __pyx_moduledef_slots, /* m_slots */ + #else + NULL, /* m_reload */ + #endif + #if CYTHON_USE_MODULE_STATE + __pyx_m_traverse, /* m_traverse */ + __pyx_m_clear, /* m_clear */ + NULL /* m_free */ + #else + NULL, /* m_traverse */ + NULL, /* m_clear */ + NULL /* m_free */ + #endif + }; + #ifdef __cplusplus +} /* anonymous namespace */ +#endif + +/* PyModInitFuncType */ +#ifndef CYTHON_NO_PYINIT_EXPORT + #define __Pyx_PyMODINIT_FUNC PyMODINIT_FUNC +#else + #ifdef __cplusplus + #define __Pyx_PyMODINIT_FUNC extern "C" PyObject * + #else + #define __Pyx_PyMODINIT_FUNC PyObject * + #endif +#endif + +__Pyx_PyMODINIT_FUNC PyInit_cybase(void) CYTHON_SMALL_CODE; /*proto*/ +__Pyx_PyMODINIT_FUNC PyInit_cybase(void) +#if CYTHON_PEP489_MULTI_PHASE_INIT +{ + return PyModuleDef_Init(&__pyx_moduledef); +} +/* ModuleCreationPEP489 */ +#if CYTHON_COMPILING_IN_LIMITED_API && (__PYX_LIMITED_VERSION_HEX < 0x03090000\ + || ((defined(_WIN32) || defined(WIN32) || defined(MS_WINDOWS)) && __PYX_LIMITED_VERSION_HEX < 0x030A0000)) +static PY_INT64_T __Pyx_GetCurrentInterpreterId(void) { + { + PyObject *module = PyImport_ImportModule("_interpreters"); // 3.13+ I think + if (!module) { + PyErr_Clear(); // just try the 3.8-3.12 version + module = PyImport_ImportModule("_xxsubinterpreters"); + if (!module) goto bad; + } + PyObject *current = PyObject_CallMethod(module, "get_current", NULL); + Py_DECREF(module); + if (!current) goto bad; + if (PyTuple_Check(current)) { + PyObject *new_current = PySequence_GetItem(current, 0); + Py_DECREF(current); + current = new_current; + if (!new_current) goto bad; + } + long long as_c_int = PyLong_AsLongLong(current); + Py_DECREF(current); + return as_c_int; + } + bad: + PySys_WriteStderr("__Pyx_GetCurrentInterpreterId failed. Try setting the C define CYTHON_PEP489_MULTI_PHASE_INIT=0\n"); + return -1; +} +#endif +#if !CYTHON_USE_MODULE_STATE +static CYTHON_SMALL_CODE int __Pyx_check_single_interpreter(void) { + static PY_INT64_T main_interpreter_id = -1; +#if CYTHON_COMPILING_IN_GRAAL && defined(GRAALPY_VERSION_NUM) && GRAALPY_VERSION_NUM > 0x19000000 + PY_INT64_T current_id = GraalPyInterpreterState_GetIDFromThreadState(PyThreadState_Get()); +#elif CYTHON_COMPILING_IN_GRAAL + PY_INT64_T current_id = PyInterpreterState_GetIDFromThreadState(PyThreadState_Get()); +#elif CYTHON_COMPILING_IN_LIMITED_API && (__PYX_LIMITED_VERSION_HEX < 0x03090000\ + || ((defined(_WIN32) || defined(WIN32) || defined(MS_WINDOWS)) && __PYX_LIMITED_VERSION_HEX < 0x030A0000)) + PY_INT64_T current_id = __Pyx_GetCurrentInterpreterId(); +#elif CYTHON_COMPILING_IN_LIMITED_API + PY_INT64_T current_id = PyInterpreterState_GetID(PyInterpreterState_Get()); +#else + PY_INT64_T current_id = PyInterpreterState_GetID(PyThreadState_Get()->interp); +#endif + if (unlikely(current_id == -1)) { + return -1; + } + if (main_interpreter_id == -1) { + main_interpreter_id = current_id; + return 0; + } else if (unlikely(main_interpreter_id != current_id)) { + PyErr_SetString( + PyExc_ImportError, + "Interpreter change detected - this module can only be loaded into one interpreter per process."); + return -1; + } + return 0; +} +#endif +static CYTHON_SMALL_CODE int __Pyx_copy_spec_to_module(PyObject *spec, PyObject *moddict, const char* from_name, const char* to_name, int allow_none) +{ + PyObject *value = PyObject_GetAttrString(spec, from_name); + int result = 0; + if (likely(value)) { + if (allow_none || value != Py_None) { + result = PyDict_SetItemString(moddict, to_name, value); + } + Py_DECREF(value); + } else if (PyErr_ExceptionMatches(PyExc_AttributeError)) { + PyErr_Clear(); + } else { + result = -1; + } + return result; +} +static CYTHON_SMALL_CODE PyObject* __pyx_pymod_create(PyObject *spec, PyModuleDef *def) { + PyObject *module = NULL, *moddict, *modname; + CYTHON_UNUSED_VAR(def); + #if !CYTHON_USE_MODULE_STATE + if (__Pyx_check_single_interpreter()) + return NULL; + #endif + if (__pyx_m) + return __Pyx_NewRef(__pyx_m); + modname = PyObject_GetAttrString(spec, "name"); + if (unlikely(!modname)) goto bad; + module = PyModule_NewObject(modname); + Py_DECREF(modname); + if (unlikely(!module)) goto bad; + moddict = PyModule_GetDict(module); + if (unlikely(!moddict)) goto bad; + if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "loader", "__loader__", 1) < 0)) goto bad; + if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "origin", "__file__", 1) < 0)) goto bad; + if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "parent", "__package__", 1) < 0)) goto bad; + if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "submodule_search_locations", "__path__", 0) < 0)) goto bad; + return module; +bad: + Py_XDECREF(module); + return NULL; +} + + +static CYTHON_SMALL_CODE int __pyx_pymod_exec_cybase(PyObject *__pyx_pyinit_module) +#endif +{ + int stringtab_initialized = 0; + #if CYTHON_USE_MODULE_STATE + int pystate_addmodule_run = 0; + #endif + __pyx_mstatetype *__pyx_mstate = NULL; + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannyDeclarations + #if CYTHON_PEP489_MULTI_PHASE_INIT + if (__pyx_m) { + if (__pyx_m == __pyx_pyinit_module) return 0; + PyErr_SetString(PyExc_RuntimeError, "Module 'cybase' has already been imported. Re-initialisation is not supported."); + return -1; + } + #else + if (__pyx_m) return __Pyx_NewRef(__pyx_m); + #endif + /*--- Module creation code ---*/ + #if CYTHON_PEP489_MULTI_PHASE_INIT + __pyx_t_1 = __pyx_pyinit_module; + Py_INCREF(__pyx_t_1); + #else + __pyx_t_1 = PyModule_Create(&__pyx_moduledef); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1, __pyx_L1_error) + #endif + #if CYTHON_USE_MODULE_STATE + { + int add_module_result = __Pyx_State_AddModule(__pyx_t_1, &__pyx_moduledef); + __pyx_t_1 = 0; /* transfer ownership from __pyx_t_1 to "cybase" pseudovariable */ + if (unlikely((add_module_result < 0))) __PYX_ERR(0, 1, __pyx_L1_error) + pystate_addmodule_run = 1; + } + #else + __pyx_m = __pyx_t_1; + #endif + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + PyUnstable_Module_SetGIL(__pyx_m, Py_MOD_GIL_NOT_USED); + #endif + __pyx_mstate = __pyx_mstate_global; + CYTHON_UNUSED_VAR(__pyx_t_1); + __pyx_mstate->__pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_mstate->__pyx_d)) __PYX_ERR(0, 1, __pyx_L1_error) + Py_INCREF(__pyx_mstate->__pyx_d); + __pyx_mstate->__pyx_b = __Pyx_PyImport_AddModuleRef(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_mstate->__pyx_b)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_mstate->__pyx_cython_runtime = __Pyx_PyImport_AddModuleRef("cython_runtime"); if (unlikely(!__pyx_mstate->__pyx_cython_runtime)) __PYX_ERR(0, 1, __pyx_L1_error) + if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_mstate->__pyx_b) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + /* ImportRefnannyAPI */ + #if CYTHON_REFNANNY + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); + if (!__Pyx_RefNanny) { + PyErr_Clear(); + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); + if (!__Pyx_RefNanny) + Py_FatalError("failed to import 'refnanny' module"); + } + #endif + +__Pyx_RefNannySetupContext("PyInit_cybase", 0); + __Pyx_init_runtime_version(); + if (__Pyx_check_binary_version(__PYX_LIMITED_VERSION_HEX, __Pyx_get_runtime_version(), CYTHON_COMPILING_IN_LIMITED_API) < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_mstate->__pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_mstate->__pyx_empty_tuple)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_mstate->__pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_mstate->__pyx_empty_bytes)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_mstate->__pyx_empty_unicode = PyUnicode_FromStringAndSize("", 0); if (unlikely(!__pyx_mstate->__pyx_empty_unicode)) __PYX_ERR(0, 1, __pyx_L1_error) + /*--- Library function declarations ---*/ + /*--- Initialize various global constants etc. ---*/ + if (__Pyx_InitConstants(__pyx_mstate) < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + stringtab_initialized = 1; + if (__Pyx_InitGlobals() < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + if (__pyx_module_is_main_thriftpy2__transport__cybase) { + if (PyObject_SetAttr(__pyx_m, __pyx_mstate_global->__pyx_n_u_name, __pyx_mstate_global->__pyx_n_u_main) < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + } + { + PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) __PYX_ERR(0, 1, __pyx_L1_error) + if (!PyDict_GetItemString(modules, "thriftpy2.transport.cybase")) { + if (unlikely((PyDict_SetItemString(modules, "thriftpy2.transport.cybase", __pyx_m) < 0))) __PYX_ERR(0, 1, __pyx_L1_error) + } + } + /*--- Builtin init code ---*/ + if (__Pyx_InitCachedBuiltins(__pyx_mstate) < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + /*--- Constants init code ---*/ + if (__Pyx_InitCachedConstants(__pyx_mstate) < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + if (__Pyx_CreateCodeObjects(__pyx_mstate) < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + /*--- Global type/function init code ---*/ + (void)__Pyx_modinit_global_init_code(__pyx_mstate); + (void)__Pyx_modinit_variable_export_code(__pyx_mstate); + (void)__Pyx_modinit_function_export_code(__pyx_mstate); + if (unlikely((__Pyx_modinit_type_init_code(__pyx_mstate) < 0))) __PYX_ERR(0, 1, __pyx_L1_error) + (void)__Pyx_modinit_type_import_code(__pyx_mstate); + (void)__Pyx_modinit_variable_import_code(__pyx_mstate); + (void)__Pyx_modinit_function_import_code(__pyx_mstate); + /*--- Execution code ---*/ + + /* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" + * def __setstate_cython__(self, __pyx_state): +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_9transport_6cybase_9TCyBuffer_5__reduce_cython__, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_TCyBuffer___reduce_cython, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_transport_cybase, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[0])); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 1, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_2); + #endif + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_reduce_cython, __pyx_t_2) < (0)) __PYX_ERR(1, 1, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "(tree fragment)":3 + * def __reduce_cython__(self): + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_9transport_6cybase_9TCyBuffer_7__setstate_cython__, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_TCyBuffer___setstate_cython, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_transport_cybase, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[1])); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 3, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_2); + #endif + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_setstate_cython, __pyx_t_2) < (0)) __PYX_ERR(1, 3, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/transport/cybase.pyx":117 + * pass + * + * def clean(self): # <<<<<<<<<<<<<< + * pass + * +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_9transport_6cybase_15CyTransportBase_1clean, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_CyTransportBase_clean, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_transport_cybase, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[2])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 117, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_2); + #endif + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase, __pyx_mstate_global->__pyx_n_u_clean, __pyx_t_2) < (0)) __PYX_ERR(0, 117, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * cdef tuple state + * cdef object _dict +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_9transport_6cybase_15CyTransportBase_3__reduce_cython__, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_CyTransportBase___reduce_cython, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_transport_cybase, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[3])); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 1, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_2); + #endif + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase, __pyx_mstate_global->__pyx_n_u_reduce_cython, __pyx_t_2) < (0)) __PYX_ERR(1, 1, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "(tree fragment)":16 + * else: + * return __pyx_unpickle_CyTransportBase, (type(self), 0xcbd31fe, state) + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * __pyx_unpickle_CyTransportBase__set_state(self, __pyx_state) +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_9transport_6cybase_15CyTransportBase_5__setstate_cython__, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_CyTransportBase___setstate_cytho, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_transport_cybase, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[4])); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 16, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_2); + #endif + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase, __pyx_mstate_global->__pyx_n_u_setstate_cython, __pyx_t_2) < (0)) __PYX_ERR(1, 16, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "(tree fragment)":4 + * int __Pyx_CheckUnpickleChecksum(long, long, long, long, const char*) except -1 + * int __Pyx_UpdateUnpickledDict(object, object, Py_ssize_t) except -1 + * def __pyx_unpickle_CyTransportBase(__pyx_type, long __pyx_checksum, tuple __pyx_state): # <<<<<<<<<<<<<< + * cdef object __pyx_result + * __Pyx_CheckUnpickleChecksum(__pyx_checksum, 0xcbd31fe, 0x2c17e4d, 0x4738019, b'trans') +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_9transport_6cybase_1__pyx_unpickle_CyTransportBase, 0, __pyx_mstate_global->__pyx_n_u_pyx_unpickle_CyTransportBase, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_transport_cybase, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[5])); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 4, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_2); + #endif + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_pyx_unpickle_CyTransportBase, __pyx_t_2) < (0)) __PYX_ERR(1, 4, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/transport/cybase.pyx":1 + * # cython: freethreading_compatible = True # <<<<<<<<<<<<<< + * + * from libc.stdlib cimport malloc, free +*/ + __pyx_t_2 = __Pyx_PyDict_NewPresized(0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_test, __pyx_t_2) < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /*--- Wrapped vars code ---*/ + + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + if (__pyx_m) { + if (__pyx_mstate->__pyx_d && stringtab_initialized) { + __Pyx_AddTraceback("init thriftpy2.transport.cybase", __pyx_clineno, __pyx_lineno, __pyx_filename); + } + #if !CYTHON_USE_MODULE_STATE + Py_CLEAR(__pyx_m); + #else + Py_DECREF(__pyx_m); + if (pystate_addmodule_run) { + PyObject *tp, *value, *tb; + PyErr_Fetch(&tp, &value, &tb); + PyState_RemoveModule(&__pyx_moduledef); + PyErr_Restore(tp, value, tb); + } + #endif + } else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_ImportError, "init thriftpy2.transport.cybase"); + } + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + #if CYTHON_PEP489_MULTI_PHASE_INIT + return (__pyx_m != NULL) ? 0 : -1; + #else + return __pyx_m; + #endif +} +/* #### Code section: pystring_table ### */ +/* #### Code section: cached_builtins ### */ + +static int __Pyx_InitCachedBuiltins(__pyx_mstatetype *__pyx_mstate) { + CYTHON_UNUSED_VAR(__pyx_mstate); + + /* Cached unbound methods */ + __pyx_mstate->__pyx_umethod_PyDict_Type_items.type = (PyObject*)&PyDict_Type; + __pyx_mstate->__pyx_umethod_PyDict_Type_items.method_name = &__pyx_mstate->__pyx_n_u_items; + __pyx_mstate->__pyx_umethod_PyDict_Type_pop.type = (PyObject*)&PyDict_Type; + __pyx_mstate->__pyx_umethod_PyDict_Type_pop.method_name = &__pyx_mstate->__pyx_n_u_pop; + __pyx_mstate->__pyx_umethod_PyDict_Type_values.type = (PyObject*)&PyDict_Type; + __pyx_mstate->__pyx_umethod_PyDict_Type_values.method_name = &__pyx_mstate->__pyx_n_u_values; + return 0; +} +/* #### Code section: cached_constants ### */ + +static int __Pyx_InitCachedConstants(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); + __Pyx_RefNannyFinishContext(); + return 0; +} +/* #### Code section: init_constants ### */ + +static int __Pyx_InitConstants(__pyx_mstatetype *__pyx_mstate) { + CYTHON_UNUSED_VAR(__pyx_mstate); + { + const struct { const unsigned int length: 8; } index[] = {{1},{179},{8},{7},{6},{2},{9},{50},{14},{30},{15},{33},{35},{21},{20},{9},{27},{29},{18},{8},{5},{18},{8},{5},{8},{12},{13},{5},{8},{10},{8},{7},{3},{14},{12},{11},{10},{30},{14},{12},{4},{10},{17},{13},{4},{12},{10},{12},{19},{4},{5},{8},{26},{6},{12},{6},{2},{9},{11},{97},{57}}; + #if (CYTHON_COMPRESS_STRINGS) == 2 /* compression: bz2 (743 bytes) */ +const char* const cstring = "BZh91AY&SY_\225R\216\000\000@\377\377\346\335\274\200\340\317\364\315\277\251|\200\277\377\377\364@@@@@@@@@@@@@\000@\000@\002} \000\220\322)\351\251\250\363T\362Oi@\365\000\036\240h\001\246\203@6\215M=@i\352oI\2248\320\3204i\221\246\2152\003\023\004\000\003@h\r2\003\002d\034hh\0324\310\323F\231\001\211\202\000\001\2404\006\231\001\2012\004\240\201\023\010\323 \246\322\032\236\220\321\247\251\204\332\231\006\201\220\030\232bz=\023$| \177\301\360D\351]\344\250\235Q\212*\271\025\257\250\254\207F\367\227;\r\373O\327\351\371}>\210Y\274\237\250\363[\373i\243J\211\320?\036v\261\302R\342\326\277m\352\005\010\223#9Jx\3060\260\371\355\034\333\201N\275\025\205\210\255\363\246\010\261\304\375\264\307\254P\020Q`*\355\206\032\006\241\211\304\032\023\345\n\375\364\335\214\rT\327\223\350\363\3728i\307\202\031\315D\0012\253'\020w\342\007\003\326\320\005X+h\346\224W\344\350\337\2765\005>\216B\335\021\224\013]\354\222\331\001\030UU!F\004\212\211\n3\2516U$\323\\9\251]\236\376OWEI\276\206\216\375\210\236\244\265E\307\3544\325\202$\362c#\301\325w\t\244\307\2346i\306\331\t\033\310r\275<9\261:\315:<\202\007\235\340$aM:\232\354Vb\310\005\263(\355\317\202\035\205\330\313\271ZIlb<\025E\026\370e2\025\364\303\341}S\200\2257kH\317\014\320\221[\321\367&\310\027\325\032\263\3046\252\020#\227>[\355\317[\027#'\001O\246\271~mbkQ\r\271\260\367\3521K\247\272\3529IV=7M\241e\322\236O\020\356\330\307n\355\256*Hh\220LZ\017k\246\2306\266\223#\253**\271\014%>*\024\301I\252>\020\302\224\212&\020Rz;\024\335%\0229h\025\022\034\013}Z\2155\335\022K|\321.;.&\032\3719{\273\002\211\312\203[V*\025\227\264\362\024\320\201*=\354j\200\332\315\252\026W\031\231\235\013\026Jqd\210\351]\204w0S\377R0\223-\255\261\023\352\335z\221/\227e\200\322\353R\"\254\347s\226\007\002#\363f\304\224\346\234d\370{w\037|\357\022T]\331\372hq\242_\332\344E|\361U\317]\225\252\213\210\374O\307\250\034\300\214\255\241\210\272\214AaK\324$ \022R`Jw\025\254\303\271x\257\313\353\203^\314\314\253\346\251?\260\213\264yh\376\316\211Y#\031\311\247A?\301""\204j\215(G\236:D\323\210\351\360\276~\227\251\251\023Vmz\207\244\033\342.\344\212p\241 \277*\245\034"; + PyObject *data = __Pyx_DecompressString(cstring, 743, 2); + if (unlikely(!data)) __PYX_ERR(0, 1, __pyx_L1_error) + const char* const bytes = __Pyx_PyBytes_AsString(data); + #if !CYTHON_ASSUME_SAFE_MACROS + if (likely(bytes)); else { Py_DECREF(data); __PYX_ERR(0, 1, __pyx_L1_error) } + #endif + #elif (CYTHON_COMPRESS_STRINGS) != 0 /* compression: zlib (642 bytes) */ +const char* const cstring = "x\332uR\277o\0231\024\246R\020\021ET\005$F\334\251H\320\264\251*\025\tD\325\237\010!UM\251\324\321\362\371\336%&\027\373\342\037i\0161d\314xc\306\216\0313v\354\310\230\361\306\376\t\374\t<\347\232P\0328\351\354\347\347\317\337\347\367\371\355\034+\013\3046\230%\373\251m(I\204!!\304\"\000\315,\304)1V\013nA{\220$'\207'k[\357\266\010\223!\321\360\r\2705\304\270\200\307\314\0300DE$p\"\266B\022\233&`*\344sDR\345\210\004\010\211U$A\334\335\003\266\001\222\030\260> \253LJe\231\025JR<.d}\225\204B\243\210\350\200?}\304b\003\025\026\206\024q\020\n\303\202\030@\372\261\316\205)\242P*\254 b.\266\204R\r\241\343@)\t\335\204B*\271\206\025u\004\213q\227\013),\245\037|\221\262n\224\323\034>\332\206\026\221M\322\315u\253\2314\211\322v\235\247\001C\351$\355\356\247g\323\354\036\246\356-+3E>\261\223\322y\000\226k\260\312\377Cx\014\014\323'i\027\377\003t\237\036C\327\236Bt\266\237\356\271(\002=\013\346\365\356n\315)1\223J.T\205+\255\034\276\022\230\300E\324\210\3570\321\3441\246\250@\3675\343\0200\336\2444\364\372\323)r\222\343\202\326\247\304\224\nCgl\302B\313P\332bH\201_K\205.\366\030*Y\253\230\341\202\322D%8`q\274\001\274i\\\253Xi0\370dE|K\356C\337GE\344d\"x\023\t\357\371U\354v\254\177|/\322v,.\0045\260\360O\013\314Y5K@\327{\025G\023\307n/\213\321m\027\335\361\221\376\303S\243\260\210b\327\202A\364\254\177*\263\376\251\024\375\343\222\020q\016\257\036\237~\315K\213\375\352o!r\250c"; + PyObject *data = __Pyx_DecompressString(cstring, 642, 1); + if (unlikely(!data)) __PYX_ERR(0, 1, __pyx_L1_error) + const char* const bytes = __Pyx_PyBytes_AsString(data); + #if !CYTHON_ASSUME_SAFE_MACROS + if (likely(bytes)); else { Py_DECREF(data); __PYX_ERR(0, 1, __pyx_L1_error) } + #endif + #else /* compression: none (1078 bytes) */ +const char* const bytes = "?Note that Cython is deliberately stricter than PEP-484 and rejects subclasses of builtin types. If you need to pass subclasses then set the 'annotation_typing' directive to False.add_notedisableenablegcisenabledno default __reduce__ due to non-trivial __cinit__thriftpy2/transport/cybase.pyxCyTransportBaseCyTransportBase.__reduce_cython__CyTransportBase.__setstate_cython__CyTransportBase.clean__Pyx_PyDict_NextRefTCyBufferTCyBuffer.__reduce_cython__TCyBuffer.__setstate_cython__asyncio.coroutinesbuf_sizecleancline_in_traceback__dict___dict__func____getstate___is_coroutineitems__main____module____name____new__pop__pyx_checksum__pyx_result__pyx_state__pyx_type__pyx_unpickle_CyTransportBase__pyx_vtable____qualname__read__reduce____reduce_cython____reduce_ex__self__set_name__setdefault__setstate____setstate_cython__sockstate__test__thriftpy2.transport.cybaseupdateuse_setstatevalues\200A\200\001\330\004\n\210+\220Q\200\001\330\004-\250Q\250f\260A\200\001\360\010\000\005\016\210T\220\021\330\004\014\210G\2201\220F\230,\240a\330\004\007\200v\210W\220E\230\024\230Q\330\010\022\220!\330\010\027\220q\340\010\027\220t\2307\240'\250\021\330\004\007\200q\330\010\017\320\0170\260\004\260A\260W\270K\300w\310a\340\010\017\320\0170\260\004\260A\260W\270K\300q\200\001\340\004\037\230q\320 0\260\013\270;\300k\320QR\330\004\023\220?\240(\250!\2501\330\004\007\200|\2207\230!\330\0101\260\021\3202D\300N\320RS\330\004\013\2101"; + PyObject *data = NULL; + CYTHON_UNUSED_VAR(__Pyx_DecompressString); + #endif + PyObject **stringtab = __pyx_mstate->__pyx_string_tab; + Py_ssize_t pos = 0; + for (int i = 0; i < 56; i++) { + Py_ssize_t bytes_length = index[i].length; + PyObject *string = PyUnicode_DecodeUTF8(bytes + pos, bytes_length, NULL); + if (likely(string) && i >= 10) PyUnicode_InternInPlace(&string); + if (unlikely(!string)) { + Py_XDECREF(data); + __PYX_ERR(0, 1, __pyx_L1_error) + } + stringtab[i] = string; + pos += bytes_length; + } + for (int i = 56; i < 61; i++) { + Py_ssize_t bytes_length = index[i].length; + PyObject *string = PyBytes_FromStringAndSize(bytes + pos, bytes_length); + stringtab[i] = string; + pos += bytes_length; + if (unlikely(!string)) { + Py_XDECREF(data); + __PYX_ERR(0, 1, __pyx_L1_error) + } + } + Py_XDECREF(data); + for (Py_ssize_t i = 0; i < 61; i++) { + if (unlikely(PyObject_Hash(stringtab[i]) == -1)) { + __PYX_ERR(0, 1, __pyx_L1_error) + } + } + #if CYTHON_IMMORTAL_CONSTANTS + { + PyObject **table = stringtab + 56; + for (Py_ssize_t i=0; i<5; ++i) { + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + #if PY_VERSION_HEX < 0x030E0000 + if (_Py_IsOwnedByCurrentThread(table[i]) && Py_REFCNT(table[i]) == 1) + #else + if (PyUnstable_Object_IsUniquelyReferenced(table[i])) + #endif + { + Py_SET_REFCNT(table[i], _Py_IMMORTAL_REFCNT_LOCAL); + } + #else + Py_SET_REFCNT(table[i], _Py_IMMORTAL_INITIAL_REFCNT); + #endif + } + } + #endif + } + { + PyObject **numbertab = __pyx_mstate->__pyx_number_tab + 0; + int8_t const cint_constants_1[] = {0,-1,-2}; + int32_t const cint_constants_4[] = {213725694L}; + for (int i = 0; i < 4; i++) { + numbertab[i] = PyLong_FromLong((i < 3 ? cint_constants_1[i - 0] : cint_constants_4[i - 3])); + if (unlikely(!numbertab[i])) __PYX_ERR(0, 1, __pyx_L1_error) + } + } + #if CYTHON_IMMORTAL_CONSTANTS + { + PyObject **table = __pyx_mstate->__pyx_number_tab; + for (Py_ssize_t i=0; i<4; ++i) { + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + #if PY_VERSION_HEX < 0x030E0000 + if (_Py_IsOwnedByCurrentThread(table[i]) && Py_REFCNT(table[i]) == 1) + #else + if (PyUnstable_Object_IsUniquelyReferenced(table[i])) + #endif + { + Py_SET_REFCNT(table[i], _Py_IMMORTAL_REFCNT_LOCAL); + } + #else + Py_SET_REFCNT(table[i], _Py_IMMORTAL_INITIAL_REFCNT); + #endif + } + } + #endif + return 0; + __pyx_L1_error:; + return -1; +} +/* #### Code section: init_codeobjects ### */ +typedef struct { + unsigned int argcount : 2; + unsigned int num_posonly_args : 1; + unsigned int num_kwonly_args : 1; + unsigned int nlocals : 3; + unsigned int flags : 10; + unsigned int first_line : 7; +} __Pyx_PyCode_New_function_description; +/* NewCodeObj.proto */ +static PyObject* __Pyx_PyCode_New( + const __Pyx_PyCode_New_function_description descr, + PyObject * const *varnames, + PyObject *filename, + PyObject *funcname, + PyObject *line_table, + PyObject *tuple_dedup_map +); + + +static int __Pyx_CreateCodeObjects(__pyx_mstatetype *__pyx_mstate) { + PyObject* tuple_dedup_map = PyDict_New(); + if (unlikely(!tuple_dedup_map)) return -1; + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 1}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[0] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_stringsource, __pyx_mstate->__pyx_n_u_reduce_cython, __pyx_mstate->__pyx_kp_b_iso88591_Q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[0])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 3}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_pyx_state}; + __pyx_mstate_global->__pyx_codeobj_tab[1] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_stringsource, __pyx_mstate->__pyx_n_u_setstate_cython, __pyx_mstate->__pyx_kp_b_iso88591_Q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[1])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 117}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[2] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_thriftpy2_transport_cybase_pyx, __pyx_mstate->__pyx_n_u_clean, __pyx_mstate->__pyx_kp_b_iso88591_A, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[2])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 4, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 1}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_state, __pyx_mstate->__pyx_n_u_dict_2, __pyx_mstate->__pyx_n_u_use_setstate}; + __pyx_mstate_global->__pyx_codeobj_tab[3] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_stringsource, __pyx_mstate->__pyx_n_u_reduce_cython, __pyx_mstate->__pyx_kp_b_iso88591_T_G1F_a_vWE_Q_q_t7_q_0_AWKwa_0, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[3])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 16}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_pyx_state}; + __pyx_mstate_global->__pyx_codeobj_tab[4] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_stringsource, __pyx_mstate->__pyx_n_u_setstate_cython, __pyx_mstate->__pyx_kp_b_iso88591_QfA, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[4])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {3, 0, 0, 4, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 4}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_pyx_type, __pyx_mstate->__pyx_n_u_pyx_checksum, __pyx_mstate->__pyx_n_u_pyx_state, __pyx_mstate->__pyx_n_u_pyx_result}; + __pyx_mstate_global->__pyx_codeobj_tab[5] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_stringsource, __pyx_mstate->__pyx_n_u_pyx_unpickle_CyTransportBase, __pyx_mstate->__pyx_kp_b_iso88591_q_0_kQR_1_7_1_2DNRS_1, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[5])) goto bad; + } + Py_DECREF(tuple_dedup_map); + return 0; + bad: + Py_DECREF(tuple_dedup_map); + return -1; +} +/* #### Code section: init_globals ### */ + +static int __Pyx_InitGlobals(void) { + /* PythonCompatibility.init */ + if (likely(__Pyx_init_co_variables() == 0)); else + + if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 1, __pyx_L1_error) + + /* CommonTypesMetaclass.init */ + if (likely(__pyx_CommonTypesMetaclass_init(__pyx_m) == 0)); else + + if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 1, __pyx_L1_error) + + /* CachedMethodType.init */ + #if CYTHON_COMPILING_IN_LIMITED_API + { + PyObject *typesModule=NULL; + typesModule = PyImport_ImportModule("types"); + if (typesModule) { + __pyx_mstate_global->__Pyx_CachedMethodType = PyObject_GetAttrString(typesModule, "MethodType"); + Py_DECREF(typesModule); + } + } // error handling follows + #endif + + if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 1, __pyx_L1_error) + + /* CythonFunctionShared.init */ + if (likely(__pyx_CyFunction_init(__pyx_m) == 0)); else + + if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 1, __pyx_L1_error) + + return 0; + __pyx_L1_error:; + return -1; +} +/* #### Code section: cleanup_globals ### */ +/* #### Code section: cleanup_module ### */ +/* #### Code section: main_method ### */ +/* #### Code section: utility_code_pragmas ### */ +#ifdef _MSC_VER +#pragma warning( push ) +/* Warning 4127: conditional expression is constant + * Cython uses constant conditional expressions to allow in inline functions to be optimized at + * compile-time, so this warning is not useful + */ +#pragma warning( disable : 4127 ) +#endif + + + +/* #### Code section: utility_code_def ### */ + +/* --- Runtime support code --- */ +/* Refnanny */ +#if CYTHON_REFNANNY +static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { + PyObject *m = NULL, *p = NULL; + void *r = NULL; + m = PyImport_ImportModule(modname); + if (!m) goto end; + p = PyObject_GetAttrString(m, "RefNannyAPI"); + if (!p) goto end; + r = PyLong_AsVoidPtr(p); +end: + Py_XDECREF(p); + Py_XDECREF(m); + return (__Pyx_RefNannyAPIStruct *)r; +} +#endif + +/* TupleAndListFromArray (used by fastcall) */ +#if !CYTHON_COMPILING_IN_CPYTHON && CYTHON_METH_FASTCALL +static CYTHON_INLINE PyObject * +__Pyx_PyTuple_FromArray(PyObject *const *src, Py_ssize_t n) +{ + PyObject *res; + Py_ssize_t i; + if (n <= 0) { + return __Pyx_NewRef(__pyx_mstate_global->__pyx_empty_tuple); + } + res = PyTuple_New(n); + if (unlikely(res == NULL)) return NULL; + for (i = 0; i < n; i++) { + if (unlikely(__Pyx_PyTuple_SET_ITEM(res, i, src[i]) < (0))) { + Py_DECREF(res); + return NULL; + } + Py_INCREF(src[i]); + } + return res; +} +#elif CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE void __Pyx_copy_object_array(PyObject *const *CYTHON_RESTRICT src, PyObject** CYTHON_RESTRICT dest, Py_ssize_t length) { + PyObject *v; + Py_ssize_t i; + for (i = 0; i < length; i++) { + v = dest[i] = src[i]; + Py_INCREF(v); + } +} +static CYTHON_INLINE PyObject * +__Pyx_PyTuple_FromArray(PyObject *const *src, Py_ssize_t n) +{ + PyObject *res; + if (n <= 0) { + return __Pyx_NewRef(__pyx_mstate_global->__pyx_empty_tuple); + } + res = PyTuple_New(n); + if (unlikely(res == NULL)) return NULL; + __Pyx_copy_object_array(src, ((PyTupleObject*)res)->ob_item, n); + return res; +} +static CYTHON_INLINE PyObject * +__Pyx_PyList_FromArray(PyObject *const *src, Py_ssize_t n) +{ + PyObject *res; + if (n <= 0) { + return PyList_New(0); + } + res = PyList_New(n); + if (unlikely(res == NULL)) return NULL; + __Pyx_copy_object_array(src, ((PyListObject*)res)->ob_item, n); + return res; +} +#endif + +/* BytesEquals (used by UnicodeEquals) */ +static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals) { +#if CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_GRAAL ||\ + !(CYTHON_ASSUME_SAFE_SIZE && CYTHON_ASSUME_SAFE_MACROS) + return PyObject_RichCompareBool(s1, s2, equals); +#else + if (s1 == s2) { + return (equals == Py_EQ); + } else if (PyBytes_CheckExact(s1) & PyBytes_CheckExact(s2)) { + const char *ps1, *ps2; + Py_ssize_t length = PyBytes_GET_SIZE(s1); + if (length != PyBytes_GET_SIZE(s2)) + return (equals == Py_NE); + ps1 = PyBytes_AS_STRING(s1); + ps2 = PyBytes_AS_STRING(s2); + if (ps1[0] != ps2[0]) { + return (equals == Py_NE); + } else if (length == 1) { + return (equals == Py_EQ); + } else { + int result; +#if CYTHON_USE_UNICODE_INTERNALS && (PY_VERSION_HEX < 0x030B0000) + Py_hash_t hash1, hash2; + hash1 = ((PyBytesObject*)s1)->ob_shash; + hash2 = ((PyBytesObject*)s2)->ob_shash; + if (hash1 != hash2 && hash1 != -1 && hash2 != -1) { + return (equals == Py_NE); + } +#endif + result = memcmp(ps1, ps2, (size_t)length); + return (equals == Py_EQ) ? (result == 0) : (result != 0); + } + } else if ((s1 == Py_None) & PyBytes_CheckExact(s2)) { + return (equals == Py_NE); + } else if ((s2 == Py_None) & PyBytes_CheckExact(s1)) { + return (equals == Py_NE); + } else { + int result; + PyObject* py_result = PyObject_RichCompare(s1, s2, equals); + if (!py_result) + return -1; + result = __Pyx_PyObject_IsTrue(py_result); + Py_DECREF(py_result); + return result; + } +#endif +} + +/* UnicodeEquals (used by fastcall) */ +static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals) { +#if CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_GRAAL + return PyObject_RichCompareBool(s1, s2, equals); +#else + int s1_is_unicode, s2_is_unicode; + if (s1 == s2) { + goto return_eq; + } + s1_is_unicode = PyUnicode_CheckExact(s1); + s2_is_unicode = PyUnicode_CheckExact(s2); + if (s1_is_unicode & s2_is_unicode) { + Py_ssize_t length, length2; + int kind; + void *data1, *data2; + #if !CYTHON_COMPILING_IN_LIMITED_API + if (unlikely(__Pyx_PyUnicode_READY(s1) < 0) || unlikely(__Pyx_PyUnicode_READY(s2) < 0)) + return -1; + #endif + length = __Pyx_PyUnicode_GET_LENGTH(s1); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(length < 0)) return -1; + #endif + length2 = __Pyx_PyUnicode_GET_LENGTH(s2); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(length2 < 0)) return -1; + #endif + if (length != length2) { + goto return_ne; + } +#if CYTHON_USE_UNICODE_INTERNALS + { + Py_hash_t hash1, hash2; + hash1 = ((PyASCIIObject*)s1)->hash; + hash2 = ((PyASCIIObject*)s2)->hash; + if (hash1 != hash2 && hash1 != -1 && hash2 != -1) { + goto return_ne; + } + } +#endif + kind = __Pyx_PyUnicode_KIND(s1); + if (kind != __Pyx_PyUnicode_KIND(s2)) { + goto return_ne; + } + data1 = __Pyx_PyUnicode_DATA(s1); + data2 = __Pyx_PyUnicode_DATA(s2); + if (__Pyx_PyUnicode_READ(kind, data1, 0) != __Pyx_PyUnicode_READ(kind, data2, 0)) { + goto return_ne; + } else if (length == 1) { + goto return_eq; + } else { + int result = memcmp(data1, data2, (size_t)(length * kind)); + return (equals == Py_EQ) ? (result == 0) : (result != 0); + } + } else if ((s1 == Py_None) & s2_is_unicode) { + goto return_ne; + } else if ((s2 == Py_None) & s1_is_unicode) { + goto return_ne; + } else { + int result; + PyObject* py_result = PyObject_RichCompare(s1, s2, equals); + if (!py_result) + return -1; + result = __Pyx_PyObject_IsTrue(py_result); + Py_DECREF(py_result); + return result; + } +return_eq: + return (equals == Py_EQ); +return_ne: + return (equals == Py_NE); +#endif +} + +/* fastcall */ +#if CYTHON_METH_FASTCALL +static CYTHON_INLINE PyObject * __Pyx_GetKwValue_FASTCALL(PyObject *kwnames, PyObject *const *kwvalues, PyObject *s) +{ + Py_ssize_t i, n = __Pyx_PyTuple_GET_SIZE(kwnames); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(n == -1)) return NULL; + #endif + for (i = 0; i < n; i++) + { + PyObject *namei = __Pyx_PyTuple_GET_ITEM(kwnames, i); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(!namei)) return NULL; + #endif + if (s == namei) return kwvalues[i]; + } + for (i = 0; i < n; i++) + { + PyObject *namei = __Pyx_PyTuple_GET_ITEM(kwnames, i); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(!namei)) return NULL; + #endif + int eq = __Pyx_PyUnicode_Equals(s, namei, Py_EQ); + if (unlikely(eq != 0)) { + if (unlikely(eq < 0)) return NULL; + return kwvalues[i]; + } + } + return NULL; +} +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030d0000 || CYTHON_COMPILING_IN_LIMITED_API +CYTHON_UNUSED static PyObject *__Pyx_KwargsAsDict_FASTCALL(PyObject *kwnames, PyObject *const *kwvalues) { + Py_ssize_t i, nkwargs; + PyObject *dict; +#if !CYTHON_ASSUME_SAFE_SIZE + nkwargs = PyTuple_Size(kwnames); + if (unlikely(nkwargs < 0)) return NULL; +#else + nkwargs = PyTuple_GET_SIZE(kwnames); +#endif + dict = PyDict_New(); + if (unlikely(!dict)) + return NULL; + for (i=0; itp_call; + if (unlikely(!call)) + return PyObject_Call(func, arg, kw); + if (unlikely(Py_EnterRecursiveCall(" while calling a Python object"))) + return NULL; + result = (*call)(func, arg, kw); + Py_LeaveRecursiveCall(); + if (unlikely(!result) && unlikely(!PyErr_Occurred())) { + PyErr_SetString( + PyExc_SystemError, + "NULL result without error in PyObject_Call"); + } + return result; +} +#endif + +/* PyObjectCallMethO (used by PyObjectFastCall) */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg) { + PyObject *self, *result; + PyCFunction cfunc; + cfunc = __Pyx_CyOrPyCFunction_GET_FUNCTION(func); + self = __Pyx_CyOrPyCFunction_GET_SELF(func); + if (unlikely(Py_EnterRecursiveCall(" while calling a Python object"))) + return NULL; + result = cfunc(self, arg); + Py_LeaveRecursiveCall(); + if (unlikely(!result) && unlikely(!PyErr_Occurred())) { + PyErr_SetString( + PyExc_SystemError, + "NULL result without error in PyObject_Call"); + } + return result; +} +#endif + +/* PyObjectFastCall (used by PyObjectCallOneArg) */ +#if PY_VERSION_HEX < 0x03090000 || CYTHON_COMPILING_IN_LIMITED_API +static PyObject* __Pyx_PyObject_FastCall_fallback(PyObject *func, PyObject * const*args, size_t nargs, PyObject *kwargs) { + PyObject *argstuple; + PyObject *result = 0; + size_t i; + argstuple = PyTuple_New((Py_ssize_t)nargs); + if (unlikely(!argstuple)) return NULL; + for (i = 0; i < nargs; i++) { + Py_INCREF(args[i]); + if (__Pyx_PyTuple_SET_ITEM(argstuple, (Py_ssize_t)i, args[i]) != (0)) goto bad; + } + result = __Pyx_PyObject_Call(func, argstuple, kwargs); + bad: + Py_DECREF(argstuple); + return result; +} +#endif +#if CYTHON_VECTORCALL && !CYTHON_COMPILING_IN_LIMITED_API + #if PY_VERSION_HEX < 0x03090000 + #define __Pyx_PyVectorcall_Function(callable) _PyVectorcall_Function(callable) + #elif CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE vectorcallfunc __Pyx_PyVectorcall_Function(PyObject *callable) { + PyTypeObject *tp = Py_TYPE(callable); + #if defined(__Pyx_CyFunction_USED) + if (__Pyx_CyFunction_CheckExact(callable)) { + return __Pyx_CyFunction_func_vectorcall(callable); + } + #endif + if (!PyType_HasFeature(tp, Py_TPFLAGS_HAVE_VECTORCALL)) { + return NULL; + } + assert(PyCallable_Check(callable)); + Py_ssize_t offset = tp->tp_vectorcall_offset; + assert(offset > 0); + vectorcallfunc ptr; + memcpy(&ptr, (char *) callable + offset, sizeof(ptr)); + return ptr; +} + #else + #define __Pyx_PyVectorcall_Function(callable) PyVectorcall_Function(callable) + #endif +#endif +static CYTHON_INLINE PyObject* __Pyx_PyObject_FastCallDict(PyObject *func, PyObject *const *args, size_t _nargs, PyObject *kwargs) { + Py_ssize_t nargs = __Pyx_PyVectorcall_NARGS(_nargs); +#if CYTHON_COMPILING_IN_CPYTHON + if (nargs == 0 && kwargs == NULL) { + if (__Pyx_CyOrPyCFunction_Check(func) && likely( __Pyx_CyOrPyCFunction_GET_FLAGS(func) & METH_NOARGS)) + return __Pyx_PyObject_CallMethO(func, NULL); + } + else if (nargs == 1 && kwargs == NULL) { + if (__Pyx_CyOrPyCFunction_Check(func) && likely( __Pyx_CyOrPyCFunction_GET_FLAGS(func) & METH_O)) + return __Pyx_PyObject_CallMethO(func, args[0]); + } +#endif + if (kwargs == NULL) { + #if CYTHON_VECTORCALL + #if CYTHON_COMPILING_IN_LIMITED_API + return PyObject_Vectorcall(func, args, _nargs, NULL); + #else + vectorcallfunc f = __Pyx_PyVectorcall_Function(func); + if (f) { + return f(func, args, _nargs, NULL); + } + #endif + #endif + } + if (nargs == 0) { + return __Pyx_PyObject_Call(func, __pyx_mstate_global->__pyx_empty_tuple, kwargs); + } + #if PY_VERSION_HEX >= 0x03090000 && !CYTHON_COMPILING_IN_LIMITED_API + return PyObject_VectorcallDict(func, args, (size_t)nargs, kwargs); + #else + return __Pyx_PyObject_FastCall_fallback(func, args, (size_t)nargs, kwargs); + #endif +} + +/* PyObjectCallOneArg (used by CallUnboundCMethod0) */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { + PyObject *args[2] = {NULL, arg}; + return __Pyx_PyObject_FastCall(func, args+1, 1 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET); +} + +/* PyObjectGetAttrStr (used by UnpackUnboundCMethod) */ +#if CYTHON_USE_TYPE_SLOTS +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { + PyTypeObject* tp = Py_TYPE(obj); + if (likely(tp->tp_getattro)) + return tp->tp_getattro(obj, attr_name); + return PyObject_GetAttr(obj, attr_name); +} +#endif + +/* UnpackUnboundCMethod (used by CallUnboundCMethod0) */ +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030C0000 +static PyObject *__Pyx_SelflessCall(PyObject *method, PyObject *args, PyObject *kwargs) { + PyObject *result; + PyObject *selfless_args = PyTuple_GetSlice(args, 1, PyTuple_Size(args)); + if (unlikely(!selfless_args)) return NULL; + result = PyObject_Call(method, selfless_args, kwargs); + Py_DECREF(selfless_args); + return result; +} +#elif CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX < 0x03090000 +static PyObject *__Pyx_SelflessCall(PyObject *method, PyObject **args, Py_ssize_t nargs, PyObject *kwnames) { + return _PyObject_Vectorcall + (method, args ? args+1 : NULL, nargs ? nargs-1 : 0, kwnames); +} +#else +static PyObject *__Pyx_SelflessCall(PyObject *method, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames) { + return +#if PY_VERSION_HEX < 0x03090000 + _PyObject_Vectorcall +#else + PyObject_Vectorcall +#endif + (method, args ? args+1 : NULL, nargs ? (size_t) nargs-1 : 0, kwnames); +} +#endif +static PyMethodDef __Pyx_UnboundCMethod_Def = { + "CythonUnboundCMethod", + __PYX_REINTERPRET_FUNCION(PyCFunction, __Pyx_SelflessCall), +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030C0000 + METH_VARARGS | METH_KEYWORDS, +#else + METH_FASTCALL | METH_KEYWORDS, +#endif + NULL +}; +static int __Pyx_TryUnpackUnboundCMethod(__Pyx_CachedCFunction* target) { + PyObject *method, *result=NULL; + method = __Pyx_PyObject_GetAttrStr(target->type, *target->method_name); + if (unlikely(!method)) + return -1; + result = method; +#if CYTHON_COMPILING_IN_CPYTHON + if (likely(__Pyx_TypeCheck(method, &PyMethodDescr_Type))) + { + PyMethodDescrObject *descr = (PyMethodDescrObject*) method; + target->func = descr->d_method->ml_meth; + target->flag = descr->d_method->ml_flags & ~(METH_CLASS | METH_STATIC | METH_COEXIST | METH_STACKLESS); + } else +#endif +#if CYTHON_COMPILING_IN_PYPY +#else + if (PyCFunction_Check(method)) +#endif + { + PyObject *self; + int self_found; +#if CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_PYPY + self = PyObject_GetAttrString(method, "__self__"); + if (!self) { + PyErr_Clear(); + } +#else + self = PyCFunction_GET_SELF(method); +#endif + self_found = (self && self != Py_None); +#if CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_PYPY + Py_XDECREF(self); +#endif + if (self_found) { + PyObject *unbound_method = PyCFunction_New(&__Pyx_UnboundCMethod_Def, method); + if (unlikely(!unbound_method)) return -1; + Py_DECREF(method); + result = unbound_method; + } + } +#if !CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + if (unlikely(target->method)) { + Py_DECREF(result); + } else +#endif + target->method = result; + return 0; +} + +/* CallUnboundCMethod0 */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_CallUnboundCMethod0(__Pyx_CachedCFunction* cfunc, PyObject* self) { + int was_initialized = __Pyx_CachedCFunction_GetAndSetInitializing(cfunc); + if (likely(was_initialized == 2 && cfunc->func)) { + if (likely(cfunc->flag == METH_NOARGS)) + return __Pyx_CallCFunction(cfunc, self, NULL); + if (likely(cfunc->flag == METH_FASTCALL)) + return __Pyx_CallCFunctionFast(cfunc, self, NULL, 0); + if (cfunc->flag == (METH_FASTCALL | METH_KEYWORDS)) + return __Pyx_CallCFunctionFastWithKeywords(cfunc, self, NULL, 0, NULL); + if (likely(cfunc->flag == (METH_VARARGS | METH_KEYWORDS))) + return __Pyx_CallCFunctionWithKeywords(cfunc, self, __pyx_mstate_global->__pyx_empty_tuple, NULL); + if (cfunc->flag == METH_VARARGS) + return __Pyx_CallCFunction(cfunc, self, __pyx_mstate_global->__pyx_empty_tuple); + return __Pyx__CallUnboundCMethod0(cfunc, self); + } +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + else if (unlikely(was_initialized == 1)) { + __Pyx_CachedCFunction tmp_cfunc = { +#ifndef __cplusplus + 0 +#endif + }; + tmp_cfunc.type = cfunc->type; + tmp_cfunc.method_name = cfunc->method_name; + return __Pyx__CallUnboundCMethod0(&tmp_cfunc, self); + } +#endif + PyObject *result = __Pyx__CallUnboundCMethod0(cfunc, self); + __Pyx_CachedCFunction_SetFinishedInitializing(cfunc); + return result; +} +#endif +static PyObject* __Pyx__CallUnboundCMethod0(__Pyx_CachedCFunction* cfunc, PyObject* self) { + PyObject *result; + if (unlikely(!cfunc->method) && unlikely(__Pyx_TryUnpackUnboundCMethod(cfunc) < 0)) return NULL; + result = __Pyx_PyObject_CallOneArg(cfunc->method, self); + return result; +} + +/* py_dict_items (used by OwnedDictNext) */ +static CYTHON_INLINE PyObject* __Pyx_PyDict_Items(PyObject* d) { + return __Pyx_CallUnboundCMethod0(&__pyx_mstate_global->__pyx_umethod_PyDict_Type_items, d); +} + +/* py_dict_values (used by OwnedDictNext) */ +static CYTHON_INLINE PyObject* __Pyx_PyDict_Values(PyObject* d) { + return __Pyx_CallUnboundCMethod0(&__pyx_mstate_global->__pyx_umethod_PyDict_Type_values, d); +} + +/* OwnedDictNext (used by ParseKeywordsImpl) */ +#if CYTHON_AVOID_BORROWED_REFS +static int __Pyx_PyDict_NextRef(PyObject *p, PyObject **ppos, PyObject **pkey, PyObject **pvalue) { + PyObject *next = NULL; + if (!*ppos) { + if (pvalue) { + PyObject *dictview = pkey ? __Pyx_PyDict_Items(p) : __Pyx_PyDict_Values(p); + if (unlikely(!dictview)) goto bad; + *ppos = PyObject_GetIter(dictview); + Py_DECREF(dictview); + } else { + *ppos = PyObject_GetIter(p); + } + if (unlikely(!*ppos)) goto bad; + } + next = PyIter_Next(*ppos); + if (!next) { + if (PyErr_Occurred()) goto bad; + return 0; + } + if (pkey && pvalue) { + *pkey = __Pyx_PySequence_ITEM(next, 0); + if (unlikely(*pkey)) goto bad; + *pvalue = __Pyx_PySequence_ITEM(next, 1); + if (unlikely(*pvalue)) goto bad; + Py_DECREF(next); + } else if (pkey) { + *pkey = next; + } else { + assert(pvalue); + *pvalue = next; + } + return 1; + bad: + Py_XDECREF(next); +#if !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d0000 + PyErr_FormatUnraisable("Exception ignored in __Pyx_PyDict_NextRef"); +#else + PyErr_WriteUnraisable(__pyx_mstate_global->__pyx_n_u_Pyx_PyDict_NextRef); +#endif + if (pkey) *pkey = NULL; + if (pvalue) *pvalue = NULL; + return 0; +} +#else // !CYTHON_AVOID_BORROWED_REFS +static int __Pyx_PyDict_NextRef(PyObject *p, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue) { + int result = PyDict_Next(p, ppos, pkey, pvalue); + if (likely(result == 1)) { + if (pkey) Py_INCREF(*pkey); + if (pvalue) Py_INCREF(*pvalue); + } + return result; +} +#endif + +/* RaiseDoubleKeywords (used by ParseKeywordsImpl) */ +static void __Pyx_RaiseDoubleKeywordsError( + const char* func_name, + PyObject* kw_name) +{ + PyErr_Format(PyExc_TypeError, + "%s() got multiple values for keyword argument '%U'", func_name, kw_name); +} + +/* CallUnboundCMethod2 */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject *__Pyx_CallUnboundCMethod2(__Pyx_CachedCFunction *cfunc, PyObject *self, PyObject *arg1, PyObject *arg2) { + int was_initialized = __Pyx_CachedCFunction_GetAndSetInitializing(cfunc); + if (likely(was_initialized == 2 && cfunc->func)) { + PyObject *args[2] = {arg1, arg2}; + if (cfunc->flag == METH_FASTCALL) { + return __Pyx_CallCFunctionFast(cfunc, self, args, 2); + } + if (cfunc->flag == (METH_FASTCALL | METH_KEYWORDS)) + return __Pyx_CallCFunctionFastWithKeywords(cfunc, self, args, 2, NULL); + } +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + else if (unlikely(was_initialized == 1)) { + __Pyx_CachedCFunction tmp_cfunc = { +#ifndef __cplusplus + 0 +#endif + }; + tmp_cfunc.type = cfunc->type; + tmp_cfunc.method_name = cfunc->method_name; + return __Pyx__CallUnboundCMethod2(&tmp_cfunc, self, arg1, arg2); + } +#endif + PyObject *result = __Pyx__CallUnboundCMethod2(cfunc, self, arg1, arg2); + __Pyx_CachedCFunction_SetFinishedInitializing(cfunc); + return result; +} +#endif +static PyObject* __Pyx__CallUnboundCMethod2(__Pyx_CachedCFunction* cfunc, PyObject* self, PyObject* arg1, PyObject* arg2){ + if (unlikely(!cfunc->func && !cfunc->method) && unlikely(__Pyx_TryUnpackUnboundCMethod(cfunc) < 0)) return NULL; +#if CYTHON_COMPILING_IN_CPYTHON + if (cfunc->func && (cfunc->flag & METH_VARARGS)) { + PyObject *result = NULL; + PyObject *args = PyTuple_New(2); + if (unlikely(!args)) return NULL; + Py_INCREF(arg1); + PyTuple_SET_ITEM(args, 0, arg1); + Py_INCREF(arg2); + PyTuple_SET_ITEM(args, 1, arg2); + if (cfunc->flag & METH_KEYWORDS) + result = __Pyx_CallCFunctionWithKeywords(cfunc, self, args, NULL); + else + result = __Pyx_CallCFunction(cfunc, self, args); + Py_DECREF(args); + return result; + } +#endif + { + PyObject *args[4] = {NULL, self, arg1, arg2}; + return __Pyx_PyObject_FastCall(cfunc->method, args+1, 3 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET); + } +} + +/* ParseKeywordsImpl (used by ParseKeywords) */ +static int __Pyx_ValidateDuplicatePosArgs( + PyObject *kwds, + PyObject ** const argnames[], + PyObject ** const *first_kw_arg, + const char* function_name) +{ + PyObject ** const *name = argnames; + while (name != first_kw_arg) { + PyObject *key = **name; + int found = PyDict_Contains(kwds, key); + if (unlikely(found)) { + if (found == 1) __Pyx_RaiseDoubleKeywordsError(function_name, key); + goto bad; + } + name++; + } + return 0; +bad: + return -1; +} +#if CYTHON_USE_UNICODE_INTERNALS +static CYTHON_INLINE int __Pyx_UnicodeKeywordsEqual(PyObject *s1, PyObject *s2) { + int kind; + Py_ssize_t len = PyUnicode_GET_LENGTH(s1); + if (len != PyUnicode_GET_LENGTH(s2)) return 0; + kind = PyUnicode_KIND(s1); + if (kind != PyUnicode_KIND(s2)) return 0; + const void *data1 = PyUnicode_DATA(s1); + const void *data2 = PyUnicode_DATA(s2); + return (memcmp(data1, data2, (size_t) len * (size_t) kind) == 0); +} +#endif +static int __Pyx_MatchKeywordArg_str( + PyObject *key, + PyObject ** const argnames[], + PyObject ** const *first_kw_arg, + size_t *index_found, + const char *function_name) +{ + PyObject ** const *name; + #if CYTHON_USE_UNICODE_INTERNALS + Py_hash_t key_hash = ((PyASCIIObject*)key)->hash; + if (unlikely(key_hash == -1)) { + key_hash = PyObject_Hash(key); + if (unlikely(key_hash == -1)) + goto bad; + } + #endif + name = first_kw_arg; + while (*name) { + PyObject *name_str = **name; + #if CYTHON_USE_UNICODE_INTERNALS + if (key_hash == ((PyASCIIObject*)name_str)->hash && __Pyx_UnicodeKeywordsEqual(name_str, key)) { + *index_found = (size_t) (name - argnames); + return 1; + } + #else + #if CYTHON_ASSUME_SAFE_SIZE + if (PyUnicode_GET_LENGTH(name_str) == PyUnicode_GET_LENGTH(key)) + #endif + { + int cmp = PyUnicode_Compare(name_str, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) { + *index_found = (size_t) (name - argnames); + return 1; + } + } + #endif + name++; + } + name = argnames; + while (name != first_kw_arg) { + PyObject *name_str = **name; + #if CYTHON_USE_UNICODE_INTERNALS + if (unlikely(key_hash == ((PyASCIIObject*)name_str)->hash)) { + if (__Pyx_UnicodeKeywordsEqual(name_str, key)) + goto arg_passed_twice; + } + #else + #if CYTHON_ASSUME_SAFE_SIZE + if (PyUnicode_GET_LENGTH(name_str) == PyUnicode_GET_LENGTH(key)) + #endif + { + if (unlikely(name_str == key)) goto arg_passed_twice; + int cmp = PyUnicode_Compare(name_str, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) goto arg_passed_twice; + } + #endif + name++; + } + return 0; +arg_passed_twice: + __Pyx_RaiseDoubleKeywordsError(function_name, key); + goto bad; +bad: + return -1; +} +static int __Pyx_MatchKeywordArg_nostr( + PyObject *key, + PyObject ** const argnames[], + PyObject ** const *first_kw_arg, + size_t *index_found, + const char *function_name) +{ + PyObject ** const *name; + if (unlikely(!PyUnicode_Check(key))) goto invalid_keyword_type; + name = first_kw_arg; + while (*name) { + int cmp = PyObject_RichCompareBool(**name, key, Py_EQ); + if (cmp == 1) { + *index_found = (size_t) (name - argnames); + return 1; + } + if (unlikely(cmp == -1)) goto bad; + name++; + } + name = argnames; + while (name != first_kw_arg) { + int cmp = PyObject_RichCompareBool(**name, key, Py_EQ); + if (unlikely(cmp != 0)) { + if (cmp == 1) goto arg_passed_twice; + else goto bad; + } + name++; + } + return 0; +arg_passed_twice: + __Pyx_RaiseDoubleKeywordsError(function_name, key); + goto bad; +invalid_keyword_type: + PyErr_Format(PyExc_TypeError, + "%.200s() keywords must be strings", function_name); + goto bad; +bad: + return -1; +} +static CYTHON_INLINE int __Pyx_MatchKeywordArg( + PyObject *key, + PyObject ** const argnames[], + PyObject ** const *first_kw_arg, + size_t *index_found, + const char *function_name) +{ + return likely(PyUnicode_CheckExact(key)) ? + __Pyx_MatchKeywordArg_str(key, argnames, first_kw_arg, index_found, function_name) : + __Pyx_MatchKeywordArg_nostr(key, argnames, first_kw_arg, index_found, function_name); +} +static void __Pyx_RejectUnknownKeyword( + PyObject *kwds, + PyObject ** const argnames[], + PyObject ** const *first_kw_arg, + const char *function_name) +{ + #if CYTHON_AVOID_BORROWED_REFS + PyObject *pos = NULL; + #else + Py_ssize_t pos = 0; + #endif + PyObject *key = NULL; + __Pyx_BEGIN_CRITICAL_SECTION(kwds); + while ( + #if CYTHON_AVOID_BORROWED_REFS + __Pyx_PyDict_NextRef(kwds, &pos, &key, NULL) + #else + PyDict_Next(kwds, &pos, &key, NULL) + #endif + ) { + PyObject** const *name = first_kw_arg; + while (*name && (**name != key)) name++; + if (!*name) { + size_t index_found = 0; + int cmp = __Pyx_MatchKeywordArg(key, argnames, first_kw_arg, &index_found, function_name); + if (cmp != 1) { + if (cmp == 0) { + PyErr_Format(PyExc_TypeError, + "%s() got an unexpected keyword argument '%U'", + function_name, key); + } + #if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(key); + #endif + break; + } + } + #if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(key); + #endif + } + __Pyx_END_CRITICAL_SECTION(); + #if CYTHON_AVOID_BORROWED_REFS + Py_XDECREF(pos); + #endif + assert(PyErr_Occurred()); +} +static int __Pyx_ParseKeywordDict( + PyObject *kwds, + PyObject ** const argnames[], + PyObject *values[], + Py_ssize_t num_pos_args, + Py_ssize_t num_kwargs, + const char* function_name, + int ignore_unknown_kwargs) +{ + PyObject** const *name; + PyObject** const *first_kw_arg = argnames + num_pos_args; + Py_ssize_t extracted = 0; +#if !CYTHON_COMPILING_IN_PYPY || defined(PyArg_ValidateKeywordArguments) + if (unlikely(!PyArg_ValidateKeywordArguments(kwds))) return -1; +#endif + name = first_kw_arg; + while (*name && num_kwargs > extracted) { + PyObject * key = **name; + PyObject *value; + int found = 0; + #if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + found = PyDict_GetItemRef(kwds, key, &value); + #else + value = PyDict_GetItemWithError(kwds, key); + if (value) { + Py_INCREF(value); + found = 1; + } else { + if (unlikely(PyErr_Occurred())) goto bad; + } + #endif + if (found) { + if (unlikely(found < 0)) goto bad; + values[name-argnames] = value; + extracted++; + } + name++; + } + if (num_kwargs > extracted) { + if (ignore_unknown_kwargs) { + if (unlikely(__Pyx_ValidateDuplicatePosArgs(kwds, argnames, first_kw_arg, function_name) == -1)) + goto bad; + } else { + __Pyx_RejectUnknownKeyword(kwds, argnames, first_kw_arg, function_name); + goto bad; + } + } + return 0; +bad: + return -1; +} +static int __Pyx_ParseKeywordDictToDict( + PyObject *kwds, + PyObject ** const argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + const char* function_name) +{ + PyObject** const *name; + PyObject** const *first_kw_arg = argnames + num_pos_args; + Py_ssize_t len; +#if !CYTHON_COMPILING_IN_PYPY || defined(PyArg_ValidateKeywordArguments) + if (unlikely(!PyArg_ValidateKeywordArguments(kwds))) return -1; +#endif + if (PyDict_Update(kwds2, kwds) < 0) goto bad; + name = first_kw_arg; + while (*name) { + PyObject *key = **name; + PyObject *value; +#if !CYTHON_COMPILING_IN_LIMITED_API && (PY_VERSION_HEX >= 0x030d00A2 || defined(PyDict_Pop)) + int found = PyDict_Pop(kwds2, key, &value); + if (found) { + if (unlikely(found < 0)) goto bad; + values[name-argnames] = value; + } +#elif __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + int found = PyDict_GetItemRef(kwds2, key, &value); + if (found) { + if (unlikely(found < 0)) goto bad; + values[name-argnames] = value; + if (unlikely(PyDict_DelItem(kwds2, key) < 0)) goto bad; + } +#else + #if CYTHON_COMPILING_IN_CPYTHON + value = _PyDict_Pop(kwds2, key, kwds2); + #else + value = __Pyx_CallUnboundCMethod2(&__pyx_mstate_global->__pyx_umethod_PyDict_Type_pop, kwds2, key, kwds2); + #endif + if (value == kwds2) { + Py_DECREF(value); + } else { + if (unlikely(!value)) goto bad; + values[name-argnames] = value; + } +#endif + name++; + } + len = PyDict_Size(kwds2); + if (len > 0) { + return __Pyx_ValidateDuplicatePosArgs(kwds, argnames, first_kw_arg, function_name); + } else if (unlikely(len == -1)) { + goto bad; + } + return 0; +bad: + return -1; +} +static int __Pyx_ParseKeywordsTuple( + PyObject *kwds, + PyObject * const *kwvalues, + PyObject ** const argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + Py_ssize_t num_kwargs, + const char* function_name, + int ignore_unknown_kwargs) +{ + PyObject *key = NULL; + PyObject** const * name; + PyObject** const *first_kw_arg = argnames + num_pos_args; + for (Py_ssize_t pos = 0; pos < num_kwargs; pos++) { +#if CYTHON_AVOID_BORROWED_REFS + key = __Pyx_PySequence_ITEM(kwds, pos); +#else + key = __Pyx_PyTuple_GET_ITEM(kwds, pos); +#endif +#if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(!key)) goto bad; +#endif + name = first_kw_arg; + while (*name && (**name != key)) name++; + if (*name) { + PyObject *value = kwvalues[pos]; + values[name-argnames] = __Pyx_NewRef(value); + } else { + size_t index_found = 0; + int cmp = __Pyx_MatchKeywordArg(key, argnames, first_kw_arg, &index_found, function_name); + if (cmp == 1) { + PyObject *value = kwvalues[pos]; + values[index_found] = __Pyx_NewRef(value); + } else { + if (unlikely(cmp == -1)) goto bad; + if (kwds2) { + PyObject *value = kwvalues[pos]; + if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; + } else if (!ignore_unknown_kwargs) { + goto invalid_keyword; + } + } + } + #if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(key); + key = NULL; + #endif + } + return 0; +invalid_keyword: + PyErr_Format(PyExc_TypeError, + "%s() got an unexpected keyword argument '%U'", + function_name, key); + goto bad; +bad: + #if CYTHON_AVOID_BORROWED_REFS + Py_XDECREF(key); + #endif + return -1; +} + +/* ParseKeywords */ +static int __Pyx_ParseKeywords( + PyObject *kwds, + PyObject * const *kwvalues, + PyObject ** const argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + Py_ssize_t num_kwargs, + const char* function_name, + int ignore_unknown_kwargs) +{ + if (CYTHON_METH_FASTCALL && likely(PyTuple_Check(kwds))) + return __Pyx_ParseKeywordsTuple(kwds, kwvalues, argnames, kwds2, values, num_pos_args, num_kwargs, function_name, ignore_unknown_kwargs); + else if (kwds2) + return __Pyx_ParseKeywordDictToDict(kwds, argnames, kwds2, values, num_pos_args, function_name); + else + return __Pyx_ParseKeywordDict(kwds, argnames, values, num_pos_args, num_kwargs, function_name, ignore_unknown_kwargs); +} + +/* RaiseArgTupleInvalid */ +static void __Pyx_RaiseArgtupleInvalid( + const char* func_name, + int exact, + Py_ssize_t num_min, + Py_ssize_t num_max, + Py_ssize_t num_found) +{ + Py_ssize_t num_expected; + const char *more_or_less; + if (num_found < num_min) { + num_expected = num_min; + more_or_less = "at least"; + } else { + num_expected = num_max; + more_or_less = "at most"; + } + if (exact) { + more_or_less = "exactly"; + } + PyErr_Format(PyExc_TypeError, + "%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)", + func_name, more_or_less, num_expected, + (num_expected == 1) ? "" : "s", num_found); +} + +/* PyObjectFastCallMethod */ +#if !CYTHON_VECTORCALL || PY_VERSION_HEX < 0x03090000 +static PyObject *__Pyx_PyObject_FastCallMethod(PyObject *name, PyObject *const *args, size_t nargsf) { + PyObject *result; + PyObject *attr = PyObject_GetAttr(args[0], name); + if (unlikely(!attr)) + return NULL; + result = __Pyx_PyObject_FastCall(attr, args+1, nargsf - 1); + Py_DECREF(attr); + return result; +} +#endif + +/* DivInt[int] */ +static CYTHON_INLINE int __Pyx_div_int(int a, int b, int b_is_constant) { + int q = a / b; + int r = a - q*b; + int adapt_python = (b_is_constant ? + ((r != 0) & ((r < 0) ^ (b < 0))) : + ((r != 0) & ((r ^ b) < 0)) + ); + return q - adapt_python; +} + +/* ModInt[int] */ +static CYTHON_INLINE int __Pyx_mod_int(int a, int b, int b_is_constant) { + int r = a % b; + int adapt_python = (b_is_constant ? + ((r != 0) & ((r < 0) ^ (b < 0))) : + ((r != 0) & ((r ^ b) < 0)) + ); + return r + adapt_python * b; +} + +/* RejectKeywords */ +static void __Pyx_RejectKeywords(const char* function_name, PyObject *kwds) { + PyObject *key = NULL; + if (CYTHON_METH_FASTCALL && likely(PyTuple_Check(kwds))) { + key = __Pyx_PySequence_ITEM(kwds, 0); + } else { +#if CYTHON_AVOID_BORROWED_REFS + PyObject *pos = NULL; +#else + Py_ssize_t pos = 0; +#endif +#if !CYTHON_COMPILING_IN_PYPY || defined(PyArg_ValidateKeywordArguments) + if (unlikely(!PyArg_ValidateKeywordArguments(kwds))) return; +#endif + __Pyx_PyDict_NextRef(kwds, &pos, &key, NULL); +#if CYTHON_AVOID_BORROWED_REFS + Py_XDECREF(pos); +#endif + } + if (likely(key)) { + PyErr_Format(PyExc_TypeError, + "%s() got an unexpected keyword argument '%U'", + function_name, key); + Py_DECREF(key); + } +} + +/* PyErrFetchRestore (used by RaiseException) */ +#if CYTHON_FAST_THREAD_STATE +static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { +#if PY_VERSION_HEX >= 0x030C00A6 + PyObject *tmp_value; + assert(type == NULL || (value != NULL && type == (PyObject*) Py_TYPE(value))); + if (value) { + #if CYTHON_COMPILING_IN_CPYTHON + if (unlikely(((PyBaseExceptionObject*) value)->traceback != tb)) + #endif + PyException_SetTraceback(value, tb); + } + tmp_value = tstate->current_exception; + tstate->current_exception = value; + Py_XDECREF(tmp_value); + Py_XDECREF(type); + Py_XDECREF(tb); +#else + PyObject *tmp_type, *tmp_value, *tmp_tb; + tmp_type = tstate->curexc_type; + tmp_value = tstate->curexc_value; + tmp_tb = tstate->curexc_traceback; + tstate->curexc_type = type; + tstate->curexc_value = value; + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#endif +} +static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { +#if PY_VERSION_HEX >= 0x030C00A6 + PyObject* exc_value; + exc_value = tstate->current_exception; + tstate->current_exception = 0; + *value = exc_value; + *type = NULL; + *tb = NULL; + if (exc_value) { + *type = (PyObject*) Py_TYPE(exc_value); + Py_INCREF(*type); + #if CYTHON_COMPILING_IN_CPYTHON + *tb = ((PyBaseExceptionObject*) exc_value)->traceback; + Py_XINCREF(*tb); + #else + *tb = PyException_GetTraceback(exc_value); + #endif + } +#else + *type = tstate->curexc_type; + *value = tstate->curexc_value; + *tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; +#endif +} +#endif + +/* RaiseException */ +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { + PyObject* owned_instance = NULL; + if (tb == Py_None) { + tb = 0; + } else if (tb && !PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto bad; + } + if (value == Py_None) + value = 0; + if (PyExceptionInstance_Check(type)) { + if (value) { + PyErr_SetString(PyExc_TypeError, + "instance exception may not have a separate value"); + goto bad; + } + value = type; + type = (PyObject*) Py_TYPE(value); + } else if (PyExceptionClass_Check(type)) { + PyObject *instance_class = NULL; + if (value && PyExceptionInstance_Check(value)) { + instance_class = (PyObject*) Py_TYPE(value); + if (instance_class != type) { + int is_subclass = PyObject_IsSubclass(instance_class, type); + if (!is_subclass) { + instance_class = NULL; + } else if (unlikely(is_subclass == -1)) { + goto bad; + } else { + type = instance_class; + } + } + } + if (!instance_class) { + PyObject *args; + if (!value) + args = PyTuple_New(0); + else if (PyTuple_Check(value)) { + Py_INCREF(value); + args = value; + } else + args = PyTuple_Pack(1, value); + if (!args) + goto bad; + owned_instance = PyObject_Call(type, args, NULL); + Py_DECREF(args); + if (!owned_instance) + goto bad; + value = owned_instance; + if (!PyExceptionInstance_Check(value)) { + PyErr_Format(PyExc_TypeError, + "calling %R should have returned an instance of " + "BaseException, not %R", + type, Py_TYPE(value)); + goto bad; + } + } + } else { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto bad; + } + if (cause) { + PyObject *fixed_cause; + if (cause == Py_None) { + fixed_cause = NULL; + } else if (PyExceptionClass_Check(cause)) { + fixed_cause = PyObject_CallObject(cause, NULL); + if (fixed_cause == NULL) + goto bad; + } else if (PyExceptionInstance_Check(cause)) { + fixed_cause = cause; + Py_INCREF(fixed_cause); + } else { + PyErr_SetString(PyExc_TypeError, + "exception causes must derive from " + "BaseException"); + goto bad; + } + PyException_SetCause(value, fixed_cause); + } + PyErr_SetObject(type, value); + if (tb) { +#if PY_VERSION_HEX >= 0x030C00A6 + PyException_SetTraceback(value, tb); +#elif CYTHON_FAST_THREAD_STATE + PyThreadState *tstate = __Pyx_PyThreadState_Current; + PyObject* tmp_tb = tstate->curexc_traceback; + if (tb != tmp_tb) { + Py_INCREF(tb); + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_tb); + } +#else + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyErr_Fetch(&tmp_type, &tmp_value, &tmp_tb); + Py_INCREF(tb); + PyErr_Restore(tmp_type, tmp_value, tb); + Py_XDECREF(tmp_tb); +#endif + } +bad: + Py_XDECREF(owned_instance); + return; +} + +/* PyErrExceptionMatches (used by GetAttr3) */ +#if CYTHON_FAST_THREAD_STATE +static int __Pyx_PyErr_ExceptionMatchesTuple(PyObject *exc_type, PyObject *tuple) { + Py_ssize_t i, n; + n = PyTuple_GET_SIZE(tuple); + for (i=0; i= 0x030C00A6 + PyObject *current_exception = tstate->current_exception; + if (unlikely(!current_exception)) return 0; + exc_type = (PyObject*) Py_TYPE(current_exception); + if (exc_type == err) return 1; +#else + exc_type = tstate->curexc_type; + if (exc_type == err) return 1; + if (unlikely(!exc_type)) return 0; +#endif + #if CYTHON_AVOID_BORROWED_REFS + Py_INCREF(exc_type); + #endif + if (unlikely(PyTuple_Check(err))) { + result = __Pyx_PyErr_ExceptionMatchesTuple(exc_type, err); + } else { + result = __Pyx_PyErr_GivenExceptionMatches(exc_type, err); + } + #if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(exc_type); + #endif + return result; +} +#endif + +/* GetAttr3 */ +#if __PYX_LIMITED_VERSION_HEX < 0x030d0000 +static PyObject *__Pyx_GetAttr3Default(PyObject *d) { + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + if (unlikely(!__Pyx_PyErr_ExceptionMatches(PyExc_AttributeError))) + return NULL; + __Pyx_PyErr_Clear(); + Py_INCREF(d); + return d; +} +#endif +static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *o, PyObject *n, PyObject *d) { + PyObject *r; +#if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + int res = PyObject_GetOptionalAttr(o, n, &r); + return (res != 0) ? r : __Pyx_NewRef(d); +#else + #if CYTHON_USE_TYPE_SLOTS + if (likely(PyUnicode_Check(n))) { + r = __Pyx_PyObject_GetAttrStrNoError(o, n); + if (unlikely(!r) && likely(!PyErr_Occurred())) { + r = __Pyx_NewRef(d); + } + return r; + } + #endif + r = PyObject_GetAttr(o, n); + return (likely(r)) ? r : __Pyx_GetAttr3Default(d); +#endif +} + +/* GetException */ +#if CYTHON_FAST_THREAD_STATE +static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) +#else +static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb) +#endif +{ + PyObject *local_type = NULL, *local_value, *local_tb = NULL; +#if CYTHON_FAST_THREAD_STATE + PyObject *tmp_type, *tmp_value, *tmp_tb; + #if PY_VERSION_HEX >= 0x030C0000 + local_value = tstate->current_exception; + tstate->current_exception = 0; + #else + local_type = tstate->curexc_type; + local_value = tstate->curexc_value; + local_tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; + #endif +#elif __PYX_LIMITED_VERSION_HEX > 0x030C0000 + local_value = PyErr_GetRaisedException(); +#else + PyErr_Fetch(&local_type, &local_value, &local_tb); +#endif +#if __PYX_LIMITED_VERSION_HEX > 0x030C0000 + if (likely(local_value)) { + local_type = (PyObject*) Py_TYPE(local_value); + Py_INCREF(local_type); + local_tb = PyException_GetTraceback(local_value); + } +#else + PyErr_NormalizeException(&local_type, &local_value, &local_tb); +#if CYTHON_FAST_THREAD_STATE + if (unlikely(tstate->curexc_type)) +#else + if (unlikely(PyErr_Occurred())) +#endif + goto bad; + if (local_tb) { + if (unlikely(PyException_SetTraceback(local_value, local_tb) < 0)) + goto bad; + } +#endif // __PYX_LIMITED_VERSION_HEX > 0x030C0000 + Py_XINCREF(local_tb); + Py_XINCREF(local_type); + Py_XINCREF(local_value); + *type = local_type; + *value = local_value; + *tb = local_tb; +#if CYTHON_FAST_THREAD_STATE + #if CYTHON_USE_EXC_INFO_STACK + { + _PyErr_StackItem *exc_info = tstate->exc_info; + #if PY_VERSION_HEX >= 0x030B00a4 + tmp_value = exc_info->exc_value; + exc_info->exc_value = local_value; + tmp_type = NULL; + tmp_tb = NULL; + Py_XDECREF(local_type); + Py_XDECREF(local_tb); + #else + tmp_type = exc_info->exc_type; + tmp_value = exc_info->exc_value; + tmp_tb = exc_info->exc_traceback; + exc_info->exc_type = local_type; + exc_info->exc_value = local_value; + exc_info->exc_traceback = local_tb; + #endif + } + #else + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = local_type; + tstate->exc_value = local_value; + tstate->exc_traceback = local_tb; + #endif + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#elif __PYX_LIMITED_VERSION_HEX >= 0x030b0000 + PyErr_SetHandledException(local_value); + Py_XDECREF(local_value); + Py_XDECREF(local_type); + Py_XDECREF(local_tb); +#else + PyErr_SetExcInfo(local_type, local_value, local_tb); +#endif + return 0; +#if __PYX_LIMITED_VERSION_HEX <= 0x030C0000 +bad: + *type = 0; + *value = 0; + *tb = 0; + Py_XDECREF(local_type); + Py_XDECREF(local_value); + Py_XDECREF(local_tb); + return -1; +#endif +} + +/* SwapException */ +#if CYTHON_FAST_THREAD_STATE +static CYTHON_INLINE void __Pyx__ExceptionSwap(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { + PyObject *tmp_type, *tmp_value, *tmp_tb; + #if CYTHON_USE_EXC_INFO_STACK && PY_VERSION_HEX >= 0x030B00a4 + _PyErr_StackItem *exc_info = tstate->exc_info; + tmp_value = exc_info->exc_value; + exc_info->exc_value = *value; + if (tmp_value == NULL || tmp_value == Py_None) { + Py_XDECREF(tmp_value); + tmp_value = NULL; + tmp_type = NULL; + tmp_tb = NULL; + } else { + tmp_type = (PyObject*) Py_TYPE(tmp_value); + Py_INCREF(tmp_type); + #if CYTHON_COMPILING_IN_CPYTHON + tmp_tb = ((PyBaseExceptionObject*) tmp_value)->traceback; + Py_XINCREF(tmp_tb); + #else + tmp_tb = PyException_GetTraceback(tmp_value); + #endif + } + #elif CYTHON_USE_EXC_INFO_STACK + _PyErr_StackItem *exc_info = tstate->exc_info; + tmp_type = exc_info->exc_type; + tmp_value = exc_info->exc_value; + tmp_tb = exc_info->exc_traceback; + exc_info->exc_type = *type; + exc_info->exc_value = *value; + exc_info->exc_traceback = *tb; + #else + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = *type; + tstate->exc_value = *value; + tstate->exc_traceback = *tb; + #endif + *type = tmp_type; + *value = tmp_value; + *tb = tmp_tb; +} +#else +static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb) { + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyErr_GetExcInfo(&tmp_type, &tmp_value, &tmp_tb); + PyErr_SetExcInfo(*type, *value, *tb); + *type = tmp_type; + *value = tmp_value; + *tb = tmp_tb; +} +#endif + +/* GetTopmostException (used by SaveResetException) */ +#if CYTHON_USE_EXC_INFO_STACK && CYTHON_FAST_THREAD_STATE +static _PyErr_StackItem * +__Pyx_PyErr_GetTopmostException(PyThreadState *tstate) +{ + _PyErr_StackItem *exc_info = tstate->exc_info; + while ((exc_info->exc_value == NULL || exc_info->exc_value == Py_None) && + exc_info->previous_item != NULL) + { + exc_info = exc_info->previous_item; + } + return exc_info; +} +#endif + +/* SaveResetException */ +#if CYTHON_FAST_THREAD_STATE +static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { + #if CYTHON_USE_EXC_INFO_STACK && PY_VERSION_HEX >= 0x030B00a4 + _PyErr_StackItem *exc_info = __Pyx_PyErr_GetTopmostException(tstate); + PyObject *exc_value = exc_info->exc_value; + if (exc_value == NULL || exc_value == Py_None) { + *value = NULL; + *type = NULL; + *tb = NULL; + } else { + *value = exc_value; + Py_INCREF(*value); + *type = (PyObject*) Py_TYPE(exc_value); + Py_INCREF(*type); + *tb = PyException_GetTraceback(exc_value); + } + #elif CYTHON_USE_EXC_INFO_STACK + _PyErr_StackItem *exc_info = __Pyx_PyErr_GetTopmostException(tstate); + *type = exc_info->exc_type; + *value = exc_info->exc_value; + *tb = exc_info->exc_traceback; + Py_XINCREF(*type); + Py_XINCREF(*value); + Py_XINCREF(*tb); + #else + *type = tstate->exc_type; + *value = tstate->exc_value; + *tb = tstate->exc_traceback; + Py_XINCREF(*type); + Py_XINCREF(*value); + Py_XINCREF(*tb); + #endif +} +static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { + #if CYTHON_USE_EXC_INFO_STACK && PY_VERSION_HEX >= 0x030B00a4 + _PyErr_StackItem *exc_info = tstate->exc_info; + PyObject *tmp_value = exc_info->exc_value; + exc_info->exc_value = value; + Py_XDECREF(tmp_value); + Py_XDECREF(type); + Py_XDECREF(tb); + #else + PyObject *tmp_type, *tmp_value, *tmp_tb; + #if CYTHON_USE_EXC_INFO_STACK + _PyErr_StackItem *exc_info = tstate->exc_info; + tmp_type = exc_info->exc_type; + tmp_value = exc_info->exc_value; + tmp_tb = exc_info->exc_traceback; + exc_info->exc_type = type; + exc_info->exc_value = value; + exc_info->exc_traceback = tb; + #else + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = type; + tstate->exc_value = value; + tstate->exc_traceback = tb; + #endif + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); + #endif +} +#endif + +/* PyObjectGetAttrStrNoError (used by GetBuiltinName) */ +#if __PYX_LIMITED_VERSION_HEX < 0x030d0000 +static void __Pyx_PyObject_GetAttrStr_ClearAttributeError(void) { + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + if (likely(__Pyx_PyErr_ExceptionMatches(PyExc_AttributeError))) + __Pyx_PyErr_Clear(); +} +#endif +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStrNoError(PyObject* obj, PyObject* attr_name) { + PyObject *result; +#if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + (void) PyObject_GetOptionalAttr(obj, attr_name, &result); + return result; +#else +#if CYTHON_COMPILING_IN_CPYTHON && CYTHON_USE_TYPE_SLOTS + PyTypeObject* tp = Py_TYPE(obj); + if (likely(tp->tp_getattro == PyObject_GenericGetAttr)) { + return _PyObject_GenericGetAttrWithDict(obj, attr_name, NULL, 1); + } +#endif + result = __Pyx_PyObject_GetAttrStr(obj, attr_name); + if (unlikely(!result)) { + __Pyx_PyObject_GetAttrStr_ClearAttributeError(); + } + return result; +#endif +} + +/* GetBuiltinName (used by GetModuleGlobalName) */ +static PyObject *__Pyx_GetBuiltinName(PyObject *name) { + PyObject* result = __Pyx_PyObject_GetAttrStrNoError(__pyx_mstate_global->__pyx_b, name); + if (unlikely(!result) && !PyErr_Occurred()) { + PyErr_Format(PyExc_NameError, + "name '%U' is not defined", name); + } + return result; +} + +/* PyDictVersioning (used by GetModuleGlobalName) */ +#if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_TYPE_SLOTS +static CYTHON_INLINE PY_UINT64_T __Pyx_get_tp_dict_version(PyObject *obj) { + PyObject *dict = Py_TYPE(obj)->tp_dict; + return likely(dict) ? __PYX_GET_DICT_VERSION(dict) : 0; +} +static CYTHON_INLINE PY_UINT64_T __Pyx_get_object_dict_version(PyObject *obj) { + PyObject **dictptr = NULL; + Py_ssize_t offset = Py_TYPE(obj)->tp_dictoffset; + if (offset) { +#if CYTHON_COMPILING_IN_CPYTHON + dictptr = (likely(offset > 0)) ? (PyObject **) ((char *)obj + offset) : _PyObject_GetDictPtr(obj); +#else + dictptr = _PyObject_GetDictPtr(obj); +#endif + } + return (dictptr && *dictptr) ? __PYX_GET_DICT_VERSION(*dictptr) : 0; +} +static CYTHON_INLINE int __Pyx_object_dict_version_matches(PyObject* obj, PY_UINT64_T tp_dict_version, PY_UINT64_T obj_dict_version) { + PyObject *dict = Py_TYPE(obj)->tp_dict; + if (unlikely(!dict) || unlikely(tp_dict_version != __PYX_GET_DICT_VERSION(dict))) + return 0; + return obj_dict_version == __Pyx_get_object_dict_version(obj); +} +#endif + +/* GetModuleGlobalName */ +#if CYTHON_USE_DICT_VERSIONS +static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_version, PyObject **dict_cached_value) +#else +static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name) +#endif +{ + PyObject *result; +#if CYTHON_COMPILING_IN_LIMITED_API + if (unlikely(!__pyx_m)) { + if (!PyErr_Occurred()) + PyErr_SetNone(PyExc_NameError); + return NULL; + } + result = PyObject_GetAttr(__pyx_m, name); + if (likely(result)) { + return result; + } + PyErr_Clear(); +#elif CYTHON_AVOID_BORROWED_REFS || CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + if (unlikely(__Pyx_PyDict_GetItemRef(__pyx_mstate_global->__pyx_d, name, &result) == -1)) PyErr_Clear(); + __PYX_UPDATE_DICT_CACHE(__pyx_mstate_global->__pyx_d, result, *dict_cached_value, *dict_version) + if (likely(result)) { + return result; + } +#else + result = _PyDict_GetItem_KnownHash(__pyx_mstate_global->__pyx_d, name, ((PyASCIIObject *) name)->hash); + __PYX_UPDATE_DICT_CACHE(__pyx_mstate_global->__pyx_d, result, *dict_cached_value, *dict_version) + if (likely(result)) { + return __Pyx_NewRef(result); + } + PyErr_Clear(); +#endif + return __Pyx_GetBuiltinName(name); +} + +/* RaiseUnexpectedTypeError */ +static int +__Pyx_RaiseUnexpectedTypeError(const char *expected, PyObject *obj) +{ + __Pyx_TypeName obj_type_name = __Pyx_PyType_GetFullyQualifiedName(Py_TYPE(obj)); + PyErr_Format(PyExc_TypeError, "Expected %s, got " __Pyx_FMT_TYPENAME, + expected, obj_type_name); + __Pyx_DECREF_TypeName(obj_type_name); + return 0; +} + +/* ArgTypeTestFunc (used by ArgTypeTest) */ +static int __Pyx__ArgTypeTest(PyObject *obj, PyTypeObject *type, const char *name, int exact) +{ + __Pyx_TypeName type_name; + __Pyx_TypeName obj_type_name; + PyObject *extra_info = __pyx_mstate_global->__pyx_empty_unicode; + int from_annotation_subclass = 0; + if (unlikely(!type)) { + PyErr_SetString(PyExc_SystemError, "Missing type object"); + return 0; + } + else if (!exact) { + if (likely(__Pyx_TypeCheck(obj, type))) return 1; + } else if (exact == 2) { + if (__Pyx_TypeCheck(obj, type)) { + from_annotation_subclass = 1; + extra_info = __pyx_mstate_global->__pyx_kp_u_Note_that_Cython_is_deliberately; + } + } + type_name = __Pyx_PyType_GetFullyQualifiedName(type); + obj_type_name = __Pyx_PyType_GetFullyQualifiedName(Py_TYPE(obj)); + PyErr_Format(PyExc_TypeError, + "Argument '%.200s' has incorrect type (expected " __Pyx_FMT_TYPENAME + ", got " __Pyx_FMT_TYPENAME ")" +#if __PYX_LIMITED_VERSION_HEX < 0x030C0000 + "%s%U" +#endif + , name, type_name, obj_type_name +#if __PYX_LIMITED_VERSION_HEX < 0x030C0000 + , (from_annotation_subclass ? ". " : ""), extra_info +#endif + ); +#if __PYX_LIMITED_VERSION_HEX >= 0x030C0000 + if (exact == 2 && from_annotation_subclass) { + PyObject *res; + PyObject *vargs[2]; + vargs[0] = PyErr_GetRaisedException(); + vargs[1] = extra_info; + res = PyObject_VectorcallMethod(__pyx_mstate_global->__pyx_kp_u_add_note, vargs, 2, NULL); + Py_XDECREF(res); + PyErr_SetRaisedException(vargs[0]); + } +#endif + __Pyx_DECREF_TypeName(type_name); + __Pyx_DECREF_TypeName(obj_type_name); + return 0; +} + +/* GetItemInt */ +static PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) { + PyObject *r; + if (unlikely(!j)) return NULL; + r = PyObject_GetItem(o, j); + Py_DECREF(j); + return r; +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck, int unsafe_shared) { + CYTHON_MAYBE_UNUSED_VAR(unsafe_shared); +#if CYTHON_ASSUME_SAFE_SIZE + Py_ssize_t wrapped_i = i; + if (wraparound & unlikely(i < 0)) { + wrapped_i += PyList_GET_SIZE(o); + } + if ((CYTHON_AVOID_BORROWED_REFS || CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS || !CYTHON_ASSUME_SAFE_MACROS)) { + return __Pyx_PyList_GetItemRefFast(o, wrapped_i, unsafe_shared); + } else + if ((!boundscheck) || likely(__Pyx_is_valid_index(wrapped_i, PyList_GET_SIZE(o)))) { + return __Pyx_NewRef(PyList_GET_ITEM(o, wrapped_i)); + } + return __Pyx_GetItemInt_Generic(o, PyLong_FromSsize_t(i)); +#else + (void)wraparound; + (void)boundscheck; + return PySequence_GetItem(o, i); +#endif +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck, int unsafe_shared) { + CYTHON_MAYBE_UNUSED_VAR(unsafe_shared); +#if CYTHON_ASSUME_SAFE_SIZE && CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + Py_ssize_t wrapped_i = i; + if (wraparound & unlikely(i < 0)) { + wrapped_i += PyTuple_GET_SIZE(o); + } + if ((!boundscheck) || likely(__Pyx_is_valid_index(wrapped_i, PyTuple_GET_SIZE(o)))) { + return __Pyx_NewRef(PyTuple_GET_ITEM(o, wrapped_i)); + } + return __Pyx_GetItemInt_Generic(o, PyLong_FromSsize_t(i)); +#else + (void)wraparound; + (void)boundscheck; + return PySequence_GetItem(o, i); +#endif +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, int is_list, + int wraparound, int boundscheck, int unsafe_shared) { + CYTHON_MAYBE_UNUSED_VAR(unsafe_shared); +#if CYTHON_ASSUME_SAFE_MACROS && CYTHON_ASSUME_SAFE_SIZE + if (is_list || PyList_CheckExact(o)) { + Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyList_GET_SIZE(o); + if ((CYTHON_AVOID_BORROWED_REFS || CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS)) { + return __Pyx_PyList_GetItemRefFast(o, n, unsafe_shared); + } else if ((!boundscheck) || (likely(__Pyx_is_valid_index(n, PyList_GET_SIZE(o))))) { + return __Pyx_NewRef(PyList_GET_ITEM(o, n)); + } + } else + #if !CYTHON_AVOID_BORROWED_REFS + if (PyTuple_CheckExact(o)) { + Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyTuple_GET_SIZE(o); + if ((!boundscheck) || likely(__Pyx_is_valid_index(n, PyTuple_GET_SIZE(o)))) { + return __Pyx_NewRef(PyTuple_GET_ITEM(o, n)); + } + } else + #endif +#endif +#if CYTHON_USE_TYPE_SLOTS && !CYTHON_COMPILING_IN_PYPY + { + PyMappingMethods *mm = Py_TYPE(o)->tp_as_mapping; + PySequenceMethods *sm = Py_TYPE(o)->tp_as_sequence; + if (!is_list && mm && mm->mp_subscript) { + PyObject *r, *key = PyLong_FromSsize_t(i); + if (unlikely(!key)) return NULL; + r = mm->mp_subscript(o, key); + Py_DECREF(key); + return r; + } + if (is_list || likely(sm && sm->sq_item)) { + if (wraparound && unlikely(i < 0) && likely(sm->sq_length)) { + Py_ssize_t l = sm->sq_length(o); + if (likely(l >= 0)) { + i += l; + } else { + if (!PyErr_ExceptionMatches(PyExc_OverflowError)) + return NULL; + PyErr_Clear(); + } + } + return sm->sq_item(o, i); + } + } +#else + if (is_list || !PyMapping_Check(o)) { + return PySequence_GetItem(o, i); + } +#endif + (void)wraparound; + (void)boundscheck; + return __Pyx_GetItemInt_Generic(o, PyLong_FromSsize_t(i)); +} + +/* AllocateExtensionType */ +static PyObject *__Pyx_AllocateExtensionType(PyTypeObject *t, int is_final) { + if (is_final || likely(!__Pyx_PyType_HasFeature(t, Py_TPFLAGS_IS_ABSTRACT))) { + allocfunc alloc_func = __Pyx_PyType_GetSlot(t, tp_alloc, allocfunc); + return alloc_func(t, 0); + } else { + newfunc tp_new = __Pyx_PyType_TryGetSlot(&PyBaseObject_Type, tp_new, newfunc); + #if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000 + if (!tp_new) { + PyObject *new_str = PyUnicode_FromString("__new__"); + if (likely(new_str)) { + PyObject *o = PyObject_CallMethodObjArgs((PyObject *)&PyBaseObject_Type, new_str, t, NULL); + Py_DECREF(new_str); + return o; + } else + return NULL; + } else + #endif + return tp_new(t, __pyx_mstate_global->__pyx_empty_tuple, 0); + } +} + +/* CallTypeTraverse */ +#if !CYTHON_USE_TYPE_SPECS || (!CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x03090000) +#else +static int __Pyx_call_type_traverse(PyObject *o, int always_call, visitproc visit, void *arg) { + #if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x03090000 + if (__Pyx_get_runtime_version() < 0x03090000) return 0; + #endif + if (!always_call) { + PyTypeObject *base = __Pyx_PyObject_GetSlot(o, tp_base, PyTypeObject*); + unsigned long flags = PyType_GetFlags(base); + if (flags & Py_TPFLAGS_HEAPTYPE) { + return 0; + } + } + Py_VISIT((PyObject*)Py_TYPE(o)); + return 0; +} +#endif + +/* LimitedApiGetTypeDict (used by SetItemOnTypeDict) */ +#if CYTHON_COMPILING_IN_LIMITED_API +static Py_ssize_t __Pyx_GetTypeDictOffset(void) { + PyObject *tp_dictoffset_o; + Py_ssize_t tp_dictoffset; + tp_dictoffset_o = PyObject_GetAttrString((PyObject*)(&PyType_Type), "__dictoffset__"); + if (unlikely(!tp_dictoffset_o)) return -1; + tp_dictoffset = PyLong_AsSsize_t(tp_dictoffset_o); + Py_DECREF(tp_dictoffset_o); + if (unlikely(tp_dictoffset == 0)) { + PyErr_SetString( + PyExc_TypeError, + "'type' doesn't have a dictoffset"); + return -1; + } else if (unlikely(tp_dictoffset < 0)) { + PyErr_SetString( + PyExc_TypeError, + "'type' has an unexpected negative dictoffset. " + "Please report this as Cython bug"); + return -1; + } + return tp_dictoffset; +} +static PyObject *__Pyx_GetTypeDict(PyTypeObject *tp) { + static Py_ssize_t tp_dictoffset = 0; + if (unlikely(tp_dictoffset == 0)) { + tp_dictoffset = __Pyx_GetTypeDictOffset(); + if (unlikely(tp_dictoffset == -1 && PyErr_Occurred())) { + tp_dictoffset = 0; // try again next time? + return NULL; + } + } + return *(PyObject**)((char*)tp + tp_dictoffset); +} +#endif + +/* SetItemOnTypeDict (used by FixUpExtensionType) */ +static int __Pyx__SetItemOnTypeDict(PyTypeObject *tp, PyObject *k, PyObject *v) { + int result; + PyObject *tp_dict; +#if CYTHON_COMPILING_IN_LIMITED_API + tp_dict = __Pyx_GetTypeDict(tp); + if (unlikely(!tp_dict)) return -1; +#else + tp_dict = tp->tp_dict; +#endif + result = PyDict_SetItem(tp_dict, k, v); + if (likely(!result)) { + PyType_Modified(tp); + if (unlikely(PyObject_HasAttr(v, __pyx_mstate_global->__pyx_n_u_set_name))) { + PyObject *setNameResult = PyObject_CallMethodObjArgs(v, __pyx_mstate_global->__pyx_n_u_set_name, (PyObject *) tp, k, NULL); + if (!setNameResult) return -1; + Py_DECREF(setNameResult); + } + } + return result; +} + +/* FixUpExtensionType */ +static int __Pyx_fix_up_extension_type_from_spec(PyType_Spec *spec, PyTypeObject *type) { +#if __PYX_LIMITED_VERSION_HEX > 0x030900B1 + CYTHON_UNUSED_VAR(spec); + CYTHON_UNUSED_VAR(type); + CYTHON_UNUSED_VAR(__Pyx__SetItemOnTypeDict); +#else + const PyType_Slot *slot = spec->slots; + int changed = 0; +#if !CYTHON_COMPILING_IN_LIMITED_API + while (slot && slot->slot && slot->slot != Py_tp_members) + slot++; + if (slot && slot->slot == Py_tp_members) { +#if !CYTHON_COMPILING_IN_CPYTHON + const +#endif // !CYTHON_COMPILING_IN_CPYTHON) + PyMemberDef *memb = (PyMemberDef*) slot->pfunc; + while (memb && memb->name) { + if (memb->name[0] == '_' && memb->name[1] == '_') { + if (strcmp(memb->name, "__weaklistoffset__") == 0) { + assert(memb->type == T_PYSSIZET); + assert(memb->flags == READONLY); + type->tp_weaklistoffset = memb->offset; + changed = 1; + } + else if (strcmp(memb->name, "__dictoffset__") == 0) { + assert(memb->type == T_PYSSIZET); + assert(memb->flags == READONLY); + type->tp_dictoffset = memb->offset; + changed = 1; + } +#if CYTHON_METH_FASTCALL + else if (strcmp(memb->name, "__vectorcalloffset__") == 0) { + assert(memb->type == T_PYSSIZET); + assert(memb->flags == READONLY); + type->tp_vectorcall_offset = memb->offset; + changed = 1; + } +#endif // CYTHON_METH_FASTCALL +#if !CYTHON_COMPILING_IN_PYPY + else if (strcmp(memb->name, "__module__") == 0) { + PyObject *descr; + assert(memb->type == T_OBJECT); + assert(memb->flags == 0 || memb->flags == READONLY); + descr = PyDescr_NewMember(type, memb); + if (unlikely(!descr)) + return -1; + int set_item_result = PyDict_SetItem(type->tp_dict, PyDescr_NAME(descr), descr); + Py_DECREF(descr); + if (unlikely(set_item_result < 0)) { + return -1; + } + changed = 1; + } +#endif // !CYTHON_COMPILING_IN_PYPY + } + memb++; + } + } +#endif // !CYTHON_COMPILING_IN_LIMITED_API +#if !CYTHON_COMPILING_IN_PYPY + slot = spec->slots; + while (slot && slot->slot && slot->slot != Py_tp_getset) + slot++; + if (slot && slot->slot == Py_tp_getset) { + PyGetSetDef *getset = (PyGetSetDef*) slot->pfunc; + while (getset && getset->name) { + if (getset->name[0] == '_' && getset->name[1] == '_' && strcmp(getset->name, "__module__") == 0) { + PyObject *descr = PyDescr_NewGetSet(type, getset); + if (unlikely(!descr)) + return -1; + #if CYTHON_COMPILING_IN_LIMITED_API + PyObject *pyname = PyUnicode_FromString(getset->name); + if (unlikely(!pyname)) { + Py_DECREF(descr); + return -1; + } + int set_item_result = __Pyx_SetItemOnTypeDict(type, pyname, descr); + Py_DECREF(pyname); + #else + CYTHON_UNUSED_VAR(__Pyx__SetItemOnTypeDict); + int set_item_result = PyDict_SetItem(type->tp_dict, PyDescr_NAME(descr), descr); + #endif + Py_DECREF(descr); + if (unlikely(set_item_result < 0)) { + return -1; + } + changed = 1; + } + ++getset; + } + } +#else + CYTHON_UNUSED_VAR(__Pyx__SetItemOnTypeDict); +#endif // !CYTHON_COMPILING_IN_PYPY + if (changed) + PyType_Modified(type); +#endif // PY_VERSION_HEX > 0x030900B1 + return 0; +} + +/* PyObjectCallNoArg (used by PyObjectCallMethod0) */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func) { + PyObject *arg[2] = {NULL, NULL}; + return __Pyx_PyObject_FastCall(func, arg + 1, 0 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET); +} + +/* PyObjectGetMethod (used by PyObjectCallMethod0) */ +#if !(CYTHON_VECTORCALL && (__PYX_LIMITED_VERSION_HEX >= 0x030C0000 || (!CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x03090000))) +static int __Pyx_PyObject_GetMethod(PyObject *obj, PyObject *name, PyObject **method) { + PyObject *attr; +#if CYTHON_UNPACK_METHODS && CYTHON_COMPILING_IN_CPYTHON && CYTHON_USE_PYTYPE_LOOKUP + __Pyx_TypeName type_name; + PyTypeObject *tp = Py_TYPE(obj); + PyObject *descr; + descrgetfunc f = NULL; + PyObject **dictptr, *dict; + int meth_found = 0; + assert (*method == NULL); + if (unlikely(tp->tp_getattro != PyObject_GenericGetAttr)) { + attr = __Pyx_PyObject_GetAttrStr(obj, name); + goto try_unpack; + } + if (unlikely(tp->tp_dict == NULL) && unlikely(PyType_Ready(tp) < 0)) { + return 0; + } + descr = _PyType_Lookup(tp, name); + if (likely(descr != NULL)) { + Py_INCREF(descr); +#if defined(Py_TPFLAGS_METHOD_DESCRIPTOR) && Py_TPFLAGS_METHOD_DESCRIPTOR + if (__Pyx_PyType_HasFeature(Py_TYPE(descr), Py_TPFLAGS_METHOD_DESCRIPTOR)) +#else + #ifdef __Pyx_CyFunction_USED + if (likely(PyFunction_Check(descr) || __Pyx_IS_TYPE(descr, &PyMethodDescr_Type) || __Pyx_CyFunction_Check(descr))) + #else + if (likely(PyFunction_Check(descr) || __Pyx_IS_TYPE(descr, &PyMethodDescr_Type))) + #endif +#endif + { + meth_found = 1; + } else { + f = Py_TYPE(descr)->tp_descr_get; + if (f != NULL && PyDescr_IsData(descr)) { + attr = f(descr, obj, (PyObject *)Py_TYPE(obj)); + Py_DECREF(descr); + goto try_unpack; + } + } + } + dictptr = _PyObject_GetDictPtr(obj); + if (dictptr != NULL && (dict = *dictptr) != NULL) { + Py_INCREF(dict); + attr = __Pyx_PyDict_GetItemStr(dict, name); + if (attr != NULL) { + Py_INCREF(attr); + Py_DECREF(dict); + Py_XDECREF(descr); + goto try_unpack; + } + Py_DECREF(dict); + } + if (meth_found) { + *method = descr; + return 1; + } + if (f != NULL) { + attr = f(descr, obj, (PyObject *)Py_TYPE(obj)); + Py_DECREF(descr); + goto try_unpack; + } + if (likely(descr != NULL)) { + *method = descr; + return 0; + } + type_name = __Pyx_PyType_GetFullyQualifiedName(tp); + PyErr_Format(PyExc_AttributeError, + "'" __Pyx_FMT_TYPENAME "' object has no attribute '%U'", + type_name, name); + __Pyx_DECREF_TypeName(type_name); + return 0; +#else + attr = __Pyx_PyObject_GetAttrStr(obj, name); + goto try_unpack; +#endif +try_unpack: +#if CYTHON_UNPACK_METHODS + if (likely(attr) && PyMethod_Check(attr) && likely(PyMethod_GET_SELF(attr) == obj)) { + PyObject *function = PyMethod_GET_FUNCTION(attr); + Py_INCREF(function); + Py_DECREF(attr); + *method = function; + return 1; + } +#endif + *method = attr; + return 0; +} +#endif + +/* PyObjectCallMethod0 (used by PyType_Ready) */ +static PyObject* __Pyx_PyObject_CallMethod0(PyObject* obj, PyObject* method_name) { +#if CYTHON_VECTORCALL && (__PYX_LIMITED_VERSION_HEX >= 0x030C0000 || (!CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x03090000)) + PyObject *args[1] = {obj}; + (void) __Pyx_PyObject_CallOneArg; + (void) __Pyx_PyObject_CallNoArg; + return PyObject_VectorcallMethod(method_name, args, 1 | PY_VECTORCALL_ARGUMENTS_OFFSET, NULL); +#else + PyObject *method = NULL, *result = NULL; + int is_method = __Pyx_PyObject_GetMethod(obj, method_name, &method); + if (likely(is_method)) { + result = __Pyx_PyObject_CallOneArg(method, obj); + Py_DECREF(method); + return result; + } + if (unlikely(!method)) goto bad; + result = __Pyx_PyObject_CallNoArg(method); + Py_DECREF(method); +bad: + return result; +#endif +} + +/* ValidateBasesTuple (used by PyType_Ready) */ +#if CYTHON_COMPILING_IN_CPYTHON || CYTHON_COMPILING_IN_LIMITED_API || CYTHON_USE_TYPE_SPECS +static int __Pyx_validate_bases_tuple(const char *type_name, Py_ssize_t dictoffset, PyObject *bases) { + Py_ssize_t i, n; +#if CYTHON_ASSUME_SAFE_SIZE + n = PyTuple_GET_SIZE(bases); +#else + n = PyTuple_Size(bases); + if (unlikely(n < 0)) return -1; +#endif + for (i = 1; i < n; i++) + { + PyTypeObject *b; +#if CYTHON_AVOID_BORROWED_REFS + PyObject *b0 = PySequence_GetItem(bases, i); + if (!b0) return -1; +#elif CYTHON_ASSUME_SAFE_MACROS + PyObject *b0 = PyTuple_GET_ITEM(bases, i); +#else + PyObject *b0 = PyTuple_GetItem(bases, i); + if (!b0) return -1; +#endif + b = (PyTypeObject*) b0; + if (!__Pyx_PyType_HasFeature(b, Py_TPFLAGS_HEAPTYPE)) + { + __Pyx_TypeName b_name = __Pyx_PyType_GetFullyQualifiedName(b); + PyErr_Format(PyExc_TypeError, + "base class '" __Pyx_FMT_TYPENAME "' is not a heap type", b_name); + __Pyx_DECREF_TypeName(b_name); +#if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(b0); +#endif + return -1; + } + if (dictoffset == 0) + { + Py_ssize_t b_dictoffset = 0; +#if CYTHON_USE_TYPE_SLOTS + b_dictoffset = b->tp_dictoffset; +#else + PyObject *py_b_dictoffset = PyObject_GetAttrString((PyObject*)b, "__dictoffset__"); + if (!py_b_dictoffset) goto dictoffset_return; + b_dictoffset = PyLong_AsSsize_t(py_b_dictoffset); + Py_DECREF(py_b_dictoffset); + if (b_dictoffset == -1 && PyErr_Occurred()) goto dictoffset_return; +#endif + if (b_dictoffset) { + { + __Pyx_TypeName b_name = __Pyx_PyType_GetFullyQualifiedName(b); + PyErr_Format(PyExc_TypeError, + "extension type '%.200s' has no __dict__ slot, " + "but base type '" __Pyx_FMT_TYPENAME "' has: " + "either add 'cdef dict __dict__' to the extension type " + "or add '__slots__ = [...]' to the base type", + type_name, b_name); + __Pyx_DECREF_TypeName(b_name); + } +#if !CYTHON_USE_TYPE_SLOTS + dictoffset_return: +#endif +#if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(b0); +#endif + return -1; + } + } +#if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(b0); +#endif + } + return 0; +} +#endif + +/* PyType_Ready */ +CYTHON_UNUSED static int __Pyx_PyType_HasMultipleInheritance(PyTypeObject *t) { + while (t) { + PyObject *bases = __Pyx_PyType_GetSlot(t, tp_bases, PyObject*); + if (bases) { + return 1; + } + t = __Pyx_PyType_GetSlot(t, tp_base, PyTypeObject*); + } + return 0; +} +static int __Pyx_PyType_Ready(PyTypeObject *t) { +#if CYTHON_USE_TYPE_SPECS || !CYTHON_COMPILING_IN_CPYTHON || defined(PYSTON_MAJOR_VERSION) + (void)__Pyx_PyObject_CallMethod0; +#if CYTHON_USE_TYPE_SPECS + (void)__Pyx_validate_bases_tuple; +#endif + return PyType_Ready(t); +#else + int r; + if (!__Pyx_PyType_HasMultipleInheritance(t)) { + return PyType_Ready(t); + } + PyObject *bases = __Pyx_PyType_GetSlot(t, tp_bases, PyObject*); + if (bases && unlikely(__Pyx_validate_bases_tuple(t->tp_name, t->tp_dictoffset, bases) == -1)) + return -1; +#if !defined(PYSTON_MAJOR_VERSION) + { + int gc_was_enabled; + #if PY_VERSION_HEX >= 0x030A00b1 + gc_was_enabled = PyGC_Disable(); + (void)__Pyx_PyObject_CallMethod0; + #else + PyObject *ret, *py_status; + PyObject *gc = NULL; + #if (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM+0 >= 0x07030400) &&\ + !CYTHON_COMPILING_IN_GRAAL + gc = PyImport_GetModule(__pyx_mstate_global->__pyx_kp_u_gc); + #endif + if (unlikely(!gc)) gc = PyImport_Import(__pyx_mstate_global->__pyx_kp_u_gc); + if (unlikely(!gc)) return -1; + py_status = __Pyx_PyObject_CallMethod0(gc, __pyx_mstate_global->__pyx_kp_u_isenabled); + if (unlikely(!py_status)) { + Py_DECREF(gc); + return -1; + } + gc_was_enabled = __Pyx_PyObject_IsTrue(py_status); + Py_DECREF(py_status); + if (gc_was_enabled > 0) { + ret = __Pyx_PyObject_CallMethod0(gc, __pyx_mstate_global->__pyx_kp_u_disable); + if (unlikely(!ret)) { + Py_DECREF(gc); + return -1; + } + Py_DECREF(ret); + } else if (unlikely(gc_was_enabled == -1)) { + Py_DECREF(gc); + return -1; + } + #endif + t->tp_flags |= Py_TPFLAGS_HEAPTYPE; +#if PY_VERSION_HEX >= 0x030A0000 + t->tp_flags |= Py_TPFLAGS_IMMUTABLETYPE; +#endif +#else + (void)__Pyx_PyObject_CallMethod0; +#endif + r = PyType_Ready(t); +#if !defined(PYSTON_MAJOR_VERSION) + t->tp_flags &= ~Py_TPFLAGS_HEAPTYPE; + #if PY_VERSION_HEX >= 0x030A00b1 + if (gc_was_enabled) + PyGC_Enable(); + #else + if (gc_was_enabled) { + PyObject *tp, *v, *tb; + PyErr_Fetch(&tp, &v, &tb); + ret = __Pyx_PyObject_CallMethod0(gc, __pyx_mstate_global->__pyx_kp_u_enable); + if (likely(ret || r == -1)) { + Py_XDECREF(ret); + PyErr_Restore(tp, v, tb); + } else { + Py_XDECREF(tp); + Py_XDECREF(v); + Py_XDECREF(tb); + r = -1; + } + } + Py_DECREF(gc); + #endif + } +#endif + return r; +#endif +} + +/* SetVTable */ +static int __Pyx_SetVtable(PyTypeObject *type, void *vtable) { + PyObject *ob = PyCapsule_New(vtable, 0, 0); + if (unlikely(!ob)) + goto bad; +#if CYTHON_COMPILING_IN_LIMITED_API + if (unlikely(PyObject_SetAttr((PyObject *) type, __pyx_mstate_global->__pyx_n_u_pyx_vtable, ob) < 0)) +#else + if (unlikely(PyDict_SetItem(type->tp_dict, __pyx_mstate_global->__pyx_n_u_pyx_vtable, ob) < 0)) +#endif + goto bad; + Py_DECREF(ob); + return 0; +bad: + Py_XDECREF(ob); + return -1; +} + +/* GetVTable (used by MergeVTables) */ +static void* __Pyx_GetVtable(PyTypeObject *type) { + void* ptr; +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *ob = PyObject_GetAttr((PyObject *)type, __pyx_mstate_global->__pyx_n_u_pyx_vtable); +#else + PyObject *ob = PyObject_GetItem(type->tp_dict, __pyx_mstate_global->__pyx_n_u_pyx_vtable); +#endif + if (!ob) + goto bad; + ptr = PyCapsule_GetPointer(ob, 0); + if (!ptr && !PyErr_Occurred()) + PyErr_SetString(PyExc_RuntimeError, "invalid vtable found for imported type"); + Py_DECREF(ob); + return ptr; +bad: + Py_XDECREF(ob); + return NULL; +} + +/* MergeVTables */ +static int __Pyx_MergeVtables(PyTypeObject *type) { + int i=0; + Py_ssize_t size; + void** base_vtables; + __Pyx_TypeName tp_base_name = NULL; + __Pyx_TypeName base_name = NULL; + void* unknown = (void*)-1; + PyObject* bases = __Pyx_PyType_GetSlot(type, tp_bases, PyObject*); + int base_depth = 0; + { + PyTypeObject* base = __Pyx_PyType_GetSlot(type, tp_base, PyTypeObject*); + while (base) { + base_depth += 1; + base = __Pyx_PyType_GetSlot(base, tp_base, PyTypeObject*); + } + } + base_vtables = (void**) PyMem_Malloc(sizeof(void*) * (size_t)(base_depth + 1)); + base_vtables[0] = unknown; +#if CYTHON_COMPILING_IN_LIMITED_API + size = PyTuple_Size(bases); + if (size < 0) goto other_failure; +#else + size = PyTuple_GET_SIZE(bases); +#endif + for (i = 1; i < size; i++) { + PyObject *basei; + void* base_vtable; +#if CYTHON_AVOID_BORROWED_REFS + basei = PySequence_GetItem(bases, i); + if (unlikely(!basei)) goto other_failure; +#elif !CYTHON_ASSUME_SAFE_MACROS + basei = PyTuple_GetItem(bases, i); + if (unlikely(!basei)) goto other_failure; +#else + basei = PyTuple_GET_ITEM(bases, i); +#endif + base_vtable = __Pyx_GetVtable((PyTypeObject*)basei); +#if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(basei); +#endif + if (base_vtable != NULL) { + int j; + PyTypeObject* base = __Pyx_PyType_GetSlot(type, tp_base, PyTypeObject*); + for (j = 0; j < base_depth; j++) { + if (base_vtables[j] == unknown) { + base_vtables[j] = __Pyx_GetVtable(base); + base_vtables[j + 1] = unknown; + } + if (base_vtables[j] == base_vtable) { + break; + } else if (base_vtables[j] == NULL) { + goto bad; + } + base = __Pyx_PyType_GetSlot(base, tp_base, PyTypeObject*); + } + } + } + PyErr_Clear(); + PyMem_Free(base_vtables); + return 0; +bad: + { + PyTypeObject* basei = NULL; + PyTypeObject* tp_base = __Pyx_PyType_GetSlot(type, tp_base, PyTypeObject*); + tp_base_name = __Pyx_PyType_GetFullyQualifiedName(tp_base); +#if CYTHON_AVOID_BORROWED_REFS + basei = (PyTypeObject*)PySequence_GetItem(bases, i); + if (unlikely(!basei)) goto really_bad; +#elif !CYTHON_ASSUME_SAFE_MACROS + basei = (PyTypeObject*)PyTuple_GetItem(bases, i); + if (unlikely(!basei)) goto really_bad; +#else + basei = (PyTypeObject*)PyTuple_GET_ITEM(bases, i); +#endif + base_name = __Pyx_PyType_GetFullyQualifiedName(basei); +#if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(basei); +#endif + } + PyErr_Format(PyExc_TypeError, + "multiple bases have vtable conflict: '" __Pyx_FMT_TYPENAME "' and '" __Pyx_FMT_TYPENAME "'", tp_base_name, base_name); +#if CYTHON_AVOID_BORROWED_REFS || !CYTHON_ASSUME_SAFE_MACROS +really_bad: // bad has failed! +#endif + __Pyx_DECREF_TypeName(tp_base_name); + __Pyx_DECREF_TypeName(base_name); +#if CYTHON_COMPILING_IN_LIMITED_API || CYTHON_AVOID_BORROWED_REFS || !CYTHON_ASSUME_SAFE_MACROS +other_failure: +#endif + PyMem_Free(base_vtables); + return -1; +} + +/* DelItemOnTypeDict (used by SetupReduce) */ +static int __Pyx__DelItemOnTypeDict(PyTypeObject *tp, PyObject *k) { + int result; + PyObject *tp_dict; +#if CYTHON_COMPILING_IN_LIMITED_API + tp_dict = __Pyx_GetTypeDict(tp); + if (unlikely(!tp_dict)) return -1; +#else + tp_dict = tp->tp_dict; +#endif + result = PyDict_DelItem(tp_dict, k); + if (likely(!result)) PyType_Modified(tp); + return result; +} + +/* SetupReduce */ +static int __Pyx_setup_reduce_is_named(PyObject* meth, PyObject* name) { + int ret; + PyObject *name_attr; + name_attr = __Pyx_PyObject_GetAttrStrNoError(meth, __pyx_mstate_global->__pyx_n_u_name); + if (likely(name_attr)) { + ret = PyObject_RichCompareBool(name_attr, name, Py_EQ); + } else { + ret = -1; + } + if (unlikely(ret < 0)) { + PyErr_Clear(); + ret = 0; + } + Py_XDECREF(name_attr); + return ret; +} +static int __Pyx_setup_reduce(PyObject* type_obj) { + int ret = 0; + PyObject *object_reduce = NULL; + PyObject *object_getstate = NULL; + PyObject *object_reduce_ex = NULL; + PyObject *reduce = NULL; + PyObject *reduce_ex = NULL; + PyObject *reduce_cython = NULL; + PyObject *setstate = NULL; + PyObject *setstate_cython = NULL; + PyObject *getstate = NULL; +#if CYTHON_USE_PYTYPE_LOOKUP + getstate = _PyType_Lookup((PyTypeObject*)type_obj, __pyx_mstate_global->__pyx_n_u_getstate); +#else + getstate = __Pyx_PyObject_GetAttrStrNoError(type_obj, __pyx_mstate_global->__pyx_n_u_getstate); + if (!getstate && PyErr_Occurred()) { + goto __PYX_BAD; + } +#endif + if (getstate) { +#if CYTHON_USE_PYTYPE_LOOKUP + object_getstate = _PyType_Lookup(&PyBaseObject_Type, __pyx_mstate_global->__pyx_n_u_getstate); +#else + object_getstate = __Pyx_PyObject_GetAttrStrNoError((PyObject*)&PyBaseObject_Type, __pyx_mstate_global->__pyx_n_u_getstate); + if (!object_getstate && PyErr_Occurred()) { + goto __PYX_BAD; + } +#endif + if (object_getstate != getstate) { + goto __PYX_GOOD; + } + } +#if CYTHON_USE_PYTYPE_LOOKUP + object_reduce_ex = _PyType_Lookup(&PyBaseObject_Type, __pyx_mstate_global->__pyx_n_u_reduce_ex); if (!object_reduce_ex) goto __PYX_BAD; +#else + object_reduce_ex = __Pyx_PyObject_GetAttrStr((PyObject*)&PyBaseObject_Type, __pyx_mstate_global->__pyx_n_u_reduce_ex); if (!object_reduce_ex) goto __PYX_BAD; +#endif + reduce_ex = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_mstate_global->__pyx_n_u_reduce_ex); if (unlikely(!reduce_ex)) goto __PYX_BAD; + if (reduce_ex == object_reduce_ex) { +#if CYTHON_USE_PYTYPE_LOOKUP + object_reduce = _PyType_Lookup(&PyBaseObject_Type, __pyx_mstate_global->__pyx_n_u_reduce); if (!object_reduce) goto __PYX_BAD; +#else + object_reduce = __Pyx_PyObject_GetAttrStr((PyObject*)&PyBaseObject_Type, __pyx_mstate_global->__pyx_n_u_reduce); if (!object_reduce) goto __PYX_BAD; +#endif + reduce = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_mstate_global->__pyx_n_u_reduce); if (unlikely(!reduce)) goto __PYX_BAD; + if (reduce == object_reduce || __Pyx_setup_reduce_is_named(reduce, __pyx_mstate_global->__pyx_n_u_reduce_cython)) { + reduce_cython = __Pyx_PyObject_GetAttrStrNoError(type_obj, __pyx_mstate_global->__pyx_n_u_reduce_cython); + if (likely(reduce_cython)) { + ret = __Pyx_SetItemOnTypeDict((PyTypeObject*)type_obj, __pyx_mstate_global->__pyx_n_u_reduce, reduce_cython); if (unlikely(ret < 0)) goto __PYX_BAD; + ret = __Pyx_DelItemOnTypeDict((PyTypeObject*)type_obj, __pyx_mstate_global->__pyx_n_u_reduce_cython); if (unlikely(ret < 0)) goto __PYX_BAD; + } else if (reduce == object_reduce || PyErr_Occurred()) { + goto __PYX_BAD; + } + setstate = __Pyx_PyObject_GetAttrStrNoError(type_obj, __pyx_mstate_global->__pyx_n_u_setstate); + if (!setstate) PyErr_Clear(); + if (!setstate || __Pyx_setup_reduce_is_named(setstate, __pyx_mstate_global->__pyx_n_u_setstate_cython)) { + setstate_cython = __Pyx_PyObject_GetAttrStrNoError(type_obj, __pyx_mstate_global->__pyx_n_u_setstate_cython); + if (likely(setstate_cython)) { + ret = __Pyx_SetItemOnTypeDict((PyTypeObject*)type_obj, __pyx_mstate_global->__pyx_n_u_setstate, setstate_cython); if (unlikely(ret < 0)) goto __PYX_BAD; + ret = __Pyx_DelItemOnTypeDict((PyTypeObject*)type_obj, __pyx_mstate_global->__pyx_n_u_setstate_cython); if (unlikely(ret < 0)) goto __PYX_BAD; + } else if (!setstate || PyErr_Occurred()) { + goto __PYX_BAD; + } + } + PyType_Modified((PyTypeObject*)type_obj); + } + } + goto __PYX_GOOD; +__PYX_BAD: + if (!PyErr_Occurred()) { + __Pyx_TypeName type_obj_name = + __Pyx_PyType_GetFullyQualifiedName((PyTypeObject*)type_obj); + PyErr_Format(PyExc_RuntimeError, + "Unable to initialize pickling for " __Pyx_FMT_TYPENAME, type_obj_name); + __Pyx_DECREF_TypeName(type_obj_name); + } + ret = -1; +__PYX_GOOD: +#if !CYTHON_USE_PYTYPE_LOOKUP + Py_XDECREF(object_reduce); + Py_XDECREF(object_reduce_ex); + Py_XDECREF(object_getstate); + Py_XDECREF(getstate); +#endif + Py_XDECREF(reduce); + Py_XDECREF(reduce_ex); + Py_XDECREF(reduce_cython); + Py_XDECREF(setstate); + Py_XDECREF(setstate_cython); + return ret; +} + +/* dict_setdefault (used by FetchCommonType) */ +static CYTHON_INLINE PyObject *__Pyx_PyDict_SetDefault(PyObject *d, PyObject *key, PyObject *default_value) { + PyObject* value; +#if __PYX_LIMITED_VERSION_HEX >= 0x030F0000 || (!CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d00A4) + PyDict_SetDefaultRef(d, key, default_value, &value); +#elif CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX >= 0x030C0000 + PyObject *args[] = {d, key, default_value}; + value = PyObject_VectorcallMethod(__pyx_mstate_global->__pyx_n_u_setdefault, args, 3 | PY_VECTORCALL_ARGUMENTS_OFFSET, NULL); +#elif CYTHON_COMPILING_IN_LIMITED_API + value = PyObject_CallMethodObjArgs(d, __pyx_mstate_global->__pyx_n_u_setdefault, key, default_value, NULL); +#else + value = PyDict_SetDefault(d, key, default_value); + if (unlikely(!value)) return NULL; + Py_INCREF(value); +#endif + return value; +} + +/* AddModuleRef (used by FetchSharedCythonModule) */ +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + static PyObject *__Pyx_PyImport_AddModuleObjectRef(PyObject *name) { + PyObject *module_dict = PyImport_GetModuleDict(); + PyObject *m; + if (PyMapping_GetOptionalItem(module_dict, name, &m) < 0) { + return NULL; + } + if (m != NULL && PyModule_Check(m)) { + return m; + } + Py_XDECREF(m); + m = PyModule_NewObject(name); + if (m == NULL) + return NULL; + if (PyDict_CheckExact(module_dict)) { + PyObject *new_m; + (void)PyDict_SetDefaultRef(module_dict, name, m, &new_m); + Py_DECREF(m); + return new_m; + } else { + if (PyObject_SetItem(module_dict, name, m) != 0) { + Py_DECREF(m); + return NULL; + } + return m; + } + } + static PyObject *__Pyx_PyImport_AddModuleRef(const char *name) { + PyObject *py_name = PyUnicode_FromString(name); + if (!py_name) return NULL; + PyObject *module = __Pyx_PyImport_AddModuleObjectRef(py_name); + Py_DECREF(py_name); + return module; + } +#elif __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + #define __Pyx_PyImport_AddModuleRef(name) PyImport_AddModuleRef(name) +#else + static PyObject *__Pyx_PyImport_AddModuleRef(const char *name) { + PyObject *module = PyImport_AddModule(name); + Py_XINCREF(module); + return module; + } +#endif + +/* FetchSharedCythonModule (used by FetchCommonType) */ +static PyObject *__Pyx_FetchSharedCythonABIModule(void) { + return __Pyx_PyImport_AddModuleRef(__PYX_ABI_MODULE_NAME); +} + +/* FetchCommonType (used by CommonTypesMetaclass) */ +#if __PYX_LIMITED_VERSION_HEX < 0x030C0000 +static PyObject* __Pyx_PyType_FromMetaclass(PyTypeObject *metaclass, PyObject *module, PyType_Spec *spec, PyObject *bases) { + PyObject *result = __Pyx_PyType_FromModuleAndSpec(module, spec, bases); + if (result && metaclass) { + PyObject *old_tp = (PyObject*)Py_TYPE(result); + Py_INCREF((PyObject*)metaclass); +#if __PYX_LIMITED_VERSION_HEX >= 0x03090000 + Py_SET_TYPE(result, metaclass); +#else + result->ob_type = metaclass; +#endif + Py_DECREF(old_tp); + } + return result; +} +#else +#define __Pyx_PyType_FromMetaclass(me, mo, s, b) PyType_FromMetaclass(me, mo, s, b) +#endif +static int __Pyx_VerifyCachedType(PyObject *cached_type, + const char *name, + Py_ssize_t expected_basicsize) { + Py_ssize_t basicsize; + if (!PyType_Check(cached_type)) { + PyErr_Format(PyExc_TypeError, + "Shared Cython type %.200s is not a type object", name); + return -1; + } + if (expected_basicsize == 0) { + return 0; // size is inherited, nothing useful to check + } +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *py_basicsize; + py_basicsize = PyObject_GetAttrString(cached_type, "__basicsize__"); + if (unlikely(!py_basicsize)) return -1; + basicsize = PyLong_AsSsize_t(py_basicsize); + Py_DECREF(py_basicsize); + py_basicsize = NULL; + if (unlikely(basicsize == (Py_ssize_t)-1) && PyErr_Occurred()) return -1; +#else + basicsize = ((PyTypeObject*) cached_type)->tp_basicsize; +#endif + if (basicsize != expected_basicsize) { + PyErr_Format(PyExc_TypeError, + "Shared Cython type %.200s has the wrong size, try recompiling", + name); + return -1; + } + return 0; +} +static PyTypeObject *__Pyx_FetchCommonTypeFromSpec(PyTypeObject *metaclass, PyObject *module, PyType_Spec *spec, PyObject *bases) { + PyObject *abi_module = NULL, *cached_type = NULL, *abi_module_dict, *new_cached_type, *py_object_name; + int get_item_ref_result; + const char* object_name = strrchr(spec->name, '.'); + object_name = object_name ? object_name+1 : spec->name; + py_object_name = PyUnicode_FromString(object_name); + if (!py_object_name) return NULL; + abi_module = __Pyx_FetchSharedCythonABIModule(); + if (!abi_module) goto done; + abi_module_dict = PyModule_GetDict(abi_module); + if (!abi_module_dict) goto done; + get_item_ref_result = __Pyx_PyDict_GetItemRef(abi_module_dict, py_object_name, &cached_type); + if (get_item_ref_result == 1) { + if (__Pyx_VerifyCachedType( + cached_type, + object_name, + spec->basicsize) < 0) { + goto bad; + } + goto done; + } else if (unlikely(get_item_ref_result == -1)) { + goto bad; + } + cached_type = __Pyx_PyType_FromMetaclass( + metaclass, + CYTHON_USE_MODULE_STATE ? module : abi_module, + spec, bases); + if (unlikely(!cached_type)) goto bad; + if (unlikely(__Pyx_fix_up_extension_type_from_spec(spec, (PyTypeObject *) cached_type) < 0)) goto bad; + new_cached_type = __Pyx_PyDict_SetDefault(abi_module_dict, py_object_name, cached_type); + if (unlikely(new_cached_type != cached_type)) { + if (unlikely(!new_cached_type)) goto bad; + Py_DECREF(cached_type); + cached_type = new_cached_type; + if (__Pyx_VerifyCachedType( + cached_type, + object_name, + spec->basicsize) < 0) { + goto bad; + } + goto done; + } else { + Py_DECREF(new_cached_type); + } +done: + Py_XDECREF(abi_module); + Py_DECREF(py_object_name); + assert(cached_type == NULL || PyType_Check(cached_type)); + return (PyTypeObject *) cached_type; +bad: + Py_XDECREF(cached_type); + cached_type = NULL; + goto done; +} + +/* CommonTypesMetaclass (used by CythonFunctionShared) */ +static PyObject* __pyx_CommonTypesMetaclass_get_module(CYTHON_UNUSED PyObject *self, CYTHON_UNUSED void* context) { + return PyUnicode_FromString(__PYX_ABI_MODULE_NAME); +} +#if __PYX_LIMITED_VERSION_HEX < 0x030A0000 +static PyObject* __pyx_CommonTypesMetaclass_call(CYTHON_UNUSED PyObject *self, CYTHON_UNUSED PyObject *args, CYTHON_UNUSED PyObject *kwds) { + PyErr_SetString(PyExc_TypeError, "Cannot instantiate Cython internal types"); + return NULL; +} +static int __pyx_CommonTypesMetaclass_setattr(CYTHON_UNUSED PyObject *self, CYTHON_UNUSED PyObject *attr, CYTHON_UNUSED PyObject *value) { + PyErr_SetString(PyExc_TypeError, "Cython internal types are immutable"); + return -1; +} +#endif +static PyGetSetDef __pyx_CommonTypesMetaclass_getset[] = { + {"__module__", __pyx_CommonTypesMetaclass_get_module, NULL, NULL, NULL}, + {0, 0, 0, 0, 0} +}; +static PyType_Slot __pyx_CommonTypesMetaclass_slots[] = { + {Py_tp_getset, (void *)__pyx_CommonTypesMetaclass_getset}, + #if __PYX_LIMITED_VERSION_HEX < 0x030A0000 + {Py_tp_call, (void*)__pyx_CommonTypesMetaclass_call}, + {Py_tp_new, (void*)__pyx_CommonTypesMetaclass_call}, + {Py_tp_setattro, (void*)__pyx_CommonTypesMetaclass_setattr}, + #endif + {0, 0} +}; +static PyType_Spec __pyx_CommonTypesMetaclass_spec = { + __PYX_TYPE_MODULE_PREFIX "_common_types_metatype", + 0, + 0, + Py_TPFLAGS_IMMUTABLETYPE | + Py_TPFLAGS_DISALLOW_INSTANTIATION | + Py_TPFLAGS_DEFAULT, + __pyx_CommonTypesMetaclass_slots +}; +static int __pyx_CommonTypesMetaclass_init(PyObject *module) { + __pyx_mstatetype *mstate = __Pyx_PyModule_GetState(module); + PyObject *bases = PyTuple_Pack(1, &PyType_Type); + if (unlikely(!bases)) { + return -1; + } + mstate->__pyx_CommonTypesMetaclassType = __Pyx_FetchCommonTypeFromSpec(NULL, module, &__pyx_CommonTypesMetaclass_spec, bases); + Py_DECREF(bases); + if (unlikely(mstate->__pyx_CommonTypesMetaclassType == NULL)) { + return -1; + } + return 0; +} + +/* PyMethodNew (used by CythonFunctionShared) */ +#if CYTHON_COMPILING_IN_LIMITED_API +static PyObject *__Pyx_PyMethod_New(PyObject *func, PyObject *self, PyObject *typ) { + PyObject *result; + CYTHON_UNUSED_VAR(typ); + if (!self) + return __Pyx_NewRef(func); + #if __PYX_LIMITED_VERSION_HEX >= 0x030C0000 + { + PyObject *args[] = {func, self}; + result = PyObject_Vectorcall(__pyx_mstate_global->__Pyx_CachedMethodType, args, 2, NULL); + } + #else + result = PyObject_CallFunctionObjArgs(__pyx_mstate_global->__Pyx_CachedMethodType, func, self, NULL); + #endif + return result; +} +#else +static PyObject *__Pyx_PyMethod_New(PyObject *func, PyObject *self, PyObject *typ) { + CYTHON_UNUSED_VAR(typ); + if (!self) + return __Pyx_NewRef(func); + return PyMethod_New(func, self); +} +#endif + +/* PyVectorcallFastCallDict (used by CythonFunctionShared) */ +#if CYTHON_METH_FASTCALL && CYTHON_VECTORCALL +static PyObject *__Pyx_PyVectorcall_FastCallDict_kw(PyObject *func, __pyx_vectorcallfunc vc, PyObject *const *args, size_t nargs, PyObject *kw) +{ + PyObject *res = NULL; + PyObject *kwnames; + PyObject **newargs; + PyObject **kwvalues; + Py_ssize_t i; + #if CYTHON_AVOID_BORROWED_REFS + PyObject *pos; + #else + Py_ssize_t pos; + #endif + size_t j; + PyObject *key, *value; + unsigned long keys_are_strings; + #if !CYTHON_ASSUME_SAFE_SIZE + Py_ssize_t nkw = PyDict_Size(kw); + if (unlikely(nkw == -1)) return NULL; + #else + Py_ssize_t nkw = PyDict_GET_SIZE(kw); + #endif + newargs = (PyObject **)PyMem_Malloc((nargs + (size_t)nkw) * sizeof(args[0])); + if (unlikely(newargs == NULL)) { + PyErr_NoMemory(); + return NULL; + } + for (j = 0; j < nargs; j++) newargs[j] = args[j]; + kwnames = PyTuple_New(nkw); + if (unlikely(kwnames == NULL)) { + PyMem_Free(newargs); + return NULL; + } + kwvalues = newargs + nargs; + pos = 0; + i = 0; + keys_are_strings = Py_TPFLAGS_UNICODE_SUBCLASS; + while (__Pyx_PyDict_NextRef(kw, &pos, &key, &value)) { + keys_are_strings &= + #if CYTHON_COMPILING_IN_LIMITED_API + PyType_GetFlags(Py_TYPE(key)); + #else + Py_TYPE(key)->tp_flags; + #endif + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(PyTuple_SetItem(kwnames, i, key) < 0)) goto cleanup; + #else + PyTuple_SET_ITEM(kwnames, i, key); + #endif + kwvalues[i] = value; + i++; + } + if (unlikely(!keys_are_strings)) { + PyErr_SetString(PyExc_TypeError, "keywords must be strings"); + goto cleanup; + } + res = vc(func, newargs, nargs, kwnames); +cleanup: + #if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(pos); + #endif + Py_DECREF(kwnames); + for (i = 0; i < nkw; i++) + Py_DECREF(kwvalues[i]); + PyMem_Free(newargs); + return res; +} +static CYTHON_INLINE PyObject *__Pyx_PyVectorcall_FastCallDict(PyObject *func, __pyx_vectorcallfunc vc, PyObject *const *args, size_t nargs, PyObject *kw) +{ + Py_ssize_t kw_size = + likely(kw == NULL) ? + 0 : +#if !CYTHON_ASSUME_SAFE_SIZE + PyDict_Size(kw); +#else + PyDict_GET_SIZE(kw); +#endif + if (kw_size == 0) { + return vc(func, args, nargs, NULL); + } +#if !CYTHON_ASSUME_SAFE_SIZE + else if (unlikely(kw_size == -1)) { + return NULL; + } +#endif + return __Pyx_PyVectorcall_FastCallDict_kw(func, vc, args, nargs, kw); +} +#endif + +/* CythonFunctionShared (used by CythonFunction) */ +#if CYTHON_COMPILING_IN_LIMITED_API +static CYTHON_INLINE int __Pyx__IsSameCyOrCFunctionNoMethod(PyObject *func, void (*cfunc)(void)) { + if (__Pyx_CyFunction_Check(func)) { + return PyCFunction_GetFunction(((__pyx_CyFunctionObject*)func)->func) == (PyCFunction) cfunc; + } else if (PyCFunction_Check(func)) { + return PyCFunction_GetFunction(func) == (PyCFunction) cfunc; + } + return 0; +} +static CYTHON_INLINE int __Pyx__IsSameCyOrCFunction(PyObject *func, void (*cfunc)(void)) { + if ((PyObject*)Py_TYPE(func) == __pyx_mstate_global->__Pyx_CachedMethodType) { + int result; + PyObject *newFunc = PyObject_GetAttr(func, __pyx_mstate_global->__pyx_n_u_func); + if (unlikely(!newFunc)) { + PyErr_Clear(); // It's only an optimization, so don't throw an error + return 0; + } + result = __Pyx__IsSameCyOrCFunctionNoMethod(newFunc, cfunc); + Py_DECREF(newFunc); + return result; + } + return __Pyx__IsSameCyOrCFunctionNoMethod(func, cfunc); +} +#else +static CYTHON_INLINE int __Pyx__IsSameCyOrCFunction(PyObject *func, void (*cfunc)(void)) { + if (PyMethod_Check(func)) { + func = PyMethod_GET_FUNCTION(func); + } + return __Pyx_CyOrPyCFunction_Check(func) && __Pyx_CyOrPyCFunction_GET_FUNCTION(func) == (PyCFunction) cfunc; +} +#endif +static CYTHON_INLINE void __Pyx__CyFunction_SetClassObj(__pyx_CyFunctionObject* f, PyObject* classobj) { +#if PY_VERSION_HEX < 0x030900B1 || CYTHON_COMPILING_IN_LIMITED_API + __Pyx_Py_XDECREF_SET( + __Pyx_CyFunction_GetClassObj(f), + ((classobj) ? __Pyx_NewRef(classobj) : NULL)); +#else + __Pyx_Py_XDECREF_SET( + ((PyCMethodObject *) (f))->mm_class, + (PyTypeObject*)((classobj) ? __Pyx_NewRef(classobj) : NULL)); +#endif +} +static PyObject * +__Pyx_CyFunction_get_doc_locked(__pyx_CyFunctionObject *op) +{ + if (unlikely(op->func_doc == NULL)) { +#if CYTHON_COMPILING_IN_LIMITED_API + op->func_doc = PyObject_GetAttrString(op->func, "__doc__"); + if (unlikely(!op->func_doc)) return NULL; +#else + if (((PyCFunctionObject*)op)->m_ml->ml_doc) { + op->func_doc = PyUnicode_FromString(((PyCFunctionObject*)op)->m_ml->ml_doc); + if (unlikely(op->func_doc == NULL)) + return NULL; + } else { + Py_INCREF(Py_None); + return Py_None; + } +#endif + } + Py_INCREF(op->func_doc); + return op->func_doc; +} +static PyObject * +__Pyx_CyFunction_get_doc(__pyx_CyFunctionObject *op, void *closure) { + PyObject *result; + CYTHON_UNUSED_VAR(closure); + __Pyx_BEGIN_CRITICAL_SECTION(op); + result = __Pyx_CyFunction_get_doc_locked(op); + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static int +__Pyx_CyFunction_set_doc(__pyx_CyFunctionObject *op, PyObject *value, void *context) +{ + CYTHON_UNUSED_VAR(context); + if (value == NULL) { + value = Py_None; + } + Py_INCREF(value); + __Pyx_BEGIN_CRITICAL_SECTION(op); + __Pyx_Py_XDECREF_SET(op->func_doc, value); + __Pyx_END_CRITICAL_SECTION(); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_name_locked(__pyx_CyFunctionObject *op) +{ + if (unlikely(op->func_name == NULL)) { +#if CYTHON_COMPILING_IN_LIMITED_API + op->func_name = PyObject_GetAttrString(op->func, "__name__"); +#else + op->func_name = PyUnicode_InternFromString(((PyCFunctionObject*)op)->m_ml->ml_name); +#endif + if (unlikely(op->func_name == NULL)) + return NULL; + } + Py_INCREF(op->func_name); + return op->func_name; +} +static PyObject * +__Pyx_CyFunction_get_name(__pyx_CyFunctionObject *op, void *context) +{ + PyObject *result = NULL; + CYTHON_UNUSED_VAR(context); + __Pyx_BEGIN_CRITICAL_SECTION(op); + result = __Pyx_CyFunction_get_name_locked(op); + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static int +__Pyx_CyFunction_set_name(__pyx_CyFunctionObject *op, PyObject *value, void *context) +{ + CYTHON_UNUSED_VAR(context); + if (unlikely(value == NULL || !PyUnicode_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "__name__ must be set to a string object"); + return -1; + } + Py_INCREF(value); + __Pyx_BEGIN_CRITICAL_SECTION(op); + __Pyx_Py_XDECREF_SET(op->func_name, value); + __Pyx_END_CRITICAL_SECTION(); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_qualname(__pyx_CyFunctionObject *op, void *context) +{ + CYTHON_UNUSED_VAR(context); + PyObject *result; + __Pyx_BEGIN_CRITICAL_SECTION(op); + Py_INCREF(op->func_qualname); + result = op->func_qualname; + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static int +__Pyx_CyFunction_set_qualname(__pyx_CyFunctionObject *op, PyObject *value, void *context) +{ + CYTHON_UNUSED_VAR(context); + if (unlikely(value == NULL || !PyUnicode_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "__qualname__ must be set to a string object"); + return -1; + } + Py_INCREF(value); + __Pyx_BEGIN_CRITICAL_SECTION(op); + __Pyx_Py_XDECREF_SET(op->func_qualname, value); + __Pyx_END_CRITICAL_SECTION(); + return 0; +} +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000 +static PyObject * +__Pyx_CyFunction_get_dict(__pyx_CyFunctionObject *op, void *context) +{ + CYTHON_UNUSED_VAR(context); + if (unlikely(op->func_dict == NULL)) { + op->func_dict = PyDict_New(); + if (unlikely(op->func_dict == NULL)) + return NULL; + } + Py_INCREF(op->func_dict); + return op->func_dict; +} +#endif +static PyObject * +__Pyx_CyFunction_get_globals(__pyx_CyFunctionObject *op, void *context) +{ + CYTHON_UNUSED_VAR(context); + Py_INCREF(op->func_globals); + return op->func_globals; +} +static PyObject * +__Pyx_CyFunction_get_closure(__pyx_CyFunctionObject *op, void *context) +{ + CYTHON_UNUSED_VAR(op); + CYTHON_UNUSED_VAR(context); + Py_INCREF(Py_None); + return Py_None; +} +static PyObject * +__Pyx_CyFunction_get_code(__pyx_CyFunctionObject *op, void *context) +{ + PyObject* result = (op->func_code) ? op->func_code : Py_None; + CYTHON_UNUSED_VAR(context); + Py_INCREF(result); + return result; +} +static int +__Pyx_CyFunction_init_defaults(__pyx_CyFunctionObject *op) { + int result = 0; + PyObject *res = op->defaults_getter((PyObject *) op); + if (unlikely(!res)) + return -1; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + op->defaults_tuple = PyTuple_GET_ITEM(res, 0); + Py_INCREF(op->defaults_tuple); + op->defaults_kwdict = PyTuple_GET_ITEM(res, 1); + Py_INCREF(op->defaults_kwdict); + #else + op->defaults_tuple = __Pyx_PySequence_ITEM(res, 0); + if (unlikely(!op->defaults_tuple)) result = -1; + else { + op->defaults_kwdict = __Pyx_PySequence_ITEM(res, 1); + if (unlikely(!op->defaults_kwdict)) result = -1; + } + #endif + Py_DECREF(res); + return result; +} +static int +__Pyx_CyFunction_set_defaults(__pyx_CyFunctionObject *op, PyObject* value, void *context) { + CYTHON_UNUSED_VAR(context); + if (!value) { + value = Py_None; + } else if (unlikely(value != Py_None && !PyTuple_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "__defaults__ must be set to a tuple object"); + return -1; + } + PyErr_WarnEx(PyExc_RuntimeWarning, "changes to cyfunction.__defaults__ will not " + "currently affect the values used in function calls", 1); + Py_INCREF(value); + __Pyx_BEGIN_CRITICAL_SECTION(op); + __Pyx_Py_XDECREF_SET(op->defaults_tuple, value); + __Pyx_END_CRITICAL_SECTION(); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_defaults_locked(__pyx_CyFunctionObject *op) { + PyObject* result = op->defaults_tuple; + if (unlikely(!result)) { + if (op->defaults_getter) { + if (unlikely(__Pyx_CyFunction_init_defaults(op) < 0)) return NULL; + result = op->defaults_tuple; + } else { + result = Py_None; + } + } + Py_INCREF(result); + return result; +} +static PyObject * +__Pyx_CyFunction_get_defaults(__pyx_CyFunctionObject *op, void *context) { + PyObject* result = NULL; + CYTHON_UNUSED_VAR(context); + __Pyx_BEGIN_CRITICAL_SECTION(op); + result = __Pyx_CyFunction_get_defaults_locked(op); + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static int +__Pyx_CyFunction_set_kwdefaults(__pyx_CyFunctionObject *op, PyObject* value, void *context) { + CYTHON_UNUSED_VAR(context); + if (!value) { + value = Py_None; + } else if (unlikely(value != Py_None && !PyDict_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "__kwdefaults__ must be set to a dict object"); + return -1; + } + PyErr_WarnEx(PyExc_RuntimeWarning, "changes to cyfunction.__kwdefaults__ will not " + "currently affect the values used in function calls", 1); + Py_INCREF(value); + __Pyx_BEGIN_CRITICAL_SECTION(op); + __Pyx_Py_XDECREF_SET(op->defaults_kwdict, value); + __Pyx_END_CRITICAL_SECTION(); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_kwdefaults_locked(__pyx_CyFunctionObject *op) { + PyObject* result = op->defaults_kwdict; + if (unlikely(!result)) { + if (op->defaults_getter) { + if (unlikely(__Pyx_CyFunction_init_defaults(op) < 0)) return NULL; + result = op->defaults_kwdict; + } else { + result = Py_None; + } + } + Py_INCREF(result); + return result; +} +static PyObject * +__Pyx_CyFunction_get_kwdefaults(__pyx_CyFunctionObject *op, void *context) { + PyObject* result; + CYTHON_UNUSED_VAR(context); + __Pyx_BEGIN_CRITICAL_SECTION(op); + result = __Pyx_CyFunction_get_kwdefaults_locked(op); + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static int +__Pyx_CyFunction_set_annotations(__pyx_CyFunctionObject *op, PyObject* value, void *context) { + CYTHON_UNUSED_VAR(context); + if (!value || value == Py_None) { + value = NULL; + } else if (unlikely(!PyDict_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "__annotations__ must be set to a dict object"); + return -1; + } + Py_XINCREF(value); + __Pyx_BEGIN_CRITICAL_SECTION(op); + __Pyx_Py_XDECREF_SET(op->func_annotations, value); + __Pyx_END_CRITICAL_SECTION(); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_annotations_locked(__pyx_CyFunctionObject *op) { + PyObject* result = op->func_annotations; + if (unlikely(!result)) { + result = PyDict_New(); + if (unlikely(!result)) return NULL; + op->func_annotations = result; + } + Py_INCREF(result); + return result; +} +static PyObject * +__Pyx_CyFunction_get_annotations(__pyx_CyFunctionObject *op, void *context) { + PyObject *result; + CYTHON_UNUSED_VAR(context); + __Pyx_BEGIN_CRITICAL_SECTION(op); + result = __Pyx_CyFunction_get_annotations_locked(op); + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static PyObject * +__Pyx_CyFunction_get_is_coroutine_value(__pyx_CyFunctionObject *op) { + int is_coroutine = op->flags & __Pyx_CYFUNCTION_COROUTINE; + if (is_coroutine) { + PyObject *is_coroutine_value, *module, *fromlist, *marker = __pyx_mstate_global->__pyx_n_u_is_coroutine; + fromlist = PyList_New(1); + if (unlikely(!fromlist)) return NULL; + Py_INCREF(marker); +#if CYTHON_ASSUME_SAFE_MACROS + PyList_SET_ITEM(fromlist, 0, marker); +#else + if (unlikely(PyList_SetItem(fromlist, 0, marker) < 0)) { + Py_DECREF(marker); + Py_DECREF(fromlist); + return NULL; + } +#endif + module = PyImport_ImportModuleLevelObject(__pyx_mstate_global->__pyx_n_u_asyncio_coroutines, NULL, NULL, fromlist, 0); + Py_DECREF(fromlist); + if (unlikely(!module)) goto ignore; + is_coroutine_value = __Pyx_PyObject_GetAttrStr(module, marker); + Py_DECREF(module); + if (likely(is_coroutine_value)) { + return is_coroutine_value; + } +ignore: + PyErr_Clear(); + } + return __Pyx_PyBool_FromLong(is_coroutine); +} +static PyObject * +__Pyx_CyFunction_get_is_coroutine(__pyx_CyFunctionObject *op, void *context) { + PyObject *result; + CYTHON_UNUSED_VAR(context); + if (op->func_is_coroutine) { + return __Pyx_NewRef(op->func_is_coroutine); + } + result = __Pyx_CyFunction_get_is_coroutine_value(op); + if (unlikely(!result)) + return NULL; + __Pyx_BEGIN_CRITICAL_SECTION(op); + if (op->func_is_coroutine) { + Py_DECREF(result); + result = __Pyx_NewRef(op->func_is_coroutine); + } else { + op->func_is_coroutine = __Pyx_NewRef(result); + } + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static void __Pyx_CyFunction_raise_argument_count_error(__pyx_CyFunctionObject *func, const char* message, Py_ssize_t size) { +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *py_name = __Pyx_CyFunction_get_name(func, NULL); + if (!py_name) return; + PyErr_Format(PyExc_TypeError, + "%.200S() %s (%" CYTHON_FORMAT_SSIZE_T "d given)", + py_name, message, size); + Py_DECREF(py_name); +#else + const char* name = ((PyCFunctionObject*)func)->m_ml->ml_name; + PyErr_Format(PyExc_TypeError, + "%.200s() %s (%" CYTHON_FORMAT_SSIZE_T "d given)", + name, message, size); +#endif +} +static void __Pyx_CyFunction_raise_type_error(__pyx_CyFunctionObject *func, const char* message) { +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *py_name = __Pyx_CyFunction_get_name(func, NULL); + if (!py_name) return; + PyErr_Format(PyExc_TypeError, + "%.200S() %s", + py_name, message); + Py_DECREF(py_name); +#else + const char* name = ((PyCFunctionObject*)func)->m_ml->ml_name; + PyErr_Format(PyExc_TypeError, + "%.200s() %s", + name, message); +#endif +} +#if CYTHON_COMPILING_IN_LIMITED_API +static PyObject * +__Pyx_CyFunction_get_module(__pyx_CyFunctionObject *op, void *context) { + CYTHON_UNUSED_VAR(context); + return PyObject_GetAttrString(op->func, "__module__"); +} +static int +__Pyx_CyFunction_set_module(__pyx_CyFunctionObject *op, PyObject* value, void *context) { + CYTHON_UNUSED_VAR(context); + return PyObject_SetAttrString(op->func, "__module__", value); +} +#endif +static PyGetSetDef __pyx_CyFunction_getsets[] = { + {"func_doc", (getter)__Pyx_CyFunction_get_doc, (setter)__Pyx_CyFunction_set_doc, 0, 0}, + {"__doc__", (getter)__Pyx_CyFunction_get_doc, (setter)__Pyx_CyFunction_set_doc, 0, 0}, + {"func_name", (getter)__Pyx_CyFunction_get_name, (setter)__Pyx_CyFunction_set_name, 0, 0}, + {"__name__", (getter)__Pyx_CyFunction_get_name, (setter)__Pyx_CyFunction_set_name, 0, 0}, + {"__qualname__", (getter)__Pyx_CyFunction_get_qualname, (setter)__Pyx_CyFunction_set_qualname, 0, 0}, +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000 + {"func_dict", (getter)__Pyx_CyFunction_get_dict, (setter)PyObject_GenericSetDict, 0, 0}, + {"__dict__", (getter)__Pyx_CyFunction_get_dict, (setter)PyObject_GenericSetDict, 0, 0}, +#else + {"func_dict", (getter)PyObject_GenericGetDict, (setter)PyObject_GenericSetDict, 0, 0}, + {"__dict__", (getter)PyObject_GenericGetDict, (setter)PyObject_GenericSetDict, 0, 0}, +#endif + {"func_globals", (getter)__Pyx_CyFunction_get_globals, 0, 0, 0}, + {"__globals__", (getter)__Pyx_CyFunction_get_globals, 0, 0, 0}, + {"func_closure", (getter)__Pyx_CyFunction_get_closure, 0, 0, 0}, + {"__closure__", (getter)__Pyx_CyFunction_get_closure, 0, 0, 0}, + {"func_code", (getter)__Pyx_CyFunction_get_code, 0, 0, 0}, + {"__code__", (getter)__Pyx_CyFunction_get_code, 0, 0, 0}, + {"func_defaults", (getter)__Pyx_CyFunction_get_defaults, (setter)__Pyx_CyFunction_set_defaults, 0, 0}, + {"__defaults__", (getter)__Pyx_CyFunction_get_defaults, (setter)__Pyx_CyFunction_set_defaults, 0, 0}, + {"__kwdefaults__", (getter)__Pyx_CyFunction_get_kwdefaults, (setter)__Pyx_CyFunction_set_kwdefaults, 0, 0}, + {"__annotations__", (getter)__Pyx_CyFunction_get_annotations, (setter)__Pyx_CyFunction_set_annotations, 0, 0}, + {"_is_coroutine", (getter)__Pyx_CyFunction_get_is_coroutine, 0, 0, 0}, +#if CYTHON_COMPILING_IN_LIMITED_API + {"__module__", (getter)__Pyx_CyFunction_get_module, (setter)__Pyx_CyFunction_set_module, 0, 0}, +#endif + {0, 0, 0, 0, 0} +}; +static PyMemberDef __pyx_CyFunction_members[] = { +#if !CYTHON_COMPILING_IN_LIMITED_API + {"__module__", T_OBJECT, offsetof(PyCFunctionObject, m_module), 0, 0}, +#endif +#if PY_VERSION_HEX < 0x030C0000 || CYTHON_COMPILING_IN_LIMITED_API + {"__dictoffset__", T_PYSSIZET, offsetof(__pyx_CyFunctionObject, func_dict), READONLY, 0}, +#endif +#if CYTHON_METH_FASTCALL +#if CYTHON_COMPILING_IN_LIMITED_API + {"__vectorcalloffset__", T_PYSSIZET, offsetof(__pyx_CyFunctionObject, func_vectorcall), READONLY, 0}, +#else + {"__vectorcalloffset__", T_PYSSIZET, offsetof(PyCFunctionObject, vectorcall), READONLY, 0}, +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + {"__weaklistoffset__", T_PYSSIZET, offsetof(__pyx_CyFunctionObject, func_weakreflist), READONLY, 0}, +#else + {"__weaklistoffset__", T_PYSSIZET, offsetof(PyCFunctionObject, m_weakreflist), READONLY, 0}, +#endif +#endif + {0, 0, 0, 0, 0} +}; +static PyObject * +__Pyx_CyFunction_reduce(__pyx_CyFunctionObject *m, PyObject *args) +{ + PyObject *result = NULL; + CYTHON_UNUSED_VAR(args); + __Pyx_BEGIN_CRITICAL_SECTION(m); + Py_INCREF(m->func_qualname); + result = m->func_qualname; + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static PyMethodDef __pyx_CyFunction_methods[] = { + {"__reduce__", (PyCFunction)__Pyx_CyFunction_reduce, METH_VARARGS, 0}, + {0, 0, 0, 0} +}; +#if CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_CyFunction_weakreflist(cyfunc) ((cyfunc)->func_weakreflist) +#else +#define __Pyx_CyFunction_weakreflist(cyfunc) (((PyCFunctionObject*)cyfunc)->m_weakreflist) +#endif +static PyObject *__Pyx_CyFunction_Init(__pyx_CyFunctionObject *op, PyMethodDef *ml, int flags, PyObject* qualname, + PyObject *closure, PyObject *module, PyObject* globals, PyObject* code) { +#if !CYTHON_COMPILING_IN_LIMITED_API + PyCFunctionObject *cf = (PyCFunctionObject*) op; +#endif + if (unlikely(op == NULL)) + return NULL; +#if CYTHON_COMPILING_IN_LIMITED_API + op->func = PyCFunction_NewEx(ml, (PyObject*)op, module); + if (unlikely(!op->func)) return NULL; +#endif + op->flags = flags; + __Pyx_CyFunction_weakreflist(op) = NULL; +#if !CYTHON_COMPILING_IN_LIMITED_API + cf->m_ml = ml; + cf->m_self = (PyObject *) op; +#endif + Py_XINCREF(closure); + op->func_closure = closure; +#if !CYTHON_COMPILING_IN_LIMITED_API + Py_XINCREF(module); + cf->m_module = module; +#endif +#if PY_VERSION_HEX < 0x030C0000 || CYTHON_COMPILING_IN_LIMITED_API + op->func_dict = NULL; +#endif + op->func_name = NULL; + Py_INCREF(qualname); + op->func_qualname = qualname; + op->func_doc = NULL; +#if PY_VERSION_HEX < 0x030900B1 || CYTHON_COMPILING_IN_LIMITED_API + op->func_classobj = NULL; +#else + ((PyCMethodObject*)op)->mm_class = NULL; +#endif + op->func_globals = globals; + Py_INCREF(op->func_globals); + Py_XINCREF(code); + op->func_code = code; + op->defaults = NULL; + op->defaults_tuple = NULL; + op->defaults_kwdict = NULL; + op->defaults_getter = NULL; + op->func_annotations = NULL; + op->func_is_coroutine = NULL; +#if CYTHON_METH_FASTCALL + switch (ml->ml_flags & (METH_VARARGS | METH_FASTCALL | METH_NOARGS | METH_O | METH_KEYWORDS | METH_METHOD)) { + case METH_NOARGS: + __Pyx_CyFunction_func_vectorcall(op) = __Pyx_CyFunction_Vectorcall_NOARGS; + break; + case METH_O: + __Pyx_CyFunction_func_vectorcall(op) = __Pyx_CyFunction_Vectorcall_O; + break; + case METH_METHOD | METH_FASTCALL | METH_KEYWORDS: + __Pyx_CyFunction_func_vectorcall(op) = __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS_METHOD; + break; + case METH_FASTCALL | METH_KEYWORDS: + __Pyx_CyFunction_func_vectorcall(op) = __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS; + break; + case METH_VARARGS | METH_KEYWORDS: + __Pyx_CyFunction_func_vectorcall(op) = NULL; + break; + default: + PyErr_SetString(PyExc_SystemError, "Bad call flags for CyFunction"); + Py_DECREF(op); + return NULL; + } +#endif + return (PyObject *) op; +} +static int +__Pyx_CyFunction_clear(__pyx_CyFunctionObject *m) +{ + Py_CLEAR(m->func_closure); +#if CYTHON_COMPILING_IN_LIMITED_API + Py_CLEAR(m->func); +#else + Py_CLEAR(((PyCFunctionObject*)m)->m_module); +#endif +#if PY_VERSION_HEX < 0x030C0000 || CYTHON_COMPILING_IN_LIMITED_API + Py_CLEAR(m->func_dict); +#elif PY_VERSION_HEX < 0x030d0000 + _PyObject_ClearManagedDict((PyObject*)m); +#else + PyObject_ClearManagedDict((PyObject*)m); +#endif + Py_CLEAR(m->func_name); + Py_CLEAR(m->func_qualname); + Py_CLEAR(m->func_doc); + Py_CLEAR(m->func_globals); + Py_CLEAR(m->func_code); +#if !CYTHON_COMPILING_IN_LIMITED_API +#if PY_VERSION_HEX < 0x030900B1 + Py_CLEAR(__Pyx_CyFunction_GetClassObj(m)); +#else + { + PyObject *cls = (PyObject*) ((PyCMethodObject *) (m))->mm_class; + ((PyCMethodObject *) (m))->mm_class = NULL; + Py_XDECREF(cls); + } +#endif +#endif + Py_CLEAR(m->defaults_tuple); + Py_CLEAR(m->defaults_kwdict); + Py_CLEAR(m->func_annotations); + Py_CLEAR(m->func_is_coroutine); + Py_CLEAR(m->defaults); + return 0; +} +static void __Pyx__CyFunction_dealloc(__pyx_CyFunctionObject *m) +{ + if (__Pyx_CyFunction_weakreflist(m) != NULL) + PyObject_ClearWeakRefs((PyObject *) m); + __Pyx_CyFunction_clear(m); + __Pyx_PyHeapTypeObject_GC_Del(m); +} +static void __Pyx_CyFunction_dealloc(__pyx_CyFunctionObject *m) +{ + PyObject_GC_UnTrack(m); + __Pyx__CyFunction_dealloc(m); +} +static int __Pyx_CyFunction_traverse(__pyx_CyFunctionObject *m, visitproc visit, void *arg) +{ + { + int e = __Pyx_call_type_traverse((PyObject*)m, 1, visit, arg); + if (e) return e; + } + Py_VISIT(m->func_closure); +#if CYTHON_COMPILING_IN_LIMITED_API + Py_VISIT(m->func); +#else + Py_VISIT(((PyCFunctionObject*)m)->m_module); +#endif +#if PY_VERSION_HEX < 0x030C0000 || CYTHON_COMPILING_IN_LIMITED_API + Py_VISIT(m->func_dict); +#else + { + int e = +#if PY_VERSION_HEX < 0x030d0000 + _PyObject_VisitManagedDict +#else + PyObject_VisitManagedDict +#endif + ((PyObject*)m, visit, arg); + if (e != 0) return e; + } +#endif + __Pyx_VISIT_CONST(m->func_name); + __Pyx_VISIT_CONST(m->func_qualname); + Py_VISIT(m->func_doc); + Py_VISIT(m->func_globals); + __Pyx_VISIT_CONST(m->func_code); +#if !CYTHON_COMPILING_IN_LIMITED_API + Py_VISIT(__Pyx_CyFunction_GetClassObj(m)); +#endif + Py_VISIT(m->defaults_tuple); + Py_VISIT(m->defaults_kwdict); + Py_VISIT(m->func_is_coroutine); + Py_VISIT(m->defaults); + return 0; +} +static PyObject* +__Pyx_CyFunction_repr(__pyx_CyFunctionObject *op) +{ + PyObject *repr; + __Pyx_BEGIN_CRITICAL_SECTION(op); + repr = PyUnicode_FromFormat("", + op->func_qualname, (void *)op); + __Pyx_END_CRITICAL_SECTION(); + return repr; +} +static PyObject * __Pyx_CyFunction_CallMethod(PyObject *func, PyObject *self, PyObject *arg, PyObject *kw) { +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *f = ((__pyx_CyFunctionObject*)func)->func; + PyCFunction meth; + int flags; + meth = PyCFunction_GetFunction(f); + if (unlikely(!meth)) return NULL; + flags = PyCFunction_GetFlags(f); + if (unlikely(flags < 0)) return NULL; +#else + PyCFunctionObject* f = (PyCFunctionObject*)func; + PyCFunction meth = f->m_ml->ml_meth; + int flags = f->m_ml->ml_flags; +#endif + Py_ssize_t size; + switch (flags & (METH_VARARGS | METH_KEYWORDS | METH_NOARGS | METH_O)) { + case METH_VARARGS: + if (likely(kw == NULL || PyDict_Size(kw) == 0)) + return (*meth)(self, arg); + break; + case METH_VARARGS | METH_KEYWORDS: + return (*(PyCFunctionWithKeywords)(void(*)(void))meth)(self, arg, kw); + case METH_NOARGS: + if (likely(kw == NULL || PyDict_Size(kw) == 0)) { +#if CYTHON_ASSUME_SAFE_SIZE + size = PyTuple_GET_SIZE(arg); +#else + size = PyTuple_Size(arg); + if (unlikely(size < 0)) return NULL; +#endif + if (likely(size == 0)) + return (*meth)(self, NULL); + __Pyx_CyFunction_raise_argument_count_error( + (__pyx_CyFunctionObject*)func, + "takes no arguments", size); + return NULL; + } + break; + case METH_O: + if (likely(kw == NULL || PyDict_Size(kw) == 0)) { +#if CYTHON_ASSUME_SAFE_SIZE + size = PyTuple_GET_SIZE(arg); +#else + size = PyTuple_Size(arg); + if (unlikely(size < 0)) return NULL; +#endif + if (likely(size == 1)) { + PyObject *result, *arg0; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + arg0 = PyTuple_GET_ITEM(arg, 0); + #else + arg0 = __Pyx_PySequence_ITEM(arg, 0); if (unlikely(!arg0)) return NULL; + #endif + result = (*meth)(self, arg0); + #if !(CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS) + Py_DECREF(arg0); + #endif + return result; + } + __Pyx_CyFunction_raise_argument_count_error( + (__pyx_CyFunctionObject*)func, + "takes exactly one argument", size); + return NULL; + } + break; + default: + PyErr_SetString(PyExc_SystemError, "Bad call flags for CyFunction"); + return NULL; + } + __Pyx_CyFunction_raise_type_error( + (__pyx_CyFunctionObject*)func, "takes no keyword arguments"); + return NULL; +} +static CYTHON_INLINE PyObject *__Pyx_CyFunction_Call(PyObject *func, PyObject *arg, PyObject *kw) { + PyObject *self, *result; +#if CYTHON_COMPILING_IN_LIMITED_API + self = PyCFunction_GetSelf(((__pyx_CyFunctionObject*)func)->func); + if (unlikely(!self) && PyErr_Occurred()) return NULL; +#else + self = ((PyCFunctionObject*)func)->m_self; +#endif + result = __Pyx_CyFunction_CallMethod(func, self, arg, kw); + return result; +} +static PyObject *__Pyx_CyFunction_CallAsMethod(PyObject *func, PyObject *args, PyObject *kw) { + PyObject *result; + __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *) func; +#if CYTHON_METH_FASTCALL && CYTHON_VECTORCALL + __pyx_vectorcallfunc vc = __Pyx_CyFunction_func_vectorcall(cyfunc); + if (vc) { +#if CYTHON_ASSUME_SAFE_MACROS && CYTHON_ASSUME_SAFE_SIZE + return __Pyx_PyVectorcall_FastCallDict(func, vc, &PyTuple_GET_ITEM(args, 0), (size_t)PyTuple_GET_SIZE(args), kw); +#else + (void) &__Pyx_PyVectorcall_FastCallDict; + return PyVectorcall_Call(func, args, kw); +#endif + } +#endif + if ((cyfunc->flags & __Pyx_CYFUNCTION_CCLASS) && !(cyfunc->flags & __Pyx_CYFUNCTION_STATICMETHOD)) { + Py_ssize_t argc; + PyObject *new_args; + PyObject *self; +#if CYTHON_ASSUME_SAFE_SIZE + argc = PyTuple_GET_SIZE(args); +#else + argc = PyTuple_Size(args); + if (unlikely(argc < 0)) return NULL; +#endif + new_args = PyTuple_GetSlice(args, 1, argc); + if (unlikely(!new_args)) + return NULL; + self = PyTuple_GetItem(args, 0); + if (unlikely(!self)) { + Py_DECREF(new_args); + PyErr_Format(PyExc_TypeError, + "unbound method %.200S() needs an argument", + cyfunc->func_qualname); + return NULL; + } + result = __Pyx_CyFunction_CallMethod(func, self, new_args, kw); + Py_DECREF(new_args); + } else { + result = __Pyx_CyFunction_Call(func, args, kw); + } + return result; +} +#if CYTHON_METH_FASTCALL && CYTHON_VECTORCALL +static CYTHON_INLINE int __Pyx_CyFunction_Vectorcall_CheckArgs(__pyx_CyFunctionObject *cyfunc, Py_ssize_t nargs, PyObject *kwnames) +{ + int ret = 0; + if ((cyfunc->flags & __Pyx_CYFUNCTION_CCLASS) && !(cyfunc->flags & __Pyx_CYFUNCTION_STATICMETHOD)) { + if (unlikely(nargs < 1)) { + __Pyx_CyFunction_raise_type_error( + cyfunc, "needs an argument"); + return -1; + } + ret = 1; + } + if (unlikely(kwnames) && unlikely(__Pyx_PyTuple_GET_SIZE(kwnames))) { + __Pyx_CyFunction_raise_type_error( + cyfunc, "takes no keyword arguments"); + return -1; + } + return ret; +} +static PyObject * __Pyx_CyFunction_Vectorcall_NOARGS(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames) +{ + __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *)func; + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); + PyObject *self; +#if CYTHON_COMPILING_IN_LIMITED_API + PyCFunction meth = PyCFunction_GetFunction(cyfunc->func); + if (unlikely(!meth)) return NULL; +#else + PyCFunction meth = ((PyCFunctionObject*)cyfunc)->m_ml->ml_meth; +#endif + switch (__Pyx_CyFunction_Vectorcall_CheckArgs(cyfunc, nargs, kwnames)) { + case 1: + self = args[0]; + args += 1; + nargs -= 1; + break; + case 0: +#if CYTHON_COMPILING_IN_LIMITED_API + self = PyCFunction_GetSelf(((__pyx_CyFunctionObject*)cyfunc)->func); + if (unlikely(!self) && PyErr_Occurred()) return NULL; +#else + self = ((PyCFunctionObject*)cyfunc)->m_self; +#endif + break; + default: + return NULL; + } + if (unlikely(nargs != 0)) { + __Pyx_CyFunction_raise_argument_count_error( + cyfunc, "takes no arguments", nargs); + return NULL; + } + return meth(self, NULL); +} +static PyObject * __Pyx_CyFunction_Vectorcall_O(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames) +{ + __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *)func; + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); + PyObject *self; +#if CYTHON_COMPILING_IN_LIMITED_API + PyCFunction meth = PyCFunction_GetFunction(cyfunc->func); + if (unlikely(!meth)) return NULL; +#else + PyCFunction meth = ((PyCFunctionObject*)cyfunc)->m_ml->ml_meth; +#endif + switch (__Pyx_CyFunction_Vectorcall_CheckArgs(cyfunc, nargs, kwnames)) { + case 1: + self = args[0]; + args += 1; + nargs -= 1; + break; + case 0: +#if CYTHON_COMPILING_IN_LIMITED_API + self = PyCFunction_GetSelf(((__pyx_CyFunctionObject*)cyfunc)->func); + if (unlikely(!self) && PyErr_Occurred()) return NULL; +#else + self = ((PyCFunctionObject*)cyfunc)->m_self; +#endif + break; + default: + return NULL; + } + if (unlikely(nargs != 1)) { + __Pyx_CyFunction_raise_argument_count_error( + cyfunc, "takes exactly one argument", nargs); + return NULL; + } + return meth(self, args[0]); +} +static PyObject * __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames) +{ + __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *)func; + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); + PyObject *self; +#if CYTHON_COMPILING_IN_LIMITED_API + PyCFunction meth = PyCFunction_GetFunction(cyfunc->func); + if (unlikely(!meth)) return NULL; +#else + PyCFunction meth = ((PyCFunctionObject*)cyfunc)->m_ml->ml_meth; +#endif + switch (__Pyx_CyFunction_Vectorcall_CheckArgs(cyfunc, nargs, NULL)) { + case 1: + self = args[0]; + args += 1; + nargs -= 1; + break; + case 0: +#if CYTHON_COMPILING_IN_LIMITED_API + self = PyCFunction_GetSelf(((__pyx_CyFunctionObject*)cyfunc)->func); + if (unlikely(!self) && PyErr_Occurred()) return NULL; +#else + self = ((PyCFunctionObject*)cyfunc)->m_self; +#endif + break; + default: + return NULL; + } + return ((__Pyx_PyCFunctionFastWithKeywords)(void(*)(void))meth)(self, args, nargs, kwnames); +} +static PyObject * __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS_METHOD(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames) +{ + __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *)func; + PyTypeObject *cls = (PyTypeObject *) __Pyx_CyFunction_GetClassObj(cyfunc); + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); + PyObject *self; +#if CYTHON_COMPILING_IN_LIMITED_API + PyCFunction meth = PyCFunction_GetFunction(cyfunc->func); + if (unlikely(!meth)) return NULL; +#else + PyCFunction meth = ((PyCFunctionObject*)cyfunc)->m_ml->ml_meth; +#endif + switch (__Pyx_CyFunction_Vectorcall_CheckArgs(cyfunc, nargs, NULL)) { + case 1: + self = args[0]; + args += 1; + nargs -= 1; + break; + case 0: +#if CYTHON_COMPILING_IN_LIMITED_API + self = PyCFunction_GetSelf(((__pyx_CyFunctionObject*)cyfunc)->func); + if (unlikely(!self) && PyErr_Occurred()) return NULL; +#else + self = ((PyCFunctionObject*)cyfunc)->m_self; +#endif + break; + default: + return NULL; + } + #if PY_VERSION_HEX < 0x030e00A6 + size_t nargs_value = (size_t) nargs; + #else + Py_ssize_t nargs_value = nargs; + #endif + return ((__Pyx_PyCMethod)(void(*)(void))meth)(self, cls, args, nargs_value, kwnames); +} +#endif +static PyType_Slot __pyx_CyFunctionType_slots[] = { + {Py_tp_dealloc, (void *)__Pyx_CyFunction_dealloc}, + {Py_tp_repr, (void *)__Pyx_CyFunction_repr}, + {Py_tp_call, (void *)__Pyx_CyFunction_CallAsMethod}, + {Py_tp_traverse, (void *)__Pyx_CyFunction_traverse}, + {Py_tp_clear, (void *)__Pyx_CyFunction_clear}, + {Py_tp_methods, (void *)__pyx_CyFunction_methods}, + {Py_tp_members, (void *)__pyx_CyFunction_members}, + {Py_tp_getset, (void *)__pyx_CyFunction_getsets}, + {Py_tp_descr_get, (void *)__Pyx_PyMethod_New}, + {0, 0}, +}; +static PyType_Spec __pyx_CyFunctionType_spec = { + __PYX_TYPE_MODULE_PREFIX "cython_function_or_method", + sizeof(__pyx_CyFunctionObject), + 0, +#ifdef Py_TPFLAGS_METHOD_DESCRIPTOR + Py_TPFLAGS_METHOD_DESCRIPTOR | +#endif +#if CYTHON_METH_FASTCALL +#if defined(Py_TPFLAGS_HAVE_VECTORCALL) + Py_TPFLAGS_HAVE_VECTORCALL | +#elif defined(_Py_TPFLAGS_HAVE_VECTORCALL) + _Py_TPFLAGS_HAVE_VECTORCALL | +#endif +#endif // CYTHON_METH_FASTCALL +#if PY_VERSION_HEX >= 0x030C0000 && !CYTHON_COMPILING_IN_LIMITED_API + Py_TPFLAGS_MANAGED_DICT | +#endif + Py_TPFLAGS_IMMUTABLETYPE | Py_TPFLAGS_DISALLOW_INSTANTIATION | + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, + __pyx_CyFunctionType_slots +}; +static int __pyx_CyFunction_init(PyObject *module) { + __pyx_mstatetype *mstate = __Pyx_PyModule_GetState(module); + mstate->__pyx_CyFunctionType = __Pyx_FetchCommonTypeFromSpec( + mstate->__pyx_CommonTypesMetaclassType, module, &__pyx_CyFunctionType_spec, NULL); + if (unlikely(mstate->__pyx_CyFunctionType == NULL)) { + return -1; + } + return 0; +} +static CYTHON_INLINE PyObject *__Pyx_CyFunction_InitDefaults(PyObject *func, PyTypeObject *defaults_type) { + __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; + m->defaults = PyObject_CallObject((PyObject*)defaults_type, NULL); // _PyObject_New(defaults_type); + if (unlikely(!m->defaults)) + return NULL; + return m->defaults; +} +static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsTuple(PyObject *func, PyObject *tuple) { + __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; + m->defaults_tuple = tuple; + Py_INCREF(tuple); +} +static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsKwDict(PyObject *func, PyObject *dict) { + __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; + m->defaults_kwdict = dict; + Py_INCREF(dict); +} +static CYTHON_INLINE void __Pyx_CyFunction_SetAnnotationsDict(PyObject *func, PyObject *dict) { + __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; + m->func_annotations = dict; + Py_INCREF(dict); +} + +/* CythonFunction */ +static PyObject *__Pyx_CyFunction_New(PyMethodDef *ml, int flags, PyObject* qualname, + PyObject *closure, PyObject *module, PyObject* globals, PyObject* code) { + PyObject *op = __Pyx_CyFunction_Init( + PyObject_GC_New(__pyx_CyFunctionObject, __pyx_mstate_global->__pyx_CyFunctionType), + ml, flags, qualname, closure, module, globals, code + ); + if (likely(op)) { + PyObject_GC_Track(op); + } + return op; +} + +/* CLineInTraceback (used by AddTraceback) */ +#if CYTHON_CLINE_IN_TRACEBACK && CYTHON_CLINE_IN_TRACEBACK_RUNTIME +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000 +#define __Pyx_PyProbablyModule_GetDict(o) __Pyx_XNewRef(PyModule_GetDict(o)) +#elif !CYTHON_COMPILING_IN_CPYTHON || CYTHON_COMPILING_IN_CPYTHON_FREETHREADING +#define __Pyx_PyProbablyModule_GetDict(o) PyObject_GenericGetDict(o, NULL); +#else +PyObject* __Pyx_PyProbablyModule_GetDict(PyObject *o) { + PyObject **dict_ptr = _PyObject_GetDictPtr(o); + return dict_ptr ? __Pyx_XNewRef(*dict_ptr) : NULL; +} +#endif +static int __Pyx_CLineForTraceback(PyThreadState *tstate, int c_line) { + PyObject *use_cline = NULL; + PyObject *ptype, *pvalue, *ptraceback; + PyObject *cython_runtime_dict; + CYTHON_MAYBE_UNUSED_VAR(tstate); + if (unlikely(!__pyx_mstate_global->__pyx_cython_runtime)) { + return c_line; + } + __Pyx_ErrFetchInState(tstate, &ptype, &pvalue, &ptraceback); + cython_runtime_dict = __Pyx_PyProbablyModule_GetDict(__pyx_mstate_global->__pyx_cython_runtime); + if (likely(cython_runtime_dict)) { + __PYX_PY_DICT_LOOKUP_IF_MODIFIED( + use_cline, cython_runtime_dict, + __Pyx_PyDict_SetDefault(cython_runtime_dict, __pyx_mstate_global->__pyx_n_u_cline_in_traceback, Py_False)) + } + if (use_cline == NULL || use_cline == Py_False || (use_cline != Py_True && PyObject_Not(use_cline) != 0)) { + c_line = 0; + } + Py_XDECREF(use_cline); + Py_XDECREF(cython_runtime_dict); + __Pyx_ErrRestoreInState(tstate, ptype, pvalue, ptraceback); + return c_line; +} +#endif + +/* CodeObjectCache (used by AddTraceback) */ +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { + int start = 0, mid = 0, end = count - 1; + if (end >= 0 && code_line > entries[end].code_line) { + return count; + } + while (start < end) { + mid = start + (end - start) / 2; + if (code_line < entries[mid].code_line) { + end = mid; + } else if (code_line > entries[mid].code_line) { + start = mid + 1; + } else { + return mid; + } + } + if (code_line <= entries[mid].code_line) { + return mid; + } else { + return mid + 1; + } +} +static __Pyx_CachedCodeObjectType *__pyx__find_code_object(struct __Pyx_CodeObjectCache *code_cache, int code_line) { + __Pyx_CachedCodeObjectType* code_object; + int pos; + if (unlikely(!code_line) || unlikely(!code_cache->entries)) { + return NULL; + } + pos = __pyx_bisect_code_objects(code_cache->entries, code_cache->count, code_line); + if (unlikely(pos >= code_cache->count) || unlikely(code_cache->entries[pos].code_line != code_line)) { + return NULL; + } + code_object = code_cache->entries[pos].code_object; + Py_INCREF(code_object); + return code_object; +} +static __Pyx_CachedCodeObjectType *__pyx_find_code_object(int code_line) { +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING && !CYTHON_ATOMICS + (void)__pyx__find_code_object; + return NULL; // Most implementation should have atomics. But otherwise, don't make it thread-safe, just miss. +#else + struct __Pyx_CodeObjectCache *code_cache = &__pyx_mstate_global->__pyx_code_cache; +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + __pyx_nonatomic_int_type old_count = __pyx_atomic_incr_acq_rel(&code_cache->accessor_count); + if (old_count < 0) { + __pyx_atomic_decr_acq_rel(&code_cache->accessor_count); + return NULL; + } +#endif + __Pyx_CachedCodeObjectType *result = __pyx__find_code_object(code_cache, code_line); +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + __pyx_atomic_decr_acq_rel(&code_cache->accessor_count); +#endif + return result; +#endif +} +static void __pyx__insert_code_object(struct __Pyx_CodeObjectCache *code_cache, int code_line, __Pyx_CachedCodeObjectType* code_object) +{ + int pos, i; + __Pyx_CodeObjectCacheEntry* entries = code_cache->entries; + if (unlikely(!code_line)) { + return; + } + if (unlikely(!entries)) { + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); + if (likely(entries)) { + code_cache->entries = entries; + code_cache->max_count = 64; + code_cache->count = 1; + entries[0].code_line = code_line; + entries[0].code_object = code_object; + Py_INCREF(code_object); + } + return; + } + pos = __pyx_bisect_code_objects(code_cache->entries, code_cache->count, code_line); + if ((pos < code_cache->count) && unlikely(code_cache->entries[pos].code_line == code_line)) { + __Pyx_CachedCodeObjectType* tmp = entries[pos].code_object; + entries[pos].code_object = code_object; + Py_INCREF(code_object); + Py_DECREF(tmp); + return; + } + if (code_cache->count == code_cache->max_count) { + int new_max = code_cache->max_count + 64; + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( + code_cache->entries, ((size_t)new_max) * sizeof(__Pyx_CodeObjectCacheEntry)); + if (unlikely(!entries)) { + return; + } + code_cache->entries = entries; + code_cache->max_count = new_max; + } + for (i=code_cache->count; i>pos; i--) { + entries[i] = entries[i-1]; + } + entries[pos].code_line = code_line; + entries[pos].code_object = code_object; + code_cache->count++; + Py_INCREF(code_object); +} +static void __pyx_insert_code_object(int code_line, __Pyx_CachedCodeObjectType* code_object) { +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING && !CYTHON_ATOMICS + (void)__pyx__insert_code_object; + return; // Most implementation should have atomics. But otherwise, don't make it thread-safe, just fail. +#else + struct __Pyx_CodeObjectCache *code_cache = &__pyx_mstate_global->__pyx_code_cache; +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + __pyx_nonatomic_int_type expected = 0; + if (!__pyx_atomic_int_cmp_exchange(&code_cache->accessor_count, &expected, INT_MIN)) { + return; + } +#endif + __pyx__insert_code_object(code_cache, code_line, code_object); +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + __pyx_atomic_sub(&code_cache->accessor_count, INT_MIN); +#endif +#endif +} + +/* AddTraceback */ +#include "compile.h" +#include "frameobject.h" +#include "traceback.h" +#if PY_VERSION_HEX >= 0x030b00a6 && !CYTHON_COMPILING_IN_LIMITED_API && !defined(PYPY_VERSION) + #ifndef Py_BUILD_CORE + #define Py_BUILD_CORE 1 + #endif + #include "internal/pycore_frame.h" +#endif +#if CYTHON_COMPILING_IN_LIMITED_API +static PyObject *__Pyx_PyCode_Replace_For_AddTraceback(PyObject *code, PyObject *scratch_dict, + PyObject *firstlineno, PyObject *name) { + PyObject *replace = NULL; + if (unlikely(PyDict_SetItemString(scratch_dict, "co_firstlineno", firstlineno))) return NULL; + if (unlikely(PyDict_SetItemString(scratch_dict, "co_name", name))) return NULL; + replace = PyObject_GetAttrString(code, "replace"); + if (likely(replace)) { + PyObject *result = PyObject_Call(replace, __pyx_mstate_global->__pyx_empty_tuple, scratch_dict); + Py_DECREF(replace); + return result; + } + PyErr_Clear(); + return NULL; +} +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename) { + PyObject *code_object = NULL, *py_py_line = NULL, *py_funcname = NULL, *dict = NULL; + PyObject *replace = NULL, *getframe = NULL, *frame = NULL; + PyObject *exc_type, *exc_value, *exc_traceback; + int success = 0; + if (c_line) { + c_line = __Pyx_CLineForTraceback(__Pyx_PyThreadState_Current, c_line); + } + PyErr_Fetch(&exc_type, &exc_value, &exc_traceback); + code_object = __pyx_find_code_object(c_line ? -c_line : py_line); + if (!code_object) { + code_object = Py_CompileString("_getframe()", filename, Py_eval_input); + if (unlikely(!code_object)) goto bad; + py_py_line = PyLong_FromLong(py_line); + if (unlikely(!py_py_line)) goto bad; + if (c_line) { + py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + } else { + py_funcname = PyUnicode_FromString(funcname); + } + if (unlikely(!py_funcname)) goto bad; + dict = PyDict_New(); + if (unlikely(!dict)) goto bad; + { + PyObject *old_code_object = code_object; + code_object = __Pyx_PyCode_Replace_For_AddTraceback(code_object, dict, py_py_line, py_funcname); + Py_DECREF(old_code_object); + } + if (unlikely(!code_object)) goto bad; + __pyx_insert_code_object(c_line ? -c_line : py_line, code_object); + } else { + dict = PyDict_New(); + } + getframe = PySys_GetObject("_getframe"); + if (unlikely(!getframe)) goto bad; + if (unlikely(PyDict_SetItemString(dict, "_getframe", getframe))) goto bad; + frame = PyEval_EvalCode(code_object, dict, dict); + if (unlikely(!frame) || frame == Py_None) goto bad; + success = 1; + bad: + PyErr_Restore(exc_type, exc_value, exc_traceback); + Py_XDECREF(code_object); + Py_XDECREF(py_py_line); + Py_XDECREF(py_funcname); + Py_XDECREF(dict); + Py_XDECREF(replace); + if (success) { + PyTraceBack_Here( + (struct _frame*)frame); + } + Py_XDECREF(frame); +} +#else +static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( + const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = NULL; + PyObject *py_funcname = NULL; + if (c_line) { + py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + if (!py_funcname) goto bad; + funcname = PyUnicode_AsUTF8(py_funcname); + if (!funcname) goto bad; + } + py_code = PyCode_NewEmpty(filename, funcname, py_line); + Py_XDECREF(py_funcname); + return py_code; +bad: + Py_XDECREF(py_funcname); + return NULL; +} +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyFrameObject *py_frame = 0; + PyThreadState *tstate = __Pyx_PyThreadState_Current; + PyObject *ptype, *pvalue, *ptraceback; + if (c_line) { + c_line = __Pyx_CLineForTraceback(tstate, c_line); + } + py_code = __pyx_find_code_object(c_line ? -c_line : py_line); + if (!py_code) { + __Pyx_ErrFetchInState(tstate, &ptype, &pvalue, &ptraceback); + py_code = __Pyx_CreateCodeObjectForTraceback( + funcname, c_line, py_line, filename); + if (!py_code) { + /* If the code object creation fails, then we should clear the + fetched exception references and propagate the new exception */ + Py_XDECREF(ptype); + Py_XDECREF(pvalue); + Py_XDECREF(ptraceback); + goto bad; + } + __Pyx_ErrRestoreInState(tstate, ptype, pvalue, ptraceback); + __pyx_insert_code_object(c_line ? -c_line : py_line, py_code); + } + py_frame = PyFrame_New( + tstate, /*PyThreadState *tstate,*/ + py_code, /*PyCodeObject *code,*/ + __pyx_mstate_global->__pyx_d, /*PyObject *globals,*/ + 0 /*PyObject *locals*/ + ); + if (!py_frame) goto bad; + __Pyx_PyFrame_SetLineNumber(py_frame, py_line); + PyTraceBack_Here(py_frame); +bad: + Py_XDECREF(py_code); + Py_XDECREF(py_frame); +} +#endif + +/* CheckUnpickleChecksum */ +static void __Pyx_RaiseUnpickleChecksumError(long checksum, long checksum1, long checksum2, long checksum3, const char *members) { + PyObject *pickle_module = PyImport_ImportModule("pickle"); + if (unlikely(!pickle_module)) return; + PyObject *pickle_error = PyObject_GetAttrString(pickle_module, "PickleError"); + Py_DECREF(pickle_module); + if (unlikely(!pickle_error)) return; + if (checksum2 == checksum1) { + PyErr_Format(pickle_error, "Incompatible checksums (0x%x vs (0x%x) = (%s))", + checksum, checksum1, members); + } else if (checksum3 == checksum2) { + PyErr_Format(pickle_error, "Incompatible checksums (0x%x vs (0x%x, 0x%x) = (%s))", + checksum, checksum1, checksum2, members); + } else { + PyErr_Format(pickle_error, "Incompatible checksums (0x%x vs (0x%x, 0x%x, 0x%x) = (%s))", + checksum, checksum1, checksum2, checksum3, members); + } + Py_DECREF(pickle_error); +} +static int __Pyx_CheckUnpickleChecksum(long checksum, long checksum1, long checksum2, long checksum3, const char *members) { + int found = 0; + found |= checksum1 == checksum; + found |= checksum2 == checksum; + found |= checksum3 == checksum; + if (likely(found)) + return 0; + __Pyx_RaiseUnpickleChecksumError(checksum, checksum1, checksum2, checksum3, members); + return -1; +} + +/* CIntFromPyVerify */ +#define __PYX_VERIFY_RETURN_INT(target_type, func_type, func_value)\ + __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 0) +#define __PYX_VERIFY_RETURN_INT_EXC(target_type, func_type, func_value)\ + __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 1) +#define __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, exc)\ + {\ + func_type value = func_value;\ + if (sizeof(target_type) < sizeof(func_type)) {\ + if (unlikely(value != (func_type) (target_type) value)) {\ + func_type zero = 0;\ + if (exc && unlikely(value == (func_type)-1 && PyErr_Occurred()))\ + return (target_type) -1;\ + if (is_unsigned && unlikely(value < zero))\ + goto raise_neg_overflow;\ + else\ + goto raise_overflow;\ + }\ + }\ + return (target_type) value;\ + } + +/* CIntFromPy */ +static CYTHON_INLINE long __Pyx_PyLong_As_long(PyObject *x) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const long neg_one = (long) -1, const_zero = (long) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (unlikely(!PyLong_Check(x))) { + long val; + PyObject *tmp = __Pyx_PyNumber_Long(x); + if (!tmp) return (long) -1; + val = __Pyx_PyLong_As_long(tmp); + Py_DECREF(tmp); + return val; + } + if (is_unsigned) { +#if CYTHON_USE_PYLONG_INTERNALS + if (unlikely(__Pyx_PyLong_IsNeg(x))) { + goto raise_neg_overflow; + } else if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(long, __Pyx_compact_upylong, __Pyx_PyLong_CompactValueUnsigned(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_DigitCount(x)) { + case 2: + if ((8 * sizeof(long) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) >= 2 * PyLong_SHIFT)) { + return (long) (((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); + } + } + break; + case 3: + if ((8 * sizeof(long) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) >= 3 * PyLong_SHIFT)) { + return (long) (((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); + } + } + break; + case 4: + if ((8 * sizeof(long) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) >= 4 * PyLong_SHIFT)) { + return (long) (((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); + } + } + break; + } + } +#endif +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030C00A7 + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } +#else + { + int result = PyObject_RichCompareBool(x, Py_False, Py_LT); + if (unlikely(result < 0)) + return (long) -1; + if (unlikely(result == 1)) + goto raise_neg_overflow; + } +#endif + if ((sizeof(long) <= sizeof(unsigned long))) { + __PYX_VERIFY_RETURN_INT_EXC(long, unsigned long, PyLong_AsUnsignedLong(x)) + } else if ((sizeof(long) <= sizeof(unsigned PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(long, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) + } + } else { +#if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(long, __Pyx_compact_pylong, __Pyx_PyLong_CompactValue(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_SignedDigitCount(x)) { + case -2: + if ((8 * sizeof(long) - 1 > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 2 * PyLong_SHIFT)) { + return (long) (((long)-1)*(((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case 2: + if ((8 * sizeof(long) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 2 * PyLong_SHIFT)) { + return (long) ((((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case -3: + if ((8 * sizeof(long) - 1 > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 3 * PyLong_SHIFT)) { + return (long) (((long)-1)*(((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case 3: + if ((8 * sizeof(long) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 3 * PyLong_SHIFT)) { + return (long) ((((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case -4: + if ((8 * sizeof(long) - 1 > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 4 * PyLong_SHIFT)) { + return (long) (((long)-1)*(((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case 4: + if ((8 * sizeof(long) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 4 * PyLong_SHIFT)) { + return (long) ((((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + } + } +#endif + if ((sizeof(long) <= sizeof(long))) { + __PYX_VERIFY_RETURN_INT_EXC(long, long, PyLong_AsLong(x)) + } else if ((sizeof(long) <= sizeof(PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(long, PY_LONG_LONG, PyLong_AsLongLong(x)) + } + } + { + long val; + int ret = -1; +#if PY_VERSION_HEX >= 0x030d00A6 && !CYTHON_COMPILING_IN_LIMITED_API + Py_ssize_t bytes_copied = PyLong_AsNativeBytes( + x, &val, sizeof(val), Py_ASNATIVEBYTES_NATIVE_ENDIAN | (is_unsigned ? Py_ASNATIVEBYTES_UNSIGNED_BUFFER | Py_ASNATIVEBYTES_REJECT_NEGATIVE : 0)); + if (unlikely(bytes_copied == -1)) { + } else if (unlikely(bytes_copied > (Py_ssize_t) sizeof(val))) { + goto raise_overflow; + } else { + ret = 0; + } +#elif PY_VERSION_HEX < 0x030d0000 && !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API) || defined(_PyLong_AsByteArray) + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + ret = _PyLong_AsByteArray((PyLongObject *)x, + bytes, sizeof(val), + is_little, !is_unsigned); +#else + PyObject *v; + PyObject *stepval = NULL, *mask = NULL, *shift = NULL; + int bits, remaining_bits, is_negative = 0; + int chunk_size = (sizeof(long) < 8) ? 30 : 62; + if (likely(PyLong_CheckExact(x))) { + v = __Pyx_NewRef(x); + } else { + v = PyNumber_Long(x); + if (unlikely(!v)) return (long) -1; + assert(PyLong_CheckExact(v)); + } + { + int result = PyObject_RichCompareBool(v, Py_False, Py_LT); + if (unlikely(result < 0)) { + Py_DECREF(v); + return (long) -1; + } + is_negative = result == 1; + } + if (is_unsigned && unlikely(is_negative)) { + Py_DECREF(v); + goto raise_neg_overflow; + } else if (is_negative) { + stepval = PyNumber_Invert(v); + Py_DECREF(v); + if (unlikely(!stepval)) + return (long) -1; + } else { + stepval = v; + } + v = NULL; + val = (long) 0; + mask = PyLong_FromLong((1L << chunk_size) - 1); if (unlikely(!mask)) goto done; + shift = PyLong_FromLong(chunk_size); if (unlikely(!shift)) goto done; + for (bits = 0; bits < (int) sizeof(long) * 8 - chunk_size; bits += chunk_size) { + PyObject *tmp, *digit; + long idigit; + digit = PyNumber_And(stepval, mask); + if (unlikely(!digit)) goto done; + idigit = PyLong_AsLong(digit); + Py_DECREF(digit); + if (unlikely(idigit < 0)) goto done; + val |= ((long) idigit) << bits; + tmp = PyNumber_Rshift(stepval, shift); + if (unlikely(!tmp)) goto done; + Py_DECREF(stepval); stepval = tmp; + } + Py_DECREF(shift); shift = NULL; + Py_DECREF(mask); mask = NULL; + { + long idigit = PyLong_AsLong(stepval); + if (unlikely(idigit < 0)) goto done; + remaining_bits = ((int) sizeof(long) * 8) - bits - (is_unsigned ? 0 : 1); + if (unlikely(idigit >= (1L << remaining_bits))) + goto raise_overflow; + val |= ((long) idigit) << bits; + } + if (!is_unsigned) { + if (unlikely(val & (((long) 1) << (sizeof(long) * 8 - 1)))) + goto raise_overflow; + if (is_negative) + val = ~val; + } + ret = 0; + done: + Py_XDECREF(shift); + Py_XDECREF(mask); + Py_XDECREF(stepval); +#endif + if (unlikely(ret)) + return (long) -1; + return val; + } +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to long"); + return (long) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to long"); + return (long) -1; +} + +/* CIntFromPy */ +static CYTHON_INLINE size_t __Pyx_PyLong_As_size_t(PyObject *x) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const size_t neg_one = (size_t) -1, const_zero = (size_t) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (unlikely(!PyLong_Check(x))) { + size_t val; + PyObject *tmp = __Pyx_PyNumber_Long(x); + if (!tmp) return (size_t) -1; + val = __Pyx_PyLong_As_size_t(tmp); + Py_DECREF(tmp); + return val; + } + if (is_unsigned) { +#if CYTHON_USE_PYLONG_INTERNALS + if (unlikely(__Pyx_PyLong_IsNeg(x))) { + goto raise_neg_overflow; + } else if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(size_t, __Pyx_compact_upylong, __Pyx_PyLong_CompactValueUnsigned(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_DigitCount(x)) { + case 2: + if ((8 * sizeof(size_t) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(size_t, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(size_t) >= 2 * PyLong_SHIFT)) { + return (size_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + } + break; + case 3: + if ((8 * sizeof(size_t) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(size_t, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(size_t) >= 3 * PyLong_SHIFT)) { + return (size_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + } + break; + case 4: + if ((8 * sizeof(size_t) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(size_t, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(size_t) >= 4 * PyLong_SHIFT)) { + return (size_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + } + break; + } + } +#endif +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030C00A7 + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } +#else + { + int result = PyObject_RichCompareBool(x, Py_False, Py_LT); + if (unlikely(result < 0)) + return (size_t) -1; + if (unlikely(result == 1)) + goto raise_neg_overflow; + } +#endif + if ((sizeof(size_t) <= sizeof(unsigned long))) { + __PYX_VERIFY_RETURN_INT_EXC(size_t, unsigned long, PyLong_AsUnsignedLong(x)) + } else if ((sizeof(size_t) <= sizeof(unsigned PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(size_t, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) + } + } else { +#if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(size_t, __Pyx_compact_pylong, __Pyx_PyLong_CompactValue(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_SignedDigitCount(x)) { + case -2: + if ((8 * sizeof(size_t) - 1 > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(size_t, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(size_t) - 1 > 2 * PyLong_SHIFT)) { + return (size_t) (((size_t)-1)*(((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]))); + } + } + break; + case 2: + if ((8 * sizeof(size_t) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(size_t, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(size_t) - 1 > 2 * PyLong_SHIFT)) { + return (size_t) ((((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]))); + } + } + break; + case -3: + if ((8 * sizeof(size_t) - 1 > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(size_t, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(size_t) - 1 > 3 * PyLong_SHIFT)) { + return (size_t) (((size_t)-1)*(((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]))); + } + } + break; + case 3: + if ((8 * sizeof(size_t) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(size_t, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(size_t) - 1 > 3 * PyLong_SHIFT)) { + return (size_t) ((((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]))); + } + } + break; + case -4: + if ((8 * sizeof(size_t) - 1 > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(size_t, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(size_t) - 1 > 4 * PyLong_SHIFT)) { + return (size_t) (((size_t)-1)*(((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]))); + } + } + break; + case 4: + if ((8 * sizeof(size_t) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(size_t, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(size_t) - 1 > 4 * PyLong_SHIFT)) { + return (size_t) ((((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]))); + } + } + break; + } + } +#endif + if ((sizeof(size_t) <= sizeof(long))) { + __PYX_VERIFY_RETURN_INT_EXC(size_t, long, PyLong_AsLong(x)) + } else if ((sizeof(size_t) <= sizeof(PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(size_t, PY_LONG_LONG, PyLong_AsLongLong(x)) + } + } + { + size_t val; + int ret = -1; +#if PY_VERSION_HEX >= 0x030d00A6 && !CYTHON_COMPILING_IN_LIMITED_API + Py_ssize_t bytes_copied = PyLong_AsNativeBytes( + x, &val, sizeof(val), Py_ASNATIVEBYTES_NATIVE_ENDIAN | (is_unsigned ? Py_ASNATIVEBYTES_UNSIGNED_BUFFER | Py_ASNATIVEBYTES_REJECT_NEGATIVE : 0)); + if (unlikely(bytes_copied == -1)) { + } else if (unlikely(bytes_copied > (Py_ssize_t) sizeof(val))) { + goto raise_overflow; + } else { + ret = 0; + } +#elif PY_VERSION_HEX < 0x030d0000 && !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API) || defined(_PyLong_AsByteArray) + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + ret = _PyLong_AsByteArray((PyLongObject *)x, + bytes, sizeof(val), + is_little, !is_unsigned); +#else + PyObject *v; + PyObject *stepval = NULL, *mask = NULL, *shift = NULL; + int bits, remaining_bits, is_negative = 0; + int chunk_size = (sizeof(long) < 8) ? 30 : 62; + if (likely(PyLong_CheckExact(x))) { + v = __Pyx_NewRef(x); + } else { + v = PyNumber_Long(x); + if (unlikely(!v)) return (size_t) -1; + assert(PyLong_CheckExact(v)); + } + { + int result = PyObject_RichCompareBool(v, Py_False, Py_LT); + if (unlikely(result < 0)) { + Py_DECREF(v); + return (size_t) -1; + } + is_negative = result == 1; + } + if (is_unsigned && unlikely(is_negative)) { + Py_DECREF(v); + goto raise_neg_overflow; + } else if (is_negative) { + stepval = PyNumber_Invert(v); + Py_DECREF(v); + if (unlikely(!stepval)) + return (size_t) -1; + } else { + stepval = v; + } + v = NULL; + val = (size_t) 0; + mask = PyLong_FromLong((1L << chunk_size) - 1); if (unlikely(!mask)) goto done; + shift = PyLong_FromLong(chunk_size); if (unlikely(!shift)) goto done; + for (bits = 0; bits < (int) sizeof(size_t) * 8 - chunk_size; bits += chunk_size) { + PyObject *tmp, *digit; + long idigit; + digit = PyNumber_And(stepval, mask); + if (unlikely(!digit)) goto done; + idigit = PyLong_AsLong(digit); + Py_DECREF(digit); + if (unlikely(idigit < 0)) goto done; + val |= ((size_t) idigit) << bits; + tmp = PyNumber_Rshift(stepval, shift); + if (unlikely(!tmp)) goto done; + Py_DECREF(stepval); stepval = tmp; + } + Py_DECREF(shift); shift = NULL; + Py_DECREF(mask); mask = NULL; + { + long idigit = PyLong_AsLong(stepval); + if (unlikely(idigit < 0)) goto done; + remaining_bits = ((int) sizeof(size_t) * 8) - bits - (is_unsigned ? 0 : 1); + if (unlikely(idigit >= (1L << remaining_bits))) + goto raise_overflow; + val |= ((size_t) idigit) << bits; + } + if (!is_unsigned) { + if (unlikely(val & (((size_t) 1) << (sizeof(size_t) * 8 - 1)))) + goto raise_overflow; + if (is_negative) + val = ~val; + } + ret = 0; + done: + Py_XDECREF(shift); + Py_XDECREF(mask); + Py_XDECREF(stepval); +#endif + if (unlikely(ret)) + return (size_t) -1; + return val; + } +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to size_t"); + return (size_t) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to size_t"); + return (size_t) -1; +} + +/* CIntFromPy */ +static CYTHON_INLINE int __Pyx_PyLong_As_int(PyObject *x) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const int neg_one = (int) -1, const_zero = (int) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (unlikely(!PyLong_Check(x))) { + int val; + PyObject *tmp = __Pyx_PyNumber_Long(x); + if (!tmp) return (int) -1; + val = __Pyx_PyLong_As_int(tmp); + Py_DECREF(tmp); + return val; + } + if (is_unsigned) { +#if CYTHON_USE_PYLONG_INTERNALS + if (unlikely(__Pyx_PyLong_IsNeg(x))) { + goto raise_neg_overflow; + } else if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(int, __Pyx_compact_upylong, __Pyx_PyLong_CompactValueUnsigned(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_DigitCount(x)) { + case 2: + if ((8 * sizeof(int) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) >= 2 * PyLong_SHIFT)) { + return (int) (((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); + } + } + break; + case 3: + if ((8 * sizeof(int) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) >= 3 * PyLong_SHIFT)) { + return (int) (((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); + } + } + break; + case 4: + if ((8 * sizeof(int) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) >= 4 * PyLong_SHIFT)) { + return (int) (((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); + } + } + break; + } + } +#endif +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030C00A7 + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } +#else + { + int result = PyObject_RichCompareBool(x, Py_False, Py_LT); + if (unlikely(result < 0)) + return (int) -1; + if (unlikely(result == 1)) + goto raise_neg_overflow; + } +#endif + if ((sizeof(int) <= sizeof(unsigned long))) { + __PYX_VERIFY_RETURN_INT_EXC(int, unsigned long, PyLong_AsUnsignedLong(x)) + } else if ((sizeof(int) <= sizeof(unsigned PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(int, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) + } + } else { +#if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(int, __Pyx_compact_pylong, __Pyx_PyLong_CompactValue(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_SignedDigitCount(x)) { + case -2: + if ((8 * sizeof(int) - 1 > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 2 * PyLong_SHIFT)) { + return (int) (((int)-1)*(((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case 2: + if ((8 * sizeof(int) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 2 * PyLong_SHIFT)) { + return (int) ((((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case -3: + if ((8 * sizeof(int) - 1 > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 3 * PyLong_SHIFT)) { + return (int) (((int)-1)*(((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case 3: + if ((8 * sizeof(int) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 3 * PyLong_SHIFT)) { + return (int) ((((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case -4: + if ((8 * sizeof(int) - 1 > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 4 * PyLong_SHIFT)) { + return (int) (((int)-1)*(((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case 4: + if ((8 * sizeof(int) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 4 * PyLong_SHIFT)) { + return (int) ((((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + } + } +#endif + if ((sizeof(int) <= sizeof(long))) { + __PYX_VERIFY_RETURN_INT_EXC(int, long, PyLong_AsLong(x)) + } else if ((sizeof(int) <= sizeof(PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(int, PY_LONG_LONG, PyLong_AsLongLong(x)) + } + } + { + int val; + int ret = -1; +#if PY_VERSION_HEX >= 0x030d00A6 && !CYTHON_COMPILING_IN_LIMITED_API + Py_ssize_t bytes_copied = PyLong_AsNativeBytes( + x, &val, sizeof(val), Py_ASNATIVEBYTES_NATIVE_ENDIAN | (is_unsigned ? Py_ASNATIVEBYTES_UNSIGNED_BUFFER | Py_ASNATIVEBYTES_REJECT_NEGATIVE : 0)); + if (unlikely(bytes_copied == -1)) { + } else if (unlikely(bytes_copied > (Py_ssize_t) sizeof(val))) { + goto raise_overflow; + } else { + ret = 0; + } +#elif PY_VERSION_HEX < 0x030d0000 && !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API) || defined(_PyLong_AsByteArray) + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + ret = _PyLong_AsByteArray((PyLongObject *)x, + bytes, sizeof(val), + is_little, !is_unsigned); +#else + PyObject *v; + PyObject *stepval = NULL, *mask = NULL, *shift = NULL; + int bits, remaining_bits, is_negative = 0; + int chunk_size = (sizeof(long) < 8) ? 30 : 62; + if (likely(PyLong_CheckExact(x))) { + v = __Pyx_NewRef(x); + } else { + v = PyNumber_Long(x); + if (unlikely(!v)) return (int) -1; + assert(PyLong_CheckExact(v)); + } + { + int result = PyObject_RichCompareBool(v, Py_False, Py_LT); + if (unlikely(result < 0)) { + Py_DECREF(v); + return (int) -1; + } + is_negative = result == 1; + } + if (is_unsigned && unlikely(is_negative)) { + Py_DECREF(v); + goto raise_neg_overflow; + } else if (is_negative) { + stepval = PyNumber_Invert(v); + Py_DECREF(v); + if (unlikely(!stepval)) + return (int) -1; + } else { + stepval = v; + } + v = NULL; + val = (int) 0; + mask = PyLong_FromLong((1L << chunk_size) - 1); if (unlikely(!mask)) goto done; + shift = PyLong_FromLong(chunk_size); if (unlikely(!shift)) goto done; + for (bits = 0; bits < (int) sizeof(int) * 8 - chunk_size; bits += chunk_size) { + PyObject *tmp, *digit; + long idigit; + digit = PyNumber_And(stepval, mask); + if (unlikely(!digit)) goto done; + idigit = PyLong_AsLong(digit); + Py_DECREF(digit); + if (unlikely(idigit < 0)) goto done; + val |= ((int) idigit) << bits; + tmp = PyNumber_Rshift(stepval, shift); + if (unlikely(!tmp)) goto done; + Py_DECREF(stepval); stepval = tmp; + } + Py_DECREF(shift); shift = NULL; + Py_DECREF(mask); mask = NULL; + { + long idigit = PyLong_AsLong(stepval); + if (unlikely(idigit < 0)) goto done; + remaining_bits = ((int) sizeof(int) * 8) - bits - (is_unsigned ? 0 : 1); + if (unlikely(idigit >= (1L << remaining_bits))) + goto raise_overflow; + val |= ((int) idigit) << bits; + } + if (!is_unsigned) { + if (unlikely(val & (((int) 1) << (sizeof(int) * 8 - 1)))) + goto raise_overflow; + if (is_negative) + val = ~val; + } + ret = 0; + done: + Py_XDECREF(shift); + Py_XDECREF(mask); + Py_XDECREF(stepval); +#endif + if (unlikely(ret)) + return (int) -1; + return val; + } +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to int"); + return (int) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to int"); + return (int) -1; +} + +/* PyObjectVectorCallKwBuilder (used by CIntToPy) */ +#if CYTHON_VECTORCALL +static int __Pyx_VectorcallBuilder_AddArg(PyObject *key, PyObject *value, PyObject *builder, PyObject **args, int n) { + (void)__Pyx_PyObject_FastCallDict; + if (__Pyx_PyTuple_SET_ITEM(builder, n, key) != (0)) return -1; + Py_INCREF(key); + args[n] = value; + return 0; +} +CYTHON_UNUSED static int __Pyx_VectorcallBuilder_AddArg_Check(PyObject *key, PyObject *value, PyObject *builder, PyObject **args, int n) { + (void)__Pyx_VectorcallBuilder_AddArgStr; + if (unlikely(!PyUnicode_Check(key))) { + PyErr_SetString(PyExc_TypeError, "keywords must be strings"); + return -1; + } + return __Pyx_VectorcallBuilder_AddArg(key, value, builder, args, n); +} +static int __Pyx_VectorcallBuilder_AddArgStr(const char *key, PyObject *value, PyObject *builder, PyObject **args, int n) { + PyObject *pyKey = PyUnicode_FromString(key); + if (!pyKey) return -1; + return __Pyx_VectorcallBuilder_AddArg(pyKey, value, builder, args, n); +} +#else // CYTHON_VECTORCALL +CYTHON_UNUSED static int __Pyx_VectorcallBuilder_AddArg_Check(PyObject *key, PyObject *value, PyObject *builder, CYTHON_UNUSED PyObject **args, CYTHON_UNUSED int n) { + if (unlikely(!PyUnicode_Check(key))) { + PyErr_SetString(PyExc_TypeError, "keywords must be strings"); + return -1; + } + return PyDict_SetItem(builder, key, value); +} +#endif + +/* CIntToPy */ +static CYTHON_INLINE PyObject* __Pyx_PyLong_From_int(int value) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const int neg_one = (int) -1, const_zero = (int) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(int) < sizeof(long)) { + return PyLong_FromLong((long) value); + } else if (sizeof(int) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); +#if !CYTHON_COMPILING_IN_PYPY + } else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) { + return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); +#endif + } + } else { + if (sizeof(int) <= sizeof(long)) { + return PyLong_FromLong((long) value); + } else if (sizeof(int) <= sizeof(PY_LONG_LONG)) { + return PyLong_FromLongLong((PY_LONG_LONG) value); + } + } + { + unsigned char *bytes = (unsigned char *)&value; +#if !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d00A4 + if (is_unsigned) { + return PyLong_FromUnsignedNativeBytes(bytes, sizeof(value), -1); + } else { + return PyLong_FromNativeBytes(bytes, sizeof(value), -1); + } +#elif !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030d0000 + int one = 1; int little = (int)*(unsigned char *)&one; + return _PyLong_FromByteArray(bytes, sizeof(int), + little, !is_unsigned); +#else + int one = 1; int little = (int)*(unsigned char *)&one; + PyObject *from_bytes, *result = NULL, *kwds = NULL; + PyObject *py_bytes = NULL, *order_str = NULL; + from_bytes = PyObject_GetAttrString((PyObject*)&PyLong_Type, "from_bytes"); + if (!from_bytes) return NULL; + py_bytes = PyBytes_FromStringAndSize((char*)bytes, sizeof(int)); + if (!py_bytes) goto limited_bad; + order_str = PyUnicode_FromString(little ? "little" : "big"); + if (!order_str) goto limited_bad; + { + PyObject *args[3+(CYTHON_VECTORCALL ? 1 : 0)] = { NULL, py_bytes, order_str }; + if (!is_unsigned) { + kwds = __Pyx_MakeVectorcallBuilderKwds(1); + if (!kwds) goto limited_bad; + if (__Pyx_VectorcallBuilder_AddArgStr("signed", __Pyx_NewRef(Py_True), kwds, args+3, 0) < 0) goto limited_bad; + } + result = __Pyx_Object_Vectorcall_CallFromBuilder(from_bytes, args+1, 2 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET, kwds); + } + limited_bad: + Py_XDECREF(kwds); + Py_XDECREF(order_str); + Py_XDECREF(py_bytes); + Py_XDECREF(from_bytes); + return result; +#endif + } +} + +/* CIntToPy */ +static CYTHON_INLINE PyObject* __Pyx_PyLong_From_long(long value) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const long neg_one = (long) -1, const_zero = (long) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(long) < sizeof(long)) { + return PyLong_FromLong((long) value); + } else if (sizeof(long) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); +#if !CYTHON_COMPILING_IN_PYPY + } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { + return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); +#endif + } + } else { + if (sizeof(long) <= sizeof(long)) { + return PyLong_FromLong((long) value); + } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { + return PyLong_FromLongLong((PY_LONG_LONG) value); + } + } + { + unsigned char *bytes = (unsigned char *)&value; +#if !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d00A4 + if (is_unsigned) { + return PyLong_FromUnsignedNativeBytes(bytes, sizeof(value), -1); + } else { + return PyLong_FromNativeBytes(bytes, sizeof(value), -1); + } +#elif !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030d0000 + int one = 1; int little = (int)*(unsigned char *)&one; + return _PyLong_FromByteArray(bytes, sizeof(long), + little, !is_unsigned); +#else + int one = 1; int little = (int)*(unsigned char *)&one; + PyObject *from_bytes, *result = NULL, *kwds = NULL; + PyObject *py_bytes = NULL, *order_str = NULL; + from_bytes = PyObject_GetAttrString((PyObject*)&PyLong_Type, "from_bytes"); + if (!from_bytes) return NULL; + py_bytes = PyBytes_FromStringAndSize((char*)bytes, sizeof(long)); + if (!py_bytes) goto limited_bad; + order_str = PyUnicode_FromString(little ? "little" : "big"); + if (!order_str) goto limited_bad; + { + PyObject *args[3+(CYTHON_VECTORCALL ? 1 : 0)] = { NULL, py_bytes, order_str }; + if (!is_unsigned) { + kwds = __Pyx_MakeVectorcallBuilderKwds(1); + if (!kwds) goto limited_bad; + if (__Pyx_VectorcallBuilder_AddArgStr("signed", __Pyx_NewRef(Py_True), kwds, args+3, 0) < 0) goto limited_bad; + } + result = __Pyx_Object_Vectorcall_CallFromBuilder(from_bytes, args+1, 2 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET, kwds); + } + limited_bad: + Py_XDECREF(kwds); + Py_XDECREF(order_str); + Py_XDECREF(py_bytes); + Py_XDECREF(from_bytes); + return result; +#endif + } +} + +/* PyObjectCall2Args */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call2Args(PyObject* function, PyObject* arg1, PyObject* arg2) { + PyObject *args[3] = {NULL, arg1, arg2}; + return __Pyx_PyObject_FastCall(function, args+1, 2 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET); +} + +/* PyObjectCallMethod1 */ +#if !(CYTHON_VECTORCALL && (__PYX_LIMITED_VERSION_HEX >= 0x030C0000 || (!CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x03090000))) +static PyObject* __Pyx__PyObject_CallMethod1(PyObject* method, PyObject* arg) { + PyObject *result = __Pyx_PyObject_CallOneArg(method, arg); + Py_DECREF(method); + return result; +} +#endif +static PyObject* __Pyx_PyObject_CallMethod1(PyObject* obj, PyObject* method_name, PyObject* arg) { +#if CYTHON_VECTORCALL && (__PYX_LIMITED_VERSION_HEX >= 0x030C0000 || (!CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x03090000)) + PyObject *args[2] = {obj, arg}; + (void) __Pyx_PyObject_CallOneArg; + (void) __Pyx_PyObject_Call2Args; + return PyObject_VectorcallMethod(method_name, args, 2 | PY_VECTORCALL_ARGUMENTS_OFFSET, NULL); +#else + PyObject *method = NULL, *result; + int is_method = __Pyx_PyObject_GetMethod(obj, method_name, &method); + if (likely(is_method)) { + result = __Pyx_PyObject_Call2Args(method, obj, arg); + Py_DECREF(method); + return result; + } + if (unlikely(!method)) return NULL; + return __Pyx__PyObject_CallMethod1(method, arg); +#endif +} + +/* UpdateUnpickledDict */ +static int __Pyx__UpdateUnpickledDict(PyObject *obj, PyObject *state, Py_ssize_t index) { + PyObject *state_dict = __Pyx_PySequence_ITEM(state, index); + if (unlikely(!state_dict)) { + return -1; + } + int non_empty = PyObject_IsTrue(state_dict); + if (non_empty == 0) { + Py_DECREF(state_dict); + return 0; + } else if (unlikely(non_empty == -1)) { + return -1; + } + PyObject *dict; + #if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000 + dict = PyObject_GetAttrString(obj, "__dict__"); + #else + dict = PyObject_GenericGetDict(obj, NULL); + #endif + if (unlikely(!dict)) { + Py_DECREF(state_dict); + return -1; + } + int result; + if (likely(PyDict_CheckExact(dict))) { + result = PyDict_Update(dict, state_dict); + } else { + PyObject *obj_result = __Pyx_PyObject_CallMethod1(dict, __pyx_mstate_global->__pyx_n_u_update, state_dict); + if (likely(obj_result)) { + Py_DECREF(obj_result); + result = 0; + } else { + result = -1; + } + } + Py_DECREF(state_dict); + Py_DECREF(dict); + return result; +} +static int __Pyx_UpdateUnpickledDict(PyObject *obj, PyObject *state, Py_ssize_t index) { + Py_ssize_t state_size = __Pyx_PyTuple_GET_SIZE(state); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(state_size == -1)) return -1; + #endif + if (state_size <= index) { + return 0; + } + return __Pyx__UpdateUnpickledDict(obj, state, index); +} + +/* FormatTypeName */ +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030d0000 +static __Pyx_TypeName +__Pyx_PyType_GetFullyQualifiedName(PyTypeObject* tp) +{ + PyObject *module = NULL, *name = NULL, *result = NULL; + #if __PYX_LIMITED_VERSION_HEX < 0x030b0000 + name = __Pyx_PyObject_GetAttrStr((PyObject *)tp, + __pyx_mstate_global->__pyx_n_u_qualname); + #else + name = PyType_GetQualName(tp); + #endif + if (unlikely(name == NULL) || unlikely(!PyUnicode_Check(name))) goto bad; + module = __Pyx_PyObject_GetAttrStr((PyObject *)tp, + __pyx_mstate_global->__pyx_n_u_module); + if (unlikely(module == NULL) || unlikely(!PyUnicode_Check(module))) goto bad; + if (PyUnicode_CompareWithASCIIString(module, "builtins") == 0) { + result = name; + name = NULL; + goto done; + } + result = PyUnicode_FromFormat("%U.%U", module, name); + if (unlikely(result == NULL)) goto bad; + done: + Py_XDECREF(name); + Py_XDECREF(module); + return result; + bad: + PyErr_Clear(); + if (name) { + result = name; + name = NULL; + } else { + result = __Pyx_NewRef(__pyx_mstate_global->__pyx_kp_u_); + } + goto done; +} +#endif + +/* FastTypeChecks */ +#if CYTHON_COMPILING_IN_CPYTHON +static int __Pyx_InBases(PyTypeObject *a, PyTypeObject *b) { + while (a) { + a = __Pyx_PyType_GetSlot(a, tp_base, PyTypeObject*); + if (a == b) + return 1; + } + return b == &PyBaseObject_Type; +} +static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b) { + PyObject *mro; + if (a == b) return 1; + mro = a->tp_mro; + if (likely(mro)) { + Py_ssize_t i, n; + n = PyTuple_GET_SIZE(mro); + for (i = 0; i < n; i++) { + if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b) + return 1; + } + return 0; + } + return __Pyx_InBases(a, b); +} +static CYTHON_INLINE int __Pyx_IsAnySubtype2(PyTypeObject *cls, PyTypeObject *a, PyTypeObject *b) { + PyObject *mro; + if (cls == a || cls == b) return 1; + mro = cls->tp_mro; + if (likely(mro)) { + Py_ssize_t i, n; + n = PyTuple_GET_SIZE(mro); + for (i = 0; i < n; i++) { + PyObject *base = PyTuple_GET_ITEM(mro, i); + if (base == (PyObject *)a || base == (PyObject *)b) + return 1; + } + return 0; + } + return __Pyx_InBases(cls, a) || __Pyx_InBases(cls, b); +} +static CYTHON_INLINE int __Pyx_inner_PyErr_GivenExceptionMatches2(PyObject *err, PyObject* exc_type1, PyObject *exc_type2) { + if (exc_type1) { + return __Pyx_IsAnySubtype2((PyTypeObject*)err, (PyTypeObject*)exc_type1, (PyTypeObject*)exc_type2); + } else { + return __Pyx_IsSubtype((PyTypeObject*)err, (PyTypeObject*)exc_type2); + } +} +static int __Pyx_PyErr_GivenExceptionMatchesTuple(PyObject *exc_type, PyObject *tuple) { + Py_ssize_t i, n; + assert(PyExceptionClass_Check(exc_type)); + n = PyTuple_GET_SIZE(tuple); + for (i=0; i>= 8; + ++i; + } + __Pyx_cached_runtime_version = version; + } +} +#endif +static unsigned long __Pyx_get_runtime_version(void) { +#if __PYX_LIMITED_VERSION_HEX >= 0x030b0000 + return Py_Version & ~0xFFUL; +#else + return __Pyx_cached_runtime_version; +#endif +} + +/* CheckBinaryVersion */ +static int __Pyx_check_binary_version(unsigned long ct_version, unsigned long rt_version, int allow_newer) { + const unsigned long MAJOR_MINOR = 0xFFFF0000UL; + if ((rt_version & MAJOR_MINOR) == (ct_version & MAJOR_MINOR)) + return 0; + if (likely(allow_newer && (rt_version & MAJOR_MINOR) > (ct_version & MAJOR_MINOR))) + return 1; + { + char message[200]; + PyOS_snprintf(message, sizeof(message), + "compile time Python version %d.%d " + "of module '%.100s' " + "%s " + "runtime version %d.%d", + (int) (ct_version >> 24), (int) ((ct_version >> 16) & 0xFF), + __Pyx_MODULE_NAME, + (allow_newer) ? "was newer than" : "does not match", + (int) (rt_version >> 24), (int) ((rt_version >> 16) & 0xFF) + ); + return PyErr_WarnEx(NULL, message, 1); + } +} + +/* NewCodeObj */ +#if CYTHON_COMPILING_IN_LIMITED_API + static PyObject* __Pyx__PyCode_New(int a, int p, int k, int l, int s, int f, + PyObject *code, PyObject *c, PyObject* n, PyObject *v, + PyObject *fv, PyObject *cell, PyObject* fn, + PyObject *name, int fline, PyObject *lnos) { + PyObject *exception_table = NULL; + PyObject *types_module=NULL, *code_type=NULL, *result=NULL; + #if __PYX_LIMITED_VERSION_HEX < 0x030b0000 + PyObject *version_info; + PyObject *py_minor_version = NULL; + #endif + long minor_version = 0; + PyObject *type, *value, *traceback; + PyErr_Fetch(&type, &value, &traceback); + #if __PYX_LIMITED_VERSION_HEX >= 0x030b0000 + minor_version = 11; + #else + if (!(version_info = PySys_GetObject("version_info"))) goto end; + if (!(py_minor_version = PySequence_GetItem(version_info, 1))) goto end; + minor_version = PyLong_AsLong(py_minor_version); + Py_DECREF(py_minor_version); + if (minor_version == -1 && PyErr_Occurred()) goto end; + #endif + if (!(types_module = PyImport_ImportModule("types"))) goto end; + if (!(code_type = PyObject_GetAttrString(types_module, "CodeType"))) goto end; + if (minor_version <= 7) { + (void)p; + result = PyObject_CallFunction(code_type, "iiiiiOOOOOOiOOO", a, k, l, s, f, code, + c, n, v, fn, name, fline, lnos, fv, cell); + } else if (minor_version <= 10) { + result = PyObject_CallFunction(code_type, "iiiiiiOOOOOOiOOO", a,p, k, l, s, f, code, + c, n, v, fn, name, fline, lnos, fv, cell); + } else { + if (!(exception_table = PyBytes_FromStringAndSize(NULL, 0))) goto end; + result = PyObject_CallFunction(code_type, "iiiiiiOOOOOOOiOOOO", a,p, k, l, s, f, code, + c, n, v, fn, name, name, fline, lnos, exception_table, fv, cell); + } + end: + Py_XDECREF(code_type); + Py_XDECREF(exception_table); + Py_XDECREF(types_module); + if (type) { + PyErr_Restore(type, value, traceback); + } + return result; + } +#elif PY_VERSION_HEX >= 0x030B0000 + static PyCodeObject* __Pyx__PyCode_New(int a, int p, int k, int l, int s, int f, + PyObject *code, PyObject *c, PyObject* n, PyObject *v, + PyObject *fv, PyObject *cell, PyObject* fn, + PyObject *name, int fline, PyObject *lnos) { + PyCodeObject *result; + result = + #if PY_VERSION_HEX >= 0x030C0000 + PyUnstable_Code_NewWithPosOnlyArgs + #else + PyCode_NewWithPosOnlyArgs + #endif + (a, p, k, l, s, f, code, c, n, v, fv, cell, fn, name, name, fline, lnos, __pyx_mstate_global->__pyx_empty_bytes); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030c00A1 + if (likely(result)) + result->_co_firsttraceable = 0; + #endif + return result; + } +#elif !CYTHON_COMPILING_IN_PYPY + #define __Pyx__PyCode_New(a, p, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ + PyCode_NewWithPosOnlyArgs(a, p, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) +#else + #define __Pyx__PyCode_New(a, p, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ + PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) +#endif +static PyObject* __Pyx_PyCode_New( + const __Pyx_PyCode_New_function_description descr, + PyObject * const *varnames, + PyObject *filename, + PyObject *funcname, + PyObject *line_table, + PyObject *tuple_dedup_map +) { + PyObject *code_obj = NULL, *varnames_tuple_dedup = NULL, *code_bytes = NULL; + Py_ssize_t var_count = (Py_ssize_t) descr.nlocals; + PyObject *varnames_tuple = PyTuple_New(var_count); + if (unlikely(!varnames_tuple)) return NULL; + for (Py_ssize_t i=0; i < var_count; i++) { + Py_INCREF(varnames[i]); + if (__Pyx_PyTuple_SET_ITEM(varnames_tuple, i, varnames[i]) != (0)) goto done; + } + #if CYTHON_COMPILING_IN_LIMITED_API + varnames_tuple_dedup = PyDict_GetItem(tuple_dedup_map, varnames_tuple); + if (!varnames_tuple_dedup) { + if (unlikely(PyDict_SetItem(tuple_dedup_map, varnames_tuple, varnames_tuple) < 0)) goto done; + varnames_tuple_dedup = varnames_tuple; + } + #else + varnames_tuple_dedup = PyDict_SetDefault(tuple_dedup_map, varnames_tuple, varnames_tuple); + if (unlikely(!varnames_tuple_dedup)) goto done; + #endif + #if CYTHON_AVOID_BORROWED_REFS + Py_INCREF(varnames_tuple_dedup); + #endif + if (__PYX_LIMITED_VERSION_HEX >= (0x030b0000) && line_table != NULL && !CYTHON_COMPILING_IN_GRAAL) { + Py_ssize_t line_table_length = __Pyx_PyBytes_GET_SIZE(line_table); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(line_table_length == -1)) goto done; + #endif + Py_ssize_t code_len = (line_table_length * 2 + 4) & ~3LL; + code_bytes = PyBytes_FromStringAndSize(NULL, code_len); + if (unlikely(!code_bytes)) goto done; + char* c_code_bytes = PyBytes_AsString(code_bytes); + if (unlikely(!c_code_bytes)) goto done; + memset(c_code_bytes, 0, (size_t) code_len); + } + code_obj = (PyObject*) __Pyx__PyCode_New( + (int) descr.argcount, + (int) descr.num_posonly_args, + (int) descr.num_kwonly_args, + (int) descr.nlocals, + 0, + (int) descr.flags, + code_bytes ? code_bytes : __pyx_mstate_global->__pyx_empty_bytes, + __pyx_mstate_global->__pyx_empty_tuple, + __pyx_mstate_global->__pyx_empty_tuple, + varnames_tuple_dedup, + __pyx_mstate_global->__pyx_empty_tuple, + __pyx_mstate_global->__pyx_empty_tuple, + filename, + funcname, + (int) descr.first_line, + (__PYX_LIMITED_VERSION_HEX >= (0x030b0000) && line_table) ? line_table : __pyx_mstate_global->__pyx_empty_bytes + ); +done: + Py_XDECREF(code_bytes); + #if CYTHON_AVOID_BORROWED_REFS + Py_XDECREF(varnames_tuple_dedup); + #endif + Py_DECREF(varnames_tuple); + return code_obj; +} + +/* DecompressString */ +static PyObject *__Pyx_DecompressString(const char *s, Py_ssize_t length, int algo) { + PyObject *module = NULL, *decompress, *compressed_bytes, *decompressed; + const char* module_name = algo == 3 ? "compression.zstd" : algo == 2 ? "bz2" : "zlib"; + PyObject *methodname = PyUnicode_FromString("decompress"); + if (unlikely(!methodname)) return NULL; + #if __PYX_LIMITED_VERSION_HEX >= 0x030e0000 + if (algo == 3) { + PyObject *fromlist = Py_BuildValue("[O]", methodname); + if (unlikely(!fromlist)) goto bad; + module = PyImport_ImportModuleLevel("compression.zstd", NULL, NULL, fromlist, 0); + Py_DECREF(fromlist); + } else + #endif + module = PyImport_ImportModule(module_name); + if (unlikely(!module)) goto import_failed; + decompress = PyObject_GetAttr(module, methodname); + if (unlikely(!decompress)) goto import_failed; + { + #ifdef __cplusplus + char *memview_bytes = const_cast(s); + #else + #if defined(__clang__) + #pragma clang diagnostic push + #pragma clang diagnostic ignored "-Wcast-qual" + #elif !defined(__INTEL_COMPILER) && defined(__GNUC__) + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wcast-qual" + #endif + char *memview_bytes = (char*) s; + #if defined(__clang__) + #pragma clang diagnostic pop + #elif !defined(__INTEL_COMPILER) && defined(__GNUC__) + #pragma GCC diagnostic pop + #endif + #endif + #if CYTHON_COMPILING_IN_LIMITED_API && !defined(PyBUF_READ) + int memview_flags = 0x100; + #else + int memview_flags = PyBUF_READ; + #endif + compressed_bytes = PyMemoryView_FromMemory(memview_bytes, length, memview_flags); + } + if (unlikely(!compressed_bytes)) { + Py_DECREF(decompress); + goto bad; + } + decompressed = PyObject_CallFunctionObjArgs(decompress, compressed_bytes, NULL); + Py_DECREF(compressed_bytes); + Py_DECREF(decompress); + Py_DECREF(module); + Py_DECREF(methodname); + return decompressed; +import_failed: + PyErr_Format(PyExc_ImportError, + "Failed to import '%.20s.decompress' - cannot initialise module strings. " + "String compression was configured with the C macro 'CYTHON_COMPRESS_STRINGS=%d'.", + module_name, algo); +bad: + Py_XDECREF(module); + Py_DECREF(methodname); + return NULL; +} + +#include +static CYTHON_INLINE Py_ssize_t __Pyx_ssize_strlen(const char *s) { + size_t len = strlen(s); + if (unlikely(len > (size_t) PY_SSIZE_T_MAX)) { + PyErr_SetString(PyExc_OverflowError, "byte string is too long"); + return -1; + } + return (Py_ssize_t) len; +} +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char* c_str) { + Py_ssize_t len = __Pyx_ssize_strlen(c_str); + if (unlikely(len < 0)) return NULL; + return __Pyx_PyUnicode_FromStringAndSize(c_str, len); +} +static CYTHON_INLINE PyObject* __Pyx_PyByteArray_FromString(const char* c_str) { + Py_ssize_t len = __Pyx_ssize_strlen(c_str); + if (unlikely(len < 0)) return NULL; + return PyByteArray_FromStringAndSize(c_str, len); +} +static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject* o) { + Py_ssize_t ignore; + return __Pyx_PyObject_AsStringAndSize(o, &ignore); +} +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 +static CYTHON_INLINE const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *length) { + if (unlikely(__Pyx_PyUnicode_READY(o) == -1)) return NULL; +#if CYTHON_COMPILING_IN_LIMITED_API + { + const char* result; + Py_ssize_t unicode_length; + CYTHON_MAYBE_UNUSED_VAR(unicode_length); // only for __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + #if __PYX_LIMITED_VERSION_HEX < 0x030A0000 + if (unlikely(PyArg_Parse(o, "s#", &result, length) < 0)) return NULL; + #else + result = PyUnicode_AsUTF8AndSize(o, length); + #endif + #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + unicode_length = PyUnicode_GetLength(o); + if (unlikely(unicode_length < 0)) return NULL; + if (unlikely(unicode_length != *length)) { + PyUnicode_AsASCIIString(o); + return NULL; + } + #endif + return result; + } +#else +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + if (likely(PyUnicode_IS_ASCII(o))) { + *length = PyUnicode_GET_LENGTH(o); + return PyUnicode_AsUTF8(o); + } else { + PyUnicode_AsASCIIString(o); + return NULL; + } +#else + return PyUnicode_AsUTF8AndSize(o, length); +#endif +#endif +} +#endif +static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 + if (PyUnicode_Check(o)) { + return __Pyx_PyUnicode_AsStringAndSize(o, length); + } else +#endif + if (PyByteArray_Check(o)) { +#if (CYTHON_ASSUME_SAFE_SIZE && CYTHON_ASSUME_SAFE_MACROS) || (CYTHON_COMPILING_IN_PYPY && (defined(PyByteArray_AS_STRING) && defined(PyByteArray_GET_SIZE))) + *length = PyByteArray_GET_SIZE(o); + return PyByteArray_AS_STRING(o); +#else + *length = PyByteArray_Size(o); + if (*length == -1) return NULL; + return PyByteArray_AsString(o); +#endif + } else + { + char* result; + int r = PyBytes_AsStringAndSize(o, &result, length); + if (unlikely(r < 0)) { + return NULL; + } else { + return result; + } + } +} +static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { + int is_true = x == Py_True; + if (is_true | (x == Py_False) | (x == Py_None)) return is_true; + else return PyObject_IsTrue(x); +} +static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject* x) { + int retval; + if (unlikely(!x)) return -1; + retval = __Pyx_PyObject_IsTrue(x); + Py_DECREF(x); + return retval; +} +static PyObject* __Pyx_PyNumber_LongWrongResultType(PyObject* result) { + __Pyx_TypeName result_type_name = __Pyx_PyType_GetFullyQualifiedName(Py_TYPE(result)); + if (PyLong_Check(result)) { + if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1, + "__int__ returned non-int (type " __Pyx_FMT_TYPENAME "). " + "The ability to return an instance of a strict subclass of int is deprecated, " + "and may be removed in a future version of Python.", + result_type_name)) { + __Pyx_DECREF_TypeName(result_type_name); + Py_DECREF(result); + return NULL; + } + __Pyx_DECREF_TypeName(result_type_name); + return result; + } + PyErr_Format(PyExc_TypeError, + "__int__ returned non-int (type " __Pyx_FMT_TYPENAME ")", + result_type_name); + __Pyx_DECREF_TypeName(result_type_name); + Py_DECREF(result); + return NULL; +} +static CYTHON_INLINE PyObject* __Pyx_PyNumber_Long(PyObject* x) { +#if CYTHON_USE_TYPE_SLOTS + PyNumberMethods *m; +#endif + PyObject *res = NULL; + if (likely(PyLong_Check(x))) + return __Pyx_NewRef(x); +#if CYTHON_USE_TYPE_SLOTS + m = Py_TYPE(x)->tp_as_number; + if (likely(m && m->nb_int)) { + res = m->nb_int(x); + } +#else + if (!PyBytes_CheckExact(x) && !PyUnicode_CheckExact(x)) { + res = PyNumber_Long(x); + } +#endif + if (likely(res)) { + if (unlikely(!PyLong_CheckExact(res))) { + return __Pyx_PyNumber_LongWrongResultType(res); + } + } + else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_TypeError, + "an integer is required"); + } + return res; +} +static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { + Py_ssize_t ival; + PyObject *x; + if (likely(PyLong_CheckExact(b))) { + #if CYTHON_USE_PYLONG_INTERNALS + if (likely(__Pyx_PyLong_IsCompact(b))) { + return __Pyx_PyLong_CompactValue(b); + } else { + const digit* digits = __Pyx_PyLong_Digits(b); + const Py_ssize_t size = __Pyx_PyLong_SignedDigitCount(b); + switch (size) { + case 2: + if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { + return (Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case -2: + if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { + return -(Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case 3: + if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { + return (Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case -3: + if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { + return -(Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case 4: + if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { + return (Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case -4: + if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { + return -(Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + } + } + #endif + return PyLong_AsSsize_t(b); + } + x = PyNumber_Index(b); + if (!x) return -1; + ival = PyLong_AsSsize_t(x); + Py_DECREF(x); + return ival; +} +static CYTHON_INLINE Py_hash_t __Pyx_PyIndex_AsHash_t(PyObject* o) { + if (sizeof(Py_hash_t) == sizeof(Py_ssize_t)) { + return (Py_hash_t) __Pyx_PyIndex_AsSsize_t(o); + } else { + Py_ssize_t ival; + PyObject *x; + x = PyNumber_Index(o); + if (!x) return -1; + ival = PyLong_AsLong(x); + Py_DECREF(x); + return ival; + } +} +static CYTHON_INLINE PyObject *__Pyx_Owned_Py_None(int b) { + CYTHON_UNUSED_VAR(b); + return __Pyx_NewRef(Py_None); +} +static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b) { + return __Pyx_NewRef(b ? Py_True: Py_False); +} +static CYTHON_INLINE PyObject * __Pyx_PyLong_FromSize_t(size_t ival) { + return PyLong_FromSize_t(ival); +} + + +/* MultiPhaseInitModuleState */ +#if CYTHON_PEP489_MULTI_PHASE_INIT && CYTHON_USE_MODULE_STATE +#ifndef CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE +#if (CYTHON_COMPILING_IN_LIMITED_API || PY_VERSION_HEX >= 0x030C0000) + #define CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE 1 +#else + #define CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE 0 +#endif +#endif +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE && !CYTHON_ATOMICS +#error "Module state with PEP489 requires atomics. Currently that's one of\ + C11, C++11, gcc atomic intrinsics or MSVC atomic intrinsics" +#endif +#if !CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE +#define __Pyx_ModuleStateLookup_Lock() +#define __Pyx_ModuleStateLookup_Unlock() +#elif !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d0000 +static PyMutex __Pyx_ModuleStateLookup_mutex = {0}; +#define __Pyx_ModuleStateLookup_Lock() PyMutex_Lock(&__Pyx_ModuleStateLookup_mutex) +#define __Pyx_ModuleStateLookup_Unlock() PyMutex_Unlock(&__Pyx_ModuleStateLookup_mutex) +#elif defined(__cplusplus) && __cplusplus >= 201103L +#include +static std::mutex __Pyx_ModuleStateLookup_mutex; +#define __Pyx_ModuleStateLookup_Lock() __Pyx_ModuleStateLookup_mutex.lock() +#define __Pyx_ModuleStateLookup_Unlock() __Pyx_ModuleStateLookup_mutex.unlock() +#elif defined(__STDC_VERSION__) && (__STDC_VERSION__ > 201112L) && !defined(__STDC_NO_THREADS__) +#include +static mtx_t __Pyx_ModuleStateLookup_mutex; +static once_flag __Pyx_ModuleStateLookup_mutex_once_flag = ONCE_FLAG_INIT; +static void __Pyx_ModuleStateLookup_initialize_mutex(void) { + mtx_init(&__Pyx_ModuleStateLookup_mutex, mtx_plain); +} +#define __Pyx_ModuleStateLookup_Lock()\ + call_once(&__Pyx_ModuleStateLookup_mutex_once_flag, __Pyx_ModuleStateLookup_initialize_mutex);\ + mtx_lock(&__Pyx_ModuleStateLookup_mutex) +#define __Pyx_ModuleStateLookup_Unlock() mtx_unlock(&__Pyx_ModuleStateLookup_mutex) +#elif defined(HAVE_PTHREAD_H) +#include +static pthread_mutex_t __Pyx_ModuleStateLookup_mutex = PTHREAD_MUTEX_INITIALIZER; +#define __Pyx_ModuleStateLookup_Lock() pthread_mutex_lock(&__Pyx_ModuleStateLookup_mutex) +#define __Pyx_ModuleStateLookup_Unlock() pthread_mutex_unlock(&__Pyx_ModuleStateLookup_mutex) +#elif defined(_WIN32) +#include // synchapi.h on its own doesn't work +static SRWLOCK __Pyx_ModuleStateLookup_mutex = SRWLOCK_INIT; +#define __Pyx_ModuleStateLookup_Lock() AcquireSRWLockExclusive(&__Pyx_ModuleStateLookup_mutex) +#define __Pyx_ModuleStateLookup_Unlock() ReleaseSRWLockExclusive(&__Pyx_ModuleStateLookup_mutex) +#else +#error "No suitable lock available for CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE.\ + Requires C standard >= C11, or C++ standard >= C++11,\ + or pthreads, or the Windows 32 API, or Python >= 3.13." +#endif +typedef struct { + int64_t id; + PyObject *module; +} __Pyx_InterpreterIdAndModule; +typedef struct { + char interpreter_id_as_index; + Py_ssize_t count; + Py_ssize_t allocated; + __Pyx_InterpreterIdAndModule table[1]; +} __Pyx_ModuleStateLookupData; +#define __PYX_MODULE_STATE_LOOKUP_SMALL_SIZE 32 +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE +static __pyx_atomic_int_type __Pyx_ModuleStateLookup_read_counter = 0; +#endif +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE +static __pyx_atomic_ptr_type __Pyx_ModuleStateLookup_data = 0; +#else +static __Pyx_ModuleStateLookupData* __Pyx_ModuleStateLookup_data = NULL; +#endif +static __Pyx_InterpreterIdAndModule* __Pyx_State_FindModuleStateLookupTableLowerBound( + __Pyx_InterpreterIdAndModule* table, + Py_ssize_t count, + int64_t interpreterId) { + __Pyx_InterpreterIdAndModule* begin = table; + __Pyx_InterpreterIdAndModule* end = begin + count; + if (begin->id == interpreterId) { + return begin; + } + while ((end - begin) > __PYX_MODULE_STATE_LOOKUP_SMALL_SIZE) { + __Pyx_InterpreterIdAndModule* halfway = begin + (end - begin)/2; + if (halfway->id == interpreterId) { + return halfway; + } + if (halfway->id < interpreterId) { + begin = halfway; + } else { + end = halfway; + } + } + for (; begin < end; ++begin) { + if (begin->id >= interpreterId) return begin; + } + return begin; +} +static PyObject *__Pyx_State_FindModule(CYTHON_UNUSED void* dummy) { + int64_t interpreter_id = PyInterpreterState_GetID(__Pyx_PyInterpreterState_Get()); + if (interpreter_id == -1) return NULL; +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE + __Pyx_ModuleStateLookupData* data = (__Pyx_ModuleStateLookupData*)__pyx_atomic_pointer_load_relaxed(&__Pyx_ModuleStateLookup_data); + { + __pyx_atomic_incr_acq_rel(&__Pyx_ModuleStateLookup_read_counter); + if (likely(data)) { + __Pyx_ModuleStateLookupData* new_data = (__Pyx_ModuleStateLookupData*)__pyx_atomic_pointer_load_acquire(&__Pyx_ModuleStateLookup_data); + if (likely(data == new_data)) { + goto read_finished; + } + } + __pyx_atomic_decr_acq_rel(&__Pyx_ModuleStateLookup_read_counter); + __Pyx_ModuleStateLookup_Lock(); + __pyx_atomic_incr_relaxed(&__Pyx_ModuleStateLookup_read_counter); + data = (__Pyx_ModuleStateLookupData*)__pyx_atomic_pointer_load_relaxed(&__Pyx_ModuleStateLookup_data); + __Pyx_ModuleStateLookup_Unlock(); + } + read_finished:; +#else + __Pyx_ModuleStateLookupData* data = __Pyx_ModuleStateLookup_data; +#endif + __Pyx_InterpreterIdAndModule* found = NULL; + if (unlikely(!data)) goto end; + if (data->interpreter_id_as_index) { + if (interpreter_id < data->count) { + found = data->table+interpreter_id; + } + } else { + found = __Pyx_State_FindModuleStateLookupTableLowerBound( + data->table, data->count, interpreter_id); + } + end: + { + PyObject *result=NULL; + if (found && found->id == interpreter_id) { + result = found->module; + } +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE + __pyx_atomic_decr_acq_rel(&__Pyx_ModuleStateLookup_read_counter); +#endif + return result; + } +} +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE +static void __Pyx_ModuleStateLookup_wait_until_no_readers(void) { + while (__pyx_atomic_load(&__Pyx_ModuleStateLookup_read_counter) != 0); +} +#else +#define __Pyx_ModuleStateLookup_wait_until_no_readers() +#endif +static int __Pyx_State_AddModuleInterpIdAsIndex(__Pyx_ModuleStateLookupData **old_data, PyObject* module, int64_t interpreter_id) { + Py_ssize_t to_allocate = (*old_data)->allocated; + while (to_allocate <= interpreter_id) { + if (to_allocate == 0) to_allocate = 1; + else to_allocate *= 2; + } + __Pyx_ModuleStateLookupData *new_data = *old_data; + if (to_allocate != (*old_data)->allocated) { + new_data = (__Pyx_ModuleStateLookupData *)realloc( + *old_data, + sizeof(__Pyx_ModuleStateLookupData)+(to_allocate-1)*sizeof(__Pyx_InterpreterIdAndModule)); + if (!new_data) { + PyErr_NoMemory(); + return -1; + } + for (Py_ssize_t i = new_data->allocated; i < to_allocate; ++i) { + new_data->table[i].id = i; + new_data->table[i].module = NULL; + } + new_data->allocated = to_allocate; + } + new_data->table[interpreter_id].module = module; + if (new_data->count < interpreter_id+1) { + new_data->count = interpreter_id+1; + } + *old_data = new_data; + return 0; +} +static void __Pyx_State_ConvertFromInterpIdAsIndex(__Pyx_ModuleStateLookupData *data) { + __Pyx_InterpreterIdAndModule *read = data->table; + __Pyx_InterpreterIdAndModule *write = data->table; + __Pyx_InterpreterIdAndModule *end = read + data->count; + for (; readmodule) { + write->id = read->id; + write->module = read->module; + ++write; + } + } + data->count = write - data->table; + for (; writeid = 0; + write->module = NULL; + } + data->interpreter_id_as_index = 0; +} +static int __Pyx_State_AddModule(PyObject* module, CYTHON_UNUSED void* dummy) { + int64_t interpreter_id = PyInterpreterState_GetID(__Pyx_PyInterpreterState_Get()); + if (interpreter_id == -1) return -1; + int result = 0; + __Pyx_ModuleStateLookup_Lock(); +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE + __Pyx_ModuleStateLookupData *old_data = (__Pyx_ModuleStateLookupData *) + __pyx_atomic_pointer_exchange(&__Pyx_ModuleStateLookup_data, 0); +#else + __Pyx_ModuleStateLookupData *old_data = __Pyx_ModuleStateLookup_data; +#endif + __Pyx_ModuleStateLookupData *new_data = old_data; + if (!new_data) { + new_data = (__Pyx_ModuleStateLookupData *)calloc(1, sizeof(__Pyx_ModuleStateLookupData)); + if (!new_data) { + result = -1; + PyErr_NoMemory(); + goto end; + } + new_data->allocated = 1; + new_data->interpreter_id_as_index = 1; + } + __Pyx_ModuleStateLookup_wait_until_no_readers(); + if (new_data->interpreter_id_as_index) { + if (interpreter_id < __PYX_MODULE_STATE_LOOKUP_SMALL_SIZE) { + result = __Pyx_State_AddModuleInterpIdAsIndex(&new_data, module, interpreter_id); + goto end; + } + __Pyx_State_ConvertFromInterpIdAsIndex(new_data); + } + { + Py_ssize_t insert_at = 0; + { + __Pyx_InterpreterIdAndModule* lower_bound = __Pyx_State_FindModuleStateLookupTableLowerBound( + new_data->table, new_data->count, interpreter_id); + assert(lower_bound); + insert_at = lower_bound - new_data->table; + if (unlikely(insert_at < new_data->count && lower_bound->id == interpreter_id)) { + lower_bound->module = module; + goto end; // already in table, nothing more to do + } + } + if (new_data->count+1 >= new_data->allocated) { + Py_ssize_t to_allocate = (new_data->count+1)*2; + new_data = + (__Pyx_ModuleStateLookupData*)realloc( + new_data, + sizeof(__Pyx_ModuleStateLookupData) + + (to_allocate-1)*sizeof(__Pyx_InterpreterIdAndModule)); + if (!new_data) { + result = -1; + new_data = old_data; + PyErr_NoMemory(); + goto end; + } + new_data->allocated = to_allocate; + } + ++new_data->count; + int64_t last_id = interpreter_id; + PyObject *last_module = module; + for (Py_ssize_t i=insert_at; icount; ++i) { + int64_t current_id = new_data->table[i].id; + new_data->table[i].id = last_id; + last_id = current_id; + PyObject *current_module = new_data->table[i].module; + new_data->table[i].module = last_module; + last_module = current_module; + } + } + end: +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE + __pyx_atomic_pointer_exchange(&__Pyx_ModuleStateLookup_data, new_data); +#else + __Pyx_ModuleStateLookup_data = new_data; +#endif + __Pyx_ModuleStateLookup_Unlock(); + return result; +} +static int __Pyx_State_RemoveModule(CYTHON_UNUSED void* dummy) { + int64_t interpreter_id = PyInterpreterState_GetID(__Pyx_PyInterpreterState_Get()); + if (interpreter_id == -1) return -1; + __Pyx_ModuleStateLookup_Lock(); +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE + __Pyx_ModuleStateLookupData *data = (__Pyx_ModuleStateLookupData *) + __pyx_atomic_pointer_exchange(&__Pyx_ModuleStateLookup_data, 0); +#else + __Pyx_ModuleStateLookupData *data = __Pyx_ModuleStateLookup_data; +#endif + if (data->interpreter_id_as_index) { + if (interpreter_id < data->count) { + data->table[interpreter_id].module = NULL; + } + goto done; + } + { + __Pyx_ModuleStateLookup_wait_until_no_readers(); + __Pyx_InterpreterIdAndModule* lower_bound = __Pyx_State_FindModuleStateLookupTableLowerBound( + data->table, data->count, interpreter_id); + if (!lower_bound) goto done; + if (lower_bound->id != interpreter_id) goto done; + __Pyx_InterpreterIdAndModule *end = data->table+data->count; + for (;lower_boundid = (lower_bound+1)->id; + lower_bound->module = (lower_bound+1)->module; + } + } + --data->count; + if (data->count == 0) { + free(data); + data = NULL; + } + done: +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE + __pyx_atomic_pointer_exchange(&__Pyx_ModuleStateLookup_data, data); +#else + __Pyx_ModuleStateLookup_data = data; +#endif + __Pyx_ModuleStateLookup_Unlock(); + return 0; +} +#endif + +/* #### Code section: utility_code_pragmas_end ### */ +#ifdef _MSC_VER +#pragma warning( pop ) +#endif + + + +/* #### Code section: end ### */ +#endif /* Py_PYTHON_H */ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/cybase.pxd b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/cybase.pxd new file mode 100644 index 0000000000000000000000000000000000000000..81586668678a80834c215e4f85c63c90c017cff6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/cybase.pxd @@ -0,0 +1,26 @@ +# cython: freethreading_compatible = True + +cdef enum: + DEFAULT_BUFFER = 4096 + STACK_STRING_LEN = 4096 + +cdef class TCyBuffer(object): + cdef: + char *buf + int cur, buf_size, data_size + + void move_to_start(self) + void clean(self) + int write(self, int sz, const char *value) + int grow(self, int min_size) + read_trans(self, trans, int sz, char *out) + + +cdef class CyTransportBase(object): + cdef object trans + + cdef c_read(self, int sz, char* out) + cdef c_write(self, char* data, int sz) + cdef c_flush(self) + + cdef get_string(self, int sz) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/cybase.pyx b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/cybase.pyx new file mode 100644 index 0000000000000000000000000000000000000000..192ccabfd6a133e4f38c5672716c125b53c2ca31 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/cybase.pyx @@ -0,0 +1,140 @@ +# cython: freethreading_compatible = True + +from libc.stdlib cimport malloc, free +from libc.string cimport memcpy, memmove + + +cdef class TCyBuffer(object): + def __cinit__(self, buf_size): + self.buf = malloc(buf_size) + self.buf_size = buf_size + self.cur = 0 + self.data_size = 0 + + def __dealloc__(self): + if self.buf != NULL: + free(self.buf) + self.buf = NULL + + cdef void move_to_start(self): + memmove(self.buf, self.buf + self.cur, self.data_size) + self.cur = 0 + + cdef void clean(self): + self.cur = 0 + self.data_size = 0 + + cdef int write(self, int sz, const char *value): + cdef: + int cap = self.buf_size - self.data_size + int remain = cap - self.cur + + if sz <= 0: + return 0 + + if remain < sz: + self.move_to_start() + + # recompute remain spaces + remain = cap - self.cur + + if remain < sz: + if self.grow(sz - remain + self.buf_size) != 0: + return -1 + + memcpy(self.buf + self.cur + self.data_size, value, sz) + self.data_size += sz + + return sz + + cdef read_trans(self, trans, int sz, char *out): + cdef int cap, new_data_len + + if sz <= 0: + return 0 + + if self.data_size < sz: + if self.buf_size < sz: + if self.grow(sz) != 0: + return -2 # grow buffer error + + cap = self.buf_size - self.data_size + + new_data = trans.read(cap) + new_data_len = len(new_data) + + while new_data_len + self.data_size < sz: + more = trans.read(cap - new_data_len) + more_len = len(more) + if more_len <= 0: + return -1 # end of file error + + new_data += more + new_data_len += more_len + + if cap - self.cur < new_data_len: + self.move_to_start() + + memcpy(self.buf + self.cur + self.data_size, new_data, + new_data_len) + self.data_size += new_data_len + + memcpy(out, self.buf + self.cur, sz) + self.cur += sz + self.data_size -= sz + + return sz + + cdef int grow(self, int min_size): + if min_size <= self.buf_size: + return 0 + + cdef int multiples = min_size // self.buf_size + if min_size % self.buf_size != 0: + multiples += 1 + + cdef int new_size = self.buf_size * multiples + cdef char *new_buf = malloc(new_size) + if new_buf == NULL: + return -1 + memcpy(new_buf + self.cur, self.buf + self.cur, self.data_size) + free(self.buf) + self.buf_size = new_size + self.buf = new_buf + return 0 + + +cdef class CyTransportBase(object): + cdef c_read(self, int sz, char* out): + pass + + cdef c_write(self, char* data, int sz): + pass + + cdef c_flush(self): + pass + + def clean(self): + pass + + @property + def sock(self): + if not self.trans: + return + return getattr(self.trans, 'sock', None) + + cdef get_string(self, int sz): + cdef: + char out[STACK_STRING_LEN] + char *dy_out + + if sz > STACK_STRING_LEN: + dy_out = malloc(sz) + try: + size = self.c_read(sz, dy_out) + return dy_out[:size] + finally: + free(dy_out) + else: + size = self.c_read(sz, out) + return out[:size] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/framed/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/framed/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ccbc3c243056bedf488387f1d7b4e5325e361bb2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/framed/__init__.py @@ -0,0 +1,74 @@ +# -*- coding: utf-8 -*- + +from __future__ import absolute_import + +import struct +from io import BytesIO + +from thriftpy2._compat import CYTHON +from ..base import TTransportBase, readall +from ..buffered import TBufferedTransport + + +class TFramedTransport(TTransportBase): + """Class that wraps another transport and frames its I/O when writing.""" + def __init__(self, trans): + self._trans = trans + self._rbuf = BytesIO() + self._wbuf = BytesIO() + + def is_open(self): + return self._trans.is_open() + + def open(self): + return self._trans.open() + + def close(self): + return self._trans.close() + + def read(self, sz): + # Important: don't attempt to read the next frame if the caller + # doesn't actually need any data. + if sz == 0: + return b'' + + ret = self._rbuf.read(sz) + if len(ret) != 0: + return ret + + self.read_frame() + return self._rbuf.read(sz) + + def read_frame(self): + buff = readall(self._trans.read, 4) + sz, = struct.unpack('!i', buff) + frame = readall(self._trans.read, sz) + self._rbuf = BytesIO(frame) + + def write(self, buf): + self._wbuf.write(buf) + + def flush(self): + # reset wbuf before write/flush to preserve state on underlying failure + out = self._wbuf.getvalue() + self._wbuf = BytesIO() + + # N.B.: Doing this string concatenation is WAY cheaper than making + # two separate calls to the underlying socket object. Socket writes in + # Python turn out to be REALLY expensive, but it seems to do a pretty + # good job of managing string buffer operations without excessive + # copies + self._trans.write(struct.pack("!i", len(out)) + out) + self._trans.flush() + + def getvalue(self): + return self._trans.getvalue() + + +class TFramedTransportFactory(object): + def get_transport(self, trans): + return TBufferedTransport(TFramedTransport(trans)) + + +if CYTHON: + from .cyframed import TCyFramedTransport, TCyFramedTransportFactory # noqa diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/framed/cyframed.c b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/framed/cyframed.c new file mode 100644 index 0000000000000000000000000000000000000000..f13637b645d4d3a56ae72966c405e2956672423c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/framed/cyframed.c @@ -0,0 +1,13352 @@ +/* Generated by Cython 3.2.4 */ + +/* BEGIN: Cython Metadata +{ + "distutils": { + "depends": [ + "thriftpy2/protocol/cybin/endian_port.h" + ], + "include_dirs": [ + "thriftpy2/transport/framed" + ], + "name": "thriftpy2.transport.framed.cyframed", + "sources": [ + "thriftpy2/transport/framed/cyframed.pyx" + ] + }, + "module_name": "thriftpy2.transport.framed.cyframed" +} +END: Cython Metadata */ + +#ifndef PY_SSIZE_T_CLEAN +#define PY_SSIZE_T_CLEAN +#endif /* PY_SSIZE_T_CLEAN */ +/* InitLimitedAPI */ +#if defined(Py_LIMITED_API) + #if !defined(CYTHON_LIMITED_API) + #define CYTHON_LIMITED_API 1 + #endif +#elif defined(CYTHON_LIMITED_API) + #ifdef _MSC_VER + #pragma message ("Limited API usage is enabled with 'CYTHON_LIMITED_API' but 'Py_LIMITED_API' does not define a Python target version. Consider setting 'Py_LIMITED_API' instead.") + #else + #warning Limited API usage is enabled with 'CYTHON_LIMITED_API' but 'Py_LIMITED_API' does not define a Python target version. Consider setting 'Py_LIMITED_API' instead. + #endif +#endif + +#include "Python.h" +#ifndef Py_PYTHON_H + #error Python headers needed to compile C extensions, please install development version of Python. +#elif PY_VERSION_HEX < 0x03080000 + #error Cython requires Python 3.8+. +#else +#define __PYX_ABI_VERSION "3_2_4" +#define CYTHON_HEX_VERSION 0x030204F0 +#define CYTHON_FUTURE_DIVISION 1 +/* CModulePreamble */ +#include +#ifndef offsetof + #define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) +#endif +#if !defined(_WIN32) && !defined(WIN32) && !defined(MS_WINDOWS) + #ifndef __stdcall + #define __stdcall + #endif + #ifndef __cdecl + #define __cdecl + #endif + #ifndef __fastcall + #define __fastcall + #endif +#endif +#ifndef DL_IMPORT + #define DL_IMPORT(t) t +#endif +#ifndef DL_EXPORT + #define DL_EXPORT(t) t +#endif +#define __PYX_COMMA , +#ifndef PY_LONG_LONG + #define PY_LONG_LONG LONG_LONG +#endif +#ifndef Py_HUGE_VAL + #define Py_HUGE_VAL HUGE_VAL +#endif +#define __PYX_LIMITED_VERSION_HEX PY_VERSION_HEX +#if defined(GRAALVM_PYTHON) + /* For very preliminary testing purposes. Most variables are set the same as PyPy. + The existence of this section does not imply that anything works or is even tested */ + #define CYTHON_COMPILING_IN_PYPY 0 + #define CYTHON_COMPILING_IN_CPYTHON 0 + #define CYTHON_COMPILING_IN_LIMITED_API 0 + #define CYTHON_COMPILING_IN_GRAAL 1 + #define CYTHON_COMPILING_IN_CPYTHON_FREETHREADING 0 + #undef CYTHON_USE_TYPE_SLOTS + #define CYTHON_USE_TYPE_SLOTS 0 + #undef CYTHON_USE_TYPE_SPECS + #define CYTHON_USE_TYPE_SPECS 0 + #undef CYTHON_USE_PYTYPE_LOOKUP + #define CYTHON_USE_PYTYPE_LOOKUP 0 + #undef CYTHON_USE_PYLIST_INTERNALS + #define CYTHON_USE_PYLIST_INTERNALS 0 + #undef CYTHON_USE_UNICODE_INTERNALS + #define CYTHON_USE_UNICODE_INTERNALS 0 + #undef CYTHON_USE_UNICODE_WRITER + #define CYTHON_USE_UNICODE_WRITER 0 + #undef CYTHON_USE_PYLONG_INTERNALS + #define CYTHON_USE_PYLONG_INTERNALS 0 + #undef CYTHON_AVOID_BORROWED_REFS + #define CYTHON_AVOID_BORROWED_REFS 1 + #undef CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + #define CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS 0 + #undef CYTHON_ASSUME_SAFE_MACROS + #define CYTHON_ASSUME_SAFE_MACROS 0 + #undef CYTHON_ASSUME_SAFE_SIZE + #define CYTHON_ASSUME_SAFE_SIZE 0 + #undef CYTHON_UNPACK_METHODS + #define CYTHON_UNPACK_METHODS 0 + #undef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 0 + #undef CYTHON_FAST_GIL + #define CYTHON_FAST_GIL 0 + #undef CYTHON_METH_FASTCALL + #define CYTHON_METH_FASTCALL 0 + #undef CYTHON_FAST_PYCALL + #define CYTHON_FAST_PYCALL 0 + #ifndef CYTHON_PEP487_INIT_SUBCLASS + #define CYTHON_PEP487_INIT_SUBCLASS 1 + #endif + #undef CYTHON_PEP489_MULTI_PHASE_INIT + #define CYTHON_PEP489_MULTI_PHASE_INIT 1 + #undef CYTHON_USE_MODULE_STATE + #define CYTHON_USE_MODULE_STATE 0 + #undef CYTHON_USE_SYS_MONITORING + #define CYTHON_USE_SYS_MONITORING 0 + #undef CYTHON_USE_TP_FINALIZE + #define CYTHON_USE_TP_FINALIZE 0 + #undef CYTHON_USE_AM_SEND + #define CYTHON_USE_AM_SEND 0 + #undef CYTHON_USE_DICT_VERSIONS + #define CYTHON_USE_DICT_VERSIONS 0 + #undef CYTHON_USE_EXC_INFO_STACK + #define CYTHON_USE_EXC_INFO_STACK 1 + #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC + #define CYTHON_UPDATE_DESCRIPTOR_DOC 0 + #endif + #undef CYTHON_USE_FREELISTS + #define CYTHON_USE_FREELISTS 0 + #undef CYTHON_IMMORTAL_CONSTANTS + #define CYTHON_IMMORTAL_CONSTANTS 0 +#elif defined(PYPY_VERSION) + #define CYTHON_COMPILING_IN_PYPY 1 + #define CYTHON_COMPILING_IN_CPYTHON 0 + #define CYTHON_COMPILING_IN_LIMITED_API 0 + #define CYTHON_COMPILING_IN_GRAAL 0 + #define CYTHON_COMPILING_IN_CPYTHON_FREETHREADING 0 + #undef CYTHON_USE_TYPE_SLOTS + #define CYTHON_USE_TYPE_SLOTS 1 + #ifndef CYTHON_USE_TYPE_SPECS + #define CYTHON_USE_TYPE_SPECS 0 + #endif + #undef CYTHON_USE_PYTYPE_LOOKUP + #define CYTHON_USE_PYTYPE_LOOKUP 0 + #undef CYTHON_USE_PYLIST_INTERNALS + #define CYTHON_USE_PYLIST_INTERNALS 0 + #undef CYTHON_USE_UNICODE_INTERNALS + #define CYTHON_USE_UNICODE_INTERNALS 0 + #undef CYTHON_USE_UNICODE_WRITER + #define CYTHON_USE_UNICODE_WRITER 0 + #undef CYTHON_USE_PYLONG_INTERNALS + #define CYTHON_USE_PYLONG_INTERNALS 0 + #undef CYTHON_AVOID_BORROWED_REFS + #define CYTHON_AVOID_BORROWED_REFS 1 + #undef CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + #define CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS 1 + #undef CYTHON_ASSUME_SAFE_MACROS + #define CYTHON_ASSUME_SAFE_MACROS 0 + #ifndef CYTHON_ASSUME_SAFE_SIZE + #define CYTHON_ASSUME_SAFE_SIZE 1 + #endif + #undef CYTHON_UNPACK_METHODS + #define CYTHON_UNPACK_METHODS 0 + #undef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 0 + #undef CYTHON_FAST_GIL + #define CYTHON_FAST_GIL 0 + #undef CYTHON_METH_FASTCALL + #define CYTHON_METH_FASTCALL 0 + #undef CYTHON_FAST_PYCALL + #define CYTHON_FAST_PYCALL 0 + #ifndef CYTHON_PEP487_INIT_SUBCLASS + #define CYTHON_PEP487_INIT_SUBCLASS 1 + #endif + #if PY_VERSION_HEX < 0x03090000 + #undef CYTHON_PEP489_MULTI_PHASE_INIT + #define CYTHON_PEP489_MULTI_PHASE_INIT 0 + #elif !defined(CYTHON_PEP489_MULTI_PHASE_INIT) + #define CYTHON_PEP489_MULTI_PHASE_INIT 1 + #endif + #undef CYTHON_USE_MODULE_STATE + #define CYTHON_USE_MODULE_STATE 0 + #undef CYTHON_USE_SYS_MONITORING + #define CYTHON_USE_SYS_MONITORING 0 + #ifndef CYTHON_USE_TP_FINALIZE + #define CYTHON_USE_TP_FINALIZE (PYPY_VERSION_NUM >= 0x07030C00) + #endif + #undef CYTHON_USE_AM_SEND + #define CYTHON_USE_AM_SEND 0 + #undef CYTHON_USE_DICT_VERSIONS + #define CYTHON_USE_DICT_VERSIONS 0 + #undef CYTHON_USE_EXC_INFO_STACK + #define CYTHON_USE_EXC_INFO_STACK 0 + #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC + #define CYTHON_UPDATE_DESCRIPTOR_DOC (PYPY_VERSION_NUM >= 0x07031100) + #endif + #undef CYTHON_USE_FREELISTS + #define CYTHON_USE_FREELISTS 0 + #undef CYTHON_IMMORTAL_CONSTANTS + #define CYTHON_IMMORTAL_CONSTANTS 0 +#elif defined(CYTHON_LIMITED_API) + #ifdef Py_LIMITED_API + #undef __PYX_LIMITED_VERSION_HEX + #define __PYX_LIMITED_VERSION_HEX Py_LIMITED_API + #endif + #define CYTHON_COMPILING_IN_PYPY 0 + #define CYTHON_COMPILING_IN_CPYTHON 0 + #define CYTHON_COMPILING_IN_LIMITED_API 1 + #define CYTHON_COMPILING_IN_GRAAL 0 + #define CYTHON_COMPILING_IN_CPYTHON_FREETHREADING 0 + #undef CYTHON_USE_TYPE_SLOTS + #define CYTHON_USE_TYPE_SLOTS 0 + #undef CYTHON_USE_TYPE_SPECS + #define CYTHON_USE_TYPE_SPECS 1 + #undef CYTHON_USE_PYTYPE_LOOKUP + #define CYTHON_USE_PYTYPE_LOOKUP 0 + #undef CYTHON_USE_PYLIST_INTERNALS + #define CYTHON_USE_PYLIST_INTERNALS 0 + #undef CYTHON_USE_UNICODE_INTERNALS + #define CYTHON_USE_UNICODE_INTERNALS 0 + #ifndef CYTHON_USE_UNICODE_WRITER + #define CYTHON_USE_UNICODE_WRITER 0 + #endif + #undef CYTHON_USE_PYLONG_INTERNALS + #define CYTHON_USE_PYLONG_INTERNALS 0 + #ifndef CYTHON_AVOID_BORROWED_REFS + #define CYTHON_AVOID_BORROWED_REFS 0 + #endif + #ifndef CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + #define CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS 0 + #endif + #undef CYTHON_ASSUME_SAFE_MACROS + #define CYTHON_ASSUME_SAFE_MACROS 0 + #undef CYTHON_ASSUME_SAFE_SIZE + #define CYTHON_ASSUME_SAFE_SIZE 0 + #undef CYTHON_UNPACK_METHODS + #define CYTHON_UNPACK_METHODS 0 + #undef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 0 + #undef CYTHON_FAST_GIL + #define CYTHON_FAST_GIL 0 + #undef CYTHON_METH_FASTCALL + #define CYTHON_METH_FASTCALL (__PYX_LIMITED_VERSION_HEX >= 0x030C0000) + #undef CYTHON_FAST_PYCALL + #define CYTHON_FAST_PYCALL 0 + #ifndef CYTHON_PEP487_INIT_SUBCLASS + #define CYTHON_PEP487_INIT_SUBCLASS 1 + #endif + #ifndef CYTHON_PEP489_MULTI_PHASE_INIT + #define CYTHON_PEP489_MULTI_PHASE_INIT 1 + #endif + #ifndef CYTHON_USE_MODULE_STATE + #define CYTHON_USE_MODULE_STATE 0 + #endif + #undef CYTHON_USE_SYS_MONITORING + #define CYTHON_USE_SYS_MONITORING 0 + #ifndef CYTHON_USE_TP_FINALIZE + #define CYTHON_USE_TP_FINALIZE 0 + #endif + #ifndef CYTHON_USE_AM_SEND + #define CYTHON_USE_AM_SEND (__PYX_LIMITED_VERSION_HEX >= 0x030A0000) + #endif + #undef CYTHON_USE_DICT_VERSIONS + #define CYTHON_USE_DICT_VERSIONS 0 + #undef CYTHON_USE_EXC_INFO_STACK + #define CYTHON_USE_EXC_INFO_STACK 0 + #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC + #define CYTHON_UPDATE_DESCRIPTOR_DOC 0 + #endif + #ifndef CYTHON_USE_FREELISTS + #define CYTHON_USE_FREELISTS 1 + #endif + #undef CYTHON_IMMORTAL_CONSTANTS + #define CYTHON_IMMORTAL_CONSTANTS 0 +#else + #define CYTHON_COMPILING_IN_PYPY 0 + #define CYTHON_COMPILING_IN_CPYTHON 1 + #define CYTHON_COMPILING_IN_LIMITED_API 0 + #define CYTHON_COMPILING_IN_GRAAL 0 + #ifdef Py_GIL_DISABLED + #define CYTHON_COMPILING_IN_CPYTHON_FREETHREADING 1 + #else + #define CYTHON_COMPILING_IN_CPYTHON_FREETHREADING 0 + #endif + #if PY_VERSION_HEX < 0x030A0000 + #undef CYTHON_USE_TYPE_SLOTS + #define CYTHON_USE_TYPE_SLOTS 1 + #elif !defined(CYTHON_USE_TYPE_SLOTS) + #define CYTHON_USE_TYPE_SLOTS 1 + #endif + #ifndef CYTHON_USE_TYPE_SPECS + #define CYTHON_USE_TYPE_SPECS 0 + #endif + #ifndef CYTHON_USE_PYTYPE_LOOKUP + #define CYTHON_USE_PYTYPE_LOOKUP 1 + #endif + #ifndef CYTHON_USE_PYLONG_INTERNALS + #define CYTHON_USE_PYLONG_INTERNALS 1 + #endif + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + #undef CYTHON_USE_PYLIST_INTERNALS + #define CYTHON_USE_PYLIST_INTERNALS 0 + #elif !defined(CYTHON_USE_PYLIST_INTERNALS) + #define CYTHON_USE_PYLIST_INTERNALS 1 + #endif + #ifndef CYTHON_USE_UNICODE_INTERNALS + #define CYTHON_USE_UNICODE_INTERNALS 1 + #endif + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING || PY_VERSION_HEX >= 0x030B00A2 + #undef CYTHON_USE_UNICODE_WRITER + #define CYTHON_USE_UNICODE_WRITER 0 + #elif !defined(CYTHON_USE_UNICODE_WRITER) + #define CYTHON_USE_UNICODE_WRITER 1 + #endif + #ifndef CYTHON_AVOID_BORROWED_REFS + #define CYTHON_AVOID_BORROWED_REFS 0 + #endif + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + #undef CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + #define CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS 1 + #elif !defined(CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS) + #define CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS 0 + #endif + #ifndef CYTHON_ASSUME_SAFE_MACROS + #define CYTHON_ASSUME_SAFE_MACROS 1 + #endif + #ifndef CYTHON_ASSUME_SAFE_SIZE + #define CYTHON_ASSUME_SAFE_SIZE 1 + #endif + #ifndef CYTHON_UNPACK_METHODS + #define CYTHON_UNPACK_METHODS 1 + #endif + #ifndef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 1 + #endif + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + #undef CYTHON_FAST_GIL + #define CYTHON_FAST_GIL 0 + #elif !defined(CYTHON_FAST_GIL) + #define CYTHON_FAST_GIL (PY_VERSION_HEX < 0x030C00A6) + #endif + #ifndef CYTHON_METH_FASTCALL + #define CYTHON_METH_FASTCALL 1 + #endif + #ifndef CYTHON_FAST_PYCALL + #define CYTHON_FAST_PYCALL 1 + #endif + #ifndef CYTHON_PEP487_INIT_SUBCLASS + #define CYTHON_PEP487_INIT_SUBCLASS 1 + #endif + #ifndef CYTHON_PEP489_MULTI_PHASE_INIT + #define CYTHON_PEP489_MULTI_PHASE_INIT 1 + #endif + #ifndef CYTHON_USE_MODULE_STATE + #define CYTHON_USE_MODULE_STATE 0 + #endif + #ifndef CYTHON_USE_SYS_MONITORING + #define CYTHON_USE_SYS_MONITORING (PY_VERSION_HEX >= 0x030d00B1) + #endif + #ifndef CYTHON_USE_TP_FINALIZE + #define CYTHON_USE_TP_FINALIZE 1 + #endif + #ifndef CYTHON_USE_AM_SEND + #define CYTHON_USE_AM_SEND 1 + #endif + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + #undef CYTHON_USE_DICT_VERSIONS + #define CYTHON_USE_DICT_VERSIONS 0 + #elif !defined(CYTHON_USE_DICT_VERSIONS) + #define CYTHON_USE_DICT_VERSIONS (PY_VERSION_HEX < 0x030C00A5 && !CYTHON_USE_MODULE_STATE) + #endif + #ifndef CYTHON_USE_EXC_INFO_STACK + #define CYTHON_USE_EXC_INFO_STACK 1 + #endif + #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC + #define CYTHON_UPDATE_DESCRIPTOR_DOC 1 + #endif + #ifndef CYTHON_USE_FREELISTS + #define CYTHON_USE_FREELISTS (!CYTHON_COMPILING_IN_CPYTHON_FREETHREADING) + #endif + #if defined(CYTHON_IMMORTAL_CONSTANTS) && PY_VERSION_HEX < 0x030C0000 + #undef CYTHON_IMMORTAL_CONSTANTS + #define CYTHON_IMMORTAL_CONSTANTS 0 // definitely won't work + #elif !defined(CYTHON_IMMORTAL_CONSTANTS) + #define CYTHON_IMMORTAL_CONSTANTS (PY_VERSION_HEX >= 0x030C0000 && !CYTHON_USE_MODULE_STATE && CYTHON_COMPILING_IN_CPYTHON_FREETHREADING) + #endif +#endif +#ifndef CYTHON_COMPRESS_STRINGS + #define CYTHON_COMPRESS_STRINGS 1 +#endif +#ifndef CYTHON_FAST_PYCCALL +#define CYTHON_FAST_PYCCALL CYTHON_FAST_PYCALL +#endif +#ifndef CYTHON_VECTORCALL +#if CYTHON_COMPILING_IN_LIMITED_API +#define CYTHON_VECTORCALL (__PYX_LIMITED_VERSION_HEX >= 0x030C0000) +#else +#define CYTHON_VECTORCALL (CYTHON_FAST_PYCCALL) +#endif +#endif +#if CYTHON_USE_PYLONG_INTERNALS + #undef SHIFT + #undef BASE + #undef MASK + #ifdef SIZEOF_VOID_P + enum { __pyx_check_sizeof_voidp = 1 / (int)(SIZEOF_VOID_P == sizeof(void*)) }; + #endif +#endif +#ifndef __has_attribute + #define __has_attribute(x) 0 +#endif +#ifndef __has_cpp_attribute + #define __has_cpp_attribute(x) 0 +#endif +#ifndef CYTHON_RESTRICT + #if defined(__GNUC__) + #define CYTHON_RESTRICT __restrict__ + #elif defined(_MSC_VER) && _MSC_VER >= 1400 + #define CYTHON_RESTRICT __restrict + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_RESTRICT restrict + #else + #define CYTHON_RESTRICT + #endif +#endif +#ifndef CYTHON_UNUSED + #if defined(__cplusplus) + /* for clang __has_cpp_attribute(maybe_unused) is true even before C++17 + * but leads to warnings with -pedantic, since it is a C++17 feature */ + #if ((defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) || __cplusplus >= 201703L) + #if __has_cpp_attribute(maybe_unused) + #define CYTHON_UNUSED [[maybe_unused]] + #endif + #endif + #endif +#endif +#ifndef CYTHON_UNUSED +# if defined(__GNUC__) +# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) +# define CYTHON_UNUSED __attribute__ ((__unused__)) +# else +# define CYTHON_UNUSED +# endif +# elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) +# define CYTHON_UNUSED __attribute__ ((__unused__)) +# else +# define CYTHON_UNUSED +# endif +#endif +#ifndef CYTHON_UNUSED_VAR +# if defined(__cplusplus) + template void CYTHON_UNUSED_VAR( const T& ) { } +# else +# define CYTHON_UNUSED_VAR(x) (void)(x) +# endif +#endif +#ifndef CYTHON_MAYBE_UNUSED_VAR + #define CYTHON_MAYBE_UNUSED_VAR(x) CYTHON_UNUSED_VAR(x) +#endif +#ifndef CYTHON_NCP_UNUSED +# if CYTHON_COMPILING_IN_CPYTHON && !CYTHON_COMPILING_IN_CPYTHON_FREETHREADING +# define CYTHON_NCP_UNUSED +# else +# define CYTHON_NCP_UNUSED CYTHON_UNUSED +# endif +#endif +#ifndef CYTHON_USE_CPP_STD_MOVE + #if defined(__cplusplus) && (\ + __cplusplus >= 201103L || (defined(_MSC_VER) && _MSC_VER >= 1600)) + #define CYTHON_USE_CPP_STD_MOVE 1 + #else + #define CYTHON_USE_CPP_STD_MOVE 0 + #endif +#endif +#define __Pyx_void_to_None(void_result) ((void)(void_result), Py_INCREF(Py_None), Py_None) +#include +typedef uintptr_t __pyx_uintptr_t; +#ifndef CYTHON_FALLTHROUGH + #if defined(__cplusplus) + /* for clang __has_cpp_attribute(fallthrough) is true even before C++17 + * but leads to warnings with -pedantic, since it is a C++17 feature */ + #if ((defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) || __cplusplus >= 201703L) + #if __has_cpp_attribute(fallthrough) + #define CYTHON_FALLTHROUGH [[fallthrough]] + #endif + #endif + #ifndef CYTHON_FALLTHROUGH + #if __has_cpp_attribute(clang::fallthrough) + #define CYTHON_FALLTHROUGH [[clang::fallthrough]] + #elif __has_cpp_attribute(gnu::fallthrough) + #define CYTHON_FALLTHROUGH [[gnu::fallthrough]] + #endif + #endif + #endif + #ifndef CYTHON_FALLTHROUGH + #if __has_attribute(fallthrough) + #define CYTHON_FALLTHROUGH __attribute__((fallthrough)) + #else + #define CYTHON_FALLTHROUGH + #endif + #endif + #if defined(__clang__) && defined(__apple_build_version__) + #if __apple_build_version__ < 7000000 + #undef CYTHON_FALLTHROUGH + #define CYTHON_FALLTHROUGH + #endif + #endif +#endif +#ifndef Py_UNREACHABLE + #define Py_UNREACHABLE() assert(0); abort() +#endif +#ifdef __cplusplus + template + struct __PYX_IS_UNSIGNED_IMPL {static const bool value = T(0) < T(-1);}; + #define __PYX_IS_UNSIGNED(type) (__PYX_IS_UNSIGNED_IMPL::value) +#else + #define __PYX_IS_UNSIGNED(type) (((type)-1) > 0) +#endif +#if CYTHON_COMPILING_IN_PYPY == 1 + #define __PYX_NEED_TP_PRINT_SLOT (PY_VERSION_HEX < 0x030A0000) +#else + #define __PYX_NEED_TP_PRINT_SLOT (PY_VERSION_HEX < 0x03090000) +#endif +#define __PYX_REINTERPRET_FUNCION(func_pointer, other_pointer) ((func_pointer)(void(*)(void))(other_pointer)) + +/* CInitCode */ +#ifndef CYTHON_INLINE + #if defined(__clang__) + #define CYTHON_INLINE __inline__ __attribute__ ((__unused__)) + #elif defined(__GNUC__) + #define CYTHON_INLINE __inline__ + #elif defined(_MSC_VER) + #define CYTHON_INLINE __inline + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_INLINE inline + #else + #define CYTHON_INLINE + #endif +#endif + +/* PythonCompatibility */ +#define __PYX_BUILD_PY_SSIZE_T "n" +#define CYTHON_FORMAT_SSIZE_T "z" +#define __Pyx_BUILTIN_MODULE_NAME "builtins" +#define __Pyx_DefaultClassType PyType_Type +#if CYTHON_COMPILING_IN_LIMITED_API + #ifndef CO_OPTIMIZED + static int CO_OPTIMIZED; + #endif + #ifndef CO_NEWLOCALS + static int CO_NEWLOCALS; + #endif + #ifndef CO_VARARGS + static int CO_VARARGS; + #endif + #ifndef CO_VARKEYWORDS + static int CO_VARKEYWORDS; + #endif + #ifndef CO_ASYNC_GENERATOR + static int CO_ASYNC_GENERATOR; + #endif + #ifndef CO_GENERATOR + static int CO_GENERATOR; + #endif + #ifndef CO_COROUTINE + static int CO_COROUTINE; + #endif +#else + #ifndef CO_COROUTINE + #define CO_COROUTINE 0x80 + #endif + #ifndef CO_ASYNC_GENERATOR + #define CO_ASYNC_GENERATOR 0x200 + #endif +#endif +static int __Pyx_init_co_variables(void); +#if PY_VERSION_HEX >= 0x030900A4 || defined(Py_IS_TYPE) + #define __Pyx_IS_TYPE(ob, type) Py_IS_TYPE(ob, type) +#else + #define __Pyx_IS_TYPE(ob, type) (((const PyObject*)ob)->ob_type == (type)) +#endif +#if PY_VERSION_HEX >= 0x030A00B1 || defined(Py_Is) + #define __Pyx_Py_Is(x, y) Py_Is(x, y) +#else + #define __Pyx_Py_Is(x, y) ((x) == (y)) +#endif +#if PY_VERSION_HEX >= 0x030A00B1 || defined(Py_IsNone) + #define __Pyx_Py_IsNone(ob) Py_IsNone(ob) +#else + #define __Pyx_Py_IsNone(ob) __Pyx_Py_Is((ob), Py_None) +#endif +#if PY_VERSION_HEX >= 0x030A00B1 || defined(Py_IsTrue) + #define __Pyx_Py_IsTrue(ob) Py_IsTrue(ob) +#else + #define __Pyx_Py_IsTrue(ob) __Pyx_Py_Is((ob), Py_True) +#endif +#if PY_VERSION_HEX >= 0x030A00B1 || defined(Py_IsFalse) + #define __Pyx_Py_IsFalse(ob) Py_IsFalse(ob) +#else + #define __Pyx_Py_IsFalse(ob) __Pyx_Py_Is((ob), Py_False) +#endif +#define __Pyx_NoneAsNull(obj) (__Pyx_Py_IsNone(obj) ? NULL : (obj)) +#if PY_VERSION_HEX >= 0x030900F0 && !CYTHON_COMPILING_IN_PYPY + #define __Pyx_PyObject_GC_IsFinalized(o) PyObject_GC_IsFinalized(o) +#else + #define __Pyx_PyObject_GC_IsFinalized(o) _PyGC_FINALIZED(o) +#endif +#ifndef Py_TPFLAGS_CHECKTYPES + #define Py_TPFLAGS_CHECKTYPES 0 +#endif +#ifndef Py_TPFLAGS_HAVE_INDEX + #define Py_TPFLAGS_HAVE_INDEX 0 +#endif +#ifndef Py_TPFLAGS_HAVE_NEWBUFFER + #define Py_TPFLAGS_HAVE_NEWBUFFER 0 +#endif +#ifndef Py_TPFLAGS_HAVE_FINALIZE + #define Py_TPFLAGS_HAVE_FINALIZE 0 +#endif +#ifndef Py_TPFLAGS_SEQUENCE + #define Py_TPFLAGS_SEQUENCE 0 +#endif +#ifndef Py_TPFLAGS_MAPPING + #define Py_TPFLAGS_MAPPING 0 +#endif +#ifndef Py_TPFLAGS_IMMUTABLETYPE + #define Py_TPFLAGS_IMMUTABLETYPE (1UL << 8) +#endif +#ifndef Py_TPFLAGS_DISALLOW_INSTANTIATION + #define Py_TPFLAGS_DISALLOW_INSTANTIATION (1UL << 7) +#endif +#ifndef METH_STACKLESS + #define METH_STACKLESS 0 +#endif +#ifndef METH_FASTCALL + #ifndef METH_FASTCALL + #define METH_FASTCALL 0x80 + #endif + typedef PyObject *(*__Pyx_PyCFunctionFast) (PyObject *self, PyObject *const *args, Py_ssize_t nargs); + typedef PyObject *(*__Pyx_PyCFunctionFastWithKeywords) (PyObject *self, PyObject *const *args, + Py_ssize_t nargs, PyObject *kwnames); +#else + #if PY_VERSION_HEX >= 0x030d00A4 + # define __Pyx_PyCFunctionFast PyCFunctionFast + # define __Pyx_PyCFunctionFastWithKeywords PyCFunctionFastWithKeywords + #else + # define __Pyx_PyCFunctionFast _PyCFunctionFast + # define __Pyx_PyCFunctionFastWithKeywords _PyCFunctionFastWithKeywords + #endif +#endif +#if CYTHON_METH_FASTCALL + #define __Pyx_METH_FASTCALL METH_FASTCALL + #define __Pyx_PyCFunction_FastCall __Pyx_PyCFunctionFast + #define __Pyx_PyCFunction_FastCallWithKeywords __Pyx_PyCFunctionFastWithKeywords +#else + #define __Pyx_METH_FASTCALL METH_VARARGS + #define __Pyx_PyCFunction_FastCall PyCFunction + #define __Pyx_PyCFunction_FastCallWithKeywords PyCFunctionWithKeywords +#endif +#if CYTHON_VECTORCALL + #define __pyx_vectorcallfunc vectorcallfunc + #define __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET PY_VECTORCALL_ARGUMENTS_OFFSET + #define __Pyx_PyVectorcall_NARGS(n) PyVectorcall_NARGS((size_t)(n)) +#else + #define __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET 0 + #define __Pyx_PyVectorcall_NARGS(n) ((Py_ssize_t)(n)) +#endif +#if PY_VERSION_HEX >= 0x030900B1 +#define __Pyx_PyCFunction_CheckExact(func) PyCFunction_CheckExact(func) +#else +#define __Pyx_PyCFunction_CheckExact(func) PyCFunction_Check(func) +#endif +#define __Pyx_CyOrPyCFunction_Check(func) PyCFunction_Check(func) +#if CYTHON_COMPILING_IN_CPYTHON +#define __Pyx_CyOrPyCFunction_GET_FUNCTION(func) (((PyCFunctionObject*)(func))->m_ml->ml_meth) +#elif !CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_CyOrPyCFunction_GET_FUNCTION(func) PyCFunction_GET_FUNCTION(func) +#endif +#if CYTHON_COMPILING_IN_CPYTHON +#define __Pyx_CyOrPyCFunction_GET_FLAGS(func) (((PyCFunctionObject*)(func))->m_ml->ml_flags) +static CYTHON_INLINE PyObject* __Pyx_CyOrPyCFunction_GET_SELF(PyObject *func) { + return (__Pyx_CyOrPyCFunction_GET_FLAGS(func) & METH_STATIC) ? NULL : ((PyCFunctionObject*)func)->m_self; +} +#endif +static CYTHON_INLINE int __Pyx__IsSameCFunction(PyObject *func, void (*cfunc)(void)) { +#if CYTHON_COMPILING_IN_LIMITED_API + return PyCFunction_Check(func) && PyCFunction_GetFunction(func) == (PyCFunction) cfunc; +#else + return PyCFunction_Check(func) && PyCFunction_GET_FUNCTION(func) == (PyCFunction) cfunc; +#endif +} +#define __Pyx_IsSameCFunction(func, cfunc) __Pyx__IsSameCFunction(func, cfunc) +#if PY_VERSION_HEX < 0x03090000 || (CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000) + #define __Pyx_PyType_FromModuleAndSpec(m, s, b) ((void)m, PyType_FromSpecWithBases(s, b)) + typedef PyObject *(*__Pyx_PyCMethod)(PyObject *, PyTypeObject *, PyObject *const *, size_t, PyObject *); +#else + #define __Pyx_PyType_FromModuleAndSpec(m, s, b) PyType_FromModuleAndSpec(m, s, b) + #define __Pyx_PyCMethod PyCMethod +#endif +#ifndef METH_METHOD + #define METH_METHOD 0x200 +#endif +#if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Malloc) + #define PyObject_Malloc(s) PyMem_Malloc(s) + #define PyObject_Free(p) PyMem_Free(p) + #define PyObject_Realloc(p) PyMem_Realloc(p) +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + #define __Pyx_PyFrame_SetLineNumber(frame, lineno) +#elif CYTHON_COMPILING_IN_GRAAL && defined(GRAALPY_VERSION_NUM) && GRAALPY_VERSION_NUM > 0x19000000 + #define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0) + #define __Pyx_PyFrame_SetLineNumber(frame, lineno) GraalPyFrame_SetLineNumber((frame), (lineno)) +#elif CYTHON_COMPILING_IN_GRAAL + #define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0) + #define __Pyx_PyFrame_SetLineNumber(frame, lineno) _PyFrame_SetLineNumber((frame), (lineno)) +#else + #define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0) + #define __Pyx_PyFrame_SetLineNumber(frame, lineno) (frame)->f_lineno = (lineno) +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + #define __Pyx_PyThreadState_Current PyThreadState_Get() +#elif !CYTHON_FAST_THREAD_STATE + #define __Pyx_PyThreadState_Current PyThreadState_GET() +#elif PY_VERSION_HEX >= 0x030d00A1 + #define __Pyx_PyThreadState_Current PyThreadState_GetUnchecked() +#else + #define __Pyx_PyThreadState_Current _PyThreadState_UncheckedGet() +#endif +#if CYTHON_USE_MODULE_STATE +static CYTHON_INLINE void *__Pyx__PyModule_GetState(PyObject *op) +{ + void *result; + result = PyModule_GetState(op); + if (!result) + Py_FatalError("Couldn't find the module state"); + return result; +} +#define __Pyx_PyModule_GetState(o) (__pyx_mstatetype *)__Pyx__PyModule_GetState(o) +#else +#define __Pyx_PyModule_GetState(op) ((void)op,__pyx_mstate_global) +#endif +#define __Pyx_PyObject_GetSlot(obj, name, func_ctype) __Pyx_PyType_GetSlot(Py_TYPE((PyObject *) obj), name, func_ctype) +#define __Pyx_PyObject_TryGetSlot(obj, name, func_ctype) __Pyx_PyType_TryGetSlot(Py_TYPE(obj), name, func_ctype) +#define __Pyx_PyObject_GetSubSlot(obj, sub, name, func_ctype) __Pyx_PyType_GetSubSlot(Py_TYPE(obj), sub, name, func_ctype) +#define __Pyx_PyObject_TryGetSubSlot(obj, sub, name, func_ctype) __Pyx_PyType_TryGetSubSlot(Py_TYPE(obj), sub, name, func_ctype) +#if CYTHON_USE_TYPE_SLOTS + #define __Pyx_PyType_GetSlot(type, name, func_ctype) ((type)->name) + #define __Pyx_PyType_TryGetSlot(type, name, func_ctype) __Pyx_PyType_GetSlot(type, name, func_ctype) + #define __Pyx_PyType_GetSubSlot(type, sub, name, func_ctype) (((type)->sub) ? ((type)->sub->name) : NULL) + #define __Pyx_PyType_TryGetSubSlot(type, sub, name, func_ctype) __Pyx_PyType_GetSubSlot(type, sub, name, func_ctype) +#else + #define __Pyx_PyType_GetSlot(type, name, func_ctype) ((func_ctype) PyType_GetSlot((type), Py_##name)) + #define __Pyx_PyType_TryGetSlot(type, name, func_ctype)\ + ((__PYX_LIMITED_VERSION_HEX >= 0x030A0000 ||\ + (PyType_GetFlags(type) & Py_TPFLAGS_HEAPTYPE) || __Pyx_get_runtime_version() >= 0x030A0000) ?\ + __Pyx_PyType_GetSlot(type, name, func_ctype) : NULL) + #define __Pyx_PyType_GetSubSlot(obj, sub, name, func_ctype) __Pyx_PyType_GetSlot(obj, name, func_ctype) + #define __Pyx_PyType_TryGetSubSlot(obj, sub, name, func_ctype) __Pyx_PyType_TryGetSlot(obj, name, func_ctype) +#endif +#if CYTHON_COMPILING_IN_CPYTHON || defined(_PyDict_NewPresized) +#define __Pyx_PyDict_NewPresized(n) ((n <= 8) ? PyDict_New() : _PyDict_NewPresized(n)) +#else +#define __Pyx_PyDict_NewPresized(n) PyDict_New() +#endif +#define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) +#define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) +#if CYTHON_COMPILING_IN_CPYTHON && CYTHON_USE_UNICODE_INTERNALS +#define __Pyx_PyDict_GetItemStrWithError(dict, name) _PyDict_GetItem_KnownHash(dict, name, ((PyASCIIObject *) name)->hash) +static CYTHON_INLINE PyObject * __Pyx_PyDict_GetItemStr(PyObject *dict, PyObject *name) { + PyObject *res = __Pyx_PyDict_GetItemStrWithError(dict, name); + if (res == NULL) PyErr_Clear(); + return res; +} +#elif !CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07020000 +#define __Pyx_PyDict_GetItemStrWithError PyDict_GetItemWithError +#define __Pyx_PyDict_GetItemStr PyDict_GetItem +#else +static CYTHON_INLINE PyObject * __Pyx_PyDict_GetItemStrWithError(PyObject *dict, PyObject *name) { +#if CYTHON_COMPILING_IN_PYPY + return PyDict_GetItem(dict, name); +#else + PyDictEntry *ep; + PyDictObject *mp = (PyDictObject*) dict; + long hash = ((PyStringObject *) name)->ob_shash; + assert(hash != -1); + ep = (mp->ma_lookup)(mp, name, hash); + if (ep == NULL) { + return NULL; + } + return ep->me_value; +#endif +} +#define __Pyx_PyDict_GetItemStr PyDict_GetItem +#endif +#if CYTHON_USE_TYPE_SLOTS + #define __Pyx_PyType_GetFlags(tp) (((PyTypeObject *)tp)->tp_flags) + #define __Pyx_PyType_HasFeature(type, feature) ((__Pyx_PyType_GetFlags(type) & (feature)) != 0) +#else + #define __Pyx_PyType_GetFlags(tp) (PyType_GetFlags((PyTypeObject *)tp)) + #define __Pyx_PyType_HasFeature(type, feature) PyType_HasFeature(type, feature) +#endif +#define __Pyx_PyObject_GetIterNextFunc(iterator) __Pyx_PyObject_GetSlot(iterator, tp_iternext, iternextfunc) +#if CYTHON_USE_TYPE_SPECS +#define __Pyx_PyHeapTypeObject_GC_Del(obj) {\ + PyTypeObject *type = Py_TYPE((PyObject*)obj);\ + assert(__Pyx_PyType_HasFeature(type, Py_TPFLAGS_HEAPTYPE));\ + PyObject_GC_Del(obj);\ + Py_DECREF(type);\ +} +#else +#define __Pyx_PyHeapTypeObject_GC_Del(obj) PyObject_GC_Del(obj) +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + #define __Pyx_PyUnicode_READY(op) (0) + #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_ReadChar(u, i) + #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) ((void)u, 1114111U) + #define __Pyx_PyUnicode_KIND(u) ((void)u, (0)) + #define __Pyx_PyUnicode_DATA(u) ((void*)u) + #define __Pyx_PyUnicode_READ(k, d, i) ((void)k, PyUnicode_ReadChar((PyObject*)(d), i)) + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GetLength(u)) +#else + #if PY_VERSION_HEX >= 0x030C0000 + #define __Pyx_PyUnicode_READY(op) (0) + #else + #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ?\ + 0 : _PyUnicode_Ready((PyObject *)(op))) + #endif + #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) + #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) PyUnicode_MAX_CHAR_VALUE(u) + #define __Pyx_PyUnicode_KIND(u) ((int)PyUnicode_KIND(u)) + #define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u) + #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) + #define __Pyx_PyUnicode_WRITE(k, d, i, ch) PyUnicode_WRITE(k, d, i, (Py_UCS4) ch) + #if PY_VERSION_HEX >= 0x030C0000 + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_LENGTH(u)) + #else + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x03090000 + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : ((PyCompactUnicodeObject *)(u))->wstr_length)) + #else + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : PyUnicode_GET_SIZE(u))) + #endif + #endif +#endif +#if CYTHON_COMPILING_IN_PYPY + #define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b) +#else + #define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ?\ + PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b)) +#endif +#if CYTHON_COMPILING_IN_PYPY + #if !defined(PyUnicode_DecodeUnicodeEscape) + #define PyUnicode_DecodeUnicodeEscape(s, size, errors) PyUnicode_Decode(s, size, "unicode_escape", errors) + #endif + #if !defined(PyUnicode_Contains) + #define PyUnicode_Contains(u, s) PySequence_Contains(u, s) + #endif + #if !defined(PyByteArray_Check) + #define PyByteArray_Check(obj) PyObject_TypeCheck(obj, &PyByteArray_Type) + #endif + #if !defined(PyObject_Format) + #define PyObject_Format(obj, fmt) PyObject_CallMethod(obj, "__format__", "O", fmt) + #endif +#endif +#define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None || (PyUnicode_Check(b) && !PyUnicode_CheckExact(b)))) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + #define __Pyx_PySequence_ListKeepNew(obj)\ + (likely(PyList_CheckExact(obj) && PyUnstable_Object_IsUniquelyReferenced(obj)) ? __Pyx_NewRef(obj) : PySequence_List(obj)) +#elif CYTHON_COMPILING_IN_CPYTHON + #define __Pyx_PySequence_ListKeepNew(obj)\ + (likely(PyList_CheckExact(obj) && Py_REFCNT(obj) == 1) ? __Pyx_NewRef(obj) : PySequence_List(obj)) +#else + #define __Pyx_PySequence_ListKeepNew(obj) PySequence_List(obj) +#endif +#ifndef PySet_CheckExact + #define PySet_CheckExact(obj) __Pyx_IS_TYPE(obj, &PySet_Type) +#endif +#if PY_VERSION_HEX >= 0x030900A4 + #define __Pyx_SET_REFCNT(obj, refcnt) Py_SET_REFCNT(obj, refcnt) + #define __Pyx_SET_SIZE(obj, size) Py_SET_SIZE(obj, size) +#else + #define __Pyx_SET_REFCNT(obj, refcnt) Py_REFCNT(obj) = (refcnt) + #define __Pyx_SET_SIZE(obj, size) Py_SIZE(obj) = (size) +#endif +enum __Pyx_ReferenceSharing { + __Pyx_ReferenceSharing_DefinitelyUnique, // We created it so we know it's unshared - no need to check + __Pyx_ReferenceSharing_OwnStrongReference, + __Pyx_ReferenceSharing_FunctionArgument, + __Pyx_ReferenceSharing_SharedReference, // Never trust it to be unshared because it's a global or similar +}; +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING && PY_VERSION_HEX >= 0x030E0000 +#define __Pyx_IS_UNIQUELY_REFERENCED(o, sharing)\ + (sharing == __Pyx_ReferenceSharing_DefinitelyUnique ? 1 :\ + (sharing == __Pyx_ReferenceSharing_FunctionArgument ? PyUnstable_Object_IsUniqueReferencedTemporary(o) :\ + (sharing == __Pyx_ReferenceSharing_OwnStrongReference ? PyUnstable_Object_IsUniquelyReferenced(o) : 0))) +#elif (CYTHON_COMPILING_IN_CPYTHON && !CYTHON_COMPILING_IN_CPYTHON_FREETHREADING) || CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_IS_UNIQUELY_REFERENCED(o, sharing) (((void)sharing), Py_REFCNT(o) == 1) +#else +#define __Pyx_IS_UNIQUELY_REFERENCED(o, sharing) (((void)o), ((void)sharing), 0) +#endif +#if CYTHON_AVOID_BORROWED_REFS || CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + #if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + #define __Pyx_PyList_GetItemRef(o, i) PyList_GetItemRef(o, i) + #elif CYTHON_COMPILING_IN_LIMITED_API || !CYTHON_ASSUME_SAFE_MACROS + #define __Pyx_PyList_GetItemRef(o, i) (likely((i) >= 0) ? PySequence_GetItem(o, i) : (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL)) + #else + #define __Pyx_PyList_GetItemRef(o, i) PySequence_ITEM(o, i) + #endif +#elif CYTHON_COMPILING_IN_LIMITED_API || !CYTHON_ASSUME_SAFE_MACROS + #if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + #define __Pyx_PyList_GetItemRef(o, i) PyList_GetItemRef(o, i) + #else + #define __Pyx_PyList_GetItemRef(o, i) __Pyx_XNewRef(PyList_GetItem(o, i)) + #endif +#else + #define __Pyx_PyList_GetItemRef(o, i) __Pyx_NewRef(PyList_GET_ITEM(o, i)) +#endif +#if CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS && !CYTHON_COMPILING_IN_LIMITED_API && CYTHON_ASSUME_SAFE_MACROS + #define __Pyx_PyList_GetItemRefFast(o, i, unsafe_shared) (__Pyx_IS_UNIQUELY_REFERENCED(o, unsafe_shared) ?\ + __Pyx_NewRef(PyList_GET_ITEM(o, i)) : __Pyx_PyList_GetItemRef(o, i)) +#else + #define __Pyx_PyList_GetItemRefFast(o, i, unsafe_shared) __Pyx_PyList_GetItemRef(o, i) +#endif +#if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 +#define __Pyx_PyDict_GetItemRef(dict, key, result) PyDict_GetItemRef(dict, key, result) +#elif CYTHON_AVOID_BORROWED_REFS || CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS +static CYTHON_INLINE int __Pyx_PyDict_GetItemRef(PyObject *dict, PyObject *key, PyObject **result) { + *result = PyObject_GetItem(dict, key); + if (*result == NULL) { + if (PyErr_ExceptionMatches(PyExc_KeyError)) { + PyErr_Clear(); + return 0; + } + return -1; + } + return 1; +} +#else +static CYTHON_INLINE int __Pyx_PyDict_GetItemRef(PyObject *dict, PyObject *key, PyObject **result) { + *result = PyDict_GetItemWithError(dict, key); + if (*result == NULL) { + return PyErr_Occurred() ? -1 : 0; + } + Py_INCREF(*result); + return 1; +} +#endif +#if defined(CYTHON_DEBUG_VISIT_CONST) && CYTHON_DEBUG_VISIT_CONST + #define __Pyx_VISIT_CONST(obj) Py_VISIT(obj) +#else + #define __Pyx_VISIT_CONST(obj) +#endif +#if CYTHON_ASSUME_SAFE_MACROS + #define __Pyx_PySequence_ITEM(o, i) PySequence_ITEM(o, i) + #define __Pyx_PySequence_SIZE(seq) Py_SIZE(seq) + #define __Pyx_PyTuple_SET_ITEM(o, i, v) (PyTuple_SET_ITEM(o, i, v), (0)) + #define __Pyx_PyTuple_GET_ITEM(o, i) PyTuple_GET_ITEM(o, i) + #define __Pyx_PyList_SET_ITEM(o, i, v) (PyList_SET_ITEM(o, i, v), (0)) + #define __Pyx_PyList_GET_ITEM(o, i) PyList_GET_ITEM(o, i) +#else + #define __Pyx_PySequence_ITEM(o, i) PySequence_GetItem(o, i) + #define __Pyx_PySequence_SIZE(seq) PySequence_Size(seq) + #define __Pyx_PyTuple_SET_ITEM(o, i, v) PyTuple_SetItem(o, i, v) + #define __Pyx_PyTuple_GET_ITEM(o, i) PyTuple_GetItem(o, i) + #define __Pyx_PyList_SET_ITEM(o, i, v) PyList_SetItem(o, i, v) + #define __Pyx_PyList_GET_ITEM(o, i) PyList_GetItem(o, i) +#endif +#if CYTHON_ASSUME_SAFE_SIZE + #define __Pyx_PyTuple_GET_SIZE(o) PyTuple_GET_SIZE(o) + #define __Pyx_PyList_GET_SIZE(o) PyList_GET_SIZE(o) + #define __Pyx_PySet_GET_SIZE(o) PySet_GET_SIZE(o) + #define __Pyx_PyBytes_GET_SIZE(o) PyBytes_GET_SIZE(o) + #define __Pyx_PyByteArray_GET_SIZE(o) PyByteArray_GET_SIZE(o) + #define __Pyx_PyUnicode_GET_LENGTH(o) PyUnicode_GET_LENGTH(o) +#else + #define __Pyx_PyTuple_GET_SIZE(o) PyTuple_Size(o) + #define __Pyx_PyList_GET_SIZE(o) PyList_Size(o) + #define __Pyx_PySet_GET_SIZE(o) PySet_Size(o) + #define __Pyx_PyBytes_GET_SIZE(o) PyBytes_Size(o) + #define __Pyx_PyByteArray_GET_SIZE(o) PyByteArray_Size(o) + #define __Pyx_PyUnicode_GET_LENGTH(o) PyUnicode_GetLength(o) +#endif +#if CYTHON_COMPILING_IN_PYPY && !defined(PyUnicode_InternFromString) + #define PyUnicode_InternFromString(s) PyUnicode_FromString(s) +#endif +#define __Pyx_PyLong_FromHash_t PyLong_FromSsize_t +#define __Pyx_PyLong_AsHash_t __Pyx_PyIndex_AsSsize_t +#if __PYX_LIMITED_VERSION_HEX >= 0x030A0000 + #define __Pyx_PySendResult PySendResult +#else + typedef enum { + PYGEN_RETURN = 0, + PYGEN_ERROR = -1, + PYGEN_NEXT = 1, + } __Pyx_PySendResult; +#endif +#if CYTHON_COMPILING_IN_LIMITED_API || PY_VERSION_HEX < 0x030A00A3 + typedef __Pyx_PySendResult (*__Pyx_pyiter_sendfunc)(PyObject *iter, PyObject *value, PyObject **result); +#else + #define __Pyx_pyiter_sendfunc sendfunc +#endif +#if !CYTHON_USE_AM_SEND +#define __PYX_HAS_PY_AM_SEND 0 +#elif __PYX_LIMITED_VERSION_HEX >= 0x030A0000 +#define __PYX_HAS_PY_AM_SEND 1 +#else +#define __PYX_HAS_PY_AM_SEND 2 // our own backported implementation +#endif +#if __PYX_HAS_PY_AM_SEND < 2 + #define __Pyx_PyAsyncMethodsStruct PyAsyncMethods +#else + typedef struct { + unaryfunc am_await; + unaryfunc am_aiter; + unaryfunc am_anext; + __Pyx_pyiter_sendfunc am_send; + } __Pyx_PyAsyncMethodsStruct; + #define __Pyx_SlotTpAsAsync(s) ((PyAsyncMethods*)(s)) +#endif +#if CYTHON_USE_AM_SEND && PY_VERSION_HEX < 0x030A00F0 + #define __Pyx_TPFLAGS_HAVE_AM_SEND (1UL << 21) +#else + #define __Pyx_TPFLAGS_HAVE_AM_SEND (0) +#endif +#if PY_VERSION_HEX >= 0x03090000 +#define __Pyx_PyInterpreterState_Get() PyInterpreterState_Get() +#else +#define __Pyx_PyInterpreterState_Get() PyThreadState_Get()->interp +#endif +#if CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030A0000 +#ifdef __cplusplus +extern "C" +#endif +PyAPI_FUNC(void *) PyMem_Calloc(size_t nelem, size_t elsize); +#endif +#if CYTHON_COMPILING_IN_LIMITED_API +static int __Pyx_init_co_variable(PyObject *inspect, const char* name, int *write_to) { + int value; + PyObject *py_value = PyObject_GetAttrString(inspect, name); + if (!py_value) return 0; + value = (int) PyLong_AsLong(py_value); + Py_DECREF(py_value); + *write_to = value; + return value != -1 || !PyErr_Occurred(); +} +static int __Pyx_init_co_variables(void) { + PyObject *inspect; + int result; + inspect = PyImport_ImportModule("inspect"); + result = +#if !defined(CO_OPTIMIZED) + __Pyx_init_co_variable(inspect, "CO_OPTIMIZED", &CO_OPTIMIZED) && +#endif +#if !defined(CO_NEWLOCALS) + __Pyx_init_co_variable(inspect, "CO_NEWLOCALS", &CO_NEWLOCALS) && +#endif +#if !defined(CO_VARARGS) + __Pyx_init_co_variable(inspect, "CO_VARARGS", &CO_VARARGS) && +#endif +#if !defined(CO_VARKEYWORDS) + __Pyx_init_co_variable(inspect, "CO_VARKEYWORDS", &CO_VARKEYWORDS) && +#endif +#if !defined(CO_ASYNC_GENERATOR) + __Pyx_init_co_variable(inspect, "CO_ASYNC_GENERATOR", &CO_ASYNC_GENERATOR) && +#endif +#if !defined(CO_GENERATOR) + __Pyx_init_co_variable(inspect, "CO_GENERATOR", &CO_GENERATOR) && +#endif +#if !defined(CO_COROUTINE) + __Pyx_init_co_variable(inspect, "CO_COROUTINE", &CO_COROUTINE) && +#endif + 1; + Py_DECREF(inspect); + return result ? 0 : -1; +} +#else +static int __Pyx_init_co_variables(void) { + return 0; // It's a limited API-only feature +} +#endif + +/* MathInitCode */ +#if defined(_WIN32) || defined(WIN32) || defined(MS_WINDOWS) + #ifndef _USE_MATH_DEFINES + #define _USE_MATH_DEFINES + #endif +#endif +#include +#if defined(__CYGWIN__) && defined(_LDBL_EQ_DBL) +#define __Pyx_truncl trunc +#else +#define __Pyx_truncl truncl +#endif + +#ifndef CYTHON_CLINE_IN_TRACEBACK_RUNTIME +#define CYTHON_CLINE_IN_TRACEBACK_RUNTIME 0 +#endif +#ifndef CYTHON_CLINE_IN_TRACEBACK +#define CYTHON_CLINE_IN_TRACEBACK CYTHON_CLINE_IN_TRACEBACK_RUNTIME +#endif +#if CYTHON_CLINE_IN_TRACEBACK +#define __PYX_MARK_ERR_POS(f_index, lineno) { __pyx_filename = __pyx_f[f_index]; (void) __pyx_filename; __pyx_lineno = lineno; (void) __pyx_lineno; __pyx_clineno = __LINE__; (void) __pyx_clineno; } +#else +#define __PYX_MARK_ERR_POS(f_index, lineno) { __pyx_filename = __pyx_f[f_index]; (void) __pyx_filename; __pyx_lineno = lineno; (void) __pyx_lineno; (void) __pyx_clineno; } +#endif +#define __PYX_ERR(f_index, lineno, Ln_error) \ + { __PYX_MARK_ERR_POS(f_index, lineno) goto Ln_error; } + +#ifdef CYTHON_EXTERN_C + #undef __PYX_EXTERN_C + #define __PYX_EXTERN_C CYTHON_EXTERN_C +#elif defined(__PYX_EXTERN_C) + #ifdef _MSC_VER + #pragma message ("Please do not define the '__PYX_EXTERN_C' macro externally. Use 'CYTHON_EXTERN_C' instead.") + #else + #warning Please do not define the '__PYX_EXTERN_C' macro externally. Use 'CYTHON_EXTERN_C' instead. + #endif +#else + #ifdef __cplusplus + #define __PYX_EXTERN_C extern "C" + #else + #define __PYX_EXTERN_C extern + #endif +#endif + +#define __PYX_HAVE__thriftpy2__transport__framed__cyframed +#define __PYX_HAVE_API__thriftpy2__transport__framed__cyframed +/* Early includes */ +#include +#include +#include +#include "../../protocol/cybin/endian_port.h" +#ifdef _OPENMP +#include +#endif /* _OPENMP */ + +#if defined(PYREX_WITHOUT_ASSERTIONS) && !defined(CYTHON_WITHOUT_ASSERTIONS) +#define CYTHON_WITHOUT_ASSERTIONS +#endif + +#ifdef CYTHON_FREETHREADING_COMPATIBLE +#if CYTHON_FREETHREADING_COMPATIBLE +#define __Pyx_FREETHREADING_COMPATIBLE Py_MOD_GIL_NOT_USED +#else +#define __Pyx_FREETHREADING_COMPATIBLE Py_MOD_GIL_USED +#endif +#else +#define __Pyx_FREETHREADING_COMPATIBLE Py_MOD_GIL_NOT_USED +#endif +#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 +#define __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 0 +#define __PYX_DEFAULT_STRING_ENCODING "" +#define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString +#define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#define __Pyx_uchar_cast(c) ((unsigned char)c) +#define __Pyx_long_cast(x) ((long)x) +#define __Pyx_fits_Py_ssize_t(v, type, is_signed) (\ + (sizeof(type) < sizeof(Py_ssize_t)) ||\ + (sizeof(type) > sizeof(Py_ssize_t) &&\ + likely(v < (type)PY_SSIZE_T_MAX ||\ + v == (type)PY_SSIZE_T_MAX) &&\ + (!is_signed || likely(v > (type)PY_SSIZE_T_MIN ||\ + v == (type)PY_SSIZE_T_MIN))) ||\ + (sizeof(type) == sizeof(Py_ssize_t) &&\ + (is_signed || likely(v < (type)PY_SSIZE_T_MAX ||\ + v == (type)PY_SSIZE_T_MAX))) ) +static CYTHON_INLINE int __Pyx_is_valid_index(Py_ssize_t i, Py_ssize_t limit) { + return (size_t) i < (size_t) limit; +} +#if defined (__cplusplus) && __cplusplus >= 201103L + #include + #define __Pyx_sst_abs(value) std::abs(value) +#elif SIZEOF_INT >= SIZEOF_SIZE_T + #define __Pyx_sst_abs(value) abs(value) +#elif SIZEOF_LONG >= SIZEOF_SIZE_T + #define __Pyx_sst_abs(value) labs(value) +#elif defined (_MSC_VER) + #define __Pyx_sst_abs(value) ((Py_ssize_t)_abs64(value)) +#elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define __Pyx_sst_abs(value) llabs(value) +#elif defined (__GNUC__) + #define __Pyx_sst_abs(value) __builtin_llabs(value) +#else + #define __Pyx_sst_abs(value) ((value<0) ? -value : value) +#endif +static CYTHON_INLINE Py_ssize_t __Pyx_ssize_strlen(const char *s); +static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject*); +static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); +static CYTHON_INLINE PyObject* __Pyx_PyByteArray_FromString(const char*); +#define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l) +#define __Pyx_PyBytes_FromString PyBytes_FromString +#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char*); +#if CYTHON_ASSUME_SAFE_MACROS + #define __Pyx_PyBytes_AsWritableString(s) ((char*) PyBytes_AS_STRING(s)) + #define __Pyx_PyBytes_AsWritableSString(s) ((signed char*) PyBytes_AS_STRING(s)) + #define __Pyx_PyBytes_AsWritableUString(s) ((unsigned char*) PyBytes_AS_STRING(s)) + #define __Pyx_PyBytes_AsString(s) ((const char*) PyBytes_AS_STRING(s)) + #define __Pyx_PyBytes_AsSString(s) ((const signed char*) PyBytes_AS_STRING(s)) + #define __Pyx_PyBytes_AsUString(s) ((const unsigned char*) PyBytes_AS_STRING(s)) + #define __Pyx_PyByteArray_AsString(s) PyByteArray_AS_STRING(s) +#else + #define __Pyx_PyBytes_AsWritableString(s) ((char*) PyBytes_AsString(s)) + #define __Pyx_PyBytes_AsWritableSString(s) ((signed char*) PyBytes_AsString(s)) + #define __Pyx_PyBytes_AsWritableUString(s) ((unsigned char*) PyBytes_AsString(s)) + #define __Pyx_PyBytes_AsString(s) ((const char*) PyBytes_AsString(s)) + #define __Pyx_PyBytes_AsSString(s) ((const signed char*) PyBytes_AsString(s)) + #define __Pyx_PyBytes_AsUString(s) ((const unsigned char*) PyBytes_AsString(s)) + #define __Pyx_PyByteArray_AsString(s) PyByteArray_AsString(s) +#endif +#define __Pyx_PyObject_AsWritableString(s) ((char*)(__pyx_uintptr_t) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsWritableSString(s) ((signed char*)(__pyx_uintptr_t) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsWritableUString(s) ((unsigned char*)(__pyx_uintptr_t) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsSString(s) ((const signed char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsUString(s) ((const unsigned char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_FromCString(s) __Pyx_PyObject_FromString((const char*)s) +#define __Pyx_PyBytes_FromCString(s) __Pyx_PyBytes_FromString((const char*)s) +#define __Pyx_PyByteArray_FromCString(s) __Pyx_PyByteArray_FromString((const char*)s) +#define __Pyx_PyUnicode_FromCString(s) __Pyx_PyUnicode_FromString((const char*)s) +#define __Pyx_PyUnicode_FromOrdinal(o) PyUnicode_FromOrdinal((int)o) +#define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode +static CYTHON_INLINE PyObject *__Pyx_NewRef(PyObject *obj) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030a0000 || defined(Py_NewRef) + return Py_NewRef(obj); +#else + Py_INCREF(obj); + return obj; +#endif +} +static CYTHON_INLINE PyObject *__Pyx_XNewRef(PyObject *obj) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030a0000 || defined(Py_XNewRef) + return Py_XNewRef(obj); +#else + Py_XINCREF(obj); + return obj; +#endif +} +static CYTHON_INLINE PyObject *__Pyx_Owned_Py_None(int b); +static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b); +static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); +static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject*); +static CYTHON_INLINE PyObject* __Pyx_PyNumber_Long(PyObject* x); +#define __Pyx_PySequence_Tuple(obj)\ + (likely(PyTuple_CheckExact(obj)) ? __Pyx_NewRef(obj) : PySequence_Tuple(obj)) +static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); +static CYTHON_INLINE PyObject * __Pyx_PyLong_FromSize_t(size_t); +static CYTHON_INLINE Py_hash_t __Pyx_PyIndex_AsHash_t(PyObject*); +#if CYTHON_ASSUME_SAFE_MACROS +#define __Pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) +#define __Pyx_PyFloat_AS_DOUBLE(x) PyFloat_AS_DOUBLE(x) +#else +#define __Pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) +#define __Pyx_PyFloat_AS_DOUBLE(x) PyFloat_AsDouble(x) +#endif +#define __Pyx_PyFloat_AsFloat(x) ((float) __Pyx_PyFloat_AsDouble(x)) +#define __Pyx_PyNumber_Int(x) (PyLong_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Long(x)) +#if CYTHON_USE_PYLONG_INTERNALS + #if PY_VERSION_HEX >= 0x030C00A7 + #ifndef _PyLong_SIGN_MASK + #define _PyLong_SIGN_MASK 3 + #endif + #ifndef _PyLong_NON_SIZE_BITS + #define _PyLong_NON_SIZE_BITS 3 + #endif + #define __Pyx_PyLong_Sign(x) (((PyLongObject*)x)->long_value.lv_tag & _PyLong_SIGN_MASK) + #define __Pyx_PyLong_IsNeg(x) ((__Pyx_PyLong_Sign(x) & 2) != 0) + #define __Pyx_PyLong_IsNonNeg(x) (!__Pyx_PyLong_IsNeg(x)) + #define __Pyx_PyLong_IsZero(x) (__Pyx_PyLong_Sign(x) & 1) + #define __Pyx_PyLong_IsPos(x) (__Pyx_PyLong_Sign(x) == 0) + #define __Pyx_PyLong_CompactValueUnsigned(x) (__Pyx_PyLong_Digits(x)[0]) + #define __Pyx_PyLong_DigitCount(x) ((Py_ssize_t) (((PyLongObject*)x)->long_value.lv_tag >> _PyLong_NON_SIZE_BITS)) + #define __Pyx_PyLong_SignedDigitCount(x)\ + ((1 - (Py_ssize_t) __Pyx_PyLong_Sign(x)) * __Pyx_PyLong_DigitCount(x)) + #if defined(PyUnstable_Long_IsCompact) && defined(PyUnstable_Long_CompactValue) + #define __Pyx_PyLong_IsCompact(x) PyUnstable_Long_IsCompact((PyLongObject*) x) + #define __Pyx_PyLong_CompactValue(x) PyUnstable_Long_CompactValue((PyLongObject*) x) + #else + #define __Pyx_PyLong_IsCompact(x) (((PyLongObject*)x)->long_value.lv_tag < (2 << _PyLong_NON_SIZE_BITS)) + #define __Pyx_PyLong_CompactValue(x) ((1 - (Py_ssize_t) __Pyx_PyLong_Sign(x)) * (Py_ssize_t) __Pyx_PyLong_Digits(x)[0]) + #endif + typedef Py_ssize_t __Pyx_compact_pylong; + typedef size_t __Pyx_compact_upylong; + #else + #define __Pyx_PyLong_IsNeg(x) (Py_SIZE(x) < 0) + #define __Pyx_PyLong_IsNonNeg(x) (Py_SIZE(x) >= 0) + #define __Pyx_PyLong_IsZero(x) (Py_SIZE(x) == 0) + #define __Pyx_PyLong_IsPos(x) (Py_SIZE(x) > 0) + #define __Pyx_PyLong_CompactValueUnsigned(x) ((Py_SIZE(x) == 0) ? 0 : __Pyx_PyLong_Digits(x)[0]) + #define __Pyx_PyLong_DigitCount(x) __Pyx_sst_abs(Py_SIZE(x)) + #define __Pyx_PyLong_SignedDigitCount(x) Py_SIZE(x) + #define __Pyx_PyLong_IsCompact(x) (Py_SIZE(x) == 0 || Py_SIZE(x) == 1 || Py_SIZE(x) == -1) + #define __Pyx_PyLong_CompactValue(x)\ + ((Py_SIZE(x) == 0) ? (sdigit) 0 : ((Py_SIZE(x) < 0) ? -(sdigit)__Pyx_PyLong_Digits(x)[0] : (sdigit)__Pyx_PyLong_Digits(x)[0])) + typedef sdigit __Pyx_compact_pylong; + typedef digit __Pyx_compact_upylong; + #endif + #if PY_VERSION_HEX >= 0x030C00A5 + #define __Pyx_PyLong_Digits(x) (((PyLongObject*)x)->long_value.ob_digit) + #else + #define __Pyx_PyLong_Digits(x) (((PyLongObject*)x)->ob_digit) + #endif +#endif +#if __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 + #define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) +#elif __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + #define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeASCII(c_str, size, NULL) +#else + #define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) +#endif + + +/* Test for GCC > 2.95 */ +#if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))) + #define likely(x) __builtin_expect(!!(x), 1) + #define unlikely(x) __builtin_expect(!!(x), 0) +#else /* !__GNUC__ or GCC < 2.95 */ + #define likely(x) (x) + #define unlikely(x) (x) +#endif /* __GNUC__ */ +/* PretendToInitialize */ +#ifdef __cplusplus +#if __cplusplus > 201103L +#include +#endif +template +static void __Pyx_pretend_to_initialize(T* ptr) { +#if __cplusplus > 201103L + if ((std::is_trivially_default_constructible::value)) +#endif + *ptr = T(); + (void)ptr; +} +#else +static CYTHON_INLINE void __Pyx_pretend_to_initialize(void* ptr) { (void)ptr; } +#endif + + +#if !CYTHON_USE_MODULE_STATE +static PyObject *__pyx_m = NULL; +#endif +static int __pyx_lineno; +static int __pyx_clineno = 0; +static const char * const __pyx_cfilenm = __FILE__; +static const char *__pyx_filename; + +/* #### Code section: filename_table ### */ + +static const char* const __pyx_f[] = { + "thriftpy2/transport/framed/cyframed.pyx", + "", + "thriftpy2/transport/cybase.pxd", +}; +/* #### Code section: utility_code_proto_before_types ### */ +/* Atomics.proto (used by UnpackUnboundCMethod) */ +#include +#ifndef CYTHON_ATOMICS + #define CYTHON_ATOMICS 1 +#endif +#define __PYX_CYTHON_ATOMICS_ENABLED() CYTHON_ATOMICS +#define __PYX_GET_CYTHON_COMPILING_IN_CPYTHON_FREETHREADING() CYTHON_COMPILING_IN_CPYTHON_FREETHREADING +#define __pyx_atomic_int_type int +#define __pyx_nonatomic_int_type int +#if CYTHON_ATOMICS && (defined(__STDC_VERSION__) &&\ + (__STDC_VERSION__ >= 201112L) &&\ + !defined(__STDC_NO_ATOMICS__)) + #include +#elif CYTHON_ATOMICS && (defined(__cplusplus) && (\ + (__cplusplus >= 201103L) ||\ + (defined(_MSC_VER) && _MSC_VER >= 1700))) + #include +#endif +#if CYTHON_ATOMICS && (defined(__STDC_VERSION__) &&\ + (__STDC_VERSION__ >= 201112L) &&\ + !defined(__STDC_NO_ATOMICS__) &&\ + ATOMIC_INT_LOCK_FREE == 2) + #undef __pyx_atomic_int_type + #define __pyx_atomic_int_type atomic_int + #define __pyx_atomic_ptr_type atomic_uintptr_t + #define __pyx_nonatomic_ptr_type uintptr_t + #define __pyx_atomic_incr_relaxed(value) atomic_fetch_add_explicit(value, 1, memory_order_relaxed) + #define __pyx_atomic_incr_acq_rel(value) atomic_fetch_add_explicit(value, 1, memory_order_acq_rel) + #define __pyx_atomic_decr_acq_rel(value) atomic_fetch_sub_explicit(value, 1, memory_order_acq_rel) + #define __pyx_atomic_sub(value, arg) atomic_fetch_sub(value, arg) + #define __pyx_atomic_int_cmp_exchange(value, expected, desired) atomic_compare_exchange_strong(value, expected, desired) + #define __pyx_atomic_load(value) atomic_load(value) + #define __pyx_atomic_store(value, new_value) atomic_store(value, new_value) + #define __pyx_atomic_pointer_load_relaxed(value) atomic_load_explicit(value, memory_order_relaxed) + #define __pyx_atomic_pointer_load_acquire(value) atomic_load_explicit(value, memory_order_acquire) + #define __pyx_atomic_pointer_exchange(value, new_value) atomic_exchange(value, (__pyx_nonatomic_ptr_type)new_value) + #define __pyx_atomic_pointer_cmp_exchange(value, expected, desired) atomic_compare_exchange_strong(value, expected, desired) + #if defined(__PYX_DEBUG_ATOMICS) && defined(_MSC_VER) + #pragma message ("Using standard C atomics") + #elif defined(__PYX_DEBUG_ATOMICS) + #warning "Using standard C atomics" + #endif +#elif CYTHON_ATOMICS && (defined(__cplusplus) && (\ + (__cplusplus >= 201103L) ||\ +\ + (defined(_MSC_VER) && _MSC_VER >= 1700)) &&\ + ATOMIC_INT_LOCK_FREE == 2) + #undef __pyx_atomic_int_type + #define __pyx_atomic_int_type std::atomic_int + #define __pyx_atomic_ptr_type std::atomic_uintptr_t + #define __pyx_nonatomic_ptr_type uintptr_t + #define __pyx_atomic_incr_relaxed(value) std::atomic_fetch_add_explicit(value, 1, std::memory_order_relaxed) + #define __pyx_atomic_incr_acq_rel(value) std::atomic_fetch_add_explicit(value, 1, std::memory_order_acq_rel) + #define __pyx_atomic_decr_acq_rel(value) std::atomic_fetch_sub_explicit(value, 1, std::memory_order_acq_rel) + #define __pyx_atomic_sub(value, arg) std::atomic_fetch_sub(value, arg) + #define __pyx_atomic_int_cmp_exchange(value, expected, desired) std::atomic_compare_exchange_strong(value, expected, desired) + #define __pyx_atomic_load(value) std::atomic_load(value) + #define __pyx_atomic_store(value, new_value) std::atomic_store(value, new_value) + #define __pyx_atomic_pointer_load_relaxed(value) std::atomic_load_explicit(value, std::memory_order_relaxed) + #define __pyx_atomic_pointer_load_acquire(value) std::atomic_load_explicit(value, std::memory_order_acquire) + #define __pyx_atomic_pointer_exchange(value, new_value) std::atomic_exchange(value, (__pyx_nonatomic_ptr_type)new_value) + #define __pyx_atomic_pointer_cmp_exchange(value, expected, desired) std::atomic_compare_exchange_strong(value, expected, desired) + #if defined(__PYX_DEBUG_ATOMICS) && defined(_MSC_VER) + #pragma message ("Using standard C++ atomics") + #elif defined(__PYX_DEBUG_ATOMICS) + #warning "Using standard C++ atomics" + #endif +#elif CYTHON_ATOMICS && (__GNUC__ >= 5 || (__GNUC__ == 4 &&\ + (__GNUC_MINOR__ > 1 ||\ + (__GNUC_MINOR__ == 1 && __GNUC_PATCHLEVEL__ >= 2)))) + #define __pyx_atomic_ptr_type void* + #define __pyx_nonatomic_ptr_type void* + #define __pyx_atomic_incr_relaxed(value) __sync_fetch_and_add(value, 1) + #define __pyx_atomic_incr_acq_rel(value) __sync_fetch_and_add(value, 1) + #define __pyx_atomic_decr_acq_rel(value) __sync_fetch_and_sub(value, 1) + #define __pyx_atomic_sub(value, arg) __sync_fetch_and_sub(value, arg) + static CYTHON_INLINE int __pyx_atomic_int_cmp_exchange(__pyx_atomic_int_type* value, __pyx_nonatomic_int_type* expected, __pyx_nonatomic_int_type desired) { + __pyx_nonatomic_int_type old = __sync_val_compare_and_swap(value, *expected, desired); + int result = old == *expected; + *expected = old; + return result; + } + #define __pyx_atomic_load(value) __sync_fetch_and_add(value, 0) + #define __pyx_atomic_store(value, new_value) __sync_lock_test_and_set(value, new_value) + #define __pyx_atomic_pointer_load_relaxed(value) __sync_fetch_and_add(value, 0) + #define __pyx_atomic_pointer_load_acquire(value) __sync_fetch_and_add(value, 0) + #define __pyx_atomic_pointer_exchange(value, new_value) __sync_lock_test_and_set(value, (__pyx_atomic_ptr_type)new_value) + static CYTHON_INLINE int __pyx_atomic_pointer_cmp_exchange(__pyx_atomic_ptr_type* value, __pyx_nonatomic_ptr_type* expected, __pyx_nonatomic_ptr_type desired) { + __pyx_nonatomic_ptr_type old = __sync_val_compare_and_swap(value, *expected, desired); + int result = old == *expected; + *expected = old; + return result; + } + #ifdef __PYX_DEBUG_ATOMICS + #warning "Using GNU atomics" + #endif +#elif CYTHON_ATOMICS && defined(_MSC_VER) + #include + #undef __pyx_atomic_int_type + #define __pyx_atomic_int_type long + #define __pyx_atomic_ptr_type void* + #undef __pyx_nonatomic_int_type + #define __pyx_nonatomic_int_type long + #define __pyx_nonatomic_ptr_type void* + #pragma intrinsic (_InterlockedExchangeAdd, _InterlockedExchange, _InterlockedCompareExchange, _InterlockedCompareExchangePointer, _InterlockedExchangePointer) + #define __pyx_atomic_incr_relaxed(value) _InterlockedExchangeAdd(value, 1) + #define __pyx_atomic_incr_acq_rel(value) _InterlockedExchangeAdd(value, 1) + #define __pyx_atomic_decr_acq_rel(value) _InterlockedExchangeAdd(value, -1) + #define __pyx_atomic_sub(value, arg) _InterlockedExchangeAdd(value, -arg) + static CYTHON_INLINE int __pyx_atomic_int_cmp_exchange(__pyx_atomic_int_type* value, __pyx_nonatomic_int_type* expected, __pyx_nonatomic_int_type desired) { + __pyx_nonatomic_int_type old = _InterlockedCompareExchange(value, desired, *expected); + int result = old == *expected; + *expected = old; + return result; + } + #define __pyx_atomic_load(value) _InterlockedExchangeAdd(value, 0) + #define __pyx_atomic_store(value, new_value) _InterlockedExchange(value, new_value) + #define __pyx_atomic_pointer_load_relaxed(value) *(void * volatile *)value + #define __pyx_atomic_pointer_load_acquire(value) _InterlockedCompareExchangePointer(value, 0, 0) + #define __pyx_atomic_pointer_exchange(value, new_value) _InterlockedExchangePointer(value, (__pyx_atomic_ptr_type)new_value) + static CYTHON_INLINE int __pyx_atomic_pointer_cmp_exchange(__pyx_atomic_ptr_type* value, __pyx_nonatomic_ptr_type* expected, __pyx_nonatomic_ptr_type desired) { + __pyx_atomic_ptr_type old = _InterlockedCompareExchangePointer(value, desired, *expected); + int result = old == *expected; + *expected = old; + return result; + } + #ifdef __PYX_DEBUG_ATOMICS + #pragma message ("Using MSVC atomics") + #endif +#else + #undef CYTHON_ATOMICS + #define CYTHON_ATOMICS 0 + #ifdef __PYX_DEBUG_ATOMICS + #warning "Not using atomics" + #endif +#endif + +/* CriticalSectionsDefinition.proto (used by CriticalSections) */ +#if !CYTHON_COMPILING_IN_CPYTHON_FREETHREADING +#define __Pyx_PyCriticalSection void* +#define __Pyx_PyCriticalSection2 void* +#define __Pyx_PyCriticalSection_End(cs) +#define __Pyx_PyCriticalSection2_End(cs) +#else +#define __Pyx_PyCriticalSection PyCriticalSection +#define __Pyx_PyCriticalSection2 PyCriticalSection2 +#define __Pyx_PyCriticalSection_End PyCriticalSection_End +#define __Pyx_PyCriticalSection2_End PyCriticalSection2_End +#endif + +/* CriticalSections.proto (used by ParseKeywordsImpl) */ +#if !CYTHON_COMPILING_IN_CPYTHON_FREETHREADING +#define __Pyx_PyCriticalSection_Begin(cs, arg) (void)(cs) +#define __Pyx_PyCriticalSection2_Begin(cs, arg1, arg2) (void)(cs) +#else +#define __Pyx_PyCriticalSection_Begin PyCriticalSection_Begin +#define __Pyx_PyCriticalSection2_Begin PyCriticalSection2_Begin +#endif +#if PY_VERSION_HEX < 0x030d0000 || CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_BEGIN_CRITICAL_SECTION(o) { +#define __Pyx_END_CRITICAL_SECTION() } +#else +#define __Pyx_BEGIN_CRITICAL_SECTION Py_BEGIN_CRITICAL_SECTION +#define __Pyx_END_CRITICAL_SECTION Py_END_CRITICAL_SECTION +#endif + +/* IncludeStructmemberH.proto (used by FixUpExtensionType) */ +#include + +/* #### Code section: numeric_typedefs ### */ +/* #### Code section: complex_type_declarations ### */ +/* #### Code section: type_declarations ### */ + +/*--- Type declarations ---*/ +struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer; +struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase; +struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport; + +/* "thriftpy2/transport/cybase.pxd":3 + * # cython: freethreading_compatible = True + * + * cdef enum: # <<<<<<<<<<<<<< + * DEFAULT_BUFFER = 4096 + * STACK_STRING_LEN = 4096 +*/ +enum { + __pyx_e_9thriftpy2_9transport_6cybase_DEFAULT_BUFFER = 0x1000, + __pyx_e_9thriftpy2_9transport_6cybase_STACK_STRING_LEN = 0x1000 +}; + +/* "thriftpy2/transport/cybase.pxd":7 + * STACK_STRING_LEN = 4096 + * + * cdef class TCyBuffer(object): # <<<<<<<<<<<<<< + * cdef: + * char *buf +*/ +struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer { + PyObject_HEAD + struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_TCyBuffer *__pyx_vtab; + char *buf; + int cur; + int buf_size; + int data_size; +}; + + +/* "thriftpy2/transport/cybase.pxd":19 + * + * + * cdef class CyTransportBase(object): # <<<<<<<<<<<<<< + * cdef object trans + * +*/ +struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase { + PyObject_HEAD + struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_CyTransportBase *__pyx_vtab; + PyObject *trans; +}; + + +/* "thriftpy2/transport/framed/cyframed.pyx":22 + * + * + * cdef class TCyFramedTransport(CyTransportBase): # <<<<<<<<<<<<<< + * cdef: + * TCyBuffer rbuf, rframe_buf, wframe_buf +*/ +struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport { + struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase __pyx_base; + struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *rbuf; + struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *rframe_buf; + struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *wframe_buf; +}; + + + +/* "thriftpy2/transport/cybase.pxd":7 + * STACK_STRING_LEN = 4096 + * + * cdef class TCyBuffer(object): # <<<<<<<<<<<<<< + * cdef: + * char *buf +*/ + +struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_TCyBuffer { + void (*move_to_start)(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *); + void (*clean)(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *); + int (*write)(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *, int, char const *); + int (*grow)(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *, int); + PyObject *(*read_trans)(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *, PyObject *, int, char *); +}; +static struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_TCyBuffer *__pyx_vtabptr_9thriftpy2_9transport_6cybase_TCyBuffer; + + +/* "thriftpy2/transport/cybase.pxd":19 + * + * + * cdef class CyTransportBase(object): # <<<<<<<<<<<<<< + * cdef object trans + * +*/ + +struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_CyTransportBase { + PyObject *(*c_read)(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *, int, char *); + PyObject *(*c_write)(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *, char *, int); + PyObject *(*c_flush)(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *); + PyObject *(*get_string)(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *, int); +}; +static struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_CyTransportBase *__pyx_vtabptr_9thriftpy2_9transport_6cybase_CyTransportBase; + + +/* "thriftpy2/transport/framed/cyframed.pyx":22 + * + * + * cdef class TCyFramedTransport(CyTransportBase): # <<<<<<<<<<<<<< + * cdef: + * TCyBuffer rbuf, rframe_buf, wframe_buf +*/ + +struct __pyx_vtabstruct_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport { + struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_CyTransportBase __pyx_base; + PyObject *(*read_trans)(struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *, int, char *); + PyObject *(*write_rframe_buffer)(struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *, char const *, int); + PyObject *(*read_frame)(struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *); +}; +static struct __pyx_vtabstruct_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *__pyx_vtabptr_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport; +/* #### Code section: utility_code_proto ### */ + +/* --- Runtime support code (head) --- */ +/* Refnanny.proto */ +#ifndef CYTHON_REFNANNY + #define CYTHON_REFNANNY 0 +#endif +#if CYTHON_REFNANNY + typedef struct { + void (*INCREF)(void*, PyObject*, Py_ssize_t); + void (*DECREF)(void*, PyObject*, Py_ssize_t); + void (*GOTREF)(void*, PyObject*, Py_ssize_t); + void (*GIVEREF)(void*, PyObject*, Py_ssize_t); + void* (*SetupContext)(const char*, Py_ssize_t, const char*); + void (*FinishContext)(void**); + } __Pyx_RefNannyAPIStruct; + static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; + static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); + #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; + #define __Pyx_RefNannySetupContext(name, acquire_gil)\ + if (acquire_gil) {\ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), (__LINE__), (__FILE__));\ + PyGILState_Release(__pyx_gilstate_save);\ + } else {\ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), (__LINE__), (__FILE__));\ + } + #define __Pyx_RefNannyFinishContextNogil() {\ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ + __Pyx_RefNannyFinishContext();\ + PyGILState_Release(__pyx_gilstate_save);\ + } + #define __Pyx_RefNannyFinishContextNogil() {\ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ + __Pyx_RefNannyFinishContext();\ + PyGILState_Release(__pyx_gilstate_save);\ + } + #define __Pyx_RefNannyFinishContext()\ + __Pyx_RefNanny->FinishContext(&__pyx_refnanny) + #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), (__LINE__)) + #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), (__LINE__)) + #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), (__LINE__)) + #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), (__LINE__)) + #define __Pyx_XINCREF(r) do { if((r) == NULL); else {__Pyx_INCREF(r); }} while(0) + #define __Pyx_XDECREF(r) do { if((r) == NULL); else {__Pyx_DECREF(r); }} while(0) + #define __Pyx_XGOTREF(r) do { if((r) == NULL); else {__Pyx_GOTREF(r); }} while(0) + #define __Pyx_XGIVEREF(r) do { if((r) == NULL); else {__Pyx_GIVEREF(r);}} while(0) +#else + #define __Pyx_RefNannyDeclarations + #define __Pyx_RefNannySetupContext(name, acquire_gil) + #define __Pyx_RefNannyFinishContextNogil() + #define __Pyx_RefNannyFinishContext() + #define __Pyx_INCREF(r) Py_INCREF(r) + #define __Pyx_DECREF(r) Py_DECREF(r) + #define __Pyx_GOTREF(r) + #define __Pyx_GIVEREF(r) + #define __Pyx_XINCREF(r) Py_XINCREF(r) + #define __Pyx_XDECREF(r) Py_XDECREF(r) + #define __Pyx_XGOTREF(r) + #define __Pyx_XGIVEREF(r) +#endif +#define __Pyx_Py_XDECREF_SET(r, v) do {\ + PyObject *tmp = (PyObject *) r;\ + r = v; Py_XDECREF(tmp);\ + } while (0) +#define __Pyx_XDECREF_SET(r, v) do {\ + PyObject *tmp = (PyObject *) r;\ + r = v; __Pyx_XDECREF(tmp);\ + } while (0) +#define __Pyx_DECREF_SET(r, v) do {\ + PyObject *tmp = (PyObject *) r;\ + r = v; __Pyx_DECREF(tmp);\ + } while (0) +#define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) +#define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) + +/* PyErrExceptionMatches.proto (used by PyObjectGetAttrStrNoError) */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_PyErr_ExceptionMatches(err) __Pyx_PyErr_ExceptionMatchesInState(__pyx_tstate, err) +static CYTHON_INLINE int __Pyx_PyErr_ExceptionMatchesInState(PyThreadState* tstate, PyObject* err); +#else +#define __Pyx_PyErr_ExceptionMatches(err) PyErr_ExceptionMatches(err) +#endif + +/* PyThreadStateGet.proto (used by PyErrFetchRestore) */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_PyThreadState_declare PyThreadState *__pyx_tstate; +#define __Pyx_PyThreadState_assign __pyx_tstate = __Pyx_PyThreadState_Current; +#if PY_VERSION_HEX >= 0x030C00A6 +#define __Pyx_PyErr_Occurred() (__pyx_tstate->current_exception != NULL) +#define __Pyx_PyErr_CurrentExceptionType() (__pyx_tstate->current_exception ? (PyObject*) Py_TYPE(__pyx_tstate->current_exception) : (PyObject*) NULL) +#else +#define __Pyx_PyErr_Occurred() (__pyx_tstate->curexc_type != NULL) +#define __Pyx_PyErr_CurrentExceptionType() (__pyx_tstate->curexc_type) +#endif +#else +#define __Pyx_PyThreadState_declare +#define __Pyx_PyThreadState_assign +#define __Pyx_PyErr_Occurred() (PyErr_Occurred() != NULL) +#define __Pyx_PyErr_CurrentExceptionType() PyErr_Occurred() +#endif + +/* PyErrFetchRestore.proto (used by PyObjectGetAttrStrNoError) */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_PyErr_Clear() __Pyx_ErrRestore(NULL, NULL, NULL) +#define __Pyx_ErrRestoreWithState(type, value, tb) __Pyx_ErrRestoreInState(PyThreadState_GET(), type, value, tb) +#define __Pyx_ErrFetchWithState(type, value, tb) __Pyx_ErrFetchInState(PyThreadState_GET(), type, value, tb) +#define __Pyx_ErrRestore(type, value, tb) __Pyx_ErrRestoreInState(__pyx_tstate, type, value, tb) +#define __Pyx_ErrFetch(type, value, tb) __Pyx_ErrFetchInState(__pyx_tstate, type, value, tb) +static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); +static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030C00A6 +#define __Pyx_PyErr_SetNone(exc) (Py_INCREF(exc), __Pyx_ErrRestore((exc), NULL, NULL)) +#else +#define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) +#endif +#else +#define __Pyx_PyErr_Clear() PyErr_Clear() +#define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) +#define __Pyx_ErrRestoreWithState(type, value, tb) PyErr_Restore(type, value, tb) +#define __Pyx_ErrFetchWithState(type, value, tb) PyErr_Fetch(type, value, tb) +#define __Pyx_ErrRestoreInState(tstate, type, value, tb) PyErr_Restore(type, value, tb) +#define __Pyx_ErrFetchInState(tstate, type, value, tb) PyErr_Fetch(type, value, tb) +#define __Pyx_ErrRestore(type, value, tb) PyErr_Restore(type, value, tb) +#define __Pyx_ErrFetch(type, value, tb) PyErr_Fetch(type, value, tb) +#endif + +/* PyObjectGetAttrStr.proto (used by PyObjectGetAttrStrNoError) */ +#if CYTHON_USE_TYPE_SLOTS +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name); +#else +#define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) +#endif + +/* PyObjectGetAttrStrNoError.proto (used by GetBuiltinName) */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStrNoError(PyObject* obj, PyObject* attr_name); + +/* GetBuiltinName.proto */ +static PyObject *__Pyx_GetBuiltinName(PyObject *name); + +/* TupleAndListFromArray.proto (used by fastcall) */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyList_FromArray(PyObject *const *src, Py_ssize_t n); +#endif +#if CYTHON_COMPILING_IN_CPYTHON || CYTHON_METH_FASTCALL +static CYTHON_INLINE PyObject* __Pyx_PyTuple_FromArray(PyObject *const *src, Py_ssize_t n); +#endif + +/* IncludeStringH.proto (used by BytesEquals) */ +#include + +/* BytesEquals.proto (used by UnicodeEquals) */ +static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals); + +/* UnicodeEquals.proto (used by fastcall) */ +static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals); + +/* fastcall.proto */ +#if CYTHON_AVOID_BORROWED_REFS + #define __Pyx_ArgRef_VARARGS(args, i) __Pyx_PySequence_ITEM(args, i) +#elif CYTHON_ASSUME_SAFE_MACROS + #define __Pyx_ArgRef_VARARGS(args, i) __Pyx_NewRef(__Pyx_PyTuple_GET_ITEM(args, i)) +#else + #define __Pyx_ArgRef_VARARGS(args, i) __Pyx_XNewRef(PyTuple_GetItem(args, i)) +#endif +#define __Pyx_NumKwargs_VARARGS(kwds) PyDict_Size(kwds) +#define __Pyx_KwValues_VARARGS(args, nargs) NULL +#define __Pyx_GetKwValue_VARARGS(kw, kwvalues, s) __Pyx_PyDict_GetItemStrWithError(kw, s) +#define __Pyx_KwargsAsDict_VARARGS(kw, kwvalues) PyDict_Copy(kw) +#if CYTHON_METH_FASTCALL + #define __Pyx_ArgRef_FASTCALL(args, i) __Pyx_NewRef(args[i]) + #define __Pyx_NumKwargs_FASTCALL(kwds) __Pyx_PyTuple_GET_SIZE(kwds) + #define __Pyx_KwValues_FASTCALL(args, nargs) ((args) + (nargs)) + static CYTHON_INLINE PyObject * __Pyx_GetKwValue_FASTCALL(PyObject *kwnames, PyObject *const *kwvalues, PyObject *s); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030d0000 || CYTHON_COMPILING_IN_LIMITED_API + CYTHON_UNUSED static PyObject *__Pyx_KwargsAsDict_FASTCALL(PyObject *kwnames, PyObject *const *kwvalues); + #else + #define __Pyx_KwargsAsDict_FASTCALL(kw, kwvalues) _PyStack_AsDict(kwvalues, kw) + #endif +#else + #define __Pyx_ArgRef_FASTCALL __Pyx_ArgRef_VARARGS + #define __Pyx_NumKwargs_FASTCALL __Pyx_NumKwargs_VARARGS + #define __Pyx_KwValues_FASTCALL __Pyx_KwValues_VARARGS + #define __Pyx_GetKwValue_FASTCALL __Pyx_GetKwValue_VARARGS + #define __Pyx_KwargsAsDict_FASTCALL __Pyx_KwargsAsDict_VARARGS +#endif +#define __Pyx_ArgsSlice_VARARGS(args, start, stop) PyTuple_GetSlice(args, start, stop) +#if CYTHON_METH_FASTCALL || (CYTHON_COMPILING_IN_CPYTHON && CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS) +#define __Pyx_ArgsSlice_FASTCALL(args, start, stop) __Pyx_PyTuple_FromArray(args + start, stop - start) +#else +#define __Pyx_ArgsSlice_FASTCALL(args, start, stop) PyTuple_GetSlice(args, start, stop) +#endif + +/* py_dict_items.proto (used by OwnedDictNext) */ +static CYTHON_INLINE PyObject* __Pyx_PyDict_Items(PyObject* d); + +/* CallCFunction.proto (used by CallUnboundCMethod0) */ +#define __Pyx_CallCFunction(cfunc, self, args)\ + ((PyCFunction)(void(*)(void))(cfunc)->func)(self, args) +#define __Pyx_CallCFunctionWithKeywords(cfunc, self, args, kwargs)\ + ((PyCFunctionWithKeywords)(void(*)(void))(cfunc)->func)(self, args, kwargs) +#define __Pyx_CallCFunctionFast(cfunc, self, args, nargs)\ + ((__Pyx_PyCFunctionFast)(void(*)(void))(PyCFunction)(cfunc)->func)(self, args, nargs) +#define __Pyx_CallCFunctionFastWithKeywords(cfunc, self, args, nargs, kwnames)\ + ((__Pyx_PyCFunctionFastWithKeywords)(void(*)(void))(PyCFunction)(cfunc)->func)(self, args, nargs, kwnames) + +/* PyObjectCall.proto (used by PyObjectFastCall) */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw); +#else +#define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw) +#endif + +/* PyObjectCallMethO.proto (used by PyObjectFastCall) */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg); +#endif + +/* PyObjectFastCall.proto (used by PyObjectCallOneArg) */ +#define __Pyx_PyObject_FastCall(func, args, nargs) __Pyx_PyObject_FastCallDict(func, args, (size_t)(nargs), NULL) +static CYTHON_INLINE PyObject* __Pyx_PyObject_FastCallDict(PyObject *func, PyObject * const*args, size_t nargs, PyObject *kwargs); + +/* PyObjectCallOneArg.proto (used by CallUnboundCMethod0) */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg); + +/* UnpackUnboundCMethod.proto (used by CallUnboundCMethod0) */ +typedef struct { + PyObject *type; + PyObject **method_name; +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING && CYTHON_ATOMICS + __pyx_atomic_int_type initialized; +#endif + PyCFunction func; + PyObject *method; + int flag; +} __Pyx_CachedCFunction; +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING +static CYTHON_INLINE int __Pyx_CachedCFunction_GetAndSetInitializing(__Pyx_CachedCFunction *cfunc) { +#if !CYTHON_ATOMICS + return 1; +#else + __pyx_nonatomic_int_type expected = 0; + if (__pyx_atomic_int_cmp_exchange(&cfunc->initialized, &expected, 1)) { + return 0; + } + return expected; +#endif +} +static CYTHON_INLINE void __Pyx_CachedCFunction_SetFinishedInitializing(__Pyx_CachedCFunction *cfunc) { +#if CYTHON_ATOMICS + __pyx_atomic_store(&cfunc->initialized, 2); +#endif +} +#else +#define __Pyx_CachedCFunction_GetAndSetInitializing(cfunc) 2 +#define __Pyx_CachedCFunction_SetFinishedInitializing(cfunc) +#endif + +/* CallUnboundCMethod0.proto */ +CYTHON_UNUSED +static PyObject* __Pyx__CallUnboundCMethod0(__Pyx_CachedCFunction* cfunc, PyObject* self); +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_CallUnboundCMethod0(__Pyx_CachedCFunction* cfunc, PyObject* self); +#else +#define __Pyx_CallUnboundCMethod0(cfunc, self) __Pyx__CallUnboundCMethod0(cfunc, self) +#endif + +/* py_dict_values.proto (used by OwnedDictNext) */ +static CYTHON_INLINE PyObject* __Pyx_PyDict_Values(PyObject* d); + +/* OwnedDictNext.proto (used by ParseKeywordsImpl) */ +#if CYTHON_AVOID_BORROWED_REFS +static int __Pyx_PyDict_NextRef(PyObject *p, PyObject **ppos, PyObject **pkey, PyObject **pvalue); +#else +CYTHON_INLINE +static int __Pyx_PyDict_NextRef(PyObject *p, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue); +#endif + +/* RaiseDoubleKeywords.proto (used by ParseKeywordsImpl) */ +static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); + +/* ParseKeywordsImpl.export */ +static int __Pyx_ParseKeywordsTuple( + PyObject *kwds, + PyObject * const *kwvalues, + PyObject ** const argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + Py_ssize_t num_kwargs, + const char* function_name, + int ignore_unknown_kwargs +); +static int __Pyx_ParseKeywordDictToDict( + PyObject *kwds, + PyObject ** const argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + const char* function_name +); +static int __Pyx_ParseKeywordDict( + PyObject *kwds, + PyObject ** const argnames[], + PyObject *values[], + Py_ssize_t num_pos_args, + Py_ssize_t num_kwargs, + const char* function_name, + int ignore_unknown_kwargs +); + +/* CallUnboundCMethod2.proto */ +CYTHON_UNUSED +static PyObject* __Pyx__CallUnboundCMethod2(__Pyx_CachedCFunction* cfunc, PyObject* self, PyObject* arg1, PyObject* arg2); +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject *__Pyx_CallUnboundCMethod2(__Pyx_CachedCFunction *cfunc, PyObject *self, PyObject *arg1, PyObject *arg2); +#else +#define __Pyx_CallUnboundCMethod2(cfunc, self, arg1, arg2) __Pyx__CallUnboundCMethod2(cfunc, self, arg1, arg2) +#endif + +/* ParseKeywords.proto */ +static CYTHON_INLINE int __Pyx_ParseKeywords( + PyObject *kwds, PyObject *const *kwvalues, PyObject ** const argnames[], + PyObject *kwds2, PyObject *values[], + Py_ssize_t num_pos_args, Py_ssize_t num_kwargs, + const char* function_name, + int ignore_unknown_kwargs +); + +/* RaiseArgTupleInvalid.proto */ +static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, + Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); + +/* PyDictVersioning.proto (used by GetModuleGlobalName) */ +#if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_TYPE_SLOTS +#define __PYX_DICT_VERSION_INIT ((PY_UINT64_T) -1) +#define __PYX_GET_DICT_VERSION(dict) (((PyDictObject*)(dict))->ma_version_tag) +#define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var)\ + (version_var) = __PYX_GET_DICT_VERSION(dict);\ + (cache_var) = (value); +#define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) {\ + static PY_UINT64_T __pyx_dict_version = 0;\ + static PyObject *__pyx_dict_cached_value = NULL;\ + if (likely(__PYX_GET_DICT_VERSION(DICT) == __pyx_dict_version)) {\ + (VAR) = __Pyx_XNewRef(__pyx_dict_cached_value);\ + } else {\ + (VAR) = __pyx_dict_cached_value = (LOOKUP);\ + __pyx_dict_version = __PYX_GET_DICT_VERSION(DICT);\ + }\ +} +static CYTHON_INLINE PY_UINT64_T __Pyx_get_tp_dict_version(PyObject *obj); +static CYTHON_INLINE PY_UINT64_T __Pyx_get_object_dict_version(PyObject *obj); +static CYTHON_INLINE int __Pyx_object_dict_version_matches(PyObject* obj, PY_UINT64_T tp_dict_version, PY_UINT64_T obj_dict_version); +#else +#define __PYX_GET_DICT_VERSION(dict) (0) +#define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var) +#define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) (VAR) = (LOOKUP); +#endif + +/* GetModuleGlobalName.proto */ +#if CYTHON_USE_DICT_VERSIONS +#define __Pyx_GetModuleGlobalName(var, name) do {\ + static PY_UINT64_T __pyx_dict_version = 0;\ + static PyObject *__pyx_dict_cached_value = NULL;\ + (var) = (likely(__pyx_dict_version == __PYX_GET_DICT_VERSION(__pyx_mstate_global->__pyx_d))) ?\ + (likely(__pyx_dict_cached_value) ? __Pyx_NewRef(__pyx_dict_cached_value) : __Pyx_GetBuiltinName(name)) :\ + __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\ +} while(0) +#define __Pyx_GetModuleGlobalNameUncached(var, name) do {\ + PY_UINT64_T __pyx_dict_version;\ + PyObject *__pyx_dict_cached_value;\ + (var) = __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\ +} while(0) +static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_version, PyObject **dict_cached_value); +#else +#define __Pyx_GetModuleGlobalName(var, name) (var) = __Pyx__GetModuleGlobalName(name) +#define __Pyx_GetModuleGlobalNameUncached(var, name) (var) = __Pyx__GetModuleGlobalName(name) +static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name); +#endif + +/* RaiseException.export */ +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); + +/* PyMemoryError_Check.proto */ +#define __Pyx_PyExc_MemoryError_Check(obj) __Pyx_TypeCheck(obj, PyExc_MemoryError) + +/* GetException.proto */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_GetException(type, value, tb) __Pyx__GetException(__pyx_tstate, type, value, tb) +static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); +#else +static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb); +#endif + +/* SwapException.proto */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_ExceptionSwap(type, value, tb) __Pyx__ExceptionSwap(__pyx_tstate, type, value, tb) +static CYTHON_INLINE void __Pyx__ExceptionSwap(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); +#else +static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb); +#endif + +/* GetTopmostException.proto (used by SaveResetException) */ +#if CYTHON_USE_EXC_INFO_STACK && CYTHON_FAST_THREAD_STATE +static _PyErr_StackItem * __Pyx_PyErr_GetTopmostException(PyThreadState *tstate); +#endif + +/* SaveResetException.proto */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_ExceptionSave(type, value, tb) __Pyx__ExceptionSave(__pyx_tstate, type, value, tb) +static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); +#define __Pyx_ExceptionReset(type, value, tb) __Pyx__ExceptionReset(__pyx_tstate, type, value, tb) +static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); +#else +#define __Pyx_ExceptionSave(type, value, tb) PyErr_GetExcInfo(type, value, tb) +#define __Pyx_ExceptionReset(type, value, tb) PyErr_SetExcInfo(type, value, tb) +#endif + +/* PyObjectFastCallMethod.proto */ +#if CYTHON_VECTORCALL && PY_VERSION_HEX >= 0x03090000 +#define __Pyx_PyObject_FastCallMethod(name, args, nargsf) PyObject_VectorcallMethod(name, args, nargsf, NULL) +#else +static PyObject *__Pyx_PyObject_FastCallMethod(PyObject *name, PyObject *const *args, size_t nargsf); +#endif + +/* ArgTypeTestFunc.export */ +static int __Pyx__ArgTypeTest(PyObject *obj, PyTypeObject *type, const char *name, int exact); + +/* ArgTypeTest.proto */ +#define __Pyx_ArgTypeTest(obj, type, none_allowed, name, exact)\ + ((likely(__Pyx_IS_TYPE(obj, type) | (none_allowed && (obj == Py_None)))) ? 1 :\ + __Pyx__ArgTypeTest(obj, type, name, exact)) + +/* RejectKeywords.export */ +static void __Pyx_RejectKeywords(const char* function_name, PyObject *kwds); + +/* GetAttr3.proto */ +static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *, PyObject *, PyObject *); + +/* RaiseUnexpectedTypeError.proto */ +static int __Pyx_RaiseUnexpectedTypeError(const char *expected, PyObject *obj); + +/* GetItemInt.proto */ +#define __Pyx_GetItemInt(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck, has_gil, unsafe_shared)\ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ + __Pyx_GetItemInt_Fast(o, (Py_ssize_t)i, is_list, wraparound, boundscheck, unsafe_shared) :\ + (is_list ? (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL) :\ + __Pyx_GetItemInt_Generic(o, to_py_func(i)))) +#define __Pyx_GetItemInt_List(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck, has_gil, unsafe_shared)\ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ + __Pyx_GetItemInt_List_Fast(o, (Py_ssize_t)i, wraparound, boundscheck, unsafe_shared) :\ + (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL)) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck, int unsafe_shared); +#define __Pyx_GetItemInt_Tuple(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck, has_gil, unsafe_shared)\ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ + __Pyx_GetItemInt_Tuple_Fast(o, (Py_ssize_t)i, wraparound, boundscheck, unsafe_shared) :\ + (PyErr_SetString(PyExc_IndexError, "tuple index out of range"), (PyObject*)NULL)) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck, int unsafe_shared); +static PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j); +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, + int is_list, int wraparound, int boundscheck, int unsafe_shared); + +/* ExtTypeTest.proto */ +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); + +/* CallNextTpDealloc.proto */ +static void __Pyx_call_next_tp_dealloc(PyObject* obj, destructor current_tp_dealloc); + +/* CallNextTpTraverse.proto */ +static int __Pyx_call_next_tp_traverse(PyObject* obj, visitproc v, void *a, traverseproc current_tp_traverse); + +/* CallTypeTraverse.proto */ +#if !CYTHON_USE_TYPE_SPECS || (!CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x03090000) +#define __Pyx_call_type_traverse(o, always_call, visit, arg) 0 +#else +static int __Pyx_call_type_traverse(PyObject *o, int always_call, visitproc visit, void *arg); +#endif + +/* CallNextTpClear.proto */ +static void __Pyx_call_next_tp_clear(PyObject* obj, inquiry current_tp_clear); + +/* TypeImport.proto */ +#ifndef __PYX_HAVE_RT_ImportType_proto_3_2_4 +#define __PYX_HAVE_RT_ImportType_proto_3_2_4 +#if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 201112L +#include +#endif +#if (defined (__STDC_VERSION__) && __STDC_VERSION__ >= 201112L) || __cplusplus >= 201103L +#define __PYX_GET_STRUCT_ALIGNMENT_3_2_4(s) alignof(s) +#else +#define __PYX_GET_STRUCT_ALIGNMENT_3_2_4(s) sizeof(void*) +#endif +enum __Pyx_ImportType_CheckSize_3_2_4 { + __Pyx_ImportType_CheckSize_Error_3_2_4 = 0, + __Pyx_ImportType_CheckSize_Warn_3_2_4 = 1, + __Pyx_ImportType_CheckSize_Ignore_3_2_4 = 2 +}; +static PyTypeObject *__Pyx_ImportType_3_2_4(PyObject* module, const char *module_name, const char *class_name, size_t size, size_t alignment, enum __Pyx_ImportType_CheckSize_3_2_4 check_size); +#endif + +/* GetVTable.proto */ +static void* __Pyx_GetVtable(PyTypeObject *type); + +/* LimitedApiGetTypeDict.proto (used by SetItemOnTypeDict) */ +#if CYTHON_COMPILING_IN_LIMITED_API +static PyObject *__Pyx_GetTypeDict(PyTypeObject *tp); +#endif + +/* SetItemOnTypeDict.proto (used by FixUpExtensionType) */ +static int __Pyx__SetItemOnTypeDict(PyTypeObject *tp, PyObject *k, PyObject *v); +#define __Pyx_SetItemOnTypeDict(tp, k, v) __Pyx__SetItemOnTypeDict((PyTypeObject*)tp, k, v) + +/* FixUpExtensionType.proto */ +static CYTHON_INLINE int __Pyx_fix_up_extension_type_from_spec(PyType_Spec *spec, PyTypeObject *type); + +/* PyObjectCallNoArg.proto (used by PyObjectCallMethod0) */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func); + +/* PyObjectGetMethod.proto (used by PyObjectCallMethod0) */ +#if !(CYTHON_VECTORCALL && (__PYX_LIMITED_VERSION_HEX >= 0x030C0000 || (!CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x03090000))) +static int __Pyx_PyObject_GetMethod(PyObject *obj, PyObject *name, PyObject **method); +#endif + +/* PyObjectCallMethod0.proto (used by PyType_Ready) */ +static PyObject* __Pyx_PyObject_CallMethod0(PyObject* obj, PyObject* method_name); + +/* ValidateBasesTuple.proto (used by PyType_Ready) */ +#if CYTHON_COMPILING_IN_CPYTHON || CYTHON_COMPILING_IN_LIMITED_API || CYTHON_USE_TYPE_SPECS +static int __Pyx_validate_bases_tuple(const char *type_name, Py_ssize_t dictoffset, PyObject *bases); +#endif + +/* PyType_Ready.proto */ +CYTHON_UNUSED static int __Pyx_PyType_Ready(PyTypeObject *t); + +/* SetVTable.proto */ +static int __Pyx_SetVtable(PyTypeObject* typeptr , void* vtable); + +/* MergeVTables.proto */ +static int __Pyx_MergeVtables(PyTypeObject *type); + +/* DelItemOnTypeDict.proto (used by SetupReduce) */ +static int __Pyx__DelItemOnTypeDict(PyTypeObject *tp, PyObject *k); +#define __Pyx_DelItemOnTypeDict(tp, k) __Pyx__DelItemOnTypeDict((PyTypeObject*)tp, k) + +/* SetupReduce.proto */ +static int __Pyx_setup_reduce(PyObject* type_obj); + +/* HasAttr.proto (used by ImportImpl) */ +#if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 +#define __Pyx_HasAttr(o, n) PyObject_HasAttrWithError(o, n) +#else +static CYTHON_INLINE int __Pyx_HasAttr(PyObject *, PyObject *); +#endif + +/* ImportImpl.export */ +static PyObject *__Pyx__Import(PyObject *name, PyObject *const *imported_names, Py_ssize_t len_imported_names, PyObject *qualname, PyObject *moddict, int level); + +/* Import.proto */ +static CYTHON_INLINE PyObject *__Pyx_Import(PyObject *name, PyObject *const *imported_names, Py_ssize_t len_imported_names, PyObject *qualname, int level); + +/* ImportFrom.proto */ +static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name); + +/* dict_setdefault.proto (used by FetchCommonType) */ +static CYTHON_INLINE PyObject *__Pyx_PyDict_SetDefault(PyObject *d, PyObject *key, PyObject *default_value); + +/* AddModuleRef.proto (used by FetchSharedCythonModule) */ +#if ((CYTHON_COMPILING_IN_CPYTHON_FREETHREADING ) ||\ + __PYX_LIMITED_VERSION_HEX < 0x030d0000) + static PyObject *__Pyx_PyImport_AddModuleRef(const char *name); +#else + #define __Pyx_PyImport_AddModuleRef(name) PyImport_AddModuleRef(name) +#endif + +/* FetchSharedCythonModule.proto (used by FetchCommonType) */ +static PyObject *__Pyx_FetchSharedCythonABIModule(void); + +/* FetchCommonType.proto (used by CommonTypesMetaclass) */ +static PyTypeObject* __Pyx_FetchCommonTypeFromSpec(PyTypeObject *metaclass, PyObject *module, PyType_Spec *spec, PyObject *bases); + +/* CommonTypesMetaclass.proto (used by CythonFunctionShared) */ +static int __pyx_CommonTypesMetaclass_init(PyObject *module); +#define __Pyx_CommonTypesMetaclass_USED + +/* PyMethodNew.proto (used by CythonFunctionShared) */ +static PyObject *__Pyx_PyMethod_New(PyObject *func, PyObject *self, PyObject *typ); + +/* PyVectorcallFastCallDict.proto (used by CythonFunctionShared) */ +#if CYTHON_METH_FASTCALL && CYTHON_VECTORCALL +static CYTHON_INLINE PyObject *__Pyx_PyVectorcall_FastCallDict(PyObject *func, __pyx_vectorcallfunc vc, PyObject *const *args, size_t nargs, PyObject *kw); +#endif + +/* CythonFunctionShared.proto (used by CythonFunction) */ +#define __Pyx_CyFunction_USED +#define __Pyx_CYFUNCTION_STATICMETHOD 0x01 +#define __Pyx_CYFUNCTION_CLASSMETHOD 0x02 +#define __Pyx_CYFUNCTION_CCLASS 0x04 +#define __Pyx_CYFUNCTION_COROUTINE 0x08 +#define __Pyx_CyFunction_GetClosure(f)\ + (((__pyx_CyFunctionObject *) (f))->func_closure) +#if PY_VERSION_HEX < 0x030900B1 || CYTHON_COMPILING_IN_LIMITED_API + #define __Pyx_CyFunction_GetClassObj(f)\ + (((__pyx_CyFunctionObject *) (f))->func_classobj) +#else + #define __Pyx_CyFunction_GetClassObj(f)\ + ((PyObject*) ((PyCMethodObject *) (f))->mm_class) +#endif +#define __Pyx_CyFunction_SetClassObj(f, classobj)\ + __Pyx__CyFunction_SetClassObj((__pyx_CyFunctionObject *) (f), (classobj)) +#define __Pyx_CyFunction_Defaults(type, f)\ + ((type *)(((__pyx_CyFunctionObject *) (f))->defaults)) +#define __Pyx_CyFunction_SetDefaultsGetter(f, g)\ + ((__pyx_CyFunctionObject *) (f))->defaults_getter = (g) +typedef struct { +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject_HEAD + PyObject *func; +#elif PY_VERSION_HEX < 0x030900B1 + PyCFunctionObject func; +#else + PyCMethodObject func; +#endif +#if CYTHON_COMPILING_IN_LIMITED_API && CYTHON_METH_FASTCALL + __pyx_vectorcallfunc func_vectorcall; +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *func_weakreflist; +#endif +#if PY_VERSION_HEX < 0x030C0000 || CYTHON_COMPILING_IN_LIMITED_API + PyObject *func_dict; +#endif + PyObject *func_name; + PyObject *func_qualname; + PyObject *func_doc; + PyObject *func_globals; + PyObject *func_code; + PyObject *func_closure; +#if PY_VERSION_HEX < 0x030900B1 || CYTHON_COMPILING_IN_LIMITED_API + PyObject *func_classobj; +#endif + PyObject *defaults; + int flags; + PyObject *defaults_tuple; + PyObject *defaults_kwdict; + PyObject *(*defaults_getter)(PyObject *); + PyObject *func_annotations; + PyObject *func_is_coroutine; +} __pyx_CyFunctionObject; +#undef __Pyx_CyOrPyCFunction_Check +#define __Pyx_CyFunction_Check(obj) __Pyx_TypeCheck(obj, __pyx_mstate_global->__pyx_CyFunctionType) +#define __Pyx_CyOrPyCFunction_Check(obj) __Pyx_TypeCheck2(obj, __pyx_mstate_global->__pyx_CyFunctionType, &PyCFunction_Type) +#define __Pyx_CyFunction_CheckExact(obj) __Pyx_IS_TYPE(obj, __pyx_mstate_global->__pyx_CyFunctionType) +static CYTHON_INLINE int __Pyx__IsSameCyOrCFunction(PyObject *func, void (*cfunc)(void)); +#undef __Pyx_IsSameCFunction +#define __Pyx_IsSameCFunction(func, cfunc) __Pyx__IsSameCyOrCFunction(func, cfunc) +static PyObject *__Pyx_CyFunction_Init(__pyx_CyFunctionObject* op, PyMethodDef *ml, + int flags, PyObject* qualname, + PyObject *closure, + PyObject *module, PyObject *globals, + PyObject* code); +static CYTHON_INLINE void __Pyx__CyFunction_SetClassObj(__pyx_CyFunctionObject* f, PyObject* classobj); +static CYTHON_INLINE PyObject *__Pyx_CyFunction_InitDefaults(PyObject *func, + PyTypeObject *defaults_type); +static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsTuple(PyObject *m, + PyObject *tuple); +static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsKwDict(PyObject *m, + PyObject *dict); +static CYTHON_INLINE void __Pyx_CyFunction_SetAnnotationsDict(PyObject *m, + PyObject *dict); +static int __pyx_CyFunction_init(PyObject *module); +#if CYTHON_METH_FASTCALL +static PyObject * __Pyx_CyFunction_Vectorcall_NOARGS(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames); +static PyObject * __Pyx_CyFunction_Vectorcall_O(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames); +static PyObject * __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames); +static PyObject * __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS_METHOD(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames); +#if CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_CyFunction_func_vectorcall(f) (((__pyx_CyFunctionObject*)f)->func_vectorcall) +#else +#define __Pyx_CyFunction_func_vectorcall(f) (((PyCFunctionObject*)f)->vectorcall) +#endif +#endif + +/* CythonFunction.proto */ +static PyObject *__Pyx_CyFunction_New(PyMethodDef *ml, + int flags, PyObject* qualname, + PyObject *closure, + PyObject *module, PyObject *globals, + PyObject* code); + +/* Py3UpdateBases.proto */ +static PyObject* __Pyx_PEP560_update_bases(PyObject *bases); + +/* CalculateMetaclass.proto */ +static PyObject *__Pyx_CalculateMetaclass(PyTypeObject *metaclass, PyObject *bases); + +/* SetNameInClass.proto */ +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030d0000 +#define __Pyx_SetNameInClass(ns, name, value)\ + (likely(PyDict_CheckExact(ns)) ? _PyDict_SetItem_KnownHash(ns, name, value, ((PyASCIIObject *) name)->hash) : PyObject_SetItem(ns, name, value)) +#elif CYTHON_COMPILING_IN_CPYTHON +#define __Pyx_SetNameInClass(ns, name, value)\ + (likely(PyDict_CheckExact(ns)) ? PyDict_SetItem(ns, name, value) : PyObject_SetItem(ns, name, value)) +#else +#define __Pyx_SetNameInClass(ns, name, value) PyObject_SetItem(ns, name, value) +#endif + +/* PyObjectCall2Args.proto (used by Py3ClassCreate) */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call2Args(PyObject* function, PyObject* arg1, PyObject* arg2); + +/* PyObjectLookupSpecial.proto (used by Py3ClassCreate) */ +#if CYTHON_USE_PYTYPE_LOOKUP && CYTHON_USE_TYPE_SLOTS +#define __Pyx_PyObject_LookupSpecialNoError(obj, attr_name) __Pyx__PyObject_LookupSpecial(obj, attr_name, 0) +#define __Pyx_PyObject_LookupSpecial(obj, attr_name) __Pyx__PyObject_LookupSpecial(obj, attr_name, 1) +static CYTHON_INLINE PyObject* __Pyx__PyObject_LookupSpecial(PyObject* obj, PyObject* attr_name, int with_error); +#else +#define __Pyx_PyObject_LookupSpecialNoError(o,n) __Pyx_PyObject_GetAttrStrNoError(o,n) +#define __Pyx_PyObject_LookupSpecial(o,n) __Pyx_PyObject_GetAttrStr(o,n) +#endif + +/* Py3ClassCreate.proto */ +static PyObject *__Pyx_Py3MetaclassPrepare(PyObject *metaclass, PyObject *bases, PyObject *name, PyObject *qualname, + PyObject *mkw, PyObject *modname, PyObject *doc); +static PyObject *__Pyx_Py3ClassCreate(PyObject *metaclass, PyObject *name, PyObject *bases, PyObject *dict, + PyObject *mkw, int calculate_metaclass, int allow_py2_metaclass); + +/* CLineInTraceback.proto (used by AddTraceback) */ +#if CYTHON_CLINE_IN_TRACEBACK && CYTHON_CLINE_IN_TRACEBACK_RUNTIME +static int __Pyx_CLineForTraceback(PyThreadState *tstate, int c_line); +#else +#define __Pyx_CLineForTraceback(tstate, c_line) (((CYTHON_CLINE_IN_TRACEBACK)) ? c_line : 0) +#endif + +/* CodeObjectCache.proto (used by AddTraceback) */ +#if CYTHON_COMPILING_IN_LIMITED_API +typedef PyObject __Pyx_CachedCodeObjectType; +#else +typedef PyCodeObject __Pyx_CachedCodeObjectType; +#endif +typedef struct { + __Pyx_CachedCodeObjectType* code_object; + int code_line; +} __Pyx_CodeObjectCacheEntry; +struct __Pyx_CodeObjectCache { + int count; + int max_count; + __Pyx_CodeObjectCacheEntry* entries; + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + __pyx_atomic_int_type accessor_count; + #endif +}; +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); +static __Pyx_CachedCodeObjectType *__pyx_find_code_object(int code_line); +static void __pyx_insert_code_object(int code_line, __Pyx_CachedCodeObjectType* code_object); + +/* AddTraceback.proto */ +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename); + +/* CheckUnpickleChecksum.proto */ +static CYTHON_INLINE int __Pyx_CheckUnpickleChecksum(long checksum, long checksum1, long checksum2, long checksum3, const char *members); + +/* GCCDiagnostics.proto */ +#if !defined(__INTEL_COMPILER) && defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) +#define __Pyx_HAS_GCC_DIAGNOSTIC +#endif + +/* CIntFromPy.proto */ +static CYTHON_INLINE int __Pyx_PyLong_As_int(PyObject *); + +/* CIntFromPy.proto */ +static CYTHON_INLINE long __Pyx_PyLong_As_long(PyObject *); + +/* PyObjectVectorCallKwBuilder.proto (used by CIntToPy) */ +CYTHON_UNUSED static int __Pyx_VectorcallBuilder_AddArg_Check(PyObject *key, PyObject *value, PyObject *builder, PyObject **args, int n); +#if CYTHON_VECTORCALL +#if PY_VERSION_HEX >= 0x03090000 +#define __Pyx_Object_Vectorcall_CallFromBuilder PyObject_Vectorcall +#else +#define __Pyx_Object_Vectorcall_CallFromBuilder _PyObject_Vectorcall +#endif +#define __Pyx_MakeVectorcallBuilderKwds(n) PyTuple_New(n) +static int __Pyx_VectorcallBuilder_AddArg(PyObject *key, PyObject *value, PyObject *builder, PyObject **args, int n); +static int __Pyx_VectorcallBuilder_AddArgStr(const char *key, PyObject *value, PyObject *builder, PyObject **args, int n); +#else +#define __Pyx_Object_Vectorcall_CallFromBuilder __Pyx_PyObject_FastCallDict +#define __Pyx_MakeVectorcallBuilderKwds(n) __Pyx_PyDict_NewPresized(n) +#define __Pyx_VectorcallBuilder_AddArg(key, value, builder, args, n) PyDict_SetItem(builder, key, value) +#define __Pyx_VectorcallBuilder_AddArgStr(key, value, builder, args, n) PyDict_SetItemString(builder, key, value) +#endif + +/* CIntToPy.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyLong_From_int(int value); + +/* CIntToPy.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyLong_From_long(long value); + +/* PyObjectCallMethod1.proto */ +static PyObject* __Pyx_PyObject_CallMethod1(PyObject* obj, PyObject* method_name, PyObject* arg); + +/* UpdateUnpickledDict.proto */ +static int __Pyx_UpdateUnpickledDict(PyObject *obj, PyObject *state, Py_ssize_t index); + +/* FormatTypeName.proto */ +#if CYTHON_COMPILING_IN_LIMITED_API +typedef PyObject *__Pyx_TypeName; +#define __Pyx_FMT_TYPENAME "%U" +#define __Pyx_DECREF_TypeName(obj) Py_XDECREF(obj) +#if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 +#define __Pyx_PyType_GetFullyQualifiedName PyType_GetFullyQualifiedName +#else +static __Pyx_TypeName __Pyx_PyType_GetFullyQualifiedName(PyTypeObject* tp); +#endif +#else // !LIMITED_API +typedef const char *__Pyx_TypeName; +#define __Pyx_FMT_TYPENAME "%.200s" +#define __Pyx_PyType_GetFullyQualifiedName(tp) ((tp)->tp_name) +#define __Pyx_DECREF_TypeName(obj) +#endif + +/* FastTypeChecks.proto */ +#if CYTHON_COMPILING_IN_CPYTHON +#define __Pyx_TypeCheck(obj, type) __Pyx_IsSubtype(Py_TYPE(obj), (PyTypeObject *)type) +#define __Pyx_TypeCheck2(obj, type1, type2) __Pyx_IsAnySubtype2(Py_TYPE(obj), (PyTypeObject *)type1, (PyTypeObject *)type2) +static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b); +static CYTHON_INLINE int __Pyx_IsAnySubtype2(PyTypeObject *cls, PyTypeObject *a, PyTypeObject *b); +static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches(PyObject *err, PyObject *type); +static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches2(PyObject *err, PyObject *type1, PyObject *type2); +#else +#define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) +#define __Pyx_TypeCheck2(obj, type1, type2) (PyObject_TypeCheck(obj, (PyTypeObject *)type1) || PyObject_TypeCheck(obj, (PyTypeObject *)type2)) +#define __Pyx_PyErr_GivenExceptionMatches(err, type) PyErr_GivenExceptionMatches(err, type) +static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches2(PyObject *err, PyObject *type1, PyObject *type2) { + return PyErr_GivenExceptionMatches(err, type1) || PyErr_GivenExceptionMatches(err, type2); +} +#endif +#define __Pyx_PyErr_ExceptionMatches2(err1, err2) __Pyx_PyErr_GivenExceptionMatches2(__Pyx_PyErr_CurrentExceptionType(), err1, err2) +#define __Pyx_PyException_Check(obj) __Pyx_TypeCheck(obj, PyExc_Exception) +#ifdef PyExceptionInstance_Check + #define __Pyx_PyBaseException_Check(obj) PyExceptionInstance_Check(obj) +#else + #define __Pyx_PyBaseException_Check(obj) __Pyx_TypeCheck(obj, PyExc_BaseException) +#endif + +/* GetRuntimeVersion.proto */ +#if __PYX_LIMITED_VERSION_HEX < 0x030b0000 +static unsigned long __Pyx_cached_runtime_version = 0; +static void __Pyx_init_runtime_version(void); +#else +#define __Pyx_init_runtime_version() +#endif +static unsigned long __Pyx_get_runtime_version(void); + +/* CheckBinaryVersion.proto */ +static int __Pyx_check_binary_version(unsigned long ct_version, unsigned long rt_version, int allow_newer); + +/* DecompressString.proto */ +static PyObject *__Pyx_DecompressString(const char *s, Py_ssize_t length, int algo); + +/* MultiPhaseInitModuleState.proto */ +#if CYTHON_PEP489_MULTI_PHASE_INIT && CYTHON_USE_MODULE_STATE +static PyObject *__Pyx_State_FindModule(void*); +static int __Pyx_State_AddModule(PyObject* module, void*); +static int __Pyx_State_RemoveModule(void*); +#elif CYTHON_USE_MODULE_STATE +#define __Pyx_State_FindModule PyState_FindModule +#define __Pyx_State_AddModule PyState_AddModule +#define __Pyx_State_RemoveModule PyState_RemoveModule +#endif + +/* #### Code section: module_declarations ### */ +/* CythonABIVersion.proto */ +#if CYTHON_COMPILING_IN_LIMITED_API + #if CYTHON_METH_FASTCALL + #define __PYX_FASTCALL_ABI_SUFFIX "_fastcall" + #else + #define __PYX_FASTCALL_ABI_SUFFIX + #endif + #define __PYX_LIMITED_ABI_SUFFIX "limited" __PYX_FASTCALL_ABI_SUFFIX __PYX_AM_SEND_ABI_SUFFIX +#else + #define __PYX_LIMITED_ABI_SUFFIX +#endif +#if __PYX_HAS_PY_AM_SEND == 1 + #define __PYX_AM_SEND_ABI_SUFFIX +#elif __PYX_HAS_PY_AM_SEND == 2 + #define __PYX_AM_SEND_ABI_SUFFIX "amsendbackport" +#else + #define __PYX_AM_SEND_ABI_SUFFIX "noamsend" +#endif +#ifndef __PYX_MONITORING_ABI_SUFFIX + #define __PYX_MONITORING_ABI_SUFFIX +#endif +#if CYTHON_USE_TP_FINALIZE + #define __PYX_TP_FINALIZE_ABI_SUFFIX +#else + #define __PYX_TP_FINALIZE_ABI_SUFFIX "nofinalize" +#endif +#if CYTHON_USE_FREELISTS || !defined(__Pyx_AsyncGen_USED) + #define __PYX_FREELISTS_ABI_SUFFIX +#else + #define __PYX_FREELISTS_ABI_SUFFIX "nofreelists" +#endif +#define CYTHON_ABI __PYX_ABI_VERSION __PYX_LIMITED_ABI_SUFFIX __PYX_MONITORING_ABI_SUFFIX __PYX_TP_FINALIZE_ABI_SUFFIX __PYX_FREELISTS_ABI_SUFFIX __PYX_AM_SEND_ABI_SUFFIX +#define __PYX_ABI_MODULE_NAME "_cython_" CYTHON_ABI +#define __PYX_TYPE_MODULE_PREFIX __PYX_ABI_MODULE_NAME "." + +static PyObject *__pyx_f_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_read_trans(struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *__pyx_v_self, int __pyx_v_sz, char *__pyx_v_out); /* proto*/ +static PyObject *__pyx_f_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_write_rframe_buffer(struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *__pyx_v_self, char const *__pyx_v_data, int __pyx_v_sz); /* proto*/ +static PyObject *__pyx_f_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_c_read(struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *__pyx_v_self, int __pyx_v_sz, char *__pyx_v_out); /* proto*/ +static PyObject *__pyx_f_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_c_write(struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *__pyx_v_self, char const *__pyx_v_data, int __pyx_v_sz); /* proto*/ +static PyObject *__pyx_f_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_read_frame(struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *__pyx_v_self); /* proto*/ +static PyObject *__pyx_f_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_c_flush(struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *__pyx_v_self); /* proto*/ + +/* Module declarations from "libc.string" */ + +/* Module declarations from "libc.stdlib" */ + +/* Module declarations from "libc.stdint" */ + +/* Module declarations from "thriftpy2.transport.cybase" */ + +/* Module declarations from "thriftpy2.transport.framed.cyframed" */ +static PyObject *__pyx_f_9thriftpy2_9transport_6framed_8cyframed___pyx_unpickle_TCyFramedTransport__set_state(struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *, PyObject *); /*proto*/ +/* #### Code section: typeinfo ### */ +/* #### Code section: before_global_var ### */ +#define __Pyx_MODULE_NAME "thriftpy2.transport.framed.cyframed" +extern int __pyx_module_is_main_thriftpy2__transport__framed__cyframed; +int __pyx_module_is_main_thriftpy2__transport__framed__cyframed = 0; + +/* Implementation of "thriftpy2.transport.framed.cyframed" */ +/* #### Code section: global_var ### */ +static PyObject *__pyx_builtin_object; +/* #### Code section: string_decls ### */ +static const char __pyx_k_rbuf_rframe_buf_trans_wframe_buf[] = "rbuf, rframe_buf, trans, wframe_buf"; +/* #### Code section: decls ### */ +static int __pyx_pf_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport___init__(struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *__pyx_v_self, PyObject *__pyx_v_trans, int __pyx_v_buf_size); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_2read(struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *__pyx_v_self, int __pyx_v_sz); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_4write(struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *__pyx_v_self, PyObject *__pyx_v_data); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_6flush(struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_8is_open(struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_10open(struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_12close(struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_14clean(struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_16__reduce_cython__(struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_18__setstate_cython__(struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *__pyx_v_self, PyObject *__pyx_v___pyx_state); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_9transport_6framed_8cyframed_25TCyFramedTransportFactory_get_transport(CYTHON_UNUSED PyObject *__pyx_self, CYTHON_UNUSED PyObject *__pyx_v_self, PyObject *__pyx_v_trans); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_9transport_6framed_8cyframed___pyx_unpickle_TCyFramedTransport(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v___pyx_type, long __pyx_v___pyx_checksum, PyObject *__pyx_v___pyx_state); /* proto */ +static PyObject *__pyx_tp_new_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +/* #### Code section: late_includes ### */ +/* #### Code section: module_state ### */ +/* SmallCodeConfig */ +#ifndef CYTHON_SMALL_CODE +#if defined(__clang__) + #define CYTHON_SMALL_CODE +#elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) + #define CYTHON_SMALL_CODE __attribute__((cold)) +#else + #define CYTHON_SMALL_CODE +#endif +#endif + +typedef struct { + PyObject *__pyx_d; + PyObject *__pyx_b; + PyObject *__pyx_cython_runtime; + PyObject *__pyx_empty_tuple; + PyObject *__pyx_empty_bytes; + PyObject *__pyx_empty_unicode; + PyTypeObject *__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer; + PyTypeObject *__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase; + PyObject *__pyx_type_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport; + PyTypeObject *__pyx_ptype_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport; + __Pyx_CachedCFunction __pyx_umethod_PyDict_Type_items; + __Pyx_CachedCFunction __pyx_umethod_PyDict_Type_pop; + __Pyx_CachedCFunction __pyx_umethod_PyDict_Type_values; + int __pyx_k_; + PyObject *__pyx_tuple[2]; + PyObject *__pyx_codeobj_tab[11]; + PyObject *__pyx_string_tab[94]; + PyObject *__pyx_number_tab[2]; +/* #### Code section: module_state_contents ### */ +/* CommonTypesMetaclass.module_state_decls */ +PyTypeObject *__pyx_CommonTypesMetaclassType; + +/* CachedMethodType.module_state_decls */ +#if CYTHON_COMPILING_IN_LIMITED_API +PyObject *__Pyx_CachedMethodType; +#endif + +/* CythonFunctionShared.module_state_decls */ +PyTypeObject *__pyx_CyFunctionType; + +/* CodeObjectCache.module_state_decls */ +struct __Pyx_CodeObjectCache __pyx_code_cache; + +/* #### Code section: module_state_end ### */ +} __pyx_mstatetype; + +#if CYTHON_USE_MODULE_STATE +#ifdef __cplusplus +namespace { +extern struct PyModuleDef __pyx_moduledef; +} /* anonymous namespace */ +#else +static struct PyModuleDef __pyx_moduledef; +#endif + +#define __pyx_mstate_global (__Pyx_PyModule_GetState(__Pyx_State_FindModule(&__pyx_moduledef))) + +#define __pyx_m (__Pyx_State_FindModule(&__pyx_moduledef)) +#else +static __pyx_mstatetype __pyx_mstate_global_static = +#ifdef __cplusplus + {}; +#else + {0}; +#endif +static __pyx_mstatetype * const __pyx_mstate_global = &__pyx_mstate_global_static; +#endif +/* #### Code section: constant_name_defines ### */ +#define __pyx_kp_u_End_of_file_reading_from_transpo __pyx_string_tab[0] +#define __pyx_kp_u_No_frame __pyx_string_tab[1] +#define __pyx_kp_u_Note_that_Cython_is_deliberately __pyx_string_tab[2] +#define __pyx_kp_u_Write_to_buffer_error __pyx_string_tab[3] +#define __pyx_kp_u__3 __pyx_string_tab[4] +#define __pyx_kp_u__4 __pyx_string_tab[5] +#define __pyx_kp_u_add_note __pyx_string_tab[6] +#define __pyx_kp_u_disable __pyx_string_tab[7] +#define __pyx_kp_u_enable __pyx_string_tab[8] +#define __pyx_kp_u_gc __pyx_string_tab[9] +#define __pyx_kp_u_grow_buffer_fail __pyx_string_tab[10] +#define __pyx_kp_u_isenabled __pyx_string_tab[11] +#define __pyx_kp_u_stringsource __pyx_string_tab[12] +#define __pyx_kp_u_thriftpy2_transport __pyx_string_tab[13] +#define __pyx_kp_u_thriftpy2_transport_framed_cyfra_2 __pyx_string_tab[14] +#define __pyx_n_u_END_OF_FILE __pyx_string_tab[15] +#define __pyx_n_u_Pyx_PyDict_NextRef __pyx_string_tab[16] +#define __pyx_n_u_TCyFramedTransport __pyx_string_tab[17] +#define __pyx_n_u_TCyFramedTransportFactory __pyx_string_tab[18] +#define __pyx_n_u_TCyFramedTransportFactory_get_tr __pyx_string_tab[19] +#define __pyx_n_u_TCyFramedTransport___reduce_cyth __pyx_string_tab[20] +#define __pyx_n_u_TCyFramedTransport___setstate_cy __pyx_string_tab[21] +#define __pyx_n_u_TCyFramedTransport_clean __pyx_string_tab[22] +#define __pyx_n_u_TCyFramedTransport_close __pyx_string_tab[23] +#define __pyx_n_u_TCyFramedTransport_flush __pyx_string_tab[24] +#define __pyx_n_u_TCyFramedTransport_is_open __pyx_string_tab[25] +#define __pyx_n_u_TCyFramedTransport_open __pyx_string_tab[26] +#define __pyx_n_u_TCyFramedTransport_read __pyx_string_tab[27] +#define __pyx_n_u_TCyFramedTransport_write __pyx_string_tab[28] +#define __pyx_n_u_TTransportException __pyx_string_tab[29] +#define __pyx_n_u_UNKNOWN __pyx_string_tab[30] +#define __pyx_n_u__2 __pyx_string_tab[31] +#define __pyx_n_u_asyncio_coroutines __pyx_string_tab[32] +#define __pyx_n_u_buf_size __pyx_string_tab[33] +#define __pyx_n_u_clean __pyx_string_tab[34] +#define __pyx_n_u_cline_in_traceback __pyx_string_tab[35] +#define __pyx_n_u_close __pyx_string_tab[36] +#define __pyx_n_u_data __pyx_string_tab[37] +#define __pyx_n_u_dict __pyx_string_tab[38] +#define __pyx_n_u_dict_2 __pyx_string_tab[39] +#define __pyx_n_u_doc __pyx_string_tab[40] +#define __pyx_n_u_flush __pyx_string_tab[41] +#define __pyx_n_u_func __pyx_string_tab[42] +#define __pyx_n_u_get_transport __pyx_string_tab[43] +#define __pyx_n_u_getstate __pyx_string_tab[44] +#define __pyx_n_u_is_coroutine __pyx_string_tab[45] +#define __pyx_n_u_is_open __pyx_string_tab[46] +#define __pyx_n_u_items __pyx_string_tab[47] +#define __pyx_n_u_main __pyx_string_tab[48] +#define __pyx_n_u_metaclass __pyx_string_tab[49] +#define __pyx_n_u_module __pyx_string_tab[50] +#define __pyx_n_u_mro_entries __pyx_string_tab[51] +#define __pyx_n_u_name __pyx_string_tab[52] +#define __pyx_n_u_new __pyx_string_tab[53] +#define __pyx_n_u_object __pyx_string_tab[54] +#define __pyx_n_u_open __pyx_string_tab[55] +#define __pyx_n_u_pop __pyx_string_tab[56] +#define __pyx_n_u_prepare __pyx_string_tab[57] +#define __pyx_n_u_pyx_checksum __pyx_string_tab[58] +#define __pyx_n_u_pyx_result __pyx_string_tab[59] +#define __pyx_n_u_pyx_state __pyx_string_tab[60] +#define __pyx_n_u_pyx_type __pyx_string_tab[61] +#define __pyx_n_u_pyx_unpickle_TCyFramedTranspor __pyx_string_tab[62] +#define __pyx_n_u_pyx_vtable __pyx_string_tab[63] +#define __pyx_n_u_qualname __pyx_string_tab[64] +#define __pyx_n_u_read __pyx_string_tab[65] +#define __pyx_n_u_reduce __pyx_string_tab[66] +#define __pyx_n_u_reduce_cython __pyx_string_tab[67] +#define __pyx_n_u_reduce_ex __pyx_string_tab[68] +#define __pyx_n_u_self __pyx_string_tab[69] +#define __pyx_n_u_set_name __pyx_string_tab[70] +#define __pyx_n_u_setdefault __pyx_string_tab[71] +#define __pyx_n_u_setstate __pyx_string_tab[72] +#define __pyx_n_u_setstate_cython __pyx_string_tab[73] +#define __pyx_n_u_state __pyx_string_tab[74] +#define __pyx_n_u_sz __pyx_string_tab[75] +#define __pyx_n_u_test __pyx_string_tab[76] +#define __pyx_n_u_thriftpy2_transport_framed_cyfra __pyx_string_tab[77] +#define __pyx_n_u_trans __pyx_string_tab[78] +#define __pyx_n_u_update __pyx_string_tab[79] +#define __pyx_n_u_use_setstate __pyx_string_tab[80] +#define __pyx_n_u_values __pyx_string_tab[81] +#define __pyx_n_u_write __pyx_string_tab[82] +#define __pyx_kp_b_iso88591_0_q __pyx_string_tab[83] +#define __pyx_kp_b_iso88591_A __pyx_string_tab[84] +#define __pyx_kp_b_iso88591_A_E_q_KvQ_KvQ __pyx_string_tab[85] +#define __pyx_kp_b_iso88591_A_HA __pyx_string_tab[86] +#define __pyx_kp_b_iso88591_A_c_HAV1 __pyx_string_tab[87] +#define __pyx_kp_b_iso88591_A_t6 __pyx_string_tab[88] +#define __pyx_kp_b_iso88591_A_t6_a __pyx_string_tab[89] +#define __pyx_kp_b_iso88591_A_t6_q __pyx_string_tab[90] +#define __pyx_kp_b_iso88591_A_t_aq __pyx_string_tab[91] +#define __pyx_kp_b_iso88591_T_M_XT_G1F_a_vWE_Q_q_t6_S_L_uCt __pyx_string_tab[92] +#define __pyx_kp_b_iso88591_q_0_kQR_XQa_7_4A5J_XY_1 __pyx_string_tab[93] +#define __pyx_int_0 __pyx_number_tab[0] +#define __pyx_int_151290000 __pyx_number_tab[1] +/* #### Code section: module_state_clear ### */ +#if CYTHON_USE_MODULE_STATE +static CYTHON_SMALL_CODE int __pyx_m_clear(PyObject *m) { + __pyx_mstatetype *clear_module_state = __Pyx_PyModule_GetState(m); + if (!clear_module_state) return 0; + Py_CLEAR(clear_module_state->__pyx_d); + Py_CLEAR(clear_module_state->__pyx_b); + Py_CLEAR(clear_module_state->__pyx_cython_runtime); + Py_CLEAR(clear_module_state->__pyx_empty_tuple); + Py_CLEAR(clear_module_state->__pyx_empty_bytes); + Py_CLEAR(clear_module_state->__pyx_empty_unicode); + #if CYTHON_PEP489_MULTI_PHASE_INIT + __Pyx_State_RemoveModule(NULL); + #endif + Py_CLEAR(clear_module_state->__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer); + Py_CLEAR(clear_module_state->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase); + Py_CLEAR(clear_module_state->__pyx_ptype_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport); + Py_CLEAR(clear_module_state->__pyx_type_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport); + for (int i=0; i<2; ++i) { Py_CLEAR(clear_module_state->__pyx_tuple[i]); } + for (int i=0; i<11; ++i) { Py_CLEAR(clear_module_state->__pyx_codeobj_tab[i]); } + for (int i=0; i<94; ++i) { Py_CLEAR(clear_module_state->__pyx_string_tab[i]); } + for (int i=0; i<2; ++i) { Py_CLEAR(clear_module_state->__pyx_number_tab[i]); } +/* #### Code section: module_state_clear_contents ### */ +/* CommonTypesMetaclass.module_state_clear */ +Py_CLEAR(clear_module_state->__pyx_CommonTypesMetaclassType); + +/* CythonFunctionShared.module_state_clear */ +Py_CLEAR(clear_module_state->__pyx_CyFunctionType); + +/* #### Code section: module_state_clear_end ### */ +return 0; +} +#endif +/* #### Code section: module_state_traverse ### */ +#if CYTHON_USE_MODULE_STATE +static CYTHON_SMALL_CODE int __pyx_m_traverse(PyObject *m, visitproc visit, void *arg) { + __pyx_mstatetype *traverse_module_state = __Pyx_PyModule_GetState(m); + if (!traverse_module_state) return 0; + Py_VISIT(traverse_module_state->__pyx_d); + Py_VISIT(traverse_module_state->__pyx_b); + Py_VISIT(traverse_module_state->__pyx_cython_runtime); + __Pyx_VISIT_CONST(traverse_module_state->__pyx_empty_tuple); + __Pyx_VISIT_CONST(traverse_module_state->__pyx_empty_bytes); + __Pyx_VISIT_CONST(traverse_module_state->__pyx_empty_unicode); + Py_VISIT(traverse_module_state->__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer); + Py_VISIT(traverse_module_state->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase); + Py_VISIT(traverse_module_state->__pyx_ptype_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport); + Py_VISIT(traverse_module_state->__pyx_type_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport); + for (int i=0; i<2; ++i) { __Pyx_VISIT_CONST(traverse_module_state->__pyx_tuple[i]); } + for (int i=0; i<11; ++i) { __Pyx_VISIT_CONST(traverse_module_state->__pyx_codeobj_tab[i]); } + for (int i=0; i<94; ++i) { __Pyx_VISIT_CONST(traverse_module_state->__pyx_string_tab[i]); } + for (int i=0; i<2; ++i) { __Pyx_VISIT_CONST(traverse_module_state->__pyx_number_tab[i]); } +/* #### Code section: module_state_traverse_contents ### */ +/* CommonTypesMetaclass.module_state_traverse */ +Py_VISIT(traverse_module_state->__pyx_CommonTypesMetaclassType); + +/* CythonFunctionShared.module_state_traverse */ +Py_VISIT(traverse_module_state->__pyx_CyFunctionType); + +/* #### Code section: module_state_traverse_end ### */ +return 0; +} +#endif +/* #### Code section: module_code ### */ + +/* "thriftpy2/transport/framed/cyframed.pyx":26 + * TCyBuffer rbuf, rframe_buf, wframe_buf + * + * def __init__(self, trans, int buf_size=DEFAULT_BUFFER): # <<<<<<<<<<<<<< + * self.trans = trans + * self.rbuf = TCyBuffer(buf_size) +*/ + +/* Python wrapper */ +static int __pyx_pw_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_trans = 0; + int __pyx_v_buf_size; + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[2] = {0,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return -1; + #endif + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_trans,&__pyx_mstate_global->__pyx_n_u_buf_size,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_VARARGS(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 26, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 2: + values[1] = __Pyx_ArgRef_VARARGS(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 26, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_VARARGS(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 26, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "__init__", 0) < (0)) __PYX_ERR(0, 26, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("__init__", 0, 1, 2, i); __PYX_ERR(0, 26, __pyx_L3_error) } + } + } else { + switch (__pyx_nargs) { + case 2: + values[1] = __Pyx_ArgRef_VARARGS(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 26, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_VARARGS(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 26, __pyx_L3_error) + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_trans = values[0]; + if (values[1]) { + __pyx_v_buf_size = __Pyx_PyLong_As_int(values[1]); if (unlikely((__pyx_v_buf_size == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 26, __pyx_L3_error) + } else { + __pyx_v_buf_size = __pyx_mstate_global->__pyx_k_; + } + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__init__", 0, 1, 2, __pyx_nargs); __PYX_ERR(0, 26, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("thriftpy2.transport.framed.cyframed.TCyFramedTransport.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport___init__(((struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *)__pyx_v_self), __pyx_v_trans, __pyx_v_buf_size); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport___init__(struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *__pyx_v_self, PyObject *__pyx_v_trans, int __pyx_v_buf_size) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + size_t __pyx_t_4; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__init__", 0); + + /* "thriftpy2/transport/framed/cyframed.pyx":27 + * + * def __init__(self, trans, int buf_size=DEFAULT_BUFFER): + * self.trans = trans # <<<<<<<<<<<<<< + * self.rbuf = TCyBuffer(buf_size) + * self.rframe_buf = TCyBuffer(buf_size) +*/ + __Pyx_INCREF(__pyx_v_trans); + __Pyx_GIVEREF(__pyx_v_trans); + __Pyx_GOTREF(__pyx_v_self->__pyx_base.trans); + __Pyx_DECREF(__pyx_v_self->__pyx_base.trans); + __pyx_v_self->__pyx_base.trans = __pyx_v_trans; + + /* "thriftpy2/transport/framed/cyframed.pyx":28 + * def __init__(self, trans, int buf_size=DEFAULT_BUFFER): + * self.trans = trans + * self.rbuf = TCyBuffer(buf_size) # <<<<<<<<<<<<<< + * self.rframe_buf = TCyBuffer(buf_size) + * self.wframe_buf = TCyBuffer(buf_size) +*/ + __pyx_t_2 = NULL; + __pyx_t_3 = __Pyx_PyLong_From_int(__pyx_v_buf_size); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 28, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, __pyx_t_3}; + __pyx_t_1 = __Pyx_PyObject_FastCall((PyObject*)__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer, __pyx_callargs+__pyx_t_4, (2-__pyx_t_4) | (__pyx_t_4*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 28, __pyx_L1_error) + __Pyx_GOTREF((PyObject *)__pyx_t_1); + } + __Pyx_GIVEREF((PyObject *)__pyx_t_1); + __Pyx_GOTREF((PyObject *)__pyx_v_self->rbuf); + __Pyx_DECREF((PyObject *)__pyx_v_self->rbuf); + __pyx_v_self->rbuf = ((struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "thriftpy2/transport/framed/cyframed.pyx":29 + * self.trans = trans + * self.rbuf = TCyBuffer(buf_size) + * self.rframe_buf = TCyBuffer(buf_size) # <<<<<<<<<<<<<< + * self.wframe_buf = TCyBuffer(buf_size) + * +*/ + __pyx_t_3 = NULL; + __pyx_t_2 = __Pyx_PyLong_From_int(__pyx_v_buf_size); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 29, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_t_2}; + __pyx_t_1 = __Pyx_PyObject_FastCall((PyObject*)__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer, __pyx_callargs+__pyx_t_4, (2-__pyx_t_4) | (__pyx_t_4*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 29, __pyx_L1_error) + __Pyx_GOTREF((PyObject *)__pyx_t_1); + } + __Pyx_GIVEREF((PyObject *)__pyx_t_1); + __Pyx_GOTREF((PyObject *)__pyx_v_self->rframe_buf); + __Pyx_DECREF((PyObject *)__pyx_v_self->rframe_buf); + __pyx_v_self->rframe_buf = ((struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "thriftpy2/transport/framed/cyframed.pyx":30 + * self.rbuf = TCyBuffer(buf_size) + * self.rframe_buf = TCyBuffer(buf_size) + * self.wframe_buf = TCyBuffer(buf_size) # <<<<<<<<<<<<<< + * + * cdef read_trans(self, int sz, char *out): +*/ + __pyx_t_2 = NULL; + __pyx_t_3 = __Pyx_PyLong_From_int(__pyx_v_buf_size); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 30, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, __pyx_t_3}; + __pyx_t_1 = __Pyx_PyObject_FastCall((PyObject*)__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer, __pyx_callargs+__pyx_t_4, (2-__pyx_t_4) | (__pyx_t_4*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 30, __pyx_L1_error) + __Pyx_GOTREF((PyObject *)__pyx_t_1); + } + __Pyx_GIVEREF((PyObject *)__pyx_t_1); + __Pyx_GOTREF((PyObject *)__pyx_v_self->wframe_buf); + __Pyx_DECREF((PyObject *)__pyx_v_self->wframe_buf); + __pyx_v_self->wframe_buf = ((struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "thriftpy2/transport/framed/cyframed.pyx":26 + * TCyBuffer rbuf, rframe_buf, wframe_buf + * + * def __init__(self, trans, int buf_size=DEFAULT_BUFFER): # <<<<<<<<<<<<<< + * self.trans = trans + * self.rbuf = TCyBuffer(buf_size) +*/ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("thriftpy2.transport.framed.cyframed.TCyFramedTransport.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/framed/cyframed.pyx":32 + * self.wframe_buf = TCyBuffer(buf_size) + * + * cdef read_trans(self, int sz, char *out): # <<<<<<<<<<<<<< + * cdef int i = self.rbuf.read_trans(self.trans, sz, out) + * if i == -1: +*/ + +static PyObject *__pyx_f_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_read_trans(struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *__pyx_v_self, int __pyx_v_sz, char *__pyx_v_out) { + int __pyx_v_i; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + size_t __pyx_t_7; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("read_trans", 0); + + /* "thriftpy2/transport/framed/cyframed.pyx":33 + * + * cdef read_trans(self, int sz, char *out): + * cdef int i = self.rbuf.read_trans(self.trans, sz, out) # <<<<<<<<<<<<<< + * if i == -1: + * raise TTransportException(TTransportException.END_OF_FILE, +*/ + __pyx_t_1 = __pyx_v_self->__pyx_base.trans; + __Pyx_INCREF(__pyx_t_1); + __pyx_t_2 = ((struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_TCyBuffer *)__pyx_v_self->rbuf->__pyx_vtab)->read_trans(__pyx_v_self->rbuf, __pyx_t_1, __pyx_v_sz, __pyx_v_out); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 33, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_3 = __Pyx_PyLong_As_int(__pyx_t_2); if (unlikely((__pyx_t_3 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 33, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_v_i = __pyx_t_3; + + /* "thriftpy2/transport/framed/cyframed.pyx":34 + * cdef read_trans(self, int sz, char *out): + * cdef int i = self.rbuf.read_trans(self.trans, sz, out) + * if i == -1: # <<<<<<<<<<<<<< + * raise TTransportException(TTransportException.END_OF_FILE, + * "End of file reading from transport") +*/ + switch (__pyx_v_i) { + case -1L: + + /* "thriftpy2/transport/framed/cyframed.pyx":35 + * cdef int i = self.rbuf.read_trans(self.trans, sz, out) + * if i == -1: + * raise TTransportException(TTransportException.END_OF_FILE, # <<<<<<<<<<<<<< + * "End of file reading from transport") + * elif i == -2: +*/ + __pyx_t_1 = NULL; + __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_mstate_global->__pyx_n_u_TTransportException); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 35, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_GetModuleGlobalName(__pyx_t_5, __pyx_mstate_global->__pyx_n_u_TTransportException); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 35, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_mstate_global->__pyx_n_u_END_OF_FILE); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 35, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_7 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_4))) { + __pyx_t_1 = PyMethod_GET_SELF(__pyx_t_4); + assert(__pyx_t_1); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_4); + __Pyx_INCREF(__pyx_t_1); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_4, __pyx__function); + __pyx_t_7 = 0; + } + #endif + { + PyObject *__pyx_callargs[3] = {__pyx_t_1, __pyx_t_6, __pyx_mstate_global->__pyx_kp_u_End_of_file_reading_from_transpo}; + __pyx_t_2 = __Pyx_PyObject_FastCall((PyObject*)__pyx_t_4, __pyx_callargs+__pyx_t_7, (3-__pyx_t_7) | (__pyx_t_7*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 35, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __PYX_ERR(0, 35, __pyx_L1_error) + + /* "thriftpy2/transport/framed/cyframed.pyx":34 + * cdef read_trans(self, int sz, char *out): + * cdef int i = self.rbuf.read_trans(self.trans, sz, out) + * if i == -1: # <<<<<<<<<<<<<< + * raise TTransportException(TTransportException.END_OF_FILE, + * "End of file reading from transport") +*/ + break; + case -2L: + + /* "thriftpy2/transport/framed/cyframed.pyx":38 + * "End of file reading from transport") + * elif i == -2: + * raise MemoryError("grow buffer fail") # <<<<<<<<<<<<<< + * + * cdef write_rframe_buffer(self, const char *data, int sz): +*/ + __pyx_t_4 = NULL; + __pyx_t_7 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_4, __pyx_mstate_global->__pyx_kp_u_grow_buffer_fail}; + __pyx_t_2 = __Pyx_PyObject_FastCall((PyObject*)(((PyTypeObject*)PyExc_MemoryError)), __pyx_callargs+__pyx_t_7, (2-__pyx_t_7) | (__pyx_t_7*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 38, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __PYX_ERR(0, 38, __pyx_L1_error) + + /* "thriftpy2/transport/framed/cyframed.pyx":37 + * raise TTransportException(TTransportException.END_OF_FILE, + * "End of file reading from transport") + * elif i == -2: # <<<<<<<<<<<<<< + * raise MemoryError("grow buffer fail") + * +*/ + break; + default: break; + } + + /* "thriftpy2/transport/framed/cyframed.pyx":32 + * self.wframe_buf = TCyBuffer(buf_size) + * + * cdef read_trans(self, int sz, char *out): # <<<<<<<<<<<<<< + * cdef int i = self.rbuf.read_trans(self.trans, sz, out) + * if i == -1: +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_AddTraceback("thriftpy2.transport.framed.cyframed.TCyFramedTransport.read_trans", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/framed/cyframed.pyx":40 + * raise MemoryError("grow buffer fail") + * + * cdef write_rframe_buffer(self, const char *data, int sz): # <<<<<<<<<<<<<< + * cdef int r = self.rframe_buf.write(sz, data) + * if r == -1: +*/ + +static PyObject *__pyx_f_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_write_rframe_buffer(struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *__pyx_v_self, char const *__pyx_v_data, int __pyx_v_sz) { + int __pyx_v_r; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + size_t __pyx_t_5; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("write_rframe_buffer", 0); + + /* "thriftpy2/transport/framed/cyframed.pyx":41 + * + * cdef write_rframe_buffer(self, const char *data, int sz): + * cdef int r = self.rframe_buf.write(sz, data) # <<<<<<<<<<<<<< + * if r == -1: + * raise MemoryError("Write to buffer error") +*/ + __pyx_t_1 = ((struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_TCyBuffer *)__pyx_v_self->rframe_buf->__pyx_vtab)->write(__pyx_v_self->rframe_buf, __pyx_v_sz, __pyx_v_data); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 41, __pyx_L1_error) + __pyx_v_r = __pyx_t_1; + + /* "thriftpy2/transport/framed/cyframed.pyx":42 + * cdef write_rframe_buffer(self, const char *data, int sz): + * cdef int r = self.rframe_buf.write(sz, data) + * if r == -1: # <<<<<<<<<<<<<< + * raise MemoryError("Write to buffer error") + * +*/ + __pyx_t_2 = (__pyx_v_r == -1L); + if (unlikely(__pyx_t_2)) { + + /* "thriftpy2/transport/framed/cyframed.pyx":43 + * cdef int r = self.rframe_buf.write(sz, data) + * if r == -1: + * raise MemoryError("Write to buffer error") # <<<<<<<<<<<<<< + * + * cdef c_read(self, int sz, char *out): +*/ + __pyx_t_4 = NULL; + __pyx_t_5 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_4, __pyx_mstate_global->__pyx_kp_u_Write_to_buffer_error}; + __pyx_t_3 = __Pyx_PyObject_FastCall((PyObject*)(((PyTypeObject*)PyExc_MemoryError)), __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 43, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + } + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __PYX_ERR(0, 43, __pyx_L1_error) + + /* "thriftpy2/transport/framed/cyframed.pyx":42 + * cdef write_rframe_buffer(self, const char *data, int sz): + * cdef int r = self.rframe_buf.write(sz, data) + * if r == -1: # <<<<<<<<<<<<<< + * raise MemoryError("Write to buffer error") + * +*/ + } + + /* "thriftpy2/transport/framed/cyframed.pyx":40 + * raise MemoryError("grow buffer fail") + * + * cdef write_rframe_buffer(self, const char *data, int sz): # <<<<<<<<<<<<<< + * cdef int r = self.rframe_buf.write(sz, data) + * if r == -1: +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("thriftpy2.transport.framed.cyframed.TCyFramedTransport.write_rframe_buffer", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/framed/cyframed.pyx":45 + * raise MemoryError("Write to buffer error") + * + * cdef c_read(self, int sz, char *out): # <<<<<<<<<<<<<< + * if sz <= 0: + * return 0 +*/ + +static PyObject *__pyx_f_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_c_read(struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *__pyx_v_self, int __pyx_v_sz, char *__pyx_v_out) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("c_read", 0); + + /* "thriftpy2/transport/framed/cyframed.pyx":46 + * + * cdef c_read(self, int sz, char *out): + * if sz <= 0: # <<<<<<<<<<<<<< + * return 0 + * +*/ + __pyx_t_1 = (__pyx_v_sz <= 0); + if (__pyx_t_1) { + + /* "thriftpy2/transport/framed/cyframed.pyx":47 + * cdef c_read(self, int sz, char *out): + * if sz <= 0: + * return 0 # <<<<<<<<<<<<<< + * + * while self.rframe_buf.data_size < sz: +*/ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_mstate_global->__pyx_int_0); + __pyx_r = __pyx_mstate_global->__pyx_int_0; + goto __pyx_L0; + + /* "thriftpy2/transport/framed/cyframed.pyx":46 + * + * cdef c_read(self, int sz, char *out): + * if sz <= 0: # <<<<<<<<<<<<<< + * return 0 + * +*/ + } + + /* "thriftpy2/transport/framed/cyframed.pyx":49 + * return 0 + * + * while self.rframe_buf.data_size < sz: # <<<<<<<<<<<<<< + * self.read_frame() + * +*/ + while (1) { + __pyx_t_1 = (__pyx_v_self->rframe_buf->data_size < __pyx_v_sz); + if (!__pyx_t_1) break; + + /* "thriftpy2/transport/framed/cyframed.pyx":50 + * + * while self.rframe_buf.data_size < sz: + * self.read_frame() # <<<<<<<<<<<<<< + * + * memcpy(out, self.rframe_buf.buf + self.rframe_buf.cur, sz) +*/ + __pyx_t_2 = ((struct __pyx_vtabstruct_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *)__pyx_v_self->__pyx_base.__pyx_vtab)->read_frame(__pyx_v_self); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 50, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } + + /* "thriftpy2/transport/framed/cyframed.pyx":52 + * self.read_frame() + * + * memcpy(out, self.rframe_buf.buf + self.rframe_buf.cur, sz) # <<<<<<<<<<<<<< + * self.rframe_buf.cur += sz + * self.rframe_buf.data_size -= sz +*/ + (void)(memcpy(__pyx_v_out, (__pyx_v_self->rframe_buf->buf + __pyx_v_self->rframe_buf->cur), __pyx_v_sz)); + + /* "thriftpy2/transport/framed/cyframed.pyx":53 + * + * memcpy(out, self.rframe_buf.buf + self.rframe_buf.cur, sz) + * self.rframe_buf.cur += sz # <<<<<<<<<<<<<< + * self.rframe_buf.data_size -= sz + * +*/ + __pyx_v_self->rframe_buf->cur = (__pyx_v_self->rframe_buf->cur + __pyx_v_sz); + + /* "thriftpy2/transport/framed/cyframed.pyx":54 + * memcpy(out, self.rframe_buf.buf + self.rframe_buf.cur, sz) + * self.rframe_buf.cur += sz + * self.rframe_buf.data_size -= sz # <<<<<<<<<<<<<< + * + * return sz +*/ + __pyx_v_self->rframe_buf->data_size = (__pyx_v_self->rframe_buf->data_size - __pyx_v_sz); + + /* "thriftpy2/transport/framed/cyframed.pyx":56 + * self.rframe_buf.data_size -= sz + * + * return sz # <<<<<<<<<<<<<< + * + * cdef c_write(self, const char *data, int sz): +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __Pyx_PyLong_From_int(__pyx_v_sz); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 56, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "thriftpy2/transport/framed/cyframed.pyx":45 + * raise MemoryError("Write to buffer error") + * + * cdef c_read(self, int sz, char *out): # <<<<<<<<<<<<<< + * if sz <= 0: + * return 0 +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("thriftpy2.transport.framed.cyframed.TCyFramedTransport.c_read", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/framed/cyframed.pyx":58 + * return sz + * + * cdef c_write(self, const char *data, int sz): # <<<<<<<<<<<<<< + * cdef int r = self.wframe_buf.write(sz, data) + * if r == -1: +*/ + +static PyObject *__pyx_f_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_c_write(struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *__pyx_v_self, char const *__pyx_v_data, int __pyx_v_sz) { + int __pyx_v_r; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + size_t __pyx_t_5; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("c_write", 0); + + /* "thriftpy2/transport/framed/cyframed.pyx":59 + * + * cdef c_write(self, const char *data, int sz): + * cdef int r = self.wframe_buf.write(sz, data) # <<<<<<<<<<<<<< + * if r == -1: + * raise MemoryError("Write to buffer error") +*/ + __pyx_t_1 = ((struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_TCyBuffer *)__pyx_v_self->wframe_buf->__pyx_vtab)->write(__pyx_v_self->wframe_buf, __pyx_v_sz, __pyx_v_data); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 59, __pyx_L1_error) + __pyx_v_r = __pyx_t_1; + + /* "thriftpy2/transport/framed/cyframed.pyx":60 + * cdef c_write(self, const char *data, int sz): + * cdef int r = self.wframe_buf.write(sz, data) + * if r == -1: # <<<<<<<<<<<<<< + * raise MemoryError("Write to buffer error") + * +*/ + __pyx_t_2 = (__pyx_v_r == -1L); + if (unlikely(__pyx_t_2)) { + + /* "thriftpy2/transport/framed/cyframed.pyx":61 + * cdef int r = self.wframe_buf.write(sz, data) + * if r == -1: + * raise MemoryError("Write to buffer error") # <<<<<<<<<<<<<< + * + * cdef read_frame(self): +*/ + __pyx_t_4 = NULL; + __pyx_t_5 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_4, __pyx_mstate_global->__pyx_kp_u_Write_to_buffer_error}; + __pyx_t_3 = __Pyx_PyObject_FastCall((PyObject*)(((PyTypeObject*)PyExc_MemoryError)), __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 61, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + } + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __PYX_ERR(0, 61, __pyx_L1_error) + + /* "thriftpy2/transport/framed/cyframed.pyx":60 + * cdef c_write(self, const char *data, int sz): + * cdef int r = self.wframe_buf.write(sz, data) + * if r == -1: # <<<<<<<<<<<<<< + * raise MemoryError("Write to buffer error") + * +*/ + } + + /* "thriftpy2/transport/framed/cyframed.pyx":58 + * return sz + * + * cdef c_write(self, const char *data, int sz): # <<<<<<<<<<<<<< + * cdef int r = self.wframe_buf.write(sz, data) + * if r == -1: +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("thriftpy2.transport.framed.cyframed.TCyFramedTransport.c_write", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/framed/cyframed.pyx":63 + * raise MemoryError("Write to buffer error") + * + * cdef read_frame(self): # <<<<<<<<<<<<<< + * cdef: + * char frame_len[4] +*/ + +static PyObject *__pyx_f_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_read_frame(struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *__pyx_v_self) { + char __pyx_v_frame_len[4]; + char __pyx_v_stack_frame[__pyx_e_9thriftpy2_9transport_6cybase_STACK_STRING_LEN]; + char *__pyx_v_dy_frame; + int32_t __pyx_v_frame_size; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + size_t __pyx_t_7; + int __pyx_t_8; + int __pyx_t_9; + char const *__pyx_t_10; + PyObject *__pyx_t_11 = NULL; + PyObject *__pyx_t_12 = NULL; + PyObject *__pyx_t_13 = NULL; + PyObject *__pyx_t_14 = NULL; + PyObject *__pyx_t_15 = NULL; + PyObject *__pyx_t_16 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("read_frame", 0); + + /* "thriftpy2/transport/framed/cyframed.pyx":70 + * int32_t frame_size + * + * self.read_trans(4, frame_len) # <<<<<<<<<<<<<< + * frame_size = be32toh((frame_len)[0]) + * +*/ + __pyx_t_1 = ((struct __pyx_vtabstruct_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *)__pyx_v_self->__pyx_base.__pyx_vtab)->read_trans(__pyx_v_self, 4, __pyx_v_frame_len); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 70, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "thriftpy2/transport/framed/cyframed.pyx":71 + * + * self.read_trans(4, frame_len) + * frame_size = be32toh((frame_len)[0]) # <<<<<<<<<<<<<< + * + * if frame_size <= 0: +*/ + __pyx_v_frame_size = be32toh((((int32_t *)__pyx_v_frame_len)[0])); + + /* "thriftpy2/transport/framed/cyframed.pyx":73 + * frame_size = be32toh((frame_len)[0]) + * + * if frame_size <= 0: # <<<<<<<<<<<<<< + * raise TTransportException("No frame.", TTransportException.UNKNOWN) + * +*/ + __pyx_t_2 = (__pyx_v_frame_size <= 0); + if (unlikely(__pyx_t_2)) { + + /* "thriftpy2/transport/framed/cyframed.pyx":74 + * + * if frame_size <= 0: + * raise TTransportException("No frame.", TTransportException.UNKNOWN) # <<<<<<<<<<<<<< + * + * if frame_size <= STACK_STRING_LEN: +*/ + __pyx_t_3 = NULL; + __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_mstate_global->__pyx_n_u_TTransportException); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 74, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_GetModuleGlobalName(__pyx_t_5, __pyx_mstate_global->__pyx_n_u_TTransportException); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 74, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_mstate_global->__pyx_n_u_UNKNOWN); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 74, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_7 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_4))) { + __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_4); + assert(__pyx_t_3); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_4); + __Pyx_INCREF(__pyx_t_3); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_4, __pyx__function); + __pyx_t_7 = 0; + } + #endif + { + PyObject *__pyx_callargs[3] = {__pyx_t_3, __pyx_mstate_global->__pyx_kp_u_No_frame, __pyx_t_6}; + __pyx_t_1 = __Pyx_PyObject_FastCall((PyObject*)__pyx_t_4, __pyx_callargs+__pyx_t_7, (3-__pyx_t_7) | (__pyx_t_7*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 74, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_ERR(0, 74, __pyx_L1_error) + + /* "thriftpy2/transport/framed/cyframed.pyx":73 + * frame_size = be32toh((frame_len)[0]) + * + * if frame_size <= 0: # <<<<<<<<<<<<<< + * raise TTransportException("No frame.", TTransportException.UNKNOWN) + * +*/ + } + + /* "thriftpy2/transport/framed/cyframed.pyx":76 + * raise TTransportException("No frame.", TTransportException.UNKNOWN) + * + * if frame_size <= STACK_STRING_LEN: # <<<<<<<<<<<<<< + * self.read_trans(frame_size, stack_frame) + * self.write_rframe_buffer(stack_frame, frame_size) +*/ + __pyx_t_2 = (__pyx_v_frame_size <= __pyx_e_9thriftpy2_9transport_6cybase_STACK_STRING_LEN); + if (__pyx_t_2) { + + /* "thriftpy2/transport/framed/cyframed.pyx":77 + * + * if frame_size <= STACK_STRING_LEN: + * self.read_trans(frame_size, stack_frame) # <<<<<<<<<<<<<< + * self.write_rframe_buffer(stack_frame, frame_size) + * else: +*/ + __pyx_t_1 = ((struct __pyx_vtabstruct_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *)__pyx_v_self->__pyx_base.__pyx_vtab)->read_trans(__pyx_v_self, __pyx_v_frame_size, __pyx_v_stack_frame); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 77, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "thriftpy2/transport/framed/cyframed.pyx":78 + * if frame_size <= STACK_STRING_LEN: + * self.read_trans(frame_size, stack_frame) + * self.write_rframe_buffer(stack_frame, frame_size) # <<<<<<<<<<<<<< + * else: + * dy_frame = malloc(frame_size) +*/ + __pyx_t_1 = ((struct __pyx_vtabstruct_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *)__pyx_v_self->__pyx_base.__pyx_vtab)->write_rframe_buffer(__pyx_v_self, __pyx_v_stack_frame, __pyx_v_frame_size); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 78, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "thriftpy2/transport/framed/cyframed.pyx":76 + * raise TTransportException("No frame.", TTransportException.UNKNOWN) + * + * if frame_size <= STACK_STRING_LEN: # <<<<<<<<<<<<<< + * self.read_trans(frame_size, stack_frame) + * self.write_rframe_buffer(stack_frame, frame_size) +*/ + goto __pyx_L4; + } + + /* "thriftpy2/transport/framed/cyframed.pyx":80 + * self.write_rframe_buffer(stack_frame, frame_size) + * else: + * dy_frame = malloc(frame_size) # <<<<<<<<<<<<<< + * try: + * self.read_trans(frame_size, dy_frame) +*/ + /*else*/ { + __pyx_v_dy_frame = ((char *)malloc(__pyx_v_frame_size)); + + /* "thriftpy2/transport/framed/cyframed.pyx":81 + * else: + * dy_frame = malloc(frame_size) + * try: # <<<<<<<<<<<<<< + * self.read_trans(frame_size, dy_frame) + * self.write_rframe_buffer(dy_frame, frame_size) +*/ + /*try:*/ { + + /* "thriftpy2/transport/framed/cyframed.pyx":82 + * dy_frame = malloc(frame_size) + * try: + * self.read_trans(frame_size, dy_frame) # <<<<<<<<<<<<<< + * self.write_rframe_buffer(dy_frame, frame_size) + * finally: +*/ + __pyx_t_1 = ((struct __pyx_vtabstruct_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *)__pyx_v_self->__pyx_base.__pyx_vtab)->read_trans(__pyx_v_self, __pyx_v_frame_size, __pyx_v_dy_frame); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 82, __pyx_L6_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "thriftpy2/transport/framed/cyframed.pyx":83 + * try: + * self.read_trans(frame_size, dy_frame) + * self.write_rframe_buffer(dy_frame, frame_size) # <<<<<<<<<<<<<< + * finally: + * free(dy_frame) +*/ + __pyx_t_1 = ((struct __pyx_vtabstruct_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *)__pyx_v_self->__pyx_base.__pyx_vtab)->write_rframe_buffer(__pyx_v_self, __pyx_v_dy_frame, __pyx_v_frame_size); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 83, __pyx_L6_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } + + /* "thriftpy2/transport/framed/cyframed.pyx":85 + * self.write_rframe_buffer(dy_frame, frame_size) + * finally: + * free(dy_frame) # <<<<<<<<<<<<<< + * + * cdef c_flush(self): +*/ + /*finally:*/ { + /*normal exit:*/{ + free(__pyx_v_dy_frame); + goto __pyx_L7; + } + __pyx_L6_error:; + /*exception exit:*/{ + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + __pyx_t_11 = 0; __pyx_t_12 = 0; __pyx_t_13 = 0; __pyx_t_14 = 0; __pyx_t_15 = 0; __pyx_t_16 = 0; + __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_ExceptionSwap(&__pyx_t_14, &__pyx_t_15, &__pyx_t_16); + if ( unlikely(__Pyx_GetException(&__pyx_t_11, &__pyx_t_12, &__pyx_t_13) < 0)) __Pyx_ErrFetch(&__pyx_t_11, &__pyx_t_12, &__pyx_t_13); + __Pyx_XGOTREF(__pyx_t_11); + __Pyx_XGOTREF(__pyx_t_12); + __Pyx_XGOTREF(__pyx_t_13); + __Pyx_XGOTREF(__pyx_t_14); + __Pyx_XGOTREF(__pyx_t_15); + __Pyx_XGOTREF(__pyx_t_16); + __pyx_t_8 = __pyx_lineno; __pyx_t_9 = __pyx_clineno; __pyx_t_10 = __pyx_filename; + { + free(__pyx_v_dy_frame); + } + __Pyx_XGIVEREF(__pyx_t_14); + __Pyx_XGIVEREF(__pyx_t_15); + __Pyx_XGIVEREF(__pyx_t_16); + __Pyx_ExceptionReset(__pyx_t_14, __pyx_t_15, __pyx_t_16); + __Pyx_XGIVEREF(__pyx_t_11); + __Pyx_XGIVEREF(__pyx_t_12); + __Pyx_XGIVEREF(__pyx_t_13); + __Pyx_ErrRestore(__pyx_t_11, __pyx_t_12, __pyx_t_13); + __pyx_t_11 = 0; __pyx_t_12 = 0; __pyx_t_13 = 0; __pyx_t_14 = 0; __pyx_t_15 = 0; __pyx_t_16 = 0; + __pyx_lineno = __pyx_t_8; __pyx_clineno = __pyx_t_9; __pyx_filename = __pyx_t_10; + goto __pyx_L1_error; + } + __pyx_L7:; + } + } + __pyx_L4:; + + /* "thriftpy2/transport/framed/cyframed.pyx":63 + * raise MemoryError("Write to buffer error") + * + * cdef read_frame(self): # <<<<<<<<<<<<<< + * cdef: + * char frame_len[4] +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_AddTraceback("thriftpy2.transport.framed.cyframed.TCyFramedTransport.read_frame", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/framed/cyframed.pyx":87 + * free(dy_frame) + * + * cdef c_flush(self): # <<<<<<<<<<<<<< + * cdef: + * bytes data +*/ + +static PyObject *__pyx_f_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_c_flush(struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *__pyx_v_self) { + PyObject *__pyx_v_data = 0; + char *__pyx_v_size_str; + int32_t __pyx_v_size; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + size_t __pyx_t_6; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("c_flush", 0); + + /* "thriftpy2/transport/framed/cyframed.pyx":92 + * char *size_str + * + * if self.wframe_buf.data_size > 0: # <<<<<<<<<<<<<< + * data = self.wframe_buf.buf[:self.wframe_buf.data_size] + * size = htobe32(self.wframe_buf.data_size) +*/ + __pyx_t_1 = (__pyx_v_self->wframe_buf->data_size > 0); + if (__pyx_t_1) { + + /* "thriftpy2/transport/framed/cyframed.pyx":93 + * + * if self.wframe_buf.data_size > 0: + * data = self.wframe_buf.buf[:self.wframe_buf.data_size] # <<<<<<<<<<<<<< + * size = htobe32(self.wframe_buf.data_size) + * size_str = (&size) +*/ + __pyx_t_2 = __Pyx_PyBytes_FromStringAndSize(__pyx_v_self->wframe_buf->buf + 0, __pyx_v_self->wframe_buf->data_size - 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 93, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_v_data = ((PyObject*)__pyx_t_2); + __pyx_t_2 = 0; + + /* "thriftpy2/transport/framed/cyframed.pyx":94 + * if self.wframe_buf.data_size > 0: + * data = self.wframe_buf.buf[:self.wframe_buf.data_size] + * size = htobe32(self.wframe_buf.data_size) # <<<<<<<<<<<<<< + * size_str = (&size) + * +*/ + __pyx_v_size = htobe32(__pyx_v_self->wframe_buf->data_size); + + /* "thriftpy2/transport/framed/cyframed.pyx":95 + * data = self.wframe_buf.buf[:self.wframe_buf.data_size] + * size = htobe32(self.wframe_buf.data_size) + * size_str = (&size) # <<<<<<<<<<<<<< + * + * self.trans.write(size_str[:4] + data) +*/ + __pyx_v_size_str = ((char *)(&__pyx_v_size)); + + /* "thriftpy2/transport/framed/cyframed.pyx":97 + * size_str = (&size) + * + * self.trans.write(size_str[:4] + data) # <<<<<<<<<<<<<< + * self.trans.flush() + * self.wframe_buf.clean() +*/ + __pyx_t_3 = __pyx_v_self->__pyx_base.trans; + __Pyx_INCREF(__pyx_t_3); + __pyx_t_4 = __Pyx_PyBytes_FromStringAndSize(__pyx_v_size_str + 0, 4 - 0); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 97, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = PyNumber_Add(__pyx_t_4, __pyx_v_data); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 97, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_t_5}; + __pyx_t_2 = __Pyx_PyObject_FastCallMethod((PyObject*)__pyx_mstate_global->__pyx_n_u_write, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 97, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/transport/framed/cyframed.pyx":98 + * + * self.trans.write(size_str[:4] + data) + * self.trans.flush() # <<<<<<<<<<<<<< + * self.wframe_buf.clean() + * +*/ + __pyx_t_5 = __pyx_v_self->__pyx_base.trans; + __Pyx_INCREF(__pyx_t_5); + __pyx_t_6 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_5, NULL}; + __pyx_t_2 = __Pyx_PyObject_FastCallMethod((PyObject*)__pyx_mstate_global->__pyx_n_u_flush, __pyx_callargs+__pyx_t_6, (1-__pyx_t_6) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 98, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/transport/framed/cyframed.pyx":99 + * self.trans.write(size_str[:4] + data) + * self.trans.flush() + * self.wframe_buf.clean() # <<<<<<<<<<<<<< + * + * def read(self, int sz): +*/ + ((struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_TCyBuffer *)__pyx_v_self->wframe_buf->__pyx_vtab)->clean(__pyx_v_self->wframe_buf); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 99, __pyx_L1_error) + + /* "thriftpy2/transport/framed/cyframed.pyx":92 + * char *size_str + * + * if self.wframe_buf.data_size > 0: # <<<<<<<<<<<<<< + * data = self.wframe_buf.buf[:self.wframe_buf.data_size] + * size = htobe32(self.wframe_buf.data_size) +*/ + } + + /* "thriftpy2/transport/framed/cyframed.pyx":87 + * free(dy_frame) + * + * cdef c_flush(self): # <<<<<<<<<<<<<< + * cdef: + * bytes data +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("thriftpy2.transport.framed.cyframed.TCyFramedTransport.c_flush", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_data); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/framed/cyframed.pyx":101 + * self.wframe_buf.clean() + * + * def read(self, int sz): # <<<<<<<<<<<<<< + * return self.get_string(sz) + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_3read(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_3read = {"read", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_3read, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_3read(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + int __pyx_v_sz; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("read (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_sz,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 101, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 101, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "read", 0) < (0)) __PYX_ERR(0, 101, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("read", 1, 1, 1, i); __PYX_ERR(0, 101, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 101, __pyx_L3_error) + } + __pyx_v_sz = __Pyx_PyLong_As_int(values[0]); if (unlikely((__pyx_v_sz == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 101, __pyx_L3_error) + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("read", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 101, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("thriftpy2.transport.framed.cyframed.TCyFramedTransport.read", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_2read(((struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *)__pyx_v_self), __pyx_v_sz); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_2read(struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *__pyx_v_self, int __pyx_v_sz) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("read", 0); + + /* "thriftpy2/transport/framed/cyframed.pyx":102 + * + * def read(self, int sz): + * return self.get_string(sz) # <<<<<<<<<<<<<< + * + * def write(self, bytes data): +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = ((struct __pyx_vtabstruct_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *)__pyx_v_self->__pyx_base.__pyx_vtab)->__pyx_base.get_string(((struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *)__pyx_v_self), __pyx_v_sz); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 102, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "thriftpy2/transport/framed/cyframed.pyx":101 + * self.wframe_buf.clean() + * + * def read(self, int sz): # <<<<<<<<<<<<<< + * return self.get_string(sz) + * +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("thriftpy2.transport.framed.cyframed.TCyFramedTransport.read", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/framed/cyframed.pyx":104 + * return self.get_string(sz) + * + * def write(self, bytes data): # <<<<<<<<<<<<<< + * cdef int sz = len(data) + * self.c_write(data, sz) +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_5write(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_5write = {"write", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_5write, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_5write(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_data = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("write (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_data,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 104, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 104, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "write", 0) < (0)) __PYX_ERR(0, 104, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("write", 1, 1, 1, i); __PYX_ERR(0, 104, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 104, __pyx_L3_error) + } + __pyx_v_data = ((PyObject*)values[0]); + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("write", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 104, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("thriftpy2.transport.framed.cyframed.TCyFramedTransport.write", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_data), (&PyBytes_Type), 1, "data", 1))) __PYX_ERR(0, 104, __pyx_L1_error) + __pyx_r = __pyx_pf_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_4write(((struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *)__pyx_v_self), __pyx_v_data); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + goto __pyx_L7_cleaned_up; + __pyx_L0:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __pyx_L7_cleaned_up:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_4write(struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *__pyx_v_self, PyObject *__pyx_v_data) { + int __pyx_v_sz; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + char *__pyx_t_2; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("write", 0); + + /* "thriftpy2/transport/framed/cyframed.pyx":105 + * + * def write(self, bytes data): + * cdef int sz = len(data) # <<<<<<<<<<<<<< + * self.c_write(data, sz) + * +*/ + if (unlikely(__pyx_v_data == Py_None)) { + PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); + __PYX_ERR(0, 105, __pyx_L1_error) + } + __pyx_t_1 = __Pyx_PyBytes_GET_SIZE(__pyx_v_data); if (unlikely(__pyx_t_1 == ((Py_ssize_t)-1))) __PYX_ERR(0, 105, __pyx_L1_error) + __pyx_v_sz = __pyx_t_1; + + /* "thriftpy2/transport/framed/cyframed.pyx":106 + * def write(self, bytes data): + * cdef int sz = len(data) + * self.c_write(data, sz) # <<<<<<<<<<<<<< + * + * def flush(self): +*/ + if (unlikely(__pyx_v_data == Py_None)) { + PyErr_SetString(PyExc_TypeError, "expected bytes, NoneType found"); + __PYX_ERR(0, 106, __pyx_L1_error) + } + __pyx_t_2 = __Pyx_PyBytes_AsWritableString(__pyx_v_data); if (unlikely((!__pyx_t_2) && PyErr_Occurred())) __PYX_ERR(0, 106, __pyx_L1_error) + __pyx_t_3 = ((struct __pyx_vtabstruct_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *)__pyx_v_self->__pyx_base.__pyx_vtab)->__pyx_base.c_write(((struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *)__pyx_v_self), __pyx_t_2, __pyx_v_sz); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 106, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "thriftpy2/transport/framed/cyframed.pyx":104 + * return self.get_string(sz) + * + * def write(self, bytes data): # <<<<<<<<<<<<<< + * cdef int sz = len(data) + * self.c_write(data, sz) +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("thriftpy2.transport.framed.cyframed.TCyFramedTransport.write", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/framed/cyframed.pyx":108 + * self.c_write(data, sz) + * + * def flush(self): # <<<<<<<<<<<<<< + * self.c_flush() + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_7flush(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_7flush = {"flush", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_7flush, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_7flush(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("flush (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("flush", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("flush", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_6flush(((struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_6flush(struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("flush", 0); + + /* "thriftpy2/transport/framed/cyframed.pyx":109 + * + * def flush(self): + * self.c_flush() # <<<<<<<<<<<<<< + * + * def is_open(self): +*/ + __pyx_t_1 = ((struct __pyx_vtabstruct_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *)__pyx_v_self->__pyx_base.__pyx_vtab)->__pyx_base.c_flush(((struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *)__pyx_v_self)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 109, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "thriftpy2/transport/framed/cyframed.pyx":108 + * self.c_write(data, sz) + * + * def flush(self): # <<<<<<<<<<<<<< + * self.c_flush() + * +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("thriftpy2.transport.framed.cyframed.TCyFramedTransport.flush", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/framed/cyframed.pyx":111 + * self.c_flush() + * + * def is_open(self): # <<<<<<<<<<<<<< + * return self.trans.is_open() + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_9is_open(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_9is_open = {"is_open", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_9is_open, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_9is_open(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("is_open (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("is_open", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("is_open", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_8is_open(((struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_8is_open(struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + size_t __pyx_t_3; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("is_open", 0); + + /* "thriftpy2/transport/framed/cyframed.pyx":112 + * + * def is_open(self): + * return self.trans.is_open() # <<<<<<<<<<<<<< + * + * def open(self): +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __pyx_v_self->__pyx_base.trans; + __Pyx_INCREF(__pyx_t_2); + __pyx_t_3 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, NULL}; + __pyx_t_1 = __Pyx_PyObject_FastCallMethod((PyObject*)__pyx_mstate_global->__pyx_n_u_is_open, __pyx_callargs+__pyx_t_3, (1-__pyx_t_3) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 112, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "thriftpy2/transport/framed/cyframed.pyx":111 + * self.c_flush() + * + * def is_open(self): # <<<<<<<<<<<<<< + * return self.trans.is_open() + * +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("thriftpy2.transport.framed.cyframed.TCyFramedTransport.is_open", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/framed/cyframed.pyx":114 + * return self.trans.is_open() + * + * def open(self): # <<<<<<<<<<<<<< + * return self.trans.open() + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_11open(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_11open = {"open", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_11open, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_11open(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("open (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("open", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("open", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_10open(((struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_10open(struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + size_t __pyx_t_3; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("open", 0); + + /* "thriftpy2/transport/framed/cyframed.pyx":115 + * + * def open(self): + * return self.trans.open() # <<<<<<<<<<<<<< + * + * def close(self): +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __pyx_v_self->__pyx_base.trans; + __Pyx_INCREF(__pyx_t_2); + __pyx_t_3 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, NULL}; + __pyx_t_1 = __Pyx_PyObject_FastCallMethod((PyObject*)__pyx_mstate_global->__pyx_n_u_open, __pyx_callargs+__pyx_t_3, (1-__pyx_t_3) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 115, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "thriftpy2/transport/framed/cyframed.pyx":114 + * return self.trans.is_open() + * + * def open(self): # <<<<<<<<<<<<<< + * return self.trans.open() + * +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("thriftpy2.transport.framed.cyframed.TCyFramedTransport.open", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/framed/cyframed.pyx":117 + * return self.trans.open() + * + * def close(self): # <<<<<<<<<<<<<< + * return self.trans.close() + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_13close(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_13close = {"close", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_13close, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_13close(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("close (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("close", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("close", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_12close(((struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_12close(struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + size_t __pyx_t_3; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("close", 0); + + /* "thriftpy2/transport/framed/cyframed.pyx":118 + * + * def close(self): + * return self.trans.close() # <<<<<<<<<<<<<< + * + * def clean(self): +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __pyx_v_self->__pyx_base.trans; + __Pyx_INCREF(__pyx_t_2); + __pyx_t_3 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, NULL}; + __pyx_t_1 = __Pyx_PyObject_FastCallMethod((PyObject*)__pyx_mstate_global->__pyx_n_u_close, __pyx_callargs+__pyx_t_3, (1-__pyx_t_3) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 118, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "thriftpy2/transport/framed/cyframed.pyx":117 + * return self.trans.open() + * + * def close(self): # <<<<<<<<<<<<<< + * return self.trans.close() + * +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("thriftpy2.transport.framed.cyframed.TCyFramedTransport.close", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/framed/cyframed.pyx":120 + * return self.trans.close() + * + * def clean(self): # <<<<<<<<<<<<<< + * self.rbuf.clean() + * self.rframe_buf.clean() +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_15clean(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_15clean = {"clean", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_15clean, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_15clean(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("clean (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("clean", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("clean", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_14clean(((struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_14clean(struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("clean", 0); + + /* "thriftpy2/transport/framed/cyframed.pyx":121 + * + * def clean(self): + * self.rbuf.clean() # <<<<<<<<<<<<<< + * self.rframe_buf.clean() + * self.wframe_buf.clean() +*/ + ((struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_TCyBuffer *)__pyx_v_self->rbuf->__pyx_vtab)->clean(__pyx_v_self->rbuf); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 121, __pyx_L1_error) + + /* "thriftpy2/transport/framed/cyframed.pyx":122 + * def clean(self): + * self.rbuf.clean() + * self.rframe_buf.clean() # <<<<<<<<<<<<<< + * self.wframe_buf.clean() + * +*/ + ((struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_TCyBuffer *)__pyx_v_self->rframe_buf->__pyx_vtab)->clean(__pyx_v_self->rframe_buf); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 122, __pyx_L1_error) + + /* "thriftpy2/transport/framed/cyframed.pyx":123 + * self.rbuf.clean() + * self.rframe_buf.clean() + * self.wframe_buf.clean() # <<<<<<<<<<<<<< + * + * +*/ + ((struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_TCyBuffer *)__pyx_v_self->wframe_buf->__pyx_vtab)->clean(__pyx_v_self->wframe_buf); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 123, __pyx_L1_error) + + /* "thriftpy2/transport/framed/cyframed.pyx":120 + * return self.trans.close() + * + * def clean(self): # <<<<<<<<<<<<<< + * self.rbuf.clean() + * self.rframe_buf.clean() +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_AddTraceback("thriftpy2.transport.framed.cyframed.TCyFramedTransport.clean", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * cdef tuple state + * cdef object _dict +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_17__reduce_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_17__reduce_cython__ = {"__reduce_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_17__reduce_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_17__reduce_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("__reduce_cython__", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("__reduce_cython__", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_16__reduce_cython__(((struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_16__reduce_cython__(struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *__pyx_v_self) { + PyObject *__pyx_v_state = 0; + PyObject *__pyx_v__dict = 0; + int __pyx_v_use_setstate; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__reduce_cython__", 0); + + /* "(tree fragment)":5 + * cdef object _dict + * cdef bint use_setstate + * state = (self.rbuf, self.rframe_buf, self.trans, self.wframe_buf) # <<<<<<<<<<<<<< + * _dict = getattr(self, '__dict__', None) + * if _dict is not None and _dict: +*/ + __pyx_t_1 = PyTuple_New(4); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 5, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF((PyObject *)__pyx_v_self->rbuf); + __Pyx_GIVEREF((PyObject *)__pyx_v_self->rbuf); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_v_self->rbuf)) != (0)) __PYX_ERR(1, 5, __pyx_L1_error); + __Pyx_INCREF((PyObject *)__pyx_v_self->rframe_buf); + __Pyx_GIVEREF((PyObject *)__pyx_v_self->rframe_buf); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 1, ((PyObject *)__pyx_v_self->rframe_buf)) != (0)) __PYX_ERR(1, 5, __pyx_L1_error); + __Pyx_INCREF(__pyx_v_self->__pyx_base.trans); + __Pyx_GIVEREF(__pyx_v_self->__pyx_base.trans); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 2, __pyx_v_self->__pyx_base.trans) != (0)) __PYX_ERR(1, 5, __pyx_L1_error); + __Pyx_INCREF((PyObject *)__pyx_v_self->wframe_buf); + __Pyx_GIVEREF((PyObject *)__pyx_v_self->wframe_buf); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 3, ((PyObject *)__pyx_v_self->wframe_buf)) != (0)) __PYX_ERR(1, 5, __pyx_L1_error); + __pyx_v_state = ((PyObject*)__pyx_t_1); + __pyx_t_1 = 0; + + /* "(tree fragment)":6 + * cdef bint use_setstate + * state = (self.rbuf, self.rframe_buf, self.trans, self.wframe_buf) + * _dict = getattr(self, '__dict__', None) # <<<<<<<<<<<<<< + * if _dict is not None and _dict: + * state += (_dict,) +*/ + __pyx_t_1 = __Pyx_GetAttr3(((PyObject *)__pyx_v_self), __pyx_mstate_global->__pyx_n_u_dict, Py_None); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 6, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v__dict = __pyx_t_1; + __pyx_t_1 = 0; + + /* "(tree fragment)":7 + * state = (self.rbuf, self.rframe_buf, self.trans, self.wframe_buf) + * _dict = getattr(self, '__dict__', None) + * if _dict is not None and _dict: # <<<<<<<<<<<<<< + * state += (_dict,) + * use_setstate = True +*/ + __pyx_t_3 = (__pyx_v__dict != Py_None); + if (__pyx_t_3) { + } else { + __pyx_t_2 = __pyx_t_3; + goto __pyx_L4_bool_binop_done; + } + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_v__dict); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(1, 7, __pyx_L1_error) + __pyx_t_2 = __pyx_t_3; + __pyx_L4_bool_binop_done:; + if (__pyx_t_2) { + + /* "(tree fragment)":8 + * _dict = getattr(self, '__dict__', None) + * if _dict is not None and _dict: + * state += (_dict,) # <<<<<<<<<<<<<< + * use_setstate = True + * else: +*/ + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 8, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_v__dict); + __Pyx_GIVEREF(__pyx_v__dict); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v__dict) != (0)) __PYX_ERR(1, 8, __pyx_L1_error); + __pyx_t_4 = PyNumber_InPlaceAdd(__pyx_v_state, __pyx_t_1); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 8, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF_SET(__pyx_v_state, ((PyObject*)__pyx_t_4)); + __pyx_t_4 = 0; + + /* "(tree fragment)":9 + * if _dict is not None and _dict: + * state += (_dict,) + * use_setstate = True # <<<<<<<<<<<<<< + * else: + * use_setstate = self.rbuf is not None or self.rframe_buf is not None or self.trans is not None or self.wframe_buf is not None +*/ + __pyx_v_use_setstate = 1; + + /* "(tree fragment)":7 + * state = (self.rbuf, self.rframe_buf, self.trans, self.wframe_buf) + * _dict = getattr(self, '__dict__', None) + * if _dict is not None and _dict: # <<<<<<<<<<<<<< + * state += (_dict,) + * use_setstate = True +*/ + goto __pyx_L3; + } + + /* "(tree fragment)":11 + * use_setstate = True + * else: + * use_setstate = self.rbuf is not None or self.rframe_buf is not None or self.trans is not None or self.wframe_buf is not None # <<<<<<<<<<<<<< + * if use_setstate: + * return __pyx_unpickle_TCyFramedTransport, (type(self), 0x9048090, None), state +*/ + /*else*/ { + __pyx_t_3 = (((PyObject *)__pyx_v_self->rbuf) != Py_None); + if (!__pyx_t_3) { + } else { + __pyx_t_2 = __pyx_t_3; + goto __pyx_L6_bool_binop_done; + } + __pyx_t_3 = (((PyObject *)__pyx_v_self->rframe_buf) != Py_None); + if (!__pyx_t_3) { + } else { + __pyx_t_2 = __pyx_t_3; + goto __pyx_L6_bool_binop_done; + } + __pyx_t_3 = (__pyx_v_self->__pyx_base.trans != Py_None); + if (!__pyx_t_3) { + } else { + __pyx_t_2 = __pyx_t_3; + goto __pyx_L6_bool_binop_done; + } + __pyx_t_3 = (((PyObject *)__pyx_v_self->wframe_buf) != Py_None); + __pyx_t_2 = __pyx_t_3; + __pyx_L6_bool_binop_done:; + __pyx_v_use_setstate = __pyx_t_2; + } + __pyx_L3:; + + /* "(tree fragment)":12 + * else: + * use_setstate = self.rbuf is not None or self.rframe_buf is not None or self.trans is not None or self.wframe_buf is not None + * if use_setstate: # <<<<<<<<<<<<<< + * return __pyx_unpickle_TCyFramedTransport, (type(self), 0x9048090, None), state + * else: +*/ + if (__pyx_v_use_setstate) { + + /* "(tree fragment)":13 + * use_setstate = self.rbuf is not None or self.rframe_buf is not None or self.trans is not None or self.wframe_buf is not None + * if use_setstate: + * return __pyx_unpickle_TCyFramedTransport, (type(self), 0x9048090, None), state # <<<<<<<<<<<<<< + * else: + * return __pyx_unpickle_TCyFramedTransport, (type(self), 0x9048090, state) +*/ + __Pyx_XDECREF(__pyx_r); + __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_mstate_global->__pyx_n_u_pyx_unpickle_TCyFramedTranspor); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 13, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_1 = PyTuple_New(3); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 13, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); + __Pyx_GIVEREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))) != (0)) __PYX_ERR(1, 13, __pyx_L1_error); + __Pyx_INCREF(__pyx_mstate_global->__pyx_int_151290000); + __Pyx_GIVEREF(__pyx_mstate_global->__pyx_int_151290000); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_mstate_global->__pyx_int_151290000) != (0)) __PYX_ERR(1, 13, __pyx_L1_error); + __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(Py_None); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 2, Py_None) != (0)) __PYX_ERR(1, 13, __pyx_L1_error); + __pyx_t_5 = PyTuple_New(3); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 13, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_GIVEREF(__pyx_t_4); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4) != (0)) __PYX_ERR(1, 13, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_1); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_1) != (0)) __PYX_ERR(1, 13, __pyx_L1_error); + __Pyx_INCREF(__pyx_v_state); + __Pyx_GIVEREF(__pyx_v_state); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_5, 2, __pyx_v_state) != (0)) __PYX_ERR(1, 13, __pyx_L1_error); + __pyx_t_4 = 0; + __pyx_t_1 = 0; + __pyx_r = __pyx_t_5; + __pyx_t_5 = 0; + goto __pyx_L0; + + /* "(tree fragment)":12 + * else: + * use_setstate = self.rbuf is not None or self.rframe_buf is not None or self.trans is not None or self.wframe_buf is not None + * if use_setstate: # <<<<<<<<<<<<<< + * return __pyx_unpickle_TCyFramedTransport, (type(self), 0x9048090, None), state + * else: +*/ + } + + /* "(tree fragment)":15 + * return __pyx_unpickle_TCyFramedTransport, (type(self), 0x9048090, None), state + * else: + * return __pyx_unpickle_TCyFramedTransport, (type(self), 0x9048090, state) # <<<<<<<<<<<<<< + * def __setstate_cython__(self, __pyx_state): + * __pyx_unpickle_TCyFramedTransport__set_state(self, __pyx_state) +*/ + /*else*/ { + __Pyx_XDECREF(__pyx_r); + __Pyx_GetModuleGlobalName(__pyx_t_5, __pyx_mstate_global->__pyx_n_u_pyx_unpickle_TCyFramedTranspor); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 15, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_1 = PyTuple_New(3); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 15, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); + __Pyx_GIVEREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))) != (0)) __PYX_ERR(1, 15, __pyx_L1_error); + __Pyx_INCREF(__pyx_mstate_global->__pyx_int_151290000); + __Pyx_GIVEREF(__pyx_mstate_global->__pyx_int_151290000); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_mstate_global->__pyx_int_151290000) != (0)) __PYX_ERR(1, 15, __pyx_L1_error); + __Pyx_INCREF(__pyx_v_state); + __Pyx_GIVEREF(__pyx_v_state); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 2, __pyx_v_state) != (0)) __PYX_ERR(1, 15, __pyx_L1_error); + __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 15, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_GIVEREF(__pyx_t_5); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_5) != (0)) __PYX_ERR(1, 15, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_1); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_1) != (0)) __PYX_ERR(1, 15, __pyx_L1_error); + __pyx_t_5 = 0; + __pyx_t_1 = 0; + __pyx_r = __pyx_t_4; + __pyx_t_4 = 0; + goto __pyx_L0; + } + + /* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * cdef tuple state + * cdef object _dict +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("thriftpy2.transport.framed.cyframed.TCyFramedTransport.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_state); + __Pyx_XDECREF(__pyx_v__dict); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":16 + * else: + * return __pyx_unpickle_TCyFramedTransport, (type(self), 0x9048090, state) + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * __pyx_unpickle_TCyFramedTransport__set_state(self, __pyx_state) +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_19__setstate_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_19__setstate_cython__ = {"__setstate_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_19__setstate_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_19__setstate_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v___pyx_state = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_pyx_state,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(1, 16, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(1, 16, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "__setstate_cython__", 0) < (0)) __PYX_ERR(1, 16, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("__setstate_cython__", 1, 1, 1, i); __PYX_ERR(1, 16, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(1, 16, __pyx_L3_error) + } + __pyx_v___pyx_state = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__setstate_cython__", 1, 1, 1, __pyx_nargs); __PYX_ERR(1, 16, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("thriftpy2.transport.framed.cyframed.TCyFramedTransport.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_18__setstate_cython__(((struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *)__pyx_v_self), __pyx_v___pyx_state); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_18__setstate_cython__(struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *__pyx_v_self, PyObject *__pyx_v___pyx_state) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__setstate_cython__", 0); + + /* "(tree fragment)":17 + * return __pyx_unpickle_TCyFramedTransport, (type(self), 0x9048090, state) + * def __setstate_cython__(self, __pyx_state): + * __pyx_unpickle_TCyFramedTransport__set_state(self, __pyx_state) # <<<<<<<<<<<<<< +*/ + __pyx_t_1 = __pyx_v___pyx_state; + __Pyx_INCREF(__pyx_t_1); + if (!(likely(PyTuple_CheckExact(__pyx_t_1))||((__pyx_t_1) == Py_None) || __Pyx_RaiseUnexpectedTypeError("tuple", __pyx_t_1))) __PYX_ERR(1, 17, __pyx_L1_error) + if (unlikely(__pyx_t_1 == Py_None)) { + PyErr_SetString(PyExc_TypeError, "cannot pass None into a C function argument that is declared 'not None'"); + __PYX_ERR(1, 17, __pyx_L1_error) + } + __pyx_t_2 = __pyx_f_9thriftpy2_9transport_6framed_8cyframed___pyx_unpickle_TCyFramedTransport__set_state(__pyx_v_self, ((PyObject*)__pyx_t_1)); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 17, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "(tree fragment)":16 + * else: + * return __pyx_unpickle_TCyFramedTransport, (type(self), 0x9048090, state) + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * __pyx_unpickle_TCyFramedTransport__set_state(self, __pyx_state) +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("thriftpy2.transport.framed.cyframed.TCyFramedTransport.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/framed/cyframed.pyx":127 + * + * class TCyFramedTransportFactory(object): + * def get_transport(self, trans): # <<<<<<<<<<<<<< + * return TCyFramedTransport(trans) +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_9transport_6framed_8cyframed_25TCyFramedTransportFactory_1get_transport(PyObject *__pyx_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_9transport_6framed_8cyframed_25TCyFramedTransportFactory_1get_transport = {"get_transport", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_6framed_8cyframed_25TCyFramedTransportFactory_1get_transport, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_9transport_6framed_8cyframed_25TCyFramedTransportFactory_1get_transport(PyObject *__pyx_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + CYTHON_UNUSED PyObject *__pyx_v_self = 0; + PyObject *__pyx_v_trans = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[2] = {0,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("get_transport (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_self,&__pyx_mstate_global->__pyx_n_u_trans,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 127, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 2: + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 127, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 127, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "get_transport", 0) < (0)) __PYX_ERR(0, 127, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 2; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("get_transport", 1, 2, 2, i); __PYX_ERR(0, 127, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 2)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 127, __pyx_L3_error) + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 127, __pyx_L3_error) + } + __pyx_v_self = values[0]; + __pyx_v_trans = values[1]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("get_transport", 1, 2, 2, __pyx_nargs); __PYX_ERR(0, 127, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("thriftpy2.transport.framed.cyframed.TCyFramedTransportFactory.get_transport", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_9thriftpy2_9transport_6framed_8cyframed_25TCyFramedTransportFactory_get_transport(__pyx_self, __pyx_v_self, __pyx_v_trans); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_9transport_6framed_8cyframed_25TCyFramedTransportFactory_get_transport(CYTHON_UNUSED PyObject *__pyx_self, CYTHON_UNUSED PyObject *__pyx_v_self, PyObject *__pyx_v_trans) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + size_t __pyx_t_3; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("get_transport", 0); + + /* "thriftpy2/transport/framed/cyframed.pyx":128 + * class TCyFramedTransportFactory(object): + * def get_transport(self, trans): + * return TCyFramedTransport(trans) # <<<<<<<<<<<<<< +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = NULL; + __pyx_t_3 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, __pyx_v_trans}; + __pyx_t_1 = __Pyx_PyObject_FastCall((PyObject*)__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport, __pyx_callargs+__pyx_t_3, (2-__pyx_t_3) | (__pyx_t_3*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 128, __pyx_L1_error) + __Pyx_GOTREF((PyObject *)__pyx_t_1); + } + __pyx_r = ((PyObject *)__pyx_t_1); + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "thriftpy2/transport/framed/cyframed.pyx":127 + * + * class TCyFramedTransportFactory(object): + * def get_transport(self, trans): # <<<<<<<<<<<<<< + * return TCyFramedTransport(trans) +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("thriftpy2.transport.framed.cyframed.TCyFramedTransportFactory.get_transport", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":4 + * int __Pyx_CheckUnpickleChecksum(long, long, long, long, const char*) except -1 + * int __Pyx_UpdateUnpickledDict(object, object, Py_ssize_t) except -1 + * def __pyx_unpickle_TCyFramedTransport(__pyx_type, long __pyx_checksum, tuple __pyx_state): # <<<<<<<<<<<<<< + * cdef object __pyx_result + * __Pyx_CheckUnpickleChecksum(__pyx_checksum, 0x9048090, 0x0039e40, 0xc4868e4, b'rbuf, rframe_buf, trans, wframe_buf') +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_9transport_6framed_8cyframed_1__pyx_unpickle_TCyFramedTransport(PyObject *__pyx_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_9transport_6framed_8cyframed_1__pyx_unpickle_TCyFramedTransport = {"__pyx_unpickle_TCyFramedTransport", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_6framed_8cyframed_1__pyx_unpickle_TCyFramedTransport, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_9transport_6framed_8cyframed_1__pyx_unpickle_TCyFramedTransport(PyObject *__pyx_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v___pyx_type = 0; + long __pyx_v___pyx_checksum; + PyObject *__pyx_v___pyx_state = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[3] = {0,0,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__pyx_unpickle_TCyFramedTransport (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_pyx_type,&__pyx_mstate_global->__pyx_n_u_pyx_checksum,&__pyx_mstate_global->__pyx_n_u_pyx_state,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(1, 4, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 3: + values[2] = __Pyx_ArgRef_FASTCALL(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(1, 4, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 2: + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(1, 4, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(1, 4, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "__pyx_unpickle_TCyFramedTransport", 0) < (0)) __PYX_ERR(1, 4, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 3; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("__pyx_unpickle_TCyFramedTransport", 1, 3, 3, i); __PYX_ERR(1, 4, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 3)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(1, 4, __pyx_L3_error) + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(1, 4, __pyx_L3_error) + values[2] = __Pyx_ArgRef_FASTCALL(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(1, 4, __pyx_L3_error) + } + __pyx_v___pyx_type = values[0]; + __pyx_v___pyx_checksum = __Pyx_PyLong_As_long(values[1]); if (unlikely((__pyx_v___pyx_checksum == (long)-1) && PyErr_Occurred())) __PYX_ERR(1, 4, __pyx_L3_error) + __pyx_v___pyx_state = ((PyObject*)values[2]); + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__pyx_unpickle_TCyFramedTransport", 1, 3, 3, __pyx_nargs); __PYX_ERR(1, 4, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("thriftpy2.transport.framed.cyframed.__pyx_unpickle_TCyFramedTransport", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v___pyx_state), (&PyTuple_Type), 1, "__pyx_state", 1))) __PYX_ERR(1, 4, __pyx_L1_error) + __pyx_r = __pyx_pf_9thriftpy2_9transport_6framed_8cyframed___pyx_unpickle_TCyFramedTransport(__pyx_self, __pyx_v___pyx_type, __pyx_v___pyx_checksum, __pyx_v___pyx_state); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + goto __pyx_L7_cleaned_up; + __pyx_L0:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __pyx_L7_cleaned_up:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_9transport_6framed_8cyframed___pyx_unpickle_TCyFramedTransport(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v___pyx_type, long __pyx_v___pyx_checksum, PyObject *__pyx_v___pyx_state) { + PyObject *__pyx_v___pyx_result = 0; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + size_t __pyx_t_4; + int __pyx_t_5; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__pyx_unpickle_TCyFramedTransport", 0); + + /* "(tree fragment)":6 + * def __pyx_unpickle_TCyFramedTransport(__pyx_type, long __pyx_checksum, tuple __pyx_state): + * cdef object __pyx_result + * __Pyx_CheckUnpickleChecksum(__pyx_checksum, 0x9048090, 0x0039e40, 0xc4868e4, b'rbuf, rframe_buf, trans, wframe_buf') # <<<<<<<<<<<<<< + * __pyx_result = TCyFramedTransport.__new__(__pyx_type) + * if __pyx_state is not None: +*/ + __pyx_t_1 = __Pyx_CheckUnpickleChecksum(__pyx_v___pyx_checksum, 0x9048090, 0x0039e40, 0xc4868e4, __pyx_k_rbuf_rframe_buf_trans_wframe_buf); if (unlikely(__pyx_t_1 == ((int)-1))) __PYX_ERR(1, 6, __pyx_L1_error) + + /* "(tree fragment)":7 + * cdef object __pyx_result + * __Pyx_CheckUnpickleChecksum(__pyx_checksum, 0x9048090, 0x0039e40, 0xc4868e4, b'rbuf, rframe_buf, trans, wframe_buf') + * __pyx_result = TCyFramedTransport.__new__(__pyx_type) # <<<<<<<<<<<<<< + * if __pyx_state is not None: + * __pyx_unpickle_TCyFramedTransport__set_state( __pyx_result, __pyx_state) +*/ + __pyx_t_3 = ((PyObject *)__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport); + __Pyx_INCREF(__pyx_t_3); + __pyx_t_4 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_v___pyx_type}; + __pyx_t_2 = __Pyx_PyObject_FastCallMethod((PyObject*)__pyx_mstate_global->__pyx_n_u_new, __pyx_callargs+__pyx_t_4, (2-__pyx_t_4) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 7, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __pyx_v___pyx_result = __pyx_t_2; + __pyx_t_2 = 0; + + /* "(tree fragment)":8 + * __Pyx_CheckUnpickleChecksum(__pyx_checksum, 0x9048090, 0x0039e40, 0xc4868e4, b'rbuf, rframe_buf, trans, wframe_buf') + * __pyx_result = TCyFramedTransport.__new__(__pyx_type) + * if __pyx_state is not None: # <<<<<<<<<<<<<< + * __pyx_unpickle_TCyFramedTransport__set_state( __pyx_result, __pyx_state) + * return __pyx_result +*/ + __pyx_t_5 = (__pyx_v___pyx_state != ((PyObject*)Py_None)); + if (__pyx_t_5) { + + /* "(tree fragment)":9 + * __pyx_result = TCyFramedTransport.__new__(__pyx_type) + * if __pyx_state is not None: + * __pyx_unpickle_TCyFramedTransport__set_state( __pyx_result, __pyx_state) # <<<<<<<<<<<<<< + * return __pyx_result + * cdef __pyx_unpickle_TCyFramedTransport__set_state(TCyFramedTransport __pyx_result, __pyx_state: tuple): +*/ + if (unlikely(__pyx_v___pyx_state == Py_None)) { + PyErr_SetString(PyExc_TypeError, "cannot pass None into a C function argument that is declared 'not None'"); + __PYX_ERR(1, 9, __pyx_L1_error) + } + __pyx_t_2 = __pyx_f_9thriftpy2_9transport_6framed_8cyframed___pyx_unpickle_TCyFramedTransport__set_state(((struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *)__pyx_v___pyx_result), __pyx_v___pyx_state); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 9, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "(tree fragment)":8 + * __Pyx_CheckUnpickleChecksum(__pyx_checksum, 0x9048090, 0x0039e40, 0xc4868e4, b'rbuf, rframe_buf, trans, wframe_buf') + * __pyx_result = TCyFramedTransport.__new__(__pyx_type) + * if __pyx_state is not None: # <<<<<<<<<<<<<< + * __pyx_unpickle_TCyFramedTransport__set_state( __pyx_result, __pyx_state) + * return __pyx_result +*/ + } + + /* "(tree fragment)":10 + * if __pyx_state is not None: + * __pyx_unpickle_TCyFramedTransport__set_state( __pyx_result, __pyx_state) + * return __pyx_result # <<<<<<<<<<<<<< + * cdef __pyx_unpickle_TCyFramedTransport__set_state(TCyFramedTransport __pyx_result, __pyx_state: tuple): + * __pyx_result.rbuf = __pyx_state[0]; __pyx_result.rframe_buf = __pyx_state[1]; __pyx_result.trans = __pyx_state[2]; __pyx_result.wframe_buf = __pyx_state[3] +*/ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v___pyx_result); + __pyx_r = __pyx_v___pyx_result; + goto __pyx_L0; + + /* "(tree fragment)":4 + * int __Pyx_CheckUnpickleChecksum(long, long, long, long, const char*) except -1 + * int __Pyx_UpdateUnpickledDict(object, object, Py_ssize_t) except -1 + * def __pyx_unpickle_TCyFramedTransport(__pyx_type, long __pyx_checksum, tuple __pyx_state): # <<<<<<<<<<<<<< + * cdef object __pyx_result + * __Pyx_CheckUnpickleChecksum(__pyx_checksum, 0x9048090, 0x0039e40, 0xc4868e4, b'rbuf, rframe_buf, trans, wframe_buf') +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("thriftpy2.transport.framed.cyframed.__pyx_unpickle_TCyFramedTransport", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v___pyx_result); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":11 + * __pyx_unpickle_TCyFramedTransport__set_state( __pyx_result, __pyx_state) + * return __pyx_result + * cdef __pyx_unpickle_TCyFramedTransport__set_state(TCyFramedTransport __pyx_result, __pyx_state: tuple): # <<<<<<<<<<<<<< + * __pyx_result.rbuf = __pyx_state[0]; __pyx_result.rframe_buf = __pyx_state[1]; __pyx_result.trans = __pyx_state[2]; __pyx_result.wframe_buf = __pyx_state[3] + * __Pyx_UpdateUnpickledDict(__pyx_result, __pyx_state, 4) +*/ + +static PyObject *__pyx_f_9thriftpy2_9transport_6framed_8cyframed___pyx_unpickle_TCyFramedTransport__set_state(struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *__pyx_v___pyx_result, PyObject *__pyx_v___pyx_state) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__pyx_unpickle_TCyFramedTransport__set_state", 0); + + /* "(tree fragment)":12 + * return __pyx_result + * cdef __pyx_unpickle_TCyFramedTransport__set_state(TCyFramedTransport __pyx_result, __pyx_state: tuple): + * __pyx_result.rbuf = __pyx_state[0]; __pyx_result.rframe_buf = __pyx_state[1]; __pyx_result.trans = __pyx_state[2]; __pyx_result.wframe_buf = __pyx_state[3] # <<<<<<<<<<<<<< + * __Pyx_UpdateUnpickledDict(__pyx_result, __pyx_state, 4) +*/ + __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 0, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1, __Pyx_ReferenceSharing_FunctionArgument); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 12, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer))))) __PYX_ERR(1, 12, __pyx_L1_error) + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF((PyObject *)__pyx_v___pyx_result->rbuf); + __Pyx_DECREF((PyObject *)__pyx_v___pyx_result->rbuf); + __pyx_v___pyx_result->rbuf = ((struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *)__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 1, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1, __Pyx_ReferenceSharing_FunctionArgument); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 12, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer))))) __PYX_ERR(1, 12, __pyx_L1_error) + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF((PyObject *)__pyx_v___pyx_result->rframe_buf); + __Pyx_DECREF((PyObject *)__pyx_v___pyx_result->rframe_buf); + __pyx_v___pyx_result->rframe_buf = ((struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *)__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 2, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1, __Pyx_ReferenceSharing_FunctionArgument); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 12, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF(__pyx_v___pyx_result->__pyx_base.trans); + __Pyx_DECREF(__pyx_v___pyx_result->__pyx_base.trans); + __pyx_v___pyx_result->__pyx_base.trans = __pyx_t_1; + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 3, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1, __Pyx_ReferenceSharing_FunctionArgument); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 12, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer))))) __PYX_ERR(1, 12, __pyx_L1_error) + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF((PyObject *)__pyx_v___pyx_result->wframe_buf); + __Pyx_DECREF((PyObject *)__pyx_v___pyx_result->wframe_buf); + __pyx_v___pyx_result->wframe_buf = ((struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "(tree fragment)":13 + * cdef __pyx_unpickle_TCyFramedTransport__set_state(TCyFramedTransport __pyx_result, __pyx_state: tuple): + * __pyx_result.rbuf = __pyx_state[0]; __pyx_result.rframe_buf = __pyx_state[1]; __pyx_result.trans = __pyx_state[2]; __pyx_result.wframe_buf = __pyx_state[3] + * __Pyx_UpdateUnpickledDict(__pyx_result, __pyx_state, 4) # <<<<<<<<<<<<<< +*/ + __pyx_t_2 = __Pyx_UpdateUnpickledDict(((PyObject *)__pyx_v___pyx_result), __pyx_v___pyx_state, 4); if (unlikely(__pyx_t_2 == ((int)-1))) __PYX_ERR(1, 13, __pyx_L1_error) + + /* "(tree fragment)":11 + * __pyx_unpickle_TCyFramedTransport__set_state( __pyx_result, __pyx_state) + * return __pyx_result + * cdef __pyx_unpickle_TCyFramedTransport__set_state(TCyFramedTransport __pyx_result, __pyx_state: tuple): # <<<<<<<<<<<<<< + * __pyx_result.rbuf = __pyx_state[0]; __pyx_result.rframe_buf = __pyx_state[1]; __pyx_result.trans = __pyx_state[2]; __pyx_result.wframe_buf = __pyx_state[3] + * __Pyx_UpdateUnpickledDict(__pyx_result, __pyx_state, 4) +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("thriftpy2.transport.framed.cyframed.__pyx_unpickle_TCyFramedTransport__set_state", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} +/* #### Code section: module_exttypes ### */ +static struct __pyx_vtabstruct_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport __pyx_vtable_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport; + +static PyObject *__pyx_tp_new_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *p; + PyObject *o = __Pyx_PyType_GetSlot(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase, tp_new, newfunc)(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *)o); + p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_CyTransportBase*)__pyx_vtabptr_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport; + p->rbuf = ((struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *)Py_None); Py_INCREF(Py_None); + p->rframe_buf = ((struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *)Py_None); Py_INCREF(Py_None); + p->wframe_buf = ((struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *)Py_None); Py_INCREF(Py_None); + return o; +} + +static void __pyx_tp_dealloc_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport(PyObject *o) { + struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *p = (struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *)o; + #if CYTHON_USE_TP_FINALIZE + if (unlikely(__Pyx_PyObject_GetSlot(o, tp_finalize, destructor)) && !__Pyx_PyObject_GC_IsFinalized(o)) { + if (__Pyx_PyObject_GetSlot(o, tp_dealloc, destructor) == __pyx_tp_dealloc_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + } + #endif + PyObject_GC_UnTrack(o); + Py_CLEAR(p->rbuf); + Py_CLEAR(p->rframe_buf); + Py_CLEAR(p->wframe_buf); + if (PyType_IS_GC(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase)) PyObject_GC_Track(o); + #if !CYTHON_USE_MODULE_STATE + if (likely(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase)) __Pyx_PyType_GetSlot(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase, tp_dealloc, destructor)(o); else + #endif + __Pyx_call_next_tp_dealloc(o, __pyx_tp_dealloc_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport); +} + +static int __pyx_tp_traverse_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *p = (struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *)o; + #if !CYTHON_USE_MODULE_STATE + e = 0; + if (likely(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase)) { + traverseproc traverse = __Pyx_PyType_GetSlot(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase, tp_traverse, traverseproc); + if (traverse) { e = traverse(o, v, a); } + } else + #endif + { e = __Pyx_call_next_tp_traverse(o, v, a, __pyx_tp_traverse_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport); } + if (e) return e; + { + e = __Pyx_call_type_traverse(o, 0, v, a); + if (e) return e; + } + if (p->rbuf) { + e = (*v)(((PyObject *)p->rbuf), a); if (e) return e; + } + if (p->rframe_buf) { + e = (*v)(((PyObject *)p->rframe_buf), a); if (e) return e; + } + if (p->wframe_buf) { + e = (*v)(((PyObject *)p->wframe_buf), a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport(PyObject *o) { + PyObject* tmp; + struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *p = (struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *)o; + #if !CYTHON_USE_MODULE_STATE + if (likely(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase)) { + inquiry clear = __Pyx_PyType_GetSlot(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase, tp_clear, inquiry); + if (clear) clear(o); + } else + #endif + { __Pyx_call_next_tp_clear(o, __pyx_tp_clear_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport); } + tmp = ((PyObject*)p->rbuf); + p->rbuf = ((struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->rframe_buf); + p->rframe_buf = ((struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->wframe_buf); + p->wframe_buf = ((struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); + return 0; +} + +static PyMethodDef __pyx_methods_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport[] = { + {"read", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_3read, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, + {"write", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_5write, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, + {"flush", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_7flush, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, + {"is_open", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_9is_open, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, + {"open", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_11open, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, + {"close", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_13close, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, + {"clean", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_15clean, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, + {"__reduce_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_17__reduce_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, + {"__setstate_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_19__setstate_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, + {0, 0, 0, 0} +}; +#if CYTHON_USE_TYPE_SPECS +static PyType_Slot __pyx_type_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport_slots[] = { + {Py_tp_dealloc, (void *)__pyx_tp_dealloc_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport}, + {Py_tp_traverse, (void *)__pyx_tp_traverse_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport}, + {Py_tp_clear, (void *)__pyx_tp_clear_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport}, + {Py_tp_methods, (void *)__pyx_methods_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport}, + {Py_tp_init, (void *)__pyx_pw_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_1__init__}, + {Py_tp_new, (void *)__pyx_tp_new_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport}, + {0, 0}, +}; +static PyType_Spec __pyx_type_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport_spec = { + "thriftpy2.transport.framed.cyframed.TCyFramedTransport", + sizeof(struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport), + 0, + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, + __pyx_type_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport_slots, +}; +#else + +static PyTypeObject __pyx_type_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport = { + PyVarObject_HEAD_INIT(0, 0) + "thriftpy2.transport.framed.cyframed.""TCyFramedTransport", /*tp_name*/ + sizeof(struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport, /*tp_dealloc*/ + 0, /*tp_vectorcall_offset*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_as_async*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + 0, /*tp_doc*/ + __pyx_tp_traverse_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport, /*tp_traverse*/ + __pyx_tp_clear_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + #if !CYTHON_USE_TYPE_SPECS + 0, /*tp_dictoffset*/ + #endif + __pyx_pw_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_1__init__, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if CYTHON_USE_TP_FINALIZE + 0, /*tp_finalize*/ + #else + NULL, /*tp_finalize*/ + #endif + #if !CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800 + 0, /*tp_vectorcall*/ + #endif + #if __PYX_NEED_TP_PRINT_SLOT == 1 + 0, /*tp_print*/ + #endif + #if PY_VERSION_HEX >= 0x030C0000 + 0, /*tp_watched*/ + #endif + #if PY_VERSION_HEX >= 0x030d00A4 + 0, /*tp_versions_used*/ + #endif + #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX >= 0x03090000 && PY_VERSION_HEX < 0x030a0000 + 0, /*tp_pypy_flags*/ + #endif +}; +#endif + +static PyMethodDef __pyx_methods[] = { + {0, 0, 0, 0} +}; +/* #### Code section: initfunc_declarations ### */ +static CYTHON_SMALL_CODE int __Pyx_InitCachedBuiltins(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_InitCachedConstants(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_InitGlobals(void); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_InitConstants(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_global_init_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_variable_export_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_function_export_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_type_init_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_type_import_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_variable_import_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_function_import_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_CreateCodeObjects(__pyx_mstatetype *__pyx_mstate); /*proto*/ +/* #### Code section: init_module ### */ + +static int __Pyx_modinit_global_init_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_modinit_global_init_code", 0); + /*--- Global init code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_modinit_variable_export_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_modinit_variable_export_code", 0); + /*--- Variable export code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_modinit_function_export_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_modinit_function_export_code", 0); + /*--- Function export code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_modinit_type_init_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__Pyx_modinit_type_init_code", 0); + /*--- Type init code ---*/ + __pyx_t_1 = PyImport_ImportModule("thriftpy2.transport.cybase"); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase = __Pyx_ImportType_3_2_4(__pyx_t_1, "thriftpy2.transport.cybase", "CyTransportBase", + #if defined(PYPY_VERSION_NUM) && PYPY_VERSION_NUM < 0x050B0000 + sizeof(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase), __PYX_GET_STRUCT_ALIGNMENT_3_2_4(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase), + #elif CYTHON_COMPILING_IN_LIMITED_API + sizeof(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase), __PYX_GET_STRUCT_ALIGNMENT_3_2_4(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase), + #else + sizeof(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase), __PYX_GET_STRUCT_ALIGNMENT_3_2_4(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase), + #endif + __Pyx_ImportType_CheckSize_Warn_3_2_4); if (!__pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_vtabptr_9thriftpy2_9transport_6cybase_CyTransportBase = (struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_CyTransportBase*)__Pyx_GetVtable(__pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase); if (unlikely(!__pyx_vtabptr_9thriftpy2_9transport_6cybase_CyTransportBase)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_vtabptr_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport = &__pyx_vtable_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport; + __pyx_vtable_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport.__pyx_base = *__pyx_vtabptr_9thriftpy2_9transport_6cybase_CyTransportBase; + __pyx_vtable_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport.__pyx_base.c_read = (PyObject *(*)(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *, int, char *))__pyx_f_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_c_read; + __pyx_vtable_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport.__pyx_base.c_write = (PyObject *(*)(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *, char *, int))__pyx_f_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_c_write; + __pyx_vtable_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport.__pyx_base.c_flush = (PyObject *(*)(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *))__pyx_f_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_c_flush; + __pyx_vtable_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport.read_trans = (PyObject *(*)(struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *, int, char *))__pyx_f_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_read_trans; + __pyx_vtable_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport.write_rframe_buffer = (PyObject *(*)(struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *, char const *, int))__pyx_f_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_write_rframe_buffer; + __pyx_vtable_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport.read_frame = (PyObject *(*)(struct __pyx_obj_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport *))__pyx_f_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_read_frame; + #if CYTHON_USE_TYPE_SPECS + __pyx_t_2 = PyTuple_Pack(1, (PyObject *)__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 22, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport = (PyTypeObject *) __Pyx_PyType_FromModuleAndSpec(__pyx_m, &__pyx_type_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport_spec, __pyx_t_2); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport)) __PYX_ERR(0, 22, __pyx_L1_error) + if (__Pyx_fix_up_extension_type_from_spec(&__pyx_type_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport_spec, __pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport) < (0)) __PYX_ERR(0, 22, __pyx_L1_error) + #else + __pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport = &__pyx_type_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport; + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + __pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport->tp_base = __pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase; + #endif + #if !CYTHON_USE_TYPE_SPECS + if (__Pyx_PyType_Ready(__pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport) < (0)) __PYX_ERR(0, 22, __pyx_L1_error) + #endif + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount((PyObject*)__pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport); + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport->tp_dictoffset && __pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport->tp_getattro == PyObject_GenericGetAttr)) { + __pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport->tp_getattro = PyObject_GenericGetAttr; + } + #endif + if (__Pyx_SetVtable(__pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport, __pyx_vtabptr_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport) < (0)) __PYX_ERR(0, 22, __pyx_L1_error) + if (__Pyx_MergeVtables(__pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport) < (0)) __PYX_ERR(0, 22, __pyx_L1_error) + if (PyObject_SetAttr(__pyx_m, __pyx_mstate_global->__pyx_n_u_TCyFramedTransport, (PyObject *) __pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport) < (0)) __PYX_ERR(0, 22, __pyx_L1_error) + if (__Pyx_setup_reduce((PyObject *) __pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport) < (0)) __PYX_ERR(0, 22, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_RefNannyFinishContext(); + return 0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_RefNannyFinishContext(); + return -1; +} + +static int __Pyx_modinit_type_import_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__Pyx_modinit_type_import_code", 0); + /*--- Type import code ---*/ + __pyx_t_1 = PyImport_ImportModule("thriftpy2.transport.cybase"); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 7, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer = __Pyx_ImportType_3_2_4(__pyx_t_1, "thriftpy2.transport.cybase", "TCyBuffer", + #if defined(PYPY_VERSION_NUM) && PYPY_VERSION_NUM < 0x050B0000 + sizeof(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer), __PYX_GET_STRUCT_ALIGNMENT_3_2_4(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer), + #elif CYTHON_COMPILING_IN_LIMITED_API + sizeof(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer), __PYX_GET_STRUCT_ALIGNMENT_3_2_4(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer), + #else + sizeof(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer), __PYX_GET_STRUCT_ALIGNMENT_3_2_4(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer), + #endif + __Pyx_ImportType_CheckSize_Warn_3_2_4); if (!__pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer) __PYX_ERR(2, 7, __pyx_L1_error) + __pyx_vtabptr_9thriftpy2_9transport_6cybase_TCyBuffer = (struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_TCyBuffer*)__Pyx_GetVtable(__pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer); if (unlikely(!__pyx_vtabptr_9thriftpy2_9transport_6cybase_TCyBuffer)) __PYX_ERR(2, 7, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_RefNannyFinishContext(); + return 0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_RefNannyFinishContext(); + return -1; +} + +static int __Pyx_modinit_variable_import_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_modinit_variable_import_code", 0); + /*--- Variable import code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_modinit_function_import_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_modinit_function_import_code", 0); + /*--- Function import code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +#if CYTHON_PEP489_MULTI_PHASE_INIT +static PyObject* __pyx_pymod_create(PyObject *spec, PyModuleDef *def); /*proto*/ +static int __pyx_pymod_exec_cyframed(PyObject* module); /*proto*/ +static PyModuleDef_Slot __pyx_moduledef_slots[] = { + {Py_mod_create, (void*)__pyx_pymod_create}, + {Py_mod_exec, (void*)__pyx_pymod_exec_cyframed}, + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + {Py_mod_gil, __Pyx_FREETHREADING_COMPATIBLE}, + #endif + #if PY_VERSION_HEX >= 0x030C0000 && CYTHON_USE_MODULE_STATE + {Py_mod_multiple_interpreters, Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED}, + #endif + {0, NULL} +}; +#endif + +#ifdef __cplusplus +namespace { + struct PyModuleDef __pyx_moduledef = + #else + static struct PyModuleDef __pyx_moduledef = + #endif + { + PyModuleDef_HEAD_INIT, + "cyframed", + 0, /* m_doc */ + #if CYTHON_USE_MODULE_STATE + sizeof(__pyx_mstatetype), /* m_size */ + #else + (CYTHON_PEP489_MULTI_PHASE_INIT) ? 0 : -1, /* m_size */ + #endif + __pyx_methods /* m_methods */, + #if CYTHON_PEP489_MULTI_PHASE_INIT + __pyx_moduledef_slots, /* m_slots */ + #else + NULL, /* m_reload */ + #endif + #if CYTHON_USE_MODULE_STATE + __pyx_m_traverse, /* m_traverse */ + __pyx_m_clear, /* m_clear */ + NULL /* m_free */ + #else + NULL, /* m_traverse */ + NULL, /* m_clear */ + NULL /* m_free */ + #endif + }; + #ifdef __cplusplus +} /* anonymous namespace */ +#endif + +/* PyModInitFuncType */ +#ifndef CYTHON_NO_PYINIT_EXPORT + #define __Pyx_PyMODINIT_FUNC PyMODINIT_FUNC +#else + #ifdef __cplusplus + #define __Pyx_PyMODINIT_FUNC extern "C" PyObject * + #else + #define __Pyx_PyMODINIT_FUNC PyObject * + #endif +#endif + +__Pyx_PyMODINIT_FUNC PyInit_cyframed(void) CYTHON_SMALL_CODE; /*proto*/ +__Pyx_PyMODINIT_FUNC PyInit_cyframed(void) +#if CYTHON_PEP489_MULTI_PHASE_INIT +{ + return PyModuleDef_Init(&__pyx_moduledef); +} +/* ModuleCreationPEP489 */ +#if CYTHON_COMPILING_IN_LIMITED_API && (__PYX_LIMITED_VERSION_HEX < 0x03090000\ + || ((defined(_WIN32) || defined(WIN32) || defined(MS_WINDOWS)) && __PYX_LIMITED_VERSION_HEX < 0x030A0000)) +static PY_INT64_T __Pyx_GetCurrentInterpreterId(void) { + { + PyObject *module = PyImport_ImportModule("_interpreters"); // 3.13+ I think + if (!module) { + PyErr_Clear(); // just try the 3.8-3.12 version + module = PyImport_ImportModule("_xxsubinterpreters"); + if (!module) goto bad; + } + PyObject *current = PyObject_CallMethod(module, "get_current", NULL); + Py_DECREF(module); + if (!current) goto bad; + if (PyTuple_Check(current)) { + PyObject *new_current = PySequence_GetItem(current, 0); + Py_DECREF(current); + current = new_current; + if (!new_current) goto bad; + } + long long as_c_int = PyLong_AsLongLong(current); + Py_DECREF(current); + return as_c_int; + } + bad: + PySys_WriteStderr("__Pyx_GetCurrentInterpreterId failed. Try setting the C define CYTHON_PEP489_MULTI_PHASE_INIT=0\n"); + return -1; +} +#endif +#if !CYTHON_USE_MODULE_STATE +static CYTHON_SMALL_CODE int __Pyx_check_single_interpreter(void) { + static PY_INT64_T main_interpreter_id = -1; +#if CYTHON_COMPILING_IN_GRAAL && defined(GRAALPY_VERSION_NUM) && GRAALPY_VERSION_NUM > 0x19000000 + PY_INT64_T current_id = GraalPyInterpreterState_GetIDFromThreadState(PyThreadState_Get()); +#elif CYTHON_COMPILING_IN_GRAAL + PY_INT64_T current_id = PyInterpreterState_GetIDFromThreadState(PyThreadState_Get()); +#elif CYTHON_COMPILING_IN_LIMITED_API && (__PYX_LIMITED_VERSION_HEX < 0x03090000\ + || ((defined(_WIN32) || defined(WIN32) || defined(MS_WINDOWS)) && __PYX_LIMITED_VERSION_HEX < 0x030A0000)) + PY_INT64_T current_id = __Pyx_GetCurrentInterpreterId(); +#elif CYTHON_COMPILING_IN_LIMITED_API + PY_INT64_T current_id = PyInterpreterState_GetID(PyInterpreterState_Get()); +#else + PY_INT64_T current_id = PyInterpreterState_GetID(PyThreadState_Get()->interp); +#endif + if (unlikely(current_id == -1)) { + return -1; + } + if (main_interpreter_id == -1) { + main_interpreter_id = current_id; + return 0; + } else if (unlikely(main_interpreter_id != current_id)) { + PyErr_SetString( + PyExc_ImportError, + "Interpreter change detected - this module can only be loaded into one interpreter per process."); + return -1; + } + return 0; +} +#endif +static CYTHON_SMALL_CODE int __Pyx_copy_spec_to_module(PyObject *spec, PyObject *moddict, const char* from_name, const char* to_name, int allow_none) +{ + PyObject *value = PyObject_GetAttrString(spec, from_name); + int result = 0; + if (likely(value)) { + if (allow_none || value != Py_None) { + result = PyDict_SetItemString(moddict, to_name, value); + } + Py_DECREF(value); + } else if (PyErr_ExceptionMatches(PyExc_AttributeError)) { + PyErr_Clear(); + } else { + result = -1; + } + return result; +} +static CYTHON_SMALL_CODE PyObject* __pyx_pymod_create(PyObject *spec, PyModuleDef *def) { + PyObject *module = NULL, *moddict, *modname; + CYTHON_UNUSED_VAR(def); + #if !CYTHON_USE_MODULE_STATE + if (__Pyx_check_single_interpreter()) + return NULL; + #endif + if (__pyx_m) + return __Pyx_NewRef(__pyx_m); + modname = PyObject_GetAttrString(spec, "name"); + if (unlikely(!modname)) goto bad; + module = PyModule_NewObject(modname); + Py_DECREF(modname); + if (unlikely(!module)) goto bad; + moddict = PyModule_GetDict(module); + if (unlikely(!moddict)) goto bad; + if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "loader", "__loader__", 1) < 0)) goto bad; + if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "origin", "__file__", 1) < 0)) goto bad; + if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "parent", "__package__", 1) < 0)) goto bad; + if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "submodule_search_locations", "__path__", 0) < 0)) goto bad; + return module; +bad: + Py_XDECREF(module); + return NULL; +} + + +static CYTHON_SMALL_CODE int __pyx_pymod_exec_cyframed(PyObject *__pyx_pyinit_module) +#endif +{ + int stringtab_initialized = 0; + #if CYTHON_USE_MODULE_STATE + int pystate_addmodule_run = 0; + #endif + __pyx_mstatetype *__pyx_mstate = NULL; + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + Py_ssize_t __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannyDeclarations + #if CYTHON_PEP489_MULTI_PHASE_INIT + if (__pyx_m) { + if (__pyx_m == __pyx_pyinit_module) return 0; + PyErr_SetString(PyExc_RuntimeError, "Module 'cyframed' has already been imported. Re-initialisation is not supported."); + return -1; + } + #else + if (__pyx_m) return __Pyx_NewRef(__pyx_m); + #endif + /*--- Module creation code ---*/ + #if CYTHON_PEP489_MULTI_PHASE_INIT + __pyx_t_1 = __pyx_pyinit_module; + Py_INCREF(__pyx_t_1); + #else + __pyx_t_1 = PyModule_Create(&__pyx_moduledef); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1, __pyx_L1_error) + #endif + #if CYTHON_USE_MODULE_STATE + { + int add_module_result = __Pyx_State_AddModule(__pyx_t_1, &__pyx_moduledef); + __pyx_t_1 = 0; /* transfer ownership from __pyx_t_1 to "cyframed" pseudovariable */ + if (unlikely((add_module_result < 0))) __PYX_ERR(0, 1, __pyx_L1_error) + pystate_addmodule_run = 1; + } + #else + __pyx_m = __pyx_t_1; + #endif + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + PyUnstable_Module_SetGIL(__pyx_m, Py_MOD_GIL_NOT_USED); + #endif + __pyx_mstate = __pyx_mstate_global; + CYTHON_UNUSED_VAR(__pyx_t_1); + __pyx_mstate->__pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_mstate->__pyx_d)) __PYX_ERR(0, 1, __pyx_L1_error) + Py_INCREF(__pyx_mstate->__pyx_d); + __pyx_mstate->__pyx_b = __Pyx_PyImport_AddModuleRef(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_mstate->__pyx_b)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_mstate->__pyx_cython_runtime = __Pyx_PyImport_AddModuleRef("cython_runtime"); if (unlikely(!__pyx_mstate->__pyx_cython_runtime)) __PYX_ERR(0, 1, __pyx_L1_error) + if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_mstate->__pyx_b) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + /* ImportRefnannyAPI */ + #if CYTHON_REFNANNY + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); + if (!__Pyx_RefNanny) { + PyErr_Clear(); + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); + if (!__Pyx_RefNanny) + Py_FatalError("failed to import 'refnanny' module"); + } + #endif + +__Pyx_RefNannySetupContext("PyInit_cyframed", 0); + __Pyx_init_runtime_version(); + if (__Pyx_check_binary_version(__PYX_LIMITED_VERSION_HEX, __Pyx_get_runtime_version(), CYTHON_COMPILING_IN_LIMITED_API) < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_mstate->__pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_mstate->__pyx_empty_tuple)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_mstate->__pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_mstate->__pyx_empty_bytes)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_mstate->__pyx_empty_unicode = PyUnicode_FromStringAndSize("", 0); if (unlikely(!__pyx_mstate->__pyx_empty_unicode)) __PYX_ERR(0, 1, __pyx_L1_error) + /*--- Library function declarations ---*/ + /*--- Initialize various global constants etc. ---*/ + if (__Pyx_InitConstants(__pyx_mstate) < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + stringtab_initialized = 1; + if (__Pyx_InitGlobals() < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + if (__pyx_module_is_main_thriftpy2__transport__framed__cyframed) { + if (PyObject_SetAttr(__pyx_m, __pyx_mstate_global->__pyx_n_u_name, __pyx_mstate_global->__pyx_n_u_main) < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + } + { + PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) __PYX_ERR(0, 1, __pyx_L1_error) + if (!PyDict_GetItemString(modules, "thriftpy2.transport.framed.cyframed")) { + if (unlikely((PyDict_SetItemString(modules, "thriftpy2.transport.framed.cyframed", __pyx_m) < 0))) __PYX_ERR(0, 1, __pyx_L1_error) + } + } + /*--- Builtin init code ---*/ + if (__Pyx_InitCachedBuiltins(__pyx_mstate) < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + /*--- Constants init code ---*/ + if (__Pyx_InitCachedConstants(__pyx_mstate) < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + if (__Pyx_CreateCodeObjects(__pyx_mstate) < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + /*--- Global type/function init code ---*/ + (void)__Pyx_modinit_global_init_code(__pyx_mstate); + (void)__Pyx_modinit_variable_export_code(__pyx_mstate); + (void)__Pyx_modinit_function_export_code(__pyx_mstate); + if (unlikely((__Pyx_modinit_type_init_code(__pyx_mstate) < 0))) __PYX_ERR(0, 1, __pyx_L1_error) + if (unlikely((__Pyx_modinit_type_import_code(__pyx_mstate) < 0))) __PYX_ERR(0, 1, __pyx_L1_error) + (void)__Pyx_modinit_variable_import_code(__pyx_mstate); + (void)__Pyx_modinit_function_import_code(__pyx_mstate); + /*--- Execution code ---*/ + + /* "thriftpy2/transport/framed/cyframed.pyx":14 + * ) + * + * from .. import TTransportException # <<<<<<<<<<<<<< + * + * +*/ + { + PyObject* const __pyx_imported_names[] = {__pyx_mstate_global->__pyx_n_u_TTransportException}; + __pyx_t_1 = __Pyx_Import(__pyx_mstate_global->__pyx_n_u__2, __pyx_imported_names, 1, __pyx_mstate_global->__pyx_kp_u_thriftpy2_transport, 2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 14, __pyx_L1_error) + } + __pyx_t_2 = __pyx_t_1; + __Pyx_GOTREF(__pyx_t_2); + { + PyObject* const __pyx_imported_names[] = {__pyx_mstate_global->__pyx_n_u_TTransportException}; + __pyx_t_3 = 0; { + __pyx_t_4 = __Pyx_ImportFrom(__pyx_t_2, __pyx_imported_names[__pyx_t_3]); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_imported_names[__pyx_t_3], __pyx_t_4) < (0)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + } + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/transport/framed/cyframed.pyx":26 + * TCyBuffer rbuf, rframe_buf, wframe_buf + * + * def __init__(self, trans, int buf_size=DEFAULT_BUFFER): # <<<<<<<<<<<<<< + * self.trans = trans + * self.rbuf = TCyBuffer(buf_size) +*/ + __pyx_mstate_global->__pyx_k_ = __pyx_e_9thriftpy2_9transport_6cybase_DEFAULT_BUFFER; + + /* "thriftpy2/transport/framed/cyframed.pyx":101 + * self.wframe_buf.clean() + * + * def read(self, int sz): # <<<<<<<<<<<<<< + * return self.get_string(sz) + * +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_3read, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_TCyFramedTransport_read, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_transport_framed_cyfra, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[0])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 101, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_2); + #endif + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport, __pyx_mstate_global->__pyx_n_u_read, __pyx_t_2) < (0)) __PYX_ERR(0, 101, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/transport/framed/cyframed.pyx":104 + * return self.get_string(sz) + * + * def write(self, bytes data): # <<<<<<<<<<<<<< + * cdef int sz = len(data) + * self.c_write(data, sz) +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_5write, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_TCyFramedTransport_write, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_transport_framed_cyfra, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[1])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 104, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_2); + #endif + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport, __pyx_mstate_global->__pyx_n_u_write, __pyx_t_2) < (0)) __PYX_ERR(0, 104, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/transport/framed/cyframed.pyx":108 + * self.c_write(data, sz) + * + * def flush(self): # <<<<<<<<<<<<<< + * self.c_flush() + * +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_7flush, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_TCyFramedTransport_flush, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_transport_framed_cyfra, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[2])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 108, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_2); + #endif + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport, __pyx_mstate_global->__pyx_n_u_flush, __pyx_t_2) < (0)) __PYX_ERR(0, 108, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/transport/framed/cyframed.pyx":111 + * self.c_flush() + * + * def is_open(self): # <<<<<<<<<<<<<< + * return self.trans.is_open() + * +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_9is_open, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_TCyFramedTransport_is_open, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_transport_framed_cyfra, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[3])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 111, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_2); + #endif + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport, __pyx_mstate_global->__pyx_n_u_is_open, __pyx_t_2) < (0)) __PYX_ERR(0, 111, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/transport/framed/cyframed.pyx":114 + * return self.trans.is_open() + * + * def open(self): # <<<<<<<<<<<<<< + * return self.trans.open() + * +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_11open, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_TCyFramedTransport_open, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_transport_framed_cyfra, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[4])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 114, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_2); + #endif + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport, __pyx_mstate_global->__pyx_n_u_open, __pyx_t_2) < (0)) __PYX_ERR(0, 114, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/transport/framed/cyframed.pyx":117 + * return self.trans.open() + * + * def close(self): # <<<<<<<<<<<<<< + * return self.trans.close() + * +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_13close, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_TCyFramedTransport_close, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_transport_framed_cyfra, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[5])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 117, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_2); + #endif + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport, __pyx_mstate_global->__pyx_n_u_close, __pyx_t_2) < (0)) __PYX_ERR(0, 117, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/transport/framed/cyframed.pyx":120 + * return self.trans.close() + * + * def clean(self): # <<<<<<<<<<<<<< + * self.rbuf.clean() + * self.rframe_buf.clean() +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_15clean, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_TCyFramedTransport_clean, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_transport_framed_cyfra, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[6])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 120, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_2); + #endif + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport, __pyx_mstate_global->__pyx_n_u_clean, __pyx_t_2) < (0)) __PYX_ERR(0, 120, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * cdef tuple state + * cdef object _dict +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_17__reduce_cython__, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_TCyFramedTransport___reduce_cyth, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_transport_framed_cyfra, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[7])); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 1, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_2); + #endif + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport, __pyx_mstate_global->__pyx_n_u_reduce_cython, __pyx_t_2) < (0)) __PYX_ERR(1, 1, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "(tree fragment)":16 + * else: + * return __pyx_unpickle_TCyFramedTransport, (type(self), 0x9048090, state) + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * __pyx_unpickle_TCyFramedTransport__set_state(self, __pyx_state) +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_9transport_6framed_8cyframed_18TCyFramedTransport_19__setstate_cython__, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_TCyFramedTransport___setstate_cy, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_transport_framed_cyfra, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[8])); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 16, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_2); + #endif + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6framed_8cyframed_TCyFramedTransport, __pyx_mstate_global->__pyx_n_u_setstate_cython, __pyx_t_2) < (0)) __PYX_ERR(1, 16, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/transport/framed/cyframed.pyx":126 + * + * + * class TCyFramedTransportFactory(object): # <<<<<<<<<<<<<< + * def get_transport(self, trans): + * return TCyFramedTransport(trans) +*/ + __pyx_t_2 = __Pyx_PEP560_update_bases(__pyx_mstate_global->__pyx_tuple[1]); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 126, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = __Pyx_CalculateMetaclass(NULL, __pyx_t_2); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 126, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = __Pyx_Py3MetaclassPrepare(__pyx_t_4, __pyx_t_2, __pyx_mstate_global->__pyx_n_u_TCyFramedTransportFactory, __pyx_mstate_global->__pyx_n_u_TCyFramedTransportFactory, (PyObject *) NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_transport_framed_cyfra, (PyObject *) NULL); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 126, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + if (__pyx_t_2 != __pyx_mstate_global->__pyx_tuple[1]) { + if (unlikely((PyDict_SetItemString(__pyx_t_5, "__orig_bases__", __pyx_mstate_global->__pyx_tuple[1]) < 0))) __PYX_ERR(0, 126, __pyx_L1_error) + } + + /* "thriftpy2/transport/framed/cyframed.pyx":127 + * + * class TCyFramedTransportFactory(object): + * def get_transport(self, trans): # <<<<<<<<<<<<<< + * return TCyFramedTransport(trans) +*/ + __pyx_t_6 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_9transport_6framed_8cyframed_25TCyFramedTransportFactory_1get_transport, 0, __pyx_mstate_global->__pyx_n_u_TCyFramedTransportFactory_get_tr, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_transport_framed_cyfra, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[9])); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 127, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_6); + #endif + if (__Pyx_SetNameInClass(__pyx_t_5, __pyx_mstate_global->__pyx_n_u_get_transport, __pyx_t_6) < (0)) __PYX_ERR(0, 127, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + + /* "thriftpy2/transport/framed/cyframed.pyx":126 + * + * + * class TCyFramedTransportFactory(object): # <<<<<<<<<<<<<< + * def get_transport(self, trans): + * return TCyFramedTransport(trans) +*/ + __pyx_t_6 = __Pyx_Py3ClassCreate(__pyx_t_4, __pyx_mstate_global->__pyx_n_u_TCyFramedTransportFactory, __pyx_t_2, __pyx_t_5, NULL, 0, 0); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 126, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_6); + #endif + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_TCyFramedTransportFactory, __pyx_t_6) < (0)) __PYX_ERR(0, 126, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "(tree fragment)":4 + * int __Pyx_CheckUnpickleChecksum(long, long, long, long, const char*) except -1 + * int __Pyx_UpdateUnpickledDict(object, object, Py_ssize_t) except -1 + * def __pyx_unpickle_TCyFramedTransport(__pyx_type, long __pyx_checksum, tuple __pyx_state): # <<<<<<<<<<<<<< + * cdef object __pyx_result + * __Pyx_CheckUnpickleChecksum(__pyx_checksum, 0x9048090, 0x0039e40, 0xc4868e4, b'rbuf, rframe_buf, trans, wframe_buf') +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_9transport_6framed_8cyframed_1__pyx_unpickle_TCyFramedTransport, 0, __pyx_mstate_global->__pyx_n_u_pyx_unpickle_TCyFramedTranspor, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_transport_framed_cyfra, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[10])); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 4, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_2); + #endif + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_pyx_unpickle_TCyFramedTranspor, __pyx_t_2) < (0)) __PYX_ERR(1, 4, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/transport/framed/cyframed.pyx":1 + * # cython: freethreading_compatible = True # <<<<<<<<<<<<<< + * + * from libc.stdlib cimport malloc, free +*/ + __pyx_t_2 = __Pyx_PyDict_NewPresized(0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_test, __pyx_t_2) < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /*--- Wrapped vars code ---*/ + + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + if (__pyx_m) { + if (__pyx_mstate->__pyx_d && stringtab_initialized) { + __Pyx_AddTraceback("init thriftpy2.transport.framed.cyframed", __pyx_clineno, __pyx_lineno, __pyx_filename); + } + #if !CYTHON_USE_MODULE_STATE + Py_CLEAR(__pyx_m); + #else + Py_DECREF(__pyx_m); + if (pystate_addmodule_run) { + PyObject *tp, *value, *tb; + PyErr_Fetch(&tp, &value, &tb); + PyState_RemoveModule(&__pyx_moduledef); + PyErr_Restore(tp, value, tb); + } + #endif + } else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_ImportError, "init thriftpy2.transport.framed.cyframed"); + } + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + #if CYTHON_PEP489_MULTI_PHASE_INIT + return (__pyx_m != NULL) ? 0 : -1; + #else + return __pyx_m; + #endif +} +/* #### Code section: pystring_table ### */ +/* #### Code section: cached_builtins ### */ + +static int __Pyx_InitCachedBuiltins(__pyx_mstatetype *__pyx_mstate) { + CYTHON_UNUSED_VAR(__pyx_mstate); + __pyx_builtin_object = __Pyx_GetBuiltinName(__pyx_mstate->__pyx_n_u_object); if (!__pyx_builtin_object) __PYX_ERR(0, 126, __pyx_L1_error) + + /* Cached unbound methods */ + __pyx_mstate->__pyx_umethod_PyDict_Type_items.type = (PyObject*)&PyDict_Type; + __pyx_mstate->__pyx_umethod_PyDict_Type_items.method_name = &__pyx_mstate->__pyx_n_u_items; + __pyx_mstate->__pyx_umethod_PyDict_Type_pop.type = (PyObject*)&PyDict_Type; + __pyx_mstate->__pyx_umethod_PyDict_Type_pop.method_name = &__pyx_mstate->__pyx_n_u_pop; + __pyx_mstate->__pyx_umethod_PyDict_Type_values.type = (PyObject*)&PyDict_Type; + __pyx_mstate->__pyx_umethod_PyDict_Type_values.method_name = &__pyx_mstate->__pyx_n_u_values; + return 0; + __pyx_L1_error:; + return -1; +} +/* #### Code section: cached_constants ### */ + +static int __Pyx_InitCachedConstants(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); + + /* "thriftpy2/transport/framed/cyframed.pyx":126 + * + * + * class TCyFramedTransportFactory(object): # <<<<<<<<<<<<<< + * def get_transport(self, trans): + * return TCyFramedTransport(trans) +*/ + __pyx_mstate_global->__pyx_tuple[0] = PyTuple_Pack(1, __pyx_builtin_object); if (unlikely(!__pyx_mstate_global->__pyx_tuple[0])) __PYX_ERR(0, 126, __pyx_L1_error) + __Pyx_GOTREF(__pyx_mstate_global->__pyx_tuple[0]); + __Pyx_GIVEREF(__pyx_mstate_global->__pyx_tuple[0]); + __pyx_mstate_global->__pyx_tuple[1] = PyTuple_Pack(1, __pyx_builtin_object); if (unlikely(!__pyx_mstate_global->__pyx_tuple[1])) __PYX_ERR(0, 126, __pyx_L1_error) + __Pyx_GOTREF(__pyx_mstate_global->__pyx_tuple[1]); + __Pyx_GIVEREF(__pyx_mstate_global->__pyx_tuple[1]); + #if CYTHON_IMMORTAL_CONSTANTS + { + PyObject **table = __pyx_mstate->__pyx_tuple; + for (Py_ssize_t i=0; i<2; ++i) { + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + #if PY_VERSION_HEX < 0x030E0000 + if (_Py_IsOwnedByCurrentThread(table[i]) && Py_REFCNT(table[i]) == 1) + #else + if (PyUnstable_Object_IsUniquelyReferenced(table[i])) + #endif + { + Py_SET_REFCNT(table[i], _Py_IMMORTAL_REFCNT_LOCAL); + } + #else + Py_SET_REFCNT(table[i], _Py_IMMORTAL_INITIAL_REFCNT); + #endif + } + } + #endif + __Pyx_RefNannyFinishContext(); + return 0; + __pyx_L1_error:; + __Pyx_RefNannyFinishContext(); + return -1; +} +/* #### Code section: init_constants ### */ + +static int __Pyx_InitConstants(__pyx_mstatetype *__pyx_mstate) { + CYTHON_UNUSED_VAR(__pyx_mstate); + { + const struct { const unsigned int length: 8; } index[] = {{34},{9},{179},{21},{1},{1},{8},{7},{6},{2},{16},{9},{14},{20},{39},{11},{20},{18},{25},{39},{36},{38},{24},{24},{24},{26},{23},{23},{24},{19},{7},{0},{18},{8},{5},{18},{5},{4},{8},{5},{7},{5},{8},{13},{12},{13},{7},{5},{8},{13},{10},{15},{8},{7},{6},{4},{3},{11},{14},{12},{11},{10},{33},{14},{12},{4},{10},{17},{13},{4},{12},{10},{12},{19},{5},{2},{8},{35},{5},{6},{12},{6},{5},{11},{12},{29},{9},{22},{13},{13},{13},{13},{156},{58}}; + #if (CYTHON_COMPRESS_STRINGS) == 2 /* compression: bz2 (1031 bytes) */ +const char* const cstring = "BZh91AY&SY\243\310\022\245\000\000u\177\377\366\315\277\300\342\207\377\315\277\377\377\360\277\377\377\374@@@@@@@@@@@@@\000@\000P\003^\264\334\243\233M5\3144\223\"h4\312142b\006F\021\243@\r\001\241\240\006\233S\324\310\315\021\262\023\020ji\244\0023\"M\246\223@\000\003A\240\000\000\000\000\000\000\000\324\364\231\004S\312m&\230S\365OS\3244\007\250\014#@h\0004\000\000\001\211\246F8h\006\200\003@h\r\000\000\000\323F\232\000\310\000\000h\323 \303\024M2T\364\330\020\247\352yPz2\203\324z\203\324\006CM\000\000\000\001\352\032\017Q\243\324\322\036\316\320!g\321\270y<\245\376\007J\321\034?\223\035\321\375\232\000\211\020\t:\0231\001N\222H\213\032\306~t(\234\003#\032ON\016\252\024e[\327(\\\334=\373.Qp\035;J\272\362\332pRO\013A\346\2414\206\375\234\203\372\205\365u\022\301eg\025\313\n\342\013\0026$FA$3\301>i:s\262,\303\322\312\025)\310\222$\274%M \332,B\2252\202\201\364\340\006\305\202\005\0175\230\230\2443SB4\032M @|@\223P\275\221Ud\n\360\243V\372j\323\013\306I\373\305\216%\007\324\214\025\262\020\203\246(\312\274\220\327\336\307\231\357q\003\202\200\301~M[/:l\323\375\033\236PF\376\217~\274F\224\010\325\2340\020t\224\220\020\304\376\231\373\030\212>=O\357M\246\t\305~\273U\226\276\343\341L\000\314v\252 \004\206\241\030\027\001\002\340\324=\356\234C\320\204\t\003\322\331\\\3611\3648i\271\327\206\355\024\224@\030$\034=\270\210#\000\3359\037~\202#LBl\203F,R\322?v\341\002\312\213of\304\010[\332\307\005\242\224\3062=\223r)\020\030D\037\222\260\031d\031\302\005\301\307\002Z\3747d\036\214\362\341w\025\261\306r`\342\027\260\\(\312\352\230=\344\234\330\305\321\013=\005\334\025P\350\227\007J\204\200\0246\335\324z\305b)\250-\010.F\276\010\226,\351\211a\252\023\337\243b\274F\220\222A\206\347\332\034\243\031\224 \210\330\014\035\305H\r5lH\344CV\013\020:\241*\243\014A\222\000\212\215\3551I\002I\362H\361\317|\303\257\275\002\202\230\344KS\316\205\223\253\212gg\037\n5kU\034A\030\303\035K\002pk \035[\250q\004uK\257\302'\304\326\2604\264\202P5\221\226\tr\314\357\221\"\351\255\351\315U\301""\300\347\013Ls\343\177\036`^\004\010\n\307\330\244\217\000p\0044T'\272\252\262\006\375\023U\034@'\244\360\010\272\373\206[\321\020\270\2431\\-\245\003\251%\240e \256i\rE$\212\t$\351\355\226Zk`\234\034\246\360\231\005Z\250\251\024\321\213\226$!\002\024\275I \211\325\000\232\215\310P\264\340Y\200\302\214+\226\000E\340.]\016A(n!\026'\261\351)\300\003*\030J\241)\234c\312\306\223K\025!\30412\0234\266\350\030H\213\357n\245\341l\233\311\n5\231 29\243\035\313\306V84\017@\016\026\265\355\331\212@\273\224\004}\206\312RUH \345?\0048\325\2105\351\326\032\201\3432\345\265\235\277\311\005\265\211+\326.\210\007\275\003\217\034*\354\212\245\317j\332\366\333\330p\255\\\231\370\004\324\337@#\322\371v9d6\001\274\302\366\303c\304\033EgJ-\372x\240\330\210.\376a\220\303\216i.\273\267\341\342j\362\3630\3303\177\302\354W\260\216'\211\223\247\213\231\351d\030\373\370\266K\003\371\276m\313\351n]^\256\266\302\217\377\037\353\222\261\227B\307\270\024G\205f\237\201w\205\334\221N\024$(\362\004\251@"; + PyObject *data = __Pyx_DecompressString(cstring, 1031, 2); + if (unlikely(!data)) __PYX_ERR(0, 1, __pyx_L1_error) + const char* const bytes = __Pyx_PyBytes_AsString(data); + #if !CYTHON_ASSUME_SAFE_MACROS + if (likely(bytes)); else { Py_DECREF(data); __PYX_ERR(0, 1, __pyx_L1_error) } + #endif + #elif (CYTHON_COMPRESS_STRINGS) != 0 /* compression: zlib (883 bytes) */ +const char* const cstring = "x\332}S\275o\0337\024\267\014\005\016\220\240\201\233\304\356\026z(\274\264\347\270u\322\002\t\032\250\216\324\246I\025;Qk7\013A\361\336I\214O\344\211\344\311:\267\203G\2157\336\250Q\343\215\036=z\274Q\243\377\204\374\t%\251\0177\260\\\001:\276\367{\217\357\213\277W\345>\022\001\nX\010H\002\361\031o\241@\212\016\322\222p\025\t\251\353\302\000\244\003^]h@\272M4\332Mt[p\304\024\362!dM\220DC\230 \245%\243\032\244u\342h\257\272\367\355\316\217;\210\230\014\022>\002\325\n\251\270IC\242\024(\233\264\031\263P3\216t\022\201\362\320\253\000%\"F\034\300GZ\240\310\370\375\367\202n\003G\n\264\025\320&\341\\h\242\231\340\330\\7Uo\"\237I\223\204\365\300\336\256\221P\201w \231vj3\016\002S\030H)\244\367\202\370>6\327\301g\2124C\000n\277-\332\222\342x\346\031\020\02625\261\370\317mg\274\245D,)\374\244\333\222\005:J\276\363\3463\362\346\330\326\034\333rS\363\267h2\021\274(\351W\353/\361\333\032\256\275zS\305x/\351\233\377K32\\\207\276~\007Ac7\2519\337\306,\310u\244F\250\0262\271\321\340\265@c}\363}\017c\t~L\001S\367\212\030/\3641\203Vf\276\377\353EC |!.\024,\300\2030V\355\0058SXD\260(\322\r\260%\352\002\370\330\276vc\256W\373\024\"\313\220?\352\257\353o\017\352D%\2342\341Q!Elx\007\312\2745V\354\004\\#44\020f\334\016\217B\223\320#\327\207O4\301\330\267\2574;|A1v\315\230#\346F\371l\346N\235\014\017c\323\333<\337\264OSdGa\334!&\227\371u@\023\307q\247\010?\016\301IR`\340\206w\340\014\334\264\352N8\306X4\355:\331X\221\2100\216$DD:\263\341\030\246m\240G*\356L4\t*\016\365D\236\026eE\273s\023)\346\021\243G&\351\365\211N\034z\332.\201\215\336\215I8)\304\276\300\234H\370\032\245\346\000\364-\225\302\300\021j\332\204\221|\010\210\253J]M\352:\345\234\246N06_\343\273h\357\246\2535\3331g\210#\363f\020+\230G\354\2210\006\345\350qZ\032\227\037\347\245|-\357\236V\306\267\357\025\3676\206\253\303\r+\337\035T\323\265\264k\205\327i/\333\237\013\023\343\257i\305\nk)\315V\263\215)\222\376\231m\2738\003\235>\315\276\032\256^)\0173r\245\254e\335\231\362,#F)}\272\275t\353\213A#]\317\312\331\357\243\007\243""\303\274q\266:.\337\035\374\222n\247\265\354\233!\031\227WN{\203\203\264\232=\260\305|\231\232\244\353i\367\322|t\366t\270>\2725z\237\227\3637\347+\347\361\305\356\205.\336\177(>\220\202\004E\300\n\326):\311\247\245\245\223Re\331\034\225\345\237\227m\274\256k\371\373|'\357\236\255\234\375}\261Y\354\277\273\374\034\3328-]\226\037e\335\002=\316\357\234=;?2.\343\362\375\342\376\327\303\303\321\376\310\225\365O\372\203\035\301N^)\236\374v\341\025\207\177\215\313w\006\333\377\002\361\202|\335"; + PyObject *data = __Pyx_DecompressString(cstring, 883, 1); + if (unlikely(!data)) __PYX_ERR(0, 1, __pyx_L1_error) + const char* const bytes = __Pyx_PyBytes_AsString(data); + #if !CYTHON_ASSUME_SAFE_MACROS + if (likely(bytes)); else { Py_DECREF(data); __PYX_ERR(0, 1, __pyx_L1_error) } + #endif + #else /* compression: none (1613 bytes) */ +const char* const bytes = "End of file reading from transportNo frame.Note that Cython is deliberately stricter than PEP-484 and rejects subclasses of builtin types. If you need to pass subclasses then set the 'annotation_typing' directive to False.Write to buffer error.?add_notedisableenablegcgrow buffer failisenabledthriftpy2.transport.thriftpy2/transport/framed/cyframed.pyxEND_OF_FILE__Pyx_PyDict_NextRefTCyFramedTransportTCyFramedTransportFactoryTCyFramedTransportFactory.get_transportTCyFramedTransport.__reduce_cython__TCyFramedTransport.__setstate_cython__TCyFramedTransport.cleanTCyFramedTransport.closeTCyFramedTransport.flushTCyFramedTransport.is_openTCyFramedTransport.openTCyFramedTransport.readTCyFramedTransport.writeTTransportExceptionUNKNOWNasyncio.coroutinesbuf_sizecleancline_in_tracebackclosedata__dict___dict__doc__flush__func__get_transport__getstate___is_coroutineis_openitems__main____metaclass____module____mro_entries____name____new__objectopenpop__prepare____pyx_checksum__pyx_result__pyx_state__pyx_type__pyx_unpickle_TCyFramedTransport__pyx_vtable____qualname__read__reduce____reduce_cython____reduce_ex__self__set_name__setdefault__setstate____setstate_cython__statesz__test__thriftpy2.transport.framed.cyframedtransupdateuse_setstatevalueswrite\200\001\330\0040\260\001\260\026\260q\200A\330\010\017\320\017!\240\021\240!\200A\330\010\014\210E\220\026\220q\330\010\014\210K\220v\230Q\330\010\014\210K\220v\230Q\200A\330\010\014\210H\220A\200A\330\010\026\220c\230\021\230!\330\010\014\210H\220A\220V\2301\200A\330\010\017\210t\2206\230\030\240\021\200A\330\010\017\210t\2206\230\025\230a\200A\330\010\017\210t\2206\230\026\230q\200A\330\010\017\210t\220;\230a\230q\200\001\360\010\000\005\016\210T\220\027\230\004\230M\250\024\250X\260T\270\021\330\004\014\210G\2201\220F\230,\240a\330\004\007\200v\210W\220E\230\024\230Q\330\010\022\220!\330\010\027\220q\340\010\027\220t\2306\240\027\250\005\250S\260\004\260L\300\007\300u\310C\310t\320SZ\320Za\320af\320fi\320im\320my\360\000""\000z\001A\002\360\000\000A\002B\002\330\004\007\200q\330\010\017\320\0173\2604\260q\270\007\270{\310'\320QR\340\010\017\320\0173\2604\260q\270\007\270{\310!\200\001\340\004\037\230q\320 0\260\013\270;\300k\320QR\330\004\023\320\023%\240X\250Q\250a\330\004\007\200|\2207\230!\330\0104\260A\3205J\310.\320XY\330\004\013\2101"; + PyObject *data = NULL; + CYTHON_UNUSED_VAR(__Pyx_DecompressString); + #endif + PyObject **stringtab = __pyx_mstate->__pyx_string_tab; + Py_ssize_t pos = 0; + for (int i = 0; i < 83; i++) { + Py_ssize_t bytes_length = index[i].length; + PyObject *string = PyUnicode_DecodeUTF8(bytes + pos, bytes_length, NULL); + if (likely(string) && i >= 15) PyUnicode_InternInPlace(&string); + if (unlikely(!string)) { + Py_XDECREF(data); + __PYX_ERR(0, 1, __pyx_L1_error) + } + stringtab[i] = string; + pos += bytes_length; + } + for (int i = 83; i < 94; i++) { + Py_ssize_t bytes_length = index[i].length; + PyObject *string = PyBytes_FromStringAndSize(bytes + pos, bytes_length); + stringtab[i] = string; + pos += bytes_length; + if (unlikely(!string)) { + Py_XDECREF(data); + __PYX_ERR(0, 1, __pyx_L1_error) + } + } + Py_XDECREF(data); + for (Py_ssize_t i = 0; i < 94; i++) { + if (unlikely(PyObject_Hash(stringtab[i]) == -1)) { + __PYX_ERR(0, 1, __pyx_L1_error) + } + } + #if CYTHON_IMMORTAL_CONSTANTS + { + PyObject **table = stringtab + 83; + for (Py_ssize_t i=0; i<11; ++i) { + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + #if PY_VERSION_HEX < 0x030E0000 + if (_Py_IsOwnedByCurrentThread(table[i]) && Py_REFCNT(table[i]) == 1) + #else + if (PyUnstable_Object_IsUniquelyReferenced(table[i])) + #endif + { + Py_SET_REFCNT(table[i], _Py_IMMORTAL_REFCNT_LOCAL); + } + #else + Py_SET_REFCNT(table[i], _Py_IMMORTAL_INITIAL_REFCNT); + #endif + } + } + #endif + } + { + PyObject **numbertab = __pyx_mstate->__pyx_number_tab + 0; + int8_t const cint_constants_1[] = {0}; + int32_t const cint_constants_4[] = {151290000L}; + for (int i = 0; i < 2; i++) { + numbertab[i] = PyLong_FromLong((i < 1 ? cint_constants_1[i - 0] : cint_constants_4[i - 1])); + if (unlikely(!numbertab[i])) __PYX_ERR(0, 1, __pyx_L1_error) + } + } + #if CYTHON_IMMORTAL_CONSTANTS + { + PyObject **table = __pyx_mstate->__pyx_number_tab; + for (Py_ssize_t i=0; i<2; ++i) { + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + #if PY_VERSION_HEX < 0x030E0000 + if (_Py_IsOwnedByCurrentThread(table[i]) && Py_REFCNT(table[i]) == 1) + #else + if (PyUnstable_Object_IsUniquelyReferenced(table[i])) + #endif + { + Py_SET_REFCNT(table[i], _Py_IMMORTAL_REFCNT_LOCAL); + } + #else + Py_SET_REFCNT(table[i], _Py_IMMORTAL_INITIAL_REFCNT); + #endif + } + } + #endif + return 0; + __pyx_L1_error:; + return -1; +} +/* #### Code section: init_codeobjects ### */ +typedef struct { + unsigned int argcount : 2; + unsigned int num_posonly_args : 1; + unsigned int num_kwonly_args : 1; + unsigned int nlocals : 3; + unsigned int flags : 10; + unsigned int first_line : 7; +} __Pyx_PyCode_New_function_description; +/* NewCodeObj.proto */ +static PyObject* __Pyx_PyCode_New( + const __Pyx_PyCode_New_function_description descr, + PyObject * const *varnames, + PyObject *filename, + PyObject *funcname, + PyObject *line_table, + PyObject *tuple_dedup_map +); + + +static int __Pyx_CreateCodeObjects(__pyx_mstatetype *__pyx_mstate) { + PyObject* tuple_dedup_map = PyDict_New(); + if (unlikely(!tuple_dedup_map)) return -1; + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 101}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_sz}; + __pyx_mstate_global->__pyx_codeobj_tab[0] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_thriftpy2_transport_framed_cyfra_2, __pyx_mstate->__pyx_n_u_read, __pyx_mstate->__pyx_kp_b_iso88591_A_t_aq, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[0])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 3, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 104}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_data, __pyx_mstate->__pyx_n_u_sz}; + __pyx_mstate_global->__pyx_codeobj_tab[1] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_thriftpy2_transport_framed_cyfra_2, __pyx_mstate->__pyx_n_u_write, __pyx_mstate->__pyx_kp_b_iso88591_A_c_HAV1, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[1])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 108}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[2] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_thriftpy2_transport_framed_cyfra_2, __pyx_mstate->__pyx_n_u_flush, __pyx_mstate->__pyx_kp_b_iso88591_A_HA, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[2])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 111}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[3] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_thriftpy2_transport_framed_cyfra_2, __pyx_mstate->__pyx_n_u_is_open, __pyx_mstate->__pyx_kp_b_iso88591_A_t6, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[3])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 114}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[4] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_thriftpy2_transport_framed_cyfra_2, __pyx_mstate->__pyx_n_u_open, __pyx_mstate->__pyx_kp_b_iso88591_A_t6_a, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[4])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 117}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[5] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_thriftpy2_transport_framed_cyfra_2, __pyx_mstate->__pyx_n_u_close, __pyx_mstate->__pyx_kp_b_iso88591_A_t6_q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[5])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 120}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[6] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_thriftpy2_transport_framed_cyfra_2, __pyx_mstate->__pyx_n_u_clean, __pyx_mstate->__pyx_kp_b_iso88591_A_E_q_KvQ_KvQ, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[6])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 4, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 1}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_state, __pyx_mstate->__pyx_n_u_dict_2, __pyx_mstate->__pyx_n_u_use_setstate}; + __pyx_mstate_global->__pyx_codeobj_tab[7] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_stringsource, __pyx_mstate->__pyx_n_u_reduce_cython, __pyx_mstate->__pyx_kp_b_iso88591_T_M_XT_G1F_a_vWE_Q_q_t6_S_L_uCt, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[7])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 16}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_pyx_state}; + __pyx_mstate_global->__pyx_codeobj_tab[8] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_stringsource, __pyx_mstate->__pyx_n_u_setstate_cython, __pyx_mstate->__pyx_kp_b_iso88591_0_q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[8])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 127}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_trans}; + __pyx_mstate_global->__pyx_codeobj_tab[9] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_thriftpy2_transport_framed_cyfra_2, __pyx_mstate->__pyx_n_u_get_transport, __pyx_mstate->__pyx_kp_b_iso88591_A, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[9])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {3, 0, 0, 4, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 4}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_pyx_type, __pyx_mstate->__pyx_n_u_pyx_checksum, __pyx_mstate->__pyx_n_u_pyx_state, __pyx_mstate->__pyx_n_u_pyx_result}; + __pyx_mstate_global->__pyx_codeobj_tab[10] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_stringsource, __pyx_mstate->__pyx_n_u_pyx_unpickle_TCyFramedTranspor, __pyx_mstate->__pyx_kp_b_iso88591_q_0_kQR_XQa_7_4A5J_XY_1, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[10])) goto bad; + } + Py_DECREF(tuple_dedup_map); + return 0; + bad: + Py_DECREF(tuple_dedup_map); + return -1; +} +/* #### Code section: init_globals ### */ + +static int __Pyx_InitGlobals(void) { + /* PythonCompatibility.init */ + if (likely(__Pyx_init_co_variables() == 0)); else + + if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 1, __pyx_L1_error) + + /* CommonTypesMetaclass.init */ + if (likely(__pyx_CommonTypesMetaclass_init(__pyx_m) == 0)); else + + if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 1, __pyx_L1_error) + + /* CachedMethodType.init */ + #if CYTHON_COMPILING_IN_LIMITED_API + { + PyObject *typesModule=NULL; + typesModule = PyImport_ImportModule("types"); + if (typesModule) { + __pyx_mstate_global->__Pyx_CachedMethodType = PyObject_GetAttrString(typesModule, "MethodType"); + Py_DECREF(typesModule); + } + } // error handling follows + #endif + + if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 1, __pyx_L1_error) + + /* CythonFunctionShared.init */ + if (likely(__pyx_CyFunction_init(__pyx_m) == 0)); else + + if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 1, __pyx_L1_error) + + return 0; + __pyx_L1_error:; + return -1; +} +/* #### Code section: cleanup_globals ### */ +/* #### Code section: cleanup_module ### */ +/* #### Code section: main_method ### */ +/* #### Code section: utility_code_pragmas ### */ +#ifdef _MSC_VER +#pragma warning( push ) +/* Warning 4127: conditional expression is constant + * Cython uses constant conditional expressions to allow in inline functions to be optimized at + * compile-time, so this warning is not useful + */ +#pragma warning( disable : 4127 ) +#endif + + + +/* #### Code section: utility_code_def ### */ + +/* --- Runtime support code --- */ +/* Refnanny */ +#if CYTHON_REFNANNY +static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { + PyObject *m = NULL, *p = NULL; + void *r = NULL; + m = PyImport_ImportModule(modname); + if (!m) goto end; + p = PyObject_GetAttrString(m, "RefNannyAPI"); + if (!p) goto end; + r = PyLong_AsVoidPtr(p); +end: + Py_XDECREF(p); + Py_XDECREF(m); + return (__Pyx_RefNannyAPIStruct *)r; +} +#endif + +/* PyErrExceptionMatches (used by PyObjectGetAttrStrNoError) */ +#if CYTHON_FAST_THREAD_STATE +static int __Pyx_PyErr_ExceptionMatchesTuple(PyObject *exc_type, PyObject *tuple) { + Py_ssize_t i, n; + n = PyTuple_GET_SIZE(tuple); + for (i=0; i= 0x030C00A6 + PyObject *current_exception = tstate->current_exception; + if (unlikely(!current_exception)) return 0; + exc_type = (PyObject*) Py_TYPE(current_exception); + if (exc_type == err) return 1; +#else + exc_type = tstate->curexc_type; + if (exc_type == err) return 1; + if (unlikely(!exc_type)) return 0; +#endif + #if CYTHON_AVOID_BORROWED_REFS + Py_INCREF(exc_type); + #endif + if (unlikely(PyTuple_Check(err))) { + result = __Pyx_PyErr_ExceptionMatchesTuple(exc_type, err); + } else { + result = __Pyx_PyErr_GivenExceptionMatches(exc_type, err); + } + #if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(exc_type); + #endif + return result; +} +#endif + +/* PyErrFetchRestore (used by PyObjectGetAttrStrNoError) */ +#if CYTHON_FAST_THREAD_STATE +static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { +#if PY_VERSION_HEX >= 0x030C00A6 + PyObject *tmp_value; + assert(type == NULL || (value != NULL && type == (PyObject*) Py_TYPE(value))); + if (value) { + #if CYTHON_COMPILING_IN_CPYTHON + if (unlikely(((PyBaseExceptionObject*) value)->traceback != tb)) + #endif + PyException_SetTraceback(value, tb); + } + tmp_value = tstate->current_exception; + tstate->current_exception = value; + Py_XDECREF(tmp_value); + Py_XDECREF(type); + Py_XDECREF(tb); +#else + PyObject *tmp_type, *tmp_value, *tmp_tb; + tmp_type = tstate->curexc_type; + tmp_value = tstate->curexc_value; + tmp_tb = tstate->curexc_traceback; + tstate->curexc_type = type; + tstate->curexc_value = value; + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#endif +} +static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { +#if PY_VERSION_HEX >= 0x030C00A6 + PyObject* exc_value; + exc_value = tstate->current_exception; + tstate->current_exception = 0; + *value = exc_value; + *type = NULL; + *tb = NULL; + if (exc_value) { + *type = (PyObject*) Py_TYPE(exc_value); + Py_INCREF(*type); + #if CYTHON_COMPILING_IN_CPYTHON + *tb = ((PyBaseExceptionObject*) exc_value)->traceback; + Py_XINCREF(*tb); + #else + *tb = PyException_GetTraceback(exc_value); + #endif + } +#else + *type = tstate->curexc_type; + *value = tstate->curexc_value; + *tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; +#endif +} +#endif + +/* PyObjectGetAttrStr (used by PyObjectGetAttrStrNoError) */ +#if CYTHON_USE_TYPE_SLOTS +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { + PyTypeObject* tp = Py_TYPE(obj); + if (likely(tp->tp_getattro)) + return tp->tp_getattro(obj, attr_name); + return PyObject_GetAttr(obj, attr_name); +} +#endif + +/* PyObjectGetAttrStrNoError (used by GetBuiltinName) */ +#if __PYX_LIMITED_VERSION_HEX < 0x030d0000 +static void __Pyx_PyObject_GetAttrStr_ClearAttributeError(void) { + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + if (likely(__Pyx_PyErr_ExceptionMatches(PyExc_AttributeError))) + __Pyx_PyErr_Clear(); +} +#endif +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStrNoError(PyObject* obj, PyObject* attr_name) { + PyObject *result; +#if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + (void) PyObject_GetOptionalAttr(obj, attr_name, &result); + return result; +#else +#if CYTHON_COMPILING_IN_CPYTHON && CYTHON_USE_TYPE_SLOTS + PyTypeObject* tp = Py_TYPE(obj); + if (likely(tp->tp_getattro == PyObject_GenericGetAttr)) { + return _PyObject_GenericGetAttrWithDict(obj, attr_name, NULL, 1); + } +#endif + result = __Pyx_PyObject_GetAttrStr(obj, attr_name); + if (unlikely(!result)) { + __Pyx_PyObject_GetAttrStr_ClearAttributeError(); + } + return result; +#endif +} + +/* GetBuiltinName */ +static PyObject *__Pyx_GetBuiltinName(PyObject *name) { + PyObject* result = __Pyx_PyObject_GetAttrStrNoError(__pyx_mstate_global->__pyx_b, name); + if (unlikely(!result) && !PyErr_Occurred()) { + PyErr_Format(PyExc_NameError, + "name '%U' is not defined", name); + } + return result; +} + +/* TupleAndListFromArray (used by fastcall) */ +#if !CYTHON_COMPILING_IN_CPYTHON && CYTHON_METH_FASTCALL +static CYTHON_INLINE PyObject * +__Pyx_PyTuple_FromArray(PyObject *const *src, Py_ssize_t n) +{ + PyObject *res; + Py_ssize_t i; + if (n <= 0) { + return __Pyx_NewRef(__pyx_mstate_global->__pyx_empty_tuple); + } + res = PyTuple_New(n); + if (unlikely(res == NULL)) return NULL; + for (i = 0; i < n; i++) { + if (unlikely(__Pyx_PyTuple_SET_ITEM(res, i, src[i]) < (0))) { + Py_DECREF(res); + return NULL; + } + Py_INCREF(src[i]); + } + return res; +} +#elif CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE void __Pyx_copy_object_array(PyObject *const *CYTHON_RESTRICT src, PyObject** CYTHON_RESTRICT dest, Py_ssize_t length) { + PyObject *v; + Py_ssize_t i; + for (i = 0; i < length; i++) { + v = dest[i] = src[i]; + Py_INCREF(v); + } +} +static CYTHON_INLINE PyObject * +__Pyx_PyTuple_FromArray(PyObject *const *src, Py_ssize_t n) +{ + PyObject *res; + if (n <= 0) { + return __Pyx_NewRef(__pyx_mstate_global->__pyx_empty_tuple); + } + res = PyTuple_New(n); + if (unlikely(res == NULL)) return NULL; + __Pyx_copy_object_array(src, ((PyTupleObject*)res)->ob_item, n); + return res; +} +static CYTHON_INLINE PyObject * +__Pyx_PyList_FromArray(PyObject *const *src, Py_ssize_t n) +{ + PyObject *res; + if (n <= 0) { + return PyList_New(0); + } + res = PyList_New(n); + if (unlikely(res == NULL)) return NULL; + __Pyx_copy_object_array(src, ((PyListObject*)res)->ob_item, n); + return res; +} +#endif + +/* BytesEquals (used by UnicodeEquals) */ +static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals) { +#if CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_GRAAL ||\ + !(CYTHON_ASSUME_SAFE_SIZE && CYTHON_ASSUME_SAFE_MACROS) + return PyObject_RichCompareBool(s1, s2, equals); +#else + if (s1 == s2) { + return (equals == Py_EQ); + } else if (PyBytes_CheckExact(s1) & PyBytes_CheckExact(s2)) { + const char *ps1, *ps2; + Py_ssize_t length = PyBytes_GET_SIZE(s1); + if (length != PyBytes_GET_SIZE(s2)) + return (equals == Py_NE); + ps1 = PyBytes_AS_STRING(s1); + ps2 = PyBytes_AS_STRING(s2); + if (ps1[0] != ps2[0]) { + return (equals == Py_NE); + } else if (length == 1) { + return (equals == Py_EQ); + } else { + int result; +#if CYTHON_USE_UNICODE_INTERNALS && (PY_VERSION_HEX < 0x030B0000) + Py_hash_t hash1, hash2; + hash1 = ((PyBytesObject*)s1)->ob_shash; + hash2 = ((PyBytesObject*)s2)->ob_shash; + if (hash1 != hash2 && hash1 != -1 && hash2 != -1) { + return (equals == Py_NE); + } +#endif + result = memcmp(ps1, ps2, (size_t)length); + return (equals == Py_EQ) ? (result == 0) : (result != 0); + } + } else if ((s1 == Py_None) & PyBytes_CheckExact(s2)) { + return (equals == Py_NE); + } else if ((s2 == Py_None) & PyBytes_CheckExact(s1)) { + return (equals == Py_NE); + } else { + int result; + PyObject* py_result = PyObject_RichCompare(s1, s2, equals); + if (!py_result) + return -1; + result = __Pyx_PyObject_IsTrue(py_result); + Py_DECREF(py_result); + return result; + } +#endif +} + +/* UnicodeEquals (used by fastcall) */ +static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals) { +#if CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_GRAAL + return PyObject_RichCompareBool(s1, s2, equals); +#else + int s1_is_unicode, s2_is_unicode; + if (s1 == s2) { + goto return_eq; + } + s1_is_unicode = PyUnicode_CheckExact(s1); + s2_is_unicode = PyUnicode_CheckExact(s2); + if (s1_is_unicode & s2_is_unicode) { + Py_ssize_t length, length2; + int kind; + void *data1, *data2; + #if !CYTHON_COMPILING_IN_LIMITED_API + if (unlikely(__Pyx_PyUnicode_READY(s1) < 0) || unlikely(__Pyx_PyUnicode_READY(s2) < 0)) + return -1; + #endif + length = __Pyx_PyUnicode_GET_LENGTH(s1); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(length < 0)) return -1; + #endif + length2 = __Pyx_PyUnicode_GET_LENGTH(s2); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(length2 < 0)) return -1; + #endif + if (length != length2) { + goto return_ne; + } +#if CYTHON_USE_UNICODE_INTERNALS + { + Py_hash_t hash1, hash2; + hash1 = ((PyASCIIObject*)s1)->hash; + hash2 = ((PyASCIIObject*)s2)->hash; + if (hash1 != hash2 && hash1 != -1 && hash2 != -1) { + goto return_ne; + } + } +#endif + kind = __Pyx_PyUnicode_KIND(s1); + if (kind != __Pyx_PyUnicode_KIND(s2)) { + goto return_ne; + } + data1 = __Pyx_PyUnicode_DATA(s1); + data2 = __Pyx_PyUnicode_DATA(s2); + if (__Pyx_PyUnicode_READ(kind, data1, 0) != __Pyx_PyUnicode_READ(kind, data2, 0)) { + goto return_ne; + } else if (length == 1) { + goto return_eq; + } else { + int result = memcmp(data1, data2, (size_t)(length * kind)); + return (equals == Py_EQ) ? (result == 0) : (result != 0); + } + } else if ((s1 == Py_None) & s2_is_unicode) { + goto return_ne; + } else if ((s2 == Py_None) & s1_is_unicode) { + goto return_ne; + } else { + int result; + PyObject* py_result = PyObject_RichCompare(s1, s2, equals); + if (!py_result) + return -1; + result = __Pyx_PyObject_IsTrue(py_result); + Py_DECREF(py_result); + return result; + } +return_eq: + return (equals == Py_EQ); +return_ne: + return (equals == Py_NE); +#endif +} + +/* fastcall */ +#if CYTHON_METH_FASTCALL +static CYTHON_INLINE PyObject * __Pyx_GetKwValue_FASTCALL(PyObject *kwnames, PyObject *const *kwvalues, PyObject *s) +{ + Py_ssize_t i, n = __Pyx_PyTuple_GET_SIZE(kwnames); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(n == -1)) return NULL; + #endif + for (i = 0; i < n; i++) + { + PyObject *namei = __Pyx_PyTuple_GET_ITEM(kwnames, i); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(!namei)) return NULL; + #endif + if (s == namei) return kwvalues[i]; + } + for (i = 0; i < n; i++) + { + PyObject *namei = __Pyx_PyTuple_GET_ITEM(kwnames, i); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(!namei)) return NULL; + #endif + int eq = __Pyx_PyUnicode_Equals(s, namei, Py_EQ); + if (unlikely(eq != 0)) { + if (unlikely(eq < 0)) return NULL; + return kwvalues[i]; + } + } + return NULL; +} +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030d0000 || CYTHON_COMPILING_IN_LIMITED_API +CYTHON_UNUSED static PyObject *__Pyx_KwargsAsDict_FASTCALL(PyObject *kwnames, PyObject *const *kwvalues) { + Py_ssize_t i, nkwargs; + PyObject *dict; +#if !CYTHON_ASSUME_SAFE_SIZE + nkwargs = PyTuple_Size(kwnames); + if (unlikely(nkwargs < 0)) return NULL; +#else + nkwargs = PyTuple_GET_SIZE(kwnames); +#endif + dict = PyDict_New(); + if (unlikely(!dict)) + return NULL; + for (i=0; itp_call; + if (unlikely(!call)) + return PyObject_Call(func, arg, kw); + if (unlikely(Py_EnterRecursiveCall(" while calling a Python object"))) + return NULL; + result = (*call)(func, arg, kw); + Py_LeaveRecursiveCall(); + if (unlikely(!result) && unlikely(!PyErr_Occurred())) { + PyErr_SetString( + PyExc_SystemError, + "NULL result without error in PyObject_Call"); + } + return result; +} +#endif + +/* PyObjectCallMethO (used by PyObjectFastCall) */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg) { + PyObject *self, *result; + PyCFunction cfunc; + cfunc = __Pyx_CyOrPyCFunction_GET_FUNCTION(func); + self = __Pyx_CyOrPyCFunction_GET_SELF(func); + if (unlikely(Py_EnterRecursiveCall(" while calling a Python object"))) + return NULL; + result = cfunc(self, arg); + Py_LeaveRecursiveCall(); + if (unlikely(!result) && unlikely(!PyErr_Occurred())) { + PyErr_SetString( + PyExc_SystemError, + "NULL result without error in PyObject_Call"); + } + return result; +} +#endif + +/* PyObjectFastCall (used by PyObjectCallOneArg) */ +#if PY_VERSION_HEX < 0x03090000 || CYTHON_COMPILING_IN_LIMITED_API +static PyObject* __Pyx_PyObject_FastCall_fallback(PyObject *func, PyObject * const*args, size_t nargs, PyObject *kwargs) { + PyObject *argstuple; + PyObject *result = 0; + size_t i; + argstuple = PyTuple_New((Py_ssize_t)nargs); + if (unlikely(!argstuple)) return NULL; + for (i = 0; i < nargs; i++) { + Py_INCREF(args[i]); + if (__Pyx_PyTuple_SET_ITEM(argstuple, (Py_ssize_t)i, args[i]) != (0)) goto bad; + } + result = __Pyx_PyObject_Call(func, argstuple, kwargs); + bad: + Py_DECREF(argstuple); + return result; +} +#endif +#if CYTHON_VECTORCALL && !CYTHON_COMPILING_IN_LIMITED_API + #if PY_VERSION_HEX < 0x03090000 + #define __Pyx_PyVectorcall_Function(callable) _PyVectorcall_Function(callable) + #elif CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE vectorcallfunc __Pyx_PyVectorcall_Function(PyObject *callable) { + PyTypeObject *tp = Py_TYPE(callable); + #if defined(__Pyx_CyFunction_USED) + if (__Pyx_CyFunction_CheckExact(callable)) { + return __Pyx_CyFunction_func_vectorcall(callable); + } + #endif + if (!PyType_HasFeature(tp, Py_TPFLAGS_HAVE_VECTORCALL)) { + return NULL; + } + assert(PyCallable_Check(callable)); + Py_ssize_t offset = tp->tp_vectorcall_offset; + assert(offset > 0); + vectorcallfunc ptr; + memcpy(&ptr, (char *) callable + offset, sizeof(ptr)); + return ptr; +} + #else + #define __Pyx_PyVectorcall_Function(callable) PyVectorcall_Function(callable) + #endif +#endif +static CYTHON_INLINE PyObject* __Pyx_PyObject_FastCallDict(PyObject *func, PyObject *const *args, size_t _nargs, PyObject *kwargs) { + Py_ssize_t nargs = __Pyx_PyVectorcall_NARGS(_nargs); +#if CYTHON_COMPILING_IN_CPYTHON + if (nargs == 0 && kwargs == NULL) { + if (__Pyx_CyOrPyCFunction_Check(func) && likely( __Pyx_CyOrPyCFunction_GET_FLAGS(func) & METH_NOARGS)) + return __Pyx_PyObject_CallMethO(func, NULL); + } + else if (nargs == 1 && kwargs == NULL) { + if (__Pyx_CyOrPyCFunction_Check(func) && likely( __Pyx_CyOrPyCFunction_GET_FLAGS(func) & METH_O)) + return __Pyx_PyObject_CallMethO(func, args[0]); + } +#endif + if (kwargs == NULL) { + #if CYTHON_VECTORCALL + #if CYTHON_COMPILING_IN_LIMITED_API + return PyObject_Vectorcall(func, args, _nargs, NULL); + #else + vectorcallfunc f = __Pyx_PyVectorcall_Function(func); + if (f) { + return f(func, args, _nargs, NULL); + } + #endif + #endif + } + if (nargs == 0) { + return __Pyx_PyObject_Call(func, __pyx_mstate_global->__pyx_empty_tuple, kwargs); + } + #if PY_VERSION_HEX >= 0x03090000 && !CYTHON_COMPILING_IN_LIMITED_API + return PyObject_VectorcallDict(func, args, (size_t)nargs, kwargs); + #else + return __Pyx_PyObject_FastCall_fallback(func, args, (size_t)nargs, kwargs); + #endif +} + +/* PyObjectCallOneArg (used by CallUnboundCMethod0) */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { + PyObject *args[2] = {NULL, arg}; + return __Pyx_PyObject_FastCall(func, args+1, 1 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET); +} + +/* UnpackUnboundCMethod (used by CallUnboundCMethod0) */ +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030C0000 +static PyObject *__Pyx_SelflessCall(PyObject *method, PyObject *args, PyObject *kwargs) { + PyObject *result; + PyObject *selfless_args = PyTuple_GetSlice(args, 1, PyTuple_Size(args)); + if (unlikely(!selfless_args)) return NULL; + result = PyObject_Call(method, selfless_args, kwargs); + Py_DECREF(selfless_args); + return result; +} +#elif CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX < 0x03090000 +static PyObject *__Pyx_SelflessCall(PyObject *method, PyObject **args, Py_ssize_t nargs, PyObject *kwnames) { + return _PyObject_Vectorcall + (method, args ? args+1 : NULL, nargs ? nargs-1 : 0, kwnames); +} +#else +static PyObject *__Pyx_SelflessCall(PyObject *method, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames) { + return +#if PY_VERSION_HEX < 0x03090000 + _PyObject_Vectorcall +#else + PyObject_Vectorcall +#endif + (method, args ? args+1 : NULL, nargs ? (size_t) nargs-1 : 0, kwnames); +} +#endif +static PyMethodDef __Pyx_UnboundCMethod_Def = { + "CythonUnboundCMethod", + __PYX_REINTERPRET_FUNCION(PyCFunction, __Pyx_SelflessCall), +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030C0000 + METH_VARARGS | METH_KEYWORDS, +#else + METH_FASTCALL | METH_KEYWORDS, +#endif + NULL +}; +static int __Pyx_TryUnpackUnboundCMethod(__Pyx_CachedCFunction* target) { + PyObject *method, *result=NULL; + method = __Pyx_PyObject_GetAttrStr(target->type, *target->method_name); + if (unlikely(!method)) + return -1; + result = method; +#if CYTHON_COMPILING_IN_CPYTHON + if (likely(__Pyx_TypeCheck(method, &PyMethodDescr_Type))) + { + PyMethodDescrObject *descr = (PyMethodDescrObject*) method; + target->func = descr->d_method->ml_meth; + target->flag = descr->d_method->ml_flags & ~(METH_CLASS | METH_STATIC | METH_COEXIST | METH_STACKLESS); + } else +#endif +#if CYTHON_COMPILING_IN_PYPY +#else + if (PyCFunction_Check(method)) +#endif + { + PyObject *self; + int self_found; +#if CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_PYPY + self = PyObject_GetAttrString(method, "__self__"); + if (!self) { + PyErr_Clear(); + } +#else + self = PyCFunction_GET_SELF(method); +#endif + self_found = (self && self != Py_None); +#if CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_PYPY + Py_XDECREF(self); +#endif + if (self_found) { + PyObject *unbound_method = PyCFunction_New(&__Pyx_UnboundCMethod_Def, method); + if (unlikely(!unbound_method)) return -1; + Py_DECREF(method); + result = unbound_method; + } + } +#if !CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + if (unlikely(target->method)) { + Py_DECREF(result); + } else +#endif + target->method = result; + return 0; +} + +/* CallUnboundCMethod0 */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_CallUnboundCMethod0(__Pyx_CachedCFunction* cfunc, PyObject* self) { + int was_initialized = __Pyx_CachedCFunction_GetAndSetInitializing(cfunc); + if (likely(was_initialized == 2 && cfunc->func)) { + if (likely(cfunc->flag == METH_NOARGS)) + return __Pyx_CallCFunction(cfunc, self, NULL); + if (likely(cfunc->flag == METH_FASTCALL)) + return __Pyx_CallCFunctionFast(cfunc, self, NULL, 0); + if (cfunc->flag == (METH_FASTCALL | METH_KEYWORDS)) + return __Pyx_CallCFunctionFastWithKeywords(cfunc, self, NULL, 0, NULL); + if (likely(cfunc->flag == (METH_VARARGS | METH_KEYWORDS))) + return __Pyx_CallCFunctionWithKeywords(cfunc, self, __pyx_mstate_global->__pyx_empty_tuple, NULL); + if (cfunc->flag == METH_VARARGS) + return __Pyx_CallCFunction(cfunc, self, __pyx_mstate_global->__pyx_empty_tuple); + return __Pyx__CallUnboundCMethod0(cfunc, self); + } +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + else if (unlikely(was_initialized == 1)) { + __Pyx_CachedCFunction tmp_cfunc = { +#ifndef __cplusplus + 0 +#endif + }; + tmp_cfunc.type = cfunc->type; + tmp_cfunc.method_name = cfunc->method_name; + return __Pyx__CallUnboundCMethod0(&tmp_cfunc, self); + } +#endif + PyObject *result = __Pyx__CallUnboundCMethod0(cfunc, self); + __Pyx_CachedCFunction_SetFinishedInitializing(cfunc); + return result; +} +#endif +static PyObject* __Pyx__CallUnboundCMethod0(__Pyx_CachedCFunction* cfunc, PyObject* self) { + PyObject *result; + if (unlikely(!cfunc->method) && unlikely(__Pyx_TryUnpackUnboundCMethod(cfunc) < 0)) return NULL; + result = __Pyx_PyObject_CallOneArg(cfunc->method, self); + return result; +} + +/* py_dict_items (used by OwnedDictNext) */ +static CYTHON_INLINE PyObject* __Pyx_PyDict_Items(PyObject* d) { + return __Pyx_CallUnboundCMethod0(&__pyx_mstate_global->__pyx_umethod_PyDict_Type_items, d); +} + +/* py_dict_values (used by OwnedDictNext) */ +static CYTHON_INLINE PyObject* __Pyx_PyDict_Values(PyObject* d) { + return __Pyx_CallUnboundCMethod0(&__pyx_mstate_global->__pyx_umethod_PyDict_Type_values, d); +} + +/* OwnedDictNext (used by ParseKeywordsImpl) */ +#if CYTHON_AVOID_BORROWED_REFS +static int __Pyx_PyDict_NextRef(PyObject *p, PyObject **ppos, PyObject **pkey, PyObject **pvalue) { + PyObject *next = NULL; + if (!*ppos) { + if (pvalue) { + PyObject *dictview = pkey ? __Pyx_PyDict_Items(p) : __Pyx_PyDict_Values(p); + if (unlikely(!dictview)) goto bad; + *ppos = PyObject_GetIter(dictview); + Py_DECREF(dictview); + } else { + *ppos = PyObject_GetIter(p); + } + if (unlikely(!*ppos)) goto bad; + } + next = PyIter_Next(*ppos); + if (!next) { + if (PyErr_Occurred()) goto bad; + return 0; + } + if (pkey && pvalue) { + *pkey = __Pyx_PySequence_ITEM(next, 0); + if (unlikely(*pkey)) goto bad; + *pvalue = __Pyx_PySequence_ITEM(next, 1); + if (unlikely(*pvalue)) goto bad; + Py_DECREF(next); + } else if (pkey) { + *pkey = next; + } else { + assert(pvalue); + *pvalue = next; + } + return 1; + bad: + Py_XDECREF(next); +#if !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d0000 + PyErr_FormatUnraisable("Exception ignored in __Pyx_PyDict_NextRef"); +#else + PyErr_WriteUnraisable(__pyx_mstate_global->__pyx_n_u_Pyx_PyDict_NextRef); +#endif + if (pkey) *pkey = NULL; + if (pvalue) *pvalue = NULL; + return 0; +} +#else // !CYTHON_AVOID_BORROWED_REFS +static int __Pyx_PyDict_NextRef(PyObject *p, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue) { + int result = PyDict_Next(p, ppos, pkey, pvalue); + if (likely(result == 1)) { + if (pkey) Py_INCREF(*pkey); + if (pvalue) Py_INCREF(*pvalue); + } + return result; +} +#endif + +/* RaiseDoubleKeywords (used by ParseKeywordsImpl) */ +static void __Pyx_RaiseDoubleKeywordsError( + const char* func_name, + PyObject* kw_name) +{ + PyErr_Format(PyExc_TypeError, + "%s() got multiple values for keyword argument '%U'", func_name, kw_name); +} + +/* CallUnboundCMethod2 */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject *__Pyx_CallUnboundCMethod2(__Pyx_CachedCFunction *cfunc, PyObject *self, PyObject *arg1, PyObject *arg2) { + int was_initialized = __Pyx_CachedCFunction_GetAndSetInitializing(cfunc); + if (likely(was_initialized == 2 && cfunc->func)) { + PyObject *args[2] = {arg1, arg2}; + if (cfunc->flag == METH_FASTCALL) { + return __Pyx_CallCFunctionFast(cfunc, self, args, 2); + } + if (cfunc->flag == (METH_FASTCALL | METH_KEYWORDS)) + return __Pyx_CallCFunctionFastWithKeywords(cfunc, self, args, 2, NULL); + } +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + else if (unlikely(was_initialized == 1)) { + __Pyx_CachedCFunction tmp_cfunc = { +#ifndef __cplusplus + 0 +#endif + }; + tmp_cfunc.type = cfunc->type; + tmp_cfunc.method_name = cfunc->method_name; + return __Pyx__CallUnboundCMethod2(&tmp_cfunc, self, arg1, arg2); + } +#endif + PyObject *result = __Pyx__CallUnboundCMethod2(cfunc, self, arg1, arg2); + __Pyx_CachedCFunction_SetFinishedInitializing(cfunc); + return result; +} +#endif +static PyObject* __Pyx__CallUnboundCMethod2(__Pyx_CachedCFunction* cfunc, PyObject* self, PyObject* arg1, PyObject* arg2){ + if (unlikely(!cfunc->func && !cfunc->method) && unlikely(__Pyx_TryUnpackUnboundCMethod(cfunc) < 0)) return NULL; +#if CYTHON_COMPILING_IN_CPYTHON + if (cfunc->func && (cfunc->flag & METH_VARARGS)) { + PyObject *result = NULL; + PyObject *args = PyTuple_New(2); + if (unlikely(!args)) return NULL; + Py_INCREF(arg1); + PyTuple_SET_ITEM(args, 0, arg1); + Py_INCREF(arg2); + PyTuple_SET_ITEM(args, 1, arg2); + if (cfunc->flag & METH_KEYWORDS) + result = __Pyx_CallCFunctionWithKeywords(cfunc, self, args, NULL); + else + result = __Pyx_CallCFunction(cfunc, self, args); + Py_DECREF(args); + return result; + } +#endif + { + PyObject *args[4] = {NULL, self, arg1, arg2}; + return __Pyx_PyObject_FastCall(cfunc->method, args+1, 3 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET); + } +} + +/* ParseKeywordsImpl (used by ParseKeywords) */ +static int __Pyx_ValidateDuplicatePosArgs( + PyObject *kwds, + PyObject ** const argnames[], + PyObject ** const *first_kw_arg, + const char* function_name) +{ + PyObject ** const *name = argnames; + while (name != first_kw_arg) { + PyObject *key = **name; + int found = PyDict_Contains(kwds, key); + if (unlikely(found)) { + if (found == 1) __Pyx_RaiseDoubleKeywordsError(function_name, key); + goto bad; + } + name++; + } + return 0; +bad: + return -1; +} +#if CYTHON_USE_UNICODE_INTERNALS +static CYTHON_INLINE int __Pyx_UnicodeKeywordsEqual(PyObject *s1, PyObject *s2) { + int kind; + Py_ssize_t len = PyUnicode_GET_LENGTH(s1); + if (len != PyUnicode_GET_LENGTH(s2)) return 0; + kind = PyUnicode_KIND(s1); + if (kind != PyUnicode_KIND(s2)) return 0; + const void *data1 = PyUnicode_DATA(s1); + const void *data2 = PyUnicode_DATA(s2); + return (memcmp(data1, data2, (size_t) len * (size_t) kind) == 0); +} +#endif +static int __Pyx_MatchKeywordArg_str( + PyObject *key, + PyObject ** const argnames[], + PyObject ** const *first_kw_arg, + size_t *index_found, + const char *function_name) +{ + PyObject ** const *name; + #if CYTHON_USE_UNICODE_INTERNALS + Py_hash_t key_hash = ((PyASCIIObject*)key)->hash; + if (unlikely(key_hash == -1)) { + key_hash = PyObject_Hash(key); + if (unlikely(key_hash == -1)) + goto bad; + } + #endif + name = first_kw_arg; + while (*name) { + PyObject *name_str = **name; + #if CYTHON_USE_UNICODE_INTERNALS + if (key_hash == ((PyASCIIObject*)name_str)->hash && __Pyx_UnicodeKeywordsEqual(name_str, key)) { + *index_found = (size_t) (name - argnames); + return 1; + } + #else + #if CYTHON_ASSUME_SAFE_SIZE + if (PyUnicode_GET_LENGTH(name_str) == PyUnicode_GET_LENGTH(key)) + #endif + { + int cmp = PyUnicode_Compare(name_str, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) { + *index_found = (size_t) (name - argnames); + return 1; + } + } + #endif + name++; + } + name = argnames; + while (name != first_kw_arg) { + PyObject *name_str = **name; + #if CYTHON_USE_UNICODE_INTERNALS + if (unlikely(key_hash == ((PyASCIIObject*)name_str)->hash)) { + if (__Pyx_UnicodeKeywordsEqual(name_str, key)) + goto arg_passed_twice; + } + #else + #if CYTHON_ASSUME_SAFE_SIZE + if (PyUnicode_GET_LENGTH(name_str) == PyUnicode_GET_LENGTH(key)) + #endif + { + if (unlikely(name_str == key)) goto arg_passed_twice; + int cmp = PyUnicode_Compare(name_str, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) goto arg_passed_twice; + } + #endif + name++; + } + return 0; +arg_passed_twice: + __Pyx_RaiseDoubleKeywordsError(function_name, key); + goto bad; +bad: + return -1; +} +static int __Pyx_MatchKeywordArg_nostr( + PyObject *key, + PyObject ** const argnames[], + PyObject ** const *first_kw_arg, + size_t *index_found, + const char *function_name) +{ + PyObject ** const *name; + if (unlikely(!PyUnicode_Check(key))) goto invalid_keyword_type; + name = first_kw_arg; + while (*name) { + int cmp = PyObject_RichCompareBool(**name, key, Py_EQ); + if (cmp == 1) { + *index_found = (size_t) (name - argnames); + return 1; + } + if (unlikely(cmp == -1)) goto bad; + name++; + } + name = argnames; + while (name != first_kw_arg) { + int cmp = PyObject_RichCompareBool(**name, key, Py_EQ); + if (unlikely(cmp != 0)) { + if (cmp == 1) goto arg_passed_twice; + else goto bad; + } + name++; + } + return 0; +arg_passed_twice: + __Pyx_RaiseDoubleKeywordsError(function_name, key); + goto bad; +invalid_keyword_type: + PyErr_Format(PyExc_TypeError, + "%.200s() keywords must be strings", function_name); + goto bad; +bad: + return -1; +} +static CYTHON_INLINE int __Pyx_MatchKeywordArg( + PyObject *key, + PyObject ** const argnames[], + PyObject ** const *first_kw_arg, + size_t *index_found, + const char *function_name) +{ + return likely(PyUnicode_CheckExact(key)) ? + __Pyx_MatchKeywordArg_str(key, argnames, first_kw_arg, index_found, function_name) : + __Pyx_MatchKeywordArg_nostr(key, argnames, first_kw_arg, index_found, function_name); +} +static void __Pyx_RejectUnknownKeyword( + PyObject *kwds, + PyObject ** const argnames[], + PyObject ** const *first_kw_arg, + const char *function_name) +{ + #if CYTHON_AVOID_BORROWED_REFS + PyObject *pos = NULL; + #else + Py_ssize_t pos = 0; + #endif + PyObject *key = NULL; + __Pyx_BEGIN_CRITICAL_SECTION(kwds); + while ( + #if CYTHON_AVOID_BORROWED_REFS + __Pyx_PyDict_NextRef(kwds, &pos, &key, NULL) + #else + PyDict_Next(kwds, &pos, &key, NULL) + #endif + ) { + PyObject** const *name = first_kw_arg; + while (*name && (**name != key)) name++; + if (!*name) { + size_t index_found = 0; + int cmp = __Pyx_MatchKeywordArg(key, argnames, first_kw_arg, &index_found, function_name); + if (cmp != 1) { + if (cmp == 0) { + PyErr_Format(PyExc_TypeError, + "%s() got an unexpected keyword argument '%U'", + function_name, key); + } + #if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(key); + #endif + break; + } + } + #if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(key); + #endif + } + __Pyx_END_CRITICAL_SECTION(); + #if CYTHON_AVOID_BORROWED_REFS + Py_XDECREF(pos); + #endif + assert(PyErr_Occurred()); +} +static int __Pyx_ParseKeywordDict( + PyObject *kwds, + PyObject ** const argnames[], + PyObject *values[], + Py_ssize_t num_pos_args, + Py_ssize_t num_kwargs, + const char* function_name, + int ignore_unknown_kwargs) +{ + PyObject** const *name; + PyObject** const *first_kw_arg = argnames + num_pos_args; + Py_ssize_t extracted = 0; +#if !CYTHON_COMPILING_IN_PYPY || defined(PyArg_ValidateKeywordArguments) + if (unlikely(!PyArg_ValidateKeywordArguments(kwds))) return -1; +#endif + name = first_kw_arg; + while (*name && num_kwargs > extracted) { + PyObject * key = **name; + PyObject *value; + int found = 0; + #if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + found = PyDict_GetItemRef(kwds, key, &value); + #else + value = PyDict_GetItemWithError(kwds, key); + if (value) { + Py_INCREF(value); + found = 1; + } else { + if (unlikely(PyErr_Occurred())) goto bad; + } + #endif + if (found) { + if (unlikely(found < 0)) goto bad; + values[name-argnames] = value; + extracted++; + } + name++; + } + if (num_kwargs > extracted) { + if (ignore_unknown_kwargs) { + if (unlikely(__Pyx_ValidateDuplicatePosArgs(kwds, argnames, first_kw_arg, function_name) == -1)) + goto bad; + } else { + __Pyx_RejectUnknownKeyword(kwds, argnames, first_kw_arg, function_name); + goto bad; + } + } + return 0; +bad: + return -1; +} +static int __Pyx_ParseKeywordDictToDict( + PyObject *kwds, + PyObject ** const argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + const char* function_name) +{ + PyObject** const *name; + PyObject** const *first_kw_arg = argnames + num_pos_args; + Py_ssize_t len; +#if !CYTHON_COMPILING_IN_PYPY || defined(PyArg_ValidateKeywordArguments) + if (unlikely(!PyArg_ValidateKeywordArguments(kwds))) return -1; +#endif + if (PyDict_Update(kwds2, kwds) < 0) goto bad; + name = first_kw_arg; + while (*name) { + PyObject *key = **name; + PyObject *value; +#if !CYTHON_COMPILING_IN_LIMITED_API && (PY_VERSION_HEX >= 0x030d00A2 || defined(PyDict_Pop)) + int found = PyDict_Pop(kwds2, key, &value); + if (found) { + if (unlikely(found < 0)) goto bad; + values[name-argnames] = value; + } +#elif __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + int found = PyDict_GetItemRef(kwds2, key, &value); + if (found) { + if (unlikely(found < 0)) goto bad; + values[name-argnames] = value; + if (unlikely(PyDict_DelItem(kwds2, key) < 0)) goto bad; + } +#else + #if CYTHON_COMPILING_IN_CPYTHON + value = _PyDict_Pop(kwds2, key, kwds2); + #else + value = __Pyx_CallUnboundCMethod2(&__pyx_mstate_global->__pyx_umethod_PyDict_Type_pop, kwds2, key, kwds2); + #endif + if (value == kwds2) { + Py_DECREF(value); + } else { + if (unlikely(!value)) goto bad; + values[name-argnames] = value; + } +#endif + name++; + } + len = PyDict_Size(kwds2); + if (len > 0) { + return __Pyx_ValidateDuplicatePosArgs(kwds, argnames, first_kw_arg, function_name); + } else if (unlikely(len == -1)) { + goto bad; + } + return 0; +bad: + return -1; +} +static int __Pyx_ParseKeywordsTuple( + PyObject *kwds, + PyObject * const *kwvalues, + PyObject ** const argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + Py_ssize_t num_kwargs, + const char* function_name, + int ignore_unknown_kwargs) +{ + PyObject *key = NULL; + PyObject** const * name; + PyObject** const *first_kw_arg = argnames + num_pos_args; + for (Py_ssize_t pos = 0; pos < num_kwargs; pos++) { +#if CYTHON_AVOID_BORROWED_REFS + key = __Pyx_PySequence_ITEM(kwds, pos); +#else + key = __Pyx_PyTuple_GET_ITEM(kwds, pos); +#endif +#if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(!key)) goto bad; +#endif + name = first_kw_arg; + while (*name && (**name != key)) name++; + if (*name) { + PyObject *value = kwvalues[pos]; + values[name-argnames] = __Pyx_NewRef(value); + } else { + size_t index_found = 0; + int cmp = __Pyx_MatchKeywordArg(key, argnames, first_kw_arg, &index_found, function_name); + if (cmp == 1) { + PyObject *value = kwvalues[pos]; + values[index_found] = __Pyx_NewRef(value); + } else { + if (unlikely(cmp == -1)) goto bad; + if (kwds2) { + PyObject *value = kwvalues[pos]; + if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; + } else if (!ignore_unknown_kwargs) { + goto invalid_keyword; + } + } + } + #if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(key); + key = NULL; + #endif + } + return 0; +invalid_keyword: + PyErr_Format(PyExc_TypeError, + "%s() got an unexpected keyword argument '%U'", + function_name, key); + goto bad; +bad: + #if CYTHON_AVOID_BORROWED_REFS + Py_XDECREF(key); + #endif + return -1; +} + +/* ParseKeywords */ +static int __Pyx_ParseKeywords( + PyObject *kwds, + PyObject * const *kwvalues, + PyObject ** const argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + Py_ssize_t num_kwargs, + const char* function_name, + int ignore_unknown_kwargs) +{ + if (CYTHON_METH_FASTCALL && likely(PyTuple_Check(kwds))) + return __Pyx_ParseKeywordsTuple(kwds, kwvalues, argnames, kwds2, values, num_pos_args, num_kwargs, function_name, ignore_unknown_kwargs); + else if (kwds2) + return __Pyx_ParseKeywordDictToDict(kwds, argnames, kwds2, values, num_pos_args, function_name); + else + return __Pyx_ParseKeywordDict(kwds, argnames, values, num_pos_args, num_kwargs, function_name, ignore_unknown_kwargs); +} + +/* RaiseArgTupleInvalid */ +static void __Pyx_RaiseArgtupleInvalid( + const char* func_name, + int exact, + Py_ssize_t num_min, + Py_ssize_t num_max, + Py_ssize_t num_found) +{ + Py_ssize_t num_expected; + const char *more_or_less; + if (num_found < num_min) { + num_expected = num_min; + more_or_less = "at least"; + } else { + num_expected = num_max; + more_or_less = "at most"; + } + if (exact) { + more_or_less = "exactly"; + } + PyErr_Format(PyExc_TypeError, + "%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)", + func_name, more_or_less, num_expected, + (num_expected == 1) ? "" : "s", num_found); +} + +/* PyDictVersioning (used by GetModuleGlobalName) */ +#if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_TYPE_SLOTS +static CYTHON_INLINE PY_UINT64_T __Pyx_get_tp_dict_version(PyObject *obj) { + PyObject *dict = Py_TYPE(obj)->tp_dict; + return likely(dict) ? __PYX_GET_DICT_VERSION(dict) : 0; +} +static CYTHON_INLINE PY_UINT64_T __Pyx_get_object_dict_version(PyObject *obj) { + PyObject **dictptr = NULL; + Py_ssize_t offset = Py_TYPE(obj)->tp_dictoffset; + if (offset) { +#if CYTHON_COMPILING_IN_CPYTHON + dictptr = (likely(offset > 0)) ? (PyObject **) ((char *)obj + offset) : _PyObject_GetDictPtr(obj); +#else + dictptr = _PyObject_GetDictPtr(obj); +#endif + } + return (dictptr && *dictptr) ? __PYX_GET_DICT_VERSION(*dictptr) : 0; +} +static CYTHON_INLINE int __Pyx_object_dict_version_matches(PyObject* obj, PY_UINT64_T tp_dict_version, PY_UINT64_T obj_dict_version) { + PyObject *dict = Py_TYPE(obj)->tp_dict; + if (unlikely(!dict) || unlikely(tp_dict_version != __PYX_GET_DICT_VERSION(dict))) + return 0; + return obj_dict_version == __Pyx_get_object_dict_version(obj); +} +#endif + +/* GetModuleGlobalName */ +#if CYTHON_USE_DICT_VERSIONS +static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_version, PyObject **dict_cached_value) +#else +static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name) +#endif +{ + PyObject *result; +#if CYTHON_COMPILING_IN_LIMITED_API + if (unlikely(!__pyx_m)) { + if (!PyErr_Occurred()) + PyErr_SetNone(PyExc_NameError); + return NULL; + } + result = PyObject_GetAttr(__pyx_m, name); + if (likely(result)) { + return result; + } + PyErr_Clear(); +#elif CYTHON_AVOID_BORROWED_REFS || CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + if (unlikely(__Pyx_PyDict_GetItemRef(__pyx_mstate_global->__pyx_d, name, &result) == -1)) PyErr_Clear(); + __PYX_UPDATE_DICT_CACHE(__pyx_mstate_global->__pyx_d, result, *dict_cached_value, *dict_version) + if (likely(result)) { + return result; + } +#else + result = _PyDict_GetItem_KnownHash(__pyx_mstate_global->__pyx_d, name, ((PyASCIIObject *) name)->hash); + __PYX_UPDATE_DICT_CACHE(__pyx_mstate_global->__pyx_d, result, *dict_cached_value, *dict_version) + if (likely(result)) { + return __Pyx_NewRef(result); + } + PyErr_Clear(); +#endif + return __Pyx_GetBuiltinName(name); +} + +/* RaiseException */ +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { + PyObject* owned_instance = NULL; + if (tb == Py_None) { + tb = 0; + } else if (tb && !PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto bad; + } + if (value == Py_None) + value = 0; + if (PyExceptionInstance_Check(type)) { + if (value) { + PyErr_SetString(PyExc_TypeError, + "instance exception may not have a separate value"); + goto bad; + } + value = type; + type = (PyObject*) Py_TYPE(value); + } else if (PyExceptionClass_Check(type)) { + PyObject *instance_class = NULL; + if (value && PyExceptionInstance_Check(value)) { + instance_class = (PyObject*) Py_TYPE(value); + if (instance_class != type) { + int is_subclass = PyObject_IsSubclass(instance_class, type); + if (!is_subclass) { + instance_class = NULL; + } else if (unlikely(is_subclass == -1)) { + goto bad; + } else { + type = instance_class; + } + } + } + if (!instance_class) { + PyObject *args; + if (!value) + args = PyTuple_New(0); + else if (PyTuple_Check(value)) { + Py_INCREF(value); + args = value; + } else + args = PyTuple_Pack(1, value); + if (!args) + goto bad; + owned_instance = PyObject_Call(type, args, NULL); + Py_DECREF(args); + if (!owned_instance) + goto bad; + value = owned_instance; + if (!PyExceptionInstance_Check(value)) { + PyErr_Format(PyExc_TypeError, + "calling %R should have returned an instance of " + "BaseException, not %R", + type, Py_TYPE(value)); + goto bad; + } + } + } else { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto bad; + } + if (cause) { + PyObject *fixed_cause; + if (cause == Py_None) { + fixed_cause = NULL; + } else if (PyExceptionClass_Check(cause)) { + fixed_cause = PyObject_CallObject(cause, NULL); + if (fixed_cause == NULL) + goto bad; + } else if (PyExceptionInstance_Check(cause)) { + fixed_cause = cause; + Py_INCREF(fixed_cause); + } else { + PyErr_SetString(PyExc_TypeError, + "exception causes must derive from " + "BaseException"); + goto bad; + } + PyException_SetCause(value, fixed_cause); + } + PyErr_SetObject(type, value); + if (tb) { +#if PY_VERSION_HEX >= 0x030C00A6 + PyException_SetTraceback(value, tb); +#elif CYTHON_FAST_THREAD_STATE + PyThreadState *tstate = __Pyx_PyThreadState_Current; + PyObject* tmp_tb = tstate->curexc_traceback; + if (tb != tmp_tb) { + Py_INCREF(tb); + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_tb); + } +#else + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyErr_Fetch(&tmp_type, &tmp_value, &tmp_tb); + Py_INCREF(tb); + PyErr_Restore(tmp_type, tmp_value, tb); + Py_XDECREF(tmp_tb); +#endif + } +bad: + Py_XDECREF(owned_instance); + return; +} + +/* GetException */ +#if CYTHON_FAST_THREAD_STATE +static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) +#else +static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb) +#endif +{ + PyObject *local_type = NULL, *local_value, *local_tb = NULL; +#if CYTHON_FAST_THREAD_STATE + PyObject *tmp_type, *tmp_value, *tmp_tb; + #if PY_VERSION_HEX >= 0x030C0000 + local_value = tstate->current_exception; + tstate->current_exception = 0; + #else + local_type = tstate->curexc_type; + local_value = tstate->curexc_value; + local_tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; + #endif +#elif __PYX_LIMITED_VERSION_HEX > 0x030C0000 + local_value = PyErr_GetRaisedException(); +#else + PyErr_Fetch(&local_type, &local_value, &local_tb); +#endif +#if __PYX_LIMITED_VERSION_HEX > 0x030C0000 + if (likely(local_value)) { + local_type = (PyObject*) Py_TYPE(local_value); + Py_INCREF(local_type); + local_tb = PyException_GetTraceback(local_value); + } +#else + PyErr_NormalizeException(&local_type, &local_value, &local_tb); +#if CYTHON_FAST_THREAD_STATE + if (unlikely(tstate->curexc_type)) +#else + if (unlikely(PyErr_Occurred())) +#endif + goto bad; + if (local_tb) { + if (unlikely(PyException_SetTraceback(local_value, local_tb) < 0)) + goto bad; + } +#endif // __PYX_LIMITED_VERSION_HEX > 0x030C0000 + Py_XINCREF(local_tb); + Py_XINCREF(local_type); + Py_XINCREF(local_value); + *type = local_type; + *value = local_value; + *tb = local_tb; +#if CYTHON_FAST_THREAD_STATE + #if CYTHON_USE_EXC_INFO_STACK + { + _PyErr_StackItem *exc_info = tstate->exc_info; + #if PY_VERSION_HEX >= 0x030B00a4 + tmp_value = exc_info->exc_value; + exc_info->exc_value = local_value; + tmp_type = NULL; + tmp_tb = NULL; + Py_XDECREF(local_type); + Py_XDECREF(local_tb); + #else + tmp_type = exc_info->exc_type; + tmp_value = exc_info->exc_value; + tmp_tb = exc_info->exc_traceback; + exc_info->exc_type = local_type; + exc_info->exc_value = local_value; + exc_info->exc_traceback = local_tb; + #endif + } + #else + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = local_type; + tstate->exc_value = local_value; + tstate->exc_traceback = local_tb; + #endif + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#elif __PYX_LIMITED_VERSION_HEX >= 0x030b0000 + PyErr_SetHandledException(local_value); + Py_XDECREF(local_value); + Py_XDECREF(local_type); + Py_XDECREF(local_tb); +#else + PyErr_SetExcInfo(local_type, local_value, local_tb); +#endif + return 0; +#if __PYX_LIMITED_VERSION_HEX <= 0x030C0000 +bad: + *type = 0; + *value = 0; + *tb = 0; + Py_XDECREF(local_type); + Py_XDECREF(local_value); + Py_XDECREF(local_tb); + return -1; +#endif +} + +/* SwapException */ +#if CYTHON_FAST_THREAD_STATE +static CYTHON_INLINE void __Pyx__ExceptionSwap(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { + PyObject *tmp_type, *tmp_value, *tmp_tb; + #if CYTHON_USE_EXC_INFO_STACK && PY_VERSION_HEX >= 0x030B00a4 + _PyErr_StackItem *exc_info = tstate->exc_info; + tmp_value = exc_info->exc_value; + exc_info->exc_value = *value; + if (tmp_value == NULL || tmp_value == Py_None) { + Py_XDECREF(tmp_value); + tmp_value = NULL; + tmp_type = NULL; + tmp_tb = NULL; + } else { + tmp_type = (PyObject*) Py_TYPE(tmp_value); + Py_INCREF(tmp_type); + #if CYTHON_COMPILING_IN_CPYTHON + tmp_tb = ((PyBaseExceptionObject*) tmp_value)->traceback; + Py_XINCREF(tmp_tb); + #else + tmp_tb = PyException_GetTraceback(tmp_value); + #endif + } + #elif CYTHON_USE_EXC_INFO_STACK + _PyErr_StackItem *exc_info = tstate->exc_info; + tmp_type = exc_info->exc_type; + tmp_value = exc_info->exc_value; + tmp_tb = exc_info->exc_traceback; + exc_info->exc_type = *type; + exc_info->exc_value = *value; + exc_info->exc_traceback = *tb; + #else + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = *type; + tstate->exc_value = *value; + tstate->exc_traceback = *tb; + #endif + *type = tmp_type; + *value = tmp_value; + *tb = tmp_tb; +} +#else +static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb) { + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyErr_GetExcInfo(&tmp_type, &tmp_value, &tmp_tb); + PyErr_SetExcInfo(*type, *value, *tb); + *type = tmp_type; + *value = tmp_value; + *tb = tmp_tb; +} +#endif + +/* GetTopmostException (used by SaveResetException) */ +#if CYTHON_USE_EXC_INFO_STACK && CYTHON_FAST_THREAD_STATE +static _PyErr_StackItem * +__Pyx_PyErr_GetTopmostException(PyThreadState *tstate) +{ + _PyErr_StackItem *exc_info = tstate->exc_info; + while ((exc_info->exc_value == NULL || exc_info->exc_value == Py_None) && + exc_info->previous_item != NULL) + { + exc_info = exc_info->previous_item; + } + return exc_info; +} +#endif + +/* SaveResetException */ +#if CYTHON_FAST_THREAD_STATE +static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { + #if CYTHON_USE_EXC_INFO_STACK && PY_VERSION_HEX >= 0x030B00a4 + _PyErr_StackItem *exc_info = __Pyx_PyErr_GetTopmostException(tstate); + PyObject *exc_value = exc_info->exc_value; + if (exc_value == NULL || exc_value == Py_None) { + *value = NULL; + *type = NULL; + *tb = NULL; + } else { + *value = exc_value; + Py_INCREF(*value); + *type = (PyObject*) Py_TYPE(exc_value); + Py_INCREF(*type); + *tb = PyException_GetTraceback(exc_value); + } + #elif CYTHON_USE_EXC_INFO_STACK + _PyErr_StackItem *exc_info = __Pyx_PyErr_GetTopmostException(tstate); + *type = exc_info->exc_type; + *value = exc_info->exc_value; + *tb = exc_info->exc_traceback; + Py_XINCREF(*type); + Py_XINCREF(*value); + Py_XINCREF(*tb); + #else + *type = tstate->exc_type; + *value = tstate->exc_value; + *tb = tstate->exc_traceback; + Py_XINCREF(*type); + Py_XINCREF(*value); + Py_XINCREF(*tb); + #endif +} +static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { + #if CYTHON_USE_EXC_INFO_STACK && PY_VERSION_HEX >= 0x030B00a4 + _PyErr_StackItem *exc_info = tstate->exc_info; + PyObject *tmp_value = exc_info->exc_value; + exc_info->exc_value = value; + Py_XDECREF(tmp_value); + Py_XDECREF(type); + Py_XDECREF(tb); + #else + PyObject *tmp_type, *tmp_value, *tmp_tb; + #if CYTHON_USE_EXC_INFO_STACK + _PyErr_StackItem *exc_info = tstate->exc_info; + tmp_type = exc_info->exc_type; + tmp_value = exc_info->exc_value; + tmp_tb = exc_info->exc_traceback; + exc_info->exc_type = type; + exc_info->exc_value = value; + exc_info->exc_traceback = tb; + #else + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = type; + tstate->exc_value = value; + tstate->exc_traceback = tb; + #endif + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); + #endif +} +#endif + +/* PyObjectFastCallMethod */ +#if !CYTHON_VECTORCALL || PY_VERSION_HEX < 0x03090000 +static PyObject *__Pyx_PyObject_FastCallMethod(PyObject *name, PyObject *const *args, size_t nargsf) { + PyObject *result; + PyObject *attr = PyObject_GetAttr(args[0], name); + if (unlikely(!attr)) + return NULL; + result = __Pyx_PyObject_FastCall(attr, args+1, nargsf - 1); + Py_DECREF(attr); + return result; +} +#endif + +/* ArgTypeTestFunc (used by ArgTypeTest) */ +static int __Pyx__ArgTypeTest(PyObject *obj, PyTypeObject *type, const char *name, int exact) +{ + __Pyx_TypeName type_name; + __Pyx_TypeName obj_type_name; + PyObject *extra_info = __pyx_mstate_global->__pyx_empty_unicode; + int from_annotation_subclass = 0; + if (unlikely(!type)) { + PyErr_SetString(PyExc_SystemError, "Missing type object"); + return 0; + } + else if (!exact) { + if (likely(__Pyx_TypeCheck(obj, type))) return 1; + } else if (exact == 2) { + if (__Pyx_TypeCheck(obj, type)) { + from_annotation_subclass = 1; + extra_info = __pyx_mstate_global->__pyx_kp_u_Note_that_Cython_is_deliberately; + } + } + type_name = __Pyx_PyType_GetFullyQualifiedName(type); + obj_type_name = __Pyx_PyType_GetFullyQualifiedName(Py_TYPE(obj)); + PyErr_Format(PyExc_TypeError, + "Argument '%.200s' has incorrect type (expected " __Pyx_FMT_TYPENAME + ", got " __Pyx_FMT_TYPENAME ")" +#if __PYX_LIMITED_VERSION_HEX < 0x030C0000 + "%s%U" +#endif + , name, type_name, obj_type_name +#if __PYX_LIMITED_VERSION_HEX < 0x030C0000 + , (from_annotation_subclass ? ". " : ""), extra_info +#endif + ); +#if __PYX_LIMITED_VERSION_HEX >= 0x030C0000 + if (exact == 2 && from_annotation_subclass) { + PyObject *res; + PyObject *vargs[2]; + vargs[0] = PyErr_GetRaisedException(); + vargs[1] = extra_info; + res = PyObject_VectorcallMethod(__pyx_mstate_global->__pyx_kp_u_add_note, vargs, 2, NULL); + Py_XDECREF(res); + PyErr_SetRaisedException(vargs[0]); + } +#endif + __Pyx_DECREF_TypeName(type_name); + __Pyx_DECREF_TypeName(obj_type_name); + return 0; +} + +/* RejectKeywords */ +static void __Pyx_RejectKeywords(const char* function_name, PyObject *kwds) { + PyObject *key = NULL; + if (CYTHON_METH_FASTCALL && likely(PyTuple_Check(kwds))) { + key = __Pyx_PySequence_ITEM(kwds, 0); + } else { +#if CYTHON_AVOID_BORROWED_REFS + PyObject *pos = NULL; +#else + Py_ssize_t pos = 0; +#endif +#if !CYTHON_COMPILING_IN_PYPY || defined(PyArg_ValidateKeywordArguments) + if (unlikely(!PyArg_ValidateKeywordArguments(kwds))) return; +#endif + __Pyx_PyDict_NextRef(kwds, &pos, &key, NULL); +#if CYTHON_AVOID_BORROWED_REFS + Py_XDECREF(pos); +#endif + } + if (likely(key)) { + PyErr_Format(PyExc_TypeError, + "%s() got an unexpected keyword argument '%U'", + function_name, key); + Py_DECREF(key); + } +} + +/* GetAttr3 */ +#if __PYX_LIMITED_VERSION_HEX < 0x030d0000 +static PyObject *__Pyx_GetAttr3Default(PyObject *d) { + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + if (unlikely(!__Pyx_PyErr_ExceptionMatches(PyExc_AttributeError))) + return NULL; + __Pyx_PyErr_Clear(); + Py_INCREF(d); + return d; +} +#endif +static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *o, PyObject *n, PyObject *d) { + PyObject *r; +#if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + int res = PyObject_GetOptionalAttr(o, n, &r); + return (res != 0) ? r : __Pyx_NewRef(d); +#else + #if CYTHON_USE_TYPE_SLOTS + if (likely(PyUnicode_Check(n))) { + r = __Pyx_PyObject_GetAttrStrNoError(o, n); + if (unlikely(!r) && likely(!PyErr_Occurred())) { + r = __Pyx_NewRef(d); + } + return r; + } + #endif + r = PyObject_GetAttr(o, n); + return (likely(r)) ? r : __Pyx_GetAttr3Default(d); +#endif +} + +/* RaiseUnexpectedTypeError */ +static int +__Pyx_RaiseUnexpectedTypeError(const char *expected, PyObject *obj) +{ + __Pyx_TypeName obj_type_name = __Pyx_PyType_GetFullyQualifiedName(Py_TYPE(obj)); + PyErr_Format(PyExc_TypeError, "Expected %s, got " __Pyx_FMT_TYPENAME, + expected, obj_type_name); + __Pyx_DECREF_TypeName(obj_type_name); + return 0; +} + +/* GetItemInt */ +static PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) { + PyObject *r; + if (unlikely(!j)) return NULL; + r = PyObject_GetItem(o, j); + Py_DECREF(j); + return r; +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck, int unsafe_shared) { + CYTHON_MAYBE_UNUSED_VAR(unsafe_shared); +#if CYTHON_ASSUME_SAFE_SIZE + Py_ssize_t wrapped_i = i; + if (wraparound & unlikely(i < 0)) { + wrapped_i += PyList_GET_SIZE(o); + } + if ((CYTHON_AVOID_BORROWED_REFS || CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS || !CYTHON_ASSUME_SAFE_MACROS)) { + return __Pyx_PyList_GetItemRefFast(o, wrapped_i, unsafe_shared); + } else + if ((!boundscheck) || likely(__Pyx_is_valid_index(wrapped_i, PyList_GET_SIZE(o)))) { + return __Pyx_NewRef(PyList_GET_ITEM(o, wrapped_i)); + } + return __Pyx_GetItemInt_Generic(o, PyLong_FromSsize_t(i)); +#else + (void)wraparound; + (void)boundscheck; + return PySequence_GetItem(o, i); +#endif +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck, int unsafe_shared) { + CYTHON_MAYBE_UNUSED_VAR(unsafe_shared); +#if CYTHON_ASSUME_SAFE_SIZE && CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + Py_ssize_t wrapped_i = i; + if (wraparound & unlikely(i < 0)) { + wrapped_i += PyTuple_GET_SIZE(o); + } + if ((!boundscheck) || likely(__Pyx_is_valid_index(wrapped_i, PyTuple_GET_SIZE(o)))) { + return __Pyx_NewRef(PyTuple_GET_ITEM(o, wrapped_i)); + } + return __Pyx_GetItemInt_Generic(o, PyLong_FromSsize_t(i)); +#else + (void)wraparound; + (void)boundscheck; + return PySequence_GetItem(o, i); +#endif +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, int is_list, + int wraparound, int boundscheck, int unsafe_shared) { + CYTHON_MAYBE_UNUSED_VAR(unsafe_shared); +#if CYTHON_ASSUME_SAFE_MACROS && CYTHON_ASSUME_SAFE_SIZE + if (is_list || PyList_CheckExact(o)) { + Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyList_GET_SIZE(o); + if ((CYTHON_AVOID_BORROWED_REFS || CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS)) { + return __Pyx_PyList_GetItemRefFast(o, n, unsafe_shared); + } else if ((!boundscheck) || (likely(__Pyx_is_valid_index(n, PyList_GET_SIZE(o))))) { + return __Pyx_NewRef(PyList_GET_ITEM(o, n)); + } + } else + #if !CYTHON_AVOID_BORROWED_REFS + if (PyTuple_CheckExact(o)) { + Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyTuple_GET_SIZE(o); + if ((!boundscheck) || likely(__Pyx_is_valid_index(n, PyTuple_GET_SIZE(o)))) { + return __Pyx_NewRef(PyTuple_GET_ITEM(o, n)); + } + } else + #endif +#endif +#if CYTHON_USE_TYPE_SLOTS && !CYTHON_COMPILING_IN_PYPY + { + PyMappingMethods *mm = Py_TYPE(o)->tp_as_mapping; + PySequenceMethods *sm = Py_TYPE(o)->tp_as_sequence; + if (!is_list && mm && mm->mp_subscript) { + PyObject *r, *key = PyLong_FromSsize_t(i); + if (unlikely(!key)) return NULL; + r = mm->mp_subscript(o, key); + Py_DECREF(key); + return r; + } + if (is_list || likely(sm && sm->sq_item)) { + if (wraparound && unlikely(i < 0) && likely(sm->sq_length)) { + Py_ssize_t l = sm->sq_length(o); + if (likely(l >= 0)) { + i += l; + } else { + if (!PyErr_ExceptionMatches(PyExc_OverflowError)) + return NULL; + PyErr_Clear(); + } + } + return sm->sq_item(o, i); + } + } +#else + if (is_list || !PyMapping_Check(o)) { + return PySequence_GetItem(o, i); + } +#endif + (void)wraparound; + (void)boundscheck; + return __Pyx_GetItemInt_Generic(o, PyLong_FromSsize_t(i)); +} + +/* ExtTypeTest */ +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { + __Pyx_TypeName obj_type_name; + __Pyx_TypeName type_name; + if (unlikely(!type)) { + PyErr_SetString(PyExc_SystemError, "Missing type object"); + return 0; + } + if (likely(__Pyx_TypeCheck(obj, type))) + return 1; + obj_type_name = __Pyx_PyType_GetFullyQualifiedName(Py_TYPE(obj)); + type_name = __Pyx_PyType_GetFullyQualifiedName(type); + PyErr_Format(PyExc_TypeError, + "Cannot convert " __Pyx_FMT_TYPENAME " to " __Pyx_FMT_TYPENAME, + obj_type_name, type_name); + __Pyx_DECREF_TypeName(obj_type_name); + __Pyx_DECREF_TypeName(type_name); + return 0; +} + +/* CallNextTpDealloc */ +static void __Pyx_call_next_tp_dealloc(PyObject* obj, destructor current_tp_dealloc) { + PyTypeObject* type = Py_TYPE(obj); + destructor tp_dealloc = NULL; + while (type && __Pyx_PyType_GetSlot(type, tp_dealloc, destructor) != current_tp_dealloc) + type = __Pyx_PyType_GetSlot(type, tp_base, PyTypeObject*); + while (type && (tp_dealloc = __Pyx_PyType_GetSlot(type, tp_dealloc, destructor)) == current_tp_dealloc) + type = __Pyx_PyType_GetSlot(type, tp_base, PyTypeObject*); + if (type) + tp_dealloc(obj); +} + +/* CallNextTpTraverse */ +static int __Pyx_call_next_tp_traverse(PyObject* obj, visitproc v, void *a, traverseproc current_tp_traverse) { + PyTypeObject* type = Py_TYPE(obj); + traverseproc tp_traverse = NULL; + while (type && __Pyx_PyType_GetSlot(type, tp_traverse, traverseproc) != current_tp_traverse) + type = __Pyx_PyType_GetSlot(type, tp_base, PyTypeObject*); + while (type && (tp_traverse = __Pyx_PyType_GetSlot(type, tp_traverse, traverseproc)) == current_tp_traverse) + type = __Pyx_PyType_GetSlot(type, tp_base, PyTypeObject*); + if (type && tp_traverse) + return tp_traverse(obj, v, a); + return 0; +} + +/* CallTypeTraverse */ +#if !CYTHON_USE_TYPE_SPECS || (!CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x03090000) +#else +static int __Pyx_call_type_traverse(PyObject *o, int always_call, visitproc visit, void *arg) { + #if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x03090000 + if (__Pyx_get_runtime_version() < 0x03090000) return 0; + #endif + if (!always_call) { + PyTypeObject *base = __Pyx_PyObject_GetSlot(o, tp_base, PyTypeObject*); + unsigned long flags = PyType_GetFlags(base); + if (flags & Py_TPFLAGS_HEAPTYPE) { + return 0; + } + } + Py_VISIT((PyObject*)Py_TYPE(o)); + return 0; +} +#endif + +/* CallNextTpClear */ +static void __Pyx_call_next_tp_clear(PyObject* obj, inquiry current_tp_clear) { + PyTypeObject* type = Py_TYPE(obj); + inquiry tp_clear = NULL; + while (type && __Pyx_PyType_GetSlot(type, tp_clear, inquiry) != current_tp_clear) + type = __Pyx_PyType_GetSlot(type, tp_base, PyTypeObject*); + while (type && (tp_clear = __Pyx_PyType_GetSlot(type, tp_clear, inquiry)) == current_tp_clear) + type = __Pyx_PyType_GetSlot(type, tp_base, PyTypeObject*); + if (type && tp_clear) + tp_clear(obj); +} + +/* TypeImport */ +#ifndef __PYX_HAVE_RT_ImportType_3_2_4 +#define __PYX_HAVE_RT_ImportType_3_2_4 +static PyTypeObject *__Pyx_ImportType_3_2_4(PyObject *module, const char *module_name, const char *class_name, + size_t size, size_t alignment, enum __Pyx_ImportType_CheckSize_3_2_4 check_size) +{ + PyObject *result = 0; + Py_ssize_t basicsize; + Py_ssize_t itemsize; +#if defined(Py_LIMITED_API) || (defined(CYTHON_COMPILING_IN_LIMITED_API) && CYTHON_COMPILING_IN_LIMITED_API) + PyObject *py_basicsize; + PyObject *py_itemsize; +#endif + result = PyObject_GetAttrString(module, class_name); + if (!result) + goto bad; + if (!PyType_Check(result)) { + PyErr_Format(PyExc_TypeError, + "%.200s.%.200s is not a type object", + module_name, class_name); + goto bad; + } +#if !( defined(Py_LIMITED_API) || (defined(CYTHON_COMPILING_IN_LIMITED_API) && CYTHON_COMPILING_IN_LIMITED_API) ) + basicsize = ((PyTypeObject *)result)->tp_basicsize; + itemsize = ((PyTypeObject *)result)->tp_itemsize; +#else + if (size == 0) { + return (PyTypeObject *)result; + } + py_basicsize = PyObject_GetAttrString(result, "__basicsize__"); + if (!py_basicsize) + goto bad; + basicsize = PyLong_AsSsize_t(py_basicsize); + Py_DECREF(py_basicsize); + py_basicsize = 0; + if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred()) + goto bad; + py_itemsize = PyObject_GetAttrString(result, "__itemsize__"); + if (!py_itemsize) + goto bad; + itemsize = PyLong_AsSsize_t(py_itemsize); + Py_DECREF(py_itemsize); + py_itemsize = 0; + if (itemsize == (Py_ssize_t)-1 && PyErr_Occurred()) + goto bad; +#endif + if (itemsize) { + if (size % alignment) { + alignment = size % alignment; + } + if (itemsize < (Py_ssize_t)alignment) + itemsize = (Py_ssize_t)alignment; + } + if ((size_t)(basicsize + itemsize) < size) { + PyErr_Format(PyExc_ValueError, + "%.200s.%.200s size changed, may indicate binary incompatibility. " + "Expected %zd from C header, got %zd from PyObject", + module_name, class_name, size, basicsize+itemsize); + goto bad; + } + if (check_size == __Pyx_ImportType_CheckSize_Error_3_2_4 && + ((size_t)basicsize > size || (size_t)(basicsize + itemsize) < size)) { + PyErr_Format(PyExc_ValueError, + "%.200s.%.200s size changed, may indicate binary incompatibility. " + "Expected %zd from C header, got %zd-%zd from PyObject", + module_name, class_name, size, basicsize, basicsize+itemsize); + goto bad; + } + else if (check_size == __Pyx_ImportType_CheckSize_Warn_3_2_4 && (size_t)basicsize > size) { + if (PyErr_WarnFormat(NULL, 0, + "%.200s.%.200s size changed, may indicate binary incompatibility. " + "Expected %zd from C header, got %zd from PyObject", + module_name, class_name, size, basicsize) < 0) { + goto bad; + } + } + return (PyTypeObject *)result; +bad: + Py_XDECREF(result); + return NULL; +} +#endif + +/* GetVTable */ +static void* __Pyx_GetVtable(PyTypeObject *type) { + void* ptr; +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *ob = PyObject_GetAttr((PyObject *)type, __pyx_mstate_global->__pyx_n_u_pyx_vtable); +#else + PyObject *ob = PyObject_GetItem(type->tp_dict, __pyx_mstate_global->__pyx_n_u_pyx_vtable); +#endif + if (!ob) + goto bad; + ptr = PyCapsule_GetPointer(ob, 0); + if (!ptr && !PyErr_Occurred()) + PyErr_SetString(PyExc_RuntimeError, "invalid vtable found for imported type"); + Py_DECREF(ob); + return ptr; +bad: + Py_XDECREF(ob); + return NULL; +} + +/* LimitedApiGetTypeDict (used by SetItemOnTypeDict) */ +#if CYTHON_COMPILING_IN_LIMITED_API +static Py_ssize_t __Pyx_GetTypeDictOffset(void) { + PyObject *tp_dictoffset_o; + Py_ssize_t tp_dictoffset; + tp_dictoffset_o = PyObject_GetAttrString((PyObject*)(&PyType_Type), "__dictoffset__"); + if (unlikely(!tp_dictoffset_o)) return -1; + tp_dictoffset = PyLong_AsSsize_t(tp_dictoffset_o); + Py_DECREF(tp_dictoffset_o); + if (unlikely(tp_dictoffset == 0)) { + PyErr_SetString( + PyExc_TypeError, + "'type' doesn't have a dictoffset"); + return -1; + } else if (unlikely(tp_dictoffset < 0)) { + PyErr_SetString( + PyExc_TypeError, + "'type' has an unexpected negative dictoffset. " + "Please report this as Cython bug"); + return -1; + } + return tp_dictoffset; +} +static PyObject *__Pyx_GetTypeDict(PyTypeObject *tp) { + static Py_ssize_t tp_dictoffset = 0; + if (unlikely(tp_dictoffset == 0)) { + tp_dictoffset = __Pyx_GetTypeDictOffset(); + if (unlikely(tp_dictoffset == -1 && PyErr_Occurred())) { + tp_dictoffset = 0; // try again next time? + return NULL; + } + } + return *(PyObject**)((char*)tp + tp_dictoffset); +} +#endif + +/* SetItemOnTypeDict (used by FixUpExtensionType) */ +static int __Pyx__SetItemOnTypeDict(PyTypeObject *tp, PyObject *k, PyObject *v) { + int result; + PyObject *tp_dict; +#if CYTHON_COMPILING_IN_LIMITED_API + tp_dict = __Pyx_GetTypeDict(tp); + if (unlikely(!tp_dict)) return -1; +#else + tp_dict = tp->tp_dict; +#endif + result = PyDict_SetItem(tp_dict, k, v); + if (likely(!result)) { + PyType_Modified(tp); + if (unlikely(PyObject_HasAttr(v, __pyx_mstate_global->__pyx_n_u_set_name))) { + PyObject *setNameResult = PyObject_CallMethodObjArgs(v, __pyx_mstate_global->__pyx_n_u_set_name, (PyObject *) tp, k, NULL); + if (!setNameResult) return -1; + Py_DECREF(setNameResult); + } + } + return result; +} + +/* FixUpExtensionType */ +static int __Pyx_fix_up_extension_type_from_spec(PyType_Spec *spec, PyTypeObject *type) { +#if __PYX_LIMITED_VERSION_HEX > 0x030900B1 + CYTHON_UNUSED_VAR(spec); + CYTHON_UNUSED_VAR(type); + CYTHON_UNUSED_VAR(__Pyx__SetItemOnTypeDict); +#else + const PyType_Slot *slot = spec->slots; + int changed = 0; +#if !CYTHON_COMPILING_IN_LIMITED_API + while (slot && slot->slot && slot->slot != Py_tp_members) + slot++; + if (slot && slot->slot == Py_tp_members) { +#if !CYTHON_COMPILING_IN_CPYTHON + const +#endif // !CYTHON_COMPILING_IN_CPYTHON) + PyMemberDef *memb = (PyMemberDef*) slot->pfunc; + while (memb && memb->name) { + if (memb->name[0] == '_' && memb->name[1] == '_') { + if (strcmp(memb->name, "__weaklistoffset__") == 0) { + assert(memb->type == T_PYSSIZET); + assert(memb->flags == READONLY); + type->tp_weaklistoffset = memb->offset; + changed = 1; + } + else if (strcmp(memb->name, "__dictoffset__") == 0) { + assert(memb->type == T_PYSSIZET); + assert(memb->flags == READONLY); + type->tp_dictoffset = memb->offset; + changed = 1; + } +#if CYTHON_METH_FASTCALL + else if (strcmp(memb->name, "__vectorcalloffset__") == 0) { + assert(memb->type == T_PYSSIZET); + assert(memb->flags == READONLY); + type->tp_vectorcall_offset = memb->offset; + changed = 1; + } +#endif // CYTHON_METH_FASTCALL +#if !CYTHON_COMPILING_IN_PYPY + else if (strcmp(memb->name, "__module__") == 0) { + PyObject *descr; + assert(memb->type == T_OBJECT); + assert(memb->flags == 0 || memb->flags == READONLY); + descr = PyDescr_NewMember(type, memb); + if (unlikely(!descr)) + return -1; + int set_item_result = PyDict_SetItem(type->tp_dict, PyDescr_NAME(descr), descr); + Py_DECREF(descr); + if (unlikely(set_item_result < 0)) { + return -1; + } + changed = 1; + } +#endif // !CYTHON_COMPILING_IN_PYPY + } + memb++; + } + } +#endif // !CYTHON_COMPILING_IN_LIMITED_API +#if !CYTHON_COMPILING_IN_PYPY + slot = spec->slots; + while (slot && slot->slot && slot->slot != Py_tp_getset) + slot++; + if (slot && slot->slot == Py_tp_getset) { + PyGetSetDef *getset = (PyGetSetDef*) slot->pfunc; + while (getset && getset->name) { + if (getset->name[0] == '_' && getset->name[1] == '_' && strcmp(getset->name, "__module__") == 0) { + PyObject *descr = PyDescr_NewGetSet(type, getset); + if (unlikely(!descr)) + return -1; + #if CYTHON_COMPILING_IN_LIMITED_API + PyObject *pyname = PyUnicode_FromString(getset->name); + if (unlikely(!pyname)) { + Py_DECREF(descr); + return -1; + } + int set_item_result = __Pyx_SetItemOnTypeDict(type, pyname, descr); + Py_DECREF(pyname); + #else + CYTHON_UNUSED_VAR(__Pyx__SetItemOnTypeDict); + int set_item_result = PyDict_SetItem(type->tp_dict, PyDescr_NAME(descr), descr); + #endif + Py_DECREF(descr); + if (unlikely(set_item_result < 0)) { + return -1; + } + changed = 1; + } + ++getset; + } + } +#else + CYTHON_UNUSED_VAR(__Pyx__SetItemOnTypeDict); +#endif // !CYTHON_COMPILING_IN_PYPY + if (changed) + PyType_Modified(type); +#endif // PY_VERSION_HEX > 0x030900B1 + return 0; +} + +/* PyObjectCallNoArg (used by PyObjectCallMethod0) */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func) { + PyObject *arg[2] = {NULL, NULL}; + return __Pyx_PyObject_FastCall(func, arg + 1, 0 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET); +} + +/* PyObjectGetMethod (used by PyObjectCallMethod0) */ +#if !(CYTHON_VECTORCALL && (__PYX_LIMITED_VERSION_HEX >= 0x030C0000 || (!CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x03090000))) +static int __Pyx_PyObject_GetMethod(PyObject *obj, PyObject *name, PyObject **method) { + PyObject *attr; +#if CYTHON_UNPACK_METHODS && CYTHON_COMPILING_IN_CPYTHON && CYTHON_USE_PYTYPE_LOOKUP + __Pyx_TypeName type_name; + PyTypeObject *tp = Py_TYPE(obj); + PyObject *descr; + descrgetfunc f = NULL; + PyObject **dictptr, *dict; + int meth_found = 0; + assert (*method == NULL); + if (unlikely(tp->tp_getattro != PyObject_GenericGetAttr)) { + attr = __Pyx_PyObject_GetAttrStr(obj, name); + goto try_unpack; + } + if (unlikely(tp->tp_dict == NULL) && unlikely(PyType_Ready(tp) < 0)) { + return 0; + } + descr = _PyType_Lookup(tp, name); + if (likely(descr != NULL)) { + Py_INCREF(descr); +#if defined(Py_TPFLAGS_METHOD_DESCRIPTOR) && Py_TPFLAGS_METHOD_DESCRIPTOR + if (__Pyx_PyType_HasFeature(Py_TYPE(descr), Py_TPFLAGS_METHOD_DESCRIPTOR)) +#else + #ifdef __Pyx_CyFunction_USED + if (likely(PyFunction_Check(descr) || __Pyx_IS_TYPE(descr, &PyMethodDescr_Type) || __Pyx_CyFunction_Check(descr))) + #else + if (likely(PyFunction_Check(descr) || __Pyx_IS_TYPE(descr, &PyMethodDescr_Type))) + #endif +#endif + { + meth_found = 1; + } else { + f = Py_TYPE(descr)->tp_descr_get; + if (f != NULL && PyDescr_IsData(descr)) { + attr = f(descr, obj, (PyObject *)Py_TYPE(obj)); + Py_DECREF(descr); + goto try_unpack; + } + } + } + dictptr = _PyObject_GetDictPtr(obj); + if (dictptr != NULL && (dict = *dictptr) != NULL) { + Py_INCREF(dict); + attr = __Pyx_PyDict_GetItemStr(dict, name); + if (attr != NULL) { + Py_INCREF(attr); + Py_DECREF(dict); + Py_XDECREF(descr); + goto try_unpack; + } + Py_DECREF(dict); + } + if (meth_found) { + *method = descr; + return 1; + } + if (f != NULL) { + attr = f(descr, obj, (PyObject *)Py_TYPE(obj)); + Py_DECREF(descr); + goto try_unpack; + } + if (likely(descr != NULL)) { + *method = descr; + return 0; + } + type_name = __Pyx_PyType_GetFullyQualifiedName(tp); + PyErr_Format(PyExc_AttributeError, + "'" __Pyx_FMT_TYPENAME "' object has no attribute '%U'", + type_name, name); + __Pyx_DECREF_TypeName(type_name); + return 0; +#else + attr = __Pyx_PyObject_GetAttrStr(obj, name); + goto try_unpack; +#endif +try_unpack: +#if CYTHON_UNPACK_METHODS + if (likely(attr) && PyMethod_Check(attr) && likely(PyMethod_GET_SELF(attr) == obj)) { + PyObject *function = PyMethod_GET_FUNCTION(attr); + Py_INCREF(function); + Py_DECREF(attr); + *method = function; + return 1; + } +#endif + *method = attr; + return 0; +} +#endif + +/* PyObjectCallMethod0 (used by PyType_Ready) */ +static PyObject* __Pyx_PyObject_CallMethod0(PyObject* obj, PyObject* method_name) { +#if CYTHON_VECTORCALL && (__PYX_LIMITED_VERSION_HEX >= 0x030C0000 || (!CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x03090000)) + PyObject *args[1] = {obj}; + (void) __Pyx_PyObject_CallOneArg; + (void) __Pyx_PyObject_CallNoArg; + return PyObject_VectorcallMethod(method_name, args, 1 | PY_VECTORCALL_ARGUMENTS_OFFSET, NULL); +#else + PyObject *method = NULL, *result = NULL; + int is_method = __Pyx_PyObject_GetMethod(obj, method_name, &method); + if (likely(is_method)) { + result = __Pyx_PyObject_CallOneArg(method, obj); + Py_DECREF(method); + return result; + } + if (unlikely(!method)) goto bad; + result = __Pyx_PyObject_CallNoArg(method); + Py_DECREF(method); +bad: + return result; +#endif +} + +/* ValidateBasesTuple (used by PyType_Ready) */ +#if CYTHON_COMPILING_IN_CPYTHON || CYTHON_COMPILING_IN_LIMITED_API || CYTHON_USE_TYPE_SPECS +static int __Pyx_validate_bases_tuple(const char *type_name, Py_ssize_t dictoffset, PyObject *bases) { + Py_ssize_t i, n; +#if CYTHON_ASSUME_SAFE_SIZE + n = PyTuple_GET_SIZE(bases); +#else + n = PyTuple_Size(bases); + if (unlikely(n < 0)) return -1; +#endif + for (i = 1; i < n; i++) + { + PyTypeObject *b; +#if CYTHON_AVOID_BORROWED_REFS + PyObject *b0 = PySequence_GetItem(bases, i); + if (!b0) return -1; +#elif CYTHON_ASSUME_SAFE_MACROS + PyObject *b0 = PyTuple_GET_ITEM(bases, i); +#else + PyObject *b0 = PyTuple_GetItem(bases, i); + if (!b0) return -1; +#endif + b = (PyTypeObject*) b0; + if (!__Pyx_PyType_HasFeature(b, Py_TPFLAGS_HEAPTYPE)) + { + __Pyx_TypeName b_name = __Pyx_PyType_GetFullyQualifiedName(b); + PyErr_Format(PyExc_TypeError, + "base class '" __Pyx_FMT_TYPENAME "' is not a heap type", b_name); + __Pyx_DECREF_TypeName(b_name); +#if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(b0); +#endif + return -1; + } + if (dictoffset == 0) + { + Py_ssize_t b_dictoffset = 0; +#if CYTHON_USE_TYPE_SLOTS + b_dictoffset = b->tp_dictoffset; +#else + PyObject *py_b_dictoffset = PyObject_GetAttrString((PyObject*)b, "__dictoffset__"); + if (!py_b_dictoffset) goto dictoffset_return; + b_dictoffset = PyLong_AsSsize_t(py_b_dictoffset); + Py_DECREF(py_b_dictoffset); + if (b_dictoffset == -1 && PyErr_Occurred()) goto dictoffset_return; +#endif + if (b_dictoffset) { + { + __Pyx_TypeName b_name = __Pyx_PyType_GetFullyQualifiedName(b); + PyErr_Format(PyExc_TypeError, + "extension type '%.200s' has no __dict__ slot, " + "but base type '" __Pyx_FMT_TYPENAME "' has: " + "either add 'cdef dict __dict__' to the extension type " + "or add '__slots__ = [...]' to the base type", + type_name, b_name); + __Pyx_DECREF_TypeName(b_name); + } +#if !CYTHON_USE_TYPE_SLOTS + dictoffset_return: +#endif +#if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(b0); +#endif + return -1; + } + } +#if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(b0); +#endif + } + return 0; +} +#endif + +/* PyType_Ready */ +CYTHON_UNUSED static int __Pyx_PyType_HasMultipleInheritance(PyTypeObject *t) { + while (t) { + PyObject *bases = __Pyx_PyType_GetSlot(t, tp_bases, PyObject*); + if (bases) { + return 1; + } + t = __Pyx_PyType_GetSlot(t, tp_base, PyTypeObject*); + } + return 0; +} +static int __Pyx_PyType_Ready(PyTypeObject *t) { +#if CYTHON_USE_TYPE_SPECS || !CYTHON_COMPILING_IN_CPYTHON || defined(PYSTON_MAJOR_VERSION) + (void)__Pyx_PyObject_CallMethod0; +#if CYTHON_USE_TYPE_SPECS + (void)__Pyx_validate_bases_tuple; +#endif + return PyType_Ready(t); +#else + int r; + if (!__Pyx_PyType_HasMultipleInheritance(t)) { + return PyType_Ready(t); + } + PyObject *bases = __Pyx_PyType_GetSlot(t, tp_bases, PyObject*); + if (bases && unlikely(__Pyx_validate_bases_tuple(t->tp_name, t->tp_dictoffset, bases) == -1)) + return -1; +#if !defined(PYSTON_MAJOR_VERSION) + { + int gc_was_enabled; + #if PY_VERSION_HEX >= 0x030A00b1 + gc_was_enabled = PyGC_Disable(); + (void)__Pyx_PyObject_CallMethod0; + #else + PyObject *ret, *py_status; + PyObject *gc = NULL; + #if (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM+0 >= 0x07030400) &&\ + !CYTHON_COMPILING_IN_GRAAL + gc = PyImport_GetModule(__pyx_mstate_global->__pyx_kp_u_gc); + #endif + if (unlikely(!gc)) gc = PyImport_Import(__pyx_mstate_global->__pyx_kp_u_gc); + if (unlikely(!gc)) return -1; + py_status = __Pyx_PyObject_CallMethod0(gc, __pyx_mstate_global->__pyx_kp_u_isenabled); + if (unlikely(!py_status)) { + Py_DECREF(gc); + return -1; + } + gc_was_enabled = __Pyx_PyObject_IsTrue(py_status); + Py_DECREF(py_status); + if (gc_was_enabled > 0) { + ret = __Pyx_PyObject_CallMethod0(gc, __pyx_mstate_global->__pyx_kp_u_disable); + if (unlikely(!ret)) { + Py_DECREF(gc); + return -1; + } + Py_DECREF(ret); + } else if (unlikely(gc_was_enabled == -1)) { + Py_DECREF(gc); + return -1; + } + #endif + t->tp_flags |= Py_TPFLAGS_HEAPTYPE; +#if PY_VERSION_HEX >= 0x030A0000 + t->tp_flags |= Py_TPFLAGS_IMMUTABLETYPE; +#endif +#else + (void)__Pyx_PyObject_CallMethod0; +#endif + r = PyType_Ready(t); +#if !defined(PYSTON_MAJOR_VERSION) + t->tp_flags &= ~Py_TPFLAGS_HEAPTYPE; + #if PY_VERSION_HEX >= 0x030A00b1 + if (gc_was_enabled) + PyGC_Enable(); + #else + if (gc_was_enabled) { + PyObject *tp, *v, *tb; + PyErr_Fetch(&tp, &v, &tb); + ret = __Pyx_PyObject_CallMethod0(gc, __pyx_mstate_global->__pyx_kp_u_enable); + if (likely(ret || r == -1)) { + Py_XDECREF(ret); + PyErr_Restore(tp, v, tb); + } else { + Py_XDECREF(tp); + Py_XDECREF(v); + Py_XDECREF(tb); + r = -1; + } + } + Py_DECREF(gc); + #endif + } +#endif + return r; +#endif +} + +/* SetVTable */ +static int __Pyx_SetVtable(PyTypeObject *type, void *vtable) { + PyObject *ob = PyCapsule_New(vtable, 0, 0); + if (unlikely(!ob)) + goto bad; +#if CYTHON_COMPILING_IN_LIMITED_API + if (unlikely(PyObject_SetAttr((PyObject *) type, __pyx_mstate_global->__pyx_n_u_pyx_vtable, ob) < 0)) +#else + if (unlikely(PyDict_SetItem(type->tp_dict, __pyx_mstate_global->__pyx_n_u_pyx_vtable, ob) < 0)) +#endif + goto bad; + Py_DECREF(ob); + return 0; +bad: + Py_XDECREF(ob); + return -1; +} + +/* MergeVTables */ +static int __Pyx_MergeVtables(PyTypeObject *type) { + int i=0; + Py_ssize_t size; + void** base_vtables; + __Pyx_TypeName tp_base_name = NULL; + __Pyx_TypeName base_name = NULL; + void* unknown = (void*)-1; + PyObject* bases = __Pyx_PyType_GetSlot(type, tp_bases, PyObject*); + int base_depth = 0; + { + PyTypeObject* base = __Pyx_PyType_GetSlot(type, tp_base, PyTypeObject*); + while (base) { + base_depth += 1; + base = __Pyx_PyType_GetSlot(base, tp_base, PyTypeObject*); + } + } + base_vtables = (void**) PyMem_Malloc(sizeof(void*) * (size_t)(base_depth + 1)); + base_vtables[0] = unknown; +#if CYTHON_COMPILING_IN_LIMITED_API + size = PyTuple_Size(bases); + if (size < 0) goto other_failure; +#else + size = PyTuple_GET_SIZE(bases); +#endif + for (i = 1; i < size; i++) { + PyObject *basei; + void* base_vtable; +#if CYTHON_AVOID_BORROWED_REFS + basei = PySequence_GetItem(bases, i); + if (unlikely(!basei)) goto other_failure; +#elif !CYTHON_ASSUME_SAFE_MACROS + basei = PyTuple_GetItem(bases, i); + if (unlikely(!basei)) goto other_failure; +#else + basei = PyTuple_GET_ITEM(bases, i); +#endif + base_vtable = __Pyx_GetVtable((PyTypeObject*)basei); +#if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(basei); +#endif + if (base_vtable != NULL) { + int j; + PyTypeObject* base = __Pyx_PyType_GetSlot(type, tp_base, PyTypeObject*); + for (j = 0; j < base_depth; j++) { + if (base_vtables[j] == unknown) { + base_vtables[j] = __Pyx_GetVtable(base); + base_vtables[j + 1] = unknown; + } + if (base_vtables[j] == base_vtable) { + break; + } else if (base_vtables[j] == NULL) { + goto bad; + } + base = __Pyx_PyType_GetSlot(base, tp_base, PyTypeObject*); + } + } + } + PyErr_Clear(); + PyMem_Free(base_vtables); + return 0; +bad: + { + PyTypeObject* basei = NULL; + PyTypeObject* tp_base = __Pyx_PyType_GetSlot(type, tp_base, PyTypeObject*); + tp_base_name = __Pyx_PyType_GetFullyQualifiedName(tp_base); +#if CYTHON_AVOID_BORROWED_REFS + basei = (PyTypeObject*)PySequence_GetItem(bases, i); + if (unlikely(!basei)) goto really_bad; +#elif !CYTHON_ASSUME_SAFE_MACROS + basei = (PyTypeObject*)PyTuple_GetItem(bases, i); + if (unlikely(!basei)) goto really_bad; +#else + basei = (PyTypeObject*)PyTuple_GET_ITEM(bases, i); +#endif + base_name = __Pyx_PyType_GetFullyQualifiedName(basei); +#if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(basei); +#endif + } + PyErr_Format(PyExc_TypeError, + "multiple bases have vtable conflict: '" __Pyx_FMT_TYPENAME "' and '" __Pyx_FMT_TYPENAME "'", tp_base_name, base_name); +#if CYTHON_AVOID_BORROWED_REFS || !CYTHON_ASSUME_SAFE_MACROS +really_bad: // bad has failed! +#endif + __Pyx_DECREF_TypeName(tp_base_name); + __Pyx_DECREF_TypeName(base_name); +#if CYTHON_COMPILING_IN_LIMITED_API || CYTHON_AVOID_BORROWED_REFS || !CYTHON_ASSUME_SAFE_MACROS +other_failure: +#endif + PyMem_Free(base_vtables); + return -1; +} + +/* DelItemOnTypeDict (used by SetupReduce) */ +static int __Pyx__DelItemOnTypeDict(PyTypeObject *tp, PyObject *k) { + int result; + PyObject *tp_dict; +#if CYTHON_COMPILING_IN_LIMITED_API + tp_dict = __Pyx_GetTypeDict(tp); + if (unlikely(!tp_dict)) return -1; +#else + tp_dict = tp->tp_dict; +#endif + result = PyDict_DelItem(tp_dict, k); + if (likely(!result)) PyType_Modified(tp); + return result; +} + +/* SetupReduce */ +static int __Pyx_setup_reduce_is_named(PyObject* meth, PyObject* name) { + int ret; + PyObject *name_attr; + name_attr = __Pyx_PyObject_GetAttrStrNoError(meth, __pyx_mstate_global->__pyx_n_u_name); + if (likely(name_attr)) { + ret = PyObject_RichCompareBool(name_attr, name, Py_EQ); + } else { + ret = -1; + } + if (unlikely(ret < 0)) { + PyErr_Clear(); + ret = 0; + } + Py_XDECREF(name_attr); + return ret; +} +static int __Pyx_setup_reduce(PyObject* type_obj) { + int ret = 0; + PyObject *object_reduce = NULL; + PyObject *object_getstate = NULL; + PyObject *object_reduce_ex = NULL; + PyObject *reduce = NULL; + PyObject *reduce_ex = NULL; + PyObject *reduce_cython = NULL; + PyObject *setstate = NULL; + PyObject *setstate_cython = NULL; + PyObject *getstate = NULL; +#if CYTHON_USE_PYTYPE_LOOKUP + getstate = _PyType_Lookup((PyTypeObject*)type_obj, __pyx_mstate_global->__pyx_n_u_getstate); +#else + getstate = __Pyx_PyObject_GetAttrStrNoError(type_obj, __pyx_mstate_global->__pyx_n_u_getstate); + if (!getstate && PyErr_Occurred()) { + goto __PYX_BAD; + } +#endif + if (getstate) { +#if CYTHON_USE_PYTYPE_LOOKUP + object_getstate = _PyType_Lookup(&PyBaseObject_Type, __pyx_mstate_global->__pyx_n_u_getstate); +#else + object_getstate = __Pyx_PyObject_GetAttrStrNoError((PyObject*)&PyBaseObject_Type, __pyx_mstate_global->__pyx_n_u_getstate); + if (!object_getstate && PyErr_Occurred()) { + goto __PYX_BAD; + } +#endif + if (object_getstate != getstate) { + goto __PYX_GOOD; + } + } +#if CYTHON_USE_PYTYPE_LOOKUP + object_reduce_ex = _PyType_Lookup(&PyBaseObject_Type, __pyx_mstate_global->__pyx_n_u_reduce_ex); if (!object_reduce_ex) goto __PYX_BAD; +#else + object_reduce_ex = __Pyx_PyObject_GetAttrStr((PyObject*)&PyBaseObject_Type, __pyx_mstate_global->__pyx_n_u_reduce_ex); if (!object_reduce_ex) goto __PYX_BAD; +#endif + reduce_ex = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_mstate_global->__pyx_n_u_reduce_ex); if (unlikely(!reduce_ex)) goto __PYX_BAD; + if (reduce_ex == object_reduce_ex) { +#if CYTHON_USE_PYTYPE_LOOKUP + object_reduce = _PyType_Lookup(&PyBaseObject_Type, __pyx_mstate_global->__pyx_n_u_reduce); if (!object_reduce) goto __PYX_BAD; +#else + object_reduce = __Pyx_PyObject_GetAttrStr((PyObject*)&PyBaseObject_Type, __pyx_mstate_global->__pyx_n_u_reduce); if (!object_reduce) goto __PYX_BAD; +#endif + reduce = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_mstate_global->__pyx_n_u_reduce); if (unlikely(!reduce)) goto __PYX_BAD; + if (reduce == object_reduce || __Pyx_setup_reduce_is_named(reduce, __pyx_mstate_global->__pyx_n_u_reduce_cython)) { + reduce_cython = __Pyx_PyObject_GetAttrStrNoError(type_obj, __pyx_mstate_global->__pyx_n_u_reduce_cython); + if (likely(reduce_cython)) { + ret = __Pyx_SetItemOnTypeDict((PyTypeObject*)type_obj, __pyx_mstate_global->__pyx_n_u_reduce, reduce_cython); if (unlikely(ret < 0)) goto __PYX_BAD; + ret = __Pyx_DelItemOnTypeDict((PyTypeObject*)type_obj, __pyx_mstate_global->__pyx_n_u_reduce_cython); if (unlikely(ret < 0)) goto __PYX_BAD; + } else if (reduce == object_reduce || PyErr_Occurred()) { + goto __PYX_BAD; + } + setstate = __Pyx_PyObject_GetAttrStrNoError(type_obj, __pyx_mstate_global->__pyx_n_u_setstate); + if (!setstate) PyErr_Clear(); + if (!setstate || __Pyx_setup_reduce_is_named(setstate, __pyx_mstate_global->__pyx_n_u_setstate_cython)) { + setstate_cython = __Pyx_PyObject_GetAttrStrNoError(type_obj, __pyx_mstate_global->__pyx_n_u_setstate_cython); + if (likely(setstate_cython)) { + ret = __Pyx_SetItemOnTypeDict((PyTypeObject*)type_obj, __pyx_mstate_global->__pyx_n_u_setstate, setstate_cython); if (unlikely(ret < 0)) goto __PYX_BAD; + ret = __Pyx_DelItemOnTypeDict((PyTypeObject*)type_obj, __pyx_mstate_global->__pyx_n_u_setstate_cython); if (unlikely(ret < 0)) goto __PYX_BAD; + } else if (!setstate || PyErr_Occurred()) { + goto __PYX_BAD; + } + } + PyType_Modified((PyTypeObject*)type_obj); + } + } + goto __PYX_GOOD; +__PYX_BAD: + if (!PyErr_Occurred()) { + __Pyx_TypeName type_obj_name = + __Pyx_PyType_GetFullyQualifiedName((PyTypeObject*)type_obj); + PyErr_Format(PyExc_RuntimeError, + "Unable to initialize pickling for " __Pyx_FMT_TYPENAME, type_obj_name); + __Pyx_DECREF_TypeName(type_obj_name); + } + ret = -1; +__PYX_GOOD: +#if !CYTHON_USE_PYTYPE_LOOKUP + Py_XDECREF(object_reduce); + Py_XDECREF(object_reduce_ex); + Py_XDECREF(object_getstate); + Py_XDECREF(getstate); +#endif + Py_XDECREF(reduce); + Py_XDECREF(reduce_ex); + Py_XDECREF(reduce_cython); + Py_XDECREF(setstate); + Py_XDECREF(setstate_cython); + return ret; +} + +/* HasAttr (used by ImportImpl) */ +#if __PYX_LIMITED_VERSION_HEX < 0x030d0000 +static CYTHON_INLINE int __Pyx_HasAttr(PyObject *o, PyObject *n) { + PyObject *r; + if (unlikely(!PyUnicode_Check(n))) { + PyErr_SetString(PyExc_TypeError, + "hasattr(): attribute name must be string"); + return -1; + } + r = __Pyx_PyObject_GetAttrStrNoError(o, n); + if (!r) { + return (unlikely(PyErr_Occurred())) ? -1 : 0; + } else { + Py_DECREF(r); + return 1; + } +} +#endif + +/* ImportImpl (used by Import) */ +static int __Pyx__Import_GetModule(PyObject *qualname, PyObject **module) { + PyObject *imported_module = PyImport_GetModule(qualname); + if (unlikely(!imported_module)) { + *module = NULL; + if (PyErr_Occurred()) { + return -1; + } + return 0; + } + *module = imported_module; + return 1; +} +static int __Pyx__Import_Lookup(PyObject *qualname, PyObject *const *imported_names, Py_ssize_t len_imported_names, PyObject **module) { + PyObject *imported_module; + PyObject *top_level_package_name; + Py_ssize_t i; + int status, module_found; + Py_ssize_t dot_index; + module_found = __Pyx__Import_GetModule(qualname, &imported_module); + if (unlikely(!module_found || module_found == -1)) { + *module = NULL; + return module_found; + } + if (imported_names) { + for (i = 0; i < len_imported_names; i++) { + PyObject *imported_name = imported_names[i]; +#if __PYX_LIMITED_VERSION_HEX < 0x030d0000 + int has_imported_attribute = PyObject_HasAttr(imported_module, imported_name); +#else + int has_imported_attribute = PyObject_HasAttrWithError(imported_module, imported_name); + if (unlikely(has_imported_attribute == -1)) goto error; +#endif + if (!has_imported_attribute) { + goto not_found; + } + } + *module = imported_module; + return 1; + } + dot_index = PyUnicode_FindChar(qualname, '.', 0, PY_SSIZE_T_MAX, 1); + if (dot_index == -1) { + *module = imported_module; + return 1; + } + if (unlikely(dot_index == -2)) goto error; + top_level_package_name = PyUnicode_Substring(qualname, 0, dot_index); + if (unlikely(!top_level_package_name)) goto error; + Py_DECREF(imported_module); + status = __Pyx__Import_GetModule(top_level_package_name, module); + Py_DECREF(top_level_package_name); + return status; +error: + Py_DECREF(imported_module); + *module = NULL; + return -1; +not_found: + Py_DECREF(imported_module); + *module = NULL; + return 0; +} +static PyObject *__Pyx__Import(PyObject *name, PyObject *const *imported_names, Py_ssize_t len_imported_names, PyObject *qualname, PyObject *moddict, int level) { + PyObject *module = 0; + PyObject *empty_dict = 0; + PyObject *from_list = 0; + int module_found; + if (!qualname) { + qualname = name; + } + module_found = __Pyx__Import_Lookup(qualname, imported_names, len_imported_names, &module); + if (likely(module_found == 1)) { + return module; + } else if (unlikely(module_found == -1)) { + return NULL; + } + empty_dict = PyDict_New(); + if (unlikely(!empty_dict)) + goto bad; + if (imported_names) { +#if CYTHON_COMPILING_IN_CPYTHON + from_list = __Pyx_PyList_FromArray(imported_names, len_imported_names); + if (unlikely(!from_list)) + goto bad; +#else + from_list = PyList_New(len_imported_names); + if (unlikely(!from_list)) goto bad; + for (Py_ssize_t i=0; i__pyx_d, level); +} + +/* ImportFrom */ +static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name) { + PyObject* value = __Pyx_PyObject_GetAttrStr(module, name); + if (unlikely(!value) && PyErr_ExceptionMatches(PyExc_AttributeError)) { + const char* module_name_str = 0; + PyObject* module_name = 0; + PyObject* module_dot = 0; + PyObject* full_name = 0; + PyErr_Clear(); + module_name_str = PyModule_GetName(module); + if (unlikely(!module_name_str)) { goto modbad; } + module_name = PyUnicode_FromString(module_name_str); + if (unlikely(!module_name)) { goto modbad; } + module_dot = PyUnicode_Concat(module_name, __pyx_mstate_global->__pyx_kp_u__3); + if (unlikely(!module_dot)) { goto modbad; } + full_name = PyUnicode_Concat(module_dot, name); + if (unlikely(!full_name)) { goto modbad; } + #if (CYTHON_COMPILING_IN_PYPY && PYPY_VERSION_NUM < 0x07030400) ||\ + CYTHON_COMPILING_IN_GRAAL + { + PyObject *modules = PyImport_GetModuleDict(); + if (unlikely(!modules)) + goto modbad; + value = PyObject_GetItem(modules, full_name); + } + #else + value = PyImport_GetModule(full_name); + #endif + modbad: + Py_XDECREF(full_name); + Py_XDECREF(module_dot); + Py_XDECREF(module_name); + } + if (unlikely(!value)) { + PyErr_Format(PyExc_ImportError, "cannot import name %S", name); + } + return value; +} + +/* dict_setdefault (used by FetchCommonType) */ +static CYTHON_INLINE PyObject *__Pyx_PyDict_SetDefault(PyObject *d, PyObject *key, PyObject *default_value) { + PyObject* value; +#if __PYX_LIMITED_VERSION_HEX >= 0x030F0000 || (!CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d00A4) + PyDict_SetDefaultRef(d, key, default_value, &value); +#elif CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX >= 0x030C0000 + PyObject *args[] = {d, key, default_value}; + value = PyObject_VectorcallMethod(__pyx_mstate_global->__pyx_n_u_setdefault, args, 3 | PY_VECTORCALL_ARGUMENTS_OFFSET, NULL); +#elif CYTHON_COMPILING_IN_LIMITED_API + value = PyObject_CallMethodObjArgs(d, __pyx_mstate_global->__pyx_n_u_setdefault, key, default_value, NULL); +#else + value = PyDict_SetDefault(d, key, default_value); + if (unlikely(!value)) return NULL; + Py_INCREF(value); +#endif + return value; +} + +/* AddModuleRef (used by FetchSharedCythonModule) */ +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + static PyObject *__Pyx_PyImport_AddModuleObjectRef(PyObject *name) { + PyObject *module_dict = PyImport_GetModuleDict(); + PyObject *m; + if (PyMapping_GetOptionalItem(module_dict, name, &m) < 0) { + return NULL; + } + if (m != NULL && PyModule_Check(m)) { + return m; + } + Py_XDECREF(m); + m = PyModule_NewObject(name); + if (m == NULL) + return NULL; + if (PyDict_CheckExact(module_dict)) { + PyObject *new_m; + (void)PyDict_SetDefaultRef(module_dict, name, m, &new_m); + Py_DECREF(m); + return new_m; + } else { + if (PyObject_SetItem(module_dict, name, m) != 0) { + Py_DECREF(m); + return NULL; + } + return m; + } + } + static PyObject *__Pyx_PyImport_AddModuleRef(const char *name) { + PyObject *py_name = PyUnicode_FromString(name); + if (!py_name) return NULL; + PyObject *module = __Pyx_PyImport_AddModuleObjectRef(py_name); + Py_DECREF(py_name); + return module; + } +#elif __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + #define __Pyx_PyImport_AddModuleRef(name) PyImport_AddModuleRef(name) +#else + static PyObject *__Pyx_PyImport_AddModuleRef(const char *name) { + PyObject *module = PyImport_AddModule(name); + Py_XINCREF(module); + return module; + } +#endif + +/* FetchSharedCythonModule (used by FetchCommonType) */ +static PyObject *__Pyx_FetchSharedCythonABIModule(void) { + return __Pyx_PyImport_AddModuleRef(__PYX_ABI_MODULE_NAME); +} + +/* FetchCommonType (used by CommonTypesMetaclass) */ +#if __PYX_LIMITED_VERSION_HEX < 0x030C0000 +static PyObject* __Pyx_PyType_FromMetaclass(PyTypeObject *metaclass, PyObject *module, PyType_Spec *spec, PyObject *bases) { + PyObject *result = __Pyx_PyType_FromModuleAndSpec(module, spec, bases); + if (result && metaclass) { + PyObject *old_tp = (PyObject*)Py_TYPE(result); + Py_INCREF((PyObject*)metaclass); +#if __PYX_LIMITED_VERSION_HEX >= 0x03090000 + Py_SET_TYPE(result, metaclass); +#else + result->ob_type = metaclass; +#endif + Py_DECREF(old_tp); + } + return result; +} +#else +#define __Pyx_PyType_FromMetaclass(me, mo, s, b) PyType_FromMetaclass(me, mo, s, b) +#endif +static int __Pyx_VerifyCachedType(PyObject *cached_type, + const char *name, + Py_ssize_t expected_basicsize) { + Py_ssize_t basicsize; + if (!PyType_Check(cached_type)) { + PyErr_Format(PyExc_TypeError, + "Shared Cython type %.200s is not a type object", name); + return -1; + } + if (expected_basicsize == 0) { + return 0; // size is inherited, nothing useful to check + } +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *py_basicsize; + py_basicsize = PyObject_GetAttrString(cached_type, "__basicsize__"); + if (unlikely(!py_basicsize)) return -1; + basicsize = PyLong_AsSsize_t(py_basicsize); + Py_DECREF(py_basicsize); + py_basicsize = NULL; + if (unlikely(basicsize == (Py_ssize_t)-1) && PyErr_Occurred()) return -1; +#else + basicsize = ((PyTypeObject*) cached_type)->tp_basicsize; +#endif + if (basicsize != expected_basicsize) { + PyErr_Format(PyExc_TypeError, + "Shared Cython type %.200s has the wrong size, try recompiling", + name); + return -1; + } + return 0; +} +static PyTypeObject *__Pyx_FetchCommonTypeFromSpec(PyTypeObject *metaclass, PyObject *module, PyType_Spec *spec, PyObject *bases) { + PyObject *abi_module = NULL, *cached_type = NULL, *abi_module_dict, *new_cached_type, *py_object_name; + int get_item_ref_result; + const char* object_name = strrchr(spec->name, '.'); + object_name = object_name ? object_name+1 : spec->name; + py_object_name = PyUnicode_FromString(object_name); + if (!py_object_name) return NULL; + abi_module = __Pyx_FetchSharedCythonABIModule(); + if (!abi_module) goto done; + abi_module_dict = PyModule_GetDict(abi_module); + if (!abi_module_dict) goto done; + get_item_ref_result = __Pyx_PyDict_GetItemRef(abi_module_dict, py_object_name, &cached_type); + if (get_item_ref_result == 1) { + if (__Pyx_VerifyCachedType( + cached_type, + object_name, + spec->basicsize) < 0) { + goto bad; + } + goto done; + } else if (unlikely(get_item_ref_result == -1)) { + goto bad; + } + cached_type = __Pyx_PyType_FromMetaclass( + metaclass, + CYTHON_USE_MODULE_STATE ? module : abi_module, + spec, bases); + if (unlikely(!cached_type)) goto bad; + if (unlikely(__Pyx_fix_up_extension_type_from_spec(spec, (PyTypeObject *) cached_type) < 0)) goto bad; + new_cached_type = __Pyx_PyDict_SetDefault(abi_module_dict, py_object_name, cached_type); + if (unlikely(new_cached_type != cached_type)) { + if (unlikely(!new_cached_type)) goto bad; + Py_DECREF(cached_type); + cached_type = new_cached_type; + if (__Pyx_VerifyCachedType( + cached_type, + object_name, + spec->basicsize) < 0) { + goto bad; + } + goto done; + } else { + Py_DECREF(new_cached_type); + } +done: + Py_XDECREF(abi_module); + Py_DECREF(py_object_name); + assert(cached_type == NULL || PyType_Check(cached_type)); + return (PyTypeObject *) cached_type; +bad: + Py_XDECREF(cached_type); + cached_type = NULL; + goto done; +} + +/* CommonTypesMetaclass (used by CythonFunctionShared) */ +static PyObject* __pyx_CommonTypesMetaclass_get_module(CYTHON_UNUSED PyObject *self, CYTHON_UNUSED void* context) { + return PyUnicode_FromString(__PYX_ABI_MODULE_NAME); +} +#if __PYX_LIMITED_VERSION_HEX < 0x030A0000 +static PyObject* __pyx_CommonTypesMetaclass_call(CYTHON_UNUSED PyObject *self, CYTHON_UNUSED PyObject *args, CYTHON_UNUSED PyObject *kwds) { + PyErr_SetString(PyExc_TypeError, "Cannot instantiate Cython internal types"); + return NULL; +} +static int __pyx_CommonTypesMetaclass_setattr(CYTHON_UNUSED PyObject *self, CYTHON_UNUSED PyObject *attr, CYTHON_UNUSED PyObject *value) { + PyErr_SetString(PyExc_TypeError, "Cython internal types are immutable"); + return -1; +} +#endif +static PyGetSetDef __pyx_CommonTypesMetaclass_getset[] = { + {"__module__", __pyx_CommonTypesMetaclass_get_module, NULL, NULL, NULL}, + {0, 0, 0, 0, 0} +}; +static PyType_Slot __pyx_CommonTypesMetaclass_slots[] = { + {Py_tp_getset, (void *)__pyx_CommonTypesMetaclass_getset}, + #if __PYX_LIMITED_VERSION_HEX < 0x030A0000 + {Py_tp_call, (void*)__pyx_CommonTypesMetaclass_call}, + {Py_tp_new, (void*)__pyx_CommonTypesMetaclass_call}, + {Py_tp_setattro, (void*)__pyx_CommonTypesMetaclass_setattr}, + #endif + {0, 0} +}; +static PyType_Spec __pyx_CommonTypesMetaclass_spec = { + __PYX_TYPE_MODULE_PREFIX "_common_types_metatype", + 0, + 0, + Py_TPFLAGS_IMMUTABLETYPE | + Py_TPFLAGS_DISALLOW_INSTANTIATION | + Py_TPFLAGS_DEFAULT, + __pyx_CommonTypesMetaclass_slots +}; +static int __pyx_CommonTypesMetaclass_init(PyObject *module) { + __pyx_mstatetype *mstate = __Pyx_PyModule_GetState(module); + PyObject *bases = PyTuple_Pack(1, &PyType_Type); + if (unlikely(!bases)) { + return -1; + } + mstate->__pyx_CommonTypesMetaclassType = __Pyx_FetchCommonTypeFromSpec(NULL, module, &__pyx_CommonTypesMetaclass_spec, bases); + Py_DECREF(bases); + if (unlikely(mstate->__pyx_CommonTypesMetaclassType == NULL)) { + return -1; + } + return 0; +} + +/* PyMethodNew (used by CythonFunctionShared) */ +#if CYTHON_COMPILING_IN_LIMITED_API +static PyObject *__Pyx_PyMethod_New(PyObject *func, PyObject *self, PyObject *typ) { + PyObject *result; + CYTHON_UNUSED_VAR(typ); + if (!self) + return __Pyx_NewRef(func); + #if __PYX_LIMITED_VERSION_HEX >= 0x030C0000 + { + PyObject *args[] = {func, self}; + result = PyObject_Vectorcall(__pyx_mstate_global->__Pyx_CachedMethodType, args, 2, NULL); + } + #else + result = PyObject_CallFunctionObjArgs(__pyx_mstate_global->__Pyx_CachedMethodType, func, self, NULL); + #endif + return result; +} +#else +static PyObject *__Pyx_PyMethod_New(PyObject *func, PyObject *self, PyObject *typ) { + CYTHON_UNUSED_VAR(typ); + if (!self) + return __Pyx_NewRef(func); + return PyMethod_New(func, self); +} +#endif + +/* PyVectorcallFastCallDict (used by CythonFunctionShared) */ +#if CYTHON_METH_FASTCALL && CYTHON_VECTORCALL +static PyObject *__Pyx_PyVectorcall_FastCallDict_kw(PyObject *func, __pyx_vectorcallfunc vc, PyObject *const *args, size_t nargs, PyObject *kw) +{ + PyObject *res = NULL; + PyObject *kwnames; + PyObject **newargs; + PyObject **kwvalues; + Py_ssize_t i; + #if CYTHON_AVOID_BORROWED_REFS + PyObject *pos; + #else + Py_ssize_t pos; + #endif + size_t j; + PyObject *key, *value; + unsigned long keys_are_strings; + #if !CYTHON_ASSUME_SAFE_SIZE + Py_ssize_t nkw = PyDict_Size(kw); + if (unlikely(nkw == -1)) return NULL; + #else + Py_ssize_t nkw = PyDict_GET_SIZE(kw); + #endif + newargs = (PyObject **)PyMem_Malloc((nargs + (size_t)nkw) * sizeof(args[0])); + if (unlikely(newargs == NULL)) { + PyErr_NoMemory(); + return NULL; + } + for (j = 0; j < nargs; j++) newargs[j] = args[j]; + kwnames = PyTuple_New(nkw); + if (unlikely(kwnames == NULL)) { + PyMem_Free(newargs); + return NULL; + } + kwvalues = newargs + nargs; + pos = 0; + i = 0; + keys_are_strings = Py_TPFLAGS_UNICODE_SUBCLASS; + while (__Pyx_PyDict_NextRef(kw, &pos, &key, &value)) { + keys_are_strings &= + #if CYTHON_COMPILING_IN_LIMITED_API + PyType_GetFlags(Py_TYPE(key)); + #else + Py_TYPE(key)->tp_flags; + #endif + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(PyTuple_SetItem(kwnames, i, key) < 0)) goto cleanup; + #else + PyTuple_SET_ITEM(kwnames, i, key); + #endif + kwvalues[i] = value; + i++; + } + if (unlikely(!keys_are_strings)) { + PyErr_SetString(PyExc_TypeError, "keywords must be strings"); + goto cleanup; + } + res = vc(func, newargs, nargs, kwnames); +cleanup: + #if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(pos); + #endif + Py_DECREF(kwnames); + for (i = 0; i < nkw; i++) + Py_DECREF(kwvalues[i]); + PyMem_Free(newargs); + return res; +} +static CYTHON_INLINE PyObject *__Pyx_PyVectorcall_FastCallDict(PyObject *func, __pyx_vectorcallfunc vc, PyObject *const *args, size_t nargs, PyObject *kw) +{ + Py_ssize_t kw_size = + likely(kw == NULL) ? + 0 : +#if !CYTHON_ASSUME_SAFE_SIZE + PyDict_Size(kw); +#else + PyDict_GET_SIZE(kw); +#endif + if (kw_size == 0) { + return vc(func, args, nargs, NULL); + } +#if !CYTHON_ASSUME_SAFE_SIZE + else if (unlikely(kw_size == -1)) { + return NULL; + } +#endif + return __Pyx_PyVectorcall_FastCallDict_kw(func, vc, args, nargs, kw); +} +#endif + +/* CythonFunctionShared (used by CythonFunction) */ +#if CYTHON_COMPILING_IN_LIMITED_API +static CYTHON_INLINE int __Pyx__IsSameCyOrCFunctionNoMethod(PyObject *func, void (*cfunc)(void)) { + if (__Pyx_CyFunction_Check(func)) { + return PyCFunction_GetFunction(((__pyx_CyFunctionObject*)func)->func) == (PyCFunction) cfunc; + } else if (PyCFunction_Check(func)) { + return PyCFunction_GetFunction(func) == (PyCFunction) cfunc; + } + return 0; +} +static CYTHON_INLINE int __Pyx__IsSameCyOrCFunction(PyObject *func, void (*cfunc)(void)) { + if ((PyObject*)Py_TYPE(func) == __pyx_mstate_global->__Pyx_CachedMethodType) { + int result; + PyObject *newFunc = PyObject_GetAttr(func, __pyx_mstate_global->__pyx_n_u_func); + if (unlikely(!newFunc)) { + PyErr_Clear(); // It's only an optimization, so don't throw an error + return 0; + } + result = __Pyx__IsSameCyOrCFunctionNoMethod(newFunc, cfunc); + Py_DECREF(newFunc); + return result; + } + return __Pyx__IsSameCyOrCFunctionNoMethod(func, cfunc); +} +#else +static CYTHON_INLINE int __Pyx__IsSameCyOrCFunction(PyObject *func, void (*cfunc)(void)) { + if (PyMethod_Check(func)) { + func = PyMethod_GET_FUNCTION(func); + } + return __Pyx_CyOrPyCFunction_Check(func) && __Pyx_CyOrPyCFunction_GET_FUNCTION(func) == (PyCFunction) cfunc; +} +#endif +static CYTHON_INLINE void __Pyx__CyFunction_SetClassObj(__pyx_CyFunctionObject* f, PyObject* classobj) { +#if PY_VERSION_HEX < 0x030900B1 || CYTHON_COMPILING_IN_LIMITED_API + __Pyx_Py_XDECREF_SET( + __Pyx_CyFunction_GetClassObj(f), + ((classobj) ? __Pyx_NewRef(classobj) : NULL)); +#else + __Pyx_Py_XDECREF_SET( + ((PyCMethodObject *) (f))->mm_class, + (PyTypeObject*)((classobj) ? __Pyx_NewRef(classobj) : NULL)); +#endif +} +static PyObject * +__Pyx_CyFunction_get_doc_locked(__pyx_CyFunctionObject *op) +{ + if (unlikely(op->func_doc == NULL)) { +#if CYTHON_COMPILING_IN_LIMITED_API + op->func_doc = PyObject_GetAttrString(op->func, "__doc__"); + if (unlikely(!op->func_doc)) return NULL; +#else + if (((PyCFunctionObject*)op)->m_ml->ml_doc) { + op->func_doc = PyUnicode_FromString(((PyCFunctionObject*)op)->m_ml->ml_doc); + if (unlikely(op->func_doc == NULL)) + return NULL; + } else { + Py_INCREF(Py_None); + return Py_None; + } +#endif + } + Py_INCREF(op->func_doc); + return op->func_doc; +} +static PyObject * +__Pyx_CyFunction_get_doc(__pyx_CyFunctionObject *op, void *closure) { + PyObject *result; + CYTHON_UNUSED_VAR(closure); + __Pyx_BEGIN_CRITICAL_SECTION(op); + result = __Pyx_CyFunction_get_doc_locked(op); + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static int +__Pyx_CyFunction_set_doc(__pyx_CyFunctionObject *op, PyObject *value, void *context) +{ + CYTHON_UNUSED_VAR(context); + if (value == NULL) { + value = Py_None; + } + Py_INCREF(value); + __Pyx_BEGIN_CRITICAL_SECTION(op); + __Pyx_Py_XDECREF_SET(op->func_doc, value); + __Pyx_END_CRITICAL_SECTION(); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_name_locked(__pyx_CyFunctionObject *op) +{ + if (unlikely(op->func_name == NULL)) { +#if CYTHON_COMPILING_IN_LIMITED_API + op->func_name = PyObject_GetAttrString(op->func, "__name__"); +#else + op->func_name = PyUnicode_InternFromString(((PyCFunctionObject*)op)->m_ml->ml_name); +#endif + if (unlikely(op->func_name == NULL)) + return NULL; + } + Py_INCREF(op->func_name); + return op->func_name; +} +static PyObject * +__Pyx_CyFunction_get_name(__pyx_CyFunctionObject *op, void *context) +{ + PyObject *result = NULL; + CYTHON_UNUSED_VAR(context); + __Pyx_BEGIN_CRITICAL_SECTION(op); + result = __Pyx_CyFunction_get_name_locked(op); + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static int +__Pyx_CyFunction_set_name(__pyx_CyFunctionObject *op, PyObject *value, void *context) +{ + CYTHON_UNUSED_VAR(context); + if (unlikely(value == NULL || !PyUnicode_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "__name__ must be set to a string object"); + return -1; + } + Py_INCREF(value); + __Pyx_BEGIN_CRITICAL_SECTION(op); + __Pyx_Py_XDECREF_SET(op->func_name, value); + __Pyx_END_CRITICAL_SECTION(); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_qualname(__pyx_CyFunctionObject *op, void *context) +{ + CYTHON_UNUSED_VAR(context); + PyObject *result; + __Pyx_BEGIN_CRITICAL_SECTION(op); + Py_INCREF(op->func_qualname); + result = op->func_qualname; + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static int +__Pyx_CyFunction_set_qualname(__pyx_CyFunctionObject *op, PyObject *value, void *context) +{ + CYTHON_UNUSED_VAR(context); + if (unlikely(value == NULL || !PyUnicode_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "__qualname__ must be set to a string object"); + return -1; + } + Py_INCREF(value); + __Pyx_BEGIN_CRITICAL_SECTION(op); + __Pyx_Py_XDECREF_SET(op->func_qualname, value); + __Pyx_END_CRITICAL_SECTION(); + return 0; +} +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000 +static PyObject * +__Pyx_CyFunction_get_dict(__pyx_CyFunctionObject *op, void *context) +{ + CYTHON_UNUSED_VAR(context); + if (unlikely(op->func_dict == NULL)) { + op->func_dict = PyDict_New(); + if (unlikely(op->func_dict == NULL)) + return NULL; + } + Py_INCREF(op->func_dict); + return op->func_dict; +} +#endif +static PyObject * +__Pyx_CyFunction_get_globals(__pyx_CyFunctionObject *op, void *context) +{ + CYTHON_UNUSED_VAR(context); + Py_INCREF(op->func_globals); + return op->func_globals; +} +static PyObject * +__Pyx_CyFunction_get_closure(__pyx_CyFunctionObject *op, void *context) +{ + CYTHON_UNUSED_VAR(op); + CYTHON_UNUSED_VAR(context); + Py_INCREF(Py_None); + return Py_None; +} +static PyObject * +__Pyx_CyFunction_get_code(__pyx_CyFunctionObject *op, void *context) +{ + PyObject* result = (op->func_code) ? op->func_code : Py_None; + CYTHON_UNUSED_VAR(context); + Py_INCREF(result); + return result; +} +static int +__Pyx_CyFunction_init_defaults(__pyx_CyFunctionObject *op) { + int result = 0; + PyObject *res = op->defaults_getter((PyObject *) op); + if (unlikely(!res)) + return -1; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + op->defaults_tuple = PyTuple_GET_ITEM(res, 0); + Py_INCREF(op->defaults_tuple); + op->defaults_kwdict = PyTuple_GET_ITEM(res, 1); + Py_INCREF(op->defaults_kwdict); + #else + op->defaults_tuple = __Pyx_PySequence_ITEM(res, 0); + if (unlikely(!op->defaults_tuple)) result = -1; + else { + op->defaults_kwdict = __Pyx_PySequence_ITEM(res, 1); + if (unlikely(!op->defaults_kwdict)) result = -1; + } + #endif + Py_DECREF(res); + return result; +} +static int +__Pyx_CyFunction_set_defaults(__pyx_CyFunctionObject *op, PyObject* value, void *context) { + CYTHON_UNUSED_VAR(context); + if (!value) { + value = Py_None; + } else if (unlikely(value != Py_None && !PyTuple_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "__defaults__ must be set to a tuple object"); + return -1; + } + PyErr_WarnEx(PyExc_RuntimeWarning, "changes to cyfunction.__defaults__ will not " + "currently affect the values used in function calls", 1); + Py_INCREF(value); + __Pyx_BEGIN_CRITICAL_SECTION(op); + __Pyx_Py_XDECREF_SET(op->defaults_tuple, value); + __Pyx_END_CRITICAL_SECTION(); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_defaults_locked(__pyx_CyFunctionObject *op) { + PyObject* result = op->defaults_tuple; + if (unlikely(!result)) { + if (op->defaults_getter) { + if (unlikely(__Pyx_CyFunction_init_defaults(op) < 0)) return NULL; + result = op->defaults_tuple; + } else { + result = Py_None; + } + } + Py_INCREF(result); + return result; +} +static PyObject * +__Pyx_CyFunction_get_defaults(__pyx_CyFunctionObject *op, void *context) { + PyObject* result = NULL; + CYTHON_UNUSED_VAR(context); + __Pyx_BEGIN_CRITICAL_SECTION(op); + result = __Pyx_CyFunction_get_defaults_locked(op); + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static int +__Pyx_CyFunction_set_kwdefaults(__pyx_CyFunctionObject *op, PyObject* value, void *context) { + CYTHON_UNUSED_VAR(context); + if (!value) { + value = Py_None; + } else if (unlikely(value != Py_None && !PyDict_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "__kwdefaults__ must be set to a dict object"); + return -1; + } + PyErr_WarnEx(PyExc_RuntimeWarning, "changes to cyfunction.__kwdefaults__ will not " + "currently affect the values used in function calls", 1); + Py_INCREF(value); + __Pyx_BEGIN_CRITICAL_SECTION(op); + __Pyx_Py_XDECREF_SET(op->defaults_kwdict, value); + __Pyx_END_CRITICAL_SECTION(); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_kwdefaults_locked(__pyx_CyFunctionObject *op) { + PyObject* result = op->defaults_kwdict; + if (unlikely(!result)) { + if (op->defaults_getter) { + if (unlikely(__Pyx_CyFunction_init_defaults(op) < 0)) return NULL; + result = op->defaults_kwdict; + } else { + result = Py_None; + } + } + Py_INCREF(result); + return result; +} +static PyObject * +__Pyx_CyFunction_get_kwdefaults(__pyx_CyFunctionObject *op, void *context) { + PyObject* result; + CYTHON_UNUSED_VAR(context); + __Pyx_BEGIN_CRITICAL_SECTION(op); + result = __Pyx_CyFunction_get_kwdefaults_locked(op); + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static int +__Pyx_CyFunction_set_annotations(__pyx_CyFunctionObject *op, PyObject* value, void *context) { + CYTHON_UNUSED_VAR(context); + if (!value || value == Py_None) { + value = NULL; + } else if (unlikely(!PyDict_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "__annotations__ must be set to a dict object"); + return -1; + } + Py_XINCREF(value); + __Pyx_BEGIN_CRITICAL_SECTION(op); + __Pyx_Py_XDECREF_SET(op->func_annotations, value); + __Pyx_END_CRITICAL_SECTION(); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_annotations_locked(__pyx_CyFunctionObject *op) { + PyObject* result = op->func_annotations; + if (unlikely(!result)) { + result = PyDict_New(); + if (unlikely(!result)) return NULL; + op->func_annotations = result; + } + Py_INCREF(result); + return result; +} +static PyObject * +__Pyx_CyFunction_get_annotations(__pyx_CyFunctionObject *op, void *context) { + PyObject *result; + CYTHON_UNUSED_VAR(context); + __Pyx_BEGIN_CRITICAL_SECTION(op); + result = __Pyx_CyFunction_get_annotations_locked(op); + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static PyObject * +__Pyx_CyFunction_get_is_coroutine_value(__pyx_CyFunctionObject *op) { + int is_coroutine = op->flags & __Pyx_CYFUNCTION_COROUTINE; + if (is_coroutine) { + PyObject *is_coroutine_value, *module, *fromlist, *marker = __pyx_mstate_global->__pyx_n_u_is_coroutine; + fromlist = PyList_New(1); + if (unlikely(!fromlist)) return NULL; + Py_INCREF(marker); +#if CYTHON_ASSUME_SAFE_MACROS + PyList_SET_ITEM(fromlist, 0, marker); +#else + if (unlikely(PyList_SetItem(fromlist, 0, marker) < 0)) { + Py_DECREF(marker); + Py_DECREF(fromlist); + return NULL; + } +#endif + module = PyImport_ImportModuleLevelObject(__pyx_mstate_global->__pyx_n_u_asyncio_coroutines, NULL, NULL, fromlist, 0); + Py_DECREF(fromlist); + if (unlikely(!module)) goto ignore; + is_coroutine_value = __Pyx_PyObject_GetAttrStr(module, marker); + Py_DECREF(module); + if (likely(is_coroutine_value)) { + return is_coroutine_value; + } +ignore: + PyErr_Clear(); + } + return __Pyx_PyBool_FromLong(is_coroutine); +} +static PyObject * +__Pyx_CyFunction_get_is_coroutine(__pyx_CyFunctionObject *op, void *context) { + PyObject *result; + CYTHON_UNUSED_VAR(context); + if (op->func_is_coroutine) { + return __Pyx_NewRef(op->func_is_coroutine); + } + result = __Pyx_CyFunction_get_is_coroutine_value(op); + if (unlikely(!result)) + return NULL; + __Pyx_BEGIN_CRITICAL_SECTION(op); + if (op->func_is_coroutine) { + Py_DECREF(result); + result = __Pyx_NewRef(op->func_is_coroutine); + } else { + op->func_is_coroutine = __Pyx_NewRef(result); + } + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static void __Pyx_CyFunction_raise_argument_count_error(__pyx_CyFunctionObject *func, const char* message, Py_ssize_t size) { +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *py_name = __Pyx_CyFunction_get_name(func, NULL); + if (!py_name) return; + PyErr_Format(PyExc_TypeError, + "%.200S() %s (%" CYTHON_FORMAT_SSIZE_T "d given)", + py_name, message, size); + Py_DECREF(py_name); +#else + const char* name = ((PyCFunctionObject*)func)->m_ml->ml_name; + PyErr_Format(PyExc_TypeError, + "%.200s() %s (%" CYTHON_FORMAT_SSIZE_T "d given)", + name, message, size); +#endif +} +static void __Pyx_CyFunction_raise_type_error(__pyx_CyFunctionObject *func, const char* message) { +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *py_name = __Pyx_CyFunction_get_name(func, NULL); + if (!py_name) return; + PyErr_Format(PyExc_TypeError, + "%.200S() %s", + py_name, message); + Py_DECREF(py_name); +#else + const char* name = ((PyCFunctionObject*)func)->m_ml->ml_name; + PyErr_Format(PyExc_TypeError, + "%.200s() %s", + name, message); +#endif +} +#if CYTHON_COMPILING_IN_LIMITED_API +static PyObject * +__Pyx_CyFunction_get_module(__pyx_CyFunctionObject *op, void *context) { + CYTHON_UNUSED_VAR(context); + return PyObject_GetAttrString(op->func, "__module__"); +} +static int +__Pyx_CyFunction_set_module(__pyx_CyFunctionObject *op, PyObject* value, void *context) { + CYTHON_UNUSED_VAR(context); + return PyObject_SetAttrString(op->func, "__module__", value); +} +#endif +static PyGetSetDef __pyx_CyFunction_getsets[] = { + {"func_doc", (getter)__Pyx_CyFunction_get_doc, (setter)__Pyx_CyFunction_set_doc, 0, 0}, + {"__doc__", (getter)__Pyx_CyFunction_get_doc, (setter)__Pyx_CyFunction_set_doc, 0, 0}, + {"func_name", (getter)__Pyx_CyFunction_get_name, (setter)__Pyx_CyFunction_set_name, 0, 0}, + {"__name__", (getter)__Pyx_CyFunction_get_name, (setter)__Pyx_CyFunction_set_name, 0, 0}, + {"__qualname__", (getter)__Pyx_CyFunction_get_qualname, (setter)__Pyx_CyFunction_set_qualname, 0, 0}, +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000 + {"func_dict", (getter)__Pyx_CyFunction_get_dict, (setter)PyObject_GenericSetDict, 0, 0}, + {"__dict__", (getter)__Pyx_CyFunction_get_dict, (setter)PyObject_GenericSetDict, 0, 0}, +#else + {"func_dict", (getter)PyObject_GenericGetDict, (setter)PyObject_GenericSetDict, 0, 0}, + {"__dict__", (getter)PyObject_GenericGetDict, (setter)PyObject_GenericSetDict, 0, 0}, +#endif + {"func_globals", (getter)__Pyx_CyFunction_get_globals, 0, 0, 0}, + {"__globals__", (getter)__Pyx_CyFunction_get_globals, 0, 0, 0}, + {"func_closure", (getter)__Pyx_CyFunction_get_closure, 0, 0, 0}, + {"__closure__", (getter)__Pyx_CyFunction_get_closure, 0, 0, 0}, + {"func_code", (getter)__Pyx_CyFunction_get_code, 0, 0, 0}, + {"__code__", (getter)__Pyx_CyFunction_get_code, 0, 0, 0}, + {"func_defaults", (getter)__Pyx_CyFunction_get_defaults, (setter)__Pyx_CyFunction_set_defaults, 0, 0}, + {"__defaults__", (getter)__Pyx_CyFunction_get_defaults, (setter)__Pyx_CyFunction_set_defaults, 0, 0}, + {"__kwdefaults__", (getter)__Pyx_CyFunction_get_kwdefaults, (setter)__Pyx_CyFunction_set_kwdefaults, 0, 0}, + {"__annotations__", (getter)__Pyx_CyFunction_get_annotations, (setter)__Pyx_CyFunction_set_annotations, 0, 0}, + {"_is_coroutine", (getter)__Pyx_CyFunction_get_is_coroutine, 0, 0, 0}, +#if CYTHON_COMPILING_IN_LIMITED_API + {"__module__", (getter)__Pyx_CyFunction_get_module, (setter)__Pyx_CyFunction_set_module, 0, 0}, +#endif + {0, 0, 0, 0, 0} +}; +static PyMemberDef __pyx_CyFunction_members[] = { +#if !CYTHON_COMPILING_IN_LIMITED_API + {"__module__", T_OBJECT, offsetof(PyCFunctionObject, m_module), 0, 0}, +#endif +#if PY_VERSION_HEX < 0x030C0000 || CYTHON_COMPILING_IN_LIMITED_API + {"__dictoffset__", T_PYSSIZET, offsetof(__pyx_CyFunctionObject, func_dict), READONLY, 0}, +#endif +#if CYTHON_METH_FASTCALL +#if CYTHON_COMPILING_IN_LIMITED_API + {"__vectorcalloffset__", T_PYSSIZET, offsetof(__pyx_CyFunctionObject, func_vectorcall), READONLY, 0}, +#else + {"__vectorcalloffset__", T_PYSSIZET, offsetof(PyCFunctionObject, vectorcall), READONLY, 0}, +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + {"__weaklistoffset__", T_PYSSIZET, offsetof(__pyx_CyFunctionObject, func_weakreflist), READONLY, 0}, +#else + {"__weaklistoffset__", T_PYSSIZET, offsetof(PyCFunctionObject, m_weakreflist), READONLY, 0}, +#endif +#endif + {0, 0, 0, 0, 0} +}; +static PyObject * +__Pyx_CyFunction_reduce(__pyx_CyFunctionObject *m, PyObject *args) +{ + PyObject *result = NULL; + CYTHON_UNUSED_VAR(args); + __Pyx_BEGIN_CRITICAL_SECTION(m); + Py_INCREF(m->func_qualname); + result = m->func_qualname; + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static PyMethodDef __pyx_CyFunction_methods[] = { + {"__reduce__", (PyCFunction)__Pyx_CyFunction_reduce, METH_VARARGS, 0}, + {0, 0, 0, 0} +}; +#if CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_CyFunction_weakreflist(cyfunc) ((cyfunc)->func_weakreflist) +#else +#define __Pyx_CyFunction_weakreflist(cyfunc) (((PyCFunctionObject*)cyfunc)->m_weakreflist) +#endif +static PyObject *__Pyx_CyFunction_Init(__pyx_CyFunctionObject *op, PyMethodDef *ml, int flags, PyObject* qualname, + PyObject *closure, PyObject *module, PyObject* globals, PyObject* code) { +#if !CYTHON_COMPILING_IN_LIMITED_API + PyCFunctionObject *cf = (PyCFunctionObject*) op; +#endif + if (unlikely(op == NULL)) + return NULL; +#if CYTHON_COMPILING_IN_LIMITED_API + op->func = PyCFunction_NewEx(ml, (PyObject*)op, module); + if (unlikely(!op->func)) return NULL; +#endif + op->flags = flags; + __Pyx_CyFunction_weakreflist(op) = NULL; +#if !CYTHON_COMPILING_IN_LIMITED_API + cf->m_ml = ml; + cf->m_self = (PyObject *) op; +#endif + Py_XINCREF(closure); + op->func_closure = closure; +#if !CYTHON_COMPILING_IN_LIMITED_API + Py_XINCREF(module); + cf->m_module = module; +#endif +#if PY_VERSION_HEX < 0x030C0000 || CYTHON_COMPILING_IN_LIMITED_API + op->func_dict = NULL; +#endif + op->func_name = NULL; + Py_INCREF(qualname); + op->func_qualname = qualname; + op->func_doc = NULL; +#if PY_VERSION_HEX < 0x030900B1 || CYTHON_COMPILING_IN_LIMITED_API + op->func_classobj = NULL; +#else + ((PyCMethodObject*)op)->mm_class = NULL; +#endif + op->func_globals = globals; + Py_INCREF(op->func_globals); + Py_XINCREF(code); + op->func_code = code; + op->defaults = NULL; + op->defaults_tuple = NULL; + op->defaults_kwdict = NULL; + op->defaults_getter = NULL; + op->func_annotations = NULL; + op->func_is_coroutine = NULL; +#if CYTHON_METH_FASTCALL + switch (ml->ml_flags & (METH_VARARGS | METH_FASTCALL | METH_NOARGS | METH_O | METH_KEYWORDS | METH_METHOD)) { + case METH_NOARGS: + __Pyx_CyFunction_func_vectorcall(op) = __Pyx_CyFunction_Vectorcall_NOARGS; + break; + case METH_O: + __Pyx_CyFunction_func_vectorcall(op) = __Pyx_CyFunction_Vectorcall_O; + break; + case METH_METHOD | METH_FASTCALL | METH_KEYWORDS: + __Pyx_CyFunction_func_vectorcall(op) = __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS_METHOD; + break; + case METH_FASTCALL | METH_KEYWORDS: + __Pyx_CyFunction_func_vectorcall(op) = __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS; + break; + case METH_VARARGS | METH_KEYWORDS: + __Pyx_CyFunction_func_vectorcall(op) = NULL; + break; + default: + PyErr_SetString(PyExc_SystemError, "Bad call flags for CyFunction"); + Py_DECREF(op); + return NULL; + } +#endif + return (PyObject *) op; +} +static int +__Pyx_CyFunction_clear(__pyx_CyFunctionObject *m) +{ + Py_CLEAR(m->func_closure); +#if CYTHON_COMPILING_IN_LIMITED_API + Py_CLEAR(m->func); +#else + Py_CLEAR(((PyCFunctionObject*)m)->m_module); +#endif +#if PY_VERSION_HEX < 0x030C0000 || CYTHON_COMPILING_IN_LIMITED_API + Py_CLEAR(m->func_dict); +#elif PY_VERSION_HEX < 0x030d0000 + _PyObject_ClearManagedDict((PyObject*)m); +#else + PyObject_ClearManagedDict((PyObject*)m); +#endif + Py_CLEAR(m->func_name); + Py_CLEAR(m->func_qualname); + Py_CLEAR(m->func_doc); + Py_CLEAR(m->func_globals); + Py_CLEAR(m->func_code); +#if !CYTHON_COMPILING_IN_LIMITED_API +#if PY_VERSION_HEX < 0x030900B1 + Py_CLEAR(__Pyx_CyFunction_GetClassObj(m)); +#else + { + PyObject *cls = (PyObject*) ((PyCMethodObject *) (m))->mm_class; + ((PyCMethodObject *) (m))->mm_class = NULL; + Py_XDECREF(cls); + } +#endif +#endif + Py_CLEAR(m->defaults_tuple); + Py_CLEAR(m->defaults_kwdict); + Py_CLEAR(m->func_annotations); + Py_CLEAR(m->func_is_coroutine); + Py_CLEAR(m->defaults); + return 0; +} +static void __Pyx__CyFunction_dealloc(__pyx_CyFunctionObject *m) +{ + if (__Pyx_CyFunction_weakreflist(m) != NULL) + PyObject_ClearWeakRefs((PyObject *) m); + __Pyx_CyFunction_clear(m); + __Pyx_PyHeapTypeObject_GC_Del(m); +} +static void __Pyx_CyFunction_dealloc(__pyx_CyFunctionObject *m) +{ + PyObject_GC_UnTrack(m); + __Pyx__CyFunction_dealloc(m); +} +static int __Pyx_CyFunction_traverse(__pyx_CyFunctionObject *m, visitproc visit, void *arg) +{ + { + int e = __Pyx_call_type_traverse((PyObject*)m, 1, visit, arg); + if (e) return e; + } + Py_VISIT(m->func_closure); +#if CYTHON_COMPILING_IN_LIMITED_API + Py_VISIT(m->func); +#else + Py_VISIT(((PyCFunctionObject*)m)->m_module); +#endif +#if PY_VERSION_HEX < 0x030C0000 || CYTHON_COMPILING_IN_LIMITED_API + Py_VISIT(m->func_dict); +#else + { + int e = +#if PY_VERSION_HEX < 0x030d0000 + _PyObject_VisitManagedDict +#else + PyObject_VisitManagedDict +#endif + ((PyObject*)m, visit, arg); + if (e != 0) return e; + } +#endif + __Pyx_VISIT_CONST(m->func_name); + __Pyx_VISIT_CONST(m->func_qualname); + Py_VISIT(m->func_doc); + Py_VISIT(m->func_globals); + __Pyx_VISIT_CONST(m->func_code); +#if !CYTHON_COMPILING_IN_LIMITED_API + Py_VISIT(__Pyx_CyFunction_GetClassObj(m)); +#endif + Py_VISIT(m->defaults_tuple); + Py_VISIT(m->defaults_kwdict); + Py_VISIT(m->func_is_coroutine); + Py_VISIT(m->defaults); + return 0; +} +static PyObject* +__Pyx_CyFunction_repr(__pyx_CyFunctionObject *op) +{ + PyObject *repr; + __Pyx_BEGIN_CRITICAL_SECTION(op); + repr = PyUnicode_FromFormat("", + op->func_qualname, (void *)op); + __Pyx_END_CRITICAL_SECTION(); + return repr; +} +static PyObject * __Pyx_CyFunction_CallMethod(PyObject *func, PyObject *self, PyObject *arg, PyObject *kw) { +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *f = ((__pyx_CyFunctionObject*)func)->func; + PyCFunction meth; + int flags; + meth = PyCFunction_GetFunction(f); + if (unlikely(!meth)) return NULL; + flags = PyCFunction_GetFlags(f); + if (unlikely(flags < 0)) return NULL; +#else + PyCFunctionObject* f = (PyCFunctionObject*)func; + PyCFunction meth = f->m_ml->ml_meth; + int flags = f->m_ml->ml_flags; +#endif + Py_ssize_t size; + switch (flags & (METH_VARARGS | METH_KEYWORDS | METH_NOARGS | METH_O)) { + case METH_VARARGS: + if (likely(kw == NULL || PyDict_Size(kw) == 0)) + return (*meth)(self, arg); + break; + case METH_VARARGS | METH_KEYWORDS: + return (*(PyCFunctionWithKeywords)(void(*)(void))meth)(self, arg, kw); + case METH_NOARGS: + if (likely(kw == NULL || PyDict_Size(kw) == 0)) { +#if CYTHON_ASSUME_SAFE_SIZE + size = PyTuple_GET_SIZE(arg); +#else + size = PyTuple_Size(arg); + if (unlikely(size < 0)) return NULL; +#endif + if (likely(size == 0)) + return (*meth)(self, NULL); + __Pyx_CyFunction_raise_argument_count_error( + (__pyx_CyFunctionObject*)func, + "takes no arguments", size); + return NULL; + } + break; + case METH_O: + if (likely(kw == NULL || PyDict_Size(kw) == 0)) { +#if CYTHON_ASSUME_SAFE_SIZE + size = PyTuple_GET_SIZE(arg); +#else + size = PyTuple_Size(arg); + if (unlikely(size < 0)) return NULL; +#endif + if (likely(size == 1)) { + PyObject *result, *arg0; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + arg0 = PyTuple_GET_ITEM(arg, 0); + #else + arg0 = __Pyx_PySequence_ITEM(arg, 0); if (unlikely(!arg0)) return NULL; + #endif + result = (*meth)(self, arg0); + #if !(CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS) + Py_DECREF(arg0); + #endif + return result; + } + __Pyx_CyFunction_raise_argument_count_error( + (__pyx_CyFunctionObject*)func, + "takes exactly one argument", size); + return NULL; + } + break; + default: + PyErr_SetString(PyExc_SystemError, "Bad call flags for CyFunction"); + return NULL; + } + __Pyx_CyFunction_raise_type_error( + (__pyx_CyFunctionObject*)func, "takes no keyword arguments"); + return NULL; +} +static CYTHON_INLINE PyObject *__Pyx_CyFunction_Call(PyObject *func, PyObject *arg, PyObject *kw) { + PyObject *self, *result; +#if CYTHON_COMPILING_IN_LIMITED_API + self = PyCFunction_GetSelf(((__pyx_CyFunctionObject*)func)->func); + if (unlikely(!self) && PyErr_Occurred()) return NULL; +#else + self = ((PyCFunctionObject*)func)->m_self; +#endif + result = __Pyx_CyFunction_CallMethod(func, self, arg, kw); + return result; +} +static PyObject *__Pyx_CyFunction_CallAsMethod(PyObject *func, PyObject *args, PyObject *kw) { + PyObject *result; + __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *) func; +#if CYTHON_METH_FASTCALL && CYTHON_VECTORCALL + __pyx_vectorcallfunc vc = __Pyx_CyFunction_func_vectorcall(cyfunc); + if (vc) { +#if CYTHON_ASSUME_SAFE_MACROS && CYTHON_ASSUME_SAFE_SIZE + return __Pyx_PyVectorcall_FastCallDict(func, vc, &PyTuple_GET_ITEM(args, 0), (size_t)PyTuple_GET_SIZE(args), kw); +#else + (void) &__Pyx_PyVectorcall_FastCallDict; + return PyVectorcall_Call(func, args, kw); +#endif + } +#endif + if ((cyfunc->flags & __Pyx_CYFUNCTION_CCLASS) && !(cyfunc->flags & __Pyx_CYFUNCTION_STATICMETHOD)) { + Py_ssize_t argc; + PyObject *new_args; + PyObject *self; +#if CYTHON_ASSUME_SAFE_SIZE + argc = PyTuple_GET_SIZE(args); +#else + argc = PyTuple_Size(args); + if (unlikely(argc < 0)) return NULL; +#endif + new_args = PyTuple_GetSlice(args, 1, argc); + if (unlikely(!new_args)) + return NULL; + self = PyTuple_GetItem(args, 0); + if (unlikely(!self)) { + Py_DECREF(new_args); + PyErr_Format(PyExc_TypeError, + "unbound method %.200S() needs an argument", + cyfunc->func_qualname); + return NULL; + } + result = __Pyx_CyFunction_CallMethod(func, self, new_args, kw); + Py_DECREF(new_args); + } else { + result = __Pyx_CyFunction_Call(func, args, kw); + } + return result; +} +#if CYTHON_METH_FASTCALL && CYTHON_VECTORCALL +static CYTHON_INLINE int __Pyx_CyFunction_Vectorcall_CheckArgs(__pyx_CyFunctionObject *cyfunc, Py_ssize_t nargs, PyObject *kwnames) +{ + int ret = 0; + if ((cyfunc->flags & __Pyx_CYFUNCTION_CCLASS) && !(cyfunc->flags & __Pyx_CYFUNCTION_STATICMETHOD)) { + if (unlikely(nargs < 1)) { + __Pyx_CyFunction_raise_type_error( + cyfunc, "needs an argument"); + return -1; + } + ret = 1; + } + if (unlikely(kwnames) && unlikely(__Pyx_PyTuple_GET_SIZE(kwnames))) { + __Pyx_CyFunction_raise_type_error( + cyfunc, "takes no keyword arguments"); + return -1; + } + return ret; +} +static PyObject * __Pyx_CyFunction_Vectorcall_NOARGS(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames) +{ + __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *)func; + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); + PyObject *self; +#if CYTHON_COMPILING_IN_LIMITED_API + PyCFunction meth = PyCFunction_GetFunction(cyfunc->func); + if (unlikely(!meth)) return NULL; +#else + PyCFunction meth = ((PyCFunctionObject*)cyfunc)->m_ml->ml_meth; +#endif + switch (__Pyx_CyFunction_Vectorcall_CheckArgs(cyfunc, nargs, kwnames)) { + case 1: + self = args[0]; + args += 1; + nargs -= 1; + break; + case 0: +#if CYTHON_COMPILING_IN_LIMITED_API + self = PyCFunction_GetSelf(((__pyx_CyFunctionObject*)cyfunc)->func); + if (unlikely(!self) && PyErr_Occurred()) return NULL; +#else + self = ((PyCFunctionObject*)cyfunc)->m_self; +#endif + break; + default: + return NULL; + } + if (unlikely(nargs != 0)) { + __Pyx_CyFunction_raise_argument_count_error( + cyfunc, "takes no arguments", nargs); + return NULL; + } + return meth(self, NULL); +} +static PyObject * __Pyx_CyFunction_Vectorcall_O(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames) +{ + __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *)func; + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); + PyObject *self; +#if CYTHON_COMPILING_IN_LIMITED_API + PyCFunction meth = PyCFunction_GetFunction(cyfunc->func); + if (unlikely(!meth)) return NULL; +#else + PyCFunction meth = ((PyCFunctionObject*)cyfunc)->m_ml->ml_meth; +#endif + switch (__Pyx_CyFunction_Vectorcall_CheckArgs(cyfunc, nargs, kwnames)) { + case 1: + self = args[0]; + args += 1; + nargs -= 1; + break; + case 0: +#if CYTHON_COMPILING_IN_LIMITED_API + self = PyCFunction_GetSelf(((__pyx_CyFunctionObject*)cyfunc)->func); + if (unlikely(!self) && PyErr_Occurred()) return NULL; +#else + self = ((PyCFunctionObject*)cyfunc)->m_self; +#endif + break; + default: + return NULL; + } + if (unlikely(nargs != 1)) { + __Pyx_CyFunction_raise_argument_count_error( + cyfunc, "takes exactly one argument", nargs); + return NULL; + } + return meth(self, args[0]); +} +static PyObject * __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames) +{ + __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *)func; + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); + PyObject *self; +#if CYTHON_COMPILING_IN_LIMITED_API + PyCFunction meth = PyCFunction_GetFunction(cyfunc->func); + if (unlikely(!meth)) return NULL; +#else + PyCFunction meth = ((PyCFunctionObject*)cyfunc)->m_ml->ml_meth; +#endif + switch (__Pyx_CyFunction_Vectorcall_CheckArgs(cyfunc, nargs, NULL)) { + case 1: + self = args[0]; + args += 1; + nargs -= 1; + break; + case 0: +#if CYTHON_COMPILING_IN_LIMITED_API + self = PyCFunction_GetSelf(((__pyx_CyFunctionObject*)cyfunc)->func); + if (unlikely(!self) && PyErr_Occurred()) return NULL; +#else + self = ((PyCFunctionObject*)cyfunc)->m_self; +#endif + break; + default: + return NULL; + } + return ((__Pyx_PyCFunctionFastWithKeywords)(void(*)(void))meth)(self, args, nargs, kwnames); +} +static PyObject * __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS_METHOD(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames) +{ + __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *)func; + PyTypeObject *cls = (PyTypeObject *) __Pyx_CyFunction_GetClassObj(cyfunc); + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); + PyObject *self; +#if CYTHON_COMPILING_IN_LIMITED_API + PyCFunction meth = PyCFunction_GetFunction(cyfunc->func); + if (unlikely(!meth)) return NULL; +#else + PyCFunction meth = ((PyCFunctionObject*)cyfunc)->m_ml->ml_meth; +#endif + switch (__Pyx_CyFunction_Vectorcall_CheckArgs(cyfunc, nargs, NULL)) { + case 1: + self = args[0]; + args += 1; + nargs -= 1; + break; + case 0: +#if CYTHON_COMPILING_IN_LIMITED_API + self = PyCFunction_GetSelf(((__pyx_CyFunctionObject*)cyfunc)->func); + if (unlikely(!self) && PyErr_Occurred()) return NULL; +#else + self = ((PyCFunctionObject*)cyfunc)->m_self; +#endif + break; + default: + return NULL; + } + #if PY_VERSION_HEX < 0x030e00A6 + size_t nargs_value = (size_t) nargs; + #else + Py_ssize_t nargs_value = nargs; + #endif + return ((__Pyx_PyCMethod)(void(*)(void))meth)(self, cls, args, nargs_value, kwnames); +} +#endif +static PyType_Slot __pyx_CyFunctionType_slots[] = { + {Py_tp_dealloc, (void *)__Pyx_CyFunction_dealloc}, + {Py_tp_repr, (void *)__Pyx_CyFunction_repr}, + {Py_tp_call, (void *)__Pyx_CyFunction_CallAsMethod}, + {Py_tp_traverse, (void *)__Pyx_CyFunction_traverse}, + {Py_tp_clear, (void *)__Pyx_CyFunction_clear}, + {Py_tp_methods, (void *)__pyx_CyFunction_methods}, + {Py_tp_members, (void *)__pyx_CyFunction_members}, + {Py_tp_getset, (void *)__pyx_CyFunction_getsets}, + {Py_tp_descr_get, (void *)__Pyx_PyMethod_New}, + {0, 0}, +}; +static PyType_Spec __pyx_CyFunctionType_spec = { + __PYX_TYPE_MODULE_PREFIX "cython_function_or_method", + sizeof(__pyx_CyFunctionObject), + 0, +#ifdef Py_TPFLAGS_METHOD_DESCRIPTOR + Py_TPFLAGS_METHOD_DESCRIPTOR | +#endif +#if CYTHON_METH_FASTCALL +#if defined(Py_TPFLAGS_HAVE_VECTORCALL) + Py_TPFLAGS_HAVE_VECTORCALL | +#elif defined(_Py_TPFLAGS_HAVE_VECTORCALL) + _Py_TPFLAGS_HAVE_VECTORCALL | +#endif +#endif // CYTHON_METH_FASTCALL +#if PY_VERSION_HEX >= 0x030C0000 && !CYTHON_COMPILING_IN_LIMITED_API + Py_TPFLAGS_MANAGED_DICT | +#endif + Py_TPFLAGS_IMMUTABLETYPE | Py_TPFLAGS_DISALLOW_INSTANTIATION | + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, + __pyx_CyFunctionType_slots +}; +static int __pyx_CyFunction_init(PyObject *module) { + __pyx_mstatetype *mstate = __Pyx_PyModule_GetState(module); + mstate->__pyx_CyFunctionType = __Pyx_FetchCommonTypeFromSpec( + mstate->__pyx_CommonTypesMetaclassType, module, &__pyx_CyFunctionType_spec, NULL); + if (unlikely(mstate->__pyx_CyFunctionType == NULL)) { + return -1; + } + return 0; +} +static CYTHON_INLINE PyObject *__Pyx_CyFunction_InitDefaults(PyObject *func, PyTypeObject *defaults_type) { + __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; + m->defaults = PyObject_CallObject((PyObject*)defaults_type, NULL); // _PyObject_New(defaults_type); + if (unlikely(!m->defaults)) + return NULL; + return m->defaults; +} +static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsTuple(PyObject *func, PyObject *tuple) { + __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; + m->defaults_tuple = tuple; + Py_INCREF(tuple); +} +static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsKwDict(PyObject *func, PyObject *dict) { + __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; + m->defaults_kwdict = dict; + Py_INCREF(dict); +} +static CYTHON_INLINE void __Pyx_CyFunction_SetAnnotationsDict(PyObject *func, PyObject *dict) { + __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; + m->func_annotations = dict; + Py_INCREF(dict); +} + +/* CythonFunction */ +static PyObject *__Pyx_CyFunction_New(PyMethodDef *ml, int flags, PyObject* qualname, + PyObject *closure, PyObject *module, PyObject* globals, PyObject* code) { + PyObject *op = __Pyx_CyFunction_Init( + PyObject_GC_New(__pyx_CyFunctionObject, __pyx_mstate_global->__pyx_CyFunctionType), + ml, flags, qualname, closure, module, globals, code + ); + if (likely(op)) { + PyObject_GC_Track(op); + } + return op; +} + +/* Py3UpdateBases */ +static PyObject* +__Pyx_PEP560_update_bases(PyObject *bases) +{ + Py_ssize_t i, j, size_bases; + PyObject *base = NULL, *meth, *new_base, *result, *new_bases = NULL; +#if CYTHON_ASSUME_SAFE_SIZE + size_bases = PyTuple_GET_SIZE(bases); +#else + size_bases = PyTuple_Size(bases); + if (size_bases < 0) return NULL; +#endif + for (i = 0; i < size_bases; i++) { +#if CYTHON_AVOID_BORROWED_REFS + Py_CLEAR(base); +#endif +#if CYTHON_ASSUME_SAFE_MACROS + base = PyTuple_GET_ITEM(bases, i); +#else + base = PyTuple_GetItem(bases, i); + if (!base) goto error; +#endif +#if CYTHON_AVOID_BORROWED_REFS + Py_INCREF(base); +#endif + if (PyType_Check(base)) { + if (new_bases) { + if (PyList_Append(new_bases, base) < 0) { + goto error; + } + } + continue; + } + meth = __Pyx_PyObject_GetAttrStrNoError(base, __pyx_mstate_global->__pyx_n_u_mro_entries); + if (!meth && PyErr_Occurred()) { + goto error; + } + if (!meth) { + if (new_bases) { + if (PyList_Append(new_bases, base) < 0) { + goto error; + } + } + continue; + } + new_base = __Pyx_PyObject_CallOneArg(meth, bases); + Py_DECREF(meth); + if (!new_base) { + goto error; + } + if (!PyTuple_Check(new_base)) { + PyErr_SetString(PyExc_TypeError, + "__mro_entries__ must return a tuple"); + Py_DECREF(new_base); + goto error; + } + if (!new_bases) { + if (!(new_bases = PyList_New(i))) { + goto error; + } + for (j = 0; j < i; j++) { + PyObject *base_from_list; +#if CYTHON_ASSUME_SAFE_MACROS + base_from_list = PyTuple_GET_ITEM(bases, j); + PyList_SET_ITEM(new_bases, j, base_from_list); + Py_INCREF(base_from_list); +#else + base_from_list = PyTuple_GetItem(bases, j); + if (!base_from_list) goto error; + Py_INCREF(base_from_list); + if (PyList_SetItem(new_bases, j, base_from_list) < 0) goto error; +#endif + } + } +#if CYTHON_ASSUME_SAFE_SIZE + j = PyList_GET_SIZE(new_bases); +#else + j = PyList_Size(new_bases); + if (j < 0) goto error; +#endif + if (PyList_SetSlice(new_bases, j, j, new_base) < 0) { + goto error; + } + Py_DECREF(new_base); + } + if (!new_bases) { + Py_INCREF(bases); + return bases; + } + result = PyList_AsTuple(new_bases); + Py_DECREF(new_bases); +#if CYTHON_AVOID_BORROWED_REFS + Py_XDECREF(base); +#endif + return result; +error: + Py_XDECREF(new_bases); +#if CYTHON_AVOID_BORROWED_REFS + Py_XDECREF(base); +#endif + return NULL; +} + +/* CalculateMetaclass */ +static PyObject *__Pyx_CalculateMetaclass(PyTypeObject *metaclass, PyObject *bases) { + Py_ssize_t i, nbases; +#if CYTHON_ASSUME_SAFE_SIZE + nbases = PyTuple_GET_SIZE(bases); +#else + nbases = PyTuple_Size(bases); + if (nbases < 0) return NULL; +#endif + for (i=0; i < nbases; i++) { + PyTypeObject *tmptype; +#if CYTHON_ASSUME_SAFE_MACROS + PyObject *tmp = PyTuple_GET_ITEM(bases, i); +#else + PyObject *tmp = PyTuple_GetItem(bases, i); + if (!tmp) return NULL; +#endif + tmptype = Py_TYPE(tmp); + if (!metaclass) { + metaclass = tmptype; + continue; + } + if (PyType_IsSubtype(metaclass, tmptype)) + continue; + if (PyType_IsSubtype(tmptype, metaclass)) { + metaclass = tmptype; + continue; + } + PyErr_SetString(PyExc_TypeError, + "metaclass conflict: " + "the metaclass of a derived class " + "must be a (non-strict) subclass " + "of the metaclasses of all its bases"); + return NULL; + } + if (!metaclass) { + metaclass = &PyType_Type; + } + Py_INCREF((PyObject*) metaclass); + return (PyObject*) metaclass; +} + +/* PyObjectCall2Args (used by Py3ClassCreate) */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call2Args(PyObject* function, PyObject* arg1, PyObject* arg2) { + PyObject *args[3] = {NULL, arg1, arg2}; + return __Pyx_PyObject_FastCall(function, args+1, 2 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET); +} + +/* PyObjectLookupSpecial (used by Py3ClassCreate) */ +#if CYTHON_USE_PYTYPE_LOOKUP && CYTHON_USE_TYPE_SLOTS +static CYTHON_INLINE PyObject* __Pyx__PyObject_LookupSpecial(PyObject* obj, PyObject* attr_name, int with_error) { + PyObject *res; + PyTypeObject *tp = Py_TYPE(obj); + res = _PyType_Lookup(tp, attr_name); + if (likely(res)) { + descrgetfunc f = Py_TYPE(res)->tp_descr_get; + if (!f) { + Py_INCREF(res); + } else { + res = f(res, obj, (PyObject *)tp); + } + } else if (with_error) { + PyErr_SetObject(PyExc_AttributeError, attr_name); + } + return res; +} +#endif + +/* Py3ClassCreate */ +static PyObject *__Pyx_Py3MetaclassPrepare(PyObject *metaclass, PyObject *bases, PyObject *name, + PyObject *qualname, PyObject *mkw, PyObject *modname, PyObject *doc) { + PyObject *ns; + if (metaclass) { + PyObject *prep = __Pyx_PyObject_GetAttrStrNoError(metaclass, __pyx_mstate_global->__pyx_n_u_prepare); + if (prep) { + PyObject *pargs[3] = {NULL, name, bases}; + ns = __Pyx_PyObject_FastCallDict(prep, pargs+1, 2 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET, mkw); + Py_DECREF(prep); + } else { + if (unlikely(PyErr_Occurred())) + return NULL; + ns = PyDict_New(); + } + } else { + ns = PyDict_New(); + } + if (unlikely(!ns)) + return NULL; + if (unlikely(PyObject_SetItem(ns, __pyx_mstate_global->__pyx_n_u_module, modname) < 0)) goto bad; + if (unlikely(PyObject_SetItem(ns, __pyx_mstate_global->__pyx_n_u_qualname, qualname) < 0)) goto bad; + if (unlikely(doc && PyObject_SetItem(ns, __pyx_mstate_global->__pyx_n_u_doc, doc) < 0)) goto bad; + return ns; +bad: + Py_DECREF(ns); + return NULL; +} +static PyObject *__Pyx_Py3ClassCreate(PyObject *metaclass, PyObject *name, PyObject *bases, + PyObject *dict, PyObject *mkw, + int calculate_metaclass, int allow_py2_metaclass) { + PyObject *result; + PyObject *owned_metaclass = NULL; + PyObject *margs[4] = {NULL, name, bases, dict}; + if (allow_py2_metaclass) { + owned_metaclass = PyObject_GetItem(dict, __pyx_mstate_global->__pyx_n_u_metaclass); + if (owned_metaclass) { + metaclass = owned_metaclass; + } else if (likely(PyErr_ExceptionMatches(PyExc_KeyError))) { + PyErr_Clear(); + } else { + return NULL; + } + } + if (calculate_metaclass && (!metaclass || PyType_Check(metaclass))) { + metaclass = __Pyx_CalculateMetaclass((PyTypeObject*) metaclass, bases); + Py_XDECREF(owned_metaclass); + if (unlikely(!metaclass)) + return NULL; + owned_metaclass = metaclass; + } + result = __Pyx_PyObject_FastCallDict(metaclass, margs+1, 3 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET, mkw); + Py_XDECREF(owned_metaclass); + return result; +} + +/* CLineInTraceback (used by AddTraceback) */ +#if CYTHON_CLINE_IN_TRACEBACK && CYTHON_CLINE_IN_TRACEBACK_RUNTIME +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000 +#define __Pyx_PyProbablyModule_GetDict(o) __Pyx_XNewRef(PyModule_GetDict(o)) +#elif !CYTHON_COMPILING_IN_CPYTHON || CYTHON_COMPILING_IN_CPYTHON_FREETHREADING +#define __Pyx_PyProbablyModule_GetDict(o) PyObject_GenericGetDict(o, NULL); +#else +PyObject* __Pyx_PyProbablyModule_GetDict(PyObject *o) { + PyObject **dict_ptr = _PyObject_GetDictPtr(o); + return dict_ptr ? __Pyx_XNewRef(*dict_ptr) : NULL; +} +#endif +static int __Pyx_CLineForTraceback(PyThreadState *tstate, int c_line) { + PyObject *use_cline = NULL; + PyObject *ptype, *pvalue, *ptraceback; + PyObject *cython_runtime_dict; + CYTHON_MAYBE_UNUSED_VAR(tstate); + if (unlikely(!__pyx_mstate_global->__pyx_cython_runtime)) { + return c_line; + } + __Pyx_ErrFetchInState(tstate, &ptype, &pvalue, &ptraceback); + cython_runtime_dict = __Pyx_PyProbablyModule_GetDict(__pyx_mstate_global->__pyx_cython_runtime); + if (likely(cython_runtime_dict)) { + __PYX_PY_DICT_LOOKUP_IF_MODIFIED( + use_cline, cython_runtime_dict, + __Pyx_PyDict_SetDefault(cython_runtime_dict, __pyx_mstate_global->__pyx_n_u_cline_in_traceback, Py_False)) + } + if (use_cline == NULL || use_cline == Py_False || (use_cline != Py_True && PyObject_Not(use_cline) != 0)) { + c_line = 0; + } + Py_XDECREF(use_cline); + Py_XDECREF(cython_runtime_dict); + __Pyx_ErrRestoreInState(tstate, ptype, pvalue, ptraceback); + return c_line; +} +#endif + +/* CodeObjectCache (used by AddTraceback) */ +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { + int start = 0, mid = 0, end = count - 1; + if (end >= 0 && code_line > entries[end].code_line) { + return count; + } + while (start < end) { + mid = start + (end - start) / 2; + if (code_line < entries[mid].code_line) { + end = mid; + } else if (code_line > entries[mid].code_line) { + start = mid + 1; + } else { + return mid; + } + } + if (code_line <= entries[mid].code_line) { + return mid; + } else { + return mid + 1; + } +} +static __Pyx_CachedCodeObjectType *__pyx__find_code_object(struct __Pyx_CodeObjectCache *code_cache, int code_line) { + __Pyx_CachedCodeObjectType* code_object; + int pos; + if (unlikely(!code_line) || unlikely(!code_cache->entries)) { + return NULL; + } + pos = __pyx_bisect_code_objects(code_cache->entries, code_cache->count, code_line); + if (unlikely(pos >= code_cache->count) || unlikely(code_cache->entries[pos].code_line != code_line)) { + return NULL; + } + code_object = code_cache->entries[pos].code_object; + Py_INCREF(code_object); + return code_object; +} +static __Pyx_CachedCodeObjectType *__pyx_find_code_object(int code_line) { +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING && !CYTHON_ATOMICS + (void)__pyx__find_code_object; + return NULL; // Most implementation should have atomics. But otherwise, don't make it thread-safe, just miss. +#else + struct __Pyx_CodeObjectCache *code_cache = &__pyx_mstate_global->__pyx_code_cache; +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + __pyx_nonatomic_int_type old_count = __pyx_atomic_incr_acq_rel(&code_cache->accessor_count); + if (old_count < 0) { + __pyx_atomic_decr_acq_rel(&code_cache->accessor_count); + return NULL; + } +#endif + __Pyx_CachedCodeObjectType *result = __pyx__find_code_object(code_cache, code_line); +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + __pyx_atomic_decr_acq_rel(&code_cache->accessor_count); +#endif + return result; +#endif +} +static void __pyx__insert_code_object(struct __Pyx_CodeObjectCache *code_cache, int code_line, __Pyx_CachedCodeObjectType* code_object) +{ + int pos, i; + __Pyx_CodeObjectCacheEntry* entries = code_cache->entries; + if (unlikely(!code_line)) { + return; + } + if (unlikely(!entries)) { + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); + if (likely(entries)) { + code_cache->entries = entries; + code_cache->max_count = 64; + code_cache->count = 1; + entries[0].code_line = code_line; + entries[0].code_object = code_object; + Py_INCREF(code_object); + } + return; + } + pos = __pyx_bisect_code_objects(code_cache->entries, code_cache->count, code_line); + if ((pos < code_cache->count) && unlikely(code_cache->entries[pos].code_line == code_line)) { + __Pyx_CachedCodeObjectType* tmp = entries[pos].code_object; + entries[pos].code_object = code_object; + Py_INCREF(code_object); + Py_DECREF(tmp); + return; + } + if (code_cache->count == code_cache->max_count) { + int new_max = code_cache->max_count + 64; + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( + code_cache->entries, ((size_t)new_max) * sizeof(__Pyx_CodeObjectCacheEntry)); + if (unlikely(!entries)) { + return; + } + code_cache->entries = entries; + code_cache->max_count = new_max; + } + for (i=code_cache->count; i>pos; i--) { + entries[i] = entries[i-1]; + } + entries[pos].code_line = code_line; + entries[pos].code_object = code_object; + code_cache->count++; + Py_INCREF(code_object); +} +static void __pyx_insert_code_object(int code_line, __Pyx_CachedCodeObjectType* code_object) { +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING && !CYTHON_ATOMICS + (void)__pyx__insert_code_object; + return; // Most implementation should have atomics. But otherwise, don't make it thread-safe, just fail. +#else + struct __Pyx_CodeObjectCache *code_cache = &__pyx_mstate_global->__pyx_code_cache; +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + __pyx_nonatomic_int_type expected = 0; + if (!__pyx_atomic_int_cmp_exchange(&code_cache->accessor_count, &expected, INT_MIN)) { + return; + } +#endif + __pyx__insert_code_object(code_cache, code_line, code_object); +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + __pyx_atomic_sub(&code_cache->accessor_count, INT_MIN); +#endif +#endif +} + +/* AddTraceback */ +#include "compile.h" +#include "frameobject.h" +#include "traceback.h" +#if PY_VERSION_HEX >= 0x030b00a6 && !CYTHON_COMPILING_IN_LIMITED_API && !defined(PYPY_VERSION) + #ifndef Py_BUILD_CORE + #define Py_BUILD_CORE 1 + #endif + #include "internal/pycore_frame.h" +#endif +#if CYTHON_COMPILING_IN_LIMITED_API +static PyObject *__Pyx_PyCode_Replace_For_AddTraceback(PyObject *code, PyObject *scratch_dict, + PyObject *firstlineno, PyObject *name) { + PyObject *replace = NULL; + if (unlikely(PyDict_SetItemString(scratch_dict, "co_firstlineno", firstlineno))) return NULL; + if (unlikely(PyDict_SetItemString(scratch_dict, "co_name", name))) return NULL; + replace = PyObject_GetAttrString(code, "replace"); + if (likely(replace)) { + PyObject *result = PyObject_Call(replace, __pyx_mstate_global->__pyx_empty_tuple, scratch_dict); + Py_DECREF(replace); + return result; + } + PyErr_Clear(); + return NULL; +} +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename) { + PyObject *code_object = NULL, *py_py_line = NULL, *py_funcname = NULL, *dict = NULL; + PyObject *replace = NULL, *getframe = NULL, *frame = NULL; + PyObject *exc_type, *exc_value, *exc_traceback; + int success = 0; + if (c_line) { + c_line = __Pyx_CLineForTraceback(__Pyx_PyThreadState_Current, c_line); + } + PyErr_Fetch(&exc_type, &exc_value, &exc_traceback); + code_object = __pyx_find_code_object(c_line ? -c_line : py_line); + if (!code_object) { + code_object = Py_CompileString("_getframe()", filename, Py_eval_input); + if (unlikely(!code_object)) goto bad; + py_py_line = PyLong_FromLong(py_line); + if (unlikely(!py_py_line)) goto bad; + if (c_line) { + py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + } else { + py_funcname = PyUnicode_FromString(funcname); + } + if (unlikely(!py_funcname)) goto bad; + dict = PyDict_New(); + if (unlikely(!dict)) goto bad; + { + PyObject *old_code_object = code_object; + code_object = __Pyx_PyCode_Replace_For_AddTraceback(code_object, dict, py_py_line, py_funcname); + Py_DECREF(old_code_object); + } + if (unlikely(!code_object)) goto bad; + __pyx_insert_code_object(c_line ? -c_line : py_line, code_object); + } else { + dict = PyDict_New(); + } + getframe = PySys_GetObject("_getframe"); + if (unlikely(!getframe)) goto bad; + if (unlikely(PyDict_SetItemString(dict, "_getframe", getframe))) goto bad; + frame = PyEval_EvalCode(code_object, dict, dict); + if (unlikely(!frame) || frame == Py_None) goto bad; + success = 1; + bad: + PyErr_Restore(exc_type, exc_value, exc_traceback); + Py_XDECREF(code_object); + Py_XDECREF(py_py_line); + Py_XDECREF(py_funcname); + Py_XDECREF(dict); + Py_XDECREF(replace); + if (success) { + PyTraceBack_Here( + (struct _frame*)frame); + } + Py_XDECREF(frame); +} +#else +static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( + const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = NULL; + PyObject *py_funcname = NULL; + if (c_line) { + py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + if (!py_funcname) goto bad; + funcname = PyUnicode_AsUTF8(py_funcname); + if (!funcname) goto bad; + } + py_code = PyCode_NewEmpty(filename, funcname, py_line); + Py_XDECREF(py_funcname); + return py_code; +bad: + Py_XDECREF(py_funcname); + return NULL; +} +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyFrameObject *py_frame = 0; + PyThreadState *tstate = __Pyx_PyThreadState_Current; + PyObject *ptype, *pvalue, *ptraceback; + if (c_line) { + c_line = __Pyx_CLineForTraceback(tstate, c_line); + } + py_code = __pyx_find_code_object(c_line ? -c_line : py_line); + if (!py_code) { + __Pyx_ErrFetchInState(tstate, &ptype, &pvalue, &ptraceback); + py_code = __Pyx_CreateCodeObjectForTraceback( + funcname, c_line, py_line, filename); + if (!py_code) { + /* If the code object creation fails, then we should clear the + fetched exception references and propagate the new exception */ + Py_XDECREF(ptype); + Py_XDECREF(pvalue); + Py_XDECREF(ptraceback); + goto bad; + } + __Pyx_ErrRestoreInState(tstate, ptype, pvalue, ptraceback); + __pyx_insert_code_object(c_line ? -c_line : py_line, py_code); + } + py_frame = PyFrame_New( + tstate, /*PyThreadState *tstate,*/ + py_code, /*PyCodeObject *code,*/ + __pyx_mstate_global->__pyx_d, /*PyObject *globals,*/ + 0 /*PyObject *locals*/ + ); + if (!py_frame) goto bad; + __Pyx_PyFrame_SetLineNumber(py_frame, py_line); + PyTraceBack_Here(py_frame); +bad: + Py_XDECREF(py_code); + Py_XDECREF(py_frame); +} +#endif + +/* CheckUnpickleChecksum */ +static void __Pyx_RaiseUnpickleChecksumError(long checksum, long checksum1, long checksum2, long checksum3, const char *members) { + PyObject *pickle_module = PyImport_ImportModule("pickle"); + if (unlikely(!pickle_module)) return; + PyObject *pickle_error = PyObject_GetAttrString(pickle_module, "PickleError"); + Py_DECREF(pickle_module); + if (unlikely(!pickle_error)) return; + if (checksum2 == checksum1) { + PyErr_Format(pickle_error, "Incompatible checksums (0x%x vs (0x%x) = (%s))", + checksum, checksum1, members); + } else if (checksum3 == checksum2) { + PyErr_Format(pickle_error, "Incompatible checksums (0x%x vs (0x%x, 0x%x) = (%s))", + checksum, checksum1, checksum2, members); + } else { + PyErr_Format(pickle_error, "Incompatible checksums (0x%x vs (0x%x, 0x%x, 0x%x) = (%s))", + checksum, checksum1, checksum2, checksum3, members); + } + Py_DECREF(pickle_error); +} +static int __Pyx_CheckUnpickleChecksum(long checksum, long checksum1, long checksum2, long checksum3, const char *members) { + int found = 0; + found |= checksum1 == checksum; + found |= checksum2 == checksum; + found |= checksum3 == checksum; + if (likely(found)) + return 0; + __Pyx_RaiseUnpickleChecksumError(checksum, checksum1, checksum2, checksum3, members); + return -1; +} + +/* CIntFromPyVerify */ +#define __PYX_VERIFY_RETURN_INT(target_type, func_type, func_value)\ + __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 0) +#define __PYX_VERIFY_RETURN_INT_EXC(target_type, func_type, func_value)\ + __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 1) +#define __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, exc)\ + {\ + func_type value = func_value;\ + if (sizeof(target_type) < sizeof(func_type)) {\ + if (unlikely(value != (func_type) (target_type) value)) {\ + func_type zero = 0;\ + if (exc && unlikely(value == (func_type)-1 && PyErr_Occurred()))\ + return (target_type) -1;\ + if (is_unsigned && unlikely(value < zero))\ + goto raise_neg_overflow;\ + else\ + goto raise_overflow;\ + }\ + }\ + return (target_type) value;\ + } + +/* CIntFromPy */ +static CYTHON_INLINE int __Pyx_PyLong_As_int(PyObject *x) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const int neg_one = (int) -1, const_zero = (int) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (unlikely(!PyLong_Check(x))) { + int val; + PyObject *tmp = __Pyx_PyNumber_Long(x); + if (!tmp) return (int) -1; + val = __Pyx_PyLong_As_int(tmp); + Py_DECREF(tmp); + return val; + } + if (is_unsigned) { +#if CYTHON_USE_PYLONG_INTERNALS + if (unlikely(__Pyx_PyLong_IsNeg(x))) { + goto raise_neg_overflow; + } else if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(int, __Pyx_compact_upylong, __Pyx_PyLong_CompactValueUnsigned(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_DigitCount(x)) { + case 2: + if ((8 * sizeof(int) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) >= 2 * PyLong_SHIFT)) { + return (int) (((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); + } + } + break; + case 3: + if ((8 * sizeof(int) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) >= 3 * PyLong_SHIFT)) { + return (int) (((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); + } + } + break; + case 4: + if ((8 * sizeof(int) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) >= 4 * PyLong_SHIFT)) { + return (int) (((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); + } + } + break; + } + } +#endif +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030C00A7 + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } +#else + { + int result = PyObject_RichCompareBool(x, Py_False, Py_LT); + if (unlikely(result < 0)) + return (int) -1; + if (unlikely(result == 1)) + goto raise_neg_overflow; + } +#endif + if ((sizeof(int) <= sizeof(unsigned long))) { + __PYX_VERIFY_RETURN_INT_EXC(int, unsigned long, PyLong_AsUnsignedLong(x)) + } else if ((sizeof(int) <= sizeof(unsigned PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(int, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) + } + } else { +#if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(int, __Pyx_compact_pylong, __Pyx_PyLong_CompactValue(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_SignedDigitCount(x)) { + case -2: + if ((8 * sizeof(int) - 1 > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 2 * PyLong_SHIFT)) { + return (int) (((int)-1)*(((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case 2: + if ((8 * sizeof(int) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 2 * PyLong_SHIFT)) { + return (int) ((((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case -3: + if ((8 * sizeof(int) - 1 > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 3 * PyLong_SHIFT)) { + return (int) (((int)-1)*(((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case 3: + if ((8 * sizeof(int) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 3 * PyLong_SHIFT)) { + return (int) ((((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case -4: + if ((8 * sizeof(int) - 1 > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 4 * PyLong_SHIFT)) { + return (int) (((int)-1)*(((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case 4: + if ((8 * sizeof(int) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 4 * PyLong_SHIFT)) { + return (int) ((((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + } + } +#endif + if ((sizeof(int) <= sizeof(long))) { + __PYX_VERIFY_RETURN_INT_EXC(int, long, PyLong_AsLong(x)) + } else if ((sizeof(int) <= sizeof(PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(int, PY_LONG_LONG, PyLong_AsLongLong(x)) + } + } + { + int val; + int ret = -1; +#if PY_VERSION_HEX >= 0x030d00A6 && !CYTHON_COMPILING_IN_LIMITED_API + Py_ssize_t bytes_copied = PyLong_AsNativeBytes( + x, &val, sizeof(val), Py_ASNATIVEBYTES_NATIVE_ENDIAN | (is_unsigned ? Py_ASNATIVEBYTES_UNSIGNED_BUFFER | Py_ASNATIVEBYTES_REJECT_NEGATIVE : 0)); + if (unlikely(bytes_copied == -1)) { + } else if (unlikely(bytes_copied > (Py_ssize_t) sizeof(val))) { + goto raise_overflow; + } else { + ret = 0; + } +#elif PY_VERSION_HEX < 0x030d0000 && !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API) || defined(_PyLong_AsByteArray) + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + ret = _PyLong_AsByteArray((PyLongObject *)x, + bytes, sizeof(val), + is_little, !is_unsigned); +#else + PyObject *v; + PyObject *stepval = NULL, *mask = NULL, *shift = NULL; + int bits, remaining_bits, is_negative = 0; + int chunk_size = (sizeof(long) < 8) ? 30 : 62; + if (likely(PyLong_CheckExact(x))) { + v = __Pyx_NewRef(x); + } else { + v = PyNumber_Long(x); + if (unlikely(!v)) return (int) -1; + assert(PyLong_CheckExact(v)); + } + { + int result = PyObject_RichCompareBool(v, Py_False, Py_LT); + if (unlikely(result < 0)) { + Py_DECREF(v); + return (int) -1; + } + is_negative = result == 1; + } + if (is_unsigned && unlikely(is_negative)) { + Py_DECREF(v); + goto raise_neg_overflow; + } else if (is_negative) { + stepval = PyNumber_Invert(v); + Py_DECREF(v); + if (unlikely(!stepval)) + return (int) -1; + } else { + stepval = v; + } + v = NULL; + val = (int) 0; + mask = PyLong_FromLong((1L << chunk_size) - 1); if (unlikely(!mask)) goto done; + shift = PyLong_FromLong(chunk_size); if (unlikely(!shift)) goto done; + for (bits = 0; bits < (int) sizeof(int) * 8 - chunk_size; bits += chunk_size) { + PyObject *tmp, *digit; + long idigit; + digit = PyNumber_And(stepval, mask); + if (unlikely(!digit)) goto done; + idigit = PyLong_AsLong(digit); + Py_DECREF(digit); + if (unlikely(idigit < 0)) goto done; + val |= ((int) idigit) << bits; + tmp = PyNumber_Rshift(stepval, shift); + if (unlikely(!tmp)) goto done; + Py_DECREF(stepval); stepval = tmp; + } + Py_DECREF(shift); shift = NULL; + Py_DECREF(mask); mask = NULL; + { + long idigit = PyLong_AsLong(stepval); + if (unlikely(idigit < 0)) goto done; + remaining_bits = ((int) sizeof(int) * 8) - bits - (is_unsigned ? 0 : 1); + if (unlikely(idigit >= (1L << remaining_bits))) + goto raise_overflow; + val |= ((int) idigit) << bits; + } + if (!is_unsigned) { + if (unlikely(val & (((int) 1) << (sizeof(int) * 8 - 1)))) + goto raise_overflow; + if (is_negative) + val = ~val; + } + ret = 0; + done: + Py_XDECREF(shift); + Py_XDECREF(mask); + Py_XDECREF(stepval); +#endif + if (unlikely(ret)) + return (int) -1; + return val; + } +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to int"); + return (int) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to int"); + return (int) -1; +} + +/* CIntFromPy */ +static CYTHON_INLINE long __Pyx_PyLong_As_long(PyObject *x) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const long neg_one = (long) -1, const_zero = (long) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (unlikely(!PyLong_Check(x))) { + long val; + PyObject *tmp = __Pyx_PyNumber_Long(x); + if (!tmp) return (long) -1; + val = __Pyx_PyLong_As_long(tmp); + Py_DECREF(tmp); + return val; + } + if (is_unsigned) { +#if CYTHON_USE_PYLONG_INTERNALS + if (unlikely(__Pyx_PyLong_IsNeg(x))) { + goto raise_neg_overflow; + } else if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(long, __Pyx_compact_upylong, __Pyx_PyLong_CompactValueUnsigned(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_DigitCount(x)) { + case 2: + if ((8 * sizeof(long) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) >= 2 * PyLong_SHIFT)) { + return (long) (((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); + } + } + break; + case 3: + if ((8 * sizeof(long) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) >= 3 * PyLong_SHIFT)) { + return (long) (((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); + } + } + break; + case 4: + if ((8 * sizeof(long) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) >= 4 * PyLong_SHIFT)) { + return (long) (((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); + } + } + break; + } + } +#endif +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030C00A7 + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } +#else + { + int result = PyObject_RichCompareBool(x, Py_False, Py_LT); + if (unlikely(result < 0)) + return (long) -1; + if (unlikely(result == 1)) + goto raise_neg_overflow; + } +#endif + if ((sizeof(long) <= sizeof(unsigned long))) { + __PYX_VERIFY_RETURN_INT_EXC(long, unsigned long, PyLong_AsUnsignedLong(x)) + } else if ((sizeof(long) <= sizeof(unsigned PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(long, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) + } + } else { +#if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(long, __Pyx_compact_pylong, __Pyx_PyLong_CompactValue(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_SignedDigitCount(x)) { + case -2: + if ((8 * sizeof(long) - 1 > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 2 * PyLong_SHIFT)) { + return (long) (((long)-1)*(((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case 2: + if ((8 * sizeof(long) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 2 * PyLong_SHIFT)) { + return (long) ((((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case -3: + if ((8 * sizeof(long) - 1 > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 3 * PyLong_SHIFT)) { + return (long) (((long)-1)*(((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case 3: + if ((8 * sizeof(long) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 3 * PyLong_SHIFT)) { + return (long) ((((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case -4: + if ((8 * sizeof(long) - 1 > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 4 * PyLong_SHIFT)) { + return (long) (((long)-1)*(((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case 4: + if ((8 * sizeof(long) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 4 * PyLong_SHIFT)) { + return (long) ((((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + } + } +#endif + if ((sizeof(long) <= sizeof(long))) { + __PYX_VERIFY_RETURN_INT_EXC(long, long, PyLong_AsLong(x)) + } else if ((sizeof(long) <= sizeof(PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(long, PY_LONG_LONG, PyLong_AsLongLong(x)) + } + } + { + long val; + int ret = -1; +#if PY_VERSION_HEX >= 0x030d00A6 && !CYTHON_COMPILING_IN_LIMITED_API + Py_ssize_t bytes_copied = PyLong_AsNativeBytes( + x, &val, sizeof(val), Py_ASNATIVEBYTES_NATIVE_ENDIAN | (is_unsigned ? Py_ASNATIVEBYTES_UNSIGNED_BUFFER | Py_ASNATIVEBYTES_REJECT_NEGATIVE : 0)); + if (unlikely(bytes_copied == -1)) { + } else if (unlikely(bytes_copied > (Py_ssize_t) sizeof(val))) { + goto raise_overflow; + } else { + ret = 0; + } +#elif PY_VERSION_HEX < 0x030d0000 && !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API) || defined(_PyLong_AsByteArray) + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + ret = _PyLong_AsByteArray((PyLongObject *)x, + bytes, sizeof(val), + is_little, !is_unsigned); +#else + PyObject *v; + PyObject *stepval = NULL, *mask = NULL, *shift = NULL; + int bits, remaining_bits, is_negative = 0; + int chunk_size = (sizeof(long) < 8) ? 30 : 62; + if (likely(PyLong_CheckExact(x))) { + v = __Pyx_NewRef(x); + } else { + v = PyNumber_Long(x); + if (unlikely(!v)) return (long) -1; + assert(PyLong_CheckExact(v)); + } + { + int result = PyObject_RichCompareBool(v, Py_False, Py_LT); + if (unlikely(result < 0)) { + Py_DECREF(v); + return (long) -1; + } + is_negative = result == 1; + } + if (is_unsigned && unlikely(is_negative)) { + Py_DECREF(v); + goto raise_neg_overflow; + } else if (is_negative) { + stepval = PyNumber_Invert(v); + Py_DECREF(v); + if (unlikely(!stepval)) + return (long) -1; + } else { + stepval = v; + } + v = NULL; + val = (long) 0; + mask = PyLong_FromLong((1L << chunk_size) - 1); if (unlikely(!mask)) goto done; + shift = PyLong_FromLong(chunk_size); if (unlikely(!shift)) goto done; + for (bits = 0; bits < (int) sizeof(long) * 8 - chunk_size; bits += chunk_size) { + PyObject *tmp, *digit; + long idigit; + digit = PyNumber_And(stepval, mask); + if (unlikely(!digit)) goto done; + idigit = PyLong_AsLong(digit); + Py_DECREF(digit); + if (unlikely(idigit < 0)) goto done; + val |= ((long) idigit) << bits; + tmp = PyNumber_Rshift(stepval, shift); + if (unlikely(!tmp)) goto done; + Py_DECREF(stepval); stepval = tmp; + } + Py_DECREF(shift); shift = NULL; + Py_DECREF(mask); mask = NULL; + { + long idigit = PyLong_AsLong(stepval); + if (unlikely(idigit < 0)) goto done; + remaining_bits = ((int) sizeof(long) * 8) - bits - (is_unsigned ? 0 : 1); + if (unlikely(idigit >= (1L << remaining_bits))) + goto raise_overflow; + val |= ((long) idigit) << bits; + } + if (!is_unsigned) { + if (unlikely(val & (((long) 1) << (sizeof(long) * 8 - 1)))) + goto raise_overflow; + if (is_negative) + val = ~val; + } + ret = 0; + done: + Py_XDECREF(shift); + Py_XDECREF(mask); + Py_XDECREF(stepval); +#endif + if (unlikely(ret)) + return (long) -1; + return val; + } +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to long"); + return (long) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to long"); + return (long) -1; +} + +/* PyObjectVectorCallKwBuilder (used by CIntToPy) */ +#if CYTHON_VECTORCALL +static int __Pyx_VectorcallBuilder_AddArg(PyObject *key, PyObject *value, PyObject *builder, PyObject **args, int n) { + (void)__Pyx_PyObject_FastCallDict; + if (__Pyx_PyTuple_SET_ITEM(builder, n, key) != (0)) return -1; + Py_INCREF(key); + args[n] = value; + return 0; +} +CYTHON_UNUSED static int __Pyx_VectorcallBuilder_AddArg_Check(PyObject *key, PyObject *value, PyObject *builder, PyObject **args, int n) { + (void)__Pyx_VectorcallBuilder_AddArgStr; + if (unlikely(!PyUnicode_Check(key))) { + PyErr_SetString(PyExc_TypeError, "keywords must be strings"); + return -1; + } + return __Pyx_VectorcallBuilder_AddArg(key, value, builder, args, n); +} +static int __Pyx_VectorcallBuilder_AddArgStr(const char *key, PyObject *value, PyObject *builder, PyObject **args, int n) { + PyObject *pyKey = PyUnicode_FromString(key); + if (!pyKey) return -1; + return __Pyx_VectorcallBuilder_AddArg(pyKey, value, builder, args, n); +} +#else // CYTHON_VECTORCALL +CYTHON_UNUSED static int __Pyx_VectorcallBuilder_AddArg_Check(PyObject *key, PyObject *value, PyObject *builder, CYTHON_UNUSED PyObject **args, CYTHON_UNUSED int n) { + if (unlikely(!PyUnicode_Check(key))) { + PyErr_SetString(PyExc_TypeError, "keywords must be strings"); + return -1; + } + return PyDict_SetItem(builder, key, value); +} +#endif + +/* CIntToPy */ +static CYTHON_INLINE PyObject* __Pyx_PyLong_From_int(int value) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const int neg_one = (int) -1, const_zero = (int) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(int) < sizeof(long)) { + return PyLong_FromLong((long) value); + } else if (sizeof(int) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); +#if !CYTHON_COMPILING_IN_PYPY + } else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) { + return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); +#endif + } + } else { + if (sizeof(int) <= sizeof(long)) { + return PyLong_FromLong((long) value); + } else if (sizeof(int) <= sizeof(PY_LONG_LONG)) { + return PyLong_FromLongLong((PY_LONG_LONG) value); + } + } + { + unsigned char *bytes = (unsigned char *)&value; +#if !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d00A4 + if (is_unsigned) { + return PyLong_FromUnsignedNativeBytes(bytes, sizeof(value), -1); + } else { + return PyLong_FromNativeBytes(bytes, sizeof(value), -1); + } +#elif !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030d0000 + int one = 1; int little = (int)*(unsigned char *)&one; + return _PyLong_FromByteArray(bytes, sizeof(int), + little, !is_unsigned); +#else + int one = 1; int little = (int)*(unsigned char *)&one; + PyObject *from_bytes, *result = NULL, *kwds = NULL; + PyObject *py_bytes = NULL, *order_str = NULL; + from_bytes = PyObject_GetAttrString((PyObject*)&PyLong_Type, "from_bytes"); + if (!from_bytes) return NULL; + py_bytes = PyBytes_FromStringAndSize((char*)bytes, sizeof(int)); + if (!py_bytes) goto limited_bad; + order_str = PyUnicode_FromString(little ? "little" : "big"); + if (!order_str) goto limited_bad; + { + PyObject *args[3+(CYTHON_VECTORCALL ? 1 : 0)] = { NULL, py_bytes, order_str }; + if (!is_unsigned) { + kwds = __Pyx_MakeVectorcallBuilderKwds(1); + if (!kwds) goto limited_bad; + if (__Pyx_VectorcallBuilder_AddArgStr("signed", __Pyx_NewRef(Py_True), kwds, args+3, 0) < 0) goto limited_bad; + } + result = __Pyx_Object_Vectorcall_CallFromBuilder(from_bytes, args+1, 2 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET, kwds); + } + limited_bad: + Py_XDECREF(kwds); + Py_XDECREF(order_str); + Py_XDECREF(py_bytes); + Py_XDECREF(from_bytes); + return result; +#endif + } +} + +/* CIntToPy */ +static CYTHON_INLINE PyObject* __Pyx_PyLong_From_long(long value) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const long neg_one = (long) -1, const_zero = (long) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(long) < sizeof(long)) { + return PyLong_FromLong((long) value); + } else if (sizeof(long) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); +#if !CYTHON_COMPILING_IN_PYPY + } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { + return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); +#endif + } + } else { + if (sizeof(long) <= sizeof(long)) { + return PyLong_FromLong((long) value); + } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { + return PyLong_FromLongLong((PY_LONG_LONG) value); + } + } + { + unsigned char *bytes = (unsigned char *)&value; +#if !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d00A4 + if (is_unsigned) { + return PyLong_FromUnsignedNativeBytes(bytes, sizeof(value), -1); + } else { + return PyLong_FromNativeBytes(bytes, sizeof(value), -1); + } +#elif !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030d0000 + int one = 1; int little = (int)*(unsigned char *)&one; + return _PyLong_FromByteArray(bytes, sizeof(long), + little, !is_unsigned); +#else + int one = 1; int little = (int)*(unsigned char *)&one; + PyObject *from_bytes, *result = NULL, *kwds = NULL; + PyObject *py_bytes = NULL, *order_str = NULL; + from_bytes = PyObject_GetAttrString((PyObject*)&PyLong_Type, "from_bytes"); + if (!from_bytes) return NULL; + py_bytes = PyBytes_FromStringAndSize((char*)bytes, sizeof(long)); + if (!py_bytes) goto limited_bad; + order_str = PyUnicode_FromString(little ? "little" : "big"); + if (!order_str) goto limited_bad; + { + PyObject *args[3+(CYTHON_VECTORCALL ? 1 : 0)] = { NULL, py_bytes, order_str }; + if (!is_unsigned) { + kwds = __Pyx_MakeVectorcallBuilderKwds(1); + if (!kwds) goto limited_bad; + if (__Pyx_VectorcallBuilder_AddArgStr("signed", __Pyx_NewRef(Py_True), kwds, args+3, 0) < 0) goto limited_bad; + } + result = __Pyx_Object_Vectorcall_CallFromBuilder(from_bytes, args+1, 2 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET, kwds); + } + limited_bad: + Py_XDECREF(kwds); + Py_XDECREF(order_str); + Py_XDECREF(py_bytes); + Py_XDECREF(from_bytes); + return result; +#endif + } +} + +/* PyObjectCallMethod1 */ +#if !(CYTHON_VECTORCALL && (__PYX_LIMITED_VERSION_HEX >= 0x030C0000 || (!CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x03090000))) +static PyObject* __Pyx__PyObject_CallMethod1(PyObject* method, PyObject* arg) { + PyObject *result = __Pyx_PyObject_CallOneArg(method, arg); + Py_DECREF(method); + return result; +} +#endif +static PyObject* __Pyx_PyObject_CallMethod1(PyObject* obj, PyObject* method_name, PyObject* arg) { +#if CYTHON_VECTORCALL && (__PYX_LIMITED_VERSION_HEX >= 0x030C0000 || (!CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x03090000)) + PyObject *args[2] = {obj, arg}; + (void) __Pyx_PyObject_CallOneArg; + (void) __Pyx_PyObject_Call2Args; + return PyObject_VectorcallMethod(method_name, args, 2 | PY_VECTORCALL_ARGUMENTS_OFFSET, NULL); +#else + PyObject *method = NULL, *result; + int is_method = __Pyx_PyObject_GetMethod(obj, method_name, &method); + if (likely(is_method)) { + result = __Pyx_PyObject_Call2Args(method, obj, arg); + Py_DECREF(method); + return result; + } + if (unlikely(!method)) return NULL; + return __Pyx__PyObject_CallMethod1(method, arg); +#endif +} + +/* UpdateUnpickledDict */ +static int __Pyx__UpdateUnpickledDict(PyObject *obj, PyObject *state, Py_ssize_t index) { + PyObject *state_dict = __Pyx_PySequence_ITEM(state, index); + if (unlikely(!state_dict)) { + return -1; + } + int non_empty = PyObject_IsTrue(state_dict); + if (non_empty == 0) { + Py_DECREF(state_dict); + return 0; + } else if (unlikely(non_empty == -1)) { + return -1; + } + PyObject *dict; + #if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000 + dict = PyObject_GetAttrString(obj, "__dict__"); + #else + dict = PyObject_GenericGetDict(obj, NULL); + #endif + if (unlikely(!dict)) { + Py_DECREF(state_dict); + return -1; + } + int result; + if (likely(PyDict_CheckExact(dict))) { + result = PyDict_Update(dict, state_dict); + } else { + PyObject *obj_result = __Pyx_PyObject_CallMethod1(dict, __pyx_mstate_global->__pyx_n_u_update, state_dict); + if (likely(obj_result)) { + Py_DECREF(obj_result); + result = 0; + } else { + result = -1; + } + } + Py_DECREF(state_dict); + Py_DECREF(dict); + return result; +} +static int __Pyx_UpdateUnpickledDict(PyObject *obj, PyObject *state, Py_ssize_t index) { + Py_ssize_t state_size = __Pyx_PyTuple_GET_SIZE(state); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(state_size == -1)) return -1; + #endif + if (state_size <= index) { + return 0; + } + return __Pyx__UpdateUnpickledDict(obj, state, index); +} + +/* FormatTypeName */ +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030d0000 +static __Pyx_TypeName +__Pyx_PyType_GetFullyQualifiedName(PyTypeObject* tp) +{ + PyObject *module = NULL, *name = NULL, *result = NULL; + #if __PYX_LIMITED_VERSION_HEX < 0x030b0000 + name = __Pyx_PyObject_GetAttrStr((PyObject *)tp, + __pyx_mstate_global->__pyx_n_u_qualname); + #else + name = PyType_GetQualName(tp); + #endif + if (unlikely(name == NULL) || unlikely(!PyUnicode_Check(name))) goto bad; + module = __Pyx_PyObject_GetAttrStr((PyObject *)tp, + __pyx_mstate_global->__pyx_n_u_module); + if (unlikely(module == NULL) || unlikely(!PyUnicode_Check(module))) goto bad; + if (PyUnicode_CompareWithASCIIString(module, "builtins") == 0) { + result = name; + name = NULL; + goto done; + } + result = PyUnicode_FromFormat("%U.%U", module, name); + if (unlikely(result == NULL)) goto bad; + done: + Py_XDECREF(name); + Py_XDECREF(module); + return result; + bad: + PyErr_Clear(); + if (name) { + result = name; + name = NULL; + } else { + result = __Pyx_NewRef(__pyx_mstate_global->__pyx_kp_u__4); + } + goto done; +} +#endif + +/* FastTypeChecks */ +#if CYTHON_COMPILING_IN_CPYTHON +static int __Pyx_InBases(PyTypeObject *a, PyTypeObject *b) { + while (a) { + a = __Pyx_PyType_GetSlot(a, tp_base, PyTypeObject*); + if (a == b) + return 1; + } + return b == &PyBaseObject_Type; +} +static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b) { + PyObject *mro; + if (a == b) return 1; + mro = a->tp_mro; + if (likely(mro)) { + Py_ssize_t i, n; + n = PyTuple_GET_SIZE(mro); + for (i = 0; i < n; i++) { + if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b) + return 1; + } + return 0; + } + return __Pyx_InBases(a, b); +} +static CYTHON_INLINE int __Pyx_IsAnySubtype2(PyTypeObject *cls, PyTypeObject *a, PyTypeObject *b) { + PyObject *mro; + if (cls == a || cls == b) return 1; + mro = cls->tp_mro; + if (likely(mro)) { + Py_ssize_t i, n; + n = PyTuple_GET_SIZE(mro); + for (i = 0; i < n; i++) { + PyObject *base = PyTuple_GET_ITEM(mro, i); + if (base == (PyObject *)a || base == (PyObject *)b) + return 1; + } + return 0; + } + return __Pyx_InBases(cls, a) || __Pyx_InBases(cls, b); +} +static CYTHON_INLINE int __Pyx_inner_PyErr_GivenExceptionMatches2(PyObject *err, PyObject* exc_type1, PyObject *exc_type2) { + if (exc_type1) { + return __Pyx_IsAnySubtype2((PyTypeObject*)err, (PyTypeObject*)exc_type1, (PyTypeObject*)exc_type2); + } else { + return __Pyx_IsSubtype((PyTypeObject*)err, (PyTypeObject*)exc_type2); + } +} +static int __Pyx_PyErr_GivenExceptionMatchesTuple(PyObject *exc_type, PyObject *tuple) { + Py_ssize_t i, n; + assert(PyExceptionClass_Check(exc_type)); + n = PyTuple_GET_SIZE(tuple); + for (i=0; i>= 8; + ++i; + } + __Pyx_cached_runtime_version = version; + } +} +#endif +static unsigned long __Pyx_get_runtime_version(void) { +#if __PYX_LIMITED_VERSION_HEX >= 0x030b0000 + return Py_Version & ~0xFFUL; +#else + return __Pyx_cached_runtime_version; +#endif +} + +/* CheckBinaryVersion */ +static int __Pyx_check_binary_version(unsigned long ct_version, unsigned long rt_version, int allow_newer) { + const unsigned long MAJOR_MINOR = 0xFFFF0000UL; + if ((rt_version & MAJOR_MINOR) == (ct_version & MAJOR_MINOR)) + return 0; + if (likely(allow_newer && (rt_version & MAJOR_MINOR) > (ct_version & MAJOR_MINOR))) + return 1; + { + char message[200]; + PyOS_snprintf(message, sizeof(message), + "compile time Python version %d.%d " + "of module '%.100s' " + "%s " + "runtime version %d.%d", + (int) (ct_version >> 24), (int) ((ct_version >> 16) & 0xFF), + __Pyx_MODULE_NAME, + (allow_newer) ? "was newer than" : "does not match", + (int) (rt_version >> 24), (int) ((rt_version >> 16) & 0xFF) + ); + return PyErr_WarnEx(NULL, message, 1); + } +} + +/* NewCodeObj */ +#if CYTHON_COMPILING_IN_LIMITED_API + static PyObject* __Pyx__PyCode_New(int a, int p, int k, int l, int s, int f, + PyObject *code, PyObject *c, PyObject* n, PyObject *v, + PyObject *fv, PyObject *cell, PyObject* fn, + PyObject *name, int fline, PyObject *lnos) { + PyObject *exception_table = NULL; + PyObject *types_module=NULL, *code_type=NULL, *result=NULL; + #if __PYX_LIMITED_VERSION_HEX < 0x030b0000 + PyObject *version_info; + PyObject *py_minor_version = NULL; + #endif + long minor_version = 0; + PyObject *type, *value, *traceback; + PyErr_Fetch(&type, &value, &traceback); + #if __PYX_LIMITED_VERSION_HEX >= 0x030b0000 + minor_version = 11; + #else + if (!(version_info = PySys_GetObject("version_info"))) goto end; + if (!(py_minor_version = PySequence_GetItem(version_info, 1))) goto end; + minor_version = PyLong_AsLong(py_minor_version); + Py_DECREF(py_minor_version); + if (minor_version == -1 && PyErr_Occurred()) goto end; + #endif + if (!(types_module = PyImport_ImportModule("types"))) goto end; + if (!(code_type = PyObject_GetAttrString(types_module, "CodeType"))) goto end; + if (minor_version <= 7) { + (void)p; + result = PyObject_CallFunction(code_type, "iiiiiOOOOOOiOOO", a, k, l, s, f, code, + c, n, v, fn, name, fline, lnos, fv, cell); + } else if (minor_version <= 10) { + result = PyObject_CallFunction(code_type, "iiiiiiOOOOOOiOOO", a,p, k, l, s, f, code, + c, n, v, fn, name, fline, lnos, fv, cell); + } else { + if (!(exception_table = PyBytes_FromStringAndSize(NULL, 0))) goto end; + result = PyObject_CallFunction(code_type, "iiiiiiOOOOOOOiOOOO", a,p, k, l, s, f, code, + c, n, v, fn, name, name, fline, lnos, exception_table, fv, cell); + } + end: + Py_XDECREF(code_type); + Py_XDECREF(exception_table); + Py_XDECREF(types_module); + if (type) { + PyErr_Restore(type, value, traceback); + } + return result; + } +#elif PY_VERSION_HEX >= 0x030B0000 + static PyCodeObject* __Pyx__PyCode_New(int a, int p, int k, int l, int s, int f, + PyObject *code, PyObject *c, PyObject* n, PyObject *v, + PyObject *fv, PyObject *cell, PyObject* fn, + PyObject *name, int fline, PyObject *lnos) { + PyCodeObject *result; + result = + #if PY_VERSION_HEX >= 0x030C0000 + PyUnstable_Code_NewWithPosOnlyArgs + #else + PyCode_NewWithPosOnlyArgs + #endif + (a, p, k, l, s, f, code, c, n, v, fv, cell, fn, name, name, fline, lnos, __pyx_mstate_global->__pyx_empty_bytes); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030c00A1 + if (likely(result)) + result->_co_firsttraceable = 0; + #endif + return result; + } +#elif !CYTHON_COMPILING_IN_PYPY + #define __Pyx__PyCode_New(a, p, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ + PyCode_NewWithPosOnlyArgs(a, p, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) +#else + #define __Pyx__PyCode_New(a, p, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ + PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) +#endif +static PyObject* __Pyx_PyCode_New( + const __Pyx_PyCode_New_function_description descr, + PyObject * const *varnames, + PyObject *filename, + PyObject *funcname, + PyObject *line_table, + PyObject *tuple_dedup_map +) { + PyObject *code_obj = NULL, *varnames_tuple_dedup = NULL, *code_bytes = NULL; + Py_ssize_t var_count = (Py_ssize_t) descr.nlocals; + PyObject *varnames_tuple = PyTuple_New(var_count); + if (unlikely(!varnames_tuple)) return NULL; + for (Py_ssize_t i=0; i < var_count; i++) { + Py_INCREF(varnames[i]); + if (__Pyx_PyTuple_SET_ITEM(varnames_tuple, i, varnames[i]) != (0)) goto done; + } + #if CYTHON_COMPILING_IN_LIMITED_API + varnames_tuple_dedup = PyDict_GetItem(tuple_dedup_map, varnames_tuple); + if (!varnames_tuple_dedup) { + if (unlikely(PyDict_SetItem(tuple_dedup_map, varnames_tuple, varnames_tuple) < 0)) goto done; + varnames_tuple_dedup = varnames_tuple; + } + #else + varnames_tuple_dedup = PyDict_SetDefault(tuple_dedup_map, varnames_tuple, varnames_tuple); + if (unlikely(!varnames_tuple_dedup)) goto done; + #endif + #if CYTHON_AVOID_BORROWED_REFS + Py_INCREF(varnames_tuple_dedup); + #endif + if (__PYX_LIMITED_VERSION_HEX >= (0x030b0000) && line_table != NULL && !CYTHON_COMPILING_IN_GRAAL) { + Py_ssize_t line_table_length = __Pyx_PyBytes_GET_SIZE(line_table); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(line_table_length == -1)) goto done; + #endif + Py_ssize_t code_len = (line_table_length * 2 + 4) & ~3LL; + code_bytes = PyBytes_FromStringAndSize(NULL, code_len); + if (unlikely(!code_bytes)) goto done; + char* c_code_bytes = PyBytes_AsString(code_bytes); + if (unlikely(!c_code_bytes)) goto done; + memset(c_code_bytes, 0, (size_t) code_len); + } + code_obj = (PyObject*) __Pyx__PyCode_New( + (int) descr.argcount, + (int) descr.num_posonly_args, + (int) descr.num_kwonly_args, + (int) descr.nlocals, + 0, + (int) descr.flags, + code_bytes ? code_bytes : __pyx_mstate_global->__pyx_empty_bytes, + __pyx_mstate_global->__pyx_empty_tuple, + __pyx_mstate_global->__pyx_empty_tuple, + varnames_tuple_dedup, + __pyx_mstate_global->__pyx_empty_tuple, + __pyx_mstate_global->__pyx_empty_tuple, + filename, + funcname, + (int) descr.first_line, + (__PYX_LIMITED_VERSION_HEX >= (0x030b0000) && line_table) ? line_table : __pyx_mstate_global->__pyx_empty_bytes + ); +done: + Py_XDECREF(code_bytes); + #if CYTHON_AVOID_BORROWED_REFS + Py_XDECREF(varnames_tuple_dedup); + #endif + Py_DECREF(varnames_tuple); + return code_obj; +} + +/* DecompressString */ +static PyObject *__Pyx_DecompressString(const char *s, Py_ssize_t length, int algo) { + PyObject *module = NULL, *decompress, *compressed_bytes, *decompressed; + const char* module_name = algo == 3 ? "compression.zstd" : algo == 2 ? "bz2" : "zlib"; + PyObject *methodname = PyUnicode_FromString("decompress"); + if (unlikely(!methodname)) return NULL; + #if __PYX_LIMITED_VERSION_HEX >= 0x030e0000 + if (algo == 3) { + PyObject *fromlist = Py_BuildValue("[O]", methodname); + if (unlikely(!fromlist)) goto bad; + module = PyImport_ImportModuleLevel("compression.zstd", NULL, NULL, fromlist, 0); + Py_DECREF(fromlist); + } else + #endif + module = PyImport_ImportModule(module_name); + if (unlikely(!module)) goto import_failed; + decompress = PyObject_GetAttr(module, methodname); + if (unlikely(!decompress)) goto import_failed; + { + #ifdef __cplusplus + char *memview_bytes = const_cast(s); + #else + #if defined(__clang__) + #pragma clang diagnostic push + #pragma clang diagnostic ignored "-Wcast-qual" + #elif !defined(__INTEL_COMPILER) && defined(__GNUC__) + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wcast-qual" + #endif + char *memview_bytes = (char*) s; + #if defined(__clang__) + #pragma clang diagnostic pop + #elif !defined(__INTEL_COMPILER) && defined(__GNUC__) + #pragma GCC diagnostic pop + #endif + #endif + #if CYTHON_COMPILING_IN_LIMITED_API && !defined(PyBUF_READ) + int memview_flags = 0x100; + #else + int memview_flags = PyBUF_READ; + #endif + compressed_bytes = PyMemoryView_FromMemory(memview_bytes, length, memview_flags); + } + if (unlikely(!compressed_bytes)) { + Py_DECREF(decompress); + goto bad; + } + decompressed = PyObject_CallFunctionObjArgs(decompress, compressed_bytes, NULL); + Py_DECREF(compressed_bytes); + Py_DECREF(decompress); + Py_DECREF(module); + Py_DECREF(methodname); + return decompressed; +import_failed: + PyErr_Format(PyExc_ImportError, + "Failed to import '%.20s.decompress' - cannot initialise module strings. " + "String compression was configured with the C macro 'CYTHON_COMPRESS_STRINGS=%d'.", + module_name, algo); +bad: + Py_XDECREF(module); + Py_DECREF(methodname); + return NULL; +} + +#include +static CYTHON_INLINE Py_ssize_t __Pyx_ssize_strlen(const char *s) { + size_t len = strlen(s); + if (unlikely(len > (size_t) PY_SSIZE_T_MAX)) { + PyErr_SetString(PyExc_OverflowError, "byte string is too long"); + return -1; + } + return (Py_ssize_t) len; +} +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char* c_str) { + Py_ssize_t len = __Pyx_ssize_strlen(c_str); + if (unlikely(len < 0)) return NULL; + return __Pyx_PyUnicode_FromStringAndSize(c_str, len); +} +static CYTHON_INLINE PyObject* __Pyx_PyByteArray_FromString(const char* c_str) { + Py_ssize_t len = __Pyx_ssize_strlen(c_str); + if (unlikely(len < 0)) return NULL; + return PyByteArray_FromStringAndSize(c_str, len); +} +static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject* o) { + Py_ssize_t ignore; + return __Pyx_PyObject_AsStringAndSize(o, &ignore); +} +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 +static CYTHON_INLINE const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *length) { + if (unlikely(__Pyx_PyUnicode_READY(o) == -1)) return NULL; +#if CYTHON_COMPILING_IN_LIMITED_API + { + const char* result; + Py_ssize_t unicode_length; + CYTHON_MAYBE_UNUSED_VAR(unicode_length); // only for __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + #if __PYX_LIMITED_VERSION_HEX < 0x030A0000 + if (unlikely(PyArg_Parse(o, "s#", &result, length) < 0)) return NULL; + #else + result = PyUnicode_AsUTF8AndSize(o, length); + #endif + #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + unicode_length = PyUnicode_GetLength(o); + if (unlikely(unicode_length < 0)) return NULL; + if (unlikely(unicode_length != *length)) { + PyUnicode_AsASCIIString(o); + return NULL; + } + #endif + return result; + } +#else +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + if (likely(PyUnicode_IS_ASCII(o))) { + *length = PyUnicode_GET_LENGTH(o); + return PyUnicode_AsUTF8(o); + } else { + PyUnicode_AsASCIIString(o); + return NULL; + } +#else + return PyUnicode_AsUTF8AndSize(o, length); +#endif +#endif +} +#endif +static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 + if (PyUnicode_Check(o)) { + return __Pyx_PyUnicode_AsStringAndSize(o, length); + } else +#endif + if (PyByteArray_Check(o)) { +#if (CYTHON_ASSUME_SAFE_SIZE && CYTHON_ASSUME_SAFE_MACROS) || (CYTHON_COMPILING_IN_PYPY && (defined(PyByteArray_AS_STRING) && defined(PyByteArray_GET_SIZE))) + *length = PyByteArray_GET_SIZE(o); + return PyByteArray_AS_STRING(o); +#else + *length = PyByteArray_Size(o); + if (*length == -1) return NULL; + return PyByteArray_AsString(o); +#endif + } else + { + char* result; + int r = PyBytes_AsStringAndSize(o, &result, length); + if (unlikely(r < 0)) { + return NULL; + } else { + return result; + } + } +} +static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { + int is_true = x == Py_True; + if (is_true | (x == Py_False) | (x == Py_None)) return is_true; + else return PyObject_IsTrue(x); +} +static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject* x) { + int retval; + if (unlikely(!x)) return -1; + retval = __Pyx_PyObject_IsTrue(x); + Py_DECREF(x); + return retval; +} +static PyObject* __Pyx_PyNumber_LongWrongResultType(PyObject* result) { + __Pyx_TypeName result_type_name = __Pyx_PyType_GetFullyQualifiedName(Py_TYPE(result)); + if (PyLong_Check(result)) { + if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1, + "__int__ returned non-int (type " __Pyx_FMT_TYPENAME "). " + "The ability to return an instance of a strict subclass of int is deprecated, " + "and may be removed in a future version of Python.", + result_type_name)) { + __Pyx_DECREF_TypeName(result_type_name); + Py_DECREF(result); + return NULL; + } + __Pyx_DECREF_TypeName(result_type_name); + return result; + } + PyErr_Format(PyExc_TypeError, + "__int__ returned non-int (type " __Pyx_FMT_TYPENAME ")", + result_type_name); + __Pyx_DECREF_TypeName(result_type_name); + Py_DECREF(result); + return NULL; +} +static CYTHON_INLINE PyObject* __Pyx_PyNumber_Long(PyObject* x) { +#if CYTHON_USE_TYPE_SLOTS + PyNumberMethods *m; +#endif + PyObject *res = NULL; + if (likely(PyLong_Check(x))) + return __Pyx_NewRef(x); +#if CYTHON_USE_TYPE_SLOTS + m = Py_TYPE(x)->tp_as_number; + if (likely(m && m->nb_int)) { + res = m->nb_int(x); + } +#else + if (!PyBytes_CheckExact(x) && !PyUnicode_CheckExact(x)) { + res = PyNumber_Long(x); + } +#endif + if (likely(res)) { + if (unlikely(!PyLong_CheckExact(res))) { + return __Pyx_PyNumber_LongWrongResultType(res); + } + } + else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_TypeError, + "an integer is required"); + } + return res; +} +static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { + Py_ssize_t ival; + PyObject *x; + if (likely(PyLong_CheckExact(b))) { + #if CYTHON_USE_PYLONG_INTERNALS + if (likely(__Pyx_PyLong_IsCompact(b))) { + return __Pyx_PyLong_CompactValue(b); + } else { + const digit* digits = __Pyx_PyLong_Digits(b); + const Py_ssize_t size = __Pyx_PyLong_SignedDigitCount(b); + switch (size) { + case 2: + if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { + return (Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case -2: + if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { + return -(Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case 3: + if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { + return (Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case -3: + if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { + return -(Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case 4: + if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { + return (Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case -4: + if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { + return -(Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + } + } + #endif + return PyLong_AsSsize_t(b); + } + x = PyNumber_Index(b); + if (!x) return -1; + ival = PyLong_AsSsize_t(x); + Py_DECREF(x); + return ival; +} +static CYTHON_INLINE Py_hash_t __Pyx_PyIndex_AsHash_t(PyObject* o) { + if (sizeof(Py_hash_t) == sizeof(Py_ssize_t)) { + return (Py_hash_t) __Pyx_PyIndex_AsSsize_t(o); + } else { + Py_ssize_t ival; + PyObject *x; + x = PyNumber_Index(o); + if (!x) return -1; + ival = PyLong_AsLong(x); + Py_DECREF(x); + return ival; + } +} +static CYTHON_INLINE PyObject *__Pyx_Owned_Py_None(int b) { + CYTHON_UNUSED_VAR(b); + return __Pyx_NewRef(Py_None); +} +static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b) { + return __Pyx_NewRef(b ? Py_True: Py_False); +} +static CYTHON_INLINE PyObject * __Pyx_PyLong_FromSize_t(size_t ival) { + return PyLong_FromSize_t(ival); +} + + +/* MultiPhaseInitModuleState */ +#if CYTHON_PEP489_MULTI_PHASE_INIT && CYTHON_USE_MODULE_STATE +#ifndef CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE +#if (CYTHON_COMPILING_IN_LIMITED_API || PY_VERSION_HEX >= 0x030C0000) + #define CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE 1 +#else + #define CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE 0 +#endif +#endif +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE && !CYTHON_ATOMICS +#error "Module state with PEP489 requires atomics. Currently that's one of\ + C11, C++11, gcc atomic intrinsics or MSVC atomic intrinsics" +#endif +#if !CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE +#define __Pyx_ModuleStateLookup_Lock() +#define __Pyx_ModuleStateLookup_Unlock() +#elif !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d0000 +static PyMutex __Pyx_ModuleStateLookup_mutex = {0}; +#define __Pyx_ModuleStateLookup_Lock() PyMutex_Lock(&__Pyx_ModuleStateLookup_mutex) +#define __Pyx_ModuleStateLookup_Unlock() PyMutex_Unlock(&__Pyx_ModuleStateLookup_mutex) +#elif defined(__cplusplus) && __cplusplus >= 201103L +#include +static std::mutex __Pyx_ModuleStateLookup_mutex; +#define __Pyx_ModuleStateLookup_Lock() __Pyx_ModuleStateLookup_mutex.lock() +#define __Pyx_ModuleStateLookup_Unlock() __Pyx_ModuleStateLookup_mutex.unlock() +#elif defined(__STDC_VERSION__) && (__STDC_VERSION__ > 201112L) && !defined(__STDC_NO_THREADS__) +#include +static mtx_t __Pyx_ModuleStateLookup_mutex; +static once_flag __Pyx_ModuleStateLookup_mutex_once_flag = ONCE_FLAG_INIT; +static void __Pyx_ModuleStateLookup_initialize_mutex(void) { + mtx_init(&__Pyx_ModuleStateLookup_mutex, mtx_plain); +} +#define __Pyx_ModuleStateLookup_Lock()\ + call_once(&__Pyx_ModuleStateLookup_mutex_once_flag, __Pyx_ModuleStateLookup_initialize_mutex);\ + mtx_lock(&__Pyx_ModuleStateLookup_mutex) +#define __Pyx_ModuleStateLookup_Unlock() mtx_unlock(&__Pyx_ModuleStateLookup_mutex) +#elif defined(HAVE_PTHREAD_H) +#include +static pthread_mutex_t __Pyx_ModuleStateLookup_mutex = PTHREAD_MUTEX_INITIALIZER; +#define __Pyx_ModuleStateLookup_Lock() pthread_mutex_lock(&__Pyx_ModuleStateLookup_mutex) +#define __Pyx_ModuleStateLookup_Unlock() pthread_mutex_unlock(&__Pyx_ModuleStateLookup_mutex) +#elif defined(_WIN32) +#include // synchapi.h on its own doesn't work +static SRWLOCK __Pyx_ModuleStateLookup_mutex = SRWLOCK_INIT; +#define __Pyx_ModuleStateLookup_Lock() AcquireSRWLockExclusive(&__Pyx_ModuleStateLookup_mutex) +#define __Pyx_ModuleStateLookup_Unlock() ReleaseSRWLockExclusive(&__Pyx_ModuleStateLookup_mutex) +#else +#error "No suitable lock available for CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE.\ + Requires C standard >= C11, or C++ standard >= C++11,\ + or pthreads, or the Windows 32 API, or Python >= 3.13." +#endif +typedef struct { + int64_t id; + PyObject *module; +} __Pyx_InterpreterIdAndModule; +typedef struct { + char interpreter_id_as_index; + Py_ssize_t count; + Py_ssize_t allocated; + __Pyx_InterpreterIdAndModule table[1]; +} __Pyx_ModuleStateLookupData; +#define __PYX_MODULE_STATE_LOOKUP_SMALL_SIZE 32 +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE +static __pyx_atomic_int_type __Pyx_ModuleStateLookup_read_counter = 0; +#endif +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE +static __pyx_atomic_ptr_type __Pyx_ModuleStateLookup_data = 0; +#else +static __Pyx_ModuleStateLookupData* __Pyx_ModuleStateLookup_data = NULL; +#endif +static __Pyx_InterpreterIdAndModule* __Pyx_State_FindModuleStateLookupTableLowerBound( + __Pyx_InterpreterIdAndModule* table, + Py_ssize_t count, + int64_t interpreterId) { + __Pyx_InterpreterIdAndModule* begin = table; + __Pyx_InterpreterIdAndModule* end = begin + count; + if (begin->id == interpreterId) { + return begin; + } + while ((end - begin) > __PYX_MODULE_STATE_LOOKUP_SMALL_SIZE) { + __Pyx_InterpreterIdAndModule* halfway = begin + (end - begin)/2; + if (halfway->id == interpreterId) { + return halfway; + } + if (halfway->id < interpreterId) { + begin = halfway; + } else { + end = halfway; + } + } + for (; begin < end; ++begin) { + if (begin->id >= interpreterId) return begin; + } + return begin; +} +static PyObject *__Pyx_State_FindModule(CYTHON_UNUSED void* dummy) { + int64_t interpreter_id = PyInterpreterState_GetID(__Pyx_PyInterpreterState_Get()); + if (interpreter_id == -1) return NULL; +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE + __Pyx_ModuleStateLookupData* data = (__Pyx_ModuleStateLookupData*)__pyx_atomic_pointer_load_relaxed(&__Pyx_ModuleStateLookup_data); + { + __pyx_atomic_incr_acq_rel(&__Pyx_ModuleStateLookup_read_counter); + if (likely(data)) { + __Pyx_ModuleStateLookupData* new_data = (__Pyx_ModuleStateLookupData*)__pyx_atomic_pointer_load_acquire(&__Pyx_ModuleStateLookup_data); + if (likely(data == new_data)) { + goto read_finished; + } + } + __pyx_atomic_decr_acq_rel(&__Pyx_ModuleStateLookup_read_counter); + __Pyx_ModuleStateLookup_Lock(); + __pyx_atomic_incr_relaxed(&__Pyx_ModuleStateLookup_read_counter); + data = (__Pyx_ModuleStateLookupData*)__pyx_atomic_pointer_load_relaxed(&__Pyx_ModuleStateLookup_data); + __Pyx_ModuleStateLookup_Unlock(); + } + read_finished:; +#else + __Pyx_ModuleStateLookupData* data = __Pyx_ModuleStateLookup_data; +#endif + __Pyx_InterpreterIdAndModule* found = NULL; + if (unlikely(!data)) goto end; + if (data->interpreter_id_as_index) { + if (interpreter_id < data->count) { + found = data->table+interpreter_id; + } + } else { + found = __Pyx_State_FindModuleStateLookupTableLowerBound( + data->table, data->count, interpreter_id); + } + end: + { + PyObject *result=NULL; + if (found && found->id == interpreter_id) { + result = found->module; + } +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE + __pyx_atomic_decr_acq_rel(&__Pyx_ModuleStateLookup_read_counter); +#endif + return result; + } +} +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE +static void __Pyx_ModuleStateLookup_wait_until_no_readers(void) { + while (__pyx_atomic_load(&__Pyx_ModuleStateLookup_read_counter) != 0); +} +#else +#define __Pyx_ModuleStateLookup_wait_until_no_readers() +#endif +static int __Pyx_State_AddModuleInterpIdAsIndex(__Pyx_ModuleStateLookupData **old_data, PyObject* module, int64_t interpreter_id) { + Py_ssize_t to_allocate = (*old_data)->allocated; + while (to_allocate <= interpreter_id) { + if (to_allocate == 0) to_allocate = 1; + else to_allocate *= 2; + } + __Pyx_ModuleStateLookupData *new_data = *old_data; + if (to_allocate != (*old_data)->allocated) { + new_data = (__Pyx_ModuleStateLookupData *)realloc( + *old_data, + sizeof(__Pyx_ModuleStateLookupData)+(to_allocate-1)*sizeof(__Pyx_InterpreterIdAndModule)); + if (!new_data) { + PyErr_NoMemory(); + return -1; + } + for (Py_ssize_t i = new_data->allocated; i < to_allocate; ++i) { + new_data->table[i].id = i; + new_data->table[i].module = NULL; + } + new_data->allocated = to_allocate; + } + new_data->table[interpreter_id].module = module; + if (new_data->count < interpreter_id+1) { + new_data->count = interpreter_id+1; + } + *old_data = new_data; + return 0; +} +static void __Pyx_State_ConvertFromInterpIdAsIndex(__Pyx_ModuleStateLookupData *data) { + __Pyx_InterpreterIdAndModule *read = data->table; + __Pyx_InterpreterIdAndModule *write = data->table; + __Pyx_InterpreterIdAndModule *end = read + data->count; + for (; readmodule) { + write->id = read->id; + write->module = read->module; + ++write; + } + } + data->count = write - data->table; + for (; writeid = 0; + write->module = NULL; + } + data->interpreter_id_as_index = 0; +} +static int __Pyx_State_AddModule(PyObject* module, CYTHON_UNUSED void* dummy) { + int64_t interpreter_id = PyInterpreterState_GetID(__Pyx_PyInterpreterState_Get()); + if (interpreter_id == -1) return -1; + int result = 0; + __Pyx_ModuleStateLookup_Lock(); +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE + __Pyx_ModuleStateLookupData *old_data = (__Pyx_ModuleStateLookupData *) + __pyx_atomic_pointer_exchange(&__Pyx_ModuleStateLookup_data, 0); +#else + __Pyx_ModuleStateLookupData *old_data = __Pyx_ModuleStateLookup_data; +#endif + __Pyx_ModuleStateLookupData *new_data = old_data; + if (!new_data) { + new_data = (__Pyx_ModuleStateLookupData *)calloc(1, sizeof(__Pyx_ModuleStateLookupData)); + if (!new_data) { + result = -1; + PyErr_NoMemory(); + goto end; + } + new_data->allocated = 1; + new_data->interpreter_id_as_index = 1; + } + __Pyx_ModuleStateLookup_wait_until_no_readers(); + if (new_data->interpreter_id_as_index) { + if (interpreter_id < __PYX_MODULE_STATE_LOOKUP_SMALL_SIZE) { + result = __Pyx_State_AddModuleInterpIdAsIndex(&new_data, module, interpreter_id); + goto end; + } + __Pyx_State_ConvertFromInterpIdAsIndex(new_data); + } + { + Py_ssize_t insert_at = 0; + { + __Pyx_InterpreterIdAndModule* lower_bound = __Pyx_State_FindModuleStateLookupTableLowerBound( + new_data->table, new_data->count, interpreter_id); + assert(lower_bound); + insert_at = lower_bound - new_data->table; + if (unlikely(insert_at < new_data->count && lower_bound->id == interpreter_id)) { + lower_bound->module = module; + goto end; // already in table, nothing more to do + } + } + if (new_data->count+1 >= new_data->allocated) { + Py_ssize_t to_allocate = (new_data->count+1)*2; + new_data = + (__Pyx_ModuleStateLookupData*)realloc( + new_data, + sizeof(__Pyx_ModuleStateLookupData) + + (to_allocate-1)*sizeof(__Pyx_InterpreterIdAndModule)); + if (!new_data) { + result = -1; + new_data = old_data; + PyErr_NoMemory(); + goto end; + } + new_data->allocated = to_allocate; + } + ++new_data->count; + int64_t last_id = interpreter_id; + PyObject *last_module = module; + for (Py_ssize_t i=insert_at; icount; ++i) { + int64_t current_id = new_data->table[i].id; + new_data->table[i].id = last_id; + last_id = current_id; + PyObject *current_module = new_data->table[i].module; + new_data->table[i].module = last_module; + last_module = current_module; + } + } + end: +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE + __pyx_atomic_pointer_exchange(&__Pyx_ModuleStateLookup_data, new_data); +#else + __Pyx_ModuleStateLookup_data = new_data; +#endif + __Pyx_ModuleStateLookup_Unlock(); + return result; +} +static int __Pyx_State_RemoveModule(CYTHON_UNUSED void* dummy) { + int64_t interpreter_id = PyInterpreterState_GetID(__Pyx_PyInterpreterState_Get()); + if (interpreter_id == -1) return -1; + __Pyx_ModuleStateLookup_Lock(); +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE + __Pyx_ModuleStateLookupData *data = (__Pyx_ModuleStateLookupData *) + __pyx_atomic_pointer_exchange(&__Pyx_ModuleStateLookup_data, 0); +#else + __Pyx_ModuleStateLookupData *data = __Pyx_ModuleStateLookup_data; +#endif + if (data->interpreter_id_as_index) { + if (interpreter_id < data->count) { + data->table[interpreter_id].module = NULL; + } + goto done; + } + { + __Pyx_ModuleStateLookup_wait_until_no_readers(); + __Pyx_InterpreterIdAndModule* lower_bound = __Pyx_State_FindModuleStateLookupTableLowerBound( + data->table, data->count, interpreter_id); + if (!lower_bound) goto done; + if (lower_bound->id != interpreter_id) goto done; + __Pyx_InterpreterIdAndModule *end = data->table+data->count; + for (;lower_boundid = (lower_bound+1)->id; + lower_bound->module = (lower_bound+1)->module; + } + } + --data->count; + if (data->count == 0) { + free(data); + data = NULL; + } + done: +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE + __pyx_atomic_pointer_exchange(&__Pyx_ModuleStateLookup_data, data); +#else + __Pyx_ModuleStateLookup_data = data; +#endif + __Pyx_ModuleStateLookup_Unlock(); + return 0; +} +#endif + +/* #### Code section: utility_code_pragmas_end ### */ +#ifdef _MSC_VER +#pragma warning( pop ) +#endif + + + +/* #### Code section: end ### */ +#endif /* Py_PYTHON_H */ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/framed/cyframed.pyx b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/framed/cyframed.pyx new file mode 100644 index 0000000000000000000000000000000000000000..16e525052893d4e7ccd5f2e2a0c8211a1590bdb7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/framed/cyframed.pyx @@ -0,0 +1,128 @@ +# cython: freethreading_compatible = True + +from libc.stdlib cimport malloc, free +from libc.string cimport memcpy +from libc.stdint cimport int32_t + +from thriftpy2.transport.cybase cimport ( + TCyBuffer, + CyTransportBase, + DEFAULT_BUFFER, + STACK_STRING_LEN +) + +from .. import TTransportException + + +cdef extern from "../../protocol/cybin/endian_port.h": + int32_t be32toh(int32_t n) + int32_t htobe32(int32_t n) + + +cdef class TCyFramedTransport(CyTransportBase): + cdef: + TCyBuffer rbuf, rframe_buf, wframe_buf + + def __init__(self, trans, int buf_size=DEFAULT_BUFFER): + self.trans = trans + self.rbuf = TCyBuffer(buf_size) + self.rframe_buf = TCyBuffer(buf_size) + self.wframe_buf = TCyBuffer(buf_size) + + cdef read_trans(self, int sz, char *out): + cdef int i = self.rbuf.read_trans(self.trans, sz, out) + if i == -1: + raise TTransportException(TTransportException.END_OF_FILE, + "End of file reading from transport") + elif i == -2: + raise MemoryError("grow buffer fail") + + cdef write_rframe_buffer(self, const char *data, int sz): + cdef int r = self.rframe_buf.write(sz, data) + if r == -1: + raise MemoryError("Write to buffer error") + + cdef c_read(self, int sz, char *out): + if sz <= 0: + return 0 + + while self.rframe_buf.data_size < sz: + self.read_frame() + + memcpy(out, self.rframe_buf.buf + self.rframe_buf.cur, sz) + self.rframe_buf.cur += sz + self.rframe_buf.data_size -= sz + + return sz + + cdef c_write(self, const char *data, int sz): + cdef int r = self.wframe_buf.write(sz, data) + if r == -1: + raise MemoryError("Write to buffer error") + + cdef read_frame(self): + cdef: + char frame_len[4] + char stack_frame[STACK_STRING_LEN] + char *dy_frame + int32_t frame_size + + self.read_trans(4, frame_len) + frame_size = be32toh((frame_len)[0]) + + if frame_size <= 0: + raise TTransportException("No frame.", TTransportException.UNKNOWN) + + if frame_size <= STACK_STRING_LEN: + self.read_trans(frame_size, stack_frame) + self.write_rframe_buffer(stack_frame, frame_size) + else: + dy_frame = malloc(frame_size) + try: + self.read_trans(frame_size, dy_frame) + self.write_rframe_buffer(dy_frame, frame_size) + finally: + free(dy_frame) + + cdef c_flush(self): + cdef: + bytes data + char *size_str + + if self.wframe_buf.data_size > 0: + data = self.wframe_buf.buf[:self.wframe_buf.data_size] + size = htobe32(self.wframe_buf.data_size) + size_str = (&size) + + self.trans.write(size_str[:4] + data) + self.trans.flush() + self.wframe_buf.clean() + + def read(self, int sz): + return self.get_string(sz) + + def write(self, bytes data): + cdef int sz = len(data) + self.c_write(data, sz) + + def flush(self): + self.c_flush() + + def is_open(self): + return self.trans.is_open() + + def open(self): + return self.trans.open() + + def close(self): + return self.trans.close() + + def clean(self): + self.rbuf.clean() + self.rframe_buf.clean() + self.wframe_buf.clean() + + +class TCyFramedTransportFactory(object): + def get_transport(self, trans): + return TCyFramedTransport(trans) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/memory/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/memory/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e97f595d130201c69e9d102af88ba0269f0402ce --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/memory/__init__.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- + +from __future__ import absolute_import + +from io import BytesIO + +from thriftpy2._compat import CYTHON +from ..base import TTransportBase + + +class TMemoryBuffer(TTransportBase): + """Wraps a BytesIO object as a TTransport.""" + + def __init__(self, value=None): + """value -- a value as the initial value in the BytesIO object. + + If value is set, the transport can be read first. + """ + self._buffer = BytesIO(value) if value is not None else BytesIO() + self._pos = 0 + + def is_open(self): + return not self._buffer.closed + + def open(self): + pass + + def close(self): + self._buffer.close() + + def read(self, sz): + return self._read(sz) + + def _read(self, sz): + orig_pos = self._buffer.tell() + self._buffer.seek(self._pos) + res = self._buffer.read(sz) + self._buffer.seek(orig_pos) + self._pos += len(res) + return res + + def write(self, buf): + self._buffer.write(buf) + + def flush(self): + pass + + def getvalue(self): + return self._buffer.getvalue() + + def setvalue(self, value): + self._buffer = BytesIO(value) + self._pos = 0 + + +if CYTHON: + from .cymemory import TCyMemoryBuffer # noqa diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/memory/cymemory.c b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/memory/cymemory.c new file mode 100644 index 0000000000000000000000000000000000000000..d89b5f9aef69da7c1b2b9a14c8c469cf05fe51b0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/memory/cymemory.c @@ -0,0 +1,12282 @@ +/* Generated by Cython 3.2.4 */ + +/* BEGIN: Cython Metadata +{ + "distutils": { + "depends": [], + "name": "thriftpy2.transport.memory.cymemory", + "sources": [ + "thriftpy2/transport/memory/cymemory.pyx" + ] + }, + "module_name": "thriftpy2.transport.memory.cymemory" +} +END: Cython Metadata */ + +#ifndef PY_SSIZE_T_CLEAN +#define PY_SSIZE_T_CLEAN +#endif /* PY_SSIZE_T_CLEAN */ +/* InitLimitedAPI */ +#if defined(Py_LIMITED_API) + #if !defined(CYTHON_LIMITED_API) + #define CYTHON_LIMITED_API 1 + #endif +#elif defined(CYTHON_LIMITED_API) + #ifdef _MSC_VER + #pragma message ("Limited API usage is enabled with 'CYTHON_LIMITED_API' but 'Py_LIMITED_API' does not define a Python target version. Consider setting 'Py_LIMITED_API' instead.") + #else + #warning Limited API usage is enabled with 'CYTHON_LIMITED_API' but 'Py_LIMITED_API' does not define a Python target version. Consider setting 'Py_LIMITED_API' instead. + #endif +#endif + +#include "Python.h" +#ifndef Py_PYTHON_H + #error Python headers needed to compile C extensions, please install development version of Python. +#elif PY_VERSION_HEX < 0x03080000 + #error Cython requires Python 3.8+. +#else +#define __PYX_ABI_VERSION "3_2_4" +#define CYTHON_HEX_VERSION 0x030204F0 +#define CYTHON_FUTURE_DIVISION 1 +/* CModulePreamble */ +#include +#ifndef offsetof + #define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) +#endif +#if !defined(_WIN32) && !defined(WIN32) && !defined(MS_WINDOWS) + #ifndef __stdcall + #define __stdcall + #endif + #ifndef __cdecl + #define __cdecl + #endif + #ifndef __fastcall + #define __fastcall + #endif +#endif +#ifndef DL_IMPORT + #define DL_IMPORT(t) t +#endif +#ifndef DL_EXPORT + #define DL_EXPORT(t) t +#endif +#define __PYX_COMMA , +#ifndef PY_LONG_LONG + #define PY_LONG_LONG LONG_LONG +#endif +#ifndef Py_HUGE_VAL + #define Py_HUGE_VAL HUGE_VAL +#endif +#define __PYX_LIMITED_VERSION_HEX PY_VERSION_HEX +#if defined(GRAALVM_PYTHON) + /* For very preliminary testing purposes. Most variables are set the same as PyPy. + The existence of this section does not imply that anything works or is even tested */ + #define CYTHON_COMPILING_IN_PYPY 0 + #define CYTHON_COMPILING_IN_CPYTHON 0 + #define CYTHON_COMPILING_IN_LIMITED_API 0 + #define CYTHON_COMPILING_IN_GRAAL 1 + #define CYTHON_COMPILING_IN_CPYTHON_FREETHREADING 0 + #undef CYTHON_USE_TYPE_SLOTS + #define CYTHON_USE_TYPE_SLOTS 0 + #undef CYTHON_USE_TYPE_SPECS + #define CYTHON_USE_TYPE_SPECS 0 + #undef CYTHON_USE_PYTYPE_LOOKUP + #define CYTHON_USE_PYTYPE_LOOKUP 0 + #undef CYTHON_USE_PYLIST_INTERNALS + #define CYTHON_USE_PYLIST_INTERNALS 0 + #undef CYTHON_USE_UNICODE_INTERNALS + #define CYTHON_USE_UNICODE_INTERNALS 0 + #undef CYTHON_USE_UNICODE_WRITER + #define CYTHON_USE_UNICODE_WRITER 0 + #undef CYTHON_USE_PYLONG_INTERNALS + #define CYTHON_USE_PYLONG_INTERNALS 0 + #undef CYTHON_AVOID_BORROWED_REFS + #define CYTHON_AVOID_BORROWED_REFS 1 + #undef CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + #define CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS 0 + #undef CYTHON_ASSUME_SAFE_MACROS + #define CYTHON_ASSUME_SAFE_MACROS 0 + #undef CYTHON_ASSUME_SAFE_SIZE + #define CYTHON_ASSUME_SAFE_SIZE 0 + #undef CYTHON_UNPACK_METHODS + #define CYTHON_UNPACK_METHODS 0 + #undef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 0 + #undef CYTHON_FAST_GIL + #define CYTHON_FAST_GIL 0 + #undef CYTHON_METH_FASTCALL + #define CYTHON_METH_FASTCALL 0 + #undef CYTHON_FAST_PYCALL + #define CYTHON_FAST_PYCALL 0 + #ifndef CYTHON_PEP487_INIT_SUBCLASS + #define CYTHON_PEP487_INIT_SUBCLASS 1 + #endif + #undef CYTHON_PEP489_MULTI_PHASE_INIT + #define CYTHON_PEP489_MULTI_PHASE_INIT 1 + #undef CYTHON_USE_MODULE_STATE + #define CYTHON_USE_MODULE_STATE 0 + #undef CYTHON_USE_SYS_MONITORING + #define CYTHON_USE_SYS_MONITORING 0 + #undef CYTHON_USE_TP_FINALIZE + #define CYTHON_USE_TP_FINALIZE 0 + #undef CYTHON_USE_AM_SEND + #define CYTHON_USE_AM_SEND 0 + #undef CYTHON_USE_DICT_VERSIONS + #define CYTHON_USE_DICT_VERSIONS 0 + #undef CYTHON_USE_EXC_INFO_STACK + #define CYTHON_USE_EXC_INFO_STACK 1 + #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC + #define CYTHON_UPDATE_DESCRIPTOR_DOC 0 + #endif + #undef CYTHON_USE_FREELISTS + #define CYTHON_USE_FREELISTS 0 + #undef CYTHON_IMMORTAL_CONSTANTS + #define CYTHON_IMMORTAL_CONSTANTS 0 +#elif defined(PYPY_VERSION) + #define CYTHON_COMPILING_IN_PYPY 1 + #define CYTHON_COMPILING_IN_CPYTHON 0 + #define CYTHON_COMPILING_IN_LIMITED_API 0 + #define CYTHON_COMPILING_IN_GRAAL 0 + #define CYTHON_COMPILING_IN_CPYTHON_FREETHREADING 0 + #undef CYTHON_USE_TYPE_SLOTS + #define CYTHON_USE_TYPE_SLOTS 1 + #ifndef CYTHON_USE_TYPE_SPECS + #define CYTHON_USE_TYPE_SPECS 0 + #endif + #undef CYTHON_USE_PYTYPE_LOOKUP + #define CYTHON_USE_PYTYPE_LOOKUP 0 + #undef CYTHON_USE_PYLIST_INTERNALS + #define CYTHON_USE_PYLIST_INTERNALS 0 + #undef CYTHON_USE_UNICODE_INTERNALS + #define CYTHON_USE_UNICODE_INTERNALS 0 + #undef CYTHON_USE_UNICODE_WRITER + #define CYTHON_USE_UNICODE_WRITER 0 + #undef CYTHON_USE_PYLONG_INTERNALS + #define CYTHON_USE_PYLONG_INTERNALS 0 + #undef CYTHON_AVOID_BORROWED_REFS + #define CYTHON_AVOID_BORROWED_REFS 1 + #undef CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + #define CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS 1 + #undef CYTHON_ASSUME_SAFE_MACROS + #define CYTHON_ASSUME_SAFE_MACROS 0 + #ifndef CYTHON_ASSUME_SAFE_SIZE + #define CYTHON_ASSUME_SAFE_SIZE 1 + #endif + #undef CYTHON_UNPACK_METHODS + #define CYTHON_UNPACK_METHODS 0 + #undef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 0 + #undef CYTHON_FAST_GIL + #define CYTHON_FAST_GIL 0 + #undef CYTHON_METH_FASTCALL + #define CYTHON_METH_FASTCALL 0 + #undef CYTHON_FAST_PYCALL + #define CYTHON_FAST_PYCALL 0 + #ifndef CYTHON_PEP487_INIT_SUBCLASS + #define CYTHON_PEP487_INIT_SUBCLASS 1 + #endif + #if PY_VERSION_HEX < 0x03090000 + #undef CYTHON_PEP489_MULTI_PHASE_INIT + #define CYTHON_PEP489_MULTI_PHASE_INIT 0 + #elif !defined(CYTHON_PEP489_MULTI_PHASE_INIT) + #define CYTHON_PEP489_MULTI_PHASE_INIT 1 + #endif + #undef CYTHON_USE_MODULE_STATE + #define CYTHON_USE_MODULE_STATE 0 + #undef CYTHON_USE_SYS_MONITORING + #define CYTHON_USE_SYS_MONITORING 0 + #ifndef CYTHON_USE_TP_FINALIZE + #define CYTHON_USE_TP_FINALIZE (PYPY_VERSION_NUM >= 0x07030C00) + #endif + #undef CYTHON_USE_AM_SEND + #define CYTHON_USE_AM_SEND 0 + #undef CYTHON_USE_DICT_VERSIONS + #define CYTHON_USE_DICT_VERSIONS 0 + #undef CYTHON_USE_EXC_INFO_STACK + #define CYTHON_USE_EXC_INFO_STACK 0 + #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC + #define CYTHON_UPDATE_DESCRIPTOR_DOC (PYPY_VERSION_NUM >= 0x07031100) + #endif + #undef CYTHON_USE_FREELISTS + #define CYTHON_USE_FREELISTS 0 + #undef CYTHON_IMMORTAL_CONSTANTS + #define CYTHON_IMMORTAL_CONSTANTS 0 +#elif defined(CYTHON_LIMITED_API) + #ifdef Py_LIMITED_API + #undef __PYX_LIMITED_VERSION_HEX + #define __PYX_LIMITED_VERSION_HEX Py_LIMITED_API + #endif + #define CYTHON_COMPILING_IN_PYPY 0 + #define CYTHON_COMPILING_IN_CPYTHON 0 + #define CYTHON_COMPILING_IN_LIMITED_API 1 + #define CYTHON_COMPILING_IN_GRAAL 0 + #define CYTHON_COMPILING_IN_CPYTHON_FREETHREADING 0 + #undef CYTHON_USE_TYPE_SLOTS + #define CYTHON_USE_TYPE_SLOTS 0 + #undef CYTHON_USE_TYPE_SPECS + #define CYTHON_USE_TYPE_SPECS 1 + #undef CYTHON_USE_PYTYPE_LOOKUP + #define CYTHON_USE_PYTYPE_LOOKUP 0 + #undef CYTHON_USE_PYLIST_INTERNALS + #define CYTHON_USE_PYLIST_INTERNALS 0 + #undef CYTHON_USE_UNICODE_INTERNALS + #define CYTHON_USE_UNICODE_INTERNALS 0 + #ifndef CYTHON_USE_UNICODE_WRITER + #define CYTHON_USE_UNICODE_WRITER 0 + #endif + #undef CYTHON_USE_PYLONG_INTERNALS + #define CYTHON_USE_PYLONG_INTERNALS 0 + #ifndef CYTHON_AVOID_BORROWED_REFS + #define CYTHON_AVOID_BORROWED_REFS 0 + #endif + #ifndef CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + #define CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS 0 + #endif + #undef CYTHON_ASSUME_SAFE_MACROS + #define CYTHON_ASSUME_SAFE_MACROS 0 + #undef CYTHON_ASSUME_SAFE_SIZE + #define CYTHON_ASSUME_SAFE_SIZE 0 + #undef CYTHON_UNPACK_METHODS + #define CYTHON_UNPACK_METHODS 0 + #undef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 0 + #undef CYTHON_FAST_GIL + #define CYTHON_FAST_GIL 0 + #undef CYTHON_METH_FASTCALL + #define CYTHON_METH_FASTCALL (__PYX_LIMITED_VERSION_HEX >= 0x030C0000) + #undef CYTHON_FAST_PYCALL + #define CYTHON_FAST_PYCALL 0 + #ifndef CYTHON_PEP487_INIT_SUBCLASS + #define CYTHON_PEP487_INIT_SUBCLASS 1 + #endif + #ifndef CYTHON_PEP489_MULTI_PHASE_INIT + #define CYTHON_PEP489_MULTI_PHASE_INIT 1 + #endif + #ifndef CYTHON_USE_MODULE_STATE + #define CYTHON_USE_MODULE_STATE 0 + #endif + #undef CYTHON_USE_SYS_MONITORING + #define CYTHON_USE_SYS_MONITORING 0 + #ifndef CYTHON_USE_TP_FINALIZE + #define CYTHON_USE_TP_FINALIZE 0 + #endif + #ifndef CYTHON_USE_AM_SEND + #define CYTHON_USE_AM_SEND (__PYX_LIMITED_VERSION_HEX >= 0x030A0000) + #endif + #undef CYTHON_USE_DICT_VERSIONS + #define CYTHON_USE_DICT_VERSIONS 0 + #undef CYTHON_USE_EXC_INFO_STACK + #define CYTHON_USE_EXC_INFO_STACK 0 + #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC + #define CYTHON_UPDATE_DESCRIPTOR_DOC 0 + #endif + #ifndef CYTHON_USE_FREELISTS + #define CYTHON_USE_FREELISTS 1 + #endif + #undef CYTHON_IMMORTAL_CONSTANTS + #define CYTHON_IMMORTAL_CONSTANTS 0 +#else + #define CYTHON_COMPILING_IN_PYPY 0 + #define CYTHON_COMPILING_IN_CPYTHON 1 + #define CYTHON_COMPILING_IN_LIMITED_API 0 + #define CYTHON_COMPILING_IN_GRAAL 0 + #ifdef Py_GIL_DISABLED + #define CYTHON_COMPILING_IN_CPYTHON_FREETHREADING 1 + #else + #define CYTHON_COMPILING_IN_CPYTHON_FREETHREADING 0 + #endif + #if PY_VERSION_HEX < 0x030A0000 + #undef CYTHON_USE_TYPE_SLOTS + #define CYTHON_USE_TYPE_SLOTS 1 + #elif !defined(CYTHON_USE_TYPE_SLOTS) + #define CYTHON_USE_TYPE_SLOTS 1 + #endif + #ifndef CYTHON_USE_TYPE_SPECS + #define CYTHON_USE_TYPE_SPECS 0 + #endif + #ifndef CYTHON_USE_PYTYPE_LOOKUP + #define CYTHON_USE_PYTYPE_LOOKUP 1 + #endif + #ifndef CYTHON_USE_PYLONG_INTERNALS + #define CYTHON_USE_PYLONG_INTERNALS 1 + #endif + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + #undef CYTHON_USE_PYLIST_INTERNALS + #define CYTHON_USE_PYLIST_INTERNALS 0 + #elif !defined(CYTHON_USE_PYLIST_INTERNALS) + #define CYTHON_USE_PYLIST_INTERNALS 1 + #endif + #ifndef CYTHON_USE_UNICODE_INTERNALS + #define CYTHON_USE_UNICODE_INTERNALS 1 + #endif + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING || PY_VERSION_HEX >= 0x030B00A2 + #undef CYTHON_USE_UNICODE_WRITER + #define CYTHON_USE_UNICODE_WRITER 0 + #elif !defined(CYTHON_USE_UNICODE_WRITER) + #define CYTHON_USE_UNICODE_WRITER 1 + #endif + #ifndef CYTHON_AVOID_BORROWED_REFS + #define CYTHON_AVOID_BORROWED_REFS 0 + #endif + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + #undef CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + #define CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS 1 + #elif !defined(CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS) + #define CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS 0 + #endif + #ifndef CYTHON_ASSUME_SAFE_MACROS + #define CYTHON_ASSUME_SAFE_MACROS 1 + #endif + #ifndef CYTHON_ASSUME_SAFE_SIZE + #define CYTHON_ASSUME_SAFE_SIZE 1 + #endif + #ifndef CYTHON_UNPACK_METHODS + #define CYTHON_UNPACK_METHODS 1 + #endif + #ifndef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 1 + #endif + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + #undef CYTHON_FAST_GIL + #define CYTHON_FAST_GIL 0 + #elif !defined(CYTHON_FAST_GIL) + #define CYTHON_FAST_GIL (PY_VERSION_HEX < 0x030C00A6) + #endif + #ifndef CYTHON_METH_FASTCALL + #define CYTHON_METH_FASTCALL 1 + #endif + #ifndef CYTHON_FAST_PYCALL + #define CYTHON_FAST_PYCALL 1 + #endif + #ifndef CYTHON_PEP487_INIT_SUBCLASS + #define CYTHON_PEP487_INIT_SUBCLASS 1 + #endif + #ifndef CYTHON_PEP489_MULTI_PHASE_INIT + #define CYTHON_PEP489_MULTI_PHASE_INIT 1 + #endif + #ifndef CYTHON_USE_MODULE_STATE + #define CYTHON_USE_MODULE_STATE 0 + #endif + #ifndef CYTHON_USE_SYS_MONITORING + #define CYTHON_USE_SYS_MONITORING (PY_VERSION_HEX >= 0x030d00B1) + #endif + #ifndef CYTHON_USE_TP_FINALIZE + #define CYTHON_USE_TP_FINALIZE 1 + #endif + #ifndef CYTHON_USE_AM_SEND + #define CYTHON_USE_AM_SEND 1 + #endif + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + #undef CYTHON_USE_DICT_VERSIONS + #define CYTHON_USE_DICT_VERSIONS 0 + #elif !defined(CYTHON_USE_DICT_VERSIONS) + #define CYTHON_USE_DICT_VERSIONS (PY_VERSION_HEX < 0x030C00A5 && !CYTHON_USE_MODULE_STATE) + #endif + #ifndef CYTHON_USE_EXC_INFO_STACK + #define CYTHON_USE_EXC_INFO_STACK 1 + #endif + #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC + #define CYTHON_UPDATE_DESCRIPTOR_DOC 1 + #endif + #ifndef CYTHON_USE_FREELISTS + #define CYTHON_USE_FREELISTS (!CYTHON_COMPILING_IN_CPYTHON_FREETHREADING) + #endif + #if defined(CYTHON_IMMORTAL_CONSTANTS) && PY_VERSION_HEX < 0x030C0000 + #undef CYTHON_IMMORTAL_CONSTANTS + #define CYTHON_IMMORTAL_CONSTANTS 0 // definitely won't work + #elif !defined(CYTHON_IMMORTAL_CONSTANTS) + #define CYTHON_IMMORTAL_CONSTANTS (PY_VERSION_HEX >= 0x030C0000 && !CYTHON_USE_MODULE_STATE && CYTHON_COMPILING_IN_CPYTHON_FREETHREADING) + #endif +#endif +#ifndef CYTHON_COMPRESS_STRINGS + #define CYTHON_COMPRESS_STRINGS 1 +#endif +#ifndef CYTHON_FAST_PYCCALL +#define CYTHON_FAST_PYCCALL CYTHON_FAST_PYCALL +#endif +#ifndef CYTHON_VECTORCALL +#if CYTHON_COMPILING_IN_LIMITED_API +#define CYTHON_VECTORCALL (__PYX_LIMITED_VERSION_HEX >= 0x030C0000) +#else +#define CYTHON_VECTORCALL (CYTHON_FAST_PYCCALL) +#endif +#endif +#if CYTHON_USE_PYLONG_INTERNALS + #undef SHIFT + #undef BASE + #undef MASK + #ifdef SIZEOF_VOID_P + enum { __pyx_check_sizeof_voidp = 1 / (int)(SIZEOF_VOID_P == sizeof(void*)) }; + #endif +#endif +#ifndef __has_attribute + #define __has_attribute(x) 0 +#endif +#ifndef __has_cpp_attribute + #define __has_cpp_attribute(x) 0 +#endif +#ifndef CYTHON_RESTRICT + #if defined(__GNUC__) + #define CYTHON_RESTRICT __restrict__ + #elif defined(_MSC_VER) && _MSC_VER >= 1400 + #define CYTHON_RESTRICT __restrict + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_RESTRICT restrict + #else + #define CYTHON_RESTRICT + #endif +#endif +#ifndef CYTHON_UNUSED + #if defined(__cplusplus) + /* for clang __has_cpp_attribute(maybe_unused) is true even before C++17 + * but leads to warnings with -pedantic, since it is a C++17 feature */ + #if ((defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) || __cplusplus >= 201703L) + #if __has_cpp_attribute(maybe_unused) + #define CYTHON_UNUSED [[maybe_unused]] + #endif + #endif + #endif +#endif +#ifndef CYTHON_UNUSED +# if defined(__GNUC__) +# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) +# define CYTHON_UNUSED __attribute__ ((__unused__)) +# else +# define CYTHON_UNUSED +# endif +# elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) +# define CYTHON_UNUSED __attribute__ ((__unused__)) +# else +# define CYTHON_UNUSED +# endif +#endif +#ifndef CYTHON_UNUSED_VAR +# if defined(__cplusplus) + template void CYTHON_UNUSED_VAR( const T& ) { } +# else +# define CYTHON_UNUSED_VAR(x) (void)(x) +# endif +#endif +#ifndef CYTHON_MAYBE_UNUSED_VAR + #define CYTHON_MAYBE_UNUSED_VAR(x) CYTHON_UNUSED_VAR(x) +#endif +#ifndef CYTHON_NCP_UNUSED +# if CYTHON_COMPILING_IN_CPYTHON && !CYTHON_COMPILING_IN_CPYTHON_FREETHREADING +# define CYTHON_NCP_UNUSED +# else +# define CYTHON_NCP_UNUSED CYTHON_UNUSED +# endif +#endif +#ifndef CYTHON_USE_CPP_STD_MOVE + #if defined(__cplusplus) && (\ + __cplusplus >= 201103L || (defined(_MSC_VER) && _MSC_VER >= 1600)) + #define CYTHON_USE_CPP_STD_MOVE 1 + #else + #define CYTHON_USE_CPP_STD_MOVE 0 + #endif +#endif +#define __Pyx_void_to_None(void_result) ((void)(void_result), Py_INCREF(Py_None), Py_None) +#include +typedef uintptr_t __pyx_uintptr_t; +#ifndef CYTHON_FALLTHROUGH + #if defined(__cplusplus) + /* for clang __has_cpp_attribute(fallthrough) is true even before C++17 + * but leads to warnings with -pedantic, since it is a C++17 feature */ + #if ((defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) || __cplusplus >= 201703L) + #if __has_cpp_attribute(fallthrough) + #define CYTHON_FALLTHROUGH [[fallthrough]] + #endif + #endif + #ifndef CYTHON_FALLTHROUGH + #if __has_cpp_attribute(clang::fallthrough) + #define CYTHON_FALLTHROUGH [[clang::fallthrough]] + #elif __has_cpp_attribute(gnu::fallthrough) + #define CYTHON_FALLTHROUGH [[gnu::fallthrough]] + #endif + #endif + #endif + #ifndef CYTHON_FALLTHROUGH + #if __has_attribute(fallthrough) + #define CYTHON_FALLTHROUGH __attribute__((fallthrough)) + #else + #define CYTHON_FALLTHROUGH + #endif + #endif + #if defined(__clang__) && defined(__apple_build_version__) + #if __apple_build_version__ < 7000000 + #undef CYTHON_FALLTHROUGH + #define CYTHON_FALLTHROUGH + #endif + #endif +#endif +#ifndef Py_UNREACHABLE + #define Py_UNREACHABLE() assert(0); abort() +#endif +#ifdef __cplusplus + template + struct __PYX_IS_UNSIGNED_IMPL {static const bool value = T(0) < T(-1);}; + #define __PYX_IS_UNSIGNED(type) (__PYX_IS_UNSIGNED_IMPL::value) +#else + #define __PYX_IS_UNSIGNED(type) (((type)-1) > 0) +#endif +#if CYTHON_COMPILING_IN_PYPY == 1 + #define __PYX_NEED_TP_PRINT_SLOT (PY_VERSION_HEX < 0x030A0000) +#else + #define __PYX_NEED_TP_PRINT_SLOT (PY_VERSION_HEX < 0x03090000) +#endif +#define __PYX_REINTERPRET_FUNCION(func_pointer, other_pointer) ((func_pointer)(void(*)(void))(other_pointer)) + +/* CInitCode */ +#ifndef CYTHON_INLINE + #if defined(__clang__) + #define CYTHON_INLINE __inline__ __attribute__ ((__unused__)) + #elif defined(__GNUC__) + #define CYTHON_INLINE __inline__ + #elif defined(_MSC_VER) + #define CYTHON_INLINE __inline + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_INLINE inline + #else + #define CYTHON_INLINE + #endif +#endif + +/* PythonCompatibility */ +#define __PYX_BUILD_PY_SSIZE_T "n" +#define CYTHON_FORMAT_SSIZE_T "z" +#define __Pyx_BUILTIN_MODULE_NAME "builtins" +#define __Pyx_DefaultClassType PyType_Type +#if CYTHON_COMPILING_IN_LIMITED_API + #ifndef CO_OPTIMIZED + static int CO_OPTIMIZED; + #endif + #ifndef CO_NEWLOCALS + static int CO_NEWLOCALS; + #endif + #ifndef CO_VARARGS + static int CO_VARARGS; + #endif + #ifndef CO_VARKEYWORDS + static int CO_VARKEYWORDS; + #endif + #ifndef CO_ASYNC_GENERATOR + static int CO_ASYNC_GENERATOR; + #endif + #ifndef CO_GENERATOR + static int CO_GENERATOR; + #endif + #ifndef CO_COROUTINE + static int CO_COROUTINE; + #endif +#else + #ifndef CO_COROUTINE + #define CO_COROUTINE 0x80 + #endif + #ifndef CO_ASYNC_GENERATOR + #define CO_ASYNC_GENERATOR 0x200 + #endif +#endif +static int __Pyx_init_co_variables(void); +#if PY_VERSION_HEX >= 0x030900A4 || defined(Py_IS_TYPE) + #define __Pyx_IS_TYPE(ob, type) Py_IS_TYPE(ob, type) +#else + #define __Pyx_IS_TYPE(ob, type) (((const PyObject*)ob)->ob_type == (type)) +#endif +#if PY_VERSION_HEX >= 0x030A00B1 || defined(Py_Is) + #define __Pyx_Py_Is(x, y) Py_Is(x, y) +#else + #define __Pyx_Py_Is(x, y) ((x) == (y)) +#endif +#if PY_VERSION_HEX >= 0x030A00B1 || defined(Py_IsNone) + #define __Pyx_Py_IsNone(ob) Py_IsNone(ob) +#else + #define __Pyx_Py_IsNone(ob) __Pyx_Py_Is((ob), Py_None) +#endif +#if PY_VERSION_HEX >= 0x030A00B1 || defined(Py_IsTrue) + #define __Pyx_Py_IsTrue(ob) Py_IsTrue(ob) +#else + #define __Pyx_Py_IsTrue(ob) __Pyx_Py_Is((ob), Py_True) +#endif +#if PY_VERSION_HEX >= 0x030A00B1 || defined(Py_IsFalse) + #define __Pyx_Py_IsFalse(ob) Py_IsFalse(ob) +#else + #define __Pyx_Py_IsFalse(ob) __Pyx_Py_Is((ob), Py_False) +#endif +#define __Pyx_NoneAsNull(obj) (__Pyx_Py_IsNone(obj) ? NULL : (obj)) +#if PY_VERSION_HEX >= 0x030900F0 && !CYTHON_COMPILING_IN_PYPY + #define __Pyx_PyObject_GC_IsFinalized(o) PyObject_GC_IsFinalized(o) +#else + #define __Pyx_PyObject_GC_IsFinalized(o) _PyGC_FINALIZED(o) +#endif +#ifndef Py_TPFLAGS_CHECKTYPES + #define Py_TPFLAGS_CHECKTYPES 0 +#endif +#ifndef Py_TPFLAGS_HAVE_INDEX + #define Py_TPFLAGS_HAVE_INDEX 0 +#endif +#ifndef Py_TPFLAGS_HAVE_NEWBUFFER + #define Py_TPFLAGS_HAVE_NEWBUFFER 0 +#endif +#ifndef Py_TPFLAGS_HAVE_FINALIZE + #define Py_TPFLAGS_HAVE_FINALIZE 0 +#endif +#ifndef Py_TPFLAGS_SEQUENCE + #define Py_TPFLAGS_SEQUENCE 0 +#endif +#ifndef Py_TPFLAGS_MAPPING + #define Py_TPFLAGS_MAPPING 0 +#endif +#ifndef Py_TPFLAGS_IMMUTABLETYPE + #define Py_TPFLAGS_IMMUTABLETYPE (1UL << 8) +#endif +#ifndef Py_TPFLAGS_DISALLOW_INSTANTIATION + #define Py_TPFLAGS_DISALLOW_INSTANTIATION (1UL << 7) +#endif +#ifndef METH_STACKLESS + #define METH_STACKLESS 0 +#endif +#ifndef METH_FASTCALL + #ifndef METH_FASTCALL + #define METH_FASTCALL 0x80 + #endif + typedef PyObject *(*__Pyx_PyCFunctionFast) (PyObject *self, PyObject *const *args, Py_ssize_t nargs); + typedef PyObject *(*__Pyx_PyCFunctionFastWithKeywords) (PyObject *self, PyObject *const *args, + Py_ssize_t nargs, PyObject *kwnames); +#else + #if PY_VERSION_HEX >= 0x030d00A4 + # define __Pyx_PyCFunctionFast PyCFunctionFast + # define __Pyx_PyCFunctionFastWithKeywords PyCFunctionFastWithKeywords + #else + # define __Pyx_PyCFunctionFast _PyCFunctionFast + # define __Pyx_PyCFunctionFastWithKeywords _PyCFunctionFastWithKeywords + #endif +#endif +#if CYTHON_METH_FASTCALL + #define __Pyx_METH_FASTCALL METH_FASTCALL + #define __Pyx_PyCFunction_FastCall __Pyx_PyCFunctionFast + #define __Pyx_PyCFunction_FastCallWithKeywords __Pyx_PyCFunctionFastWithKeywords +#else + #define __Pyx_METH_FASTCALL METH_VARARGS + #define __Pyx_PyCFunction_FastCall PyCFunction + #define __Pyx_PyCFunction_FastCallWithKeywords PyCFunctionWithKeywords +#endif +#if CYTHON_VECTORCALL + #define __pyx_vectorcallfunc vectorcallfunc + #define __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET PY_VECTORCALL_ARGUMENTS_OFFSET + #define __Pyx_PyVectorcall_NARGS(n) PyVectorcall_NARGS((size_t)(n)) +#else + #define __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET 0 + #define __Pyx_PyVectorcall_NARGS(n) ((Py_ssize_t)(n)) +#endif +#if PY_VERSION_HEX >= 0x030900B1 +#define __Pyx_PyCFunction_CheckExact(func) PyCFunction_CheckExact(func) +#else +#define __Pyx_PyCFunction_CheckExact(func) PyCFunction_Check(func) +#endif +#define __Pyx_CyOrPyCFunction_Check(func) PyCFunction_Check(func) +#if CYTHON_COMPILING_IN_CPYTHON +#define __Pyx_CyOrPyCFunction_GET_FUNCTION(func) (((PyCFunctionObject*)(func))->m_ml->ml_meth) +#elif !CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_CyOrPyCFunction_GET_FUNCTION(func) PyCFunction_GET_FUNCTION(func) +#endif +#if CYTHON_COMPILING_IN_CPYTHON +#define __Pyx_CyOrPyCFunction_GET_FLAGS(func) (((PyCFunctionObject*)(func))->m_ml->ml_flags) +static CYTHON_INLINE PyObject* __Pyx_CyOrPyCFunction_GET_SELF(PyObject *func) { + return (__Pyx_CyOrPyCFunction_GET_FLAGS(func) & METH_STATIC) ? NULL : ((PyCFunctionObject*)func)->m_self; +} +#endif +static CYTHON_INLINE int __Pyx__IsSameCFunction(PyObject *func, void (*cfunc)(void)) { +#if CYTHON_COMPILING_IN_LIMITED_API + return PyCFunction_Check(func) && PyCFunction_GetFunction(func) == (PyCFunction) cfunc; +#else + return PyCFunction_Check(func) && PyCFunction_GET_FUNCTION(func) == (PyCFunction) cfunc; +#endif +} +#define __Pyx_IsSameCFunction(func, cfunc) __Pyx__IsSameCFunction(func, cfunc) +#if PY_VERSION_HEX < 0x03090000 || (CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000) + #define __Pyx_PyType_FromModuleAndSpec(m, s, b) ((void)m, PyType_FromSpecWithBases(s, b)) + typedef PyObject *(*__Pyx_PyCMethod)(PyObject *, PyTypeObject *, PyObject *const *, size_t, PyObject *); +#else + #define __Pyx_PyType_FromModuleAndSpec(m, s, b) PyType_FromModuleAndSpec(m, s, b) + #define __Pyx_PyCMethod PyCMethod +#endif +#ifndef METH_METHOD + #define METH_METHOD 0x200 +#endif +#if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Malloc) + #define PyObject_Malloc(s) PyMem_Malloc(s) + #define PyObject_Free(p) PyMem_Free(p) + #define PyObject_Realloc(p) PyMem_Realloc(p) +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + #define __Pyx_PyFrame_SetLineNumber(frame, lineno) +#elif CYTHON_COMPILING_IN_GRAAL && defined(GRAALPY_VERSION_NUM) && GRAALPY_VERSION_NUM > 0x19000000 + #define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0) + #define __Pyx_PyFrame_SetLineNumber(frame, lineno) GraalPyFrame_SetLineNumber((frame), (lineno)) +#elif CYTHON_COMPILING_IN_GRAAL + #define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0) + #define __Pyx_PyFrame_SetLineNumber(frame, lineno) _PyFrame_SetLineNumber((frame), (lineno)) +#else + #define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0) + #define __Pyx_PyFrame_SetLineNumber(frame, lineno) (frame)->f_lineno = (lineno) +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + #define __Pyx_PyThreadState_Current PyThreadState_Get() +#elif !CYTHON_FAST_THREAD_STATE + #define __Pyx_PyThreadState_Current PyThreadState_GET() +#elif PY_VERSION_HEX >= 0x030d00A1 + #define __Pyx_PyThreadState_Current PyThreadState_GetUnchecked() +#else + #define __Pyx_PyThreadState_Current _PyThreadState_UncheckedGet() +#endif +#if CYTHON_USE_MODULE_STATE +static CYTHON_INLINE void *__Pyx__PyModule_GetState(PyObject *op) +{ + void *result; + result = PyModule_GetState(op); + if (!result) + Py_FatalError("Couldn't find the module state"); + return result; +} +#define __Pyx_PyModule_GetState(o) (__pyx_mstatetype *)__Pyx__PyModule_GetState(o) +#else +#define __Pyx_PyModule_GetState(op) ((void)op,__pyx_mstate_global) +#endif +#define __Pyx_PyObject_GetSlot(obj, name, func_ctype) __Pyx_PyType_GetSlot(Py_TYPE((PyObject *) obj), name, func_ctype) +#define __Pyx_PyObject_TryGetSlot(obj, name, func_ctype) __Pyx_PyType_TryGetSlot(Py_TYPE(obj), name, func_ctype) +#define __Pyx_PyObject_GetSubSlot(obj, sub, name, func_ctype) __Pyx_PyType_GetSubSlot(Py_TYPE(obj), sub, name, func_ctype) +#define __Pyx_PyObject_TryGetSubSlot(obj, sub, name, func_ctype) __Pyx_PyType_TryGetSubSlot(Py_TYPE(obj), sub, name, func_ctype) +#if CYTHON_USE_TYPE_SLOTS + #define __Pyx_PyType_GetSlot(type, name, func_ctype) ((type)->name) + #define __Pyx_PyType_TryGetSlot(type, name, func_ctype) __Pyx_PyType_GetSlot(type, name, func_ctype) + #define __Pyx_PyType_GetSubSlot(type, sub, name, func_ctype) (((type)->sub) ? ((type)->sub->name) : NULL) + #define __Pyx_PyType_TryGetSubSlot(type, sub, name, func_ctype) __Pyx_PyType_GetSubSlot(type, sub, name, func_ctype) +#else + #define __Pyx_PyType_GetSlot(type, name, func_ctype) ((func_ctype) PyType_GetSlot((type), Py_##name)) + #define __Pyx_PyType_TryGetSlot(type, name, func_ctype)\ + ((__PYX_LIMITED_VERSION_HEX >= 0x030A0000 ||\ + (PyType_GetFlags(type) & Py_TPFLAGS_HEAPTYPE) || __Pyx_get_runtime_version() >= 0x030A0000) ?\ + __Pyx_PyType_GetSlot(type, name, func_ctype) : NULL) + #define __Pyx_PyType_GetSubSlot(obj, sub, name, func_ctype) __Pyx_PyType_GetSlot(obj, name, func_ctype) + #define __Pyx_PyType_TryGetSubSlot(obj, sub, name, func_ctype) __Pyx_PyType_TryGetSlot(obj, name, func_ctype) +#endif +#if CYTHON_COMPILING_IN_CPYTHON || defined(_PyDict_NewPresized) +#define __Pyx_PyDict_NewPresized(n) ((n <= 8) ? PyDict_New() : _PyDict_NewPresized(n)) +#else +#define __Pyx_PyDict_NewPresized(n) PyDict_New() +#endif +#define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) +#define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) +#if CYTHON_COMPILING_IN_CPYTHON && CYTHON_USE_UNICODE_INTERNALS +#define __Pyx_PyDict_GetItemStrWithError(dict, name) _PyDict_GetItem_KnownHash(dict, name, ((PyASCIIObject *) name)->hash) +static CYTHON_INLINE PyObject * __Pyx_PyDict_GetItemStr(PyObject *dict, PyObject *name) { + PyObject *res = __Pyx_PyDict_GetItemStrWithError(dict, name); + if (res == NULL) PyErr_Clear(); + return res; +} +#elif !CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07020000 +#define __Pyx_PyDict_GetItemStrWithError PyDict_GetItemWithError +#define __Pyx_PyDict_GetItemStr PyDict_GetItem +#else +static CYTHON_INLINE PyObject * __Pyx_PyDict_GetItemStrWithError(PyObject *dict, PyObject *name) { +#if CYTHON_COMPILING_IN_PYPY + return PyDict_GetItem(dict, name); +#else + PyDictEntry *ep; + PyDictObject *mp = (PyDictObject*) dict; + long hash = ((PyStringObject *) name)->ob_shash; + assert(hash != -1); + ep = (mp->ma_lookup)(mp, name, hash); + if (ep == NULL) { + return NULL; + } + return ep->me_value; +#endif +} +#define __Pyx_PyDict_GetItemStr PyDict_GetItem +#endif +#if CYTHON_USE_TYPE_SLOTS + #define __Pyx_PyType_GetFlags(tp) (((PyTypeObject *)tp)->tp_flags) + #define __Pyx_PyType_HasFeature(type, feature) ((__Pyx_PyType_GetFlags(type) & (feature)) != 0) +#else + #define __Pyx_PyType_GetFlags(tp) (PyType_GetFlags((PyTypeObject *)tp)) + #define __Pyx_PyType_HasFeature(type, feature) PyType_HasFeature(type, feature) +#endif +#define __Pyx_PyObject_GetIterNextFunc(iterator) __Pyx_PyObject_GetSlot(iterator, tp_iternext, iternextfunc) +#if CYTHON_USE_TYPE_SPECS +#define __Pyx_PyHeapTypeObject_GC_Del(obj) {\ + PyTypeObject *type = Py_TYPE((PyObject*)obj);\ + assert(__Pyx_PyType_HasFeature(type, Py_TPFLAGS_HEAPTYPE));\ + PyObject_GC_Del(obj);\ + Py_DECREF(type);\ +} +#else +#define __Pyx_PyHeapTypeObject_GC_Del(obj) PyObject_GC_Del(obj) +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + #define __Pyx_PyUnicode_READY(op) (0) + #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_ReadChar(u, i) + #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) ((void)u, 1114111U) + #define __Pyx_PyUnicode_KIND(u) ((void)u, (0)) + #define __Pyx_PyUnicode_DATA(u) ((void*)u) + #define __Pyx_PyUnicode_READ(k, d, i) ((void)k, PyUnicode_ReadChar((PyObject*)(d), i)) + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GetLength(u)) +#else + #if PY_VERSION_HEX >= 0x030C0000 + #define __Pyx_PyUnicode_READY(op) (0) + #else + #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ?\ + 0 : _PyUnicode_Ready((PyObject *)(op))) + #endif + #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) + #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) PyUnicode_MAX_CHAR_VALUE(u) + #define __Pyx_PyUnicode_KIND(u) ((int)PyUnicode_KIND(u)) + #define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u) + #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) + #define __Pyx_PyUnicode_WRITE(k, d, i, ch) PyUnicode_WRITE(k, d, i, (Py_UCS4) ch) + #if PY_VERSION_HEX >= 0x030C0000 + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_LENGTH(u)) + #else + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x03090000 + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : ((PyCompactUnicodeObject *)(u))->wstr_length)) + #else + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : PyUnicode_GET_SIZE(u))) + #endif + #endif +#endif +#if CYTHON_COMPILING_IN_PYPY + #define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b) +#else + #define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ?\ + PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b)) +#endif +#if CYTHON_COMPILING_IN_PYPY + #if !defined(PyUnicode_DecodeUnicodeEscape) + #define PyUnicode_DecodeUnicodeEscape(s, size, errors) PyUnicode_Decode(s, size, "unicode_escape", errors) + #endif + #if !defined(PyUnicode_Contains) + #define PyUnicode_Contains(u, s) PySequence_Contains(u, s) + #endif + #if !defined(PyByteArray_Check) + #define PyByteArray_Check(obj) PyObject_TypeCheck(obj, &PyByteArray_Type) + #endif + #if !defined(PyObject_Format) + #define PyObject_Format(obj, fmt) PyObject_CallMethod(obj, "__format__", "O", fmt) + #endif +#endif +#define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None || (PyUnicode_Check(b) && !PyUnicode_CheckExact(b)))) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + #define __Pyx_PySequence_ListKeepNew(obj)\ + (likely(PyList_CheckExact(obj) && PyUnstable_Object_IsUniquelyReferenced(obj)) ? __Pyx_NewRef(obj) : PySequence_List(obj)) +#elif CYTHON_COMPILING_IN_CPYTHON + #define __Pyx_PySequence_ListKeepNew(obj)\ + (likely(PyList_CheckExact(obj) && Py_REFCNT(obj) == 1) ? __Pyx_NewRef(obj) : PySequence_List(obj)) +#else + #define __Pyx_PySequence_ListKeepNew(obj) PySequence_List(obj) +#endif +#ifndef PySet_CheckExact + #define PySet_CheckExact(obj) __Pyx_IS_TYPE(obj, &PySet_Type) +#endif +#if PY_VERSION_HEX >= 0x030900A4 + #define __Pyx_SET_REFCNT(obj, refcnt) Py_SET_REFCNT(obj, refcnt) + #define __Pyx_SET_SIZE(obj, size) Py_SET_SIZE(obj, size) +#else + #define __Pyx_SET_REFCNT(obj, refcnt) Py_REFCNT(obj) = (refcnt) + #define __Pyx_SET_SIZE(obj, size) Py_SIZE(obj) = (size) +#endif +enum __Pyx_ReferenceSharing { + __Pyx_ReferenceSharing_DefinitelyUnique, // We created it so we know it's unshared - no need to check + __Pyx_ReferenceSharing_OwnStrongReference, + __Pyx_ReferenceSharing_FunctionArgument, + __Pyx_ReferenceSharing_SharedReference, // Never trust it to be unshared because it's a global or similar +}; +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING && PY_VERSION_HEX >= 0x030E0000 +#define __Pyx_IS_UNIQUELY_REFERENCED(o, sharing)\ + (sharing == __Pyx_ReferenceSharing_DefinitelyUnique ? 1 :\ + (sharing == __Pyx_ReferenceSharing_FunctionArgument ? PyUnstable_Object_IsUniqueReferencedTemporary(o) :\ + (sharing == __Pyx_ReferenceSharing_OwnStrongReference ? PyUnstable_Object_IsUniquelyReferenced(o) : 0))) +#elif (CYTHON_COMPILING_IN_CPYTHON && !CYTHON_COMPILING_IN_CPYTHON_FREETHREADING) || CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_IS_UNIQUELY_REFERENCED(o, sharing) (((void)sharing), Py_REFCNT(o) == 1) +#else +#define __Pyx_IS_UNIQUELY_REFERENCED(o, sharing) (((void)o), ((void)sharing), 0) +#endif +#if CYTHON_AVOID_BORROWED_REFS || CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + #if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + #define __Pyx_PyList_GetItemRef(o, i) PyList_GetItemRef(o, i) + #elif CYTHON_COMPILING_IN_LIMITED_API || !CYTHON_ASSUME_SAFE_MACROS + #define __Pyx_PyList_GetItemRef(o, i) (likely((i) >= 0) ? PySequence_GetItem(o, i) : (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL)) + #else + #define __Pyx_PyList_GetItemRef(o, i) PySequence_ITEM(o, i) + #endif +#elif CYTHON_COMPILING_IN_LIMITED_API || !CYTHON_ASSUME_SAFE_MACROS + #if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + #define __Pyx_PyList_GetItemRef(o, i) PyList_GetItemRef(o, i) + #else + #define __Pyx_PyList_GetItemRef(o, i) __Pyx_XNewRef(PyList_GetItem(o, i)) + #endif +#else + #define __Pyx_PyList_GetItemRef(o, i) __Pyx_NewRef(PyList_GET_ITEM(o, i)) +#endif +#if CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS && !CYTHON_COMPILING_IN_LIMITED_API && CYTHON_ASSUME_SAFE_MACROS + #define __Pyx_PyList_GetItemRefFast(o, i, unsafe_shared) (__Pyx_IS_UNIQUELY_REFERENCED(o, unsafe_shared) ?\ + __Pyx_NewRef(PyList_GET_ITEM(o, i)) : __Pyx_PyList_GetItemRef(o, i)) +#else + #define __Pyx_PyList_GetItemRefFast(o, i, unsafe_shared) __Pyx_PyList_GetItemRef(o, i) +#endif +#if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 +#define __Pyx_PyDict_GetItemRef(dict, key, result) PyDict_GetItemRef(dict, key, result) +#elif CYTHON_AVOID_BORROWED_REFS || CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS +static CYTHON_INLINE int __Pyx_PyDict_GetItemRef(PyObject *dict, PyObject *key, PyObject **result) { + *result = PyObject_GetItem(dict, key); + if (*result == NULL) { + if (PyErr_ExceptionMatches(PyExc_KeyError)) { + PyErr_Clear(); + return 0; + } + return -1; + } + return 1; +} +#else +static CYTHON_INLINE int __Pyx_PyDict_GetItemRef(PyObject *dict, PyObject *key, PyObject **result) { + *result = PyDict_GetItemWithError(dict, key); + if (*result == NULL) { + return PyErr_Occurred() ? -1 : 0; + } + Py_INCREF(*result); + return 1; +} +#endif +#if defined(CYTHON_DEBUG_VISIT_CONST) && CYTHON_DEBUG_VISIT_CONST + #define __Pyx_VISIT_CONST(obj) Py_VISIT(obj) +#else + #define __Pyx_VISIT_CONST(obj) +#endif +#if CYTHON_ASSUME_SAFE_MACROS + #define __Pyx_PySequence_ITEM(o, i) PySequence_ITEM(o, i) + #define __Pyx_PySequence_SIZE(seq) Py_SIZE(seq) + #define __Pyx_PyTuple_SET_ITEM(o, i, v) (PyTuple_SET_ITEM(o, i, v), (0)) + #define __Pyx_PyTuple_GET_ITEM(o, i) PyTuple_GET_ITEM(o, i) + #define __Pyx_PyList_SET_ITEM(o, i, v) (PyList_SET_ITEM(o, i, v), (0)) + #define __Pyx_PyList_GET_ITEM(o, i) PyList_GET_ITEM(o, i) +#else + #define __Pyx_PySequence_ITEM(o, i) PySequence_GetItem(o, i) + #define __Pyx_PySequence_SIZE(seq) PySequence_Size(seq) + #define __Pyx_PyTuple_SET_ITEM(o, i, v) PyTuple_SetItem(o, i, v) + #define __Pyx_PyTuple_GET_ITEM(o, i) PyTuple_GetItem(o, i) + #define __Pyx_PyList_SET_ITEM(o, i, v) PyList_SetItem(o, i, v) + #define __Pyx_PyList_GET_ITEM(o, i) PyList_GetItem(o, i) +#endif +#if CYTHON_ASSUME_SAFE_SIZE + #define __Pyx_PyTuple_GET_SIZE(o) PyTuple_GET_SIZE(o) + #define __Pyx_PyList_GET_SIZE(o) PyList_GET_SIZE(o) + #define __Pyx_PySet_GET_SIZE(o) PySet_GET_SIZE(o) + #define __Pyx_PyBytes_GET_SIZE(o) PyBytes_GET_SIZE(o) + #define __Pyx_PyByteArray_GET_SIZE(o) PyByteArray_GET_SIZE(o) + #define __Pyx_PyUnicode_GET_LENGTH(o) PyUnicode_GET_LENGTH(o) +#else + #define __Pyx_PyTuple_GET_SIZE(o) PyTuple_Size(o) + #define __Pyx_PyList_GET_SIZE(o) PyList_Size(o) + #define __Pyx_PySet_GET_SIZE(o) PySet_Size(o) + #define __Pyx_PyBytes_GET_SIZE(o) PyBytes_Size(o) + #define __Pyx_PyByteArray_GET_SIZE(o) PyByteArray_Size(o) + #define __Pyx_PyUnicode_GET_LENGTH(o) PyUnicode_GetLength(o) +#endif +#if CYTHON_COMPILING_IN_PYPY && !defined(PyUnicode_InternFromString) + #define PyUnicode_InternFromString(s) PyUnicode_FromString(s) +#endif +#define __Pyx_PyLong_FromHash_t PyLong_FromSsize_t +#define __Pyx_PyLong_AsHash_t __Pyx_PyIndex_AsSsize_t +#if __PYX_LIMITED_VERSION_HEX >= 0x030A0000 + #define __Pyx_PySendResult PySendResult +#else + typedef enum { + PYGEN_RETURN = 0, + PYGEN_ERROR = -1, + PYGEN_NEXT = 1, + } __Pyx_PySendResult; +#endif +#if CYTHON_COMPILING_IN_LIMITED_API || PY_VERSION_HEX < 0x030A00A3 + typedef __Pyx_PySendResult (*__Pyx_pyiter_sendfunc)(PyObject *iter, PyObject *value, PyObject **result); +#else + #define __Pyx_pyiter_sendfunc sendfunc +#endif +#if !CYTHON_USE_AM_SEND +#define __PYX_HAS_PY_AM_SEND 0 +#elif __PYX_LIMITED_VERSION_HEX >= 0x030A0000 +#define __PYX_HAS_PY_AM_SEND 1 +#else +#define __PYX_HAS_PY_AM_SEND 2 // our own backported implementation +#endif +#if __PYX_HAS_PY_AM_SEND < 2 + #define __Pyx_PyAsyncMethodsStruct PyAsyncMethods +#else + typedef struct { + unaryfunc am_await; + unaryfunc am_aiter; + unaryfunc am_anext; + __Pyx_pyiter_sendfunc am_send; + } __Pyx_PyAsyncMethodsStruct; + #define __Pyx_SlotTpAsAsync(s) ((PyAsyncMethods*)(s)) +#endif +#if CYTHON_USE_AM_SEND && PY_VERSION_HEX < 0x030A00F0 + #define __Pyx_TPFLAGS_HAVE_AM_SEND (1UL << 21) +#else + #define __Pyx_TPFLAGS_HAVE_AM_SEND (0) +#endif +#if PY_VERSION_HEX >= 0x03090000 +#define __Pyx_PyInterpreterState_Get() PyInterpreterState_Get() +#else +#define __Pyx_PyInterpreterState_Get() PyThreadState_Get()->interp +#endif +#if CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030A0000 +#ifdef __cplusplus +extern "C" +#endif +PyAPI_FUNC(void *) PyMem_Calloc(size_t nelem, size_t elsize); +#endif +#if CYTHON_COMPILING_IN_LIMITED_API +static int __Pyx_init_co_variable(PyObject *inspect, const char* name, int *write_to) { + int value; + PyObject *py_value = PyObject_GetAttrString(inspect, name); + if (!py_value) return 0; + value = (int) PyLong_AsLong(py_value); + Py_DECREF(py_value); + *write_to = value; + return value != -1 || !PyErr_Occurred(); +} +static int __Pyx_init_co_variables(void) { + PyObject *inspect; + int result; + inspect = PyImport_ImportModule("inspect"); + result = +#if !defined(CO_OPTIMIZED) + __Pyx_init_co_variable(inspect, "CO_OPTIMIZED", &CO_OPTIMIZED) && +#endif +#if !defined(CO_NEWLOCALS) + __Pyx_init_co_variable(inspect, "CO_NEWLOCALS", &CO_NEWLOCALS) && +#endif +#if !defined(CO_VARARGS) + __Pyx_init_co_variable(inspect, "CO_VARARGS", &CO_VARARGS) && +#endif +#if !defined(CO_VARKEYWORDS) + __Pyx_init_co_variable(inspect, "CO_VARKEYWORDS", &CO_VARKEYWORDS) && +#endif +#if !defined(CO_ASYNC_GENERATOR) + __Pyx_init_co_variable(inspect, "CO_ASYNC_GENERATOR", &CO_ASYNC_GENERATOR) && +#endif +#if !defined(CO_GENERATOR) + __Pyx_init_co_variable(inspect, "CO_GENERATOR", &CO_GENERATOR) && +#endif +#if !defined(CO_COROUTINE) + __Pyx_init_co_variable(inspect, "CO_COROUTINE", &CO_COROUTINE) && +#endif + 1; + Py_DECREF(inspect); + return result ? 0 : -1; +} +#else +static int __Pyx_init_co_variables(void) { + return 0; // It's a limited API-only feature +} +#endif + +/* MathInitCode */ +#if defined(_WIN32) || defined(WIN32) || defined(MS_WINDOWS) + #ifndef _USE_MATH_DEFINES + #define _USE_MATH_DEFINES + #endif +#endif +#include +#if defined(__CYGWIN__) && defined(_LDBL_EQ_DBL) +#define __Pyx_truncl trunc +#else +#define __Pyx_truncl truncl +#endif + +#ifndef CYTHON_CLINE_IN_TRACEBACK_RUNTIME +#define CYTHON_CLINE_IN_TRACEBACK_RUNTIME 0 +#endif +#ifndef CYTHON_CLINE_IN_TRACEBACK +#define CYTHON_CLINE_IN_TRACEBACK CYTHON_CLINE_IN_TRACEBACK_RUNTIME +#endif +#if CYTHON_CLINE_IN_TRACEBACK +#define __PYX_MARK_ERR_POS(f_index, lineno) { __pyx_filename = __pyx_f[f_index]; (void) __pyx_filename; __pyx_lineno = lineno; (void) __pyx_lineno; __pyx_clineno = __LINE__; (void) __pyx_clineno; } +#else +#define __PYX_MARK_ERR_POS(f_index, lineno) { __pyx_filename = __pyx_f[f_index]; (void) __pyx_filename; __pyx_lineno = lineno; (void) __pyx_lineno; (void) __pyx_clineno; } +#endif +#define __PYX_ERR(f_index, lineno, Ln_error) \ + { __PYX_MARK_ERR_POS(f_index, lineno) goto Ln_error; } + +#ifdef CYTHON_EXTERN_C + #undef __PYX_EXTERN_C + #define __PYX_EXTERN_C CYTHON_EXTERN_C +#elif defined(__PYX_EXTERN_C) + #ifdef _MSC_VER + #pragma message ("Please do not define the '__PYX_EXTERN_C' macro externally. Use 'CYTHON_EXTERN_C' instead.") + #else + #warning Please do not define the '__PYX_EXTERN_C' macro externally. Use 'CYTHON_EXTERN_C' instead. + #endif +#else + #ifdef __cplusplus + #define __PYX_EXTERN_C extern "C" + #else + #define __PYX_EXTERN_C extern + #endif +#endif + +#define __PYX_HAVE__thriftpy2__transport__memory__cymemory +#define __PYX_HAVE_API__thriftpy2__transport__memory__cymemory +/* Early includes */ +#include +#include +#ifdef _OPENMP +#include +#endif /* _OPENMP */ + +#if defined(PYREX_WITHOUT_ASSERTIONS) && !defined(CYTHON_WITHOUT_ASSERTIONS) +#define CYTHON_WITHOUT_ASSERTIONS +#endif + +#ifdef CYTHON_FREETHREADING_COMPATIBLE +#if CYTHON_FREETHREADING_COMPATIBLE +#define __Pyx_FREETHREADING_COMPATIBLE Py_MOD_GIL_NOT_USED +#else +#define __Pyx_FREETHREADING_COMPATIBLE Py_MOD_GIL_USED +#endif +#else +#define __Pyx_FREETHREADING_COMPATIBLE Py_MOD_GIL_NOT_USED +#endif +#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 +#define __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 0 +#define __PYX_DEFAULT_STRING_ENCODING "" +#define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString +#define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#define __Pyx_uchar_cast(c) ((unsigned char)c) +#define __Pyx_long_cast(x) ((long)x) +#define __Pyx_fits_Py_ssize_t(v, type, is_signed) (\ + (sizeof(type) < sizeof(Py_ssize_t)) ||\ + (sizeof(type) > sizeof(Py_ssize_t) &&\ + likely(v < (type)PY_SSIZE_T_MAX ||\ + v == (type)PY_SSIZE_T_MAX) &&\ + (!is_signed || likely(v > (type)PY_SSIZE_T_MIN ||\ + v == (type)PY_SSIZE_T_MIN))) ||\ + (sizeof(type) == sizeof(Py_ssize_t) &&\ + (is_signed || likely(v < (type)PY_SSIZE_T_MAX ||\ + v == (type)PY_SSIZE_T_MAX))) ) +static CYTHON_INLINE int __Pyx_is_valid_index(Py_ssize_t i, Py_ssize_t limit) { + return (size_t) i < (size_t) limit; +} +#if defined (__cplusplus) && __cplusplus >= 201103L + #include + #define __Pyx_sst_abs(value) std::abs(value) +#elif SIZEOF_INT >= SIZEOF_SIZE_T + #define __Pyx_sst_abs(value) abs(value) +#elif SIZEOF_LONG >= SIZEOF_SIZE_T + #define __Pyx_sst_abs(value) labs(value) +#elif defined (_MSC_VER) + #define __Pyx_sst_abs(value) ((Py_ssize_t)_abs64(value)) +#elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define __Pyx_sst_abs(value) llabs(value) +#elif defined (__GNUC__) + #define __Pyx_sst_abs(value) __builtin_llabs(value) +#else + #define __Pyx_sst_abs(value) ((value<0) ? -value : value) +#endif +static CYTHON_INLINE Py_ssize_t __Pyx_ssize_strlen(const char *s); +static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject*); +static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); +static CYTHON_INLINE PyObject* __Pyx_PyByteArray_FromString(const char*); +#define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l) +#define __Pyx_PyBytes_FromString PyBytes_FromString +#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char*); +#if CYTHON_ASSUME_SAFE_MACROS + #define __Pyx_PyBytes_AsWritableString(s) ((char*) PyBytes_AS_STRING(s)) + #define __Pyx_PyBytes_AsWritableSString(s) ((signed char*) PyBytes_AS_STRING(s)) + #define __Pyx_PyBytes_AsWritableUString(s) ((unsigned char*) PyBytes_AS_STRING(s)) + #define __Pyx_PyBytes_AsString(s) ((const char*) PyBytes_AS_STRING(s)) + #define __Pyx_PyBytes_AsSString(s) ((const signed char*) PyBytes_AS_STRING(s)) + #define __Pyx_PyBytes_AsUString(s) ((const unsigned char*) PyBytes_AS_STRING(s)) + #define __Pyx_PyByteArray_AsString(s) PyByteArray_AS_STRING(s) +#else + #define __Pyx_PyBytes_AsWritableString(s) ((char*) PyBytes_AsString(s)) + #define __Pyx_PyBytes_AsWritableSString(s) ((signed char*) PyBytes_AsString(s)) + #define __Pyx_PyBytes_AsWritableUString(s) ((unsigned char*) PyBytes_AsString(s)) + #define __Pyx_PyBytes_AsString(s) ((const char*) PyBytes_AsString(s)) + #define __Pyx_PyBytes_AsSString(s) ((const signed char*) PyBytes_AsString(s)) + #define __Pyx_PyBytes_AsUString(s) ((const unsigned char*) PyBytes_AsString(s)) + #define __Pyx_PyByteArray_AsString(s) PyByteArray_AsString(s) +#endif +#define __Pyx_PyObject_AsWritableString(s) ((char*)(__pyx_uintptr_t) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsWritableSString(s) ((signed char*)(__pyx_uintptr_t) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsWritableUString(s) ((unsigned char*)(__pyx_uintptr_t) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsSString(s) ((const signed char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsUString(s) ((const unsigned char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_FromCString(s) __Pyx_PyObject_FromString((const char*)s) +#define __Pyx_PyBytes_FromCString(s) __Pyx_PyBytes_FromString((const char*)s) +#define __Pyx_PyByteArray_FromCString(s) __Pyx_PyByteArray_FromString((const char*)s) +#define __Pyx_PyUnicode_FromCString(s) __Pyx_PyUnicode_FromString((const char*)s) +#define __Pyx_PyUnicode_FromOrdinal(o) PyUnicode_FromOrdinal((int)o) +#define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode +static CYTHON_INLINE PyObject *__Pyx_NewRef(PyObject *obj) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030a0000 || defined(Py_NewRef) + return Py_NewRef(obj); +#else + Py_INCREF(obj); + return obj; +#endif +} +static CYTHON_INLINE PyObject *__Pyx_XNewRef(PyObject *obj) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030a0000 || defined(Py_XNewRef) + return Py_XNewRef(obj); +#else + Py_XINCREF(obj); + return obj; +#endif +} +static CYTHON_INLINE PyObject *__Pyx_Owned_Py_None(int b); +static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b); +static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); +static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject*); +static CYTHON_INLINE PyObject* __Pyx_PyNumber_Long(PyObject* x); +#define __Pyx_PySequence_Tuple(obj)\ + (likely(PyTuple_CheckExact(obj)) ? __Pyx_NewRef(obj) : PySequence_Tuple(obj)) +static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); +static CYTHON_INLINE PyObject * __Pyx_PyLong_FromSize_t(size_t); +static CYTHON_INLINE Py_hash_t __Pyx_PyIndex_AsHash_t(PyObject*); +#if CYTHON_ASSUME_SAFE_MACROS +#define __Pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) +#define __Pyx_PyFloat_AS_DOUBLE(x) PyFloat_AS_DOUBLE(x) +#else +#define __Pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) +#define __Pyx_PyFloat_AS_DOUBLE(x) PyFloat_AsDouble(x) +#endif +#define __Pyx_PyFloat_AsFloat(x) ((float) __Pyx_PyFloat_AsDouble(x)) +#define __Pyx_PyNumber_Int(x) (PyLong_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Long(x)) +#if CYTHON_USE_PYLONG_INTERNALS + #if PY_VERSION_HEX >= 0x030C00A7 + #ifndef _PyLong_SIGN_MASK + #define _PyLong_SIGN_MASK 3 + #endif + #ifndef _PyLong_NON_SIZE_BITS + #define _PyLong_NON_SIZE_BITS 3 + #endif + #define __Pyx_PyLong_Sign(x) (((PyLongObject*)x)->long_value.lv_tag & _PyLong_SIGN_MASK) + #define __Pyx_PyLong_IsNeg(x) ((__Pyx_PyLong_Sign(x) & 2) != 0) + #define __Pyx_PyLong_IsNonNeg(x) (!__Pyx_PyLong_IsNeg(x)) + #define __Pyx_PyLong_IsZero(x) (__Pyx_PyLong_Sign(x) & 1) + #define __Pyx_PyLong_IsPos(x) (__Pyx_PyLong_Sign(x) == 0) + #define __Pyx_PyLong_CompactValueUnsigned(x) (__Pyx_PyLong_Digits(x)[0]) + #define __Pyx_PyLong_DigitCount(x) ((Py_ssize_t) (((PyLongObject*)x)->long_value.lv_tag >> _PyLong_NON_SIZE_BITS)) + #define __Pyx_PyLong_SignedDigitCount(x)\ + ((1 - (Py_ssize_t) __Pyx_PyLong_Sign(x)) * __Pyx_PyLong_DigitCount(x)) + #if defined(PyUnstable_Long_IsCompact) && defined(PyUnstable_Long_CompactValue) + #define __Pyx_PyLong_IsCompact(x) PyUnstable_Long_IsCompact((PyLongObject*) x) + #define __Pyx_PyLong_CompactValue(x) PyUnstable_Long_CompactValue((PyLongObject*) x) + #else + #define __Pyx_PyLong_IsCompact(x) (((PyLongObject*)x)->long_value.lv_tag < (2 << _PyLong_NON_SIZE_BITS)) + #define __Pyx_PyLong_CompactValue(x) ((1 - (Py_ssize_t) __Pyx_PyLong_Sign(x)) * (Py_ssize_t) __Pyx_PyLong_Digits(x)[0]) + #endif + typedef Py_ssize_t __Pyx_compact_pylong; + typedef size_t __Pyx_compact_upylong; + #else + #define __Pyx_PyLong_IsNeg(x) (Py_SIZE(x) < 0) + #define __Pyx_PyLong_IsNonNeg(x) (Py_SIZE(x) >= 0) + #define __Pyx_PyLong_IsZero(x) (Py_SIZE(x) == 0) + #define __Pyx_PyLong_IsPos(x) (Py_SIZE(x) > 0) + #define __Pyx_PyLong_CompactValueUnsigned(x) ((Py_SIZE(x) == 0) ? 0 : __Pyx_PyLong_Digits(x)[0]) + #define __Pyx_PyLong_DigitCount(x) __Pyx_sst_abs(Py_SIZE(x)) + #define __Pyx_PyLong_SignedDigitCount(x) Py_SIZE(x) + #define __Pyx_PyLong_IsCompact(x) (Py_SIZE(x) == 0 || Py_SIZE(x) == 1 || Py_SIZE(x) == -1) + #define __Pyx_PyLong_CompactValue(x)\ + ((Py_SIZE(x) == 0) ? (sdigit) 0 : ((Py_SIZE(x) < 0) ? -(sdigit)__Pyx_PyLong_Digits(x)[0] : (sdigit)__Pyx_PyLong_Digits(x)[0])) + typedef sdigit __Pyx_compact_pylong; + typedef digit __Pyx_compact_upylong; + #endif + #if PY_VERSION_HEX >= 0x030C00A5 + #define __Pyx_PyLong_Digits(x) (((PyLongObject*)x)->long_value.ob_digit) + #else + #define __Pyx_PyLong_Digits(x) (((PyLongObject*)x)->ob_digit) + #endif +#endif +#if __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 + #define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) +#elif __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + #define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeASCII(c_str, size, NULL) +#else + #define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) +#endif + + +/* Test for GCC > 2.95 */ +#if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))) + #define likely(x) __builtin_expect(!!(x), 1) + #define unlikely(x) __builtin_expect(!!(x), 0) +#else /* !__GNUC__ or GCC < 2.95 */ + #define likely(x) (x) + #define unlikely(x) (x) +#endif /* __GNUC__ */ +/* PretendToInitialize */ +#ifdef __cplusplus +#if __cplusplus > 201103L +#include +#endif +template +static void __Pyx_pretend_to_initialize(T* ptr) { +#if __cplusplus > 201103L + if ((std::is_trivially_default_constructible::value)) +#endif + *ptr = T(); + (void)ptr; +} +#else +static CYTHON_INLINE void __Pyx_pretend_to_initialize(void* ptr) { (void)ptr; } +#endif + + +#if !CYTHON_USE_MODULE_STATE +static PyObject *__pyx_m = NULL; +#endif +static int __pyx_lineno; +static int __pyx_clineno = 0; +static const char * const __pyx_cfilenm = __FILE__; +static const char *__pyx_filename; + +/* #### Code section: filename_table ### */ + +static const char* const __pyx_f[] = { + "thriftpy2/transport/memory/cymemory.pyx", + "", + "thriftpy2/transport/cybase.pxd", +}; +/* #### Code section: utility_code_proto_before_types ### */ +/* Atomics.proto (used by UnpackUnboundCMethod) */ +#include +#ifndef CYTHON_ATOMICS + #define CYTHON_ATOMICS 1 +#endif +#define __PYX_CYTHON_ATOMICS_ENABLED() CYTHON_ATOMICS +#define __PYX_GET_CYTHON_COMPILING_IN_CPYTHON_FREETHREADING() CYTHON_COMPILING_IN_CPYTHON_FREETHREADING +#define __pyx_atomic_int_type int +#define __pyx_nonatomic_int_type int +#if CYTHON_ATOMICS && (defined(__STDC_VERSION__) &&\ + (__STDC_VERSION__ >= 201112L) &&\ + !defined(__STDC_NO_ATOMICS__)) + #include +#elif CYTHON_ATOMICS && (defined(__cplusplus) && (\ + (__cplusplus >= 201103L) ||\ + (defined(_MSC_VER) && _MSC_VER >= 1700))) + #include +#endif +#if CYTHON_ATOMICS && (defined(__STDC_VERSION__) &&\ + (__STDC_VERSION__ >= 201112L) &&\ + !defined(__STDC_NO_ATOMICS__) &&\ + ATOMIC_INT_LOCK_FREE == 2) + #undef __pyx_atomic_int_type + #define __pyx_atomic_int_type atomic_int + #define __pyx_atomic_ptr_type atomic_uintptr_t + #define __pyx_nonatomic_ptr_type uintptr_t + #define __pyx_atomic_incr_relaxed(value) atomic_fetch_add_explicit(value, 1, memory_order_relaxed) + #define __pyx_atomic_incr_acq_rel(value) atomic_fetch_add_explicit(value, 1, memory_order_acq_rel) + #define __pyx_atomic_decr_acq_rel(value) atomic_fetch_sub_explicit(value, 1, memory_order_acq_rel) + #define __pyx_atomic_sub(value, arg) atomic_fetch_sub(value, arg) + #define __pyx_atomic_int_cmp_exchange(value, expected, desired) atomic_compare_exchange_strong(value, expected, desired) + #define __pyx_atomic_load(value) atomic_load(value) + #define __pyx_atomic_store(value, new_value) atomic_store(value, new_value) + #define __pyx_atomic_pointer_load_relaxed(value) atomic_load_explicit(value, memory_order_relaxed) + #define __pyx_atomic_pointer_load_acquire(value) atomic_load_explicit(value, memory_order_acquire) + #define __pyx_atomic_pointer_exchange(value, new_value) atomic_exchange(value, (__pyx_nonatomic_ptr_type)new_value) + #define __pyx_atomic_pointer_cmp_exchange(value, expected, desired) atomic_compare_exchange_strong(value, expected, desired) + #if defined(__PYX_DEBUG_ATOMICS) && defined(_MSC_VER) + #pragma message ("Using standard C atomics") + #elif defined(__PYX_DEBUG_ATOMICS) + #warning "Using standard C atomics" + #endif +#elif CYTHON_ATOMICS && (defined(__cplusplus) && (\ + (__cplusplus >= 201103L) ||\ +\ + (defined(_MSC_VER) && _MSC_VER >= 1700)) &&\ + ATOMIC_INT_LOCK_FREE == 2) + #undef __pyx_atomic_int_type + #define __pyx_atomic_int_type std::atomic_int + #define __pyx_atomic_ptr_type std::atomic_uintptr_t + #define __pyx_nonatomic_ptr_type uintptr_t + #define __pyx_atomic_incr_relaxed(value) std::atomic_fetch_add_explicit(value, 1, std::memory_order_relaxed) + #define __pyx_atomic_incr_acq_rel(value) std::atomic_fetch_add_explicit(value, 1, std::memory_order_acq_rel) + #define __pyx_atomic_decr_acq_rel(value) std::atomic_fetch_sub_explicit(value, 1, std::memory_order_acq_rel) + #define __pyx_atomic_sub(value, arg) std::atomic_fetch_sub(value, arg) + #define __pyx_atomic_int_cmp_exchange(value, expected, desired) std::atomic_compare_exchange_strong(value, expected, desired) + #define __pyx_atomic_load(value) std::atomic_load(value) + #define __pyx_atomic_store(value, new_value) std::atomic_store(value, new_value) + #define __pyx_atomic_pointer_load_relaxed(value) std::atomic_load_explicit(value, std::memory_order_relaxed) + #define __pyx_atomic_pointer_load_acquire(value) std::atomic_load_explicit(value, std::memory_order_acquire) + #define __pyx_atomic_pointer_exchange(value, new_value) std::atomic_exchange(value, (__pyx_nonatomic_ptr_type)new_value) + #define __pyx_atomic_pointer_cmp_exchange(value, expected, desired) std::atomic_compare_exchange_strong(value, expected, desired) + #if defined(__PYX_DEBUG_ATOMICS) && defined(_MSC_VER) + #pragma message ("Using standard C++ atomics") + #elif defined(__PYX_DEBUG_ATOMICS) + #warning "Using standard C++ atomics" + #endif +#elif CYTHON_ATOMICS && (__GNUC__ >= 5 || (__GNUC__ == 4 &&\ + (__GNUC_MINOR__ > 1 ||\ + (__GNUC_MINOR__ == 1 && __GNUC_PATCHLEVEL__ >= 2)))) + #define __pyx_atomic_ptr_type void* + #define __pyx_nonatomic_ptr_type void* + #define __pyx_atomic_incr_relaxed(value) __sync_fetch_and_add(value, 1) + #define __pyx_atomic_incr_acq_rel(value) __sync_fetch_and_add(value, 1) + #define __pyx_atomic_decr_acq_rel(value) __sync_fetch_and_sub(value, 1) + #define __pyx_atomic_sub(value, arg) __sync_fetch_and_sub(value, arg) + static CYTHON_INLINE int __pyx_atomic_int_cmp_exchange(__pyx_atomic_int_type* value, __pyx_nonatomic_int_type* expected, __pyx_nonatomic_int_type desired) { + __pyx_nonatomic_int_type old = __sync_val_compare_and_swap(value, *expected, desired); + int result = old == *expected; + *expected = old; + return result; + } + #define __pyx_atomic_load(value) __sync_fetch_and_add(value, 0) + #define __pyx_atomic_store(value, new_value) __sync_lock_test_and_set(value, new_value) + #define __pyx_atomic_pointer_load_relaxed(value) __sync_fetch_and_add(value, 0) + #define __pyx_atomic_pointer_load_acquire(value) __sync_fetch_and_add(value, 0) + #define __pyx_atomic_pointer_exchange(value, new_value) __sync_lock_test_and_set(value, (__pyx_atomic_ptr_type)new_value) + static CYTHON_INLINE int __pyx_atomic_pointer_cmp_exchange(__pyx_atomic_ptr_type* value, __pyx_nonatomic_ptr_type* expected, __pyx_nonatomic_ptr_type desired) { + __pyx_nonatomic_ptr_type old = __sync_val_compare_and_swap(value, *expected, desired); + int result = old == *expected; + *expected = old; + return result; + } + #ifdef __PYX_DEBUG_ATOMICS + #warning "Using GNU atomics" + #endif +#elif CYTHON_ATOMICS && defined(_MSC_VER) + #include + #undef __pyx_atomic_int_type + #define __pyx_atomic_int_type long + #define __pyx_atomic_ptr_type void* + #undef __pyx_nonatomic_int_type + #define __pyx_nonatomic_int_type long + #define __pyx_nonatomic_ptr_type void* + #pragma intrinsic (_InterlockedExchangeAdd, _InterlockedExchange, _InterlockedCompareExchange, _InterlockedCompareExchangePointer, _InterlockedExchangePointer) + #define __pyx_atomic_incr_relaxed(value) _InterlockedExchangeAdd(value, 1) + #define __pyx_atomic_incr_acq_rel(value) _InterlockedExchangeAdd(value, 1) + #define __pyx_atomic_decr_acq_rel(value) _InterlockedExchangeAdd(value, -1) + #define __pyx_atomic_sub(value, arg) _InterlockedExchangeAdd(value, -arg) + static CYTHON_INLINE int __pyx_atomic_int_cmp_exchange(__pyx_atomic_int_type* value, __pyx_nonatomic_int_type* expected, __pyx_nonatomic_int_type desired) { + __pyx_nonatomic_int_type old = _InterlockedCompareExchange(value, desired, *expected); + int result = old == *expected; + *expected = old; + return result; + } + #define __pyx_atomic_load(value) _InterlockedExchangeAdd(value, 0) + #define __pyx_atomic_store(value, new_value) _InterlockedExchange(value, new_value) + #define __pyx_atomic_pointer_load_relaxed(value) *(void * volatile *)value + #define __pyx_atomic_pointer_load_acquire(value) _InterlockedCompareExchangePointer(value, 0, 0) + #define __pyx_atomic_pointer_exchange(value, new_value) _InterlockedExchangePointer(value, (__pyx_atomic_ptr_type)new_value) + static CYTHON_INLINE int __pyx_atomic_pointer_cmp_exchange(__pyx_atomic_ptr_type* value, __pyx_nonatomic_ptr_type* expected, __pyx_nonatomic_ptr_type desired) { + __pyx_atomic_ptr_type old = _InterlockedCompareExchangePointer(value, desired, *expected); + int result = old == *expected; + *expected = old; + return result; + } + #ifdef __PYX_DEBUG_ATOMICS + #pragma message ("Using MSVC atomics") + #endif +#else + #undef CYTHON_ATOMICS + #define CYTHON_ATOMICS 0 + #ifdef __PYX_DEBUG_ATOMICS + #warning "Not using atomics" + #endif +#endif + +/* CriticalSectionsDefinition.proto (used by CriticalSections) */ +#if !CYTHON_COMPILING_IN_CPYTHON_FREETHREADING +#define __Pyx_PyCriticalSection void* +#define __Pyx_PyCriticalSection2 void* +#define __Pyx_PyCriticalSection_End(cs) +#define __Pyx_PyCriticalSection2_End(cs) +#else +#define __Pyx_PyCriticalSection PyCriticalSection +#define __Pyx_PyCriticalSection2 PyCriticalSection2 +#define __Pyx_PyCriticalSection_End PyCriticalSection_End +#define __Pyx_PyCriticalSection2_End PyCriticalSection2_End +#endif + +/* CriticalSections.proto (used by ParseKeywordsImpl) */ +#if !CYTHON_COMPILING_IN_CPYTHON_FREETHREADING +#define __Pyx_PyCriticalSection_Begin(cs, arg) (void)(cs) +#define __Pyx_PyCriticalSection2_Begin(cs, arg1, arg2) (void)(cs) +#else +#define __Pyx_PyCriticalSection_Begin PyCriticalSection_Begin +#define __Pyx_PyCriticalSection2_Begin PyCriticalSection2_Begin +#endif +#if PY_VERSION_HEX < 0x030d0000 || CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_BEGIN_CRITICAL_SECTION(o) { +#define __Pyx_END_CRITICAL_SECTION() } +#else +#define __Pyx_BEGIN_CRITICAL_SECTION Py_BEGIN_CRITICAL_SECTION +#define __Pyx_END_CRITICAL_SECTION Py_END_CRITICAL_SECTION +#endif + +/* IncludeStructmemberH.proto (used by FixUpExtensionType) */ +#include + +/* #### Code section: numeric_typedefs ### */ +/* #### Code section: complex_type_declarations ### */ +/* #### Code section: type_declarations ### */ + +/*--- Type declarations ---*/ +struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer; +struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase; +struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer; + +/* "thriftpy2/transport/cybase.pxd":3 + * # cython: freethreading_compatible = True + * + * cdef enum: # <<<<<<<<<<<<<< + * DEFAULT_BUFFER = 4096 + * STACK_STRING_LEN = 4096 +*/ +enum { + __pyx_e_9thriftpy2_9transport_6cybase_DEFAULT_BUFFER = 0x1000, + __pyx_e_9thriftpy2_9transport_6cybase_STACK_STRING_LEN = 0x1000 +}; + +/* "thriftpy2/transport/cybase.pxd":7 + * STACK_STRING_LEN = 4096 + * + * cdef class TCyBuffer(object): # <<<<<<<<<<<<<< + * cdef: + * char *buf +*/ +struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer { + PyObject_HEAD + struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_TCyBuffer *__pyx_vtab; + char *buf; + int cur; + int buf_size; + int data_size; +}; + + +/* "thriftpy2/transport/cybase.pxd":19 + * + * + * cdef class CyTransportBase(object): # <<<<<<<<<<<<<< + * cdef object trans + * +*/ +struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase { + PyObject_HEAD + struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_CyTransportBase *__pyx_vtab; + PyObject *trans; +}; + + +/* "thriftpy2/transport/memory/cymemory.pyx":12 + * + * + * cdef class TCyMemoryBuffer(CyTransportBase): # <<<<<<<<<<<<<< + * cdef TCyBuffer buf + * +*/ +struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer { + struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase __pyx_base; + struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *buf; +}; + + + +/* "thriftpy2/transport/cybase.pxd":7 + * STACK_STRING_LEN = 4096 + * + * cdef class TCyBuffer(object): # <<<<<<<<<<<<<< + * cdef: + * char *buf +*/ + +struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_TCyBuffer { + void (*move_to_start)(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *); + void (*clean)(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *); + int (*write)(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *, int, char const *); + int (*grow)(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *, int); + PyObject *(*read_trans)(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *, PyObject *, int, char *); +}; +static struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_TCyBuffer *__pyx_vtabptr_9thriftpy2_9transport_6cybase_TCyBuffer; + + +/* "thriftpy2/transport/cybase.pxd":19 + * + * + * cdef class CyTransportBase(object): # <<<<<<<<<<<<<< + * cdef object trans + * +*/ + +struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_CyTransportBase { + PyObject *(*c_read)(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *, int, char *); + PyObject *(*c_write)(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *, char *, int); + PyObject *(*c_flush)(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *); + PyObject *(*get_string)(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *, int); +}; +static struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_CyTransportBase *__pyx_vtabptr_9thriftpy2_9transport_6cybase_CyTransportBase; + + +/* "thriftpy2/transport/memory/cymemory.pyx":12 + * + * + * cdef class TCyMemoryBuffer(CyTransportBase): # <<<<<<<<<<<<<< + * cdef TCyBuffer buf + * +*/ + +struct __pyx_vtabstruct_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer { + struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_CyTransportBase __pyx_base; + PyObject *(*_getvalue)(struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *); + PyObject *(*_setvalue)(struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *, int, char const *); +}; +static struct __pyx_vtabstruct_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *__pyx_vtabptr_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer; +/* #### Code section: utility_code_proto ### */ + +/* --- Runtime support code (head) --- */ +/* Refnanny.proto */ +#ifndef CYTHON_REFNANNY + #define CYTHON_REFNANNY 0 +#endif +#if CYTHON_REFNANNY + typedef struct { + void (*INCREF)(void*, PyObject*, Py_ssize_t); + void (*DECREF)(void*, PyObject*, Py_ssize_t); + void (*GOTREF)(void*, PyObject*, Py_ssize_t); + void (*GIVEREF)(void*, PyObject*, Py_ssize_t); + void* (*SetupContext)(const char*, Py_ssize_t, const char*); + void (*FinishContext)(void**); + } __Pyx_RefNannyAPIStruct; + static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; + static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); + #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; + #define __Pyx_RefNannySetupContext(name, acquire_gil)\ + if (acquire_gil) {\ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), (__LINE__), (__FILE__));\ + PyGILState_Release(__pyx_gilstate_save);\ + } else {\ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), (__LINE__), (__FILE__));\ + } + #define __Pyx_RefNannyFinishContextNogil() {\ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ + __Pyx_RefNannyFinishContext();\ + PyGILState_Release(__pyx_gilstate_save);\ + } + #define __Pyx_RefNannyFinishContextNogil() {\ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ + __Pyx_RefNannyFinishContext();\ + PyGILState_Release(__pyx_gilstate_save);\ + } + #define __Pyx_RefNannyFinishContext()\ + __Pyx_RefNanny->FinishContext(&__pyx_refnanny) + #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), (__LINE__)) + #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), (__LINE__)) + #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), (__LINE__)) + #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), (__LINE__)) + #define __Pyx_XINCREF(r) do { if((r) == NULL); else {__Pyx_INCREF(r); }} while(0) + #define __Pyx_XDECREF(r) do { if((r) == NULL); else {__Pyx_DECREF(r); }} while(0) + #define __Pyx_XGOTREF(r) do { if((r) == NULL); else {__Pyx_GOTREF(r); }} while(0) + #define __Pyx_XGIVEREF(r) do { if((r) == NULL); else {__Pyx_GIVEREF(r);}} while(0) +#else + #define __Pyx_RefNannyDeclarations + #define __Pyx_RefNannySetupContext(name, acquire_gil) + #define __Pyx_RefNannyFinishContextNogil() + #define __Pyx_RefNannyFinishContext() + #define __Pyx_INCREF(r) Py_INCREF(r) + #define __Pyx_DECREF(r) Py_DECREF(r) + #define __Pyx_GOTREF(r) + #define __Pyx_GIVEREF(r) + #define __Pyx_XINCREF(r) Py_XINCREF(r) + #define __Pyx_XDECREF(r) Py_XDECREF(r) + #define __Pyx_XGOTREF(r) + #define __Pyx_XGIVEREF(r) +#endif +#define __Pyx_Py_XDECREF_SET(r, v) do {\ + PyObject *tmp = (PyObject *) r;\ + r = v; Py_XDECREF(tmp);\ + } while (0) +#define __Pyx_XDECREF_SET(r, v) do {\ + PyObject *tmp = (PyObject *) r;\ + r = v; __Pyx_XDECREF(tmp);\ + } while (0) +#define __Pyx_DECREF_SET(r, v) do {\ + PyObject *tmp = (PyObject *) r;\ + r = v; __Pyx_DECREF(tmp);\ + } while (0) +#define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) +#define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) + +/* TupleAndListFromArray.proto (used by fastcall) */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyList_FromArray(PyObject *const *src, Py_ssize_t n); +#endif +#if CYTHON_COMPILING_IN_CPYTHON || CYTHON_METH_FASTCALL +static CYTHON_INLINE PyObject* __Pyx_PyTuple_FromArray(PyObject *const *src, Py_ssize_t n); +#endif + +/* IncludeStringH.proto (used by BytesEquals) */ +#include + +/* BytesEquals.proto (used by UnicodeEquals) */ +static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals); + +/* UnicodeEquals.proto (used by fastcall) */ +static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals); + +/* fastcall.proto */ +#if CYTHON_AVOID_BORROWED_REFS + #define __Pyx_ArgRef_VARARGS(args, i) __Pyx_PySequence_ITEM(args, i) +#elif CYTHON_ASSUME_SAFE_MACROS + #define __Pyx_ArgRef_VARARGS(args, i) __Pyx_NewRef(__Pyx_PyTuple_GET_ITEM(args, i)) +#else + #define __Pyx_ArgRef_VARARGS(args, i) __Pyx_XNewRef(PyTuple_GetItem(args, i)) +#endif +#define __Pyx_NumKwargs_VARARGS(kwds) PyDict_Size(kwds) +#define __Pyx_KwValues_VARARGS(args, nargs) NULL +#define __Pyx_GetKwValue_VARARGS(kw, kwvalues, s) __Pyx_PyDict_GetItemStrWithError(kw, s) +#define __Pyx_KwargsAsDict_VARARGS(kw, kwvalues) PyDict_Copy(kw) +#if CYTHON_METH_FASTCALL + #define __Pyx_ArgRef_FASTCALL(args, i) __Pyx_NewRef(args[i]) + #define __Pyx_NumKwargs_FASTCALL(kwds) __Pyx_PyTuple_GET_SIZE(kwds) + #define __Pyx_KwValues_FASTCALL(args, nargs) ((args) + (nargs)) + static CYTHON_INLINE PyObject * __Pyx_GetKwValue_FASTCALL(PyObject *kwnames, PyObject *const *kwvalues, PyObject *s); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030d0000 || CYTHON_COMPILING_IN_LIMITED_API + CYTHON_UNUSED static PyObject *__Pyx_KwargsAsDict_FASTCALL(PyObject *kwnames, PyObject *const *kwvalues); + #else + #define __Pyx_KwargsAsDict_FASTCALL(kw, kwvalues) _PyStack_AsDict(kwvalues, kw) + #endif +#else + #define __Pyx_ArgRef_FASTCALL __Pyx_ArgRef_VARARGS + #define __Pyx_NumKwargs_FASTCALL __Pyx_NumKwargs_VARARGS + #define __Pyx_KwValues_FASTCALL __Pyx_KwValues_VARARGS + #define __Pyx_GetKwValue_FASTCALL __Pyx_GetKwValue_VARARGS + #define __Pyx_KwargsAsDict_FASTCALL __Pyx_KwargsAsDict_VARARGS +#endif +#define __Pyx_ArgsSlice_VARARGS(args, start, stop) PyTuple_GetSlice(args, start, stop) +#if CYTHON_METH_FASTCALL || (CYTHON_COMPILING_IN_CPYTHON && CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS) +#define __Pyx_ArgsSlice_FASTCALL(args, start, stop) __Pyx_PyTuple_FromArray(args + start, stop - start) +#else +#define __Pyx_ArgsSlice_FASTCALL(args, start, stop) PyTuple_GetSlice(args, start, stop) +#endif + +/* py_dict_items.proto (used by OwnedDictNext) */ +static CYTHON_INLINE PyObject* __Pyx_PyDict_Items(PyObject* d); + +/* CallCFunction.proto (used by CallUnboundCMethod0) */ +#define __Pyx_CallCFunction(cfunc, self, args)\ + ((PyCFunction)(void(*)(void))(cfunc)->func)(self, args) +#define __Pyx_CallCFunctionWithKeywords(cfunc, self, args, kwargs)\ + ((PyCFunctionWithKeywords)(void(*)(void))(cfunc)->func)(self, args, kwargs) +#define __Pyx_CallCFunctionFast(cfunc, self, args, nargs)\ + ((__Pyx_PyCFunctionFast)(void(*)(void))(PyCFunction)(cfunc)->func)(self, args, nargs) +#define __Pyx_CallCFunctionFastWithKeywords(cfunc, self, args, nargs, kwnames)\ + ((__Pyx_PyCFunctionFastWithKeywords)(void(*)(void))(PyCFunction)(cfunc)->func)(self, args, nargs, kwnames) + +/* PyObjectCall.proto (used by PyObjectFastCall) */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw); +#else +#define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw) +#endif + +/* PyObjectCallMethO.proto (used by PyObjectFastCall) */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg); +#endif + +/* PyObjectFastCall.proto (used by PyObjectCallOneArg) */ +#define __Pyx_PyObject_FastCall(func, args, nargs) __Pyx_PyObject_FastCallDict(func, args, (size_t)(nargs), NULL) +static CYTHON_INLINE PyObject* __Pyx_PyObject_FastCallDict(PyObject *func, PyObject * const*args, size_t nargs, PyObject *kwargs); + +/* PyObjectCallOneArg.proto (used by CallUnboundCMethod0) */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg); + +/* PyObjectGetAttrStr.proto (used by UnpackUnboundCMethod) */ +#if CYTHON_USE_TYPE_SLOTS +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name); +#else +#define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) +#endif + +/* UnpackUnboundCMethod.proto (used by CallUnboundCMethod0) */ +typedef struct { + PyObject *type; + PyObject **method_name; +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING && CYTHON_ATOMICS + __pyx_atomic_int_type initialized; +#endif + PyCFunction func; + PyObject *method; + int flag; +} __Pyx_CachedCFunction; +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING +static CYTHON_INLINE int __Pyx_CachedCFunction_GetAndSetInitializing(__Pyx_CachedCFunction *cfunc) { +#if !CYTHON_ATOMICS + return 1; +#else + __pyx_nonatomic_int_type expected = 0; + if (__pyx_atomic_int_cmp_exchange(&cfunc->initialized, &expected, 1)) { + return 0; + } + return expected; +#endif +} +static CYTHON_INLINE void __Pyx_CachedCFunction_SetFinishedInitializing(__Pyx_CachedCFunction *cfunc) { +#if CYTHON_ATOMICS + __pyx_atomic_store(&cfunc->initialized, 2); +#endif +} +#else +#define __Pyx_CachedCFunction_GetAndSetInitializing(cfunc) 2 +#define __Pyx_CachedCFunction_SetFinishedInitializing(cfunc) +#endif + +/* CallUnboundCMethod0.proto */ +CYTHON_UNUSED +static PyObject* __Pyx__CallUnboundCMethod0(__Pyx_CachedCFunction* cfunc, PyObject* self); +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_CallUnboundCMethod0(__Pyx_CachedCFunction* cfunc, PyObject* self); +#else +#define __Pyx_CallUnboundCMethod0(cfunc, self) __Pyx__CallUnboundCMethod0(cfunc, self) +#endif + +/* py_dict_values.proto (used by OwnedDictNext) */ +static CYTHON_INLINE PyObject* __Pyx_PyDict_Values(PyObject* d); + +/* OwnedDictNext.proto (used by ParseKeywordsImpl) */ +#if CYTHON_AVOID_BORROWED_REFS +static int __Pyx_PyDict_NextRef(PyObject *p, PyObject **ppos, PyObject **pkey, PyObject **pvalue); +#else +CYTHON_INLINE +static int __Pyx_PyDict_NextRef(PyObject *p, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue); +#endif + +/* RaiseDoubleKeywords.proto (used by ParseKeywordsImpl) */ +static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); + +/* ParseKeywordsImpl.export */ +static int __Pyx_ParseKeywordsTuple( + PyObject *kwds, + PyObject * const *kwvalues, + PyObject ** const argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + Py_ssize_t num_kwargs, + const char* function_name, + int ignore_unknown_kwargs +); +static int __Pyx_ParseKeywordDictToDict( + PyObject *kwds, + PyObject ** const argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + const char* function_name +); +static int __Pyx_ParseKeywordDict( + PyObject *kwds, + PyObject ** const argnames[], + PyObject *values[], + Py_ssize_t num_pos_args, + Py_ssize_t num_kwargs, + const char* function_name, + int ignore_unknown_kwargs +); + +/* CallUnboundCMethod2.proto */ +CYTHON_UNUSED +static PyObject* __Pyx__CallUnboundCMethod2(__Pyx_CachedCFunction* cfunc, PyObject* self, PyObject* arg1, PyObject* arg2); +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject *__Pyx_CallUnboundCMethod2(__Pyx_CachedCFunction *cfunc, PyObject *self, PyObject *arg1, PyObject *arg2); +#else +#define __Pyx_CallUnboundCMethod2(cfunc, self, arg1, arg2) __Pyx__CallUnboundCMethod2(cfunc, self, arg1, arg2) +#endif + +/* ParseKeywords.proto */ +static CYTHON_INLINE int __Pyx_ParseKeywords( + PyObject *kwds, PyObject *const *kwvalues, PyObject ** const argnames[], + PyObject *kwds2, PyObject *values[], + Py_ssize_t num_pos_args, Py_ssize_t num_kwargs, + const char* function_name, + int ignore_unknown_kwargs +); + +/* RaiseArgTupleInvalid.proto */ +static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, + Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); + +/* PyObjectFastCallMethod.proto */ +#if CYTHON_VECTORCALL && PY_VERSION_HEX >= 0x03090000 +#define __Pyx_PyObject_FastCallMethod(name, args, nargsf) PyObject_VectorcallMethod(name, args, nargsf, NULL) +#else +static PyObject *__Pyx_PyObject_FastCallMethod(PyObject *name, PyObject *const *args, size_t nargsf); +#endif + +/* PyMemoryError_Check.proto */ +#define __Pyx_PyExc_MemoryError_Check(obj) __Pyx_TypeCheck(obj, PyExc_MemoryError) + +/* PyThreadStateGet.proto (used by PyErrFetchRestore) */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_PyThreadState_declare PyThreadState *__pyx_tstate; +#define __Pyx_PyThreadState_assign __pyx_tstate = __Pyx_PyThreadState_Current; +#if PY_VERSION_HEX >= 0x030C00A6 +#define __Pyx_PyErr_Occurred() (__pyx_tstate->current_exception != NULL) +#define __Pyx_PyErr_CurrentExceptionType() (__pyx_tstate->current_exception ? (PyObject*) Py_TYPE(__pyx_tstate->current_exception) : (PyObject*) NULL) +#else +#define __Pyx_PyErr_Occurred() (__pyx_tstate->curexc_type != NULL) +#define __Pyx_PyErr_CurrentExceptionType() (__pyx_tstate->curexc_type) +#endif +#else +#define __Pyx_PyThreadState_declare +#define __Pyx_PyThreadState_assign +#define __Pyx_PyErr_Occurred() (PyErr_Occurred() != NULL) +#define __Pyx_PyErr_CurrentExceptionType() PyErr_Occurred() +#endif + +/* PyErrFetchRestore.proto (used by RaiseException) */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_PyErr_Clear() __Pyx_ErrRestore(NULL, NULL, NULL) +#define __Pyx_ErrRestoreWithState(type, value, tb) __Pyx_ErrRestoreInState(PyThreadState_GET(), type, value, tb) +#define __Pyx_ErrFetchWithState(type, value, tb) __Pyx_ErrFetchInState(PyThreadState_GET(), type, value, tb) +#define __Pyx_ErrRestore(type, value, tb) __Pyx_ErrRestoreInState(__pyx_tstate, type, value, tb) +#define __Pyx_ErrFetch(type, value, tb) __Pyx_ErrFetchInState(__pyx_tstate, type, value, tb) +static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); +static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030C00A6 +#define __Pyx_PyErr_SetNone(exc) (Py_INCREF(exc), __Pyx_ErrRestore((exc), NULL, NULL)) +#else +#define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) +#endif +#else +#define __Pyx_PyErr_Clear() PyErr_Clear() +#define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) +#define __Pyx_ErrRestoreWithState(type, value, tb) PyErr_Restore(type, value, tb) +#define __Pyx_ErrFetchWithState(type, value, tb) PyErr_Fetch(type, value, tb) +#define __Pyx_ErrRestoreInState(tstate, type, value, tb) PyErr_Restore(type, value, tb) +#define __Pyx_ErrFetchInState(tstate, type, value, tb) PyErr_Fetch(type, value, tb) +#define __Pyx_ErrRestore(type, value, tb) PyErr_Restore(type, value, tb) +#define __Pyx_ErrFetch(type, value, tb) PyErr_Fetch(type, value, tb) +#endif + +/* RaiseException.export */ +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); + +/* GetException.proto */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_GetException(type, value, tb) __Pyx__GetException(__pyx_tstate, type, value, tb) +static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); +#else +static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb); +#endif + +/* SwapException.proto */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_ExceptionSwap(type, value, tb) __Pyx__ExceptionSwap(__pyx_tstate, type, value, tb) +static CYTHON_INLINE void __Pyx__ExceptionSwap(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); +#else +static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb); +#endif + +/* GetTopmostException.proto (used by SaveResetException) */ +#if CYTHON_USE_EXC_INFO_STACK && CYTHON_FAST_THREAD_STATE +static _PyErr_StackItem * __Pyx_PyErr_GetTopmostException(PyThreadState *tstate); +#endif + +/* SaveResetException.proto */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_ExceptionSave(type, value, tb) __Pyx__ExceptionSave(__pyx_tstate, type, value, tb) +static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); +#define __Pyx_ExceptionReset(type, value, tb) __Pyx__ExceptionReset(__pyx_tstate, type, value, tb) +static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); +#else +#define __Pyx_ExceptionSave(type, value, tb) PyErr_GetExcInfo(type, value, tb) +#define __Pyx_ExceptionReset(type, value, tb) PyErr_SetExcInfo(type, value, tb) +#endif + +/* RejectKeywords.export */ +static void __Pyx_RejectKeywords(const char* function_name, PyObject *kwds); + +/* PyErrExceptionMatches.proto (used by GetAttr3) */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_PyErr_ExceptionMatches(err) __Pyx_PyErr_ExceptionMatchesInState(__pyx_tstate, err) +static CYTHON_INLINE int __Pyx_PyErr_ExceptionMatchesInState(PyThreadState* tstate, PyObject* err); +#else +#define __Pyx_PyErr_ExceptionMatches(err) PyErr_ExceptionMatches(err) +#endif + +/* GetAttr3.proto */ +static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *, PyObject *, PyObject *); + +/* PyObjectGetAttrStrNoError.proto (used by GetBuiltinName) */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStrNoError(PyObject* obj, PyObject* attr_name); + +/* GetBuiltinName.proto (used by GetModuleGlobalName) */ +static PyObject *__Pyx_GetBuiltinName(PyObject *name); + +/* PyDictVersioning.proto (used by GetModuleGlobalName) */ +#if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_TYPE_SLOTS +#define __PYX_DICT_VERSION_INIT ((PY_UINT64_T) -1) +#define __PYX_GET_DICT_VERSION(dict) (((PyDictObject*)(dict))->ma_version_tag) +#define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var)\ + (version_var) = __PYX_GET_DICT_VERSION(dict);\ + (cache_var) = (value); +#define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) {\ + static PY_UINT64_T __pyx_dict_version = 0;\ + static PyObject *__pyx_dict_cached_value = NULL;\ + if (likely(__PYX_GET_DICT_VERSION(DICT) == __pyx_dict_version)) {\ + (VAR) = __Pyx_XNewRef(__pyx_dict_cached_value);\ + } else {\ + (VAR) = __pyx_dict_cached_value = (LOOKUP);\ + __pyx_dict_version = __PYX_GET_DICT_VERSION(DICT);\ + }\ +} +static CYTHON_INLINE PY_UINT64_T __Pyx_get_tp_dict_version(PyObject *obj); +static CYTHON_INLINE PY_UINT64_T __Pyx_get_object_dict_version(PyObject *obj); +static CYTHON_INLINE int __Pyx_object_dict_version_matches(PyObject* obj, PY_UINT64_T tp_dict_version, PY_UINT64_T obj_dict_version); +#else +#define __PYX_GET_DICT_VERSION(dict) (0) +#define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var) +#define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) (VAR) = (LOOKUP); +#endif + +/* GetModuleGlobalName.proto */ +#if CYTHON_USE_DICT_VERSIONS +#define __Pyx_GetModuleGlobalName(var, name) do {\ + static PY_UINT64_T __pyx_dict_version = 0;\ + static PyObject *__pyx_dict_cached_value = NULL;\ + (var) = (likely(__pyx_dict_version == __PYX_GET_DICT_VERSION(__pyx_mstate_global->__pyx_d))) ?\ + (likely(__pyx_dict_cached_value) ? __Pyx_NewRef(__pyx_dict_cached_value) : __Pyx_GetBuiltinName(name)) :\ + __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\ +} while(0) +#define __Pyx_GetModuleGlobalNameUncached(var, name) do {\ + PY_UINT64_T __pyx_dict_version;\ + PyObject *__pyx_dict_cached_value;\ + (var) = __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\ +} while(0) +static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_version, PyObject **dict_cached_value); +#else +#define __Pyx_GetModuleGlobalName(var, name) (var) = __Pyx__GetModuleGlobalName(name) +#define __Pyx_GetModuleGlobalNameUncached(var, name) (var) = __Pyx__GetModuleGlobalName(name) +static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name); +#endif + +/* RaiseUnexpectedTypeError.proto */ +static int __Pyx_RaiseUnexpectedTypeError(const char *expected, PyObject *obj); + +/* ArgTypeTestFunc.export */ +static int __Pyx__ArgTypeTest(PyObject *obj, PyTypeObject *type, const char *name, int exact); + +/* ArgTypeTest.proto */ +#define __Pyx_ArgTypeTest(obj, type, none_allowed, name, exact)\ + ((likely(__Pyx_IS_TYPE(obj, type) | (none_allowed && (obj == Py_None)))) ? 1 :\ + __Pyx__ArgTypeTest(obj, type, name, exact)) + +/* GetItemInt.proto */ +#define __Pyx_GetItemInt(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck, has_gil, unsafe_shared)\ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ + __Pyx_GetItemInt_Fast(o, (Py_ssize_t)i, is_list, wraparound, boundscheck, unsafe_shared) :\ + (is_list ? (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL) :\ + __Pyx_GetItemInt_Generic(o, to_py_func(i)))) +#define __Pyx_GetItemInt_List(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck, has_gil, unsafe_shared)\ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ + __Pyx_GetItemInt_List_Fast(o, (Py_ssize_t)i, wraparound, boundscheck, unsafe_shared) :\ + (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL)) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck, int unsafe_shared); +#define __Pyx_GetItemInt_Tuple(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck, has_gil, unsafe_shared)\ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ + __Pyx_GetItemInt_Tuple_Fast(o, (Py_ssize_t)i, wraparound, boundscheck, unsafe_shared) :\ + (PyErr_SetString(PyExc_IndexError, "tuple index out of range"), (PyObject*)NULL)) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck, int unsafe_shared); +static PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j); +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, + int is_list, int wraparound, int boundscheck, int unsafe_shared); + +/* ExtTypeTest.proto */ +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); + +/* CallNextTpDealloc.proto */ +static void __Pyx_call_next_tp_dealloc(PyObject* obj, destructor current_tp_dealloc); + +/* CallNextTpTraverse.proto */ +static int __Pyx_call_next_tp_traverse(PyObject* obj, visitproc v, void *a, traverseproc current_tp_traverse); + +/* CallTypeTraverse.proto */ +#if !CYTHON_USE_TYPE_SPECS || (!CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x03090000) +#define __Pyx_call_type_traverse(o, always_call, visit, arg) 0 +#else +static int __Pyx_call_type_traverse(PyObject *o, int always_call, visitproc visit, void *arg); +#endif + +/* CallNextTpClear.proto */ +static void __Pyx_call_next_tp_clear(PyObject* obj, inquiry current_tp_clear); + +/* TypeImport.proto */ +#ifndef __PYX_HAVE_RT_ImportType_proto_3_2_4 +#define __PYX_HAVE_RT_ImportType_proto_3_2_4 +#if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 201112L +#include +#endif +#if (defined (__STDC_VERSION__) && __STDC_VERSION__ >= 201112L) || __cplusplus >= 201103L +#define __PYX_GET_STRUCT_ALIGNMENT_3_2_4(s) alignof(s) +#else +#define __PYX_GET_STRUCT_ALIGNMENT_3_2_4(s) sizeof(void*) +#endif +enum __Pyx_ImportType_CheckSize_3_2_4 { + __Pyx_ImportType_CheckSize_Error_3_2_4 = 0, + __Pyx_ImportType_CheckSize_Warn_3_2_4 = 1, + __Pyx_ImportType_CheckSize_Ignore_3_2_4 = 2 +}; +static PyTypeObject *__Pyx_ImportType_3_2_4(PyObject* module, const char *module_name, const char *class_name, size_t size, size_t alignment, enum __Pyx_ImportType_CheckSize_3_2_4 check_size); +#endif + +/* GetVTable.proto */ +static void* __Pyx_GetVtable(PyTypeObject *type); + +/* LimitedApiGetTypeDict.proto (used by SetItemOnTypeDict) */ +#if CYTHON_COMPILING_IN_LIMITED_API +static PyObject *__Pyx_GetTypeDict(PyTypeObject *tp); +#endif + +/* SetItemOnTypeDict.proto (used by FixUpExtensionType) */ +static int __Pyx__SetItemOnTypeDict(PyTypeObject *tp, PyObject *k, PyObject *v); +#define __Pyx_SetItemOnTypeDict(tp, k, v) __Pyx__SetItemOnTypeDict((PyTypeObject*)tp, k, v) + +/* FixUpExtensionType.proto */ +static CYTHON_INLINE int __Pyx_fix_up_extension_type_from_spec(PyType_Spec *spec, PyTypeObject *type); + +/* PyObjectCallNoArg.proto (used by PyObjectCallMethod0) */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func); + +/* PyObjectGetMethod.proto (used by PyObjectCallMethod0) */ +#if !(CYTHON_VECTORCALL && (__PYX_LIMITED_VERSION_HEX >= 0x030C0000 || (!CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x03090000))) +static int __Pyx_PyObject_GetMethod(PyObject *obj, PyObject *name, PyObject **method); +#endif + +/* PyObjectCallMethod0.proto (used by PyType_Ready) */ +static PyObject* __Pyx_PyObject_CallMethod0(PyObject* obj, PyObject* method_name); + +/* ValidateBasesTuple.proto (used by PyType_Ready) */ +#if CYTHON_COMPILING_IN_CPYTHON || CYTHON_COMPILING_IN_LIMITED_API || CYTHON_USE_TYPE_SPECS +static int __Pyx_validate_bases_tuple(const char *type_name, Py_ssize_t dictoffset, PyObject *bases); +#endif + +/* PyType_Ready.proto */ +CYTHON_UNUSED static int __Pyx_PyType_Ready(PyTypeObject *t); + +/* SetVTable.proto */ +static int __Pyx_SetVtable(PyTypeObject* typeptr , void* vtable); + +/* MergeVTables.proto */ +static int __Pyx_MergeVtables(PyTypeObject *type); + +/* DelItemOnTypeDict.proto (used by SetupReduce) */ +static int __Pyx__DelItemOnTypeDict(PyTypeObject *tp, PyObject *k); +#define __Pyx_DelItemOnTypeDict(tp, k) __Pyx__DelItemOnTypeDict((PyTypeObject*)tp, k) + +/* SetupReduce.proto */ +static int __Pyx_setup_reduce(PyObject* type_obj); + +/* dict_setdefault.proto (used by FetchCommonType) */ +static CYTHON_INLINE PyObject *__Pyx_PyDict_SetDefault(PyObject *d, PyObject *key, PyObject *default_value); + +/* AddModuleRef.proto (used by FetchSharedCythonModule) */ +#if ((CYTHON_COMPILING_IN_CPYTHON_FREETHREADING ) ||\ + __PYX_LIMITED_VERSION_HEX < 0x030d0000) + static PyObject *__Pyx_PyImport_AddModuleRef(const char *name); +#else + #define __Pyx_PyImport_AddModuleRef(name) PyImport_AddModuleRef(name) +#endif + +/* FetchSharedCythonModule.proto (used by FetchCommonType) */ +static PyObject *__Pyx_FetchSharedCythonABIModule(void); + +/* FetchCommonType.proto (used by CommonTypesMetaclass) */ +static PyTypeObject* __Pyx_FetchCommonTypeFromSpec(PyTypeObject *metaclass, PyObject *module, PyType_Spec *spec, PyObject *bases); + +/* CommonTypesMetaclass.proto (used by CythonFunctionShared) */ +static int __pyx_CommonTypesMetaclass_init(PyObject *module); +#define __Pyx_CommonTypesMetaclass_USED + +/* PyMethodNew.proto (used by CythonFunctionShared) */ +static PyObject *__Pyx_PyMethod_New(PyObject *func, PyObject *self, PyObject *typ); + +/* PyVectorcallFastCallDict.proto (used by CythonFunctionShared) */ +#if CYTHON_METH_FASTCALL && CYTHON_VECTORCALL +static CYTHON_INLINE PyObject *__Pyx_PyVectorcall_FastCallDict(PyObject *func, __pyx_vectorcallfunc vc, PyObject *const *args, size_t nargs, PyObject *kw); +#endif + +/* CythonFunctionShared.proto (used by CythonFunction) */ +#define __Pyx_CyFunction_USED +#define __Pyx_CYFUNCTION_STATICMETHOD 0x01 +#define __Pyx_CYFUNCTION_CLASSMETHOD 0x02 +#define __Pyx_CYFUNCTION_CCLASS 0x04 +#define __Pyx_CYFUNCTION_COROUTINE 0x08 +#define __Pyx_CyFunction_GetClosure(f)\ + (((__pyx_CyFunctionObject *) (f))->func_closure) +#if PY_VERSION_HEX < 0x030900B1 || CYTHON_COMPILING_IN_LIMITED_API + #define __Pyx_CyFunction_GetClassObj(f)\ + (((__pyx_CyFunctionObject *) (f))->func_classobj) +#else + #define __Pyx_CyFunction_GetClassObj(f)\ + ((PyObject*) ((PyCMethodObject *) (f))->mm_class) +#endif +#define __Pyx_CyFunction_SetClassObj(f, classobj)\ + __Pyx__CyFunction_SetClassObj((__pyx_CyFunctionObject *) (f), (classobj)) +#define __Pyx_CyFunction_Defaults(type, f)\ + ((type *)(((__pyx_CyFunctionObject *) (f))->defaults)) +#define __Pyx_CyFunction_SetDefaultsGetter(f, g)\ + ((__pyx_CyFunctionObject *) (f))->defaults_getter = (g) +typedef struct { +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject_HEAD + PyObject *func; +#elif PY_VERSION_HEX < 0x030900B1 + PyCFunctionObject func; +#else + PyCMethodObject func; +#endif +#if CYTHON_COMPILING_IN_LIMITED_API && CYTHON_METH_FASTCALL + __pyx_vectorcallfunc func_vectorcall; +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *func_weakreflist; +#endif +#if PY_VERSION_HEX < 0x030C0000 || CYTHON_COMPILING_IN_LIMITED_API + PyObject *func_dict; +#endif + PyObject *func_name; + PyObject *func_qualname; + PyObject *func_doc; + PyObject *func_globals; + PyObject *func_code; + PyObject *func_closure; +#if PY_VERSION_HEX < 0x030900B1 || CYTHON_COMPILING_IN_LIMITED_API + PyObject *func_classobj; +#endif + PyObject *defaults; + int flags; + PyObject *defaults_tuple; + PyObject *defaults_kwdict; + PyObject *(*defaults_getter)(PyObject *); + PyObject *func_annotations; + PyObject *func_is_coroutine; +} __pyx_CyFunctionObject; +#undef __Pyx_CyOrPyCFunction_Check +#define __Pyx_CyFunction_Check(obj) __Pyx_TypeCheck(obj, __pyx_mstate_global->__pyx_CyFunctionType) +#define __Pyx_CyOrPyCFunction_Check(obj) __Pyx_TypeCheck2(obj, __pyx_mstate_global->__pyx_CyFunctionType, &PyCFunction_Type) +#define __Pyx_CyFunction_CheckExact(obj) __Pyx_IS_TYPE(obj, __pyx_mstate_global->__pyx_CyFunctionType) +static CYTHON_INLINE int __Pyx__IsSameCyOrCFunction(PyObject *func, void (*cfunc)(void)); +#undef __Pyx_IsSameCFunction +#define __Pyx_IsSameCFunction(func, cfunc) __Pyx__IsSameCyOrCFunction(func, cfunc) +static PyObject *__Pyx_CyFunction_Init(__pyx_CyFunctionObject* op, PyMethodDef *ml, + int flags, PyObject* qualname, + PyObject *closure, + PyObject *module, PyObject *globals, + PyObject* code); +static CYTHON_INLINE void __Pyx__CyFunction_SetClassObj(__pyx_CyFunctionObject* f, PyObject* classobj); +static CYTHON_INLINE PyObject *__Pyx_CyFunction_InitDefaults(PyObject *func, + PyTypeObject *defaults_type); +static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsTuple(PyObject *m, + PyObject *tuple); +static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsKwDict(PyObject *m, + PyObject *dict); +static CYTHON_INLINE void __Pyx_CyFunction_SetAnnotationsDict(PyObject *m, + PyObject *dict); +static int __pyx_CyFunction_init(PyObject *module); +#if CYTHON_METH_FASTCALL +static PyObject * __Pyx_CyFunction_Vectorcall_NOARGS(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames); +static PyObject * __Pyx_CyFunction_Vectorcall_O(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames); +static PyObject * __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames); +static PyObject * __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS_METHOD(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames); +#if CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_CyFunction_func_vectorcall(f) (((__pyx_CyFunctionObject*)f)->func_vectorcall) +#else +#define __Pyx_CyFunction_func_vectorcall(f) (((PyCFunctionObject*)f)->vectorcall) +#endif +#endif + +/* CythonFunction.proto */ +static PyObject *__Pyx_CyFunction_New(PyMethodDef *ml, + int flags, PyObject* qualname, + PyObject *closure, + PyObject *module, PyObject *globals, + PyObject* code); + +/* CLineInTraceback.proto (used by AddTraceback) */ +#if CYTHON_CLINE_IN_TRACEBACK && CYTHON_CLINE_IN_TRACEBACK_RUNTIME +static int __Pyx_CLineForTraceback(PyThreadState *tstate, int c_line); +#else +#define __Pyx_CLineForTraceback(tstate, c_line) (((CYTHON_CLINE_IN_TRACEBACK)) ? c_line : 0) +#endif + +/* CodeObjectCache.proto (used by AddTraceback) */ +#if CYTHON_COMPILING_IN_LIMITED_API +typedef PyObject __Pyx_CachedCodeObjectType; +#else +typedef PyCodeObject __Pyx_CachedCodeObjectType; +#endif +typedef struct { + __Pyx_CachedCodeObjectType* code_object; + int code_line; +} __Pyx_CodeObjectCacheEntry; +struct __Pyx_CodeObjectCache { + int count; + int max_count; + __Pyx_CodeObjectCacheEntry* entries; + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + __pyx_atomic_int_type accessor_count; + #endif +}; +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); +static __Pyx_CachedCodeObjectType *__pyx_find_code_object(int code_line); +static void __pyx_insert_code_object(int code_line, __Pyx_CachedCodeObjectType* code_object); + +/* AddTraceback.proto */ +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename); + +/* CheckUnpickleChecksum.proto */ +static CYTHON_INLINE int __Pyx_CheckUnpickleChecksum(long checksum, long checksum1, long checksum2, long checksum3, const char *members); + +/* GCCDiagnostics.proto */ +#if !defined(__INTEL_COMPILER) && defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) +#define __Pyx_HAS_GCC_DIAGNOSTIC +#endif + +/* CIntFromPy.proto */ +static CYTHON_INLINE int __Pyx_PyLong_As_int(PyObject *); + +/* CIntFromPy.proto */ +static CYTHON_INLINE long __Pyx_PyLong_As_long(PyObject *); + +/* PyObjectVectorCallKwBuilder.proto (used by CIntToPy) */ +CYTHON_UNUSED static int __Pyx_VectorcallBuilder_AddArg_Check(PyObject *key, PyObject *value, PyObject *builder, PyObject **args, int n); +#if CYTHON_VECTORCALL +#if PY_VERSION_HEX >= 0x03090000 +#define __Pyx_Object_Vectorcall_CallFromBuilder PyObject_Vectorcall +#else +#define __Pyx_Object_Vectorcall_CallFromBuilder _PyObject_Vectorcall +#endif +#define __Pyx_MakeVectorcallBuilderKwds(n) PyTuple_New(n) +static int __Pyx_VectorcallBuilder_AddArg(PyObject *key, PyObject *value, PyObject *builder, PyObject **args, int n); +static int __Pyx_VectorcallBuilder_AddArgStr(const char *key, PyObject *value, PyObject *builder, PyObject **args, int n); +#else +#define __Pyx_Object_Vectorcall_CallFromBuilder __Pyx_PyObject_FastCallDict +#define __Pyx_MakeVectorcallBuilderKwds(n) __Pyx_PyDict_NewPresized(n) +#define __Pyx_VectorcallBuilder_AddArg(key, value, builder, args, n) PyDict_SetItem(builder, key, value) +#define __Pyx_VectorcallBuilder_AddArgStr(key, value, builder, args, n) PyDict_SetItemString(builder, key, value) +#endif + +/* CIntToPy.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyLong_From_int(int value); + +/* CIntToPy.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyLong_From_long(long value); + +/* PyObjectCall2Args.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call2Args(PyObject* function, PyObject* arg1, PyObject* arg2); + +/* PyObjectCallMethod1.proto */ +static PyObject* __Pyx_PyObject_CallMethod1(PyObject* obj, PyObject* method_name, PyObject* arg); + +/* UpdateUnpickledDict.proto */ +static int __Pyx_UpdateUnpickledDict(PyObject *obj, PyObject *state, Py_ssize_t index); + +/* FormatTypeName.proto */ +#if CYTHON_COMPILING_IN_LIMITED_API +typedef PyObject *__Pyx_TypeName; +#define __Pyx_FMT_TYPENAME "%U" +#define __Pyx_DECREF_TypeName(obj) Py_XDECREF(obj) +#if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 +#define __Pyx_PyType_GetFullyQualifiedName PyType_GetFullyQualifiedName +#else +static __Pyx_TypeName __Pyx_PyType_GetFullyQualifiedName(PyTypeObject* tp); +#endif +#else // !LIMITED_API +typedef const char *__Pyx_TypeName; +#define __Pyx_FMT_TYPENAME "%.200s" +#define __Pyx_PyType_GetFullyQualifiedName(tp) ((tp)->tp_name) +#define __Pyx_DECREF_TypeName(obj) +#endif + +/* FastTypeChecks.proto */ +#if CYTHON_COMPILING_IN_CPYTHON +#define __Pyx_TypeCheck(obj, type) __Pyx_IsSubtype(Py_TYPE(obj), (PyTypeObject *)type) +#define __Pyx_TypeCheck2(obj, type1, type2) __Pyx_IsAnySubtype2(Py_TYPE(obj), (PyTypeObject *)type1, (PyTypeObject *)type2) +static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b); +static CYTHON_INLINE int __Pyx_IsAnySubtype2(PyTypeObject *cls, PyTypeObject *a, PyTypeObject *b); +static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches(PyObject *err, PyObject *type); +static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches2(PyObject *err, PyObject *type1, PyObject *type2); +#else +#define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) +#define __Pyx_TypeCheck2(obj, type1, type2) (PyObject_TypeCheck(obj, (PyTypeObject *)type1) || PyObject_TypeCheck(obj, (PyTypeObject *)type2)) +#define __Pyx_PyErr_GivenExceptionMatches(err, type) PyErr_GivenExceptionMatches(err, type) +static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches2(PyObject *err, PyObject *type1, PyObject *type2) { + return PyErr_GivenExceptionMatches(err, type1) || PyErr_GivenExceptionMatches(err, type2); +} +#endif +#define __Pyx_PyErr_ExceptionMatches2(err1, err2) __Pyx_PyErr_GivenExceptionMatches2(__Pyx_PyErr_CurrentExceptionType(), err1, err2) +#define __Pyx_PyException_Check(obj) __Pyx_TypeCheck(obj, PyExc_Exception) +#ifdef PyExceptionInstance_Check + #define __Pyx_PyBaseException_Check(obj) PyExceptionInstance_Check(obj) +#else + #define __Pyx_PyBaseException_Check(obj) __Pyx_TypeCheck(obj, PyExc_BaseException) +#endif + +/* GetRuntimeVersion.proto */ +#if __PYX_LIMITED_VERSION_HEX < 0x030b0000 +static unsigned long __Pyx_cached_runtime_version = 0; +static void __Pyx_init_runtime_version(void); +#else +#define __Pyx_init_runtime_version() +#endif +static unsigned long __Pyx_get_runtime_version(void); + +/* CheckBinaryVersion.proto */ +static int __Pyx_check_binary_version(unsigned long ct_version, unsigned long rt_version, int allow_newer); + +/* DecompressString.proto */ +static PyObject *__Pyx_DecompressString(const char *s, Py_ssize_t length, int algo); + +/* MultiPhaseInitModuleState.proto */ +#if CYTHON_PEP489_MULTI_PHASE_INIT && CYTHON_USE_MODULE_STATE +static PyObject *__Pyx_State_FindModule(void*); +static int __Pyx_State_AddModule(PyObject* module, void*); +static int __Pyx_State_RemoveModule(void*); +#elif CYTHON_USE_MODULE_STATE +#define __Pyx_State_FindModule PyState_FindModule +#define __Pyx_State_AddModule PyState_AddModule +#define __Pyx_State_RemoveModule PyState_RemoveModule +#endif + +/* #### Code section: module_declarations ### */ +/* CythonABIVersion.proto */ +#if CYTHON_COMPILING_IN_LIMITED_API + #if CYTHON_METH_FASTCALL + #define __PYX_FASTCALL_ABI_SUFFIX "_fastcall" + #else + #define __PYX_FASTCALL_ABI_SUFFIX + #endif + #define __PYX_LIMITED_ABI_SUFFIX "limited" __PYX_FASTCALL_ABI_SUFFIX __PYX_AM_SEND_ABI_SUFFIX +#else + #define __PYX_LIMITED_ABI_SUFFIX +#endif +#if __PYX_HAS_PY_AM_SEND == 1 + #define __PYX_AM_SEND_ABI_SUFFIX +#elif __PYX_HAS_PY_AM_SEND == 2 + #define __PYX_AM_SEND_ABI_SUFFIX "amsendbackport" +#else + #define __PYX_AM_SEND_ABI_SUFFIX "noamsend" +#endif +#ifndef __PYX_MONITORING_ABI_SUFFIX + #define __PYX_MONITORING_ABI_SUFFIX +#endif +#if CYTHON_USE_TP_FINALIZE + #define __PYX_TP_FINALIZE_ABI_SUFFIX +#else + #define __PYX_TP_FINALIZE_ABI_SUFFIX "nofinalize" +#endif +#if CYTHON_USE_FREELISTS || !defined(__Pyx_AsyncGen_USED) + #define __PYX_FREELISTS_ABI_SUFFIX +#else + #define __PYX_FREELISTS_ABI_SUFFIX "nofreelists" +#endif +#define CYTHON_ABI __PYX_ABI_VERSION __PYX_LIMITED_ABI_SUFFIX __PYX_MONITORING_ABI_SUFFIX __PYX_TP_FINALIZE_ABI_SUFFIX __PYX_FREELISTS_ABI_SUFFIX __PYX_AM_SEND_ABI_SUFFIX +#define __PYX_ABI_MODULE_NAME "_cython_" CYTHON_ABI +#define __PYX_TYPE_MODULE_PREFIX __PYX_ABI_MODULE_NAME "." + +static PyObject *__pyx_f_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_c_read(struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *__pyx_v_self, int __pyx_v_sz, char *__pyx_v_out); /* proto*/ +static PyObject *__pyx_f_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_c_write(struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *__pyx_v_self, char const *__pyx_v_data, int __pyx_v_sz); /* proto*/ +static PyObject *__pyx_f_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer__getvalue(struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *__pyx_v_self); /* proto*/ +static PyObject *__pyx_f_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer__setvalue(struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *__pyx_v_self, int __pyx_v_sz, char const *__pyx_v_value); /* proto*/ + +/* Module declarations from "libc.string" */ + +/* Module declarations from "libc.stdlib" */ + +/* Module declarations from "thriftpy2.transport.cybase" */ + +/* Module declarations from "thriftpy2.transport.memory.cymemory" */ +static PyObject *__pyx_f_9thriftpy2_9transport_6memory_8cymemory___pyx_unpickle_TCyMemoryBuffer__set_state(struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *, PyObject *); /*proto*/ +/* #### Code section: typeinfo ### */ +/* #### Code section: before_global_var ### */ +#define __Pyx_MODULE_NAME "thriftpy2.transport.memory.cymemory" +extern int __pyx_module_is_main_thriftpy2__transport__memory__cymemory; +int __pyx_module_is_main_thriftpy2__transport__memory__cymemory = 0; + +/* Implementation of "thriftpy2.transport.memory.cymemory" */ +/* #### Code section: global_var ### */ +/* #### Code section: string_decls ### */ +static const char __pyx_k_buf_trans[] = "buf, trans"; +/* #### Code section: decls ### */ +static int __pyx_pf_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer___init__(struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *__pyx_v_self, PyObject *__pyx_v_value, int __pyx_v_buf_size); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_2read(struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *__pyx_v_self, PyObject *__pyx_v_sz); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_4write(struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *__pyx_v_self, PyObject *__pyx_v_data); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_6is_open(CYTHON_UNUSED struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_8open(CYTHON_UNUSED struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_10close(CYTHON_UNUSED struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_12flush(CYTHON_UNUSED struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_14clean(struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_16getvalue(struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_18setvalue(struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *__pyx_v_self, PyObject *__pyx_v_value); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_20__reduce_cython__(struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_22__setstate_cython__(struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *__pyx_v_self, PyObject *__pyx_v___pyx_state); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_9transport_6memory_8cymemory___pyx_unpickle_TCyMemoryBuffer(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v___pyx_type, long __pyx_v___pyx_checksum, PyObject *__pyx_v___pyx_state); /* proto */ +static PyObject *__pyx_tp_new_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +/* #### Code section: late_includes ### */ +/* #### Code section: module_state ### */ +/* SmallCodeConfig */ +#ifndef CYTHON_SMALL_CODE +#if defined(__clang__) + #define CYTHON_SMALL_CODE +#elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) + #define CYTHON_SMALL_CODE __attribute__((cold)) +#else + #define CYTHON_SMALL_CODE +#endif +#endif + +typedef struct { + PyObject *__pyx_d; + PyObject *__pyx_b; + PyObject *__pyx_cython_runtime; + PyObject *__pyx_empty_tuple; + PyObject *__pyx_empty_bytes; + PyObject *__pyx_empty_unicode; + PyTypeObject *__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer; + PyTypeObject *__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase; + PyObject *__pyx_type_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer; + PyTypeObject *__pyx_ptype_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer; + __Pyx_CachedCFunction __pyx_umethod_PyDict_Type_items; + __Pyx_CachedCFunction __pyx_umethod_PyDict_Type_pop; + __Pyx_CachedCFunction __pyx_umethod_PyDict_Type_values; + int __pyx_k__2; + PyObject *__pyx_codeobj_tab[12]; + PyObject *__pyx_string_tab[81]; + PyObject *__pyx_number_tab[1]; +/* #### Code section: module_state_contents ### */ +/* CommonTypesMetaclass.module_state_decls */ +PyTypeObject *__pyx_CommonTypesMetaclassType; + +/* CachedMethodType.module_state_decls */ +#if CYTHON_COMPILING_IN_LIMITED_API +PyObject *__Pyx_CachedMethodType; +#endif + +/* CythonFunctionShared.module_state_decls */ +PyTypeObject *__pyx_CyFunctionType; + +/* CodeObjectCache.module_state_decls */ +struct __Pyx_CodeObjectCache __pyx_code_cache; + +/* #### Code section: module_state_end ### */ +} __pyx_mstatetype; + +#if CYTHON_USE_MODULE_STATE +#ifdef __cplusplus +namespace { +extern struct PyModuleDef __pyx_moduledef; +} /* anonymous namespace */ +#else +static struct PyModuleDef __pyx_moduledef; +#endif + +#define __pyx_mstate_global (__Pyx_PyModule_GetState(__Pyx_State_FindModule(&__pyx_moduledef))) + +#define __pyx_m (__Pyx_State_FindModule(&__pyx_moduledef)) +#else +static __pyx_mstatetype __pyx_mstate_global_static = +#ifdef __cplusplus + {}; +#else + {0}; +#endif +static __pyx_mstatetype * const __pyx_mstate_global = &__pyx_mstate_global_static; +#endif +/* #### Code section: constant_name_defines ### */ +#define __pyx_kp_u_Note_that_Cython_is_deliberately __pyx_string_tab[0] +#define __pyx_kp_u_Write_to_memory_error __pyx_string_tab[1] +#define __pyx_kp_u__3 __pyx_string_tab[2] +#define __pyx_kp_u_add_note __pyx_string_tab[3] +#define __pyx_kp_u_disable __pyx_string_tab[4] +#define __pyx_kp_u_enable __pyx_string_tab[5] +#define __pyx_kp_u_gc __pyx_string_tab[6] +#define __pyx_kp_u_isenabled __pyx_string_tab[7] +#define __pyx_kp_u_stringsource __pyx_string_tab[8] +#define __pyx_kp_u_thriftpy2_transport_memory_cymem_2 __pyx_string_tab[9] +#define __pyx_n_u_Pyx_PyDict_NextRef __pyx_string_tab[10] +#define __pyx_n_u_TCyMemoryBuffer __pyx_string_tab[11] +#define __pyx_n_u_TCyMemoryBuffer___reduce_cython __pyx_string_tab[12] +#define __pyx_n_u_TCyMemoryBuffer___setstate_cytho __pyx_string_tab[13] +#define __pyx_n_u_TCyMemoryBuffer_clean __pyx_string_tab[14] +#define __pyx_n_u_TCyMemoryBuffer_close __pyx_string_tab[15] +#define __pyx_n_u_TCyMemoryBuffer_flush __pyx_string_tab[16] +#define __pyx_n_u_TCyMemoryBuffer_getvalue __pyx_string_tab[17] +#define __pyx_n_u_TCyMemoryBuffer_is_open __pyx_string_tab[18] +#define __pyx_n_u_TCyMemoryBuffer_open __pyx_string_tab[19] +#define __pyx_n_u_TCyMemoryBuffer_read __pyx_string_tab[20] +#define __pyx_n_u_TCyMemoryBuffer_setvalue __pyx_string_tab[21] +#define __pyx_n_u_TCyMemoryBuffer_write __pyx_string_tab[22] +#define __pyx_n_u_asyncio_coroutines __pyx_string_tab[23] +#define __pyx_n_u_buf_size __pyx_string_tab[24] +#define __pyx_n_u_clean __pyx_string_tab[25] +#define __pyx_n_u_cline_in_traceback __pyx_string_tab[26] +#define __pyx_n_u_close __pyx_string_tab[27] +#define __pyx_n_u_data __pyx_string_tab[28] +#define __pyx_n_u_dict __pyx_string_tab[29] +#define __pyx_n_u_dict_2 __pyx_string_tab[30] +#define __pyx_n_u_flush __pyx_string_tab[31] +#define __pyx_n_u_func __pyx_string_tab[32] +#define __pyx_n_u_getstate __pyx_string_tab[33] +#define __pyx_n_u_getvalue __pyx_string_tab[34] +#define __pyx_n_u_is_coroutine __pyx_string_tab[35] +#define __pyx_n_u_is_open __pyx_string_tab[36] +#define __pyx_n_u_items __pyx_string_tab[37] +#define __pyx_n_u_main __pyx_string_tab[38] +#define __pyx_n_u_module __pyx_string_tab[39] +#define __pyx_n_u_name __pyx_string_tab[40] +#define __pyx_n_u_new __pyx_string_tab[41] +#define __pyx_n_u_open __pyx_string_tab[42] +#define __pyx_n_u_pop __pyx_string_tab[43] +#define __pyx_n_u_pyx_checksum __pyx_string_tab[44] +#define __pyx_n_u_pyx_result __pyx_string_tab[45] +#define __pyx_n_u_pyx_state __pyx_string_tab[46] +#define __pyx_n_u_pyx_type __pyx_string_tab[47] +#define __pyx_n_u_pyx_unpickle_TCyMemoryBuffer __pyx_string_tab[48] +#define __pyx_n_u_pyx_vtable __pyx_string_tab[49] +#define __pyx_n_u_qualname __pyx_string_tab[50] +#define __pyx_n_u_read __pyx_string_tab[51] +#define __pyx_n_u_reduce __pyx_string_tab[52] +#define __pyx_n_u_reduce_cython __pyx_string_tab[53] +#define __pyx_n_u_reduce_ex __pyx_string_tab[54] +#define __pyx_n_u_self __pyx_string_tab[55] +#define __pyx_n_u_set_name __pyx_string_tab[56] +#define __pyx_n_u_setdefault __pyx_string_tab[57] +#define __pyx_n_u_setstate __pyx_string_tab[58] +#define __pyx_n_u_setstate_cython __pyx_string_tab[59] +#define __pyx_n_u_setvalue __pyx_string_tab[60] +#define __pyx_n_u_state __pyx_string_tab[61] +#define __pyx_n_u_sz __pyx_string_tab[62] +#define __pyx_n_u_test __pyx_string_tab[63] +#define __pyx_n_u_thriftpy2_transport_memory_cymem __pyx_string_tab[64] +#define __pyx_n_u_update __pyx_string_tab[65] +#define __pyx_n_u_use_setstate __pyx_string_tab[66] +#define __pyx_n_u_value __pyx_string_tab[67] +#define __pyx_n_u_values __pyx_string_tab[68] +#define __pyx_n_u_write __pyx_string_tab[69] +#define __pyx_kp_b_ __pyx_string_tab[70] +#define __pyx_kp_b_iso88591_A __pyx_string_tab[71] +#define __pyx_kp_b_iso88591_A_D_a __pyx_string_tab[72] +#define __pyx_kp_b_iso88591_A_QfA_IU_c_t81F __pyx_string_tab[73] +#define __pyx_kp_b_iso88591_A_QgQ_YfG1A_Jas_81 __pyx_string_tab[74] +#define __pyx_kp_b_iso88591_A_q __pyx_string_tab[75] +#define __pyx_kp_b_iso88591_A_t_Q __pyx_string_tab[76] +#define __pyx_kp_b_iso88591_A_t_aq __pyx_string_tab[77] +#define __pyx_kp_b_iso88591_QfA __pyx_string_tab[78] +#define __pyx_kp_b_iso88591_T_t1_G1F_a_vWE_Q_q_t5_uCt7_q_0 __pyx_string_tab[79] +#define __pyx_kp_b_iso88591_q_0_kQR_1_7_1_2DNRS_1 __pyx_string_tab[80] +#define __pyx_int_157935663 __pyx_number_tab[0] +/* #### Code section: module_state_clear ### */ +#if CYTHON_USE_MODULE_STATE +static CYTHON_SMALL_CODE int __pyx_m_clear(PyObject *m) { + __pyx_mstatetype *clear_module_state = __Pyx_PyModule_GetState(m); + if (!clear_module_state) return 0; + Py_CLEAR(clear_module_state->__pyx_d); + Py_CLEAR(clear_module_state->__pyx_b); + Py_CLEAR(clear_module_state->__pyx_cython_runtime); + Py_CLEAR(clear_module_state->__pyx_empty_tuple); + Py_CLEAR(clear_module_state->__pyx_empty_bytes); + Py_CLEAR(clear_module_state->__pyx_empty_unicode); + #if CYTHON_PEP489_MULTI_PHASE_INIT + __Pyx_State_RemoveModule(NULL); + #endif + Py_CLEAR(clear_module_state->__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer); + Py_CLEAR(clear_module_state->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase); + Py_CLEAR(clear_module_state->__pyx_ptype_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer); + Py_CLEAR(clear_module_state->__pyx_type_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer); + for (int i=0; i<12; ++i) { Py_CLEAR(clear_module_state->__pyx_codeobj_tab[i]); } + for (int i=0; i<81; ++i) { Py_CLEAR(clear_module_state->__pyx_string_tab[i]); } + for (int i=0; i<1; ++i) { Py_CLEAR(clear_module_state->__pyx_number_tab[i]); } +/* #### Code section: module_state_clear_contents ### */ +/* CommonTypesMetaclass.module_state_clear */ +Py_CLEAR(clear_module_state->__pyx_CommonTypesMetaclassType); + +/* CythonFunctionShared.module_state_clear */ +Py_CLEAR(clear_module_state->__pyx_CyFunctionType); + +/* #### Code section: module_state_clear_end ### */ +return 0; +} +#endif +/* #### Code section: module_state_traverse ### */ +#if CYTHON_USE_MODULE_STATE +static CYTHON_SMALL_CODE int __pyx_m_traverse(PyObject *m, visitproc visit, void *arg) { + __pyx_mstatetype *traverse_module_state = __Pyx_PyModule_GetState(m); + if (!traverse_module_state) return 0; + Py_VISIT(traverse_module_state->__pyx_d); + Py_VISIT(traverse_module_state->__pyx_b); + Py_VISIT(traverse_module_state->__pyx_cython_runtime); + __Pyx_VISIT_CONST(traverse_module_state->__pyx_empty_tuple); + __Pyx_VISIT_CONST(traverse_module_state->__pyx_empty_bytes); + __Pyx_VISIT_CONST(traverse_module_state->__pyx_empty_unicode); + Py_VISIT(traverse_module_state->__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer); + Py_VISIT(traverse_module_state->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase); + Py_VISIT(traverse_module_state->__pyx_ptype_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer); + Py_VISIT(traverse_module_state->__pyx_type_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer); + for (int i=0; i<12; ++i) { __Pyx_VISIT_CONST(traverse_module_state->__pyx_codeobj_tab[i]); } + for (int i=0; i<81; ++i) { __Pyx_VISIT_CONST(traverse_module_state->__pyx_string_tab[i]); } + for (int i=0; i<1; ++i) { __Pyx_VISIT_CONST(traverse_module_state->__pyx_number_tab[i]); } +/* #### Code section: module_state_traverse_contents ### */ +/* CommonTypesMetaclass.module_state_traverse */ +Py_VISIT(traverse_module_state->__pyx_CommonTypesMetaclassType); + +/* CythonFunctionShared.module_state_traverse */ +Py_VISIT(traverse_module_state->__pyx_CyFunctionType); + +/* #### Code section: module_state_traverse_end ### */ +return 0; +} +#endif +/* #### Code section: module_code ### */ + +/* "thriftpy2/transport/memory/cymemory.pyx":15 + * cdef TCyBuffer buf + * + * def __init__(self, value=b'', int buf_size=DEFAULT_BUFFER): # <<<<<<<<<<<<<< + * self.trans = None + * self.buf = TCyBuffer(buf_size) +*/ + +/* Python wrapper */ +static int __pyx_pw_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_value = 0; + int __pyx_v_buf_size; + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[2] = {0,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return -1; + #endif + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_value,&__pyx_mstate_global->__pyx_n_u_buf_size,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_VARARGS(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 15, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 2: + values[1] = __Pyx_ArgRef_VARARGS(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 15, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_VARARGS(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 15, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "__init__", 0) < (0)) __PYX_ERR(0, 15, __pyx_L3_error) + if (!values[0]) values[0] = __Pyx_NewRef(((PyObject *)__pyx_mstate_global->__pyx_kp_b_)); + } else { + switch (__pyx_nargs) { + case 2: + values[1] = __Pyx_ArgRef_VARARGS(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 15, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_VARARGS(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 15, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + if (!values[0]) values[0] = __Pyx_NewRef(((PyObject *)__pyx_mstate_global->__pyx_kp_b_)); + } + __pyx_v_value = values[0]; + if (values[1]) { + __pyx_v_buf_size = __Pyx_PyLong_As_int(values[1]); if (unlikely((__pyx_v_buf_size == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 15, __pyx_L3_error) + } else { + __pyx_v_buf_size = __pyx_mstate_global->__pyx_k__2; + } + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__init__", 0, 0, 2, __pyx_nargs); __PYX_ERR(0, 15, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("thriftpy2.transport.memory.cymemory.TCyMemoryBuffer.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer___init__(((struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *)__pyx_v_self), __pyx_v_value, __pyx_v_buf_size); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer___init__(struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *__pyx_v_self, PyObject *__pyx_v_value, int __pyx_v_buf_size) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + size_t __pyx_t_4; + int __pyx_t_5; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__init__", 0); + + /* "thriftpy2/transport/memory/cymemory.pyx":16 + * + * def __init__(self, value=b'', int buf_size=DEFAULT_BUFFER): + * self.trans = None # <<<<<<<<<<<<<< + * self.buf = TCyBuffer(buf_size) + * +*/ + __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(Py_None); + __Pyx_GOTREF(__pyx_v_self->__pyx_base.trans); + __Pyx_DECREF(__pyx_v_self->__pyx_base.trans); + __pyx_v_self->__pyx_base.trans = Py_None; + + /* "thriftpy2/transport/memory/cymemory.pyx":17 + * def __init__(self, value=b'', int buf_size=DEFAULT_BUFFER): + * self.trans = None + * self.buf = TCyBuffer(buf_size) # <<<<<<<<<<<<<< + * + * if value: +*/ + __pyx_t_2 = NULL; + __pyx_t_3 = __Pyx_PyLong_From_int(__pyx_v_buf_size); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 17, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, __pyx_t_3}; + __pyx_t_1 = __Pyx_PyObject_FastCall((PyObject*)__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer, __pyx_callargs+__pyx_t_4, (2-__pyx_t_4) | (__pyx_t_4*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 17, __pyx_L1_error) + __Pyx_GOTREF((PyObject *)__pyx_t_1); + } + __Pyx_GIVEREF((PyObject *)__pyx_t_1); + __Pyx_GOTREF((PyObject *)__pyx_v_self->buf); + __Pyx_DECREF((PyObject *)__pyx_v_self->buf); + __pyx_v_self->buf = ((struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "thriftpy2/transport/memory/cymemory.pyx":19 + * self.buf = TCyBuffer(buf_size) + * + * if value: # <<<<<<<<<<<<<< + * self.setvalue(value) + * +*/ + __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_v_value); if (unlikely((__pyx_t_5 < 0))) __PYX_ERR(0, 19, __pyx_L1_error) + if (__pyx_t_5) { + + /* "thriftpy2/transport/memory/cymemory.pyx":20 + * + * if value: + * self.setvalue(value) # <<<<<<<<<<<<<< + * + * cdef c_read(self, int sz, char* out): +*/ + __pyx_t_3 = ((PyObject *)__pyx_v_self); + __Pyx_INCREF(__pyx_t_3); + __pyx_t_4 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_v_value}; + __pyx_t_1 = __Pyx_PyObject_FastCallMethod((PyObject*)__pyx_mstate_global->__pyx_n_u_setvalue, __pyx_callargs+__pyx_t_4, (2-__pyx_t_4) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 20, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "thriftpy2/transport/memory/cymemory.pyx":19 + * self.buf = TCyBuffer(buf_size) + * + * if value: # <<<<<<<<<<<<<< + * self.setvalue(value) + * +*/ + } + + /* "thriftpy2/transport/memory/cymemory.pyx":15 + * cdef TCyBuffer buf + * + * def __init__(self, value=b'', int buf_size=DEFAULT_BUFFER): # <<<<<<<<<<<<<< + * self.trans = None + * self.buf = TCyBuffer(buf_size) +*/ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("thriftpy2.transport.memory.cymemory.TCyMemoryBuffer.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/memory/cymemory.pyx":22 + * self.setvalue(value) + * + * cdef c_read(self, int sz, char* out): # <<<<<<<<<<<<<< + * if self.buf.data_size < sz: + * sz = self.buf.data_size +*/ + +static PyObject *__pyx_f_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_c_read(struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *__pyx_v_self, int __pyx_v_sz, char *__pyx_v_out) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("c_read", 0); + + /* "thriftpy2/transport/memory/cymemory.pyx":23 + * + * cdef c_read(self, int sz, char* out): + * if self.buf.data_size < sz: # <<<<<<<<<<<<<< + * sz = self.buf.data_size + * +*/ + __pyx_t_1 = (__pyx_v_self->buf->data_size < __pyx_v_sz); + if (__pyx_t_1) { + + /* "thriftpy2/transport/memory/cymemory.pyx":24 + * cdef c_read(self, int sz, char* out): + * if self.buf.data_size < sz: + * sz = self.buf.data_size # <<<<<<<<<<<<<< + * + * if sz <= 0: +*/ + __pyx_t_2 = __pyx_v_self->buf->data_size; + __pyx_v_sz = __pyx_t_2; + + /* "thriftpy2/transport/memory/cymemory.pyx":23 + * + * cdef c_read(self, int sz, char* out): + * if self.buf.data_size < sz: # <<<<<<<<<<<<<< + * sz = self.buf.data_size + * +*/ + } + + /* "thriftpy2/transport/memory/cymemory.pyx":26 + * sz = self.buf.data_size + * + * if sz <= 0: # <<<<<<<<<<<<<< + * out[0] = '\0' + * else: +*/ + __pyx_t_1 = (__pyx_v_sz <= 0); + if (__pyx_t_1) { + + /* "thriftpy2/transport/memory/cymemory.pyx":27 + * + * if sz <= 0: + * out[0] = '\0' # <<<<<<<<<<<<<< + * else: + * memcpy(out, self.buf.buf + self.buf.cur, sz) +*/ + (__pyx_v_out[0]) = '\x00'; + + /* "thriftpy2/transport/memory/cymemory.pyx":26 + * sz = self.buf.data_size + * + * if sz <= 0: # <<<<<<<<<<<<<< + * out[0] = '\0' + * else: +*/ + goto __pyx_L4; + } + + /* "thriftpy2/transport/memory/cymemory.pyx":29 + * out[0] = '\0' + * else: + * memcpy(out, self.buf.buf + self.buf.cur, sz) # <<<<<<<<<<<<<< + * self.buf.cur += sz + * self.buf.data_size -= sz +*/ + /*else*/ { + (void)(memcpy(__pyx_v_out, (__pyx_v_self->buf->buf + __pyx_v_self->buf->cur), __pyx_v_sz)); + + /* "thriftpy2/transport/memory/cymemory.pyx":30 + * else: + * memcpy(out, self.buf.buf + self.buf.cur, sz) + * self.buf.cur += sz # <<<<<<<<<<<<<< + * self.buf.data_size -= sz + * +*/ + __pyx_v_self->buf->cur = (__pyx_v_self->buf->cur + __pyx_v_sz); + + /* "thriftpy2/transport/memory/cymemory.pyx":31 + * memcpy(out, self.buf.buf + self.buf.cur, sz) + * self.buf.cur += sz + * self.buf.data_size -= sz # <<<<<<<<<<<<<< + * + * return sz +*/ + __pyx_v_self->buf->data_size = (__pyx_v_self->buf->data_size - __pyx_v_sz); + } + __pyx_L4:; + + /* "thriftpy2/transport/memory/cymemory.pyx":33 + * self.buf.data_size -= sz + * + * return sz # <<<<<<<<<<<<<< + * + * cdef c_write(self, const char* data, int sz): +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_3 = __Pyx_PyLong_From_int(__pyx_v_sz); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 33, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + + /* "thriftpy2/transport/memory/cymemory.pyx":22 + * self.setvalue(value) + * + * cdef c_read(self, int sz, char* out): # <<<<<<<<<<<<<< + * if self.buf.data_size < sz: + * sz = self.buf.data_size +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("thriftpy2.transport.memory.cymemory.TCyMemoryBuffer.c_read", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/memory/cymemory.pyx":35 + * return sz + * + * cdef c_write(self, const char* data, int sz): # <<<<<<<<<<<<<< + * cdef int r = self.buf.write(sz, data) + * if r == -1: +*/ + +static PyObject *__pyx_f_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_c_write(struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *__pyx_v_self, char const *__pyx_v_data, int __pyx_v_sz) { + int __pyx_v_r; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + size_t __pyx_t_5; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("c_write", 0); + + /* "thriftpy2/transport/memory/cymemory.pyx":36 + * + * cdef c_write(self, const char* data, int sz): + * cdef int r = self.buf.write(sz, data) # <<<<<<<<<<<<<< + * if r == -1: + * raise MemoryError("Write to memory error") +*/ + __pyx_t_1 = ((struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_TCyBuffer *)__pyx_v_self->buf->__pyx_vtab)->write(__pyx_v_self->buf, __pyx_v_sz, __pyx_v_data); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 36, __pyx_L1_error) + __pyx_v_r = __pyx_t_1; + + /* "thriftpy2/transport/memory/cymemory.pyx":37 + * cdef c_write(self, const char* data, int sz): + * cdef int r = self.buf.write(sz, data) + * if r == -1: # <<<<<<<<<<<<<< + * raise MemoryError("Write to memory error") + * +*/ + __pyx_t_2 = (__pyx_v_r == -1L); + if (unlikely(__pyx_t_2)) { + + /* "thriftpy2/transport/memory/cymemory.pyx":38 + * cdef int r = self.buf.write(sz, data) + * if r == -1: + * raise MemoryError("Write to memory error") # <<<<<<<<<<<<<< + * + * cdef _getvalue(self): +*/ + __pyx_t_4 = NULL; + __pyx_t_5 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_4, __pyx_mstate_global->__pyx_kp_u_Write_to_memory_error}; + __pyx_t_3 = __Pyx_PyObject_FastCall((PyObject*)(((PyTypeObject*)PyExc_MemoryError)), __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 38, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + } + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __PYX_ERR(0, 38, __pyx_L1_error) + + /* "thriftpy2/transport/memory/cymemory.pyx":37 + * cdef c_write(self, const char* data, int sz): + * cdef int r = self.buf.write(sz, data) + * if r == -1: # <<<<<<<<<<<<<< + * raise MemoryError("Write to memory error") + * +*/ + } + + /* "thriftpy2/transport/memory/cymemory.pyx":35 + * return sz + * + * cdef c_write(self, const char* data, int sz): # <<<<<<<<<<<<<< + * cdef int r = self.buf.write(sz, data) + * if r == -1: +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("thriftpy2.transport.memory.cymemory.TCyMemoryBuffer.c_write", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/memory/cymemory.pyx":40 + * raise MemoryError("Write to memory error") + * + * cdef _getvalue(self): # <<<<<<<<<<<<<< + * cdef char *out + * cdef int size = self.buf.data_size +*/ + +static PyObject *__pyx_f_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer__getvalue(struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *__pyx_v_self) { + char *__pyx_v_out; + int __pyx_v_size; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + int __pyx_t_4; + char const *__pyx_t_5; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + PyObject *__pyx_t_9 = NULL; + PyObject *__pyx_t_10 = NULL; + PyObject *__pyx_t_11 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_getvalue", 0); + + /* "thriftpy2/transport/memory/cymemory.pyx":42 + * cdef _getvalue(self): + * cdef char *out + * cdef int size = self.buf.data_size # <<<<<<<<<<<<<< + * + * if size <= 0: +*/ + __pyx_t_1 = __pyx_v_self->buf->data_size; + __pyx_v_size = __pyx_t_1; + + /* "thriftpy2/transport/memory/cymemory.pyx":44 + * cdef int size = self.buf.data_size + * + * if size <= 0: # <<<<<<<<<<<<<< + * return b'' + * +*/ + __pyx_t_2 = (__pyx_v_size <= 0); + if (__pyx_t_2) { + + /* "thriftpy2/transport/memory/cymemory.pyx":45 + * + * if size <= 0: + * return b'' # <<<<<<<<<<<<<< + * + * out = malloc(size) +*/ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_mstate_global->__pyx_kp_b_); + __pyx_r = __pyx_mstate_global->__pyx_kp_b_; + goto __pyx_L0; + + /* "thriftpy2/transport/memory/cymemory.pyx":44 + * cdef int size = self.buf.data_size + * + * if size <= 0: # <<<<<<<<<<<<<< + * return b'' + * +*/ + } + + /* "thriftpy2/transport/memory/cymemory.pyx":47 + * return b'' + * + * out = malloc(size) # <<<<<<<<<<<<<< + * try: + * memcpy(out, self.buf.buf + self.buf.cur, size) +*/ + __pyx_v_out = ((char *)malloc(__pyx_v_size)); + + /* "thriftpy2/transport/memory/cymemory.pyx":48 + * + * out = malloc(size) + * try: # <<<<<<<<<<<<<< + * memcpy(out, self.buf.buf + self.buf.cur, size) + * return out[:size] +*/ + /*try:*/ { + + /* "thriftpy2/transport/memory/cymemory.pyx":49 + * out = malloc(size) + * try: + * memcpy(out, self.buf.buf + self.buf.cur, size) # <<<<<<<<<<<<<< + * return out[:size] + * finally: +*/ + (void)(memcpy(__pyx_v_out, (__pyx_v_self->buf->buf + __pyx_v_self->buf->cur), __pyx_v_size)); + + /* "thriftpy2/transport/memory/cymemory.pyx":50 + * try: + * memcpy(out, self.buf.buf + self.buf.cur, size) + * return out[:size] # <<<<<<<<<<<<<< + * finally: + * free(out) +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_3 = __Pyx_PyBytes_FromStringAndSize(__pyx_v_out + 0, __pyx_v_size - 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 50, __pyx_L5_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L4_return; + } + + /* "thriftpy2/transport/memory/cymemory.pyx":52 + * return out[:size] + * finally: + * free(out) # <<<<<<<<<<<<<< + * + * cdef _setvalue(self, int sz, const char *value): +*/ + /*finally:*/ { + __pyx_L5_error:; + /*exception exit:*/{ + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + __pyx_t_6 = 0; __pyx_t_7 = 0; __pyx_t_8 = 0; __pyx_t_9 = 0; __pyx_t_10 = 0; __pyx_t_11 = 0; + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_ExceptionSwap(&__pyx_t_9, &__pyx_t_10, &__pyx_t_11); + if ( unlikely(__Pyx_GetException(&__pyx_t_6, &__pyx_t_7, &__pyx_t_8) < 0)) __Pyx_ErrFetch(&__pyx_t_6, &__pyx_t_7, &__pyx_t_8); + __Pyx_XGOTREF(__pyx_t_6); + __Pyx_XGOTREF(__pyx_t_7); + __Pyx_XGOTREF(__pyx_t_8); + __Pyx_XGOTREF(__pyx_t_9); + __Pyx_XGOTREF(__pyx_t_10); + __Pyx_XGOTREF(__pyx_t_11); + __pyx_t_1 = __pyx_lineno; __pyx_t_4 = __pyx_clineno; __pyx_t_5 = __pyx_filename; + { + free(__pyx_v_out); + } + __Pyx_XGIVEREF(__pyx_t_9); + __Pyx_XGIVEREF(__pyx_t_10); + __Pyx_XGIVEREF(__pyx_t_11); + __Pyx_ExceptionReset(__pyx_t_9, __pyx_t_10, __pyx_t_11); + __Pyx_XGIVEREF(__pyx_t_6); + __Pyx_XGIVEREF(__pyx_t_7); + __Pyx_XGIVEREF(__pyx_t_8); + __Pyx_ErrRestore(__pyx_t_6, __pyx_t_7, __pyx_t_8); + __pyx_t_6 = 0; __pyx_t_7 = 0; __pyx_t_8 = 0; __pyx_t_9 = 0; __pyx_t_10 = 0; __pyx_t_11 = 0; + __pyx_lineno = __pyx_t_1; __pyx_clineno = __pyx_t_4; __pyx_filename = __pyx_t_5; + goto __pyx_L1_error; + } + __pyx_L4_return: { + __pyx_t_11 = __pyx_r; + __pyx_r = 0; + free(__pyx_v_out); + __pyx_r = __pyx_t_11; + __pyx_t_11 = 0; + goto __pyx_L0; + } + } + + /* "thriftpy2/transport/memory/cymemory.pyx":40 + * raise MemoryError("Write to memory error") + * + * cdef _getvalue(self): # <<<<<<<<<<<<<< + * cdef char *out + * cdef int size = self.buf.data_size +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("thriftpy2.transport.memory.cymemory.TCyMemoryBuffer._getvalue", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/memory/cymemory.pyx":54 + * free(out) + * + * cdef _setvalue(self, int sz, const char *value): # <<<<<<<<<<<<<< + * self.buf.clean() + * self.buf.write(sz, value) +*/ + +static PyObject *__pyx_f_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer__setvalue(struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *__pyx_v_self, int __pyx_v_sz, char const *__pyx_v_value) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_setvalue", 0); + + /* "thriftpy2/transport/memory/cymemory.pyx":55 + * + * cdef _setvalue(self, int sz, const char *value): + * self.buf.clean() # <<<<<<<<<<<<<< + * self.buf.write(sz, value) + * +*/ + ((struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_TCyBuffer *)__pyx_v_self->buf->__pyx_vtab)->clean(__pyx_v_self->buf); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 55, __pyx_L1_error) + + /* "thriftpy2/transport/memory/cymemory.pyx":56 + * cdef _setvalue(self, int sz, const char *value): + * self.buf.clean() + * self.buf.write(sz, value) # <<<<<<<<<<<<<< + * + * def read(self, sz): +*/ + ((struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_TCyBuffer *)__pyx_v_self->buf->__pyx_vtab)->write(__pyx_v_self->buf, __pyx_v_sz, __pyx_v_value); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 56, __pyx_L1_error) + + /* "thriftpy2/transport/memory/cymemory.pyx":54 + * free(out) + * + * cdef _setvalue(self, int sz, const char *value): # <<<<<<<<<<<<<< + * self.buf.clean() + * self.buf.write(sz, value) +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_AddTraceback("thriftpy2.transport.memory.cymemory.TCyMemoryBuffer._setvalue", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/memory/cymemory.pyx":58 + * self.buf.write(sz, value) + * + * def read(self, sz): # <<<<<<<<<<<<<< + * return self.get_string(sz) + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_3read(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_3read = {"read", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_3read, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_3read(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_sz = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("read (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_sz,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 58, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 58, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "read", 0) < (0)) __PYX_ERR(0, 58, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("read", 1, 1, 1, i); __PYX_ERR(0, 58, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 58, __pyx_L3_error) + } + __pyx_v_sz = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("read", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 58, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("thriftpy2.transport.memory.cymemory.TCyMemoryBuffer.read", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_2read(((struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *)__pyx_v_self), __pyx_v_sz); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_2read(struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *__pyx_v_self, PyObject *__pyx_v_sz) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("read", 0); + + /* "thriftpy2/transport/memory/cymemory.pyx":59 + * + * def read(self, sz): + * return self.get_string(sz) # <<<<<<<<<<<<<< + * + * def write(self, data): +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyLong_As_int(__pyx_v_sz); if (unlikely((__pyx_t_1 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 59, __pyx_L1_error) + __pyx_t_2 = ((struct __pyx_vtabstruct_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *)__pyx_v_self->__pyx_base.__pyx_vtab)->__pyx_base.get_string(((struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *)__pyx_v_self), __pyx_t_1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 59, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "thriftpy2/transport/memory/cymemory.pyx":58 + * self.buf.write(sz, value) + * + * def read(self, sz): # <<<<<<<<<<<<<< + * return self.get_string(sz) + * +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("thriftpy2.transport.memory.cymemory.TCyMemoryBuffer.read", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/memory/cymemory.pyx":61 + * return self.get_string(sz) + * + * def write(self, data): # <<<<<<<<<<<<<< + * if isinstance(data, unicode): + * data = (data).encode('utf-8') +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_5write(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_5write = {"write", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_5write, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_5write(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_data = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("write (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_data,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 61, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 61, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "write", 0) < (0)) __PYX_ERR(0, 61, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("write", 1, 1, 1, i); __PYX_ERR(0, 61, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 61, __pyx_L3_error) + } + __pyx_v_data = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("write", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 61, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("thriftpy2.transport.memory.cymemory.TCyMemoryBuffer.write", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_4write(((struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *)__pyx_v_self), __pyx_v_data); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_4write(struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *__pyx_v_self, PyObject *__pyx_v_data) { + int __pyx_v_sz; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + Py_ssize_t __pyx_t_3; + char *__pyx_t_4; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("write", 0); + __Pyx_INCREF(__pyx_v_data); + + /* "thriftpy2/transport/memory/cymemory.pyx":62 + * + * def write(self, data): + * if isinstance(data, unicode): # <<<<<<<<<<<<<< + * data = (data).encode('utf-8') + * +*/ + __pyx_t_1 = PyUnicode_Check(__pyx_v_data); + if (__pyx_t_1) { + + /* "thriftpy2/transport/memory/cymemory.pyx":63 + * def write(self, data): + * if isinstance(data, unicode): + * data = (data).encode('utf-8') # <<<<<<<<<<<<<< + * + * cdef int sz = len(data) +*/ + if (unlikely(__pyx_v_data == Py_None)) { + PyErr_Format(PyExc_AttributeError, "'NoneType' object has no attribute '%.30s'", "encode"); + __PYX_ERR(0, 63, __pyx_L1_error) + } + __pyx_t_2 = PyUnicode_AsUTF8String(((PyObject*)__pyx_v_data)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 63, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF_SET(__pyx_v_data, __pyx_t_2); + __pyx_t_2 = 0; + + /* "thriftpy2/transport/memory/cymemory.pyx":62 + * + * def write(self, data): + * if isinstance(data, unicode): # <<<<<<<<<<<<<< + * data = (data).encode('utf-8') + * +*/ + } + + /* "thriftpy2/transport/memory/cymemory.pyx":65 + * data = (data).encode('utf-8') + * + * cdef int sz = len(data) # <<<<<<<<<<<<<< + * return self.c_write(data, sz) + * +*/ + __pyx_t_3 = PyObject_Length(__pyx_v_data); if (unlikely(__pyx_t_3 == ((Py_ssize_t)-1))) __PYX_ERR(0, 65, __pyx_L1_error) + __pyx_v_sz = __pyx_t_3; + + /* "thriftpy2/transport/memory/cymemory.pyx":66 + * + * cdef int sz = len(data) + * return self.c_write(data, sz) # <<<<<<<<<<<<<< + * + * def is_open(self): +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_4 = __Pyx_PyObject_AsWritableString(__pyx_v_data); if (unlikely((!__pyx_t_4) && PyErr_Occurred())) __PYX_ERR(0, 66, __pyx_L1_error) + __pyx_t_2 = ((struct __pyx_vtabstruct_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *)__pyx_v_self->__pyx_base.__pyx_vtab)->__pyx_base.c_write(((struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *)__pyx_v_self), __pyx_t_4, __pyx_v_sz); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 66, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "thriftpy2/transport/memory/cymemory.pyx":61 + * return self.get_string(sz) + * + * def write(self, data): # <<<<<<<<<<<<<< + * if isinstance(data, unicode): + * data = (data).encode('utf-8') +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("thriftpy2.transport.memory.cymemory.TCyMemoryBuffer.write", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_data); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/memory/cymemory.pyx":68 + * return self.c_write(data, sz) + * + * def is_open(self): # <<<<<<<<<<<<<< + * return True + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_7is_open(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_7is_open = {"is_open", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_7is_open, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_7is_open(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("is_open (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("is_open", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("is_open", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_6is_open(((struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_6is_open(CYTHON_UNUSED struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("is_open", 0); + + /* "thriftpy2/transport/memory/cymemory.pyx":69 + * + * def is_open(self): + * return True # <<<<<<<<<<<<<< + * + * def open(self): +*/ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(Py_True); + __pyx_r = Py_True; + goto __pyx_L0; + + /* "thriftpy2/transport/memory/cymemory.pyx":68 + * return self.c_write(data, sz) + * + * def is_open(self): # <<<<<<<<<<<<<< + * return True + * +*/ + + /* function exit code */ + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/memory/cymemory.pyx":71 + * return True + * + * def open(self): # <<<<<<<<<<<<<< + * pass + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_9open(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_9open = {"open", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_9open, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_9open(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("open (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("open", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("open", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_8open(((struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_8open(CYTHON_UNUSED struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("open", 0); + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/memory/cymemory.pyx":74 + * pass + * + * def close(self): # <<<<<<<<<<<<<< + * pass + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_11close(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_11close = {"close", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_11close, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_11close(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("close (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("close", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("close", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_10close(((struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_10close(CYTHON_UNUSED struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("close", 0); + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/memory/cymemory.pyx":77 + * pass + * + * def flush(self): # <<<<<<<<<<<<<< + * pass + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_13flush(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_13flush = {"flush", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_13flush, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_13flush(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("flush (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("flush", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("flush", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_12flush(((struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_12flush(CYTHON_UNUSED struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("flush", 0); + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/memory/cymemory.pyx":80 + * pass + * + * def clean(self): # <<<<<<<<<<<<<< + * self.buf.clean() + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_15clean(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_15clean = {"clean", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_15clean, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_15clean(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("clean (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("clean", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("clean", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_14clean(((struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_14clean(struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("clean", 0); + + /* "thriftpy2/transport/memory/cymemory.pyx":81 + * + * def clean(self): + * self.buf.clean() # <<<<<<<<<<<<<< + * + * def getvalue(self): +*/ + ((struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_TCyBuffer *)__pyx_v_self->buf->__pyx_vtab)->clean(__pyx_v_self->buf); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 81, __pyx_L1_error) + + /* "thriftpy2/transport/memory/cymemory.pyx":80 + * pass + * + * def clean(self): # <<<<<<<<<<<<<< + * self.buf.clean() + * +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_AddTraceback("thriftpy2.transport.memory.cymemory.TCyMemoryBuffer.clean", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/memory/cymemory.pyx":83 + * self.buf.clean() + * + * def getvalue(self): # <<<<<<<<<<<<<< + * return self._getvalue() + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_17getvalue(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_17getvalue = {"getvalue", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_17getvalue, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_17getvalue(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("getvalue (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("getvalue", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("getvalue", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_16getvalue(((struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_16getvalue(struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("getvalue", 0); + + /* "thriftpy2/transport/memory/cymemory.pyx":84 + * + * def getvalue(self): + * return self._getvalue() # <<<<<<<<<<<<<< + * + * def setvalue(self, value): +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = ((struct __pyx_vtabstruct_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *)__pyx_v_self->__pyx_base.__pyx_vtab)->_getvalue(__pyx_v_self); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 84, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "thriftpy2/transport/memory/cymemory.pyx":83 + * self.buf.clean() + * + * def getvalue(self): # <<<<<<<<<<<<<< + * return self._getvalue() + * +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("thriftpy2.transport.memory.cymemory.TCyMemoryBuffer.getvalue", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/memory/cymemory.pyx":86 + * return self._getvalue() + * + * def setvalue(self, value): # <<<<<<<<<<<<<< + * if isinstance(value, unicode): + * value = (value).encode('utf-8') +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_19setvalue(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_19setvalue = {"setvalue", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_19setvalue, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_19setvalue(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_value = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("setvalue (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_value,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 86, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 86, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "setvalue", 0) < (0)) __PYX_ERR(0, 86, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("setvalue", 1, 1, 1, i); __PYX_ERR(0, 86, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 86, __pyx_L3_error) + } + __pyx_v_value = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("setvalue", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 86, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("thriftpy2.transport.memory.cymemory.TCyMemoryBuffer.setvalue", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_18setvalue(((struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *)__pyx_v_self), __pyx_v_value); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_18setvalue(struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *__pyx_v_self, PyObject *__pyx_v_value) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + Py_ssize_t __pyx_t_3; + char const *__pyx_t_4; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("setvalue", 0); + __Pyx_INCREF(__pyx_v_value); + + /* "thriftpy2/transport/memory/cymemory.pyx":87 + * + * def setvalue(self, value): + * if isinstance(value, unicode): # <<<<<<<<<<<<<< + * value = (value).encode('utf-8') + * self._setvalue(len(value), value) +*/ + __pyx_t_1 = PyUnicode_Check(__pyx_v_value); + if (__pyx_t_1) { + + /* "thriftpy2/transport/memory/cymemory.pyx":88 + * def setvalue(self, value): + * if isinstance(value, unicode): + * value = (value).encode('utf-8') # <<<<<<<<<<<<<< + * self._setvalue(len(value), value) +*/ + if (unlikely(__pyx_v_value == Py_None)) { + PyErr_Format(PyExc_AttributeError, "'NoneType' object has no attribute '%.30s'", "encode"); + __PYX_ERR(0, 88, __pyx_L1_error) + } + __pyx_t_2 = PyUnicode_AsUTF8String(((PyObject*)__pyx_v_value)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 88, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF_SET(__pyx_v_value, __pyx_t_2); + __pyx_t_2 = 0; + + /* "thriftpy2/transport/memory/cymemory.pyx":87 + * + * def setvalue(self, value): + * if isinstance(value, unicode): # <<<<<<<<<<<<<< + * value = (value).encode('utf-8') + * self._setvalue(len(value), value) +*/ + } + + /* "thriftpy2/transport/memory/cymemory.pyx":89 + * if isinstance(value, unicode): + * value = (value).encode('utf-8') + * self._setvalue(len(value), value) # <<<<<<<<<<<<<< +*/ + __pyx_t_3 = PyObject_Length(__pyx_v_value); if (unlikely(__pyx_t_3 == ((Py_ssize_t)-1))) __PYX_ERR(0, 89, __pyx_L1_error) + __pyx_t_4 = __Pyx_PyObject_AsString(__pyx_v_value); if (unlikely((!__pyx_t_4) && PyErr_Occurred())) __PYX_ERR(0, 89, __pyx_L1_error) + __pyx_t_2 = ((struct __pyx_vtabstruct_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *)__pyx_v_self->__pyx_base.__pyx_vtab)->_setvalue(__pyx_v_self, __pyx_t_3, __pyx_t_4); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 89, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/transport/memory/cymemory.pyx":86 + * return self._getvalue() + * + * def setvalue(self, value): # <<<<<<<<<<<<<< + * if isinstance(value, unicode): + * value = (value).encode('utf-8') +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("thriftpy2.transport.memory.cymemory.TCyMemoryBuffer.setvalue", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_value); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * cdef tuple state + * cdef object _dict +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_21__reduce_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_21__reduce_cython__ = {"__reduce_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_21__reduce_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_21__reduce_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("__reduce_cython__", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("__reduce_cython__", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_20__reduce_cython__(((struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_20__reduce_cython__(struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *__pyx_v_self) { + PyObject *__pyx_v_state = 0; + PyObject *__pyx_v__dict = 0; + int __pyx_v_use_setstate; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__reduce_cython__", 0); + + /* "(tree fragment)":5 + * cdef object _dict + * cdef bint use_setstate + * state = (self.buf, self.trans) # <<<<<<<<<<<<<< + * _dict = getattr(self, '__dict__', None) + * if _dict is not None and _dict: +*/ + __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 5, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF((PyObject *)__pyx_v_self->buf); + __Pyx_GIVEREF((PyObject *)__pyx_v_self->buf); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_v_self->buf)) != (0)) __PYX_ERR(1, 5, __pyx_L1_error); + __Pyx_INCREF(__pyx_v_self->__pyx_base.trans); + __Pyx_GIVEREF(__pyx_v_self->__pyx_base.trans); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_self->__pyx_base.trans) != (0)) __PYX_ERR(1, 5, __pyx_L1_error); + __pyx_v_state = ((PyObject*)__pyx_t_1); + __pyx_t_1 = 0; + + /* "(tree fragment)":6 + * cdef bint use_setstate + * state = (self.buf, self.trans) + * _dict = getattr(self, '__dict__', None) # <<<<<<<<<<<<<< + * if _dict is not None and _dict: + * state += (_dict,) +*/ + __pyx_t_1 = __Pyx_GetAttr3(((PyObject *)__pyx_v_self), __pyx_mstate_global->__pyx_n_u_dict, Py_None); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 6, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v__dict = __pyx_t_1; + __pyx_t_1 = 0; + + /* "(tree fragment)":7 + * state = (self.buf, self.trans) + * _dict = getattr(self, '__dict__', None) + * if _dict is not None and _dict: # <<<<<<<<<<<<<< + * state += (_dict,) + * use_setstate = True +*/ + __pyx_t_3 = (__pyx_v__dict != Py_None); + if (__pyx_t_3) { + } else { + __pyx_t_2 = __pyx_t_3; + goto __pyx_L4_bool_binop_done; + } + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_v__dict); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(1, 7, __pyx_L1_error) + __pyx_t_2 = __pyx_t_3; + __pyx_L4_bool_binop_done:; + if (__pyx_t_2) { + + /* "(tree fragment)":8 + * _dict = getattr(self, '__dict__', None) + * if _dict is not None and _dict: + * state += (_dict,) # <<<<<<<<<<<<<< + * use_setstate = True + * else: +*/ + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 8, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_v__dict); + __Pyx_GIVEREF(__pyx_v__dict); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v__dict) != (0)) __PYX_ERR(1, 8, __pyx_L1_error); + __pyx_t_4 = PyNumber_InPlaceAdd(__pyx_v_state, __pyx_t_1); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 8, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF_SET(__pyx_v_state, ((PyObject*)__pyx_t_4)); + __pyx_t_4 = 0; + + /* "(tree fragment)":9 + * if _dict is not None and _dict: + * state += (_dict,) + * use_setstate = True # <<<<<<<<<<<<<< + * else: + * use_setstate = self.buf is not None or self.trans is not None +*/ + __pyx_v_use_setstate = 1; + + /* "(tree fragment)":7 + * state = (self.buf, self.trans) + * _dict = getattr(self, '__dict__', None) + * if _dict is not None and _dict: # <<<<<<<<<<<<<< + * state += (_dict,) + * use_setstate = True +*/ + goto __pyx_L3; + } + + /* "(tree fragment)":11 + * use_setstate = True + * else: + * use_setstate = self.buf is not None or self.trans is not None # <<<<<<<<<<<<<< + * if use_setstate: + * return __pyx_unpickle_TCyMemoryBuffer, (type(self), 0x969e82f, None), state +*/ + /*else*/ { + __pyx_t_3 = (((PyObject *)__pyx_v_self->buf) != Py_None); + if (!__pyx_t_3) { + } else { + __pyx_t_2 = __pyx_t_3; + goto __pyx_L6_bool_binop_done; + } + __pyx_t_3 = (__pyx_v_self->__pyx_base.trans != Py_None); + __pyx_t_2 = __pyx_t_3; + __pyx_L6_bool_binop_done:; + __pyx_v_use_setstate = __pyx_t_2; + } + __pyx_L3:; + + /* "(tree fragment)":12 + * else: + * use_setstate = self.buf is not None or self.trans is not None + * if use_setstate: # <<<<<<<<<<<<<< + * return __pyx_unpickle_TCyMemoryBuffer, (type(self), 0x969e82f, None), state + * else: +*/ + if (__pyx_v_use_setstate) { + + /* "(tree fragment)":13 + * use_setstate = self.buf is not None or self.trans is not None + * if use_setstate: + * return __pyx_unpickle_TCyMemoryBuffer, (type(self), 0x969e82f, None), state # <<<<<<<<<<<<<< + * else: + * return __pyx_unpickle_TCyMemoryBuffer, (type(self), 0x969e82f, state) +*/ + __Pyx_XDECREF(__pyx_r); + __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_mstate_global->__pyx_n_u_pyx_unpickle_TCyMemoryBuffer); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 13, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_1 = PyTuple_New(3); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 13, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); + __Pyx_GIVEREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))) != (0)) __PYX_ERR(1, 13, __pyx_L1_error); + __Pyx_INCREF(__pyx_mstate_global->__pyx_int_157935663); + __Pyx_GIVEREF(__pyx_mstate_global->__pyx_int_157935663); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_mstate_global->__pyx_int_157935663) != (0)) __PYX_ERR(1, 13, __pyx_L1_error); + __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(Py_None); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 2, Py_None) != (0)) __PYX_ERR(1, 13, __pyx_L1_error); + __pyx_t_5 = PyTuple_New(3); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 13, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_GIVEREF(__pyx_t_4); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4) != (0)) __PYX_ERR(1, 13, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_1); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_1) != (0)) __PYX_ERR(1, 13, __pyx_L1_error); + __Pyx_INCREF(__pyx_v_state); + __Pyx_GIVEREF(__pyx_v_state); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_5, 2, __pyx_v_state) != (0)) __PYX_ERR(1, 13, __pyx_L1_error); + __pyx_t_4 = 0; + __pyx_t_1 = 0; + __pyx_r = __pyx_t_5; + __pyx_t_5 = 0; + goto __pyx_L0; + + /* "(tree fragment)":12 + * else: + * use_setstate = self.buf is not None or self.trans is not None + * if use_setstate: # <<<<<<<<<<<<<< + * return __pyx_unpickle_TCyMemoryBuffer, (type(self), 0x969e82f, None), state + * else: +*/ + } + + /* "(tree fragment)":15 + * return __pyx_unpickle_TCyMemoryBuffer, (type(self), 0x969e82f, None), state + * else: + * return __pyx_unpickle_TCyMemoryBuffer, (type(self), 0x969e82f, state) # <<<<<<<<<<<<<< + * def __setstate_cython__(self, __pyx_state): + * __pyx_unpickle_TCyMemoryBuffer__set_state(self, __pyx_state) +*/ + /*else*/ { + __Pyx_XDECREF(__pyx_r); + __Pyx_GetModuleGlobalName(__pyx_t_5, __pyx_mstate_global->__pyx_n_u_pyx_unpickle_TCyMemoryBuffer); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 15, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_1 = PyTuple_New(3); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 15, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); + __Pyx_GIVEREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))) != (0)) __PYX_ERR(1, 15, __pyx_L1_error); + __Pyx_INCREF(__pyx_mstate_global->__pyx_int_157935663); + __Pyx_GIVEREF(__pyx_mstate_global->__pyx_int_157935663); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_mstate_global->__pyx_int_157935663) != (0)) __PYX_ERR(1, 15, __pyx_L1_error); + __Pyx_INCREF(__pyx_v_state); + __Pyx_GIVEREF(__pyx_v_state); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 2, __pyx_v_state) != (0)) __PYX_ERR(1, 15, __pyx_L1_error); + __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 15, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_GIVEREF(__pyx_t_5); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_5) != (0)) __PYX_ERR(1, 15, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_1); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_1) != (0)) __PYX_ERR(1, 15, __pyx_L1_error); + __pyx_t_5 = 0; + __pyx_t_1 = 0; + __pyx_r = __pyx_t_4; + __pyx_t_4 = 0; + goto __pyx_L0; + } + + /* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * cdef tuple state + * cdef object _dict +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("thriftpy2.transport.memory.cymemory.TCyMemoryBuffer.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_state); + __Pyx_XDECREF(__pyx_v__dict); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":16 + * else: + * return __pyx_unpickle_TCyMemoryBuffer, (type(self), 0x969e82f, state) + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * __pyx_unpickle_TCyMemoryBuffer__set_state(self, __pyx_state) +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_23__setstate_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_23__setstate_cython__ = {"__setstate_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_23__setstate_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_23__setstate_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v___pyx_state = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_pyx_state,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(1, 16, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(1, 16, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "__setstate_cython__", 0) < (0)) __PYX_ERR(1, 16, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("__setstate_cython__", 1, 1, 1, i); __PYX_ERR(1, 16, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(1, 16, __pyx_L3_error) + } + __pyx_v___pyx_state = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__setstate_cython__", 1, 1, 1, __pyx_nargs); __PYX_ERR(1, 16, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("thriftpy2.transport.memory.cymemory.TCyMemoryBuffer.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_22__setstate_cython__(((struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *)__pyx_v_self), __pyx_v___pyx_state); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_22__setstate_cython__(struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *__pyx_v_self, PyObject *__pyx_v___pyx_state) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__setstate_cython__", 0); + + /* "(tree fragment)":17 + * return __pyx_unpickle_TCyMemoryBuffer, (type(self), 0x969e82f, state) + * def __setstate_cython__(self, __pyx_state): + * __pyx_unpickle_TCyMemoryBuffer__set_state(self, __pyx_state) # <<<<<<<<<<<<<< +*/ + __pyx_t_1 = __pyx_v___pyx_state; + __Pyx_INCREF(__pyx_t_1); + if (!(likely(PyTuple_CheckExact(__pyx_t_1))||((__pyx_t_1) == Py_None) || __Pyx_RaiseUnexpectedTypeError("tuple", __pyx_t_1))) __PYX_ERR(1, 17, __pyx_L1_error) + if (unlikely(__pyx_t_1 == Py_None)) { + PyErr_SetString(PyExc_TypeError, "cannot pass None into a C function argument that is declared 'not None'"); + __PYX_ERR(1, 17, __pyx_L1_error) + } + __pyx_t_2 = __pyx_f_9thriftpy2_9transport_6memory_8cymemory___pyx_unpickle_TCyMemoryBuffer__set_state(__pyx_v_self, ((PyObject*)__pyx_t_1)); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 17, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "(tree fragment)":16 + * else: + * return __pyx_unpickle_TCyMemoryBuffer, (type(self), 0x969e82f, state) + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * __pyx_unpickle_TCyMemoryBuffer__set_state(self, __pyx_state) +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("thriftpy2.transport.memory.cymemory.TCyMemoryBuffer.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":4 + * int __Pyx_CheckUnpickleChecksum(long, long, long, long, const char*) except -1 + * int __Pyx_UpdateUnpickledDict(object, object, Py_ssize_t) except -1 + * def __pyx_unpickle_TCyMemoryBuffer(__pyx_type, long __pyx_checksum, tuple __pyx_state): # <<<<<<<<<<<<<< + * cdef object __pyx_result + * __Pyx_CheckUnpickleChecksum(__pyx_checksum, 0x969e82f, 0x5876d04, 0xfcd695e, b'buf, trans') +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_9transport_6memory_8cymemory_1__pyx_unpickle_TCyMemoryBuffer(PyObject *__pyx_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_9transport_6memory_8cymemory_1__pyx_unpickle_TCyMemoryBuffer = {"__pyx_unpickle_TCyMemoryBuffer", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_6memory_8cymemory_1__pyx_unpickle_TCyMemoryBuffer, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_9transport_6memory_8cymemory_1__pyx_unpickle_TCyMemoryBuffer(PyObject *__pyx_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v___pyx_type = 0; + long __pyx_v___pyx_checksum; + PyObject *__pyx_v___pyx_state = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[3] = {0,0,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__pyx_unpickle_TCyMemoryBuffer (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_pyx_type,&__pyx_mstate_global->__pyx_n_u_pyx_checksum,&__pyx_mstate_global->__pyx_n_u_pyx_state,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(1, 4, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 3: + values[2] = __Pyx_ArgRef_FASTCALL(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(1, 4, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 2: + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(1, 4, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(1, 4, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "__pyx_unpickle_TCyMemoryBuffer", 0) < (0)) __PYX_ERR(1, 4, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 3; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("__pyx_unpickle_TCyMemoryBuffer", 1, 3, 3, i); __PYX_ERR(1, 4, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 3)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(1, 4, __pyx_L3_error) + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(1, 4, __pyx_L3_error) + values[2] = __Pyx_ArgRef_FASTCALL(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(1, 4, __pyx_L3_error) + } + __pyx_v___pyx_type = values[0]; + __pyx_v___pyx_checksum = __Pyx_PyLong_As_long(values[1]); if (unlikely((__pyx_v___pyx_checksum == (long)-1) && PyErr_Occurred())) __PYX_ERR(1, 4, __pyx_L3_error) + __pyx_v___pyx_state = ((PyObject*)values[2]); + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__pyx_unpickle_TCyMemoryBuffer", 1, 3, 3, __pyx_nargs); __PYX_ERR(1, 4, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("thriftpy2.transport.memory.cymemory.__pyx_unpickle_TCyMemoryBuffer", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v___pyx_state), (&PyTuple_Type), 1, "__pyx_state", 1))) __PYX_ERR(1, 4, __pyx_L1_error) + __pyx_r = __pyx_pf_9thriftpy2_9transport_6memory_8cymemory___pyx_unpickle_TCyMemoryBuffer(__pyx_self, __pyx_v___pyx_type, __pyx_v___pyx_checksum, __pyx_v___pyx_state); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + goto __pyx_L7_cleaned_up; + __pyx_L0:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __pyx_L7_cleaned_up:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_9transport_6memory_8cymemory___pyx_unpickle_TCyMemoryBuffer(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v___pyx_type, long __pyx_v___pyx_checksum, PyObject *__pyx_v___pyx_state) { + PyObject *__pyx_v___pyx_result = 0; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + size_t __pyx_t_4; + int __pyx_t_5; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__pyx_unpickle_TCyMemoryBuffer", 0); + + /* "(tree fragment)":6 + * def __pyx_unpickle_TCyMemoryBuffer(__pyx_type, long __pyx_checksum, tuple __pyx_state): + * cdef object __pyx_result + * __Pyx_CheckUnpickleChecksum(__pyx_checksum, 0x969e82f, 0x5876d04, 0xfcd695e, b'buf, trans') # <<<<<<<<<<<<<< + * __pyx_result = TCyMemoryBuffer.__new__(__pyx_type) + * if __pyx_state is not None: +*/ + __pyx_t_1 = __Pyx_CheckUnpickleChecksum(__pyx_v___pyx_checksum, 0x969e82f, 0x5876d04, 0xfcd695e, __pyx_k_buf_trans); if (unlikely(__pyx_t_1 == ((int)-1))) __PYX_ERR(1, 6, __pyx_L1_error) + + /* "(tree fragment)":7 + * cdef object __pyx_result + * __Pyx_CheckUnpickleChecksum(__pyx_checksum, 0x969e82f, 0x5876d04, 0xfcd695e, b'buf, trans') + * __pyx_result = TCyMemoryBuffer.__new__(__pyx_type) # <<<<<<<<<<<<<< + * if __pyx_state is not None: + * __pyx_unpickle_TCyMemoryBuffer__set_state( __pyx_result, __pyx_state) +*/ + __pyx_t_3 = ((PyObject *)__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer); + __Pyx_INCREF(__pyx_t_3); + __pyx_t_4 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_v___pyx_type}; + __pyx_t_2 = __Pyx_PyObject_FastCallMethod((PyObject*)__pyx_mstate_global->__pyx_n_u_new, __pyx_callargs+__pyx_t_4, (2-__pyx_t_4) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 7, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __pyx_v___pyx_result = __pyx_t_2; + __pyx_t_2 = 0; + + /* "(tree fragment)":8 + * __Pyx_CheckUnpickleChecksum(__pyx_checksum, 0x969e82f, 0x5876d04, 0xfcd695e, b'buf, trans') + * __pyx_result = TCyMemoryBuffer.__new__(__pyx_type) + * if __pyx_state is not None: # <<<<<<<<<<<<<< + * __pyx_unpickle_TCyMemoryBuffer__set_state( __pyx_result, __pyx_state) + * return __pyx_result +*/ + __pyx_t_5 = (__pyx_v___pyx_state != ((PyObject*)Py_None)); + if (__pyx_t_5) { + + /* "(tree fragment)":9 + * __pyx_result = TCyMemoryBuffer.__new__(__pyx_type) + * if __pyx_state is not None: + * __pyx_unpickle_TCyMemoryBuffer__set_state( __pyx_result, __pyx_state) # <<<<<<<<<<<<<< + * return __pyx_result + * cdef __pyx_unpickle_TCyMemoryBuffer__set_state(TCyMemoryBuffer __pyx_result, __pyx_state: tuple): +*/ + if (unlikely(__pyx_v___pyx_state == Py_None)) { + PyErr_SetString(PyExc_TypeError, "cannot pass None into a C function argument that is declared 'not None'"); + __PYX_ERR(1, 9, __pyx_L1_error) + } + __pyx_t_2 = __pyx_f_9thriftpy2_9transport_6memory_8cymemory___pyx_unpickle_TCyMemoryBuffer__set_state(((struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *)__pyx_v___pyx_result), __pyx_v___pyx_state); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 9, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "(tree fragment)":8 + * __Pyx_CheckUnpickleChecksum(__pyx_checksum, 0x969e82f, 0x5876d04, 0xfcd695e, b'buf, trans') + * __pyx_result = TCyMemoryBuffer.__new__(__pyx_type) + * if __pyx_state is not None: # <<<<<<<<<<<<<< + * __pyx_unpickle_TCyMemoryBuffer__set_state( __pyx_result, __pyx_state) + * return __pyx_result +*/ + } + + /* "(tree fragment)":10 + * if __pyx_state is not None: + * __pyx_unpickle_TCyMemoryBuffer__set_state( __pyx_result, __pyx_state) + * return __pyx_result # <<<<<<<<<<<<<< + * cdef __pyx_unpickle_TCyMemoryBuffer__set_state(TCyMemoryBuffer __pyx_result, __pyx_state: tuple): + * __pyx_result.buf = __pyx_state[0]; __pyx_result.trans = __pyx_state[1] +*/ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v___pyx_result); + __pyx_r = __pyx_v___pyx_result; + goto __pyx_L0; + + /* "(tree fragment)":4 + * int __Pyx_CheckUnpickleChecksum(long, long, long, long, const char*) except -1 + * int __Pyx_UpdateUnpickledDict(object, object, Py_ssize_t) except -1 + * def __pyx_unpickle_TCyMemoryBuffer(__pyx_type, long __pyx_checksum, tuple __pyx_state): # <<<<<<<<<<<<<< + * cdef object __pyx_result + * __Pyx_CheckUnpickleChecksum(__pyx_checksum, 0x969e82f, 0x5876d04, 0xfcd695e, b'buf, trans') +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("thriftpy2.transport.memory.cymemory.__pyx_unpickle_TCyMemoryBuffer", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v___pyx_result); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":11 + * __pyx_unpickle_TCyMemoryBuffer__set_state( __pyx_result, __pyx_state) + * return __pyx_result + * cdef __pyx_unpickle_TCyMemoryBuffer__set_state(TCyMemoryBuffer __pyx_result, __pyx_state: tuple): # <<<<<<<<<<<<<< + * __pyx_result.buf = __pyx_state[0]; __pyx_result.trans = __pyx_state[1] + * __Pyx_UpdateUnpickledDict(__pyx_result, __pyx_state, 2) +*/ + +static PyObject *__pyx_f_9thriftpy2_9transport_6memory_8cymemory___pyx_unpickle_TCyMemoryBuffer__set_state(struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *__pyx_v___pyx_result, PyObject *__pyx_v___pyx_state) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__pyx_unpickle_TCyMemoryBuffer__set_state", 0); + + /* "(tree fragment)":12 + * return __pyx_result + * cdef __pyx_unpickle_TCyMemoryBuffer__set_state(TCyMemoryBuffer __pyx_result, __pyx_state: tuple): + * __pyx_result.buf = __pyx_state[0]; __pyx_result.trans = __pyx_state[1] # <<<<<<<<<<<<<< + * __Pyx_UpdateUnpickledDict(__pyx_result, __pyx_state, 2) +*/ + __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 0, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1, __Pyx_ReferenceSharing_FunctionArgument); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 12, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer))))) __PYX_ERR(1, 12, __pyx_L1_error) + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF((PyObject *)__pyx_v___pyx_result->buf); + __Pyx_DECREF((PyObject *)__pyx_v___pyx_result->buf); + __pyx_v___pyx_result->buf = ((struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *)__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 1, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1, __Pyx_ReferenceSharing_FunctionArgument); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 12, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF(__pyx_v___pyx_result->__pyx_base.trans); + __Pyx_DECREF(__pyx_v___pyx_result->__pyx_base.trans); + __pyx_v___pyx_result->__pyx_base.trans = __pyx_t_1; + __pyx_t_1 = 0; + + /* "(tree fragment)":13 + * cdef __pyx_unpickle_TCyMemoryBuffer__set_state(TCyMemoryBuffer __pyx_result, __pyx_state: tuple): + * __pyx_result.buf = __pyx_state[0]; __pyx_result.trans = __pyx_state[1] + * __Pyx_UpdateUnpickledDict(__pyx_result, __pyx_state, 2) # <<<<<<<<<<<<<< +*/ + __pyx_t_2 = __Pyx_UpdateUnpickledDict(((PyObject *)__pyx_v___pyx_result), __pyx_v___pyx_state, 2); if (unlikely(__pyx_t_2 == ((int)-1))) __PYX_ERR(1, 13, __pyx_L1_error) + + /* "(tree fragment)":11 + * __pyx_unpickle_TCyMemoryBuffer__set_state( __pyx_result, __pyx_state) + * return __pyx_result + * cdef __pyx_unpickle_TCyMemoryBuffer__set_state(TCyMemoryBuffer __pyx_result, __pyx_state: tuple): # <<<<<<<<<<<<<< + * __pyx_result.buf = __pyx_state[0]; __pyx_result.trans = __pyx_state[1] + * __Pyx_UpdateUnpickledDict(__pyx_result, __pyx_state, 2) +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("thriftpy2.transport.memory.cymemory.__pyx_unpickle_TCyMemoryBuffer__set_state", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} +/* #### Code section: module_exttypes ### */ +static struct __pyx_vtabstruct_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer __pyx_vtable_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer; + +static PyObject *__pyx_tp_new_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *p; + PyObject *o = __Pyx_PyType_GetSlot(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase, tp_new, newfunc)(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *)o); + p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_CyTransportBase*)__pyx_vtabptr_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer; + p->buf = ((struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *)Py_None); Py_INCREF(Py_None); + return o; +} + +static void __pyx_tp_dealloc_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer(PyObject *o) { + struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *p = (struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *)o; + #if CYTHON_USE_TP_FINALIZE + if (unlikely(__Pyx_PyObject_GetSlot(o, tp_finalize, destructor)) && !__Pyx_PyObject_GC_IsFinalized(o)) { + if (__Pyx_PyObject_GetSlot(o, tp_dealloc, destructor) == __pyx_tp_dealloc_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + } + #endif + PyObject_GC_UnTrack(o); + Py_CLEAR(p->buf); + if (PyType_IS_GC(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase)) PyObject_GC_Track(o); + #if !CYTHON_USE_MODULE_STATE + if (likely(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase)) __Pyx_PyType_GetSlot(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase, tp_dealloc, destructor)(o); else + #endif + __Pyx_call_next_tp_dealloc(o, __pyx_tp_dealloc_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer); +} + +static int __pyx_tp_traverse_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *p = (struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *)o; + #if !CYTHON_USE_MODULE_STATE + e = 0; + if (likely(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase)) { + traverseproc traverse = __Pyx_PyType_GetSlot(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase, tp_traverse, traverseproc); + if (traverse) { e = traverse(o, v, a); } + } else + #endif + { e = __Pyx_call_next_tp_traverse(o, v, a, __pyx_tp_traverse_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer); } + if (e) return e; + { + e = __Pyx_call_type_traverse(o, 0, v, a); + if (e) return e; + } + if (p->buf) { + e = (*v)(((PyObject *)p->buf), a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer(PyObject *o) { + PyObject* tmp; + struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *p = (struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *)o; + #if !CYTHON_USE_MODULE_STATE + if (likely(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase)) { + inquiry clear = __Pyx_PyType_GetSlot(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase, tp_clear, inquiry); + if (clear) clear(o); + } else + #endif + { __Pyx_call_next_tp_clear(o, __pyx_tp_clear_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer); } + tmp = ((PyObject*)p->buf); + p->buf = ((struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); + return 0; +} + +static PyMethodDef __pyx_methods_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer[] = { + {"read", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_3read, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, + {"write", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_5write, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, + {"is_open", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_7is_open, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, + {"open", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_9open, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, + {"close", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_11close, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, + {"flush", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_13flush, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, + {"clean", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_15clean, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, + {"getvalue", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_17getvalue, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, + {"setvalue", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_19setvalue, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, + {"__reduce_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_21__reduce_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, + {"__setstate_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_23__setstate_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, + {0, 0, 0, 0} +}; +#if CYTHON_USE_TYPE_SPECS +static PyType_Slot __pyx_type_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer_slots[] = { + {Py_tp_dealloc, (void *)__pyx_tp_dealloc_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer}, + {Py_tp_traverse, (void *)__pyx_tp_traverse_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer}, + {Py_tp_clear, (void *)__pyx_tp_clear_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer}, + {Py_tp_methods, (void *)__pyx_methods_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer}, + {Py_tp_init, (void *)__pyx_pw_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_1__init__}, + {Py_tp_new, (void *)__pyx_tp_new_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer}, + {0, 0}, +}; +static PyType_Spec __pyx_type_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer_spec = { + "thriftpy2.transport.memory.cymemory.TCyMemoryBuffer", + sizeof(struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer), + 0, + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, + __pyx_type_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer_slots, +}; +#else + +static PyTypeObject __pyx_type_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer = { + PyVarObject_HEAD_INIT(0, 0) + "thriftpy2.transport.memory.cymemory.""TCyMemoryBuffer", /*tp_name*/ + sizeof(struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer, /*tp_dealloc*/ + 0, /*tp_vectorcall_offset*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_as_async*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + 0, /*tp_doc*/ + __pyx_tp_traverse_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer, /*tp_traverse*/ + __pyx_tp_clear_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + #if !CYTHON_USE_TYPE_SPECS + 0, /*tp_dictoffset*/ + #endif + __pyx_pw_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_1__init__, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if CYTHON_USE_TP_FINALIZE + 0, /*tp_finalize*/ + #else + NULL, /*tp_finalize*/ + #endif + #if !CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800 + 0, /*tp_vectorcall*/ + #endif + #if __PYX_NEED_TP_PRINT_SLOT == 1 + 0, /*tp_print*/ + #endif + #if PY_VERSION_HEX >= 0x030C0000 + 0, /*tp_watched*/ + #endif + #if PY_VERSION_HEX >= 0x030d00A4 + 0, /*tp_versions_used*/ + #endif + #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX >= 0x03090000 && PY_VERSION_HEX < 0x030a0000 + 0, /*tp_pypy_flags*/ + #endif +}; +#endif + +static PyMethodDef __pyx_methods[] = { + {0, 0, 0, 0} +}; +/* #### Code section: initfunc_declarations ### */ +static CYTHON_SMALL_CODE int __Pyx_InitCachedBuiltins(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_InitCachedConstants(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_InitGlobals(void); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_InitConstants(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_global_init_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_variable_export_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_function_export_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_type_init_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_type_import_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_variable_import_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_function_import_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_CreateCodeObjects(__pyx_mstatetype *__pyx_mstate); /*proto*/ +/* #### Code section: init_module ### */ + +static int __Pyx_modinit_global_init_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_modinit_global_init_code", 0); + /*--- Global init code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_modinit_variable_export_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_modinit_variable_export_code", 0); + /*--- Variable export code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_modinit_function_export_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_modinit_function_export_code", 0); + /*--- Function export code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_modinit_type_init_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__Pyx_modinit_type_init_code", 0); + /*--- Type init code ---*/ + __pyx_t_1 = PyImport_ImportModule("thriftpy2.transport.cybase"); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase = __Pyx_ImportType_3_2_4(__pyx_t_1, "thriftpy2.transport.cybase", "CyTransportBase", + #if defined(PYPY_VERSION_NUM) && PYPY_VERSION_NUM < 0x050B0000 + sizeof(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase), __PYX_GET_STRUCT_ALIGNMENT_3_2_4(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase), + #elif CYTHON_COMPILING_IN_LIMITED_API + sizeof(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase), __PYX_GET_STRUCT_ALIGNMENT_3_2_4(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase), + #else + sizeof(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase), __PYX_GET_STRUCT_ALIGNMENT_3_2_4(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase), + #endif + __Pyx_ImportType_CheckSize_Warn_3_2_4); if (!__pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_vtabptr_9thriftpy2_9transport_6cybase_CyTransportBase = (struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_CyTransportBase*)__Pyx_GetVtable(__pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase); if (unlikely(!__pyx_vtabptr_9thriftpy2_9transport_6cybase_CyTransportBase)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_vtabptr_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer = &__pyx_vtable_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer; + __pyx_vtable_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer.__pyx_base = *__pyx_vtabptr_9thriftpy2_9transport_6cybase_CyTransportBase; + __pyx_vtable_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer.__pyx_base.c_read = (PyObject *(*)(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *, int, char *))__pyx_f_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_c_read; + __pyx_vtable_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer.__pyx_base.c_write = (PyObject *(*)(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *, char *, int))__pyx_f_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_c_write; + __pyx_vtable_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer._getvalue = (PyObject *(*)(struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *))__pyx_f_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer__getvalue; + __pyx_vtable_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer._setvalue = (PyObject *(*)(struct __pyx_obj_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer *, int, char const *))__pyx_f_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer__setvalue; + #if CYTHON_USE_TYPE_SPECS + __pyx_t_2 = PyTuple_Pack(1, (PyObject *)__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 12, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer = (PyTypeObject *) __Pyx_PyType_FromModuleAndSpec(__pyx_m, &__pyx_type_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer_spec, __pyx_t_2); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer)) __PYX_ERR(0, 12, __pyx_L1_error) + if (__Pyx_fix_up_extension_type_from_spec(&__pyx_type_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer_spec, __pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer) < (0)) __PYX_ERR(0, 12, __pyx_L1_error) + #else + __pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer = &__pyx_type_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer; + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + __pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer->tp_base = __pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase; + #endif + #if !CYTHON_USE_TYPE_SPECS + if (__Pyx_PyType_Ready(__pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer) < (0)) __PYX_ERR(0, 12, __pyx_L1_error) + #endif + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount((PyObject*)__pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer); + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer->tp_dictoffset && __pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer->tp_getattro == PyObject_GenericGetAttr)) { + __pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer->tp_getattro = PyObject_GenericGetAttr; + } + #endif + if (__Pyx_SetVtable(__pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer, __pyx_vtabptr_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer) < (0)) __PYX_ERR(0, 12, __pyx_L1_error) + if (__Pyx_MergeVtables(__pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer) < (0)) __PYX_ERR(0, 12, __pyx_L1_error) + if (PyObject_SetAttr(__pyx_m, __pyx_mstate_global->__pyx_n_u_TCyMemoryBuffer, (PyObject *) __pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer) < (0)) __PYX_ERR(0, 12, __pyx_L1_error) + if (__Pyx_setup_reduce((PyObject *) __pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer) < (0)) __PYX_ERR(0, 12, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_RefNannyFinishContext(); + return 0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_RefNannyFinishContext(); + return -1; +} + +static int __Pyx_modinit_type_import_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__Pyx_modinit_type_import_code", 0); + /*--- Type import code ---*/ + __pyx_t_1 = PyImport_ImportModule("thriftpy2.transport.cybase"); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 7, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer = __Pyx_ImportType_3_2_4(__pyx_t_1, "thriftpy2.transport.cybase", "TCyBuffer", + #if defined(PYPY_VERSION_NUM) && PYPY_VERSION_NUM < 0x050B0000 + sizeof(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer), __PYX_GET_STRUCT_ALIGNMENT_3_2_4(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer), + #elif CYTHON_COMPILING_IN_LIMITED_API + sizeof(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer), __PYX_GET_STRUCT_ALIGNMENT_3_2_4(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer), + #else + sizeof(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer), __PYX_GET_STRUCT_ALIGNMENT_3_2_4(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer), + #endif + __Pyx_ImportType_CheckSize_Warn_3_2_4); if (!__pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer) __PYX_ERR(2, 7, __pyx_L1_error) + __pyx_vtabptr_9thriftpy2_9transport_6cybase_TCyBuffer = (struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_TCyBuffer*)__Pyx_GetVtable(__pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer); if (unlikely(!__pyx_vtabptr_9thriftpy2_9transport_6cybase_TCyBuffer)) __PYX_ERR(2, 7, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_RefNannyFinishContext(); + return 0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_RefNannyFinishContext(); + return -1; +} + +static int __Pyx_modinit_variable_import_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_modinit_variable_import_code", 0); + /*--- Variable import code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_modinit_function_import_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_modinit_function_import_code", 0); + /*--- Function import code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +#if CYTHON_PEP489_MULTI_PHASE_INIT +static PyObject* __pyx_pymod_create(PyObject *spec, PyModuleDef *def); /*proto*/ +static int __pyx_pymod_exec_cymemory(PyObject* module); /*proto*/ +static PyModuleDef_Slot __pyx_moduledef_slots[] = { + {Py_mod_create, (void*)__pyx_pymod_create}, + {Py_mod_exec, (void*)__pyx_pymod_exec_cymemory}, + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + {Py_mod_gil, __Pyx_FREETHREADING_COMPATIBLE}, + #endif + #if PY_VERSION_HEX >= 0x030C0000 && CYTHON_USE_MODULE_STATE + {Py_mod_multiple_interpreters, Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED}, + #endif + {0, NULL} +}; +#endif + +#ifdef __cplusplus +namespace { + struct PyModuleDef __pyx_moduledef = + #else + static struct PyModuleDef __pyx_moduledef = + #endif + { + PyModuleDef_HEAD_INIT, + "cymemory", + 0, /* m_doc */ + #if CYTHON_USE_MODULE_STATE + sizeof(__pyx_mstatetype), /* m_size */ + #else + (CYTHON_PEP489_MULTI_PHASE_INIT) ? 0 : -1, /* m_size */ + #endif + __pyx_methods /* m_methods */, + #if CYTHON_PEP489_MULTI_PHASE_INIT + __pyx_moduledef_slots, /* m_slots */ + #else + NULL, /* m_reload */ + #endif + #if CYTHON_USE_MODULE_STATE + __pyx_m_traverse, /* m_traverse */ + __pyx_m_clear, /* m_clear */ + NULL /* m_free */ + #else + NULL, /* m_traverse */ + NULL, /* m_clear */ + NULL /* m_free */ + #endif + }; + #ifdef __cplusplus +} /* anonymous namespace */ +#endif + +/* PyModInitFuncType */ +#ifndef CYTHON_NO_PYINIT_EXPORT + #define __Pyx_PyMODINIT_FUNC PyMODINIT_FUNC +#else + #ifdef __cplusplus + #define __Pyx_PyMODINIT_FUNC extern "C" PyObject * + #else + #define __Pyx_PyMODINIT_FUNC PyObject * + #endif +#endif + +__Pyx_PyMODINIT_FUNC PyInit_cymemory(void) CYTHON_SMALL_CODE; /*proto*/ +__Pyx_PyMODINIT_FUNC PyInit_cymemory(void) +#if CYTHON_PEP489_MULTI_PHASE_INIT +{ + return PyModuleDef_Init(&__pyx_moduledef); +} +/* ModuleCreationPEP489 */ +#if CYTHON_COMPILING_IN_LIMITED_API && (__PYX_LIMITED_VERSION_HEX < 0x03090000\ + || ((defined(_WIN32) || defined(WIN32) || defined(MS_WINDOWS)) && __PYX_LIMITED_VERSION_HEX < 0x030A0000)) +static PY_INT64_T __Pyx_GetCurrentInterpreterId(void) { + { + PyObject *module = PyImport_ImportModule("_interpreters"); // 3.13+ I think + if (!module) { + PyErr_Clear(); // just try the 3.8-3.12 version + module = PyImport_ImportModule("_xxsubinterpreters"); + if (!module) goto bad; + } + PyObject *current = PyObject_CallMethod(module, "get_current", NULL); + Py_DECREF(module); + if (!current) goto bad; + if (PyTuple_Check(current)) { + PyObject *new_current = PySequence_GetItem(current, 0); + Py_DECREF(current); + current = new_current; + if (!new_current) goto bad; + } + long long as_c_int = PyLong_AsLongLong(current); + Py_DECREF(current); + return as_c_int; + } + bad: + PySys_WriteStderr("__Pyx_GetCurrentInterpreterId failed. Try setting the C define CYTHON_PEP489_MULTI_PHASE_INIT=0\n"); + return -1; +} +#endif +#if !CYTHON_USE_MODULE_STATE +static CYTHON_SMALL_CODE int __Pyx_check_single_interpreter(void) { + static PY_INT64_T main_interpreter_id = -1; +#if CYTHON_COMPILING_IN_GRAAL && defined(GRAALPY_VERSION_NUM) && GRAALPY_VERSION_NUM > 0x19000000 + PY_INT64_T current_id = GraalPyInterpreterState_GetIDFromThreadState(PyThreadState_Get()); +#elif CYTHON_COMPILING_IN_GRAAL + PY_INT64_T current_id = PyInterpreterState_GetIDFromThreadState(PyThreadState_Get()); +#elif CYTHON_COMPILING_IN_LIMITED_API && (__PYX_LIMITED_VERSION_HEX < 0x03090000\ + || ((defined(_WIN32) || defined(WIN32) || defined(MS_WINDOWS)) && __PYX_LIMITED_VERSION_HEX < 0x030A0000)) + PY_INT64_T current_id = __Pyx_GetCurrentInterpreterId(); +#elif CYTHON_COMPILING_IN_LIMITED_API + PY_INT64_T current_id = PyInterpreterState_GetID(PyInterpreterState_Get()); +#else + PY_INT64_T current_id = PyInterpreterState_GetID(PyThreadState_Get()->interp); +#endif + if (unlikely(current_id == -1)) { + return -1; + } + if (main_interpreter_id == -1) { + main_interpreter_id = current_id; + return 0; + } else if (unlikely(main_interpreter_id != current_id)) { + PyErr_SetString( + PyExc_ImportError, + "Interpreter change detected - this module can only be loaded into one interpreter per process."); + return -1; + } + return 0; +} +#endif +static CYTHON_SMALL_CODE int __Pyx_copy_spec_to_module(PyObject *spec, PyObject *moddict, const char* from_name, const char* to_name, int allow_none) +{ + PyObject *value = PyObject_GetAttrString(spec, from_name); + int result = 0; + if (likely(value)) { + if (allow_none || value != Py_None) { + result = PyDict_SetItemString(moddict, to_name, value); + } + Py_DECREF(value); + } else if (PyErr_ExceptionMatches(PyExc_AttributeError)) { + PyErr_Clear(); + } else { + result = -1; + } + return result; +} +static CYTHON_SMALL_CODE PyObject* __pyx_pymod_create(PyObject *spec, PyModuleDef *def) { + PyObject *module = NULL, *moddict, *modname; + CYTHON_UNUSED_VAR(def); + #if !CYTHON_USE_MODULE_STATE + if (__Pyx_check_single_interpreter()) + return NULL; + #endif + if (__pyx_m) + return __Pyx_NewRef(__pyx_m); + modname = PyObject_GetAttrString(spec, "name"); + if (unlikely(!modname)) goto bad; + module = PyModule_NewObject(modname); + Py_DECREF(modname); + if (unlikely(!module)) goto bad; + moddict = PyModule_GetDict(module); + if (unlikely(!moddict)) goto bad; + if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "loader", "__loader__", 1) < 0)) goto bad; + if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "origin", "__file__", 1) < 0)) goto bad; + if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "parent", "__package__", 1) < 0)) goto bad; + if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "submodule_search_locations", "__path__", 0) < 0)) goto bad; + return module; +bad: + Py_XDECREF(module); + return NULL; +} + + +static CYTHON_SMALL_CODE int __pyx_pymod_exec_cymemory(PyObject *__pyx_pyinit_module) +#endif +{ + int stringtab_initialized = 0; + #if CYTHON_USE_MODULE_STATE + int pystate_addmodule_run = 0; + #endif + __pyx_mstatetype *__pyx_mstate = NULL; + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannyDeclarations + #if CYTHON_PEP489_MULTI_PHASE_INIT + if (__pyx_m) { + if (__pyx_m == __pyx_pyinit_module) return 0; + PyErr_SetString(PyExc_RuntimeError, "Module 'cymemory' has already been imported. Re-initialisation is not supported."); + return -1; + } + #else + if (__pyx_m) return __Pyx_NewRef(__pyx_m); + #endif + /*--- Module creation code ---*/ + #if CYTHON_PEP489_MULTI_PHASE_INIT + __pyx_t_1 = __pyx_pyinit_module; + Py_INCREF(__pyx_t_1); + #else + __pyx_t_1 = PyModule_Create(&__pyx_moduledef); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1, __pyx_L1_error) + #endif + #if CYTHON_USE_MODULE_STATE + { + int add_module_result = __Pyx_State_AddModule(__pyx_t_1, &__pyx_moduledef); + __pyx_t_1 = 0; /* transfer ownership from __pyx_t_1 to "cymemory" pseudovariable */ + if (unlikely((add_module_result < 0))) __PYX_ERR(0, 1, __pyx_L1_error) + pystate_addmodule_run = 1; + } + #else + __pyx_m = __pyx_t_1; + #endif + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + PyUnstable_Module_SetGIL(__pyx_m, Py_MOD_GIL_NOT_USED); + #endif + __pyx_mstate = __pyx_mstate_global; + CYTHON_UNUSED_VAR(__pyx_t_1); + __pyx_mstate->__pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_mstate->__pyx_d)) __PYX_ERR(0, 1, __pyx_L1_error) + Py_INCREF(__pyx_mstate->__pyx_d); + __pyx_mstate->__pyx_b = __Pyx_PyImport_AddModuleRef(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_mstate->__pyx_b)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_mstate->__pyx_cython_runtime = __Pyx_PyImport_AddModuleRef("cython_runtime"); if (unlikely(!__pyx_mstate->__pyx_cython_runtime)) __PYX_ERR(0, 1, __pyx_L1_error) + if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_mstate->__pyx_b) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + /* ImportRefnannyAPI */ + #if CYTHON_REFNANNY + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); + if (!__Pyx_RefNanny) { + PyErr_Clear(); + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); + if (!__Pyx_RefNanny) + Py_FatalError("failed to import 'refnanny' module"); + } + #endif + +__Pyx_RefNannySetupContext("PyInit_cymemory", 0); + __Pyx_init_runtime_version(); + if (__Pyx_check_binary_version(__PYX_LIMITED_VERSION_HEX, __Pyx_get_runtime_version(), CYTHON_COMPILING_IN_LIMITED_API) < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_mstate->__pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_mstate->__pyx_empty_tuple)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_mstate->__pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_mstate->__pyx_empty_bytes)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_mstate->__pyx_empty_unicode = PyUnicode_FromStringAndSize("", 0); if (unlikely(!__pyx_mstate->__pyx_empty_unicode)) __PYX_ERR(0, 1, __pyx_L1_error) + /*--- Library function declarations ---*/ + /*--- Initialize various global constants etc. ---*/ + if (__Pyx_InitConstants(__pyx_mstate) < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + stringtab_initialized = 1; + if (__Pyx_InitGlobals() < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + if (__pyx_module_is_main_thriftpy2__transport__memory__cymemory) { + if (PyObject_SetAttr(__pyx_m, __pyx_mstate_global->__pyx_n_u_name, __pyx_mstate_global->__pyx_n_u_main) < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + } + { + PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) __PYX_ERR(0, 1, __pyx_L1_error) + if (!PyDict_GetItemString(modules, "thriftpy2.transport.memory.cymemory")) { + if (unlikely((PyDict_SetItemString(modules, "thriftpy2.transport.memory.cymemory", __pyx_m) < 0))) __PYX_ERR(0, 1, __pyx_L1_error) + } + } + /*--- Builtin init code ---*/ + if (__Pyx_InitCachedBuiltins(__pyx_mstate) < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + /*--- Constants init code ---*/ + if (__Pyx_InitCachedConstants(__pyx_mstate) < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + if (__Pyx_CreateCodeObjects(__pyx_mstate) < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + /*--- Global type/function init code ---*/ + (void)__Pyx_modinit_global_init_code(__pyx_mstate); + (void)__Pyx_modinit_variable_export_code(__pyx_mstate); + (void)__Pyx_modinit_function_export_code(__pyx_mstate); + if (unlikely((__Pyx_modinit_type_init_code(__pyx_mstate) < 0))) __PYX_ERR(0, 1, __pyx_L1_error) + if (unlikely((__Pyx_modinit_type_import_code(__pyx_mstate) < 0))) __PYX_ERR(0, 1, __pyx_L1_error) + (void)__Pyx_modinit_variable_import_code(__pyx_mstate); + (void)__Pyx_modinit_function_import_code(__pyx_mstate); + /*--- Execution code ---*/ + + /* "thriftpy2/transport/memory/cymemory.pyx":15 + * cdef TCyBuffer buf + * + * def __init__(self, value=b'', int buf_size=DEFAULT_BUFFER): # <<<<<<<<<<<<<< + * self.trans = None + * self.buf = TCyBuffer(buf_size) +*/ + __pyx_mstate_global->__pyx_k__2 = __pyx_e_9thriftpy2_9transport_6cybase_DEFAULT_BUFFER; + + /* "thriftpy2/transport/memory/cymemory.pyx":58 + * self.buf.write(sz, value) + * + * def read(self, sz): # <<<<<<<<<<<<<< + * return self.get_string(sz) + * +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_3read, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_TCyMemoryBuffer_read, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_transport_memory_cymem, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[0])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 58, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_2); + #endif + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer, __pyx_mstate_global->__pyx_n_u_read, __pyx_t_2) < (0)) __PYX_ERR(0, 58, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/transport/memory/cymemory.pyx":61 + * return self.get_string(sz) + * + * def write(self, data): # <<<<<<<<<<<<<< + * if isinstance(data, unicode): + * data = (data).encode('utf-8') +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_5write, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_TCyMemoryBuffer_write, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_transport_memory_cymem, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[1])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 61, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_2); + #endif + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer, __pyx_mstate_global->__pyx_n_u_write, __pyx_t_2) < (0)) __PYX_ERR(0, 61, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/transport/memory/cymemory.pyx":68 + * return self.c_write(data, sz) + * + * def is_open(self): # <<<<<<<<<<<<<< + * return True + * +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_7is_open, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_TCyMemoryBuffer_is_open, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_transport_memory_cymem, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[2])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 68, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_2); + #endif + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer, __pyx_mstate_global->__pyx_n_u_is_open, __pyx_t_2) < (0)) __PYX_ERR(0, 68, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/transport/memory/cymemory.pyx":71 + * return True + * + * def open(self): # <<<<<<<<<<<<<< + * pass + * +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_9open, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_TCyMemoryBuffer_open, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_transport_memory_cymem, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[3])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 71, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_2); + #endif + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer, __pyx_mstate_global->__pyx_n_u_open, __pyx_t_2) < (0)) __PYX_ERR(0, 71, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/transport/memory/cymemory.pyx":74 + * pass + * + * def close(self): # <<<<<<<<<<<<<< + * pass + * +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_11close, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_TCyMemoryBuffer_close, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_transport_memory_cymem, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[4])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 74, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_2); + #endif + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer, __pyx_mstate_global->__pyx_n_u_close, __pyx_t_2) < (0)) __PYX_ERR(0, 74, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/transport/memory/cymemory.pyx":77 + * pass + * + * def flush(self): # <<<<<<<<<<<<<< + * pass + * +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_13flush, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_TCyMemoryBuffer_flush, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_transport_memory_cymem, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[5])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 77, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_2); + #endif + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer, __pyx_mstate_global->__pyx_n_u_flush, __pyx_t_2) < (0)) __PYX_ERR(0, 77, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/transport/memory/cymemory.pyx":80 + * pass + * + * def clean(self): # <<<<<<<<<<<<<< + * self.buf.clean() + * +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_15clean, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_TCyMemoryBuffer_clean, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_transport_memory_cymem, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[6])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 80, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_2); + #endif + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer, __pyx_mstate_global->__pyx_n_u_clean, __pyx_t_2) < (0)) __PYX_ERR(0, 80, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/transport/memory/cymemory.pyx":83 + * self.buf.clean() + * + * def getvalue(self): # <<<<<<<<<<<<<< + * return self._getvalue() + * +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_17getvalue, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_TCyMemoryBuffer_getvalue, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_transport_memory_cymem, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[7])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 83, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_2); + #endif + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer, __pyx_mstate_global->__pyx_n_u_getvalue, __pyx_t_2) < (0)) __PYX_ERR(0, 83, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/transport/memory/cymemory.pyx":86 + * return self._getvalue() + * + * def setvalue(self, value): # <<<<<<<<<<<<<< + * if isinstance(value, unicode): + * value = (value).encode('utf-8') +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_19setvalue, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_TCyMemoryBuffer_setvalue, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_transport_memory_cymem, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[8])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 86, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_2); + #endif + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer, __pyx_mstate_global->__pyx_n_u_setvalue, __pyx_t_2) < (0)) __PYX_ERR(0, 86, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * cdef tuple state + * cdef object _dict +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_21__reduce_cython__, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_TCyMemoryBuffer___reduce_cython, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_transport_memory_cymem, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[9])); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 1, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_2); + #endif + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer, __pyx_mstate_global->__pyx_n_u_reduce_cython, __pyx_t_2) < (0)) __PYX_ERR(1, 1, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "(tree fragment)":16 + * else: + * return __pyx_unpickle_TCyMemoryBuffer, (type(self), 0x969e82f, state) + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * __pyx_unpickle_TCyMemoryBuffer__set_state(self, __pyx_state) +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_9transport_6memory_8cymemory_15TCyMemoryBuffer_23__setstate_cython__, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_TCyMemoryBuffer___setstate_cytho, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_transport_memory_cymem, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[10])); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 16, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_2); + #endif + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6memory_8cymemory_TCyMemoryBuffer, __pyx_mstate_global->__pyx_n_u_setstate_cython, __pyx_t_2) < (0)) __PYX_ERR(1, 16, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "(tree fragment)":4 + * int __Pyx_CheckUnpickleChecksum(long, long, long, long, const char*) except -1 + * int __Pyx_UpdateUnpickledDict(object, object, Py_ssize_t) except -1 + * def __pyx_unpickle_TCyMemoryBuffer(__pyx_type, long __pyx_checksum, tuple __pyx_state): # <<<<<<<<<<<<<< + * cdef object __pyx_result + * __Pyx_CheckUnpickleChecksum(__pyx_checksum, 0x969e82f, 0x5876d04, 0xfcd695e, b'buf, trans') +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_9transport_6memory_8cymemory_1__pyx_unpickle_TCyMemoryBuffer, 0, __pyx_mstate_global->__pyx_n_u_pyx_unpickle_TCyMemoryBuffer, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_transport_memory_cymem, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[11])); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 4, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_2); + #endif + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_pyx_unpickle_TCyMemoryBuffer, __pyx_t_2) < (0)) __PYX_ERR(1, 4, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/transport/memory/cymemory.pyx":1 + * # cython: freethreading_compatible = True # <<<<<<<<<<<<<< + * + * from libc.string cimport memcpy +*/ + __pyx_t_2 = __Pyx_PyDict_NewPresized(0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_test, __pyx_t_2) < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /*--- Wrapped vars code ---*/ + + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + if (__pyx_m) { + if (__pyx_mstate->__pyx_d && stringtab_initialized) { + __Pyx_AddTraceback("init thriftpy2.transport.memory.cymemory", __pyx_clineno, __pyx_lineno, __pyx_filename); + } + #if !CYTHON_USE_MODULE_STATE + Py_CLEAR(__pyx_m); + #else + Py_DECREF(__pyx_m); + if (pystate_addmodule_run) { + PyObject *tp, *value, *tb; + PyErr_Fetch(&tp, &value, &tb); + PyState_RemoveModule(&__pyx_moduledef); + PyErr_Restore(tp, value, tb); + } + #endif + } else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_ImportError, "init thriftpy2.transport.memory.cymemory"); + } + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + #if CYTHON_PEP489_MULTI_PHASE_INIT + return (__pyx_m != NULL) ? 0 : -1; + #else + return __pyx_m; + #endif +} +/* #### Code section: pystring_table ### */ +/* #### Code section: cached_builtins ### */ + +static int __Pyx_InitCachedBuiltins(__pyx_mstatetype *__pyx_mstate) { + CYTHON_UNUSED_VAR(__pyx_mstate); + + /* Cached unbound methods */ + __pyx_mstate->__pyx_umethod_PyDict_Type_items.type = (PyObject*)&PyDict_Type; + __pyx_mstate->__pyx_umethod_PyDict_Type_items.method_name = &__pyx_mstate->__pyx_n_u_items; + __pyx_mstate->__pyx_umethod_PyDict_Type_pop.type = (PyObject*)&PyDict_Type; + __pyx_mstate->__pyx_umethod_PyDict_Type_pop.method_name = &__pyx_mstate->__pyx_n_u_pop; + __pyx_mstate->__pyx_umethod_PyDict_Type_values.type = (PyObject*)&PyDict_Type; + __pyx_mstate->__pyx_umethod_PyDict_Type_values.method_name = &__pyx_mstate->__pyx_n_u_values; + return 0; +} +/* #### Code section: cached_constants ### */ + +static int __Pyx_InitCachedConstants(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); + __Pyx_RefNannyFinishContext(); + return 0; +} +/* #### Code section: init_constants ### */ + +static int __Pyx_InitConstants(__pyx_mstatetype *__pyx_mstate) { + CYTHON_UNUSED_VAR(__pyx_mstate); + { + const struct { const unsigned int length: 8; } index[] = {{179},{21},{1},{8},{7},{6},{2},{9},{14},{39},{20},{15},{33},{35},{21},{21},{21},{24},{23},{20},{20},{24},{21},{18},{8},{5},{18},{5},{4},{8},{5},{5},{8},{12},{8},{13},{7},{5},{8},{10},{8},{7},{4},{3},{14},{12},{11},{10},{30},{14},{12},{4},{10},{17},{13},{4},{12},{10},{12},{19},{8},{5},{2},{8},{35},{6},{12},{5},{6},{5},{0},{2},{11},{48},{41},{7},{11},{13},{11},{111},{57}}; + #if (CYTHON_COMPRESS_STRINGS) == 2 /* compression: bz2 (880 bytes) */ +const char* const cstring = "BZh91AY&SY\010\203\232\372\000\000y\177\377\347\315\277\200\340\307\366\335\277\273~\240\277\377\377\364@@@@@@@@@@@@@\000@\000@\002\365\260P\003\030i#\022\231\036D\366\251\345\017H\r\003!\241\243M\032\032\000hmCM\244\365\033Shj=A(@A=\021\225=\251\251\344\024\362mP4\332\231\000\032\000\000\000zM=M\247\221\010\247\246\212d\036\241\3524\230\3224\323L\001\006\0041\014\200\3010\023\010\310\031\01642i\246M\000\014\020\006\203&\200\001\223@\000\000\311\220\r#\361\001\322\233\304\354^\262=U'\233\266 IEUW\326M\3039m\355\030O>\351v\035\214\304\231vL\017ndP\322\207{\336*x\220\306\004-t\3508\300\316R\353\004\246k\312t\3122\327\252#p\242\377\002R\360\001J2\312\023\010u\t\210\246\002w%N\324\320\231\3005b\261\327\343\34119\003\006\236\3568>|\352*QR\252 \237\262\t\242\016\267\035U\305g\014^\367\\M\004\364\376\036o\262o2\262\262\214;\273\372~\275\311\234\271t\253\032\233\232\030\333\265\265\227\300\nnd\251@k\006\003\310\317\005Xt\302\217\347\335\327\3278\030.\031\351\203\342\372otm\210PU\024W\324\361\302\020T \2659\211\262\251!\242\265\365L\374\363x?\215\342M0\221\305\341\260\307q\010\341z\021VS\rF\315\275\265g<\373\003,\372)\020\206\247\373n\235Z\215\215\026\3376\210@\374\210\340\n]\000\334\0314\022\200\365\200\024,\025`\241\241g\220Y\006\203\210N\205\222p\"\021\027\215\227\310\231\030\327\311\r\364\224\347\000\255\374\3703\237\027\3070\177\350\"\265\267\021\261\207\361\240\232\361\211\013c\2432\264\003b\242\252\2539a\247\314\354\272\251\204\332\344\021\220Mr\341+\331\351z\364\257\346\252O\225\345i\302\240S\037\373^\225Si\341\025\374\r\337\314'RF\325g\214\375\352\357,\314\335\\\230\273y\355\351\271\271M\352[\017F\301\"i\231\250\312V\016t\324\036\265\213\372\372x\317\336\262$\300\265\361\013\333\261\261k\027\353\367\354[\367q\262\225o\346\215\253\372}K\335\246k\024\365\215\261\266;\256\345\366'\215\377\370=\327)\326\177\262\237\\\017\252[\323\315\331\223\275\313\203\331\321\237Emm\334\372\027$'\033\234"; + PyObject *data = __Pyx_DecompressString(cstring, 777, 1); + if (unlikely(!data)) __PYX_ERR(0, 1, __pyx_L1_error) + const char* const bytes = __Pyx_PyBytes_AsString(data); + #if !CYTHON_ASSUME_SAFE_MACROS + if (likely(bytes)); else { Py_DECREF(data); __PYX_ERR(0, 1, __pyx_L1_error) } + #endif + #else /* compression: none (1361 bytes) */ +const char* const bytes = "Note that Cython is deliberately stricter than PEP-484 and rejects subclasses of builtin types. If you need to pass subclasses then set the 'annotation_typing' directive to False.Write to memory error?add_notedisableenablegcisenabledthriftpy2/transport/memory/cymemory.pyx__Pyx_PyDict_NextRefTCyMemoryBufferTCyMemoryBuffer.__reduce_cython__TCyMemoryBuffer.__setstate_cython__TCyMemoryBuffer.cleanTCyMemoryBuffer.closeTCyMemoryBuffer.flushTCyMemoryBuffer.getvalueTCyMemoryBuffer.is_openTCyMemoryBuffer.openTCyMemoryBuffer.readTCyMemoryBuffer.setvalueTCyMemoryBuffer.writeasyncio.coroutinesbuf_sizecleancline_in_tracebackclosedata__dict___dictflush__func____getstate__getvalue_is_coroutineis_openitems__main____module____name____new__openpop__pyx_checksum__pyx_result__pyx_state__pyx_type__pyx_unpickle_TCyMemoryBuffer__pyx_vtable____qualname__read__reduce____reduce_cython____reduce_ex__self__set_name__setdefault__setstate____setstate_cython__setvaluestatesz__test__thriftpy2.transport.memory.cymemoryupdateuse_setstatevaluevalueswrite\200A\200A\330\010\014\210D\220\006\220a\200A\330\010\013\210:\220Q\220f\230A\330\014\024\220I\230U\240'\250\021\250!\340\010\026\220c\230\021\230!\330\010\017\210t\2208\2301\230F\240!\200A\330\010\013\210:\220Q\220g\230Q\330\014\025\220Y\230f\240G\2501\250A\330\010\014\210J\220a\220s\230!\2308\2401\200A\330\010\017\210q\200A\330\010\017\210t\220:\230Q\200A\330\010\017\210t\220;\230a\230q\200\001\330\004-\250Q\250f\260A\200\001\360\010\000\005\016\210T\220\026\220t\2301\330\004\014\210G\2201\220F\230,\240a\330\004\007\200v\210W\220E\230\024\230Q\330\010\022\220!\330\010\027\220q\340\010\027\220t\2305\240\007\240u\250C\250t\2607\270'\300\021\330\004\007\200q\330\010\017\320\0170\260\004\260A\260W\270K\300w\310a\340\010\017\320\0170\260\004\260A\260W\270K\300q\200\001\340\004\037\230q\320 0\260\013\270;\300k\320QR\330\004\023\220?\240(\250!\2501\330\004\007\200|\2207\230!\330\0101\260\021\3202D\300N\320RS\330\004\013\2101"; + PyObject *data = NULL; + CYTHON_UNUSED_VAR(__Pyx_DecompressString); + #endif + PyObject **stringtab = __pyx_mstate->__pyx_string_tab; + Py_ssize_t pos = 0; + for (int i = 0; i < 70; i++) { + Py_ssize_t bytes_length = index[i].length; + PyObject *string = PyUnicode_DecodeUTF8(bytes + pos, bytes_length, NULL); + if (likely(string) && i >= 10) PyUnicode_InternInPlace(&string); + if (unlikely(!string)) { + Py_XDECREF(data); + __PYX_ERR(0, 1, __pyx_L1_error) + } + stringtab[i] = string; + pos += bytes_length; + } + for (int i = 70; i < 81; i++) { + Py_ssize_t bytes_length = index[i].length; + PyObject *string = PyBytes_FromStringAndSize(bytes + pos, bytes_length); + stringtab[i] = string; + pos += bytes_length; + if (unlikely(!string)) { + Py_XDECREF(data); + __PYX_ERR(0, 1, __pyx_L1_error) + } + } + Py_XDECREF(data); + for (Py_ssize_t i = 0; i < 81; i++) { + if (unlikely(PyObject_Hash(stringtab[i]) == -1)) { + __PYX_ERR(0, 1, __pyx_L1_error) + } + } + #if CYTHON_IMMORTAL_CONSTANTS + { + PyObject **table = stringtab + 70; + for (Py_ssize_t i=0; i<11; ++i) { + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + #if PY_VERSION_HEX < 0x030E0000 + if (_Py_IsOwnedByCurrentThread(table[i]) && Py_REFCNT(table[i]) == 1) + #else + if (PyUnstable_Object_IsUniquelyReferenced(table[i])) + #endif + { + Py_SET_REFCNT(table[i], _Py_IMMORTAL_REFCNT_LOCAL); + } + #else + Py_SET_REFCNT(table[i], _Py_IMMORTAL_INITIAL_REFCNT); + #endif + } + } + #endif + } + { + PyObject **numbertab = __pyx_mstate->__pyx_number_tab + 0; + int32_t const cint_constants_4[] = {157935663L}; + for (int i = 0; i < 1; i++) { + numbertab[i] = PyLong_FromLong(cint_constants_4[i - 0]); + if (unlikely(!numbertab[i])) __PYX_ERR(0, 1, __pyx_L1_error) + } + } + #if CYTHON_IMMORTAL_CONSTANTS + { + PyObject **table = __pyx_mstate->__pyx_number_tab; + for (Py_ssize_t i=0; i<1; ++i) { + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + #if PY_VERSION_HEX < 0x030E0000 + if (_Py_IsOwnedByCurrentThread(table[i]) && Py_REFCNT(table[i]) == 1) + #else + if (PyUnstable_Object_IsUniquelyReferenced(table[i])) + #endif + { + Py_SET_REFCNT(table[i], _Py_IMMORTAL_REFCNT_LOCAL); + } + #else + Py_SET_REFCNT(table[i], _Py_IMMORTAL_INITIAL_REFCNT); + #endif + } + } + #endif + return 0; + __pyx_L1_error:; + return -1; +} +/* #### Code section: init_codeobjects ### */ +typedef struct { + unsigned int argcount : 2; + unsigned int num_posonly_args : 1; + unsigned int num_kwonly_args : 1; + unsigned int nlocals : 3; + unsigned int flags : 10; + unsigned int first_line : 7; +} __Pyx_PyCode_New_function_description; +/* NewCodeObj.proto */ +static PyObject* __Pyx_PyCode_New( + const __Pyx_PyCode_New_function_description descr, + PyObject * const *varnames, + PyObject *filename, + PyObject *funcname, + PyObject *line_table, + PyObject *tuple_dedup_map +); + + +static int __Pyx_CreateCodeObjects(__pyx_mstatetype *__pyx_mstate) { + PyObject* tuple_dedup_map = PyDict_New(); + if (unlikely(!tuple_dedup_map)) return -1; + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 58}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_sz}; + __pyx_mstate_global->__pyx_codeobj_tab[0] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_thriftpy2_transport_memory_cymem_2, __pyx_mstate->__pyx_n_u_read, __pyx_mstate->__pyx_kp_b_iso88591_A_t_aq, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[0])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 3, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 61}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_data, __pyx_mstate->__pyx_n_u_sz}; + __pyx_mstate_global->__pyx_codeobj_tab[1] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_thriftpy2_transport_memory_cymem_2, __pyx_mstate->__pyx_n_u_write, __pyx_mstate->__pyx_kp_b_iso88591_A_QfA_IU_c_t81F, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[1])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 68}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[2] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_thriftpy2_transport_memory_cymem_2, __pyx_mstate->__pyx_n_u_is_open, __pyx_mstate->__pyx_kp_b_iso88591_A_q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[2])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 71}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[3] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_thriftpy2_transport_memory_cymem_2, __pyx_mstate->__pyx_n_u_open, __pyx_mstate->__pyx_kp_b_iso88591_A, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[3])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 74}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[4] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_thriftpy2_transport_memory_cymem_2, __pyx_mstate->__pyx_n_u_close, __pyx_mstate->__pyx_kp_b_iso88591_A, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[4])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 77}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[5] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_thriftpy2_transport_memory_cymem_2, __pyx_mstate->__pyx_n_u_flush, __pyx_mstate->__pyx_kp_b_iso88591_A, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[5])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 80}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[6] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_thriftpy2_transport_memory_cymem_2, __pyx_mstate->__pyx_n_u_clean, __pyx_mstate->__pyx_kp_b_iso88591_A_D_a, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[6])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 83}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[7] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_thriftpy2_transport_memory_cymem_2, __pyx_mstate->__pyx_n_u_getvalue, __pyx_mstate->__pyx_kp_b_iso88591_A_t_Q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[7])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 86}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_value}; + __pyx_mstate_global->__pyx_codeobj_tab[8] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_thriftpy2_transport_memory_cymem_2, __pyx_mstate->__pyx_n_u_setvalue, __pyx_mstate->__pyx_kp_b_iso88591_A_QgQ_YfG1A_Jas_81, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[8])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 4, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 1}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_state, __pyx_mstate->__pyx_n_u_dict_2, __pyx_mstate->__pyx_n_u_use_setstate}; + __pyx_mstate_global->__pyx_codeobj_tab[9] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_stringsource, __pyx_mstate->__pyx_n_u_reduce_cython, __pyx_mstate->__pyx_kp_b_iso88591_T_t1_G1F_a_vWE_Q_q_t5_uCt7_q_0, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[9])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 16}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_pyx_state}; + __pyx_mstate_global->__pyx_codeobj_tab[10] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_stringsource, __pyx_mstate->__pyx_n_u_setstate_cython, __pyx_mstate->__pyx_kp_b_iso88591_QfA, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[10])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {3, 0, 0, 4, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 4}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_pyx_type, __pyx_mstate->__pyx_n_u_pyx_checksum, __pyx_mstate->__pyx_n_u_pyx_state, __pyx_mstate->__pyx_n_u_pyx_result}; + __pyx_mstate_global->__pyx_codeobj_tab[11] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_stringsource, __pyx_mstate->__pyx_n_u_pyx_unpickle_TCyMemoryBuffer, __pyx_mstate->__pyx_kp_b_iso88591_q_0_kQR_1_7_1_2DNRS_1, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[11])) goto bad; + } + Py_DECREF(tuple_dedup_map); + return 0; + bad: + Py_DECREF(tuple_dedup_map); + return -1; +} +/* #### Code section: init_globals ### */ + +static int __Pyx_InitGlobals(void) { + /* PythonCompatibility.init */ + if (likely(__Pyx_init_co_variables() == 0)); else + + if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 1, __pyx_L1_error) + + /* CommonTypesMetaclass.init */ + if (likely(__pyx_CommonTypesMetaclass_init(__pyx_m) == 0)); else + + if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 1, __pyx_L1_error) + + /* CachedMethodType.init */ + #if CYTHON_COMPILING_IN_LIMITED_API + { + PyObject *typesModule=NULL; + typesModule = PyImport_ImportModule("types"); + if (typesModule) { + __pyx_mstate_global->__Pyx_CachedMethodType = PyObject_GetAttrString(typesModule, "MethodType"); + Py_DECREF(typesModule); + } + } // error handling follows + #endif + + if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 1, __pyx_L1_error) + + /* CythonFunctionShared.init */ + if (likely(__pyx_CyFunction_init(__pyx_m) == 0)); else + + if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 1, __pyx_L1_error) + + return 0; + __pyx_L1_error:; + return -1; +} +/* #### Code section: cleanup_globals ### */ +/* #### Code section: cleanup_module ### */ +/* #### Code section: main_method ### */ +/* #### Code section: utility_code_pragmas ### */ +#ifdef _MSC_VER +#pragma warning( push ) +/* Warning 4127: conditional expression is constant + * Cython uses constant conditional expressions to allow in inline functions to be optimized at + * compile-time, so this warning is not useful + */ +#pragma warning( disable : 4127 ) +#endif + + + +/* #### Code section: utility_code_def ### */ + +/* --- Runtime support code --- */ +/* Refnanny */ +#if CYTHON_REFNANNY +static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { + PyObject *m = NULL, *p = NULL; + void *r = NULL; + m = PyImport_ImportModule(modname); + if (!m) goto end; + p = PyObject_GetAttrString(m, "RefNannyAPI"); + if (!p) goto end; + r = PyLong_AsVoidPtr(p); +end: + Py_XDECREF(p); + Py_XDECREF(m); + return (__Pyx_RefNannyAPIStruct *)r; +} +#endif + +/* TupleAndListFromArray (used by fastcall) */ +#if !CYTHON_COMPILING_IN_CPYTHON && CYTHON_METH_FASTCALL +static CYTHON_INLINE PyObject * +__Pyx_PyTuple_FromArray(PyObject *const *src, Py_ssize_t n) +{ + PyObject *res; + Py_ssize_t i; + if (n <= 0) { + return __Pyx_NewRef(__pyx_mstate_global->__pyx_empty_tuple); + } + res = PyTuple_New(n); + if (unlikely(res == NULL)) return NULL; + for (i = 0; i < n; i++) { + if (unlikely(__Pyx_PyTuple_SET_ITEM(res, i, src[i]) < (0))) { + Py_DECREF(res); + return NULL; + } + Py_INCREF(src[i]); + } + return res; +} +#elif CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE void __Pyx_copy_object_array(PyObject *const *CYTHON_RESTRICT src, PyObject** CYTHON_RESTRICT dest, Py_ssize_t length) { + PyObject *v; + Py_ssize_t i; + for (i = 0; i < length; i++) { + v = dest[i] = src[i]; + Py_INCREF(v); + } +} +static CYTHON_INLINE PyObject * +__Pyx_PyTuple_FromArray(PyObject *const *src, Py_ssize_t n) +{ + PyObject *res; + if (n <= 0) { + return __Pyx_NewRef(__pyx_mstate_global->__pyx_empty_tuple); + } + res = PyTuple_New(n); + if (unlikely(res == NULL)) return NULL; + __Pyx_copy_object_array(src, ((PyTupleObject*)res)->ob_item, n); + return res; +} +static CYTHON_INLINE PyObject * +__Pyx_PyList_FromArray(PyObject *const *src, Py_ssize_t n) +{ + PyObject *res; + if (n <= 0) { + return PyList_New(0); + } + res = PyList_New(n); + if (unlikely(res == NULL)) return NULL; + __Pyx_copy_object_array(src, ((PyListObject*)res)->ob_item, n); + return res; +} +#endif + +/* BytesEquals (used by UnicodeEquals) */ +static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals) { +#if CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_GRAAL ||\ + !(CYTHON_ASSUME_SAFE_SIZE && CYTHON_ASSUME_SAFE_MACROS) + return PyObject_RichCompareBool(s1, s2, equals); +#else + if (s1 == s2) { + return (equals == Py_EQ); + } else if (PyBytes_CheckExact(s1) & PyBytes_CheckExact(s2)) { + const char *ps1, *ps2; + Py_ssize_t length = PyBytes_GET_SIZE(s1); + if (length != PyBytes_GET_SIZE(s2)) + return (equals == Py_NE); + ps1 = PyBytes_AS_STRING(s1); + ps2 = PyBytes_AS_STRING(s2); + if (ps1[0] != ps2[0]) { + return (equals == Py_NE); + } else if (length == 1) { + return (equals == Py_EQ); + } else { + int result; +#if CYTHON_USE_UNICODE_INTERNALS && (PY_VERSION_HEX < 0x030B0000) + Py_hash_t hash1, hash2; + hash1 = ((PyBytesObject*)s1)->ob_shash; + hash2 = ((PyBytesObject*)s2)->ob_shash; + if (hash1 != hash2 && hash1 != -1 && hash2 != -1) { + return (equals == Py_NE); + } +#endif + result = memcmp(ps1, ps2, (size_t)length); + return (equals == Py_EQ) ? (result == 0) : (result != 0); + } + } else if ((s1 == Py_None) & PyBytes_CheckExact(s2)) { + return (equals == Py_NE); + } else if ((s2 == Py_None) & PyBytes_CheckExact(s1)) { + return (equals == Py_NE); + } else { + int result; + PyObject* py_result = PyObject_RichCompare(s1, s2, equals); + if (!py_result) + return -1; + result = __Pyx_PyObject_IsTrue(py_result); + Py_DECREF(py_result); + return result; + } +#endif +} + +/* UnicodeEquals (used by fastcall) */ +static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals) { +#if CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_GRAAL + return PyObject_RichCompareBool(s1, s2, equals); +#else + int s1_is_unicode, s2_is_unicode; + if (s1 == s2) { + goto return_eq; + } + s1_is_unicode = PyUnicode_CheckExact(s1); + s2_is_unicode = PyUnicode_CheckExact(s2); + if (s1_is_unicode & s2_is_unicode) { + Py_ssize_t length, length2; + int kind; + void *data1, *data2; + #if !CYTHON_COMPILING_IN_LIMITED_API + if (unlikely(__Pyx_PyUnicode_READY(s1) < 0) || unlikely(__Pyx_PyUnicode_READY(s2) < 0)) + return -1; + #endif + length = __Pyx_PyUnicode_GET_LENGTH(s1); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(length < 0)) return -1; + #endif + length2 = __Pyx_PyUnicode_GET_LENGTH(s2); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(length2 < 0)) return -1; + #endif + if (length != length2) { + goto return_ne; + } +#if CYTHON_USE_UNICODE_INTERNALS + { + Py_hash_t hash1, hash2; + hash1 = ((PyASCIIObject*)s1)->hash; + hash2 = ((PyASCIIObject*)s2)->hash; + if (hash1 != hash2 && hash1 != -1 && hash2 != -1) { + goto return_ne; + } + } +#endif + kind = __Pyx_PyUnicode_KIND(s1); + if (kind != __Pyx_PyUnicode_KIND(s2)) { + goto return_ne; + } + data1 = __Pyx_PyUnicode_DATA(s1); + data2 = __Pyx_PyUnicode_DATA(s2); + if (__Pyx_PyUnicode_READ(kind, data1, 0) != __Pyx_PyUnicode_READ(kind, data2, 0)) { + goto return_ne; + } else if (length == 1) { + goto return_eq; + } else { + int result = memcmp(data1, data2, (size_t)(length * kind)); + return (equals == Py_EQ) ? (result == 0) : (result != 0); + } + } else if ((s1 == Py_None) & s2_is_unicode) { + goto return_ne; + } else if ((s2 == Py_None) & s1_is_unicode) { + goto return_ne; + } else { + int result; + PyObject* py_result = PyObject_RichCompare(s1, s2, equals); + if (!py_result) + return -1; + result = __Pyx_PyObject_IsTrue(py_result); + Py_DECREF(py_result); + return result; + } +return_eq: + return (equals == Py_EQ); +return_ne: + return (equals == Py_NE); +#endif +} + +/* fastcall */ +#if CYTHON_METH_FASTCALL +static CYTHON_INLINE PyObject * __Pyx_GetKwValue_FASTCALL(PyObject *kwnames, PyObject *const *kwvalues, PyObject *s) +{ + Py_ssize_t i, n = __Pyx_PyTuple_GET_SIZE(kwnames); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(n == -1)) return NULL; + #endif + for (i = 0; i < n; i++) + { + PyObject *namei = __Pyx_PyTuple_GET_ITEM(kwnames, i); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(!namei)) return NULL; + #endif + if (s == namei) return kwvalues[i]; + } + for (i = 0; i < n; i++) + { + PyObject *namei = __Pyx_PyTuple_GET_ITEM(kwnames, i); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(!namei)) return NULL; + #endif + int eq = __Pyx_PyUnicode_Equals(s, namei, Py_EQ); + if (unlikely(eq != 0)) { + if (unlikely(eq < 0)) return NULL; + return kwvalues[i]; + } + } + return NULL; +} +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030d0000 || CYTHON_COMPILING_IN_LIMITED_API +CYTHON_UNUSED static PyObject *__Pyx_KwargsAsDict_FASTCALL(PyObject *kwnames, PyObject *const *kwvalues) { + Py_ssize_t i, nkwargs; + PyObject *dict; +#if !CYTHON_ASSUME_SAFE_SIZE + nkwargs = PyTuple_Size(kwnames); + if (unlikely(nkwargs < 0)) return NULL; +#else + nkwargs = PyTuple_GET_SIZE(kwnames); +#endif + dict = PyDict_New(); + if (unlikely(!dict)) + return NULL; + for (i=0; itp_call; + if (unlikely(!call)) + return PyObject_Call(func, arg, kw); + if (unlikely(Py_EnterRecursiveCall(" while calling a Python object"))) + return NULL; + result = (*call)(func, arg, kw); + Py_LeaveRecursiveCall(); + if (unlikely(!result) && unlikely(!PyErr_Occurred())) { + PyErr_SetString( + PyExc_SystemError, + "NULL result without error in PyObject_Call"); + } + return result; +} +#endif + +/* PyObjectCallMethO (used by PyObjectFastCall) */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg) { + PyObject *self, *result; + PyCFunction cfunc; + cfunc = __Pyx_CyOrPyCFunction_GET_FUNCTION(func); + self = __Pyx_CyOrPyCFunction_GET_SELF(func); + if (unlikely(Py_EnterRecursiveCall(" while calling a Python object"))) + return NULL; + result = cfunc(self, arg); + Py_LeaveRecursiveCall(); + if (unlikely(!result) && unlikely(!PyErr_Occurred())) { + PyErr_SetString( + PyExc_SystemError, + "NULL result without error in PyObject_Call"); + } + return result; +} +#endif + +/* PyObjectFastCall (used by PyObjectCallOneArg) */ +#if PY_VERSION_HEX < 0x03090000 || CYTHON_COMPILING_IN_LIMITED_API +static PyObject* __Pyx_PyObject_FastCall_fallback(PyObject *func, PyObject * const*args, size_t nargs, PyObject *kwargs) { + PyObject *argstuple; + PyObject *result = 0; + size_t i; + argstuple = PyTuple_New((Py_ssize_t)nargs); + if (unlikely(!argstuple)) return NULL; + for (i = 0; i < nargs; i++) { + Py_INCREF(args[i]); + if (__Pyx_PyTuple_SET_ITEM(argstuple, (Py_ssize_t)i, args[i]) != (0)) goto bad; + } + result = __Pyx_PyObject_Call(func, argstuple, kwargs); + bad: + Py_DECREF(argstuple); + return result; +} +#endif +#if CYTHON_VECTORCALL && !CYTHON_COMPILING_IN_LIMITED_API + #if PY_VERSION_HEX < 0x03090000 + #define __Pyx_PyVectorcall_Function(callable) _PyVectorcall_Function(callable) + #elif CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE vectorcallfunc __Pyx_PyVectorcall_Function(PyObject *callable) { + PyTypeObject *tp = Py_TYPE(callable); + #if defined(__Pyx_CyFunction_USED) + if (__Pyx_CyFunction_CheckExact(callable)) { + return __Pyx_CyFunction_func_vectorcall(callable); + } + #endif + if (!PyType_HasFeature(tp, Py_TPFLAGS_HAVE_VECTORCALL)) { + return NULL; + } + assert(PyCallable_Check(callable)); + Py_ssize_t offset = tp->tp_vectorcall_offset; + assert(offset > 0); + vectorcallfunc ptr; + memcpy(&ptr, (char *) callable + offset, sizeof(ptr)); + return ptr; +} + #else + #define __Pyx_PyVectorcall_Function(callable) PyVectorcall_Function(callable) + #endif +#endif +static CYTHON_INLINE PyObject* __Pyx_PyObject_FastCallDict(PyObject *func, PyObject *const *args, size_t _nargs, PyObject *kwargs) { + Py_ssize_t nargs = __Pyx_PyVectorcall_NARGS(_nargs); +#if CYTHON_COMPILING_IN_CPYTHON + if (nargs == 0 && kwargs == NULL) { + if (__Pyx_CyOrPyCFunction_Check(func) && likely( __Pyx_CyOrPyCFunction_GET_FLAGS(func) & METH_NOARGS)) + return __Pyx_PyObject_CallMethO(func, NULL); + } + else if (nargs == 1 && kwargs == NULL) { + if (__Pyx_CyOrPyCFunction_Check(func) && likely( __Pyx_CyOrPyCFunction_GET_FLAGS(func) & METH_O)) + return __Pyx_PyObject_CallMethO(func, args[0]); + } +#endif + if (kwargs == NULL) { + #if CYTHON_VECTORCALL + #if CYTHON_COMPILING_IN_LIMITED_API + return PyObject_Vectorcall(func, args, _nargs, NULL); + #else + vectorcallfunc f = __Pyx_PyVectorcall_Function(func); + if (f) { + return f(func, args, _nargs, NULL); + } + #endif + #endif + } + if (nargs == 0) { + return __Pyx_PyObject_Call(func, __pyx_mstate_global->__pyx_empty_tuple, kwargs); + } + #if PY_VERSION_HEX >= 0x03090000 && !CYTHON_COMPILING_IN_LIMITED_API + return PyObject_VectorcallDict(func, args, (size_t)nargs, kwargs); + #else + return __Pyx_PyObject_FastCall_fallback(func, args, (size_t)nargs, kwargs); + #endif +} + +/* PyObjectCallOneArg (used by CallUnboundCMethod0) */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { + PyObject *args[2] = {NULL, arg}; + return __Pyx_PyObject_FastCall(func, args+1, 1 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET); +} + +/* PyObjectGetAttrStr (used by UnpackUnboundCMethod) */ +#if CYTHON_USE_TYPE_SLOTS +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { + PyTypeObject* tp = Py_TYPE(obj); + if (likely(tp->tp_getattro)) + return tp->tp_getattro(obj, attr_name); + return PyObject_GetAttr(obj, attr_name); +} +#endif + +/* UnpackUnboundCMethod (used by CallUnboundCMethod0) */ +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030C0000 +static PyObject *__Pyx_SelflessCall(PyObject *method, PyObject *args, PyObject *kwargs) { + PyObject *result; + PyObject *selfless_args = PyTuple_GetSlice(args, 1, PyTuple_Size(args)); + if (unlikely(!selfless_args)) return NULL; + result = PyObject_Call(method, selfless_args, kwargs); + Py_DECREF(selfless_args); + return result; +} +#elif CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX < 0x03090000 +static PyObject *__Pyx_SelflessCall(PyObject *method, PyObject **args, Py_ssize_t nargs, PyObject *kwnames) { + return _PyObject_Vectorcall + (method, args ? args+1 : NULL, nargs ? nargs-1 : 0, kwnames); +} +#else +static PyObject *__Pyx_SelflessCall(PyObject *method, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames) { + return +#if PY_VERSION_HEX < 0x03090000 + _PyObject_Vectorcall +#else + PyObject_Vectorcall +#endif + (method, args ? args+1 : NULL, nargs ? (size_t) nargs-1 : 0, kwnames); +} +#endif +static PyMethodDef __Pyx_UnboundCMethod_Def = { + "CythonUnboundCMethod", + __PYX_REINTERPRET_FUNCION(PyCFunction, __Pyx_SelflessCall), +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030C0000 + METH_VARARGS | METH_KEYWORDS, +#else + METH_FASTCALL | METH_KEYWORDS, +#endif + NULL +}; +static int __Pyx_TryUnpackUnboundCMethod(__Pyx_CachedCFunction* target) { + PyObject *method, *result=NULL; + method = __Pyx_PyObject_GetAttrStr(target->type, *target->method_name); + if (unlikely(!method)) + return -1; + result = method; +#if CYTHON_COMPILING_IN_CPYTHON + if (likely(__Pyx_TypeCheck(method, &PyMethodDescr_Type))) + { + PyMethodDescrObject *descr = (PyMethodDescrObject*) method; + target->func = descr->d_method->ml_meth; + target->flag = descr->d_method->ml_flags & ~(METH_CLASS | METH_STATIC | METH_COEXIST | METH_STACKLESS); + } else +#endif +#if CYTHON_COMPILING_IN_PYPY +#else + if (PyCFunction_Check(method)) +#endif + { + PyObject *self; + int self_found; +#if CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_PYPY + self = PyObject_GetAttrString(method, "__self__"); + if (!self) { + PyErr_Clear(); + } +#else + self = PyCFunction_GET_SELF(method); +#endif + self_found = (self && self != Py_None); +#if CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_PYPY + Py_XDECREF(self); +#endif + if (self_found) { + PyObject *unbound_method = PyCFunction_New(&__Pyx_UnboundCMethod_Def, method); + if (unlikely(!unbound_method)) return -1; + Py_DECREF(method); + result = unbound_method; + } + } +#if !CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + if (unlikely(target->method)) { + Py_DECREF(result); + } else +#endif + target->method = result; + return 0; +} + +/* CallUnboundCMethod0 */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_CallUnboundCMethod0(__Pyx_CachedCFunction* cfunc, PyObject* self) { + int was_initialized = __Pyx_CachedCFunction_GetAndSetInitializing(cfunc); + if (likely(was_initialized == 2 && cfunc->func)) { + if (likely(cfunc->flag == METH_NOARGS)) + return __Pyx_CallCFunction(cfunc, self, NULL); + if (likely(cfunc->flag == METH_FASTCALL)) + return __Pyx_CallCFunctionFast(cfunc, self, NULL, 0); + if (cfunc->flag == (METH_FASTCALL | METH_KEYWORDS)) + return __Pyx_CallCFunctionFastWithKeywords(cfunc, self, NULL, 0, NULL); + if (likely(cfunc->flag == (METH_VARARGS | METH_KEYWORDS))) + return __Pyx_CallCFunctionWithKeywords(cfunc, self, __pyx_mstate_global->__pyx_empty_tuple, NULL); + if (cfunc->flag == METH_VARARGS) + return __Pyx_CallCFunction(cfunc, self, __pyx_mstate_global->__pyx_empty_tuple); + return __Pyx__CallUnboundCMethod0(cfunc, self); + } +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + else if (unlikely(was_initialized == 1)) { + __Pyx_CachedCFunction tmp_cfunc = { +#ifndef __cplusplus + 0 +#endif + }; + tmp_cfunc.type = cfunc->type; + tmp_cfunc.method_name = cfunc->method_name; + return __Pyx__CallUnboundCMethod0(&tmp_cfunc, self); + } +#endif + PyObject *result = __Pyx__CallUnboundCMethod0(cfunc, self); + __Pyx_CachedCFunction_SetFinishedInitializing(cfunc); + return result; +} +#endif +static PyObject* __Pyx__CallUnboundCMethod0(__Pyx_CachedCFunction* cfunc, PyObject* self) { + PyObject *result; + if (unlikely(!cfunc->method) && unlikely(__Pyx_TryUnpackUnboundCMethod(cfunc) < 0)) return NULL; + result = __Pyx_PyObject_CallOneArg(cfunc->method, self); + return result; +} + +/* py_dict_items (used by OwnedDictNext) */ +static CYTHON_INLINE PyObject* __Pyx_PyDict_Items(PyObject* d) { + return __Pyx_CallUnboundCMethod0(&__pyx_mstate_global->__pyx_umethod_PyDict_Type_items, d); +} + +/* py_dict_values (used by OwnedDictNext) */ +static CYTHON_INLINE PyObject* __Pyx_PyDict_Values(PyObject* d) { + return __Pyx_CallUnboundCMethod0(&__pyx_mstate_global->__pyx_umethod_PyDict_Type_values, d); +} + +/* OwnedDictNext (used by ParseKeywordsImpl) */ +#if CYTHON_AVOID_BORROWED_REFS +static int __Pyx_PyDict_NextRef(PyObject *p, PyObject **ppos, PyObject **pkey, PyObject **pvalue) { + PyObject *next = NULL; + if (!*ppos) { + if (pvalue) { + PyObject *dictview = pkey ? __Pyx_PyDict_Items(p) : __Pyx_PyDict_Values(p); + if (unlikely(!dictview)) goto bad; + *ppos = PyObject_GetIter(dictview); + Py_DECREF(dictview); + } else { + *ppos = PyObject_GetIter(p); + } + if (unlikely(!*ppos)) goto bad; + } + next = PyIter_Next(*ppos); + if (!next) { + if (PyErr_Occurred()) goto bad; + return 0; + } + if (pkey && pvalue) { + *pkey = __Pyx_PySequence_ITEM(next, 0); + if (unlikely(*pkey)) goto bad; + *pvalue = __Pyx_PySequence_ITEM(next, 1); + if (unlikely(*pvalue)) goto bad; + Py_DECREF(next); + } else if (pkey) { + *pkey = next; + } else { + assert(pvalue); + *pvalue = next; + } + return 1; + bad: + Py_XDECREF(next); +#if !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d0000 + PyErr_FormatUnraisable("Exception ignored in __Pyx_PyDict_NextRef"); +#else + PyErr_WriteUnraisable(__pyx_mstate_global->__pyx_n_u_Pyx_PyDict_NextRef); +#endif + if (pkey) *pkey = NULL; + if (pvalue) *pvalue = NULL; + return 0; +} +#else // !CYTHON_AVOID_BORROWED_REFS +static int __Pyx_PyDict_NextRef(PyObject *p, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue) { + int result = PyDict_Next(p, ppos, pkey, pvalue); + if (likely(result == 1)) { + if (pkey) Py_INCREF(*pkey); + if (pvalue) Py_INCREF(*pvalue); + } + return result; +} +#endif + +/* RaiseDoubleKeywords (used by ParseKeywordsImpl) */ +static void __Pyx_RaiseDoubleKeywordsError( + const char* func_name, + PyObject* kw_name) +{ + PyErr_Format(PyExc_TypeError, + "%s() got multiple values for keyword argument '%U'", func_name, kw_name); +} + +/* CallUnboundCMethod2 */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject *__Pyx_CallUnboundCMethod2(__Pyx_CachedCFunction *cfunc, PyObject *self, PyObject *arg1, PyObject *arg2) { + int was_initialized = __Pyx_CachedCFunction_GetAndSetInitializing(cfunc); + if (likely(was_initialized == 2 && cfunc->func)) { + PyObject *args[2] = {arg1, arg2}; + if (cfunc->flag == METH_FASTCALL) { + return __Pyx_CallCFunctionFast(cfunc, self, args, 2); + } + if (cfunc->flag == (METH_FASTCALL | METH_KEYWORDS)) + return __Pyx_CallCFunctionFastWithKeywords(cfunc, self, args, 2, NULL); + } +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + else if (unlikely(was_initialized == 1)) { + __Pyx_CachedCFunction tmp_cfunc = { +#ifndef __cplusplus + 0 +#endif + }; + tmp_cfunc.type = cfunc->type; + tmp_cfunc.method_name = cfunc->method_name; + return __Pyx__CallUnboundCMethod2(&tmp_cfunc, self, arg1, arg2); + } +#endif + PyObject *result = __Pyx__CallUnboundCMethod2(cfunc, self, arg1, arg2); + __Pyx_CachedCFunction_SetFinishedInitializing(cfunc); + return result; +} +#endif +static PyObject* __Pyx__CallUnboundCMethod2(__Pyx_CachedCFunction* cfunc, PyObject* self, PyObject* arg1, PyObject* arg2){ + if (unlikely(!cfunc->func && !cfunc->method) && unlikely(__Pyx_TryUnpackUnboundCMethod(cfunc) < 0)) return NULL; +#if CYTHON_COMPILING_IN_CPYTHON + if (cfunc->func && (cfunc->flag & METH_VARARGS)) { + PyObject *result = NULL; + PyObject *args = PyTuple_New(2); + if (unlikely(!args)) return NULL; + Py_INCREF(arg1); + PyTuple_SET_ITEM(args, 0, arg1); + Py_INCREF(arg2); + PyTuple_SET_ITEM(args, 1, arg2); + if (cfunc->flag & METH_KEYWORDS) + result = __Pyx_CallCFunctionWithKeywords(cfunc, self, args, NULL); + else + result = __Pyx_CallCFunction(cfunc, self, args); + Py_DECREF(args); + return result; + } +#endif + { + PyObject *args[4] = {NULL, self, arg1, arg2}; + return __Pyx_PyObject_FastCall(cfunc->method, args+1, 3 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET); + } +} + +/* ParseKeywordsImpl (used by ParseKeywords) */ +static int __Pyx_ValidateDuplicatePosArgs( + PyObject *kwds, + PyObject ** const argnames[], + PyObject ** const *first_kw_arg, + const char* function_name) +{ + PyObject ** const *name = argnames; + while (name != first_kw_arg) { + PyObject *key = **name; + int found = PyDict_Contains(kwds, key); + if (unlikely(found)) { + if (found == 1) __Pyx_RaiseDoubleKeywordsError(function_name, key); + goto bad; + } + name++; + } + return 0; +bad: + return -1; +} +#if CYTHON_USE_UNICODE_INTERNALS +static CYTHON_INLINE int __Pyx_UnicodeKeywordsEqual(PyObject *s1, PyObject *s2) { + int kind; + Py_ssize_t len = PyUnicode_GET_LENGTH(s1); + if (len != PyUnicode_GET_LENGTH(s2)) return 0; + kind = PyUnicode_KIND(s1); + if (kind != PyUnicode_KIND(s2)) return 0; + const void *data1 = PyUnicode_DATA(s1); + const void *data2 = PyUnicode_DATA(s2); + return (memcmp(data1, data2, (size_t) len * (size_t) kind) == 0); +} +#endif +static int __Pyx_MatchKeywordArg_str( + PyObject *key, + PyObject ** const argnames[], + PyObject ** const *first_kw_arg, + size_t *index_found, + const char *function_name) +{ + PyObject ** const *name; + #if CYTHON_USE_UNICODE_INTERNALS + Py_hash_t key_hash = ((PyASCIIObject*)key)->hash; + if (unlikely(key_hash == -1)) { + key_hash = PyObject_Hash(key); + if (unlikely(key_hash == -1)) + goto bad; + } + #endif + name = first_kw_arg; + while (*name) { + PyObject *name_str = **name; + #if CYTHON_USE_UNICODE_INTERNALS + if (key_hash == ((PyASCIIObject*)name_str)->hash && __Pyx_UnicodeKeywordsEqual(name_str, key)) { + *index_found = (size_t) (name - argnames); + return 1; + } + #else + #if CYTHON_ASSUME_SAFE_SIZE + if (PyUnicode_GET_LENGTH(name_str) == PyUnicode_GET_LENGTH(key)) + #endif + { + int cmp = PyUnicode_Compare(name_str, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) { + *index_found = (size_t) (name - argnames); + return 1; + } + } + #endif + name++; + } + name = argnames; + while (name != first_kw_arg) { + PyObject *name_str = **name; + #if CYTHON_USE_UNICODE_INTERNALS + if (unlikely(key_hash == ((PyASCIIObject*)name_str)->hash)) { + if (__Pyx_UnicodeKeywordsEqual(name_str, key)) + goto arg_passed_twice; + } + #else + #if CYTHON_ASSUME_SAFE_SIZE + if (PyUnicode_GET_LENGTH(name_str) == PyUnicode_GET_LENGTH(key)) + #endif + { + if (unlikely(name_str == key)) goto arg_passed_twice; + int cmp = PyUnicode_Compare(name_str, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) goto arg_passed_twice; + } + #endif + name++; + } + return 0; +arg_passed_twice: + __Pyx_RaiseDoubleKeywordsError(function_name, key); + goto bad; +bad: + return -1; +} +static int __Pyx_MatchKeywordArg_nostr( + PyObject *key, + PyObject ** const argnames[], + PyObject ** const *first_kw_arg, + size_t *index_found, + const char *function_name) +{ + PyObject ** const *name; + if (unlikely(!PyUnicode_Check(key))) goto invalid_keyword_type; + name = first_kw_arg; + while (*name) { + int cmp = PyObject_RichCompareBool(**name, key, Py_EQ); + if (cmp == 1) { + *index_found = (size_t) (name - argnames); + return 1; + } + if (unlikely(cmp == -1)) goto bad; + name++; + } + name = argnames; + while (name != first_kw_arg) { + int cmp = PyObject_RichCompareBool(**name, key, Py_EQ); + if (unlikely(cmp != 0)) { + if (cmp == 1) goto arg_passed_twice; + else goto bad; + } + name++; + } + return 0; +arg_passed_twice: + __Pyx_RaiseDoubleKeywordsError(function_name, key); + goto bad; +invalid_keyword_type: + PyErr_Format(PyExc_TypeError, + "%.200s() keywords must be strings", function_name); + goto bad; +bad: + return -1; +} +static CYTHON_INLINE int __Pyx_MatchKeywordArg( + PyObject *key, + PyObject ** const argnames[], + PyObject ** const *first_kw_arg, + size_t *index_found, + const char *function_name) +{ + return likely(PyUnicode_CheckExact(key)) ? + __Pyx_MatchKeywordArg_str(key, argnames, first_kw_arg, index_found, function_name) : + __Pyx_MatchKeywordArg_nostr(key, argnames, first_kw_arg, index_found, function_name); +} +static void __Pyx_RejectUnknownKeyword( + PyObject *kwds, + PyObject ** const argnames[], + PyObject ** const *first_kw_arg, + const char *function_name) +{ + #if CYTHON_AVOID_BORROWED_REFS + PyObject *pos = NULL; + #else + Py_ssize_t pos = 0; + #endif + PyObject *key = NULL; + __Pyx_BEGIN_CRITICAL_SECTION(kwds); + while ( + #if CYTHON_AVOID_BORROWED_REFS + __Pyx_PyDict_NextRef(kwds, &pos, &key, NULL) + #else + PyDict_Next(kwds, &pos, &key, NULL) + #endif + ) { + PyObject** const *name = first_kw_arg; + while (*name && (**name != key)) name++; + if (!*name) { + size_t index_found = 0; + int cmp = __Pyx_MatchKeywordArg(key, argnames, first_kw_arg, &index_found, function_name); + if (cmp != 1) { + if (cmp == 0) { + PyErr_Format(PyExc_TypeError, + "%s() got an unexpected keyword argument '%U'", + function_name, key); + } + #if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(key); + #endif + break; + } + } + #if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(key); + #endif + } + __Pyx_END_CRITICAL_SECTION(); + #if CYTHON_AVOID_BORROWED_REFS + Py_XDECREF(pos); + #endif + assert(PyErr_Occurred()); +} +static int __Pyx_ParseKeywordDict( + PyObject *kwds, + PyObject ** const argnames[], + PyObject *values[], + Py_ssize_t num_pos_args, + Py_ssize_t num_kwargs, + const char* function_name, + int ignore_unknown_kwargs) +{ + PyObject** const *name; + PyObject** const *first_kw_arg = argnames + num_pos_args; + Py_ssize_t extracted = 0; +#if !CYTHON_COMPILING_IN_PYPY || defined(PyArg_ValidateKeywordArguments) + if (unlikely(!PyArg_ValidateKeywordArguments(kwds))) return -1; +#endif + name = first_kw_arg; + while (*name && num_kwargs > extracted) { + PyObject * key = **name; + PyObject *value; + int found = 0; + #if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + found = PyDict_GetItemRef(kwds, key, &value); + #else + value = PyDict_GetItemWithError(kwds, key); + if (value) { + Py_INCREF(value); + found = 1; + } else { + if (unlikely(PyErr_Occurred())) goto bad; + } + #endif + if (found) { + if (unlikely(found < 0)) goto bad; + values[name-argnames] = value; + extracted++; + } + name++; + } + if (num_kwargs > extracted) { + if (ignore_unknown_kwargs) { + if (unlikely(__Pyx_ValidateDuplicatePosArgs(kwds, argnames, first_kw_arg, function_name) == -1)) + goto bad; + } else { + __Pyx_RejectUnknownKeyword(kwds, argnames, first_kw_arg, function_name); + goto bad; + } + } + return 0; +bad: + return -1; +} +static int __Pyx_ParseKeywordDictToDict( + PyObject *kwds, + PyObject ** const argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + const char* function_name) +{ + PyObject** const *name; + PyObject** const *first_kw_arg = argnames + num_pos_args; + Py_ssize_t len; +#if !CYTHON_COMPILING_IN_PYPY || defined(PyArg_ValidateKeywordArguments) + if (unlikely(!PyArg_ValidateKeywordArguments(kwds))) return -1; +#endif + if (PyDict_Update(kwds2, kwds) < 0) goto bad; + name = first_kw_arg; + while (*name) { + PyObject *key = **name; + PyObject *value; +#if !CYTHON_COMPILING_IN_LIMITED_API && (PY_VERSION_HEX >= 0x030d00A2 || defined(PyDict_Pop)) + int found = PyDict_Pop(kwds2, key, &value); + if (found) { + if (unlikely(found < 0)) goto bad; + values[name-argnames] = value; + } +#elif __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + int found = PyDict_GetItemRef(kwds2, key, &value); + if (found) { + if (unlikely(found < 0)) goto bad; + values[name-argnames] = value; + if (unlikely(PyDict_DelItem(kwds2, key) < 0)) goto bad; + } +#else + #if CYTHON_COMPILING_IN_CPYTHON + value = _PyDict_Pop(kwds2, key, kwds2); + #else + value = __Pyx_CallUnboundCMethod2(&__pyx_mstate_global->__pyx_umethod_PyDict_Type_pop, kwds2, key, kwds2); + #endif + if (value == kwds2) { + Py_DECREF(value); + } else { + if (unlikely(!value)) goto bad; + values[name-argnames] = value; + } +#endif + name++; + } + len = PyDict_Size(kwds2); + if (len > 0) { + return __Pyx_ValidateDuplicatePosArgs(kwds, argnames, first_kw_arg, function_name); + } else if (unlikely(len == -1)) { + goto bad; + } + return 0; +bad: + return -1; +} +static int __Pyx_ParseKeywordsTuple( + PyObject *kwds, + PyObject * const *kwvalues, + PyObject ** const argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + Py_ssize_t num_kwargs, + const char* function_name, + int ignore_unknown_kwargs) +{ + PyObject *key = NULL; + PyObject** const * name; + PyObject** const *first_kw_arg = argnames + num_pos_args; + for (Py_ssize_t pos = 0; pos < num_kwargs; pos++) { +#if CYTHON_AVOID_BORROWED_REFS + key = __Pyx_PySequence_ITEM(kwds, pos); +#else + key = __Pyx_PyTuple_GET_ITEM(kwds, pos); +#endif +#if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(!key)) goto bad; +#endif + name = first_kw_arg; + while (*name && (**name != key)) name++; + if (*name) { + PyObject *value = kwvalues[pos]; + values[name-argnames] = __Pyx_NewRef(value); + } else { + size_t index_found = 0; + int cmp = __Pyx_MatchKeywordArg(key, argnames, first_kw_arg, &index_found, function_name); + if (cmp == 1) { + PyObject *value = kwvalues[pos]; + values[index_found] = __Pyx_NewRef(value); + } else { + if (unlikely(cmp == -1)) goto bad; + if (kwds2) { + PyObject *value = kwvalues[pos]; + if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; + } else if (!ignore_unknown_kwargs) { + goto invalid_keyword; + } + } + } + #if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(key); + key = NULL; + #endif + } + return 0; +invalid_keyword: + PyErr_Format(PyExc_TypeError, + "%s() got an unexpected keyword argument '%U'", + function_name, key); + goto bad; +bad: + #if CYTHON_AVOID_BORROWED_REFS + Py_XDECREF(key); + #endif + return -1; +} + +/* ParseKeywords */ +static int __Pyx_ParseKeywords( + PyObject *kwds, + PyObject * const *kwvalues, + PyObject ** const argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + Py_ssize_t num_kwargs, + const char* function_name, + int ignore_unknown_kwargs) +{ + if (CYTHON_METH_FASTCALL && likely(PyTuple_Check(kwds))) + return __Pyx_ParseKeywordsTuple(kwds, kwvalues, argnames, kwds2, values, num_pos_args, num_kwargs, function_name, ignore_unknown_kwargs); + else if (kwds2) + return __Pyx_ParseKeywordDictToDict(kwds, argnames, kwds2, values, num_pos_args, function_name); + else + return __Pyx_ParseKeywordDict(kwds, argnames, values, num_pos_args, num_kwargs, function_name, ignore_unknown_kwargs); +} + +/* RaiseArgTupleInvalid */ +static void __Pyx_RaiseArgtupleInvalid( + const char* func_name, + int exact, + Py_ssize_t num_min, + Py_ssize_t num_max, + Py_ssize_t num_found) +{ + Py_ssize_t num_expected; + const char *more_or_less; + if (num_found < num_min) { + num_expected = num_min; + more_or_less = "at least"; + } else { + num_expected = num_max; + more_or_less = "at most"; + } + if (exact) { + more_or_less = "exactly"; + } + PyErr_Format(PyExc_TypeError, + "%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)", + func_name, more_or_less, num_expected, + (num_expected == 1) ? "" : "s", num_found); +} + +/* PyObjectFastCallMethod */ +#if !CYTHON_VECTORCALL || PY_VERSION_HEX < 0x03090000 +static PyObject *__Pyx_PyObject_FastCallMethod(PyObject *name, PyObject *const *args, size_t nargsf) { + PyObject *result; + PyObject *attr = PyObject_GetAttr(args[0], name); + if (unlikely(!attr)) + return NULL; + result = __Pyx_PyObject_FastCall(attr, args+1, nargsf - 1); + Py_DECREF(attr); + return result; +} +#endif + +/* PyErrFetchRestore (used by RaiseException) */ +#if CYTHON_FAST_THREAD_STATE +static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { +#if PY_VERSION_HEX >= 0x030C00A6 + PyObject *tmp_value; + assert(type == NULL || (value != NULL && type == (PyObject*) Py_TYPE(value))); + if (value) { + #if CYTHON_COMPILING_IN_CPYTHON + if (unlikely(((PyBaseExceptionObject*) value)->traceback != tb)) + #endif + PyException_SetTraceback(value, tb); + } + tmp_value = tstate->current_exception; + tstate->current_exception = value; + Py_XDECREF(tmp_value); + Py_XDECREF(type); + Py_XDECREF(tb); +#else + PyObject *tmp_type, *tmp_value, *tmp_tb; + tmp_type = tstate->curexc_type; + tmp_value = tstate->curexc_value; + tmp_tb = tstate->curexc_traceback; + tstate->curexc_type = type; + tstate->curexc_value = value; + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#endif +} +static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { +#if PY_VERSION_HEX >= 0x030C00A6 + PyObject* exc_value; + exc_value = tstate->current_exception; + tstate->current_exception = 0; + *value = exc_value; + *type = NULL; + *tb = NULL; + if (exc_value) { + *type = (PyObject*) Py_TYPE(exc_value); + Py_INCREF(*type); + #if CYTHON_COMPILING_IN_CPYTHON + *tb = ((PyBaseExceptionObject*) exc_value)->traceback; + Py_XINCREF(*tb); + #else + *tb = PyException_GetTraceback(exc_value); + #endif + } +#else + *type = tstate->curexc_type; + *value = tstate->curexc_value; + *tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; +#endif +} +#endif + +/* RaiseException */ +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { + PyObject* owned_instance = NULL; + if (tb == Py_None) { + tb = 0; + } else if (tb && !PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto bad; + } + if (value == Py_None) + value = 0; + if (PyExceptionInstance_Check(type)) { + if (value) { + PyErr_SetString(PyExc_TypeError, + "instance exception may not have a separate value"); + goto bad; + } + value = type; + type = (PyObject*) Py_TYPE(value); + } else if (PyExceptionClass_Check(type)) { + PyObject *instance_class = NULL; + if (value && PyExceptionInstance_Check(value)) { + instance_class = (PyObject*) Py_TYPE(value); + if (instance_class != type) { + int is_subclass = PyObject_IsSubclass(instance_class, type); + if (!is_subclass) { + instance_class = NULL; + } else if (unlikely(is_subclass == -1)) { + goto bad; + } else { + type = instance_class; + } + } + } + if (!instance_class) { + PyObject *args; + if (!value) + args = PyTuple_New(0); + else if (PyTuple_Check(value)) { + Py_INCREF(value); + args = value; + } else + args = PyTuple_Pack(1, value); + if (!args) + goto bad; + owned_instance = PyObject_Call(type, args, NULL); + Py_DECREF(args); + if (!owned_instance) + goto bad; + value = owned_instance; + if (!PyExceptionInstance_Check(value)) { + PyErr_Format(PyExc_TypeError, + "calling %R should have returned an instance of " + "BaseException, not %R", + type, Py_TYPE(value)); + goto bad; + } + } + } else { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto bad; + } + if (cause) { + PyObject *fixed_cause; + if (cause == Py_None) { + fixed_cause = NULL; + } else if (PyExceptionClass_Check(cause)) { + fixed_cause = PyObject_CallObject(cause, NULL); + if (fixed_cause == NULL) + goto bad; + } else if (PyExceptionInstance_Check(cause)) { + fixed_cause = cause; + Py_INCREF(fixed_cause); + } else { + PyErr_SetString(PyExc_TypeError, + "exception causes must derive from " + "BaseException"); + goto bad; + } + PyException_SetCause(value, fixed_cause); + } + PyErr_SetObject(type, value); + if (tb) { +#if PY_VERSION_HEX >= 0x030C00A6 + PyException_SetTraceback(value, tb); +#elif CYTHON_FAST_THREAD_STATE + PyThreadState *tstate = __Pyx_PyThreadState_Current; + PyObject* tmp_tb = tstate->curexc_traceback; + if (tb != tmp_tb) { + Py_INCREF(tb); + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_tb); + } +#else + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyErr_Fetch(&tmp_type, &tmp_value, &tmp_tb); + Py_INCREF(tb); + PyErr_Restore(tmp_type, tmp_value, tb); + Py_XDECREF(tmp_tb); +#endif + } +bad: + Py_XDECREF(owned_instance); + return; +} + +/* GetException */ +#if CYTHON_FAST_THREAD_STATE +static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) +#else +static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb) +#endif +{ + PyObject *local_type = NULL, *local_value, *local_tb = NULL; +#if CYTHON_FAST_THREAD_STATE + PyObject *tmp_type, *tmp_value, *tmp_tb; + #if PY_VERSION_HEX >= 0x030C0000 + local_value = tstate->current_exception; + tstate->current_exception = 0; + #else + local_type = tstate->curexc_type; + local_value = tstate->curexc_value; + local_tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; + #endif +#elif __PYX_LIMITED_VERSION_HEX > 0x030C0000 + local_value = PyErr_GetRaisedException(); +#else + PyErr_Fetch(&local_type, &local_value, &local_tb); +#endif +#if __PYX_LIMITED_VERSION_HEX > 0x030C0000 + if (likely(local_value)) { + local_type = (PyObject*) Py_TYPE(local_value); + Py_INCREF(local_type); + local_tb = PyException_GetTraceback(local_value); + } +#else + PyErr_NormalizeException(&local_type, &local_value, &local_tb); +#if CYTHON_FAST_THREAD_STATE + if (unlikely(tstate->curexc_type)) +#else + if (unlikely(PyErr_Occurred())) +#endif + goto bad; + if (local_tb) { + if (unlikely(PyException_SetTraceback(local_value, local_tb) < 0)) + goto bad; + } +#endif // __PYX_LIMITED_VERSION_HEX > 0x030C0000 + Py_XINCREF(local_tb); + Py_XINCREF(local_type); + Py_XINCREF(local_value); + *type = local_type; + *value = local_value; + *tb = local_tb; +#if CYTHON_FAST_THREAD_STATE + #if CYTHON_USE_EXC_INFO_STACK + { + _PyErr_StackItem *exc_info = tstate->exc_info; + #if PY_VERSION_HEX >= 0x030B00a4 + tmp_value = exc_info->exc_value; + exc_info->exc_value = local_value; + tmp_type = NULL; + tmp_tb = NULL; + Py_XDECREF(local_type); + Py_XDECREF(local_tb); + #else + tmp_type = exc_info->exc_type; + tmp_value = exc_info->exc_value; + tmp_tb = exc_info->exc_traceback; + exc_info->exc_type = local_type; + exc_info->exc_value = local_value; + exc_info->exc_traceback = local_tb; + #endif + } + #else + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = local_type; + tstate->exc_value = local_value; + tstate->exc_traceback = local_tb; + #endif + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#elif __PYX_LIMITED_VERSION_HEX >= 0x030b0000 + PyErr_SetHandledException(local_value); + Py_XDECREF(local_value); + Py_XDECREF(local_type); + Py_XDECREF(local_tb); +#else + PyErr_SetExcInfo(local_type, local_value, local_tb); +#endif + return 0; +#if __PYX_LIMITED_VERSION_HEX <= 0x030C0000 +bad: + *type = 0; + *value = 0; + *tb = 0; + Py_XDECREF(local_type); + Py_XDECREF(local_value); + Py_XDECREF(local_tb); + return -1; +#endif +} + +/* SwapException */ +#if CYTHON_FAST_THREAD_STATE +static CYTHON_INLINE void __Pyx__ExceptionSwap(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { + PyObject *tmp_type, *tmp_value, *tmp_tb; + #if CYTHON_USE_EXC_INFO_STACK && PY_VERSION_HEX >= 0x030B00a4 + _PyErr_StackItem *exc_info = tstate->exc_info; + tmp_value = exc_info->exc_value; + exc_info->exc_value = *value; + if (tmp_value == NULL || tmp_value == Py_None) { + Py_XDECREF(tmp_value); + tmp_value = NULL; + tmp_type = NULL; + tmp_tb = NULL; + } else { + tmp_type = (PyObject*) Py_TYPE(tmp_value); + Py_INCREF(tmp_type); + #if CYTHON_COMPILING_IN_CPYTHON + tmp_tb = ((PyBaseExceptionObject*) tmp_value)->traceback; + Py_XINCREF(tmp_tb); + #else + tmp_tb = PyException_GetTraceback(tmp_value); + #endif + } + #elif CYTHON_USE_EXC_INFO_STACK + _PyErr_StackItem *exc_info = tstate->exc_info; + tmp_type = exc_info->exc_type; + tmp_value = exc_info->exc_value; + tmp_tb = exc_info->exc_traceback; + exc_info->exc_type = *type; + exc_info->exc_value = *value; + exc_info->exc_traceback = *tb; + #else + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = *type; + tstate->exc_value = *value; + tstate->exc_traceback = *tb; + #endif + *type = tmp_type; + *value = tmp_value; + *tb = tmp_tb; +} +#else +static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb) { + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyErr_GetExcInfo(&tmp_type, &tmp_value, &tmp_tb); + PyErr_SetExcInfo(*type, *value, *tb); + *type = tmp_type; + *value = tmp_value; + *tb = tmp_tb; +} +#endif + +/* GetTopmostException (used by SaveResetException) */ +#if CYTHON_USE_EXC_INFO_STACK && CYTHON_FAST_THREAD_STATE +static _PyErr_StackItem * +__Pyx_PyErr_GetTopmostException(PyThreadState *tstate) +{ + _PyErr_StackItem *exc_info = tstate->exc_info; + while ((exc_info->exc_value == NULL || exc_info->exc_value == Py_None) && + exc_info->previous_item != NULL) + { + exc_info = exc_info->previous_item; + } + return exc_info; +} +#endif + +/* SaveResetException */ +#if CYTHON_FAST_THREAD_STATE +static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { + #if CYTHON_USE_EXC_INFO_STACK && PY_VERSION_HEX >= 0x030B00a4 + _PyErr_StackItem *exc_info = __Pyx_PyErr_GetTopmostException(tstate); + PyObject *exc_value = exc_info->exc_value; + if (exc_value == NULL || exc_value == Py_None) { + *value = NULL; + *type = NULL; + *tb = NULL; + } else { + *value = exc_value; + Py_INCREF(*value); + *type = (PyObject*) Py_TYPE(exc_value); + Py_INCREF(*type); + *tb = PyException_GetTraceback(exc_value); + } + #elif CYTHON_USE_EXC_INFO_STACK + _PyErr_StackItem *exc_info = __Pyx_PyErr_GetTopmostException(tstate); + *type = exc_info->exc_type; + *value = exc_info->exc_value; + *tb = exc_info->exc_traceback; + Py_XINCREF(*type); + Py_XINCREF(*value); + Py_XINCREF(*tb); + #else + *type = tstate->exc_type; + *value = tstate->exc_value; + *tb = tstate->exc_traceback; + Py_XINCREF(*type); + Py_XINCREF(*value); + Py_XINCREF(*tb); + #endif +} +static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { + #if CYTHON_USE_EXC_INFO_STACK && PY_VERSION_HEX >= 0x030B00a4 + _PyErr_StackItem *exc_info = tstate->exc_info; + PyObject *tmp_value = exc_info->exc_value; + exc_info->exc_value = value; + Py_XDECREF(tmp_value); + Py_XDECREF(type); + Py_XDECREF(tb); + #else + PyObject *tmp_type, *tmp_value, *tmp_tb; + #if CYTHON_USE_EXC_INFO_STACK + _PyErr_StackItem *exc_info = tstate->exc_info; + tmp_type = exc_info->exc_type; + tmp_value = exc_info->exc_value; + tmp_tb = exc_info->exc_traceback; + exc_info->exc_type = type; + exc_info->exc_value = value; + exc_info->exc_traceback = tb; + #else + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = type; + tstate->exc_value = value; + tstate->exc_traceback = tb; + #endif + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); + #endif +} +#endif + +/* RejectKeywords */ +static void __Pyx_RejectKeywords(const char* function_name, PyObject *kwds) { + PyObject *key = NULL; + if (CYTHON_METH_FASTCALL && likely(PyTuple_Check(kwds))) { + key = __Pyx_PySequence_ITEM(kwds, 0); + } else { +#if CYTHON_AVOID_BORROWED_REFS + PyObject *pos = NULL; +#else + Py_ssize_t pos = 0; +#endif +#if !CYTHON_COMPILING_IN_PYPY || defined(PyArg_ValidateKeywordArguments) + if (unlikely(!PyArg_ValidateKeywordArguments(kwds))) return; +#endif + __Pyx_PyDict_NextRef(kwds, &pos, &key, NULL); +#if CYTHON_AVOID_BORROWED_REFS + Py_XDECREF(pos); +#endif + } + if (likely(key)) { + PyErr_Format(PyExc_TypeError, + "%s() got an unexpected keyword argument '%U'", + function_name, key); + Py_DECREF(key); + } +} + +/* PyErrExceptionMatches (used by GetAttr3) */ +#if CYTHON_FAST_THREAD_STATE +static int __Pyx_PyErr_ExceptionMatchesTuple(PyObject *exc_type, PyObject *tuple) { + Py_ssize_t i, n; + n = PyTuple_GET_SIZE(tuple); + for (i=0; i= 0x030C00A6 + PyObject *current_exception = tstate->current_exception; + if (unlikely(!current_exception)) return 0; + exc_type = (PyObject*) Py_TYPE(current_exception); + if (exc_type == err) return 1; +#else + exc_type = tstate->curexc_type; + if (exc_type == err) return 1; + if (unlikely(!exc_type)) return 0; +#endif + #if CYTHON_AVOID_BORROWED_REFS + Py_INCREF(exc_type); + #endif + if (unlikely(PyTuple_Check(err))) { + result = __Pyx_PyErr_ExceptionMatchesTuple(exc_type, err); + } else { + result = __Pyx_PyErr_GivenExceptionMatches(exc_type, err); + } + #if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(exc_type); + #endif + return result; +} +#endif + +/* GetAttr3 */ +#if __PYX_LIMITED_VERSION_HEX < 0x030d0000 +static PyObject *__Pyx_GetAttr3Default(PyObject *d) { + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + if (unlikely(!__Pyx_PyErr_ExceptionMatches(PyExc_AttributeError))) + return NULL; + __Pyx_PyErr_Clear(); + Py_INCREF(d); + return d; +} +#endif +static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *o, PyObject *n, PyObject *d) { + PyObject *r; +#if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + int res = PyObject_GetOptionalAttr(o, n, &r); + return (res != 0) ? r : __Pyx_NewRef(d); +#else + #if CYTHON_USE_TYPE_SLOTS + if (likely(PyUnicode_Check(n))) { + r = __Pyx_PyObject_GetAttrStrNoError(o, n); + if (unlikely(!r) && likely(!PyErr_Occurred())) { + r = __Pyx_NewRef(d); + } + return r; + } + #endif + r = PyObject_GetAttr(o, n); + return (likely(r)) ? r : __Pyx_GetAttr3Default(d); +#endif +} + +/* PyObjectGetAttrStrNoError (used by GetBuiltinName) */ +#if __PYX_LIMITED_VERSION_HEX < 0x030d0000 +static void __Pyx_PyObject_GetAttrStr_ClearAttributeError(void) { + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + if (likely(__Pyx_PyErr_ExceptionMatches(PyExc_AttributeError))) + __Pyx_PyErr_Clear(); +} +#endif +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStrNoError(PyObject* obj, PyObject* attr_name) { + PyObject *result; +#if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + (void) PyObject_GetOptionalAttr(obj, attr_name, &result); + return result; +#else +#if CYTHON_COMPILING_IN_CPYTHON && CYTHON_USE_TYPE_SLOTS + PyTypeObject* tp = Py_TYPE(obj); + if (likely(tp->tp_getattro == PyObject_GenericGetAttr)) { + return _PyObject_GenericGetAttrWithDict(obj, attr_name, NULL, 1); + } +#endif + result = __Pyx_PyObject_GetAttrStr(obj, attr_name); + if (unlikely(!result)) { + __Pyx_PyObject_GetAttrStr_ClearAttributeError(); + } + return result; +#endif +} + +/* GetBuiltinName (used by GetModuleGlobalName) */ +static PyObject *__Pyx_GetBuiltinName(PyObject *name) { + PyObject* result = __Pyx_PyObject_GetAttrStrNoError(__pyx_mstate_global->__pyx_b, name); + if (unlikely(!result) && !PyErr_Occurred()) { + PyErr_Format(PyExc_NameError, + "name '%U' is not defined", name); + } + return result; +} + +/* PyDictVersioning (used by GetModuleGlobalName) */ +#if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_TYPE_SLOTS +static CYTHON_INLINE PY_UINT64_T __Pyx_get_tp_dict_version(PyObject *obj) { + PyObject *dict = Py_TYPE(obj)->tp_dict; + return likely(dict) ? __PYX_GET_DICT_VERSION(dict) : 0; +} +static CYTHON_INLINE PY_UINT64_T __Pyx_get_object_dict_version(PyObject *obj) { + PyObject **dictptr = NULL; + Py_ssize_t offset = Py_TYPE(obj)->tp_dictoffset; + if (offset) { +#if CYTHON_COMPILING_IN_CPYTHON + dictptr = (likely(offset > 0)) ? (PyObject **) ((char *)obj + offset) : _PyObject_GetDictPtr(obj); +#else + dictptr = _PyObject_GetDictPtr(obj); +#endif + } + return (dictptr && *dictptr) ? __PYX_GET_DICT_VERSION(*dictptr) : 0; +} +static CYTHON_INLINE int __Pyx_object_dict_version_matches(PyObject* obj, PY_UINT64_T tp_dict_version, PY_UINT64_T obj_dict_version) { + PyObject *dict = Py_TYPE(obj)->tp_dict; + if (unlikely(!dict) || unlikely(tp_dict_version != __PYX_GET_DICT_VERSION(dict))) + return 0; + return obj_dict_version == __Pyx_get_object_dict_version(obj); +} +#endif + +/* GetModuleGlobalName */ +#if CYTHON_USE_DICT_VERSIONS +static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_version, PyObject **dict_cached_value) +#else +static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name) +#endif +{ + PyObject *result; +#if CYTHON_COMPILING_IN_LIMITED_API + if (unlikely(!__pyx_m)) { + if (!PyErr_Occurred()) + PyErr_SetNone(PyExc_NameError); + return NULL; + } + result = PyObject_GetAttr(__pyx_m, name); + if (likely(result)) { + return result; + } + PyErr_Clear(); +#elif CYTHON_AVOID_BORROWED_REFS || CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + if (unlikely(__Pyx_PyDict_GetItemRef(__pyx_mstate_global->__pyx_d, name, &result) == -1)) PyErr_Clear(); + __PYX_UPDATE_DICT_CACHE(__pyx_mstate_global->__pyx_d, result, *dict_cached_value, *dict_version) + if (likely(result)) { + return result; + } +#else + result = _PyDict_GetItem_KnownHash(__pyx_mstate_global->__pyx_d, name, ((PyASCIIObject *) name)->hash); + __PYX_UPDATE_DICT_CACHE(__pyx_mstate_global->__pyx_d, result, *dict_cached_value, *dict_version) + if (likely(result)) { + return __Pyx_NewRef(result); + } + PyErr_Clear(); +#endif + return __Pyx_GetBuiltinName(name); +} + +/* RaiseUnexpectedTypeError */ +static int +__Pyx_RaiseUnexpectedTypeError(const char *expected, PyObject *obj) +{ + __Pyx_TypeName obj_type_name = __Pyx_PyType_GetFullyQualifiedName(Py_TYPE(obj)); + PyErr_Format(PyExc_TypeError, "Expected %s, got " __Pyx_FMT_TYPENAME, + expected, obj_type_name); + __Pyx_DECREF_TypeName(obj_type_name); + return 0; +} + +/* ArgTypeTestFunc (used by ArgTypeTest) */ +static int __Pyx__ArgTypeTest(PyObject *obj, PyTypeObject *type, const char *name, int exact) +{ + __Pyx_TypeName type_name; + __Pyx_TypeName obj_type_name; + PyObject *extra_info = __pyx_mstate_global->__pyx_empty_unicode; + int from_annotation_subclass = 0; + if (unlikely(!type)) { + PyErr_SetString(PyExc_SystemError, "Missing type object"); + return 0; + } + else if (!exact) { + if (likely(__Pyx_TypeCheck(obj, type))) return 1; + } else if (exact == 2) { + if (__Pyx_TypeCheck(obj, type)) { + from_annotation_subclass = 1; + extra_info = __pyx_mstate_global->__pyx_kp_u_Note_that_Cython_is_deliberately; + } + } + type_name = __Pyx_PyType_GetFullyQualifiedName(type); + obj_type_name = __Pyx_PyType_GetFullyQualifiedName(Py_TYPE(obj)); + PyErr_Format(PyExc_TypeError, + "Argument '%.200s' has incorrect type (expected " __Pyx_FMT_TYPENAME + ", got " __Pyx_FMT_TYPENAME ")" +#if __PYX_LIMITED_VERSION_HEX < 0x030C0000 + "%s%U" +#endif + , name, type_name, obj_type_name +#if __PYX_LIMITED_VERSION_HEX < 0x030C0000 + , (from_annotation_subclass ? ". " : ""), extra_info +#endif + ); +#if __PYX_LIMITED_VERSION_HEX >= 0x030C0000 + if (exact == 2 && from_annotation_subclass) { + PyObject *res; + PyObject *vargs[2]; + vargs[0] = PyErr_GetRaisedException(); + vargs[1] = extra_info; + res = PyObject_VectorcallMethod(__pyx_mstate_global->__pyx_kp_u_add_note, vargs, 2, NULL); + Py_XDECREF(res); + PyErr_SetRaisedException(vargs[0]); + } +#endif + __Pyx_DECREF_TypeName(type_name); + __Pyx_DECREF_TypeName(obj_type_name); + return 0; +} + +/* GetItemInt */ +static PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) { + PyObject *r; + if (unlikely(!j)) return NULL; + r = PyObject_GetItem(o, j); + Py_DECREF(j); + return r; +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck, int unsafe_shared) { + CYTHON_MAYBE_UNUSED_VAR(unsafe_shared); +#if CYTHON_ASSUME_SAFE_SIZE + Py_ssize_t wrapped_i = i; + if (wraparound & unlikely(i < 0)) { + wrapped_i += PyList_GET_SIZE(o); + } + if ((CYTHON_AVOID_BORROWED_REFS || CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS || !CYTHON_ASSUME_SAFE_MACROS)) { + return __Pyx_PyList_GetItemRefFast(o, wrapped_i, unsafe_shared); + } else + if ((!boundscheck) || likely(__Pyx_is_valid_index(wrapped_i, PyList_GET_SIZE(o)))) { + return __Pyx_NewRef(PyList_GET_ITEM(o, wrapped_i)); + } + return __Pyx_GetItemInt_Generic(o, PyLong_FromSsize_t(i)); +#else + (void)wraparound; + (void)boundscheck; + return PySequence_GetItem(o, i); +#endif +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck, int unsafe_shared) { + CYTHON_MAYBE_UNUSED_VAR(unsafe_shared); +#if CYTHON_ASSUME_SAFE_SIZE && CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + Py_ssize_t wrapped_i = i; + if (wraparound & unlikely(i < 0)) { + wrapped_i += PyTuple_GET_SIZE(o); + } + if ((!boundscheck) || likely(__Pyx_is_valid_index(wrapped_i, PyTuple_GET_SIZE(o)))) { + return __Pyx_NewRef(PyTuple_GET_ITEM(o, wrapped_i)); + } + return __Pyx_GetItemInt_Generic(o, PyLong_FromSsize_t(i)); +#else + (void)wraparound; + (void)boundscheck; + return PySequence_GetItem(o, i); +#endif +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, int is_list, + int wraparound, int boundscheck, int unsafe_shared) { + CYTHON_MAYBE_UNUSED_VAR(unsafe_shared); +#if CYTHON_ASSUME_SAFE_MACROS && CYTHON_ASSUME_SAFE_SIZE + if (is_list || PyList_CheckExact(o)) { + Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyList_GET_SIZE(o); + if ((CYTHON_AVOID_BORROWED_REFS || CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS)) { + return __Pyx_PyList_GetItemRefFast(o, n, unsafe_shared); + } else if ((!boundscheck) || (likely(__Pyx_is_valid_index(n, PyList_GET_SIZE(o))))) { + return __Pyx_NewRef(PyList_GET_ITEM(o, n)); + } + } else + #if !CYTHON_AVOID_BORROWED_REFS + if (PyTuple_CheckExact(o)) { + Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyTuple_GET_SIZE(o); + if ((!boundscheck) || likely(__Pyx_is_valid_index(n, PyTuple_GET_SIZE(o)))) { + return __Pyx_NewRef(PyTuple_GET_ITEM(o, n)); + } + } else + #endif +#endif +#if CYTHON_USE_TYPE_SLOTS && !CYTHON_COMPILING_IN_PYPY + { + PyMappingMethods *mm = Py_TYPE(o)->tp_as_mapping; + PySequenceMethods *sm = Py_TYPE(o)->tp_as_sequence; + if (!is_list && mm && mm->mp_subscript) { + PyObject *r, *key = PyLong_FromSsize_t(i); + if (unlikely(!key)) return NULL; + r = mm->mp_subscript(o, key); + Py_DECREF(key); + return r; + } + if (is_list || likely(sm && sm->sq_item)) { + if (wraparound && unlikely(i < 0) && likely(sm->sq_length)) { + Py_ssize_t l = sm->sq_length(o); + if (likely(l >= 0)) { + i += l; + } else { + if (!PyErr_ExceptionMatches(PyExc_OverflowError)) + return NULL; + PyErr_Clear(); + } + } + return sm->sq_item(o, i); + } + } +#else + if (is_list || !PyMapping_Check(o)) { + return PySequence_GetItem(o, i); + } +#endif + (void)wraparound; + (void)boundscheck; + return __Pyx_GetItemInt_Generic(o, PyLong_FromSsize_t(i)); +} + +/* ExtTypeTest */ +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { + __Pyx_TypeName obj_type_name; + __Pyx_TypeName type_name; + if (unlikely(!type)) { + PyErr_SetString(PyExc_SystemError, "Missing type object"); + return 0; + } + if (likely(__Pyx_TypeCheck(obj, type))) + return 1; + obj_type_name = __Pyx_PyType_GetFullyQualifiedName(Py_TYPE(obj)); + type_name = __Pyx_PyType_GetFullyQualifiedName(type); + PyErr_Format(PyExc_TypeError, + "Cannot convert " __Pyx_FMT_TYPENAME " to " __Pyx_FMT_TYPENAME, + obj_type_name, type_name); + __Pyx_DECREF_TypeName(obj_type_name); + __Pyx_DECREF_TypeName(type_name); + return 0; +} + +/* CallNextTpDealloc */ +static void __Pyx_call_next_tp_dealloc(PyObject* obj, destructor current_tp_dealloc) { + PyTypeObject* type = Py_TYPE(obj); + destructor tp_dealloc = NULL; + while (type && __Pyx_PyType_GetSlot(type, tp_dealloc, destructor) != current_tp_dealloc) + type = __Pyx_PyType_GetSlot(type, tp_base, PyTypeObject*); + while (type && (tp_dealloc = __Pyx_PyType_GetSlot(type, tp_dealloc, destructor)) == current_tp_dealloc) + type = __Pyx_PyType_GetSlot(type, tp_base, PyTypeObject*); + if (type) + tp_dealloc(obj); +} + +/* CallNextTpTraverse */ +static int __Pyx_call_next_tp_traverse(PyObject* obj, visitproc v, void *a, traverseproc current_tp_traverse) { + PyTypeObject* type = Py_TYPE(obj); + traverseproc tp_traverse = NULL; + while (type && __Pyx_PyType_GetSlot(type, tp_traverse, traverseproc) != current_tp_traverse) + type = __Pyx_PyType_GetSlot(type, tp_base, PyTypeObject*); + while (type && (tp_traverse = __Pyx_PyType_GetSlot(type, tp_traverse, traverseproc)) == current_tp_traverse) + type = __Pyx_PyType_GetSlot(type, tp_base, PyTypeObject*); + if (type && tp_traverse) + return tp_traverse(obj, v, a); + return 0; +} + +/* CallTypeTraverse */ +#if !CYTHON_USE_TYPE_SPECS || (!CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x03090000) +#else +static int __Pyx_call_type_traverse(PyObject *o, int always_call, visitproc visit, void *arg) { + #if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x03090000 + if (__Pyx_get_runtime_version() < 0x03090000) return 0; + #endif + if (!always_call) { + PyTypeObject *base = __Pyx_PyObject_GetSlot(o, tp_base, PyTypeObject*); + unsigned long flags = PyType_GetFlags(base); + if (flags & Py_TPFLAGS_HEAPTYPE) { + return 0; + } + } + Py_VISIT((PyObject*)Py_TYPE(o)); + return 0; +} +#endif + +/* CallNextTpClear */ +static void __Pyx_call_next_tp_clear(PyObject* obj, inquiry current_tp_clear) { + PyTypeObject* type = Py_TYPE(obj); + inquiry tp_clear = NULL; + while (type && __Pyx_PyType_GetSlot(type, tp_clear, inquiry) != current_tp_clear) + type = __Pyx_PyType_GetSlot(type, tp_base, PyTypeObject*); + while (type && (tp_clear = __Pyx_PyType_GetSlot(type, tp_clear, inquiry)) == current_tp_clear) + type = __Pyx_PyType_GetSlot(type, tp_base, PyTypeObject*); + if (type && tp_clear) + tp_clear(obj); +} + +/* TypeImport */ +#ifndef __PYX_HAVE_RT_ImportType_3_2_4 +#define __PYX_HAVE_RT_ImportType_3_2_4 +static PyTypeObject *__Pyx_ImportType_3_2_4(PyObject *module, const char *module_name, const char *class_name, + size_t size, size_t alignment, enum __Pyx_ImportType_CheckSize_3_2_4 check_size) +{ + PyObject *result = 0; + Py_ssize_t basicsize; + Py_ssize_t itemsize; +#if defined(Py_LIMITED_API) || (defined(CYTHON_COMPILING_IN_LIMITED_API) && CYTHON_COMPILING_IN_LIMITED_API) + PyObject *py_basicsize; + PyObject *py_itemsize; +#endif + result = PyObject_GetAttrString(module, class_name); + if (!result) + goto bad; + if (!PyType_Check(result)) { + PyErr_Format(PyExc_TypeError, + "%.200s.%.200s is not a type object", + module_name, class_name); + goto bad; + } +#if !( defined(Py_LIMITED_API) || (defined(CYTHON_COMPILING_IN_LIMITED_API) && CYTHON_COMPILING_IN_LIMITED_API) ) + basicsize = ((PyTypeObject *)result)->tp_basicsize; + itemsize = ((PyTypeObject *)result)->tp_itemsize; +#else + if (size == 0) { + return (PyTypeObject *)result; + } + py_basicsize = PyObject_GetAttrString(result, "__basicsize__"); + if (!py_basicsize) + goto bad; + basicsize = PyLong_AsSsize_t(py_basicsize); + Py_DECREF(py_basicsize); + py_basicsize = 0; + if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred()) + goto bad; + py_itemsize = PyObject_GetAttrString(result, "__itemsize__"); + if (!py_itemsize) + goto bad; + itemsize = PyLong_AsSsize_t(py_itemsize); + Py_DECREF(py_itemsize); + py_itemsize = 0; + if (itemsize == (Py_ssize_t)-1 && PyErr_Occurred()) + goto bad; +#endif + if (itemsize) { + if (size % alignment) { + alignment = size % alignment; + } + if (itemsize < (Py_ssize_t)alignment) + itemsize = (Py_ssize_t)alignment; + } + if ((size_t)(basicsize + itemsize) < size) { + PyErr_Format(PyExc_ValueError, + "%.200s.%.200s size changed, may indicate binary incompatibility. " + "Expected %zd from C header, got %zd from PyObject", + module_name, class_name, size, basicsize+itemsize); + goto bad; + } + if (check_size == __Pyx_ImportType_CheckSize_Error_3_2_4 && + ((size_t)basicsize > size || (size_t)(basicsize + itemsize) < size)) { + PyErr_Format(PyExc_ValueError, + "%.200s.%.200s size changed, may indicate binary incompatibility. " + "Expected %zd from C header, got %zd-%zd from PyObject", + module_name, class_name, size, basicsize, basicsize+itemsize); + goto bad; + } + else if (check_size == __Pyx_ImportType_CheckSize_Warn_3_2_4 && (size_t)basicsize > size) { + if (PyErr_WarnFormat(NULL, 0, + "%.200s.%.200s size changed, may indicate binary incompatibility. " + "Expected %zd from C header, got %zd from PyObject", + module_name, class_name, size, basicsize) < 0) { + goto bad; + } + } + return (PyTypeObject *)result; +bad: + Py_XDECREF(result); + return NULL; +} +#endif + +/* GetVTable */ +static void* __Pyx_GetVtable(PyTypeObject *type) { + void* ptr; +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *ob = PyObject_GetAttr((PyObject *)type, __pyx_mstate_global->__pyx_n_u_pyx_vtable); +#else + PyObject *ob = PyObject_GetItem(type->tp_dict, __pyx_mstate_global->__pyx_n_u_pyx_vtable); +#endif + if (!ob) + goto bad; + ptr = PyCapsule_GetPointer(ob, 0); + if (!ptr && !PyErr_Occurred()) + PyErr_SetString(PyExc_RuntimeError, "invalid vtable found for imported type"); + Py_DECREF(ob); + return ptr; +bad: + Py_XDECREF(ob); + return NULL; +} + +/* LimitedApiGetTypeDict (used by SetItemOnTypeDict) */ +#if CYTHON_COMPILING_IN_LIMITED_API +static Py_ssize_t __Pyx_GetTypeDictOffset(void) { + PyObject *tp_dictoffset_o; + Py_ssize_t tp_dictoffset; + tp_dictoffset_o = PyObject_GetAttrString((PyObject*)(&PyType_Type), "__dictoffset__"); + if (unlikely(!tp_dictoffset_o)) return -1; + tp_dictoffset = PyLong_AsSsize_t(tp_dictoffset_o); + Py_DECREF(tp_dictoffset_o); + if (unlikely(tp_dictoffset == 0)) { + PyErr_SetString( + PyExc_TypeError, + "'type' doesn't have a dictoffset"); + return -1; + } else if (unlikely(tp_dictoffset < 0)) { + PyErr_SetString( + PyExc_TypeError, + "'type' has an unexpected negative dictoffset. " + "Please report this as Cython bug"); + return -1; + } + return tp_dictoffset; +} +static PyObject *__Pyx_GetTypeDict(PyTypeObject *tp) { + static Py_ssize_t tp_dictoffset = 0; + if (unlikely(tp_dictoffset == 0)) { + tp_dictoffset = __Pyx_GetTypeDictOffset(); + if (unlikely(tp_dictoffset == -1 && PyErr_Occurred())) { + tp_dictoffset = 0; // try again next time? + return NULL; + } + } + return *(PyObject**)((char*)tp + tp_dictoffset); +} +#endif + +/* SetItemOnTypeDict (used by FixUpExtensionType) */ +static int __Pyx__SetItemOnTypeDict(PyTypeObject *tp, PyObject *k, PyObject *v) { + int result; + PyObject *tp_dict; +#if CYTHON_COMPILING_IN_LIMITED_API + tp_dict = __Pyx_GetTypeDict(tp); + if (unlikely(!tp_dict)) return -1; +#else + tp_dict = tp->tp_dict; +#endif + result = PyDict_SetItem(tp_dict, k, v); + if (likely(!result)) { + PyType_Modified(tp); + if (unlikely(PyObject_HasAttr(v, __pyx_mstate_global->__pyx_n_u_set_name))) { + PyObject *setNameResult = PyObject_CallMethodObjArgs(v, __pyx_mstate_global->__pyx_n_u_set_name, (PyObject *) tp, k, NULL); + if (!setNameResult) return -1; + Py_DECREF(setNameResult); + } + } + return result; +} + +/* FixUpExtensionType */ +static int __Pyx_fix_up_extension_type_from_spec(PyType_Spec *spec, PyTypeObject *type) { +#if __PYX_LIMITED_VERSION_HEX > 0x030900B1 + CYTHON_UNUSED_VAR(spec); + CYTHON_UNUSED_VAR(type); + CYTHON_UNUSED_VAR(__Pyx__SetItemOnTypeDict); +#else + const PyType_Slot *slot = spec->slots; + int changed = 0; +#if !CYTHON_COMPILING_IN_LIMITED_API + while (slot && slot->slot && slot->slot != Py_tp_members) + slot++; + if (slot && slot->slot == Py_tp_members) { +#if !CYTHON_COMPILING_IN_CPYTHON + const +#endif // !CYTHON_COMPILING_IN_CPYTHON) + PyMemberDef *memb = (PyMemberDef*) slot->pfunc; + while (memb && memb->name) { + if (memb->name[0] == '_' && memb->name[1] == '_') { + if (strcmp(memb->name, "__weaklistoffset__") == 0) { + assert(memb->type == T_PYSSIZET); + assert(memb->flags == READONLY); + type->tp_weaklistoffset = memb->offset; + changed = 1; + } + else if (strcmp(memb->name, "__dictoffset__") == 0) { + assert(memb->type == T_PYSSIZET); + assert(memb->flags == READONLY); + type->tp_dictoffset = memb->offset; + changed = 1; + } +#if CYTHON_METH_FASTCALL + else if (strcmp(memb->name, "__vectorcalloffset__") == 0) { + assert(memb->type == T_PYSSIZET); + assert(memb->flags == READONLY); + type->tp_vectorcall_offset = memb->offset; + changed = 1; + } +#endif // CYTHON_METH_FASTCALL +#if !CYTHON_COMPILING_IN_PYPY + else if (strcmp(memb->name, "__module__") == 0) { + PyObject *descr; + assert(memb->type == T_OBJECT); + assert(memb->flags == 0 || memb->flags == READONLY); + descr = PyDescr_NewMember(type, memb); + if (unlikely(!descr)) + return -1; + int set_item_result = PyDict_SetItem(type->tp_dict, PyDescr_NAME(descr), descr); + Py_DECREF(descr); + if (unlikely(set_item_result < 0)) { + return -1; + } + changed = 1; + } +#endif // !CYTHON_COMPILING_IN_PYPY + } + memb++; + } + } +#endif // !CYTHON_COMPILING_IN_LIMITED_API +#if !CYTHON_COMPILING_IN_PYPY + slot = spec->slots; + while (slot && slot->slot && slot->slot != Py_tp_getset) + slot++; + if (slot && slot->slot == Py_tp_getset) { + PyGetSetDef *getset = (PyGetSetDef*) slot->pfunc; + while (getset && getset->name) { + if (getset->name[0] == '_' && getset->name[1] == '_' && strcmp(getset->name, "__module__") == 0) { + PyObject *descr = PyDescr_NewGetSet(type, getset); + if (unlikely(!descr)) + return -1; + #if CYTHON_COMPILING_IN_LIMITED_API + PyObject *pyname = PyUnicode_FromString(getset->name); + if (unlikely(!pyname)) { + Py_DECREF(descr); + return -1; + } + int set_item_result = __Pyx_SetItemOnTypeDict(type, pyname, descr); + Py_DECREF(pyname); + #else + CYTHON_UNUSED_VAR(__Pyx__SetItemOnTypeDict); + int set_item_result = PyDict_SetItem(type->tp_dict, PyDescr_NAME(descr), descr); + #endif + Py_DECREF(descr); + if (unlikely(set_item_result < 0)) { + return -1; + } + changed = 1; + } + ++getset; + } + } +#else + CYTHON_UNUSED_VAR(__Pyx__SetItemOnTypeDict); +#endif // !CYTHON_COMPILING_IN_PYPY + if (changed) + PyType_Modified(type); +#endif // PY_VERSION_HEX > 0x030900B1 + return 0; +} + +/* PyObjectCallNoArg (used by PyObjectCallMethod0) */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func) { + PyObject *arg[2] = {NULL, NULL}; + return __Pyx_PyObject_FastCall(func, arg + 1, 0 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET); +} + +/* PyObjectGetMethod (used by PyObjectCallMethod0) */ +#if !(CYTHON_VECTORCALL && (__PYX_LIMITED_VERSION_HEX >= 0x030C0000 || (!CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x03090000))) +static int __Pyx_PyObject_GetMethod(PyObject *obj, PyObject *name, PyObject **method) { + PyObject *attr; +#if CYTHON_UNPACK_METHODS && CYTHON_COMPILING_IN_CPYTHON && CYTHON_USE_PYTYPE_LOOKUP + __Pyx_TypeName type_name; + PyTypeObject *tp = Py_TYPE(obj); + PyObject *descr; + descrgetfunc f = NULL; + PyObject **dictptr, *dict; + int meth_found = 0; + assert (*method == NULL); + if (unlikely(tp->tp_getattro != PyObject_GenericGetAttr)) { + attr = __Pyx_PyObject_GetAttrStr(obj, name); + goto try_unpack; + } + if (unlikely(tp->tp_dict == NULL) && unlikely(PyType_Ready(tp) < 0)) { + return 0; + } + descr = _PyType_Lookup(tp, name); + if (likely(descr != NULL)) { + Py_INCREF(descr); +#if defined(Py_TPFLAGS_METHOD_DESCRIPTOR) && Py_TPFLAGS_METHOD_DESCRIPTOR + if (__Pyx_PyType_HasFeature(Py_TYPE(descr), Py_TPFLAGS_METHOD_DESCRIPTOR)) +#else + #ifdef __Pyx_CyFunction_USED + if (likely(PyFunction_Check(descr) || __Pyx_IS_TYPE(descr, &PyMethodDescr_Type) || __Pyx_CyFunction_Check(descr))) + #else + if (likely(PyFunction_Check(descr) || __Pyx_IS_TYPE(descr, &PyMethodDescr_Type))) + #endif +#endif + { + meth_found = 1; + } else { + f = Py_TYPE(descr)->tp_descr_get; + if (f != NULL && PyDescr_IsData(descr)) { + attr = f(descr, obj, (PyObject *)Py_TYPE(obj)); + Py_DECREF(descr); + goto try_unpack; + } + } + } + dictptr = _PyObject_GetDictPtr(obj); + if (dictptr != NULL && (dict = *dictptr) != NULL) { + Py_INCREF(dict); + attr = __Pyx_PyDict_GetItemStr(dict, name); + if (attr != NULL) { + Py_INCREF(attr); + Py_DECREF(dict); + Py_XDECREF(descr); + goto try_unpack; + } + Py_DECREF(dict); + } + if (meth_found) { + *method = descr; + return 1; + } + if (f != NULL) { + attr = f(descr, obj, (PyObject *)Py_TYPE(obj)); + Py_DECREF(descr); + goto try_unpack; + } + if (likely(descr != NULL)) { + *method = descr; + return 0; + } + type_name = __Pyx_PyType_GetFullyQualifiedName(tp); + PyErr_Format(PyExc_AttributeError, + "'" __Pyx_FMT_TYPENAME "' object has no attribute '%U'", + type_name, name); + __Pyx_DECREF_TypeName(type_name); + return 0; +#else + attr = __Pyx_PyObject_GetAttrStr(obj, name); + goto try_unpack; +#endif +try_unpack: +#if CYTHON_UNPACK_METHODS + if (likely(attr) && PyMethod_Check(attr) && likely(PyMethod_GET_SELF(attr) == obj)) { + PyObject *function = PyMethod_GET_FUNCTION(attr); + Py_INCREF(function); + Py_DECREF(attr); + *method = function; + return 1; + } +#endif + *method = attr; + return 0; +} +#endif + +/* PyObjectCallMethod0 (used by PyType_Ready) */ +static PyObject* __Pyx_PyObject_CallMethod0(PyObject* obj, PyObject* method_name) { +#if CYTHON_VECTORCALL && (__PYX_LIMITED_VERSION_HEX >= 0x030C0000 || (!CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x03090000)) + PyObject *args[1] = {obj}; + (void) __Pyx_PyObject_CallOneArg; + (void) __Pyx_PyObject_CallNoArg; + return PyObject_VectorcallMethod(method_name, args, 1 | PY_VECTORCALL_ARGUMENTS_OFFSET, NULL); +#else + PyObject *method = NULL, *result = NULL; + int is_method = __Pyx_PyObject_GetMethod(obj, method_name, &method); + if (likely(is_method)) { + result = __Pyx_PyObject_CallOneArg(method, obj); + Py_DECREF(method); + return result; + } + if (unlikely(!method)) goto bad; + result = __Pyx_PyObject_CallNoArg(method); + Py_DECREF(method); +bad: + return result; +#endif +} + +/* ValidateBasesTuple (used by PyType_Ready) */ +#if CYTHON_COMPILING_IN_CPYTHON || CYTHON_COMPILING_IN_LIMITED_API || CYTHON_USE_TYPE_SPECS +static int __Pyx_validate_bases_tuple(const char *type_name, Py_ssize_t dictoffset, PyObject *bases) { + Py_ssize_t i, n; +#if CYTHON_ASSUME_SAFE_SIZE + n = PyTuple_GET_SIZE(bases); +#else + n = PyTuple_Size(bases); + if (unlikely(n < 0)) return -1; +#endif + for (i = 1; i < n; i++) + { + PyTypeObject *b; +#if CYTHON_AVOID_BORROWED_REFS + PyObject *b0 = PySequence_GetItem(bases, i); + if (!b0) return -1; +#elif CYTHON_ASSUME_SAFE_MACROS + PyObject *b0 = PyTuple_GET_ITEM(bases, i); +#else + PyObject *b0 = PyTuple_GetItem(bases, i); + if (!b0) return -1; +#endif + b = (PyTypeObject*) b0; + if (!__Pyx_PyType_HasFeature(b, Py_TPFLAGS_HEAPTYPE)) + { + __Pyx_TypeName b_name = __Pyx_PyType_GetFullyQualifiedName(b); + PyErr_Format(PyExc_TypeError, + "base class '" __Pyx_FMT_TYPENAME "' is not a heap type", b_name); + __Pyx_DECREF_TypeName(b_name); +#if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(b0); +#endif + return -1; + } + if (dictoffset == 0) + { + Py_ssize_t b_dictoffset = 0; +#if CYTHON_USE_TYPE_SLOTS + b_dictoffset = b->tp_dictoffset; +#else + PyObject *py_b_dictoffset = PyObject_GetAttrString((PyObject*)b, "__dictoffset__"); + if (!py_b_dictoffset) goto dictoffset_return; + b_dictoffset = PyLong_AsSsize_t(py_b_dictoffset); + Py_DECREF(py_b_dictoffset); + if (b_dictoffset == -1 && PyErr_Occurred()) goto dictoffset_return; +#endif + if (b_dictoffset) { + { + __Pyx_TypeName b_name = __Pyx_PyType_GetFullyQualifiedName(b); + PyErr_Format(PyExc_TypeError, + "extension type '%.200s' has no __dict__ slot, " + "but base type '" __Pyx_FMT_TYPENAME "' has: " + "either add 'cdef dict __dict__' to the extension type " + "or add '__slots__ = [...]' to the base type", + type_name, b_name); + __Pyx_DECREF_TypeName(b_name); + } +#if !CYTHON_USE_TYPE_SLOTS + dictoffset_return: +#endif +#if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(b0); +#endif + return -1; + } + } +#if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(b0); +#endif + } + return 0; +} +#endif + +/* PyType_Ready */ +CYTHON_UNUSED static int __Pyx_PyType_HasMultipleInheritance(PyTypeObject *t) { + while (t) { + PyObject *bases = __Pyx_PyType_GetSlot(t, tp_bases, PyObject*); + if (bases) { + return 1; + } + t = __Pyx_PyType_GetSlot(t, tp_base, PyTypeObject*); + } + return 0; +} +static int __Pyx_PyType_Ready(PyTypeObject *t) { +#if CYTHON_USE_TYPE_SPECS || !CYTHON_COMPILING_IN_CPYTHON || defined(PYSTON_MAJOR_VERSION) + (void)__Pyx_PyObject_CallMethod0; +#if CYTHON_USE_TYPE_SPECS + (void)__Pyx_validate_bases_tuple; +#endif + return PyType_Ready(t); +#else + int r; + if (!__Pyx_PyType_HasMultipleInheritance(t)) { + return PyType_Ready(t); + } + PyObject *bases = __Pyx_PyType_GetSlot(t, tp_bases, PyObject*); + if (bases && unlikely(__Pyx_validate_bases_tuple(t->tp_name, t->tp_dictoffset, bases) == -1)) + return -1; +#if !defined(PYSTON_MAJOR_VERSION) + { + int gc_was_enabled; + #if PY_VERSION_HEX >= 0x030A00b1 + gc_was_enabled = PyGC_Disable(); + (void)__Pyx_PyObject_CallMethod0; + #else + PyObject *ret, *py_status; + PyObject *gc = NULL; + #if (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM+0 >= 0x07030400) &&\ + !CYTHON_COMPILING_IN_GRAAL + gc = PyImport_GetModule(__pyx_mstate_global->__pyx_kp_u_gc); + #endif + if (unlikely(!gc)) gc = PyImport_Import(__pyx_mstate_global->__pyx_kp_u_gc); + if (unlikely(!gc)) return -1; + py_status = __Pyx_PyObject_CallMethod0(gc, __pyx_mstate_global->__pyx_kp_u_isenabled); + if (unlikely(!py_status)) { + Py_DECREF(gc); + return -1; + } + gc_was_enabled = __Pyx_PyObject_IsTrue(py_status); + Py_DECREF(py_status); + if (gc_was_enabled > 0) { + ret = __Pyx_PyObject_CallMethod0(gc, __pyx_mstate_global->__pyx_kp_u_disable); + if (unlikely(!ret)) { + Py_DECREF(gc); + return -1; + } + Py_DECREF(ret); + } else if (unlikely(gc_was_enabled == -1)) { + Py_DECREF(gc); + return -1; + } + #endif + t->tp_flags |= Py_TPFLAGS_HEAPTYPE; +#if PY_VERSION_HEX >= 0x030A0000 + t->tp_flags |= Py_TPFLAGS_IMMUTABLETYPE; +#endif +#else + (void)__Pyx_PyObject_CallMethod0; +#endif + r = PyType_Ready(t); +#if !defined(PYSTON_MAJOR_VERSION) + t->tp_flags &= ~Py_TPFLAGS_HEAPTYPE; + #if PY_VERSION_HEX >= 0x030A00b1 + if (gc_was_enabled) + PyGC_Enable(); + #else + if (gc_was_enabled) { + PyObject *tp, *v, *tb; + PyErr_Fetch(&tp, &v, &tb); + ret = __Pyx_PyObject_CallMethod0(gc, __pyx_mstate_global->__pyx_kp_u_enable); + if (likely(ret || r == -1)) { + Py_XDECREF(ret); + PyErr_Restore(tp, v, tb); + } else { + Py_XDECREF(tp); + Py_XDECREF(v); + Py_XDECREF(tb); + r = -1; + } + } + Py_DECREF(gc); + #endif + } +#endif + return r; +#endif +} + +/* SetVTable */ +static int __Pyx_SetVtable(PyTypeObject *type, void *vtable) { + PyObject *ob = PyCapsule_New(vtable, 0, 0); + if (unlikely(!ob)) + goto bad; +#if CYTHON_COMPILING_IN_LIMITED_API + if (unlikely(PyObject_SetAttr((PyObject *) type, __pyx_mstate_global->__pyx_n_u_pyx_vtable, ob) < 0)) +#else + if (unlikely(PyDict_SetItem(type->tp_dict, __pyx_mstate_global->__pyx_n_u_pyx_vtable, ob) < 0)) +#endif + goto bad; + Py_DECREF(ob); + return 0; +bad: + Py_XDECREF(ob); + return -1; +} + +/* MergeVTables */ +static int __Pyx_MergeVtables(PyTypeObject *type) { + int i=0; + Py_ssize_t size; + void** base_vtables; + __Pyx_TypeName tp_base_name = NULL; + __Pyx_TypeName base_name = NULL; + void* unknown = (void*)-1; + PyObject* bases = __Pyx_PyType_GetSlot(type, tp_bases, PyObject*); + int base_depth = 0; + { + PyTypeObject* base = __Pyx_PyType_GetSlot(type, tp_base, PyTypeObject*); + while (base) { + base_depth += 1; + base = __Pyx_PyType_GetSlot(base, tp_base, PyTypeObject*); + } + } + base_vtables = (void**) PyMem_Malloc(sizeof(void*) * (size_t)(base_depth + 1)); + base_vtables[0] = unknown; +#if CYTHON_COMPILING_IN_LIMITED_API + size = PyTuple_Size(bases); + if (size < 0) goto other_failure; +#else + size = PyTuple_GET_SIZE(bases); +#endif + for (i = 1; i < size; i++) { + PyObject *basei; + void* base_vtable; +#if CYTHON_AVOID_BORROWED_REFS + basei = PySequence_GetItem(bases, i); + if (unlikely(!basei)) goto other_failure; +#elif !CYTHON_ASSUME_SAFE_MACROS + basei = PyTuple_GetItem(bases, i); + if (unlikely(!basei)) goto other_failure; +#else + basei = PyTuple_GET_ITEM(bases, i); +#endif + base_vtable = __Pyx_GetVtable((PyTypeObject*)basei); +#if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(basei); +#endif + if (base_vtable != NULL) { + int j; + PyTypeObject* base = __Pyx_PyType_GetSlot(type, tp_base, PyTypeObject*); + for (j = 0; j < base_depth; j++) { + if (base_vtables[j] == unknown) { + base_vtables[j] = __Pyx_GetVtable(base); + base_vtables[j + 1] = unknown; + } + if (base_vtables[j] == base_vtable) { + break; + } else if (base_vtables[j] == NULL) { + goto bad; + } + base = __Pyx_PyType_GetSlot(base, tp_base, PyTypeObject*); + } + } + } + PyErr_Clear(); + PyMem_Free(base_vtables); + return 0; +bad: + { + PyTypeObject* basei = NULL; + PyTypeObject* tp_base = __Pyx_PyType_GetSlot(type, tp_base, PyTypeObject*); + tp_base_name = __Pyx_PyType_GetFullyQualifiedName(tp_base); +#if CYTHON_AVOID_BORROWED_REFS + basei = (PyTypeObject*)PySequence_GetItem(bases, i); + if (unlikely(!basei)) goto really_bad; +#elif !CYTHON_ASSUME_SAFE_MACROS + basei = (PyTypeObject*)PyTuple_GetItem(bases, i); + if (unlikely(!basei)) goto really_bad; +#else + basei = (PyTypeObject*)PyTuple_GET_ITEM(bases, i); +#endif + base_name = __Pyx_PyType_GetFullyQualifiedName(basei); +#if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(basei); +#endif + } + PyErr_Format(PyExc_TypeError, + "multiple bases have vtable conflict: '" __Pyx_FMT_TYPENAME "' and '" __Pyx_FMT_TYPENAME "'", tp_base_name, base_name); +#if CYTHON_AVOID_BORROWED_REFS || !CYTHON_ASSUME_SAFE_MACROS +really_bad: // bad has failed! +#endif + __Pyx_DECREF_TypeName(tp_base_name); + __Pyx_DECREF_TypeName(base_name); +#if CYTHON_COMPILING_IN_LIMITED_API || CYTHON_AVOID_BORROWED_REFS || !CYTHON_ASSUME_SAFE_MACROS +other_failure: +#endif + PyMem_Free(base_vtables); + return -1; +} + +/* DelItemOnTypeDict (used by SetupReduce) */ +static int __Pyx__DelItemOnTypeDict(PyTypeObject *tp, PyObject *k) { + int result; + PyObject *tp_dict; +#if CYTHON_COMPILING_IN_LIMITED_API + tp_dict = __Pyx_GetTypeDict(tp); + if (unlikely(!tp_dict)) return -1; +#else + tp_dict = tp->tp_dict; +#endif + result = PyDict_DelItem(tp_dict, k); + if (likely(!result)) PyType_Modified(tp); + return result; +} + +/* SetupReduce */ +static int __Pyx_setup_reduce_is_named(PyObject* meth, PyObject* name) { + int ret; + PyObject *name_attr; + name_attr = __Pyx_PyObject_GetAttrStrNoError(meth, __pyx_mstate_global->__pyx_n_u_name); + if (likely(name_attr)) { + ret = PyObject_RichCompareBool(name_attr, name, Py_EQ); + } else { + ret = -1; + } + if (unlikely(ret < 0)) { + PyErr_Clear(); + ret = 0; + } + Py_XDECREF(name_attr); + return ret; +} +static int __Pyx_setup_reduce(PyObject* type_obj) { + int ret = 0; + PyObject *object_reduce = NULL; + PyObject *object_getstate = NULL; + PyObject *object_reduce_ex = NULL; + PyObject *reduce = NULL; + PyObject *reduce_ex = NULL; + PyObject *reduce_cython = NULL; + PyObject *setstate = NULL; + PyObject *setstate_cython = NULL; + PyObject *getstate = NULL; +#if CYTHON_USE_PYTYPE_LOOKUP + getstate = _PyType_Lookup((PyTypeObject*)type_obj, __pyx_mstate_global->__pyx_n_u_getstate); +#else + getstate = __Pyx_PyObject_GetAttrStrNoError(type_obj, __pyx_mstate_global->__pyx_n_u_getstate); + if (!getstate && PyErr_Occurred()) { + goto __PYX_BAD; + } +#endif + if (getstate) { +#if CYTHON_USE_PYTYPE_LOOKUP + object_getstate = _PyType_Lookup(&PyBaseObject_Type, __pyx_mstate_global->__pyx_n_u_getstate); +#else + object_getstate = __Pyx_PyObject_GetAttrStrNoError((PyObject*)&PyBaseObject_Type, __pyx_mstate_global->__pyx_n_u_getstate); + if (!object_getstate && PyErr_Occurred()) { + goto __PYX_BAD; + } +#endif + if (object_getstate != getstate) { + goto __PYX_GOOD; + } + } +#if CYTHON_USE_PYTYPE_LOOKUP + object_reduce_ex = _PyType_Lookup(&PyBaseObject_Type, __pyx_mstate_global->__pyx_n_u_reduce_ex); if (!object_reduce_ex) goto __PYX_BAD; +#else + object_reduce_ex = __Pyx_PyObject_GetAttrStr((PyObject*)&PyBaseObject_Type, __pyx_mstate_global->__pyx_n_u_reduce_ex); if (!object_reduce_ex) goto __PYX_BAD; +#endif + reduce_ex = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_mstate_global->__pyx_n_u_reduce_ex); if (unlikely(!reduce_ex)) goto __PYX_BAD; + if (reduce_ex == object_reduce_ex) { +#if CYTHON_USE_PYTYPE_LOOKUP + object_reduce = _PyType_Lookup(&PyBaseObject_Type, __pyx_mstate_global->__pyx_n_u_reduce); if (!object_reduce) goto __PYX_BAD; +#else + object_reduce = __Pyx_PyObject_GetAttrStr((PyObject*)&PyBaseObject_Type, __pyx_mstate_global->__pyx_n_u_reduce); if (!object_reduce) goto __PYX_BAD; +#endif + reduce = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_mstate_global->__pyx_n_u_reduce); if (unlikely(!reduce)) goto __PYX_BAD; + if (reduce == object_reduce || __Pyx_setup_reduce_is_named(reduce, __pyx_mstate_global->__pyx_n_u_reduce_cython)) { + reduce_cython = __Pyx_PyObject_GetAttrStrNoError(type_obj, __pyx_mstate_global->__pyx_n_u_reduce_cython); + if (likely(reduce_cython)) { + ret = __Pyx_SetItemOnTypeDict((PyTypeObject*)type_obj, __pyx_mstate_global->__pyx_n_u_reduce, reduce_cython); if (unlikely(ret < 0)) goto __PYX_BAD; + ret = __Pyx_DelItemOnTypeDict((PyTypeObject*)type_obj, __pyx_mstate_global->__pyx_n_u_reduce_cython); if (unlikely(ret < 0)) goto __PYX_BAD; + } else if (reduce == object_reduce || PyErr_Occurred()) { + goto __PYX_BAD; + } + setstate = __Pyx_PyObject_GetAttrStrNoError(type_obj, __pyx_mstate_global->__pyx_n_u_setstate); + if (!setstate) PyErr_Clear(); + if (!setstate || __Pyx_setup_reduce_is_named(setstate, __pyx_mstate_global->__pyx_n_u_setstate_cython)) { + setstate_cython = __Pyx_PyObject_GetAttrStrNoError(type_obj, __pyx_mstate_global->__pyx_n_u_setstate_cython); + if (likely(setstate_cython)) { + ret = __Pyx_SetItemOnTypeDict((PyTypeObject*)type_obj, __pyx_mstate_global->__pyx_n_u_setstate, setstate_cython); if (unlikely(ret < 0)) goto __PYX_BAD; + ret = __Pyx_DelItemOnTypeDict((PyTypeObject*)type_obj, __pyx_mstate_global->__pyx_n_u_setstate_cython); if (unlikely(ret < 0)) goto __PYX_BAD; + } else if (!setstate || PyErr_Occurred()) { + goto __PYX_BAD; + } + } + PyType_Modified((PyTypeObject*)type_obj); + } + } + goto __PYX_GOOD; +__PYX_BAD: + if (!PyErr_Occurred()) { + __Pyx_TypeName type_obj_name = + __Pyx_PyType_GetFullyQualifiedName((PyTypeObject*)type_obj); + PyErr_Format(PyExc_RuntimeError, + "Unable to initialize pickling for " __Pyx_FMT_TYPENAME, type_obj_name); + __Pyx_DECREF_TypeName(type_obj_name); + } + ret = -1; +__PYX_GOOD: +#if !CYTHON_USE_PYTYPE_LOOKUP + Py_XDECREF(object_reduce); + Py_XDECREF(object_reduce_ex); + Py_XDECREF(object_getstate); + Py_XDECREF(getstate); +#endif + Py_XDECREF(reduce); + Py_XDECREF(reduce_ex); + Py_XDECREF(reduce_cython); + Py_XDECREF(setstate); + Py_XDECREF(setstate_cython); + return ret; +} + +/* dict_setdefault (used by FetchCommonType) */ +static CYTHON_INLINE PyObject *__Pyx_PyDict_SetDefault(PyObject *d, PyObject *key, PyObject *default_value) { + PyObject* value; +#if __PYX_LIMITED_VERSION_HEX >= 0x030F0000 || (!CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d00A4) + PyDict_SetDefaultRef(d, key, default_value, &value); +#elif CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX >= 0x030C0000 + PyObject *args[] = {d, key, default_value}; + value = PyObject_VectorcallMethod(__pyx_mstate_global->__pyx_n_u_setdefault, args, 3 | PY_VECTORCALL_ARGUMENTS_OFFSET, NULL); +#elif CYTHON_COMPILING_IN_LIMITED_API + value = PyObject_CallMethodObjArgs(d, __pyx_mstate_global->__pyx_n_u_setdefault, key, default_value, NULL); +#else + value = PyDict_SetDefault(d, key, default_value); + if (unlikely(!value)) return NULL; + Py_INCREF(value); +#endif + return value; +} + +/* AddModuleRef (used by FetchSharedCythonModule) */ +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + static PyObject *__Pyx_PyImport_AddModuleObjectRef(PyObject *name) { + PyObject *module_dict = PyImport_GetModuleDict(); + PyObject *m; + if (PyMapping_GetOptionalItem(module_dict, name, &m) < 0) { + return NULL; + } + if (m != NULL && PyModule_Check(m)) { + return m; + } + Py_XDECREF(m); + m = PyModule_NewObject(name); + if (m == NULL) + return NULL; + if (PyDict_CheckExact(module_dict)) { + PyObject *new_m; + (void)PyDict_SetDefaultRef(module_dict, name, m, &new_m); + Py_DECREF(m); + return new_m; + } else { + if (PyObject_SetItem(module_dict, name, m) != 0) { + Py_DECREF(m); + return NULL; + } + return m; + } + } + static PyObject *__Pyx_PyImport_AddModuleRef(const char *name) { + PyObject *py_name = PyUnicode_FromString(name); + if (!py_name) return NULL; + PyObject *module = __Pyx_PyImport_AddModuleObjectRef(py_name); + Py_DECREF(py_name); + return module; + } +#elif __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + #define __Pyx_PyImport_AddModuleRef(name) PyImport_AddModuleRef(name) +#else + static PyObject *__Pyx_PyImport_AddModuleRef(const char *name) { + PyObject *module = PyImport_AddModule(name); + Py_XINCREF(module); + return module; + } +#endif + +/* FetchSharedCythonModule (used by FetchCommonType) */ +static PyObject *__Pyx_FetchSharedCythonABIModule(void) { + return __Pyx_PyImport_AddModuleRef(__PYX_ABI_MODULE_NAME); +} + +/* FetchCommonType (used by CommonTypesMetaclass) */ +#if __PYX_LIMITED_VERSION_HEX < 0x030C0000 +static PyObject* __Pyx_PyType_FromMetaclass(PyTypeObject *metaclass, PyObject *module, PyType_Spec *spec, PyObject *bases) { + PyObject *result = __Pyx_PyType_FromModuleAndSpec(module, spec, bases); + if (result && metaclass) { + PyObject *old_tp = (PyObject*)Py_TYPE(result); + Py_INCREF((PyObject*)metaclass); +#if __PYX_LIMITED_VERSION_HEX >= 0x03090000 + Py_SET_TYPE(result, metaclass); +#else + result->ob_type = metaclass; +#endif + Py_DECREF(old_tp); + } + return result; +} +#else +#define __Pyx_PyType_FromMetaclass(me, mo, s, b) PyType_FromMetaclass(me, mo, s, b) +#endif +static int __Pyx_VerifyCachedType(PyObject *cached_type, + const char *name, + Py_ssize_t expected_basicsize) { + Py_ssize_t basicsize; + if (!PyType_Check(cached_type)) { + PyErr_Format(PyExc_TypeError, + "Shared Cython type %.200s is not a type object", name); + return -1; + } + if (expected_basicsize == 0) { + return 0; // size is inherited, nothing useful to check + } +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *py_basicsize; + py_basicsize = PyObject_GetAttrString(cached_type, "__basicsize__"); + if (unlikely(!py_basicsize)) return -1; + basicsize = PyLong_AsSsize_t(py_basicsize); + Py_DECREF(py_basicsize); + py_basicsize = NULL; + if (unlikely(basicsize == (Py_ssize_t)-1) && PyErr_Occurred()) return -1; +#else + basicsize = ((PyTypeObject*) cached_type)->tp_basicsize; +#endif + if (basicsize != expected_basicsize) { + PyErr_Format(PyExc_TypeError, + "Shared Cython type %.200s has the wrong size, try recompiling", + name); + return -1; + } + return 0; +} +static PyTypeObject *__Pyx_FetchCommonTypeFromSpec(PyTypeObject *metaclass, PyObject *module, PyType_Spec *spec, PyObject *bases) { + PyObject *abi_module = NULL, *cached_type = NULL, *abi_module_dict, *new_cached_type, *py_object_name; + int get_item_ref_result; + const char* object_name = strrchr(spec->name, '.'); + object_name = object_name ? object_name+1 : spec->name; + py_object_name = PyUnicode_FromString(object_name); + if (!py_object_name) return NULL; + abi_module = __Pyx_FetchSharedCythonABIModule(); + if (!abi_module) goto done; + abi_module_dict = PyModule_GetDict(abi_module); + if (!abi_module_dict) goto done; + get_item_ref_result = __Pyx_PyDict_GetItemRef(abi_module_dict, py_object_name, &cached_type); + if (get_item_ref_result == 1) { + if (__Pyx_VerifyCachedType( + cached_type, + object_name, + spec->basicsize) < 0) { + goto bad; + } + goto done; + } else if (unlikely(get_item_ref_result == -1)) { + goto bad; + } + cached_type = __Pyx_PyType_FromMetaclass( + metaclass, + CYTHON_USE_MODULE_STATE ? module : abi_module, + spec, bases); + if (unlikely(!cached_type)) goto bad; + if (unlikely(__Pyx_fix_up_extension_type_from_spec(spec, (PyTypeObject *) cached_type) < 0)) goto bad; + new_cached_type = __Pyx_PyDict_SetDefault(abi_module_dict, py_object_name, cached_type); + if (unlikely(new_cached_type != cached_type)) { + if (unlikely(!new_cached_type)) goto bad; + Py_DECREF(cached_type); + cached_type = new_cached_type; + if (__Pyx_VerifyCachedType( + cached_type, + object_name, + spec->basicsize) < 0) { + goto bad; + } + goto done; + } else { + Py_DECREF(new_cached_type); + } +done: + Py_XDECREF(abi_module); + Py_DECREF(py_object_name); + assert(cached_type == NULL || PyType_Check(cached_type)); + return (PyTypeObject *) cached_type; +bad: + Py_XDECREF(cached_type); + cached_type = NULL; + goto done; +} + +/* CommonTypesMetaclass (used by CythonFunctionShared) */ +static PyObject* __pyx_CommonTypesMetaclass_get_module(CYTHON_UNUSED PyObject *self, CYTHON_UNUSED void* context) { + return PyUnicode_FromString(__PYX_ABI_MODULE_NAME); +} +#if __PYX_LIMITED_VERSION_HEX < 0x030A0000 +static PyObject* __pyx_CommonTypesMetaclass_call(CYTHON_UNUSED PyObject *self, CYTHON_UNUSED PyObject *args, CYTHON_UNUSED PyObject *kwds) { + PyErr_SetString(PyExc_TypeError, "Cannot instantiate Cython internal types"); + return NULL; +} +static int __pyx_CommonTypesMetaclass_setattr(CYTHON_UNUSED PyObject *self, CYTHON_UNUSED PyObject *attr, CYTHON_UNUSED PyObject *value) { + PyErr_SetString(PyExc_TypeError, "Cython internal types are immutable"); + return -1; +} +#endif +static PyGetSetDef __pyx_CommonTypesMetaclass_getset[] = { + {"__module__", __pyx_CommonTypesMetaclass_get_module, NULL, NULL, NULL}, + {0, 0, 0, 0, 0} +}; +static PyType_Slot __pyx_CommonTypesMetaclass_slots[] = { + {Py_tp_getset, (void *)__pyx_CommonTypesMetaclass_getset}, + #if __PYX_LIMITED_VERSION_HEX < 0x030A0000 + {Py_tp_call, (void*)__pyx_CommonTypesMetaclass_call}, + {Py_tp_new, (void*)__pyx_CommonTypesMetaclass_call}, + {Py_tp_setattro, (void*)__pyx_CommonTypesMetaclass_setattr}, + #endif + {0, 0} +}; +static PyType_Spec __pyx_CommonTypesMetaclass_spec = { + __PYX_TYPE_MODULE_PREFIX "_common_types_metatype", + 0, + 0, + Py_TPFLAGS_IMMUTABLETYPE | + Py_TPFLAGS_DISALLOW_INSTANTIATION | + Py_TPFLAGS_DEFAULT, + __pyx_CommonTypesMetaclass_slots +}; +static int __pyx_CommonTypesMetaclass_init(PyObject *module) { + __pyx_mstatetype *mstate = __Pyx_PyModule_GetState(module); + PyObject *bases = PyTuple_Pack(1, &PyType_Type); + if (unlikely(!bases)) { + return -1; + } + mstate->__pyx_CommonTypesMetaclassType = __Pyx_FetchCommonTypeFromSpec(NULL, module, &__pyx_CommonTypesMetaclass_spec, bases); + Py_DECREF(bases); + if (unlikely(mstate->__pyx_CommonTypesMetaclassType == NULL)) { + return -1; + } + return 0; +} + +/* PyMethodNew (used by CythonFunctionShared) */ +#if CYTHON_COMPILING_IN_LIMITED_API +static PyObject *__Pyx_PyMethod_New(PyObject *func, PyObject *self, PyObject *typ) { + PyObject *result; + CYTHON_UNUSED_VAR(typ); + if (!self) + return __Pyx_NewRef(func); + #if __PYX_LIMITED_VERSION_HEX >= 0x030C0000 + { + PyObject *args[] = {func, self}; + result = PyObject_Vectorcall(__pyx_mstate_global->__Pyx_CachedMethodType, args, 2, NULL); + } + #else + result = PyObject_CallFunctionObjArgs(__pyx_mstate_global->__Pyx_CachedMethodType, func, self, NULL); + #endif + return result; +} +#else +static PyObject *__Pyx_PyMethod_New(PyObject *func, PyObject *self, PyObject *typ) { + CYTHON_UNUSED_VAR(typ); + if (!self) + return __Pyx_NewRef(func); + return PyMethod_New(func, self); +} +#endif + +/* PyVectorcallFastCallDict (used by CythonFunctionShared) */ +#if CYTHON_METH_FASTCALL && CYTHON_VECTORCALL +static PyObject *__Pyx_PyVectorcall_FastCallDict_kw(PyObject *func, __pyx_vectorcallfunc vc, PyObject *const *args, size_t nargs, PyObject *kw) +{ + PyObject *res = NULL; + PyObject *kwnames; + PyObject **newargs; + PyObject **kwvalues; + Py_ssize_t i; + #if CYTHON_AVOID_BORROWED_REFS + PyObject *pos; + #else + Py_ssize_t pos; + #endif + size_t j; + PyObject *key, *value; + unsigned long keys_are_strings; + #if !CYTHON_ASSUME_SAFE_SIZE + Py_ssize_t nkw = PyDict_Size(kw); + if (unlikely(nkw == -1)) return NULL; + #else + Py_ssize_t nkw = PyDict_GET_SIZE(kw); + #endif + newargs = (PyObject **)PyMem_Malloc((nargs + (size_t)nkw) * sizeof(args[0])); + if (unlikely(newargs == NULL)) { + PyErr_NoMemory(); + return NULL; + } + for (j = 0; j < nargs; j++) newargs[j] = args[j]; + kwnames = PyTuple_New(nkw); + if (unlikely(kwnames == NULL)) { + PyMem_Free(newargs); + return NULL; + } + kwvalues = newargs + nargs; + pos = 0; + i = 0; + keys_are_strings = Py_TPFLAGS_UNICODE_SUBCLASS; + while (__Pyx_PyDict_NextRef(kw, &pos, &key, &value)) { + keys_are_strings &= + #if CYTHON_COMPILING_IN_LIMITED_API + PyType_GetFlags(Py_TYPE(key)); + #else + Py_TYPE(key)->tp_flags; + #endif + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(PyTuple_SetItem(kwnames, i, key) < 0)) goto cleanup; + #else + PyTuple_SET_ITEM(kwnames, i, key); + #endif + kwvalues[i] = value; + i++; + } + if (unlikely(!keys_are_strings)) { + PyErr_SetString(PyExc_TypeError, "keywords must be strings"); + goto cleanup; + } + res = vc(func, newargs, nargs, kwnames); +cleanup: + #if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(pos); + #endif + Py_DECREF(kwnames); + for (i = 0; i < nkw; i++) + Py_DECREF(kwvalues[i]); + PyMem_Free(newargs); + return res; +} +static CYTHON_INLINE PyObject *__Pyx_PyVectorcall_FastCallDict(PyObject *func, __pyx_vectorcallfunc vc, PyObject *const *args, size_t nargs, PyObject *kw) +{ + Py_ssize_t kw_size = + likely(kw == NULL) ? + 0 : +#if !CYTHON_ASSUME_SAFE_SIZE + PyDict_Size(kw); +#else + PyDict_GET_SIZE(kw); +#endif + if (kw_size == 0) { + return vc(func, args, nargs, NULL); + } +#if !CYTHON_ASSUME_SAFE_SIZE + else if (unlikely(kw_size == -1)) { + return NULL; + } +#endif + return __Pyx_PyVectorcall_FastCallDict_kw(func, vc, args, nargs, kw); +} +#endif + +/* CythonFunctionShared (used by CythonFunction) */ +#if CYTHON_COMPILING_IN_LIMITED_API +static CYTHON_INLINE int __Pyx__IsSameCyOrCFunctionNoMethod(PyObject *func, void (*cfunc)(void)) { + if (__Pyx_CyFunction_Check(func)) { + return PyCFunction_GetFunction(((__pyx_CyFunctionObject*)func)->func) == (PyCFunction) cfunc; + } else if (PyCFunction_Check(func)) { + return PyCFunction_GetFunction(func) == (PyCFunction) cfunc; + } + return 0; +} +static CYTHON_INLINE int __Pyx__IsSameCyOrCFunction(PyObject *func, void (*cfunc)(void)) { + if ((PyObject*)Py_TYPE(func) == __pyx_mstate_global->__Pyx_CachedMethodType) { + int result; + PyObject *newFunc = PyObject_GetAttr(func, __pyx_mstate_global->__pyx_n_u_func); + if (unlikely(!newFunc)) { + PyErr_Clear(); // It's only an optimization, so don't throw an error + return 0; + } + result = __Pyx__IsSameCyOrCFunctionNoMethod(newFunc, cfunc); + Py_DECREF(newFunc); + return result; + } + return __Pyx__IsSameCyOrCFunctionNoMethod(func, cfunc); +} +#else +static CYTHON_INLINE int __Pyx__IsSameCyOrCFunction(PyObject *func, void (*cfunc)(void)) { + if (PyMethod_Check(func)) { + func = PyMethod_GET_FUNCTION(func); + } + return __Pyx_CyOrPyCFunction_Check(func) && __Pyx_CyOrPyCFunction_GET_FUNCTION(func) == (PyCFunction) cfunc; +} +#endif +static CYTHON_INLINE void __Pyx__CyFunction_SetClassObj(__pyx_CyFunctionObject* f, PyObject* classobj) { +#if PY_VERSION_HEX < 0x030900B1 || CYTHON_COMPILING_IN_LIMITED_API + __Pyx_Py_XDECREF_SET( + __Pyx_CyFunction_GetClassObj(f), + ((classobj) ? __Pyx_NewRef(classobj) : NULL)); +#else + __Pyx_Py_XDECREF_SET( + ((PyCMethodObject *) (f))->mm_class, + (PyTypeObject*)((classobj) ? __Pyx_NewRef(classobj) : NULL)); +#endif +} +static PyObject * +__Pyx_CyFunction_get_doc_locked(__pyx_CyFunctionObject *op) +{ + if (unlikely(op->func_doc == NULL)) { +#if CYTHON_COMPILING_IN_LIMITED_API + op->func_doc = PyObject_GetAttrString(op->func, "__doc__"); + if (unlikely(!op->func_doc)) return NULL; +#else + if (((PyCFunctionObject*)op)->m_ml->ml_doc) { + op->func_doc = PyUnicode_FromString(((PyCFunctionObject*)op)->m_ml->ml_doc); + if (unlikely(op->func_doc == NULL)) + return NULL; + } else { + Py_INCREF(Py_None); + return Py_None; + } +#endif + } + Py_INCREF(op->func_doc); + return op->func_doc; +} +static PyObject * +__Pyx_CyFunction_get_doc(__pyx_CyFunctionObject *op, void *closure) { + PyObject *result; + CYTHON_UNUSED_VAR(closure); + __Pyx_BEGIN_CRITICAL_SECTION(op); + result = __Pyx_CyFunction_get_doc_locked(op); + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static int +__Pyx_CyFunction_set_doc(__pyx_CyFunctionObject *op, PyObject *value, void *context) +{ + CYTHON_UNUSED_VAR(context); + if (value == NULL) { + value = Py_None; + } + Py_INCREF(value); + __Pyx_BEGIN_CRITICAL_SECTION(op); + __Pyx_Py_XDECREF_SET(op->func_doc, value); + __Pyx_END_CRITICAL_SECTION(); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_name_locked(__pyx_CyFunctionObject *op) +{ + if (unlikely(op->func_name == NULL)) { +#if CYTHON_COMPILING_IN_LIMITED_API + op->func_name = PyObject_GetAttrString(op->func, "__name__"); +#else + op->func_name = PyUnicode_InternFromString(((PyCFunctionObject*)op)->m_ml->ml_name); +#endif + if (unlikely(op->func_name == NULL)) + return NULL; + } + Py_INCREF(op->func_name); + return op->func_name; +} +static PyObject * +__Pyx_CyFunction_get_name(__pyx_CyFunctionObject *op, void *context) +{ + PyObject *result = NULL; + CYTHON_UNUSED_VAR(context); + __Pyx_BEGIN_CRITICAL_SECTION(op); + result = __Pyx_CyFunction_get_name_locked(op); + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static int +__Pyx_CyFunction_set_name(__pyx_CyFunctionObject *op, PyObject *value, void *context) +{ + CYTHON_UNUSED_VAR(context); + if (unlikely(value == NULL || !PyUnicode_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "__name__ must be set to a string object"); + return -1; + } + Py_INCREF(value); + __Pyx_BEGIN_CRITICAL_SECTION(op); + __Pyx_Py_XDECREF_SET(op->func_name, value); + __Pyx_END_CRITICAL_SECTION(); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_qualname(__pyx_CyFunctionObject *op, void *context) +{ + CYTHON_UNUSED_VAR(context); + PyObject *result; + __Pyx_BEGIN_CRITICAL_SECTION(op); + Py_INCREF(op->func_qualname); + result = op->func_qualname; + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static int +__Pyx_CyFunction_set_qualname(__pyx_CyFunctionObject *op, PyObject *value, void *context) +{ + CYTHON_UNUSED_VAR(context); + if (unlikely(value == NULL || !PyUnicode_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "__qualname__ must be set to a string object"); + return -1; + } + Py_INCREF(value); + __Pyx_BEGIN_CRITICAL_SECTION(op); + __Pyx_Py_XDECREF_SET(op->func_qualname, value); + __Pyx_END_CRITICAL_SECTION(); + return 0; +} +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000 +static PyObject * +__Pyx_CyFunction_get_dict(__pyx_CyFunctionObject *op, void *context) +{ + CYTHON_UNUSED_VAR(context); + if (unlikely(op->func_dict == NULL)) { + op->func_dict = PyDict_New(); + if (unlikely(op->func_dict == NULL)) + return NULL; + } + Py_INCREF(op->func_dict); + return op->func_dict; +} +#endif +static PyObject * +__Pyx_CyFunction_get_globals(__pyx_CyFunctionObject *op, void *context) +{ + CYTHON_UNUSED_VAR(context); + Py_INCREF(op->func_globals); + return op->func_globals; +} +static PyObject * +__Pyx_CyFunction_get_closure(__pyx_CyFunctionObject *op, void *context) +{ + CYTHON_UNUSED_VAR(op); + CYTHON_UNUSED_VAR(context); + Py_INCREF(Py_None); + return Py_None; +} +static PyObject * +__Pyx_CyFunction_get_code(__pyx_CyFunctionObject *op, void *context) +{ + PyObject* result = (op->func_code) ? op->func_code : Py_None; + CYTHON_UNUSED_VAR(context); + Py_INCREF(result); + return result; +} +static int +__Pyx_CyFunction_init_defaults(__pyx_CyFunctionObject *op) { + int result = 0; + PyObject *res = op->defaults_getter((PyObject *) op); + if (unlikely(!res)) + return -1; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + op->defaults_tuple = PyTuple_GET_ITEM(res, 0); + Py_INCREF(op->defaults_tuple); + op->defaults_kwdict = PyTuple_GET_ITEM(res, 1); + Py_INCREF(op->defaults_kwdict); + #else + op->defaults_tuple = __Pyx_PySequence_ITEM(res, 0); + if (unlikely(!op->defaults_tuple)) result = -1; + else { + op->defaults_kwdict = __Pyx_PySequence_ITEM(res, 1); + if (unlikely(!op->defaults_kwdict)) result = -1; + } + #endif + Py_DECREF(res); + return result; +} +static int +__Pyx_CyFunction_set_defaults(__pyx_CyFunctionObject *op, PyObject* value, void *context) { + CYTHON_UNUSED_VAR(context); + if (!value) { + value = Py_None; + } else if (unlikely(value != Py_None && !PyTuple_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "__defaults__ must be set to a tuple object"); + return -1; + } + PyErr_WarnEx(PyExc_RuntimeWarning, "changes to cyfunction.__defaults__ will not " + "currently affect the values used in function calls", 1); + Py_INCREF(value); + __Pyx_BEGIN_CRITICAL_SECTION(op); + __Pyx_Py_XDECREF_SET(op->defaults_tuple, value); + __Pyx_END_CRITICAL_SECTION(); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_defaults_locked(__pyx_CyFunctionObject *op) { + PyObject* result = op->defaults_tuple; + if (unlikely(!result)) { + if (op->defaults_getter) { + if (unlikely(__Pyx_CyFunction_init_defaults(op) < 0)) return NULL; + result = op->defaults_tuple; + } else { + result = Py_None; + } + } + Py_INCREF(result); + return result; +} +static PyObject * +__Pyx_CyFunction_get_defaults(__pyx_CyFunctionObject *op, void *context) { + PyObject* result = NULL; + CYTHON_UNUSED_VAR(context); + __Pyx_BEGIN_CRITICAL_SECTION(op); + result = __Pyx_CyFunction_get_defaults_locked(op); + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static int +__Pyx_CyFunction_set_kwdefaults(__pyx_CyFunctionObject *op, PyObject* value, void *context) { + CYTHON_UNUSED_VAR(context); + if (!value) { + value = Py_None; + } else if (unlikely(value != Py_None && !PyDict_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "__kwdefaults__ must be set to a dict object"); + return -1; + } + PyErr_WarnEx(PyExc_RuntimeWarning, "changes to cyfunction.__kwdefaults__ will not " + "currently affect the values used in function calls", 1); + Py_INCREF(value); + __Pyx_BEGIN_CRITICAL_SECTION(op); + __Pyx_Py_XDECREF_SET(op->defaults_kwdict, value); + __Pyx_END_CRITICAL_SECTION(); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_kwdefaults_locked(__pyx_CyFunctionObject *op) { + PyObject* result = op->defaults_kwdict; + if (unlikely(!result)) { + if (op->defaults_getter) { + if (unlikely(__Pyx_CyFunction_init_defaults(op) < 0)) return NULL; + result = op->defaults_kwdict; + } else { + result = Py_None; + } + } + Py_INCREF(result); + return result; +} +static PyObject * +__Pyx_CyFunction_get_kwdefaults(__pyx_CyFunctionObject *op, void *context) { + PyObject* result; + CYTHON_UNUSED_VAR(context); + __Pyx_BEGIN_CRITICAL_SECTION(op); + result = __Pyx_CyFunction_get_kwdefaults_locked(op); + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static int +__Pyx_CyFunction_set_annotations(__pyx_CyFunctionObject *op, PyObject* value, void *context) { + CYTHON_UNUSED_VAR(context); + if (!value || value == Py_None) { + value = NULL; + } else if (unlikely(!PyDict_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "__annotations__ must be set to a dict object"); + return -1; + } + Py_XINCREF(value); + __Pyx_BEGIN_CRITICAL_SECTION(op); + __Pyx_Py_XDECREF_SET(op->func_annotations, value); + __Pyx_END_CRITICAL_SECTION(); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_annotations_locked(__pyx_CyFunctionObject *op) { + PyObject* result = op->func_annotations; + if (unlikely(!result)) { + result = PyDict_New(); + if (unlikely(!result)) return NULL; + op->func_annotations = result; + } + Py_INCREF(result); + return result; +} +static PyObject * +__Pyx_CyFunction_get_annotations(__pyx_CyFunctionObject *op, void *context) { + PyObject *result; + CYTHON_UNUSED_VAR(context); + __Pyx_BEGIN_CRITICAL_SECTION(op); + result = __Pyx_CyFunction_get_annotations_locked(op); + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static PyObject * +__Pyx_CyFunction_get_is_coroutine_value(__pyx_CyFunctionObject *op) { + int is_coroutine = op->flags & __Pyx_CYFUNCTION_COROUTINE; + if (is_coroutine) { + PyObject *is_coroutine_value, *module, *fromlist, *marker = __pyx_mstate_global->__pyx_n_u_is_coroutine; + fromlist = PyList_New(1); + if (unlikely(!fromlist)) return NULL; + Py_INCREF(marker); +#if CYTHON_ASSUME_SAFE_MACROS + PyList_SET_ITEM(fromlist, 0, marker); +#else + if (unlikely(PyList_SetItem(fromlist, 0, marker) < 0)) { + Py_DECREF(marker); + Py_DECREF(fromlist); + return NULL; + } +#endif + module = PyImport_ImportModuleLevelObject(__pyx_mstate_global->__pyx_n_u_asyncio_coroutines, NULL, NULL, fromlist, 0); + Py_DECREF(fromlist); + if (unlikely(!module)) goto ignore; + is_coroutine_value = __Pyx_PyObject_GetAttrStr(module, marker); + Py_DECREF(module); + if (likely(is_coroutine_value)) { + return is_coroutine_value; + } +ignore: + PyErr_Clear(); + } + return __Pyx_PyBool_FromLong(is_coroutine); +} +static PyObject * +__Pyx_CyFunction_get_is_coroutine(__pyx_CyFunctionObject *op, void *context) { + PyObject *result; + CYTHON_UNUSED_VAR(context); + if (op->func_is_coroutine) { + return __Pyx_NewRef(op->func_is_coroutine); + } + result = __Pyx_CyFunction_get_is_coroutine_value(op); + if (unlikely(!result)) + return NULL; + __Pyx_BEGIN_CRITICAL_SECTION(op); + if (op->func_is_coroutine) { + Py_DECREF(result); + result = __Pyx_NewRef(op->func_is_coroutine); + } else { + op->func_is_coroutine = __Pyx_NewRef(result); + } + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static void __Pyx_CyFunction_raise_argument_count_error(__pyx_CyFunctionObject *func, const char* message, Py_ssize_t size) { +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *py_name = __Pyx_CyFunction_get_name(func, NULL); + if (!py_name) return; + PyErr_Format(PyExc_TypeError, + "%.200S() %s (%" CYTHON_FORMAT_SSIZE_T "d given)", + py_name, message, size); + Py_DECREF(py_name); +#else + const char* name = ((PyCFunctionObject*)func)->m_ml->ml_name; + PyErr_Format(PyExc_TypeError, + "%.200s() %s (%" CYTHON_FORMAT_SSIZE_T "d given)", + name, message, size); +#endif +} +static void __Pyx_CyFunction_raise_type_error(__pyx_CyFunctionObject *func, const char* message) { +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *py_name = __Pyx_CyFunction_get_name(func, NULL); + if (!py_name) return; + PyErr_Format(PyExc_TypeError, + "%.200S() %s", + py_name, message); + Py_DECREF(py_name); +#else + const char* name = ((PyCFunctionObject*)func)->m_ml->ml_name; + PyErr_Format(PyExc_TypeError, + "%.200s() %s", + name, message); +#endif +} +#if CYTHON_COMPILING_IN_LIMITED_API +static PyObject * +__Pyx_CyFunction_get_module(__pyx_CyFunctionObject *op, void *context) { + CYTHON_UNUSED_VAR(context); + return PyObject_GetAttrString(op->func, "__module__"); +} +static int +__Pyx_CyFunction_set_module(__pyx_CyFunctionObject *op, PyObject* value, void *context) { + CYTHON_UNUSED_VAR(context); + return PyObject_SetAttrString(op->func, "__module__", value); +} +#endif +static PyGetSetDef __pyx_CyFunction_getsets[] = { + {"func_doc", (getter)__Pyx_CyFunction_get_doc, (setter)__Pyx_CyFunction_set_doc, 0, 0}, + {"__doc__", (getter)__Pyx_CyFunction_get_doc, (setter)__Pyx_CyFunction_set_doc, 0, 0}, + {"func_name", (getter)__Pyx_CyFunction_get_name, (setter)__Pyx_CyFunction_set_name, 0, 0}, + {"__name__", (getter)__Pyx_CyFunction_get_name, (setter)__Pyx_CyFunction_set_name, 0, 0}, + {"__qualname__", (getter)__Pyx_CyFunction_get_qualname, (setter)__Pyx_CyFunction_set_qualname, 0, 0}, +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000 + {"func_dict", (getter)__Pyx_CyFunction_get_dict, (setter)PyObject_GenericSetDict, 0, 0}, + {"__dict__", (getter)__Pyx_CyFunction_get_dict, (setter)PyObject_GenericSetDict, 0, 0}, +#else + {"func_dict", (getter)PyObject_GenericGetDict, (setter)PyObject_GenericSetDict, 0, 0}, + {"__dict__", (getter)PyObject_GenericGetDict, (setter)PyObject_GenericSetDict, 0, 0}, +#endif + {"func_globals", (getter)__Pyx_CyFunction_get_globals, 0, 0, 0}, + {"__globals__", (getter)__Pyx_CyFunction_get_globals, 0, 0, 0}, + {"func_closure", (getter)__Pyx_CyFunction_get_closure, 0, 0, 0}, + {"__closure__", (getter)__Pyx_CyFunction_get_closure, 0, 0, 0}, + {"func_code", (getter)__Pyx_CyFunction_get_code, 0, 0, 0}, + {"__code__", (getter)__Pyx_CyFunction_get_code, 0, 0, 0}, + {"func_defaults", (getter)__Pyx_CyFunction_get_defaults, (setter)__Pyx_CyFunction_set_defaults, 0, 0}, + {"__defaults__", (getter)__Pyx_CyFunction_get_defaults, (setter)__Pyx_CyFunction_set_defaults, 0, 0}, + {"__kwdefaults__", (getter)__Pyx_CyFunction_get_kwdefaults, (setter)__Pyx_CyFunction_set_kwdefaults, 0, 0}, + {"__annotations__", (getter)__Pyx_CyFunction_get_annotations, (setter)__Pyx_CyFunction_set_annotations, 0, 0}, + {"_is_coroutine", (getter)__Pyx_CyFunction_get_is_coroutine, 0, 0, 0}, +#if CYTHON_COMPILING_IN_LIMITED_API + {"__module__", (getter)__Pyx_CyFunction_get_module, (setter)__Pyx_CyFunction_set_module, 0, 0}, +#endif + {0, 0, 0, 0, 0} +}; +static PyMemberDef __pyx_CyFunction_members[] = { +#if !CYTHON_COMPILING_IN_LIMITED_API + {"__module__", T_OBJECT, offsetof(PyCFunctionObject, m_module), 0, 0}, +#endif +#if PY_VERSION_HEX < 0x030C0000 || CYTHON_COMPILING_IN_LIMITED_API + {"__dictoffset__", T_PYSSIZET, offsetof(__pyx_CyFunctionObject, func_dict), READONLY, 0}, +#endif +#if CYTHON_METH_FASTCALL +#if CYTHON_COMPILING_IN_LIMITED_API + {"__vectorcalloffset__", T_PYSSIZET, offsetof(__pyx_CyFunctionObject, func_vectorcall), READONLY, 0}, +#else + {"__vectorcalloffset__", T_PYSSIZET, offsetof(PyCFunctionObject, vectorcall), READONLY, 0}, +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + {"__weaklistoffset__", T_PYSSIZET, offsetof(__pyx_CyFunctionObject, func_weakreflist), READONLY, 0}, +#else + {"__weaklistoffset__", T_PYSSIZET, offsetof(PyCFunctionObject, m_weakreflist), READONLY, 0}, +#endif +#endif + {0, 0, 0, 0, 0} +}; +static PyObject * +__Pyx_CyFunction_reduce(__pyx_CyFunctionObject *m, PyObject *args) +{ + PyObject *result = NULL; + CYTHON_UNUSED_VAR(args); + __Pyx_BEGIN_CRITICAL_SECTION(m); + Py_INCREF(m->func_qualname); + result = m->func_qualname; + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static PyMethodDef __pyx_CyFunction_methods[] = { + {"__reduce__", (PyCFunction)__Pyx_CyFunction_reduce, METH_VARARGS, 0}, + {0, 0, 0, 0} +}; +#if CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_CyFunction_weakreflist(cyfunc) ((cyfunc)->func_weakreflist) +#else +#define __Pyx_CyFunction_weakreflist(cyfunc) (((PyCFunctionObject*)cyfunc)->m_weakreflist) +#endif +static PyObject *__Pyx_CyFunction_Init(__pyx_CyFunctionObject *op, PyMethodDef *ml, int flags, PyObject* qualname, + PyObject *closure, PyObject *module, PyObject* globals, PyObject* code) { +#if !CYTHON_COMPILING_IN_LIMITED_API + PyCFunctionObject *cf = (PyCFunctionObject*) op; +#endif + if (unlikely(op == NULL)) + return NULL; +#if CYTHON_COMPILING_IN_LIMITED_API + op->func = PyCFunction_NewEx(ml, (PyObject*)op, module); + if (unlikely(!op->func)) return NULL; +#endif + op->flags = flags; + __Pyx_CyFunction_weakreflist(op) = NULL; +#if !CYTHON_COMPILING_IN_LIMITED_API + cf->m_ml = ml; + cf->m_self = (PyObject *) op; +#endif + Py_XINCREF(closure); + op->func_closure = closure; +#if !CYTHON_COMPILING_IN_LIMITED_API + Py_XINCREF(module); + cf->m_module = module; +#endif +#if PY_VERSION_HEX < 0x030C0000 || CYTHON_COMPILING_IN_LIMITED_API + op->func_dict = NULL; +#endif + op->func_name = NULL; + Py_INCREF(qualname); + op->func_qualname = qualname; + op->func_doc = NULL; +#if PY_VERSION_HEX < 0x030900B1 || CYTHON_COMPILING_IN_LIMITED_API + op->func_classobj = NULL; +#else + ((PyCMethodObject*)op)->mm_class = NULL; +#endif + op->func_globals = globals; + Py_INCREF(op->func_globals); + Py_XINCREF(code); + op->func_code = code; + op->defaults = NULL; + op->defaults_tuple = NULL; + op->defaults_kwdict = NULL; + op->defaults_getter = NULL; + op->func_annotations = NULL; + op->func_is_coroutine = NULL; +#if CYTHON_METH_FASTCALL + switch (ml->ml_flags & (METH_VARARGS | METH_FASTCALL | METH_NOARGS | METH_O | METH_KEYWORDS | METH_METHOD)) { + case METH_NOARGS: + __Pyx_CyFunction_func_vectorcall(op) = __Pyx_CyFunction_Vectorcall_NOARGS; + break; + case METH_O: + __Pyx_CyFunction_func_vectorcall(op) = __Pyx_CyFunction_Vectorcall_O; + break; + case METH_METHOD | METH_FASTCALL | METH_KEYWORDS: + __Pyx_CyFunction_func_vectorcall(op) = __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS_METHOD; + break; + case METH_FASTCALL | METH_KEYWORDS: + __Pyx_CyFunction_func_vectorcall(op) = __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS; + break; + case METH_VARARGS | METH_KEYWORDS: + __Pyx_CyFunction_func_vectorcall(op) = NULL; + break; + default: + PyErr_SetString(PyExc_SystemError, "Bad call flags for CyFunction"); + Py_DECREF(op); + return NULL; + } +#endif + return (PyObject *) op; +} +static int +__Pyx_CyFunction_clear(__pyx_CyFunctionObject *m) +{ + Py_CLEAR(m->func_closure); +#if CYTHON_COMPILING_IN_LIMITED_API + Py_CLEAR(m->func); +#else + Py_CLEAR(((PyCFunctionObject*)m)->m_module); +#endif +#if PY_VERSION_HEX < 0x030C0000 || CYTHON_COMPILING_IN_LIMITED_API + Py_CLEAR(m->func_dict); +#elif PY_VERSION_HEX < 0x030d0000 + _PyObject_ClearManagedDict((PyObject*)m); +#else + PyObject_ClearManagedDict((PyObject*)m); +#endif + Py_CLEAR(m->func_name); + Py_CLEAR(m->func_qualname); + Py_CLEAR(m->func_doc); + Py_CLEAR(m->func_globals); + Py_CLEAR(m->func_code); +#if !CYTHON_COMPILING_IN_LIMITED_API +#if PY_VERSION_HEX < 0x030900B1 + Py_CLEAR(__Pyx_CyFunction_GetClassObj(m)); +#else + { + PyObject *cls = (PyObject*) ((PyCMethodObject *) (m))->mm_class; + ((PyCMethodObject *) (m))->mm_class = NULL; + Py_XDECREF(cls); + } +#endif +#endif + Py_CLEAR(m->defaults_tuple); + Py_CLEAR(m->defaults_kwdict); + Py_CLEAR(m->func_annotations); + Py_CLEAR(m->func_is_coroutine); + Py_CLEAR(m->defaults); + return 0; +} +static void __Pyx__CyFunction_dealloc(__pyx_CyFunctionObject *m) +{ + if (__Pyx_CyFunction_weakreflist(m) != NULL) + PyObject_ClearWeakRefs((PyObject *) m); + __Pyx_CyFunction_clear(m); + __Pyx_PyHeapTypeObject_GC_Del(m); +} +static void __Pyx_CyFunction_dealloc(__pyx_CyFunctionObject *m) +{ + PyObject_GC_UnTrack(m); + __Pyx__CyFunction_dealloc(m); +} +static int __Pyx_CyFunction_traverse(__pyx_CyFunctionObject *m, visitproc visit, void *arg) +{ + { + int e = __Pyx_call_type_traverse((PyObject*)m, 1, visit, arg); + if (e) return e; + } + Py_VISIT(m->func_closure); +#if CYTHON_COMPILING_IN_LIMITED_API + Py_VISIT(m->func); +#else + Py_VISIT(((PyCFunctionObject*)m)->m_module); +#endif +#if PY_VERSION_HEX < 0x030C0000 || CYTHON_COMPILING_IN_LIMITED_API + Py_VISIT(m->func_dict); +#else + { + int e = +#if PY_VERSION_HEX < 0x030d0000 + _PyObject_VisitManagedDict +#else + PyObject_VisitManagedDict +#endif + ((PyObject*)m, visit, arg); + if (e != 0) return e; + } +#endif + __Pyx_VISIT_CONST(m->func_name); + __Pyx_VISIT_CONST(m->func_qualname); + Py_VISIT(m->func_doc); + Py_VISIT(m->func_globals); + __Pyx_VISIT_CONST(m->func_code); +#if !CYTHON_COMPILING_IN_LIMITED_API + Py_VISIT(__Pyx_CyFunction_GetClassObj(m)); +#endif + Py_VISIT(m->defaults_tuple); + Py_VISIT(m->defaults_kwdict); + Py_VISIT(m->func_is_coroutine); + Py_VISIT(m->defaults); + return 0; +} +static PyObject* +__Pyx_CyFunction_repr(__pyx_CyFunctionObject *op) +{ + PyObject *repr; + __Pyx_BEGIN_CRITICAL_SECTION(op); + repr = PyUnicode_FromFormat("", + op->func_qualname, (void *)op); + __Pyx_END_CRITICAL_SECTION(); + return repr; +} +static PyObject * __Pyx_CyFunction_CallMethod(PyObject *func, PyObject *self, PyObject *arg, PyObject *kw) { +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *f = ((__pyx_CyFunctionObject*)func)->func; + PyCFunction meth; + int flags; + meth = PyCFunction_GetFunction(f); + if (unlikely(!meth)) return NULL; + flags = PyCFunction_GetFlags(f); + if (unlikely(flags < 0)) return NULL; +#else + PyCFunctionObject* f = (PyCFunctionObject*)func; + PyCFunction meth = f->m_ml->ml_meth; + int flags = f->m_ml->ml_flags; +#endif + Py_ssize_t size; + switch (flags & (METH_VARARGS | METH_KEYWORDS | METH_NOARGS | METH_O)) { + case METH_VARARGS: + if (likely(kw == NULL || PyDict_Size(kw) == 0)) + return (*meth)(self, arg); + break; + case METH_VARARGS | METH_KEYWORDS: + return (*(PyCFunctionWithKeywords)(void(*)(void))meth)(self, arg, kw); + case METH_NOARGS: + if (likely(kw == NULL || PyDict_Size(kw) == 0)) { +#if CYTHON_ASSUME_SAFE_SIZE + size = PyTuple_GET_SIZE(arg); +#else + size = PyTuple_Size(arg); + if (unlikely(size < 0)) return NULL; +#endif + if (likely(size == 0)) + return (*meth)(self, NULL); + __Pyx_CyFunction_raise_argument_count_error( + (__pyx_CyFunctionObject*)func, + "takes no arguments", size); + return NULL; + } + break; + case METH_O: + if (likely(kw == NULL || PyDict_Size(kw) == 0)) { +#if CYTHON_ASSUME_SAFE_SIZE + size = PyTuple_GET_SIZE(arg); +#else + size = PyTuple_Size(arg); + if (unlikely(size < 0)) return NULL; +#endif + if (likely(size == 1)) { + PyObject *result, *arg0; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + arg0 = PyTuple_GET_ITEM(arg, 0); + #else + arg0 = __Pyx_PySequence_ITEM(arg, 0); if (unlikely(!arg0)) return NULL; + #endif + result = (*meth)(self, arg0); + #if !(CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS) + Py_DECREF(arg0); + #endif + return result; + } + __Pyx_CyFunction_raise_argument_count_error( + (__pyx_CyFunctionObject*)func, + "takes exactly one argument", size); + return NULL; + } + break; + default: + PyErr_SetString(PyExc_SystemError, "Bad call flags for CyFunction"); + return NULL; + } + __Pyx_CyFunction_raise_type_error( + (__pyx_CyFunctionObject*)func, "takes no keyword arguments"); + return NULL; +} +static CYTHON_INLINE PyObject *__Pyx_CyFunction_Call(PyObject *func, PyObject *arg, PyObject *kw) { + PyObject *self, *result; +#if CYTHON_COMPILING_IN_LIMITED_API + self = PyCFunction_GetSelf(((__pyx_CyFunctionObject*)func)->func); + if (unlikely(!self) && PyErr_Occurred()) return NULL; +#else + self = ((PyCFunctionObject*)func)->m_self; +#endif + result = __Pyx_CyFunction_CallMethod(func, self, arg, kw); + return result; +} +static PyObject *__Pyx_CyFunction_CallAsMethod(PyObject *func, PyObject *args, PyObject *kw) { + PyObject *result; + __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *) func; +#if CYTHON_METH_FASTCALL && CYTHON_VECTORCALL + __pyx_vectorcallfunc vc = __Pyx_CyFunction_func_vectorcall(cyfunc); + if (vc) { +#if CYTHON_ASSUME_SAFE_MACROS && CYTHON_ASSUME_SAFE_SIZE + return __Pyx_PyVectorcall_FastCallDict(func, vc, &PyTuple_GET_ITEM(args, 0), (size_t)PyTuple_GET_SIZE(args), kw); +#else + (void) &__Pyx_PyVectorcall_FastCallDict; + return PyVectorcall_Call(func, args, kw); +#endif + } +#endif + if ((cyfunc->flags & __Pyx_CYFUNCTION_CCLASS) && !(cyfunc->flags & __Pyx_CYFUNCTION_STATICMETHOD)) { + Py_ssize_t argc; + PyObject *new_args; + PyObject *self; +#if CYTHON_ASSUME_SAFE_SIZE + argc = PyTuple_GET_SIZE(args); +#else + argc = PyTuple_Size(args); + if (unlikely(argc < 0)) return NULL; +#endif + new_args = PyTuple_GetSlice(args, 1, argc); + if (unlikely(!new_args)) + return NULL; + self = PyTuple_GetItem(args, 0); + if (unlikely(!self)) { + Py_DECREF(new_args); + PyErr_Format(PyExc_TypeError, + "unbound method %.200S() needs an argument", + cyfunc->func_qualname); + return NULL; + } + result = __Pyx_CyFunction_CallMethod(func, self, new_args, kw); + Py_DECREF(new_args); + } else { + result = __Pyx_CyFunction_Call(func, args, kw); + } + return result; +} +#if CYTHON_METH_FASTCALL && CYTHON_VECTORCALL +static CYTHON_INLINE int __Pyx_CyFunction_Vectorcall_CheckArgs(__pyx_CyFunctionObject *cyfunc, Py_ssize_t nargs, PyObject *kwnames) +{ + int ret = 0; + if ((cyfunc->flags & __Pyx_CYFUNCTION_CCLASS) && !(cyfunc->flags & __Pyx_CYFUNCTION_STATICMETHOD)) { + if (unlikely(nargs < 1)) { + __Pyx_CyFunction_raise_type_error( + cyfunc, "needs an argument"); + return -1; + } + ret = 1; + } + if (unlikely(kwnames) && unlikely(__Pyx_PyTuple_GET_SIZE(kwnames))) { + __Pyx_CyFunction_raise_type_error( + cyfunc, "takes no keyword arguments"); + return -1; + } + return ret; +} +static PyObject * __Pyx_CyFunction_Vectorcall_NOARGS(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames) +{ + __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *)func; + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); + PyObject *self; +#if CYTHON_COMPILING_IN_LIMITED_API + PyCFunction meth = PyCFunction_GetFunction(cyfunc->func); + if (unlikely(!meth)) return NULL; +#else + PyCFunction meth = ((PyCFunctionObject*)cyfunc)->m_ml->ml_meth; +#endif + switch (__Pyx_CyFunction_Vectorcall_CheckArgs(cyfunc, nargs, kwnames)) { + case 1: + self = args[0]; + args += 1; + nargs -= 1; + break; + case 0: +#if CYTHON_COMPILING_IN_LIMITED_API + self = PyCFunction_GetSelf(((__pyx_CyFunctionObject*)cyfunc)->func); + if (unlikely(!self) && PyErr_Occurred()) return NULL; +#else + self = ((PyCFunctionObject*)cyfunc)->m_self; +#endif + break; + default: + return NULL; + } + if (unlikely(nargs != 0)) { + __Pyx_CyFunction_raise_argument_count_error( + cyfunc, "takes no arguments", nargs); + return NULL; + } + return meth(self, NULL); +} +static PyObject * __Pyx_CyFunction_Vectorcall_O(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames) +{ + __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *)func; + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); + PyObject *self; +#if CYTHON_COMPILING_IN_LIMITED_API + PyCFunction meth = PyCFunction_GetFunction(cyfunc->func); + if (unlikely(!meth)) return NULL; +#else + PyCFunction meth = ((PyCFunctionObject*)cyfunc)->m_ml->ml_meth; +#endif + switch (__Pyx_CyFunction_Vectorcall_CheckArgs(cyfunc, nargs, kwnames)) { + case 1: + self = args[0]; + args += 1; + nargs -= 1; + break; + case 0: +#if CYTHON_COMPILING_IN_LIMITED_API + self = PyCFunction_GetSelf(((__pyx_CyFunctionObject*)cyfunc)->func); + if (unlikely(!self) && PyErr_Occurred()) return NULL; +#else + self = ((PyCFunctionObject*)cyfunc)->m_self; +#endif + break; + default: + return NULL; + } + if (unlikely(nargs != 1)) { + __Pyx_CyFunction_raise_argument_count_error( + cyfunc, "takes exactly one argument", nargs); + return NULL; + } + return meth(self, args[0]); +} +static PyObject * __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames) +{ + __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *)func; + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); + PyObject *self; +#if CYTHON_COMPILING_IN_LIMITED_API + PyCFunction meth = PyCFunction_GetFunction(cyfunc->func); + if (unlikely(!meth)) return NULL; +#else + PyCFunction meth = ((PyCFunctionObject*)cyfunc)->m_ml->ml_meth; +#endif + switch (__Pyx_CyFunction_Vectorcall_CheckArgs(cyfunc, nargs, NULL)) { + case 1: + self = args[0]; + args += 1; + nargs -= 1; + break; + case 0: +#if CYTHON_COMPILING_IN_LIMITED_API + self = PyCFunction_GetSelf(((__pyx_CyFunctionObject*)cyfunc)->func); + if (unlikely(!self) && PyErr_Occurred()) return NULL; +#else + self = ((PyCFunctionObject*)cyfunc)->m_self; +#endif + break; + default: + return NULL; + } + return ((__Pyx_PyCFunctionFastWithKeywords)(void(*)(void))meth)(self, args, nargs, kwnames); +} +static PyObject * __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS_METHOD(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames) +{ + __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *)func; + PyTypeObject *cls = (PyTypeObject *) __Pyx_CyFunction_GetClassObj(cyfunc); + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); + PyObject *self; +#if CYTHON_COMPILING_IN_LIMITED_API + PyCFunction meth = PyCFunction_GetFunction(cyfunc->func); + if (unlikely(!meth)) return NULL; +#else + PyCFunction meth = ((PyCFunctionObject*)cyfunc)->m_ml->ml_meth; +#endif + switch (__Pyx_CyFunction_Vectorcall_CheckArgs(cyfunc, nargs, NULL)) { + case 1: + self = args[0]; + args += 1; + nargs -= 1; + break; + case 0: +#if CYTHON_COMPILING_IN_LIMITED_API + self = PyCFunction_GetSelf(((__pyx_CyFunctionObject*)cyfunc)->func); + if (unlikely(!self) && PyErr_Occurred()) return NULL; +#else + self = ((PyCFunctionObject*)cyfunc)->m_self; +#endif + break; + default: + return NULL; + } + #if PY_VERSION_HEX < 0x030e00A6 + size_t nargs_value = (size_t) nargs; + #else + Py_ssize_t nargs_value = nargs; + #endif + return ((__Pyx_PyCMethod)(void(*)(void))meth)(self, cls, args, nargs_value, kwnames); +} +#endif +static PyType_Slot __pyx_CyFunctionType_slots[] = { + {Py_tp_dealloc, (void *)__Pyx_CyFunction_dealloc}, + {Py_tp_repr, (void *)__Pyx_CyFunction_repr}, + {Py_tp_call, (void *)__Pyx_CyFunction_CallAsMethod}, + {Py_tp_traverse, (void *)__Pyx_CyFunction_traverse}, + {Py_tp_clear, (void *)__Pyx_CyFunction_clear}, + {Py_tp_methods, (void *)__pyx_CyFunction_methods}, + {Py_tp_members, (void *)__pyx_CyFunction_members}, + {Py_tp_getset, (void *)__pyx_CyFunction_getsets}, + {Py_tp_descr_get, (void *)__Pyx_PyMethod_New}, + {0, 0}, +}; +static PyType_Spec __pyx_CyFunctionType_spec = { + __PYX_TYPE_MODULE_PREFIX "cython_function_or_method", + sizeof(__pyx_CyFunctionObject), + 0, +#ifdef Py_TPFLAGS_METHOD_DESCRIPTOR + Py_TPFLAGS_METHOD_DESCRIPTOR | +#endif +#if CYTHON_METH_FASTCALL +#if defined(Py_TPFLAGS_HAVE_VECTORCALL) + Py_TPFLAGS_HAVE_VECTORCALL | +#elif defined(_Py_TPFLAGS_HAVE_VECTORCALL) + _Py_TPFLAGS_HAVE_VECTORCALL | +#endif +#endif // CYTHON_METH_FASTCALL +#if PY_VERSION_HEX >= 0x030C0000 && !CYTHON_COMPILING_IN_LIMITED_API + Py_TPFLAGS_MANAGED_DICT | +#endif + Py_TPFLAGS_IMMUTABLETYPE | Py_TPFLAGS_DISALLOW_INSTANTIATION | + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, + __pyx_CyFunctionType_slots +}; +static int __pyx_CyFunction_init(PyObject *module) { + __pyx_mstatetype *mstate = __Pyx_PyModule_GetState(module); + mstate->__pyx_CyFunctionType = __Pyx_FetchCommonTypeFromSpec( + mstate->__pyx_CommonTypesMetaclassType, module, &__pyx_CyFunctionType_spec, NULL); + if (unlikely(mstate->__pyx_CyFunctionType == NULL)) { + return -1; + } + return 0; +} +static CYTHON_INLINE PyObject *__Pyx_CyFunction_InitDefaults(PyObject *func, PyTypeObject *defaults_type) { + __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; + m->defaults = PyObject_CallObject((PyObject*)defaults_type, NULL); // _PyObject_New(defaults_type); + if (unlikely(!m->defaults)) + return NULL; + return m->defaults; +} +static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsTuple(PyObject *func, PyObject *tuple) { + __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; + m->defaults_tuple = tuple; + Py_INCREF(tuple); +} +static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsKwDict(PyObject *func, PyObject *dict) { + __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; + m->defaults_kwdict = dict; + Py_INCREF(dict); +} +static CYTHON_INLINE void __Pyx_CyFunction_SetAnnotationsDict(PyObject *func, PyObject *dict) { + __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; + m->func_annotations = dict; + Py_INCREF(dict); +} + +/* CythonFunction */ +static PyObject *__Pyx_CyFunction_New(PyMethodDef *ml, int flags, PyObject* qualname, + PyObject *closure, PyObject *module, PyObject* globals, PyObject* code) { + PyObject *op = __Pyx_CyFunction_Init( + PyObject_GC_New(__pyx_CyFunctionObject, __pyx_mstate_global->__pyx_CyFunctionType), + ml, flags, qualname, closure, module, globals, code + ); + if (likely(op)) { + PyObject_GC_Track(op); + } + return op; +} + +/* CLineInTraceback (used by AddTraceback) */ +#if CYTHON_CLINE_IN_TRACEBACK && CYTHON_CLINE_IN_TRACEBACK_RUNTIME +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000 +#define __Pyx_PyProbablyModule_GetDict(o) __Pyx_XNewRef(PyModule_GetDict(o)) +#elif !CYTHON_COMPILING_IN_CPYTHON || CYTHON_COMPILING_IN_CPYTHON_FREETHREADING +#define __Pyx_PyProbablyModule_GetDict(o) PyObject_GenericGetDict(o, NULL); +#else +PyObject* __Pyx_PyProbablyModule_GetDict(PyObject *o) { + PyObject **dict_ptr = _PyObject_GetDictPtr(o); + return dict_ptr ? __Pyx_XNewRef(*dict_ptr) : NULL; +} +#endif +static int __Pyx_CLineForTraceback(PyThreadState *tstate, int c_line) { + PyObject *use_cline = NULL; + PyObject *ptype, *pvalue, *ptraceback; + PyObject *cython_runtime_dict; + CYTHON_MAYBE_UNUSED_VAR(tstate); + if (unlikely(!__pyx_mstate_global->__pyx_cython_runtime)) { + return c_line; + } + __Pyx_ErrFetchInState(tstate, &ptype, &pvalue, &ptraceback); + cython_runtime_dict = __Pyx_PyProbablyModule_GetDict(__pyx_mstate_global->__pyx_cython_runtime); + if (likely(cython_runtime_dict)) { + __PYX_PY_DICT_LOOKUP_IF_MODIFIED( + use_cline, cython_runtime_dict, + __Pyx_PyDict_SetDefault(cython_runtime_dict, __pyx_mstate_global->__pyx_n_u_cline_in_traceback, Py_False)) + } + if (use_cline == NULL || use_cline == Py_False || (use_cline != Py_True && PyObject_Not(use_cline) != 0)) { + c_line = 0; + } + Py_XDECREF(use_cline); + Py_XDECREF(cython_runtime_dict); + __Pyx_ErrRestoreInState(tstate, ptype, pvalue, ptraceback); + return c_line; +} +#endif + +/* CodeObjectCache (used by AddTraceback) */ +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { + int start = 0, mid = 0, end = count - 1; + if (end >= 0 && code_line > entries[end].code_line) { + return count; + } + while (start < end) { + mid = start + (end - start) / 2; + if (code_line < entries[mid].code_line) { + end = mid; + } else if (code_line > entries[mid].code_line) { + start = mid + 1; + } else { + return mid; + } + } + if (code_line <= entries[mid].code_line) { + return mid; + } else { + return mid + 1; + } +} +static __Pyx_CachedCodeObjectType *__pyx__find_code_object(struct __Pyx_CodeObjectCache *code_cache, int code_line) { + __Pyx_CachedCodeObjectType* code_object; + int pos; + if (unlikely(!code_line) || unlikely(!code_cache->entries)) { + return NULL; + } + pos = __pyx_bisect_code_objects(code_cache->entries, code_cache->count, code_line); + if (unlikely(pos >= code_cache->count) || unlikely(code_cache->entries[pos].code_line != code_line)) { + return NULL; + } + code_object = code_cache->entries[pos].code_object; + Py_INCREF(code_object); + return code_object; +} +static __Pyx_CachedCodeObjectType *__pyx_find_code_object(int code_line) { +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING && !CYTHON_ATOMICS + (void)__pyx__find_code_object; + return NULL; // Most implementation should have atomics. But otherwise, don't make it thread-safe, just miss. +#else + struct __Pyx_CodeObjectCache *code_cache = &__pyx_mstate_global->__pyx_code_cache; +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + __pyx_nonatomic_int_type old_count = __pyx_atomic_incr_acq_rel(&code_cache->accessor_count); + if (old_count < 0) { + __pyx_atomic_decr_acq_rel(&code_cache->accessor_count); + return NULL; + } +#endif + __Pyx_CachedCodeObjectType *result = __pyx__find_code_object(code_cache, code_line); +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + __pyx_atomic_decr_acq_rel(&code_cache->accessor_count); +#endif + return result; +#endif +} +static void __pyx__insert_code_object(struct __Pyx_CodeObjectCache *code_cache, int code_line, __Pyx_CachedCodeObjectType* code_object) +{ + int pos, i; + __Pyx_CodeObjectCacheEntry* entries = code_cache->entries; + if (unlikely(!code_line)) { + return; + } + if (unlikely(!entries)) { + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); + if (likely(entries)) { + code_cache->entries = entries; + code_cache->max_count = 64; + code_cache->count = 1; + entries[0].code_line = code_line; + entries[0].code_object = code_object; + Py_INCREF(code_object); + } + return; + } + pos = __pyx_bisect_code_objects(code_cache->entries, code_cache->count, code_line); + if ((pos < code_cache->count) && unlikely(code_cache->entries[pos].code_line == code_line)) { + __Pyx_CachedCodeObjectType* tmp = entries[pos].code_object; + entries[pos].code_object = code_object; + Py_INCREF(code_object); + Py_DECREF(tmp); + return; + } + if (code_cache->count == code_cache->max_count) { + int new_max = code_cache->max_count + 64; + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( + code_cache->entries, ((size_t)new_max) * sizeof(__Pyx_CodeObjectCacheEntry)); + if (unlikely(!entries)) { + return; + } + code_cache->entries = entries; + code_cache->max_count = new_max; + } + for (i=code_cache->count; i>pos; i--) { + entries[i] = entries[i-1]; + } + entries[pos].code_line = code_line; + entries[pos].code_object = code_object; + code_cache->count++; + Py_INCREF(code_object); +} +static void __pyx_insert_code_object(int code_line, __Pyx_CachedCodeObjectType* code_object) { +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING && !CYTHON_ATOMICS + (void)__pyx__insert_code_object; + return; // Most implementation should have atomics. But otherwise, don't make it thread-safe, just fail. +#else + struct __Pyx_CodeObjectCache *code_cache = &__pyx_mstate_global->__pyx_code_cache; +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + __pyx_nonatomic_int_type expected = 0; + if (!__pyx_atomic_int_cmp_exchange(&code_cache->accessor_count, &expected, INT_MIN)) { + return; + } +#endif + __pyx__insert_code_object(code_cache, code_line, code_object); +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + __pyx_atomic_sub(&code_cache->accessor_count, INT_MIN); +#endif +#endif +} + +/* AddTraceback */ +#include "compile.h" +#include "frameobject.h" +#include "traceback.h" +#if PY_VERSION_HEX >= 0x030b00a6 && !CYTHON_COMPILING_IN_LIMITED_API && !defined(PYPY_VERSION) + #ifndef Py_BUILD_CORE + #define Py_BUILD_CORE 1 + #endif + #include "internal/pycore_frame.h" +#endif +#if CYTHON_COMPILING_IN_LIMITED_API +static PyObject *__Pyx_PyCode_Replace_For_AddTraceback(PyObject *code, PyObject *scratch_dict, + PyObject *firstlineno, PyObject *name) { + PyObject *replace = NULL; + if (unlikely(PyDict_SetItemString(scratch_dict, "co_firstlineno", firstlineno))) return NULL; + if (unlikely(PyDict_SetItemString(scratch_dict, "co_name", name))) return NULL; + replace = PyObject_GetAttrString(code, "replace"); + if (likely(replace)) { + PyObject *result = PyObject_Call(replace, __pyx_mstate_global->__pyx_empty_tuple, scratch_dict); + Py_DECREF(replace); + return result; + } + PyErr_Clear(); + return NULL; +} +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename) { + PyObject *code_object = NULL, *py_py_line = NULL, *py_funcname = NULL, *dict = NULL; + PyObject *replace = NULL, *getframe = NULL, *frame = NULL; + PyObject *exc_type, *exc_value, *exc_traceback; + int success = 0; + if (c_line) { + c_line = __Pyx_CLineForTraceback(__Pyx_PyThreadState_Current, c_line); + } + PyErr_Fetch(&exc_type, &exc_value, &exc_traceback); + code_object = __pyx_find_code_object(c_line ? -c_line : py_line); + if (!code_object) { + code_object = Py_CompileString("_getframe()", filename, Py_eval_input); + if (unlikely(!code_object)) goto bad; + py_py_line = PyLong_FromLong(py_line); + if (unlikely(!py_py_line)) goto bad; + if (c_line) { + py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + } else { + py_funcname = PyUnicode_FromString(funcname); + } + if (unlikely(!py_funcname)) goto bad; + dict = PyDict_New(); + if (unlikely(!dict)) goto bad; + { + PyObject *old_code_object = code_object; + code_object = __Pyx_PyCode_Replace_For_AddTraceback(code_object, dict, py_py_line, py_funcname); + Py_DECREF(old_code_object); + } + if (unlikely(!code_object)) goto bad; + __pyx_insert_code_object(c_line ? -c_line : py_line, code_object); + } else { + dict = PyDict_New(); + } + getframe = PySys_GetObject("_getframe"); + if (unlikely(!getframe)) goto bad; + if (unlikely(PyDict_SetItemString(dict, "_getframe", getframe))) goto bad; + frame = PyEval_EvalCode(code_object, dict, dict); + if (unlikely(!frame) || frame == Py_None) goto bad; + success = 1; + bad: + PyErr_Restore(exc_type, exc_value, exc_traceback); + Py_XDECREF(code_object); + Py_XDECREF(py_py_line); + Py_XDECREF(py_funcname); + Py_XDECREF(dict); + Py_XDECREF(replace); + if (success) { + PyTraceBack_Here( + (struct _frame*)frame); + } + Py_XDECREF(frame); +} +#else +static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( + const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = NULL; + PyObject *py_funcname = NULL; + if (c_line) { + py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + if (!py_funcname) goto bad; + funcname = PyUnicode_AsUTF8(py_funcname); + if (!funcname) goto bad; + } + py_code = PyCode_NewEmpty(filename, funcname, py_line); + Py_XDECREF(py_funcname); + return py_code; +bad: + Py_XDECREF(py_funcname); + return NULL; +} +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyFrameObject *py_frame = 0; + PyThreadState *tstate = __Pyx_PyThreadState_Current; + PyObject *ptype, *pvalue, *ptraceback; + if (c_line) { + c_line = __Pyx_CLineForTraceback(tstate, c_line); + } + py_code = __pyx_find_code_object(c_line ? -c_line : py_line); + if (!py_code) { + __Pyx_ErrFetchInState(tstate, &ptype, &pvalue, &ptraceback); + py_code = __Pyx_CreateCodeObjectForTraceback( + funcname, c_line, py_line, filename); + if (!py_code) { + /* If the code object creation fails, then we should clear the + fetched exception references and propagate the new exception */ + Py_XDECREF(ptype); + Py_XDECREF(pvalue); + Py_XDECREF(ptraceback); + goto bad; + } + __Pyx_ErrRestoreInState(tstate, ptype, pvalue, ptraceback); + __pyx_insert_code_object(c_line ? -c_line : py_line, py_code); + } + py_frame = PyFrame_New( + tstate, /*PyThreadState *tstate,*/ + py_code, /*PyCodeObject *code,*/ + __pyx_mstate_global->__pyx_d, /*PyObject *globals,*/ + 0 /*PyObject *locals*/ + ); + if (!py_frame) goto bad; + __Pyx_PyFrame_SetLineNumber(py_frame, py_line); + PyTraceBack_Here(py_frame); +bad: + Py_XDECREF(py_code); + Py_XDECREF(py_frame); +} +#endif + +/* CheckUnpickleChecksum */ +static void __Pyx_RaiseUnpickleChecksumError(long checksum, long checksum1, long checksum2, long checksum3, const char *members) { + PyObject *pickle_module = PyImport_ImportModule("pickle"); + if (unlikely(!pickle_module)) return; + PyObject *pickle_error = PyObject_GetAttrString(pickle_module, "PickleError"); + Py_DECREF(pickle_module); + if (unlikely(!pickle_error)) return; + if (checksum2 == checksum1) { + PyErr_Format(pickle_error, "Incompatible checksums (0x%x vs (0x%x) = (%s))", + checksum, checksum1, members); + } else if (checksum3 == checksum2) { + PyErr_Format(pickle_error, "Incompatible checksums (0x%x vs (0x%x, 0x%x) = (%s))", + checksum, checksum1, checksum2, members); + } else { + PyErr_Format(pickle_error, "Incompatible checksums (0x%x vs (0x%x, 0x%x, 0x%x) = (%s))", + checksum, checksum1, checksum2, checksum3, members); + } + Py_DECREF(pickle_error); +} +static int __Pyx_CheckUnpickleChecksum(long checksum, long checksum1, long checksum2, long checksum3, const char *members) { + int found = 0; + found |= checksum1 == checksum; + found |= checksum2 == checksum; + found |= checksum3 == checksum; + if (likely(found)) + return 0; + __Pyx_RaiseUnpickleChecksumError(checksum, checksum1, checksum2, checksum3, members); + return -1; +} + +/* CIntFromPyVerify */ +#define __PYX_VERIFY_RETURN_INT(target_type, func_type, func_value)\ + __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 0) +#define __PYX_VERIFY_RETURN_INT_EXC(target_type, func_type, func_value)\ + __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 1) +#define __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, exc)\ + {\ + func_type value = func_value;\ + if (sizeof(target_type) < sizeof(func_type)) {\ + if (unlikely(value != (func_type) (target_type) value)) {\ + func_type zero = 0;\ + if (exc && unlikely(value == (func_type)-1 && PyErr_Occurred()))\ + return (target_type) -1;\ + if (is_unsigned && unlikely(value < zero))\ + goto raise_neg_overflow;\ + else\ + goto raise_overflow;\ + }\ + }\ + return (target_type) value;\ + } + +/* CIntFromPy */ +static CYTHON_INLINE int __Pyx_PyLong_As_int(PyObject *x) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const int neg_one = (int) -1, const_zero = (int) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (unlikely(!PyLong_Check(x))) { + int val; + PyObject *tmp = __Pyx_PyNumber_Long(x); + if (!tmp) return (int) -1; + val = __Pyx_PyLong_As_int(tmp); + Py_DECREF(tmp); + return val; + } + if (is_unsigned) { +#if CYTHON_USE_PYLONG_INTERNALS + if (unlikely(__Pyx_PyLong_IsNeg(x))) { + goto raise_neg_overflow; + } else if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(int, __Pyx_compact_upylong, __Pyx_PyLong_CompactValueUnsigned(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_DigitCount(x)) { + case 2: + if ((8 * sizeof(int) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) >= 2 * PyLong_SHIFT)) { + return (int) (((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); + } + } + break; + case 3: + if ((8 * sizeof(int) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) >= 3 * PyLong_SHIFT)) { + return (int) (((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); + } + } + break; + case 4: + if ((8 * sizeof(int) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) >= 4 * PyLong_SHIFT)) { + return (int) (((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); + } + } + break; + } + } +#endif +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030C00A7 + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } +#else + { + int result = PyObject_RichCompareBool(x, Py_False, Py_LT); + if (unlikely(result < 0)) + return (int) -1; + if (unlikely(result == 1)) + goto raise_neg_overflow; + } +#endif + if ((sizeof(int) <= sizeof(unsigned long))) { + __PYX_VERIFY_RETURN_INT_EXC(int, unsigned long, PyLong_AsUnsignedLong(x)) + } else if ((sizeof(int) <= sizeof(unsigned PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(int, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) + } + } else { +#if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(int, __Pyx_compact_pylong, __Pyx_PyLong_CompactValue(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_SignedDigitCount(x)) { + case -2: + if ((8 * sizeof(int) - 1 > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 2 * PyLong_SHIFT)) { + return (int) (((int)-1)*(((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case 2: + if ((8 * sizeof(int) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 2 * PyLong_SHIFT)) { + return (int) ((((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case -3: + if ((8 * sizeof(int) - 1 > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 3 * PyLong_SHIFT)) { + return (int) (((int)-1)*(((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case 3: + if ((8 * sizeof(int) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 3 * PyLong_SHIFT)) { + return (int) ((((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case -4: + if ((8 * sizeof(int) - 1 > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 4 * PyLong_SHIFT)) { + return (int) (((int)-1)*(((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case 4: + if ((8 * sizeof(int) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 4 * PyLong_SHIFT)) { + return (int) ((((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + } + } +#endif + if ((sizeof(int) <= sizeof(long))) { + __PYX_VERIFY_RETURN_INT_EXC(int, long, PyLong_AsLong(x)) + } else if ((sizeof(int) <= sizeof(PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(int, PY_LONG_LONG, PyLong_AsLongLong(x)) + } + } + { + int val; + int ret = -1; +#if PY_VERSION_HEX >= 0x030d00A6 && !CYTHON_COMPILING_IN_LIMITED_API + Py_ssize_t bytes_copied = PyLong_AsNativeBytes( + x, &val, sizeof(val), Py_ASNATIVEBYTES_NATIVE_ENDIAN | (is_unsigned ? Py_ASNATIVEBYTES_UNSIGNED_BUFFER | Py_ASNATIVEBYTES_REJECT_NEGATIVE : 0)); + if (unlikely(bytes_copied == -1)) { + } else if (unlikely(bytes_copied > (Py_ssize_t) sizeof(val))) { + goto raise_overflow; + } else { + ret = 0; + } +#elif PY_VERSION_HEX < 0x030d0000 && !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API) || defined(_PyLong_AsByteArray) + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + ret = _PyLong_AsByteArray((PyLongObject *)x, + bytes, sizeof(val), + is_little, !is_unsigned); +#else + PyObject *v; + PyObject *stepval = NULL, *mask = NULL, *shift = NULL; + int bits, remaining_bits, is_negative = 0; + int chunk_size = (sizeof(long) < 8) ? 30 : 62; + if (likely(PyLong_CheckExact(x))) { + v = __Pyx_NewRef(x); + } else { + v = PyNumber_Long(x); + if (unlikely(!v)) return (int) -1; + assert(PyLong_CheckExact(v)); + } + { + int result = PyObject_RichCompareBool(v, Py_False, Py_LT); + if (unlikely(result < 0)) { + Py_DECREF(v); + return (int) -1; + } + is_negative = result == 1; + } + if (is_unsigned && unlikely(is_negative)) { + Py_DECREF(v); + goto raise_neg_overflow; + } else if (is_negative) { + stepval = PyNumber_Invert(v); + Py_DECREF(v); + if (unlikely(!stepval)) + return (int) -1; + } else { + stepval = v; + } + v = NULL; + val = (int) 0; + mask = PyLong_FromLong((1L << chunk_size) - 1); if (unlikely(!mask)) goto done; + shift = PyLong_FromLong(chunk_size); if (unlikely(!shift)) goto done; + for (bits = 0; bits < (int) sizeof(int) * 8 - chunk_size; bits += chunk_size) { + PyObject *tmp, *digit; + long idigit; + digit = PyNumber_And(stepval, mask); + if (unlikely(!digit)) goto done; + idigit = PyLong_AsLong(digit); + Py_DECREF(digit); + if (unlikely(idigit < 0)) goto done; + val |= ((int) idigit) << bits; + tmp = PyNumber_Rshift(stepval, shift); + if (unlikely(!tmp)) goto done; + Py_DECREF(stepval); stepval = tmp; + } + Py_DECREF(shift); shift = NULL; + Py_DECREF(mask); mask = NULL; + { + long idigit = PyLong_AsLong(stepval); + if (unlikely(idigit < 0)) goto done; + remaining_bits = ((int) sizeof(int) * 8) - bits - (is_unsigned ? 0 : 1); + if (unlikely(idigit >= (1L << remaining_bits))) + goto raise_overflow; + val |= ((int) idigit) << bits; + } + if (!is_unsigned) { + if (unlikely(val & (((int) 1) << (sizeof(int) * 8 - 1)))) + goto raise_overflow; + if (is_negative) + val = ~val; + } + ret = 0; + done: + Py_XDECREF(shift); + Py_XDECREF(mask); + Py_XDECREF(stepval); +#endif + if (unlikely(ret)) + return (int) -1; + return val; + } +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to int"); + return (int) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to int"); + return (int) -1; +} + +/* CIntFromPy */ +static CYTHON_INLINE long __Pyx_PyLong_As_long(PyObject *x) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const long neg_one = (long) -1, const_zero = (long) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (unlikely(!PyLong_Check(x))) { + long val; + PyObject *tmp = __Pyx_PyNumber_Long(x); + if (!tmp) return (long) -1; + val = __Pyx_PyLong_As_long(tmp); + Py_DECREF(tmp); + return val; + } + if (is_unsigned) { +#if CYTHON_USE_PYLONG_INTERNALS + if (unlikely(__Pyx_PyLong_IsNeg(x))) { + goto raise_neg_overflow; + } else if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(long, __Pyx_compact_upylong, __Pyx_PyLong_CompactValueUnsigned(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_DigitCount(x)) { + case 2: + if ((8 * sizeof(long) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) >= 2 * PyLong_SHIFT)) { + return (long) (((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); + } + } + break; + case 3: + if ((8 * sizeof(long) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) >= 3 * PyLong_SHIFT)) { + return (long) (((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); + } + } + break; + case 4: + if ((8 * sizeof(long) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) >= 4 * PyLong_SHIFT)) { + return (long) (((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); + } + } + break; + } + } +#endif +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030C00A7 + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } +#else + { + int result = PyObject_RichCompareBool(x, Py_False, Py_LT); + if (unlikely(result < 0)) + return (long) -1; + if (unlikely(result == 1)) + goto raise_neg_overflow; + } +#endif + if ((sizeof(long) <= sizeof(unsigned long))) { + __PYX_VERIFY_RETURN_INT_EXC(long, unsigned long, PyLong_AsUnsignedLong(x)) + } else if ((sizeof(long) <= sizeof(unsigned PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(long, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) + } + } else { +#if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(long, __Pyx_compact_pylong, __Pyx_PyLong_CompactValue(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_SignedDigitCount(x)) { + case -2: + if ((8 * sizeof(long) - 1 > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 2 * PyLong_SHIFT)) { + return (long) (((long)-1)*(((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case 2: + if ((8 * sizeof(long) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 2 * PyLong_SHIFT)) { + return (long) ((((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case -3: + if ((8 * sizeof(long) - 1 > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 3 * PyLong_SHIFT)) { + return (long) (((long)-1)*(((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case 3: + if ((8 * sizeof(long) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 3 * PyLong_SHIFT)) { + return (long) ((((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case -4: + if ((8 * sizeof(long) - 1 > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 4 * PyLong_SHIFT)) { + return (long) (((long)-1)*(((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case 4: + if ((8 * sizeof(long) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 4 * PyLong_SHIFT)) { + return (long) ((((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + } + } +#endif + if ((sizeof(long) <= sizeof(long))) { + __PYX_VERIFY_RETURN_INT_EXC(long, long, PyLong_AsLong(x)) + } else if ((sizeof(long) <= sizeof(PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(long, PY_LONG_LONG, PyLong_AsLongLong(x)) + } + } + { + long val; + int ret = -1; +#if PY_VERSION_HEX >= 0x030d00A6 && !CYTHON_COMPILING_IN_LIMITED_API + Py_ssize_t bytes_copied = PyLong_AsNativeBytes( + x, &val, sizeof(val), Py_ASNATIVEBYTES_NATIVE_ENDIAN | (is_unsigned ? Py_ASNATIVEBYTES_UNSIGNED_BUFFER | Py_ASNATIVEBYTES_REJECT_NEGATIVE : 0)); + if (unlikely(bytes_copied == -1)) { + } else if (unlikely(bytes_copied > (Py_ssize_t) sizeof(val))) { + goto raise_overflow; + } else { + ret = 0; + } +#elif PY_VERSION_HEX < 0x030d0000 && !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API) || defined(_PyLong_AsByteArray) + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + ret = _PyLong_AsByteArray((PyLongObject *)x, + bytes, sizeof(val), + is_little, !is_unsigned); +#else + PyObject *v; + PyObject *stepval = NULL, *mask = NULL, *shift = NULL; + int bits, remaining_bits, is_negative = 0; + int chunk_size = (sizeof(long) < 8) ? 30 : 62; + if (likely(PyLong_CheckExact(x))) { + v = __Pyx_NewRef(x); + } else { + v = PyNumber_Long(x); + if (unlikely(!v)) return (long) -1; + assert(PyLong_CheckExact(v)); + } + { + int result = PyObject_RichCompareBool(v, Py_False, Py_LT); + if (unlikely(result < 0)) { + Py_DECREF(v); + return (long) -1; + } + is_negative = result == 1; + } + if (is_unsigned && unlikely(is_negative)) { + Py_DECREF(v); + goto raise_neg_overflow; + } else if (is_negative) { + stepval = PyNumber_Invert(v); + Py_DECREF(v); + if (unlikely(!stepval)) + return (long) -1; + } else { + stepval = v; + } + v = NULL; + val = (long) 0; + mask = PyLong_FromLong((1L << chunk_size) - 1); if (unlikely(!mask)) goto done; + shift = PyLong_FromLong(chunk_size); if (unlikely(!shift)) goto done; + for (bits = 0; bits < (int) sizeof(long) * 8 - chunk_size; bits += chunk_size) { + PyObject *tmp, *digit; + long idigit; + digit = PyNumber_And(stepval, mask); + if (unlikely(!digit)) goto done; + idigit = PyLong_AsLong(digit); + Py_DECREF(digit); + if (unlikely(idigit < 0)) goto done; + val |= ((long) idigit) << bits; + tmp = PyNumber_Rshift(stepval, shift); + if (unlikely(!tmp)) goto done; + Py_DECREF(stepval); stepval = tmp; + } + Py_DECREF(shift); shift = NULL; + Py_DECREF(mask); mask = NULL; + { + long idigit = PyLong_AsLong(stepval); + if (unlikely(idigit < 0)) goto done; + remaining_bits = ((int) sizeof(long) * 8) - bits - (is_unsigned ? 0 : 1); + if (unlikely(idigit >= (1L << remaining_bits))) + goto raise_overflow; + val |= ((long) idigit) << bits; + } + if (!is_unsigned) { + if (unlikely(val & (((long) 1) << (sizeof(long) * 8 - 1)))) + goto raise_overflow; + if (is_negative) + val = ~val; + } + ret = 0; + done: + Py_XDECREF(shift); + Py_XDECREF(mask); + Py_XDECREF(stepval); +#endif + if (unlikely(ret)) + return (long) -1; + return val; + } +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to long"); + return (long) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to long"); + return (long) -1; +} + +/* PyObjectVectorCallKwBuilder (used by CIntToPy) */ +#if CYTHON_VECTORCALL +static int __Pyx_VectorcallBuilder_AddArg(PyObject *key, PyObject *value, PyObject *builder, PyObject **args, int n) { + (void)__Pyx_PyObject_FastCallDict; + if (__Pyx_PyTuple_SET_ITEM(builder, n, key) != (0)) return -1; + Py_INCREF(key); + args[n] = value; + return 0; +} +CYTHON_UNUSED static int __Pyx_VectorcallBuilder_AddArg_Check(PyObject *key, PyObject *value, PyObject *builder, PyObject **args, int n) { + (void)__Pyx_VectorcallBuilder_AddArgStr; + if (unlikely(!PyUnicode_Check(key))) { + PyErr_SetString(PyExc_TypeError, "keywords must be strings"); + return -1; + } + return __Pyx_VectorcallBuilder_AddArg(key, value, builder, args, n); +} +static int __Pyx_VectorcallBuilder_AddArgStr(const char *key, PyObject *value, PyObject *builder, PyObject **args, int n) { + PyObject *pyKey = PyUnicode_FromString(key); + if (!pyKey) return -1; + return __Pyx_VectorcallBuilder_AddArg(pyKey, value, builder, args, n); +} +#else // CYTHON_VECTORCALL +CYTHON_UNUSED static int __Pyx_VectorcallBuilder_AddArg_Check(PyObject *key, PyObject *value, PyObject *builder, CYTHON_UNUSED PyObject **args, CYTHON_UNUSED int n) { + if (unlikely(!PyUnicode_Check(key))) { + PyErr_SetString(PyExc_TypeError, "keywords must be strings"); + return -1; + } + return PyDict_SetItem(builder, key, value); +} +#endif + +/* CIntToPy */ +static CYTHON_INLINE PyObject* __Pyx_PyLong_From_int(int value) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const int neg_one = (int) -1, const_zero = (int) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(int) < sizeof(long)) { + return PyLong_FromLong((long) value); + } else if (sizeof(int) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); +#if !CYTHON_COMPILING_IN_PYPY + } else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) { + return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); +#endif + } + } else { + if (sizeof(int) <= sizeof(long)) { + return PyLong_FromLong((long) value); + } else if (sizeof(int) <= sizeof(PY_LONG_LONG)) { + return PyLong_FromLongLong((PY_LONG_LONG) value); + } + } + { + unsigned char *bytes = (unsigned char *)&value; +#if !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d00A4 + if (is_unsigned) { + return PyLong_FromUnsignedNativeBytes(bytes, sizeof(value), -1); + } else { + return PyLong_FromNativeBytes(bytes, sizeof(value), -1); + } +#elif !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030d0000 + int one = 1; int little = (int)*(unsigned char *)&one; + return _PyLong_FromByteArray(bytes, sizeof(int), + little, !is_unsigned); +#else + int one = 1; int little = (int)*(unsigned char *)&one; + PyObject *from_bytes, *result = NULL, *kwds = NULL; + PyObject *py_bytes = NULL, *order_str = NULL; + from_bytes = PyObject_GetAttrString((PyObject*)&PyLong_Type, "from_bytes"); + if (!from_bytes) return NULL; + py_bytes = PyBytes_FromStringAndSize((char*)bytes, sizeof(int)); + if (!py_bytes) goto limited_bad; + order_str = PyUnicode_FromString(little ? "little" : "big"); + if (!order_str) goto limited_bad; + { + PyObject *args[3+(CYTHON_VECTORCALL ? 1 : 0)] = { NULL, py_bytes, order_str }; + if (!is_unsigned) { + kwds = __Pyx_MakeVectorcallBuilderKwds(1); + if (!kwds) goto limited_bad; + if (__Pyx_VectorcallBuilder_AddArgStr("signed", __Pyx_NewRef(Py_True), kwds, args+3, 0) < 0) goto limited_bad; + } + result = __Pyx_Object_Vectorcall_CallFromBuilder(from_bytes, args+1, 2 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET, kwds); + } + limited_bad: + Py_XDECREF(kwds); + Py_XDECREF(order_str); + Py_XDECREF(py_bytes); + Py_XDECREF(from_bytes); + return result; +#endif + } +} + +/* CIntToPy */ +static CYTHON_INLINE PyObject* __Pyx_PyLong_From_long(long value) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const long neg_one = (long) -1, const_zero = (long) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(long) < sizeof(long)) { + return PyLong_FromLong((long) value); + } else if (sizeof(long) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); +#if !CYTHON_COMPILING_IN_PYPY + } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { + return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); +#endif + } + } else { + if (sizeof(long) <= sizeof(long)) { + return PyLong_FromLong((long) value); + } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { + return PyLong_FromLongLong((PY_LONG_LONG) value); + } + } + { + unsigned char *bytes = (unsigned char *)&value; +#if !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d00A4 + if (is_unsigned) { + return PyLong_FromUnsignedNativeBytes(bytes, sizeof(value), -1); + } else { + return PyLong_FromNativeBytes(bytes, sizeof(value), -1); + } +#elif !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030d0000 + int one = 1; int little = (int)*(unsigned char *)&one; + return _PyLong_FromByteArray(bytes, sizeof(long), + little, !is_unsigned); +#else + int one = 1; int little = (int)*(unsigned char *)&one; + PyObject *from_bytes, *result = NULL, *kwds = NULL; + PyObject *py_bytes = NULL, *order_str = NULL; + from_bytes = PyObject_GetAttrString((PyObject*)&PyLong_Type, "from_bytes"); + if (!from_bytes) return NULL; + py_bytes = PyBytes_FromStringAndSize((char*)bytes, sizeof(long)); + if (!py_bytes) goto limited_bad; + order_str = PyUnicode_FromString(little ? "little" : "big"); + if (!order_str) goto limited_bad; + { + PyObject *args[3+(CYTHON_VECTORCALL ? 1 : 0)] = { NULL, py_bytes, order_str }; + if (!is_unsigned) { + kwds = __Pyx_MakeVectorcallBuilderKwds(1); + if (!kwds) goto limited_bad; + if (__Pyx_VectorcallBuilder_AddArgStr("signed", __Pyx_NewRef(Py_True), kwds, args+3, 0) < 0) goto limited_bad; + } + result = __Pyx_Object_Vectorcall_CallFromBuilder(from_bytes, args+1, 2 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET, kwds); + } + limited_bad: + Py_XDECREF(kwds); + Py_XDECREF(order_str); + Py_XDECREF(py_bytes); + Py_XDECREF(from_bytes); + return result; +#endif + } +} + +/* PyObjectCall2Args */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call2Args(PyObject* function, PyObject* arg1, PyObject* arg2) { + PyObject *args[3] = {NULL, arg1, arg2}; + return __Pyx_PyObject_FastCall(function, args+1, 2 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET); +} + +/* PyObjectCallMethod1 */ +#if !(CYTHON_VECTORCALL && (__PYX_LIMITED_VERSION_HEX >= 0x030C0000 || (!CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x03090000))) +static PyObject* __Pyx__PyObject_CallMethod1(PyObject* method, PyObject* arg) { + PyObject *result = __Pyx_PyObject_CallOneArg(method, arg); + Py_DECREF(method); + return result; +} +#endif +static PyObject* __Pyx_PyObject_CallMethod1(PyObject* obj, PyObject* method_name, PyObject* arg) { +#if CYTHON_VECTORCALL && (__PYX_LIMITED_VERSION_HEX >= 0x030C0000 || (!CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x03090000)) + PyObject *args[2] = {obj, arg}; + (void) __Pyx_PyObject_CallOneArg; + (void) __Pyx_PyObject_Call2Args; + return PyObject_VectorcallMethod(method_name, args, 2 | PY_VECTORCALL_ARGUMENTS_OFFSET, NULL); +#else + PyObject *method = NULL, *result; + int is_method = __Pyx_PyObject_GetMethod(obj, method_name, &method); + if (likely(is_method)) { + result = __Pyx_PyObject_Call2Args(method, obj, arg); + Py_DECREF(method); + return result; + } + if (unlikely(!method)) return NULL; + return __Pyx__PyObject_CallMethod1(method, arg); +#endif +} + +/* UpdateUnpickledDict */ +static int __Pyx__UpdateUnpickledDict(PyObject *obj, PyObject *state, Py_ssize_t index) { + PyObject *state_dict = __Pyx_PySequence_ITEM(state, index); + if (unlikely(!state_dict)) { + return -1; + } + int non_empty = PyObject_IsTrue(state_dict); + if (non_empty == 0) { + Py_DECREF(state_dict); + return 0; + } else if (unlikely(non_empty == -1)) { + return -1; + } + PyObject *dict; + #if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000 + dict = PyObject_GetAttrString(obj, "__dict__"); + #else + dict = PyObject_GenericGetDict(obj, NULL); + #endif + if (unlikely(!dict)) { + Py_DECREF(state_dict); + return -1; + } + int result; + if (likely(PyDict_CheckExact(dict))) { + result = PyDict_Update(dict, state_dict); + } else { + PyObject *obj_result = __Pyx_PyObject_CallMethod1(dict, __pyx_mstate_global->__pyx_n_u_update, state_dict); + if (likely(obj_result)) { + Py_DECREF(obj_result); + result = 0; + } else { + result = -1; + } + } + Py_DECREF(state_dict); + Py_DECREF(dict); + return result; +} +static int __Pyx_UpdateUnpickledDict(PyObject *obj, PyObject *state, Py_ssize_t index) { + Py_ssize_t state_size = __Pyx_PyTuple_GET_SIZE(state); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(state_size == -1)) return -1; + #endif + if (state_size <= index) { + return 0; + } + return __Pyx__UpdateUnpickledDict(obj, state, index); +} + +/* FormatTypeName */ +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030d0000 +static __Pyx_TypeName +__Pyx_PyType_GetFullyQualifiedName(PyTypeObject* tp) +{ + PyObject *module = NULL, *name = NULL, *result = NULL; + #if __PYX_LIMITED_VERSION_HEX < 0x030b0000 + name = __Pyx_PyObject_GetAttrStr((PyObject *)tp, + __pyx_mstate_global->__pyx_n_u_qualname); + #else + name = PyType_GetQualName(tp); + #endif + if (unlikely(name == NULL) || unlikely(!PyUnicode_Check(name))) goto bad; + module = __Pyx_PyObject_GetAttrStr((PyObject *)tp, + __pyx_mstate_global->__pyx_n_u_module); + if (unlikely(module == NULL) || unlikely(!PyUnicode_Check(module))) goto bad; + if (PyUnicode_CompareWithASCIIString(module, "builtins") == 0) { + result = name; + name = NULL; + goto done; + } + result = PyUnicode_FromFormat("%U.%U", module, name); + if (unlikely(result == NULL)) goto bad; + done: + Py_XDECREF(name); + Py_XDECREF(module); + return result; + bad: + PyErr_Clear(); + if (name) { + result = name; + name = NULL; + } else { + result = __Pyx_NewRef(__pyx_mstate_global->__pyx_kp_u__3); + } + goto done; +} +#endif + +/* FastTypeChecks */ +#if CYTHON_COMPILING_IN_CPYTHON +static int __Pyx_InBases(PyTypeObject *a, PyTypeObject *b) { + while (a) { + a = __Pyx_PyType_GetSlot(a, tp_base, PyTypeObject*); + if (a == b) + return 1; + } + return b == &PyBaseObject_Type; +} +static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b) { + PyObject *mro; + if (a == b) return 1; + mro = a->tp_mro; + if (likely(mro)) { + Py_ssize_t i, n; + n = PyTuple_GET_SIZE(mro); + for (i = 0; i < n; i++) { + if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b) + return 1; + } + return 0; + } + return __Pyx_InBases(a, b); +} +static CYTHON_INLINE int __Pyx_IsAnySubtype2(PyTypeObject *cls, PyTypeObject *a, PyTypeObject *b) { + PyObject *mro; + if (cls == a || cls == b) return 1; + mro = cls->tp_mro; + if (likely(mro)) { + Py_ssize_t i, n; + n = PyTuple_GET_SIZE(mro); + for (i = 0; i < n; i++) { + PyObject *base = PyTuple_GET_ITEM(mro, i); + if (base == (PyObject *)a || base == (PyObject *)b) + return 1; + } + return 0; + } + return __Pyx_InBases(cls, a) || __Pyx_InBases(cls, b); +} +static CYTHON_INLINE int __Pyx_inner_PyErr_GivenExceptionMatches2(PyObject *err, PyObject* exc_type1, PyObject *exc_type2) { + if (exc_type1) { + return __Pyx_IsAnySubtype2((PyTypeObject*)err, (PyTypeObject*)exc_type1, (PyTypeObject*)exc_type2); + } else { + return __Pyx_IsSubtype((PyTypeObject*)err, (PyTypeObject*)exc_type2); + } +} +static int __Pyx_PyErr_GivenExceptionMatchesTuple(PyObject *exc_type, PyObject *tuple) { + Py_ssize_t i, n; + assert(PyExceptionClass_Check(exc_type)); + n = PyTuple_GET_SIZE(tuple); + for (i=0; i>= 8; + ++i; + } + __Pyx_cached_runtime_version = version; + } +} +#endif +static unsigned long __Pyx_get_runtime_version(void) { +#if __PYX_LIMITED_VERSION_HEX >= 0x030b0000 + return Py_Version & ~0xFFUL; +#else + return __Pyx_cached_runtime_version; +#endif +} + +/* CheckBinaryVersion */ +static int __Pyx_check_binary_version(unsigned long ct_version, unsigned long rt_version, int allow_newer) { + const unsigned long MAJOR_MINOR = 0xFFFF0000UL; + if ((rt_version & MAJOR_MINOR) == (ct_version & MAJOR_MINOR)) + return 0; + if (likely(allow_newer && (rt_version & MAJOR_MINOR) > (ct_version & MAJOR_MINOR))) + return 1; + { + char message[200]; + PyOS_snprintf(message, sizeof(message), + "compile time Python version %d.%d " + "of module '%.100s' " + "%s " + "runtime version %d.%d", + (int) (ct_version >> 24), (int) ((ct_version >> 16) & 0xFF), + __Pyx_MODULE_NAME, + (allow_newer) ? "was newer than" : "does not match", + (int) (rt_version >> 24), (int) ((rt_version >> 16) & 0xFF) + ); + return PyErr_WarnEx(NULL, message, 1); + } +} + +/* NewCodeObj */ +#if CYTHON_COMPILING_IN_LIMITED_API + static PyObject* __Pyx__PyCode_New(int a, int p, int k, int l, int s, int f, + PyObject *code, PyObject *c, PyObject* n, PyObject *v, + PyObject *fv, PyObject *cell, PyObject* fn, + PyObject *name, int fline, PyObject *lnos) { + PyObject *exception_table = NULL; + PyObject *types_module=NULL, *code_type=NULL, *result=NULL; + #if __PYX_LIMITED_VERSION_HEX < 0x030b0000 + PyObject *version_info; + PyObject *py_minor_version = NULL; + #endif + long minor_version = 0; + PyObject *type, *value, *traceback; + PyErr_Fetch(&type, &value, &traceback); + #if __PYX_LIMITED_VERSION_HEX >= 0x030b0000 + minor_version = 11; + #else + if (!(version_info = PySys_GetObject("version_info"))) goto end; + if (!(py_minor_version = PySequence_GetItem(version_info, 1))) goto end; + minor_version = PyLong_AsLong(py_minor_version); + Py_DECREF(py_minor_version); + if (minor_version == -1 && PyErr_Occurred()) goto end; + #endif + if (!(types_module = PyImport_ImportModule("types"))) goto end; + if (!(code_type = PyObject_GetAttrString(types_module, "CodeType"))) goto end; + if (minor_version <= 7) { + (void)p; + result = PyObject_CallFunction(code_type, "iiiiiOOOOOOiOOO", a, k, l, s, f, code, + c, n, v, fn, name, fline, lnos, fv, cell); + } else if (minor_version <= 10) { + result = PyObject_CallFunction(code_type, "iiiiiiOOOOOOiOOO", a,p, k, l, s, f, code, + c, n, v, fn, name, fline, lnos, fv, cell); + } else { + if (!(exception_table = PyBytes_FromStringAndSize(NULL, 0))) goto end; + result = PyObject_CallFunction(code_type, "iiiiiiOOOOOOOiOOOO", a,p, k, l, s, f, code, + c, n, v, fn, name, name, fline, lnos, exception_table, fv, cell); + } + end: + Py_XDECREF(code_type); + Py_XDECREF(exception_table); + Py_XDECREF(types_module); + if (type) { + PyErr_Restore(type, value, traceback); + } + return result; + } +#elif PY_VERSION_HEX >= 0x030B0000 + static PyCodeObject* __Pyx__PyCode_New(int a, int p, int k, int l, int s, int f, + PyObject *code, PyObject *c, PyObject* n, PyObject *v, + PyObject *fv, PyObject *cell, PyObject* fn, + PyObject *name, int fline, PyObject *lnos) { + PyCodeObject *result; + result = + #if PY_VERSION_HEX >= 0x030C0000 + PyUnstable_Code_NewWithPosOnlyArgs + #else + PyCode_NewWithPosOnlyArgs + #endif + (a, p, k, l, s, f, code, c, n, v, fv, cell, fn, name, name, fline, lnos, __pyx_mstate_global->__pyx_empty_bytes); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030c00A1 + if (likely(result)) + result->_co_firsttraceable = 0; + #endif + return result; + } +#elif !CYTHON_COMPILING_IN_PYPY + #define __Pyx__PyCode_New(a, p, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ + PyCode_NewWithPosOnlyArgs(a, p, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) +#else + #define __Pyx__PyCode_New(a, p, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ + PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) +#endif +static PyObject* __Pyx_PyCode_New( + const __Pyx_PyCode_New_function_description descr, + PyObject * const *varnames, + PyObject *filename, + PyObject *funcname, + PyObject *line_table, + PyObject *tuple_dedup_map +) { + PyObject *code_obj = NULL, *varnames_tuple_dedup = NULL, *code_bytes = NULL; + Py_ssize_t var_count = (Py_ssize_t) descr.nlocals; + PyObject *varnames_tuple = PyTuple_New(var_count); + if (unlikely(!varnames_tuple)) return NULL; + for (Py_ssize_t i=0; i < var_count; i++) { + Py_INCREF(varnames[i]); + if (__Pyx_PyTuple_SET_ITEM(varnames_tuple, i, varnames[i]) != (0)) goto done; + } + #if CYTHON_COMPILING_IN_LIMITED_API + varnames_tuple_dedup = PyDict_GetItem(tuple_dedup_map, varnames_tuple); + if (!varnames_tuple_dedup) { + if (unlikely(PyDict_SetItem(tuple_dedup_map, varnames_tuple, varnames_tuple) < 0)) goto done; + varnames_tuple_dedup = varnames_tuple; + } + #else + varnames_tuple_dedup = PyDict_SetDefault(tuple_dedup_map, varnames_tuple, varnames_tuple); + if (unlikely(!varnames_tuple_dedup)) goto done; + #endif + #if CYTHON_AVOID_BORROWED_REFS + Py_INCREF(varnames_tuple_dedup); + #endif + if (__PYX_LIMITED_VERSION_HEX >= (0x030b0000) && line_table != NULL && !CYTHON_COMPILING_IN_GRAAL) { + Py_ssize_t line_table_length = __Pyx_PyBytes_GET_SIZE(line_table); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(line_table_length == -1)) goto done; + #endif + Py_ssize_t code_len = (line_table_length * 2 + 4) & ~3LL; + code_bytes = PyBytes_FromStringAndSize(NULL, code_len); + if (unlikely(!code_bytes)) goto done; + char* c_code_bytes = PyBytes_AsString(code_bytes); + if (unlikely(!c_code_bytes)) goto done; + memset(c_code_bytes, 0, (size_t) code_len); + } + code_obj = (PyObject*) __Pyx__PyCode_New( + (int) descr.argcount, + (int) descr.num_posonly_args, + (int) descr.num_kwonly_args, + (int) descr.nlocals, + 0, + (int) descr.flags, + code_bytes ? code_bytes : __pyx_mstate_global->__pyx_empty_bytes, + __pyx_mstate_global->__pyx_empty_tuple, + __pyx_mstate_global->__pyx_empty_tuple, + varnames_tuple_dedup, + __pyx_mstate_global->__pyx_empty_tuple, + __pyx_mstate_global->__pyx_empty_tuple, + filename, + funcname, + (int) descr.first_line, + (__PYX_LIMITED_VERSION_HEX >= (0x030b0000) && line_table) ? line_table : __pyx_mstate_global->__pyx_empty_bytes + ); +done: + Py_XDECREF(code_bytes); + #if CYTHON_AVOID_BORROWED_REFS + Py_XDECREF(varnames_tuple_dedup); + #endif + Py_DECREF(varnames_tuple); + return code_obj; +} + +/* DecompressString */ +static PyObject *__Pyx_DecompressString(const char *s, Py_ssize_t length, int algo) { + PyObject *module = NULL, *decompress, *compressed_bytes, *decompressed; + const char* module_name = algo == 3 ? "compression.zstd" : algo == 2 ? "bz2" : "zlib"; + PyObject *methodname = PyUnicode_FromString("decompress"); + if (unlikely(!methodname)) return NULL; + #if __PYX_LIMITED_VERSION_HEX >= 0x030e0000 + if (algo == 3) { + PyObject *fromlist = Py_BuildValue("[O]", methodname); + if (unlikely(!fromlist)) goto bad; + module = PyImport_ImportModuleLevel("compression.zstd", NULL, NULL, fromlist, 0); + Py_DECREF(fromlist); + } else + #endif + module = PyImport_ImportModule(module_name); + if (unlikely(!module)) goto import_failed; + decompress = PyObject_GetAttr(module, methodname); + if (unlikely(!decompress)) goto import_failed; + { + #ifdef __cplusplus + char *memview_bytes = const_cast(s); + #else + #if defined(__clang__) + #pragma clang diagnostic push + #pragma clang diagnostic ignored "-Wcast-qual" + #elif !defined(__INTEL_COMPILER) && defined(__GNUC__) + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wcast-qual" + #endif + char *memview_bytes = (char*) s; + #if defined(__clang__) + #pragma clang diagnostic pop + #elif !defined(__INTEL_COMPILER) && defined(__GNUC__) + #pragma GCC diagnostic pop + #endif + #endif + #if CYTHON_COMPILING_IN_LIMITED_API && !defined(PyBUF_READ) + int memview_flags = 0x100; + #else + int memview_flags = PyBUF_READ; + #endif + compressed_bytes = PyMemoryView_FromMemory(memview_bytes, length, memview_flags); + } + if (unlikely(!compressed_bytes)) { + Py_DECREF(decompress); + goto bad; + } + decompressed = PyObject_CallFunctionObjArgs(decompress, compressed_bytes, NULL); + Py_DECREF(compressed_bytes); + Py_DECREF(decompress); + Py_DECREF(module); + Py_DECREF(methodname); + return decompressed; +import_failed: + PyErr_Format(PyExc_ImportError, + "Failed to import '%.20s.decompress' - cannot initialise module strings. " + "String compression was configured with the C macro 'CYTHON_COMPRESS_STRINGS=%d'.", + module_name, algo); +bad: + Py_XDECREF(module); + Py_DECREF(methodname); + return NULL; +} + +#include +static CYTHON_INLINE Py_ssize_t __Pyx_ssize_strlen(const char *s) { + size_t len = strlen(s); + if (unlikely(len > (size_t) PY_SSIZE_T_MAX)) { + PyErr_SetString(PyExc_OverflowError, "byte string is too long"); + return -1; + } + return (Py_ssize_t) len; +} +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char* c_str) { + Py_ssize_t len = __Pyx_ssize_strlen(c_str); + if (unlikely(len < 0)) return NULL; + return __Pyx_PyUnicode_FromStringAndSize(c_str, len); +} +static CYTHON_INLINE PyObject* __Pyx_PyByteArray_FromString(const char* c_str) { + Py_ssize_t len = __Pyx_ssize_strlen(c_str); + if (unlikely(len < 0)) return NULL; + return PyByteArray_FromStringAndSize(c_str, len); +} +static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject* o) { + Py_ssize_t ignore; + return __Pyx_PyObject_AsStringAndSize(o, &ignore); +} +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 +static CYTHON_INLINE const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *length) { + if (unlikely(__Pyx_PyUnicode_READY(o) == -1)) return NULL; +#if CYTHON_COMPILING_IN_LIMITED_API + { + const char* result; + Py_ssize_t unicode_length; + CYTHON_MAYBE_UNUSED_VAR(unicode_length); // only for __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + #if __PYX_LIMITED_VERSION_HEX < 0x030A0000 + if (unlikely(PyArg_Parse(o, "s#", &result, length) < 0)) return NULL; + #else + result = PyUnicode_AsUTF8AndSize(o, length); + #endif + #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + unicode_length = PyUnicode_GetLength(o); + if (unlikely(unicode_length < 0)) return NULL; + if (unlikely(unicode_length != *length)) { + PyUnicode_AsASCIIString(o); + return NULL; + } + #endif + return result; + } +#else +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + if (likely(PyUnicode_IS_ASCII(o))) { + *length = PyUnicode_GET_LENGTH(o); + return PyUnicode_AsUTF8(o); + } else { + PyUnicode_AsASCIIString(o); + return NULL; + } +#else + return PyUnicode_AsUTF8AndSize(o, length); +#endif +#endif +} +#endif +static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 + if (PyUnicode_Check(o)) { + return __Pyx_PyUnicode_AsStringAndSize(o, length); + } else +#endif + if (PyByteArray_Check(o)) { +#if (CYTHON_ASSUME_SAFE_SIZE && CYTHON_ASSUME_SAFE_MACROS) || (CYTHON_COMPILING_IN_PYPY && (defined(PyByteArray_AS_STRING) && defined(PyByteArray_GET_SIZE))) + *length = PyByteArray_GET_SIZE(o); + return PyByteArray_AS_STRING(o); +#else + *length = PyByteArray_Size(o); + if (*length == -1) return NULL; + return PyByteArray_AsString(o); +#endif + } else + { + char* result; + int r = PyBytes_AsStringAndSize(o, &result, length); + if (unlikely(r < 0)) { + return NULL; + } else { + return result; + } + } +} +static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { + int is_true = x == Py_True; + if (is_true | (x == Py_False) | (x == Py_None)) return is_true; + else return PyObject_IsTrue(x); +} +static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject* x) { + int retval; + if (unlikely(!x)) return -1; + retval = __Pyx_PyObject_IsTrue(x); + Py_DECREF(x); + return retval; +} +static PyObject* __Pyx_PyNumber_LongWrongResultType(PyObject* result) { + __Pyx_TypeName result_type_name = __Pyx_PyType_GetFullyQualifiedName(Py_TYPE(result)); + if (PyLong_Check(result)) { + if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1, + "__int__ returned non-int (type " __Pyx_FMT_TYPENAME "). " + "The ability to return an instance of a strict subclass of int is deprecated, " + "and may be removed in a future version of Python.", + result_type_name)) { + __Pyx_DECREF_TypeName(result_type_name); + Py_DECREF(result); + return NULL; + } + __Pyx_DECREF_TypeName(result_type_name); + return result; + } + PyErr_Format(PyExc_TypeError, + "__int__ returned non-int (type " __Pyx_FMT_TYPENAME ")", + result_type_name); + __Pyx_DECREF_TypeName(result_type_name); + Py_DECREF(result); + return NULL; +} +static CYTHON_INLINE PyObject* __Pyx_PyNumber_Long(PyObject* x) { +#if CYTHON_USE_TYPE_SLOTS + PyNumberMethods *m; +#endif + PyObject *res = NULL; + if (likely(PyLong_Check(x))) + return __Pyx_NewRef(x); +#if CYTHON_USE_TYPE_SLOTS + m = Py_TYPE(x)->tp_as_number; + if (likely(m && m->nb_int)) { + res = m->nb_int(x); + } +#else + if (!PyBytes_CheckExact(x) && !PyUnicode_CheckExact(x)) { + res = PyNumber_Long(x); + } +#endif + if (likely(res)) { + if (unlikely(!PyLong_CheckExact(res))) { + return __Pyx_PyNumber_LongWrongResultType(res); + } + } + else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_TypeError, + "an integer is required"); + } + return res; +} +static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { + Py_ssize_t ival; + PyObject *x; + if (likely(PyLong_CheckExact(b))) { + #if CYTHON_USE_PYLONG_INTERNALS + if (likely(__Pyx_PyLong_IsCompact(b))) { + return __Pyx_PyLong_CompactValue(b); + } else { + const digit* digits = __Pyx_PyLong_Digits(b); + const Py_ssize_t size = __Pyx_PyLong_SignedDigitCount(b); + switch (size) { + case 2: + if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { + return (Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case -2: + if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { + return -(Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case 3: + if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { + return (Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case -3: + if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { + return -(Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case 4: + if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { + return (Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case -4: + if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { + return -(Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + } + } + #endif + return PyLong_AsSsize_t(b); + } + x = PyNumber_Index(b); + if (!x) return -1; + ival = PyLong_AsSsize_t(x); + Py_DECREF(x); + return ival; +} +static CYTHON_INLINE Py_hash_t __Pyx_PyIndex_AsHash_t(PyObject* o) { + if (sizeof(Py_hash_t) == sizeof(Py_ssize_t)) { + return (Py_hash_t) __Pyx_PyIndex_AsSsize_t(o); + } else { + Py_ssize_t ival; + PyObject *x; + x = PyNumber_Index(o); + if (!x) return -1; + ival = PyLong_AsLong(x); + Py_DECREF(x); + return ival; + } +} +static CYTHON_INLINE PyObject *__Pyx_Owned_Py_None(int b) { + CYTHON_UNUSED_VAR(b); + return __Pyx_NewRef(Py_None); +} +static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b) { + return __Pyx_NewRef(b ? Py_True: Py_False); +} +static CYTHON_INLINE PyObject * __Pyx_PyLong_FromSize_t(size_t ival) { + return PyLong_FromSize_t(ival); +} + + +/* MultiPhaseInitModuleState */ +#if CYTHON_PEP489_MULTI_PHASE_INIT && CYTHON_USE_MODULE_STATE +#ifndef CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE +#if (CYTHON_COMPILING_IN_LIMITED_API || PY_VERSION_HEX >= 0x030C0000) + #define CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE 1 +#else + #define CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE 0 +#endif +#endif +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE && !CYTHON_ATOMICS +#error "Module state with PEP489 requires atomics. Currently that's one of\ + C11, C++11, gcc atomic intrinsics or MSVC atomic intrinsics" +#endif +#if !CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE +#define __Pyx_ModuleStateLookup_Lock() +#define __Pyx_ModuleStateLookup_Unlock() +#elif !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d0000 +static PyMutex __Pyx_ModuleStateLookup_mutex = {0}; +#define __Pyx_ModuleStateLookup_Lock() PyMutex_Lock(&__Pyx_ModuleStateLookup_mutex) +#define __Pyx_ModuleStateLookup_Unlock() PyMutex_Unlock(&__Pyx_ModuleStateLookup_mutex) +#elif defined(__cplusplus) && __cplusplus >= 201103L +#include +static std::mutex __Pyx_ModuleStateLookup_mutex; +#define __Pyx_ModuleStateLookup_Lock() __Pyx_ModuleStateLookup_mutex.lock() +#define __Pyx_ModuleStateLookup_Unlock() __Pyx_ModuleStateLookup_mutex.unlock() +#elif defined(__STDC_VERSION__) && (__STDC_VERSION__ > 201112L) && !defined(__STDC_NO_THREADS__) +#include +static mtx_t __Pyx_ModuleStateLookup_mutex; +static once_flag __Pyx_ModuleStateLookup_mutex_once_flag = ONCE_FLAG_INIT; +static void __Pyx_ModuleStateLookup_initialize_mutex(void) { + mtx_init(&__Pyx_ModuleStateLookup_mutex, mtx_plain); +} +#define __Pyx_ModuleStateLookup_Lock()\ + call_once(&__Pyx_ModuleStateLookup_mutex_once_flag, __Pyx_ModuleStateLookup_initialize_mutex);\ + mtx_lock(&__Pyx_ModuleStateLookup_mutex) +#define __Pyx_ModuleStateLookup_Unlock() mtx_unlock(&__Pyx_ModuleStateLookup_mutex) +#elif defined(HAVE_PTHREAD_H) +#include +static pthread_mutex_t __Pyx_ModuleStateLookup_mutex = PTHREAD_MUTEX_INITIALIZER; +#define __Pyx_ModuleStateLookup_Lock() pthread_mutex_lock(&__Pyx_ModuleStateLookup_mutex) +#define __Pyx_ModuleStateLookup_Unlock() pthread_mutex_unlock(&__Pyx_ModuleStateLookup_mutex) +#elif defined(_WIN32) +#include // synchapi.h on its own doesn't work +static SRWLOCK __Pyx_ModuleStateLookup_mutex = SRWLOCK_INIT; +#define __Pyx_ModuleStateLookup_Lock() AcquireSRWLockExclusive(&__Pyx_ModuleStateLookup_mutex) +#define __Pyx_ModuleStateLookup_Unlock() ReleaseSRWLockExclusive(&__Pyx_ModuleStateLookup_mutex) +#else +#error "No suitable lock available for CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE.\ + Requires C standard >= C11, or C++ standard >= C++11,\ + or pthreads, or the Windows 32 API, or Python >= 3.13." +#endif +typedef struct { + int64_t id; + PyObject *module; +} __Pyx_InterpreterIdAndModule; +typedef struct { + char interpreter_id_as_index; + Py_ssize_t count; + Py_ssize_t allocated; + __Pyx_InterpreterIdAndModule table[1]; +} __Pyx_ModuleStateLookupData; +#define __PYX_MODULE_STATE_LOOKUP_SMALL_SIZE 32 +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE +static __pyx_atomic_int_type __Pyx_ModuleStateLookup_read_counter = 0; +#endif +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE +static __pyx_atomic_ptr_type __Pyx_ModuleStateLookup_data = 0; +#else +static __Pyx_ModuleStateLookupData* __Pyx_ModuleStateLookup_data = NULL; +#endif +static __Pyx_InterpreterIdAndModule* __Pyx_State_FindModuleStateLookupTableLowerBound( + __Pyx_InterpreterIdAndModule* table, + Py_ssize_t count, + int64_t interpreterId) { + __Pyx_InterpreterIdAndModule* begin = table; + __Pyx_InterpreterIdAndModule* end = begin + count; + if (begin->id == interpreterId) { + return begin; + } + while ((end - begin) > __PYX_MODULE_STATE_LOOKUP_SMALL_SIZE) { + __Pyx_InterpreterIdAndModule* halfway = begin + (end - begin)/2; + if (halfway->id == interpreterId) { + return halfway; + } + if (halfway->id < interpreterId) { + begin = halfway; + } else { + end = halfway; + } + } + for (; begin < end; ++begin) { + if (begin->id >= interpreterId) return begin; + } + return begin; +} +static PyObject *__Pyx_State_FindModule(CYTHON_UNUSED void* dummy) { + int64_t interpreter_id = PyInterpreterState_GetID(__Pyx_PyInterpreterState_Get()); + if (interpreter_id == -1) return NULL; +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE + __Pyx_ModuleStateLookupData* data = (__Pyx_ModuleStateLookupData*)__pyx_atomic_pointer_load_relaxed(&__Pyx_ModuleStateLookup_data); + { + __pyx_atomic_incr_acq_rel(&__Pyx_ModuleStateLookup_read_counter); + if (likely(data)) { + __Pyx_ModuleStateLookupData* new_data = (__Pyx_ModuleStateLookupData*)__pyx_atomic_pointer_load_acquire(&__Pyx_ModuleStateLookup_data); + if (likely(data == new_data)) { + goto read_finished; + } + } + __pyx_atomic_decr_acq_rel(&__Pyx_ModuleStateLookup_read_counter); + __Pyx_ModuleStateLookup_Lock(); + __pyx_atomic_incr_relaxed(&__Pyx_ModuleStateLookup_read_counter); + data = (__Pyx_ModuleStateLookupData*)__pyx_atomic_pointer_load_relaxed(&__Pyx_ModuleStateLookup_data); + __Pyx_ModuleStateLookup_Unlock(); + } + read_finished:; +#else + __Pyx_ModuleStateLookupData* data = __Pyx_ModuleStateLookup_data; +#endif + __Pyx_InterpreterIdAndModule* found = NULL; + if (unlikely(!data)) goto end; + if (data->interpreter_id_as_index) { + if (interpreter_id < data->count) { + found = data->table+interpreter_id; + } + } else { + found = __Pyx_State_FindModuleStateLookupTableLowerBound( + data->table, data->count, interpreter_id); + } + end: + { + PyObject *result=NULL; + if (found && found->id == interpreter_id) { + result = found->module; + } +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE + __pyx_atomic_decr_acq_rel(&__Pyx_ModuleStateLookup_read_counter); +#endif + return result; + } +} +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE +static void __Pyx_ModuleStateLookup_wait_until_no_readers(void) { + while (__pyx_atomic_load(&__Pyx_ModuleStateLookup_read_counter) != 0); +} +#else +#define __Pyx_ModuleStateLookup_wait_until_no_readers() +#endif +static int __Pyx_State_AddModuleInterpIdAsIndex(__Pyx_ModuleStateLookupData **old_data, PyObject* module, int64_t interpreter_id) { + Py_ssize_t to_allocate = (*old_data)->allocated; + while (to_allocate <= interpreter_id) { + if (to_allocate == 0) to_allocate = 1; + else to_allocate *= 2; + } + __Pyx_ModuleStateLookupData *new_data = *old_data; + if (to_allocate != (*old_data)->allocated) { + new_data = (__Pyx_ModuleStateLookupData *)realloc( + *old_data, + sizeof(__Pyx_ModuleStateLookupData)+(to_allocate-1)*sizeof(__Pyx_InterpreterIdAndModule)); + if (!new_data) { + PyErr_NoMemory(); + return -1; + } + for (Py_ssize_t i = new_data->allocated; i < to_allocate; ++i) { + new_data->table[i].id = i; + new_data->table[i].module = NULL; + } + new_data->allocated = to_allocate; + } + new_data->table[interpreter_id].module = module; + if (new_data->count < interpreter_id+1) { + new_data->count = interpreter_id+1; + } + *old_data = new_data; + return 0; +} +static void __Pyx_State_ConvertFromInterpIdAsIndex(__Pyx_ModuleStateLookupData *data) { + __Pyx_InterpreterIdAndModule *read = data->table; + __Pyx_InterpreterIdAndModule *write = data->table; + __Pyx_InterpreterIdAndModule *end = read + data->count; + for (; readmodule) { + write->id = read->id; + write->module = read->module; + ++write; + } + } + data->count = write - data->table; + for (; writeid = 0; + write->module = NULL; + } + data->interpreter_id_as_index = 0; +} +static int __Pyx_State_AddModule(PyObject* module, CYTHON_UNUSED void* dummy) { + int64_t interpreter_id = PyInterpreterState_GetID(__Pyx_PyInterpreterState_Get()); + if (interpreter_id == -1) return -1; + int result = 0; + __Pyx_ModuleStateLookup_Lock(); +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE + __Pyx_ModuleStateLookupData *old_data = (__Pyx_ModuleStateLookupData *) + __pyx_atomic_pointer_exchange(&__Pyx_ModuleStateLookup_data, 0); +#else + __Pyx_ModuleStateLookupData *old_data = __Pyx_ModuleStateLookup_data; +#endif + __Pyx_ModuleStateLookupData *new_data = old_data; + if (!new_data) { + new_data = (__Pyx_ModuleStateLookupData *)calloc(1, sizeof(__Pyx_ModuleStateLookupData)); + if (!new_data) { + result = -1; + PyErr_NoMemory(); + goto end; + } + new_data->allocated = 1; + new_data->interpreter_id_as_index = 1; + } + __Pyx_ModuleStateLookup_wait_until_no_readers(); + if (new_data->interpreter_id_as_index) { + if (interpreter_id < __PYX_MODULE_STATE_LOOKUP_SMALL_SIZE) { + result = __Pyx_State_AddModuleInterpIdAsIndex(&new_data, module, interpreter_id); + goto end; + } + __Pyx_State_ConvertFromInterpIdAsIndex(new_data); + } + { + Py_ssize_t insert_at = 0; + { + __Pyx_InterpreterIdAndModule* lower_bound = __Pyx_State_FindModuleStateLookupTableLowerBound( + new_data->table, new_data->count, interpreter_id); + assert(lower_bound); + insert_at = lower_bound - new_data->table; + if (unlikely(insert_at < new_data->count && lower_bound->id == interpreter_id)) { + lower_bound->module = module; + goto end; // already in table, nothing more to do + } + } + if (new_data->count+1 >= new_data->allocated) { + Py_ssize_t to_allocate = (new_data->count+1)*2; + new_data = + (__Pyx_ModuleStateLookupData*)realloc( + new_data, + sizeof(__Pyx_ModuleStateLookupData) + + (to_allocate-1)*sizeof(__Pyx_InterpreterIdAndModule)); + if (!new_data) { + result = -1; + new_data = old_data; + PyErr_NoMemory(); + goto end; + } + new_data->allocated = to_allocate; + } + ++new_data->count; + int64_t last_id = interpreter_id; + PyObject *last_module = module; + for (Py_ssize_t i=insert_at; icount; ++i) { + int64_t current_id = new_data->table[i].id; + new_data->table[i].id = last_id; + last_id = current_id; + PyObject *current_module = new_data->table[i].module; + new_data->table[i].module = last_module; + last_module = current_module; + } + } + end: +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE + __pyx_atomic_pointer_exchange(&__Pyx_ModuleStateLookup_data, new_data); +#else + __Pyx_ModuleStateLookup_data = new_data; +#endif + __Pyx_ModuleStateLookup_Unlock(); + return result; +} +static int __Pyx_State_RemoveModule(CYTHON_UNUSED void* dummy) { + int64_t interpreter_id = PyInterpreterState_GetID(__Pyx_PyInterpreterState_Get()); + if (interpreter_id == -1) return -1; + __Pyx_ModuleStateLookup_Lock(); +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE + __Pyx_ModuleStateLookupData *data = (__Pyx_ModuleStateLookupData *) + __pyx_atomic_pointer_exchange(&__Pyx_ModuleStateLookup_data, 0); +#else + __Pyx_ModuleStateLookupData *data = __Pyx_ModuleStateLookup_data; +#endif + if (data->interpreter_id_as_index) { + if (interpreter_id < data->count) { + data->table[interpreter_id].module = NULL; + } + goto done; + } + { + __Pyx_ModuleStateLookup_wait_until_no_readers(); + __Pyx_InterpreterIdAndModule* lower_bound = __Pyx_State_FindModuleStateLookupTableLowerBound( + data->table, data->count, interpreter_id); + if (!lower_bound) goto done; + if (lower_bound->id != interpreter_id) goto done; + __Pyx_InterpreterIdAndModule *end = data->table+data->count; + for (;lower_boundid = (lower_bound+1)->id; + lower_bound->module = (lower_bound+1)->module; + } + } + --data->count; + if (data->count == 0) { + free(data); + data = NULL; + } + done: +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE + __pyx_atomic_pointer_exchange(&__Pyx_ModuleStateLookup_data, data); +#else + __Pyx_ModuleStateLookup_data = data; +#endif + __Pyx_ModuleStateLookup_Unlock(); + return 0; +} +#endif + +/* #### Code section: utility_code_pragmas_end ### */ +#ifdef _MSC_VER +#pragma warning( pop ) +#endif + + + +/* #### Code section: end ### */ +#endif /* Py_PYTHON_H */ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/memory/cymemory.pyx b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/memory/cymemory.pyx new file mode 100644 index 0000000000000000000000000000000000000000..7dc8ae653b67a946c7495d0bafa38380c7704e0e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/memory/cymemory.pyx @@ -0,0 +1,89 @@ +# cython: freethreading_compatible = True + +from libc.string cimport memcpy +from libc.stdlib cimport malloc, free +from thriftpy2.transport.cybase cimport ( + TCyBuffer, + CyTransportBase, + DEFAULT_BUFFER, +) + + +cdef class TCyMemoryBuffer(CyTransportBase): + cdef TCyBuffer buf + + def __init__(self, value=b'', int buf_size=DEFAULT_BUFFER): + self.trans = None + self.buf = TCyBuffer(buf_size) + + if value: + self.setvalue(value) + + cdef c_read(self, int sz, char* out): + if self.buf.data_size < sz: + sz = self.buf.data_size + + if sz <= 0: + out[0] = '\0' + else: + memcpy(out, self.buf.buf + self.buf.cur, sz) + self.buf.cur += sz + self.buf.data_size -= sz + + return sz + + cdef c_write(self, const char* data, int sz): + cdef int r = self.buf.write(sz, data) + if r == -1: + raise MemoryError("Write to memory error") + + cdef _getvalue(self): + cdef char *out + cdef int size = self.buf.data_size + + if size <= 0: + return b'' + + out = malloc(size) + try: + memcpy(out, self.buf.buf + self.buf.cur, size) + return out[:size] + finally: + free(out) + + cdef _setvalue(self, int sz, const char *value): + self.buf.clean() + self.buf.write(sz, value) + + def read(self, sz): + return self.get_string(sz) + + def write(self, data): + if isinstance(data, unicode): + data = (data).encode('utf-8') + + cdef int sz = len(data) + return self.c_write(data, sz) + + def is_open(self): + return True + + def open(self): + pass + + def close(self): + pass + + def flush(self): + pass + + def clean(self): + self.buf.clean() + + def getvalue(self): + return self._getvalue() + + def setvalue(self, value): + if isinstance(value, unicode): + value = (value).encode('utf-8') + self._setvalue(len(value), value) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/sasl/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/sasl/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3ec1c5a1a4b639017eb13f786b90941eae86f80d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/sasl/__init__.py @@ -0,0 +1,203 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# +""" SASL transports for Thrift. """ + +# Initially copied from +# https://github.com/cloudera/thrift_sasl/blob/master/thrift_sasl/__init__.py + +from __future__ import absolute_import + +import struct +from io import BytesIO + +from ..._compat import CYTHON +from ..base import TTransportBase, readall +from .. import TTransportException + + +class TSaslClientTransport(TTransportBase): + START = 1 + OK = 2 + BAD = 3 + ERROR = 4 + COMPLETE = 5 + + def __init__(self, sasl_client_factory, mechanism, trans): + """ + @param sasl_client_factory: a callable that returns a new sasl.Client object + @param mechanism: the SASL mechanism (e.g. "GSSAPI") + @param trans: the underlying transport over which to communicate. + """ + self._trans = trans + self.sasl_client_factory = sasl_client_factory + self.sasl = None + self.mechanism = mechanism + self.__wbuf = BytesIO() + self.__rbuf = BytesIO(b'') + self.encode = None + + def is_open(self): + return self._trans.is_open() + + def open(self): + if not self.is_open(): + self._trans.open() + + if self.sasl is not None: + raise TTransportException( + type=TTransportException.NOT_OPEN, + message="Already open!") + self.sasl = self.sasl_client_factory() + + ret, chosen_mech, initial_response = self.sasl.start(self.mechanism) + if not ret: + raise TTransportException(type=TTransportException.NOT_OPEN, + message=("Could not start SASL: %s" % self.sasl.getError())) + + # Send initial response + self._send_message(self.START, chosen_mech) + self._send_message(self.OK, initial_response) + + # SASL negotiation loop + while True: + status, payload = self._recv_sasl_message() + if status not in (self.OK, self.COMPLETE): + raise TTransportException(type=TTransportException.NOT_OPEN, + message=("Bad status: %d (%s)" % (status, payload))) + if status == self.COMPLETE: + break + ret, response = self.sasl.step(payload) + if not ret: + raise TTransportException(type=TTransportException.NOT_OPEN, + message=("Bad SASL result: %s" % (self.sasl.getError()))) + self._send_message(self.OK, response) + + def _send_message(self, status, body): + header = struct.pack(">BI", status, len(body)) + self._trans.write(header + body) + self._trans.flush() + + def _recv_sasl_message(self): + header = readall(self._trans.read, 5) + status, length = struct.unpack(">BI", header) + if length > 0: + payload = readall(self._trans.read, length) + else: + payload = "" + return status, payload + + def write(self, data): + self.__wbuf.write(data) + + def flush(self): + buffer = self.__wbuf.getvalue() + # The first time we flush data, we send it to sasl.encode() + # If the length doesn't change, then we must be using a QOP + # of auth and we should no longer call sasl.encode(), otherwise + # we encode every time. + if self.encode is None: + success, encoded = self.sasl.encode(buffer) + if not success: + raise TTransportException(type=TTransportException.UNKNOWN, + message=self.sasl.getError()) + if (len(encoded) == len(buffer)): + self.encode = False + self._flushPlain(buffer) + else: + self.encode = True + self._trans.write(encoded) + elif self.encode: + self._flushEncoded(buffer) + else: + self._flushPlain(buffer) + + self._trans.flush() + self.__wbuf = BytesIO() + + def _flushEncoded(self, buffer): + # sasl.ecnode() does the encoding and adds the length header, so nothing + # to do but call it and write the result. + success, encoded = self.sasl.encode(buffer) + if not success: + raise TTransportException(type=TTransportException.UNKNOWN, + message=self.sasl.getError()) + self._trans.write(encoded) + + def _flushPlain(self, buffer): + # When we have QOP of auth, sasl.encode() will pass the input to the output + # but won't put a length header, so we have to do that. + + # Note stolen from TFramedTransport: + # N.B.: Doing this string concatenation is WAY cheaper than making + # two separate calls to the underlying socket object. Socket writes in + # Python turn out to be REALLY expensive, but it seems to do a pretty + # good job of managing string buffer operations without excessive copies + self._trans.write(struct.pack(">I", len(buffer)) + buffer) + + def c_flush(self): + return self.flush() + + def read(self, sz): + ret = self.__rbuf.read(sz) + if len(ret) == sz: + return ret + + self._read_frame() + return ret + self.__rbuf.read(sz - len(ret)) + + def _read_frame(self): + header = readall(self._trans.read, 4) + (length,) = struct.unpack(">I", header) + if self.encode: + # If the frames are encoded (i.e. you're using a QOP of auth-int or + # auth-conf), then make sure to include the header in the bytes you send to + # sasl.decode() + encoded = header + readall(self._trans.read, length) + success, decoded = self.sasl.decode(encoded) + if not success: + raise TTransportException(type=TTransportException.UNKNOWN, + message=self.sasl.getError()) + else: + # If the frames are not encoded, just pass it through + decoded = readall(self._trans.read, length) + self.__rbuf = BytesIO(decoded) + + def close(self): + self._trans.close() + self.sasl = None + + # XXX: Is this actually needed? + # Implement the CReadableTransport interface. + # Stolen shamelessly from TFramedTransport + @property + def cstringio_buf(self): + return self.__rbuf + + def cstringio_refill(self, prefix, reqlen): + # self.__rbuf will already be empty here because fastbinary doesn't + # ask for a refill until the previous buffer is empty. Therefore, + # we can start reading new frames immediately. + while len(prefix) < reqlen: + self._read_frame() + prefix += self.__rbuf.getvalue() + self.__rbuf = BytesIO(prefix) + return self.__rbuf + + +if CYTHON: + from .cysasl import TCySaslClientTransport # noqa diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/sasl/cysasl.c b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/sasl/cysasl.c new file mode 100644 index 0000000000000000000000000000000000000000..5b0b156ce5f6ea87da668243888276580abc6498 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/sasl/cysasl.c @@ -0,0 +1,15317 @@ +/* Generated by Cython 3.2.4 */ + +/* BEGIN: Cython Metadata +{ + "distutils": { + "depends": [], + "name": "thriftpy2.transport.sasl.cysasl", + "sources": [ + "thriftpy2/transport/sasl/cysasl.pyx" + ] + }, + "module_name": "thriftpy2.transport.sasl.cysasl" +} +END: Cython Metadata */ + +#ifndef PY_SSIZE_T_CLEAN +#define PY_SSIZE_T_CLEAN +#endif /* PY_SSIZE_T_CLEAN */ +/* InitLimitedAPI */ +#if defined(Py_LIMITED_API) + #if !defined(CYTHON_LIMITED_API) + #define CYTHON_LIMITED_API 1 + #endif +#elif defined(CYTHON_LIMITED_API) + #ifdef _MSC_VER + #pragma message ("Limited API usage is enabled with 'CYTHON_LIMITED_API' but 'Py_LIMITED_API' does not define a Python target version. Consider setting 'Py_LIMITED_API' instead.") + #else + #warning Limited API usage is enabled with 'CYTHON_LIMITED_API' but 'Py_LIMITED_API' does not define a Python target version. Consider setting 'Py_LIMITED_API' instead. + #endif +#endif + +#include "Python.h" +#ifndef Py_PYTHON_H + #error Python headers needed to compile C extensions, please install development version of Python. +#elif PY_VERSION_HEX < 0x03080000 + #error Cython requires Python 3.8+. +#else +#define __PYX_ABI_VERSION "3_2_4" +#define CYTHON_HEX_VERSION 0x030204F0 +#define CYTHON_FUTURE_DIVISION 1 +/* CModulePreamble */ +#include +#ifndef offsetof + #define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) +#endif +#if !defined(_WIN32) && !defined(WIN32) && !defined(MS_WINDOWS) + #ifndef __stdcall + #define __stdcall + #endif + #ifndef __cdecl + #define __cdecl + #endif + #ifndef __fastcall + #define __fastcall + #endif +#endif +#ifndef DL_IMPORT + #define DL_IMPORT(t) t +#endif +#ifndef DL_EXPORT + #define DL_EXPORT(t) t +#endif +#define __PYX_COMMA , +#ifndef PY_LONG_LONG + #define PY_LONG_LONG LONG_LONG +#endif +#ifndef Py_HUGE_VAL + #define Py_HUGE_VAL HUGE_VAL +#endif +#define __PYX_LIMITED_VERSION_HEX PY_VERSION_HEX +#if defined(GRAALVM_PYTHON) + /* For very preliminary testing purposes. Most variables are set the same as PyPy. + The existence of this section does not imply that anything works or is even tested */ + #define CYTHON_COMPILING_IN_PYPY 0 + #define CYTHON_COMPILING_IN_CPYTHON 0 + #define CYTHON_COMPILING_IN_LIMITED_API 0 + #define CYTHON_COMPILING_IN_GRAAL 1 + #define CYTHON_COMPILING_IN_CPYTHON_FREETHREADING 0 + #undef CYTHON_USE_TYPE_SLOTS + #define CYTHON_USE_TYPE_SLOTS 0 + #undef CYTHON_USE_TYPE_SPECS + #define CYTHON_USE_TYPE_SPECS 0 + #undef CYTHON_USE_PYTYPE_LOOKUP + #define CYTHON_USE_PYTYPE_LOOKUP 0 + #undef CYTHON_USE_PYLIST_INTERNALS + #define CYTHON_USE_PYLIST_INTERNALS 0 + #undef CYTHON_USE_UNICODE_INTERNALS + #define CYTHON_USE_UNICODE_INTERNALS 0 + #undef CYTHON_USE_UNICODE_WRITER + #define CYTHON_USE_UNICODE_WRITER 0 + #undef CYTHON_USE_PYLONG_INTERNALS + #define CYTHON_USE_PYLONG_INTERNALS 0 + #undef CYTHON_AVOID_BORROWED_REFS + #define CYTHON_AVOID_BORROWED_REFS 1 + #undef CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + #define CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS 0 + #undef CYTHON_ASSUME_SAFE_MACROS + #define CYTHON_ASSUME_SAFE_MACROS 0 + #undef CYTHON_ASSUME_SAFE_SIZE + #define CYTHON_ASSUME_SAFE_SIZE 0 + #undef CYTHON_UNPACK_METHODS + #define CYTHON_UNPACK_METHODS 0 + #undef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 0 + #undef CYTHON_FAST_GIL + #define CYTHON_FAST_GIL 0 + #undef CYTHON_METH_FASTCALL + #define CYTHON_METH_FASTCALL 0 + #undef CYTHON_FAST_PYCALL + #define CYTHON_FAST_PYCALL 0 + #ifndef CYTHON_PEP487_INIT_SUBCLASS + #define CYTHON_PEP487_INIT_SUBCLASS 1 + #endif + #undef CYTHON_PEP489_MULTI_PHASE_INIT + #define CYTHON_PEP489_MULTI_PHASE_INIT 1 + #undef CYTHON_USE_MODULE_STATE + #define CYTHON_USE_MODULE_STATE 0 + #undef CYTHON_USE_SYS_MONITORING + #define CYTHON_USE_SYS_MONITORING 0 + #undef CYTHON_USE_TP_FINALIZE + #define CYTHON_USE_TP_FINALIZE 0 + #undef CYTHON_USE_AM_SEND + #define CYTHON_USE_AM_SEND 0 + #undef CYTHON_USE_DICT_VERSIONS + #define CYTHON_USE_DICT_VERSIONS 0 + #undef CYTHON_USE_EXC_INFO_STACK + #define CYTHON_USE_EXC_INFO_STACK 1 + #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC + #define CYTHON_UPDATE_DESCRIPTOR_DOC 0 + #endif + #undef CYTHON_USE_FREELISTS + #define CYTHON_USE_FREELISTS 0 + #undef CYTHON_IMMORTAL_CONSTANTS + #define CYTHON_IMMORTAL_CONSTANTS 0 +#elif defined(PYPY_VERSION) + #define CYTHON_COMPILING_IN_PYPY 1 + #define CYTHON_COMPILING_IN_CPYTHON 0 + #define CYTHON_COMPILING_IN_LIMITED_API 0 + #define CYTHON_COMPILING_IN_GRAAL 0 + #define CYTHON_COMPILING_IN_CPYTHON_FREETHREADING 0 + #undef CYTHON_USE_TYPE_SLOTS + #define CYTHON_USE_TYPE_SLOTS 1 + #ifndef CYTHON_USE_TYPE_SPECS + #define CYTHON_USE_TYPE_SPECS 0 + #endif + #undef CYTHON_USE_PYTYPE_LOOKUP + #define CYTHON_USE_PYTYPE_LOOKUP 0 + #undef CYTHON_USE_PYLIST_INTERNALS + #define CYTHON_USE_PYLIST_INTERNALS 0 + #undef CYTHON_USE_UNICODE_INTERNALS + #define CYTHON_USE_UNICODE_INTERNALS 0 + #undef CYTHON_USE_UNICODE_WRITER + #define CYTHON_USE_UNICODE_WRITER 0 + #undef CYTHON_USE_PYLONG_INTERNALS + #define CYTHON_USE_PYLONG_INTERNALS 0 + #undef CYTHON_AVOID_BORROWED_REFS + #define CYTHON_AVOID_BORROWED_REFS 1 + #undef CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + #define CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS 1 + #undef CYTHON_ASSUME_SAFE_MACROS + #define CYTHON_ASSUME_SAFE_MACROS 0 + #ifndef CYTHON_ASSUME_SAFE_SIZE + #define CYTHON_ASSUME_SAFE_SIZE 1 + #endif + #undef CYTHON_UNPACK_METHODS + #define CYTHON_UNPACK_METHODS 0 + #undef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 0 + #undef CYTHON_FAST_GIL + #define CYTHON_FAST_GIL 0 + #undef CYTHON_METH_FASTCALL + #define CYTHON_METH_FASTCALL 0 + #undef CYTHON_FAST_PYCALL + #define CYTHON_FAST_PYCALL 0 + #ifndef CYTHON_PEP487_INIT_SUBCLASS + #define CYTHON_PEP487_INIT_SUBCLASS 1 + #endif + #if PY_VERSION_HEX < 0x03090000 + #undef CYTHON_PEP489_MULTI_PHASE_INIT + #define CYTHON_PEP489_MULTI_PHASE_INIT 0 + #elif !defined(CYTHON_PEP489_MULTI_PHASE_INIT) + #define CYTHON_PEP489_MULTI_PHASE_INIT 1 + #endif + #undef CYTHON_USE_MODULE_STATE + #define CYTHON_USE_MODULE_STATE 0 + #undef CYTHON_USE_SYS_MONITORING + #define CYTHON_USE_SYS_MONITORING 0 + #ifndef CYTHON_USE_TP_FINALIZE + #define CYTHON_USE_TP_FINALIZE (PYPY_VERSION_NUM >= 0x07030C00) + #endif + #undef CYTHON_USE_AM_SEND + #define CYTHON_USE_AM_SEND 0 + #undef CYTHON_USE_DICT_VERSIONS + #define CYTHON_USE_DICT_VERSIONS 0 + #undef CYTHON_USE_EXC_INFO_STACK + #define CYTHON_USE_EXC_INFO_STACK 0 + #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC + #define CYTHON_UPDATE_DESCRIPTOR_DOC (PYPY_VERSION_NUM >= 0x07031100) + #endif + #undef CYTHON_USE_FREELISTS + #define CYTHON_USE_FREELISTS 0 + #undef CYTHON_IMMORTAL_CONSTANTS + #define CYTHON_IMMORTAL_CONSTANTS 0 +#elif defined(CYTHON_LIMITED_API) + #ifdef Py_LIMITED_API + #undef __PYX_LIMITED_VERSION_HEX + #define __PYX_LIMITED_VERSION_HEX Py_LIMITED_API + #endif + #define CYTHON_COMPILING_IN_PYPY 0 + #define CYTHON_COMPILING_IN_CPYTHON 0 + #define CYTHON_COMPILING_IN_LIMITED_API 1 + #define CYTHON_COMPILING_IN_GRAAL 0 + #define CYTHON_COMPILING_IN_CPYTHON_FREETHREADING 0 + #undef CYTHON_USE_TYPE_SLOTS + #define CYTHON_USE_TYPE_SLOTS 0 + #undef CYTHON_USE_TYPE_SPECS + #define CYTHON_USE_TYPE_SPECS 1 + #undef CYTHON_USE_PYTYPE_LOOKUP + #define CYTHON_USE_PYTYPE_LOOKUP 0 + #undef CYTHON_USE_PYLIST_INTERNALS + #define CYTHON_USE_PYLIST_INTERNALS 0 + #undef CYTHON_USE_UNICODE_INTERNALS + #define CYTHON_USE_UNICODE_INTERNALS 0 + #ifndef CYTHON_USE_UNICODE_WRITER + #define CYTHON_USE_UNICODE_WRITER 0 + #endif + #undef CYTHON_USE_PYLONG_INTERNALS + #define CYTHON_USE_PYLONG_INTERNALS 0 + #ifndef CYTHON_AVOID_BORROWED_REFS + #define CYTHON_AVOID_BORROWED_REFS 0 + #endif + #ifndef CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + #define CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS 0 + #endif + #undef CYTHON_ASSUME_SAFE_MACROS + #define CYTHON_ASSUME_SAFE_MACROS 0 + #undef CYTHON_ASSUME_SAFE_SIZE + #define CYTHON_ASSUME_SAFE_SIZE 0 + #undef CYTHON_UNPACK_METHODS + #define CYTHON_UNPACK_METHODS 0 + #undef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 0 + #undef CYTHON_FAST_GIL + #define CYTHON_FAST_GIL 0 + #undef CYTHON_METH_FASTCALL + #define CYTHON_METH_FASTCALL (__PYX_LIMITED_VERSION_HEX >= 0x030C0000) + #undef CYTHON_FAST_PYCALL + #define CYTHON_FAST_PYCALL 0 + #ifndef CYTHON_PEP487_INIT_SUBCLASS + #define CYTHON_PEP487_INIT_SUBCLASS 1 + #endif + #ifndef CYTHON_PEP489_MULTI_PHASE_INIT + #define CYTHON_PEP489_MULTI_PHASE_INIT 1 + #endif + #ifndef CYTHON_USE_MODULE_STATE + #define CYTHON_USE_MODULE_STATE 0 + #endif + #undef CYTHON_USE_SYS_MONITORING + #define CYTHON_USE_SYS_MONITORING 0 + #ifndef CYTHON_USE_TP_FINALIZE + #define CYTHON_USE_TP_FINALIZE 0 + #endif + #ifndef CYTHON_USE_AM_SEND + #define CYTHON_USE_AM_SEND (__PYX_LIMITED_VERSION_HEX >= 0x030A0000) + #endif + #undef CYTHON_USE_DICT_VERSIONS + #define CYTHON_USE_DICT_VERSIONS 0 + #undef CYTHON_USE_EXC_INFO_STACK + #define CYTHON_USE_EXC_INFO_STACK 0 + #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC + #define CYTHON_UPDATE_DESCRIPTOR_DOC 0 + #endif + #ifndef CYTHON_USE_FREELISTS + #define CYTHON_USE_FREELISTS 1 + #endif + #undef CYTHON_IMMORTAL_CONSTANTS + #define CYTHON_IMMORTAL_CONSTANTS 0 +#else + #define CYTHON_COMPILING_IN_PYPY 0 + #define CYTHON_COMPILING_IN_CPYTHON 1 + #define CYTHON_COMPILING_IN_LIMITED_API 0 + #define CYTHON_COMPILING_IN_GRAAL 0 + #ifdef Py_GIL_DISABLED + #define CYTHON_COMPILING_IN_CPYTHON_FREETHREADING 1 + #else + #define CYTHON_COMPILING_IN_CPYTHON_FREETHREADING 0 + #endif + #if PY_VERSION_HEX < 0x030A0000 + #undef CYTHON_USE_TYPE_SLOTS + #define CYTHON_USE_TYPE_SLOTS 1 + #elif !defined(CYTHON_USE_TYPE_SLOTS) + #define CYTHON_USE_TYPE_SLOTS 1 + #endif + #ifndef CYTHON_USE_TYPE_SPECS + #define CYTHON_USE_TYPE_SPECS 0 + #endif + #ifndef CYTHON_USE_PYTYPE_LOOKUP + #define CYTHON_USE_PYTYPE_LOOKUP 1 + #endif + #ifndef CYTHON_USE_PYLONG_INTERNALS + #define CYTHON_USE_PYLONG_INTERNALS 1 + #endif + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + #undef CYTHON_USE_PYLIST_INTERNALS + #define CYTHON_USE_PYLIST_INTERNALS 0 + #elif !defined(CYTHON_USE_PYLIST_INTERNALS) + #define CYTHON_USE_PYLIST_INTERNALS 1 + #endif + #ifndef CYTHON_USE_UNICODE_INTERNALS + #define CYTHON_USE_UNICODE_INTERNALS 1 + #endif + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING || PY_VERSION_HEX >= 0x030B00A2 + #undef CYTHON_USE_UNICODE_WRITER + #define CYTHON_USE_UNICODE_WRITER 0 + #elif !defined(CYTHON_USE_UNICODE_WRITER) + #define CYTHON_USE_UNICODE_WRITER 1 + #endif + #ifndef CYTHON_AVOID_BORROWED_REFS + #define CYTHON_AVOID_BORROWED_REFS 0 + #endif + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + #undef CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + #define CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS 1 + #elif !defined(CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS) + #define CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS 0 + #endif + #ifndef CYTHON_ASSUME_SAFE_MACROS + #define CYTHON_ASSUME_SAFE_MACROS 1 + #endif + #ifndef CYTHON_ASSUME_SAFE_SIZE + #define CYTHON_ASSUME_SAFE_SIZE 1 + #endif + #ifndef CYTHON_UNPACK_METHODS + #define CYTHON_UNPACK_METHODS 1 + #endif + #ifndef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 1 + #endif + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + #undef CYTHON_FAST_GIL + #define CYTHON_FAST_GIL 0 + #elif !defined(CYTHON_FAST_GIL) + #define CYTHON_FAST_GIL (PY_VERSION_HEX < 0x030C00A6) + #endif + #ifndef CYTHON_METH_FASTCALL + #define CYTHON_METH_FASTCALL 1 + #endif + #ifndef CYTHON_FAST_PYCALL + #define CYTHON_FAST_PYCALL 1 + #endif + #ifndef CYTHON_PEP487_INIT_SUBCLASS + #define CYTHON_PEP487_INIT_SUBCLASS 1 + #endif + #ifndef CYTHON_PEP489_MULTI_PHASE_INIT + #define CYTHON_PEP489_MULTI_PHASE_INIT 1 + #endif + #ifndef CYTHON_USE_MODULE_STATE + #define CYTHON_USE_MODULE_STATE 0 + #endif + #ifndef CYTHON_USE_SYS_MONITORING + #define CYTHON_USE_SYS_MONITORING (PY_VERSION_HEX >= 0x030d00B1) + #endif + #ifndef CYTHON_USE_TP_FINALIZE + #define CYTHON_USE_TP_FINALIZE 1 + #endif + #ifndef CYTHON_USE_AM_SEND + #define CYTHON_USE_AM_SEND 1 + #endif + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + #undef CYTHON_USE_DICT_VERSIONS + #define CYTHON_USE_DICT_VERSIONS 0 + #elif !defined(CYTHON_USE_DICT_VERSIONS) + #define CYTHON_USE_DICT_VERSIONS (PY_VERSION_HEX < 0x030C00A5 && !CYTHON_USE_MODULE_STATE) + #endif + #ifndef CYTHON_USE_EXC_INFO_STACK + #define CYTHON_USE_EXC_INFO_STACK 1 + #endif + #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC + #define CYTHON_UPDATE_DESCRIPTOR_DOC 1 + #endif + #ifndef CYTHON_USE_FREELISTS + #define CYTHON_USE_FREELISTS (!CYTHON_COMPILING_IN_CPYTHON_FREETHREADING) + #endif + #if defined(CYTHON_IMMORTAL_CONSTANTS) && PY_VERSION_HEX < 0x030C0000 + #undef CYTHON_IMMORTAL_CONSTANTS + #define CYTHON_IMMORTAL_CONSTANTS 0 // definitely won't work + #elif !defined(CYTHON_IMMORTAL_CONSTANTS) + #define CYTHON_IMMORTAL_CONSTANTS (PY_VERSION_HEX >= 0x030C0000 && !CYTHON_USE_MODULE_STATE && CYTHON_COMPILING_IN_CPYTHON_FREETHREADING) + #endif +#endif +#ifndef CYTHON_COMPRESS_STRINGS + #define CYTHON_COMPRESS_STRINGS 1 +#endif +#ifndef CYTHON_FAST_PYCCALL +#define CYTHON_FAST_PYCCALL CYTHON_FAST_PYCALL +#endif +#ifndef CYTHON_VECTORCALL +#if CYTHON_COMPILING_IN_LIMITED_API +#define CYTHON_VECTORCALL (__PYX_LIMITED_VERSION_HEX >= 0x030C0000) +#else +#define CYTHON_VECTORCALL (CYTHON_FAST_PYCCALL) +#endif +#endif +#if CYTHON_USE_PYLONG_INTERNALS + #undef SHIFT + #undef BASE + #undef MASK + #ifdef SIZEOF_VOID_P + enum { __pyx_check_sizeof_voidp = 1 / (int)(SIZEOF_VOID_P == sizeof(void*)) }; + #endif +#endif +#ifndef __has_attribute + #define __has_attribute(x) 0 +#endif +#ifndef __has_cpp_attribute + #define __has_cpp_attribute(x) 0 +#endif +#ifndef CYTHON_RESTRICT + #if defined(__GNUC__) + #define CYTHON_RESTRICT __restrict__ + #elif defined(_MSC_VER) && _MSC_VER >= 1400 + #define CYTHON_RESTRICT __restrict + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_RESTRICT restrict + #else + #define CYTHON_RESTRICT + #endif +#endif +#ifndef CYTHON_UNUSED + #if defined(__cplusplus) + /* for clang __has_cpp_attribute(maybe_unused) is true even before C++17 + * but leads to warnings with -pedantic, since it is a C++17 feature */ + #if ((defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) || __cplusplus >= 201703L) + #if __has_cpp_attribute(maybe_unused) + #define CYTHON_UNUSED [[maybe_unused]] + #endif + #endif + #endif +#endif +#ifndef CYTHON_UNUSED +# if defined(__GNUC__) +# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) +# define CYTHON_UNUSED __attribute__ ((__unused__)) +# else +# define CYTHON_UNUSED +# endif +# elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) +# define CYTHON_UNUSED __attribute__ ((__unused__)) +# else +# define CYTHON_UNUSED +# endif +#endif +#ifndef CYTHON_UNUSED_VAR +# if defined(__cplusplus) + template void CYTHON_UNUSED_VAR( const T& ) { } +# else +# define CYTHON_UNUSED_VAR(x) (void)(x) +# endif +#endif +#ifndef CYTHON_MAYBE_UNUSED_VAR + #define CYTHON_MAYBE_UNUSED_VAR(x) CYTHON_UNUSED_VAR(x) +#endif +#ifndef CYTHON_NCP_UNUSED +# if CYTHON_COMPILING_IN_CPYTHON && !CYTHON_COMPILING_IN_CPYTHON_FREETHREADING +# define CYTHON_NCP_UNUSED +# else +# define CYTHON_NCP_UNUSED CYTHON_UNUSED +# endif +#endif +#ifndef CYTHON_USE_CPP_STD_MOVE + #if defined(__cplusplus) && (\ + __cplusplus >= 201103L || (defined(_MSC_VER) && _MSC_VER >= 1600)) + #define CYTHON_USE_CPP_STD_MOVE 1 + #else + #define CYTHON_USE_CPP_STD_MOVE 0 + #endif +#endif +#define __Pyx_void_to_None(void_result) ((void)(void_result), Py_INCREF(Py_None), Py_None) +#include +typedef uintptr_t __pyx_uintptr_t; +#ifndef CYTHON_FALLTHROUGH + #if defined(__cplusplus) + /* for clang __has_cpp_attribute(fallthrough) is true even before C++17 + * but leads to warnings with -pedantic, since it is a C++17 feature */ + #if ((defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) || __cplusplus >= 201703L) + #if __has_cpp_attribute(fallthrough) + #define CYTHON_FALLTHROUGH [[fallthrough]] + #endif + #endif + #ifndef CYTHON_FALLTHROUGH + #if __has_cpp_attribute(clang::fallthrough) + #define CYTHON_FALLTHROUGH [[clang::fallthrough]] + #elif __has_cpp_attribute(gnu::fallthrough) + #define CYTHON_FALLTHROUGH [[gnu::fallthrough]] + #endif + #endif + #endif + #ifndef CYTHON_FALLTHROUGH + #if __has_attribute(fallthrough) + #define CYTHON_FALLTHROUGH __attribute__((fallthrough)) + #else + #define CYTHON_FALLTHROUGH + #endif + #endif + #if defined(__clang__) && defined(__apple_build_version__) + #if __apple_build_version__ < 7000000 + #undef CYTHON_FALLTHROUGH + #define CYTHON_FALLTHROUGH + #endif + #endif +#endif +#ifndef Py_UNREACHABLE + #define Py_UNREACHABLE() assert(0); abort() +#endif +#ifdef __cplusplus + template + struct __PYX_IS_UNSIGNED_IMPL {static const bool value = T(0) < T(-1);}; + #define __PYX_IS_UNSIGNED(type) (__PYX_IS_UNSIGNED_IMPL::value) +#else + #define __PYX_IS_UNSIGNED(type) (((type)-1) > 0) +#endif +#if CYTHON_COMPILING_IN_PYPY == 1 + #define __PYX_NEED_TP_PRINT_SLOT (PY_VERSION_HEX < 0x030A0000) +#else + #define __PYX_NEED_TP_PRINT_SLOT (PY_VERSION_HEX < 0x03090000) +#endif +#define __PYX_REINTERPRET_FUNCION(func_pointer, other_pointer) ((func_pointer)(void(*)(void))(other_pointer)) + +/* CInitCode */ +#ifndef CYTHON_INLINE + #if defined(__clang__) + #define CYTHON_INLINE __inline__ __attribute__ ((__unused__)) + #elif defined(__GNUC__) + #define CYTHON_INLINE __inline__ + #elif defined(_MSC_VER) + #define CYTHON_INLINE __inline + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_INLINE inline + #else + #define CYTHON_INLINE + #endif +#endif + +/* PythonCompatibility */ +#define __PYX_BUILD_PY_SSIZE_T "n" +#define CYTHON_FORMAT_SSIZE_T "z" +#define __Pyx_BUILTIN_MODULE_NAME "builtins" +#define __Pyx_DefaultClassType PyType_Type +#if CYTHON_COMPILING_IN_LIMITED_API + #ifndef CO_OPTIMIZED + static int CO_OPTIMIZED; + #endif + #ifndef CO_NEWLOCALS + static int CO_NEWLOCALS; + #endif + #ifndef CO_VARARGS + static int CO_VARARGS; + #endif + #ifndef CO_VARKEYWORDS + static int CO_VARKEYWORDS; + #endif + #ifndef CO_ASYNC_GENERATOR + static int CO_ASYNC_GENERATOR; + #endif + #ifndef CO_GENERATOR + static int CO_GENERATOR; + #endif + #ifndef CO_COROUTINE + static int CO_COROUTINE; + #endif +#else + #ifndef CO_COROUTINE + #define CO_COROUTINE 0x80 + #endif + #ifndef CO_ASYNC_GENERATOR + #define CO_ASYNC_GENERATOR 0x200 + #endif +#endif +static int __Pyx_init_co_variables(void); +#if PY_VERSION_HEX >= 0x030900A4 || defined(Py_IS_TYPE) + #define __Pyx_IS_TYPE(ob, type) Py_IS_TYPE(ob, type) +#else + #define __Pyx_IS_TYPE(ob, type) (((const PyObject*)ob)->ob_type == (type)) +#endif +#if PY_VERSION_HEX >= 0x030A00B1 || defined(Py_Is) + #define __Pyx_Py_Is(x, y) Py_Is(x, y) +#else + #define __Pyx_Py_Is(x, y) ((x) == (y)) +#endif +#if PY_VERSION_HEX >= 0x030A00B1 || defined(Py_IsNone) + #define __Pyx_Py_IsNone(ob) Py_IsNone(ob) +#else + #define __Pyx_Py_IsNone(ob) __Pyx_Py_Is((ob), Py_None) +#endif +#if PY_VERSION_HEX >= 0x030A00B1 || defined(Py_IsTrue) + #define __Pyx_Py_IsTrue(ob) Py_IsTrue(ob) +#else + #define __Pyx_Py_IsTrue(ob) __Pyx_Py_Is((ob), Py_True) +#endif +#if PY_VERSION_HEX >= 0x030A00B1 || defined(Py_IsFalse) + #define __Pyx_Py_IsFalse(ob) Py_IsFalse(ob) +#else + #define __Pyx_Py_IsFalse(ob) __Pyx_Py_Is((ob), Py_False) +#endif +#define __Pyx_NoneAsNull(obj) (__Pyx_Py_IsNone(obj) ? NULL : (obj)) +#if PY_VERSION_HEX >= 0x030900F0 && !CYTHON_COMPILING_IN_PYPY + #define __Pyx_PyObject_GC_IsFinalized(o) PyObject_GC_IsFinalized(o) +#else + #define __Pyx_PyObject_GC_IsFinalized(o) _PyGC_FINALIZED(o) +#endif +#ifndef Py_TPFLAGS_CHECKTYPES + #define Py_TPFLAGS_CHECKTYPES 0 +#endif +#ifndef Py_TPFLAGS_HAVE_INDEX + #define Py_TPFLAGS_HAVE_INDEX 0 +#endif +#ifndef Py_TPFLAGS_HAVE_NEWBUFFER + #define Py_TPFLAGS_HAVE_NEWBUFFER 0 +#endif +#ifndef Py_TPFLAGS_HAVE_FINALIZE + #define Py_TPFLAGS_HAVE_FINALIZE 0 +#endif +#ifndef Py_TPFLAGS_SEQUENCE + #define Py_TPFLAGS_SEQUENCE 0 +#endif +#ifndef Py_TPFLAGS_MAPPING + #define Py_TPFLAGS_MAPPING 0 +#endif +#ifndef Py_TPFLAGS_IMMUTABLETYPE + #define Py_TPFLAGS_IMMUTABLETYPE (1UL << 8) +#endif +#ifndef Py_TPFLAGS_DISALLOW_INSTANTIATION + #define Py_TPFLAGS_DISALLOW_INSTANTIATION (1UL << 7) +#endif +#ifndef METH_STACKLESS + #define METH_STACKLESS 0 +#endif +#ifndef METH_FASTCALL + #ifndef METH_FASTCALL + #define METH_FASTCALL 0x80 + #endif + typedef PyObject *(*__Pyx_PyCFunctionFast) (PyObject *self, PyObject *const *args, Py_ssize_t nargs); + typedef PyObject *(*__Pyx_PyCFunctionFastWithKeywords) (PyObject *self, PyObject *const *args, + Py_ssize_t nargs, PyObject *kwnames); +#else + #if PY_VERSION_HEX >= 0x030d00A4 + # define __Pyx_PyCFunctionFast PyCFunctionFast + # define __Pyx_PyCFunctionFastWithKeywords PyCFunctionFastWithKeywords + #else + # define __Pyx_PyCFunctionFast _PyCFunctionFast + # define __Pyx_PyCFunctionFastWithKeywords _PyCFunctionFastWithKeywords + #endif +#endif +#if CYTHON_METH_FASTCALL + #define __Pyx_METH_FASTCALL METH_FASTCALL + #define __Pyx_PyCFunction_FastCall __Pyx_PyCFunctionFast + #define __Pyx_PyCFunction_FastCallWithKeywords __Pyx_PyCFunctionFastWithKeywords +#else + #define __Pyx_METH_FASTCALL METH_VARARGS + #define __Pyx_PyCFunction_FastCall PyCFunction + #define __Pyx_PyCFunction_FastCallWithKeywords PyCFunctionWithKeywords +#endif +#if CYTHON_VECTORCALL + #define __pyx_vectorcallfunc vectorcallfunc + #define __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET PY_VECTORCALL_ARGUMENTS_OFFSET + #define __Pyx_PyVectorcall_NARGS(n) PyVectorcall_NARGS((size_t)(n)) +#else + #define __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET 0 + #define __Pyx_PyVectorcall_NARGS(n) ((Py_ssize_t)(n)) +#endif +#if PY_VERSION_HEX >= 0x030900B1 +#define __Pyx_PyCFunction_CheckExact(func) PyCFunction_CheckExact(func) +#else +#define __Pyx_PyCFunction_CheckExact(func) PyCFunction_Check(func) +#endif +#define __Pyx_CyOrPyCFunction_Check(func) PyCFunction_Check(func) +#if CYTHON_COMPILING_IN_CPYTHON +#define __Pyx_CyOrPyCFunction_GET_FUNCTION(func) (((PyCFunctionObject*)(func))->m_ml->ml_meth) +#elif !CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_CyOrPyCFunction_GET_FUNCTION(func) PyCFunction_GET_FUNCTION(func) +#endif +#if CYTHON_COMPILING_IN_CPYTHON +#define __Pyx_CyOrPyCFunction_GET_FLAGS(func) (((PyCFunctionObject*)(func))->m_ml->ml_flags) +static CYTHON_INLINE PyObject* __Pyx_CyOrPyCFunction_GET_SELF(PyObject *func) { + return (__Pyx_CyOrPyCFunction_GET_FLAGS(func) & METH_STATIC) ? NULL : ((PyCFunctionObject*)func)->m_self; +} +#endif +static CYTHON_INLINE int __Pyx__IsSameCFunction(PyObject *func, void (*cfunc)(void)) { +#if CYTHON_COMPILING_IN_LIMITED_API + return PyCFunction_Check(func) && PyCFunction_GetFunction(func) == (PyCFunction) cfunc; +#else + return PyCFunction_Check(func) && PyCFunction_GET_FUNCTION(func) == (PyCFunction) cfunc; +#endif +} +#define __Pyx_IsSameCFunction(func, cfunc) __Pyx__IsSameCFunction(func, cfunc) +#if PY_VERSION_HEX < 0x03090000 || (CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000) + #define __Pyx_PyType_FromModuleAndSpec(m, s, b) ((void)m, PyType_FromSpecWithBases(s, b)) + typedef PyObject *(*__Pyx_PyCMethod)(PyObject *, PyTypeObject *, PyObject *const *, size_t, PyObject *); +#else + #define __Pyx_PyType_FromModuleAndSpec(m, s, b) PyType_FromModuleAndSpec(m, s, b) + #define __Pyx_PyCMethod PyCMethod +#endif +#ifndef METH_METHOD + #define METH_METHOD 0x200 +#endif +#if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Malloc) + #define PyObject_Malloc(s) PyMem_Malloc(s) + #define PyObject_Free(p) PyMem_Free(p) + #define PyObject_Realloc(p) PyMem_Realloc(p) +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + #define __Pyx_PyFrame_SetLineNumber(frame, lineno) +#elif CYTHON_COMPILING_IN_GRAAL && defined(GRAALPY_VERSION_NUM) && GRAALPY_VERSION_NUM > 0x19000000 + #define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0) + #define __Pyx_PyFrame_SetLineNumber(frame, lineno) GraalPyFrame_SetLineNumber((frame), (lineno)) +#elif CYTHON_COMPILING_IN_GRAAL + #define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0) + #define __Pyx_PyFrame_SetLineNumber(frame, lineno) _PyFrame_SetLineNumber((frame), (lineno)) +#else + #define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0) + #define __Pyx_PyFrame_SetLineNumber(frame, lineno) (frame)->f_lineno = (lineno) +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + #define __Pyx_PyThreadState_Current PyThreadState_Get() +#elif !CYTHON_FAST_THREAD_STATE + #define __Pyx_PyThreadState_Current PyThreadState_GET() +#elif PY_VERSION_HEX >= 0x030d00A1 + #define __Pyx_PyThreadState_Current PyThreadState_GetUnchecked() +#else + #define __Pyx_PyThreadState_Current _PyThreadState_UncheckedGet() +#endif +#if CYTHON_USE_MODULE_STATE +static CYTHON_INLINE void *__Pyx__PyModule_GetState(PyObject *op) +{ + void *result; + result = PyModule_GetState(op); + if (!result) + Py_FatalError("Couldn't find the module state"); + return result; +} +#define __Pyx_PyModule_GetState(o) (__pyx_mstatetype *)__Pyx__PyModule_GetState(o) +#else +#define __Pyx_PyModule_GetState(op) ((void)op,__pyx_mstate_global) +#endif +#define __Pyx_PyObject_GetSlot(obj, name, func_ctype) __Pyx_PyType_GetSlot(Py_TYPE((PyObject *) obj), name, func_ctype) +#define __Pyx_PyObject_TryGetSlot(obj, name, func_ctype) __Pyx_PyType_TryGetSlot(Py_TYPE(obj), name, func_ctype) +#define __Pyx_PyObject_GetSubSlot(obj, sub, name, func_ctype) __Pyx_PyType_GetSubSlot(Py_TYPE(obj), sub, name, func_ctype) +#define __Pyx_PyObject_TryGetSubSlot(obj, sub, name, func_ctype) __Pyx_PyType_TryGetSubSlot(Py_TYPE(obj), sub, name, func_ctype) +#if CYTHON_USE_TYPE_SLOTS + #define __Pyx_PyType_GetSlot(type, name, func_ctype) ((type)->name) + #define __Pyx_PyType_TryGetSlot(type, name, func_ctype) __Pyx_PyType_GetSlot(type, name, func_ctype) + #define __Pyx_PyType_GetSubSlot(type, sub, name, func_ctype) (((type)->sub) ? ((type)->sub->name) : NULL) + #define __Pyx_PyType_TryGetSubSlot(type, sub, name, func_ctype) __Pyx_PyType_GetSubSlot(type, sub, name, func_ctype) +#else + #define __Pyx_PyType_GetSlot(type, name, func_ctype) ((func_ctype) PyType_GetSlot((type), Py_##name)) + #define __Pyx_PyType_TryGetSlot(type, name, func_ctype)\ + ((__PYX_LIMITED_VERSION_HEX >= 0x030A0000 ||\ + (PyType_GetFlags(type) & Py_TPFLAGS_HEAPTYPE) || __Pyx_get_runtime_version() >= 0x030A0000) ?\ + __Pyx_PyType_GetSlot(type, name, func_ctype) : NULL) + #define __Pyx_PyType_GetSubSlot(obj, sub, name, func_ctype) __Pyx_PyType_GetSlot(obj, name, func_ctype) + #define __Pyx_PyType_TryGetSubSlot(obj, sub, name, func_ctype) __Pyx_PyType_TryGetSlot(obj, name, func_ctype) +#endif +#if CYTHON_COMPILING_IN_CPYTHON || defined(_PyDict_NewPresized) +#define __Pyx_PyDict_NewPresized(n) ((n <= 8) ? PyDict_New() : _PyDict_NewPresized(n)) +#else +#define __Pyx_PyDict_NewPresized(n) PyDict_New() +#endif +#define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) +#define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) +#if CYTHON_COMPILING_IN_CPYTHON && CYTHON_USE_UNICODE_INTERNALS +#define __Pyx_PyDict_GetItemStrWithError(dict, name) _PyDict_GetItem_KnownHash(dict, name, ((PyASCIIObject *) name)->hash) +static CYTHON_INLINE PyObject * __Pyx_PyDict_GetItemStr(PyObject *dict, PyObject *name) { + PyObject *res = __Pyx_PyDict_GetItemStrWithError(dict, name); + if (res == NULL) PyErr_Clear(); + return res; +} +#elif !CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07020000 +#define __Pyx_PyDict_GetItemStrWithError PyDict_GetItemWithError +#define __Pyx_PyDict_GetItemStr PyDict_GetItem +#else +static CYTHON_INLINE PyObject * __Pyx_PyDict_GetItemStrWithError(PyObject *dict, PyObject *name) { +#if CYTHON_COMPILING_IN_PYPY + return PyDict_GetItem(dict, name); +#else + PyDictEntry *ep; + PyDictObject *mp = (PyDictObject*) dict; + long hash = ((PyStringObject *) name)->ob_shash; + assert(hash != -1); + ep = (mp->ma_lookup)(mp, name, hash); + if (ep == NULL) { + return NULL; + } + return ep->me_value; +#endif +} +#define __Pyx_PyDict_GetItemStr PyDict_GetItem +#endif +#if CYTHON_USE_TYPE_SLOTS + #define __Pyx_PyType_GetFlags(tp) (((PyTypeObject *)tp)->tp_flags) + #define __Pyx_PyType_HasFeature(type, feature) ((__Pyx_PyType_GetFlags(type) & (feature)) != 0) +#else + #define __Pyx_PyType_GetFlags(tp) (PyType_GetFlags((PyTypeObject *)tp)) + #define __Pyx_PyType_HasFeature(type, feature) PyType_HasFeature(type, feature) +#endif +#define __Pyx_PyObject_GetIterNextFunc(iterator) __Pyx_PyObject_GetSlot(iterator, tp_iternext, iternextfunc) +#if CYTHON_USE_TYPE_SPECS +#define __Pyx_PyHeapTypeObject_GC_Del(obj) {\ + PyTypeObject *type = Py_TYPE((PyObject*)obj);\ + assert(__Pyx_PyType_HasFeature(type, Py_TPFLAGS_HEAPTYPE));\ + PyObject_GC_Del(obj);\ + Py_DECREF(type);\ +} +#else +#define __Pyx_PyHeapTypeObject_GC_Del(obj) PyObject_GC_Del(obj) +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + #define __Pyx_PyUnicode_READY(op) (0) + #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_ReadChar(u, i) + #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) ((void)u, 1114111U) + #define __Pyx_PyUnicode_KIND(u) ((void)u, (0)) + #define __Pyx_PyUnicode_DATA(u) ((void*)u) + #define __Pyx_PyUnicode_READ(k, d, i) ((void)k, PyUnicode_ReadChar((PyObject*)(d), i)) + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GetLength(u)) +#else + #if PY_VERSION_HEX >= 0x030C0000 + #define __Pyx_PyUnicode_READY(op) (0) + #else + #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ?\ + 0 : _PyUnicode_Ready((PyObject *)(op))) + #endif + #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) + #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) PyUnicode_MAX_CHAR_VALUE(u) + #define __Pyx_PyUnicode_KIND(u) ((int)PyUnicode_KIND(u)) + #define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u) + #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) + #define __Pyx_PyUnicode_WRITE(k, d, i, ch) PyUnicode_WRITE(k, d, i, (Py_UCS4) ch) + #if PY_VERSION_HEX >= 0x030C0000 + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_LENGTH(u)) + #else + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x03090000 + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : ((PyCompactUnicodeObject *)(u))->wstr_length)) + #else + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : PyUnicode_GET_SIZE(u))) + #endif + #endif +#endif +#if CYTHON_COMPILING_IN_PYPY + #define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b) +#else + #define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ?\ + PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b)) +#endif +#if CYTHON_COMPILING_IN_PYPY + #if !defined(PyUnicode_DecodeUnicodeEscape) + #define PyUnicode_DecodeUnicodeEscape(s, size, errors) PyUnicode_Decode(s, size, "unicode_escape", errors) + #endif + #if !defined(PyUnicode_Contains) + #define PyUnicode_Contains(u, s) PySequence_Contains(u, s) + #endif + #if !defined(PyByteArray_Check) + #define PyByteArray_Check(obj) PyObject_TypeCheck(obj, &PyByteArray_Type) + #endif + #if !defined(PyObject_Format) + #define PyObject_Format(obj, fmt) PyObject_CallMethod(obj, "__format__", "O", fmt) + #endif +#endif +#define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None || (PyUnicode_Check(b) && !PyUnicode_CheckExact(b)))) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + #define __Pyx_PySequence_ListKeepNew(obj)\ + (likely(PyList_CheckExact(obj) && PyUnstable_Object_IsUniquelyReferenced(obj)) ? __Pyx_NewRef(obj) : PySequence_List(obj)) +#elif CYTHON_COMPILING_IN_CPYTHON + #define __Pyx_PySequence_ListKeepNew(obj)\ + (likely(PyList_CheckExact(obj) && Py_REFCNT(obj) == 1) ? __Pyx_NewRef(obj) : PySequence_List(obj)) +#else + #define __Pyx_PySequence_ListKeepNew(obj) PySequence_List(obj) +#endif +#ifndef PySet_CheckExact + #define PySet_CheckExact(obj) __Pyx_IS_TYPE(obj, &PySet_Type) +#endif +#if PY_VERSION_HEX >= 0x030900A4 + #define __Pyx_SET_REFCNT(obj, refcnt) Py_SET_REFCNT(obj, refcnt) + #define __Pyx_SET_SIZE(obj, size) Py_SET_SIZE(obj, size) +#else + #define __Pyx_SET_REFCNT(obj, refcnt) Py_REFCNT(obj) = (refcnt) + #define __Pyx_SET_SIZE(obj, size) Py_SIZE(obj) = (size) +#endif +enum __Pyx_ReferenceSharing { + __Pyx_ReferenceSharing_DefinitelyUnique, // We created it so we know it's unshared - no need to check + __Pyx_ReferenceSharing_OwnStrongReference, + __Pyx_ReferenceSharing_FunctionArgument, + __Pyx_ReferenceSharing_SharedReference, // Never trust it to be unshared because it's a global or similar +}; +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING && PY_VERSION_HEX >= 0x030E0000 +#define __Pyx_IS_UNIQUELY_REFERENCED(o, sharing)\ + (sharing == __Pyx_ReferenceSharing_DefinitelyUnique ? 1 :\ + (sharing == __Pyx_ReferenceSharing_FunctionArgument ? PyUnstable_Object_IsUniqueReferencedTemporary(o) :\ + (sharing == __Pyx_ReferenceSharing_OwnStrongReference ? PyUnstable_Object_IsUniquelyReferenced(o) : 0))) +#elif (CYTHON_COMPILING_IN_CPYTHON && !CYTHON_COMPILING_IN_CPYTHON_FREETHREADING) || CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_IS_UNIQUELY_REFERENCED(o, sharing) (((void)sharing), Py_REFCNT(o) == 1) +#else +#define __Pyx_IS_UNIQUELY_REFERENCED(o, sharing) (((void)o), ((void)sharing), 0) +#endif +#if CYTHON_AVOID_BORROWED_REFS || CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + #if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + #define __Pyx_PyList_GetItemRef(o, i) PyList_GetItemRef(o, i) + #elif CYTHON_COMPILING_IN_LIMITED_API || !CYTHON_ASSUME_SAFE_MACROS + #define __Pyx_PyList_GetItemRef(o, i) (likely((i) >= 0) ? PySequence_GetItem(o, i) : (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL)) + #else + #define __Pyx_PyList_GetItemRef(o, i) PySequence_ITEM(o, i) + #endif +#elif CYTHON_COMPILING_IN_LIMITED_API || !CYTHON_ASSUME_SAFE_MACROS + #if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + #define __Pyx_PyList_GetItemRef(o, i) PyList_GetItemRef(o, i) + #else + #define __Pyx_PyList_GetItemRef(o, i) __Pyx_XNewRef(PyList_GetItem(o, i)) + #endif +#else + #define __Pyx_PyList_GetItemRef(o, i) __Pyx_NewRef(PyList_GET_ITEM(o, i)) +#endif +#if CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS && !CYTHON_COMPILING_IN_LIMITED_API && CYTHON_ASSUME_SAFE_MACROS + #define __Pyx_PyList_GetItemRefFast(o, i, unsafe_shared) (__Pyx_IS_UNIQUELY_REFERENCED(o, unsafe_shared) ?\ + __Pyx_NewRef(PyList_GET_ITEM(o, i)) : __Pyx_PyList_GetItemRef(o, i)) +#else + #define __Pyx_PyList_GetItemRefFast(o, i, unsafe_shared) __Pyx_PyList_GetItemRef(o, i) +#endif +#if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 +#define __Pyx_PyDict_GetItemRef(dict, key, result) PyDict_GetItemRef(dict, key, result) +#elif CYTHON_AVOID_BORROWED_REFS || CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS +static CYTHON_INLINE int __Pyx_PyDict_GetItemRef(PyObject *dict, PyObject *key, PyObject **result) { + *result = PyObject_GetItem(dict, key); + if (*result == NULL) { + if (PyErr_ExceptionMatches(PyExc_KeyError)) { + PyErr_Clear(); + return 0; + } + return -1; + } + return 1; +} +#else +static CYTHON_INLINE int __Pyx_PyDict_GetItemRef(PyObject *dict, PyObject *key, PyObject **result) { + *result = PyDict_GetItemWithError(dict, key); + if (*result == NULL) { + return PyErr_Occurred() ? -1 : 0; + } + Py_INCREF(*result); + return 1; +} +#endif +#if defined(CYTHON_DEBUG_VISIT_CONST) && CYTHON_DEBUG_VISIT_CONST + #define __Pyx_VISIT_CONST(obj) Py_VISIT(obj) +#else + #define __Pyx_VISIT_CONST(obj) +#endif +#if CYTHON_ASSUME_SAFE_MACROS + #define __Pyx_PySequence_ITEM(o, i) PySequence_ITEM(o, i) + #define __Pyx_PySequence_SIZE(seq) Py_SIZE(seq) + #define __Pyx_PyTuple_SET_ITEM(o, i, v) (PyTuple_SET_ITEM(o, i, v), (0)) + #define __Pyx_PyTuple_GET_ITEM(o, i) PyTuple_GET_ITEM(o, i) + #define __Pyx_PyList_SET_ITEM(o, i, v) (PyList_SET_ITEM(o, i, v), (0)) + #define __Pyx_PyList_GET_ITEM(o, i) PyList_GET_ITEM(o, i) +#else + #define __Pyx_PySequence_ITEM(o, i) PySequence_GetItem(o, i) + #define __Pyx_PySequence_SIZE(seq) PySequence_Size(seq) + #define __Pyx_PyTuple_SET_ITEM(o, i, v) PyTuple_SetItem(o, i, v) + #define __Pyx_PyTuple_GET_ITEM(o, i) PyTuple_GetItem(o, i) + #define __Pyx_PyList_SET_ITEM(o, i, v) PyList_SetItem(o, i, v) + #define __Pyx_PyList_GET_ITEM(o, i) PyList_GetItem(o, i) +#endif +#if CYTHON_ASSUME_SAFE_SIZE + #define __Pyx_PyTuple_GET_SIZE(o) PyTuple_GET_SIZE(o) + #define __Pyx_PyList_GET_SIZE(o) PyList_GET_SIZE(o) + #define __Pyx_PySet_GET_SIZE(o) PySet_GET_SIZE(o) + #define __Pyx_PyBytes_GET_SIZE(o) PyBytes_GET_SIZE(o) + #define __Pyx_PyByteArray_GET_SIZE(o) PyByteArray_GET_SIZE(o) + #define __Pyx_PyUnicode_GET_LENGTH(o) PyUnicode_GET_LENGTH(o) +#else + #define __Pyx_PyTuple_GET_SIZE(o) PyTuple_Size(o) + #define __Pyx_PyList_GET_SIZE(o) PyList_Size(o) + #define __Pyx_PySet_GET_SIZE(o) PySet_Size(o) + #define __Pyx_PyBytes_GET_SIZE(o) PyBytes_Size(o) + #define __Pyx_PyByteArray_GET_SIZE(o) PyByteArray_Size(o) + #define __Pyx_PyUnicode_GET_LENGTH(o) PyUnicode_GetLength(o) +#endif +#if CYTHON_COMPILING_IN_PYPY && !defined(PyUnicode_InternFromString) + #define PyUnicode_InternFromString(s) PyUnicode_FromString(s) +#endif +#define __Pyx_PyLong_FromHash_t PyLong_FromSsize_t +#define __Pyx_PyLong_AsHash_t __Pyx_PyIndex_AsSsize_t +#if __PYX_LIMITED_VERSION_HEX >= 0x030A0000 + #define __Pyx_PySendResult PySendResult +#else + typedef enum { + PYGEN_RETURN = 0, + PYGEN_ERROR = -1, + PYGEN_NEXT = 1, + } __Pyx_PySendResult; +#endif +#if CYTHON_COMPILING_IN_LIMITED_API || PY_VERSION_HEX < 0x030A00A3 + typedef __Pyx_PySendResult (*__Pyx_pyiter_sendfunc)(PyObject *iter, PyObject *value, PyObject **result); +#else + #define __Pyx_pyiter_sendfunc sendfunc +#endif +#if !CYTHON_USE_AM_SEND +#define __PYX_HAS_PY_AM_SEND 0 +#elif __PYX_LIMITED_VERSION_HEX >= 0x030A0000 +#define __PYX_HAS_PY_AM_SEND 1 +#else +#define __PYX_HAS_PY_AM_SEND 2 // our own backported implementation +#endif +#if __PYX_HAS_PY_AM_SEND < 2 + #define __Pyx_PyAsyncMethodsStruct PyAsyncMethods +#else + typedef struct { + unaryfunc am_await; + unaryfunc am_aiter; + unaryfunc am_anext; + __Pyx_pyiter_sendfunc am_send; + } __Pyx_PyAsyncMethodsStruct; + #define __Pyx_SlotTpAsAsync(s) ((PyAsyncMethods*)(s)) +#endif +#if CYTHON_USE_AM_SEND && PY_VERSION_HEX < 0x030A00F0 + #define __Pyx_TPFLAGS_HAVE_AM_SEND (1UL << 21) +#else + #define __Pyx_TPFLAGS_HAVE_AM_SEND (0) +#endif +#if PY_VERSION_HEX >= 0x03090000 +#define __Pyx_PyInterpreterState_Get() PyInterpreterState_Get() +#else +#define __Pyx_PyInterpreterState_Get() PyThreadState_Get()->interp +#endif +#if CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030A0000 +#ifdef __cplusplus +extern "C" +#endif +PyAPI_FUNC(void *) PyMem_Calloc(size_t nelem, size_t elsize); +#endif +#if CYTHON_COMPILING_IN_LIMITED_API +static int __Pyx_init_co_variable(PyObject *inspect, const char* name, int *write_to) { + int value; + PyObject *py_value = PyObject_GetAttrString(inspect, name); + if (!py_value) return 0; + value = (int) PyLong_AsLong(py_value); + Py_DECREF(py_value); + *write_to = value; + return value != -1 || !PyErr_Occurred(); +} +static int __Pyx_init_co_variables(void) { + PyObject *inspect; + int result; + inspect = PyImport_ImportModule("inspect"); + result = +#if !defined(CO_OPTIMIZED) + __Pyx_init_co_variable(inspect, "CO_OPTIMIZED", &CO_OPTIMIZED) && +#endif +#if !defined(CO_NEWLOCALS) + __Pyx_init_co_variable(inspect, "CO_NEWLOCALS", &CO_NEWLOCALS) && +#endif +#if !defined(CO_VARARGS) + __Pyx_init_co_variable(inspect, "CO_VARARGS", &CO_VARARGS) && +#endif +#if !defined(CO_VARKEYWORDS) + __Pyx_init_co_variable(inspect, "CO_VARKEYWORDS", &CO_VARKEYWORDS) && +#endif +#if !defined(CO_ASYNC_GENERATOR) + __Pyx_init_co_variable(inspect, "CO_ASYNC_GENERATOR", &CO_ASYNC_GENERATOR) && +#endif +#if !defined(CO_GENERATOR) + __Pyx_init_co_variable(inspect, "CO_GENERATOR", &CO_GENERATOR) && +#endif +#if !defined(CO_COROUTINE) + __Pyx_init_co_variable(inspect, "CO_COROUTINE", &CO_COROUTINE) && +#endif + 1; + Py_DECREF(inspect); + return result ? 0 : -1; +} +#else +static int __Pyx_init_co_variables(void) { + return 0; // It's a limited API-only feature +} +#endif + +/* MathInitCode */ +#if defined(_WIN32) || defined(WIN32) || defined(MS_WINDOWS) + #ifndef _USE_MATH_DEFINES + #define _USE_MATH_DEFINES + #endif +#endif +#include +#if defined(__CYGWIN__) && defined(_LDBL_EQ_DBL) +#define __Pyx_truncl trunc +#else +#define __Pyx_truncl truncl +#endif + +#ifndef CYTHON_CLINE_IN_TRACEBACK_RUNTIME +#define CYTHON_CLINE_IN_TRACEBACK_RUNTIME 0 +#endif +#ifndef CYTHON_CLINE_IN_TRACEBACK +#define CYTHON_CLINE_IN_TRACEBACK CYTHON_CLINE_IN_TRACEBACK_RUNTIME +#endif +#if CYTHON_CLINE_IN_TRACEBACK +#define __PYX_MARK_ERR_POS(f_index, lineno) { __pyx_filename = __pyx_f[f_index]; (void) __pyx_filename; __pyx_lineno = lineno; (void) __pyx_lineno; __pyx_clineno = __LINE__; (void) __pyx_clineno; } +#else +#define __PYX_MARK_ERR_POS(f_index, lineno) { __pyx_filename = __pyx_f[f_index]; (void) __pyx_filename; __pyx_lineno = lineno; (void) __pyx_lineno; (void) __pyx_clineno; } +#endif +#define __PYX_ERR(f_index, lineno, Ln_error) \ + { __PYX_MARK_ERR_POS(f_index, lineno) goto Ln_error; } + +#ifdef CYTHON_EXTERN_C + #undef __PYX_EXTERN_C + #define __PYX_EXTERN_C CYTHON_EXTERN_C +#elif defined(__PYX_EXTERN_C) + #ifdef _MSC_VER + #pragma message ("Please do not define the '__PYX_EXTERN_C' macro externally. Use 'CYTHON_EXTERN_C' instead.") + #else + #warning Please do not define the '__PYX_EXTERN_C' macro externally. Use 'CYTHON_EXTERN_C' instead. + #endif +#else + #ifdef __cplusplus + #define __PYX_EXTERN_C extern "C" + #else + #define __PYX_EXTERN_C extern + #endif +#endif + +#define __PYX_HAVE__thriftpy2__transport__sasl__cysasl +#define __PYX_HAVE_API__thriftpy2__transport__sasl__cysasl +/* Early includes */ +#include +#ifdef _OPENMP +#include +#endif /* _OPENMP */ + +#if defined(PYREX_WITHOUT_ASSERTIONS) && !defined(CYTHON_WITHOUT_ASSERTIONS) +#define CYTHON_WITHOUT_ASSERTIONS +#endif + +#ifdef CYTHON_FREETHREADING_COMPATIBLE +#if CYTHON_FREETHREADING_COMPATIBLE +#define __Pyx_FREETHREADING_COMPATIBLE Py_MOD_GIL_NOT_USED +#else +#define __Pyx_FREETHREADING_COMPATIBLE Py_MOD_GIL_USED +#endif +#else +#define __Pyx_FREETHREADING_COMPATIBLE Py_MOD_GIL_NOT_USED +#endif +#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 +#define __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 0 +#define __PYX_DEFAULT_STRING_ENCODING "" +#define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString +#define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#define __Pyx_uchar_cast(c) ((unsigned char)c) +#define __Pyx_long_cast(x) ((long)x) +#define __Pyx_fits_Py_ssize_t(v, type, is_signed) (\ + (sizeof(type) < sizeof(Py_ssize_t)) ||\ + (sizeof(type) > sizeof(Py_ssize_t) &&\ + likely(v < (type)PY_SSIZE_T_MAX ||\ + v == (type)PY_SSIZE_T_MAX) &&\ + (!is_signed || likely(v > (type)PY_SSIZE_T_MIN ||\ + v == (type)PY_SSIZE_T_MIN))) ||\ + (sizeof(type) == sizeof(Py_ssize_t) &&\ + (is_signed || likely(v < (type)PY_SSIZE_T_MAX ||\ + v == (type)PY_SSIZE_T_MAX))) ) +static CYTHON_INLINE int __Pyx_is_valid_index(Py_ssize_t i, Py_ssize_t limit) { + return (size_t) i < (size_t) limit; +} +#if defined (__cplusplus) && __cplusplus >= 201103L + #include + #define __Pyx_sst_abs(value) std::abs(value) +#elif SIZEOF_INT >= SIZEOF_SIZE_T + #define __Pyx_sst_abs(value) abs(value) +#elif SIZEOF_LONG >= SIZEOF_SIZE_T + #define __Pyx_sst_abs(value) labs(value) +#elif defined (_MSC_VER) + #define __Pyx_sst_abs(value) ((Py_ssize_t)_abs64(value)) +#elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define __Pyx_sst_abs(value) llabs(value) +#elif defined (__GNUC__) + #define __Pyx_sst_abs(value) __builtin_llabs(value) +#else + #define __Pyx_sst_abs(value) ((value<0) ? -value : value) +#endif +static CYTHON_INLINE Py_ssize_t __Pyx_ssize_strlen(const char *s); +static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject*); +static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); +static CYTHON_INLINE PyObject* __Pyx_PyByteArray_FromString(const char*); +#define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l) +#define __Pyx_PyBytes_FromString PyBytes_FromString +#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char*); +#if CYTHON_ASSUME_SAFE_MACROS + #define __Pyx_PyBytes_AsWritableString(s) ((char*) PyBytes_AS_STRING(s)) + #define __Pyx_PyBytes_AsWritableSString(s) ((signed char*) PyBytes_AS_STRING(s)) + #define __Pyx_PyBytes_AsWritableUString(s) ((unsigned char*) PyBytes_AS_STRING(s)) + #define __Pyx_PyBytes_AsString(s) ((const char*) PyBytes_AS_STRING(s)) + #define __Pyx_PyBytes_AsSString(s) ((const signed char*) PyBytes_AS_STRING(s)) + #define __Pyx_PyBytes_AsUString(s) ((const unsigned char*) PyBytes_AS_STRING(s)) + #define __Pyx_PyByteArray_AsString(s) PyByteArray_AS_STRING(s) +#else + #define __Pyx_PyBytes_AsWritableString(s) ((char*) PyBytes_AsString(s)) + #define __Pyx_PyBytes_AsWritableSString(s) ((signed char*) PyBytes_AsString(s)) + #define __Pyx_PyBytes_AsWritableUString(s) ((unsigned char*) PyBytes_AsString(s)) + #define __Pyx_PyBytes_AsString(s) ((const char*) PyBytes_AsString(s)) + #define __Pyx_PyBytes_AsSString(s) ((const signed char*) PyBytes_AsString(s)) + #define __Pyx_PyBytes_AsUString(s) ((const unsigned char*) PyBytes_AsString(s)) + #define __Pyx_PyByteArray_AsString(s) PyByteArray_AsString(s) +#endif +#define __Pyx_PyObject_AsWritableString(s) ((char*)(__pyx_uintptr_t) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsWritableSString(s) ((signed char*)(__pyx_uintptr_t) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsWritableUString(s) ((unsigned char*)(__pyx_uintptr_t) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsSString(s) ((const signed char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsUString(s) ((const unsigned char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_FromCString(s) __Pyx_PyObject_FromString((const char*)s) +#define __Pyx_PyBytes_FromCString(s) __Pyx_PyBytes_FromString((const char*)s) +#define __Pyx_PyByteArray_FromCString(s) __Pyx_PyByteArray_FromString((const char*)s) +#define __Pyx_PyUnicode_FromCString(s) __Pyx_PyUnicode_FromString((const char*)s) +#define __Pyx_PyUnicode_FromOrdinal(o) PyUnicode_FromOrdinal((int)o) +#define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode +static CYTHON_INLINE PyObject *__Pyx_NewRef(PyObject *obj) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030a0000 || defined(Py_NewRef) + return Py_NewRef(obj); +#else + Py_INCREF(obj); + return obj; +#endif +} +static CYTHON_INLINE PyObject *__Pyx_XNewRef(PyObject *obj) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030a0000 || defined(Py_XNewRef) + return Py_XNewRef(obj); +#else + Py_XINCREF(obj); + return obj; +#endif +} +static CYTHON_INLINE PyObject *__Pyx_Owned_Py_None(int b); +static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b); +static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); +static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject*); +static CYTHON_INLINE PyObject* __Pyx_PyNumber_Long(PyObject* x); +#define __Pyx_PySequence_Tuple(obj)\ + (likely(PyTuple_CheckExact(obj)) ? __Pyx_NewRef(obj) : PySequence_Tuple(obj)) +static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); +static CYTHON_INLINE PyObject * __Pyx_PyLong_FromSize_t(size_t); +static CYTHON_INLINE Py_hash_t __Pyx_PyIndex_AsHash_t(PyObject*); +#if CYTHON_ASSUME_SAFE_MACROS +#define __Pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) +#define __Pyx_PyFloat_AS_DOUBLE(x) PyFloat_AS_DOUBLE(x) +#else +#define __Pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) +#define __Pyx_PyFloat_AS_DOUBLE(x) PyFloat_AsDouble(x) +#endif +#define __Pyx_PyFloat_AsFloat(x) ((float) __Pyx_PyFloat_AsDouble(x)) +#define __Pyx_PyNumber_Int(x) (PyLong_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Long(x)) +#if CYTHON_USE_PYLONG_INTERNALS + #if PY_VERSION_HEX >= 0x030C00A7 + #ifndef _PyLong_SIGN_MASK + #define _PyLong_SIGN_MASK 3 + #endif + #ifndef _PyLong_NON_SIZE_BITS + #define _PyLong_NON_SIZE_BITS 3 + #endif + #define __Pyx_PyLong_Sign(x) (((PyLongObject*)x)->long_value.lv_tag & _PyLong_SIGN_MASK) + #define __Pyx_PyLong_IsNeg(x) ((__Pyx_PyLong_Sign(x) & 2) != 0) + #define __Pyx_PyLong_IsNonNeg(x) (!__Pyx_PyLong_IsNeg(x)) + #define __Pyx_PyLong_IsZero(x) (__Pyx_PyLong_Sign(x) & 1) + #define __Pyx_PyLong_IsPos(x) (__Pyx_PyLong_Sign(x) == 0) + #define __Pyx_PyLong_CompactValueUnsigned(x) (__Pyx_PyLong_Digits(x)[0]) + #define __Pyx_PyLong_DigitCount(x) ((Py_ssize_t) (((PyLongObject*)x)->long_value.lv_tag >> _PyLong_NON_SIZE_BITS)) + #define __Pyx_PyLong_SignedDigitCount(x)\ + ((1 - (Py_ssize_t) __Pyx_PyLong_Sign(x)) * __Pyx_PyLong_DigitCount(x)) + #if defined(PyUnstable_Long_IsCompact) && defined(PyUnstable_Long_CompactValue) + #define __Pyx_PyLong_IsCompact(x) PyUnstable_Long_IsCompact((PyLongObject*) x) + #define __Pyx_PyLong_CompactValue(x) PyUnstable_Long_CompactValue((PyLongObject*) x) + #else + #define __Pyx_PyLong_IsCompact(x) (((PyLongObject*)x)->long_value.lv_tag < (2 << _PyLong_NON_SIZE_BITS)) + #define __Pyx_PyLong_CompactValue(x) ((1 - (Py_ssize_t) __Pyx_PyLong_Sign(x)) * (Py_ssize_t) __Pyx_PyLong_Digits(x)[0]) + #endif + typedef Py_ssize_t __Pyx_compact_pylong; + typedef size_t __Pyx_compact_upylong; + #else + #define __Pyx_PyLong_IsNeg(x) (Py_SIZE(x) < 0) + #define __Pyx_PyLong_IsNonNeg(x) (Py_SIZE(x) >= 0) + #define __Pyx_PyLong_IsZero(x) (Py_SIZE(x) == 0) + #define __Pyx_PyLong_IsPos(x) (Py_SIZE(x) > 0) + #define __Pyx_PyLong_CompactValueUnsigned(x) ((Py_SIZE(x) == 0) ? 0 : __Pyx_PyLong_Digits(x)[0]) + #define __Pyx_PyLong_DigitCount(x) __Pyx_sst_abs(Py_SIZE(x)) + #define __Pyx_PyLong_SignedDigitCount(x) Py_SIZE(x) + #define __Pyx_PyLong_IsCompact(x) (Py_SIZE(x) == 0 || Py_SIZE(x) == 1 || Py_SIZE(x) == -1) + #define __Pyx_PyLong_CompactValue(x)\ + ((Py_SIZE(x) == 0) ? (sdigit) 0 : ((Py_SIZE(x) < 0) ? -(sdigit)__Pyx_PyLong_Digits(x)[0] : (sdigit)__Pyx_PyLong_Digits(x)[0])) + typedef sdigit __Pyx_compact_pylong; + typedef digit __Pyx_compact_upylong; + #endif + #if PY_VERSION_HEX >= 0x030C00A5 + #define __Pyx_PyLong_Digits(x) (((PyLongObject*)x)->long_value.ob_digit) + #else + #define __Pyx_PyLong_Digits(x) (((PyLongObject*)x)->ob_digit) + #endif +#endif +#if __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 + #define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) +#elif __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + #define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeASCII(c_str, size, NULL) +#else + #define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) +#endif + + +/* Test for GCC > 2.95 */ +#if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))) + #define likely(x) __builtin_expect(!!(x), 1) + #define unlikely(x) __builtin_expect(!!(x), 0) +#else /* !__GNUC__ or GCC < 2.95 */ + #define likely(x) (x) + #define unlikely(x) (x) +#endif /* __GNUC__ */ +/* PretendToInitialize */ +#ifdef __cplusplus +#if __cplusplus > 201103L +#include +#endif +template +static void __Pyx_pretend_to_initialize(T* ptr) { +#if __cplusplus > 201103L + if ((std::is_trivially_default_constructible::value)) +#endif + *ptr = T(); + (void)ptr; +} +#else +static CYTHON_INLINE void __Pyx_pretend_to_initialize(void* ptr) { (void)ptr; } +#endif + + +#if !CYTHON_USE_MODULE_STATE +static PyObject *__pyx_m = NULL; +#endif +static int __pyx_lineno; +static int __pyx_clineno = 0; +static const char * const __pyx_cfilenm = __FILE__; +static const char *__pyx_filename; + +/* #### Code section: filename_table ### */ + +static const char* const __pyx_f[] = { + "thriftpy2/transport/sasl/cysasl.pyx", + "", + "thriftpy2/transport/cybase.pxd", +}; +/* #### Code section: utility_code_proto_before_types ### */ +/* Atomics.proto (used by UnpackUnboundCMethod) */ +#include +#ifndef CYTHON_ATOMICS + #define CYTHON_ATOMICS 1 +#endif +#define __PYX_CYTHON_ATOMICS_ENABLED() CYTHON_ATOMICS +#define __PYX_GET_CYTHON_COMPILING_IN_CPYTHON_FREETHREADING() CYTHON_COMPILING_IN_CPYTHON_FREETHREADING +#define __pyx_atomic_int_type int +#define __pyx_nonatomic_int_type int +#if CYTHON_ATOMICS && (defined(__STDC_VERSION__) &&\ + (__STDC_VERSION__ >= 201112L) &&\ + !defined(__STDC_NO_ATOMICS__)) + #include +#elif CYTHON_ATOMICS && (defined(__cplusplus) && (\ + (__cplusplus >= 201103L) ||\ + (defined(_MSC_VER) && _MSC_VER >= 1700))) + #include +#endif +#if CYTHON_ATOMICS && (defined(__STDC_VERSION__) &&\ + (__STDC_VERSION__ >= 201112L) &&\ + !defined(__STDC_NO_ATOMICS__) &&\ + ATOMIC_INT_LOCK_FREE == 2) + #undef __pyx_atomic_int_type + #define __pyx_atomic_int_type atomic_int + #define __pyx_atomic_ptr_type atomic_uintptr_t + #define __pyx_nonatomic_ptr_type uintptr_t + #define __pyx_atomic_incr_relaxed(value) atomic_fetch_add_explicit(value, 1, memory_order_relaxed) + #define __pyx_atomic_incr_acq_rel(value) atomic_fetch_add_explicit(value, 1, memory_order_acq_rel) + #define __pyx_atomic_decr_acq_rel(value) atomic_fetch_sub_explicit(value, 1, memory_order_acq_rel) + #define __pyx_atomic_sub(value, arg) atomic_fetch_sub(value, arg) + #define __pyx_atomic_int_cmp_exchange(value, expected, desired) atomic_compare_exchange_strong(value, expected, desired) + #define __pyx_atomic_load(value) atomic_load(value) + #define __pyx_atomic_store(value, new_value) atomic_store(value, new_value) + #define __pyx_atomic_pointer_load_relaxed(value) atomic_load_explicit(value, memory_order_relaxed) + #define __pyx_atomic_pointer_load_acquire(value) atomic_load_explicit(value, memory_order_acquire) + #define __pyx_atomic_pointer_exchange(value, new_value) atomic_exchange(value, (__pyx_nonatomic_ptr_type)new_value) + #define __pyx_atomic_pointer_cmp_exchange(value, expected, desired) atomic_compare_exchange_strong(value, expected, desired) + #if defined(__PYX_DEBUG_ATOMICS) && defined(_MSC_VER) + #pragma message ("Using standard C atomics") + #elif defined(__PYX_DEBUG_ATOMICS) + #warning "Using standard C atomics" + #endif +#elif CYTHON_ATOMICS && (defined(__cplusplus) && (\ + (__cplusplus >= 201103L) ||\ +\ + (defined(_MSC_VER) && _MSC_VER >= 1700)) &&\ + ATOMIC_INT_LOCK_FREE == 2) + #undef __pyx_atomic_int_type + #define __pyx_atomic_int_type std::atomic_int + #define __pyx_atomic_ptr_type std::atomic_uintptr_t + #define __pyx_nonatomic_ptr_type uintptr_t + #define __pyx_atomic_incr_relaxed(value) std::atomic_fetch_add_explicit(value, 1, std::memory_order_relaxed) + #define __pyx_atomic_incr_acq_rel(value) std::atomic_fetch_add_explicit(value, 1, std::memory_order_acq_rel) + #define __pyx_atomic_decr_acq_rel(value) std::atomic_fetch_sub_explicit(value, 1, std::memory_order_acq_rel) + #define __pyx_atomic_sub(value, arg) std::atomic_fetch_sub(value, arg) + #define __pyx_atomic_int_cmp_exchange(value, expected, desired) std::atomic_compare_exchange_strong(value, expected, desired) + #define __pyx_atomic_load(value) std::atomic_load(value) + #define __pyx_atomic_store(value, new_value) std::atomic_store(value, new_value) + #define __pyx_atomic_pointer_load_relaxed(value) std::atomic_load_explicit(value, std::memory_order_relaxed) + #define __pyx_atomic_pointer_load_acquire(value) std::atomic_load_explicit(value, std::memory_order_acquire) + #define __pyx_atomic_pointer_exchange(value, new_value) std::atomic_exchange(value, (__pyx_nonatomic_ptr_type)new_value) + #define __pyx_atomic_pointer_cmp_exchange(value, expected, desired) std::atomic_compare_exchange_strong(value, expected, desired) + #if defined(__PYX_DEBUG_ATOMICS) && defined(_MSC_VER) + #pragma message ("Using standard C++ atomics") + #elif defined(__PYX_DEBUG_ATOMICS) + #warning "Using standard C++ atomics" + #endif +#elif CYTHON_ATOMICS && (__GNUC__ >= 5 || (__GNUC__ == 4 &&\ + (__GNUC_MINOR__ > 1 ||\ + (__GNUC_MINOR__ == 1 && __GNUC_PATCHLEVEL__ >= 2)))) + #define __pyx_atomic_ptr_type void* + #define __pyx_nonatomic_ptr_type void* + #define __pyx_atomic_incr_relaxed(value) __sync_fetch_and_add(value, 1) + #define __pyx_atomic_incr_acq_rel(value) __sync_fetch_and_add(value, 1) + #define __pyx_atomic_decr_acq_rel(value) __sync_fetch_and_sub(value, 1) + #define __pyx_atomic_sub(value, arg) __sync_fetch_and_sub(value, arg) + static CYTHON_INLINE int __pyx_atomic_int_cmp_exchange(__pyx_atomic_int_type* value, __pyx_nonatomic_int_type* expected, __pyx_nonatomic_int_type desired) { + __pyx_nonatomic_int_type old = __sync_val_compare_and_swap(value, *expected, desired); + int result = old == *expected; + *expected = old; + return result; + } + #define __pyx_atomic_load(value) __sync_fetch_and_add(value, 0) + #define __pyx_atomic_store(value, new_value) __sync_lock_test_and_set(value, new_value) + #define __pyx_atomic_pointer_load_relaxed(value) __sync_fetch_and_add(value, 0) + #define __pyx_atomic_pointer_load_acquire(value) __sync_fetch_and_add(value, 0) + #define __pyx_atomic_pointer_exchange(value, new_value) __sync_lock_test_and_set(value, (__pyx_atomic_ptr_type)new_value) + static CYTHON_INLINE int __pyx_atomic_pointer_cmp_exchange(__pyx_atomic_ptr_type* value, __pyx_nonatomic_ptr_type* expected, __pyx_nonatomic_ptr_type desired) { + __pyx_nonatomic_ptr_type old = __sync_val_compare_and_swap(value, *expected, desired); + int result = old == *expected; + *expected = old; + return result; + } + #ifdef __PYX_DEBUG_ATOMICS + #warning "Using GNU atomics" + #endif +#elif CYTHON_ATOMICS && defined(_MSC_VER) + #include + #undef __pyx_atomic_int_type + #define __pyx_atomic_int_type long + #define __pyx_atomic_ptr_type void* + #undef __pyx_nonatomic_int_type + #define __pyx_nonatomic_int_type long + #define __pyx_nonatomic_ptr_type void* + #pragma intrinsic (_InterlockedExchangeAdd, _InterlockedExchange, _InterlockedCompareExchange, _InterlockedCompareExchangePointer, _InterlockedExchangePointer) + #define __pyx_atomic_incr_relaxed(value) _InterlockedExchangeAdd(value, 1) + #define __pyx_atomic_incr_acq_rel(value) _InterlockedExchangeAdd(value, 1) + #define __pyx_atomic_decr_acq_rel(value) _InterlockedExchangeAdd(value, -1) + #define __pyx_atomic_sub(value, arg) _InterlockedExchangeAdd(value, -arg) + static CYTHON_INLINE int __pyx_atomic_int_cmp_exchange(__pyx_atomic_int_type* value, __pyx_nonatomic_int_type* expected, __pyx_nonatomic_int_type desired) { + __pyx_nonatomic_int_type old = _InterlockedCompareExchange(value, desired, *expected); + int result = old == *expected; + *expected = old; + return result; + } + #define __pyx_atomic_load(value) _InterlockedExchangeAdd(value, 0) + #define __pyx_atomic_store(value, new_value) _InterlockedExchange(value, new_value) + #define __pyx_atomic_pointer_load_relaxed(value) *(void * volatile *)value + #define __pyx_atomic_pointer_load_acquire(value) _InterlockedCompareExchangePointer(value, 0, 0) + #define __pyx_atomic_pointer_exchange(value, new_value) _InterlockedExchangePointer(value, (__pyx_atomic_ptr_type)new_value) + static CYTHON_INLINE int __pyx_atomic_pointer_cmp_exchange(__pyx_atomic_ptr_type* value, __pyx_nonatomic_ptr_type* expected, __pyx_nonatomic_ptr_type desired) { + __pyx_atomic_ptr_type old = _InterlockedCompareExchangePointer(value, desired, *expected); + int result = old == *expected; + *expected = old; + return result; + } + #ifdef __PYX_DEBUG_ATOMICS + #pragma message ("Using MSVC atomics") + #endif +#else + #undef CYTHON_ATOMICS + #define CYTHON_ATOMICS 0 + #ifdef __PYX_DEBUG_ATOMICS + #warning "Not using atomics" + #endif +#endif + +/* CriticalSectionsDefinition.proto (used by CriticalSections) */ +#if !CYTHON_COMPILING_IN_CPYTHON_FREETHREADING +#define __Pyx_PyCriticalSection void* +#define __Pyx_PyCriticalSection2 void* +#define __Pyx_PyCriticalSection_End(cs) +#define __Pyx_PyCriticalSection2_End(cs) +#else +#define __Pyx_PyCriticalSection PyCriticalSection +#define __Pyx_PyCriticalSection2 PyCriticalSection2 +#define __Pyx_PyCriticalSection_End PyCriticalSection_End +#define __Pyx_PyCriticalSection2_End PyCriticalSection2_End +#endif + +/* CriticalSections.proto (used by ParseKeywordsImpl) */ +#if !CYTHON_COMPILING_IN_CPYTHON_FREETHREADING +#define __Pyx_PyCriticalSection_Begin(cs, arg) (void)(cs) +#define __Pyx_PyCriticalSection2_Begin(cs, arg1, arg2) (void)(cs) +#else +#define __Pyx_PyCriticalSection_Begin PyCriticalSection_Begin +#define __Pyx_PyCriticalSection2_Begin PyCriticalSection2_Begin +#endif +#if PY_VERSION_HEX < 0x030d0000 || CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_BEGIN_CRITICAL_SECTION(o) { +#define __Pyx_END_CRITICAL_SECTION() } +#else +#define __Pyx_BEGIN_CRITICAL_SECTION Py_BEGIN_CRITICAL_SECTION +#define __Pyx_END_CRITICAL_SECTION Py_END_CRITICAL_SECTION +#endif + +/* IncludeStructmemberH.proto (used by FixUpExtensionType) */ +#include + +/* #### Code section: numeric_typedefs ### */ +/* #### Code section: complex_type_declarations ### */ +/* #### Code section: type_declarations ### */ + +/*--- Type declarations ---*/ +struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer; +struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase; +struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport; + +/* "thriftpy2/transport/cybase.pxd":3 + * # cython: freethreading_compatible = True + * + * cdef enum: # <<<<<<<<<<<<<< + * DEFAULT_BUFFER = 4096 + * STACK_STRING_LEN = 4096 +*/ +enum { + __pyx_e_9thriftpy2_9transport_6cybase_DEFAULT_BUFFER = 0x1000, + __pyx_e_9thriftpy2_9transport_6cybase_STACK_STRING_LEN = 0x1000 +}; + +/* "thriftpy2/transport/cybase.pxd":7 + * STACK_STRING_LEN = 4096 + * + * cdef class TCyBuffer(object): # <<<<<<<<<<<<<< + * cdef: + * char *buf +*/ +struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer { + PyObject_HEAD + struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_TCyBuffer *__pyx_vtab; + char *buf; + int cur; + int buf_size; + int data_size; +}; + + +/* "thriftpy2/transport/cybase.pxd":19 + * + * + * cdef class CyTransportBase(object): # <<<<<<<<<<<<<< + * cdef object trans + * +*/ +struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase { + PyObject_HEAD + struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_CyTransportBase *__pyx_vtab; + PyObject *trans; +}; + + +/* "thriftpy2/transport/sasl/cysasl.pyx":18 + * DEF MIN_BUFFER_SIZE = 1024 + * + * cdef class TCySaslClientTransport(CyTransportBase): # <<<<<<<<<<<<<< + * """sasl wrapper""" + * +*/ +struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport { + struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase __pyx_base; + PyObject *sasl; + PyObject *sasl_client_factory; + struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *_TCySaslClientTransport__wbuf; + struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *_TCySaslClientTransport__rbuf; + int opened; + int encode; + int encode_decided; + PyObject *mechanism; +}; + + + +/* "thriftpy2/transport/cybase.pxd":7 + * STACK_STRING_LEN = 4096 + * + * cdef class TCyBuffer(object): # <<<<<<<<<<<<<< + * cdef: + * char *buf +*/ + +struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_TCyBuffer { + void (*move_to_start)(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *); + void (*clean)(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *); + int (*write)(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *, int, char const *); + int (*grow)(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *, int); + PyObject *(*read_trans)(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *, PyObject *, int, char *); +}; +static struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_TCyBuffer *__pyx_vtabptr_9thriftpy2_9transport_6cybase_TCyBuffer; + + +/* "thriftpy2/transport/cybase.pxd":19 + * + * + * cdef class CyTransportBase(object): # <<<<<<<<<<<<<< + * cdef object trans + * +*/ + +struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_CyTransportBase { + PyObject *(*c_read)(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *, int, char *); + PyObject *(*c_write)(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *, char *, int); + PyObject *(*c_flush)(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *); + PyObject *(*get_string)(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *, int); +}; +static struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_CyTransportBase *__pyx_vtabptr_9thriftpy2_9transport_6cybase_CyTransportBase; + + +/* "thriftpy2/transport/sasl/cysasl.pyx":18 + * DEF MIN_BUFFER_SIZE = 1024 + * + * cdef class TCySaslClientTransport(CyTransportBase): # <<<<<<<<<<<<<< + * """sasl wrapper""" + * +*/ + +struct __pyx_vtabstruct_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport { + struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_CyTransportBase __pyx_base; +}; +static struct __pyx_vtabstruct_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *__pyx_vtabptr_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport; +/* #### Code section: utility_code_proto ### */ + +/* --- Runtime support code (head) --- */ +/* Refnanny.proto */ +#ifndef CYTHON_REFNANNY + #define CYTHON_REFNANNY 0 +#endif +#if CYTHON_REFNANNY + typedef struct { + void (*INCREF)(void*, PyObject*, Py_ssize_t); + void (*DECREF)(void*, PyObject*, Py_ssize_t); + void (*GOTREF)(void*, PyObject*, Py_ssize_t); + void (*GIVEREF)(void*, PyObject*, Py_ssize_t); + void* (*SetupContext)(const char*, Py_ssize_t, const char*); + void (*FinishContext)(void**); + } __Pyx_RefNannyAPIStruct; + static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; + static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); + #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; + #define __Pyx_RefNannySetupContext(name, acquire_gil)\ + if (acquire_gil) {\ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), (__LINE__), (__FILE__));\ + PyGILState_Release(__pyx_gilstate_save);\ + } else {\ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), (__LINE__), (__FILE__));\ + } + #define __Pyx_RefNannyFinishContextNogil() {\ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ + __Pyx_RefNannyFinishContext();\ + PyGILState_Release(__pyx_gilstate_save);\ + } + #define __Pyx_RefNannyFinishContextNogil() {\ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ + __Pyx_RefNannyFinishContext();\ + PyGILState_Release(__pyx_gilstate_save);\ + } + #define __Pyx_RefNannyFinishContext()\ + __Pyx_RefNanny->FinishContext(&__pyx_refnanny) + #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), (__LINE__)) + #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), (__LINE__)) + #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), (__LINE__)) + #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), (__LINE__)) + #define __Pyx_XINCREF(r) do { if((r) == NULL); else {__Pyx_INCREF(r); }} while(0) + #define __Pyx_XDECREF(r) do { if((r) == NULL); else {__Pyx_DECREF(r); }} while(0) + #define __Pyx_XGOTREF(r) do { if((r) == NULL); else {__Pyx_GOTREF(r); }} while(0) + #define __Pyx_XGIVEREF(r) do { if((r) == NULL); else {__Pyx_GIVEREF(r);}} while(0) +#else + #define __Pyx_RefNannyDeclarations + #define __Pyx_RefNannySetupContext(name, acquire_gil) + #define __Pyx_RefNannyFinishContextNogil() + #define __Pyx_RefNannyFinishContext() + #define __Pyx_INCREF(r) Py_INCREF(r) + #define __Pyx_DECREF(r) Py_DECREF(r) + #define __Pyx_GOTREF(r) + #define __Pyx_GIVEREF(r) + #define __Pyx_XINCREF(r) Py_XINCREF(r) + #define __Pyx_XDECREF(r) Py_XDECREF(r) + #define __Pyx_XGOTREF(r) + #define __Pyx_XGIVEREF(r) +#endif +#define __Pyx_Py_XDECREF_SET(r, v) do {\ + PyObject *tmp = (PyObject *) r;\ + r = v; Py_XDECREF(tmp);\ + } while (0) +#define __Pyx_XDECREF_SET(r, v) do {\ + PyObject *tmp = (PyObject *) r;\ + r = v; __Pyx_XDECREF(tmp);\ + } while (0) +#define __Pyx_DECREF_SET(r, v) do {\ + PyObject *tmp = (PyObject *) r;\ + r = v; __Pyx_DECREF(tmp);\ + } while (0) +#define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) +#define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) + +/* TupleAndListFromArray.proto (used by fastcall) */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyList_FromArray(PyObject *const *src, Py_ssize_t n); +#endif +#if CYTHON_COMPILING_IN_CPYTHON || CYTHON_METH_FASTCALL +static CYTHON_INLINE PyObject* __Pyx_PyTuple_FromArray(PyObject *const *src, Py_ssize_t n); +#endif + +/* IncludeStringH.proto (used by BytesEquals) */ +#include + +/* BytesEquals.proto (used by UnicodeEquals) */ +static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals); + +/* UnicodeEquals.proto (used by fastcall) */ +static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals); + +/* fastcall.proto */ +#if CYTHON_AVOID_BORROWED_REFS + #define __Pyx_ArgRef_VARARGS(args, i) __Pyx_PySequence_ITEM(args, i) +#elif CYTHON_ASSUME_SAFE_MACROS + #define __Pyx_ArgRef_VARARGS(args, i) __Pyx_NewRef(__Pyx_PyTuple_GET_ITEM(args, i)) +#else + #define __Pyx_ArgRef_VARARGS(args, i) __Pyx_XNewRef(PyTuple_GetItem(args, i)) +#endif +#define __Pyx_NumKwargs_VARARGS(kwds) PyDict_Size(kwds) +#define __Pyx_KwValues_VARARGS(args, nargs) NULL +#define __Pyx_GetKwValue_VARARGS(kw, kwvalues, s) __Pyx_PyDict_GetItemStrWithError(kw, s) +#define __Pyx_KwargsAsDict_VARARGS(kw, kwvalues) PyDict_Copy(kw) +#if CYTHON_METH_FASTCALL + #define __Pyx_ArgRef_FASTCALL(args, i) __Pyx_NewRef(args[i]) + #define __Pyx_NumKwargs_FASTCALL(kwds) __Pyx_PyTuple_GET_SIZE(kwds) + #define __Pyx_KwValues_FASTCALL(args, nargs) ((args) + (nargs)) + static CYTHON_INLINE PyObject * __Pyx_GetKwValue_FASTCALL(PyObject *kwnames, PyObject *const *kwvalues, PyObject *s); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030d0000 || CYTHON_COMPILING_IN_LIMITED_API + CYTHON_UNUSED static PyObject *__Pyx_KwargsAsDict_FASTCALL(PyObject *kwnames, PyObject *const *kwvalues); + #else + #define __Pyx_KwargsAsDict_FASTCALL(kw, kwvalues) _PyStack_AsDict(kwvalues, kw) + #endif +#else + #define __Pyx_ArgRef_FASTCALL __Pyx_ArgRef_VARARGS + #define __Pyx_NumKwargs_FASTCALL __Pyx_NumKwargs_VARARGS + #define __Pyx_KwValues_FASTCALL __Pyx_KwValues_VARARGS + #define __Pyx_GetKwValue_FASTCALL __Pyx_GetKwValue_VARARGS + #define __Pyx_KwargsAsDict_FASTCALL __Pyx_KwargsAsDict_VARARGS +#endif +#define __Pyx_ArgsSlice_VARARGS(args, start, stop) PyTuple_GetSlice(args, start, stop) +#if CYTHON_METH_FASTCALL || (CYTHON_COMPILING_IN_CPYTHON && CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS) +#define __Pyx_ArgsSlice_FASTCALL(args, start, stop) __Pyx_PyTuple_FromArray(args + start, stop - start) +#else +#define __Pyx_ArgsSlice_FASTCALL(args, start, stop) PyTuple_GetSlice(args, start, stop) +#endif + +/* py_dict_items.proto (used by OwnedDictNext) */ +static CYTHON_INLINE PyObject* __Pyx_PyDict_Items(PyObject* d); + +/* CallCFunction.proto (used by CallUnboundCMethod0) */ +#define __Pyx_CallCFunction(cfunc, self, args)\ + ((PyCFunction)(void(*)(void))(cfunc)->func)(self, args) +#define __Pyx_CallCFunctionWithKeywords(cfunc, self, args, kwargs)\ + ((PyCFunctionWithKeywords)(void(*)(void))(cfunc)->func)(self, args, kwargs) +#define __Pyx_CallCFunctionFast(cfunc, self, args, nargs)\ + ((__Pyx_PyCFunctionFast)(void(*)(void))(PyCFunction)(cfunc)->func)(self, args, nargs) +#define __Pyx_CallCFunctionFastWithKeywords(cfunc, self, args, nargs, kwnames)\ + ((__Pyx_PyCFunctionFastWithKeywords)(void(*)(void))(PyCFunction)(cfunc)->func)(self, args, nargs, kwnames) + +/* PyObjectCall.proto (used by PyObjectFastCall) */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw); +#else +#define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw) +#endif + +/* PyObjectCallMethO.proto (used by PyObjectFastCall) */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg); +#endif + +/* PyObjectFastCall.proto (used by PyObjectCallOneArg) */ +#define __Pyx_PyObject_FastCall(func, args, nargs) __Pyx_PyObject_FastCallDict(func, args, (size_t)(nargs), NULL) +static CYTHON_INLINE PyObject* __Pyx_PyObject_FastCallDict(PyObject *func, PyObject * const*args, size_t nargs, PyObject *kwargs); + +/* PyObjectCallOneArg.proto (used by CallUnboundCMethod0) */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg); + +/* PyObjectGetAttrStr.proto (used by UnpackUnboundCMethod) */ +#if CYTHON_USE_TYPE_SLOTS +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name); +#else +#define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) +#endif + +/* UnpackUnboundCMethod.proto (used by CallUnboundCMethod0) */ +typedef struct { + PyObject *type; + PyObject **method_name; +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING && CYTHON_ATOMICS + __pyx_atomic_int_type initialized; +#endif + PyCFunction func; + PyObject *method; + int flag; +} __Pyx_CachedCFunction; +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING +static CYTHON_INLINE int __Pyx_CachedCFunction_GetAndSetInitializing(__Pyx_CachedCFunction *cfunc) { +#if !CYTHON_ATOMICS + return 1; +#else + __pyx_nonatomic_int_type expected = 0; + if (__pyx_atomic_int_cmp_exchange(&cfunc->initialized, &expected, 1)) { + return 0; + } + return expected; +#endif +} +static CYTHON_INLINE void __Pyx_CachedCFunction_SetFinishedInitializing(__Pyx_CachedCFunction *cfunc) { +#if CYTHON_ATOMICS + __pyx_atomic_store(&cfunc->initialized, 2); +#endif +} +#else +#define __Pyx_CachedCFunction_GetAndSetInitializing(cfunc) 2 +#define __Pyx_CachedCFunction_SetFinishedInitializing(cfunc) +#endif + +/* CallUnboundCMethod0.proto */ +CYTHON_UNUSED +static PyObject* __Pyx__CallUnboundCMethod0(__Pyx_CachedCFunction* cfunc, PyObject* self); +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_CallUnboundCMethod0(__Pyx_CachedCFunction* cfunc, PyObject* self); +#else +#define __Pyx_CallUnboundCMethod0(cfunc, self) __Pyx__CallUnboundCMethod0(cfunc, self) +#endif + +/* py_dict_values.proto (used by OwnedDictNext) */ +static CYTHON_INLINE PyObject* __Pyx_PyDict_Values(PyObject* d); + +/* OwnedDictNext.proto (used by ParseKeywordsImpl) */ +#if CYTHON_AVOID_BORROWED_REFS +static int __Pyx_PyDict_NextRef(PyObject *p, PyObject **ppos, PyObject **pkey, PyObject **pvalue); +#else +CYTHON_INLINE +static int __Pyx_PyDict_NextRef(PyObject *p, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue); +#endif + +/* RaiseDoubleKeywords.proto (used by ParseKeywordsImpl) */ +static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); + +/* ParseKeywordsImpl.export */ +static int __Pyx_ParseKeywordsTuple( + PyObject *kwds, + PyObject * const *kwvalues, + PyObject ** const argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + Py_ssize_t num_kwargs, + const char* function_name, + int ignore_unknown_kwargs +); +static int __Pyx_ParseKeywordDictToDict( + PyObject *kwds, + PyObject ** const argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + const char* function_name +); +static int __Pyx_ParseKeywordDict( + PyObject *kwds, + PyObject ** const argnames[], + PyObject *values[], + Py_ssize_t num_pos_args, + Py_ssize_t num_kwargs, + const char* function_name, + int ignore_unknown_kwargs +); + +/* CallUnboundCMethod2.proto */ +CYTHON_UNUSED +static PyObject* __Pyx__CallUnboundCMethod2(__Pyx_CachedCFunction* cfunc, PyObject* self, PyObject* arg1, PyObject* arg2); +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject *__Pyx_CallUnboundCMethod2(__Pyx_CachedCFunction *cfunc, PyObject *self, PyObject *arg1, PyObject *arg2); +#else +#define __Pyx_CallUnboundCMethod2(cfunc, self, arg1, arg2) __Pyx__CallUnboundCMethod2(cfunc, self, arg1, arg2) +#endif + +/* ParseKeywords.proto */ +static CYTHON_INLINE int __Pyx_ParseKeywords( + PyObject *kwds, PyObject *const *kwvalues, PyObject ** const argnames[], + PyObject *kwds2, PyObject *values[], + Py_ssize_t num_pos_args, Py_ssize_t num_kwargs, + const char* function_name, + int ignore_unknown_kwargs +); + +/* RaiseArgTupleInvalid.proto */ +static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, + Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); + +/* RaiseUnexpectedTypeError.proto */ +static int __Pyx_RaiseUnexpectedTypeError(const char *expected, PyObject *obj); + +/* RejectKeywords.export */ +static void __Pyx_RejectKeywords(const char* function_name, PyObject *kwds); + +/* PyObjectFastCallMethod.proto */ +#if CYTHON_VECTORCALL && PY_VERSION_HEX >= 0x03090000 +#define __Pyx_PyObject_FastCallMethod(name, args, nargsf) PyObject_VectorcallMethod(name, args, nargsf, NULL) +#else +static PyObject *__Pyx_PyObject_FastCallMethod(PyObject *name, PyObject *const *args, size_t nargsf); +#endif + +/* PyErrExceptionMatches.proto (used by PyObjectGetAttrStrNoError) */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_PyErr_ExceptionMatches(err) __Pyx_PyErr_ExceptionMatchesInState(__pyx_tstate, err) +static CYTHON_INLINE int __Pyx_PyErr_ExceptionMatchesInState(PyThreadState* tstate, PyObject* err); +#else +#define __Pyx_PyErr_ExceptionMatches(err) PyErr_ExceptionMatches(err) +#endif + +/* PyThreadStateGet.proto (used by PyErrFetchRestore) */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_PyThreadState_declare PyThreadState *__pyx_tstate; +#define __Pyx_PyThreadState_assign __pyx_tstate = __Pyx_PyThreadState_Current; +#if PY_VERSION_HEX >= 0x030C00A6 +#define __Pyx_PyErr_Occurred() (__pyx_tstate->current_exception != NULL) +#define __Pyx_PyErr_CurrentExceptionType() (__pyx_tstate->current_exception ? (PyObject*) Py_TYPE(__pyx_tstate->current_exception) : (PyObject*) NULL) +#else +#define __Pyx_PyErr_Occurred() (__pyx_tstate->curexc_type != NULL) +#define __Pyx_PyErr_CurrentExceptionType() (__pyx_tstate->curexc_type) +#endif +#else +#define __Pyx_PyThreadState_declare +#define __Pyx_PyThreadState_assign +#define __Pyx_PyErr_Occurred() (PyErr_Occurred() != NULL) +#define __Pyx_PyErr_CurrentExceptionType() PyErr_Occurred() +#endif + +/* PyErrFetchRestore.proto (used by PyObjectGetAttrStrNoError) */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_PyErr_Clear() __Pyx_ErrRestore(NULL, NULL, NULL) +#define __Pyx_ErrRestoreWithState(type, value, tb) __Pyx_ErrRestoreInState(PyThreadState_GET(), type, value, tb) +#define __Pyx_ErrFetchWithState(type, value, tb) __Pyx_ErrFetchInState(PyThreadState_GET(), type, value, tb) +#define __Pyx_ErrRestore(type, value, tb) __Pyx_ErrRestoreInState(__pyx_tstate, type, value, tb) +#define __Pyx_ErrFetch(type, value, tb) __Pyx_ErrFetchInState(__pyx_tstate, type, value, tb) +static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); +static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030C00A6 +#define __Pyx_PyErr_SetNone(exc) (Py_INCREF(exc), __Pyx_ErrRestore((exc), NULL, NULL)) +#else +#define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) +#endif +#else +#define __Pyx_PyErr_Clear() PyErr_Clear() +#define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) +#define __Pyx_ErrRestoreWithState(type, value, tb) PyErr_Restore(type, value, tb) +#define __Pyx_ErrFetchWithState(type, value, tb) PyErr_Fetch(type, value, tb) +#define __Pyx_ErrRestoreInState(tstate, type, value, tb) PyErr_Restore(type, value, tb) +#define __Pyx_ErrFetchInState(tstate, type, value, tb) PyErr_Fetch(type, value, tb) +#define __Pyx_ErrRestore(type, value, tb) PyErr_Restore(type, value, tb) +#define __Pyx_ErrFetch(type, value, tb) PyErr_Fetch(type, value, tb) +#endif + +/* PyObjectGetAttrStrNoError.proto (used by GetBuiltinName) */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStrNoError(PyObject* obj, PyObject* attr_name); + +/* GetBuiltinName.proto (used by GetModuleGlobalName) */ +static PyObject *__Pyx_GetBuiltinName(PyObject *name); + +/* PyDictVersioning.proto (used by GetModuleGlobalName) */ +#if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_TYPE_SLOTS +#define __PYX_DICT_VERSION_INIT ((PY_UINT64_T) -1) +#define __PYX_GET_DICT_VERSION(dict) (((PyDictObject*)(dict))->ma_version_tag) +#define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var)\ + (version_var) = __PYX_GET_DICT_VERSION(dict);\ + (cache_var) = (value); +#define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) {\ + static PY_UINT64_T __pyx_dict_version = 0;\ + static PyObject *__pyx_dict_cached_value = NULL;\ + if (likely(__PYX_GET_DICT_VERSION(DICT) == __pyx_dict_version)) {\ + (VAR) = __Pyx_XNewRef(__pyx_dict_cached_value);\ + } else {\ + (VAR) = __pyx_dict_cached_value = (LOOKUP);\ + __pyx_dict_version = __PYX_GET_DICT_VERSION(DICT);\ + }\ +} +static CYTHON_INLINE PY_UINT64_T __Pyx_get_tp_dict_version(PyObject *obj); +static CYTHON_INLINE PY_UINT64_T __Pyx_get_object_dict_version(PyObject *obj); +static CYTHON_INLINE int __Pyx_object_dict_version_matches(PyObject* obj, PY_UINT64_T tp_dict_version, PY_UINT64_T obj_dict_version); +#else +#define __PYX_GET_DICT_VERSION(dict) (0) +#define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var) +#define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) (VAR) = (LOOKUP); +#endif + +/* GetModuleGlobalName.proto */ +#if CYTHON_USE_DICT_VERSIONS +#define __Pyx_GetModuleGlobalName(var, name) do {\ + static PY_UINT64_T __pyx_dict_version = 0;\ + static PyObject *__pyx_dict_cached_value = NULL;\ + (var) = (likely(__pyx_dict_version == __PYX_GET_DICT_VERSION(__pyx_mstate_global->__pyx_d))) ?\ + (likely(__pyx_dict_cached_value) ? __Pyx_NewRef(__pyx_dict_cached_value) : __Pyx_GetBuiltinName(name)) :\ + __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\ +} while(0) +#define __Pyx_GetModuleGlobalNameUncached(var, name) do {\ + PY_UINT64_T __pyx_dict_version;\ + PyObject *__pyx_dict_cached_value;\ + (var) = __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\ +} while(0) +static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_version, PyObject **dict_cached_value); +#else +#define __Pyx_GetModuleGlobalName(var, name) (var) = __Pyx__GetModuleGlobalName(name) +#define __Pyx_GetModuleGlobalNameUncached(var, name) (var) = __Pyx__GetModuleGlobalName(name) +static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name); +#endif + +/* PyObjectVectorCallKwBuilder.proto */ +CYTHON_UNUSED static int __Pyx_VectorcallBuilder_AddArg_Check(PyObject *key, PyObject *value, PyObject *builder, PyObject **args, int n); +#if CYTHON_VECTORCALL +#if PY_VERSION_HEX >= 0x03090000 +#define __Pyx_Object_Vectorcall_CallFromBuilder PyObject_Vectorcall +#else +#define __Pyx_Object_Vectorcall_CallFromBuilder _PyObject_Vectorcall +#endif +#define __Pyx_MakeVectorcallBuilderKwds(n) PyTuple_New(n) +static int __Pyx_VectorcallBuilder_AddArg(PyObject *key, PyObject *value, PyObject *builder, PyObject **args, int n); +static int __Pyx_VectorcallBuilder_AddArgStr(const char *key, PyObject *value, PyObject *builder, PyObject **args, int n); +#else +#define __Pyx_Object_Vectorcall_CallFromBuilder __Pyx_PyObject_FastCallDict +#define __Pyx_MakeVectorcallBuilderKwds(n) __Pyx_PyDict_NewPresized(n) +#define __Pyx_VectorcallBuilder_AddArg(key, value, builder, args, n) PyDict_SetItem(builder, key, value) +#define __Pyx_VectorcallBuilder_AddArgStr(key, value, builder, args, n) PyDict_SetItemString(builder, key, value) +#endif + +/* RaiseException.export */ +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); + +/* RaiseTooManyValuesToUnpack.proto */ +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); + +/* RaiseNeedMoreValuesToUnpack.proto */ +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); + +/* IterFinish.proto */ +static CYTHON_INLINE int __Pyx_IterFinish(void); + +/* UnpackItemEndCheck.proto */ +static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected); + +/* PyObjectFormatAndDecref.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_FormatSimpleAndDecref(PyObject* s, PyObject* f); +static CYTHON_INLINE PyObject* __Pyx_PyObject_FormatAndDecref(PyObject* s, PyObject* f); + +/* JoinPyUnicode.export */ +static PyObject* __Pyx_PyUnicode_Join(PyObject** values, Py_ssize_t value_count, Py_ssize_t result_ulength, + Py_UCS4 max_char); + +/* ArgTypeTestFunc.export */ +static int __Pyx__ArgTypeTest(PyObject *obj, PyTypeObject *type, const char *name, int exact); + +/* ArgTypeTest.proto */ +#define __Pyx_ArgTypeTest(obj, type, none_allowed, name, exact)\ + ((likely(__Pyx_IS_TYPE(obj, type) | (none_allowed && (obj == Py_None)))) ? 1 :\ + __Pyx__ArgTypeTest(obj, type, name, exact)) + +/* PyMemoryError_Check.proto */ +#define __Pyx_PyExc_MemoryError_Check(obj) __Pyx_TypeCheck(obj, PyExc_MemoryError) + +/* GetAttr3.proto */ +static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *, PyObject *, PyObject *); + +/* GetItemInt.proto */ +#define __Pyx_GetItemInt(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck, has_gil, unsafe_shared)\ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ + __Pyx_GetItemInt_Fast(o, (Py_ssize_t)i, is_list, wraparound, boundscheck, unsafe_shared) :\ + (is_list ? (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL) :\ + __Pyx_GetItemInt_Generic(o, to_py_func(i)))) +#define __Pyx_GetItemInt_List(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck, has_gil, unsafe_shared)\ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ + __Pyx_GetItemInt_List_Fast(o, (Py_ssize_t)i, wraparound, boundscheck, unsafe_shared) :\ + (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL)) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck, int unsafe_shared); +#define __Pyx_GetItemInt_Tuple(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck, has_gil, unsafe_shared)\ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ + __Pyx_GetItemInt_Tuple_Fast(o, (Py_ssize_t)i, wraparound, boundscheck, unsafe_shared) :\ + (PyErr_SetString(PyExc_IndexError, "tuple index out of range"), (PyObject*)NULL)) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck, int unsafe_shared); +static PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j); +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, + int is_list, int wraparound, int boundscheck, int unsafe_shared); + +/* ExtTypeTest.proto */ +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); + +/* CallNextTpDealloc.proto */ +static void __Pyx_call_next_tp_dealloc(PyObject* obj, destructor current_tp_dealloc); + +/* CallNextTpTraverse.proto */ +static int __Pyx_call_next_tp_traverse(PyObject* obj, visitproc v, void *a, traverseproc current_tp_traverse); + +/* CallTypeTraverse.proto */ +#if !CYTHON_USE_TYPE_SPECS || (!CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x03090000) +#define __Pyx_call_type_traverse(o, always_call, visit, arg) 0 +#else +static int __Pyx_call_type_traverse(PyObject *o, int always_call, visitproc visit, void *arg); +#endif + +/* CallNextTpClear.proto */ +static void __Pyx_call_next_tp_clear(PyObject* obj, inquiry current_tp_clear); + +/* TypeImport.proto */ +#ifndef __PYX_HAVE_RT_ImportType_proto_3_2_4 +#define __PYX_HAVE_RT_ImportType_proto_3_2_4 +#if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 201112L +#include +#endif +#if (defined (__STDC_VERSION__) && __STDC_VERSION__ >= 201112L) || __cplusplus >= 201103L +#define __PYX_GET_STRUCT_ALIGNMENT_3_2_4(s) alignof(s) +#else +#define __PYX_GET_STRUCT_ALIGNMENT_3_2_4(s) sizeof(void*) +#endif +enum __Pyx_ImportType_CheckSize_3_2_4 { + __Pyx_ImportType_CheckSize_Error_3_2_4 = 0, + __Pyx_ImportType_CheckSize_Warn_3_2_4 = 1, + __Pyx_ImportType_CheckSize_Ignore_3_2_4 = 2 +}; +static PyTypeObject *__Pyx_ImportType_3_2_4(PyObject* module, const char *module_name, const char *class_name, size_t size, size_t alignment, enum __Pyx_ImportType_CheckSize_3_2_4 check_size); +#endif + +/* GetVTable.proto */ +static void* __Pyx_GetVtable(PyTypeObject *type); + +/* LimitedApiGetTypeDict.proto (used by SetItemOnTypeDict) */ +#if CYTHON_COMPILING_IN_LIMITED_API +static PyObject *__Pyx_GetTypeDict(PyTypeObject *tp); +#endif + +/* SetItemOnTypeDict.proto (used by FixUpExtensionType) */ +static int __Pyx__SetItemOnTypeDict(PyTypeObject *tp, PyObject *k, PyObject *v); +#define __Pyx_SetItemOnTypeDict(tp, k, v) __Pyx__SetItemOnTypeDict((PyTypeObject*)tp, k, v) + +/* FixUpExtensionType.proto */ +static CYTHON_INLINE int __Pyx_fix_up_extension_type_from_spec(PyType_Spec *spec, PyTypeObject *type); + +/* PyObjectCallNoArg.proto (used by PyObjectCallMethod0) */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func); + +/* PyObjectGetMethod.proto (used by PyObjectCallMethod0) */ +#if !(CYTHON_VECTORCALL && (__PYX_LIMITED_VERSION_HEX >= 0x030C0000 || (!CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x03090000))) +static int __Pyx_PyObject_GetMethod(PyObject *obj, PyObject *name, PyObject **method); +#endif + +/* PyObjectCallMethod0.proto (used by PyType_Ready) */ +static PyObject* __Pyx_PyObject_CallMethod0(PyObject* obj, PyObject* method_name); + +/* ValidateBasesTuple.proto (used by PyType_Ready) */ +#if CYTHON_COMPILING_IN_CPYTHON || CYTHON_COMPILING_IN_LIMITED_API || CYTHON_USE_TYPE_SPECS +static int __Pyx_validate_bases_tuple(const char *type_name, Py_ssize_t dictoffset, PyObject *bases); +#endif + +/* PyType_Ready.proto */ +CYTHON_UNUSED static int __Pyx_PyType_Ready(PyTypeObject *t); + +/* SetVTable.proto */ +static int __Pyx_SetVtable(PyTypeObject* typeptr , void* vtable); + +/* MergeVTables.proto */ +static int __Pyx_MergeVtables(PyTypeObject *type); + +/* DelItemOnTypeDict.proto (used by SetupReduce) */ +static int __Pyx__DelItemOnTypeDict(PyTypeObject *tp, PyObject *k); +#define __Pyx_DelItemOnTypeDict(tp, k) __Pyx__DelItemOnTypeDict((PyTypeObject*)tp, k) + +/* SetupReduce.proto */ +static int __Pyx_setup_reduce(PyObject* type_obj); + +/* HasAttr.proto (used by ImportImpl) */ +#if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 +#define __Pyx_HasAttr(o, n) PyObject_HasAttrWithError(o, n) +#else +static CYTHON_INLINE int __Pyx_HasAttr(PyObject *, PyObject *); +#endif + +/* ImportImpl.export */ +static PyObject *__Pyx__Import(PyObject *name, PyObject *const *imported_names, Py_ssize_t len_imported_names, PyObject *qualname, PyObject *moddict, int level); + +/* Import.proto */ +static CYTHON_INLINE PyObject *__Pyx_Import(PyObject *name, PyObject *const *imported_names, Py_ssize_t len_imported_names, PyObject *qualname, int level); + +/* ImportFrom.proto */ +static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name); + +/* dict_setdefault.proto (used by FetchCommonType) */ +static CYTHON_INLINE PyObject *__Pyx_PyDict_SetDefault(PyObject *d, PyObject *key, PyObject *default_value); + +/* AddModuleRef.proto (used by FetchSharedCythonModule) */ +#if ((CYTHON_COMPILING_IN_CPYTHON_FREETHREADING ) ||\ + __PYX_LIMITED_VERSION_HEX < 0x030d0000) + static PyObject *__Pyx_PyImport_AddModuleRef(const char *name); +#else + #define __Pyx_PyImport_AddModuleRef(name) PyImport_AddModuleRef(name) +#endif + +/* FetchSharedCythonModule.proto (used by FetchCommonType) */ +static PyObject *__Pyx_FetchSharedCythonABIModule(void); + +/* FetchCommonType.proto (used by CommonTypesMetaclass) */ +static PyTypeObject* __Pyx_FetchCommonTypeFromSpec(PyTypeObject *metaclass, PyObject *module, PyType_Spec *spec, PyObject *bases); + +/* CommonTypesMetaclass.proto (used by CythonFunctionShared) */ +static int __pyx_CommonTypesMetaclass_init(PyObject *module); +#define __Pyx_CommonTypesMetaclass_USED + +/* PyMethodNew.proto (used by CythonFunctionShared) */ +static PyObject *__Pyx_PyMethod_New(PyObject *func, PyObject *self, PyObject *typ); + +/* PyVectorcallFastCallDict.proto (used by CythonFunctionShared) */ +#if CYTHON_METH_FASTCALL && CYTHON_VECTORCALL +static CYTHON_INLINE PyObject *__Pyx_PyVectorcall_FastCallDict(PyObject *func, __pyx_vectorcallfunc vc, PyObject *const *args, size_t nargs, PyObject *kw); +#endif + +/* CythonFunctionShared.proto (used by CythonFunction) */ +#define __Pyx_CyFunction_USED +#define __Pyx_CYFUNCTION_STATICMETHOD 0x01 +#define __Pyx_CYFUNCTION_CLASSMETHOD 0x02 +#define __Pyx_CYFUNCTION_CCLASS 0x04 +#define __Pyx_CYFUNCTION_COROUTINE 0x08 +#define __Pyx_CyFunction_GetClosure(f)\ + (((__pyx_CyFunctionObject *) (f))->func_closure) +#if PY_VERSION_HEX < 0x030900B1 || CYTHON_COMPILING_IN_LIMITED_API + #define __Pyx_CyFunction_GetClassObj(f)\ + (((__pyx_CyFunctionObject *) (f))->func_classobj) +#else + #define __Pyx_CyFunction_GetClassObj(f)\ + ((PyObject*) ((PyCMethodObject *) (f))->mm_class) +#endif +#define __Pyx_CyFunction_SetClassObj(f, classobj)\ + __Pyx__CyFunction_SetClassObj((__pyx_CyFunctionObject *) (f), (classobj)) +#define __Pyx_CyFunction_Defaults(type, f)\ + ((type *)(((__pyx_CyFunctionObject *) (f))->defaults)) +#define __Pyx_CyFunction_SetDefaultsGetter(f, g)\ + ((__pyx_CyFunctionObject *) (f))->defaults_getter = (g) +typedef struct { +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject_HEAD + PyObject *func; +#elif PY_VERSION_HEX < 0x030900B1 + PyCFunctionObject func; +#else + PyCMethodObject func; +#endif +#if CYTHON_COMPILING_IN_LIMITED_API && CYTHON_METH_FASTCALL + __pyx_vectorcallfunc func_vectorcall; +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *func_weakreflist; +#endif +#if PY_VERSION_HEX < 0x030C0000 || CYTHON_COMPILING_IN_LIMITED_API + PyObject *func_dict; +#endif + PyObject *func_name; + PyObject *func_qualname; + PyObject *func_doc; + PyObject *func_globals; + PyObject *func_code; + PyObject *func_closure; +#if PY_VERSION_HEX < 0x030900B1 || CYTHON_COMPILING_IN_LIMITED_API + PyObject *func_classobj; +#endif + PyObject *defaults; + int flags; + PyObject *defaults_tuple; + PyObject *defaults_kwdict; + PyObject *(*defaults_getter)(PyObject *); + PyObject *func_annotations; + PyObject *func_is_coroutine; +} __pyx_CyFunctionObject; +#undef __Pyx_CyOrPyCFunction_Check +#define __Pyx_CyFunction_Check(obj) __Pyx_TypeCheck(obj, __pyx_mstate_global->__pyx_CyFunctionType) +#define __Pyx_CyOrPyCFunction_Check(obj) __Pyx_TypeCheck2(obj, __pyx_mstate_global->__pyx_CyFunctionType, &PyCFunction_Type) +#define __Pyx_CyFunction_CheckExact(obj) __Pyx_IS_TYPE(obj, __pyx_mstate_global->__pyx_CyFunctionType) +static CYTHON_INLINE int __Pyx__IsSameCyOrCFunction(PyObject *func, void (*cfunc)(void)); +#undef __Pyx_IsSameCFunction +#define __Pyx_IsSameCFunction(func, cfunc) __Pyx__IsSameCyOrCFunction(func, cfunc) +static PyObject *__Pyx_CyFunction_Init(__pyx_CyFunctionObject* op, PyMethodDef *ml, + int flags, PyObject* qualname, + PyObject *closure, + PyObject *module, PyObject *globals, + PyObject* code); +static CYTHON_INLINE void __Pyx__CyFunction_SetClassObj(__pyx_CyFunctionObject* f, PyObject* classobj); +static CYTHON_INLINE PyObject *__Pyx_CyFunction_InitDefaults(PyObject *func, + PyTypeObject *defaults_type); +static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsTuple(PyObject *m, + PyObject *tuple); +static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsKwDict(PyObject *m, + PyObject *dict); +static CYTHON_INLINE void __Pyx_CyFunction_SetAnnotationsDict(PyObject *m, + PyObject *dict); +static int __pyx_CyFunction_init(PyObject *module); +#if CYTHON_METH_FASTCALL +static PyObject * __Pyx_CyFunction_Vectorcall_NOARGS(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames); +static PyObject * __Pyx_CyFunction_Vectorcall_O(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames); +static PyObject * __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames); +static PyObject * __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS_METHOD(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames); +#if CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_CyFunction_func_vectorcall(f) (((__pyx_CyFunctionObject*)f)->func_vectorcall) +#else +#define __Pyx_CyFunction_func_vectorcall(f) (((PyCFunctionObject*)f)->vectorcall) +#endif +#endif + +/* CythonFunction.proto */ +static PyObject *__Pyx_CyFunction_New(PyMethodDef *ml, + int flags, PyObject* qualname, + PyObject *closure, + PyObject *module, PyObject *globals, + PyObject* code); + +/* CLineInTraceback.proto (used by AddTraceback) */ +#if CYTHON_CLINE_IN_TRACEBACK && CYTHON_CLINE_IN_TRACEBACK_RUNTIME +static int __Pyx_CLineForTraceback(PyThreadState *tstate, int c_line); +#else +#define __Pyx_CLineForTraceback(tstate, c_line) (((CYTHON_CLINE_IN_TRACEBACK)) ? c_line : 0) +#endif + +/* CodeObjectCache.proto (used by AddTraceback) */ +#if CYTHON_COMPILING_IN_LIMITED_API +typedef PyObject __Pyx_CachedCodeObjectType; +#else +typedef PyCodeObject __Pyx_CachedCodeObjectType; +#endif +typedef struct { + __Pyx_CachedCodeObjectType* code_object; + int code_line; +} __Pyx_CodeObjectCacheEntry; +struct __Pyx_CodeObjectCache { + int count; + int max_count; + __Pyx_CodeObjectCacheEntry* entries; + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + __pyx_atomic_int_type accessor_count; + #endif +}; +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); +static __Pyx_CachedCodeObjectType *__pyx_find_code_object(int code_line); +static void __pyx_insert_code_object(int code_line, __Pyx_CachedCodeObjectType* code_object); + +/* AddTraceback.proto */ +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename); + +/* CheckUnpickleChecksum.proto */ +static CYTHON_INLINE int __Pyx_CheckUnpickleChecksum(long checksum, long checksum1, long checksum2, long checksum3, const char *members); + +/* GCCDiagnostics.proto */ +#if !defined(__INTEL_COMPILER) && defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) +#define __Pyx_HAS_GCC_DIAGNOSTIC +#endif + +/* CIntFromPy.proto */ +static CYTHON_INLINE long __Pyx_PyLong_As_long(PyObject *); + +/* CIntToPy.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyLong_From___pyx_anon_enum(int value); + +/* CIntFromPy.proto */ +static CYTHON_INLINE int __Pyx_PyLong_As_int(PyObject *); + +/* CIntToPy.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyLong_From_long(long value); + +/* PyObjectCall2Args.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call2Args(PyObject* function, PyObject* arg1, PyObject* arg2); + +/* PyObjectCallMethod1.proto */ +static PyObject* __Pyx_PyObject_CallMethod1(PyObject* obj, PyObject* method_name, PyObject* arg); + +/* UpdateUnpickledDict.proto */ +static int __Pyx_UpdateUnpickledDict(PyObject *obj, PyObject *state, Py_ssize_t index); + +/* FormatTypeName.proto */ +#if CYTHON_COMPILING_IN_LIMITED_API +typedef PyObject *__Pyx_TypeName; +#define __Pyx_FMT_TYPENAME "%U" +#define __Pyx_DECREF_TypeName(obj) Py_XDECREF(obj) +#if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 +#define __Pyx_PyType_GetFullyQualifiedName PyType_GetFullyQualifiedName +#else +static __Pyx_TypeName __Pyx_PyType_GetFullyQualifiedName(PyTypeObject* tp); +#endif +#else // !LIMITED_API +typedef const char *__Pyx_TypeName; +#define __Pyx_FMT_TYPENAME "%.200s" +#define __Pyx_PyType_GetFullyQualifiedName(tp) ((tp)->tp_name) +#define __Pyx_DECREF_TypeName(obj) +#endif + +/* FastTypeChecks.proto */ +#if CYTHON_COMPILING_IN_CPYTHON +#define __Pyx_TypeCheck(obj, type) __Pyx_IsSubtype(Py_TYPE(obj), (PyTypeObject *)type) +#define __Pyx_TypeCheck2(obj, type1, type2) __Pyx_IsAnySubtype2(Py_TYPE(obj), (PyTypeObject *)type1, (PyTypeObject *)type2) +static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b); +static CYTHON_INLINE int __Pyx_IsAnySubtype2(PyTypeObject *cls, PyTypeObject *a, PyTypeObject *b); +static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches(PyObject *err, PyObject *type); +static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches2(PyObject *err, PyObject *type1, PyObject *type2); +#else +#define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) +#define __Pyx_TypeCheck2(obj, type1, type2) (PyObject_TypeCheck(obj, (PyTypeObject *)type1) || PyObject_TypeCheck(obj, (PyTypeObject *)type2)) +#define __Pyx_PyErr_GivenExceptionMatches(err, type) PyErr_GivenExceptionMatches(err, type) +static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches2(PyObject *err, PyObject *type1, PyObject *type2) { + return PyErr_GivenExceptionMatches(err, type1) || PyErr_GivenExceptionMatches(err, type2); +} +#endif +#define __Pyx_PyErr_ExceptionMatches2(err1, err2) __Pyx_PyErr_GivenExceptionMatches2(__Pyx_PyErr_CurrentExceptionType(), err1, err2) +#define __Pyx_PyException_Check(obj) __Pyx_TypeCheck(obj, PyExc_Exception) +#ifdef PyExceptionInstance_Check + #define __Pyx_PyBaseException_Check(obj) PyExceptionInstance_Check(obj) +#else + #define __Pyx_PyBaseException_Check(obj) __Pyx_TypeCheck(obj, PyExc_BaseException) +#endif + +/* GetRuntimeVersion.proto */ +#if __PYX_LIMITED_VERSION_HEX < 0x030b0000 +static unsigned long __Pyx_cached_runtime_version = 0; +static void __Pyx_init_runtime_version(void); +#else +#define __Pyx_init_runtime_version() +#endif +static unsigned long __Pyx_get_runtime_version(void); + +/* CheckBinaryVersion.proto */ +static int __Pyx_check_binary_version(unsigned long ct_version, unsigned long rt_version, int allow_newer); + +/* DecompressString.proto */ +static PyObject *__Pyx_DecompressString(const char *s, Py_ssize_t length, int algo); + +/* MultiPhaseInitModuleState.proto */ +#if CYTHON_PEP489_MULTI_PHASE_INIT && CYTHON_USE_MODULE_STATE +static PyObject *__Pyx_State_FindModule(void*); +static int __Pyx_State_AddModule(PyObject* module, void*); +static int __Pyx_State_RemoveModule(void*); +#elif CYTHON_USE_MODULE_STATE +#define __Pyx_State_FindModule PyState_FindModule +#define __Pyx_State_AddModule PyState_AddModule +#define __Pyx_State_RemoveModule PyState_RemoveModule +#endif + +/* #### Code section: module_declarations ### */ +/* CythonABIVersion.proto */ +#if CYTHON_COMPILING_IN_LIMITED_API + #if CYTHON_METH_FASTCALL + #define __PYX_FASTCALL_ABI_SUFFIX "_fastcall" + #else + #define __PYX_FASTCALL_ABI_SUFFIX + #endif + #define __PYX_LIMITED_ABI_SUFFIX "limited" __PYX_FASTCALL_ABI_SUFFIX __PYX_AM_SEND_ABI_SUFFIX +#else + #define __PYX_LIMITED_ABI_SUFFIX +#endif +#if __PYX_HAS_PY_AM_SEND == 1 + #define __PYX_AM_SEND_ABI_SUFFIX +#elif __PYX_HAS_PY_AM_SEND == 2 + #define __PYX_AM_SEND_ABI_SUFFIX "amsendbackport" +#else + #define __PYX_AM_SEND_ABI_SUFFIX "noamsend" +#endif +#ifndef __PYX_MONITORING_ABI_SUFFIX + #define __PYX_MONITORING_ABI_SUFFIX +#endif +#if CYTHON_USE_TP_FINALIZE + #define __PYX_TP_FINALIZE_ABI_SUFFIX +#else + #define __PYX_TP_FINALIZE_ABI_SUFFIX "nofinalize" +#endif +#if CYTHON_USE_FREELISTS || !defined(__Pyx_AsyncGen_USED) + #define __PYX_FREELISTS_ABI_SUFFIX +#else + #define __PYX_FREELISTS_ABI_SUFFIX "nofreelists" +#endif +#define CYTHON_ABI __PYX_ABI_VERSION __PYX_LIMITED_ABI_SUFFIX __PYX_MONITORING_ABI_SUFFIX __PYX_TP_FINALIZE_ABI_SUFFIX __PYX_FREELISTS_ABI_SUFFIX __PYX_AM_SEND_ABI_SUFFIX +#define __PYX_ABI_MODULE_NAME "_cython_" CYTHON_ABI +#define __PYX_TYPE_MODULE_PREFIX __PYX_ABI_MODULE_NAME "." + +static PyObject *__pyx_f_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_c_write(struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *__pyx_v_self, char const *__pyx_v_data, int __pyx_v_sz); /* proto*/ +static PyObject *__pyx_f_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_c_flush(struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *__pyx_v_self); /* proto*/ +static PyObject *__pyx_f_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_c_read(struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *__pyx_v_self, int __pyx_v_sz, char *__pyx_v_out); /* proto*/ + +/* Module declarations from "thriftpy2.transport.cybase" */ + +/* Module declarations from "libc.string" */ + +/* Module declarations from "thriftpy2.transport.sasl.cysasl" */ +static PyObject *__pyx_f_9thriftpy2_9transport_4sasl_6cysasl___pyx_unpickle_TCySaslClientTransport__set_state(struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *, PyObject *); /*proto*/ +/* #### Code section: typeinfo ### */ +/* #### Code section: before_global_var ### */ +#define __Pyx_MODULE_NAME "thriftpy2.transport.sasl.cysasl" +extern int __pyx_module_is_main_thriftpy2__transport__sasl__cysasl; +int __pyx_module_is_main_thriftpy2__transport__sasl__cysasl = 0; + +/* Implementation of "thriftpy2.transport.sasl.cysasl" */ +/* #### Code section: global_var ### */ +/* #### Code section: string_decls ### */ +static const char __pyx_k_TCySaslClientTransport__rbuf__T[] = "_TCySaslClientTransport__rbuf, _TCySaslClientTransport__wbuf, encode, encode_decided, mechanism, opened, sasl, sasl_client_factory, trans"; +/* #### Code section: decls ### */ +static int __pyx_pf_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport___init__(struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *__pyx_v_self, PyObject *__pyx_v_sasl_client_factory, PyObject *__pyx_v_mechanism, PyObject *__pyx_v_trans); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_2is_open(struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_4open(struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_6_send_message(struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *__pyx_v_self, PyObject *__pyx_v_status, PyObject *__pyx_v_body); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_8_recv_sasl_message(struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_10write(struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *__pyx_v_self, PyObject *__pyx_v_data); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_12flush(struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_14_flushEncoded(struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *__pyx_v_self, PyObject *__pyx_v_buffer); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_16_flushPlain(struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *__pyx_v_self, PyObject *__pyx_v_buffer); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_18read(struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *__pyx_v_self, PyObject *__pyx_v_sz); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_20_read_frame(struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_22clean(struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_24close(struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_26__reduce_cython__(struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_28__setstate_cython__(struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *__pyx_v_self, PyObject *__pyx_v___pyx_state); /* proto */ +static PyObject *__pyx_pf_9thriftpy2_9transport_4sasl_6cysasl___pyx_unpickle_TCySaslClientTransport(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v___pyx_type, long __pyx_v___pyx_checksum, PyObject *__pyx_v___pyx_state); /* proto */ +static PyObject *__pyx_tp_new_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +/* #### Code section: late_includes ### */ +/* #### Code section: module_state ### */ +/* SmallCodeConfig */ +#ifndef CYTHON_SMALL_CODE +#if defined(__clang__) + #define CYTHON_SMALL_CODE +#elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) + #define CYTHON_SMALL_CODE __attribute__((cold)) +#else + #define CYTHON_SMALL_CODE +#endif +#endif + +typedef struct { + PyObject *__pyx_d; + PyObject *__pyx_b; + PyObject *__pyx_cython_runtime; + PyObject *__pyx_empty_tuple; + PyObject *__pyx_empty_bytes; + PyObject *__pyx_empty_unicode; + PyTypeObject *__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer; + PyTypeObject *__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase; + PyObject *__pyx_type_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport; + PyTypeObject *__pyx_ptype_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport; + __Pyx_CachedCFunction __pyx_umethod_PyDict_Type_items; + __Pyx_CachedCFunction __pyx_umethod_PyDict_Type_pop; + __Pyx_CachedCFunction __pyx_umethod_PyDict_Type_values; + PyObject *__pyx_codeobj_tab[15]; + PyObject *__pyx_string_tab[141]; + PyObject *__pyx_number_tab[7]; +/* #### Code section: module_state_contents ### */ +/* CommonTypesMetaclass.module_state_decls */ +PyTypeObject *__pyx_CommonTypesMetaclassType; + +/* CachedMethodType.module_state_decls */ +#if CYTHON_COMPILING_IN_LIMITED_API +PyObject *__Pyx_CachedMethodType; +#endif + +/* CythonFunctionShared.module_state_decls */ +PyTypeObject *__pyx_CyFunctionType; + +/* CodeObjectCache.module_state_decls */ +struct __Pyx_CodeObjectCache __pyx_code_cache; + +/* #### Code section: module_state_end ### */ +} __pyx_mstatetype; + +#if CYTHON_USE_MODULE_STATE +#ifdef __cplusplus +namespace { +extern struct PyModuleDef __pyx_moduledef; +} /* anonymous namespace */ +#else +static struct PyModuleDef __pyx_moduledef; +#endif + +#define __pyx_mstate_global (__Pyx_PyModule_GetState(__Pyx_State_FindModule(&__pyx_moduledef))) + +#define __pyx_m (__Pyx_State_FindModule(&__pyx_moduledef)) +#else +static __pyx_mstatetype __pyx_mstate_global_static = +#ifdef __cplusplus + {}; +#else + {0}; +#endif +static __pyx_mstatetype * const __pyx_mstate_global = &__pyx_mstate_global_static; +#endif +/* #### Code section: constant_name_defines ### */ +#define __pyx_kp_u_ __pyx_string_tab[0] +#define __pyx_kp_u_Already_open __pyx_string_tab[1] +#define __pyx_kp_u_BI __pyx_string_tab[2] +#define __pyx_kp_u_Bad_SASL_result_s __pyx_string_tab[3] +#define __pyx_kp_u_Bad_status __pyx_string_tab[4] +#define __pyx_kp_u_Could_not_start_SASL_s __pyx_string_tab[5] +#define __pyx_kp_u_DUN_FLUSHING_IN_SASL __pyx_string_tab[6] +#define __pyx_kp_u_I __pyx_string_tab[7] +#define __pyx_kp_u_Note_that_Cython_is_deliberately __pyx_string_tab[8] +#define __pyx_kp_u_Write_to_buffer_error __pyx_string_tab[9] +#define __pyx_kp_u__2 __pyx_string_tab[10] +#define __pyx_kp_u__3 __pyx_string_tab[11] +#define __pyx_kp_u__4 __pyx_string_tab[12] +#define __pyx_kp_u__5 __pyx_string_tab[13] +#define __pyx_kp_u_add_note __pyx_string_tab[14] +#define __pyx_kp_u_disable __pyx_string_tab[15] +#define __pyx_kp_u_enable __pyx_string_tab[16] +#define __pyx_kp_u_gc __pyx_string_tab[17] +#define __pyx_kp_u_isenabled __pyx_string_tab[18] +#define __pyx_kp_u_stringsource __pyx_string_tab[19] +#define __pyx_kp_u_thriftpy2_transport __pyx_string_tab[20] +#define __pyx_kp_u_thriftpy2_transport_base __pyx_string_tab[21] +#define __pyx_kp_u_thriftpy2_transport_sasl_cysasl_2 __pyx_string_tab[22] +#define __pyx_n_u_BAD __pyx_string_tab[23] +#define __pyx_n_u_COMPLETE __pyx_string_tab[24] +#define __pyx_n_u_ERROR __pyx_string_tab[25] +#define __pyx_n_u_NOT_OPEN __pyx_string_tab[26] +#define __pyx_n_u_OK __pyx_string_tab[27] +#define __pyx_n_u_Pyx_PyDict_NextRef __pyx_string_tab[28] +#define __pyx_n_u_START __pyx_string_tab[29] +#define __pyx_n_u_TCySaslClientTransport __pyx_string_tab[30] +#define __pyx_n_u_TCySaslClientTransport___reduce __pyx_string_tab[31] +#define __pyx_n_u_TCySaslClientTransport___setstat __pyx_string_tab[32] +#define __pyx_n_u_TCySaslClientTransport__flushEnc __pyx_string_tab[33] +#define __pyx_n_u_TCySaslClientTransport__flushPla __pyx_string_tab[34] +#define __pyx_n_u_TCySaslClientTransport__read_fra __pyx_string_tab[35] +#define __pyx_n_u_TCySaslClientTransport__recv_sas __pyx_string_tab[36] +#define __pyx_n_u_TCySaslClientTransport__send_mes __pyx_string_tab[37] +#define __pyx_n_u_TCySaslClientTransport_clean __pyx_string_tab[38] +#define __pyx_n_u_TCySaslClientTransport_close __pyx_string_tab[39] +#define __pyx_n_u_TCySaslClientTransport_flush __pyx_string_tab[40] +#define __pyx_n_u_TCySaslClientTransport_is_open __pyx_string_tab[41] +#define __pyx_n_u_TCySaslClientTransport_open __pyx_string_tab[42] +#define __pyx_n_u_TCySaslClientTransport_read __pyx_string_tab[43] +#define __pyx_n_u_TCySaslClientTransport_write __pyx_string_tab[44] +#define __pyx_n_u_TTransportException __pyx_string_tab[45] +#define __pyx_n_u_UNKNOWN __pyx_string_tab[46] +#define __pyx_n_u__3 __pyx_string_tab[47] +#define __pyx_n_u_asyncio_coroutines __pyx_string_tab[48] +#define __pyx_n_u_base __pyx_string_tab[49] +#define __pyx_n_u_body __pyx_string_tab[50] +#define __pyx_n_u_buffer __pyx_string_tab[51] +#define __pyx_n_u_chosen_mech __pyx_string_tab[52] +#define __pyx_n_u_clean __pyx_string_tab[53] +#define __pyx_n_u_cline_in_traceback __pyx_string_tab[54] +#define __pyx_n_u_close __pyx_string_tab[55] +#define __pyx_n_u_d __pyx_string_tab[56] +#define __pyx_n_u_data __pyx_string_tab[57] +#define __pyx_n_u_decode __pyx_string_tab[58] +#define __pyx_n_u_decoded __pyx_string_tab[59] +#define __pyx_n_u_dict __pyx_string_tab[60] +#define __pyx_n_u_dict_2 __pyx_string_tab[61] +#define __pyx_n_u_encode __pyx_string_tab[62] +#define __pyx_n_u_encoded __pyx_string_tab[63] +#define __pyx_n_u_flush __pyx_string_tab[64] +#define __pyx_n_u_flushEncoded __pyx_string_tab[65] +#define __pyx_n_u_flushPlain __pyx_string_tab[66] +#define __pyx_n_u_func __pyx_string_tab[67] +#define __pyx_n_u_getError __pyx_string_tab[68] +#define __pyx_n_u_getstate __pyx_string_tab[69] +#define __pyx_n_u_header __pyx_string_tab[70] +#define __pyx_n_u_initial_response __pyx_string_tab[71] +#define __pyx_n_u_is_coroutine __pyx_string_tab[72] +#define __pyx_n_u_is_open __pyx_string_tab[73] +#define __pyx_n_u_items __pyx_string_tab[74] +#define __pyx_n_u_length __pyx_string_tab[75] +#define __pyx_n_u_main __pyx_string_tab[76] +#define __pyx_n_u_mechanism __pyx_string_tab[77] +#define __pyx_n_u_message __pyx_string_tab[78] +#define __pyx_n_u_module __pyx_string_tab[79] +#define __pyx_n_u_name __pyx_string_tab[80] +#define __pyx_n_u_new __pyx_string_tab[81] +#define __pyx_n_u_open __pyx_string_tab[82] +#define __pyx_n_u_pack __pyx_string_tab[83] +#define __pyx_n_u_payload __pyx_string_tab[84] +#define __pyx_n_u_pop __pyx_string_tab[85] +#define __pyx_n_u_pyx_checksum __pyx_string_tab[86] +#define __pyx_n_u_pyx_result __pyx_string_tab[87] +#define __pyx_n_u_pyx_state __pyx_string_tab[88] +#define __pyx_n_u_pyx_type __pyx_string_tab[89] +#define __pyx_n_u_pyx_unpickle_TCySaslClientTran __pyx_string_tab[90] +#define __pyx_n_u_pyx_vtable __pyx_string_tab[91] +#define __pyx_n_u_qualname __pyx_string_tab[92] +#define __pyx_n_u_read __pyx_string_tab[93] +#define __pyx_n_u_read_frame __pyx_string_tab[94] +#define __pyx_n_u_readall __pyx_string_tab[95] +#define __pyx_n_u_recv_sasl_message __pyx_string_tab[96] +#define __pyx_n_u_reduce __pyx_string_tab[97] +#define __pyx_n_u_reduce_cython __pyx_string_tab[98] +#define __pyx_n_u_reduce_ex __pyx_string_tab[99] +#define __pyx_n_u_response __pyx_string_tab[100] +#define __pyx_n_u_ret __pyx_string_tab[101] +#define __pyx_n_u_sasl_client_factory __pyx_string_tab[102] +#define __pyx_n_u_self __pyx_string_tab[103] +#define __pyx_n_u_send_message __pyx_string_tab[104] +#define __pyx_n_u_set_name __pyx_string_tab[105] +#define __pyx_n_u_setdefault __pyx_string_tab[106] +#define __pyx_n_u_setstate __pyx_string_tab[107] +#define __pyx_n_u_setstate_cython __pyx_string_tab[108] +#define __pyx_n_u_start __pyx_string_tab[109] +#define __pyx_n_u_state __pyx_string_tab[110] +#define __pyx_n_u_status __pyx_string_tab[111] +#define __pyx_n_u_step __pyx_string_tab[112] +#define __pyx_n_u_struct __pyx_string_tab[113] +#define __pyx_n_u_success __pyx_string_tab[114] +#define __pyx_n_u_sz __pyx_string_tab[115] +#define __pyx_n_u_test __pyx_string_tab[116] +#define __pyx_n_u_thriftpy2_transport_sasl_cysasl __pyx_string_tab[117] +#define __pyx_n_u_trans __pyx_string_tab[118] +#define __pyx_n_u_type __pyx_string_tab[119] +#define __pyx_n_u_unpack __pyx_string_tab[120] +#define __pyx_n_u_update __pyx_string_tab[121] +#define __pyx_n_u_use_setstate __pyx_string_tab[122] +#define __pyx_n_u_values __pyx_string_tab[123] +#define __pyx_n_u_write __pyx_string_tab[124] +#define __pyx_kp_b__3 __pyx_string_tab[125] +#define __pyx_kp_b_iso88591_4AV1 __pyx_string_tab[126] +#define __pyx_kp_b_iso88591_A_4t81_e1_4vWA_Q_HD_A_T_fAT_4q_Q __pyx_string_tab[127] +#define __pyx_kp_b_iso88591_A_4uG1A_4q_au_q_t5_F __pyx_string_tab[128] +#define __pyx_kp_b_iso88591_A_F_HA __pyx_string_tab[129] +#define __pyx_kp_b_iso88591_A_F_uAV3ay __pyx_string_tab[130] +#define __pyx_kp_b_iso88591_A_G6_G6 __pyx_string_tab[131] +#define __pyx_kp_b_iso88591_A_V7_F_4_t4q_gRwat6_Zt5_q_t1_B_2 __pyx_string_tab[132] +#define __pyx_kp_b_iso88591_A_V7_wawa_7_A_gQd_q_a_xq __pyx_string_tab[133] +#define __pyx_kp_b_iso88591_A_c_t81F __pyx_string_tab[134] +#define __pyx_kp_b_iso88591_A_t6 __pyx_string_tab[135] +#define __pyx_kp_b_iso88591_A_t81 __pyx_string_tab[136] +#define __pyx_kp_b_iso88591_A_t_aq __pyx_string_tab[137] +#define __pyx_kp_b_iso88591_A_uAWHCq_F_F __pyx_string_tab[138] +#define __pyx_kp_b_iso88591_T_1_5UUYYbbffww_H_H_L_L_U_U_Y_Y __pyx_string_tab[139] +#define __pyx_kp_b_iso88591_q_0_kQR_7_8_9RR_a_1 __pyx_string_tab[140] +#define __pyx_int_0 __pyx_number_tab[0] +#define __pyx_int_1 __pyx_number_tab[1] +#define __pyx_int_2 __pyx_number_tab[2] +#define __pyx_int_3 __pyx_number_tab[3] +#define __pyx_int_4 __pyx_number_tab[4] +#define __pyx_int_5 __pyx_number_tab[5] +#define __pyx_int_2696121 __pyx_number_tab[6] +/* #### Code section: module_state_clear ### */ +#if CYTHON_USE_MODULE_STATE +static CYTHON_SMALL_CODE int __pyx_m_clear(PyObject *m) { + __pyx_mstatetype *clear_module_state = __Pyx_PyModule_GetState(m); + if (!clear_module_state) return 0; + Py_CLEAR(clear_module_state->__pyx_d); + Py_CLEAR(clear_module_state->__pyx_b); + Py_CLEAR(clear_module_state->__pyx_cython_runtime); + Py_CLEAR(clear_module_state->__pyx_empty_tuple); + Py_CLEAR(clear_module_state->__pyx_empty_bytes); + Py_CLEAR(clear_module_state->__pyx_empty_unicode); + #if CYTHON_PEP489_MULTI_PHASE_INIT + __Pyx_State_RemoveModule(NULL); + #endif + Py_CLEAR(clear_module_state->__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer); + Py_CLEAR(clear_module_state->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase); + Py_CLEAR(clear_module_state->__pyx_ptype_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport); + Py_CLEAR(clear_module_state->__pyx_type_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport); + for (int i=0; i<15; ++i) { Py_CLEAR(clear_module_state->__pyx_codeobj_tab[i]); } + for (int i=0; i<141; ++i) { Py_CLEAR(clear_module_state->__pyx_string_tab[i]); } + for (int i=0; i<7; ++i) { Py_CLEAR(clear_module_state->__pyx_number_tab[i]); } +/* #### Code section: module_state_clear_contents ### */ +/* CommonTypesMetaclass.module_state_clear */ +Py_CLEAR(clear_module_state->__pyx_CommonTypesMetaclassType); + +/* CythonFunctionShared.module_state_clear */ +Py_CLEAR(clear_module_state->__pyx_CyFunctionType); + +/* #### Code section: module_state_clear_end ### */ +return 0; +} +#endif +/* #### Code section: module_state_traverse ### */ +#if CYTHON_USE_MODULE_STATE +static CYTHON_SMALL_CODE int __pyx_m_traverse(PyObject *m, visitproc visit, void *arg) { + __pyx_mstatetype *traverse_module_state = __Pyx_PyModule_GetState(m); + if (!traverse_module_state) return 0; + Py_VISIT(traverse_module_state->__pyx_d); + Py_VISIT(traverse_module_state->__pyx_b); + Py_VISIT(traverse_module_state->__pyx_cython_runtime); + __Pyx_VISIT_CONST(traverse_module_state->__pyx_empty_tuple); + __Pyx_VISIT_CONST(traverse_module_state->__pyx_empty_bytes); + __Pyx_VISIT_CONST(traverse_module_state->__pyx_empty_unicode); + Py_VISIT(traverse_module_state->__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer); + Py_VISIT(traverse_module_state->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase); + Py_VISIT(traverse_module_state->__pyx_ptype_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport); + Py_VISIT(traverse_module_state->__pyx_type_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport); + for (int i=0; i<15; ++i) { __Pyx_VISIT_CONST(traverse_module_state->__pyx_codeobj_tab[i]); } + for (int i=0; i<141; ++i) { __Pyx_VISIT_CONST(traverse_module_state->__pyx_string_tab[i]); } + for (int i=0; i<7; ++i) { __Pyx_VISIT_CONST(traverse_module_state->__pyx_number_tab[i]); } +/* #### Code section: module_state_traverse_contents ### */ +/* CommonTypesMetaclass.module_state_traverse */ +Py_VISIT(traverse_module_state->__pyx_CommonTypesMetaclassType); + +/* CythonFunctionShared.module_state_traverse */ +Py_VISIT(traverse_module_state->__pyx_CyFunctionType); + +/* #### Code section: module_state_traverse_end ### */ +return 0; +} +#endif +/* #### Code section: module_code ### */ + +/* "thriftpy2/transport/sasl/cysasl.pyx":32 + * cdef str mechanism + * + * def __init__(self, sasl_client_factory, mechanism, trans): # <<<<<<<<<<<<<< + * """ + * @param sasl_client_factory: a callable that returns a new sasl.Client object +*/ + +/* Python wrapper */ +static int __pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +PyDoc_STRVAR(__pyx_doc_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport___init__, "\n @param sasl_client_factory: a callable that returns a new sasl.Client object\n @param mechanism: the SASL mechanism (e.g. \"GSSAPI\")\n @param trans: the underlying transport over which to communicate.\n "); +#if CYTHON_UPDATE_DESCRIPTOR_DOC +struct wrapperbase __pyx_wrapperbase_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport___init__; +#endif +static int __pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_sasl_client_factory = 0; + PyObject *__pyx_v_mechanism = 0; + PyObject *__pyx_v_trans = 0; + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[3] = {0,0,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return -1; + #endif + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_sasl_client_factory,&__pyx_mstate_global->__pyx_n_u_mechanism,&__pyx_mstate_global->__pyx_n_u_trans,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_VARARGS(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 32, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 3: + values[2] = __Pyx_ArgRef_VARARGS(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(0, 32, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 2: + values[1] = __Pyx_ArgRef_VARARGS(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 32, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_VARARGS(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 32, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "__init__", 0) < (0)) __PYX_ERR(0, 32, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 3; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("__init__", 1, 3, 3, i); __PYX_ERR(0, 32, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 3)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_VARARGS(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 32, __pyx_L3_error) + values[1] = __Pyx_ArgRef_VARARGS(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 32, __pyx_L3_error) + values[2] = __Pyx_ArgRef_VARARGS(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(0, 32, __pyx_L3_error) + } + __pyx_v_sasl_client_factory = values[0]; + __pyx_v_mechanism = values[1]; + __pyx_v_trans = values[2]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__init__", 1, 3, 3, __pyx_nargs); __PYX_ERR(0, 32, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("thriftpy2.transport.sasl.cysasl.TCySaslClientTransport.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport___init__(((struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *)__pyx_v_self), __pyx_v_sasl_client_factory, __pyx_v_mechanism, __pyx_v_trans); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport___init__(struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *__pyx_v_self, PyObject *__pyx_v_sasl_client_factory, PyObject *__pyx_v_mechanism, PyObject *__pyx_v_trans) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + size_t __pyx_t_4; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__init__", 0); + + /* "thriftpy2/transport/sasl/cysasl.pyx":38 + * @param trans: the underlying transport over which to communicate. + * """ + * self.trans = trans # <<<<<<<<<<<<<< + * self.sasl_client_factory = sasl_client_factory + * self.sasl = None +*/ + __Pyx_INCREF(__pyx_v_trans); + __Pyx_GIVEREF(__pyx_v_trans); + __Pyx_GOTREF(__pyx_v_self->__pyx_base.trans); + __Pyx_DECREF(__pyx_v_self->__pyx_base.trans); + __pyx_v_self->__pyx_base.trans = __pyx_v_trans; + + /* "thriftpy2/transport/sasl/cysasl.pyx":39 + * """ + * self.trans = trans + * self.sasl_client_factory = sasl_client_factory # <<<<<<<<<<<<<< + * self.sasl = None + * self.mechanism = mechanism +*/ + __Pyx_INCREF(__pyx_v_sasl_client_factory); + __Pyx_GIVEREF(__pyx_v_sasl_client_factory); + __Pyx_GOTREF(__pyx_v_self->sasl_client_factory); + __Pyx_DECREF(__pyx_v_self->sasl_client_factory); + __pyx_v_self->sasl_client_factory = __pyx_v_sasl_client_factory; + + /* "thriftpy2/transport/sasl/cysasl.pyx":40 + * self.trans = trans + * self.sasl_client_factory = sasl_client_factory + * self.sasl = None # <<<<<<<<<<<<<< + * self.mechanism = mechanism + * self.__wbuf = TCyBuffer(DEFAULT_BUFFER) +*/ + __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(Py_None); + __Pyx_GOTREF(__pyx_v_self->sasl); + __Pyx_DECREF(__pyx_v_self->sasl); + __pyx_v_self->sasl = Py_None; + + /* "thriftpy2/transport/sasl/cysasl.pyx":41 + * self.sasl_client_factory = sasl_client_factory + * self.sasl = None + * self.mechanism = mechanism # <<<<<<<<<<<<<< + * self.__wbuf = TCyBuffer(DEFAULT_BUFFER) + * self.__rbuf = TCyBuffer(DEFAULT_BUFFER) +*/ + __pyx_t_1 = __pyx_v_mechanism; + __Pyx_INCREF(__pyx_t_1); + if (!(likely(PyUnicode_CheckExact(__pyx_t_1))||((__pyx_t_1) == Py_None) || __Pyx_RaiseUnexpectedTypeError("str", __pyx_t_1))) __PYX_ERR(0, 41, __pyx_L1_error) + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF(__pyx_v_self->mechanism); + __Pyx_DECREF(__pyx_v_self->mechanism); + __pyx_v_self->mechanism = ((PyObject*)__pyx_t_1); + __pyx_t_1 = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":42 + * self.sasl = None + * self.mechanism = mechanism + * self.__wbuf = TCyBuffer(DEFAULT_BUFFER) # <<<<<<<<<<<<<< + * self.__rbuf = TCyBuffer(DEFAULT_BUFFER) + * self.encode_decided = False +*/ + __pyx_t_2 = NULL; + __pyx_t_3 = __Pyx_PyLong_From___pyx_anon_enum(__pyx_e_9thriftpy2_9transport_6cybase_DEFAULT_BUFFER); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 42, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, __pyx_t_3}; + __pyx_t_1 = __Pyx_PyObject_FastCall((PyObject*)__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer, __pyx_callargs+__pyx_t_4, (2-__pyx_t_4) | (__pyx_t_4*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 42, __pyx_L1_error) + __Pyx_GOTREF((PyObject *)__pyx_t_1); + } + __Pyx_GIVEREF((PyObject *)__pyx_t_1); + __Pyx_GOTREF((PyObject *)__pyx_v_self->_TCySaslClientTransport__wbuf); + __Pyx_DECREF((PyObject *)__pyx_v_self->_TCySaslClientTransport__wbuf); + __pyx_v_self->_TCySaslClientTransport__wbuf = ((struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":43 + * self.mechanism = mechanism + * self.__wbuf = TCyBuffer(DEFAULT_BUFFER) + * self.__rbuf = TCyBuffer(DEFAULT_BUFFER) # <<<<<<<<<<<<<< + * self.encode_decided = False + * self.encode = False +*/ + __pyx_t_3 = NULL; + __pyx_t_2 = __Pyx_PyLong_From___pyx_anon_enum(__pyx_e_9thriftpy2_9transport_6cybase_DEFAULT_BUFFER); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 43, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_t_2}; + __pyx_t_1 = __Pyx_PyObject_FastCall((PyObject*)__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer, __pyx_callargs+__pyx_t_4, (2-__pyx_t_4) | (__pyx_t_4*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 43, __pyx_L1_error) + __Pyx_GOTREF((PyObject *)__pyx_t_1); + } + __Pyx_GIVEREF((PyObject *)__pyx_t_1); + __Pyx_GOTREF((PyObject *)__pyx_v_self->_TCySaslClientTransport__rbuf); + __Pyx_DECREF((PyObject *)__pyx_v_self->_TCySaslClientTransport__rbuf); + __pyx_v_self->_TCySaslClientTransport__rbuf = ((struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":44 + * self.__wbuf = TCyBuffer(DEFAULT_BUFFER) + * self.__rbuf = TCyBuffer(DEFAULT_BUFFER) + * self.encode_decided = False # <<<<<<<<<<<<<< + * self.encode = False + * +*/ + __pyx_v_self->encode_decided = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":45 + * self.__rbuf = TCyBuffer(DEFAULT_BUFFER) + * self.encode_decided = False + * self.encode = False # <<<<<<<<<<<<<< + * + * def is_open(self): +*/ + __pyx_v_self->encode = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":32 + * cdef str mechanism + * + * def __init__(self, sasl_client_factory, mechanism, trans): # <<<<<<<<<<<<<< + * """ + * @param sasl_client_factory: a callable that returns a new sasl.Client object +*/ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("thriftpy2.transport.sasl.cysasl.TCySaslClientTransport.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/sasl/cysasl.pyx":47 + * self.encode = False + * + * def is_open(self): # <<<<<<<<<<<<<< + * return self.trans.is_open() + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_3is_open(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_3is_open = {"is_open", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_3is_open, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_3is_open(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("is_open (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("is_open", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("is_open", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_2is_open(((struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_2is_open(struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + size_t __pyx_t_3; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("is_open", 0); + + /* "thriftpy2/transport/sasl/cysasl.pyx":48 + * + * def is_open(self): + * return self.trans.is_open() # <<<<<<<<<<<<<< + * + * def open(self): +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __pyx_v_self->__pyx_base.trans; + __Pyx_INCREF(__pyx_t_2); + __pyx_t_3 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, NULL}; + __pyx_t_1 = __Pyx_PyObject_FastCallMethod((PyObject*)__pyx_mstate_global->__pyx_n_u_is_open, __pyx_callargs+__pyx_t_3, (1-__pyx_t_3) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 48, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":47 + * self.encode = False + * + * def is_open(self): # <<<<<<<<<<<<<< + * return self.trans.is_open() + * +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("thriftpy2.transport.sasl.cysasl.TCySaslClientTransport.is_open", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/sasl/cysasl.pyx":50 + * return self.trans.is_open() + * + * def open(self): # <<<<<<<<<<<<<< + * if not self.is_open(): + * self.trans.open() +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_5open(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_5open = {"open", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_5open, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_5open(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("open (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("open", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("open", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_4open(((struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_4open(struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *__pyx_v_self) { + PyObject *__pyx_v_ret = NULL; + PyObject *__pyx_v_chosen_mech = NULL; + PyObject *__pyx_v_initial_response = NULL; + PyObject *__pyx_v_status = NULL; + PyObject *__pyx_v_payload = NULL; + PyObject *__pyx_v_response = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + size_t __pyx_t_3; + int __pyx_t_4; + int __pyx_t_5; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + PyObject *(*__pyx_t_9)(PyObject *); + PyObject *__pyx_t_10 = NULL; + PyObject *__pyx_t_11[5]; + PyObject *__pyx_t_12 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("open", 0); + + /* "thriftpy2/transport/sasl/cysasl.pyx":51 + * + * def open(self): + * if not self.is_open(): # <<<<<<<<<<<<<< + * self.trans.open() + * +*/ + __pyx_t_2 = ((PyObject *)__pyx_v_self); + __Pyx_INCREF(__pyx_t_2); + __pyx_t_3 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, NULL}; + __pyx_t_1 = __Pyx_PyObject_FastCallMethod((PyObject*)__pyx_mstate_global->__pyx_n_u_is_open, __pyx_callargs+__pyx_t_3, (1-__pyx_t_3) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 51, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely((__pyx_t_4 < 0))) __PYX_ERR(0, 51, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_5 = (!__pyx_t_4); + if (__pyx_t_5) { + + /* "thriftpy2/transport/sasl/cysasl.pyx":52 + * def open(self): + * if not self.is_open(): + * self.trans.open() # <<<<<<<<<<<<<< + * + * if self.sasl is not None: +*/ + __pyx_t_2 = __pyx_v_self->__pyx_base.trans; + __Pyx_INCREF(__pyx_t_2); + __pyx_t_3 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, NULL}; + __pyx_t_1 = __Pyx_PyObject_FastCallMethod((PyObject*)__pyx_mstate_global->__pyx_n_u_open, __pyx_callargs+__pyx_t_3, (1-__pyx_t_3) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 52, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":51 + * + * def open(self): + * if not self.is_open(): # <<<<<<<<<<<<<< + * self.trans.open() + * +*/ + } + + /* "thriftpy2/transport/sasl/cysasl.pyx":54 + * self.trans.open() + * + * if self.sasl is not None: # <<<<<<<<<<<<<< + * raise TTransportException( + * type=TTransportException.NOT_OPEN, +*/ + __pyx_t_5 = (__pyx_v_self->sasl != Py_None); + if (unlikely(__pyx_t_5)) { + + /* "thriftpy2/transport/sasl/cysasl.pyx":55 + * + * if self.sasl is not None: + * raise TTransportException( # <<<<<<<<<<<<<< + * type=TTransportException.NOT_OPEN, + * message="Already open!") +*/ + __pyx_t_2 = NULL; + __Pyx_GetModuleGlobalName(__pyx_t_6, __pyx_mstate_global->__pyx_n_u_TTransportException); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 55, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + + /* "thriftpy2/transport/sasl/cysasl.pyx":56 + * if self.sasl is not None: + * raise TTransportException( + * type=TTransportException.NOT_OPEN, # <<<<<<<<<<<<<< + * message="Already open!") + * self.sasl = self.sasl_client_factory() +*/ + __Pyx_GetModuleGlobalName(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_TTransportException); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 56, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_NOT_OPEN); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 56, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_3 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_6))) { + __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_6); + assert(__pyx_t_2); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_6); + __Pyx_INCREF(__pyx_t_2); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_6, __pyx__function); + __pyx_t_3 = 0; + } + #endif + { + PyObject *__pyx_callargs[2 + ((CYTHON_VECTORCALL) ? 2 : 0)] = {__pyx_t_2, NULL}; + __pyx_t_7 = __Pyx_MakeVectorcallBuilderKwds(2); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 55, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + if (__Pyx_VectorcallBuilder_AddArg(__pyx_mstate_global->__pyx_n_u_type, __pyx_t_8, __pyx_t_7, __pyx_callargs+1, 0) < (0)) __PYX_ERR(0, 55, __pyx_L1_error) + if (__Pyx_VectorcallBuilder_AddArg(__pyx_mstate_global->__pyx_n_u_message, __pyx_mstate_global->__pyx_kp_u_Already_open, __pyx_t_7, __pyx_callargs+1, 1) < (0)) __PYX_ERR(0, 55, __pyx_L1_error) + __pyx_t_1 = __Pyx_Object_Vectorcall_CallFromBuilder((PyObject*)__pyx_t_6, __pyx_callargs+__pyx_t_3, (1-__pyx_t_3) | (__pyx_t_3*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET), __pyx_t_7); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 55, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_ERR(0, 55, __pyx_L1_error) + + /* "thriftpy2/transport/sasl/cysasl.pyx":54 + * self.trans.open() + * + * if self.sasl is not None: # <<<<<<<<<<<<<< + * raise TTransportException( + * type=TTransportException.NOT_OPEN, +*/ + } + + /* "thriftpy2/transport/sasl/cysasl.pyx":58 + * type=TTransportException.NOT_OPEN, + * message="Already open!") + * self.sasl = self.sasl_client_factory() # <<<<<<<<<<<<<< + * + * ret, chosen_mech, initial_response = self.sasl.start(self.mechanism) +*/ + __pyx_t_6 = NULL; + __Pyx_INCREF(__pyx_v_self->sasl_client_factory); + __pyx_t_7 = __pyx_v_self->sasl_client_factory; + __pyx_t_3 = 1; + #if CYTHON_UNPACK_METHODS + if (likely(PyMethod_Check(__pyx_t_7))) { + __pyx_t_6 = PyMethod_GET_SELF(__pyx_t_7); + assert(__pyx_t_6); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_7); + __Pyx_INCREF(__pyx_t_6); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_7, __pyx__function); + __pyx_t_3 = 0; + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_6, NULL}; + __pyx_t_1 = __Pyx_PyObject_FastCall((PyObject*)__pyx_t_7, __pyx_callargs+__pyx_t_3, (1-__pyx_t_3) | (__pyx_t_3*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 58, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF(__pyx_v_self->sasl); + __Pyx_DECREF(__pyx_v_self->sasl); + __pyx_v_self->sasl = __pyx_t_1; + __pyx_t_1 = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":60 + * self.sasl = self.sasl_client_factory() + * + * ret, chosen_mech, initial_response = self.sasl.start(self.mechanism) # <<<<<<<<<<<<<< + * if not ret: + * raise TTransportException(type=TTransportException.NOT_OPEN, +*/ + __pyx_t_7 = __pyx_v_self->sasl; + __Pyx_INCREF(__pyx_t_7); + __pyx_t_3 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_7, __pyx_v_self->mechanism}; + __pyx_t_1 = __Pyx_PyObject_FastCallMethod((PyObject*)__pyx_mstate_global->__pyx_n_u_start, __pyx_callargs+__pyx_t_3, (2-__pyx_t_3) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 60, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + if ((likely(PyTuple_CheckExact(__pyx_t_1))) || (PyList_CheckExact(__pyx_t_1))) { + PyObject* sequence = __pyx_t_1; + Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); + if (unlikely(size != 3)) { + if (size > 3) __Pyx_RaiseTooManyValuesError(3); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + __PYX_ERR(0, 60, __pyx_L1_error) + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + if (likely(PyTuple_CheckExact(sequence))) { + __pyx_t_7 = PyTuple_GET_ITEM(sequence, 0); + __Pyx_INCREF(__pyx_t_7); + __pyx_t_6 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_6); + __pyx_t_8 = PyTuple_GET_ITEM(sequence, 2); + __Pyx_INCREF(__pyx_t_8); + } else { + __pyx_t_7 = __Pyx_PyList_GetItemRefFast(sequence, 0, __Pyx_ReferenceSharing_SharedReference); + if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 60, __pyx_L1_error) + __Pyx_XGOTREF(__pyx_t_7); + __pyx_t_6 = __Pyx_PyList_GetItemRefFast(sequence, 1, __Pyx_ReferenceSharing_SharedReference); + if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 60, __pyx_L1_error) + __Pyx_XGOTREF(__pyx_t_6); + __pyx_t_8 = __Pyx_PyList_GetItemRefFast(sequence, 2, __Pyx_ReferenceSharing_SharedReference); + if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 60, __pyx_L1_error) + __Pyx_XGOTREF(__pyx_t_8); + } + #else + __pyx_t_7 = __Pyx_PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 60, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_6 = __Pyx_PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 60, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_8 = __Pyx_PySequence_ITEM(sequence, 2); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 60, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + #endif + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } else { + Py_ssize_t index = -1; + __pyx_t_2 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 60, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_9 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_2); + index = 0; __pyx_t_7 = __pyx_t_9(__pyx_t_2); if (unlikely(!__pyx_t_7)) goto __pyx_L5_unpacking_failed; + __Pyx_GOTREF(__pyx_t_7); + index = 1; __pyx_t_6 = __pyx_t_9(__pyx_t_2); if (unlikely(!__pyx_t_6)) goto __pyx_L5_unpacking_failed; + __Pyx_GOTREF(__pyx_t_6); + index = 2; __pyx_t_8 = __pyx_t_9(__pyx_t_2); if (unlikely(!__pyx_t_8)) goto __pyx_L5_unpacking_failed; + __Pyx_GOTREF(__pyx_t_8); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_9(__pyx_t_2), 3) < (0)) __PYX_ERR(0, 60, __pyx_L1_error) + __pyx_t_9 = NULL; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + goto __pyx_L6_unpacking_done; + __pyx_L5_unpacking_failed:; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_9 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + __PYX_ERR(0, 60, __pyx_L1_error) + __pyx_L6_unpacking_done:; + } + __pyx_v_ret = __pyx_t_7; + __pyx_t_7 = 0; + __pyx_v_chosen_mech = __pyx_t_6; + __pyx_t_6 = 0; + __pyx_v_initial_response = __pyx_t_8; + __pyx_t_8 = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":61 + * + * ret, chosen_mech, initial_response = self.sasl.start(self.mechanism) + * if not ret: # <<<<<<<<<<<<<< + * raise TTransportException(type=TTransportException.NOT_OPEN, + * message=("Could not start SASL: %s" % self.sasl.getError())) +*/ + __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_v_ret); if (unlikely((__pyx_t_5 < 0))) __PYX_ERR(0, 61, __pyx_L1_error) + __pyx_t_4 = (!__pyx_t_5); + if (unlikely(__pyx_t_4)) { + + /* "thriftpy2/transport/sasl/cysasl.pyx":62 + * ret, chosen_mech, initial_response = self.sasl.start(self.mechanism) + * if not ret: + * raise TTransportException(type=TTransportException.NOT_OPEN, # <<<<<<<<<<<<<< + * message=("Could not start SASL: %s" % self.sasl.getError())) + * +*/ + __pyx_t_8 = NULL; + __Pyx_GetModuleGlobalName(__pyx_t_6, __pyx_mstate_global->__pyx_n_u_TTransportException); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 62, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_GetModuleGlobalName(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_TTransportException); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 62, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_NOT_OPEN); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 62, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":63 + * if not ret: + * raise TTransportException(type=TTransportException.NOT_OPEN, + * message=("Could not start SASL: %s" % self.sasl.getError())) # <<<<<<<<<<<<<< + * + * # Send initial response +*/ + __pyx_t_10 = __pyx_v_self->sasl; + __Pyx_INCREF(__pyx_t_10); + __pyx_t_3 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_10, NULL}; + __pyx_t_7 = __Pyx_PyObject_FastCallMethod((PyObject*)__pyx_mstate_global->__pyx_n_u_getError, __pyx_callargs+__pyx_t_3, (1-__pyx_t_3) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_10); __pyx_t_10 = 0; + if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 63, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + } + __pyx_t_10 = __Pyx_PyUnicode_FormatSafe(__pyx_mstate_global->__pyx_kp_u_Could_not_start_SASL_s, __pyx_t_7); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 63, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_3 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_6))) { + __pyx_t_8 = PyMethod_GET_SELF(__pyx_t_6); + assert(__pyx_t_8); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_6); + __Pyx_INCREF(__pyx_t_8); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_6, __pyx__function); + __pyx_t_3 = 0; + } + #endif + { + PyObject *__pyx_callargs[2 + ((CYTHON_VECTORCALL) ? 2 : 0)] = {__pyx_t_8, NULL}; + __pyx_t_7 = __Pyx_MakeVectorcallBuilderKwds(2); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 62, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + if (__Pyx_VectorcallBuilder_AddArg(__pyx_mstate_global->__pyx_n_u_type, __pyx_t_2, __pyx_t_7, __pyx_callargs+1, 0) < (0)) __PYX_ERR(0, 62, __pyx_L1_error) + if (__Pyx_VectorcallBuilder_AddArg(__pyx_mstate_global->__pyx_n_u_message, __pyx_t_10, __pyx_t_7, __pyx_callargs+1, 1) < (0)) __PYX_ERR(0, 62, __pyx_L1_error) + __pyx_t_1 = __Pyx_Object_Vectorcall_CallFromBuilder((PyObject*)__pyx_t_6, __pyx_callargs+__pyx_t_3, (1-__pyx_t_3) | (__pyx_t_3*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET), __pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 62, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_ERR(0, 62, __pyx_L1_error) + + /* "thriftpy2/transport/sasl/cysasl.pyx":61 + * + * ret, chosen_mech, initial_response = self.sasl.start(self.mechanism) + * if not ret: # <<<<<<<<<<<<<< + * raise TTransportException(type=TTransportException.NOT_OPEN, + * message=("Could not start SASL: %s" % self.sasl.getError())) +*/ + } + + /* "thriftpy2/transport/sasl/cysasl.pyx":66 + * + * # Send initial response + * self._send_message(self.START, chosen_mech) # <<<<<<<<<<<<<< + * self._send_message(self.OK, initial_response) + * +*/ + __pyx_t_6 = ((PyObject *)__pyx_v_self); + __Pyx_INCREF(__pyx_t_6); + __pyx_t_7 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_mstate_global->__pyx_n_u_START); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 66, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_3 = 0; + { + PyObject *__pyx_callargs[3] = {__pyx_t_6, __pyx_t_7, __pyx_v_chosen_mech}; + __pyx_t_1 = __Pyx_PyObject_FastCallMethod((PyObject*)__pyx_mstate_global->__pyx_n_u_send_message, __pyx_callargs+__pyx_t_3, (3-__pyx_t_3) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 66, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":67 + * # Send initial response + * self._send_message(self.START, chosen_mech) + * self._send_message(self.OK, initial_response) # <<<<<<<<<<<<<< + * + * # SASL negotiation loop +*/ + __pyx_t_7 = ((PyObject *)__pyx_v_self); + __Pyx_INCREF(__pyx_t_7); + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_mstate_global->__pyx_n_u_OK); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 67, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_3 = 0; + { + PyObject *__pyx_callargs[3] = {__pyx_t_7, __pyx_t_6, __pyx_v_initial_response}; + __pyx_t_1 = __Pyx_PyObject_FastCallMethod((PyObject*)__pyx_mstate_global->__pyx_n_u_send_message, __pyx_callargs+__pyx_t_3, (3-__pyx_t_3) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 67, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":70 + * + * # SASL negotiation loop + * while True: # <<<<<<<<<<<<<< + * status, payload = self._recv_sasl_message() + * if status not in (self.OK, self.COMPLETE): +*/ + while (1) { + + /* "thriftpy2/transport/sasl/cysasl.pyx":71 + * # SASL negotiation loop + * while True: + * status, payload = self._recv_sasl_message() # <<<<<<<<<<<<<< + * if status not in (self.OK, self.COMPLETE): + * raise TTransportException(type=TTransportException.NOT_OPEN, +*/ + __pyx_t_6 = ((PyObject *)__pyx_v_self); + __Pyx_INCREF(__pyx_t_6); + __pyx_t_3 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_6, NULL}; + __pyx_t_1 = __Pyx_PyObject_FastCallMethod((PyObject*)__pyx_mstate_global->__pyx_n_u_recv_sasl_message, __pyx_callargs+__pyx_t_3, (1-__pyx_t_3) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 71, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + if ((likely(PyTuple_CheckExact(__pyx_t_1))) || (PyList_CheckExact(__pyx_t_1))) { + PyObject* sequence = __pyx_t_1; + Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + __PYX_ERR(0, 71, __pyx_L1_error) + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + if (likely(PyTuple_CheckExact(sequence))) { + __pyx_t_6 = PyTuple_GET_ITEM(sequence, 0); + __Pyx_INCREF(__pyx_t_6); + __pyx_t_7 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_7); + } else { + __pyx_t_6 = __Pyx_PyList_GetItemRefFast(sequence, 0, __Pyx_ReferenceSharing_SharedReference); + if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 71, __pyx_L1_error) + __Pyx_XGOTREF(__pyx_t_6); + __pyx_t_7 = __Pyx_PyList_GetItemRefFast(sequence, 1, __Pyx_ReferenceSharing_SharedReference); + if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 71, __pyx_L1_error) + __Pyx_XGOTREF(__pyx_t_7); + } + #else + __pyx_t_6 = __Pyx_PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 71, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = __Pyx_PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 71, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + #endif + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } else { + Py_ssize_t index = -1; + __pyx_t_10 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 71, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_9 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_10); + index = 0; __pyx_t_6 = __pyx_t_9(__pyx_t_10); if (unlikely(!__pyx_t_6)) goto __pyx_L10_unpacking_failed; + __Pyx_GOTREF(__pyx_t_6); + index = 1; __pyx_t_7 = __pyx_t_9(__pyx_t_10); if (unlikely(!__pyx_t_7)) goto __pyx_L10_unpacking_failed; + __Pyx_GOTREF(__pyx_t_7); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_9(__pyx_t_10), 2) < (0)) __PYX_ERR(0, 71, __pyx_L1_error) + __pyx_t_9 = NULL; + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + goto __pyx_L11_unpacking_done; + __pyx_L10_unpacking_failed:; + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + __pyx_t_9 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + __PYX_ERR(0, 71, __pyx_L1_error) + __pyx_L11_unpacking_done:; + } + __Pyx_XDECREF_SET(__pyx_v_status, __pyx_t_6); + __pyx_t_6 = 0; + __Pyx_XDECREF_SET(__pyx_v_payload, __pyx_t_7); + __pyx_t_7 = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":72 + * while True: + * status, payload = self._recv_sasl_message() + * if status not in (self.OK, self.COMPLETE): # <<<<<<<<<<<<<< + * raise TTransportException(type=TTransportException.NOT_OPEN, + * message=("Bad status: %d (%s)" % (status, payload))) +*/ + __Pyx_INCREF(__pyx_v_status); + __pyx_t_1 = __pyx_v_status; + __pyx_t_7 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_mstate_global->__pyx_n_u_OK); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 72, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_6 = PyObject_RichCompare(__pyx_t_1, __pyx_t_7, Py_NE); __Pyx_XGOTREF(__pyx_t_6); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 72, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_6); if (unlikely((__pyx_t_5 < 0))) __PYX_ERR(0, 72, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (__pyx_t_5) { + } else { + __pyx_t_4 = __pyx_t_5; + goto __pyx_L13_bool_binop_done; + } + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_mstate_global->__pyx_n_u_COMPLETE); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 72, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = PyObject_RichCompare(__pyx_t_1, __pyx_t_6, Py_NE); __Pyx_XGOTREF(__pyx_t_7); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 72, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_7); if (unlikely((__pyx_t_5 < 0))) __PYX_ERR(0, 72, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_4 = __pyx_t_5; + __pyx_L13_bool_binop_done:; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_5 = __pyx_t_4; + if (unlikely(__pyx_t_5)) { + + /* "thriftpy2/transport/sasl/cysasl.pyx":73 + * status, payload = self._recv_sasl_message() + * if status not in (self.OK, self.COMPLETE): + * raise TTransportException(type=TTransportException.NOT_OPEN, # <<<<<<<<<<<<<< + * message=("Bad status: %d (%s)" % (status, payload))) + * if status == self.COMPLETE: +*/ + __pyx_t_7 = NULL; + __Pyx_GetModuleGlobalName(__pyx_t_6, __pyx_mstate_global->__pyx_n_u_TTransportException); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 73, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_GetModuleGlobalName(__pyx_t_10, __pyx_mstate_global->__pyx_n_u_TTransportException); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 73, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_10, __pyx_mstate_global->__pyx_n_u_NOT_OPEN); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 73, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":74 + * if status not in (self.OK, self.COMPLETE): + * raise TTransportException(type=TTransportException.NOT_OPEN, + * message=("Bad status: %d (%s)" % (status, payload))) # <<<<<<<<<<<<<< + * if status == self.COMPLETE: + * break +*/ + __pyx_t_10 = __Pyx_PyObject_FormatAndDecref(__Pyx_PyNumber_Long(__pyx_v_status), __pyx_mstate_global->__pyx_n_u_d); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 74, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + __pyx_t_8 = __Pyx_PyObject_FormatSimpleAndDecref(PyObject_Str(__pyx_v_payload), __pyx_mstate_global->__pyx_empty_unicode); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 74, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_11[0] = __pyx_mstate_global->__pyx_kp_u_Bad_status; + __pyx_t_11[1] = __pyx_t_10; + __pyx_t_11[2] = __pyx_mstate_global->__pyx_kp_u_; + __pyx_t_11[3] = __pyx_t_8; + __pyx_t_11[4] = __pyx_mstate_global->__pyx_kp_u__2; + __pyx_t_12 = __Pyx_PyUnicode_Join(__pyx_t_11, 5, 12 + __Pyx_PyUnicode_GET_LENGTH(__pyx_t_10) + 2 + __Pyx_PyUnicode_GET_LENGTH(__pyx_t_8) + 1, 127 | __Pyx_PyUnicode_MAX_CHAR_VALUE(__pyx_t_10) | __Pyx_PyUnicode_MAX_CHAR_VALUE(__pyx_t_8)); + if (unlikely(!__pyx_t_12)) __PYX_ERR(0, 74, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_12); + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_3 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_6))) { + __pyx_t_7 = PyMethod_GET_SELF(__pyx_t_6); + assert(__pyx_t_7); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_6); + __Pyx_INCREF(__pyx_t_7); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_6, __pyx__function); + __pyx_t_3 = 0; + } + #endif + { + PyObject *__pyx_callargs[2 + ((CYTHON_VECTORCALL) ? 2 : 0)] = {__pyx_t_7, NULL}; + __pyx_t_8 = __Pyx_MakeVectorcallBuilderKwds(2); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 73, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + if (__Pyx_VectorcallBuilder_AddArg(__pyx_mstate_global->__pyx_n_u_type, __pyx_t_2, __pyx_t_8, __pyx_callargs+1, 0) < (0)) __PYX_ERR(0, 73, __pyx_L1_error) + if (__Pyx_VectorcallBuilder_AddArg(__pyx_mstate_global->__pyx_n_u_message, __pyx_t_12, __pyx_t_8, __pyx_callargs+1, 1) < (0)) __PYX_ERR(0, 73, __pyx_L1_error) + __pyx_t_1 = __Pyx_Object_Vectorcall_CallFromBuilder((PyObject*)__pyx_t_6, __pyx_callargs+__pyx_t_3, (1-__pyx_t_3) | (__pyx_t_3*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET), __pyx_t_8); + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 73, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_ERR(0, 73, __pyx_L1_error) + + /* "thriftpy2/transport/sasl/cysasl.pyx":72 + * while True: + * status, payload = self._recv_sasl_message() + * if status not in (self.OK, self.COMPLETE): # <<<<<<<<<<<<<< + * raise TTransportException(type=TTransportException.NOT_OPEN, + * message=("Bad status: %d (%s)" % (status, payload))) +*/ + } + + /* "thriftpy2/transport/sasl/cysasl.pyx":75 + * raise TTransportException(type=TTransportException.NOT_OPEN, + * message=("Bad status: %d (%s)" % (status, payload))) + * if status == self.COMPLETE: # <<<<<<<<<<<<<< + * break + * ret, response = self.sasl.step(payload) +*/ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_mstate_global->__pyx_n_u_COMPLETE); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 75, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_6 = PyObject_RichCompare(__pyx_v_status, __pyx_t_1, Py_EQ); __Pyx_XGOTREF(__pyx_t_6); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 75, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_6); if (unlikely((__pyx_t_5 < 0))) __PYX_ERR(0, 75, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (__pyx_t_5) { + + /* "thriftpy2/transport/sasl/cysasl.pyx":76 + * message=("Bad status: %d (%s)" % (status, payload))) + * if status == self.COMPLETE: + * break # <<<<<<<<<<<<<< + * ret, response = self.sasl.step(payload) + * if not ret: +*/ + goto __pyx_L9_break; + + /* "thriftpy2/transport/sasl/cysasl.pyx":75 + * raise TTransportException(type=TTransportException.NOT_OPEN, + * message=("Bad status: %d (%s)" % (status, payload))) + * if status == self.COMPLETE: # <<<<<<<<<<<<<< + * break + * ret, response = self.sasl.step(payload) +*/ + } + + /* "thriftpy2/transport/sasl/cysasl.pyx":77 + * if status == self.COMPLETE: + * break + * ret, response = self.sasl.step(payload) # <<<<<<<<<<<<<< + * if not ret: + * raise TTransportException(type=TTransportException.NOT_OPEN, +*/ + __pyx_t_1 = __pyx_v_self->sasl; + __Pyx_INCREF(__pyx_t_1); + __pyx_t_3 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_1, __pyx_v_payload}; + __pyx_t_6 = __Pyx_PyObject_FastCallMethod((PyObject*)__pyx_mstate_global->__pyx_n_u_step, __pyx_callargs+__pyx_t_3, (2-__pyx_t_3) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 77, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + } + if ((likely(PyTuple_CheckExact(__pyx_t_6))) || (PyList_CheckExact(__pyx_t_6))) { + PyObject* sequence = __pyx_t_6; + Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + __PYX_ERR(0, 77, __pyx_L1_error) + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + if (likely(PyTuple_CheckExact(sequence))) { + __pyx_t_1 = PyTuple_GET_ITEM(sequence, 0); + __Pyx_INCREF(__pyx_t_1); + __pyx_t_8 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_8); + } else { + __pyx_t_1 = __Pyx_PyList_GetItemRefFast(sequence, 0, __Pyx_ReferenceSharing_SharedReference); + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 77, __pyx_L1_error) + __Pyx_XGOTREF(__pyx_t_1); + __pyx_t_8 = __Pyx_PyList_GetItemRefFast(sequence, 1, __Pyx_ReferenceSharing_SharedReference); + if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 77, __pyx_L1_error) + __Pyx_XGOTREF(__pyx_t_8); + } + #else + __pyx_t_1 = __Pyx_PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 77, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_8 = __Pyx_PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 77, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + #endif + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + } else { + Py_ssize_t index = -1; + __pyx_t_12 = PyObject_GetIter(__pyx_t_6); if (unlikely(!__pyx_t_12)) __PYX_ERR(0, 77, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_12); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_9 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_12); + index = 0; __pyx_t_1 = __pyx_t_9(__pyx_t_12); if (unlikely(!__pyx_t_1)) goto __pyx_L16_unpacking_failed; + __Pyx_GOTREF(__pyx_t_1); + index = 1; __pyx_t_8 = __pyx_t_9(__pyx_t_12); if (unlikely(!__pyx_t_8)) goto __pyx_L16_unpacking_failed; + __Pyx_GOTREF(__pyx_t_8); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_9(__pyx_t_12), 2) < (0)) __PYX_ERR(0, 77, __pyx_L1_error) + __pyx_t_9 = NULL; + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + goto __pyx_L17_unpacking_done; + __pyx_L16_unpacking_failed:; + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __pyx_t_9 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + __PYX_ERR(0, 77, __pyx_L1_error) + __pyx_L17_unpacking_done:; + } + __Pyx_DECREF_SET(__pyx_v_ret, __pyx_t_1); + __pyx_t_1 = 0; + __Pyx_XDECREF_SET(__pyx_v_response, __pyx_t_8); + __pyx_t_8 = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":78 + * break + * ret, response = self.sasl.step(payload) + * if not ret: # <<<<<<<<<<<<<< + * raise TTransportException(type=TTransportException.NOT_OPEN, + * message=("Bad SASL result: %s" % (self.sasl.getError()))) +*/ + __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_v_ret); if (unlikely((__pyx_t_5 < 0))) __PYX_ERR(0, 78, __pyx_L1_error) + __pyx_t_4 = (!__pyx_t_5); + if (unlikely(__pyx_t_4)) { + + /* "thriftpy2/transport/sasl/cysasl.pyx":79 + * ret, response = self.sasl.step(payload) + * if not ret: + * raise TTransportException(type=TTransportException.NOT_OPEN, # <<<<<<<<<<<<<< + * message=("Bad SASL result: %s" % (self.sasl.getError()))) + * self._send_message(self.OK, response) +*/ + __pyx_t_8 = NULL; + __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_mstate_global->__pyx_n_u_TTransportException); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 79, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_GetModuleGlobalName(__pyx_t_12, __pyx_mstate_global->__pyx_n_u_TTransportException); if (unlikely(!__pyx_t_12)) __PYX_ERR(0, 79, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_12); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_12, __pyx_mstate_global->__pyx_n_u_NOT_OPEN); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 79, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":80 + * if not ret: + * raise TTransportException(type=TTransportException.NOT_OPEN, + * message=("Bad SASL result: %s" % (self.sasl.getError()))) # <<<<<<<<<<<<<< + * self._send_message(self.OK, response) + * +*/ + __pyx_t_7 = __pyx_v_self->sasl; + __Pyx_INCREF(__pyx_t_7); + __pyx_t_3 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_7, NULL}; + __pyx_t_12 = __Pyx_PyObject_FastCallMethod((PyObject*)__pyx_mstate_global->__pyx_n_u_getError, __pyx_callargs+__pyx_t_3, (1-__pyx_t_3) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + if (unlikely(!__pyx_t_12)) __PYX_ERR(0, 80, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_12); + } + __pyx_t_7 = __Pyx_PyUnicode_FormatSafe(__pyx_mstate_global->__pyx_kp_u_Bad_SASL_result_s, __pyx_t_12); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 80, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __pyx_t_3 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_1))) { + __pyx_t_8 = PyMethod_GET_SELF(__pyx_t_1); + assert(__pyx_t_8); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_1); + __Pyx_INCREF(__pyx_t_8); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_1, __pyx__function); + __pyx_t_3 = 0; + } + #endif + { + PyObject *__pyx_callargs[2 + ((CYTHON_VECTORCALL) ? 2 : 0)] = {__pyx_t_8, NULL}; + __pyx_t_12 = __Pyx_MakeVectorcallBuilderKwds(2); if (unlikely(!__pyx_t_12)) __PYX_ERR(0, 79, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_12); + if (__Pyx_VectorcallBuilder_AddArg(__pyx_mstate_global->__pyx_n_u_type, __pyx_t_2, __pyx_t_12, __pyx_callargs+1, 0) < (0)) __PYX_ERR(0, 79, __pyx_L1_error) + if (__Pyx_VectorcallBuilder_AddArg(__pyx_mstate_global->__pyx_n_u_message, __pyx_t_7, __pyx_t_12, __pyx_callargs+1, 1) < (0)) __PYX_ERR(0, 79, __pyx_L1_error) + __pyx_t_6 = __Pyx_Object_Vectorcall_CallFromBuilder((PyObject*)__pyx_t_1, __pyx_callargs+__pyx_t_3, (1-__pyx_t_3) | (__pyx_t_3*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET), __pyx_t_12); + __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 79, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + } + __Pyx_Raise(__pyx_t_6, 0, 0, 0); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __PYX_ERR(0, 79, __pyx_L1_error) + + /* "thriftpy2/transport/sasl/cysasl.pyx":78 + * break + * ret, response = self.sasl.step(payload) + * if not ret: # <<<<<<<<<<<<<< + * raise TTransportException(type=TTransportException.NOT_OPEN, + * message=("Bad SASL result: %s" % (self.sasl.getError()))) +*/ + } + + /* "thriftpy2/transport/sasl/cysasl.pyx":81 + * raise TTransportException(type=TTransportException.NOT_OPEN, + * message=("Bad SASL result: %s" % (self.sasl.getError()))) + * self._send_message(self.OK, response) # <<<<<<<<<<<<<< + * + * def _send_message(self, status, body): +*/ + __pyx_t_1 = ((PyObject *)__pyx_v_self); + __Pyx_INCREF(__pyx_t_1); + __pyx_t_12 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_mstate_global->__pyx_n_u_OK); if (unlikely(!__pyx_t_12)) __PYX_ERR(0, 81, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_12); + __pyx_t_3 = 0; + { + PyObject *__pyx_callargs[3] = {__pyx_t_1, __pyx_t_12, __pyx_v_response}; + __pyx_t_6 = __Pyx_PyObject_FastCallMethod((PyObject*)__pyx_mstate_global->__pyx_n_u_send_message, __pyx_callargs+__pyx_t_3, (3-__pyx_t_3) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 81, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + } + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + } + __pyx_L9_break:; + + /* "thriftpy2/transport/sasl/cysasl.pyx":50 + * return self.trans.is_open() + * + * def open(self): # <<<<<<<<<<<<<< + * if not self.is_open(): + * self.trans.open() +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_XDECREF(__pyx_t_10); + __Pyx_XDECREF(__pyx_t_12); + __Pyx_AddTraceback("thriftpy2.transport.sasl.cysasl.TCySaslClientTransport.open", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_ret); + __Pyx_XDECREF(__pyx_v_chosen_mech); + __Pyx_XDECREF(__pyx_v_initial_response); + __Pyx_XDECREF(__pyx_v_status); + __Pyx_XDECREF(__pyx_v_payload); + __Pyx_XDECREF(__pyx_v_response); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/sasl/cysasl.pyx":83 + * self._send_message(self.OK, response) + * + * def _send_message(self, status, body): # <<<<<<<<<<<<<< + * header = struct.pack(">BI", status, len(body)) + * self.trans.write(header + body) +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_7_send_message(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_7_send_message = {"_send_message", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_7_send_message, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_7_send_message(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_status = 0; + PyObject *__pyx_v_body = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[2] = {0,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("_send_message (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_status,&__pyx_mstate_global->__pyx_n_u_body,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 83, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 2: + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 83, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 83, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "_send_message", 0) < (0)) __PYX_ERR(0, 83, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 2; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("_send_message", 1, 2, 2, i); __PYX_ERR(0, 83, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 2)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 83, __pyx_L3_error) + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 83, __pyx_L3_error) + } + __pyx_v_status = values[0]; + __pyx_v_body = values[1]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("_send_message", 1, 2, 2, __pyx_nargs); __PYX_ERR(0, 83, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("thriftpy2.transport.sasl.cysasl.TCySaslClientTransport._send_message", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_6_send_message(((struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *)__pyx_v_self), __pyx_v_status, __pyx_v_body); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_6_send_message(struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *__pyx_v_self, PyObject *__pyx_v_status, PyObject *__pyx_v_body) { + PyObject *__pyx_v_header = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + Py_ssize_t __pyx_t_5; + size_t __pyx_t_6; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_send_message", 0); + + /* "thriftpy2/transport/sasl/cysasl.pyx":84 + * + * def _send_message(self, status, body): + * header = struct.pack(">BI", status, len(body)) # <<<<<<<<<<<<<< + * self.trans.write(header + body) + * self.trans.flush() +*/ + __pyx_t_2 = NULL; + __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_mstate_global->__pyx_n_u_struct); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 84, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_mstate_global->__pyx_n_u_pack); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 84, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_5 = PyObject_Length(__pyx_v_body); if (unlikely(__pyx_t_5 == ((Py_ssize_t)-1))) __PYX_ERR(0, 84, __pyx_L1_error) + __pyx_t_3 = PyLong_FromSsize_t(__pyx_t_5); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 84, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_6 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_4))) { + __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_4); + assert(__pyx_t_2); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_4); + __Pyx_INCREF(__pyx_t_2); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_4, __pyx__function); + __pyx_t_6 = 0; + } + #endif + { + PyObject *__pyx_callargs[4] = {__pyx_t_2, __pyx_mstate_global->__pyx_kp_u_BI, __pyx_v_status, __pyx_t_3}; + __pyx_t_1 = __Pyx_PyObject_FastCall((PyObject*)__pyx_t_4, __pyx_callargs+__pyx_t_6, (4-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 84, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __pyx_v_header = __pyx_t_1; + __pyx_t_1 = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":85 + * def _send_message(self, status, body): + * header = struct.pack(">BI", status, len(body)) + * self.trans.write(header + body) # <<<<<<<<<<<<<< + * self.trans.flush() + * +*/ + __pyx_t_4 = __pyx_v_self->__pyx_base.trans; + __Pyx_INCREF(__pyx_t_4); + __pyx_t_3 = PyNumber_Add(__pyx_v_header, __pyx_v_body); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 85, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_6 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_4, __pyx_t_3}; + __pyx_t_1 = __Pyx_PyObject_FastCallMethod((PyObject*)__pyx_mstate_global->__pyx_n_u_write, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 85, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":86 + * header = struct.pack(">BI", status, len(body)) + * self.trans.write(header + body) + * self.trans.flush() # <<<<<<<<<<<<<< + * + * def _recv_sasl_message(self): +*/ + __pyx_t_3 = __pyx_v_self->__pyx_base.trans; + __Pyx_INCREF(__pyx_t_3); + __pyx_t_6 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_3, NULL}; + __pyx_t_1 = __Pyx_PyObject_FastCallMethod((PyObject*)__pyx_mstate_global->__pyx_n_u_flush, __pyx_callargs+__pyx_t_6, (1-__pyx_t_6) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 86, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":83 + * self._send_message(self.OK, response) + * + * def _send_message(self, status, body): # <<<<<<<<<<<<<< + * header = struct.pack(">BI", status, len(body)) + * self.trans.write(header + body) +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("thriftpy2.transport.sasl.cysasl.TCySaslClientTransport._send_message", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_header); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/sasl/cysasl.pyx":88 + * self.trans.flush() + * + * def _recv_sasl_message(self): # <<<<<<<<<<<<<< + * header = readall(self.trans.read, 5) + * status, length = struct.unpack(">BI", header) +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_9_recv_sasl_message(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_9_recv_sasl_message = {"_recv_sasl_message", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_9_recv_sasl_message, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_9_recv_sasl_message(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("_recv_sasl_message (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("_recv_sasl_message", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("_recv_sasl_message", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_8_recv_sasl_message(((struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_8_recv_sasl_message(struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *__pyx_v_self) { + PyObject *__pyx_v_header = NULL; + PyObject *__pyx_v_status = NULL; + PyObject *__pyx_v_length = NULL; + PyObject *__pyx_v_payload = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + size_t __pyx_t_5; + PyObject *(*__pyx_t_6)(PyObject *); + int __pyx_t_7; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_recv_sasl_message", 0); + + /* "thriftpy2/transport/sasl/cysasl.pyx":89 + * + * def _recv_sasl_message(self): + * header = readall(self.trans.read, 5) # <<<<<<<<<<<<<< + * status, length = struct.unpack(">BI", header) + * if length > 0: +*/ + __pyx_t_2 = NULL; + __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_mstate_global->__pyx_n_u_readall); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 89, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_self->__pyx_base.trans, __pyx_mstate_global->__pyx_n_u_read); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 89, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_3))) { + __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_3); + assert(__pyx_t_2); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_3); + __Pyx_INCREF(__pyx_t_2); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_3, __pyx__function); + __pyx_t_5 = 0; + } + #endif + { + PyObject *__pyx_callargs[3] = {__pyx_t_2, __pyx_t_4, __pyx_mstate_global->__pyx_int_5}; + __pyx_t_1 = __Pyx_PyObject_FastCall((PyObject*)__pyx_t_3, __pyx_callargs+__pyx_t_5, (3-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 89, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __pyx_v_header = __pyx_t_1; + __pyx_t_1 = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":90 + * def _recv_sasl_message(self): + * header = readall(self.trans.read, 5) + * status, length = struct.unpack(">BI", header) # <<<<<<<<<<<<<< + * if length > 0: + * payload = readall(self.trans.read, length) +*/ + __pyx_t_3 = NULL; + __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_mstate_global->__pyx_n_u_struct); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 90, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_mstate_global->__pyx_n_u_unpack); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 90, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_5 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_2))) { + __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_2); + assert(__pyx_t_3); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_2); + __Pyx_INCREF(__pyx_t_3); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_2, __pyx__function); + __pyx_t_5 = 0; + } + #endif + { + PyObject *__pyx_callargs[3] = {__pyx_t_3, __pyx_mstate_global->__pyx_kp_u_BI, __pyx_v_header}; + __pyx_t_1 = __Pyx_PyObject_FastCall((PyObject*)__pyx_t_2, __pyx_callargs+__pyx_t_5, (3-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 90, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + if ((likely(PyTuple_CheckExact(__pyx_t_1))) || (PyList_CheckExact(__pyx_t_1))) { + PyObject* sequence = __pyx_t_1; + Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + __PYX_ERR(0, 90, __pyx_L1_error) + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + if (likely(PyTuple_CheckExact(sequence))) { + __pyx_t_2 = PyTuple_GET_ITEM(sequence, 0); + __Pyx_INCREF(__pyx_t_2); + __pyx_t_3 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_3); + } else { + __pyx_t_2 = __Pyx_PyList_GetItemRefFast(sequence, 0, __Pyx_ReferenceSharing_SharedReference); + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 90, __pyx_L1_error) + __Pyx_XGOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PyList_GetItemRefFast(sequence, 1, __Pyx_ReferenceSharing_SharedReference); + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 90, __pyx_L1_error) + __Pyx_XGOTREF(__pyx_t_3); + } + #else + __pyx_t_2 = __Pyx_PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 90, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 90, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + #endif + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } else { + Py_ssize_t index = -1; + __pyx_t_4 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 90, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_6 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_4); + index = 0; __pyx_t_2 = __pyx_t_6(__pyx_t_4); if (unlikely(!__pyx_t_2)) goto __pyx_L3_unpacking_failed; + __Pyx_GOTREF(__pyx_t_2); + index = 1; __pyx_t_3 = __pyx_t_6(__pyx_t_4); if (unlikely(!__pyx_t_3)) goto __pyx_L3_unpacking_failed; + __Pyx_GOTREF(__pyx_t_3); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_6(__pyx_t_4), 2) < (0)) __PYX_ERR(0, 90, __pyx_L1_error) + __pyx_t_6 = NULL; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + goto __pyx_L4_unpacking_done; + __pyx_L3_unpacking_failed:; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_6 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + __PYX_ERR(0, 90, __pyx_L1_error) + __pyx_L4_unpacking_done:; + } + __pyx_v_status = __pyx_t_2; + __pyx_t_2 = 0; + __pyx_v_length = __pyx_t_3; + __pyx_t_3 = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":91 + * header = readall(self.trans.read, 5) + * status, length = struct.unpack(">BI", header) + * if length > 0: # <<<<<<<<<<<<<< + * payload = readall(self.trans.read, length) + * else: +*/ + __pyx_t_1 = PyObject_RichCompare(__pyx_v_length, __pyx_mstate_global->__pyx_int_0, Py_GT); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 91, __pyx_L1_error) + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely((__pyx_t_7 < 0))) __PYX_ERR(0, 91, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (__pyx_t_7) { + + /* "thriftpy2/transport/sasl/cysasl.pyx":92 + * status, length = struct.unpack(">BI", header) + * if length > 0: + * payload = readall(self.trans.read, length) # <<<<<<<<<<<<<< + * else: + * payload = "" +*/ + __pyx_t_3 = NULL; + __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_mstate_global->__pyx_n_u_readall); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 92, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_self->__pyx_base.trans, __pyx_mstate_global->__pyx_n_u_read); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 92, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_2))) { + __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_2); + assert(__pyx_t_3); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_2); + __Pyx_INCREF(__pyx_t_3); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_2, __pyx__function); + __pyx_t_5 = 0; + } + #endif + { + PyObject *__pyx_callargs[3] = {__pyx_t_3, __pyx_t_4, __pyx_v_length}; + __pyx_t_1 = __Pyx_PyObject_FastCall((PyObject*)__pyx_t_2, __pyx_callargs+__pyx_t_5, (3-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 92, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __pyx_v_payload = __pyx_t_1; + __pyx_t_1 = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":91 + * header = readall(self.trans.read, 5) + * status, length = struct.unpack(">BI", header) + * if length > 0: # <<<<<<<<<<<<<< + * payload = readall(self.trans.read, length) + * else: +*/ + goto __pyx_L5; + } + + /* "thriftpy2/transport/sasl/cysasl.pyx":94 + * payload = readall(self.trans.read, length) + * else: + * payload = "" # <<<<<<<<<<<<<< + * return status, payload + * +*/ + /*else*/ { + __Pyx_INCREF(__pyx_mstate_global->__pyx_kp_u__3); + __pyx_v_payload = __pyx_mstate_global->__pyx_kp_u__3; + } + __pyx_L5:; + + /* "thriftpy2/transport/sasl/cysasl.pyx":95 + * else: + * payload = "" + * return status, payload # <<<<<<<<<<<<<< + * + * def write(self, bytes data): +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 95, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_v_status); + __Pyx_GIVEREF(__pyx_v_status); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_status) != (0)) __PYX_ERR(0, 95, __pyx_L1_error); + __Pyx_INCREF(__pyx_v_payload); + __Pyx_GIVEREF(__pyx_v_payload); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_payload) != (0)) __PYX_ERR(0, 95, __pyx_L1_error); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":88 + * self.trans.flush() + * + * def _recv_sasl_message(self): # <<<<<<<<<<<<<< + * header = readall(self.trans.read, 5) + * status, length = struct.unpack(">BI", header) +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("thriftpy2.transport.sasl.cysasl.TCySaslClientTransport._recv_sasl_message", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_header); + __Pyx_XDECREF(__pyx_v_status); + __Pyx_XDECREF(__pyx_v_length); + __Pyx_XDECREF(__pyx_v_payload); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/sasl/cysasl.pyx":97 + * return status, payload + * + * def write(self, bytes data): # <<<<<<<<<<<<<< + * cdef int sz = len(data) + * return self.c_write(data, sz) +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_11write(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_11write = {"write", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_11write, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_11write(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_data = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("write (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_data,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 97, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 97, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "write", 0) < (0)) __PYX_ERR(0, 97, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("write", 1, 1, 1, i); __PYX_ERR(0, 97, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 97, __pyx_L3_error) + } + __pyx_v_data = ((PyObject*)values[0]); + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("write", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 97, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("thriftpy2.transport.sasl.cysasl.TCySaslClientTransport.write", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_data), (&PyBytes_Type), 1, "data", 1))) __PYX_ERR(0, 97, __pyx_L1_error) + __pyx_r = __pyx_pf_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_10write(((struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *)__pyx_v_self), __pyx_v_data); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + goto __pyx_L7_cleaned_up; + __pyx_L0:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __pyx_L7_cleaned_up:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_10write(struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *__pyx_v_self, PyObject *__pyx_v_data) { + int __pyx_v_sz; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + char *__pyx_t_2; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("write", 0); + + /* "thriftpy2/transport/sasl/cysasl.pyx":98 + * + * def write(self, bytes data): + * cdef int sz = len(data) # <<<<<<<<<<<<<< + * return self.c_write(data, sz) + * +*/ + if (unlikely(__pyx_v_data == Py_None)) { + PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); + __PYX_ERR(0, 98, __pyx_L1_error) + } + __pyx_t_1 = __Pyx_PyBytes_GET_SIZE(__pyx_v_data); if (unlikely(__pyx_t_1 == ((Py_ssize_t)-1))) __PYX_ERR(0, 98, __pyx_L1_error) + __pyx_v_sz = __pyx_t_1; + + /* "thriftpy2/transport/sasl/cysasl.pyx":99 + * def write(self, bytes data): + * cdef int sz = len(data) + * return self.c_write(data, sz) # <<<<<<<<<<<<<< + * + * cdef c_write(self, const char *data, int sz): +*/ + __Pyx_XDECREF(__pyx_r); + if (unlikely(__pyx_v_data == Py_None)) { + PyErr_SetString(PyExc_TypeError, "expected bytes, NoneType found"); + __PYX_ERR(0, 99, __pyx_L1_error) + } + __pyx_t_2 = __Pyx_PyBytes_AsWritableString(__pyx_v_data); if (unlikely((!__pyx_t_2) && PyErr_Occurred())) __PYX_ERR(0, 99, __pyx_L1_error) + __pyx_t_3 = ((struct __pyx_vtabstruct_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *)__pyx_v_self->__pyx_base.__pyx_vtab)->__pyx_base.c_write(((struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *)__pyx_v_self), __pyx_t_2, __pyx_v_sz); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 99, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":97 + * return status, payload + * + * def write(self, bytes data): # <<<<<<<<<<<<<< + * cdef int sz = len(data) + * return self.c_write(data, sz) +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("thriftpy2.transport.sasl.cysasl.TCySaslClientTransport.write", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/sasl/cysasl.pyx":101 + * return self.c_write(data, sz) + * + * cdef c_write(self, const char *data, int sz): # <<<<<<<<<<<<<< + * cdef: + * int cap = self.__wbuf.buf_size - self.__wbuf.data_size +*/ + +static PyObject *__pyx_f_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_c_write(struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *__pyx_v_self, char const *__pyx_v_data, int __pyx_v_sz) { + int __pyx_v_cap; + int __pyx_v_r; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + size_t __pyx_t_5; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("c_write", 0); + + /* "thriftpy2/transport/sasl/cysasl.pyx":103 + * cdef c_write(self, const char *data, int sz): + * cdef: + * int cap = self.__wbuf.buf_size - self.__wbuf.data_size # <<<<<<<<<<<<<< + * int r + * +*/ + __pyx_v_cap = (__pyx_v_self->_TCySaslClientTransport__wbuf->buf_size - __pyx_v_self->_TCySaslClientTransport__wbuf->data_size); + + /* "thriftpy2/transport/sasl/cysasl.pyx":106 + * int r + * + * if cap < sz: # <<<<<<<<<<<<<< + * self.c_flush() + * +*/ + __pyx_t_1 = (__pyx_v_cap < __pyx_v_sz); + if (__pyx_t_1) { + + /* "thriftpy2/transport/sasl/cysasl.pyx":107 + * + * if cap < sz: + * self.c_flush() # <<<<<<<<<<<<<< + * + * r = self.__wbuf.write(sz, data) +*/ + __pyx_t_2 = ((struct __pyx_vtabstruct_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *)__pyx_v_self->__pyx_base.__pyx_vtab)->__pyx_base.c_flush(((struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *)__pyx_v_self)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 107, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":106 + * int r + * + * if cap < sz: # <<<<<<<<<<<<<< + * self.c_flush() + * +*/ + } + + /* "thriftpy2/transport/sasl/cysasl.pyx":109 + * self.c_flush() + * + * r = self.__wbuf.write(sz, data) # <<<<<<<<<<<<<< + * if r == -1: + * raise MemoryError("Write to buffer error") +*/ + __pyx_t_3 = ((struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_TCyBuffer *)__pyx_v_self->_TCySaslClientTransport__wbuf->__pyx_vtab)->write(__pyx_v_self->_TCySaslClientTransport__wbuf, __pyx_v_sz, __pyx_v_data); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 109, __pyx_L1_error) + __pyx_v_r = __pyx_t_3; + + /* "thriftpy2/transport/sasl/cysasl.pyx":110 + * + * r = self.__wbuf.write(sz, data) + * if r == -1: # <<<<<<<<<<<<<< + * raise MemoryError("Write to buffer error") + * +*/ + __pyx_t_1 = (__pyx_v_r == -1L); + if (unlikely(__pyx_t_1)) { + + /* "thriftpy2/transport/sasl/cysasl.pyx":111 + * r = self.__wbuf.write(sz, data) + * if r == -1: + * raise MemoryError("Write to buffer error") # <<<<<<<<<<<<<< + * + * def flush(self): +*/ + __pyx_t_4 = NULL; + __pyx_t_5 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_4, __pyx_mstate_global->__pyx_kp_u_Write_to_buffer_error}; + __pyx_t_2 = __Pyx_PyObject_FastCall((PyObject*)(((PyTypeObject*)PyExc_MemoryError)), __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 111, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __PYX_ERR(0, 111, __pyx_L1_error) + + /* "thriftpy2/transport/sasl/cysasl.pyx":110 + * + * r = self.__wbuf.write(sz, data) + * if r == -1: # <<<<<<<<<<<<<< + * raise MemoryError("Write to buffer error") + * +*/ + } + + /* "thriftpy2/transport/sasl/cysasl.pyx":101 + * return self.c_write(data, sz) + * + * cdef c_write(self, const char *data, int sz): # <<<<<<<<<<<<<< + * cdef: + * int cap = self.__wbuf.buf_size - self.__wbuf.data_size +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("thriftpy2.transport.sasl.cysasl.TCySaslClientTransport.c_write", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/sasl/cysasl.pyx":113 + * raise MemoryError("Write to buffer error") + * + * def flush(self): # <<<<<<<<<<<<<< + * return self.c_flush() + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_13flush(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_13flush = {"flush", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_13flush, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_13flush(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("flush (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("flush", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("flush", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_12flush(((struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_12flush(struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("flush", 0); + + /* "thriftpy2/transport/sasl/cysasl.pyx":114 + * + * def flush(self): + * return self.c_flush() # <<<<<<<<<<<<<< + * + * cdef c_flush(self): +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = ((struct __pyx_vtabstruct_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *)__pyx_v_self->__pyx_base.__pyx_vtab)->__pyx_base.c_flush(((struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *)__pyx_v_self)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 114, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":113 + * raise MemoryError("Write to buffer error") + * + * def flush(self): # <<<<<<<<<<<<<< + * return self.c_flush() + * +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("thriftpy2.transport.sasl.cysasl.TCySaslClientTransport.flush", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/sasl/cysasl.pyx":116 + * return self.c_flush() + * + * cdef c_flush(self): # <<<<<<<<<<<<<< + * cdef bytes data + * if self.__wbuf.data_size > 0: +*/ + +static PyObject *__pyx_f_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_c_flush(struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *__pyx_v_self) { + PyObject *__pyx_v_data = 0; + PyObject *__pyx_v_success = NULL; + PyObject *__pyx_v_encoded = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + size_t __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *(*__pyx_t_7)(PyObject *); + int __pyx_t_8; + PyObject *__pyx_t_9 = NULL; + PyObject *__pyx_t_10 = NULL; + Py_ssize_t __pyx_t_11; + Py_ssize_t __pyx_t_12; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("c_flush", 0); + + /* "thriftpy2/transport/sasl/cysasl.pyx":118 + * cdef c_flush(self): + * cdef bytes data + * if self.__wbuf.data_size > 0: # <<<<<<<<<<<<<< + * data = self.__wbuf.buf[:self.__wbuf.data_size] + * # The first time we flush data, we send it to sasl.encode() +*/ + __pyx_t_1 = (__pyx_v_self->_TCySaslClientTransport__wbuf->data_size > 0); + if (__pyx_t_1) { + + /* "thriftpy2/transport/sasl/cysasl.pyx":119 + * cdef bytes data + * if self.__wbuf.data_size > 0: + * data = self.__wbuf.buf[:self.__wbuf.data_size] # <<<<<<<<<<<<<< + * # The first time we flush data, we send it to sasl.encode() + * # If the length doesn't change, then we must be using a QOP +*/ + __pyx_t_2 = __Pyx_PyBytes_FromStringAndSize(__pyx_v_self->_TCySaslClientTransport__wbuf->buf + 0, __pyx_v_self->_TCySaslClientTransport__wbuf->data_size - 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 119, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_v_data = ((PyObject*)__pyx_t_2); + __pyx_t_2 = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":124 + * # of auth and we should no longer call sasl.encode(), otherwise + * # we encode every time. + * if not self.encode_decided: # <<<<<<<<<<<<<< + * success, encoded = self.sasl.encode(data) + * if not success: +*/ + __pyx_t_1 = (!__pyx_v_self->encode_decided); + if (__pyx_t_1) { + + /* "thriftpy2/transport/sasl/cysasl.pyx":125 + * # we encode every time. + * if not self.encode_decided: + * success, encoded = self.sasl.encode(data) # <<<<<<<<<<<<<< + * if not success: + * raise TTransportException(type=TTransportException.UNKNOWN, +*/ + __pyx_t_3 = __pyx_v_self->sasl; + __Pyx_INCREF(__pyx_t_3); + __pyx_t_4 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_v_data}; + __pyx_t_2 = __Pyx_PyObject_FastCallMethod((PyObject*)__pyx_mstate_global->__pyx_n_u_encode, __pyx_callargs+__pyx_t_4, (2-__pyx_t_4) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 125, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + if ((likely(PyTuple_CheckExact(__pyx_t_2))) || (PyList_CheckExact(__pyx_t_2))) { + PyObject* sequence = __pyx_t_2; + Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + __PYX_ERR(0, 125, __pyx_L1_error) + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + if (likely(PyTuple_CheckExact(sequence))) { + __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); + __Pyx_INCREF(__pyx_t_3); + __pyx_t_5 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_5); + } else { + __pyx_t_3 = __Pyx_PyList_GetItemRefFast(sequence, 0, __Pyx_ReferenceSharing_SharedReference); + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 125, __pyx_L1_error) + __Pyx_XGOTREF(__pyx_t_3); + __pyx_t_5 = __Pyx_PyList_GetItemRefFast(sequence, 1, __Pyx_ReferenceSharing_SharedReference); + if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 125, __pyx_L1_error) + __Pyx_XGOTREF(__pyx_t_5); + } + #else + __pyx_t_3 = __Pyx_PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 125, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = __Pyx_PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 125, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + #endif + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } else { + Py_ssize_t index = -1; + __pyx_t_6 = PyObject_GetIter(__pyx_t_2); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 125, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_7 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_6); + index = 0; __pyx_t_3 = __pyx_t_7(__pyx_t_6); if (unlikely(!__pyx_t_3)) goto __pyx_L5_unpacking_failed; + __Pyx_GOTREF(__pyx_t_3); + index = 1; __pyx_t_5 = __pyx_t_7(__pyx_t_6); if (unlikely(!__pyx_t_5)) goto __pyx_L5_unpacking_failed; + __Pyx_GOTREF(__pyx_t_5); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_7(__pyx_t_6), 2) < (0)) __PYX_ERR(0, 125, __pyx_L1_error) + __pyx_t_7 = NULL; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + goto __pyx_L6_unpacking_done; + __pyx_L5_unpacking_failed:; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_7 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + __PYX_ERR(0, 125, __pyx_L1_error) + __pyx_L6_unpacking_done:; + } + __pyx_v_success = __pyx_t_3; + __pyx_t_3 = 0; + __pyx_v_encoded = __pyx_t_5; + __pyx_t_5 = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":126 + * if not self.encode_decided: + * success, encoded = self.sasl.encode(data) + * if not success: # <<<<<<<<<<<<<< + * raise TTransportException(type=TTransportException.UNKNOWN, + * message=self.sasl.getError()) +*/ + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_v_success); if (unlikely((__pyx_t_1 < 0))) __PYX_ERR(0, 126, __pyx_L1_error) + __pyx_t_8 = (!__pyx_t_1); + if (unlikely(__pyx_t_8)) { + + /* "thriftpy2/transport/sasl/cysasl.pyx":127 + * success, encoded = self.sasl.encode(data) + * if not success: + * raise TTransportException(type=TTransportException.UNKNOWN, # <<<<<<<<<<<<<< + * message=self.sasl.getError()) + * if (len(encoded)==len(data)): +*/ + __pyx_t_5 = NULL; + __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_mstate_global->__pyx_n_u_TTransportException); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 127, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_GetModuleGlobalName(__pyx_t_6, __pyx_mstate_global->__pyx_n_u_TTransportException); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 127, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_t_6, __pyx_mstate_global->__pyx_n_u_UNKNOWN); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 127, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":128 + * if not success: + * raise TTransportException(type=TTransportException.UNKNOWN, + * message=self.sasl.getError()) # <<<<<<<<<<<<<< + * if (len(encoded)==len(data)): + * self.encode = False +*/ + __pyx_t_10 = __pyx_v_self->sasl; + __Pyx_INCREF(__pyx_t_10); + __pyx_t_4 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_10, NULL}; + __pyx_t_6 = __Pyx_PyObject_FastCallMethod((PyObject*)__pyx_mstate_global->__pyx_n_u_getError, __pyx_callargs+__pyx_t_4, (1-__pyx_t_4) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_10); __pyx_t_10 = 0; + if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 128, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + } + __pyx_t_4 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_3))) { + __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_3); + assert(__pyx_t_5); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_3); + __Pyx_INCREF(__pyx_t_5); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_3, __pyx__function); + __pyx_t_4 = 0; + } + #endif + { + PyObject *__pyx_callargs[2 + ((CYTHON_VECTORCALL) ? 2 : 0)] = {__pyx_t_5, NULL}; + __pyx_t_10 = __Pyx_MakeVectorcallBuilderKwds(2); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 127, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + if (__Pyx_VectorcallBuilder_AddArg(__pyx_mstate_global->__pyx_n_u_type, __pyx_t_9, __pyx_t_10, __pyx_callargs+1, 0) < (0)) __PYX_ERR(0, 127, __pyx_L1_error) + if (__Pyx_VectorcallBuilder_AddArg(__pyx_mstate_global->__pyx_n_u_message, __pyx_t_6, __pyx_t_10, __pyx_callargs+1, 1) < (0)) __PYX_ERR(0, 127, __pyx_L1_error) + __pyx_t_2 = __Pyx_Object_Vectorcall_CallFromBuilder((PyObject*)__pyx_t_3, __pyx_callargs+__pyx_t_4, (1-__pyx_t_4) | (__pyx_t_4*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET), __pyx_t_10); + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 127, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __PYX_ERR(0, 127, __pyx_L1_error) + + /* "thriftpy2/transport/sasl/cysasl.pyx":126 + * if not self.encode_decided: + * success, encoded = self.sasl.encode(data) + * if not success: # <<<<<<<<<<<<<< + * raise TTransportException(type=TTransportException.UNKNOWN, + * message=self.sasl.getError()) +*/ + } + + /* "thriftpy2/transport/sasl/cysasl.pyx":129 + * raise TTransportException(type=TTransportException.UNKNOWN, + * message=self.sasl.getError()) + * if (len(encoded)==len(data)): # <<<<<<<<<<<<<< + * self.encode = False + * self._flushPlain(data) +*/ + __pyx_t_11 = PyObject_Length(__pyx_v_encoded); if (unlikely(__pyx_t_11 == ((Py_ssize_t)-1))) __PYX_ERR(0, 129, __pyx_L1_error) + __pyx_t_12 = __Pyx_PyBytes_GET_SIZE(__pyx_v_data); if (unlikely(__pyx_t_12 == ((Py_ssize_t)-1))) __PYX_ERR(0, 129, __pyx_L1_error) + __pyx_t_8 = (__pyx_t_11 == __pyx_t_12); + if (__pyx_t_8) { + + /* "thriftpy2/transport/sasl/cysasl.pyx":130 + * message=self.sasl.getError()) + * if (len(encoded)==len(data)): + * self.encode = False # <<<<<<<<<<<<<< + * self._flushPlain(data) + * else: +*/ + __pyx_v_self->encode = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":131 + * if (len(encoded)==len(data)): + * self.encode = False + * self._flushPlain(data) # <<<<<<<<<<<<<< + * else: + * self.encode = True +*/ + __pyx_t_3 = ((PyObject *)__pyx_v_self); + __Pyx_INCREF(__pyx_t_3); + __pyx_t_4 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_v_data}; + __pyx_t_2 = __Pyx_PyObject_FastCallMethod((PyObject*)__pyx_mstate_global->__pyx_n_u_flushPlain, __pyx_callargs+__pyx_t_4, (2-__pyx_t_4) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 131, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":129 + * raise TTransportException(type=TTransportException.UNKNOWN, + * message=self.sasl.getError()) + * if (len(encoded)==len(data)): # <<<<<<<<<<<<<< + * self.encode = False + * self._flushPlain(data) +*/ + goto __pyx_L8; + } + + /* "thriftpy2/transport/sasl/cysasl.pyx":133 + * self._flushPlain(data) + * else: + * self.encode = True # <<<<<<<<<<<<<< + * self.trans.write(encoded) + * self.encode_decided = True +*/ + /*else*/ { + __pyx_v_self->encode = 1; + + /* "thriftpy2/transport/sasl/cysasl.pyx":134 + * else: + * self.encode = True + * self.trans.write(encoded) # <<<<<<<<<<<<<< + * self.encode_decided = True + * elif self.encode: +*/ + __pyx_t_3 = __pyx_v_self->__pyx_base.trans; + __Pyx_INCREF(__pyx_t_3); + __pyx_t_4 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_v_encoded}; + __pyx_t_2 = __Pyx_PyObject_FastCallMethod((PyObject*)__pyx_mstate_global->__pyx_n_u_write, __pyx_callargs+__pyx_t_4, (2-__pyx_t_4) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 134, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } + __pyx_L8:; + + /* "thriftpy2/transport/sasl/cysasl.pyx":135 + * self.encode = True + * self.trans.write(encoded) + * self.encode_decided = True # <<<<<<<<<<<<<< + * elif self.encode: + * self._flushEncoded(data) +*/ + __pyx_v_self->encode_decided = 1; + + /* "thriftpy2/transport/sasl/cysasl.pyx":124 + * # of auth and we should no longer call sasl.encode(), otherwise + * # we encode every time. + * if not self.encode_decided: # <<<<<<<<<<<<<< + * success, encoded = self.sasl.encode(data) + * if not success: +*/ + goto __pyx_L4; + } + + /* "thriftpy2/transport/sasl/cysasl.pyx":136 + * self.trans.write(encoded) + * self.encode_decided = True + * elif self.encode: # <<<<<<<<<<<<<< + * self._flushEncoded(data) + * else: +*/ + if (__pyx_v_self->encode) { + + /* "thriftpy2/transport/sasl/cysasl.pyx":137 + * self.encode_decided = True + * elif self.encode: + * self._flushEncoded(data) # <<<<<<<<<<<<<< + * else: + * self._flushPlain(data) +*/ + __pyx_t_3 = ((PyObject *)__pyx_v_self); + __Pyx_INCREF(__pyx_t_3); + __pyx_t_4 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_v_data}; + __pyx_t_2 = __Pyx_PyObject_FastCallMethod((PyObject*)__pyx_mstate_global->__pyx_n_u_flushEncoded, __pyx_callargs+__pyx_t_4, (2-__pyx_t_4) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 137, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":136 + * self.trans.write(encoded) + * self.encode_decided = True + * elif self.encode: # <<<<<<<<<<<<<< + * self._flushEncoded(data) + * else: +*/ + goto __pyx_L4; + } + + /* "thriftpy2/transport/sasl/cysasl.pyx":139 + * self._flushEncoded(data) + * else: + * self._flushPlain(data) # <<<<<<<<<<<<<< + * + * self.trans.flush() +*/ + /*else*/ { + __pyx_t_3 = ((PyObject *)__pyx_v_self); + __Pyx_INCREF(__pyx_t_3); + __pyx_t_4 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_v_data}; + __pyx_t_2 = __Pyx_PyObject_FastCallMethod((PyObject*)__pyx_mstate_global->__pyx_n_u_flushPlain, __pyx_callargs+__pyx_t_4, (2-__pyx_t_4) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 139, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } + __pyx_L4:; + + /* "thriftpy2/transport/sasl/cysasl.pyx":141 + * self._flushPlain(data) + * + * self.trans.flush() # <<<<<<<<<<<<<< + * self.__wbuf.clean() + * return("DUN FLUSHING IN SASL") +*/ + __pyx_t_3 = __pyx_v_self->__pyx_base.trans; + __Pyx_INCREF(__pyx_t_3); + __pyx_t_4 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_3, NULL}; + __pyx_t_2 = __Pyx_PyObject_FastCallMethod((PyObject*)__pyx_mstate_global->__pyx_n_u_flush, __pyx_callargs+__pyx_t_4, (1-__pyx_t_4) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 141, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":142 + * + * self.trans.flush() + * self.__wbuf.clean() # <<<<<<<<<<<<<< + * return("DUN FLUSHING IN SASL") + * +*/ + ((struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_TCyBuffer *)__pyx_v_self->_TCySaslClientTransport__wbuf->__pyx_vtab)->clean(__pyx_v_self->_TCySaslClientTransport__wbuf); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 142, __pyx_L1_error) + + /* "thriftpy2/transport/sasl/cysasl.pyx":118 + * cdef c_flush(self): + * cdef bytes data + * if self.__wbuf.data_size > 0: # <<<<<<<<<<<<<< + * data = self.__wbuf.buf[:self.__wbuf.data_size] + * # The first time we flush data, we send it to sasl.encode() +*/ + } + + /* "thriftpy2/transport/sasl/cysasl.pyx":143 + * self.trans.flush() + * self.__wbuf.clean() + * return("DUN FLUSHING IN SASL") # <<<<<<<<<<<<<< + * + * def _flushEncoded(self, buffer): +*/ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_mstate_global->__pyx_kp_u_DUN_FLUSHING_IN_SASL); + __pyx_r = __pyx_mstate_global->__pyx_kp_u_DUN_FLUSHING_IN_SASL; + goto __pyx_L0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":116 + * return self.c_flush() + * + * cdef c_flush(self): # <<<<<<<<<<<<<< + * cdef bytes data + * if self.__wbuf.data_size > 0: +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_XDECREF(__pyx_t_10); + __Pyx_AddTraceback("thriftpy2.transport.sasl.cysasl.TCySaslClientTransport.c_flush", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_data); + __Pyx_XDECREF(__pyx_v_success); + __Pyx_XDECREF(__pyx_v_encoded); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/sasl/cysasl.pyx":145 + * return("DUN FLUSHING IN SASL") + * + * def _flushEncoded(self, buffer): # <<<<<<<<<<<<<< + * # sasl.ecnode() does the encoding and adds the length header, so nothing + * # to do but call it and write the result. +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_15_flushEncoded(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_15_flushEncoded = {"_flushEncoded", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_15_flushEncoded, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_15_flushEncoded(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_buffer = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("_flushEncoded (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_buffer,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 145, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 145, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "_flushEncoded", 0) < (0)) __PYX_ERR(0, 145, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("_flushEncoded", 1, 1, 1, i); __PYX_ERR(0, 145, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 145, __pyx_L3_error) + } + __pyx_v_buffer = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("_flushEncoded", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 145, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("thriftpy2.transport.sasl.cysasl.TCySaslClientTransport._flushEncoded", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_14_flushEncoded(((struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *)__pyx_v_self), __pyx_v_buffer); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_14_flushEncoded(struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *__pyx_v_self, PyObject *__pyx_v_buffer) { + PyObject *__pyx_v_success = NULL; + PyObject *__pyx_v_encoded = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + size_t __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *(*__pyx_t_6)(PyObject *); + int __pyx_t_7; + int __pyx_t_8; + PyObject *__pyx_t_9 = NULL; + PyObject *__pyx_t_10 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_flushEncoded", 0); + + /* "thriftpy2/transport/sasl/cysasl.pyx":148 + * # sasl.ecnode() does the encoding and adds the length header, so nothing + * # to do but call it and write the result. + * success, encoded = self.sasl.encode(buffer) # <<<<<<<<<<<<<< + * if not success: + * raise TTransportException(type=TTransportException.UNKNOWN, +*/ + __pyx_t_2 = __pyx_v_self->sasl; + __Pyx_INCREF(__pyx_t_2); + __pyx_t_3 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, __pyx_v_buffer}; + __pyx_t_1 = __Pyx_PyObject_FastCallMethod((PyObject*)__pyx_mstate_global->__pyx_n_u_encode, __pyx_callargs+__pyx_t_3, (2-__pyx_t_3) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 148, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + if ((likely(PyTuple_CheckExact(__pyx_t_1))) || (PyList_CheckExact(__pyx_t_1))) { + PyObject* sequence = __pyx_t_1; + Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + __PYX_ERR(0, 148, __pyx_L1_error) + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + if (likely(PyTuple_CheckExact(sequence))) { + __pyx_t_2 = PyTuple_GET_ITEM(sequence, 0); + __Pyx_INCREF(__pyx_t_2); + __pyx_t_4 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_4); + } else { + __pyx_t_2 = __Pyx_PyList_GetItemRefFast(sequence, 0, __Pyx_ReferenceSharing_SharedReference); + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 148, __pyx_L1_error) + __Pyx_XGOTREF(__pyx_t_2); + __pyx_t_4 = __Pyx_PyList_GetItemRefFast(sequence, 1, __Pyx_ReferenceSharing_SharedReference); + if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 148, __pyx_L1_error) + __Pyx_XGOTREF(__pyx_t_4); + } + #else + __pyx_t_2 = __Pyx_PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 148, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = __Pyx_PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 148, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + #endif + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } else { + Py_ssize_t index = -1; + __pyx_t_5 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 148, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_6 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_5); + index = 0; __pyx_t_2 = __pyx_t_6(__pyx_t_5); if (unlikely(!__pyx_t_2)) goto __pyx_L3_unpacking_failed; + __Pyx_GOTREF(__pyx_t_2); + index = 1; __pyx_t_4 = __pyx_t_6(__pyx_t_5); if (unlikely(!__pyx_t_4)) goto __pyx_L3_unpacking_failed; + __Pyx_GOTREF(__pyx_t_4); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_6(__pyx_t_5), 2) < (0)) __PYX_ERR(0, 148, __pyx_L1_error) + __pyx_t_6 = NULL; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + goto __pyx_L4_unpacking_done; + __pyx_L3_unpacking_failed:; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_6 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + __PYX_ERR(0, 148, __pyx_L1_error) + __pyx_L4_unpacking_done:; + } + __pyx_v_success = __pyx_t_2; + __pyx_t_2 = 0; + __pyx_v_encoded = __pyx_t_4; + __pyx_t_4 = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":149 + * # to do but call it and write the result. + * success, encoded = self.sasl.encode(buffer) + * if not success: # <<<<<<<<<<<<<< + * raise TTransportException(type=TTransportException.UNKNOWN, + * message=self.sasl.getError()) +*/ + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_v_success); if (unlikely((__pyx_t_7 < 0))) __PYX_ERR(0, 149, __pyx_L1_error) + __pyx_t_8 = (!__pyx_t_7); + if (unlikely(__pyx_t_8)) { + + /* "thriftpy2/transport/sasl/cysasl.pyx":150 + * success, encoded = self.sasl.encode(buffer) + * if not success: + * raise TTransportException(type=TTransportException.UNKNOWN, # <<<<<<<<<<<<<< + * message=self.sasl.getError()) + * self.trans.write(encoded) +*/ + __pyx_t_4 = NULL; + __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_mstate_global->__pyx_n_u_TTransportException); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 150, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_GetModuleGlobalName(__pyx_t_5, __pyx_mstate_global->__pyx_n_u_TTransportException); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 150, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_mstate_global->__pyx_n_u_UNKNOWN); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 150, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":151 + * if not success: + * raise TTransportException(type=TTransportException.UNKNOWN, + * message=self.sasl.getError()) # <<<<<<<<<<<<<< + * self.trans.write(encoded) + * +*/ + __pyx_t_10 = __pyx_v_self->sasl; + __Pyx_INCREF(__pyx_t_10); + __pyx_t_3 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_10, NULL}; + __pyx_t_5 = __Pyx_PyObject_FastCallMethod((PyObject*)__pyx_mstate_global->__pyx_n_u_getError, __pyx_callargs+__pyx_t_3, (1-__pyx_t_3) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_10); __pyx_t_10 = 0; + if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 151, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + } + __pyx_t_3 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_2))) { + __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_2); + assert(__pyx_t_4); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_2); + __Pyx_INCREF(__pyx_t_4); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_2, __pyx__function); + __pyx_t_3 = 0; + } + #endif + { + PyObject *__pyx_callargs[2 + ((CYTHON_VECTORCALL) ? 2 : 0)] = {__pyx_t_4, NULL}; + __pyx_t_10 = __Pyx_MakeVectorcallBuilderKwds(2); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 150, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + if (__Pyx_VectorcallBuilder_AddArg(__pyx_mstate_global->__pyx_n_u_type, __pyx_t_9, __pyx_t_10, __pyx_callargs+1, 0) < (0)) __PYX_ERR(0, 150, __pyx_L1_error) + if (__Pyx_VectorcallBuilder_AddArg(__pyx_mstate_global->__pyx_n_u_message, __pyx_t_5, __pyx_t_10, __pyx_callargs+1, 1) < (0)) __PYX_ERR(0, 150, __pyx_L1_error) + __pyx_t_1 = __Pyx_Object_Vectorcall_CallFromBuilder((PyObject*)__pyx_t_2, __pyx_callargs+__pyx_t_3, (1-__pyx_t_3) | (__pyx_t_3*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET), __pyx_t_10); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 150, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_ERR(0, 150, __pyx_L1_error) + + /* "thriftpy2/transport/sasl/cysasl.pyx":149 + * # to do but call it and write the result. + * success, encoded = self.sasl.encode(buffer) + * if not success: # <<<<<<<<<<<<<< + * raise TTransportException(type=TTransportException.UNKNOWN, + * message=self.sasl.getError()) +*/ + } + + /* "thriftpy2/transport/sasl/cysasl.pyx":152 + * raise TTransportException(type=TTransportException.UNKNOWN, + * message=self.sasl.getError()) + * self.trans.write(encoded) # <<<<<<<<<<<<<< + * + * def _flushPlain(self, buffer): +*/ + __pyx_t_2 = __pyx_v_self->__pyx_base.trans; + __Pyx_INCREF(__pyx_t_2); + __pyx_t_3 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, __pyx_v_encoded}; + __pyx_t_1 = __Pyx_PyObject_FastCallMethod((PyObject*)__pyx_mstate_global->__pyx_n_u_write, __pyx_callargs+__pyx_t_3, (2-__pyx_t_3) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 152, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":145 + * return("DUN FLUSHING IN SASL") + * + * def _flushEncoded(self, buffer): # <<<<<<<<<<<<<< + * # sasl.ecnode() does the encoding and adds the length header, so nothing + * # to do but call it and write the result. +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_XDECREF(__pyx_t_10); + __Pyx_AddTraceback("thriftpy2.transport.sasl.cysasl.TCySaslClientTransport._flushEncoded", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_success); + __Pyx_XDECREF(__pyx_v_encoded); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/sasl/cysasl.pyx":154 + * self.trans.write(encoded) + * + * def _flushPlain(self, buffer): # <<<<<<<<<<<<<< + * # When we have QOP of auth, sasl.encode() will pass the input to the output + * # but won't put a length header, so we have to do that. +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_17_flushPlain(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_17_flushPlain = {"_flushPlain", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_17_flushPlain, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_17_flushPlain(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_buffer = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("_flushPlain (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_buffer,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 154, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 154, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "_flushPlain", 0) < (0)) __PYX_ERR(0, 154, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("_flushPlain", 1, 1, 1, i); __PYX_ERR(0, 154, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 154, __pyx_L3_error) + } + __pyx_v_buffer = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("_flushPlain", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 154, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("thriftpy2.transport.sasl.cysasl.TCySaslClientTransport._flushPlain", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_16_flushPlain(((struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *)__pyx_v_self), __pyx_v_buffer); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_16_flushPlain(struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *__pyx_v_self, PyObject *__pyx_v_buffer) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + Py_ssize_t __pyx_t_7; + size_t __pyx_t_8; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_flushPlain", 0); + + /* "thriftpy2/transport/sasl/cysasl.pyx":163 + * # Python turn out to be REALLY expensive, but it seems to do a pretty + * # good job of managing string buffer operations without excessive copies + * self.trans.write(struct.pack(">I", len(buffer)) + buffer) # <<<<<<<<<<<<<< + * + * def read(self, sz): +*/ + __pyx_t_2 = __pyx_v_self->__pyx_base.trans; + __Pyx_INCREF(__pyx_t_2); + __pyx_t_4 = NULL; + __Pyx_GetModuleGlobalName(__pyx_t_5, __pyx_mstate_global->__pyx_n_u_struct); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 163, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_mstate_global->__pyx_n_u_pack); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 163, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_7 = PyObject_Length(__pyx_v_buffer); if (unlikely(__pyx_t_7 == ((Py_ssize_t)-1))) __PYX_ERR(0, 163, __pyx_L1_error) + __pyx_t_5 = PyLong_FromSsize_t(__pyx_t_7); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 163, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_8 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_6))) { + __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_6); + assert(__pyx_t_4); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_6); + __Pyx_INCREF(__pyx_t_4); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_6, __pyx__function); + __pyx_t_8 = 0; + } + #endif + { + PyObject *__pyx_callargs[3] = {__pyx_t_4, __pyx_mstate_global->__pyx_kp_u_I, __pyx_t_5}; + __pyx_t_3 = __Pyx_PyObject_FastCall((PyObject*)__pyx_t_6, __pyx_callargs+__pyx_t_8, (3-__pyx_t_8) | (__pyx_t_8*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 163, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + } + __pyx_t_6 = PyNumber_Add(__pyx_t_3, __pyx_v_buffer); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 163, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_8 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, __pyx_t_6}; + __pyx_t_1 = __Pyx_PyObject_FastCallMethod((PyObject*)__pyx_mstate_global->__pyx_n_u_write, __pyx_callargs+__pyx_t_8, (2-__pyx_t_8) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 163, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":154 + * self.trans.write(encoded) + * + * def _flushPlain(self, buffer): # <<<<<<<<<<<<<< + * # When we have QOP of auth, sasl.encode() will pass the input to the output + * # but won't put a length header, so we have to do that. +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_AddTraceback("thriftpy2.transport.sasl.cysasl.TCySaslClientTransport._flushPlain", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/sasl/cysasl.pyx":165 + * self.trans.write(struct.pack(">I", len(buffer)) + buffer) + * + * def read(self, sz): # <<<<<<<<<<<<<< + * return self.get_string(sz) + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_19read(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_19read = {"read", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_19read, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_19read(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_sz = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("read (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_sz,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 165, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 165, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "read", 0) < (0)) __PYX_ERR(0, 165, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("read", 1, 1, 1, i); __PYX_ERR(0, 165, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 165, __pyx_L3_error) + } + __pyx_v_sz = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("read", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 165, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("thriftpy2.transport.sasl.cysasl.TCySaslClientTransport.read", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_18read(((struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *)__pyx_v_self), __pyx_v_sz); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_18read(struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *__pyx_v_self, PyObject *__pyx_v_sz) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("read", 0); + + /* "thriftpy2/transport/sasl/cysasl.pyx":166 + * + * def read(self, sz): + * return self.get_string(sz) # <<<<<<<<<<<<<< + * + * cdef c_read(self, int sz, char* out): +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyLong_As_int(__pyx_v_sz); if (unlikely((__pyx_t_1 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 166, __pyx_L1_error) + __pyx_t_2 = ((struct __pyx_vtabstruct_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *)__pyx_v_self->__pyx_base.__pyx_vtab)->__pyx_base.get_string(((struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *)__pyx_v_self), __pyx_t_1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 166, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":165 + * self.trans.write(struct.pack(">I", len(buffer)) + buffer) + * + * def read(self, sz): # <<<<<<<<<<<<<< + * return self.get_string(sz) + * +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("thriftpy2.transport.sasl.cysasl.TCySaslClientTransport.read", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/sasl/cysasl.pyx":168 + * return self.get_string(sz) + * + * cdef c_read(self, int sz, char* out): # <<<<<<<<<<<<<< + * cdef bytes ret + * +*/ + +static PyObject *__pyx_f_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_c_read(struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *__pyx_v_self, int __pyx_v_sz, char *__pyx_v_out) { + PyObject *__pyx_v_ret = 0; + int __pyx_v_orig_sz; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + size_t __pyx_t_4; + char *__pyx_t_5; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("c_read", 0); + + /* "thriftpy2/transport/sasl/cysasl.pyx":171 + * cdef bytes ret + * + * ret = b"" # <<<<<<<<<<<<<< + * + * if sz <= 0: +*/ + __Pyx_INCREF(__pyx_mstate_global->__pyx_kp_b__3); + __pyx_v_ret = __pyx_mstate_global->__pyx_kp_b__3; + + /* "thriftpy2/transport/sasl/cysasl.pyx":173 + * ret = b"" + * + * if sz <= 0: # <<<<<<<<<<<<<< + * return 0 + * +*/ + __pyx_t_1 = (__pyx_v_sz <= 0); + if (__pyx_t_1) { + + /* "thriftpy2/transport/sasl/cysasl.pyx":174 + * + * if sz <= 0: + * return 0 # <<<<<<<<<<<<<< + * + * orig_sz = sz +*/ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_mstate_global->__pyx_int_0); + __pyx_r = __pyx_mstate_global->__pyx_int_0; + goto __pyx_L0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":173 + * ret = b"" + * + * if sz <= 0: # <<<<<<<<<<<<<< + * return 0 + * +*/ + } + + /* "thriftpy2/transport/sasl/cysasl.pyx":176 + * return 0 + * + * orig_sz = sz # <<<<<<<<<<<<<< + * if self.__rbuf.data_size < sz: + * # Read what remains, then get more data plz +*/ + __pyx_v_orig_sz = __pyx_v_sz; + + /* "thriftpy2/transport/sasl/cysasl.pyx":177 + * + * orig_sz = sz + * if self.__rbuf.data_size < sz: # <<<<<<<<<<<<<< + * # Read what remains, then get more data plz + * ret += self.__rbuf.buf[:self.__rbuf.data_size] +*/ + __pyx_t_1 = (__pyx_v_self->_TCySaslClientTransport__rbuf->data_size < __pyx_v_sz); + if (__pyx_t_1) { + + /* "thriftpy2/transport/sasl/cysasl.pyx":179 + * if self.__rbuf.data_size < sz: + * # Read what remains, then get more data plz + * ret += self.__rbuf.buf[:self.__rbuf.data_size] # <<<<<<<<<<<<<< + * sz -= self.__rbuf.data_size + * self._read_frame() +*/ + __pyx_t_2 = __Pyx_PyBytes_FromStringAndSize(__pyx_v_self->_TCySaslClientTransport__rbuf->buf + 0, __pyx_v_self->_TCySaslClientTransport__rbuf->data_size - 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 179, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyNumber_InPlaceAdd(__pyx_v_ret, __pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 179, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF_SET(__pyx_v_ret, ((PyObject*)__pyx_t_3)); + __pyx_t_3 = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":180 + * # Read what remains, then get more data plz + * ret += self.__rbuf.buf[:self.__rbuf.data_size] + * sz -= self.__rbuf.data_size # <<<<<<<<<<<<<< + * self._read_frame() + * +*/ + __pyx_v_sz = (__pyx_v_sz - __pyx_v_self->_TCySaslClientTransport__rbuf->data_size); + + /* "thriftpy2/transport/sasl/cysasl.pyx":181 + * ret += self.__rbuf.buf[:self.__rbuf.data_size] + * sz -= self.__rbuf.data_size + * self._read_frame() # <<<<<<<<<<<<<< + * + * ret += self.__rbuf.buf[self.__rbuf.cur:self.__rbuf.cur + sz] +*/ + __pyx_t_2 = ((PyObject *)__pyx_v_self); + __Pyx_INCREF(__pyx_t_2); + __pyx_t_4 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, NULL}; + __pyx_t_3 = __Pyx_PyObject_FastCallMethod((PyObject*)__pyx_mstate_global->__pyx_n_u_read_frame, __pyx_callargs+__pyx_t_4, (1-__pyx_t_4) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 181, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":177 + * + * orig_sz = sz + * if self.__rbuf.data_size < sz: # <<<<<<<<<<<<<< + * # Read what remains, then get more data plz + * ret += self.__rbuf.buf[:self.__rbuf.data_size] +*/ + } + + /* "thriftpy2/transport/sasl/cysasl.pyx":183 + * self._read_frame() + * + * ret += self.__rbuf.buf[self.__rbuf.cur:self.__rbuf.cur + sz] # <<<<<<<<<<<<<< + * self.__rbuf.cur += sz + * self.__rbuf.data_size -= sz +*/ + __pyx_t_3 = __Pyx_PyBytes_FromStringAndSize(__pyx_v_self->_TCySaslClientTransport__rbuf->buf + __pyx_v_self->_TCySaslClientTransport__rbuf->cur, (__pyx_v_self->_TCySaslClientTransport__rbuf->cur + __pyx_v_sz) - __pyx_v_self->_TCySaslClientTransport__rbuf->cur); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 183, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = PyNumber_InPlaceAdd(__pyx_v_ret, __pyx_t_3); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 183, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF_SET(__pyx_v_ret, ((PyObject*)__pyx_t_2)); + __pyx_t_2 = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":184 + * + * ret += self.__rbuf.buf[self.__rbuf.cur:self.__rbuf.cur + sz] + * self.__rbuf.cur += sz # <<<<<<<<<<<<<< + * self.__rbuf.data_size -= sz + * +*/ + __pyx_v_self->_TCySaslClientTransport__rbuf->cur = (__pyx_v_self->_TCySaslClientTransport__rbuf->cur + __pyx_v_sz); + + /* "thriftpy2/transport/sasl/cysasl.pyx":185 + * ret += self.__rbuf.buf[self.__rbuf.cur:self.__rbuf.cur + sz] + * self.__rbuf.cur += sz + * self.__rbuf.data_size -= sz # <<<<<<<<<<<<<< + * + * memcpy(out, ret, orig_sz) +*/ + __pyx_v_self->_TCySaslClientTransport__rbuf->data_size = (__pyx_v_self->_TCySaslClientTransport__rbuf->data_size - __pyx_v_sz); + + /* "thriftpy2/transport/sasl/cysasl.pyx":187 + * self.__rbuf.data_size -= sz + * + * memcpy(out, ret, orig_sz) # <<<<<<<<<<<<<< + * + * def _read_frame(self): +*/ + __pyx_t_5 = __Pyx_PyBytes_AsWritableString(__pyx_v_ret); if (unlikely((!__pyx_t_5) && PyErr_Occurred())) __PYX_ERR(0, 187, __pyx_L1_error) + (void)(memcpy(__pyx_v_out, ((char *)__pyx_t_5), __pyx_v_orig_sz)); + + /* "thriftpy2/transport/sasl/cysasl.pyx":168 + * return self.get_string(sz) + * + * cdef c_read(self, int sz, char* out): # <<<<<<<<<<<<<< + * cdef bytes ret + * +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("thriftpy2.transport.sasl.cysasl.TCySaslClientTransport.c_read", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_ret); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/sasl/cysasl.pyx":189 + * memcpy(out, ret, orig_sz) + * + * def _read_frame(self): # <<<<<<<<<<<<<< + * header = readall(self.trans.read, 4) + * (length,) = struct.unpack(">I", header) +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_21_read_frame(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_21_read_frame = {"_read_frame", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_21_read_frame, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_21_read_frame(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("_read_frame (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("_read_frame", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("_read_frame", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_20_read_frame(((struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_20_read_frame(struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *__pyx_v_self) { + PyObject *__pyx_v_header = NULL; + PyObject *__pyx_v_length = NULL; + PyObject *__pyx_v_encoded = NULL; + PyObject *__pyx_v_success = NULL; + PyObject *__pyx_v_decoded = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + size_t __pyx_t_5; + PyObject *(*__pyx_t_6)(PyObject *); + int __pyx_t_7; + int __pyx_t_8; + PyObject *__pyx_t_9 = NULL; + PyObject *__pyx_t_10 = NULL; + Py_ssize_t __pyx_t_11; + char *__pyx_t_12; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_read_frame", 0); + + /* "thriftpy2/transport/sasl/cysasl.pyx":190 + * + * def _read_frame(self): + * header = readall(self.trans.read, 4) # <<<<<<<<<<<<<< + * (length,) = struct.unpack(">I", header) + * if self.encode_decided and self.encode: +*/ + __pyx_t_2 = NULL; + __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_mstate_global->__pyx_n_u_readall); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 190, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_self->__pyx_base.trans, __pyx_mstate_global->__pyx_n_u_read); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 190, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_3))) { + __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_3); + assert(__pyx_t_2); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_3); + __Pyx_INCREF(__pyx_t_2); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_3, __pyx__function); + __pyx_t_5 = 0; + } + #endif + { + PyObject *__pyx_callargs[3] = {__pyx_t_2, __pyx_t_4, __pyx_mstate_global->__pyx_int_4}; + __pyx_t_1 = __Pyx_PyObject_FastCall((PyObject*)__pyx_t_3, __pyx_callargs+__pyx_t_5, (3-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 190, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __pyx_v_header = __pyx_t_1; + __pyx_t_1 = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":191 + * def _read_frame(self): + * header = readall(self.trans.read, 4) + * (length,) = struct.unpack(">I", header) # <<<<<<<<<<<<<< + * if self.encode_decided and self.encode: + * # If the frames are encoded (i.e. you're using a QOP of auth-int or +*/ + __pyx_t_3 = NULL; + __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_mstate_global->__pyx_n_u_struct); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 191, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_mstate_global->__pyx_n_u_unpack); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 191, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_5 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_2))) { + __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_2); + assert(__pyx_t_3); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_2); + __Pyx_INCREF(__pyx_t_3); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_2, __pyx__function); + __pyx_t_5 = 0; + } + #endif + { + PyObject *__pyx_callargs[3] = {__pyx_t_3, __pyx_mstate_global->__pyx_kp_u_I, __pyx_v_header}; + __pyx_t_1 = __Pyx_PyObject_FastCall((PyObject*)__pyx_t_2, __pyx_callargs+__pyx_t_5, (3-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 191, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + if ((likely(PyTuple_CheckExact(__pyx_t_1))) || (PyList_CheckExact(__pyx_t_1))) { + PyObject* sequence = __pyx_t_1; + Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); + if (unlikely(size != 1)) { + if (size > 1) __Pyx_RaiseTooManyValuesError(1); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + __PYX_ERR(0, 191, __pyx_L1_error) + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + if (likely(PyTuple_CheckExact(sequence))) { + __pyx_t_2 = PyTuple_GET_ITEM(sequence, 0); + __Pyx_INCREF(__pyx_t_2); + } else { + __pyx_t_2 = __Pyx_PyList_GetItemRefFast(sequence, 0, __Pyx_ReferenceSharing_SharedReference); + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 191, __pyx_L1_error) + __Pyx_XGOTREF(__pyx_t_2); + } + #else + __pyx_t_2 = __Pyx_PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 191, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #endif + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } else { + Py_ssize_t index = -1; + __pyx_t_3 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 191, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_6 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_3); + index = 0; __pyx_t_2 = __pyx_t_6(__pyx_t_3); if (unlikely(!__pyx_t_2)) goto __pyx_L3_unpacking_failed; + __Pyx_GOTREF(__pyx_t_2); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_6(__pyx_t_3), 1) < (0)) __PYX_ERR(0, 191, __pyx_L1_error) + __pyx_t_6 = NULL; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + goto __pyx_L4_unpacking_done; + __pyx_L3_unpacking_failed:; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + __PYX_ERR(0, 191, __pyx_L1_error) + __pyx_L4_unpacking_done:; + } + __pyx_v_length = __pyx_t_2; + __pyx_t_2 = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":192 + * header = readall(self.trans.read, 4) + * (length,) = struct.unpack(">I", header) + * if self.encode_decided and self.encode: # <<<<<<<<<<<<<< + * # If the frames are encoded (i.e. you're using a QOP of auth-int or + * # auth-conf), then make sure to include the header in the bytes you send to +*/ + if (__pyx_v_self->encode_decided) { + } else { + __pyx_t_7 = __pyx_v_self->encode_decided; + goto __pyx_L6_bool_binop_done; + } + __pyx_t_7 = __pyx_v_self->encode; + __pyx_L6_bool_binop_done:; + if (__pyx_t_7) { + + /* "thriftpy2/transport/sasl/cysasl.pyx":196 + * # auth-conf), then make sure to include the header in the bytes you send to + * # sasl.decode() + * encoded = header + readall(self.trans.read, length) # <<<<<<<<<<<<<< + * success, decoded = self.sasl.decode(encoded) + * if not success: +*/ + __pyx_t_2 = NULL; + __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_mstate_global->__pyx_n_u_readall); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 196, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_self->__pyx_base.trans, __pyx_mstate_global->__pyx_n_u_read); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 196, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_3))) { + __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_3); + assert(__pyx_t_2); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_3); + __Pyx_INCREF(__pyx_t_2); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_3, __pyx__function); + __pyx_t_5 = 0; + } + #endif + { + PyObject *__pyx_callargs[3] = {__pyx_t_2, __pyx_t_4, __pyx_v_length}; + __pyx_t_1 = __Pyx_PyObject_FastCall((PyObject*)__pyx_t_3, __pyx_callargs+__pyx_t_5, (3-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 196, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __pyx_t_3 = PyNumber_Add(__pyx_v_header, __pyx_t_1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 196, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_encoded = __pyx_t_3; + __pyx_t_3 = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":197 + * # sasl.decode() + * encoded = header + readall(self.trans.read, length) + * success, decoded = self.sasl.decode(encoded) # <<<<<<<<<<<<<< + * if not success: + * raise TTransportException(type=TTransportException.UNKNOWN, +*/ + __pyx_t_1 = __pyx_v_self->sasl; + __Pyx_INCREF(__pyx_t_1); + __pyx_t_5 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_1, __pyx_v_encoded}; + __pyx_t_3 = __Pyx_PyObject_FastCallMethod((PyObject*)__pyx_mstate_global->__pyx_n_u_decode, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 197, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + } + if ((likely(PyTuple_CheckExact(__pyx_t_3))) || (PyList_CheckExact(__pyx_t_3))) { + PyObject* sequence = __pyx_t_3; + Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + __PYX_ERR(0, 197, __pyx_L1_error) + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + if (likely(PyTuple_CheckExact(sequence))) { + __pyx_t_1 = PyTuple_GET_ITEM(sequence, 0); + __Pyx_INCREF(__pyx_t_1); + __pyx_t_4 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_4); + } else { + __pyx_t_1 = __Pyx_PyList_GetItemRefFast(sequence, 0, __Pyx_ReferenceSharing_SharedReference); + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 197, __pyx_L1_error) + __Pyx_XGOTREF(__pyx_t_1); + __pyx_t_4 = __Pyx_PyList_GetItemRefFast(sequence, 1, __Pyx_ReferenceSharing_SharedReference); + if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 197, __pyx_L1_error) + __Pyx_XGOTREF(__pyx_t_4); + } + #else + __pyx_t_1 = __Pyx_PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 197, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_4 = __Pyx_PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 197, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + #endif + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + } else { + Py_ssize_t index = -1; + __pyx_t_2 = PyObject_GetIter(__pyx_t_3); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 197, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_2); + index = 0; __pyx_t_1 = __pyx_t_6(__pyx_t_2); if (unlikely(!__pyx_t_1)) goto __pyx_L8_unpacking_failed; + __Pyx_GOTREF(__pyx_t_1); + index = 1; __pyx_t_4 = __pyx_t_6(__pyx_t_2); if (unlikely(!__pyx_t_4)) goto __pyx_L8_unpacking_failed; + __Pyx_GOTREF(__pyx_t_4); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_6(__pyx_t_2), 2) < (0)) __PYX_ERR(0, 197, __pyx_L1_error) + __pyx_t_6 = NULL; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + goto __pyx_L9_unpacking_done; + __pyx_L8_unpacking_failed:; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_6 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + __PYX_ERR(0, 197, __pyx_L1_error) + __pyx_L9_unpacking_done:; + } + __pyx_v_success = __pyx_t_1; + __pyx_t_1 = 0; + __pyx_v_decoded = __pyx_t_4; + __pyx_t_4 = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":198 + * encoded = header + readall(self.trans.read, length) + * success, decoded = self.sasl.decode(encoded) + * if not success: # <<<<<<<<<<<<<< + * raise TTransportException(type=TTransportException.UNKNOWN, + * message=self.sasl.getError()) +*/ + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_v_success); if (unlikely((__pyx_t_7 < 0))) __PYX_ERR(0, 198, __pyx_L1_error) + __pyx_t_8 = (!__pyx_t_7); + if (unlikely(__pyx_t_8)) { + + /* "thriftpy2/transport/sasl/cysasl.pyx":199 + * success, decoded = self.sasl.decode(encoded) + * if not success: + * raise TTransportException(type=TTransportException.UNKNOWN, # <<<<<<<<<<<<<< + * message=self.sasl.getError()) + * else: +*/ + __pyx_t_4 = NULL; + __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_mstate_global->__pyx_n_u_TTransportException); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 199, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_mstate_global->__pyx_n_u_TTransportException); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 199, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_mstate_global->__pyx_n_u_UNKNOWN); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 199, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":200 + * if not success: + * raise TTransportException(type=TTransportException.UNKNOWN, + * message=self.sasl.getError()) # <<<<<<<<<<<<<< + * else: + * # If the frames are not encoded, just pass it through +*/ + __pyx_t_10 = __pyx_v_self->sasl; + __Pyx_INCREF(__pyx_t_10); + __pyx_t_5 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_10, NULL}; + __pyx_t_2 = __Pyx_PyObject_FastCallMethod((PyObject*)__pyx_mstate_global->__pyx_n_u_getError, __pyx_callargs+__pyx_t_5, (1-__pyx_t_5) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_10); __pyx_t_10 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 200, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __pyx_t_5 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_1))) { + __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_1); + assert(__pyx_t_4); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_1); + __Pyx_INCREF(__pyx_t_4); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_1, __pyx__function); + __pyx_t_5 = 0; + } + #endif + { + PyObject *__pyx_callargs[2 + ((CYTHON_VECTORCALL) ? 2 : 0)] = {__pyx_t_4, NULL}; + __pyx_t_10 = __Pyx_MakeVectorcallBuilderKwds(2); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 199, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + if (__Pyx_VectorcallBuilder_AddArg(__pyx_mstate_global->__pyx_n_u_type, __pyx_t_9, __pyx_t_10, __pyx_callargs+1, 0) < (0)) __PYX_ERR(0, 199, __pyx_L1_error) + if (__Pyx_VectorcallBuilder_AddArg(__pyx_mstate_global->__pyx_n_u_message, __pyx_t_2, __pyx_t_10, __pyx_callargs+1, 1) < (0)) __PYX_ERR(0, 199, __pyx_L1_error) + __pyx_t_3 = __Pyx_Object_Vectorcall_CallFromBuilder((PyObject*)__pyx_t_1, __pyx_callargs+__pyx_t_5, (1-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET), __pyx_t_10); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 199, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + } + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __PYX_ERR(0, 199, __pyx_L1_error) + + /* "thriftpy2/transport/sasl/cysasl.pyx":198 + * encoded = header + readall(self.trans.read, length) + * success, decoded = self.sasl.decode(encoded) + * if not success: # <<<<<<<<<<<<<< + * raise TTransportException(type=TTransportException.UNKNOWN, + * message=self.sasl.getError()) +*/ + } + + /* "thriftpy2/transport/sasl/cysasl.pyx":192 + * header = readall(self.trans.read, 4) + * (length,) = struct.unpack(">I", header) + * if self.encode_decided and self.encode: # <<<<<<<<<<<<<< + * # If the frames are encoded (i.e. you're using a QOP of auth-int or + * # auth-conf), then make sure to include the header in the bytes you send to +*/ + goto __pyx_L5; + } + + /* "thriftpy2/transport/sasl/cysasl.pyx":203 + * else: + * # If the frames are not encoded, just pass it through + * decoded = readall(self.trans.read, length) # <<<<<<<<<<<<<< + * self.__rbuf = TCyBuffer(len(decoded)+1) # just to be sure make room for an extra byte + * memcpy(self.__rbuf.buf, decoded, len(decoded)) +*/ + /*else*/ { + __pyx_t_1 = NULL; + __Pyx_GetModuleGlobalName(__pyx_t_10, __pyx_mstate_global->__pyx_n_u_readall); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 203, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_self->__pyx_base.trans, __pyx_mstate_global->__pyx_n_u_read); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 203, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_5 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_10))) { + __pyx_t_1 = PyMethod_GET_SELF(__pyx_t_10); + assert(__pyx_t_1); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_10); + __Pyx_INCREF(__pyx_t_1); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_10, __pyx__function); + __pyx_t_5 = 0; + } + #endif + { + PyObject *__pyx_callargs[3] = {__pyx_t_1, __pyx_t_2, __pyx_v_length}; + __pyx_t_3 = __Pyx_PyObject_FastCall((PyObject*)__pyx_t_10, __pyx_callargs+__pyx_t_5, (3-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 203, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + } + __pyx_v_decoded = __pyx_t_3; + __pyx_t_3 = 0; + } + __pyx_L5:; + + /* "thriftpy2/transport/sasl/cysasl.pyx":204 + * # If the frames are not encoded, just pass it through + * decoded = readall(self.trans.read, length) + * self.__rbuf = TCyBuffer(len(decoded)+1) # just to be sure make room for an extra byte # <<<<<<<<<<<<<< + * memcpy(self.__rbuf.buf, decoded, len(decoded)) + * self.__rbuf.data_size = len(decoded) +*/ + __pyx_t_10 = NULL; + __pyx_t_11 = PyObject_Length(__pyx_v_decoded); if (unlikely(__pyx_t_11 == ((Py_ssize_t)-1))) __PYX_ERR(0, 204, __pyx_L1_error) + __pyx_t_2 = PyLong_FromSsize_t((__pyx_t_11 + 1)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 204, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_5 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_10, __pyx_t_2}; + __pyx_t_3 = __Pyx_PyObject_FastCall((PyObject*)__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_10); __pyx_t_10 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 204, __pyx_L1_error) + __Pyx_GOTREF((PyObject *)__pyx_t_3); + } + __Pyx_GIVEREF((PyObject *)__pyx_t_3); + __Pyx_GOTREF((PyObject *)__pyx_v_self->_TCySaslClientTransport__rbuf); + __Pyx_DECREF((PyObject *)__pyx_v_self->_TCySaslClientTransport__rbuf); + __pyx_v_self->_TCySaslClientTransport__rbuf = ((struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *)__pyx_t_3); + __pyx_t_3 = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":205 + * decoded = readall(self.trans.read, length) + * self.__rbuf = TCyBuffer(len(decoded)+1) # just to be sure make room for an extra byte + * memcpy(self.__rbuf.buf, decoded, len(decoded)) # <<<<<<<<<<<<<< + * self.__rbuf.data_size = len(decoded) + * self.__rbuf.cur = 0 +*/ + __pyx_t_12 = __Pyx_PyObject_AsWritableString(__pyx_v_decoded); if (unlikely((!__pyx_t_12) && PyErr_Occurred())) __PYX_ERR(0, 205, __pyx_L1_error) + __pyx_t_11 = PyObject_Length(__pyx_v_decoded); if (unlikely(__pyx_t_11 == ((Py_ssize_t)-1))) __PYX_ERR(0, 205, __pyx_L1_error) + (void)(memcpy(__pyx_v_self->_TCySaslClientTransport__rbuf->buf, ((char *)__pyx_t_12), __pyx_t_11)); + + /* "thriftpy2/transport/sasl/cysasl.pyx":206 + * self.__rbuf = TCyBuffer(len(decoded)+1) # just to be sure make room for an extra byte + * memcpy(self.__rbuf.buf, decoded, len(decoded)) + * self.__rbuf.data_size = len(decoded) # <<<<<<<<<<<<<< + * self.__rbuf.cur = 0 + * +*/ + __pyx_t_11 = PyObject_Length(__pyx_v_decoded); if (unlikely(__pyx_t_11 == ((Py_ssize_t)-1))) __PYX_ERR(0, 206, __pyx_L1_error) + __pyx_v_self->_TCySaslClientTransport__rbuf->data_size = __pyx_t_11; + + /* "thriftpy2/transport/sasl/cysasl.pyx":207 + * memcpy(self.__rbuf.buf, decoded, len(decoded)) + * self.__rbuf.data_size = len(decoded) + * self.__rbuf.cur = 0 # <<<<<<<<<<<<<< + * + * def clean(self): +*/ + __pyx_v_self->_TCySaslClientTransport__rbuf->cur = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":189 + * memcpy(out, ret, orig_sz) + * + * def _read_frame(self): # <<<<<<<<<<<<<< + * header = readall(self.trans.read, 4) + * (length,) = struct.unpack(">I", header) +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_XDECREF(__pyx_t_10); + __Pyx_AddTraceback("thriftpy2.transport.sasl.cysasl.TCySaslClientTransport._read_frame", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_header); + __Pyx_XDECREF(__pyx_v_length); + __Pyx_XDECREF(__pyx_v_encoded); + __Pyx_XDECREF(__pyx_v_success); + __Pyx_XDECREF(__pyx_v_decoded); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/sasl/cysasl.pyx":209 + * self.__rbuf.cur = 0 + * + * def clean(self): # <<<<<<<<<<<<<< + * self.__rbuf.clean() + * self.__wbuf.clean() +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_23clean(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_23clean = {"clean", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_23clean, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_23clean(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("clean (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("clean", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("clean", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_22clean(((struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_22clean(struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("clean", 0); + + /* "thriftpy2/transport/sasl/cysasl.pyx":210 + * + * def clean(self): + * self.__rbuf.clean() # <<<<<<<<<<<<<< + * self.__wbuf.clean() + * +*/ + ((struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_TCyBuffer *)__pyx_v_self->_TCySaslClientTransport__rbuf->__pyx_vtab)->clean(__pyx_v_self->_TCySaslClientTransport__rbuf); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 210, __pyx_L1_error) + + /* "thriftpy2/transport/sasl/cysasl.pyx":211 + * def clean(self): + * self.__rbuf.clean() + * self.__wbuf.clean() # <<<<<<<<<<<<<< + * + * def close(self): +*/ + ((struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_TCyBuffer *)__pyx_v_self->_TCySaslClientTransport__wbuf->__pyx_vtab)->clean(__pyx_v_self->_TCySaslClientTransport__wbuf); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 211, __pyx_L1_error) + + /* "thriftpy2/transport/sasl/cysasl.pyx":209 + * self.__rbuf.cur = 0 + * + * def clean(self): # <<<<<<<<<<<<<< + * self.__rbuf.clean() + * self.__wbuf.clean() +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_AddTraceback("thriftpy2.transport.sasl.cysasl.TCySaslClientTransport.clean", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "thriftpy2/transport/sasl/cysasl.pyx":213 + * self.__wbuf.clean() + * + * def close(self): # <<<<<<<<<<<<<< + * self.trans.close() + * self.sasl = None +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_25close(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_25close = {"close", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_25close, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_25close(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("close (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("close", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("close", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_24close(((struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_24close(struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + size_t __pyx_t_3; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("close", 0); + + /* "thriftpy2/transport/sasl/cysasl.pyx":214 + * + * def close(self): + * self.trans.close() # <<<<<<<<<<<<<< + * self.sasl = None + * +*/ + __pyx_t_2 = __pyx_v_self->__pyx_base.trans; + __Pyx_INCREF(__pyx_t_2); + __pyx_t_3 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, NULL}; + __pyx_t_1 = __Pyx_PyObject_FastCallMethod((PyObject*)__pyx_mstate_global->__pyx_n_u_close, __pyx_callargs+__pyx_t_3, (1-__pyx_t_3) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 214, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":215 + * def close(self): + * self.trans.close() + * self.sasl = None # <<<<<<<<<<<<<< + * +*/ + __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(Py_None); + __Pyx_GOTREF(__pyx_v_self->sasl); + __Pyx_DECREF(__pyx_v_self->sasl); + __pyx_v_self->sasl = Py_None; + + /* "thriftpy2/transport/sasl/cysasl.pyx":213 + * self.__wbuf.clean() + * + * def close(self): # <<<<<<<<<<<<<< + * self.trans.close() + * self.sasl = None +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("thriftpy2.transport.sasl.cysasl.TCySaslClientTransport.close", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * cdef tuple state + * cdef object _dict +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_27__reduce_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_27__reduce_cython__ = {"__reduce_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_27__reduce_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_27__reduce_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("__reduce_cython__", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("__reduce_cython__", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_26__reduce_cython__(((struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_26__reduce_cython__(struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *__pyx_v_self) { + PyObject *__pyx_v_state = 0; + PyObject *__pyx_v__dict = 0; + int __pyx_v_use_setstate; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_t_5; + int __pyx_t_6; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__reduce_cython__", 0); + + /* "(tree fragment)":5 + * cdef object _dict + * cdef bint use_setstate + * state = (self._TCySaslClientTransport__rbuf, self._TCySaslClientTransport__wbuf, self.encode, self.encode_decided, self.mechanism, self.opened, self.sasl, self.sasl_client_factory, self.trans) # <<<<<<<<<<<<<< + * _dict = getattr(self, '__dict__', None) + * if _dict is not None and _dict: +*/ + __pyx_t_1 = __Pyx_PyBool_FromLong(__pyx_v_self->encode); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 5, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_self->encode_decided); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 5, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PyBool_FromLong(__pyx_v_self->opened); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 5, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyTuple_New(9); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 5, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_INCREF((PyObject *)__pyx_v_self->_TCySaslClientTransport__rbuf); + __Pyx_GIVEREF((PyObject *)__pyx_v_self->_TCySaslClientTransport__rbuf); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_v_self->_TCySaslClientTransport__rbuf)) != (0)) __PYX_ERR(1, 5, __pyx_L1_error); + __Pyx_INCREF((PyObject *)__pyx_v_self->_TCySaslClientTransport__wbuf); + __Pyx_GIVEREF((PyObject *)__pyx_v_self->_TCySaslClientTransport__wbuf); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_4, 1, ((PyObject *)__pyx_v_self->_TCySaslClientTransport__wbuf)) != (0)) __PYX_ERR(1, 5, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_1); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_4, 2, __pyx_t_1) != (0)) __PYX_ERR(1, 5, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_2); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_4, 3, __pyx_t_2) != (0)) __PYX_ERR(1, 5, __pyx_L1_error); + __Pyx_INCREF(__pyx_v_self->mechanism); + __Pyx_GIVEREF(__pyx_v_self->mechanism); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_4, 4, __pyx_v_self->mechanism) != (0)) __PYX_ERR(1, 5, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_3); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_4, 5, __pyx_t_3) != (0)) __PYX_ERR(1, 5, __pyx_L1_error); + __Pyx_INCREF(__pyx_v_self->sasl); + __Pyx_GIVEREF(__pyx_v_self->sasl); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_4, 6, __pyx_v_self->sasl) != (0)) __PYX_ERR(1, 5, __pyx_L1_error); + __Pyx_INCREF(__pyx_v_self->sasl_client_factory); + __Pyx_GIVEREF(__pyx_v_self->sasl_client_factory); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_4, 7, __pyx_v_self->sasl_client_factory) != (0)) __PYX_ERR(1, 5, __pyx_L1_error); + __Pyx_INCREF(__pyx_v_self->__pyx_base.trans); + __Pyx_GIVEREF(__pyx_v_self->__pyx_base.trans); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_4, 8, __pyx_v_self->__pyx_base.trans) != (0)) __PYX_ERR(1, 5, __pyx_L1_error); + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_t_3 = 0; + __pyx_v_state = ((PyObject*)__pyx_t_4); + __pyx_t_4 = 0; + + /* "(tree fragment)":6 + * cdef bint use_setstate + * state = (self._TCySaslClientTransport__rbuf, self._TCySaslClientTransport__wbuf, self.encode, self.encode_decided, self.mechanism, self.opened, self.sasl, self.sasl_client_factory, self.trans) + * _dict = getattr(self, '__dict__', None) # <<<<<<<<<<<<<< + * if _dict is not None and _dict: + * state += (_dict,) +*/ + __pyx_t_4 = __Pyx_GetAttr3(((PyObject *)__pyx_v_self), __pyx_mstate_global->__pyx_n_u_dict, Py_None); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 6, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_v__dict = __pyx_t_4; + __pyx_t_4 = 0; + + /* "(tree fragment)":7 + * state = (self._TCySaslClientTransport__rbuf, self._TCySaslClientTransport__wbuf, self.encode, self.encode_decided, self.mechanism, self.opened, self.sasl, self.sasl_client_factory, self.trans) + * _dict = getattr(self, '__dict__', None) + * if _dict is not None and _dict: # <<<<<<<<<<<<<< + * state += (_dict,) + * use_setstate = True +*/ + __pyx_t_6 = (__pyx_v__dict != Py_None); + if (__pyx_t_6) { + } else { + __pyx_t_5 = __pyx_t_6; + goto __pyx_L4_bool_binop_done; + } + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_v__dict); if (unlikely((__pyx_t_6 < 0))) __PYX_ERR(1, 7, __pyx_L1_error) + __pyx_t_5 = __pyx_t_6; + __pyx_L4_bool_binop_done:; + if (__pyx_t_5) { + + /* "(tree fragment)":8 + * _dict = getattr(self, '__dict__', None) + * if _dict is not None and _dict: + * state += (_dict,) # <<<<<<<<<<<<<< + * use_setstate = True + * else: +*/ + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 8, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_INCREF(__pyx_v__dict); + __Pyx_GIVEREF(__pyx_v__dict); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_v__dict) != (0)) __PYX_ERR(1, 8, __pyx_L1_error); + __pyx_t_3 = PyNumber_InPlaceAdd(__pyx_v_state, __pyx_t_4); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 8, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF_SET(__pyx_v_state, ((PyObject*)__pyx_t_3)); + __pyx_t_3 = 0; + + /* "(tree fragment)":9 + * if _dict is not None and _dict: + * state += (_dict,) + * use_setstate = True # <<<<<<<<<<<<<< + * else: + * use_setstate = self._TCySaslClientTransport__rbuf is not None or self._TCySaslClientTransport__wbuf is not None or self.mechanism is not None or self.sasl is not None or self.sasl_client_factory is not None or self.trans is not None +*/ + __pyx_v_use_setstate = 1; + + /* "(tree fragment)":7 + * state = (self._TCySaslClientTransport__rbuf, self._TCySaslClientTransport__wbuf, self.encode, self.encode_decided, self.mechanism, self.opened, self.sasl, self.sasl_client_factory, self.trans) + * _dict = getattr(self, '__dict__', None) + * if _dict is not None and _dict: # <<<<<<<<<<<<<< + * state += (_dict,) + * use_setstate = True +*/ + goto __pyx_L3; + } + + /* "(tree fragment)":11 + * use_setstate = True + * else: + * use_setstate = self._TCySaslClientTransport__rbuf is not None or self._TCySaslClientTransport__wbuf is not None or self.mechanism is not None or self.sasl is not None or self.sasl_client_factory is not None or self.trans is not None # <<<<<<<<<<<<<< + * if use_setstate: + * return __pyx_unpickle_TCySaslClientTransport, (type(self), 0x02923b9, None), state +*/ + /*else*/ { + __pyx_t_6 = (((PyObject *)__pyx_v_self->_TCySaslClientTransport__rbuf) != Py_None); + if (!__pyx_t_6) { + } else { + __pyx_t_5 = __pyx_t_6; + goto __pyx_L6_bool_binop_done; + } + __pyx_t_6 = (((PyObject *)__pyx_v_self->_TCySaslClientTransport__wbuf) != Py_None); + if (!__pyx_t_6) { + } else { + __pyx_t_5 = __pyx_t_6; + goto __pyx_L6_bool_binop_done; + } + __pyx_t_6 = (__pyx_v_self->mechanism != ((PyObject*)Py_None)); + if (!__pyx_t_6) { + } else { + __pyx_t_5 = __pyx_t_6; + goto __pyx_L6_bool_binop_done; + } + __pyx_t_6 = (__pyx_v_self->sasl != Py_None); + if (!__pyx_t_6) { + } else { + __pyx_t_5 = __pyx_t_6; + goto __pyx_L6_bool_binop_done; + } + __pyx_t_6 = (__pyx_v_self->sasl_client_factory != Py_None); + if (!__pyx_t_6) { + } else { + __pyx_t_5 = __pyx_t_6; + goto __pyx_L6_bool_binop_done; + } + __pyx_t_6 = (__pyx_v_self->__pyx_base.trans != Py_None); + __pyx_t_5 = __pyx_t_6; + __pyx_L6_bool_binop_done:; + __pyx_v_use_setstate = __pyx_t_5; + } + __pyx_L3:; + + /* "(tree fragment)":12 + * else: + * use_setstate = self._TCySaslClientTransport__rbuf is not None or self._TCySaslClientTransport__wbuf is not None or self.mechanism is not None or self.sasl is not None or self.sasl_client_factory is not None or self.trans is not None + * if use_setstate: # <<<<<<<<<<<<<< + * return __pyx_unpickle_TCySaslClientTransport, (type(self), 0x02923b9, None), state + * else: +*/ + if (__pyx_v_use_setstate) { + + /* "(tree fragment)":13 + * use_setstate = self._TCySaslClientTransport__rbuf is not None or self._TCySaslClientTransport__wbuf is not None or self.mechanism is not None or self.sasl is not None or self.sasl_client_factory is not None or self.trans is not None + * if use_setstate: + * return __pyx_unpickle_TCySaslClientTransport, (type(self), 0x02923b9, None), state # <<<<<<<<<<<<<< + * else: + * return __pyx_unpickle_TCySaslClientTransport, (type(self), 0x02923b9, state) +*/ + __Pyx_XDECREF(__pyx_r); + __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_mstate_global->__pyx_n_u_pyx_unpickle_TCySaslClientTran); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 13, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyTuple_New(3); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 13, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_INCREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); + __Pyx_GIVEREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))) != (0)) __PYX_ERR(1, 13, __pyx_L1_error); + __Pyx_INCREF(__pyx_mstate_global->__pyx_int_2696121); + __Pyx_GIVEREF(__pyx_mstate_global->__pyx_int_2696121); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_mstate_global->__pyx_int_2696121) != (0)) __PYX_ERR(1, 13, __pyx_L1_error); + __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(Py_None); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_4, 2, Py_None) != (0)) __PYX_ERR(1, 13, __pyx_L1_error); + __pyx_t_2 = PyTuple_New(3); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 13, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_GIVEREF(__pyx_t_3); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_3) != (0)) __PYX_ERR(1, 13, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_4); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_4) != (0)) __PYX_ERR(1, 13, __pyx_L1_error); + __Pyx_INCREF(__pyx_v_state); + __Pyx_GIVEREF(__pyx_v_state); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_2, 2, __pyx_v_state) != (0)) __PYX_ERR(1, 13, __pyx_L1_error); + __pyx_t_3 = 0; + __pyx_t_4 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "(tree fragment)":12 + * else: + * use_setstate = self._TCySaslClientTransport__rbuf is not None or self._TCySaslClientTransport__wbuf is not None or self.mechanism is not None or self.sasl is not None or self.sasl_client_factory is not None or self.trans is not None + * if use_setstate: # <<<<<<<<<<<<<< + * return __pyx_unpickle_TCySaslClientTransport, (type(self), 0x02923b9, None), state + * else: +*/ + } + + /* "(tree fragment)":15 + * return __pyx_unpickle_TCySaslClientTransport, (type(self), 0x02923b9, None), state + * else: + * return __pyx_unpickle_TCySaslClientTransport, (type(self), 0x02923b9, state) # <<<<<<<<<<<<<< + * def __setstate_cython__(self, __pyx_state): + * __pyx_unpickle_TCySaslClientTransport__set_state(self, __pyx_state) +*/ + /*else*/ { + __Pyx_XDECREF(__pyx_r); + __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_mstate_global->__pyx_n_u_pyx_unpickle_TCySaslClientTran); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 15, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = PyTuple_New(3); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 15, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_INCREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); + __Pyx_GIVEREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))) != (0)) __PYX_ERR(1, 15, __pyx_L1_error); + __Pyx_INCREF(__pyx_mstate_global->__pyx_int_2696121); + __Pyx_GIVEREF(__pyx_mstate_global->__pyx_int_2696121); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_mstate_global->__pyx_int_2696121) != (0)) __PYX_ERR(1, 15, __pyx_L1_error); + __Pyx_INCREF(__pyx_v_state); + __Pyx_GIVEREF(__pyx_v_state); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_4, 2, __pyx_v_state) != (0)) __PYX_ERR(1, 15, __pyx_L1_error); + __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 15, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_GIVEREF(__pyx_t_2); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_2) != (0)) __PYX_ERR(1, 15, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_4); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_4) != (0)) __PYX_ERR(1, 15, __pyx_L1_error); + __pyx_t_2 = 0; + __pyx_t_4 = 0; + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + } + + /* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * cdef tuple state + * cdef object _dict +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("thriftpy2.transport.sasl.cysasl.TCySaslClientTransport.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_state); + __Pyx_XDECREF(__pyx_v__dict); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":16 + * else: + * return __pyx_unpickle_TCySaslClientTransport, (type(self), 0x02923b9, state) + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * __pyx_unpickle_TCySaslClientTransport__set_state(self, __pyx_state) +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_29__setstate_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_29__setstate_cython__ = {"__setstate_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_29__setstate_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_29__setstate_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v___pyx_state = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_pyx_state,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(1, 16, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(1, 16, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "__setstate_cython__", 0) < (0)) __PYX_ERR(1, 16, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("__setstate_cython__", 1, 1, 1, i); __PYX_ERR(1, 16, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(1, 16, __pyx_L3_error) + } + __pyx_v___pyx_state = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__setstate_cython__", 1, 1, 1, __pyx_nargs); __PYX_ERR(1, 16, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("thriftpy2.transport.sasl.cysasl.TCySaslClientTransport.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_28__setstate_cython__(((struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *)__pyx_v_self), __pyx_v___pyx_state); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_28__setstate_cython__(struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *__pyx_v_self, PyObject *__pyx_v___pyx_state) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__setstate_cython__", 0); + + /* "(tree fragment)":17 + * return __pyx_unpickle_TCySaslClientTransport, (type(self), 0x02923b9, state) + * def __setstate_cython__(self, __pyx_state): + * __pyx_unpickle_TCySaslClientTransport__set_state(self, __pyx_state) # <<<<<<<<<<<<<< +*/ + __pyx_t_1 = __pyx_v___pyx_state; + __Pyx_INCREF(__pyx_t_1); + if (!(likely(PyTuple_CheckExact(__pyx_t_1))||((__pyx_t_1) == Py_None) || __Pyx_RaiseUnexpectedTypeError("tuple", __pyx_t_1))) __PYX_ERR(1, 17, __pyx_L1_error) + if (unlikely(__pyx_t_1 == Py_None)) { + PyErr_SetString(PyExc_TypeError, "cannot pass None into a C function argument that is declared 'not None'"); + __PYX_ERR(1, 17, __pyx_L1_error) + } + __pyx_t_2 = __pyx_f_9thriftpy2_9transport_4sasl_6cysasl___pyx_unpickle_TCySaslClientTransport__set_state(__pyx_v_self, ((PyObject*)__pyx_t_1)); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 17, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "(tree fragment)":16 + * else: + * return __pyx_unpickle_TCySaslClientTransport, (type(self), 0x02923b9, state) + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * __pyx_unpickle_TCySaslClientTransport__set_state(self, __pyx_state) +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("thriftpy2.transport.sasl.cysasl.TCySaslClientTransport.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":4 + * int __Pyx_CheckUnpickleChecksum(long, long, long, long, const char*) except -1 + * int __Pyx_UpdateUnpickledDict(object, object, Py_ssize_t) except -1 + * def __pyx_unpickle_TCySaslClientTransport(__pyx_type, long __pyx_checksum, tuple __pyx_state): # <<<<<<<<<<<<<< + * cdef object __pyx_result + * __Pyx_CheckUnpickleChecksum(__pyx_checksum, 0x02923b9, 0x4ea3d29, 0x16559e7, b'_TCySaslClientTransport__rbuf, _TCySaslClientTransport__wbuf, encode, encode_decided, mechanism, opened, sasl, sasl_client_factory, trans') +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_1__pyx_unpickle_TCySaslClientTransport(PyObject *__pyx_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static PyMethodDef __pyx_mdef_9thriftpy2_9transport_4sasl_6cysasl_1__pyx_unpickle_TCySaslClientTransport = {"__pyx_unpickle_TCySaslClientTransport", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_1__pyx_unpickle_TCySaslClientTransport, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_1__pyx_unpickle_TCySaslClientTransport(PyObject *__pyx_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v___pyx_type = 0; + long __pyx_v___pyx_checksum; + PyObject *__pyx_v___pyx_state = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[3] = {0,0,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__pyx_unpickle_TCySaslClientTransport (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_pyx_type,&__pyx_mstate_global->__pyx_n_u_pyx_checksum,&__pyx_mstate_global->__pyx_n_u_pyx_state,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(1, 4, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 3: + values[2] = __Pyx_ArgRef_FASTCALL(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(1, 4, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 2: + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(1, 4, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(1, 4, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "__pyx_unpickle_TCySaslClientTransport", 0) < (0)) __PYX_ERR(1, 4, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 3; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("__pyx_unpickle_TCySaslClientTransport", 1, 3, 3, i); __PYX_ERR(1, 4, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 3)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(1, 4, __pyx_L3_error) + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(1, 4, __pyx_L3_error) + values[2] = __Pyx_ArgRef_FASTCALL(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(1, 4, __pyx_L3_error) + } + __pyx_v___pyx_type = values[0]; + __pyx_v___pyx_checksum = __Pyx_PyLong_As_long(values[1]); if (unlikely((__pyx_v___pyx_checksum == (long)-1) && PyErr_Occurred())) __PYX_ERR(1, 4, __pyx_L3_error) + __pyx_v___pyx_state = ((PyObject*)values[2]); + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__pyx_unpickle_TCySaslClientTransport", 1, 3, 3, __pyx_nargs); __PYX_ERR(1, 4, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("thriftpy2.transport.sasl.cysasl.__pyx_unpickle_TCySaslClientTransport", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v___pyx_state), (&PyTuple_Type), 1, "__pyx_state", 1))) __PYX_ERR(1, 4, __pyx_L1_error) + __pyx_r = __pyx_pf_9thriftpy2_9transport_4sasl_6cysasl___pyx_unpickle_TCySaslClientTransport(__pyx_self, __pyx_v___pyx_type, __pyx_v___pyx_checksum, __pyx_v___pyx_state); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + goto __pyx_L7_cleaned_up; + __pyx_L0:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __pyx_L7_cleaned_up:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9thriftpy2_9transport_4sasl_6cysasl___pyx_unpickle_TCySaslClientTransport(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v___pyx_type, long __pyx_v___pyx_checksum, PyObject *__pyx_v___pyx_state) { + PyObject *__pyx_v___pyx_result = 0; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + size_t __pyx_t_4; + int __pyx_t_5; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__pyx_unpickle_TCySaslClientTransport", 0); + + /* "(tree fragment)":6 + * def __pyx_unpickle_TCySaslClientTransport(__pyx_type, long __pyx_checksum, tuple __pyx_state): + * cdef object __pyx_result + * __Pyx_CheckUnpickleChecksum(__pyx_checksum, 0x02923b9, 0x4ea3d29, 0x16559e7, b'_TCySaslClientTransport__rbuf, _TCySaslClientTransport__wbuf, encode, encode_decided, mechanism, opened, sasl, sasl_client_factory, trans') # <<<<<<<<<<<<<< + * __pyx_result = TCySaslClientTransport.__new__(__pyx_type) + * if __pyx_state is not None: +*/ + __pyx_t_1 = __Pyx_CheckUnpickleChecksum(__pyx_v___pyx_checksum, 0x02923b9, 0x4ea3d29, 0x16559e7, __pyx_k_TCySaslClientTransport__rbuf__T); if (unlikely(__pyx_t_1 == ((int)-1))) __PYX_ERR(1, 6, __pyx_L1_error) + + /* "(tree fragment)":7 + * cdef object __pyx_result + * __Pyx_CheckUnpickleChecksum(__pyx_checksum, 0x02923b9, 0x4ea3d29, 0x16559e7, b'_TCySaslClientTransport__rbuf, _TCySaslClientTransport__wbuf, encode, encode_decided, mechanism, opened, sasl, sasl_client_factory, trans') + * __pyx_result = TCySaslClientTransport.__new__(__pyx_type) # <<<<<<<<<<<<<< + * if __pyx_state is not None: + * __pyx_unpickle_TCySaslClientTransport__set_state( __pyx_result, __pyx_state) +*/ + __pyx_t_3 = ((PyObject *)__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport); + __Pyx_INCREF(__pyx_t_3); + __pyx_t_4 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_v___pyx_type}; + __pyx_t_2 = __Pyx_PyObject_FastCallMethod((PyObject*)__pyx_mstate_global->__pyx_n_u_new, __pyx_callargs+__pyx_t_4, (2-__pyx_t_4) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 7, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __pyx_v___pyx_result = __pyx_t_2; + __pyx_t_2 = 0; + + /* "(tree fragment)":8 + * __Pyx_CheckUnpickleChecksum(__pyx_checksum, 0x02923b9, 0x4ea3d29, 0x16559e7, b'_TCySaslClientTransport__rbuf, _TCySaslClientTransport__wbuf, encode, encode_decided, mechanism, opened, sasl, sasl_client_factory, trans') + * __pyx_result = TCySaslClientTransport.__new__(__pyx_type) + * if __pyx_state is not None: # <<<<<<<<<<<<<< + * __pyx_unpickle_TCySaslClientTransport__set_state( __pyx_result, __pyx_state) + * return __pyx_result +*/ + __pyx_t_5 = (__pyx_v___pyx_state != ((PyObject*)Py_None)); + if (__pyx_t_5) { + + /* "(tree fragment)":9 + * __pyx_result = TCySaslClientTransport.__new__(__pyx_type) + * if __pyx_state is not None: + * __pyx_unpickle_TCySaslClientTransport__set_state( __pyx_result, __pyx_state) # <<<<<<<<<<<<<< + * return __pyx_result + * cdef __pyx_unpickle_TCySaslClientTransport__set_state(TCySaslClientTransport __pyx_result, __pyx_state: tuple): +*/ + if (unlikely(__pyx_v___pyx_state == Py_None)) { + PyErr_SetString(PyExc_TypeError, "cannot pass None into a C function argument that is declared 'not None'"); + __PYX_ERR(1, 9, __pyx_L1_error) + } + __pyx_t_2 = __pyx_f_9thriftpy2_9transport_4sasl_6cysasl___pyx_unpickle_TCySaslClientTransport__set_state(((struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *)__pyx_v___pyx_result), __pyx_v___pyx_state); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 9, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "(tree fragment)":8 + * __Pyx_CheckUnpickleChecksum(__pyx_checksum, 0x02923b9, 0x4ea3d29, 0x16559e7, b'_TCySaslClientTransport__rbuf, _TCySaslClientTransport__wbuf, encode, encode_decided, mechanism, opened, sasl, sasl_client_factory, trans') + * __pyx_result = TCySaslClientTransport.__new__(__pyx_type) + * if __pyx_state is not None: # <<<<<<<<<<<<<< + * __pyx_unpickle_TCySaslClientTransport__set_state( __pyx_result, __pyx_state) + * return __pyx_result +*/ + } + + /* "(tree fragment)":10 + * if __pyx_state is not None: + * __pyx_unpickle_TCySaslClientTransport__set_state( __pyx_result, __pyx_state) + * return __pyx_result # <<<<<<<<<<<<<< + * cdef __pyx_unpickle_TCySaslClientTransport__set_state(TCySaslClientTransport __pyx_result, __pyx_state: tuple): + * __pyx_result._TCySaslClientTransport__rbuf = __pyx_state[0]; __pyx_result._TCySaslClientTransport__wbuf = __pyx_state[1]; __pyx_result.encode = __pyx_state[2]; __pyx_result.encode_decided = __pyx_state[3]; __pyx_result.mechanism = __pyx_state[4]; __pyx_result.opened = __pyx_state[5]; __pyx_result.sasl = __pyx_state[6]; __pyx_result.sasl_client_factory = __pyx_state[7]; __pyx_result.trans = __pyx_state[8] +*/ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v___pyx_result); + __pyx_r = __pyx_v___pyx_result; + goto __pyx_L0; + + /* "(tree fragment)":4 + * int __Pyx_CheckUnpickleChecksum(long, long, long, long, const char*) except -1 + * int __Pyx_UpdateUnpickledDict(object, object, Py_ssize_t) except -1 + * def __pyx_unpickle_TCySaslClientTransport(__pyx_type, long __pyx_checksum, tuple __pyx_state): # <<<<<<<<<<<<<< + * cdef object __pyx_result + * __Pyx_CheckUnpickleChecksum(__pyx_checksum, 0x02923b9, 0x4ea3d29, 0x16559e7, b'_TCySaslClientTransport__rbuf, _TCySaslClientTransport__wbuf, encode, encode_decided, mechanism, opened, sasl, sasl_client_factory, trans') +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("thriftpy2.transport.sasl.cysasl.__pyx_unpickle_TCySaslClientTransport", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v___pyx_result); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":11 + * __pyx_unpickle_TCySaslClientTransport__set_state( __pyx_result, __pyx_state) + * return __pyx_result + * cdef __pyx_unpickle_TCySaslClientTransport__set_state(TCySaslClientTransport __pyx_result, __pyx_state: tuple): # <<<<<<<<<<<<<< + * __pyx_result._TCySaslClientTransport__rbuf = __pyx_state[0]; __pyx_result._TCySaslClientTransport__wbuf = __pyx_state[1]; __pyx_result.encode = __pyx_state[2]; __pyx_result.encode_decided = __pyx_state[3]; __pyx_result.mechanism = __pyx_state[4]; __pyx_result.opened = __pyx_state[5]; __pyx_result.sasl = __pyx_state[6]; __pyx_result.sasl_client_factory = __pyx_state[7]; __pyx_result.trans = __pyx_state[8] + * __Pyx_UpdateUnpickledDict(__pyx_result, __pyx_state, 9) +*/ + +static PyObject *__pyx_f_9thriftpy2_9transport_4sasl_6cysasl___pyx_unpickle_TCySaslClientTransport__set_state(struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *__pyx_v___pyx_result, PyObject *__pyx_v___pyx_state) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__pyx_unpickle_TCySaslClientTransport__set_state", 0); + + /* "(tree fragment)":12 + * return __pyx_result + * cdef __pyx_unpickle_TCySaslClientTransport__set_state(TCySaslClientTransport __pyx_result, __pyx_state: tuple): + * __pyx_result._TCySaslClientTransport__rbuf = __pyx_state[0]; __pyx_result._TCySaslClientTransport__wbuf = __pyx_state[1]; __pyx_result.encode = __pyx_state[2]; __pyx_result.encode_decided = __pyx_state[3]; __pyx_result.mechanism = __pyx_state[4]; __pyx_result.opened = __pyx_state[5]; __pyx_result.sasl = __pyx_state[6]; __pyx_result.sasl_client_factory = __pyx_state[7]; __pyx_result.trans = __pyx_state[8] # <<<<<<<<<<<<<< + * __Pyx_UpdateUnpickledDict(__pyx_result, __pyx_state, 9) +*/ + __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 0, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1, __Pyx_ReferenceSharing_FunctionArgument); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 12, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer))))) __PYX_ERR(1, 12, __pyx_L1_error) + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF((PyObject *)__pyx_v___pyx_result->_TCySaslClientTransport__rbuf); + __Pyx_DECREF((PyObject *)__pyx_v___pyx_result->_TCySaslClientTransport__rbuf); + __pyx_v___pyx_result->_TCySaslClientTransport__rbuf = ((struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *)__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 1, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1, __Pyx_ReferenceSharing_FunctionArgument); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 12, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer))))) __PYX_ERR(1, 12, __pyx_L1_error) + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF((PyObject *)__pyx_v___pyx_result->_TCySaslClientTransport__wbuf); + __Pyx_DECREF((PyObject *)__pyx_v___pyx_result->_TCySaslClientTransport__wbuf); + __pyx_v___pyx_result->_TCySaslClientTransport__wbuf = ((struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *)__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 2, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1, __Pyx_ReferenceSharing_FunctionArgument); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 12, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely((__pyx_t_2 == (int)-1) && PyErr_Occurred())) __PYX_ERR(1, 12, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v___pyx_result->encode = __pyx_t_2; + __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 3, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1, __Pyx_ReferenceSharing_FunctionArgument); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 12, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely((__pyx_t_2 == (int)-1) && PyErr_Occurred())) __PYX_ERR(1, 12, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v___pyx_result->encode_decided = __pyx_t_2; + __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 4, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1, __Pyx_ReferenceSharing_FunctionArgument); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 12, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(PyUnicode_CheckExact(__pyx_t_1))||((__pyx_t_1) == Py_None) || __Pyx_RaiseUnexpectedTypeError("str", __pyx_t_1))) __PYX_ERR(1, 12, __pyx_L1_error) + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF(__pyx_v___pyx_result->mechanism); + __Pyx_DECREF(__pyx_v___pyx_result->mechanism); + __pyx_v___pyx_result->mechanism = ((PyObject*)__pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 5, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1, __Pyx_ReferenceSharing_FunctionArgument); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 12, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely((__pyx_t_2 == (int)-1) && PyErr_Occurred())) __PYX_ERR(1, 12, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v___pyx_result->opened = __pyx_t_2; + __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 6, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1, __Pyx_ReferenceSharing_FunctionArgument); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 12, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF(__pyx_v___pyx_result->sasl); + __Pyx_DECREF(__pyx_v___pyx_result->sasl); + __pyx_v___pyx_result->sasl = __pyx_t_1; + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 7, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1, __Pyx_ReferenceSharing_FunctionArgument); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 12, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF(__pyx_v___pyx_result->sasl_client_factory); + __Pyx_DECREF(__pyx_v___pyx_result->sasl_client_factory); + __pyx_v___pyx_result->sasl_client_factory = __pyx_t_1; + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 8, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1, __Pyx_ReferenceSharing_FunctionArgument); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 12, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF(__pyx_v___pyx_result->__pyx_base.trans); + __Pyx_DECREF(__pyx_v___pyx_result->__pyx_base.trans); + __pyx_v___pyx_result->__pyx_base.trans = __pyx_t_1; + __pyx_t_1 = 0; + + /* "(tree fragment)":13 + * cdef __pyx_unpickle_TCySaslClientTransport__set_state(TCySaslClientTransport __pyx_result, __pyx_state: tuple): + * __pyx_result._TCySaslClientTransport__rbuf = __pyx_state[0]; __pyx_result._TCySaslClientTransport__wbuf = __pyx_state[1]; __pyx_result.encode = __pyx_state[2]; __pyx_result.encode_decided = __pyx_state[3]; __pyx_result.mechanism = __pyx_state[4]; __pyx_result.opened = __pyx_state[5]; __pyx_result.sasl = __pyx_state[6]; __pyx_result.sasl_client_factory = __pyx_state[7]; __pyx_result.trans = __pyx_state[8] + * __Pyx_UpdateUnpickledDict(__pyx_result, __pyx_state, 9) # <<<<<<<<<<<<<< +*/ + __pyx_t_3 = __Pyx_UpdateUnpickledDict(((PyObject *)__pyx_v___pyx_result), __pyx_v___pyx_state, 9); if (unlikely(__pyx_t_3 == ((int)-1))) __PYX_ERR(1, 13, __pyx_L1_error) + + /* "(tree fragment)":11 + * __pyx_unpickle_TCySaslClientTransport__set_state( __pyx_result, __pyx_state) + * return __pyx_result + * cdef __pyx_unpickle_TCySaslClientTransport__set_state(TCySaslClientTransport __pyx_result, __pyx_state: tuple): # <<<<<<<<<<<<<< + * __pyx_result._TCySaslClientTransport__rbuf = __pyx_state[0]; __pyx_result._TCySaslClientTransport__wbuf = __pyx_state[1]; __pyx_result.encode = __pyx_state[2]; __pyx_result.encode_decided = __pyx_state[3]; __pyx_result.mechanism = __pyx_state[4]; __pyx_result.opened = __pyx_state[5]; __pyx_result.sasl = __pyx_state[6]; __pyx_result.sasl_client_factory = __pyx_state[7]; __pyx_result.trans = __pyx_state[8] + * __Pyx_UpdateUnpickledDict(__pyx_result, __pyx_state, 9) +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("thriftpy2.transport.sasl.cysasl.__pyx_unpickle_TCySaslClientTransport__set_state", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} +/* #### Code section: module_exttypes ### */ +static struct __pyx_vtabstruct_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport __pyx_vtable_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport; + +static PyObject *__pyx_tp_new_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *p; + PyObject *o = __Pyx_PyType_GetSlot(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase, tp_new, newfunc)(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *)o); + p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_CyTransportBase*)__pyx_vtabptr_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport; + p->sasl = Py_None; Py_INCREF(Py_None); + p->sasl_client_factory = Py_None; Py_INCREF(Py_None); + p->_TCySaslClientTransport__wbuf = ((struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *)Py_None); Py_INCREF(Py_None); + p->_TCySaslClientTransport__rbuf = ((struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *)Py_None); Py_INCREF(Py_None); + p->mechanism = ((PyObject*)Py_None); Py_INCREF(Py_None); + return o; +} + +static void __pyx_tp_dealloc_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport(PyObject *o) { + struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *p = (struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *)o; + #if CYTHON_USE_TP_FINALIZE + if (unlikely(__Pyx_PyObject_GetSlot(o, tp_finalize, destructor)) && !__Pyx_PyObject_GC_IsFinalized(o)) { + if (__Pyx_PyObject_GetSlot(o, tp_dealloc, destructor) == __pyx_tp_dealloc_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + } + #endif + PyObject_GC_UnTrack(o); + Py_CLEAR(p->sasl); + Py_CLEAR(p->sasl_client_factory); + Py_CLEAR(p->_TCySaslClientTransport__wbuf); + Py_CLEAR(p->_TCySaslClientTransport__rbuf); + Py_CLEAR(p->mechanism); + if (PyType_IS_GC(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase)) PyObject_GC_Track(o); + #if !CYTHON_USE_MODULE_STATE + if (likely(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase)) __Pyx_PyType_GetSlot(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase, tp_dealloc, destructor)(o); else + #endif + __Pyx_call_next_tp_dealloc(o, __pyx_tp_dealloc_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport); +} + +static int __pyx_tp_traverse_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *p = (struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *)o; + #if !CYTHON_USE_MODULE_STATE + e = 0; + if (likely(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase)) { + traverseproc traverse = __Pyx_PyType_GetSlot(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase, tp_traverse, traverseproc); + if (traverse) { e = traverse(o, v, a); } + } else + #endif + { e = __Pyx_call_next_tp_traverse(o, v, a, __pyx_tp_traverse_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport); } + if (e) return e; + { + e = __Pyx_call_type_traverse(o, 0, v, a); + if (e) return e; + } + if (p->sasl) { + e = (*v)(p->sasl, a); if (e) return e; + } + if (p->sasl_client_factory) { + e = (*v)(p->sasl_client_factory, a); if (e) return e; + } + if (p->_TCySaslClientTransport__wbuf) { + e = (*v)(((PyObject *)p->_TCySaslClientTransport__wbuf), a); if (e) return e; + } + if (p->_TCySaslClientTransport__rbuf) { + e = (*v)(((PyObject *)p->_TCySaslClientTransport__rbuf), a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport(PyObject *o) { + PyObject* tmp; + struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *p = (struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport *)o; + #if !CYTHON_USE_MODULE_STATE + if (likely(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase)) { + inquiry clear = __Pyx_PyType_GetSlot(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase, tp_clear, inquiry); + if (clear) clear(o); + } else + #endif + { __Pyx_call_next_tp_clear(o, __pyx_tp_clear_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport); } + tmp = ((PyObject*)p->sasl); + p->sasl = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->sasl_client_factory); + p->sasl_client_factory = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->_TCySaslClientTransport__wbuf); + p->_TCySaslClientTransport__wbuf = ((struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->_TCySaslClientTransport__rbuf); + p->_TCySaslClientTransport__rbuf = ((struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer *)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); + return 0; +} + +static PyMethodDef __pyx_methods_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport[] = { + {"is_open", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_3is_open, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, + {"open", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_5open, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, + {"_send_message", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_7_send_message, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, + {"_recv_sasl_message", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_9_recv_sasl_message, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, + {"write", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_11write, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, + {"flush", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_13flush, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, + {"_flushEncoded", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_15_flushEncoded, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, + {"_flushPlain", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_17_flushPlain, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, + {"read", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_19read, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, + {"_read_frame", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_21_read_frame, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, + {"clean", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_23clean, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, + {"close", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_25close, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, + {"__reduce_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_27__reduce_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, + {"__setstate_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_29__setstate_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, + {0, 0, 0, 0} +}; +#if CYTHON_USE_TYPE_SPECS +static PyType_Slot __pyx_type_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport_slots[] = { + {Py_tp_dealloc, (void *)__pyx_tp_dealloc_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport}, + {Py_tp_doc, (void *)PyDoc_STR("sasl wrapper")}, + {Py_tp_traverse, (void *)__pyx_tp_traverse_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport}, + {Py_tp_clear, (void *)__pyx_tp_clear_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport}, + {Py_tp_methods, (void *)__pyx_methods_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport}, + {Py_tp_init, (void *)__pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_1__init__}, + {Py_tp_new, (void *)__pyx_tp_new_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport}, + {0, 0}, +}; +static PyType_Spec __pyx_type_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport_spec = { + "thriftpy2.transport.sasl.cysasl.TCySaslClientTransport", + sizeof(struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport), + 0, + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, + __pyx_type_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport_slots, +}; +#else + +static PyTypeObject __pyx_type_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport = { + PyVarObject_HEAD_INIT(0, 0) + "thriftpy2.transport.sasl.cysasl.""TCySaslClientTransport", /*tp_name*/ + sizeof(struct __pyx_obj_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport, /*tp_dealloc*/ + 0, /*tp_vectorcall_offset*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_as_async*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + PyDoc_STR("sasl wrapper"), /*tp_doc*/ + __pyx_tp_traverse_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport, /*tp_traverse*/ + __pyx_tp_clear_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + #if !CYTHON_USE_TYPE_SPECS + 0, /*tp_dictoffset*/ + #endif + __pyx_pw_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_1__init__, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if CYTHON_USE_TP_FINALIZE + 0, /*tp_finalize*/ + #else + NULL, /*tp_finalize*/ + #endif + #if !CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800 + 0, /*tp_vectorcall*/ + #endif + #if __PYX_NEED_TP_PRINT_SLOT == 1 + 0, /*tp_print*/ + #endif + #if PY_VERSION_HEX >= 0x030C0000 + 0, /*tp_watched*/ + #endif + #if PY_VERSION_HEX >= 0x030d00A4 + 0, /*tp_versions_used*/ + #endif + #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX >= 0x03090000 && PY_VERSION_HEX < 0x030a0000 + 0, /*tp_pypy_flags*/ + #endif +}; +#endif + +static PyMethodDef __pyx_methods[] = { + {0, 0, 0, 0} +}; +/* #### Code section: initfunc_declarations ### */ +static CYTHON_SMALL_CODE int __Pyx_InitCachedBuiltins(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_InitCachedConstants(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_InitGlobals(void); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_InitConstants(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_global_init_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_variable_export_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_function_export_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_type_init_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_type_import_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_variable_import_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_function_import_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_CreateCodeObjects(__pyx_mstatetype *__pyx_mstate); /*proto*/ +/* #### Code section: init_module ### */ + +static int __Pyx_modinit_global_init_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_modinit_global_init_code", 0); + /*--- Global init code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_modinit_variable_export_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_modinit_variable_export_code", 0); + /*--- Variable export code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_modinit_function_export_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_modinit_function_export_code", 0); + /*--- Function export code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_modinit_type_init_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__Pyx_modinit_type_init_code", 0); + /*--- Type init code ---*/ + __pyx_t_1 = PyImport_ImportModule("thriftpy2.transport.cybase"); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase = __Pyx_ImportType_3_2_4(__pyx_t_1, "thriftpy2.transport.cybase", "CyTransportBase", + #if defined(PYPY_VERSION_NUM) && PYPY_VERSION_NUM < 0x050B0000 + sizeof(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase), __PYX_GET_STRUCT_ALIGNMENT_3_2_4(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase), + #elif CYTHON_COMPILING_IN_LIMITED_API + sizeof(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase), __PYX_GET_STRUCT_ALIGNMENT_3_2_4(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase), + #else + sizeof(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase), __PYX_GET_STRUCT_ALIGNMENT_3_2_4(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase), + #endif + __Pyx_ImportType_CheckSize_Warn_3_2_4); if (!__pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_vtabptr_9thriftpy2_9transport_6cybase_CyTransportBase = (struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_CyTransportBase*)__Pyx_GetVtable(__pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase); if (unlikely(!__pyx_vtabptr_9thriftpy2_9transport_6cybase_CyTransportBase)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_vtabptr_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport = &__pyx_vtable_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport; + __pyx_vtable_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport.__pyx_base = *__pyx_vtabptr_9thriftpy2_9transport_6cybase_CyTransportBase; + __pyx_vtable_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport.__pyx_base.c_read = (PyObject *(*)(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *, int, char *))__pyx_f_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_c_read; + __pyx_vtable_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport.__pyx_base.c_write = (PyObject *(*)(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *, char *, int))__pyx_f_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_c_write; + __pyx_vtable_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport.__pyx_base.c_flush = (PyObject *(*)(struct __pyx_obj_9thriftpy2_9transport_6cybase_CyTransportBase *))__pyx_f_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_c_flush; + #if CYTHON_USE_TYPE_SPECS + __pyx_t_2 = PyTuple_Pack(1, (PyObject *)__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 18, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_mstate->__pyx_ptype_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport = (PyTypeObject *) __Pyx_PyType_FromModuleAndSpec(__pyx_m, &__pyx_type_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport_spec, __pyx_t_2); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_mstate->__pyx_ptype_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport)) __PYX_ERR(0, 18, __pyx_L1_error) + if (__Pyx_fix_up_extension_type_from_spec(&__pyx_type_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport_spec, __pyx_mstate->__pyx_ptype_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport) < (0)) __PYX_ERR(0, 18, __pyx_L1_error) + #else + __pyx_mstate->__pyx_ptype_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport = &__pyx_type_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport; + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + __pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport->tp_base = __pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_6cybase_CyTransportBase; + #endif + #if !CYTHON_USE_TYPE_SPECS + if (__Pyx_PyType_Ready(__pyx_mstate->__pyx_ptype_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport) < (0)) __PYX_ERR(0, 18, __pyx_L1_error) + #endif + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount((PyObject*)__pyx_mstate->__pyx_ptype_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport); + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_mstate->__pyx_ptype_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport->tp_dictoffset && __pyx_mstate->__pyx_ptype_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport->tp_getattro == PyObject_GenericGetAttr)) { + __pyx_mstate->__pyx_ptype_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport->tp_getattro = PyObject_GenericGetAttr; + } + #endif + #if CYTHON_UPDATE_DESCRIPTOR_DOC + { + PyObject *wrapper = PyObject_GetAttrString((PyObject *)__pyx_mstate->__pyx_ptype_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport, "__init__"); if (unlikely(!wrapper)) __PYX_ERR(0, 18, __pyx_L1_error) + if (__Pyx_IS_TYPE(wrapper, &PyWrapperDescr_Type)) { + __pyx_wrapperbase_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport___init__ = *((PyWrapperDescrObject *)wrapper)->d_base; + __pyx_wrapperbase_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport___init__.doc = __pyx_doc_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport___init__; + ((PyWrapperDescrObject *)wrapper)->d_base = &__pyx_wrapperbase_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport___init__; + } + } + #endif + if (__Pyx_SetVtable(__pyx_mstate->__pyx_ptype_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport, __pyx_vtabptr_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport) < (0)) __PYX_ERR(0, 18, __pyx_L1_error) + if (__Pyx_MergeVtables(__pyx_mstate->__pyx_ptype_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport) < (0)) __PYX_ERR(0, 18, __pyx_L1_error) + if (PyObject_SetAttr(__pyx_m, __pyx_mstate_global->__pyx_n_u_TCySaslClientTransport, (PyObject *) __pyx_mstate->__pyx_ptype_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport) < (0)) __PYX_ERR(0, 18, __pyx_L1_error) + if (__Pyx_setup_reduce((PyObject *) __pyx_mstate->__pyx_ptype_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport) < (0)) __PYX_ERR(0, 18, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_RefNannyFinishContext(); + return 0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_RefNannyFinishContext(); + return -1; +} + +static int __Pyx_modinit_type_import_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__Pyx_modinit_type_import_code", 0); + /*--- Type import code ---*/ + __pyx_t_1 = PyImport_ImportModule("thriftpy2.transport.cybase"); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 7, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer = __Pyx_ImportType_3_2_4(__pyx_t_1, "thriftpy2.transport.cybase", "TCyBuffer", + #if defined(PYPY_VERSION_NUM) && PYPY_VERSION_NUM < 0x050B0000 + sizeof(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer), __PYX_GET_STRUCT_ALIGNMENT_3_2_4(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer), + #elif CYTHON_COMPILING_IN_LIMITED_API + sizeof(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer), __PYX_GET_STRUCT_ALIGNMENT_3_2_4(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer), + #else + sizeof(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer), __PYX_GET_STRUCT_ALIGNMENT_3_2_4(struct __pyx_obj_9thriftpy2_9transport_6cybase_TCyBuffer), + #endif + __Pyx_ImportType_CheckSize_Warn_3_2_4); if (!__pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer) __PYX_ERR(2, 7, __pyx_L1_error) + __pyx_vtabptr_9thriftpy2_9transport_6cybase_TCyBuffer = (struct __pyx_vtabstruct_9thriftpy2_9transport_6cybase_TCyBuffer*)__Pyx_GetVtable(__pyx_mstate->__pyx_ptype_9thriftpy2_9transport_6cybase_TCyBuffer); if (unlikely(!__pyx_vtabptr_9thriftpy2_9transport_6cybase_TCyBuffer)) __PYX_ERR(2, 7, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_RefNannyFinishContext(); + return 0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_RefNannyFinishContext(); + return -1; +} + +static int __Pyx_modinit_variable_import_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_modinit_variable_import_code", 0); + /*--- Variable import code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_modinit_function_import_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_modinit_function_import_code", 0); + /*--- Function import code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +#if CYTHON_PEP489_MULTI_PHASE_INIT +static PyObject* __pyx_pymod_create(PyObject *spec, PyModuleDef *def); /*proto*/ +static int __pyx_pymod_exec_cysasl(PyObject* module); /*proto*/ +static PyModuleDef_Slot __pyx_moduledef_slots[] = { + {Py_mod_create, (void*)__pyx_pymod_create}, + {Py_mod_exec, (void*)__pyx_pymod_exec_cysasl}, + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + {Py_mod_gil, __Pyx_FREETHREADING_COMPATIBLE}, + #endif + #if PY_VERSION_HEX >= 0x030C0000 && CYTHON_USE_MODULE_STATE + {Py_mod_multiple_interpreters, Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED}, + #endif + {0, NULL} +}; +#endif + +#ifdef __cplusplus +namespace { + struct PyModuleDef __pyx_moduledef = + #else + static struct PyModuleDef __pyx_moduledef = + #endif + { + PyModuleDef_HEAD_INIT, + "cysasl", + 0, /* m_doc */ + #if CYTHON_USE_MODULE_STATE + sizeof(__pyx_mstatetype), /* m_size */ + #else + (CYTHON_PEP489_MULTI_PHASE_INIT) ? 0 : -1, /* m_size */ + #endif + __pyx_methods /* m_methods */, + #if CYTHON_PEP489_MULTI_PHASE_INIT + __pyx_moduledef_slots, /* m_slots */ + #else + NULL, /* m_reload */ + #endif + #if CYTHON_USE_MODULE_STATE + __pyx_m_traverse, /* m_traverse */ + __pyx_m_clear, /* m_clear */ + NULL /* m_free */ + #else + NULL, /* m_traverse */ + NULL, /* m_clear */ + NULL /* m_free */ + #endif + }; + #ifdef __cplusplus +} /* anonymous namespace */ +#endif + +/* PyModInitFuncType */ +#ifndef CYTHON_NO_PYINIT_EXPORT + #define __Pyx_PyMODINIT_FUNC PyMODINIT_FUNC +#else + #ifdef __cplusplus + #define __Pyx_PyMODINIT_FUNC extern "C" PyObject * + #else + #define __Pyx_PyMODINIT_FUNC PyObject * + #endif +#endif + +__Pyx_PyMODINIT_FUNC PyInit_cysasl(void) CYTHON_SMALL_CODE; /*proto*/ +__Pyx_PyMODINIT_FUNC PyInit_cysasl(void) +#if CYTHON_PEP489_MULTI_PHASE_INIT +{ + return PyModuleDef_Init(&__pyx_moduledef); +} +/* ModuleCreationPEP489 */ +#if CYTHON_COMPILING_IN_LIMITED_API && (__PYX_LIMITED_VERSION_HEX < 0x03090000\ + || ((defined(_WIN32) || defined(WIN32) || defined(MS_WINDOWS)) && __PYX_LIMITED_VERSION_HEX < 0x030A0000)) +static PY_INT64_T __Pyx_GetCurrentInterpreterId(void) { + { + PyObject *module = PyImport_ImportModule("_interpreters"); // 3.13+ I think + if (!module) { + PyErr_Clear(); // just try the 3.8-3.12 version + module = PyImport_ImportModule("_xxsubinterpreters"); + if (!module) goto bad; + } + PyObject *current = PyObject_CallMethod(module, "get_current", NULL); + Py_DECREF(module); + if (!current) goto bad; + if (PyTuple_Check(current)) { + PyObject *new_current = PySequence_GetItem(current, 0); + Py_DECREF(current); + current = new_current; + if (!new_current) goto bad; + } + long long as_c_int = PyLong_AsLongLong(current); + Py_DECREF(current); + return as_c_int; + } + bad: + PySys_WriteStderr("__Pyx_GetCurrentInterpreterId failed. Try setting the C define CYTHON_PEP489_MULTI_PHASE_INIT=0\n"); + return -1; +} +#endif +#if !CYTHON_USE_MODULE_STATE +static CYTHON_SMALL_CODE int __Pyx_check_single_interpreter(void) { + static PY_INT64_T main_interpreter_id = -1; +#if CYTHON_COMPILING_IN_GRAAL && defined(GRAALPY_VERSION_NUM) && GRAALPY_VERSION_NUM > 0x19000000 + PY_INT64_T current_id = GraalPyInterpreterState_GetIDFromThreadState(PyThreadState_Get()); +#elif CYTHON_COMPILING_IN_GRAAL + PY_INT64_T current_id = PyInterpreterState_GetIDFromThreadState(PyThreadState_Get()); +#elif CYTHON_COMPILING_IN_LIMITED_API && (__PYX_LIMITED_VERSION_HEX < 0x03090000\ + || ((defined(_WIN32) || defined(WIN32) || defined(MS_WINDOWS)) && __PYX_LIMITED_VERSION_HEX < 0x030A0000)) + PY_INT64_T current_id = __Pyx_GetCurrentInterpreterId(); +#elif CYTHON_COMPILING_IN_LIMITED_API + PY_INT64_T current_id = PyInterpreterState_GetID(PyInterpreterState_Get()); +#else + PY_INT64_T current_id = PyInterpreterState_GetID(PyThreadState_Get()->interp); +#endif + if (unlikely(current_id == -1)) { + return -1; + } + if (main_interpreter_id == -1) { + main_interpreter_id = current_id; + return 0; + } else if (unlikely(main_interpreter_id != current_id)) { + PyErr_SetString( + PyExc_ImportError, + "Interpreter change detected - this module can only be loaded into one interpreter per process."); + return -1; + } + return 0; +} +#endif +static CYTHON_SMALL_CODE int __Pyx_copy_spec_to_module(PyObject *spec, PyObject *moddict, const char* from_name, const char* to_name, int allow_none) +{ + PyObject *value = PyObject_GetAttrString(spec, from_name); + int result = 0; + if (likely(value)) { + if (allow_none || value != Py_None) { + result = PyDict_SetItemString(moddict, to_name, value); + } + Py_DECREF(value); + } else if (PyErr_ExceptionMatches(PyExc_AttributeError)) { + PyErr_Clear(); + } else { + result = -1; + } + return result; +} +static CYTHON_SMALL_CODE PyObject* __pyx_pymod_create(PyObject *spec, PyModuleDef *def) { + PyObject *module = NULL, *moddict, *modname; + CYTHON_UNUSED_VAR(def); + #if !CYTHON_USE_MODULE_STATE + if (__Pyx_check_single_interpreter()) + return NULL; + #endif + if (__pyx_m) + return __Pyx_NewRef(__pyx_m); + modname = PyObject_GetAttrString(spec, "name"); + if (unlikely(!modname)) goto bad; + module = PyModule_NewObject(modname); + Py_DECREF(modname); + if (unlikely(!module)) goto bad; + moddict = PyModule_GetDict(module); + if (unlikely(!moddict)) goto bad; + if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "loader", "__loader__", 1) < 0)) goto bad; + if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "origin", "__file__", 1) < 0)) goto bad; + if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "parent", "__package__", 1) < 0)) goto bad; + if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "submodule_search_locations", "__path__", 0) < 0)) goto bad; + return module; +bad: + Py_XDECREF(module); + return NULL; +} + + +static CYTHON_SMALL_CODE int __pyx_pymod_exec_cysasl(PyObject *__pyx_pyinit_module) +#endif +{ + int stringtab_initialized = 0; + #if CYTHON_USE_MODULE_STATE + int pystate_addmodule_run = 0; + #endif + __pyx_mstatetype *__pyx_mstate = NULL; + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + Py_ssize_t __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannyDeclarations + #if CYTHON_PEP489_MULTI_PHASE_INIT + if (__pyx_m) { + if (__pyx_m == __pyx_pyinit_module) return 0; + PyErr_SetString(PyExc_RuntimeError, "Module 'cysasl' has already been imported. Re-initialisation is not supported."); + return -1; + } + #else + if (__pyx_m) return __Pyx_NewRef(__pyx_m); + #endif + /*--- Module creation code ---*/ + #if CYTHON_PEP489_MULTI_PHASE_INIT + __pyx_t_1 = __pyx_pyinit_module; + Py_INCREF(__pyx_t_1); + #else + __pyx_t_1 = PyModule_Create(&__pyx_moduledef); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1, __pyx_L1_error) + #endif + #if CYTHON_USE_MODULE_STATE + { + int add_module_result = __Pyx_State_AddModule(__pyx_t_1, &__pyx_moduledef); + __pyx_t_1 = 0; /* transfer ownership from __pyx_t_1 to "cysasl" pseudovariable */ + if (unlikely((add_module_result < 0))) __PYX_ERR(0, 1, __pyx_L1_error) + pystate_addmodule_run = 1; + } + #else + __pyx_m = __pyx_t_1; + #endif + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + PyUnstable_Module_SetGIL(__pyx_m, Py_MOD_GIL_NOT_USED); + #endif + __pyx_mstate = __pyx_mstate_global; + CYTHON_UNUSED_VAR(__pyx_t_1); + __pyx_mstate->__pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_mstate->__pyx_d)) __PYX_ERR(0, 1, __pyx_L1_error) + Py_INCREF(__pyx_mstate->__pyx_d); + __pyx_mstate->__pyx_b = __Pyx_PyImport_AddModuleRef(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_mstate->__pyx_b)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_mstate->__pyx_cython_runtime = __Pyx_PyImport_AddModuleRef("cython_runtime"); if (unlikely(!__pyx_mstate->__pyx_cython_runtime)) __PYX_ERR(0, 1, __pyx_L1_error) + if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_mstate->__pyx_b) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + /* ImportRefnannyAPI */ + #if CYTHON_REFNANNY + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); + if (!__Pyx_RefNanny) { + PyErr_Clear(); + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); + if (!__Pyx_RefNanny) + Py_FatalError("failed to import 'refnanny' module"); + } + #endif + +__Pyx_RefNannySetupContext("PyInit_cysasl", 0); + __Pyx_init_runtime_version(); + if (__Pyx_check_binary_version(__PYX_LIMITED_VERSION_HEX, __Pyx_get_runtime_version(), CYTHON_COMPILING_IN_LIMITED_API) < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_mstate->__pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_mstate->__pyx_empty_tuple)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_mstate->__pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_mstate->__pyx_empty_bytes)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_mstate->__pyx_empty_unicode = PyUnicode_FromStringAndSize("", 0); if (unlikely(!__pyx_mstate->__pyx_empty_unicode)) __PYX_ERR(0, 1, __pyx_L1_error) + /*--- Library function declarations ---*/ + /*--- Initialize various global constants etc. ---*/ + if (__Pyx_InitConstants(__pyx_mstate) < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + stringtab_initialized = 1; + if (__Pyx_InitGlobals() < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + if (__pyx_module_is_main_thriftpy2__transport__sasl__cysasl) { + if (PyObject_SetAttr(__pyx_m, __pyx_mstate_global->__pyx_n_u_name, __pyx_mstate_global->__pyx_n_u_main) < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + } + { + PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) __PYX_ERR(0, 1, __pyx_L1_error) + if (!PyDict_GetItemString(modules, "thriftpy2.transport.sasl.cysasl")) { + if (unlikely((PyDict_SetItemString(modules, "thriftpy2.transport.sasl.cysasl", __pyx_m) < 0))) __PYX_ERR(0, 1, __pyx_L1_error) + } + } + /*--- Builtin init code ---*/ + if (__Pyx_InitCachedBuiltins(__pyx_mstate) < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + /*--- Constants init code ---*/ + if (__Pyx_InitCachedConstants(__pyx_mstate) < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + if (__Pyx_CreateCodeObjects(__pyx_mstate) < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + /*--- Global type/function init code ---*/ + (void)__Pyx_modinit_global_init_code(__pyx_mstate); + (void)__Pyx_modinit_variable_export_code(__pyx_mstate); + (void)__Pyx_modinit_function_export_code(__pyx_mstate); + if (unlikely((__Pyx_modinit_type_init_code(__pyx_mstate) < 0))) __PYX_ERR(0, 1, __pyx_L1_error) + if (unlikely((__Pyx_modinit_type_import_code(__pyx_mstate) < 0))) __PYX_ERR(0, 1, __pyx_L1_error) + (void)__Pyx_modinit_variable_import_code(__pyx_mstate); + (void)__Pyx_modinit_function_import_code(__pyx_mstate); + /*--- Execution code ---*/ + + /* "thriftpy2/transport/sasl/cysasl.pyx":3 + * # cython: freethreading_compatible = True + * + * import struct # <<<<<<<<<<<<<< + * + * from thriftpy2.transport.cybase cimport ( +*/ + __pyx_t_1 = __Pyx_Import(__pyx_mstate_global->__pyx_n_u_struct, 0, 0, NULL, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 3, __pyx_L1_error) + __pyx_t_2 = __pyx_t_1; + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_struct, __pyx_t_2) < (0)) __PYX_ERR(0, 3, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":11 + * ) + * + * from ..base import readall # <<<<<<<<<<<<<< + * from .. import TTransportException + * +*/ + { + PyObject* const __pyx_imported_names[] = {__pyx_mstate_global->__pyx_n_u_readall}; + __pyx_t_1 = __Pyx_Import(__pyx_mstate_global->__pyx_n_u_base, __pyx_imported_names, 1, __pyx_mstate_global->__pyx_kp_u_thriftpy2_transport_base, 2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 11, __pyx_L1_error) + } + __pyx_t_2 = __pyx_t_1; + __Pyx_GOTREF(__pyx_t_2); + { + PyObject* const __pyx_imported_names[] = {__pyx_mstate_global->__pyx_n_u_readall}; + __pyx_t_3 = 0; { + __pyx_t_4 = __Pyx_ImportFrom(__pyx_t_2, __pyx_imported_names[__pyx_t_3]); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 11, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_imported_names[__pyx_t_3], __pyx_t_4) < (0)) __PYX_ERR(0, 11, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + } + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":12 + * + * from ..base import readall + * from .. import TTransportException # <<<<<<<<<<<<<< + * + * from libc.string cimport memcpy +*/ + { + PyObject* const __pyx_imported_names[] = {__pyx_mstate_global->__pyx_n_u_TTransportException}; + __pyx_t_1 = __Pyx_Import(__pyx_mstate_global->__pyx_n_u__3, __pyx_imported_names, 1, __pyx_mstate_global->__pyx_kp_u_thriftpy2_transport, 2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 12, __pyx_L1_error) + } + __pyx_t_2 = __pyx_t_1; + __Pyx_GOTREF(__pyx_t_2); + { + PyObject* const __pyx_imported_names[] = {__pyx_mstate_global->__pyx_n_u_TTransportException}; + __pyx_t_3 = 0; { + __pyx_t_4 = __Pyx_ImportFrom(__pyx_t_2, __pyx_imported_names[__pyx_t_3]); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 12, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_imported_names[__pyx_t_3], __pyx_t_4) < (0)) __PYX_ERR(0, 12, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + } + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":21 + * """sasl wrapper""" + * + * START = 1 # <<<<<<<<<<<<<< + * OK = 2 + * BAD = 3 +*/ + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport, __pyx_mstate_global->__pyx_n_u_START, __pyx_mstate_global->__pyx_int_1) < (0)) __PYX_ERR(0, 21, __pyx_L1_error) + + /* "thriftpy2/transport/sasl/cysasl.pyx":22 + * + * START = 1 + * OK = 2 # <<<<<<<<<<<<<< + * BAD = 3 + * ERROR = 4 +*/ + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport, __pyx_mstate_global->__pyx_n_u_OK, __pyx_mstate_global->__pyx_int_2) < (0)) __PYX_ERR(0, 22, __pyx_L1_error) + + /* "thriftpy2/transport/sasl/cysasl.pyx":23 + * START = 1 + * OK = 2 + * BAD = 3 # <<<<<<<<<<<<<< + * ERROR = 4 + * COMPLETE = 5 +*/ + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport, __pyx_mstate_global->__pyx_n_u_BAD, __pyx_mstate_global->__pyx_int_3) < (0)) __PYX_ERR(0, 23, __pyx_L1_error) + + /* "thriftpy2/transport/sasl/cysasl.pyx":24 + * OK = 2 + * BAD = 3 + * ERROR = 4 # <<<<<<<<<<<<<< + * COMPLETE = 5 + * +*/ + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport, __pyx_mstate_global->__pyx_n_u_ERROR, __pyx_mstate_global->__pyx_int_4) < (0)) __PYX_ERR(0, 24, __pyx_L1_error) + + /* "thriftpy2/transport/sasl/cysasl.pyx":25 + * BAD = 3 + * ERROR = 4 + * COMPLETE = 5 # <<<<<<<<<<<<<< + * + * cdef object sasl, sasl_client_factory +*/ + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport, __pyx_mstate_global->__pyx_n_u_COMPLETE, __pyx_mstate_global->__pyx_int_5) < (0)) __PYX_ERR(0, 25, __pyx_L1_error) + + /* "thriftpy2/transport/sasl/cysasl.pyx":47 + * self.encode = False + * + * def is_open(self): # <<<<<<<<<<<<<< + * return self.trans.is_open() + * +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_3is_open, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_TCySaslClientTransport_is_open, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_transport_sasl_cysasl, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[0])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 47, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_2); + #endif + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport, __pyx_mstate_global->__pyx_n_u_is_open, __pyx_t_2) < (0)) __PYX_ERR(0, 47, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":50 + * return self.trans.is_open() + * + * def open(self): # <<<<<<<<<<<<<< + * if not self.is_open(): + * self.trans.open() +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_5open, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_TCySaslClientTransport_open, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_transport_sasl_cysasl, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[1])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 50, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_2); + #endif + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport, __pyx_mstate_global->__pyx_n_u_open, __pyx_t_2) < (0)) __PYX_ERR(0, 50, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":83 + * self._send_message(self.OK, response) + * + * def _send_message(self, status, body): # <<<<<<<<<<<<<< + * header = struct.pack(">BI", status, len(body)) + * self.trans.write(header + body) +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_7_send_message, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_TCySaslClientTransport__send_mes, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_transport_sasl_cysasl, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[2])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 83, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_2); + #endif + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport, __pyx_mstate_global->__pyx_n_u_send_message, __pyx_t_2) < (0)) __PYX_ERR(0, 83, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":88 + * self.trans.flush() + * + * def _recv_sasl_message(self): # <<<<<<<<<<<<<< + * header = readall(self.trans.read, 5) + * status, length = struct.unpack(">BI", header) +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_9_recv_sasl_message, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_TCySaslClientTransport__recv_sas, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_transport_sasl_cysasl, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[3])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 88, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_2); + #endif + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport, __pyx_mstate_global->__pyx_n_u_recv_sasl_message, __pyx_t_2) < (0)) __PYX_ERR(0, 88, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":97 + * return status, payload + * + * def write(self, bytes data): # <<<<<<<<<<<<<< + * cdef int sz = len(data) + * return self.c_write(data, sz) +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_11write, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_TCySaslClientTransport_write, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_transport_sasl_cysasl, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[4])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 97, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_2); + #endif + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport, __pyx_mstate_global->__pyx_n_u_write, __pyx_t_2) < (0)) __PYX_ERR(0, 97, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":113 + * raise MemoryError("Write to buffer error") + * + * def flush(self): # <<<<<<<<<<<<<< + * return self.c_flush() + * +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_13flush, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_TCySaslClientTransport_flush, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_transport_sasl_cysasl, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[5])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 113, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_2); + #endif + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport, __pyx_mstate_global->__pyx_n_u_flush, __pyx_t_2) < (0)) __PYX_ERR(0, 113, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":145 + * return("DUN FLUSHING IN SASL") + * + * def _flushEncoded(self, buffer): # <<<<<<<<<<<<<< + * # sasl.ecnode() does the encoding and adds the length header, so nothing + * # to do but call it and write the result. +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_15_flushEncoded, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_TCySaslClientTransport__flushEnc, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_transport_sasl_cysasl, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[6])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 145, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_2); + #endif + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport, __pyx_mstate_global->__pyx_n_u_flushEncoded, __pyx_t_2) < (0)) __PYX_ERR(0, 145, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":154 + * self.trans.write(encoded) + * + * def _flushPlain(self, buffer): # <<<<<<<<<<<<<< + * # When we have QOP of auth, sasl.encode() will pass the input to the output + * # but won't put a length header, so we have to do that. +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_17_flushPlain, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_TCySaslClientTransport__flushPla, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_transport_sasl_cysasl, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[7])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 154, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_2); + #endif + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport, __pyx_mstate_global->__pyx_n_u_flushPlain, __pyx_t_2) < (0)) __PYX_ERR(0, 154, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":165 + * self.trans.write(struct.pack(">I", len(buffer)) + buffer) + * + * def read(self, sz): # <<<<<<<<<<<<<< + * return self.get_string(sz) + * +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_19read, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_TCySaslClientTransport_read, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_transport_sasl_cysasl, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[8])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 165, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_2); + #endif + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport, __pyx_mstate_global->__pyx_n_u_read, __pyx_t_2) < (0)) __PYX_ERR(0, 165, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":189 + * memcpy(out, ret, orig_sz) + * + * def _read_frame(self): # <<<<<<<<<<<<<< + * header = readall(self.trans.read, 4) + * (length,) = struct.unpack(">I", header) +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_21_read_frame, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_TCySaslClientTransport__read_fra, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_transport_sasl_cysasl, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[9])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 189, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_2); + #endif + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport, __pyx_mstate_global->__pyx_n_u_read_frame, __pyx_t_2) < (0)) __PYX_ERR(0, 189, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":209 + * self.__rbuf.cur = 0 + * + * def clean(self): # <<<<<<<<<<<<<< + * self.__rbuf.clean() + * self.__wbuf.clean() +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_23clean, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_TCySaslClientTransport_clean, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_transport_sasl_cysasl, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[10])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 209, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_2); + #endif + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport, __pyx_mstate_global->__pyx_n_u_clean, __pyx_t_2) < (0)) __PYX_ERR(0, 209, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":213 + * self.__wbuf.clean() + * + * def close(self): # <<<<<<<<<<<<<< + * self.trans.close() + * self.sasl = None +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_25close, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_TCySaslClientTransport_close, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_transport_sasl_cysasl, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[11])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 213, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_2); + #endif + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport, __pyx_mstate_global->__pyx_n_u_close, __pyx_t_2) < (0)) __PYX_ERR(0, 213, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * cdef tuple state + * cdef object _dict +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_27__reduce_cython__, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_TCySaslClientTransport___reduce, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_transport_sasl_cysasl, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[12])); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 1, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_2); + #endif + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport, __pyx_mstate_global->__pyx_n_u_reduce_cython, __pyx_t_2) < (0)) __PYX_ERR(1, 1, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "(tree fragment)":16 + * else: + * return __pyx_unpickle_TCySaslClientTransport, (type(self), 0x02923b9, state) + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * __pyx_unpickle_TCySaslClientTransport__set_state(self, __pyx_state) +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_9transport_4sasl_6cysasl_22TCySaslClientTransport_29__setstate_cython__, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_TCySaslClientTransport___setstat, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_transport_sasl_cysasl, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[13])); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 16, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_2); + #endif + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_9thriftpy2_9transport_4sasl_6cysasl_TCySaslClientTransport, __pyx_mstate_global->__pyx_n_u_setstate_cython, __pyx_t_2) < (0)) __PYX_ERR(1, 16, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "(tree fragment)":4 + * int __Pyx_CheckUnpickleChecksum(long, long, long, long, const char*) except -1 + * int __Pyx_UpdateUnpickledDict(object, object, Py_ssize_t) except -1 + * def __pyx_unpickle_TCySaslClientTransport(__pyx_type, long __pyx_checksum, tuple __pyx_state): # <<<<<<<<<<<<<< + * cdef object __pyx_result + * __Pyx_CheckUnpickleChecksum(__pyx_checksum, 0x02923b9, 0x4ea3d29, 0x16559e7, b'_TCySaslClientTransport__rbuf, _TCySaslClientTransport__wbuf, encode, encode_decided, mechanism, opened, sasl, sasl_client_factory, trans') +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_9thriftpy2_9transport_4sasl_6cysasl_1__pyx_unpickle_TCySaslClientTransport, 0, __pyx_mstate_global->__pyx_n_u_pyx_unpickle_TCySaslClientTran, NULL, __pyx_mstate_global->__pyx_n_u_thriftpy2_transport_sasl_cysasl, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[14])); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 4, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_2); + #endif + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_pyx_unpickle_TCySaslClientTran, __pyx_t_2) < (0)) __PYX_ERR(1, 4, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "thriftpy2/transport/sasl/cysasl.pyx":1 + * # cython: freethreading_compatible = True # <<<<<<<<<<<<<< + * + * import struct +*/ + __pyx_t_2 = __Pyx_PyDict_NewPresized(0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_test, __pyx_t_2) < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /*--- Wrapped vars code ---*/ + + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_4); + if (__pyx_m) { + if (__pyx_mstate->__pyx_d && stringtab_initialized) { + __Pyx_AddTraceback("init thriftpy2.transport.sasl.cysasl", __pyx_clineno, __pyx_lineno, __pyx_filename); + } + #if !CYTHON_USE_MODULE_STATE + Py_CLEAR(__pyx_m); + #else + Py_DECREF(__pyx_m); + if (pystate_addmodule_run) { + PyObject *tp, *value, *tb; + PyErr_Fetch(&tp, &value, &tb); + PyState_RemoveModule(&__pyx_moduledef); + PyErr_Restore(tp, value, tb); + } + #endif + } else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_ImportError, "init thriftpy2.transport.sasl.cysasl"); + } + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + #if CYTHON_PEP489_MULTI_PHASE_INIT + return (__pyx_m != NULL) ? 0 : -1; + #else + return __pyx_m; + #endif +} +/* #### Code section: pystring_table ### */ +/* #### Code section: cached_builtins ### */ + +static int __Pyx_InitCachedBuiltins(__pyx_mstatetype *__pyx_mstate) { + CYTHON_UNUSED_VAR(__pyx_mstate); + + /* Cached unbound methods */ + __pyx_mstate->__pyx_umethod_PyDict_Type_items.type = (PyObject*)&PyDict_Type; + __pyx_mstate->__pyx_umethod_PyDict_Type_items.method_name = &__pyx_mstate->__pyx_n_u_items; + __pyx_mstate->__pyx_umethod_PyDict_Type_pop.type = (PyObject*)&PyDict_Type; + __pyx_mstate->__pyx_umethod_PyDict_Type_pop.method_name = &__pyx_mstate->__pyx_n_u_pop; + __pyx_mstate->__pyx_umethod_PyDict_Type_values.type = (PyObject*)&PyDict_Type; + __pyx_mstate->__pyx_umethod_PyDict_Type_values.method_name = &__pyx_mstate->__pyx_n_u_values; + return 0; +} +/* #### Code section: cached_constants ### */ + +static int __Pyx_InitCachedConstants(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); + __Pyx_RefNannyFinishContext(); + return 0; +} +/* #### Code section: init_constants ### */ + +static int __Pyx_InitConstants(__pyx_mstatetype *__pyx_mstate) { + CYTHON_UNUSED_VAR(__pyx_mstate); + { + const struct { const unsigned int length: 9; } index[] = {{2},{13},{3},{19},{12},{24},{20},{2},{179},{21},{1},{0},{1},{1},{8},{7},{6},{2},{9},{14},{20},{24},{35},{3},{8},{5},{8},{2},{20},{5},{22},{40},{42},{36},{34},{34},{41},{36},{28},{28},{28},{30},{27},{27},{28},{19},{7},{0},{18},{4},{4},{6},{11},{5},{18},{5},{1},{4},{6},{7},{8},{5},{6},{7},{5},{13},{11},{8},{8},{12},{6},{16},{13},{7},{5},{6},{8},{9},{7},{10},{8},{7},{4},{4},{7},{3},{14},{12},{11},{10},{37},{14},{12},{4},{11},{7},{18},{10},{17},{13},{8},{3},{19},{4},{13},{12},{10},{12},{19},{5},{5},{6},{4},{6},{7},{2},{8},{31},{5},{4},{6},{6},{12},{6},{5},{0},{11},{289},{63},{18},{31},{20},{192},{68},{24},{13},{11},{13},{45},{328},{59}}; + #if (CYTHON_COMPRESS_STRINGS) == 2 /* compression: bz2 (1755 bytes) */ +const char* const cstring = "BZh91AY&SY3\372^I\000\000\266\177\377\377\377\377\372\367\377\377\377\377\377\377\373\377\377\377\375\300@@@@@@@@@@@@\000@\000P\005\333y\272\354\3539p\326\200\003\200\3544D\020j\237\250\236\322O\320\006\251\352m\023\324\375\020\2314i\352l\2400\2151\000x\232\236\232\232z\232\036\247\243Sj2cB\031\036H4E\032S\375\024\332\207\350\217D\232z\211\210z\231\241\250\332\203\0020\001\036\220a4`L \323CF'\240\232d\304\323\r\001\004\215S\324\332\206\203\322\030\203\324\000\r\031\000\311\223\020\003@\000\032\000i\246\200\r=F\324\036\242\014\0010\230\023\t\204\323\004\304`\t\200#C&\0010\000\000\0020\023\000\000\002SP\230DO@M\r4\320h\023\3250\002\006\203M\032\000\000\000\000\000\000\000\000\311p\210\024\345\2442F C\266\014\310\314\300\372Z\375\031\013v\226\333\003\376;:\237'\235\366\351eg\350ij\352\353\354|\276\373\324\323\311\313\321/\372\362\326\265\256\255k]HZ\326\363\317;\361\332\372W~)\302\"\340R\224\252R\235q\273\013E\316 \377\271,\375\366\201\026\222\031\222\031 \022\220)n\363)\3066\030\263\023O\010 \0352#\371j\235\206\350\017\004&\2233\234\237\246\325\006\203\237X\251\270\033\n\352b\232(\n8\032:D\036`T\334I\226\255V&\250u\244\034\252\207\014\032K\254\226R\223T\314\306hf~\270\340\244\262yw?v\352K\232\262\332\353\312w\327\312\367\231\362\267\236&j\314%U\204\253\272\240xT;:\373\005b\361Ul\"^\226\241\241\2240\304\246$P!>S\225\2533y'\231\3779*C\243\261\225O\324\315\010!\004&\363\240\214\313\\\215\302J\023^\277\373\365,6\0102\353\032\t\216\262\r\016\001]Jk\331\260\300\017\t\214j\212APVz\3110\302\351%\206@u%\224\372\003n\307\252\272\263\004\324\326]\317\207^\305\033\234Y\345\262\376Cq\"\300E\"QD\021*\262\252\250\321\337\271\301\t\365\222\374\316\000\r8\000\025\337\272zo\337\2278\3743\177f\351\033\207\013\016)\335\275\215ms7\267\232\242\243j\277_+\225a\355\2068\322\2237\344\325\325z\325\334\006\337\277cc\332\266\010\300\272\242\351\017\037\300\343\214\027\014\305\020\345#\020\322\3068\354\233\026\353\225O\221\275\245\224**]\260\000\211\307\305\032TH\316\004\004\367c\274\374\211J""\004M\030\206tO\303=\333:\3017\365Z\021\024\306\333\252\243&r\232\210\344T))i\021\344\"3\001\"3\317\320\216Wf\n\316\224 %\001\016\032\246k|\330j\331\t\316\206ZUB\302#0\366\003+N\346!\257j\334\341\212\005\266\317\273\266\214\345\n\230b\313\n^8\026,\271+1\347\307\"\366l\225\324\302*T7\023\014d/\006,C]\323\272\271\202\\]ny\316\215UX^.o\0356g!\220\222e\014*\333Y\331v\236\027\314\216\022\252{ \235\325\351\233%\2444h{\014):\315\253\262\253a\305\377\314\250 \306\014\335\t\340\037LWs\334\265\361W&F\341\215\344\221yPg\214\307\002\2376\351[\014A\314!F\267WMA s\340\357\353\202\217#\023B\323e0;[\004\\0A\316\351+\0008\312\236\247\010\364\251\006\n\"\016\302A\207'R\245~\r\0147\203U\215h\365\254\226\246\251\216\313\2262\334\n\354m\212Z\321\270\306\024\352\311\327\027p\001\304\332\r\376y\303\223\257F\322\026\336\3454aQj\305\202\366ym\302\261\234\362\355\366\277\210\226\275}\226=\034\021\330\277\275\022\341s\006rh""n\027JR\236\256-\240\347r\200!\257\034\372\341\220\331\223\201\353\323\005\002N0m\266 b\272\254CXs\266\327\223g[\314\r\030\211J\024\355o\227\t\025\241h\310\201\335\311B)\nd\311\204\031\231m\027@\254\231\363yHZ\226\014\031\360\240\202)\327>\375\270g\003olt\356\361\244\323zZB\237\300\200e\366s\373\220y\210In\232\220\265\004T\010\203l\246L\270z1,\305\322\021\201\230\233\376\231\347\371\010\356\350r\204~\234\306\025P\211W\262\365\245\313\330\221\333\317\224b\240\311+\341\311\006\r\312\203\212N>\t\333\221\221\t\344b\243i\355\264 o\201\265\216\033.\344\346\3339\355\264\214-\353\355\352\264U\260\260\307\262\374\266lO\302\341\303\300\203%\341\307\202\255\273\376\026#\212\030\355>u\321\310\347DQ\323\367A\rO\370\356N\021\263\262\341\223\243z'y\261\240\201'T?\324\034\201\345\022\241w\236/\020\234\344\216\354\"\321\323?\246v\225\017\306\355\254]\235z9\365s(x\217*\265~\036\350#\301\225\220\311\006\244d(s\203*\223\032\026\362\020uX\3067\031\026\002\004\322\231R|#\321\250\353\334k\251!!$\231$\203QFhQw\376.\344\212p\241 g\364\274\222"; + PyObject *data = __Pyx_DecompressString(cstring, 1755, 2); + if (unlikely(!data)) __PYX_ERR(0, 1, __pyx_L1_error) + const char* const bytes = __Pyx_PyBytes_AsString(data); + #if !CYTHON_ASSUME_SAFE_MACROS + if (likely(bytes)); else { Py_DECREF(data); __PYX_ERR(0, 1, __pyx_L1_error) } + #endif + #elif (CYTHON_COMPRESS_STRINGS) != 0 /* compression: zlib (1607 bytes) */ +const char* const cstring = "x\332\205T\315W\333\306\026\217e\332\220\027\0220\345#mOO\345\236\0074\357\245\360\334\220\220&\357\245\317\200\t4\324\200\261C\223\236\327\311X\032a=\204dkF\330NzZ\226^j\251\245\226Zj\251%\313,\265\324\222?!\177\302\233;\302~\311\tn\027\322o\346\316\275w~\367k\344\257\213\206M\260\332\225\255&1\363\217W\267V\261*\357\027\367\267e\233P\307`\017\3459\n\"\3120s\350Cy\315r\014U6-\006\022\233\tU\320Y\257\225\345\215\355\332\376\346V\371\211\274U\026\362\307[e\213\021\23150\223\327\272\254a\231\262Ne\225\030z\235\330\230\021\243\313\235\330\272\302\210\rJ\246\274[\332\375f\371\301\262\214M\225_\377_\2420*S\247\256\030\230RBeK\223\353\216n0\335\224Y\267I\350\242\274\245\311]\313\221MBT\231Yr\223\353\275k\300\032\304\224)a\260\220\027\260\311ic\246[&\342\346\272y\270 \253\272\315/\321O\010Xo`\203\222\305\003[gb[w4\215\023#\266m\331\267\027\277\307\252\212\270=Qu\212\353\006!&\374\017\025\235\246+\365\237\020\212yH-\307V\310c\326\260u\2155\273\337.2\033\233\264i\331l\3612Y\035sz}\371\322@\276D15\226\224.\300b\263\333Y-\256\257\355\374\270\273]\252\226J\225\312N\245\274SE;\273\245\362\316S\204v\273\035\376\255\3634\2422\351\260\n\321\366\253\305J\265\272\326\335\347\326k\206NLV\355;\276\\\272\210\220MTG!H\021eBh\250\036\247\013\255\360\347\232\232\341\320F\311T,\225\250\177\250\263k`\335\034\246\001\275\2114\033\037\223\341\032\312\t\202<\241cB)>\034\252\310\013\245\376\211\216b\020l\016=\263\3500;\021\307\2203\235\"\030\255!\247\177p\004\241\0179jC\217V\007\373RG!M\350\353Z\371iy\347\240\214i\327TtkQ\261l\313\341\323B(\264Y\335R\273iO+\r\036\212\311s\2414D\304\212\301u\220\316\307\302\306\n\251c\345H\004\253\252\230a\225\210\n\246\177\204Th\263\024\210\250m\372WE\006\336\253\371;\305EHsL\005\241C\302J0Mb\225v\021j\360(\t\037\034\235\351\330\340\305\344\001\231\224\223\241h\300\376\"\203<\344cj\020\363\2205\020:\026n!\002l\352\364\370\242\254\\b\251\216\301\021!\223\367\214@\322F\302\276\311\343j\342\256aa\265i5\021\342c\205\224\006Q\216\250s\234\356\322\027/]_\320\203%\2745""\351\3121\233\272r\304\375_^\227T\351\204\301{\000W\267\034l\2444D\033\377\277\227a\205\r\343\303\336\035\314!\372`\"\007\002\322A\203<\331<\217`\256\010\"H\303\n\263\354.%\206\366^\273\213\261\275\310\010_\251D\303\"\320\3010\243K\006[\274\357B\224\276\375\224\221&\177\343\034\376(;\212\302\035\323W\010\301!\377_\362\262\211\247+}\301\204\020\262\350\210\"8M\336X\304\341U\356\337y\202\r\207P\321\325\247\231dd9,\206\317\242\302i1\031\275\336[\3561\367\201WH\306&\334\217]\342\025\316\205\354\304=\360\212\311\330d<9\347\357%\023\323\361\364\327A&\231\270\345e\222\321\261\336\246\273\036\337\272\023\024\317Go\364\376\023\177\366MP\r\247C-*F\325\263\\\352\263\325\267\365I\374\367\307\021N&>\215?]\016WC5\232\213\272o2o?\276r\355F\257\354\345\275e\257\343\267\300i\272q\374\"\234\375%\031\233r\177\360\324\370\253{\341^26\336k\273\rO\365\347|\026\024\222\211\231x\346v\220\013\346\342\245\325\263|2\365E\374\305\375\260\301/\021z\2127\345q\312\271d,\347~\356\255\373\037\371\265 \317\255\370!s/5\276\033\336\355\363\2024\334\364\260\307\374{A\346TP\231t?\023\274\236\004\205\240\330\217\356\306'\361'\363>\366\235\370\316\367Q+YX\nXx/\272\006\341\217\3656\334y/\343\345 \277\027\2334iE\356p\022\342N\025f X\377Yp7\300A7\222\242|j\360\304\275\357\345\006\013\220\345\334Y\256>\345=\363W\202|rm\312\335\360\026\374\234?\317+\002t\342\361/9\337e\277\365v\364\312\215Y\367\320\253xmN\215\005\367\303\331\210G4\355\276\020\361\\\rZafH\032\376\366m\370\327\220D\337\235A\310\302\311\036O\367<\330\000\225\037\\\335k\371Y\277\340o\006\305`/\031\275\331\303\334\315\2127\357_\365\273a6,\204\027\334\377%\264.6+^\376C\376\243\023\3565\036;Pl\007\030\"Xq\277ry\263\315\274{\3539\337\362\303\361^\307m\201\217\031^\327\234\227\007\211\350Wo\303\027\276a{\337\273\345\347\372\033~\326_>\342\205l\245\004f\\\307+z\007\234\376\232\310\302\240J\263\276\344\347\007\333\323\014\317\341G7{\3258W\010\247\342{\265\270\366<~^\217\353Z\254\265\343\366\353\267W\256\374\232\331\2248lJ\333\000\333R\r\240&=\007x.\275""\004x)\251\000\252\364\n\340\225\364\033\300o\322\357R2\002Y)\360\372\335\361q2r\365\364\244w\340\226D\277\216N\272\234\306\254\333:\347?\026\177\3760Z8\233>S\336L\305?\032\261Ac\332\211;\257\343\327\277sO\377\226\236\202\303\247R\005\240\"\035\000\034H/\000^H\277\000\374\322gp\004p$5\001\232\022\005\240R\033\240-mg!\200\354>\300~\366'\200\237\262?\003\374\234E\000(\253\001h\331c\200\343\254\231\005\316\274!\306\343\361\225\220E\205\350\311\331\2437\207q\355\331\371\373\"|\2329\037\371\322k\305\362?\302\353\321\243\263\243x\257\222\214\360\221\271\035\334\nsa\036\334\374\n\335\221\214>\2102\361w\225\270\3622~\3113r\275W\370\037&5Mr"; + PyObject *data = __Pyx_DecompressString(cstring, 1607, 1); + if (unlikely(!data)) __PYX_ERR(0, 1, __pyx_L1_error) + const char* const bytes = __Pyx_PyBytes_AsString(data); + #if !CYTHON_ASSUME_SAFE_MACROS + if (likely(bytes)); else { Py_DECREF(data); __PYX_ERR(0, 1, __pyx_L1_error) } + #endif + #else /* compression: none (2866 bytes) */ +const char* const bytes = " (Already open!>BIBad SASL result: %sBad status: Could not start SASL: %sDUN FLUSHING IN SASL>INote that Cython is deliberately stricter than PEP-484 and rejects subclasses of builtin types. If you need to pass subclasses then set the 'annotation_typing' directive to False.Write to buffer error).?add_notedisableenablegcisenabledthriftpy2.transport.thriftpy2.transport.basethriftpy2/transport/sasl/cysasl.pyxBADCOMPLETEERRORNOT_OPENOK__Pyx_PyDict_NextRefSTARTTCySaslClientTransportTCySaslClientTransport.__reduce_cython__TCySaslClientTransport.__setstate_cython__TCySaslClientTransport._flushEncodedTCySaslClientTransport._flushPlainTCySaslClientTransport._read_frameTCySaslClientTransport._recv_sasl_messageTCySaslClientTransport._send_messageTCySaslClientTransport.cleanTCySaslClientTransport.closeTCySaslClientTransport.flushTCySaslClientTransport.is_openTCySaslClientTransport.openTCySaslClientTransport.readTCySaslClientTransport.writeTTransportExceptionUNKNOWNasyncio.coroutinesbasebodybufferchosen_mechcleancline_in_tracebackcloseddatadecodedecoded__dict___dictencodeencodedflush_flushEncoded_flushPlain__func__getError__getstate__headerinitial_response_is_coroutineis_openitemslength__main__mechanismmessage__module____name____new__openpackpayloadpop__pyx_checksum__pyx_result__pyx_state__pyx_type__pyx_unpickle_TCySaslClientTransport__pyx_vtable____qualname__read_read_framereadall_recv_sasl_message__reduce____reduce_cython____reduce_ex__responseretsasl_client_factoryself_send_message__set_name__setdefault__setstate____setstate_cython__startstatestatusstepstructsuccesssz__test__thriftpy2.transport.sasl.cysasltranstypeunpackupdateuse_setstatevalueswrite\200\001\330\0044\260A\260V\2701\200A\330\010\013\2104\210t\2208\2301\330\014\020\220\006\220e\2301\340\010\013\2104\210v\220W\230A\330\014\022\320\022%\240Q\330\020\025\320\025(\250\001\330\020\030\230\001\330\010\014\210H\220D\320\030,\250A\340\010\r\210]\320\032-\250T\260\025\260f\270A\270T\300\021\330\010\013\2104""\210q\330\014\022\320\022%\240Q\240e\320+>\270a\330\020\031\320\0314\260B\260d\270%\270y\310\001\360\006\000\t\r\210N\230!\2304\230x\240q\330\010\014\210N\230!\2304\230u\240A\360\006\000\t\n\330\014\024\220J\230d\320\"5\260Q\330\014\017\210w\220h\230d\240%\240t\2501\330\020\026\320\026)\250\021\250%\320/B\300!\330\024\035\320\0356\260h\270a\330\014\017\210w\220c\230\024\230Q\330\020\021\330\014\021\220\033\230D\240\005\240U\250!\2501\330\014\017\210t\2201\330\020\026\320\026)\250\021\250%\320/B\300!\330\024\035\320\0353\2603\260d\270%\270y\310\001\330\014\020\220\016\230a\230t\2405\250\001\200A\360\006\000\t\022\220\032\2304\230u\240G\2501\250A\330\010\013\2104\210q\330\r\023\320\023&\240a\240u\320,?\270q\330'/\250t\2605\270\t\300\021\330\010\014\210F\220&\230\001\230\021\200A\330\010\014\210F\220&\230\001\330\010\014\210H\220A\200A\360\022\000\t\r\210F\220&\230\001\230\026\230u\240A\240V\2503\250a\250y\270\002\270!\200A\330\010\014\210G\2206\230\021\330\010\014\210G\2206\230\021\200A\330\010\021\220\027\230\001\230\024\230V\2407\250!\330\t\024\220F\230'\240\021\240&\250\001\330\010\013\2104\320\017\037\230t\2404\240q\360\010\000\r\027\220g\230R\230w\240a\240t\2506\260\027\270\001\330\014\025\220Z\230t\2405\250\007\250q\260\001\330\014\017\210t\2201\330\020\026\320\026)\250\021\250%\320/B\300!\330*2\260$\260e\2709\300A\360\006\000\r\027\220g\230Q\230d\240&\250\007\250q\330\010\014\210J\220i\230q\240\003\2401\240H\250A\250Q\330\010\016\210a\210t\2207\230&\240\007\240y\260\003\2601\260A\330\010\014\210G\220=\240\003\2401\240A\330\010\014\210G\2207\230!\200A\330\010\021\220\027\230\001\230\024\230V\2407\250!\330\010\020\220\t\230\026\230w\240a\240w\250a\330\010\013\2107\220\"\220A\330\014\026\220g\230Q\230d\240&\250\007\250q\340\014\026\220a\330\010\017\210x\220q\200A\330\010\026\220c\230\021\230!\330\010\017\210t\2208\2301\230F\240!\200A\330\010\017\210t\2206\230\030\240\021\200A\330\010\017\210t\2208\2301\200A\330\010\017\210t\220;\230a\230q\200A\330\010\021\220\026""\220u\230A\230W\240H\250C\250q\260\001\330\010\014\210F\220&\230\001\230\027\240\002\240!\330\010\014\210F\220&\230\001\200\001\360\010\000\005\016\210T\320\0211\260\024\3205U\320UY\320Yb\320bf\320fw\320w{\360\000\000|\001H\002\360\000\000H\002L\002\360\000\000L\002U\002\360\000\000U\002Y\002\360\000\000Y\002`\002\360\000\000`\002d\002\360\000\000d\002z\002\360\000\000z\002~\002\360\000\000~\002\177\002\330\004\014\210G\2201\220F\230,\240a\330\004\007\200v\210W\220E\230\024\230Q\330\010\022\220!\330\010\027\220q\340\010\027\220t\320\033:\270'\300\025\300c\310\024\320Ml\320ls\320sx\320x{\320{\177\360\000\000@\002K\002\360\000\000K\002R\002\360\000\000R\002W\002\360\000\000W\002Z\002\360\000\000Z\002^\002\360\000\000^\002d\002\360\000\000d\002k\002\360\000\000k\002p\002\360\000\000p\002s\002\360\000\000s\002w\002\360\000\000w\002L\003\360\000\000L\003S\003\360\000\000S\003X\003\360\000\000X\003[\003\360\000\000[\003_\003\360\000\000_\003f\003\360\000\000f\003m\003\360\000\000m\003n\003\330\004\007\200q\330\010\017\320\0177\260t\2701\270G\300;\310g\320UV\340\010\017\320\0177\260t\2701\270G\300;\310a\200\001\340\004\037\230q\320 0\260\013\270;\300k\320QR\330\004\023\320\023)\250\030\260\021\260!\330\004\007\200|\2207\230!\330\0108\270\001\3209R\320R`\320`a\330\004\013\2101"; + PyObject *data = NULL; + CYTHON_UNUSED_VAR(__Pyx_DecompressString); + #endif + PyObject **stringtab = __pyx_mstate->__pyx_string_tab; + Py_ssize_t pos = 0; + for (int i = 0; i < 125; i++) { + Py_ssize_t bytes_length = index[i].length; + PyObject *string = PyUnicode_DecodeUTF8(bytes + pos, bytes_length, NULL); + if (likely(string) && i >= 23) PyUnicode_InternInPlace(&string); + if (unlikely(!string)) { + Py_XDECREF(data); + __PYX_ERR(0, 1, __pyx_L1_error) + } + stringtab[i] = string; + pos += bytes_length; + } + for (int i = 125; i < 141; i++) { + Py_ssize_t bytes_length = index[i].length; + PyObject *string = PyBytes_FromStringAndSize(bytes + pos, bytes_length); + stringtab[i] = string; + pos += bytes_length; + if (unlikely(!string)) { + Py_XDECREF(data); + __PYX_ERR(0, 1, __pyx_L1_error) + } + } + Py_XDECREF(data); + for (Py_ssize_t i = 0; i < 141; i++) { + if (unlikely(PyObject_Hash(stringtab[i]) == -1)) { + __PYX_ERR(0, 1, __pyx_L1_error) + } + } + #if CYTHON_IMMORTAL_CONSTANTS + { + PyObject **table = stringtab + 125; + for (Py_ssize_t i=0; i<16; ++i) { + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + #if PY_VERSION_HEX < 0x030E0000 + if (_Py_IsOwnedByCurrentThread(table[i]) && Py_REFCNT(table[i]) == 1) + #else + if (PyUnstable_Object_IsUniquelyReferenced(table[i])) + #endif + { + Py_SET_REFCNT(table[i], _Py_IMMORTAL_REFCNT_LOCAL); + } + #else + Py_SET_REFCNT(table[i], _Py_IMMORTAL_INITIAL_REFCNT); + #endif + } + } + #endif + } + { + PyObject **numbertab = __pyx_mstate->__pyx_number_tab + 0; + int8_t const cint_constants_1[] = {0,1,2,3,4,5}; + int32_t const cint_constants_4[] = {2696121L}; + for (int i = 0; i < 7; i++) { + numbertab[i] = PyLong_FromLong((i < 6 ? cint_constants_1[i - 0] : cint_constants_4[i - 6])); + if (unlikely(!numbertab[i])) __PYX_ERR(0, 1, __pyx_L1_error) + } + } + #if CYTHON_IMMORTAL_CONSTANTS + { + PyObject **table = __pyx_mstate->__pyx_number_tab; + for (Py_ssize_t i=0; i<7; ++i) { + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + #if PY_VERSION_HEX < 0x030E0000 + if (_Py_IsOwnedByCurrentThread(table[i]) && Py_REFCNT(table[i]) == 1) + #else + if (PyUnstable_Object_IsUniquelyReferenced(table[i])) + #endif + { + Py_SET_REFCNT(table[i], _Py_IMMORTAL_REFCNT_LOCAL); + } + #else + Py_SET_REFCNT(table[i], _Py_IMMORTAL_INITIAL_REFCNT); + #endif + } + } + #endif + return 0; + __pyx_L1_error:; + return -1; +} +/* #### Code section: init_codeobjects ### */ +typedef struct { + unsigned int argcount : 2; + unsigned int num_posonly_args : 1; + unsigned int num_kwonly_args : 1; + unsigned int nlocals : 3; + unsigned int flags : 10; + unsigned int first_line : 8; +} __Pyx_PyCode_New_function_description; +/* NewCodeObj.proto */ +static PyObject* __Pyx_PyCode_New( + const __Pyx_PyCode_New_function_description descr, + PyObject * const *varnames, + PyObject *filename, + PyObject *funcname, + PyObject *line_table, + PyObject *tuple_dedup_map +); + + +static int __Pyx_CreateCodeObjects(__pyx_mstatetype *__pyx_mstate) { + PyObject* tuple_dedup_map = PyDict_New(); + if (unlikely(!tuple_dedup_map)) return -1; + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 47}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[0] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_thriftpy2_transport_sasl_cysasl_2, __pyx_mstate->__pyx_n_u_is_open, __pyx_mstate->__pyx_kp_b_iso88591_A_t6, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[0])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 7, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 50}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_ret, __pyx_mstate->__pyx_n_u_chosen_mech, __pyx_mstate->__pyx_n_u_initial_response, __pyx_mstate->__pyx_n_u_status, __pyx_mstate->__pyx_n_u_payload, __pyx_mstate->__pyx_n_u_response}; + __pyx_mstate_global->__pyx_codeobj_tab[1] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_thriftpy2_transport_sasl_cysasl_2, __pyx_mstate->__pyx_n_u_open, __pyx_mstate->__pyx_kp_b_iso88591_A_4t81_e1_4vWA_Q_HD_A_T_fAT_4q_Q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[1])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {3, 0, 0, 4, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 83}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_status, __pyx_mstate->__pyx_n_u_body, __pyx_mstate->__pyx_n_u_header}; + __pyx_mstate_global->__pyx_codeobj_tab[2] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_thriftpy2_transport_sasl_cysasl_2, __pyx_mstate->__pyx_n_u_send_message, __pyx_mstate->__pyx_kp_b_iso88591_A_uAWHCq_F_F, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[2])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 5, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 88}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_header, __pyx_mstate->__pyx_n_u_status, __pyx_mstate->__pyx_n_u_length, __pyx_mstate->__pyx_n_u_payload}; + __pyx_mstate_global->__pyx_codeobj_tab[3] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_thriftpy2_transport_sasl_cysasl_2, __pyx_mstate->__pyx_n_u_recv_sasl_message, __pyx_mstate->__pyx_kp_b_iso88591_A_V7_wawa_7_A_gQd_q_a_xq, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[3])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 3, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 97}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_data, __pyx_mstate->__pyx_n_u_sz}; + __pyx_mstate_global->__pyx_codeobj_tab[4] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_thriftpy2_transport_sasl_cysasl_2, __pyx_mstate->__pyx_n_u_write, __pyx_mstate->__pyx_kp_b_iso88591_A_c_t81F, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[4])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 113}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[5] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_thriftpy2_transport_sasl_cysasl_2, __pyx_mstate->__pyx_n_u_flush, __pyx_mstate->__pyx_kp_b_iso88591_A_t81, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[5])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 4, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 145}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_buffer, __pyx_mstate->__pyx_n_u_success, __pyx_mstate->__pyx_n_u_encoded}; + __pyx_mstate_global->__pyx_codeobj_tab[6] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_thriftpy2_transport_sasl_cysasl_2, __pyx_mstate->__pyx_n_u_flushEncoded, __pyx_mstate->__pyx_kp_b_iso88591_A_4uG1A_4q_au_q_t5_F, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[6])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 154}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_buffer}; + __pyx_mstate_global->__pyx_codeobj_tab[7] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_thriftpy2_transport_sasl_cysasl_2, __pyx_mstate->__pyx_n_u_flushPlain, __pyx_mstate->__pyx_kp_b_iso88591_A_F_uAV3ay, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[7])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 165}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_sz}; + __pyx_mstate_global->__pyx_codeobj_tab[8] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_thriftpy2_transport_sasl_cysasl_2, __pyx_mstate->__pyx_n_u_read, __pyx_mstate->__pyx_kp_b_iso88591_A_t_aq, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[8])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 6, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 189}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_header, __pyx_mstate->__pyx_n_u_length, __pyx_mstate->__pyx_n_u_encoded, __pyx_mstate->__pyx_n_u_success, __pyx_mstate->__pyx_n_u_decoded}; + __pyx_mstate_global->__pyx_codeobj_tab[9] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_thriftpy2_transport_sasl_cysasl_2, __pyx_mstate->__pyx_n_u_read_frame, __pyx_mstate->__pyx_kp_b_iso88591_A_V7_F_4_t4q_gRwat6_Zt5_q_t1_B_2, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[9])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 209}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[10] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_thriftpy2_transport_sasl_cysasl_2, __pyx_mstate->__pyx_n_u_clean, __pyx_mstate->__pyx_kp_b_iso88591_A_G6_G6, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[10])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 213}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[11] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_thriftpy2_transport_sasl_cysasl_2, __pyx_mstate->__pyx_n_u_close, __pyx_mstate->__pyx_kp_b_iso88591_A_F_HA, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[11])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 4, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 1}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_state, __pyx_mstate->__pyx_n_u_dict_2, __pyx_mstate->__pyx_n_u_use_setstate}; + __pyx_mstate_global->__pyx_codeobj_tab[12] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_stringsource, __pyx_mstate->__pyx_n_u_reduce_cython, __pyx_mstate->__pyx_kp_b_iso88591_T_1_5UUYYbbffww_H_H_L_L_U_U_Y_Y, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[12])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 16}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_pyx_state}; + __pyx_mstate_global->__pyx_codeobj_tab[13] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_stringsource, __pyx_mstate->__pyx_n_u_setstate_cython, __pyx_mstate->__pyx_kp_b_iso88591_4AV1, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[13])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {3, 0, 0, 4, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 4}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_pyx_type, __pyx_mstate->__pyx_n_u_pyx_checksum, __pyx_mstate->__pyx_n_u_pyx_state, __pyx_mstate->__pyx_n_u_pyx_result}; + __pyx_mstate_global->__pyx_codeobj_tab[14] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_stringsource, __pyx_mstate->__pyx_n_u_pyx_unpickle_TCySaslClientTran, __pyx_mstate->__pyx_kp_b_iso88591_q_0_kQR_7_8_9RR_a_1, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[14])) goto bad; + } + Py_DECREF(tuple_dedup_map); + return 0; + bad: + Py_DECREF(tuple_dedup_map); + return -1; +} +/* #### Code section: init_globals ### */ + +static int __Pyx_InitGlobals(void) { + /* PythonCompatibility.init */ + if (likely(__Pyx_init_co_variables() == 0)); else + + if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 1, __pyx_L1_error) + + /* CommonTypesMetaclass.init */ + if (likely(__pyx_CommonTypesMetaclass_init(__pyx_m) == 0)); else + + if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 1, __pyx_L1_error) + + /* CachedMethodType.init */ + #if CYTHON_COMPILING_IN_LIMITED_API + { + PyObject *typesModule=NULL; + typesModule = PyImport_ImportModule("types"); + if (typesModule) { + __pyx_mstate_global->__Pyx_CachedMethodType = PyObject_GetAttrString(typesModule, "MethodType"); + Py_DECREF(typesModule); + } + } // error handling follows + #endif + + if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 1, __pyx_L1_error) + + /* CythonFunctionShared.init */ + if (likely(__pyx_CyFunction_init(__pyx_m) == 0)); else + + if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 1, __pyx_L1_error) + + return 0; + __pyx_L1_error:; + return -1; +} +/* #### Code section: cleanup_globals ### */ +/* #### Code section: cleanup_module ### */ +/* #### Code section: main_method ### */ +/* #### Code section: utility_code_pragmas ### */ +#ifdef _MSC_VER +#pragma warning( push ) +/* Warning 4127: conditional expression is constant + * Cython uses constant conditional expressions to allow in inline functions to be optimized at + * compile-time, so this warning is not useful + */ +#pragma warning( disable : 4127 ) +#endif + + + +/* #### Code section: utility_code_def ### */ + +/* --- Runtime support code --- */ +/* Refnanny */ +#if CYTHON_REFNANNY +static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { + PyObject *m = NULL, *p = NULL; + void *r = NULL; + m = PyImport_ImportModule(modname); + if (!m) goto end; + p = PyObject_GetAttrString(m, "RefNannyAPI"); + if (!p) goto end; + r = PyLong_AsVoidPtr(p); +end: + Py_XDECREF(p); + Py_XDECREF(m); + return (__Pyx_RefNannyAPIStruct *)r; +} +#endif + +/* TupleAndListFromArray (used by fastcall) */ +#if !CYTHON_COMPILING_IN_CPYTHON && CYTHON_METH_FASTCALL +static CYTHON_INLINE PyObject * +__Pyx_PyTuple_FromArray(PyObject *const *src, Py_ssize_t n) +{ + PyObject *res; + Py_ssize_t i; + if (n <= 0) { + return __Pyx_NewRef(__pyx_mstate_global->__pyx_empty_tuple); + } + res = PyTuple_New(n); + if (unlikely(res == NULL)) return NULL; + for (i = 0; i < n; i++) { + if (unlikely(__Pyx_PyTuple_SET_ITEM(res, i, src[i]) < (0))) { + Py_DECREF(res); + return NULL; + } + Py_INCREF(src[i]); + } + return res; +} +#elif CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE void __Pyx_copy_object_array(PyObject *const *CYTHON_RESTRICT src, PyObject** CYTHON_RESTRICT dest, Py_ssize_t length) { + PyObject *v; + Py_ssize_t i; + for (i = 0; i < length; i++) { + v = dest[i] = src[i]; + Py_INCREF(v); + } +} +static CYTHON_INLINE PyObject * +__Pyx_PyTuple_FromArray(PyObject *const *src, Py_ssize_t n) +{ + PyObject *res; + if (n <= 0) { + return __Pyx_NewRef(__pyx_mstate_global->__pyx_empty_tuple); + } + res = PyTuple_New(n); + if (unlikely(res == NULL)) return NULL; + __Pyx_copy_object_array(src, ((PyTupleObject*)res)->ob_item, n); + return res; +} +static CYTHON_INLINE PyObject * +__Pyx_PyList_FromArray(PyObject *const *src, Py_ssize_t n) +{ + PyObject *res; + if (n <= 0) { + return PyList_New(0); + } + res = PyList_New(n); + if (unlikely(res == NULL)) return NULL; + __Pyx_copy_object_array(src, ((PyListObject*)res)->ob_item, n); + return res; +} +#endif + +/* BytesEquals (used by UnicodeEquals) */ +static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals) { +#if CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_GRAAL ||\ + !(CYTHON_ASSUME_SAFE_SIZE && CYTHON_ASSUME_SAFE_MACROS) + return PyObject_RichCompareBool(s1, s2, equals); +#else + if (s1 == s2) { + return (equals == Py_EQ); + } else if (PyBytes_CheckExact(s1) & PyBytes_CheckExact(s2)) { + const char *ps1, *ps2; + Py_ssize_t length = PyBytes_GET_SIZE(s1); + if (length != PyBytes_GET_SIZE(s2)) + return (equals == Py_NE); + ps1 = PyBytes_AS_STRING(s1); + ps2 = PyBytes_AS_STRING(s2); + if (ps1[0] != ps2[0]) { + return (equals == Py_NE); + } else if (length == 1) { + return (equals == Py_EQ); + } else { + int result; +#if CYTHON_USE_UNICODE_INTERNALS && (PY_VERSION_HEX < 0x030B0000) + Py_hash_t hash1, hash2; + hash1 = ((PyBytesObject*)s1)->ob_shash; + hash2 = ((PyBytesObject*)s2)->ob_shash; + if (hash1 != hash2 && hash1 != -1 && hash2 != -1) { + return (equals == Py_NE); + } +#endif + result = memcmp(ps1, ps2, (size_t)length); + return (equals == Py_EQ) ? (result == 0) : (result != 0); + } + } else if ((s1 == Py_None) & PyBytes_CheckExact(s2)) { + return (equals == Py_NE); + } else if ((s2 == Py_None) & PyBytes_CheckExact(s1)) { + return (equals == Py_NE); + } else { + int result; + PyObject* py_result = PyObject_RichCompare(s1, s2, equals); + if (!py_result) + return -1; + result = __Pyx_PyObject_IsTrue(py_result); + Py_DECREF(py_result); + return result; + } +#endif +} + +/* UnicodeEquals (used by fastcall) */ +static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals) { +#if CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_GRAAL + return PyObject_RichCompareBool(s1, s2, equals); +#else + int s1_is_unicode, s2_is_unicode; + if (s1 == s2) { + goto return_eq; + } + s1_is_unicode = PyUnicode_CheckExact(s1); + s2_is_unicode = PyUnicode_CheckExact(s2); + if (s1_is_unicode & s2_is_unicode) { + Py_ssize_t length, length2; + int kind; + void *data1, *data2; + #if !CYTHON_COMPILING_IN_LIMITED_API + if (unlikely(__Pyx_PyUnicode_READY(s1) < 0) || unlikely(__Pyx_PyUnicode_READY(s2) < 0)) + return -1; + #endif + length = __Pyx_PyUnicode_GET_LENGTH(s1); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(length < 0)) return -1; + #endif + length2 = __Pyx_PyUnicode_GET_LENGTH(s2); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(length2 < 0)) return -1; + #endif + if (length != length2) { + goto return_ne; + } +#if CYTHON_USE_UNICODE_INTERNALS + { + Py_hash_t hash1, hash2; + hash1 = ((PyASCIIObject*)s1)->hash; + hash2 = ((PyASCIIObject*)s2)->hash; + if (hash1 != hash2 && hash1 != -1 && hash2 != -1) { + goto return_ne; + } + } +#endif + kind = __Pyx_PyUnicode_KIND(s1); + if (kind != __Pyx_PyUnicode_KIND(s2)) { + goto return_ne; + } + data1 = __Pyx_PyUnicode_DATA(s1); + data2 = __Pyx_PyUnicode_DATA(s2); + if (__Pyx_PyUnicode_READ(kind, data1, 0) != __Pyx_PyUnicode_READ(kind, data2, 0)) { + goto return_ne; + } else if (length == 1) { + goto return_eq; + } else { + int result = memcmp(data1, data2, (size_t)(length * kind)); + return (equals == Py_EQ) ? (result == 0) : (result != 0); + } + } else if ((s1 == Py_None) & s2_is_unicode) { + goto return_ne; + } else if ((s2 == Py_None) & s1_is_unicode) { + goto return_ne; + } else { + int result; + PyObject* py_result = PyObject_RichCompare(s1, s2, equals); + if (!py_result) + return -1; + result = __Pyx_PyObject_IsTrue(py_result); + Py_DECREF(py_result); + return result; + } +return_eq: + return (equals == Py_EQ); +return_ne: + return (equals == Py_NE); +#endif +} + +/* fastcall */ +#if CYTHON_METH_FASTCALL +static CYTHON_INLINE PyObject * __Pyx_GetKwValue_FASTCALL(PyObject *kwnames, PyObject *const *kwvalues, PyObject *s) +{ + Py_ssize_t i, n = __Pyx_PyTuple_GET_SIZE(kwnames); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(n == -1)) return NULL; + #endif + for (i = 0; i < n; i++) + { + PyObject *namei = __Pyx_PyTuple_GET_ITEM(kwnames, i); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(!namei)) return NULL; + #endif + if (s == namei) return kwvalues[i]; + } + for (i = 0; i < n; i++) + { + PyObject *namei = __Pyx_PyTuple_GET_ITEM(kwnames, i); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(!namei)) return NULL; + #endif + int eq = __Pyx_PyUnicode_Equals(s, namei, Py_EQ); + if (unlikely(eq != 0)) { + if (unlikely(eq < 0)) return NULL; + return kwvalues[i]; + } + } + return NULL; +} +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030d0000 || CYTHON_COMPILING_IN_LIMITED_API +CYTHON_UNUSED static PyObject *__Pyx_KwargsAsDict_FASTCALL(PyObject *kwnames, PyObject *const *kwvalues) { + Py_ssize_t i, nkwargs; + PyObject *dict; +#if !CYTHON_ASSUME_SAFE_SIZE + nkwargs = PyTuple_Size(kwnames); + if (unlikely(nkwargs < 0)) return NULL; +#else + nkwargs = PyTuple_GET_SIZE(kwnames); +#endif + dict = PyDict_New(); + if (unlikely(!dict)) + return NULL; + for (i=0; itp_call; + if (unlikely(!call)) + return PyObject_Call(func, arg, kw); + if (unlikely(Py_EnterRecursiveCall(" while calling a Python object"))) + return NULL; + result = (*call)(func, arg, kw); + Py_LeaveRecursiveCall(); + if (unlikely(!result) && unlikely(!PyErr_Occurred())) { + PyErr_SetString( + PyExc_SystemError, + "NULL result without error in PyObject_Call"); + } + return result; +} +#endif + +/* PyObjectCallMethO (used by PyObjectFastCall) */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg) { + PyObject *self, *result; + PyCFunction cfunc; + cfunc = __Pyx_CyOrPyCFunction_GET_FUNCTION(func); + self = __Pyx_CyOrPyCFunction_GET_SELF(func); + if (unlikely(Py_EnterRecursiveCall(" while calling a Python object"))) + return NULL; + result = cfunc(self, arg); + Py_LeaveRecursiveCall(); + if (unlikely(!result) && unlikely(!PyErr_Occurred())) { + PyErr_SetString( + PyExc_SystemError, + "NULL result without error in PyObject_Call"); + } + return result; +} +#endif + +/* PyObjectFastCall (used by PyObjectCallOneArg) */ +#if PY_VERSION_HEX < 0x03090000 || CYTHON_COMPILING_IN_LIMITED_API +static PyObject* __Pyx_PyObject_FastCall_fallback(PyObject *func, PyObject * const*args, size_t nargs, PyObject *kwargs) { + PyObject *argstuple; + PyObject *result = 0; + size_t i; + argstuple = PyTuple_New((Py_ssize_t)nargs); + if (unlikely(!argstuple)) return NULL; + for (i = 0; i < nargs; i++) { + Py_INCREF(args[i]); + if (__Pyx_PyTuple_SET_ITEM(argstuple, (Py_ssize_t)i, args[i]) != (0)) goto bad; + } + result = __Pyx_PyObject_Call(func, argstuple, kwargs); + bad: + Py_DECREF(argstuple); + return result; +} +#endif +#if CYTHON_VECTORCALL && !CYTHON_COMPILING_IN_LIMITED_API + #if PY_VERSION_HEX < 0x03090000 + #define __Pyx_PyVectorcall_Function(callable) _PyVectorcall_Function(callable) + #elif CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE vectorcallfunc __Pyx_PyVectorcall_Function(PyObject *callable) { + PyTypeObject *tp = Py_TYPE(callable); + #if defined(__Pyx_CyFunction_USED) + if (__Pyx_CyFunction_CheckExact(callable)) { + return __Pyx_CyFunction_func_vectorcall(callable); + } + #endif + if (!PyType_HasFeature(tp, Py_TPFLAGS_HAVE_VECTORCALL)) { + return NULL; + } + assert(PyCallable_Check(callable)); + Py_ssize_t offset = tp->tp_vectorcall_offset; + assert(offset > 0); + vectorcallfunc ptr; + memcpy(&ptr, (char *) callable + offset, sizeof(ptr)); + return ptr; +} + #else + #define __Pyx_PyVectorcall_Function(callable) PyVectorcall_Function(callable) + #endif +#endif +static CYTHON_INLINE PyObject* __Pyx_PyObject_FastCallDict(PyObject *func, PyObject *const *args, size_t _nargs, PyObject *kwargs) { + Py_ssize_t nargs = __Pyx_PyVectorcall_NARGS(_nargs); +#if CYTHON_COMPILING_IN_CPYTHON + if (nargs == 0 && kwargs == NULL) { + if (__Pyx_CyOrPyCFunction_Check(func) && likely( __Pyx_CyOrPyCFunction_GET_FLAGS(func) & METH_NOARGS)) + return __Pyx_PyObject_CallMethO(func, NULL); + } + else if (nargs == 1 && kwargs == NULL) { + if (__Pyx_CyOrPyCFunction_Check(func) && likely( __Pyx_CyOrPyCFunction_GET_FLAGS(func) & METH_O)) + return __Pyx_PyObject_CallMethO(func, args[0]); + } +#endif + if (kwargs == NULL) { + #if CYTHON_VECTORCALL + #if CYTHON_COMPILING_IN_LIMITED_API + return PyObject_Vectorcall(func, args, _nargs, NULL); + #else + vectorcallfunc f = __Pyx_PyVectorcall_Function(func); + if (f) { + return f(func, args, _nargs, NULL); + } + #endif + #endif + } + if (nargs == 0) { + return __Pyx_PyObject_Call(func, __pyx_mstate_global->__pyx_empty_tuple, kwargs); + } + #if PY_VERSION_HEX >= 0x03090000 && !CYTHON_COMPILING_IN_LIMITED_API + return PyObject_VectorcallDict(func, args, (size_t)nargs, kwargs); + #else + return __Pyx_PyObject_FastCall_fallback(func, args, (size_t)nargs, kwargs); + #endif +} + +/* PyObjectCallOneArg (used by CallUnboundCMethod0) */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { + PyObject *args[2] = {NULL, arg}; + return __Pyx_PyObject_FastCall(func, args+1, 1 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET); +} + +/* PyObjectGetAttrStr (used by UnpackUnboundCMethod) */ +#if CYTHON_USE_TYPE_SLOTS +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { + PyTypeObject* tp = Py_TYPE(obj); + if (likely(tp->tp_getattro)) + return tp->tp_getattro(obj, attr_name); + return PyObject_GetAttr(obj, attr_name); +} +#endif + +/* UnpackUnboundCMethod (used by CallUnboundCMethod0) */ +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030C0000 +static PyObject *__Pyx_SelflessCall(PyObject *method, PyObject *args, PyObject *kwargs) { + PyObject *result; + PyObject *selfless_args = PyTuple_GetSlice(args, 1, PyTuple_Size(args)); + if (unlikely(!selfless_args)) return NULL; + result = PyObject_Call(method, selfless_args, kwargs); + Py_DECREF(selfless_args); + return result; +} +#elif CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX < 0x03090000 +static PyObject *__Pyx_SelflessCall(PyObject *method, PyObject **args, Py_ssize_t nargs, PyObject *kwnames) { + return _PyObject_Vectorcall + (method, args ? args+1 : NULL, nargs ? nargs-1 : 0, kwnames); +} +#else +static PyObject *__Pyx_SelflessCall(PyObject *method, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames) { + return +#if PY_VERSION_HEX < 0x03090000 + _PyObject_Vectorcall +#else + PyObject_Vectorcall +#endif + (method, args ? args+1 : NULL, nargs ? (size_t) nargs-1 : 0, kwnames); +} +#endif +static PyMethodDef __Pyx_UnboundCMethod_Def = { + "CythonUnboundCMethod", + __PYX_REINTERPRET_FUNCION(PyCFunction, __Pyx_SelflessCall), +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030C0000 + METH_VARARGS | METH_KEYWORDS, +#else + METH_FASTCALL | METH_KEYWORDS, +#endif + NULL +}; +static int __Pyx_TryUnpackUnboundCMethod(__Pyx_CachedCFunction* target) { + PyObject *method, *result=NULL; + method = __Pyx_PyObject_GetAttrStr(target->type, *target->method_name); + if (unlikely(!method)) + return -1; + result = method; +#if CYTHON_COMPILING_IN_CPYTHON + if (likely(__Pyx_TypeCheck(method, &PyMethodDescr_Type))) + { + PyMethodDescrObject *descr = (PyMethodDescrObject*) method; + target->func = descr->d_method->ml_meth; + target->flag = descr->d_method->ml_flags & ~(METH_CLASS | METH_STATIC | METH_COEXIST | METH_STACKLESS); + } else +#endif +#if CYTHON_COMPILING_IN_PYPY +#else + if (PyCFunction_Check(method)) +#endif + { + PyObject *self; + int self_found; +#if CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_PYPY + self = PyObject_GetAttrString(method, "__self__"); + if (!self) { + PyErr_Clear(); + } +#else + self = PyCFunction_GET_SELF(method); +#endif + self_found = (self && self != Py_None); +#if CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_PYPY + Py_XDECREF(self); +#endif + if (self_found) { + PyObject *unbound_method = PyCFunction_New(&__Pyx_UnboundCMethod_Def, method); + if (unlikely(!unbound_method)) return -1; + Py_DECREF(method); + result = unbound_method; + } + } +#if !CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + if (unlikely(target->method)) { + Py_DECREF(result); + } else +#endif + target->method = result; + return 0; +} + +/* CallUnboundCMethod0 */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_CallUnboundCMethod0(__Pyx_CachedCFunction* cfunc, PyObject* self) { + int was_initialized = __Pyx_CachedCFunction_GetAndSetInitializing(cfunc); + if (likely(was_initialized == 2 && cfunc->func)) { + if (likely(cfunc->flag == METH_NOARGS)) + return __Pyx_CallCFunction(cfunc, self, NULL); + if (likely(cfunc->flag == METH_FASTCALL)) + return __Pyx_CallCFunctionFast(cfunc, self, NULL, 0); + if (cfunc->flag == (METH_FASTCALL | METH_KEYWORDS)) + return __Pyx_CallCFunctionFastWithKeywords(cfunc, self, NULL, 0, NULL); + if (likely(cfunc->flag == (METH_VARARGS | METH_KEYWORDS))) + return __Pyx_CallCFunctionWithKeywords(cfunc, self, __pyx_mstate_global->__pyx_empty_tuple, NULL); + if (cfunc->flag == METH_VARARGS) + return __Pyx_CallCFunction(cfunc, self, __pyx_mstate_global->__pyx_empty_tuple); + return __Pyx__CallUnboundCMethod0(cfunc, self); + } +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + else if (unlikely(was_initialized == 1)) { + __Pyx_CachedCFunction tmp_cfunc = { +#ifndef __cplusplus + 0 +#endif + }; + tmp_cfunc.type = cfunc->type; + tmp_cfunc.method_name = cfunc->method_name; + return __Pyx__CallUnboundCMethod0(&tmp_cfunc, self); + } +#endif + PyObject *result = __Pyx__CallUnboundCMethod0(cfunc, self); + __Pyx_CachedCFunction_SetFinishedInitializing(cfunc); + return result; +} +#endif +static PyObject* __Pyx__CallUnboundCMethod0(__Pyx_CachedCFunction* cfunc, PyObject* self) { + PyObject *result; + if (unlikely(!cfunc->method) && unlikely(__Pyx_TryUnpackUnboundCMethod(cfunc) < 0)) return NULL; + result = __Pyx_PyObject_CallOneArg(cfunc->method, self); + return result; +} + +/* py_dict_items (used by OwnedDictNext) */ +static CYTHON_INLINE PyObject* __Pyx_PyDict_Items(PyObject* d) { + return __Pyx_CallUnboundCMethod0(&__pyx_mstate_global->__pyx_umethod_PyDict_Type_items, d); +} + +/* py_dict_values (used by OwnedDictNext) */ +static CYTHON_INLINE PyObject* __Pyx_PyDict_Values(PyObject* d) { + return __Pyx_CallUnboundCMethod0(&__pyx_mstate_global->__pyx_umethod_PyDict_Type_values, d); +} + +/* OwnedDictNext (used by ParseKeywordsImpl) */ +#if CYTHON_AVOID_BORROWED_REFS +static int __Pyx_PyDict_NextRef(PyObject *p, PyObject **ppos, PyObject **pkey, PyObject **pvalue) { + PyObject *next = NULL; + if (!*ppos) { + if (pvalue) { + PyObject *dictview = pkey ? __Pyx_PyDict_Items(p) : __Pyx_PyDict_Values(p); + if (unlikely(!dictview)) goto bad; + *ppos = PyObject_GetIter(dictview); + Py_DECREF(dictview); + } else { + *ppos = PyObject_GetIter(p); + } + if (unlikely(!*ppos)) goto bad; + } + next = PyIter_Next(*ppos); + if (!next) { + if (PyErr_Occurred()) goto bad; + return 0; + } + if (pkey && pvalue) { + *pkey = __Pyx_PySequence_ITEM(next, 0); + if (unlikely(*pkey)) goto bad; + *pvalue = __Pyx_PySequence_ITEM(next, 1); + if (unlikely(*pvalue)) goto bad; + Py_DECREF(next); + } else if (pkey) { + *pkey = next; + } else { + assert(pvalue); + *pvalue = next; + } + return 1; + bad: + Py_XDECREF(next); +#if !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d0000 + PyErr_FormatUnraisable("Exception ignored in __Pyx_PyDict_NextRef"); +#else + PyErr_WriteUnraisable(__pyx_mstate_global->__pyx_n_u_Pyx_PyDict_NextRef); +#endif + if (pkey) *pkey = NULL; + if (pvalue) *pvalue = NULL; + return 0; +} +#else // !CYTHON_AVOID_BORROWED_REFS +static int __Pyx_PyDict_NextRef(PyObject *p, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue) { + int result = PyDict_Next(p, ppos, pkey, pvalue); + if (likely(result == 1)) { + if (pkey) Py_INCREF(*pkey); + if (pvalue) Py_INCREF(*pvalue); + } + return result; +} +#endif + +/* RaiseDoubleKeywords (used by ParseKeywordsImpl) */ +static void __Pyx_RaiseDoubleKeywordsError( + const char* func_name, + PyObject* kw_name) +{ + PyErr_Format(PyExc_TypeError, + "%s() got multiple values for keyword argument '%U'", func_name, kw_name); +} + +/* CallUnboundCMethod2 */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject *__Pyx_CallUnboundCMethod2(__Pyx_CachedCFunction *cfunc, PyObject *self, PyObject *arg1, PyObject *arg2) { + int was_initialized = __Pyx_CachedCFunction_GetAndSetInitializing(cfunc); + if (likely(was_initialized == 2 && cfunc->func)) { + PyObject *args[2] = {arg1, arg2}; + if (cfunc->flag == METH_FASTCALL) { + return __Pyx_CallCFunctionFast(cfunc, self, args, 2); + } + if (cfunc->flag == (METH_FASTCALL | METH_KEYWORDS)) + return __Pyx_CallCFunctionFastWithKeywords(cfunc, self, args, 2, NULL); + } +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + else if (unlikely(was_initialized == 1)) { + __Pyx_CachedCFunction tmp_cfunc = { +#ifndef __cplusplus + 0 +#endif + }; + tmp_cfunc.type = cfunc->type; + tmp_cfunc.method_name = cfunc->method_name; + return __Pyx__CallUnboundCMethod2(&tmp_cfunc, self, arg1, arg2); + } +#endif + PyObject *result = __Pyx__CallUnboundCMethod2(cfunc, self, arg1, arg2); + __Pyx_CachedCFunction_SetFinishedInitializing(cfunc); + return result; +} +#endif +static PyObject* __Pyx__CallUnboundCMethod2(__Pyx_CachedCFunction* cfunc, PyObject* self, PyObject* arg1, PyObject* arg2){ + if (unlikely(!cfunc->func && !cfunc->method) && unlikely(__Pyx_TryUnpackUnboundCMethod(cfunc) < 0)) return NULL; +#if CYTHON_COMPILING_IN_CPYTHON + if (cfunc->func && (cfunc->flag & METH_VARARGS)) { + PyObject *result = NULL; + PyObject *args = PyTuple_New(2); + if (unlikely(!args)) return NULL; + Py_INCREF(arg1); + PyTuple_SET_ITEM(args, 0, arg1); + Py_INCREF(arg2); + PyTuple_SET_ITEM(args, 1, arg2); + if (cfunc->flag & METH_KEYWORDS) + result = __Pyx_CallCFunctionWithKeywords(cfunc, self, args, NULL); + else + result = __Pyx_CallCFunction(cfunc, self, args); + Py_DECREF(args); + return result; + } +#endif + { + PyObject *args[4] = {NULL, self, arg1, arg2}; + return __Pyx_PyObject_FastCall(cfunc->method, args+1, 3 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET); + } +} + +/* ParseKeywordsImpl (used by ParseKeywords) */ +static int __Pyx_ValidateDuplicatePosArgs( + PyObject *kwds, + PyObject ** const argnames[], + PyObject ** const *first_kw_arg, + const char* function_name) +{ + PyObject ** const *name = argnames; + while (name != first_kw_arg) { + PyObject *key = **name; + int found = PyDict_Contains(kwds, key); + if (unlikely(found)) { + if (found == 1) __Pyx_RaiseDoubleKeywordsError(function_name, key); + goto bad; + } + name++; + } + return 0; +bad: + return -1; +} +#if CYTHON_USE_UNICODE_INTERNALS +static CYTHON_INLINE int __Pyx_UnicodeKeywordsEqual(PyObject *s1, PyObject *s2) { + int kind; + Py_ssize_t len = PyUnicode_GET_LENGTH(s1); + if (len != PyUnicode_GET_LENGTH(s2)) return 0; + kind = PyUnicode_KIND(s1); + if (kind != PyUnicode_KIND(s2)) return 0; + const void *data1 = PyUnicode_DATA(s1); + const void *data2 = PyUnicode_DATA(s2); + return (memcmp(data1, data2, (size_t) len * (size_t) kind) == 0); +} +#endif +static int __Pyx_MatchKeywordArg_str( + PyObject *key, + PyObject ** const argnames[], + PyObject ** const *first_kw_arg, + size_t *index_found, + const char *function_name) +{ + PyObject ** const *name; + #if CYTHON_USE_UNICODE_INTERNALS + Py_hash_t key_hash = ((PyASCIIObject*)key)->hash; + if (unlikely(key_hash == -1)) { + key_hash = PyObject_Hash(key); + if (unlikely(key_hash == -1)) + goto bad; + } + #endif + name = first_kw_arg; + while (*name) { + PyObject *name_str = **name; + #if CYTHON_USE_UNICODE_INTERNALS + if (key_hash == ((PyASCIIObject*)name_str)->hash && __Pyx_UnicodeKeywordsEqual(name_str, key)) { + *index_found = (size_t) (name - argnames); + return 1; + } + #else + #if CYTHON_ASSUME_SAFE_SIZE + if (PyUnicode_GET_LENGTH(name_str) == PyUnicode_GET_LENGTH(key)) + #endif + { + int cmp = PyUnicode_Compare(name_str, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) { + *index_found = (size_t) (name - argnames); + return 1; + } + } + #endif + name++; + } + name = argnames; + while (name != first_kw_arg) { + PyObject *name_str = **name; + #if CYTHON_USE_UNICODE_INTERNALS + if (unlikely(key_hash == ((PyASCIIObject*)name_str)->hash)) { + if (__Pyx_UnicodeKeywordsEqual(name_str, key)) + goto arg_passed_twice; + } + #else + #if CYTHON_ASSUME_SAFE_SIZE + if (PyUnicode_GET_LENGTH(name_str) == PyUnicode_GET_LENGTH(key)) + #endif + { + if (unlikely(name_str == key)) goto arg_passed_twice; + int cmp = PyUnicode_Compare(name_str, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) goto arg_passed_twice; + } + #endif + name++; + } + return 0; +arg_passed_twice: + __Pyx_RaiseDoubleKeywordsError(function_name, key); + goto bad; +bad: + return -1; +} +static int __Pyx_MatchKeywordArg_nostr( + PyObject *key, + PyObject ** const argnames[], + PyObject ** const *first_kw_arg, + size_t *index_found, + const char *function_name) +{ + PyObject ** const *name; + if (unlikely(!PyUnicode_Check(key))) goto invalid_keyword_type; + name = first_kw_arg; + while (*name) { + int cmp = PyObject_RichCompareBool(**name, key, Py_EQ); + if (cmp == 1) { + *index_found = (size_t) (name - argnames); + return 1; + } + if (unlikely(cmp == -1)) goto bad; + name++; + } + name = argnames; + while (name != first_kw_arg) { + int cmp = PyObject_RichCompareBool(**name, key, Py_EQ); + if (unlikely(cmp != 0)) { + if (cmp == 1) goto arg_passed_twice; + else goto bad; + } + name++; + } + return 0; +arg_passed_twice: + __Pyx_RaiseDoubleKeywordsError(function_name, key); + goto bad; +invalid_keyword_type: + PyErr_Format(PyExc_TypeError, + "%.200s() keywords must be strings", function_name); + goto bad; +bad: + return -1; +} +static CYTHON_INLINE int __Pyx_MatchKeywordArg( + PyObject *key, + PyObject ** const argnames[], + PyObject ** const *first_kw_arg, + size_t *index_found, + const char *function_name) +{ + return likely(PyUnicode_CheckExact(key)) ? + __Pyx_MatchKeywordArg_str(key, argnames, first_kw_arg, index_found, function_name) : + __Pyx_MatchKeywordArg_nostr(key, argnames, first_kw_arg, index_found, function_name); +} +static void __Pyx_RejectUnknownKeyword( + PyObject *kwds, + PyObject ** const argnames[], + PyObject ** const *first_kw_arg, + const char *function_name) +{ + #if CYTHON_AVOID_BORROWED_REFS + PyObject *pos = NULL; + #else + Py_ssize_t pos = 0; + #endif + PyObject *key = NULL; + __Pyx_BEGIN_CRITICAL_SECTION(kwds); + while ( + #if CYTHON_AVOID_BORROWED_REFS + __Pyx_PyDict_NextRef(kwds, &pos, &key, NULL) + #else + PyDict_Next(kwds, &pos, &key, NULL) + #endif + ) { + PyObject** const *name = first_kw_arg; + while (*name && (**name != key)) name++; + if (!*name) { + size_t index_found = 0; + int cmp = __Pyx_MatchKeywordArg(key, argnames, first_kw_arg, &index_found, function_name); + if (cmp != 1) { + if (cmp == 0) { + PyErr_Format(PyExc_TypeError, + "%s() got an unexpected keyword argument '%U'", + function_name, key); + } + #if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(key); + #endif + break; + } + } + #if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(key); + #endif + } + __Pyx_END_CRITICAL_SECTION(); + #if CYTHON_AVOID_BORROWED_REFS + Py_XDECREF(pos); + #endif + assert(PyErr_Occurred()); +} +static int __Pyx_ParseKeywordDict( + PyObject *kwds, + PyObject ** const argnames[], + PyObject *values[], + Py_ssize_t num_pos_args, + Py_ssize_t num_kwargs, + const char* function_name, + int ignore_unknown_kwargs) +{ + PyObject** const *name; + PyObject** const *first_kw_arg = argnames + num_pos_args; + Py_ssize_t extracted = 0; +#if !CYTHON_COMPILING_IN_PYPY || defined(PyArg_ValidateKeywordArguments) + if (unlikely(!PyArg_ValidateKeywordArguments(kwds))) return -1; +#endif + name = first_kw_arg; + while (*name && num_kwargs > extracted) { + PyObject * key = **name; + PyObject *value; + int found = 0; + #if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + found = PyDict_GetItemRef(kwds, key, &value); + #else + value = PyDict_GetItemWithError(kwds, key); + if (value) { + Py_INCREF(value); + found = 1; + } else { + if (unlikely(PyErr_Occurred())) goto bad; + } + #endif + if (found) { + if (unlikely(found < 0)) goto bad; + values[name-argnames] = value; + extracted++; + } + name++; + } + if (num_kwargs > extracted) { + if (ignore_unknown_kwargs) { + if (unlikely(__Pyx_ValidateDuplicatePosArgs(kwds, argnames, first_kw_arg, function_name) == -1)) + goto bad; + } else { + __Pyx_RejectUnknownKeyword(kwds, argnames, first_kw_arg, function_name); + goto bad; + } + } + return 0; +bad: + return -1; +} +static int __Pyx_ParseKeywordDictToDict( + PyObject *kwds, + PyObject ** const argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + const char* function_name) +{ + PyObject** const *name; + PyObject** const *first_kw_arg = argnames + num_pos_args; + Py_ssize_t len; +#if !CYTHON_COMPILING_IN_PYPY || defined(PyArg_ValidateKeywordArguments) + if (unlikely(!PyArg_ValidateKeywordArguments(kwds))) return -1; +#endif + if (PyDict_Update(kwds2, kwds) < 0) goto bad; + name = first_kw_arg; + while (*name) { + PyObject *key = **name; + PyObject *value; +#if !CYTHON_COMPILING_IN_LIMITED_API && (PY_VERSION_HEX >= 0x030d00A2 || defined(PyDict_Pop)) + int found = PyDict_Pop(kwds2, key, &value); + if (found) { + if (unlikely(found < 0)) goto bad; + values[name-argnames] = value; + } +#elif __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + int found = PyDict_GetItemRef(kwds2, key, &value); + if (found) { + if (unlikely(found < 0)) goto bad; + values[name-argnames] = value; + if (unlikely(PyDict_DelItem(kwds2, key) < 0)) goto bad; + } +#else + #if CYTHON_COMPILING_IN_CPYTHON + value = _PyDict_Pop(kwds2, key, kwds2); + #else + value = __Pyx_CallUnboundCMethod2(&__pyx_mstate_global->__pyx_umethod_PyDict_Type_pop, kwds2, key, kwds2); + #endif + if (value == kwds2) { + Py_DECREF(value); + } else { + if (unlikely(!value)) goto bad; + values[name-argnames] = value; + } +#endif + name++; + } + len = PyDict_Size(kwds2); + if (len > 0) { + return __Pyx_ValidateDuplicatePosArgs(kwds, argnames, first_kw_arg, function_name); + } else if (unlikely(len == -1)) { + goto bad; + } + return 0; +bad: + return -1; +} +static int __Pyx_ParseKeywordsTuple( + PyObject *kwds, + PyObject * const *kwvalues, + PyObject ** const argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + Py_ssize_t num_kwargs, + const char* function_name, + int ignore_unknown_kwargs) +{ + PyObject *key = NULL; + PyObject** const * name; + PyObject** const *first_kw_arg = argnames + num_pos_args; + for (Py_ssize_t pos = 0; pos < num_kwargs; pos++) { +#if CYTHON_AVOID_BORROWED_REFS + key = __Pyx_PySequence_ITEM(kwds, pos); +#else + key = __Pyx_PyTuple_GET_ITEM(kwds, pos); +#endif +#if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(!key)) goto bad; +#endif + name = first_kw_arg; + while (*name && (**name != key)) name++; + if (*name) { + PyObject *value = kwvalues[pos]; + values[name-argnames] = __Pyx_NewRef(value); + } else { + size_t index_found = 0; + int cmp = __Pyx_MatchKeywordArg(key, argnames, first_kw_arg, &index_found, function_name); + if (cmp == 1) { + PyObject *value = kwvalues[pos]; + values[index_found] = __Pyx_NewRef(value); + } else { + if (unlikely(cmp == -1)) goto bad; + if (kwds2) { + PyObject *value = kwvalues[pos]; + if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; + } else if (!ignore_unknown_kwargs) { + goto invalid_keyword; + } + } + } + #if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(key); + key = NULL; + #endif + } + return 0; +invalid_keyword: + PyErr_Format(PyExc_TypeError, + "%s() got an unexpected keyword argument '%U'", + function_name, key); + goto bad; +bad: + #if CYTHON_AVOID_BORROWED_REFS + Py_XDECREF(key); + #endif + return -1; +} + +/* ParseKeywords */ +static int __Pyx_ParseKeywords( + PyObject *kwds, + PyObject * const *kwvalues, + PyObject ** const argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + Py_ssize_t num_kwargs, + const char* function_name, + int ignore_unknown_kwargs) +{ + if (CYTHON_METH_FASTCALL && likely(PyTuple_Check(kwds))) + return __Pyx_ParseKeywordsTuple(kwds, kwvalues, argnames, kwds2, values, num_pos_args, num_kwargs, function_name, ignore_unknown_kwargs); + else if (kwds2) + return __Pyx_ParseKeywordDictToDict(kwds, argnames, kwds2, values, num_pos_args, function_name); + else + return __Pyx_ParseKeywordDict(kwds, argnames, values, num_pos_args, num_kwargs, function_name, ignore_unknown_kwargs); +} + +/* RaiseArgTupleInvalid */ +static void __Pyx_RaiseArgtupleInvalid( + const char* func_name, + int exact, + Py_ssize_t num_min, + Py_ssize_t num_max, + Py_ssize_t num_found) +{ + Py_ssize_t num_expected; + const char *more_or_less; + if (num_found < num_min) { + num_expected = num_min; + more_or_less = "at least"; + } else { + num_expected = num_max; + more_or_less = "at most"; + } + if (exact) { + more_or_less = "exactly"; + } + PyErr_Format(PyExc_TypeError, + "%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)", + func_name, more_or_less, num_expected, + (num_expected == 1) ? "" : "s", num_found); +} + +/* RaiseUnexpectedTypeError */ +static int +__Pyx_RaiseUnexpectedTypeError(const char *expected, PyObject *obj) +{ + __Pyx_TypeName obj_type_name = __Pyx_PyType_GetFullyQualifiedName(Py_TYPE(obj)); + PyErr_Format(PyExc_TypeError, "Expected %s, got " __Pyx_FMT_TYPENAME, + expected, obj_type_name); + __Pyx_DECREF_TypeName(obj_type_name); + return 0; +} + +/* RejectKeywords */ +static void __Pyx_RejectKeywords(const char* function_name, PyObject *kwds) { + PyObject *key = NULL; + if (CYTHON_METH_FASTCALL && likely(PyTuple_Check(kwds))) { + key = __Pyx_PySequence_ITEM(kwds, 0); + } else { +#if CYTHON_AVOID_BORROWED_REFS + PyObject *pos = NULL; +#else + Py_ssize_t pos = 0; +#endif +#if !CYTHON_COMPILING_IN_PYPY || defined(PyArg_ValidateKeywordArguments) + if (unlikely(!PyArg_ValidateKeywordArguments(kwds))) return; +#endif + __Pyx_PyDict_NextRef(kwds, &pos, &key, NULL); +#if CYTHON_AVOID_BORROWED_REFS + Py_XDECREF(pos); +#endif + } + if (likely(key)) { + PyErr_Format(PyExc_TypeError, + "%s() got an unexpected keyword argument '%U'", + function_name, key); + Py_DECREF(key); + } +} + +/* PyObjectFastCallMethod */ +#if !CYTHON_VECTORCALL || PY_VERSION_HEX < 0x03090000 +static PyObject *__Pyx_PyObject_FastCallMethod(PyObject *name, PyObject *const *args, size_t nargsf) { + PyObject *result; + PyObject *attr = PyObject_GetAttr(args[0], name); + if (unlikely(!attr)) + return NULL; + result = __Pyx_PyObject_FastCall(attr, args+1, nargsf - 1); + Py_DECREF(attr); + return result; +} +#endif + +/* PyErrExceptionMatches (used by PyObjectGetAttrStrNoError) */ +#if CYTHON_FAST_THREAD_STATE +static int __Pyx_PyErr_ExceptionMatchesTuple(PyObject *exc_type, PyObject *tuple) { + Py_ssize_t i, n; + n = PyTuple_GET_SIZE(tuple); + for (i=0; i= 0x030C00A6 + PyObject *current_exception = tstate->current_exception; + if (unlikely(!current_exception)) return 0; + exc_type = (PyObject*) Py_TYPE(current_exception); + if (exc_type == err) return 1; +#else + exc_type = tstate->curexc_type; + if (exc_type == err) return 1; + if (unlikely(!exc_type)) return 0; +#endif + #if CYTHON_AVOID_BORROWED_REFS + Py_INCREF(exc_type); + #endif + if (unlikely(PyTuple_Check(err))) { + result = __Pyx_PyErr_ExceptionMatchesTuple(exc_type, err); + } else { + result = __Pyx_PyErr_GivenExceptionMatches(exc_type, err); + } + #if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(exc_type); + #endif + return result; +} +#endif + +/* PyErrFetchRestore (used by PyObjectGetAttrStrNoError) */ +#if CYTHON_FAST_THREAD_STATE +static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { +#if PY_VERSION_HEX >= 0x030C00A6 + PyObject *tmp_value; + assert(type == NULL || (value != NULL && type == (PyObject*) Py_TYPE(value))); + if (value) { + #if CYTHON_COMPILING_IN_CPYTHON + if (unlikely(((PyBaseExceptionObject*) value)->traceback != tb)) + #endif + PyException_SetTraceback(value, tb); + } + tmp_value = tstate->current_exception; + tstate->current_exception = value; + Py_XDECREF(tmp_value); + Py_XDECREF(type); + Py_XDECREF(tb); +#else + PyObject *tmp_type, *tmp_value, *tmp_tb; + tmp_type = tstate->curexc_type; + tmp_value = tstate->curexc_value; + tmp_tb = tstate->curexc_traceback; + tstate->curexc_type = type; + tstate->curexc_value = value; + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#endif +} +static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { +#if PY_VERSION_HEX >= 0x030C00A6 + PyObject* exc_value; + exc_value = tstate->current_exception; + tstate->current_exception = 0; + *value = exc_value; + *type = NULL; + *tb = NULL; + if (exc_value) { + *type = (PyObject*) Py_TYPE(exc_value); + Py_INCREF(*type); + #if CYTHON_COMPILING_IN_CPYTHON + *tb = ((PyBaseExceptionObject*) exc_value)->traceback; + Py_XINCREF(*tb); + #else + *tb = PyException_GetTraceback(exc_value); + #endif + } +#else + *type = tstate->curexc_type; + *value = tstate->curexc_value; + *tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; +#endif +} +#endif + +/* PyObjectGetAttrStrNoError (used by GetBuiltinName) */ +#if __PYX_LIMITED_VERSION_HEX < 0x030d0000 +static void __Pyx_PyObject_GetAttrStr_ClearAttributeError(void) { + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + if (likely(__Pyx_PyErr_ExceptionMatches(PyExc_AttributeError))) + __Pyx_PyErr_Clear(); +} +#endif +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStrNoError(PyObject* obj, PyObject* attr_name) { + PyObject *result; +#if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + (void) PyObject_GetOptionalAttr(obj, attr_name, &result); + return result; +#else +#if CYTHON_COMPILING_IN_CPYTHON && CYTHON_USE_TYPE_SLOTS + PyTypeObject* tp = Py_TYPE(obj); + if (likely(tp->tp_getattro == PyObject_GenericGetAttr)) { + return _PyObject_GenericGetAttrWithDict(obj, attr_name, NULL, 1); + } +#endif + result = __Pyx_PyObject_GetAttrStr(obj, attr_name); + if (unlikely(!result)) { + __Pyx_PyObject_GetAttrStr_ClearAttributeError(); + } + return result; +#endif +} + +/* GetBuiltinName (used by GetModuleGlobalName) */ +static PyObject *__Pyx_GetBuiltinName(PyObject *name) { + PyObject* result = __Pyx_PyObject_GetAttrStrNoError(__pyx_mstate_global->__pyx_b, name); + if (unlikely(!result) && !PyErr_Occurred()) { + PyErr_Format(PyExc_NameError, + "name '%U' is not defined", name); + } + return result; +} + +/* PyDictVersioning (used by GetModuleGlobalName) */ +#if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_TYPE_SLOTS +static CYTHON_INLINE PY_UINT64_T __Pyx_get_tp_dict_version(PyObject *obj) { + PyObject *dict = Py_TYPE(obj)->tp_dict; + return likely(dict) ? __PYX_GET_DICT_VERSION(dict) : 0; +} +static CYTHON_INLINE PY_UINT64_T __Pyx_get_object_dict_version(PyObject *obj) { + PyObject **dictptr = NULL; + Py_ssize_t offset = Py_TYPE(obj)->tp_dictoffset; + if (offset) { +#if CYTHON_COMPILING_IN_CPYTHON + dictptr = (likely(offset > 0)) ? (PyObject **) ((char *)obj + offset) : _PyObject_GetDictPtr(obj); +#else + dictptr = _PyObject_GetDictPtr(obj); +#endif + } + return (dictptr && *dictptr) ? __PYX_GET_DICT_VERSION(*dictptr) : 0; +} +static CYTHON_INLINE int __Pyx_object_dict_version_matches(PyObject* obj, PY_UINT64_T tp_dict_version, PY_UINT64_T obj_dict_version) { + PyObject *dict = Py_TYPE(obj)->tp_dict; + if (unlikely(!dict) || unlikely(tp_dict_version != __PYX_GET_DICT_VERSION(dict))) + return 0; + return obj_dict_version == __Pyx_get_object_dict_version(obj); +} +#endif + +/* GetModuleGlobalName */ +#if CYTHON_USE_DICT_VERSIONS +static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_version, PyObject **dict_cached_value) +#else +static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name) +#endif +{ + PyObject *result; +#if CYTHON_COMPILING_IN_LIMITED_API + if (unlikely(!__pyx_m)) { + if (!PyErr_Occurred()) + PyErr_SetNone(PyExc_NameError); + return NULL; + } + result = PyObject_GetAttr(__pyx_m, name); + if (likely(result)) { + return result; + } + PyErr_Clear(); +#elif CYTHON_AVOID_BORROWED_REFS || CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + if (unlikely(__Pyx_PyDict_GetItemRef(__pyx_mstate_global->__pyx_d, name, &result) == -1)) PyErr_Clear(); + __PYX_UPDATE_DICT_CACHE(__pyx_mstate_global->__pyx_d, result, *dict_cached_value, *dict_version) + if (likely(result)) { + return result; + } +#else + result = _PyDict_GetItem_KnownHash(__pyx_mstate_global->__pyx_d, name, ((PyASCIIObject *) name)->hash); + __PYX_UPDATE_DICT_CACHE(__pyx_mstate_global->__pyx_d, result, *dict_cached_value, *dict_version) + if (likely(result)) { + return __Pyx_NewRef(result); + } + PyErr_Clear(); +#endif + return __Pyx_GetBuiltinName(name); +} + +/* PyObjectVectorCallKwBuilder */ +#if CYTHON_VECTORCALL +static int __Pyx_VectorcallBuilder_AddArg(PyObject *key, PyObject *value, PyObject *builder, PyObject **args, int n) { + (void)__Pyx_PyObject_FastCallDict; + if (__Pyx_PyTuple_SET_ITEM(builder, n, key) != (0)) return -1; + Py_INCREF(key); + args[n] = value; + return 0; +} +CYTHON_UNUSED static int __Pyx_VectorcallBuilder_AddArg_Check(PyObject *key, PyObject *value, PyObject *builder, PyObject **args, int n) { + (void)__Pyx_VectorcallBuilder_AddArgStr; + if (unlikely(!PyUnicode_Check(key))) { + PyErr_SetString(PyExc_TypeError, "keywords must be strings"); + return -1; + } + return __Pyx_VectorcallBuilder_AddArg(key, value, builder, args, n); +} +static int __Pyx_VectorcallBuilder_AddArgStr(const char *key, PyObject *value, PyObject *builder, PyObject **args, int n) { + PyObject *pyKey = PyUnicode_FromString(key); + if (!pyKey) return -1; + return __Pyx_VectorcallBuilder_AddArg(pyKey, value, builder, args, n); +} +#else // CYTHON_VECTORCALL +CYTHON_UNUSED static int __Pyx_VectorcallBuilder_AddArg_Check(PyObject *key, PyObject *value, PyObject *builder, CYTHON_UNUSED PyObject **args, CYTHON_UNUSED int n) { + if (unlikely(!PyUnicode_Check(key))) { + PyErr_SetString(PyExc_TypeError, "keywords must be strings"); + return -1; + } + return PyDict_SetItem(builder, key, value); +} +#endif + +/* RaiseException */ +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { + PyObject* owned_instance = NULL; + if (tb == Py_None) { + tb = 0; + } else if (tb && !PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto bad; + } + if (value == Py_None) + value = 0; + if (PyExceptionInstance_Check(type)) { + if (value) { + PyErr_SetString(PyExc_TypeError, + "instance exception may not have a separate value"); + goto bad; + } + value = type; + type = (PyObject*) Py_TYPE(value); + } else if (PyExceptionClass_Check(type)) { + PyObject *instance_class = NULL; + if (value && PyExceptionInstance_Check(value)) { + instance_class = (PyObject*) Py_TYPE(value); + if (instance_class != type) { + int is_subclass = PyObject_IsSubclass(instance_class, type); + if (!is_subclass) { + instance_class = NULL; + } else if (unlikely(is_subclass == -1)) { + goto bad; + } else { + type = instance_class; + } + } + } + if (!instance_class) { + PyObject *args; + if (!value) + args = PyTuple_New(0); + else if (PyTuple_Check(value)) { + Py_INCREF(value); + args = value; + } else + args = PyTuple_Pack(1, value); + if (!args) + goto bad; + owned_instance = PyObject_Call(type, args, NULL); + Py_DECREF(args); + if (!owned_instance) + goto bad; + value = owned_instance; + if (!PyExceptionInstance_Check(value)) { + PyErr_Format(PyExc_TypeError, + "calling %R should have returned an instance of " + "BaseException, not %R", + type, Py_TYPE(value)); + goto bad; + } + } + } else { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto bad; + } + if (cause) { + PyObject *fixed_cause; + if (cause == Py_None) { + fixed_cause = NULL; + } else if (PyExceptionClass_Check(cause)) { + fixed_cause = PyObject_CallObject(cause, NULL); + if (fixed_cause == NULL) + goto bad; + } else if (PyExceptionInstance_Check(cause)) { + fixed_cause = cause; + Py_INCREF(fixed_cause); + } else { + PyErr_SetString(PyExc_TypeError, + "exception causes must derive from " + "BaseException"); + goto bad; + } + PyException_SetCause(value, fixed_cause); + } + PyErr_SetObject(type, value); + if (tb) { +#if PY_VERSION_HEX >= 0x030C00A6 + PyException_SetTraceback(value, tb); +#elif CYTHON_FAST_THREAD_STATE + PyThreadState *tstate = __Pyx_PyThreadState_Current; + PyObject* tmp_tb = tstate->curexc_traceback; + if (tb != tmp_tb) { + Py_INCREF(tb); + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_tb); + } +#else + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyErr_Fetch(&tmp_type, &tmp_value, &tmp_tb); + Py_INCREF(tb); + PyErr_Restore(tmp_type, tmp_value, tb); + Py_XDECREF(tmp_tb); +#endif + } +bad: + Py_XDECREF(owned_instance); + return; +} + +/* RaiseTooManyValuesToUnpack */ +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { + PyErr_Format(PyExc_ValueError, + "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); +} + +/* RaiseNeedMoreValuesToUnpack */ +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { + PyErr_Format(PyExc_ValueError, + "need more than %" CYTHON_FORMAT_SSIZE_T "d value%.1s to unpack", + index, (index == 1) ? "" : "s"); +} + +/* IterFinish */ +static CYTHON_INLINE int __Pyx_IterFinish(void) { + PyObject* exc_type; + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + exc_type = __Pyx_PyErr_CurrentExceptionType(); + if (unlikely(exc_type)) { + if (unlikely(!__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) + return -1; + __Pyx_PyErr_Clear(); + return 0; + } + return 0; +} + +/* UnpackItemEndCheck */ +static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected) { + if (unlikely(retval)) { + Py_DECREF(retval); + __Pyx_RaiseTooManyValuesError(expected); + return -1; + } + return __Pyx_IterFinish(); +} + +/* PyObjectFormatAndDecref */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_FormatSimpleAndDecref(PyObject* s, PyObject* f) { + if (unlikely(!s)) return NULL; + if (likely(PyUnicode_CheckExact(s))) return s; + return __Pyx_PyObject_FormatAndDecref(s, f); +} +static CYTHON_INLINE PyObject* __Pyx_PyObject_FormatAndDecref(PyObject* s, PyObject* f) { + PyObject *result; + if (unlikely(!s)) return NULL; + result = PyObject_Format(s, f); + Py_DECREF(s); + return result; +} + +/* JoinPyUnicode */ +static PyObject* __Pyx_PyUnicode_Join(PyObject** values, Py_ssize_t value_count, Py_ssize_t result_ulength, + Py_UCS4 max_char) { +#if CYTHON_USE_UNICODE_INTERNALS && CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + PyObject *result_uval; + int result_ukind, kind_shift; + Py_ssize_t i, char_pos; + void *result_udata; + if (max_char > 1114111) max_char = 1114111; + result_uval = PyUnicode_New(result_ulength, max_char); + if (unlikely(!result_uval)) return NULL; + result_ukind = (max_char <= 255) ? PyUnicode_1BYTE_KIND : (max_char <= 65535) ? PyUnicode_2BYTE_KIND : PyUnicode_4BYTE_KIND; + kind_shift = (result_ukind == PyUnicode_4BYTE_KIND) ? 2 : result_ukind - 1; + result_udata = PyUnicode_DATA(result_uval); + assert(kind_shift == 2 || kind_shift == 1 || kind_shift == 0); + if (unlikely((PY_SSIZE_T_MAX >> kind_shift) - result_ulength < 0)) + goto overflow; + char_pos = 0; + for (i=0; i < value_count; i++) { + int ukind; + Py_ssize_t ulength; + void *udata; + PyObject *uval = values[i]; + #if !CYTHON_COMPILING_IN_LIMITED_API + if (__Pyx_PyUnicode_READY(uval) == (-1)) + goto bad; + #endif + ulength = __Pyx_PyUnicode_GET_LENGTH(uval); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(ulength < 0)) goto bad; + #endif + if (unlikely(!ulength)) + continue; + if (unlikely((PY_SSIZE_T_MAX >> kind_shift) - ulength < char_pos)) + goto overflow; + ukind = __Pyx_PyUnicode_KIND(uval); + udata = __Pyx_PyUnicode_DATA(uval); + if (ukind == result_ukind) { + memcpy((char *)result_udata + (char_pos << kind_shift), udata, (size_t) (ulength << kind_shift)); + } else { + #if PY_VERSION_HEX >= 0x030d0000 + if (unlikely(PyUnicode_CopyCharacters(result_uval, char_pos, uval, 0, ulength) < 0)) goto bad; + #elif CYTHON_COMPILING_IN_CPYTHON || defined(_PyUnicode_FastCopyCharacters) + _PyUnicode_FastCopyCharacters(result_uval, char_pos, uval, 0, ulength); + #else + Py_ssize_t j; + for (j=0; j < ulength; j++) { + Py_UCS4 uchar = __Pyx_PyUnicode_READ(ukind, udata, j); + __Pyx_PyUnicode_WRITE(result_ukind, result_udata, char_pos+j, uchar); + } + #endif + } + char_pos += ulength; + } + return result_uval; +overflow: + PyErr_SetString(PyExc_OverflowError, "join() result is too long for a Python string"); +bad: + Py_DECREF(result_uval); + return NULL; +#else + Py_ssize_t i; + PyObject *result = NULL; + PyObject *value_tuple = PyTuple_New(value_count); + if (unlikely(!value_tuple)) return NULL; + CYTHON_UNUSED_VAR(max_char); + CYTHON_UNUSED_VAR(result_ulength); + for (i=0; i__pyx_empty_unicode, value_tuple); +bad: + Py_DECREF(value_tuple); + return result; +#endif +} + +/* ArgTypeTestFunc (used by ArgTypeTest) */ +static int __Pyx__ArgTypeTest(PyObject *obj, PyTypeObject *type, const char *name, int exact) +{ + __Pyx_TypeName type_name; + __Pyx_TypeName obj_type_name; + PyObject *extra_info = __pyx_mstate_global->__pyx_empty_unicode; + int from_annotation_subclass = 0; + if (unlikely(!type)) { + PyErr_SetString(PyExc_SystemError, "Missing type object"); + return 0; + } + else if (!exact) { + if (likely(__Pyx_TypeCheck(obj, type))) return 1; + } else if (exact == 2) { + if (__Pyx_TypeCheck(obj, type)) { + from_annotation_subclass = 1; + extra_info = __pyx_mstate_global->__pyx_kp_u_Note_that_Cython_is_deliberately; + } + } + type_name = __Pyx_PyType_GetFullyQualifiedName(type); + obj_type_name = __Pyx_PyType_GetFullyQualifiedName(Py_TYPE(obj)); + PyErr_Format(PyExc_TypeError, + "Argument '%.200s' has incorrect type (expected " __Pyx_FMT_TYPENAME + ", got " __Pyx_FMT_TYPENAME ")" +#if __PYX_LIMITED_VERSION_HEX < 0x030C0000 + "%s%U" +#endif + , name, type_name, obj_type_name +#if __PYX_LIMITED_VERSION_HEX < 0x030C0000 + , (from_annotation_subclass ? ". " : ""), extra_info +#endif + ); +#if __PYX_LIMITED_VERSION_HEX >= 0x030C0000 + if (exact == 2 && from_annotation_subclass) { + PyObject *res; + PyObject *vargs[2]; + vargs[0] = PyErr_GetRaisedException(); + vargs[1] = extra_info; + res = PyObject_VectorcallMethod(__pyx_mstate_global->__pyx_kp_u_add_note, vargs, 2, NULL); + Py_XDECREF(res); + PyErr_SetRaisedException(vargs[0]); + } +#endif + __Pyx_DECREF_TypeName(type_name); + __Pyx_DECREF_TypeName(obj_type_name); + return 0; +} + +/* GetAttr3 */ +#if __PYX_LIMITED_VERSION_HEX < 0x030d0000 +static PyObject *__Pyx_GetAttr3Default(PyObject *d) { + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + if (unlikely(!__Pyx_PyErr_ExceptionMatches(PyExc_AttributeError))) + return NULL; + __Pyx_PyErr_Clear(); + Py_INCREF(d); + return d; +} +#endif +static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *o, PyObject *n, PyObject *d) { + PyObject *r; +#if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + int res = PyObject_GetOptionalAttr(o, n, &r); + return (res != 0) ? r : __Pyx_NewRef(d); +#else + #if CYTHON_USE_TYPE_SLOTS + if (likely(PyUnicode_Check(n))) { + r = __Pyx_PyObject_GetAttrStrNoError(o, n); + if (unlikely(!r) && likely(!PyErr_Occurred())) { + r = __Pyx_NewRef(d); + } + return r; + } + #endif + r = PyObject_GetAttr(o, n); + return (likely(r)) ? r : __Pyx_GetAttr3Default(d); +#endif +} + +/* GetItemInt */ +static PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) { + PyObject *r; + if (unlikely(!j)) return NULL; + r = PyObject_GetItem(o, j); + Py_DECREF(j); + return r; +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck, int unsafe_shared) { + CYTHON_MAYBE_UNUSED_VAR(unsafe_shared); +#if CYTHON_ASSUME_SAFE_SIZE + Py_ssize_t wrapped_i = i; + if (wraparound & unlikely(i < 0)) { + wrapped_i += PyList_GET_SIZE(o); + } + if ((CYTHON_AVOID_BORROWED_REFS || CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS || !CYTHON_ASSUME_SAFE_MACROS)) { + return __Pyx_PyList_GetItemRefFast(o, wrapped_i, unsafe_shared); + } else + if ((!boundscheck) || likely(__Pyx_is_valid_index(wrapped_i, PyList_GET_SIZE(o)))) { + return __Pyx_NewRef(PyList_GET_ITEM(o, wrapped_i)); + } + return __Pyx_GetItemInt_Generic(o, PyLong_FromSsize_t(i)); +#else + (void)wraparound; + (void)boundscheck; + return PySequence_GetItem(o, i); +#endif +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck, int unsafe_shared) { + CYTHON_MAYBE_UNUSED_VAR(unsafe_shared); +#if CYTHON_ASSUME_SAFE_SIZE && CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + Py_ssize_t wrapped_i = i; + if (wraparound & unlikely(i < 0)) { + wrapped_i += PyTuple_GET_SIZE(o); + } + if ((!boundscheck) || likely(__Pyx_is_valid_index(wrapped_i, PyTuple_GET_SIZE(o)))) { + return __Pyx_NewRef(PyTuple_GET_ITEM(o, wrapped_i)); + } + return __Pyx_GetItemInt_Generic(o, PyLong_FromSsize_t(i)); +#else + (void)wraparound; + (void)boundscheck; + return PySequence_GetItem(o, i); +#endif +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, int is_list, + int wraparound, int boundscheck, int unsafe_shared) { + CYTHON_MAYBE_UNUSED_VAR(unsafe_shared); +#if CYTHON_ASSUME_SAFE_MACROS && CYTHON_ASSUME_SAFE_SIZE + if (is_list || PyList_CheckExact(o)) { + Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyList_GET_SIZE(o); + if ((CYTHON_AVOID_BORROWED_REFS || CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS)) { + return __Pyx_PyList_GetItemRefFast(o, n, unsafe_shared); + } else if ((!boundscheck) || (likely(__Pyx_is_valid_index(n, PyList_GET_SIZE(o))))) { + return __Pyx_NewRef(PyList_GET_ITEM(o, n)); + } + } else + #if !CYTHON_AVOID_BORROWED_REFS + if (PyTuple_CheckExact(o)) { + Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyTuple_GET_SIZE(o); + if ((!boundscheck) || likely(__Pyx_is_valid_index(n, PyTuple_GET_SIZE(o)))) { + return __Pyx_NewRef(PyTuple_GET_ITEM(o, n)); + } + } else + #endif +#endif +#if CYTHON_USE_TYPE_SLOTS && !CYTHON_COMPILING_IN_PYPY + { + PyMappingMethods *mm = Py_TYPE(o)->tp_as_mapping; + PySequenceMethods *sm = Py_TYPE(o)->tp_as_sequence; + if (!is_list && mm && mm->mp_subscript) { + PyObject *r, *key = PyLong_FromSsize_t(i); + if (unlikely(!key)) return NULL; + r = mm->mp_subscript(o, key); + Py_DECREF(key); + return r; + } + if (is_list || likely(sm && sm->sq_item)) { + if (wraparound && unlikely(i < 0) && likely(sm->sq_length)) { + Py_ssize_t l = sm->sq_length(o); + if (likely(l >= 0)) { + i += l; + } else { + if (!PyErr_ExceptionMatches(PyExc_OverflowError)) + return NULL; + PyErr_Clear(); + } + } + return sm->sq_item(o, i); + } + } +#else + if (is_list || !PyMapping_Check(o)) { + return PySequence_GetItem(o, i); + } +#endif + (void)wraparound; + (void)boundscheck; + return __Pyx_GetItemInt_Generic(o, PyLong_FromSsize_t(i)); +} + +/* ExtTypeTest */ +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { + __Pyx_TypeName obj_type_name; + __Pyx_TypeName type_name; + if (unlikely(!type)) { + PyErr_SetString(PyExc_SystemError, "Missing type object"); + return 0; + } + if (likely(__Pyx_TypeCheck(obj, type))) + return 1; + obj_type_name = __Pyx_PyType_GetFullyQualifiedName(Py_TYPE(obj)); + type_name = __Pyx_PyType_GetFullyQualifiedName(type); + PyErr_Format(PyExc_TypeError, + "Cannot convert " __Pyx_FMT_TYPENAME " to " __Pyx_FMT_TYPENAME, + obj_type_name, type_name); + __Pyx_DECREF_TypeName(obj_type_name); + __Pyx_DECREF_TypeName(type_name); + return 0; +} + +/* CallNextTpDealloc */ +static void __Pyx_call_next_tp_dealloc(PyObject* obj, destructor current_tp_dealloc) { + PyTypeObject* type = Py_TYPE(obj); + destructor tp_dealloc = NULL; + while (type && __Pyx_PyType_GetSlot(type, tp_dealloc, destructor) != current_tp_dealloc) + type = __Pyx_PyType_GetSlot(type, tp_base, PyTypeObject*); + while (type && (tp_dealloc = __Pyx_PyType_GetSlot(type, tp_dealloc, destructor)) == current_tp_dealloc) + type = __Pyx_PyType_GetSlot(type, tp_base, PyTypeObject*); + if (type) + tp_dealloc(obj); +} + +/* CallNextTpTraverse */ +static int __Pyx_call_next_tp_traverse(PyObject* obj, visitproc v, void *a, traverseproc current_tp_traverse) { + PyTypeObject* type = Py_TYPE(obj); + traverseproc tp_traverse = NULL; + while (type && __Pyx_PyType_GetSlot(type, tp_traverse, traverseproc) != current_tp_traverse) + type = __Pyx_PyType_GetSlot(type, tp_base, PyTypeObject*); + while (type && (tp_traverse = __Pyx_PyType_GetSlot(type, tp_traverse, traverseproc)) == current_tp_traverse) + type = __Pyx_PyType_GetSlot(type, tp_base, PyTypeObject*); + if (type && tp_traverse) + return tp_traverse(obj, v, a); + return 0; +} + +/* CallTypeTraverse */ +#if !CYTHON_USE_TYPE_SPECS || (!CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x03090000) +#else +static int __Pyx_call_type_traverse(PyObject *o, int always_call, visitproc visit, void *arg) { + #if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x03090000 + if (__Pyx_get_runtime_version() < 0x03090000) return 0; + #endif + if (!always_call) { + PyTypeObject *base = __Pyx_PyObject_GetSlot(o, tp_base, PyTypeObject*); + unsigned long flags = PyType_GetFlags(base); + if (flags & Py_TPFLAGS_HEAPTYPE) { + return 0; + } + } + Py_VISIT((PyObject*)Py_TYPE(o)); + return 0; +} +#endif + +/* CallNextTpClear */ +static void __Pyx_call_next_tp_clear(PyObject* obj, inquiry current_tp_clear) { + PyTypeObject* type = Py_TYPE(obj); + inquiry tp_clear = NULL; + while (type && __Pyx_PyType_GetSlot(type, tp_clear, inquiry) != current_tp_clear) + type = __Pyx_PyType_GetSlot(type, tp_base, PyTypeObject*); + while (type && (tp_clear = __Pyx_PyType_GetSlot(type, tp_clear, inquiry)) == current_tp_clear) + type = __Pyx_PyType_GetSlot(type, tp_base, PyTypeObject*); + if (type && tp_clear) + tp_clear(obj); +} + +/* TypeImport */ +#ifndef __PYX_HAVE_RT_ImportType_3_2_4 +#define __PYX_HAVE_RT_ImportType_3_2_4 +static PyTypeObject *__Pyx_ImportType_3_2_4(PyObject *module, const char *module_name, const char *class_name, + size_t size, size_t alignment, enum __Pyx_ImportType_CheckSize_3_2_4 check_size) +{ + PyObject *result = 0; + Py_ssize_t basicsize; + Py_ssize_t itemsize; +#if defined(Py_LIMITED_API) || (defined(CYTHON_COMPILING_IN_LIMITED_API) && CYTHON_COMPILING_IN_LIMITED_API) + PyObject *py_basicsize; + PyObject *py_itemsize; +#endif + result = PyObject_GetAttrString(module, class_name); + if (!result) + goto bad; + if (!PyType_Check(result)) { + PyErr_Format(PyExc_TypeError, + "%.200s.%.200s is not a type object", + module_name, class_name); + goto bad; + } +#if !( defined(Py_LIMITED_API) || (defined(CYTHON_COMPILING_IN_LIMITED_API) && CYTHON_COMPILING_IN_LIMITED_API) ) + basicsize = ((PyTypeObject *)result)->tp_basicsize; + itemsize = ((PyTypeObject *)result)->tp_itemsize; +#else + if (size == 0) { + return (PyTypeObject *)result; + } + py_basicsize = PyObject_GetAttrString(result, "__basicsize__"); + if (!py_basicsize) + goto bad; + basicsize = PyLong_AsSsize_t(py_basicsize); + Py_DECREF(py_basicsize); + py_basicsize = 0; + if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred()) + goto bad; + py_itemsize = PyObject_GetAttrString(result, "__itemsize__"); + if (!py_itemsize) + goto bad; + itemsize = PyLong_AsSsize_t(py_itemsize); + Py_DECREF(py_itemsize); + py_itemsize = 0; + if (itemsize == (Py_ssize_t)-1 && PyErr_Occurred()) + goto bad; +#endif + if (itemsize) { + if (size % alignment) { + alignment = size % alignment; + } + if (itemsize < (Py_ssize_t)alignment) + itemsize = (Py_ssize_t)alignment; + } + if ((size_t)(basicsize + itemsize) < size) { + PyErr_Format(PyExc_ValueError, + "%.200s.%.200s size changed, may indicate binary incompatibility. " + "Expected %zd from C header, got %zd from PyObject", + module_name, class_name, size, basicsize+itemsize); + goto bad; + } + if (check_size == __Pyx_ImportType_CheckSize_Error_3_2_4 && + ((size_t)basicsize > size || (size_t)(basicsize + itemsize) < size)) { + PyErr_Format(PyExc_ValueError, + "%.200s.%.200s size changed, may indicate binary incompatibility. " + "Expected %zd from C header, got %zd-%zd from PyObject", + module_name, class_name, size, basicsize, basicsize+itemsize); + goto bad; + } + else if (check_size == __Pyx_ImportType_CheckSize_Warn_3_2_4 && (size_t)basicsize > size) { + if (PyErr_WarnFormat(NULL, 0, + "%.200s.%.200s size changed, may indicate binary incompatibility. " + "Expected %zd from C header, got %zd from PyObject", + module_name, class_name, size, basicsize) < 0) { + goto bad; + } + } + return (PyTypeObject *)result; +bad: + Py_XDECREF(result); + return NULL; +} +#endif + +/* GetVTable */ +static void* __Pyx_GetVtable(PyTypeObject *type) { + void* ptr; +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *ob = PyObject_GetAttr((PyObject *)type, __pyx_mstate_global->__pyx_n_u_pyx_vtable); +#else + PyObject *ob = PyObject_GetItem(type->tp_dict, __pyx_mstate_global->__pyx_n_u_pyx_vtable); +#endif + if (!ob) + goto bad; + ptr = PyCapsule_GetPointer(ob, 0); + if (!ptr && !PyErr_Occurred()) + PyErr_SetString(PyExc_RuntimeError, "invalid vtable found for imported type"); + Py_DECREF(ob); + return ptr; +bad: + Py_XDECREF(ob); + return NULL; +} + +/* LimitedApiGetTypeDict (used by SetItemOnTypeDict) */ +#if CYTHON_COMPILING_IN_LIMITED_API +static Py_ssize_t __Pyx_GetTypeDictOffset(void) { + PyObject *tp_dictoffset_o; + Py_ssize_t tp_dictoffset; + tp_dictoffset_o = PyObject_GetAttrString((PyObject*)(&PyType_Type), "__dictoffset__"); + if (unlikely(!tp_dictoffset_o)) return -1; + tp_dictoffset = PyLong_AsSsize_t(tp_dictoffset_o); + Py_DECREF(tp_dictoffset_o); + if (unlikely(tp_dictoffset == 0)) { + PyErr_SetString( + PyExc_TypeError, + "'type' doesn't have a dictoffset"); + return -1; + } else if (unlikely(tp_dictoffset < 0)) { + PyErr_SetString( + PyExc_TypeError, + "'type' has an unexpected negative dictoffset. " + "Please report this as Cython bug"); + return -1; + } + return tp_dictoffset; +} +static PyObject *__Pyx_GetTypeDict(PyTypeObject *tp) { + static Py_ssize_t tp_dictoffset = 0; + if (unlikely(tp_dictoffset == 0)) { + tp_dictoffset = __Pyx_GetTypeDictOffset(); + if (unlikely(tp_dictoffset == -1 && PyErr_Occurred())) { + tp_dictoffset = 0; // try again next time? + return NULL; + } + } + return *(PyObject**)((char*)tp + tp_dictoffset); +} +#endif + +/* SetItemOnTypeDict (used by FixUpExtensionType) */ +static int __Pyx__SetItemOnTypeDict(PyTypeObject *tp, PyObject *k, PyObject *v) { + int result; + PyObject *tp_dict; +#if CYTHON_COMPILING_IN_LIMITED_API + tp_dict = __Pyx_GetTypeDict(tp); + if (unlikely(!tp_dict)) return -1; +#else + tp_dict = tp->tp_dict; +#endif + result = PyDict_SetItem(tp_dict, k, v); + if (likely(!result)) { + PyType_Modified(tp); + if (unlikely(PyObject_HasAttr(v, __pyx_mstate_global->__pyx_n_u_set_name))) { + PyObject *setNameResult = PyObject_CallMethodObjArgs(v, __pyx_mstate_global->__pyx_n_u_set_name, (PyObject *) tp, k, NULL); + if (!setNameResult) return -1; + Py_DECREF(setNameResult); + } + } + return result; +} + +/* FixUpExtensionType */ +static int __Pyx_fix_up_extension_type_from_spec(PyType_Spec *spec, PyTypeObject *type) { +#if __PYX_LIMITED_VERSION_HEX > 0x030900B1 + CYTHON_UNUSED_VAR(spec); + CYTHON_UNUSED_VAR(type); + CYTHON_UNUSED_VAR(__Pyx__SetItemOnTypeDict); +#else + const PyType_Slot *slot = spec->slots; + int changed = 0; +#if !CYTHON_COMPILING_IN_LIMITED_API + while (slot && slot->slot && slot->slot != Py_tp_members) + slot++; + if (slot && slot->slot == Py_tp_members) { +#if !CYTHON_COMPILING_IN_CPYTHON + const +#endif // !CYTHON_COMPILING_IN_CPYTHON) + PyMemberDef *memb = (PyMemberDef*) slot->pfunc; + while (memb && memb->name) { + if (memb->name[0] == '_' && memb->name[1] == '_') { + if (strcmp(memb->name, "__weaklistoffset__") == 0) { + assert(memb->type == T_PYSSIZET); + assert(memb->flags == READONLY); + type->tp_weaklistoffset = memb->offset; + changed = 1; + } + else if (strcmp(memb->name, "__dictoffset__") == 0) { + assert(memb->type == T_PYSSIZET); + assert(memb->flags == READONLY); + type->tp_dictoffset = memb->offset; + changed = 1; + } +#if CYTHON_METH_FASTCALL + else if (strcmp(memb->name, "__vectorcalloffset__") == 0) { + assert(memb->type == T_PYSSIZET); + assert(memb->flags == READONLY); + type->tp_vectorcall_offset = memb->offset; + changed = 1; + } +#endif // CYTHON_METH_FASTCALL +#if !CYTHON_COMPILING_IN_PYPY + else if (strcmp(memb->name, "__module__") == 0) { + PyObject *descr; + assert(memb->type == T_OBJECT); + assert(memb->flags == 0 || memb->flags == READONLY); + descr = PyDescr_NewMember(type, memb); + if (unlikely(!descr)) + return -1; + int set_item_result = PyDict_SetItem(type->tp_dict, PyDescr_NAME(descr), descr); + Py_DECREF(descr); + if (unlikely(set_item_result < 0)) { + return -1; + } + changed = 1; + } +#endif // !CYTHON_COMPILING_IN_PYPY + } + memb++; + } + } +#endif // !CYTHON_COMPILING_IN_LIMITED_API +#if !CYTHON_COMPILING_IN_PYPY + slot = spec->slots; + while (slot && slot->slot && slot->slot != Py_tp_getset) + slot++; + if (slot && slot->slot == Py_tp_getset) { + PyGetSetDef *getset = (PyGetSetDef*) slot->pfunc; + while (getset && getset->name) { + if (getset->name[0] == '_' && getset->name[1] == '_' && strcmp(getset->name, "__module__") == 0) { + PyObject *descr = PyDescr_NewGetSet(type, getset); + if (unlikely(!descr)) + return -1; + #if CYTHON_COMPILING_IN_LIMITED_API + PyObject *pyname = PyUnicode_FromString(getset->name); + if (unlikely(!pyname)) { + Py_DECREF(descr); + return -1; + } + int set_item_result = __Pyx_SetItemOnTypeDict(type, pyname, descr); + Py_DECREF(pyname); + #else + CYTHON_UNUSED_VAR(__Pyx__SetItemOnTypeDict); + int set_item_result = PyDict_SetItem(type->tp_dict, PyDescr_NAME(descr), descr); + #endif + Py_DECREF(descr); + if (unlikely(set_item_result < 0)) { + return -1; + } + changed = 1; + } + ++getset; + } + } +#else + CYTHON_UNUSED_VAR(__Pyx__SetItemOnTypeDict); +#endif // !CYTHON_COMPILING_IN_PYPY + if (changed) + PyType_Modified(type); +#endif // PY_VERSION_HEX > 0x030900B1 + return 0; +} + +/* PyObjectCallNoArg (used by PyObjectCallMethod0) */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func) { + PyObject *arg[2] = {NULL, NULL}; + return __Pyx_PyObject_FastCall(func, arg + 1, 0 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET); +} + +/* PyObjectGetMethod (used by PyObjectCallMethod0) */ +#if !(CYTHON_VECTORCALL && (__PYX_LIMITED_VERSION_HEX >= 0x030C0000 || (!CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x03090000))) +static int __Pyx_PyObject_GetMethod(PyObject *obj, PyObject *name, PyObject **method) { + PyObject *attr; +#if CYTHON_UNPACK_METHODS && CYTHON_COMPILING_IN_CPYTHON && CYTHON_USE_PYTYPE_LOOKUP + __Pyx_TypeName type_name; + PyTypeObject *tp = Py_TYPE(obj); + PyObject *descr; + descrgetfunc f = NULL; + PyObject **dictptr, *dict; + int meth_found = 0; + assert (*method == NULL); + if (unlikely(tp->tp_getattro != PyObject_GenericGetAttr)) { + attr = __Pyx_PyObject_GetAttrStr(obj, name); + goto try_unpack; + } + if (unlikely(tp->tp_dict == NULL) && unlikely(PyType_Ready(tp) < 0)) { + return 0; + } + descr = _PyType_Lookup(tp, name); + if (likely(descr != NULL)) { + Py_INCREF(descr); +#if defined(Py_TPFLAGS_METHOD_DESCRIPTOR) && Py_TPFLAGS_METHOD_DESCRIPTOR + if (__Pyx_PyType_HasFeature(Py_TYPE(descr), Py_TPFLAGS_METHOD_DESCRIPTOR)) +#else + #ifdef __Pyx_CyFunction_USED + if (likely(PyFunction_Check(descr) || __Pyx_IS_TYPE(descr, &PyMethodDescr_Type) || __Pyx_CyFunction_Check(descr))) + #else + if (likely(PyFunction_Check(descr) || __Pyx_IS_TYPE(descr, &PyMethodDescr_Type))) + #endif +#endif + { + meth_found = 1; + } else { + f = Py_TYPE(descr)->tp_descr_get; + if (f != NULL && PyDescr_IsData(descr)) { + attr = f(descr, obj, (PyObject *)Py_TYPE(obj)); + Py_DECREF(descr); + goto try_unpack; + } + } + } + dictptr = _PyObject_GetDictPtr(obj); + if (dictptr != NULL && (dict = *dictptr) != NULL) { + Py_INCREF(dict); + attr = __Pyx_PyDict_GetItemStr(dict, name); + if (attr != NULL) { + Py_INCREF(attr); + Py_DECREF(dict); + Py_XDECREF(descr); + goto try_unpack; + } + Py_DECREF(dict); + } + if (meth_found) { + *method = descr; + return 1; + } + if (f != NULL) { + attr = f(descr, obj, (PyObject *)Py_TYPE(obj)); + Py_DECREF(descr); + goto try_unpack; + } + if (likely(descr != NULL)) { + *method = descr; + return 0; + } + type_name = __Pyx_PyType_GetFullyQualifiedName(tp); + PyErr_Format(PyExc_AttributeError, + "'" __Pyx_FMT_TYPENAME "' object has no attribute '%U'", + type_name, name); + __Pyx_DECREF_TypeName(type_name); + return 0; +#else + attr = __Pyx_PyObject_GetAttrStr(obj, name); + goto try_unpack; +#endif +try_unpack: +#if CYTHON_UNPACK_METHODS + if (likely(attr) && PyMethod_Check(attr) && likely(PyMethod_GET_SELF(attr) == obj)) { + PyObject *function = PyMethod_GET_FUNCTION(attr); + Py_INCREF(function); + Py_DECREF(attr); + *method = function; + return 1; + } +#endif + *method = attr; + return 0; +} +#endif + +/* PyObjectCallMethod0 (used by PyType_Ready) */ +static PyObject* __Pyx_PyObject_CallMethod0(PyObject* obj, PyObject* method_name) { +#if CYTHON_VECTORCALL && (__PYX_LIMITED_VERSION_HEX >= 0x030C0000 || (!CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x03090000)) + PyObject *args[1] = {obj}; + (void) __Pyx_PyObject_CallOneArg; + (void) __Pyx_PyObject_CallNoArg; + return PyObject_VectorcallMethod(method_name, args, 1 | PY_VECTORCALL_ARGUMENTS_OFFSET, NULL); +#else + PyObject *method = NULL, *result = NULL; + int is_method = __Pyx_PyObject_GetMethod(obj, method_name, &method); + if (likely(is_method)) { + result = __Pyx_PyObject_CallOneArg(method, obj); + Py_DECREF(method); + return result; + } + if (unlikely(!method)) goto bad; + result = __Pyx_PyObject_CallNoArg(method); + Py_DECREF(method); +bad: + return result; +#endif +} + +/* ValidateBasesTuple (used by PyType_Ready) */ +#if CYTHON_COMPILING_IN_CPYTHON || CYTHON_COMPILING_IN_LIMITED_API || CYTHON_USE_TYPE_SPECS +static int __Pyx_validate_bases_tuple(const char *type_name, Py_ssize_t dictoffset, PyObject *bases) { + Py_ssize_t i, n; +#if CYTHON_ASSUME_SAFE_SIZE + n = PyTuple_GET_SIZE(bases); +#else + n = PyTuple_Size(bases); + if (unlikely(n < 0)) return -1; +#endif + for (i = 1; i < n; i++) + { + PyTypeObject *b; +#if CYTHON_AVOID_BORROWED_REFS + PyObject *b0 = PySequence_GetItem(bases, i); + if (!b0) return -1; +#elif CYTHON_ASSUME_SAFE_MACROS + PyObject *b0 = PyTuple_GET_ITEM(bases, i); +#else + PyObject *b0 = PyTuple_GetItem(bases, i); + if (!b0) return -1; +#endif + b = (PyTypeObject*) b0; + if (!__Pyx_PyType_HasFeature(b, Py_TPFLAGS_HEAPTYPE)) + { + __Pyx_TypeName b_name = __Pyx_PyType_GetFullyQualifiedName(b); + PyErr_Format(PyExc_TypeError, + "base class '" __Pyx_FMT_TYPENAME "' is not a heap type", b_name); + __Pyx_DECREF_TypeName(b_name); +#if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(b0); +#endif + return -1; + } + if (dictoffset == 0) + { + Py_ssize_t b_dictoffset = 0; +#if CYTHON_USE_TYPE_SLOTS + b_dictoffset = b->tp_dictoffset; +#else + PyObject *py_b_dictoffset = PyObject_GetAttrString((PyObject*)b, "__dictoffset__"); + if (!py_b_dictoffset) goto dictoffset_return; + b_dictoffset = PyLong_AsSsize_t(py_b_dictoffset); + Py_DECREF(py_b_dictoffset); + if (b_dictoffset == -1 && PyErr_Occurred()) goto dictoffset_return; +#endif + if (b_dictoffset) { + { + __Pyx_TypeName b_name = __Pyx_PyType_GetFullyQualifiedName(b); + PyErr_Format(PyExc_TypeError, + "extension type '%.200s' has no __dict__ slot, " + "but base type '" __Pyx_FMT_TYPENAME "' has: " + "either add 'cdef dict __dict__' to the extension type " + "or add '__slots__ = [...]' to the base type", + type_name, b_name); + __Pyx_DECREF_TypeName(b_name); + } +#if !CYTHON_USE_TYPE_SLOTS + dictoffset_return: +#endif +#if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(b0); +#endif + return -1; + } + } +#if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(b0); +#endif + } + return 0; +} +#endif + +/* PyType_Ready */ +CYTHON_UNUSED static int __Pyx_PyType_HasMultipleInheritance(PyTypeObject *t) { + while (t) { + PyObject *bases = __Pyx_PyType_GetSlot(t, tp_bases, PyObject*); + if (bases) { + return 1; + } + t = __Pyx_PyType_GetSlot(t, tp_base, PyTypeObject*); + } + return 0; +} +static int __Pyx_PyType_Ready(PyTypeObject *t) { +#if CYTHON_USE_TYPE_SPECS || !CYTHON_COMPILING_IN_CPYTHON || defined(PYSTON_MAJOR_VERSION) + (void)__Pyx_PyObject_CallMethod0; +#if CYTHON_USE_TYPE_SPECS + (void)__Pyx_validate_bases_tuple; +#endif + return PyType_Ready(t); +#else + int r; + if (!__Pyx_PyType_HasMultipleInheritance(t)) { + return PyType_Ready(t); + } + PyObject *bases = __Pyx_PyType_GetSlot(t, tp_bases, PyObject*); + if (bases && unlikely(__Pyx_validate_bases_tuple(t->tp_name, t->tp_dictoffset, bases) == -1)) + return -1; +#if !defined(PYSTON_MAJOR_VERSION) + { + int gc_was_enabled; + #if PY_VERSION_HEX >= 0x030A00b1 + gc_was_enabled = PyGC_Disable(); + (void)__Pyx_PyObject_CallMethod0; + #else + PyObject *ret, *py_status; + PyObject *gc = NULL; + #if (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM+0 >= 0x07030400) &&\ + !CYTHON_COMPILING_IN_GRAAL + gc = PyImport_GetModule(__pyx_mstate_global->__pyx_kp_u_gc); + #endif + if (unlikely(!gc)) gc = PyImport_Import(__pyx_mstate_global->__pyx_kp_u_gc); + if (unlikely(!gc)) return -1; + py_status = __Pyx_PyObject_CallMethod0(gc, __pyx_mstate_global->__pyx_kp_u_isenabled); + if (unlikely(!py_status)) { + Py_DECREF(gc); + return -1; + } + gc_was_enabled = __Pyx_PyObject_IsTrue(py_status); + Py_DECREF(py_status); + if (gc_was_enabled > 0) { + ret = __Pyx_PyObject_CallMethod0(gc, __pyx_mstate_global->__pyx_kp_u_disable); + if (unlikely(!ret)) { + Py_DECREF(gc); + return -1; + } + Py_DECREF(ret); + } else if (unlikely(gc_was_enabled == -1)) { + Py_DECREF(gc); + return -1; + } + #endif + t->tp_flags |= Py_TPFLAGS_HEAPTYPE; +#if PY_VERSION_HEX >= 0x030A0000 + t->tp_flags |= Py_TPFLAGS_IMMUTABLETYPE; +#endif +#else + (void)__Pyx_PyObject_CallMethod0; +#endif + r = PyType_Ready(t); +#if !defined(PYSTON_MAJOR_VERSION) + t->tp_flags &= ~Py_TPFLAGS_HEAPTYPE; + #if PY_VERSION_HEX >= 0x030A00b1 + if (gc_was_enabled) + PyGC_Enable(); + #else + if (gc_was_enabled) { + PyObject *tp, *v, *tb; + PyErr_Fetch(&tp, &v, &tb); + ret = __Pyx_PyObject_CallMethod0(gc, __pyx_mstate_global->__pyx_kp_u_enable); + if (likely(ret || r == -1)) { + Py_XDECREF(ret); + PyErr_Restore(tp, v, tb); + } else { + Py_XDECREF(tp); + Py_XDECREF(v); + Py_XDECREF(tb); + r = -1; + } + } + Py_DECREF(gc); + #endif + } +#endif + return r; +#endif +} + +/* SetVTable */ +static int __Pyx_SetVtable(PyTypeObject *type, void *vtable) { + PyObject *ob = PyCapsule_New(vtable, 0, 0); + if (unlikely(!ob)) + goto bad; +#if CYTHON_COMPILING_IN_LIMITED_API + if (unlikely(PyObject_SetAttr((PyObject *) type, __pyx_mstate_global->__pyx_n_u_pyx_vtable, ob) < 0)) +#else + if (unlikely(PyDict_SetItem(type->tp_dict, __pyx_mstate_global->__pyx_n_u_pyx_vtable, ob) < 0)) +#endif + goto bad; + Py_DECREF(ob); + return 0; +bad: + Py_XDECREF(ob); + return -1; +} + +/* MergeVTables */ +static int __Pyx_MergeVtables(PyTypeObject *type) { + int i=0; + Py_ssize_t size; + void** base_vtables; + __Pyx_TypeName tp_base_name = NULL; + __Pyx_TypeName base_name = NULL; + void* unknown = (void*)-1; + PyObject* bases = __Pyx_PyType_GetSlot(type, tp_bases, PyObject*); + int base_depth = 0; + { + PyTypeObject* base = __Pyx_PyType_GetSlot(type, tp_base, PyTypeObject*); + while (base) { + base_depth += 1; + base = __Pyx_PyType_GetSlot(base, tp_base, PyTypeObject*); + } + } + base_vtables = (void**) PyMem_Malloc(sizeof(void*) * (size_t)(base_depth + 1)); + base_vtables[0] = unknown; +#if CYTHON_COMPILING_IN_LIMITED_API + size = PyTuple_Size(bases); + if (size < 0) goto other_failure; +#else + size = PyTuple_GET_SIZE(bases); +#endif + for (i = 1; i < size; i++) { + PyObject *basei; + void* base_vtable; +#if CYTHON_AVOID_BORROWED_REFS + basei = PySequence_GetItem(bases, i); + if (unlikely(!basei)) goto other_failure; +#elif !CYTHON_ASSUME_SAFE_MACROS + basei = PyTuple_GetItem(bases, i); + if (unlikely(!basei)) goto other_failure; +#else + basei = PyTuple_GET_ITEM(bases, i); +#endif + base_vtable = __Pyx_GetVtable((PyTypeObject*)basei); +#if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(basei); +#endif + if (base_vtable != NULL) { + int j; + PyTypeObject* base = __Pyx_PyType_GetSlot(type, tp_base, PyTypeObject*); + for (j = 0; j < base_depth; j++) { + if (base_vtables[j] == unknown) { + base_vtables[j] = __Pyx_GetVtable(base); + base_vtables[j + 1] = unknown; + } + if (base_vtables[j] == base_vtable) { + break; + } else if (base_vtables[j] == NULL) { + goto bad; + } + base = __Pyx_PyType_GetSlot(base, tp_base, PyTypeObject*); + } + } + } + PyErr_Clear(); + PyMem_Free(base_vtables); + return 0; +bad: + { + PyTypeObject* basei = NULL; + PyTypeObject* tp_base = __Pyx_PyType_GetSlot(type, tp_base, PyTypeObject*); + tp_base_name = __Pyx_PyType_GetFullyQualifiedName(tp_base); +#if CYTHON_AVOID_BORROWED_REFS + basei = (PyTypeObject*)PySequence_GetItem(bases, i); + if (unlikely(!basei)) goto really_bad; +#elif !CYTHON_ASSUME_SAFE_MACROS + basei = (PyTypeObject*)PyTuple_GetItem(bases, i); + if (unlikely(!basei)) goto really_bad; +#else + basei = (PyTypeObject*)PyTuple_GET_ITEM(bases, i); +#endif + base_name = __Pyx_PyType_GetFullyQualifiedName(basei); +#if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(basei); +#endif + } + PyErr_Format(PyExc_TypeError, + "multiple bases have vtable conflict: '" __Pyx_FMT_TYPENAME "' and '" __Pyx_FMT_TYPENAME "'", tp_base_name, base_name); +#if CYTHON_AVOID_BORROWED_REFS || !CYTHON_ASSUME_SAFE_MACROS +really_bad: // bad has failed! +#endif + __Pyx_DECREF_TypeName(tp_base_name); + __Pyx_DECREF_TypeName(base_name); +#if CYTHON_COMPILING_IN_LIMITED_API || CYTHON_AVOID_BORROWED_REFS || !CYTHON_ASSUME_SAFE_MACROS +other_failure: +#endif + PyMem_Free(base_vtables); + return -1; +} + +/* DelItemOnTypeDict (used by SetupReduce) */ +static int __Pyx__DelItemOnTypeDict(PyTypeObject *tp, PyObject *k) { + int result; + PyObject *tp_dict; +#if CYTHON_COMPILING_IN_LIMITED_API + tp_dict = __Pyx_GetTypeDict(tp); + if (unlikely(!tp_dict)) return -1; +#else + tp_dict = tp->tp_dict; +#endif + result = PyDict_DelItem(tp_dict, k); + if (likely(!result)) PyType_Modified(tp); + return result; +} + +/* SetupReduce */ +static int __Pyx_setup_reduce_is_named(PyObject* meth, PyObject* name) { + int ret; + PyObject *name_attr; + name_attr = __Pyx_PyObject_GetAttrStrNoError(meth, __pyx_mstate_global->__pyx_n_u_name); + if (likely(name_attr)) { + ret = PyObject_RichCompareBool(name_attr, name, Py_EQ); + } else { + ret = -1; + } + if (unlikely(ret < 0)) { + PyErr_Clear(); + ret = 0; + } + Py_XDECREF(name_attr); + return ret; +} +static int __Pyx_setup_reduce(PyObject* type_obj) { + int ret = 0; + PyObject *object_reduce = NULL; + PyObject *object_getstate = NULL; + PyObject *object_reduce_ex = NULL; + PyObject *reduce = NULL; + PyObject *reduce_ex = NULL; + PyObject *reduce_cython = NULL; + PyObject *setstate = NULL; + PyObject *setstate_cython = NULL; + PyObject *getstate = NULL; +#if CYTHON_USE_PYTYPE_LOOKUP + getstate = _PyType_Lookup((PyTypeObject*)type_obj, __pyx_mstate_global->__pyx_n_u_getstate); +#else + getstate = __Pyx_PyObject_GetAttrStrNoError(type_obj, __pyx_mstate_global->__pyx_n_u_getstate); + if (!getstate && PyErr_Occurred()) { + goto __PYX_BAD; + } +#endif + if (getstate) { +#if CYTHON_USE_PYTYPE_LOOKUP + object_getstate = _PyType_Lookup(&PyBaseObject_Type, __pyx_mstate_global->__pyx_n_u_getstate); +#else + object_getstate = __Pyx_PyObject_GetAttrStrNoError((PyObject*)&PyBaseObject_Type, __pyx_mstate_global->__pyx_n_u_getstate); + if (!object_getstate && PyErr_Occurred()) { + goto __PYX_BAD; + } +#endif + if (object_getstate != getstate) { + goto __PYX_GOOD; + } + } +#if CYTHON_USE_PYTYPE_LOOKUP + object_reduce_ex = _PyType_Lookup(&PyBaseObject_Type, __pyx_mstate_global->__pyx_n_u_reduce_ex); if (!object_reduce_ex) goto __PYX_BAD; +#else + object_reduce_ex = __Pyx_PyObject_GetAttrStr((PyObject*)&PyBaseObject_Type, __pyx_mstate_global->__pyx_n_u_reduce_ex); if (!object_reduce_ex) goto __PYX_BAD; +#endif + reduce_ex = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_mstate_global->__pyx_n_u_reduce_ex); if (unlikely(!reduce_ex)) goto __PYX_BAD; + if (reduce_ex == object_reduce_ex) { +#if CYTHON_USE_PYTYPE_LOOKUP + object_reduce = _PyType_Lookup(&PyBaseObject_Type, __pyx_mstate_global->__pyx_n_u_reduce); if (!object_reduce) goto __PYX_BAD; +#else + object_reduce = __Pyx_PyObject_GetAttrStr((PyObject*)&PyBaseObject_Type, __pyx_mstate_global->__pyx_n_u_reduce); if (!object_reduce) goto __PYX_BAD; +#endif + reduce = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_mstate_global->__pyx_n_u_reduce); if (unlikely(!reduce)) goto __PYX_BAD; + if (reduce == object_reduce || __Pyx_setup_reduce_is_named(reduce, __pyx_mstate_global->__pyx_n_u_reduce_cython)) { + reduce_cython = __Pyx_PyObject_GetAttrStrNoError(type_obj, __pyx_mstate_global->__pyx_n_u_reduce_cython); + if (likely(reduce_cython)) { + ret = __Pyx_SetItemOnTypeDict((PyTypeObject*)type_obj, __pyx_mstate_global->__pyx_n_u_reduce, reduce_cython); if (unlikely(ret < 0)) goto __PYX_BAD; + ret = __Pyx_DelItemOnTypeDict((PyTypeObject*)type_obj, __pyx_mstate_global->__pyx_n_u_reduce_cython); if (unlikely(ret < 0)) goto __PYX_BAD; + } else if (reduce == object_reduce || PyErr_Occurred()) { + goto __PYX_BAD; + } + setstate = __Pyx_PyObject_GetAttrStrNoError(type_obj, __pyx_mstate_global->__pyx_n_u_setstate); + if (!setstate) PyErr_Clear(); + if (!setstate || __Pyx_setup_reduce_is_named(setstate, __pyx_mstate_global->__pyx_n_u_setstate_cython)) { + setstate_cython = __Pyx_PyObject_GetAttrStrNoError(type_obj, __pyx_mstate_global->__pyx_n_u_setstate_cython); + if (likely(setstate_cython)) { + ret = __Pyx_SetItemOnTypeDict((PyTypeObject*)type_obj, __pyx_mstate_global->__pyx_n_u_setstate, setstate_cython); if (unlikely(ret < 0)) goto __PYX_BAD; + ret = __Pyx_DelItemOnTypeDict((PyTypeObject*)type_obj, __pyx_mstate_global->__pyx_n_u_setstate_cython); if (unlikely(ret < 0)) goto __PYX_BAD; + } else if (!setstate || PyErr_Occurred()) { + goto __PYX_BAD; + } + } + PyType_Modified((PyTypeObject*)type_obj); + } + } + goto __PYX_GOOD; +__PYX_BAD: + if (!PyErr_Occurred()) { + __Pyx_TypeName type_obj_name = + __Pyx_PyType_GetFullyQualifiedName((PyTypeObject*)type_obj); + PyErr_Format(PyExc_RuntimeError, + "Unable to initialize pickling for " __Pyx_FMT_TYPENAME, type_obj_name); + __Pyx_DECREF_TypeName(type_obj_name); + } + ret = -1; +__PYX_GOOD: +#if !CYTHON_USE_PYTYPE_LOOKUP + Py_XDECREF(object_reduce); + Py_XDECREF(object_reduce_ex); + Py_XDECREF(object_getstate); + Py_XDECREF(getstate); +#endif + Py_XDECREF(reduce); + Py_XDECREF(reduce_ex); + Py_XDECREF(reduce_cython); + Py_XDECREF(setstate); + Py_XDECREF(setstate_cython); + return ret; +} + +/* HasAttr (used by ImportImpl) */ +#if __PYX_LIMITED_VERSION_HEX < 0x030d0000 +static CYTHON_INLINE int __Pyx_HasAttr(PyObject *o, PyObject *n) { + PyObject *r; + if (unlikely(!PyUnicode_Check(n))) { + PyErr_SetString(PyExc_TypeError, + "hasattr(): attribute name must be string"); + return -1; + } + r = __Pyx_PyObject_GetAttrStrNoError(o, n); + if (!r) { + return (unlikely(PyErr_Occurred())) ? -1 : 0; + } else { + Py_DECREF(r); + return 1; + } +} +#endif + +/* ImportImpl (used by Import) */ +static int __Pyx__Import_GetModule(PyObject *qualname, PyObject **module) { + PyObject *imported_module = PyImport_GetModule(qualname); + if (unlikely(!imported_module)) { + *module = NULL; + if (PyErr_Occurred()) { + return -1; + } + return 0; + } + *module = imported_module; + return 1; +} +static int __Pyx__Import_Lookup(PyObject *qualname, PyObject *const *imported_names, Py_ssize_t len_imported_names, PyObject **module) { + PyObject *imported_module; + PyObject *top_level_package_name; + Py_ssize_t i; + int status, module_found; + Py_ssize_t dot_index; + module_found = __Pyx__Import_GetModule(qualname, &imported_module); + if (unlikely(!module_found || module_found == -1)) { + *module = NULL; + return module_found; + } + if (imported_names) { + for (i = 0; i < len_imported_names; i++) { + PyObject *imported_name = imported_names[i]; +#if __PYX_LIMITED_VERSION_HEX < 0x030d0000 + int has_imported_attribute = PyObject_HasAttr(imported_module, imported_name); +#else + int has_imported_attribute = PyObject_HasAttrWithError(imported_module, imported_name); + if (unlikely(has_imported_attribute == -1)) goto error; +#endif + if (!has_imported_attribute) { + goto not_found; + } + } + *module = imported_module; + return 1; + } + dot_index = PyUnicode_FindChar(qualname, '.', 0, PY_SSIZE_T_MAX, 1); + if (dot_index == -1) { + *module = imported_module; + return 1; + } + if (unlikely(dot_index == -2)) goto error; + top_level_package_name = PyUnicode_Substring(qualname, 0, dot_index); + if (unlikely(!top_level_package_name)) goto error; + Py_DECREF(imported_module); + status = __Pyx__Import_GetModule(top_level_package_name, module); + Py_DECREF(top_level_package_name); + return status; +error: + Py_DECREF(imported_module); + *module = NULL; + return -1; +not_found: + Py_DECREF(imported_module); + *module = NULL; + return 0; +} +static PyObject *__Pyx__Import(PyObject *name, PyObject *const *imported_names, Py_ssize_t len_imported_names, PyObject *qualname, PyObject *moddict, int level) { + PyObject *module = 0; + PyObject *empty_dict = 0; + PyObject *from_list = 0; + int module_found; + if (!qualname) { + qualname = name; + } + module_found = __Pyx__Import_Lookup(qualname, imported_names, len_imported_names, &module); + if (likely(module_found == 1)) { + return module; + } else if (unlikely(module_found == -1)) { + return NULL; + } + empty_dict = PyDict_New(); + if (unlikely(!empty_dict)) + goto bad; + if (imported_names) { +#if CYTHON_COMPILING_IN_CPYTHON + from_list = __Pyx_PyList_FromArray(imported_names, len_imported_names); + if (unlikely(!from_list)) + goto bad; +#else + from_list = PyList_New(len_imported_names); + if (unlikely(!from_list)) goto bad; + for (Py_ssize_t i=0; i__pyx_d, level); +} + +/* ImportFrom */ +static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name) { + PyObject* value = __Pyx_PyObject_GetAttrStr(module, name); + if (unlikely(!value) && PyErr_ExceptionMatches(PyExc_AttributeError)) { + const char* module_name_str = 0; + PyObject* module_name = 0; + PyObject* module_dot = 0; + PyObject* full_name = 0; + PyErr_Clear(); + module_name_str = PyModule_GetName(module); + if (unlikely(!module_name_str)) { goto modbad; } + module_name = PyUnicode_FromString(module_name_str); + if (unlikely(!module_name)) { goto modbad; } + module_dot = PyUnicode_Concat(module_name, __pyx_mstate_global->__pyx_kp_u__4); + if (unlikely(!module_dot)) { goto modbad; } + full_name = PyUnicode_Concat(module_dot, name); + if (unlikely(!full_name)) { goto modbad; } + #if (CYTHON_COMPILING_IN_PYPY && PYPY_VERSION_NUM < 0x07030400) ||\ + CYTHON_COMPILING_IN_GRAAL + { + PyObject *modules = PyImport_GetModuleDict(); + if (unlikely(!modules)) + goto modbad; + value = PyObject_GetItem(modules, full_name); + } + #else + value = PyImport_GetModule(full_name); + #endif + modbad: + Py_XDECREF(full_name); + Py_XDECREF(module_dot); + Py_XDECREF(module_name); + } + if (unlikely(!value)) { + PyErr_Format(PyExc_ImportError, "cannot import name %S", name); + } + return value; +} + +/* dict_setdefault (used by FetchCommonType) */ +static CYTHON_INLINE PyObject *__Pyx_PyDict_SetDefault(PyObject *d, PyObject *key, PyObject *default_value) { + PyObject* value; +#if __PYX_LIMITED_VERSION_HEX >= 0x030F0000 || (!CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d00A4) + PyDict_SetDefaultRef(d, key, default_value, &value); +#elif CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX >= 0x030C0000 + PyObject *args[] = {d, key, default_value}; + value = PyObject_VectorcallMethod(__pyx_mstate_global->__pyx_n_u_setdefault, args, 3 | PY_VECTORCALL_ARGUMENTS_OFFSET, NULL); +#elif CYTHON_COMPILING_IN_LIMITED_API + value = PyObject_CallMethodObjArgs(d, __pyx_mstate_global->__pyx_n_u_setdefault, key, default_value, NULL); +#else + value = PyDict_SetDefault(d, key, default_value); + if (unlikely(!value)) return NULL; + Py_INCREF(value); +#endif + return value; +} + +/* AddModuleRef (used by FetchSharedCythonModule) */ +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + static PyObject *__Pyx_PyImport_AddModuleObjectRef(PyObject *name) { + PyObject *module_dict = PyImport_GetModuleDict(); + PyObject *m; + if (PyMapping_GetOptionalItem(module_dict, name, &m) < 0) { + return NULL; + } + if (m != NULL && PyModule_Check(m)) { + return m; + } + Py_XDECREF(m); + m = PyModule_NewObject(name); + if (m == NULL) + return NULL; + if (PyDict_CheckExact(module_dict)) { + PyObject *new_m; + (void)PyDict_SetDefaultRef(module_dict, name, m, &new_m); + Py_DECREF(m); + return new_m; + } else { + if (PyObject_SetItem(module_dict, name, m) != 0) { + Py_DECREF(m); + return NULL; + } + return m; + } + } + static PyObject *__Pyx_PyImport_AddModuleRef(const char *name) { + PyObject *py_name = PyUnicode_FromString(name); + if (!py_name) return NULL; + PyObject *module = __Pyx_PyImport_AddModuleObjectRef(py_name); + Py_DECREF(py_name); + return module; + } +#elif __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + #define __Pyx_PyImport_AddModuleRef(name) PyImport_AddModuleRef(name) +#else + static PyObject *__Pyx_PyImport_AddModuleRef(const char *name) { + PyObject *module = PyImport_AddModule(name); + Py_XINCREF(module); + return module; + } +#endif + +/* FetchSharedCythonModule (used by FetchCommonType) */ +static PyObject *__Pyx_FetchSharedCythonABIModule(void) { + return __Pyx_PyImport_AddModuleRef(__PYX_ABI_MODULE_NAME); +} + +/* FetchCommonType (used by CommonTypesMetaclass) */ +#if __PYX_LIMITED_VERSION_HEX < 0x030C0000 +static PyObject* __Pyx_PyType_FromMetaclass(PyTypeObject *metaclass, PyObject *module, PyType_Spec *spec, PyObject *bases) { + PyObject *result = __Pyx_PyType_FromModuleAndSpec(module, spec, bases); + if (result && metaclass) { + PyObject *old_tp = (PyObject*)Py_TYPE(result); + Py_INCREF((PyObject*)metaclass); +#if __PYX_LIMITED_VERSION_HEX >= 0x03090000 + Py_SET_TYPE(result, metaclass); +#else + result->ob_type = metaclass; +#endif + Py_DECREF(old_tp); + } + return result; +} +#else +#define __Pyx_PyType_FromMetaclass(me, mo, s, b) PyType_FromMetaclass(me, mo, s, b) +#endif +static int __Pyx_VerifyCachedType(PyObject *cached_type, + const char *name, + Py_ssize_t expected_basicsize) { + Py_ssize_t basicsize; + if (!PyType_Check(cached_type)) { + PyErr_Format(PyExc_TypeError, + "Shared Cython type %.200s is not a type object", name); + return -1; + } + if (expected_basicsize == 0) { + return 0; // size is inherited, nothing useful to check + } +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *py_basicsize; + py_basicsize = PyObject_GetAttrString(cached_type, "__basicsize__"); + if (unlikely(!py_basicsize)) return -1; + basicsize = PyLong_AsSsize_t(py_basicsize); + Py_DECREF(py_basicsize); + py_basicsize = NULL; + if (unlikely(basicsize == (Py_ssize_t)-1) && PyErr_Occurred()) return -1; +#else + basicsize = ((PyTypeObject*) cached_type)->tp_basicsize; +#endif + if (basicsize != expected_basicsize) { + PyErr_Format(PyExc_TypeError, + "Shared Cython type %.200s has the wrong size, try recompiling", + name); + return -1; + } + return 0; +} +static PyTypeObject *__Pyx_FetchCommonTypeFromSpec(PyTypeObject *metaclass, PyObject *module, PyType_Spec *spec, PyObject *bases) { + PyObject *abi_module = NULL, *cached_type = NULL, *abi_module_dict, *new_cached_type, *py_object_name; + int get_item_ref_result; + const char* object_name = strrchr(spec->name, '.'); + object_name = object_name ? object_name+1 : spec->name; + py_object_name = PyUnicode_FromString(object_name); + if (!py_object_name) return NULL; + abi_module = __Pyx_FetchSharedCythonABIModule(); + if (!abi_module) goto done; + abi_module_dict = PyModule_GetDict(abi_module); + if (!abi_module_dict) goto done; + get_item_ref_result = __Pyx_PyDict_GetItemRef(abi_module_dict, py_object_name, &cached_type); + if (get_item_ref_result == 1) { + if (__Pyx_VerifyCachedType( + cached_type, + object_name, + spec->basicsize) < 0) { + goto bad; + } + goto done; + } else if (unlikely(get_item_ref_result == -1)) { + goto bad; + } + cached_type = __Pyx_PyType_FromMetaclass( + metaclass, + CYTHON_USE_MODULE_STATE ? module : abi_module, + spec, bases); + if (unlikely(!cached_type)) goto bad; + if (unlikely(__Pyx_fix_up_extension_type_from_spec(spec, (PyTypeObject *) cached_type) < 0)) goto bad; + new_cached_type = __Pyx_PyDict_SetDefault(abi_module_dict, py_object_name, cached_type); + if (unlikely(new_cached_type != cached_type)) { + if (unlikely(!new_cached_type)) goto bad; + Py_DECREF(cached_type); + cached_type = new_cached_type; + if (__Pyx_VerifyCachedType( + cached_type, + object_name, + spec->basicsize) < 0) { + goto bad; + } + goto done; + } else { + Py_DECREF(new_cached_type); + } +done: + Py_XDECREF(abi_module); + Py_DECREF(py_object_name); + assert(cached_type == NULL || PyType_Check(cached_type)); + return (PyTypeObject *) cached_type; +bad: + Py_XDECREF(cached_type); + cached_type = NULL; + goto done; +} + +/* CommonTypesMetaclass (used by CythonFunctionShared) */ +static PyObject* __pyx_CommonTypesMetaclass_get_module(CYTHON_UNUSED PyObject *self, CYTHON_UNUSED void* context) { + return PyUnicode_FromString(__PYX_ABI_MODULE_NAME); +} +#if __PYX_LIMITED_VERSION_HEX < 0x030A0000 +static PyObject* __pyx_CommonTypesMetaclass_call(CYTHON_UNUSED PyObject *self, CYTHON_UNUSED PyObject *args, CYTHON_UNUSED PyObject *kwds) { + PyErr_SetString(PyExc_TypeError, "Cannot instantiate Cython internal types"); + return NULL; +} +static int __pyx_CommonTypesMetaclass_setattr(CYTHON_UNUSED PyObject *self, CYTHON_UNUSED PyObject *attr, CYTHON_UNUSED PyObject *value) { + PyErr_SetString(PyExc_TypeError, "Cython internal types are immutable"); + return -1; +} +#endif +static PyGetSetDef __pyx_CommonTypesMetaclass_getset[] = { + {"__module__", __pyx_CommonTypesMetaclass_get_module, NULL, NULL, NULL}, + {0, 0, 0, 0, 0} +}; +static PyType_Slot __pyx_CommonTypesMetaclass_slots[] = { + {Py_tp_getset, (void *)__pyx_CommonTypesMetaclass_getset}, + #if __PYX_LIMITED_VERSION_HEX < 0x030A0000 + {Py_tp_call, (void*)__pyx_CommonTypesMetaclass_call}, + {Py_tp_new, (void*)__pyx_CommonTypesMetaclass_call}, + {Py_tp_setattro, (void*)__pyx_CommonTypesMetaclass_setattr}, + #endif + {0, 0} +}; +static PyType_Spec __pyx_CommonTypesMetaclass_spec = { + __PYX_TYPE_MODULE_PREFIX "_common_types_metatype", + 0, + 0, + Py_TPFLAGS_IMMUTABLETYPE | + Py_TPFLAGS_DISALLOW_INSTANTIATION | + Py_TPFLAGS_DEFAULT, + __pyx_CommonTypesMetaclass_slots +}; +static int __pyx_CommonTypesMetaclass_init(PyObject *module) { + __pyx_mstatetype *mstate = __Pyx_PyModule_GetState(module); + PyObject *bases = PyTuple_Pack(1, &PyType_Type); + if (unlikely(!bases)) { + return -1; + } + mstate->__pyx_CommonTypesMetaclassType = __Pyx_FetchCommonTypeFromSpec(NULL, module, &__pyx_CommonTypesMetaclass_spec, bases); + Py_DECREF(bases); + if (unlikely(mstate->__pyx_CommonTypesMetaclassType == NULL)) { + return -1; + } + return 0; +} + +/* PyMethodNew (used by CythonFunctionShared) */ +#if CYTHON_COMPILING_IN_LIMITED_API +static PyObject *__Pyx_PyMethod_New(PyObject *func, PyObject *self, PyObject *typ) { + PyObject *result; + CYTHON_UNUSED_VAR(typ); + if (!self) + return __Pyx_NewRef(func); + #if __PYX_LIMITED_VERSION_HEX >= 0x030C0000 + { + PyObject *args[] = {func, self}; + result = PyObject_Vectorcall(__pyx_mstate_global->__Pyx_CachedMethodType, args, 2, NULL); + } + #else + result = PyObject_CallFunctionObjArgs(__pyx_mstate_global->__Pyx_CachedMethodType, func, self, NULL); + #endif + return result; +} +#else +static PyObject *__Pyx_PyMethod_New(PyObject *func, PyObject *self, PyObject *typ) { + CYTHON_UNUSED_VAR(typ); + if (!self) + return __Pyx_NewRef(func); + return PyMethod_New(func, self); +} +#endif + +/* PyVectorcallFastCallDict (used by CythonFunctionShared) */ +#if CYTHON_METH_FASTCALL && CYTHON_VECTORCALL +static PyObject *__Pyx_PyVectorcall_FastCallDict_kw(PyObject *func, __pyx_vectorcallfunc vc, PyObject *const *args, size_t nargs, PyObject *kw) +{ + PyObject *res = NULL; + PyObject *kwnames; + PyObject **newargs; + PyObject **kwvalues; + Py_ssize_t i; + #if CYTHON_AVOID_BORROWED_REFS + PyObject *pos; + #else + Py_ssize_t pos; + #endif + size_t j; + PyObject *key, *value; + unsigned long keys_are_strings; + #if !CYTHON_ASSUME_SAFE_SIZE + Py_ssize_t nkw = PyDict_Size(kw); + if (unlikely(nkw == -1)) return NULL; + #else + Py_ssize_t nkw = PyDict_GET_SIZE(kw); + #endif + newargs = (PyObject **)PyMem_Malloc((nargs + (size_t)nkw) * sizeof(args[0])); + if (unlikely(newargs == NULL)) { + PyErr_NoMemory(); + return NULL; + } + for (j = 0; j < nargs; j++) newargs[j] = args[j]; + kwnames = PyTuple_New(nkw); + if (unlikely(kwnames == NULL)) { + PyMem_Free(newargs); + return NULL; + } + kwvalues = newargs + nargs; + pos = 0; + i = 0; + keys_are_strings = Py_TPFLAGS_UNICODE_SUBCLASS; + while (__Pyx_PyDict_NextRef(kw, &pos, &key, &value)) { + keys_are_strings &= + #if CYTHON_COMPILING_IN_LIMITED_API + PyType_GetFlags(Py_TYPE(key)); + #else + Py_TYPE(key)->tp_flags; + #endif + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(PyTuple_SetItem(kwnames, i, key) < 0)) goto cleanup; + #else + PyTuple_SET_ITEM(kwnames, i, key); + #endif + kwvalues[i] = value; + i++; + } + if (unlikely(!keys_are_strings)) { + PyErr_SetString(PyExc_TypeError, "keywords must be strings"); + goto cleanup; + } + res = vc(func, newargs, nargs, kwnames); +cleanup: + #if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(pos); + #endif + Py_DECREF(kwnames); + for (i = 0; i < nkw; i++) + Py_DECREF(kwvalues[i]); + PyMem_Free(newargs); + return res; +} +static CYTHON_INLINE PyObject *__Pyx_PyVectorcall_FastCallDict(PyObject *func, __pyx_vectorcallfunc vc, PyObject *const *args, size_t nargs, PyObject *kw) +{ + Py_ssize_t kw_size = + likely(kw == NULL) ? + 0 : +#if !CYTHON_ASSUME_SAFE_SIZE + PyDict_Size(kw); +#else + PyDict_GET_SIZE(kw); +#endif + if (kw_size == 0) { + return vc(func, args, nargs, NULL); + } +#if !CYTHON_ASSUME_SAFE_SIZE + else if (unlikely(kw_size == -1)) { + return NULL; + } +#endif + return __Pyx_PyVectorcall_FastCallDict_kw(func, vc, args, nargs, kw); +} +#endif + +/* CythonFunctionShared (used by CythonFunction) */ +#if CYTHON_COMPILING_IN_LIMITED_API +static CYTHON_INLINE int __Pyx__IsSameCyOrCFunctionNoMethod(PyObject *func, void (*cfunc)(void)) { + if (__Pyx_CyFunction_Check(func)) { + return PyCFunction_GetFunction(((__pyx_CyFunctionObject*)func)->func) == (PyCFunction) cfunc; + } else if (PyCFunction_Check(func)) { + return PyCFunction_GetFunction(func) == (PyCFunction) cfunc; + } + return 0; +} +static CYTHON_INLINE int __Pyx__IsSameCyOrCFunction(PyObject *func, void (*cfunc)(void)) { + if ((PyObject*)Py_TYPE(func) == __pyx_mstate_global->__Pyx_CachedMethodType) { + int result; + PyObject *newFunc = PyObject_GetAttr(func, __pyx_mstate_global->__pyx_n_u_func); + if (unlikely(!newFunc)) { + PyErr_Clear(); // It's only an optimization, so don't throw an error + return 0; + } + result = __Pyx__IsSameCyOrCFunctionNoMethod(newFunc, cfunc); + Py_DECREF(newFunc); + return result; + } + return __Pyx__IsSameCyOrCFunctionNoMethod(func, cfunc); +} +#else +static CYTHON_INLINE int __Pyx__IsSameCyOrCFunction(PyObject *func, void (*cfunc)(void)) { + if (PyMethod_Check(func)) { + func = PyMethod_GET_FUNCTION(func); + } + return __Pyx_CyOrPyCFunction_Check(func) && __Pyx_CyOrPyCFunction_GET_FUNCTION(func) == (PyCFunction) cfunc; +} +#endif +static CYTHON_INLINE void __Pyx__CyFunction_SetClassObj(__pyx_CyFunctionObject* f, PyObject* classobj) { +#if PY_VERSION_HEX < 0x030900B1 || CYTHON_COMPILING_IN_LIMITED_API + __Pyx_Py_XDECREF_SET( + __Pyx_CyFunction_GetClassObj(f), + ((classobj) ? __Pyx_NewRef(classobj) : NULL)); +#else + __Pyx_Py_XDECREF_SET( + ((PyCMethodObject *) (f))->mm_class, + (PyTypeObject*)((classobj) ? __Pyx_NewRef(classobj) : NULL)); +#endif +} +static PyObject * +__Pyx_CyFunction_get_doc_locked(__pyx_CyFunctionObject *op) +{ + if (unlikely(op->func_doc == NULL)) { +#if CYTHON_COMPILING_IN_LIMITED_API + op->func_doc = PyObject_GetAttrString(op->func, "__doc__"); + if (unlikely(!op->func_doc)) return NULL; +#else + if (((PyCFunctionObject*)op)->m_ml->ml_doc) { + op->func_doc = PyUnicode_FromString(((PyCFunctionObject*)op)->m_ml->ml_doc); + if (unlikely(op->func_doc == NULL)) + return NULL; + } else { + Py_INCREF(Py_None); + return Py_None; + } +#endif + } + Py_INCREF(op->func_doc); + return op->func_doc; +} +static PyObject * +__Pyx_CyFunction_get_doc(__pyx_CyFunctionObject *op, void *closure) { + PyObject *result; + CYTHON_UNUSED_VAR(closure); + __Pyx_BEGIN_CRITICAL_SECTION(op); + result = __Pyx_CyFunction_get_doc_locked(op); + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static int +__Pyx_CyFunction_set_doc(__pyx_CyFunctionObject *op, PyObject *value, void *context) +{ + CYTHON_UNUSED_VAR(context); + if (value == NULL) { + value = Py_None; + } + Py_INCREF(value); + __Pyx_BEGIN_CRITICAL_SECTION(op); + __Pyx_Py_XDECREF_SET(op->func_doc, value); + __Pyx_END_CRITICAL_SECTION(); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_name_locked(__pyx_CyFunctionObject *op) +{ + if (unlikely(op->func_name == NULL)) { +#if CYTHON_COMPILING_IN_LIMITED_API + op->func_name = PyObject_GetAttrString(op->func, "__name__"); +#else + op->func_name = PyUnicode_InternFromString(((PyCFunctionObject*)op)->m_ml->ml_name); +#endif + if (unlikely(op->func_name == NULL)) + return NULL; + } + Py_INCREF(op->func_name); + return op->func_name; +} +static PyObject * +__Pyx_CyFunction_get_name(__pyx_CyFunctionObject *op, void *context) +{ + PyObject *result = NULL; + CYTHON_UNUSED_VAR(context); + __Pyx_BEGIN_CRITICAL_SECTION(op); + result = __Pyx_CyFunction_get_name_locked(op); + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static int +__Pyx_CyFunction_set_name(__pyx_CyFunctionObject *op, PyObject *value, void *context) +{ + CYTHON_UNUSED_VAR(context); + if (unlikely(value == NULL || !PyUnicode_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "__name__ must be set to a string object"); + return -1; + } + Py_INCREF(value); + __Pyx_BEGIN_CRITICAL_SECTION(op); + __Pyx_Py_XDECREF_SET(op->func_name, value); + __Pyx_END_CRITICAL_SECTION(); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_qualname(__pyx_CyFunctionObject *op, void *context) +{ + CYTHON_UNUSED_VAR(context); + PyObject *result; + __Pyx_BEGIN_CRITICAL_SECTION(op); + Py_INCREF(op->func_qualname); + result = op->func_qualname; + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static int +__Pyx_CyFunction_set_qualname(__pyx_CyFunctionObject *op, PyObject *value, void *context) +{ + CYTHON_UNUSED_VAR(context); + if (unlikely(value == NULL || !PyUnicode_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "__qualname__ must be set to a string object"); + return -1; + } + Py_INCREF(value); + __Pyx_BEGIN_CRITICAL_SECTION(op); + __Pyx_Py_XDECREF_SET(op->func_qualname, value); + __Pyx_END_CRITICAL_SECTION(); + return 0; +} +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000 +static PyObject * +__Pyx_CyFunction_get_dict(__pyx_CyFunctionObject *op, void *context) +{ + CYTHON_UNUSED_VAR(context); + if (unlikely(op->func_dict == NULL)) { + op->func_dict = PyDict_New(); + if (unlikely(op->func_dict == NULL)) + return NULL; + } + Py_INCREF(op->func_dict); + return op->func_dict; +} +#endif +static PyObject * +__Pyx_CyFunction_get_globals(__pyx_CyFunctionObject *op, void *context) +{ + CYTHON_UNUSED_VAR(context); + Py_INCREF(op->func_globals); + return op->func_globals; +} +static PyObject * +__Pyx_CyFunction_get_closure(__pyx_CyFunctionObject *op, void *context) +{ + CYTHON_UNUSED_VAR(op); + CYTHON_UNUSED_VAR(context); + Py_INCREF(Py_None); + return Py_None; +} +static PyObject * +__Pyx_CyFunction_get_code(__pyx_CyFunctionObject *op, void *context) +{ + PyObject* result = (op->func_code) ? op->func_code : Py_None; + CYTHON_UNUSED_VAR(context); + Py_INCREF(result); + return result; +} +static int +__Pyx_CyFunction_init_defaults(__pyx_CyFunctionObject *op) { + int result = 0; + PyObject *res = op->defaults_getter((PyObject *) op); + if (unlikely(!res)) + return -1; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + op->defaults_tuple = PyTuple_GET_ITEM(res, 0); + Py_INCREF(op->defaults_tuple); + op->defaults_kwdict = PyTuple_GET_ITEM(res, 1); + Py_INCREF(op->defaults_kwdict); + #else + op->defaults_tuple = __Pyx_PySequence_ITEM(res, 0); + if (unlikely(!op->defaults_tuple)) result = -1; + else { + op->defaults_kwdict = __Pyx_PySequence_ITEM(res, 1); + if (unlikely(!op->defaults_kwdict)) result = -1; + } + #endif + Py_DECREF(res); + return result; +} +static int +__Pyx_CyFunction_set_defaults(__pyx_CyFunctionObject *op, PyObject* value, void *context) { + CYTHON_UNUSED_VAR(context); + if (!value) { + value = Py_None; + } else if (unlikely(value != Py_None && !PyTuple_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "__defaults__ must be set to a tuple object"); + return -1; + } + PyErr_WarnEx(PyExc_RuntimeWarning, "changes to cyfunction.__defaults__ will not " + "currently affect the values used in function calls", 1); + Py_INCREF(value); + __Pyx_BEGIN_CRITICAL_SECTION(op); + __Pyx_Py_XDECREF_SET(op->defaults_tuple, value); + __Pyx_END_CRITICAL_SECTION(); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_defaults_locked(__pyx_CyFunctionObject *op) { + PyObject* result = op->defaults_tuple; + if (unlikely(!result)) { + if (op->defaults_getter) { + if (unlikely(__Pyx_CyFunction_init_defaults(op) < 0)) return NULL; + result = op->defaults_tuple; + } else { + result = Py_None; + } + } + Py_INCREF(result); + return result; +} +static PyObject * +__Pyx_CyFunction_get_defaults(__pyx_CyFunctionObject *op, void *context) { + PyObject* result = NULL; + CYTHON_UNUSED_VAR(context); + __Pyx_BEGIN_CRITICAL_SECTION(op); + result = __Pyx_CyFunction_get_defaults_locked(op); + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static int +__Pyx_CyFunction_set_kwdefaults(__pyx_CyFunctionObject *op, PyObject* value, void *context) { + CYTHON_UNUSED_VAR(context); + if (!value) { + value = Py_None; + } else if (unlikely(value != Py_None && !PyDict_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "__kwdefaults__ must be set to a dict object"); + return -1; + } + PyErr_WarnEx(PyExc_RuntimeWarning, "changes to cyfunction.__kwdefaults__ will not " + "currently affect the values used in function calls", 1); + Py_INCREF(value); + __Pyx_BEGIN_CRITICAL_SECTION(op); + __Pyx_Py_XDECREF_SET(op->defaults_kwdict, value); + __Pyx_END_CRITICAL_SECTION(); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_kwdefaults_locked(__pyx_CyFunctionObject *op) { + PyObject* result = op->defaults_kwdict; + if (unlikely(!result)) { + if (op->defaults_getter) { + if (unlikely(__Pyx_CyFunction_init_defaults(op) < 0)) return NULL; + result = op->defaults_kwdict; + } else { + result = Py_None; + } + } + Py_INCREF(result); + return result; +} +static PyObject * +__Pyx_CyFunction_get_kwdefaults(__pyx_CyFunctionObject *op, void *context) { + PyObject* result; + CYTHON_UNUSED_VAR(context); + __Pyx_BEGIN_CRITICAL_SECTION(op); + result = __Pyx_CyFunction_get_kwdefaults_locked(op); + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static int +__Pyx_CyFunction_set_annotations(__pyx_CyFunctionObject *op, PyObject* value, void *context) { + CYTHON_UNUSED_VAR(context); + if (!value || value == Py_None) { + value = NULL; + } else if (unlikely(!PyDict_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "__annotations__ must be set to a dict object"); + return -1; + } + Py_XINCREF(value); + __Pyx_BEGIN_CRITICAL_SECTION(op); + __Pyx_Py_XDECREF_SET(op->func_annotations, value); + __Pyx_END_CRITICAL_SECTION(); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_annotations_locked(__pyx_CyFunctionObject *op) { + PyObject* result = op->func_annotations; + if (unlikely(!result)) { + result = PyDict_New(); + if (unlikely(!result)) return NULL; + op->func_annotations = result; + } + Py_INCREF(result); + return result; +} +static PyObject * +__Pyx_CyFunction_get_annotations(__pyx_CyFunctionObject *op, void *context) { + PyObject *result; + CYTHON_UNUSED_VAR(context); + __Pyx_BEGIN_CRITICAL_SECTION(op); + result = __Pyx_CyFunction_get_annotations_locked(op); + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static PyObject * +__Pyx_CyFunction_get_is_coroutine_value(__pyx_CyFunctionObject *op) { + int is_coroutine = op->flags & __Pyx_CYFUNCTION_COROUTINE; + if (is_coroutine) { + PyObject *is_coroutine_value, *module, *fromlist, *marker = __pyx_mstate_global->__pyx_n_u_is_coroutine; + fromlist = PyList_New(1); + if (unlikely(!fromlist)) return NULL; + Py_INCREF(marker); +#if CYTHON_ASSUME_SAFE_MACROS + PyList_SET_ITEM(fromlist, 0, marker); +#else + if (unlikely(PyList_SetItem(fromlist, 0, marker) < 0)) { + Py_DECREF(marker); + Py_DECREF(fromlist); + return NULL; + } +#endif + module = PyImport_ImportModuleLevelObject(__pyx_mstate_global->__pyx_n_u_asyncio_coroutines, NULL, NULL, fromlist, 0); + Py_DECREF(fromlist); + if (unlikely(!module)) goto ignore; + is_coroutine_value = __Pyx_PyObject_GetAttrStr(module, marker); + Py_DECREF(module); + if (likely(is_coroutine_value)) { + return is_coroutine_value; + } +ignore: + PyErr_Clear(); + } + return __Pyx_PyBool_FromLong(is_coroutine); +} +static PyObject * +__Pyx_CyFunction_get_is_coroutine(__pyx_CyFunctionObject *op, void *context) { + PyObject *result; + CYTHON_UNUSED_VAR(context); + if (op->func_is_coroutine) { + return __Pyx_NewRef(op->func_is_coroutine); + } + result = __Pyx_CyFunction_get_is_coroutine_value(op); + if (unlikely(!result)) + return NULL; + __Pyx_BEGIN_CRITICAL_SECTION(op); + if (op->func_is_coroutine) { + Py_DECREF(result); + result = __Pyx_NewRef(op->func_is_coroutine); + } else { + op->func_is_coroutine = __Pyx_NewRef(result); + } + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static void __Pyx_CyFunction_raise_argument_count_error(__pyx_CyFunctionObject *func, const char* message, Py_ssize_t size) { +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *py_name = __Pyx_CyFunction_get_name(func, NULL); + if (!py_name) return; + PyErr_Format(PyExc_TypeError, + "%.200S() %s (%" CYTHON_FORMAT_SSIZE_T "d given)", + py_name, message, size); + Py_DECREF(py_name); +#else + const char* name = ((PyCFunctionObject*)func)->m_ml->ml_name; + PyErr_Format(PyExc_TypeError, + "%.200s() %s (%" CYTHON_FORMAT_SSIZE_T "d given)", + name, message, size); +#endif +} +static void __Pyx_CyFunction_raise_type_error(__pyx_CyFunctionObject *func, const char* message) { +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *py_name = __Pyx_CyFunction_get_name(func, NULL); + if (!py_name) return; + PyErr_Format(PyExc_TypeError, + "%.200S() %s", + py_name, message); + Py_DECREF(py_name); +#else + const char* name = ((PyCFunctionObject*)func)->m_ml->ml_name; + PyErr_Format(PyExc_TypeError, + "%.200s() %s", + name, message); +#endif +} +#if CYTHON_COMPILING_IN_LIMITED_API +static PyObject * +__Pyx_CyFunction_get_module(__pyx_CyFunctionObject *op, void *context) { + CYTHON_UNUSED_VAR(context); + return PyObject_GetAttrString(op->func, "__module__"); +} +static int +__Pyx_CyFunction_set_module(__pyx_CyFunctionObject *op, PyObject* value, void *context) { + CYTHON_UNUSED_VAR(context); + return PyObject_SetAttrString(op->func, "__module__", value); +} +#endif +static PyGetSetDef __pyx_CyFunction_getsets[] = { + {"func_doc", (getter)__Pyx_CyFunction_get_doc, (setter)__Pyx_CyFunction_set_doc, 0, 0}, + {"__doc__", (getter)__Pyx_CyFunction_get_doc, (setter)__Pyx_CyFunction_set_doc, 0, 0}, + {"func_name", (getter)__Pyx_CyFunction_get_name, (setter)__Pyx_CyFunction_set_name, 0, 0}, + {"__name__", (getter)__Pyx_CyFunction_get_name, (setter)__Pyx_CyFunction_set_name, 0, 0}, + {"__qualname__", (getter)__Pyx_CyFunction_get_qualname, (setter)__Pyx_CyFunction_set_qualname, 0, 0}, +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000 + {"func_dict", (getter)__Pyx_CyFunction_get_dict, (setter)PyObject_GenericSetDict, 0, 0}, + {"__dict__", (getter)__Pyx_CyFunction_get_dict, (setter)PyObject_GenericSetDict, 0, 0}, +#else + {"func_dict", (getter)PyObject_GenericGetDict, (setter)PyObject_GenericSetDict, 0, 0}, + {"__dict__", (getter)PyObject_GenericGetDict, (setter)PyObject_GenericSetDict, 0, 0}, +#endif + {"func_globals", (getter)__Pyx_CyFunction_get_globals, 0, 0, 0}, + {"__globals__", (getter)__Pyx_CyFunction_get_globals, 0, 0, 0}, + {"func_closure", (getter)__Pyx_CyFunction_get_closure, 0, 0, 0}, + {"__closure__", (getter)__Pyx_CyFunction_get_closure, 0, 0, 0}, + {"func_code", (getter)__Pyx_CyFunction_get_code, 0, 0, 0}, + {"__code__", (getter)__Pyx_CyFunction_get_code, 0, 0, 0}, + {"func_defaults", (getter)__Pyx_CyFunction_get_defaults, (setter)__Pyx_CyFunction_set_defaults, 0, 0}, + {"__defaults__", (getter)__Pyx_CyFunction_get_defaults, (setter)__Pyx_CyFunction_set_defaults, 0, 0}, + {"__kwdefaults__", (getter)__Pyx_CyFunction_get_kwdefaults, (setter)__Pyx_CyFunction_set_kwdefaults, 0, 0}, + {"__annotations__", (getter)__Pyx_CyFunction_get_annotations, (setter)__Pyx_CyFunction_set_annotations, 0, 0}, + {"_is_coroutine", (getter)__Pyx_CyFunction_get_is_coroutine, 0, 0, 0}, +#if CYTHON_COMPILING_IN_LIMITED_API + {"__module__", (getter)__Pyx_CyFunction_get_module, (setter)__Pyx_CyFunction_set_module, 0, 0}, +#endif + {0, 0, 0, 0, 0} +}; +static PyMemberDef __pyx_CyFunction_members[] = { +#if !CYTHON_COMPILING_IN_LIMITED_API + {"__module__", T_OBJECT, offsetof(PyCFunctionObject, m_module), 0, 0}, +#endif +#if PY_VERSION_HEX < 0x030C0000 || CYTHON_COMPILING_IN_LIMITED_API + {"__dictoffset__", T_PYSSIZET, offsetof(__pyx_CyFunctionObject, func_dict), READONLY, 0}, +#endif +#if CYTHON_METH_FASTCALL +#if CYTHON_COMPILING_IN_LIMITED_API + {"__vectorcalloffset__", T_PYSSIZET, offsetof(__pyx_CyFunctionObject, func_vectorcall), READONLY, 0}, +#else + {"__vectorcalloffset__", T_PYSSIZET, offsetof(PyCFunctionObject, vectorcall), READONLY, 0}, +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + {"__weaklistoffset__", T_PYSSIZET, offsetof(__pyx_CyFunctionObject, func_weakreflist), READONLY, 0}, +#else + {"__weaklistoffset__", T_PYSSIZET, offsetof(PyCFunctionObject, m_weakreflist), READONLY, 0}, +#endif +#endif + {0, 0, 0, 0, 0} +}; +static PyObject * +__Pyx_CyFunction_reduce(__pyx_CyFunctionObject *m, PyObject *args) +{ + PyObject *result = NULL; + CYTHON_UNUSED_VAR(args); + __Pyx_BEGIN_CRITICAL_SECTION(m); + Py_INCREF(m->func_qualname); + result = m->func_qualname; + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static PyMethodDef __pyx_CyFunction_methods[] = { + {"__reduce__", (PyCFunction)__Pyx_CyFunction_reduce, METH_VARARGS, 0}, + {0, 0, 0, 0} +}; +#if CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_CyFunction_weakreflist(cyfunc) ((cyfunc)->func_weakreflist) +#else +#define __Pyx_CyFunction_weakreflist(cyfunc) (((PyCFunctionObject*)cyfunc)->m_weakreflist) +#endif +static PyObject *__Pyx_CyFunction_Init(__pyx_CyFunctionObject *op, PyMethodDef *ml, int flags, PyObject* qualname, + PyObject *closure, PyObject *module, PyObject* globals, PyObject* code) { +#if !CYTHON_COMPILING_IN_LIMITED_API + PyCFunctionObject *cf = (PyCFunctionObject*) op; +#endif + if (unlikely(op == NULL)) + return NULL; +#if CYTHON_COMPILING_IN_LIMITED_API + op->func = PyCFunction_NewEx(ml, (PyObject*)op, module); + if (unlikely(!op->func)) return NULL; +#endif + op->flags = flags; + __Pyx_CyFunction_weakreflist(op) = NULL; +#if !CYTHON_COMPILING_IN_LIMITED_API + cf->m_ml = ml; + cf->m_self = (PyObject *) op; +#endif + Py_XINCREF(closure); + op->func_closure = closure; +#if !CYTHON_COMPILING_IN_LIMITED_API + Py_XINCREF(module); + cf->m_module = module; +#endif +#if PY_VERSION_HEX < 0x030C0000 || CYTHON_COMPILING_IN_LIMITED_API + op->func_dict = NULL; +#endif + op->func_name = NULL; + Py_INCREF(qualname); + op->func_qualname = qualname; + op->func_doc = NULL; +#if PY_VERSION_HEX < 0x030900B1 || CYTHON_COMPILING_IN_LIMITED_API + op->func_classobj = NULL; +#else + ((PyCMethodObject*)op)->mm_class = NULL; +#endif + op->func_globals = globals; + Py_INCREF(op->func_globals); + Py_XINCREF(code); + op->func_code = code; + op->defaults = NULL; + op->defaults_tuple = NULL; + op->defaults_kwdict = NULL; + op->defaults_getter = NULL; + op->func_annotations = NULL; + op->func_is_coroutine = NULL; +#if CYTHON_METH_FASTCALL + switch (ml->ml_flags & (METH_VARARGS | METH_FASTCALL | METH_NOARGS | METH_O | METH_KEYWORDS | METH_METHOD)) { + case METH_NOARGS: + __Pyx_CyFunction_func_vectorcall(op) = __Pyx_CyFunction_Vectorcall_NOARGS; + break; + case METH_O: + __Pyx_CyFunction_func_vectorcall(op) = __Pyx_CyFunction_Vectorcall_O; + break; + case METH_METHOD | METH_FASTCALL | METH_KEYWORDS: + __Pyx_CyFunction_func_vectorcall(op) = __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS_METHOD; + break; + case METH_FASTCALL | METH_KEYWORDS: + __Pyx_CyFunction_func_vectorcall(op) = __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS; + break; + case METH_VARARGS | METH_KEYWORDS: + __Pyx_CyFunction_func_vectorcall(op) = NULL; + break; + default: + PyErr_SetString(PyExc_SystemError, "Bad call flags for CyFunction"); + Py_DECREF(op); + return NULL; + } +#endif + return (PyObject *) op; +} +static int +__Pyx_CyFunction_clear(__pyx_CyFunctionObject *m) +{ + Py_CLEAR(m->func_closure); +#if CYTHON_COMPILING_IN_LIMITED_API + Py_CLEAR(m->func); +#else + Py_CLEAR(((PyCFunctionObject*)m)->m_module); +#endif +#if PY_VERSION_HEX < 0x030C0000 || CYTHON_COMPILING_IN_LIMITED_API + Py_CLEAR(m->func_dict); +#elif PY_VERSION_HEX < 0x030d0000 + _PyObject_ClearManagedDict((PyObject*)m); +#else + PyObject_ClearManagedDict((PyObject*)m); +#endif + Py_CLEAR(m->func_name); + Py_CLEAR(m->func_qualname); + Py_CLEAR(m->func_doc); + Py_CLEAR(m->func_globals); + Py_CLEAR(m->func_code); +#if !CYTHON_COMPILING_IN_LIMITED_API +#if PY_VERSION_HEX < 0x030900B1 + Py_CLEAR(__Pyx_CyFunction_GetClassObj(m)); +#else + { + PyObject *cls = (PyObject*) ((PyCMethodObject *) (m))->mm_class; + ((PyCMethodObject *) (m))->mm_class = NULL; + Py_XDECREF(cls); + } +#endif +#endif + Py_CLEAR(m->defaults_tuple); + Py_CLEAR(m->defaults_kwdict); + Py_CLEAR(m->func_annotations); + Py_CLEAR(m->func_is_coroutine); + Py_CLEAR(m->defaults); + return 0; +} +static void __Pyx__CyFunction_dealloc(__pyx_CyFunctionObject *m) +{ + if (__Pyx_CyFunction_weakreflist(m) != NULL) + PyObject_ClearWeakRefs((PyObject *) m); + __Pyx_CyFunction_clear(m); + __Pyx_PyHeapTypeObject_GC_Del(m); +} +static void __Pyx_CyFunction_dealloc(__pyx_CyFunctionObject *m) +{ + PyObject_GC_UnTrack(m); + __Pyx__CyFunction_dealloc(m); +} +static int __Pyx_CyFunction_traverse(__pyx_CyFunctionObject *m, visitproc visit, void *arg) +{ + { + int e = __Pyx_call_type_traverse((PyObject*)m, 1, visit, arg); + if (e) return e; + } + Py_VISIT(m->func_closure); +#if CYTHON_COMPILING_IN_LIMITED_API + Py_VISIT(m->func); +#else + Py_VISIT(((PyCFunctionObject*)m)->m_module); +#endif +#if PY_VERSION_HEX < 0x030C0000 || CYTHON_COMPILING_IN_LIMITED_API + Py_VISIT(m->func_dict); +#else + { + int e = +#if PY_VERSION_HEX < 0x030d0000 + _PyObject_VisitManagedDict +#else + PyObject_VisitManagedDict +#endif + ((PyObject*)m, visit, arg); + if (e != 0) return e; + } +#endif + __Pyx_VISIT_CONST(m->func_name); + __Pyx_VISIT_CONST(m->func_qualname); + Py_VISIT(m->func_doc); + Py_VISIT(m->func_globals); + __Pyx_VISIT_CONST(m->func_code); +#if !CYTHON_COMPILING_IN_LIMITED_API + Py_VISIT(__Pyx_CyFunction_GetClassObj(m)); +#endif + Py_VISIT(m->defaults_tuple); + Py_VISIT(m->defaults_kwdict); + Py_VISIT(m->func_is_coroutine); + Py_VISIT(m->defaults); + return 0; +} +static PyObject* +__Pyx_CyFunction_repr(__pyx_CyFunctionObject *op) +{ + PyObject *repr; + __Pyx_BEGIN_CRITICAL_SECTION(op); + repr = PyUnicode_FromFormat("", + op->func_qualname, (void *)op); + __Pyx_END_CRITICAL_SECTION(); + return repr; +} +static PyObject * __Pyx_CyFunction_CallMethod(PyObject *func, PyObject *self, PyObject *arg, PyObject *kw) { +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *f = ((__pyx_CyFunctionObject*)func)->func; + PyCFunction meth; + int flags; + meth = PyCFunction_GetFunction(f); + if (unlikely(!meth)) return NULL; + flags = PyCFunction_GetFlags(f); + if (unlikely(flags < 0)) return NULL; +#else + PyCFunctionObject* f = (PyCFunctionObject*)func; + PyCFunction meth = f->m_ml->ml_meth; + int flags = f->m_ml->ml_flags; +#endif + Py_ssize_t size; + switch (flags & (METH_VARARGS | METH_KEYWORDS | METH_NOARGS | METH_O)) { + case METH_VARARGS: + if (likely(kw == NULL || PyDict_Size(kw) == 0)) + return (*meth)(self, arg); + break; + case METH_VARARGS | METH_KEYWORDS: + return (*(PyCFunctionWithKeywords)(void(*)(void))meth)(self, arg, kw); + case METH_NOARGS: + if (likely(kw == NULL || PyDict_Size(kw) == 0)) { +#if CYTHON_ASSUME_SAFE_SIZE + size = PyTuple_GET_SIZE(arg); +#else + size = PyTuple_Size(arg); + if (unlikely(size < 0)) return NULL; +#endif + if (likely(size == 0)) + return (*meth)(self, NULL); + __Pyx_CyFunction_raise_argument_count_error( + (__pyx_CyFunctionObject*)func, + "takes no arguments", size); + return NULL; + } + break; + case METH_O: + if (likely(kw == NULL || PyDict_Size(kw) == 0)) { +#if CYTHON_ASSUME_SAFE_SIZE + size = PyTuple_GET_SIZE(arg); +#else + size = PyTuple_Size(arg); + if (unlikely(size < 0)) return NULL; +#endif + if (likely(size == 1)) { + PyObject *result, *arg0; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + arg0 = PyTuple_GET_ITEM(arg, 0); + #else + arg0 = __Pyx_PySequence_ITEM(arg, 0); if (unlikely(!arg0)) return NULL; + #endif + result = (*meth)(self, arg0); + #if !(CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS) + Py_DECREF(arg0); + #endif + return result; + } + __Pyx_CyFunction_raise_argument_count_error( + (__pyx_CyFunctionObject*)func, + "takes exactly one argument", size); + return NULL; + } + break; + default: + PyErr_SetString(PyExc_SystemError, "Bad call flags for CyFunction"); + return NULL; + } + __Pyx_CyFunction_raise_type_error( + (__pyx_CyFunctionObject*)func, "takes no keyword arguments"); + return NULL; +} +static CYTHON_INLINE PyObject *__Pyx_CyFunction_Call(PyObject *func, PyObject *arg, PyObject *kw) { + PyObject *self, *result; +#if CYTHON_COMPILING_IN_LIMITED_API + self = PyCFunction_GetSelf(((__pyx_CyFunctionObject*)func)->func); + if (unlikely(!self) && PyErr_Occurred()) return NULL; +#else + self = ((PyCFunctionObject*)func)->m_self; +#endif + result = __Pyx_CyFunction_CallMethod(func, self, arg, kw); + return result; +} +static PyObject *__Pyx_CyFunction_CallAsMethod(PyObject *func, PyObject *args, PyObject *kw) { + PyObject *result; + __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *) func; +#if CYTHON_METH_FASTCALL && CYTHON_VECTORCALL + __pyx_vectorcallfunc vc = __Pyx_CyFunction_func_vectorcall(cyfunc); + if (vc) { +#if CYTHON_ASSUME_SAFE_MACROS && CYTHON_ASSUME_SAFE_SIZE + return __Pyx_PyVectorcall_FastCallDict(func, vc, &PyTuple_GET_ITEM(args, 0), (size_t)PyTuple_GET_SIZE(args), kw); +#else + (void) &__Pyx_PyVectorcall_FastCallDict; + return PyVectorcall_Call(func, args, kw); +#endif + } +#endif + if ((cyfunc->flags & __Pyx_CYFUNCTION_CCLASS) && !(cyfunc->flags & __Pyx_CYFUNCTION_STATICMETHOD)) { + Py_ssize_t argc; + PyObject *new_args; + PyObject *self; +#if CYTHON_ASSUME_SAFE_SIZE + argc = PyTuple_GET_SIZE(args); +#else + argc = PyTuple_Size(args); + if (unlikely(argc < 0)) return NULL; +#endif + new_args = PyTuple_GetSlice(args, 1, argc); + if (unlikely(!new_args)) + return NULL; + self = PyTuple_GetItem(args, 0); + if (unlikely(!self)) { + Py_DECREF(new_args); + PyErr_Format(PyExc_TypeError, + "unbound method %.200S() needs an argument", + cyfunc->func_qualname); + return NULL; + } + result = __Pyx_CyFunction_CallMethod(func, self, new_args, kw); + Py_DECREF(new_args); + } else { + result = __Pyx_CyFunction_Call(func, args, kw); + } + return result; +} +#if CYTHON_METH_FASTCALL && CYTHON_VECTORCALL +static CYTHON_INLINE int __Pyx_CyFunction_Vectorcall_CheckArgs(__pyx_CyFunctionObject *cyfunc, Py_ssize_t nargs, PyObject *kwnames) +{ + int ret = 0; + if ((cyfunc->flags & __Pyx_CYFUNCTION_CCLASS) && !(cyfunc->flags & __Pyx_CYFUNCTION_STATICMETHOD)) { + if (unlikely(nargs < 1)) { + __Pyx_CyFunction_raise_type_error( + cyfunc, "needs an argument"); + return -1; + } + ret = 1; + } + if (unlikely(kwnames) && unlikely(__Pyx_PyTuple_GET_SIZE(kwnames))) { + __Pyx_CyFunction_raise_type_error( + cyfunc, "takes no keyword arguments"); + return -1; + } + return ret; +} +static PyObject * __Pyx_CyFunction_Vectorcall_NOARGS(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames) +{ + __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *)func; + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); + PyObject *self; +#if CYTHON_COMPILING_IN_LIMITED_API + PyCFunction meth = PyCFunction_GetFunction(cyfunc->func); + if (unlikely(!meth)) return NULL; +#else + PyCFunction meth = ((PyCFunctionObject*)cyfunc)->m_ml->ml_meth; +#endif + switch (__Pyx_CyFunction_Vectorcall_CheckArgs(cyfunc, nargs, kwnames)) { + case 1: + self = args[0]; + args += 1; + nargs -= 1; + break; + case 0: +#if CYTHON_COMPILING_IN_LIMITED_API + self = PyCFunction_GetSelf(((__pyx_CyFunctionObject*)cyfunc)->func); + if (unlikely(!self) && PyErr_Occurred()) return NULL; +#else + self = ((PyCFunctionObject*)cyfunc)->m_self; +#endif + break; + default: + return NULL; + } + if (unlikely(nargs != 0)) { + __Pyx_CyFunction_raise_argument_count_error( + cyfunc, "takes no arguments", nargs); + return NULL; + } + return meth(self, NULL); +} +static PyObject * __Pyx_CyFunction_Vectorcall_O(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames) +{ + __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *)func; + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); + PyObject *self; +#if CYTHON_COMPILING_IN_LIMITED_API + PyCFunction meth = PyCFunction_GetFunction(cyfunc->func); + if (unlikely(!meth)) return NULL; +#else + PyCFunction meth = ((PyCFunctionObject*)cyfunc)->m_ml->ml_meth; +#endif + switch (__Pyx_CyFunction_Vectorcall_CheckArgs(cyfunc, nargs, kwnames)) { + case 1: + self = args[0]; + args += 1; + nargs -= 1; + break; + case 0: +#if CYTHON_COMPILING_IN_LIMITED_API + self = PyCFunction_GetSelf(((__pyx_CyFunctionObject*)cyfunc)->func); + if (unlikely(!self) && PyErr_Occurred()) return NULL; +#else + self = ((PyCFunctionObject*)cyfunc)->m_self; +#endif + break; + default: + return NULL; + } + if (unlikely(nargs != 1)) { + __Pyx_CyFunction_raise_argument_count_error( + cyfunc, "takes exactly one argument", nargs); + return NULL; + } + return meth(self, args[0]); +} +static PyObject * __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames) +{ + __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *)func; + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); + PyObject *self; +#if CYTHON_COMPILING_IN_LIMITED_API + PyCFunction meth = PyCFunction_GetFunction(cyfunc->func); + if (unlikely(!meth)) return NULL; +#else + PyCFunction meth = ((PyCFunctionObject*)cyfunc)->m_ml->ml_meth; +#endif + switch (__Pyx_CyFunction_Vectorcall_CheckArgs(cyfunc, nargs, NULL)) { + case 1: + self = args[0]; + args += 1; + nargs -= 1; + break; + case 0: +#if CYTHON_COMPILING_IN_LIMITED_API + self = PyCFunction_GetSelf(((__pyx_CyFunctionObject*)cyfunc)->func); + if (unlikely(!self) && PyErr_Occurred()) return NULL; +#else + self = ((PyCFunctionObject*)cyfunc)->m_self; +#endif + break; + default: + return NULL; + } + return ((__Pyx_PyCFunctionFastWithKeywords)(void(*)(void))meth)(self, args, nargs, kwnames); +} +static PyObject * __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS_METHOD(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames) +{ + __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *)func; + PyTypeObject *cls = (PyTypeObject *) __Pyx_CyFunction_GetClassObj(cyfunc); + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); + PyObject *self; +#if CYTHON_COMPILING_IN_LIMITED_API + PyCFunction meth = PyCFunction_GetFunction(cyfunc->func); + if (unlikely(!meth)) return NULL; +#else + PyCFunction meth = ((PyCFunctionObject*)cyfunc)->m_ml->ml_meth; +#endif + switch (__Pyx_CyFunction_Vectorcall_CheckArgs(cyfunc, nargs, NULL)) { + case 1: + self = args[0]; + args += 1; + nargs -= 1; + break; + case 0: +#if CYTHON_COMPILING_IN_LIMITED_API + self = PyCFunction_GetSelf(((__pyx_CyFunctionObject*)cyfunc)->func); + if (unlikely(!self) && PyErr_Occurred()) return NULL; +#else + self = ((PyCFunctionObject*)cyfunc)->m_self; +#endif + break; + default: + return NULL; + } + #if PY_VERSION_HEX < 0x030e00A6 + size_t nargs_value = (size_t) nargs; + #else + Py_ssize_t nargs_value = nargs; + #endif + return ((__Pyx_PyCMethod)(void(*)(void))meth)(self, cls, args, nargs_value, kwnames); +} +#endif +static PyType_Slot __pyx_CyFunctionType_slots[] = { + {Py_tp_dealloc, (void *)__Pyx_CyFunction_dealloc}, + {Py_tp_repr, (void *)__Pyx_CyFunction_repr}, + {Py_tp_call, (void *)__Pyx_CyFunction_CallAsMethod}, + {Py_tp_traverse, (void *)__Pyx_CyFunction_traverse}, + {Py_tp_clear, (void *)__Pyx_CyFunction_clear}, + {Py_tp_methods, (void *)__pyx_CyFunction_methods}, + {Py_tp_members, (void *)__pyx_CyFunction_members}, + {Py_tp_getset, (void *)__pyx_CyFunction_getsets}, + {Py_tp_descr_get, (void *)__Pyx_PyMethod_New}, + {0, 0}, +}; +static PyType_Spec __pyx_CyFunctionType_spec = { + __PYX_TYPE_MODULE_PREFIX "cython_function_or_method", + sizeof(__pyx_CyFunctionObject), + 0, +#ifdef Py_TPFLAGS_METHOD_DESCRIPTOR + Py_TPFLAGS_METHOD_DESCRIPTOR | +#endif +#if CYTHON_METH_FASTCALL +#if defined(Py_TPFLAGS_HAVE_VECTORCALL) + Py_TPFLAGS_HAVE_VECTORCALL | +#elif defined(_Py_TPFLAGS_HAVE_VECTORCALL) + _Py_TPFLAGS_HAVE_VECTORCALL | +#endif +#endif // CYTHON_METH_FASTCALL +#if PY_VERSION_HEX >= 0x030C0000 && !CYTHON_COMPILING_IN_LIMITED_API + Py_TPFLAGS_MANAGED_DICT | +#endif + Py_TPFLAGS_IMMUTABLETYPE | Py_TPFLAGS_DISALLOW_INSTANTIATION | + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, + __pyx_CyFunctionType_slots +}; +static int __pyx_CyFunction_init(PyObject *module) { + __pyx_mstatetype *mstate = __Pyx_PyModule_GetState(module); + mstate->__pyx_CyFunctionType = __Pyx_FetchCommonTypeFromSpec( + mstate->__pyx_CommonTypesMetaclassType, module, &__pyx_CyFunctionType_spec, NULL); + if (unlikely(mstate->__pyx_CyFunctionType == NULL)) { + return -1; + } + return 0; +} +static CYTHON_INLINE PyObject *__Pyx_CyFunction_InitDefaults(PyObject *func, PyTypeObject *defaults_type) { + __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; + m->defaults = PyObject_CallObject((PyObject*)defaults_type, NULL); // _PyObject_New(defaults_type); + if (unlikely(!m->defaults)) + return NULL; + return m->defaults; +} +static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsTuple(PyObject *func, PyObject *tuple) { + __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; + m->defaults_tuple = tuple; + Py_INCREF(tuple); +} +static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsKwDict(PyObject *func, PyObject *dict) { + __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; + m->defaults_kwdict = dict; + Py_INCREF(dict); +} +static CYTHON_INLINE void __Pyx_CyFunction_SetAnnotationsDict(PyObject *func, PyObject *dict) { + __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; + m->func_annotations = dict; + Py_INCREF(dict); +} + +/* CythonFunction */ +static PyObject *__Pyx_CyFunction_New(PyMethodDef *ml, int flags, PyObject* qualname, + PyObject *closure, PyObject *module, PyObject* globals, PyObject* code) { + PyObject *op = __Pyx_CyFunction_Init( + PyObject_GC_New(__pyx_CyFunctionObject, __pyx_mstate_global->__pyx_CyFunctionType), + ml, flags, qualname, closure, module, globals, code + ); + if (likely(op)) { + PyObject_GC_Track(op); + } + return op; +} + +/* CLineInTraceback (used by AddTraceback) */ +#if CYTHON_CLINE_IN_TRACEBACK && CYTHON_CLINE_IN_TRACEBACK_RUNTIME +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000 +#define __Pyx_PyProbablyModule_GetDict(o) __Pyx_XNewRef(PyModule_GetDict(o)) +#elif !CYTHON_COMPILING_IN_CPYTHON || CYTHON_COMPILING_IN_CPYTHON_FREETHREADING +#define __Pyx_PyProbablyModule_GetDict(o) PyObject_GenericGetDict(o, NULL); +#else +PyObject* __Pyx_PyProbablyModule_GetDict(PyObject *o) { + PyObject **dict_ptr = _PyObject_GetDictPtr(o); + return dict_ptr ? __Pyx_XNewRef(*dict_ptr) : NULL; +} +#endif +static int __Pyx_CLineForTraceback(PyThreadState *tstate, int c_line) { + PyObject *use_cline = NULL; + PyObject *ptype, *pvalue, *ptraceback; + PyObject *cython_runtime_dict; + CYTHON_MAYBE_UNUSED_VAR(tstate); + if (unlikely(!__pyx_mstate_global->__pyx_cython_runtime)) { + return c_line; + } + __Pyx_ErrFetchInState(tstate, &ptype, &pvalue, &ptraceback); + cython_runtime_dict = __Pyx_PyProbablyModule_GetDict(__pyx_mstate_global->__pyx_cython_runtime); + if (likely(cython_runtime_dict)) { + __PYX_PY_DICT_LOOKUP_IF_MODIFIED( + use_cline, cython_runtime_dict, + __Pyx_PyDict_SetDefault(cython_runtime_dict, __pyx_mstate_global->__pyx_n_u_cline_in_traceback, Py_False)) + } + if (use_cline == NULL || use_cline == Py_False || (use_cline != Py_True && PyObject_Not(use_cline) != 0)) { + c_line = 0; + } + Py_XDECREF(use_cline); + Py_XDECREF(cython_runtime_dict); + __Pyx_ErrRestoreInState(tstate, ptype, pvalue, ptraceback); + return c_line; +} +#endif + +/* CodeObjectCache (used by AddTraceback) */ +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { + int start = 0, mid = 0, end = count - 1; + if (end >= 0 && code_line > entries[end].code_line) { + return count; + } + while (start < end) { + mid = start + (end - start) / 2; + if (code_line < entries[mid].code_line) { + end = mid; + } else if (code_line > entries[mid].code_line) { + start = mid + 1; + } else { + return mid; + } + } + if (code_line <= entries[mid].code_line) { + return mid; + } else { + return mid + 1; + } +} +static __Pyx_CachedCodeObjectType *__pyx__find_code_object(struct __Pyx_CodeObjectCache *code_cache, int code_line) { + __Pyx_CachedCodeObjectType* code_object; + int pos; + if (unlikely(!code_line) || unlikely(!code_cache->entries)) { + return NULL; + } + pos = __pyx_bisect_code_objects(code_cache->entries, code_cache->count, code_line); + if (unlikely(pos >= code_cache->count) || unlikely(code_cache->entries[pos].code_line != code_line)) { + return NULL; + } + code_object = code_cache->entries[pos].code_object; + Py_INCREF(code_object); + return code_object; +} +static __Pyx_CachedCodeObjectType *__pyx_find_code_object(int code_line) { +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING && !CYTHON_ATOMICS + (void)__pyx__find_code_object; + return NULL; // Most implementation should have atomics. But otherwise, don't make it thread-safe, just miss. +#else + struct __Pyx_CodeObjectCache *code_cache = &__pyx_mstate_global->__pyx_code_cache; +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + __pyx_nonatomic_int_type old_count = __pyx_atomic_incr_acq_rel(&code_cache->accessor_count); + if (old_count < 0) { + __pyx_atomic_decr_acq_rel(&code_cache->accessor_count); + return NULL; + } +#endif + __Pyx_CachedCodeObjectType *result = __pyx__find_code_object(code_cache, code_line); +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + __pyx_atomic_decr_acq_rel(&code_cache->accessor_count); +#endif + return result; +#endif +} +static void __pyx__insert_code_object(struct __Pyx_CodeObjectCache *code_cache, int code_line, __Pyx_CachedCodeObjectType* code_object) +{ + int pos, i; + __Pyx_CodeObjectCacheEntry* entries = code_cache->entries; + if (unlikely(!code_line)) { + return; + } + if (unlikely(!entries)) { + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); + if (likely(entries)) { + code_cache->entries = entries; + code_cache->max_count = 64; + code_cache->count = 1; + entries[0].code_line = code_line; + entries[0].code_object = code_object; + Py_INCREF(code_object); + } + return; + } + pos = __pyx_bisect_code_objects(code_cache->entries, code_cache->count, code_line); + if ((pos < code_cache->count) && unlikely(code_cache->entries[pos].code_line == code_line)) { + __Pyx_CachedCodeObjectType* tmp = entries[pos].code_object; + entries[pos].code_object = code_object; + Py_INCREF(code_object); + Py_DECREF(tmp); + return; + } + if (code_cache->count == code_cache->max_count) { + int new_max = code_cache->max_count + 64; + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( + code_cache->entries, ((size_t)new_max) * sizeof(__Pyx_CodeObjectCacheEntry)); + if (unlikely(!entries)) { + return; + } + code_cache->entries = entries; + code_cache->max_count = new_max; + } + for (i=code_cache->count; i>pos; i--) { + entries[i] = entries[i-1]; + } + entries[pos].code_line = code_line; + entries[pos].code_object = code_object; + code_cache->count++; + Py_INCREF(code_object); +} +static void __pyx_insert_code_object(int code_line, __Pyx_CachedCodeObjectType* code_object) { +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING && !CYTHON_ATOMICS + (void)__pyx__insert_code_object; + return; // Most implementation should have atomics. But otherwise, don't make it thread-safe, just fail. +#else + struct __Pyx_CodeObjectCache *code_cache = &__pyx_mstate_global->__pyx_code_cache; +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + __pyx_nonatomic_int_type expected = 0; + if (!__pyx_atomic_int_cmp_exchange(&code_cache->accessor_count, &expected, INT_MIN)) { + return; + } +#endif + __pyx__insert_code_object(code_cache, code_line, code_object); +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + __pyx_atomic_sub(&code_cache->accessor_count, INT_MIN); +#endif +#endif +} + +/* AddTraceback */ +#include "compile.h" +#include "frameobject.h" +#include "traceback.h" +#if PY_VERSION_HEX >= 0x030b00a6 && !CYTHON_COMPILING_IN_LIMITED_API && !defined(PYPY_VERSION) + #ifndef Py_BUILD_CORE + #define Py_BUILD_CORE 1 + #endif + #include "internal/pycore_frame.h" +#endif +#if CYTHON_COMPILING_IN_LIMITED_API +static PyObject *__Pyx_PyCode_Replace_For_AddTraceback(PyObject *code, PyObject *scratch_dict, + PyObject *firstlineno, PyObject *name) { + PyObject *replace = NULL; + if (unlikely(PyDict_SetItemString(scratch_dict, "co_firstlineno", firstlineno))) return NULL; + if (unlikely(PyDict_SetItemString(scratch_dict, "co_name", name))) return NULL; + replace = PyObject_GetAttrString(code, "replace"); + if (likely(replace)) { + PyObject *result = PyObject_Call(replace, __pyx_mstate_global->__pyx_empty_tuple, scratch_dict); + Py_DECREF(replace); + return result; + } + PyErr_Clear(); + return NULL; +} +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename) { + PyObject *code_object = NULL, *py_py_line = NULL, *py_funcname = NULL, *dict = NULL; + PyObject *replace = NULL, *getframe = NULL, *frame = NULL; + PyObject *exc_type, *exc_value, *exc_traceback; + int success = 0; + if (c_line) { + c_line = __Pyx_CLineForTraceback(__Pyx_PyThreadState_Current, c_line); + } + PyErr_Fetch(&exc_type, &exc_value, &exc_traceback); + code_object = __pyx_find_code_object(c_line ? -c_line : py_line); + if (!code_object) { + code_object = Py_CompileString("_getframe()", filename, Py_eval_input); + if (unlikely(!code_object)) goto bad; + py_py_line = PyLong_FromLong(py_line); + if (unlikely(!py_py_line)) goto bad; + if (c_line) { + py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + } else { + py_funcname = PyUnicode_FromString(funcname); + } + if (unlikely(!py_funcname)) goto bad; + dict = PyDict_New(); + if (unlikely(!dict)) goto bad; + { + PyObject *old_code_object = code_object; + code_object = __Pyx_PyCode_Replace_For_AddTraceback(code_object, dict, py_py_line, py_funcname); + Py_DECREF(old_code_object); + } + if (unlikely(!code_object)) goto bad; + __pyx_insert_code_object(c_line ? -c_line : py_line, code_object); + } else { + dict = PyDict_New(); + } + getframe = PySys_GetObject("_getframe"); + if (unlikely(!getframe)) goto bad; + if (unlikely(PyDict_SetItemString(dict, "_getframe", getframe))) goto bad; + frame = PyEval_EvalCode(code_object, dict, dict); + if (unlikely(!frame) || frame == Py_None) goto bad; + success = 1; + bad: + PyErr_Restore(exc_type, exc_value, exc_traceback); + Py_XDECREF(code_object); + Py_XDECREF(py_py_line); + Py_XDECREF(py_funcname); + Py_XDECREF(dict); + Py_XDECREF(replace); + if (success) { + PyTraceBack_Here( + (struct _frame*)frame); + } + Py_XDECREF(frame); +} +#else +static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( + const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = NULL; + PyObject *py_funcname = NULL; + if (c_line) { + py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + if (!py_funcname) goto bad; + funcname = PyUnicode_AsUTF8(py_funcname); + if (!funcname) goto bad; + } + py_code = PyCode_NewEmpty(filename, funcname, py_line); + Py_XDECREF(py_funcname); + return py_code; +bad: + Py_XDECREF(py_funcname); + return NULL; +} +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyFrameObject *py_frame = 0; + PyThreadState *tstate = __Pyx_PyThreadState_Current; + PyObject *ptype, *pvalue, *ptraceback; + if (c_line) { + c_line = __Pyx_CLineForTraceback(tstate, c_line); + } + py_code = __pyx_find_code_object(c_line ? -c_line : py_line); + if (!py_code) { + __Pyx_ErrFetchInState(tstate, &ptype, &pvalue, &ptraceback); + py_code = __Pyx_CreateCodeObjectForTraceback( + funcname, c_line, py_line, filename); + if (!py_code) { + /* If the code object creation fails, then we should clear the + fetched exception references and propagate the new exception */ + Py_XDECREF(ptype); + Py_XDECREF(pvalue); + Py_XDECREF(ptraceback); + goto bad; + } + __Pyx_ErrRestoreInState(tstate, ptype, pvalue, ptraceback); + __pyx_insert_code_object(c_line ? -c_line : py_line, py_code); + } + py_frame = PyFrame_New( + tstate, /*PyThreadState *tstate,*/ + py_code, /*PyCodeObject *code,*/ + __pyx_mstate_global->__pyx_d, /*PyObject *globals,*/ + 0 /*PyObject *locals*/ + ); + if (!py_frame) goto bad; + __Pyx_PyFrame_SetLineNumber(py_frame, py_line); + PyTraceBack_Here(py_frame); +bad: + Py_XDECREF(py_code); + Py_XDECREF(py_frame); +} +#endif + +/* CheckUnpickleChecksum */ +static void __Pyx_RaiseUnpickleChecksumError(long checksum, long checksum1, long checksum2, long checksum3, const char *members) { + PyObject *pickle_module = PyImport_ImportModule("pickle"); + if (unlikely(!pickle_module)) return; + PyObject *pickle_error = PyObject_GetAttrString(pickle_module, "PickleError"); + Py_DECREF(pickle_module); + if (unlikely(!pickle_error)) return; + if (checksum2 == checksum1) { + PyErr_Format(pickle_error, "Incompatible checksums (0x%x vs (0x%x) = (%s))", + checksum, checksum1, members); + } else if (checksum3 == checksum2) { + PyErr_Format(pickle_error, "Incompatible checksums (0x%x vs (0x%x, 0x%x) = (%s))", + checksum, checksum1, checksum2, members); + } else { + PyErr_Format(pickle_error, "Incompatible checksums (0x%x vs (0x%x, 0x%x, 0x%x) = (%s))", + checksum, checksum1, checksum2, checksum3, members); + } + Py_DECREF(pickle_error); +} +static int __Pyx_CheckUnpickleChecksum(long checksum, long checksum1, long checksum2, long checksum3, const char *members) { + int found = 0; + found |= checksum1 == checksum; + found |= checksum2 == checksum; + found |= checksum3 == checksum; + if (likely(found)) + return 0; + __Pyx_RaiseUnpickleChecksumError(checksum, checksum1, checksum2, checksum3, members); + return -1; +} + +/* CIntFromPyVerify */ +#define __PYX_VERIFY_RETURN_INT(target_type, func_type, func_value)\ + __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 0) +#define __PYX_VERIFY_RETURN_INT_EXC(target_type, func_type, func_value)\ + __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 1) +#define __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, exc)\ + {\ + func_type value = func_value;\ + if (sizeof(target_type) < sizeof(func_type)) {\ + if (unlikely(value != (func_type) (target_type) value)) {\ + func_type zero = 0;\ + if (exc && unlikely(value == (func_type)-1 && PyErr_Occurred()))\ + return (target_type) -1;\ + if (is_unsigned && unlikely(value < zero))\ + goto raise_neg_overflow;\ + else\ + goto raise_overflow;\ + }\ + }\ + return (target_type) value;\ + } + +/* CIntFromPy */ +static CYTHON_INLINE long __Pyx_PyLong_As_long(PyObject *x) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const long neg_one = (long) -1, const_zero = (long) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (unlikely(!PyLong_Check(x))) { + long val; + PyObject *tmp = __Pyx_PyNumber_Long(x); + if (!tmp) return (long) -1; + val = __Pyx_PyLong_As_long(tmp); + Py_DECREF(tmp); + return val; + } + if (is_unsigned) { +#if CYTHON_USE_PYLONG_INTERNALS + if (unlikely(__Pyx_PyLong_IsNeg(x))) { + goto raise_neg_overflow; + } else if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(long, __Pyx_compact_upylong, __Pyx_PyLong_CompactValueUnsigned(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_DigitCount(x)) { + case 2: + if ((8 * sizeof(long) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) >= 2 * PyLong_SHIFT)) { + return (long) (((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); + } + } + break; + case 3: + if ((8 * sizeof(long) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) >= 3 * PyLong_SHIFT)) { + return (long) (((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); + } + } + break; + case 4: + if ((8 * sizeof(long) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) >= 4 * PyLong_SHIFT)) { + return (long) (((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); + } + } + break; + } + } +#endif +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030C00A7 + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } +#else + { + int result = PyObject_RichCompareBool(x, Py_False, Py_LT); + if (unlikely(result < 0)) + return (long) -1; + if (unlikely(result == 1)) + goto raise_neg_overflow; + } +#endif + if ((sizeof(long) <= sizeof(unsigned long))) { + __PYX_VERIFY_RETURN_INT_EXC(long, unsigned long, PyLong_AsUnsignedLong(x)) + } else if ((sizeof(long) <= sizeof(unsigned PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(long, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) + } + } else { +#if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(long, __Pyx_compact_pylong, __Pyx_PyLong_CompactValue(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_SignedDigitCount(x)) { + case -2: + if ((8 * sizeof(long) - 1 > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 2 * PyLong_SHIFT)) { + return (long) (((long)-1)*(((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case 2: + if ((8 * sizeof(long) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 2 * PyLong_SHIFT)) { + return (long) ((((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case -3: + if ((8 * sizeof(long) - 1 > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 3 * PyLong_SHIFT)) { + return (long) (((long)-1)*(((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case 3: + if ((8 * sizeof(long) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 3 * PyLong_SHIFT)) { + return (long) ((((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case -4: + if ((8 * sizeof(long) - 1 > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 4 * PyLong_SHIFT)) { + return (long) (((long)-1)*(((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case 4: + if ((8 * sizeof(long) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 4 * PyLong_SHIFT)) { + return (long) ((((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + } + } +#endif + if ((sizeof(long) <= sizeof(long))) { + __PYX_VERIFY_RETURN_INT_EXC(long, long, PyLong_AsLong(x)) + } else if ((sizeof(long) <= sizeof(PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(long, PY_LONG_LONG, PyLong_AsLongLong(x)) + } + } + { + long val; + int ret = -1; +#if PY_VERSION_HEX >= 0x030d00A6 && !CYTHON_COMPILING_IN_LIMITED_API + Py_ssize_t bytes_copied = PyLong_AsNativeBytes( + x, &val, sizeof(val), Py_ASNATIVEBYTES_NATIVE_ENDIAN | (is_unsigned ? Py_ASNATIVEBYTES_UNSIGNED_BUFFER | Py_ASNATIVEBYTES_REJECT_NEGATIVE : 0)); + if (unlikely(bytes_copied == -1)) { + } else if (unlikely(bytes_copied > (Py_ssize_t) sizeof(val))) { + goto raise_overflow; + } else { + ret = 0; + } +#elif PY_VERSION_HEX < 0x030d0000 && !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API) || defined(_PyLong_AsByteArray) + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + ret = _PyLong_AsByteArray((PyLongObject *)x, + bytes, sizeof(val), + is_little, !is_unsigned); +#else + PyObject *v; + PyObject *stepval = NULL, *mask = NULL, *shift = NULL; + int bits, remaining_bits, is_negative = 0; + int chunk_size = (sizeof(long) < 8) ? 30 : 62; + if (likely(PyLong_CheckExact(x))) { + v = __Pyx_NewRef(x); + } else { + v = PyNumber_Long(x); + if (unlikely(!v)) return (long) -1; + assert(PyLong_CheckExact(v)); + } + { + int result = PyObject_RichCompareBool(v, Py_False, Py_LT); + if (unlikely(result < 0)) { + Py_DECREF(v); + return (long) -1; + } + is_negative = result == 1; + } + if (is_unsigned && unlikely(is_negative)) { + Py_DECREF(v); + goto raise_neg_overflow; + } else if (is_negative) { + stepval = PyNumber_Invert(v); + Py_DECREF(v); + if (unlikely(!stepval)) + return (long) -1; + } else { + stepval = v; + } + v = NULL; + val = (long) 0; + mask = PyLong_FromLong((1L << chunk_size) - 1); if (unlikely(!mask)) goto done; + shift = PyLong_FromLong(chunk_size); if (unlikely(!shift)) goto done; + for (bits = 0; bits < (int) sizeof(long) * 8 - chunk_size; bits += chunk_size) { + PyObject *tmp, *digit; + long idigit; + digit = PyNumber_And(stepval, mask); + if (unlikely(!digit)) goto done; + idigit = PyLong_AsLong(digit); + Py_DECREF(digit); + if (unlikely(idigit < 0)) goto done; + val |= ((long) idigit) << bits; + tmp = PyNumber_Rshift(stepval, shift); + if (unlikely(!tmp)) goto done; + Py_DECREF(stepval); stepval = tmp; + } + Py_DECREF(shift); shift = NULL; + Py_DECREF(mask); mask = NULL; + { + long idigit = PyLong_AsLong(stepval); + if (unlikely(idigit < 0)) goto done; + remaining_bits = ((int) sizeof(long) * 8) - bits - (is_unsigned ? 0 : 1); + if (unlikely(idigit >= (1L << remaining_bits))) + goto raise_overflow; + val |= ((long) idigit) << bits; + } + if (!is_unsigned) { + if (unlikely(val & (((long) 1) << (sizeof(long) * 8 - 1)))) + goto raise_overflow; + if (is_negative) + val = ~val; + } + ret = 0; + done: + Py_XDECREF(shift); + Py_XDECREF(mask); + Py_XDECREF(stepval); +#endif + if (unlikely(ret)) + return (long) -1; + return val; + } +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to long"); + return (long) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to long"); + return (long) -1; +} + +/* CIntToPy */ +static CYTHON_INLINE PyObject* __Pyx_PyLong_From___pyx_anon_enum(int value) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const int neg_one = (int) -1, const_zero = (int) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(int) < sizeof(long)) { + return PyLong_FromLong((long) value); + } else if (sizeof(int) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); +#if !CYTHON_COMPILING_IN_PYPY + } else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) { + return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); +#endif + } + } else { + if (sizeof(int) <= sizeof(long)) { + return PyLong_FromLong((long) value); + } else if (sizeof(int) <= sizeof(PY_LONG_LONG)) { + return PyLong_FromLongLong((PY_LONG_LONG) value); + } + } + { + unsigned char *bytes = (unsigned char *)&value; +#if !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d00A4 + if (is_unsigned) { + return PyLong_FromUnsignedNativeBytes(bytes, sizeof(value), -1); + } else { + return PyLong_FromNativeBytes(bytes, sizeof(value), -1); + } +#elif !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030d0000 + int one = 1; int little = (int)*(unsigned char *)&one; + return _PyLong_FromByteArray(bytes, sizeof(int), + little, !is_unsigned); +#else + int one = 1; int little = (int)*(unsigned char *)&one; + PyObject *from_bytes, *result = NULL, *kwds = NULL; + PyObject *py_bytes = NULL, *order_str = NULL; + from_bytes = PyObject_GetAttrString((PyObject*)&PyLong_Type, "from_bytes"); + if (!from_bytes) return NULL; + py_bytes = PyBytes_FromStringAndSize((char*)bytes, sizeof(int)); + if (!py_bytes) goto limited_bad; + order_str = PyUnicode_FromString(little ? "little" : "big"); + if (!order_str) goto limited_bad; + { + PyObject *args[3+(CYTHON_VECTORCALL ? 1 : 0)] = { NULL, py_bytes, order_str }; + if (!is_unsigned) { + kwds = __Pyx_MakeVectorcallBuilderKwds(1); + if (!kwds) goto limited_bad; + if (__Pyx_VectorcallBuilder_AddArgStr("signed", __Pyx_NewRef(Py_True), kwds, args+3, 0) < 0) goto limited_bad; + } + result = __Pyx_Object_Vectorcall_CallFromBuilder(from_bytes, args+1, 2 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET, kwds); + } + limited_bad: + Py_XDECREF(kwds); + Py_XDECREF(order_str); + Py_XDECREF(py_bytes); + Py_XDECREF(from_bytes); + return result; +#endif + } +} + +/* CIntFromPy */ +static CYTHON_INLINE int __Pyx_PyLong_As_int(PyObject *x) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const int neg_one = (int) -1, const_zero = (int) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (unlikely(!PyLong_Check(x))) { + int val; + PyObject *tmp = __Pyx_PyNumber_Long(x); + if (!tmp) return (int) -1; + val = __Pyx_PyLong_As_int(tmp); + Py_DECREF(tmp); + return val; + } + if (is_unsigned) { +#if CYTHON_USE_PYLONG_INTERNALS + if (unlikely(__Pyx_PyLong_IsNeg(x))) { + goto raise_neg_overflow; + } else if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(int, __Pyx_compact_upylong, __Pyx_PyLong_CompactValueUnsigned(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_DigitCount(x)) { + case 2: + if ((8 * sizeof(int) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) >= 2 * PyLong_SHIFT)) { + return (int) (((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); + } + } + break; + case 3: + if ((8 * sizeof(int) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) >= 3 * PyLong_SHIFT)) { + return (int) (((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); + } + } + break; + case 4: + if ((8 * sizeof(int) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) >= 4 * PyLong_SHIFT)) { + return (int) (((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); + } + } + break; + } + } +#endif +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030C00A7 + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } +#else + { + int result = PyObject_RichCompareBool(x, Py_False, Py_LT); + if (unlikely(result < 0)) + return (int) -1; + if (unlikely(result == 1)) + goto raise_neg_overflow; + } +#endif + if ((sizeof(int) <= sizeof(unsigned long))) { + __PYX_VERIFY_RETURN_INT_EXC(int, unsigned long, PyLong_AsUnsignedLong(x)) + } else if ((sizeof(int) <= sizeof(unsigned PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(int, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) + } + } else { +#if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(int, __Pyx_compact_pylong, __Pyx_PyLong_CompactValue(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_SignedDigitCount(x)) { + case -2: + if ((8 * sizeof(int) - 1 > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 2 * PyLong_SHIFT)) { + return (int) (((int)-1)*(((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case 2: + if ((8 * sizeof(int) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 2 * PyLong_SHIFT)) { + return (int) ((((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case -3: + if ((8 * sizeof(int) - 1 > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 3 * PyLong_SHIFT)) { + return (int) (((int)-1)*(((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case 3: + if ((8 * sizeof(int) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 3 * PyLong_SHIFT)) { + return (int) ((((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case -4: + if ((8 * sizeof(int) - 1 > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 4 * PyLong_SHIFT)) { + return (int) (((int)-1)*(((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case 4: + if ((8 * sizeof(int) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 4 * PyLong_SHIFT)) { + return (int) ((((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + } + } +#endif + if ((sizeof(int) <= sizeof(long))) { + __PYX_VERIFY_RETURN_INT_EXC(int, long, PyLong_AsLong(x)) + } else if ((sizeof(int) <= sizeof(PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(int, PY_LONG_LONG, PyLong_AsLongLong(x)) + } + } + { + int val; + int ret = -1; +#if PY_VERSION_HEX >= 0x030d00A6 && !CYTHON_COMPILING_IN_LIMITED_API + Py_ssize_t bytes_copied = PyLong_AsNativeBytes( + x, &val, sizeof(val), Py_ASNATIVEBYTES_NATIVE_ENDIAN | (is_unsigned ? Py_ASNATIVEBYTES_UNSIGNED_BUFFER | Py_ASNATIVEBYTES_REJECT_NEGATIVE : 0)); + if (unlikely(bytes_copied == -1)) { + } else if (unlikely(bytes_copied > (Py_ssize_t) sizeof(val))) { + goto raise_overflow; + } else { + ret = 0; + } +#elif PY_VERSION_HEX < 0x030d0000 && !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API) || defined(_PyLong_AsByteArray) + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + ret = _PyLong_AsByteArray((PyLongObject *)x, + bytes, sizeof(val), + is_little, !is_unsigned); +#else + PyObject *v; + PyObject *stepval = NULL, *mask = NULL, *shift = NULL; + int bits, remaining_bits, is_negative = 0; + int chunk_size = (sizeof(long) < 8) ? 30 : 62; + if (likely(PyLong_CheckExact(x))) { + v = __Pyx_NewRef(x); + } else { + v = PyNumber_Long(x); + if (unlikely(!v)) return (int) -1; + assert(PyLong_CheckExact(v)); + } + { + int result = PyObject_RichCompareBool(v, Py_False, Py_LT); + if (unlikely(result < 0)) { + Py_DECREF(v); + return (int) -1; + } + is_negative = result == 1; + } + if (is_unsigned && unlikely(is_negative)) { + Py_DECREF(v); + goto raise_neg_overflow; + } else if (is_negative) { + stepval = PyNumber_Invert(v); + Py_DECREF(v); + if (unlikely(!stepval)) + return (int) -1; + } else { + stepval = v; + } + v = NULL; + val = (int) 0; + mask = PyLong_FromLong((1L << chunk_size) - 1); if (unlikely(!mask)) goto done; + shift = PyLong_FromLong(chunk_size); if (unlikely(!shift)) goto done; + for (bits = 0; bits < (int) sizeof(int) * 8 - chunk_size; bits += chunk_size) { + PyObject *tmp, *digit; + long idigit; + digit = PyNumber_And(stepval, mask); + if (unlikely(!digit)) goto done; + idigit = PyLong_AsLong(digit); + Py_DECREF(digit); + if (unlikely(idigit < 0)) goto done; + val |= ((int) idigit) << bits; + tmp = PyNumber_Rshift(stepval, shift); + if (unlikely(!tmp)) goto done; + Py_DECREF(stepval); stepval = tmp; + } + Py_DECREF(shift); shift = NULL; + Py_DECREF(mask); mask = NULL; + { + long idigit = PyLong_AsLong(stepval); + if (unlikely(idigit < 0)) goto done; + remaining_bits = ((int) sizeof(int) * 8) - bits - (is_unsigned ? 0 : 1); + if (unlikely(idigit >= (1L << remaining_bits))) + goto raise_overflow; + val |= ((int) idigit) << bits; + } + if (!is_unsigned) { + if (unlikely(val & (((int) 1) << (sizeof(int) * 8 - 1)))) + goto raise_overflow; + if (is_negative) + val = ~val; + } + ret = 0; + done: + Py_XDECREF(shift); + Py_XDECREF(mask); + Py_XDECREF(stepval); +#endif + if (unlikely(ret)) + return (int) -1; + return val; + } +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to int"); + return (int) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to int"); + return (int) -1; +} + +/* CIntToPy */ +static CYTHON_INLINE PyObject* __Pyx_PyLong_From_long(long value) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const long neg_one = (long) -1, const_zero = (long) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(long) < sizeof(long)) { + return PyLong_FromLong((long) value); + } else if (sizeof(long) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); +#if !CYTHON_COMPILING_IN_PYPY + } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { + return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); +#endif + } + } else { + if (sizeof(long) <= sizeof(long)) { + return PyLong_FromLong((long) value); + } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { + return PyLong_FromLongLong((PY_LONG_LONG) value); + } + } + { + unsigned char *bytes = (unsigned char *)&value; +#if !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d00A4 + if (is_unsigned) { + return PyLong_FromUnsignedNativeBytes(bytes, sizeof(value), -1); + } else { + return PyLong_FromNativeBytes(bytes, sizeof(value), -1); + } +#elif !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030d0000 + int one = 1; int little = (int)*(unsigned char *)&one; + return _PyLong_FromByteArray(bytes, sizeof(long), + little, !is_unsigned); +#else + int one = 1; int little = (int)*(unsigned char *)&one; + PyObject *from_bytes, *result = NULL, *kwds = NULL; + PyObject *py_bytes = NULL, *order_str = NULL; + from_bytes = PyObject_GetAttrString((PyObject*)&PyLong_Type, "from_bytes"); + if (!from_bytes) return NULL; + py_bytes = PyBytes_FromStringAndSize((char*)bytes, sizeof(long)); + if (!py_bytes) goto limited_bad; + order_str = PyUnicode_FromString(little ? "little" : "big"); + if (!order_str) goto limited_bad; + { + PyObject *args[3+(CYTHON_VECTORCALL ? 1 : 0)] = { NULL, py_bytes, order_str }; + if (!is_unsigned) { + kwds = __Pyx_MakeVectorcallBuilderKwds(1); + if (!kwds) goto limited_bad; + if (__Pyx_VectorcallBuilder_AddArgStr("signed", __Pyx_NewRef(Py_True), kwds, args+3, 0) < 0) goto limited_bad; + } + result = __Pyx_Object_Vectorcall_CallFromBuilder(from_bytes, args+1, 2 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET, kwds); + } + limited_bad: + Py_XDECREF(kwds); + Py_XDECREF(order_str); + Py_XDECREF(py_bytes); + Py_XDECREF(from_bytes); + return result; +#endif + } +} + +/* PyObjectCall2Args */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call2Args(PyObject* function, PyObject* arg1, PyObject* arg2) { + PyObject *args[3] = {NULL, arg1, arg2}; + return __Pyx_PyObject_FastCall(function, args+1, 2 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET); +} + +/* PyObjectCallMethod1 */ +#if !(CYTHON_VECTORCALL && (__PYX_LIMITED_VERSION_HEX >= 0x030C0000 || (!CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x03090000))) +static PyObject* __Pyx__PyObject_CallMethod1(PyObject* method, PyObject* arg) { + PyObject *result = __Pyx_PyObject_CallOneArg(method, arg); + Py_DECREF(method); + return result; +} +#endif +static PyObject* __Pyx_PyObject_CallMethod1(PyObject* obj, PyObject* method_name, PyObject* arg) { +#if CYTHON_VECTORCALL && (__PYX_LIMITED_VERSION_HEX >= 0x030C0000 || (!CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x03090000)) + PyObject *args[2] = {obj, arg}; + (void) __Pyx_PyObject_CallOneArg; + (void) __Pyx_PyObject_Call2Args; + return PyObject_VectorcallMethod(method_name, args, 2 | PY_VECTORCALL_ARGUMENTS_OFFSET, NULL); +#else + PyObject *method = NULL, *result; + int is_method = __Pyx_PyObject_GetMethod(obj, method_name, &method); + if (likely(is_method)) { + result = __Pyx_PyObject_Call2Args(method, obj, arg); + Py_DECREF(method); + return result; + } + if (unlikely(!method)) return NULL; + return __Pyx__PyObject_CallMethod1(method, arg); +#endif +} + +/* UpdateUnpickledDict */ +static int __Pyx__UpdateUnpickledDict(PyObject *obj, PyObject *state, Py_ssize_t index) { + PyObject *state_dict = __Pyx_PySequence_ITEM(state, index); + if (unlikely(!state_dict)) { + return -1; + } + int non_empty = PyObject_IsTrue(state_dict); + if (non_empty == 0) { + Py_DECREF(state_dict); + return 0; + } else if (unlikely(non_empty == -1)) { + return -1; + } + PyObject *dict; + #if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000 + dict = PyObject_GetAttrString(obj, "__dict__"); + #else + dict = PyObject_GenericGetDict(obj, NULL); + #endif + if (unlikely(!dict)) { + Py_DECREF(state_dict); + return -1; + } + int result; + if (likely(PyDict_CheckExact(dict))) { + result = PyDict_Update(dict, state_dict); + } else { + PyObject *obj_result = __Pyx_PyObject_CallMethod1(dict, __pyx_mstate_global->__pyx_n_u_update, state_dict); + if (likely(obj_result)) { + Py_DECREF(obj_result); + result = 0; + } else { + result = -1; + } + } + Py_DECREF(state_dict); + Py_DECREF(dict); + return result; +} +static int __Pyx_UpdateUnpickledDict(PyObject *obj, PyObject *state, Py_ssize_t index) { + Py_ssize_t state_size = __Pyx_PyTuple_GET_SIZE(state); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(state_size == -1)) return -1; + #endif + if (state_size <= index) { + return 0; + } + return __Pyx__UpdateUnpickledDict(obj, state, index); +} + +/* FormatTypeName */ +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030d0000 +static __Pyx_TypeName +__Pyx_PyType_GetFullyQualifiedName(PyTypeObject* tp) +{ + PyObject *module = NULL, *name = NULL, *result = NULL; + #if __PYX_LIMITED_VERSION_HEX < 0x030b0000 + name = __Pyx_PyObject_GetAttrStr((PyObject *)tp, + __pyx_mstate_global->__pyx_n_u_qualname); + #else + name = PyType_GetQualName(tp); + #endif + if (unlikely(name == NULL) || unlikely(!PyUnicode_Check(name))) goto bad; + module = __Pyx_PyObject_GetAttrStr((PyObject *)tp, + __pyx_mstate_global->__pyx_n_u_module); + if (unlikely(module == NULL) || unlikely(!PyUnicode_Check(module))) goto bad; + if (PyUnicode_CompareWithASCIIString(module, "builtins") == 0) { + result = name; + name = NULL; + goto done; + } + result = PyUnicode_FromFormat("%U.%U", module, name); + if (unlikely(result == NULL)) goto bad; + done: + Py_XDECREF(name); + Py_XDECREF(module); + return result; + bad: + PyErr_Clear(); + if (name) { + result = name; + name = NULL; + } else { + result = __Pyx_NewRef(__pyx_mstate_global->__pyx_kp_u__5); + } + goto done; +} +#endif + +/* FastTypeChecks */ +#if CYTHON_COMPILING_IN_CPYTHON +static int __Pyx_InBases(PyTypeObject *a, PyTypeObject *b) { + while (a) { + a = __Pyx_PyType_GetSlot(a, tp_base, PyTypeObject*); + if (a == b) + return 1; + } + return b == &PyBaseObject_Type; +} +static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b) { + PyObject *mro; + if (a == b) return 1; + mro = a->tp_mro; + if (likely(mro)) { + Py_ssize_t i, n; + n = PyTuple_GET_SIZE(mro); + for (i = 0; i < n; i++) { + if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b) + return 1; + } + return 0; + } + return __Pyx_InBases(a, b); +} +static CYTHON_INLINE int __Pyx_IsAnySubtype2(PyTypeObject *cls, PyTypeObject *a, PyTypeObject *b) { + PyObject *mro; + if (cls == a || cls == b) return 1; + mro = cls->tp_mro; + if (likely(mro)) { + Py_ssize_t i, n; + n = PyTuple_GET_SIZE(mro); + for (i = 0; i < n; i++) { + PyObject *base = PyTuple_GET_ITEM(mro, i); + if (base == (PyObject *)a || base == (PyObject *)b) + return 1; + } + return 0; + } + return __Pyx_InBases(cls, a) || __Pyx_InBases(cls, b); +} +static CYTHON_INLINE int __Pyx_inner_PyErr_GivenExceptionMatches2(PyObject *err, PyObject* exc_type1, PyObject *exc_type2) { + if (exc_type1) { + return __Pyx_IsAnySubtype2((PyTypeObject*)err, (PyTypeObject*)exc_type1, (PyTypeObject*)exc_type2); + } else { + return __Pyx_IsSubtype((PyTypeObject*)err, (PyTypeObject*)exc_type2); + } +} +static int __Pyx_PyErr_GivenExceptionMatchesTuple(PyObject *exc_type, PyObject *tuple) { + Py_ssize_t i, n; + assert(PyExceptionClass_Check(exc_type)); + n = PyTuple_GET_SIZE(tuple); + for (i=0; i>= 8; + ++i; + } + __Pyx_cached_runtime_version = version; + } +} +#endif +static unsigned long __Pyx_get_runtime_version(void) { +#if __PYX_LIMITED_VERSION_HEX >= 0x030b0000 + return Py_Version & ~0xFFUL; +#else + return __Pyx_cached_runtime_version; +#endif +} + +/* CheckBinaryVersion */ +static int __Pyx_check_binary_version(unsigned long ct_version, unsigned long rt_version, int allow_newer) { + const unsigned long MAJOR_MINOR = 0xFFFF0000UL; + if ((rt_version & MAJOR_MINOR) == (ct_version & MAJOR_MINOR)) + return 0; + if (likely(allow_newer && (rt_version & MAJOR_MINOR) > (ct_version & MAJOR_MINOR))) + return 1; + { + char message[200]; + PyOS_snprintf(message, sizeof(message), + "compile time Python version %d.%d " + "of module '%.100s' " + "%s " + "runtime version %d.%d", + (int) (ct_version >> 24), (int) ((ct_version >> 16) & 0xFF), + __Pyx_MODULE_NAME, + (allow_newer) ? "was newer than" : "does not match", + (int) (rt_version >> 24), (int) ((rt_version >> 16) & 0xFF) + ); + return PyErr_WarnEx(NULL, message, 1); + } +} + +/* NewCodeObj */ +#if CYTHON_COMPILING_IN_LIMITED_API + static PyObject* __Pyx__PyCode_New(int a, int p, int k, int l, int s, int f, + PyObject *code, PyObject *c, PyObject* n, PyObject *v, + PyObject *fv, PyObject *cell, PyObject* fn, + PyObject *name, int fline, PyObject *lnos) { + PyObject *exception_table = NULL; + PyObject *types_module=NULL, *code_type=NULL, *result=NULL; + #if __PYX_LIMITED_VERSION_HEX < 0x030b0000 + PyObject *version_info; + PyObject *py_minor_version = NULL; + #endif + long minor_version = 0; + PyObject *type, *value, *traceback; + PyErr_Fetch(&type, &value, &traceback); + #if __PYX_LIMITED_VERSION_HEX >= 0x030b0000 + minor_version = 11; + #else + if (!(version_info = PySys_GetObject("version_info"))) goto end; + if (!(py_minor_version = PySequence_GetItem(version_info, 1))) goto end; + minor_version = PyLong_AsLong(py_minor_version); + Py_DECREF(py_minor_version); + if (minor_version == -1 && PyErr_Occurred()) goto end; + #endif + if (!(types_module = PyImport_ImportModule("types"))) goto end; + if (!(code_type = PyObject_GetAttrString(types_module, "CodeType"))) goto end; + if (minor_version <= 7) { + (void)p; + result = PyObject_CallFunction(code_type, "iiiiiOOOOOOiOOO", a, k, l, s, f, code, + c, n, v, fn, name, fline, lnos, fv, cell); + } else if (minor_version <= 10) { + result = PyObject_CallFunction(code_type, "iiiiiiOOOOOOiOOO", a,p, k, l, s, f, code, + c, n, v, fn, name, fline, lnos, fv, cell); + } else { + if (!(exception_table = PyBytes_FromStringAndSize(NULL, 0))) goto end; + result = PyObject_CallFunction(code_type, "iiiiiiOOOOOOOiOOOO", a,p, k, l, s, f, code, + c, n, v, fn, name, name, fline, lnos, exception_table, fv, cell); + } + end: + Py_XDECREF(code_type); + Py_XDECREF(exception_table); + Py_XDECREF(types_module); + if (type) { + PyErr_Restore(type, value, traceback); + } + return result; + } +#elif PY_VERSION_HEX >= 0x030B0000 + static PyCodeObject* __Pyx__PyCode_New(int a, int p, int k, int l, int s, int f, + PyObject *code, PyObject *c, PyObject* n, PyObject *v, + PyObject *fv, PyObject *cell, PyObject* fn, + PyObject *name, int fline, PyObject *lnos) { + PyCodeObject *result; + result = + #if PY_VERSION_HEX >= 0x030C0000 + PyUnstable_Code_NewWithPosOnlyArgs + #else + PyCode_NewWithPosOnlyArgs + #endif + (a, p, k, l, s, f, code, c, n, v, fv, cell, fn, name, name, fline, lnos, __pyx_mstate_global->__pyx_empty_bytes); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030c00A1 + if (likely(result)) + result->_co_firsttraceable = 0; + #endif + return result; + } +#elif !CYTHON_COMPILING_IN_PYPY + #define __Pyx__PyCode_New(a, p, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ + PyCode_NewWithPosOnlyArgs(a, p, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) +#else + #define __Pyx__PyCode_New(a, p, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ + PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) +#endif +static PyObject* __Pyx_PyCode_New( + const __Pyx_PyCode_New_function_description descr, + PyObject * const *varnames, + PyObject *filename, + PyObject *funcname, + PyObject *line_table, + PyObject *tuple_dedup_map +) { + PyObject *code_obj = NULL, *varnames_tuple_dedup = NULL, *code_bytes = NULL; + Py_ssize_t var_count = (Py_ssize_t) descr.nlocals; + PyObject *varnames_tuple = PyTuple_New(var_count); + if (unlikely(!varnames_tuple)) return NULL; + for (Py_ssize_t i=0; i < var_count; i++) { + Py_INCREF(varnames[i]); + if (__Pyx_PyTuple_SET_ITEM(varnames_tuple, i, varnames[i]) != (0)) goto done; + } + #if CYTHON_COMPILING_IN_LIMITED_API + varnames_tuple_dedup = PyDict_GetItem(tuple_dedup_map, varnames_tuple); + if (!varnames_tuple_dedup) { + if (unlikely(PyDict_SetItem(tuple_dedup_map, varnames_tuple, varnames_tuple) < 0)) goto done; + varnames_tuple_dedup = varnames_tuple; + } + #else + varnames_tuple_dedup = PyDict_SetDefault(tuple_dedup_map, varnames_tuple, varnames_tuple); + if (unlikely(!varnames_tuple_dedup)) goto done; + #endif + #if CYTHON_AVOID_BORROWED_REFS + Py_INCREF(varnames_tuple_dedup); + #endif + if (__PYX_LIMITED_VERSION_HEX >= (0x030b0000) && line_table != NULL && !CYTHON_COMPILING_IN_GRAAL) { + Py_ssize_t line_table_length = __Pyx_PyBytes_GET_SIZE(line_table); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(line_table_length == -1)) goto done; + #endif + Py_ssize_t code_len = (line_table_length * 2 + 4) & ~3LL; + code_bytes = PyBytes_FromStringAndSize(NULL, code_len); + if (unlikely(!code_bytes)) goto done; + char* c_code_bytes = PyBytes_AsString(code_bytes); + if (unlikely(!c_code_bytes)) goto done; + memset(c_code_bytes, 0, (size_t) code_len); + } + code_obj = (PyObject*) __Pyx__PyCode_New( + (int) descr.argcount, + (int) descr.num_posonly_args, + (int) descr.num_kwonly_args, + (int) descr.nlocals, + 0, + (int) descr.flags, + code_bytes ? code_bytes : __pyx_mstate_global->__pyx_empty_bytes, + __pyx_mstate_global->__pyx_empty_tuple, + __pyx_mstate_global->__pyx_empty_tuple, + varnames_tuple_dedup, + __pyx_mstate_global->__pyx_empty_tuple, + __pyx_mstate_global->__pyx_empty_tuple, + filename, + funcname, + (int) descr.first_line, + (__PYX_LIMITED_VERSION_HEX >= (0x030b0000) && line_table) ? line_table : __pyx_mstate_global->__pyx_empty_bytes + ); +done: + Py_XDECREF(code_bytes); + #if CYTHON_AVOID_BORROWED_REFS + Py_XDECREF(varnames_tuple_dedup); + #endif + Py_DECREF(varnames_tuple); + return code_obj; +} + +/* DecompressString */ +static PyObject *__Pyx_DecompressString(const char *s, Py_ssize_t length, int algo) { + PyObject *module = NULL, *decompress, *compressed_bytes, *decompressed; + const char* module_name = algo == 3 ? "compression.zstd" : algo == 2 ? "bz2" : "zlib"; + PyObject *methodname = PyUnicode_FromString("decompress"); + if (unlikely(!methodname)) return NULL; + #if __PYX_LIMITED_VERSION_HEX >= 0x030e0000 + if (algo == 3) { + PyObject *fromlist = Py_BuildValue("[O]", methodname); + if (unlikely(!fromlist)) goto bad; + module = PyImport_ImportModuleLevel("compression.zstd", NULL, NULL, fromlist, 0); + Py_DECREF(fromlist); + } else + #endif + module = PyImport_ImportModule(module_name); + if (unlikely(!module)) goto import_failed; + decompress = PyObject_GetAttr(module, methodname); + if (unlikely(!decompress)) goto import_failed; + { + #ifdef __cplusplus + char *memview_bytes = const_cast(s); + #else + #if defined(__clang__) + #pragma clang diagnostic push + #pragma clang diagnostic ignored "-Wcast-qual" + #elif !defined(__INTEL_COMPILER) && defined(__GNUC__) + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wcast-qual" + #endif + char *memview_bytes = (char*) s; + #if defined(__clang__) + #pragma clang diagnostic pop + #elif !defined(__INTEL_COMPILER) && defined(__GNUC__) + #pragma GCC diagnostic pop + #endif + #endif + #if CYTHON_COMPILING_IN_LIMITED_API && !defined(PyBUF_READ) + int memview_flags = 0x100; + #else + int memview_flags = PyBUF_READ; + #endif + compressed_bytes = PyMemoryView_FromMemory(memview_bytes, length, memview_flags); + } + if (unlikely(!compressed_bytes)) { + Py_DECREF(decompress); + goto bad; + } + decompressed = PyObject_CallFunctionObjArgs(decompress, compressed_bytes, NULL); + Py_DECREF(compressed_bytes); + Py_DECREF(decompress); + Py_DECREF(module); + Py_DECREF(methodname); + return decompressed; +import_failed: + PyErr_Format(PyExc_ImportError, + "Failed to import '%.20s.decompress' - cannot initialise module strings. " + "String compression was configured with the C macro 'CYTHON_COMPRESS_STRINGS=%d'.", + module_name, algo); +bad: + Py_XDECREF(module); + Py_DECREF(methodname); + return NULL; +} + +#include +static CYTHON_INLINE Py_ssize_t __Pyx_ssize_strlen(const char *s) { + size_t len = strlen(s); + if (unlikely(len > (size_t) PY_SSIZE_T_MAX)) { + PyErr_SetString(PyExc_OverflowError, "byte string is too long"); + return -1; + } + return (Py_ssize_t) len; +} +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char* c_str) { + Py_ssize_t len = __Pyx_ssize_strlen(c_str); + if (unlikely(len < 0)) return NULL; + return __Pyx_PyUnicode_FromStringAndSize(c_str, len); +} +static CYTHON_INLINE PyObject* __Pyx_PyByteArray_FromString(const char* c_str) { + Py_ssize_t len = __Pyx_ssize_strlen(c_str); + if (unlikely(len < 0)) return NULL; + return PyByteArray_FromStringAndSize(c_str, len); +} +static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject* o) { + Py_ssize_t ignore; + return __Pyx_PyObject_AsStringAndSize(o, &ignore); +} +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 +static CYTHON_INLINE const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *length) { + if (unlikely(__Pyx_PyUnicode_READY(o) == -1)) return NULL; +#if CYTHON_COMPILING_IN_LIMITED_API + { + const char* result; + Py_ssize_t unicode_length; + CYTHON_MAYBE_UNUSED_VAR(unicode_length); // only for __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + #if __PYX_LIMITED_VERSION_HEX < 0x030A0000 + if (unlikely(PyArg_Parse(o, "s#", &result, length) < 0)) return NULL; + #else + result = PyUnicode_AsUTF8AndSize(o, length); + #endif + #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + unicode_length = PyUnicode_GetLength(o); + if (unlikely(unicode_length < 0)) return NULL; + if (unlikely(unicode_length != *length)) { + PyUnicode_AsASCIIString(o); + return NULL; + } + #endif + return result; + } +#else +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + if (likely(PyUnicode_IS_ASCII(o))) { + *length = PyUnicode_GET_LENGTH(o); + return PyUnicode_AsUTF8(o); + } else { + PyUnicode_AsASCIIString(o); + return NULL; + } +#else + return PyUnicode_AsUTF8AndSize(o, length); +#endif +#endif +} +#endif +static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 + if (PyUnicode_Check(o)) { + return __Pyx_PyUnicode_AsStringAndSize(o, length); + } else +#endif + if (PyByteArray_Check(o)) { +#if (CYTHON_ASSUME_SAFE_SIZE && CYTHON_ASSUME_SAFE_MACROS) || (CYTHON_COMPILING_IN_PYPY && (defined(PyByteArray_AS_STRING) && defined(PyByteArray_GET_SIZE))) + *length = PyByteArray_GET_SIZE(o); + return PyByteArray_AS_STRING(o); +#else + *length = PyByteArray_Size(o); + if (*length == -1) return NULL; + return PyByteArray_AsString(o); +#endif + } else + { + char* result; + int r = PyBytes_AsStringAndSize(o, &result, length); + if (unlikely(r < 0)) { + return NULL; + } else { + return result; + } + } +} +static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { + int is_true = x == Py_True; + if (is_true | (x == Py_False) | (x == Py_None)) return is_true; + else return PyObject_IsTrue(x); +} +static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject* x) { + int retval; + if (unlikely(!x)) return -1; + retval = __Pyx_PyObject_IsTrue(x); + Py_DECREF(x); + return retval; +} +static PyObject* __Pyx_PyNumber_LongWrongResultType(PyObject* result) { + __Pyx_TypeName result_type_name = __Pyx_PyType_GetFullyQualifiedName(Py_TYPE(result)); + if (PyLong_Check(result)) { + if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1, + "__int__ returned non-int (type " __Pyx_FMT_TYPENAME "). " + "The ability to return an instance of a strict subclass of int is deprecated, " + "and may be removed in a future version of Python.", + result_type_name)) { + __Pyx_DECREF_TypeName(result_type_name); + Py_DECREF(result); + return NULL; + } + __Pyx_DECREF_TypeName(result_type_name); + return result; + } + PyErr_Format(PyExc_TypeError, + "__int__ returned non-int (type " __Pyx_FMT_TYPENAME ")", + result_type_name); + __Pyx_DECREF_TypeName(result_type_name); + Py_DECREF(result); + return NULL; +} +static CYTHON_INLINE PyObject* __Pyx_PyNumber_Long(PyObject* x) { +#if CYTHON_USE_TYPE_SLOTS + PyNumberMethods *m; +#endif + PyObject *res = NULL; + if (likely(PyLong_Check(x))) + return __Pyx_NewRef(x); +#if CYTHON_USE_TYPE_SLOTS + m = Py_TYPE(x)->tp_as_number; + if (likely(m && m->nb_int)) { + res = m->nb_int(x); + } +#else + if (!PyBytes_CheckExact(x) && !PyUnicode_CheckExact(x)) { + res = PyNumber_Long(x); + } +#endif + if (likely(res)) { + if (unlikely(!PyLong_CheckExact(res))) { + return __Pyx_PyNumber_LongWrongResultType(res); + } + } + else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_TypeError, + "an integer is required"); + } + return res; +} +static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { + Py_ssize_t ival; + PyObject *x; + if (likely(PyLong_CheckExact(b))) { + #if CYTHON_USE_PYLONG_INTERNALS + if (likely(__Pyx_PyLong_IsCompact(b))) { + return __Pyx_PyLong_CompactValue(b); + } else { + const digit* digits = __Pyx_PyLong_Digits(b); + const Py_ssize_t size = __Pyx_PyLong_SignedDigitCount(b); + switch (size) { + case 2: + if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { + return (Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case -2: + if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { + return -(Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case 3: + if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { + return (Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case -3: + if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { + return -(Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case 4: + if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { + return (Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case -4: + if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { + return -(Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + } + } + #endif + return PyLong_AsSsize_t(b); + } + x = PyNumber_Index(b); + if (!x) return -1; + ival = PyLong_AsSsize_t(x); + Py_DECREF(x); + return ival; +} +static CYTHON_INLINE Py_hash_t __Pyx_PyIndex_AsHash_t(PyObject* o) { + if (sizeof(Py_hash_t) == sizeof(Py_ssize_t)) { + return (Py_hash_t) __Pyx_PyIndex_AsSsize_t(o); + } else { + Py_ssize_t ival; + PyObject *x; + x = PyNumber_Index(o); + if (!x) return -1; + ival = PyLong_AsLong(x); + Py_DECREF(x); + return ival; + } +} +static CYTHON_INLINE PyObject *__Pyx_Owned_Py_None(int b) { + CYTHON_UNUSED_VAR(b); + return __Pyx_NewRef(Py_None); +} +static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b) { + return __Pyx_NewRef(b ? Py_True: Py_False); +} +static CYTHON_INLINE PyObject * __Pyx_PyLong_FromSize_t(size_t ival) { + return PyLong_FromSize_t(ival); +} + + +/* MultiPhaseInitModuleState */ +#if CYTHON_PEP489_MULTI_PHASE_INIT && CYTHON_USE_MODULE_STATE +#ifndef CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE +#if (CYTHON_COMPILING_IN_LIMITED_API || PY_VERSION_HEX >= 0x030C0000) + #define CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE 1 +#else + #define CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE 0 +#endif +#endif +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE && !CYTHON_ATOMICS +#error "Module state with PEP489 requires atomics. Currently that's one of\ + C11, C++11, gcc atomic intrinsics or MSVC atomic intrinsics" +#endif +#if !CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE +#define __Pyx_ModuleStateLookup_Lock() +#define __Pyx_ModuleStateLookup_Unlock() +#elif !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d0000 +static PyMutex __Pyx_ModuleStateLookup_mutex = {0}; +#define __Pyx_ModuleStateLookup_Lock() PyMutex_Lock(&__Pyx_ModuleStateLookup_mutex) +#define __Pyx_ModuleStateLookup_Unlock() PyMutex_Unlock(&__Pyx_ModuleStateLookup_mutex) +#elif defined(__cplusplus) && __cplusplus >= 201103L +#include +static std::mutex __Pyx_ModuleStateLookup_mutex; +#define __Pyx_ModuleStateLookup_Lock() __Pyx_ModuleStateLookup_mutex.lock() +#define __Pyx_ModuleStateLookup_Unlock() __Pyx_ModuleStateLookup_mutex.unlock() +#elif defined(__STDC_VERSION__) && (__STDC_VERSION__ > 201112L) && !defined(__STDC_NO_THREADS__) +#include +static mtx_t __Pyx_ModuleStateLookup_mutex; +static once_flag __Pyx_ModuleStateLookup_mutex_once_flag = ONCE_FLAG_INIT; +static void __Pyx_ModuleStateLookup_initialize_mutex(void) { + mtx_init(&__Pyx_ModuleStateLookup_mutex, mtx_plain); +} +#define __Pyx_ModuleStateLookup_Lock()\ + call_once(&__Pyx_ModuleStateLookup_mutex_once_flag, __Pyx_ModuleStateLookup_initialize_mutex);\ + mtx_lock(&__Pyx_ModuleStateLookup_mutex) +#define __Pyx_ModuleStateLookup_Unlock() mtx_unlock(&__Pyx_ModuleStateLookup_mutex) +#elif defined(HAVE_PTHREAD_H) +#include +static pthread_mutex_t __Pyx_ModuleStateLookup_mutex = PTHREAD_MUTEX_INITIALIZER; +#define __Pyx_ModuleStateLookup_Lock() pthread_mutex_lock(&__Pyx_ModuleStateLookup_mutex) +#define __Pyx_ModuleStateLookup_Unlock() pthread_mutex_unlock(&__Pyx_ModuleStateLookup_mutex) +#elif defined(_WIN32) +#include // synchapi.h on its own doesn't work +static SRWLOCK __Pyx_ModuleStateLookup_mutex = SRWLOCK_INIT; +#define __Pyx_ModuleStateLookup_Lock() AcquireSRWLockExclusive(&__Pyx_ModuleStateLookup_mutex) +#define __Pyx_ModuleStateLookup_Unlock() ReleaseSRWLockExclusive(&__Pyx_ModuleStateLookup_mutex) +#else +#error "No suitable lock available for CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE.\ + Requires C standard >= C11, or C++ standard >= C++11,\ + or pthreads, or the Windows 32 API, or Python >= 3.13." +#endif +typedef struct { + int64_t id; + PyObject *module; +} __Pyx_InterpreterIdAndModule; +typedef struct { + char interpreter_id_as_index; + Py_ssize_t count; + Py_ssize_t allocated; + __Pyx_InterpreterIdAndModule table[1]; +} __Pyx_ModuleStateLookupData; +#define __PYX_MODULE_STATE_LOOKUP_SMALL_SIZE 32 +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE +static __pyx_atomic_int_type __Pyx_ModuleStateLookup_read_counter = 0; +#endif +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE +static __pyx_atomic_ptr_type __Pyx_ModuleStateLookup_data = 0; +#else +static __Pyx_ModuleStateLookupData* __Pyx_ModuleStateLookup_data = NULL; +#endif +static __Pyx_InterpreterIdAndModule* __Pyx_State_FindModuleStateLookupTableLowerBound( + __Pyx_InterpreterIdAndModule* table, + Py_ssize_t count, + int64_t interpreterId) { + __Pyx_InterpreterIdAndModule* begin = table; + __Pyx_InterpreterIdAndModule* end = begin + count; + if (begin->id == interpreterId) { + return begin; + } + while ((end - begin) > __PYX_MODULE_STATE_LOOKUP_SMALL_SIZE) { + __Pyx_InterpreterIdAndModule* halfway = begin + (end - begin)/2; + if (halfway->id == interpreterId) { + return halfway; + } + if (halfway->id < interpreterId) { + begin = halfway; + } else { + end = halfway; + } + } + for (; begin < end; ++begin) { + if (begin->id >= interpreterId) return begin; + } + return begin; +} +static PyObject *__Pyx_State_FindModule(CYTHON_UNUSED void* dummy) { + int64_t interpreter_id = PyInterpreterState_GetID(__Pyx_PyInterpreterState_Get()); + if (interpreter_id == -1) return NULL; +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE + __Pyx_ModuleStateLookupData* data = (__Pyx_ModuleStateLookupData*)__pyx_atomic_pointer_load_relaxed(&__Pyx_ModuleStateLookup_data); + { + __pyx_atomic_incr_acq_rel(&__Pyx_ModuleStateLookup_read_counter); + if (likely(data)) { + __Pyx_ModuleStateLookupData* new_data = (__Pyx_ModuleStateLookupData*)__pyx_atomic_pointer_load_acquire(&__Pyx_ModuleStateLookup_data); + if (likely(data == new_data)) { + goto read_finished; + } + } + __pyx_atomic_decr_acq_rel(&__Pyx_ModuleStateLookup_read_counter); + __Pyx_ModuleStateLookup_Lock(); + __pyx_atomic_incr_relaxed(&__Pyx_ModuleStateLookup_read_counter); + data = (__Pyx_ModuleStateLookupData*)__pyx_atomic_pointer_load_relaxed(&__Pyx_ModuleStateLookup_data); + __Pyx_ModuleStateLookup_Unlock(); + } + read_finished:; +#else + __Pyx_ModuleStateLookupData* data = __Pyx_ModuleStateLookup_data; +#endif + __Pyx_InterpreterIdAndModule* found = NULL; + if (unlikely(!data)) goto end; + if (data->interpreter_id_as_index) { + if (interpreter_id < data->count) { + found = data->table+interpreter_id; + } + } else { + found = __Pyx_State_FindModuleStateLookupTableLowerBound( + data->table, data->count, interpreter_id); + } + end: + { + PyObject *result=NULL; + if (found && found->id == interpreter_id) { + result = found->module; + } +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE + __pyx_atomic_decr_acq_rel(&__Pyx_ModuleStateLookup_read_counter); +#endif + return result; + } +} +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE +static void __Pyx_ModuleStateLookup_wait_until_no_readers(void) { + while (__pyx_atomic_load(&__Pyx_ModuleStateLookup_read_counter) != 0); +} +#else +#define __Pyx_ModuleStateLookup_wait_until_no_readers() +#endif +static int __Pyx_State_AddModuleInterpIdAsIndex(__Pyx_ModuleStateLookupData **old_data, PyObject* module, int64_t interpreter_id) { + Py_ssize_t to_allocate = (*old_data)->allocated; + while (to_allocate <= interpreter_id) { + if (to_allocate == 0) to_allocate = 1; + else to_allocate *= 2; + } + __Pyx_ModuleStateLookupData *new_data = *old_data; + if (to_allocate != (*old_data)->allocated) { + new_data = (__Pyx_ModuleStateLookupData *)realloc( + *old_data, + sizeof(__Pyx_ModuleStateLookupData)+(to_allocate-1)*sizeof(__Pyx_InterpreterIdAndModule)); + if (!new_data) { + PyErr_NoMemory(); + return -1; + } + for (Py_ssize_t i = new_data->allocated; i < to_allocate; ++i) { + new_data->table[i].id = i; + new_data->table[i].module = NULL; + } + new_data->allocated = to_allocate; + } + new_data->table[interpreter_id].module = module; + if (new_data->count < interpreter_id+1) { + new_data->count = interpreter_id+1; + } + *old_data = new_data; + return 0; +} +static void __Pyx_State_ConvertFromInterpIdAsIndex(__Pyx_ModuleStateLookupData *data) { + __Pyx_InterpreterIdAndModule *read = data->table; + __Pyx_InterpreterIdAndModule *write = data->table; + __Pyx_InterpreterIdAndModule *end = read + data->count; + for (; readmodule) { + write->id = read->id; + write->module = read->module; + ++write; + } + } + data->count = write - data->table; + for (; writeid = 0; + write->module = NULL; + } + data->interpreter_id_as_index = 0; +} +static int __Pyx_State_AddModule(PyObject* module, CYTHON_UNUSED void* dummy) { + int64_t interpreter_id = PyInterpreterState_GetID(__Pyx_PyInterpreterState_Get()); + if (interpreter_id == -1) return -1; + int result = 0; + __Pyx_ModuleStateLookup_Lock(); +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE + __Pyx_ModuleStateLookupData *old_data = (__Pyx_ModuleStateLookupData *) + __pyx_atomic_pointer_exchange(&__Pyx_ModuleStateLookup_data, 0); +#else + __Pyx_ModuleStateLookupData *old_data = __Pyx_ModuleStateLookup_data; +#endif + __Pyx_ModuleStateLookupData *new_data = old_data; + if (!new_data) { + new_data = (__Pyx_ModuleStateLookupData *)calloc(1, sizeof(__Pyx_ModuleStateLookupData)); + if (!new_data) { + result = -1; + PyErr_NoMemory(); + goto end; + } + new_data->allocated = 1; + new_data->interpreter_id_as_index = 1; + } + __Pyx_ModuleStateLookup_wait_until_no_readers(); + if (new_data->interpreter_id_as_index) { + if (interpreter_id < __PYX_MODULE_STATE_LOOKUP_SMALL_SIZE) { + result = __Pyx_State_AddModuleInterpIdAsIndex(&new_data, module, interpreter_id); + goto end; + } + __Pyx_State_ConvertFromInterpIdAsIndex(new_data); + } + { + Py_ssize_t insert_at = 0; + { + __Pyx_InterpreterIdAndModule* lower_bound = __Pyx_State_FindModuleStateLookupTableLowerBound( + new_data->table, new_data->count, interpreter_id); + assert(lower_bound); + insert_at = lower_bound - new_data->table; + if (unlikely(insert_at < new_data->count && lower_bound->id == interpreter_id)) { + lower_bound->module = module; + goto end; // already in table, nothing more to do + } + } + if (new_data->count+1 >= new_data->allocated) { + Py_ssize_t to_allocate = (new_data->count+1)*2; + new_data = + (__Pyx_ModuleStateLookupData*)realloc( + new_data, + sizeof(__Pyx_ModuleStateLookupData) + + (to_allocate-1)*sizeof(__Pyx_InterpreterIdAndModule)); + if (!new_data) { + result = -1; + new_data = old_data; + PyErr_NoMemory(); + goto end; + } + new_data->allocated = to_allocate; + } + ++new_data->count; + int64_t last_id = interpreter_id; + PyObject *last_module = module; + for (Py_ssize_t i=insert_at; icount; ++i) { + int64_t current_id = new_data->table[i].id; + new_data->table[i].id = last_id; + last_id = current_id; + PyObject *current_module = new_data->table[i].module; + new_data->table[i].module = last_module; + last_module = current_module; + } + } + end: +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE + __pyx_atomic_pointer_exchange(&__Pyx_ModuleStateLookup_data, new_data); +#else + __Pyx_ModuleStateLookup_data = new_data; +#endif + __Pyx_ModuleStateLookup_Unlock(); + return result; +} +static int __Pyx_State_RemoveModule(CYTHON_UNUSED void* dummy) { + int64_t interpreter_id = PyInterpreterState_GetID(__Pyx_PyInterpreterState_Get()); + if (interpreter_id == -1) return -1; + __Pyx_ModuleStateLookup_Lock(); +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE + __Pyx_ModuleStateLookupData *data = (__Pyx_ModuleStateLookupData *) + __pyx_atomic_pointer_exchange(&__Pyx_ModuleStateLookup_data, 0); +#else + __Pyx_ModuleStateLookupData *data = __Pyx_ModuleStateLookup_data; +#endif + if (data->interpreter_id_as_index) { + if (interpreter_id < data->count) { + data->table[interpreter_id].module = NULL; + } + goto done; + } + { + __Pyx_ModuleStateLookup_wait_until_no_readers(); + __Pyx_InterpreterIdAndModule* lower_bound = __Pyx_State_FindModuleStateLookupTableLowerBound( + data->table, data->count, interpreter_id); + if (!lower_bound) goto done; + if (lower_bound->id != interpreter_id) goto done; + __Pyx_InterpreterIdAndModule *end = data->table+data->count; + for (;lower_boundid = (lower_bound+1)->id; + lower_bound->module = (lower_bound+1)->module; + } + } + --data->count; + if (data->count == 0) { + free(data); + data = NULL; + } + done: +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE + __pyx_atomic_pointer_exchange(&__Pyx_ModuleStateLookup_data, data); +#else + __Pyx_ModuleStateLookup_data = data; +#endif + __Pyx_ModuleStateLookup_Unlock(); + return 0; +} +#endif + +/* #### Code section: utility_code_pragmas_end ### */ +#ifdef _MSC_VER +#pragma warning( pop ) +#endif + + + +/* #### Code section: end ### */ +#endif /* Py_PYTHON_H */ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/sasl/cysasl.pyx b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/sasl/cysasl.pyx new file mode 100644 index 0000000000000000000000000000000000000000..a6ab64150b5fa30bf8b30d061a6d4f67d4fc49e1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/sasl/cysasl.pyx @@ -0,0 +1,216 @@ +# cython: freethreading_compatible = True + +import struct + +from thriftpy2.transport.cybase cimport ( + TCyBuffer, + CyTransportBase, + DEFAULT_BUFFER +) + +from ..base import readall +from .. import TTransportException + +from libc.string cimport memcpy + +DEF MIN_BUFFER_SIZE = 1024 + +cdef class TCySaslClientTransport(CyTransportBase): + """sasl wrapper""" + + START = 1 + OK = 2 + BAD = 3 + ERROR = 4 + COMPLETE = 5 + + cdef object sasl, sasl_client_factory + cdef TCyBuffer __wbuf, __rbuf + cdef bint opened, encode, encode_decided + cdef str mechanism + + def __init__(self, sasl_client_factory, mechanism, trans): + """ + @param sasl_client_factory: a callable that returns a new sasl.Client object + @param mechanism: the SASL mechanism (e.g. "GSSAPI") + @param trans: the underlying transport over which to communicate. + """ + self.trans = trans + self.sasl_client_factory = sasl_client_factory + self.sasl = None + self.mechanism = mechanism + self.__wbuf = TCyBuffer(DEFAULT_BUFFER) + self.__rbuf = TCyBuffer(DEFAULT_BUFFER) + self.encode_decided = False + self.encode = False + + def is_open(self): + return self.trans.is_open() + + def open(self): + if not self.is_open(): + self.trans.open() + + if self.sasl is not None: + raise TTransportException( + type=TTransportException.NOT_OPEN, + message="Already open!") + self.sasl = self.sasl_client_factory() + + ret, chosen_mech, initial_response = self.sasl.start(self.mechanism) + if not ret: + raise TTransportException(type=TTransportException.NOT_OPEN, + message=("Could not start SASL: %s" % self.sasl.getError())) + + # Send initial response + self._send_message(self.START, chosen_mech) + self._send_message(self.OK, initial_response) + + # SASL negotiation loop + while True: + status, payload = self._recv_sasl_message() + if status not in (self.OK, self.COMPLETE): + raise TTransportException(type=TTransportException.NOT_OPEN, + message=("Bad status: %d (%s)" % (status, payload))) + if status == self.COMPLETE: + break + ret, response = self.sasl.step(payload) + if not ret: + raise TTransportException(type=TTransportException.NOT_OPEN, + message=("Bad SASL result: %s" % (self.sasl.getError()))) + self._send_message(self.OK, response) + + def _send_message(self, status, body): + header = struct.pack(">BI", status, len(body)) + self.trans.write(header + body) + self.trans.flush() + + def _recv_sasl_message(self): + header = readall(self.trans.read, 5) + status, length = struct.unpack(">BI", header) + if length > 0: + payload = readall(self.trans.read, length) + else: + payload = "" + return status, payload + + def write(self, bytes data): + cdef int sz = len(data) + return self.c_write(data, sz) + + cdef c_write(self, const char *data, int sz): + cdef: + int cap = self.__wbuf.buf_size - self.__wbuf.data_size + int r + + if cap < sz: + self.c_flush() + + r = self.__wbuf.write(sz, data) + if r == -1: + raise MemoryError("Write to buffer error") + + def flush(self): + return self.c_flush() + + cdef c_flush(self): + cdef bytes data + if self.__wbuf.data_size > 0: + data = self.__wbuf.buf[:self.__wbuf.data_size] + # The first time we flush data, we send it to sasl.encode() + # If the length doesn't change, then we must be using a QOP + # of auth and we should no longer call sasl.encode(), otherwise + # we encode every time. + if not self.encode_decided: + success, encoded = self.sasl.encode(data) + if not success: + raise TTransportException(type=TTransportException.UNKNOWN, + message=self.sasl.getError()) + if (len(encoded)==len(data)): + self.encode = False + self._flushPlain(data) + else: + self.encode = True + self.trans.write(encoded) + self.encode_decided = True + elif self.encode: + self._flushEncoded(data) + else: + self._flushPlain(data) + + self.trans.flush() + self.__wbuf.clean() + return("DUN FLUSHING IN SASL") + + def _flushEncoded(self, buffer): + # sasl.ecnode() does the encoding and adds the length header, so nothing + # to do but call it and write the result. + success, encoded = self.sasl.encode(buffer) + if not success: + raise TTransportException(type=TTransportException.UNKNOWN, + message=self.sasl.getError()) + self.trans.write(encoded) + + def _flushPlain(self, buffer): + # When we have QOP of auth, sasl.encode() will pass the input to the output + # but won't put a length header, so we have to do that. + + # Note stolen from TFramedTransport: + # N.B.: Doing this string concatenation is WAY cheaper than making + # two separate calls to the underlying socket object. Socket writes in + # Python turn out to be REALLY expensive, but it seems to do a pretty + # good job of managing string buffer operations without excessive copies + self.trans.write(struct.pack(">I", len(buffer)) + buffer) + + def read(self, sz): + return self.get_string(sz) + + cdef c_read(self, int sz, char* out): + cdef bytes ret + + ret = b"" + + if sz <= 0: + return 0 + + orig_sz = sz + if self.__rbuf.data_size < sz: + # Read what remains, then get more data plz + ret += self.__rbuf.buf[:self.__rbuf.data_size] + sz -= self.__rbuf.data_size + self._read_frame() + + ret += self.__rbuf.buf[self.__rbuf.cur:self.__rbuf.cur + sz] + self.__rbuf.cur += sz + self.__rbuf.data_size -= sz + + memcpy(out, ret, orig_sz) + + def _read_frame(self): + header = readall(self.trans.read, 4) + (length,) = struct.unpack(">I", header) + if self.encode_decided and self.encode: + # If the frames are encoded (i.e. you're using a QOP of auth-int or + # auth-conf), then make sure to include the header in the bytes you send to + # sasl.decode() + encoded = header + readall(self.trans.read, length) + success, decoded = self.sasl.decode(encoded) + if not success: + raise TTransportException(type=TTransportException.UNKNOWN, + message=self.sasl.getError()) + else: + # If the frames are not encoded, just pass it through + decoded = readall(self.trans.read, length) + self.__rbuf = TCyBuffer(len(decoded)+1) # just to be sure make room for an extra byte + memcpy(self.__rbuf.buf, decoded, len(decoded)) + self.__rbuf.data_size = len(decoded) + self.__rbuf.cur = 0 + + def clean(self): + self.__rbuf.clean() + self.__wbuf.clean() + + def close(self): + self.trans.close() + self.sasl = None + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/socket.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/socket.py new file mode 100644 index 0000000000000000000000000000000000000000..b98b4c8c1ed783eb27f2060d535b5e8fd5e5e852 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/socket.py @@ -0,0 +1,243 @@ +# -*- coding: utf-8 -*- + +from __future__ import absolute_import, division + +import errno +import os +import socket +import struct +import sys + +from . import TTransportException + +MAC_OR_BSD = sys.platform == 'darwin' or sys.platform.startswith('freebsd') + + +class TSocket(object): + """Socket implementation for client side.""" + + def __init__(self, host=None, port=None, unix_socket=None, + sock=None, socket_family=socket.AF_INET, + socket_timeout=3000, connect_timeout=None): + """Initialize a TSocket + + TSocket can be initialized in 3 ways: + * host + port. can configure to use AF_INET/AF_INET6 + * unix_socket + * socket. should pass already opened socket here. + + @param host(str) The host to connect to. + @param port(int) The (TCP) port to connect to. + @param unix_socket(str) The filename of a unix socket to connect to. + @param sock(socket) Initialize with opened socket directly. + If this param used, the host, port and unix_socket params will + be ignored. + @param socket_family(str) socket.AF_INET or socket.AF_INET6. only + take effect when using host/port + @param socket_timeout socket timeout in ms + @param connect_timeout connect timeout in ms, only used in + connection, will be set to socket_timeout if not set. + """ + if sock: + self.sock = sock + elif unix_socket: + self.unix_socket = unix_socket + self.host = None + self.port = None + self.sock = None + else: + self.unix_socket = None + self.host = host + self.port = port + self.sock = None + + self.socket_family = socket_family + self.socket_timeout = socket_timeout / 1000 if socket_timeout else None + self.connect_timeout = connect_timeout / 1000 if connect_timeout \ + else self.socket_timeout + + def _init_sock(self): + if self.unix_socket: + _sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + else: + _sock = socket.socket(self.socket_family, socket.SOCK_STREAM) + _sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) + + # socket options + linger = struct.pack('ii', 0, 0) + _sock.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, linger) + _sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) + + self.sock = _sock + + def set_handle(self, sock): + self.sock = sock + + def set_timeout(self, ms): + """Backward compat api, will bind the timeout to both connect_timeout + and socket_timeout. + """ + self.socket_timeout = ms / 1000 if (ms and ms > 0) else None + self.connect_timeout = self.socket_timeout + + if self.sock is not None: + self.sock.settimeout(self.socket_timeout) + + def is_open(self): + return bool(self.sock) + + def open(self): + self._init_sock() + + addr = self.unix_socket or (self.host, self.port) + + try: + if self.connect_timeout: + self.sock.settimeout(self.connect_timeout) + + self.sock.connect(addr) + + if self.socket_timeout: + self.sock.settimeout(self.socket_timeout) + + except (socket.error, OSError): + self.close() + raise TTransportException( + type=TTransportException.NOT_OPEN, + message="Could not connect to %s" % str(addr)) + + def read(self, sz): + while True: + try: + buff = self.sock.recv(sz) + except socket.error as e: + if e.errno == errno.EINTR: + continue + if e.args[0] == errno.ECONNRESET and MAC_OR_BSD: + # freebsd and Mach don't follow POSIX semantic of recv + # and fail with ECONNRESET if peer performed shutdown. + # See corresponding comment and code in TSocket::read() + # in lib/cpp/src/transport/TSocket.cpp. + self.close() + # Trigger the check to raise the END_OF_FILE exception. + buff = '' + break + else: + raise + else: + break + + if len(buff) == 0: + raise TTransportException(type=TTransportException.END_OF_FILE, + message='TSocket read 0 bytes') + return buff + + def write(self, buff): + self.sock.sendall(buff) + + def flush(self): + pass + + def close(self): + if not self.sock: + return + + try: + self.sock.shutdown(socket.SHUT_RDWR) + except OSError: + pass + + try: + self.sock.close() + except OSError: + pass + self.sock = None + + +class TServerSocket(object): + """Socket implementation for server side.""" + + def __init__(self, host=None, port=None, unix_socket=None, + socket_family=socket.AF_INET, client_timeout=3000, + backlog=128): + """Initialize a TServerSocket + + TSocket can be initialized in 2 ways: + * host + port. can configure to use AF_INET/AF_INET6 + * unix_socket + + @param host(str) The host to connect to + @param port(int) The (TCP) port to connect to + @param unix_socket(str) The filename of a unix socket to connect to + @param socket_family(str) socket.AF_INET or socket.AF_INET6. only + take effect when using host/port + @param client_timeout client socket timeout + @param backlog backlog for server socket + """ + + if unix_socket: + self.unix_socket = unix_socket + self.host = None + self.port = None + else: + self.unix_socket = None + self.host = host + self.port = port + + self.socket_family = socket_family + self.client_timeout = client_timeout / 1000 if client_timeout else None + self.backlog = backlog + + def _init_sock(self): + if self.unix_socket: + # try remove the sock file it already exists + _sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + try: + _sock.connect(self.unix_socket) + except (socket.error, OSError) as err: + if err.args[0] == errno.ECONNREFUSED: + os.unlink(self.unix_socket) + else: + _sock = socket.socket(self.socket_family, socket.SOCK_STREAM) + + _sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + # valid socket https://github.com/python/cpython/issues/128916 + valid_family = (socket.AF_INET, socket.AF_INET6) + if _sock.family in valid_family and hasattr(socket, "SO_REUSEPORT"): + try: + _sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) + except socket.error as err: + if err[0] in (errno.ENOPROTOOPT, errno.EINVAL): + pass + else: + raise + _sock.settimeout(None) + self.sock = _sock + + def listen(self): + self._init_sock() + + addr = self.unix_socket or (self.host, self.port) + self.sock.bind(addr) + self.sock.listen(self.backlog) + + def accept(self): + client, _ = self.sock.accept() + if self.client_timeout: + client.settimeout(self.client_timeout) + return TSocket(sock=client) + + def close(self): + if not self.sock: + return + + try: + self.sock.shutdown(socket.SHUT_RDWR) + except OSError: + pass + + try: + self.sock.close() + except OSError: + pass + self.sock = None diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/sslsocket.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/sslsocket.py new file mode 100644 index 0000000000000000000000000000000000000000..3972e34841a5e8d69af2e9fc5d4c7825abf48f99 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/transport/sslsocket.py @@ -0,0 +1,123 @@ +# -*- coding: utf-8 -*- + +from __future__ import absolute_import + +import os +import socket +import ssl +import struct + +from ._ssl import ( + create_thriftpy_context, + RESTRICTED_SERVER_CIPHERS, + DEFAULT_CIPHERS +) +from .socket import TSocket, TServerSocket + + +class TSSLSocket(TSocket): + """SSL socket implementation for client side + """ + + def __init__(self, host, port, socket_family=socket.AF_INET, + socket_timeout=3000, connect_timeout=None, + ssl_context=None, validate=True, + cafile=None, capath=None, certfile=None, keyfile=None, + ciphers=DEFAULT_CIPHERS): + """Initialize a TSSLSocket + + @param validate(bool) Set to False to disable SSL certificate + validation and hostname validation. Default enabled. + @param cafile(str) Path to a file of concatenated CA + certificates in PEM format. + @param capath(str) path to a directory containing several CA + certificates in PEM format, following an OpenSSL specific layout. + @param certfile(str) The certfile string must be the path to a + single file in PEM format containing the certificate as well as + any number of CA certificates needed to establish the + certificate’s authenticity. + @param keyfile(str) The keyfile string, if not present, + the private key will be taken from certfile as well. + @param ciphers(list) The cipher suites to allow + @param ssl_context(SSLContext) Customize the SSLContext, can be used + to persist SSLContext object. Caution it's easy to get wrong, only + use if you know what you're doing. + + The `host` must be the same with server if validate enabled. + """ + super(TSSLSocket, self).__init__( + host=host, port=port, socket_family=socket_family, + connect_timeout=connect_timeout, socket_timeout=socket_timeout) + + if ssl_context: + self.ssl_context = ssl_context + else: + self.ssl_context = create_thriftpy_context(server_side=False, + ciphers=ciphers) + + if cafile or capath: + self.ssl_context.load_verify_locations(cafile=cafile, + capath=capath) + + if certfile: + self.ssl_context.load_cert_chain(certfile, keyfile=keyfile) + + if not validate: + self.ssl_context.check_hostname = False + self.ssl_context.verify_mode = ssl.CERT_NONE + + def _init_sock(self): + _sock = socket.socket(self.socket_family, socket.SOCK_STREAM) + _sock = self.ssl_context.wrap_socket(_sock, + server_hostname=self.host) + # socket options + linger = struct.pack('ii', 0, 0) + _sock.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, linger) + _sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) + _sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) + self.sock = _sock + + +class TSSLServerSocket(TServerSocket): + """SSL implementation of TServerSocket + """ + + def __init__(self, host, port, socket_family=socket.AF_INET, + client_timeout=3000, backlog=128, + ssl_context=None, certfile='cert.pem', + ciphers=RESTRICTED_SERVER_CIPHERS): + """Initialize a TSSLServerSocket + + @param certfile(str) The server cert pem filename + @param ciphers(list) The cipher suites to allow + @param ssl_context(SSLContext) Customize the SSLContext, can be used + to persist SSLContext object. Caution it's easy to get wrong, only + use if you know what you're doing. + """ + super(TSSLServerSocket, self).__init__( + host=host, port=port, socket_family=socket_family, + client_timeout=client_timeout, backlog=backlog) + + if ssl_context: + self.ssl_context = ssl_context + else: + if not os.access(certfile, os.R_OK): + raise IOError('No such certfile found: %s' % certfile) + + self.ssl_context = create_thriftpy_context(server_side=True, + ciphers=ciphers) + self.ssl_context.load_cert_chain(certfile=certfile) + + def accept(self): + sock, _ = self.sock.accept() + try: + ssl_sock = self.ssl_context.wrap_socket(sock, server_side=True) + except ssl.SSLError: + # failed handshake/ssl wrap, close socket to client + sock.shutdown(socket.SHUT_RDWR) + sock.close() + raise + else: + if self.client_timeout: + ssl_sock.settimeout(self.client_timeout) + return TSocket(sock=ssl_sock) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..b38014a74d579702f360cc7f77071bf29f68901a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/thriftpy2/utils.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- + +from __future__ import absolute_import + +import binascii + +from .transport import TMemoryBuffer +from .protocol.base import TProtocolFactory +from .protocol.binary import TBinaryProtocolFactory + + +def serialize(thrift_object, proto_factory: TProtocolFactory=TBinaryProtocolFactory()): + transport = TMemoryBuffer() + protocol = proto_factory.get_protocol(transport) + thrift_object.write(protocol) + protocol.write_message_end() + return transport.getvalue() + + +def deserialize(thrift_object, buf, proto_factory: TProtocolFactory=TBinaryProtocolFactory()): + transport = TMemoryBuffer(buf) + protocol = proto_factory.get_protocol(transport) + thrift_object.read(protocol) + return thrift_object + + +def hexlify(byte_array, delimeter=' '): + s = binascii.hexlify(byte_array).decode('utf-8') + return delimeter.join(a + b for a, b in zip(s[::2], s[1::2])) + + +def hexprint(byte_array, delimeter: str=' ', count: int=10) -> None: + print("Bytes:") + print(byte_array) + + print("\nHex:") + g = hexlify(byte_array, delimeter).split(delimeter) + print('\n'.join(' '.join(g[i:i + 10]) for i in range(0, len(g), 10))) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers-0.22.2.dist-info/INSTALLER b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers-0.22.2.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers-0.22.2.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers-0.22.2.dist-info/METADATA b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers-0.22.2.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..4bb4912e0688994cd2f122f4278cd577833644a0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers-0.22.2.dist-info/METADATA @@ -0,0 +1,214 @@ +Metadata-Version: 2.4 +Name: tokenizers +Version: 0.22.2 +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: Education +Classifier: Intended Audience :: Science/Research +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence +Requires-Dist: huggingface-hub>=0.16.4,<2.0 +Requires-Dist: pytest ; extra == 'testing' +Requires-Dist: pytest-asyncio ; extra == 'testing' +Requires-Dist: requests ; extra == 'testing' +Requires-Dist: numpy ; extra == 'testing' +Requires-Dist: datasets ; extra == 'testing' +Requires-Dist: ruff ; extra == 'testing' +Requires-Dist: ty ; extra == 'testing' +Requires-Dist: sphinx ; extra == 'docs' +Requires-Dist: sphinx-rtd-theme ; extra == 'docs' +Requires-Dist: setuptools-rust ; extra == 'docs' +Requires-Dist: tokenizers[testing] ; extra == 'dev' +Provides-Extra: testing +Provides-Extra: docs +Provides-Extra: dev +Keywords: NLP,tokenizer,BPE,transformer,deep learning +Author-email: Nicolas Patry , Anthony Moi +Requires-Python: >=3.9 +Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM +Project-URL: Homepage, https://github.com/huggingface/tokenizers +Project-URL: Source, https://github.com/huggingface/tokenizers + +

+
+ +
+

+

+ + Build + + + GitHub + +

+
+ +# Tokenizers + +Provides an implementation of today's most used tokenizers, with a focus on performance and +versatility. + +Bindings over the [Rust](https://github.com/huggingface/tokenizers/tree/master/tokenizers) implementation. +If you are interested in the High-level design, you can go check it there. + +Otherwise, let's dive in! + +## Main features: + + - Train new vocabularies and tokenize using 4 pre-made tokenizers (Bert WordPiece and the 3 + most common BPE versions). + - Extremely fast (both training and tokenization), thanks to the Rust implementation. Takes + less than 20 seconds to tokenize a GB of text on a server's CPU. + - Easy to use, but also extremely versatile. + - Designed for research and production. + - Normalization comes with alignments tracking. It's always possible to get the part of the + original sentence that corresponds to a given token. + - Does all the pre-processing: Truncate, Pad, add the special tokens your model needs. + +### Installation + +#### With pip: + +```bash +pip install tokenizers +``` + +#### From sources: + +To use this method, you need to have the Rust installed: + +```bash +# Install with: +curl https://sh.rustup.rs -sSf | sh -s -- -y +export PATH="$HOME/.cargo/bin:$PATH" +``` + +Once Rust is installed, you can compile doing the following + +```bash +git clone https://github.com/huggingface/tokenizers +cd tokenizers/bindings/python + +# Create a virtual env (you can use yours as well) +python -m venv .env +source .env/bin/activate + +# Install `tokenizers` in the current virtual env +pip install -e . +``` + +### Load a pretrained tokenizer from the Hub + +```python +from tokenizers import Tokenizer + +tokenizer = Tokenizer.from_pretrained("bert-base-cased") +``` + +### Using the provided Tokenizers + +We provide some pre-build tokenizers to cover the most common cases. You can easily load one of +these using some `vocab.json` and `merges.txt` files: + +```python +from tokenizers import CharBPETokenizer + +# Initialize a tokenizer +vocab = "./path/to/vocab.json" +merges = "./path/to/merges.txt" +tokenizer = CharBPETokenizer(vocab, merges) + +# And then encode: +encoded = tokenizer.encode("I can feel the magic, can you?") +print(encoded.ids) +print(encoded.tokens) +``` + +And you can train them just as simply: + +```python +from tokenizers import CharBPETokenizer + +# Initialize a tokenizer +tokenizer = CharBPETokenizer() + +# Then train it! +tokenizer.train([ "./path/to/files/1.txt", "./path/to/files/2.txt" ]) + +# Now, let's use it: +encoded = tokenizer.encode("I can feel the magic, can you?") + +# And finally save it somewhere +tokenizer.save("./path/to/directory/my-bpe.tokenizer.json") +``` + +#### Provided Tokenizers + + - `CharBPETokenizer`: The original BPE + - `ByteLevelBPETokenizer`: The byte level version of the BPE + - `SentencePieceBPETokenizer`: A BPE implementation compatible with the one used by SentencePiece + - `BertWordPieceTokenizer`: The famous Bert tokenizer, using WordPiece + +All of these can be used and trained as explained above! + +### Build your own + +Whenever these provided tokenizers don't give you enough freedom, you can build your own tokenizer, +by putting all the different parts you need together. +You can check how we implemented the [provided tokenizers](https://github.com/huggingface/tokenizers/tree/master/bindings/python/py_src/tokenizers/implementations) and adapt them easily to your own needs. + +#### Building a byte-level BPE + +Here is an example showing how to build your own byte-level BPE by putting all the different pieces +together, and then saving it to a single file: + +```python +from tokenizers import Tokenizer, models, pre_tokenizers, decoders, trainers, processors + +# Initialize a tokenizer +tokenizer = Tokenizer(models.BPE()) + +# Customize pre-tokenization and decoding +tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=True) +tokenizer.decoder = decoders.ByteLevel() +tokenizer.post_processor = processors.ByteLevel(trim_offsets=True) + +# And then train +trainer = trainers.BpeTrainer( + vocab_size=20000, + min_frequency=2, + initial_alphabet=pre_tokenizers.ByteLevel.alphabet() +) +tokenizer.train([ + "./path/to/dataset/1.txt", + "./path/to/dataset/2.txt", + "./path/to/dataset/3.txt" +], trainer=trainer) + +# And Save it +tokenizer.save("byte-level-bpe.tokenizer.json", pretty=True) +``` + +Now, when you want to use this tokenizer, this is as simple as: + +```python +from tokenizers import Tokenizer + +tokenizer = Tokenizer.from_file("byte-level-bpe.tokenizer.json") + +encoded = tokenizer.encode("I can feel the magic, can you?") +``` + +### Typing support and `stub.py` + +The compiled PyO3 extension does not expose type annotations, so editors and type checkers would otherwise see most objects as `Any`. The `stub.py` helper walks the loaded extension modules, renders `.pyi` stub files (plus minimal forwarding `__init__.py` shims), and formats them so that tools like mypy/pyright can understand the public API. Run `python stub.py` whenever you change the Python-visible surface to keep the generated stubs in sync. + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers-0.22.2.dist-info/RECORD b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers-0.22.2.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..9dcf668082e285fdef58afc62c39740aa6a2ea5e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers-0.22.2.dist-info/RECORD @@ -0,0 +1,46 @@ +tokenizers-0.22.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +tokenizers-0.22.2.dist-info/METADATA,sha256=FaXdr0ifWSt34Kk0wO60a1ETCpQGTKEpIyr9sKOGjvw,7254 +tokenizers-0.22.2.dist-info/RECORD,, +tokenizers-0.22.2.dist-info/WHEEL,sha256=5mwg5nCvp3YrLxikUrE5E0HBDKerMOoBBb70NjCncME,143 +tokenizers/__init__.py,sha256=FI7LEi8_7gO-mrsf4hPdhfvGkb8q0rQ3_1MVM3gaajo,2639 +tokenizers/__init__.pyi,sha256=MKWF2m4mz7IG1bPTdJ7AjXkQDNzkmQSLMmACQ2VUYJU,55891 +tokenizers/__pycache__/__init__.cpython-310.pyc,, +tokenizers/decoders/__init__.py,sha256=hfwM6CFUDvlMGGL4-xsaaYz81K9P5rQI5ZL5UHWK8Y4,372 +tokenizers/decoders/__init__.pyi,sha256=T60mFckMbS8YrsonOAPtfvb7VYHUJi9mm47Wd8pT62o,12019 +tokenizers/decoders/__pycache__/__init__.cpython-310.pyc,, +tokenizers/implementations/__init__.py,sha256=VzAsplaIo7rl4AFO8Miu7ig7MfZjvonwVblZw01zR6M,310 +tokenizers/implementations/__pycache__/__init__.cpython-310.pyc,, +tokenizers/implementations/__pycache__/base_tokenizer.cpython-310.pyc,, +tokenizers/implementations/__pycache__/bert_wordpiece.cpython-310.pyc,, +tokenizers/implementations/__pycache__/byte_level_bpe.cpython-310.pyc,, +tokenizers/implementations/__pycache__/char_level_bpe.cpython-310.pyc,, +tokenizers/implementations/__pycache__/sentencepiece_bpe.cpython-310.pyc,, +tokenizers/implementations/__pycache__/sentencepiece_unigram.cpython-310.pyc,, +tokenizers/implementations/base_tokenizer.py,sha256=PtQ2TSmoMGlTpL8oc8fDvwJVIY6isWGmps9comzsWjE,15806 +tokenizers/implementations/bert_wordpiece.py,sha256=sKCum0FKPYdSgJFJN8LDerVBoTDRSqyqSdrcm-lvQqI,5520 +tokenizers/implementations/byte_level_bpe.py,sha256=iBepM_z1s5Ky7zFDVrYLc3L5byYrIouk7-k0JGuF10s,4272 +tokenizers/implementations/char_level_bpe.py,sha256=Nag_HFq8Rvcucqi8MhV1-0xtoR0C7FjHOecFVURL7ss,5449 +tokenizers/implementations/sentencepiece_bpe.py,sha256=c08fKf6i92E2RsKgsxy7LzZfYX8-MACHSRG8U_I5ytY,3721 +tokenizers/implementations/sentencepiece_unigram.py,sha256=2RoIfFVpiMkJOtOCskM_VCeCELWaC_bNnds6GvtE0KQ,7630 +tokenizers/models/__init__.py,sha256=eJZ4HTAQZpxnKILNylWaTFqxXy-Ba6OKswWN47feeV8,176 +tokenizers/models/__init__.pyi,sha256=2gZPQR1Z5_krTzLXx-ts5ai7Fz7bTZ0QI1OSJ5MyOuc,19517 +tokenizers/models/__pycache__/__init__.cpython-310.pyc,, +tokenizers/normalizers/__init__.py,sha256=_06w4cqRItveEgIddYaLMScgkSOkIAMIzYCesb5AA4U,841 +tokenizers/normalizers/__init__.pyi,sha256=6zYmbFtvdF1WhoWQSdEN974mxHjc7ZwJBA0TI2dJk98,25709 +tokenizers/normalizers/__pycache__/__init__.cpython-310.pyc,, +tokenizers/pre_tokenizers/__init__.py,sha256=KV9-EsAykGENUUzkGWCbv4n6YM6hYa1hfnY-gzBpMNE,598 +tokenizers/pre_tokenizers/__init__.pyi,sha256=_pc34-Kd2N7Nvs7vTHPULBKjm18iJRM9qLOClVHw9n4,31566 +tokenizers/pre_tokenizers/__pycache__/__init__.cpython-310.pyc,, +tokenizers/processors/__init__.py,sha256=xM2DEKwKtHIumHsszM8AMkq-AlaqvBZFXWgLU8SNhOY,307 +tokenizers/processors/__init__.pyi,sha256=5L5OBZ7SXCg7AEy51jyDHViaCSHG5c7vW4eWjSVQbUs,14348 +tokenizers/processors/__pycache__/__init__.cpython-310.pyc,, +tokenizers/tokenizers.abi3.so,sha256=wRb88egNRhzgo1wzKXTyWUnoNZQW9Qs9UzcYENLOHMw,10074176 +tokenizers/tokenizers.pyi,sha256=Mq4G5RcxKiVc0FZd_Omi-bT7YQMRc-iDBU_nPCmCZOA,468 +tokenizers/tools/__init__.py,sha256=xG8caB9OHC8cbB01S5vYV14HZxhO6eWbLehsb70ppio,55 +tokenizers/tools/__pycache__/__init__.cpython-310.pyc,, +tokenizers/tools/__pycache__/visualizer.cpython-310.pyc,, +tokenizers/tools/visualizer-styles.css,sha256=zAydq1oGWD8QEll4-eyL8Llw0B1sty_hpIE3tYxL02k,4850 +tokenizers/tools/visualizer.py,sha256=jtxka01phNP47uQSocIQFO_DMnL3ZHdwohGVDqqYJPo,14834 +tokenizers/trainers/__init__.py,sha256=UTu22AGcp76IvpW45xLRbJWET04NxPW6NfCb2YYz0EM,248 +tokenizers/trainers/__init__.pyi,sha256=jKtDNXnoX6FWeCTeHz-W62Cj2_JErgYG7h1PReUz1rU,10719 +tokenizers/trainers/__pycache__/__init__.cpython-310.pyc,, diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers-0.22.2.dist-info/WHEEL b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers-0.22.2.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..323110c9487be1c50bc2f1c4e93b2ddbd7d02233 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers-0.22.2.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: maturin (1.10.2) +Root-Is-Purelib: false +Tag: cp39-abi3-manylinux_2_17_x86_64 +Tag: cp39-abi3-manylinux2014_x86_64 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d689252a22fb15c409ed0355d0b949d24948bc37 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/__init__.py @@ -0,0 +1,100 @@ +from enum import Enum +from typing import List, Tuple, Union + + +Offsets = Tuple[int, int] + +TextInputSequence = str +"""A :obj:`str` that represents an input sequence """ + +PreTokenizedInputSequence = Union[List[str], Tuple[str]] +"""A pre-tokenized input sequence. Can be one of: + + - A :obj:`List` of :obj:`str` + - A :obj:`Tuple` of :obj:`str` +""" + +TextEncodeInput = Union[ + TextInputSequence, + Tuple[TextInputSequence, TextInputSequence], + List[TextInputSequence], +] +"""Represents a textual input for encoding. Can be either: + + - A single sequence: :data:`~tokenizers.TextInputSequence` + - A pair of sequences: + + - A :obj:`Tuple` of :data:`~tokenizers.TextInputSequence` + - Or a :obj:`List` of :data:`~tokenizers.TextInputSequence` of size 2 +""" + +PreTokenizedEncodeInput = Union[ + PreTokenizedInputSequence, + Tuple[PreTokenizedInputSequence, PreTokenizedInputSequence], + List[PreTokenizedInputSequence], +] +"""Represents a pre-tokenized input for encoding. Can be either: + + - A single sequence: :data:`~tokenizers.PreTokenizedInputSequence` + - A pair of sequences: + + - A :obj:`Tuple` of :data:`~tokenizers.PreTokenizedInputSequence` + - Or a :obj:`List` of :data:`~tokenizers.PreTokenizedInputSequence` of size 2 +""" + +InputSequence = Union[TextInputSequence, PreTokenizedInputSequence] +"""Represents all the possible types of input sequences for encoding. Can be: + + - When ``is_pretokenized=False``: :data:`~TextInputSequence` + - When ``is_pretokenized=True``: :data:`~PreTokenizedInputSequence` +""" + +EncodeInput = Union[TextEncodeInput, PreTokenizedEncodeInput] +"""Represents all the possible types of input for encoding. Can be: + + - When ``is_pretokenized=False``: :data:`~TextEncodeInput` + - When ``is_pretokenized=True``: :data:`~PreTokenizedEncodeInput` +""" + + +class OffsetReferential(Enum): + ORIGINAL = "original" + NORMALIZED = "normalized" + + +class OffsetType(Enum): + BYTE = "byte" + CHAR = "char" + + +class SplitDelimiterBehavior(Enum): + REMOVED = "removed" + ISOLATED = "isolated" + MERGED_WITH_PREVIOUS = "merged_with_previous" + MERGED_WITH_NEXT = "merged_with_next" + CONTIGUOUS = "contiguous" + + +from .tokenizers import ( # type: ignore[import] + AddedToken, + Encoding, + NormalizedString, + PreTokenizedString, + Regex, + Token, + Tokenizer, + decoders, + models, + normalizers, + pre_tokenizers, + processors, + trainers, + __version__, +) +from .implementations import ( + BertWordPieceTokenizer, + ByteLevelBPETokenizer, + CharBPETokenizer, + SentencePieceBPETokenizer, + SentencePieceUnigramTokenizer, +) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/__init__.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..44f19b8a442e4d769ca5e4f7452a25d624a4049f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/__init__.pyi @@ -0,0 +1,1800 @@ +# Generated content DO NOT EDIT +class AddedToken: + """ + Represents a token that can be be added to a :class:`~tokenizers.Tokenizer`. + It can have special options that defines the way it should behave. + + Args: + content (:obj:`str`): The content of the token + + single_word (:obj:`bool`, defaults to :obj:`False`): + Defines whether this token should only match single words. If :obj:`True`, this + token will never match inside of a word. For example the token ``ing`` would match + on ``tokenizing`` if this option is :obj:`False`, but not if it is :obj:`True`. + The notion of "`inside of a word`" is defined by the word boundaries pattern in + regular expressions (ie. the token should start and end with word boundaries). + + lstrip (:obj:`bool`, defaults to :obj:`False`): + Defines whether this token should strip all potential whitespaces on its left side. + If :obj:`True`, this token will greedily match any whitespace on its left. For + example if we try to match the token ``[MASK]`` with ``lstrip=True``, in the text + ``"I saw a [MASK]"``, we would match on ``" [MASK]"``. (Note the space on the left). + + rstrip (:obj:`bool`, defaults to :obj:`False`): + Defines whether this token should strip all potential whitespaces on its right + side. If :obj:`True`, this token will greedily match any whitespace on its right. + It works just like :obj:`lstrip` but on the right. + + normalized (:obj:`bool`, defaults to :obj:`True` with :meth:`~tokenizers.Tokenizer.add_tokens` and :obj:`False` with :meth:`~tokenizers.Tokenizer.add_special_tokens`): + Defines whether this token should match against the normalized version of the input + text. For example, with the added token ``"yesterday"``, and a normalizer in charge of + lowercasing the text, the token could be extract from the input ``"I saw a lion + Yesterday"``. + special (:obj:`bool`, defaults to :obj:`False` with :meth:`~tokenizers.Tokenizer.add_tokens` and :obj:`False` with :meth:`~tokenizers.Tokenizer.add_special_tokens`): + Defines whether this token should be skipped when decoding. + + """ + def __init__(self, content=None, single_word=False, lstrip=False, rstrip=False, normalized=True, special=False): + pass + + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + + @property + def content(self): + """ + Get the content of this :obj:`AddedToken` + """ + pass + + @content.setter + def content(self, value): + """ + Get the content of this :obj:`AddedToken` + """ + pass + + @property + def lstrip(self): + """ + Get the value of the :obj:`lstrip` option + """ + pass + + @lstrip.setter + def lstrip(self, value): + """ + Get the value of the :obj:`lstrip` option + """ + pass + + @property + def normalized(self): + """ + Get the value of the :obj:`normalized` option + """ + pass + + @normalized.setter + def normalized(self, value): + """ + Get the value of the :obj:`normalized` option + """ + pass + + @property + def rstrip(self): + """ + Get the value of the :obj:`rstrip` option + """ + pass + + @rstrip.setter + def rstrip(self, value): + """ + Get the value of the :obj:`rstrip` option + """ + pass + + @property + def single_word(self): + """ + Get the value of the :obj:`single_word` option + """ + pass + + @single_word.setter + def single_word(self, value): + """ + Get the value of the :obj:`single_word` option + """ + pass + + @property + def special(self): + """ + Get the value of the :obj:`special` option + """ + pass + + @special.setter + def special(self, value): + """ + Get the value of the :obj:`special` option + """ + pass + +class Encoding: + """ + The :class:`~tokenizers.Encoding` represents the output of a :class:`~tokenizers.Tokenizer`. + """ + def __init__(self): + pass + + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + + @property + def attention_mask(self): + """ + The attention mask + + This indicates to the LM which tokens should be attended to, and which should not. + This is especially important when batching sequences, where we need to applying + padding. + + Returns: + :obj:`List[int]`: The attention mask + """ + pass + + @attention_mask.setter + def attention_mask(self, value): + """ + The attention mask + + This indicates to the LM which tokens should be attended to, and which should not. + This is especially important when batching sequences, where we need to applying + padding. + + Returns: + :obj:`List[int]`: The attention mask + """ + pass + + def char_to_token(self, char_pos, sequence_index=0): + """ + Get the token that contains the char at the given position in the input sequence. + + Args: + char_pos (:obj:`int`): + The position of a char in the input string + sequence_index (:obj:`int`, defaults to :obj:`0`): + The index of the sequence that contains the target char + + Returns: + :obj:`int`: The index of the token that contains this char in the encoded sequence + """ + pass + + def char_to_word(self, char_pos, sequence_index=0): + """ + Get the word that contains the char at the given position in the input sequence. + + Args: + char_pos (:obj:`int`): + The position of a char in the input string + sequence_index (:obj:`int`, defaults to :obj:`0`): + The index of the sequence that contains the target char + + Returns: + :obj:`int`: The index of the word that contains this char in the input sequence + """ + pass + + @property + def ids(self): + """ + The generated IDs + + The IDs are the main input to a Language Model. They are the token indices, + the numerical representations that a LM understands. + + Returns: + :obj:`List[int]`: The list of IDs + """ + pass + + @ids.setter + def ids(self, value): + """ + The generated IDs + + The IDs are the main input to a Language Model. They are the token indices, + the numerical representations that a LM understands. + + Returns: + :obj:`List[int]`: The list of IDs + """ + pass + + @staticmethod + def merge(encodings, growing_offsets=True): + """ + Merge the list of encodings into one final :class:`~tokenizers.Encoding` + + Args: + encodings (A :obj:`List` of :class:`~tokenizers.Encoding`): + The list of encodings that should be merged in one + + growing_offsets (:obj:`bool`, defaults to :obj:`True`): + Whether the offsets should accumulate while merging + + Returns: + :class:`~tokenizers.Encoding`: The resulting Encoding + """ + pass + + @property + def n_sequences(self): + """ + The number of sequences represented + + Returns: + :obj:`int`: The number of sequences in this :class:`~tokenizers.Encoding` + """ + pass + + @n_sequences.setter + def n_sequences(self, value): + """ + The number of sequences represented + + Returns: + :obj:`int`: The number of sequences in this :class:`~tokenizers.Encoding` + """ + pass + + @property + def offsets(self): + """ + The offsets associated to each token + + These offsets let's you slice the input string, and thus retrieve the original + part that led to producing the corresponding token. + + Returns: + A :obj:`List` of :obj:`Tuple[int, int]`: The list of offsets + """ + pass + + @offsets.setter + def offsets(self, value): + """ + The offsets associated to each token + + These offsets let's you slice the input string, and thus retrieve the original + part that led to producing the corresponding token. + + Returns: + A :obj:`List` of :obj:`Tuple[int, int]`: The list of offsets + """ + pass + + @property + def overflowing(self): + """ + A :obj:`List` of overflowing :class:`~tokenizers.Encoding` + + When using truncation, the :class:`~tokenizers.Tokenizer` takes care of splitting + the output into as many pieces as required to match the specified maximum length. + This field lets you retrieve all the subsequent pieces. + + When you use pairs of sequences, the overflowing pieces will contain enough + variations to cover all the possible combinations, while respecting the provided + maximum length. + """ + pass + + @overflowing.setter + def overflowing(self, value): + """ + A :obj:`List` of overflowing :class:`~tokenizers.Encoding` + + When using truncation, the :class:`~tokenizers.Tokenizer` takes care of splitting + the output into as many pieces as required to match the specified maximum length. + This field lets you retrieve all the subsequent pieces. + + When you use pairs of sequences, the overflowing pieces will contain enough + variations to cover all the possible combinations, while respecting the provided + maximum length. + """ + pass + + def pad(self, length, direction="right", pad_id=0, pad_type_id=0, pad_token="[PAD]"): + """ + Pad the :class:`~tokenizers.Encoding` at the given length + + Args: + length (:obj:`int`): + The desired length + + direction: (:obj:`str`, defaults to :obj:`right`): + The expected padding direction. Can be either :obj:`right` or :obj:`left` + + pad_id (:obj:`int`, defaults to :obj:`0`): + The ID corresponding to the padding token + + pad_type_id (:obj:`int`, defaults to :obj:`0`): + The type ID corresponding to the padding token + + pad_token (:obj:`str`, defaults to `[PAD]`): + The pad token to use + """ + pass + + @property + def sequence_ids(self): + """ + The generated sequence indices. + + They represent the index of the input sequence associated to each token. + The sequence id can be None if the token is not related to any input sequence, + like for example with special tokens. + + Returns: + A :obj:`List` of :obj:`Optional[int]`: A list of optional sequence index. + """ + pass + + @sequence_ids.setter + def sequence_ids(self, value): + """ + The generated sequence indices. + + They represent the index of the input sequence associated to each token. + The sequence id can be None if the token is not related to any input sequence, + like for example with special tokens. + + Returns: + A :obj:`List` of :obj:`Optional[int]`: A list of optional sequence index. + """ + pass + + def set_sequence_id(self, sequence_id): + """ + Set the given sequence index + + Set the given sequence index for the whole range of tokens contained in this + :class:`~tokenizers.Encoding`. + """ + pass + + @property + def special_tokens_mask(self): + """ + The special token mask + + This indicates which tokens are special tokens, and which are not. + + Returns: + :obj:`List[int]`: The special tokens mask + """ + pass + + @special_tokens_mask.setter + def special_tokens_mask(self, value): + """ + The special token mask + + This indicates which tokens are special tokens, and which are not. + + Returns: + :obj:`List[int]`: The special tokens mask + """ + pass + + def token_to_chars(self, token_index): + """ + Get the offsets of the token at the given index. + + The returned offsets are related to the input sequence that contains the + token. In order to determine in which input sequence it belongs, you + must call :meth:`~tokenizers.Encoding.token_to_sequence()`. + + Args: + token_index (:obj:`int`): + The index of a token in the encoded sequence. + + Returns: + :obj:`Tuple[int, int]`: The token offsets :obj:`(first, last + 1)` + """ + pass + + def token_to_sequence(self, token_index): + """ + Get the index of the sequence represented by the given token. + + In the general use case, this method returns :obj:`0` for a single sequence or + the first sequence of a pair, and :obj:`1` for the second sequence of a pair + + Args: + token_index (:obj:`int`): + The index of a token in the encoded sequence. + + Returns: + :obj:`int`: The sequence id of the given token + """ + pass + + def token_to_word(self, token_index): + """ + Get the index of the word that contains the token in one of the input sequences. + + The returned word index is related to the input sequence that contains + the token. In order to determine in which input sequence it belongs, you + must call :meth:`~tokenizers.Encoding.token_to_sequence()`. + + Args: + token_index (:obj:`int`): + The index of a token in the encoded sequence. + + Returns: + :obj:`int`: The index of the word in the relevant input sequence. + """ + pass + + @property + def tokens(self): + """ + The generated tokens + + They are the string representation of the IDs. + + Returns: + :obj:`List[str]`: The list of tokens + """ + pass + + @tokens.setter + def tokens(self, value): + """ + The generated tokens + + They are the string representation of the IDs. + + Returns: + :obj:`List[str]`: The list of tokens + """ + pass + + def truncate(self, max_length, stride=0, direction="right"): + """ + Truncate the :class:`~tokenizers.Encoding` at the given length + + If this :class:`~tokenizers.Encoding` represents multiple sequences, when truncating + this information is lost. It will be considered as representing a single sequence. + + Args: + max_length (:obj:`int`): + The desired length + + stride (:obj:`int`, defaults to :obj:`0`): + The length of previous content to be included in each overflowing piece + + direction (:obj:`str`, defaults to :obj:`right`): + Truncate direction + """ + pass + + @property + def type_ids(self): + """ + The generated type IDs + + Generally used for tasks like sequence classification or question answering, + these tokens let the LM know which input sequence corresponds to each tokens. + + Returns: + :obj:`List[int]`: The list of type ids + """ + pass + + @type_ids.setter + def type_ids(self, value): + """ + The generated type IDs + + Generally used for tasks like sequence classification or question answering, + these tokens let the LM know which input sequence corresponds to each tokens. + + Returns: + :obj:`List[int]`: The list of type ids + """ + pass + + @property + def word_ids(self): + """ + The generated word indices. + + They represent the index of the word associated to each token. + When the input is pre-tokenized, they correspond to the ID of the given input label, + otherwise they correspond to the words indices as defined by the + :class:`~tokenizers.pre_tokenizers.PreTokenizer` that was used. + + For special tokens and such (any token that was generated from something that was + not part of the input), the output is :obj:`None` + + Returns: + A :obj:`List` of :obj:`Optional[int]`: A list of optional word index. + """ + pass + + @word_ids.setter + def word_ids(self, value): + """ + The generated word indices. + + They represent the index of the word associated to each token. + When the input is pre-tokenized, they correspond to the ID of the given input label, + otherwise they correspond to the words indices as defined by the + :class:`~tokenizers.pre_tokenizers.PreTokenizer` that was used. + + For special tokens and such (any token that was generated from something that was + not part of the input), the output is :obj:`None` + + Returns: + A :obj:`List` of :obj:`Optional[int]`: A list of optional word index. + """ + pass + + def word_to_chars(self, word_index, sequence_index=0): + """ + Get the offsets of the word at the given index in one of the input sequences. + + Args: + word_index (:obj:`int`): + The index of a word in one of the input sequences. + sequence_index (:obj:`int`, defaults to :obj:`0`): + The index of the sequence that contains the target word + + Returns: + :obj:`Tuple[int, int]`: The range of characters (span) :obj:`(first, last + 1)` + """ + pass + + def word_to_tokens(self, word_index, sequence_index=0): + """ + Get the encoded tokens corresponding to the word at the given index + in one of the input sequences. + + Args: + word_index (:obj:`int`): + The index of a word in one of the input sequences. + sequence_index (:obj:`int`, defaults to :obj:`0`): + The index of the sequence that contains the target word + + Returns: + :obj:`Tuple[int, int]`: The range of tokens: :obj:`(first, last + 1)` + """ + pass + + @property + def words(self): + """ + The generated word indices. + + .. warning:: + This is deprecated and will be removed in a future version. + Please use :obj:`~tokenizers.Encoding.word_ids` instead. + + They represent the index of the word associated to each token. + When the input is pre-tokenized, they correspond to the ID of the given input label, + otherwise they correspond to the words indices as defined by the + :class:`~tokenizers.pre_tokenizers.PreTokenizer` that was used. + + For special tokens and such (any token that was generated from something that was + not part of the input), the output is :obj:`None` + + Returns: + A :obj:`List` of :obj:`Optional[int]`: A list of optional word index. + """ + pass + + @words.setter + def words(self, value): + """ + The generated word indices. + + .. warning:: + This is deprecated and will be removed in a future version. + Please use :obj:`~tokenizers.Encoding.word_ids` instead. + + They represent the index of the word associated to each token. + When the input is pre-tokenized, they correspond to the ID of the given input label, + otherwise they correspond to the words indices as defined by the + :class:`~tokenizers.pre_tokenizers.PreTokenizer` that was used. + + For special tokens and such (any token that was generated from something that was + not part of the input), the output is :obj:`None` + + Returns: + A :obj:`List` of :obj:`Optional[int]`: A list of optional word index. + """ + pass + +class NormalizedString: + """ + NormalizedString + + A NormalizedString takes care of modifying an "original" string, to obtain a "normalized" one. + While making all the requested modifications, it keeps track of the alignment information + between the two versions of the string. + + Args: + sequence: str: + The string sequence used to initialize this NormalizedString + """ + def __init__(self, sequence): + pass + + def __getitem__(self, key): + """ + Return self[key]. + """ + pass + + def __getstate__(self, /): + """ + Helper for pickle. + """ + pass + + def append(self, s): + """ + Append the given sequence to the string + """ + pass + + def clear(self): + """ + Clears the string + """ + pass + + def filter(self, func): + """ + Filter each character of the string using the given func + """ + pass + + def for_each(self, func): + """ + Calls the given function for each character of the string + """ + pass + + def lowercase(self): + """ + Lowercase the string + """ + pass + + def lstrip(self): + """ + Strip the left of the string + """ + pass + + def map(self, func): + """ + Calls the given function for each character of the string + + Replaces each character of the string using the returned value. Each + returned value **must** be a str of length 1 (ie a character). + """ + pass + + def nfc(self): + """ + Runs the NFC normalization + """ + pass + + def nfd(self): + """ + Runs the NFD normalization + """ + pass + + def nfkc(self): + """ + Runs the NFKC normalization + """ + pass + + def nfkd(self): + """ + Runs the NFKD normalization + """ + pass + + @property + def normalized(self): + """ + The normalized part of the string + """ + pass + + @normalized.setter + def normalized(self, value): + """ + The normalized part of the string + """ + pass + + @property + def original(self): + """ """ + pass + + @original.setter + def original(self, value): + """ """ + pass + + def prepend(self, s): + """ + Prepend the given sequence to the string + """ + pass + + def replace(self, pattern, content): + """ + Replace the content of the given pattern with the provided content + + Args: + pattern: Pattern: + A pattern used to match the string. Usually a string or a Regex + + content: str: + The content to be used as replacement + """ + pass + + def rstrip(self): + """ + Strip the right of the string + """ + pass + + def slice(self, range): + """ + Slice the string using the given range + """ + pass + + def split(self, pattern, behavior): + """ + Split the NormalizedString using the given pattern and the specified behavior + + Args: + pattern: Pattern: + A pattern used to split the string. Usually a string or a regex built with `tokenizers.Regex` + + behavior: SplitDelimiterBehavior: + The behavior to use when splitting. + Choices: "removed", "isolated", "merged_with_previous", "merged_with_next", + "contiguous" + + Returns: + A list of NormalizedString, representing each split + """ + pass + + def strip(self): + """ + Strip both ends of the string + """ + pass + + def uppercase(self): + """ + Uppercase the string + """ + pass + +class PreTokenizedString: + """ + PreTokenizedString + + Wrapper over a string, that provides a way to normalize, pre-tokenize, tokenize the + underlying string, while keeping track of the alignment information (offsets). + + The PreTokenizedString manages what we call `splits`. Each split represents a substring + which is a subpart of the original string, with the relevant offsets and tokens. + + When calling one of the methods used to modify the PreTokenizedString (namely one of + `split`, `normalize` or `tokenize), only the `splits` that don't have any associated + tokens will get modified. + + Args: + sequence: str: + The string sequence used to initialize this PreTokenizedString + """ + def __init__(self, sequence): + pass + + def __getstate__(self, /): + """ + Helper for pickle. + """ + pass + + def get_splits(self, offset_referential="original", offset_type="char"): + """ + Get the splits currently managed by the PreTokenizedString + + Args: + offset_referential: :obj:`str` + Whether the returned splits should have offsets expressed relative + to the original string, or the normalized one. choices: "original", "normalized". + + offset_type: :obj:`str` + Whether the returned splits should have offsets expressed in bytes or chars. + When slicing an str, we usually want to use chars, which is the default value. + Now in some cases it might be interesting to get these offsets expressed in bytes, + so it is possible to change this here. + choices: "char", "bytes" + + Returns + A list of splits + """ + pass + + def normalize(self, func): + """ + Normalize each split of the `PreTokenizedString` using the given `func` + + Args: + func: Callable[[NormalizedString], None]: + The function used to normalize each underlying split. This function + does not need to return anything, just calling the methods on the provided + NormalizedString allow its modification. + """ + pass + + def split(self, func): + """ + Split the PreTokenizedString using the given `func` + + Args: + func: Callable[[index, NormalizedString], List[NormalizedString]]: + The function used to split each underlying split. + It is expected to return a list of `NormalizedString`, that represent the new + splits. If the given `NormalizedString` does not need any splitting, we can + just return it directly. + In order for the offsets to be tracked accurately, any returned `NormalizedString` + should come from calling either `.split` or `.slice` on the received one. + """ + pass + + def to_encoding(self, type_id=0, word_idx=None): + """ + Return an Encoding generated from this PreTokenizedString + + Args: + type_id: int = 0: + The type_id to be used on the generated Encoding. + + word_idx: Optional[int] = None: + An optional word index to be used for each token of this Encoding. If provided, + all the word indices in the generated Encoding will use this value, instead + of the one automatically tracked during pre-tokenization. + + Returns: + An Encoding + """ + pass + + def tokenize(self, func): + """ + Tokenize each split of the `PreTokenizedString` using the given `func` + + Args: + func: Callable[[str], List[Token]]: + The function used to tokenize each underlying split. This function must return + a list of Token generated from the input str. + """ + pass + +class Regex: + """ + Instantiate a new Regex with the given pattern + """ + def __init__(self, pattern): + pass + + def __getstate__(self, /): + """ + Helper for pickle. + """ + pass + +class Token: + def __init__(self, id, value, offsets): + pass + + def __getstate__(self, /): + """ + Helper for pickle. + """ + pass + + def as_tuple(self): + """ """ + pass + + @property + def id(self): + """ """ + pass + + @id.setter + def id(self, value): + """ """ + pass + + @property + def offsets(self): + """ """ + pass + + @offsets.setter + def offsets(self, value): + """ """ + pass + + @property + def value(self): + """ """ + pass + + @value.setter + def value(self, value): + """ """ + pass + +class Tokenizer: + """ + A :obj:`Tokenizer` works as a pipeline. It processes some raw text as input + and outputs an :class:`~tokenizers.Encoding`. + + Args: + model (:class:`~tokenizers.models.Model`): + The core algorithm that this :obj:`Tokenizer` should be using. + + """ + def __init__(self, model): + pass + + def __getnewargs__(self): + """ """ + pass + + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + + def add_special_tokens(self, tokens): + """ + Add the given special tokens to the Tokenizer. + + If these tokens are already part of the vocabulary, it just let the Tokenizer know about + them. If they don't exist, the Tokenizer creates them, giving them a new id. + + These special tokens will never be processed by the model (ie won't be split into + multiple tokens), and they can be removed from the output when decoding. + + Args: + tokens (A :obj:`List` of :class:`~tokenizers.AddedToken` or :obj:`str`): + The list of special tokens we want to add to the vocabulary. Each token can either + be a string or an instance of :class:`~tokenizers.AddedToken` for more + customization. + + Returns: + :obj:`int`: The number of tokens that were created in the vocabulary + """ + pass + + def add_tokens(self, tokens): + """ + Add the given tokens to the vocabulary + + The given tokens are added only if they don't already exist in the vocabulary. + Each token then gets a new attributed id. + + Args: + tokens (A :obj:`List` of :class:`~tokenizers.AddedToken` or :obj:`str`): + The list of tokens we want to add to the vocabulary. Each token can be either a + string or an instance of :class:`~tokenizers.AddedToken` for more customization. + + Returns: + :obj:`int`: The number of tokens that were created in the vocabulary + """ + pass + + def async_decode_batch(self, sequences, skip_special_tokens=True): + """ + Decode a batch of ids back to their corresponding string + + Args: + sequences (:obj:`List` of :obj:`List[int]`): + The batch of sequences we want to decode + + skip_special_tokens (:obj:`bool`, defaults to :obj:`True`): + Whether the special tokens should be removed from the decoded strings + + Returns: + :obj:`List[str]`: A list of decoded strings + """ + pass + + def async_encode(self, sequence, pair=None, is_pretokenized=False, add_special_tokens=True): + """ + Asynchronously encode the given input with character offsets. + + This is an async version of encode that can be awaited in async Python code. + + Example: + Here are some examples of the inputs that are accepted:: + + await async_encode("A single sequence") + + Args: + sequence (:obj:`~tokenizers.InputSequence`): + The main input sequence we want to encode. This sequence can be either raw + text or pre-tokenized, according to the ``is_pretokenized`` argument: + + - If ``is_pretokenized=False``: :class:`~tokenizers.TextInputSequence` + - If ``is_pretokenized=True``: :class:`~tokenizers.PreTokenizedInputSequence` + + pair (:obj:`~tokenizers.InputSequence`, `optional`): + An optional input sequence. The expected format is the same that for ``sequence``. + + is_pretokenized (:obj:`bool`, defaults to :obj:`False`): + Whether the input is already pre-tokenized + + add_special_tokens (:obj:`bool`, defaults to :obj:`True`): + Whether to add the special tokens + + Returns: + :class:`~tokenizers.Encoding`: The encoded result + + """ + pass + + def async_encode_batch(self, input, is_pretokenized=False, add_special_tokens=True): + """ + Asynchronously encode the given batch of inputs with character offsets. + + This is an async version of encode_batch that can be awaited in async Python code. + + Example: + Here are some examples of the inputs that are accepted:: + + await async_encode_batch([ + "A single sequence", + ("A tuple with a sequence", "And its pair"), + [ "A", "pre", "tokenized", "sequence" ], + ([ "A", "pre", "tokenized", "sequence" ], "And its pair") + ]) + + Args: + input (A :obj:`List`/:obj:`Tuple` of :obj:`~tokenizers.EncodeInput`): + A list of single sequences or pair sequences to encode. Each sequence + can be either raw text or pre-tokenized, according to the ``is_pretokenized`` + argument: + + - If ``is_pretokenized=False``: :class:`~tokenizers.TextEncodeInput` + - If ``is_pretokenized=True``: :class:`~tokenizers.PreTokenizedEncodeInput` + + is_pretokenized (:obj:`bool`, defaults to :obj:`False`): + Whether the input is already pre-tokenized + + add_special_tokens (:obj:`bool`, defaults to :obj:`True`): + Whether to add the special tokens + + Returns: + A :obj:`List` of :class:`~tokenizers.Encoding`: The encoded batch + + """ + pass + + def async_encode_batch_fast(self, input, is_pretokenized=False, add_special_tokens=True): + """ + Asynchronously encode the given batch of inputs without tracking character offsets. + + This is an async version of encode_batch_fast that can be awaited in async Python code. + + Example: + Here are some examples of the inputs that are accepted:: + + await async_encode_batch_fast([ + "A single sequence", + ("A tuple with a sequence", "And its pair"), + [ "A", "pre", "tokenized", "sequence" ], + ([ "A", "pre", "tokenized", "sequence" ], "And its pair") + ]) + + Args: + input (A :obj:`List`/:obj:`Tuple` of :obj:`~tokenizers.EncodeInput`): + A list of single sequences or pair sequences to encode. Each sequence + can be either raw text or pre-tokenized, according to the ``is_pretokenized`` + argument: + + - If ``is_pretokenized=False``: :class:`~tokenizers.TextEncodeInput` + - If ``is_pretokenized=True``: :class:`~tokenizers.PreTokenizedEncodeInput` + + is_pretokenized (:obj:`bool`, defaults to :obj:`False`): + Whether the input is already pre-tokenized + + add_special_tokens (:obj:`bool`, defaults to :obj:`True`): + Whether to add the special tokens + + Returns: + A :obj:`List` of :class:`~tokenizers.Encoding`: The encoded batch + + """ + pass + + def decode(self, ids, skip_special_tokens=True): + """ + Decode the given list of ids back to a string + + This is used to decode anything coming back from a Language Model + + Args: + ids (A :obj:`List/Tuple` of :obj:`int`): + The list of ids that we want to decode + + skip_special_tokens (:obj:`bool`, defaults to :obj:`True`): + Whether the special tokens should be removed from the decoded string + + Returns: + :obj:`str`: The decoded string + """ + pass + + def decode_batch(self, sequences, skip_special_tokens=True): + """ + Decode a batch of ids back to their corresponding string + + Args: + sequences (:obj:`List` of :obj:`List[int]`): + The batch of sequences we want to decode + + skip_special_tokens (:obj:`bool`, defaults to :obj:`True`): + Whether the special tokens should be removed from the decoded strings + + Returns: + :obj:`List[str]`: A list of decoded strings + """ + pass + + @property + def decoder(self): + """ + The `optional` :class:`~tokenizers.decoders.Decoder` in use by the Tokenizer + """ + pass + + @decoder.setter + def decoder(self, value): + """ + The `optional` :class:`~tokenizers.decoders.Decoder` in use by the Tokenizer + """ + pass + + def enable_padding( + self, direction="right", pad_id=0, pad_type_id=0, pad_token="[PAD]", length=None, pad_to_multiple_of=None + ): + """ + Enable the padding + + Args: + direction (:obj:`str`, `optional`, defaults to :obj:`right`): + The direction in which to pad. Can be either ``right`` or ``left`` + + pad_to_multiple_of (:obj:`int`, `optional`): + If specified, the padding length should always snap to the next multiple of the + given value. For example if we were going to pad witha length of 250 but + ``pad_to_multiple_of=8`` then we will pad to 256. + + pad_id (:obj:`int`, defaults to 0): + The id to be used when padding + + pad_type_id (:obj:`int`, defaults to 0): + The type id to be used when padding + + pad_token (:obj:`str`, defaults to :obj:`[PAD]`): + The pad token to be used when padding + + length (:obj:`int`, `optional`): + If specified, the length at which to pad. If not specified we pad using the size of + the longest sequence in a batch. + """ + pass + + def enable_truncation(self, max_length, stride=0, strategy="longest_first", direction="right"): + """ + Enable truncation + + Args: + max_length (:obj:`int`): + The max length at which to truncate + + stride (:obj:`int`, `optional`): + The length of the previous first sequence to be included in the overflowing + sequence + + strategy (:obj:`str`, `optional`, defaults to :obj:`longest_first`): + The strategy used to truncation. Can be one of ``longest_first``, ``only_first`` or + ``only_second``. + + direction (:obj:`str`, defaults to :obj:`right`): + Truncate direction + """ + pass + + def encode(self, sequence, pair=None, is_pretokenized=False, add_special_tokens=True): + """ + Encode the given sequence and pair. This method can process raw text sequences + as well as already pre-tokenized sequences. + + Example: + Here are some examples of the inputs that are accepted:: + + encode("A single sequence")` + encode("A sequence", "And its pair")` + encode([ "A", "pre", "tokenized", "sequence" ], is_pretokenized=True)` + encode( + [ "A", "pre", "tokenized", "sequence" ], [ "And", "its", "pair" ], + is_pretokenized=True + ) + + Args: + sequence (:obj:`~tokenizers.InputSequence`): + The main input sequence we want to encode. This sequence can be either raw + text or pre-tokenized, according to the ``is_pretokenized`` argument: + + - If ``is_pretokenized=False``: :class:`~tokenizers.TextInputSequence` + - If ``is_pretokenized=True``: :class:`~tokenizers.PreTokenizedInputSequence` + + pair (:obj:`~tokenizers.InputSequence`, `optional`): + An optional input sequence. The expected format is the same that for ``sequence``. + + is_pretokenized (:obj:`bool`, defaults to :obj:`False`): + Whether the input is already pre-tokenized + + add_special_tokens (:obj:`bool`, defaults to :obj:`True`): + Whether to add the special tokens + + Returns: + :class:`~tokenizers.Encoding`: The encoded result + + """ + pass + + def encode_batch(self, input, is_pretokenized=False, add_special_tokens=True): + """ + Encode the given batch of inputs. This method accept both raw text sequences + as well as already pre-tokenized sequences. The reason we use `PySequence` is + because it allows type checking with zero-cost (according to PyO3) as we don't + have to convert to check. + + Example: + Here are some examples of the inputs that are accepted:: + + encode_batch([ + "A single sequence", + ("A tuple with a sequence", "And its pair"), + [ "A", "pre", "tokenized", "sequence" ], + ([ "A", "pre", "tokenized", "sequence" ], "And its pair") + ]) + + Args: + input (A :obj:`List`/:obj:`Tuple` of :obj:`~tokenizers.EncodeInput`): + A list of single sequences or pair sequences to encode. Each sequence + can be either raw text or pre-tokenized, according to the ``is_pretokenized`` + argument: + + - If ``is_pretokenized=False``: :class:`~tokenizers.TextEncodeInput` + - If ``is_pretokenized=True``: :class:`~tokenizers.PreTokenizedEncodeInput` + + is_pretokenized (:obj:`bool`, defaults to :obj:`False`): + Whether the input is already pre-tokenized + + add_special_tokens (:obj:`bool`, defaults to :obj:`True`): + Whether to add the special tokens + + Returns: + A :obj:`List` of :class:`~tokenizers.Encoding`: The encoded batch + + """ + pass + + def encode_batch_fast(self, input, is_pretokenized=False, add_special_tokens=True): + """ + Encode the given batch of inputs. This method is faster than `encode_batch` + because it doesn't keep track of offsets, they will be all zeros. + + Example: + Here are some examples of the inputs that are accepted:: + + encode_batch_fast([ + "A single sequence", + ("A tuple with a sequence", "And its pair"), + [ "A", "pre", "tokenized", "sequence" ], + ([ "A", "pre", "tokenized", "sequence" ], "And its pair") + ]) + + Args: + input (A :obj:`List`/:obj:`Tuple` of :obj:`~tokenizers.EncodeInput`): + A list of single sequences or pair sequences to encode. Each sequence + can be either raw text or pre-tokenized, according to the ``is_pretokenized`` + argument: + + - If ``is_pretokenized=False``: :class:`~tokenizers.TextEncodeInput` + - If ``is_pretokenized=True``: :class:`~tokenizers.PreTokenizedEncodeInput` + + is_pretokenized (:obj:`bool`, defaults to :obj:`False`): + Whether the input is already pre-tokenized + + add_special_tokens (:obj:`bool`, defaults to :obj:`True`): + Whether to add the special tokens + + Returns: + A :obj:`List` of :class:`~tokenizers.Encoding`: The encoded batch + + """ + pass + + @property + def encode_special_tokens(self): + """ + Modifies the tokenizer in order to use or not the special tokens + during encoding. + + Args: + value (:obj:`bool`): + Whether to use the special tokens or not + + """ + pass + + @encode_special_tokens.setter + def encode_special_tokens(self, value): + """ + Modifies the tokenizer in order to use or not the special tokens + during encoding. + + Args: + value (:obj:`bool`): + Whether to use the special tokens or not + + """ + pass + + @staticmethod + def from_buffer(buffer): + """ + Instantiate a new :class:`~tokenizers.Tokenizer` from the given buffer. + + Args: + buffer (:obj:`bytes`): + A buffer containing a previously serialized :class:`~tokenizers.Tokenizer` + + Returns: + :class:`~tokenizers.Tokenizer`: The new tokenizer + """ + pass + + @staticmethod + def from_file(path): + """ + Instantiate a new :class:`~tokenizers.Tokenizer` from the file at the given path. + + Args: + path (:obj:`str`): + A path to a local JSON file representing a previously serialized + :class:`~tokenizers.Tokenizer` + + Returns: + :class:`~tokenizers.Tokenizer`: The new tokenizer + """ + pass + + @staticmethod + def from_pretrained(identifier, revision="main", token=None): + """ + Instantiate a new :class:`~tokenizers.Tokenizer` from an existing file on the + Hugging Face Hub. + + Args: + identifier (:obj:`str`): + The identifier of a Model on the Hugging Face Hub, that contains + a tokenizer.json file + revision (:obj:`str`, defaults to `main`): + A branch or commit id + token (:obj:`str`, `optional`, defaults to `None`): + An optional auth token used to access private repositories on the + Hugging Face Hub + + Returns: + :class:`~tokenizers.Tokenizer`: The new tokenizer + """ + pass + + @staticmethod + def from_str(json): + """ + Instantiate a new :class:`~tokenizers.Tokenizer` from the given JSON string. + + Args: + json (:obj:`str`): + A valid JSON string representing a previously serialized + :class:`~tokenizers.Tokenizer` + + Returns: + :class:`~tokenizers.Tokenizer`: The new tokenizer + """ + pass + + def get_added_tokens_decoder(self): + """ + Get the underlying vocabulary + + Returns: + :obj:`Dict[int, AddedToken]`: The vocabulary + """ + pass + + def get_vocab(self, with_added_tokens=True): + """ + Get the underlying vocabulary + + Args: + with_added_tokens (:obj:`bool`, defaults to :obj:`True`): + Whether to include the added tokens + + Returns: + :obj:`Dict[str, int]`: The vocabulary + """ + pass + + def get_vocab_size(self, with_added_tokens=True): + """ + Get the size of the underlying vocabulary + + Args: + with_added_tokens (:obj:`bool`, defaults to :obj:`True`): + Whether to include the added tokens + + Returns: + :obj:`int`: The size of the vocabulary + """ + pass + + def id_to_token(self, id): + """ + Convert the given id to its corresponding token if it exists + + Args: + id (:obj:`int`): + The id to convert + + Returns: + :obj:`Optional[str]`: An optional token, :obj:`None` if out of vocabulary + """ + pass + + @property + def model(self): + """ + The :class:`~tokenizers.models.Model` in use by the Tokenizer + """ + pass + + @model.setter + def model(self, value): + """ + The :class:`~tokenizers.models.Model` in use by the Tokenizer + """ + pass + + def no_padding(self): + """ + Disable padding + """ + pass + + def no_truncation(self): + """ + Disable truncation + """ + pass + + @property + def normalizer(self): + """ + The `optional` :class:`~tokenizers.normalizers.Normalizer` in use by the Tokenizer + """ + pass + + @normalizer.setter + def normalizer(self, value): + """ + The `optional` :class:`~tokenizers.normalizers.Normalizer` in use by the Tokenizer + """ + pass + + def num_special_tokens_to_add(self, is_pair): + """ + Return the number of special tokens that would be added for single/pair sentences. + :param is_pair: Boolean indicating if the input would be a single sentence or a pair + :return: + """ + pass + + @property + def padding(self): + """ + Get the current padding parameters + + `Cannot be set, use` :meth:`~tokenizers.Tokenizer.enable_padding` `instead` + + Returns: + (:obj:`dict`, `optional`): + A dict with the current padding parameters if padding is enabled + """ + pass + + @padding.setter + def padding(self, value): + """ + Get the current padding parameters + + `Cannot be set, use` :meth:`~tokenizers.Tokenizer.enable_padding` `instead` + + Returns: + (:obj:`dict`, `optional`): + A dict with the current padding parameters if padding is enabled + """ + pass + + def post_process(self, encoding, pair=None, add_special_tokens=True): + """ + Apply all the post-processing steps to the given encodings. + + The various steps are: + + 1. Truncate according to the set truncation params (provided with + :meth:`~tokenizers.Tokenizer.enable_truncation`) + 2. Apply the :class:`~tokenizers.processors.PostProcessor` + 3. Pad according to the set padding params (provided with + :meth:`~tokenizers.Tokenizer.enable_padding`) + + Args: + encoding (:class:`~tokenizers.Encoding`): + The :class:`~tokenizers.Encoding` corresponding to the main sequence. + + pair (:class:`~tokenizers.Encoding`, `optional`): + An optional :class:`~tokenizers.Encoding` corresponding to the pair sequence. + + add_special_tokens (:obj:`bool`): + Whether to add the special tokens + + Returns: + :class:`~tokenizers.Encoding`: The final post-processed encoding + """ + pass + + @property + def post_processor(self): + """ + The `optional` :class:`~tokenizers.processors.PostProcessor` in use by the Tokenizer + """ + pass + + @post_processor.setter + def post_processor(self, value): + """ + The `optional` :class:`~tokenizers.processors.PostProcessor` in use by the Tokenizer + """ + pass + + @property + def pre_tokenizer(self): + """ + The `optional` :class:`~tokenizers.pre_tokenizers.PreTokenizer` in use by the Tokenizer + """ + pass + + @pre_tokenizer.setter + def pre_tokenizer(self, value): + """ + The `optional` :class:`~tokenizers.pre_tokenizers.PreTokenizer` in use by the Tokenizer + """ + pass + + def save(self, path, pretty=True): + """ + Save the :class:`~tokenizers.Tokenizer` to the file at the given path. + + Args: + path (:obj:`str`): + A path to a file in which to save the serialized tokenizer. + + pretty (:obj:`bool`, defaults to :obj:`True`): + Whether the JSON file should be pretty formatted. + """ + pass + + def to_str(self, pretty=False): + """ + Gets a serialized string representing this :class:`~tokenizers.Tokenizer`. + + Args: + pretty (:obj:`bool`, defaults to :obj:`False`): + Whether the JSON string should be pretty formatted. + + Returns: + :obj:`str`: A string representing the serialized Tokenizer + """ + pass + + def token_to_id(self, token): + """ + Convert the given token to its corresponding id if it exists + + Args: + token (:obj:`str`): + The token to convert + + Returns: + :obj:`Optional[int]`: An optional id, :obj:`None` if out of vocabulary + """ + pass + + def train(self, files, trainer=None): + """ + Train the Tokenizer using the given files. + + Reads the files line by line, while keeping all the whitespace, even new lines. + If you want to train from data store in-memory, you can check + :meth:`~tokenizers.Tokenizer.train_from_iterator` + + Args: + files (:obj:`List[str]`): + A list of path to the files that we should use for training + + trainer (:obj:`~tokenizers.trainers.Trainer`, `optional`): + An optional trainer that should be used to train our Model + """ + pass + + def train_from_iterator(self, iterator, trainer=None, length=None): + """ + Train the Tokenizer using the provided iterator. + + You can provide anything that is a Python Iterator + + * A list of sequences :obj:`List[str]` + * A generator that yields :obj:`str` or :obj:`List[str]` + * A Numpy array of strings + * ... + + Args: + iterator (:obj:`Iterator`): + Any iterator over strings or list of strings + + trainer (:obj:`~tokenizers.trainers.Trainer`, `optional`): + An optional trainer that should be used to train our Model + + length (:obj:`int`, `optional`): + The total number of sequences in the iterator. This is used to + provide meaningful progress tracking + """ + pass + + @property + def truncation(self): + """ + Get the currently set truncation parameters + + `Cannot set, use` :meth:`~tokenizers.Tokenizer.enable_truncation` `instead` + + Returns: + (:obj:`dict`, `optional`): + A dict with the current truncation parameters if truncation is enabled + """ + pass + + @truncation.setter + def truncation(self, value): + """ + Get the currently set truncation parameters + + `Cannot set, use` :meth:`~tokenizers.Tokenizer.enable_truncation` `instead` + + Returns: + (:obj:`dict`, `optional`): + A dict with the current truncation parameters if truncation is enabled + """ + pass + +from enum import Enum +from typing import List, Tuple, Union, Any + +Offsets = Tuple[int, int] +TextInputSequence = str +PreTokenizedInputSequence = Union[List[str], Tuple[str, ...]] +TextEncodeInput = Union[ + TextInputSequence, + Tuple[TextInputSequence, TextInputSequence], + List[TextInputSequence], +] +PreTokenizedEncodeInput = Union[ + PreTokenizedInputSequence, + Tuple[PreTokenizedInputSequence, PreTokenizedInputSequence], + List[PreTokenizedInputSequence], +] +InputSequence = Union[TextInputSequence, PreTokenizedInputSequence] +EncodeInput = Union[TextEncodeInput, PreTokenizedEncodeInput] + +class OffsetReferential(Enum): + ORIGINAL = "original" + NORMALIZED = "normalized" + +class OffsetType(Enum): + BYTE = "byte" + CHAR = "char" + +class SplitDelimiterBehavior(Enum): + REMOVED = "removed" + ISOLATED = "isolated" + MERGED_WITH_PREVIOUS = "merged_with_previous" + MERGED_WITH_NEXT = "merged_with_next" + CONTIGUOUS = "contiguous" + +from .implementations import ( + BertWordPieceTokenizer, + ByteLevelBPETokenizer, + CharBPETokenizer, + SentencePieceBPETokenizer, + SentencePieceUnigramTokenizer, +) + +def __getattr__(name: str) -> Any: ... + +BertWordPieceTokenizer: Any +ByteLevelBPETokenizer: Any +CharBPETokenizer: Any +SentencePieceBPETokenizer: Any +SentencePieceUnigramTokenizer: Any diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/decoders/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/decoders/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..12ada5dbda08f28a2ffc863cb502bd3f25455ded --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/decoders/__init__.py @@ -0,0 +1,15 @@ +from .. import decoders + + +Decoder = decoders.Decoder +ByteLevel = decoders.ByteLevel +Replace = decoders.Replace +WordPiece = decoders.WordPiece +ByteFallback = decoders.ByteFallback +Fuse = decoders.Fuse +Strip = decoders.Strip +Metaspace = decoders.Metaspace +BPEDecoder = decoders.BPEDecoder +CTC = decoders.CTC +Sequence = decoders.Sequence +DecodeStream = decoders.DecodeStream diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/decoders/__init__.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/decoders/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..29fb501c994fccb325192bdfcaf98d3e81d35cd7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/decoders/__init__.pyi @@ -0,0 +1,569 @@ +# Generated content DO NOT EDIT +class DecodeStream: + """ + Class needed for streaming decode + + """ + def __init__(self, ids=None, skip_special_tokens=False): + pass + + def __getstate__(self, /): + """ + Helper for pickle. + """ + pass + + def step(self, tokenizer, id): + """ + Streaming decode step + + Args: + tokenizer (:class:`~tokenizers.Tokenizer`): + The tokenizer to use for decoding + id (:obj:`int` or `List[int]`): + The next token id or list of token ids to add to the stream + + + Returns: + :obj:`Optional[str]`: The next decoded string chunk, or None if not enough + tokens have been provided yet. + """ + pass + +class Decoder: + """ + Base class for all decoders + + This class is not supposed to be instantiated directly. Instead, any implementation of + a Decoder will return an instance of this class when instantiated. + """ + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + + @staticmethod + def custom(decoder): + """ """ + pass + + def decode(self, tokens): + """ + Decode the given list of tokens to a final string + + Args: + tokens (:obj:`List[str]`): + The list of tokens to decode + + Returns: + :obj:`str`: The decoded string + """ + pass + +class BPEDecoder(Decoder): + """ + BPEDecoder Decoder + + Args: + suffix (:obj:`str`, `optional`, defaults to :obj:``): + The suffix that was used to characterize an end-of-word. This suffix will + be replaced by whitespaces during the decoding + """ + def __init__(self, suffix=""): + pass + + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + + @staticmethod + def custom(decoder): + """ """ + pass + + def decode(self, tokens): + """ + Decode the given list of tokens to a final string + + Args: + tokens (:obj:`List[str]`): + The list of tokens to decode + + Returns: + :obj:`str`: The decoded string + """ + pass + + @property + def suffix(self): + """ """ + pass + + @suffix.setter + def suffix(self, value): + """ """ + pass + +class ByteFallback(Decoder): + """ + ByteFallback Decoder + ByteFallback is a simple trick which converts tokens looking like `<0x61>` + to pure bytes, and attempts to make them into a string. If the tokens + cannot be decoded you will get � instead for each inconvertible byte token + + """ + def __init__(self): + pass + + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + + @staticmethod + def custom(decoder): + """ """ + pass + + def decode(self, tokens): + """ + Decode the given list of tokens to a final string + + Args: + tokens (:obj:`List[str]`): + The list of tokens to decode + + Returns: + :obj:`str`: The decoded string + """ + pass + +class ByteLevel(Decoder): + """ + ByteLevel Decoder + + This decoder is to be used in tandem with the :class:`~tokenizers.pre_tokenizers.ByteLevel` + :class:`~tokenizers.pre_tokenizers.PreTokenizer`. + """ + def __init__(self): + pass + + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + + @staticmethod + def custom(decoder): + """ """ + pass + + def decode(self, tokens): + """ + Decode the given list of tokens to a final string + + Args: + tokens (:obj:`List[str]`): + The list of tokens to decode + + Returns: + :obj:`str`: The decoded string + """ + pass + +class CTC(Decoder): + """ + CTC Decoder + + Args: + pad_token (:obj:`str`, `optional`, defaults to :obj:``): + The pad token used by CTC to delimit a new token. + word_delimiter_token (:obj:`str`, `optional`, defaults to :obj:`|`): + The word delimiter token. It will be replaced by a + cleanup (:obj:`bool`, `optional`, defaults to :obj:`True`): + Whether to cleanup some tokenization artifacts. + Mainly spaces before punctuation, and some abbreviated english forms. + """ + def __init__(self, pad_token="", word_delimiter_token="|", cleanup=True): + pass + + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + + @property + def cleanup(self): + """ """ + pass + + @cleanup.setter + def cleanup(self, value): + """ """ + pass + + @staticmethod + def custom(decoder): + """ """ + pass + + def decode(self, tokens): + """ + Decode the given list of tokens to a final string + + Args: + tokens (:obj:`List[str]`): + The list of tokens to decode + + Returns: + :obj:`str`: The decoded string + """ + pass + + @property + def pad_token(self): + """ """ + pass + + @pad_token.setter + def pad_token(self, value): + """ """ + pass + + @property + def word_delimiter_token(self): + """ """ + pass + + @word_delimiter_token.setter + def word_delimiter_token(self, value): + """ """ + pass + +class Fuse(Decoder): + """ + Fuse Decoder + Fuse simply fuses every token into a single string. + This is the last step of decoding, this decoder exists only if + there is need to add other decoders *after* the fusion + """ + def __init__(self): + pass + + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + + @staticmethod + def custom(decoder): + """ """ + pass + + def decode(self, tokens): + """ + Decode the given list of tokens to a final string + + Args: + tokens (:obj:`List[str]`): + The list of tokens to decode + + Returns: + :obj:`str`: The decoded string + """ + pass + +class Metaspace(Decoder): + """ + Metaspace Decoder + + Args: + replacement (:obj:`str`, `optional`, defaults to :obj:`▁`): + The replacement character. Must be exactly one character. By default we + use the `▁` (U+2581) meta symbol (Same as in SentencePiece). + + prepend_scheme (:obj:`str`, `optional`, defaults to :obj:`"always"`): + Whether to add a space to the first word if there isn't already one. This + lets us treat `hello` exactly like `say hello`. + Choices: "always", "never", "first". First means the space is only added on the first + token (relevant when special tokens are used or other pre_tokenizer are used). + """ + def __init__(self, replacement="▁", prepend_scheme="always", split=True): + pass + + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + + @staticmethod + def custom(decoder): + """ """ + pass + + def decode(self, tokens): + """ + Decode the given list of tokens to a final string + + Args: + tokens (:obj:`List[str]`): + The list of tokens to decode + + Returns: + :obj:`str`: The decoded string + """ + pass + + @property + def prepend_scheme(self): + """ """ + pass + + @prepend_scheme.setter + def prepend_scheme(self, value): + """ """ + pass + + @property + def replacement(self): + """ """ + pass + + @replacement.setter + def replacement(self, value): + """ """ + pass + + @property + def split(self): + """ """ + pass + + @split.setter + def split(self, value): + """ """ + pass + +class Replace(Decoder): + """ + Replace Decoder + + This decoder is to be used in tandem with the :class:`~tokenizers.pre_tokenizers.Replace` + :class:`~tokenizers.pre_tokenizers.PreTokenizer`. + """ + def __init__(self, pattern, content): + pass + + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + + @staticmethod + def custom(decoder): + """ """ + pass + + def decode(self, tokens): + """ + Decode the given list of tokens to a final string + + Args: + tokens (:obj:`List[str]`): + The list of tokens to decode + + Returns: + :obj:`str`: The decoded string + """ + pass + +class Sequence(Decoder): + """ + Sequence Decoder + + Args: + decoders (:obj:`List[Decoder]`) + The decoders that need to be chained + """ + def __init__(self, decoders): + pass + + def __getnewargs__(self): + """ """ + pass + + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + + @staticmethod + def custom(decoder): + """ """ + pass + + def decode(self, tokens): + """ + Decode the given list of tokens to a final string + + Args: + tokens (:obj:`List[str]`): + The list of tokens to decode + + Returns: + :obj:`str`: The decoded string + """ + pass + +class Strip(Decoder): + """ + Strip normalizer + Strips n left characters of each token, or n right characters of each token + """ + def __init__(self, content=" ", left=0, right=0): + pass + + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + + @property + def content(self): + """ """ + pass + + @content.setter + def content(self, value): + """ """ + pass + + @staticmethod + def custom(decoder): + """ """ + pass + + def decode(self, tokens): + """ + Decode the given list of tokens to a final string + + Args: + tokens (:obj:`List[str]`): + The list of tokens to decode + + Returns: + :obj:`str`: The decoded string + """ + pass + + @property + def start(self): + """ """ + pass + + @start.setter + def start(self, value): + """ """ + pass + + @property + def stop(self): + """ """ + pass + + @stop.setter + def stop(self, value): + """ """ + pass + +class WordPiece(Decoder): + """ + WordPiece Decoder + + Args: + prefix (:obj:`str`, `optional`, defaults to :obj:`##`): + The prefix to use for subwords that are not a beginning-of-word + + cleanup (:obj:`bool`, `optional`, defaults to :obj:`True`): + Whether to cleanup some tokenization artifacts. Mainly spaces before punctuation, + and some abbreviated english forms. + """ + def __init__(self, prefix="##", cleanup=True): + pass + + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + + @property + def cleanup(self): + """ """ + pass + + @cleanup.setter + def cleanup(self, value): + """ """ + pass + + @staticmethod + def custom(decoder): + """ """ + pass + + def decode(self, tokens): + """ + Decode the given list of tokens to a final string + + Args: + tokens (:obj:`List[str]`): + The list of tokens to decode + + Returns: + :obj:`str`: The decoded string + """ + pass + + @property + def prefix(self): + """ """ + pass + + @prefix.setter + def prefix(self, value): + """ """ + pass diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/implementations/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/implementations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7e775892d04a91d645653ea9015954b7985d3147 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/implementations/__init__.py @@ -0,0 +1,6 @@ +from .base_tokenizer import BaseTokenizer +from .bert_wordpiece import BertWordPieceTokenizer +from .byte_level_bpe import ByteLevelBPETokenizer +from .char_level_bpe import CharBPETokenizer +from .sentencepiece_bpe import SentencePieceBPETokenizer +from .sentencepiece_unigram import SentencePieceUnigramTokenizer diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/implementations/base_tokenizer.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/implementations/base_tokenizer.py new file mode 100644 index 0000000000000000000000000000000000000000..c2e7effb4cfeeef4a4cf060ebcfdd4a4c420a7a4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/implementations/base_tokenizer.py @@ -0,0 +1,459 @@ +from typing import Dict, List, Optional, Tuple, Union + +from tokenizers import AddedToken, EncodeInput, Encoding, InputSequence, Tokenizer +from tokenizers.decoders import Decoder +from tokenizers.models import Model +from tokenizers.normalizers import Normalizer +from tokenizers.pre_tokenizers import PreTokenizer +from tokenizers.processors import PostProcessor + + +Offsets = Tuple[int, int] + + +class BaseTokenizer: + def __init__(self, tokenizer: Tokenizer, parameters=None): + self._tokenizer = tokenizer + self._parameters = parameters if parameters is not None else {} + + def __repr__(self): + return "Tokenizer(vocabulary_size={}, {})".format( + self._tokenizer.get_vocab_size(), + ", ".join(k + "=" + str(v) for k, v in self._parameters.items()), + ) + + def num_special_tokens_to_add(self, is_pair: bool) -> int: + """ + Return the number of special tokens that would be added for single/pair sentences. + :param is_pair: Boolean indicating if the input would be a single sentence or a pair + :return: + """ + return self._tokenizer.num_special_tokens_to_add(is_pair) + + def get_vocab(self, with_added_tokens: bool = True) -> Dict[str, int]: + """Returns the vocabulary + + Args: + with_added_tokens: boolean: + Whether to include the added tokens in the vocabulary + + Returns: + The vocabulary + """ + return self._tokenizer.get_vocab(with_added_tokens=with_added_tokens) + + def get_added_tokens_decoder(self) -> Dict[int, AddedToken]: + """Returns the added reverse vocabulary + + Returns: + The added vocabulary mapping ints to AddedTokens + """ + return self._tokenizer.get_added_tokens_decoder() + + def get_vocab_size(self, with_added_tokens: bool = True) -> int: + """Return the size of vocabulary, with or without added tokens. + + Args: + with_added_tokens: (`optional`) bool: + Whether to count in added special tokens or not + + Returns: + Size of vocabulary + """ + return self._tokenizer.get_vocab_size(with_added_tokens=with_added_tokens) + + def enable_padding( + self, + direction: Optional[str] = "right", + pad_to_multiple_of: Optional[int] = None, + pad_id: Optional[int] = 0, + pad_type_id: Optional[int] = 0, + pad_token: Optional[str] = "[PAD]", + length: Optional[int] = None, + ): + """Change the padding strategy + + Args: + direction: (`optional`) str: + Can be one of: `right` or `left` + + pad_to_multiple_of: (`optional`) unsigned int: + If specified, the padding length should always snap to the next multiple of + the given value. For example if we were going to pad with a length of 250 but + `pad_to_multiple_of=8` then we will pad to 256. + + pad_id: (`optional`) unsigned int: + The indice to be used when padding + + pad_type_id: (`optional`) unsigned int: + The type indice to be used when padding + + pad_token: (`optional`) str: + The pad token to be used when padding + + length: (`optional`) unsigned int: + If specified, the length at which to pad. If not specified + we pad using the size of the longest sequence in a batch + """ + return self._tokenizer.enable_padding( + direction=direction, + pad_to_multiple_of=pad_to_multiple_of, + pad_id=pad_id, + pad_type_id=pad_type_id, + pad_token=pad_token, + length=length, + ) + + def no_padding(self): + """Disable padding""" + return self._tokenizer.no_padding() + + @property + def padding(self) -> Optional[dict]: + """Get the current padding parameters + + Returns: + None if padding is disabled, a dict with the currently set parameters + if the padding is enabled. + """ + return self._tokenizer.padding + + def enable_truncation(self, max_length: int, stride: Optional[int] = 0, strategy: Optional[str] = "longest_first"): + """Change the truncation options + + Args: + max_length: unsigned int: + The maximum length at which to truncate + + stride: (`optional`) unsigned int: + The length of the previous first sequence to be included + in the overflowing sequence + + strategy: (`optional`) str: + Can be one of `longest_first`, `only_first` or `only_second` + """ + return self._tokenizer.enable_truncation(max_length, stride=stride, strategy=strategy) + + def no_truncation(self): + """Disable truncation""" + return self._tokenizer.no_truncation() + + @property + def truncation(self) -> Optional[dict]: + """Get the current truncation parameters + + Returns: + None if truncation is disabled, a dict with the current truncation parameters if + truncation is enabled + """ + return self._tokenizer.truncation + + def add_tokens(self, tokens: List[Union[str, AddedToken]]) -> int: + """Add the given tokens to the vocabulary + + Args: + tokens: List[Union[str, AddedToken]]: + A list of tokens to add to the vocabulary. Each token can either be + a string, or an instance of AddedToken + + Returns: + The number of tokens that were added to the vocabulary + """ + return self._tokenizer.add_tokens(tokens) + + def add_special_tokens(self, special_tokens: List[Union[str, AddedToken]]) -> int: + """Add the given special tokens to the vocabulary, and treat them as special tokens. + + The special tokens will never be processed by the model, and will be + removed while decoding. + + Args: + tokens: List[Union[str, AddedToken]]: + A list of special tokens to add to the vocabulary. Each token can either be + a string, or an instance of AddedToken + + Returns: + The number of tokens that were added to the vocabulary + """ + return self._tokenizer.add_special_tokens(special_tokens) + + def normalize(self, sequence: str) -> str: + """Normalize the given sequence + + Args: + sequence: str: + The sequence to normalize + + Returns: + The normalized string + """ + return self._tokenizer.normalizer.normalize_str(sequence) + + def encode( + self, + sequence: InputSequence, + pair: Optional[InputSequence] = None, + is_pretokenized: bool = False, + add_special_tokens: bool = True, + ) -> Encoding: + """Encode the given sequence and pair. This method can process raw text sequences as well + as already pre-tokenized sequences. + + Args: + sequence: InputSequence: + The sequence we want to encode. This sequence can be either raw text or + pre-tokenized, according to the `is_pretokenized` argument: + + - If `is_pretokenized=False`: `InputSequence` is expected to be `str` + - If `is_pretokenized=True`: `InputSequence` is expected to be + `Union[List[str], Tuple[str]]` + + is_pretokenized: bool: + Whether the input is already pre-tokenized. + + add_special_tokens: bool: + Whether to add the special tokens while encoding. + + Returns: + An Encoding + """ + if sequence is None: + raise ValueError("encode: `sequence` can't be `None`") + + return self._tokenizer.encode(sequence, pair, is_pretokenized, add_special_tokens) + + def encode_batch( + self, + inputs: List[EncodeInput], + is_pretokenized: bool = False, + add_special_tokens: bool = True, + ) -> List[Encoding]: + """Encode the given inputs. This method accept both raw text sequences as well as already + pre-tokenized sequences. + + Args: + inputs: List[EncodeInput]: + A list of single sequences or pair sequences to encode. Each `EncodeInput` is + expected to be of the following form: + `Union[InputSequence, Tuple[InputSequence, InputSequence]]` + + Each `InputSequence` can either be raw text or pre-tokenized, + according to the `is_pretokenized` argument: + + - If `is_pretokenized=False`: `InputSequence` is expected to be `str` + - If `is_pretokenized=True`: `InputSequence` is expected to be + `Union[List[str], Tuple[str]]` + + is_pretokenized: bool: + Whether the input is already pre-tokenized. + + add_special_tokens: bool: + Whether to add the special tokens while encoding. + + Returns: + A list of Encoding + """ + + if inputs is None: + raise ValueError("encode_batch: `inputs` can't be `None`") + + return self._tokenizer.encode_batch(inputs, is_pretokenized, add_special_tokens) + + async def async_encode_batch( + self, + inputs: List[EncodeInput], + is_pretokenized: bool = False, + add_special_tokens: bool = True, + ) -> List[Encoding]: + """Asynchronously encode a batch (tracks character offsets). + + Args: + inputs: A list of single or pair sequences to encode. + is_pretokenized: Whether inputs are already pre-tokenized. + add_special_tokens: Whether to add special tokens. + + Returns: + A list of Encoding. + """ + if inputs is None: + raise ValueError("async_encode_batch: `inputs` can't be `None`") + # Exposed by the Rust bindings via pyo3_async_runtimes::tokio::future_into_py + return await self._tokenizer.async_encode_batch(inputs, is_pretokenized, add_special_tokens) + + async def async_encode_batch_fast( + self, + inputs: List[EncodeInput], + is_pretokenized: bool = False, + add_special_tokens: bool = True, + ) -> List[Encoding]: + """Asynchronously encode a batch (no character offsets, faster). + + Args: + inputs: A list of single or pair sequences to encode. + is_pretokenized: Whether inputs are already pre-tokenized. + add_special_tokens: Whether to add special tokens. + + Returns: + A list of Encoding. + """ + if inputs is None: + raise ValueError("async_encode_batch_fast: `inputs` can't be `None`") + return await self._tokenizer.async_encode_batch_fast(inputs, is_pretokenized, add_special_tokens) + + def decode(self, ids: List[int], skip_special_tokens: Optional[bool] = True) -> str: + """Decode the given list of ids to a string sequence + + Args: + ids: List[unsigned int]: + A list of ids to be decoded + + skip_special_tokens: (`optional`) boolean: + Whether to remove all the special tokens from the output string + + Returns: + The decoded string + """ + if ids is None: + raise ValueError("None input is not valid. Should be a list of integers.") + + return self._tokenizer.decode(ids, skip_special_tokens=skip_special_tokens) + + def decode_batch(self, sequences: List[List[int]], skip_special_tokens: Optional[bool] = True) -> str: + """Decode the list of sequences to a list of string sequences + + Args: + sequences: List[List[unsigned int]]: + A list of sequence of ids to be decoded + + skip_special_tokens: (`optional`) boolean: + Whether to remove all the special tokens from the output strings + + Returns: + A list of decoded strings + """ + if sequences is None: + raise ValueError("None input is not valid. Should be list of list of integers.") + + return self._tokenizer.decode_batch(sequences, skip_special_tokens=skip_special_tokens) + + def token_to_id(self, token: str) -> Optional[int]: + """Convert the given token to its corresponding id + + Args: + token: str: + The token to convert + + Returns: + The corresponding id if it exists, None otherwise + """ + return self._tokenizer.token_to_id(token) + + def id_to_token(self, id: int) -> Optional[str]: + """Convert the given token id to its corresponding string + + Args: + token: id: + The token id to convert + + Returns: + The corresponding string if it exists, None otherwise + """ + return self._tokenizer.id_to_token(id) + + def save_model(self, directory: str, prefix: Optional[str] = None): + """Save the current model to the given directory + + Args: + directory: str: + A path to the destination directory + + prefix: (Optional) str: + An optional prefix, used to prefix each file name + """ + return self._tokenizer.model.save(directory, prefix=prefix) + + def save(self, path: str, pretty: bool = True): + """Save the current Tokenizer at the given path + + Args: + path: str: + A path to the destination Tokenizer file + """ + return self._tokenizer.save(path, pretty) + + def to_str(self, pretty: bool = False): + """Get a serialized JSON version of the Tokenizer as a str + + Args: + pretty: bool: + Whether the JSON string should be prettified + + Returns: + str + """ + return self._tokenizer.to_str(pretty) + + def post_process( + self, encoding: Encoding, pair: Optional[Encoding] = None, add_special_tokens: bool = True + ) -> Encoding: + """Apply all the post-processing steps to the given encodings. + + The various steps are: + 1. Truncate according to global params (provided to `enable_truncation`) + 2. Apply the PostProcessor + 3. Pad according to global params. (provided to `enable_padding`) + + Args: + encoding: Encoding: + The main Encoding to post process + + pair: Optional[Encoding]: + An optional pair Encoding + + add_special_tokens: bool: + Whether to add special tokens + + Returns: + The resulting Encoding + """ + return self._tokenizer.post_process(encoding, pair, add_special_tokens) + + @property + def model(self) -> Model: + return self._tokenizer.model + + @model.setter + def model(self, model: Model): + self._tokenizer.model = model + + @property + def normalizer(self) -> Normalizer: + return self._tokenizer.normalizer + + @normalizer.setter + def normalizer(self, normalizer: Normalizer): + self._tokenizer.normalizer = normalizer + + @property + def pre_tokenizer(self) -> PreTokenizer: + return self._tokenizer.pre_tokenizer + + @pre_tokenizer.setter + def pre_tokenizer(self, pre_tokenizer: PreTokenizer): + self._tokenizer.pre_tokenizer = pre_tokenizer + + @property + def post_processor(self) -> PostProcessor: + return self._tokenizer.post_processor + + @post_processor.setter + def post_processor(self, post_processor: PostProcessor): + self._tokenizer.post_processor = post_processor + + @property + def decoder(self) -> Decoder: + return self._tokenizer.decoder + + @decoder.setter + def decoder(self, decoder: Decoder): + self._tokenizer.decoder = decoder diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/implementations/bert_wordpiece.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/implementations/bert_wordpiece.py new file mode 100644 index 0000000000000000000000000000000000000000..1f34e3ca8a4f8b3ed454e09d828918881232ef90 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/implementations/bert_wordpiece.py @@ -0,0 +1,151 @@ +from typing import Dict, Iterator, List, Optional, Union + +from tokenizers import AddedToken, Tokenizer, decoders, trainers +from tokenizers.models import WordPiece +from tokenizers.normalizers import BertNormalizer +from tokenizers.pre_tokenizers import BertPreTokenizer +from tokenizers.processors import BertProcessing + +from .base_tokenizer import BaseTokenizer + + +class BertWordPieceTokenizer(BaseTokenizer): + """Bert WordPiece Tokenizer""" + + def __init__( + self, + vocab: Optional[Union[str, Dict[str, int]]] = None, + unk_token: Union[str, AddedToken] = "[UNK]", + sep_token: Union[str, AddedToken] = "[SEP]", + cls_token: Union[str, AddedToken] = "[CLS]", + pad_token: Union[str, AddedToken] = "[PAD]", + mask_token: Union[str, AddedToken] = "[MASK]", + clean_text: bool = True, + handle_chinese_chars: bool = True, + strip_accents: Optional[bool] = None, + lowercase: bool = True, + wordpieces_prefix: str = "##", + ): + if vocab is not None: + tokenizer = Tokenizer(WordPiece(vocab, unk_token=str(unk_token))) + else: + tokenizer = Tokenizer(WordPiece(unk_token=str(unk_token))) + + # Let the tokenizer know about special tokens if they are part of the vocab + if tokenizer.token_to_id(str(unk_token)) is not None: + tokenizer.add_special_tokens([str(unk_token)]) + if tokenizer.token_to_id(str(sep_token)) is not None: + tokenizer.add_special_tokens([str(sep_token)]) + if tokenizer.token_to_id(str(cls_token)) is not None: + tokenizer.add_special_tokens([str(cls_token)]) + if tokenizer.token_to_id(str(pad_token)) is not None: + tokenizer.add_special_tokens([str(pad_token)]) + if tokenizer.token_to_id(str(mask_token)) is not None: + tokenizer.add_special_tokens([str(mask_token)]) + + tokenizer.normalizer = BertNormalizer( + clean_text=clean_text, + handle_chinese_chars=handle_chinese_chars, + strip_accents=strip_accents, + lowercase=lowercase, + ) + tokenizer.pre_tokenizer = BertPreTokenizer() + + if vocab is not None: + sep_token_id = tokenizer.token_to_id(str(sep_token)) + if sep_token_id is None: + raise TypeError("sep_token not found in the vocabulary") + cls_token_id = tokenizer.token_to_id(str(cls_token)) + if cls_token_id is None: + raise TypeError("cls_token not found in the vocabulary") + + tokenizer.post_processor = BertProcessing((str(sep_token), sep_token_id), (str(cls_token), cls_token_id)) + tokenizer.decoder = decoders.WordPiece(prefix=wordpieces_prefix) + + parameters = { + "model": "BertWordPiece", + "unk_token": unk_token, + "sep_token": sep_token, + "cls_token": cls_token, + "pad_token": pad_token, + "mask_token": mask_token, + "clean_text": clean_text, + "handle_chinese_chars": handle_chinese_chars, + "strip_accents": strip_accents, + "lowercase": lowercase, + "wordpieces_prefix": wordpieces_prefix, + } + + super().__init__(tokenizer, parameters) + + @staticmethod + def from_file(vocab: str, **kwargs): + vocab = WordPiece.read_file(vocab) + return BertWordPieceTokenizer(vocab, **kwargs) + + def train( + self, + files: Union[str, List[str]], + vocab_size: int = 30000, + min_frequency: int = 2, + limit_alphabet: int = 1000, + initial_alphabet: List[str] = [], + special_tokens: List[Union[str, AddedToken]] = [ + "[PAD]", + "[UNK]", + "[CLS]", + "[SEP]", + "[MASK]", + ], + show_progress: bool = True, + wordpieces_prefix: str = "##", + ): + """Train the model using the given files""" + + trainer = trainers.WordPieceTrainer( + vocab_size=vocab_size, + min_frequency=min_frequency, + limit_alphabet=limit_alphabet, + initial_alphabet=initial_alphabet, + special_tokens=special_tokens, + show_progress=show_progress, + continuing_subword_prefix=wordpieces_prefix, + ) + if isinstance(files, str): + files = [files] + self._tokenizer.train(files, trainer=trainer) + + def train_from_iterator( + self, + iterator: Union[Iterator[str], Iterator[Iterator[str]]], + vocab_size: int = 30000, + min_frequency: int = 2, + limit_alphabet: int = 1000, + initial_alphabet: List[str] = [], + special_tokens: List[Union[str, AddedToken]] = [ + "[PAD]", + "[UNK]", + "[CLS]", + "[SEP]", + "[MASK]", + ], + show_progress: bool = True, + wordpieces_prefix: str = "##", + length: Optional[int] = None, + ): + """Train the model using the given iterator""" + + trainer = trainers.WordPieceTrainer( + vocab_size=vocab_size, + min_frequency=min_frequency, + limit_alphabet=limit_alphabet, + initial_alphabet=initial_alphabet, + special_tokens=special_tokens, + show_progress=show_progress, + continuing_subword_prefix=wordpieces_prefix, + ) + self._tokenizer.train_from_iterator( + iterator, + trainer=trainer, + length=length, + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/implementations/byte_level_bpe.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/implementations/byte_level_bpe.py new file mode 100644 index 0000000000000000000000000000000000000000..f65f05e1ddd4c8ec6b3791aa3045762cc06523e3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/implementations/byte_level_bpe.py @@ -0,0 +1,122 @@ +from typing import Dict, Iterator, List, Optional, Tuple, Union + +from tokenizers import AddedToken, Tokenizer, decoders, pre_tokenizers, processors, trainers +from tokenizers.models import BPE +from tokenizers.normalizers import Lowercase, Sequence, unicode_normalizer_from_str + +from .base_tokenizer import BaseTokenizer + + +class ByteLevelBPETokenizer(BaseTokenizer): + """ByteLevelBPETokenizer + + Represents a Byte-level BPE as introduced by OpenAI with their GPT-2 model + """ + + def __init__( + self, + vocab: Optional[Union[str, Dict[str, int]]] = None, + merges: Optional[Union[str, List[Tuple[str, str]]]] = None, + add_prefix_space: bool = False, + lowercase: bool = False, + dropout: Optional[float] = None, + unicode_normalizer: Optional[str] = None, + continuing_subword_prefix: Optional[str] = None, + end_of_word_suffix: Optional[str] = None, + trim_offsets: bool = False, + ): + if vocab is not None and merges is not None: + tokenizer = Tokenizer( + BPE( + vocab, + merges, + dropout=dropout, + continuing_subword_prefix=continuing_subword_prefix or "", + end_of_word_suffix=end_of_word_suffix or "", + ) + ) + else: + tokenizer = Tokenizer(BPE()) + + # Check for Unicode normalization first (before everything else) + normalizers = [] + + if unicode_normalizer: + normalizers += [unicode_normalizer_from_str(unicode_normalizer)] + + if lowercase: + normalizers += [Lowercase()] + + # Create the normalizer structure + if len(normalizers) > 0: + if len(normalizers) > 1: + tokenizer.normalizer = Sequence(normalizers) + else: + tokenizer.normalizer = normalizers[0] + + tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=add_prefix_space) + tokenizer.decoder = decoders.ByteLevel() + tokenizer.post_processor = processors.ByteLevel(trim_offsets=trim_offsets) + + parameters = { + "model": "ByteLevelBPE", + "add_prefix_space": add_prefix_space, + "lowercase": lowercase, + "dropout": dropout, + "unicode_normalizer": unicode_normalizer, + "continuing_subword_prefix": continuing_subword_prefix, + "end_of_word_suffix": end_of_word_suffix, + "trim_offsets": trim_offsets, + } + + super().__init__(tokenizer, parameters) + + @staticmethod + def from_file(vocab_filename: str, merges_filename: str, **kwargs): + vocab, merges = BPE.read_file(vocab_filename, merges_filename) + return ByteLevelBPETokenizer(vocab, merges, **kwargs) + + def train( + self, + files: Union[str, List[str]], + vocab_size: int = 30000, + min_frequency: int = 2, + show_progress: bool = True, + special_tokens: List[Union[str, AddedToken]] = [], + ): + """Train the model using the given files""" + + trainer = trainers.BpeTrainer( + vocab_size=vocab_size, + min_frequency=min_frequency, + show_progress=show_progress, + special_tokens=special_tokens, + initial_alphabet=pre_tokenizers.ByteLevel.alphabet(), + ) + if isinstance(files, str): + files = [files] + self._tokenizer.train(files, trainer=trainer) + + def train_from_iterator( + self, + iterator: Union[Iterator[str], Iterator[Iterator[str]]], + vocab_size: int = 30000, + min_frequency: int = 2, + show_progress: bool = True, + special_tokens: List[Union[str, AddedToken]] = [], + length: Optional[int] = None, + ): + """Train the model using the given iterator""" + + trainer = trainers.BpeTrainer( + vocab_size=vocab_size, + min_frequency=min_frequency, + show_progress=show_progress, + special_tokens=special_tokens, + initial_alphabet=pre_tokenizers.ByteLevel.alphabet(), + ) + self._tokenizer.train_from_iterator( + iterator, + trainer=trainer, + length=length, + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/implementations/char_level_bpe.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/implementations/char_level_bpe.py new file mode 100644 index 0000000000000000000000000000000000000000..62b5bcdf06b4026ce48620ee4d681f0c7399b520 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/implementations/char_level_bpe.py @@ -0,0 +1,150 @@ +from typing import Dict, Iterator, List, Optional, Tuple, Union + +from .. import AddedToken, Tokenizer, decoders, pre_tokenizers, trainers +from ..models import BPE +from ..normalizers import BertNormalizer, Lowercase, Sequence, unicode_normalizer_from_str +from .base_tokenizer import BaseTokenizer + + +class CharBPETokenizer(BaseTokenizer): + """Original BPE Tokenizer + + Represents the BPE algorithm, as introduced by Rico Sennrich + (https://arxiv.org/abs/1508.07909) + + The defaults settings corresponds to OpenAI GPT BPE tokenizers and differs from the original + Sennrich subword-nmt implementation by the following options that you can deactivate: + - adding a normalizer to clean up the text (deactivate with `bert_normalizer=False`) by: + * removing any control characters and replacing all whitespaces by the classic one. + * handle chinese chars by putting spaces around them. + * strip all accents. + - spitting on punctuation in addition to whitespaces (deactivate it with + `split_on_whitespace_only=True`) + """ + + def __init__( + self, + vocab: Optional[Union[str, Dict[str, int]]] = None, + merges: Optional[Union[str, List[Tuple[str, str]]]] = None, + unk_token: Union[str, AddedToken] = "", + suffix: str = "", + dropout: Optional[float] = None, + lowercase: bool = False, + unicode_normalizer: Optional[str] = None, + bert_normalizer: bool = True, + split_on_whitespace_only: bool = False, + ): + if vocab is not None and merges is not None: + tokenizer = Tokenizer( + BPE( + vocab, + merges, + dropout=dropout, + unk_token=str(unk_token), + end_of_word_suffix=suffix, + ) + ) + else: + tokenizer = Tokenizer(BPE(unk_token=str(unk_token), dropout=dropout, end_of_word_suffix=suffix)) + + if tokenizer.token_to_id(str(unk_token)) is not None: + tokenizer.add_special_tokens([str(unk_token)]) + + # Check for Unicode normalization first (before everything else) + normalizers = [] + + if unicode_normalizer: + normalizers += [unicode_normalizer_from_str(unicode_normalizer)] + + if bert_normalizer: + normalizers += [BertNormalizer(lowercase=False)] + + if lowercase: + normalizers += [Lowercase()] + + # Create the normalizer structure + if len(normalizers) > 0: + if len(normalizers) > 1: + tokenizer.normalizer = Sequence(normalizers) + else: + tokenizer.normalizer = normalizers[0] + + if split_on_whitespace_only: + tokenizer.pre_tokenizer = pre_tokenizers.WhitespaceSplit() + else: + tokenizer.pre_tokenizer = pre_tokenizers.BertPreTokenizer() + + tokenizer.decoder = decoders.BPEDecoder(suffix=suffix) + + parameters = { + "model": "BPE", + "unk_token": unk_token, + "suffix": suffix, + "dropout": dropout, + "lowercase": lowercase, + "unicode_normalizer": unicode_normalizer, + "bert_normalizer": bert_normalizer, + "split_on_whitespace_only": split_on_whitespace_only, + } + + super().__init__(tokenizer, parameters) + + @staticmethod + def from_file(vocab_filename: str, merges_filename: str, **kwargs): + vocab, merges = BPE.read_file(vocab_filename, merges_filename) + return CharBPETokenizer(vocab, merges, **kwargs) + + def train( + self, + files: Union[str, List[str]], + vocab_size: int = 30000, + min_frequency: int = 2, + special_tokens: List[Union[str, AddedToken]] = [""], + limit_alphabet: int = 1000, + initial_alphabet: List[str] = [], + suffix: Optional[str] = "", + show_progress: bool = True, + ): + """Train the model using the given files""" + + trainer = trainers.BpeTrainer( + vocab_size=vocab_size, + min_frequency=min_frequency, + special_tokens=special_tokens, + limit_alphabet=limit_alphabet, + initial_alphabet=initial_alphabet, + end_of_word_suffix=suffix, + show_progress=show_progress, + ) + if isinstance(files, str): + files = [files] + self._tokenizer.train(files, trainer=trainer) + + def train_from_iterator( + self, + iterator: Union[Iterator[str], Iterator[Iterator[str]]], + vocab_size: int = 30000, + min_frequency: int = 2, + special_tokens: List[Union[str, AddedToken]] = [""], + limit_alphabet: int = 1000, + initial_alphabet: List[str] = [], + suffix: Optional[str] = "", + show_progress: bool = True, + length: Optional[int] = None, + ): + """Train the model using the given iterator""" + + trainer = trainers.BpeTrainer( + vocab_size=vocab_size, + min_frequency=min_frequency, + special_tokens=special_tokens, + limit_alphabet=limit_alphabet, + initial_alphabet=initial_alphabet, + end_of_word_suffix=suffix, + show_progress=show_progress, + ) + self._tokenizer.train_from_iterator( + iterator, + trainer=trainer, + length=length, + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/implementations/sentencepiece_bpe.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/implementations/sentencepiece_bpe.py new file mode 100644 index 0000000000000000000000000000000000000000..26200489a60dfc6420b43f5dda21ad18ebfe7484 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/implementations/sentencepiece_bpe.py @@ -0,0 +1,103 @@ +from typing import Dict, Iterator, List, Optional, Tuple, Union + +from tokenizers import AddedToken, Tokenizer, decoders, pre_tokenizers, trainers +from tokenizers.models import BPE +from tokenizers.normalizers import NFKC + +from .base_tokenizer import BaseTokenizer + + +class SentencePieceBPETokenizer(BaseTokenizer): + """SentencePiece BPE Tokenizer + + Represents the BPE algorithm, with the pretokenization used by SentencePiece + """ + + def __init__( + self, + vocab: Optional[Union[str, Dict[str, int]]] = None, + merges: Optional[Union[str, List[Tuple[str, str]]]] = None, + unk_token: Union[str, AddedToken] = "", + replacement: str = "▁", + add_prefix_space: bool = True, + dropout: Optional[float] = None, + fuse_unk: Optional[bool] = False, + ): + if vocab is not None and merges is not None: + tokenizer = Tokenizer(BPE(vocab, merges, dropout=dropout, unk_token=unk_token, fuse_unk=fuse_unk)) + else: + tokenizer = Tokenizer(BPE(dropout=dropout, unk_token=unk_token, fuse_unk=fuse_unk)) + + if tokenizer.token_to_id(str(unk_token)) is not None: + tokenizer.add_special_tokens([str(unk_token)]) + + tokenizer.normalizer = NFKC() + prepend_scheme = "always" if add_prefix_space else "never" + tokenizer.pre_tokenizer = pre_tokenizers.Metaspace(replacement=replacement, prepend_scheme=prepend_scheme) + tokenizer.decoder = decoders.Metaspace(replacement=replacement, prepend_scheme=prepend_scheme) + + parameters = { + "model": "SentencePieceBPE", + "unk_token": unk_token, + "replacement": replacement, + "add_prefix_space": add_prefix_space, + "dropout": dropout, + } + + super().__init__(tokenizer, parameters) + + @staticmethod + def from_file(vocab_filename: str, merges_filename: str, **kwargs): + vocab, merges = BPE.read_file(vocab_filename, merges_filename) + return SentencePieceBPETokenizer(vocab, merges, **kwargs) + + def train( + self, + files: Union[str, List[str]], + vocab_size: int = 30000, + min_frequency: int = 2, + special_tokens: List[Union[str, AddedToken]] = [""], + limit_alphabet: int = 1000, + initial_alphabet: List[str] = [], + show_progress: bool = True, + ): + """Train the model using the given files""" + + trainer = trainers.BpeTrainer( + vocab_size=vocab_size, + min_frequency=min_frequency, + special_tokens=special_tokens, + limit_alphabet=limit_alphabet, + initial_alphabet=initial_alphabet, + show_progress=show_progress, + ) + if isinstance(files, str): + files = [files] + self._tokenizer.train(files, trainer=trainer) + + def train_from_iterator( + self, + iterator: Union[Iterator[str], Iterator[Iterator[str]]], + vocab_size: int = 30000, + min_frequency: int = 2, + special_tokens: List[Union[str, AddedToken]] = [""], + limit_alphabet: int = 1000, + initial_alphabet: List[str] = [], + show_progress: bool = True, + length: Optional[int] = None, + ): + """Train the model using the given iterator""" + + trainer = trainers.BpeTrainer( + vocab_size=vocab_size, + min_frequency=min_frequency, + special_tokens=special_tokens, + limit_alphabet=limit_alphabet, + initial_alphabet=initial_alphabet, + show_progress=show_progress, + ) + self._tokenizer.train_from_iterator( + iterator, + trainer=trainer, + length=length, + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/implementations/sentencepiece_unigram.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/implementations/sentencepiece_unigram.py new file mode 100644 index 0000000000000000000000000000000000000000..5e945a433686be6643363a140b17dd56e64013f9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/implementations/sentencepiece_unigram.py @@ -0,0 +1,196 @@ +import json +import os +from typing import Iterator, List, Optional, Union, Tuple + +from tokenizers import AddedToken, Regex, Tokenizer, decoders, normalizers, pre_tokenizers, trainers +from tokenizers.models import Unigram + +from .base_tokenizer import BaseTokenizer + + +class SentencePieceUnigramTokenizer(BaseTokenizer): + """SentencePiece Unigram Tokenizer + + Represents the Unigram algorithm, with the pretokenization used by SentencePiece + """ + + def __init__( + self, + vocab: Optional[List[Tuple[str, float]]] = None, + replacement: str = "▁", + add_prefix_space: bool = True, + ): + if vocab is not None: + # Let Unigram(..) fail if only one of them is None + tokenizer = Tokenizer(Unigram(vocab)) + else: + tokenizer = Tokenizer(Unigram()) + + tokenizer.normalizer = normalizers.Sequence( + [normalizers.Nmt(), normalizers.NFKC(), normalizers.Replace(Regex(" {2,}"), " ")] + ) + prepend_scheme = "always" if add_prefix_space else "never" + tokenizer.pre_tokenizer = pre_tokenizers.Metaspace(replacement=replacement, prepend_scheme=prepend_scheme) + tokenizer.decoder = decoders.Metaspace(replacement=replacement, prepend_scheme=prepend_scheme) + + parameters = { + "model": "SentencePieceUnigram", + "replacement": replacement, + "add_prefix_space": add_prefix_space, + } + + super().__init__(tokenizer, parameters) + + def train( + self, + files: Union[str, List[str]], + vocab_size: int = 8000, + show_progress: bool = True, + special_tokens: Optional[List[Union[str, AddedToken]]] = None, + initial_alphabet: Optional[List[str]] = None, + unk_token: Optional[str] = None, + ): + """ + Train the model using the given files + + Args: + files (:obj:`List[str]`): + A list of path to the files that we should use for training + vocab_size (:obj:`int`): + The size of the final vocabulary, including all tokens and alphabet. + show_progress (:obj:`bool`): + Whether to show progress bars while training. + special_tokens (:obj:`List[Union[str, AddedToken]]`, `optional`): + A list of special tokens the model should know of. + initial_alphabet (:obj:`List[str]`, `optional`): + A list of characters to include in the initial alphabet, even + if not seen in the training dataset. + If the strings contain more than one character, only the first one + is kept. + unk_token (:obj:`str`, `optional`): + The unknown token to be used by the model. + """ + + if special_tokens is None: + special_tokens = [] + + if initial_alphabet is None: + initial_alphabet = [] + + trainer = trainers.UnigramTrainer( + vocab_size=vocab_size, + special_tokens=special_tokens, + show_progress=show_progress, + initial_alphabet=initial_alphabet, + unk_token=unk_token, + ) + + if isinstance(files, str): + files = [files] + self._tokenizer.train(files, trainer=trainer) + + def train_from_iterator( + self, + iterator: Union[Iterator[str], Iterator[Iterator[str]]], + vocab_size: int = 8000, + show_progress: bool = True, + special_tokens: Optional[List[Union[str, AddedToken]]] = None, + initial_alphabet: Optional[List[str]] = None, + unk_token: Optional[str] = None, + length: Optional[int] = None, + ): + """ + Train the model using the given iterator + + Args: + iterator (:obj:`Union[Iterator[str], Iterator[Iterator[str]]]`): + Any iterator over strings or list of strings + vocab_size (:obj:`int`): + The size of the final vocabulary, including all tokens and alphabet. + show_progress (:obj:`bool`): + Whether to show progress bars while training. + special_tokens (:obj:`List[Union[str, AddedToken]]`, `optional`): + A list of special tokens the model should know of. + initial_alphabet (:obj:`List[str]`, `optional`): + A list of characters to include in the initial alphabet, even + if not seen in the training dataset. + If the strings contain more than one character, only the first one + is kept. + unk_token (:obj:`str`, `optional`): + The unknown token to be used by the model. + length (:obj:`int`, `optional`): + The total number of sequences in the iterator. This is used to + provide meaningful progress tracking + """ + + if special_tokens is None: + special_tokens = [] + + if initial_alphabet is None: + initial_alphabet = [] + + trainer = trainers.UnigramTrainer( + vocab_size=vocab_size, + special_tokens=special_tokens, + show_progress=show_progress, + initial_alphabet=initial_alphabet, + unk_token=unk_token, + ) + + self._tokenizer.train_from_iterator( + iterator, + trainer=trainer, + length=length, + ) + + @staticmethod + def from_spm(filename: str): + try: + import sys + + sys.path.append(".") + + import sentencepiece_model_pb2 as model # type: ignore[import] + except Exception: + raise Exception( + "You don't seem to have the required protobuf file, in order to use this function you need to run `pip install protobuf` and `wget https://raw.githubusercontent.com/google/sentencepiece/master/python/src/sentencepiece/sentencepiece_model_pb2.py` for us to be able to read the intrinsics of your spm_file. `pip install sentencepiece` is not required." + ) + + m = model.ModelProto() + m.ParseFromString(open(filename, "rb").read()) + + precompiled_charsmap = m.normalizer_spec.precompiled_charsmap + vocab = [(piece.piece, piece.score) for piece in m.pieces] + unk_id = m.trainer_spec.unk_id + model_type = m.trainer_spec.model_type + byte_fallback = m.trainer_spec.byte_fallback + if model_type != 1: + raise Exception( + "You're trying to run a `Unigram` model but you're file was trained with a different algorithm" + ) + + replacement = "▁" + add_prefix_space = True + + tokenizer = Tokenizer(Unigram(vocab, unk_id, byte_fallback)) + + if precompiled_charsmap: + tokenizer.normalizer = normalizers.Sequence( + [ + normalizers.Precompiled(precompiled_charsmap), + normalizers.Replace(Regex(" {2,}"), " "), + ] + ) + else: + tokenizer.normalizer = normalizers.Sequence([normalizers.Replace(Regex(" {2,}"), " ")]) + prepend_scheme = "always" if add_prefix_space else "never" + tokenizer.pre_tokenizer = pre_tokenizers.Metaspace(replacement=replacement, prepend_scheme=prepend_scheme) + tokenizer.decoder = decoders.Metaspace(replacement=replacement, prepend_scheme=prepend_scheme) + + parameters = { + "model": "SentencePieceUnigram", + } + + obj = BaseTokenizer.__new__(SentencePieceUnigramTokenizer, tokenizer, parameters) # type: ignore[arg-type] + BaseTokenizer.__init__(obj, tokenizer, parameters) + return obj diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/models/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..68ac211aa8032249db6b929ca64f9130c358d40b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/models/__init__.py @@ -0,0 +1,8 @@ +# Generated content DO NOT EDIT +from .. import models + +Model = models.Model +BPE = models.BPE +Unigram = models.Unigram +WordLevel = models.WordLevel +WordPiece = models.WordPiece diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/models/__init__.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/models/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..2548697410ffb5d0143c2d26df36fcf4fc0de242 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/models/__init__.pyi @@ -0,0 +1,744 @@ +# Generated content DO NOT EDIT +class Model: + """ + Base class for all models + + The model represents the actual tokenization algorithm. This is the part that + will contain and manage the learned vocabulary. + + This class cannot be constructed directly. Please use one of the concrete models. + """ + def __init__(self): + pass + + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + + def get_trainer(self): + """ + Get the associated :class:`~tokenizers.trainers.Trainer` + + Retrieve the :class:`~tokenizers.trainers.Trainer` associated to this + :class:`~tokenizers.models.Model`. + + Returns: + :class:`~tokenizers.trainers.Trainer`: The Trainer used to train this model + """ + pass + + def id_to_token(self, id): + """ + Get the token associated to an ID + + Args: + id (:obj:`int`): + An ID to convert to a token + + Returns: + :obj:`str`: The token associated to the ID + """ + pass + + def save(self, folder, prefix): + """ + Save the current model + + Save the current model in the given folder, using the given prefix for the various + files that will get created. + Any file with the same name that already exists in this folder will be overwritten. + + Args: + folder (:obj:`str`): + The path to the target folder in which to save the various files + + prefix (:obj:`str`, `optional`): + An optional prefix, used to prefix each file name + + Returns: + :obj:`List[str]`: The list of saved files + """ + pass + + def token_to_id(self, tokens): + """ + Get the ID associated to a token + + Args: + token (:obj:`str`): + A token to convert to an ID + + Returns: + :obj:`int`: The ID associated to the token + """ + pass + + def tokenize(self, sequence): + """ + Tokenize a sequence + + Args: + sequence (:obj:`str`): + A sequence to tokenize + + Returns: + A :obj:`List` of :class:`~tokenizers.Token`: The generated tokens + """ + pass + +class BPE(Model): + """ + An implementation of the BPE (Byte-Pair Encoding) algorithm + + Args: + vocab (:obj:`Dict[str, int]`, `optional`): + A dictionary of string keys and their ids :obj:`{"am": 0,...}` + + merges (:obj:`List[Tuple[str, str]]`, `optional`): + A list of pairs of tokens (:obj:`Tuple[str, str]`) :obj:`[("a", "b"),...]` + + cache_capacity (:obj:`int`, `optional`): + The number of words that the BPE cache can contain. The cache allows + to speed-up the process by keeping the result of the merge operations + for a number of words. + + dropout (:obj:`float`, `optional`): + A float between 0 and 1 that represents the BPE dropout to use. + + unk_token (:obj:`str`, `optional`): + The unknown token to be used by the model. + + continuing_subword_prefix (:obj:`str`, `optional`): + The prefix to attach to subword units that don't represent a beginning of word. + + end_of_word_suffix (:obj:`str`, `optional`): + The suffix to attach to subword units that represent an end of word. + + fuse_unk (:obj:`bool`, `optional`): + Whether to fuse any subsequent unknown tokens into a single one + + byte_fallback (:obj:`bool`, `optional`): + Whether to use spm byte-fallback trick (defaults to False) + + ignore_merges (:obj:`bool`, `optional`): + Whether or not to match tokens with the vocab before using merges. + """ + def __init__( + self, + vocab=None, + merges=None, + cache_capacity=None, + dropout=None, + unk_token=None, + continuing_subword_prefix=None, + end_of_word_suffix=None, + fuse_unk=None, + byte_fallback=False, + ignore_merges=False, + ): + pass + + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + + @property + def byte_fallback(self): + """ """ + pass + + @byte_fallback.setter + def byte_fallback(self, value): + """ """ + pass + + @property + def continuing_subword_prefix(self): + """ """ + pass + + @continuing_subword_prefix.setter + def continuing_subword_prefix(self, value): + """ """ + pass + + @property + def dropout(self): + """ """ + pass + + @dropout.setter + def dropout(self, value): + """ """ + pass + + @property + def end_of_word_suffix(self): + """ """ + pass + + @end_of_word_suffix.setter + def end_of_word_suffix(self, value): + """ """ + pass + + @staticmethod + def from_file(vocab, merges, **kwargs): + """ + Instantiate a BPE model from the given files. + + This method is roughly equivalent to doing:: + + vocab, merges = BPE.read_file(vocab_filename, merges_filename) + bpe = BPE(vocab, merges) + + If you don't need to keep the :obj:`vocab, merges` values lying around, + this method is more optimized than manually calling + :meth:`~tokenizers.models.BPE.read_file` to initialize a :class:`~tokenizers.models.BPE` + + Args: + vocab (:obj:`str`): + The path to a :obj:`vocab.json` file + + merges (:obj:`str`): + The path to a :obj:`merges.txt` file + + Returns: + :class:`~tokenizers.models.BPE`: An instance of BPE loaded from these files + """ + pass + + @property + def fuse_unk(self): + """ """ + pass + + @fuse_unk.setter + def fuse_unk(self, value): + """ """ + pass + + def get_trainer(self): + """ + Get the associated :class:`~tokenizers.trainers.Trainer` + + Retrieve the :class:`~tokenizers.trainers.Trainer` associated to this + :class:`~tokenizers.models.Model`. + + Returns: + :class:`~tokenizers.trainers.Trainer`: The Trainer used to train this model + """ + pass + + def id_to_token(self, id): + """ + Get the token associated to an ID + + Args: + id (:obj:`int`): + An ID to convert to a token + + Returns: + :obj:`str`: The token associated to the ID + """ + pass + + @property + def ignore_merges(self): + """ """ + pass + + @ignore_merges.setter + def ignore_merges(self, value): + """ """ + pass + + @staticmethod + def read_file(vocab, merges): + """ + Read a :obj:`vocab.json` and a :obj:`merges.txt` files + + This method provides a way to read and parse the content of these files, + returning the relevant data structures. If you want to instantiate some BPE models + from memory, this method gives you the expected input from the standard files. + + Args: + vocab (:obj:`str`): + The path to a :obj:`vocab.json` file + + merges (:obj:`str`): + The path to a :obj:`merges.txt` file + + Returns: + A :obj:`Tuple` with the vocab and the merges: + The vocabulary and merges loaded into memory + """ + pass + + def save(self, folder, prefix): + """ + Save the current model + + Save the current model in the given folder, using the given prefix for the various + files that will get created. + Any file with the same name that already exists in this folder will be overwritten. + + Args: + folder (:obj:`str`): + The path to the target folder in which to save the various files + + prefix (:obj:`str`, `optional`): + An optional prefix, used to prefix each file name + + Returns: + :obj:`List[str]`: The list of saved files + """ + pass + + def token_to_id(self, tokens): + """ + Get the ID associated to a token + + Args: + token (:obj:`str`): + A token to convert to an ID + + Returns: + :obj:`int`: The ID associated to the token + """ + pass + + def tokenize(self, sequence): + """ + Tokenize a sequence + + Args: + sequence (:obj:`str`): + A sequence to tokenize + + Returns: + A :obj:`List` of :class:`~tokenizers.Token`: The generated tokens + """ + pass + + @property + def unk_token(self): + """ """ + pass + + @unk_token.setter + def unk_token(self, value): + """ """ + pass + +class Unigram(Model): + """ + An implementation of the Unigram algorithm + + Args: + vocab (:obj:`List[Tuple[str, float]]`, `optional`, `optional`): + A list of vocabulary items and their relative score [("am", -0.2442),...] + """ + def __init__(self, vocab=None, unk_id=None, byte_fallback=None): + pass + + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + + def get_trainer(self): + """ + Get the associated :class:`~tokenizers.trainers.Trainer` + + Retrieve the :class:`~tokenizers.trainers.Trainer` associated to this + :class:`~tokenizers.models.Model`. + + Returns: + :class:`~tokenizers.trainers.Trainer`: The Trainer used to train this model + """ + pass + + def id_to_token(self, id): + """ + Get the token associated to an ID + + Args: + id (:obj:`int`): + An ID to convert to a token + + Returns: + :obj:`str`: The token associated to the ID + """ + pass + + def save(self, folder, prefix): + """ + Save the current model + + Save the current model in the given folder, using the given prefix for the various + files that will get created. + Any file with the same name that already exists in this folder will be overwritten. + + Args: + folder (:obj:`str`): + The path to the target folder in which to save the various files + + prefix (:obj:`str`, `optional`): + An optional prefix, used to prefix each file name + + Returns: + :obj:`List[str]`: The list of saved files + """ + pass + + def token_to_id(self, tokens): + """ + Get the ID associated to a token + + Args: + token (:obj:`str`): + A token to convert to an ID + + Returns: + :obj:`int`: The ID associated to the token + """ + pass + + def tokenize(self, sequence): + """ + Tokenize a sequence + + Args: + sequence (:obj:`str`): + A sequence to tokenize + + Returns: + A :obj:`List` of :class:`~tokenizers.Token`: The generated tokens + """ + pass + +class WordLevel(Model): + """ + An implementation of the WordLevel algorithm + + Most simple tokenizer model based on mapping tokens to their corresponding id. + + Args: + vocab (:obj:`str`, `optional`): + A dictionary of string keys and their ids :obj:`{"am": 0,...}` + + unk_token (:obj:`str`, `optional`): + The unknown token to be used by the model. + """ + def __init__(self, vocab=None, unk_token=None): + pass + + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + + @staticmethod + def from_file(vocab, unk_token=None): + """ + Instantiate a WordLevel model from the given file + + This method is roughly equivalent to doing:: + + vocab = WordLevel.read_file(vocab_filename) + wordlevel = WordLevel(vocab) + + If you don't need to keep the :obj:`vocab` values lying around, this method is + more optimized than manually calling :meth:`~tokenizers.models.WordLevel.read_file` to + initialize a :class:`~tokenizers.models.WordLevel` + + Args: + vocab (:obj:`str`): + The path to a :obj:`vocab.json` file + + Returns: + :class:`~tokenizers.models.WordLevel`: An instance of WordLevel loaded from file + """ + pass + + def get_trainer(self): + """ + Get the associated :class:`~tokenizers.trainers.Trainer` + + Retrieve the :class:`~tokenizers.trainers.Trainer` associated to this + :class:`~tokenizers.models.Model`. + + Returns: + :class:`~tokenizers.trainers.Trainer`: The Trainer used to train this model + """ + pass + + def id_to_token(self, id): + """ + Get the token associated to an ID + + Args: + id (:obj:`int`): + An ID to convert to a token + + Returns: + :obj:`str`: The token associated to the ID + """ + pass + + @staticmethod + def read_file(vocab): + """ + Read a :obj:`vocab.json` + + This method provides a way to read and parse the content of a vocabulary file, + returning the relevant data structures. If you want to instantiate some WordLevel models + from memory, this method gives you the expected input from the standard files. + + Args: + vocab (:obj:`str`): + The path to a :obj:`vocab.json` file + + Returns: + :obj:`Dict[str, int]`: The vocabulary as a :obj:`dict` + """ + pass + + def save(self, folder, prefix): + """ + Save the current model + + Save the current model in the given folder, using the given prefix for the various + files that will get created. + Any file with the same name that already exists in this folder will be overwritten. + + Args: + folder (:obj:`str`): + The path to the target folder in which to save the various files + + prefix (:obj:`str`, `optional`): + An optional prefix, used to prefix each file name + + Returns: + :obj:`List[str]`: The list of saved files + """ + pass + + def token_to_id(self, tokens): + """ + Get the ID associated to a token + + Args: + token (:obj:`str`): + A token to convert to an ID + + Returns: + :obj:`int`: The ID associated to the token + """ + pass + + def tokenize(self, sequence): + """ + Tokenize a sequence + + Args: + sequence (:obj:`str`): + A sequence to tokenize + + Returns: + A :obj:`List` of :class:`~tokenizers.Token`: The generated tokens + """ + pass + + @property + def unk_token(self): + """ """ + pass + + @unk_token.setter + def unk_token(self, value): + """ """ + pass + +class WordPiece(Model): + """ + An implementation of the WordPiece algorithm + + Args: + vocab (:obj:`Dict[str, int]`, `optional`): + A dictionary of string keys and their ids :obj:`{"am": 0,...}` + + unk_token (:obj:`str`, `optional`): + The unknown token to be used by the model. + + max_input_chars_per_word (:obj:`int`, `optional`): + The maximum number of characters to authorize in a single word. + """ + def __init__(self, vocab=None, unk_token="[UNK]", max_input_chars_per_word=100, continuing_subword_prefix="##"): + pass + + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + + @property + def continuing_subword_prefix(self): + """ """ + pass + + @continuing_subword_prefix.setter + def continuing_subword_prefix(self, value): + """ """ + pass + + @staticmethod + def from_file(vocab, **kwargs): + """ + Instantiate a WordPiece model from the given file + + This method is roughly equivalent to doing:: + + vocab = WordPiece.read_file(vocab_filename) + wordpiece = WordPiece(vocab) + + If you don't need to keep the :obj:`vocab` values lying around, this method is + more optimized than manually calling :meth:`~tokenizers.models.WordPiece.read_file` to + initialize a :class:`~tokenizers.models.WordPiece` + + Args: + vocab (:obj:`str`): + The path to a :obj:`vocab.txt` file + + Returns: + :class:`~tokenizers.models.WordPiece`: An instance of WordPiece loaded from file + """ + pass + + def get_trainer(self): + """ + Get the associated :class:`~tokenizers.trainers.Trainer` + + Retrieve the :class:`~tokenizers.trainers.Trainer` associated to this + :class:`~tokenizers.models.Model`. + + Returns: + :class:`~tokenizers.trainers.Trainer`: The Trainer used to train this model + """ + pass + + def id_to_token(self, id): + """ + Get the token associated to an ID + + Args: + id (:obj:`int`): + An ID to convert to a token + + Returns: + :obj:`str`: The token associated to the ID + """ + pass + + @property + def max_input_chars_per_word(self): + """ """ + pass + + @max_input_chars_per_word.setter + def max_input_chars_per_word(self, value): + """ """ + pass + + @staticmethod + def read_file(vocab): + """ + Read a :obj:`vocab.txt` file + + This method provides a way to read and parse the content of a standard `vocab.txt` + file as used by the WordPiece Model, returning the relevant data structures. If you + want to instantiate some WordPiece models from memory, this method gives you the + expected input from the standard files. + + Args: + vocab (:obj:`str`): + The path to a :obj:`vocab.txt` file + + Returns: + :obj:`Dict[str, int]`: The vocabulary as a :obj:`dict` + """ + pass + + def save(self, folder, prefix): + """ + Save the current model + + Save the current model in the given folder, using the given prefix for the various + files that will get created. + Any file with the same name that already exists in this folder will be overwritten. + + Args: + folder (:obj:`str`): + The path to the target folder in which to save the various files + + prefix (:obj:`str`, `optional`): + An optional prefix, used to prefix each file name + + Returns: + :obj:`List[str]`: The list of saved files + """ + pass + + def token_to_id(self, tokens): + """ + Get the ID associated to a token + + Args: + token (:obj:`str`): + A token to convert to an ID + + Returns: + :obj:`int`: The ID associated to the token + """ + pass + + def tokenize(self, sequence): + """ + Tokenize a sequence + + Args: + sequence (:obj:`str`): + A sequence to tokenize + + Returns: + A :obj:`List` of :class:`~tokenizers.Token`: The generated tokens + """ + pass + + @property + def unk_token(self): + """ """ + pass + + @unk_token.setter + def unk_token(self, value): + """ """ + pass diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/normalizers/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/normalizers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..86d233bd216821d77f5ccf88f874b6f530cedbf5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/normalizers/__init__.py @@ -0,0 +1,29 @@ +from .. import normalizers + + +Normalizer = normalizers.Normalizer +BertNormalizer = normalizers.BertNormalizer +NFD = normalizers.NFD +NFKD = normalizers.NFKD +NFC = normalizers.NFC +NFKC = normalizers.NFKC +Sequence = normalizers.Sequence +Lowercase = normalizers.Lowercase +Prepend = normalizers.Prepend +Strip = normalizers.Strip +StripAccents = normalizers.StripAccents +Nmt = normalizers.Nmt +Precompiled = normalizers.Precompiled +Replace = normalizers.Replace +ByteLevel = normalizers.ByteLevel + +NORMALIZERS = {"nfc": NFC, "nfd": NFD, "nfkc": NFKC, "nfkd": NFKD} + + +def unicode_normalizer_from_str(normalizer: str) -> Normalizer: + if normalizer not in NORMALIZERS: + raise ValueError( + "{} is not a known unicode normalizer. Available are {}".format(normalizer, NORMALIZERS.keys()) + ) + + return NORMALIZERS[normalizer]() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/normalizers/__init__.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/normalizers/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..8d920e0ed73ae051f2135aa250d2426562b73a43 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/normalizers/__init__.pyi @@ -0,0 +1,946 @@ +# Generated content DO NOT EDIT +class Normalizer: + """ + Base class for all normalizers + + This class is not supposed to be instantiated directly. Instead, any implementation of a + Normalizer will return an instance of this class when instantiated. + """ + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + + @staticmethod + def custom(normalizer): + """ """ + pass + + def normalize(self, normalized): + """ + Normalize a :class:`~tokenizers.NormalizedString` in-place + + This method allows to modify a :class:`~tokenizers.NormalizedString` to + keep track of the alignment information. If you just want to see the result + of the normalization on a raw string, you can use + :meth:`~tokenizers.normalizers.Normalizer.normalize_str` + + Args: + normalized (:class:`~tokenizers.NormalizedString`): + The normalized string on which to apply this + :class:`~tokenizers.normalizers.Normalizer` + """ + pass + + def normalize_str(self, sequence): + """ + Normalize the given string + + This method provides a way to visualize the effect of a + :class:`~tokenizers.normalizers.Normalizer` but it does not keep track of the alignment + information. If you need to get/convert offsets, you can use + :meth:`~tokenizers.normalizers.Normalizer.normalize` + + Args: + sequence (:obj:`str`): + A string to normalize + + Returns: + :obj:`str`: A string after normalization + """ + pass + +class BertNormalizer(Normalizer): + """ + BertNormalizer + + Takes care of normalizing raw text before giving it to a Bert model. + This includes cleaning the text, handling accents, chinese chars and lowercasing + + Args: + clean_text (:obj:`bool`, `optional`, defaults to :obj:`True`): + Whether to clean the text, by removing any control characters + and replacing all whitespaces by the classic one. + + handle_chinese_chars (:obj:`bool`, `optional`, defaults to :obj:`True`): + Whether to handle chinese chars by putting spaces around them. + + strip_accents (:obj:`bool`, `optional`): + Whether to strip all accents. If this option is not specified (ie == None), + then it will be determined by the value for `lowercase` (as in the original Bert). + + lowercase (:obj:`bool`, `optional`, defaults to :obj:`True`): + Whether to lowercase. + """ + def __init__(self, clean_text=True, handle_chinese_chars=True, strip_accents=None, lowercase=True): + pass + + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + + @property + def clean_text(self): + """ """ + pass + + @clean_text.setter + def clean_text(self, value): + """ """ + pass + + @staticmethod + def custom(normalizer): + """ """ + pass + + @property + def handle_chinese_chars(self): + """ """ + pass + + @handle_chinese_chars.setter + def handle_chinese_chars(self, value): + """ """ + pass + + @property + def lowercase(self): + """ """ + pass + + @lowercase.setter + def lowercase(self, value): + """ """ + pass + + def normalize(self, normalized): + """ + Normalize a :class:`~tokenizers.NormalizedString` in-place + + This method allows to modify a :class:`~tokenizers.NormalizedString` to + keep track of the alignment information. If you just want to see the result + of the normalization on a raw string, you can use + :meth:`~tokenizers.normalizers.Normalizer.normalize_str` + + Args: + normalized (:class:`~tokenizers.NormalizedString`): + The normalized string on which to apply this + :class:`~tokenizers.normalizers.Normalizer` + """ + pass + + def normalize_str(self, sequence): + """ + Normalize the given string + + This method provides a way to visualize the effect of a + :class:`~tokenizers.normalizers.Normalizer` but it does not keep track of the alignment + information. If you need to get/convert offsets, you can use + :meth:`~tokenizers.normalizers.Normalizer.normalize` + + Args: + sequence (:obj:`str`): + A string to normalize + + Returns: + :obj:`str`: A string after normalization + """ + pass + + @property + def strip_accents(self): + """ """ + pass + + @strip_accents.setter + def strip_accents(self, value): + """ """ + pass + +class ByteLevel(Normalizer): + """ + Bytelevel Normalizer + """ + def __init__(self): + pass + + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + + @staticmethod + def custom(normalizer): + """ """ + pass + + def normalize(self, normalized): + """ + Normalize a :class:`~tokenizers.NormalizedString` in-place + + This method allows to modify a :class:`~tokenizers.NormalizedString` to + keep track of the alignment information. If you just want to see the result + of the normalization on a raw string, you can use + :meth:`~tokenizers.normalizers.Normalizer.normalize_str` + + Args: + normalized (:class:`~tokenizers.NormalizedString`): + The normalized string on which to apply this + :class:`~tokenizers.normalizers.Normalizer` + """ + pass + + def normalize_str(self, sequence): + """ + Normalize the given string + + This method provides a way to visualize the effect of a + :class:`~tokenizers.normalizers.Normalizer` but it does not keep track of the alignment + information. If you need to get/convert offsets, you can use + :meth:`~tokenizers.normalizers.Normalizer.normalize` + + Args: + sequence (:obj:`str`): + A string to normalize + + Returns: + :obj:`str`: A string after normalization + """ + pass + +class Lowercase(Normalizer): + """ + Lowercase Normalizer + """ + def __init__(self): + pass + + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + + @staticmethod + def custom(normalizer): + """ """ + pass + + def normalize(self, normalized): + """ + Normalize a :class:`~tokenizers.NormalizedString` in-place + + This method allows to modify a :class:`~tokenizers.NormalizedString` to + keep track of the alignment information. If you just want to see the result + of the normalization on a raw string, you can use + :meth:`~tokenizers.normalizers.Normalizer.normalize_str` + + Args: + normalized (:class:`~tokenizers.NormalizedString`): + The normalized string on which to apply this + :class:`~tokenizers.normalizers.Normalizer` + """ + pass + + def normalize_str(self, sequence): + """ + Normalize the given string + + This method provides a way to visualize the effect of a + :class:`~tokenizers.normalizers.Normalizer` but it does not keep track of the alignment + information. If you need to get/convert offsets, you can use + :meth:`~tokenizers.normalizers.Normalizer.normalize` + + Args: + sequence (:obj:`str`): + A string to normalize + + Returns: + :obj:`str`: A string after normalization + """ + pass + +class NFC(Normalizer): + """ + NFC Unicode Normalizer + """ + def __init__(self): + pass + + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + + @staticmethod + def custom(normalizer): + """ """ + pass + + def normalize(self, normalized): + """ + Normalize a :class:`~tokenizers.NormalizedString` in-place + + This method allows to modify a :class:`~tokenizers.NormalizedString` to + keep track of the alignment information. If you just want to see the result + of the normalization on a raw string, you can use + :meth:`~tokenizers.normalizers.Normalizer.normalize_str` + + Args: + normalized (:class:`~tokenizers.NormalizedString`): + The normalized string on which to apply this + :class:`~tokenizers.normalizers.Normalizer` + """ + pass + + def normalize_str(self, sequence): + """ + Normalize the given string + + This method provides a way to visualize the effect of a + :class:`~tokenizers.normalizers.Normalizer` but it does not keep track of the alignment + information. If you need to get/convert offsets, you can use + :meth:`~tokenizers.normalizers.Normalizer.normalize` + + Args: + sequence (:obj:`str`): + A string to normalize + + Returns: + :obj:`str`: A string after normalization + """ + pass + +class NFD(Normalizer): + """ + NFD Unicode Normalizer + """ + def __init__(self): + pass + + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + + @staticmethod + def custom(normalizer): + """ """ + pass + + def normalize(self, normalized): + """ + Normalize a :class:`~tokenizers.NormalizedString` in-place + + This method allows to modify a :class:`~tokenizers.NormalizedString` to + keep track of the alignment information. If you just want to see the result + of the normalization on a raw string, you can use + :meth:`~tokenizers.normalizers.Normalizer.normalize_str` + + Args: + normalized (:class:`~tokenizers.NormalizedString`): + The normalized string on which to apply this + :class:`~tokenizers.normalizers.Normalizer` + """ + pass + + def normalize_str(self, sequence): + """ + Normalize the given string + + This method provides a way to visualize the effect of a + :class:`~tokenizers.normalizers.Normalizer` but it does not keep track of the alignment + information. If you need to get/convert offsets, you can use + :meth:`~tokenizers.normalizers.Normalizer.normalize` + + Args: + sequence (:obj:`str`): + A string to normalize + + Returns: + :obj:`str`: A string after normalization + """ + pass + +class NFKC(Normalizer): + """ + NFKC Unicode Normalizer + """ + def __init__(self): + pass + + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + + @staticmethod + def custom(normalizer): + """ """ + pass + + def normalize(self, normalized): + """ + Normalize a :class:`~tokenizers.NormalizedString` in-place + + This method allows to modify a :class:`~tokenizers.NormalizedString` to + keep track of the alignment information. If you just want to see the result + of the normalization on a raw string, you can use + :meth:`~tokenizers.normalizers.Normalizer.normalize_str` + + Args: + normalized (:class:`~tokenizers.NormalizedString`): + The normalized string on which to apply this + :class:`~tokenizers.normalizers.Normalizer` + """ + pass + + def normalize_str(self, sequence): + """ + Normalize the given string + + This method provides a way to visualize the effect of a + :class:`~tokenizers.normalizers.Normalizer` but it does not keep track of the alignment + information. If you need to get/convert offsets, you can use + :meth:`~tokenizers.normalizers.Normalizer.normalize` + + Args: + sequence (:obj:`str`): + A string to normalize + + Returns: + :obj:`str`: A string after normalization + """ + pass + +class NFKD(Normalizer): + """ + NFKD Unicode Normalizer + """ + def __init__(self): + pass + + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + + @staticmethod + def custom(normalizer): + """ """ + pass + + def normalize(self, normalized): + """ + Normalize a :class:`~tokenizers.NormalizedString` in-place + + This method allows to modify a :class:`~tokenizers.NormalizedString` to + keep track of the alignment information. If you just want to see the result + of the normalization on a raw string, you can use + :meth:`~tokenizers.normalizers.Normalizer.normalize_str` + + Args: + normalized (:class:`~tokenizers.NormalizedString`): + The normalized string on which to apply this + :class:`~tokenizers.normalizers.Normalizer` + """ + pass + + def normalize_str(self, sequence): + """ + Normalize the given string + + This method provides a way to visualize the effect of a + :class:`~tokenizers.normalizers.Normalizer` but it does not keep track of the alignment + information. If you need to get/convert offsets, you can use + :meth:`~tokenizers.normalizers.Normalizer.normalize` + + Args: + sequence (:obj:`str`): + A string to normalize + + Returns: + :obj:`str`: A string after normalization + """ + pass + +class Nmt(Normalizer): + """ + Nmt normalizer + """ + def __init__(self): + pass + + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + + @staticmethod + def custom(normalizer): + """ """ + pass + + def normalize(self, normalized): + """ + Normalize a :class:`~tokenizers.NormalizedString` in-place + + This method allows to modify a :class:`~tokenizers.NormalizedString` to + keep track of the alignment information. If you just want to see the result + of the normalization on a raw string, you can use + :meth:`~tokenizers.normalizers.Normalizer.normalize_str` + + Args: + normalized (:class:`~tokenizers.NormalizedString`): + The normalized string on which to apply this + :class:`~tokenizers.normalizers.Normalizer` + """ + pass + + def normalize_str(self, sequence): + """ + Normalize the given string + + This method provides a way to visualize the effect of a + :class:`~tokenizers.normalizers.Normalizer` but it does not keep track of the alignment + information. If you need to get/convert offsets, you can use + :meth:`~tokenizers.normalizers.Normalizer.normalize` + + Args: + sequence (:obj:`str`): + A string to normalize + + Returns: + :obj:`str`: A string after normalization + """ + pass + +class Precompiled(Normalizer): + """ + Precompiled normalizer + Don't use manually it is used for compatibility for SentencePiece. + """ + def __init__(self, precompiled_charsmap): + pass + + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + + @staticmethod + def custom(normalizer): + """ """ + pass + + def normalize(self, normalized): + """ + Normalize a :class:`~tokenizers.NormalizedString` in-place + + This method allows to modify a :class:`~tokenizers.NormalizedString` to + keep track of the alignment information. If you just want to see the result + of the normalization on a raw string, you can use + :meth:`~tokenizers.normalizers.Normalizer.normalize_str` + + Args: + normalized (:class:`~tokenizers.NormalizedString`): + The normalized string on which to apply this + :class:`~tokenizers.normalizers.Normalizer` + """ + pass + + def normalize_str(self, sequence): + """ + Normalize the given string + + This method provides a way to visualize the effect of a + :class:`~tokenizers.normalizers.Normalizer` but it does not keep track of the alignment + information. If you need to get/convert offsets, you can use + :meth:`~tokenizers.normalizers.Normalizer.normalize` + + Args: + sequence (:obj:`str`): + A string to normalize + + Returns: + :obj:`str`: A string after normalization + """ + pass + +class Prepend(Normalizer): + """ + Prepend normalizer + """ + def __init__(self, prepend): + pass + + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + + @staticmethod + def custom(normalizer): + """ """ + pass + + def normalize(self, normalized): + """ + Normalize a :class:`~tokenizers.NormalizedString` in-place + + This method allows to modify a :class:`~tokenizers.NormalizedString` to + keep track of the alignment information. If you just want to see the result + of the normalization on a raw string, you can use + :meth:`~tokenizers.normalizers.Normalizer.normalize_str` + + Args: + normalized (:class:`~tokenizers.NormalizedString`): + The normalized string on which to apply this + :class:`~tokenizers.normalizers.Normalizer` + """ + pass + + def normalize_str(self, sequence): + """ + Normalize the given string + + This method provides a way to visualize the effect of a + :class:`~tokenizers.normalizers.Normalizer` but it does not keep track of the alignment + information. If you need to get/convert offsets, you can use + :meth:`~tokenizers.normalizers.Normalizer.normalize` + + Args: + sequence (:obj:`str`): + A string to normalize + + Returns: + :obj:`str`: A string after normalization + """ + pass + + @property + def prepend(self): + """ """ + pass + + @prepend.setter + def prepend(self, value): + """ """ + pass + +class Replace(Normalizer): + """ + Replace normalizer + """ + def __init__(self, pattern, content): + pass + + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + + @property + def content(self): + """ """ + pass + + @content.setter + def content(self, value): + """ """ + pass + + @staticmethod + def custom(normalizer): + """ """ + pass + + def normalize(self, normalized): + """ + Normalize a :class:`~tokenizers.NormalizedString` in-place + + This method allows to modify a :class:`~tokenizers.NormalizedString` to + keep track of the alignment information. If you just want to see the result + of the normalization on a raw string, you can use + :meth:`~tokenizers.normalizers.Normalizer.normalize_str` + + Args: + normalized (:class:`~tokenizers.NormalizedString`): + The normalized string on which to apply this + :class:`~tokenizers.normalizers.Normalizer` + """ + pass + + def normalize_str(self, sequence): + """ + Normalize the given string + + This method provides a way to visualize the effect of a + :class:`~tokenizers.normalizers.Normalizer` but it does not keep track of the alignment + information. If you need to get/convert offsets, you can use + :meth:`~tokenizers.normalizers.Normalizer.normalize` + + Args: + sequence (:obj:`str`): + A string to normalize + + Returns: + :obj:`str`: A string after normalization + """ + pass + + @property + def pattern(self): + """ """ + pass + + @pattern.setter + def pattern(self, value): + """ """ + pass + +class Sequence(Normalizer): + """ + Allows concatenating multiple other Normalizer as a Sequence. + All the normalizers run in sequence in the given order + + Args: + normalizers (:obj:`List[Normalizer]`): + A list of Normalizer to be run as a sequence + """ + def __init__(self, normalizers): + pass + + def __getitem__(self, key): + """ + Return self[key]. + """ + pass + + def __getnewargs__(self): + """ """ + pass + + def __getstate__(self): + """ """ + pass + + def __setitem__(self, key, value): + """ + Set self[key] to value. + """ + pass + + def __setstate__(self, state): + """ """ + pass + + @staticmethod + def custom(normalizer): + """ """ + pass + + def normalize(self, normalized): + """ + Normalize a :class:`~tokenizers.NormalizedString` in-place + + This method allows to modify a :class:`~tokenizers.NormalizedString` to + keep track of the alignment information. If you just want to see the result + of the normalization on a raw string, you can use + :meth:`~tokenizers.normalizers.Normalizer.normalize_str` + + Args: + normalized (:class:`~tokenizers.NormalizedString`): + The normalized string on which to apply this + :class:`~tokenizers.normalizers.Normalizer` + """ + pass + + def normalize_str(self, sequence): + """ + Normalize the given string + + This method provides a way to visualize the effect of a + :class:`~tokenizers.normalizers.Normalizer` but it does not keep track of the alignment + information. If you need to get/convert offsets, you can use + :meth:`~tokenizers.normalizers.Normalizer.normalize` + + Args: + sequence (:obj:`str`): + A string to normalize + + Returns: + :obj:`str`: A string after normalization + """ + pass + +class Strip(Normalizer): + """ + Strip normalizer + """ + def __init__(self, left=True, right=True): + pass + + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + + @staticmethod + def custom(normalizer): + """ """ + pass + + @property + def left(self): + """ """ + pass + + @left.setter + def left(self, value): + """ """ + pass + + def normalize(self, normalized): + """ + Normalize a :class:`~tokenizers.NormalizedString` in-place + + This method allows to modify a :class:`~tokenizers.NormalizedString` to + keep track of the alignment information. If you just want to see the result + of the normalization on a raw string, you can use + :meth:`~tokenizers.normalizers.Normalizer.normalize_str` + + Args: + normalized (:class:`~tokenizers.NormalizedString`): + The normalized string on which to apply this + :class:`~tokenizers.normalizers.Normalizer` + """ + pass + + def normalize_str(self, sequence): + """ + Normalize the given string + + This method provides a way to visualize the effect of a + :class:`~tokenizers.normalizers.Normalizer` but it does not keep track of the alignment + information. If you need to get/convert offsets, you can use + :meth:`~tokenizers.normalizers.Normalizer.normalize` + + Args: + sequence (:obj:`str`): + A string to normalize + + Returns: + :obj:`str`: A string after normalization + """ + pass + + @property + def right(self): + """ """ + pass + + @right.setter + def right(self, value): + """ """ + pass + +class StripAccents(Normalizer): + """ + StripAccents normalizer + """ + def __init__(self): + pass + + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + + @staticmethod + def custom(normalizer): + """ """ + pass + + def normalize(self, normalized): + """ + Normalize a :class:`~tokenizers.NormalizedString` in-place + + This method allows to modify a :class:`~tokenizers.NormalizedString` to + keep track of the alignment information. If you just want to see the result + of the normalization on a raw string, you can use + :meth:`~tokenizers.normalizers.Normalizer.normalize_str` + + Args: + normalized (:class:`~tokenizers.NormalizedString`): + The normalized string on which to apply this + :class:`~tokenizers.normalizers.Normalizer` + """ + pass + + def normalize_str(self, sequence): + """ + Normalize the given string + + This method provides a way to visualize the effect of a + :class:`~tokenizers.normalizers.Normalizer` but it does not keep track of the alignment + information. If you need to get/convert offsets, you can use + :meth:`~tokenizers.normalizers.Normalizer.normalize` + + Args: + sequence (:obj:`str`): + A string to normalize + + Returns: + :obj:`str`: A string after normalization + """ + pass + +from typing import Dict + +NORMALIZERS: Dict[str, Normalizer] + +def unicode_normalizer_from_str(normalizer: str) -> Normalizer: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/pre_tokenizers/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/pre_tokenizers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..db8ddc20805b1c525be405134f8fa722ace89667 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/pre_tokenizers/__init__.py @@ -0,0 +1,16 @@ +# Generated content DO NOT EDIT +from .. import pre_tokenizers + +PreTokenizer = pre_tokenizers.PreTokenizer +BertPreTokenizer = pre_tokenizers.BertPreTokenizer +ByteLevel = pre_tokenizers.ByteLevel +CharDelimiterSplit = pre_tokenizers.CharDelimiterSplit +Digits = pre_tokenizers.Digits +FixedLength = pre_tokenizers.FixedLength +Metaspace = pre_tokenizers.Metaspace +Punctuation = pre_tokenizers.Punctuation +Sequence = pre_tokenizers.Sequence +Split = pre_tokenizers.Split +UnicodeScripts = pre_tokenizers.UnicodeScripts +Whitespace = pre_tokenizers.Whitespace +WhitespaceSplit = pre_tokenizers.WhitespaceSplit diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/pre_tokenizers/__init__.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/pre_tokenizers/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..1e58d5d040816761987935facee50666221a94bd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/pre_tokenizers/__init__.pyi @@ -0,0 +1,1015 @@ +# Generated content DO NOT EDIT +class PreTokenizer: + """ + Base class for all pre-tokenizers + + This class is not supposed to be instantiated directly. Instead, any implementation of a + PreTokenizer will return an instance of this class when instantiated. + """ + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + + @staticmethod + def custom(pretok): + """ """ + pass + + def pre_tokenize(self, pretok): + """ + Pre-tokenize a :class:`~tokenizers.PyPreTokenizedString` in-place + + This method allows to modify a :class:`~tokenizers.PreTokenizedString` to + keep track of the pre-tokenization, and leverage the capabilities of the + :class:`~tokenizers.PreTokenizedString`. If you just want to see the result of + the pre-tokenization of a raw string, you can use + :meth:`~tokenizers.pre_tokenizers.PreTokenizer.pre_tokenize_str` + + Args: + pretok (:class:`~tokenizers.PreTokenizedString): + The pre-tokenized string on which to apply this + :class:`~tokenizers.pre_tokenizers.PreTokenizer` + """ + pass + + def pre_tokenize_str(self, sequence): + """ + Pre tokenize the given string + + This method provides a way to visualize the effect of a + :class:`~tokenizers.pre_tokenizers.PreTokenizer` but it does not keep track of the + alignment, nor does it provide all the capabilities of the + :class:`~tokenizers.PreTokenizedString`. If you need some of these, you can use + :meth:`~tokenizers.pre_tokenizers.PreTokenizer.pre_tokenize` + + Args: + sequence (:obj:`str`): + A string to pre-tokeize + + Returns: + :obj:`List[Tuple[str, Offsets]]`: + A list of tuple with the pre-tokenized parts and their offsets + """ + pass + +class BertPreTokenizer(PreTokenizer): + """ + BertPreTokenizer + + This pre-tokenizer splits tokens on spaces, and also on punctuation. + Each occurrence of a punctuation character will be treated separately. + """ + def __init__(self): + pass + + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + + @staticmethod + def custom(pretok): + """ """ + pass + + def pre_tokenize(self, pretok): + """ + Pre-tokenize a :class:`~tokenizers.PyPreTokenizedString` in-place + + This method allows to modify a :class:`~tokenizers.PreTokenizedString` to + keep track of the pre-tokenization, and leverage the capabilities of the + :class:`~tokenizers.PreTokenizedString`. If you just want to see the result of + the pre-tokenization of a raw string, you can use + :meth:`~tokenizers.pre_tokenizers.PreTokenizer.pre_tokenize_str` + + Args: + pretok (:class:`~tokenizers.PreTokenizedString): + The pre-tokenized string on which to apply this + :class:`~tokenizers.pre_tokenizers.PreTokenizer` + """ + pass + + def pre_tokenize_str(self, sequence): + """ + Pre tokenize the given string + + This method provides a way to visualize the effect of a + :class:`~tokenizers.pre_tokenizers.PreTokenizer` but it does not keep track of the + alignment, nor does it provide all the capabilities of the + :class:`~tokenizers.PreTokenizedString`. If you need some of these, you can use + :meth:`~tokenizers.pre_tokenizers.PreTokenizer.pre_tokenize` + + Args: + sequence (:obj:`str`): + A string to pre-tokeize + + Returns: + :obj:`List[Tuple[str, Offsets]]`: + A list of tuple with the pre-tokenized parts and their offsets + """ + pass + +class ByteLevel(PreTokenizer): + """ + ByteLevel PreTokenizer + + This pre-tokenizer takes care of replacing all bytes of the given string + with a corresponding representation, as well as splitting into words. + + Args: + add_prefix_space (:obj:`bool`, `optional`, defaults to :obj:`True`): + Whether to add a space to the first word if there isn't already one. This + lets us treat `hello` exactly like `say hello`. + use_regex (:obj:`bool`, `optional`, defaults to :obj:`True`): + Set this to :obj:`False` to prevent this `pre_tokenizer` from using + the GPT2 specific regexp for spliting on whitespace. + """ + def __init__(self, add_prefix_space=True, trim_offsets=True, use_regex=True): + pass + + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + + @property + def add_prefix_space(self): + """ """ + pass + + @add_prefix_space.setter + def add_prefix_space(self, value): + """ """ + pass + + @staticmethod + def alphabet(): + """ + Returns the alphabet used by this PreTokenizer. + + Since the ByteLevel works as its name suggests, at the byte level, it + encodes each byte value to a unique visible character. This means that there is a + total of 256 different characters composing this alphabet. + + Returns: + :obj:`List[str]`: A list of characters that compose the alphabet + """ + pass + + @staticmethod + def custom(pretok): + """ """ + pass + + def pre_tokenize(self, pretok): + """ + Pre-tokenize a :class:`~tokenizers.PyPreTokenizedString` in-place + + This method allows to modify a :class:`~tokenizers.PreTokenizedString` to + keep track of the pre-tokenization, and leverage the capabilities of the + :class:`~tokenizers.PreTokenizedString`. If you just want to see the result of + the pre-tokenization of a raw string, you can use + :meth:`~tokenizers.pre_tokenizers.PreTokenizer.pre_tokenize_str` + + Args: + pretok (:class:`~tokenizers.PreTokenizedString): + The pre-tokenized string on which to apply this + :class:`~tokenizers.pre_tokenizers.PreTokenizer` + """ + pass + + def pre_tokenize_str(self, sequence): + """ + Pre tokenize the given string + + This method provides a way to visualize the effect of a + :class:`~tokenizers.pre_tokenizers.PreTokenizer` but it does not keep track of the + alignment, nor does it provide all the capabilities of the + :class:`~tokenizers.PreTokenizedString`. If you need some of these, you can use + :meth:`~tokenizers.pre_tokenizers.PreTokenizer.pre_tokenize` + + Args: + sequence (:obj:`str`): + A string to pre-tokeize + + Returns: + :obj:`List[Tuple[str, Offsets]]`: + A list of tuple with the pre-tokenized parts and their offsets + """ + pass + + @property + def trim_offsets(self): + """ """ + pass + + @trim_offsets.setter + def trim_offsets(self, value): + """ """ + pass + + @property + def use_regex(self): + """ """ + pass + + @use_regex.setter + def use_regex(self, value): + """ """ + pass + +class CharDelimiterSplit(PreTokenizer): + """ + This pre-tokenizer simply splits on the provided char. Works like `.split(delimiter)` + + Args: + delimiter: str: + The delimiter char that will be used to split input + """ + def __init__(self, delimiter): + pass + + def __getnewargs__(self): + """ """ + pass + + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + + @staticmethod + def custom(pretok): + """ """ + pass + + @property + def delimiter(self): + """ """ + pass + + @delimiter.setter + def delimiter(self, value): + """ """ + pass + + def pre_tokenize(self, pretok): + """ + Pre-tokenize a :class:`~tokenizers.PyPreTokenizedString` in-place + + This method allows to modify a :class:`~tokenizers.PreTokenizedString` to + keep track of the pre-tokenization, and leverage the capabilities of the + :class:`~tokenizers.PreTokenizedString`. If you just want to see the result of + the pre-tokenization of a raw string, you can use + :meth:`~tokenizers.pre_tokenizers.PreTokenizer.pre_tokenize_str` + + Args: + pretok (:class:`~tokenizers.PreTokenizedString): + The pre-tokenized string on which to apply this + :class:`~tokenizers.pre_tokenizers.PreTokenizer` + """ + pass + + def pre_tokenize_str(self, sequence): + """ + Pre tokenize the given string + + This method provides a way to visualize the effect of a + :class:`~tokenizers.pre_tokenizers.PreTokenizer` but it does not keep track of the + alignment, nor does it provide all the capabilities of the + :class:`~tokenizers.PreTokenizedString`. If you need some of these, you can use + :meth:`~tokenizers.pre_tokenizers.PreTokenizer.pre_tokenize` + + Args: + sequence (:obj:`str`): + A string to pre-tokeize + + Returns: + :obj:`List[Tuple[str, Offsets]]`: + A list of tuple with the pre-tokenized parts and their offsets + """ + pass + +class Digits(PreTokenizer): + """ + This pre-tokenizer simply splits using the digits in separate tokens + + Args: + individual_digits (:obj:`bool`, `optional`, defaults to :obj:`False`): + If set to True, digits will each be separated as follows:: + + "Call 123 please" -> "Call ", "1", "2", "3", " please" + + If set to False, digits will grouped as follows:: + + "Call 123 please" -> "Call ", "123", " please" + """ + def __init__(self, individual_digits=False): + pass + + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + + @staticmethod + def custom(pretok): + """ """ + pass + + @property + def individual_digits(self): + """ """ + pass + + @individual_digits.setter + def individual_digits(self, value): + """ """ + pass + + def pre_tokenize(self, pretok): + """ + Pre-tokenize a :class:`~tokenizers.PyPreTokenizedString` in-place + + This method allows to modify a :class:`~tokenizers.PreTokenizedString` to + keep track of the pre-tokenization, and leverage the capabilities of the + :class:`~tokenizers.PreTokenizedString`. If you just want to see the result of + the pre-tokenization of a raw string, you can use + :meth:`~tokenizers.pre_tokenizers.PreTokenizer.pre_tokenize_str` + + Args: + pretok (:class:`~tokenizers.PreTokenizedString): + The pre-tokenized string on which to apply this + :class:`~tokenizers.pre_tokenizers.PreTokenizer` + """ + pass + + def pre_tokenize_str(self, sequence): + """ + Pre tokenize the given string + + This method provides a way to visualize the effect of a + :class:`~tokenizers.pre_tokenizers.PreTokenizer` but it does not keep track of the + alignment, nor does it provide all the capabilities of the + :class:`~tokenizers.PreTokenizedString`. If you need some of these, you can use + :meth:`~tokenizers.pre_tokenizers.PreTokenizer.pre_tokenize` + + Args: + sequence (:obj:`str`): + A string to pre-tokeize + + Returns: + :obj:`List[Tuple[str, Offsets]]`: + A list of tuple with the pre-tokenized parts and their offsets + """ + pass + +class FixedLength(PreTokenizer): + """ + This pre-tokenizer splits the text into fixed length chunks as used + [here](https://www.biorxiv.org/content/10.1101/2023.01.11.523679v1.full) + + Args: + length (:obj:`int`, `optional`, defaults to :obj:`5`): + The length of the chunks to split the text into. + + Strings are split on the character level rather than the byte level to avoid + splitting unicode characters consisting of multiple bytes. + """ + def __init__(self, length=5): + pass + + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + + @staticmethod + def custom(pretok): + """ """ + pass + + @property + def length(self): + """ """ + pass + + @length.setter + def length(self, value): + """ """ + pass + + def pre_tokenize(self, pretok): + """ + Pre-tokenize a :class:`~tokenizers.PyPreTokenizedString` in-place + + This method allows to modify a :class:`~tokenizers.PreTokenizedString` to + keep track of the pre-tokenization, and leverage the capabilities of the + :class:`~tokenizers.PreTokenizedString`. If you just want to see the result of + the pre-tokenization of a raw string, you can use + :meth:`~tokenizers.pre_tokenizers.PreTokenizer.pre_tokenize_str` + + Args: + pretok (:class:`~tokenizers.PreTokenizedString): + The pre-tokenized string on which to apply this + :class:`~tokenizers.pre_tokenizers.PreTokenizer` + """ + pass + + def pre_tokenize_str(self, sequence): + """ + Pre tokenize the given string + + This method provides a way to visualize the effect of a + :class:`~tokenizers.pre_tokenizers.PreTokenizer` but it does not keep track of the + alignment, nor does it provide all the capabilities of the + :class:`~tokenizers.PreTokenizedString`. If you need some of these, you can use + :meth:`~tokenizers.pre_tokenizers.PreTokenizer.pre_tokenize` + + Args: + sequence (:obj:`str`): + A string to pre-tokeize + + Returns: + :obj:`List[Tuple[str, Offsets]]`: + A list of tuple with the pre-tokenized parts and their offsets + """ + pass + +class Metaspace(PreTokenizer): + """ + Metaspace pre-tokenizer + + This pre-tokenizer replaces any whitespace by the provided replacement character. + It then tries to split on these spaces. + + Args: + replacement (:obj:`str`, `optional`, defaults to :obj:`▁`): + The replacement character. Must be exactly one character. By default we + use the `▁` (U+2581) meta symbol (Same as in SentencePiece). + + prepend_scheme (:obj:`str`, `optional`, defaults to :obj:`"always"`): + Whether to add a space to the first word if there isn't already one. This + lets us treat `hello` exactly like `say hello`. + Choices: "always", "never", "first". First means the space is only added on the first + token (relevant when special tokens are used or other pre_tokenizer are used). + + """ + def __init__(self, replacement="_", prepend_scheme="always", split=True): + pass + + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + + @staticmethod + def custom(pretok): + """ """ + pass + + def pre_tokenize(self, pretok): + """ + Pre-tokenize a :class:`~tokenizers.PyPreTokenizedString` in-place + + This method allows to modify a :class:`~tokenizers.PreTokenizedString` to + keep track of the pre-tokenization, and leverage the capabilities of the + :class:`~tokenizers.PreTokenizedString`. If you just want to see the result of + the pre-tokenization of a raw string, you can use + :meth:`~tokenizers.pre_tokenizers.PreTokenizer.pre_tokenize_str` + + Args: + pretok (:class:`~tokenizers.PreTokenizedString): + The pre-tokenized string on which to apply this + :class:`~tokenizers.pre_tokenizers.PreTokenizer` + """ + pass + + def pre_tokenize_str(self, sequence): + """ + Pre tokenize the given string + + This method provides a way to visualize the effect of a + :class:`~tokenizers.pre_tokenizers.PreTokenizer` but it does not keep track of the + alignment, nor does it provide all the capabilities of the + :class:`~tokenizers.PreTokenizedString`. If you need some of these, you can use + :meth:`~tokenizers.pre_tokenizers.PreTokenizer.pre_tokenize` + + Args: + sequence (:obj:`str`): + A string to pre-tokeize + + Returns: + :obj:`List[Tuple[str, Offsets]]`: + A list of tuple with the pre-tokenized parts and their offsets + """ + pass + + @property + def prepend_scheme(self): + """ """ + pass + + @prepend_scheme.setter + def prepend_scheme(self, value): + """ """ + pass + + @property + def replacement(self): + """ """ + pass + + @replacement.setter + def replacement(self, value): + """ """ + pass + + @property + def split(self): + """ """ + pass + + @split.setter + def split(self, value): + """ """ + pass + +class Punctuation(PreTokenizer): + """ + This pre-tokenizer simply splits on punctuation as individual characters. + + Args: + behavior (:class:`~tokenizers.SplitDelimiterBehavior`): + The behavior to use when splitting. + Choices: "removed", "isolated" (default), "merged_with_previous", "merged_with_next", + "contiguous" + """ + def __init__(self, behavior="isolated"): + pass + + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + + @property + def behavior(self): + """ """ + pass + + @behavior.setter + def behavior(self, value): + """ """ + pass + + @staticmethod + def custom(pretok): + """ """ + pass + + def pre_tokenize(self, pretok): + """ + Pre-tokenize a :class:`~tokenizers.PyPreTokenizedString` in-place + + This method allows to modify a :class:`~tokenizers.PreTokenizedString` to + keep track of the pre-tokenization, and leverage the capabilities of the + :class:`~tokenizers.PreTokenizedString`. If you just want to see the result of + the pre-tokenization of a raw string, you can use + :meth:`~tokenizers.pre_tokenizers.PreTokenizer.pre_tokenize_str` + + Args: + pretok (:class:`~tokenizers.PreTokenizedString): + The pre-tokenized string on which to apply this + :class:`~tokenizers.pre_tokenizers.PreTokenizer` + """ + pass + + def pre_tokenize_str(self, sequence): + """ + Pre tokenize the given string + + This method provides a way to visualize the effect of a + :class:`~tokenizers.pre_tokenizers.PreTokenizer` but it does not keep track of the + alignment, nor does it provide all the capabilities of the + :class:`~tokenizers.PreTokenizedString`. If you need some of these, you can use + :meth:`~tokenizers.pre_tokenizers.PreTokenizer.pre_tokenize` + + Args: + sequence (:obj:`str`): + A string to pre-tokeize + + Returns: + :obj:`List[Tuple[str, Offsets]]`: + A list of tuple with the pre-tokenized parts and their offsets + """ + pass + +class Sequence(PreTokenizer): + """ + This pre-tokenizer composes other pre_tokenizers and applies them in sequence + """ + def __init__(self, pretokenizers): + pass + + def __getitem__(self, key): + """ + Return self[key]. + """ + pass + + def __getnewargs__(self): + """ """ + pass + + def __getstate__(self): + """ """ + pass + + def __setitem__(self, key, value): + """ + Set self[key] to value. + """ + pass + + def __setstate__(self, state): + """ """ + pass + + @staticmethod + def custom(pretok): + """ """ + pass + + def pre_tokenize(self, pretok): + """ + Pre-tokenize a :class:`~tokenizers.PyPreTokenizedString` in-place + + This method allows to modify a :class:`~tokenizers.PreTokenizedString` to + keep track of the pre-tokenization, and leverage the capabilities of the + :class:`~tokenizers.PreTokenizedString`. If you just want to see the result of + the pre-tokenization of a raw string, you can use + :meth:`~tokenizers.pre_tokenizers.PreTokenizer.pre_tokenize_str` + + Args: + pretok (:class:`~tokenizers.PreTokenizedString): + The pre-tokenized string on which to apply this + :class:`~tokenizers.pre_tokenizers.PreTokenizer` + """ + pass + + def pre_tokenize_str(self, sequence): + """ + Pre tokenize the given string + + This method provides a way to visualize the effect of a + :class:`~tokenizers.pre_tokenizers.PreTokenizer` but it does not keep track of the + alignment, nor does it provide all the capabilities of the + :class:`~tokenizers.PreTokenizedString`. If you need some of these, you can use + :meth:`~tokenizers.pre_tokenizers.PreTokenizer.pre_tokenize` + + Args: + sequence (:obj:`str`): + A string to pre-tokeize + + Returns: + :obj:`List[Tuple[str, Offsets]]`: + A list of tuple with the pre-tokenized parts and their offsets + """ + pass + +class Split(PreTokenizer): + """ + Split PreTokenizer + + This versatile pre-tokenizer splits using the provided pattern and + according to the provided behavior. The pattern can be inverted by + making use of the invert flag. + + Args: + pattern (:obj:`str` or :class:`~tokenizers.Regex`): + A pattern used to split the string. Usually a string or a regex built with `tokenizers.Regex`. + If you want to use a regex pattern, it has to be wrapped around a `tokenizers.Regex`, + otherwise we consider is as a string pattern. For example `pattern="|"` + means you want to split on `|` (imagine a csv file for example), while + `pattern=tokenizers.Regex("1|2")` means you split on either '1' or '2'. + behavior (:class:`~tokenizers.SplitDelimiterBehavior`): + The behavior to use when splitting. + Choices: "removed", "isolated", "merged_with_previous", "merged_with_next", + "contiguous" + + invert (:obj:`bool`, `optional`, defaults to :obj:`False`): + Whether to invert the pattern. + """ + def __init__(self, pattern, behavior, invert=False): + pass + + def __getnewargs__(self): + """ """ + pass + + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + + @property + def behavior(self): + """ """ + pass + + @behavior.setter + def behavior(self, value): + """ """ + pass + + @staticmethod + def custom(pretok): + """ """ + pass + + @property + def invert(self): + """ """ + pass + + @invert.setter + def invert(self, value): + """ """ + pass + + @property + def pattern(self): + """ """ + pass + + @pattern.setter + def pattern(self, value): + """ """ + pass + + def pre_tokenize(self, pretok): + """ + Pre-tokenize a :class:`~tokenizers.PyPreTokenizedString` in-place + + This method allows to modify a :class:`~tokenizers.PreTokenizedString` to + keep track of the pre-tokenization, and leverage the capabilities of the + :class:`~tokenizers.PreTokenizedString`. If you just want to see the result of + the pre-tokenization of a raw string, you can use + :meth:`~tokenizers.pre_tokenizers.PreTokenizer.pre_tokenize_str` + + Args: + pretok (:class:`~tokenizers.PreTokenizedString): + The pre-tokenized string on which to apply this + :class:`~tokenizers.pre_tokenizers.PreTokenizer` + """ + pass + + def pre_tokenize_str(self, sequence): + """ + Pre tokenize the given string + + This method provides a way to visualize the effect of a + :class:`~tokenizers.pre_tokenizers.PreTokenizer` but it does not keep track of the + alignment, nor does it provide all the capabilities of the + :class:`~tokenizers.PreTokenizedString`. If you need some of these, you can use + :meth:`~tokenizers.pre_tokenizers.PreTokenizer.pre_tokenize` + + Args: + sequence (:obj:`str`): + A string to pre-tokeize + + Returns: + :obj:`List[Tuple[str, Offsets]]`: + A list of tuple with the pre-tokenized parts and their offsets + """ + pass + +class UnicodeScripts(PreTokenizer): + """ + This pre-tokenizer splits on characters that belong to different language family + It roughly follows https://github.com/google/sentencepiece/blob/master/data/Scripts.txt + Actually Hiragana and Katakana are fused with Han, and 0x30FC is Han too. + This mimicks SentencePiece Unigram implementation. + """ + def __init__(self): + pass + + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + + @staticmethod + def custom(pretok): + """ """ + pass + + def pre_tokenize(self, pretok): + """ + Pre-tokenize a :class:`~tokenizers.PyPreTokenizedString` in-place + + This method allows to modify a :class:`~tokenizers.PreTokenizedString` to + keep track of the pre-tokenization, and leverage the capabilities of the + :class:`~tokenizers.PreTokenizedString`. If you just want to see the result of + the pre-tokenization of a raw string, you can use + :meth:`~tokenizers.pre_tokenizers.PreTokenizer.pre_tokenize_str` + + Args: + pretok (:class:`~tokenizers.PreTokenizedString): + The pre-tokenized string on which to apply this + :class:`~tokenizers.pre_tokenizers.PreTokenizer` + """ + pass + + def pre_tokenize_str(self, sequence): + """ + Pre tokenize the given string + + This method provides a way to visualize the effect of a + :class:`~tokenizers.pre_tokenizers.PreTokenizer` but it does not keep track of the + alignment, nor does it provide all the capabilities of the + :class:`~tokenizers.PreTokenizedString`. If you need some of these, you can use + :meth:`~tokenizers.pre_tokenizers.PreTokenizer.pre_tokenize` + + Args: + sequence (:obj:`str`): + A string to pre-tokeize + + Returns: + :obj:`List[Tuple[str, Offsets]]`: + A list of tuple with the pre-tokenized parts and their offsets + """ + pass + +class Whitespace(PreTokenizer): + """ + This pre-tokenizer splits on word boundaries according to the `\w+|[^\w\s]+` + regex pattern. It splits on word characters or characters that aren't words or + whitespaces (punctuation such as hyphens, apostrophes, commas, etc.). + + Example: + Use the `Whitespace` function as shown below:: + + ```python + from tokenizers.pre_tokenizers import Whitespace + + pre_tokenizer = Whitespace() + text = "Hello, world! Let's try the Whitespace pre-tokenizer." + pre_tokenizer.pre_tokenize_str(text) + [('Hello', (0, 5)), + (',', (5, 6)), + ('world', (7, 12)), + ('!', (12, 13)), + ('Let', (14, 17)), + ("'", (17, 18)), + ('s', (18, 19)), + ('try', (20, 23)), + ('the', (24, 27)), + ('Whitespace', (28, 38)), + ('pre', (39, 42)), + ('-', (42, 43)), + ('tokenizer', (43, 52)), + ('.', (52, 53))] + ``` + """ + def __init__(self): + pass + + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + + @staticmethod + def custom(pretok): + """ """ + pass + + def pre_tokenize(self, pretok): + """ + Pre-tokenize a :class:`~tokenizers.PyPreTokenizedString` in-place + + This method allows to modify a :class:`~tokenizers.PreTokenizedString` to + keep track of the pre-tokenization, and leverage the capabilities of the + :class:`~tokenizers.PreTokenizedString`. If you just want to see the result of + the pre-tokenization of a raw string, you can use + :meth:`~tokenizers.pre_tokenizers.PreTokenizer.pre_tokenize_str` + + Args: + pretok (:class:`~tokenizers.PreTokenizedString): + The pre-tokenized string on which to apply this + :class:`~tokenizers.pre_tokenizers.PreTokenizer` + """ + pass + + def pre_tokenize_str(self, sequence): + """ + Pre tokenize the given string + + This method provides a way to visualize the effect of a + :class:`~tokenizers.pre_tokenizers.PreTokenizer` but it does not keep track of the + alignment, nor does it provide all the capabilities of the + :class:`~tokenizers.PreTokenizedString`. If you need some of these, you can use + :meth:`~tokenizers.pre_tokenizers.PreTokenizer.pre_tokenize` + + Args: + sequence (:obj:`str`): + A string to pre-tokeize + + Returns: + :obj:`List[Tuple[str, Offsets]]`: + A list of tuple with the pre-tokenized parts and their offsets + """ + pass + +class WhitespaceSplit(PreTokenizer): + """ + This pre-tokenizer simply splits on the whitespace. Works like `.split()` + """ + def __init__(self): + pass + + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + + @staticmethod + def custom(pretok): + """ """ + pass + + def pre_tokenize(self, pretok): + """ + Pre-tokenize a :class:`~tokenizers.PyPreTokenizedString` in-place + + This method allows to modify a :class:`~tokenizers.PreTokenizedString` to + keep track of the pre-tokenization, and leverage the capabilities of the + :class:`~tokenizers.PreTokenizedString`. If you just want to see the result of + the pre-tokenization of a raw string, you can use + :meth:`~tokenizers.pre_tokenizers.PreTokenizer.pre_tokenize_str` + + Args: + pretok (:class:`~tokenizers.PreTokenizedString): + The pre-tokenized string on which to apply this + :class:`~tokenizers.pre_tokenizers.PreTokenizer` + """ + pass + + def pre_tokenize_str(self, sequence): + """ + Pre tokenize the given string + + This method provides a way to visualize the effect of a + :class:`~tokenizers.pre_tokenizers.PreTokenizer` but it does not keep track of the + alignment, nor does it provide all the capabilities of the + :class:`~tokenizers.PreTokenizedString`. If you need some of these, you can use + :meth:`~tokenizers.pre_tokenizers.PreTokenizer.pre_tokenize` + + Args: + sequence (:obj:`str`): + A string to pre-tokeize + + Returns: + :obj:`List[Tuple[str, Offsets]]`: + A list of tuple with the pre-tokenized parts and their offsets + """ + pass diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/processors/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/processors/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..06d124037b6d932615fa0d31b02f8ac82ac0b5fc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/processors/__init__.py @@ -0,0 +1,9 @@ +# Generated content DO NOT EDIT +from .. import processors + +PostProcessor = processors.PostProcessor +BertProcessing = processors.BertProcessing +ByteLevel = processors.ByteLevel +RobertaProcessing = processors.RobertaProcessing +Sequence = processors.Sequence +TemplateProcessing = processors.TemplateProcessing diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/processors/__init__.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/processors/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..0d49520c63e56c90b45c4a24604938daebbaeb07 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/processors/__init__.pyi @@ -0,0 +1,519 @@ +# Generated content DO NOT EDIT +class PostProcessor: + """ + Base class for all post-processors + + This class is not supposed to be instantiated directly. Instead, any implementation of + a PostProcessor will return an instance of this class when instantiated. + """ + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + + def num_special_tokens_to_add(self, is_pair): + """ + Return the number of special tokens that would be added for single/pair sentences. + + Args: + is_pair (:obj:`bool`): + Whether the input would be a pair of sequences + + Returns: + :obj:`int`: The number of tokens to add + """ + pass + + def process(self, encoding, pair=None, add_special_tokens=True): + """ + Post-process the given encodings, generating the final one + + Args: + encoding (:class:`~tokenizers.Encoding`): + The encoding for the first sequence + + pair (:class:`~tokenizers.Encoding`, `optional`): + The encoding for the pair sequence + + add_special_tokens (:obj:`bool`): + Whether to add the special tokens + + Return: + :class:`~tokenizers.Encoding`: The final encoding + """ + pass + +class BertProcessing(PostProcessor): + """ + This post-processor takes care of adding the special tokens needed by + a Bert model: + + - a SEP token + - a CLS token + + Args: + sep (:obj:`Tuple[str, int]`): + A tuple with the string representation of the SEP token, and its id + + cls (:obj:`Tuple[str, int]`): + A tuple with the string representation of the CLS token, and its id + """ + def __init__(self, sep, cls): + pass + + def __getnewargs__(self): + """ """ + pass + + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + + @property + def cls(self): + """ """ + pass + + @cls.setter + def cls(self, value): + """ """ + pass + + def num_special_tokens_to_add(self, is_pair): + """ + Return the number of special tokens that would be added for single/pair sentences. + + Args: + is_pair (:obj:`bool`): + Whether the input would be a pair of sequences + + Returns: + :obj:`int`: The number of tokens to add + """ + pass + + def process(self, encoding, pair=None, add_special_tokens=True): + """ + Post-process the given encodings, generating the final one + + Args: + encoding (:class:`~tokenizers.Encoding`): + The encoding for the first sequence + + pair (:class:`~tokenizers.Encoding`, `optional`): + The encoding for the pair sequence + + add_special_tokens (:obj:`bool`): + Whether to add the special tokens + + Return: + :class:`~tokenizers.Encoding`: The final encoding + """ + pass + + @property + def sep(self): + """ """ + pass + + @sep.setter + def sep(self, value): + """ """ + pass + +class ByteLevel(PostProcessor): + """ + This post-processor takes care of trimming the offsets. + + By default, the ByteLevel BPE might include whitespaces in the produced tokens. If you don't + want the offsets to include these whitespaces, then this PostProcessor must be used. + + Args: + trim_offsets (:obj:`bool`): + Whether to trim the whitespaces from the produced offsets. + + add_prefix_space (:obj:`bool`, `optional`, defaults to :obj:`True`): + If :obj:`True`, keeps the first token's offset as is. If :obj:`False`, increments + the start of the first token's offset by 1. Only has an effect if :obj:`trim_offsets` + is set to :obj:`True`. + """ + def __init__(self, add_prefix_space=None, trim_offsets=None, use_regex=None): + pass + + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + + @property + def add_prefix_space(self): + """ """ + pass + + @add_prefix_space.setter + def add_prefix_space(self, value): + """ """ + pass + + def num_special_tokens_to_add(self, is_pair): + """ + Return the number of special tokens that would be added for single/pair sentences. + + Args: + is_pair (:obj:`bool`): + Whether the input would be a pair of sequences + + Returns: + :obj:`int`: The number of tokens to add + """ + pass + + def process(self, encoding, pair=None, add_special_tokens=True): + """ + Post-process the given encodings, generating the final one + + Args: + encoding (:class:`~tokenizers.Encoding`): + The encoding for the first sequence + + pair (:class:`~tokenizers.Encoding`, `optional`): + The encoding for the pair sequence + + add_special_tokens (:obj:`bool`): + Whether to add the special tokens + + Return: + :class:`~tokenizers.Encoding`: The final encoding + """ + pass + + @property + def trim_offsets(self): + """ """ + pass + + @trim_offsets.setter + def trim_offsets(self, value): + """ """ + pass + + @property + def use_regex(self): + """ """ + pass + + @use_regex.setter + def use_regex(self, value): + """ """ + pass + +class RobertaProcessing(PostProcessor): + """ + This post-processor takes care of adding the special tokens needed by + a Roberta model: + + - a SEP token + - a CLS token + + It also takes care of trimming the offsets. + By default, the ByteLevel BPE might include whitespaces in the produced tokens. If you don't + want the offsets to include these whitespaces, then this PostProcessor should be initialized + with :obj:`trim_offsets=True` + + Args: + sep (:obj:`Tuple[str, int]`): + A tuple with the string representation of the SEP token, and its id + + cls (:obj:`Tuple[str, int]`): + A tuple with the string representation of the CLS token, and its id + + trim_offsets (:obj:`bool`, `optional`, defaults to :obj:`True`): + Whether to trim the whitespaces from the produced offsets. + + add_prefix_space (:obj:`bool`, `optional`, defaults to :obj:`True`): + Whether the add_prefix_space option was enabled during pre-tokenization. This + is relevant because it defines the way the offsets are trimmed out. + """ + def __init__(self, sep, cls, trim_offsets=True, add_prefix_space=True): + pass + + def __getnewargs__(self): + """ """ + pass + + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + + @property + def add_prefix_space(self): + """ """ + pass + + @add_prefix_space.setter + def add_prefix_space(self, value): + """ """ + pass + + @property + def cls(self): + """ """ + pass + + @cls.setter + def cls(self, value): + """ """ + pass + + def num_special_tokens_to_add(self, is_pair): + """ + Return the number of special tokens that would be added for single/pair sentences. + + Args: + is_pair (:obj:`bool`): + Whether the input would be a pair of sequences + + Returns: + :obj:`int`: The number of tokens to add + """ + pass + + def process(self, encoding, pair=None, add_special_tokens=True): + """ + Post-process the given encodings, generating the final one + + Args: + encoding (:class:`~tokenizers.Encoding`): + The encoding for the first sequence + + pair (:class:`~tokenizers.Encoding`, `optional`): + The encoding for the pair sequence + + add_special_tokens (:obj:`bool`): + Whether to add the special tokens + + Return: + :class:`~tokenizers.Encoding`: The final encoding + """ + pass + + @property + def sep(self): + """ """ + pass + + @sep.setter + def sep(self, value): + """ """ + pass + + @property + def trim_offsets(self): + """ """ + pass + + @trim_offsets.setter + def trim_offsets(self, value): + """ """ + pass + +class Sequence(PostProcessor): + """ + Sequence Processor + + Args: + processors (:obj:`List[PostProcessor]`) + The processors that need to be chained + """ + def __init__(self, processors): + pass + + def __getitem__(self, key): + """ + Return self[key]. + """ + pass + + def __getnewargs__(self): + """ """ + pass + + def __getstate__(self): + """ """ + pass + + def __setitem__(self, key, value): + """ + Set self[key] to value. + """ + pass + + def __setstate__(self, state): + """ """ + pass + + def num_special_tokens_to_add(self, is_pair): + """ + Return the number of special tokens that would be added for single/pair sentences. + + Args: + is_pair (:obj:`bool`): + Whether the input would be a pair of sequences + + Returns: + :obj:`int`: The number of tokens to add + """ + pass + + def process(self, encoding, pair=None, add_special_tokens=True): + """ + Post-process the given encodings, generating the final one + + Args: + encoding (:class:`~tokenizers.Encoding`): + The encoding for the first sequence + + pair (:class:`~tokenizers.Encoding`, `optional`): + The encoding for the pair sequence + + add_special_tokens (:obj:`bool`): + Whether to add the special tokens + + Return: + :class:`~tokenizers.Encoding`: The final encoding + """ + pass + +class TemplateProcessing(PostProcessor): + """ + Provides a way to specify templates in order to add the special tokens to each + input sequence as relevant. + + Let's take :obj:`BERT` tokenizer as an example. It uses two special tokens, used to + delimitate each sequence. :obj:`[CLS]` is always used at the beginning of the first + sequence, and :obj:`[SEP]` is added at the end of both the first, and the pair + sequences. The final result looks like this: + + - Single sequence: :obj:`[CLS] Hello there [SEP]` + - Pair sequences: :obj:`[CLS] My name is Anthony [SEP] What is my name? [SEP]` + + With the type ids as following:: + + [CLS] ... [SEP] ... [SEP] + 0 0 0 1 1 + + You can achieve such behavior using a TemplateProcessing:: + + TemplateProcessing( + single="[CLS] $0 [SEP]", + pair="[CLS] $A [SEP] $B:1 [SEP]:1", + special_tokens=[("[CLS]", 1), ("[SEP]", 0)], + ) + + In this example, each input sequence is identified using a ``$`` construct. This identifier + lets us specify each input sequence, and the type_id to use. When nothing is specified, + it uses the default values. Here are the different ways to specify it: + + - Specifying the sequence, with default ``type_id == 0``: ``$A`` or ``$B`` + - Specifying the `type_id` with default ``sequence == A``: ``$0``, ``$1``, ``$2``, ... + - Specifying both: ``$A:0``, ``$B:1``, ... + + The same construct is used for special tokens: ``(:)?``. + + **Warning**: You must ensure that you are giving the correct tokens/ids as these + will be added to the Encoding without any further check. If the given ids correspond + to something totally different in a `Tokenizer` using this `PostProcessor`, it + might lead to unexpected results. + + Args: + single (:obj:`Template`): + The template used for single sequences + + pair (:obj:`Template`): + The template used when both sequences are specified + + special_tokens (:obj:`Tokens`): + The list of special tokens used in each sequences + + Types: + + Template (:obj:`str` or :obj:`List`): + - If a :obj:`str` is provided, the whitespace is used as delimiter between tokens + - If a :obj:`List[str]` is provided, a list of tokens + + Tokens (:obj:`List[Union[Tuple[int, str], Tuple[str, int], dict]]`): + - A :obj:`Tuple` with both a token and its associated ID, in any order + - A :obj:`dict` with the following keys: + - "id": :obj:`str` => The special token id, as specified in the Template + - "ids": :obj:`List[int]` => The associated IDs + - "tokens": :obj:`List[str]` => The associated tokens + + The given dict expects the provided :obj:`ids` and :obj:`tokens` lists to have + the same length. + """ + def __init__(self, single=None, pair=None, special_tokens=None): + pass + + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + + def num_special_tokens_to_add(self, is_pair): + """ + Return the number of special tokens that would be added for single/pair sentences. + + Args: + is_pair (:obj:`bool`): + Whether the input would be a pair of sequences + + Returns: + :obj:`int`: The number of tokens to add + """ + pass + + def process(self, encoding, pair=None, add_special_tokens=True): + """ + Post-process the given encodings, generating the final one + + Args: + encoding (:class:`~tokenizers.Encoding`): + The encoding for the first sequence + + pair (:class:`~tokenizers.Encoding`, `optional`): + The encoding for the pair sequence + + add_special_tokens (:obj:`bool`): + Whether to add the special tokens + + Return: + :class:`~tokenizers.Encoding`: The final encoding + """ + pass + + @property + def single(self): + """ """ + pass + + @single.setter + def single(self, value): + """ """ + pass diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/tokenizers.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/tokenizers.pyi new file mode 100644 index 0000000000000000000000000000000000000000..e27c329f0dee4fc12190c89065e5393f19676123 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/tokenizers.pyi @@ -0,0 +1,17 @@ +# Generated content DO NOT EDIT +from . import ( + AddedToken as AddedToken, + Encoding as Encoding, + NormalizedString as NormalizedString, + PreTokenizedString as PreTokenizedString, + Regex as Regex, + Token as Token, + Tokenizer as Tokenizer, + __version__ as __version__, + decoders as decoders, + models as models, + normalizers as normalizers, + pre_tokenizers as pre_tokenizers, + processors as processors, + trainers as trainers, +) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/tools/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/tools/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f941e2ed39c7d69fa14abff7dcf973d93843ea06 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/tools/__init__.py @@ -0,0 +1 @@ +from .visualizer import Annotation, EncodingVisualizer diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/tools/visualizer-styles.css b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/tools/visualizer-styles.css new file mode 100644 index 0000000000000000000000000000000000000000..f54fde45ada66c902c0b41969d0f40d51c9717da --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/tools/visualizer-styles.css @@ -0,0 +1,170 @@ +.tokenized-text { + width:100%; + padding:2rem; + max-height: 400px; + overflow-y: auto; + box-sizing:border-box; + line-height:4rem; /* Lots of space between lines */ + font-family: "Roboto Light", "Ubuntu Light", "Ubuntu", monospace; + box-shadow: 2px 2px 2px rgba(0,0,0,0.2); + background-color: rgba(0,0,0,0.01); + letter-spacing:2px; /* Give some extra separation between chars */ +} +.non-token{ + /* White space and other things the tokenizer ignores*/ + white-space: pre; + letter-spacing:4px; + border-top:1px solid #A0A0A0; /* A gentle border on top and bottom makes tabs more ovious*/ + border-bottom:1px solid #A0A0A0; + line-height: 1rem; + height: calc(100% - 2px); +} + +.token { + white-space: pre; + position:relative; + color:black; + letter-spacing:2px; +} + +.annotation{ + white-space:nowrap; /* Important - ensures that annotations appears even if the annotated text wraps a line */ + border-radius:4px; + position:relative; + width:fit-content; +} +.annotation:before { + /*The before holds the text and the after holds the background*/ + z-index:1000; /* Make sure this is above the background */ + content:attr(data-label); /* The annotations label is on a data attribute */ + color:white; + position:absolute; + font-size:1rem; + text-align:center; + font-weight:bold; + + top:1.75rem; + line-height:0; + left:0; + width:100%; + padding:0.5rem 0; + /* These make it so an annotation doesn't stretch beyond the annotated text if the label is longer*/ + overflow: hidden; + white-space: nowrap; + text-overflow:ellipsis; +} + +.annotation:after { + content:attr(data-label); /* The content defines the width of the annotation*/ + position:absolute; + font-size:0.75rem; + text-align:center; + font-weight:bold; + text-overflow:ellipsis; + top:1.75rem; + line-height:0; + overflow: hidden; + white-space: nowrap; + + left:0; + width:100%; /* 100% of the parent, which is the annotation whose width is the tokens inside it*/ + + padding:0.5rem 0; + /* Nast hack below: + We set the annotations color in code because we don't know the colors at css time. + But you can't pass a color as a data attribute to get it into the pseudo element (this thing) + So to get around that, annotations have the color set on them with a style attribute and then we + can get the color with currentColor. + Annotations wrap tokens and tokens set the color back to black + */ + background-color: currentColor; +} +.annotation:hover::after, .annotation:hover::before{ + /* When the user hovers over an annotation expand the label to display in full + */ + min-width: fit-content; +} + +.annotation:hover{ + /* Emphasize the annotation start end with a border on hover*/ + border-color: currentColor; + border: 2px solid; +} +.special-token:not(:empty){ + /* + A none empty special token is like UNK (as opposed to CLS which has no representation in the text ) + */ + position:relative; +} +.special-token:empty::before{ + /* Special tokens that don't have text are displayed as pseudo elements so we dont select them with the mouse*/ + content:attr(data-stok); + background:#202020; + font-size:0.75rem; + color:white; + margin: 0 0.25rem; + padding: 0.25rem; + border-radius:4px +} + +.special-token:not(:empty):before { + /* Special tokens that have text (UNK) are displayed above the actual text*/ + content:attr(data-stok); + position:absolute; + bottom:1.75rem; + min-width:100%; + width:100%; + height:1rem; + line-height:1rem; + font-size:1rem; + text-align:center; + color:white; + font-weight:bold; + background:#202020; + border-radius:10%; +} +/* +We want to alternate the color of tokens, but we can't use nth child because tokens might be broken up by annotations +instead we apply even and odd class at generation time and color them that way + */ +.even-token{ + background:#DCDCDC ; + border: 1px solid #DCDCDC; +} +.odd-token{ + background:#A0A0A0; + border: 1px solid #A0A0A0; +} +.even-token.multi-token,.odd-token.multi-token{ + background: repeating-linear-gradient( + 45deg, + transparent, + transparent 1px, + #ccc 1px, + #ccc 1px + ), + /* on "bottom" */ + linear-gradient( + to bottom, + #FFB6C1, + #999 + ); +} + +.multi-token:hover::after { + content:"This char has more than 1 token"; /* The content defines the width of the annotation*/ + color:white; + background-color: black; + position:absolute; + font-size:0.75rem; + text-align:center; + font-weight:bold; + text-overflow:ellipsis; + top:1.75rem; + line-height:0; + overflow: hidden; + white-space: nowrap; + left:0; + width:fit-content; /* 100% of the parent, which is the annotation whose width is the tokens inside it*/ + padding:0.5rem 0; +} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/tools/visualizer.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/tools/visualizer.py new file mode 100644 index 0000000000000000000000000000000000000000..9e85f13e05baea5cec69136eb3c951cf28a84207 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/tools/visualizer.py @@ -0,0 +1,407 @@ +import itertools +import os +import re +from string import Template +from typing import Any, Callable, Dict, List, NamedTuple, Optional, Tuple + +from tokenizers import Encoding, Tokenizer + + +dirname = os.path.dirname(__file__) +css_filename = os.path.join(dirname, "visualizer-styles.css") +with open(css_filename) as f: + css = f.read() + + +class Annotation: + start: int + end: int + label: str + + def __init__(self, start: int, end: int, label: str): + self.start = start + self.end = end + self.label = label + + +AnnotationList = List[Annotation] +PartialIntList = List[Optional[int]] + + +class CharStateKey(NamedTuple): + token_ix: Optional[int] + anno_ix: Optional[int] + + +class CharState: + char_ix: Optional[int] + + def __init__(self, char_ix): + self.char_ix = char_ix + + self.anno_ix: Optional[int] = None + self.tokens: List[int] = [] + + @property + def token_ix(self): + return self.tokens[0] if len(self.tokens) > 0 else None + + @property + def is_multitoken(self): + """ + BPE tokenizers can output more than one token for a char + """ + return len(self.tokens) > 1 + + def partition_key(self) -> CharStateKey: + return CharStateKey( + token_ix=self.token_ix, + anno_ix=self.anno_ix, + ) + + +class Aligned: + pass + + +class EncodingVisualizer: + """ + Build an EncodingVisualizer + + Args: + + tokenizer (:class:`~tokenizers.Tokenizer`): + A tokenizer instance + + default_to_notebook (:obj:`bool`): + Whether to render html output in a notebook by default + + annotation_converter (:obj:`Callable`, `optional`): + An optional (lambda) function that takes an annotation in any format and returns + an Annotation object + """ + + unk_token_regex = re.compile("(.{1}\b)?(unk|oov)(\b.{1})?", flags=re.IGNORECASE) + + def __init__( + self, + tokenizer: Tokenizer, + default_to_notebook: bool = True, + annotation_converter: Optional[Callable[[Any], Annotation]] = None, + ): + if default_to_notebook: + try: + from IPython.core.display import HTML, display # type: ignore[attr-defined] + except ImportError: + raise Exception( + """We couldn't import IPython utils for html display. + Are you running in a notebook? + You can also pass `default_to_notebook=False` to get back raw HTML + """ + ) + + self.tokenizer = tokenizer + self.default_to_notebook = default_to_notebook + self.annotation_coverter = annotation_converter + pass + + def __call__( + self, + text: str, + annotations: Optional[List[Any]] = None, + default_to_notebook: Optional[bool] = None, + ) -> Optional[str]: + """ + Build a visualization of the given text + + Args: + text (:obj:`str`): + The text to tokenize + + annotations (:obj:`List[Annotation]`, `optional`): + An optional list of annotations of the text. The can either be an annotation class + or anything else if you instantiated the visualizer with a converter function + + default_to_notebook (:obj:`bool`, `optional`, defaults to `False`): + If True, will render the html in a notebook. Otherwise returns an html string. + + Returns: + The HTML string if default_to_notebook is False, otherwise (default) returns None and + renders the HTML in the notebook + + """ + final_default_to_notebook = self.default_to_notebook + if default_to_notebook is not None: + final_default_to_notebook = default_to_notebook + if final_default_to_notebook: + try: + from IPython.core.display import HTML, display # type: ignore[attr-defined] + except ImportError: + raise Exception( + """We couldn't import IPython utils for html display. + Are you running in a notebook?""" + ) + if annotations is None: + annotations = [] + if self.annotation_coverter is not None: + annotations = list(map(self.annotation_coverter, annotations)) + encoding = self.tokenizer.encode(text) + html = EncodingVisualizer.__make_html(text, encoding, annotations) + if final_default_to_notebook: + display(HTML(html)) + else: + return html + + @staticmethod + def calculate_label_colors(annotations: AnnotationList) -> Dict[str, str]: + """ + Generates a color palette for all the labels in a given set of annotations + + Args: + annotations (:obj:`Annotation`): + A list of annotations + + Returns: + :obj:`dict`: A dictionary mapping labels to colors in HSL format + """ + if len(annotations) == 0: + return {} + labels = set(map(lambda x: x.label, annotations)) + num_labels = len(labels) + h_step = int(255 / num_labels) + if h_step < 20: + h_step = 20 + s = 32 + l = 64 # noqa: E741 + h = 10 + colors = {} + + for label in sorted(labels): # sort so we always get the same colors for a given set of labels + colors[label] = f"hsl({h},{s}%,{l}%)" + h += h_step + return colors + + @staticmethod + def consecutive_chars_to_html( + consecutive_chars_list: List[CharState], + text: str, + encoding: Encoding, + ): + """ + Converts a list of "consecutive chars" into a single HTML element. + Chars are consecutive if they fall under the same word, token and annotation. + The CharState class is a named tuple with a "partition_key" method that makes it easy to + compare if two chars are consecutive. + + Args: + consecutive_chars_list (:obj:`List[CharState]`): + A list of CharStates that have been grouped together + + text (:obj:`str`): + The original text being processed + + encoding (:class:`~tokenizers.Encoding`): + The encoding returned from the tokenizer + + Returns: + :obj:`str`: The HTML span for a set of consecutive chars + """ + first = consecutive_chars_list[0] + if first.char_ix is None: + # its a special token + stoken = encoding.tokens[first.token_ix] + # special tokens are represented as empty spans. We use the data attribute and css + # magic to display it + return f'' + # We're not in a special token so this group has a start and end. + last = consecutive_chars_list[-1] + assert first.char_ix is not None + assert last.char_ix is not None + start = first.char_ix + end = last.char_ix + 1 + span_text = text[start:end] + css_classes = [] # What css classes will we apply on the resulting span + data_items = {} # What data attributes will we apply on the result span + if first.token_ix is not None: + # We can either be in a token or not (e.g. in white space) + css_classes.append("token") + if first.is_multitoken: + css_classes.append("multi-token") + if first.token_ix % 2: + # We use this to color alternating tokens. + # A token might be split by an annotation that ends in the middle of it, so this + # lets us visually indicate a consecutive token despite its possible splitting in + # the html markup + css_classes.append("odd-token") + else: + # Like above, but a different color so we can see the tokens alternate + css_classes.append("even-token") + if EncodingVisualizer.unk_token_regex.search(encoding.tokens[first.token_ix]) is not None: + # This is a special token that is in the text. probably UNK + css_classes.append("special-token") + # TODO is this the right name for the data attribute ? + data_items["stok"] = encoding.tokens[first.token_ix] + else: + # In this case we are looking at a group/single char that is not tokenized. + # e.g. white space + css_classes.append("non-token") + css = f'''class="{" ".join(css_classes)}"''' + data = "" + for key, val in data_items.items(): + data += f' data-{key}="{val}"' + return f"{span_text}" + + @staticmethod + def __make_html(text: str, encoding: Encoding, annotations: AnnotationList) -> str: + char_states = EncodingVisualizer.__make_char_states(text, encoding, annotations) + current_consecutive_chars = [char_states[0]] + prev_anno_ix = char_states[0].anno_ix + spans = [] + label_colors_dict = EncodingVisualizer.calculate_label_colors(annotations) + cur_anno_ix = char_states[0].anno_ix + if cur_anno_ix is not None: + # If we started in an annotation make a span for it + anno = annotations[cur_anno_ix] + label = anno.label + color = label_colors_dict[label] + spans.append(f'') + + for cs in char_states[1:]: + cur_anno_ix = cs.anno_ix + if cur_anno_ix != prev_anno_ix: + # If we've transitioned in or out of an annotation + spans.append( + # Create a span from the current consecutive characters + EncodingVisualizer.consecutive_chars_to_html( + current_consecutive_chars, + text=text, + encoding=encoding, + ) + ) + current_consecutive_chars = [cs] + + if prev_anno_ix is not None: + # if we transitioned out of an annotation close it's span + spans.append("") + if cur_anno_ix is not None: + # If we entered a new annotation make a span for it + anno = annotations[cur_anno_ix] + label = anno.label + color = label_colors_dict[label] + spans.append(f'') + prev_anno_ix = cur_anno_ix + + if cs.partition_key() == current_consecutive_chars[0].partition_key(): + # If the current charchter is in the same "group" as the previous one + current_consecutive_chars.append(cs) + else: + # Otherwise we make a span for the previous group + spans.append( + EncodingVisualizer.consecutive_chars_to_html( + current_consecutive_chars, + text=text, + encoding=encoding, + ) + ) + # An reset the consecutive_char_list to form a new group + current_consecutive_chars = [cs] + # All that's left is to fill out the final span + # TODO I think there is an edge case here where an annotation's span might not close + spans.append( + EncodingVisualizer.consecutive_chars_to_html( + current_consecutive_chars, + text=text, + encoding=encoding, + ) + ) + res = HTMLBody(spans) # Send the list of spans to the body of our html + return res + + @staticmethod + def __make_anno_map(text: str, annotations: AnnotationList) -> PartialIntList: + """ + Args: + text (:obj:`str`): + The raw text we want to align to + + annotations (:obj:`AnnotationList`): + A (possibly empty) list of annotations + + Returns: + A list of length len(text) whose entry at index i is None if there is no annotation on + character i or k, the index of the annotation that covers index i where k is with + respect to the list of annotations + """ + annotation_map = [None] * len(text) + for anno_ix, a in enumerate(annotations): + for i in range(a.start, a.end): + annotation_map[i] = anno_ix + return annotation_map + + @staticmethod + def __make_char_states(text: str, encoding: Encoding, annotations: AnnotationList) -> List[CharState]: + """ + For each character in the original text, we emit a tuple representing it's "state": + + * which token_ix it corresponds to + * which word_ix it corresponds to + * which annotation_ix it corresponds to + + Args: + text (:obj:`str`): + The raw text we want to align to + + annotations (:obj:`List[Annotation]`): + A (possibly empty) list of annotations + + encoding: (:class:`~tokenizers.Encoding`): + The encoding returned from the tokenizer + + Returns: + :obj:`List[CharState]`: A list of CharStates, indicating for each char in the text what + it's state is + """ + annotation_map = EncodingVisualizer.__make_anno_map(text, annotations) + # Todo make this a dataclass or named tuple + char_states: List[CharState] = [CharState(char_ix) for char_ix in range(len(text))] + for token_ix, token in enumerate(encoding.tokens): + offsets = encoding.token_to_chars(token_ix) + if offsets is not None: + start, end = offsets + for i in range(start, end): + char_states[i].tokens.append(token_ix) + for char_ix, anno_ix in enumerate(annotation_map): + char_states[char_ix].anno_ix = anno_ix + + return char_states + + +def HTMLBody(children: List[str], css_styles=css) -> str: + """ + Generates the full html with css from a list of html spans + + Args: + children (:obj:`List[str]`): + A list of strings, assumed to be html elements + + css_styles (:obj:`str`, `optional`): + Optional alternative implementation of the css + + Returns: + :obj:`str`: An HTML string with style markup + """ + children_text = "".join(children) + return f""" + + + + + +
+ {children_text} +
+ + + """ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/trainers/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/trainers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..22f94c50b7cf63f0b38231ab1ecec88141a678fd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/trainers/__init__.py @@ -0,0 +1,8 @@ +# Generated content DO NOT EDIT +from .. import trainers + +Trainer = trainers.Trainer +BpeTrainer = trainers.BpeTrainer +UnigramTrainer = trainers.UnigramTrainer +WordLevelTrainer = trainers.WordLevelTrainer +WordPieceTrainer = trainers.WordPieceTrainer diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/trainers/__init__.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/trainers/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..d7bf6c5283afb0d9fa046ffa93bb5501fafe06aa --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tokenizers/trainers/__init__.pyi @@ -0,0 +1,462 @@ +# Generated content DO NOT EDIT +class Trainer: + """ + Base class for all trainers + + This class is not supposed to be instantiated directly. Instead, any implementation of a + Trainer will return an instance of this class when instantiated. + """ + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + +class BpeTrainer(Trainer): + """ + Trainer capable of training a BPE model + + Args: + vocab_size (:obj:`int`, `optional`): + The size of the final vocabulary, including all tokens and alphabet. + + min_frequency (:obj:`int`, `optional`): + The minimum frequency a pair should have in order to be merged. + + show_progress (:obj:`bool`, `optional`): + Whether to show progress bars while training. + + special_tokens (:obj:`List[Union[str, AddedToken]]`, `optional`): + A list of special tokens the model should know of. + + limit_alphabet (:obj:`int`, `optional`): + The maximum different characters to keep in the alphabet. + + initial_alphabet (:obj:`List[str]`, `optional`): + A list of characters to include in the initial alphabet, even + if not seen in the training dataset. + If the strings contain more than one character, only the first one + is kept. + + continuing_subword_prefix (:obj:`str`, `optional`): + A prefix to be used for every subword that is not a beginning-of-word. + + end_of_word_suffix (:obj:`str`, `optional`): + A suffix to be used for every subword that is a end-of-word. + + max_token_length (:obj:`int`, `optional`): + Prevents creating tokens longer than the specified size. + This can help with reducing polluting your vocabulary with + highly repetitive tokens like `======` for wikipedia + + """ + def __init__( + self, + vocab_size=30000, + min_frequency=0, + show_progress=True, + special_tokens=[], + limit_alphabet=None, + initial_alphabet=[], + continuing_subword_prefix=None, + end_of_word_suffix=None, + max_token_length=None, + words={}, + ): + pass + + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + + @property + def continuing_subword_prefix(self): + """ """ + pass + + @continuing_subword_prefix.setter + def continuing_subword_prefix(self, value): + """ """ + pass + + @property + def end_of_word_suffix(self): + """ """ + pass + + @end_of_word_suffix.setter + def end_of_word_suffix(self, value): + """ """ + pass + + @property + def initial_alphabet(self): + """ """ + pass + + @initial_alphabet.setter + def initial_alphabet(self, value): + """ """ + pass + + @property + def limit_alphabet(self): + """ """ + pass + + @limit_alphabet.setter + def limit_alphabet(self, value): + """ """ + pass + + @property + def max_token_length(self): + """ """ + pass + + @max_token_length.setter + def max_token_length(self, value): + """ """ + pass + + @property + def min_frequency(self): + """ """ + pass + + @min_frequency.setter + def min_frequency(self, value): + """ """ + pass + + @property + def show_progress(self): + """ """ + pass + + @show_progress.setter + def show_progress(self, value): + """ """ + pass + + @property + def special_tokens(self): + """ """ + pass + + @special_tokens.setter + def special_tokens(self, value): + """ """ + pass + + @property + def vocab_size(self): + """ """ + pass + + @vocab_size.setter + def vocab_size(self, value): + """ """ + pass + +class UnigramTrainer(Trainer): + """ + Trainer capable of training a Unigram model + + Args: + vocab_size (:obj:`int`): + The size of the final vocabulary, including all tokens and alphabet. + + show_progress (:obj:`bool`): + Whether to show progress bars while training. + + special_tokens (:obj:`List[Union[str, AddedToken]]`): + A list of special tokens the model should know of. + + initial_alphabet (:obj:`List[str]`): + A list of characters to include in the initial alphabet, even + if not seen in the training dataset. + If the strings contain more than one character, only the first one + is kept. + + shrinking_factor (:obj:`float`): + The shrinking factor used at each step of the training to prune the + vocabulary. + + unk_token (:obj:`str`): + The token used for out-of-vocabulary tokens. + + max_piece_length (:obj:`int`): + The maximum length of a given token. + + n_sub_iterations (:obj:`int`): + The number of iterations of the EM algorithm to perform before + pruning the vocabulary. + """ + def __init__( + self, + vocab_size=8000, + show_progress=True, + special_tokens=[], + initial_alphabet=[], + shrinking_factor=0.75, + unk_token=None, + max_piece_length=16, + n_sub_iterations=2, + ): + pass + + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + + @property + def initial_alphabet(self): + """ """ + pass + + @initial_alphabet.setter + def initial_alphabet(self, value): + """ """ + pass + + @property + def show_progress(self): + """ """ + pass + + @show_progress.setter + def show_progress(self, value): + """ """ + pass + + @property + def special_tokens(self): + """ """ + pass + + @special_tokens.setter + def special_tokens(self, value): + """ """ + pass + + @property + def vocab_size(self): + """ """ + pass + + @vocab_size.setter + def vocab_size(self, value): + """ """ + pass + +class WordLevelTrainer(Trainer): + """ + Trainer capable of training a WorldLevel model + + Args: + vocab_size (:obj:`int`, `optional`): + The size of the final vocabulary, including all tokens and alphabet. + + min_frequency (:obj:`int`, `optional`): + The minimum frequency a pair should have in order to be merged. + + show_progress (:obj:`bool`, `optional`): + Whether to show progress bars while training. + + special_tokens (:obj:`List[Union[str, AddedToken]]`): + A list of special tokens the model should know of. + """ + def __init__(self, vocab_size=30000, min_frequency=0, show_progress=True, special_tokens=[]): + pass + + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + + @property + def min_frequency(self): + """ """ + pass + + @min_frequency.setter + def min_frequency(self, value): + """ """ + pass + + @property + def show_progress(self): + """ """ + pass + + @show_progress.setter + def show_progress(self, value): + """ """ + pass + + @property + def special_tokens(self): + """ """ + pass + + @special_tokens.setter + def special_tokens(self, value): + """ """ + pass + + @property + def vocab_size(self): + """ """ + pass + + @vocab_size.setter + def vocab_size(self, value): + """ """ + pass + +class WordPieceTrainer(Trainer): + """ + Trainer capable of training a WordPiece model + + Args: + vocab_size (:obj:`int`, `optional`): + The size of the final vocabulary, including all tokens and alphabet. + + min_frequency (:obj:`int`, `optional`): + The minimum frequency a pair should have in order to be merged. + + show_progress (:obj:`bool`, `optional`): + Whether to show progress bars while training. + + special_tokens (:obj:`List[Union[str, AddedToken]]`, `optional`): + A list of special tokens the model should know of. + + limit_alphabet (:obj:`int`, `optional`): + The maximum different characters to keep in the alphabet. + + initial_alphabet (:obj:`List[str]`, `optional`): + A list of characters to include in the initial alphabet, even + if not seen in the training dataset. + If the strings contain more than one character, only the first one + is kept. + + continuing_subword_prefix (:obj:`str`, `optional`): + A prefix to be used for every subword that is not a beginning-of-word. + + end_of_word_suffix (:obj:`str`, `optional`): + A suffix to be used for every subword that is a end-of-word. + """ + def __init__( + self, + vocab_size=30000, + min_frequency=0, + show_progress=True, + special_tokens=[], + limit_alphabet=None, + initial_alphabet=[], + continuing_subword_prefix="##", + end_of_word_suffix=None, + ): + pass + + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + + @property + def continuing_subword_prefix(self): + """ """ + pass + + @continuing_subword_prefix.setter + def continuing_subword_prefix(self, value): + """ """ + pass + + @property + def end_of_word_suffix(self): + """ """ + pass + + @end_of_word_suffix.setter + def end_of_word_suffix(self, value): + """ """ + pass + + @property + def initial_alphabet(self): + """ """ + pass + + @initial_alphabet.setter + def initial_alphabet(self, value): + """ """ + pass + + @property + def limit_alphabet(self): + """ """ + pass + + @limit_alphabet.setter + def limit_alphabet(self, value): + """ """ + pass + + @property + def min_frequency(self): + """ """ + pass + + @min_frequency.setter + def min_frequency(self, value): + """ """ + pass + + @property + def show_progress(self): + """ """ + pass + + @show_progress.setter + def show_progress(self, value): + """ """ + pass + + @property + def special_tokens(self): + """ """ + pass + + @special_tokens.setter + def special_tokens(self, value): + """ """ + pass + + @property + def vocab_size(self): + """ """ + pass + + @vocab_size.setter + def vocab_size(self, value): + """ """ + pass diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C.cpython-310-x86_64-linux-gnu.so b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..f083403fbb9e29ee2a9b561a13b0c77df7829c8e Binary files /dev/null and b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C.cpython-310-x86_64-linux-gnu.so differ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_VariableFunctions.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_VariableFunctions.pyi new file mode 100644 index 0000000000000000000000000000000000000000..9fd18ba29fa23b662defcaaed6d53c4918da67fe --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_VariableFunctions.pyi @@ -0,0 +1,33783 @@ +# @generated by tools/pyi/gen_pyi.py from torch/_C/_VariableFunctions.pyi.in +# mypy: disable-error-code="type-arg" +# mypy: allow-untyped-defs +# ruff: noqa: F401,PYI054 + +from collections.abc import Callable, Sequence +from types import EllipsisType +from typing import Any, Literal, overload, TypeVar + +import torch +from torch import ( + contiguous_format, + Generator, + inf, + memory_format, + strided, + SymInt, + Tensor, +) +from torch._prims_common import DeviceLikeType +from torch.types import ( + _bool, + _complex, + _device, + _dtype, + _float, + _int, + _layout, + _qscheme, + _size, + Device, + Number, +) + +__all__ = [ + "__and__", + "__lshift__", + "__or__", + "__rshift__", + "__xor__", + "_adaptive_avg_pool2d", + "_adaptive_avg_pool3d", + "_add_batch_dim", + "_add_relu", + "_add_relu_", + "_addmm_activation", + "_aminmax", + "_amp_foreach_non_finite_check_and_unscale_", + "_amp_update_scale_", + "_assert_async", + "_assert_scalar", + "_assert_tensor_metadata", + "_batch_norm_impl_index", + "_cast_Byte", + "_cast_Char", + "_cast_Double", + "_cast_Float", + "_cast_Half", + "_cast_Int", + "_cast_Long", + "_cast_Short", + "_choose_qparams_per_tensor", + "_chunk_cat", + "_coalesce", + "_compute_linear_combination", + "_conj", + "_conj_copy", + "_conj_physical", + "_convert_indices_from_coo_to_csr", + "_convert_indices_from_csr_to_coo", + "_convert_weight_to_int4pack", + "_convert_weight_to_int4pack_for_cpu", + "_convolution", + "_convolution_mode", + "_copy_from", + "_copy_from_and_resize", + "_cslt_compress", + "_cslt_sparse_mm", + "_cslt_sparse_mm_search", + "_ctc_loss", + "_cudnn_ctc_loss", + "_cudnn_init_dropout_state", + "_cudnn_rnn", + "_cudnn_rnn_flatten_weight", + "_cufft_clear_plan_cache", + "_cufft_get_plan_cache_max_size", + "_cufft_get_plan_cache_size", + "_cufft_set_plan_cache_max_size", + "_cummax_helper", + "_cummin_helper", + "_debug_has_internal_overlap", + "_dim_arange", + "_dirichlet_grad", + "_disable_functionalization", + "_dyn_quant_matmul_4bit", + "_dyn_quant_pack_4bit_weight", + "_efficientzerotensor", + "_embedding_bag", + "_embedding_bag_forward_only", + "_empty_affine_quantized", + "_empty_per_channel_affine_quantized", + "_enable_functionalization", + "_euclidean_dist", + "_fake_quantize_learnable_per_channel_affine", + "_fake_quantize_learnable_per_tensor_affine", + "_fake_quantize_per_tensor_affine_cachemask_tensor_qparams", + "_fft_c2c", + "_fft_c2r", + "_fft_r2c", + "_fill_mem_eff_dropout_mask_", + "_foobar", + "_foreach_abs", + "_foreach_abs_", + "_foreach_acos", + "_foreach_acos_", + "_foreach_add", + "_foreach_add_", + "_foreach_addcdiv", + "_foreach_addcdiv_", + "_foreach_addcmul", + "_foreach_addcmul_", + "_foreach_asin", + "_foreach_asin_", + "_foreach_atan", + "_foreach_atan_", + "_foreach_ceil", + "_foreach_ceil_", + "_foreach_clamp_max", + "_foreach_clamp_max_", + "_foreach_clamp_min", + "_foreach_clamp_min_", + "_foreach_copy_", + "_foreach_cos", + "_foreach_cos_", + "_foreach_cosh", + "_foreach_cosh_", + "_foreach_div", + "_foreach_div_", + "_foreach_erf", + "_foreach_erf_", + "_foreach_erfc", + "_foreach_erfc_", + "_foreach_exp", + "_foreach_exp_", + "_foreach_expm1", + "_foreach_expm1_", + "_foreach_floor", + "_foreach_floor_", + "_foreach_frac", + "_foreach_frac_", + "_foreach_lerp", + "_foreach_lerp_", + "_foreach_lgamma", + "_foreach_lgamma_", + "_foreach_log", + "_foreach_log10", + "_foreach_log10_", + "_foreach_log1p", + "_foreach_log1p_", + "_foreach_log2", + "_foreach_log2_", + "_foreach_log_", + "_foreach_max", + "_foreach_maximum", + "_foreach_maximum_", + "_foreach_minimum", + "_foreach_minimum_", + "_foreach_mul", + "_foreach_mul_", + "_foreach_neg", + "_foreach_neg_", + "_foreach_norm", + "_foreach_pow", + "_foreach_pow_", + "_foreach_reciprocal", + "_foreach_reciprocal_", + "_foreach_round", + "_foreach_round_", + "_foreach_rsqrt", + "_foreach_rsqrt_", + "_foreach_sigmoid", + "_foreach_sigmoid_", + "_foreach_sign", + "_foreach_sign_", + "_foreach_sin", + "_foreach_sin_", + "_foreach_sinh", + "_foreach_sinh_", + "_foreach_sqrt", + "_foreach_sqrt_", + "_foreach_sub", + "_foreach_sub_", + "_foreach_tan", + "_foreach_tan_", + "_foreach_tanh", + "_foreach_tanh_", + "_foreach_trunc", + "_foreach_trunc_", + "_foreach_zero_", + "_from_functional_tensor", + "_functional_assert_async", + "_functional_assert_scalar", + "_functional_sym_constrain_range", + "_functional_sym_constrain_range_for_size", + "_functionalize_apply_view_metas", + "_functionalize_are_all_mutations_hidden_from_autograd", + "_functionalize_are_all_mutations_under_no_grad_or_inference_mode", + "_functionalize_commit_update", + "_functionalize_has_metadata_mutation", + "_functionalize_inductor_storage_resized_counter", + "_functionalize_is_symbolic", + "_functionalize_mark_mutation_hidden_from_autograd", + "_functionalize_mark_storage_changed", + "_functionalize_mutation_counter", + "_functionalize_replace", + "_functionalize_storage_changed_counter", + "_functionalize_sync", + "_functionalize_unsafe_set", + "_functionalize_was_inductor_storage_resized", + "_functionalize_was_storage_changed", + "_fused_adagrad_", + "_fused_adam_", + "_fused_adamw_", + "_fused_dropout", + "_fused_moving_avg_obs_fq_helper", + "_fused_rms_norm", + "_fused_sdp_choice", + "_fused_sgd_", + "_fw_primal_copy", + "_grid_sampler_2d_cpu_fallback", + "_grouped_mm", + "_has_compatible_shallow_copy_type", + "_histogramdd_bin_edges", + "_histogramdd_from_bin_cts", + "_histogramdd_from_bin_tensors", + "_index_put_impl_", + "_indices_copy", + "_int_mm", + "_is_all_true", + "_is_any_true", + "_is_functional_tensor", + "_is_functional_tensor_base", + "_is_zerotensor", + "_lazy_clone", + "_linalg_check_errors", + "_linalg_det", + "_linalg_eigh", + "_linalg_slogdet", + "_linalg_solve_ex", + "_linalg_svd", + "_log_softmax", + "_log_softmax_backward_data", + "_logcumsumexp", + "_lstm_mps", + "_lu_with_info", + "_make_dep_token", + "_make_dual", + "_make_dual_copy", + "_make_per_channel_quantized_tensor", + "_make_per_tensor_quantized_tensor", + "_masked_scale", + "_masked_softmax", + "_mixed_dtypes_linear", + "_mkldnn_reshape", + "_mkldnn_transpose", + "_mkldnn_transpose_", + "_mps_convolution", + "_mps_convolution_transpose", + "_native_batch_norm_legit", + "_native_batch_norm_legit_no_training", + "_native_multi_head_attention", + "_neg_view", + "_neg_view_copy", + "_nested_compute_contiguous_strides_offsets", + "_nested_from_padded", + "_nested_from_padded_and_nested_example", + "_nested_from_padded_tensor", + "_nested_get_jagged_dummy", + "_nested_get_lengths", + "_nested_get_max_seqlen", + "_nested_get_min_seqlen", + "_nested_get_offsets", + "_nested_get_ragged_idx", + "_nested_get_values", + "_nested_get_values_copy", + "_nested_tensor_from_mask", + "_nested_tensor_from_mask_left_aligned", + "_nested_tensor_from_tensor_list", + "_nested_tensor_softmax_with_shape", + "_nested_view_from_buffer", + "_nested_view_from_buffer_copy", + "_nested_view_from_jagged", + "_nested_view_from_jagged_copy", + "_nnpack_available", + "_nnpack_spatial_convolution", + "_pack_padded_sequence", + "_pad_packed_sequence", + "_pin_memory", + "_prelu_kernel", + "_print", + "_propagate_xla_data", + "_remove_batch_dim", + "_reshape_alias_copy", + "_reshape_from_tensor", + "_resize_output_", + "_rowwise_prune", + "_safe_softmax", + "_sample_dirichlet", + "_saturate_weight_to_fp16", + "_scaled_dot_product_attention_math", + "_scaled_dot_product_attention_math_for_mps", + "_scaled_dot_product_cudnn_attention", + "_scaled_dot_product_efficient_attention", + "_scaled_dot_product_flash_attention", + "_scaled_dot_product_flash_attention_for_cpu", + "_scaled_grouped_mm", + "_scaled_grouped_mm_v2", + "_scaled_mm", + "_scaled_mm_v2", + "_shape_as_tensor", + "_sobol_engine_draw", + "_sobol_engine_ff_", + "_sobol_engine_initialize_state_", + "_sobol_engine_scramble_", + "_softmax", + "_softmax_backward_data", + "_sparse_broadcast_to", + "_sparse_broadcast_to_copy", + "_sparse_csr_prod", + "_sparse_csr_sum", + "_sparse_log_softmax_backward_data", + "_sparse_semi_structured_addmm", + "_sparse_semi_structured_apply", + "_sparse_semi_structured_apply_dense", + "_sparse_semi_structured_linear", + "_sparse_semi_structured_mm", + "_sparse_semi_structured_tile", + "_sparse_softmax_backward_data", + "_sparse_sparse_matmul", + "_sparse_sum", + "_stack", + "_standard_gamma", + "_standard_gamma_grad", + "_sync", + "_test_autograd_multiple_dispatch", + "_test_autograd_multiple_dispatch_view", + "_test_autograd_multiple_dispatch_view_copy", + "_test_check_tensor", + "_test_functorch_fallback", + "_test_parallel_materialize", + "_test_serialization_subcmul", + "_to_cpu", + "_to_functional_tensor", + "_to_sparse_semi_structured", + "_transform_bias_rescale_qkv", + "_transformer_encoder_layer_fwd", + "_trilinear", + "_triton_multi_head_attention", + "_triton_scaled_dot_attention", + "_unique", + "_unique2", + "_unpack_dual", + "_unsafe_index", + "_unsafe_index_put", + "_unsafe_masked_index", + "_unsafe_masked_index_put_accumulate", + "_use_cudnn_ctc_loss", + "_use_cudnn_rnn_flatten_weight", + "_validate_compressed_sparse_indices", + "_validate_sparse_bsc_tensor_args", + "_validate_sparse_bsr_tensor_args", + "_validate_sparse_compressed_tensor_args", + "_validate_sparse_coo_tensor_args", + "_validate_sparse_csc_tensor_args", + "_validate_sparse_csr_tensor_args", + "_values_copy", + "_weight_int4pack_mm", + "_weight_int4pack_mm_for_cpu", + "_weight_int4pack_mm_with_scales_and_zeros", + "_weight_int8pack_mm", + "_weight_norm", + "_weight_norm_interface", + "_wrapped_linear_prepack", + "_wrapped_quantized_linear_prepacked", + "abs", + "abs_", + "absolute", + "acos", + "acos_", + "acosh", + "acosh_", + "adaptive_avg_pool1d", + "adaptive_max_pool1d", + "add", + "addbmm", + "addcdiv", + "addcmul", + "addmm", + "addmv", + "addmv_", + "addr", + "adjoint", + "affine_grid_generator", + "alias_copy", + "all", + "allclose", + "alpha_dropout", + "alpha_dropout_", + "amax", + "amin", + "aminmax", + "angle", + "any", + "arange", + "arccos", + "arccos_", + "arccosh", + "arccosh_", + "arcsin", + "arcsin_", + "arcsinh", + "arcsinh_", + "arctan", + "arctan2", + "arctan_", + "arctanh", + "arctanh_", + "argmax", + "argmin", + "argsort", + "argwhere", + "as_strided", + "as_strided_", + "as_strided_copy", + "as_strided_scatter", + "as_tensor", + "asarray", + "asin", + "asin_", + "asinh", + "asinh_", + "atan", + "atan2", + "atan_", + "atanh", + "atanh_", + "avg_pool1d", + "baddbmm", + "bartlett_window", + "batch_norm", + "batch_norm_backward_elemt", + "batch_norm_backward_reduce", + "batch_norm_elemt", + "batch_norm_gather_stats", + "batch_norm_gather_stats_with_counts", + "batch_norm_stats", + "batch_norm_update_stats", + "bernoulli", + "bilinear", + "binary_cross_entropy_with_logits", + "bincount", + "binomial", + "bitwise_and", + "bitwise_left_shift", + "bitwise_not", + "bitwise_or", + "bitwise_right_shift", + "bitwise_xor", + "blackman_window", + "bmm", + "broadcast_to", + "bucketize", + "can_cast", + "cat", + "ccol_indices_copy", + "ceil", + "ceil_", + "celu", + "celu_", + "channel_shuffle", + "cholesky", + "cholesky_inverse", + "cholesky_solve", + "choose_qparams_optimized", + "chunk", + "clamp", + "clamp_", + "clamp_max", + "clamp_max_", + "clamp_min", + "clamp_min_", + "clip", + "clip_", + "clone", + "col_indices_copy", + "column_stack", + "combinations", + "complex", + "concat", + "concatenate", + "conj", + "conj_physical", + "conj_physical_", + "constant_pad_nd", + "conv1d", + "conv2d", + "conv3d", + "conv_tbc", + "conv_transpose1d", + "conv_transpose2d", + "conv_transpose3d", + "convolution", + "copysign", + "corrcoef", + "cos", + "cos_", + "cosh", + "cosh_", + "cosine_embedding_loss", + "cosine_similarity", + "count_nonzero", + "cov", + "cross", + "crow_indices_copy", + "ctc_loss", + "cudnn_affine_grid_generator", + "cudnn_batch_norm", + "cudnn_convolution", + "cudnn_convolution_add_relu", + "cudnn_convolution_relu", + "cudnn_convolution_transpose", + "cudnn_grid_sampler", + "cudnn_is_acceptable", + "cummax", + "cummin", + "cumprod", + "cumsum", + "cumulative_trapezoid", + "deg2rad", + "deg2rad_", + "dequantize", + "det", + "detach", + "detach_", + "detach_copy", + "diag", + "diag_embed", + "diagflat", + "diagonal", + "diagonal_copy", + "diagonal_scatter", + "diff", + "digamma", + "dist", + "div", + "divide", + "dot", + "dropout", + "dropout_", + "dsmm", + "dsplit", + "dstack", + "embedding", + "embedding_bag", + "embedding_renorm_", + "empty", + "empty_like", + "empty_permuted", + "empty_quantized", + "empty_strided", + "eq", + "equal", + "erf", + "erf_", + "erfc", + "erfc_", + "erfinv", + "exp", + "exp2", + "exp2_", + "exp_", + "expand_copy", + "expm1", + "expm1_", + "eye", + "fake_quantize_per_channel_affine", + "fake_quantize_per_tensor_affine", + "fbgemm_linear_fp16_weight", + "fbgemm_linear_fp16_weight_fp32_activation", + "fbgemm_linear_int8_weight", + "fbgemm_linear_int8_weight_fp32_activation", + "fbgemm_linear_quantize_weight", + "fbgemm_pack_gemm_matrix_fp16", + "fbgemm_pack_quantized_matrix", + "feature_alpha_dropout", + "feature_alpha_dropout_", + "feature_dropout", + "feature_dropout_", + "fill", + "fill_", + "fix", + "fix_", + "flatten", + "flip", + "fliplr", + "flipud", + "float_power", + "floor", + "floor_", + "floor_divide", + "fmax", + "fmin", + "fmod", + "frac", + "frac_", + "frexp", + "frobenius_norm", + "from_file", + "from_numpy", + "frombuffer", + "full", + "full_like", + "fused_moving_avg_obs_fake_quant", + "gather", + "gcd", + "gcd_", + "ge", + "geqrf", + "ger", + "get_default_dtype", + "get_num_interop_threads", + "get_num_threads", + "gradient", + "greater", + "greater_equal", + "grid_sampler", + "grid_sampler_2d", + "grid_sampler_3d", + "group_norm", + "gru", + "gru_cell", + "gt", + "hamming_window", + "hann_window", + "hardshrink", + "hash_tensor", + "heaviside", + "hinge_embedding_loss", + "histc", + "histogram", + "histogramdd", + "hsmm", + "hsplit", + "hspmm", + "hstack", + "hypot", + "i0", + "i0_", + "igamma", + "igammac", + "imag", + "index_add", + "index_copy", + "index_fill", + "index_put", + "index_put_", + "index_reduce", + "index_select", + "indices_copy", + "init_num_threads", + "inner", + "instance_norm", + "int_repr", + "inverse", + "is_complex", + "is_conj", + "is_distributed", + "is_floating_point", + "is_grad_enabled", + "is_inference", + "is_inference_mode_enabled", + "is_neg", + "is_nonzero", + "is_same_size", + "is_signed", + "is_vulkan_available", + "isclose", + "isfinite", + "isin", + "isinf", + "isnan", + "isneginf", + "isposinf", + "isreal", + "istft", + "kaiser_window", + "kl_div", + "kron", + "kthvalue", + "layer_norm", + "lcm", + "lcm_", + "ldexp", + "ldexp_", + "le", + "lerp", + "less", + "less_equal", + "lgamma", + "linspace", + "log", + "log10", + "log10_", + "log1p", + "log1p_", + "log2", + "log2_", + "log_", + "log_softmax", + "logaddexp", + "logaddexp2", + "logcumsumexp", + "logdet", + "logical_and", + "logical_not", + "logical_or", + "logical_xor", + "logit", + "logit_", + "logspace", + "logsumexp", + "lstm", + "lstm_cell", + "lt", + "lu_solve", + "lu_unpack", + "margin_ranking_loss", + "masked_fill", + "masked_scatter", + "masked_select", + "matmul", + "matrix_exp", + "matrix_power", + "max", + "max_pool1d", + "max_pool1d_with_indices", + "max_pool2d", + "max_pool3d", + "maximum", + "mean", + "median", + "min", + "minimum", + "miopen_batch_norm", + "miopen_convolution", + "miopen_convolution_add_relu", + "miopen_convolution_relu", + "miopen_convolution_transpose", + "miopen_depthwise_convolution", + "miopen_rnn", + "mkldnn_adaptive_avg_pool2d", + "mkldnn_convolution", + "mkldnn_linear_backward_weights", + "mkldnn_max_pool2d", + "mkldnn_max_pool3d", + "mkldnn_rnn_layer", + "mm", + "mode", + "moveaxis", + "movedim", + "msort", + "mul", + "multinomial", + "multiply", + "mv", + "mvlgamma", + "nan_to_num", + "nan_to_num_", + "nanmean", + "nanmedian", + "nanquantile", + "nansum", + "narrow", + "narrow_copy", + "native_batch_norm", + "native_channel_shuffle", + "native_dropout", + "native_group_norm", + "native_layer_norm", + "native_norm", + "ne", + "neg", + "neg_", + "negative", + "negative_", + "nextafter", + "nonzero", + "nonzero_static", + "norm_except_dim", + "normal", + "not_equal", + "nuclear_norm", + "numel", + "ones", + "ones_like", + "orgqr", + "ormqr", + "outer", + "pairwise_distance", + "pdist", + "permute", + "permute_copy", + "pinverse", + "pixel_shuffle", + "pixel_unshuffle", + "poisson", + "poisson_nll_loss", + "polar", + "polygamma", + "positive", + "pow", + "prelu", + "prod", + "promote_types", + "put", + "q_per_channel_axis", + "q_per_channel_scales", + "q_per_channel_zero_points", + "q_scale", + "q_zero_point", + "qr", + "quantile", + "quantize_per_channel", + "quantize_per_tensor", + "quantize_per_tensor_dynamic", + "quantized_batch_norm", + "quantized_gru_cell", + "quantized_lstm_cell", + "quantized_max_pool1d", + "quantized_max_pool2d", + "quantized_max_pool3d", + "quantized_rnn_relu_cell", + "quantized_rnn_tanh_cell", + "rad2deg", + "rad2deg_", + "rand", + "rand_like", + "randint", + "randint_like", + "randn", + "randn_like", + "randperm", + "range", + "ravel", + "real", + "reciprocal", + "reciprocal_", + "relu", + "relu_", + "remainder", + "renorm", + "repeat_interleave", + "reshape", + "resize_as_", + "resize_as_sparse_", + "resolve_conj", + "resolve_neg", + "result_type", + "rms_norm", + "rnn_relu", + "rnn_relu_cell", + "rnn_tanh", + "rnn_tanh_cell", + "roll", + "rot90", + "round", + "round_", + "row_indices_copy", + "row_stack", + "rrelu", + "rrelu_", + "rsqrt", + "rsqrt_", + "rsub", + "saddmm", + "scalar_tensor", + "scatter", + "scatter_add", + "scatter_reduce", + "searchsorted", + "segment_reduce", + "select", + "select_copy", + "select_scatter", + "selu", + "selu_", + "set_flush_denormal", + "set_num_interop_threads", + "set_num_threads", + "sgn", + "sigmoid", + "sigmoid_", + "sign", + "signbit", + "sin", + "sin_", + "sinc", + "sinc_", + "sinh", + "sinh_", + "slice_copy", + "slice_inverse", + "slice_scatter", + "slogdet", + "smm", + "softmax", + "sort", + "sparse_bsc_tensor", + "sparse_bsr_tensor", + "sparse_compressed_tensor", + "sparse_coo_tensor", + "sparse_csc_tensor", + "sparse_csr_tensor", + "split_copy", + "split_with_sizes", + "split_with_sizes_copy", + "spmm", + "sqrt", + "sqrt_", + "square", + "square_", + "squeeze", + "squeeze_copy", + "sspaddmm", + "stack", + "std", + "std_mean", + "sub", + "subtract", + "sum", + "svd", + "swapaxes", + "swapdims", + "sym_constrain_range", + "sym_constrain_range_for_size", + "t", + "t_copy", + "take", + "take_along_dim", + "tan", + "tan_", + "tanh", + "tanh_", + "tensor", + "tensor_split", + "threshold", + "threshold_", + "tile", + "topk", + "trace", + "transpose", + "transpose_copy", + "trapezoid", + "trapz", + "triangular_solve", + "tril", + "tril_indices", + "triplet_margin_loss", + "triu", + "triu_indices", + "true_divide", + "trunc", + "trunc_", + "unbind", + "unbind_copy", + "unflatten", + "unfold_copy", + "unique_dim", + "unsafe_chunk", + "unsafe_split", + "unsafe_split_with_sizes", + "unsqueeze", + "unsqueeze_copy", + "values_copy", + "vander", + "var", + "var_mean", + "vdot", + "view_as_complex", + "view_as_complex_copy", + "view_as_real", + "view_as_real_copy", + "view_copy", + "vsplit", + "vstack", + "where", + "xlogy", + "xlogy_", + "zero_", + "zeros", + "zeros_like", +] + +@overload +def __and__(input: Tensor, other: Tensor) -> Tensor: ... +@overload +def __and__(input: Tensor, other: Number | _complex) -> Tensor: ... +@overload +def __lshift__(input: Tensor, other: Tensor) -> Tensor: ... +@overload +def __lshift__(input: Tensor, other: Number | _complex) -> Tensor: ... +@overload +def __or__(input: Tensor, other: Tensor) -> Tensor: ... +@overload +def __or__(input: Tensor, other: Number | _complex) -> Tensor: ... +@overload +def __rshift__(input: Tensor, other: Tensor) -> Tensor: ... +@overload +def __rshift__(input: Tensor, other: Number | _complex) -> Tensor: ... +@overload +def __xor__(input: Tensor, other: Tensor) -> Tensor: ... +@overload +def __xor__(input: Tensor, other: Number | _complex) -> Tensor: ... +def _adaptive_avg_pool2d( + input: Tensor, + output_size: _int | SymInt | Sequence[_int | SymInt], +) -> Tensor: ... +def _adaptive_avg_pool3d( + input: Tensor, + output_size: _int | SymInt | Sequence[_int | SymInt], +) -> Tensor: ... +def _add_batch_dim(input: Tensor, batch_dim: _int, level: _int) -> Tensor: ... +@overload +def _add_relu( + input: Tensor, + other: Tensor, + *, + alpha: Number | _complex = 1, + out: Tensor | None = None, +) -> Tensor: ... +@overload +def _add_relu( + input: Tensor, + other: Number | _complex, + alpha: Number | _complex = 1, +) -> Tensor: ... +@overload +def _add_relu_( + input: Tensor, + other: Tensor, + *, + alpha: Number | _complex = 1, +) -> Tensor: ... +@overload +def _add_relu_( + input: Tensor, + other: Number | _complex, + alpha: Number | _complex = 1, +) -> Tensor: ... +def _addmm_activation( + input: Tensor, + mat1: Tensor, + mat2: Tensor, + *, + beta: Number | _complex = 1, + alpha: Number | _complex = 1, + use_gelu: _bool = False, + out: Tensor | None = None, +) -> Tensor: ... +@overload +def _aminmax(input: Tensor) -> tuple[Tensor, Tensor]: ... +@overload +def _aminmax( + input: Tensor, + dim: _int, + keepdim: _bool = False, +) -> tuple[Tensor, Tensor]: ... +def _amp_foreach_non_finite_check_and_unscale_( + self: tuple[Tensor, ...] | list[Tensor] | None, + found_inf: Tensor, + inv_scale: Tensor, +) -> None: ... +def _amp_update_scale_( + input: Tensor, + growth_tracker: Tensor, + found_inf: Tensor, + scale_growth_factor: _float, + scale_backoff_factor: _float, + growth_interval: _int, +) -> Tensor: ... +@overload +def _assert_async(input: Tensor) -> None: + r""" + _assert_async(tensor) -> void + + Asynchronously assert that the contents of tensor are nonzero. For CPU tensors, + this is equivalent to ``assert tensor`` or ``assert tensor.is_nonzero()``; for + CUDA tensors, we DO NOT synchronize and you may only find out the assertion + failed at a later CUDA kernel launch. Asynchronous assertion can be helpful for + testing invariants in CUDA tensors without giving up performance. This function + is NOT intended to be used for regular error checking, as it will trash your CUDA + context if the assert fails (forcing you to restart your PyTorch process.) + + Args: + tensor (Tensor): a one element tensor to test to see if it is nonzero. Zero + elements (including False for boolean tensors) cause an assertion failure + to be raised. + """ + +@overload +def _assert_async(input: Tensor, assert_msg: str) -> None: + r""" + _assert_async(tensor) -> void + + Asynchronously assert that the contents of tensor are nonzero. For CPU tensors, + this is equivalent to ``assert tensor`` or ``assert tensor.is_nonzero()``; for + CUDA tensors, we DO NOT synchronize and you may only find out the assertion + failed at a later CUDA kernel launch. Asynchronous assertion can be helpful for + testing invariants in CUDA tensors without giving up performance. This function + is NOT intended to be used for regular error checking, as it will trash your CUDA + context if the assert fails (forcing you to restart your PyTorch process.) + + Args: + tensor (Tensor): a one element tensor to test to see if it is nonzero. Zero + elements (including False for boolean tensors) cause an assertion failure + to be raised. + """ + +def _assert_scalar(self: Number | _complex, assert_msg: str) -> None: ... +def _assert_tensor_metadata( + a: Tensor, + size: Sequence[_int | SymInt] | None = None, + stride: Sequence[_int | SymInt] | None = None, + dtype: _dtype | None = None, + *, + device: DeviceLikeType | None = None, + layout: _layout | None = None, +) -> None: ... +def _batch_norm_impl_index( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + running_mean: Tensor | None, + running_var: Tensor | None, + training: _bool, + momentum: _float, + eps: _float, + cudnn_enabled: _bool, +) -> tuple[Tensor, Tensor, Tensor, Tensor, _int]: ... +def _cast_Byte(input: Tensor, non_blocking: _bool = False) -> Tensor: ... +def _cast_Char(input: Tensor, non_blocking: _bool = False) -> Tensor: ... +def _cast_Double(input: Tensor, non_blocking: _bool = False) -> Tensor: ... +def _cast_Float(input: Tensor, non_blocking: _bool = False) -> Tensor: ... +def _cast_Half(input: Tensor, non_blocking: _bool = False) -> Tensor: ... +def _cast_Int(input: Tensor, non_blocking: _bool = False) -> Tensor: ... +def _cast_Long(input: Tensor, non_blocking: _bool = False) -> Tensor: ... +def _cast_Short(input: Tensor, non_blocking: _bool = False) -> Tensor: ... +def _choose_qparams_per_tensor( + input: Tensor, + reduce_range: _bool = False, +) -> tuple[_float, _int]: ... +def _chunk_cat( + tensors: tuple[Tensor, ...] | list[Tensor] | None, + dim: _int, + num_chunks: _int, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _coalesce(input: Tensor) -> Tensor: ... +def _compute_linear_combination( + input: Tensor, + coefficients: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _conj(input: Tensor) -> Tensor: ... +def _conj_copy(input: Tensor, *, out: Tensor | None = None) -> Tensor: ... +def _conj_physical(input: Tensor) -> Tensor: ... +def _convert_indices_from_coo_to_csr( + input: Tensor, + size: _int, + *, + out_int32: _bool = False, + out: Tensor | None = None, +) -> Tensor: ... +def _convert_indices_from_csr_to_coo( + crow_indices: Tensor, + col_indices: Tensor, + *, + out_int32: _bool = False, + transpose: _bool = False, + out: Tensor | None = None, +) -> Tensor: ... +def _convert_weight_to_int4pack(input: Tensor, innerKTiles: _int) -> Tensor: ... +def _convert_weight_to_int4pack_for_cpu( + input: Tensor, + innerKTiles: _int, +) -> Tensor: ... +@overload +def _convolution( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + stride: Sequence[_int | SymInt], + padding: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + transposed: _bool, + output_padding: _size, + groups: _int | SymInt, + benchmark: _bool, + deterministic: _bool, + cudnn_enabled: _bool, +) -> Tensor: ... +@overload +def _convolution( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + stride: Sequence[_int | SymInt], + padding: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + transposed: _bool, + output_padding: Sequence[_int | SymInt], + groups: _int | SymInt, + benchmark: _bool, + deterministic: _bool, + cudnn_enabled: _bool, + allow_tf32: _bool, +) -> Tensor: ... +def _convolution_mode( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + stride: Sequence[_int | SymInt], + padding: str, + dilation: Sequence[_int | SymInt], + groups: _int | SymInt, +) -> Tensor: ... +def _copy_from( + input: Tensor, + dst: Tensor, + non_blocking: _bool = False, +) -> Tensor: ... +def _copy_from_and_resize(input: Tensor, dst: Tensor) -> Tensor: ... +def _cslt_compress(input: Tensor) -> Tensor: ... +def _cslt_sparse_mm( + compressed_A: Tensor, + dense_B: Tensor, + bias: Tensor | None = None, + alpha: Tensor | None = None, + out_dtype: _dtype | None = None, + transpose_result: _bool = False, + alg_id: _int = 0, + split_k: _int = 1, + split_k_mode: _int = -1, +) -> Tensor: ... +def _cslt_sparse_mm_search( + compressed_A: Tensor, + dense_B: Tensor, + bias: Tensor | None = None, + alpha: Tensor | None = None, + out_dtype: _dtype | None = None, + transpose_result: _bool = False, +) -> _int: ... +@overload +def _ctc_loss( + log_probs: Tensor, + targets: Tensor, + input_lengths: _size, + target_lengths: _size, + blank: _int = 0, + zero_infinity: _bool = False, +) -> tuple[Tensor, Tensor]: ... +@overload +def _ctc_loss( + log_probs: Tensor, + targets: Tensor, + input_lengths: Tensor, + target_lengths: Tensor, + blank: _int = 0, + zero_infinity: _bool = False, +) -> tuple[Tensor, Tensor]: ... +@overload +def _cudnn_ctc_loss( + log_probs: Tensor, + targets: Tensor, + input_lengths: _size, + target_lengths: _size, + blank: _int, + deterministic: _bool, + zero_infinity: _bool, +) -> tuple[Tensor, Tensor]: ... +@overload +def _cudnn_ctc_loss( + log_probs: Tensor, + targets: Tensor, + input_lengths: Tensor, + target_lengths: Tensor, + blank: _int, + deterministic: _bool, + zero_infinity: _bool, +) -> tuple[Tensor, Tensor]: ... +def _cudnn_init_dropout_state( + dropout: _float, + train: _bool, + dropout_seed: _int, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: ... +def _cudnn_rnn( + input: Tensor, + weight: tuple[Tensor, ...] | list[Tensor] | None, + weight_stride0: _int, + weight_buf: Tensor | None, + hx: Tensor, + cx: Tensor | None, + mode: _int, + hidden_size: _int | SymInt, + proj_size: _int | SymInt, + num_layers: _int, + batch_first: _bool, + dropout: _float, + train: _bool, + bidirectional: _bool, + batch_sizes: Sequence[_int | SymInt], + dropout_state: Tensor | None, +) -> tuple[Tensor, Tensor, Tensor, Tensor, Tensor]: ... +def _cudnn_rnn_flatten_weight( + weight_arr: tuple[Tensor, ...] | list[Tensor] | None, + weight_stride0: _int, + input_size: _int | SymInt, + mode: _int, + hidden_size: _int | SymInt, + proj_size: _int | SymInt, + num_layers: _int, + batch_first: _bool, + bidirectional: _bool, +) -> Tensor: ... +def _cufft_clear_plan_cache(device_index: _int) -> None: ... +def _cufft_get_plan_cache_max_size(device_index: _int) -> _int: ... +def _cufft_get_plan_cache_size(device_index: _int) -> _int: ... +def _cufft_set_plan_cache_max_size( + device_index: _int, + max_size: _int, +) -> None: ... +def _cummax_helper( + input: Tensor, + values: Tensor, + indices: Tensor, + dim: _int, +) -> None: ... +def _cummin_helper( + input: Tensor, + values: Tensor, + indices: Tensor, + dim: _int, +) -> None: ... +def _debug_has_internal_overlap(input: Tensor) -> _int: ... +def _dim_arange(like: Tensor, dim: _int) -> Tensor: ... +def _dirichlet_grad(x: Tensor, alpha: Tensor, total: Tensor) -> Tensor: ... +def _disable_functionalization(): ... +def _dyn_quant_matmul_4bit( + inp: Tensor, + packed_weights: Tensor, + block_size: _int, + in_features: _int, + out_features: _int, +) -> Tensor: ... +def _dyn_quant_pack_4bit_weight( + weights: Tensor, + scales_zeros: Tensor, + bias: Tensor | None, + block_size: _int, + in_features: _int, + out_features: _int, +) -> Tensor: ... +@overload +def _efficientzerotensor( + size: Sequence[_int | SymInt], + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: ... +@overload +def _efficientzerotensor( + *size: _int | SymInt, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: ... +def _embedding_bag( + weight: Tensor, + indices: Tensor, + offsets: Tensor, + scale_grad_by_freq: _bool = False, + mode: _int = 0, + sparse: _bool = False, + per_sample_weights: Tensor | None = None, + include_last_offset: _bool = False, + padding_idx: _int = -1, +) -> tuple[Tensor, Tensor, Tensor, Tensor]: ... +def _embedding_bag_forward_only( + weight: Tensor, + indices: Tensor, + offsets: Tensor, + scale_grad_by_freq: _bool = False, + mode: _int = 0, + sparse: _bool = False, + per_sample_weights: Tensor | None = None, + include_last_offset: _bool = False, + padding_idx: _int = -1, +) -> tuple[Tensor, Tensor, Tensor, Tensor]: ... +@overload +def _empty_affine_quantized( + size: Sequence[_int | SymInt], + *, + scale: _float = 1, + zero_point: _int = 0, + memory_format: memory_format | None = contiguous_format, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: ... +@overload +def _empty_affine_quantized( + *size: _int | SymInt, + scale: _float = 1, + zero_point: _int = 0, + memory_format: memory_format | None = contiguous_format, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: ... +@overload +def _empty_per_channel_affine_quantized( + size: Sequence[_int | SymInt], + *, + scales: Tensor, + zero_points: Tensor, + axis: _int, + memory_format: memory_format | None = contiguous_format, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: ... +@overload +def _empty_per_channel_affine_quantized( + *size: _int | SymInt, + scales: Tensor, + zero_points: Tensor, + axis: _int, + memory_format: memory_format | None = contiguous_format, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: ... +def _enable_functionalization(*, reapply_views: _bool = False) -> None: ... +def _euclidean_dist(x1: Tensor, x2: Tensor) -> Tensor: ... +def _fake_quantize_learnable_per_channel_affine( + input: Tensor, + scale: Tensor, + zero_point: Tensor, + axis: _int, + quant_min: _int, + quant_max: _int, + grad_factor: _float = 1.0, +) -> Tensor: ... +def _fake_quantize_learnable_per_tensor_affine( + input: Tensor, + scale: Tensor, + zero_point: Tensor, + quant_min: _int, + quant_max: _int, + grad_factor: _float = 1.0, +) -> Tensor: ... +def _fake_quantize_per_tensor_affine_cachemask_tensor_qparams( + input: Tensor, + scale: Tensor, + zero_point: Tensor, + fake_quant_enabled: Tensor, + quant_min: _int, + quant_max: _int, +) -> torch.return_types._fake_quantize_per_tensor_affine_cachemask_tensor_qparams: # fmt: skip + ... +def _fft_c2c( + input: Tensor, + dim: Sequence[_int | SymInt], + normalization: _int, + forward: _bool, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _fft_c2r( + input: Tensor, + dim: _size, + normalization: _int, + last_dim_size: _int | SymInt, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _fft_r2c( + input: Tensor, + dim: _size, + normalization: _int, + onesided: _bool, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _fill_mem_eff_dropout_mask_( + input: Tensor, + dropout_p: _float, + seed: _int, + offset: _int, +) -> Tensor: ... +def _foobar( + input: Tensor, + arg1: _bool = True, + arg2: _bool = True, + *, + arg3: _bool = True, +) -> Tensor: ... +def _foreach_abs( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: + r""" + _foreach_abs(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.abs` to each Tensor of the input list. + """ + +def _foreach_abs_(self: tuple[Tensor, ...] | list[Tensor] | None) -> None: + r""" + _foreach_abs_(self: List[Tensor]) -> None + + Apply :func:`torch.abs` to each Tensor of the input list. + """ + +def _foreach_acos( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: + r""" + _foreach_acos(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.acos` to each Tensor of the input list. + """ + +def _foreach_acos_(self: tuple[Tensor, ...] | list[Tensor] | None) -> None: + r""" + _foreach_acos_(self: List[Tensor]) -> None + + Apply :func:`torch.acos` to each Tensor of the input list. + """ + +@overload +def _foreach_add( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalars: Sequence[Number | _complex], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_add( + self: tuple[Tensor, ...] | list[Tensor] | None, + other: tuple[Tensor, ...] | list[Tensor] | None, + *, + alpha: Number | _complex = 1, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_add( + self: tuple[Tensor, ...] | list[Tensor] | None, + other: Tensor, + *, + alpha: Number | _complex = 1, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_add( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalar: Number | _complex, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_add_( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalars: Sequence[Number | _complex], +) -> None: ... +@overload +def _foreach_add_( + self: tuple[Tensor, ...] | list[Tensor] | None, + other: tuple[Tensor, ...] | list[Tensor] | None, + *, + alpha: Number | _complex = 1, +) -> None: ... +@overload +def _foreach_add_( + self: tuple[Tensor, ...] | list[Tensor] | None, + other: Tensor, + *, + alpha: Number | _complex = 1, +) -> None: ... +@overload +def _foreach_add_( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalar: Number | _complex, +) -> None: ... +@overload +def _foreach_addcdiv( + self: tuple[Tensor, ...] | list[Tensor] | None, + tensor1: tuple[Tensor, ...] | list[Tensor] | None, + tensor2: tuple[Tensor, ...] | list[Tensor] | None, + scalars: Sequence[Number | _complex], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_addcdiv( + self: tuple[Tensor, ...] | list[Tensor] | None, + tensor1: tuple[Tensor, ...] | list[Tensor] | None, + tensor2: tuple[Tensor, ...] | list[Tensor] | None, + scalars: Tensor, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_addcdiv( + self: tuple[Tensor, ...] | list[Tensor] | None, + tensor1: tuple[Tensor, ...] | list[Tensor] | None, + tensor2: tuple[Tensor, ...] | list[Tensor] | None, + value: Number | _complex = 1, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_addcdiv_( + self: tuple[Tensor, ...] | list[Tensor] | None, + tensor1: tuple[Tensor, ...] | list[Tensor] | None, + tensor2: tuple[Tensor, ...] | list[Tensor] | None, + scalars: Sequence[Number | _complex], +) -> None: ... +@overload +def _foreach_addcdiv_( + self: tuple[Tensor, ...] | list[Tensor] | None, + tensor1: tuple[Tensor, ...] | list[Tensor] | None, + tensor2: tuple[Tensor, ...] | list[Tensor] | None, + scalars: Tensor, +) -> None: ... +@overload +def _foreach_addcdiv_( + self: tuple[Tensor, ...] | list[Tensor] | None, + tensor1: tuple[Tensor, ...] | list[Tensor] | None, + tensor2: tuple[Tensor, ...] | list[Tensor] | None, + value: Number | _complex = 1, +) -> None: ... +@overload +def _foreach_addcmul( + self: tuple[Tensor, ...] | list[Tensor] | None, + tensor1: tuple[Tensor, ...] | list[Tensor] | None, + tensor2: tuple[Tensor, ...] | list[Tensor] | None, + scalars: Sequence[Number | _complex], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_addcmul( + self: tuple[Tensor, ...] | list[Tensor] | None, + tensor1: tuple[Tensor, ...] | list[Tensor] | None, + tensor2: tuple[Tensor, ...] | list[Tensor] | None, + scalars: Tensor, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_addcmul( + self: tuple[Tensor, ...] | list[Tensor] | None, + tensor1: tuple[Tensor, ...] | list[Tensor] | None, + tensor2: tuple[Tensor, ...] | list[Tensor] | None, + value: Number | _complex = 1, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_addcmul_( + self: tuple[Tensor, ...] | list[Tensor] | None, + tensor1: tuple[Tensor, ...] | list[Tensor] | None, + tensor2: tuple[Tensor, ...] | list[Tensor] | None, + scalars: Sequence[Number | _complex], +) -> None: ... +@overload +def _foreach_addcmul_( + self: tuple[Tensor, ...] | list[Tensor] | None, + tensor1: tuple[Tensor, ...] | list[Tensor] | None, + tensor2: tuple[Tensor, ...] | list[Tensor] | None, + scalars: Tensor, +) -> None: ... +@overload +def _foreach_addcmul_( + self: tuple[Tensor, ...] | list[Tensor] | None, + tensor1: tuple[Tensor, ...] | list[Tensor] | None, + tensor2: tuple[Tensor, ...] | list[Tensor] | None, + value: Number | _complex = 1, +) -> None: ... +def _foreach_asin( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: + r""" + _foreach_asin(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.asin` to each Tensor of the input list. + """ + +def _foreach_asin_(self: tuple[Tensor, ...] | list[Tensor] | None) -> None: + r""" + _foreach_asin_(self: List[Tensor]) -> None + + Apply :func:`torch.asin` to each Tensor of the input list. + """ + +def _foreach_atan( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: + r""" + _foreach_atan(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.atan` to each Tensor of the input list. + """ + +def _foreach_atan_(self: tuple[Tensor, ...] | list[Tensor] | None) -> None: + r""" + _foreach_atan_(self: List[Tensor]) -> None + + Apply :func:`torch.atan` to each Tensor of the input list. + """ + +def _foreach_ceil( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: + r""" + _foreach_ceil(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.ceil` to each Tensor of the input list. + """ + +def _foreach_ceil_(self: tuple[Tensor, ...] | list[Tensor] | None) -> None: + r""" + _foreach_ceil_(self: List[Tensor]) -> None + + Apply :func:`torch.ceil` to each Tensor of the input list. + """ + +@overload +def _foreach_clamp_max( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalars: Sequence[Number | _complex], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_clamp_max( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalar: Number | _complex, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_clamp_max( + self: tuple[Tensor, ...] | list[Tensor] | None, + other: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_clamp_max_( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalars: Sequence[Number | _complex], +) -> None: ... +@overload +def _foreach_clamp_max_( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalar: Number | _complex, +) -> None: ... +@overload +def _foreach_clamp_max_( + self: tuple[Tensor, ...] | list[Tensor] | None, + other: tuple[Tensor, ...] | list[Tensor] | None, +) -> None: ... +@overload +def _foreach_clamp_min( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalars: Sequence[Number | _complex], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_clamp_min( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalar: Number | _complex, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_clamp_min( + self: tuple[Tensor, ...] | list[Tensor] | None, + other: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_clamp_min_( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalars: Sequence[Number | _complex], +) -> None: ... +@overload +def _foreach_clamp_min_( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalar: Number | _complex, +) -> None: ... +@overload +def _foreach_clamp_min_( + self: tuple[Tensor, ...] | list[Tensor] | None, + other: tuple[Tensor, ...] | list[Tensor] | None, +) -> None: ... +def _foreach_copy_( + self: tuple[Tensor, ...] | list[Tensor] | None, + src: tuple[Tensor, ...] | list[Tensor] | None, + non_blocking: _bool = False, +) -> None: ... +def _foreach_cos( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: + r""" + _foreach_cos(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.cos` to each Tensor of the input list. + """ + +def _foreach_cos_(self: tuple[Tensor, ...] | list[Tensor] | None) -> None: + r""" + _foreach_cos_(self: List[Tensor]) -> None + + Apply :func:`torch.cos` to each Tensor of the input list. + """ + +def _foreach_cosh( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: + r""" + _foreach_cosh(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.cosh` to each Tensor of the input list. + """ + +def _foreach_cosh_(self: tuple[Tensor, ...] | list[Tensor] | None) -> None: + r""" + _foreach_cosh_(self: List[Tensor]) -> None + + Apply :func:`torch.cosh` to each Tensor of the input list. + """ + +@overload +def _foreach_div( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalars: Sequence[Number | _complex], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_div( + self: tuple[Tensor, ...] | list[Tensor] | None, + other: Tensor, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_div( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalar: Number | _complex, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_div( + self: tuple[Tensor, ...] | list[Tensor] | None, + other: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_div_( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalars: Sequence[Number | _complex], +) -> None: ... +@overload +def _foreach_div_( + self: tuple[Tensor, ...] | list[Tensor] | None, + other: Tensor, +) -> None: ... +@overload +def _foreach_div_( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalar: Number | _complex, +) -> None: ... +@overload +def _foreach_div_( + self: tuple[Tensor, ...] | list[Tensor] | None, + other: tuple[Tensor, ...] | list[Tensor] | None, +) -> None: ... +def _foreach_erf( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: + r""" + _foreach_erf(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.erf` to each Tensor of the input list. + """ + +def _foreach_erf_(self: tuple[Tensor, ...] | list[Tensor] | None) -> None: + r""" + _foreach_erf_(self: List[Tensor]) -> None + + Apply :func:`torch.erf` to each Tensor of the input list. + """ + +def _foreach_erfc( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: + r""" + _foreach_erfc(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.erfc` to each Tensor of the input list. + """ + +def _foreach_erfc_(self: tuple[Tensor, ...] | list[Tensor] | None) -> None: + r""" + _foreach_erfc_(self: List[Tensor]) -> None + + Apply :func:`torch.erfc` to each Tensor of the input list. + """ + +def _foreach_exp( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: + r""" + _foreach_exp(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.exp` to each Tensor of the input list. + """ + +def _foreach_exp_(self: tuple[Tensor, ...] | list[Tensor] | None) -> None: + r""" + _foreach_exp_(self: List[Tensor]) -> None + + Apply :func:`torch.exp` to each Tensor of the input list. + """ + +def _foreach_expm1( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: + r""" + _foreach_expm1(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.expm1` to each Tensor of the input list. + """ + +def _foreach_expm1_(self: tuple[Tensor, ...] | list[Tensor] | None) -> None: + r""" + _foreach_expm1_(self: List[Tensor]) -> None + + Apply :func:`torch.expm1` to each Tensor of the input list. + """ + +def _foreach_floor( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: + r""" + _foreach_floor(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.floor` to each Tensor of the input list. + """ + +def _foreach_floor_(self: tuple[Tensor, ...] | list[Tensor] | None) -> None: + r""" + _foreach_floor_(self: List[Tensor]) -> None + + Apply :func:`torch.floor` to each Tensor of the input list. + """ + +def _foreach_frac( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: + r""" + _foreach_frac(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.frac` to each Tensor of the input list. + """ + +def _foreach_frac_(self: tuple[Tensor, ...] | list[Tensor] | None) -> None: + r""" + _foreach_frac_(self: List[Tensor]) -> None + + Apply :func:`torch.frac` to each Tensor of the input list. + """ + +@overload +def _foreach_lerp( + self: tuple[Tensor, ...] | list[Tensor] | None, + tensors1: tuple[Tensor, ...] | list[Tensor] | None, + weight: Number | _complex, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_lerp( + self: tuple[Tensor, ...] | list[Tensor] | None, + tensors1: tuple[Tensor, ...] | list[Tensor] | None, + weight: Sequence[Number | _complex], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_lerp( + self: tuple[Tensor, ...] | list[Tensor] | None, + tensors1: tuple[Tensor, ...] | list[Tensor] | None, + weights: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_lerp_( + self: tuple[Tensor, ...] | list[Tensor] | None, + tensors1: tuple[Tensor, ...] | list[Tensor] | None, + weight: Number | _complex, +) -> None: ... +@overload +def _foreach_lerp_( + self: tuple[Tensor, ...] | list[Tensor] | None, + tensors1: tuple[Tensor, ...] | list[Tensor] | None, + weight: Sequence[Number | _complex], +) -> None: ... +@overload +def _foreach_lerp_( + self: tuple[Tensor, ...] | list[Tensor] | None, + tensors1: tuple[Tensor, ...] | list[Tensor] | None, + weights: tuple[Tensor, ...] | list[Tensor] | None, +) -> None: ... +def _foreach_lgamma( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: + r""" + _foreach_lgamma(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.lgamma` to each Tensor of the input list. + """ + +def _foreach_lgamma_( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> None: + r""" + _foreach_lgamma_(self: List[Tensor]) -> None + + Apply :func:`torch.lgamma` to each Tensor of the input list. + """ + +def _foreach_log( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: + r""" + _foreach_log(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.log` to each Tensor of the input list. + """ + +def _foreach_log10( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: + r""" + _foreach_log10(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.log10` to each Tensor of the input list. + """ + +def _foreach_log10_(self: tuple[Tensor, ...] | list[Tensor] | None) -> None: + r""" + _foreach_log10_(self: List[Tensor]) -> None + + Apply :func:`torch.log10` to each Tensor of the input list. + """ + +def _foreach_log1p( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: + r""" + _foreach_log1p(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.log1p` to each Tensor of the input list. + """ + +def _foreach_log1p_(self: tuple[Tensor, ...] | list[Tensor] | None) -> None: + r""" + _foreach_log1p_(self: List[Tensor]) -> None + + Apply :func:`torch.log1p` to each Tensor of the input list. + """ + +def _foreach_log2( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: + r""" + _foreach_log2(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.log2` to each Tensor of the input list. + """ + +def _foreach_log2_(self: tuple[Tensor, ...] | list[Tensor] | None) -> None: + r""" + _foreach_log2_(self: List[Tensor]) -> None + + Apply :func:`torch.log2` to each Tensor of the input list. + """ + +def _foreach_log_(self: tuple[Tensor, ...] | list[Tensor] | None) -> None: + r""" + _foreach_log_(self: List[Tensor]) -> None + + Apply :func:`torch.log` to each Tensor of the input list. + """ + +def _foreach_max( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_maximum( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalars: Sequence[Number | _complex], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_maximum( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalar: Number | _complex, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_maximum( + self: tuple[Tensor, ...] | list[Tensor] | None, + other: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_maximum_( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalars: Sequence[Number | _complex], +) -> None: ... +@overload +def _foreach_maximum_( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalar: Number | _complex, +) -> None: ... +@overload +def _foreach_maximum_( + self: tuple[Tensor, ...] | list[Tensor] | None, + other: tuple[Tensor, ...] | list[Tensor] | None, +) -> None: ... +@overload +def _foreach_minimum( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalars: Sequence[Number | _complex], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_minimum( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalar: Number | _complex, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_minimum( + self: tuple[Tensor, ...] | list[Tensor] | None, + other: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_minimum_( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalars: Sequence[Number | _complex], +) -> None: ... +@overload +def _foreach_minimum_( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalar: Number | _complex, +) -> None: ... +@overload +def _foreach_minimum_( + self: tuple[Tensor, ...] | list[Tensor] | None, + other: tuple[Tensor, ...] | list[Tensor] | None, +) -> None: ... +@overload +def _foreach_mul( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalars: Sequence[Number | _complex], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_mul( + self: tuple[Tensor, ...] | list[Tensor] | None, + other: Tensor, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_mul( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalar: Number | _complex, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_mul( + self: tuple[Tensor, ...] | list[Tensor] | None, + other: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_mul_( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalars: Sequence[Number | _complex], +) -> None: ... +@overload +def _foreach_mul_( + self: tuple[Tensor, ...] | list[Tensor] | None, + other: Tensor, +) -> None: ... +@overload +def _foreach_mul_( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalar: Number | _complex, +) -> None: ... +@overload +def _foreach_mul_( + self: tuple[Tensor, ...] | list[Tensor] | None, + other: tuple[Tensor, ...] | list[Tensor] | None, +) -> None: ... +def _foreach_neg( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: + r""" + _foreach_neg(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.neg` to each Tensor of the input list. + """ + +def _foreach_neg_(self: tuple[Tensor, ...] | list[Tensor] | None) -> None: + r""" + _foreach_neg_(self: List[Tensor]) -> None + + Apply :func:`torch.neg` to each Tensor of the input list. + """ + +def _foreach_norm( + self: tuple[Tensor, ...] | list[Tensor] | None, + ord: Number | _complex = 2, + dtype: _dtype | None = None, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_pow( + self: tuple[Tensor, ...] | list[Tensor] | None, + exponent: Sequence[Number | _complex], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_pow( + self: tuple[Tensor, ...] | list[Tensor] | None, + exponent: Number | _complex, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_pow( + self: tuple[Tensor, ...] | list[Tensor] | None, + exponent: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_pow( + self: Number | _complex, + exponent: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_pow_( + self: tuple[Tensor, ...] | list[Tensor] | None, + exponent: Sequence[Number | _complex], +) -> None: ... +@overload +def _foreach_pow_( + self: tuple[Tensor, ...] | list[Tensor] | None, + exponent: Number | _complex, +) -> None: ... +@overload +def _foreach_pow_( + self: tuple[Tensor, ...] | list[Tensor] | None, + exponent: tuple[Tensor, ...] | list[Tensor] | None, +) -> None: ... +def _foreach_reciprocal( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: + r""" + _foreach_reciprocal(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.reciprocal` to each Tensor of the input list. + """ + +def _foreach_reciprocal_( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> None: + r""" + _foreach_reciprocal_(self: List[Tensor]) -> None + + Apply :func:`torch.reciprocal` to each Tensor of the input list. + """ + +def _foreach_round( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: + r""" + _foreach_round(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.round` to each Tensor of the input list. + """ + +def _foreach_round_(self: tuple[Tensor, ...] | list[Tensor] | None) -> None: + r""" + _foreach_round_(self: List[Tensor]) -> None + + Apply :func:`torch.round` to each Tensor of the input list. + """ + +def _foreach_rsqrt( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: ... +def _foreach_rsqrt_(self: tuple[Tensor, ...] | list[Tensor] | None) -> None: ... +def _foreach_sigmoid( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: + r""" + _foreach_sigmoid(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.sigmoid` to each Tensor of the input list. + """ + +def _foreach_sigmoid_( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> None: + r""" + _foreach_sigmoid_(self: List[Tensor]) -> None + + Apply :func:`torch.sigmoid` to each Tensor of the input list. + """ + +def _foreach_sign( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: ... +def _foreach_sign_(self: tuple[Tensor, ...] | list[Tensor] | None) -> None: ... +def _foreach_sin( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: + r""" + _foreach_sin(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.sin` to each Tensor of the input list. + """ + +def _foreach_sin_(self: tuple[Tensor, ...] | list[Tensor] | None) -> None: + r""" + _foreach_sin_(self: List[Tensor]) -> None + + Apply :func:`torch.sin` to each Tensor of the input list. + """ + +def _foreach_sinh( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: + r""" + _foreach_sinh(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.sinh` to each Tensor of the input list. + """ + +def _foreach_sinh_(self: tuple[Tensor, ...] | list[Tensor] | None) -> None: + r""" + _foreach_sinh_(self: List[Tensor]) -> None + + Apply :func:`torch.sinh` to each Tensor of the input list. + """ + +def _foreach_sqrt( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: + r""" + _foreach_sqrt(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.sqrt` to each Tensor of the input list. + """ + +def _foreach_sqrt_(self: tuple[Tensor, ...] | list[Tensor] | None) -> None: + r""" + _foreach_sqrt_(self: List[Tensor]) -> None + + Apply :func:`torch.sqrt` to each Tensor of the input list. + """ + +@overload +def _foreach_sub( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalars: Sequence[Number | _complex], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_sub( + self: tuple[Tensor, ...] | list[Tensor] | None, + other: tuple[Tensor, ...] | list[Tensor] | None, + *, + alpha: Number | _complex = 1, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_sub( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalar: Number | _complex, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_sub_( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalars: Sequence[Number | _complex], +) -> None: ... +@overload +def _foreach_sub_( + self: tuple[Tensor, ...] | list[Tensor] | None, + other: tuple[Tensor, ...] | list[Tensor] | None, + *, + alpha: Number | _complex = 1, +) -> None: ... +@overload +def _foreach_sub_( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalar: Number | _complex, +) -> None: ... +def _foreach_tan( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: + r""" + _foreach_tan(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.tan` to each Tensor of the input list. + """ + +def _foreach_tan_(self: tuple[Tensor, ...] | list[Tensor] | None) -> None: + r""" + _foreach_tan_(self: List[Tensor]) -> None + + Apply :func:`torch.tan` to each Tensor of the input list. + """ + +def _foreach_tanh( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: + r""" + _foreach_tanh(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.tanh` to each Tensor of the input list. + """ + +def _foreach_tanh_(self: tuple[Tensor, ...] | list[Tensor] | None) -> None: + r""" + _foreach_tanh_(self: List[Tensor]) -> None + + Apply :func:`torch.tanh` to each Tensor of the input list. + """ + +def _foreach_trunc( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: + r""" + _foreach_trunc(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.trunc` to each Tensor of the input list. + """ + +def _foreach_trunc_(self: tuple[Tensor, ...] | list[Tensor] | None) -> None: + r""" + _foreach_trunc_(self: List[Tensor]) -> None + + Apply :func:`torch.trunc` to each Tensor of the input list. + """ + +def _foreach_zero_(self: tuple[Tensor, ...] | list[Tensor] | None) -> None: + r""" + _foreach_zero_(self: List[Tensor]) -> None + + Apply :func:`torch.zero` to each Tensor of the input list. + """ + +def _from_functional_tensor(t: Tensor) -> Tensor: ... +def _functional_assert_async( + input: Tensor, + assert_msg: str, + dep_token: Tensor, +) -> Tensor: ... +def _functional_assert_scalar( + self: Number | _complex, + assert_msg: str, + dep_token: Tensor, +) -> Tensor: ... +def _functional_sym_constrain_range( + size: Number | _complex, + min: _int | None, + max: _int | None, + dep_token: Tensor, +) -> Tensor: ... +def _functional_sym_constrain_range_for_size( + size: Number | _complex, + min: _int | None, + max: _int | None, + dep_token: Tensor, +) -> Tensor: ... +def _functionalize_apply_view_metas(tensor: Tensor, base: Tensor) -> Tensor: ... +def _functionalize_are_all_mutations_hidden_from_autograd( + t: Tensor, +) -> _bool: ... +def _functionalize_are_all_mutations_under_no_grad_or_inference_mode( + t: Tensor, +) -> _bool: ... +def _functionalize_commit_update(t: Tensor) -> None: ... +def _functionalize_has_metadata_mutation(tensor: Tensor) -> _bool: ... +def _functionalize_inductor_storage_resized_counter(t: Tensor) -> _int: ... +def _functionalize_is_symbolic(tensor: Tensor) -> _bool: ... +def _functionalize_mark_mutation_hidden_from_autograd(t: Tensor) -> None: ... +def _functionalize_mark_storage_changed(tensor: Tensor) -> _bool: ... +def _functionalize_mutation_counter(t: Tensor) -> _int: ... +def _functionalize_replace(self_: Tensor, other: Tensor) -> None: ... +def _functionalize_storage_changed_counter(t: Tensor) -> _int: ... +def _functionalize_sync(t: Tensor) -> None: ... +def _functionalize_unsafe_set(dst: Tensor, src: Tensor) -> None: ... +def _functionalize_was_inductor_storage_resized(t: Tensor) -> _bool: ... +def _functionalize_was_storage_changed(tensor: Tensor) -> _bool: ... +@overload +def _fused_adagrad_( + self: tuple[Tensor, ...] | list[Tensor] | None, + grads: tuple[Tensor, ...] | list[Tensor] | None, + state_sums: tuple[Tensor, ...] | list[Tensor] | None, + state_steps: tuple[Tensor, ...] | list[Tensor] | None, + *, + lr: Tensor, + lr_decay: _float, + weight_decay: _float, + eps: _float, + maximize: _bool, + grad_scale: Tensor | None = None, + found_inf: Tensor | None = None, +) -> None: ... +@overload +def _fused_adagrad_( + self: tuple[Tensor, ...] | list[Tensor] | None, + grads: tuple[Tensor, ...] | list[Tensor] | None, + state_sums: tuple[Tensor, ...] | list[Tensor] | None, + state_steps: tuple[Tensor, ...] | list[Tensor] | None, + *, + lr: _float, + lr_decay: _float, + weight_decay: _float, + eps: _float, + maximize: _bool, + grad_scale: Tensor | None = None, + found_inf: Tensor | None = None, +) -> None: ... +@overload +def _fused_adam_( + self: tuple[Tensor, ...] | list[Tensor] | None, + grads: tuple[Tensor, ...] | list[Tensor] | None, + exp_avgs: tuple[Tensor, ...] | list[Tensor] | None, + exp_avg_sqs: tuple[Tensor, ...] | list[Tensor] | None, + max_exp_avg_sqs: tuple[Tensor, ...] | list[Tensor] | None, + state_steps: tuple[Tensor, ...] | list[Tensor] | None, + *, + lr: Tensor, + beta1: _float, + beta2: _float, + weight_decay: _float, + eps: _float, + amsgrad: _bool, + maximize: _bool, + grad_scale: Tensor | None = None, + found_inf: Tensor | None = None, +) -> None: ... +@overload +def _fused_adam_( + self: tuple[Tensor, ...] | list[Tensor] | None, + grads: tuple[Tensor, ...] | list[Tensor] | None, + exp_avgs: tuple[Tensor, ...] | list[Tensor] | None, + exp_avg_sqs: tuple[Tensor, ...] | list[Tensor] | None, + max_exp_avg_sqs: tuple[Tensor, ...] | list[Tensor] | None, + state_steps: tuple[Tensor, ...] | list[Tensor] | None, + *, + lr: _float, + beta1: _float, + beta2: _float, + weight_decay: _float, + eps: _float, + amsgrad: _bool, + maximize: _bool, + grad_scale: Tensor | None = None, + found_inf: Tensor | None = None, +) -> None: ... +@overload +def _fused_adamw_( + self: tuple[Tensor, ...] | list[Tensor] | None, + grads: tuple[Tensor, ...] | list[Tensor] | None, + exp_avgs: tuple[Tensor, ...] | list[Tensor] | None, + exp_avg_sqs: tuple[Tensor, ...] | list[Tensor] | None, + max_exp_avg_sqs: tuple[Tensor, ...] | list[Tensor] | None, + state_steps: tuple[Tensor, ...] | list[Tensor] | None, + *, + lr: Tensor, + beta1: _float, + beta2: _float, + weight_decay: _float, + eps: _float, + amsgrad: _bool, + maximize: _bool, + grad_scale: Tensor | None = None, + found_inf: Tensor | None = None, +) -> None: ... +@overload +def _fused_adamw_( + self: tuple[Tensor, ...] | list[Tensor] | None, + grads: tuple[Tensor, ...] | list[Tensor] | None, + exp_avgs: tuple[Tensor, ...] | list[Tensor] | None, + exp_avg_sqs: tuple[Tensor, ...] | list[Tensor] | None, + max_exp_avg_sqs: tuple[Tensor, ...] | list[Tensor] | None, + state_steps: tuple[Tensor, ...] | list[Tensor] | None, + *, + lr: _float, + beta1: _float, + beta2: _float, + weight_decay: _float, + eps: _float, + amsgrad: _bool, + maximize: _bool, + grad_scale: Tensor | None = None, + found_inf: Tensor | None = None, +) -> None: ... +def _fused_dropout( + input: Tensor, + p: _float, + generator: Generator | None = None, +) -> tuple[Tensor, Tensor]: ... +def _fused_moving_avg_obs_fq_helper( + input: Tensor, + observer_on: Tensor, + fake_quant_on: Tensor, + running_min: Tensor, + running_max: Tensor, + scale: Tensor, + zero_point: Tensor, + averaging_const: _float, + quant_min: _int, + quant_max: _int, + ch_axis: _int, + per_row_fake_quant: _bool = False, + symmetric_quant: _bool = False, +) -> torch.return_types._fused_moving_avg_obs_fq_helper: ... +def _fused_rms_norm( + input: Tensor, + normalized_shape: _size, + weight: Tensor | None, + eps: _float | None, +) -> tuple[Tensor, Tensor]: ... +def _fused_sdp_choice( + query: Tensor, + key: Tensor, + value: Tensor, + attn_mask: Tensor | None = None, + dropout_p: _float = 0.0, + is_causal: _bool = False, + *, + scale: _float | None = None, + enable_gqa: _bool = False, +) -> _int: ... +@overload +def _fused_sgd_( + self: tuple[Tensor, ...] | list[Tensor] | None, + grads: tuple[Tensor, ...] | list[Tensor] | None, + momentum_buffer_list: tuple[Tensor, ...] | list[Tensor] | None, + *, + weight_decay: _float, + momentum: _float, + lr: Tensor, + dampening: _float, + nesterov: _bool, + maximize: _bool, + is_first_step: _bool, + grad_scale: Tensor | None = None, + found_inf: Tensor | None = None, +) -> None: ... +@overload +def _fused_sgd_( + self: tuple[Tensor, ...] | list[Tensor] | None, + grads: tuple[Tensor, ...] | list[Tensor] | None, + momentum_buffer_list: tuple[Tensor, ...] | list[Tensor] | None, + *, + weight_decay: _float, + momentum: _float, + lr: _float, + dampening: _float, + nesterov: _bool, + maximize: _bool, + is_first_step: _bool, + grad_scale: Tensor | None = None, + found_inf: Tensor | None = None, +) -> None: ... +def _fw_primal_copy( + input: Tensor, + level: _int, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _grid_sampler_2d_cpu_fallback( + input: Tensor, + grid: Tensor, + interpolation_mode: _int, + padding_mode: _int, + align_corners: _bool, +) -> Tensor: ... +def _grouped_mm( + input: Tensor, + mat2: Tensor, + offs: Tensor | None = None, + bias: Tensor | None = None, + out_dtype: _dtype | None = None, +) -> Tensor: ... +def _has_compatible_shallow_copy_type( + input: Tensor, + from_: Tensor, +) -> _bool: ... +def _histogramdd_bin_edges( + input: Tensor, + bins: _size, + *, + range: Sequence[_float] | None = None, + weight: Tensor | None = None, + density: _bool = False, +) -> tuple[Tensor, ...]: ... +def _histogramdd_from_bin_cts( + input: Tensor, + bins: _size, + *, + range: Sequence[_float] | None = None, + weight: Tensor | None = None, + density: _bool = False, +) -> Tensor: ... +def _histogramdd_from_bin_tensors( + input: Tensor, + bins: tuple[Tensor, ...] | list[Tensor] | None, + *, + weight: Tensor | None = None, + density: _bool = False, +) -> Tensor: ... +def _index_put_impl_( + input: Tensor, + indices: tuple[Tensor, ...] | list[Tensor] | None, + values: Tensor, + accumulate: _bool = False, + unsafe: _bool = False, +) -> Tensor: ... +def _indices_copy(input: Tensor, *, out: Tensor | None = None) -> Tensor: ... +def _int_mm( + input: Tensor, + mat2: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _is_all_true(input: Tensor) -> Tensor: ... +def _is_any_true(input: Tensor) -> Tensor: ... +def _is_functional_tensor(t: Tensor) -> _bool: ... +def _is_functional_tensor_base(t: Tensor) -> _bool: ... +def _is_zerotensor(input: Tensor) -> _bool: ... +def _lazy_clone(input: Tensor) -> Tensor: ... +def _linalg_check_errors( + info: Tensor, + api_name: str, + *, + is_matrix: _bool, +) -> None: ... +def _linalg_det( + A: Tensor, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types._linalg_det: ... +def _linalg_eigh( + A: Tensor, + UPLO: str = "L", + compute_v: _bool = True, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types._linalg_eigh: ... +def _linalg_slogdet( + A: Tensor, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types._linalg_slogdet: ... +def _linalg_solve_ex( + A: Tensor, + B: Tensor, + *, + left: _bool = True, + check_errors: _bool = False, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types._linalg_solve_ex: ... +def _linalg_svd( + A: Tensor, + full_matrices: _bool = False, + compute_uv: _bool = True, + *, + driver: str | None = None, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types._linalg_svd: ... +def _log_softmax( + input: Tensor, + dim: _int, + half_to_float: _bool, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _log_softmax_backward_data( + grad_output: Tensor, + output: Tensor, + dim: _int, + input_dtype: _dtype, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _logcumsumexp( + input: Tensor, + dim: _int, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _lstm_mps( + input: Tensor, + hx: tuple[Tensor, ...] | list[Tensor] | None, + params: tuple[Tensor, ...] | list[Tensor] | None, + has_biases: _bool, + num_layers: _int, + dropout: _float, + train: _bool, + bidirectional: _bool, + batch_first: _bool, +) -> tuple[Tensor, Tensor, Tensor, Tensor, Tensor, Tensor]: ... +def _lu_with_info( + input: Tensor, + pivot: _bool = True, + check_errors: _bool = True, +) -> torch.return_types._lu_with_info: ... +def _make_dep_token( + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: ... +def _make_dual(primal: Tensor, tangent: Tensor, level: _int) -> Tensor: ... +def _make_dual_copy( + primal: Tensor, + tangent: Tensor, + level: _int, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _make_per_channel_quantized_tensor( + input: Tensor, + scale: Tensor, + zero_point: Tensor, + axis: _int, +) -> Tensor: ... +def _make_per_tensor_quantized_tensor( + input: Tensor, + scale: _float, + zero_point: _int, +) -> Tensor: ... +def _masked_scale(input: Tensor, mask: Tensor, scale: _float) -> Tensor: ... +def _masked_softmax( + input: Tensor, + mask: Tensor, + dim: _int | None = None, + mask_type: _int | None = None, +) -> Tensor: ... +def _mixed_dtypes_linear( + input: Tensor, + weight: Tensor, + scale: Tensor, + *, + bias: Tensor | None = None, + activation: str | None = None, +) -> Tensor: ... +def _mkldnn_reshape(input: Tensor, shape: _size) -> Tensor: ... +def _mkldnn_transpose(input: Tensor, dim0: _int, dim1: _int) -> Tensor: ... +def _mkldnn_transpose_(input: Tensor, dim0: _int, dim1: _int) -> Tensor: ... +def _mps_convolution( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + padding: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + groups: _int | SymInt, +) -> Tensor: ... +def _mps_convolution_transpose( + input: Tensor, + weight: Tensor, + padding: Sequence[_int | SymInt], + output_padding: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + groups: _int | SymInt, +) -> Tensor: ... +@overload +def _native_batch_norm_legit( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + running_mean: Tensor, + running_var: Tensor, + training: _bool, + momentum: _float, + eps: _float, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> tuple[Tensor, Tensor, Tensor]: ... +@overload +def _native_batch_norm_legit( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + training: _bool, + momentum: _float, + eps: _float, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> tuple[Tensor, Tensor, Tensor]: ... +def _native_batch_norm_legit_no_training( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + running_mean: Tensor, + running_var: Tensor, + momentum: _float, + eps: _float, +) -> tuple[Tensor, Tensor, Tensor]: ... +def _native_multi_head_attention( + query: Tensor, + key: Tensor, + value: Tensor, + embed_dim: _int, + num_head: _int, + qkv_weight: Tensor, + qkv_bias: Tensor, + proj_weight: Tensor, + proj_bias: Tensor, + mask: Tensor | None = None, + need_weights: _bool = True, + average_attn_weights: _bool = True, + mask_type: _int | None = None, +) -> tuple[Tensor, Tensor]: ... +def _neg_view(input: Tensor) -> Tensor: ... +def _neg_view_copy(input: Tensor, *, out: Tensor | None = None) -> Tensor: ... +def _nested_compute_contiguous_strides_offsets( + nested_size: Tensor, +) -> tuple[Tensor, Tensor]: ... +def _nested_from_padded( + padded: Tensor, + cpu_nested_shape_example: Tensor, + fuse_transform_0213: _bool = False, +) -> Tensor: ... +def _nested_from_padded_and_nested_example( + padded: Tensor, + nt_example: Tensor, +) -> Tensor: ... +def _nested_from_padded_tensor( + padded: Tensor, + offsets: Tensor, + dummy: Tensor, + ragged_idx: _int = 1, + min_seqlen: Tensor | None = None, + max_seqlen: Tensor | None = None, + sum_S: _int | SymInt | None = None, +) -> Tensor: ... +def _nested_get_jagged_dummy(any: Tensor) -> Tensor: ... +def _nested_get_lengths(input: Tensor) -> Tensor: ... +def _nested_get_max_seqlen(input: Tensor) -> Tensor: ... +def _nested_get_min_seqlen(input: Tensor) -> Tensor: ... +def _nested_get_offsets(input: Tensor) -> Tensor: ... +def _nested_get_ragged_idx(input: Tensor) -> _int: ... +def _nested_get_values(input: Tensor) -> Tensor: ... +def _nested_get_values_copy( + input: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _nested_tensor_from_mask( + t: Tensor, + mask: Tensor, + mask_check: _bool = True, +) -> Tensor: ... +def _nested_tensor_from_mask_left_aligned(t: Tensor, mask: Tensor) -> _bool: ... +def _nested_tensor_from_tensor_list( + list: tuple[Tensor, ...] | list[Tensor] | None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = None, +) -> Tensor: ... +def _nested_tensor_softmax_with_shape( + input: Tensor, + query: Tensor, +) -> Tensor: ... +def _nested_view_from_buffer( + input: Tensor, + nested_size: Tensor, + nested_strides: Tensor, + offsets: Tensor, +) -> Tensor: ... +def _nested_view_from_buffer_copy( + input: Tensor, + nested_size: Tensor, + nested_strides: Tensor, + offsets: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _nested_view_from_jagged( + input: Tensor, + offsets: Tensor, + dummy: Tensor, + lengths: Tensor | None = None, + ragged_idx: _int = 1, + min_seqlen: Tensor | None = None, + max_seqlen: Tensor | None = None, +) -> Tensor: ... +def _nested_view_from_jagged_copy( + input: Tensor, + offsets: Tensor, + dummy: Tensor, + lengths: Tensor | None = None, + ragged_idx: _int = 1, + min_seqlen: Tensor | None = None, + max_seqlen: Tensor | None = None, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _nnpack_available() -> _bool: ... +def _nnpack_spatial_convolution( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + padding: _int | SymInt | Sequence[_int | SymInt], + stride: _int | SymInt | Sequence[_int | SymInt] = 1, +) -> Tensor: ... +def _pack_padded_sequence( + input: Tensor, + lengths: Tensor, + batch_first: _bool, +) -> tuple[Tensor, Tensor]: ... +def _pad_packed_sequence( + data: Tensor, + batch_sizes: Tensor, + batch_first: _bool, + padding_value: Number | _complex, + total_length: _int, +) -> tuple[Tensor, Tensor]: ... +def _pin_memory( + input: Tensor, + device: DeviceLikeType | None = None, +) -> Tensor: ... +def _prelu_kernel(input: Tensor, weight: Tensor) -> Tensor: ... +def _print(s: str) -> None: ... +def _propagate_xla_data(input: Tensor, output: Tensor) -> None: ... +def _remove_batch_dim( + input: Tensor, + level: _int, + batch_size: _int | SymInt, + out_dim: _int, +) -> Tensor: ... +def _reshape_alias_copy( + input: Tensor, + size: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + *, + out: Tensor | None = None, +) -> Tensor: ... +def _reshape_from_tensor(input: Tensor, shape: Tensor) -> Tensor: ... +def _resize_output_( + input: Tensor, + size: Sequence[_int | SymInt], + device: DeviceLikeType | None, +) -> Tensor: ... +def _rowwise_prune( + weight: Tensor, + mask: Tensor, + compressed_indices_dtype: _dtype, +) -> tuple[Tensor, Tensor]: ... +def _safe_softmax( + input: Tensor, + dim: _int, + dtype: _dtype | None = None, +) -> Tensor: ... +def _sample_dirichlet( + input: Tensor, + generator: Generator | None = None, +) -> Tensor: ... +def _saturate_weight_to_fp16(weight: Tensor) -> Tensor: ... +def _scaled_dot_product_attention_math( + query: Tensor, + key: Tensor, + value: Tensor, + attn_mask: Tensor | None = None, + dropout_p: _float = 0.0, + is_causal: _bool = False, + dropout_mask: Tensor | None = None, + *, + scale: _float | None = None, + enable_gqa: _bool = False, +) -> tuple[Tensor, Tensor]: ... +def _scaled_dot_product_attention_math_for_mps( + query: Tensor, + key: Tensor, + value: Tensor, + attn_mask: Tensor | None = None, + dropout_p: _float = 0.0, + is_causal: _bool = False, + dropout_mask: Tensor | None = None, + *, + scale: _float | None = None, +) -> tuple[Tensor, Tensor]: ... +def _scaled_dot_product_cudnn_attention( + query: Tensor, + key: Tensor, + value: Tensor, + attn_bias: Tensor | None, + compute_log_sumexp: _bool, + dropout_p: _float = 0.0, + is_causal: _bool = False, + return_debug_mask: _bool = False, + *, + scale: _float | None = None, +) -> torch.return_types._scaled_dot_product_cudnn_attention: ... +def _scaled_dot_product_efficient_attention( + query: Tensor, + key: Tensor, + value: Tensor, + attn_bias: Tensor | None, + compute_log_sumexp: _bool, + dropout_p: _float = 0.0, + is_causal: _bool = False, + *, + scale: _float | None = None, +) -> torch.return_types._scaled_dot_product_efficient_attention: ... +def _scaled_dot_product_flash_attention( + query: Tensor, + key: Tensor, + value: Tensor, + dropout_p: _float = 0.0, + is_causal: _bool = False, + return_debug_mask: _bool = False, + *, + scale: _float | None = None, +) -> torch.return_types._scaled_dot_product_flash_attention: ... +def _scaled_dot_product_flash_attention_for_cpu( + query: Tensor, + key: Tensor, + value: Tensor, + dropout_p: _float = 0.0, + is_causal: _bool = False, + *, + attn_mask: Tensor | None = None, + scale: _float | None = None, +) -> torch.return_types._scaled_dot_product_flash_attention_for_cpu: ... +def _scaled_grouped_mm( + input: Tensor, + mat2: Tensor, + scale_a: Tensor, + scale_b: Tensor, + offs: Tensor | None = None, + bias: Tensor | None = None, + scale_result: Tensor | None = None, + out_dtype: _dtype | None = None, + use_fast_accum: _bool = False, +) -> Tensor: ... +def _scaled_grouped_mm_v2( + input: Tensor, + mat2: Tensor, + scale_a: tuple[Tensor, ...] | list[Tensor] | None, + recipe_a: _size, + swizzle_a: _size, + scale_b: tuple[Tensor, ...] | list[Tensor] | None, + recipe_b: _size, + swizzle_b: _size, + offs: Tensor | None = None, + bias: Tensor | None = None, + out_dtype: _dtype | None = None, + contraction_dim: _size = (), + use_fast_accum: _bool = False, +) -> Tensor: ... +def _scaled_mm( + input: Tensor, + mat2: Tensor, + scale_a: Tensor, + scale_b: Tensor, + bias: Tensor | None = None, + scale_result: Tensor | None = None, + out_dtype: _dtype | None = None, + use_fast_accum: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _scaled_mm_v2( + input: Tensor, + mat2: Tensor, + scale_a: tuple[Tensor, ...] | list[Tensor] | None, + recipe_a: _size, + swizzle_a: _size, + scale_b: tuple[Tensor, ...] | list[Tensor] | None, + recipe_b: _size, + swizzle_b: _size, + bias: Tensor | None, + out_dtype: _dtype | None, + contraction_dim: _size = (), + use_fast_accum: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _shape_as_tensor(input: Tensor) -> Tensor: ... +def _sobol_engine_draw( + quasi: Tensor, + n: _int, + sobolstate: Tensor, + dimension: _int, + num_generated: _int, + dtype: _dtype | None, +) -> tuple[Tensor, Tensor]: ... +def _sobol_engine_ff_( + input: Tensor, + n: _int, + sobolstate: Tensor, + dimension: _int, + num_generated: _int, +) -> Tensor: ... +def _sobol_engine_initialize_state_( + input: Tensor, + dimension: _int, +) -> Tensor: ... +def _sobol_engine_scramble_( + input: Tensor, + ltm: Tensor, + dimension: _int, +) -> Tensor: ... +def _softmax( + input: Tensor, + dim: _int, + half_to_float: _bool, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _softmax_backward_data( + grad_output: Tensor, + output: Tensor, + dim: _int, + input_dtype: _dtype, + *, + grad_input: Tensor | None = None, +) -> Tensor: ... +def _sparse_broadcast_to(input: Tensor, size: _size) -> Tensor: ... +def _sparse_broadcast_to_copy( + input: Tensor, + size: _size, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _sparse_csr_prod( + input: Tensor, + dim: _int | _size, + keepdim: _bool = False, + *, + dtype: _dtype | None = None, +) -> Tensor: ... +def _sparse_csr_sum( + input: Tensor, + dim: _int | _size, + keepdim: _bool = False, + *, + dtype: _dtype | None = None, +) -> Tensor: ... +def _sparse_log_softmax_backward_data( + grad_output: Tensor, + output: Tensor, + dim: _int, + input: Tensor, +) -> Tensor: ... +def _sparse_semi_structured_addmm( + input: Tensor, + mat1: Tensor, + mat1_meta: Tensor, + mat2: Tensor, + *, + alpha: Number | _complex = 1, + beta: Number | _complex = 1, + out_dtype: _dtype | None = None, +) -> Tensor: ... +def _sparse_semi_structured_apply( + input: Tensor, + thread_masks: Tensor, +) -> tuple[Tensor, Tensor]: ... +def _sparse_semi_structured_apply_dense( + input: Tensor, + thread_masks: Tensor, +) -> Tensor: ... +def _sparse_semi_structured_linear( + input: Tensor, + weight: Tensor, + meta: Tensor, + *, + bias: Tensor | None = None, + activation: str | None = None, + out_dtype: _dtype | None = None, +) -> Tensor: ... +def _sparse_semi_structured_mm( + mat1: Tensor, + mat1_meta: Tensor, + mat2: Tensor, + *, + out_dtype: _dtype | None = None, +) -> Tensor: ... +def _sparse_semi_structured_tile( + input: Tensor, + algorithm: str = "", + use_cutlass: _bool = True, +) -> tuple[Tensor, Tensor, Tensor, Tensor, Tensor]: ... +def _sparse_softmax_backward_data( + grad_output: Tensor, + output: Tensor, + dim: _int, + input: Tensor, +) -> Tensor: ... +def _sparse_sparse_matmul(input: Tensor, other: Tensor) -> Tensor: ... +@overload +def _sparse_sum(input: Tensor) -> Tensor: ... +@overload +def _sparse_sum(input: Tensor, *, dtype: _dtype) -> Tensor: ... +@overload +def _sparse_sum(input: Tensor, dim: _int | _size) -> Tensor: ... +@overload +def _sparse_sum( + input: Tensor, + dim: _int | _size, + *, + dtype: _dtype, +) -> Tensor: ... +def _stack( + tensors: tuple[Tensor, ...] | list[Tensor] | None, + dim: _int = 0, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _standard_gamma( + input: Tensor, + generator: Generator | None = None, +) -> Tensor: ... +def _standard_gamma_grad(input: Tensor, output: Tensor) -> Tensor: ... +def _sync(t: Tensor) -> None: ... +@overload +def _test_autograd_multiple_dispatch(input: Tensor) -> Tensor: ... +@overload +def _test_autograd_multiple_dispatch(input: Tensor, b: _bool) -> Tensor: ... +def _test_autograd_multiple_dispatch_view(input: Tensor) -> Tensor: ... +def _test_autograd_multiple_dispatch_view_copy( + input: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _test_check_tensor(input: Tensor) -> Tensor: ... +def _test_functorch_fallback(input: Tensor, other: Tensor) -> Tensor: ... +def _test_parallel_materialize( + input: Tensor, + num_parallel: _int, + skip_first: _bool = False, +) -> Tensor: ... +def _test_serialization_subcmul( + input: Tensor, + other: Tensor, + alpha: Number | _complex = 1, +) -> Tensor: ... +def _to_cpu( + tensors: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: ... +def _to_functional_tensor(t: Tensor) -> Tensor: ... +def _to_sparse_semi_structured(dense: Tensor) -> tuple[Tensor, Tensor]: ... +def _transform_bias_rescale_qkv( + qkv: Tensor, + qkv_bias: Tensor, + num_heads: _int, +) -> tuple[Tensor, Tensor, Tensor]: ... +def _transformer_encoder_layer_fwd( + src: Tensor, + embed_dim: _int, + num_heads: _int, + qkv_weight: Tensor, + qkv_bias: Tensor, + proj_weight: Tensor, + proj_bias: Tensor, + use_gelu: _bool, + norm_first: _bool, + eps: _float, + norm_weight_1: Tensor, + norm_bias_1: Tensor, + norm_weight_2: Tensor, + norm_bias_2: Tensor, + ffn_weight_1: Tensor, + ffn_bias_1: Tensor, + ffn_weight_2: Tensor, + ffn_bias_2: Tensor, + mask: Tensor | None = None, + mask_type: _int | None = None, +) -> Tensor: ... +def _trilinear( + i1: Tensor, + i2: Tensor, + i3: Tensor, + expand1: _size, + expand2: _size, + expand3: _size, + sumdim: _size, + unroll_dim: _int = 1, +) -> Tensor: ... +def _triton_multi_head_attention( + query: Tensor, + key: Tensor, + value: Tensor, + embed_dim: _int, + num_head: _int, + qkv_weight: Tensor, + qkv_bias: Tensor, + proj_weight: Tensor, + proj_bias: Tensor, + mask: Tensor | None = None, +) -> Tensor: ... +def _triton_scaled_dot_attention( + q: Tensor, + k: Tensor, + v: Tensor, + dropout_p: _float = 0.0, +) -> Tensor: ... +def _unique( + input: Tensor, + sorted: _bool = True, + return_inverse: _bool = False, +) -> tuple[Tensor, Tensor]: ... +def _unique2( + input: Tensor, + sorted: _bool = True, + return_inverse: _bool = False, + return_counts: _bool = False, +) -> tuple[Tensor, Tensor, Tensor]: ... +def _unpack_dual( + dual: Tensor, + level: _int, +) -> torch.return_types._unpack_dual: ... +def _unsafe_index( + input: Tensor, + indices: tuple[Tensor, ...] | list[Tensor] | None, +) -> Tensor: ... +def _unsafe_index_put( + input: Tensor, + indices: tuple[Tensor, ...] | list[Tensor] | None, + values: Tensor, + accumulate: _bool = False, +) -> Tensor: ... +def _unsafe_masked_index( + input: Tensor, + mask: Tensor, + indices: tuple[Tensor, ...] | list[Tensor] | None, + fill: Number | _complex, +) -> Tensor: ... +def _unsafe_masked_index_put_accumulate( + input: Tensor, + mask: Tensor, + indices: tuple[Tensor, ...] | list[Tensor] | None, + values: Tensor, +) -> Tensor: ... +@overload +def _use_cudnn_ctc_loss( + log_probs: Tensor, + targets: Tensor, + input_lengths: Tensor, + target_lengths: Tensor, + blank: _int, +) -> _bool: ... +@overload +def _use_cudnn_ctc_loss( + log_probs: Tensor, + targets: Tensor, + input_lengths: _size, + target_lengths: _size, + blank: _int, +) -> _bool: ... +def _use_cudnn_rnn_flatten_weight() -> _bool: ... +def _validate_compressed_sparse_indices( + is_crow: _bool, + compressed_idx: Tensor, + plain_idx: Tensor, + cdim: _int, + dim: _int, + nnz: _int, +) -> None: ... +def _validate_sparse_bsc_tensor_args( + ccol_indices: Tensor, + row_indices: Tensor, + values: Tensor, + size: _size, + check_pinning: _bool | None = None, +) -> None: ... +def _validate_sparse_bsr_tensor_args( + crow_indices: Tensor, + col_indices: Tensor, + values: Tensor, + size: _size, + check_pinning: _bool | None = None, +) -> None: ... +def _validate_sparse_compressed_tensor_args( + compressed_indices: Tensor, + plain_indices: Tensor, + values: Tensor, + size: _size, + layout: _layout, + check_pinning: _bool | None = None, +) -> None: ... +def _validate_sparse_coo_tensor_args( + indices: Tensor, + values: Tensor, + size: _size, + is_coalesced: _bool | None = None, + check_pinning: _bool | None = None, +) -> None: ... +def _validate_sparse_csc_tensor_args( + ccol_indices: Tensor, + row_indices: Tensor, + values: Tensor, + size: _size, + check_pinning: _bool | None = None, +) -> None: ... +def _validate_sparse_csr_tensor_args( + crow_indices: Tensor, + col_indices: Tensor, + values: Tensor, + size: _size, + check_pinning: _bool | None = None, +) -> None: ... +def _values_copy(input: Tensor, *, out: Tensor | None = None) -> Tensor: ... +def _weight_int4pack_mm( + input: Tensor, + mat2: Tensor, + qGroupSize: _int, + qScaleAndZeros: Tensor, +) -> Tensor: ... +def _weight_int4pack_mm_for_cpu( + input: Tensor, + mat2: Tensor, + qGroupSize: _int, + qScaleAndZeros: Tensor, +) -> Tensor: ... +def _weight_int4pack_mm_with_scales_and_zeros( + input: Tensor, + mat2: Tensor, + qGroupSize: _int, + qScale: Tensor, + qZeros: Tensor, +) -> Tensor: ... +def _weight_int8pack_mm( + input: Tensor, + mat2: Tensor, + scales: Tensor, +) -> Tensor: ... +def _weight_norm(v: Tensor, g: Tensor, dim: _int = 0) -> Tensor: ... +def _weight_norm_interface( + v: Tensor, + g: Tensor, + dim: _int = 0, +) -> tuple[Tensor, Tensor]: ... +def _wrapped_linear_prepack( + weight: Tensor, + weight_scale: Tensor, + weight_zero_point: Tensor, + bias: Tensor, +) -> Tensor: ... +def _wrapped_quantized_linear_prepacked( + input: Tensor, + input_scale: Tensor, + input_zero_point: Tensor, + packed_weight: Tensor, + output_scale: Tensor, + output_zero_point: Tensor, + out_channel: _int, +) -> Tensor: ... +def abs(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + abs(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Computes the absolute value of each element in :attr:`input`. + + .. math:: + \text{out}_{i} = |\text{input}_{i}| + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.abs(torch.tensor([-1, -2, 3])) + tensor([ 1, 2, 3]) + """ + +def abs_(input: Tensor) -> Tensor: ... +def absolute(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + absolute(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Alias for :func:`torch.abs` + """ + +def acos(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + acos(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Returns a new tensor with the arccosine (in radians) of each element in :attr:`input`. + + .. math:: + \text{out}_{i} = \cos^{-1}(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.3348, -0.5889, 0.2005, -0.1584]) + >>> torch.acos(a) + tensor([ 1.2294, 2.2004, 1.3690, 1.7298]) + """ + +def acos_(input: Tensor) -> Tensor: ... +def acosh(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + acosh(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Returns a new tensor with the inverse hyperbolic cosine of the elements of :attr:`input`. + + .. math:: + \text{out}_{i} = \cosh^{-1}(\text{input}_{i}) + + Note: + The domain of the inverse hyperbolic cosine is `[1, inf)` and values outside this range + will be mapped to ``NaN``, except for `+ INF` for which the output is mapped to `+ INF`. + + Args: + input (Tensor): the input tensor. + + Keyword arguments: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4).uniform_(1, 2) + >>> a + tensor([ 1.3192, 1.9915, 1.9674, 1.7151 ]) + >>> torch.acosh(a) + tensor([ 0.7791, 1.3120, 1.2979, 1.1341 ]) + """ + +def acosh_(input: Tensor) -> Tensor: ... +def adaptive_avg_pool1d(input: Tensor, output_size: _int | _size) -> Tensor: ... +def adaptive_max_pool1d( + input: Tensor, + output_size: _int | _size, +) -> tuple[Tensor, Tensor]: ... +@overload +def add( + input: Tensor | Number | _complex, + other: Tensor | Number | _complex, + *, + alpha: Number | _complex | None = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + add(input, other, *, alpha=1, out=None) -> Tensor + + Adds :attr:`other`, scaled by :attr:`alpha`, to :attr:`input`. + + .. math:: + \text{{out}}_i = \text{{input}}_i + \text{{alpha}} \times \text{{other}}_i + + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer, float, and complex inputs. + + Args: + input (Tensor): the input tensor. + other (Tensor or Number): the tensor or number to add to :attr:`input`. + + Keyword arguments: + alpha (Number): the multiplier for :attr:`other`. + out (Tensor, optional): the output tensor. + + Examples:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.0202, 1.0985, 1.3506, -0.6056]) + >>> torch.add(a, 20) + tensor([ 20.0202, 21.0985, 21.3506, 19.3944]) + + >>> b = torch.randn(4) + >>> b + tensor([-0.9732, -0.3497, 0.6245, 0.4022]) + >>> c = torch.randn(4, 1) + >>> c + tensor([[ 0.3743], + [-1.7724], + [-0.5811], + [-0.8017]]) + >>> torch.add(b, c, alpha=10) + tensor([[ 2.7695, 3.3930, 4.3672, 4.1450], + [-18.6971, -18.0736, -17.0994, -17.3216], + [ -6.7845, -6.1610, -5.1868, -5.4090], + [ -8.9902, -8.3667, -7.3925, -7.6147]]) + """ + +@overload +def add(self: Tensor, alpha: Number | _complex, other: Tensor) -> Tensor: + r""" + add(input, other, *, alpha=1, out=None) -> Tensor + + Adds :attr:`other`, scaled by :attr:`alpha`, to :attr:`input`. + + .. math:: + \text{{out}}_i = \text{{input}}_i + \text{{alpha}} \times \text{{other}}_i + + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer, float, and complex inputs. + + Args: + input (Tensor): the input tensor. + other (Tensor or Number): the tensor or number to add to :attr:`input`. + + Keyword arguments: + alpha (Number): the multiplier for :attr:`other`. + out (Tensor, optional): the output tensor. + + Examples:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.0202, 1.0985, 1.3506, -0.6056]) + >>> torch.add(a, 20) + tensor([ 20.0202, 21.0985, 21.3506, 19.3944]) + + >>> b = torch.randn(4) + >>> b + tensor([-0.9732, -0.3497, 0.6245, 0.4022]) + >>> c = torch.randn(4, 1) + >>> c + tensor([[ 0.3743], + [-1.7724], + [-0.5811], + [-0.8017]]) + >>> torch.add(b, c, alpha=10) + tensor([[ 2.7695, 3.3930, 4.3672, 4.1450], + [-18.6971, -18.0736, -17.0994, -17.3216], + [ -6.7845, -6.1610, -5.1868, -5.4090], + [ -8.9902, -8.3667, -7.3925, -7.6147]]) + """ + +@overload +def add( + self: Tensor, + alpha: Number | _complex, + other: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + add(input, other, *, alpha=1, out=None) -> Tensor + + Adds :attr:`other`, scaled by :attr:`alpha`, to :attr:`input`. + + .. math:: + \text{{out}}_i = \text{{input}}_i + \text{{alpha}} \times \text{{other}}_i + + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer, float, and complex inputs. + + Args: + input (Tensor): the input tensor. + other (Tensor or Number): the tensor or number to add to :attr:`input`. + + Keyword arguments: + alpha (Number): the multiplier for :attr:`other`. + out (Tensor, optional): the output tensor. + + Examples:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.0202, 1.0985, 1.3506, -0.6056]) + >>> torch.add(a, 20) + tensor([ 20.0202, 21.0985, 21.3506, 19.3944]) + + >>> b = torch.randn(4) + >>> b + tensor([-0.9732, -0.3497, 0.6245, 0.4022]) + >>> c = torch.randn(4, 1) + >>> c + tensor([[ 0.3743], + [-1.7724], + [-0.5811], + [-0.8017]]) + >>> torch.add(b, c, alpha=10) + tensor([[ 2.7695, 3.3930, 4.3672, 4.1450], + [-18.6971, -18.0736, -17.0994, -17.3216], + [ -6.7845, -6.1610, -5.1868, -5.4090], + [ -8.9902, -8.3667, -7.3925, -7.6147]]) + """ + +@overload +def addbmm( + beta: Number | _complex, + self: Tensor, + alpha: Number | _complex, + batch1: Tensor, + batch2: Tensor, +) -> Tensor: + r""" + addbmm(input, batch1, batch2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a batch matrix-matrix product of matrices stored + in :attr:`batch1` and :attr:`batch2`, + with a reduced add step (all matrix multiplications get accumulated + along the first dimension). + :attr:`input` is added to the final result. + + :attr:`batch1` and :attr:`batch2` must be 3-D tensors each containing the + same number of matrices. + + If :attr:`batch1` is a :math:`(b \times n \times m)` tensor, :attr:`batch2` is a + :math:`(b \times m \times p)` tensor, :attr:`input` must be + :ref:`broadcastable ` with a :math:`(n \times p)` tensor + and :attr:`out` will be a :math:`(n \times p)` tensor. + + .. math:: + out = \beta\ \text{input} + \alpha\ (\sum_{i=0}^{b-1} \text{batch1}_i \mathbin{@} \text{batch2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and :attr:`alpha` + must be real numbers, otherwise they should be integers. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): matrix to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for `batch1 @ batch2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(3, 5) + >>> batch1 = torch.randn(10, 3, 4) + >>> batch2 = torch.randn(10, 4, 5) + >>> torch.addbmm(M, batch1, batch2) + tensor([[ 6.6311, 0.0503, 6.9768, -12.0362, -2.1653], + [ -4.8185, -1.4255, -6.6760, 8.9453, 2.5743], + [ -3.8202, 4.3691, 1.0943, -1.1109, 5.4730]]) + """ + +@overload +def addbmm( + beta: Number | _complex, + self: Tensor, + alpha: Number | _complex, + batch1: Tensor, + batch2: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + addbmm(input, batch1, batch2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a batch matrix-matrix product of matrices stored + in :attr:`batch1` and :attr:`batch2`, + with a reduced add step (all matrix multiplications get accumulated + along the first dimension). + :attr:`input` is added to the final result. + + :attr:`batch1` and :attr:`batch2` must be 3-D tensors each containing the + same number of matrices. + + If :attr:`batch1` is a :math:`(b \times n \times m)` tensor, :attr:`batch2` is a + :math:`(b \times m \times p)` tensor, :attr:`input` must be + :ref:`broadcastable ` with a :math:`(n \times p)` tensor + and :attr:`out` will be a :math:`(n \times p)` tensor. + + .. math:: + out = \beta\ \text{input} + \alpha\ (\sum_{i=0}^{b-1} \text{batch1}_i \mathbin{@} \text{batch2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and :attr:`alpha` + must be real numbers, otherwise they should be integers. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): matrix to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for `batch1 @ batch2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(3, 5) + >>> batch1 = torch.randn(10, 3, 4) + >>> batch2 = torch.randn(10, 4, 5) + >>> torch.addbmm(M, batch1, batch2) + tensor([[ 6.6311, 0.0503, 6.9768, -12.0362, -2.1653], + [ -4.8185, -1.4255, -6.6760, 8.9453, 2.5743], + [ -3.8202, 4.3691, 1.0943, -1.1109, 5.4730]]) + """ + +@overload +def addbmm( + input: Tensor, + batch1: Tensor, + batch2: Tensor, + *, + beta: Number | _complex = 1, + alpha: Number | _complex = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + addbmm(input, batch1, batch2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a batch matrix-matrix product of matrices stored + in :attr:`batch1` and :attr:`batch2`, + with a reduced add step (all matrix multiplications get accumulated + along the first dimension). + :attr:`input` is added to the final result. + + :attr:`batch1` and :attr:`batch2` must be 3-D tensors each containing the + same number of matrices. + + If :attr:`batch1` is a :math:`(b \times n \times m)` tensor, :attr:`batch2` is a + :math:`(b \times m \times p)` tensor, :attr:`input` must be + :ref:`broadcastable ` with a :math:`(n \times p)` tensor + and :attr:`out` will be a :math:`(n \times p)` tensor. + + .. math:: + out = \beta\ \text{input} + \alpha\ (\sum_{i=0}^{b-1} \text{batch1}_i \mathbin{@} \text{batch2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and :attr:`alpha` + must be real numbers, otherwise they should be integers. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): matrix to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for `batch1 @ batch2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(3, 5) + >>> batch1 = torch.randn(10, 3, 4) + >>> batch2 = torch.randn(10, 4, 5) + >>> torch.addbmm(M, batch1, batch2) + tensor([[ 6.6311, 0.0503, 6.9768, -12.0362, -2.1653], + [ -4.8185, -1.4255, -6.6760, 8.9453, 2.5743], + [ -3.8202, 4.3691, 1.0943, -1.1109, 5.4730]]) + """ + +@overload +def addbmm( + beta: Number | _complex, + self: Tensor, + batch1: Tensor, + batch2: Tensor, +) -> Tensor: + r""" + addbmm(input, batch1, batch2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a batch matrix-matrix product of matrices stored + in :attr:`batch1` and :attr:`batch2`, + with a reduced add step (all matrix multiplications get accumulated + along the first dimension). + :attr:`input` is added to the final result. + + :attr:`batch1` and :attr:`batch2` must be 3-D tensors each containing the + same number of matrices. + + If :attr:`batch1` is a :math:`(b \times n \times m)` tensor, :attr:`batch2` is a + :math:`(b \times m \times p)` tensor, :attr:`input` must be + :ref:`broadcastable ` with a :math:`(n \times p)` tensor + and :attr:`out` will be a :math:`(n \times p)` tensor. + + .. math:: + out = \beta\ \text{input} + \alpha\ (\sum_{i=0}^{b-1} \text{batch1}_i \mathbin{@} \text{batch2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and :attr:`alpha` + must be real numbers, otherwise they should be integers. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): matrix to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for `batch1 @ batch2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(3, 5) + >>> batch1 = torch.randn(10, 3, 4) + >>> batch2 = torch.randn(10, 4, 5) + >>> torch.addbmm(M, batch1, batch2) + tensor([[ 6.6311, 0.0503, 6.9768, -12.0362, -2.1653], + [ -4.8185, -1.4255, -6.6760, 8.9453, 2.5743], + [ -3.8202, 4.3691, 1.0943, -1.1109, 5.4730]]) + """ + +@overload +def addbmm( + beta: Number | _complex, + self: Tensor, + batch1: Tensor, + batch2: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + addbmm(input, batch1, batch2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a batch matrix-matrix product of matrices stored + in :attr:`batch1` and :attr:`batch2`, + with a reduced add step (all matrix multiplications get accumulated + along the first dimension). + :attr:`input` is added to the final result. + + :attr:`batch1` and :attr:`batch2` must be 3-D tensors each containing the + same number of matrices. + + If :attr:`batch1` is a :math:`(b \times n \times m)` tensor, :attr:`batch2` is a + :math:`(b \times m \times p)` tensor, :attr:`input` must be + :ref:`broadcastable ` with a :math:`(n \times p)` tensor + and :attr:`out` will be a :math:`(n \times p)` tensor. + + .. math:: + out = \beta\ \text{input} + \alpha\ (\sum_{i=0}^{b-1} \text{batch1}_i \mathbin{@} \text{batch2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and :attr:`alpha` + must be real numbers, otherwise they should be integers. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): matrix to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for `batch1 @ batch2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(3, 5) + >>> batch1 = torch.randn(10, 3, 4) + >>> batch2 = torch.randn(10, 4, 5) + >>> torch.addbmm(M, batch1, batch2) + tensor([[ 6.6311, 0.0503, 6.9768, -12.0362, -2.1653], + [ -4.8185, -1.4255, -6.6760, 8.9453, 2.5743], + [ -3.8202, 4.3691, 1.0943, -1.1109, 5.4730]]) + """ + +@overload +def addcdiv( + self: Tensor, + value: Number | _complex, + tensor1: Tensor, + tensor2: Tensor, +) -> Tensor: + r""" + addcdiv(input, tensor1, tensor2, *, value=1, out=None) -> Tensor + + Performs the element-wise division of :attr:`tensor1` by :attr:`tensor2`, + multiplies the result by the scalar :attr:`value` and adds it to :attr:`input`. + + .. warning:: + Integer division with addcdiv is no longer supported, and in a future + release addcdiv will perform a true division of tensor1 and tensor2. + The historic addcdiv behavior can be implemented as + (input + value * torch.trunc(tensor1 / tensor2)).to(input.dtype) + for integer inputs and as (input + value * tensor1 / tensor2) for float inputs. + The future addcdiv behavior is just the latter implementation: + (input + value * tensor1 / tensor2), for all dtypes. + + .. math:: + \text{out}_i = \text{input}_i + \text{value} \times \frac{\text{tensor1}_i}{\text{tensor2}_i} + + + The shapes of :attr:`input`, :attr:`tensor1`, and :attr:`tensor2` must be + :ref:`broadcastable `. + + For inputs of type `FloatTensor` or `DoubleTensor`, :attr:`value` must be + a real number, otherwise an integer. + + Args: + input (Tensor): the tensor to be added + tensor1 (Tensor): the numerator tensor + tensor2 (Tensor): the denominator tensor + + Keyword args: + value (Number, optional): multiplier for :math:`\text{tensor1} / \text{tensor2}` + out (Tensor, optional): the output tensor. + + Example:: + + >>> t = torch.randn(1, 3) + >>> t1 = torch.randn(3, 1) + >>> t2 = torch.randn(1, 3) + >>> torch.addcdiv(t, t1, t2, value=0.1) + tensor([[-0.2312, -3.6496, 0.1312], + [-1.0428, 3.4292, -0.1030], + [-0.5369, -0.9829, 0.0430]]) + """ + +@overload +def addcdiv( + self: Tensor, + value: Number | _complex, + tensor1: Tensor, + tensor2: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + addcdiv(input, tensor1, tensor2, *, value=1, out=None) -> Tensor + + Performs the element-wise division of :attr:`tensor1` by :attr:`tensor2`, + multiplies the result by the scalar :attr:`value` and adds it to :attr:`input`. + + .. warning:: + Integer division with addcdiv is no longer supported, and in a future + release addcdiv will perform a true division of tensor1 and tensor2. + The historic addcdiv behavior can be implemented as + (input + value * torch.trunc(tensor1 / tensor2)).to(input.dtype) + for integer inputs and as (input + value * tensor1 / tensor2) for float inputs. + The future addcdiv behavior is just the latter implementation: + (input + value * tensor1 / tensor2), for all dtypes. + + .. math:: + \text{out}_i = \text{input}_i + \text{value} \times \frac{\text{tensor1}_i}{\text{tensor2}_i} + + + The shapes of :attr:`input`, :attr:`tensor1`, and :attr:`tensor2` must be + :ref:`broadcastable `. + + For inputs of type `FloatTensor` or `DoubleTensor`, :attr:`value` must be + a real number, otherwise an integer. + + Args: + input (Tensor): the tensor to be added + tensor1 (Tensor): the numerator tensor + tensor2 (Tensor): the denominator tensor + + Keyword args: + value (Number, optional): multiplier for :math:`\text{tensor1} / \text{tensor2}` + out (Tensor, optional): the output tensor. + + Example:: + + >>> t = torch.randn(1, 3) + >>> t1 = torch.randn(3, 1) + >>> t2 = torch.randn(1, 3) + >>> torch.addcdiv(t, t1, t2, value=0.1) + tensor([[-0.2312, -3.6496, 0.1312], + [-1.0428, 3.4292, -0.1030], + [-0.5369, -0.9829, 0.0430]]) + """ + +@overload +def addcdiv( + input: Tensor, + tensor1: Tensor, + tensor2: Tensor, + *, + value: Number | _complex = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + addcdiv(input, tensor1, tensor2, *, value=1, out=None) -> Tensor + + Performs the element-wise division of :attr:`tensor1` by :attr:`tensor2`, + multiplies the result by the scalar :attr:`value` and adds it to :attr:`input`. + + .. warning:: + Integer division with addcdiv is no longer supported, and in a future + release addcdiv will perform a true division of tensor1 and tensor2. + The historic addcdiv behavior can be implemented as + (input + value * torch.trunc(tensor1 / tensor2)).to(input.dtype) + for integer inputs and as (input + value * tensor1 / tensor2) for float inputs. + The future addcdiv behavior is just the latter implementation: + (input + value * tensor1 / tensor2), for all dtypes. + + .. math:: + \text{out}_i = \text{input}_i + \text{value} \times \frac{\text{tensor1}_i}{\text{tensor2}_i} + + + The shapes of :attr:`input`, :attr:`tensor1`, and :attr:`tensor2` must be + :ref:`broadcastable `. + + For inputs of type `FloatTensor` or `DoubleTensor`, :attr:`value` must be + a real number, otherwise an integer. + + Args: + input (Tensor): the tensor to be added + tensor1 (Tensor): the numerator tensor + tensor2 (Tensor): the denominator tensor + + Keyword args: + value (Number, optional): multiplier for :math:`\text{tensor1} / \text{tensor2}` + out (Tensor, optional): the output tensor. + + Example:: + + >>> t = torch.randn(1, 3) + >>> t1 = torch.randn(3, 1) + >>> t2 = torch.randn(1, 3) + >>> torch.addcdiv(t, t1, t2, value=0.1) + tensor([[-0.2312, -3.6496, 0.1312], + [-1.0428, 3.4292, -0.1030], + [-0.5369, -0.9829, 0.0430]]) + """ + +@overload +def addcmul( + self: Tensor, + value: Number | _complex, + tensor1: Tensor, + tensor2: Tensor, +) -> Tensor: + r""" + addcmul(input, tensor1, tensor2, *, value=1, out=None) -> Tensor + + Performs the element-wise multiplication of :attr:`tensor1` + by :attr:`tensor2`, multiplies the result by the scalar :attr:`value` + and adds it to :attr:`input`. + + .. math:: + \text{out}_i = \text{input}_i + \text{value} \times \text{tensor1}_i \times \text{tensor2}_i + + The shapes of :attr:`tensor`, :attr:`tensor1`, and :attr:`tensor2` must be + :ref:`broadcastable `. + + For inputs of type `FloatTensor` or `DoubleTensor`, :attr:`value` must be + a real number, otherwise an integer. + + Args: + input (Tensor): the tensor to be added + tensor1 (Tensor): the tensor to be multiplied + tensor2 (Tensor): the tensor to be multiplied + + Keyword args: + value (Number, optional): multiplier for :math:`tensor1 .* tensor2` + out (Tensor, optional): the output tensor. + + Example:: + + >>> t = torch.randn(1, 3) + >>> t1 = torch.randn(3, 1) + >>> t2 = torch.randn(1, 3) + >>> torch.addcmul(t, t1, t2, value=0.1) + tensor([[-0.8635, -0.6391, 1.6174], + [-0.7617, -0.5879, 1.7388], + [-0.8353, -0.6249, 1.6511]]) + """ + +@overload +def addcmul( + self: Tensor, + value: Number | _complex, + tensor1: Tensor, + tensor2: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + addcmul(input, tensor1, tensor2, *, value=1, out=None) -> Tensor + + Performs the element-wise multiplication of :attr:`tensor1` + by :attr:`tensor2`, multiplies the result by the scalar :attr:`value` + and adds it to :attr:`input`. + + .. math:: + \text{out}_i = \text{input}_i + \text{value} \times \text{tensor1}_i \times \text{tensor2}_i + + The shapes of :attr:`tensor`, :attr:`tensor1`, and :attr:`tensor2` must be + :ref:`broadcastable `. + + For inputs of type `FloatTensor` or `DoubleTensor`, :attr:`value` must be + a real number, otherwise an integer. + + Args: + input (Tensor): the tensor to be added + tensor1 (Tensor): the tensor to be multiplied + tensor2 (Tensor): the tensor to be multiplied + + Keyword args: + value (Number, optional): multiplier for :math:`tensor1 .* tensor2` + out (Tensor, optional): the output tensor. + + Example:: + + >>> t = torch.randn(1, 3) + >>> t1 = torch.randn(3, 1) + >>> t2 = torch.randn(1, 3) + >>> torch.addcmul(t, t1, t2, value=0.1) + tensor([[-0.8635, -0.6391, 1.6174], + [-0.7617, -0.5879, 1.7388], + [-0.8353, -0.6249, 1.6511]]) + """ + +@overload +def addcmul( + input: Tensor, + tensor1: Tensor, + tensor2: Tensor, + *, + value: Number | _complex = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + addcmul(input, tensor1, tensor2, *, value=1, out=None) -> Tensor + + Performs the element-wise multiplication of :attr:`tensor1` + by :attr:`tensor2`, multiplies the result by the scalar :attr:`value` + and adds it to :attr:`input`. + + .. math:: + \text{out}_i = \text{input}_i + \text{value} \times \text{tensor1}_i \times \text{tensor2}_i + + The shapes of :attr:`tensor`, :attr:`tensor1`, and :attr:`tensor2` must be + :ref:`broadcastable `. + + For inputs of type `FloatTensor` or `DoubleTensor`, :attr:`value` must be + a real number, otherwise an integer. + + Args: + input (Tensor): the tensor to be added + tensor1 (Tensor): the tensor to be multiplied + tensor2 (Tensor): the tensor to be multiplied + + Keyword args: + value (Number, optional): multiplier for :math:`tensor1 .* tensor2` + out (Tensor, optional): the output tensor. + + Example:: + + >>> t = torch.randn(1, 3) + >>> t1 = torch.randn(3, 1) + >>> t2 = torch.randn(1, 3) + >>> torch.addcmul(t, t1, t2, value=0.1) + tensor([[-0.8635, -0.6391, 1.6174], + [-0.7617, -0.5879, 1.7388], + [-0.8353, -0.6249, 1.6511]]) + """ + +@overload +def addmm( + beta: Number | _complex, + self: Tensor, + alpha: Number | _complex, + mat1: Tensor, + mat2: Tensor, +) -> Tensor: + r""" + addmm(input, mat1, mat2, out_dtype=None, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a matrix multiplication of the matrices :attr:`mat1` and :attr:`mat2`. + The matrix :attr:`input` is added to the final result. + + If :attr:`mat1` is a :math:`(n \times m)` tensor, :attr:`mat2` is a + :math:`(m \times p)` tensor, then :attr:`input` must be + :ref:`broadcastable ` with a :math:`(n \times p)` tensor + and :attr:`out` will be a :math:`(n \times p)` tensor. + + :attr:`alpha` and :attr:`beta` are scaling factors on matrix-vector product between + :attr:`mat1` and :attr:`mat2` and the added matrix :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{mat1}_i \mathbin{@} \text{mat2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + This operation has support for arguments with :ref:`sparse layouts`. If + :attr:`input` is sparse the result will have the same layout and if :attr:`out` + is provided it must have the same layout as :attr:`input`. + + + .. warning:: + Sparse support is a beta feature and some layout(s)/dtype/device combinations may not be supported, + or may not have autograd support. If you notice missing functionality please + open a feature request. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): matrix to be added + mat1 (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + out_dtype (dtype, optional): the dtype of the output tensor, + Supported only on CUDA and for torch.float32 given + torch.float16/torch.bfloat16 input dtypes + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(2, 3) + >>> mat1 = torch.randn(2, 3) + >>> mat2 = torch.randn(3, 3) + >>> torch.addmm(M, mat1, mat2) + tensor([[-4.8716, 1.4671, -1.3746], + [ 0.7573, -3.9555, -2.8681]]) + """ + +@overload +def addmm( + beta: Number | _complex, + self: Tensor, + alpha: Number | _complex, + mat1: Tensor, + mat2: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + addmm(input, mat1, mat2, out_dtype=None, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a matrix multiplication of the matrices :attr:`mat1` and :attr:`mat2`. + The matrix :attr:`input` is added to the final result. + + If :attr:`mat1` is a :math:`(n \times m)` tensor, :attr:`mat2` is a + :math:`(m \times p)` tensor, then :attr:`input` must be + :ref:`broadcastable ` with a :math:`(n \times p)` tensor + and :attr:`out` will be a :math:`(n \times p)` tensor. + + :attr:`alpha` and :attr:`beta` are scaling factors on matrix-vector product between + :attr:`mat1` and :attr:`mat2` and the added matrix :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{mat1}_i \mathbin{@} \text{mat2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + This operation has support for arguments with :ref:`sparse layouts`. If + :attr:`input` is sparse the result will have the same layout and if :attr:`out` + is provided it must have the same layout as :attr:`input`. + + + .. warning:: + Sparse support is a beta feature and some layout(s)/dtype/device combinations may not be supported, + or may not have autograd support. If you notice missing functionality please + open a feature request. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): matrix to be added + mat1 (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + out_dtype (dtype, optional): the dtype of the output tensor, + Supported only on CUDA and for torch.float32 given + torch.float16/torch.bfloat16 input dtypes + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(2, 3) + >>> mat1 = torch.randn(2, 3) + >>> mat2 = torch.randn(3, 3) + >>> torch.addmm(M, mat1, mat2) + tensor([[-4.8716, 1.4671, -1.3746], + [ 0.7573, -3.9555, -2.8681]]) + """ + +@overload +def addmm( + input: Tensor, + mat1: Tensor, + mat2: Tensor, + *, + beta: Number | _complex = 1, + alpha: Number | _complex = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + addmm(input, mat1, mat2, out_dtype=None, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a matrix multiplication of the matrices :attr:`mat1` and :attr:`mat2`. + The matrix :attr:`input` is added to the final result. + + If :attr:`mat1` is a :math:`(n \times m)` tensor, :attr:`mat2` is a + :math:`(m \times p)` tensor, then :attr:`input` must be + :ref:`broadcastable ` with a :math:`(n \times p)` tensor + and :attr:`out` will be a :math:`(n \times p)` tensor. + + :attr:`alpha` and :attr:`beta` are scaling factors on matrix-vector product between + :attr:`mat1` and :attr:`mat2` and the added matrix :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{mat1}_i \mathbin{@} \text{mat2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + This operation has support for arguments with :ref:`sparse layouts`. If + :attr:`input` is sparse the result will have the same layout and if :attr:`out` + is provided it must have the same layout as :attr:`input`. + + + .. warning:: + Sparse support is a beta feature and some layout(s)/dtype/device combinations may not be supported, + or may not have autograd support. If you notice missing functionality please + open a feature request. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): matrix to be added + mat1 (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + out_dtype (dtype, optional): the dtype of the output tensor, + Supported only on CUDA and for torch.float32 given + torch.float16/torch.bfloat16 input dtypes + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(2, 3) + >>> mat1 = torch.randn(2, 3) + >>> mat2 = torch.randn(3, 3) + >>> torch.addmm(M, mat1, mat2) + tensor([[-4.8716, 1.4671, -1.3746], + [ 0.7573, -3.9555, -2.8681]]) + """ + +@overload +def addmm( + input: Tensor, + mat1: Tensor, + mat2: Tensor, + out_dtype: _dtype, + *, + beta: Number | _complex = 1, + alpha: Number | _complex = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + addmm(input, mat1, mat2, out_dtype=None, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a matrix multiplication of the matrices :attr:`mat1` and :attr:`mat2`. + The matrix :attr:`input` is added to the final result. + + If :attr:`mat1` is a :math:`(n \times m)` tensor, :attr:`mat2` is a + :math:`(m \times p)` tensor, then :attr:`input` must be + :ref:`broadcastable ` with a :math:`(n \times p)` tensor + and :attr:`out` will be a :math:`(n \times p)` tensor. + + :attr:`alpha` and :attr:`beta` are scaling factors on matrix-vector product between + :attr:`mat1` and :attr:`mat2` and the added matrix :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{mat1}_i \mathbin{@} \text{mat2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + This operation has support for arguments with :ref:`sparse layouts`. If + :attr:`input` is sparse the result will have the same layout and if :attr:`out` + is provided it must have the same layout as :attr:`input`. + + + .. warning:: + Sparse support is a beta feature and some layout(s)/dtype/device combinations may not be supported, + or may not have autograd support. If you notice missing functionality please + open a feature request. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): matrix to be added + mat1 (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + out_dtype (dtype, optional): the dtype of the output tensor, + Supported only on CUDA and for torch.float32 given + torch.float16/torch.bfloat16 input dtypes + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(2, 3) + >>> mat1 = torch.randn(2, 3) + >>> mat2 = torch.randn(3, 3) + >>> torch.addmm(M, mat1, mat2) + tensor([[-4.8716, 1.4671, -1.3746], + [ 0.7573, -3.9555, -2.8681]]) + """ + +@overload +def addmm( + beta: Number | _complex, + self: Tensor, + mat1: Tensor, + mat2: Tensor, +) -> Tensor: + r""" + addmm(input, mat1, mat2, out_dtype=None, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a matrix multiplication of the matrices :attr:`mat1` and :attr:`mat2`. + The matrix :attr:`input` is added to the final result. + + If :attr:`mat1` is a :math:`(n \times m)` tensor, :attr:`mat2` is a + :math:`(m \times p)` tensor, then :attr:`input` must be + :ref:`broadcastable ` with a :math:`(n \times p)` tensor + and :attr:`out` will be a :math:`(n \times p)` tensor. + + :attr:`alpha` and :attr:`beta` are scaling factors on matrix-vector product between + :attr:`mat1` and :attr:`mat2` and the added matrix :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{mat1}_i \mathbin{@} \text{mat2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + This operation has support for arguments with :ref:`sparse layouts`. If + :attr:`input` is sparse the result will have the same layout and if :attr:`out` + is provided it must have the same layout as :attr:`input`. + + + .. warning:: + Sparse support is a beta feature and some layout(s)/dtype/device combinations may not be supported, + or may not have autograd support. If you notice missing functionality please + open a feature request. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): matrix to be added + mat1 (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + out_dtype (dtype, optional): the dtype of the output tensor, + Supported only on CUDA and for torch.float32 given + torch.float16/torch.bfloat16 input dtypes + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(2, 3) + >>> mat1 = torch.randn(2, 3) + >>> mat2 = torch.randn(3, 3) + >>> torch.addmm(M, mat1, mat2) + tensor([[-4.8716, 1.4671, -1.3746], + [ 0.7573, -3.9555, -2.8681]]) + """ + +@overload +def addmm( + beta: Number | _complex, + self: Tensor, + mat1: Tensor, + mat2: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + addmm(input, mat1, mat2, out_dtype=None, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a matrix multiplication of the matrices :attr:`mat1` and :attr:`mat2`. + The matrix :attr:`input` is added to the final result. + + If :attr:`mat1` is a :math:`(n \times m)` tensor, :attr:`mat2` is a + :math:`(m \times p)` tensor, then :attr:`input` must be + :ref:`broadcastable ` with a :math:`(n \times p)` tensor + and :attr:`out` will be a :math:`(n \times p)` tensor. + + :attr:`alpha` and :attr:`beta` are scaling factors on matrix-vector product between + :attr:`mat1` and :attr:`mat2` and the added matrix :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{mat1}_i \mathbin{@} \text{mat2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + This operation has support for arguments with :ref:`sparse layouts`. If + :attr:`input` is sparse the result will have the same layout and if :attr:`out` + is provided it must have the same layout as :attr:`input`. + + + .. warning:: + Sparse support is a beta feature and some layout(s)/dtype/device combinations may not be supported, + or may not have autograd support. If you notice missing functionality please + open a feature request. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): matrix to be added + mat1 (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + out_dtype (dtype, optional): the dtype of the output tensor, + Supported only on CUDA and for torch.float32 given + torch.float16/torch.bfloat16 input dtypes + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(2, 3) + >>> mat1 = torch.randn(2, 3) + >>> mat2 = torch.randn(3, 3) + >>> torch.addmm(M, mat1, mat2) + tensor([[-4.8716, 1.4671, -1.3746], + [ 0.7573, -3.9555, -2.8681]]) + """ + +@overload +def addmv( + beta: Number | _complex, + self: Tensor, + alpha: Number | _complex, + mat: Tensor, + vec: Tensor, +) -> Tensor: + r""" + addmv(input, mat, vec, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a matrix-vector product of the matrix :attr:`mat` and + the vector :attr:`vec`. + The vector :attr:`input` is added to the final result. + + If :attr:`mat` is a :math:`(n \times m)` tensor, :attr:`vec` is a 1-D tensor of + size `m`, then :attr:`input` must be + :ref:`broadcastable ` with a 1-D tensor of size `n` and + :attr:`out` will be 1-D tensor of size `n`. + + :attr:`alpha` and :attr:`beta` are scaling factors on matrix-vector product between + :attr:`mat` and :attr:`vec` and the added tensor :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{mat} \mathbin{@} \text{vec}) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + Args: + input (Tensor): vector to be added + mat (Tensor): matrix to be matrix multiplied + vec (Tensor): vector to be matrix multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat @ vec` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(2) + >>> mat = torch.randn(2, 3) + >>> vec = torch.randn(3) + >>> torch.addmv(M, mat, vec) + tensor([-0.3768, -5.5565]) + """ + +@overload +def addmv( + beta: Number | _complex, + self: Tensor, + alpha: Number | _complex, + mat: Tensor, + vec: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + addmv(input, mat, vec, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a matrix-vector product of the matrix :attr:`mat` and + the vector :attr:`vec`. + The vector :attr:`input` is added to the final result. + + If :attr:`mat` is a :math:`(n \times m)` tensor, :attr:`vec` is a 1-D tensor of + size `m`, then :attr:`input` must be + :ref:`broadcastable ` with a 1-D tensor of size `n` and + :attr:`out` will be 1-D tensor of size `n`. + + :attr:`alpha` and :attr:`beta` are scaling factors on matrix-vector product between + :attr:`mat` and :attr:`vec` and the added tensor :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{mat} \mathbin{@} \text{vec}) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + Args: + input (Tensor): vector to be added + mat (Tensor): matrix to be matrix multiplied + vec (Tensor): vector to be matrix multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat @ vec` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(2) + >>> mat = torch.randn(2, 3) + >>> vec = torch.randn(3) + >>> torch.addmv(M, mat, vec) + tensor([-0.3768, -5.5565]) + """ + +@overload +def addmv( + input: Tensor, + mat: Tensor, + vec: Tensor, + *, + beta: Number | _complex = 1, + alpha: Number | _complex = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + addmv(input, mat, vec, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a matrix-vector product of the matrix :attr:`mat` and + the vector :attr:`vec`. + The vector :attr:`input` is added to the final result. + + If :attr:`mat` is a :math:`(n \times m)` tensor, :attr:`vec` is a 1-D tensor of + size `m`, then :attr:`input` must be + :ref:`broadcastable ` with a 1-D tensor of size `n` and + :attr:`out` will be 1-D tensor of size `n`. + + :attr:`alpha` and :attr:`beta` are scaling factors on matrix-vector product between + :attr:`mat` and :attr:`vec` and the added tensor :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{mat} \mathbin{@} \text{vec}) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + Args: + input (Tensor): vector to be added + mat (Tensor): matrix to be matrix multiplied + vec (Tensor): vector to be matrix multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat @ vec` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(2) + >>> mat = torch.randn(2, 3) + >>> vec = torch.randn(3) + >>> torch.addmv(M, mat, vec) + tensor([-0.3768, -5.5565]) + """ + +@overload +def addmv( + beta: Number | _complex, + self: Tensor, + mat: Tensor, + vec: Tensor, +) -> Tensor: + r""" + addmv(input, mat, vec, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a matrix-vector product of the matrix :attr:`mat` and + the vector :attr:`vec`. + The vector :attr:`input` is added to the final result. + + If :attr:`mat` is a :math:`(n \times m)` tensor, :attr:`vec` is a 1-D tensor of + size `m`, then :attr:`input` must be + :ref:`broadcastable ` with a 1-D tensor of size `n` and + :attr:`out` will be 1-D tensor of size `n`. + + :attr:`alpha` and :attr:`beta` are scaling factors on matrix-vector product between + :attr:`mat` and :attr:`vec` and the added tensor :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{mat} \mathbin{@} \text{vec}) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + Args: + input (Tensor): vector to be added + mat (Tensor): matrix to be matrix multiplied + vec (Tensor): vector to be matrix multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat @ vec` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(2) + >>> mat = torch.randn(2, 3) + >>> vec = torch.randn(3) + >>> torch.addmv(M, mat, vec) + tensor([-0.3768, -5.5565]) + """ + +@overload +def addmv( + beta: Number | _complex, + self: Tensor, + mat: Tensor, + vec: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + addmv(input, mat, vec, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a matrix-vector product of the matrix :attr:`mat` and + the vector :attr:`vec`. + The vector :attr:`input` is added to the final result. + + If :attr:`mat` is a :math:`(n \times m)` tensor, :attr:`vec` is a 1-D tensor of + size `m`, then :attr:`input` must be + :ref:`broadcastable ` with a 1-D tensor of size `n` and + :attr:`out` will be 1-D tensor of size `n`. + + :attr:`alpha` and :attr:`beta` are scaling factors on matrix-vector product between + :attr:`mat` and :attr:`vec` and the added tensor :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{mat} \mathbin{@} \text{vec}) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + Args: + input (Tensor): vector to be added + mat (Tensor): matrix to be matrix multiplied + vec (Tensor): vector to be matrix multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat @ vec` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(2) + >>> mat = torch.randn(2, 3) + >>> vec = torch.randn(3) + >>> torch.addmv(M, mat, vec) + tensor([-0.3768, -5.5565]) + """ + +@overload +def addmv_( + beta: Number | _complex, + self: Tensor, + alpha: Number | _complex, + mat: Tensor, + vec: Tensor, +) -> Tensor: ... +@overload +def addmv_( + input: Tensor, + mat: Tensor, + vec: Tensor, + *, + beta: Number | _complex = 1, + alpha: Number | _complex = 1, +) -> Tensor: ... +@overload +def addmv_( + beta: Number | _complex, + self: Tensor, + mat: Tensor, + vec: Tensor, +) -> Tensor: ... +@overload +def addr( + beta: Number | _complex, + self: Tensor, + alpha: Number | _complex, + vec1: Tensor, + vec2: Tensor, +) -> Tensor: + r""" + addr(input, vec1, vec2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs the outer-product of vectors :attr:`vec1` and :attr:`vec2` + and adds it to the matrix :attr:`input`. + + Optional values :attr:`beta` and :attr:`alpha` are scaling factors on the + outer product between :attr:`vec1` and :attr:`vec2` and the added matrix + :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{vec1} \otimes \text{vec2}) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + If :attr:`vec1` is a vector of size `n` and :attr:`vec2` is a vector + of size `m`, then :attr:`input` must be + :ref:`broadcastable ` with a matrix of size + :math:`(n \times m)` and :attr:`out` will be a matrix of size + :math:`(n \times m)`. + + Args: + input (Tensor): matrix to be added + vec1 (Tensor): the first vector of the outer product + vec2 (Tensor): the second vector of the outer product + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{vec1} \otimes \text{vec2}` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> vec1 = torch.arange(1., 4.) + >>> vec2 = torch.arange(1., 3.) + >>> M = torch.zeros(3, 2) + >>> torch.addr(M, vec1, vec2) + tensor([[ 1., 2.], + [ 2., 4.], + [ 3., 6.]]) + """ + +@overload +def addr( + beta: Number | _complex, + self: Tensor, + alpha: Number | _complex, + vec1: Tensor, + vec2: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + addr(input, vec1, vec2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs the outer-product of vectors :attr:`vec1` and :attr:`vec2` + and adds it to the matrix :attr:`input`. + + Optional values :attr:`beta` and :attr:`alpha` are scaling factors on the + outer product between :attr:`vec1` and :attr:`vec2` and the added matrix + :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{vec1} \otimes \text{vec2}) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + If :attr:`vec1` is a vector of size `n` and :attr:`vec2` is a vector + of size `m`, then :attr:`input` must be + :ref:`broadcastable ` with a matrix of size + :math:`(n \times m)` and :attr:`out` will be a matrix of size + :math:`(n \times m)`. + + Args: + input (Tensor): matrix to be added + vec1 (Tensor): the first vector of the outer product + vec2 (Tensor): the second vector of the outer product + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{vec1} \otimes \text{vec2}` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> vec1 = torch.arange(1., 4.) + >>> vec2 = torch.arange(1., 3.) + >>> M = torch.zeros(3, 2) + >>> torch.addr(M, vec1, vec2) + tensor([[ 1., 2.], + [ 2., 4.], + [ 3., 6.]]) + """ + +@overload +def addr( + input: Tensor, + vec1: Tensor, + vec2: Tensor, + *, + beta: Number | _complex = 1, + alpha: Number | _complex = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + addr(input, vec1, vec2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs the outer-product of vectors :attr:`vec1` and :attr:`vec2` + and adds it to the matrix :attr:`input`. + + Optional values :attr:`beta` and :attr:`alpha` are scaling factors on the + outer product between :attr:`vec1` and :attr:`vec2` and the added matrix + :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{vec1} \otimes \text{vec2}) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + If :attr:`vec1` is a vector of size `n` and :attr:`vec2` is a vector + of size `m`, then :attr:`input` must be + :ref:`broadcastable ` with a matrix of size + :math:`(n \times m)` and :attr:`out` will be a matrix of size + :math:`(n \times m)`. + + Args: + input (Tensor): matrix to be added + vec1 (Tensor): the first vector of the outer product + vec2 (Tensor): the second vector of the outer product + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{vec1} \otimes \text{vec2}` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> vec1 = torch.arange(1., 4.) + >>> vec2 = torch.arange(1., 3.) + >>> M = torch.zeros(3, 2) + >>> torch.addr(M, vec1, vec2) + tensor([[ 1., 2.], + [ 2., 4.], + [ 3., 6.]]) + """ + +@overload +def addr( + beta: Number | _complex, + self: Tensor, + vec1: Tensor, + vec2: Tensor, +) -> Tensor: + r""" + addr(input, vec1, vec2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs the outer-product of vectors :attr:`vec1` and :attr:`vec2` + and adds it to the matrix :attr:`input`. + + Optional values :attr:`beta` and :attr:`alpha` are scaling factors on the + outer product between :attr:`vec1` and :attr:`vec2` and the added matrix + :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{vec1} \otimes \text{vec2}) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + If :attr:`vec1` is a vector of size `n` and :attr:`vec2` is a vector + of size `m`, then :attr:`input` must be + :ref:`broadcastable ` with a matrix of size + :math:`(n \times m)` and :attr:`out` will be a matrix of size + :math:`(n \times m)`. + + Args: + input (Tensor): matrix to be added + vec1 (Tensor): the first vector of the outer product + vec2 (Tensor): the second vector of the outer product + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{vec1} \otimes \text{vec2}` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> vec1 = torch.arange(1., 4.) + >>> vec2 = torch.arange(1., 3.) + >>> M = torch.zeros(3, 2) + >>> torch.addr(M, vec1, vec2) + tensor([[ 1., 2.], + [ 2., 4.], + [ 3., 6.]]) + """ + +@overload +def addr( + beta: Number | _complex, + self: Tensor, + vec1: Tensor, + vec2: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + addr(input, vec1, vec2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs the outer-product of vectors :attr:`vec1` and :attr:`vec2` + and adds it to the matrix :attr:`input`. + + Optional values :attr:`beta` and :attr:`alpha` are scaling factors on the + outer product between :attr:`vec1` and :attr:`vec2` and the added matrix + :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{vec1} \otimes \text{vec2}) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + If :attr:`vec1` is a vector of size `n` and :attr:`vec2` is a vector + of size `m`, then :attr:`input` must be + :ref:`broadcastable ` with a matrix of size + :math:`(n \times m)` and :attr:`out` will be a matrix of size + :math:`(n \times m)`. + + Args: + input (Tensor): matrix to be added + vec1 (Tensor): the first vector of the outer product + vec2 (Tensor): the second vector of the outer product + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{vec1} \otimes \text{vec2}` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> vec1 = torch.arange(1., 4.) + >>> vec2 = torch.arange(1., 3.) + >>> M = torch.zeros(3, 2) + >>> torch.addr(M, vec1, vec2) + tensor([[ 1., 2.], + [ 2., 4.], + [ 3., 6.]]) + """ + +def adjoint(input: Tensor) -> Tensor: + r""" + adjoint(input: Tensor) -> Tensor + Returns a view of the tensor conjugated and with the last two dimensions transposed. + + ``x.adjoint()`` is equivalent to ``x.transpose(-2, -1).conj()`` for complex tensors and + to ``x.transpose(-2, -1)`` for real tensors. + + Args: + {input} + + Example:: + + >>> x = torch.arange(4, dtype=torch.float) + >>> A = torch.complex(x, x).reshape(2, 2) + >>> A + tensor([[0.+0.j, 1.+1.j], + [2.+2.j, 3.+3.j]]) + >>> A.adjoint() + tensor([[0.-0.j, 2.-2.j], + [1.-1.j, 3.-3.j]]) + >>> (A.adjoint() == A.mH).all() + tensor(True) + """ + +def affine_grid_generator( + theta: Tensor, + size: Sequence[_int | SymInt], + align_corners: _bool, +) -> Tensor: ... +def alias_copy(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + Performs the same operation as :func:`torch.alias`, but all output tensors + are freshly created instead of aliasing the input. + """ + +@overload +def all(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + all(input: Tensor, *, out=None) -> Tensor + + Tests if all elements in :attr:`input` evaluate to `True`. + + .. note:: This function matches the behaviour of NumPy in returning + output of dtype `bool` for all supported dtypes except `uint8`. + For `uint8` the dtype of output is `uint8` itself. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(1, 2).bool() + >>> a + tensor([[False, True]], dtype=torch.bool) + >>> torch.all(a) + tensor(False, dtype=torch.bool) + >>> a = torch.arange(0, 3) + >>> a + tensor([0, 1, 2]) + >>> torch.all(a) + tensor(False) + + .. function:: all(input, dim, keepdim=False, *, out=None) -> Tensor + :noindex: + + For each row of :attr:`input` in the given dimension :attr:`dim`, + returns `True` if all elements in the row evaluate to `True` and `False` otherwise. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(4, 2).bool() + >>> a + tensor([[True, True], + [True, False], + [True, True], + [True, True]], dtype=torch.bool) + >>> torch.all(a, dim=1) + tensor([ True, False, True, True], dtype=torch.bool) + >>> torch.all(a, dim=0) + tensor([ True, False], dtype=torch.bool) + """ + +@overload +def all( + input: Tensor, + dim: _size | None = None, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + all(input: Tensor, *, out=None) -> Tensor + + Tests if all elements in :attr:`input` evaluate to `True`. + + .. note:: This function matches the behaviour of NumPy in returning + output of dtype `bool` for all supported dtypes except `uint8`. + For `uint8` the dtype of output is `uint8` itself. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(1, 2).bool() + >>> a + tensor([[False, True]], dtype=torch.bool) + >>> torch.all(a) + tensor(False, dtype=torch.bool) + >>> a = torch.arange(0, 3) + >>> a + tensor([0, 1, 2]) + >>> torch.all(a) + tensor(False) + + .. function:: all(input, dim, keepdim=False, *, out=None) -> Tensor + :noindex: + + For each row of :attr:`input` in the given dimension :attr:`dim`, + returns `True` if all elements in the row evaluate to `True` and `False` otherwise. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(4, 2).bool() + >>> a + tensor([[True, True], + [True, False], + [True, True], + [True, True]], dtype=torch.bool) + >>> torch.all(a, dim=1) + tensor([ True, False, True, True], dtype=torch.bool) + >>> torch.all(a, dim=0) + tensor([ True, False], dtype=torch.bool) + """ + +@overload +def all( + input: Tensor, + dim: _int, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + all(input: Tensor, *, out=None) -> Tensor + + Tests if all elements in :attr:`input` evaluate to `True`. + + .. note:: This function matches the behaviour of NumPy in returning + output of dtype `bool` for all supported dtypes except `uint8`. + For `uint8` the dtype of output is `uint8` itself. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(1, 2).bool() + >>> a + tensor([[False, True]], dtype=torch.bool) + >>> torch.all(a) + tensor(False, dtype=torch.bool) + >>> a = torch.arange(0, 3) + >>> a + tensor([0, 1, 2]) + >>> torch.all(a) + tensor(False) + + .. function:: all(input, dim, keepdim=False, *, out=None) -> Tensor + :noindex: + + For each row of :attr:`input` in the given dimension :attr:`dim`, + returns `True` if all elements in the row evaluate to `True` and `False` otherwise. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(4, 2).bool() + >>> a + tensor([[True, True], + [True, False], + [True, True], + [True, True]], dtype=torch.bool) + >>> torch.all(a, dim=1) + tensor([ True, False, True, True], dtype=torch.bool) + >>> torch.all(a, dim=0) + tensor([ True, False], dtype=torch.bool) + """ + +@overload +def all( + input: Tensor, + dim: str | EllipsisType | None, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + all(input: Tensor, *, out=None) -> Tensor + + Tests if all elements in :attr:`input` evaluate to `True`. + + .. note:: This function matches the behaviour of NumPy in returning + output of dtype `bool` for all supported dtypes except `uint8`. + For `uint8` the dtype of output is `uint8` itself. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(1, 2).bool() + >>> a + tensor([[False, True]], dtype=torch.bool) + >>> torch.all(a) + tensor(False, dtype=torch.bool) + >>> a = torch.arange(0, 3) + >>> a + tensor([0, 1, 2]) + >>> torch.all(a) + tensor(False) + + .. function:: all(input, dim, keepdim=False, *, out=None) -> Tensor + :noindex: + + For each row of :attr:`input` in the given dimension :attr:`dim`, + returns `True` if all elements in the row evaluate to `True` and `False` otherwise. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(4, 2).bool() + >>> a + tensor([[True, True], + [True, False], + [True, True], + [True, True]], dtype=torch.bool) + >>> torch.all(a, dim=1) + tensor([ True, False, True, True], dtype=torch.bool) + >>> torch.all(a, dim=0) + tensor([ True, False], dtype=torch.bool) + """ + +def allclose( + input: Tensor, + other: Tensor, + rtol: _float = 1e-05, + atol: _float = 1e-08, + equal_nan: _bool = False, +) -> _bool: + r""" + allclose(input: Tensor, other: Tensor, rtol: float = 1e-05, atol: float = 1e-08, equal_nan: bool = False) -> bool + + This function checks if :attr:`input` and :attr:`other` satisfy the condition: + + .. math:: + \lvert \text{input}_i - \text{other}_i \rvert \leq \texttt{atol} + \texttt{rtol} \times \lvert \text{other}_i \rvert + + elementwise, for all elements of :attr:`input` and :attr:`other`. The behaviour of this function is analogous to + `numpy.allclose `_ + + Args: + input (Tensor): first tensor to compare + other (Tensor): second tensor to compare + atol (float, optional): absolute tolerance. Default: 1e-08 + rtol (float, optional): relative tolerance. Default: 1e-05 + equal_nan (bool, optional): if ``True``, then two ``NaN`` s will be considered equal. Default: ``False`` + + Example:: + + >>> torch.allclose(torch.tensor([10000., 1e-07]), torch.tensor([10000.1, 1e-08])) + False + >>> torch.allclose(torch.tensor([10000., 1e-08]), torch.tensor([10000.1, 1e-09])) + True + >>> torch.allclose(torch.tensor([1.0, float('nan')]), torch.tensor([1.0, float('nan')])) + False + >>> torch.allclose(torch.tensor([1.0, float('nan')]), torch.tensor([1.0, float('nan')]), equal_nan=True) + True + """ + +def alpha_dropout(input: Tensor, p: _float, train: _bool) -> Tensor: ... +def alpha_dropout_(input: Tensor, p: _float, train: _bool) -> Tensor: ... +def amax( + input: Tensor, + dim: _int | _size = (), + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + amax(input, dim, keepdim=False, *, out=None) -> Tensor + + Returns the maximum value of each slice of the :attr:`input` tensor in the given + dimension(s) :attr:`dim`. + + .. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.8177, 1.4878, -0.2491, 0.9130], + [-0.7158, 1.1775, 2.0992, 0.4817], + [-0.0053, 0.0164, -1.3738, -0.0507], + [ 1.9700, 1.1106, -1.0318, -1.0816]]) + >>> torch.amax(a, 1) + tensor([1.4878, 2.0992, 0.0164, 1.9700]) + """ + +def amin( + input: Tensor, + dim: _int | _size = (), + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + amin(input, dim, keepdim=False, *, out=None) -> Tensor + + Returns the minimum value of each slice of the :attr:`input` tensor in the given + dimension(s) :attr:`dim`. + + .. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.6451, -0.4866, 0.2987, -1.3312], + [-0.5744, 1.2980, 1.8397, -0.2713], + [ 0.9128, 0.9214, -1.7268, -0.2995], + [ 0.9023, 0.4853, 0.9075, -1.6165]]) + >>> torch.amin(a, 1) + tensor([-1.3312, -0.5744, -1.7268, -1.6165]) + """ + +def aminmax( + input: Tensor, + *, + dim: _int | None = None, + keepdim: _bool = False, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.aminmax: + r""" + aminmax(input, *, dim=None, keepdim=False, out=None) -> (Tensor min, Tensor max) + + Computes the minimum and maximum values of the :attr:`input` tensor. + + Args: + input (Tensor): + The input tensor + + Keyword Args: + dim (Optional[int]): + The dimension along which to compute the values. If `None`, + computes the values over the entire :attr:`input` tensor. + Default is `None`. + keepdim (bool): + If `True`, the reduced dimensions will be kept in the output + tensor as dimensions with size 1 for broadcasting, otherwise + they will be removed, as if calling (:func:`torch.squeeze`). + Default is `False`. + out (Optional[Tuple[Tensor, Tensor]]): + Optional tensors on which to write the result. Must have the same + shape and dtype as the expected output. + Default is `None`. + + Returns: + A named tuple `(min, max)` containing the minimum and maximum values. + + Raises: + RuntimeError + If any of the dimensions to compute the values over has size 0. + + .. note:: + NaN values are propagated to the output if at least one value is NaN. + + .. seealso:: + :func:`torch.amin` computes just the minimum value + :func:`torch.amax` computes just the maximum value + + Example:: + + >>> torch.aminmax(torch.tensor([1, -3, 5])) + torch.return_types.aminmax( + min=tensor(-3), + max=tensor(5)) + + >>> # aminmax propagates NaNs + >>> torch.aminmax(torch.tensor([1, -3, 5, torch.nan])) + torch.return_types.aminmax( + min=tensor(nan), + max=tensor(nan)) + + >>> t = torch.arange(10).view(2, 5) + >>> t + tensor([[0, 1, 2, 3, 4], + [5, 6, 7, 8, 9]]) + >>> t.aminmax(dim=0, keepdim=True) + torch.return_types.aminmax( + min=tensor([[0, 1, 2, 3, 4]]), + max=tensor([[5, 6, 7, 8, 9]])) + """ + +def angle(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + angle(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Computes the element-wise angle (in radians) of the given :attr:`input` tensor. + + .. math:: + \text{out}_{i} = angle(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + .. note:: Starting in PyTorch 1.8, angle returns pi for negative real numbers, + zero for non-negative real numbers, and propagates NaNs. Previously + the function would return zero for all real numbers and not propagate + floating-point NaNs. + + Example:: + + >>> torch.angle(torch.tensor([-1 + 1j, -2 + 2j, 3 - 3j]))*180/3.14159 + tensor([ 135., 135, -45]) + """ + +@overload +def any(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + any(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Tests if any element in :attr:`input` evaluates to `True`. + + .. note:: This function matches the behaviour of NumPy in returning + output of dtype `bool` for all supported dtypes except `uint8`. + For `uint8` the dtype of output is `uint8` itself. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(1, 2).bool() + >>> a + tensor([[False, True]], dtype=torch.bool) + >>> torch.any(a) + tensor(True, dtype=torch.bool) + >>> a = torch.arange(0, 3) + >>> a + tensor([0, 1, 2]) + >>> torch.any(a) + tensor(True) + + .. function:: any(input, dim, keepdim=False, *, out=None) -> Tensor + :noindex: + + For each row of :attr:`input` in the given dimension :attr:`dim`, + returns `True` if any element in the row evaluate to `True` and `False` otherwise. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4, 2) < 0 + >>> a + tensor([[ True, True], + [False, True], + [ True, True], + [False, False]]) + >>> torch.any(a, 1) + tensor([ True, True, True, False]) + >>> torch.any(a, 0) + tensor([True, True]) + """ + +@overload +def any( + input: Tensor, + dim: _size | None = None, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + any(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Tests if any element in :attr:`input` evaluates to `True`. + + .. note:: This function matches the behaviour of NumPy in returning + output of dtype `bool` for all supported dtypes except `uint8`. + For `uint8` the dtype of output is `uint8` itself. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(1, 2).bool() + >>> a + tensor([[False, True]], dtype=torch.bool) + >>> torch.any(a) + tensor(True, dtype=torch.bool) + >>> a = torch.arange(0, 3) + >>> a + tensor([0, 1, 2]) + >>> torch.any(a) + tensor(True) + + .. function:: any(input, dim, keepdim=False, *, out=None) -> Tensor + :noindex: + + For each row of :attr:`input` in the given dimension :attr:`dim`, + returns `True` if any element in the row evaluate to `True` and `False` otherwise. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4, 2) < 0 + >>> a + tensor([[ True, True], + [False, True], + [ True, True], + [False, False]]) + >>> torch.any(a, 1) + tensor([ True, True, True, False]) + >>> torch.any(a, 0) + tensor([True, True]) + """ + +@overload +def any( + input: Tensor, + dim: _int, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + any(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Tests if any element in :attr:`input` evaluates to `True`. + + .. note:: This function matches the behaviour of NumPy in returning + output of dtype `bool` for all supported dtypes except `uint8`. + For `uint8` the dtype of output is `uint8` itself. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(1, 2).bool() + >>> a + tensor([[False, True]], dtype=torch.bool) + >>> torch.any(a) + tensor(True, dtype=torch.bool) + >>> a = torch.arange(0, 3) + >>> a + tensor([0, 1, 2]) + >>> torch.any(a) + tensor(True) + + .. function:: any(input, dim, keepdim=False, *, out=None) -> Tensor + :noindex: + + For each row of :attr:`input` in the given dimension :attr:`dim`, + returns `True` if any element in the row evaluate to `True` and `False` otherwise. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4, 2) < 0 + >>> a + tensor([[ True, True], + [False, True], + [ True, True], + [False, False]]) + >>> torch.any(a, 1) + tensor([ True, True, True, False]) + >>> torch.any(a, 0) + tensor([True, True]) + """ + +@overload +def any( + input: Tensor, + dim: str | EllipsisType | None, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + any(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Tests if any element in :attr:`input` evaluates to `True`. + + .. note:: This function matches the behaviour of NumPy in returning + output of dtype `bool` for all supported dtypes except `uint8`. + For `uint8` the dtype of output is `uint8` itself. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(1, 2).bool() + >>> a + tensor([[False, True]], dtype=torch.bool) + >>> torch.any(a) + tensor(True, dtype=torch.bool) + >>> a = torch.arange(0, 3) + >>> a + tensor([0, 1, 2]) + >>> torch.any(a) + tensor(True) + + .. function:: any(input, dim, keepdim=False, *, out=None) -> Tensor + :noindex: + + For each row of :attr:`input` in the given dimension :attr:`dim`, + returns `True` if any element in the row evaluate to `True` and `False` otherwise. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4, 2) < 0 + >>> a + tensor([[ True, True], + [False, True], + [ True, True], + [False, False]]) + >>> torch.any(a, 1) + tensor([ True, True, True, False]) + >>> torch.any(a, 0) + tensor([True, True]) + """ + +@overload +def arange( + start: Number, + end: Number, + step: Number, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + pin_memory: _bool = False, +) -> Tensor: + r""" + arange(start=0, end, step=1, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a 1-D tensor of size :math:`\left\lceil \frac{\text{end} - \text{start}}{\text{step}} \right\rceil` + with values from the interval ``[start, end)`` taken with common difference + :attr:`step` beginning from `start`. + + Note: When using floating-point dtypes (especially reduced precision types like ``bfloat16``), + the results may be affected by floating-point rounding behavior. Some values in the sequence + might not be exactly representable in certain floating-point formats, which can lead to + repeated values or unexpected rounding. For precise sequences, it is recommended to use + integer dtypes instead of floating-point dtypes. + + Note that non-integer :attr:`step` is subject to floating point rounding errors when + comparing against :attr:`end`; to avoid inconsistency, we advise subtracting a small epsilon from :attr:`end` + in such cases. + + .. math:: + \text{out}_{{i+1}} = \text{out}_{i} + \text{step} + + Args: + start (Number, optional): the starting value for the set of points. Default: ``0``. + end (Number): the ending value for the set of points + step (Number, optional): the gap between each pair of adjacent points. Default: ``1``. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). If `dtype` is not given, infer the data type from the other input + arguments. If any of `start`, `end`, or `stop` are floating-point, the + `dtype` is inferred to be the default dtype, see + :meth:`~torch.get_default_dtype`. Otherwise, the `dtype` is inferred to + be `torch.int64`. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.arange(5) + tensor([ 0, 1, 2, 3, 4]) + >>> torch.arange(1, 4) + tensor([ 1, 2, 3]) + >>> torch.arange(1, 2.5, 0.5) + tensor([ 1.0000, 1.5000, 2.0000]) + """ + +@overload +def arange( + start: Number, + end: Number, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + pin_memory: _bool = False, +) -> Tensor: + r""" + arange(start=0, end, step=1, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a 1-D tensor of size :math:`\left\lceil \frac{\text{end} - \text{start}}{\text{step}} \right\rceil` + with values from the interval ``[start, end)`` taken with common difference + :attr:`step` beginning from `start`. + + Note: When using floating-point dtypes (especially reduced precision types like ``bfloat16``), + the results may be affected by floating-point rounding behavior. Some values in the sequence + might not be exactly representable in certain floating-point formats, which can lead to + repeated values or unexpected rounding. For precise sequences, it is recommended to use + integer dtypes instead of floating-point dtypes. + + Note that non-integer :attr:`step` is subject to floating point rounding errors when + comparing against :attr:`end`; to avoid inconsistency, we advise subtracting a small epsilon from :attr:`end` + in such cases. + + .. math:: + \text{out}_{{i+1}} = \text{out}_{i} + \text{step} + + Args: + start (Number, optional): the starting value for the set of points. Default: ``0``. + end (Number): the ending value for the set of points + step (Number, optional): the gap between each pair of adjacent points. Default: ``1``. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). If `dtype` is not given, infer the data type from the other input + arguments. If any of `start`, `end`, or `stop` are floating-point, the + `dtype` is inferred to be the default dtype, see + :meth:`~torch.get_default_dtype`. Otherwise, the `dtype` is inferred to + be `torch.int64`. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.arange(5) + tensor([ 0, 1, 2, 3, 4]) + >>> torch.arange(1, 4) + tensor([ 1, 2, 3]) + >>> torch.arange(1, 2.5, 0.5) + tensor([ 1.0000, 1.5000, 2.0000]) + """ + +@overload +def arange( + end: Number, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + pin_memory: _bool = False, +) -> Tensor: + r""" + arange(start=0, end, step=1, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a 1-D tensor of size :math:`\left\lceil \frac{\text{end} - \text{start}}{\text{step}} \right\rceil` + with values from the interval ``[start, end)`` taken with common difference + :attr:`step` beginning from `start`. + + Note: When using floating-point dtypes (especially reduced precision types like ``bfloat16``), + the results may be affected by floating-point rounding behavior. Some values in the sequence + might not be exactly representable in certain floating-point formats, which can lead to + repeated values or unexpected rounding. For precise sequences, it is recommended to use + integer dtypes instead of floating-point dtypes. + + Note that non-integer :attr:`step` is subject to floating point rounding errors when + comparing against :attr:`end`; to avoid inconsistency, we advise subtracting a small epsilon from :attr:`end` + in such cases. + + .. math:: + \text{out}_{{i+1}} = \text{out}_{i} + \text{step} + + Args: + start (Number, optional): the starting value for the set of points. Default: ``0``. + end (Number): the ending value for the set of points + step (Number, optional): the gap between each pair of adjacent points. Default: ``1``. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). If `dtype` is not given, infer the data type from the other input + arguments. If any of `start`, `end`, or `stop` are floating-point, the + `dtype` is inferred to be the default dtype, see + :meth:`~torch.get_default_dtype`. Otherwise, the `dtype` is inferred to + be `torch.int64`. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.arange(5) + tensor([ 0, 1, 2, 3, 4]) + >>> torch.arange(1, 4) + tensor([ 1, 2, 3]) + >>> torch.arange(1, 2.5, 0.5) + tensor([ 1.0000, 1.5000, 2.0000]) + """ + +@overload +def arange( + end: Number | _complex, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + arange(start=0, end, step=1, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a 1-D tensor of size :math:`\left\lceil \frac{\text{end} - \text{start}}{\text{step}} \right\rceil` + with values from the interval ``[start, end)`` taken with common difference + :attr:`step` beginning from `start`. + + Note: When using floating-point dtypes (especially reduced precision types like ``bfloat16``), + the results may be affected by floating-point rounding behavior. Some values in the sequence + might not be exactly representable in certain floating-point formats, which can lead to + repeated values or unexpected rounding. For precise sequences, it is recommended to use + integer dtypes instead of floating-point dtypes. + + Note that non-integer :attr:`step` is subject to floating point rounding errors when + comparing against :attr:`end`; to avoid inconsistency, we advise subtracting a small epsilon from :attr:`end` + in such cases. + + .. math:: + \text{out}_{{i+1}} = \text{out}_{i} + \text{step} + + Args: + start (Number, optional): the starting value for the set of points. Default: ``0``. + end (Number): the ending value for the set of points + step (Number, optional): the gap between each pair of adjacent points. Default: ``1``. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). If `dtype` is not given, infer the data type from the other input + arguments. If any of `start`, `end`, or `stop` are floating-point, the + `dtype` is inferred to be the default dtype, see + :meth:`~torch.get_default_dtype`. Otherwise, the `dtype` is inferred to + be `torch.int64`. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.arange(5) + tensor([ 0, 1, 2, 3, 4]) + >>> torch.arange(1, 4) + tensor([ 1, 2, 3]) + >>> torch.arange(1, 2.5, 0.5) + tensor([ 1.0000, 1.5000, 2.0000]) + """ + +@overload +def arange( + start: Number | _complex, + end: Number | _complex, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + arange(start=0, end, step=1, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a 1-D tensor of size :math:`\left\lceil \frac{\text{end} - \text{start}}{\text{step}} \right\rceil` + with values from the interval ``[start, end)`` taken with common difference + :attr:`step` beginning from `start`. + + Note: When using floating-point dtypes (especially reduced precision types like ``bfloat16``), + the results may be affected by floating-point rounding behavior. Some values in the sequence + might not be exactly representable in certain floating-point formats, which can lead to + repeated values or unexpected rounding. For precise sequences, it is recommended to use + integer dtypes instead of floating-point dtypes. + + Note that non-integer :attr:`step` is subject to floating point rounding errors when + comparing against :attr:`end`; to avoid inconsistency, we advise subtracting a small epsilon from :attr:`end` + in such cases. + + .. math:: + \text{out}_{{i+1}} = \text{out}_{i} + \text{step} + + Args: + start (Number, optional): the starting value for the set of points. Default: ``0``. + end (Number): the ending value for the set of points + step (Number, optional): the gap between each pair of adjacent points. Default: ``1``. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). If `dtype` is not given, infer the data type from the other input + arguments. If any of `start`, `end`, or `stop` are floating-point, the + `dtype` is inferred to be the default dtype, see + :meth:`~torch.get_default_dtype`. Otherwise, the `dtype` is inferred to + be `torch.int64`. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.arange(5) + tensor([ 0, 1, 2, 3, 4]) + >>> torch.arange(1, 4) + tensor([ 1, 2, 3]) + >>> torch.arange(1, 2.5, 0.5) + tensor([ 1.0000, 1.5000, 2.0000]) + """ + +@overload +def arange( + start: Number | _complex, + end: Number | _complex, + step: Number | _complex = 1, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + arange(start=0, end, step=1, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a 1-D tensor of size :math:`\left\lceil \frac{\text{end} - \text{start}}{\text{step}} \right\rceil` + with values from the interval ``[start, end)`` taken with common difference + :attr:`step` beginning from `start`. + + Note: When using floating-point dtypes (especially reduced precision types like ``bfloat16``), + the results may be affected by floating-point rounding behavior. Some values in the sequence + might not be exactly representable in certain floating-point formats, which can lead to + repeated values or unexpected rounding. For precise sequences, it is recommended to use + integer dtypes instead of floating-point dtypes. + + Note that non-integer :attr:`step` is subject to floating point rounding errors when + comparing against :attr:`end`; to avoid inconsistency, we advise subtracting a small epsilon from :attr:`end` + in such cases. + + .. math:: + \text{out}_{{i+1}} = \text{out}_{i} + \text{step} + + Args: + start (Number, optional): the starting value for the set of points. Default: ``0``. + end (Number): the ending value for the set of points + step (Number, optional): the gap between each pair of adjacent points. Default: ``1``. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). If `dtype` is not given, infer the data type from the other input + arguments. If any of `start`, `end`, or `stop` are floating-point, the + `dtype` is inferred to be the default dtype, see + :meth:`~torch.get_default_dtype`. Otherwise, the `dtype` is inferred to + be `torch.int64`. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.arange(5) + tensor([ 0, 1, 2, 3, 4]) + >>> torch.arange(1, 4) + tensor([ 1, 2, 3]) + >>> torch.arange(1, 2.5, 0.5) + tensor([ 1.0000, 1.5000, 2.0000]) + """ + +def arccos(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + arccos(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Alias for :func:`torch.acos`. + """ + +def arccos_(input: Tensor) -> Tensor: ... +def arccosh(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + arccosh(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Alias for :func:`torch.acosh`. + """ + +def arccosh_(input: Tensor) -> Tensor: ... +def arcsin(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + arcsin(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Alias for :func:`torch.asin`. + """ + +def arcsin_(input: Tensor) -> Tensor: ... +def arcsinh(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + arcsinh(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Alias for :func:`torch.asinh`. + """ + +def arcsinh_(input: Tensor) -> Tensor: ... +def arctan(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + arctan(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Alias for :func:`torch.atan`. + """ + +def arctan2( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + arctan2(input: Tensor, other: Tensor, *, out: Optional[Tensor]) -> Tensor + Alias for :func:`torch.atan2`. + """ + +def arctan_(input: Tensor) -> Tensor: ... +def arctanh(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + arctanh(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Alias for :func:`torch.atanh`. + """ + +def arctanh_(input: Tensor) -> Tensor: ... +def argmax( + input: Tensor, + dim: _int | None = None, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + argmax(input) -> LongTensor + + Returns the indices of the maximum value of all elements in the :attr:`input` tensor. + + This is the second value returned by :meth:`torch.max`. See its + documentation for the exact semantics of this method. + + .. note:: If there are multiple maximal values then the indices of the first maximal value are returned. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 1.3398, 0.2663, -0.2686, 0.2450], + [-0.7401, -0.8805, -0.3402, -1.1936], + [ 0.4907, -1.3948, -1.0691, -0.3132], + [-1.6092, 0.5419, -0.2993, 0.3195]]) + >>> torch.argmax(a) + tensor(0) + + .. function:: argmax(input, dim, keepdim=False) -> LongTensor + :noindex: + + Returns the indices of the maximum values of a tensor across a dimension. + + This is the second value returned by :meth:`torch.max`. See its + documentation for the exact semantics of this method. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. + If ``None``, the argmax of the flattened input is returned. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 1.3398, 0.2663, -0.2686, 0.2450], + [-0.7401, -0.8805, -0.3402, -1.1936], + [ 0.4907, -1.3948, -1.0691, -0.3132], + [-1.6092, 0.5419, -0.2993, 0.3195]]) + >>> torch.argmax(a, dim=1) + tensor([ 0, 2, 0, 1]) + """ + +def argmin( + input: Tensor, + dim: _int | None = None, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + argmin(input, dim=None, keepdim=False) -> LongTensor + + Returns the indices of the minimum value(s) of the flattened tensor or along a dimension + + This is the second value returned by :meth:`torch.min`. See its + documentation for the exact semantics of this method. + + .. note:: If there are multiple minimal values then the indices of the first minimal value are returned. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. + If ``None``, the argmin of the flattened input is returned. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.1139, 0.2254, -0.1381, 0.3687], + [ 1.0100, -1.1975, -0.0102, -0.4732], + [-0.9240, 0.1207, -0.7506, -1.0213], + [ 1.7809, -1.2960, 0.9384, 0.1438]]) + >>> torch.argmin(a) + tensor(13) + >>> torch.argmin(a, dim=1) + tensor([ 2, 1, 3, 1]) + >>> torch.argmin(a, dim=1, keepdim=True) + tensor([[2], + [1], + [3], + [1]]) + """ + +@overload +def argsort( + input: Tensor, + *, + stable: _bool, + dim: _int = -1, + descending: _bool = False, + out: Tensor | None = None, +) -> Tensor: + r""" + argsort(input, dim=-1, descending=False, *, stable=False) -> Tensor + + Returns the indices that sort a tensor along a given dimension in ascending + order by value. + + This is the second value returned by :meth:`torch.sort`. See its documentation + for the exact semantics of this method. + + If :attr:`stable` is ``True`` then the sorting routine becomes stable, preserving + the order of equivalent elements. If ``False``, the relative order of values + which compare equal is not guaranteed. ``True`` is slower. + + Args: + input (Tensor): the input tensor. + dim (int, optional): the dimension to sort along + descending (bool, optional): controls the sorting order (ascending or descending) + + Keyword args: + stable (bool, optional): controls the relative order of equivalent elements + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.0785, 1.5267, -0.8521, 0.4065], + [ 0.1598, 0.0788, -0.0745, -1.2700], + [ 1.2208, 1.0722, -0.7064, 1.2564], + [ 0.0669, -0.2318, -0.8229, -0.9280]]) + + + >>> torch.argsort(a, dim=1) + tensor([[2, 0, 3, 1], + [3, 2, 1, 0], + [2, 1, 0, 3], + [3, 2, 1, 0]]) + """ + +@overload +def argsort( + input: Tensor, + dim: _int = -1, + descending: _bool = False, +) -> Tensor: + r""" + argsort(input, dim=-1, descending=False, *, stable=False) -> Tensor + + Returns the indices that sort a tensor along a given dimension in ascending + order by value. + + This is the second value returned by :meth:`torch.sort`. See its documentation + for the exact semantics of this method. + + If :attr:`stable` is ``True`` then the sorting routine becomes stable, preserving + the order of equivalent elements. If ``False``, the relative order of values + which compare equal is not guaranteed. ``True`` is slower. + + Args: + input (Tensor): the input tensor. + dim (int, optional): the dimension to sort along + descending (bool, optional): controls the sorting order (ascending or descending) + + Keyword args: + stable (bool, optional): controls the relative order of equivalent elements + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.0785, 1.5267, -0.8521, 0.4065], + [ 0.1598, 0.0788, -0.0745, -1.2700], + [ 1.2208, 1.0722, -0.7064, 1.2564], + [ 0.0669, -0.2318, -0.8229, -0.9280]]) + + + >>> torch.argsort(a, dim=1) + tensor([[2, 0, 3, 1], + [3, 2, 1, 0], + [2, 1, 0, 3], + [3, 2, 1, 0]]) + """ + +@overload +def argsort( + input: Tensor, + dim: str | EllipsisType | None, + descending: _bool = False, +) -> Tensor: + r""" + argsort(input, dim=-1, descending=False, *, stable=False) -> Tensor + + Returns the indices that sort a tensor along a given dimension in ascending + order by value. + + This is the second value returned by :meth:`torch.sort`. See its documentation + for the exact semantics of this method. + + If :attr:`stable` is ``True`` then the sorting routine becomes stable, preserving + the order of equivalent elements. If ``False``, the relative order of values + which compare equal is not guaranteed. ``True`` is slower. + + Args: + input (Tensor): the input tensor. + dim (int, optional): the dimension to sort along + descending (bool, optional): controls the sorting order (ascending or descending) + + Keyword args: + stable (bool, optional): controls the relative order of equivalent elements + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.0785, 1.5267, -0.8521, 0.4065], + [ 0.1598, 0.0788, -0.0745, -1.2700], + [ 1.2208, 1.0722, -0.7064, 1.2564], + [ 0.0669, -0.2318, -0.8229, -0.9280]]) + + + >>> torch.argsort(a, dim=1) + tensor([[2, 0, 3, 1], + [3, 2, 1, 0], + [2, 1, 0, 3], + [3, 2, 1, 0]]) + """ + +def argwhere(input: Tensor) -> Tensor: + r""" + argwhere(input) -> Tensor + + Returns a tensor containing the indices of all non-zero elements of + :attr:`input`. Each row in the result contains the indices of a non-zero + element in :attr:`input`. The result is sorted lexicographically, with + the last index changing the fastest (C-style). + + If :attr:`input` has :math:`n` dimensions, then the resulting indices tensor + :attr:`out` is of size :math:`(z \times n)`, where :math:`z` is the total number of + non-zero elements in the :attr:`input` tensor. + + .. note:: + This function is similar to NumPy's `argwhere`. + + When :attr:`input` is on CUDA, this function causes host-device synchronization. + + Args: + {input} + + Example:: + + >>> t = torch.tensor([1, 0, 1]) + >>> torch.argwhere(t) + tensor([[0], + [2]]) + >>> t = torch.tensor([[1, 0, 1], [0, 1, 1]]) + >>> torch.argwhere(t) + tensor([[0, 0], + [0, 2], + [1, 1], + [1, 2]]) + """ + +def as_strided( + input: Tensor, + size: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + storage_offset: _int | SymInt | None = None, +) -> Tensor: + r""" + as_strided(input, size, stride, storage_offset=None) -> Tensor + + Create a view of an existing `torch.Tensor` :attr:`input` with specified + :attr:`size`, :attr:`stride` and :attr:`storage_offset`. + + .. warning:: + Prefer using other view functions, like :meth:`torch.Tensor.view` or + :meth:`torch.Tensor.expand`, to setting a view's strides manually with + `as_strided`, as this function will throw an error on non-standard Pytorch + backends (that do not have a concept of stride) and the result will depend + on the current layout in memory. The constructed view must only refer to + elements within the Tensor's storage or a runtime error will be thrown. + If the generated view is "overlapped" (with multiple indices referring to + the same element in memory), the behavior of inplace operations on this view + is undefined (and might not throw runtime errors). + + Args: + input (Tensor): the input tensor. + size (tuple or ints): the shape of the output tensor + stride (tuple or ints): the stride of the output tensor + storage_offset (int, optional): the offset in the underlying storage of the output tensor. + If ``None``, the storage_offset of the output tensor will match the input tensor. + + Example:: + + >>> x = torch.randn(3, 3) + >>> x + tensor([[ 0.9039, 0.6291, 1.0795], + [ 0.1586, 2.1939, -0.4900], + [-0.1909, -0.7503, 1.9355]]) + >>> t = torch.as_strided(x, (2, 2), (1, 2)) + >>> t + tensor([[0.9039, 1.0795], + [0.6291, 0.1586]]) + >>> t = torch.as_strided(x, (2, 2), (1, 2), 1) + tensor([[0.6291, 0.1586], + [1.0795, 2.1939]]) + """ + +def as_strided_( + input: Tensor, + size: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + storage_offset: _int | SymInt | None = None, +) -> Tensor: ... +def as_strided_copy( + input: Tensor, + size: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + storage_offset: _int | SymInt | None = None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.as_strided`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def as_strided_scatter( + input: Tensor, + src: Tensor, + size: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + storage_offset: _int | SymInt | None = None, +) -> Tensor: + r""" + as_strided_scatter(input, src, size, stride, storage_offset=None) -> Tensor + + Embeds the values of the :attr:`src` tensor into :attr:`input` along + the elements corresponding to the result of calling + input.as_strided(size, stride, storage_offset). + + This function returns a tensor with fresh storage; it does not + return a view. + + Args: + input (Tensor): the input tensor. + size (tuple or ints): the shape of the output tensor + stride (tuple or ints): the stride of the output tensor + storage_offset (int, optional): the offset in the underlying storage of the output tensor + + .. note:: + + :attr:`src` must be of the proper size in order to be embedded + into :attr:`input`. Specifically, it should have the same shape as + `torch.as_strided(input, size, stride, storage_offset)` + + Example:: + + >>> a = torch.arange(4).reshape(2, 2) + 1 + >>> a + tensor([[1, 2], + [3, 4]]) + >>> b = torch.zeros(3, 3) + >>> b + tensor([[0., 0., 0.], + [0., 0., 0.], + [0., 0., 0.]]) + >>> torch.as_strided_scatter(b, a, (2, 2), (1, 2)) + tensor([[1., 3., 2.], + [4., 0., 0.], + [0., 0., 0.]]) + """ + +def as_tensor( + data: Any, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, +) -> Tensor: + r""" + as_tensor(data: Any, dtype: Optional[dtype] = None, device: Optional[DeviceLikeType]) -> Tensor + + Converts :attr:`data` into a tensor, sharing data and preserving autograd + history if possible. + + If :attr:`data` is already a tensor with the requested dtype and device + then :attr:`data` itself is returned, but if :attr:`data` is a + tensor with a different dtype or device then it's copied as if using + `data.to(dtype=dtype, device=device)`. + + If :attr:`data` is a NumPy array (an ndarray) with the same dtype and device then a + tensor is constructed using :func:`torch.from_numpy`. + + If :attr:`data` is a CuPy array, the returned tensor will be located on the same device as the CuPy array unless + specifically overwritten by :attr:`device` or a default device. The device of the CuPy array is inferred from the + pointer of the array using `cudaPointerGetAttributes` unless :attr:`device` is provided with an explicit device index. + + .. seealso:: + + :func:`torch.tensor` never shares its data and creates a new "leaf tensor" (see :doc:`/notes/autograd`). + + + Args: + data (array_like): Initial data for the tensor. Can be a list, tuple, + NumPy ``ndarray``, scalar, and other types. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, infers data type from :attr:`data`. + device (:class:`torch.device`, optional): the device of the constructed tensor. If None and data is a tensor + then the device of data is used. If None and data is not a tensor then + the result tensor is constructed on the current device. + + + Example:: + + >>> a = numpy.array([1, 2, 3]) + >>> t = torch.as_tensor(a) + >>> t + tensor([ 1, 2, 3]) + >>> t[0] = -1 + >>> a + array([-1, 2, 3]) + + >>> a = numpy.array([1, 2, 3]) + >>> t = torch.as_tensor(a, device=torch.device('cuda')) + >>> t + tensor([ 1, 2, 3]) + >>> t[0] = -1 + >>> a + array([1, 2, 3]) + """ + +def asarray( + obj: Any, + *, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + copy: _bool | None = None, + requires_grad: _bool = False, +) -> Tensor: + r""" + asarray(obj: Any, *, dtype: Optional[dtype], device: Optional[DeviceLikeType], copy: Optional[bool] = None, requires_grad: bool = False) -> Tensor # noqa: B950 + + Converts :attr:`obj` to a tensor. + + :attr:`obj` can be one of: + + 1. a tensor + 2. a NumPy array or a NumPy scalar + 3. a DLPack capsule + 4. an object that implements Python's buffer protocol + 5. a scalar + 6. a sequence of scalars + + When :attr:`obj` is a tensor, NumPy array, or DLPack capsule the returned tensor will, + by default, not require a gradient, have the same datatype as :attr:`obj`, be on the + same device, and share memory with it. These properties can be controlled with the + :attr:`dtype`, :attr:`device`, :attr:`copy`, and :attr:`requires_grad` keyword arguments. + If the returned tensor is of a different datatype, on a different device, or a copy is + requested then it will not share its memory with :attr:`obj`. If :attr:`requires_grad` + is ``True`` then the returned tensor will require a gradient, and if :attr:`obj` is + also a tensor with an autograd history then the returned tensor will have the same history. + + When :attr:`obj` is not a tensor, NumPy array, or DLPack capsule but implements Python's + buffer protocol then the buffer is interpreted as an array of bytes grouped according to + the size of the datatype passed to the :attr:`dtype` keyword argument. (If no datatype is + passed then the default floating point datatype is used, instead.) The returned tensor + will have the specified datatype (or default floating point datatype if none is specified) + and, by default, be on the CPU device and share memory with the buffer. + + When :attr:`obj` is a NumPy scalar, the returned tensor will be a 0-dimensional tensor on + the CPU and that doesn't share its memory (i.e. ``copy=True``). By default datatype will + be the PyTorch datatype corresponding to the NumPy's scalar's datatype. + + When :attr:`obj` is none of the above but a scalar, or a sequence of scalars then the + returned tensor will, by default, infer its datatype from the scalar values, be on the + current default device, and not share its memory. + + .. seealso:: + + :func:`torch.tensor` creates a tensor that always copies the data from the input object. + :func:`torch.from_numpy` creates a tensor that always shares memory from NumPy arrays. + :func:`torch.frombuffer` creates a tensor that always shares memory from objects that + implement the buffer protocol. + :func:`torch.from_dlpack` creates a tensor that always shares memory from + DLPack capsules. + + Args: + obj (object): a tensor, NumPy array, DLPack Capsule, object that implements Python's + buffer protocol, scalar, or sequence of scalars. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the datatype of the returned tensor. + Default: ``None``, which causes the datatype of the returned tensor to be + inferred from :attr:`obj`. + copy (bool, optional): controls whether the returned tensor shares memory with :attr:`obj`. + Default: ``None``, which causes the returned tensor to share memory with :attr:`obj` + whenever possible. If ``True`` then the returned tensor does not share its memory. + If ``False`` then the returned tensor shares its memory with :attr:`obj` and an + error is thrown if it cannot. + device (:class:`torch.device`, optional): the device of the returned tensor. + Default: ``None``, which causes the device of :attr:`obj` to be used. Or, if + :attr:`obj` is a Python sequence, the current default device will be used. + requires_grad (bool, optional): whether the returned tensor requires grad. + Default: ``False``, which causes the returned tensor not to require a gradient. + If ``True``, then the returned tensor will require a gradient, and if :attr:`obj` + is also a tensor with an autograd history then the returned tensor will have + the same history. + + Example:: + + >>> a = torch.tensor([1, 2, 3]) + >>> # Shares memory with tensor 'a' + >>> b = torch.asarray(a) + >>> a.data_ptr() == b.data_ptr() + True + >>> # Forces memory copy + >>> c = torch.asarray(a, copy=True) + >>> a.data_ptr() == c.data_ptr() + False + + >>> a = torch.tensor([1., 2., 3.], requires_grad=True) + >>> b = a + 2 + >>> b + tensor([3., 4., 5.], grad_fn=) + >>> # Shares memory with tensor 'b', with no grad + >>> c = torch.asarray(b) + >>> c + tensor([3., 4., 5.]) + >>> # Shares memory with tensor 'b', retaining autograd history + >>> d = torch.asarray(b, requires_grad=True) + >>> d + tensor([3., 4., 5.], grad_fn=) + + >>> array = numpy.array([1, 2, 3]) + >>> # Shares memory with array 'array' + >>> t1 = torch.asarray(array) + >>> array.__array_interface__['data'][0] == t1.data_ptr() + True + >>> # Copies memory due to dtype mismatch + >>> t2 = torch.asarray(array, dtype=torch.float32) + >>> array.__array_interface__['data'][0] == t2.data_ptr() + False + + >>> scalar = numpy.float64(0.5) + >>> torch.asarray(scalar) + tensor(0.5000, dtype=torch.float64) + """ + +def asin(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + asin(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Returns a new tensor with the arcsine of the elements (in radians) in the :attr:`input` tensor. + + .. math:: + \text{out}_{i} = \sin^{-1}(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-0.5962, 1.4985, -0.4396, 1.4525]) + >>> torch.asin(a) + tensor([-0.6387, nan, -0.4552, nan]) + """ + +def asin_(input: Tensor) -> Tensor: ... +def asinh(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + asinh(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Returns a new tensor with the inverse hyperbolic sine of the elements of :attr:`input`. + + .. math:: + \text{out}_{i} = \sinh^{-1}(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword arguments: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.1606, -1.4267, -1.0899, -1.0250 ]) + >>> torch.asinh(a) + tensor([ 0.1599, -1.1534, -0.9435, -0.8990 ]) + """ + +def asinh_(input: Tensor) -> Tensor: ... +def atan(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + atan(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Returns a new tensor with the arctangent of the elements (in radians) in the :attr:`input` tensor. + + .. math:: + \text{out}_{i} = \tan^{-1}(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.2341, 0.2539, -0.6256, -0.6448]) + >>> torch.atan(a) + tensor([ 0.2299, 0.2487, -0.5591, -0.5727]) + """ + +def atan2( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + atan2(input: Tensor, other: Tensor, *, out: Optional[Tensor]) -> Tensor + + Element-wise arctangent of :math:`\text{input}_{i} / \text{other}_{i}` + with consideration of the quadrant. Returns a new tensor with the signed angles + in radians between vector :math:`(\text{other}_{i}, \text{input}_{i})` + and vector :math:`(1, 0)`. (Note that :math:`\text{other}_{i}`, the second + parameter, is the x-coordinate, while :math:`\text{input}_{i}`, the first + parameter, is the y-coordinate.) + + The shapes of ``input`` and ``other`` must be + :ref:`broadcastable `. + + Args: + input (Tensor): the first input tensor + other (Tensor): the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.9041, 0.0196, -0.3108, -2.4423]) + >>> torch.atan2(a, torch.randn(4)) + tensor([ 0.9833, 0.0811, -1.9743, -1.4151]) + """ + +def atan_(input: Tensor) -> Tensor: ... +def atanh(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + atanh(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Returns a new tensor with the inverse hyperbolic tangent of the elements of :attr:`input`. + + Note: + The domain of the inverse hyperbolic tangent is `(-1, 1)` and values outside this range + will be mapped to ``NaN``, except for the values `1` and `-1` for which the output is + mapped to `+/-INF` respectively. + + .. math:: + \text{out}_{i} = \tanh^{-1}(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword arguments: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4).uniform_(-1, 1) + >>> a + tensor([ -0.9385, 0.2968, -0.8591, -0.1871 ]) + >>> torch.atanh(a) + tensor([ -1.7253, 0.3060, -1.2899, -0.1893 ]) + """ + +def atanh_(input: Tensor) -> Tensor: ... +def avg_pool1d( + input: Tensor, + kernel_size: _int | _size, + stride: _int | _size = (), + padding: _int | _size = 0, + ceil_mode: _bool = False, + count_include_pad: _bool = True, +) -> Tensor: ... +@overload +def baddbmm( + beta: Number | _complex, + self: Tensor, + alpha: Number | _complex, + batch1: Tensor, + batch2: Tensor, +) -> Tensor: + r""" + baddbmm(input, batch1, batch2, out_dtype=None, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a batch matrix-matrix product of matrices in :attr:`batch1` + and :attr:`batch2`. + :attr:`input` is added to the final result. + + :attr:`batch1` and :attr:`batch2` must be 3-D tensors each containing the same + number of matrices. + + If :attr:`batch1` is a :math:`(b \times n \times m)` tensor, :attr:`batch2` is a + :math:`(b \times m \times p)` tensor, then :attr:`input` must be + :ref:`broadcastable ` with a + :math:`(b \times n \times p)` tensor and :attr:`out` will be a + :math:`(b \times n \times p)` tensor. Both :attr:`alpha` and :attr:`beta` mean the + same as the scaling factors used in :meth:`torch.addbmm`. + + .. math:: + \text{out}_i = \beta\ \text{input}_i + \alpha\ (\text{batch1}_i \mathbin{@} \text{batch2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): the tensor to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + out_dtype (dtype, optional): the dtype of the output tensor, + Supported only on CUDA and for torch.float32 given + torch.float16/torch.bfloat16 input dtypes + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{batch1} \mathbin{@} \text{batch2}` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(10, 3, 5) + >>> batch1 = torch.randn(10, 3, 4) + >>> batch2 = torch.randn(10, 4, 5) + >>> torch.baddbmm(M, batch1, batch2).size() + torch.Size([10, 3, 5]) + """ + +@overload +def baddbmm( + beta: Number | _complex, + self: Tensor, + alpha: Number | _complex, + batch1: Tensor, + batch2: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + baddbmm(input, batch1, batch2, out_dtype=None, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a batch matrix-matrix product of matrices in :attr:`batch1` + and :attr:`batch2`. + :attr:`input` is added to the final result. + + :attr:`batch1` and :attr:`batch2` must be 3-D tensors each containing the same + number of matrices. + + If :attr:`batch1` is a :math:`(b \times n \times m)` tensor, :attr:`batch2` is a + :math:`(b \times m \times p)` tensor, then :attr:`input` must be + :ref:`broadcastable ` with a + :math:`(b \times n \times p)` tensor and :attr:`out` will be a + :math:`(b \times n \times p)` tensor. Both :attr:`alpha` and :attr:`beta` mean the + same as the scaling factors used in :meth:`torch.addbmm`. + + .. math:: + \text{out}_i = \beta\ \text{input}_i + \alpha\ (\text{batch1}_i \mathbin{@} \text{batch2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): the tensor to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + out_dtype (dtype, optional): the dtype of the output tensor, + Supported only on CUDA and for torch.float32 given + torch.float16/torch.bfloat16 input dtypes + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{batch1} \mathbin{@} \text{batch2}` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(10, 3, 5) + >>> batch1 = torch.randn(10, 3, 4) + >>> batch2 = torch.randn(10, 4, 5) + >>> torch.baddbmm(M, batch1, batch2).size() + torch.Size([10, 3, 5]) + """ + +@overload +def baddbmm( + input: Tensor, + batch1: Tensor, + batch2: Tensor, + *, + beta: Number | _complex = 1, + alpha: Number | _complex = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + baddbmm(input, batch1, batch2, out_dtype=None, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a batch matrix-matrix product of matrices in :attr:`batch1` + and :attr:`batch2`. + :attr:`input` is added to the final result. + + :attr:`batch1` and :attr:`batch2` must be 3-D tensors each containing the same + number of matrices. + + If :attr:`batch1` is a :math:`(b \times n \times m)` tensor, :attr:`batch2` is a + :math:`(b \times m \times p)` tensor, then :attr:`input` must be + :ref:`broadcastable ` with a + :math:`(b \times n \times p)` tensor and :attr:`out` will be a + :math:`(b \times n \times p)` tensor. Both :attr:`alpha` and :attr:`beta` mean the + same as the scaling factors used in :meth:`torch.addbmm`. + + .. math:: + \text{out}_i = \beta\ \text{input}_i + \alpha\ (\text{batch1}_i \mathbin{@} \text{batch2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): the tensor to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + out_dtype (dtype, optional): the dtype of the output tensor, + Supported only on CUDA and for torch.float32 given + torch.float16/torch.bfloat16 input dtypes + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{batch1} \mathbin{@} \text{batch2}` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(10, 3, 5) + >>> batch1 = torch.randn(10, 3, 4) + >>> batch2 = torch.randn(10, 4, 5) + >>> torch.baddbmm(M, batch1, batch2).size() + torch.Size([10, 3, 5]) + """ + +@overload +def baddbmm( + input: Tensor, + batch1: Tensor, + batch2: Tensor, + out_dtype: _dtype, + *, + beta: Number | _complex = 1, + alpha: Number | _complex = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + baddbmm(input, batch1, batch2, out_dtype=None, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a batch matrix-matrix product of matrices in :attr:`batch1` + and :attr:`batch2`. + :attr:`input` is added to the final result. + + :attr:`batch1` and :attr:`batch2` must be 3-D tensors each containing the same + number of matrices. + + If :attr:`batch1` is a :math:`(b \times n \times m)` tensor, :attr:`batch2` is a + :math:`(b \times m \times p)` tensor, then :attr:`input` must be + :ref:`broadcastable ` with a + :math:`(b \times n \times p)` tensor and :attr:`out` will be a + :math:`(b \times n \times p)` tensor. Both :attr:`alpha` and :attr:`beta` mean the + same as the scaling factors used in :meth:`torch.addbmm`. + + .. math:: + \text{out}_i = \beta\ \text{input}_i + \alpha\ (\text{batch1}_i \mathbin{@} \text{batch2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): the tensor to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + out_dtype (dtype, optional): the dtype of the output tensor, + Supported only on CUDA and for torch.float32 given + torch.float16/torch.bfloat16 input dtypes + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{batch1} \mathbin{@} \text{batch2}` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(10, 3, 5) + >>> batch1 = torch.randn(10, 3, 4) + >>> batch2 = torch.randn(10, 4, 5) + >>> torch.baddbmm(M, batch1, batch2).size() + torch.Size([10, 3, 5]) + """ + +@overload +def baddbmm( + beta: Number | _complex, + self: Tensor, + batch1: Tensor, + batch2: Tensor, +) -> Tensor: + r""" + baddbmm(input, batch1, batch2, out_dtype=None, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a batch matrix-matrix product of matrices in :attr:`batch1` + and :attr:`batch2`. + :attr:`input` is added to the final result. + + :attr:`batch1` and :attr:`batch2` must be 3-D tensors each containing the same + number of matrices. + + If :attr:`batch1` is a :math:`(b \times n \times m)` tensor, :attr:`batch2` is a + :math:`(b \times m \times p)` tensor, then :attr:`input` must be + :ref:`broadcastable ` with a + :math:`(b \times n \times p)` tensor and :attr:`out` will be a + :math:`(b \times n \times p)` tensor. Both :attr:`alpha` and :attr:`beta` mean the + same as the scaling factors used in :meth:`torch.addbmm`. + + .. math:: + \text{out}_i = \beta\ \text{input}_i + \alpha\ (\text{batch1}_i \mathbin{@} \text{batch2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): the tensor to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + out_dtype (dtype, optional): the dtype of the output tensor, + Supported only on CUDA and for torch.float32 given + torch.float16/torch.bfloat16 input dtypes + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{batch1} \mathbin{@} \text{batch2}` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(10, 3, 5) + >>> batch1 = torch.randn(10, 3, 4) + >>> batch2 = torch.randn(10, 4, 5) + >>> torch.baddbmm(M, batch1, batch2).size() + torch.Size([10, 3, 5]) + """ + +@overload +def baddbmm( + beta: Number | _complex, + self: Tensor, + batch1: Tensor, + batch2: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + baddbmm(input, batch1, batch2, out_dtype=None, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a batch matrix-matrix product of matrices in :attr:`batch1` + and :attr:`batch2`. + :attr:`input` is added to the final result. + + :attr:`batch1` and :attr:`batch2` must be 3-D tensors each containing the same + number of matrices. + + If :attr:`batch1` is a :math:`(b \times n \times m)` tensor, :attr:`batch2` is a + :math:`(b \times m \times p)` tensor, then :attr:`input` must be + :ref:`broadcastable ` with a + :math:`(b \times n \times p)` tensor and :attr:`out` will be a + :math:`(b \times n \times p)` tensor. Both :attr:`alpha` and :attr:`beta` mean the + same as the scaling factors used in :meth:`torch.addbmm`. + + .. math:: + \text{out}_i = \beta\ \text{input}_i + \alpha\ (\text{batch1}_i \mathbin{@} \text{batch2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): the tensor to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + out_dtype (dtype, optional): the dtype of the output tensor, + Supported only on CUDA and for torch.float32 given + torch.float16/torch.bfloat16 input dtypes + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{batch1} \mathbin{@} \text{batch2}` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(10, 3, 5) + >>> batch1 = torch.randn(10, 3, 4) + >>> batch2 = torch.randn(10, 4, 5) + >>> torch.baddbmm(M, batch1, batch2).size() + torch.Size([10, 3, 5]) + """ + +@overload +def bartlett_window( + window_length: _int, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + bartlett_window(window_length, periodic=True, *, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Bartlett window function. + + .. math:: + w[n] = 1 - \left| \frac{2n}{N-1} - 1 \right| = \begin{cases} + \frac{2n}{N - 1} & \text{if } 0 \leq n \leq \frac{N - 1}{2} \\ + 2 - \frac{2n}{N - 1} & \text{if } \frac{N - 1}{2} < n < N \\ + \end{cases}, + + where :math:`N` is the full window size. + + The input :attr:`window_length` is a positive integer controlling the + returned window size. :attr:`periodic` flag determines whether the returned + window trims off the last duplicate value from the symmetric window and is + ready to be used as a periodic window with functions like + :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in + above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have + ``torch.bartlett_window(L, periodic=True)`` equal to + ``torch.bartlett_window(L + 1, periodic=False)[:-1])``. + + .. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. + + Arguments: + window_length (int): the size of returned window + periodic (bool, optional): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window + """ + +@overload +def bartlett_window( + window_length: _int, + periodic: _bool, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + bartlett_window(window_length, periodic=True, *, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Bartlett window function. + + .. math:: + w[n] = 1 - \left| \frac{2n}{N-1} - 1 \right| = \begin{cases} + \frac{2n}{N - 1} & \text{if } 0 \leq n \leq \frac{N - 1}{2} \\ + 2 - \frac{2n}{N - 1} & \text{if } \frac{N - 1}{2} < n < N \\ + \end{cases}, + + where :math:`N` is the full window size. + + The input :attr:`window_length` is a positive integer controlling the + returned window size. :attr:`periodic` flag determines whether the returned + window trims off the last duplicate value from the symmetric window and is + ready to be used as a periodic window with functions like + :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in + above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have + ``torch.bartlett_window(L, periodic=True)`` equal to + ``torch.bartlett_window(L + 1, periodic=False)[:-1])``. + + .. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. + + Arguments: + window_length (int): the size of returned window + periodic (bool, optional): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window + """ + +def batch_norm( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + running_mean: Tensor | None, + running_var: Tensor | None, + training: _bool, + momentum: _float, + eps: _float, + cudnn_enabled: _bool, +) -> Tensor: ... +def batch_norm_backward_elemt( + grad_out: Tensor, + input: Tensor, + mean: Tensor, + invstd: Tensor, + weight: Tensor | None, + sum_dy: Tensor, + sum_dy_xmu: Tensor, + count: Tensor, +) -> Tensor: ... +def batch_norm_backward_reduce( + grad_out: Tensor, + input: Tensor, + mean: Tensor, + invstd: Tensor, + weight: Tensor | None, + input_g: _bool, + weight_g: _bool, + bias_g: _bool, +) -> tuple[Tensor, Tensor, Tensor, Tensor]: ... +def batch_norm_elemt( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + mean: Tensor, + invstd: Tensor, + eps: _float, + *, + out: Tensor | None = None, +) -> Tensor: ... +def batch_norm_gather_stats( + input: Tensor, + mean: Tensor, + invstd: Tensor, + running_mean: Tensor | None, + running_var: Tensor | None, + momentum: _float, + eps: _float, + count: _int, +) -> tuple[Tensor, Tensor]: ... +def batch_norm_gather_stats_with_counts( + input: Tensor, + mean: Tensor, + invstd: Tensor, + running_mean: Tensor | None, + running_var: Tensor | None, + momentum: _float, + eps: _float, + counts: Tensor, +) -> tuple[Tensor, Tensor]: ... +def batch_norm_stats(input: Tensor, eps: _float) -> tuple[Tensor, Tensor]: ... +def batch_norm_update_stats( + input: Tensor, + running_mean: Tensor | None, + running_var: Tensor | None, + momentum: _float, +) -> tuple[Tensor, Tensor]: ... +@overload +def bernoulli( + input: Tensor, + *, + generator: Generator | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + bernoulli(input: Tensor, *, generator: Optional[Generator], out: Optional[Tensor]) -> Tensor + + Draws binary random numbers (0 or 1) from a Bernoulli distribution. + + The :attr:`input` tensor should be a tensor containing probabilities + to be used for drawing the binary random number. + Hence, all values in :attr:`input` have to be in the range: + :math:`0 \leq \text{input}_i \leq 1`. + + The :math:`\text{i}^{th}` element of the output tensor will draw a + value :math:`1` according to the :math:`\text{i}^{th}` probability value given + in :attr:`input`. + + .. math:: + \text{out}_{i} \sim \mathrm{Bernoulli}(p = \text{input}_{i}) + + The returned :attr:`out` tensor only has values 0 or 1 and is of the same + shape as :attr:`input`. + + :attr:`out` can have integral ``dtype``, but :attr:`input` must have floating + point ``dtype``. + + Args: + input (Tensor): the input tensor of probability values for the Bernoulli distribution + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.empty(3, 3).uniform_(0, 1) # generate a uniform random matrix with range [0, 1] + >>> a + tensor([[ 0.1737, 0.0950, 0.3609], + [ 0.7148, 0.0289, 0.2676], + [ 0.9456, 0.8937, 0.7202]]) + >>> torch.bernoulli(a) + tensor([[ 1., 0., 0.], + [ 0., 0., 0.], + [ 1., 1., 1.]]) + + >>> a = torch.ones(3, 3) # probability of drawing "1" is 1 + >>> torch.bernoulli(a) + tensor([[ 1., 1., 1.], + [ 1., 1., 1.], + [ 1., 1., 1.]]) + >>> a = torch.zeros(3, 3) # probability of drawing "1" is 0 + >>> torch.bernoulli(a) + tensor([[ 0., 0., 0.], + [ 0., 0., 0.], + [ 0., 0., 0.]]) + """ + +@overload +def bernoulli( + input: Tensor, + p: _float, + *, + generator: Generator | None = None, +) -> Tensor: + r""" + bernoulli(input: Tensor, *, generator: Optional[Generator], out: Optional[Tensor]) -> Tensor + + Draws binary random numbers (0 or 1) from a Bernoulli distribution. + + The :attr:`input` tensor should be a tensor containing probabilities + to be used for drawing the binary random number. + Hence, all values in :attr:`input` have to be in the range: + :math:`0 \leq \text{input}_i \leq 1`. + + The :math:`\text{i}^{th}` element of the output tensor will draw a + value :math:`1` according to the :math:`\text{i}^{th}` probability value given + in :attr:`input`. + + .. math:: + \text{out}_{i} \sim \mathrm{Bernoulli}(p = \text{input}_{i}) + + The returned :attr:`out` tensor only has values 0 or 1 and is of the same + shape as :attr:`input`. + + :attr:`out` can have integral ``dtype``, but :attr:`input` must have floating + point ``dtype``. + + Args: + input (Tensor): the input tensor of probability values for the Bernoulli distribution + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.empty(3, 3).uniform_(0, 1) # generate a uniform random matrix with range [0, 1] + >>> a + tensor([[ 0.1737, 0.0950, 0.3609], + [ 0.7148, 0.0289, 0.2676], + [ 0.9456, 0.8937, 0.7202]]) + >>> torch.bernoulli(a) + tensor([[ 1., 0., 0.], + [ 0., 0., 0.], + [ 1., 1., 1.]]) + + >>> a = torch.ones(3, 3) # probability of drawing "1" is 1 + >>> torch.bernoulli(a) + tensor([[ 1., 1., 1.], + [ 1., 1., 1.], + [ 1., 1., 1.]]) + >>> a = torch.zeros(3, 3) # probability of drawing "1" is 0 + >>> torch.bernoulli(a) + tensor([[ 0., 0., 0.], + [ 0., 0., 0.], + [ 0., 0., 0.]]) + """ + +def bilinear( + input1: Tensor, + input2: Tensor, + weight: Tensor, + bias: Tensor | None = None, +) -> Tensor: ... +def binary_cross_entropy_with_logits( + input: Tensor, + target: Tensor, + weight: Tensor | None = None, + pos_weight: Tensor | None = None, + reduction: _int = 1, +) -> Tensor: ... +def bincount( + input: Tensor, + weights: Tensor | None = None, + minlength: _int | SymInt = 0, +) -> Tensor: + r""" + bincount(input, weights=None, minlength=0) -> Tensor + + Count the frequency of each value in an array of non-negative ints. + + The number of bins (size 1) is one larger than the largest value in + :attr:`input` unless :attr:`input` is empty, in which case the result is a + tensor of size 0. If :attr:`minlength` is specified, the number of bins is at least + :attr:`minlength` and if :attr:`input` is empty, then the result is tensor of size + :attr:`minlength` filled with zeros. If ``n`` is the value at position ``i``, + ``out[n] += weights[i]`` if :attr:`weights` is specified else + ``out[n] += 1``. + + Note: + This operation may produce nondeterministic gradients when given tensors on a CUDA device. See :doc:`/notes/randomness` for more information. + + Arguments: + input (Tensor): 1-d int tensor + weights (Tensor): optional, weight for each value in the input tensor. + Should be of same size as input tensor. + minlength (int): optional, minimum number of bins. Should be non-negative. + + Returns: + output (Tensor): a tensor of shape ``Size([max(input) + 1])`` if + :attr:`input` is non-empty, else ``Size(0)`` + + Example:: + + >>> input = torch.randint(0, 8, (5,), dtype=torch.int64) + >>> weights = torch.linspace(0, 1, steps=5) + >>> input, weights + (tensor([4, 3, 6, 3, 4]), + tensor([ 0.0000, 0.2500, 0.5000, 0.7500, 1.0000]) + + >>> torch.bincount(input) + tensor([0, 0, 0, 2, 2, 0, 1]) + + >>> input.bincount(weights) + tensor([0.0000, 0.0000, 0.0000, 1.0000, 1.0000, 0.0000, 0.5000]) + """ + +def binomial( + count: Tensor, + prob: Tensor, + generator: Generator | None = None, +) -> Tensor: ... +@overload +def bitwise_and( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + bitwise_and(input, other, *, out=None) -> Tensor + + Computes the bitwise AND of :attr:`input` and :attr:`other`. The input tensor must be of + integral or Boolean types. For bool tensors, it computes the logical AND. + + Args: + input: the first input tensor + other: the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_and(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([1, 0, 3], dtype=torch.int8) + >>> torch.bitwise_and(torch.tensor([True, True, False]), torch.tensor([False, True, False])) + tensor([ False, True, False]) + """ + +@overload +def bitwise_and(self: Number | _complex, other: Tensor) -> Tensor: + r""" + bitwise_and(input, other, *, out=None) -> Tensor + + Computes the bitwise AND of :attr:`input` and :attr:`other`. The input tensor must be of + integral or Boolean types. For bool tensors, it computes the logical AND. + + Args: + input: the first input tensor + other: the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_and(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([1, 0, 3], dtype=torch.int8) + >>> torch.bitwise_and(torch.tensor([True, True, False]), torch.tensor([False, True, False])) + tensor([ False, True, False]) + """ + +@overload +def bitwise_and( + input: Tensor, + other: Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + bitwise_and(input, other, *, out=None) -> Tensor + + Computes the bitwise AND of :attr:`input` and :attr:`other`. The input tensor must be of + integral or Boolean types. For bool tensors, it computes the logical AND. + + Args: + input: the first input tensor + other: the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_and(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([1, 0, 3], dtype=torch.int8) + >>> torch.bitwise_and(torch.tensor([True, True, False]), torch.tensor([False, True, False])) + tensor([ False, True, False]) + """ + +@overload +def bitwise_left_shift( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + bitwise_left_shift(input, other, *, out=None) -> Tensor + + Computes the left arithmetic shift of :attr:`input` by :attr:`other` bits. + The input tensor must be of integral type. This operator supports + :ref:`broadcasting to a common shape ` and + :ref:`type promotion `. + + The operation applied is: + + .. math:: + \text{out}_i = \text{input}_i << \text{other}_i + + Args: + input (Tensor or Scalar): the first input tensor + other (Tensor or Scalar): the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_left_shift(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-2, -2, 24], dtype=torch.int8) + """ + +@overload +def bitwise_left_shift(self: Number | _complex, other: Tensor) -> Tensor: + r""" + bitwise_left_shift(input, other, *, out=None) -> Tensor + + Computes the left arithmetic shift of :attr:`input` by :attr:`other` bits. + The input tensor must be of integral type. This operator supports + :ref:`broadcasting to a common shape ` and + :ref:`type promotion `. + + The operation applied is: + + .. math:: + \text{out}_i = \text{input}_i << \text{other}_i + + Args: + input (Tensor or Scalar): the first input tensor + other (Tensor or Scalar): the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_left_shift(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-2, -2, 24], dtype=torch.int8) + """ + +@overload +def bitwise_left_shift( + input: Tensor, + other: Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + bitwise_left_shift(input, other, *, out=None) -> Tensor + + Computes the left arithmetic shift of :attr:`input` by :attr:`other` bits. + The input tensor must be of integral type. This operator supports + :ref:`broadcasting to a common shape ` and + :ref:`type promotion `. + + The operation applied is: + + .. math:: + \text{out}_i = \text{input}_i << \text{other}_i + + Args: + input (Tensor or Scalar): the first input tensor + other (Tensor or Scalar): the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_left_shift(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-2, -2, 24], dtype=torch.int8) + """ + +def bitwise_not(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + bitwise_not(input, *, out=None) -> Tensor + + Computes the bitwise NOT of the given input tensor. The input tensor must be of + integral or Boolean types. For bool tensors, it computes the logical NOT. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_not(torch.tensor([-1, -2, 3], dtype=torch.int8)) + tensor([ 0, 1, -4], dtype=torch.int8) + """ + +@overload +def bitwise_or( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + bitwise_or(input: Tensor, other: Tensor, *, out: Optional[Tensor]) -> Tensor + + Computes the bitwise OR of :attr:`input` and :attr:`other`. The input tensor must be of + integral or Boolean types. For bool tensors, it computes the logical OR. + + Args: + input: the first input tensor + other: the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_or(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-1, -2, 3], dtype=torch.int8) + >>> torch.bitwise_or(torch.tensor([True, True, False]), torch.tensor([False, True, False])) + tensor([ True, True, False]) + """ + +@overload +def bitwise_or(self: Number | _complex, other: Tensor) -> Tensor: + r""" + bitwise_or(input: Tensor, other: Tensor, *, out: Optional[Tensor]) -> Tensor + + Computes the bitwise OR of :attr:`input` and :attr:`other`. The input tensor must be of + integral or Boolean types. For bool tensors, it computes the logical OR. + + Args: + input: the first input tensor + other: the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_or(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-1, -2, 3], dtype=torch.int8) + >>> torch.bitwise_or(torch.tensor([True, True, False]), torch.tensor([False, True, False])) + tensor([ True, True, False]) + """ + +@overload +def bitwise_or( + input: Tensor, + other: Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + bitwise_or(input: Tensor, other: Tensor, *, out: Optional[Tensor]) -> Tensor + + Computes the bitwise OR of :attr:`input` and :attr:`other`. The input tensor must be of + integral or Boolean types. For bool tensors, it computes the logical OR. + + Args: + input: the first input tensor + other: the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_or(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-1, -2, 3], dtype=torch.int8) + >>> torch.bitwise_or(torch.tensor([True, True, False]), torch.tensor([False, True, False])) + tensor([ True, True, False]) + """ + +@overload +def bitwise_right_shift( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + bitwise_right_shift(input, other, *, out=None) -> Tensor + + Computes the right arithmetic shift of :attr:`input` by :attr:`other` bits. + The input tensor must be of integral type. This operator supports + :ref:`broadcasting to a common shape ` and + :ref:`type promotion `. + In any case, if the value of the right operand is negative or is greater + or equal to the number of bits in the promoted left operand, the behavior is undefined. + + The operation applied is: + + .. math:: + \text{out}_i = \text{input}_i >> \text{other}_i + + Args: + input (Tensor or Scalar): the first input tensor + other (Tensor or Scalar): the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_right_shift(torch.tensor([-2, -7, 31], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-1, -7, 3], dtype=torch.int8) + """ + +@overload +def bitwise_right_shift(self: Number | _complex, other: Tensor) -> Tensor: + r""" + bitwise_right_shift(input, other, *, out=None) -> Tensor + + Computes the right arithmetic shift of :attr:`input` by :attr:`other` bits. + The input tensor must be of integral type. This operator supports + :ref:`broadcasting to a common shape ` and + :ref:`type promotion `. + In any case, if the value of the right operand is negative or is greater + or equal to the number of bits in the promoted left operand, the behavior is undefined. + + The operation applied is: + + .. math:: + \text{out}_i = \text{input}_i >> \text{other}_i + + Args: + input (Tensor or Scalar): the first input tensor + other (Tensor or Scalar): the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_right_shift(torch.tensor([-2, -7, 31], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-1, -7, 3], dtype=torch.int8) + """ + +@overload +def bitwise_right_shift( + input: Tensor, + other: Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + bitwise_right_shift(input, other, *, out=None) -> Tensor + + Computes the right arithmetic shift of :attr:`input` by :attr:`other` bits. + The input tensor must be of integral type. This operator supports + :ref:`broadcasting to a common shape ` and + :ref:`type promotion `. + In any case, if the value of the right operand is negative or is greater + or equal to the number of bits in the promoted left operand, the behavior is undefined. + + The operation applied is: + + .. math:: + \text{out}_i = \text{input}_i >> \text{other}_i + + Args: + input (Tensor or Scalar): the first input tensor + other (Tensor or Scalar): the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_right_shift(torch.tensor([-2, -7, 31], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-1, -7, 3], dtype=torch.int8) + """ + +@overload +def bitwise_xor( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + bitwise_xor(input, other, *, out=None) -> Tensor + + Computes the bitwise XOR of :attr:`input` and :attr:`other`. The input tensor must be of + integral or Boolean types. For bool tensors, it computes the logical XOR. + + Args: + input: the first input tensor + other: the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_xor(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-2, -2, 0], dtype=torch.int8) + >>> torch.bitwise_xor(torch.tensor([True, True, False]), torch.tensor([False, True, False])) + tensor([ True, False, False]) + """ + +@overload +def bitwise_xor(self: Number | _complex, other: Tensor) -> Tensor: + r""" + bitwise_xor(input, other, *, out=None) -> Tensor + + Computes the bitwise XOR of :attr:`input` and :attr:`other`. The input tensor must be of + integral or Boolean types. For bool tensors, it computes the logical XOR. + + Args: + input: the first input tensor + other: the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_xor(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-2, -2, 0], dtype=torch.int8) + >>> torch.bitwise_xor(torch.tensor([True, True, False]), torch.tensor([False, True, False])) + tensor([ True, False, False]) + """ + +@overload +def bitwise_xor( + input: Tensor, + other: Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + bitwise_xor(input, other, *, out=None) -> Tensor + + Computes the bitwise XOR of :attr:`input` and :attr:`other`. The input tensor must be of + integral or Boolean types. For bool tensors, it computes the logical XOR. + + Args: + input: the first input tensor + other: the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_xor(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-2, -2, 0], dtype=torch.int8) + >>> torch.bitwise_xor(torch.tensor([True, True, False]), torch.tensor([False, True, False])) + tensor([ True, False, False]) + """ + +@overload +def blackman_window( + window_length: _int, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + blackman_window(window_length, periodic=True, *, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Blackman window function. + + .. math:: + w[n] = 0.42 - 0.5 \cos \left( \frac{2 \pi n}{N - 1} \right) + 0.08 \cos \left( \frac{4 \pi n}{N - 1} \right) + + where :math:`N` is the full window size. + + The input :attr:`window_length` is a positive integer controlling the + returned window size. :attr:`periodic` flag determines whether the returned + window trims off the last duplicate value from the symmetric window and is + ready to be used as a periodic window with functions like + :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in + above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have + ``torch.blackman_window(L, periodic=True)`` equal to + ``torch.blackman_window(L + 1, periodic=False)[:-1]``. + + .. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. + + Arguments: + window_length (int): the size of returned window + periodic (bool, optional): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window + """ + +@overload +def blackman_window( + window_length: _int, + periodic: _bool, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + blackman_window(window_length, periodic=True, *, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Blackman window function. + + .. math:: + w[n] = 0.42 - 0.5 \cos \left( \frac{2 \pi n}{N - 1} \right) + 0.08 \cos \left( \frac{4 \pi n}{N - 1} \right) + + where :math:`N` is the full window size. + + The input :attr:`window_length` is a positive integer controlling the + returned window size. :attr:`periodic` flag determines whether the returned + window trims off the last duplicate value from the symmetric window and is + ready to be used as a periodic window with functions like + :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in + above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have + ``torch.blackman_window(L, periodic=True)`` equal to + ``torch.blackman_window(L + 1, periodic=False)[:-1]``. + + .. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. + + Arguments: + window_length (int): the size of returned window + periodic (bool, optional): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window + """ + +@overload +def bmm( + input: Tensor, + mat2: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + bmm(input, mat2, out_dtype=None, *, out=None) -> Tensor + + Performs a batch matrix-matrix product of matrices stored in :attr:`input` + and :attr:`mat2`. + + :attr:`input` and :attr:`mat2` must be 3-D tensors each containing + the same number of matrices. + + If :attr:`input` is a :math:`(b \times n \times m)` tensor, :attr:`mat2` is a + :math:`(b \times m \times p)` tensor, :attr:`out` will be a + :math:`(b \times n \times p)` tensor. + + .. math:: + \text{out}_i = \text{input}_i \mathbin{@} \text{mat2}_i + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + .. note:: This function does not :ref:`broadcast `. + For broadcasting matrix products, see :func:`torch.matmul`. + + Args: + input (Tensor): the first batch of matrices to be multiplied + mat2 (Tensor): the second batch of matrices to be multiplied + out_dtype (dtype, optional): the dtype of the output tensor, + Supported only on CUDA and for torch.float32 given + torch.float16/torch.bfloat16 input dtypes + + Keyword Args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> input = torch.randn(10, 3, 4) + >>> mat2 = torch.randn(10, 4, 5) + >>> res = torch.bmm(input, mat2) + >>> res.size() + torch.Size([10, 3, 5]) + """ + +@overload +def bmm( + input: Tensor, + mat2: Tensor, + out_dtype: _dtype, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + bmm(input, mat2, out_dtype=None, *, out=None) -> Tensor + + Performs a batch matrix-matrix product of matrices stored in :attr:`input` + and :attr:`mat2`. + + :attr:`input` and :attr:`mat2` must be 3-D tensors each containing + the same number of matrices. + + If :attr:`input` is a :math:`(b \times n \times m)` tensor, :attr:`mat2` is a + :math:`(b \times m \times p)` tensor, :attr:`out` will be a + :math:`(b \times n \times p)` tensor. + + .. math:: + \text{out}_i = \text{input}_i \mathbin{@} \text{mat2}_i + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + .. note:: This function does not :ref:`broadcast `. + For broadcasting matrix products, see :func:`torch.matmul`. + + Args: + input (Tensor): the first batch of matrices to be multiplied + mat2 (Tensor): the second batch of matrices to be multiplied + out_dtype (dtype, optional): the dtype of the output tensor, + Supported only on CUDA and for torch.float32 given + torch.float16/torch.bfloat16 input dtypes + + Keyword Args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> input = torch.randn(10, 3, 4) + >>> mat2 = torch.randn(10, 4, 5) + >>> res = torch.bmm(input, mat2) + >>> res.size() + torch.Size([10, 3, 5]) + """ + +def broadcast_to(input: Tensor, size: Sequence[_int | SymInt]) -> Tensor: + r""" + broadcast_to(input, shape) -> Tensor + + Broadcasts :attr:`input` to the shape :attr:`\shape`. + Equivalent to calling ``input.expand(shape)``. See :meth:`~Tensor.expand` for details. + + Args: + input (Tensor): the input tensor. + shape (list, tuple, or :class:`torch.Size`): the new shape. + + Example:: + + >>> x = torch.tensor([1, 2, 3]) + >>> torch.broadcast_to(x, (3, 3)) + tensor([[1, 2, 3], + [1, 2, 3], + [1, 2, 3]]) + """ + +@overload +def bucketize( + input: Tensor, + boundaries: Tensor, + *, + out_int32: _bool = False, + right: _bool = False, + out: Tensor | None = None, +) -> Tensor: + r""" + bucketize(input, boundaries, *, out_int32=False, right=False, out=None) -> Tensor + + Returns the indices of the buckets to which each value in the :attr:`input` belongs, where the + boundaries of the buckets are set by :attr:`boundaries`. Return a new tensor with the same size + as :attr:`input`. If :attr:`right` is False (default), then the left boundary is open. Note that + this behavior is opposite the behavior of + `numpy.digitize `_. + More formally, the returned index satisfies the following rules: + + .. list-table:: + :widths: 15 85 + :header-rows: 1 + + * - :attr:`right` + - *returned index satisfies* + * - False + - ``boundaries[i-1] < input[m][n]...[l][x] <= boundaries[i]`` + * - True + - ``boundaries[i-1] <= input[m][n]...[l][x] < boundaries[i]`` + + Args: + input (Tensor or Scalar): N-D tensor or a Scalar containing the search value(s). + boundaries (Tensor): 1-D tensor, must contain a strictly increasing sequence, or the return value is undefined. + + Keyword args: + out_int32 (bool, optional): indicate the output data type. torch.int32 if True, torch.int64 otherwise. + Default value is False, i.e. default output data type is torch.int64. + right (bool, optional): determines the behavior for values in :attr:`boundaries`. See the table above. + out (Tensor, optional): the output tensor, must be the same size as :attr:`input` if provided. + + + Example:: + + >>> boundaries = torch.tensor([1, 3, 5, 7, 9]) + >>> boundaries + tensor([1, 3, 5, 7, 9]) + >>> v = torch.tensor([[3, 6, 9], [3, 6, 9]]) + >>> v + tensor([[3, 6, 9], + [3, 6, 9]]) + >>> torch.bucketize(v, boundaries) + tensor([[1, 3, 4], + [1, 3, 4]]) + >>> torch.bucketize(v, boundaries, right=True) + tensor([[2, 3, 5], + [2, 3, 5]]) + """ + +@overload +def bucketize( + self: Number | _complex, + boundaries: Tensor, + *, + out_int32: _bool = False, + right: _bool = False, +) -> Tensor: + r""" + bucketize(input, boundaries, *, out_int32=False, right=False, out=None) -> Tensor + + Returns the indices of the buckets to which each value in the :attr:`input` belongs, where the + boundaries of the buckets are set by :attr:`boundaries`. Return a new tensor with the same size + as :attr:`input`. If :attr:`right` is False (default), then the left boundary is open. Note that + this behavior is opposite the behavior of + `numpy.digitize `_. + More formally, the returned index satisfies the following rules: + + .. list-table:: + :widths: 15 85 + :header-rows: 1 + + * - :attr:`right` + - *returned index satisfies* + * - False + - ``boundaries[i-1] < input[m][n]...[l][x] <= boundaries[i]`` + * - True + - ``boundaries[i-1] <= input[m][n]...[l][x] < boundaries[i]`` + + Args: + input (Tensor or Scalar): N-D tensor or a Scalar containing the search value(s). + boundaries (Tensor): 1-D tensor, must contain a strictly increasing sequence, or the return value is undefined. + + Keyword args: + out_int32 (bool, optional): indicate the output data type. torch.int32 if True, torch.int64 otherwise. + Default value is False, i.e. default output data type is torch.int64. + right (bool, optional): determines the behavior for values in :attr:`boundaries`. See the table above. + out (Tensor, optional): the output tensor, must be the same size as :attr:`input` if provided. + + + Example:: + + >>> boundaries = torch.tensor([1, 3, 5, 7, 9]) + >>> boundaries + tensor([1, 3, 5, 7, 9]) + >>> v = torch.tensor([[3, 6, 9], [3, 6, 9]]) + >>> v + tensor([[3, 6, 9], + [3, 6, 9]]) + >>> torch.bucketize(v, boundaries) + tensor([[1, 3, 4], + [1, 3, 4]]) + >>> torch.bucketize(v, boundaries, right=True) + tensor([[2, 3, 5], + [2, 3, 5]]) + """ + +def can_cast(from_: _dtype, to: _dtype) -> _bool: + r""" + can_cast(from_, to) -> bool + + Determines if a type conversion is allowed under PyTorch casting rules + described in the type promotion :ref:`documentation `. + + Args: + from\_ (dtype): The original :class:`torch.dtype`. + to (dtype): The target :class:`torch.dtype`. + + Example:: + + >>> torch.can_cast(torch.double, torch.float) + True + >>> torch.can_cast(torch.float, torch.int) + False + """ + +@overload +def cat( + tensors: tuple[Tensor, ...] | list[Tensor] | None, + dim: _int = 0, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + cat(tensors, dim=0, *, out=None) -> Tensor + + Concatenates the given sequence of tensors in :attr:`tensors` in the given dimension. + All tensors must either have the same shape (except in the concatenating + dimension) or be a 1-D empty tensor with size ``(0,)``. + + :func:`torch.cat` can be seen as an inverse operation for :func:`torch.split` + and :func:`torch.chunk`. + + :func:`torch.cat` can be best understood via examples. + + .. seealso:: + + :func:`torch.stack` concatenates the given sequence along a new dimension. + + Args: + tensors (sequence of Tensors): Non-empty tensors provided must have the same shape, + except in the cat dimension. + + dim (int, optional): the dimension over which the tensors are concatenated + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> x = torch.randn(2, 3) + >>> x + tensor([[ 0.6580, -1.0969, -0.4614], + [-0.1034, -0.5790, 0.1497]]) + >>> torch.cat((x, x, x), 0) + tensor([[ 0.6580, -1.0969, -0.4614], + [-0.1034, -0.5790, 0.1497], + [ 0.6580, -1.0969, -0.4614], + [-0.1034, -0.5790, 0.1497], + [ 0.6580, -1.0969, -0.4614], + [-0.1034, -0.5790, 0.1497]]) + >>> torch.cat((x, x, x), 1) + tensor([[ 0.6580, -1.0969, -0.4614, 0.6580, -1.0969, -0.4614, 0.6580, + -1.0969, -0.4614], + [-0.1034, -0.5790, 0.1497, -0.1034, -0.5790, 0.1497, -0.1034, + -0.5790, 0.1497]]) + """ + +@overload +def cat( + tensors: tuple[Tensor, ...] | list[Tensor] | None, + dim: str | EllipsisType | None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + cat(tensors, dim=0, *, out=None) -> Tensor + + Concatenates the given sequence of tensors in :attr:`tensors` in the given dimension. + All tensors must either have the same shape (except in the concatenating + dimension) or be a 1-D empty tensor with size ``(0,)``. + + :func:`torch.cat` can be seen as an inverse operation for :func:`torch.split` + and :func:`torch.chunk`. + + :func:`torch.cat` can be best understood via examples. + + .. seealso:: + + :func:`torch.stack` concatenates the given sequence along a new dimension. + + Args: + tensors (sequence of Tensors): Non-empty tensors provided must have the same shape, + except in the cat dimension. + + dim (int, optional): the dimension over which the tensors are concatenated + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> x = torch.randn(2, 3) + >>> x + tensor([[ 0.6580, -1.0969, -0.4614], + [-0.1034, -0.5790, 0.1497]]) + >>> torch.cat((x, x, x), 0) + tensor([[ 0.6580, -1.0969, -0.4614], + [-0.1034, -0.5790, 0.1497], + [ 0.6580, -1.0969, -0.4614], + [-0.1034, -0.5790, 0.1497], + [ 0.6580, -1.0969, -0.4614], + [-0.1034, -0.5790, 0.1497]]) + >>> torch.cat((x, x, x), 1) + tensor([[ 0.6580, -1.0969, -0.4614, 0.6580, -1.0969, -0.4614, 0.6580, + -1.0969, -0.4614], + [-0.1034, -0.5790, 0.1497, -0.1034, -0.5790, 0.1497, -0.1034, + -0.5790, 0.1497]]) + """ + +def ccol_indices_copy( + input: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: ... +def ceil(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + ceil(input, *, out=None) -> Tensor + + Returns a new tensor with the ceil of the elements of :attr:`input`, + the smallest integer greater than or equal to each element. + + For integer inputs, follows the array-api convention of returning a + copy of the input tensor. + + .. math:: + \text{out}_{i} = \left\lceil \text{input}_{i} \right\rceil + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-0.6341, -1.4208, -1.0900, 0.5826]) + >>> torch.ceil(a) + tensor([-0., -1., -1., 1.]) + """ + +def ceil_(input: Tensor) -> Tensor: ... +def celu(input: Tensor, alpha: Number | _complex = 1.0) -> Tensor: ... +def celu_(input: Tensor, alpha: Number | _complex = 1.0) -> Tensor: ... +def channel_shuffle(input: Tensor, groups: _int | SymInt) -> Tensor: ... +def cholesky( + input: Tensor, + upper: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + cholesky(input, upper=False, *, out=None) -> Tensor + + Computes the Cholesky decomposition of a symmetric positive-definite + matrix :math:`A` or for batches of symmetric positive-definite matrices. + + If :attr:`upper` is ``True``, the returned matrix ``U`` is upper-triangular, and + the decomposition has the form: + + .. math:: + + A = U^TU + + If :attr:`upper` is ``False``, the returned matrix ``L`` is lower-triangular, and + the decomposition has the form: + + .. math:: + + A = LL^T + + If :attr:`upper` is ``True``, and :math:`A` is a batch of symmetric positive-definite + matrices, then the returned tensor will be composed of upper-triangular Cholesky factors + of each of the individual matrices. Similarly, when :attr:`upper` is ``False``, the returned + tensor will be composed of lower-triangular Cholesky factors of each of the individual + matrices. + + .. warning:: + + :func:`torch.cholesky` is deprecated in favor of :func:`torch.linalg.cholesky` + and will be removed in a future PyTorch release. + + ``L = torch.cholesky(A)`` should be replaced with + + .. code:: python + + L = torch.linalg.cholesky(A) + + ``U = torch.cholesky(A, upper=True)`` should be replaced with + + .. code:: python + + U = torch.linalg.cholesky(A).mH + + This transform will produce equivalent results for all valid (symmetric positive definite) inputs. + + Args: + input (Tensor): the input tensor :math:`A` of size :math:`(*, n, n)` where `*` is zero or more + batch dimensions consisting of symmetric positive-definite matrices. + upper (bool, optional): flag that indicates whether to return a + upper or lower triangular matrix. Default: ``False`` + + Keyword args: + out (Tensor, optional): the output matrix + + Example:: + + >>> a = torch.randn(3, 3) + >>> a = a @ a.mT + 1e-3 # make symmetric positive-definite + >>> l = torch.cholesky(a) + >>> a + tensor([[ 2.4112, -0.7486, 1.4551], + [-0.7486, 1.3544, 0.1294], + [ 1.4551, 0.1294, 1.6724]]) + >>> l + tensor([[ 1.5528, 0.0000, 0.0000], + [-0.4821, 1.0592, 0.0000], + [ 0.9371, 0.5487, 0.7023]]) + >>> l @ l.mT + tensor([[ 2.4112, -0.7486, 1.4551], + [-0.7486, 1.3544, 0.1294], + [ 1.4551, 0.1294, 1.6724]]) + >>> a = torch.randn(3, 2, 2) # Example for batched input + >>> a = a @ a.mT + 1e-03 # make symmetric positive-definite + >>> l = torch.cholesky(a) + >>> z = l @ l.mT + >>> torch.dist(z, a) + tensor(2.3842e-07) + """ + +def cholesky_inverse( + input: Tensor, + upper: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + cholesky_inverse(L, upper=False, *, out=None) -> Tensor + + Computes the inverse of a complex Hermitian or real symmetric + positive-definite matrix given its Cholesky decomposition. + + Let :math:`A` be a complex Hermitian or real symmetric positive-definite matrix, + and :math:`L` its Cholesky decomposition such that: + + .. math:: + + A = LL^{\text{H}} + + where :math:`L^{\text{H}}` is the conjugate transpose when :math:`L` is complex, + and the transpose when :math:`L` is real-valued. + + Computes the inverse matrix :math:`A^{-1}`. + + Supports input of float, double, cfloat and cdouble dtypes. + Also supports batches of matrices, and if :math:`A` is a batch of matrices + then the output has the same batch dimensions. + + Args: + L (Tensor): tensor of shape `(*, n, n)` where `*` is zero or more batch dimensions + consisting of lower or upper triangular Cholesky decompositions of + symmetric or Hermitian positive-definite matrices. + upper (bool, optional): flag that indicates whether :math:`L` is lower triangular + or upper triangular. Default: ``False`` + + Keyword args: + out (Tensor, optional): output tensor. Ignored if `None`. Default: `None`. + + Example:: + + >>> A = torch.randn(3, 3) + >>> A = A @ A.T + torch.eye(3) * 1e-3 # Creates a symmetric positive-definite matrix + >>> L = torch.linalg.cholesky(A) # Extract Cholesky decomposition + >>> torch.cholesky_inverse(L) + tensor([[ 1.9314, 1.2251, -0.0889], + [ 1.2251, 2.4439, 0.2122], + [-0.0889, 0.2122, 0.1412]]) + >>> A.inverse() + tensor([[ 1.9314, 1.2251, -0.0889], + [ 1.2251, 2.4439, 0.2122], + [-0.0889, 0.2122, 0.1412]]) + + >>> A = torch.randn(3, 2, 2, dtype=torch.complex64) + >>> A = A @ A.mH + torch.eye(2) * 1e-3 # Batch of Hermitian positive-definite matrices + >>> L = torch.linalg.cholesky(A) + >>> torch.dist(torch.inverse(A), torch.cholesky_inverse(L)) + tensor(5.6358e-7) + """ + +def cholesky_solve( + input: Tensor, + input2: Tensor, + upper: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + cholesky_solve(B, L, upper=False, *, out=None) -> Tensor + + Computes the solution of a system of linear equations with complex Hermitian + or real symmetric positive-definite lhs given its Cholesky decomposition. + + Let :math:`A` be a complex Hermitian or real symmetric positive-definite matrix, + and :math:`L` its Cholesky decomposition such that: + + .. math:: + + A = LL^{\text{H}} + + where :math:`L^{\text{H}}` is the conjugate transpose when :math:`L` is complex, + and the transpose when :math:`L` is real-valued. + + Returns the solution :math:`X` of the following linear system: + + .. math:: + + AX = B + + Supports inputs of float, double, cfloat and cdouble dtypes. + Also supports batches of matrices, and if :math:`A` or :math:`B` is a batch of matrices + then the output has the same batch dimensions. + + Args: + B (Tensor): right-hand side tensor of shape `(*, n, k)` + where :math:`*` is zero or more batch dimensions + L (Tensor): tensor of shape `(*, n, n)` where `*` is zero or more batch dimensions + consisting of lower or upper triangular Cholesky decompositions of + symmetric or Hermitian positive-definite matrices. + upper (bool, optional): flag that indicates whether :math:`L` is lower triangular + or upper triangular. Default: ``False``. + + Keyword args: + out (Tensor, optional): output tensor. Ignored if `None`. Default: `None`. + + Example:: + + >>> A = torch.randn(3, 3) + >>> A = A @ A.T + torch.eye(3) * 1e-3 # Creates a symmetric positive-definite matrix + >>> L = torch.linalg.cholesky(A) # Extract Cholesky decomposition + >>> B = torch.randn(3, 2) + >>> torch.cholesky_solve(B, L) + tensor([[ -8.1625, 19.6097], + [ -5.8398, 14.2387], + [ -4.3771, 10.4173]]) + >>> A.inverse() @ B + tensor([[ -8.1626, 19.6097], + [ -5.8398, 14.2387], + [ -4.3771, 10.4173]]) + + >>> A = torch.randn(3, 2, 2, dtype=torch.complex64) + >>> A = A @ A.mH + torch.eye(2) * 1e-3 # Batch of Hermitian positive-definite matrices + >>> L = torch.linalg.cholesky(A) + >>> B = torch.randn(2, 1, dtype=torch.complex64) + >>> X = torch.cholesky_solve(B, L) + >>> torch.dist(X, A.inverse() @ B) + tensor(1.6881e-5) + """ + +def choose_qparams_optimized( + input: Tensor, + numel: _int, + n_bins: _int, + ratio: _float, + bit_width: _int, +) -> tuple[Tensor, Tensor]: ... +def chunk(input: Tensor, chunks: _int, dim: _int = 0) -> tuple[Tensor, ...]: + r""" + chunk(input: Tensor, chunks: int, dim: int = 0) -> Tuple[Tensor, ...] + + Attempts to split a tensor into the specified number of chunks. Each chunk is a view of + the input tensor. + + + .. note:: + + This function may return fewer than the specified number of chunks! + + .. seealso:: + + :func:`torch.tensor_split` a function that always returns exactly the specified number of chunks + + If the tensor size along the given dimension :attr:`dim` is divisible by :attr:`chunks`, + all returned chunks will be the same size. + If the tensor size along the given dimension :attr:`dim` is not divisible by :attr:`chunks`, + all returned chunks will be the same size, except the last one. + If such division is not possible, this function may return fewer + than the specified number of chunks. + + Arguments: + input (Tensor): the tensor to split + chunks (int): number of chunks to return + dim (int): dimension along which to split the tensor + + Example: + >>> torch.arange(11).chunk(6) + (tensor([0, 1]), + tensor([2, 3]), + tensor([4, 5]), + tensor([6, 7]), + tensor([8, 9]), + tensor([10])) + >>> torch.arange(12).chunk(6) + (tensor([0, 1]), + tensor([2, 3]), + tensor([4, 5]), + tensor([6, 7]), + tensor([8, 9]), + tensor([10, 11])) + >>> torch.arange(13).chunk(6) + (tensor([0, 1, 2]), + tensor([3, 4, 5]), + tensor([6, 7, 8]), + tensor([ 9, 10, 11]), + tensor([12])) + """ + +@overload +def clamp( + input: Tensor, + min: Tensor | None = None, + max: Tensor | None = None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + clamp(input, min=None, max=None, *, out=None) -> Tensor + + Clamps all elements in :attr:`input` into the range `[` :attr:`min`, :attr:`max` `]`. + Letting min_value and max_value be :attr:`min` and :attr:`max`, respectively, this returns: + + .. math:: + y_i = \min(\max(x_i, \text{min\_value}_i), \text{max\_value}_i) + + If :attr:`min` is ``None``, there is no lower bound. + Or, if :attr:`max` is ``None`` there is no upper bound. + + + .. note:: + If :attr:`min` is greater than :attr:`max` :func:`torch.clamp(..., min, max) ` + sets all elements in :attr:`input` to the value of :attr:`max`. + + Args: + input (Tensor): the input tensor. + min (Number or Tensor, optional): lower-bound of the range to be clamped to + max (Number or Tensor, optional): upper-bound of the range to be clamped to + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-1.7120, 0.1734, -0.0478, -0.0922]) + >>> torch.clamp(a, min=-0.5, max=0.5) + tensor([-0.5000, 0.1734, -0.0478, -0.0922]) + + >>> min = torch.linspace(-1, 1, steps=4) + >>> torch.clamp(a, min=min) + tensor([-1.0000, 0.1734, 0.3333, 1.0000]) + """ + +@overload +def clamp( + input: Tensor, + min: Number | _complex | None = None, + max: Number | _complex | None = None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + clamp(input, min=None, max=None, *, out=None) -> Tensor + + Clamps all elements in :attr:`input` into the range `[` :attr:`min`, :attr:`max` `]`. + Letting min_value and max_value be :attr:`min` and :attr:`max`, respectively, this returns: + + .. math:: + y_i = \min(\max(x_i, \text{min\_value}_i), \text{max\_value}_i) + + If :attr:`min` is ``None``, there is no lower bound. + Or, if :attr:`max` is ``None`` there is no upper bound. + + + .. note:: + If :attr:`min` is greater than :attr:`max` :func:`torch.clamp(..., min, max) ` + sets all elements in :attr:`input` to the value of :attr:`max`. + + Args: + input (Tensor): the input tensor. + min (Number or Tensor, optional): lower-bound of the range to be clamped to + max (Number or Tensor, optional): upper-bound of the range to be clamped to + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-1.7120, 0.1734, -0.0478, -0.0922]) + >>> torch.clamp(a, min=-0.5, max=0.5) + tensor([-0.5000, 0.1734, -0.0478, -0.0922]) + + >>> min = torch.linspace(-1, 1, steps=4) + >>> torch.clamp(a, min=min) + tensor([-1.0000, 0.1734, 0.3333, 1.0000]) + """ + +@overload +def clamp_( + input: Tensor, + min: Tensor | None = None, + max: Tensor | None = None, +) -> Tensor: ... +@overload +def clamp_( + input: Tensor, + min: Number | _complex | None = None, + max: Number | _complex | None = None, +) -> Tensor: ... +@overload +def clamp_max( + input: Tensor, + max: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: ... +@overload +def clamp_max( + input: Tensor, + max: Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: ... +@overload +def clamp_max_(input: Tensor, max: Tensor) -> Tensor: ... +@overload +def clamp_max_(input: Tensor, max: Number | _complex) -> Tensor: ... +@overload +def clamp_min( + input: Tensor, + min: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: ... +@overload +def clamp_min( + input: Tensor, + min: Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: ... +@overload +def clamp_min_(input: Tensor, min: Tensor) -> Tensor: ... +@overload +def clamp_min_(input: Tensor, min: Number | _complex) -> Tensor: ... +@overload +def clip( + input: Tensor, + min: Tensor | None = None, + max: Tensor | None = None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + clip(input, min=None, max=None, *, out=None) -> Tensor + + Alias for :func:`torch.clamp`. + """ + +@overload +def clip( + input: Tensor, + min: Number | _complex | None = None, + max: Number | _complex | None = None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + clip(input, min=None, max=None, *, out=None) -> Tensor + + Alias for :func:`torch.clamp`. + """ + +@overload +def clip_( + input: Tensor, + min: Tensor | None = None, + max: Tensor | None = None, +) -> Tensor: ... +@overload +def clip_( + input: Tensor, + min: Number | _complex | None = None, + max: Number | _complex | None = None, +) -> Tensor: ... +def clone( + input: Tensor, + *, + memory_format: memory_format | None = None, +) -> Tensor: + r""" + clone(input, *, memory_format=torch.preserve_format) -> Tensor + + Returns a copy of :attr:`input`. + + .. note:: + + This function is differentiable, so gradients will flow back from the + result of this operation to :attr:`input`. To create a tensor without an + autograd relationship to :attr:`input` see :meth:`~Tensor.detach`. + + In addition, when ``torch.preserve_format`` is used: + If the input tensor is dense (i.e., non-overlapping strided), + its memory format (including strides) is retained. + Otherwise (e.g., a non-dense view like a stepped slice), + the output is converted to the dense (contiguous) format. + + Args: + input (Tensor): the input tensor. + + Keyword args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned tensor. Default: ``torch.preserve_format``. + """ + +def col_indices_copy(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + Performs the same operation as :func:`torch.col_indices`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def column_stack( + tensors: tuple[Tensor, ...] | list[Tensor] | None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + column_stack(tensors, *, out=None) -> Tensor + + Creates a new tensor by horizontally stacking the tensors in :attr:`tensors`. + + Equivalent to ``torch.hstack(tensors)``, except each zero or one dimensional tensor ``t`` + in :attr:`tensors` is first reshaped into a ``(t.numel(), 1)`` column before being stacked horizontally. + + Args: + tensors (sequence of Tensors): sequence of tensors to concatenate + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([1, 2, 3]) + >>> b = torch.tensor([4, 5, 6]) + >>> torch.column_stack((a, b)) + tensor([[1, 4], + [2, 5], + [3, 6]]) + >>> a = torch.arange(5) + >>> b = torch.arange(10).reshape(5, 2) + >>> torch.column_stack((a, b, b)) + tensor([[0, 0, 1, 0, 1], + [1, 2, 3, 2, 3], + [2, 4, 5, 4, 5], + [3, 6, 7, 6, 7], + [4, 8, 9, 8, 9]]) + """ + +def combinations( + input: Tensor, + r: _int = 2, + with_replacement: _bool = False, +) -> Tensor: + r""" + combinations(input: Tensor, r: int = 2, with_replacement: bool = False) -> seq + + Compute combinations of length :math:`r` of the given tensor. The behavior is similar to + python's `itertools.combinations` when `with_replacement` is set to `False`, and + `itertools.combinations_with_replacement` when `with_replacement` is set to `True`. + + Arguments: + input (Tensor): 1D vector. + r (int, optional): number of elements to combine + with_replacement (bool, optional): whether to allow duplication in combination + + Returns: + Tensor: A tensor equivalent to converting all the input tensors into lists, do + `itertools.combinations` or `itertools.combinations_with_replacement` on these + lists, and finally convert the resulting list into tensor. + + Example:: + + >>> a = [1, 2, 3] + >>> list(itertools.combinations(a, r=2)) + [(1, 2), (1, 3), (2, 3)] + >>> list(itertools.combinations(a, r=3)) + [(1, 2, 3)] + >>> list(itertools.combinations_with_replacement(a, r=2)) + [(1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)] + >>> tensor_a = torch.tensor(a) + >>> torch.combinations(tensor_a) + tensor([[1, 2], + [1, 3], + [2, 3]]) + >>> torch.combinations(tensor_a, r=3) + tensor([[1, 2, 3]]) + >>> torch.combinations(tensor_a, with_replacement=True) + tensor([[1, 1], + [1, 2], + [1, 3], + [2, 2], + [2, 3], + [3, 3]]) + """ + +def complex( + real: Tensor, + imag: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + complex(real, imag, *, out=None) -> Tensor + + Constructs a complex tensor with its real part equal to :attr:`real` and its + imaginary part equal to :attr:`imag`. + + Args: + real (Tensor): The real part of the complex tensor. Must be half, float or double. + imag (Tensor): The imaginary part of the complex tensor. Must be same dtype + as :attr:`real`. + + Keyword args: + out (Tensor): If the inputs are ``torch.float32``, must be + ``torch.complex64``. If the inputs are ``torch.float64``, must be + ``torch.complex128``. + + Example:: + + >>> real = torch.tensor([1, 2], dtype=torch.float32) + >>> imag = torch.tensor([3, 4], dtype=torch.float32) + >>> z = torch.complex(real, imag) + >>> z + tensor([(1.+3.j), (2.+4.j)]) + >>> z.dtype + torch.complex64 + """ + +@overload +def concat( + tensors: tuple[Tensor, ...] | list[Tensor] | None, + dim: _int = 0, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + concat(tensors, dim=0, *, out=None) -> Tensor + + Alias of :func:`torch.cat`. + """ + +@overload +def concat( + tensors: tuple[Tensor, ...] | list[Tensor] | None, + dim: str | EllipsisType | None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + concat(tensors, dim=0, *, out=None) -> Tensor + + Alias of :func:`torch.cat`. + """ + +@overload +def concatenate( + tensors: tuple[Tensor, ...] | list[Tensor] | None, + dim: _int = 0, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + concatenate(tensors, axis=0, out=None) -> Tensor + + Alias of :func:`torch.cat`. + """ + +@overload +def concatenate( + tensors: tuple[Tensor, ...] | list[Tensor] | None, + dim: str | EllipsisType | None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + concatenate(tensors, axis=0, out=None) -> Tensor + + Alias of :func:`torch.cat`. + """ + +def conj(input: Tensor) -> Tensor: + r""" + conj(input) -> Tensor + + Returns a view of :attr:`input` with a flipped conjugate bit. If :attr:`input` has a non-complex dtype, + this function just returns :attr:`input`. + + .. note:: + :func:`torch.conj` performs a lazy conjugation, but the actual conjugated tensor can be materialized + at any time using :func:`torch.resolve_conj`. + + .. warning:: In the future, :func:`torch.conj` may return a non-writeable view for an :attr:`input` of + non-complex dtype. It's recommended that programs not modify the tensor returned by :func:`torch.conj_physical` + when :attr:`input` is of non-complex dtype to be compatible with this change. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> x = torch.tensor([-1 + 1j, -2 + 2j, 3 - 3j]) + >>> x.is_conj() + False + >>> y = torch.conj(x) + >>> y.is_conj() + True + """ + +def conj_physical(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + conj_physical(input, *, out=None) -> Tensor + + Computes the element-wise conjugate of the given :attr:`input` tensor. + If :attr:`input` has a non-complex dtype, this function just returns :attr:`input`. + + .. note:: + This performs the conjugate operation regardless of the fact conjugate bit is set or not. + + .. warning:: In the future, :func:`torch.conj_physical` may return a non-writeable view for an :attr:`input` of + non-complex dtype. It's recommended that programs not modify the tensor returned by :func:`torch.conj_physical` + when :attr:`input` is of non-complex dtype to be compatible with this change. + + .. math:: + \text{out}_{i} = conj(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.conj_physical(torch.tensor([-1 + 1j, -2 + 2j, 3 - 3j])) + tensor([-1 - 1j, -2 - 2j, 3 + 3j]) + """ + +def conj_physical_(input: Tensor) -> Tensor: ... +def constant_pad_nd( + input: Tensor, + pad: Sequence[_int | SymInt], + value: Number | _complex = 0, +) -> Tensor: ... +@overload +def conv1d( + input: Tensor, + weight: Tensor, + bias: Tensor | None = None, + stride: _int | SymInt | Sequence[_int | SymInt] = 1, + padding: _int | SymInt | Sequence[_int | SymInt] = 0, + dilation: _int | SymInt | Sequence[_int | SymInt] = 1, + groups: _int | SymInt = 1, +) -> Tensor: ... +@overload +def conv1d( + input: Tensor, + weight: Tensor, + bias: Tensor | None = None, + stride: _int | SymInt | Sequence[_int | SymInt] = 1, + padding: str = "valid", + dilation: _int | SymInt | Sequence[_int | SymInt] = 1, + groups: _int | SymInt = 1, +) -> Tensor: ... +@overload +def conv2d( + input: Tensor, + weight: Tensor, + bias: Tensor | None = None, + stride: _int | SymInt | Sequence[_int | SymInt] = 1, + padding: _int | SymInt | Sequence[_int | SymInt] = 0, + dilation: _int | SymInt | Sequence[_int | SymInt] = 1, + groups: _int | SymInt = 1, +) -> Tensor: ... +@overload +def conv2d( + input: Tensor, + weight: Tensor, + bias: Tensor | None = None, + stride: _int | SymInt | Sequence[_int | SymInt] = 1, + padding: str = "valid", + dilation: _int | SymInt | Sequence[_int | SymInt] = 1, + groups: _int | SymInt = 1, +) -> Tensor: ... +@overload +def conv3d( + input: Tensor, + weight: Tensor, + bias: Tensor | None = None, + stride: _int | SymInt | Sequence[_int | SymInt] = 1, + padding: _int | SymInt | Sequence[_int | SymInt] = 0, + dilation: _int | SymInt | Sequence[_int | SymInt] = 1, + groups: _int | SymInt = 1, +) -> Tensor: ... +@overload +def conv3d( + input: Tensor, + weight: Tensor, + bias: Tensor | None = None, + stride: _int | SymInt | Sequence[_int | SymInt] = 1, + padding: str = "valid", + dilation: _int | SymInt | Sequence[_int | SymInt] = 1, + groups: _int | SymInt = 1, +) -> Tensor: ... +def conv_tbc( + input: Tensor, + weight: Tensor, + bias: Tensor, + pad: _int = 0, +) -> Tensor: ... +def conv_transpose1d( + input: Tensor, + weight: Tensor, + bias: Tensor | None = None, + stride: _int | SymInt | Sequence[_int | SymInt] = 1, + padding: _int | SymInt | Sequence[_int | SymInt] = 0, + output_padding: _int | SymInt | Sequence[_int | SymInt] = 0, + groups: _int | SymInt = 1, + dilation: _int | SymInt | Sequence[_int | SymInt] = 1, +) -> Tensor: ... +def conv_transpose2d( + input: Tensor, + weight: Tensor, + bias: Tensor | None = None, + stride: _int | SymInt | Sequence[_int | SymInt] = 1, + padding: _int | SymInt | Sequence[_int | SymInt] = 0, + output_padding: _int | SymInt | Sequence[_int | SymInt] = 0, + groups: _int | SymInt = 1, + dilation: _int | SymInt | Sequence[_int | SymInt] = 1, +) -> Tensor: ... +def conv_transpose3d( + input: Tensor, + weight: Tensor, + bias: Tensor | None = None, + stride: _int | SymInt | Sequence[_int | SymInt] = 1, + padding: _int | SymInt | Sequence[_int | SymInt] = 0, + output_padding: _int | SymInt | Sequence[_int | SymInt] = 0, + groups: _int | SymInt = 1, + dilation: _int | SymInt | Sequence[_int | SymInt] = 1, +) -> Tensor: ... +def convolution( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + stride: Sequence[_int | SymInt], + padding: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + transposed: _bool, + output_padding: Sequence[_int | SymInt], + groups: _int | SymInt, +) -> Tensor: ... +@overload +def copysign( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + copysign(input, other, *, out=None) -> Tensor + + Create a new floating-point tensor with the magnitude of :attr:`input` and the sign of :attr:`other`, elementwise. + + .. math:: + \text{out}_{i} = \begin{cases} + -|\text{input}_{i}| & \text{if } \text{other}_{i} \leq -0.0 \\ + |\text{input}_{i}| & \text{if } \text{other}_{i} \geq 0.0 \\ + \end{cases} + + + Supports :ref:`broadcasting to a common shape `, + and integer and float inputs. + + Args: + input (Tensor): magnitudes. + other (Tensor or Number): contains value(s) whose signbit(s) are + applied to the magnitudes in :attr:`input`. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(5) + >>> a + tensor([-1.2557, -0.0026, -0.5387, 0.4740, -0.9244]) + >>> torch.copysign(a, 1) + tensor([1.2557, 0.0026, 0.5387, 0.4740, 0.9244]) + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.7079, 0.2778, -1.0249, 0.5719], + [-0.0059, -0.2600, -0.4475, -1.3948], + [ 0.3667, -0.9567, -2.5757, -0.1751], + [ 0.2046, -0.0742, 0.2998, -0.1054]]) + >>> b = torch.randn(4) + tensor([ 0.2373, 0.3120, 0.3190, -1.1128]) + >>> torch.copysign(a, b) + tensor([[ 0.7079, 0.2778, 1.0249, -0.5719], + [ 0.0059, 0.2600, 0.4475, -1.3948], + [ 0.3667, 0.9567, 2.5757, -0.1751], + [ 0.2046, 0.0742, 0.2998, -0.1054]]) + >>> a = torch.tensor([1.]) + >>> b = torch.tensor([-0.]) + >>> torch.copysign(a, b) + tensor([-1.]) + + .. note:: + copysign handles signed zeros. If the other argument has a negative zero (-0), + the corresponding output value will be negative. + """ + +@overload +def copysign( + input: Tensor, + other: Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + copysign(input, other, *, out=None) -> Tensor + + Create a new floating-point tensor with the magnitude of :attr:`input` and the sign of :attr:`other`, elementwise. + + .. math:: + \text{out}_{i} = \begin{cases} + -|\text{input}_{i}| & \text{if } \text{other}_{i} \leq -0.0 \\ + |\text{input}_{i}| & \text{if } \text{other}_{i} \geq 0.0 \\ + \end{cases} + + + Supports :ref:`broadcasting to a common shape `, + and integer and float inputs. + + Args: + input (Tensor): magnitudes. + other (Tensor or Number): contains value(s) whose signbit(s) are + applied to the magnitudes in :attr:`input`. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(5) + >>> a + tensor([-1.2557, -0.0026, -0.5387, 0.4740, -0.9244]) + >>> torch.copysign(a, 1) + tensor([1.2557, 0.0026, 0.5387, 0.4740, 0.9244]) + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.7079, 0.2778, -1.0249, 0.5719], + [-0.0059, -0.2600, -0.4475, -1.3948], + [ 0.3667, -0.9567, -2.5757, -0.1751], + [ 0.2046, -0.0742, 0.2998, -0.1054]]) + >>> b = torch.randn(4) + tensor([ 0.2373, 0.3120, 0.3190, -1.1128]) + >>> torch.copysign(a, b) + tensor([[ 0.7079, 0.2778, 1.0249, -0.5719], + [ 0.0059, 0.2600, 0.4475, -1.3948], + [ 0.3667, 0.9567, 2.5757, -0.1751], + [ 0.2046, 0.0742, 0.2998, -0.1054]]) + >>> a = torch.tensor([1.]) + >>> b = torch.tensor([-0.]) + >>> torch.copysign(a, b) + tensor([-1.]) + + .. note:: + copysign handles signed zeros. If the other argument has a negative zero (-0), + the corresponding output value will be negative. + """ + +def corrcoef(input: Tensor) -> Tensor: + r""" + corrcoef(input) -> Tensor + + Estimates the Pearson product-moment correlation coefficient matrix of the variables given by the :attr:`input` matrix, + where rows are the variables and columns are the observations. + + .. note:: + + The correlation coefficient matrix R is computed using the covariance matrix C as given by + :math:`R_{ij} = \frac{ C_{ij} } { \sqrt{ C_{ii} * C_{jj} } }` + + .. note:: + + Due to floating point rounding, the resulting array may not be Hermitian and its diagonal elements may not be 1. + The real and imaginary values are clipped to the interval [-1, 1] in an attempt to improve this situation. + + Args: + input (Tensor): A 2D matrix containing multiple variables and observations, or a + Scalar or 1D vector representing a single variable. + + Returns: + (Tensor) The correlation coefficient matrix of the variables. + + .. seealso:: + + :func:`torch.cov` covariance matrix. + + Example:: + + >>> x = torch.tensor([[0, 1, 2], [2, 1, 0]]) + >>> torch.corrcoef(x) + tensor([[ 1., -1.], + [-1., 1.]]) + >>> x = torch.randn(2, 4) + >>> x + tensor([[-0.2678, -0.0908, -0.3766, 0.2780], + [-0.5812, 0.1535, 0.2387, 0.2350]]) + >>> torch.corrcoef(x) + tensor([[1.0000, 0.3582], + [0.3582, 1.0000]]) + >>> torch.corrcoef(x[0]) + tensor(1.) + """ + +def cos(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + cos(input, *, out=None) -> Tensor + + Returns a new tensor with the cosine of the elements of :attr:`input` given in radians. + + .. math:: + \text{out}_{i} = \cos(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 1.4309, 1.2706, -0.8562, 0.9796]) + >>> torch.cos(a) + tensor([ 0.1395, 0.2957, 0.6553, 0.5574]) + """ + +def cos_(input: Tensor) -> Tensor: ... +def cosh(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + cosh(input, *, out=None) -> Tensor + + Returns a new tensor with the hyperbolic cosine of the elements of + :attr:`input`. + + .. math:: + \text{out}_{i} = \cosh(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.1632, 1.1835, -0.6979, -0.7325]) + >>> torch.cosh(a) + tensor([ 1.0133, 1.7860, 1.2536, 1.2805]) + + .. note:: + When :attr:`input` is on the CPU, the implementation of torch.cosh may use + the Sleef library, which rounds very large results to infinity or negative + infinity. See `here `_ for details. + """ + +def cosh_(input: Tensor) -> Tensor: ... +def cosine_embedding_loss( + input1: Tensor, + input2: Tensor, + target: Tensor, + margin: _float = 0.0, + reduction: _int = 1, +) -> Tensor: ... +def cosine_similarity( + x1: Tensor, + x2: Tensor, + dim: _int = 1, + eps: _float = 1e-08, +) -> Tensor: ... +@overload +def count_nonzero(input: Tensor, dim: _int | None = None) -> Tensor: + r""" + count_nonzero(input, dim=None) -> Tensor + + Counts the number of non-zero values in the tensor :attr:`input` along the given :attr:`dim`. + If no dim is specified then all non-zeros in the tensor are counted. + + Args: + input (Tensor): the input tensor. + dim (int or tuple of ints, optional): Dim or tuple of dims along which to count non-zeros. + + Example:: + + >>> x = torch.zeros(3,3) + >>> x[torch.randn(3,3) > 0.5] = 1 + >>> x + tensor([[0., 1., 1.], + [0., 0., 0.], + [0., 0., 1.]]) + >>> torch.count_nonzero(x) + tensor(3) + >>> torch.count_nonzero(x, dim=0) + tensor([0, 1, 2]) + """ + +@overload +def count_nonzero(input: Tensor, dim: _size) -> Tensor: + r""" + count_nonzero(input, dim=None) -> Tensor + + Counts the number of non-zero values in the tensor :attr:`input` along the given :attr:`dim`. + If no dim is specified then all non-zeros in the tensor are counted. + + Args: + input (Tensor): the input tensor. + dim (int or tuple of ints, optional): Dim or tuple of dims along which to count non-zeros. + + Example:: + + >>> x = torch.zeros(3,3) + >>> x[torch.randn(3,3) > 0.5] = 1 + >>> x + tensor([[0., 1., 1.], + [0., 0., 0.], + [0., 0., 1.]]) + >>> torch.count_nonzero(x) + tensor(3) + >>> torch.count_nonzero(x, dim=0) + tensor([0, 1, 2]) + """ + +def cov( + input: Tensor, + *, + correction: _int = 1, + fweights: Tensor | None = None, + aweights: Tensor | None = None, +) -> Tensor: + r""" + cov(input, *, correction=1, fweights=None, aweights=None) -> Tensor + + Estimates the covariance matrix of the variables given by the :attr:`input` matrix, where rows are + the variables and columns are the observations. + + A covariance matrix is a square matrix giving the covariance of each pair of variables. The diagonal contains + the variance of each variable (covariance of a variable with itself). By definition, if :attr:`input` represents + a single variable (Scalar or 1D) then its variance is returned. + + The sample covariance of the variables :math:`x` and :math:`y` is given by: + + .. math:: + \text{cov}(x,y) = \frac{\sum^{N}_{i = 1}(x_{i} - \bar{x})(y_{i} - \bar{y})}{\max(0,~N~-~\delta N)} + + where :math:`\bar{x}` and :math:`\bar{y}` are the simple means of the :math:`x` and :math:`y` respectively, and + :math:`\delta N` is the :attr:`correction`. + + If :attr:`fweights` and/or :attr:`aweights` are provided, the weighted covariance + is calculated, which is given by: + + .. math:: + \text{cov}_w(x,y) = \frac{\sum^{N}_{i = 1}w_i(x_{i} - \mu_x^*)(y_{i} - \mu_y^*)} + {\max(0,~\sum^{N}_{i = 1}w_i~-~\frac{\sum^{N}_{i = 1}w_ia_i}{\sum^{N}_{i = 1}w_i}~\delta N)} + + where :math:`w` denotes :attr:`fweights` or :attr:`aweights` (``f`` and ``a`` for brevity) based on whichever is + provided, or :math:`w = f \times a` if both are provided, and + :math:`\mu_x^* = \frac{\sum^{N}_{i = 1}w_ix_{i} }{\sum^{N}_{i = 1}w_i}` is the weighted mean of the variable. If not + provided, ``f`` and/or ``a`` can be seen as a :math:`\mathbb{1}` vector of appropriate size. + + Args: + input (Tensor): A 2D matrix containing multiple variables and observations, or a + Scalar or 1D vector representing a single variable. + + Keyword Args: + correction (int, optional): difference between the sample size and sample degrees of freedom. + Defaults to Bessel's correction, ``correction = 1`` which returns the unbiased estimate, + even if both :attr:`fweights` and :attr:`aweights` are specified. ``correction = 0`` + will return the simple average. Defaults to ``1``. + fweights (tensor, optional): A Scalar or 1D tensor of observation vector frequencies representing the number of + times each observation should be repeated. Its numel must equal the number of columns of :attr:`input`. + Must have integral dtype. Ignored if ``None``. Defaults to ``None``. + aweights (tensor, optional): A Scalar or 1D array of observation vector weights. + These relative weights are typically large for observations considered "important" and smaller for + observations considered less "important". Its numel must equal the number of columns of :attr:`input`. + Must have floating point dtype. Ignored if ``None``. Defaults to ``None``. + + Returns: + (Tensor) The covariance matrix of the variables. + + .. seealso:: + + :func:`torch.corrcoef` normalized covariance matrix. + + Example:: + + >>> x = torch.tensor([[0, 2], [1, 1], [2, 0]]).T + >>> x + tensor([[0, 1, 2], + [2, 1, 0]]) + >>> torch.cov(x) + tensor([[ 1., -1.], + [-1., 1.]]) + >>> torch.cov(x, correction=0) + tensor([[ 0.6667, -0.6667], + [-0.6667, 0.6667]]) + >>> fw = torch.randint(1, 10, (3,)) + >>> fw + tensor([1, 6, 9]) + >>> aw = torch.rand(3) + >>> aw + tensor([0.4282, 0.0255, 0.4144]) + >>> torch.cov(x, fweights=fw, aweights=aw) + tensor([[ 0.4169, -0.4169], + [-0.4169, 0.4169]]) + """ + +def cross( + input: Tensor, + other: Tensor, + dim: _int | None = None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + cross(input, other, dim=None, *, out=None) -> Tensor + + + Returns the cross product of vectors in dimension :attr:`dim` of :attr:`input` + and :attr:`other`. + + Supports input of float, double, cfloat and cdouble dtypes. Also supports batches + of vectors, for which it computes the product along the dimension :attr:`dim`. + In this case, the output has the same batch dimensions as the inputs. + + .. warning:: + If :attr:`dim` is not given, it defaults to the first dimension found + with the size 3. Note that this might be unexpected. + + This behavior is deprecated and will be changed to match that of :func:`torch.linalg.cross` + in a future release. + + .. seealso:: + :func:`torch.linalg.cross` which has dim=-1 as default. + + + Args: + input (Tensor): the input tensor. + other (Tensor): the second input tensor + dim (int, optional): the dimension to take the cross-product in. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4, 3) + >>> a + tensor([[-0.3956, 1.1455, 1.6895], + [-0.5849, 1.3672, 0.3599], + [-1.1626, 0.7180, -0.0521], + [-0.1339, 0.9902, -2.0225]]) + >>> b = torch.randn(4, 3) + >>> b + tensor([[-0.0257, -1.4725, -1.2251], + [-1.1479, -0.7005, -1.9757], + [-1.3904, 0.3726, -1.1836], + [-0.9688, -0.7153, 0.2159]]) + >>> torch.cross(a, b, dim=1) + tensor([[ 1.0844, -0.5281, 0.6120], + [-2.4490, -1.5687, 1.9792], + [-0.8304, -1.3037, 0.5650], + [-1.2329, 1.9883, 1.0551]]) + >>> torch.cross(a, b) + tensor([[ 1.0844, -0.5281, 0.6120], + [-2.4490, -1.5687, 1.9792], + [-0.8304, -1.3037, 0.5650], + [-1.2329, 1.9883, 1.0551]]) + """ + +def crow_indices_copy( + input: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.crow_indices`, but all output tensors + are freshly created instead of aliasing the input. + """ + +@overload +def ctc_loss( + log_probs: Tensor, + targets: Tensor, + input_lengths: _size, + target_lengths: _size, + blank: _int = 0, + reduction: _int = 1, + zero_infinity: _bool = False, +) -> Tensor: ... +@overload +def ctc_loss( + log_probs: Tensor, + targets: Tensor, + input_lengths: Tensor, + target_lengths: Tensor, + blank: _int = 0, + reduction: _int = 1, + zero_infinity: _bool = False, +) -> Tensor: ... +def cudnn_affine_grid_generator( + theta: Tensor, + N: _int, + C: _int, + H: _int, + W: _int, +) -> Tensor: ... +def cudnn_batch_norm( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + running_mean: Tensor | None, + running_var: Tensor | None, + training: _bool, + exponential_average_factor: _float, + epsilon: _float, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> tuple[Tensor, Tensor, Tensor, Tensor]: ... +def cudnn_convolution( + input: Tensor, + weight: Tensor, + padding: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + groups: _int | SymInt, + benchmark: _bool, + deterministic: _bool, + allow_tf32: _bool, + *, + out: Tensor | None = None, +) -> Tensor: ... +def cudnn_convolution_add_relu( + input: Tensor, + weight: Tensor, + z: Tensor, + alpha: Number | _complex | None, + bias: Tensor | None, + stride: Sequence[_int | SymInt], + padding: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + groups: _int | SymInt, +) -> Tensor: ... +def cudnn_convolution_relu( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + stride: Sequence[_int | SymInt], + padding: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + groups: _int | SymInt, +) -> Tensor: ... +def cudnn_convolution_transpose( + input: Tensor, + weight: Tensor, + padding: Sequence[_int | SymInt], + output_padding: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + groups: _int | SymInt, + benchmark: _bool, + deterministic: _bool, + allow_tf32: _bool, +) -> Tensor: ... +def cudnn_grid_sampler(input: Tensor, grid: Tensor) -> Tensor: ... +def cudnn_is_acceptable(input: Tensor) -> _bool: ... +@overload +def cummax( + input: Tensor, + dim: _int, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.cummax: + r""" + cummax(input, dim, *, out=None) -> (Tensor, LongTensor) + Returns a namedtuple ``(values, indices)`` where ``values`` is the cumulative maximum of + elements of :attr:`input` in the dimension :attr:`dim`. And ``indices`` is the index + location of each maximum value found in the dimension :attr:`dim`. + + .. math:: + y_i = max(x_1, x_2, x_3, \dots, x_i) + + Args: + input (Tensor): the input tensor. + dim (int): the dimension to do the operation over + + Keyword args: + out (tuple, optional): the result tuple of two output tensors (values, indices) + + Example:: + + >>> a = torch.randn(10) + >>> a + tensor([-0.3449, -1.5447, 0.0685, -1.5104, -1.1706, 0.2259, 1.4696, -1.3284, + 1.9946, -0.8209]) + >>> torch.cummax(a, dim=0) + torch.return_types.cummax( + values=tensor([-0.3449, -0.3449, 0.0685, 0.0685, 0.0685, 0.2259, 1.4696, 1.4696, + 1.9946, 1.9946]), + indices=tensor([0, 0, 2, 2, 2, 5, 6, 6, 8, 8])) + """ + +@overload +def cummax( + input: Tensor, + dim: str | EllipsisType | None, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.cummax: + r""" + cummax(input, dim, *, out=None) -> (Tensor, LongTensor) + Returns a namedtuple ``(values, indices)`` where ``values`` is the cumulative maximum of + elements of :attr:`input` in the dimension :attr:`dim`. And ``indices`` is the index + location of each maximum value found in the dimension :attr:`dim`. + + .. math:: + y_i = max(x_1, x_2, x_3, \dots, x_i) + + Args: + input (Tensor): the input tensor. + dim (int): the dimension to do the operation over + + Keyword args: + out (tuple, optional): the result tuple of two output tensors (values, indices) + + Example:: + + >>> a = torch.randn(10) + >>> a + tensor([-0.3449, -1.5447, 0.0685, -1.5104, -1.1706, 0.2259, 1.4696, -1.3284, + 1.9946, -0.8209]) + >>> torch.cummax(a, dim=0) + torch.return_types.cummax( + values=tensor([-0.3449, -0.3449, 0.0685, 0.0685, 0.0685, 0.2259, 1.4696, 1.4696, + 1.9946, 1.9946]), + indices=tensor([0, 0, 2, 2, 2, 5, 6, 6, 8, 8])) + """ + +@overload +def cummin( + input: Tensor, + dim: _int, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.cummin: + r""" + cummin(input, dim, *, out=None) -> (Tensor, LongTensor) + Returns a namedtuple ``(values, indices)`` where ``values`` is the cumulative minimum of + elements of :attr:`input` in the dimension :attr:`dim`. And ``indices`` is the index + location of each maximum value found in the dimension :attr:`dim`. + + .. math:: + y_i = min(x_1, x_2, x_3, \dots, x_i) + + Args: + input (Tensor): the input tensor. + dim (int): the dimension to do the operation over + + Keyword args: + out (tuple, optional): the result tuple of two output tensors (values, indices) + + Example:: + + >>> a = torch.randn(10) + >>> a + tensor([-0.2284, -0.6628, 0.0975, 0.2680, -1.3298, -0.4220, -0.3885, 1.1762, + 0.9165, 1.6684]) + >>> torch.cummin(a, dim=0) + torch.return_types.cummin( + values=tensor([-0.2284, -0.6628, -0.6628, -0.6628, -1.3298, -1.3298, -1.3298, -1.3298, + -1.3298, -1.3298]), + indices=tensor([0, 1, 1, 1, 4, 4, 4, 4, 4, 4])) + """ + +@overload +def cummin( + input: Tensor, + dim: str | EllipsisType | None, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.cummin: + r""" + cummin(input, dim, *, out=None) -> (Tensor, LongTensor) + Returns a namedtuple ``(values, indices)`` where ``values`` is the cumulative minimum of + elements of :attr:`input` in the dimension :attr:`dim`. And ``indices`` is the index + location of each maximum value found in the dimension :attr:`dim`. + + .. math:: + y_i = min(x_1, x_2, x_3, \dots, x_i) + + Args: + input (Tensor): the input tensor. + dim (int): the dimension to do the operation over + + Keyword args: + out (tuple, optional): the result tuple of two output tensors (values, indices) + + Example:: + + >>> a = torch.randn(10) + >>> a + tensor([-0.2284, -0.6628, 0.0975, 0.2680, -1.3298, -0.4220, -0.3885, 1.1762, + 0.9165, 1.6684]) + >>> torch.cummin(a, dim=0) + torch.return_types.cummin( + values=tensor([-0.2284, -0.6628, -0.6628, -0.6628, -1.3298, -1.3298, -1.3298, -1.3298, + -1.3298, -1.3298]), + indices=tensor([0, 1, 1, 1, 4, 4, 4, 4, 4, 4])) + """ + +@overload +def cumprod( + input: Tensor, + dim: _int, + *, + dtype: _dtype | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + cumprod(input, dim, *, dtype=None, out=None) -> Tensor + + Returns the cumulative product of elements of :attr:`input` in the dimension + :attr:`dim`. + + For example, if :attr:`input` is a vector of size N, the result will also be + a vector of size N, with elements. + + .. math:: + y_i = x_1 \times x_2\times x_3\times \dots \times x_i + + Args: + input (Tensor): the input tensor. + dim (int): the dimension to do the operation over + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(10) + >>> a + tensor([ 0.6001, 0.2069, -0.1919, 0.9792, 0.6727, 1.0062, 0.4126, + -0.2129, -0.4206, 0.1968]) + >>> torch.cumprod(a, dim=0) + tensor([ 0.6001, 0.1241, -0.0238, -0.0233, -0.0157, -0.0158, -0.0065, + 0.0014, -0.0006, -0.0001]) + + >>> a[5] = 0.0 + >>> torch.cumprod(a, dim=0) + tensor([ 0.6001, 0.1241, -0.0238, -0.0233, -0.0157, -0.0000, -0.0000, + 0.0000, -0.0000, -0.0000]) + """ + +@overload +def cumprod( + input: Tensor, + dim: str | EllipsisType | None, + *, + dtype: _dtype | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + cumprod(input, dim, *, dtype=None, out=None) -> Tensor + + Returns the cumulative product of elements of :attr:`input` in the dimension + :attr:`dim`. + + For example, if :attr:`input` is a vector of size N, the result will also be + a vector of size N, with elements. + + .. math:: + y_i = x_1 \times x_2\times x_3\times \dots \times x_i + + Args: + input (Tensor): the input tensor. + dim (int): the dimension to do the operation over + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(10) + >>> a + tensor([ 0.6001, 0.2069, -0.1919, 0.9792, 0.6727, 1.0062, 0.4126, + -0.2129, -0.4206, 0.1968]) + >>> torch.cumprod(a, dim=0) + tensor([ 0.6001, 0.1241, -0.0238, -0.0233, -0.0157, -0.0158, -0.0065, + 0.0014, -0.0006, -0.0001]) + + >>> a[5] = 0.0 + >>> torch.cumprod(a, dim=0) + tensor([ 0.6001, 0.1241, -0.0238, -0.0233, -0.0157, -0.0000, -0.0000, + 0.0000, -0.0000, -0.0000]) + """ + +@overload +def cumsum( + input: Tensor, + dim: _int, + *, + dtype: _dtype | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + cumsum(input, dim, *, dtype=None, out=None) -> Tensor + + Returns the cumulative sum of elements of :attr:`input` in the dimension + :attr:`dim`. + + For example, if :attr:`input` is a vector of size N, the result will also be + a vector of size N, with elements. + + .. math:: + y_i = x_1 + x_2 + x_3 + \dots + x_i + + Args: + input (Tensor): the input tensor. + dim (int): the dimension to do the operation over + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randint(1, 20, (10,)) + >>> a + tensor([13, 7, 3, 10, 13, 3, 15, 10, 9, 10]) + >>> torch.cumsum(a, dim=0) + tensor([13, 20, 23, 33, 46, 49, 64, 74, 83, 93]) + """ + +@overload +def cumsum( + input: Tensor, + dim: str | EllipsisType | None, + *, + dtype: _dtype | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + cumsum(input, dim, *, dtype=None, out=None) -> Tensor + + Returns the cumulative sum of elements of :attr:`input` in the dimension + :attr:`dim`. + + For example, if :attr:`input` is a vector of size N, the result will also be + a vector of size N, with elements. + + .. math:: + y_i = x_1 + x_2 + x_3 + \dots + x_i + + Args: + input (Tensor): the input tensor. + dim (int): the dimension to do the operation over + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randint(1, 20, (10,)) + >>> a + tensor([13, 7, 3, 10, 13, 3, 15, 10, 9, 10]) + >>> torch.cumsum(a, dim=0) + tensor([13, 20, 23, 33, 46, 49, 64, 74, 83, 93]) + """ + +@overload +def cumulative_trapezoid(y: Tensor, x: Tensor, *, dim: _int = -1) -> Tensor: + r""" + cumulative_trapezoid(y, x=None, *, dx=None, dim=-1) -> Tensor + + Cumulatively computes the `trapezoidal rule `_ + along :attr:`dim`. By default the spacing between elements is assumed to be 1, but + :attr:`dx` can be used to specify a different constant spacing, and :attr:`x` can be + used to specify arbitrary spacing along :attr:`dim`. + + For more details, please read :func:`torch.trapezoid`. The difference between :func:`torch.trapezoid` + and this function is that, :func:`torch.trapezoid` returns a value for each integration, + where as this function returns a cumulative value for every spacing within the integration. This + is analogous to how `.sum` returns a value and `.cumsum` returns a cumulative sum. + + Arguments: + y (Tensor): Values to use when computing the trapezoidal rule. + x (Tensor): If specified, defines spacing between values as specified above. + + Keyword arguments: + dx (float): constant spacing between values. If neither :attr:`x` or :attr:`dx` + are specified then this defaults to 1. Effectively multiplies the result by its value. + dim (int): The dimension along which to compute the trapezoidal rule. + The last (inner-most) dimension by default. + + Examples:: + + >>> # Cumulatively computes the trapezoidal rule in 1D, spacing is implicitly 1. + >>> y = torch.tensor([1, 5, 10]) + >>> torch.cumulative_trapezoid(y) + tensor([3., 10.5]) + + >>> # Computes the same trapezoidal rule directly up to each element to verify + >>> (1 + 5) / 2 + 3.0 + >>> (1 + 10 + 10) / 2 + 10.5 + + >>> # Cumulatively computes the trapezoidal rule in 1D with constant spacing of 2 + >>> # NOTE: the result is the same as before, but multiplied by 2 + >>> torch.cumulative_trapezoid(y, dx=2) + tensor([6., 21.]) + + >>> # Cumulatively computes the trapezoidal rule in 1D with arbitrary spacing + >>> x = torch.tensor([1, 3, 6]) + >>> torch.cumulative_trapezoid(y, x) + tensor([6., 28.5]) + + >>> # Computes the same trapezoidal rule directly up to each element to verify + >>> ((3 - 1) * (1 + 5)) / 2 + 6.0 + >>> ((3 - 1) * (1 + 5) + (6 - 3) * (5 + 10)) / 2 + 28.5 + + >>> # Cumulatively computes the trapezoidal rule for each row of a 3x3 matrix + >>> y = torch.arange(9).reshape(3, 3) + tensor([[0, 1, 2], + [3, 4, 5], + [6, 7, 8]]) + >>> torch.cumulative_trapezoid(y) + tensor([[ 0.5, 2.], + [ 3.5, 8.], + [ 6.5, 14.]]) + + >>> # Cumulatively computes the trapezoidal rule for each column of the matrix + >>> torch.cumulative_trapezoid(y, dim=0) + tensor([[ 1.5, 2.5, 3.5], + [ 6.0, 8.0, 10.0]]) + + >>> # Cumulatively computes the trapezoidal rule for each row of a 3x3 ones matrix + >>> # with the same arbitrary spacing + >>> y = torch.ones(3, 3) + >>> x = torch.tensor([1, 3, 6]) + >>> torch.cumulative_trapezoid(y, x) + tensor([[2., 5.], + [2., 5.], + [2., 5.]]) + + >>> # Cumulatively computes the trapezoidal rule for each row of a 3x3 ones matrix + >>> # with different arbitrary spacing per row + >>> y = torch.ones(3, 3) + >>> x = torch.tensor([[1, 2, 3], [1, 3, 5], [1, 4, 7]]) + >>> torch.cumulative_trapezoid(y, x) + tensor([[1., 2.], + [2., 4.], + [3., 6.]]) + """ + +@overload +def cumulative_trapezoid( + y: Tensor, + *, + dx: Number | _complex = 1, + dim: _int = -1, +) -> Tensor: + r""" + cumulative_trapezoid(y, x=None, *, dx=None, dim=-1) -> Tensor + + Cumulatively computes the `trapezoidal rule `_ + along :attr:`dim`. By default the spacing between elements is assumed to be 1, but + :attr:`dx` can be used to specify a different constant spacing, and :attr:`x` can be + used to specify arbitrary spacing along :attr:`dim`. + + For more details, please read :func:`torch.trapezoid`. The difference between :func:`torch.trapezoid` + and this function is that, :func:`torch.trapezoid` returns a value for each integration, + where as this function returns a cumulative value for every spacing within the integration. This + is analogous to how `.sum` returns a value and `.cumsum` returns a cumulative sum. + + Arguments: + y (Tensor): Values to use when computing the trapezoidal rule. + x (Tensor): If specified, defines spacing between values as specified above. + + Keyword arguments: + dx (float): constant spacing between values. If neither :attr:`x` or :attr:`dx` + are specified then this defaults to 1. Effectively multiplies the result by its value. + dim (int): The dimension along which to compute the trapezoidal rule. + The last (inner-most) dimension by default. + + Examples:: + + >>> # Cumulatively computes the trapezoidal rule in 1D, spacing is implicitly 1. + >>> y = torch.tensor([1, 5, 10]) + >>> torch.cumulative_trapezoid(y) + tensor([3., 10.5]) + + >>> # Computes the same trapezoidal rule directly up to each element to verify + >>> (1 + 5) / 2 + 3.0 + >>> (1 + 10 + 10) / 2 + 10.5 + + >>> # Cumulatively computes the trapezoidal rule in 1D with constant spacing of 2 + >>> # NOTE: the result is the same as before, but multiplied by 2 + >>> torch.cumulative_trapezoid(y, dx=2) + tensor([6., 21.]) + + >>> # Cumulatively computes the trapezoidal rule in 1D with arbitrary spacing + >>> x = torch.tensor([1, 3, 6]) + >>> torch.cumulative_trapezoid(y, x) + tensor([6., 28.5]) + + >>> # Computes the same trapezoidal rule directly up to each element to verify + >>> ((3 - 1) * (1 + 5)) / 2 + 6.0 + >>> ((3 - 1) * (1 + 5) + (6 - 3) * (5 + 10)) / 2 + 28.5 + + >>> # Cumulatively computes the trapezoidal rule for each row of a 3x3 matrix + >>> y = torch.arange(9).reshape(3, 3) + tensor([[0, 1, 2], + [3, 4, 5], + [6, 7, 8]]) + >>> torch.cumulative_trapezoid(y) + tensor([[ 0.5, 2.], + [ 3.5, 8.], + [ 6.5, 14.]]) + + >>> # Cumulatively computes the trapezoidal rule for each column of the matrix + >>> torch.cumulative_trapezoid(y, dim=0) + tensor([[ 1.5, 2.5, 3.5], + [ 6.0, 8.0, 10.0]]) + + >>> # Cumulatively computes the trapezoidal rule for each row of a 3x3 ones matrix + >>> # with the same arbitrary spacing + >>> y = torch.ones(3, 3) + >>> x = torch.tensor([1, 3, 6]) + >>> torch.cumulative_trapezoid(y, x) + tensor([[2., 5.], + [2., 5.], + [2., 5.]]) + + >>> # Cumulatively computes the trapezoidal rule for each row of a 3x3 ones matrix + >>> # with different arbitrary spacing per row + >>> y = torch.ones(3, 3) + >>> x = torch.tensor([[1, 2, 3], [1, 3, 5], [1, 4, 7]]) + >>> torch.cumulative_trapezoid(y, x) + tensor([[1., 2.], + [2., 4.], + [3., 6.]]) + """ + +def deg2rad(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + deg2rad(input, *, out=None) -> Tensor + + Returns a new tensor with each of the elements of :attr:`input` + converted from angles in degrees to radians. + + Args: + input (Tensor): the input tensor. + + Keyword arguments: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([[180.0, -180.0], [360.0, -360.0], [90.0, -90.0]]) + >>> torch.deg2rad(a) + tensor([[ 3.1416, -3.1416], + [ 6.2832, -6.2832], + [ 1.5708, -1.5708]]) + """ + +def deg2rad_(input: Tensor) -> Tensor: ... +@overload +def dequantize(input: Tensor) -> Tensor: + r""" + dequantize(tensor) -> Tensor + + Returns an fp32 Tensor by dequantizing a quantized Tensor + + Args: + tensor (Tensor): A quantized Tensor + + .. function:: dequantize(tensors) -> sequence of Tensors + :noindex: + + Given a list of quantized Tensors, dequantize them and return a list of fp32 Tensors + + Args: + tensors (sequence of Tensors): A list of quantized Tensors + """ + +@overload +def dequantize( + tensors: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: + r""" + dequantize(tensor) -> Tensor + + Returns an fp32 Tensor by dequantizing a quantized Tensor + + Args: + tensor (Tensor): A quantized Tensor + + .. function:: dequantize(tensors) -> sequence of Tensors + :noindex: + + Given a list of quantized Tensors, dequantize them and return a list of fp32 Tensors + + Args: + tensors (sequence of Tensors): A list of quantized Tensors + """ + +def det(input: Tensor) -> Tensor: + r""" + det(input) -> Tensor + + Alias for :func:`torch.linalg.det` + """ + +def detach(input: Tensor) -> Tensor: ... +def detach_(input: Tensor) -> Tensor: ... +def detach_copy(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + Performs the same operation as :func:`torch.detach`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def diag( + input: Tensor, + diagonal: _int = 0, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + diag(input, diagonal=0, *, out=None) -> Tensor + + - If :attr:`input` is a vector (1-D tensor), then returns a 2-D square tensor + with the elements of :attr:`input` as the diagonal. + - If :attr:`input` is a matrix (2-D tensor), then returns a 1-D tensor with + the diagonal elements of :attr:`input`. + + The argument :attr:`diagonal` controls which diagonal to consider: + + - If :attr:`diagonal` = 0, it is the main diagonal. + - If :attr:`diagonal` > 0, it is above the main diagonal. + - If :attr:`diagonal` < 0, it is below the main diagonal. + + Args: + input (Tensor): the input tensor. + diagonal (int, optional): the diagonal to consider + + Keyword args: + out (Tensor, optional): the output tensor. + + .. seealso:: + + :func:`torch.diagonal` always returns the diagonal of its input. + + :func:`torch.diagflat` always constructs a tensor with diagonal elements + specified by the input. + + Examples: + + Get the square matrix where the input vector is the diagonal:: + + >>> a = torch.randn(3) + >>> a + tensor([ 0.5950,-0.0872, 2.3298]) + >>> torch.diag(a) + tensor([[ 0.5950, 0.0000, 0.0000], + [ 0.0000,-0.0872, 0.0000], + [ 0.0000, 0.0000, 2.3298]]) + >>> torch.diag(a, 1) + tensor([[ 0.0000, 0.5950, 0.0000, 0.0000], + [ 0.0000, 0.0000,-0.0872, 0.0000], + [ 0.0000, 0.0000, 0.0000, 2.3298], + [ 0.0000, 0.0000, 0.0000, 0.0000]]) + + Get the k-th diagonal of a given matrix:: + + >>> a = torch.randn(3, 3) + >>> a + tensor([[-0.4264, 0.0255,-0.1064], + [ 0.8795,-0.2429, 0.1374], + [ 0.1029,-0.6482,-1.6300]]) + >>> torch.diag(a, 0) + tensor([-0.4264,-0.2429,-1.6300]) + >>> torch.diag(a, 1) + tensor([ 0.0255, 0.1374]) + """ + +def diag_embed( + input: Tensor, + offset: _int = 0, + dim1: _int = -2, + dim2: _int = -1, +) -> Tensor: + r""" + diag_embed(input, offset=0, dim1=-2, dim2=-1) -> Tensor + + Creates a tensor whose diagonals of certain 2D planes (specified by + :attr:`dim1` and :attr:`dim2`) are filled by :attr:`input`. + To facilitate creating batched diagonal matrices, the 2D planes formed by + the last two dimensions of the returned tensor are chosen by default. + + The argument :attr:`offset` controls which diagonal to consider: + + - If :attr:`offset` = 0, it is the main diagonal. + - If :attr:`offset` > 0, it is above the main diagonal. + - If :attr:`offset` < 0, it is below the main diagonal. + + The size of the new matrix will be calculated to make the specified diagonal + of the size of the last input dimension. + Note that for :attr:`offset` other than :math:`0`, the order of :attr:`dim1` + and :attr:`dim2` matters. Exchanging them is equivalent to changing the + sign of :attr:`offset`. + + Applying :meth:`torch.diagonal` to the output of this function with + the same arguments yields a matrix identical to input. However, + :meth:`torch.diagonal` has different default dimensions, so those + need to be explicitly specified. + + Args: + input (Tensor): the input tensor. Must be at least 1-dimensional. + offset (int, optional): which diagonal to consider. Default: 0 + (main diagonal). + dim1 (int, optional): first dimension with respect to which to + take diagonal. Default: -2. + dim2 (int, optional): second dimension with respect to which to + take diagonal. Default: -1. + + Example:: + + >>> a = torch.randn(2, 3) + >>> torch.diag_embed(a) + tensor([[[ 1.5410, 0.0000, 0.0000], + [ 0.0000, -0.2934, 0.0000], + [ 0.0000, 0.0000, -2.1788]], + + [[ 0.5684, 0.0000, 0.0000], + [ 0.0000, -1.0845, 0.0000], + [ 0.0000, 0.0000, -1.3986]]]) + + >>> torch.diag_embed(a, offset=1, dim1=0, dim2=2) + tensor([[[ 0.0000, 1.5410, 0.0000, 0.0000], + [ 0.0000, 0.5684, 0.0000, 0.0000]], + + [[ 0.0000, 0.0000, -0.2934, 0.0000], + [ 0.0000, 0.0000, -1.0845, 0.0000]], + + [[ 0.0000, 0.0000, 0.0000, -2.1788], + [ 0.0000, 0.0000, 0.0000, -1.3986]], + + [[ 0.0000, 0.0000, 0.0000, 0.0000], + [ 0.0000, 0.0000, 0.0000, 0.0000]]]) + """ + +def diagflat(input: Tensor, offset: _int = 0) -> Tensor: + r""" + diagflat(input, offset=0) -> Tensor + + - If :attr:`input` is a vector (1-D tensor), then returns a 2-D square tensor + with the elements of :attr:`input` as the diagonal. + - If :attr:`input` is a tensor with more than one dimension, then returns a + 2-D tensor with diagonal elements equal to a flattened :attr:`input`. + + The argument :attr:`offset` controls which diagonal to consider: + + - If :attr:`offset` = 0, it is the main diagonal. + - If :attr:`offset` > 0, it is above the main diagonal. + - If :attr:`offset` < 0, it is below the main diagonal. + + Args: + input (Tensor): the input tensor. + offset (int, optional): the diagonal to consider. Default: 0 (main + diagonal). + + Examples:: + + >>> a = torch.randn(3) + >>> a + tensor([-0.2956, -0.9068, 0.1695]) + >>> torch.diagflat(a) + tensor([[-0.2956, 0.0000, 0.0000], + [ 0.0000, -0.9068, 0.0000], + [ 0.0000, 0.0000, 0.1695]]) + >>> torch.diagflat(a, 1) + tensor([[ 0.0000, -0.2956, 0.0000, 0.0000], + [ 0.0000, 0.0000, -0.9068, 0.0000], + [ 0.0000, 0.0000, 0.0000, 0.1695], + [ 0.0000, 0.0000, 0.0000, 0.0000]]) + + >>> a = torch.randn(2, 2) + >>> a + tensor([[ 0.2094, -0.3018], + [-0.1516, 1.9342]]) + >>> torch.diagflat(a) + tensor([[ 0.2094, 0.0000, 0.0000, 0.0000], + [ 0.0000, -0.3018, 0.0000, 0.0000], + [ 0.0000, 0.0000, -0.1516, 0.0000], + [ 0.0000, 0.0000, 0.0000, 1.9342]]) + """ + +@overload +def diagonal( + input: Tensor, + offset: _int = 0, + dim1: _int = 0, + dim2: _int = 1, +) -> Tensor: + r""" + diagonal(input, offset=0, dim1=0, dim2=1) -> Tensor + + Returns a partial view of :attr:`input` with the its diagonal elements + with respect to :attr:`dim1` and :attr:`dim2` appended as a dimension + at the end of the shape. + + The argument :attr:`offset` controls which diagonal to consider: + + - If :attr:`offset` = 0, it is the main diagonal. + - If :attr:`offset` > 0, it is above the main diagonal. + - If :attr:`offset` < 0, it is below the main diagonal. + + Applying :meth:`torch.diag_embed` to the output of this function with + the same arguments yields a diagonal matrix with the diagonal entries + of the input. However, :meth:`torch.diag_embed` has different default + dimensions, so those need to be explicitly specified. + + Args: + input (Tensor): the input tensor. Must be at least 2-dimensional. + offset (int, optional): which diagonal to consider. Default: 0 + (main diagonal). + dim1 (int, optional): first dimension with respect to which to + take diagonal. Default: 0. + dim2 (int, optional): second dimension with respect to which to + take diagonal. Default: 1. + + .. note:: To take a batch diagonal, pass in dim1=-2, dim2=-1. + + Examples:: + + >>> a = torch.randn(3, 3) + >>> a + tensor([[-1.0854, 1.1431, -0.1752], + [ 0.8536, -0.0905, 0.0360], + [ 0.6927, -0.3735, -0.4945]]) + + + >>> torch.diagonal(a) + tensor([-1.0854, -0.0905, -0.4945]) + + + >>> torch.diagonal(a, 1) + tensor([ 1.1431, 0.0360]) + + >>> b = torch.randn(2, 5) + >>> b + tensor([[-1.7948, -1.2731, -0.3181, 2.0200, -1.6745], + [ 1.8262, -1.5049, 0.4114, 1.0704, -1.2607]]) + + >>> torch.diagonal(b, 1, 1, 0) + tensor([1.8262]) + + >>> x = torch.randn(2, 5, 4, 2) + >>> torch.diagonal(x, offset=-1, dim1=1, dim2=2) + tensor([[[-1.2631, 0.3755, -1.5977, -1.8172], + [-1.1065, 1.0401, -0.2235, -0.7938]], + + [[-1.7325, -0.3081, 0.6166, 0.2335], + [ 1.0500, 0.7336, -0.3836, -1.1015]]]) + """ + +@overload +def diagonal( + input: Tensor, + *, + outdim: str | EllipsisType | None, + dim1: str | EllipsisType | None, + dim2: str | EllipsisType | None, + offset: _int = 0, +) -> Tensor: + r""" + diagonal(input, offset=0, dim1=0, dim2=1) -> Tensor + + Returns a partial view of :attr:`input` with the its diagonal elements + with respect to :attr:`dim1` and :attr:`dim2` appended as a dimension + at the end of the shape. + + The argument :attr:`offset` controls which diagonal to consider: + + - If :attr:`offset` = 0, it is the main diagonal. + - If :attr:`offset` > 0, it is above the main diagonal. + - If :attr:`offset` < 0, it is below the main diagonal. + + Applying :meth:`torch.diag_embed` to the output of this function with + the same arguments yields a diagonal matrix with the diagonal entries + of the input. However, :meth:`torch.diag_embed` has different default + dimensions, so those need to be explicitly specified. + + Args: + input (Tensor): the input tensor. Must be at least 2-dimensional. + offset (int, optional): which diagonal to consider. Default: 0 + (main diagonal). + dim1 (int, optional): first dimension with respect to which to + take diagonal. Default: 0. + dim2 (int, optional): second dimension with respect to which to + take diagonal. Default: 1. + + .. note:: To take a batch diagonal, pass in dim1=-2, dim2=-1. + + Examples:: + + >>> a = torch.randn(3, 3) + >>> a + tensor([[-1.0854, 1.1431, -0.1752], + [ 0.8536, -0.0905, 0.0360], + [ 0.6927, -0.3735, -0.4945]]) + + + >>> torch.diagonal(a) + tensor([-1.0854, -0.0905, -0.4945]) + + + >>> torch.diagonal(a, 1) + tensor([ 1.1431, 0.0360]) + + >>> b = torch.randn(2, 5) + >>> b + tensor([[-1.7948, -1.2731, -0.3181, 2.0200, -1.6745], + [ 1.8262, -1.5049, 0.4114, 1.0704, -1.2607]]) + + >>> torch.diagonal(b, 1, 1, 0) + tensor([1.8262]) + + >>> x = torch.randn(2, 5, 4, 2) + >>> torch.diagonal(x, offset=-1, dim1=1, dim2=2) + tensor([[[-1.2631, 0.3755, -1.5977, -1.8172], + [-1.1065, 1.0401, -0.2235, -0.7938]], + + [[-1.7325, -0.3081, 0.6166, 0.2335], + [ 1.0500, 0.7336, -0.3836, -1.1015]]]) + """ + +def diagonal_copy( + input: Tensor, + offset: _int = 0, + dim1: _int = 0, + dim2: _int = 1, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.diagonal`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def diagonal_scatter( + input: Tensor, + src: Tensor, + offset: _int = 0, + dim1: _int = 0, + dim2: _int = 1, +) -> Tensor: + r""" + diagonal_scatter(input, src, offset=0, dim1=0, dim2=1) -> Tensor + + Embeds the values of the :attr:`src` tensor into :attr:`input` along + the diagonal elements of :attr:`input`, with respect to :attr:`dim1` + and :attr:`dim2`. + + This function returns a tensor with fresh storage; it does not + return a view. + + The argument :attr:`offset` controls which diagonal to consider: + + - If :attr:`offset` = 0, it is the main diagonal. + - If :attr:`offset` > 0, it is above the main diagonal. + - If :attr:`offset` < 0, it is below the main diagonal. + + Args: + input (Tensor): the input tensor. Must be at least 2-dimensional. + src (Tensor): the tensor to embed into :attr:`input`. + offset (int, optional): which diagonal to consider. Default: 0 + (main diagonal). + dim1 (int, optional): first dimension with respect to which to + take diagonal. Default: 0. + dim2 (int, optional): second dimension with respect to which to + take diagonal. Default: 1. + + .. note:: + + :attr:`src` must be of the proper size in order to be embedded + into :attr:`input`. Specifically, it should have the same shape as + ``torch.diagonal(input, offset, dim1, dim2)`` + + Examples:: + + >>> a = torch.zeros(3, 3) + >>> a + tensor([[0., 0., 0.], + [0., 0., 0.], + [0., 0., 0.]]) + + >>> torch.diagonal_scatter(a, torch.ones(3), 0) + tensor([[1., 0., 0.], + [0., 1., 0.], + [0., 0., 1.]]) + + >>> torch.diagonal_scatter(a, torch.ones(2), 1) + tensor([[0., 1., 0.], + [0., 0., 1.], + [0., 0., 0.]]) + """ + +def diff( + input: Tensor, + n: _int = 1, + dim: _int = -1, + prepend: Tensor | None = None, + append: Tensor | None = None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + diff(input, n=1, dim=-1, prepend=None, append=None) -> Tensor + + Computes the n-th forward difference along the given dimension. + + The first-order differences are given by `out[i] = input[i + 1] - input[i]`. Higher-order + differences are calculated by using :func:`torch.diff` recursively. + + Args: + input (Tensor): the tensor to compute the differences on + n (int, optional): the number of times to recursively compute the difference + dim (int, optional): the dimension to compute the difference along. + Default is the last dimension. + prepend, append (Tensor, optional): values to prepend or append to + :attr:`input` along :attr:`dim` before computing the difference. + Their dimensions must be equivalent to that of input, and their shapes + must match input's shape except on :attr:`dim`. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([1, 3, 2]) + >>> torch.diff(a) + tensor([ 2, -1]) + >>> b = torch.tensor([4, 5]) + >>> torch.diff(a, append=b) + tensor([ 2, -1, 2, 1]) + >>> c = torch.tensor([[1, 2, 3], [3, 4, 5]]) + >>> torch.diff(c, dim=0) + tensor([[2, 2, 2]]) + >>> torch.diff(c, dim=1) + tensor([[1, 1], + [1, 1]]) + """ + +def digamma(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + digamma(input, *, out=None) -> Tensor + + Alias for :func:`torch.special.digamma`. + """ + +def dist(input: Tensor, other: Tensor, p: Number | _complex = 2) -> Tensor: + r""" + dist(input, other, p=2) -> Tensor + + Returns the p-norm of (:attr:`input` - :attr:`other`) + + The shapes of :attr:`input` and :attr:`other` must be + :ref:`broadcastable `. + + Args: + input (Tensor): the input tensor. + other (Tensor): the Right-hand-side input tensor + p (float, optional): the norm to be computed + + Example:: + + >>> x = torch.randn(4) + >>> x + tensor([-1.5393, -0.8675, 0.5916, 1.6321]) + >>> y = torch.randn(4) + >>> y + tensor([ 0.0967, -1.0511, 0.6295, 0.8360]) + >>> torch.dist(x, y, 3.5) + tensor(1.6727) + >>> torch.dist(x, y, 3) + tensor(1.6973) + >>> torch.dist(x, y, 0) + tensor(4.) + >>> torch.dist(x, y, 1) + tensor(2.6537) + """ + +def div( + input: Tensor | Number, + other: Tensor | Number, + *, + rounding_mode: str | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + div(input, other, *, rounding_mode=None, out=None) -> Tensor + + Divides each element of the input ``input`` by the corresponding element of + :attr:`other`. + + .. math:: + \text{out}_i = \frac{\text{input}_i}{\text{other}_i} + + .. note:: + By default, this performs a "true" division like Python 3. + See the :attr:`rounding_mode` argument for floor division. + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer, float, and complex inputs. + Always promotes integer types to the default scalar type. + + Args: + input (Tensor): the dividend + other (Tensor or Number): the divisor + + Keyword args: + rounding_mode (str, optional): Type of rounding applied to the result: + + * None - default behavior. Performs no rounding and, if both :attr:`input` and + :attr:`other` are integer types, promotes the inputs to the default scalar type. + Equivalent to true division in Python (the ``/`` operator) and NumPy's ``np.true_divide``. + * ``"trunc"`` - rounds the results of the division towards zero. + Equivalent to C-style integer division. + * ``"floor"`` - rounds the results of the division down. + Equivalent to floor division in Python (the ``//`` operator) and NumPy's ``np.floor_divide``. + + out (Tensor, optional): the output tensor. + + Examples:: + + >>> x = torch.tensor([ 0.3810, 1.2774, -0.2972, -0.3719, 0.4637]) + >>> torch.div(x, 0.5) + tensor([ 0.7620, 2.5548, -0.5944, -0.7438, 0.9274]) + + >>> a = torch.tensor([[-0.3711, -1.9353, -0.4605, -0.2917], + ... [ 0.1815, -1.0111, 0.9805, -1.5923], + ... [ 0.1062, 1.4581, 0.7759, -1.2344], + ... [-0.1830, -0.0313, 1.1908, -1.4757]]) + >>> b = torch.tensor([ 0.8032, 0.2930, -0.8113, -0.2308]) + >>> torch.div(a, b) + tensor([[-0.4620, -6.6051, 0.5676, 1.2639], + [ 0.2260, -3.4509, -1.2086, 6.8990], + [ 0.1322, 4.9764, -0.9564, 5.3484], + [-0.2278, -0.1068, -1.4678, 6.3938]]) + + >>> torch.div(a, b, rounding_mode='trunc') + tensor([[-0., -6., 0., 1.], + [ 0., -3., -1., 6.], + [ 0., 4., -0., 5.], + [-0., -0., -1., 6.]]) + + >>> torch.div(a, b, rounding_mode='floor') + tensor([[-1., -7., 0., 1.], + [ 0., -4., -2., 6.], + [ 0., 4., -1., 5.], + [-1., -1., -2., 6.]]) + """ + +@overload +def divide( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + divide(input, other, *, rounding_mode=None, out=None) -> Tensor + + Alias for :func:`torch.div`. + """ + +@overload +def divide( + input: Tensor, + other: Tensor, + *, + rounding_mode: str | None, + out: Tensor | None = None, +) -> Tensor: + r""" + divide(input, other, *, rounding_mode=None, out=None) -> Tensor + + Alias for :func:`torch.div`. + """ + +@overload +def divide( + input: Tensor, + other: Number | _complex, + *, + rounding_mode: str | None, +) -> Tensor: + r""" + divide(input, other, *, rounding_mode=None, out=None) -> Tensor + + Alias for :func:`torch.div`. + """ + +@overload +def divide(input: Tensor, other: Number | _complex) -> Tensor: + r""" + divide(input, other, *, rounding_mode=None, out=None) -> Tensor + + Alias for :func:`torch.div`. + """ + +def dot( + input: Tensor, + tensor: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + dot(input, tensor, *, out=None) -> Tensor + + Computes the dot product of two 1D tensors. + + .. note:: + + Unlike NumPy's dot, torch.dot intentionally only supports computing the dot product + of two 1D tensors with the same number of elements. + + Args: + input (Tensor): first tensor in the dot product, must be 1D. + tensor (Tensor): second tensor in the dot product, must be 1D. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.dot(torch.tensor([2, 3]), torch.tensor([2, 1])) + tensor(7) + + >>> t1, t2 = torch.tensor([0, 1]), torch.tensor([2, 3]) + >>> torch.dot(t1, t2) + tensor(3) + """ + +def dropout(input: Tensor, p: _float, train: _bool) -> Tensor: ... +def dropout_(input: Tensor, p: _float, train: _bool) -> Tensor: ... +def dsmm(input: Tensor, mat2: Tensor) -> Tensor: ... +@overload +def dsplit(input: Tensor, sections: _int) -> tuple[Tensor, ...]: + r""" + dsplit(input, indices_or_sections) -> List of Tensors + + Splits :attr:`input`, a tensor with three or more dimensions, into multiple tensors + depthwise according to :attr:`indices_or_sections`. Each split is a view of + :attr:`input`. + + This is equivalent to calling torch.tensor_split(input, indices_or_sections, dim=2) + (the split dimension is 2), except that if :attr:`indices_or_sections` is an integer + it must evenly divide the split dimension or a runtime error will be thrown. + + This function is based on NumPy's :func:`numpy.dsplit`. + + Args: + input (Tensor): tensor to split. + indices_or_sections (int or list or tuple of ints): See argument in :func:`torch.tensor_split`. + + Example:: + + >>> t = torch.arange(16.0).reshape(2, 2, 4) + >>> t + tensor([[[ 0., 1., 2., 3.], + [ 4., 5., 6., 7.]], + [[ 8., 9., 10., 11.], + [12., 13., 14., 15.]]]) + >>> torch.dsplit(t, 2) + (tensor([[[ 0., 1.], + [ 4., 5.]], + [[ 8., 9.], + [12., 13.]]]), + tensor([[[ 2., 3.], + [ 6., 7.]], + [[10., 11.], + [14., 15.]]])) + + >>> torch.dsplit(t, [3, 6]) + (tensor([[[ 0., 1., 2.], + [ 4., 5., 6.]], + [[ 8., 9., 10.], + [12., 13., 14.]]]), + tensor([[[ 3.], + [ 7.]], + [[11.], + [15.]]]), + tensor([], size=(2, 2, 0))) + """ + +@overload +def dsplit(input: Tensor, indices: _size) -> tuple[Tensor, ...]: + r""" + dsplit(input, indices_or_sections) -> List of Tensors + + Splits :attr:`input`, a tensor with three or more dimensions, into multiple tensors + depthwise according to :attr:`indices_or_sections`. Each split is a view of + :attr:`input`. + + This is equivalent to calling torch.tensor_split(input, indices_or_sections, dim=2) + (the split dimension is 2), except that if :attr:`indices_or_sections` is an integer + it must evenly divide the split dimension or a runtime error will be thrown. + + This function is based on NumPy's :func:`numpy.dsplit`. + + Args: + input (Tensor): tensor to split. + indices_or_sections (int or list or tuple of ints): See argument in :func:`torch.tensor_split`. + + Example:: + + >>> t = torch.arange(16.0).reshape(2, 2, 4) + >>> t + tensor([[[ 0., 1., 2., 3.], + [ 4., 5., 6., 7.]], + [[ 8., 9., 10., 11.], + [12., 13., 14., 15.]]]) + >>> torch.dsplit(t, 2) + (tensor([[[ 0., 1.], + [ 4., 5.]], + [[ 8., 9.], + [12., 13.]]]), + tensor([[[ 2., 3.], + [ 6., 7.]], + [[10., 11.], + [14., 15.]]])) + + >>> torch.dsplit(t, [3, 6]) + (tensor([[[ 0., 1., 2.], + [ 4., 5., 6.]], + [[ 8., 9., 10.], + [12., 13., 14.]]]), + tensor([[[ 3.], + [ 7.]], + [[11.], + [15.]]]), + tensor([], size=(2, 2, 0))) + """ + +def dstack( + tensors: tuple[Tensor, ...] | list[Tensor] | None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + dstack(tensors, *, out=None) -> Tensor + + Stack tensors in sequence depthwise (along third axis). + + This is equivalent to concatenation along the third axis after 1-D and 2-D tensors have been reshaped by :func:`torch.atleast_3d`. + + Args: + tensors (sequence of Tensors): sequence of tensors to concatenate + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([1, 2, 3]) + >>> b = torch.tensor([4, 5, 6]) + >>> torch.dstack((a,b)) + tensor([[[1, 4], + [2, 5], + [3, 6]]]) + >>> a = torch.tensor([[1],[2],[3]]) + >>> b = torch.tensor([[4],[5],[6]]) + >>> torch.dstack((a,b)) + tensor([[[1, 4]], + [[2, 5]], + [[3, 6]]]) + """ + +def embedding( + weight: Tensor, + indices: Tensor, + padding_idx: _int | SymInt = -1, + scale_grad_by_freq: _bool = False, + sparse: _bool = False, +) -> Tensor: ... +@overload +def embedding_bag( + weight: Tensor, + indices: Tensor, + offsets: Tensor, + scale_grad_by_freq: _bool, + mode: _int, + sparse: _bool, + per_sample_weights: Tensor | None, + include_last_offset: _bool, + padding_idx: _int | None, +) -> tuple[Tensor, Tensor, Tensor, Tensor]: ... +@overload +def embedding_bag( + weight: Tensor, + indices: Tensor, + offsets: Tensor, + scale_grad_by_freq: _bool = False, + mode: _int = 0, + sparse: _bool = False, + per_sample_weights: Tensor | None = None, + include_last_offset: _bool = False, +) -> tuple[Tensor, Tensor, Tensor, Tensor]: ... +def embedding_renorm_( + input: Tensor, + indices: Tensor, + max_norm: _float, + norm_type: _float, +) -> Tensor: ... +@overload +def empty( + size: Sequence[_int | SymInt], + *, + memory_format: memory_format | None = None, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + empty(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False, memory_format=torch.contiguous_format) -> Tensor + + Returns a tensor filled with uninitialized data. The shape of the tensor is + defined by the variable argument :attr:`size`. + + .. note:: + If :func:`torch.use_deterministic_algorithms()` and + :attr:`torch.utils.deterministic.fill_uninitialized_memory` are both set to + ``True``, the output tensor is initialized to prevent any possible + nondeterministic behavior from using the data as an input to an operation. + Floating point and complex tensors are filled with NaN, and integer tensors + are filled with the maximum value. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.contiguous_format``. + + Example:: + + >>> torch.empty((2,3), dtype=torch.int64) + tensor([[ 9.4064e+13, 2.8000e+01, 9.3493e+13], + [ 7.5751e+18, 7.1428e+18, 7.5955e+18]]) + """ + +@overload +def empty( + *size: _int | SymInt, + memory_format: memory_format | None = None, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + empty(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False, memory_format=torch.contiguous_format) -> Tensor + + Returns a tensor filled with uninitialized data. The shape of the tensor is + defined by the variable argument :attr:`size`. + + .. note:: + If :func:`torch.use_deterministic_algorithms()` and + :attr:`torch.utils.deterministic.fill_uninitialized_memory` are both set to + ``True``, the output tensor is initialized to prevent any possible + nondeterministic behavior from using the data as an input to an operation. + Floating point and complex tensors are filled with NaN, and integer tensors + are filled with the maximum value. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.contiguous_format``. + + Example:: + + >>> torch.empty((2,3), dtype=torch.int64) + tensor([[ 9.4064e+13, 2.8000e+01, 9.3493e+13], + [ 7.5751e+18, 7.1428e+18, 7.5955e+18]]) + """ + +@overload +def empty( + size: _size, + *, + names: Sequence[str | EllipsisType | None] | None, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + empty(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False, memory_format=torch.contiguous_format) -> Tensor + + Returns a tensor filled with uninitialized data. The shape of the tensor is + defined by the variable argument :attr:`size`. + + .. note:: + If :func:`torch.use_deterministic_algorithms()` and + :attr:`torch.utils.deterministic.fill_uninitialized_memory` are both set to + ``True``, the output tensor is initialized to prevent any possible + nondeterministic behavior from using the data as an input to an operation. + Floating point and complex tensors are filled with NaN, and integer tensors + are filled with the maximum value. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.contiguous_format``. + + Example:: + + >>> torch.empty((2,3), dtype=torch.int64) + tensor([[ 9.4064e+13, 2.8000e+01, 9.3493e+13], + [ 7.5751e+18, 7.1428e+18, 7.5955e+18]]) + """ + +@overload +def empty( + *size: _int, + names: Sequence[str | EllipsisType | None] | None, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + empty(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False, memory_format=torch.contiguous_format) -> Tensor + + Returns a tensor filled with uninitialized data. The shape of the tensor is + defined by the variable argument :attr:`size`. + + .. note:: + If :func:`torch.use_deterministic_algorithms()` and + :attr:`torch.utils.deterministic.fill_uninitialized_memory` are both set to + ``True``, the output tensor is initialized to prevent any possible + nondeterministic behavior from using the data as an input to an operation. + Floating point and complex tensors are filled with NaN, and integer tensors + are filled with the maximum value. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.contiguous_format``. + + Example:: + + >>> torch.empty((2,3), dtype=torch.int64) + tensor([[ 9.4064e+13, 2.8000e+01, 9.3493e+13], + [ 7.5751e+18, 7.1428e+18, 7.5955e+18]]) + """ + +def empty_like( + input: Tensor, + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + empty_like(input, *, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns an uninitialized tensor with the same size as :attr:`input`. + ``torch.empty_like(input)`` is equivalent to + ``torch.empty(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``. + + .. note:: + If :func:`torch.use_deterministic_algorithms()` and + :attr:`torch.utils.deterministic.fill_uninitialized_memory` are both set to + ``True``, the output tensor is initialized to prevent any possible + nondeterministic behavior from using the data as an input to an operation. + Floating point and complex tensors are filled with NaN, and integer tensors + are filled with the maximum value. + + When ``torch.preserve_format`` is used: + If the input tensor is dense (i.e., non-overlapping strided), + its memory format (including strides) is retained. + Otherwise (e.g., a non-dense view like a stepped slice), + the output is converted to the dense format. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + + Example:: + + >>> a=torch.empty((2,3), dtype=torch.int32, device = 'cuda') + >>> torch.empty_like(a) + tensor([[0, 0, 0], + [0, 0, 0]], device='cuda:0', dtype=torch.int32) + """ + +def empty_permuted( + size: Sequence[_int | SymInt], + physical_layout: _size, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + empty_permuted(size, physical_layout, *, dtype=None, layout=None, device=None, requires_grad=False, pin_memory=False) -> Tensor + + Creates an uninitialized, non-overlapping and dense tensor with the + specified :attr:`size`, with :attr:`physical_layout` specifying how the + dimensions are physically laid out in memory (each logical dimension is listed + from outermost to innermost). :attr:`physical_layout` is a generalization + of NCHW/NHWC notation: if each dimension is assigned a number according to + what order they occur in size (N=0, C=1, H=2, W=3), then NCHW is ``(0, 1, 2, 3)`` + while NHWC is ``(0, 2, 3, 1)``. Equivalently, the strides of the output + tensor ``t`` are such that ``t.stride(physical_layout[i]) == contiguous_strides[i]`` + (notably, this function is *not* equivalent to ``torch.empty(size).permute(physical_layout)``). + + Unlike :func:`torch.empty_strided`, this is guaranteed to produce a dense + tensor with no overlaps. If possible, prefer using this function over + :func:`torch.empty_strided` or manual use of :func:`torch.as_strided`. + + .. note:: + If :func:`torch.use_deterministic_algorithms()` and + :attr:`torch.utils.deterministic.fill_uninitialized_memory` are both set to + ``True``, the output tensor is initialized to prevent any possible + nondeterministic behavior from using the data as an input to an operation. + Floating point and complex tensors are filled with NaN, and integer tensors + are filled with the maximum value. + + Args: + size (tuple of int): the shape of the output tensor + physical_layout (tuple of int): the ordering of dimensions physically in memory + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Examples: + + >>> torch.empty((2, 3, 5, 7)).stride() + (105, 35, 7, 1) + >>> torch.empty_permuted((2, 3, 5, 7), (0, 1, 2, 3)).stride() + (105, 35, 7, 1) + >>> torch.empty((2, 3, 5, 7), memory_format=torch.channels_last).stride() + (105, 1, 21, 3) + >>> torch.empty_permuted((2, 3, 5, 7), (0, 2, 3, 1)).stride() + (105, 1, 21, 3) + >>> torch.empty_permuted((2, 3, 5, 7), (0, 2, 3, 1)).dim_order() + (0, 2, 3, 1) + """ + +def empty_quantized( + size: _size, + qtensor: Tensor, + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: ... +def empty_strided( + size: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + empty_strided(size, stride, *, dtype=None, layout=None, device=None, requires_grad=False, pin_memory=False) -> Tensor + + Creates a tensor with the specified :attr:`size` and :attr:`stride` and filled with undefined data. + + .. warning:: + If the constructed tensor is "overlapped" (with multiple indices referring to the same element + in memory) its behavior is undefined. + + .. note:: + If :func:`torch.use_deterministic_algorithms()` and + :attr:`torch.utils.deterministic.fill_uninitialized_memory` are both set to + ``True``, the output tensor is initialized to prevent any possible + nondeterministic behavior from using the data as an input to an operation. + Floating point and complex tensors are filled with NaN, and integer tensors + are filled with the maximum value. + + Args: + size (tuple of int): the shape of the output tensor + stride (tuple of int): the strides of the output tensor + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> a = torch.empty_strided((2, 3), (1, 2)) + >>> a + tensor([[8.9683e-44, 4.4842e-44, 5.1239e+07], + [0.0000e+00, 0.0000e+00, 3.0705e-41]]) + >>> a.stride() + (1, 2) + >>> a.size() + torch.Size([2, 3]) + """ + +@overload +def eq( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + eq(input, other, *, out=None) -> Tensor + + Computes element-wise equality + + The second argument can be a number or a tensor whose shape is + :ref:`broadcastable ` with the first argument. + + Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is equal to :attr:`other` and False elsewhere + + Example:: + + >>> torch.eq(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[ True, False], + [False, True]]) + """ + +@overload +def eq( + input: Tensor, + other: Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + eq(input, other, *, out=None) -> Tensor + + Computes element-wise equality + + The second argument can be a number or a tensor whose shape is + :ref:`broadcastable ` with the first argument. + + Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is equal to :attr:`other` and False elsewhere + + Example:: + + >>> torch.eq(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[ True, False], + [False, True]]) + """ + +def equal(input: Tensor, other: Tensor) -> _bool: + r""" + equal(input, other) -> bool + + ``True`` if two tensors have the same size and elements, ``False`` otherwise. + + .. note:: + + Tensors containing NaNs are never equal to each other. Additionally, this function does not + differentiate between the data types of the tensors during comparison. For more thorough tensor checks, + use :meth:`torch.testing.assert_close`. + + Example:: + + >>> torch.equal(torch.tensor([1, 2]), torch.tensor([1, 2])) + True + >>> torch.equal(torch.tensor([3, torch.nan]), torch.tensor([3, torch.nan])) + False + >>> torch.equal(torch.tensor([1, 2, 3], dtype=torch.int32), torch.tensor([1, 2, 3], dtype=torch.float32)) + True + """ + +def erf(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + erf(input, *, out=None) -> Tensor + + Alias for :func:`torch.special.erf`. + """ + +def erf_(input: Tensor) -> Tensor: ... +def erfc(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + erfc(input, *, out=None) -> Tensor + + Alias for :func:`torch.special.erfc`. + """ + +def erfc_(input: Tensor) -> Tensor: ... +def erfinv(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + erfinv(input, *, out=None) -> Tensor + + Alias for :func:`torch.special.erfinv`. + """ + +def exp(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + exp(input, *, out=None) -> Tensor + + Returns a new tensor with the exponential of the elements + of the input tensor :attr:`input`. + + .. math:: + y_{i} = e^{x_{i}} + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.exp(torch.tensor([0, math.log(2.)])) + tensor([ 1., 2.]) + """ + +def exp2(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + exp2(input, *, out=None) -> Tensor + + Alias for :func:`torch.special.exp2`. + """ + +def exp2_(input: Tensor) -> Tensor: ... +def exp_(input: Tensor) -> Tensor: ... +def expand_copy( + input: Tensor, + size: Sequence[_int | SymInt], + *, + implicit: _bool = False, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.Tensor.expand`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def expm1(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + expm1(input, *, out=None) -> Tensor + + Alias for :func:`torch.special.expm1`. + """ + +def expm1_(input: Tensor) -> Tensor: ... +@overload +def eye( + n: _int | SymInt, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + eye(n, m=None, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a 2-D tensor with ones on the diagonal and zeros elsewhere. + + Args: + n (int): the number of rows + m (int, optional): the number of columns with default being :attr:`n` + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 2-D tensor with ones on the diagonal and zeros elsewhere + + Example:: + + >>> torch.eye(3) + tensor([[ 1., 0., 0.], + [ 0., 1., 0.], + [ 0., 0., 1.]]) + """ + +@overload +def eye( + n: _int | SymInt, + m: _int | SymInt, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + eye(n, m=None, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a 2-D tensor with ones on the diagonal and zeros elsewhere. + + Args: + n (int): the number of rows + m (int, optional): the number of columns with default being :attr:`n` + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 2-D tensor with ones on the diagonal and zeros elsewhere + + Example:: + + >>> torch.eye(3) + tensor([[ 1., 0., 0.], + [ 0., 1., 0.], + [ 0., 0., 1.]]) + """ + +def fake_quantize_per_channel_affine( + input: Tensor, + scale: Tensor, + zero_point: Tensor, + axis: _int, + quant_min: _int, + quant_max: _int, +) -> Tensor: + r""" + fake_quantize_per_channel_affine(input, scale, zero_point, axis, quant_min, quant_max) -> Tensor + + Returns a new tensor with the data in :attr:`input` fake quantized per channel using :attr:`scale`, + :attr:`zero_point`, :attr:`quant_min` and :attr:`quant_max`, across the channel specified by :attr:`axis`. + + .. math:: + \text{output} = ( + min( + \text{quant\_max}, + max( + \text{quant\_min}, + \text{std::nearby\_int}(\text{input} / \text{scale}) + \text{zero\_point} + ) + ) - \text{zero\_point} + ) \times \text{scale} + + Args: + input (Tensor): the input value(s), in ``torch.float32`` + scale (Tensor): quantization scale, per channel in ``torch.float32`` + zero_point (Tensor): quantization zero_point, per channel in ``torch.int32`` or ``torch.half`` or ``torch.float32`` + axis (int32): channel axis + quant_min (int64): lower bound of the quantized domain + quant_max (int64): upper bound of the quantized domain + + Returns: + Tensor: A newly fake_quantized per channel ``torch.float32`` tensor + + Example:: + + >>> x = torch.randn(2, 2, 2) + >>> x + tensor([[[-0.2525, -0.0466], + [ 0.3491, -0.2168]], + + [[-0.5906, 1.6258], + [ 0.6444, -0.0542]]]) + >>> scales = (torch.randn(2) + 1) * 0.05 + >>> scales + tensor([0.0475, 0.0486]) + >>> zero_points = torch.zeros(2).to(torch.int32) + >>> zero_points + tensor([0, 0]) + >>> torch.fake_quantize_per_channel_affine(x, scales, zero_points, 1, 0, 255) + tensor([[[0.0000, 0.0000], + [0.3405, 0.0000]], + + [[0.0000, 1.6134], + [0.6323, 0.0000]]]) + """ + +@overload +def fake_quantize_per_tensor_affine( + input: Tensor, + scale: _float, + zero_point: _int, + quant_min: _int, + quant_max: _int, +) -> Tensor: + r""" + fake_quantize_per_tensor_affine(input, scale, zero_point, quant_min, quant_max) -> Tensor + + Returns a new tensor with the data in :attr:`input` fake quantized using :attr:`scale`, + :attr:`zero_point`, :attr:`quant_min` and :attr:`quant_max`. + + .. math:: + \text{output} = ( + min( + \text{quant\_max}, + max( + \text{quant\_min}, + \text{std::nearby\_int}(\text{input} / \text{scale}) + \text{zero\_point} + ) + ) - \text{zero\_point} + ) \times \text{scale} + + Args: + input (Tensor): the input value(s), ``torch.float32`` tensor + scale (double scalar or ``float32`` Tensor): quantization scale + zero_point (int64 scalar or ``int32`` Tensor): quantization zero_point + quant_min (int64): lower bound of the quantized domain + quant_max (int64): upper bound of the quantized domain + + Returns: + Tensor: A newly fake_quantized ``torch.float32`` tensor + + Example:: + + >>> x = torch.randn(4) + >>> x + tensor([ 0.0552, 0.9730, 0.3973, -1.0780]) + >>> torch.fake_quantize_per_tensor_affine(x, 0.1, 0, 0, 255) + tensor([0.1000, 1.0000, 0.4000, 0.0000]) + >>> torch.fake_quantize_per_tensor_affine(x, torch.tensor(0.1), torch.tensor(0), 0, 255) + tensor([0.1000, 1.0000, 0.4000, 0.0000]) + """ + +@overload +def fake_quantize_per_tensor_affine( + input: Tensor, + scale: Tensor, + zero_point: Tensor, + quant_min: _int, + quant_max: _int, +) -> Tensor: + r""" + fake_quantize_per_tensor_affine(input, scale, zero_point, quant_min, quant_max) -> Tensor + + Returns a new tensor with the data in :attr:`input` fake quantized using :attr:`scale`, + :attr:`zero_point`, :attr:`quant_min` and :attr:`quant_max`. + + .. math:: + \text{output} = ( + min( + \text{quant\_max}, + max( + \text{quant\_min}, + \text{std::nearby\_int}(\text{input} / \text{scale}) + \text{zero\_point} + ) + ) - \text{zero\_point} + ) \times \text{scale} + + Args: + input (Tensor): the input value(s), ``torch.float32`` tensor + scale (double scalar or ``float32`` Tensor): quantization scale + zero_point (int64 scalar or ``int32`` Tensor): quantization zero_point + quant_min (int64): lower bound of the quantized domain + quant_max (int64): upper bound of the quantized domain + + Returns: + Tensor: A newly fake_quantized ``torch.float32`` tensor + + Example:: + + >>> x = torch.randn(4) + >>> x + tensor([ 0.0552, 0.9730, 0.3973, -1.0780]) + >>> torch.fake_quantize_per_tensor_affine(x, 0.1, 0, 0, 255) + tensor([0.1000, 1.0000, 0.4000, 0.0000]) + >>> torch.fake_quantize_per_tensor_affine(x, torch.tensor(0.1), torch.tensor(0), 0, 255) + tensor([0.1000, 1.0000, 0.4000, 0.0000]) + """ + +@overload +def fbgemm_linear_fp16_weight( + input: Tensor, + packed_weight: Tensor, + bias: Tensor, +) -> Tensor: ... +@overload +def fbgemm_linear_fp16_weight( + input: Tensor, + packed_weight: Tensor, + bias: Tensor, + output: Tensor, +) -> Tensor: ... +@overload +def fbgemm_linear_fp16_weight_fp32_activation( + input: Tensor, + packed_weight: Tensor, + bias: Tensor | None, +) -> Tensor: ... +@overload +def fbgemm_linear_fp16_weight_fp32_activation( + input: Tensor, + packed_weight: Tensor, + bias: Tensor | None, + output: Tensor, +) -> Tensor: ... +def fbgemm_linear_int8_weight( + input: Tensor, + weight: Tensor, + packed: Tensor, + col_offsets: Tensor, + weight_scale: Number | _complex, + weight_zero_point: Number | _complex, + bias: Tensor, +) -> Tensor: ... +def fbgemm_linear_int8_weight_fp32_activation( + input: Tensor, + weight: Tensor, + packed: Tensor, + col_offsets: Tensor, + weight_scale: Number | _complex, + weight_zero_point: Number | _complex, + bias: Tensor, +) -> Tensor: ... +def fbgemm_linear_quantize_weight( + input: Tensor, +) -> tuple[Tensor, Tensor, _float, _int]: ... +def fbgemm_pack_gemm_matrix_fp16(input: Tensor) -> Tensor: ... +@overload +def fbgemm_pack_quantized_matrix(input: Tensor) -> Tensor: ... +@overload +def fbgemm_pack_quantized_matrix(input: Tensor, K: _int, N: _int) -> Tensor: ... +def feature_alpha_dropout(input: Tensor, p: _float, train: _bool) -> Tensor: ... +def feature_alpha_dropout_( + input: Tensor, + p: _float, + train: _bool, +) -> Tensor: ... +def feature_dropout(input: Tensor, p: _float, train: _bool) -> Tensor: ... +def feature_dropout_(input: Tensor, p: _float, train: _bool) -> Tensor: ... +@overload +def fill(input: Tensor, value: Tensor) -> Tensor: ... +@overload +def fill(input: Tensor, value: Number | _complex) -> Tensor: ... +@overload +def fill_(input: Tensor, value: Tensor) -> Tensor: ... +@overload +def fill_(input: Tensor, value: Number | _complex) -> Tensor: ... +def fix(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + fix(input, *, out=None) -> Tensor + + Alias for :func:`torch.trunc` + """ + +def fix_(input: Tensor) -> Tensor: ... +@overload +def flatten( + input: Tensor, + start_dim: _int = 0, + end_dim: _int = -1, +) -> Tensor: + r""" + flatten(input, start_dim=0, end_dim=-1) -> Tensor + + Flattens :attr:`input` by reshaping it into a one-dimensional tensor. If :attr:`start_dim` or :attr:`end_dim` + are passed, only dimensions starting with :attr:`start_dim` and ending with :attr:`end_dim` are flattened. + The order of elements in :attr:`input` is unchanged. + + Unlike NumPy's flatten, which always copies input's data, this function may return the original object, a view, + or copy. If no dimensions are flattened, then the original object :attr:`input` is returned. Otherwise, if input can + be viewed as the flattened shape, then that view is returned. Finally, only if the input cannot be viewed as the + flattened shape is input's data copied. See :meth:`torch.Tensor.view` for details on when a view will be returned. + + .. note:: + Flattening a zero-dimensional tensor will return a one-dimensional view. + + Args: + input (Tensor): the input tensor. + start_dim (int): the first dim to flatten + end_dim (int): the last dim to flatten + + Example:: + + >>> t = torch.tensor([[[1, 2], + ... [3, 4]], + ... [[5, 6], + ... [7, 8]]]) + >>> torch.flatten(t) + tensor([1, 2, 3, 4, 5, 6, 7, 8]) + >>> torch.flatten(t, start_dim=1) + tensor([[1, 2, 3, 4], + [5, 6, 7, 8]]) + """ + +@overload +def flatten( + input: Tensor, + start_dim: _int, + end_dim: _int, + out_dim: str | EllipsisType | None, +) -> Tensor: + r""" + flatten(input, start_dim=0, end_dim=-1) -> Tensor + + Flattens :attr:`input` by reshaping it into a one-dimensional tensor. If :attr:`start_dim` or :attr:`end_dim` + are passed, only dimensions starting with :attr:`start_dim` and ending with :attr:`end_dim` are flattened. + The order of elements in :attr:`input` is unchanged. + + Unlike NumPy's flatten, which always copies input's data, this function may return the original object, a view, + or copy. If no dimensions are flattened, then the original object :attr:`input` is returned. Otherwise, if input can + be viewed as the flattened shape, then that view is returned. Finally, only if the input cannot be viewed as the + flattened shape is input's data copied. See :meth:`torch.Tensor.view` for details on when a view will be returned. + + .. note:: + Flattening a zero-dimensional tensor will return a one-dimensional view. + + Args: + input (Tensor): the input tensor. + start_dim (int): the first dim to flatten + end_dim (int): the last dim to flatten + + Example:: + + >>> t = torch.tensor([[[1, 2], + ... [3, 4]], + ... [[5, 6], + ... [7, 8]]]) + >>> torch.flatten(t) + tensor([1, 2, 3, 4, 5, 6, 7, 8]) + >>> torch.flatten(t, start_dim=1) + tensor([[1, 2, 3, 4], + [5, 6, 7, 8]]) + """ + +@overload +def flatten( + input: Tensor, + start_dim: str | EllipsisType | None, + end_dim: str | EllipsisType | None, + out_dim: str | EllipsisType | None, +) -> Tensor: + r""" + flatten(input, start_dim=0, end_dim=-1) -> Tensor + + Flattens :attr:`input` by reshaping it into a one-dimensional tensor. If :attr:`start_dim` or :attr:`end_dim` + are passed, only dimensions starting with :attr:`start_dim` and ending with :attr:`end_dim` are flattened. + The order of elements in :attr:`input` is unchanged. + + Unlike NumPy's flatten, which always copies input's data, this function may return the original object, a view, + or copy. If no dimensions are flattened, then the original object :attr:`input` is returned. Otherwise, if input can + be viewed as the flattened shape, then that view is returned. Finally, only if the input cannot be viewed as the + flattened shape is input's data copied. See :meth:`torch.Tensor.view` for details on when a view will be returned. + + .. note:: + Flattening a zero-dimensional tensor will return a one-dimensional view. + + Args: + input (Tensor): the input tensor. + start_dim (int): the first dim to flatten + end_dim (int): the last dim to flatten + + Example:: + + >>> t = torch.tensor([[[1, 2], + ... [3, 4]], + ... [[5, 6], + ... [7, 8]]]) + >>> torch.flatten(t) + tensor([1, 2, 3, 4, 5, 6, 7, 8]) + >>> torch.flatten(t, start_dim=1) + tensor([[1, 2, 3, 4], + [5, 6, 7, 8]]) + """ + +@overload +def flatten( + input: Tensor, + dims: Sequence[str | EllipsisType | None], + out_dim: str | EllipsisType | None, +) -> Tensor: + r""" + flatten(input, start_dim=0, end_dim=-1) -> Tensor + + Flattens :attr:`input` by reshaping it into a one-dimensional tensor. If :attr:`start_dim` or :attr:`end_dim` + are passed, only dimensions starting with :attr:`start_dim` and ending with :attr:`end_dim` are flattened. + The order of elements in :attr:`input` is unchanged. + + Unlike NumPy's flatten, which always copies input's data, this function may return the original object, a view, + or copy. If no dimensions are flattened, then the original object :attr:`input` is returned. Otherwise, if input can + be viewed as the flattened shape, then that view is returned. Finally, only if the input cannot be viewed as the + flattened shape is input's data copied. See :meth:`torch.Tensor.view` for details on when a view will be returned. + + .. note:: + Flattening a zero-dimensional tensor will return a one-dimensional view. + + Args: + input (Tensor): the input tensor. + start_dim (int): the first dim to flatten + end_dim (int): the last dim to flatten + + Example:: + + >>> t = torch.tensor([[[1, 2], + ... [3, 4]], + ... [[5, 6], + ... [7, 8]]]) + >>> torch.flatten(t) + tensor([1, 2, 3, 4, 5, 6, 7, 8]) + >>> torch.flatten(t, start_dim=1) + tensor([[1, 2, 3, 4], + [5, 6, 7, 8]]) + """ + +def flip(input: Tensor, dims: _size) -> Tensor: + r""" + flip(input, dims) -> Tensor + + Reverse the order of an n-D tensor along given axis in dims. + + .. note:: + `torch.flip` makes a copy of :attr:`input`'s data. This is different from NumPy's `np.flip`, + which returns a view in constant time. Since copying a tensor's data is more work than viewing that data, + `torch.flip` is expected to be slower than `np.flip`. + + Args: + input (Tensor): the input tensor. + dims (a list or tuple): axis to flip on + + Example:: + + >>> x = torch.arange(8).view(2, 2, 2) + >>> x + tensor([[[ 0, 1], + [ 2, 3]], + + [[ 4, 5], + [ 6, 7]]]) + >>> torch.flip(x, [0, 1]) + tensor([[[ 6, 7], + [ 4, 5]], + + [[ 2, 3], + [ 0, 1]]]) + """ + +def fliplr(input: Tensor) -> Tensor: + r""" + fliplr(input) -> Tensor + + Flip tensor in the left/right direction, returning a new tensor. + + Flip the entries in each row in the left/right direction. + Columns are preserved, but appear in a different order than before. + + Note: + Requires the tensor to be at least 2-D. + + .. note:: + `torch.fliplr` makes a copy of :attr:`input`'s data. This is different from NumPy's `np.fliplr`, + which returns a view in constant time. Since copying a tensor's data is more work than viewing that data, + `torch.fliplr` is expected to be slower than `np.fliplr`. + + Args: + input (Tensor): Must be at least 2-dimensional. + + Example:: + + >>> x = torch.arange(4).view(2, 2) + >>> x + tensor([[0, 1], + [2, 3]]) + >>> torch.fliplr(x) + tensor([[1, 0], + [3, 2]]) + """ + +def flipud(input: Tensor) -> Tensor: + r""" + flipud(input) -> Tensor + + Flip tensor in the up/down direction, returning a new tensor. + + Flip the entries in each column in the up/down direction. + Rows are preserved, but appear in a different order than before. + + Note: + Requires the tensor to be at least 1-D. + + .. note:: + `torch.flipud` makes a copy of :attr:`input`'s data. This is different from NumPy's `np.flipud`, + which returns a view in constant time. Since copying a tensor's data is more work than viewing that data, + `torch.flipud` is expected to be slower than `np.flipud`. + + Args: + input (Tensor): Must be at least 1-dimensional. + + Example:: + + >>> x = torch.arange(4).view(2, 2) + >>> x + tensor([[0, 1], + [2, 3]]) + >>> torch.flipud(x) + tensor([[2, 3], + [0, 1]]) + """ + +@overload +def float_power( + input: Tensor, + exponent: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + float_power(input, exponent, *, out=None) -> Tensor + + Raises :attr:`input` to the power of :attr:`exponent`, elementwise, in double precision. + If neither input is complex returns a ``torch.float64`` tensor, + and if one or more inputs is complex returns a ``torch.complex128`` tensor. + + .. note:: + This function always computes in double precision, unlike :func:`torch.pow`, + which implements more typical :ref:`type promotion `. + This is useful when the computation needs to be performed in a wider or more precise dtype, + or the results of the computation may contain fractional values not representable in the input dtypes, + like when an integer base is raised to a negative integer exponent. + + Args: + input (Tensor or Number): the base value(s) + exponent (Tensor or Number): the exponent value(s) + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randint(10, (4,)) + >>> a + tensor([6, 4, 7, 1]) + >>> torch.float_power(a, 2) + tensor([36., 16., 49., 1.], dtype=torch.float64) + + >>> a = torch.arange(1, 5) + >>> a + tensor([ 1, 2, 3, 4]) + >>> exp = torch.tensor([2, -3, 4, -5]) + >>> exp + tensor([ 2, -3, 4, -5]) + >>> torch.float_power(a, exp) + tensor([1.0000e+00, 1.2500e-01, 8.1000e+01, 9.7656e-04], dtype=torch.float64) + """ + +@overload +def float_power( + self: Number | _complex, + exponent: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + float_power(input, exponent, *, out=None) -> Tensor + + Raises :attr:`input` to the power of :attr:`exponent`, elementwise, in double precision. + If neither input is complex returns a ``torch.float64`` tensor, + and if one or more inputs is complex returns a ``torch.complex128`` tensor. + + .. note:: + This function always computes in double precision, unlike :func:`torch.pow`, + which implements more typical :ref:`type promotion `. + This is useful when the computation needs to be performed in a wider or more precise dtype, + or the results of the computation may contain fractional values not representable in the input dtypes, + like when an integer base is raised to a negative integer exponent. + + Args: + input (Tensor or Number): the base value(s) + exponent (Tensor or Number): the exponent value(s) + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randint(10, (4,)) + >>> a + tensor([6, 4, 7, 1]) + >>> torch.float_power(a, 2) + tensor([36., 16., 49., 1.], dtype=torch.float64) + + >>> a = torch.arange(1, 5) + >>> a + tensor([ 1, 2, 3, 4]) + >>> exp = torch.tensor([2, -3, 4, -5]) + >>> exp + tensor([ 2, -3, 4, -5]) + >>> torch.float_power(a, exp) + tensor([1.0000e+00, 1.2500e-01, 8.1000e+01, 9.7656e-04], dtype=torch.float64) + """ + +@overload +def float_power( + input: Tensor, + exponent: Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + float_power(input, exponent, *, out=None) -> Tensor + + Raises :attr:`input` to the power of :attr:`exponent`, elementwise, in double precision. + If neither input is complex returns a ``torch.float64`` tensor, + and if one or more inputs is complex returns a ``torch.complex128`` tensor. + + .. note:: + This function always computes in double precision, unlike :func:`torch.pow`, + which implements more typical :ref:`type promotion `. + This is useful when the computation needs to be performed in a wider or more precise dtype, + or the results of the computation may contain fractional values not representable in the input dtypes, + like when an integer base is raised to a negative integer exponent. + + Args: + input (Tensor or Number): the base value(s) + exponent (Tensor or Number): the exponent value(s) + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randint(10, (4,)) + >>> a + tensor([6, 4, 7, 1]) + >>> torch.float_power(a, 2) + tensor([36., 16., 49., 1.], dtype=torch.float64) + + >>> a = torch.arange(1, 5) + >>> a + tensor([ 1, 2, 3, 4]) + >>> exp = torch.tensor([2, -3, 4, -5]) + >>> exp + tensor([ 2, -3, 4, -5]) + >>> torch.float_power(a, exp) + tensor([1.0000e+00, 1.2500e-01, 8.1000e+01, 9.7656e-04], dtype=torch.float64) + """ + +def floor(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + floor(input, *, out=None) -> Tensor + + Returns a new tensor with the floor of the elements of :attr:`input`, + the largest integer less than or equal to each element. + + For integer inputs, follows the array-api convention of returning a + copy of the input tensor. + + .. math:: + \text{out}_{i} = \left\lfloor \text{input}_{i} \right\rfloor + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-0.8166, 1.5308, -0.2530, -0.2091]) + >>> torch.floor(a) + tensor([-1., 1., -1., -1.]) + """ + +def floor_(input: Tensor) -> Tensor: ... +def floor_divide( + input: Tensor | Number, + other: Tensor | Number, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + floor_divide(input, other, *, out=None) -> Tensor + + .. note:: + + Before PyTorch 1.13 :func:`torch.floor_divide` incorrectly performed + truncation division. To restore the previous behavior use + :func:`torch.div` with ``rounding_mode='trunc'``. + + Computes :attr:`input` divided by :attr:`other`, elementwise, and floors + the result. + + .. math:: + \text{{out}}_i = \text{floor} \left( \frac{{\text{{input}}_i}}{{\text{{other}}_i}} \right) + + + + Supports broadcasting to a common shape, type promotion, and integer and float inputs. + + Args: + input (Tensor or Number): the dividend + other (Tensor or Number): the divisor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([4.0, 3.0]) + >>> b = torch.tensor([2.0, 2.0]) + >>> torch.floor_divide(a, b) + tensor([2.0, 1.0]) + >>> torch.floor_divide(a, 1.4) + tensor([2.0, 2.0]) + """ + +def fmax( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + fmax(input, other, *, out=None) -> Tensor + + Computes the element-wise maximum of :attr:`input` and :attr:`other`. + + This is like :func:`torch.maximum` except it handles NaNs differently: + if exactly one of the two elements being compared is a NaN then the non-NaN element is taken as the maximum. + Only if both elements are NaN is NaN propagated. + + This function is a wrapper around C++'s ``std::fmax`` and is similar to NumPy's ``fmax`` function. + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer and floating-point inputs. + + Args: + input (Tensor): the input tensor. + other (Tensor): the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([9.7, float('nan'), 3.1, float('nan')]) + >>> b = torch.tensor([-2.2, 0.5, float('nan'), float('nan')]) + >>> torch.fmax(a, b) + tensor([9.7000, 0.5000, 3.1000, nan]) + """ + +def fmin( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + fmin(input, other, *, out=None) -> Tensor + + Computes the element-wise minimum of :attr:`input` and :attr:`other`. + + This is like :func:`torch.minimum` except it handles NaNs differently: + if exactly one of the two elements being compared is a NaN then the non-NaN element is taken as the minimum. + Only if both elements are NaN is NaN propagated. + + This function is a wrapper around C++'s ``std::fmin`` and is similar to NumPy's ``fmin`` function. + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer and floating-point inputs. + + Args: + input (Tensor): the input tensor. + other (Tensor): the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([2.2, float('nan'), 2.1, float('nan')]) + >>> b = torch.tensor([-9.3, 0.1, float('nan'), float('nan')]) + >>> torch.fmin(a, b) + tensor([-9.3000, 0.1000, 2.1000, nan]) + """ + +@overload +def fmod( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + fmod(input, other, *, out=None) -> Tensor + + Applies C++'s `std::fmod `_ entrywise. + The result has the same sign as the dividend :attr:`input` and its absolute value + is less than that of :attr:`other`. + + This function may be defined in terms of :func:`torch.div` as + + .. code:: python + + torch.fmod(a, b) == a - a.div(b, rounding_mode="trunc") * b + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer and float inputs. + + .. note:: + + When the divisor is zero, returns ``NaN`` for floating point dtypes + on both CPU and GPU; raises ``RuntimeError`` for integer division by + zero on CPU; Integer division by zero on GPU may return any value. + + .. note:: + + Complex inputs are not supported. In some cases, it is not mathematically + possible to satisfy the definition of a modulo operation with complex numbers. + + .. seealso:: + + :func:`torch.remainder` which implements Python's modulus operator. + This one is defined using division rounding down the result. + + Args: + input (Tensor): the dividend + other (Tensor or Scalar): the divisor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.fmod(torch.tensor([-3., -2, -1, 1, 2, 3]), 2) + tensor([-1., -0., -1., 1., 0., 1.]) + >>> torch.fmod(torch.tensor([1, 2, 3, 4, 5]), -1.5) + tensor([1.0000, 0.5000, 0.0000, 1.0000, 0.5000]) + """ + +@overload +def fmod( + input: Tensor, + other: Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + fmod(input, other, *, out=None) -> Tensor + + Applies C++'s `std::fmod `_ entrywise. + The result has the same sign as the dividend :attr:`input` and its absolute value + is less than that of :attr:`other`. + + This function may be defined in terms of :func:`torch.div` as + + .. code:: python + + torch.fmod(a, b) == a - a.div(b, rounding_mode="trunc") * b + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer and float inputs. + + .. note:: + + When the divisor is zero, returns ``NaN`` for floating point dtypes + on both CPU and GPU; raises ``RuntimeError`` for integer division by + zero on CPU; Integer division by zero on GPU may return any value. + + .. note:: + + Complex inputs are not supported. In some cases, it is not mathematically + possible to satisfy the definition of a modulo operation with complex numbers. + + .. seealso:: + + :func:`torch.remainder` which implements Python's modulus operator. + This one is defined using division rounding down the result. + + Args: + input (Tensor): the dividend + other (Tensor or Scalar): the divisor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.fmod(torch.tensor([-3., -2, -1, 1, 2, 3]), 2) + tensor([-1., -0., -1., 1., 0., 1.]) + >>> torch.fmod(torch.tensor([1, 2, 3, 4, 5]), -1.5) + tensor([1.0000, 0.5000, 0.0000, 1.0000, 0.5000]) + """ + +def frac(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + frac(input, *, out=None) -> Tensor + + Computes the fractional portion of each element in :attr:`input`. + + .. math:: + \text{out}_{i} = \text{input}_{i} - \left\lfloor |\text{input}_{i}| \right\rfloor * \operatorname{sgn}(\text{input}_{i}) + + Example:: + + >>> torch.frac(torch.tensor([1, 2.5, -3.2])) + tensor([ 0.0000, 0.5000, -0.2000]) + """ + +def frac_(input: Tensor) -> Tensor: ... +def frexp( + input: Tensor, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.frexp: + r""" + frexp(input, *, out=None) -> (Tensor mantissa, Tensor exponent) + + Decomposes :attr:`input` into mantissa and exponent tensors + such that :math:`\text{input} = \text{mantissa} \times 2^{\text{exponent}}`. + + The range of mantissa is the open interval (-1, 1). + + Supports float inputs. + + Args: + input (Tensor): the input tensor + + + Keyword args: + out (tuple, optional): the output tensors + + Example:: + + >>> x = torch.arange(9.) + >>> mantissa, exponent = torch.frexp(x) + >>> mantissa + tensor([0.0000, 0.5000, 0.5000, 0.7500, 0.5000, 0.6250, 0.7500, 0.8750, 0.5000]) + >>> exponent + tensor([0, 1, 2, 2, 3, 3, 3, 3, 4], dtype=torch.int32) + >>> torch.ldexp(mantissa, exponent) + tensor([0., 1., 2., 3., 4., 5., 6., 7., 8.]) + """ + +def frobenius_norm( + input: Tensor, + dim: _int | _size, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: ... +def from_file( + filename: str, + shared: _bool | None = None, + size: _int | None = 0, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + from_file(filename, shared=None, size=0, *, dtype=None, layout=None, device=None, pin_memory=False) + + Creates a CPU tensor with a storage backed by a memory-mapped file. + + If ``shared`` is True, then memory is shared between processes. All changes are written to the file. + If ``shared`` is False, then changes to the tensor do not affect the file. + + ``size`` is the number of elements in the Tensor. If ``shared`` is ``False``, then the file must contain + at least ``size * sizeof(dtype)`` bytes. If ``shared`` is ``True`` the file will be created if needed. + + .. note:: + Only CPU tensors can be mapped to files. + + .. note:: + For now, tensors with storages backed by a memory-mapped file cannot be created in pinned memory. + + + Args: + filename (str): file name to map + shared (bool): whether to share memory (whether ``MAP_SHARED`` or ``MAP_PRIVATE`` is passed to the + underlying `mmap(2) call `_) + size (int): number of elements in the tensor + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> t = torch.randn(2, 5, dtype=torch.float64) + >>> t.numpy().tofile('storage.pt') + >>> t_mapped = torch.from_file('storage.pt', shared=False, size=10, dtype=torch.float64) + """ + +def from_numpy(ndarray) -> Tensor: + r""" + from_numpy(ndarray) -> Tensor + + Creates a :class:`Tensor` from a :class:`numpy.ndarray`. + + The returned tensor and :attr:`ndarray` share the same memory. Modifications to + the tensor will be reflected in the :attr:`ndarray` and vice versa. The returned + tensor is not resizable. + + It currently accepts :attr:`ndarray` with dtypes of ``numpy.float64``, + ``numpy.float32``, ``numpy.float16``, ``numpy.complex64``, ``numpy.complex128``, + ``numpy.int64``, ``numpy.int32``, ``numpy.int16``, ``numpy.int8``, ``numpy.uint8``, + and ``bool``. + + .. warning:: + Writing to a tensor created from a read-only NumPy array is not supported and will result in undefined behavior. + + Example:: + + >>> a = numpy.array([1, 2, 3]) + >>> t = torch.from_numpy(a) + >>> t + tensor([ 1, 2, 3]) + >>> t[0] = -1 + >>> a + array([-1, 2, 3]) + """ + +def frombuffer( + buffer: Any, + *, + dtype: _dtype, + count: int = -1, + offset: int = 0, + requires_grad: _bool = False, +) -> Tensor: + r""" + frombuffer(buffer, *, dtype, count=-1, offset=0, requires_grad=False) -> Tensor + + Creates a 1-dimensional :class:`Tensor` from an object that implements + the Python buffer protocol. + + Skips the first :attr:`offset` bytes in the buffer, and interprets the rest of + the raw bytes as a 1-dimensional tensor of type :attr:`dtype` with :attr:`count` + elements. + + Note that either of the following must be true: + + 1. :attr:`count` is a positive non-zero number, and the total number of bytes + in the buffer is more than :attr:`offset` plus :attr:`count` times the size + (in bytes) of :attr:`dtype`. + + 2. :attr:`count` is negative, and the length (number of bytes) of the buffer + subtracted by the :attr:`offset` is a multiple of the size (in bytes) of + :attr:`dtype`. + + The returned tensor and buffer share the same memory. Modifications to + the tensor will be reflected in the buffer and vice versa. The returned + tensor is not resizable. + + .. note:: + This function increments the reference count for the object that + owns the shared memory. Therefore, such memory will not be deallocated + before the returned tensor goes out of scope. + + .. warning:: + This function's behavior is undefined when passed an object implementing + the buffer protocol whose data is not on the CPU. Doing so is likely to + cause a segmentation fault. + + .. warning:: + This function does not try to infer the :attr:`dtype` (hence, it is not + optional). Passing a different :attr:`dtype` than its source may result + in unexpected behavior. + + Args: + buffer (object): a Python object that exposes the buffer interface. + + Keyword args: + dtype (:class:`torch.dtype`): the desired data type of returned tensor. + count (int, optional): the number of desired elements to be read. + If negative, all the elements (until the end of the buffer) will be + read. Default: -1. + offset (int, optional): the number of bytes to skip at the start of + the buffer. Default: 0. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> import array + >>> a = array.array('i', [1, 2, 3]) + >>> t = torch.frombuffer(a, dtype=torch.int32) + >>> t + tensor([ 1, 2, 3]) + >>> t[0] = -1 + >>> a + array([-1, 2, 3]) + + >>> # Interprets the signed char bytes as 32-bit integers. + >>> # Each 4 signed char elements will be interpreted as + >>> # 1 signed 32-bit integer. + >>> import array + >>> a = array.array('b', [-1, 0, 0, 0]) + >>> torch.frombuffer(a, dtype=torch.int32) + tensor([255], dtype=torch.int32) + """ + +@overload +def full( + size: _size, + fill_value: Number | _complex, + *, + out: Tensor | None = None, + layout: _layout = strided, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + pin_memory: _bool = False, +) -> Tensor: + r""" + full(size, fill_value, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Creates a tensor of size :attr:`size` filled with :attr:`fill_value`. The + tensor's dtype is inferred from :attr:`fill_value`. + + Args: + size (int...): a list, tuple, or :class:`torch.Size` of integers defining the + shape of the output tensor. + fill_value (Scalar): the value to fill the output tensor with. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.full((2, 3), 3.141592) + tensor([[ 3.1416, 3.1416, 3.1416], + [ 3.1416, 3.1416, 3.1416]]) + """ + +@overload +def full( + size: _size, + fill_value: Number | _complex, + *, + names: list[str | None], + layout: _layout = strided, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + pin_memory: _bool = False, +) -> Tensor: + r""" + full(size, fill_value, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Creates a tensor of size :attr:`size` filled with :attr:`fill_value`. The + tensor's dtype is inferred from :attr:`fill_value`. + + Args: + size (int...): a list, tuple, or :class:`torch.Size` of integers defining the + shape of the output tensor. + fill_value (Scalar): the value to fill the output tensor with. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.full((2, 3), 3.141592) + tensor([[ 3.1416, 3.1416, 3.1416], + [ 3.1416, 3.1416, 3.1416]]) + """ + +@overload +def full( + size: Sequence[_int | SymInt], + fill_value: Number | _complex, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + full(size, fill_value, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Creates a tensor of size :attr:`size` filled with :attr:`fill_value`. The + tensor's dtype is inferred from :attr:`fill_value`. + + Args: + size (int...): a list, tuple, or :class:`torch.Size` of integers defining the + shape of the output tensor. + fill_value (Scalar): the value to fill the output tensor with. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.full((2, 3), 3.141592) + tensor([[ 3.1416, 3.1416, 3.1416], + [ 3.1416, 3.1416, 3.1416]]) + """ + +@overload +def full( + size: _size, + fill_value: Number | _complex, + *, + names: Sequence[str | EllipsisType | None] | None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + full(size, fill_value, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Creates a tensor of size :attr:`size` filled with :attr:`fill_value`. The + tensor's dtype is inferred from :attr:`fill_value`. + + Args: + size (int...): a list, tuple, or :class:`torch.Size` of integers defining the + shape of the output tensor. + fill_value (Scalar): the value to fill the output tensor with. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.full((2, 3), 3.141592) + tensor([[ 3.1416, 3.1416, 3.1416], + [ 3.1416, 3.1416, 3.1416]]) + """ + +def full_like( + input: Tensor, + fill_value: Number | _complex, + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + full_like(input, fill_value, \*, dtype=None, layout=torch.strided, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same size as :attr:`input` filled with :attr:`fill_value`. + ``torch.full_like(input, fill_value)`` is equivalent to + ``torch.full(input.size(), fill_value, dtype=input.dtype, layout=input.layout, device=input.device)``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + fill_value: the number to fill the output tensor with. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + + Example:: + + >>> x = torch.ones(2, 3) + >>> torch.full_like(x, 3.141592) + tensor([[ 3.1416, 3.1416, 3.1416], + [ 3.1416, 3.1416, 3.1416]]) + >>> torch.full_like(x, 7) + tensor([[7., 7., 7.], + [7., 7., 7.]]) + >>> torch.full_like(x, 0.5, dtype=torch.int32) + tensor([[0, 0, 0], + [0, 0, 0]], dtype=torch.int32) + >>> y = torch.randn(3, 4, dtype=torch.float64) + >>> torch.full_like(y, -1.0) + tensor([[-1., -1., -1., -1.], + [-1., -1., -1., -1.], + [-1., -1., -1., -1.]], dtype=torch.float64) + """ + +def fused_moving_avg_obs_fake_quant( + input: Tensor, + observer_on: Tensor, + fake_quant_on: Tensor, + running_min: Tensor, + running_max: Tensor, + scale: Tensor, + zero_point: Tensor, + averaging_const: _float, + quant_min: _int, + quant_max: _int, + ch_axis: _int, + per_row_fake_quant: _bool = False, + symmetric_quant: _bool = False, +) -> Tensor: ... +@overload +def gather( + input: Tensor, + dim: _int, + index: Tensor, + *, + sparse_grad: _bool = False, + out: Tensor | None = None, +) -> Tensor: + r""" + gather(input, dim, index, *, sparse_grad=False, out=None) -> Tensor + + Gathers values along an axis specified by `dim`. + + For a 3-D tensor the output is specified by:: + + out[i][j][k] = input[index[i][j][k]][j][k] # if dim == 0 + out[i][j][k] = input[i][index[i][j][k]][k] # if dim == 1 + out[i][j][k] = input[i][j][index[i][j][k]] # if dim == 2 + + :attr:`input` and :attr:`index` must have the same number of dimensions. + It is also required that ``index.size(d) <= input.size(d)`` for all + dimensions ``d != dim``. :attr:`out` will have the same shape as :attr:`index`. + Note that ``input`` and ``index`` do not broadcast against each other. + When :attr:`index` is empty, we always return an empty output with the same shape + without further error checking. + + Args: + input (Tensor): the source tensor + dim (int): the axis along which to index + index (LongTensor): the indices of elements to gather + + Keyword arguments: + sparse_grad (bool, optional): If ``True``, gradient w.r.t. :attr:`input` will be a sparse tensor. + out (Tensor, optional): the destination tensor + + Example:: + + >>> t = torch.tensor([[1, 2], [3, 4]]) + >>> torch.gather(t, 1, torch.tensor([[0, 0], [1, 0]])) + tensor([[ 1, 1], + [ 4, 3]]) + """ + +@overload +def gather( + input: Tensor, + dim: str | EllipsisType | None, + index: Tensor, + *, + sparse_grad: _bool = False, + out: Tensor | None = None, +) -> Tensor: + r""" + gather(input, dim, index, *, sparse_grad=False, out=None) -> Tensor + + Gathers values along an axis specified by `dim`. + + For a 3-D tensor the output is specified by:: + + out[i][j][k] = input[index[i][j][k]][j][k] # if dim == 0 + out[i][j][k] = input[i][index[i][j][k]][k] # if dim == 1 + out[i][j][k] = input[i][j][index[i][j][k]] # if dim == 2 + + :attr:`input` and :attr:`index` must have the same number of dimensions. + It is also required that ``index.size(d) <= input.size(d)`` for all + dimensions ``d != dim``. :attr:`out` will have the same shape as :attr:`index`. + Note that ``input`` and ``index`` do not broadcast against each other. + When :attr:`index` is empty, we always return an empty output with the same shape + without further error checking. + + Args: + input (Tensor): the source tensor + dim (int): the axis along which to index + index (LongTensor): the indices of elements to gather + + Keyword arguments: + sparse_grad (bool, optional): If ``True``, gradient w.r.t. :attr:`input` will be a sparse tensor. + out (Tensor, optional): the destination tensor + + Example:: + + >>> t = torch.tensor([[1, 2], [3, 4]]) + >>> torch.gather(t, 1, torch.tensor([[0, 0], [1, 0]])) + tensor([[ 1, 1], + [ 4, 3]]) + """ + +def gcd( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + gcd(input, other, *, out=None) -> Tensor + + Computes the element-wise greatest common divisor (GCD) of :attr:`input` and :attr:`other`. + + Both :attr:`input` and :attr:`other` must have integer types. + + .. note:: + This defines :math:`gcd(0, 0) = 0`. + + Args: + input (Tensor): the input tensor. + other (Tensor): the second input tensor + + Keyword arguments: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([5, 10, 15]) + >>> b = torch.tensor([3, 4, 5]) + >>> torch.gcd(a, b) + tensor([1, 2, 5]) + >>> c = torch.tensor([3]) + >>> torch.gcd(a, c) + tensor([1, 1, 3]) + """ + +def gcd_(input: Tensor, other: Tensor) -> Tensor: ... +@overload +def ge( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + ge(input, other, *, out=None) -> Tensor + + Computes :math:`\text{input} \geq \text{other}` element-wise. + + + The second argument can be a number or a tensor whose shape is + :ref:`broadcastable ` with the first argument. + + Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is greater than or equal to :attr:`other` and False elsewhere + + Example:: + + >>> torch.ge(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[True, True], [False, True]]) + """ + +@overload +def ge( + input: Tensor, + other: Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + ge(input, other, *, out=None) -> Tensor + + Computes :math:`\text{input} \geq \text{other}` element-wise. + + + The second argument can be a number or a tensor whose shape is + :ref:`broadcastable ` with the first argument. + + Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is greater than or equal to :attr:`other` and False elsewhere + + Example:: + + >>> torch.ge(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[True, True], [False, True]]) + """ + +def geqrf( + input: Tensor, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.geqrf: + r""" + geqrf(input, *, out=None) -> (Tensor, Tensor) + + This is a low-level function for calling LAPACK's geqrf directly. This function + returns a namedtuple (a, tau) as defined in `LAPACK documentation for geqrf`_ . + + Computes a QR decomposition of :attr:`input`. + Both `Q` and `R` matrices are stored in the same output tensor `a`. + The elements of `R` are stored on and above the diagonal. + Elementary reflectors (or Householder vectors) implicitly defining matrix `Q` + are stored below the diagonal. + The results of this function can be used together with :func:`torch.linalg.householder_product` + to obtain the `Q` matrix or + with :func:`torch.ormqr`, which uses an implicit representation of the `Q` matrix, + for an efficient matrix-matrix multiplication. + + See `LAPACK documentation for geqrf`_ for further details. + + .. note:: + See also :func:`torch.linalg.qr`, which computes Q and R matrices, and :func:`torch.linalg.lstsq` + with the ``driver="gels"`` option for a function that can solve matrix equations using a QR decomposition. + + Args: + input (Tensor): the input matrix + + Keyword args: + out (tuple, optional): the output tuple of (Tensor, Tensor). Ignored if `None`. Default: `None`. + + .. _LAPACK documentation for geqrf: + http://www.netlib.org/lapack/explore-html/df/dc5/group__variants_g_ecomputational_ga3766ea903391b5cf9008132f7440ec7b.html + """ + +def ger( + input: Tensor, + vec2: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + ger(input, vec2, *, out=None) -> Tensor + + Alias of :func:`torch.outer`. + + .. warning:: + This function is deprecated and will be removed in a future PyTorch release. + Use :func:`torch.outer` instead. + """ + +def get_default_dtype() -> _dtype: + r""" + get_default_dtype() -> torch.dtype + + Get the current default floating point :class:`torch.dtype`. + + Example:: + + >>> torch.get_default_dtype() # initial default for floating point is torch.float32 + torch.float32 + >>> torch.set_default_dtype(torch.float64) + >>> torch.get_default_dtype() # default is now changed to torch.float64 + torch.float64 + """ + +def get_num_interop_threads() -> _int: + r""" + get_num_interop_threads() -> int + + Returns the number of threads used for inter-op parallelism on CPU + (e.g. in JIT interpreter) + """ + +def get_num_threads() -> _int: + r""" + get_num_threads() -> int + + Returns the number of threads used for parallelizing CPU operations + """ + +@overload +def gradient( + input: Tensor, + *, + spacing: Number | _complex | None = None, + dim: _int | None = None, + edge_order: _int = 1, +) -> tuple[Tensor, ...]: + r""" + gradient(input, *, spacing=1, dim=None, edge_order=1) -> List of Tensors + + Estimates the gradient of a function :math:`g : \mathbb{R}^n \rightarrow \mathbb{R}` in + one or more dimensions using the `second-order accurate central differences method + `_ and + either first or second order estimates at the boundaries. + + The gradient of :math:`g` is estimated using samples. By default, when :attr:`spacing` is not + specified, the samples are entirely described by :attr:`input`, and the mapping of input coordinates + to an output is the same as the tensor's mapping of indices to values. For example, for a three-dimensional + :attr:`input` the function described is :math:`g : \mathbb{R}^3 \rightarrow \mathbb{R}`, and + :math:`g(1, 2, 3)\ == input[1, 2, 3]`. + + When :attr:`spacing` is specified, it modifies the relationship between :attr:`input` and input coordinates. + This is detailed in the "Keyword Arguments" section below. + + The gradient is estimated by estimating each partial derivative of :math:`g` independently. This estimation is + accurate if :math:`g` is in :math:`C^3` (it has at least 3 continuous derivatives), and the estimation can be + improved by providing closer samples. Mathematically, the value at each interior point of a partial derivative + is estimated using `Taylor's theorem with remainder `_. + Letting :math:`x` be an interior point with :math:`x-h_l` and :math:`x+h_r` be points neighboring + it to the left and right respectively, :math:`f(x+h_r)` and :math:`f(x-h_l)` can be estimated using: + + .. math:: + \begin{aligned} + f(x+h_r) = f(x) + h_r f'(x) + {h_r}^2 \frac{f''(x)}{2} + {h_r}^3 \frac{f'''(\xi_1)}{6}, \xi_1 \in (x, x+h_r) \\ + f(x-h_l) = f(x) - h_l f'(x) + {h_l}^2 \frac{f''(x)}{2} - {h_l}^3 \frac{f'''(\xi_2)}{6}, \xi_2 \in (x, x-h_l) \\ + \end{aligned} + + Using the fact that :math:`f \in C^3` and solving the linear system, we derive: + + .. math:: + f'(x) \approx \frac{ {h_l}^2 f(x+h_r) - {h_r}^2 f(x-h_l) + + ({h_r}^2-{h_l}^2 ) f(x) }{ {h_r} {h_l}^2 + {h_r}^2 {h_l} } + + .. note:: + We estimate the gradient of functions in complex domain + :math:`g : \mathbb{C}^n \rightarrow \mathbb{C}` in the same way. + + The value of each partial derivative at the boundary points is computed differently. See edge_order below. + + Args: + input (``Tensor``): the tensor that represents the values of the function + + Keyword args: + spacing (``scalar``, ``list of scalar``, ``list of Tensor``, optional): :attr:`spacing` can be used to modify + how the :attr:`input` tensor's indices relate to sample coordinates. If :attr:`spacing` is a scalar then + the indices are multiplied by the scalar to produce the coordinates. For example, if :attr:`spacing=2` the + indices (1, 2, 3) become coordinates (2, 4, 6). If :attr:`spacing` is a list of scalars then the corresponding + indices are multiplied. For example, if :attr:`spacing=(2, -1, 3)` the indices (1, 2, 3) become coordinates (2, -2, 9). + Finally, if :attr:`spacing` is a list of one-dimensional tensors then each tensor specifies the coordinates for + the corresponding dimension. For example, if the indices are (1, 2, 3) and the tensors are (t0, t1, t2), then + the coordinates are (t0[1], t1[2], t2[3]) + + dim (``int``, ``list of int``, optional): the dimension or dimensions to approximate the gradient over. By default + the partial gradient in every dimension is computed. Note that when :attr:`dim` is specified the elements of + the :attr:`spacing` argument must correspond with the specified dims." + + edge_order (``int``, optional): 1 or 2, for `first-order + `_ or + `second-order `_ + estimation of the boundary ("edge") values, respectively. Note that when :attr:`edge_order` is specified, each + dimension size of :attr:`input` should be at least edge_order+1 + + Examples:: + + >>> # Estimates the gradient of f(x)=x^2 at points [-2, -1, 2, 4] + >>> coordinates = (torch.tensor([-2., -1., 1., 4.]),) + >>> values = torch.tensor([4., 1., 1., 16.], ) + >>> torch.gradient(values, spacing = coordinates) + (tensor([-3., -2., 2., 5.]),) + + >>> # Estimates the gradient of the R^2 -> R function whose samples are + >>> # described by the tensor t. Implicit coordinates are [0, 1] for the outermost + >>> # dimension and [0, 1, 2, 3] for the innermost dimension, and function estimates + >>> # partial derivative for both dimensions. + >>> t = torch.tensor([[1, 2, 4, 8], [10, 20, 40, 80]]) + >>> torch.gradient(t) + (tensor([[ 9., 18., 36., 72.], + [ 9., 18., 36., 72.]]), + tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]])) + + >>> # A scalar value for spacing modifies the relationship between tensor indices + >>> # and input coordinates by multiplying the indices to find the + >>> # coordinates. For example, below the indices of the innermost + >>> # 0, 1, 2, 3 translate to coordinates of [0, 2, 4, 6], and the indices of + >>> # the outermost dimension 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = 2.0) # dim = None (implicitly [0, 1]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.5000, 0.7500, 1.5000, 2.0000], + [ 5.0000, 7.5000, 15.0000, 20.0000]])) + >>> # doubling the spacing between samples halves the estimated partial gradients. + + >>> + >>> # Estimates only the partial derivative for dimension 1 + >>> torch.gradient(t, dim = 1) # spacing = None (implicitly 1.) + (tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]]),) + + >>> # When spacing is a list of scalars, the relationship between the tensor + >>> # indices and input coordinates changes based on dimension. + >>> # For example, below, the indices of the innermost dimension 0, 1, 2, 3 translate + >>> # to coordinates of [0, 3, 6, 9], and the indices of the outermost dimension + >>> # 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = [3., 2.]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + + >>> # The following example is a replication of the previous one with explicit + >>> # coordinates. + >>> coords = (torch.tensor([0, 2]), torch.tensor([0, 3, 6, 9])) + >>> torch.gradient(t, spacing = coords) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + """ + +@overload +def gradient( + input: Tensor, + *, + spacing: Sequence[Number | _complex], + dim: _int | None = None, + edge_order: _int = 1, +) -> tuple[Tensor, ...]: + r""" + gradient(input, *, spacing=1, dim=None, edge_order=1) -> List of Tensors + + Estimates the gradient of a function :math:`g : \mathbb{R}^n \rightarrow \mathbb{R}` in + one or more dimensions using the `second-order accurate central differences method + `_ and + either first or second order estimates at the boundaries. + + The gradient of :math:`g` is estimated using samples. By default, when :attr:`spacing` is not + specified, the samples are entirely described by :attr:`input`, and the mapping of input coordinates + to an output is the same as the tensor's mapping of indices to values. For example, for a three-dimensional + :attr:`input` the function described is :math:`g : \mathbb{R}^3 \rightarrow \mathbb{R}`, and + :math:`g(1, 2, 3)\ == input[1, 2, 3]`. + + When :attr:`spacing` is specified, it modifies the relationship between :attr:`input` and input coordinates. + This is detailed in the "Keyword Arguments" section below. + + The gradient is estimated by estimating each partial derivative of :math:`g` independently. This estimation is + accurate if :math:`g` is in :math:`C^3` (it has at least 3 continuous derivatives), and the estimation can be + improved by providing closer samples. Mathematically, the value at each interior point of a partial derivative + is estimated using `Taylor's theorem with remainder `_. + Letting :math:`x` be an interior point with :math:`x-h_l` and :math:`x+h_r` be points neighboring + it to the left and right respectively, :math:`f(x+h_r)` and :math:`f(x-h_l)` can be estimated using: + + .. math:: + \begin{aligned} + f(x+h_r) = f(x) + h_r f'(x) + {h_r}^2 \frac{f''(x)}{2} + {h_r}^3 \frac{f'''(\xi_1)}{6}, \xi_1 \in (x, x+h_r) \\ + f(x-h_l) = f(x) - h_l f'(x) + {h_l}^2 \frac{f''(x)}{2} - {h_l}^3 \frac{f'''(\xi_2)}{6}, \xi_2 \in (x, x-h_l) \\ + \end{aligned} + + Using the fact that :math:`f \in C^3` and solving the linear system, we derive: + + .. math:: + f'(x) \approx \frac{ {h_l}^2 f(x+h_r) - {h_r}^2 f(x-h_l) + + ({h_r}^2-{h_l}^2 ) f(x) }{ {h_r} {h_l}^2 + {h_r}^2 {h_l} } + + .. note:: + We estimate the gradient of functions in complex domain + :math:`g : \mathbb{C}^n \rightarrow \mathbb{C}` in the same way. + + The value of each partial derivative at the boundary points is computed differently. See edge_order below. + + Args: + input (``Tensor``): the tensor that represents the values of the function + + Keyword args: + spacing (``scalar``, ``list of scalar``, ``list of Tensor``, optional): :attr:`spacing` can be used to modify + how the :attr:`input` tensor's indices relate to sample coordinates. If :attr:`spacing` is a scalar then + the indices are multiplied by the scalar to produce the coordinates. For example, if :attr:`spacing=2` the + indices (1, 2, 3) become coordinates (2, 4, 6). If :attr:`spacing` is a list of scalars then the corresponding + indices are multiplied. For example, if :attr:`spacing=(2, -1, 3)` the indices (1, 2, 3) become coordinates (2, -2, 9). + Finally, if :attr:`spacing` is a list of one-dimensional tensors then each tensor specifies the coordinates for + the corresponding dimension. For example, if the indices are (1, 2, 3) and the tensors are (t0, t1, t2), then + the coordinates are (t0[1], t1[2], t2[3]) + + dim (``int``, ``list of int``, optional): the dimension or dimensions to approximate the gradient over. By default + the partial gradient in every dimension is computed. Note that when :attr:`dim` is specified the elements of + the :attr:`spacing` argument must correspond with the specified dims." + + edge_order (``int``, optional): 1 or 2, for `first-order + `_ or + `second-order `_ + estimation of the boundary ("edge") values, respectively. Note that when :attr:`edge_order` is specified, each + dimension size of :attr:`input` should be at least edge_order+1 + + Examples:: + + >>> # Estimates the gradient of f(x)=x^2 at points [-2, -1, 2, 4] + >>> coordinates = (torch.tensor([-2., -1., 1., 4.]),) + >>> values = torch.tensor([4., 1., 1., 16.], ) + >>> torch.gradient(values, spacing = coordinates) + (tensor([-3., -2., 2., 5.]),) + + >>> # Estimates the gradient of the R^2 -> R function whose samples are + >>> # described by the tensor t. Implicit coordinates are [0, 1] for the outermost + >>> # dimension and [0, 1, 2, 3] for the innermost dimension, and function estimates + >>> # partial derivative for both dimensions. + >>> t = torch.tensor([[1, 2, 4, 8], [10, 20, 40, 80]]) + >>> torch.gradient(t) + (tensor([[ 9., 18., 36., 72.], + [ 9., 18., 36., 72.]]), + tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]])) + + >>> # A scalar value for spacing modifies the relationship between tensor indices + >>> # and input coordinates by multiplying the indices to find the + >>> # coordinates. For example, below the indices of the innermost + >>> # 0, 1, 2, 3 translate to coordinates of [0, 2, 4, 6], and the indices of + >>> # the outermost dimension 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = 2.0) # dim = None (implicitly [0, 1]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.5000, 0.7500, 1.5000, 2.0000], + [ 5.0000, 7.5000, 15.0000, 20.0000]])) + >>> # doubling the spacing between samples halves the estimated partial gradients. + + >>> + >>> # Estimates only the partial derivative for dimension 1 + >>> torch.gradient(t, dim = 1) # spacing = None (implicitly 1.) + (tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]]),) + + >>> # When spacing is a list of scalars, the relationship between the tensor + >>> # indices and input coordinates changes based on dimension. + >>> # For example, below, the indices of the innermost dimension 0, 1, 2, 3 translate + >>> # to coordinates of [0, 3, 6, 9], and the indices of the outermost dimension + >>> # 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = [3., 2.]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + + >>> # The following example is a replication of the previous one with explicit + >>> # coordinates. + >>> coords = (torch.tensor([0, 2]), torch.tensor([0, 3, 6, 9])) + >>> torch.gradient(t, spacing = coords) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + """ + +@overload +def gradient( + input: Tensor, + *, + spacing: Sequence[Number | _complex], + dim: _size, + edge_order: _int = 1, +) -> tuple[Tensor, ...]: + r""" + gradient(input, *, spacing=1, dim=None, edge_order=1) -> List of Tensors + + Estimates the gradient of a function :math:`g : \mathbb{R}^n \rightarrow \mathbb{R}` in + one or more dimensions using the `second-order accurate central differences method + `_ and + either first or second order estimates at the boundaries. + + The gradient of :math:`g` is estimated using samples. By default, when :attr:`spacing` is not + specified, the samples are entirely described by :attr:`input`, and the mapping of input coordinates + to an output is the same as the tensor's mapping of indices to values. For example, for a three-dimensional + :attr:`input` the function described is :math:`g : \mathbb{R}^3 \rightarrow \mathbb{R}`, and + :math:`g(1, 2, 3)\ == input[1, 2, 3]`. + + When :attr:`spacing` is specified, it modifies the relationship between :attr:`input` and input coordinates. + This is detailed in the "Keyword Arguments" section below. + + The gradient is estimated by estimating each partial derivative of :math:`g` independently. This estimation is + accurate if :math:`g` is in :math:`C^3` (it has at least 3 continuous derivatives), and the estimation can be + improved by providing closer samples. Mathematically, the value at each interior point of a partial derivative + is estimated using `Taylor's theorem with remainder `_. + Letting :math:`x` be an interior point with :math:`x-h_l` and :math:`x+h_r` be points neighboring + it to the left and right respectively, :math:`f(x+h_r)` and :math:`f(x-h_l)` can be estimated using: + + .. math:: + \begin{aligned} + f(x+h_r) = f(x) + h_r f'(x) + {h_r}^2 \frac{f''(x)}{2} + {h_r}^3 \frac{f'''(\xi_1)}{6}, \xi_1 \in (x, x+h_r) \\ + f(x-h_l) = f(x) - h_l f'(x) + {h_l}^2 \frac{f''(x)}{2} - {h_l}^3 \frac{f'''(\xi_2)}{6}, \xi_2 \in (x, x-h_l) \\ + \end{aligned} + + Using the fact that :math:`f \in C^3` and solving the linear system, we derive: + + .. math:: + f'(x) \approx \frac{ {h_l}^2 f(x+h_r) - {h_r}^2 f(x-h_l) + + ({h_r}^2-{h_l}^2 ) f(x) }{ {h_r} {h_l}^2 + {h_r}^2 {h_l} } + + .. note:: + We estimate the gradient of functions in complex domain + :math:`g : \mathbb{C}^n \rightarrow \mathbb{C}` in the same way. + + The value of each partial derivative at the boundary points is computed differently. See edge_order below. + + Args: + input (``Tensor``): the tensor that represents the values of the function + + Keyword args: + spacing (``scalar``, ``list of scalar``, ``list of Tensor``, optional): :attr:`spacing` can be used to modify + how the :attr:`input` tensor's indices relate to sample coordinates. If :attr:`spacing` is a scalar then + the indices are multiplied by the scalar to produce the coordinates. For example, if :attr:`spacing=2` the + indices (1, 2, 3) become coordinates (2, 4, 6). If :attr:`spacing` is a list of scalars then the corresponding + indices are multiplied. For example, if :attr:`spacing=(2, -1, 3)` the indices (1, 2, 3) become coordinates (2, -2, 9). + Finally, if :attr:`spacing` is a list of one-dimensional tensors then each tensor specifies the coordinates for + the corresponding dimension. For example, if the indices are (1, 2, 3) and the tensors are (t0, t1, t2), then + the coordinates are (t0[1], t1[2], t2[3]) + + dim (``int``, ``list of int``, optional): the dimension or dimensions to approximate the gradient over. By default + the partial gradient in every dimension is computed. Note that when :attr:`dim` is specified the elements of + the :attr:`spacing` argument must correspond with the specified dims." + + edge_order (``int``, optional): 1 or 2, for `first-order + `_ or + `second-order `_ + estimation of the boundary ("edge") values, respectively. Note that when :attr:`edge_order` is specified, each + dimension size of :attr:`input` should be at least edge_order+1 + + Examples:: + + >>> # Estimates the gradient of f(x)=x^2 at points [-2, -1, 2, 4] + >>> coordinates = (torch.tensor([-2., -1., 1., 4.]),) + >>> values = torch.tensor([4., 1., 1., 16.], ) + >>> torch.gradient(values, spacing = coordinates) + (tensor([-3., -2., 2., 5.]),) + + >>> # Estimates the gradient of the R^2 -> R function whose samples are + >>> # described by the tensor t. Implicit coordinates are [0, 1] for the outermost + >>> # dimension and [0, 1, 2, 3] for the innermost dimension, and function estimates + >>> # partial derivative for both dimensions. + >>> t = torch.tensor([[1, 2, 4, 8], [10, 20, 40, 80]]) + >>> torch.gradient(t) + (tensor([[ 9., 18., 36., 72.], + [ 9., 18., 36., 72.]]), + tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]])) + + >>> # A scalar value for spacing modifies the relationship between tensor indices + >>> # and input coordinates by multiplying the indices to find the + >>> # coordinates. For example, below the indices of the innermost + >>> # 0, 1, 2, 3 translate to coordinates of [0, 2, 4, 6], and the indices of + >>> # the outermost dimension 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = 2.0) # dim = None (implicitly [0, 1]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.5000, 0.7500, 1.5000, 2.0000], + [ 5.0000, 7.5000, 15.0000, 20.0000]])) + >>> # doubling the spacing between samples halves the estimated partial gradients. + + >>> + >>> # Estimates only the partial derivative for dimension 1 + >>> torch.gradient(t, dim = 1) # spacing = None (implicitly 1.) + (tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]]),) + + >>> # When spacing is a list of scalars, the relationship between the tensor + >>> # indices and input coordinates changes based on dimension. + >>> # For example, below, the indices of the innermost dimension 0, 1, 2, 3 translate + >>> # to coordinates of [0, 3, 6, 9], and the indices of the outermost dimension + >>> # 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = [3., 2.]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + + >>> # The following example is a replication of the previous one with explicit + >>> # coordinates. + >>> coords = (torch.tensor([0, 2]), torch.tensor([0, 3, 6, 9])) + >>> torch.gradient(t, spacing = coords) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + """ + +@overload +def gradient( + input: Tensor, + *, + spacing: tuple[Tensor, ...] | list[Tensor] | None, + dim: _int | None = None, + edge_order: _int = 1, +) -> tuple[Tensor, ...]: + r""" + gradient(input, *, spacing=1, dim=None, edge_order=1) -> List of Tensors + + Estimates the gradient of a function :math:`g : \mathbb{R}^n \rightarrow \mathbb{R}` in + one or more dimensions using the `second-order accurate central differences method + `_ and + either first or second order estimates at the boundaries. + + The gradient of :math:`g` is estimated using samples. By default, when :attr:`spacing` is not + specified, the samples are entirely described by :attr:`input`, and the mapping of input coordinates + to an output is the same as the tensor's mapping of indices to values. For example, for a three-dimensional + :attr:`input` the function described is :math:`g : \mathbb{R}^3 \rightarrow \mathbb{R}`, and + :math:`g(1, 2, 3)\ == input[1, 2, 3]`. + + When :attr:`spacing` is specified, it modifies the relationship between :attr:`input` and input coordinates. + This is detailed in the "Keyword Arguments" section below. + + The gradient is estimated by estimating each partial derivative of :math:`g` independently. This estimation is + accurate if :math:`g` is in :math:`C^3` (it has at least 3 continuous derivatives), and the estimation can be + improved by providing closer samples. Mathematically, the value at each interior point of a partial derivative + is estimated using `Taylor's theorem with remainder `_. + Letting :math:`x` be an interior point with :math:`x-h_l` and :math:`x+h_r` be points neighboring + it to the left and right respectively, :math:`f(x+h_r)` and :math:`f(x-h_l)` can be estimated using: + + .. math:: + \begin{aligned} + f(x+h_r) = f(x) + h_r f'(x) + {h_r}^2 \frac{f''(x)}{2} + {h_r}^3 \frac{f'''(\xi_1)}{6}, \xi_1 \in (x, x+h_r) \\ + f(x-h_l) = f(x) - h_l f'(x) + {h_l}^2 \frac{f''(x)}{2} - {h_l}^3 \frac{f'''(\xi_2)}{6}, \xi_2 \in (x, x-h_l) \\ + \end{aligned} + + Using the fact that :math:`f \in C^3` and solving the linear system, we derive: + + .. math:: + f'(x) \approx \frac{ {h_l}^2 f(x+h_r) - {h_r}^2 f(x-h_l) + + ({h_r}^2-{h_l}^2 ) f(x) }{ {h_r} {h_l}^2 + {h_r}^2 {h_l} } + + .. note:: + We estimate the gradient of functions in complex domain + :math:`g : \mathbb{C}^n \rightarrow \mathbb{C}` in the same way. + + The value of each partial derivative at the boundary points is computed differently. See edge_order below. + + Args: + input (``Tensor``): the tensor that represents the values of the function + + Keyword args: + spacing (``scalar``, ``list of scalar``, ``list of Tensor``, optional): :attr:`spacing` can be used to modify + how the :attr:`input` tensor's indices relate to sample coordinates. If :attr:`spacing` is a scalar then + the indices are multiplied by the scalar to produce the coordinates. For example, if :attr:`spacing=2` the + indices (1, 2, 3) become coordinates (2, 4, 6). If :attr:`spacing` is a list of scalars then the corresponding + indices are multiplied. For example, if :attr:`spacing=(2, -1, 3)` the indices (1, 2, 3) become coordinates (2, -2, 9). + Finally, if :attr:`spacing` is a list of one-dimensional tensors then each tensor specifies the coordinates for + the corresponding dimension. For example, if the indices are (1, 2, 3) and the tensors are (t0, t1, t2), then + the coordinates are (t0[1], t1[2], t2[3]) + + dim (``int``, ``list of int``, optional): the dimension or dimensions to approximate the gradient over. By default + the partial gradient in every dimension is computed. Note that when :attr:`dim` is specified the elements of + the :attr:`spacing` argument must correspond with the specified dims." + + edge_order (``int``, optional): 1 or 2, for `first-order + `_ or + `second-order `_ + estimation of the boundary ("edge") values, respectively. Note that when :attr:`edge_order` is specified, each + dimension size of :attr:`input` should be at least edge_order+1 + + Examples:: + + >>> # Estimates the gradient of f(x)=x^2 at points [-2, -1, 2, 4] + >>> coordinates = (torch.tensor([-2., -1., 1., 4.]),) + >>> values = torch.tensor([4., 1., 1., 16.], ) + >>> torch.gradient(values, spacing = coordinates) + (tensor([-3., -2., 2., 5.]),) + + >>> # Estimates the gradient of the R^2 -> R function whose samples are + >>> # described by the tensor t. Implicit coordinates are [0, 1] for the outermost + >>> # dimension and [0, 1, 2, 3] for the innermost dimension, and function estimates + >>> # partial derivative for both dimensions. + >>> t = torch.tensor([[1, 2, 4, 8], [10, 20, 40, 80]]) + >>> torch.gradient(t) + (tensor([[ 9., 18., 36., 72.], + [ 9., 18., 36., 72.]]), + tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]])) + + >>> # A scalar value for spacing modifies the relationship between tensor indices + >>> # and input coordinates by multiplying the indices to find the + >>> # coordinates. For example, below the indices of the innermost + >>> # 0, 1, 2, 3 translate to coordinates of [0, 2, 4, 6], and the indices of + >>> # the outermost dimension 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = 2.0) # dim = None (implicitly [0, 1]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.5000, 0.7500, 1.5000, 2.0000], + [ 5.0000, 7.5000, 15.0000, 20.0000]])) + >>> # doubling the spacing between samples halves the estimated partial gradients. + + >>> + >>> # Estimates only the partial derivative for dimension 1 + >>> torch.gradient(t, dim = 1) # spacing = None (implicitly 1.) + (tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]]),) + + >>> # When spacing is a list of scalars, the relationship between the tensor + >>> # indices and input coordinates changes based on dimension. + >>> # For example, below, the indices of the innermost dimension 0, 1, 2, 3 translate + >>> # to coordinates of [0, 3, 6, 9], and the indices of the outermost dimension + >>> # 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = [3., 2.]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + + >>> # The following example is a replication of the previous one with explicit + >>> # coordinates. + >>> coords = (torch.tensor([0, 2]), torch.tensor([0, 3, 6, 9])) + >>> torch.gradient(t, spacing = coords) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + """ + +@overload +def gradient( + input: Tensor, + *, + spacing: Number | _complex, + dim: _size, + edge_order: _int = 1, +) -> tuple[Tensor, ...]: + r""" + gradient(input, *, spacing=1, dim=None, edge_order=1) -> List of Tensors + + Estimates the gradient of a function :math:`g : \mathbb{R}^n \rightarrow \mathbb{R}` in + one or more dimensions using the `second-order accurate central differences method + `_ and + either first or second order estimates at the boundaries. + + The gradient of :math:`g` is estimated using samples. By default, when :attr:`spacing` is not + specified, the samples are entirely described by :attr:`input`, and the mapping of input coordinates + to an output is the same as the tensor's mapping of indices to values. For example, for a three-dimensional + :attr:`input` the function described is :math:`g : \mathbb{R}^3 \rightarrow \mathbb{R}`, and + :math:`g(1, 2, 3)\ == input[1, 2, 3]`. + + When :attr:`spacing` is specified, it modifies the relationship between :attr:`input` and input coordinates. + This is detailed in the "Keyword Arguments" section below. + + The gradient is estimated by estimating each partial derivative of :math:`g` independently. This estimation is + accurate if :math:`g` is in :math:`C^3` (it has at least 3 continuous derivatives), and the estimation can be + improved by providing closer samples. Mathematically, the value at each interior point of a partial derivative + is estimated using `Taylor's theorem with remainder `_. + Letting :math:`x` be an interior point with :math:`x-h_l` and :math:`x+h_r` be points neighboring + it to the left and right respectively, :math:`f(x+h_r)` and :math:`f(x-h_l)` can be estimated using: + + .. math:: + \begin{aligned} + f(x+h_r) = f(x) + h_r f'(x) + {h_r}^2 \frac{f''(x)}{2} + {h_r}^3 \frac{f'''(\xi_1)}{6}, \xi_1 \in (x, x+h_r) \\ + f(x-h_l) = f(x) - h_l f'(x) + {h_l}^2 \frac{f''(x)}{2} - {h_l}^3 \frac{f'''(\xi_2)}{6}, \xi_2 \in (x, x-h_l) \\ + \end{aligned} + + Using the fact that :math:`f \in C^3` and solving the linear system, we derive: + + .. math:: + f'(x) \approx \frac{ {h_l}^2 f(x+h_r) - {h_r}^2 f(x-h_l) + + ({h_r}^2-{h_l}^2 ) f(x) }{ {h_r} {h_l}^2 + {h_r}^2 {h_l} } + + .. note:: + We estimate the gradient of functions in complex domain + :math:`g : \mathbb{C}^n \rightarrow \mathbb{C}` in the same way. + + The value of each partial derivative at the boundary points is computed differently. See edge_order below. + + Args: + input (``Tensor``): the tensor that represents the values of the function + + Keyword args: + spacing (``scalar``, ``list of scalar``, ``list of Tensor``, optional): :attr:`spacing` can be used to modify + how the :attr:`input` tensor's indices relate to sample coordinates. If :attr:`spacing` is a scalar then + the indices are multiplied by the scalar to produce the coordinates. For example, if :attr:`spacing=2` the + indices (1, 2, 3) become coordinates (2, 4, 6). If :attr:`spacing` is a list of scalars then the corresponding + indices are multiplied. For example, if :attr:`spacing=(2, -1, 3)` the indices (1, 2, 3) become coordinates (2, -2, 9). + Finally, if :attr:`spacing` is a list of one-dimensional tensors then each tensor specifies the coordinates for + the corresponding dimension. For example, if the indices are (1, 2, 3) and the tensors are (t0, t1, t2), then + the coordinates are (t0[1], t1[2], t2[3]) + + dim (``int``, ``list of int``, optional): the dimension or dimensions to approximate the gradient over. By default + the partial gradient in every dimension is computed. Note that when :attr:`dim` is specified the elements of + the :attr:`spacing` argument must correspond with the specified dims." + + edge_order (``int``, optional): 1 or 2, for `first-order + `_ or + `second-order `_ + estimation of the boundary ("edge") values, respectively. Note that when :attr:`edge_order` is specified, each + dimension size of :attr:`input` should be at least edge_order+1 + + Examples:: + + >>> # Estimates the gradient of f(x)=x^2 at points [-2, -1, 2, 4] + >>> coordinates = (torch.tensor([-2., -1., 1., 4.]),) + >>> values = torch.tensor([4., 1., 1., 16.], ) + >>> torch.gradient(values, spacing = coordinates) + (tensor([-3., -2., 2., 5.]),) + + >>> # Estimates the gradient of the R^2 -> R function whose samples are + >>> # described by the tensor t. Implicit coordinates are [0, 1] for the outermost + >>> # dimension and [0, 1, 2, 3] for the innermost dimension, and function estimates + >>> # partial derivative for both dimensions. + >>> t = torch.tensor([[1, 2, 4, 8], [10, 20, 40, 80]]) + >>> torch.gradient(t) + (tensor([[ 9., 18., 36., 72.], + [ 9., 18., 36., 72.]]), + tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]])) + + >>> # A scalar value for spacing modifies the relationship between tensor indices + >>> # and input coordinates by multiplying the indices to find the + >>> # coordinates. For example, below the indices of the innermost + >>> # 0, 1, 2, 3 translate to coordinates of [0, 2, 4, 6], and the indices of + >>> # the outermost dimension 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = 2.0) # dim = None (implicitly [0, 1]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.5000, 0.7500, 1.5000, 2.0000], + [ 5.0000, 7.5000, 15.0000, 20.0000]])) + >>> # doubling the spacing between samples halves the estimated partial gradients. + + >>> + >>> # Estimates only the partial derivative for dimension 1 + >>> torch.gradient(t, dim = 1) # spacing = None (implicitly 1.) + (tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]]),) + + >>> # When spacing is a list of scalars, the relationship between the tensor + >>> # indices and input coordinates changes based on dimension. + >>> # For example, below, the indices of the innermost dimension 0, 1, 2, 3 translate + >>> # to coordinates of [0, 3, 6, 9], and the indices of the outermost dimension + >>> # 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = [3., 2.]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + + >>> # The following example is a replication of the previous one with explicit + >>> # coordinates. + >>> coords = (torch.tensor([0, 2]), torch.tensor([0, 3, 6, 9])) + >>> torch.gradient(t, spacing = coords) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + """ + +@overload +def gradient( + input: Tensor, + *, + spacing: tuple[Tensor, ...] | list[Tensor] | None, + dim: _size, + edge_order: _int = 1, +) -> tuple[Tensor, ...]: + r""" + gradient(input, *, spacing=1, dim=None, edge_order=1) -> List of Tensors + + Estimates the gradient of a function :math:`g : \mathbb{R}^n \rightarrow \mathbb{R}` in + one or more dimensions using the `second-order accurate central differences method + `_ and + either first or second order estimates at the boundaries. + + The gradient of :math:`g` is estimated using samples. By default, when :attr:`spacing` is not + specified, the samples are entirely described by :attr:`input`, and the mapping of input coordinates + to an output is the same as the tensor's mapping of indices to values. For example, for a three-dimensional + :attr:`input` the function described is :math:`g : \mathbb{R}^3 \rightarrow \mathbb{R}`, and + :math:`g(1, 2, 3)\ == input[1, 2, 3]`. + + When :attr:`spacing` is specified, it modifies the relationship between :attr:`input` and input coordinates. + This is detailed in the "Keyword Arguments" section below. + + The gradient is estimated by estimating each partial derivative of :math:`g` independently. This estimation is + accurate if :math:`g` is in :math:`C^3` (it has at least 3 continuous derivatives), and the estimation can be + improved by providing closer samples. Mathematically, the value at each interior point of a partial derivative + is estimated using `Taylor's theorem with remainder `_. + Letting :math:`x` be an interior point with :math:`x-h_l` and :math:`x+h_r` be points neighboring + it to the left and right respectively, :math:`f(x+h_r)` and :math:`f(x-h_l)` can be estimated using: + + .. math:: + \begin{aligned} + f(x+h_r) = f(x) + h_r f'(x) + {h_r}^2 \frac{f''(x)}{2} + {h_r}^3 \frac{f'''(\xi_1)}{6}, \xi_1 \in (x, x+h_r) \\ + f(x-h_l) = f(x) - h_l f'(x) + {h_l}^2 \frac{f''(x)}{2} - {h_l}^3 \frac{f'''(\xi_2)}{6}, \xi_2 \in (x, x-h_l) \\ + \end{aligned} + + Using the fact that :math:`f \in C^3` and solving the linear system, we derive: + + .. math:: + f'(x) \approx \frac{ {h_l}^2 f(x+h_r) - {h_r}^2 f(x-h_l) + + ({h_r}^2-{h_l}^2 ) f(x) }{ {h_r} {h_l}^2 + {h_r}^2 {h_l} } + + .. note:: + We estimate the gradient of functions in complex domain + :math:`g : \mathbb{C}^n \rightarrow \mathbb{C}` in the same way. + + The value of each partial derivative at the boundary points is computed differently. See edge_order below. + + Args: + input (``Tensor``): the tensor that represents the values of the function + + Keyword args: + spacing (``scalar``, ``list of scalar``, ``list of Tensor``, optional): :attr:`spacing` can be used to modify + how the :attr:`input` tensor's indices relate to sample coordinates. If :attr:`spacing` is a scalar then + the indices are multiplied by the scalar to produce the coordinates. For example, if :attr:`spacing=2` the + indices (1, 2, 3) become coordinates (2, 4, 6). If :attr:`spacing` is a list of scalars then the corresponding + indices are multiplied. For example, if :attr:`spacing=(2, -1, 3)` the indices (1, 2, 3) become coordinates (2, -2, 9). + Finally, if :attr:`spacing` is a list of one-dimensional tensors then each tensor specifies the coordinates for + the corresponding dimension. For example, if the indices are (1, 2, 3) and the tensors are (t0, t1, t2), then + the coordinates are (t0[1], t1[2], t2[3]) + + dim (``int``, ``list of int``, optional): the dimension or dimensions to approximate the gradient over. By default + the partial gradient in every dimension is computed. Note that when :attr:`dim` is specified the elements of + the :attr:`spacing` argument must correspond with the specified dims." + + edge_order (``int``, optional): 1 or 2, for `first-order + `_ or + `second-order `_ + estimation of the boundary ("edge") values, respectively. Note that when :attr:`edge_order` is specified, each + dimension size of :attr:`input` should be at least edge_order+1 + + Examples:: + + >>> # Estimates the gradient of f(x)=x^2 at points [-2, -1, 2, 4] + >>> coordinates = (torch.tensor([-2., -1., 1., 4.]),) + >>> values = torch.tensor([4., 1., 1., 16.], ) + >>> torch.gradient(values, spacing = coordinates) + (tensor([-3., -2., 2., 5.]),) + + >>> # Estimates the gradient of the R^2 -> R function whose samples are + >>> # described by the tensor t. Implicit coordinates are [0, 1] for the outermost + >>> # dimension and [0, 1, 2, 3] for the innermost dimension, and function estimates + >>> # partial derivative for both dimensions. + >>> t = torch.tensor([[1, 2, 4, 8], [10, 20, 40, 80]]) + >>> torch.gradient(t) + (tensor([[ 9., 18., 36., 72.], + [ 9., 18., 36., 72.]]), + tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]])) + + >>> # A scalar value for spacing modifies the relationship between tensor indices + >>> # and input coordinates by multiplying the indices to find the + >>> # coordinates. For example, below the indices of the innermost + >>> # 0, 1, 2, 3 translate to coordinates of [0, 2, 4, 6], and the indices of + >>> # the outermost dimension 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = 2.0) # dim = None (implicitly [0, 1]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.5000, 0.7500, 1.5000, 2.0000], + [ 5.0000, 7.5000, 15.0000, 20.0000]])) + >>> # doubling the spacing between samples halves the estimated partial gradients. + + >>> + >>> # Estimates only the partial derivative for dimension 1 + >>> torch.gradient(t, dim = 1) # spacing = None (implicitly 1.) + (tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]]),) + + >>> # When spacing is a list of scalars, the relationship between the tensor + >>> # indices and input coordinates changes based on dimension. + >>> # For example, below, the indices of the innermost dimension 0, 1, 2, 3 translate + >>> # to coordinates of [0, 3, 6, 9], and the indices of the outermost dimension + >>> # 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = [3., 2.]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + + >>> # The following example is a replication of the previous one with explicit + >>> # coordinates. + >>> coords = (torch.tensor([0, 2]), torch.tensor([0, 3, 6, 9])) + >>> torch.gradient(t, spacing = coords) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + """ + +@overload +def gradient( + input: Tensor, + *, + dim: _size, + edge_order: _int = 1, +) -> tuple[Tensor, ...]: + r""" + gradient(input, *, spacing=1, dim=None, edge_order=1) -> List of Tensors + + Estimates the gradient of a function :math:`g : \mathbb{R}^n \rightarrow \mathbb{R}` in + one or more dimensions using the `second-order accurate central differences method + `_ and + either first or second order estimates at the boundaries. + + The gradient of :math:`g` is estimated using samples. By default, when :attr:`spacing` is not + specified, the samples are entirely described by :attr:`input`, and the mapping of input coordinates + to an output is the same as the tensor's mapping of indices to values. For example, for a three-dimensional + :attr:`input` the function described is :math:`g : \mathbb{R}^3 \rightarrow \mathbb{R}`, and + :math:`g(1, 2, 3)\ == input[1, 2, 3]`. + + When :attr:`spacing` is specified, it modifies the relationship between :attr:`input` and input coordinates. + This is detailed in the "Keyword Arguments" section below. + + The gradient is estimated by estimating each partial derivative of :math:`g` independently. This estimation is + accurate if :math:`g` is in :math:`C^3` (it has at least 3 continuous derivatives), and the estimation can be + improved by providing closer samples. Mathematically, the value at each interior point of a partial derivative + is estimated using `Taylor's theorem with remainder `_. + Letting :math:`x` be an interior point with :math:`x-h_l` and :math:`x+h_r` be points neighboring + it to the left and right respectively, :math:`f(x+h_r)` and :math:`f(x-h_l)` can be estimated using: + + .. math:: + \begin{aligned} + f(x+h_r) = f(x) + h_r f'(x) + {h_r}^2 \frac{f''(x)}{2} + {h_r}^3 \frac{f'''(\xi_1)}{6}, \xi_1 \in (x, x+h_r) \\ + f(x-h_l) = f(x) - h_l f'(x) + {h_l}^2 \frac{f''(x)}{2} - {h_l}^3 \frac{f'''(\xi_2)}{6}, \xi_2 \in (x, x-h_l) \\ + \end{aligned} + + Using the fact that :math:`f \in C^3` and solving the linear system, we derive: + + .. math:: + f'(x) \approx \frac{ {h_l}^2 f(x+h_r) - {h_r}^2 f(x-h_l) + + ({h_r}^2-{h_l}^2 ) f(x) }{ {h_r} {h_l}^2 + {h_r}^2 {h_l} } + + .. note:: + We estimate the gradient of functions in complex domain + :math:`g : \mathbb{C}^n \rightarrow \mathbb{C}` in the same way. + + The value of each partial derivative at the boundary points is computed differently. See edge_order below. + + Args: + input (``Tensor``): the tensor that represents the values of the function + + Keyword args: + spacing (``scalar``, ``list of scalar``, ``list of Tensor``, optional): :attr:`spacing` can be used to modify + how the :attr:`input` tensor's indices relate to sample coordinates. If :attr:`spacing` is a scalar then + the indices are multiplied by the scalar to produce the coordinates. For example, if :attr:`spacing=2` the + indices (1, 2, 3) become coordinates (2, 4, 6). If :attr:`spacing` is a list of scalars then the corresponding + indices are multiplied. For example, if :attr:`spacing=(2, -1, 3)` the indices (1, 2, 3) become coordinates (2, -2, 9). + Finally, if :attr:`spacing` is a list of one-dimensional tensors then each tensor specifies the coordinates for + the corresponding dimension. For example, if the indices are (1, 2, 3) and the tensors are (t0, t1, t2), then + the coordinates are (t0[1], t1[2], t2[3]) + + dim (``int``, ``list of int``, optional): the dimension or dimensions to approximate the gradient over. By default + the partial gradient in every dimension is computed. Note that when :attr:`dim` is specified the elements of + the :attr:`spacing` argument must correspond with the specified dims." + + edge_order (``int``, optional): 1 or 2, for `first-order + `_ or + `second-order `_ + estimation of the boundary ("edge") values, respectively. Note that when :attr:`edge_order` is specified, each + dimension size of :attr:`input` should be at least edge_order+1 + + Examples:: + + >>> # Estimates the gradient of f(x)=x^2 at points [-2, -1, 2, 4] + >>> coordinates = (torch.tensor([-2., -1., 1., 4.]),) + >>> values = torch.tensor([4., 1., 1., 16.], ) + >>> torch.gradient(values, spacing = coordinates) + (tensor([-3., -2., 2., 5.]),) + + >>> # Estimates the gradient of the R^2 -> R function whose samples are + >>> # described by the tensor t. Implicit coordinates are [0, 1] for the outermost + >>> # dimension and [0, 1, 2, 3] for the innermost dimension, and function estimates + >>> # partial derivative for both dimensions. + >>> t = torch.tensor([[1, 2, 4, 8], [10, 20, 40, 80]]) + >>> torch.gradient(t) + (tensor([[ 9., 18., 36., 72.], + [ 9., 18., 36., 72.]]), + tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]])) + + >>> # A scalar value for spacing modifies the relationship between tensor indices + >>> # and input coordinates by multiplying the indices to find the + >>> # coordinates. For example, below the indices of the innermost + >>> # 0, 1, 2, 3 translate to coordinates of [0, 2, 4, 6], and the indices of + >>> # the outermost dimension 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = 2.0) # dim = None (implicitly [0, 1]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.5000, 0.7500, 1.5000, 2.0000], + [ 5.0000, 7.5000, 15.0000, 20.0000]])) + >>> # doubling the spacing between samples halves the estimated partial gradients. + + >>> + >>> # Estimates only the partial derivative for dimension 1 + >>> torch.gradient(t, dim = 1) # spacing = None (implicitly 1.) + (tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]]),) + + >>> # When spacing is a list of scalars, the relationship between the tensor + >>> # indices and input coordinates changes based on dimension. + >>> # For example, below, the indices of the innermost dimension 0, 1, 2, 3 translate + >>> # to coordinates of [0, 3, 6, 9], and the indices of the outermost dimension + >>> # 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = [3., 2.]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + + >>> # The following example is a replication of the previous one with explicit + >>> # coordinates. + >>> coords = (torch.tensor([0, 2]), torch.tensor([0, 3, 6, 9])) + >>> torch.gradient(t, spacing = coords) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + """ + +@overload +def greater( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + greater(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.gt`. + """ + +@overload +def greater( + input: Tensor, + other: Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + greater(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.gt`. + """ + +@overload +def greater_equal( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + greater_equal(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.ge`. + """ + +@overload +def greater_equal( + input: Tensor, + other: Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + greater_equal(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.ge`. + """ + +def grid_sampler( + input: Tensor, + grid: Tensor, + interpolation_mode: _int, + padding_mode: _int, + align_corners: _bool, +) -> Tensor: ... +def grid_sampler_2d( + input: Tensor, + grid: Tensor, + interpolation_mode: _int, + padding_mode: _int, + align_corners: _bool, +) -> Tensor: ... +def grid_sampler_3d( + input: Tensor, + grid: Tensor, + interpolation_mode: _int, + padding_mode: _int, + align_corners: _bool, +) -> Tensor: ... +def group_norm( + input: Tensor, + num_groups: _int, + weight: Tensor | None = None, + bias: Tensor | None = None, + eps: _float = 1e-05, + cudnn_enabled: _bool = True, +) -> Tensor: ... +@overload +def gru( + data: Tensor, + batch_sizes: Tensor, + hx: Tensor, + params: tuple[Tensor, ...] | list[Tensor] | None, + has_biases: _bool, + num_layers: _int, + dropout: _float, + train: _bool, + bidirectional: _bool, +) -> tuple[Tensor, Tensor]: ... +@overload +def gru( + input: Tensor, + hx: Tensor, + params: tuple[Tensor, ...] | list[Tensor] | None, + has_biases: _bool, + num_layers: _int, + dropout: _float, + train: _bool, + bidirectional: _bool, + batch_first: _bool, +) -> tuple[Tensor, Tensor]: ... +def gru_cell( + input: Tensor, + hx: Tensor, + w_ih: Tensor, + w_hh: Tensor, + b_ih: Tensor | None = None, + b_hh: Tensor | None = None, +) -> Tensor: ... +@overload +def gt( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + gt(input, other, *, out=None) -> Tensor + + Computes :math:`\text{input} > \text{other}` element-wise. + + + The second argument can be a number or a tensor whose shape is + :ref:`broadcastable ` with the first argument. + + Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is greater than :attr:`other` and False elsewhere + + Example:: + + >>> torch.gt(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[False, True], [False, False]]) + """ + +@overload +def gt( + input: Tensor, + other: Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + gt(input, other, *, out=None) -> Tensor + + Computes :math:`\text{input} > \text{other}` element-wise. + + + The second argument can be a number or a tensor whose shape is + :ref:`broadcastable ` with the first argument. + + Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is greater than :attr:`other` and False elsewhere + + Example:: + + >>> torch.gt(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[False, True], [False, False]]) + """ + +@overload +def hamming_window( + window_length: _int, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + hamming_window(window_length, *, dtype=None, layout=None, device=None, pin_memory=False, requires_grad=False) -> Tensor + + Hamming window function. + + .. math:: + w[n] = \alpha - \beta\ \cos \left( \frac{2 \pi n}{N - 1} \right), + + where :math:`N` is the full window size. + + The input :attr:`window_length` is a positive integer controlling the + returned window size. :attr:`periodic` flag determines whether the returned + window trims off the last duplicate value from the symmetric window and is + ready to be used as a periodic window with functions like + :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in + above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have + ``torch.hamming_window(L, periodic=True)`` equal to + ``torch.hamming_window(L + 1, periodic=False)[:-1])``. + + .. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. + + .. note:: + This is a generalized version of :meth:`torch.hann_window`. + + Arguments: + window_length (int): the size of returned window + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, *, dtype=None, layout=None, device=None, \ + pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, float alpha, *, dtype=None, layout=None, device=None, \ + pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic and alpha specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + alpha (float): The coefficient :math:`\alpha` in the equation above + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, float alpha, float beta, *, dtype=None, layout=None, \ + device=None, pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic, alpha and beta specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + alpha (float): The coefficient :math:`\alpha` in the equation above + beta (float): The coefficient :math:`\beta` in the equation above + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + """ + +@overload +def hamming_window( + window_length: _int, + periodic: _bool, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + hamming_window(window_length, *, dtype=None, layout=None, device=None, pin_memory=False, requires_grad=False) -> Tensor + + Hamming window function. + + .. math:: + w[n] = \alpha - \beta\ \cos \left( \frac{2 \pi n}{N - 1} \right), + + where :math:`N` is the full window size. + + The input :attr:`window_length` is a positive integer controlling the + returned window size. :attr:`periodic` flag determines whether the returned + window trims off the last duplicate value from the symmetric window and is + ready to be used as a periodic window with functions like + :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in + above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have + ``torch.hamming_window(L, periodic=True)`` equal to + ``torch.hamming_window(L + 1, periodic=False)[:-1])``. + + .. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. + + .. note:: + This is a generalized version of :meth:`torch.hann_window`. + + Arguments: + window_length (int): the size of returned window + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, *, dtype=None, layout=None, device=None, \ + pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, float alpha, *, dtype=None, layout=None, device=None, \ + pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic and alpha specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + alpha (float): The coefficient :math:`\alpha` in the equation above + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, float alpha, float beta, *, dtype=None, layout=None, \ + device=None, pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic, alpha and beta specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + alpha (float): The coefficient :math:`\alpha` in the equation above + beta (float): The coefficient :math:`\beta` in the equation above + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + """ + +@overload +def hamming_window( + window_length: _int, + periodic: _bool, + alpha: _float, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + hamming_window(window_length, *, dtype=None, layout=None, device=None, pin_memory=False, requires_grad=False) -> Tensor + + Hamming window function. + + .. math:: + w[n] = \alpha - \beta\ \cos \left( \frac{2 \pi n}{N - 1} \right), + + where :math:`N` is the full window size. + + The input :attr:`window_length` is a positive integer controlling the + returned window size. :attr:`periodic` flag determines whether the returned + window trims off the last duplicate value from the symmetric window and is + ready to be used as a periodic window with functions like + :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in + above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have + ``torch.hamming_window(L, periodic=True)`` equal to + ``torch.hamming_window(L + 1, periodic=False)[:-1])``. + + .. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. + + .. note:: + This is a generalized version of :meth:`torch.hann_window`. + + Arguments: + window_length (int): the size of returned window + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, *, dtype=None, layout=None, device=None, \ + pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, float alpha, *, dtype=None, layout=None, device=None, \ + pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic and alpha specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + alpha (float): The coefficient :math:`\alpha` in the equation above + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, float alpha, float beta, *, dtype=None, layout=None, \ + device=None, pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic, alpha and beta specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + alpha (float): The coefficient :math:`\alpha` in the equation above + beta (float): The coefficient :math:`\beta` in the equation above + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + """ + +@overload +def hamming_window( + window_length: _int, + periodic: _bool, + alpha: _float, + beta: _float, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + hamming_window(window_length, *, dtype=None, layout=None, device=None, pin_memory=False, requires_grad=False) -> Tensor + + Hamming window function. + + .. math:: + w[n] = \alpha - \beta\ \cos \left( \frac{2 \pi n}{N - 1} \right), + + where :math:`N` is the full window size. + + The input :attr:`window_length` is a positive integer controlling the + returned window size. :attr:`periodic` flag determines whether the returned + window trims off the last duplicate value from the symmetric window and is + ready to be used as a periodic window with functions like + :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in + above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have + ``torch.hamming_window(L, periodic=True)`` equal to + ``torch.hamming_window(L + 1, periodic=False)[:-1])``. + + .. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. + + .. note:: + This is a generalized version of :meth:`torch.hann_window`. + + Arguments: + window_length (int): the size of returned window + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, *, dtype=None, layout=None, device=None, \ + pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, float alpha, *, dtype=None, layout=None, device=None, \ + pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic and alpha specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + alpha (float): The coefficient :math:`\alpha` in the equation above + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, float alpha, float beta, *, dtype=None, layout=None, \ + device=None, pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic, alpha and beta specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + alpha (float): The coefficient :math:`\alpha` in the equation above + beta (float): The coefficient :math:`\beta` in the equation above + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + """ + +@overload +def hann_window( + window_length: _int, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + hann_window(window_length, periodic=True, *, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Hann window function. + + .. math:: + w[n] = \frac{1}{2}\ \left[1 - \cos \left( \frac{2 \pi n}{N - 1} \right)\right] = + \sin^2 \left( \frac{\pi n}{N - 1} \right), + + where :math:`N` is the full window size. + + The input :attr:`window_length` is a positive integer controlling the + returned window size. :attr:`periodic` flag determines whether the returned + window trims off the last duplicate value from the symmetric window and is + ready to be used as a periodic window with functions like + :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in + above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have + ``torch.hann_window(L, periodic=True)`` equal to + ``torch.hann_window(L + 1, periodic=False)[:-1])``. + + .. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. + + Arguments: + window_length (int): the size of returned window + periodic (bool, optional): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window + """ + +@overload +def hann_window( + window_length: _int, + periodic: _bool, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + hann_window(window_length, periodic=True, *, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Hann window function. + + .. math:: + w[n] = \frac{1}{2}\ \left[1 - \cos \left( \frac{2 \pi n}{N - 1} \right)\right] = + \sin^2 \left( \frac{\pi n}{N - 1} \right), + + where :math:`N` is the full window size. + + The input :attr:`window_length` is a positive integer controlling the + returned window size. :attr:`periodic` flag determines whether the returned + window trims off the last duplicate value from the symmetric window and is + ready to be used as a periodic window with functions like + :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in + above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have + ``torch.hann_window(L, periodic=True)`` equal to + ``torch.hann_window(L + 1, periodic=False)[:-1])``. + + .. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. + + Arguments: + window_length (int): the size of returned window + periodic (bool, optional): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window + """ + +def hardshrink( + input: Tensor, + lambd: Number | _complex = 0.5, + *, + out: Tensor | None = None, +) -> Tensor: ... +def hash_tensor( + input: Tensor, + dim: _int | _size = (), + *, + keepdim: _bool = False, + mode: _int = 0, + out: Tensor | None = None, +) -> Tensor: + r""" + hash_tensor(input, *, mode=0) -> Tensor + + Returns a hash of all elements in the :attr:`input` tensor. + + Currently only mode=0 (reduction via xor) is supported. The output will always + be of type ``torch.uint64``. The elements of ``input`` are upcasted to their + 64 bit float / integer equivalent and bitcasted to ``torch.uint64`` before + reduction via xor. + + Args: + input (Tensor): the input tensor. + + Keyword Args: + mode (int) : The hash to use. Default: 0 (xor_reduction) + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 1.1918, -1.1813, 0.3373]]) + >>> torch.hash_tensor(a) + tensor(13822780554648485888, dtype=torch.uint64) + + .. function:: hash_tensor(input, dim, *, keepdim=False, mode=0) -> Tensor + :noindex: + + Returns the hash of each row of the :attr:`input` tensor in the given + dimension :attr:`dim` given by mode. If :attr:`dim` is a list of dimensions, + reduce over all of them. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword Args: + mode (int) : The hash to use. Default: 0 (xor_reduction) + + Example:: + + >>> a = torch.randn(2, 4) + >>> a + tensor([[ 0.1317, -0.5554, -1.4724, -1.1391], + [ 0.0778, -0.6070, 0.6375, 0.1798]]) + >>> torch.hash_tensor(a, 1) + tensor([9233691267014066176, 9255993250844508160], dtype=torch.uint64) + """ + +def heaviside( + input: Tensor, + values: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + heaviside(input, values, *, out=None) -> Tensor + + Computes the Heaviside step function for each element in :attr:`input`. + The Heaviside step function is defined as: + + .. math:: + \text{{heaviside}}(input, values) = \begin{cases} + 0, & \text{if input < 0}\\ + values, & \text{if input == 0}\\ + 1, & \text{if input > 0} + \end{cases} + + + Args: + input (Tensor): the input tensor. + values (Tensor): The values to use where :attr:`input` is zero. + + Keyword arguments: + out (Tensor, optional): the output tensor. + + Example:: + + >>> input = torch.tensor([-1.5, 0, 2.0]) + >>> values = torch.tensor([0.5]) + >>> torch.heaviside(input, values) + tensor([0.0000, 0.5000, 1.0000]) + >>> values = torch.tensor([1.2, -2.0, 3.5]) + >>> torch.heaviside(input, values) + tensor([0., -2., 1.]) + """ + +def hinge_embedding_loss( + input: Tensor, + target: Tensor, + margin: _float = 1.0, + reduction: _int = 1, +) -> Tensor: ... +def histc( + input: Tensor, + bins: _int = 100, + min: Number | _complex = 0, + max: Number | _complex = 0, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + histc(input, bins=100, min=0, max=0, *, out=None) -> Tensor + + Computes the histogram of a tensor. + + The elements are sorted into equal width bins between :attr:`min` and + :attr:`max`. If :attr:`min` and :attr:`max` are both zero, the minimum and + maximum values of the data are used. + + Elements lower than min and higher than max and ``NaN`` elements are ignored. + + Args: + input (Tensor): the input tensor. + bins (int): number of histogram bins + min (Scalar): lower end of the range (inclusive) + max (Scalar): upper end of the range (inclusive) + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + Tensor: Histogram represented as a tensor + + Example:: + + >>> torch.histc(torch.tensor([1., 2, 1]), bins=4, min=0, max=3) + tensor([ 0., 2., 1., 0.]) + """ + +@overload +def histogram( + input: Tensor, + bins: Tensor, + *, + weight: Tensor | None = None, + density: _bool = False, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.histogram: + r""" + histogram(input, bins, *, range=None, weight=None, density=False, out=None) -> (Tensor, Tensor) + + Computes a histogram of the values in a tensor. + + :attr:`bins` can be an integer or a 1D tensor. + + If :attr:`bins` is an int, it specifies the number of equal-width bins. + By default, the lower and upper range of the bins is determined by the + minimum and maximum elements of the input tensor. The :attr:`range` + argument can be provided to specify a range for the bins. + + If :attr:`bins` is a 1D tensor, it specifies the sequence of bin edges + including the rightmost edge. It should contain at least 2 elements + and its elements should be increasing. + + Args: + input (Tensor): the input tensor. + bins: int or 1D Tensor. If int, defines the number of equal-width bins. If tensor, + defines the sequence of bin edges including the rightmost edge. + + Keyword args: + range (tuple of float): Defines the range of the bins. + weight (Tensor): If provided, weight should have the same shape as input. Each value in + input contributes its associated weight towards its bin's result. + density (bool): If False, the result will contain the count (or total weight) in each bin. + If True, the result is the value of the probability density function over the bins, + normalized such that the integral over the range of the bins is 1. + out (Tensor, optional): the output tensor. (tuple, optional): The result tuple of two output tensors (hist, bin_edges). + + Returns: + hist (Tensor): 1D Tensor containing the values of the histogram. + bin_edges(Tensor): 1D Tensor containing the edges of the histogram bins. + + Example:: + + >>> torch.histogram(torch.tensor([1., 2, 1]), bins=4, range=(0., 3.), weight=torch.tensor([1., 2., 4.])) + (tensor([ 0., 5., 2., 0.]), tensor([0., 0.75, 1.5, 2.25, 3.])) + >>> torch.histogram(torch.tensor([1., 2, 1]), bins=4, range=(0., 3.), weight=torch.tensor([1., 2., 4.]), density=True) + (tensor([ 0., 0.9524, 0.3810, 0.]), tensor([0., 0.75, 1.5, 2.25, 3.])) + """ + +@overload +def histogram( + input: Tensor, + bins: _int = 100, + *, + range: Sequence[_float] | None = None, + weight: Tensor | None = None, + density: _bool = False, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.histogram: + r""" + histogram(input, bins, *, range=None, weight=None, density=False, out=None) -> (Tensor, Tensor) + + Computes a histogram of the values in a tensor. + + :attr:`bins` can be an integer or a 1D tensor. + + If :attr:`bins` is an int, it specifies the number of equal-width bins. + By default, the lower and upper range of the bins is determined by the + minimum and maximum elements of the input tensor. The :attr:`range` + argument can be provided to specify a range for the bins. + + If :attr:`bins` is a 1D tensor, it specifies the sequence of bin edges + including the rightmost edge. It should contain at least 2 elements + and its elements should be increasing. + + Args: + input (Tensor): the input tensor. + bins: int or 1D Tensor. If int, defines the number of equal-width bins. If tensor, + defines the sequence of bin edges including the rightmost edge. + + Keyword args: + range (tuple of float): Defines the range of the bins. + weight (Tensor): If provided, weight should have the same shape as input. Each value in + input contributes its associated weight towards its bin's result. + density (bool): If False, the result will contain the count (or total weight) in each bin. + If True, the result is the value of the probability density function over the bins, + normalized such that the integral over the range of the bins is 1. + out (Tensor, optional): the output tensor. (tuple, optional): The result tuple of two output tensors (hist, bin_edges). + + Returns: + hist (Tensor): 1D Tensor containing the values of the histogram. + bin_edges(Tensor): 1D Tensor containing the edges of the histogram bins. + + Example:: + + >>> torch.histogram(torch.tensor([1., 2, 1]), bins=4, range=(0., 3.), weight=torch.tensor([1., 2., 4.])) + (tensor([ 0., 5., 2., 0.]), tensor([0., 0.75, 1.5, 2.25, 3.])) + >>> torch.histogram(torch.tensor([1., 2, 1]), bins=4, range=(0., 3.), weight=torch.tensor([1., 2., 4.]), density=True) + (tensor([ 0., 0.9524, 0.3810, 0.]), tensor([0., 0.75, 1.5, 2.25, 3.])) + """ + +@overload +def histogramdd( + input: Tensor, + bins: _int, + range: Sequence[_float] | None = None, + weight: Tensor | None = None, + density: _bool = False, +) -> torch.return_types.histogramdd: + r""" + histogramdd(input, bins, *, range=None, weight=None, density=False, out=None) -> (Tensor, Tensor[]) + + Computes a multi-dimensional histogram of the values in a tensor. + + Interprets the elements of an input tensor whose innermost dimension has size N + as a collection of N-dimensional points. Maps each of the points into a set of + N-dimensional bins and returns the number of points (or total weight) in each bin. + + :attr:`input` must be a tensor with at least 2 dimensions. + If input has shape (M, N), each of its M rows defines a point in N-dimensional space. + If input has three or more dimensions, all but the last dimension are flattened. + + Each dimension is independently associated with its own strictly increasing sequence + of bin edges. Bin edges may be specified explicitly by passing a sequence of 1D + tensors. Alternatively, bin edges may be constructed automatically by passing a + sequence of integers specifying the number of equal-width bins in each dimension. + + For each N-dimensional point in input: + - Each of its coordinates is binned independently among the bin edges + corresponding to its dimension + - Binning results are combined to identify the N-dimensional bin (if any) + into which the point falls + - If the point falls into a bin, the bin's count (or total weight) is incremented + - Points which do not fall into any bin do not contribute to the output + + :attr:`bins` can be a sequence of N 1D tensors, a sequence of N ints, or a single int. + + If :attr:`bins` is a sequence of N 1D tensors, it explicitly specifies the N sequences + of bin edges. Each 1D tensor should contain a strictly increasing sequence with at + least one element. A sequence of K bin edges defines K-1 bins, explicitly specifying + the left and right edges of all bins. Every bin is inclusive of its left edge. Only + the rightmost bin is inclusive of its right edge. + + If :attr:`bins` is a sequence of N ints, it specifies the number of equal-width bins + in each dimension. By default, the leftmost and rightmost bin edges in each dimension + are determined by the minimum and maximum elements of the input tensor in the + corresponding dimension. The :attr:`range` argument can be provided to manually + specify the leftmost and rightmost bin edges in each dimension. + + If :attr:`bins` is an int, it specifies the number of equal-width bins for all dimensions. + + .. note:: + See also :func:`torch.histogram`, which specifically computes 1D histograms. + While :func:`torch.histogramdd` infers the dimensionality of its bins and + binned values from the shape of :attr:`input`, :func:`torch.histogram` + accepts and flattens :attr:`input` of any shape. + + Args: + input (Tensor): the input tensor. + bins: Tensor[], int[], or int. + If Tensor[], defines the sequences of bin edges. + If int[], defines the number of equal-width bins in each dimension. + If int, defines the number of equal-width bins for all dimensions. + Keyword args: + range (sequence of float): Defines the leftmost and rightmost bin edges + in each dimension. + weight (Tensor): By default, each value in the input has weight 1. If a weight + tensor is passed, each N-dimensional coordinate in input + contributes its associated weight towards its bin's result. + The weight tensor should have the same shape as the :attr:`input` + tensor excluding its innermost dimension N. + density (bool): If False (default), the result will contain the count (or total weight) + in each bin. If True, each count (weight) is divided by the total count + (total weight), then divided by the volume of its associated bin. + Returns: + hist (Tensor): N-dimensional Tensor containing the values of the histogram. + bin_edges(Tensor[]): sequence of N 1D Tensors containing the bin edges. + + Example:: + + >>> torch.histogramdd(torch.tensor([[0., 1.], [1., 0.], [2., 0.], [2., 2.]]), bins=[3, 3], + ... weight=torch.tensor([1., 2., 4., 8.])) + torch.return_types.histogramdd( + hist=tensor([[0., 1., 0.], + [2., 0., 0.], + [4., 0., 8.]]), + bin_edges=(tensor([0.0000, 0.6667, 1.3333, 2.0000]), + tensor([0.0000, 0.6667, 1.3333, 2.0000]))) + + >>> torch.histogramdd(torch.tensor([[0., 0.], [1., 1.], [2., 2.]]), bins=[2, 2], + ... range=[0., 1., 0., 1.], density=True) + torch.return_types.histogramdd( + hist=tensor([[2., 0.], + [0., 2.]]), + bin_edges=(tensor([0.0000, 0.5000, 1.0000]), + tensor([0.0000, 0.5000, 1.0000]))) + """ + +@overload +def histogramdd( + input: Tensor, + bins: _size, + range: Sequence[_float] | None = None, + weight: Tensor | None = None, + density: _bool = False, +) -> torch.return_types.histogramdd: + r""" + histogramdd(input, bins, *, range=None, weight=None, density=False, out=None) -> (Tensor, Tensor[]) + + Computes a multi-dimensional histogram of the values in a tensor. + + Interprets the elements of an input tensor whose innermost dimension has size N + as a collection of N-dimensional points. Maps each of the points into a set of + N-dimensional bins and returns the number of points (or total weight) in each bin. + + :attr:`input` must be a tensor with at least 2 dimensions. + If input has shape (M, N), each of its M rows defines a point in N-dimensional space. + If input has three or more dimensions, all but the last dimension are flattened. + + Each dimension is independently associated with its own strictly increasing sequence + of bin edges. Bin edges may be specified explicitly by passing a sequence of 1D + tensors. Alternatively, bin edges may be constructed automatically by passing a + sequence of integers specifying the number of equal-width bins in each dimension. + + For each N-dimensional point in input: + - Each of its coordinates is binned independently among the bin edges + corresponding to its dimension + - Binning results are combined to identify the N-dimensional bin (if any) + into which the point falls + - If the point falls into a bin, the bin's count (or total weight) is incremented + - Points which do not fall into any bin do not contribute to the output + + :attr:`bins` can be a sequence of N 1D tensors, a sequence of N ints, or a single int. + + If :attr:`bins` is a sequence of N 1D tensors, it explicitly specifies the N sequences + of bin edges. Each 1D tensor should contain a strictly increasing sequence with at + least one element. A sequence of K bin edges defines K-1 bins, explicitly specifying + the left and right edges of all bins. Every bin is inclusive of its left edge. Only + the rightmost bin is inclusive of its right edge. + + If :attr:`bins` is a sequence of N ints, it specifies the number of equal-width bins + in each dimension. By default, the leftmost and rightmost bin edges in each dimension + are determined by the minimum and maximum elements of the input tensor in the + corresponding dimension. The :attr:`range` argument can be provided to manually + specify the leftmost and rightmost bin edges in each dimension. + + If :attr:`bins` is an int, it specifies the number of equal-width bins for all dimensions. + + .. note:: + See also :func:`torch.histogram`, which specifically computes 1D histograms. + While :func:`torch.histogramdd` infers the dimensionality of its bins and + binned values from the shape of :attr:`input`, :func:`torch.histogram` + accepts and flattens :attr:`input` of any shape. + + Args: + input (Tensor): the input tensor. + bins: Tensor[], int[], or int. + If Tensor[], defines the sequences of bin edges. + If int[], defines the number of equal-width bins in each dimension. + If int, defines the number of equal-width bins for all dimensions. + Keyword args: + range (sequence of float): Defines the leftmost and rightmost bin edges + in each dimension. + weight (Tensor): By default, each value in the input has weight 1. If a weight + tensor is passed, each N-dimensional coordinate in input + contributes its associated weight towards its bin's result. + The weight tensor should have the same shape as the :attr:`input` + tensor excluding its innermost dimension N. + density (bool): If False (default), the result will contain the count (or total weight) + in each bin. If True, each count (weight) is divided by the total count + (total weight), then divided by the volume of its associated bin. + Returns: + hist (Tensor): N-dimensional Tensor containing the values of the histogram. + bin_edges(Tensor[]): sequence of N 1D Tensors containing the bin edges. + + Example:: + + >>> torch.histogramdd(torch.tensor([[0., 1.], [1., 0.], [2., 0.], [2., 2.]]), bins=[3, 3], + ... weight=torch.tensor([1., 2., 4., 8.])) + torch.return_types.histogramdd( + hist=tensor([[0., 1., 0.], + [2., 0., 0.], + [4., 0., 8.]]), + bin_edges=(tensor([0.0000, 0.6667, 1.3333, 2.0000]), + tensor([0.0000, 0.6667, 1.3333, 2.0000]))) + + >>> torch.histogramdd(torch.tensor([[0., 0.], [1., 1.], [2., 2.]]), bins=[2, 2], + ... range=[0., 1., 0., 1.], density=True) + torch.return_types.histogramdd( + hist=tensor([[2., 0.], + [0., 2.]]), + bin_edges=(tensor([0.0000, 0.5000, 1.0000]), + tensor([0.0000, 0.5000, 1.0000]))) + """ + +@overload +def histogramdd( + input: Tensor, + bins: tuple[Tensor, ...] | list[Tensor] | None, + range: Sequence[_float] | None = None, + weight: Tensor | None = None, + density: _bool = False, +) -> torch.return_types.histogramdd: + r""" + histogramdd(input, bins, *, range=None, weight=None, density=False, out=None) -> (Tensor, Tensor[]) + + Computes a multi-dimensional histogram of the values in a tensor. + + Interprets the elements of an input tensor whose innermost dimension has size N + as a collection of N-dimensional points. Maps each of the points into a set of + N-dimensional bins and returns the number of points (or total weight) in each bin. + + :attr:`input` must be a tensor with at least 2 dimensions. + If input has shape (M, N), each of its M rows defines a point in N-dimensional space. + If input has three or more dimensions, all but the last dimension are flattened. + + Each dimension is independently associated with its own strictly increasing sequence + of bin edges. Bin edges may be specified explicitly by passing a sequence of 1D + tensors. Alternatively, bin edges may be constructed automatically by passing a + sequence of integers specifying the number of equal-width bins in each dimension. + + For each N-dimensional point in input: + - Each of its coordinates is binned independently among the bin edges + corresponding to its dimension + - Binning results are combined to identify the N-dimensional bin (if any) + into which the point falls + - If the point falls into a bin, the bin's count (or total weight) is incremented + - Points which do not fall into any bin do not contribute to the output + + :attr:`bins` can be a sequence of N 1D tensors, a sequence of N ints, or a single int. + + If :attr:`bins` is a sequence of N 1D tensors, it explicitly specifies the N sequences + of bin edges. Each 1D tensor should contain a strictly increasing sequence with at + least one element. A sequence of K bin edges defines K-1 bins, explicitly specifying + the left and right edges of all bins. Every bin is inclusive of its left edge. Only + the rightmost bin is inclusive of its right edge. + + If :attr:`bins` is a sequence of N ints, it specifies the number of equal-width bins + in each dimension. By default, the leftmost and rightmost bin edges in each dimension + are determined by the minimum and maximum elements of the input tensor in the + corresponding dimension. The :attr:`range` argument can be provided to manually + specify the leftmost and rightmost bin edges in each dimension. + + If :attr:`bins` is an int, it specifies the number of equal-width bins for all dimensions. + + .. note:: + See also :func:`torch.histogram`, which specifically computes 1D histograms. + While :func:`torch.histogramdd` infers the dimensionality of its bins and + binned values from the shape of :attr:`input`, :func:`torch.histogram` + accepts and flattens :attr:`input` of any shape. + + Args: + input (Tensor): the input tensor. + bins: Tensor[], int[], or int. + If Tensor[], defines the sequences of bin edges. + If int[], defines the number of equal-width bins in each dimension. + If int, defines the number of equal-width bins for all dimensions. + Keyword args: + range (sequence of float): Defines the leftmost and rightmost bin edges + in each dimension. + weight (Tensor): By default, each value in the input has weight 1. If a weight + tensor is passed, each N-dimensional coordinate in input + contributes its associated weight towards its bin's result. + The weight tensor should have the same shape as the :attr:`input` + tensor excluding its innermost dimension N. + density (bool): If False (default), the result will contain the count (or total weight) + in each bin. If True, each count (weight) is divided by the total count + (total weight), then divided by the volume of its associated bin. + Returns: + hist (Tensor): N-dimensional Tensor containing the values of the histogram. + bin_edges(Tensor[]): sequence of N 1D Tensors containing the bin edges. + + Example:: + + >>> torch.histogramdd(torch.tensor([[0., 1.], [1., 0.], [2., 0.], [2., 2.]]), bins=[3, 3], + ... weight=torch.tensor([1., 2., 4., 8.])) + torch.return_types.histogramdd( + hist=tensor([[0., 1., 0.], + [2., 0., 0.], + [4., 0., 8.]]), + bin_edges=(tensor([0.0000, 0.6667, 1.3333, 2.0000]), + tensor([0.0000, 0.6667, 1.3333, 2.0000]))) + + >>> torch.histogramdd(torch.tensor([[0., 0.], [1., 1.], [2., 2.]]), bins=[2, 2], + ... range=[0., 1., 0., 1.], density=True) + torch.return_types.histogramdd( + hist=tensor([[2., 0.], + [0., 2.]]), + bin_edges=(tensor([0.0000, 0.5000, 1.0000]), + tensor([0.0000, 0.5000, 1.0000]))) + """ + +def hsmm(input: Tensor, mat2: Tensor) -> Tensor: ... +@overload +def hsplit(input: Tensor, sections: _int) -> tuple[Tensor, ...]: + r""" + hsplit(input, indices_or_sections) -> List of Tensors + + Splits :attr:`input`, a tensor with one or more dimensions, into multiple tensors + horizontally according to :attr:`indices_or_sections`. Each split is a view of + :attr:`input`. + + If :attr:`input` is one dimensional this is equivalent to calling + torch.tensor_split(input, indices_or_sections, dim=0) (the split dimension is + zero), and if :attr:`input` has two or more dimensions it's equivalent to calling + torch.tensor_split(input, indices_or_sections, dim=1) (the split dimension is 1), + except that if :attr:`indices_or_sections` is an integer it must evenly divide + the split dimension or a runtime error will be thrown. + + This function is based on NumPy's :func:`numpy.hsplit`. + + Args: + input (Tensor): tensor to split. + indices_or_sections (int or list or tuple of ints): See argument in :func:`torch.tensor_split`. + + Example:: + + >>> t = torch.arange(16.0).reshape(4,4) + >>> t + tensor([[ 0., 1., 2., 3.], + [ 4., 5., 6., 7.], + [ 8., 9., 10., 11.], + [12., 13., 14., 15.]]) + >>> torch.hsplit(t, 2) + (tensor([[ 0., 1.], + [ 4., 5.], + [ 8., 9.], + [12., 13.]]), + tensor([[ 2., 3.], + [ 6., 7.], + [10., 11.], + [14., 15.]])) + >>> torch.hsplit(t, [3, 6]) + (tensor([[ 0., 1., 2.], + [ 4., 5., 6.], + [ 8., 9., 10.], + [12., 13., 14.]]), + tensor([[ 3.], + [ 7.], + [11.], + [15.]]), + tensor([], size=(4, 0))) + """ + +@overload +def hsplit(input: Tensor, indices: _size) -> tuple[Tensor, ...]: + r""" + hsplit(input, indices_or_sections) -> List of Tensors + + Splits :attr:`input`, a tensor with one or more dimensions, into multiple tensors + horizontally according to :attr:`indices_or_sections`. Each split is a view of + :attr:`input`. + + If :attr:`input` is one dimensional this is equivalent to calling + torch.tensor_split(input, indices_or_sections, dim=0) (the split dimension is + zero), and if :attr:`input` has two or more dimensions it's equivalent to calling + torch.tensor_split(input, indices_or_sections, dim=1) (the split dimension is 1), + except that if :attr:`indices_or_sections` is an integer it must evenly divide + the split dimension or a runtime error will be thrown. + + This function is based on NumPy's :func:`numpy.hsplit`. + + Args: + input (Tensor): tensor to split. + indices_or_sections (int or list or tuple of ints): See argument in :func:`torch.tensor_split`. + + Example:: + + >>> t = torch.arange(16.0).reshape(4,4) + >>> t + tensor([[ 0., 1., 2., 3.], + [ 4., 5., 6., 7.], + [ 8., 9., 10., 11.], + [12., 13., 14., 15.]]) + >>> torch.hsplit(t, 2) + (tensor([[ 0., 1.], + [ 4., 5.], + [ 8., 9.], + [12., 13.]]), + tensor([[ 2., 3.], + [ 6., 7.], + [10., 11.], + [14., 15.]])) + >>> torch.hsplit(t, [3, 6]) + (tensor([[ 0., 1., 2.], + [ 4., 5., 6.], + [ 8., 9., 10.], + [12., 13., 14.]]), + tensor([[ 3.], + [ 7.], + [11.], + [15.]]), + tensor([], size=(4, 0))) + """ + +def hspmm( + mat1: Tensor, + mat2: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + hspmm(mat1, mat2, *, out=None) -> Tensor + + Performs a matrix multiplication of a :ref:`sparse COO matrix + ` :attr:`mat1` and a strided matrix :attr:`mat2`. The + result is a (1 + 1)-dimensional :ref:`hybrid COO matrix + `. + + Args: + mat1 (Tensor): the first sparse matrix to be matrix multiplied + mat2 (Tensor): the second strided matrix to be matrix multiplied + + Keyword args: + out (Tensor, optional): the output tensor. + """ + +def hstack( + tensors: tuple[Tensor, ...] | list[Tensor] | None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + hstack(tensors, *, out=None) -> Tensor + + Stack tensors in sequence horizontally (column wise). + + This is equivalent to concatenation along the first axis for 1-D tensors, and along the second axis for all other tensors. + + Args: + tensors (sequence of Tensors): sequence of tensors to concatenate + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([1, 2, 3]) + >>> b = torch.tensor([4, 5, 6]) + >>> torch.hstack((a,b)) + tensor([1, 2, 3, 4, 5, 6]) + >>> a = torch.tensor([[1],[2],[3]]) + >>> b = torch.tensor([[4],[5],[6]]) + >>> torch.hstack((a,b)) + tensor([[1, 4], + [2, 5], + [3, 6]]) + """ + +def hypot( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + hypot(input, other, *, out=None) -> Tensor + + Given the legs of a right triangle, return its hypotenuse. + + .. math:: + \text{out}_{i} = \sqrt{\text{input}_{i}^{2} + \text{other}_{i}^{2}} + + The shapes of ``input`` and ``other`` must be + :ref:`broadcastable `. + + Args: + input (Tensor): the first input tensor + other (Tensor): the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.hypot(torch.tensor([4.0]), torch.tensor([3.0, 4.0, 5.0])) + tensor([5.0000, 5.6569, 6.4031]) + """ + +def i0(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + i0(input, *, out=None) -> Tensor + + Alias for :func:`torch.special.i0`. + """ + +def i0_(input: Tensor) -> Tensor: ... +def igamma( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + igamma(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.special.gammainc`. + """ + +def igammac( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + igammac(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.special.gammaincc`. + """ + +def imag(input: Tensor) -> Tensor: + r""" + imag(input) -> Tensor + + Returns a new tensor containing imaginary values of the :attr:`self` tensor. + The returned tensor and :attr:`self` share the same underlying storage. + + .. warning:: + :func:`imag` is only supported for tensors with complex dtypes. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> x=torch.randn(4, dtype=torch.cfloat) + >>> x + tensor([(0.3100+0.3553j), (-0.5445-0.7896j), (-1.6492-0.0633j), (-0.0638-0.8119j)]) + >>> x.imag + tensor([ 0.3553, -0.7896, -0.0633, -0.8119]) + """ + +@overload +def index_add( + input: Tensor, + dim: _int, + index: Tensor, + source: Tensor, + *, + alpha: Number | _complex = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + index_add(input: Tensor, dim: int, index: Tensor, source: Tensor, *, alpha: Union[Number, _complex] = 1, out: Optional[Tensor]) -> Tensor # noqa: B950 + + See :meth:`~Tensor.index_add_` for function description. + """ + +@overload +def index_add( + input: Tensor, + dim: str | EllipsisType | None, + index: Tensor, + source: Tensor, + *, + alpha: Number | _complex = 1, +) -> Tensor: + r""" + index_add(input: Tensor, dim: int, index: Tensor, source: Tensor, *, alpha: Union[Number, _complex] = 1, out: Optional[Tensor]) -> Tensor # noqa: B950 + + See :meth:`~Tensor.index_add_` for function description. + """ + +@overload +def index_copy( + input: Tensor, + dim: _int, + index: Tensor, + source: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + index_copy(input: Tensor, dim: int, index: Tensor, source: Tensor, *, out: Optional[Tensor]) -> Tensor + + See :meth:`~Tensor.index_add_` for function description. + """ + +@overload +def index_copy( + input: Tensor, + dim: str | EllipsisType | None, + index: Tensor, + source: Tensor, +) -> Tensor: + r""" + index_copy(input: Tensor, dim: int, index: Tensor, source: Tensor, *, out: Optional[Tensor]) -> Tensor + + See :meth:`~Tensor.index_add_` for function description. + """ + +@overload +def index_fill( + input: Tensor, + dim: _int, + index: Tensor, + value: Tensor, +) -> Tensor: ... +@overload +def index_fill( + input: Tensor, + dim: str | EllipsisType | None, + index: Tensor, + value: Tensor, +) -> Tensor: ... +@overload +def index_fill( + input: Tensor, + dim: _int, + index: Tensor, + value: Number | _complex, +) -> Tensor: ... +@overload +def index_fill( + input: Tensor, + dim: str | EllipsisType | None, + index: Tensor, + value: Number | _complex, +) -> Tensor: ... +def index_put( + input: Tensor, + indices: tuple[Tensor, ...] | list[Tensor] | None, + values: Tensor, + accumulate: _bool = False, +) -> Tensor: ... +def index_put_( + input: Tensor, + indices: tuple[Tensor, ...] | list[Tensor] | None, + values: Tensor, + accumulate: _bool = False, +) -> Tensor: ... +def index_reduce( + input: Tensor, + dim: _int, + index: Tensor, + source: Tensor, + reduce: str, + *, + include_self: _bool = True, + out: Tensor | None = None, +) -> Tensor: + r""" + index_reduce(input: Tensor, dim: int, index: Tensor, source: Tensor, reduce: str, *, include_self: bool = True, out: Optional[Tensor]) -> Tensor # noqa: B950 + + See :meth:`~Tensor.index_reduce_` for function description. + """ + +@overload +def index_select( + input: Tensor, + dim: _int, + index: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + index_select(input, dim, index, *, out=None) -> Tensor + + Returns a new tensor which indexes the :attr:`input` tensor along dimension + :attr:`dim` using the entries in :attr:`index`. + + The returned tensor has the same number of dimensions as the original tensor + (:attr:`input`). The :attr:`dim`\ th dimension has the same size as the length + of :attr:`index`; other dimensions have the same size as in the original tensor. + + .. note:: The returned tensor does **not** use the same storage as the original + tensor. If :attr:`out` has a different shape than expected, we + silently change it to the correct shape, reallocating the underlying + storage if necessary. + + Args: + input (Tensor): the input tensor. + dim (int): the dimension in which we index + index (IntTensor or LongTensor): the 1-D tensor containing the indices to index + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> x = torch.randn(3, 4) + >>> x + tensor([[ 0.1427, 0.0231, -0.5414, -1.0009], + [-0.4664, 0.2647, -0.1228, -1.1068], + [-1.1734, -0.6571, 0.7230, -0.6004]]) + >>> indices = torch.tensor([0, 2]) + >>> torch.index_select(x, 0, indices) + tensor([[ 0.1427, 0.0231, -0.5414, -1.0009], + [-1.1734, -0.6571, 0.7230, -0.6004]]) + >>> torch.index_select(x, 1, indices) + tensor([[ 0.1427, -0.5414], + [-0.4664, -0.1228], + [-1.1734, 0.7230]]) + """ + +@overload +def index_select( + input: Tensor, + dim: str | EllipsisType | None, + index: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + index_select(input, dim, index, *, out=None) -> Tensor + + Returns a new tensor which indexes the :attr:`input` tensor along dimension + :attr:`dim` using the entries in :attr:`index`. + + The returned tensor has the same number of dimensions as the original tensor + (:attr:`input`). The :attr:`dim`\ th dimension has the same size as the length + of :attr:`index`; other dimensions have the same size as in the original tensor. + + .. note:: The returned tensor does **not** use the same storage as the original + tensor. If :attr:`out` has a different shape than expected, we + silently change it to the correct shape, reallocating the underlying + storage if necessary. + + Args: + input (Tensor): the input tensor. + dim (int): the dimension in which we index + index (IntTensor or LongTensor): the 1-D tensor containing the indices to index + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> x = torch.randn(3, 4) + >>> x + tensor([[ 0.1427, 0.0231, -0.5414, -1.0009], + [-0.4664, 0.2647, -0.1228, -1.1068], + [-1.1734, -0.6571, 0.7230, -0.6004]]) + >>> indices = torch.tensor([0, 2]) + >>> torch.index_select(x, 0, indices) + tensor([[ 0.1427, 0.0231, -0.5414, -1.0009], + [-1.1734, -0.6571, 0.7230, -0.6004]]) + >>> torch.index_select(x, 1, indices) + tensor([[ 0.1427, -0.5414], + [-0.4664, -0.1228], + [-1.1734, 0.7230]]) + """ + +def indices_copy(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + Performs the same operation as :func:`torch.indices`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def init_num_threads() -> None: ... +def inner( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + inner(input, other, *, out=None) -> Tensor + + Computes the dot product for 1D tensors. For higher dimensions, sums the product + of elements from :attr:`input` and :attr:`other` along their last dimension. + + .. note:: + + If either :attr:`input` or :attr:`other` is a scalar, the result is equivalent + to `torch.mul(input, other)`. + + If both :attr:`input` and :attr:`other` are non-scalars, the size of their last + dimension must match and the result is equivalent to `torch.tensordot(input, + other, dims=([-1], [-1]))` + + Args: + input (Tensor): First input tensor + other (Tensor): Second input tensor + + Keyword args: + out (Tensor, optional): Optional output tensor to write result into. The output + shape is `input.shape[:-1] + other.shape[:-1]`. + + Example:: + + # Dot product + >>> torch.inner(torch.tensor([1, 2, 3]), torch.tensor([0, 2, 1])) + tensor(7) + + # Multidimensional input tensors + >>> a = torch.randn(2, 3) + >>> a + tensor([[0.8173, 1.0874, 1.1784], + [0.3279, 0.1234, 2.7894]]) + >>> b = torch.randn(2, 4, 3) + >>> b + tensor([[[-0.4682, -0.7159, 0.1506], + [ 0.4034, -0.3657, 1.0387], + [ 0.9892, -0.6684, 0.1774], + [ 0.9482, 1.3261, 0.3917]], + + [[ 0.4537, 0.7493, 1.1724], + [ 0.2291, 0.5749, -0.2267], + [-0.7920, 0.3607, -0.3701], + [ 1.3666, -0.5850, -1.7242]]]) + >>> torch.inner(a, b) + tensor([[[-0.9837, 1.1560, 0.2907, 2.6785], + [ 2.5671, 0.5452, -0.6912, -1.5509]], + + [[ 0.1782, 2.9843, 0.7366, 1.5672], + [ 3.5115, -0.4864, -1.2476, -4.4337]]]) + + # Scalar input + >>> torch.inner(a, torch.tensor(2)) + tensor([[1.6347, 2.1748, 2.3567], + [0.6558, 0.2469, 5.5787]]) + """ + +def instance_norm( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + running_mean: Tensor | None, + running_var: Tensor | None, + use_input_stats: _bool, + momentum: _float, + eps: _float, + cudnn_enabled: _bool, +) -> Tensor: ... +def int_repr(input: Tensor) -> Tensor: ... +def inverse(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + inverse(input, *, out=None) -> Tensor + + Alias for :func:`torch.linalg.inv` + """ + +def is_complex(input: Tensor) -> _bool: + r""" + is_complex(input: Tensor) -> bool + + Returns True if the data type of :attr:`input` is a complex data type i.e., + one of ``torch.complex64``, and ``torch.complex128``. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> torch.is_complex(torch.tensor([1, 2, 3], dtype=torch.complex64)) + True + >>> torch.is_complex(torch.tensor([1, 2, 3], dtype=torch.complex128)) + True + >>> torch.is_complex(torch.tensor([1, 2, 3], dtype=torch.int32)) + False + >>> torch.is_complex(torch.tensor([1.0, 2.0, 3.0], dtype=torch.float16)) + False + """ + +def is_conj(input: Tensor) -> _bool: + r""" + is_conj(input) -> (bool) + + Returns True if the :attr:`input` is a conjugated tensor, i.e. its conjugate bit is set to `True`. + + Args: + input (Tensor): the input tensor. + """ + +def is_distributed(input: Tensor) -> _bool: ... +def is_floating_point(input: Tensor) -> _bool: + r""" + is_floating_point(input: Tensor) -> bool + + Returns True if the data type of :attr:`input` is a floating point data type i.e., + one of ``torch.float64``, ``torch.float32``, ``torch.float16``, and ``torch.bfloat16``. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> torch.is_floating_point(torch.tensor([1.0, 2.0, 3.0])) + True + >>> torch.is_floating_point(torch.tensor([1, 2, 3], dtype=torch.int32)) + False + >>> torch.is_floating_point(torch.tensor([1.0, 2.0, 3.0], dtype=torch.float16)) + True + >>> torch.is_floating_point(torch.tensor([1, 2, 3], dtype=torch.complex64)) + False + """ + +def is_grad_enabled() -> _bool: + r""" + is_grad_enabled() -> (bool) + + Returns True if grad mode is currently enabled. + """ + +def is_inference(input: Tensor) -> _bool: + r""" + is_inference(input) -> (bool) + + Returns True if :attr:`input` is an inference tensor. + + A non-view tensor is an inference tensor if and only if it was + allocated during inference mode. A view tensor is an inference + tensor if and only if the tensor it is a view of is an inference tensor. + + For details on inference mode please see + `Inference Mode `_. + + Args: + input (Tensor): the input tensor. + """ + +def is_inference_mode_enabled() -> _bool: + r""" + is_inference_mode_enabled() -> (bool) + + Returns True if inference mode is currently enabled. + """ + +def is_neg(input: Tensor) -> _bool: ... +def is_nonzero(input: Tensor) -> _bool: + r""" + is_nonzero(input) -> (bool) + + Returns True if the :attr:`input` is a single element tensor which is not equal to zero + after type conversions. + i.e. not equal to ``torch.tensor([0.])`` or ``torch.tensor([0])`` or + ``torch.tensor([False])``. + Throws a ``RuntimeError`` if ``torch.numel() != 1`` (even in case + of sparse tensors). + + Args: + input (Tensor): the input tensor. + + Examples:: + + >>> torch.is_nonzero(torch.tensor([0.])) + False + >>> torch.is_nonzero(torch.tensor([1.5])) + True + >>> torch.is_nonzero(torch.tensor([False])) + False + >>> torch.is_nonzero(torch.tensor([3])) + True + >>> torch.is_nonzero(torch.tensor([1, 3, 5])) + Traceback (most recent call last): + ... + RuntimeError: Boolean value of Tensor with more than one value is ambiguous + >>> torch.is_nonzero(torch.tensor([])) + Traceback (most recent call last): + ... + RuntimeError: Boolean value of Tensor with no values is ambiguous + """ + +def is_same_size(input: Tensor, other: Tensor) -> _bool: ... +def is_signed(input: Tensor) -> _bool: ... +def is_vulkan_available() -> _bool: ... +def isclose( + input: Tensor, + other: Tensor, + rtol: _float = 1e-05, + atol: _float = 1e-08, + equal_nan: _bool = False, +) -> Tensor: + r""" + isclose(input, other, rtol=1e-05, atol=1e-08, equal_nan=False) -> Tensor + + Returns a new tensor with boolean elements representing if each element of + :attr:`input` is "close" to the corresponding element of :attr:`other`. + Closeness is defined as: + + .. math:: + \lvert \text{input}_i - \text{other}_i \rvert \leq \texttt{rtol} \times \lvert \text{other}_i \rvert + \texttt{atol} + + + where :attr:`input` and :attr:`other` are finite. Where :attr:`input` + and/or :attr:`other` are nonfinite they are close if and only if + they are equal, with NaNs being considered equal to each other when + :attr:`equal_nan` is True. + + Args: + input (Tensor): first tensor to compare + other (Tensor): second tensor to compare + rtol (float, optional): relative tolerance. Default: 1e-05 + atol (float, optional): absolute tolerance. Default: 1e-08 + equal_nan (bool, optional): if ``True``, then two ``NaN`` s will be considered equal. Default: ``False`` + + Examples:: + + >>> torch.isclose(torch.tensor((1., 2, 3)), torch.tensor((1 + 1e-10, 3, 4))) + tensor([ True, False, False]) + >>> torch.isclose(torch.tensor((float('inf'), 4)), torch.tensor((float('inf'), 6)), rtol=.5) + tensor([True, True]) + """ + +def isfinite(input: Tensor) -> Tensor: + r""" + isfinite(input) -> Tensor + + Returns a new tensor with boolean elements representing if each element is `finite` or not. + + Real values are finite when they are not NaN, negative infinity, or infinity. + Complex values are finite when both their real and imaginary parts are finite. + + Args: + input (Tensor): the input tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is finite and False elsewhere + + Example:: + + >>> torch.isfinite(torch.tensor([1, float('inf'), 2, float('-inf'), float('nan')])) + tensor([True, False, True, False, False]) + """ + +@overload +def isin( + elements: Tensor, + test_elements: Tensor, + *, + assume_unique: _bool = False, + invert: _bool = False, + out: Tensor | None = None, +) -> Tensor: + r""" + isin(elements, test_elements, *, assume_unique=False, invert=False) -> Tensor + + Tests if each element of :attr:`elements` is in :attr:`test_elements`. Returns + a boolean tensor of the same shape as :attr:`elements` that is True for elements + in :attr:`test_elements` and False otherwise. + + .. note:: + One of :attr:`elements` or :attr:`test_elements` can be a scalar, but not both. + + Args: + elements (Tensor or Scalar): Input elements + test_elements (Tensor or Scalar): Values against which to test for each input element + assume_unique (bool, optional): If True, assumes both :attr:`elements` and + :attr:`test_elements` contain unique elements, which can speed up the + calculation. Default: False + invert (bool, optional): If True, inverts the boolean return tensor, resulting in True + values for elements *not* in :attr:`test_elements`. Default: False + + Returns: + A boolean tensor of the same shape as :attr:`elements` that is True for elements in + :attr:`test_elements` and False otherwise + + Example: + >>> torch.isin(torch.tensor([[1, 2], [3, 4]]), torch.tensor([2, 3])) + tensor([[False, True], + [ True, False]]) + """ + +@overload +def isin( + element: Number | _complex, + test_elements: Tensor, + *, + assume_unique: _bool = False, + invert: _bool = False, + out: Tensor | None = None, +) -> Tensor: + r""" + isin(elements, test_elements, *, assume_unique=False, invert=False) -> Tensor + + Tests if each element of :attr:`elements` is in :attr:`test_elements`. Returns + a boolean tensor of the same shape as :attr:`elements` that is True for elements + in :attr:`test_elements` and False otherwise. + + .. note:: + One of :attr:`elements` or :attr:`test_elements` can be a scalar, but not both. + + Args: + elements (Tensor or Scalar): Input elements + test_elements (Tensor or Scalar): Values against which to test for each input element + assume_unique (bool, optional): If True, assumes both :attr:`elements` and + :attr:`test_elements` contain unique elements, which can speed up the + calculation. Default: False + invert (bool, optional): If True, inverts the boolean return tensor, resulting in True + values for elements *not* in :attr:`test_elements`. Default: False + + Returns: + A boolean tensor of the same shape as :attr:`elements` that is True for elements in + :attr:`test_elements` and False otherwise + + Example: + >>> torch.isin(torch.tensor([[1, 2], [3, 4]]), torch.tensor([2, 3])) + tensor([[False, True], + [ True, False]]) + """ + +@overload +def isin( + elements: Tensor, + test_element: Number | _complex, + *, + assume_unique: _bool = False, + invert: _bool = False, + out: Tensor | None = None, +) -> Tensor: + r""" + isin(elements, test_elements, *, assume_unique=False, invert=False) -> Tensor + + Tests if each element of :attr:`elements` is in :attr:`test_elements`. Returns + a boolean tensor of the same shape as :attr:`elements` that is True for elements + in :attr:`test_elements` and False otherwise. + + .. note:: + One of :attr:`elements` or :attr:`test_elements` can be a scalar, but not both. + + Args: + elements (Tensor or Scalar): Input elements + test_elements (Tensor or Scalar): Values against which to test for each input element + assume_unique (bool, optional): If True, assumes both :attr:`elements` and + :attr:`test_elements` contain unique elements, which can speed up the + calculation. Default: False + invert (bool, optional): If True, inverts the boolean return tensor, resulting in True + values for elements *not* in :attr:`test_elements`. Default: False + + Returns: + A boolean tensor of the same shape as :attr:`elements` that is True for elements in + :attr:`test_elements` and False otherwise + + Example: + >>> torch.isin(torch.tensor([[1, 2], [3, 4]]), torch.tensor([2, 3])) + tensor([[False, True], + [ True, False]]) + """ + +def isinf(input: Tensor) -> Tensor: + r""" + isinf(input) -> Tensor + + Tests if each element of :attr:`input` is infinite + (positive or negative infinity) or not. + + .. note:: + Complex values are infinite when their real or imaginary part is + infinite. + + Args: + input (Tensor): the input tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is infinite and False elsewhere + + Example:: + + >>> torch.isinf(torch.tensor([1, float('inf'), 2, float('-inf'), float('nan')])) + tensor([False, True, False, True, False]) + """ + +def isnan(input: Tensor) -> Tensor: + r""" + isnan(input) -> Tensor + + Returns a new tensor with boolean elements representing if each element of :attr:`input` + is NaN or not. Complex values are considered NaN when either their real + and/or imaginary part is NaN. + + Arguments: + input (Tensor): the input tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is NaN and False elsewhere + + Example:: + + >>> torch.isnan(torch.tensor([1, float('nan'), 2])) + tensor([False, True, False]) + """ + +def isneginf(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + isneginf(input, *, out=None) -> Tensor + Tests if each element of :attr:`input` is negative infinity or not. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([-float('inf'), float('inf'), 1.2]) + >>> torch.isneginf(a) + tensor([ True, False, False]) + """ + +def isposinf(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + isposinf(input, *, out=None) -> Tensor + Tests if each element of :attr:`input` is positive infinity or not. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([-float('inf'), float('inf'), 1.2]) + >>> torch.isposinf(a) + tensor([False, True, False]) + """ + +def isreal(input: Tensor) -> Tensor: + r""" + isreal(input) -> Tensor + + Returns a new tensor with boolean elements representing if each element of :attr:`input` is real-valued or not. + All real-valued types are considered real. Complex values are considered real when their imaginary part is 0. + + Arguments: + input (Tensor): the input tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is real and False elsewhere + + Example:: + + >>> torch.isreal(torch.tensor([1, 1+1j, 2+0j])) + tensor([True, False, True]) + """ + +def istft( + input: Tensor, + n_fft: _int, + hop_length: _int | None = None, + win_length: _int | None = None, + window: Tensor | None = None, + center: _bool = True, + normalized: _bool = False, + onesided: _bool | None = None, + length: _int | None = None, + return_complex: _bool = False, +) -> Tensor: ... +@overload +def kaiser_window( + window_length: _int, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + kaiser_window(window_length, periodic=True, beta=12.0, *, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Computes the Kaiser window with window length :attr:`window_length` and shape parameter :attr:`beta`. + + Let I_0 be the zeroth order modified Bessel function of the first kind (see :func:`torch.i0`) and + ``N = L - 1`` if :attr:`periodic` is False and ``L`` if :attr:`periodic` is True, + where ``L`` is the :attr:`window_length`. This function computes: + + .. math:: + out_i = I_0 \left( \beta \sqrt{1 - \left( {\frac{i - N/2}{N/2}} \right) ^2 } \right) / I_0( \beta ) + + Calling ``torch.kaiser_window(L, B, periodic=True)`` is equivalent to calling + ``torch.kaiser_window(L + 1, B, periodic=False)[:-1])``. + The :attr:`periodic` argument is intended as a helpful shorthand + to produce a periodic window as input to functions like :func:`torch.stft`. + + .. note:: + If :attr:`window_length` is one, then the returned window is a single element tensor containing a one. + + + Args: + window_length (int): length of the window. + periodic (bool, optional): If True, returns a periodic window suitable for use in spectral analysis. + If False, returns a symmetric window suitable for use in filter design. + beta (float, optional): shape parameter for the window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + """ + +@overload +def kaiser_window( + window_length: _int, + periodic: _bool, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + kaiser_window(window_length, periodic=True, beta=12.0, *, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Computes the Kaiser window with window length :attr:`window_length` and shape parameter :attr:`beta`. + + Let I_0 be the zeroth order modified Bessel function of the first kind (see :func:`torch.i0`) and + ``N = L - 1`` if :attr:`periodic` is False and ``L`` if :attr:`periodic` is True, + where ``L`` is the :attr:`window_length`. This function computes: + + .. math:: + out_i = I_0 \left( \beta \sqrt{1 - \left( {\frac{i - N/2}{N/2}} \right) ^2 } \right) / I_0( \beta ) + + Calling ``torch.kaiser_window(L, B, periodic=True)`` is equivalent to calling + ``torch.kaiser_window(L + 1, B, periodic=False)[:-1])``. + The :attr:`periodic` argument is intended as a helpful shorthand + to produce a periodic window as input to functions like :func:`torch.stft`. + + .. note:: + If :attr:`window_length` is one, then the returned window is a single element tensor containing a one. + + + Args: + window_length (int): length of the window. + periodic (bool, optional): If True, returns a periodic window suitable for use in spectral analysis. + If False, returns a symmetric window suitable for use in filter design. + beta (float, optional): shape parameter for the window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + """ + +@overload +def kaiser_window( + window_length: _int, + periodic: _bool, + beta: _float, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + kaiser_window(window_length, periodic=True, beta=12.0, *, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Computes the Kaiser window with window length :attr:`window_length` and shape parameter :attr:`beta`. + + Let I_0 be the zeroth order modified Bessel function of the first kind (see :func:`torch.i0`) and + ``N = L - 1`` if :attr:`periodic` is False and ``L`` if :attr:`periodic` is True, + where ``L`` is the :attr:`window_length`. This function computes: + + .. math:: + out_i = I_0 \left( \beta \sqrt{1 - \left( {\frac{i - N/2}{N/2}} \right) ^2 } \right) / I_0( \beta ) + + Calling ``torch.kaiser_window(L, B, periodic=True)`` is equivalent to calling + ``torch.kaiser_window(L + 1, B, periodic=False)[:-1])``. + The :attr:`periodic` argument is intended as a helpful shorthand + to produce a periodic window as input to functions like :func:`torch.stft`. + + .. note:: + If :attr:`window_length` is one, then the returned window is a single element tensor containing a one. + + + Args: + window_length (int): length of the window. + periodic (bool, optional): If True, returns a periodic window suitable for use in spectral analysis. + If False, returns a symmetric window suitable for use in filter design. + beta (float, optional): shape parameter for the window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + """ + +def kl_div( + input: Tensor, + target: Tensor, + reduction: _int = 1, + *, + log_target: _bool = False, +) -> Tensor: ... +def kron( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + kron(input, other, *, out=None) -> Tensor + + Computes the Kronecker product, denoted by :math:`\otimes`, of :attr:`input` and :attr:`other`. + + If :attr:`input` is a :math:`(a_0 \times a_1 \times \dots \times a_n)` tensor and :attr:`other` is a + :math:`(b_0 \times b_1 \times \dots \times b_n)` tensor, the result will be a + :math:`(a_0*b_0 \times a_1*b_1 \times \dots \times a_n*b_n)` tensor with the following entries: + + .. math:: + (\text{input} \otimes \text{other})_{k_0, k_1, \dots, k_n} = + \text{input}_{i_0, i_1, \dots, i_n} * \text{other}_{j_0, j_1, \dots, j_n}, + + where :math:`k_t = i_t * b_t + j_t` for :math:`0 \leq t \leq n`. + If one tensor has fewer dimensions than the other it is unsqueezed until it has the same number of dimensions. + + Supports real-valued and complex-valued inputs. + + .. note:: + This function generalizes the typical definition of the Kronecker product for two matrices to two tensors, + as described above. When :attr:`input` is a :math:`(m \times n)` matrix and :attr:`other` is a + :math:`(p \times q)` matrix, the result will be a :math:`(p*m \times q*n)` block matrix: + + .. math:: + \mathbf{A} \otimes \mathbf{B}=\begin{bmatrix} + a_{11} \mathbf{B} & \cdots & a_{1 n} \mathbf{B} \\ + \vdots & \ddots & \vdots \\ + a_{m 1} \mathbf{B} & \cdots & a_{m n} \mathbf{B} \end{bmatrix} + + where :attr:`input` is :math:`\mathbf{A}` and :attr:`other` is :math:`\mathbf{B}`. + + Arguments: + input (Tensor) + other (Tensor) + + Keyword args: + out (Tensor, optional): The output tensor. Ignored if ``None``. Default: ``None`` + + Examples:: + + >>> mat1 = torch.eye(2) + >>> mat2 = torch.ones(2, 2) + >>> torch.kron(mat1, mat2) + tensor([[1., 1., 0., 0.], + [1., 1., 0., 0.], + [0., 0., 1., 1.], + [0., 0., 1., 1.]]) + + >>> mat1 = torch.eye(2) + >>> mat2 = torch.arange(1, 5).reshape(2, 2) + >>> torch.kron(mat1, mat2) + tensor([[1., 2., 0., 0.], + [3., 4., 0., 0.], + [0., 0., 1., 2.], + [0., 0., 3., 4.]]) + """ + +@overload +def kthvalue( + input: Tensor, + k: _int | SymInt, + dim: _int = -1, + keepdim: _bool = False, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.kthvalue: + r""" + kthvalue(input, k, dim=None, keepdim=False, *, out=None) -> (Tensor, LongTensor) + + Returns a namedtuple ``(values, indices)`` where ``values`` is the :attr:`k` th + smallest element of each row of the :attr:`input` tensor in the given dimension + :attr:`dim`. And ``indices`` is the index location of each element found. + + If :attr:`dim` is not given, the last dimension of the `input` is chosen. + + If :attr:`keepdim` is ``True``, both the :attr:`values` and :attr:`indices` tensors + are the same size as :attr:`input`, except in the dimension :attr:`dim` where + they are of size 1. Otherwise, :attr:`dim` is squeezed + (see :func:`torch.squeeze`), resulting in both the :attr:`values` and + :attr:`indices` tensors having 1 fewer dimension than the :attr:`input` tensor. + + .. note:: + When :attr:`input` is a CUDA tensor and there are multiple valid + :attr:`k` th values, this function may nondeterministically return + :attr:`indices` for any of them. + + Args: + input (Tensor): the input tensor. + k (int): k for the k-th smallest element + dim (int, optional): the dimension to find the kth value along + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (tuple, optional): the output tuple of (Tensor, LongTensor) + can be optionally given to be used as output buffers + + Example:: + + >>> x = torch.arange(1., 6.) + >>> x + tensor([ 1., 2., 3., 4., 5.]) + >>> torch.kthvalue(x, 4) + torch.return_types.kthvalue(values=tensor(4.), indices=tensor(3)) + + >>> x=torch.arange(1.,7.).resize_(2,3) + >>> x + tensor([[ 1., 2., 3.], + [ 4., 5., 6.]]) + >>> torch.kthvalue(x, 2, 0, True) + torch.return_types.kthvalue(values=tensor([[4., 5., 6.]]), indices=tensor([[1, 1, 1]])) + """ + +@overload +def kthvalue( + input: Tensor, + k: _int | SymInt, + dim: str | EllipsisType | None, + keepdim: _bool = False, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.kthvalue: + r""" + kthvalue(input, k, dim=None, keepdim=False, *, out=None) -> (Tensor, LongTensor) + + Returns a namedtuple ``(values, indices)`` where ``values`` is the :attr:`k` th + smallest element of each row of the :attr:`input` tensor in the given dimension + :attr:`dim`. And ``indices`` is the index location of each element found. + + If :attr:`dim` is not given, the last dimension of the `input` is chosen. + + If :attr:`keepdim` is ``True``, both the :attr:`values` and :attr:`indices` tensors + are the same size as :attr:`input`, except in the dimension :attr:`dim` where + they are of size 1. Otherwise, :attr:`dim` is squeezed + (see :func:`torch.squeeze`), resulting in both the :attr:`values` and + :attr:`indices` tensors having 1 fewer dimension than the :attr:`input` tensor. + + .. note:: + When :attr:`input` is a CUDA tensor and there are multiple valid + :attr:`k` th values, this function may nondeterministically return + :attr:`indices` for any of them. + + Args: + input (Tensor): the input tensor. + k (int): k for the k-th smallest element + dim (int, optional): the dimension to find the kth value along + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (tuple, optional): the output tuple of (Tensor, LongTensor) + can be optionally given to be used as output buffers + + Example:: + + >>> x = torch.arange(1., 6.) + >>> x + tensor([ 1., 2., 3., 4., 5.]) + >>> torch.kthvalue(x, 4) + torch.return_types.kthvalue(values=tensor(4.), indices=tensor(3)) + + >>> x=torch.arange(1.,7.).resize_(2,3) + >>> x + tensor([[ 1., 2., 3.], + [ 4., 5., 6.]]) + >>> torch.kthvalue(x, 2, 0, True) + torch.return_types.kthvalue(values=tensor([[4., 5., 6.]]), indices=tensor([[1, 1, 1]])) + """ + +def layer_norm( + input: Tensor, + normalized_shape: Sequence[_int | SymInt], + weight: Tensor | None = None, + bias: Tensor | None = None, + eps: _float = 1e-05, + cudnn_enable: _bool = True, +) -> Tensor: ... +def lcm( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + lcm(input, other, *, out=None) -> Tensor + + Computes the element-wise least common multiple (LCM) of :attr:`input` and :attr:`other`. + + Both :attr:`input` and :attr:`other` must have integer types. + + .. note:: + This defines :math:`lcm(0, 0) = 0` and :math:`lcm(0, a) = 0`. + + Args: + input (Tensor): the input tensor. + other (Tensor): the second input tensor + + Keyword arguments: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([5, 10, 15]) + >>> b = torch.tensor([3, 4, 5]) + >>> torch.lcm(a, b) + tensor([15, 20, 15]) + >>> c = torch.tensor([3]) + >>> torch.lcm(a, c) + tensor([15, 30, 15]) + """ + +def lcm_(input: Tensor, other: Tensor) -> Tensor: ... +def ldexp( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + ldexp(input, other, *, out=None) -> Tensor + + Multiplies :attr:`input` by 2 ** :attr:`other`. + + .. math:: + \text{{out}}_i = \text{{input}}_i * 2^\text{{other}}_i + + + Typically this function is used to construct floating point numbers by multiplying + mantissas in :attr:`input` with integral powers of two created from the exponents + in :attr:`other`. + + Args: + input (Tensor): the input tensor. + other (Tensor): a tensor of exponents, typically integers. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.ldexp(torch.tensor([1.]), torch.tensor([1])) + tensor([2.]) + >>> torch.ldexp(torch.tensor([1.0]), torch.tensor([1, 2, 3, 4])) + tensor([ 2., 4., 8., 16.]) + """ + +def ldexp_(input: Tensor, other: Tensor) -> Tensor: ... +@overload +def le( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + le(input, other, *, out=None) -> Tensor + + Computes :math:`\text{input} \leq \text{other}` element-wise. + + + The second argument can be a number or a tensor whose shape is + :ref:`broadcastable ` with the first argument. + + Args: + input (Tensor): the tensor to compare + other (Tensor or Scalar): the tensor or value to compare + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is less than or equal to + :attr:`other` and False elsewhere + + Example:: + + >>> torch.le(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[True, False], [True, True]]) + """ + +@overload +def le( + input: Tensor, + other: Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + le(input, other, *, out=None) -> Tensor + + Computes :math:`\text{input} \leq \text{other}` element-wise. + + + The second argument can be a number or a tensor whose shape is + :ref:`broadcastable ` with the first argument. + + Args: + input (Tensor): the tensor to compare + other (Tensor or Scalar): the tensor or value to compare + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is less than or equal to + :attr:`other` and False elsewhere + + Example:: + + >>> torch.le(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[True, False], [True, True]]) + """ + +@overload +def lerp( + input: Tensor, + end: Tensor, + weight: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + lerp(input, end, weight, *, out=None) + + Does a linear interpolation of two tensors :attr:`start` (given by :attr:`input`) and :attr:`end` based + on a scalar or tensor :attr:`weight` and returns the resulting :attr:`out` tensor. + + .. math:: + \text{out}_i = \text{start}_i + \text{weight}_i \times (\text{end}_i - \text{start}_i) + + The shapes of :attr:`start` and :attr:`end` must be + :ref:`broadcastable `. If :attr:`weight` is a tensor, then + the shapes of :attr:`weight`, :attr:`start`, and :attr:`end` must be :ref:`broadcastable `. + + Args: + input (Tensor): the tensor with the starting points + end (Tensor): the tensor with the ending points + weight (float or tensor): the weight for the interpolation formula + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> start = torch.arange(1., 5.) + >>> end = torch.empty(4).fill_(10) + >>> start + tensor([ 1., 2., 3., 4.]) + >>> end + tensor([ 10., 10., 10., 10.]) + >>> torch.lerp(start, end, 0.5) + tensor([ 5.5000, 6.0000, 6.5000, 7.0000]) + >>> torch.lerp(start, end, torch.full_like(start, 0.5)) + tensor([ 5.5000, 6.0000, 6.5000, 7.0000]) + """ + +@overload +def lerp( + input: Tensor, + end: Tensor, + weight: Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + lerp(input, end, weight, *, out=None) + + Does a linear interpolation of two tensors :attr:`start` (given by :attr:`input`) and :attr:`end` based + on a scalar or tensor :attr:`weight` and returns the resulting :attr:`out` tensor. + + .. math:: + \text{out}_i = \text{start}_i + \text{weight}_i \times (\text{end}_i - \text{start}_i) + + The shapes of :attr:`start` and :attr:`end` must be + :ref:`broadcastable `. If :attr:`weight` is a tensor, then + the shapes of :attr:`weight`, :attr:`start`, and :attr:`end` must be :ref:`broadcastable `. + + Args: + input (Tensor): the tensor with the starting points + end (Tensor): the tensor with the ending points + weight (float or tensor): the weight for the interpolation formula + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> start = torch.arange(1., 5.) + >>> end = torch.empty(4).fill_(10) + >>> start + tensor([ 1., 2., 3., 4.]) + >>> end + tensor([ 10., 10., 10., 10.]) + >>> torch.lerp(start, end, 0.5) + tensor([ 5.5000, 6.0000, 6.5000, 7.0000]) + >>> torch.lerp(start, end, torch.full_like(start, 0.5)) + tensor([ 5.5000, 6.0000, 6.5000, 7.0000]) + """ + +@overload +def less( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + less(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.lt`. + """ + +@overload +def less( + input: Tensor, + other: Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + less(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.lt`. + """ + +@overload +def less_equal( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + less_equal(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.le`. + """ + +@overload +def less_equal( + input: Tensor, + other: Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + less_equal(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.le`. + """ + +def lgamma(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + lgamma(input, *, out=None) -> Tensor + + Computes the natural logarithm of the absolute value of the gamma function on :attr:`input`. + + .. math:: + \text{out}_{i} = \ln |\Gamma(\text{input}_{i})| + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.arange(0.5, 2, 0.5) + >>> torch.lgamma(a) + tensor([ 0.5724, 0.0000, -0.1208]) + """ + +@overload +def linspace( + start: Number, + end: Number, + steps: _int | None = None, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + pin_memory: _bool = False, +) -> Tensor: + r""" + linspace(start, end, steps, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Creates a one-dimensional tensor of size :attr:`steps` whose values are evenly + spaced from :attr:`start` to :attr:`end`, inclusive. That is, the value are: + + .. math:: + (\text{start}, + \text{start} + \frac{\text{end} - \text{start}}{\text{steps} - 1}, + \ldots, + \text{start} + (\text{steps} - 2) * \frac{\text{end} - \text{start}}{\text{steps} - 1}, + \text{end}) + + + From PyTorch 1.11 linspace requires the steps argument. Use steps=100 to restore the previous behavior. + + Args: + start (float or Tensor): the starting value for the set of points. If `Tensor`, it must be 0-dimensional + end (float or Tensor): the ending value for the set of points. If `Tensor`, it must be 0-dimensional + steps (int): size of the constructed tensor + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the data type to perform the computation in. + Default: if None, uses the global default dtype (see torch.get_default_dtype()) + when both :attr:`start` and :attr:`end` are real, + and corresponding complex dtype when either is complex. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + + Example:: + + >>> torch.linspace(3, 10, steps=5) + tensor([ 3.0000, 4.7500, 6.5000, 8.2500, 10.0000]) + >>> torch.linspace(-10, 10, steps=5) + tensor([-10., -5., 0., 5., 10.]) + >>> torch.linspace(start=-10, end=10, steps=5) + tensor([-10., -5., 0., 5., 10.]) + >>> torch.linspace(start=-10, end=10, steps=1) + tensor([-10.]) + """ + +@overload +def linspace( + start: Tensor, + end: Tensor, + steps: _int, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + linspace(start, end, steps, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Creates a one-dimensional tensor of size :attr:`steps` whose values are evenly + spaced from :attr:`start` to :attr:`end`, inclusive. That is, the value are: + + .. math:: + (\text{start}, + \text{start} + \frac{\text{end} - \text{start}}{\text{steps} - 1}, + \ldots, + \text{start} + (\text{steps} - 2) * \frac{\text{end} - \text{start}}{\text{steps} - 1}, + \text{end}) + + + From PyTorch 1.11 linspace requires the steps argument. Use steps=100 to restore the previous behavior. + + Args: + start (float or Tensor): the starting value for the set of points. If `Tensor`, it must be 0-dimensional + end (float or Tensor): the ending value for the set of points. If `Tensor`, it must be 0-dimensional + steps (int): size of the constructed tensor + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the data type to perform the computation in. + Default: if None, uses the global default dtype (see torch.get_default_dtype()) + when both :attr:`start` and :attr:`end` are real, + and corresponding complex dtype when either is complex. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + + Example:: + + >>> torch.linspace(3, 10, steps=5) + tensor([ 3.0000, 4.7500, 6.5000, 8.2500, 10.0000]) + >>> torch.linspace(-10, 10, steps=5) + tensor([-10., -5., 0., 5., 10.]) + >>> torch.linspace(start=-10, end=10, steps=5) + tensor([-10., -5., 0., 5., 10.]) + >>> torch.linspace(start=-10, end=10, steps=1) + tensor([-10.]) + """ + +@overload +def linspace( + start: Number | _complex, + end: Tensor, + steps: _int, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + linspace(start, end, steps, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Creates a one-dimensional tensor of size :attr:`steps` whose values are evenly + spaced from :attr:`start` to :attr:`end`, inclusive. That is, the value are: + + .. math:: + (\text{start}, + \text{start} + \frac{\text{end} - \text{start}}{\text{steps} - 1}, + \ldots, + \text{start} + (\text{steps} - 2) * \frac{\text{end} - \text{start}}{\text{steps} - 1}, + \text{end}) + + + From PyTorch 1.11 linspace requires the steps argument. Use steps=100 to restore the previous behavior. + + Args: + start (float or Tensor): the starting value for the set of points. If `Tensor`, it must be 0-dimensional + end (float or Tensor): the ending value for the set of points. If `Tensor`, it must be 0-dimensional + steps (int): size of the constructed tensor + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the data type to perform the computation in. + Default: if None, uses the global default dtype (see torch.get_default_dtype()) + when both :attr:`start` and :attr:`end` are real, + and corresponding complex dtype when either is complex. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + + Example:: + + >>> torch.linspace(3, 10, steps=5) + tensor([ 3.0000, 4.7500, 6.5000, 8.2500, 10.0000]) + >>> torch.linspace(-10, 10, steps=5) + tensor([-10., -5., 0., 5., 10.]) + >>> torch.linspace(start=-10, end=10, steps=5) + tensor([-10., -5., 0., 5., 10.]) + >>> torch.linspace(start=-10, end=10, steps=1) + tensor([-10.]) + """ + +@overload +def linspace( + start: Tensor, + end: Number | _complex, + steps: _int, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + linspace(start, end, steps, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Creates a one-dimensional tensor of size :attr:`steps` whose values are evenly + spaced from :attr:`start` to :attr:`end`, inclusive. That is, the value are: + + .. math:: + (\text{start}, + \text{start} + \frac{\text{end} - \text{start}}{\text{steps} - 1}, + \ldots, + \text{start} + (\text{steps} - 2) * \frac{\text{end} - \text{start}}{\text{steps} - 1}, + \text{end}) + + + From PyTorch 1.11 linspace requires the steps argument. Use steps=100 to restore the previous behavior. + + Args: + start (float or Tensor): the starting value for the set of points. If `Tensor`, it must be 0-dimensional + end (float or Tensor): the ending value for the set of points. If `Tensor`, it must be 0-dimensional + steps (int): size of the constructed tensor + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the data type to perform the computation in. + Default: if None, uses the global default dtype (see torch.get_default_dtype()) + when both :attr:`start` and :attr:`end` are real, + and corresponding complex dtype when either is complex. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + + Example:: + + >>> torch.linspace(3, 10, steps=5) + tensor([ 3.0000, 4.7500, 6.5000, 8.2500, 10.0000]) + >>> torch.linspace(-10, 10, steps=5) + tensor([-10., -5., 0., 5., 10.]) + >>> torch.linspace(start=-10, end=10, steps=5) + tensor([-10., -5., 0., 5., 10.]) + >>> torch.linspace(start=-10, end=10, steps=1) + tensor([-10.]) + """ + +@overload +def linspace( + start: Number | _complex, + end: Number | _complex, + steps: _int, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + linspace(start, end, steps, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Creates a one-dimensional tensor of size :attr:`steps` whose values are evenly + spaced from :attr:`start` to :attr:`end`, inclusive. That is, the value are: + + .. math:: + (\text{start}, + \text{start} + \frac{\text{end} - \text{start}}{\text{steps} - 1}, + \ldots, + \text{start} + (\text{steps} - 2) * \frac{\text{end} - \text{start}}{\text{steps} - 1}, + \text{end}) + + + From PyTorch 1.11 linspace requires the steps argument. Use steps=100 to restore the previous behavior. + + Args: + start (float or Tensor): the starting value for the set of points. If `Tensor`, it must be 0-dimensional + end (float or Tensor): the ending value for the set of points. If `Tensor`, it must be 0-dimensional + steps (int): size of the constructed tensor + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the data type to perform the computation in. + Default: if None, uses the global default dtype (see torch.get_default_dtype()) + when both :attr:`start` and :attr:`end` are real, + and corresponding complex dtype when either is complex. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + + Example:: + + >>> torch.linspace(3, 10, steps=5) + tensor([ 3.0000, 4.7500, 6.5000, 8.2500, 10.0000]) + >>> torch.linspace(-10, 10, steps=5) + tensor([-10., -5., 0., 5., 10.]) + >>> torch.linspace(start=-10, end=10, steps=5) + tensor([-10., -5., 0., 5., 10.]) + >>> torch.linspace(start=-10, end=10, steps=1) + tensor([-10.]) + """ + +def log(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + log(input, *, out=None) -> Tensor + + Returns a new tensor with the natural logarithm of the elements + of :attr:`input`. + + .. math:: + y_{i} = \log_{e} (x_{i}) + + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(5) * 5 + >>> a + tensor([4.7767, 4.3234, 1.2156, 0.2411, 4.5739]) + >>> torch.log(a) + tensor([ 1.5637, 1.4640, 0.1952, -1.4226, 1.5204]) + """ + +def log10(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + log10(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Returns a new tensor with the logarithm to the base 10 of the elements + of :attr:`input`. + + .. math:: + y_{i} = \log_{10} (x_{i}) + + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(5) + >>> a + tensor([ 0.5224, 0.9354, 0.7257, 0.1301, 0.2251]) + + + >>> torch.log10(a) + tensor([-0.2820, -0.0290, -0.1392, -0.8857, -0.6476]) + """ + +def log10_(input: Tensor) -> Tensor: ... +def log1p(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + log1p(input, *, out=None) -> Tensor + + Returns a new tensor with the natural logarithm of (1 + :attr:`input`). + + .. math:: + y_i = \log_{e} (x_i + 1) + + .. note:: This function is more accurate than :func:`torch.log` for small + values of :attr:`input` + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(5) + >>> a + tensor([-1.0090, -0.9923, 1.0249, -0.5372, 0.2492]) + >>> torch.log1p(a) + tensor([ nan, -4.8653, 0.7055, -0.7705, 0.2225]) + """ + +def log1p_(input: Tensor) -> Tensor: ... +def log2(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + log2(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Returns a new tensor with the logarithm to the base 2 of the elements + of :attr:`input`. + + .. math:: + y_{i} = \log_{2} (x_{i}) + + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(5) + >>> a + tensor([ 0.8419, 0.8003, 0.9971, 0.5287, 0.0490]) + + + >>> torch.log2(a) + tensor([-0.2483, -0.3213, -0.0042, -0.9196, -4.3504]) + """ + +def log2_(input: Tensor) -> Tensor: ... +def log_(input: Tensor) -> Tensor: ... +@overload +def log_softmax( + input: Tensor, + dim: _int, + dtype: _dtype | None = None, + *, + out: Tensor | None = None, +) -> Tensor: ... +@overload +def log_softmax( + input: Tensor, + dim: str | EllipsisType | None, + *, + dtype: _dtype | None = None, +) -> Tensor: ... +def logaddexp( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + logaddexp(input, other, *, out=None) -> Tensor + + Logarithm of the sum of exponentiations of the inputs. + + Calculates pointwise :math:`\log\left(e^x + e^y\right)`. This function is useful + in statistics where the calculated probabilities of events may be so small as to + exceed the range of normal floating point numbers. In such cases the logarithm + of the calculated probability is stored. This function allows adding + probabilities stored in such a fashion. + + This op should be disambiguated with :func:`torch.logsumexp` which performs a + reduction on a single tensor. + + Args: + input (Tensor): the input tensor. + other (Tensor): the second input tensor + + Keyword arguments: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.logaddexp(torch.tensor([-1.0]), torch.tensor([-1.0, -2, -3])) + tensor([-0.3069, -0.6867, -0.8731]) + >>> torch.logaddexp(torch.tensor([-100.0, -200, -300]), torch.tensor([-1.0, -2, -3])) + tensor([-1., -2., -3.]) + >>> torch.logaddexp(torch.tensor([1.0, 2000, 30000]), torch.tensor([-1.0, -2, -3])) + tensor([1.1269e+00, 2.0000e+03, 3.0000e+04]) + """ + +def logaddexp2( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + logaddexp2(input, other, *, out=None) -> Tensor + + Logarithm of the sum of exponentiations of the inputs in base-2. + + Calculates pointwise :math:`\log_2\left(2^x + 2^y\right)`. See + :func:`torch.logaddexp` for more details. + + Args: + input (Tensor): the input tensor. + other (Tensor): the second input tensor + + Keyword arguments: + out (Tensor, optional): the output tensor. + """ + +@overload +def logcumsumexp( + input: Tensor, + dim: _int, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + logcumsumexp(input, dim, *, out=None) -> Tensor + Returns the logarithm of the cumulative summation of the exponentiation of + elements of :attr:`input` in the dimension :attr:`dim`. + + For summation index :math:`j` given by `dim` and other indices :math:`i`, the result is + + .. math:: + \text{logcumsumexp}(x)_{ij} = \log \sum\limits_{k=0}^{j} \exp(x_{ik}) + + Args: + input (Tensor): the input tensor. + dim (int): the dimension to do the operation over + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(10) + >>> torch.logcumsumexp(a, dim=0) + tensor([-0.42296738, -0.04462666, 0.86278635, 0.94622083, 1.05277811, + 1.39202815, 1.83525007, 1.84492621, 2.06084887, 2.06844475])) + """ + +@overload +def logcumsumexp( + input: Tensor, + dim: str | EllipsisType | None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + logcumsumexp(input, dim, *, out=None) -> Tensor + Returns the logarithm of the cumulative summation of the exponentiation of + elements of :attr:`input` in the dimension :attr:`dim`. + + For summation index :math:`j` given by `dim` and other indices :math:`i`, the result is + + .. math:: + \text{logcumsumexp}(x)_{ij} = \log \sum\limits_{k=0}^{j} \exp(x_{ik}) + + Args: + input (Tensor): the input tensor. + dim (int): the dimension to do the operation over + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(10) + >>> torch.logcumsumexp(a, dim=0) + tensor([-0.42296738, -0.04462666, 0.86278635, 0.94622083, 1.05277811, + 1.39202815, 1.83525007, 1.84492621, 2.06084887, 2.06844475])) + """ + +def logdet(input: Tensor) -> Tensor: + r""" + logdet(input) -> Tensor + + Calculates log determinant of a square matrix or batches of square matrices. + + It returns ``-inf`` if the input has a determinant of zero, and ``NaN`` if it has + a negative determinant. + + .. note:: + Backward through :meth:`logdet` internally uses SVD results when :attr:`input` + is not invertible. In this case, double backward through :meth:`logdet` will + be unstable in when :attr:`input` doesn't have distinct singular values. See + :func:`torch.linalg.svd` for details. + + .. seealso:: + + :func:`torch.linalg.slogdet` computes the sign (resp. angle) and natural logarithm of the + absolute value of the determinant of real-valued (resp. complex) square matrices. + + Arguments: + input (Tensor): the input tensor of size ``(*, n, n)`` where ``*`` is zero or more + batch dimensions. + + Example:: + + >>> A = torch.randn(3, 3) + >>> torch.det(A) + tensor(0.2611) + >>> torch.logdet(A) + tensor(-1.3430) + >>> A + tensor([[[ 0.9254, -0.6213], + [-0.5787, 1.6843]], + + [[ 0.3242, -0.9665], + [ 0.4539, -0.0887]], + + [[ 1.1336, -0.4025], + [-0.7089, 0.9032]]]) + >>> A.det() + tensor([1.1990, 0.4099, 0.7386]) + >>> A.det().log() + tensor([ 0.1815, -0.8917, -0.3031]) + """ + +def logical_and( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + logical_and(input, other, *, out=None) -> Tensor + + Computes the element-wise logical AND of the given input tensors. Zeros are treated as ``False`` and nonzeros are + treated as ``True``. + + Args: + input (Tensor): the input tensor. + other (Tensor): the tensor to compute AND with + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.logical_and(torch.tensor([True, False, True]), torch.tensor([True, False, False])) + tensor([ True, False, False]) + >>> a = torch.tensor([0, 1, 10, 0], dtype=torch.int8) + >>> b = torch.tensor([4, 0, 1, 0], dtype=torch.int8) + >>> torch.logical_and(a, b) + tensor([False, False, True, False]) + >>> torch.logical_and(a.double(), b.double()) + tensor([False, False, True, False]) + >>> torch.logical_and(a.double(), b) + tensor([False, False, True, False]) + >>> torch.logical_and(a, b, out=torch.empty(4, dtype=torch.bool)) + tensor([False, False, True, False]) + """ + +def logical_not(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + logical_not(input, *, out=None) -> Tensor + + Computes the element-wise logical NOT of the given input tensor. If not specified, the output tensor will have the bool + dtype. If the input tensor is not a bool tensor, zeros are treated as ``False`` and non-zeros are treated as ``True``. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.logical_not(torch.tensor([True, False])) + tensor([False, True]) + >>> torch.logical_not(torch.tensor([0, 1, -10], dtype=torch.int8)) + tensor([ True, False, False]) + >>> torch.logical_not(torch.tensor([0., 1.5, -10.], dtype=torch.double)) + tensor([ True, False, False]) + >>> torch.logical_not(torch.tensor([0., 1., -10.], dtype=torch.double), out=torch.empty(3, dtype=torch.int16)) + tensor([1, 0, 0], dtype=torch.int16) + """ + +def logical_or( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + logical_or(input, other, *, out=None) -> Tensor + + Computes the element-wise logical OR of the given input tensors. Zeros are treated as ``False`` and nonzeros are + treated as ``True``. + + Args: + input (Tensor): the input tensor. + other (Tensor): the tensor to compute OR with + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.logical_or(torch.tensor([True, False, True]), torch.tensor([True, False, False])) + tensor([ True, False, True]) + >>> a = torch.tensor([0, 1, 10, 0], dtype=torch.int8) + >>> b = torch.tensor([4, 0, 1, 0], dtype=torch.int8) + >>> torch.logical_or(a, b) + tensor([ True, True, True, False]) + >>> torch.logical_or(a.double(), b.double()) + tensor([ True, True, True, False]) + >>> torch.logical_or(a.double(), b) + tensor([ True, True, True, False]) + >>> torch.logical_or(a, b, out=torch.empty(4, dtype=torch.bool)) + tensor([ True, True, True, False]) + """ + +def logical_xor( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + logical_xor(input: Tensor, other: Tensor, *, out: Optional[Tensor]) -> Tensor + + Computes the element-wise logical XOR of the given input tensors. Zeros are treated as ``False`` and nonzeros are + treated as ``True``. + + Args: + input (Tensor): the input tensor. + other (Tensor): the tensor to compute XOR with + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.logical_xor(torch.tensor([True, False, True]), torch.tensor([True, False, False])) + tensor([False, False, True]) + >>> a = torch.tensor([0, 1, 10, 0], dtype=torch.int8) + >>> b = torch.tensor([4, 0, 1, 0], dtype=torch.int8) + >>> torch.logical_xor(a, b) + tensor([ True, True, False, False]) + >>> torch.logical_xor(a.double(), b.double()) + tensor([ True, True, False, False]) + >>> torch.logical_xor(a.double(), b) + tensor([ True, True, False, False]) + >>> torch.logical_xor(a, b, out=torch.empty(4, dtype=torch.bool)) + tensor([ True, True, False, False]) + """ + +def logit( + input: Tensor, + eps: _float | None = None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + logit(input, eps=None, *, out=None) -> Tensor + + Alias for :func:`torch.special.logit`. + """ + +def logit_(input: Tensor, eps: _float | None = None) -> Tensor: ... +@overload +def logspace( + start: Number, + end: Number, + steps: _int | None = None, + base: _float = 10.0, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + pin_memory: _bool = False, +) -> Tensor: + r""" + logspace(start, end, steps, base=10.0, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + + Creates a one-dimensional tensor of size :attr:`steps` whose values are evenly + spaced from :math:`{{\text{{base}}}}^{{\text{{start}}}}` to + :math:`{{\text{{base}}}}^{{\text{{end}}}}`, inclusive, on a logarithmic scale + with base :attr:`base`. That is, the values are: + + .. math:: + (\text{base}^{\text{start}}, + \text{base}^{(\text{start} + \frac{\text{end} - \text{start}}{ \text{steps} - 1})}, + \ldots, + \text{base}^{(\text{start} + (\text{steps} - 2) * \frac{\text{end} - \text{start}}{ \text{steps} - 1})}, + \text{base}^{\text{end}}) + + + + From PyTorch 1.11 logspace requires the steps argument. Use steps=100 to restore the previous behavior. + + Args: + start (float or Tensor): the starting value for the set of points. If `Tensor`, it must be 0-dimensional + end (float or Tensor): the ending value for the set of points. If `Tensor`, it must be 0-dimensional + steps (int): size of the constructed tensor + base (float, optional): base of the logarithm function. Default: ``10.0``. + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the data type to perform the computation in. + Default: if None, uses the global default dtype (see torch.get_default_dtype()) + when both :attr:`start` and :attr:`end` are real, + and corresponding complex dtype when either is complex. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.logspace(start=-10, end=10, steps=5) + tensor([ 1.0000e-10, 1.0000e-05, 1.0000e+00, 1.0000e+05, 1.0000e+10]) + >>> torch.logspace(start=0.1, end=1.0, steps=5) + tensor([ 1.2589, 2.1135, 3.5481, 5.9566, 10.0000]) + >>> torch.logspace(start=0.1, end=1.0, steps=1) + tensor([1.2589]) + >>> torch.logspace(start=2, end=2, steps=1, base=2) + tensor([4.0]) + """ + +@overload +def logspace( + start: Tensor, + end: Tensor, + steps: _int, + base: _float = 10.0, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + logspace(start, end, steps, base=10.0, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + + Creates a one-dimensional tensor of size :attr:`steps` whose values are evenly + spaced from :math:`{{\text{{base}}}}^{{\text{{start}}}}` to + :math:`{{\text{{base}}}}^{{\text{{end}}}}`, inclusive, on a logarithmic scale + with base :attr:`base`. That is, the values are: + + .. math:: + (\text{base}^{\text{start}}, + \text{base}^{(\text{start} + \frac{\text{end} - \text{start}}{ \text{steps} - 1})}, + \ldots, + \text{base}^{(\text{start} + (\text{steps} - 2) * \frac{\text{end} - \text{start}}{ \text{steps} - 1})}, + \text{base}^{\text{end}}) + + + + From PyTorch 1.11 logspace requires the steps argument. Use steps=100 to restore the previous behavior. + + Args: + start (float or Tensor): the starting value for the set of points. If `Tensor`, it must be 0-dimensional + end (float or Tensor): the ending value for the set of points. If `Tensor`, it must be 0-dimensional + steps (int): size of the constructed tensor + base (float, optional): base of the logarithm function. Default: ``10.0``. + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the data type to perform the computation in. + Default: if None, uses the global default dtype (see torch.get_default_dtype()) + when both :attr:`start` and :attr:`end` are real, + and corresponding complex dtype when either is complex. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.logspace(start=-10, end=10, steps=5) + tensor([ 1.0000e-10, 1.0000e-05, 1.0000e+00, 1.0000e+05, 1.0000e+10]) + >>> torch.logspace(start=0.1, end=1.0, steps=5) + tensor([ 1.2589, 2.1135, 3.5481, 5.9566, 10.0000]) + >>> torch.logspace(start=0.1, end=1.0, steps=1) + tensor([1.2589]) + >>> torch.logspace(start=2, end=2, steps=1, base=2) + tensor([4.0]) + """ + +@overload +def logspace( + start: Number | _complex, + end: Tensor, + steps: _int, + base: _float = 10.0, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + logspace(start, end, steps, base=10.0, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + + Creates a one-dimensional tensor of size :attr:`steps` whose values are evenly + spaced from :math:`{{\text{{base}}}}^{{\text{{start}}}}` to + :math:`{{\text{{base}}}}^{{\text{{end}}}}`, inclusive, on a logarithmic scale + with base :attr:`base`. That is, the values are: + + .. math:: + (\text{base}^{\text{start}}, + \text{base}^{(\text{start} + \frac{\text{end} - \text{start}}{ \text{steps} - 1})}, + \ldots, + \text{base}^{(\text{start} + (\text{steps} - 2) * \frac{\text{end} - \text{start}}{ \text{steps} - 1})}, + \text{base}^{\text{end}}) + + + + From PyTorch 1.11 logspace requires the steps argument. Use steps=100 to restore the previous behavior. + + Args: + start (float or Tensor): the starting value for the set of points. If `Tensor`, it must be 0-dimensional + end (float or Tensor): the ending value for the set of points. If `Tensor`, it must be 0-dimensional + steps (int): size of the constructed tensor + base (float, optional): base of the logarithm function. Default: ``10.0``. + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the data type to perform the computation in. + Default: if None, uses the global default dtype (see torch.get_default_dtype()) + when both :attr:`start` and :attr:`end` are real, + and corresponding complex dtype when either is complex. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.logspace(start=-10, end=10, steps=5) + tensor([ 1.0000e-10, 1.0000e-05, 1.0000e+00, 1.0000e+05, 1.0000e+10]) + >>> torch.logspace(start=0.1, end=1.0, steps=5) + tensor([ 1.2589, 2.1135, 3.5481, 5.9566, 10.0000]) + >>> torch.logspace(start=0.1, end=1.0, steps=1) + tensor([1.2589]) + >>> torch.logspace(start=2, end=2, steps=1, base=2) + tensor([4.0]) + """ + +@overload +def logspace( + start: Tensor, + end: Number | _complex, + steps: _int, + base: _float = 10.0, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + logspace(start, end, steps, base=10.0, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + + Creates a one-dimensional tensor of size :attr:`steps` whose values are evenly + spaced from :math:`{{\text{{base}}}}^{{\text{{start}}}}` to + :math:`{{\text{{base}}}}^{{\text{{end}}}}`, inclusive, on a logarithmic scale + with base :attr:`base`. That is, the values are: + + .. math:: + (\text{base}^{\text{start}}, + \text{base}^{(\text{start} + \frac{\text{end} - \text{start}}{ \text{steps} - 1})}, + \ldots, + \text{base}^{(\text{start} + (\text{steps} - 2) * \frac{\text{end} - \text{start}}{ \text{steps} - 1})}, + \text{base}^{\text{end}}) + + + + From PyTorch 1.11 logspace requires the steps argument. Use steps=100 to restore the previous behavior. + + Args: + start (float or Tensor): the starting value for the set of points. If `Tensor`, it must be 0-dimensional + end (float or Tensor): the ending value for the set of points. If `Tensor`, it must be 0-dimensional + steps (int): size of the constructed tensor + base (float, optional): base of the logarithm function. Default: ``10.0``. + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the data type to perform the computation in. + Default: if None, uses the global default dtype (see torch.get_default_dtype()) + when both :attr:`start` and :attr:`end` are real, + and corresponding complex dtype when either is complex. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.logspace(start=-10, end=10, steps=5) + tensor([ 1.0000e-10, 1.0000e-05, 1.0000e+00, 1.0000e+05, 1.0000e+10]) + >>> torch.logspace(start=0.1, end=1.0, steps=5) + tensor([ 1.2589, 2.1135, 3.5481, 5.9566, 10.0000]) + >>> torch.logspace(start=0.1, end=1.0, steps=1) + tensor([1.2589]) + >>> torch.logspace(start=2, end=2, steps=1, base=2) + tensor([4.0]) + """ + +@overload +def logspace( + start: Number | _complex, + end: Number | _complex, + steps: _int, + base: _float = 10.0, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + logspace(start, end, steps, base=10.0, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + + Creates a one-dimensional tensor of size :attr:`steps` whose values are evenly + spaced from :math:`{{\text{{base}}}}^{{\text{{start}}}}` to + :math:`{{\text{{base}}}}^{{\text{{end}}}}`, inclusive, on a logarithmic scale + with base :attr:`base`. That is, the values are: + + .. math:: + (\text{base}^{\text{start}}, + \text{base}^{(\text{start} + \frac{\text{end} - \text{start}}{ \text{steps} - 1})}, + \ldots, + \text{base}^{(\text{start} + (\text{steps} - 2) * \frac{\text{end} - \text{start}}{ \text{steps} - 1})}, + \text{base}^{\text{end}}) + + + + From PyTorch 1.11 logspace requires the steps argument. Use steps=100 to restore the previous behavior. + + Args: + start (float or Tensor): the starting value for the set of points. If `Tensor`, it must be 0-dimensional + end (float or Tensor): the ending value for the set of points. If `Tensor`, it must be 0-dimensional + steps (int): size of the constructed tensor + base (float, optional): base of the logarithm function. Default: ``10.0``. + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the data type to perform the computation in. + Default: if None, uses the global default dtype (see torch.get_default_dtype()) + when both :attr:`start` and :attr:`end` are real, + and corresponding complex dtype when either is complex. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.logspace(start=-10, end=10, steps=5) + tensor([ 1.0000e-10, 1.0000e-05, 1.0000e+00, 1.0000e+05, 1.0000e+10]) + >>> torch.logspace(start=0.1, end=1.0, steps=5) + tensor([ 1.2589, 2.1135, 3.5481, 5.9566, 10.0000]) + >>> torch.logspace(start=0.1, end=1.0, steps=1) + tensor([1.2589]) + >>> torch.logspace(start=2, end=2, steps=1, base=2) + tensor([4.0]) + """ + +@overload +def logsumexp( + input: Tensor, + dim: _int | _size, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + logsumexp(input, dim, keepdim=False, *, out=None) + + Returns the log of summed exponentials of each row of the :attr:`input` + tensor in the given dimension :attr:`dim`. The computation is numerically + stabilized. + + For summation index :math:`j` given by `dim` and other indices :math:`i`, the result is + + .. math:: + \text{logsumexp}(x)_{i} = \log \sum_j \exp(x_{ij}) + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + dim (int or tuple of ints): the dimension or dimensions to reduce. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(3, 3) + >>> torch.logsumexp(a, 1) + tensor([1.4907, 1.0593, 1.5696]) + >>> torch.dist(torch.logsumexp(a, 1), torch.log(torch.sum(torch.exp(a), 1))) + tensor(1.6859e-07) + """ + +@overload +def logsumexp( + input: Tensor, + dim: Sequence[str | EllipsisType | None], + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + logsumexp(input, dim, keepdim=False, *, out=None) + + Returns the log of summed exponentials of each row of the :attr:`input` + tensor in the given dimension :attr:`dim`. The computation is numerically + stabilized. + + For summation index :math:`j` given by `dim` and other indices :math:`i`, the result is + + .. math:: + \text{logsumexp}(x)_{i} = \log \sum_j \exp(x_{ij}) + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + dim (int or tuple of ints): the dimension or dimensions to reduce. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(3, 3) + >>> torch.logsumexp(a, 1) + tensor([1.4907, 1.0593, 1.5696]) + >>> torch.dist(torch.logsumexp(a, 1), torch.log(torch.sum(torch.exp(a), 1))) + tensor(1.6859e-07) + """ + +@overload +def lstm( + data: Tensor, + batch_sizes: Tensor, + hx: tuple[Tensor, ...] | list[Tensor] | None, + params: tuple[Tensor, ...] | list[Tensor] | None, + has_biases: _bool, + num_layers: _int, + dropout: _float, + train: _bool, + bidirectional: _bool, +) -> tuple[Tensor, Tensor, Tensor]: ... +@overload +def lstm( + input: Tensor, + hx: tuple[Tensor, ...] | list[Tensor] | None, + params: tuple[Tensor, ...] | list[Tensor] | None, + has_biases: _bool, + num_layers: _int, + dropout: _float, + train: _bool, + bidirectional: _bool, + batch_first: _bool, +) -> tuple[Tensor, Tensor, Tensor]: ... +def lstm_cell( + input: Tensor, + hx: tuple[Tensor, ...] | list[Tensor] | None, + w_ih: Tensor, + w_hh: Tensor, + b_ih: Tensor | None = None, + b_hh: Tensor | None = None, +) -> tuple[Tensor, Tensor]: ... +@overload +def lt( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + lt(input, other, *, out=None) -> Tensor + + Computes :math:`\text{input} < \text{other}` element-wise. + + + The second argument can be a number or a tensor whose shape is + :ref:`broadcastable ` with the first argument. + + Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is less than :attr:`other` and False elsewhere + + Example:: + + >>> torch.lt(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[False, False], [True, False]]) + """ + +@overload +def lt( + input: Tensor, + other: Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + lt(input, other, *, out=None) -> Tensor + + Computes :math:`\text{input} < \text{other}` element-wise. + + + The second argument can be a number or a tensor whose shape is + :ref:`broadcastable ` with the first argument. + + Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is less than :attr:`other` and False elsewhere + + Example:: + + >>> torch.lt(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[False, False], [True, False]]) + """ + +def lu_solve( + input: Tensor, + LU_data: Tensor, + LU_pivots: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + lu_solve(b, LU_data, LU_pivots, *, out=None) -> Tensor + + Returns the LU solve of the linear system :math:`Ax = b` using the partially pivoted + LU factorization of A from :func:`~linalg.lu_factor`. + + This function supports ``float``, ``double``, ``cfloat`` and ``cdouble`` dtypes for :attr:`input`. + + .. warning:: + + :func:`torch.lu_solve` is deprecated in favor of :func:`torch.linalg.lu_solve`. + :func:`torch.lu_solve` will be removed in a future PyTorch release. + ``X = torch.lu_solve(B, LU, pivots)`` should be replaced with + + .. code:: python + + X = linalg.lu_solve(LU, pivots, B) + + Arguments: + b (Tensor): the RHS tensor of size :math:`(*, m, k)`, where :math:`*` + is zero or more batch dimensions. + LU_data (Tensor): the pivoted LU factorization of A from :meth:`~linalg.lu_factor` of size :math:`(*, m, m)`, + where :math:`*` is zero or more batch dimensions. + LU_pivots (IntTensor): the pivots of the LU factorization from :meth:`~linalg.lu_factor` of size :math:`(*, m)`, + where :math:`*` is zero or more batch dimensions. + The batch dimensions of :attr:`LU_pivots` must be equal to the batch dimensions of + :attr:`LU_data`. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> A = torch.randn(2, 3, 3) + >>> b = torch.randn(2, 3, 1) + >>> LU, pivots = torch.linalg.lu_factor(A) + >>> x = torch.lu_solve(b, LU, pivots) + >>> torch.dist(A @ x, b) + tensor(1.00000e-07 * + 2.8312) + """ + +def lu_unpack( + LU_data: Tensor, + LU_pivots: Tensor, + unpack_data: _bool = True, + unpack_pivots: _bool = True, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.lu_unpack: + r""" + lu_unpack(LU_data, LU_pivots, unpack_data=True, unpack_pivots=True, *, out=None) -> (Tensor, Tensor, Tensor) + + Unpacks the LU decomposition returned by :func:`~linalg.lu_factor` into the `P, L, U` matrices. + + .. seealso:: + + :func:`~linalg.lu` returns the matrices from the LU decomposition. Its gradient formula is more efficient + than that of doing :func:`~linalg.lu_factor` followed by :func:`~linalg.lu_unpack`. + + Args: + LU_data (Tensor): the packed LU factorization data + LU_pivots (Tensor): the packed LU factorization pivots + unpack_data (bool): flag indicating if the data should be unpacked. + If ``False``, then the returned ``L`` and ``U`` are empty tensors. + Default: ``True`` + unpack_pivots (bool): flag indicating if the pivots should be unpacked into a permutation matrix ``P``. + If ``False``, then the returned ``P`` is an empty tensor. + Default: ``True`` + + Keyword args: + out (tuple, optional): output tuple of three tensors. Ignored if `None`. + + Returns: + A namedtuple ``(P, L, U)`` + + Examples:: + + >>> A = torch.randn(2, 3, 3) + >>> LU, pivots = torch.linalg.lu_factor(A) + >>> P, L, U = torch.lu_unpack(LU, pivots) + >>> # We can recover A from the factorization + >>> A_ = P @ L @ U + >>> torch.allclose(A, A_) + True + + >>> # LU factorization of a rectangular matrix: + >>> A = torch.randn(2, 3, 2) + >>> LU, pivots = torch.linalg.lu_factor(A) + >>> P, L, U = torch.lu_unpack(LU, pivots) + >>> # P, L, U are the same as returned by linalg.lu + >>> P_, L_, U_ = torch.linalg.lu(A) + >>> torch.allclose(P, P_) and torch.allclose(L, L_) and torch.allclose(U, U_) + True + """ + +def margin_ranking_loss( + input1: Tensor, + input2: Tensor, + target: Tensor, + margin: _float = 0.0, + reduction: _int = 1, +) -> Tensor: ... +@overload +def masked_fill(input: Tensor, mask: Tensor, value: Tensor) -> Tensor: ... +@overload +def masked_fill( + input: Tensor, + mask: Tensor, + value: Number | _complex, +) -> Tensor: ... +def masked_scatter(input: Tensor, mask: Tensor, source: Tensor) -> Tensor: ... +def masked_select( + input: Tensor, + mask: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + masked_select(input, mask, *, out=None) -> Tensor + + Returns a new 1-D tensor which indexes the :attr:`input` tensor according to + the boolean mask :attr:`mask` which is a `BoolTensor`. + + The shapes of the :attr:`mask` tensor and the :attr:`input` tensor don't need + to match, but they must be :ref:`broadcastable `. + + .. note:: The returned tensor does **not** use the same storage + as the original tensor + + Args: + input (Tensor): the input tensor. + mask (BoolTensor): the tensor containing the binary mask to index with + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> x = torch.randn(3, 4) + >>> x + tensor([[ 0.3552, -2.3825, -0.8297, 0.3477], + [-1.2035, 1.2252, 0.5002, 0.6248], + [ 0.1307, -2.0608, 0.1244, 2.0139]]) + >>> mask = x.ge(0.5) + >>> mask + tensor([[False, False, False, False], + [False, True, True, True], + [False, False, False, True]]) + >>> torch.masked_select(x, mask) + tensor([ 1.2252, 0.5002, 0.6248, 2.0139]) + """ + +def matmul( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + matmul(input, other, *, out=None) -> Tensor + + Matrix product of two tensors. + + The behavior depends on the dimensionality of the tensors as follows: + + - If both tensors are 1-dimensional, the dot product (scalar) is returned. + - If both arguments are 2-dimensional, the matrix-matrix product is returned. + - If the first argument is 1-dimensional and the second argument is 2-dimensional, + a 1 is prepended to its dimension for the purpose of the matrix multiply. + After the matrix multiply, the prepended dimension is removed. + - If the first argument is 2-dimensional and the second argument is 1-dimensional, + the matrix-vector product is returned. + - If both arguments are at least 1-dimensional and at least one argument is + N-dimensional (where N > 2), then a batched matrix multiply is returned. If the first + argument is 1-dimensional, a 1 is prepended to its dimension for the purpose of the + batched matrix multiply and removed after. If the second argument is 1-dimensional, a + 1 is appended to its dimension for the purpose of the batched matrix multiply and removed after. + + The first N-2 dimensions of each argument, the batch dimensions, are + :ref:`broadcast ` (and thus must be broadcastable). + The last 2, the matrix dimensions, are handled as in the matrix-matrix product. + + For example, if :attr:`input` is a + :math:`(j \times 1 \times n \times m)` tensor and :attr:`other` is a :math:`(k \times m \times p)` + tensor, the batch dimensions are :math:`(j \times 1)` and :math:`(k)`, + and the matrix dimensions are :math:`(n \times m)` and :math:`(m \times p)`. + :attr:`out` will be a :math:`(j \times k \times n \times p)` tensor. + + This operation has support for arguments with :ref:`sparse layouts`. In particular the + matrix-matrix (both arguments 2-dimensional) supports sparse arguments with the same restrictions + as :func:`torch.mm` + + + .. warning:: + Sparse support is a beta feature and some layout(s)/dtype/device combinations may not be supported, + or may not have autograd support. If you notice missing functionality please + open a feature request. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + .. note:: + + The 1-dimensional dot product version of this function does not support an :attr:`out` parameter. + + Arguments: + input (Tensor): the first tensor to be multiplied + other (Tensor): the second tensor to be multiplied + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> # vector x vector + >>> tensor1 = torch.randn(3) + >>> tensor2 = torch.randn(3) + >>> torch.matmul(tensor1, tensor2).size() + torch.Size([]) + >>> # matrix x vector + >>> tensor1 = torch.randn(3, 4) + >>> tensor2 = torch.randn(4) + >>> torch.matmul(tensor1, tensor2).size() + torch.Size([3]) + >>> # batched matrix x broadcasted vector + >>> tensor1 = torch.randn(10, 3, 4) + >>> tensor2 = torch.randn(4) + >>> torch.matmul(tensor1, tensor2).size() + torch.Size([10, 3]) + >>> # batched matrix x batched matrix + >>> tensor1 = torch.randn(10, 3, 4) + >>> tensor2 = torch.randn(10, 4, 5) + >>> torch.matmul(tensor1, tensor2).size() + torch.Size([10, 3, 5]) + >>> # batched matrix x broadcasted matrix + >>> tensor1 = torch.randn(10, 3, 4) + >>> tensor2 = torch.randn(4, 5) + >>> torch.matmul(tensor1, tensor2).size() + torch.Size([10, 3, 5]) + """ + +def matrix_exp(input: Tensor) -> Tensor: + r""" + matrix_exp(A) -> Tensor + + Alias for :func:`torch.linalg.matrix_exp`. + """ + +def matrix_power( + input: Tensor, + n: _int, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + matrix_power(input, n, *, out=None) -> Tensor + + Alias for :func:`torch.linalg.matrix_power` + """ + +@overload +def max(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + max(input, *, out=None) -> Tensor + + Returns the maximum value of all elements in the ``input`` tensor. + + .. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.6763, 0.7445, -2.2369]]) + >>> torch.max(a) + tensor(0.7445) + + .. function:: max(input, dim, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` is the maximum + value of each row of the :attr:`input` tensor in the given dimension + :attr:`dim`. And ``indices`` is the index location of each maximum value found + (argmax). + + If ``keepdim`` is ``True``, the output tensors are of the same size + as ``input`` except in the dimension ``dim`` where they are of size 1. + Otherwise, ``dim`` is squeezed (see :func:`torch.squeeze`), resulting + in the output tensors having 1 fewer dimension than ``input``. + + .. note:: If there are multiple maximal values in a reduced row then + the indices of the first maximal value are returned. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. If omitted, all dimensions are reduced. Explicit ``None`` is not supported. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (tuple, optional): the result tuple of two output tensors (max, max_indices) + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-1.2360, -0.2942, -0.1222, 0.8475], + [ 1.1949, -1.1127, -2.2379, -0.6702], + [ 1.5717, -0.9207, 0.1297, -1.8768], + [-0.6172, 1.0036, -0.6060, -0.2432]]) + >>> torch.max(a, 1) + torch.return_types.max(values=tensor([0.8475, 1.1949, 1.5717, 1.0036]), indices=tensor([3, 0, 0, 1])) + >>> a = torch.tensor([[1.0, 2.0], [3.0, 4.0]]) + >>> a.max(dim=1, keepdim=True) + torch.return_types.max( + values=tensor([[2.], [4.]]), + indices=tensor([[1], [1]])) + >>> a.max(dim=1, keepdim=False) + torch.return_types.max( + values=tensor([2., 4.]), + indices=tensor([1, 1])) + + .. function:: max(input, other, *, out=None) -> Tensor + :noindex: + + See :func:`torch.maximum`. + """ + +@overload +def max( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + max(input, *, out=None) -> Tensor + + Returns the maximum value of all elements in the ``input`` tensor. + + .. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.6763, 0.7445, -2.2369]]) + >>> torch.max(a) + tensor(0.7445) + + .. function:: max(input, dim, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` is the maximum + value of each row of the :attr:`input` tensor in the given dimension + :attr:`dim`. And ``indices`` is the index location of each maximum value found + (argmax). + + If ``keepdim`` is ``True``, the output tensors are of the same size + as ``input`` except in the dimension ``dim`` where they are of size 1. + Otherwise, ``dim`` is squeezed (see :func:`torch.squeeze`), resulting + in the output tensors having 1 fewer dimension than ``input``. + + .. note:: If there are multiple maximal values in a reduced row then + the indices of the first maximal value are returned. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. If omitted, all dimensions are reduced. Explicit ``None`` is not supported. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (tuple, optional): the result tuple of two output tensors (max, max_indices) + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-1.2360, -0.2942, -0.1222, 0.8475], + [ 1.1949, -1.1127, -2.2379, -0.6702], + [ 1.5717, -0.9207, 0.1297, -1.8768], + [-0.6172, 1.0036, -0.6060, -0.2432]]) + >>> torch.max(a, 1) + torch.return_types.max(values=tensor([0.8475, 1.1949, 1.5717, 1.0036]), indices=tensor([3, 0, 0, 1])) + >>> a = torch.tensor([[1.0, 2.0], [3.0, 4.0]]) + >>> a.max(dim=1, keepdim=True) + torch.return_types.max( + values=tensor([[2.], [4.]]), + indices=tensor([[1], [1]])) + >>> a.max(dim=1, keepdim=False) + torch.return_types.max( + values=tensor([2., 4.]), + indices=tensor([1, 1])) + + .. function:: max(input, other, *, out=None) -> Tensor + :noindex: + + See :func:`torch.maximum`. + """ + +@overload +def max( + input: Tensor, + dim: _int, + keepdim: _bool = False, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.max: + r""" + max(input, *, out=None) -> Tensor + + Returns the maximum value of all elements in the ``input`` tensor. + + .. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.6763, 0.7445, -2.2369]]) + >>> torch.max(a) + tensor(0.7445) + + .. function:: max(input, dim, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` is the maximum + value of each row of the :attr:`input` tensor in the given dimension + :attr:`dim`. And ``indices`` is the index location of each maximum value found + (argmax). + + If ``keepdim`` is ``True``, the output tensors are of the same size + as ``input`` except in the dimension ``dim`` where they are of size 1. + Otherwise, ``dim`` is squeezed (see :func:`torch.squeeze`), resulting + in the output tensors having 1 fewer dimension than ``input``. + + .. note:: If there are multiple maximal values in a reduced row then + the indices of the first maximal value are returned. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. If omitted, all dimensions are reduced. Explicit ``None`` is not supported. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (tuple, optional): the result tuple of two output tensors (max, max_indices) + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-1.2360, -0.2942, -0.1222, 0.8475], + [ 1.1949, -1.1127, -2.2379, -0.6702], + [ 1.5717, -0.9207, 0.1297, -1.8768], + [-0.6172, 1.0036, -0.6060, -0.2432]]) + >>> torch.max(a, 1) + torch.return_types.max(values=tensor([0.8475, 1.1949, 1.5717, 1.0036]), indices=tensor([3, 0, 0, 1])) + >>> a = torch.tensor([[1.0, 2.0], [3.0, 4.0]]) + >>> a.max(dim=1, keepdim=True) + torch.return_types.max( + values=tensor([[2.], [4.]]), + indices=tensor([[1], [1]])) + >>> a.max(dim=1, keepdim=False) + torch.return_types.max( + values=tensor([2., 4.]), + indices=tensor([1, 1])) + + .. function:: max(input, other, *, out=None) -> Tensor + :noindex: + + See :func:`torch.maximum`. + """ + +@overload +def max( + input: Tensor, + dim: str | EllipsisType | None, + keepdim: _bool = False, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.max: + r""" + max(input, *, out=None) -> Tensor + + Returns the maximum value of all elements in the ``input`` tensor. + + .. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.6763, 0.7445, -2.2369]]) + >>> torch.max(a) + tensor(0.7445) + + .. function:: max(input, dim, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` is the maximum + value of each row of the :attr:`input` tensor in the given dimension + :attr:`dim`. And ``indices`` is the index location of each maximum value found + (argmax). + + If ``keepdim`` is ``True``, the output tensors are of the same size + as ``input`` except in the dimension ``dim`` where they are of size 1. + Otherwise, ``dim`` is squeezed (see :func:`torch.squeeze`), resulting + in the output tensors having 1 fewer dimension than ``input``. + + .. note:: If there are multiple maximal values in a reduced row then + the indices of the first maximal value are returned. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. If omitted, all dimensions are reduced. Explicit ``None`` is not supported. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (tuple, optional): the result tuple of two output tensors (max, max_indices) + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-1.2360, -0.2942, -0.1222, 0.8475], + [ 1.1949, -1.1127, -2.2379, -0.6702], + [ 1.5717, -0.9207, 0.1297, -1.8768], + [-0.6172, 1.0036, -0.6060, -0.2432]]) + >>> torch.max(a, 1) + torch.return_types.max(values=tensor([0.8475, 1.1949, 1.5717, 1.0036]), indices=tensor([3, 0, 0, 1])) + >>> a = torch.tensor([[1.0, 2.0], [3.0, 4.0]]) + >>> a.max(dim=1, keepdim=True) + torch.return_types.max( + values=tensor([[2.], [4.]]), + indices=tensor([[1], [1]])) + >>> a.max(dim=1, keepdim=False) + torch.return_types.max( + values=tensor([2., 4.]), + indices=tensor([1, 1])) + + .. function:: max(input, other, *, out=None) -> Tensor + :noindex: + + See :func:`torch.maximum`. + """ + +def max_pool1d( + input: Tensor, + kernel_size: _int | _size, + stride: _int | _size = (), + padding: _int | _size = 0, + dilation: _int | _size = 1, + ceil_mode: _bool = False, +) -> Tensor: ... +def max_pool1d_with_indices( + input: Tensor, + kernel_size: _int | _size, + stride: _int | _size = (), + padding: _int | _size = 0, + dilation: _int | _size = 1, + ceil_mode: _bool = False, +) -> tuple[Tensor, Tensor]: ... +def max_pool2d( + input: Tensor, + kernel_size: _int | _size, + stride: _int | _size = (), + padding: _int | _size = 0, + dilation: _int | _size = 1, + ceil_mode: _bool = False, +) -> Tensor: ... +def max_pool3d( + input: Tensor, + kernel_size: _int | _size, + stride: _int | _size = (), + padding: _int | _size = 0, + dilation: _int | _size = 1, + ceil_mode: _bool = False, +) -> Tensor: ... +def maximum( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + maximum(input, other, *, out=None) -> Tensor + + Computes the element-wise maximum of :attr:`input` and :attr:`other`. + + .. note:: + If one of the elements being compared is a NaN, then that element is returned. + :func:`maximum` is not supported for tensors with complex dtypes. + + Args: + input (Tensor): the input tensor. + other (Tensor): the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor((1, 2, -1)) + >>> b = torch.tensor((3, 0, 4)) + >>> torch.maximum(a, b) + tensor([3, 2, 4]) + """ + +@overload +def mean( + input: Tensor, + *, + dtype: _dtype | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + mean(input, *, dtype=None) -> Tensor + + .. note:: + If the `input` tensor is empty, ``torch.mean()`` returns ``nan``. + This behavior is consistent with NumPy and follows the definition + that the mean over an empty set is undefined. + + + Returns the mean value of all elements in the :attr:`input` tensor. Input must be floating point or complex. + + Args: + input (Tensor): + the input tensor, either of floating point or complex dtype + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.2294, -0.5481, 1.3288]]) + >>> torch.mean(a) + tensor(0.3367) + + .. function:: mean(input, dim, keepdim=False, *, dtype=None, out=None) -> Tensor + :noindex: + + Returns the mean value of each row of the :attr:`input` tensor in the given + dimension :attr:`dim`. If :attr:`dim` is a list of dimensions, + reduce over all of them. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + out (Tensor, optional): the output tensor. + + .. seealso:: + + :func:`torch.nanmean` computes the mean value of `non-NaN` elements. + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-0.3841, 0.6320, 0.4254, -0.7384], + [-0.9644, 1.0131, -0.6549, -1.4279], + [-0.2951, -1.3350, -0.7694, 0.5600], + [ 1.0842, -0.9580, 0.3623, 0.2343]]) + >>> torch.mean(a, 1) + tensor([-0.0163, -0.5085, -0.4599, 0.1807]) + >>> torch.mean(a, 1, True) + tensor([[-0.0163], + [-0.5085], + [-0.4599], + [ 0.1807]]) + """ + +@overload +def mean( + input: Tensor, + dim: _int | _size | None, + keepdim: _bool = False, + *, + dtype: _dtype | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + mean(input, *, dtype=None) -> Tensor + + .. note:: + If the `input` tensor is empty, ``torch.mean()`` returns ``nan``. + This behavior is consistent with NumPy and follows the definition + that the mean over an empty set is undefined. + + + Returns the mean value of all elements in the :attr:`input` tensor. Input must be floating point or complex. + + Args: + input (Tensor): + the input tensor, either of floating point or complex dtype + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.2294, -0.5481, 1.3288]]) + >>> torch.mean(a) + tensor(0.3367) + + .. function:: mean(input, dim, keepdim=False, *, dtype=None, out=None) -> Tensor + :noindex: + + Returns the mean value of each row of the :attr:`input` tensor in the given + dimension :attr:`dim`. If :attr:`dim` is a list of dimensions, + reduce over all of them. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + out (Tensor, optional): the output tensor. + + .. seealso:: + + :func:`torch.nanmean` computes the mean value of `non-NaN` elements. + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-0.3841, 0.6320, 0.4254, -0.7384], + [-0.9644, 1.0131, -0.6549, -1.4279], + [-0.2951, -1.3350, -0.7694, 0.5600], + [ 1.0842, -0.9580, 0.3623, 0.2343]]) + >>> torch.mean(a, 1) + tensor([-0.0163, -0.5085, -0.4599, 0.1807]) + >>> torch.mean(a, 1, True) + tensor([[-0.0163], + [-0.5085], + [-0.4599], + [ 0.1807]]) + """ + +@overload +def mean( + input: Tensor, + dim: Sequence[str | EllipsisType | None], + keepdim: _bool = False, + *, + dtype: _dtype | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + mean(input, *, dtype=None) -> Tensor + + .. note:: + If the `input` tensor is empty, ``torch.mean()`` returns ``nan``. + This behavior is consistent with NumPy and follows the definition + that the mean over an empty set is undefined. + + + Returns the mean value of all elements in the :attr:`input` tensor. Input must be floating point or complex. + + Args: + input (Tensor): + the input tensor, either of floating point or complex dtype + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.2294, -0.5481, 1.3288]]) + >>> torch.mean(a) + tensor(0.3367) + + .. function:: mean(input, dim, keepdim=False, *, dtype=None, out=None) -> Tensor + :noindex: + + Returns the mean value of each row of the :attr:`input` tensor in the given + dimension :attr:`dim`. If :attr:`dim` is a list of dimensions, + reduce over all of them. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + out (Tensor, optional): the output tensor. + + .. seealso:: + + :func:`torch.nanmean` computes the mean value of `non-NaN` elements. + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-0.3841, 0.6320, 0.4254, -0.7384], + [-0.9644, 1.0131, -0.6549, -1.4279], + [-0.2951, -1.3350, -0.7694, 0.5600], + [ 1.0842, -0.9580, 0.3623, 0.2343]]) + >>> torch.mean(a, 1) + tensor([-0.0163, -0.5085, -0.4599, 0.1807]) + >>> torch.mean(a, 1, True) + tensor([[-0.0163], + [-0.5085], + [-0.4599], + [ 0.1807]]) + """ + +@overload +def median(input: Tensor) -> Tensor: + r""" + median(input) -> Tensor + + Returns the median of the values in :attr:`input`. + + .. note:: + The median is not unique for :attr:`input` tensors with an even number + of elements. In this case the lower of the two medians is returned. To + compute the mean of both medians, use :func:`torch.quantile` with ``q=0.5`` instead. + + .. warning:: + This function produces deterministic (sub)gradients unlike ``median(dim=0)`` + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 1.5219, -1.5212, 0.2202]]) + >>> torch.median(a) + tensor(0.2202) + + .. function:: median(input, dim=-1, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` contains the median of each row of :attr:`input` + in the dimension :attr:`dim`, and ``indices`` contains the index of the median values found in the dimension :attr:`dim`. + + By default, :attr:`dim` is the last dimension of the :attr:`input` tensor. + + If :attr:`keepdim` is ``True``, the output tensors are of the same size + as :attr:`input` except in the dimension :attr:`dim` where they are of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in + the outputs tensor having 1 fewer dimension than :attr:`input`. + + .. note:: + The median is not unique for :attr:`input` tensors with an even number + of elements in the dimension :attr:`dim`. In this case the lower of the + two medians is returned. To compute the mean of both medians in + :attr:`input`, use :func:`torch.quantile` with ``q=0.5`` instead. + + .. warning:: + ``indices`` does not necessarily contain the first occurrence of each + median value found, unless it is unique. + The exact implementation details are device-specific. + Do not expect the same result when run on CPU and GPU in general. + For the same reason do not expect the gradients to be deterministic. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out ((Tensor, Tensor), optional): The first tensor will be populated with the median values and the second + tensor, which must have dtype long, with their indices in the dimension + :attr:`dim` of :attr:`input`. + + Example:: + + >>> a = torch.randn(4, 5) + >>> a + tensor([[ 0.2505, -0.3982, -0.9948, 0.3518, -1.3131], + [ 0.3180, -0.6993, 1.0436, 0.0438, 0.2270], + [-0.2751, 0.7303, 0.2192, 0.3321, 0.2488], + [ 1.0778, -1.9510, 0.7048, 0.4742, -0.7125]]) + >>> torch.median(a, 1) + torch.return_types.median(values=tensor([-0.3982, 0.2270, 0.2488, 0.4742]), indices=tensor([1, 4, 4, 3])) + """ + +@overload +def median( + input: Tensor, + dim: _int, + keepdim: _bool = False, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.median: + r""" + median(input) -> Tensor + + Returns the median of the values in :attr:`input`. + + .. note:: + The median is not unique for :attr:`input` tensors with an even number + of elements. In this case the lower of the two medians is returned. To + compute the mean of both medians, use :func:`torch.quantile` with ``q=0.5`` instead. + + .. warning:: + This function produces deterministic (sub)gradients unlike ``median(dim=0)`` + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 1.5219, -1.5212, 0.2202]]) + >>> torch.median(a) + tensor(0.2202) + + .. function:: median(input, dim=-1, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` contains the median of each row of :attr:`input` + in the dimension :attr:`dim`, and ``indices`` contains the index of the median values found in the dimension :attr:`dim`. + + By default, :attr:`dim` is the last dimension of the :attr:`input` tensor. + + If :attr:`keepdim` is ``True``, the output tensors are of the same size + as :attr:`input` except in the dimension :attr:`dim` where they are of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in + the outputs tensor having 1 fewer dimension than :attr:`input`. + + .. note:: + The median is not unique for :attr:`input` tensors with an even number + of elements in the dimension :attr:`dim`. In this case the lower of the + two medians is returned. To compute the mean of both medians in + :attr:`input`, use :func:`torch.quantile` with ``q=0.5`` instead. + + .. warning:: + ``indices`` does not necessarily contain the first occurrence of each + median value found, unless it is unique. + The exact implementation details are device-specific. + Do not expect the same result when run on CPU and GPU in general. + For the same reason do not expect the gradients to be deterministic. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out ((Tensor, Tensor), optional): The first tensor will be populated with the median values and the second + tensor, which must have dtype long, with their indices in the dimension + :attr:`dim` of :attr:`input`. + + Example:: + + >>> a = torch.randn(4, 5) + >>> a + tensor([[ 0.2505, -0.3982, -0.9948, 0.3518, -1.3131], + [ 0.3180, -0.6993, 1.0436, 0.0438, 0.2270], + [-0.2751, 0.7303, 0.2192, 0.3321, 0.2488], + [ 1.0778, -1.9510, 0.7048, 0.4742, -0.7125]]) + >>> torch.median(a, 1) + torch.return_types.median(values=tensor([-0.3982, 0.2270, 0.2488, 0.4742]), indices=tensor([1, 4, 4, 3])) + """ + +@overload +def median( + input: Tensor, + dim: str | EllipsisType | None, + keepdim: _bool = False, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.median: + r""" + median(input) -> Tensor + + Returns the median of the values in :attr:`input`. + + .. note:: + The median is not unique for :attr:`input` tensors with an even number + of elements. In this case the lower of the two medians is returned. To + compute the mean of both medians, use :func:`torch.quantile` with ``q=0.5`` instead. + + .. warning:: + This function produces deterministic (sub)gradients unlike ``median(dim=0)`` + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 1.5219, -1.5212, 0.2202]]) + >>> torch.median(a) + tensor(0.2202) + + .. function:: median(input, dim=-1, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` contains the median of each row of :attr:`input` + in the dimension :attr:`dim`, and ``indices`` contains the index of the median values found in the dimension :attr:`dim`. + + By default, :attr:`dim` is the last dimension of the :attr:`input` tensor. + + If :attr:`keepdim` is ``True``, the output tensors are of the same size + as :attr:`input` except in the dimension :attr:`dim` where they are of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in + the outputs tensor having 1 fewer dimension than :attr:`input`. + + .. note:: + The median is not unique for :attr:`input` tensors with an even number + of elements in the dimension :attr:`dim`. In this case the lower of the + two medians is returned. To compute the mean of both medians in + :attr:`input`, use :func:`torch.quantile` with ``q=0.5`` instead. + + .. warning:: + ``indices`` does not necessarily contain the first occurrence of each + median value found, unless it is unique. + The exact implementation details are device-specific. + Do not expect the same result when run on CPU and GPU in general. + For the same reason do not expect the gradients to be deterministic. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out ((Tensor, Tensor), optional): The first tensor will be populated with the median values and the second + tensor, which must have dtype long, with their indices in the dimension + :attr:`dim` of :attr:`input`. + + Example:: + + >>> a = torch.randn(4, 5) + >>> a + tensor([[ 0.2505, -0.3982, -0.9948, 0.3518, -1.3131], + [ 0.3180, -0.6993, 1.0436, 0.0438, 0.2270], + [-0.2751, 0.7303, 0.2192, 0.3321, 0.2488], + [ 1.0778, -1.9510, 0.7048, 0.4742, -0.7125]]) + >>> torch.median(a, 1) + torch.return_types.median(values=tensor([-0.3982, 0.2270, 0.2488, 0.4742]), indices=tensor([1, 4, 4, 3])) + """ + +@overload +def min(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + min(input, *, out=None) -> Tensor + + Returns the minimum value of all elements in the :attr:`input` tensor. + + .. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.6750, 1.0857, 1.7197]]) + >>> torch.min(a) + tensor(0.6750) + + .. function:: min(input, dim, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` is the minimum + value of each row of the :attr:`input` tensor in the given dimension + :attr:`dim`. And ``indices`` is the index location of each minimum value found + (argmin). + + If :attr:`keepdim` is ``True``, the output tensors are of the same size as + :attr:`input` except in the dimension :attr:`dim` where they are of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in + the output tensors having 1 fewer dimension than :attr:`input`. + + .. note:: If there are multiple minimal values in a reduced row then + the indices of the first minimal value are returned. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. If omitted, all dimensions are reduced. Explicit ``None`` is not supported. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (tuple, optional): the tuple of two output tensors (min, min_indices) + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-0.6248, 1.1334, -1.1899, -0.2803], + [-1.4644, -0.2635, -0.3651, 0.6134], + [ 0.2457, 0.0384, 1.0128, 0.7015], + [-0.1153, 2.9849, 2.1458, 0.5788]]) + >>> torch.min(a, 1) + torch.return_types.min(values=tensor([-1.1899, -1.4644, 0.0384, -0.1153]), indices=tensor([2, 0, 1, 0])) + + .. function:: min(input, other, *, out=None) -> Tensor + :noindex: + + See :func:`torch.minimum`. + """ + +@overload +def min( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + min(input, *, out=None) -> Tensor + + Returns the minimum value of all elements in the :attr:`input` tensor. + + .. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.6750, 1.0857, 1.7197]]) + >>> torch.min(a) + tensor(0.6750) + + .. function:: min(input, dim, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` is the minimum + value of each row of the :attr:`input` tensor in the given dimension + :attr:`dim`. And ``indices`` is the index location of each minimum value found + (argmin). + + If :attr:`keepdim` is ``True``, the output tensors are of the same size as + :attr:`input` except in the dimension :attr:`dim` where they are of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in + the output tensors having 1 fewer dimension than :attr:`input`. + + .. note:: If there are multiple minimal values in a reduced row then + the indices of the first minimal value are returned. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. If omitted, all dimensions are reduced. Explicit ``None`` is not supported. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (tuple, optional): the tuple of two output tensors (min, min_indices) + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-0.6248, 1.1334, -1.1899, -0.2803], + [-1.4644, -0.2635, -0.3651, 0.6134], + [ 0.2457, 0.0384, 1.0128, 0.7015], + [-0.1153, 2.9849, 2.1458, 0.5788]]) + >>> torch.min(a, 1) + torch.return_types.min(values=tensor([-1.1899, -1.4644, 0.0384, -0.1153]), indices=tensor([2, 0, 1, 0])) + + .. function:: min(input, other, *, out=None) -> Tensor + :noindex: + + See :func:`torch.minimum`. + """ + +@overload +def min( + input: Tensor, + dim: _int, + keepdim: _bool = False, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.min: + r""" + min(input, *, out=None) -> Tensor + + Returns the minimum value of all elements in the :attr:`input` tensor. + + .. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.6750, 1.0857, 1.7197]]) + >>> torch.min(a) + tensor(0.6750) + + .. function:: min(input, dim, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` is the minimum + value of each row of the :attr:`input` tensor in the given dimension + :attr:`dim`. And ``indices`` is the index location of each minimum value found + (argmin). + + If :attr:`keepdim` is ``True``, the output tensors are of the same size as + :attr:`input` except in the dimension :attr:`dim` where they are of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in + the output tensors having 1 fewer dimension than :attr:`input`. + + .. note:: If there are multiple minimal values in a reduced row then + the indices of the first minimal value are returned. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. If omitted, all dimensions are reduced. Explicit ``None`` is not supported. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (tuple, optional): the tuple of two output tensors (min, min_indices) + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-0.6248, 1.1334, -1.1899, -0.2803], + [-1.4644, -0.2635, -0.3651, 0.6134], + [ 0.2457, 0.0384, 1.0128, 0.7015], + [-0.1153, 2.9849, 2.1458, 0.5788]]) + >>> torch.min(a, 1) + torch.return_types.min(values=tensor([-1.1899, -1.4644, 0.0384, -0.1153]), indices=tensor([2, 0, 1, 0])) + + .. function:: min(input, other, *, out=None) -> Tensor + :noindex: + + See :func:`torch.minimum`. + """ + +@overload +def min( + input: Tensor, + dim: str | EllipsisType | None, + keepdim: _bool = False, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.min: + r""" + min(input, *, out=None) -> Tensor + + Returns the minimum value of all elements in the :attr:`input` tensor. + + .. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.6750, 1.0857, 1.7197]]) + >>> torch.min(a) + tensor(0.6750) + + .. function:: min(input, dim, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` is the minimum + value of each row of the :attr:`input` tensor in the given dimension + :attr:`dim`. And ``indices`` is the index location of each minimum value found + (argmin). + + If :attr:`keepdim` is ``True``, the output tensors are of the same size as + :attr:`input` except in the dimension :attr:`dim` where they are of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in + the output tensors having 1 fewer dimension than :attr:`input`. + + .. note:: If there are multiple minimal values in a reduced row then + the indices of the first minimal value are returned. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. If omitted, all dimensions are reduced. Explicit ``None`` is not supported. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (tuple, optional): the tuple of two output tensors (min, min_indices) + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-0.6248, 1.1334, -1.1899, -0.2803], + [-1.4644, -0.2635, -0.3651, 0.6134], + [ 0.2457, 0.0384, 1.0128, 0.7015], + [-0.1153, 2.9849, 2.1458, 0.5788]]) + >>> torch.min(a, 1) + torch.return_types.min(values=tensor([-1.1899, -1.4644, 0.0384, -0.1153]), indices=tensor([2, 0, 1, 0])) + + .. function:: min(input, other, *, out=None) -> Tensor + :noindex: + + See :func:`torch.minimum`. + """ + +def minimum( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + minimum(input, other, *, out=None) -> Tensor + + Computes the element-wise minimum of :attr:`input` and :attr:`other`. + + .. note:: + If one of the elements being compared is a NaN, then that element is returned. + :func:`minimum` is not supported for tensors with complex dtypes. + + Args: + input (Tensor): the input tensor. + other (Tensor): the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor((1, 2, -1)) + >>> b = torch.tensor((3, 0, 4)) + >>> torch.minimum(a, b) + tensor([1, 0, -1]) + """ + +def miopen_batch_norm( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + running_mean: Tensor | None, + running_var: Tensor | None, + training: _bool, + exponential_average_factor: _float, + epsilon: _float, +) -> tuple[Tensor, Tensor, Tensor]: ... +def miopen_convolution( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + padding: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + groups: _int | SymInt, + benchmark: _bool, + deterministic: _bool, +) -> Tensor: ... +def miopen_convolution_add_relu( + input: Tensor, + weight: Tensor, + z: Tensor, + alpha: Number | _complex | None, + bias: Tensor | None, + stride: Sequence[_int | SymInt], + padding: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + groups: _int | SymInt, +) -> Tensor: ... +def miopen_convolution_relu( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + stride: Sequence[_int | SymInt], + padding: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + groups: _int | SymInt, +) -> Tensor: ... +def miopen_convolution_transpose( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + padding: Sequence[_int | SymInt], + output_padding: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + groups: _int | SymInt, + benchmark: _bool, + deterministic: _bool, +) -> Tensor: ... +def miopen_depthwise_convolution( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + padding: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + groups: _int | SymInt, + benchmark: _bool, + deterministic: _bool, +) -> Tensor: ... +def miopen_rnn( + input: Tensor, + weight: tuple[Tensor, ...] | list[Tensor] | None, + weight_stride0: _int, + hx: Tensor, + cx: Tensor | None, + mode: _int, + hidden_size: _int, + num_layers: _int, + batch_first: _bool, + dropout: _float, + train: _bool, + bidirectional: _bool, + batch_sizes: _size, + dropout_state: Tensor | None, +) -> tuple[Tensor, Tensor, Tensor, Tensor, Tensor]: ... +def mkldnn_adaptive_avg_pool2d( + input: Tensor, + output_size: _int | _size, + *, + out: Tensor | None = None, +) -> Tensor: ... +def mkldnn_convolution( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + padding: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + groups: _int | SymInt, +) -> Tensor: ... +def mkldnn_linear_backward_weights( + grad_output: Tensor, + input: Tensor, + weight: Tensor, + bias_defined: _bool, +) -> tuple[Tensor, Tensor]: ... +def mkldnn_max_pool2d( + input: Tensor, + kernel_size: _int | _size, + stride: _int | _size = (), + padding: _int | _size = 0, + dilation: _int | _size = 1, + ceil_mode: _bool = False, +) -> Tensor: ... +def mkldnn_max_pool3d( + input: Tensor, + kernel_size: _int | _size, + stride: _int | _size = (), + padding: _int | _size = 0, + dilation: _int | _size = 1, + ceil_mode: _bool = False, +) -> Tensor: ... +def mkldnn_rnn_layer( + input: Tensor, + weight0: Tensor, + weight1: Tensor, + weight2: Tensor, + weight3: Tensor, + hx_: Tensor, + cx_: Tensor, + reverse: _bool, + batch_sizes: _size, + mode: _int, + hidden_size: _int, + num_layers: _int, + has_biases: _bool, + bidirectional: _bool, + batch_first: _bool, + train: _bool, +) -> tuple[Tensor, Tensor, Tensor, Tensor]: ... +@overload +def mm(input: Tensor, mat2: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + mm(input, mat2, out_dtype=None, *, out=None) -> Tensor + + Performs a matrix multiplication of the matrices :attr:`input` and :attr:`mat2`. + + If :attr:`input` is a :math:`(n \times m)` tensor, :attr:`mat2` is a + :math:`(m \times p)` tensor, :attr:`out` will be a :math:`(n \times p)` tensor. + + .. note:: This function does not :ref:`broadcast `. + For broadcasting matrix products, see :func:`torch.matmul`. + + Supports strided and sparse 2-D tensors as inputs, autograd with + respect to strided inputs. + + This operation has support for arguments with :ref:`sparse layouts`. + If :attr:`out` is provided its layout will be used. Otherwise, the result + layout will be deduced from that of :attr:`input`. + + + .. warning:: + Sparse support is a beta feature and some layout(s)/dtype/device combinations may not be supported, + or may not have autograd support. If you notice missing functionality please + open a feature request. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + out_dtype (dtype, optional): the dtype of the output tensor, + Supported only on CUDA and for torch.float32 given + torch.float16/torch.bfloat16 input dtypes + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> mat1 = torch.randn(2, 3) + >>> mat2 = torch.randn(3, 3) + >>> torch.mm(mat1, mat2) + tensor([[ 0.4851, 0.5037, -0.3633], + [-0.0760, -3.6705, 2.4784]]) + """ + +@overload +def mm( + input: Tensor, + mat2: Tensor, + out_dtype: _dtype, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + mm(input, mat2, out_dtype=None, *, out=None) -> Tensor + + Performs a matrix multiplication of the matrices :attr:`input` and :attr:`mat2`. + + If :attr:`input` is a :math:`(n \times m)` tensor, :attr:`mat2` is a + :math:`(m \times p)` tensor, :attr:`out` will be a :math:`(n \times p)` tensor. + + .. note:: This function does not :ref:`broadcast `. + For broadcasting matrix products, see :func:`torch.matmul`. + + Supports strided and sparse 2-D tensors as inputs, autograd with + respect to strided inputs. + + This operation has support for arguments with :ref:`sparse layouts`. + If :attr:`out` is provided its layout will be used. Otherwise, the result + layout will be deduced from that of :attr:`input`. + + + .. warning:: + Sparse support is a beta feature and some layout(s)/dtype/device combinations may not be supported, + or may not have autograd support. If you notice missing functionality please + open a feature request. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + out_dtype (dtype, optional): the dtype of the output tensor, + Supported only on CUDA and for torch.float32 given + torch.float16/torch.bfloat16 input dtypes + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> mat1 = torch.randn(2, 3) + >>> mat2 = torch.randn(3, 3) + >>> torch.mm(mat1, mat2) + tensor([[ 0.4851, 0.5037, -0.3633], + [-0.0760, -3.6705, 2.4784]]) + """ + +@overload +def mode( + input: Tensor, + dim: _int = -1, + keepdim: _bool = False, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.mode: + r""" + mode(input, dim=-1, keepdim=False, *, out=None) -> (Tensor, LongTensor) + + Returns a namedtuple ``(values, indices)`` where ``values`` is the mode + value of each row of the :attr:`input` tensor in the given dimension + :attr:`dim`, i.e. a value which appears most often + in that row, and ``indices`` is the index location of each mode value found. + + By default, :attr:`dim` is the last dimension of the :attr:`input` tensor. + + If :attr:`keepdim` is ``True``, the output tensors are of the same size as + :attr:`input` except in the dimension :attr:`dim` where they are of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting + in the output tensors having 1 fewer dimension than :attr:`input`. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (tuple, optional): the result tuple of two output tensors (values, indices) + + Example:: + + >>> b = torch.tensor([[0, 0, 0, 2, 0, 0, 2], + ... [0, 3, 0, 0, 2, 0, 1], + ... [2, 2, 2, 0, 0, 0, 3], + ... [2, 2, 3, 0, 1, 1, 0], + ... [1, 1, 0, 0, 2, 0, 2]]) + >>> torch.mode(b, 0) + torch.return_types.mode( + values=tensor([0, 2, 0, 0, 0, 0, 2]), + indices=tensor([1, 3, 4, 4, 2, 4, 4])) + """ + +@overload +def mode( + input: Tensor, + dim: str | EllipsisType | None, + keepdim: _bool = False, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.mode: + r""" + mode(input, dim=-1, keepdim=False, *, out=None) -> (Tensor, LongTensor) + + Returns a namedtuple ``(values, indices)`` where ``values`` is the mode + value of each row of the :attr:`input` tensor in the given dimension + :attr:`dim`, i.e. a value which appears most often + in that row, and ``indices`` is the index location of each mode value found. + + By default, :attr:`dim` is the last dimension of the :attr:`input` tensor. + + If :attr:`keepdim` is ``True``, the output tensors are of the same size as + :attr:`input` except in the dimension :attr:`dim` where they are of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting + in the output tensors having 1 fewer dimension than :attr:`input`. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (tuple, optional): the result tuple of two output tensors (values, indices) + + Example:: + + >>> b = torch.tensor([[0, 0, 0, 2, 0, 0, 2], + ... [0, 3, 0, 0, 2, 0, 1], + ... [2, 2, 2, 0, 0, 0, 3], + ... [2, 2, 3, 0, 1, 1, 0], + ... [1, 1, 0, 0, 2, 0, 2]]) + >>> torch.mode(b, 0) + torch.return_types.mode( + values=tensor([0, 2, 0, 0, 0, 0, 2]), + indices=tensor([1, 3, 4, 4, 2, 4, 4])) + """ + +@overload +def moveaxis(input: Tensor, source: _int, destination: _int) -> Tensor: + r""" + moveaxis(input, source, destination) -> Tensor + + Alias for :func:`torch.movedim`. + + This function is equivalent to NumPy's moveaxis function. + + Examples:: + + >>> t = torch.randn(3,2,1) + >>> t + tensor([[[-0.3362], + [-0.8437]], + + [[-0.9627], + [ 0.1727]], + + [[ 0.5173], + [-0.1398]]]) + >>> torch.moveaxis(t, 1, 0).shape + torch.Size([2, 3, 1]) + >>> torch.moveaxis(t, 1, 0) + tensor([[[-0.3362], + [-0.9627], + [ 0.5173]], + + [[-0.8437], + [ 0.1727], + [-0.1398]]]) + >>> torch.moveaxis(t, (1, 2), (0, 1)).shape + torch.Size([2, 1, 3]) + >>> torch.moveaxis(t, (1, 2), (0, 1)) + tensor([[[-0.3362, -0.9627, 0.5173]], + + [[-0.8437, 0.1727, -0.1398]]]) + """ + +@overload +def moveaxis(input: Tensor, source: _size, destination: _size) -> Tensor: + r""" + moveaxis(input, source, destination) -> Tensor + + Alias for :func:`torch.movedim`. + + This function is equivalent to NumPy's moveaxis function. + + Examples:: + + >>> t = torch.randn(3,2,1) + >>> t + tensor([[[-0.3362], + [-0.8437]], + + [[-0.9627], + [ 0.1727]], + + [[ 0.5173], + [-0.1398]]]) + >>> torch.moveaxis(t, 1, 0).shape + torch.Size([2, 3, 1]) + >>> torch.moveaxis(t, 1, 0) + tensor([[[-0.3362], + [-0.9627], + [ 0.5173]], + + [[-0.8437], + [ 0.1727], + [-0.1398]]]) + >>> torch.moveaxis(t, (1, 2), (0, 1)).shape + torch.Size([2, 1, 3]) + >>> torch.moveaxis(t, (1, 2), (0, 1)) + tensor([[[-0.3362, -0.9627, 0.5173]], + + [[-0.8437, 0.1727, -0.1398]]]) + """ + +@overload +def movedim(input: Tensor, source: _int, destination: _int) -> Tensor: + r""" + movedim(input, source, destination) -> Tensor + + Moves the dimension(s) of :attr:`input` at the position(s) in :attr:`source` + to the position(s) in :attr:`destination`. + + Other dimensions of :attr:`input` that are not explicitly moved remain in + their original order and appear at the positions not specified in :attr:`destination`. + + Args: + input (Tensor): the input tensor. + source (int or tuple of ints): Original positions of the dims to move. These must be unique. + destination (int or tuple of ints): Destination positions for each of the original dims. These must also be unique. + + Examples:: + + >>> t = torch.randn(3,2,1) + >>> t + tensor([[[-0.3362], + [-0.8437]], + + [[-0.9627], + [ 0.1727]], + + [[ 0.5173], + [-0.1398]]]) + >>> torch.movedim(t, 1, 0).shape + torch.Size([2, 3, 1]) + >>> torch.movedim(t, 1, 0) + tensor([[[-0.3362], + [-0.9627], + [ 0.5173]], + + [[-0.8437], + [ 0.1727], + [-0.1398]]]) + >>> torch.movedim(t, (1, 2), (0, 1)).shape + torch.Size([2, 1, 3]) + >>> torch.movedim(t, (1, 2), (0, 1)) + tensor([[[-0.3362, -0.9627, 0.5173]], + + [[-0.8437, 0.1727, -0.1398]]]) + """ + +@overload +def movedim(input: Tensor, source: _size, destination: _size) -> Tensor: + r""" + movedim(input, source, destination) -> Tensor + + Moves the dimension(s) of :attr:`input` at the position(s) in :attr:`source` + to the position(s) in :attr:`destination`. + + Other dimensions of :attr:`input` that are not explicitly moved remain in + their original order and appear at the positions not specified in :attr:`destination`. + + Args: + input (Tensor): the input tensor. + source (int or tuple of ints): Original positions of the dims to move. These must be unique. + destination (int or tuple of ints): Destination positions for each of the original dims. These must also be unique. + + Examples:: + + >>> t = torch.randn(3,2,1) + >>> t + tensor([[[-0.3362], + [-0.8437]], + + [[-0.9627], + [ 0.1727]], + + [[ 0.5173], + [-0.1398]]]) + >>> torch.movedim(t, 1, 0).shape + torch.Size([2, 3, 1]) + >>> torch.movedim(t, 1, 0) + tensor([[[-0.3362], + [-0.9627], + [ 0.5173]], + + [[-0.8437], + [ 0.1727], + [-0.1398]]]) + >>> torch.movedim(t, (1, 2), (0, 1)).shape + torch.Size([2, 1, 3]) + >>> torch.movedim(t, (1, 2), (0, 1)) + tensor([[[-0.3362, -0.9627, 0.5173]], + + [[-0.8437, 0.1727, -0.1398]]]) + """ + +def msort(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + msort(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Sorts the elements of the :attr:`input` tensor along its first dimension + in ascending order by value. + + .. note:: `torch.msort(t)` is equivalent to `torch.sort(t, dim=0)[0]`. + See also :func:`torch.sort`. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> t = torch.randn(3, 4) + >>> t + tensor([[-0.1321, 0.4370, -1.2631, -1.1289], + [-2.0527, -1.1250, 0.2275, 0.3077], + [-0.0881, -0.1259, -0.5495, 1.0284]]) + >>> torch.msort(t) + tensor([[-2.0527, -1.1250, -1.2631, -1.1289], + [-0.1321, -0.1259, -0.5495, 0.3077], + [-0.0881, 0.4370, 0.2275, 1.0284]]) + """ + +def mul( + input: Tensor | Number | _complex, + other: Tensor | Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + mul(input, other, *, out=None) -> Tensor + + Multiplies :attr:`input` by :attr:`other`. + + + .. math:: + \text{out}_i = \text{input}_i \times \text{other}_i + + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer, float, and complex inputs. + + Args: + input (Tensor): the input tensor. + other (Tensor or Number): the tensor or number to multiply input by. + + Keyword args: + out (Tensor, optional): the output tensor. + + Examples:: + + >>> a = torch.randn(3) + >>> a + tensor([ 0.2015, -0.4255, 2.6087]) + >>> torch.mul(a, 100) + tensor([ 20.1494, -42.5491, 260.8663]) + + >>> b = torch.randn(4, 1) + >>> b + tensor([[ 1.1207], + [-0.3137], + [ 0.0700], + [ 0.8378]]) + >>> c = torch.randn(1, 4) + >>> c + tensor([[ 0.5146, 0.1216, -0.5244, 2.2382]]) + >>> torch.mul(b, c) + tensor([[ 0.5767, 0.1363, -0.5877, 2.5083], + [-0.1614, -0.0382, 0.1645, -0.7021], + [ 0.0360, 0.0085, -0.0367, 0.1567], + [ 0.4312, 0.1019, -0.4394, 1.8753]]) + """ + +def multinomial( + input: Tensor, + num_samples: _int | SymInt, + replacement: _bool = False, + *, + generator: Generator | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + multinomial(input, num_samples, replacement=False, *, generator=None, out=None) -> LongTensor + + Returns a tensor where each row contains :attr:`num_samples` indices sampled + from the multinomial (a stricter definition would be multivariate, + refer to :class:`torch.distributions.multinomial.Multinomial` for more details) + probability distribution located in the corresponding row + of tensor :attr:`input`. + + .. note:: + The rows of :attr:`input` do not need to sum to one (in which case we use + the values as weights), but must be non-negative, finite and have + a non-zero sum. + + Indices are ordered from left to right according to when each was sampled + (first samples are placed in first column). + + If :attr:`input` is a vector, :attr:`out` is a vector of size :attr:`num_samples`. + + If :attr:`input` is a matrix with `m` rows, :attr:`out` is an matrix of shape + :math:`(m \times \text{num\_samples})`. + + If replacement is ``True``, samples are drawn with replacement. + + If not, they are drawn without replacement, which means that when a + sample index is drawn for a row, it cannot be drawn again for that row. + + .. note:: + When drawn without replacement, :attr:`num_samples` must be lower than + number of non-zero elements in :attr:`input` (or the min number of non-zero + elements in each row of :attr:`input` if it is a matrix). + + Args: + input (Tensor): the input tensor containing probabilities + num_samples (int): number of samples to draw + replacement (bool, optional): whether to draw with replacement or not + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + + Example:: + + >>> weights = torch.tensor([0, 10, 3, 0], dtype=torch.float) # create a tensor of weights + >>> torch.multinomial(weights, 2) + tensor([1, 2]) + >>> torch.multinomial(weights, 5) # ERROR! + RuntimeError: cannot sample n_sample > prob_dist.size(-1) samples without replacement + >>> torch.multinomial(weights, 4, replacement=True) + tensor([ 2, 1, 1, 1]) + """ + +@overload +def multiply( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + multiply(input, other, *, out=None) + + Alias for :func:`torch.mul`. + """ + +@overload +def multiply(input: Tensor, other: Number | _complex) -> Tensor: + r""" + multiply(input, other, *, out=None) + + Alias for :func:`torch.mul`. + """ + +def mv(input: Tensor, vec: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + mv(input, vec, *, out=None) -> Tensor + + Performs a matrix-vector product of the matrix :attr:`input` and the vector + :attr:`vec`. + + If :attr:`input` is a :math:`(n \times m)` tensor, :attr:`vec` is a 1-D tensor of + size :math:`m`, :attr:`out` will be 1-D of size :math:`n`. + + .. note:: This function does not :ref:`broadcast `. + + Args: + input (Tensor): matrix to be multiplied + vec (Tensor): vector to be multiplied + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> mat = torch.randn(2, 3) + >>> vec = torch.randn(3) + >>> torch.mv(mat, vec) + tensor([ 1.0404, -0.6361]) + """ + +def mvlgamma( + input: Tensor, + p: _int, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + mvlgamma(input, p, *, out=None) -> Tensor + + Alias for :func:`torch.special.multigammaln`. + """ + +def nan_to_num( + input: Tensor, + nan: _float | None = None, + posinf: _float | None = None, + neginf: _float | None = None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + nan_to_num(input, nan=0.0, posinf=None, neginf=None, *, out=None) -> Tensor + + Replaces :literal:`NaN`, positive infinity, and negative infinity values in :attr:`input` + with the values specified by :attr:`nan`, :attr:`posinf`, and :attr:`neginf`, respectively. + By default, :literal:`NaN`\ s are replaced with zero, positive infinity is replaced with the + greatest finite value representable by :attr:`input`'s dtype, and negative infinity + is replaced with the least finite value representable by :attr:`input`'s dtype. + + Args: + input (Tensor): the input tensor. + nan (Number, optional): the value to replace :literal:`NaN`\s with. Default is zero. + posinf (Number, optional): if a Number, the value to replace positive infinity values with. + If None, positive infinity values are replaced with the greatest finite value representable by :attr:`input`'s dtype. + Default is None. + neginf (Number, optional): if a Number, the value to replace negative infinity values with. + If None, negative infinity values are replaced with the lowest finite value representable by :attr:`input`'s dtype. + Default is None. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> x = torch.tensor([float('nan'), float('inf'), -float('inf'), 3.14]) + >>> torch.nan_to_num(x) + tensor([ 0.0000e+00, 3.4028e+38, -3.4028e+38, 3.1400e+00]) + >>> torch.nan_to_num(x, nan=2.0) + tensor([ 2.0000e+00, 3.4028e+38, -3.4028e+38, 3.1400e+00]) + >>> torch.nan_to_num(x, nan=2.0, posinf=1.0) + tensor([ 2.0000e+00, 1.0000e+00, -3.4028e+38, 3.1400e+00]) + """ + +def nan_to_num_( + input: Tensor, + nan: _float | None = None, + posinf: _float | None = None, + neginf: _float | None = None, +) -> Tensor: ... +def nanmean( + input: Tensor, + dim: _int | _size | None = None, + keepdim: _bool = False, + *, + dtype: _dtype | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + nanmean(input, dim=None, keepdim=False, *, dtype=None, out=None) -> Tensor + + Computes the mean of all `non-NaN` elements along the specified dimensions. + Input must be floating point or complex. + + This function is identical to :func:`torch.mean` when there are no `NaN` values + in the :attr:`input` tensor. In the presence of `NaN`, :func:`torch.mean` will + propagate the `NaN` to the output whereas :func:`torch.nanmean` will ignore the + `NaN` values (`torch.nanmean(a)` is equivalent to `torch.mean(a[~a.isnan()])`). + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor, either of floating point or complex dtype + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + out (Tensor, optional): the output tensor. + + .. seealso:: + + :func:`torch.mean` computes the mean value, propagating `NaN`. + + Example:: + + >>> x = torch.tensor([[torch.nan, 1, 2], [1, 2, 3]]) + >>> x.mean() + tensor(nan) + >>> x.nanmean() + tensor(1.8000) + >>> x.mean(dim=0) + tensor([ nan, 1.5000, 2.5000]) + >>> x.nanmean(dim=0) + tensor([1.0000, 1.5000, 2.5000]) + + # If all elements in the reduced dimensions are NaN then the result is NaN + >>> torch.tensor([torch.nan]).nanmean() + tensor(nan) + """ + +@overload +def nanmedian(input: Tensor) -> Tensor: + r""" + nanmedian(input) -> Tensor + + Returns the median of the values in :attr:`input`, ignoring ``NaN`` values. + + This function is identical to :func:`torch.median` when there are no ``NaN`` values in :attr:`input`. + When :attr:`input` has one or more ``NaN`` values, :func:`torch.median` will always return ``NaN``, + while this function will return the median of the non-``NaN`` elements in :attr:`input`. + If all the elements in :attr:`input` are ``NaN`` it will also return ``NaN``. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> a = torch.tensor([1, float('nan'), 3, 2]) + >>> a.median() + tensor(nan) + >>> a.nanmedian() + tensor(2.) + + .. function:: nanmedian(input, dim=-1, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` contains the median of each row of :attr:`input` + in the dimension :attr:`dim`, ignoring ``NaN`` values, and ``indices`` contains the index of the median values + found in the dimension :attr:`dim`. + + This function is identical to :func:`torch.median` when there are no ``NaN`` values in a reduced row. When a reduced row has + one or more ``NaN`` values, :func:`torch.median` will always reduce it to ``NaN``, while this function will reduce it to the + median of the non-``NaN`` elements. If all the elements in a reduced row are ``NaN`` then it will be reduced to ``NaN``, too. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out ((Tensor, Tensor), optional): The first tensor will be populated with the median values and the second + tensor, which must have dtype long, with their indices in the dimension + :attr:`dim` of :attr:`input`. + + Example:: + + >>> a = torch.tensor([[2, 3, 1], [float('nan'), 1, float('nan')]]) + >>> a + tensor([[2., 3., 1.], + [nan, 1., nan]]) + >>> a.median(0) + torch.return_types.median(values=tensor([nan, 1., nan]), indices=tensor([1, 1, 1])) + >>> a.nanmedian(0) + torch.return_types.nanmedian(values=tensor([2., 1., 1.]), indices=tensor([0, 1, 0])) + """ + +@overload +def nanmedian( + input: Tensor, + dim: _int, + keepdim: _bool = False, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.nanmedian: + r""" + nanmedian(input) -> Tensor + + Returns the median of the values in :attr:`input`, ignoring ``NaN`` values. + + This function is identical to :func:`torch.median` when there are no ``NaN`` values in :attr:`input`. + When :attr:`input` has one or more ``NaN`` values, :func:`torch.median` will always return ``NaN``, + while this function will return the median of the non-``NaN`` elements in :attr:`input`. + If all the elements in :attr:`input` are ``NaN`` it will also return ``NaN``. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> a = torch.tensor([1, float('nan'), 3, 2]) + >>> a.median() + tensor(nan) + >>> a.nanmedian() + tensor(2.) + + .. function:: nanmedian(input, dim=-1, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` contains the median of each row of :attr:`input` + in the dimension :attr:`dim`, ignoring ``NaN`` values, and ``indices`` contains the index of the median values + found in the dimension :attr:`dim`. + + This function is identical to :func:`torch.median` when there are no ``NaN`` values in a reduced row. When a reduced row has + one or more ``NaN`` values, :func:`torch.median` will always reduce it to ``NaN``, while this function will reduce it to the + median of the non-``NaN`` elements. If all the elements in a reduced row are ``NaN`` then it will be reduced to ``NaN``, too. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out ((Tensor, Tensor), optional): The first tensor will be populated with the median values and the second + tensor, which must have dtype long, with their indices in the dimension + :attr:`dim` of :attr:`input`. + + Example:: + + >>> a = torch.tensor([[2, 3, 1], [float('nan'), 1, float('nan')]]) + >>> a + tensor([[2., 3., 1.], + [nan, 1., nan]]) + >>> a.median(0) + torch.return_types.median(values=tensor([nan, 1., nan]), indices=tensor([1, 1, 1])) + >>> a.nanmedian(0) + torch.return_types.nanmedian(values=tensor([2., 1., 1.]), indices=tensor([0, 1, 0])) + """ + +@overload +def nanmedian( + input: Tensor, + dim: str | EllipsisType | None, + keepdim: _bool = False, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.nanmedian: + r""" + nanmedian(input) -> Tensor + + Returns the median of the values in :attr:`input`, ignoring ``NaN`` values. + + This function is identical to :func:`torch.median` when there are no ``NaN`` values in :attr:`input`. + When :attr:`input` has one or more ``NaN`` values, :func:`torch.median` will always return ``NaN``, + while this function will return the median of the non-``NaN`` elements in :attr:`input`. + If all the elements in :attr:`input` are ``NaN`` it will also return ``NaN``. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> a = torch.tensor([1, float('nan'), 3, 2]) + >>> a.median() + tensor(nan) + >>> a.nanmedian() + tensor(2.) + + .. function:: nanmedian(input, dim=-1, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` contains the median of each row of :attr:`input` + in the dimension :attr:`dim`, ignoring ``NaN`` values, and ``indices`` contains the index of the median values + found in the dimension :attr:`dim`. + + This function is identical to :func:`torch.median` when there are no ``NaN`` values in a reduced row. When a reduced row has + one or more ``NaN`` values, :func:`torch.median` will always reduce it to ``NaN``, while this function will reduce it to the + median of the non-``NaN`` elements. If all the elements in a reduced row are ``NaN`` then it will be reduced to ``NaN``, too. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out ((Tensor, Tensor), optional): The first tensor will be populated with the median values and the second + tensor, which must have dtype long, with their indices in the dimension + :attr:`dim` of :attr:`input`. + + Example:: + + >>> a = torch.tensor([[2, 3, 1], [float('nan'), 1, float('nan')]]) + >>> a + tensor([[2., 3., 1.], + [nan, 1., nan]]) + >>> a.median(0) + torch.return_types.median(values=tensor([nan, 1., nan]), indices=tensor([1, 1, 1])) + >>> a.nanmedian(0) + torch.return_types.nanmedian(values=tensor([2., 1., 1.]), indices=tensor([0, 1, 0])) + """ + +@overload +def nanquantile( + input: Tensor, + q: Tensor, + dim: _int | None = None, + keepdim: _bool = False, + *, + interpolation: str = "linear", + out: Tensor | None = None, +) -> Tensor: + r""" + nanquantile(input, q, dim=None, keepdim=False, *, interpolation='linear', out=None) -> Tensor + + This is a variant of :func:`torch.quantile` that "ignores" ``NaN`` values, + computing the quantiles :attr:`q` as if ``NaN`` values in :attr:`input` did + not exist. If all values in a reduced row are ``NaN`` then the quantiles for + that reduction will be ``NaN``. See the documentation for :func:`torch.quantile`. + + Args: + input (Tensor): the input tensor. + q (float or Tensor): a scalar or 1D tensor of quantile values in the range [0, 1] + + dim (int, optional): the dimension to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword arguments: + interpolation (str): interpolation method to use when the desired quantile lies between two data points. + Can be ``linear``, ``lower``, ``higher``, ``midpoint`` and ``nearest``. + Default is ``linear``. + out (Tensor, optional): the output tensor. + + Example:: + + >>> t = torch.tensor([float('nan'), 1, 2]) + >>> t.quantile(0.5) + tensor(nan) + >>> t.nanquantile(0.5) + tensor(1.5000) + >>> t = torch.tensor([[float('nan'), float('nan')], [1, 2]]) + >>> t + tensor([[nan, nan], + [1., 2.]]) + >>> t.nanquantile(0.5, dim=0) + tensor([1., 2.]) + >>> t.nanquantile(0.5, dim=1) + tensor([ nan, 1.5000]) + """ + +@overload +def nanquantile( + input: Tensor, + q: _float, + dim: _int | None = None, + keepdim: _bool = False, + *, + interpolation: str = "linear", + out: Tensor | None = None, +) -> Tensor: + r""" + nanquantile(input, q, dim=None, keepdim=False, *, interpolation='linear', out=None) -> Tensor + + This is a variant of :func:`torch.quantile` that "ignores" ``NaN`` values, + computing the quantiles :attr:`q` as if ``NaN`` values in :attr:`input` did + not exist. If all values in a reduced row are ``NaN`` then the quantiles for + that reduction will be ``NaN``. See the documentation for :func:`torch.quantile`. + + Args: + input (Tensor): the input tensor. + q (float or Tensor): a scalar or 1D tensor of quantile values in the range [0, 1] + + dim (int, optional): the dimension to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword arguments: + interpolation (str): interpolation method to use when the desired quantile lies between two data points. + Can be ``linear``, ``lower``, ``higher``, ``midpoint`` and ``nearest``. + Default is ``linear``. + out (Tensor, optional): the output tensor. + + Example:: + + >>> t = torch.tensor([float('nan'), 1, 2]) + >>> t.quantile(0.5) + tensor(nan) + >>> t.nanquantile(0.5) + tensor(1.5000) + >>> t = torch.tensor([[float('nan'), float('nan')], [1, 2]]) + >>> t + tensor([[nan, nan], + [1., 2.]]) + >>> t.nanquantile(0.5, dim=0) + tensor([1., 2.]) + >>> t.nanquantile(0.5, dim=1) + tensor([ nan, 1.5000]) + """ + +def nansum( + input: Tensor, + dim: _int | _size | None = None, + keepdim: _bool = False, + *, + dtype: _dtype | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + nansum(input, *, dtype=None) -> Tensor + + Returns the sum of all elements, treating Not a Numbers (NaNs) as zero. + + Args: + input (Tensor): the input tensor. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + + Example:: + + >>> a = torch.tensor([1., 2., float('nan'), 4.]) + >>> torch.nansum(a) + tensor(7.) + + .. function:: nansum(input, dim, keepdim=False, *, dtype=None) -> Tensor + :noindex: + + Returns the sum of each row of the :attr:`input` tensor in the given + dimension :attr:`dim`, treating Not a Numbers (NaNs) as zero. + If :attr:`dim` is a list of dimensions, reduce over all of them. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + + Example:: + + >>> torch.nansum(torch.tensor([1., float("nan")])) + tensor(1.) + >>> a = torch.tensor([[1, 2], [3., float("nan")]]) + >>> torch.nansum(a) + tensor(6.) + >>> torch.nansum(a, dim=0) + tensor([4., 2.]) + >>> torch.nansum(a, dim=1) + tensor([3., 3.]) + """ + +@overload +def narrow( + input: Tensor, + dim: _int, + start: Tensor, + length: _int | SymInt, +) -> Tensor: + r""" + narrow(input, dim, start, length) -> Tensor + + Returns a new tensor that is a narrowed version of :attr:`input` tensor. The + dimension :attr:`dim` is input from :attr:`start` to ``start + length``. The + returned tensor and :attr:`input` tensor share the same underlying storage. + + Args: + input (Tensor): the tensor to narrow + dim (int): the dimension along which to narrow + start (int or Tensor): index of the element to start the narrowed dimension + from. Can be negative, which means indexing from the end of `dim`. If + `Tensor`, it must be an 0-dim integral `Tensor` (bools not allowed) + length (int): length of the narrowed dimension, must be weakly positive + + Example:: + + >>> x = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + >>> torch.narrow(x, 0, 0, 2) + tensor([[ 1, 2, 3], + [ 4, 5, 6]]) + >>> torch.narrow(x, 1, 1, 2) + tensor([[ 2, 3], + [ 5, 6], + [ 8, 9]]) + >>> torch.narrow(x, -1, torch.tensor(-1), 1) + tensor([[3], + [6], + [9]]) + """ + +@overload +def narrow( + input: Tensor, + dim: _int, + start: _int | SymInt, + length: _int | SymInt, +) -> Tensor: + r""" + narrow(input, dim, start, length) -> Tensor + + Returns a new tensor that is a narrowed version of :attr:`input` tensor. The + dimension :attr:`dim` is input from :attr:`start` to ``start + length``. The + returned tensor and :attr:`input` tensor share the same underlying storage. + + Args: + input (Tensor): the tensor to narrow + dim (int): the dimension along which to narrow + start (int or Tensor): index of the element to start the narrowed dimension + from. Can be negative, which means indexing from the end of `dim`. If + `Tensor`, it must be an 0-dim integral `Tensor` (bools not allowed) + length (int): length of the narrowed dimension, must be weakly positive + + Example:: + + >>> x = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + >>> torch.narrow(x, 0, 0, 2) + tensor([[ 1, 2, 3], + [ 4, 5, 6]]) + >>> torch.narrow(x, 1, 1, 2) + tensor([[ 2, 3], + [ 5, 6], + [ 8, 9]]) + >>> torch.narrow(x, -1, torch.tensor(-1), 1) + tensor([[3], + [6], + [9]]) + """ + +def narrow_copy( + input: Tensor, + dim: _int, + start: _int | SymInt, + length: _int | SymInt, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + narrow_copy(input, dim, start, length, *, out=None) -> Tensor + + Same as :meth:`Tensor.narrow` except this returns a copy rather + than shared storage. This is primarily for sparse tensors, which + do not have a shared-storage narrow method. + + Args: + input (Tensor): the tensor to narrow + dim (int): the dimension along which to narrow + start (int): index of the element to start the narrowed dimension from. Can + be negative, which means indexing from the end of `dim` + length (int): length of the narrowed dimension, must be weakly positive + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> x = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + >>> torch.narrow_copy(x, 0, 0, 2) + tensor([[ 1, 2, 3], + [ 4, 5, 6]]) + >>> torch.narrow_copy(x, 1, 1, 2) + tensor([[ 2, 3], + [ 5, 6], + [ 8, 9]]) + >>> s = torch.arange(16).reshape(2, 2, 2, 2).to_sparse(2) + >>> torch.narrow_copy(s, 0, 0, 1) + tensor(indices=tensor([[0, 0], + [0, 1]]), + values=tensor([[[0, 1], + [2, 3]], + + [[4, 5], + [6, 7]]]), + size=(1, 2, 2, 2), nnz=2, layout=torch.sparse_coo) + + .. seealso:: + + :func:`torch.narrow` for a non copy variant + """ + +def native_batch_norm( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + running_mean: Tensor | None, + running_var: Tensor | None, + training: _bool, + momentum: _float, + eps: _float, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> tuple[Tensor, Tensor, Tensor]: ... +def native_channel_shuffle(input: Tensor, groups: _int | SymInt) -> Tensor: ... +def native_dropout( + input: Tensor, + p: _float, + train: _bool | None, +) -> tuple[Tensor, Tensor]: ... +def native_group_norm( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + N: _int | SymInt, + C: _int | SymInt, + HxW: _int | SymInt, + group: _int, + eps: _float, +) -> tuple[Tensor, Tensor, Tensor]: ... +def native_layer_norm( + input: Tensor, + normalized_shape: Sequence[_int | SymInt], + weight: Tensor | None, + bias: Tensor | None, + eps: _float, +) -> tuple[Tensor, Tensor, Tensor]: ... +@overload +def native_norm( + input: Tensor, + p: Number | _complex | None, + dim: _int | _size, + keepdim: _bool, + dtype: _dtype | None, +) -> Tensor: ... +@overload +def native_norm(input: Tensor, p: Number | _complex = 2) -> Tensor: ... +@overload +def ne( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + ne(input, other, *, out=None) -> Tensor + + Computes :math:`\text{input} \neq \text{other}` element-wise. + + + The second argument can be a number or a tensor whose shape is + :ref:`broadcastable ` with the first argument. + + Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is not equal to :attr:`other` and False elsewhere + + Example:: + + >>> torch.ne(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[False, True], [True, False]]) + """ + +@overload +def ne( + input: Tensor, + other: Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + ne(input, other, *, out=None) -> Tensor + + Computes :math:`\text{input} \neq \text{other}` element-wise. + + + The second argument can be a number or a tensor whose shape is + :ref:`broadcastable ` with the first argument. + + Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is not equal to :attr:`other` and False elsewhere + + Example:: + + >>> torch.ne(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[False, True], [True, False]]) + """ + +def neg(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + neg(input, *, out=None) -> Tensor + + Returns a new tensor with the negative of the elements of :attr:`input`. + + .. math:: + \text{out} = -1 \times \text{input} + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(5) + >>> a + tensor([ 0.0090, -0.2262, -0.0682, -0.2866, 0.3940]) + >>> torch.neg(a) + tensor([-0.0090, 0.2262, 0.0682, 0.2866, -0.3940]) + """ + +def neg_(input: Tensor) -> Tensor: ... +def negative(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + negative(input, *, out=None) -> Tensor + + Alias for :func:`torch.neg` + """ + +def negative_(input: Tensor) -> Tensor: ... +def nextafter( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + nextafter(input, other, *, out=None) -> Tensor + + Return the next floating-point value after :attr:`input` towards :attr:`other`, elementwise. + + The shapes of ``input`` and ``other`` must be + :ref:`broadcastable `. + + Args: + input (Tensor): the first input tensor + other (Tensor): the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> eps = torch.finfo(torch.float32).eps + >>> torch.nextafter(torch.tensor([1.0, 2.0]), torch.tensor([2.0, 1.0])) == torch.tensor([eps + 1, 2 - eps]) + tensor([True, True]) + """ + +@overload +def nonzero( + input: Tensor, + *, + as_tuple: Literal[False] = False, + out: Tensor | None = None, +) -> Tensor: + r""" + nonzero(input, *, out=None, as_tuple=False) -> LongTensor or tuple of LongTensors + + .. note:: + :func:`torch.nonzero(..., as_tuple=False) ` (default) returns a + 2-D tensor where each row is the index for a nonzero value. + + :func:`torch.nonzero(..., as_tuple=True) ` returns a tuple of 1-D + index tensors, allowing for advanced indexing, so ``x[x.nonzero(as_tuple=True)]`` + gives all nonzero values of tensor ``x``. Of the returned tuple, each index tensor + contains nonzero indices for a certain dimension. + + See below for more details on the two behaviors. + + When :attr:`input` is on CUDA, :func:`torch.nonzero() ` causes + host-device synchronization. + + **When** :attr:`as_tuple` **is** ``False`` **(default)**: + + Returns a tensor containing the indices of all non-zero elements of + :attr:`input`. Each row in the result contains the indices of a non-zero + element in :attr:`input`. The result is sorted lexicographically, with + the last index changing the fastest (C-style). + + If :attr:`input` has :math:`n` dimensions, then the resulting indices tensor + :attr:`out` is of size :math:`(z \times n)`, where :math:`z` is the total number of + non-zero elements in the :attr:`input` tensor. + + **When** :attr:`as_tuple` **is** ``True``: + + Returns a tuple of 1-D tensors, one for each dimension in :attr:`input`, + each containing the indices (in that dimension) of all non-zero elements of + :attr:`input` . + + If :attr:`input` has :math:`n` dimensions, then the resulting tuple contains :math:`n` + tensors of size :math:`z`, where :math:`z` is the total number of + non-zero elements in the :attr:`input` tensor. + + As a special case, when :attr:`input` has zero dimensions and a nonzero scalar + value, it is treated as a one-dimensional tensor with one element. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (LongTensor, optional): the output tensor containing indices + + Returns: + LongTensor or tuple of LongTensor: If :attr:`as_tuple` is ``False``, the output + tensor containing indices. If :attr:`as_tuple` is ``True``, one 1-D tensor for + each dimension, containing the indices of each nonzero element along that + dimension. + + Example:: + + >>> torch.nonzero(torch.tensor([1, 1, 1, 0, 1])) + tensor([[ 0], + [ 1], + [ 2], + [ 4]]) + >>> torch.nonzero(torch.tensor([[0.6, 0.0, 0.0, 0.0], + ... [0.0, 0.4, 0.0, 0.0], + ... [0.0, 0.0, 1.2, 0.0], + ... [0.0, 0.0, 0.0,-0.4]])) + tensor([[ 0, 0], + [ 1, 1], + [ 2, 2], + [ 3, 3]]) + >>> torch.nonzero(torch.tensor([1, 1, 1, 0, 1]), as_tuple=True) + (tensor([0, 1, 2, 4]),) + >>> torch.nonzero(torch.tensor([[0.6, 0.0, 0.0, 0.0], + ... [0.0, 0.4, 0.0, 0.0], + ... [0.0, 0.0, 1.2, 0.0], + ... [0.0, 0.0, 0.0,-0.4]]), as_tuple=True) + (tensor([0, 1, 2, 3]), tensor([0, 1, 2, 3])) + >>> torch.nonzero(torch.tensor(5), as_tuple=True) + (tensor([0]),) + """ + +@overload +def nonzero( + input: Tensor, + *, + as_tuple: Literal[True], +) -> tuple[Tensor, ...]: + r""" + nonzero(input, *, out=None, as_tuple=False) -> LongTensor or tuple of LongTensors + + .. note:: + :func:`torch.nonzero(..., as_tuple=False) ` (default) returns a + 2-D tensor where each row is the index for a nonzero value. + + :func:`torch.nonzero(..., as_tuple=True) ` returns a tuple of 1-D + index tensors, allowing for advanced indexing, so ``x[x.nonzero(as_tuple=True)]`` + gives all nonzero values of tensor ``x``. Of the returned tuple, each index tensor + contains nonzero indices for a certain dimension. + + See below for more details on the two behaviors. + + When :attr:`input` is on CUDA, :func:`torch.nonzero() ` causes + host-device synchronization. + + **When** :attr:`as_tuple` **is** ``False`` **(default)**: + + Returns a tensor containing the indices of all non-zero elements of + :attr:`input`. Each row in the result contains the indices of a non-zero + element in :attr:`input`. The result is sorted lexicographically, with + the last index changing the fastest (C-style). + + If :attr:`input` has :math:`n` dimensions, then the resulting indices tensor + :attr:`out` is of size :math:`(z \times n)`, where :math:`z` is the total number of + non-zero elements in the :attr:`input` tensor. + + **When** :attr:`as_tuple` **is** ``True``: + + Returns a tuple of 1-D tensors, one for each dimension in :attr:`input`, + each containing the indices (in that dimension) of all non-zero elements of + :attr:`input` . + + If :attr:`input` has :math:`n` dimensions, then the resulting tuple contains :math:`n` + tensors of size :math:`z`, where :math:`z` is the total number of + non-zero elements in the :attr:`input` tensor. + + As a special case, when :attr:`input` has zero dimensions and a nonzero scalar + value, it is treated as a one-dimensional tensor with one element. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (LongTensor, optional): the output tensor containing indices + + Returns: + LongTensor or tuple of LongTensor: If :attr:`as_tuple` is ``False``, the output + tensor containing indices. If :attr:`as_tuple` is ``True``, one 1-D tensor for + each dimension, containing the indices of each nonzero element along that + dimension. + + Example:: + + >>> torch.nonzero(torch.tensor([1, 1, 1, 0, 1])) + tensor([[ 0], + [ 1], + [ 2], + [ 4]]) + >>> torch.nonzero(torch.tensor([[0.6, 0.0, 0.0, 0.0], + ... [0.0, 0.4, 0.0, 0.0], + ... [0.0, 0.0, 1.2, 0.0], + ... [0.0, 0.0, 0.0,-0.4]])) + tensor([[ 0, 0], + [ 1, 1], + [ 2, 2], + [ 3, 3]]) + >>> torch.nonzero(torch.tensor([1, 1, 1, 0, 1]), as_tuple=True) + (tensor([0, 1, 2, 4]),) + >>> torch.nonzero(torch.tensor([[0.6, 0.0, 0.0, 0.0], + ... [0.0, 0.4, 0.0, 0.0], + ... [0.0, 0.0, 1.2, 0.0], + ... [0.0, 0.0, 0.0,-0.4]]), as_tuple=True) + (tensor([0, 1, 2, 3]), tensor([0, 1, 2, 3])) + >>> torch.nonzero(torch.tensor(5), as_tuple=True) + (tensor([0]),) + """ + +def nonzero_static( + input: Tensor, + *, + size: _int | SymInt, + fill_value: _int = -1, + out: Tensor | None = None, +) -> Tensor: ... +def norm_except_dim(v: Tensor, pow: _int = 2, dim: _int = 0) -> Tensor: ... +@overload +def normal( + mean: Tensor, + std: Tensor, + *, + generator: Generator | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + normal(mean, std, *, generator=None, out=None) -> Tensor + + Returns a tensor of random numbers drawn from separate normal distributions + whose mean and standard deviation are given. + + The :attr:`mean` is a tensor with the mean of + each output element's normal distribution + + The :attr:`std` is a tensor with the standard deviation of + each output element's normal distribution + + The shapes of :attr:`mean` and :attr:`std` don't need to match, but the + total number of elements in each tensor need to be the same. + + .. note:: When the shapes do not match, the shape of :attr:`mean` + is used as the shape for the returned output tensor + + .. note:: When :attr:`std` is a CUDA tensor, this function synchronizes + its device with the CPU. + + Args: + mean (Tensor): the tensor of per-element means + std (Tensor): the tensor of per-element standard deviations + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.normal(mean=torch.arange(1., 11.), std=torch.arange(1, 0, -0.1)) + tensor([ 1.0425, 3.5672, 2.7969, 4.2925, 4.7229, 6.2134, + 8.0505, 8.1408, 9.0563, 10.0566]) + + .. function:: normal(mean=0.0, std, *, out=None) -> Tensor + :noindex: + + Similar to the function above, but the means are shared among all drawn + elements. + + Args: + mean (float, optional): the mean for all distributions + std (Tensor): the tensor of per-element standard deviations + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.normal(mean=0.5, std=torch.arange(1., 6.)) + tensor([-1.2793, -1.0732, -2.0687, 5.1177, -1.2303]) + + .. function:: normal(mean, std=1.0, *, out=None) -> Tensor + :noindex: + + Similar to the function above, but the standard deviations are shared among + all drawn elements. + + Args: + mean (Tensor): the tensor of per-element means + std (float, optional): the standard deviation for all distributions + + Keyword args: + out (Tensor, optional): the output tensor + + Example:: + + >>> torch.normal(mean=torch.arange(1., 6.)) + tensor([ 1.1552, 2.6148, 2.6535, 5.8318, 4.2361]) + + .. function:: normal(mean, std, size, *, out=None) -> Tensor + :noindex: + + Similar to the function above, but the means and standard deviations are shared + among all drawn elements. The resulting tensor has size given by :attr:`size`. + + Args: + mean (float): the mean for all distributions + std (float): the standard deviation for all distributions + size (int...): a sequence of integers defining the shape of the output tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.normal(2, 3, size=(1, 4)) + tensor([[-1.3987, -1.9544, 3.6048, 0.7909]]) + """ + +@overload +def normal( + mean: Tensor, + std: _float = 1, + *, + generator: Generator | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + normal(mean, std, *, generator=None, out=None) -> Tensor + + Returns a tensor of random numbers drawn from separate normal distributions + whose mean and standard deviation are given. + + The :attr:`mean` is a tensor with the mean of + each output element's normal distribution + + The :attr:`std` is a tensor with the standard deviation of + each output element's normal distribution + + The shapes of :attr:`mean` and :attr:`std` don't need to match, but the + total number of elements in each tensor need to be the same. + + .. note:: When the shapes do not match, the shape of :attr:`mean` + is used as the shape for the returned output tensor + + .. note:: When :attr:`std` is a CUDA tensor, this function synchronizes + its device with the CPU. + + Args: + mean (Tensor): the tensor of per-element means + std (Tensor): the tensor of per-element standard deviations + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.normal(mean=torch.arange(1., 11.), std=torch.arange(1, 0, -0.1)) + tensor([ 1.0425, 3.5672, 2.7969, 4.2925, 4.7229, 6.2134, + 8.0505, 8.1408, 9.0563, 10.0566]) + + .. function:: normal(mean=0.0, std, *, out=None) -> Tensor + :noindex: + + Similar to the function above, but the means are shared among all drawn + elements. + + Args: + mean (float, optional): the mean for all distributions + std (Tensor): the tensor of per-element standard deviations + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.normal(mean=0.5, std=torch.arange(1., 6.)) + tensor([-1.2793, -1.0732, -2.0687, 5.1177, -1.2303]) + + .. function:: normal(mean, std=1.0, *, out=None) -> Tensor + :noindex: + + Similar to the function above, but the standard deviations are shared among + all drawn elements. + + Args: + mean (Tensor): the tensor of per-element means + std (float, optional): the standard deviation for all distributions + + Keyword args: + out (Tensor, optional): the output tensor + + Example:: + + >>> torch.normal(mean=torch.arange(1., 6.)) + tensor([ 1.1552, 2.6148, 2.6535, 5.8318, 4.2361]) + + .. function:: normal(mean, std, size, *, out=None) -> Tensor + :noindex: + + Similar to the function above, but the means and standard deviations are shared + among all drawn elements. The resulting tensor has size given by :attr:`size`. + + Args: + mean (float): the mean for all distributions + std (float): the standard deviation for all distributions + size (int...): a sequence of integers defining the shape of the output tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.normal(2, 3, size=(1, 4)) + tensor([[-1.3987, -1.9544, 3.6048, 0.7909]]) + """ + +@overload +def normal( + mean: _float, + std: Tensor, + *, + generator: Generator | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + normal(mean, std, *, generator=None, out=None) -> Tensor + + Returns a tensor of random numbers drawn from separate normal distributions + whose mean and standard deviation are given. + + The :attr:`mean` is a tensor with the mean of + each output element's normal distribution + + The :attr:`std` is a tensor with the standard deviation of + each output element's normal distribution + + The shapes of :attr:`mean` and :attr:`std` don't need to match, but the + total number of elements in each tensor need to be the same. + + .. note:: When the shapes do not match, the shape of :attr:`mean` + is used as the shape for the returned output tensor + + .. note:: When :attr:`std` is a CUDA tensor, this function synchronizes + its device with the CPU. + + Args: + mean (Tensor): the tensor of per-element means + std (Tensor): the tensor of per-element standard deviations + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.normal(mean=torch.arange(1., 11.), std=torch.arange(1, 0, -0.1)) + tensor([ 1.0425, 3.5672, 2.7969, 4.2925, 4.7229, 6.2134, + 8.0505, 8.1408, 9.0563, 10.0566]) + + .. function:: normal(mean=0.0, std, *, out=None) -> Tensor + :noindex: + + Similar to the function above, but the means are shared among all drawn + elements. + + Args: + mean (float, optional): the mean for all distributions + std (Tensor): the tensor of per-element standard deviations + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.normal(mean=0.5, std=torch.arange(1., 6.)) + tensor([-1.2793, -1.0732, -2.0687, 5.1177, -1.2303]) + + .. function:: normal(mean, std=1.0, *, out=None) -> Tensor + :noindex: + + Similar to the function above, but the standard deviations are shared among + all drawn elements. + + Args: + mean (Tensor): the tensor of per-element means + std (float, optional): the standard deviation for all distributions + + Keyword args: + out (Tensor, optional): the output tensor + + Example:: + + >>> torch.normal(mean=torch.arange(1., 6.)) + tensor([ 1.1552, 2.6148, 2.6535, 5.8318, 4.2361]) + + .. function:: normal(mean, std, size, *, out=None) -> Tensor + :noindex: + + Similar to the function above, but the means and standard deviations are shared + among all drawn elements. The resulting tensor has size given by :attr:`size`. + + Args: + mean (float): the mean for all distributions + std (float): the standard deviation for all distributions + size (int...): a sequence of integers defining the shape of the output tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.normal(2, 3, size=(1, 4)) + tensor([[-1.3987, -1.9544, 3.6048, 0.7909]]) + """ + +@overload +def normal( + mean: _float, + std: _float, + size: Sequence[_int | SymInt], + *, + generator: Generator | None = None, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + normal(mean, std, *, generator=None, out=None) -> Tensor + + Returns a tensor of random numbers drawn from separate normal distributions + whose mean and standard deviation are given. + + The :attr:`mean` is a tensor with the mean of + each output element's normal distribution + + The :attr:`std` is a tensor with the standard deviation of + each output element's normal distribution + + The shapes of :attr:`mean` and :attr:`std` don't need to match, but the + total number of elements in each tensor need to be the same. + + .. note:: When the shapes do not match, the shape of :attr:`mean` + is used as the shape for the returned output tensor + + .. note:: When :attr:`std` is a CUDA tensor, this function synchronizes + its device with the CPU. + + Args: + mean (Tensor): the tensor of per-element means + std (Tensor): the tensor of per-element standard deviations + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.normal(mean=torch.arange(1., 11.), std=torch.arange(1, 0, -0.1)) + tensor([ 1.0425, 3.5672, 2.7969, 4.2925, 4.7229, 6.2134, + 8.0505, 8.1408, 9.0563, 10.0566]) + + .. function:: normal(mean=0.0, std, *, out=None) -> Tensor + :noindex: + + Similar to the function above, but the means are shared among all drawn + elements. + + Args: + mean (float, optional): the mean for all distributions + std (Tensor): the tensor of per-element standard deviations + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.normal(mean=0.5, std=torch.arange(1., 6.)) + tensor([-1.2793, -1.0732, -2.0687, 5.1177, -1.2303]) + + .. function:: normal(mean, std=1.0, *, out=None) -> Tensor + :noindex: + + Similar to the function above, but the standard deviations are shared among + all drawn elements. + + Args: + mean (Tensor): the tensor of per-element means + std (float, optional): the standard deviation for all distributions + + Keyword args: + out (Tensor, optional): the output tensor + + Example:: + + >>> torch.normal(mean=torch.arange(1., 6.)) + tensor([ 1.1552, 2.6148, 2.6535, 5.8318, 4.2361]) + + .. function:: normal(mean, std, size, *, out=None) -> Tensor + :noindex: + + Similar to the function above, but the means and standard deviations are shared + among all drawn elements. The resulting tensor has size given by :attr:`size`. + + Args: + mean (float): the mean for all distributions + std (float): the standard deviation for all distributions + size (int...): a sequence of integers defining the shape of the output tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.normal(2, 3, size=(1, 4)) + tensor([[-1.3987, -1.9544, 3.6048, 0.7909]]) + """ + +@overload +def not_equal( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + not_equal(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.ne`. + """ + +@overload +def not_equal( + input: Tensor, + other: Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + not_equal(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.ne`. + """ + +@overload +def nuclear_norm( + input: Tensor, + dim: _int | _size, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: ... +@overload +def nuclear_norm( + input: Tensor, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: ... +def numel(self: Tensor) -> _int: + r""" + numel(input: Tensor) -> int + + Returns the total number of elements in the :attr:`input` tensor. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> a = torch.randn(1, 2, 3, 4, 5) + >>> torch.numel(a) + 120 + >>> a = torch.zeros(4,4) + >>> torch.numel(a) + 16 + """ + +@overload +def ones( + size: Sequence[_int | SymInt], + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + ones(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with the scalar value `1`, with the shape defined + by the variable argument :attr:`size`. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.ones(2, 3) + tensor([[ 1., 1., 1.], + [ 1., 1., 1.]]) + + >>> torch.ones(5) + tensor([ 1., 1., 1., 1., 1.]) + """ + +@overload +def ones( + *size: _int | SymInt, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + ones(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with the scalar value `1`, with the shape defined + by the variable argument :attr:`size`. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.ones(2, 3) + tensor([[ 1., 1., 1.], + [ 1., 1., 1.]]) + + >>> torch.ones(5) + tensor([ 1., 1., 1., 1., 1.]) + """ + +@overload +def ones( + size: _size, + *, + names: Sequence[str | EllipsisType | None] | None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + ones(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with the scalar value `1`, with the shape defined + by the variable argument :attr:`size`. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.ones(2, 3) + tensor([[ 1., 1., 1.], + [ 1., 1., 1.]]) + + >>> torch.ones(5) + tensor([ 1., 1., 1., 1., 1.]) + """ + +@overload +def ones( + *size: _int, + names: Sequence[str | EllipsisType | None] | None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + ones(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with the scalar value `1`, with the shape defined + by the variable argument :attr:`size`. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.ones(2, 3) + tensor([[ 1., 1., 1.], + [ 1., 1., 1.]]) + + >>> torch.ones(5) + tensor([ 1., 1., 1., 1., 1.]) + """ + +def ones_like( + input: Tensor, + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + ones_like(input, *, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor filled with the scalar value `1`, with the same size as + :attr:`input`. ``torch.ones_like(input)`` is equivalent to + ``torch.ones(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``. + + .. warning:: + As of 0.4, this function does not support an :attr:`out` keyword. As an alternative, + the old ``torch.ones_like(input, out=output)`` is equivalent to + ``torch.ones(input.size(), out=output)``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + + Keyword arguments: + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + + Example:: + + >>> input = torch.empty(2, 3) + >>> torch.ones_like(input) + tensor([[ 1., 1., 1.], + [ 1., 1., 1.]]) + """ + +def orgqr( + input: Tensor, + input2: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + orgqr(input, tau) -> Tensor + + Alias for :func:`torch.linalg.householder_product`. + """ + +def ormqr( + input: Tensor, + input2: Tensor, + input3: Tensor, + left: _bool = True, + transpose: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + ormqr(input, tau, other, left=True, transpose=False, *, out=None) -> Tensor + + Computes the matrix-matrix multiplication of a product of Householder matrices with a general matrix. + + Multiplies a :math:`m \times n` matrix `C` (given by :attr:`other`) with a matrix `Q`, + where `Q` is represented using Householder reflectors `(input, tau)`. + See `Representation of Orthogonal or Unitary Matrices`_ for further details. + + If :attr:`left` is `True` then `op(Q)` times `C` is computed, otherwise the result is `C` times `op(Q)`. + When :attr:`left` is `True`, the implicit matrix `Q` has size :math:`m \times m`. + It has size :math:`n \times n` otherwise. + If :attr:`transpose` is `True` then `op` is the conjugate transpose operation, otherwise it's a no-op. + + Supports inputs of float, double, cfloat and cdouble dtypes. + Also supports batched inputs, and, if the input is batched, the output is batched with the same dimensions. + + .. seealso:: + :func:`torch.geqrf` can be used to form the Householder representation `(input, tau)` of matrix `Q` + from the QR decomposition. + + .. note:: + This function supports backward but it is only fast when ``(input, tau)`` do not require gradients + and/or ``tau.size(-1)`` is very small. + `` + + Args: + input (Tensor): tensor of shape `(*, mn, k)` where `*` is zero or more batch dimensions + and `mn` equals to `m` or `n` depending on the :attr:`left`. + tau (Tensor): tensor of shape `(*, min(mn, k))` where `*` is zero or more batch dimensions. + other (Tensor): tensor of shape `(*, m, n)` where `*` is zero or more batch dimensions. + left (bool): controls the order of multiplication. + transpose (bool): controls whether the matrix `Q` is conjugate transposed or not. + + Keyword args: + out (Tensor, optional): the output Tensor. Ignored if `None`. Default: `None`. + + .. _Representation of Orthogonal or Unitary Matrices: + https://www.netlib.org/lapack/lug/node128.html + """ + +def outer( + input: Tensor, + vec2: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + outer(input, vec2, *, out=None) -> Tensor + + Outer product of :attr:`input` and :attr:`vec2`. + If :attr:`input` is a vector of size :math:`n` and :attr:`vec2` is a vector of + size :math:`m`, then :attr:`out` must be a matrix of size :math:`(n \times m)`. + + .. note:: This function does not :ref:`broadcast `. + + Args: + input (Tensor): 1-D input vector + vec2 (Tensor): 1-D input vector + + Keyword args: + out (Tensor, optional): optional output matrix + + Example:: + + >>> v1 = torch.arange(1., 5.) + >>> v2 = torch.arange(1., 4.) + >>> torch.outer(v1, v2) + tensor([[ 1., 2., 3.], + [ 2., 4., 6.], + [ 3., 6., 9.], + [ 4., 8., 12.]]) + """ + +def pairwise_distance( + x1: Tensor, + x2: Tensor, + p: _float = 2, + eps: _float = 1e-06, + keepdim: _bool = False, +) -> Tensor: ... +def pdist(input: Tensor, p: _float = 2) -> Tensor: ... +def permute(input: Tensor, dims: _size) -> Tensor: + r""" + permute(input, dims) -> Tensor + + Returns a view of the original tensor :attr:`input` with its dimensions permuted. + + Args: + input (Tensor): the input tensor. + dims (tuple of int): The desired ordering of dimensions + + Example: + >>> x = torch.randn(2, 3, 5) + >>> x.size() + torch.Size([2, 3, 5]) + >>> torch.permute(x, (2, 0, 1)).size() + torch.Size([5, 2, 3]) + """ + +def permute_copy( + input: Tensor, + dims: _size, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.permute`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def pinverse(input: Tensor, rcond: _float = 1e-15) -> Tensor: + r""" + pinverse(input, rcond=1e-15) -> Tensor + + Alias for :func:`torch.linalg.pinv` + """ + +def pixel_shuffle(input: Tensor, upscale_factor: _int) -> Tensor: ... +def pixel_unshuffle(input: Tensor, downscale_factor: _int) -> Tensor: ... +def poisson(input: Tensor, generator: Generator | None = None) -> Tensor: + r""" + poisson(input, generator=None) -> Tensor + + Returns a tensor of the same size as :attr:`input` with each element + sampled from a Poisson distribution with rate parameter given by the corresponding + element in :attr:`input` i.e., + + .. math:: + \text{out}_i \sim \text{Poisson}(\text{input}_i) + + :attr:`input` must be non-negative. + + Args: + input (Tensor): the input tensor containing the rates of the Poisson distribution + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + + Example:: + + >>> rates = torch.rand(4, 4) * 5 # rate parameter between 0 and 5 + >>> torch.poisson(rates) + tensor([[9., 1., 3., 5.], + [8., 6., 6., 0.], + [0., 4., 5., 3.], + [2., 1., 4., 2.]]) + """ + +def poisson_nll_loss( + input: Tensor, + target: Tensor, + log_input: _bool, + full: _bool, + eps: _float, + reduction: _int, +) -> Tensor: ... +def polar( + abs: Tensor, + angle: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + polar(abs, angle, *, out=None) -> Tensor + + Constructs a complex tensor whose elements are Cartesian coordinates + corresponding to the polar coordinates with absolute value :attr:`abs` and angle + :attr:`angle`. + + .. math:: + \text{out} = \text{abs} \cdot \cos(\text{angle}) + \text{abs} \cdot \sin(\text{angle}) \cdot j + + .. note:: + `torch.polar` is similar to + `std::polar `_ + and does not compute the polar decomposition + of a complex tensor like Python's `cmath.polar` and SciPy's `linalg.polar` do. + The behavior of this function is undefined if `abs` is negative or NaN, or if `angle` is + infinite. + + + Args: + abs (Tensor): The absolute value the complex tensor. Must be float or double. + angle (Tensor): The angle of the complex tensor. Must be same dtype as + :attr:`abs`. + + Keyword args: + out (Tensor): If the inputs are ``torch.float32``, must be + ``torch.complex64``. If the inputs are ``torch.float64``, must be + ``torch.complex128``. + + Example:: + + >>> import numpy as np + >>> abs = torch.tensor([1, 2], dtype=torch.float64) + >>> angle = torch.tensor([np.pi / 2, 5 * np.pi / 4], dtype=torch.float64) + >>> z = torch.polar(abs, angle) + >>> z + tensor([(0.0000+1.0000j), (-1.4142-1.4142j)], dtype=torch.complex128) + """ + +def polygamma( + n: _int, + input: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + polygamma(n, input, *, out=None) -> Tensor + + Alias for :func:`torch.special.polygamma`. + """ + +def positive(input: Tensor) -> Tensor: + r""" + positive(input) -> Tensor + + Returns :attr:`input`. + Throws a runtime error if :attr:`input` is a bool tensor. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> t = torch.randn(5) + >>> t + tensor([ 0.0090, -0.2262, -0.0682, -0.2866, 0.3940]) + >>> torch.positive(t) + tensor([ 0.0090, -0.2262, -0.0682, -0.2866, 0.3940]) + """ + +@overload +def pow( + input: Tensor, + exponent: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + pow(input, exponent, *, out=None) -> Tensor + + Takes the power of each element in :attr:`input` with :attr:`exponent` and + returns a tensor with the result. + + :attr:`exponent` can be either a single ``float`` number or a `Tensor` + with the same number of elements as :attr:`input`. + + When :attr:`exponent` is a scalar value, the operation applied is: + + .. math:: + \text{out}_i = x_i ^ \text{exponent} + + When :attr:`exponent` is a tensor, the operation applied is: + + .. math:: + \text{out}_i = x_i ^ {\text{exponent}_i} + + When :attr:`exponent` is a tensor, the shapes of :attr:`input` + and :attr:`exponent` must be :ref:`broadcastable `. + + Args: + input (Tensor): the input tensor. + exponent (float or tensor): the exponent value + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.4331, 1.2475, 0.6834, -0.2791]) + >>> torch.pow(a, 2) + tensor([ 0.1875, 1.5561, 0.4670, 0.0779]) + >>> exp = torch.arange(1., 5.) + + >>> a = torch.arange(1., 5.) + >>> a + tensor([ 1., 2., 3., 4.]) + >>> exp + tensor([ 1., 2., 3., 4.]) + >>> torch.pow(a, exp) + tensor([ 1., 4., 27., 256.]) + + .. function:: pow(self, exponent, *, out=None) -> Tensor + :noindex: + + :attr:`self` is a scalar ``float`` value, and :attr:`exponent` is a tensor. + The returned tensor :attr:`out` is of the same shape as :attr:`exponent` + + The operation applied is: + + .. math:: + \text{out}_i = \text{self} ^ {\text{exponent}_i} + + Args: + self (float): the scalar base value for the power operation + exponent (Tensor): the exponent tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> exp = torch.arange(1., 5.) + >>> base = 2 + >>> torch.pow(base, exp) + tensor([ 2., 4., 8., 16.]) + """ + +@overload +def pow( + self: Number | _complex, + exponent: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + pow(input, exponent, *, out=None) -> Tensor + + Takes the power of each element in :attr:`input` with :attr:`exponent` and + returns a tensor with the result. + + :attr:`exponent` can be either a single ``float`` number or a `Tensor` + with the same number of elements as :attr:`input`. + + When :attr:`exponent` is a scalar value, the operation applied is: + + .. math:: + \text{out}_i = x_i ^ \text{exponent} + + When :attr:`exponent` is a tensor, the operation applied is: + + .. math:: + \text{out}_i = x_i ^ {\text{exponent}_i} + + When :attr:`exponent` is a tensor, the shapes of :attr:`input` + and :attr:`exponent` must be :ref:`broadcastable `. + + Args: + input (Tensor): the input tensor. + exponent (float or tensor): the exponent value + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.4331, 1.2475, 0.6834, -0.2791]) + >>> torch.pow(a, 2) + tensor([ 0.1875, 1.5561, 0.4670, 0.0779]) + >>> exp = torch.arange(1., 5.) + + >>> a = torch.arange(1., 5.) + >>> a + tensor([ 1., 2., 3., 4.]) + >>> exp + tensor([ 1., 2., 3., 4.]) + >>> torch.pow(a, exp) + tensor([ 1., 4., 27., 256.]) + + .. function:: pow(self, exponent, *, out=None) -> Tensor + :noindex: + + :attr:`self` is a scalar ``float`` value, and :attr:`exponent` is a tensor. + The returned tensor :attr:`out` is of the same shape as :attr:`exponent` + + The operation applied is: + + .. math:: + \text{out}_i = \text{self} ^ {\text{exponent}_i} + + Args: + self (float): the scalar base value for the power operation + exponent (Tensor): the exponent tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> exp = torch.arange(1., 5.) + >>> base = 2 + >>> torch.pow(base, exp) + tensor([ 2., 4., 8., 16.]) + """ + +@overload +def pow( + input: Tensor, + exponent: Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + pow(input, exponent, *, out=None) -> Tensor + + Takes the power of each element in :attr:`input` with :attr:`exponent` and + returns a tensor with the result. + + :attr:`exponent` can be either a single ``float`` number or a `Tensor` + with the same number of elements as :attr:`input`. + + When :attr:`exponent` is a scalar value, the operation applied is: + + .. math:: + \text{out}_i = x_i ^ \text{exponent} + + When :attr:`exponent` is a tensor, the operation applied is: + + .. math:: + \text{out}_i = x_i ^ {\text{exponent}_i} + + When :attr:`exponent` is a tensor, the shapes of :attr:`input` + and :attr:`exponent` must be :ref:`broadcastable `. + + Args: + input (Tensor): the input tensor. + exponent (float or tensor): the exponent value + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.4331, 1.2475, 0.6834, -0.2791]) + >>> torch.pow(a, 2) + tensor([ 0.1875, 1.5561, 0.4670, 0.0779]) + >>> exp = torch.arange(1., 5.) + + >>> a = torch.arange(1., 5.) + >>> a + tensor([ 1., 2., 3., 4.]) + >>> exp + tensor([ 1., 2., 3., 4.]) + >>> torch.pow(a, exp) + tensor([ 1., 4., 27., 256.]) + + .. function:: pow(self, exponent, *, out=None) -> Tensor + :noindex: + + :attr:`self` is a scalar ``float`` value, and :attr:`exponent` is a tensor. + The returned tensor :attr:`out` is of the same shape as :attr:`exponent` + + The operation applied is: + + .. math:: + \text{out}_i = \text{self} ^ {\text{exponent}_i} + + Args: + self (float): the scalar base value for the power operation + exponent (Tensor): the exponent tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> exp = torch.arange(1., 5.) + >>> base = 2 + >>> torch.pow(base, exp) + tensor([ 2., 4., 8., 16.]) + """ + +def prelu(input: Tensor, weight: Tensor) -> Tensor: ... +@overload +def prod(input: Tensor, *, dtype: _dtype | None = None) -> Tensor: + r""" + prod(input: Tensor, *, dtype: Optional[_dtype]) -> Tensor + + Returns the product of all elements in the :attr:`input` tensor. + + Args: + input (Tensor): the input tensor. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[-0.8020, 0.5428, -1.5854]]) + >>> torch.prod(a) + tensor(0.6902) + + .. function:: prod(input, dim, keepdim=False, *, dtype=None) -> Tensor + :noindex: + + Returns the product of each row of the :attr:`input` tensor in the given + dimension :attr:`dim`. + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in + the output tensor having 1 fewer dimension than :attr:`input`. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + + Example:: + + >>> a = torch.randn(4, 2) + >>> a + tensor([[ 0.5261, -0.3837], + [ 1.1857, -0.2498], + [-1.1646, 0.0705], + [ 1.1131, -1.0629]]) + >>> torch.prod(a, 1) + tensor([-0.2018, -0.2962, -0.0821, -1.1831]) + """ + +@overload +def prod( + input: Tensor, + dim: _int, + keepdim: _bool = False, + *, + dtype: _dtype | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + prod(input: Tensor, *, dtype: Optional[_dtype]) -> Tensor + + Returns the product of all elements in the :attr:`input` tensor. + + Args: + input (Tensor): the input tensor. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[-0.8020, 0.5428, -1.5854]]) + >>> torch.prod(a) + tensor(0.6902) + + .. function:: prod(input, dim, keepdim=False, *, dtype=None) -> Tensor + :noindex: + + Returns the product of each row of the :attr:`input` tensor in the given + dimension :attr:`dim`. + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in + the output tensor having 1 fewer dimension than :attr:`input`. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + + Example:: + + >>> a = torch.randn(4, 2) + >>> a + tensor([[ 0.5261, -0.3837], + [ 1.1857, -0.2498], + [-1.1646, 0.0705], + [ 1.1131, -1.0629]]) + >>> torch.prod(a, 1) + tensor([-0.2018, -0.2962, -0.0821, -1.1831]) + """ + +@overload +def prod( + input: Tensor, + dim: str | EllipsisType | None, + keepdim: _bool = False, + *, + dtype: _dtype | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + prod(input: Tensor, *, dtype: Optional[_dtype]) -> Tensor + + Returns the product of all elements in the :attr:`input` tensor. + + Args: + input (Tensor): the input tensor. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[-0.8020, 0.5428, -1.5854]]) + >>> torch.prod(a) + tensor(0.6902) + + .. function:: prod(input, dim, keepdim=False, *, dtype=None) -> Tensor + :noindex: + + Returns the product of each row of the :attr:`input` tensor in the given + dimension :attr:`dim`. + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in + the output tensor having 1 fewer dimension than :attr:`input`. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + + Example:: + + >>> a = torch.randn(4, 2) + >>> a + tensor([[ 0.5261, -0.3837], + [ 1.1857, -0.2498], + [-1.1646, 0.0705], + [ 1.1131, -1.0629]]) + >>> torch.prod(a, 1) + tensor([-0.2018, -0.2962, -0.0821, -1.1831]) + """ + +def promote_types(type1: _dtype, type2: _dtype) -> _dtype: + r""" + promote_types(type1, type2) -> dtype + + Returns the :class:`torch.dtype` with the smallest size and scalar kind that is + not smaller nor of lower kind than either `type1` or `type2`. See type promotion + :ref:`documentation ` for more information on the type + promotion logic. + + Args: + type1 (:class:`torch.dtype`) + type2 (:class:`torch.dtype`) + + Example:: + + >>> torch.promote_types(torch.int32, torch.float32) + torch.float32 + >>> torch.promote_types(torch.uint8, torch.long) + torch.long + """ + +def put( + input: Tensor, + index: Tensor, + source: Tensor, + accumulate: _bool = False, +) -> Tensor: ... +def q_per_channel_axis(input: Tensor) -> _int: ... +def q_per_channel_scales(input: Tensor) -> Tensor: ... +def q_per_channel_zero_points(input: Tensor) -> Tensor: ... +def q_scale(input: Tensor) -> _float: ... +def q_zero_point(input: Tensor) -> _int: ... +def qr( + input: Tensor, + some: _bool = True, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.qr: + r""" + qr(input: Tensor, some: bool = True, *, out: Union[Tensor, Tuple[Tensor, ...], List[Tensor], None]) -> (Tensor, Tensor) + + Computes the QR decomposition of a matrix or a batch of matrices :attr:`input`, + and returns a namedtuple (Q, R) of tensors such that :math:`\text{input} = Q R` + with :math:`Q` being an orthogonal matrix or batch of orthogonal matrices and + :math:`R` being an upper triangular matrix or batch of upper triangular matrices. + + If :attr:`some` is ``True``, then this function returns the thin (reduced) QR factorization. + Otherwise, if :attr:`some` is ``False``, this function returns the complete QR factorization. + + .. warning:: + + :func:`torch.qr` is deprecated in favor of :func:`torch.linalg.qr` + and will be removed in a future PyTorch release. The boolean parameter :attr:`some` has been + replaced with a string parameter :attr:`mode`. + + ``Q, R = torch.qr(A)`` should be replaced with + + .. code:: python + + Q, R = torch.linalg.qr(A) + + ``Q, R = torch.qr(A, some=False)`` should be replaced with + + .. code:: python + + Q, R = torch.linalg.qr(A, mode="complete") + + .. warning:: + If you plan to backpropagate through QR, note that the current backward implementation + is only well-defined when the first :math:`\min(input.size(-1), input.size(-2))` + columns of :attr:`input` are linearly independent. + This behavior will probably change once QR supports pivoting. + + .. note:: This function uses LAPACK for CPU inputs and MAGMA for CUDA inputs, + and may produce different (valid) decompositions on different device types + or different platforms. + + Args: + input (Tensor): the input tensor of size :math:`(*, m, n)` where `*` is zero or more + batch dimensions consisting of matrices of dimension :math:`m \times n`. + some (bool, optional): Set to ``True`` for reduced QR decomposition and ``False`` for + complete QR decomposition. If `k = min(m, n)` then: + + * ``some=True`` : returns `(Q, R)` with dimensions (m, k), (k, n) (default) + + * ``'some=False'``: returns `(Q, R)` with dimensions (m, m), (m, n) + + Keyword args: + out (tuple, optional): tuple of `Q` and `R` tensors. + The dimensions of `Q` and `R` are detailed in the description of :attr:`some` above. + + Example:: + + >>> a = torch.tensor([[12., -51, 4], [6, 167, -68], [-4, 24, -41]]) + >>> q, r = torch.qr(a) + >>> q + tensor([[-0.8571, 0.3943, 0.3314], + [-0.4286, -0.9029, -0.0343], + [ 0.2857, -0.1714, 0.9429]]) + >>> r + tensor([[ -14.0000, -21.0000, 14.0000], + [ 0.0000, -175.0000, 70.0000], + [ 0.0000, 0.0000, -35.0000]]) + >>> torch.mm(q, r).round() + tensor([[ 12., -51., 4.], + [ 6., 167., -68.], + [ -4., 24., -41.]]) + >>> torch.mm(q.t(), q).round() + tensor([[ 1., 0., 0.], + [ 0., 1., -0.], + [ 0., -0., 1.]]) + >>> a = torch.randn(3, 4, 5) + >>> q, r = torch.qr(a, some=False) + >>> torch.allclose(torch.matmul(q, r), a) + True + >>> torch.allclose(torch.matmul(q.mT, q), torch.eye(5)) + True + """ + +@overload +def quantile( + input: Tensor, + q: Tensor, + dim: _int | None = None, + keepdim: _bool = False, + *, + interpolation: str = "linear", + out: Tensor | None = None, +) -> Tensor: + r""" + quantile(input, q, dim=None, keepdim=False, *, interpolation='linear', out=None) -> Tensor + + Computes the q-th quantiles of each row of the :attr:`input` tensor along the dimension :attr:`dim`. + + To compute the quantile, we map q in [0, 1] to the range of indices [0, n] to find the location + of the quantile in the sorted input. If the quantile lies between two data points ``a < b`` with + indices ``i`` and ``j`` in the sorted order, result is computed according to the given + :attr:`interpolation` method as follows: + + - ``linear``: ``a + (b - a) * fraction``, where ``fraction`` is the fractional part of the computed quantile index. + - ``lower``: ``a``. + - ``higher``: ``b``. + - ``nearest``: ``a`` or ``b``, whichever's index is closer to the computed quantile index (follows :func:`torch.round`). + - ``midpoint``: ``(a + b) / 2``. + + If :attr:`q` is a 1D tensor, the first dimension of the output represents the quantiles and has size + equal to the size of :attr:`q`, the remaining dimensions are what remains from the reduction. + + .. note:: + By default :attr:`dim` is ``None`` resulting in the :attr:`input` tensor being flattened before computation. + + Args: + input (Tensor): the input tensor. + q (float or Tensor): a scalar or 1D tensor of values in the range [0, 1]. + + dim (int, optional): the dimension to reduce. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword arguments: + interpolation (str, optional): interpolation method to use when the desired quantile lies between two data points. + Can be ``linear``, ``lower``, ``higher``, ``midpoint`` and ``nearest``. + Default is ``linear``. + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(2, 3) + >>> a + tensor([[ 0.0795, -1.2117, 0.9765], + [ 1.1707, 0.6706, 0.4884]]) + >>> q = torch.tensor([0.25, 0.5, 0.75]) + >>> torch.quantile(a, q, dim=1, keepdim=True) + tensor([[[-0.5661], + [ 0.5795]], + + [[ 0.0795], + [ 0.6706]], + + [[ 0.5280], + [ 0.9206]]]) + >>> torch.quantile(a, q, dim=1, keepdim=True).shape + torch.Size([3, 2, 1]) + >>> a = torch.arange(4.) + >>> a + tensor([0., 1., 2., 3.]) + >>> torch.quantile(a, 0.6, interpolation='linear') + tensor(1.8000) + >>> torch.quantile(a, 0.6, interpolation='lower') + tensor(1.) + >>> torch.quantile(a, 0.6, interpolation='higher') + tensor(2.) + >>> torch.quantile(a, 0.6, interpolation='midpoint') + tensor(1.5000) + >>> torch.quantile(a, 0.6, interpolation='nearest') + tensor(2.) + >>> torch.quantile(a, 0.4, interpolation='nearest') + tensor(1.) + """ + +@overload +def quantile( + input: Tensor, + q: _float, + dim: _int | None = None, + keepdim: _bool = False, + *, + interpolation: str = "linear", + out: Tensor | None = None, +) -> Tensor: + r""" + quantile(input, q, dim=None, keepdim=False, *, interpolation='linear', out=None) -> Tensor + + Computes the q-th quantiles of each row of the :attr:`input` tensor along the dimension :attr:`dim`. + + To compute the quantile, we map q in [0, 1] to the range of indices [0, n] to find the location + of the quantile in the sorted input. If the quantile lies between two data points ``a < b`` with + indices ``i`` and ``j`` in the sorted order, result is computed according to the given + :attr:`interpolation` method as follows: + + - ``linear``: ``a + (b - a) * fraction``, where ``fraction`` is the fractional part of the computed quantile index. + - ``lower``: ``a``. + - ``higher``: ``b``. + - ``nearest``: ``a`` or ``b``, whichever's index is closer to the computed quantile index (follows :func:`torch.round`). + - ``midpoint``: ``(a + b) / 2``. + + If :attr:`q` is a 1D tensor, the first dimension of the output represents the quantiles and has size + equal to the size of :attr:`q`, the remaining dimensions are what remains from the reduction. + + .. note:: + By default :attr:`dim` is ``None`` resulting in the :attr:`input` tensor being flattened before computation. + + Args: + input (Tensor): the input tensor. + q (float or Tensor): a scalar or 1D tensor of values in the range [0, 1]. + + dim (int, optional): the dimension to reduce. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword arguments: + interpolation (str, optional): interpolation method to use when the desired quantile lies between two data points. + Can be ``linear``, ``lower``, ``higher``, ``midpoint`` and ``nearest``. + Default is ``linear``. + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(2, 3) + >>> a + tensor([[ 0.0795, -1.2117, 0.9765], + [ 1.1707, 0.6706, 0.4884]]) + >>> q = torch.tensor([0.25, 0.5, 0.75]) + >>> torch.quantile(a, q, dim=1, keepdim=True) + tensor([[[-0.5661], + [ 0.5795]], + + [[ 0.0795], + [ 0.6706]], + + [[ 0.5280], + [ 0.9206]]]) + >>> torch.quantile(a, q, dim=1, keepdim=True).shape + torch.Size([3, 2, 1]) + >>> a = torch.arange(4.) + >>> a + tensor([0., 1., 2., 3.]) + >>> torch.quantile(a, 0.6, interpolation='linear') + tensor(1.8000) + >>> torch.quantile(a, 0.6, interpolation='lower') + tensor(1.) + >>> torch.quantile(a, 0.6, interpolation='higher') + tensor(2.) + >>> torch.quantile(a, 0.6, interpolation='midpoint') + tensor(1.5000) + >>> torch.quantile(a, 0.6, interpolation='nearest') + tensor(2.) + >>> torch.quantile(a, 0.4, interpolation='nearest') + tensor(1.) + """ + +def quantize_per_channel( + input: Tensor, + scales: Tensor, + zero_points: Tensor, + axis: _int, + dtype: _dtype, +) -> Tensor: + r""" + quantize_per_channel(input, scales, zero_points, axis, dtype) -> Tensor + + Converts a float tensor to a per-channel quantized tensor with given scales and zero points. + + Arguments: + input (Tensor): float tensor to quantize + scales (Tensor): float 1D tensor of scales to use, size should match ``input.size(axis)`` + zero_points (int): integer 1D tensor of offset to use, size should match ``input.size(axis)`` + axis (int): dimension on which apply per-channel quantization + dtype (:class:`torch.dtype`): the desired data type of returned tensor. + Has to be one of the quantized dtypes: ``torch.quint8``, ``torch.qint8``, ``torch.qint32`` + + Returns: + Tensor: A newly quantized tensor + + Example:: + + >>> x = torch.tensor([[-1.0, 0.0], [1.0, 2.0]]) + >>> torch.quantize_per_channel(x, torch.tensor([0.1, 0.01]), torch.tensor([10, 0]), 0, torch.quint8) + tensor([[-1., 0.], + [ 1., 2.]], size=(2, 2), dtype=torch.quint8, + quantization_scheme=torch.per_channel_affine, + scale=tensor([0.1000, 0.0100], dtype=torch.float64), + zero_point=tensor([10, 0]), axis=0) + >>> torch.quantize_per_channel(x, torch.tensor([0.1, 0.01]), torch.tensor([10, 0]), 0, torch.quint8).int_repr() + tensor([[ 0, 10], + [100, 200]], dtype=torch.uint8) + """ + +@overload +def quantize_per_tensor( + input: Tensor, + scale: Tensor, + zero_point: Tensor, + dtype: _dtype, +) -> Tensor: + r""" + quantize_per_tensor(input, scale, zero_point, dtype) -> Tensor + + Converts a float tensor to a quantized tensor with given scale and zero point. + + Arguments: + input (Tensor): float tensor or list of tensors to quantize + scale (float or Tensor): scale to apply in quantization formula + zero_point (int or Tensor): offset in integer value that maps to float zero + dtype (:class:`torch.dtype`): the desired data type of returned tensor. + Has to be one of the quantized dtypes: ``torch.quint8``, ``torch.qint8``, ``torch.qint32`` + + Returns: + Tensor: A newly quantized tensor or list of quantized tensors. + + Example:: + + >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), 0.1, 10, torch.quint8) + tensor([-1., 0., 1., 2.], size=(4,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.1, zero_point=10) + >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), 0.1, 10, torch.quint8).int_repr() + tensor([ 0, 10, 20, 30], dtype=torch.uint8) + >>> torch.quantize_per_tensor([torch.tensor([-1.0, 0.0]), torch.tensor([-2.0, 2.0])], + >>> torch.tensor([0.1, 0.2]), torch.tensor([10, 20]), torch.quint8) + (tensor([-1., 0.], size=(2,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.1, zero_point=10), + tensor([-2., 2.], size=(2,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.2, zero_point=20)) + >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), torch.tensor(0.1), torch.tensor(10), torch.quint8) + tensor([-1., 0., 1., 2.], size=(4,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.10, zero_point=10) + """ + +@overload +def quantize_per_tensor( + input: Tensor, + scale: _float, + zero_point: _int, + dtype: _dtype, +) -> Tensor: + r""" + quantize_per_tensor(input, scale, zero_point, dtype) -> Tensor + + Converts a float tensor to a quantized tensor with given scale and zero point. + + Arguments: + input (Tensor): float tensor or list of tensors to quantize + scale (float or Tensor): scale to apply in quantization formula + zero_point (int or Tensor): offset in integer value that maps to float zero + dtype (:class:`torch.dtype`): the desired data type of returned tensor. + Has to be one of the quantized dtypes: ``torch.quint8``, ``torch.qint8``, ``torch.qint32`` + + Returns: + Tensor: A newly quantized tensor or list of quantized tensors. + + Example:: + + >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), 0.1, 10, torch.quint8) + tensor([-1., 0., 1., 2.], size=(4,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.1, zero_point=10) + >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), 0.1, 10, torch.quint8).int_repr() + tensor([ 0, 10, 20, 30], dtype=torch.uint8) + >>> torch.quantize_per_tensor([torch.tensor([-1.0, 0.0]), torch.tensor([-2.0, 2.0])], + >>> torch.tensor([0.1, 0.2]), torch.tensor([10, 20]), torch.quint8) + (tensor([-1., 0.], size=(2,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.1, zero_point=10), + tensor([-2., 2.], size=(2,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.2, zero_point=20)) + >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), torch.tensor(0.1), torch.tensor(10), torch.quint8) + tensor([-1., 0., 1., 2.], size=(4,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.10, zero_point=10) + """ + +@overload +def quantize_per_tensor( + tensors: tuple[Tensor, ...] | list[Tensor] | None, + scales: Tensor, + zero_points: Tensor, + dtype: _dtype, +) -> tuple[Tensor, ...]: + r""" + quantize_per_tensor(input, scale, zero_point, dtype) -> Tensor + + Converts a float tensor to a quantized tensor with given scale and zero point. + + Arguments: + input (Tensor): float tensor or list of tensors to quantize + scale (float or Tensor): scale to apply in quantization formula + zero_point (int or Tensor): offset in integer value that maps to float zero + dtype (:class:`torch.dtype`): the desired data type of returned tensor. + Has to be one of the quantized dtypes: ``torch.quint8``, ``torch.qint8``, ``torch.qint32`` + + Returns: + Tensor: A newly quantized tensor or list of quantized tensors. + + Example:: + + >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), 0.1, 10, torch.quint8) + tensor([-1., 0., 1., 2.], size=(4,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.1, zero_point=10) + >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), 0.1, 10, torch.quint8).int_repr() + tensor([ 0, 10, 20, 30], dtype=torch.uint8) + >>> torch.quantize_per_tensor([torch.tensor([-1.0, 0.0]), torch.tensor([-2.0, 2.0])], + >>> torch.tensor([0.1, 0.2]), torch.tensor([10, 20]), torch.quint8) + (tensor([-1., 0.], size=(2,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.1, zero_point=10), + tensor([-2., 2.], size=(2,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.2, zero_point=20)) + >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), torch.tensor(0.1), torch.tensor(10), torch.quint8) + tensor([-1., 0., 1., 2.], size=(4,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.10, zero_point=10) + """ + +def quantize_per_tensor_dynamic( + input: Tensor, + dtype: _dtype, + reduce_range: _bool, +) -> Tensor: + r""" + quantize_per_tensor_dynamic(input, dtype, reduce_range) -> Tensor + + Converts a float tensor to a quantized tensor with scale and zero_point calculated + dynamically based on the input. + + Arguments: + input (Tensor): float tensor or list of tensors to quantize + dtype (:class:`torch.dtype`): the desired data type of returned tensor. + Has to be one of the quantized dtypes: ``torch.quint8``, ``torch.qint8`` + reduce_range (bool): a flag to indicate whether to reduce the range of quantized + data by 1 bit, it's required to avoid instruction overflow for some hardwares + + Returns: + Tensor: A newly (dynamically) quantized tensor + + Example:: + + >>> t = torch.quantize_per_tensor_dynamic(torch.tensor([-1.0, 0.0, 1.0, 2.0]), torch.quint8, False) + >>> print(t) + tensor([-1., 0., 1., 2.], size=(4,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.011764705882352941, + zero_point=85) + >>> t.int_repr() + tensor([ 0, 85, 170, 255], dtype=torch.uint8) + """ + +def quantized_batch_norm( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + mean: Tensor, + var: Tensor, + eps: _float, + output_scale: _float, + output_zero_point: _int, +) -> Tensor: + r""" + quantized_batch_norm(input, weight=None, bias=None, mean, var, eps, output_scale, output_zero_point) -> Tensor + + Applies batch normalization on a 4D (NCHW) quantized tensor. + + .. math:: + + y = \frac{x - \mathrm{E}[x]}{\sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta + + Arguments: + input (Tensor): quantized tensor + weight (Tensor): float tensor that corresponds to the gamma, size C + bias (Tensor): float tensor that corresponds to the beta, size C + mean (Tensor): float mean value in batch normalization, size C + var (Tensor): float tensor for variance, size C + eps (float): a value added to the denominator for numerical stability. + output_scale (float): output quantized tensor scale + output_zero_point (int): output quantized tensor zero_point + + Returns: + Tensor: A quantized tensor with batch normalization applied. + + Example:: + + >>> qx = torch.quantize_per_tensor(torch.rand(2, 2, 2, 2), 1.5, 3, torch.quint8) + >>> torch.quantized_batch_norm(qx, torch.ones(2), torch.zeros(2), torch.rand(2), torch.rand(2), 0.00001, 0.2, 2) + tensor([[[[-0.2000, -0.2000], + [ 1.6000, -0.2000]], + + [[-0.4000, -0.4000], + [-0.4000, 0.6000]]], + + + [[[-0.2000, -0.2000], + [-0.2000, -0.2000]], + + [[ 0.6000, -0.4000], + [ 0.6000, -0.4000]]]], size=(2, 2, 2, 2), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.2, zero_point=2) + """ + +def quantized_gru_cell( + input: Tensor, + hx: Tensor, + w_ih: Tensor, + w_hh: Tensor, + b_ih: Tensor, + b_hh: Tensor, + packed_ih: Tensor, + packed_hh: Tensor, + col_offsets_ih: Tensor, + col_offsets_hh: Tensor, + scale_ih: Number | _complex, + scale_hh: Number | _complex, + zero_point_ih: Number | _complex, + zero_point_hh: Number | _complex, +) -> Tensor: ... +def quantized_lstm_cell( + input: Tensor, + hx: tuple[Tensor, ...] | list[Tensor] | None, + w_ih: Tensor, + w_hh: Tensor, + b_ih: Tensor, + b_hh: Tensor, + packed_ih: Tensor, + packed_hh: Tensor, + col_offsets_ih: Tensor, + col_offsets_hh: Tensor, + scale_ih: Number | _complex, + scale_hh: Number | _complex, + zero_point_ih: Number | _complex, + zero_point_hh: Number | _complex, +) -> tuple[Tensor, Tensor]: ... +def quantized_max_pool1d( + input: Tensor, + kernel_size: _int | _size, + stride: _int | _size = (), + padding: _int | _size = 0, + dilation: _int | _size = 1, + ceil_mode: _bool = False, +) -> Tensor: + r""" + quantized_max_pool1d(input, kernel_size, stride=[], padding=0, dilation=1, ceil_mode=False) -> Tensor + + Applies a 1D max pooling over an input quantized tensor composed of several input planes. + + Arguments: + input (Tensor): quantized tensor + kernel_size (list of int): the size of the sliding window + stride (``list of int``, optional): the stride of the sliding window + padding (``list of int``, optional): padding to be added on both sides, must be >= 0 and <= kernel_size / 2 + dilation (``list of int``, optional): The stride between elements within a sliding window, must be > 0. Default 1 + ceil_mode (bool, optional): If True, will use ceil instead of floor to compute the output shape. + Defaults to False. + + + Returns: + Tensor: A quantized tensor with max_pool1d applied. + + Example:: + + >>> qx = torch.quantize_per_tensor(torch.rand(2, 2), 1.5, 3, torch.quint8) + >>> torch.quantized_max_pool1d(qx, [2]) + tensor([[0.0000], + [1.5000]], size=(2, 1), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=1.5, zero_point=3) + """ + +def quantized_max_pool2d( + input: Tensor, + kernel_size: _int | _size, + stride: _int | _size = (), + padding: _int | _size = 0, + dilation: _int | _size = 1, + ceil_mode: _bool = False, +) -> Tensor: + r""" + quantized_max_pool2d(input, kernel_size, stride=[], padding=0, dilation=1, ceil_mode=False) -> Tensor + + Applies a 2D max pooling over an input quantized tensor composed of several input planes. + + Arguments: + input (Tensor): quantized tensor + kernel_size (``list of int``): the size of the sliding window + stride (``list of int``, optional): the stride of the sliding window + padding (``list of int``, optional): padding to be added on both sides, must be >= 0 and <= kernel_size / 2 + dilation (``list of int``, optional): The stride between elements within a sliding window, must be > 0. Default 1 + ceil_mode (bool, optional): If True, will use ceil instead of floor to compute the output shape. + Defaults to False. + + + Returns: + Tensor: A quantized tensor with max_pool2d applied. + + Example:: + + >>> qx = torch.quantize_per_tensor(torch.rand(2, 2, 2, 2), 1.5, 3, torch.quint8) + >>> torch.quantized_max_pool2d(qx, [2,2]) + tensor([[[[1.5000]], + + [[1.5000]]], + + + [[[0.0000]], + + [[0.0000]]]], size=(2, 2, 1, 1), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=1.5, zero_point=3) + """ + +def quantized_max_pool3d( + input: Tensor, + kernel_size: _int | _size, + stride: _int | _size = (), + padding: _int | _size = 0, + dilation: _int | _size = 1, + ceil_mode: _bool = False, +) -> Tensor: ... +def quantized_rnn_relu_cell( + input: Tensor, + hx: Tensor, + w_ih: Tensor, + w_hh: Tensor, + b_ih: Tensor, + b_hh: Tensor, + packed_ih: Tensor, + packed_hh: Tensor, + col_offsets_ih: Tensor, + col_offsets_hh: Tensor, + scale_ih: Number | _complex, + scale_hh: Number | _complex, + zero_point_ih: Number | _complex, + zero_point_hh: Number | _complex, +) -> Tensor: ... +def quantized_rnn_tanh_cell( + input: Tensor, + hx: Tensor, + w_ih: Tensor, + w_hh: Tensor, + b_ih: Tensor, + b_hh: Tensor, + packed_ih: Tensor, + packed_hh: Tensor, + col_offsets_ih: Tensor, + col_offsets_hh: Tensor, + scale_ih: Number | _complex, + scale_hh: Number | _complex, + zero_point_ih: Number | _complex, + zero_point_hh: Number | _complex, +) -> Tensor: ... +def rad2deg(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + rad2deg(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Returns a new tensor with each of the elements of :attr:`input` + converted from angles in radians to degrees. + + Args: + input (Tensor): the input tensor. + + Keyword arguments: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([[3.142, -3.142], [6.283, -6.283], [1.570, -1.570]]) + >>> torch.rad2deg(a) + tensor([[ 180.0233, -180.0233], + [ 359.9894, -359.9894], + [ 89.9544, -89.9544]]) + """ + +def rad2deg_(input: Tensor) -> Tensor: ... +@overload +def rand( + size: Sequence[_int | SymInt], + *, + generator: Generator | None, + names: Sequence[str | EllipsisType | None] | None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + rand(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + Returns a tensor filled with random numbers from a uniform distribution + on the interval :math:`[0, 1)` + + The shape of the tensor is defined by the variable argument :attr:`size`. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.rand(4) + tensor([ 0.5204, 0.2503, 0.3525, 0.5673]) + >>> torch.rand(2, 3) + tensor([[ 0.8237, 0.5781, 0.6879], + [ 0.3816, 0.7249, 0.0998]]) + """ + +@overload +def rand( + *size: _int | SymInt, + generator: Generator | None, + names: Sequence[str | EllipsisType | None] | None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + rand(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + Returns a tensor filled with random numbers from a uniform distribution + on the interval :math:`[0, 1)` + + The shape of the tensor is defined by the variable argument :attr:`size`. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.rand(4) + tensor([ 0.5204, 0.2503, 0.3525, 0.5673]) + >>> torch.rand(2, 3) + tensor([[ 0.8237, 0.5781, 0.6879], + [ 0.3816, 0.7249, 0.0998]]) + """ + +@overload +def rand( + size: Sequence[_int | SymInt], + *, + generator: Generator | None, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + rand(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + Returns a tensor filled with random numbers from a uniform distribution + on the interval :math:`[0, 1)` + + The shape of the tensor is defined by the variable argument :attr:`size`. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.rand(4) + tensor([ 0.5204, 0.2503, 0.3525, 0.5673]) + >>> torch.rand(2, 3) + tensor([[ 0.8237, 0.5781, 0.6879], + [ 0.3816, 0.7249, 0.0998]]) + """ + +@overload +def rand( + *size: _int | SymInt, + generator: Generator | None, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + rand(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + Returns a tensor filled with random numbers from a uniform distribution + on the interval :math:`[0, 1)` + + The shape of the tensor is defined by the variable argument :attr:`size`. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.rand(4) + tensor([ 0.5204, 0.2503, 0.3525, 0.5673]) + >>> torch.rand(2, 3) + tensor([[ 0.8237, 0.5781, 0.6879], + [ 0.3816, 0.7249, 0.0998]]) + """ + +@overload +def rand( + size: Sequence[_int | SymInt], + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + rand(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + Returns a tensor filled with random numbers from a uniform distribution + on the interval :math:`[0, 1)` + + The shape of the tensor is defined by the variable argument :attr:`size`. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.rand(4) + tensor([ 0.5204, 0.2503, 0.3525, 0.5673]) + >>> torch.rand(2, 3) + tensor([[ 0.8237, 0.5781, 0.6879], + [ 0.3816, 0.7249, 0.0998]]) + """ + +@overload +def rand( + *size: _int | SymInt, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + rand(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + Returns a tensor filled with random numbers from a uniform distribution + on the interval :math:`[0, 1)` + + The shape of the tensor is defined by the variable argument :attr:`size`. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.rand(4) + tensor([ 0.5204, 0.2503, 0.3525, 0.5673]) + >>> torch.rand(2, 3) + tensor([[ 0.8237, 0.5781, 0.6879], + [ 0.3816, 0.7249, 0.0998]]) + """ + +@overload +def rand( + size: Sequence[_int | SymInt], + *, + names: Sequence[str | EllipsisType | None] | None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + rand(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + Returns a tensor filled with random numbers from a uniform distribution + on the interval :math:`[0, 1)` + + The shape of the tensor is defined by the variable argument :attr:`size`. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.rand(4) + tensor([ 0.5204, 0.2503, 0.3525, 0.5673]) + >>> torch.rand(2, 3) + tensor([[ 0.8237, 0.5781, 0.6879], + [ 0.3816, 0.7249, 0.0998]]) + """ + +@overload +def rand( + *size: _int | SymInt, + names: Sequence[str | EllipsisType | None] | None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + rand(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + Returns a tensor filled with random numbers from a uniform distribution + on the interval :math:`[0, 1)` + + The shape of the tensor is defined by the variable argument :attr:`size`. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.rand(4) + tensor([ 0.5204, 0.2503, 0.3525, 0.5673]) + >>> torch.rand(2, 3) + tensor([[ 0.8237, 0.5781, 0.6879], + [ 0.3816, 0.7249, 0.0998]]) + """ + +@overload +def rand_like( + input: Tensor, + *, + generator: Generator | None, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + rand_like(input, *, generator=None, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same size as :attr:`input` that is filled with + random numbers from a uniform distribution on the interval :math:`[0, 1)`. + ``torch.rand_like(input)`` is equivalent to + ``torch.rand(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def rand_like( + input: Tensor, + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + rand_like(input, *, generator=None, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same size as :attr:`input` that is filled with + random numbers from a uniform distribution on the interval :math:`[0, 1)`. + ``torch.rand_like(input)`` is equivalent to + ``torch.rand(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def randint( + low: _int, + high: _int, + size: _size, + *, + generator: Generator | None = None, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + pin_memory: _bool = False, +) -> Tensor: + r""" + randint(low=0, high, size, \*, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with random integers generated uniformly + between :attr:`low` (inclusive) and :attr:`high` (exclusive). + + The shape of the tensor is defined by the variable argument :attr:`size`. + + .. note:: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + size (tuple): a tuple defining the shape of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the desired data type of returned tensor. Default: if ``None``, + this function returns a tensor with dtype ``torch.int64``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.randint(3, 5, (3,)) + tensor([4, 3, 4]) + + + >>> torch.randint(10, (2, 2)) + tensor([[0, 2], + [5, 5]]) + + + >>> torch.randint(3, 10, (2, 2)) + tensor([[4, 5], + [6, 7]]) + """ + +@overload +def randint( + high: _int, + size: _size, + *, + generator: Generator | None = None, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + pin_memory: _bool = False, +) -> Tensor: + r""" + randint(low=0, high, size, \*, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with random integers generated uniformly + between :attr:`low` (inclusive) and :attr:`high` (exclusive). + + The shape of the tensor is defined by the variable argument :attr:`size`. + + .. note:: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + size (tuple): a tuple defining the shape of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the desired data type of returned tensor. Default: if ``None``, + this function returns a tensor with dtype ``torch.int64``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.randint(3, 5, (3,)) + tensor([4, 3, 4]) + + + >>> torch.randint(10, (2, 2)) + tensor([[0, 2], + [5, 5]]) + + + >>> torch.randint(3, 10, (2, 2)) + tensor([[4, 5], + [6, 7]]) + """ + +@overload +def randint( + high: _int | SymInt, + size: Sequence[_int | SymInt], + *, + generator: Generator | None, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint(low=0, high, size, \*, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with random integers generated uniformly + between :attr:`low` (inclusive) and :attr:`high` (exclusive). + + The shape of the tensor is defined by the variable argument :attr:`size`. + + .. note:: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + size (tuple): a tuple defining the shape of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the desired data type of returned tensor. Default: if ``None``, + this function returns a tensor with dtype ``torch.int64``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.randint(3, 5, (3,)) + tensor([4, 3, 4]) + + + >>> torch.randint(10, (2, 2)) + tensor([[0, 2], + [5, 5]]) + + + >>> torch.randint(3, 10, (2, 2)) + tensor([[4, 5], + [6, 7]]) + """ + +@overload +def randint( + high: _int | SymInt, + size: Sequence[_int | SymInt], + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint(low=0, high, size, \*, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with random integers generated uniformly + between :attr:`low` (inclusive) and :attr:`high` (exclusive). + + The shape of the tensor is defined by the variable argument :attr:`size`. + + .. note:: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + size (tuple): a tuple defining the shape of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the desired data type of returned tensor. Default: if ``None``, + this function returns a tensor with dtype ``torch.int64``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.randint(3, 5, (3,)) + tensor([4, 3, 4]) + + + >>> torch.randint(10, (2, 2)) + tensor([[0, 2], + [5, 5]]) + + + >>> torch.randint(3, 10, (2, 2)) + tensor([[4, 5], + [6, 7]]) + """ + +@overload +def randint( + low: _int | SymInt, + high: _int | SymInt, + size: Sequence[_int | SymInt], + *, + generator: Generator | None, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint(low=0, high, size, \*, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with random integers generated uniformly + between :attr:`low` (inclusive) and :attr:`high` (exclusive). + + The shape of the tensor is defined by the variable argument :attr:`size`. + + .. note:: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + size (tuple): a tuple defining the shape of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the desired data type of returned tensor. Default: if ``None``, + this function returns a tensor with dtype ``torch.int64``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.randint(3, 5, (3,)) + tensor([4, 3, 4]) + + + >>> torch.randint(10, (2, 2)) + tensor([[0, 2], + [5, 5]]) + + + >>> torch.randint(3, 10, (2, 2)) + tensor([[4, 5], + [6, 7]]) + """ + +@overload +def randint( + low: _int | SymInt, + high: _int | SymInt, + size: Sequence[_int | SymInt], + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint(low=0, high, size, \*, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with random integers generated uniformly + between :attr:`low` (inclusive) and :attr:`high` (exclusive). + + The shape of the tensor is defined by the variable argument :attr:`size`. + + .. note:: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + size (tuple): a tuple defining the shape of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the desired data type of returned tensor. Default: if ``None``, + this function returns a tensor with dtype ``torch.int64``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.randint(3, 5, (3,)) + tensor([4, 3, 4]) + + + >>> torch.randint(10, (2, 2)) + tensor([[0, 2], + [5, 5]]) + + + >>> torch.randint(3, 10, (2, 2)) + tensor([[4, 5], + [6, 7]]) + """ + +@overload +def randint_like( + input: Tensor, + low: _int | SymInt, + high: _int | SymInt, + *, + generator: Generator | None, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint_like(input, low=0, high, \*, generator=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same shape as Tensor :attr:`input` filled with + random integers generated uniformly between :attr:`low` (inclusive) and + :attr:`high` (exclusive). + + .. note: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def randint_like( + input: Tensor, + low: _int | SymInt, + high: _int | SymInt, + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint_like(input, low=0, high, \*, generator=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same shape as Tensor :attr:`input` filled with + random integers generated uniformly between :attr:`low` (inclusive) and + :attr:`high` (exclusive). + + .. note: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def randint_like( + input: Tensor, + high: Tensor, + *, + generator: Generator | None, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint_like(input, low=0, high, \*, generator=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same shape as Tensor :attr:`input` filled with + random integers generated uniformly between :attr:`low` (inclusive) and + :attr:`high` (exclusive). + + .. note: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def randint_like( + input: Tensor, + high: Tensor, + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint_like(input, low=0, high, \*, generator=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same shape as Tensor :attr:`input` filled with + random integers generated uniformly between :attr:`low` (inclusive) and + :attr:`high` (exclusive). + + .. note: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def randint_like( + input: Tensor, + high: _int | SymInt, + *, + generator: Generator | None, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint_like(input, low=0, high, \*, generator=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same shape as Tensor :attr:`input` filled with + random integers generated uniformly between :attr:`low` (inclusive) and + :attr:`high` (exclusive). + + .. note: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def randint_like( + input: Tensor, + high: _int | SymInt, + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint_like(input, low=0, high, \*, generator=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same shape as Tensor :attr:`input` filled with + random integers generated uniformly between :attr:`low` (inclusive) and + :attr:`high` (exclusive). + + .. note: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def randn( + size: Sequence[_int | SymInt], + *, + generator: Generator | None, + names: Sequence[str | EllipsisType | None] | None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randn(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + + Returns a tensor filled with random numbers from a normal distribution + with mean `0` and variance `1` (also called the standard normal + distribution). + + .. math:: + \text{out}_{i} \sim \mathcal{N}(0, 1) + + For complex dtypes, the tensor is i.i.d. sampled from a `complex normal distribution`_ with zero mean and + unit variance as + + .. math:: + \text{out}_{i} \sim \mathcal{CN}(0, 1) + + This is equivalent to separately sampling the real :math:`(\operatorname{Re})` and imaginary + :math:`(\operatorname{Im})` part of :math:`\text{out}_i` as + + .. math:: + \operatorname{Re}(\text{out}_{i}) \sim \mathcal{N}(0, \frac{1}{2}),\quad + \operatorname{Im}(\text{out}_{i}) \sim \mathcal{N}(0, \frac{1}{2}) + + The shape of the tensor is defined by the variable argument :attr:`size`. + + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.randn(4) + tensor([-2.1436, 0.9966, 2.3426, -0.6366]) + >>> torch.randn(2, 3) + tensor([[ 1.5954, 2.8929, -1.0923], + [ 1.1719, -0.4709, -0.1996]]) + + .. _complex normal distribution: https://en.wikipedia.org/wiki/Complex_normal_distribution + """ + +@overload +def randn( + *size: _int | SymInt, + generator: Generator | None, + names: Sequence[str | EllipsisType | None] | None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randn(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + + Returns a tensor filled with random numbers from a normal distribution + with mean `0` and variance `1` (also called the standard normal + distribution). + + .. math:: + \text{out}_{i} \sim \mathcal{N}(0, 1) + + For complex dtypes, the tensor is i.i.d. sampled from a `complex normal distribution`_ with zero mean and + unit variance as + + .. math:: + \text{out}_{i} \sim \mathcal{CN}(0, 1) + + This is equivalent to separately sampling the real :math:`(\operatorname{Re})` and imaginary + :math:`(\operatorname{Im})` part of :math:`\text{out}_i` as + + .. math:: + \operatorname{Re}(\text{out}_{i}) \sim \mathcal{N}(0, \frac{1}{2}),\quad + \operatorname{Im}(\text{out}_{i}) \sim \mathcal{N}(0, \frac{1}{2}) + + The shape of the tensor is defined by the variable argument :attr:`size`. + + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.randn(4) + tensor([-2.1436, 0.9966, 2.3426, -0.6366]) + >>> torch.randn(2, 3) + tensor([[ 1.5954, 2.8929, -1.0923], + [ 1.1719, -0.4709, -0.1996]]) + + .. _complex normal distribution: https://en.wikipedia.org/wiki/Complex_normal_distribution + """ + +@overload +def randn( + size: Sequence[_int | SymInt], + *, + generator: Generator | None, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randn(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + + Returns a tensor filled with random numbers from a normal distribution + with mean `0` and variance `1` (also called the standard normal + distribution). + + .. math:: + \text{out}_{i} \sim \mathcal{N}(0, 1) + + For complex dtypes, the tensor is i.i.d. sampled from a `complex normal distribution`_ with zero mean and + unit variance as + + .. math:: + \text{out}_{i} \sim \mathcal{CN}(0, 1) + + This is equivalent to separately sampling the real :math:`(\operatorname{Re})` and imaginary + :math:`(\operatorname{Im})` part of :math:`\text{out}_i` as + + .. math:: + \operatorname{Re}(\text{out}_{i}) \sim \mathcal{N}(0, \frac{1}{2}),\quad + \operatorname{Im}(\text{out}_{i}) \sim \mathcal{N}(0, \frac{1}{2}) + + The shape of the tensor is defined by the variable argument :attr:`size`. + + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.randn(4) + tensor([-2.1436, 0.9966, 2.3426, -0.6366]) + >>> torch.randn(2, 3) + tensor([[ 1.5954, 2.8929, -1.0923], + [ 1.1719, -0.4709, -0.1996]]) + + .. _complex normal distribution: https://en.wikipedia.org/wiki/Complex_normal_distribution + """ + +@overload +def randn( + *size: _int | SymInt, + generator: Generator | None, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randn(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + + Returns a tensor filled with random numbers from a normal distribution + with mean `0` and variance `1` (also called the standard normal + distribution). + + .. math:: + \text{out}_{i} \sim \mathcal{N}(0, 1) + + For complex dtypes, the tensor is i.i.d. sampled from a `complex normal distribution`_ with zero mean and + unit variance as + + .. math:: + \text{out}_{i} \sim \mathcal{CN}(0, 1) + + This is equivalent to separately sampling the real :math:`(\operatorname{Re})` and imaginary + :math:`(\operatorname{Im})` part of :math:`\text{out}_i` as + + .. math:: + \operatorname{Re}(\text{out}_{i}) \sim \mathcal{N}(0, \frac{1}{2}),\quad + \operatorname{Im}(\text{out}_{i}) \sim \mathcal{N}(0, \frac{1}{2}) + + The shape of the tensor is defined by the variable argument :attr:`size`. + + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.randn(4) + tensor([-2.1436, 0.9966, 2.3426, -0.6366]) + >>> torch.randn(2, 3) + tensor([[ 1.5954, 2.8929, -1.0923], + [ 1.1719, -0.4709, -0.1996]]) + + .. _complex normal distribution: https://en.wikipedia.org/wiki/Complex_normal_distribution + """ + +@overload +def randn( + size: Sequence[_int | SymInt], + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randn(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + + Returns a tensor filled with random numbers from a normal distribution + with mean `0` and variance `1` (also called the standard normal + distribution). + + .. math:: + \text{out}_{i} \sim \mathcal{N}(0, 1) + + For complex dtypes, the tensor is i.i.d. sampled from a `complex normal distribution`_ with zero mean and + unit variance as + + .. math:: + \text{out}_{i} \sim \mathcal{CN}(0, 1) + + This is equivalent to separately sampling the real :math:`(\operatorname{Re})` and imaginary + :math:`(\operatorname{Im})` part of :math:`\text{out}_i` as + + .. math:: + \operatorname{Re}(\text{out}_{i}) \sim \mathcal{N}(0, \frac{1}{2}),\quad + \operatorname{Im}(\text{out}_{i}) \sim \mathcal{N}(0, \frac{1}{2}) + + The shape of the tensor is defined by the variable argument :attr:`size`. + + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.randn(4) + tensor([-2.1436, 0.9966, 2.3426, -0.6366]) + >>> torch.randn(2, 3) + tensor([[ 1.5954, 2.8929, -1.0923], + [ 1.1719, -0.4709, -0.1996]]) + + .. _complex normal distribution: https://en.wikipedia.org/wiki/Complex_normal_distribution + """ + +@overload +def randn( + *size: _int | SymInt, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randn(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + + Returns a tensor filled with random numbers from a normal distribution + with mean `0` and variance `1` (also called the standard normal + distribution). + + .. math:: + \text{out}_{i} \sim \mathcal{N}(0, 1) + + For complex dtypes, the tensor is i.i.d. sampled from a `complex normal distribution`_ with zero mean and + unit variance as + + .. math:: + \text{out}_{i} \sim \mathcal{CN}(0, 1) + + This is equivalent to separately sampling the real :math:`(\operatorname{Re})` and imaginary + :math:`(\operatorname{Im})` part of :math:`\text{out}_i` as + + .. math:: + \operatorname{Re}(\text{out}_{i}) \sim \mathcal{N}(0, \frac{1}{2}),\quad + \operatorname{Im}(\text{out}_{i}) \sim \mathcal{N}(0, \frac{1}{2}) + + The shape of the tensor is defined by the variable argument :attr:`size`. + + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.randn(4) + tensor([-2.1436, 0.9966, 2.3426, -0.6366]) + >>> torch.randn(2, 3) + tensor([[ 1.5954, 2.8929, -1.0923], + [ 1.1719, -0.4709, -0.1996]]) + + .. _complex normal distribution: https://en.wikipedia.org/wiki/Complex_normal_distribution + """ + +@overload +def randn( + size: Sequence[_int | SymInt], + *, + names: Sequence[str | EllipsisType | None] | None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randn(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + + Returns a tensor filled with random numbers from a normal distribution + with mean `0` and variance `1` (also called the standard normal + distribution). + + .. math:: + \text{out}_{i} \sim \mathcal{N}(0, 1) + + For complex dtypes, the tensor is i.i.d. sampled from a `complex normal distribution`_ with zero mean and + unit variance as + + .. math:: + \text{out}_{i} \sim \mathcal{CN}(0, 1) + + This is equivalent to separately sampling the real :math:`(\operatorname{Re})` and imaginary + :math:`(\operatorname{Im})` part of :math:`\text{out}_i` as + + .. math:: + \operatorname{Re}(\text{out}_{i}) \sim \mathcal{N}(0, \frac{1}{2}),\quad + \operatorname{Im}(\text{out}_{i}) \sim \mathcal{N}(0, \frac{1}{2}) + + The shape of the tensor is defined by the variable argument :attr:`size`. + + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.randn(4) + tensor([-2.1436, 0.9966, 2.3426, -0.6366]) + >>> torch.randn(2, 3) + tensor([[ 1.5954, 2.8929, -1.0923], + [ 1.1719, -0.4709, -0.1996]]) + + .. _complex normal distribution: https://en.wikipedia.org/wiki/Complex_normal_distribution + """ + +@overload +def randn( + *size: _int | SymInt, + names: Sequence[str | EllipsisType | None] | None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randn(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + + Returns a tensor filled with random numbers from a normal distribution + with mean `0` and variance `1` (also called the standard normal + distribution). + + .. math:: + \text{out}_{i} \sim \mathcal{N}(0, 1) + + For complex dtypes, the tensor is i.i.d. sampled from a `complex normal distribution`_ with zero mean and + unit variance as + + .. math:: + \text{out}_{i} \sim \mathcal{CN}(0, 1) + + This is equivalent to separately sampling the real :math:`(\operatorname{Re})` and imaginary + :math:`(\operatorname{Im})` part of :math:`\text{out}_i` as + + .. math:: + \operatorname{Re}(\text{out}_{i}) \sim \mathcal{N}(0, \frac{1}{2}),\quad + \operatorname{Im}(\text{out}_{i}) \sim \mathcal{N}(0, \frac{1}{2}) + + The shape of the tensor is defined by the variable argument :attr:`size`. + + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.randn(4) + tensor([-2.1436, 0.9966, 2.3426, -0.6366]) + >>> torch.randn(2, 3) + tensor([[ 1.5954, 2.8929, -1.0923], + [ 1.1719, -0.4709, -0.1996]]) + + .. _complex normal distribution: https://en.wikipedia.org/wiki/Complex_normal_distribution + """ + +@overload +def randn_like( + input: Tensor, + *, + generator: Generator | None, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randn_like(input, *, generator=None, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same size as :attr:`input` that is filled with + random numbers from a normal distribution with mean 0 and variance 1. Please refer to :func:`torch.randn` for the + sampling process of complex dtypes. ``torch.randn_like(input)`` is equivalent to + ``torch.randn(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def randn_like( + input: Tensor, + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randn_like(input, *, generator=None, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same size as :attr:`input` that is filled with + random numbers from a normal distribution with mean 0 and variance 1. Please refer to :func:`torch.randn` for the + sampling process of complex dtypes. ``torch.randn_like(input)`` is equivalent to + ``torch.randn(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def randperm( + n: _int | SymInt, + *, + generator: Generator | None, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randperm(n, *, generator=None, out=None, dtype=torch.int64,layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + Returns a random permutation of integers from ``0`` to ``n - 1``. + + Args: + n (int): the upper bound (exclusive) + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: ``torch.int64``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.randperm(4) + tensor([2, 1, 0, 3]) + """ + +@overload +def randperm( + n: _int | SymInt, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randperm(n, *, generator=None, out=None, dtype=torch.int64,layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + Returns a random permutation of integers from ``0`` to ``n - 1``. + + Args: + n (int): the upper bound (exclusive) + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: ``torch.int64``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.randperm(4) + tensor([2, 1, 0, 3]) + """ + +def range( + start: Number, + end: Number, + step: Number = 1, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + pin_memory: _bool = False, +) -> Tensor: + r""" + range(start=0, end, step=1, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a 1-D tensor of size :math:`\left\lfloor \frac{\text{end} - \text{start}}{\text{step}} \right\rfloor + 1` + with values from :attr:`start` to :attr:`end` with step :attr:`step`. Step is + the gap between two values in the tensor. + + .. math:: + \text{out}_{i+1} = \text{out}_i + \text{step}. + + .. warning:: + This function is deprecated and will be removed in a future release because its behavior is inconsistent with + Python's range builtin. Instead, use :func:`torch.arange`, which produces values in [start, end). + + Args: + start (float, optional): the starting value for the set of points. Default: ``0``. + end (float): the ending value for the set of points + step (float, optional): the gap between each pair of adjacent points. Default: ``1``. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). If `dtype` is not given, infer the data type from the other input + arguments. If any of `start`, `end`, or `step` are floating-point, the + `dtype` is inferred to be the default dtype, see + :meth:`~torch.get_default_dtype`. Otherwise, the `dtype` is inferred to + be `torch.int64`. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.range(1, 4) + tensor([ 1., 2., 3., 4.]) + >>> torch.range(1, 4, 0.5) + tensor([ 1.0000, 1.5000, 2.0000, 2.5000, 3.0000, 3.5000, 4.0000]) + """ + +def ravel(input: Tensor) -> Tensor: + r""" + ravel(input) -> Tensor + + Return a contiguous flattened tensor. A copy is made only if needed. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> t = torch.tensor([[[1, 2], + ... [3, 4]], + ... [[5, 6], + ... [7, 8]]]) + >>> torch.ravel(t) + tensor([1, 2, 3, 4, 5, 6, 7, 8]) + """ + +def real(input: Tensor) -> Tensor: + r""" + real(input) -> Tensor + + Returns a new tensor containing real values of the :attr:`self` tensor. + The returned tensor and :attr:`self` share the same underlying storage. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> x=torch.randn(4, dtype=torch.cfloat) + >>> x + tensor([(0.3100+0.3553j), (-0.5445-0.7896j), (-1.6492-0.0633j), (-0.0638-0.8119j)]) + >>> x.real + tensor([ 0.3100, -0.5445, -1.6492, -0.0638]) + """ + +def reciprocal(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + reciprocal(input, *, out=None) -> Tensor + + Returns a new tensor with the reciprocal of the elements of :attr:`input` + + .. math:: + \text{out}_{i} = \frac{1}{\text{input}_{i}} + + .. note:: + Unlike NumPy's reciprocal, torch.reciprocal supports integral inputs. Integral + inputs to reciprocal are automatically :ref:`promoted ` to + the default scalar type. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-0.4595, -2.1219, -1.4314, 0.7298]) + >>> torch.reciprocal(a) + tensor([-2.1763, -0.4713, -0.6986, 1.3702]) + """ + +def reciprocal_(input: Tensor) -> Tensor: ... +def relu(input: Tensor) -> Tensor: ... +def relu_(input: Tensor) -> Tensor: ... +@overload +def remainder( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + remainder(input, other, *, out=None) -> Tensor + + Computes + `Python's modulus operation `_ + entrywise. The result has the same sign as the divisor :attr:`other` and its absolute value + is less than that of :attr:`other`. + + It may also be defined in terms of :func:`torch.div` as + + .. code:: python + + torch.remainder(a, b) == a - a.div(b, rounding_mode="floor") * b + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer and float inputs. + + .. note:: + Complex inputs are not supported. In some cases, it is not mathematically + possible to satisfy the definition of a modulo operation with complex numbers. + See :func:`torch.fmod` for how division by zero is handled. + + .. seealso:: + + :func:`torch.fmod` which implements C++'s `std::fmod `_. + This one is defined in terms of division rounding towards zero. + + Args: + input (Tensor or Scalar): the dividend + other (Tensor or Scalar): the divisor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.remainder(torch.tensor([-3., -2, -1, 1, 2, 3]), 2) + tensor([ 1., 0., 1., 1., 0., 1.]) + >>> torch.remainder(torch.tensor([1, 2, 3, 4, 5]), -1.5) + tensor([ -0.5000, -1.0000, 0.0000, -0.5000, -1.0000 ]) + """ + +@overload +def remainder(self: Number | _complex, other: Tensor) -> Tensor: + r""" + remainder(input, other, *, out=None) -> Tensor + + Computes + `Python's modulus operation `_ + entrywise. The result has the same sign as the divisor :attr:`other` and its absolute value + is less than that of :attr:`other`. + + It may also be defined in terms of :func:`torch.div` as + + .. code:: python + + torch.remainder(a, b) == a - a.div(b, rounding_mode="floor") * b + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer and float inputs. + + .. note:: + Complex inputs are not supported. In some cases, it is not mathematically + possible to satisfy the definition of a modulo operation with complex numbers. + See :func:`torch.fmod` for how division by zero is handled. + + .. seealso:: + + :func:`torch.fmod` which implements C++'s `std::fmod `_. + This one is defined in terms of division rounding towards zero. + + Args: + input (Tensor or Scalar): the dividend + other (Tensor or Scalar): the divisor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.remainder(torch.tensor([-3., -2, -1, 1, 2, 3]), 2) + tensor([ 1., 0., 1., 1., 0., 1.]) + >>> torch.remainder(torch.tensor([1, 2, 3, 4, 5]), -1.5) + tensor([ -0.5000, -1.0000, 0.0000, -0.5000, -1.0000 ]) + """ + +@overload +def remainder( + input: Tensor, + other: Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + remainder(input, other, *, out=None) -> Tensor + + Computes + `Python's modulus operation `_ + entrywise. The result has the same sign as the divisor :attr:`other` and its absolute value + is less than that of :attr:`other`. + + It may also be defined in terms of :func:`torch.div` as + + .. code:: python + + torch.remainder(a, b) == a - a.div(b, rounding_mode="floor") * b + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer and float inputs. + + .. note:: + Complex inputs are not supported. In some cases, it is not mathematically + possible to satisfy the definition of a modulo operation with complex numbers. + See :func:`torch.fmod` for how division by zero is handled. + + .. seealso:: + + :func:`torch.fmod` which implements C++'s `std::fmod `_. + This one is defined in terms of division rounding towards zero. + + Args: + input (Tensor or Scalar): the dividend + other (Tensor or Scalar): the divisor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.remainder(torch.tensor([-3., -2, -1, 1, 2, 3]), 2) + tensor([ 1., 0., 1., 1., 0., 1.]) + >>> torch.remainder(torch.tensor([1, 2, 3, 4, 5]), -1.5) + tensor([ -0.5000, -1.0000, 0.0000, -0.5000, -1.0000 ]) + """ + +def renorm( + input: Tensor, + p: Number | _complex, + dim: _int, + maxnorm: Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + renorm(input, p, dim, maxnorm, *, out=None) -> Tensor + + Returns a tensor where each sub-tensor of :attr:`input` along dimension + :attr:`dim` is normalized such that the `p`-norm of the sub-tensor is lower + than the value :attr:`maxnorm` + + .. note:: If the norm of a row is lower than `maxnorm`, the row is unchanged + + Args: + input (Tensor): the input tensor. + p (float): the power for the norm computation + dim (int): the dimension to slice over to get the sub-tensors + maxnorm (float): the maximum norm to keep each sub-tensor under + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> x = torch.ones(3, 3) + >>> x[1].fill_(2) + tensor([ 2., 2., 2.]) + >>> x[2].fill_(3) + tensor([ 3., 3., 3.]) + >>> x + tensor([[ 1., 1., 1.], + [ 2., 2., 2.], + [ 3., 3., 3.]]) + >>> torch.renorm(x, 1, 0, 5) + tensor([[ 1.0000, 1.0000, 1.0000], + [ 1.6667, 1.6667, 1.6667], + [ 1.6667, 1.6667, 1.6667]]) + """ + +@overload +def repeat_interleave( + input: Tensor, + repeats: Tensor, + dim: _int | None = None, + *, + output_size: _int | SymInt | None = None, +) -> Tensor: + r""" + repeat_interleave(input, repeats, dim=None, *, output_size=None) -> Tensor + + Repeat elements of a tensor. + + .. warning:: + + This is different from :meth:`torch.Tensor.repeat` but similar to ``numpy.repeat``. + + Args: + input (Tensor): the input tensor. + repeats (Tensor or int): The number of repetitions for each element. + repeats is broadcasted to fit the shape of the given axis. + dim (int, optional): The dimension along which to repeat values. + By default, use the flattened input array, and return a flat output + array. + + Keyword args: + output_size (int, optional): Total output size for the given axis + ( e.g. sum of repeats). If given, it will avoid stream synchronization + needed to calculate output shape of the tensor. + + Returns: + Tensor: Repeated tensor which has the same shape as input, except along the given axis. + + Example:: + + >>> x = torch.tensor([1, 2, 3]) + >>> x.repeat_interleave(2) + tensor([1, 1, 2, 2, 3, 3]) + >>> y = torch.tensor([[1, 2], [3, 4]]) + >>> torch.repeat_interleave(y, 2) + tensor([1, 1, 2, 2, 3, 3, 4, 4]) + >>> torch.repeat_interleave(y, 3, dim=1) + tensor([[1, 1, 1, 2, 2, 2], + [3, 3, 3, 4, 4, 4]]) + >>> torch.repeat_interleave(y, torch.tensor([1, 2]), dim=0) + tensor([[1, 2], + [3, 4], + [3, 4]]) + >>> torch.repeat_interleave(y, torch.tensor([1, 2]), dim=0, output_size=3) + tensor([[1, 2], + [3, 4], + [3, 4]]) + + If the `repeats` is `tensor([n1, n2, n3, ...])`, then the output will be + `tensor([0, 0, ..., 1, 1, ..., 2, 2, ..., ...])` where `0` appears `n1` times, + `1` appears `n2` times, `2` appears `n3` times, etc. + + .. function:: repeat_interleave(repeats, *) -> Tensor + :noindex: + + Repeats 0 repeats[0] times, 1 repeats[1] times, 2 repeats[2] times, etc. + + Args: + repeats (Tensor): The number of repetitions for each element. + + Returns: + Tensor: Repeated tensor of size `sum(repeats)`. + + Example:: + + >>> torch.repeat_interleave(torch.tensor([1, 2, 3])) + tensor([0, 1, 1, 2, 2, 2]) + """ + +@overload +def repeat_interleave( + repeats: Tensor, + *, + output_size: _int | SymInt | None = None, +) -> Tensor: + r""" + repeat_interleave(input, repeats, dim=None, *, output_size=None) -> Tensor + + Repeat elements of a tensor. + + .. warning:: + + This is different from :meth:`torch.Tensor.repeat` but similar to ``numpy.repeat``. + + Args: + input (Tensor): the input tensor. + repeats (Tensor or int): The number of repetitions for each element. + repeats is broadcasted to fit the shape of the given axis. + dim (int, optional): The dimension along which to repeat values. + By default, use the flattened input array, and return a flat output + array. + + Keyword args: + output_size (int, optional): Total output size for the given axis + ( e.g. sum of repeats). If given, it will avoid stream synchronization + needed to calculate output shape of the tensor. + + Returns: + Tensor: Repeated tensor which has the same shape as input, except along the given axis. + + Example:: + + >>> x = torch.tensor([1, 2, 3]) + >>> x.repeat_interleave(2) + tensor([1, 1, 2, 2, 3, 3]) + >>> y = torch.tensor([[1, 2], [3, 4]]) + >>> torch.repeat_interleave(y, 2) + tensor([1, 1, 2, 2, 3, 3, 4, 4]) + >>> torch.repeat_interleave(y, 3, dim=1) + tensor([[1, 1, 1, 2, 2, 2], + [3, 3, 3, 4, 4, 4]]) + >>> torch.repeat_interleave(y, torch.tensor([1, 2]), dim=0) + tensor([[1, 2], + [3, 4], + [3, 4]]) + >>> torch.repeat_interleave(y, torch.tensor([1, 2]), dim=0, output_size=3) + tensor([[1, 2], + [3, 4], + [3, 4]]) + + If the `repeats` is `tensor([n1, n2, n3, ...])`, then the output will be + `tensor([0, 0, ..., 1, 1, ..., 2, 2, ..., ...])` where `0` appears `n1` times, + `1` appears `n2` times, `2` appears `n3` times, etc. + + .. function:: repeat_interleave(repeats, *) -> Tensor + :noindex: + + Repeats 0 repeats[0] times, 1 repeats[1] times, 2 repeats[2] times, etc. + + Args: + repeats (Tensor): The number of repetitions for each element. + + Returns: + Tensor: Repeated tensor of size `sum(repeats)`. + + Example:: + + >>> torch.repeat_interleave(torch.tensor([1, 2, 3])) + tensor([0, 1, 1, 2, 2, 2]) + """ + +@overload +def repeat_interleave( + input: Tensor, + repeats: _int | SymInt, + dim: _int | None = None, + *, + output_size: _int | SymInt | None = None, +) -> Tensor: + r""" + repeat_interleave(input, repeats, dim=None, *, output_size=None) -> Tensor + + Repeat elements of a tensor. + + .. warning:: + + This is different from :meth:`torch.Tensor.repeat` but similar to ``numpy.repeat``. + + Args: + input (Tensor): the input tensor. + repeats (Tensor or int): The number of repetitions for each element. + repeats is broadcasted to fit the shape of the given axis. + dim (int, optional): The dimension along which to repeat values. + By default, use the flattened input array, and return a flat output + array. + + Keyword args: + output_size (int, optional): Total output size for the given axis + ( e.g. sum of repeats). If given, it will avoid stream synchronization + needed to calculate output shape of the tensor. + + Returns: + Tensor: Repeated tensor which has the same shape as input, except along the given axis. + + Example:: + + >>> x = torch.tensor([1, 2, 3]) + >>> x.repeat_interleave(2) + tensor([1, 1, 2, 2, 3, 3]) + >>> y = torch.tensor([[1, 2], [3, 4]]) + >>> torch.repeat_interleave(y, 2) + tensor([1, 1, 2, 2, 3, 3, 4, 4]) + >>> torch.repeat_interleave(y, 3, dim=1) + tensor([[1, 1, 1, 2, 2, 2], + [3, 3, 3, 4, 4, 4]]) + >>> torch.repeat_interleave(y, torch.tensor([1, 2]), dim=0) + tensor([[1, 2], + [3, 4], + [3, 4]]) + >>> torch.repeat_interleave(y, torch.tensor([1, 2]), dim=0, output_size=3) + tensor([[1, 2], + [3, 4], + [3, 4]]) + + If the `repeats` is `tensor([n1, n2, n3, ...])`, then the output will be + `tensor([0, 0, ..., 1, 1, ..., 2, 2, ..., ...])` where `0` appears `n1` times, + `1` appears `n2` times, `2` appears `n3` times, etc. + + .. function:: repeat_interleave(repeats, *) -> Tensor + :noindex: + + Repeats 0 repeats[0] times, 1 repeats[1] times, 2 repeats[2] times, etc. + + Args: + repeats (Tensor): The number of repetitions for each element. + + Returns: + Tensor: Repeated tensor of size `sum(repeats)`. + + Example:: + + >>> torch.repeat_interleave(torch.tensor([1, 2, 3])) + tensor([0, 1, 1, 2, 2, 2]) + """ + +def reshape(input: Tensor, shape: Sequence[_int | SymInt]) -> Tensor: + r""" + reshape(input, shape) -> Tensor + + Returns a tensor with the same data and number of elements as :attr:`input`, + but with the specified shape. When possible, the returned tensor will be a view + of :attr:`input`. Otherwise, it will be a copy. Contiguous inputs and inputs + with compatible strides can be reshaped without copying, but you should not + depend on the copying vs. viewing behavior. + + See :meth:`torch.Tensor.view` on when it is possible to return a view. + + A single dimension may be -1, in which case it's inferred from the remaining + dimensions and the number of elements in :attr:`input`. + + Args: + input (Tensor): the tensor to be reshaped + shape (tuple of int): the new shape + + Example:: + + >>> a = torch.arange(4.) + >>> torch.reshape(a, (2, 2)) + tensor([[ 0., 1.], + [ 2., 3.]]) + >>> b = torch.tensor([[0, 1], [2, 3]]) + >>> torch.reshape(b, (-1,)) + tensor([ 0, 1, 2, 3]) + """ + +def resize_as_( + input: Tensor, + the_template: Tensor, + *, + memory_format: memory_format | None = None, +) -> Tensor: ... +def resize_as_sparse_(input: Tensor, the_template: Tensor) -> Tensor: ... +def resolve_conj(input: Tensor) -> Tensor: + r""" + resolve_conj(input) -> Tensor + + Returns a new tensor with materialized conjugation if :attr:`input`'s conjugate bit is set to `True`, + else returns :attr:`input`. The output tensor will always have its conjugate bit set to `False`. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> x = torch.tensor([-1 + 1j, -2 + 2j, 3 - 3j]) + >>> y = x.conj() + >>> y.is_conj() + True + >>> z = y.resolve_conj() + >>> z + tensor([-1 - 1j, -2 - 2j, 3 + 3j]) + >>> z.is_conj() + False + """ + +def resolve_neg(input: Tensor) -> Tensor: + r""" + resolve_neg(input) -> Tensor + + Returns a new tensor with materialized negation if :attr:`input`'s negative bit is set to `True`, + else returns :attr:`input`. The output tensor will always have its negative bit set to `False`. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> x = torch.tensor([-1 + 1j, -2 + 2j, 3 - 3j]) + >>> y = x.conj() + >>> z = y.imag + >>> z.is_neg() + True + >>> out = z.resolve_neg() + >>> out + tensor([-1., -2., 3.]) + >>> out.is_neg() + False + """ + +@overload +def result_type(tensor: Tensor, other: Tensor) -> _dtype: + r""" + result_type(tensor1, tensor2) -> dtype + + Returns the :class:`torch.dtype` that would result from performing an arithmetic + operation on the provided input tensors. See type promotion :ref:`documentation ` + for more information on the type promotion logic. + + Args: + tensor1 (Tensor or Number): an input tensor or number + tensor2 (Tensor or Number): an input tensor or number + + Example:: + + >>> torch.result_type(torch.tensor([1, 2], dtype=torch.int), 1.0) + torch.float32 + >>> torch.result_type(torch.tensor([1, 2], dtype=torch.uint8), torch.tensor(1)) + torch.uint8 + """ + +@overload +def result_type(scalar: Number | _complex, tensor: Tensor) -> _dtype: + r""" + result_type(tensor1, tensor2) -> dtype + + Returns the :class:`torch.dtype` that would result from performing an arithmetic + operation on the provided input tensors. See type promotion :ref:`documentation ` + for more information on the type promotion logic. + + Args: + tensor1 (Tensor or Number): an input tensor or number + tensor2 (Tensor or Number): an input tensor or number + + Example:: + + >>> torch.result_type(torch.tensor([1, 2], dtype=torch.int), 1.0) + torch.float32 + >>> torch.result_type(torch.tensor([1, 2], dtype=torch.uint8), torch.tensor(1)) + torch.uint8 + """ + +@overload +def result_type(tensor: Tensor, other: Number | _complex) -> _dtype: + r""" + result_type(tensor1, tensor2) -> dtype + + Returns the :class:`torch.dtype` that would result from performing an arithmetic + operation on the provided input tensors. See type promotion :ref:`documentation ` + for more information on the type promotion logic. + + Args: + tensor1 (Tensor or Number): an input tensor or number + tensor2 (Tensor or Number): an input tensor or number + + Example:: + + >>> torch.result_type(torch.tensor([1, 2], dtype=torch.int), 1.0) + torch.float32 + >>> torch.result_type(torch.tensor([1, 2], dtype=torch.uint8), torch.tensor(1)) + torch.uint8 + """ + +@overload +def result_type( + scalar1: Number | _complex, + scalar2: Number | _complex, +) -> _dtype: + r""" + result_type(tensor1, tensor2) -> dtype + + Returns the :class:`torch.dtype` that would result from performing an arithmetic + operation on the provided input tensors. See type promotion :ref:`documentation ` + for more information on the type promotion logic. + + Args: + tensor1 (Tensor or Number): an input tensor or number + tensor2 (Tensor or Number): an input tensor or number + + Example:: + + >>> torch.result_type(torch.tensor([1, 2], dtype=torch.int), 1.0) + torch.float32 + >>> torch.result_type(torch.tensor([1, 2], dtype=torch.uint8), torch.tensor(1)) + torch.uint8 + """ + +def rms_norm( + input: Tensor, + normalized_shape: Sequence[_int | SymInt], + weight: Tensor | None = None, + eps: _float | None = None, +) -> Tensor: ... +@overload +def rnn_relu( + data: Tensor, + batch_sizes: Tensor, + hx: Tensor, + params: tuple[Tensor, ...] | list[Tensor] | None, + has_biases: _bool, + num_layers: _int, + dropout: _float, + train: _bool, + bidirectional: _bool, +) -> tuple[Tensor, Tensor]: ... +@overload +def rnn_relu( + input: Tensor, + hx: Tensor, + params: tuple[Tensor, ...] | list[Tensor] | None, + has_biases: _bool, + num_layers: _int, + dropout: _float, + train: _bool, + bidirectional: _bool, + batch_first: _bool, +) -> tuple[Tensor, Tensor]: ... +def rnn_relu_cell( + input: Tensor, + hx: Tensor, + w_ih: Tensor, + w_hh: Tensor, + b_ih: Tensor | None = None, + b_hh: Tensor | None = None, +) -> Tensor: ... +@overload +def rnn_tanh( + data: Tensor, + batch_sizes: Tensor, + hx: Tensor, + params: tuple[Tensor, ...] | list[Tensor] | None, + has_biases: _bool, + num_layers: _int, + dropout: _float, + train: _bool, + bidirectional: _bool, +) -> tuple[Tensor, Tensor]: ... +@overload +def rnn_tanh( + input: Tensor, + hx: Tensor, + params: tuple[Tensor, ...] | list[Tensor] | None, + has_biases: _bool, + num_layers: _int, + dropout: _float, + train: _bool, + bidirectional: _bool, + batch_first: _bool, +) -> tuple[Tensor, Tensor]: ... +def rnn_tanh_cell( + input: Tensor, + hx: Tensor, + w_ih: Tensor, + w_hh: Tensor, + b_ih: Tensor | None = None, + b_hh: Tensor | None = None, +) -> Tensor: ... +def roll( + input: Tensor, + shifts: _int | SymInt | Sequence[_int | SymInt], + dims: _int | _size = (), +) -> Tensor: + r""" + roll(input, shifts, dims=None) -> Tensor + + Roll the tensor :attr:`input` along the given dimension(s). Elements that are + shifted beyond the last position are re-introduced at the first position. If + :attr:`dims` is `None`, the tensor will be flattened before rolling and then + restored to the original shape. + + Args: + input (Tensor): the input tensor. + shifts (int or tuple of ints): The number of places by which the elements + of the tensor are shifted. If shifts is a tuple, dims must be a tuple of + the same size, and each dimension will be rolled by the corresponding + value + dims (int or tuple of ints): Axis along which to roll + + Example:: + + >>> x = torch.tensor([1, 2, 3, 4, 5, 6, 7, 8]).view(4, 2) + >>> x + tensor([[1, 2], + [3, 4], + [5, 6], + [7, 8]]) + >>> torch.roll(x, 1) + tensor([[8, 1], + [2, 3], + [4, 5], + [6, 7]]) + >>> torch.roll(x, 1, 0) + tensor([[7, 8], + [1, 2], + [3, 4], + [5, 6]]) + >>> torch.roll(x, -1, 0) + tensor([[3, 4], + [5, 6], + [7, 8], + [1, 2]]) + >>> torch.roll(x, shifts=(2, 1), dims=(0, 1)) + tensor([[6, 5], + [8, 7], + [2, 1], + [4, 3]]) + """ + +def rot90(input: Tensor, k: _int = 1, dims: _size = (0, 1)) -> Tensor: + r""" + rot90(input, k=1, dims=(0, 1)) -> Tensor + + Rotate an n-D tensor by 90 degrees in the plane specified by dims axis. + Rotation direction is from the first towards the second axis if k > 0, and from the second towards the first for k < 0. + + Args: + input (Tensor): the input tensor. + k (int): number of times to rotate. Default value is 1 + dims (a list or tuple): axis to rotate. Default value is [0, 1] + + Example:: + + >>> x = torch.arange(4).view(2, 2) + >>> x + tensor([[0, 1], + [2, 3]]) + >>> torch.rot90(x, 1, [0, 1]) + tensor([[1, 3], + [0, 2]]) + + >>> x = torch.arange(8).view(2, 2, 2) + >>> x + tensor([[[0, 1], + [2, 3]], + + [[4, 5], + [6, 7]]]) + >>> torch.rot90(x, 1, [1, 2]) + tensor([[[1, 3], + [0, 2]], + + [[5, 7], + [4, 6]]]) + """ + +@overload +def round(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + round(input, *, decimals=0, out=None) -> Tensor + + Rounds elements of :attr:`input` to the nearest integer. + + For integer inputs, follows the array-api convention of returning a + copy of the input tensor. + The return type of output is same as that of input's dtype. + + .. note:: + This function implements the "round half to even" to + break ties when a number is equidistant from two + integers (e.g. `round(2.5)` is 2). + + When the :attr:\`decimals\` argument is specified the + algorithm used is similar to NumPy's `around`. This + algorithm is fast but inexact and it can easily + overflow for low precision dtypes. + Eg. `round(tensor([10000], dtype=torch.float16), decimals=3)` is `inf`. + + .. seealso:: + :func:`torch.ceil`, which rounds up. + :func:`torch.floor`, which rounds down. + :func:`torch.trunc`, which rounds towards zero. + + Args: + input (Tensor): the input tensor. + decimals (int): Number of decimal places to round to (default: 0). + If decimals is negative, it specifies the number of positions + to the left of the decimal point. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.round(torch.tensor((4.7, -2.3, 9.1, -7.7))) + tensor([ 5., -2., 9., -8.]) + + >>> # Values equidistant from two integers are rounded towards the + >>> # the nearest even value (zero is treated as even) + >>> torch.round(torch.tensor([-0.5, 0.5, 1.5, 2.5])) + tensor([-0., 0., 2., 2.]) + + >>> # A positive decimals argument rounds to the to that decimal place + >>> torch.round(torch.tensor([0.1234567]), decimals=3) + tensor([0.1230]) + + >>> # A negative decimals argument rounds to the left of the decimal + >>> torch.round(torch.tensor([1200.1234567]), decimals=-3) + tensor([1000.]) + """ + +@overload +def round( + input: Tensor, + *, + decimals: _int, + out: Tensor | None = None, +) -> Tensor: + r""" + round(input, *, decimals=0, out=None) -> Tensor + + Rounds elements of :attr:`input` to the nearest integer. + + For integer inputs, follows the array-api convention of returning a + copy of the input tensor. + The return type of output is same as that of input's dtype. + + .. note:: + This function implements the "round half to even" to + break ties when a number is equidistant from two + integers (e.g. `round(2.5)` is 2). + + When the :attr:\`decimals\` argument is specified the + algorithm used is similar to NumPy's `around`. This + algorithm is fast but inexact and it can easily + overflow for low precision dtypes. + Eg. `round(tensor([10000], dtype=torch.float16), decimals=3)` is `inf`. + + .. seealso:: + :func:`torch.ceil`, which rounds up. + :func:`torch.floor`, which rounds down. + :func:`torch.trunc`, which rounds towards zero. + + Args: + input (Tensor): the input tensor. + decimals (int): Number of decimal places to round to (default: 0). + If decimals is negative, it specifies the number of positions + to the left of the decimal point. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.round(torch.tensor((4.7, -2.3, 9.1, -7.7))) + tensor([ 5., -2., 9., -8.]) + + >>> # Values equidistant from two integers are rounded towards the + >>> # the nearest even value (zero is treated as even) + >>> torch.round(torch.tensor([-0.5, 0.5, 1.5, 2.5])) + tensor([-0., 0., 2., 2.]) + + >>> # A positive decimals argument rounds to the to that decimal place + >>> torch.round(torch.tensor([0.1234567]), decimals=3) + tensor([0.1230]) + + >>> # A negative decimals argument rounds to the left of the decimal + >>> torch.round(torch.tensor([1200.1234567]), decimals=-3) + tensor([1000.]) + """ + +@overload +def round_(input: Tensor) -> Tensor: ... +@overload +def round_(input: Tensor, *, decimals: _int) -> Tensor: ... +def row_indices_copy(input: Tensor, *, out: Tensor | None = None) -> Tensor: ... +def row_stack( + tensors: tuple[Tensor, ...] | list[Tensor] | None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + row_stack(tensors, *, out=None) -> Tensor + + Alias of :func:`torch.vstack`. + """ + +def rrelu( + input: Tensor, + lower: Number | _complex = 0.125, + upper: Number | _complex = 0.3333333333333333, + training: _bool = False, + generator: Generator | None = None, +) -> Tensor: ... +def rrelu_( + input: Tensor, + lower: Number | _complex = 0.125, + upper: Number | _complex = 0.3333333333333333, + training: _bool = False, + generator: Generator | None = None, +) -> Tensor: ... +def rsqrt(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + rsqrt(input, *, out=None) -> Tensor + + Returns a new tensor with the reciprocal of the square-root of each of + the elements of :attr:`input`. + + .. math:: + \text{out}_{i} = \frac{1}{\sqrt{\text{input}_{i}}} + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-0.0370, 0.2970, 1.5420, -0.9105]) + >>> torch.rsqrt(a) + tensor([ nan, 1.8351, 0.8053, nan]) + """ + +def rsqrt_(input: Tensor) -> Tensor: ... +@overload +def rsub( + input: Tensor, + other: Tensor, + *, + alpha: Number | _complex = 1, +) -> Tensor: ... +@overload +def rsub( + input: Tensor, + other: Number | _complex, + alpha: Number | _complex = 1, +) -> Tensor: ... +def saddmm( + input: Tensor, + mat1: Tensor, + mat2: Tensor, + *, + beta: Number = 1, + alpha: Number = 1, + out: Tensor | None = None, +) -> Tensor: ... +def scalar_tensor( + s: Number | _complex, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: ... +@overload +def scatter( + input: Tensor, + dim: _int, + index: Tensor, + src: Tensor, + *, + reduce: str, + out: Tensor | None = None, +) -> Tensor: + r""" + scatter(input, dim, index, src) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.scatter_` + """ + +@overload +def scatter( + input: Tensor, + dim: _int, + index: Tensor, + src: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + scatter(input, dim, index, src) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.scatter_` + """ + +@overload +def scatter( + input: Tensor, + dim: _int, + index: Tensor, + value: Number | _complex, + *, + reduce: str, + out: Tensor | None = None, +) -> Tensor: + r""" + scatter(input, dim, index, src) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.scatter_` + """ + +@overload +def scatter( + input: Tensor, + dim: str | EllipsisType | None, + index: Tensor, + src: Tensor, +) -> Tensor: + r""" + scatter(input, dim, index, src) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.scatter_` + """ + +@overload +def scatter( + input: Tensor, + dim: _int, + index: Tensor, + value: Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + scatter(input, dim, index, src) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.scatter_` + """ + +@overload +def scatter( + input: Tensor, + dim: str | EllipsisType | None, + index: Tensor, + value: Number | _complex, +) -> Tensor: + r""" + scatter(input, dim, index, src) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.scatter_` + """ + +@overload +def scatter_add( + input: Tensor, + dim: _int, + index: Tensor, + src: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + scatter_add(input, dim, index, src) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.scatter_add_` + """ + +@overload +def scatter_add( + input: Tensor, + dim: str | EllipsisType | None, + index: Tensor, + src: Tensor, +) -> Tensor: + r""" + scatter_add(input, dim, index, src) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.scatter_add_` + """ + +def scatter_reduce( + input: Tensor, + dim: _int, + index: Tensor, + src: Tensor, + reduce: str, + *, + include_self: _bool = True, + out: Tensor | None = None, +) -> Tensor: + r""" + scatter_reduce(input, dim, index, src, reduce, *, include_self=True) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.scatter_reduce_` + """ + +@overload +def searchsorted( + sorted_sequence: Tensor, + input: Tensor, + *, + out_int32: _bool = False, + right: _bool = False, + side: str | None = None, + sorter: Tensor | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + searchsorted(sorted_sequence, values, *, out_int32=False, right=False, side=None, out=None, sorter=None) -> Tensor + + Find the indices from the *innermost* dimension of :attr:`sorted_sequence` such that, if the + corresponding values in :attr:`values` were inserted before the indices, when sorted, the order + of the corresponding *innermost* dimension within :attr:`sorted_sequence` would be preserved. + Return a new tensor with the same size as :attr:`values`. More formally, + the returned index satisfies the following rules: + + .. list-table:: + :widths: 12 10 78 + :header-rows: 1 + + * - :attr:`sorted_sequence` + - :attr:`right` + - *returned index satisfies* + * - 1-D + - False + - ``sorted_sequence[i-1] < values[m][n]...[l][x] <= sorted_sequence[i]`` + * - 1-D + - True + - ``sorted_sequence[i-1] <= values[m][n]...[l][x] < sorted_sequence[i]`` + * - N-D + - False + - ``sorted_sequence[m][n]...[l][i-1] < values[m][n]...[l][x] <= sorted_sequence[m][n]...[l][i]`` + * - N-D + - True + - ``sorted_sequence[m][n]...[l][i-1] <= values[m][n]...[l][x] < sorted_sequence[m][n]...[l][i]`` + + Args: + sorted_sequence (Tensor): N-D or 1-D tensor, containing monotonically increasing sequence on the *innermost* + dimension unless :attr:`sorter` is provided, in which case the sequence does not + need to be sorted + values (Tensor or Scalar): N-D tensor or a Scalar containing the search value(s). + + Keyword args: + out_int32 (bool, optional): indicate the output data type. torch.int32 if True, torch.int64 otherwise. + Default value is False, i.e. default output data type is torch.int64. + right (bool, optional): if False, return the first suitable location that is found. If True, return the + last such index. If no suitable index found, return 0 for non-numerical value + (eg. nan, inf) or the size of *innermost* dimension within :attr:`sorted_sequence` + (one pass the last index of the *innermost* dimension). In other words, if False, + gets the lower bound index for each value in :attr:`values` on the corresponding + *innermost* dimension of the :attr:`sorted_sequence`. If True, gets the upper + bound index instead. Default value is False. :attr:`side` does the same and is + preferred. It will error if :attr:`side` is set to "left" while this is True. + side (str, optional): the same as :attr:`right` but preferred. "left" corresponds to False for :attr:`right` + and "right" corresponds to True for :attr:`right`. It will error if this is set to + "left" while :attr:`right` is True. Default value is None. + out (Tensor, optional): the output tensor, must be the same size as :attr:`values` if provided. + sorter (LongTensor, optional): if provided, a tensor matching the shape of the unsorted + :attr:`sorted_sequence` containing a sequence of indices that sort it in the + ascending order on the innermost dimension + + + Example:: + + >>> sorted_sequence = torch.tensor([[1, 3, 5, 7, 9], [2, 4, 6, 8, 10]]) + >>> sorted_sequence + tensor([[ 1, 3, 5, 7, 9], + [ 2, 4, 6, 8, 10]]) + >>> values = torch.tensor([[3, 6, 9], [3, 6, 9]]) + >>> values + tensor([[3, 6, 9], + [3, 6, 9]]) + >>> torch.searchsorted(sorted_sequence, values) + tensor([[1, 3, 4], + [1, 2, 4]]) + >>> torch.searchsorted(sorted_sequence, values, side='right') + tensor([[2, 3, 5], + [1, 3, 4]]) + + >>> sorted_sequence_1d = torch.tensor([1, 3, 5, 7, 9]) + >>> sorted_sequence_1d + tensor([1, 3, 5, 7, 9]) + >>> torch.searchsorted(sorted_sequence_1d, values) + tensor([[1, 3, 4], + [1, 3, 4]]) + """ + +@overload +def searchsorted( + sorted_sequence: Tensor, + self: Number | _complex, + *, + out_int32: _bool = False, + right: _bool = False, + side: str | None = None, + sorter: Tensor | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + searchsorted(sorted_sequence, values, *, out_int32=False, right=False, side=None, out=None, sorter=None) -> Tensor + + Find the indices from the *innermost* dimension of :attr:`sorted_sequence` such that, if the + corresponding values in :attr:`values` were inserted before the indices, when sorted, the order + of the corresponding *innermost* dimension within :attr:`sorted_sequence` would be preserved. + Return a new tensor with the same size as :attr:`values`. More formally, + the returned index satisfies the following rules: + + .. list-table:: + :widths: 12 10 78 + :header-rows: 1 + + * - :attr:`sorted_sequence` + - :attr:`right` + - *returned index satisfies* + * - 1-D + - False + - ``sorted_sequence[i-1] < values[m][n]...[l][x] <= sorted_sequence[i]`` + * - 1-D + - True + - ``sorted_sequence[i-1] <= values[m][n]...[l][x] < sorted_sequence[i]`` + * - N-D + - False + - ``sorted_sequence[m][n]...[l][i-1] < values[m][n]...[l][x] <= sorted_sequence[m][n]...[l][i]`` + * - N-D + - True + - ``sorted_sequence[m][n]...[l][i-1] <= values[m][n]...[l][x] < sorted_sequence[m][n]...[l][i]`` + + Args: + sorted_sequence (Tensor): N-D or 1-D tensor, containing monotonically increasing sequence on the *innermost* + dimension unless :attr:`sorter` is provided, in which case the sequence does not + need to be sorted + values (Tensor or Scalar): N-D tensor or a Scalar containing the search value(s). + + Keyword args: + out_int32 (bool, optional): indicate the output data type. torch.int32 if True, torch.int64 otherwise. + Default value is False, i.e. default output data type is torch.int64. + right (bool, optional): if False, return the first suitable location that is found. If True, return the + last such index. If no suitable index found, return 0 for non-numerical value + (eg. nan, inf) or the size of *innermost* dimension within :attr:`sorted_sequence` + (one pass the last index of the *innermost* dimension). In other words, if False, + gets the lower bound index for each value in :attr:`values` on the corresponding + *innermost* dimension of the :attr:`sorted_sequence`. If True, gets the upper + bound index instead. Default value is False. :attr:`side` does the same and is + preferred. It will error if :attr:`side` is set to "left" while this is True. + side (str, optional): the same as :attr:`right` but preferred. "left" corresponds to False for :attr:`right` + and "right" corresponds to True for :attr:`right`. It will error if this is set to + "left" while :attr:`right` is True. Default value is None. + out (Tensor, optional): the output tensor, must be the same size as :attr:`values` if provided. + sorter (LongTensor, optional): if provided, a tensor matching the shape of the unsorted + :attr:`sorted_sequence` containing a sequence of indices that sort it in the + ascending order on the innermost dimension + + + Example:: + + >>> sorted_sequence = torch.tensor([[1, 3, 5, 7, 9], [2, 4, 6, 8, 10]]) + >>> sorted_sequence + tensor([[ 1, 3, 5, 7, 9], + [ 2, 4, 6, 8, 10]]) + >>> values = torch.tensor([[3, 6, 9], [3, 6, 9]]) + >>> values + tensor([[3, 6, 9], + [3, 6, 9]]) + >>> torch.searchsorted(sorted_sequence, values) + tensor([[1, 3, 4], + [1, 2, 4]]) + >>> torch.searchsorted(sorted_sequence, values, side='right') + tensor([[2, 3, 5], + [1, 3, 4]]) + + >>> sorted_sequence_1d = torch.tensor([1, 3, 5, 7, 9]) + >>> sorted_sequence_1d + tensor([1, 3, 5, 7, 9]) + >>> torch.searchsorted(sorted_sequence_1d, values) + tensor([[1, 3, 4], + [1, 3, 4]]) + """ + +def segment_reduce( + data: Tensor, + reduce: str, + *, + lengths: Tensor | None = None, + indices: Tensor | None = None, + offsets: Tensor | None = None, + axis: _int = 0, + unsafe: _bool = False, + initial: Number | _complex | None = None, +) -> Tensor: + r""" + segment_reduce(data: Tensor, reduce: str, *, lengths: Tensor | None = None, indices: Tensor | None = None, offsets: Tensor | None = None, axis: _int = 0, unsafe: _bool = False, initial: Number | _complex | None = None) -> Tensor # noqa: B950 + + Perform a segment reduction operation on the input tensor along the specified axis. + + Args: + data (Tensor): The input tensor on which the segment reduction operation will be performed. + reduce (str): The type of reduction operation. Supported values are ``sum``, ``mean``, ``max``, ``min``, ``prod``. + + Keyword args: + lengths (Tensor, optional): Length of each segment. Default: ``None``. + offsets (Tensor, optional): Offset of each segment. Default: ``None``. + axis (int, optional): The axis perform reduction. Default: ``0``. + unsafe (bool, optional): Skip validation If `True`. Default: ``False``. + initial (Number, optional): The initial value for the reduction operation. Default: ``None``. + + Example:: + + >>> data = torch.tensor([[1, 2, 3, 4],[5, 6, 7, 8],[9, 10, 11, 12]], dtype=torch.float32, device='cuda') + >>> lengths = torch.tensor([2, 1], device='cuda') + >>> torch.segment_reduce(data, 'max', lengths=lengths) + tensor([[ 5., 6., 7., 8.], + [ 9., 10., 11., 12.]], device='cuda:0') + """ + +@overload +def select(input: Tensor, dim: _int, index: _int | SymInt) -> Tensor: + r""" + select(input, dim, index) -> Tensor + + Slices the :attr:`input` tensor along the selected dimension at the given index. + This function returns a view of the original tensor with the given dimension removed. + + .. note:: If :attr:`input` is a sparse tensor and returning a view of + the tensor is not possible, a RuntimeError exception is + raised. In this is the case, consider using + :func:`torch.select_copy` function. + + Args: + input (Tensor): the input tensor. + dim (int): the dimension to slice + index (int): the index to select with + + .. note:: + + :meth:`select` is equivalent to slicing. For example, + ``tensor.select(0, index)`` is equivalent to ``tensor[index]`` and + ``tensor.select(2, index)`` is equivalent to ``tensor[:,:,index]``. + """ + +@overload +def select( + input: Tensor, + dim: str | EllipsisType | None, + index: _int, +) -> Tensor: + r""" + select(input, dim, index) -> Tensor + + Slices the :attr:`input` tensor along the selected dimension at the given index. + This function returns a view of the original tensor with the given dimension removed. + + .. note:: If :attr:`input` is a sparse tensor and returning a view of + the tensor is not possible, a RuntimeError exception is + raised. In this is the case, consider using + :func:`torch.select_copy` function. + + Args: + input (Tensor): the input tensor. + dim (int): the dimension to slice + index (int): the index to select with + + .. note:: + + :meth:`select` is equivalent to slicing. For example, + ``tensor.select(0, index)`` is equivalent to ``tensor[index]`` and + ``tensor.select(2, index)`` is equivalent to ``tensor[:,:,index]``. + """ + +def select_copy( + input: Tensor, + dim: _int, + index: _int | SymInt, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.select`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def select_scatter( + input: Tensor, + src: Tensor, + dim: _int, + index: _int | SymInt, +) -> Tensor: + r""" + select_scatter(input, src, dim, index) -> Tensor + + Embeds the values of the :attr:`src` tensor into :attr:`input` at the given index. + This function returns a tensor with fresh storage; it does not create a view. + + + Args: + input (Tensor): the input tensor. + src (Tensor): The tensor to embed into :attr:`input` + dim (int): the dimension to insert the slice into. + index (int): the index to select with + + .. note:: + + :attr:`src` must be of the proper size in order to be embedded + into :attr:`input`. Specifically, it should have the same shape as + ``torch.select(input, dim, index)`` + + Example:: + + >>> a = torch.zeros(2, 2) + >>> b = torch.ones(2) + >>> a.select_scatter(b, 0, 0) + tensor([[1., 1.], + [0., 0.]]) + """ + +def selu(input: Tensor) -> Tensor: ... +def selu_(input: Tensor) -> Tensor: ... +def set_flush_denormal(mode: _bool) -> _bool: + r""" + set_flush_denormal(mode) -> bool + + Disables denormal floating numbers on CPU. + + Returns ``True`` if your system supports flushing denormal numbers and it + successfully configures flush denormal mode. :meth:`~torch.set_flush_denormal` + is supported on x86 architectures supporting SSE3 and AArch64 architecture. + + Args: + mode (bool): Controls whether to enable flush denormal mode or not + + Example:: + + >>> torch.set_flush_denormal(True) + True + >>> torch.tensor([1e-323], dtype=torch.float64) + tensor([ 0.], dtype=torch.float64) + >>> torch.set_flush_denormal(False) + True + >>> torch.tensor([1e-323], dtype=torch.float64) + tensor(9.88131e-324 * + [ 1.0000], dtype=torch.float64) + """ + +def set_num_interop_threads(num: _int) -> None: + r""" + set_num_interop_threads(int) + + Sets the number of threads used for interop parallelism + (e.g. in JIT interpreter) on CPU. + + .. warning:: + Can only be called once and before any inter-op parallel work + is started (e.g. JIT execution). + """ + +def set_num_threads(num: _int) -> None: + r""" + set_num_threads(int) + + Sets the number of threads used for intraop parallelism on CPU. + + .. warning:: + To ensure that the correct number of threads is used, set_num_threads + must be called before running eager, JIT or autograd code. + """ + +def sgn(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + sgn(input, *, out=None) -> Tensor + + This function is an extension of torch.sign() to complex tensors. + It computes a new tensor whose elements have + the same angles as the corresponding elements of :attr:`input` and + absolute values (i.e. magnitudes) of one for complex tensors and + is equivalent to torch.sign() for non-complex tensors. + + .. math:: + \text{out}_{i} = \begin{cases} + 0 & |\text{{input}}_i| == 0 \\ + \frac{{\text{{input}}_i}}{|{\text{{input}}_i}|} & \text{otherwise} + \end{cases} + + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> t = torch.tensor([3+4j, 7-24j, 0, 1+2j]) + >>> t.sgn() + tensor([0.6000+0.8000j, 0.2800-0.9600j, 0.0000+0.0000j, 0.4472+0.8944j]) + """ + +def sigmoid(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + sigmoid(input, *, out=None) -> Tensor + + Alias for :func:`torch.special.expit`. + """ + +def sigmoid_(input: Tensor) -> Tensor: ... +def sign(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + sign(input, *, out=None) -> Tensor + + Returns a new tensor with the signs of the elements of :attr:`input`. + + .. math:: + \text{out}_{i} = \operatorname{sgn}(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([0.7, -1.2, 0., 2.3]) + >>> a + tensor([ 0.7000, -1.2000, 0.0000, 2.3000]) + >>> torch.sign(a) + tensor([ 1., -1., 0., 1.]) + """ + +def signbit(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + signbit(input, *, out=None) -> Tensor + + Tests if each element of :attr:`input` has its sign bit set or not. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([0.7, -1.2, 0., 2.3]) + >>> torch.signbit(a) + tensor([ False, True, False, False]) + >>> a = torch.tensor([-0.0, 0.0]) + >>> torch.signbit(a) + tensor([ True, False]) + + .. note:: + signbit handles signed zeros, so negative zero (-0) returns True. + """ + +def sin(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + sin(input, *, out=None) -> Tensor + + Returns a new tensor with the sine of the elements in the :attr:`input` tensor, + where each value in this input tensor is in radians. + + .. math:: + \text{out}_{i} = \sin(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-0.5461, 0.1347, -2.7266, -0.2746]) + >>> torch.sin(a) + tensor([-0.5194, 0.1343, -0.4032, -0.2711]) + """ + +def sin_(input: Tensor) -> Tensor: ... +def sinc(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + sinc(input, *, out=None) -> Tensor + + Alias for :func:`torch.special.sinc`. + """ + +def sinc_(input: Tensor) -> Tensor: ... +def sinh(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + sinh(input, *, out=None) -> Tensor + + Returns a new tensor with the hyperbolic sine of the elements of + :attr:`input`. + + .. math:: + \text{out}_{i} = \sinh(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.5380, -0.8632, -0.1265, 0.9399]) + >>> torch.sinh(a) + tensor([ 0.5644, -0.9744, -0.1268, 1.0845]) + + .. note:: + When :attr:`input` is on the CPU, the implementation of torch.sinh may use + the Sleef library, which rounds very large results to infinity or negative + infinity. See `here `_ for details. + """ + +def sinh_(input: Tensor) -> Tensor: ... +def slice_copy( + input: Tensor, + dim: _int = 0, + start: _int | SymInt | None = None, + end: _int | SymInt | None = None, + step: _int | SymInt = 1, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.slice`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def slice_inverse( + input: Tensor, + src: Tensor, + dim: _int = 0, + start: _int | SymInt | None = None, + end: _int | SymInt | None = None, + step: _int | SymInt = 1, +) -> Tensor: ... +def slice_scatter( + input: Tensor, + src: Tensor, + dim: _int = 0, + start: _int | SymInt | None = None, + end: _int | SymInt | None = None, + step: _int | SymInt = 1, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + slice_scatter(input, src, dim=0, start=None, end=None, step=1) -> Tensor + + Embeds the values of the :attr:`src` tensor into :attr:`input` at the given + dimension. + This function returns a tensor with fresh storage; it does not create a view. + + + Args: + input (Tensor): the input tensor. + src (Tensor): The tensor to embed into :attr:`input` + dim (int): the dimension to insert the slice into + start (Optional[int]): the start index of where to insert the slice + end (Optional[int]): the end index of where to insert the slice + step (int): the how many elements to skip in + + Example:: + + >>> a = torch.zeros(8, 8) + >>> b = torch.ones(2, 8) + >>> a.slice_scatter(b, start=6) + tensor([[0., 0., 0., 0., 0., 0., 0., 0.], + [0., 0., 0., 0., 0., 0., 0., 0.], + [0., 0., 0., 0., 0., 0., 0., 0.], + [0., 0., 0., 0., 0., 0., 0., 0.], + [0., 0., 0., 0., 0., 0., 0., 0.], + [0., 0., 0., 0., 0., 0., 0., 0.], + [1., 1., 1., 1., 1., 1., 1., 1.], + [1., 1., 1., 1., 1., 1., 1., 1.]]) + + >>> b = torch.ones(8, 2) + >>> a.slice_scatter(b, dim=1, start=2, end=6, step=2) + tensor([[0., 0., 1., 0., 1., 0., 0., 0.], + [0., 0., 1., 0., 1., 0., 0., 0.], + [0., 0., 1., 0., 1., 0., 0., 0.], + [0., 0., 1., 0., 1., 0., 0., 0.], + [0., 0., 1., 0., 1., 0., 0., 0.], + [0., 0., 1., 0., 1., 0., 0., 0.], + [0., 0., 1., 0., 1., 0., 0., 0.], + [0., 0., 1., 0., 1., 0., 0., 0.]]) + """ + +def slogdet( + input: Tensor, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.slogdet: + r""" + slogdet(input) -> (Tensor, Tensor) + + Alias for :func:`torch.linalg.slogdet` + """ + +def smm(input: Tensor, mat2: Tensor) -> Tensor: + r""" + smm(input, mat) -> Tensor + + Performs a matrix multiplication of the sparse matrix :attr:`input` + with the dense matrix :attr:`mat`. + + Args: + input (Tensor): a sparse matrix to be matrix multiplied + mat (Tensor): a dense matrix to be matrix multiplied + """ + +@overload +def softmax( + input: Tensor, + dim: _int, + dtype: _dtype | None = None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + softmax(input, dim, *, dtype=None) -> Tensor + + Alias for :func:`torch.nn.functional.softmax`. + """ + +@overload +def softmax( + input: Tensor, + dim: str | EllipsisType | None, + *, + dtype: _dtype | None = None, +) -> Tensor: + r""" + softmax(input, dim, *, dtype=None) -> Tensor + + Alias for :func:`torch.nn.functional.softmax`. + """ + +@overload +def sort( + input: Tensor, + *, + stable: _bool | None, + dim: _int = -1, + descending: _bool = False, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.sort: + r""" + sort(input, dim=-1, descending=False, *, stable=False, out=None) -> (Tensor, LongTensor) + + Sorts the elements of the :attr:`input` tensor along a given dimension + in ascending order by value. + + If :attr:`dim` is not given, the last dimension of the `input` is chosen. + + If :attr:`descending` is ``True`` then the elements are sorted in descending + order by value. + + If :attr:`stable` is ``True`` then the sorting routine becomes stable, preserving + the order of equivalent elements. + + A namedtuple of (values, indices) is returned, where the `values` are the + sorted values and `indices` are the indices of the elements in the original + `input` tensor. + + Args: + input (Tensor): the input tensor. + dim (int, optional): the dimension to sort along + descending (bool, optional): controls the sorting order (ascending or descending) + + Keyword args: + stable (bool, optional): makes the sorting routine stable, which guarantees that the order + of equivalent elements is preserved. + out (tuple, optional): the output tuple of (`Tensor`, `LongTensor`) that can + be optionally given to be used as output buffers + + Example:: + + >>> x = torch.randn(3, 4) + >>> sorted, indices = torch.sort(x) + >>> sorted + tensor([[-0.2162, 0.0608, 0.6719, 2.3332], + [-0.5793, 0.0061, 0.6058, 0.9497], + [-0.5071, 0.3343, 0.9553, 1.0960]]) + >>> indices + tensor([[ 1, 0, 2, 3], + [ 3, 1, 0, 2], + [ 0, 3, 1, 2]]) + + >>> sorted, indices = torch.sort(x, 0) + >>> sorted + tensor([[-0.5071, -0.2162, 0.6719, -0.5793], + [ 0.0608, 0.0061, 0.9497, 0.3343], + [ 0.6058, 0.9553, 1.0960, 2.3332]]) + >>> indices + tensor([[ 2, 0, 0, 1], + [ 0, 1, 1, 2], + [ 1, 2, 2, 0]]) + >>> x = torch.tensor([0, 1] * 9) + >>> x.sort() + torch.return_types.sort( + values=tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1]), + indices=tensor([ 2, 16, 4, 6, 14, 8, 0, 10, 12, 9, 17, 15, 13, 11, 7, 5, 3, 1])) + >>> x.sort(stable=True) + torch.return_types.sort( + values=tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1]), + indices=tensor([ 0, 2, 4, 6, 8, 10, 12, 14, 16, 1, 3, 5, 7, 9, 11, 13, 15, 17])) + """ + +@overload +def sort( + input: Tensor, + dim: _int = -1, + descending: _bool = False, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.sort: + r""" + sort(input, dim=-1, descending=False, *, stable=False, out=None) -> (Tensor, LongTensor) + + Sorts the elements of the :attr:`input` tensor along a given dimension + in ascending order by value. + + If :attr:`dim` is not given, the last dimension of the `input` is chosen. + + If :attr:`descending` is ``True`` then the elements are sorted in descending + order by value. + + If :attr:`stable` is ``True`` then the sorting routine becomes stable, preserving + the order of equivalent elements. + + A namedtuple of (values, indices) is returned, where the `values` are the + sorted values and `indices` are the indices of the elements in the original + `input` tensor. + + Args: + input (Tensor): the input tensor. + dim (int, optional): the dimension to sort along + descending (bool, optional): controls the sorting order (ascending or descending) + + Keyword args: + stable (bool, optional): makes the sorting routine stable, which guarantees that the order + of equivalent elements is preserved. + out (tuple, optional): the output tuple of (`Tensor`, `LongTensor`) that can + be optionally given to be used as output buffers + + Example:: + + >>> x = torch.randn(3, 4) + >>> sorted, indices = torch.sort(x) + >>> sorted + tensor([[-0.2162, 0.0608, 0.6719, 2.3332], + [-0.5793, 0.0061, 0.6058, 0.9497], + [-0.5071, 0.3343, 0.9553, 1.0960]]) + >>> indices + tensor([[ 1, 0, 2, 3], + [ 3, 1, 0, 2], + [ 0, 3, 1, 2]]) + + >>> sorted, indices = torch.sort(x, 0) + >>> sorted + tensor([[-0.5071, -0.2162, 0.6719, -0.5793], + [ 0.0608, 0.0061, 0.9497, 0.3343], + [ 0.6058, 0.9553, 1.0960, 2.3332]]) + >>> indices + tensor([[ 2, 0, 0, 1], + [ 0, 1, 1, 2], + [ 1, 2, 2, 0]]) + >>> x = torch.tensor([0, 1] * 9) + >>> x.sort() + torch.return_types.sort( + values=tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1]), + indices=tensor([ 2, 16, 4, 6, 14, 8, 0, 10, 12, 9, 17, 15, 13, 11, 7, 5, 3, 1])) + >>> x.sort(stable=True) + torch.return_types.sort( + values=tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1]), + indices=tensor([ 0, 2, 4, 6, 8, 10, 12, 14, 16, 1, 3, 5, 7, 9, 11, 13, 15, 17])) + """ + +@overload +def sort( + input: Tensor, + *, + stable: _bool | None, + dim: str | EllipsisType | None, + descending: _bool = False, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.sort: + r""" + sort(input, dim=-1, descending=False, *, stable=False, out=None) -> (Tensor, LongTensor) + + Sorts the elements of the :attr:`input` tensor along a given dimension + in ascending order by value. + + If :attr:`dim` is not given, the last dimension of the `input` is chosen. + + If :attr:`descending` is ``True`` then the elements are sorted in descending + order by value. + + If :attr:`stable` is ``True`` then the sorting routine becomes stable, preserving + the order of equivalent elements. + + A namedtuple of (values, indices) is returned, where the `values` are the + sorted values and `indices` are the indices of the elements in the original + `input` tensor. + + Args: + input (Tensor): the input tensor. + dim (int, optional): the dimension to sort along + descending (bool, optional): controls the sorting order (ascending or descending) + + Keyword args: + stable (bool, optional): makes the sorting routine stable, which guarantees that the order + of equivalent elements is preserved. + out (tuple, optional): the output tuple of (`Tensor`, `LongTensor`) that can + be optionally given to be used as output buffers + + Example:: + + >>> x = torch.randn(3, 4) + >>> sorted, indices = torch.sort(x) + >>> sorted + tensor([[-0.2162, 0.0608, 0.6719, 2.3332], + [-0.5793, 0.0061, 0.6058, 0.9497], + [-0.5071, 0.3343, 0.9553, 1.0960]]) + >>> indices + tensor([[ 1, 0, 2, 3], + [ 3, 1, 0, 2], + [ 0, 3, 1, 2]]) + + >>> sorted, indices = torch.sort(x, 0) + >>> sorted + tensor([[-0.5071, -0.2162, 0.6719, -0.5793], + [ 0.0608, 0.0061, 0.9497, 0.3343], + [ 0.6058, 0.9553, 1.0960, 2.3332]]) + >>> indices + tensor([[ 2, 0, 0, 1], + [ 0, 1, 1, 2], + [ 1, 2, 2, 0]]) + >>> x = torch.tensor([0, 1] * 9) + >>> x.sort() + torch.return_types.sort( + values=tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1]), + indices=tensor([ 2, 16, 4, 6, 14, 8, 0, 10, 12, 9, 17, 15, 13, 11, 7, 5, 3, 1])) + >>> x.sort(stable=True) + torch.return_types.sort( + values=tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1]), + indices=tensor([ 0, 2, 4, 6, 8, 10, 12, 14, 16, 1, 3, 5, 7, 9, 11, 13, 15, 17])) + """ + +@overload +def sort( + input: Tensor, + dim: str | EllipsisType | None, + descending: _bool = False, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.sort: + r""" + sort(input, dim=-1, descending=False, *, stable=False, out=None) -> (Tensor, LongTensor) + + Sorts the elements of the :attr:`input` tensor along a given dimension + in ascending order by value. + + If :attr:`dim` is not given, the last dimension of the `input` is chosen. + + If :attr:`descending` is ``True`` then the elements are sorted in descending + order by value. + + If :attr:`stable` is ``True`` then the sorting routine becomes stable, preserving + the order of equivalent elements. + + A namedtuple of (values, indices) is returned, where the `values` are the + sorted values and `indices` are the indices of the elements in the original + `input` tensor. + + Args: + input (Tensor): the input tensor. + dim (int, optional): the dimension to sort along + descending (bool, optional): controls the sorting order (ascending or descending) + + Keyword args: + stable (bool, optional): makes the sorting routine stable, which guarantees that the order + of equivalent elements is preserved. + out (tuple, optional): the output tuple of (`Tensor`, `LongTensor`) that can + be optionally given to be used as output buffers + + Example:: + + >>> x = torch.randn(3, 4) + >>> sorted, indices = torch.sort(x) + >>> sorted + tensor([[-0.2162, 0.0608, 0.6719, 2.3332], + [-0.5793, 0.0061, 0.6058, 0.9497], + [-0.5071, 0.3343, 0.9553, 1.0960]]) + >>> indices + tensor([[ 1, 0, 2, 3], + [ 3, 1, 0, 2], + [ 0, 3, 1, 2]]) + + >>> sorted, indices = torch.sort(x, 0) + >>> sorted + tensor([[-0.5071, -0.2162, 0.6719, -0.5793], + [ 0.0608, 0.0061, 0.9497, 0.3343], + [ 0.6058, 0.9553, 1.0960, 2.3332]]) + >>> indices + tensor([[ 2, 0, 0, 1], + [ 0, 1, 1, 2], + [ 1, 2, 2, 0]]) + >>> x = torch.tensor([0, 1] * 9) + >>> x.sort() + torch.return_types.sort( + values=tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1]), + indices=tensor([ 2, 16, 4, 6, 14, 8, 0, 10, 12, 9, 17, 15, 13, 11, 7, 5, 3, 1])) + >>> x.sort(stable=True) + torch.return_types.sort( + values=tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1]), + indices=tensor([ 0, 2, 4, 6, 8, 10, 12, 14, 16, 1, 3, 5, 7, 9, 11, 13, 15, 17])) + """ + +def sparse_bsc_tensor( + ccol_indices: Tensor | list, + row_indices: Tensor | list, + values: Tensor | list, + size: _size | None = None, + *, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + check_invariants: _bool | None = None, +) -> Tensor: + r""" + sparse_bsc_tensor(ccol_indices, row_indices, values, size=None, *, dtype=None, device=None, pin_memory=False, requires_grad=False, check_invariants=None) -> Tensor + + Constructs a :ref:`sparse tensor in BSC (Block Compressed Sparse + Column)) ` with specified 2-dimensional blocks at the + given :attr:`ccol_indices` and :attr:`row_indices`. Sparse matrix + multiplication operations in BSC format are typically faster than that + for sparse tensors in COO format. Make you have a look at :ref:`the + note on the data type of the indices `. + + .. note:: + + If the ``device`` argument is not specified the device of the given + :attr:`values` and indices tensor(s) must match. If, however, the + argument is specified the input Tensors will be converted to the + given device and in turn determine the device of the constructed + sparse tensor. + + Args: + ccol_indices (array_like): (B+1)-dimensional array of size + ``(*batchsize, ncolblocks + 1)``. The last element of each + batch is the number of non-zeros. This tensor encodes the + index in values and row_indices depending on where the given + column starts. Each successive number in the tensor subtracted + by the number before it denotes the number of elements in a + given column. + row_indices (array_like): Row block coordinates of each block in + values. (B+1)-dimensional tensor with the same length + as values. + values (array_list): Initial blocks for the tensor. Can be a list, + tuple, NumPy ``ndarray``, and other types that + represents a (1 + 2 + K)-dimensional tensor where ``K`` is the + number of dense dimensions. + size (list, tuple, :class:`torch.Size`, optional): Size of the + sparse tensor: ``(*batchsize, nrows * blocksize[0], ncols * + blocksize[1], *densesize)`` If not provided, the size will be + inferred as the minimum size big enough to hold all non-zero + blocks. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of + returned tensor. Default: if None, infers data type from + :attr:`values`. + device (:class:`torch.device`, optional): the desired device of + returned tensor. Default: if None, uses the current device + for the default tensor type (see + :func:`torch.set_default_device`). :attr:`device` will be + the CPU for CPU tensor types and the current CUDA device for + CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + check_invariants (bool, optional): If sparse tensor invariants are checked. + Default: as returned by :func:`torch.sparse.check_sparse_tensor_invariants.is_enabled`, + initially False. + + Example:: + + >>> ccol_indices = [0, 1, 2] + >>> row_indices = [0, 1] + >>> values = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]] + >>> torch.sparse_bsc_tensor(torch.tensor(ccol_indices, dtype=torch.int64), + ... torch.tensor(row_indices, dtype=torch.int64), + ... torch.tensor(values), dtype=torch.double) + tensor(ccol_indices=tensor([0, 1, 2]), + row_indices=tensor([0, 1]), + values=tensor([[[1., 2.], + [3., 4.]], + [[5., 6.], + [7., 8.]]]), size=(2, 2), nnz=2, dtype=torch.float64, + layout=torch.sparse_bsc) + """ + +def sparse_bsr_tensor( + crow_indices: Tensor | list, + col_indices: Tensor | list, + values: Tensor | list, + size: _size | None = None, + *, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + check_invariants: _bool | None = None, +) -> Tensor: + r""" + sparse_bsr_tensor(crow_indices, col_indices, values, size=None, *, dtype=None, device=None, pin_memory=False, requires_grad=False, check_invariants=None) -> Tensor + + Constructs a :ref:`sparse tensor in BSR (Block Compressed Sparse Row)) + ` with specified 2-dimensional blocks at the given + :attr:`crow_indices` and :attr:`col_indices`. Sparse matrix + multiplication operations in BSR format are typically faster than that + for sparse tensors in COO format. Make you have a look at :ref:`the + note on the data type of the indices `. + + .. note:: + + If the ``device`` argument is not specified the device of the given + :attr:`values` and indices tensor(s) must match. If, however, the + argument is specified the input Tensors will be converted to the + given device and in turn determine the device of the constructed + sparse tensor. + + Args: + crow_indices (array_like): (B+1)-dimensional array of size + ``(*batchsize, nrowblocks + 1)``. The last element of each + batch is the number of non-zeros. This tensor encodes the + block index in values and col_indices depending on where the + given row block starts. Each successive number in the tensor + subtracted by the number before it denotes the number of + blocks in a given row. + col_indices (array_like): Column block coordinates of each block + in values. (B+1)-dimensional tensor with the same length as + values. + values (array_list): Initial values for the tensor. Can be a list, + tuple, NumPy ``ndarray``, scalar, and other types that + represents a (1 + 2 + K)-dimensional tensor where ``K`` is the + number of dense dimensions. + size (list, tuple, :class:`torch.Size`, optional): Size of the + sparse tensor: ``(*batchsize, nrows * blocksize[0], ncols * + blocksize[1], *densesize)`` where ``blocksize == + values.shape[1:3]``. If not provided, the size will be + inferred as the minimum size big enough to hold all non-zero + blocks. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of + returned tensor. Default: if None, infers data type from + :attr:`values`. + device (:class:`torch.device`, optional): the desired device of + returned tensor. Default: if None, uses the current device + for the default tensor type (see + :func:`torch.set_default_device`). :attr:`device` will be + the CPU for CPU tensor types and the current CUDA device for + CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + check_invariants (bool, optional): If sparse tensor invariants are checked. + Default: as returned by :func:`torch.sparse.check_sparse_tensor_invariants.is_enabled`, + initially False. + + Example:: + + >>> crow_indices = [0, 1, 2] + >>> col_indices = [0, 1] + >>> values = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]] + >>> torch.sparse_bsr_tensor(torch.tensor(crow_indices, dtype=torch.int64), + ... torch.tensor(col_indices, dtype=torch.int64), + ... torch.tensor(values), dtype=torch.double) + tensor(crow_indices=tensor([0, 1, 2]), + col_indices=tensor([0, 1]), + values=tensor([[[1., 2.], + [3., 4.]], + [[5., 6.], + [7., 8.]]]), size=(2, 2), nnz=2, dtype=torch.float64, + layout=torch.sparse_bsr) + """ + +def sparse_compressed_tensor( + compressed_indices: Tensor | list, + plain_indices: Tensor | list, + values: Tensor | list, + size: _size | None = None, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + check_invariants: _bool | None = None, +) -> Tensor: + r""" + sparse_compressed_tensor(compressed_indices, plain_indices, values, size=None, *, dtype=None, layout=None, device=None, pin_memory=False, requires_grad=False, check_invariants=None) -> Tensor + + Constructs a :ref:`sparse tensor in Compressed Sparse format - CSR, + CSC, BSR, or BSC - ` with specified values at + the given :attr:`compressed_indices` and :attr:`plain_indices`. Sparse + matrix multiplication operations in Compressed Sparse format are + typically faster than that for sparse tensors in COO format. Make you + have a look at :ref:`the note on the data type of the indices + `. + + .. note:: + + If the ``device`` argument is not specified the device of the given + :attr:`values` and indices tensor(s) must match. If, however, the + argument is specified the input Tensors will be converted to the + given device and in turn determine the device of the constructed + sparse tensor. + + Args: + compressed_indices (array_like): (B+1)-dimensional array of size + ``(*batchsize, compressed_dim_size + 1)``. The last element of + each batch is the number of non-zero elements or blocks. This + tensor encodes the index in ``values`` and ``plain_indices`` + depending on where the given compressed dimension (row or + column) starts. Each successive number in the tensor + subtracted by the number before it denotes the number of + elements or blocks in a given compressed dimension. + plain_indices (array_like): Plain dimension (column or row) + coordinates of each element or block in values. (B+1)-dimensional + tensor with the same length as values. + + values (array_list): Initial values for the tensor. Can be a list, + tuple, NumPy ``ndarray``, scalar, and other types. that + represents a (1+K)-dimensional (for CSR and CSC layouts) or + (1+2+K)-dimensional tensor (for BSR and BSC layouts) where + ``K`` is the number of dense dimensions. + size (list, tuple, :class:`torch.Size`, optional): Size of the + sparse tensor: ``(*batchsize, nrows * blocksize[0], ncols * + blocksize[1], *densesize)`` where ``blocksize[0] == + blocksize[1] == 1`` for CSR and CSC formats. If not provided, + the size will be inferred as the minimum size big enough to + hold all non-zero elements or blocks. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of + returned tensor. Default: if None, infers data type from + :attr:`values`. + layout (:class:`torch.layout`, required): the desired layout of + returned tensor: :attr:`torch.sparse_csr`, + :attr:`torch.sparse_csc`, :attr:`torch.sparse_bsr`, or + :attr:`torch.sparse_bsc`. + device (:class:`torch.device`, optional): the desired device of + returned tensor. Default: if None, uses the current device + for the default tensor type (see + :func:`torch.set_default_device`). :attr:`device` will be + the CPU for CPU tensor types and the current CUDA device for + CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + check_invariants (bool, optional): If sparse tensor invariants are checked. + Default: as returned by :func:`torch.sparse.check_sparse_tensor_invariants.is_enabled`, + initially False. + + Example:: + + >>> compressed_indices = [0, 2, 4] + >>> plain_indices = [0, 1, 0, 1] + >>> values = [1, 2, 3, 4] + >>> torch.sparse_compressed_tensor(torch.tensor(compressed_indices, dtype=torch.int64), + ... torch.tensor(plain_indices, dtype=torch.int64), + ... torch.tensor(values), dtype=torch.double, layout=torch.sparse_csr) + tensor(crow_indices=tensor([0, 2, 4]), + col_indices=tensor([0, 1, 0, 1]), + values=tensor([1., 2., 3., 4.]), size=(2, 2), nnz=4, + dtype=torch.float64, layout=torch.sparse_csr) + """ + +def sparse_coo_tensor( + indices: Tensor, + values: Tensor | list, + size: _size | None = None, + *, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + check_invariants: _bool | None = None, + is_coalesced: _bool | None = None, +) -> Tensor: + r""" + sparse_coo_tensor(indices, values, size=None, *, dtype=None, device=None, pin_memory=False, requires_grad=False, check_invariants=None, is_coalesced=None) -> Tensor + + Constructs a :ref:`sparse tensor in COO(rdinate) format + ` with specified values at the given + :attr:`indices`. + + .. note:: + + This function returns an :ref:`uncoalesced tensor + ` when :attr:`is_coalesced` is + unspecified or ``None``. + + .. note:: + + If the ``device`` argument is not specified the device of the given + :attr:`values` and indices tensor(s) must match. If, however, the + argument is specified the input Tensors will be converted to the + given device and in turn determine the device of the constructed + sparse tensor. + + Args: + indices (array_like): Initial data for the tensor. Can be a list, tuple, + NumPy ``ndarray``, scalar, and other types. Will be cast to a :class:`torch.LongTensor` + internally. The indices are the coordinates of the non-zero values in the matrix, and thus + should be two-dimensional where the first dimension is the number of tensor dimensions and + the second dimension is the number of non-zero values. + values (array_like): Initial values for the tensor. Can be a list, tuple, + NumPy ``ndarray``, scalar, and other types. + size (list, tuple, or :class:`torch.Size`, optional): Size of the sparse tensor. If not + provided the size will be inferred as the minimum size big enough to hold all non-zero + elements. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if None, infers data type from :attr:`values`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if None, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + check_invariants (bool, optional): If sparse tensor invariants are checked. + Default: as returned by :func:`torch.sparse.check_sparse_tensor_invariants.is_enabled`, + initially False. + is_coalesced (bool, optional): When``True``, the caller is + responsible for providing tensor indices that correspond to a + coalesced tensor. If the :attr:`check_invariants` flag is + False, no error will be raised if the prerequisites are not + met and this will lead to silently incorrect results. To force + coalescion please use :meth:`coalesce` on the resulting + Tensor. + Default: None: except for trivial cases (e.g. nnz < 2) the + resulting Tensor has is_coalesced set to ``False```. + + Example:: + + >>> i = torch.tensor([[0, 1, 1], + ... [2, 0, 2]]) + >>> v = torch.tensor([3, 4, 5], dtype=torch.float32) + >>> torch.sparse_coo_tensor(i, v, [2, 4]) + tensor(indices=tensor([[0, 1, 1], + [2, 0, 2]]), + values=tensor([3., 4., 5.]), + size=(2, 4), nnz=3, layout=torch.sparse_coo) + + >>> torch.sparse_coo_tensor(i, v) # Shape inference + tensor(indices=tensor([[0, 1, 1], + [2, 0, 2]]), + values=tensor([3., 4., 5.]), + size=(2, 3), nnz=3, layout=torch.sparse_coo) + + >>> torch.sparse_coo_tensor(i, v, [2, 4], + ... dtype=torch.float64, + ... device=torch.device('cuda:0')) + tensor(indices=tensor([[0, 1, 1], + [2, 0, 2]]), + values=tensor([3., 4., 5.]), + device='cuda:0', size=(2, 4), nnz=3, dtype=torch.float64, + layout=torch.sparse_coo) + + # Create an empty sparse tensor with the following invariants: + # 1. sparse_dim + dense_dim = len(SparseTensor.shape) + # 2. SparseTensor._indices().shape = (sparse_dim, nnz) + # 3. SparseTensor._values().shape = (nnz, SparseTensor.shape[sparse_dim:]) + # + # For instance, to create an empty sparse tensor with nnz = 0, dense_dim = 0 and + # sparse_dim = 1 (hence indices is a 2D tensor of shape = (1, 0)) + >>> S = torch.sparse_coo_tensor(torch.empty([1, 0]), [], [1]) + tensor(indices=tensor([], size=(1, 0)), + values=tensor([], size=(0,)), + size=(1,), nnz=0, layout=torch.sparse_coo) + + # and to create an empty sparse tensor with nnz = 0, dense_dim = 1 and + # sparse_dim = 1 + >>> S = torch.sparse_coo_tensor(torch.empty([1, 0]), torch.empty([0, 2]), [1, 2]) + tensor(indices=tensor([], size=(1, 0)), + values=tensor([], size=(0, 2)), + size=(1, 2), nnz=0, layout=torch.sparse_coo) + + .. _torch.sparse: https://pytorch.org/docs/stable/sparse.html + """ + +def sparse_csc_tensor( + ccol_indices: Tensor | list, + row_indices: Tensor | list, + values: Tensor | list, + size: _size | None = None, + *, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + check_invariants: _bool | None = None, +) -> Tensor: + r""" + sparse_csc_tensor(ccol_indices, row_indices, values, size=None, *, dtype=None, device=None, pin_memory=False, requires_grad=False, check_invariants=None) -> Tensor + + Constructs a :ref:`sparse tensor in CSC (Compressed Sparse Column) + ` with specified values at the given + :attr:`ccol_indices` and :attr:`row_indices`. Sparse matrix + multiplication operations in CSC format are typically faster than that + for sparse tensors in COO format. Make you have a look at :ref:`the + note on the data type of the indices `. + + .. note:: + + If the ``device`` argument is not specified the device of the given + :attr:`values` and indices tensor(s) must match. If, however, the + argument is specified the input Tensors will be converted to the + given device and in turn determine the device of the constructed + sparse tensor. + + Args: + ccol_indices (array_like): (B+1)-dimensional array of size + ``(*batchsize, ncols + 1)``. The last element of each batch + is the number of non-zeros. This tensor encodes the index in + values and row_indices depending on where the given column + starts. Each successive number in the tensor subtracted by the + number before it denotes the number of elements in a given + column. + row_indices (array_like): Row coordinates of each element in + values. (B+1)-dimensional tensor with the same length as + values. + values (array_list): Initial values for the tensor. Can be a list, + tuple, NumPy ``ndarray``, scalar, and other types that + represents a (1+K)-dimensional tensor where ``K`` is the number + of dense dimensions. + size (list, tuple, :class:`torch.Size`, optional): Size of the + sparse tensor: ``(*batchsize, nrows, ncols, *densesize)``. If + not provided, the size will be inferred as the minimum size + big enough to hold all non-zero elements. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of + returned tensor. Default: if None, infers data type from + :attr:`values`. + device (:class:`torch.device`, optional): the desired device of + returned tensor. Default: if None, uses the current device + for the default tensor type (see + :func:`torch.set_default_device`). :attr:`device` will be + the CPU for CPU tensor types and the current CUDA device for + CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + check_invariants (bool, optional): If sparse tensor invariants are checked. + Default: as returned by :func:`torch.sparse.check_sparse_tensor_invariants.is_enabled`, + initially False. + + Example:: + + >>> ccol_indices = [0, 2, 4] + >>> row_indices = [0, 1, 0, 1] + >>> values = [1, 2, 3, 4] + >>> torch.sparse_csc_tensor(torch.tensor(ccol_indices, dtype=torch.int64), + ... torch.tensor(row_indices, dtype=torch.int64), + ... torch.tensor(values), dtype=torch.double) + tensor(ccol_indices=tensor([0, 2, 4]), + row_indices=tensor([0, 1, 0, 1]), + values=tensor([1., 2., 3., 4.]), size=(2, 2), nnz=4, + dtype=torch.float64, layout=torch.sparse_csc) + """ + +def sparse_csr_tensor( + crow_indices: Tensor | list, + col_indices: Tensor | list, + values: Tensor | list, + size: _size | None = None, + *, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + check_invariants: _bool | None = None, +) -> Tensor: + r""" + sparse_csr_tensor(crow_indices, col_indices, values, size=None, *, dtype=None, device=None, pin_memory=False, requires_grad=False, check_invariants=None) -> Tensor + + Constructs a :ref:`sparse tensor in CSR (Compressed Sparse Row) ` with specified + values at the given :attr:`crow_indices` and :attr:`col_indices`. Sparse matrix multiplication operations + in CSR format are typically faster than that for sparse tensors in COO format. Make you have a look + at :ref:`the note on the data type of the indices `. + + .. note:: + + If the ``device`` argument is not specified the device of the given + :attr:`values` and indices tensor(s) must match. If, however, the + argument is specified the input Tensors will be converted to the + given device and in turn determine the device of the constructed + sparse tensor. + + Args: + crow_indices (array_like): (B+1)-dimensional array of size + ``(*batchsize, nrows + 1)``. The last element of each batch + is the number of non-zeros. This tensor encodes the index in + values and col_indices depending on where the given row + starts. Each successive number in the tensor subtracted by the + number before it denotes the number of elements in a given + row. + col_indices (array_like): Column coordinates of each element in + values. (B+1)-dimensional tensor with the same length + as values. + values (array_list): Initial values for the tensor. Can be a list, + tuple, NumPy ``ndarray``, scalar, and other types that + represents a (1+K)-dimensional tensor where ``K`` is the number + of dense dimensions. + size (list, tuple, :class:`torch.Size`, optional): Size of the + sparse tensor: ``(*batchsize, nrows, ncols, *densesize)``. If + not provided, the size will be inferred as the minimum size + big enough to hold all non-zero elements. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of + returned tensor. Default: if None, infers data type from + :attr:`values`. + device (:class:`torch.device`, optional): the desired device of + returned tensor. Default: if None, uses the current device + for the default tensor type (see + :func:`torch.set_default_device`). :attr:`device` will be + the CPU for CPU tensor types and the current CUDA device for + CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + check_invariants (bool, optional): If sparse tensor invariants are checked. + Default: as returned by :func:`torch.sparse.check_sparse_tensor_invariants.is_enabled`, + initially False. + + Example:: + + >>> crow_indices = [0, 2, 4] + >>> col_indices = [0, 1, 0, 1] + >>> values = [1, 2, 3, 4] + >>> torch.sparse_csr_tensor(torch.tensor(crow_indices, dtype=torch.int64), + ... torch.tensor(col_indices, dtype=torch.int64), + ... torch.tensor(values), dtype=torch.double) + tensor(crow_indices=tensor([0, 2, 4]), + col_indices=tensor([0, 1, 0, 1]), + values=tensor([1., 2., 3., 4.]), size=(2, 2), nnz=4, + dtype=torch.float64, layout=torch.sparse_csr) + """ + +def split_copy( + input: Tensor, + split_size: _int | SymInt, + dim: _int = 0, + *, + out: tuple[Tensor, ...] | list[Tensor] | None = None, +) -> None: + r""" + Performs the same operation as :func:`torch.split`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def split_with_sizes( + input: Tensor, + split_sizes: Sequence[_int | SymInt], + dim: _int = 0, +) -> tuple[Tensor, ...]: ... +def split_with_sizes_copy( + input: Tensor, + split_sizes: Sequence[_int | SymInt], + dim: _int = 0, + *, + out: tuple[Tensor, ...] | list[Tensor] | None = None, +) -> None: + r""" + Performs the same operation as :func:`torch.split_with_sizes`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def spmm(input: Tensor, mat2: Tensor) -> Tensor: ... +def sqrt(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + sqrt(input, *, out=None) -> Tensor + + Returns a new tensor with the square-root of the elements of :attr:`input`. + + .. math:: + \text{out}_{i} = \sqrt{\text{input}_{i}} + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-2.0755, 1.0226, 0.0831, 0.4806]) + >>> torch.sqrt(a) + tensor([ nan, 1.0112, 0.2883, 0.6933]) + """ + +def sqrt_(input: Tensor) -> Tensor: ... +def square(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + square(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Returns a new tensor with the square of the elements of :attr:`input`. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-2.0755, 1.0226, 0.0831, 0.4806]) + >>> torch.square(a) + tensor([ 4.3077, 1.0457, 0.0069, 0.2310]) + """ + +def square_(input: Tensor) -> Tensor: ... +@overload +def squeeze(input: Tensor) -> Tensor: + r""" + squeeze(input: Tensor, dim: Optional[Union[int, List[int]]]) -> Tensor + + Returns a tensor with all specified dimensions of :attr:`input` of size `1` removed. + + For example, if `input` is of shape: + :math:`(A \times 1 \times B \times C \times 1 \times D)` then the `input.squeeze()` + will be of shape: :math:`(A \times B \times C \times D)`. + + When :attr:`dim` is given, a squeeze operation is done only in the given + dimension(s). If `input` is of shape: :math:`(A \times 1 \times B)`, + ``squeeze(input, 0)`` leaves the tensor unchanged, but ``squeeze(input, 1)`` + will squeeze the tensor to the shape :math:`(A \times B)`. + + .. note:: The returned tensor shares the storage with the input tensor, + so changing the contents of one will change the contents of the other. + + .. warning:: If the tensor has a batch dimension of size 1, then `squeeze(input)` + will also remove the batch dimension, which can lead to unexpected + errors. Consider specifying only the dims you wish to be squeezed. + + Args: + input (Tensor): the input tensor. + dim (int or tuple of ints, optional): if given, the input will be squeezed + only in the specified dimensions. + + .. versionchanged:: 2.0 + :attr:`dim` now accepts tuples of dimensions. + + Example:: + + >>> x = torch.zeros(2, 1, 2, 1, 2) + >>> x.size() + torch.Size([2, 1, 2, 1, 2]) + >>> y = torch.squeeze(x) + >>> y.size() + torch.Size([2, 2, 2]) + >>> y = torch.squeeze(x, 0) + >>> y.size() + torch.Size([2, 1, 2, 1, 2]) + >>> y = torch.squeeze(x, 1) + >>> y.size() + torch.Size([2, 2, 1, 2]) + >>> y = torch.squeeze(x, (1, 2, 3)) + torch.Size([2, 2, 2]) + """ + +@overload +def squeeze(input: Tensor, dim: _int) -> Tensor: + r""" + squeeze(input: Tensor, dim: Optional[Union[int, List[int]]]) -> Tensor + + Returns a tensor with all specified dimensions of :attr:`input` of size `1` removed. + + For example, if `input` is of shape: + :math:`(A \times 1 \times B \times C \times 1 \times D)` then the `input.squeeze()` + will be of shape: :math:`(A \times B \times C \times D)`. + + When :attr:`dim` is given, a squeeze operation is done only in the given + dimension(s). If `input` is of shape: :math:`(A \times 1 \times B)`, + ``squeeze(input, 0)`` leaves the tensor unchanged, but ``squeeze(input, 1)`` + will squeeze the tensor to the shape :math:`(A \times B)`. + + .. note:: The returned tensor shares the storage with the input tensor, + so changing the contents of one will change the contents of the other. + + .. warning:: If the tensor has a batch dimension of size 1, then `squeeze(input)` + will also remove the batch dimension, which can lead to unexpected + errors. Consider specifying only the dims you wish to be squeezed. + + Args: + input (Tensor): the input tensor. + dim (int or tuple of ints, optional): if given, the input will be squeezed + only in the specified dimensions. + + .. versionchanged:: 2.0 + :attr:`dim` now accepts tuples of dimensions. + + Example:: + + >>> x = torch.zeros(2, 1, 2, 1, 2) + >>> x.size() + torch.Size([2, 1, 2, 1, 2]) + >>> y = torch.squeeze(x) + >>> y.size() + torch.Size([2, 2, 2]) + >>> y = torch.squeeze(x, 0) + >>> y.size() + torch.Size([2, 1, 2, 1, 2]) + >>> y = torch.squeeze(x, 1) + >>> y.size() + torch.Size([2, 2, 1, 2]) + >>> y = torch.squeeze(x, (1, 2, 3)) + torch.Size([2, 2, 2]) + """ + +@overload +def squeeze(input: Tensor, dim: _size) -> Tensor: + r""" + squeeze(input: Tensor, dim: Optional[Union[int, List[int]]]) -> Tensor + + Returns a tensor with all specified dimensions of :attr:`input` of size `1` removed. + + For example, if `input` is of shape: + :math:`(A \times 1 \times B \times C \times 1 \times D)` then the `input.squeeze()` + will be of shape: :math:`(A \times B \times C \times D)`. + + When :attr:`dim` is given, a squeeze operation is done only in the given + dimension(s). If `input` is of shape: :math:`(A \times 1 \times B)`, + ``squeeze(input, 0)`` leaves the tensor unchanged, but ``squeeze(input, 1)`` + will squeeze the tensor to the shape :math:`(A \times B)`. + + .. note:: The returned tensor shares the storage with the input tensor, + so changing the contents of one will change the contents of the other. + + .. warning:: If the tensor has a batch dimension of size 1, then `squeeze(input)` + will also remove the batch dimension, which can lead to unexpected + errors. Consider specifying only the dims you wish to be squeezed. + + Args: + input (Tensor): the input tensor. + dim (int or tuple of ints, optional): if given, the input will be squeezed + only in the specified dimensions. + + .. versionchanged:: 2.0 + :attr:`dim` now accepts tuples of dimensions. + + Example:: + + >>> x = torch.zeros(2, 1, 2, 1, 2) + >>> x.size() + torch.Size([2, 1, 2, 1, 2]) + >>> y = torch.squeeze(x) + >>> y.size() + torch.Size([2, 2, 2]) + >>> y = torch.squeeze(x, 0) + >>> y.size() + torch.Size([2, 1, 2, 1, 2]) + >>> y = torch.squeeze(x, 1) + >>> y.size() + torch.Size([2, 2, 1, 2]) + >>> y = torch.squeeze(x, (1, 2, 3)) + torch.Size([2, 2, 2]) + """ + +@overload +def squeeze(input: Tensor, dim: str | EllipsisType | None) -> Tensor: + r""" + squeeze(input: Tensor, dim: Optional[Union[int, List[int]]]) -> Tensor + + Returns a tensor with all specified dimensions of :attr:`input` of size `1` removed. + + For example, if `input` is of shape: + :math:`(A \times 1 \times B \times C \times 1 \times D)` then the `input.squeeze()` + will be of shape: :math:`(A \times B \times C \times D)`. + + When :attr:`dim` is given, a squeeze operation is done only in the given + dimension(s). If `input` is of shape: :math:`(A \times 1 \times B)`, + ``squeeze(input, 0)`` leaves the tensor unchanged, but ``squeeze(input, 1)`` + will squeeze the tensor to the shape :math:`(A \times B)`. + + .. note:: The returned tensor shares the storage with the input tensor, + so changing the contents of one will change the contents of the other. + + .. warning:: If the tensor has a batch dimension of size 1, then `squeeze(input)` + will also remove the batch dimension, which can lead to unexpected + errors. Consider specifying only the dims you wish to be squeezed. + + Args: + input (Tensor): the input tensor. + dim (int or tuple of ints, optional): if given, the input will be squeezed + only in the specified dimensions. + + .. versionchanged:: 2.0 + :attr:`dim` now accepts tuples of dimensions. + + Example:: + + >>> x = torch.zeros(2, 1, 2, 1, 2) + >>> x.size() + torch.Size([2, 1, 2, 1, 2]) + >>> y = torch.squeeze(x) + >>> y.size() + torch.Size([2, 2, 2]) + >>> y = torch.squeeze(x, 0) + >>> y.size() + torch.Size([2, 1, 2, 1, 2]) + >>> y = torch.squeeze(x, 1) + >>> y.size() + torch.Size([2, 2, 1, 2]) + >>> y = torch.squeeze(x, (1, 2, 3)) + torch.Size([2, 2, 2]) + """ + +@overload +def squeeze_copy(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + Performs the same operation as :func:`torch.squeeze`, but all output tensors + are freshly created instead of aliasing the input. + """ + +@overload +def squeeze_copy( + input: Tensor, + dim: _int, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.squeeze`, but all output tensors + are freshly created instead of aliasing the input. + """ + +@overload +def squeeze_copy( + input: Tensor, + dim: _size, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.squeeze`, but all output tensors + are freshly created instead of aliasing the input. + """ + +@overload +def sspaddmm( + beta: Number | _complex, + self: Tensor, + alpha: Number | _complex, + mat1: Tensor, + mat2: Tensor, +) -> Tensor: + r""" + sspaddmm(input, mat1, mat2, *, beta=1, alpha=1, out=None) -> Tensor + + Matrix multiplies a sparse tensor :attr:`mat1` with a dense tensor + :attr:`mat2`, then adds the sparse tensor :attr:`input` to the result. + + Note: This function is equivalent to :func:`torch.addmm`, except + :attr:`input` and :attr:`mat1` are sparse. + + Args: + input (Tensor): a sparse matrix to be added + mat1 (Tensor): a sparse matrix to be matrix multiplied + mat2 (Tensor): a dense matrix to be matrix multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`mat` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + """ + +@overload +def sspaddmm( + input: Tensor, + mat1: Tensor, + mat2: Tensor, + *, + beta: Number | _complex = 1, + alpha: Number | _complex = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + sspaddmm(input, mat1, mat2, *, beta=1, alpha=1, out=None) -> Tensor + + Matrix multiplies a sparse tensor :attr:`mat1` with a dense tensor + :attr:`mat2`, then adds the sparse tensor :attr:`input` to the result. + + Note: This function is equivalent to :func:`torch.addmm`, except + :attr:`input` and :attr:`mat1` are sparse. + + Args: + input (Tensor): a sparse matrix to be added + mat1 (Tensor): a sparse matrix to be matrix multiplied + mat2 (Tensor): a dense matrix to be matrix multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`mat` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + """ + +@overload +def sspaddmm( + beta: Number | _complex, + self: Tensor, + mat1: Tensor, + mat2: Tensor, +) -> Tensor: + r""" + sspaddmm(input, mat1, mat2, *, beta=1, alpha=1, out=None) -> Tensor + + Matrix multiplies a sparse tensor :attr:`mat1` with a dense tensor + :attr:`mat2`, then adds the sparse tensor :attr:`input` to the result. + + Note: This function is equivalent to :func:`torch.addmm`, except + :attr:`input` and :attr:`mat1` are sparse. + + Args: + input (Tensor): a sparse matrix to be added + mat1 (Tensor): a sparse matrix to be matrix multiplied + mat2 (Tensor): a dense matrix to be matrix multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`mat` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + """ + +def stack( + tensors: tuple[Tensor, ...] | list[Tensor] | None, + dim: _int = 0, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + stack(tensors, dim=0, *, out=None) -> Tensor + + Concatenates a sequence of tensors along a new dimension. + + All tensors need to be of the same size. + + .. seealso:: + + :func:`torch.cat` concatenates the given sequence along an existing dimension. + + Arguments: + tensors (sequence of Tensors): sequence of tensors to concatenate + dim (int, optional): dimension to insert. Has to be between 0 and the number + of dimensions of concatenated tensors (inclusive). Default: 0 + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> x = torch.randn(2, 3) + >>> x + tensor([[ 0.3367, 0.1288, 0.2345], + [ 0.2303, -1.1229, -0.1863]]) + >>> torch.stack((x, x)) # same as torch.stack((x, x), dim=0) + tensor([[[ 0.3367, 0.1288, 0.2345], + [ 0.2303, -1.1229, -0.1863]], + + [[ 0.3367, 0.1288, 0.2345], + [ 0.2303, -1.1229, -0.1863]]]) + >>> torch.stack((x, x)).size() + torch.Size([2, 2, 3]) + >>> torch.stack((x, x), dim=1) + tensor([[[ 0.3367, 0.1288, 0.2345], + [ 0.3367, 0.1288, 0.2345]], + + [[ 0.2303, -1.1229, -0.1863], + [ 0.2303, -1.1229, -0.1863]]]) + >>> torch.stack((x, x), dim=2) + tensor([[[ 0.3367, 0.3367], + [ 0.1288, 0.1288], + [ 0.2345, 0.2345]], + + [[ 0.2303, 0.2303], + [-1.1229, -1.1229], + [-0.1863, -0.1863]]]) + >>> torch.stack((x, x), dim=-1) + tensor([[[ 0.3367, 0.3367], + [ 0.1288, 0.1288], + [ 0.2345, 0.2345]], + + [[ 0.2303, 0.2303], + [-1.1229, -1.1229], + [-0.1863, -0.1863]]]) + """ + +@overload +def std( + input: Tensor, + dim: _int | _size | None, + unbiased: _bool = True, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + std(input, dim=None, *, correction=1, keepdim=False, out=None) -> Tensor + + Calculates the standard deviation over the dimensions specified by :attr:`dim`. + :attr:`dim` can be a single dimension, list of dimensions, or ``None`` to + reduce over all dimensions. + + The standard deviation (:math:`\sigma`) is calculated as + + .. math:: \sigma = \sqrt{\frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2} + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.std(a, dim=1, keepdim=True) + tensor([[1.0311], + [0.7477], + [1.2204], + [0.9087]]) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def std( + input: Tensor, + dim: _int | _size | None = None, + *, + correction: Number | _complex | None = None, + keepdim: _bool = False, + out: Tensor | None = None, +) -> Tensor: + r""" + std(input, dim=None, *, correction=1, keepdim=False, out=None) -> Tensor + + Calculates the standard deviation over the dimensions specified by :attr:`dim`. + :attr:`dim` can be a single dimension, list of dimensions, or ``None`` to + reduce over all dimensions. + + The standard deviation (:math:`\sigma`) is calculated as + + .. math:: \sigma = \sqrt{\frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2} + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.std(a, dim=1, keepdim=True) + tensor([[1.0311], + [0.7477], + [1.2204], + [0.9087]]) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def std(input: Tensor, unbiased: _bool = True) -> Tensor: + r""" + std(input, dim=None, *, correction=1, keepdim=False, out=None) -> Tensor + + Calculates the standard deviation over the dimensions specified by :attr:`dim`. + :attr:`dim` can be a single dimension, list of dimensions, or ``None`` to + reduce over all dimensions. + + The standard deviation (:math:`\sigma`) is calculated as + + .. math:: \sigma = \sqrt{\frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2} + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.std(a, dim=1, keepdim=True) + tensor([[1.0311], + [0.7477], + [1.2204], + [0.9087]]) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def std( + input: Tensor, + dim: Sequence[str | EllipsisType | None], + *, + correction: Number | _complex | None = None, + keepdim: _bool = False, + out: Tensor | None = None, +) -> Tensor: + r""" + std(input, dim=None, *, correction=1, keepdim=False, out=None) -> Tensor + + Calculates the standard deviation over the dimensions specified by :attr:`dim`. + :attr:`dim` can be a single dimension, list of dimensions, or ``None`` to + reduce over all dimensions. + + The standard deviation (:math:`\sigma`) is calculated as + + .. math:: \sigma = \sqrt{\frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2} + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.std(a, dim=1, keepdim=True) + tensor([[1.0311], + [0.7477], + [1.2204], + [0.9087]]) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def std( + input: Tensor, + dim: Sequence[str | EllipsisType | None], + unbiased: _bool = True, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + std(input, dim=None, *, correction=1, keepdim=False, out=None) -> Tensor + + Calculates the standard deviation over the dimensions specified by :attr:`dim`. + :attr:`dim` can be a single dimension, list of dimensions, or ``None`` to + reduce over all dimensions. + + The standard deviation (:math:`\sigma`) is calculated as + + .. math:: \sigma = \sqrt{\frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2} + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.std(a, dim=1, keepdim=True) + tensor([[1.0311], + [0.7477], + [1.2204], + [0.9087]]) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def std_mean( + input: Tensor, + dim: _int | _size | None, + unbiased: _bool = True, + keepdim: _bool = False, +) -> tuple[Tensor, Tensor]: + r""" + std_mean(input, dim=None, *, correction=1, keepdim=False, out=None) -> (Tensor, Tensor) + + Calculates the standard deviation and mean over the dimensions specified by + :attr:`dim`. :attr:`dim` can be a single dimension, list of dimensions, or + ``None`` to reduce over all dimensions. + + The standard deviation (:math:`\sigma`) is calculated as + + .. math:: \sigma = \sqrt{\frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2} + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Returns: + A tuple (std, mean) containing the standard deviation and mean. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.std_mean(a, dim=0, keepdim=True) + (tensor([[1.2620, 1.0028, 1.0957, 0.6038]]), + tensor([[ 0.0645, 0.4485, 0.8707, -0.0665]])) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def std_mean( + input: Tensor, + dim: _int | _size | None = None, + *, + correction: Number | _complex | None = None, + keepdim: _bool = False, +) -> tuple[Tensor, Tensor]: + r""" + std_mean(input, dim=None, *, correction=1, keepdim=False, out=None) -> (Tensor, Tensor) + + Calculates the standard deviation and mean over the dimensions specified by + :attr:`dim`. :attr:`dim` can be a single dimension, list of dimensions, or + ``None`` to reduce over all dimensions. + + The standard deviation (:math:`\sigma`) is calculated as + + .. math:: \sigma = \sqrt{\frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2} + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Returns: + A tuple (std, mean) containing the standard deviation and mean. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.std_mean(a, dim=0, keepdim=True) + (tensor([[1.2620, 1.0028, 1.0957, 0.6038]]), + tensor([[ 0.0645, 0.4485, 0.8707, -0.0665]])) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def std_mean( + input: Tensor, + unbiased: _bool = True, +) -> tuple[Tensor, Tensor]: + r""" + std_mean(input, dim=None, *, correction=1, keepdim=False, out=None) -> (Tensor, Tensor) + + Calculates the standard deviation and mean over the dimensions specified by + :attr:`dim`. :attr:`dim` can be a single dimension, list of dimensions, or + ``None`` to reduce over all dimensions. + + The standard deviation (:math:`\sigma`) is calculated as + + .. math:: \sigma = \sqrt{\frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2} + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Returns: + A tuple (std, mean) containing the standard deviation and mean. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.std_mean(a, dim=0, keepdim=True) + (tensor([[1.2620, 1.0028, 1.0957, 0.6038]]), + tensor([[ 0.0645, 0.4485, 0.8707, -0.0665]])) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def std_mean( + input: Tensor, + dim: Sequence[str | EllipsisType | None], + *, + correction: Number | _complex | None = None, + keepdim: _bool = False, +) -> tuple[Tensor, Tensor]: + r""" + std_mean(input, dim=None, *, correction=1, keepdim=False, out=None) -> (Tensor, Tensor) + + Calculates the standard deviation and mean over the dimensions specified by + :attr:`dim`. :attr:`dim` can be a single dimension, list of dimensions, or + ``None`` to reduce over all dimensions. + + The standard deviation (:math:`\sigma`) is calculated as + + .. math:: \sigma = \sqrt{\frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2} + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Returns: + A tuple (std, mean) containing the standard deviation and mean. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.std_mean(a, dim=0, keepdim=True) + (tensor([[1.2620, 1.0028, 1.0957, 0.6038]]), + tensor([[ 0.0645, 0.4485, 0.8707, -0.0665]])) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def std_mean( + input: Tensor, + dim: Sequence[str | EllipsisType | None], + unbiased: _bool = True, + keepdim: _bool = False, +) -> tuple[Tensor, Tensor]: + r""" + std_mean(input, dim=None, *, correction=1, keepdim=False, out=None) -> (Tensor, Tensor) + + Calculates the standard deviation and mean over the dimensions specified by + :attr:`dim`. :attr:`dim` can be a single dimension, list of dimensions, or + ``None`` to reduce over all dimensions. + + The standard deviation (:math:`\sigma`) is calculated as + + .. math:: \sigma = \sqrt{\frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2} + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Returns: + A tuple (std, mean) containing the standard deviation and mean. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.std_mean(a, dim=0, keepdim=True) + (tensor([[1.2620, 1.0028, 1.0957, 0.6038]]), + tensor([[ 0.0645, 0.4485, 0.8707, -0.0665]])) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def sub( + input: Tensor | Number | _complex, + other: Tensor | Number | _complex, + *, + alpha: Number | _complex | None = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + sub(input, other, *, alpha=1, out=None) -> Tensor + + Subtracts :attr:`other`, scaled by :attr:`alpha`, from :attr:`input`. + + .. math:: + \text{{out}}_i = \text{{input}}_i - \text{{alpha}} \times \text{{other}}_i + + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer, float, and complex inputs. + + Args: + input (Tensor): the input tensor. + other (Tensor or Number): the tensor or number to subtract from :attr:`input`. + + Keyword args: + alpha (Number): the multiplier for :attr:`other`. + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor((1, 2)) + >>> b = torch.tensor((0, 1)) + >>> torch.sub(a, b, alpha=2) + tensor([1, 0]) + """ + +@overload +def sub(self: Tensor, alpha: Number | _complex, other: Tensor) -> Tensor: + r""" + sub(input, other, *, alpha=1, out=None) -> Tensor + + Subtracts :attr:`other`, scaled by :attr:`alpha`, from :attr:`input`. + + .. math:: + \text{{out}}_i = \text{{input}}_i - \text{{alpha}} \times \text{{other}}_i + + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer, float, and complex inputs. + + Args: + input (Tensor): the input tensor. + other (Tensor or Number): the tensor or number to subtract from :attr:`input`. + + Keyword args: + alpha (Number): the multiplier for :attr:`other`. + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor((1, 2)) + >>> b = torch.tensor((0, 1)) + >>> torch.sub(a, b, alpha=2) + tensor([1, 0]) + """ + +@overload +def sub( + self: Tensor, + alpha: Number | _complex, + other: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + sub(input, other, *, alpha=1, out=None) -> Tensor + + Subtracts :attr:`other`, scaled by :attr:`alpha`, from :attr:`input`. + + .. math:: + \text{{out}}_i = \text{{input}}_i - \text{{alpha}} \times \text{{other}}_i + + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer, float, and complex inputs. + + Args: + input (Tensor): the input tensor. + other (Tensor or Number): the tensor or number to subtract from :attr:`input`. + + Keyword args: + alpha (Number): the multiplier for :attr:`other`. + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor((1, 2)) + >>> b = torch.tensor((0, 1)) + >>> torch.sub(a, b, alpha=2) + tensor([1, 0]) + """ + +@overload +def subtract( + input: Tensor, + other: Tensor, + *, + alpha: Number | _complex = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + subtract(input, other, *, alpha=1, out=None) -> Tensor + + Alias for :func:`torch.sub`. + """ + +@overload +def subtract( + input: Tensor, + other: Number | _complex, + alpha: Number | _complex = 1, +) -> Tensor: + r""" + subtract(input, other, *, alpha=1, out=None) -> Tensor + + Alias for :func:`torch.sub`. + """ + +@overload +def sum(input: Tensor, *, dtype: _dtype | None = None) -> Tensor: + r""" + sum(input, *, dtype=None) -> Tensor + + Returns the sum of all elements in the :attr:`input` tensor. + + Args: + input (Tensor): the input tensor. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + + .. note:: Use the `dtype` argument if you need the result in a specific tensor type. + Otherwise, the result type may be automatically promoted (e.g., from `torch.int32` to `torch.int64`). + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.1133, -0.9567, 0.2958]]) + >>> torch.sum(a) + tensor(-0.5475) + + .. function:: sum(input, dim, keepdim=False, *, dtype=None) -> Tensor + :noindex: + + Returns the sum of each row of the :attr:`input` tensor in the given + dimension :attr:`dim`. If :attr:`dim` is a list of dimensions, + reduce over all of them. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.0569, -0.2475, 0.0737, -0.3429], + [-0.2993, 0.9138, 0.9337, -1.6864], + [ 0.1132, 0.7892, -0.1003, 0.5688], + [ 0.3637, -0.9906, -0.4752, -1.5197]]) + >>> torch.sum(a, 1) + tensor([-0.4598, -0.1381, 1.3708, -2.6217]) + >>> b = torch.arange(4 * 5 * 6).view(4, 5, 6) + >>> torch.sum(b, (2, 1)) + tensor([ 435., 1335., 2235., 3135.]) + """ + +@overload +def sum( + input: Tensor, + dim: _int | _size | None, + keepdim: _bool = False, + *, + dtype: _dtype | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + sum(input, *, dtype=None) -> Tensor + + Returns the sum of all elements in the :attr:`input` tensor. + + Args: + input (Tensor): the input tensor. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + + .. note:: Use the `dtype` argument if you need the result in a specific tensor type. + Otherwise, the result type may be automatically promoted (e.g., from `torch.int32` to `torch.int64`). + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.1133, -0.9567, 0.2958]]) + >>> torch.sum(a) + tensor(-0.5475) + + .. function:: sum(input, dim, keepdim=False, *, dtype=None) -> Tensor + :noindex: + + Returns the sum of each row of the :attr:`input` tensor in the given + dimension :attr:`dim`. If :attr:`dim` is a list of dimensions, + reduce over all of them. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.0569, -0.2475, 0.0737, -0.3429], + [-0.2993, 0.9138, 0.9337, -1.6864], + [ 0.1132, 0.7892, -0.1003, 0.5688], + [ 0.3637, -0.9906, -0.4752, -1.5197]]) + >>> torch.sum(a, 1) + tensor([-0.4598, -0.1381, 1.3708, -2.6217]) + >>> b = torch.arange(4 * 5 * 6).view(4, 5, 6) + >>> torch.sum(b, (2, 1)) + tensor([ 435., 1335., 2235., 3135.]) + """ + +@overload +def sum( + input: Tensor, + dim: Sequence[str | EllipsisType | None], + keepdim: _bool = False, + *, + dtype: _dtype | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + sum(input, *, dtype=None) -> Tensor + + Returns the sum of all elements in the :attr:`input` tensor. + + Args: + input (Tensor): the input tensor. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + + .. note:: Use the `dtype` argument if you need the result in a specific tensor type. + Otherwise, the result type may be automatically promoted (e.g., from `torch.int32` to `torch.int64`). + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.1133, -0.9567, 0.2958]]) + >>> torch.sum(a) + tensor(-0.5475) + + .. function:: sum(input, dim, keepdim=False, *, dtype=None) -> Tensor + :noindex: + + Returns the sum of each row of the :attr:`input` tensor in the given + dimension :attr:`dim`. If :attr:`dim` is a list of dimensions, + reduce over all of them. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.0569, -0.2475, 0.0737, -0.3429], + [-0.2993, 0.9138, 0.9337, -1.6864], + [ 0.1132, 0.7892, -0.1003, 0.5688], + [ 0.3637, -0.9906, -0.4752, -1.5197]]) + >>> torch.sum(a, 1) + tensor([-0.4598, -0.1381, 1.3708, -2.6217]) + >>> b = torch.arange(4 * 5 * 6).view(4, 5, 6) + >>> torch.sum(b, (2, 1)) + tensor([ 435., 1335., 2235., 3135.]) + """ + +def svd( + input: Tensor, + some: _bool = True, + compute_uv: _bool = True, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.svd: + r""" + svd(input, some=True, compute_uv=True, *, out=None) -> (Tensor, Tensor, Tensor) + + Computes the singular value decomposition of either a matrix or batch of + matrices :attr:`input`. The singular value decomposition is represented as a + namedtuple `(U, S, V)`, such that :attr:`input` :math:`= U \text{diag}(S) V^{\text{H}}`. + where :math:`V^{\text{H}}` is the transpose of `V` for real inputs, + and the conjugate transpose of `V` for complex inputs. + If :attr:`input` is a batch of matrices, then `U`, `S`, and `V` are also + batched with the same batch dimensions as :attr:`input`. + + If :attr:`some` is `True` (default), the method returns the reduced singular + value decomposition. In this case, if the last two dimensions of :attr:`input` are + `m` and `n`, then the returned `U` and `V` matrices will contain only + `min(n, m)` orthonormal columns. + + If :attr:`compute_uv` is `False`, the returned `U` and `V` will be + zero-filled matrices of shape `(m, m)` and `(n, n)` + respectively, and the same device as :attr:`input`. The argument :attr:`some` + has no effect when :attr:`compute_uv` is `False`. + + Supports :attr:`input` of float, double, cfloat and cdouble data types. + The dtypes of `U` and `V` are the same as :attr:`input`'s. `S` will + always be real-valued, even if :attr:`input` is complex. + + .. warning:: + + :func:`torch.svd` is deprecated in favor of :func:`torch.linalg.svd` + and will be removed in a future PyTorch release. + + ``U, S, V = torch.svd(A, some=some, compute_uv=True)`` (default) should be replaced with + + .. code:: python + + U, S, Vh = torch.linalg.svd(A, full_matrices=not some) + V = Vh.mH + + ``_, S, _ = torch.svd(A, some=some, compute_uv=False)`` should be replaced with + + .. code:: python + + S = torch.linalg.svdvals(A) + + .. note:: Differences with :func:`torch.linalg.svd`: + + * :attr:`some` is the opposite of + :func:`torch.linalg.svd`'s :attr:`full_matrices`. Note that + default value for both is `True`, so the default behavior is + effectively the opposite. + * :func:`torch.svd` returns `V`, whereas :func:`torch.linalg.svd` returns + `Vh`, that is, :math:`V^{\text{H}}`. + * If :attr:`compute_uv` is `False`, :func:`torch.svd` returns zero-filled + tensors for `U` and `Vh`, whereas :func:`torch.linalg.svd` returns + empty tensors. + + .. note:: The singular values are returned in descending order. If :attr:`input` is a batch of matrices, + then the singular values of each matrix in the batch are returned in descending order. + + .. note:: The `S` tensor can only be used to compute gradients if :attr:`compute_uv` is `True`. + + .. note:: When :attr:`some` is `False`, the gradients on `U[..., :, min(m, n):]` + and `V[..., :, min(m, n):]` will be ignored in the backward pass, as those vectors + can be arbitrary bases of the corresponding subspaces. + + .. note:: The implementation of :func:`torch.linalg.svd` on CPU uses LAPACK's routine `?gesdd` + (a divide-and-conquer algorithm) instead of `?gesvd` for speed. Analogously, + on GPU, it uses cuSOLVER's routines `gesvdj` and `gesvdjBatched` on CUDA 10.1.243 + and later, and MAGMA's routine `gesdd` on earlier versions of CUDA. + + .. note:: The returned `U` will not be contiguous. The matrix (or batch of matrices) will + be represented as a column-major matrix (i.e. Fortran-contiguous). + + .. warning:: The gradients with respect to `U` and `V` will only be finite when the input does not + have zero nor repeated singular values. + + .. warning:: If the distance between any two singular values is close to zero, the gradients with respect to + `U` and `V` will be numerically unstable, as they depends on + :math:`\frac{1}{\min_{i \neq j} \sigma_i^2 - \sigma_j^2}`. The same happens when the matrix + has small singular values, as these gradients also depend on `S^{-1}`. + + .. warning:: For complex-valued :attr:`input` the singular value decomposition is not unique, + as `U` and `V` may be multiplied by an arbitrary phase factor :math:`e^{i \phi}` on every column. + The same happens when :attr:`input` has repeated singular values, where one may multiply + the columns of the spanning subspace in `U` and `V` by a rotation matrix + and `the resulting vectors will span the same subspace`_. + Different platforms, like NumPy, or inputs on different device types, + may produce different `U` and `V` tensors. + + Args: + input (Tensor): the input tensor of size `(*, m, n)` where `*` is zero or more + batch dimensions consisting of `(m, n)` matrices. + some (bool, optional): controls whether to compute the reduced or full decomposition, and + consequently, the shape of returned `U` and `V`. Default: `True`. + compute_uv (bool, optional): controls whether to compute `U` and `V`. Default: `True`. + + Keyword args: + out (tuple, optional): the output tuple of tensors + + Example:: + + >>> a = torch.randn(5, 3) + >>> a + tensor([[ 0.2364, -0.7752, 0.6372], + [ 1.7201, 0.7394, -0.0504], + [-0.3371, -1.0584, 0.5296], + [ 0.3550, -0.4022, 1.5569], + [ 0.2445, -0.0158, 1.1414]]) + >>> u, s, v = torch.svd(a) + >>> u + tensor([[ 0.4027, 0.0287, 0.5434], + [-0.1946, 0.8833, 0.3679], + [ 0.4296, -0.2890, 0.5261], + [ 0.6604, 0.2717, -0.2618], + [ 0.4234, 0.2481, -0.4733]]) + >>> s + tensor([2.3289, 2.0315, 0.7806]) + >>> v + tensor([[-0.0199, 0.8766, 0.4809], + [-0.5080, 0.4054, -0.7600], + [ 0.8611, 0.2594, -0.4373]]) + >>> torch.dist(a, torch.mm(torch.mm(u, torch.diag(s)), v.t())) + tensor(8.6531e-07) + >>> a_big = torch.randn(7, 5, 3) + >>> u, s, v = torch.svd(a_big) + >>> torch.dist(a_big, torch.matmul(torch.matmul(u, torch.diag_embed(s)), v.mT)) + tensor(2.6503e-06) + + .. _the resulting vectors will span the same subspace: + (https://en.wikipedia.org/wiki/Singular_value_decomposition#Singular_values,_singular_vectors,_and_their_relation_to_the_SVD) + """ + +def swapaxes(input: Tensor, axis0: _int, axis1: _int) -> Tensor: + r""" + swapaxes(input, axis0, axis1) -> Tensor + + Alias for :func:`torch.transpose`. + + This function is equivalent to NumPy's swapaxes function. + + Examples:: + + >>> x = torch.tensor([[[0,1],[2,3]],[[4,5],[6,7]]]) + >>> x + tensor([[[0, 1], + [2, 3]], + + [[4, 5], + [6, 7]]]) + >>> torch.swapaxes(x, 0, 1) + tensor([[[0, 1], + [4, 5]], + + [[2, 3], + [6, 7]]]) + >>> torch.swapaxes(x, 0, 2) + tensor([[[0, 4], + [2, 6]], + + [[1, 5], + [3, 7]]]) + """ + +def swapdims(input: Tensor, dim0: _int, dim1: _int) -> Tensor: + r""" + swapdims(input, dim0, dim1) -> Tensor + + Alias for :func:`torch.transpose`. + + This function is equivalent to NumPy's swapaxes function. + + Examples:: + + >>> x = torch.tensor([[[0,1],[2,3]],[[4,5],[6,7]]]) + >>> x + tensor([[[0, 1], + [2, 3]], + + [[4, 5], + [6, 7]]]) + >>> torch.swapdims(x, 0, 1) + tensor([[[0, 1], + [4, 5]], + + [[2, 3], + [6, 7]]]) + >>> torch.swapdims(x, 0, 2) + tensor([[[0, 4], + [2, 6]], + + [[1, 5], + [3, 7]]]) + """ + +def sym_constrain_range( + size: Number | _complex, + *, + min: _int | None = None, + max: _int | None = None, +) -> None: ... +def sym_constrain_range_for_size( + size: Number | _complex, + *, + min: _int | None = None, + max: _int | None = None, +) -> None: ... +def t(input: Tensor) -> Tensor: + r""" + t(input) -> Tensor + + Expects :attr:`input` to be <= 2-D tensor and transposes dimensions 0 + and 1. + + 0-D and 1-D tensors are returned as is. When input is a 2-D tensor this + is equivalent to ``transpose(input, 0, 1)``. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> x = torch.randn(()) + >>> x + tensor(0.1995) + >>> torch.t(x) + tensor(0.1995) + >>> x = torch.randn(3) + >>> x + tensor([ 2.4320, -0.4608, 0.7702]) + >>> torch.t(x) + tensor([ 2.4320, -0.4608, 0.7702]) + >>> x = torch.randn(2, 3) + >>> x + tensor([[ 0.4875, 0.9158, -0.5872], + [ 0.3938, -0.6929, 0.6932]]) + >>> torch.t(x) + tensor([[ 0.4875, 0.3938], + [ 0.9158, -0.6929], + [-0.5872, 0.6932]]) + + See also :func:`torch.transpose`. + """ + +def t_copy(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + Performs the same operation as :func:`torch.t`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def take( + input: Tensor, + index: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + take(input, index) -> Tensor + + Returns a new tensor with the elements of :attr:`input` at the given indices. + The input tensor is treated as if it were viewed as a 1-D tensor. The result + takes the same shape as the indices. + + Args: + input (Tensor): the input tensor. + index (LongTensor): the indices into tensor + + Example:: + + >>> src = torch.tensor([[4, 3, 5], + ... [6, 7, 8]]) + >>> torch.take(src, torch.tensor([0, 2, 5])) + tensor([ 4, 5, 8]) + """ + +def take_along_dim( + input: Tensor, + indices: Tensor, + dim: _int | None = None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + take_along_dim(input, indices, dim=None, *, out=None) -> Tensor + + Selects values from :attr:`input` at the 1-dimensional indices from :attr:`indices` along the given :attr:`dim`. + + If :attr:`dim` is None, the input array is treated as if it has been flattened to 1d. + + Functions that return indices along a dimension, like :func:`torch.argmax` and :func:`torch.argsort`, + are designed to work with this function. See the examples below. + + .. note:: + This function is similar to NumPy's `take_along_axis`. + See also :func:`torch.gather`. + + Args: + input (Tensor): the input tensor. + indices (LongTensor): the indices into :attr:`input`. Must have long dtype. + dim (int, optional): dimension to select along. Default: 0 + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> t = torch.tensor([[10, 30, 20], [60, 40, 50]]) + >>> max_idx = torch.argmax(t) + >>> torch.take_along_dim(t, max_idx) + tensor([60]) + >>> sorted_idx = torch.argsort(t, dim=1) + >>> torch.take_along_dim(t, sorted_idx, dim=1) + tensor([[10, 20, 30], + [40, 50, 60]]) + """ + +def tan(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + tan(input, *, out=None) -> Tensor + + Returns a new tensor with the tangent of the elements in the :attr:`input` tensor, + where each value in this input tensor is in radians. + + .. math:: + \text{out}_{i} = \tan(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-1.2027, -1.7687, 0.4412, -1.3856]) + >>> torch.tan(a) + tensor([-2.5930, 4.9859, 0.4722, -5.3366]) + """ + +def tan_(input: Tensor) -> Tensor: ... +def tanh(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + tanh(input, *, out=None) -> Tensor + + Returns a new tensor with the hyperbolic tangent of the elements + of :attr:`input`. + + .. math:: + \text{out}_{i} = \tanh(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.8986, -0.7279, 1.1745, 0.2611]) + >>> torch.tanh(a) + tensor([ 0.7156, -0.6218, 0.8257, 0.2553]) + """ + +def tanh_(input: Tensor) -> Tensor: ... +def tensor( + data: Any, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + pin_memory: _bool = False, +) -> Tensor: + r""" + tensor(data, *, dtype=None, device=None, requires_grad=False, pin_memory=False) -> Tensor + + Constructs a tensor with no autograd history (also known as a "leaf tensor", see :doc:`/notes/autograd`) by copying :attr:`data`. + + .. warning:: + + When working with tensors prefer using :func:`torch.Tensor.clone`, + :func:`torch.Tensor.detach`, and :func:`torch.Tensor.requires_grad_` for + readability. Letting `t` be a tensor, ``torch.tensor(t)`` is equivalent to + ``t.detach().clone()``, and ``torch.tensor(t, requires_grad=True)`` + is equivalent to ``t.detach().clone().requires_grad_(True)``. + + .. seealso:: + + :func:`torch.as_tensor` preserves autograd history and avoids copies where possible. + :func:`torch.from_numpy` creates a tensor that shares storage with a NumPy array. + + Args: + data (array_like): Initial data for the tensor. Can be a list, tuple, + NumPy ``ndarray``, scalar, and other types. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, infers data type from :attr:`data`. + device (:class:`torch.device`, optional): the device of the constructed tensor. If None and data is a tensor + then the device of data is used. If None and data is not a tensor then + the result tensor is constructed on the current device. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + + Example:: + + >>> torch.tensor([[0.1, 1.2], [2.2, 3.1], [4.9, 5.2]]) + tensor([[ 0.1000, 1.2000], + [ 2.2000, 3.1000], + [ 4.9000, 5.2000]]) + + >>> torch.tensor([0, 1]) # Type inference on data + tensor([ 0, 1]) + + >>> torch.tensor([[0.11111, 0.222222, 0.3333333]], + ... dtype=torch.float64, + ... device=torch.device('cuda:0')) # creates a double tensor on a CUDA device + tensor([[ 0.1111, 0.2222, 0.3333]], dtype=torch.float64, device='cuda:0') + + >>> torch.tensor(3.14159) # Create a zero-dimensional (scalar) tensor + tensor(3.1416) + + >>> torch.tensor([]) # Create an empty tensor (of size (0,)) + tensor([]) + """ + +@overload +def tensor_split( + input: Tensor, + tensor_indices_or_sections: Tensor, + dim: _int = 0, +) -> tuple[Tensor, ...]: + r""" + tensor_split(input, indices_or_sections, dim=0) -> List of Tensors + + Splits a tensor into multiple sub-tensors, all of which are views of :attr:`input`, + along dimension :attr:`dim` according to the indices or number of sections specified + by :attr:`indices_or_sections`. This function is based on NumPy's + :func:`numpy.array_split`. + + Args: + input (Tensor): the tensor to split + indices_or_sections (Tensor, int or list or tuple of ints): + If :attr:`indices_or_sections` is an integer ``n`` or a zero dimensional long tensor + with value ``n``, :attr:`input` is split into ``n`` sections along dimension :attr:`dim`. + If :attr:`input` is divisible by ``n`` along dimension :attr:`dim`, each + section will be of equal size, :code:`input.size(dim) / n`. If :attr:`input` + is not divisible by ``n``, the sizes of the first :code:`int(input.size(dim) % n)` + sections will have size :code:`int(input.size(dim) / n) + 1`, and the rest will + have size :code:`int(input.size(dim) / n)`. + + If :attr:`indices_or_sections` is a list or tuple of ints, or a one-dimensional long + tensor, then :attr:`input` is split along dimension :attr:`dim` at each of the indices + in the list, tuple or tensor. For instance, :code:`indices_or_sections=[2, 3]` and :code:`dim=0` + would result in the tensors :code:`input[:2]`, :code:`input[2:3]`, and :code:`input[3:]`. + + If :attr:`indices_or_sections` is a tensor, it must be a zero-dimensional or one-dimensional + long tensor on the CPU. + + dim (int, optional): dimension along which to split the tensor. Default: ``0`` + + Example:: + + >>> x = torch.arange(8) + >>> torch.tensor_split(x, 3) + (tensor([0, 1, 2]), tensor([3, 4, 5]), tensor([6, 7])) + + >>> x = torch.arange(7) + >>> torch.tensor_split(x, 3) + (tensor([0, 1, 2]), tensor([3, 4]), tensor([5, 6])) + >>> torch.tensor_split(x, (1, 6)) + (tensor([0]), tensor([1, 2, 3, 4, 5]), tensor([6])) + + >>> x = torch.arange(14).reshape(2, 7) + >>> x + tensor([[ 0, 1, 2, 3, 4, 5, 6], + [ 7, 8, 9, 10, 11, 12, 13]]) + >>> torch.tensor_split(x, 3, dim=1) + (tensor([[0, 1, 2], + [7, 8, 9]]), + tensor([[ 3, 4], + [10, 11]]), + tensor([[ 5, 6], + [12, 13]])) + >>> torch.tensor_split(x, (1, 6), dim=1) + (tensor([[0], + [7]]), + tensor([[ 1, 2, 3, 4, 5], + [ 8, 9, 10, 11, 12]]), + tensor([[ 6], + [13]])) + """ + +@overload +def tensor_split( + input: Tensor, + sections: _int | SymInt, + dim: _int = 0, +) -> tuple[Tensor, ...]: + r""" + tensor_split(input, indices_or_sections, dim=0) -> List of Tensors + + Splits a tensor into multiple sub-tensors, all of which are views of :attr:`input`, + along dimension :attr:`dim` according to the indices or number of sections specified + by :attr:`indices_or_sections`. This function is based on NumPy's + :func:`numpy.array_split`. + + Args: + input (Tensor): the tensor to split + indices_or_sections (Tensor, int or list or tuple of ints): + If :attr:`indices_or_sections` is an integer ``n`` or a zero dimensional long tensor + with value ``n``, :attr:`input` is split into ``n`` sections along dimension :attr:`dim`. + If :attr:`input` is divisible by ``n`` along dimension :attr:`dim`, each + section will be of equal size, :code:`input.size(dim) / n`. If :attr:`input` + is not divisible by ``n``, the sizes of the first :code:`int(input.size(dim) % n)` + sections will have size :code:`int(input.size(dim) / n) + 1`, and the rest will + have size :code:`int(input.size(dim) / n)`. + + If :attr:`indices_or_sections` is a list or tuple of ints, or a one-dimensional long + tensor, then :attr:`input` is split along dimension :attr:`dim` at each of the indices + in the list, tuple or tensor. For instance, :code:`indices_or_sections=[2, 3]` and :code:`dim=0` + would result in the tensors :code:`input[:2]`, :code:`input[2:3]`, and :code:`input[3:]`. + + If :attr:`indices_or_sections` is a tensor, it must be a zero-dimensional or one-dimensional + long tensor on the CPU. + + dim (int, optional): dimension along which to split the tensor. Default: ``0`` + + Example:: + + >>> x = torch.arange(8) + >>> torch.tensor_split(x, 3) + (tensor([0, 1, 2]), tensor([3, 4, 5]), tensor([6, 7])) + + >>> x = torch.arange(7) + >>> torch.tensor_split(x, 3) + (tensor([0, 1, 2]), tensor([3, 4]), tensor([5, 6])) + >>> torch.tensor_split(x, (1, 6)) + (tensor([0]), tensor([1, 2, 3, 4, 5]), tensor([6])) + + >>> x = torch.arange(14).reshape(2, 7) + >>> x + tensor([[ 0, 1, 2, 3, 4, 5, 6], + [ 7, 8, 9, 10, 11, 12, 13]]) + >>> torch.tensor_split(x, 3, dim=1) + (tensor([[0, 1, 2], + [7, 8, 9]]), + tensor([[ 3, 4], + [10, 11]]), + tensor([[ 5, 6], + [12, 13]])) + >>> torch.tensor_split(x, (1, 6), dim=1) + (tensor([[0], + [7]]), + tensor([[ 1, 2, 3, 4, 5], + [ 8, 9, 10, 11, 12]]), + tensor([[ 6], + [13]])) + """ + +@overload +def tensor_split( + input: Tensor, + indices: Sequence[_int | SymInt], + dim: _int = 0, +) -> tuple[Tensor, ...]: + r""" + tensor_split(input, indices_or_sections, dim=0) -> List of Tensors + + Splits a tensor into multiple sub-tensors, all of which are views of :attr:`input`, + along dimension :attr:`dim` according to the indices or number of sections specified + by :attr:`indices_or_sections`. This function is based on NumPy's + :func:`numpy.array_split`. + + Args: + input (Tensor): the tensor to split + indices_or_sections (Tensor, int or list or tuple of ints): + If :attr:`indices_or_sections` is an integer ``n`` or a zero dimensional long tensor + with value ``n``, :attr:`input` is split into ``n`` sections along dimension :attr:`dim`. + If :attr:`input` is divisible by ``n`` along dimension :attr:`dim`, each + section will be of equal size, :code:`input.size(dim) / n`. If :attr:`input` + is not divisible by ``n``, the sizes of the first :code:`int(input.size(dim) % n)` + sections will have size :code:`int(input.size(dim) / n) + 1`, and the rest will + have size :code:`int(input.size(dim) / n)`. + + If :attr:`indices_or_sections` is a list or tuple of ints, or a one-dimensional long + tensor, then :attr:`input` is split along dimension :attr:`dim` at each of the indices + in the list, tuple or tensor. For instance, :code:`indices_or_sections=[2, 3]` and :code:`dim=0` + would result in the tensors :code:`input[:2]`, :code:`input[2:3]`, and :code:`input[3:]`. + + If :attr:`indices_or_sections` is a tensor, it must be a zero-dimensional or one-dimensional + long tensor on the CPU. + + dim (int, optional): dimension along which to split the tensor. Default: ``0`` + + Example:: + + >>> x = torch.arange(8) + >>> torch.tensor_split(x, 3) + (tensor([0, 1, 2]), tensor([3, 4, 5]), tensor([6, 7])) + + >>> x = torch.arange(7) + >>> torch.tensor_split(x, 3) + (tensor([0, 1, 2]), tensor([3, 4]), tensor([5, 6])) + >>> torch.tensor_split(x, (1, 6)) + (tensor([0]), tensor([1, 2, 3, 4, 5]), tensor([6])) + + >>> x = torch.arange(14).reshape(2, 7) + >>> x + tensor([[ 0, 1, 2, 3, 4, 5, 6], + [ 7, 8, 9, 10, 11, 12, 13]]) + >>> torch.tensor_split(x, 3, dim=1) + (tensor([[0, 1, 2], + [7, 8, 9]]), + tensor([[ 3, 4], + [10, 11]]), + tensor([[ 5, 6], + [12, 13]])) + >>> torch.tensor_split(x, (1, 6), dim=1) + (tensor([[0], + [7]]), + tensor([[ 1, 2, 3, 4, 5], + [ 8, 9, 10, 11, 12]]), + tensor([[ 6], + [13]])) + """ + +def threshold( + input: Tensor, + threshold: Number | _complex, + value: Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: ... +def threshold_( + input: Tensor, + threshold: Number | _complex, + value: Number | _complex, +) -> Tensor: ... +def tile(input: Tensor, dims: Sequence[_int | SymInt]) -> Tensor: + r""" + tile(input, dims) -> Tensor + + Constructs a tensor by repeating the elements of :attr:`input`. + The :attr:`dims` argument specifies the number of repetitions + in each dimension. + + If :attr:`dims` specifies fewer dimensions than :attr:`input` has, then + ones are prepended to :attr:`dims` until all dimensions are specified. + For example, if :attr:`input` has shape (8, 6, 4, 2) and :attr:`dims` + is (2, 2), then :attr:`dims` is treated as (1, 1, 2, 2). + + Analogously, if :attr:`input` has fewer dimensions than :attr:`dims` + specifies, then :attr:`input` is treated as if it were unsqueezed at + dimension zero until it has as many dimensions as :attr:`dims` specifies. + For example, if :attr:`input` has shape (4, 2) and :attr:`dims` + is (3, 3, 2, 2), then :attr:`input` is treated as if it had the + shape (1, 1, 4, 2). + + .. note:: + + This function is similar to NumPy's tile function. + + Args: + input (Tensor): the tensor whose elements to repeat. + dims (tuple): the number of repetitions per dimension. + + Example:: + + >>> x = torch.tensor([1, 2, 3]) + >>> x.tile((2,)) + tensor([1, 2, 3, 1, 2, 3]) + >>> y = torch.tensor([[1, 2], [3, 4]]) + >>> torch.tile(y, (2, 2)) + tensor([[1, 2, 1, 2], + [3, 4, 3, 4], + [1, 2, 1, 2], + [3, 4, 3, 4]]) + """ + +def topk( + input: Tensor, + k: _int | SymInt, + dim: _int = -1, + largest: _bool = True, + sorted: _bool = True, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.topk: + r""" + topk(input, k, dim=None, largest=True, sorted=True, *, out=None) -> (Tensor, LongTensor) + + Returns the :attr:`k` largest elements of the given :attr:`input` tensor along + a given dimension. + + If :attr:`dim` is not given, the last dimension of the `input` is chosen. + + If :attr:`largest` is ``False`` then the `k` smallest elements are returned. + + A namedtuple of `(values, indices)` is returned with the `values` and + `indices` of the largest `k` elements of each row of the `input` tensor in the + given dimension `dim`. + + The boolean option :attr:`sorted` if ``True``, will make sure that the returned + `k` elements are themselves sorted + + .. note:: + When using `torch.topk`, the indices of tied elements are not guaranteed to be stable + and may vary across different invocations. + + Args: + input (Tensor): the input tensor. + k (int): the k in "top-k" + dim (int, optional): the dimension to sort along + largest (bool, optional): controls whether to return largest or + smallest elements + sorted (bool, optional): controls whether to return the elements + in sorted order + + Keyword args: + out (tuple, optional): the output tuple of (Tensor, LongTensor) that can be + optionally given to be used as output buffers + + Example:: + + >>> x = torch.arange(1., 6.) + >>> x + tensor([ 1., 2., 3., 4., 5.]) + >>> torch.topk(x, 3) + torch.return_types.topk(values=tensor([5., 4., 3.]), indices=tensor([4, 3, 2])) + """ + +def trace(input: Tensor) -> Tensor: + r""" + trace(input) -> Tensor + + Returns the sum of the elements of the diagonal of the input 2-D matrix. + + Example:: + + >>> x = torch.arange(1., 10.).view(3, 3) + >>> x + tensor([[ 1., 2., 3.], + [ 4., 5., 6.], + [ 7., 8., 9.]]) + >>> torch.trace(x) + tensor(15.) + """ + +@overload +def transpose(input: Tensor, dim0: _int, dim1: _int) -> Tensor: + r""" + transpose(input, dim0, dim1) -> Tensor + + Returns a tensor that is a transposed version of :attr:`input`. + The given dimensions :attr:`dim0` and :attr:`dim1` are swapped. + + If :attr:`input` is a strided tensor then the resulting :attr:`out` + tensor shares its underlying storage with the :attr:`input` tensor, so + changing the content of one would change the content of the other. + + If :attr:`input` is a :ref:`sparse tensor ` then the + resulting :attr:`out` tensor *does not* share the underlying storage + with the :attr:`input` tensor. + + If :attr:`input` is a :ref:`sparse tensor ` with compressed + layout (SparseCSR, SparseBSR, SparseCSC or SparseBSC) the arguments + :attr:`dim0` and :attr:`dim1` must be both batch dimensions, or must + both be sparse dimensions. The batch dimensions of a sparse tensor are the + dimensions preceding the sparse dimensions. + + .. note:: + Transpositions which interchange the sparse dimensions of a `SparseCSR` + or `SparseCSC` layout tensor will result in the layout changing between + the two options. Transposition of the sparse dimensions of a ` SparseBSR` + or `SparseBSC` layout tensor will likewise generate a result with the + opposite layout. + + + Args: + input (Tensor): the input tensor. + dim0 (int): the first dimension to be transposed + dim1 (int): the second dimension to be transposed + + Example:: + + >>> x = torch.randn(2, 3) + >>> x + tensor([[ 1.0028, -0.9893, 0.5809], + [-0.1669, 0.7299, 0.4942]]) + >>> torch.transpose(x, 0, 1) + tensor([[ 1.0028, -0.1669], + [-0.9893, 0.7299], + [ 0.5809, 0.4942]]) + + See also :func:`torch.t`. + """ + +@overload +def transpose( + input: Tensor, + dim0: str | EllipsisType | None, + dim1: str | EllipsisType | None, +) -> Tensor: + r""" + transpose(input, dim0, dim1) -> Tensor + + Returns a tensor that is a transposed version of :attr:`input`. + The given dimensions :attr:`dim0` and :attr:`dim1` are swapped. + + If :attr:`input` is a strided tensor then the resulting :attr:`out` + tensor shares its underlying storage with the :attr:`input` tensor, so + changing the content of one would change the content of the other. + + If :attr:`input` is a :ref:`sparse tensor ` then the + resulting :attr:`out` tensor *does not* share the underlying storage + with the :attr:`input` tensor. + + If :attr:`input` is a :ref:`sparse tensor ` with compressed + layout (SparseCSR, SparseBSR, SparseCSC or SparseBSC) the arguments + :attr:`dim0` and :attr:`dim1` must be both batch dimensions, or must + both be sparse dimensions. The batch dimensions of a sparse tensor are the + dimensions preceding the sparse dimensions. + + .. note:: + Transpositions which interchange the sparse dimensions of a `SparseCSR` + or `SparseCSC` layout tensor will result in the layout changing between + the two options. Transposition of the sparse dimensions of a ` SparseBSR` + or `SparseBSC` layout tensor will likewise generate a result with the + opposite layout. + + + Args: + input (Tensor): the input tensor. + dim0 (int): the first dimension to be transposed + dim1 (int): the second dimension to be transposed + + Example:: + + >>> x = torch.randn(2, 3) + >>> x + tensor([[ 1.0028, -0.9893, 0.5809], + [-0.1669, 0.7299, 0.4942]]) + >>> torch.transpose(x, 0, 1) + tensor([[ 1.0028, -0.1669], + [-0.9893, 0.7299], + [ 0.5809, 0.4942]]) + + See also :func:`torch.t`. + """ + +def transpose_copy( + input: Tensor, + dim0: _int, + dim1: _int, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.transpose`, but all output tensors + are freshly created instead of aliasing the input. + """ + +@overload +def trapezoid(y: Tensor, x: Tensor, *, dim: _int = -1) -> Tensor: + r""" + trapezoid(y, x=None, *, dx=None, dim=-1) -> Tensor + + Computes the `trapezoidal rule `_ along + :attr:`dim`. By default the spacing between elements is assumed to be 1, but + :attr:`dx` can be used to specify a different constant spacing, and :attr:`x` can be + used to specify arbitrary spacing along :attr:`dim`. Only one of :attr:`x` or :attr:`dx` should be specified. + + + Assuming :attr:`y` is a one-dimensional tensor with elements :math:`{y_0, y_1, ..., y_n}`, + the default computation is + + .. math:: + \begin{aligned} + \sum_{i = 1}^{n} \frac{1}{2} (y_i + y_{i-1}) + \end{aligned} + + When :attr:`dx` is specified the computation becomes + + .. math:: + \begin{aligned} + \sum_{i = 1}^{n} \frac{\Delta x}{2} (y_i + y_{i-1}) + \end{aligned} + + effectively multiplying the result by :attr:`dx`. When :attr:`x` is specified, + assuming :attr:`x` is also a one-dimensional tensor with + elements :math:`{x_0, x_1, ..., x_n}`, the computation becomes + + .. math:: + \begin{aligned} + \sum_{i = 1}^{n} \frac{(x_i - x_{i-1})}{2} (y_i + y_{i-1}) + \end{aligned} + + When :attr:`x` and :attr:`y` have the same size, the computation is as described above and no broadcasting is needed. + The broadcasting behavior of this function is as follows when their sizes are different. For both :attr:`x` + and :attr:`y`, the function computes the difference between consecutive elements along + dimension :attr:`dim`. This effectively creates two tensors, `x_diff` and `y_diff`, that have + the same shape as the original tensors except their lengths along the dimension :attr:`dim` is reduced by 1. + After that, those two tensors are broadcast together to compute final output as part of the trapezoidal rule. + See the examples below for details. + + .. note:: + The trapezoidal rule is a technique for approximating the definite integral of a function + by averaging its left and right Riemann sums. The approximation becomes more accurate as + the resolution of the partition increases. + + Arguments: + y (Tensor): Values to use when computing the trapezoidal rule. + x (Tensor): If specified, defines spacing between values as specified above. + + Keyword arguments: + dx (float): constant spacing between values. If neither :attr:`x` or :attr:`dx` + are specified then this defaults to 1. Effectively multiplies the result by its value. + dim (int): The dimension along which to compute the trapezoidal rule. + The last (inner-most) dimension by default. + + Examples:: + + >>> # Computes the trapezoidal rule in 1D, spacing is implicitly 1 + >>> y = torch.tensor([1, 5, 10]) + >>> torch.trapezoid(y) + tensor(10.5) + + >>> # Computes the same trapezoidal rule directly to verify + >>> (1 + 10 + 10) / 2 + 10.5 + + >>> # Computes the trapezoidal rule in 1D with constant spacing of 2 + >>> # NOTE: the result is the same as before, but multiplied by 2 + >>> torch.trapezoid(y, dx=2) + 21.0 + + >>> # Computes the trapezoidal rule in 1D with arbitrary spacing + >>> x = torch.tensor([1, 3, 6]) + >>> torch.trapezoid(y, x) + 28.5 + + >>> # Computes the same trapezoidal rule directly to verify + >>> ((3 - 1) * (1 + 5) + (6 - 3) * (5 + 10)) / 2 + 28.5 + + >>> # Computes the trapezoidal rule for each row of a 3x3 matrix + >>> y = torch.arange(9).reshape(3, 3) + tensor([[0, 1, 2], + [3, 4, 5], + [6, 7, 8]]) + >>> torch.trapezoid(y) + tensor([ 2., 8., 14.]) + + >>> # Computes the trapezoidal rule for each column of the matrix + >>> torch.trapezoid(y, dim=0) + tensor([ 6., 8., 10.]) + + >>> # Computes the trapezoidal rule for each row of a 3x3 ones matrix + >>> # with the same arbitrary spacing + >>> y = torch.ones(3, 3) + >>> x = torch.tensor([1, 3, 6]) + >>> torch.trapezoid(y, x) + array([5., 5., 5.]) + + >>> # Computes the trapezoidal rule for each row of a 3x3 ones matrix + >>> # with different arbitrary spacing per row + >>> y = torch.ones(3, 3) + >>> x = torch.tensor([[1, 2, 3], [1, 3, 5], [1, 4, 7]]) + >>> torch.trapezoid(y, x) + array([2., 4., 6.]) + """ + +@overload +def trapezoid( + y: Tensor, + *, + dx: Number | _complex = 1, + dim: _int = -1, +) -> Tensor: + r""" + trapezoid(y, x=None, *, dx=None, dim=-1) -> Tensor + + Computes the `trapezoidal rule `_ along + :attr:`dim`. By default the spacing between elements is assumed to be 1, but + :attr:`dx` can be used to specify a different constant spacing, and :attr:`x` can be + used to specify arbitrary spacing along :attr:`dim`. Only one of :attr:`x` or :attr:`dx` should be specified. + + + Assuming :attr:`y` is a one-dimensional tensor with elements :math:`{y_0, y_1, ..., y_n}`, + the default computation is + + .. math:: + \begin{aligned} + \sum_{i = 1}^{n} \frac{1}{2} (y_i + y_{i-1}) + \end{aligned} + + When :attr:`dx` is specified the computation becomes + + .. math:: + \begin{aligned} + \sum_{i = 1}^{n} \frac{\Delta x}{2} (y_i + y_{i-1}) + \end{aligned} + + effectively multiplying the result by :attr:`dx`. When :attr:`x` is specified, + assuming :attr:`x` is also a one-dimensional tensor with + elements :math:`{x_0, x_1, ..., x_n}`, the computation becomes + + .. math:: + \begin{aligned} + \sum_{i = 1}^{n} \frac{(x_i - x_{i-1})}{2} (y_i + y_{i-1}) + \end{aligned} + + When :attr:`x` and :attr:`y` have the same size, the computation is as described above and no broadcasting is needed. + The broadcasting behavior of this function is as follows when their sizes are different. For both :attr:`x` + and :attr:`y`, the function computes the difference between consecutive elements along + dimension :attr:`dim`. This effectively creates two tensors, `x_diff` and `y_diff`, that have + the same shape as the original tensors except their lengths along the dimension :attr:`dim` is reduced by 1. + After that, those two tensors are broadcast together to compute final output as part of the trapezoidal rule. + See the examples below for details. + + .. note:: + The trapezoidal rule is a technique for approximating the definite integral of a function + by averaging its left and right Riemann sums. The approximation becomes more accurate as + the resolution of the partition increases. + + Arguments: + y (Tensor): Values to use when computing the trapezoidal rule. + x (Tensor): If specified, defines spacing between values as specified above. + + Keyword arguments: + dx (float): constant spacing between values. If neither :attr:`x` or :attr:`dx` + are specified then this defaults to 1. Effectively multiplies the result by its value. + dim (int): The dimension along which to compute the trapezoidal rule. + The last (inner-most) dimension by default. + + Examples:: + + >>> # Computes the trapezoidal rule in 1D, spacing is implicitly 1 + >>> y = torch.tensor([1, 5, 10]) + >>> torch.trapezoid(y) + tensor(10.5) + + >>> # Computes the same trapezoidal rule directly to verify + >>> (1 + 10 + 10) / 2 + 10.5 + + >>> # Computes the trapezoidal rule in 1D with constant spacing of 2 + >>> # NOTE: the result is the same as before, but multiplied by 2 + >>> torch.trapezoid(y, dx=2) + 21.0 + + >>> # Computes the trapezoidal rule in 1D with arbitrary spacing + >>> x = torch.tensor([1, 3, 6]) + >>> torch.trapezoid(y, x) + 28.5 + + >>> # Computes the same trapezoidal rule directly to verify + >>> ((3 - 1) * (1 + 5) + (6 - 3) * (5 + 10)) / 2 + 28.5 + + >>> # Computes the trapezoidal rule for each row of a 3x3 matrix + >>> y = torch.arange(9).reshape(3, 3) + tensor([[0, 1, 2], + [3, 4, 5], + [6, 7, 8]]) + >>> torch.trapezoid(y) + tensor([ 2., 8., 14.]) + + >>> # Computes the trapezoidal rule for each column of the matrix + >>> torch.trapezoid(y, dim=0) + tensor([ 6., 8., 10.]) + + >>> # Computes the trapezoidal rule for each row of a 3x3 ones matrix + >>> # with the same arbitrary spacing + >>> y = torch.ones(3, 3) + >>> x = torch.tensor([1, 3, 6]) + >>> torch.trapezoid(y, x) + array([5., 5., 5.]) + + >>> # Computes the trapezoidal rule for each row of a 3x3 ones matrix + >>> # with different arbitrary spacing per row + >>> y = torch.ones(3, 3) + >>> x = torch.tensor([[1, 2, 3], [1, 3, 5], [1, 4, 7]]) + >>> torch.trapezoid(y, x) + array([2., 4., 6.]) + """ + +@overload +def trapz(y: Tensor, *, dx: _float = 1, dim: _int = -1) -> Tensor: + r""" + trapz(y, x, *, dim=-1) -> Tensor + + Alias for :func:`torch.trapezoid`. + """ + +@overload +def trapz(y: Tensor, x: Tensor, *, dim: _int = -1) -> Tensor: + r""" + trapz(y, x, *, dim=-1) -> Tensor + + Alias for :func:`torch.trapezoid`. + """ + +def triangular_solve( + input: Tensor, + A: Tensor, + upper: _bool = True, + transpose: _bool = False, + unitriangular: _bool = False, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.triangular_solve: + r""" + triangular_solve(b, A, upper=True, transpose=False, unitriangular=False, *, out=None) -> (Tensor, Tensor) + + Solves a system of equations with a square upper or lower triangular invertible matrix :math:`A` + and multiple right-hand sides :math:`b`. + + In symbols, it solves :math:`AX = b` and assumes :math:`A` is square upper-triangular + (or lower-triangular if :attr:`upper`\ `= False`) and does not have zeros on the diagonal. + + `torch.triangular_solve(b, A)` can take in 2D inputs `b, A` or inputs that are + batches of 2D matrices. If the inputs are batches, then returns + batched outputs `X` + + If the diagonal of :attr:`A` contains zeros or elements that are very close to zero and + :attr:`unitriangular`\ `= False` (default) or if the input matrix is badly conditioned, + the result may contain `NaN` s. + + Supports input of float, double, cfloat and cdouble data types. + + .. warning:: + + :func:`torch.triangular_solve` is deprecated in favor of :func:`torch.linalg.solve_triangular` + and will be removed in a future PyTorch release. + :func:`torch.linalg.solve_triangular` has its arguments reversed and does not return a + copy of one of the inputs. + + ``X = torch.triangular_solve(B, A).solution`` should be replaced with + + .. code:: python + + X = torch.linalg.solve_triangular(A, B) + + Args: + b (Tensor): multiple right-hand sides of size :math:`(*, m, k)` where + :math:`*` is zero of more batch dimensions + A (Tensor): the input triangular coefficient matrix of size :math:`(*, m, m)` + where :math:`*` is zero or more batch dimensions + upper (bool, optional): whether :math:`A` is upper or lower triangular. Default: ``True``. + transpose (bool, optional): solves `op(A)X = b` where `op(A) = A^T` if this flag is ``True``, + and `op(A) = A` if it is ``False``. Default: ``False``. + unitriangular (bool, optional): whether :math:`A` is unit triangular. + If True, the diagonal elements of :math:`A` are assumed to be + 1 and not referenced from :math:`A`. Default: ``False``. + + Keyword args: + out ((Tensor, Tensor), optional): tuple of two tensors to write + the output to. Ignored if `None`. Default: `None`. + + Returns: + A namedtuple `(solution, cloned_coefficient)` where `cloned_coefficient` + is a clone of :math:`A` and `solution` is the solution :math:`X` to :math:`AX = b` + (or whatever variant of the system of equations, depending on the keyword arguments.) + + Examples:: + + >>> A = torch.randn(2, 2).triu() + >>> A + tensor([[ 1.1527, -1.0753], + [ 0.0000, 0.7986]]) + >>> b = torch.randn(2, 3) + >>> b + tensor([[-0.0210, 2.3513, -1.5492], + [ 1.5429, 0.7403, -1.0243]]) + >>> torch.triangular_solve(b, A) + torch.return_types.triangular_solve( + solution=tensor([[ 1.7841, 2.9046, -2.5405], + [ 1.9320, 0.9270, -1.2826]]), + cloned_coefficient=tensor([[ 1.1527, -1.0753], + [ 0.0000, 0.7986]])) + """ + +def tril( + input: Tensor, + diagonal: _int | SymInt = 0, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + tril(input, diagonal=0, *, out=None) -> Tensor + + Returns the lower triangular part of the matrix (2-D tensor) or batch of matrices + :attr:`input`, the other elements of the result tensor :attr:`out` are set to 0. + + The lower triangular part of the matrix is defined as the elements on and + below the diagonal. + + The argument :attr:`diagonal` controls which diagonal to consider. If + :attr:`diagonal` = 0, all elements on and below the main diagonal are + retained. A positive value includes just as many diagonals above the main + diagonal, and similarly a negative value excludes just as many diagonals below + the main diagonal. The main diagonal are the set of indices + :math:`\lbrace (i, i) \rbrace` for :math:`i \in [0, \min\{d_{1}, d_{2}\} - 1]` where + :math:`d_{1}, d_{2}` are the dimensions of the matrix. + + Args: + input (Tensor): the input tensor. + diagonal (int, optional): the diagonal to consider + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(3, 3) + >>> a + tensor([[-1.0813, -0.8619, 0.7105], + [ 0.0935, 0.1380, 2.2112], + [-0.3409, -0.9828, 0.0289]]) + >>> torch.tril(a) + tensor([[-1.0813, 0.0000, 0.0000], + [ 0.0935, 0.1380, 0.0000], + [-0.3409, -0.9828, 0.0289]]) + + >>> b = torch.randn(4, 6) + >>> b + tensor([[ 1.2219, 0.5653, -0.2521, -0.2345, 1.2544, 0.3461], + [ 0.4785, -0.4477, 0.6049, 0.6368, 0.8775, 0.7145], + [ 1.1502, 3.2716, -1.1243, -0.5413, 0.3615, 0.6864], + [-0.0614, -0.7344, -1.3164, -0.7648, -1.4024, 0.0978]]) + >>> torch.tril(b, diagonal=1) + tensor([[ 1.2219, 0.5653, 0.0000, 0.0000, 0.0000, 0.0000], + [ 0.4785, -0.4477, 0.6049, 0.0000, 0.0000, 0.0000], + [ 1.1502, 3.2716, -1.1243, -0.5413, 0.0000, 0.0000], + [-0.0614, -0.7344, -1.3164, -0.7648, -1.4024, 0.0000]]) + >>> torch.tril(b, diagonal=-1) + tensor([[ 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000], + [ 0.4785, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000], + [ 1.1502, 3.2716, 0.0000, 0.0000, 0.0000, 0.0000], + [-0.0614, -0.7344, -1.3164, 0.0000, 0.0000, 0.0000]]) + """ + +def tril_indices( + row: _int, + col: _int, + offset: _int = 0, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + tril_indices(row, col, offset=0, *, dtype=torch.long, device='cpu', layout=torch.strided) -> Tensor + + Returns the indices of the lower triangular part of a :attr:`row`-by- + :attr:`col` matrix in a 2-by-N Tensor, where the first row contains row + coordinates of all indices and the second row contains column coordinates. + Indices are ordered based on rows and then columns. + + The lower triangular part of the matrix is defined as the elements on and + below the diagonal. + + The argument :attr:`offset` controls which diagonal to consider. If + :attr:`offset` = 0, all elements on and below the main diagonal are + retained. A positive value includes just as many diagonals above the main + diagonal, and similarly a negative value excludes just as many diagonals below + the main diagonal. The main diagonal are the set of indices + :math:`\lbrace (i, i) \rbrace` for :math:`i \in [0, \min\{d_{1}, d_{2}\} - 1]` + where :math:`d_{1}, d_{2}` are the dimensions of the matrix. + + .. note:: + When running on CUDA, ``row * col`` must be less than :math:`2^{59}` to + prevent overflow during calculation. + + Args: + row (``int``): number of rows in the 2-D matrix. + col (``int``): number of columns in the 2-D matrix. + offset (``int``): diagonal offset from the main diagonal. + Default: if not provided, 0. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor, + only support ``torch.int``, ``torch.long``. Default: if ``None``, ``torch.long``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + layout (:class:`torch.layout`, optional): currently only support ``torch.strided``. + + Example:: + + >>> a = torch.tril_indices(3, 3) + >>> a + tensor([[0, 1, 1, 2, 2, 2], + [0, 0, 1, 0, 1, 2]]) + + >>> a = torch.tril_indices(4, 3, -1) + >>> a + tensor([[1, 2, 2, 3, 3, 3], + [0, 0, 1, 0, 1, 2]]) + + >>> a = torch.tril_indices(4, 3, 1) + >>> a + tensor([[0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3], + [0, 1, 0, 1, 2, 0, 1, 2, 0, 1, 2]]) + """ + +def triplet_margin_loss( + anchor: Tensor, + positive: Tensor, + negative: Tensor, + margin: _float = 1.0, + p: _float = 2, + eps: _float = 1e-06, + swap: _bool = False, + reduction: _int = 1, +) -> Tensor: ... +def triu( + input: Tensor, + diagonal: _int | SymInt = 0, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + triu(input, diagonal=0, *, out=None) -> Tensor + + Returns the upper triangular part of a matrix (2-D tensor) or batch of matrices + :attr:`input`, the other elements of the result tensor :attr:`out` are set to 0. + + The upper triangular part of the matrix is defined as the elements on and + above the diagonal. + + The argument :attr:`diagonal` controls which diagonal to consider. If + :attr:`diagonal` = 0, all elements on and above the main diagonal are + retained. A positive value excludes just as many diagonals above the main + diagonal, and similarly a negative value includes just as many diagonals below + the main diagonal. The main diagonal are the set of indices + :math:`\lbrace (i, i) \rbrace` for :math:`i \in [0, \min\{d_{1}, d_{2}\} - 1]` where + :math:`d_{1}, d_{2}` are the dimensions of the matrix. + + Args: + input (Tensor): the input tensor. + diagonal (int, optional): the diagonal to consider + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(3, 3) + >>> a + tensor([[ 0.2309, 0.5207, 2.0049], + [ 0.2072, -1.0680, 0.6602], + [ 0.3480, -0.5211, -0.4573]]) + >>> torch.triu(a) + tensor([[ 0.2309, 0.5207, 2.0049], + [ 0.0000, -1.0680, 0.6602], + [ 0.0000, 0.0000, -0.4573]]) + >>> torch.triu(a, diagonal=1) + tensor([[ 0.0000, 0.5207, 2.0049], + [ 0.0000, 0.0000, 0.6602], + [ 0.0000, 0.0000, 0.0000]]) + >>> torch.triu(a, diagonal=-1) + tensor([[ 0.2309, 0.5207, 2.0049], + [ 0.2072, -1.0680, 0.6602], + [ 0.0000, -0.5211, -0.4573]]) + + >>> b = torch.randn(4, 6) + >>> b + tensor([[ 0.5876, -0.0794, -1.8373, 0.6654, 0.2604, 1.5235], + [-0.2447, 0.9556, -1.2919, 1.3378, -0.1768, -1.0857], + [ 0.4333, 0.3146, 0.6576, -1.0432, 0.9348, -0.4410], + [-0.9888, 1.0679, -1.3337, -1.6556, 0.4798, 0.2830]]) + >>> torch.triu(b, diagonal=1) + tensor([[ 0.0000, -0.0794, -1.8373, 0.6654, 0.2604, 1.5235], + [ 0.0000, 0.0000, -1.2919, 1.3378, -0.1768, -1.0857], + [ 0.0000, 0.0000, 0.0000, -1.0432, 0.9348, -0.4410], + [ 0.0000, 0.0000, 0.0000, 0.0000, 0.4798, 0.2830]]) + >>> torch.triu(b, diagonal=-1) + tensor([[ 0.5876, -0.0794, -1.8373, 0.6654, 0.2604, 1.5235], + [-0.2447, 0.9556, -1.2919, 1.3378, -0.1768, -1.0857], + [ 0.0000, 0.3146, 0.6576, -1.0432, 0.9348, -0.4410], + [ 0.0000, 0.0000, -1.3337, -1.6556, 0.4798, 0.2830]]) + """ + +def triu_indices( + row: _int, + col: _int, + offset: _int = 0, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + triu_indices(row, col, offset=0, *, dtype=torch.long, device='cpu', layout=torch.strided) -> Tensor + + Returns the indices of the upper triangular part of a :attr:`row` by + :attr:`col` matrix in a 2-by-N Tensor, where the first row contains row + coordinates of all indices and the second row contains column coordinates. + Indices are ordered based on rows and then columns. + + The upper triangular part of the matrix is defined as the elements on and + above the diagonal. + + The argument :attr:`offset` controls which diagonal to consider. If + :attr:`offset` = 0, all elements on and above the main diagonal are + retained. A positive value excludes just as many diagonals above the main + diagonal, and similarly a negative value includes just as many diagonals below + the main diagonal. The main diagonal are the set of indices + :math:`\lbrace (i, i) \rbrace` for :math:`i \in [0, \min\{d_{1}, d_{2}\} - 1]` + where :math:`d_{1}, d_{2}` are the dimensions of the matrix. + + .. note:: + When running on CUDA, ``row * col`` must be less than :math:`2^{59}` to + prevent overflow during calculation. + + Args: + row (``int``): number of rows in the 2-D matrix. + col (``int``): number of columns in the 2-D matrix. + offset (``int``): diagonal offset from the main diagonal. + Default: if not provided, 0. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor, + only support ``torch.int``, ``torch.long``. Default: if ``None``, ``torch.long``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + layout (:class:`torch.layout`, optional): currently only support ``torch.strided``. + + Example:: + + >>> a = torch.triu_indices(3, 3) + >>> a + tensor([[0, 0, 0, 1, 1, 2], + [0, 1, 2, 1, 2, 2]]) + + >>> a = torch.triu_indices(4, 3, -1) + >>> a + tensor([[0, 0, 0, 1, 1, 1, 2, 2, 3], + [0, 1, 2, 0, 1, 2, 1, 2, 2]]) + + >>> a = torch.triu_indices(4, 3, 1) + >>> a + tensor([[0, 0, 1], + [1, 2, 2]]) + """ + +def true_divide( + input: Tensor | Number, + other: Tensor | Number, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + true_divide(dividend, divisor, *, out) -> Tensor + + Alias for :func:`torch.div` with ``rounding_mode=None``. + """ + +def trunc(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + trunc(input, *, out=None) -> Tensor + + Returns a new tensor with the truncated integer values of + the elements of :attr:`input`. + + For integer inputs, follows the array-api convention of returning a + copy of the input tensor. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 3.4742, 0.5466, -0.8008, -0.9079]) + >>> torch.trunc(a) + tensor([ 3., 0., -0., -0.]) + """ + +def trunc_(input: Tensor) -> Tensor: ... +@overload +def unbind(input: Tensor, dim: _int = 0) -> tuple[Tensor, ...]: + r""" + unbind(input, dim=0) -> seq + + Removes a tensor dimension. + + Returns a tuple of all slices along a given dimension, already without it. + + Arguments: + input (Tensor): the tensor to unbind + dim (int): dimension to remove + + Example:: + + >>> torch.unbind(torch.tensor([[1, 2, 3], + >>> [4, 5, 6], + >>> [7, 8, 9]])) + (tensor([1, 2, 3]), tensor([4, 5, 6]), tensor([7, 8, 9])) + """ + +@overload +def unbind( + input: Tensor, + dim: str | EllipsisType | None, +) -> tuple[Tensor, ...]: + r""" + unbind(input, dim=0) -> seq + + Removes a tensor dimension. + + Returns a tuple of all slices along a given dimension, already without it. + + Arguments: + input (Tensor): the tensor to unbind + dim (int): dimension to remove + + Example:: + + >>> torch.unbind(torch.tensor([[1, 2, 3], + >>> [4, 5, 6], + >>> [7, 8, 9]])) + (tensor([1, 2, 3]), tensor([4, 5, 6]), tensor([7, 8, 9])) + """ + +def unbind_copy( + input: Tensor, + dim: _int = 0, + *, + out: tuple[Tensor, ...] | list[Tensor] | None = None, +) -> None: + r""" + Performs the same operation as :func:`torch.unbind`, but all output tensors + are freshly created instead of aliasing the input. + """ + +@overload +def unflatten( + input: Tensor, + dim: str | EllipsisType | None, + sizes: Sequence[_int | SymInt], + names: Sequence[str | EllipsisType | None], +) -> Tensor: + r""" + unflatten(input, dim, sizes) -> Tensor + + Expands a dimension of the input tensor over multiple dimensions. + + .. seealso:: + + :func:`torch.flatten` the inverse of this function. It coalesces several dimensions into one. + + Args: + input (Tensor): the input tensor. + dim (int): Dimension to be unflattened, specified as an index into + ``input.shape``. + sizes (Tuple[int]): New shape of the unflattened dimension. + One of its elements can be `-1` in which case the corresponding output + dimension is inferred. Otherwise, the product of ``sizes`` *must* + equal ``input.shape[dim]``. + + Returns: + A View of input with the specified dimension unflattened. + + Examples:: + >>> torch.unflatten(torch.randn(3, 4, 1), 1, (2, 2)).shape + torch.Size([3, 2, 2, 1]) + >>> torch.unflatten(torch.randn(3, 4, 1), 1, (-1, 2)).shape + torch.Size([3, 2, 2, 1]) + >>> torch.unflatten(torch.randn(5, 12, 3), -2, (2, 2, 3, 1, 1)).shape + torch.Size([5, 2, 2, 3, 1, 1, 3]) + """ + +@overload +def unflatten( + input: Tensor, + dim: _int, + sizes: Sequence[_int | SymInt], +) -> Tensor: + r""" + unflatten(input, dim, sizes) -> Tensor + + Expands a dimension of the input tensor over multiple dimensions. + + .. seealso:: + + :func:`torch.flatten` the inverse of this function. It coalesces several dimensions into one. + + Args: + input (Tensor): the input tensor. + dim (int): Dimension to be unflattened, specified as an index into + ``input.shape``. + sizes (Tuple[int]): New shape of the unflattened dimension. + One of its elements can be `-1` in which case the corresponding output + dimension is inferred. Otherwise, the product of ``sizes`` *must* + equal ``input.shape[dim]``. + + Returns: + A View of input with the specified dimension unflattened. + + Examples:: + >>> torch.unflatten(torch.randn(3, 4, 1), 1, (2, 2)).shape + torch.Size([3, 2, 2, 1]) + >>> torch.unflatten(torch.randn(3, 4, 1), 1, (-1, 2)).shape + torch.Size([3, 2, 2, 1]) + >>> torch.unflatten(torch.randn(5, 12, 3), -2, (2, 2, 3, 1, 1)).shape + torch.Size([5, 2, 2, 3, 1, 1, 3]) + """ + +def unfold_copy( + input: Tensor, + dimension: _int, + size: _int, + step: _int, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.unfold`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def unique_dim( + input: Tensor, + dim: _int, + sorted: _bool = True, + return_inverse: _bool = False, + return_counts: _bool = False, +) -> tuple[Tensor, Tensor, Tensor]: ... +def unsafe_chunk( + input: Tensor, + chunks: _int, + dim: _int = 0, +) -> tuple[Tensor, ...]: + r""" + unsafe_chunk(input, chunks, dim=0) -> List of Tensors + + Works like :func:`torch.chunk` but without enforcing the autograd restrictions + on inplace modification of the outputs. + + .. warning:: + This function is safe to use as long as only the input, or only the outputs + are modified inplace after calling this function. It is user's + responsibility to ensure that is the case. If both the input and one or more + of the outputs are modified inplace, gradients computed by autograd will be + silently incorrect. + """ + +def unsafe_split( + input: Tensor, + split_size: _int | SymInt, + dim: _int = 0, +) -> tuple[Tensor, ...]: + r""" + unsafe_split(tensor, split_size_or_sections, dim=0) -> List of Tensors + + Works like :func:`torch.split` but without enforcing the autograd restrictions + on inplace modification of the outputs. + + .. warning:: + This function is safe to use as long as only the input, or only the outputs + are modified inplace after calling this function. It is user's + responsibility to ensure that is the case. If both the input and one or more + of the outputs are modified inplace, gradients computed by autograd will be + silently incorrect. + """ + +def unsafe_split_with_sizes( + input: Tensor, + split_sizes: Sequence[_int | SymInt], + dim: _int = 0, +) -> tuple[Tensor, ...]: ... +def unsqueeze(input: Tensor, dim: _int) -> Tensor: + r""" + unsqueeze(input, dim) -> Tensor + + Returns a new tensor with a dimension of size one inserted at the + specified position. + + The returned tensor shares the same underlying data with this tensor. + + A :attr:`dim` value within the range ``[-input.dim() - 1, input.dim() + 1)`` + can be used. Negative :attr:`dim` will correspond to :meth:`unsqueeze` + applied at :attr:`dim` = ``dim + input.dim() + 1``. + + Args: + input (Tensor): the input tensor. + dim (int): the index at which to insert the singleton dimension + + Example:: + + >>> x = torch.tensor([1, 2, 3, 4]) + >>> torch.unsqueeze(x, 0) + tensor([[ 1, 2, 3, 4]]) + >>> torch.unsqueeze(x, 1) + tensor([[ 1], + [ 2], + [ 3], + [ 4]]) + """ + +def unsqueeze_copy( + input: Tensor, + dim: _int, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.unsqueeze`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def values_copy(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + Performs the same operation as :func:`torch.values`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def vander( + x: Tensor, + N: _int | None = None, + increasing: _bool = False, +) -> Tensor: + r""" + vander(x, N=None, increasing=False) -> Tensor + + Generates a Vandermonde matrix. + + The columns of the output matrix are elementwise powers of the input vector :math:`x^{(N-1)}, x^{(N-2)}, ..., x^0`. + If increasing is True, the order of the columns is reversed :math:`x^0, x^1, ..., x^{(N-1)}`. Such a + matrix with a geometric progression in each row is named for Alexandre-Theophile Vandermonde. + + Arguments: + x (Tensor): 1-D input tensor. + N (int, optional): Number of columns in the output. If N is not specified, + a square array is returned :math:`(N = len(x))`. + increasing (bool, optional): Order of the powers of the columns. If True, + the powers increase from left to right, if False (the default) they are reversed. + + Returns: + Tensor: Vandermonde matrix. If increasing is False, the first column is :math:`x^{(N-1)}`, + the second :math:`x^{(N-2)}` and so forth. If increasing is True, the columns + are :math:`x^0, x^1, ..., x^{(N-1)}`. + + Example:: + + >>> x = torch.tensor([1, 2, 3, 5]) + >>> torch.vander(x) + tensor([[ 1, 1, 1, 1], + [ 8, 4, 2, 1], + [ 27, 9, 3, 1], + [125, 25, 5, 1]]) + >>> torch.vander(x, N=3) + tensor([[ 1, 1, 1], + [ 4, 2, 1], + [ 9, 3, 1], + [25, 5, 1]]) + >>> torch.vander(x, N=3, increasing=True) + tensor([[ 1, 1, 1], + [ 1, 2, 4], + [ 1, 3, 9], + [ 1, 5, 25]]) + """ + +@overload +def var( + input: Tensor, + dim: _int | _size | None, + unbiased: _bool = True, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + var(input, dim=None, *, correction=1, keepdim=False, out=None) -> Tensor + + Calculates the variance over the dimensions specified by :attr:`dim`. :attr:`dim` + can be a single dimension, list of dimensions, or ``None`` to reduce over all + dimensions. + + The variance (:math:`\sigma^2`) is calculated as + + .. math:: \sigma^2 = \frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2 + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.var(a, dim=1, keepdim=True) + tensor([[1.0631], + [0.5590], + [1.4893], + [0.8258]]) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def var( + input: Tensor, + dim: _int | _size | None = None, + *, + correction: Number | _complex | None = None, + keepdim: _bool = False, + out: Tensor | None = None, +) -> Tensor: + r""" + var(input, dim=None, *, correction=1, keepdim=False, out=None) -> Tensor + + Calculates the variance over the dimensions specified by :attr:`dim`. :attr:`dim` + can be a single dimension, list of dimensions, or ``None`` to reduce over all + dimensions. + + The variance (:math:`\sigma^2`) is calculated as + + .. math:: \sigma^2 = \frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2 + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.var(a, dim=1, keepdim=True) + tensor([[1.0631], + [0.5590], + [1.4893], + [0.8258]]) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def var(input: Tensor, unbiased: _bool = True) -> Tensor: + r""" + var(input, dim=None, *, correction=1, keepdim=False, out=None) -> Tensor + + Calculates the variance over the dimensions specified by :attr:`dim`. :attr:`dim` + can be a single dimension, list of dimensions, or ``None`` to reduce over all + dimensions. + + The variance (:math:`\sigma^2`) is calculated as + + .. math:: \sigma^2 = \frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2 + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.var(a, dim=1, keepdim=True) + tensor([[1.0631], + [0.5590], + [1.4893], + [0.8258]]) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def var( + input: Tensor, + dim: Sequence[str | EllipsisType | None], + *, + correction: Number | _complex | None = None, + keepdim: _bool = False, + out: Tensor | None = None, +) -> Tensor: + r""" + var(input, dim=None, *, correction=1, keepdim=False, out=None) -> Tensor + + Calculates the variance over the dimensions specified by :attr:`dim`. :attr:`dim` + can be a single dimension, list of dimensions, or ``None`` to reduce over all + dimensions. + + The variance (:math:`\sigma^2`) is calculated as + + .. math:: \sigma^2 = \frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2 + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.var(a, dim=1, keepdim=True) + tensor([[1.0631], + [0.5590], + [1.4893], + [0.8258]]) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def var( + input: Tensor, + dim: Sequence[str | EllipsisType | None], + unbiased: _bool = True, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + var(input, dim=None, *, correction=1, keepdim=False, out=None) -> Tensor + + Calculates the variance over the dimensions specified by :attr:`dim`. :attr:`dim` + can be a single dimension, list of dimensions, or ``None`` to reduce over all + dimensions. + + The variance (:math:`\sigma^2`) is calculated as + + .. math:: \sigma^2 = \frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2 + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.var(a, dim=1, keepdim=True) + tensor([[1.0631], + [0.5590], + [1.4893], + [0.8258]]) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def var_mean( + input: Tensor, + dim: _int | _size | None, + unbiased: _bool = True, + keepdim: _bool = False, +) -> tuple[Tensor, Tensor]: + r""" + var_mean(input, dim=None, *, correction=1, keepdim=False, out=None) -> (Tensor, Tensor) + + Calculates the variance and mean over the dimensions specified by :attr:`dim`. + :attr:`dim` can be a single dimension, list of dimensions, or ``None`` to + reduce over all dimensions. + + The variance (:math:`\sigma^2`) is calculated as + + .. math:: \sigma^2 = \frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2 + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Returns: + A tuple (var, mean) containing the variance and mean. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.var_mean(a, dim=0, keepdim=True) + (tensor([[1.5926, 1.0056, 1.2005, 0.3646]]), + tensor([[ 0.0645, 0.4485, 0.8707, -0.0665]])) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def var_mean( + input: Tensor, + dim: _int | _size | None = None, + *, + correction: Number | _complex | None = None, + keepdim: _bool = False, +) -> tuple[Tensor, Tensor]: + r""" + var_mean(input, dim=None, *, correction=1, keepdim=False, out=None) -> (Tensor, Tensor) + + Calculates the variance and mean over the dimensions specified by :attr:`dim`. + :attr:`dim` can be a single dimension, list of dimensions, or ``None`` to + reduce over all dimensions. + + The variance (:math:`\sigma^2`) is calculated as + + .. math:: \sigma^2 = \frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2 + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Returns: + A tuple (var, mean) containing the variance and mean. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.var_mean(a, dim=0, keepdim=True) + (tensor([[1.5926, 1.0056, 1.2005, 0.3646]]), + tensor([[ 0.0645, 0.4485, 0.8707, -0.0665]])) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def var_mean( + input: Tensor, + unbiased: _bool = True, +) -> tuple[Tensor, Tensor]: + r""" + var_mean(input, dim=None, *, correction=1, keepdim=False, out=None) -> (Tensor, Tensor) + + Calculates the variance and mean over the dimensions specified by :attr:`dim`. + :attr:`dim` can be a single dimension, list of dimensions, or ``None`` to + reduce over all dimensions. + + The variance (:math:`\sigma^2`) is calculated as + + .. math:: \sigma^2 = \frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2 + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Returns: + A tuple (var, mean) containing the variance and mean. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.var_mean(a, dim=0, keepdim=True) + (tensor([[1.5926, 1.0056, 1.2005, 0.3646]]), + tensor([[ 0.0645, 0.4485, 0.8707, -0.0665]])) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def var_mean( + input: Tensor, + dim: Sequence[str | EllipsisType | None], + *, + correction: Number | _complex | None = None, + keepdim: _bool = False, +) -> tuple[Tensor, Tensor]: + r""" + var_mean(input, dim=None, *, correction=1, keepdim=False, out=None) -> (Tensor, Tensor) + + Calculates the variance and mean over the dimensions specified by :attr:`dim`. + :attr:`dim` can be a single dimension, list of dimensions, or ``None`` to + reduce over all dimensions. + + The variance (:math:`\sigma^2`) is calculated as + + .. math:: \sigma^2 = \frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2 + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Returns: + A tuple (var, mean) containing the variance and mean. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.var_mean(a, dim=0, keepdim=True) + (tensor([[1.5926, 1.0056, 1.2005, 0.3646]]), + tensor([[ 0.0645, 0.4485, 0.8707, -0.0665]])) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def var_mean( + input: Tensor, + dim: Sequence[str | EllipsisType | None], + unbiased: _bool = True, + keepdim: _bool = False, +) -> tuple[Tensor, Tensor]: + r""" + var_mean(input, dim=None, *, correction=1, keepdim=False, out=None) -> (Tensor, Tensor) + + Calculates the variance and mean over the dimensions specified by :attr:`dim`. + :attr:`dim` can be a single dimension, list of dimensions, or ``None`` to + reduce over all dimensions. + + The variance (:math:`\sigma^2`) is calculated as + + .. math:: \sigma^2 = \frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2 + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Returns: + A tuple (var, mean) containing the variance and mean. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.var_mean(a, dim=0, keepdim=True) + (tensor([[1.5926, 1.0056, 1.2005, 0.3646]]), + tensor([[ 0.0645, 0.4485, 0.8707, -0.0665]])) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +def vdot( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + vdot(input, other, *, out=None) -> Tensor + + Computes the dot product of two 1D vectors along a dimension. + + In symbols, this function computes + + .. math:: + + \sum_{i=1}^n \overline{x_i}y_i. + + where :math:`\overline{x_i}` denotes the conjugate for complex + vectors, and it is the identity for real vectors. + + .. note:: + + Unlike NumPy's vdot, torch.vdot intentionally only supports computing the dot product + of two 1D tensors with the same number of elements. + + .. seealso:: + + :func:`torch.linalg.vecdot` computes the dot product of two batches of vectors along a dimension. + + Args: + input (Tensor): first tensor in the dot product, must be 1D. Its conjugate is used if it's complex. + other (Tensor): second tensor in the dot product, must be 1D. + + Keyword args: + + .. note:: out (Tensor, optional): the output tensor. + + + Example:: + + >>> torch.vdot(torch.tensor([2, 3]), torch.tensor([2, 1])) + tensor(7) + >>> a = torch.tensor((1 +2j, 3 - 1j)) + >>> b = torch.tensor((2 +1j, 4 - 0j)) + >>> torch.vdot(a, b) + tensor([16.+1.j]) + >>> torch.vdot(b, a) + tensor([16.-1.j]) + """ + +def view_as_complex(input: Tensor) -> Tensor: + r""" + view_as_complex(input) -> Tensor + + Returns a view of :attr:`input` as a complex tensor. For an input complex + tensor of :attr:`size` :math:`m1, m2, \dots, mi, 2`, this function returns a + new complex tensor of :attr:`size` :math:`m1, m2, \dots, mi` where the last + dimension of the input tensor is expected to represent the real and imaginary + components of complex numbers. + + .. warning:: + :func:`view_as_complex` is only supported for tensors with + :class:`torch.dtype` ``torch.float64`` and ``torch.float32``. The input is + expected to have the last dimension of :attr:`size` 2. In addition, the + tensor must have a `stride` of 1 for its last dimension. The strides of all + other dimensions must be even numbers. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> x=torch.randn(4, 2) + >>> x + tensor([[ 1.6116, -0.5772], + [-1.4606, -0.9120], + [ 0.0786, -1.7497], + [-0.6561, -1.6623]]) + >>> torch.view_as_complex(x) + tensor([(1.6116-0.5772j), (-1.4606-0.9120j), (0.0786-1.7497j), (-0.6561-1.6623j)]) + """ + +def view_as_complex_copy( + input: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.view_as_complex`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def view_as_real(input: Tensor) -> Tensor: + r""" + view_as_real(input) -> Tensor + + Returns a view of :attr:`input` as a real tensor. For an input complex tensor of + :attr:`size` :math:`m1, m2, \dots, mi`, this function returns a new + real tensor of size :math:`m1, m2, \dots, mi, 2`, where the last dimension of size 2 + represents the real and imaginary components of complex numbers. + + .. warning:: + :func:`view_as_real` is only supported for tensors with ``complex dtypes``. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> x=torch.randn(4, dtype=torch.cfloat) + >>> x + tensor([(0.4737-0.3839j), (-0.2098-0.6699j), (0.3470-0.9451j), (-0.5174-1.3136j)]) + >>> torch.view_as_real(x) + tensor([[ 0.4737, -0.3839], + [-0.2098, -0.6699], + [ 0.3470, -0.9451], + [-0.5174, -1.3136]]) + """ + +def view_as_real_copy( + input: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.view_as_real`, but all output tensors + are freshly created instead of aliasing the input. + """ + +@overload +def view_copy( + input: Tensor, + dtype: _dtype, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.view`, but all output tensors + are freshly created instead of aliasing the input. + """ + +@overload +def view_copy( + input: Tensor, + size: Sequence[_int | SymInt], + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.view`, but all output tensors + are freshly created instead of aliasing the input. + """ + +@overload +def vsplit(input: Tensor, sections: _int) -> tuple[Tensor, ...]: + r""" + vsplit(input, indices_or_sections) -> List of Tensors + + Splits :attr:`input`, a tensor with two or more dimensions, into multiple tensors + vertically according to :attr:`indices_or_sections`. Each split is a view of + :attr:`input`. + + This is equivalent to calling torch.tensor_split(input, indices_or_sections, dim=0) + (the split dimension is 0), except that if :attr:`indices_or_sections` is an integer + it must evenly divide the split dimension or a runtime error will be thrown. + + This function is based on NumPy's :func:`numpy.vsplit`. + + Args: + input (Tensor): tensor to split. + indices_or_sections (int or list or tuple of ints): See argument in :func:`torch.tensor_split`. + + Example:: + + >>> t = torch.arange(16.0).reshape(4,4) + >>> t + tensor([[ 0., 1., 2., 3.], + [ 4., 5., 6., 7.], + [ 8., 9., 10., 11.], + [12., 13., 14., 15.]]) + >>> torch.vsplit(t, 2) + (tensor([[0., 1., 2., 3.], + [4., 5., 6., 7.]]), + tensor([[ 8., 9., 10., 11.], + [12., 13., 14., 15.]])) + >>> torch.vsplit(t, [3, 6]) + (tensor([[ 0., 1., 2., 3.], + [ 4., 5., 6., 7.], + [ 8., 9., 10., 11.]]), + tensor([[12., 13., 14., 15.]]), + tensor([], size=(0, 4))) + """ + +@overload +def vsplit(input: Tensor, indices: _size) -> tuple[Tensor, ...]: + r""" + vsplit(input, indices_or_sections) -> List of Tensors + + Splits :attr:`input`, a tensor with two or more dimensions, into multiple tensors + vertically according to :attr:`indices_or_sections`. Each split is a view of + :attr:`input`. + + This is equivalent to calling torch.tensor_split(input, indices_or_sections, dim=0) + (the split dimension is 0), except that if :attr:`indices_or_sections` is an integer + it must evenly divide the split dimension or a runtime error will be thrown. + + This function is based on NumPy's :func:`numpy.vsplit`. + + Args: + input (Tensor): tensor to split. + indices_or_sections (int or list or tuple of ints): See argument in :func:`torch.tensor_split`. + + Example:: + + >>> t = torch.arange(16.0).reshape(4,4) + >>> t + tensor([[ 0., 1., 2., 3.], + [ 4., 5., 6., 7.], + [ 8., 9., 10., 11.], + [12., 13., 14., 15.]]) + >>> torch.vsplit(t, 2) + (tensor([[0., 1., 2., 3.], + [4., 5., 6., 7.]]), + tensor([[ 8., 9., 10., 11.], + [12., 13., 14., 15.]])) + >>> torch.vsplit(t, [3, 6]) + (tensor([[ 0., 1., 2., 3.], + [ 4., 5., 6., 7.], + [ 8., 9., 10., 11.]]), + tensor([[12., 13., 14., 15.]]), + tensor([], size=(0, 4))) + """ + +def vstack( + tensors: tuple[Tensor, ...] | list[Tensor] | None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + vstack(tensors, *, out=None) -> Tensor + + Stack tensors in sequence vertically (row wise). + + This is equivalent to concatenation along the first axis after all 1-D tensors have been reshaped by :func:`torch.atleast_2d`. + + Args: + tensors (sequence of Tensors): sequence of tensors to concatenate + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([1, 2, 3]) + >>> b = torch.tensor([4, 5, 6]) + >>> torch.vstack((a,b)) + tensor([[1, 2, 3], + [4, 5, 6]]) + >>> a = torch.tensor([[1],[2],[3]]) + >>> b = torch.tensor([[4],[5],[6]]) + >>> torch.vstack((a,b)) + tensor([[1], + [2], + [3], + [4], + [5], + [6]]) + """ + +@overload +def where(condition: Tensor) -> tuple[Tensor, ...]: + r""" + where(condition, input, other, *, out=None) -> Tensor + + Return a tensor of elements selected from either :attr:`input` or :attr:`other`, depending on :attr:`condition`. + + The operation is defined as: + + .. math:: + \text{out}_i = \begin{cases} + \text{input}_i & \text{if } \text{condition}_i \\ + \text{other}_i & \text{otherwise} \\ + \end{cases} + + .. note:: + The tensors :attr:`condition`, :attr:`input`, :attr:`other` must be :ref:`broadcastable `. + + Arguments: + condition (BoolTensor): When True (nonzero), yield input, otherwise yield other + input (Tensor or Scalar): value (if :attr:`input` is a scalar) or values selected at indices + where :attr:`condition` is ``True`` + other (Tensor or Scalar): value (if :attr:`other` is a scalar) or values selected at indices + where :attr:`condition` is ``False`` + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + Tensor: A tensor of shape equal to the broadcasted shape of :attr:`condition`, :attr:`input`, :attr:`other` + + Example:: + + >>> x = torch.randn(3, 2) + >>> y = torch.ones(3, 2) + >>> x + tensor([[-0.4620, 0.3139], + [ 0.3898, -0.7197], + [ 0.0478, -0.1657]]) + >>> torch.where(x > 0, 1.0, 0.0) + tensor([[0., 1.], + [1., 0.], + [1., 0.]]) + >>> torch.where(x > 0, x, y) + tensor([[ 1.0000, 0.3139], + [ 0.3898, 1.0000], + [ 0.0478, 1.0000]]) + >>> x = torch.randn(2, 2, dtype=torch.double) + >>> x + tensor([[ 1.0779, 0.0383], + [-0.8785, -1.1089]], dtype=torch.float64) + >>> torch.where(x > 0, x, 0.) + tensor([[1.0779, 0.0383], + [0.0000, 0.0000]], dtype=torch.float64) + + .. function:: where(condition) -> tuple of LongTensor + :noindex: + + ``torch.where(condition)`` is identical to + ``torch.nonzero(condition, as_tuple=True)``. + + .. note:: + See also :func:`torch.nonzero`. + """ + +@overload +def where( + condition: Tensor, + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + where(condition, input, other, *, out=None) -> Tensor + + Return a tensor of elements selected from either :attr:`input` or :attr:`other`, depending on :attr:`condition`. + + The operation is defined as: + + .. math:: + \text{out}_i = \begin{cases} + \text{input}_i & \text{if } \text{condition}_i \\ + \text{other}_i & \text{otherwise} \\ + \end{cases} + + .. note:: + The tensors :attr:`condition`, :attr:`input`, :attr:`other` must be :ref:`broadcastable `. + + Arguments: + condition (BoolTensor): When True (nonzero), yield input, otherwise yield other + input (Tensor or Scalar): value (if :attr:`input` is a scalar) or values selected at indices + where :attr:`condition` is ``True`` + other (Tensor or Scalar): value (if :attr:`other` is a scalar) or values selected at indices + where :attr:`condition` is ``False`` + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + Tensor: A tensor of shape equal to the broadcasted shape of :attr:`condition`, :attr:`input`, :attr:`other` + + Example:: + + >>> x = torch.randn(3, 2) + >>> y = torch.ones(3, 2) + >>> x + tensor([[-0.4620, 0.3139], + [ 0.3898, -0.7197], + [ 0.0478, -0.1657]]) + >>> torch.where(x > 0, 1.0, 0.0) + tensor([[0., 1.], + [1., 0.], + [1., 0.]]) + >>> torch.where(x > 0, x, y) + tensor([[ 1.0000, 0.3139], + [ 0.3898, 1.0000], + [ 0.0478, 1.0000]]) + >>> x = torch.randn(2, 2, dtype=torch.double) + >>> x + tensor([[ 1.0779, 0.0383], + [-0.8785, -1.1089]], dtype=torch.float64) + >>> torch.where(x > 0, x, 0.) + tensor([[1.0779, 0.0383], + [0.0000, 0.0000]], dtype=torch.float64) + + .. function:: where(condition) -> tuple of LongTensor + :noindex: + + ``torch.where(condition)`` is identical to + ``torch.nonzero(condition, as_tuple=True)``. + + .. note:: + See also :func:`torch.nonzero`. + """ + +@overload +def where( + condition: Tensor, + self: Number | _complex, + other: Tensor, +) -> Tensor: + r""" + where(condition, input, other, *, out=None) -> Tensor + + Return a tensor of elements selected from either :attr:`input` or :attr:`other`, depending on :attr:`condition`. + + The operation is defined as: + + .. math:: + \text{out}_i = \begin{cases} + \text{input}_i & \text{if } \text{condition}_i \\ + \text{other}_i & \text{otherwise} \\ + \end{cases} + + .. note:: + The tensors :attr:`condition`, :attr:`input`, :attr:`other` must be :ref:`broadcastable `. + + Arguments: + condition (BoolTensor): When True (nonzero), yield input, otherwise yield other + input (Tensor or Scalar): value (if :attr:`input` is a scalar) or values selected at indices + where :attr:`condition` is ``True`` + other (Tensor or Scalar): value (if :attr:`other` is a scalar) or values selected at indices + where :attr:`condition` is ``False`` + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + Tensor: A tensor of shape equal to the broadcasted shape of :attr:`condition`, :attr:`input`, :attr:`other` + + Example:: + + >>> x = torch.randn(3, 2) + >>> y = torch.ones(3, 2) + >>> x + tensor([[-0.4620, 0.3139], + [ 0.3898, -0.7197], + [ 0.0478, -0.1657]]) + >>> torch.where(x > 0, 1.0, 0.0) + tensor([[0., 1.], + [1., 0.], + [1., 0.]]) + >>> torch.where(x > 0, x, y) + tensor([[ 1.0000, 0.3139], + [ 0.3898, 1.0000], + [ 0.0478, 1.0000]]) + >>> x = torch.randn(2, 2, dtype=torch.double) + >>> x + tensor([[ 1.0779, 0.0383], + [-0.8785, -1.1089]], dtype=torch.float64) + >>> torch.where(x > 0, x, 0.) + tensor([[1.0779, 0.0383], + [0.0000, 0.0000]], dtype=torch.float64) + + .. function:: where(condition) -> tuple of LongTensor + :noindex: + + ``torch.where(condition)`` is identical to + ``torch.nonzero(condition, as_tuple=True)``. + + .. note:: + See also :func:`torch.nonzero`. + """ + +@overload +def where( + condition: Tensor, + input: Tensor, + other: Number | _complex, +) -> Tensor: + r""" + where(condition, input, other, *, out=None) -> Tensor + + Return a tensor of elements selected from either :attr:`input` or :attr:`other`, depending on :attr:`condition`. + + The operation is defined as: + + .. math:: + \text{out}_i = \begin{cases} + \text{input}_i & \text{if } \text{condition}_i \\ + \text{other}_i & \text{otherwise} \\ + \end{cases} + + .. note:: + The tensors :attr:`condition`, :attr:`input`, :attr:`other` must be :ref:`broadcastable `. + + Arguments: + condition (BoolTensor): When True (nonzero), yield input, otherwise yield other + input (Tensor or Scalar): value (if :attr:`input` is a scalar) or values selected at indices + where :attr:`condition` is ``True`` + other (Tensor or Scalar): value (if :attr:`other` is a scalar) or values selected at indices + where :attr:`condition` is ``False`` + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + Tensor: A tensor of shape equal to the broadcasted shape of :attr:`condition`, :attr:`input`, :attr:`other` + + Example:: + + >>> x = torch.randn(3, 2) + >>> y = torch.ones(3, 2) + >>> x + tensor([[-0.4620, 0.3139], + [ 0.3898, -0.7197], + [ 0.0478, -0.1657]]) + >>> torch.where(x > 0, 1.0, 0.0) + tensor([[0., 1.], + [1., 0.], + [1., 0.]]) + >>> torch.where(x > 0, x, y) + tensor([[ 1.0000, 0.3139], + [ 0.3898, 1.0000], + [ 0.0478, 1.0000]]) + >>> x = torch.randn(2, 2, dtype=torch.double) + >>> x + tensor([[ 1.0779, 0.0383], + [-0.8785, -1.1089]], dtype=torch.float64) + >>> torch.where(x > 0, x, 0.) + tensor([[1.0779, 0.0383], + [0.0000, 0.0000]], dtype=torch.float64) + + .. function:: where(condition) -> tuple of LongTensor + :noindex: + + ``torch.where(condition)`` is identical to + ``torch.nonzero(condition, as_tuple=True)``. + + .. note:: + See also :func:`torch.nonzero`. + """ + +@overload +def where( + condition: Tensor, + self: Number | _complex, + other: Number | _complex, +) -> Tensor: + r""" + where(condition, input, other, *, out=None) -> Tensor + + Return a tensor of elements selected from either :attr:`input` or :attr:`other`, depending on :attr:`condition`. + + The operation is defined as: + + .. math:: + \text{out}_i = \begin{cases} + \text{input}_i & \text{if } \text{condition}_i \\ + \text{other}_i & \text{otherwise} \\ + \end{cases} + + .. note:: + The tensors :attr:`condition`, :attr:`input`, :attr:`other` must be :ref:`broadcastable `. + + Arguments: + condition (BoolTensor): When True (nonzero), yield input, otherwise yield other + input (Tensor or Scalar): value (if :attr:`input` is a scalar) or values selected at indices + where :attr:`condition` is ``True`` + other (Tensor or Scalar): value (if :attr:`other` is a scalar) or values selected at indices + where :attr:`condition` is ``False`` + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + Tensor: A tensor of shape equal to the broadcasted shape of :attr:`condition`, :attr:`input`, :attr:`other` + + Example:: + + >>> x = torch.randn(3, 2) + >>> y = torch.ones(3, 2) + >>> x + tensor([[-0.4620, 0.3139], + [ 0.3898, -0.7197], + [ 0.0478, -0.1657]]) + >>> torch.where(x > 0, 1.0, 0.0) + tensor([[0., 1.], + [1., 0.], + [1., 0.]]) + >>> torch.where(x > 0, x, y) + tensor([[ 1.0000, 0.3139], + [ 0.3898, 1.0000], + [ 0.0478, 1.0000]]) + >>> x = torch.randn(2, 2, dtype=torch.double) + >>> x + tensor([[ 1.0779, 0.0383], + [-0.8785, -1.1089]], dtype=torch.float64) + >>> torch.where(x > 0, x, 0.) + tensor([[1.0779, 0.0383], + [0.0000, 0.0000]], dtype=torch.float64) + + .. function:: where(condition) -> tuple of LongTensor + :noindex: + + ``torch.where(condition)`` is identical to + ``torch.nonzero(condition, as_tuple=True)``. + + .. note:: + See also :func:`torch.nonzero`. + """ + +@overload +def xlogy( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + xlogy(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.special.xlogy`. + """ + +@overload +def xlogy( + self: Number | _complex, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + xlogy(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.special.xlogy`. + """ + +@overload +def xlogy( + input: Tensor, + other: Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + xlogy(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.special.xlogy`. + """ + +@overload +def xlogy_(input: Tensor, other: Tensor) -> Tensor: ... +@overload +def xlogy_(input: Tensor, other: Number | _complex) -> Tensor: ... +def zero_(input: Tensor) -> Tensor: ... +@overload +def zeros( + size: Sequence[_int | SymInt], + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + zeros(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with the scalar value `0`, with the shape defined + by the variable argument :attr:`size`. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.zeros(2, 3) + tensor([[ 0., 0., 0.], + [ 0., 0., 0.]]) + + >>> torch.zeros(5) + tensor([ 0., 0., 0., 0., 0.]) + """ + +@overload +def zeros( + *size: _int | SymInt, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + zeros(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with the scalar value `0`, with the shape defined + by the variable argument :attr:`size`. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.zeros(2, 3) + tensor([[ 0., 0., 0.], + [ 0., 0., 0.]]) + + >>> torch.zeros(5) + tensor([ 0., 0., 0., 0., 0.]) + """ + +@overload +def zeros( + size: _size, + *, + names: Sequence[str | EllipsisType | None] | None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + zeros(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with the scalar value `0`, with the shape defined + by the variable argument :attr:`size`. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.zeros(2, 3) + tensor([[ 0., 0., 0.], + [ 0., 0., 0.]]) + + >>> torch.zeros(5) + tensor([ 0., 0., 0., 0., 0.]) + """ + +@overload +def zeros( + *size: _int, + names: Sequence[str | EllipsisType | None] | None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + zeros(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with the scalar value `0`, with the shape defined + by the variable argument :attr:`size`. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.zeros(2, 3) + tensor([[ 0., 0., 0.], + [ 0., 0., 0.]]) + + >>> torch.zeros(5) + tensor([ 0., 0., 0., 0., 0.]) + """ + +def zeros_like( + input: Tensor, + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + zeros_like(input, *, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor filled with the scalar value `0`, with the same size as + :attr:`input`. ``torch.zeros_like(input)`` is equivalent to + ``torch.zeros(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``. + + .. warning:: + As of 0.4, this function does not support an :attr:`out` keyword. As an alternative, + the old ``torch.zeros_like(input, out=output)`` is equivalent to + ``torch.zeros(input.size(), out=output)``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + + Example:: + + >>> input = torch.empty(2, 3) + >>> torch.zeros_like(input) + tensor([[ 0., 0., 0.], + [ 0., 0., 0.]]) + """ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/__init__.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..392d89ff7185e80f5063f64bc0a9b7cdb5a6e007 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/__init__.pyi @@ -0,0 +1,13003 @@ +# @generated by tools/pyi/gen_pyi.py from torch/_C/__init__.pyi.in +# mypy: disable-error-code="type-arg" +# mypy: allow-untyped-defs +# ruff: noqa: F401 + +from collections.abc import Callable, Iterable, Iterator, Sequence +from enum import Enum, IntEnum +from pathlib import Path +from types import EllipsisType +from typing import ( + Any, + AnyStr, + Generic, + IO, + Literal, + NamedTuple, + overload, + Protocol, + runtime_checkable, + SupportsIndex, + TypeAlias, + TypeVar, +) +from typing_extensions import ParamSpec, Self + +import numpy + +import torch +from torch import inf, SymInt, Tensor +from torch._C import ( + _acc, + _aoti, + _cpu, + _dynamo, + _export, + _functionalization, + _functorch, + _lazy, + _lazy_ts_backend, + _nn, + _onnx, + _VariableFunctions, + _verbose, +) +from torch._prims_common import DeviceLikeType +from torch.autograd.graph import Node as _Node +from torch.cuda import _POOL_HANDLE +from torch.distributed.device_mesh import DeviceMesh +from torch.distributed.tensor._op_schema import OpSchema +from torch.distributed.tensor.placement_types import Placement +from torch.fx.node import Node as FxNode +from torch.package import PackageExporter +from torch.storage import TypedStorage, UntypedStorage +from torch.types import ( + _bool, + _bytes, + _complex, + _device, + _dispatchkey, + _dtype, + _float, + _int, + _layout, + _qscheme, + _size, + _str, + _symsize, + Device, + IntLikeType, + Number, + Storage, +) +from torch.utils._python_dispatch import TorchDispatchMode +from torch.utils.checkpoint import GraphExecGroup + +# This module is defined in torch/csrc/Module.cpp + +K = TypeVar("K") # noqa: PYI001 +T = TypeVar("T") # noqa: PYI001 +S = TypeVar("S", bound=torch.Tensor) # noqa: PYI001 +P = ParamSpec("P") # noqa: PYI001 +R = TypeVar("R", covariant=True) # return value (always covariant) # noqa: PYI001 +T_co = TypeVar("T_co", covariant=True) # noqa: PYI001 + +@runtime_checkable +class _NestedSequence(Protocol[T_co]): + """A protocol for representing nested sequences. + + References:: + `numpy._typing._NestedSequence` + + """ + + def __len__(self, /) -> _int: ... + def __getitem__(self, index: _int, /) -> T_co | _NestedSequence[T_co]: ... + def __contains__(self, x: object, /) -> _bool: ... + def __iter__(self, /) -> Iterator[T_co | _NestedSequence[T_co]]: ... + def __reversed__(self, /) -> Iterator[T_co | _NestedSequence[T_co]]: ... + def count(self, value: Any, /) -> _int: ... + def index(self, value: Any, /) -> _int: ... + +# Defined in torch/csrc/Device.cpp +class device: + type: str # THPDevice_type + index: _int # THPDevice_index + + def __get__(self, instance, owner=None) -> device: ... + + # THPDevice_pynew + @overload + def __init__(self, device: DeviceLikeType) -> None: ... + @overload + def __init__(self, type: str, index: _int) -> None: ... + + # Uncomment if we ever make torch.device a decorator + # def __call__(self, func: T) -> T: ... + + def __enter__(self) -> Self: ... + def __exit__(self, exc_type, exc_val, exc_tb) -> None: ... + def __reduce__(self) -> tuple[Any, ...]: ... # THPDevice_reduce + +# Defined in torch/csrc/Stream.cpp +class Stream: + stream_id: _int # Stream id + device_index: _int + device_type: _int + + device: _device # The device of the stream + + @overload + def __new__( + cls, + device: DeviceLikeType | None = None, + *, + priority: _int = 0, + ) -> Self: ... + @overload + def __new__( + cls, + stream_id: _int, + device_index: _int, + device_type: _int, + *, + priority: _int = 0, + ) -> Self: ... + def query(self) -> _bool: ... + def synchronize(self) -> None: ... + def wait_event(self, event: Event) -> None: ... + def wait_stream(self, other: Stream) -> None: ... + def record_event(self, event: Event | None = None) -> Event: ... + def __hash__(self) -> _int: ... + def __eq__(self, other: object) -> _bool: ... + def __enter__(self) -> Self: ... + def __exit__(self, exc_type, exc_val, exc_tb) -> None: ... + +# Defined in torch/csrc/Event.cpp +class Event: + device: _device # The device of the Event + event_id: _int # The raw event created by device backend + + def __new__( + cls, + device: DeviceLikeType | None = None, + *, + enable_timing: _bool = False, + blocking: _bool = False, + interprocess: _bool = False, + ) -> Self: ... + @classmethod + def from_ipc_handle(cls, device: _device, ipc_handle: bytes) -> Event: ... + def record(self, stream: Stream | None = None) -> None: ... + def wait(self, stream: Stream | None = None) -> None: ... + def query(self) -> _bool: ... + def elapsed_time(self, other: Event) -> _float: ... + def synchronize(self) -> None: ... + def ipc_handle(self) -> bytes: ... + +# Defined in torch/csrc/Size.cpp +class Size(tuple[_int, ...]): + # TODO: __reduce__ + + @overload + def __getitem__(self: Size, key: SupportsIndex, /) -> _int: ... + @overload + def __getitem__(self: Size, key: slice, /) -> Size: ... + # Note: torch.Size does not support adding non-integer tuples. + def __add__(self, other: tuple[_int, ...], /) -> Size: ... # type: ignore[override] + def __radd__(self: Size, other: tuple[_int, ...], /) -> Size: ... + def __mul__(self, other: SupportsIndex, /) -> Size: ... + def __rmul__(self, other: SupportsIndex, /) -> Size: ... + def numel(self: Size, /) -> _int: ... + +# Defined in torch/csrc/Dtype.cpp +class dtype: + # TODO: __reduce__ + is_floating_point: _bool + is_complex: _bool + is_signed: _bool + itemsize: _int + def to_real(self) -> dtype: ... + def to_complex(self) -> dtype: ... + +# Defined in torch/csrc/TypeInfo.cpp +class iinfo: + bits: _int + min: _int + max: _int + dtype: str + + def __init__(self, dtype: _dtype) -> None: ... + +class finfo: + bits: _int + min: _float + max: _float + eps: _float + tiny: _float + smallest_normal: _float + resolution: _float + dtype: str + + @overload + def __init__(self, dtype: _dtype) -> None: ... + @overload + def __init__(self) -> None: ... + +float32: dtype = ... +float: dtype = ... +float64: dtype = ... +double: dtype = ... +float16: dtype = ... +bfloat16: dtype = ... +float8_e4m3fn: dtype = ... +float8_e4m3fnuz: dtype = ... +float8_e5m2: dtype = ... +float8_e5m2fnuz: dtype = ... +float8_e8m0fnu: dtype = ... +float4_e2m1fn_x2: dtype = ... +half: dtype = ... +uint8: dtype = ... +uint16: dtype = ... +uint32: dtype = ... +uint64: dtype = ... +int8: dtype = ... +int16: dtype = ... +short: dtype = ... +int32: dtype = ... +int: dtype = ... +int64: dtype = ... +long: dtype = ... +complex32: dtype = ... +complex64: dtype = ... +chalf: dtype = ... +cfloat: dtype = ... +complex128: dtype = ... +cdouble: dtype = ... +quint8: dtype = ... +qint8: dtype = ... +qint32: dtype = ... +bool: dtype = ... +quint4x2: dtype = ... +quint2x4: dtype = ... +bits1x8: dtype = ... +bits2x4: dtype = ... +bits4x2: dtype = ... +bits8: dtype = ... +bits16: dtype = ... + +# Defined in torch/csrc/Layout.cpp +class layout: ... + +# Defined in torch/csrc/utils/disable_torch_function.cpp +def DisableTorchFunction(): ... +def DisableTorchFunctionSubclass(): ... + +# Defined in torch/csrc/utils/tensor_layouts.cpp +strided: layout = ... +sparse_coo: layout = ... +sparse_csr: layout = ... +sparse_csc: layout = ... +sparse_bsr: layout = ... +sparse_bsc: layout = ... +_mkldnn: layout = ... +jagged: layout = ... + +# Defined in torch/csrc/MemoryFormat.cpp +class memory_format: ... + +# Defined in torch/csrc/utils/tensor_memoryformats.cpp +contiguous_format: memory_format = ... +channels_last: memory_format = ... +channels_last_3d: memory_format = ... +preserve_format: memory_format = ... + +# Defined in torch/csrc/QScheme.cpp +class qscheme: ... + +# Defined in torch/csrc/utils/tensor_qschemes.h +per_tensor_affine: qscheme = ... +per_channel_affine: qscheme = ... +per_tensor_symmetric: qscheme = ... +per_channel_symmetric: qscheme = ... +per_channel_affine_float_qparams: qscheme = ... + +# Defined in torch/csrc/autograd/python_function.cpp +class _FunctionBase: + saved_tensors: tuple[Tensor] + _raw_saved_tensors: tuple[Any] + next_functions: tuple[tuple[Any, _int], ...] + needs_input_grad: tuple[_bool] + metadata: dict + _materialize_non_diff_grads: _bool + # skip adding type hints for the fields that have wrappers defined + # in torch/autograd/function.py + +# Defined in torch/csrc/autograd/python_legacy_variable.cpp +class _LegacyVariableBase(Tensor): # inherits from Tensor to appease mypy + def __init__( + self, + data: Tensor | None = ..., + requires_grad: _bool | None = ..., + volatile: _bool | None = ..., + _grad_fn: _FunctionBase | None = ..., + ) -> None: ... + +# Defined in torch/csrc/jit/python/init.cpp +class IODescriptor: ... +class JITException(Exception): ... + +class Future(Generic[T]): + def __init__(self, devices: list[device]) -> None: ... + def done(self) -> _bool: ... + def value(self) -> T: ... + def wait(self) -> T: ... + def add_done_callback(self, callback: Callable) -> None: ... + def then(self, callback: Callable) -> Future[T]: ... + def set_result(self, result: T) -> None: ... + def _set_unwrap_func(self, callback: Callable) -> None: ... + +class _Await: + def __init__(self) -> None: ... + def fn(self) -> Callable: ... + def args(self) -> tuple[Any, ...]: ... + def is_nowait(self) -> _bool: ... + +def _jit_set_num_profiled_runs(num: _size) -> _size: ... + +# Defined in torch/csrc/jit/passes/mobile_optimizer_type.h +class _MobileOptimizerType: ... + +CONV_BN_FUSION: _MobileOptimizerType +INSERT_FOLD_PREPACK_OPS: _MobileOptimizerType +REMOVE_DROPOUT: _MobileOptimizerType +FUSE_ADD_RELU: _MobileOptimizerType +HOIST_CONV_PACKED_PARAMS: _MobileOptimizerType +VULKAN_AUTOMATIC_GPU_TRANSFER: _MobileOptimizerType + +def fork(*args: Any, **kwargs: Any) -> Future: ... +def wait(fut: Future) -> Any: ... +def _awaitable(*args: Any, **kwargs: Any) -> _Await: ... +def _awaitable_wait(aw: _Await) -> Any: ... +def _awaitable_nowait(x: Any) -> _Await: ... +def _collect_all(futures: list[Future]) -> Future: ... +def _set_print_stack_traces_on_fatal_signal(print: _bool) -> None: ... +def unify_type_list(types: list[JitType]) -> JitType: ... +def _freeze_module( + module: ScriptModule, + preserved_attrs: list[str] = ..., + freeze_interfaces: _bool = True, + preserveParameters: _bool = True, +) -> ScriptModule: ... +def _jit_pass_optimize_frozen_graph(Graph, optimize_numerics: _bool = True) -> None: ... +def _jit_pass_optimize_for_inference( + module: torch.jit.ScriptModule, + other_methods: list[str] = ..., +) -> None: ... +def _jit_pass_fold_frozen_conv_bn(graph: Graph): ... +def _jit_pass_fold_frozen_conv_add_or_sub(graph: Graph): ... +def _jit_pass_fold_frozen_conv_mul_or_div(graph: Graph): ... +def _jit_pass_fuse_frozen_conv_add_relu(graph: Graph): ... +def _jit_pass_concat_frozen_linear(graph: Graph): ... +def _jit_pass_convert_frozen_ops_to_mkldnn(graph: Graph): ... +def _jit_pass_transpose_frozen_linear(graph: Graph): ... +def _jit_pass_remove_dropout(module: torch.jit.ScriptModule): ... +def _is_tracing() -> _bool: ... +def _jit_init() -> _bool: ... +def _jit_flatten(arg: Any) -> tuple[list[Tensor], IODescriptor]: ... +def _jit_unflatten(vars: list[Tensor], desc: IODescriptor) -> Any: ... +def _jit_get_operation(op_name: str) -> tuple[Callable, list[str]]: ... +def _get_operation_overload( + op_name: str, + op_overload_name: str, +) -> tuple[Callable, Callable, list[Any]]: ... +def _get_schema(op_name: str, overload_name: str) -> FunctionSchema: ... +def _jit_pass_optimize_for_mobile( + module: torch.jit.ScriptModule, + optimization_blocklist: set[_MobileOptimizerType], + preserved_methods: list[AnyStr], +) -> torch.jit.ScriptModule: ... +def _clone_module_with_class( + module: torch.jit.ScriptModule, + ignored_methods: list[AnyStr], + ignored_attributes: list[AnyStr], +) -> torch.jit.ScriptModule: ... +def _jit_pass_vulkan_optimize_for_mobile( + module: torch.jit.ScriptModule, + optimization_blocklist: set[_MobileOptimizerType], + preserved_methods: list[AnyStr], +) -> torch.jit.ScriptModule: ... +def _jit_pass_metal_optimize_for_mobile( + module: torch.jit.ScriptModule, + preserved_methods: list[AnyStr], +) -> torch.jit.ScriptModule: ... +def _jit_pass_inline(Graph) -> None: ... +def _jit_pass_constant_propagation(Graph) -> None: ... +def _jit_pass_propagate_shapes_on_graph(Graph) -> None: ... +def _jit_register_decomposition_for_schema(schema: FunctionSchema, Graph) -> None: ... +def _jit_erase_non_input_shape_information(Graph) -> None: ... +def _jit_get_schemas_for_operator(name: str) -> list[FunctionSchema]: ... +def _jit_get_all_schemas() -> list[FunctionSchema]: ... +def _jit_check_alias_annotation( + g: Graph, + args: tuple[Any, ...], + unqualified_op_name: str, +): ... +def _jit_can_fuse_on_cpu() -> _bool: ... +def _jit_can_fuse_on_gpu() -> _bool: ... +def _jit_can_fuse_on_cpu_legacy() -> _bool: ... +def _debug_get_fusion_group_inlining() -> _bool: ... +def _debug_set_fusion_group_inlining(enable: _bool): ... +def _jit_texpr_fuser_enabled() -> _bool: ... +def _jit_nvfuser_enabled() -> _bool: ... +def _jit_llga_enabled() -> _bool: ... +def _jit_set_llga_enabled(enable: _bool): ... +def _llvm_enabled() -> _bool: ... +def _jit_override_can_fuse_on_cpu(override: _bool): ... +def _jit_override_can_fuse_on_gpu(override: _bool): ... +def _jit_override_can_fuse_on_cpu_legacy(override: _bool): ... +def _jit_set_symbolic_shapes_test_mode(override: _bool): ... +def _jit_symbolic_shapes_test_mode_enabled() -> _bool: ... +def _jit_set_texpr_fuser_enabled(enable: _bool): ... +def _jit_set_te_must_use_llvm_cpu(use_llvm: _bool): ... +def _jit_set_nvfuser_enabled(enable: _bool) -> _bool: ... +def _jit_cat_wo_conditionals(optimize_cat: _bool): ... +def _jit_opt_conditionals(opt_conds: _bool): ... +def _jit_pass_canonicalize(graph: Graph, keep_unique_names: _bool = True): ... +def _jit_pass_erase_shape_information(graph: Graph): ... +def _jit_pass_fold_convbn(module: torch.jit.ScriptModule): ... +def _jit_pass_insert_observers( + module: torch.jit.ScriptModule, + method_name: str, + qconfig_dict: dict[str, Any], + inplace: _bool, + quant_type: _int, +): ... +def _jit_pass_insert_quant_dequant( + module: torch.jit.ScriptModule, + method_name: str, + inplace: _bool, + debug: _bool, + quant_type: _int, +): ... +def _jit_pass_insert_quant_dequant_for_ondevice_ptq( + module: torch.jit.ScriptModule, + method_name: str, + inplace: _bool, + debug: _bool, + quant_type: _int, +): ... +def _jit_pass_quant_finalize( + module: torch.jit.ScriptModule, + quant_type: _int, + preserved_attrs: Sequence[str], +): ... +def _jit_pass_quant_finalize_for_ondevice_ptq( + module: torch.jit.ScriptModule, + quant_type: _int, + method_name: str, +): ... +def _jit_pass_insert_observer_method_for_ondevice_ptq( + module: torch.jit.ScriptModule, + method_name: str, + qconfig_dict: dict[str, Any], + inplace: _bool, + quant_type: _int, +): ... +def _jit_set_profiling_executor(profiling_flag: _bool) -> _bool: ... +def _jit_set_profiling_mode(profiling_flag: _bool) -> _bool: ... +def _jit_set_fusion_strategy( + strategy: list[tuple[str, _int]], +) -> list[tuple[str, _int]]: ... +def _jit_try_infer_type(obj: Any) -> InferredType: ... +def _jit_get_trigger_value(trigger_name: str) -> _int: ... + +# Defined in torch/csrc/jit/python/script_init.cpp +ResolutionCallback: TypeAlias = Callable[[str], Callable[..., Any]] + +# Defined in torch/csrc/jit/python/script_init.cpp +# and torch/csrc/jit/python/init.cpp +def _maybe_call_torch_function_for_op_packet( + op_overload_packet: Any, + *args: Any, + **kwargs: Any, +) -> Any: ... +def _check_schema_allow_fake_script_object( + schema: FunctionSchema, + *args: Any, + **kwargs: Any, +) -> _bool: ... +def _create_function_from_graph(qualname: str, graph: Graph) -> ScriptFunction: ... +def _debug_set_autodiff_subgraph_inlining(disabled: _bool) -> None: ... +def _ivalue_tags_match(lhs: ScriptModule, rhs: ScriptModule) -> _bool: ... +def _jit_assert_is_instance(obj: Any, type: JitType): ... +def _jit_clear_class_registry() -> None: ... +def _jit_set_emit_hooks( + ModuleHook: Callable | None, + FunctionHook: Callable | None, +) -> None: ... +def _jit_get_emit_hooks() -> tuple[Callable, Callable]: ... +def _load_for_lite_interpreter( + filename: str | Path, + map_location: DeviceLikeType | None, +): ... +def _load_for_lite_interpreter_from_buffer( + buffer: IO[bytes], + map_location: DeviceLikeType | None, +): ... +def _export_operator_list(module: LiteScriptModule): ... +def _quantize_ondevice_ptq_dynamic(module: LiteScriptModule, method_name: str): ... +def _get_model_bytecode_version(filename: str | Path) -> _int: ... +def _get_model_bytecode_version_from_buffer(buffer: IO[bytes]) -> _int: ... +def _backport_for_mobile( + filename_input: str | Path, + filename_output: str | Path, + to_version: _int, +) -> None: ... +def _backport_for_mobile_from_buffer( + buffer: IO[bytes], + filename_output: str | Path, + to_version: _int, +) -> None: ... +def _backport_for_mobile_to_buffer( + filename_input: str | Path, + to_version: _int, +) -> bytes: ... +def _backport_for_mobile_from_buffer_to_buffer( + buffer: IO[bytes], + to_version: _int, +) -> bytes: ... +def _get_model_ops_and_info(filename: str | Path): ... +def _get_model_ops_and_info_from_buffer(buffer: IO[bytes]): ... +def _get_mobile_model_contained_types(filename: str | Path): ... +def _get_mobile_model_contained_types_from_buffer(buffer: IO[bytes]): ... +def _logging_set_logger(logger: LoggerBase) -> LoggerBase: ... +def _get_graph_executor_optimize(optimize: _bool | None = None) -> _bool: ... +def _set_graph_executor_optimize(optimize: _bool): ... +def _export_opnames(module: ScriptModule) -> list[str]: ... +def _create_function_from_trace( + qualname: str, + func: Callable[..., Any], + input_tuple: tuple[Any, ...], + var_lookup_fn: Callable[[Tensor], str], + strict: _bool, + force_outplace: _bool, + argument_names: list[str], +) -> tuple[Graph, Stack]: ... +def _create_function_from_trace_with_dict( + qualname: str, + func: Callable[..., Any], + input_dict: dict[str, Any], + var_lookup_fn: Callable[[Tensor], str], + strict: _bool, + force_outplace: _bool, + argument_names: list[str], +) -> tuple[Graph, Stack]: ... +def _jit_is_script_object(obj: Any) -> _bool: ... +def _last_executed_optimized_graph() -> Graph: ... +def parse_type_comment(comment: str) -> Decl: ... +def _get_upgraders_map_size() -> _int: ... +def _get_upgraders_entry_map() -> dict[str, str]: ... +def _dump_upgraders_map() -> dict[str, str]: ... +def _test_only_populate_upgraders(content: dict[str, str]) -> None: ... +def _test_only_remove_upgraders(content: dict[str, str]) -> None: ... +def merge_type_from_type_comment( + decl: Decl, + type_annotation_decl: Decl, + is_method: _bool, +) -> Decl: ... +def parse_ir(input: str, parse_tensor_constants: _bool = False) -> Graph: ... +def parse_schema(schema: str) -> FunctionSchema: ... +def get_device(input: Tensor) -> _int: ... +def _resolve_type_from_object( + obj: Any, + range: SourceRange, + rcb: ResolutionCallback, +) -> JitType: ... +def _create_module_with_type(ty: JitType) -> ScriptModule: ... +def _create_object_with_type(ty: ClassType) -> ScriptObject: ... +def _run_emit_module_hook(m: ScriptModule): ... +def _replace_overloaded_method_decl( + overload_decl: Decl, + implementation_def: Def, + new_name: str, +) -> Def: ... +def _jit_pass_lower_all_tuples(graph: Graph) -> None: ... +def _jit_pass_onnx_set_dynamic_input_shape( + graph: Graph, + dynamic_axes: dict[str, dict[_int, str]], + input_names: list[str], +) -> None: ... +def _jit_pass_onnx_graph_shape_type_inference( + graph: Graph, + params_dict: dict[str, IValue], + opset_version: _int, +) -> None: ... +def _jit_pass_onnx_assign_output_shape( + graph: Graph, + tensors: list[Tensor], + desc: IODescriptor, + onnx_shape_inference: _bool, + is_script: _bool, + opset_version: _int, +) -> None: ... +def _jit_pass_onnx_remove_inplace_ops_for_onnx( + graph: Graph, + module: ScriptModule | None = None, +) -> None: ... +def _jit_pass_remove_inplace_ops(graph: Graph) -> None: ... +def _jit_pass_canonicalize_graph_fuser_ops(graph: Graph) -> None: ... +def _jit_pass_peephole( + graph: Graph, + disable_shape_peepholes: _bool = False, +) -> None: ... +def _jit_pass_onnx_autograd_function_process(graph: Graph) -> None: ... +def _jit_pass_fuse_addmm(graph: Graph) -> None: ... +def _jit_pass_onnx_preprocess(graph: Graph) -> None: ... +def _jit_pass_prepare_division_for_onnx(graph: Graph) -> None: ... +def _jit_pass_onnx_remove_print(graph: Graph) -> None: ... +def _jit_pass_onnx_preprocess_caffe2(graph: Graph) -> None: ... +def _jit_pass_onnx_unpack_quantized_weights( + graph: Graph, + paramsDict: dict[str, IValue], +) -> dict[str, IValue]: ... +def _jit_pass_onnx_quantization_insert_permutes( + graph: Graph, + paramsDict: dict[str, IValue], +) -> dict[str, IValue]: ... +def _jit_pass_custom_pattern_based_rewrite_graph( + pattern: str, + fused_node_name: str, + graph: Graph, +) -> None: ... +def _jit_onnx_list_model_parameters( + module: ScriptModule, +) -> tuple[ScriptModule, list[IValue]]: ... +def _jit_pass_erase_number_types(graph: Graph) -> None: ... +def _jit_pass_onnx_lint(graph: Graph) -> None: ... +def _jit_pass_onnx( + graph: Graph, + _jit_pass_onnx: _onnx.OperatorExportTypes, +) -> Graph: ... +def _jit_pass_onnx_scalar_type_analysis( + graph: Graph, + lowprecision_cast: _bool, + opset_version: _int, +) -> None: ... +def _jit_pass_onnx_peephole( + graph: Graph, + opset_version: _int, + fixed_batch_size: _bool, +) -> None: ... +def _jit_pass_dce_allow_deleting_nodes_with_side_effects(graph: Graph) -> None: ... +def _jit_pass_onnx_function_substitution(graph: Graph) -> None: ... +def _jit_pass_onnx_function_extraction( + graph: Graph, + module_names: set[str], + param_names: list[str], +) -> dict[Node, dict[str, str]]: ... +def _jit_pass_onnx_clear_scope_records() -> None: ... +def _jit_pass_onnx_track_scope_attributes( + graph: Graph, + onnx_attrs: dict[str, Any], +) -> None: ... +def _jit_is_onnx_log_enabled() -> _bool: ... +def _jit_set_onnx_log_enabled(enabled: _bool) -> None: ... +def _jit_set_onnx_log_output_stream(stream_name: str) -> None: ... +def _jit_onnx_log(*args: Any) -> None: ... +def _jit_pass_lower_graph(graph: Graph, m: Module) -> tuple[Graph, list[IValue]]: ... +def _jit_pass_inline_fork_wait(graph: Graph) -> None: ... +def _jit_pass_onnx_deduplicate_initializers( + graph: Graph, + params_dict: dict[str, IValue], + is_train: _bool, +) -> dict[str, IValue]: ... +def _jit_pass_onnx_eval_peephole( + graph: Graph, + paramsDict: dict[str, IValue], +) -> dict[str, IValue]: ... +def _jit_pass_onnx_constant_fold( + graph: Graph, + paramsDict: dict[str, IValue], + opset_version: _int, +) -> dict[str, IValue]: ... +def _jit_pass_onnx_eliminate_unused_items( + graph: Graph, + paramsDict: dict[str, IValue], +) -> dict[str, IValue]: ... +def _jit_pass_onnx_cast_all_constant_to_floating(graph: Graph) -> None: ... +def _jit_pass_filter_non_tensor_arguments( + params: dict[str, IValue], +) -> dict[str, Tensor]: ... +def _jit_decay_packed_param_input_types(graph: Graph) -> None: ... +def _jit_pass_onnx_node_shape_type_inference( + n: Node, + paramsDict: dict[str, IValue], + opset_version: _int, +) -> None: ... +def _jit_onnx_convert_pattern_from_subblock( + block: Block, + n: Node, + env: dict[Value, Value], + values_in_env: set[Value], +) -> list[Value]: ... +def _jit_pass_onnx_block( + old_block: Block, + new_block: Block, + operator_export_type: _onnx.OperatorExportTypes, + env: dict[Value, Value], + values_in_env: set[Value], + is_sub_block: _bool, +) -> dict[Value, Value]: ... +def _jit_pass_onnx_assign_scoped_names_for_node_and_value(graph: Graph) -> None: ... +def _jit_pass_fixup_onnx_controlflow_node( + n: Node, + opset_version: _int, +) -> list[Value]: ... +def _jit_onnx_create_full_scope_name(class_name: str, variable_name: str) -> str: ... +def _compile_graph_to_code_table(name: str, graph: Graph) -> IValue: ... +def _generate_upgraders_graph() -> dict[str, Graph]: ... +def _calculate_package_version_based_on_upgraders(val: _bool): ... +def _get_version_calculator_flag() -> _bool: ... +def _jit_script_interface_compile( + name: str, + class_def: ClassDef, + rcb: ResolutionCallback, + is_module: _bool, +): ... +def _jit_script_compile_overload( + qualname: str, + overload_decl: Decl, + implementation_def: Def, + rcb: ResolutionCallback, + implementation_defaults: dict[str, Any], + signature: Any, +): ... +def _jit_script_compile( + qual_name: str, + definition: Def, + rcb: ResolutionCallback, + defaults: dict[str, Any], +): ... +def _jit_script_class_compile( + qual_name: str, + definition: ClassDef, + defaults: dict[str, dict[str, Any]], + rcb: ResolutionCallback, +): ... +def _parse_source_def(src: str) -> Def: ... +def import_ir_module( + cu: CompilationUnit, + filename: str | Path, + map_location: DeviceLikeType | None, + extra_files: dict[str, Any], +) -> ScriptModule: ... +def import_ir_module_from_buffer( + cu: CompilationUnit, + buffer: IO[bytes], + map_location: DeviceLikeType | None, + extra_files: dict[str, Any], +) -> ScriptModule: ... +def _import_ir_module_from_package( + cu: CompilationUnit, + reader: PyTorchFileReader, + storage_context: DeserializationStorageContext, + map_location: DeviceLikeType | None, + ts_id: str, +) -> ScriptModule: ... +def _assign_output_shapes(graph: Graph, inputs: list[Tensor]) -> Graph: ... +def _check_onnx_proto(proto: str) -> None: ... +def _propagate_and_assign_input_shapes( + graph: Graph, + inputs: tuple[Tensor, ...], + param_count_list: list[_int], + with_grad: _bool, + propagate: _bool, +) -> Graph: ... + +# Defined in torch/csrc/jit/runtime/graph_executor.h +class GraphExecutorState: ... + +# Defined in torch/torch/csrc/jit/ir/alias_analysis.h +class AliasDb: ... + +class _InsertPoint: + def __enter__(self) -> None: ... + def __exit__(self, *exc_info: object) -> None: ... + +# Defined in torch/csrc/jit/ir/ir.h +class Use: + @property + def user(self) -> Node: ... + @property + def offset(self) -> _int: ... + def isAfter(self, other: Use) -> _bool: ... + +# Defined in torch/csrc/jit/ir/ir.h +class Value: + def type(self) -> JitType: ... + def setType(self, t: JitType) -> Value: ... + def setTypeAs(self, other: Value) -> Value: ... + def inferTypeFrom(self, t: Tensor) -> None: ... + def debugName(self) -> str: ... + def setDebugName(self, name: str) -> None: ... + def unique(self) -> _int: ... + def offset(self) -> _int: ... + def node(self) -> Node: ... + def uses(self) -> list[Use]: ... + def replaceAllUsesWith(self, val: Value) -> None: ... + def replaceAllUsesAfterNodeWith(self, node: Node, val: Value) -> None: ... + def requires_grad(self) -> _bool: ... + def requiresGrad(self) -> _bool: ... + def copyMetadata(self, other: Value) -> Value: ... + def isCompleteTensor(self) -> _bool: ... + def toIValue(self) -> IValue: ... + +# Defined in torch/csrc/jit/ir/ir.h +class Block: + def inputs(self) -> Iterator[Value]: ... + def outputs(self) -> Iterator[Value]: ... + def nodes(self) -> Iterator[Node]: ... + def paramNode(self) -> Node: ... + def returnNode(self) -> Node: ... + def owningNode(self) -> Node: ... + def registerOutput(self, n: Value) -> _int: ... + def addNode(self, name: str, inputs: Sequence[Value]) -> Node: ... + +# Defined in torch/csrc/jit/ir/ir.h +class Node: + def __getitem__(self, key: str) -> Any: ... + def schema(self) -> str: ... + def input(self) -> Value: ... + def inputs(self) -> Iterator[Value]: ... + def inputsAt(self, idx: _int) -> Value: ... + def inputsSize(self) -> _int: ... + def output(self) -> Value: ... + def outputs(self) -> Iterator[Value]: ... + def outputsAt(self, idx: _int) -> Value: ... + def outputsSize(self) -> _int: ... + def hasMultipleOutputs(self) -> _bool: ... + def blocks(self) -> list[Block]: ... + def addBlock(self) -> Block: ... + def mustBeNone(self) -> _bool: ... + def matches(self, pattern: str) -> _bool: ... + def kind(self) -> str: ... + def kindOf(self, name: str) -> str: ... + def addInput(self, name: str) -> Value: ... + def replaceInput(self, i: _int, newValue: Value) -> Value: ... + def replaceInputWith(self, from_: Value, to: Value) -> None: ... + def replaceAllUsesWith(self, n: Node) -> None: ... + def insertBefore(self, n: Node) -> Node: ... + def insertAfter(self, n: Node) -> Node: ... + def isBefore(self, n: Node) -> _bool: ... + def isAfter(self, n: Node) -> _bool: ... + def moveBefore(self, n: Node) -> None: ... + def moveAfter(self, n: Node) -> None: ... + def removeInput(self, i: _int) -> None: ... + def removeAllInputs(self, i: _int) -> None: ... + def hasUses(self) -> _bool: ... + def eraseOutput(self, i: _int) -> None: ... + def addOutput(self) -> Value: ... + def scopeName(self) -> str: ... + def isNondeterministic(self) -> _bool: ... + def copyAttributes(self, rhs: Node) -> Node: ... + def copyMetadata(self, rhs: Node) -> Node: ... + def hasAttributes(self) -> _bool: ... + def hasAttribute(self, name: str) -> _bool: ... + def removeAttribute(self, attr: str) -> Node: ... + def namedInput(self, name: str) -> Value: ... + def sourceRange(self) -> SourceRange: ... + def owningBlock(self) -> Block: ... + def findNode(self, kind: str, recurse: _bool = True) -> Node: ... + def findAllNodes(self, kind: str, recurse: _bool = True) -> list[Node]: ... + def getModuleHierarchy(self) -> str: ... + def prev(self) -> Node: ... + def destroy(self) -> None: ... + def attributeNames(self) -> list[str]: ... + + # Accessors for attributes as types. + def f(self, name: str) -> _float: ... + def f_(self, name: str, val: _float) -> Node: ... + def fs(self, name: str) -> list[_float]: ... + def fs_(self, name: str, val: list[_float]) -> Node: ... + def c(self, name: str) -> complex: ... + def c_(self, name: str, val: complex) -> Node: ... + def s(self, name: str) -> str: ... + def s_(self, name: str, val: str) -> Node: ... + def ss(self, name: str) -> list[str]: ... + def ss_(self, name: str, val: list[str]) -> Node: ... + def i(self, name: str) -> _int: ... + def i_(self, name: str, val: _int) -> Node: ... + # Cannot define "is" like this because it's a reserved keyword in python. + # def is(self, name: str) -> List[_int]: ... + # def is_(self, name: str, val: List[_int]) -> Node: ... + def g(self, name: str) -> Graph: ... + def g_(self, name: str, val: Graph) -> Node: ... + def gs(self, name: str) -> list[Graph]: ... + def gs_(self, name: str, val: list[Graph]) -> Node: ... + def ival(self, name: str) -> IValue: ... + def ival_(self, name: str, val: IValue) -> Node: ... + def t(self, name: str) -> Tensor: ... + def t_(self, name: str, val: Tensor) -> Node: ... + def ts(self, name: str) -> list[Tensor]: ... + def ts_(self, name: str, val: list[Tensor]) -> Node: ... + def ty(self, name: str) -> JitType: ... + def ty_(self, name: str, val: JitType) -> Node: ... + def tys(self, name: str) -> list[JitType]: ... + def tys_(self, name: str, val: list[JitType]) -> Node: ... + +# Defined in torch/torch/csrc/jit/ir/ir.h +class Graph: + def inputs(self) -> Iterator[Value]: ... + def outputs(self) -> Iterator[Value]: ... + def nodes(self) -> Iterator[Node]: ... + def param_node(self) -> Node: ... + def return_node(self) -> Node: ... + def addInput(self, name: str = "") -> Value: ... + def eraseInput(self, i: _int) -> None: ... + def registerOutput(self, n: Value) -> _int: ... + def eraseOutput(self, i: _int) -> None: ... + def create(self, name: str, args, num_outputs: _int) -> Node: ... + def appendNode(self, n: Node) -> Node: ... + def prependNode(self, n: Node) -> Node: ... + def insertNode(self, n: Node) -> Node: ... + def block(self) -> Block: ... + def lint(self) -> None: ... + def alias_db(self) -> AliasDb: ... + def setInsertPoint(self, n: Block | Node) -> None: ... + def insert_point_guard(self, n: Block | Node) -> _InsertPoint: ... + def insertPoint(self) -> Node: ... + def insertGraph(self, callee: Graph, inputs: list[Value]) -> list[Value]: ... + def makeMultiOutputIntoTuple(self) -> None: ... + def copy(self) -> Graph: ... + +# Defined in torch/aten/src/ATen/core/alias_info.h +class AliasInfo: + is_write: _bool + before_set: set[str] + after_set: set[str] + def __init__( + self, + is_write: _bool, + before_set: set[str], + after_set: set[str], + ) -> None: ... + +# Defined in torch/aten/src/ATen/core/function_schema.h +class Argument: + name: str + type: JitType + default_value: Any | None + def has_default_value(self) -> _bool: ... + kwarg_only: _bool + is_out: _bool + alias_info: AliasInfo | None + is_write: _bool + real_type: JitType + def __init__( + self, + name: str, + type: JitType, + N: _int | None, + defualt_value: Any | None, + kwarg_only: _bool, + alias_info: AliasInfo | None, + ) -> None: ... + +class FunctionSchema: + arguments: list[Argument] + returns: list[Argument] + name: str + overload_name: str + is_mutable: _bool + def __init__( + self, + name: str, + overload_name: str, + arguments: list[Argument], + returns: list[Argument], + is_vararg: _bool, + is_varret: _bool, + ) -> None: ... + def _is_view_op(self) -> _bool: ... + +class _UpgraderEntry: + bumped_at_version: _int + upgrader_name: str + old_schema: str + def __init__( + self, + bumped_at_version: _int, + upgrader_name: str, + old_schema: str, + ) -> None: ... + +class _UpgraderRange: + min_version: _int + max_version: _int + +def _get_max_operator_version() -> _int: ... +def _get_operator_version_map() -> dict[str, list[_UpgraderEntry]]: ... +def _get_upgrader_ranges(name: str) -> list[_UpgraderRange]: ... +def _test_only_add_entry_to_op_version(op_name: str, entry: _UpgraderEntry) -> None: ... +def _test_only_remove_entry_to_op_version(op_name: str) -> None: ... + +# Defined in torch/csrc/jit/python/script_init.cpp +class ScriptModuleSerializer: + def __init__(self, export_writer: PyTorchFileWriter) -> None: ... + def serialize(self, model: ScriptModule, script_module_id: _int) -> None: ... + def write_files(self) -> None: ... + def storage_context(self) -> SerializationStorageContext: ... + +# Defined in torch/csrc/jit/python/script_init.cpp +class SerializationStorageContext: + def __init__(self) -> None: ... + def has_storage(self, storage: Storage) -> _bool: ... + def get_or_add_storage(self, storage: Storage) -> _int: ... + +# Defined in torch/csrc/jit/python/script_init.cpp +class DeserializationStorageContext: + def __init__(self) -> None: ... + def get_storage(self, name: str, dtype: _dtype) -> Tensor: ... + def has_storage(self, name: str) -> _bool: ... + def add_storage(self, name: str, tensor: Tensor) -> _int: ... + +# Defined in torch/csrc/jit/python/script_init.cpp +class ConcreteModuleTypeBuilder: + def __init__(self, obj: Any) -> None: ... + def set_module_dict(self): ... + def set_module_list(self): ... + def set_parameter_list(self): ... + def set_parameter_dict(self): ... + def add_attribute( + self, + name: str, + ty: JitType, + is_param: _bool, + is_buffer: _bool, + ): ... + def add_module(self, name: str, meta: ConcreteModuleType): ... + def add_constant(self, name: str, value: Any): ... + def add_overload(self, method_name: str, overloaded_method_names: list[str]): ... + def add_builtin_function(self, name: str, symbol_name: str): ... + def add_failed_attribute(self, name: str, failure_reason: str): ... + def add_function_attribute( + self, + name: str, + ty: JitType, + func: Callable[..., Any], + ): ... + def add_ignored_attribute(self, name: str): ... + def add_ignored_attributes(self, names: list[str]): ... + def add_forward_hook(self, hook: Callable[..., Any]): ... + def add_forward_pre_hook(self, pre_hook: Callable[..., Any]): ... + +class ConcreteModuleType: + def get_constants(self) -> dict[str, Any]: ... + def equals(self, other: ConcreteModuleType) -> _bool: ... + @staticmethod + def from_jit_type(ty: JitType) -> ConcreteModuleType: ... + +class CallStack: + def __init__(self, name: str, range: SourceRange) -> None: ... + +class ErrorReport: + def __init__(self, range: SourceRange) -> None: ... + def what(self) -> str: ... + @staticmethod + def call_stack() -> str: ... + +class CompilationUnit: + def __init__(self, lang: str = ..., _frames_up: _int = ...) -> None: ... + def find_function(self, name: str) -> ScriptFunction: ... + def __getattr__(self, name: str) -> ScriptFunction: ... + def define( + self, + script: str, + rcb: ResolutionCallback = ..., + _frames_up: _int = ..., + ): ... + def get_interface(self, name: str) -> InterfaceType: ... + def get_functions(self) -> list[ScriptFunction]: ... + def create_function( + self, + name: str, + graph: Graph, + shouldMangle: _bool = ..., + ) -> ScriptFunction: ... + def get_class(self, name: str) -> ClassType: ... + +class ScriptObject: + def setattr(self, name: str, value: Any): ... + def _get_method(self, name: str) -> ScriptMethod: ... + def _type(self) -> ClassType: ... + +class ScriptModule(ScriptObject): + def _method_names(self) -> list[str]: ... + def _get_method(self, name: str) -> ScriptMethod: ... + +class LiteScriptModule: + def __call__(self, *input): ... + def find_method(self, method_name: str): ... + def forward(self, *input) -> list[str]: ... + def run_method(self, method_name: str, *input): ... + +# NOTE: switch to collections.abc.Callable in python 3.9 +class ScriptFunction(Generic[P, R]): + def __call__(self, *args: P.args, **kwargs: P.kwargs) -> R: ... + def save(self, filename: str, _extra_files: dict[str, bytes]) -> None: ... + def save_to_buffer(self, _extra_files: dict[str, bytes]) -> bytes: ... + @property + def graph(self) -> Graph: ... + def inlined_graph(self) -> Graph: ... + def schema(self) -> FunctionSchema: ... + def code(self) -> str: ... + def name(self) -> str: ... + @property + def qualified_name(self) -> str: ... + +# NOTE: switch to collections.abc.Callable in python 3.9 +class ScriptMethod(Generic[P, R]): + graph: Graph + def __call__(self, *args: P.args, **kwargs: P.kwargs) -> R: ... + @property + def owner(self) -> ScriptModule: ... + @property + def name(self) -> str: ... + @property + def schema(self) -> FunctionSchema: ... + +class ScriptDict(Generic[K, T]): + def __init__(self, dict: dict[K, T]) -> None: ... + def __len__(self) -> _int: ... + def __contains__(self, key: K) -> _bool: ... + def __getitem__(self, key: K) -> T: ... + def __setitem__(self, key: K, value: T) -> None: ... + def __delitem__(self, key: K) -> None: ... + def __iter__(self) -> Iterator[K]: ... + def items(self) -> Iterator[tuple[K, T]]: ... + def keys(self) -> Iterator[K]: ... + +class ScriptList(Generic[T]): + def __init__(self, list: list[T]) -> None: ... + def __len__(self) -> _int: ... + def __contains__(self, item: T) -> _bool: ... + @overload + def __getitem__(self, idx: _int) -> T: ... + @overload + def __getitem__(self, idx: slice) -> ScriptList[T]: ... + @overload + def __setitem__(self, idx: _int, value: T) -> None: ... + @overload + def __setitem__(self, idx: slice, value: list[T]) -> None: ... + def __delitem__(self, idx: _int) -> None: ... + def __iter__(self) -> Iterator[T]: ... + def count(self, value: T) -> _int: ... + def remove(self, value: T) -> None: ... + def append(self, value: T) -> None: ... + def clear(self) -> None: ... + @overload + def extend(self, values: list[T]) -> None: ... + @overload + def extend(self, values: Iterable[T]) -> None: ... + @overload + def pop(self) -> T: ... + @overload + def pop(self, idx: _int) -> T: ... + +class ModuleDict: + def __init__(self, mod: ScriptModule) -> None: ... + def items(self) -> list[tuple[str, Any]]: ... + +class ParameterDict: + def __init__(self, mod: ScriptModule) -> None: ... + +class BufferDict: + def __init__(self, mod: ScriptModule) -> None: ... + +# Defined in torch/csrc/jit/api/module.h +class Module: ... + +# Defined in torch/csrc/Module.cpp +def _initExtension(shm_manager_path: str) -> None: ... # THPModule_initExtension +def _autograd_init() -> _bool: ... # THPAutograd_initExtension +def _add_docstr(obj: T, doc_obj: str) -> T: ... # THPModule_addDocStr +def _init_names(arg: Sequence[type]) -> None: ... # THPModule_initNames +def _has_distributed() -> _bool: ... # THPModule_hasDistributed +def _set_default_tensor_type(type) -> None: ... # THPModule_setDefaultTensorType +def _set_default_dtype(d: _dtype) -> None: ... # THPModule_setDefaultDtype +def _infer_size(arg1: Size, arg2: Size) -> Size: ... # THPModule_inferSize +def _crash_if_csrc_asan() -> _int: ... # THPModule_crashIfCsrcASAN +def _crash_if_csrc_ubsan() -> _int: ... # THPModule_crashIfCsrcUBSAN +def _crash_if_aten_asan() -> _int: ... # THPModule_crashIfATenASAN +def _show_config() -> str: ... # THPModule_showConfig +def _cxx_flags() -> str: ... # THPModule_cxxFlags +def _parallel_info() -> str: ... # THPModule_parallelInfo +def _get_cpu_capability() -> str: ... # THPModule_getCpuCapability +def _set_backcompat_broadcast_warn( + arg: _bool, +) -> None: ... # THPModule_setBackcompatBroadcastWarn +def _get_backcompat_broadcast_warn() -> ( + _bool +): ... # THPModule_getBackcompatBroadcastWarn +def _set_backcompat_keepdim_warn( + arg: _bool, +) -> None: ... # THPModule_setBackcompatKeepdimWarn +def _get_backcompat_keepdim_warn() -> _bool: ... # THPModule_getBackcompatKeepdimWarn +def get_num_thread() -> _int: ... # THPModule_getNumThreads +def set_num_threads(nthreads: _int) -> None: ... # THPModule_setNumThreads +def get_num_interop_threads() -> _int: ... # THPModule_getNumInteropThreads +def set_num_interop_threads( + nthreads: _int, +) -> None: ... # THPModule_setNumInteropThreads +def _get_cudnn_enabled() -> _bool: ... # THPModule_userEnabledCuDNN +def _set_cudnn_enabled(arg: _bool) -> None: ... # THPModule_setUserEnabledCuDNN +def _get_flash_sdp_enabled() -> _bool: ... # THPModule_userEnabledFusedSDP +def _set_sdp_use_flash(arg: _bool) -> None: ... # THPModule_setSDPUseFlash +def _get_mem_efficient_sdp_enabled() -> _bool: ... # THPModule_userEnabledMathSDP +def _set_sdp_use_mem_efficient( + arg: _bool, +) -> None: ... # THPModule_setSDPUseMemEfficient +def _get_math_sdp_enabled() -> _bool: ... # THPModule_userEnabledMathSDP +def _set_sdp_use_math(arg: _bool) -> None: ... # THPModule_setSDPUseMath +def _get_math_sdp_allow_fp16_bf16_reduction() -> ( + _bool +): ... # THPModule_allowFP16BF16ReductionMathSDP +def _set_math_sdp_allow_fp16_bf16_reduction( + arg: _bool, +) -> None: ... # THPModule_setAllowFP16BF16ReductionMathSDP +def _get_overrideable_sdp_enabled() -> ( + _bool +): ... # THPModule_userEnabledOverrideableSDP +def _set_sdp_use_overrideable( + arg: _bool, +) -> None: ... # THPModule_setSDPUseOverrideable +def _get_sdp_priority_order() -> list[_int]: ... # THPModule_getSDPPriorityOrder +def _set_sdp_priority_order( + arg: list[_int], +) -> None: ... # THPModule_setSDPPriorityOrder +def _get_cudnn_sdp_enabled() -> _bool: ... # THPModule_userEnabledMathSDP +def _set_sdp_use_cudnn(arg: _bool) -> None: ... # THPModule_setSDPUseMath +def _get_mkldnn_enabled() -> _bool: ... # THPModule_userEnabledMkldnn +def _set_mkldnn_enabled(arg: _bool) -> None: ... # THPModule_setUserEnabledMkldnn +def _get_cudnn_benchmark() -> _bool: ... # THPModule_benchmarkCuDNN +def _set_cudnn_benchmark(arg: _bool) -> None: ... # THPModule_setBenchmarkCuDNN +def _get_miopen_immediate() -> _bool: ... # THPModule_userImmediateMiopen +def _set_miopen_immediate(arg: _bool) -> None: ... # THPModule_setUserImmediateMiopen +def _get_cudnn_deterministic() -> _bool: ... # THPModule_deterministicCuDNN +def _set_cudnn_deterministic(arg: _bool) -> None: ... # THPModule_setDeterministicCuDNN +def _get_mkldnn_deterministic() -> _bool: ... # THPModule_deterministicMkldnn +def _set_mkldnn_deterministic( + arg: _bool, +) -> None: ... # THPModule_setDeterministicMkldnn +def _get_onednn_allow_tf32() -> _bool: ... # THPModule_allowTF32OneDNN +def _set_onednn_allow_tf32(arg: _bool) -> None: ... # THPModule_setAllowTF32OneDNN +def _get_deterministic_algorithms() -> _bool: ... # THPModule_deterministicAlgorithms +def _get_deterministic_algorithms_warn_only() -> ( + _bool +): ... # THPModule_deterministicAlgorithmsWarnOnly +def _set_deterministic_algorithms( + mode: _bool, + *, + warn_only: _bool = ..., +) -> None: ... # THPModule_setDeterministicAlgorithms +def _get_deterministic_fill_uninitialized_memory() -> ( + _bool +): ... # THPModule_deterministicFillUninitializedMemory +def _set_deterministic_fill_uninitialized_memory( + arg: _bool, +) -> None: ... # THPModule_setDeterministicFillUninitializedMemory +def _get_nnpack_enabled() -> _bool: ... # THPModule_userEnabledNNPACK +def _set_nnpack_enabled(arg: _bool) -> None: ... # THPModule_setUserEnabledNNPACK +def _get_warnAlways() -> _bool: ... # THPModule_warnAlways +def _set_warnAlways(arg: _bool) -> None: ... # THPModule_setWarnAlways +def _get_cudnn_allow_tf32() -> _bool: ... # THPModule_allowTF32CuDNN +def _set_cudnn_allow_tf32(arg: _bool) -> None: ... # THPModule_setAllowTF32CuDNN +def _get_cublas_allow_tf32() -> _bool: ... # THPModule_allowTF32CuBLAS +def _set_cublas_allow_tf32(arg: _bool) -> None: ... # THPModule_setAllowTF32CuBLAS +def _get_float32_matmul_precision() -> str: ... # THPModule_float32MatmulPrecision +def _set_float32_matmul_precision( + arg: str, +) -> None: ... # THPModule_setFloat32MatmulPrecision +def _get_cublas_allow_fp16_reduced_precision_reduction() -> tuple[ + _bool, _bool +]: ... # THPModule_allowFP16ReductionCuBLAS +def _set_cublas_allow_fp16_reduced_precision_reduction( + arg: _bool, + allow_splitk: _bool = ..., +) -> None: ... # THPModule_setAllowFP16ReductionCuBLAS +def _get_cublas_allow_bf16_reduced_precision_reduction() -> tuple[ + _bool, _bool +]: ... # THPModule_allowBF16ReductionCuBLAS +def _set_cublas_allow_bf16_reduced_precision_reduction( + arg: _bool, + allow_splitk: _bool = ..., +) -> None: ... # THPModule_setAllowBF16ReductionCuBLAS +def _get_cublas_allow_fp16_accumulation() -> ( + _bool +): ... # THPModule_allowFP16AccumulationCuBLAS +def _set_cublas_allow_fp16_accumulation( + arg: _bool, +) -> None: ... # THPModule_setAllowFP16AccumulationCuBLAS +def _get_sm_carveout_experimental() -> _int | None: ... +def _set_sm_carveout_experimental(arg: _int | None) -> None: ... +def _set_conj(x: Tensor, conj: _bool) -> None: ... +def _set_neg(x: Tensor, neg: _bool) -> None: ... +def _set_meta_in_tls_dispatch_include(meta_in_tls: _bool) -> None: ... +def _autocast_supported_devices() -> list[str]: ... +def _meta_in_tls_dispatch_include() -> _bool: ... +def _stash_obj_in_tls(key: str, arg: Any) -> None: ... +def _get_obj_in_tls(key: str) -> Any: ... +def _is_key_in_tls(key: str) -> _bool: ... +def _select_batch_norm_backend(*args, **kwargs) -> BatchNormBackend: ... +def _select_conv_backend(*args, **kwargs) -> ConvBackend: ... +def _conv_determine_backend_memory_format( + input: Tensor, + weight: Tensor, + backend: ConvBackend, +) -> memory_format: ... +def _has_storage(x: Tensor) -> _bool: ... +def _construct_storage_from_data_pointer( + data_ptr: _int, + device: torch.device, + size: _int, +) -> Storage: ... +def _should_allow_numbers_as_tensors(func_name: str) -> _bool: ... +def _group_tensors_by_device_and_dtype( + nested_tensorlists: list[list[Tensor | None]], + with_indices: _bool = False, +) -> dict[ + tuple[torch.device, torch.dtype], + tuple[list[list[Tensor | None]], list[_int]], +]: ... +def _initCrashHandler() -> None: ... +def _set_warn_on_accumulate_grad_stream_mismatch(enabled: _bool) -> None: ... + +# NB: There is no Capsule type in typing, see +# https://github.com/python/cpython/issues/109562 +def _to_dlpack( + data: Tensor, + dl_device: tuple[IntEnum, _int] | None = None, + copy: _bool | None = None, +) -> Any: ... # THPModule_toDLPack +def _to_dlpack_versioned( + data: Tensor, + dl_device: tuple[IntEnum, _int] | None = None, + copy: _bool | None = None, +) -> Any: ... # THPModule_toDLPackVersioned +def _from_dlpack(data: Any) -> Tensor: ... # THPModule_fromDLPack +def _torchDeviceToDLDevice( + device: torch.device, +) -> tuple[_int, _int]: ... # THPModule_torchDeviceToDLDevice +def _dlpack_exchange_api() -> object: ... # THPModule_DLPackExchangeAPI +def _get_cpp_backtrace( + frames_to_skip: _int, + maximum_number_of_frames: _int, +) -> str: ... # THPModule_getCppBacktrace +def set_flush_denormal(arg: _bool) -> _bool: ... # THPModule_setFlushDenormal +def get_default_dtype() -> _dtype: ... # THPModule_getDefaultDtype +def _get_default_device() -> str: ... # THPModule_getDefaultDevice +def _get_qengine() -> _int: ... # THPModule_qEngine +def _set_qengine(qengine: _int) -> None: ... # THPModule_setQEngine +def _supported_qengines() -> list[_int]: ... # THPModule_supportedQEngines +def _is_xnnpack_enabled() -> _bool: ... # THPModule_isEnabledXNNPACK +def _check_sparse_tensor_invariants() -> ( + _bool +): ... # THPModule_checkSparseTensorInvariants +def _set_check_sparse_tensor_invariants( + arg: _bool, +) -> None: ... # THPModule_setCheckSparseTensorInvariants +def _is_default_mobile_cpu_allocator_set() -> ( + _bool +): ... # THPModule_isDefaultMobileCPUAllocatorSet +def _set_default_mobile_cpu_allocator() -> ( + None +): ... # THPModule_setDefaultMobileCPUAllocator +def _unset_default_mobile_cpu_allocator() -> ( + None +): ... # THPModule_unsetDefaultMobileCPUAllocator +def _is_torch_function_enabled() -> _bool: ... # THPModule_isEnabledTorchFunction +def _is_torch_function_all_disabled() -> ( + _bool +): ... # THPModule_isAllDisabledTorchFunction +def _has_torch_function( + args: Iterable[Any], +) -> _bool: ... # THPModule_has_torch_function +def _has_torch_function_unary(Any) -> _bool: ... # THPModule_has_torch_function_unary +def _has_torch_function_variadic( + *args: Any, +) -> _bool: ... # THPModule_has_torch_function_variadic +def _vmapmode_increment_nesting() -> _int: ... # THPModule_vmapmode_increment_nesting +def _vmapmode_decrement_nesting() -> _int: ... # THPModule_vmapmode_decrement_nesting +def _log_api_usage_once(str) -> None: ... # LogAPIUsageOnceFromPython +def _log_api_usage_metadata( + event: str, + metadata_map: dict[str, str], +) -> None: ... # LogAPIUsageMetadataFromPython +def _demangle(str) -> str: ... # c10::demangle +def _disabled_torch_function_impl( + func: Callable, + types: Iterable[type], + args: tuple, + kwargs: dict, +) -> Any: ... # THPModule_disable_torch_function +def _disabled_torch_dispatch_impl( + func: Callable, + types: Iterable[type], + args: tuple, + kwargs: dict, +) -> Any: ... # THPModule_disable_dispatch_function +def _get_linalg_preferred_backend() -> _LinalgBackend: ... +def _set_linalg_preferred_backend(arg: _LinalgBackend): ... +def _get_fp32_precision_getter(backend: str, op: str) -> str: ... +def _set_fp32_precision_setter(backend: str, op: str, value: str) -> str: ... +def _ensureCUDADeviceGuardSet() -> None: ... + +class _LinalgBackend: + Default: _LinalgBackend + Cusolver: _LinalgBackend + Magma: _LinalgBackend + +# mypy error: +# Detected enum "torch._C.BatchNormBackend" in a type stub with zero +# members. There is a chance this is due to a recent change in the semantics +# of enum membership. If so, use `member = value` to mark an enum member, +# instead of `member: type` +class BatchNormBackend(Enum): ... # type: ignore[misc] + +def _get_blas_preferred_backend() -> _BlasBackend: ... +def _set_blas_preferred_backend(arg: _BlasBackend): ... + +class _BlasBackend: + Default: _BlasBackend + Cublas: _BlasBackend + Cublaslt: _BlasBackend + Ck: _BlasBackend + +def _get_rocm_fa_preferred_backend() -> torch._C._ROCmFABackend: ... +def _set_rocm_fa_preferred_backend(arg: torch._C._ROCmFABackend): ... + +class _ROCmFABackend: + Default: _ROCmFABackend + AOTriton: _ROCmFABackend + Ck: _ROCmFABackend + +# mypy error: +# Error (MYPY) [misc] +# Detected enum "torch._C.ConvBackend" in a type stub with zero members. +# There is a chance this is due to a recent change in the semantics of enum +# membership. If so, use `member = value` to mark an enum member, instead of +# `member: type` +class ConvBackend(Enum): ... # type: ignore[misc] + +class Tag(Enum): + core = 0 + cudagraph_unsafe = 1 + data_dependent_output = 2 + dynamic_output_shape = 3 + flexible_layout = 4 + generated = 5 + inplace_view = 6 + maybe_aliasing_or_mutating = 7 + needs_contiguous_strides = 8 + needs_exact_strides = 9 + needs_fixed_stride_order = 10 + nondeterministic_bitwise = 11 + nondeterministic_seeded = 12 + pointwise = 13 + pt2_compliant_tag = 14 + reduction = 15 + view_copy = 16 + +# Defined in `valgrind.h` and `callgrind.h` respectively. +def _valgrind_supported_platform() -> _bool: ... # NVALGRIND +def _valgrind_toggle() -> None: ... # CALLGRIND_TOGGLE_COLLECT +def _valgrind_toggle_and_dump_stats() -> ( + None +): ... # CALLGRIND_TOGGLE_COLLECT and CALLGRIND_DUMP_STATS + +has_openmp: _bool +has_mkl: _bool +_has_kleidiai: _bool +_has_mps: _bool +has_lapack: _bool +_has_cuda: _bool +_has_magma: _bool +_has_xpu: _bool +_has_mkldnn: _bool +_has_mkldnn_acl: _bool +_has_cudnn: _bool +_has_cusparselt: _bool +has_spectral: _bool +_GLIBCXX_USE_CXX11_ABI: _bool +default_generator: Generator + +# Defined in torch/csrc/autograd/init.cpp +def _set_grad_enabled(enabled: _bool) -> None: ... +def is_grad_enabled() -> _bool: ... +def _set_fwd_grad_enabled(enabled: _bool) -> None: ... +def _is_fwd_grad_enabled() -> _bool: ... +def _any_requires_grad(*args, **kwargs) -> _bool: ... +def _any_output_is_alias_to_input_or_output(*args, **kwargs) -> _bool: ... +def is_inference_mode_enabled() -> _bool: ... +@overload +def set_autocast_enabled(device_type: str, enabled: _bool) -> None: ... +@overload +def set_autocast_enabled(enabled: _bool) -> None: ... +@overload +def is_autocast_enabled(device_type: str) -> _bool: ... +@overload +def is_autocast_enabled() -> _bool: ... +def set_autocast_dtype(device_type: str, dtype: _dtype) -> None: ... +def get_autocast_dtype(device_type: str) -> _dtype: ... +def clear_autocast_cache() -> None: ... +def set_autocast_cpu_enabled(enabled: _bool) -> None: ... +def is_autocast_cpu_enabled() -> _bool: ... +def _is_any_autocast_enabled() -> _bool: ... +def _is_autocast_available(device_type: str) -> _bool: ... +def set_autocast_cpu_dtype(dtype: _dtype) -> None: ... +def set_autocast_gpu_dtype(dtype: _dtype) -> None: ... +def get_autocast_cpu_dtype() -> _dtype: ... +def get_autocast_gpu_dtype() -> _dtype: ... +def autocast_increment_nesting() -> _int: ... +def autocast_decrement_nesting() -> _int: ... +def is_autocast_cache_enabled() -> _bool: ... +def set_autocast_cache_enabled(enabled: _bool) -> None: ... +def _increment_version(tensors: Iterable[Tensor]) -> None: ... +def set_anomaly_enabled(enabled: _bool, check_nan: _bool = True) -> None: ... +def is_anomaly_enabled() -> _bool: ... +def is_anomaly_check_nan_enabled() -> _bool: ... +def _is_multithreading_enabled() -> _bool: ... +def _set_multithreading_enabled(enabled: _bool) -> None: ... +def _set_view_replay_enabled(enabled: _bool) -> None: ... +def _is_view_replay_enabled() -> _bool: ... +def _set_graph_exec_group(group: GraphExecGroup | None) -> None: ... +def _get_graph_exec_group() -> GraphExecGroup | None: ... +def _enter_dual_level() -> _int: ... +def _exit_dual_level(level: _int) -> None: ... +def _make_dual(tensor: Tensor, tangent: Tensor, level: _int) -> Tensor: ... +def _unpack_dual(tensor: Tensor, level: _int) -> Tensor: ... +def __set_forward_AD_enabled(enabled: _bool) -> None: ... +def __is_forward_AD_enabled() -> _bool: ... +def _register_default_hooks(pack_hook: Callable, unpack_hook: Callable) -> None: ... +def _reset_default_hooks() -> None: ... +def _is_torch_function_mode_enabled() -> _bool: ... +def _push_on_torch_function_stack(cls: Any) -> None: ... +def _pop_torch_function_stack() -> Any: ... +def _get_function_stack_at(idx: _int) -> Any: ... +def _len_torch_function_stack() -> _int: ... +def _set_torch_dispatch_mode(cls: Any) -> None: ... +def _push_on_torch_dispatch_stack(cls: TorchDispatchMode) -> None: ... +def _pop_torch_dispatch_stack(mode_key: _TorchDispatchModeKey | None = None) -> Any: ... +def _get_dispatch_mode(mode_key: _TorchDispatchModeKey | None) -> Any: ... +def _unset_dispatch_mode(mode: _TorchDispatchModeKey) -> TorchDispatchMode | None: ... +def _set_dispatch_mode(mode: TorchDispatchMode) -> None: ... +def _get_dispatch_stack_at(idx: _int) -> Any: ... +def _len_torch_dispatch_stack() -> _int: ... +def _activate_gpu_trace() -> None: ... + +class _DisableTorchDispatch: + def __init__(self) -> None: ... + def __enter__(self): ... + def __exit__(self, *exc_info: object) -> None: ... + +class _EnableTorchFunction: + def __init__(self) -> None: ... + def __enter__(self): ... + def __exit__(self, *exc_info: object) -> None: ... + +class _EnablePythonDispatcher: + def __init__(self) -> None: ... + def __enter__(self): ... + def __exit__(self, *exc_info: object) -> None: ... + +class _DisablePythonDispatcher: + def __init__(self) -> None: ... + def __enter__(self): ... + def __exit__(self, *exc_info: object) -> None: ... + +class _EnablePreDispatch: + def __init__(self) -> None: ... + def __enter__(self): ... + def __exit__(self, *exc_info: object) -> None: ... + +class _DisableFuncTorch: + def __init__(self) -> None: ... + def __enter__(self): ... + def __exit__(self, *exc_info: object) -> None: ... + +class _DisableAutocast: + def __init__(self) -> None: ... + def __enter__(self): ... + def __exit__(self, *exc_info: object) -> None: ... + +class _InferenceMode: + def __init__(self, enabled: _bool) -> None: ... + def __enter__(self): ... + def __exit__(self, *exc_info: object) -> None: ... + +def _set_autograd_fallback_mode(mode: str) -> None: ... +def _get_autograd_fallback_mode() -> str: ... + +# Defined in torch/csrc/jit/python/script_init.cpp +class LoggerBase: ... +class NoopLogger(LoggerBase): ... +class LockingLogger(LoggerBase): ... + +class AggregationType(Enum): + SUM = 0 + AVG = 1 + +class FileCheck: + def run(self, test_string: str) -> None: ... + def check(self, test_string: str) -> FileCheck: ... + def check_not(self, test_string: str) -> FileCheck: ... + def check_same(self, test_string: str) -> FileCheck: ... + def check_next(self, test_string: str) -> FileCheck: ... + def check_count( + self, + test_string: str, + count: _int, + exactly: _bool = False, + ) -> FileCheck: ... + def check_dag(self, test_string: str) -> FileCheck: ... + def check_source_highlighted(self, test_string: str) -> FileCheck: ... + def check_regex(self, test_string: str) -> FileCheck: ... + +# Defined in torch/csrc/jit/python/init.cpp +class PyTorchFileReader: + @overload + def __init__(self, name: str) -> None: ... + @overload + def __init__(self, buffer: IO[bytes]) -> None: ... + def get_record(self, name: str) -> bytes: ... + def get_all_records(self) -> list[str]: ... + def serialization_id(self) -> str: ... + +class PyTorchFileWriter: + @overload + def __init__( + self, + name: str, + compute_crc32: _bool = True, + storage_alignment: _int = 64, + ) -> None: ... + @overload + def __init__( + self, + buffer: IO[bytes], + compute_crc32: _bool = True, + storage_alignment: _int = 64, + ) -> None: ... + def write_record( + self, + name: str, + data: Storage | bytes | _int, + size: _int, + ) -> None: ... + def write_end_of_file(self) -> None: ... + def set_min_version(self, version: _int) -> None: ... + def get_all_written_records(self) -> list[str]: ... + def archive_name(self) -> str: ... + def serialization_id(self) -> str: ... + +def _jit_get_inline_everything_mode() -> _bool: ... +def _jit_set_inline_everything_mode(enabled: _bool) -> None: ... +def _jit_get_logging_option() -> str: ... +def _jit_set_logging_option(option: str) -> None: ... +def _jit_set_logging_stream(stream_name: str) -> None: ... +def _jit_pass_cse(Graph) -> _bool: ... +def _jit_pass_dce(Graph) -> None: ... +def _jit_pass_dce_graph(Graph) -> None: ... +def _jit_pass_lint(Graph) -> None: ... +def _register_opaque_type(type_name: str) -> None: ... +def _is_opaque_type_registered(type_name: str) -> _bool: ... + +# Defined in torch/csrc/jit/python/python_custom_class.cpp +def _get_custom_class_python_wrapper(name: str, attr: str) -> Any: ... + +# Defined in torch/csrc/Module.cpp +def _rename_privateuse1_backend(backend: str) -> None: ... +def _get_privateuse1_backend_name() -> str: ... + +# Defined in torch/csrc/Generator.cpp +class Generator: + device: _device + def __init__(self, device: DeviceLikeType | None = None) -> None: ... + def __reduce__( + self, + ) -> tuple[type[Generator], tuple[_device], tuple[_int, _int | None, Tensor]]: ... + def __setstate__(self, state: tuple[_int, _int | None, Tensor]) -> None: ... + def get_state(self) -> Tensor: ... + def set_state(self, _new_state: Tensor) -> Generator: ... + def clone_state(self) -> Generator: ... + def graphsafe_get_state(self) -> Generator: ... + def graphsafe_set_state(self, _new_state: Generator) -> Generator: ... + def set_offset(self, offset: _int) -> Generator: ... + def get_offset(self) -> _int: ... + def manual_seed(self, seed: _int) -> Generator: ... + def seed(self) -> _int: ... + def initial_seed(self) -> _int: ... + +# Defined in torch/csrc/utils/python_dispatch.cpp + +class _DispatchOperatorHandle: + def schema(self) -> FunctionSchema: ... + def debug(self) -> str: ... + def redispatch_boxed(self, keyset: DispatchKeySet, *args, **kwargs) -> Any: ... + +class _DispatchModule: + def reset(self) -> None: ... + def def_(self, schema: str, alias: str = "") -> _DispatchModule: ... + def def_legacy(self, schema: str) -> _DispatchModule: ... + def def_name_t_t( + self, + name: str, + dispatch: str, + debug: str = "default_def_name_t_t", + ) -> _DispatchModule: ... + def def_schema_t_t( + self, + schema: str, + dispatch: str, + alias: str, + debug: str = "default_def_schema_t_t", + ) -> _DispatchModule: ... + def impl_t_t( + self, + name: str, + dispatch: str, + debug: str = "impl_t_t", + ) -> _DispatchModule: ... + def impl_with_aoti_compile( + self, + ns: str, + op_name_with_overload: str, + dispatch: _dispatchkey, + ) -> None: ... + def impl(self, name: str, dispatch: _dispatchkey, func: Callable) -> None: ... + def define(self, schema: str, alias: str = "") -> str: ... + def fallback_fallthrough(self, dispatch: str = "") -> _DispatchModule: ... + def fallback( + self, + dispatch: _dispatchkey, + func: Callable, + with_keyset: _bool = False, + ) -> None: ... + +_after_ADInplaceOrView_keyset: DispatchKeySet +_after_autograd_keyset: DispatchKeySet + +class _SafeKernelFunction: + def call_boxed(self, keyset: DispatchKeySet, *args, **kwargs) -> Any: ... + @property + def op_handle(self) -> _DispatchOperatorHandle: ... + +def _dispatch_library( + kind: str, + name: str, + dispatch: str, + file: str = "", + linenum: Any = 0, +) -> _DispatchModule: ... +def _dispatch_dump(name: str) -> str: ... +def _dispatch_dump_table(name: str) -> str: ... +def _dispatch_check_invariants(name: str) -> None: ... +def _dispatch_check_all_invariants() -> None: ... +def _dispatch_call_boxed(handle: _DispatchOperatorHandle, *args, **kwargs) -> Any: ... +def _dispatch_find_schema_or_throw( + name: str, + overload_name: str, +) -> _DispatchOperatorHandle: ... +def _dispatch_set_report_error_callback( + handle: _DispatchOperatorHandle, + callback: Callable, +) -> None: ... +def _dispatch_has_kernel(name: str) -> _bool: ... +def _dispatch_has_kernel_for_dispatch_key( + name: str, + dispatch: _dispatchkey, +) -> _bool: ... +def _dispatch_has_kernel_for_any_dispatch_key( + name: str, + dispatch_key_set: DispatchKeySet, +) -> _bool: ... +def _dispatch_kernel_for_dispatch_key_is_fallthrough( + name: str, + dispatch: _dispatchkey, +) -> _bool: ... +def _dispatch_has_computed_kernel_for_dispatch_key( + name: str, + dispatch: _dispatchkey, +) -> _bool: ... +def _dispatch_get_computed_kernel_for_dispatch_key( + name: str, + dispatch: _dispatchkey, +) -> _SafeKernelFunction: ... +def _dispatch_find_dangling_impls() -> list[str]: ... +def _dispatch_get_all_op_names() -> list[str]: ... +def _dispatch_tls_set_dispatch_key_excluded( + dispatch: _dispatchkey, + val: _bool, +) -> None: ... +def _dispatch_tls_is_dispatch_key_excluded(dispatch: _dispatchkey) -> _bool: ... +def _dispatch_tls_set_dispatch_key_included( + dispatch: _dispatchkey, + val: _bool, +) -> None: ... +def _dispatch_tls_is_dispatch_key_included(dispatch: _dispatchkey) -> _bool: ... +def _dispatch_isTensorSubclassLike(tensor: Tensor) -> _bool: ... +def _dispatch_key_name(dispatch: _dispatchkey) -> str: ... +def _dispatch_key_for_device(device_type: str) -> str: ... +def _parse_dispatch_key(key: str) -> DispatchKey | None: ... +def _dispatch_key_parse(dispatch: _dispatchkey) -> DispatchKey: ... +def _dispatch_num_backends() -> _int: ... +def _dispatch_pystub(name: str, overload: str) -> tuple[str, str] | None: ... +def _dispatch_is_alias_key(dispatch: _dispatchkey) -> _bool: ... +def _functionality_to_backend_keys(dispatch: _dispatchkey) -> list[DispatchKey]: ... +def _functionalization_reapply_views_tls() -> _bool: ... +def _only_lift_cpu_tensors() -> _bool: ... +def _set_only_lift_cpu_tensors(value: _bool) -> None: ... +def _set_throw_on_mutable_data_ptr(tensor: Tensor) -> None: ... +def _set_warn_deprecated_on_mutable_data_ptr(tensor: Tensor) -> None: ... + +class DispatchKey(Enum): + Undefined = ... + FPGA = ... + MAIA = ... + Vulkan = ... + Metal = ... + MKLDNN = ... + OpenGL = ... + OpenCL = ... + IDEEP = ... + CustomRNGKeyId = ... + MkldnnCPU = ... + Sparse = ... + SparseCsr = ... + NestedTensor = ... + Dense = ... + PythonTLSSnapshot = ... + PreDispatch = ... + PythonDispatcher = ... + Python = ... + FuncTorchDynamicLayerBackMode = ... + ZeroTensor = ... + Conjugate = ... + Negative = ... + BackendSelect = ... + Named = ... + AutogradOther = ... + AutogradFunctionality = ... + AutogradNestedTensor = ... + Tracer = ... + Autocast = ... + AutocastCPU = ... + AutocastCUDA = ... + Batched = ... + VmapMode = ... + FuncTorchGradWrapper = ... + FuncTorchBatched = ... + BatchedNestedTensor = ... + FuncTorchVmapMode = ... + FuncTorchDynamicLayerFrontMode = ... + Functionalize = ... + TESTING_ONLY_GenericWrapper = ... + TESTING_ONLY_GenericMode = ... + ADInplaceOrView = ... + Autograd = ... + CompositeImplicitAutograd = ... + CompositeImplicitAutogradNestedTensor = ... + CompositeExplicitAutograd = ... + CompositeExplicitAutogradNonFunctional = ... + FuncTorchBatchedDecomposition = ... + CPU = ... + CUDA = ... + HIP = ... + XLA = ... + MTIA = ... + MPS = ... + IPU = ... + XPU = ... + HPU = ... + VE = ... + Lazy = ... + Meta = ... + PrivateUse1 = ... + PrivateUse2 = ... + PrivateUse3 = ... + QuantizedCPU = ... + QuantizedCUDA = ... + QuantizedHIP = ... + QuantizedXLA = ... + QuantizedMTIA = ... + QuantizedMPS = ... + QuantizedIPU = ... + QuantizedXPU = ... + QuantizedHPU = ... + QuantizedVE = ... + QuantizedLazy = ... + QuantizedMeta = ... + QuantizedPrivateUse1 = ... + QuantizedPrivateUse2 = ... + QuantizedPrivateUse3 = ... + SparseCPU = ... + SparseCUDA = ... + SparseHIP = ... + SparseXLA = ... + SparseMTIA = ... + SparseMPS = ... + SparseIPU = ... + SparseXPU = ... + SparseHPU = ... + SparseVE = ... + SparseLazy = ... + SparseMeta = ... + SparsePrivateUse1 = ... + SparsePrivateUse2 = ... + SparsePrivateUse3 = ... + SparseCsrCPU = ... + SparseCsrCUDA = ... + SparseCsrHIP = ... + SparseCsrXLA = ... + SparseCsrMTIA = ... + SparseCsrMPS = ... + SparseCsrIPU = ... + SparseCsrXPU = ... + SparseCsrHPU = ... + SparseCsrVE = ... + SparseCsrLazy = ... + SparseCsrMeta = ... + SparseCsrPrivateUse1 = ... + SparseCsrPrivateUse2 = ... + SparseCsrPrivateUse3 = ... + NestedTensorCPU = ... + NestedTensorCUDA = ... + NestedTensorHIP = ... + NestedTensorXLA = ... + NestedTensorMTIA = ... + NestedTensorMPS = ... + NestedTensorIPU = ... + NestedTensorXPU = ... + NestedTensorHPU = ... + NestedTensorVE = ... + NestedTensorLazy = ... + NestedTensorMeta = ... + NestedTensorPrivateUse1 = ... + NestedTensorPrivateUse2 = ... + NestedTensorPrivateUse3 = ... + AutogradCPU = ... + AutogradCUDA = ... + AutogradHIP = ... + AutogradXLA = ... + AutogradMTIA = ... + AutogradMPS = ... + AutogradIPU = ... + AutogradXPU = ... + AutogradHPU = ... + AutogradVE = ... + AutogradLazy = ... + AutogradMeta = ... + AutogradPrivateUse1 = ... + AutogradPrivateUse2 = ... + AutogradPrivateUse3 = ... + +class DispatchKeySet: + def __init__(self, key: DispatchKey) -> None: ... + def __or__(self, other: DispatchKeySet) -> DispatchKeySet: ... + def __sub__(self, other: DispatchKeySet) -> DispatchKeySet: ... + def __and__(self, other: DispatchKeySet) -> DispatchKeySet: ... + def raw_repr(self) -> _int: ... + @staticmethod + def from_raw_repr(raw: _int) -> DispatchKeySet: ... + def highestPriorityTypeId(self) -> DispatchKey: ... + def has(self, k: _dispatchkey) -> _bool: ... + def add(self, k: _dispatchkey) -> DispatchKeySet: ... + def remove(self, k: _dispatchkey) -> DispatchKeySet: ... + +_dispatch_autogradother_backends: DispatchKeySet +_additional_keys_to_prop_for_wrapper_tensors: DispatchKeySet + +def _dispatch_has_backend_fallback(dispatch: _dispatchkey) -> _bool: ... +def _dispatch_keyset_full_after(t: _dispatchkey) -> DispatchKeySet: ... +def _dispatch_keyset_full() -> DispatchKeySet: ... +def _dispatch_keyset_to_string(keyset: DispatchKeySet) -> str: ... +def _dispatch_get_backend_keyset_from_autograd( + dispatch: _dispatchkey, +) -> DispatchKeySet: ... +def _dispatch_keys(tensor: Tensor) -> DispatchKeySet: ... +def _dispatch_tls_local_exclude_set() -> DispatchKeySet: ... +def _dispatch_tls_local_include_set() -> DispatchKeySet: ... +def _dispatch_is_included_in_alias( + dispatch_a: _dispatchkey, + dispatch_b: _dispatchkey, +) -> _bool: ... +def _propagate_xla_data(a: Tensor, b: Tensor) -> None: ... +def _replace_(a: Tensor, b: Tensor) -> None: ... +def _commit_update(a: Tensor) -> None: ... + +class _ExcludeDispatchKeyGuard: + def __init__(self, keyset: DispatchKeySet) -> None: ... + def __enter__(self): ... + def __exit__(self, *exc_info: object) -> None: ... + +class _IncludeDispatchKeyGuard: + def __init__(self, k: DispatchKey) -> None: ... + def __enter__(self): ... + def __exit__(self, *exc_info: object) -> None: ... + +class _ForceDispatchKeyGuard: + def __init__(self, include: DispatchKeySet, exclude: DispatchKeySet) -> None: ... + def __enter__(self): ... + def __exit__(self, *exc_info: object) -> None: ... + +class _PreserveDispatchKeyGuard: + def __init__(self) -> None: ... + def __enter__(self): ... + def __exit__(self, *exc_info: object) -> None: ... + +class _AutoDispatchBelowAutograd: + def __init__(self) -> None: ... + def __enter__(self): ... + def __exit__(self, *exc_info: object) -> None: ... + +class _AutoDispatchBelowADInplaceOrView: + def __init__(self) -> None: ... + def __enter__(self): ... + def __exit__(self, *exc_info: object) -> None: ... + +def _dispatch_print_registrations_for_dispatch_key(dispatch_key: str = "") -> None: ... +def _dispatch_get_registrations_for_dispatch_key( + dispatch_key: str = "", +) -> list[str]: ... +def _are_functorch_transforms_active() -> _bool: ... + +# Define in torch/csrc/autograd/init.cpp +def _set_python_dispatcher(dispatcher: object) -> None: ... +def _get_nested_int(id: _int, coeff: _int) -> SymInt: ... +def _get_constant_bool_symnode(val: _bool) -> Any: ... + +class _TorchDispatchModeKey(Enum): + FAKE = ... + PROXY = ... + FUNCTIONAL = ... + +class _SetExcludeDispatchKeyGuard: + def __init__(self, k: DispatchKey, enabled: _bool) -> None: ... + def __enter__(self): ... + def __exit__(self, *exc_info: object) -> None: ... + +def _get_dtensor_allow_implicit_replication() -> _bool: ... +def _set_dtensor_allow_implicit_replication(value: _bool) -> None: ... + +# Defined in torch/csrc/utils/schema_info.h + +class _SchemaInfo: + def __init__(self, schema: FunctionSchema) -> None: ... + @overload + def is_mutable(self) -> _bool: ... + @overload + def is_mutable(self, name: str) -> _bool: ... + def has_argument(self, name: str) -> _bool: ... + +# Defined in torch/csrc/utils/init.cpp +class BenchmarkConfig: + num_calling_threads: _int + num_worker_threads: _int + num_warmup_iters: _int + num_iters: _int + profiler_output_path: str + +class BenchmarkExecutionStats: + latency_avg_ms: _float + num_iters: _int + +class ThroughputBenchmark: + def __init__(self, module: Any) -> None: ... + def add_input(self, *args: Any, **kwargs: Any) -> None: ... + def run_once(self, *args: Any, **kwargs: Any) -> Any: ... + def benchmark(self, config: BenchmarkConfig) -> BenchmarkExecutionStats: ... + +# Defined in torch/csrc/Storage.cpp +class StorageBase: ... + +# TODO: where +class DoubleTensor(Tensor): ... +class FloatTensor(Tensor): ... +class BFloat16Tensor(Tensor): ... +class LongTensor(Tensor): ... +class IntTensor(Tensor): ... +class ShortTensor(Tensor): ... +class HalfTensor(Tensor): ... +class CharTensor(Tensor): ... +class ByteTensor(Tensor): ... +class BoolTensor(Tensor): ... + +# Defined in torch/csrc/autograd/python_engine.cpp +class _ImperativeEngine: + def queue_callback(self, callback: Callable[[], None]) -> None: ... + def run_backward(self, *args: Any, **kwargs: Any) -> tuple[Tensor, ...]: ... + def is_checkpoint_valid(self) -> _bool: ... + +# Defined in torch/csrc/autograd/python_variable.cpp +class _TensorMeta(type): ... + +_Index: TypeAlias = SupportsIndex | _bool | _int | slice | EllipsisType | Tensor | None | _NestedSequence[_bool | _int | slice | EllipsisType | Tensor | None] # fmt: skip + +# Defined in torch/csrc/autograd/python_variable.cpp +class TensorBase(metaclass=_TensorMeta): + requires_grad: _bool + retains_grad: _bool + shape: Size + data: Tensor + names: list[str] + device: _device + dtype: _dtype + grad_dtype: _dtype | None + layout: _layout + real: Tensor + imag: Tensor + T: Tensor + H: Tensor + mT: Tensor + mH: Tensor + ndim: _int + output_nr: _int + _version: _int + _base: Tensor | None + _cdata: _int + grad_fn: _Node | None + _grad_fn: Any + _grad: Tensor | None + grad: Tensor | None + _backward_hooks: dict[_int, Callable[[Tensor], Tensor | None]] | None + nbytes: _int + itemsize: _int + _has_symbolic_sizes_strides: _bool + + def _view_func_unsafe( + self, + new_base: Tensor, + symint_visitor_fn: Callable[[_int], _int] | None = None, + tensor_visitor_fn: Callable[[Tensor], Tensor] | None = None, + ): ... + def __abs__(self) -> Tensor: ... + def __add__(self, other: Tensor | Number | _complex) -> Tensor: ... + @overload + def __and__(self, other: Tensor) -> Tensor: ... + @overload + def __and__(self, other: Number | _complex) -> Tensor: ... + @overload + def __and__(self, other: Tensor | _int) -> Tensor: ... + def __bool__(self) -> _bool: ... + def __complex__(self) -> _complex: ... + def __contains__(self, item: Any, /) -> _bool: ... + def __div__(self, other: Tensor | Number | _complex) -> Tensor: ... + @overload + def __eq__(self, other: Tensor | Number | _complex) -> Tensor: ... # type: ignore[overload-overlap] + @overload + def __eq__(self, other: object) -> _bool: ... + def __float__(self) -> _float: ... + def __floordiv__(self, other: Tensor | Number | _complex) -> Tensor: ... + def __ge__(self, other: Tensor | Number | _complex) -> Tensor: ... + def __getitem__(self, indices: _Index | tuple[_Index, ...], /) -> Tensor: ... + def __gt__(self, other: Tensor | Number | _complex) -> Tensor: ... + def __iadd__(self, other: Tensor | Number | _complex) -> Tensor: ... # noqa: PYI034 + @overload + def __iand__(self, other: Tensor) -> Tensor: ... + @overload + def __iand__(self, other: Number | _complex) -> Tensor: ... + @overload + def __iand__(self, other: Tensor | _int) -> Tensor: ... + def __idiv__(self, other: Tensor | Number | _complex) -> Tensor: ... # noqa: PYI034 + def __ifloordiv__(self, other: Tensor | Number | _complex) -> Tensor: ... # noqa: PYI034 + @overload + def __ilshift__(self, other: Tensor) -> Tensor: ... + @overload + def __ilshift__(self, other: Number | _complex) -> Tensor: ... + @overload + def __ilshift__(self, other: Tensor | _int) -> Tensor: ... + def __imod__(self, other: Tensor | Number | _complex) -> Tensor: ... # noqa: PYI034 + def __imul__(self, other: Tensor | Number | _complex) -> Tensor: ... # noqa: PYI034 + def __index__(self) -> _int: ... + @overload + def __init__( + self, + *args: Any, + device: DeviceLikeType | None = None, + ) -> None: ... + @overload + def __init__(self, storage: Storage) -> None: ... + @overload + def __init__(self, other: Tensor) -> None: ... + @overload + def __init__( + self, + size: _size, + *, + device: DeviceLikeType | None = None, + ) -> None: ... + def __int__(self) -> _int: ... + def __invert__(self) -> Tensor: ... + @overload + def __ior__(self, other: Tensor) -> Tensor: ... + @overload + def __ior__(self, other: Number | _complex) -> Tensor: ... + @overload + def __ior__(self, other: Tensor | _int) -> Tensor: ... + @overload + def __irshift__(self, other: Tensor) -> Tensor: ... + @overload + def __irshift__(self, other: Number | _complex) -> Tensor: ... + @overload + def __irshift__(self, other: Tensor | _int) -> Tensor: ... + def __isub__(self, other: Tensor | Number | _complex) -> Tensor: ... # noqa: PYI034 + @overload + def __ixor__(self, other: Tensor) -> Tensor: ... + @overload + def __ixor__(self, other: Number | _complex) -> Tensor: ... + @overload + def __ixor__(self, other: Tensor | _int) -> Tensor: ... + def __le__(self, other: Tensor | Number | _complex) -> Tensor: ... + def __long__(self) -> _int: ... + @overload + def __lshift__(self, other: Tensor) -> Tensor: ... + @overload + def __lshift__(self, other: Number | _complex) -> Tensor: ... + @overload + def __lshift__(self, other: Tensor | _int) -> Tensor: ... + def __lt__(self, other: Tensor | Number | _complex) -> Tensor: ... + def __matmul__(self, other: Tensor | Number | _complex) -> Tensor: ... + def __mod__(self, other: Tensor | Number | _complex) -> Tensor: ... + def __mul__(self, other: Tensor | Number | _complex) -> Tensor: ... + @overload + def __ne__(self, other: Tensor | Number | _complex) -> Tensor: ... # type: ignore[overload-overlap] + @overload + def __ne__(self, other: object) -> _bool: ... + def __neg__(self) -> Tensor: ... + def __new__(cls, *args, **kwargs) -> Self: ... + def __nonzero__(self) -> _bool: ... + @overload + def __or__(self, other: Tensor) -> Tensor: ... + @overload + def __or__(self, other: Number | _complex) -> Tensor: ... + @overload + def __or__(self, other: Tensor | _int) -> Tensor: ... + def __pow__(self, other: Tensor | Number | _complex) -> Tensor: ... + def __radd__(self, other: Tensor | Number | _complex) -> Tensor: ... + def __rand__(self, other: Tensor | _int) -> Tensor: ... + def __rfloordiv__(self, other: Tensor | Number | _complex) -> Tensor: ... + def __rmul__(self, other: Tensor | Number | _complex) -> Tensor: ... + def __ror__(self, other: Tensor | _int) -> Tensor: ... + def __rpow__(self, other: Tensor | Number | _complex) -> Tensor: ... # type: ignore[has-type] + @overload + def __rshift__(self, other: Tensor) -> Tensor: ... + @overload + def __rshift__(self, other: Number | _complex) -> Tensor: ... + @overload + def __rshift__(self, other: Tensor | _int) -> Tensor: ... + def __rsub__(self, other: Tensor | Number | _complex) -> Tensor: ... + def __rtruediv__(self, other: Tensor | Number | _complex) -> Tensor: ... + def __rxor__(self, other: Tensor | _int) -> Tensor: ... + def __setitem__( + self, + indices: _Index | tuple[_Index, ...], + value: Tensor | Number, + /, + ) -> None: ... + def __sub__(self, other: Tensor | Number | _complex) -> Tensor: ... + def __truediv__(self, other: Tensor | Number | _complex) -> Tensor: ... + @overload + def __xor__(self, other: Tensor) -> Tensor: ... + @overload + def __xor__(self, other: Number | _complex) -> Tensor: ... + @overload + def __xor__(self, other: Tensor | _int) -> Tensor: ... + def _addmm_activation( + self, + mat1: Tensor, + mat2: Tensor, + *, + beta: Number | _complex = 1, + alpha: Number | _complex = 1, + use_gelu: _bool = False, + ) -> Tensor: ... + def _autocast_to_full_precision( + self, + cuda_enabled: _bool, + cpu_enabled: _bool, + ) -> Tensor: ... + def _autocast_to_reduced_precision( + self, + cuda_enabled: _bool, + cpu_enabled: _bool, + cuda_dtype: _dtype, + cpu_dtype: _dtype, + ) -> Tensor: ... + def _coalesced_(self, coalesced: _bool) -> Tensor: ... + def _conj(self) -> Tensor: ... + def _conj_physical(self) -> Tensor: ... + def _dimI(self) -> _int: ... + def _dimV(self) -> _int: ... + @staticmethod + def _dtensor__new__( + cls: type[S], + local_tensor: Tensor, + spec: torch.distributed.tensor._dtensor_spec.DTensorSpec, + requires_grad: _bool, + ) -> S: ... + def _indices(self) -> Tensor: ... + def _is_all_true(self) -> Tensor: ... + def _is_any_true(self) -> Tensor: ... + def _is_view(self) -> _bool: ... + def _is_zerotensor(self) -> _bool: ... + def _lazy_clone(self) -> Tensor: ... + @staticmethod + def _make_subclass( + cls: type[S], + data: Tensor, + require_grad: _bool = False, + dispatch_strides: _bool = False, + dispatch_device: _bool = False, + device_for_backend_keys: _device | None = None, + ) -> S: ... + @staticmethod + def _make_wrapper_subclass( + cls: type[S], + size: Sequence[_int | SymInt], + strides: Sequence[_int | SymInt] | None = None, + storage_offset: _int | SymInt | None = None, + memory_format: torch.memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout = strided, + device: _device | None = None, + pin_memory: _bool = False, + requires_grad: _bool = False, + dispatch_sizes_strides_policy: str | None = None, + dispatch_device: _bool = False, + dispatch_layout: _bool = False, + _extra_dispatch_keys: torch.DispatchKeySet | None = None, + storage_size: _int | SymInt | None = None, + ) -> S: ... + def _neg_view(self) -> Tensor: ... + def _nested_tensor_size(self) -> Tensor: ... + def _nested_tensor_storage_offsets(self) -> Tensor: ... + def _nested_tensor_strides(self) -> Tensor: ... + def _nnz(self) -> _int: ... + def _sparse_mask_projection( + self, + mask: Tensor, + accumulate_matches: _bool = False, + ) -> Tensor: ... + def _to_dense( + self, + dtype: _dtype | None = None, + masked_grad: _bool | None = None, + ) -> Tensor: ... + @overload + def _to_sparse( + self, + *, + layout: _layout | None = None, + blocksize: _int | _size | None = None, + dense_dim: _int | None = None, + ) -> Tensor: ... + @overload + def _to_sparse(self, sparse_dim: _int) -> Tensor: ... + def _to_sparse_bsc( + self, + blocksize: _int | _size, + dense_dim: _int | None = None, + ) -> Tensor: ... + def _to_sparse_bsr( + self, + blocksize: _int | _size, + dense_dim: _int | None = None, + ) -> Tensor: ... + def _to_sparse_csc(self, dense_dim: _int | None = None) -> Tensor: ... + def _to_sparse_csr(self, dense_dim: _int | None = None) -> Tensor: ... + def _values(self) -> Tensor: ... + def abs(self) -> Tensor: + r""" + abs() -> Tensor + + See :func:`torch.abs` + """ + + def abs_(self) -> Tensor: + r""" + abs_() -> Tensor + + In-place version of :meth:`~Tensor.abs` + """ + + def absolute(self) -> Tensor: + r""" + absolute() -> Tensor + + Alias for :func:`abs` + """ + + def absolute_(self) -> Tensor: + r""" + absolute_() -> Tensor + + In-place version of :meth:`~Tensor.absolute` + Alias for :func:`abs_` + """ + + def acos(self) -> Tensor: + r""" + acos() -> Tensor + + See :func:`torch.acos` + """ + + def acos_(self) -> Tensor: + r""" + acos_() -> Tensor + + In-place version of :meth:`~Tensor.acos` + """ + + def acosh(self) -> Tensor: + r""" + acosh() -> Tensor + + See :func:`torch.acosh` + """ + + def acosh_(self) -> Tensor: + r""" + acosh_() -> Tensor + + In-place version of :meth:`~Tensor.acosh` + """ + + def add( + self, + other: Tensor | Number | _complex | torch.SymInt | torch.SymFloat, + *, + alpha: Number | _complex | None = 1, + out: Tensor | None = None, + ) -> Tensor: + r""" + add(other, *, alpha=1) -> Tensor + + Add a scalar or tensor to :attr:`self` tensor. If both :attr:`alpha` + and :attr:`other` are specified, each element of :attr:`other` is scaled by + :attr:`alpha` before being used. + + When :attr:`other` is a tensor, the shape of :attr:`other` must be + :ref:`broadcastable ` with the shape of the underlying + tensor + + See :func:`torch.add` + """ + + def add_( + self, + other: Tensor | Number | _complex | torch.SymInt | torch.SymFloat, + *, + alpha: Number | _complex | None = 1, + ) -> Tensor: + r""" + add_(other, *, alpha=1) -> Tensor + + In-place version of :meth:`~Tensor.add` + """ + + def addbmm( + self, + batch1: Tensor, + batch2: Tensor, + *, + beta: Number | _complex = 1, + alpha: Number | _complex = 1, + ) -> Tensor: + r""" + addbmm(batch1, batch2, *, beta=1, alpha=1) -> Tensor + + See :func:`torch.addbmm` + """ + + def addbmm_( + self, + batch1: Tensor, + batch2: Tensor, + *, + beta: Number | _complex = 1, + alpha: Number | _complex = 1, + ) -> Tensor: + r""" + addbmm_(batch1, batch2, *, beta=1, alpha=1) -> Tensor + + In-place version of :meth:`~Tensor.addbmm` + """ + + def addcdiv( + self, + tensor1: Tensor, + tensor2: Tensor, + *, + value: Number | _complex = 1, + ) -> Tensor: + r""" + addcdiv(tensor1, tensor2, *, value=1) -> Tensor + + See :func:`torch.addcdiv` + """ + + def addcdiv_( + self, + tensor1: Tensor, + tensor2: Tensor, + *, + value: Number | _complex = 1, + ) -> Tensor: + r""" + addcdiv_(tensor1, tensor2, *, value=1) -> Tensor + + In-place version of :meth:`~Tensor.addcdiv` + """ + + def addcmul( + self, + tensor1: Tensor, + tensor2: Tensor, + *, + value: Number | _complex = 1, + ) -> Tensor: + r""" + addcmul(tensor1, tensor2, *, value=1) -> Tensor + + See :func:`torch.addcmul` + """ + + def addcmul_( + self, + tensor1: Tensor, + tensor2: Tensor, + *, + value: Number | _complex = 1, + ) -> Tensor: + r""" + addcmul_(tensor1, tensor2, *, value=1) -> Tensor + + In-place version of :meth:`~Tensor.addcmul` + """ + + def addmm( + self, + mat1: Tensor, + mat2: Tensor, + *, + beta: Number | _complex = 1, + alpha: Number | _complex = 1, + ) -> Tensor: + r""" + addmm(mat1, mat2, *, beta=1, alpha=1) -> Tensor + + See :func:`torch.addmm` + """ + + def addmm_( + self, + mat1: Tensor, + mat2: Tensor, + *, + beta: Number | _complex = 1, + alpha: Number | _complex = 1, + ) -> Tensor: + r""" + addmm_(mat1, mat2, *, beta=1, alpha=1) -> Tensor + + In-place version of :meth:`~Tensor.addmm` + """ + + def addmv( + self, + mat: Tensor, + vec: Tensor, + *, + beta: Number | _complex = 1, + alpha: Number | _complex = 1, + ) -> Tensor: + r""" + addmv(mat, vec, *, beta=1, alpha=1) -> Tensor + + See :func:`torch.addmv` + """ + + def addmv_( + self, + mat: Tensor, + vec: Tensor, + *, + beta: Number | _complex = 1, + alpha: Number | _complex = 1, + ) -> Tensor: + r""" + addmv_(mat, vec, *, beta=1, alpha=1) -> Tensor + + In-place version of :meth:`~Tensor.addmv` + """ + + def addr( + self, + vec1: Tensor, + vec2: Tensor, + *, + beta: Number | _complex = 1, + alpha: Number | _complex = 1, + ) -> Tensor: + r""" + addr(vec1, vec2, *, beta=1, alpha=1) -> Tensor + + See :func:`torch.addr` + """ + + def addr_( + self, + vec1: Tensor, + vec2: Tensor, + *, + beta: Number | _complex = 1, + alpha: Number | _complex = 1, + ) -> Tensor: + r""" + addr_(vec1, vec2, *, beta=1, alpha=1) -> Tensor + + In-place version of :meth:`~Tensor.addr` + """ + + def adjoint(self) -> Tensor: + r""" + adjoint() -> Tensor + + Alias for :func:`adjoint` + """ + + def align_as(self, other: Tensor) -> Tensor: + r""" + align_as(other) -> Tensor + + Permutes the dimensions of the :attr:`self` tensor to match the dimension order + in the :attr:`other` tensor, adding size-one dims for any new names. + + This operation is useful for explicit broadcasting by names (see examples). + + All of the dims of :attr:`self` must be named in order to use this method. + The resulting tensor is a view on the original tensor. + + All dimension names of :attr:`self` must be present in ``other.names``. + :attr:`other` may contain named dimensions that are not in ``self.names``; + the output tensor has a size-one dimension for each of those new names. + + To align a tensor to a specific order, use :meth:`~Tensor.align_to`. + + Examples:: + + # Example 1: Applying a mask + >>> mask = torch.randint(2, [127, 128], dtype=torch.bool).refine_names('W', 'H') + >>> imgs = torch.randn(32, 128, 127, 3, names=('N', 'H', 'W', 'C')) + >>> imgs.masked_fill_(mask.align_as(imgs), 0) + + + # Example 2: Applying a per-channel-scale + >>> def scale_channels(input, scale): + >>> scale = scale.refine_names('C') + >>> return input * scale.align_as(input) + + >>> num_channels = 3 + >>> scale = torch.randn(num_channels, names=('C',)) + >>> imgs = torch.rand(32, 128, 128, num_channels, names=('N', 'H', 'W', 'C')) + >>> more_imgs = torch.rand(32, num_channels, 128, 128, names=('N', 'C', 'H', 'W')) + >>> videos = torch.randn(3, num_channels, 128, 128, 128, names=('N', 'C', 'H', 'W', 'D')) + + # scale_channels is agnostic to the dimension order of the input + >>> scale_channels(imgs, scale) + >>> scale_channels(more_imgs, scale) + >>> scale_channels(videos, scale) + + .. warning:: + The named tensor API is experimental and subject to change. + """ + + @overload + def align_to( + self, + order: Sequence[str | EllipsisType | None], + ellipsis_idx: _int, + ) -> Tensor: ... + @overload + def align_to(self, names: Sequence[str | EllipsisType | None]) -> Tensor: ... + @overload + def all(self) -> Tensor: + r""" + all(dim=None, keepdim=False) -> Tensor + + See :func:`torch.all` + """ + + @overload + def all(self, dim: _size | None = None, keepdim: _bool = False) -> Tensor: + r""" + all(dim=None, keepdim=False) -> Tensor + + See :func:`torch.all` + """ + + @overload + def all(self, dim: _int, keepdim: _bool = False) -> Tensor: + r""" + all(dim=None, keepdim=False) -> Tensor + + See :func:`torch.all` + """ + + @overload + def all( + self, + dim: str | EllipsisType | None, + keepdim: _bool = False, + ) -> Tensor: + r""" + all(dim=None, keepdim=False) -> Tensor + + See :func:`torch.all` + """ + + def allclose( + self, + other: Tensor, + rtol: _float = 1e-05, + atol: _float = 1e-08, + equal_nan: _bool = False, + ) -> _bool: + r""" + allclose(other, rtol=1e-05, atol=1e-08, equal_nan=False) -> Tensor + + See :func:`torch.allclose` + """ + + def amax(self, dim: _int | _size = (), keepdim: _bool = False) -> Tensor: + r""" + amax(dim=None, keepdim=False) -> Tensor + + See :func:`torch.amax` + """ + + def amin(self, dim: _int | _size = (), keepdim: _bool = False) -> Tensor: + r""" + amin(dim=None, keepdim=False) -> Tensor + + See :func:`torch.amin` + """ + + def aminmax( + self, + *, + dim: _int | None = None, + keepdim: _bool = False, + ) -> torch.return_types.aminmax: + r""" + aminmax(*, dim=None, keepdim=False) -> (Tensor min, Tensor max) + + See :func:`torch.aminmax` + """ + + def angle(self) -> Tensor: + r""" + angle() -> Tensor + + See :func:`torch.angle` + """ + + @overload + def any(self) -> Tensor: + r""" + any(dim=None, keepdim=False) -> Tensor + + See :func:`torch.any` + """ + + @overload + def any(self, dim: _size | None = None, keepdim: _bool = False) -> Tensor: + r""" + any(dim=None, keepdim=False) -> Tensor + + See :func:`torch.any` + """ + + @overload + def any(self, dim: _int, keepdim: _bool = False) -> Tensor: + r""" + any(dim=None, keepdim=False) -> Tensor + + See :func:`torch.any` + """ + + @overload + def any( + self, + dim: str | EllipsisType | None, + keepdim: _bool = False, + ) -> Tensor: + r""" + any(dim=None, keepdim=False) -> Tensor + + See :func:`torch.any` + """ + + def apply_(self, callable: Callable) -> Tensor: + r""" + apply_(callable) -> Tensor + + Applies the function :attr:`callable` to each element in the tensor, replacing + each element with the value returned by :attr:`callable`. + + .. note:: + + This function only works with CPU tensors and should not be used in code + sections that require high performance. + """ + + def arccos(self) -> Tensor: + r""" + arccos() -> Tensor + + See :func:`torch.arccos` + """ + + def arccos_(self) -> Tensor: + r""" + arccos_() -> Tensor + + In-place version of :meth:`~Tensor.arccos` + """ + + def arccosh(self) -> Tensor: + r""" + acosh() -> Tensor + + See :func:`torch.arccosh` + """ + + def arccosh_(self) -> Tensor: + r""" + acosh_() -> Tensor + + In-place version of :meth:`~Tensor.arccosh` + """ + + def arcsin(self) -> Tensor: + r""" + arcsin() -> Tensor + + See :func:`torch.arcsin` + """ + + def arcsin_(self) -> Tensor: + r""" + arcsin_() -> Tensor + + In-place version of :meth:`~Tensor.arcsin` + """ + + def arcsinh(self) -> Tensor: + r""" + arcsinh() -> Tensor + + See :func:`torch.arcsinh` + """ + + def arcsinh_(self) -> Tensor: + r""" + arcsinh_() -> Tensor + + In-place version of :meth:`~Tensor.arcsinh` + """ + + def arctan(self) -> Tensor: + r""" + arctan() -> Tensor + + See :func:`torch.arctan` + """ + + def arctan2(self, other: Tensor) -> Tensor: + r""" + arctan2(other) -> Tensor + + See :func:`torch.arctan2` + """ + + def arctan2_(self, other: Tensor) -> Tensor: + r""" + atan2_(other) -> Tensor + + In-place version of :meth:`~Tensor.arctan2` + """ + + def arctan_(self) -> Tensor: + r""" + arctan_() -> Tensor + + In-place version of :meth:`~Tensor.arctan` + """ + + def arctanh(self) -> Tensor: + r""" + arctanh() -> Tensor + + See :func:`torch.arctanh` + """ + + def arctanh_(self) -> Tensor: + r""" + arctanh_(other) -> Tensor + + In-place version of :meth:`~Tensor.arctanh` + """ + + def argmax(self, dim: _int | None = None, keepdim: _bool = False) -> Tensor: + r""" + argmax(dim=None, keepdim=False) -> LongTensor + + See :func:`torch.argmax` + """ + + def argmin(self, dim: _int | None = None, keepdim: _bool = False) -> Tensor: + r""" + argmin(dim=None, keepdim=False) -> LongTensor + + See :func:`torch.argmin` + """ + + @overload + def argsort( + self, + *, + stable: _bool, + dim: _int = -1, + descending: _bool = False, + ) -> Tensor: + r""" + argsort(dim=-1, descending=False) -> LongTensor + + See :func:`torch.argsort` + """ + + @overload + def argsort(self, dim: _int = -1, descending: _bool = False) -> Tensor: + r""" + argsort(dim=-1, descending=False) -> LongTensor + + See :func:`torch.argsort` + """ + + @overload + def argsort( + self, + dim: str | EllipsisType | None, + descending: _bool = False, + ) -> Tensor: + r""" + argsort(dim=-1, descending=False) -> LongTensor + + See :func:`torch.argsort` + """ + + def argwhere(self) -> Tensor: + r""" + argwhere() -> Tensor + + See :func:`torch.argwhere` + """ + + def as_strided( + self, + size: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + storage_offset: _int | SymInt | None = None, + ) -> Tensor: + r""" + as_strided(size, stride, storage_offset=None) -> Tensor + + See :func:`torch.as_strided` + """ + + def as_strided_( + self, + size: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + storage_offset: _int | SymInt | None = None, + ) -> Tensor: + r""" + as_strided_(size, stride, storage_offset=None) -> Tensor + + In-place version of :meth:`~Tensor.as_strided` + """ + + def as_strided_scatter( + self, + src: Tensor, + size: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + storage_offset: _int | SymInt | None = None, + ) -> Tensor: + r""" + as_strided_scatter(src, size, stride, storage_offset=None) -> Tensor + + See :func:`torch.as_strided_scatter` + """ + + def as_subclass(self, cls: type[S]) -> S: + r""" + as_subclass(cls) -> Tensor + + Makes a ``cls`` instance with the same data pointer as ``self``. Changes + in the output mirror changes in ``self``, and the output stays attached + to the autograd graph. ``cls`` must be a subclass of ``Tensor``. + """ + + def asin(self) -> Tensor: + r""" + asin() -> Tensor + + See :func:`torch.asin` + """ + + def asin_(self) -> Tensor: + r""" + asin_() -> Tensor + + In-place version of :meth:`~Tensor.asin` + """ + + def asinh(self) -> Tensor: + r""" + asinh() -> Tensor + + See :func:`torch.asinh` + """ + + def asinh_(self) -> Tensor: + r""" + asinh_() -> Tensor + + In-place version of :meth:`~Tensor.asinh` + """ + + def atan(self) -> Tensor: + r""" + atan() -> Tensor + + See :func:`torch.atan` + """ + + def atan2(self, other: Tensor) -> Tensor: + r""" + atan2(other) -> Tensor + + See :func:`torch.atan2` + """ + + def atan2_(self, other: Tensor) -> Tensor: + r""" + atan2_(other) -> Tensor + + In-place version of :meth:`~Tensor.atan2` + """ + + def atan_(self) -> Tensor: + r""" + atan_() -> Tensor + + In-place version of :meth:`~Tensor.atan` + """ + + def atanh(self) -> Tensor: + r""" + atanh() -> Tensor + + See :func:`torch.atanh` + """ + + def atanh_(self) -> Tensor: + r""" + atanh_(other) -> Tensor + + In-place version of :meth:`~Tensor.atanh` + """ + + def baddbmm( + self, + batch1: Tensor, + batch2: Tensor, + *, + beta: Number | _complex = 1, + alpha: Number | _complex = 1, + ) -> Tensor: + r""" + baddbmm(batch1, batch2, *, beta=1, alpha=1) -> Tensor + + See :func:`torch.baddbmm` + """ + + def baddbmm_( + self, + batch1: Tensor, + batch2: Tensor, + *, + beta: Number | _complex = 1, + alpha: Number | _complex = 1, + ) -> Tensor: + r""" + baddbmm_(batch1, batch2, *, beta=1, alpha=1) -> Tensor + + In-place version of :meth:`~Tensor.baddbmm` + """ + + @overload + def bernoulli(self, *, generator: Generator | None = None) -> Tensor: + r""" + bernoulli(*, generator=None) -> Tensor + + Returns a result tensor where each :math:`\texttt{result[i]}` is independently + sampled from :math:`\text{Bernoulli}(\texttt{self[i]})`. :attr:`self` must have + floating point ``dtype``, and the result will have the same ``dtype``. + + See :func:`torch.bernoulli` + """ + + @overload + def bernoulli( + self, + p: _float, + *, + generator: Generator | None = None, + ) -> Tensor: + r""" + bernoulli(*, generator=None) -> Tensor + + Returns a result tensor where each :math:`\texttt{result[i]}` is independently + sampled from :math:`\text{Bernoulli}(\texttt{self[i]})`. :attr:`self` must have + floating point ``dtype``, and the result will have the same ``dtype``. + + See :func:`torch.bernoulli` + """ + + @overload + def bernoulli_( + self, + p: Tensor, + *, + generator: Generator | None = None, + ) -> Tensor: + r""" + bernoulli_(p=0.5, *, generator=None) -> Tensor + + Fills each location of :attr:`self` with an independent sample from + :math:`\text{Bernoulli}(\texttt{p})`. :attr:`self` can have integral + ``dtype``. + + :attr:`p` should either be a scalar or tensor containing probabilities to be + used for drawing the binary random number. + + If it is a tensor, the :math:`\text{i}^{th}` element of :attr:`self` tensor + will be set to a value sampled from + :math:`\text{Bernoulli}(\texttt{p\_tensor[i]})`. In this case `p` must have + floating point ``dtype``. + + See also :meth:`~Tensor.bernoulli` and :func:`torch.bernoulli` + """ + + @overload + def bernoulli_( + self, + p: _float = 0.5, + *, + generator: Generator | None = None, + ) -> Tensor: + r""" + bernoulli_(p=0.5, *, generator=None) -> Tensor + + Fills each location of :attr:`self` with an independent sample from + :math:`\text{Bernoulli}(\texttt{p})`. :attr:`self` can have integral + ``dtype``. + + :attr:`p` should either be a scalar or tensor containing probabilities to be + used for drawing the binary random number. + + If it is a tensor, the :math:`\text{i}^{th}` element of :attr:`self` tensor + will be set to a value sampled from + :math:`\text{Bernoulli}(\texttt{p\_tensor[i]})`. In this case `p` must have + floating point ``dtype``. + + See also :meth:`~Tensor.bernoulli` and :func:`torch.bernoulli` + """ + + def bfloat16(self) -> Tensor: + r""" + bfloat16(memory_format=torch.preserve_format) -> Tensor + ``self.bfloat16()`` is equivalent to ``self.to(torch.bfloat16)``. See :func:`to`. + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + + def bincount( + self, + weights: Tensor | None = None, + minlength: _int | SymInt = 0, + ) -> Tensor: + r""" + bincount(weights=None, minlength=0) -> Tensor + + See :func:`torch.bincount` + """ + + @overload + def bitwise_and(self, other: Tensor) -> Tensor: + r""" + bitwise_and() -> Tensor + + See :func:`torch.bitwise_and` + """ + + @overload + def bitwise_and(self, other: Number | _complex) -> Tensor: + r""" + bitwise_and() -> Tensor + + See :func:`torch.bitwise_and` + """ + + @overload + def bitwise_and_(self, other: Tensor) -> Tensor: + r""" + bitwise_and_() -> Tensor + + In-place version of :meth:`~Tensor.bitwise_and` + """ + + @overload + def bitwise_and_(self, other: Number | _complex) -> Tensor: + r""" + bitwise_and_() -> Tensor + + In-place version of :meth:`~Tensor.bitwise_and` + """ + + @overload + def bitwise_left_shift(self, other: Tensor) -> Tensor: + r""" + bitwise_left_shift(other) -> Tensor + + See :func:`torch.bitwise_left_shift` + """ + + @overload + def bitwise_left_shift(self, other: Number | _complex) -> Tensor: + r""" + bitwise_left_shift(other) -> Tensor + + See :func:`torch.bitwise_left_shift` + """ + + @overload + def bitwise_left_shift_(self, other: Tensor) -> Tensor: + r""" + bitwise_left_shift_(other) -> Tensor + + In-place version of :meth:`~Tensor.bitwise_left_shift` + """ + + @overload + def bitwise_left_shift_(self, other: Number | _complex) -> Tensor: + r""" + bitwise_left_shift_(other) -> Tensor + + In-place version of :meth:`~Tensor.bitwise_left_shift` + """ + + def bitwise_not(self) -> Tensor: + r""" + bitwise_not() -> Tensor + + See :func:`torch.bitwise_not` + """ + + def bitwise_not_(self) -> Tensor: + r""" + bitwise_not_() -> Tensor + + In-place version of :meth:`~Tensor.bitwise_not` + """ + + @overload + def bitwise_or(self, other: Tensor) -> Tensor: + r""" + bitwise_or() -> Tensor + + See :func:`torch.bitwise_or` + """ + + @overload + def bitwise_or(self, other: Number | _complex) -> Tensor: + r""" + bitwise_or() -> Tensor + + See :func:`torch.bitwise_or` + """ + + @overload + def bitwise_or_(self, other: Tensor) -> Tensor: + r""" + bitwise_or_() -> Tensor + + In-place version of :meth:`~Tensor.bitwise_or` + """ + + @overload + def bitwise_or_(self, other: Number | _complex) -> Tensor: + r""" + bitwise_or_() -> Tensor + + In-place version of :meth:`~Tensor.bitwise_or` + """ + + @overload + def bitwise_right_shift(self, other: Tensor) -> Tensor: + r""" + bitwise_right_shift(other) -> Tensor + + See :func:`torch.bitwise_right_shift` + """ + + @overload + def bitwise_right_shift(self, other: Number | _complex) -> Tensor: + r""" + bitwise_right_shift(other) -> Tensor + + See :func:`torch.bitwise_right_shift` + """ + + @overload + def bitwise_right_shift_(self, other: Tensor) -> Tensor: + r""" + bitwise_right_shift_(other) -> Tensor + + In-place version of :meth:`~Tensor.bitwise_right_shift` + """ + + @overload + def bitwise_right_shift_(self, other: Number | _complex) -> Tensor: + r""" + bitwise_right_shift_(other) -> Tensor + + In-place version of :meth:`~Tensor.bitwise_right_shift` + """ + + @overload + def bitwise_xor(self, other: Tensor) -> Tensor: + r""" + bitwise_xor() -> Tensor + + See :func:`torch.bitwise_xor` + """ + + @overload + def bitwise_xor(self, other: Number | _complex) -> Tensor: + r""" + bitwise_xor() -> Tensor + + See :func:`torch.bitwise_xor` + """ + + @overload + def bitwise_xor_(self, other: Tensor) -> Tensor: + r""" + bitwise_xor_() -> Tensor + + In-place version of :meth:`~Tensor.bitwise_xor` + """ + + @overload + def bitwise_xor_(self, other: Number | _complex) -> Tensor: + r""" + bitwise_xor_() -> Tensor + + In-place version of :meth:`~Tensor.bitwise_xor` + """ + + def bmm(self, mat2: Tensor) -> Tensor: + r""" + bmm(batch2) -> Tensor + + See :func:`torch.bmm` + """ + + def bool(self) -> Tensor: + r""" + bool(memory_format=torch.preserve_format) -> Tensor + + ``self.bool()`` is equivalent to ``self.to(torch.bool)``. See :func:`to`. + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + + @overload + def broadcast_to(self, size: Sequence[_int | SymInt]) -> Tensor: + r""" + broadcast_to(shape) -> Tensor + + See :func:`torch.broadcast_to`. + """ + + @overload + def broadcast_to(self, *size: _int | SymInt) -> Tensor: + r""" + broadcast_to(shape) -> Tensor + + See :func:`torch.broadcast_to`. + """ + + def byte(self) -> Tensor: + r""" + byte(memory_format=torch.preserve_format) -> Tensor + + ``self.byte()`` is equivalent to ``self.to(torch.uint8)``. See :func:`to`. + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + + def cauchy_( + self, + median: _float = 0, + sigma: _float = 1, + *, + generator: Generator | None = None, + ) -> Tensor: + r""" + cauchy_(median=0, sigma=1, *, generator=None) -> Tensor + + Fills the tensor with numbers drawn from the Cauchy distribution: + + .. math:: + + f(x) = \dfrac{1}{\pi} \dfrac{\sigma}{(x - \text{median})^2 + \sigma^2} + + .. note:: + Sigma (:math:`\sigma`) is used to denote the scale parameter in Cauchy distribution. + """ + + def ccol_indices(self) -> Tensor: ... + def ceil(self) -> Tensor: + r""" + ceil() -> Tensor + + See :func:`torch.ceil` + """ + + def ceil_(self) -> Tensor: + r""" + ceil_() -> Tensor + + In-place version of :meth:`~Tensor.ceil` + """ + + def chalf(self, *, memory_format: memory_format | None = None) -> Tensor: + r""" + chalf(memory_format=torch.preserve_format) -> Tensor + + ``self.chalf()`` is equivalent to ``self.to(torch.complex32)``. See :func:`to`. + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + + def char(self) -> Tensor: + r""" + char(memory_format=torch.preserve_format) -> Tensor + + ``self.char()`` is equivalent to ``self.to(torch.int8)``. See :func:`to`. + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + + def cholesky(self, upper: _bool = False) -> Tensor: + r""" + cholesky(upper=False) -> Tensor + + See :func:`torch.cholesky` + """ + + def cholesky_inverse(self, upper: _bool = False) -> Tensor: + r""" + cholesky_inverse(upper=False) -> Tensor + + See :func:`torch.cholesky_inverse` + """ + + def cholesky_solve(self, input2: Tensor, upper: _bool = False) -> Tensor: + r""" + cholesky_solve(input2, upper=False) -> Tensor + + See :func:`torch.cholesky_solve` + """ + + def chunk(self, chunks: _int, dim: _int = 0) -> tuple[Tensor, ...]: + r""" + chunk(chunks, dim=0) -> List of Tensors + + See :func:`torch.chunk` + """ + + @overload + def clamp( + self, + min: Tensor | None = None, + max: Tensor | None = None, + ) -> Tensor: + r""" + clamp(min=None, max=None) -> Tensor + + See :func:`torch.clamp` + """ + + @overload + def clamp( + self, + min: Number | _complex | None = None, + max: Number | _complex | None = None, + ) -> Tensor: + r""" + clamp(min=None, max=None) -> Tensor + + See :func:`torch.clamp` + """ + + @overload + def clamp_( + self, + min: Tensor | None = None, + max: Tensor | None = None, + ) -> Tensor: + r""" + clamp_(min=None, max=None) -> Tensor + + In-place version of :meth:`~Tensor.clamp` + """ + + @overload + def clamp_( + self, + min: Number | _complex | None = None, + max: Number | _complex | None = None, + ) -> Tensor: + r""" + clamp_(min=None, max=None) -> Tensor + + In-place version of :meth:`~Tensor.clamp` + """ + + @overload + def clamp_max(self, max: Tensor) -> Tensor: ... + @overload + def clamp_max(self, max: Number | _complex) -> Tensor: ... + @overload + def clamp_max_(self, max: Tensor) -> Tensor: ... + @overload + def clamp_max_(self, max: Number | _complex) -> Tensor: ... + @overload + def clamp_min(self, min: Tensor) -> Tensor: ... + @overload + def clamp_min(self, min: Number | _complex) -> Tensor: ... + @overload + def clamp_min_(self, min: Tensor) -> Tensor: ... + @overload + def clamp_min_(self, min: Number | _complex) -> Tensor: ... + @overload + def clip( + self, + min: Tensor | None = None, + max: Tensor | None = None, + ) -> Tensor: + r""" + clip(min=None, max=None) -> Tensor + + Alias for :meth:`~Tensor.clamp`. + """ + + @overload + def clip( + self, + min: Number | _complex | None = None, + max: Number | _complex | None = None, + ) -> Tensor: + r""" + clip(min=None, max=None) -> Tensor + + Alias for :meth:`~Tensor.clamp`. + """ + + @overload + def clip_( + self, + min: Tensor | None = None, + max: Tensor | None = None, + ) -> Tensor: + r""" + clip_(min=None, max=None) -> Tensor + + Alias for :meth:`~Tensor.clamp_`. + """ + + @overload + def clip_( + self, + min: Number | _complex | None = None, + max: Number | _complex | None = None, + ) -> Tensor: + r""" + clip_(min=None, max=None) -> Tensor + + Alias for :meth:`~Tensor.clamp_`. + """ + + def clone(self, *, memory_format: memory_format | None = None) -> Tensor: + r""" + clone(*, memory_format=torch.preserve_format) -> Tensor + + See :func:`torch.clone` + """ + + def coalesce(self) -> Tensor: + r""" + coalesce() -> Tensor + + Returns a coalesced copy of :attr:`self` if :attr:`self` is an + :ref:`uncoalesced tensor `. + + Returns :attr:`self` if :attr:`self` is a coalesced tensor. + + .. warning:: + Throws an error if :attr:`self` is not a sparse COO tensor. + """ + + def col_indices(self) -> Tensor: + r""" + col_indices() -> IntTensor + + Returns the tensor containing the column indices of the :attr:`self` + tensor when :attr:`self` is a sparse CSR tensor of layout ``sparse_csr``. + The ``col_indices`` tensor is strictly of shape (:attr:`self`.nnz()) + and of type ``int32`` or ``int64``. When using MKL routines such as sparse + matrix multiplication, it is necessary to use ``int32`` indexing in order + to avoid downcasting and potentially losing information. + + Example:: + + >>> csr = torch.eye(5,5).to_sparse_csr() + >>> csr.col_indices() + tensor([0, 1, 2, 3, 4], dtype=torch.int32) + """ + + def conj(self) -> Tensor: + r""" + conj() -> Tensor + + See :func:`torch.conj` + """ + + def conj_physical(self) -> Tensor: + r""" + conj_physical() -> Tensor + + See :func:`torch.conj_physical` + """ + + def conj_physical_(self) -> Tensor: + r""" + conj_physical_() -> Tensor + + In-place version of :meth:`~Tensor.conj_physical` + """ + + def contiguous( + self, + memory_format: torch.memory_format = torch.contiguous_format, + ) -> Tensor: + r""" + contiguous(memory_format=torch.contiguous_format) -> Tensor + + Returns a contiguous in memory tensor containing the same data as :attr:`self` tensor. If + :attr:`self` tensor is already in the specified memory format, this function returns the + :attr:`self` tensor. + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.contiguous_format``. + """ + + def copy_(self, other: Tensor, non_blocking: _bool = False) -> Tensor: + r""" + copy_(src, non_blocking=False) -> Tensor + + Copies the elements from :attr:`src` into :attr:`self` tensor and returns + :attr:`self`. + + The :attr:`src` tensor must be :ref:`broadcastable ` + with the :attr:`self` tensor. It may be of a different data type or reside on a + different device. + + Args: + src (Tensor): the source tensor to copy from + non_blocking (bool, optional): if ``True`` and this copy is between CPU and GPU, + the copy may occur asynchronously with respect to the host. For other + cases, this argument has no effect. Default: ``False`` + """ + + @overload + def copysign(self, other: Tensor) -> Tensor: + r""" + copysign(other) -> Tensor + + See :func:`torch.copysign` + """ + + @overload + def copysign(self, other: Number | _complex) -> Tensor: + r""" + copysign(other) -> Tensor + + See :func:`torch.copysign` + """ + + @overload + def copysign_(self, other: Tensor) -> Tensor: + r""" + copysign_(other) -> Tensor + + In-place version of :meth:`~Tensor.copysign` + """ + + @overload + def copysign_(self, other: Number | _complex) -> Tensor: + r""" + copysign_(other) -> Tensor + + In-place version of :meth:`~Tensor.copysign` + """ + + def corrcoef(self) -> Tensor: + r""" + corrcoef() -> Tensor + + See :func:`torch.corrcoef` + """ + + def cos(self) -> Tensor: + r""" + cos() -> Tensor + + See :func:`torch.cos` + """ + + def cos_(self) -> Tensor: + r""" + cos_() -> Tensor + + In-place version of :meth:`~Tensor.cos` + """ + + def cosh(self) -> Tensor: + r""" + cosh() -> Tensor + + See :func:`torch.cosh` + """ + + def cosh_(self) -> Tensor: + r""" + cosh_() -> Tensor + + In-place version of :meth:`~Tensor.cosh` + """ + + @overload + def count_nonzero(self, dim: _int | None = None) -> Tensor: + r""" + count_nonzero(dim=None) -> Tensor + + See :func:`torch.count_nonzero` + """ + + @overload + def count_nonzero(self, dim: _size) -> Tensor: + r""" + count_nonzero(dim=None) -> Tensor + + See :func:`torch.count_nonzero` + """ + + @overload + def count_nonzero(self, *dim: _int) -> Tensor: + r""" + count_nonzero(dim=None) -> Tensor + + See :func:`torch.count_nonzero` + """ + + def cov( + self, + *, + correction: _int = 1, + fweights: Tensor | None = None, + aweights: Tensor | None = None, + ) -> Tensor: + r""" + cov(*, correction=1, fweights=None, aweights=None) -> Tensor + + See :func:`torch.cov` + """ + + def cpu( + self, + memory_format: torch.memory_format = torch.preserve_format, + ) -> Tensor: + r""" + cpu(memory_format=torch.preserve_format) -> Tensor + + Returns a copy of this object in CPU memory. + + If this object is already in CPU memory, + then no copy is performed and the original object is returned. + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + + def cross(self, other: Tensor, dim: _int | None = None) -> Tensor: + r""" + cross(other, dim=None) -> Tensor + + See :func:`torch.cross` + """ + + def crow_indices(self) -> Tensor: + r""" + crow_indices() -> IntTensor + + Returns the tensor containing the compressed row indices of the :attr:`self` + tensor when :attr:`self` is a sparse CSR tensor of layout ``sparse_csr``. + The ``crow_indices`` tensor is strictly of shape (:attr:`self`.size(0) + 1) + and of type ``int32`` or ``int64``. When using MKL routines such as sparse + matrix multiplication, it is necessary to use ``int32`` indexing in order + to avoid downcasting and potentially losing information. + + Example:: + + >>> csr = torch.eye(5,5).to_sparse_csr() + >>> csr.crow_indices() + tensor([0, 1, 2, 3, 4, 5], dtype=torch.int32) + """ + + def cuda( + self, + device: _device | _int | str | None = None, + non_blocking: _bool = False, + memory_format: torch.memory_format = torch.preserve_format, + ) -> Tensor: + r""" + cuda(device=None, non_blocking=False, memory_format=torch.preserve_format) -> Tensor + + Returns a copy of this object in CUDA memory. + + If this object is already in CUDA memory and on the correct device, + then no copy is performed and the original object is returned. + + Args: + device (:class:`torch.device`, optional): The destination GPU device. + Defaults to the current CUDA device. + non_blocking (bool, optional): If ``True`` and the source is in pinned memory, + the copy will be asynchronous with respect to the host. + Otherwise, the argument has no effect. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + + @overload + def cummax(self, dim: _int) -> torch.return_types.cummax: + r""" + cummax(dim) -> (Tensor, Tensor) + + See :func:`torch.cummax` + """ + + @overload + def cummax( + self, + dim: str | EllipsisType | None, + ) -> torch.return_types.cummax: + r""" + cummax(dim) -> (Tensor, Tensor) + + See :func:`torch.cummax` + """ + + @overload + def cummin(self, dim: _int) -> torch.return_types.cummin: + r""" + cummin(dim) -> (Tensor, Tensor) + + See :func:`torch.cummin` + """ + + @overload + def cummin( + self, + dim: str | EllipsisType | None, + ) -> torch.return_types.cummin: + r""" + cummin(dim) -> (Tensor, Tensor) + + See :func:`torch.cummin` + """ + + @overload + def cumprod(self, dim: _int, *, dtype: _dtype | None = None) -> Tensor: + r""" + cumprod(dim, dtype=None) -> Tensor + + See :func:`torch.cumprod` + """ + + @overload + def cumprod( + self, + dim: str | EllipsisType | None, + *, + dtype: _dtype | None = None, + ) -> Tensor: + r""" + cumprod(dim, dtype=None) -> Tensor + + See :func:`torch.cumprod` + """ + + @overload + def cumprod_(self, dim: _int, *, dtype: _dtype | None = None) -> Tensor: + r""" + cumprod_(dim, dtype=None) -> Tensor + + In-place version of :meth:`~Tensor.cumprod` + """ + + @overload + def cumprod_( + self, + dim: str | EllipsisType | None, + *, + dtype: _dtype | None = None, + ) -> Tensor: + r""" + cumprod_(dim, dtype=None) -> Tensor + + In-place version of :meth:`~Tensor.cumprod` + """ + + @overload + def cumsum(self, dim: _int, *, dtype: _dtype | None = None) -> Tensor: + r""" + cumsum(dim, dtype=None) -> Tensor + + See :func:`torch.cumsum` + """ + + @overload + def cumsum( + self, + dim: str | EllipsisType | None, + *, + dtype: _dtype | None = None, + ) -> Tensor: + r""" + cumsum(dim, dtype=None) -> Tensor + + See :func:`torch.cumsum` + """ + + @overload + def cumsum_(self, dim: _int, *, dtype: _dtype | None = None) -> Tensor: + r""" + cumsum_(dim, dtype=None) -> Tensor + + In-place version of :meth:`~Tensor.cumsum` + """ + + @overload + def cumsum_( + self, + dim: str | EllipsisType | None, + *, + dtype: _dtype | None = None, + ) -> Tensor: + r""" + cumsum_(dim, dtype=None) -> Tensor + + In-place version of :meth:`~Tensor.cumsum` + """ + + def data_ptr(self) -> _int: + r""" + data_ptr() -> int + + Returns the address of the first element of :attr:`self` tensor. + """ + + def deg2rad(self) -> Tensor: + r""" + deg2rad() -> Tensor + + See :func:`torch.deg2rad` + """ + + def deg2rad_(self) -> Tensor: + r""" + deg2rad_() -> Tensor + + In-place version of :meth:`~Tensor.deg2rad` + """ + + def dense_dim(self) -> _int: + r""" + dense_dim() -> int + + Return the number of dense dimensions in a :ref:`sparse tensor ` :attr:`self`. + + .. note:: + Returns ``len(self.shape)`` if :attr:`self` is not a sparse tensor. + + See also :meth:`Tensor.sparse_dim` and :ref:`hybrid tensors `. + """ + + def dequantize(self) -> Tensor: + r""" + dequantize() -> Tensor + + Given a quantized Tensor, dequantize it and return the dequantized float Tensor. + """ + + def det(self) -> Tensor: + r""" + det() -> Tensor + + See :func:`torch.det` + """ + + def detach(self) -> Tensor: ... + def detach_(self) -> Tensor: ... + def diag(self, diagonal: _int = 0) -> Tensor: + r""" + diag(diagonal=0) -> Tensor + + See :func:`torch.diag` + """ + + def diag_embed( + self, + offset: _int = 0, + dim1: _int = -2, + dim2: _int = -1, + ) -> Tensor: + r""" + diag_embed(offset=0, dim1=-2, dim2=-1) -> Tensor + + See :func:`torch.diag_embed` + """ + + def diagflat(self, offset: _int = 0) -> Tensor: + r""" + diagflat(offset=0) -> Tensor + + See :func:`torch.diagflat` + """ + + @overload + def diagonal( + self, + *, + outdim: str | EllipsisType | None, + dim1: str | EllipsisType | None, + dim2: str | EllipsisType | None, + offset: _int = 0, + ) -> Tensor: + r""" + diagonal(offset=0, dim1=0, dim2=1) -> Tensor + + See :func:`torch.diagonal` + """ + + @overload + def diagonal( + self, + offset: _int = 0, + dim1: _int = 0, + dim2: _int = 1, + ) -> Tensor: + r""" + diagonal(offset=0, dim1=0, dim2=1) -> Tensor + + See :func:`torch.diagonal` + """ + + def diagonal_scatter( + self, + src: Tensor, + offset: _int = 0, + dim1: _int = 0, + dim2: _int = 1, + ) -> Tensor: + r""" + diagonal_scatter(src, offset=0, dim1=0, dim2=1) -> Tensor + + See :func:`torch.diagonal_scatter` + """ + + def diff( + self, + n: _int = 1, + dim: _int = -1, + prepend: Tensor | None = None, + append: Tensor | None = None, + ) -> Tensor: + r""" + diff(n=1, dim=-1, prepend=None, append=None) -> Tensor + + See :func:`torch.diff` + """ + + def digamma(self) -> Tensor: + r""" + digamma() -> Tensor + + See :func:`torch.digamma` + """ + + def digamma_(self) -> Tensor: + r""" + digamma_() -> Tensor + + In-place version of :meth:`~Tensor.digamma` + """ + + def dim(self) -> _int: + r""" + dim() -> int + + Returns the number of dimensions of :attr:`self` tensor. + """ + + def dist(self, other: Tensor, p: Number | _complex = 2) -> Tensor: + r""" + dist(other, p=2) -> Tensor + + See :func:`torch.dist` + """ + + def div( + self, + other: Tensor | Number, + *, + rounding_mode: str | None = None, + ) -> Tensor: + r""" + div(value, *, rounding_mode=None) -> Tensor + + See :func:`torch.div` + """ + + def div_( + self, + other: Tensor | Number, + *, + rounding_mode: str | None = None, + ) -> Tensor: + r""" + div_(value, *, rounding_mode=None) -> Tensor + + In-place version of :meth:`~Tensor.div` + """ + + @overload + def divide(self, other: Tensor) -> Tensor: + r""" + divide(value, *, rounding_mode=None) -> Tensor + + See :func:`torch.divide` + """ + + @overload + def divide(self, other: Tensor, *, rounding_mode: str | None) -> Tensor: + r""" + divide(value, *, rounding_mode=None) -> Tensor + + See :func:`torch.divide` + """ + + @overload + def divide( + self, + other: Number | _complex, + *, + rounding_mode: str | None, + ) -> Tensor: + r""" + divide(value, *, rounding_mode=None) -> Tensor + + See :func:`torch.divide` + """ + + @overload + def divide(self, other: Number | _complex) -> Tensor: + r""" + divide(value, *, rounding_mode=None) -> Tensor + + See :func:`torch.divide` + """ + + @overload + def divide_(self, other: Tensor) -> Tensor: + r""" + divide_(value, *, rounding_mode=None) -> Tensor + + In-place version of :meth:`~Tensor.divide` + """ + + @overload + def divide_(self, other: Tensor, *, rounding_mode: str | None) -> Tensor: + r""" + divide_(value, *, rounding_mode=None) -> Tensor + + In-place version of :meth:`~Tensor.divide` + """ + + @overload + def divide_( + self, + other: Number | _complex, + *, + rounding_mode: str | None, + ) -> Tensor: + r""" + divide_(value, *, rounding_mode=None) -> Tensor + + In-place version of :meth:`~Tensor.divide` + """ + + @overload + def divide_(self, other: Number | _complex) -> Tensor: + r""" + divide_(value, *, rounding_mode=None) -> Tensor + + In-place version of :meth:`~Tensor.divide` + """ + + def dot(self, tensor: Tensor) -> Tensor: + r""" + dot(other) -> Tensor + + See :func:`torch.dot` + """ + + def double(self) -> Tensor: + r""" + double(memory_format=torch.preserve_format) -> Tensor + + ``self.double()`` is equivalent to ``self.to(torch.float64)``. See :func:`to`. + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + + @overload + def dsplit(self, sections: _int) -> tuple[Tensor, ...]: + r""" + dsplit(split_size_or_sections) -> List of Tensors + + See :func:`torch.dsplit` + """ + + @overload + def dsplit(self, indices: _size) -> tuple[Tensor, ...]: + r""" + dsplit(split_size_or_sections) -> List of Tensors + + See :func:`torch.dsplit` + """ + + @overload + def dsplit(self, *indices: _int) -> tuple[Tensor, ...]: + r""" + dsplit(split_size_or_sections) -> List of Tensors + + See :func:`torch.dsplit` + """ + + def element_size(self) -> _int: + r""" + element_size() -> int + + Returns the size in bytes of an individual element. + + Example:: + + >>> torch.tensor([]).element_size() + 4 + >>> torch.tensor([], dtype=torch.uint8).element_size() + 1 + """ + + @overload + def eq(self, other: Tensor) -> Tensor: + r""" + eq(other) -> Tensor + + See :func:`torch.eq` + """ + + @overload + def eq(self, other: Number | _complex) -> Tensor: + r""" + eq(other) -> Tensor + + See :func:`torch.eq` + """ + + @overload + def eq_(self, other: Tensor) -> Tensor: + r""" + eq_(other) -> Tensor + + In-place version of :meth:`~Tensor.eq` + """ + + @overload + def eq_(self, other: Number | _complex) -> Tensor: + r""" + eq_(other) -> Tensor + + In-place version of :meth:`~Tensor.eq` + """ + + def equal(self, other: Tensor) -> _bool: + r""" + equal(other) -> bool + + See :func:`torch.equal` + """ + + def erf(self) -> Tensor: + r""" + erf() -> Tensor + + See :func:`torch.erf` + """ + + def erf_(self) -> Tensor: + r""" + erf_() -> Tensor + + In-place version of :meth:`~Tensor.erf` + """ + + def erfc(self) -> Tensor: + r""" + erfc() -> Tensor + + See :func:`torch.erfc` + """ + + def erfc_(self) -> Tensor: + r""" + erfc_() -> Tensor + + In-place version of :meth:`~Tensor.erfc` + """ + + def erfinv(self) -> Tensor: + r""" + erfinv() -> Tensor + + See :func:`torch.erfinv` + """ + + def erfinv_(self) -> Tensor: + r""" + erfinv_() -> Tensor + + In-place version of :meth:`~Tensor.erfinv` + """ + + def exp(self) -> Tensor: + r""" + exp() -> Tensor + + See :func:`torch.exp` + """ + + def exp2(self) -> Tensor: + r""" + exp2() -> Tensor + + See :func:`torch.exp2` + """ + + def exp2_(self) -> Tensor: + r""" + exp2_() -> Tensor + + In-place version of :meth:`~Tensor.exp2` + """ + + def exp_(self) -> Tensor: + r""" + exp_() -> Tensor + + In-place version of :meth:`~Tensor.exp` + """ + + @overload + def expand( + self, + size: Sequence[_int | SymInt], + *, + implicit: _bool = False, + ) -> Tensor: + r""" + expand(*sizes) -> Tensor + + Returns a new view of the :attr:`self` tensor with singleton dimensions expanded + to a larger size. + + Passing -1 as the size for a dimension means not changing the size of + that dimension. + + Tensor can be also expanded to a larger number of dimensions, and the + new ones will be appended at the front. For the new dimensions, the + size cannot be set to -1. + + Expanding a tensor does not allocate new memory, but only creates a + new view on the existing tensor where a dimension of size one is + expanded to a larger size by setting the ``stride`` to 0. Any dimension + of size 1 can be expanded to an arbitrary value without allocating new + memory. + + Args: + *sizes (torch.Size or int...): the desired expanded size + + .. warning:: + + More than one element of an expanded tensor may refer to a single + memory location. As a result, in-place operations (especially ones that + are vectorized) may result in incorrect behavior. If you need to write + to the tensors, please clone them first. + + Example:: + + >>> x = torch.tensor([[1], [2], [3]]) + >>> x.size() + torch.Size([3, 1]) + >>> x.expand(3, 4) + tensor([[ 1, 1, 1, 1], + [ 2, 2, 2, 2], + [ 3, 3, 3, 3]]) + >>> x.expand(-1, 4) # -1 means not changing the size of that dimension + tensor([[ 1, 1, 1, 1], + [ 2, 2, 2, 2], + [ 3, 3, 3, 3]]) + """ + + @overload + def expand(self, *size: _int | SymInt, implicit: _bool = False) -> Tensor: + r""" + expand(*sizes) -> Tensor + + Returns a new view of the :attr:`self` tensor with singleton dimensions expanded + to a larger size. + + Passing -1 as the size for a dimension means not changing the size of + that dimension. + + Tensor can be also expanded to a larger number of dimensions, and the + new ones will be appended at the front. For the new dimensions, the + size cannot be set to -1. + + Expanding a tensor does not allocate new memory, but only creates a + new view on the existing tensor where a dimension of size one is + expanded to a larger size by setting the ``stride`` to 0. Any dimension + of size 1 can be expanded to an arbitrary value without allocating new + memory. + + Args: + *sizes (torch.Size or int...): the desired expanded size + + .. warning:: + + More than one element of an expanded tensor may refer to a single + memory location. As a result, in-place operations (especially ones that + are vectorized) may result in incorrect behavior. If you need to write + to the tensors, please clone them first. + + Example:: + + >>> x = torch.tensor([[1], [2], [3]]) + >>> x.size() + torch.Size([3, 1]) + >>> x.expand(3, 4) + tensor([[ 1, 1, 1, 1], + [ 2, 2, 2, 2], + [ 3, 3, 3, 3]]) + >>> x.expand(-1, 4) # -1 means not changing the size of that dimension + tensor([[ 1, 1, 1, 1], + [ 2, 2, 2, 2], + [ 3, 3, 3, 3]]) + """ + + def expand_as(self, other: Tensor) -> Tensor: + r""" + expand_as(other) -> Tensor + + Expand this tensor to the same size as :attr:`other`. + ``self.expand_as(other)`` is equivalent to ``self.expand(other.size())``. + + Please see :meth:`~Tensor.expand` for more information about ``expand``. + + Args: + other (:class:`torch.Tensor`): The result tensor has the same size + as :attr:`other`. + """ + + def expm1(self) -> Tensor: + r""" + expm1() -> Tensor + + See :func:`torch.expm1` + """ + + def expm1_(self) -> Tensor: + r""" + expm1_() -> Tensor + + In-place version of :meth:`~Tensor.expm1` + """ + + def exponential_( + self, + lambd: _float = 1, + *, + generator: Generator | None = None, + ) -> Tensor: + r""" + exponential_(lambd=1, *, generator=None) -> Tensor + + Fills :attr:`self` tensor with elements drawn from the PDF (probability density function): + + .. math:: + + f(x) = \lambda e^{-\lambda x}, x > 0 + + .. note:: + In probability theory, exponential distribution is supported on interval [0, :math:`\inf`) (i.e., :math:`x >= 0`) + implying that zero can be sampled from the exponential distribution. + However, :func:`torch.Tensor.exponential_` does not sample zero, + which means that its actual support is the interval (0, :math:`\inf`). + + Note that :func:`torch.distributions.exponential.Exponential` is supported on the interval [0, :math:`\inf`) and can sample zero. + """ + + @overload + def fill_(self, value: Tensor) -> Tensor: + r""" + fill_(value) -> Tensor + + Fills :attr:`self` tensor with the specified value. + """ + + @overload + def fill_(self, value: Number | _complex) -> Tensor: + r""" + fill_(value) -> Tensor + + Fills :attr:`self` tensor with the specified value. + """ + + def fill_diagonal_( + self, + fill_value: Number | _complex, + wrap: _bool = False, + ) -> Tensor: + r""" + fill_diagonal_(fill_value, wrap=False) -> Tensor + + Fill the main diagonal of a tensor that has at least 2-dimensions. + When dims>2, all dimensions of input must be of equal length. + This function modifies the input tensor in-place, and returns the input tensor. + + Arguments: + fill_value (Scalar): the fill value + wrap (bool, optional): the diagonal 'wrapped' after N columns for tall matrices. Default: ``False`` + + Example:: + + >>> a = torch.zeros(3, 3) + >>> a.fill_diagonal_(5) + tensor([[5., 0., 0.], + [0., 5., 0.], + [0., 0., 5.]]) + >>> b = torch.zeros(7, 3) + >>> b.fill_diagonal_(5) + tensor([[5., 0., 0.], + [0., 5., 0.], + [0., 0., 5.], + [0., 0., 0.], + [0., 0., 0.], + [0., 0., 0.], + [0., 0., 0.]]) + >>> c = torch.zeros(7, 3) + >>> c.fill_diagonal_(5, wrap=True) + tensor([[5., 0., 0.], + [0., 5., 0.], + [0., 0., 5.], + [0., 0., 0.], + [5., 0., 0.], + [0., 5., 0.], + [0., 0., 5.]]) + """ + + def fix(self) -> Tensor: + r""" + fix() -> Tensor + + See :func:`torch.fix`. + """ + + def fix_(self) -> Tensor: + r""" + fix_() -> Tensor + + In-place version of :meth:`~Tensor.fix` + """ + + @overload + def flatten( + self, + start_dim: _int, + end_dim: _int, + out_dim: str | EllipsisType | None, + ) -> Tensor: + r""" + flatten(start_dim=0, end_dim=-1) -> Tensor + + See :func:`torch.flatten` + """ + + @overload + def flatten(self, start_dim: _int = 0, end_dim: _int = -1) -> Tensor: + r""" + flatten(start_dim=0, end_dim=-1) -> Tensor + + See :func:`torch.flatten` + """ + + @overload + def flatten( + self, + start_dim: str | EllipsisType | None, + end_dim: str | EllipsisType | None, + out_dim: str | EllipsisType | None, + ) -> Tensor: + r""" + flatten(start_dim=0, end_dim=-1) -> Tensor + + See :func:`torch.flatten` + """ + + @overload + def flatten( + self, + dims: Sequence[str | EllipsisType | None], + out_dim: str | EllipsisType | None, + ) -> Tensor: + r""" + flatten(start_dim=0, end_dim=-1) -> Tensor + + See :func:`torch.flatten` + """ + + @overload + def flip(self, dims: _size) -> Tensor: + r""" + flip(dims) -> Tensor + + See :func:`torch.flip` + """ + + @overload + def flip(self, *dims: _int) -> Tensor: + r""" + flip(dims) -> Tensor + + See :func:`torch.flip` + """ + + def fliplr(self) -> Tensor: + r""" + fliplr() -> Tensor + + See :func:`torch.fliplr` + """ + + def flipud(self) -> Tensor: + r""" + flipud() -> Tensor + + See :func:`torch.flipud` + """ + + def float(self) -> Tensor: + r""" + float(memory_format=torch.preserve_format) -> Tensor + + ``self.float()`` is equivalent to ``self.to(torch.float32)``. See :func:`to`. + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + + @overload + def float_power(self, exponent: Tensor) -> Tensor: + r""" + float_power(exponent) -> Tensor + + See :func:`torch.float_power` + """ + + @overload + def float_power(self, exponent: Number | _complex) -> Tensor: + r""" + float_power(exponent) -> Tensor + + See :func:`torch.float_power` + """ + + @overload + def float_power_(self, exponent: Tensor) -> Tensor: + r""" + float_power_(exponent) -> Tensor + + In-place version of :meth:`~Tensor.float_power` + """ + + @overload + def float_power_(self, exponent: Number | _complex) -> Tensor: + r""" + float_power_(exponent) -> Tensor + + In-place version of :meth:`~Tensor.float_power` + """ + + def floor(self) -> Tensor: + r""" + floor() -> Tensor + + See :func:`torch.floor` + """ + + def floor_(self) -> Tensor: + r""" + floor_() -> Tensor + + In-place version of :meth:`~Tensor.floor` + """ + + def floor_divide( + self, + other: Tensor | Number | torch.SymInt | torch.SymFloat, + *, + out: Tensor | None = None, + ) -> Tensor: + r""" + floor_divide(value) -> Tensor + + See :func:`torch.floor_divide` + """ + + def floor_divide_( + self, + other: Tensor | Number | torch.SymInt | torch.SymFloat, + ) -> Tensor: + r""" + floor_divide_(value) -> Tensor + + In-place version of :meth:`~Tensor.floor_divide` + """ + + def fmax(self, other: Tensor) -> Tensor: + r""" + fmax(other) -> Tensor + + See :func:`torch.fmax` + """ + + def fmin(self, other: Tensor) -> Tensor: + r""" + fmin(other) -> Tensor + + See :func:`torch.fmin` + """ + + @overload + def fmod(self, other: Tensor) -> Tensor: + r""" + fmod(divisor) -> Tensor + + See :func:`torch.fmod` + """ + + @overload + def fmod(self, other: Number | _complex) -> Tensor: + r""" + fmod(divisor) -> Tensor + + See :func:`torch.fmod` + """ + + @overload + def fmod_(self, other: Tensor) -> Tensor: + r""" + fmod_(divisor) -> Tensor + + In-place version of :meth:`~Tensor.fmod` + """ + + @overload + def fmod_(self, other: Number | _complex) -> Tensor: + r""" + fmod_(divisor) -> Tensor + + In-place version of :meth:`~Tensor.fmod` + """ + + def frac(self) -> Tensor: + r""" + frac() -> Tensor + + See :func:`torch.frac` + """ + + def frac_(self) -> Tensor: + r""" + frac_() -> Tensor + + In-place version of :meth:`~Tensor.frac` + """ + + def frexp(self) -> torch.return_types.frexp: + r""" + frexp(input) -> (Tensor mantissa, Tensor exponent) + + See :func:`torch.frexp` + """ + + @overload + def gather( + self, + dim: _int, + index: Tensor, + *, + sparse_grad: _bool = False, + ) -> Tensor: + r""" + gather(dim, index) -> Tensor + + See :func:`torch.gather` + """ + + @overload + def gather( + self, + dim: str | EllipsisType | None, + index: Tensor, + *, + sparse_grad: _bool = False, + ) -> Tensor: + r""" + gather(dim, index) -> Tensor + + See :func:`torch.gather` + """ + + def gcd(self, other: Tensor) -> Tensor: + r""" + gcd(other) -> Tensor + + See :func:`torch.gcd` + """ + + def gcd_(self, other: Tensor) -> Tensor: + r""" + gcd_(other) -> Tensor + + In-place version of :meth:`~Tensor.gcd` + """ + + @overload + def ge(self, other: Tensor) -> Tensor: + r""" + ge(other) -> Tensor + + See :func:`torch.ge`. + """ + + @overload + def ge(self, other: Number | _complex) -> Tensor: + r""" + ge(other) -> Tensor + + See :func:`torch.ge`. + """ + + @overload + def ge_(self, other: Tensor) -> Tensor: + r""" + ge_(other) -> Tensor + + In-place version of :meth:`~Tensor.ge`. + """ + + @overload + def ge_(self, other: Number | _complex) -> Tensor: + r""" + ge_(other) -> Tensor + + In-place version of :meth:`~Tensor.ge`. + """ + + def geometric_( + self, + p: _float, + *, + generator: Generator | None = None, + ) -> Tensor: + r""" + geometric_(p, *, generator=None) -> Tensor + + Fills :attr:`self` tensor with elements drawn from the geometric distribution: + + .. math:: + + P(X=k) = (1 - p)^{k - 1} p, k = 1, 2, ... + + .. note:: + :func:`torch.Tensor.geometric_` `k`-th trial is the first success hence draws samples in :math:`\{1, 2, \ldots\}`, whereas + :func:`torch.distributions.geometric.Geometric` :math:`(k+1)`-th trial is the first success + hence draws samples in :math:`\{0, 1, \ldots\}`. + """ + + def geqrf(self) -> torch.return_types.geqrf: + r""" + geqrf() -> (Tensor, Tensor) + + See :func:`torch.geqrf` + """ + + def ger(self, vec2: Tensor) -> Tensor: + r""" + ger(vec2) -> Tensor + + See :func:`torch.ger` + """ + + def get_device(self) -> _int: + r""" + get_device() -> Device ordinal (Integer) + + For CUDA tensors, this function returns the device ordinal of the GPU on which the tensor resides. + For CPU tensors, this function returns `-1`. + + Example:: + + >>> x = torch.randn(3, 4, 5, device='cuda:0') + >>> x.get_device() + 0 + >>> x.cpu().get_device() + -1 + """ + + @overload + def greater(self, other: Tensor) -> Tensor: + r""" + greater(other) -> Tensor + + See :func:`torch.greater`. + """ + + @overload + def greater(self, other: Number | _complex) -> Tensor: + r""" + greater(other) -> Tensor + + See :func:`torch.greater`. + """ + + @overload + def greater_(self, other: Tensor) -> Tensor: + r""" + greater_(other) -> Tensor + + In-place version of :meth:`~Tensor.greater`. + """ + + @overload + def greater_(self, other: Number | _complex) -> Tensor: + r""" + greater_(other) -> Tensor + + In-place version of :meth:`~Tensor.greater`. + """ + + @overload + def greater_equal(self, other: Tensor) -> Tensor: + r""" + greater_equal(other) -> Tensor + + See :func:`torch.greater_equal`. + """ + + @overload + def greater_equal(self, other: Number | _complex) -> Tensor: + r""" + greater_equal(other) -> Tensor + + See :func:`torch.greater_equal`. + """ + + @overload + def greater_equal_(self, other: Tensor) -> Tensor: + r""" + greater_equal_(other) -> Tensor + + In-place version of :meth:`~Tensor.greater_equal`. + """ + + @overload + def greater_equal_(self, other: Number | _complex) -> Tensor: + r""" + greater_equal_(other) -> Tensor + + In-place version of :meth:`~Tensor.greater_equal`. + """ + + @overload + def gt(self, other: Tensor) -> Tensor: + r""" + gt(other) -> Tensor + + See :func:`torch.gt`. + """ + + @overload + def gt(self, other: Number | _complex) -> Tensor: + r""" + gt(other) -> Tensor + + See :func:`torch.gt`. + """ + + @overload + def gt_(self, other: Tensor) -> Tensor: + r""" + gt_(other) -> Tensor + + In-place version of :meth:`~Tensor.gt`. + """ + + @overload + def gt_(self, other: Number | _complex) -> Tensor: + r""" + gt_(other) -> Tensor + + In-place version of :meth:`~Tensor.gt`. + """ + + def half(self) -> Tensor: + r""" + half(memory_format=torch.preserve_format) -> Tensor + + ``self.half()`` is equivalent to ``self.to(torch.float16)``. See :func:`to`. + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + + def hardshrink(self, lambd: Number | _complex = 0.5) -> Tensor: + r""" + hardshrink(lambd=0.5) -> Tensor + + See :func:`torch.nn.functional.hardshrink` + """ + + def has_names(self) -> _bool: + r""" + Is ``True`` if any of this tensor's dimensions are named. Otherwise, is ``False``. + """ + + @overload + def hash_tensor( + self, + dim: _int | _size = (), + *, + keepdim: _bool = False, + mode: _int = 0, + ) -> Tensor: ... + @overload + def hash_tensor( + self, + *dim: _int, + keepdim: _bool = False, + mode: _int = 0, + ) -> Tensor: ... + def heaviside(self, values: Tensor) -> Tensor: + r""" + heaviside(values) -> Tensor + + See :func:`torch.heaviside` + """ + + def heaviside_(self, values: Tensor) -> Tensor: + r""" + heaviside_(values) -> Tensor + + In-place version of :meth:`~Tensor.heaviside` + """ + + def histc( + self, + bins: _int = 100, + min: Number | _complex = 0, + max: Number | _complex = 0, + ) -> Tensor: + r""" + histc(bins=100, min=0, max=0) -> Tensor + + See :func:`torch.histc` + """ + + @overload + def histogram( + self, + bins: Tensor, + *, + weight: Tensor | None = None, + density: _bool = False, + ) -> torch.return_types.histogram: + r""" + histogram(input, bins, *, range=None, weight=None, density=False) -> (Tensor, Tensor) + + See :func:`torch.histogram` + """ + + @overload + def histogram( + self, + bins: _int = 100, + *, + range: Sequence[_float] | None = None, + weight: Tensor | None = None, + density: _bool = False, + ) -> torch.return_types.histogram: + r""" + histogram(input, bins, *, range=None, weight=None, density=False) -> (Tensor, Tensor) + + See :func:`torch.histogram` + """ + + @overload + def hsplit(self, sections: _int) -> tuple[Tensor, ...]: + r""" + hsplit(split_size_or_sections) -> List of Tensors + + See :func:`torch.hsplit` + """ + + @overload + def hsplit(self, indices: _size) -> tuple[Tensor, ...]: + r""" + hsplit(split_size_or_sections) -> List of Tensors + + See :func:`torch.hsplit` + """ + + @overload + def hsplit(self, *indices: _int) -> tuple[Tensor, ...]: + r""" + hsplit(split_size_or_sections) -> List of Tensors + + See :func:`torch.hsplit` + """ + + def hypot(self, other: Tensor) -> Tensor: + r""" + hypot(other) -> Tensor + + See :func:`torch.hypot` + """ + + def hypot_(self, other: Tensor) -> Tensor: + r""" + hypot_(other) -> Tensor + + In-place version of :meth:`~Tensor.hypot` + """ + + def i0(self) -> Tensor: + r""" + i0() -> Tensor + + See :func:`torch.i0` + """ + + def i0_(self) -> Tensor: + r""" + i0_() -> Tensor + + In-place version of :meth:`~Tensor.i0` + """ + + def igamma(self, other: Tensor) -> Tensor: + r""" + igamma(other) -> Tensor + + See :func:`torch.igamma` + """ + + def igamma_(self, other: Tensor) -> Tensor: + r""" + igamma_(other) -> Tensor + + In-place version of :meth:`~Tensor.igamma` + """ + + def igammac(self, other: Tensor) -> Tensor: + r""" + igammac(other) -> Tensor + See :func:`torch.igammac` + """ + + def igammac_(self, other: Tensor) -> Tensor: + r""" + igammac_(other) -> Tensor + In-place version of :meth:`~Tensor.igammac` + """ + + @overload + def index_add( + self, + dim: _int, + index: Tensor, + source: Tensor, + *, + alpha: Number | _complex = 1, + ) -> Tensor: + r""" + index_add(dim, index, source, *, alpha=1) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.index_add_`. + """ + + @overload + def index_add( + self, + dim: str | EllipsisType | None, + index: Tensor, + source: Tensor, + *, + alpha: Number | _complex = 1, + ) -> Tensor: + r""" + index_add(dim, index, source, *, alpha=1) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.index_add_`. + """ + + def index_add_( + self, + dim: _int, + index: Tensor, + source: Tensor, + *, + alpha: Number | _complex = 1, + ) -> Tensor: + r""" + index_add_(dim, index, source, *, alpha=1) -> Tensor + + Accumulate the elements of :attr:`alpha` times ``source`` into the :attr:`self` + tensor by adding to the indices in the order given in :attr:`index`. For example, + if ``dim == 0``, ``index[i] == j``, and ``alpha=-1``, then the ``i``\ th row of + ``source`` is subtracted from the ``j``\ th row of :attr:`self`. + + The :attr:`dim`\ th dimension of ``source`` must have the same size as the + length of :attr:`index` (which must be a vector), and all other dimensions must + match :attr:`self`, or an error will be raised. + + For a 3-D tensor the output is given as:: + + self[index[i], :, :] += alpha * src[i, :, :] # if dim == 0 + self[:, index[i], :] += alpha * src[:, i, :] # if dim == 1 + self[:, :, index[i]] += alpha * src[:, :, i] # if dim == 2 + + Note: + This operation may behave nondeterministically when given tensors on a CUDA device. See :doc:`/notes/randomness` for more information. + + Args: + dim (int): dimension along which to index + index (Tensor): indices of ``source`` to select from, + should have dtype either `torch.int64` or `torch.int32` + source (Tensor): the tensor containing values to add + + Keyword args: + alpha (Number): the scalar multiplier for ``source`` + + Example:: + + >>> x = torch.ones(5, 3) + >>> t = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=torch.float) + >>> index = torch.tensor([0, 4, 2]) + >>> x.index_add_(0, index, t) + tensor([[ 2., 3., 4.], + [ 1., 1., 1.], + [ 8., 9., 10.], + [ 1., 1., 1.], + [ 5., 6., 7.]]) + >>> x.index_add_(0, index, t, alpha=-1) + tensor([[ 1., 1., 1.], + [ 1., 1., 1.], + [ 1., 1., 1.], + [ 1., 1., 1.], + [ 1., 1., 1.]]) + """ + + @overload + def index_copy(self, dim: _int, index: Tensor, source: Tensor) -> Tensor: + r""" + index_copy(dim, index, tensor2) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.index_copy_`. + """ + + @overload + def index_copy( + self, + dim: str | EllipsisType | None, + index: Tensor, + source: Tensor, + ) -> Tensor: + r""" + index_copy(dim, index, tensor2) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.index_copy_`. + """ + + @overload + def index_copy_(self, dim: _int, index: Tensor, source: Tensor) -> Tensor: + r""" + index_copy_(dim, index, tensor) -> Tensor + + Copies the elements of :attr:`tensor` into the :attr:`self` tensor by selecting + the indices in the order given in :attr:`index`. For example, if ``dim == 0`` + and ``index[i] == j``, then the ``i``\ th row of :attr:`tensor` is copied to the + ``j``\ th row of :attr:`self`. + + The :attr:`dim`\ th dimension of :attr:`tensor` must have the same size as the + length of :attr:`index` (which must be a vector), and all other dimensions must + match :attr:`self`, or an error will be raised. + + .. note:: + If :attr:`index` contains duplicate entries, multiple elements from + :attr:`tensor` will be copied to the same index of :attr:`self`. The result + is nondeterministic since it depends on which copy occurs last. + + Args: + dim (int): dimension along which to index + index (LongTensor): indices of :attr:`tensor` to select from + tensor (Tensor): the tensor containing values to copy + + Example:: + + >>> x = torch.zeros(5, 3) + >>> t = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=torch.float) + >>> index = torch.tensor([0, 4, 2]) + >>> x.index_copy_(0, index, t) + tensor([[ 1., 2., 3.], + [ 0., 0., 0.], + [ 7., 8., 9.], + [ 0., 0., 0.], + [ 4., 5., 6.]]) + """ + + @overload + def index_copy_( + self, + dim: str | EllipsisType | None, + index: Tensor, + source: Tensor, + ) -> Tensor: + r""" + index_copy_(dim, index, tensor) -> Tensor + + Copies the elements of :attr:`tensor` into the :attr:`self` tensor by selecting + the indices in the order given in :attr:`index`. For example, if ``dim == 0`` + and ``index[i] == j``, then the ``i``\ th row of :attr:`tensor` is copied to the + ``j``\ th row of :attr:`self`. + + The :attr:`dim`\ th dimension of :attr:`tensor` must have the same size as the + length of :attr:`index` (which must be a vector), and all other dimensions must + match :attr:`self`, or an error will be raised. + + .. note:: + If :attr:`index` contains duplicate entries, multiple elements from + :attr:`tensor` will be copied to the same index of :attr:`self`. The result + is nondeterministic since it depends on which copy occurs last. + + Args: + dim (int): dimension along which to index + index (LongTensor): indices of :attr:`tensor` to select from + tensor (Tensor): the tensor containing values to copy + + Example:: + + >>> x = torch.zeros(5, 3) + >>> t = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=torch.float) + >>> index = torch.tensor([0, 4, 2]) + >>> x.index_copy_(0, index, t) + tensor([[ 1., 2., 3.], + [ 0., 0., 0.], + [ 7., 8., 9.], + [ 0., 0., 0.], + [ 4., 5., 6.]]) + """ + + @overload + def index_fill(self, dim: _int, index: Tensor, value: Tensor) -> Tensor: + r""" + index_fill(dim, index, value) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.index_fill_`. + """ + + @overload + def index_fill( + self, + dim: str | EllipsisType | None, + index: Tensor, + value: Tensor, + ) -> Tensor: + r""" + index_fill(dim, index, value) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.index_fill_`. + """ + + @overload + def index_fill( + self, + dim: _int, + index: Tensor, + value: Number | _complex, + ) -> Tensor: + r""" + index_fill(dim, index, value) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.index_fill_`. + """ + + @overload + def index_fill( + self, + dim: str | EllipsisType | None, + index: Tensor, + value: Number | _complex, + ) -> Tensor: + r""" + index_fill(dim, index, value) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.index_fill_`. + """ + + @overload + def index_fill_(self, dim: _int, index: Tensor, value: Tensor) -> Tensor: + r""" + index_fill_(dim, index, value) -> Tensor + + Fills the elements of the :attr:`self` tensor with value :attr:`value` by + selecting the indices in the order given in :attr:`index`. + + Args: + dim (int): dimension along which to index + index (LongTensor): indices of :attr:`self` tensor to fill in + value (float): the value to fill with + + Example:: + + >>> x = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=torch.float) + >>> index = torch.tensor([0, 2]) + >>> x.index_fill_(1, index, -1) + tensor([[-1., 2., -1.], + [-1., 5., -1.], + [-1., 8., -1.]]) + """ + + @overload + def index_fill_( + self, + dim: str | EllipsisType | None, + index: Tensor, + value: Tensor, + ) -> Tensor: + r""" + index_fill_(dim, index, value) -> Tensor + + Fills the elements of the :attr:`self` tensor with value :attr:`value` by + selecting the indices in the order given in :attr:`index`. + + Args: + dim (int): dimension along which to index + index (LongTensor): indices of :attr:`self` tensor to fill in + value (float): the value to fill with + + Example:: + + >>> x = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=torch.float) + >>> index = torch.tensor([0, 2]) + >>> x.index_fill_(1, index, -1) + tensor([[-1., 2., -1.], + [-1., 5., -1.], + [-1., 8., -1.]]) + """ + + @overload + def index_fill_( + self, + dim: _int, + index: Tensor, + value: Number | _complex, + ) -> Tensor: + r""" + index_fill_(dim, index, value) -> Tensor + + Fills the elements of the :attr:`self` tensor with value :attr:`value` by + selecting the indices in the order given in :attr:`index`. + + Args: + dim (int): dimension along which to index + index (LongTensor): indices of :attr:`self` tensor to fill in + value (float): the value to fill with + + Example:: + + >>> x = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=torch.float) + >>> index = torch.tensor([0, 2]) + >>> x.index_fill_(1, index, -1) + tensor([[-1., 2., -1.], + [-1., 5., -1.], + [-1., 8., -1.]]) + """ + + @overload + def index_fill_( + self, + dim: str | EllipsisType | None, + index: Tensor, + value: Number | _complex, + ) -> Tensor: + r""" + index_fill_(dim, index, value) -> Tensor + + Fills the elements of the :attr:`self` tensor with value :attr:`value` by + selecting the indices in the order given in :attr:`index`. + + Args: + dim (int): dimension along which to index + index (LongTensor): indices of :attr:`self` tensor to fill in + value (float): the value to fill with + + Example:: + + >>> x = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=torch.float) + >>> index = torch.tensor([0, 2]) + >>> x.index_fill_(1, index, -1) + tensor([[-1., 2., -1.], + [-1., 5., -1.], + [-1., 8., -1.]]) + """ + + def index_put( + self, + indices: tuple[Tensor, ...] | list[Tensor] | None, + values: Tensor, + accumulate: _bool = False, + ) -> Tensor: + r""" + index_put(indices, values, accumulate=False) -> Tensor + + Out-place version of :meth:`~Tensor.index_put_`. + """ + + def index_put_( + self, + indices: tuple[Tensor, ...] | list[Tensor] | None, + values: Tensor, + accumulate: _bool = False, + ) -> Tensor: + r""" + index_put_(indices, values, accumulate=False) -> Tensor + + Puts values from the tensor :attr:`values` into the tensor :attr:`self` using + the indices specified in :attr:`indices` (which is a tuple of Tensors). The + expression ``tensor.index_put_(indices, values)`` is equivalent to + ``tensor[indices] = values``. Returns :attr:`self`. + + If :attr:`accumulate` is ``True``, the elements in :attr:`values` are added to + :attr:`self`. If accumulate is ``False``, the behavior is undefined if indices + contain duplicate elements. + + Args: + indices (tuple of LongTensor): tensors used to index into `self`. + values (Tensor): tensor of same dtype as `self`. + accumulate (bool): whether to accumulate into self + """ + + def index_reduce( + self, + dim: _int, + index: Tensor, + source: Tensor, + reduce: str, + *, + include_self: _bool = True, + ) -> Tensor: ... + def index_reduce_( + self, + dim: _int, + index: Tensor, + source: Tensor, + reduce: str, + *, + include_self: _bool = True, + ) -> Tensor: + r""" + index_reduce_(dim, index, source, reduce, *, include_self=True) -> Tensor + + Accumulate the elements of ``source`` into the :attr:`self` + tensor by accumulating to the indices in the order given in :attr:`index` + using the reduction given by the ``reduce`` argument. For example, if ``dim == 0``, + ``index[i] == j``, ``reduce == prod`` and ``include_self == True`` then the ``i``\ th + row of ``source`` is multiplied by the ``j``\ th row of :attr:`self`. If + :obj:`include_self="True"`, the values in the :attr:`self` tensor are included + in the reduction, otherwise, rows in the :attr:`self` tensor that are accumulated + to are treated as if they were filled with the reduction identities. + + The :attr:`dim`\ th dimension of ``source`` must have the same size as the + length of :attr:`index` (which must be a vector), and all other dimensions must + match :attr:`self`, or an error will be raised. + + For a 3-D tensor with :obj:`reduce="prod"` and :obj:`include_self=True` the + output is given as:: + + self[index[i], :, :] *= src[i, :, :] # if dim == 0 + self[:, index[i], :] *= src[:, i, :] # if dim == 1 + self[:, :, index[i]] *= src[:, :, i] # if dim == 2 + + Note: + This operation may behave nondeterministically when given tensors on a CUDA device. See :doc:`/notes/randomness` for more information. + + .. note:: + + This function only supports floating point tensors. + + .. warning:: + + This function is in beta and may change in the near future. + + Args: + dim (int): dimension along which to index + index (Tensor): indices of ``source`` to select from, + should have dtype either `torch.int64` or `torch.int32` + source (FloatTensor): the tensor containing values to accumulate + reduce (str): the reduction operation to apply + (:obj:`"prod"`, :obj:`"mean"`, :obj:`"amax"`, :obj:`"amin"`) + + Keyword args: + include_self (bool): whether the elements from the ``self`` tensor are + included in the reduction + + Example:: + + >>> x = torch.empty(5, 3).fill_(2) + >>> t = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]], dtype=torch.float) + >>> index = torch.tensor([0, 4, 2, 0]) + >>> x.index_reduce_(0, index, t, 'prod') + tensor([[20., 44., 72.], + [ 2., 2., 2.], + [14., 16., 18.], + [ 2., 2., 2.], + [ 8., 10., 12.]]) + >>> x = torch.empty(5, 3).fill_(2) + >>> x.index_reduce_(0, index, t, 'prod', include_self=False) + tensor([[10., 22., 36.], + [ 2., 2., 2.], + [ 7., 8., 9.], + [ 2., 2., 2.], + [ 4., 5., 6.]]) + """ + + @overload + def index_select(self, dim: _int, index: Tensor) -> Tensor: + r""" + index_select(dim, index) -> Tensor + + See :func:`torch.index_select` + """ + + @overload + def index_select( + self, + dim: str | EllipsisType | None, + index: Tensor, + ) -> Tensor: + r""" + index_select(dim, index) -> Tensor + + See :func:`torch.index_select` + """ + + def indices(self) -> Tensor: + r""" + indices() -> Tensor + + Return the indices tensor of a :ref:`sparse COO tensor `. + + .. warning:: + Throws an error if :attr:`self` is not a sparse COO tensor. + + See also :meth:`Tensor.values`. + + .. note:: + This method can only be called on a coalesced sparse tensor. See + :meth:`Tensor.coalesce` for details. + """ + + def inner(self, other: Tensor) -> Tensor: + r""" + inner(other) -> Tensor + + See :func:`torch.inner`. + """ + + def int(self) -> Tensor: + r""" + int(memory_format=torch.preserve_format) -> Tensor + + ``self.int()`` is equivalent to ``self.to(torch.int32)``. See :func:`to`. + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + + def int_repr(self) -> Tensor: + r""" + int_repr() -> Tensor + + Given a quantized Tensor, + ``self.int_repr()`` returns a CPU Tensor with uint8_t as data type that stores the + underlying uint8_t values of the given Tensor. + """ + + def inverse(self) -> Tensor: + r""" + inverse() -> Tensor + + See :func:`torch.inverse` + """ + + def is_coalesced(self) -> _bool: + r""" + is_coalesced() -> bool + + Returns ``True`` if :attr:`self` is a :ref:`sparse COO tensor + ` that is coalesced, ``False`` otherwise. + + .. warning:: + Throws an error if :attr:`self` is not a sparse COO tensor. + + See :meth:`coalesce` and :ref:`uncoalesced tensors `. + """ + + def is_complex(self) -> _bool: + r""" + is_complex() -> bool + + Returns True if the data type of :attr:`self` is a complex data type. + """ + + def is_conj(self) -> _bool: + r""" + is_conj() -> bool + + Returns True if the conjugate bit of :attr:`self` is set to true. + """ + + def is_contiguous( + self, + memory_format: torch.memory_format = torch.contiguous_format, + ) -> _bool: + r""" + is_contiguous(memory_format=torch.contiguous_format) -> bool + + Returns True if :attr:`self` tensor is contiguous in memory in the order specified + by memory format. + + Args: + memory_format (:class:`torch.memory_format`, optional): Specifies memory allocation + order. Default: ``torch.contiguous_format``. + """ + is_cpu: _bool + r"""Is ``True`` if the Tensor is stored on the CPU, ``False`` otherwise.""" + is_cuda: _bool + r"""Is ``True`` if the Tensor is stored on the GPU, ``False`` otherwise.""" + + def is_distributed(self) -> _bool: ... + def is_floating_point(self) -> _bool: + r""" + is_floating_point() -> bool + + Returns True if the data type of :attr:`self` is a floating point data type. + """ + + def is_inference(self) -> _bool: + r""" + is_inference() -> bool + + See :func:`torch.is_inference` + """ + is_ipu: _bool + r"""Is ``True`` if the Tensor is stored on the IPU, ``False`` otherwise.""" + is_leaf: _bool + r"""All Tensors that have :attr:`requires_grad` which is ``False`` will be leaf Tensors by convention. + + For Tensors that have :attr:`requires_grad` which is ``True``, they will be leaf Tensors if they were + created by the user. This means that they are not the result of an operation and so + :attr:`grad_fn` is None. + + Only leaf Tensors will have their :attr:`grad` populated during a call to :func:`backward`. + To get :attr:`grad` populated for non-leaf Tensors, you can use :func:`retain_grad`. + + Example:: + + >>> a = torch.rand(10, requires_grad=True) + >>> a.is_leaf + True + >>> b = torch.rand(10, requires_grad=True).cuda() + >>> b.is_leaf + False + # b was created by the operation that cast a cpu Tensor into a cuda Tensor + >>> c = torch.rand(10, requires_grad=True) + 2 + >>> c.is_leaf + False + # c was created by the addition operation + >>> d = torch.rand(10).cuda() + >>> d.is_leaf + True + # d does not require gradients and so has no operation creating it (that is tracked by the autograd engine) + >>> e = torch.rand(10).cuda().requires_grad_() + >>> e.is_leaf + True + # e requires gradients and has no operations creating it + >>> f = torch.rand(10, requires_grad=True, device="cuda") + >>> f.is_leaf + True + # f requires grad, has no operation creating it""" + is_maia: _bool + is_meta: _bool + r"""Is ``True`` if the Tensor is a meta tensor, ``False`` otherwise. Meta tensors + are like normal tensors, but they carry no data.""" + is_mkldnn: _bool + is_mps: _bool + r"""Is ``True`` if the Tensor is stored on the MPS device, ``False`` otherwise.""" + is_mtia: _bool + def is_neg(self) -> _bool: + r""" + is_neg() -> bool + + Returns True if the negative bit of :attr:`self` is set to true. + """ + is_nested: _bool + def is_nonzero(self) -> _bool: ... + def is_pinned(self, device: DeviceLikeType | None = None) -> _bool: + r""" + Returns true if this tensor resides in pinned memory. + By default, the device pinned memory on will be the current :ref:`accelerator`. + """ + is_quantized: _bool + r"""Is ``True`` if the Tensor is quantized, ``False`` otherwise.""" + + def is_same_size(self, other: Tensor) -> _bool: ... + def is_set_to(self, tensor: Tensor) -> _bool: + r""" + is_set_to(tensor) -> bool + + Returns True if both tensors are pointing to the exact same memory (same + storage, offset, size and stride). + """ + + def is_signed(self) -> _bool: + r""" + is_signed() -> bool + + Returns True if the data type of :attr:`self` is a signed data type. + """ + is_sparse: _bool + r"""Is ``True`` if the Tensor uses sparse COO storage layout, ``False`` otherwise.""" + is_sparse_csr: _bool + r"""Is ``True`` if the Tensor uses sparse CSR storage layout, ``False`` otherwise.""" + is_vulkan: _bool + is_xpu: _bool + r"""Is ``True`` if the Tensor is stored on the XPU, ``False`` otherwise.""" + + def isclose( + self, + other: Tensor, + rtol: _float = 1e-05, + atol: _float = 1e-08, + equal_nan: _bool = False, + ) -> Tensor: + r""" + isclose(other, rtol=1e-05, atol=1e-08, equal_nan=False) -> Tensor + + See :func:`torch.isclose` + """ + + def isfinite(self) -> Tensor: + r""" + isfinite() -> Tensor + + See :func:`torch.isfinite` + """ + + def isinf(self) -> Tensor: + r""" + isinf() -> Tensor + + See :func:`torch.isinf` + """ + + def isnan(self) -> Tensor: + r""" + isnan() -> Tensor + + See :func:`torch.isnan` + """ + + def isneginf(self) -> Tensor: + r""" + isneginf() -> Tensor + + See :func:`torch.isneginf` + """ + + def isposinf(self) -> Tensor: + r""" + isposinf() -> Tensor + + See :func:`torch.isposinf` + """ + + def isreal(self) -> Tensor: + r""" + isreal() -> Tensor + + See :func:`torch.isreal` + """ + + def istft( + self, + n_fft: _int, + hop_length: _int | None = None, + win_length: _int | None = None, + window: Tensor | None = None, + center: _bool = True, + normalized: _bool = False, + onesided: _bool | None = None, + length: _int | None = None, + return_complex: _bool = False, + ) -> Tensor: + r""" + istft(n_fft, hop_length=None, win_length=None, window=None, + center=True, normalized=False, onesided=True, length=None) -> Tensor + + See :func:`torch.istft` + """ + + def item(self) -> Number: + r""" + item() -> number + + Returns the value of this tensor as a standard Python number. This only works + for tensors with one element. For other cases, see :meth:`~Tensor.tolist`. + + This operation is not differentiable. + + Example:: + + >>> x = torch.tensor([1.0]) + >>> x.item() + 1.0 + """ + + def kron(self, other: Tensor) -> Tensor: + r""" + kron(other) -> Tensor + + See :func:`torch.kron` + """ + + @overload + def kthvalue( + self, + k: _int | SymInt, + dim: _int = -1, + keepdim: _bool = False, + ) -> torch.return_types.kthvalue: + r""" + kthvalue(k, dim=None, keepdim=False) -> (Tensor, LongTensor) + + See :func:`torch.kthvalue` + """ + + @overload + def kthvalue( + self, + k: _int | SymInt, + dim: str | EllipsisType | None, + keepdim: _bool = False, + ) -> torch.return_types.kthvalue: + r""" + kthvalue(k, dim=None, keepdim=False) -> (Tensor, LongTensor) + + See :func:`torch.kthvalue` + """ + + def lcm(self, other: Tensor) -> Tensor: + r""" + lcm(other) -> Tensor + + See :func:`torch.lcm` + """ + + def lcm_(self, other: Tensor) -> Tensor: + r""" + lcm_(other) -> Tensor + + In-place version of :meth:`~Tensor.lcm` + """ + + def ldexp(self, other: Tensor) -> Tensor: + r""" + ldexp(other) -> Tensor + + See :func:`torch.ldexp` + """ + + def ldexp_(self, other: Tensor) -> Tensor: + r""" + ldexp_(other) -> Tensor + + In-place version of :meth:`~Tensor.ldexp` + """ + + @overload + def le(self, other: Tensor) -> Tensor: + r""" + le(other) -> Tensor + + See :func:`torch.le`. + """ + + @overload + def le(self, other: Number | _complex) -> Tensor: + r""" + le(other) -> Tensor + + See :func:`torch.le`. + """ + + @overload + def le_(self, other: Tensor) -> Tensor: + r""" + le_(other) -> Tensor + + In-place version of :meth:`~Tensor.le`. + """ + + @overload + def le_(self, other: Number | _complex) -> Tensor: + r""" + le_(other) -> Tensor + + In-place version of :meth:`~Tensor.le`. + """ + + @overload + def lerp(self, end: Tensor, weight: Tensor) -> Tensor: + r""" + lerp(end, weight) -> Tensor + + See :func:`torch.lerp` + """ + + @overload + def lerp(self, end: Tensor, weight: Number | _complex) -> Tensor: + r""" + lerp(end, weight) -> Tensor + + See :func:`torch.lerp` + """ + + @overload + def lerp_(self, end: Tensor, weight: Tensor) -> Tensor: + r""" + lerp_(end, weight) -> Tensor + + In-place version of :meth:`~Tensor.lerp` + """ + + @overload + def lerp_(self, end: Tensor, weight: Number | _complex) -> Tensor: + r""" + lerp_(end, weight) -> Tensor + + In-place version of :meth:`~Tensor.lerp` + """ + + @overload + def less(self, other: Tensor) -> Tensor: + r""" + lt(other) -> Tensor + + See :func:`torch.less`. + """ + + @overload + def less(self, other: Number | _complex) -> Tensor: + r""" + lt(other) -> Tensor + + See :func:`torch.less`. + """ + + @overload + def less_(self, other: Tensor) -> Tensor: + r""" + less_(other) -> Tensor + + In-place version of :meth:`~Tensor.less`. + """ + + @overload + def less_(self, other: Number | _complex) -> Tensor: + r""" + less_(other) -> Tensor + + In-place version of :meth:`~Tensor.less`. + """ + + @overload + def less_equal(self, other: Tensor) -> Tensor: + r""" + less_equal(other) -> Tensor + + See :func:`torch.less_equal`. + """ + + @overload + def less_equal(self, other: Number | _complex) -> Tensor: + r""" + less_equal(other) -> Tensor + + See :func:`torch.less_equal`. + """ + + @overload + def less_equal_(self, other: Tensor) -> Tensor: + r""" + less_equal_(other) -> Tensor + + In-place version of :meth:`~Tensor.less_equal`. + """ + + @overload + def less_equal_(self, other: Number | _complex) -> Tensor: + r""" + less_equal_(other) -> Tensor + + In-place version of :meth:`~Tensor.less_equal`. + """ + + def lgamma(self) -> Tensor: + r""" + lgamma() -> Tensor + + See :func:`torch.lgamma` + """ + + def lgamma_(self) -> Tensor: + r""" + lgamma_() -> Tensor + + In-place version of :meth:`~Tensor.lgamma` + """ + + def log(self) -> Tensor: + r""" + log() -> Tensor + + See :func:`torch.log` + """ + + def log10(self) -> Tensor: + r""" + log10() -> Tensor + + See :func:`torch.log10` + """ + + def log10_(self) -> Tensor: + r""" + log10_() -> Tensor + + In-place version of :meth:`~Tensor.log10` + """ + + def log1p(self) -> Tensor: + r""" + log1p() -> Tensor + + See :func:`torch.log1p` + """ + + def log1p_(self) -> Tensor: + r""" + log1p_() -> Tensor + + In-place version of :meth:`~Tensor.log1p` + """ + + def log2(self) -> Tensor: + r""" + log2() -> Tensor + + See :func:`torch.log2` + """ + + def log2_(self) -> Tensor: + r""" + log2_() -> Tensor + + In-place version of :meth:`~Tensor.log2` + """ + + def log_(self) -> Tensor: + r""" + log_() -> Tensor + + In-place version of :meth:`~Tensor.log` + """ + + def log_normal_( + self, + mean: _float = 1, + std: _float = 2, + *, + generator: Generator | None = None, + ) -> Tensor: + r""" + log_normal_(mean=1, std=2, *, generator=None) + + Fills :attr:`self` tensor with numbers samples from the log-normal distribution + parameterized by the given mean :math:`\mu` and standard deviation + :math:`\sigma`. Note that :attr:`mean` and :attr:`std` are the mean and + standard deviation of the underlying normal distribution, and not of the + returned distribution: + + .. math:: + + f(x) = \dfrac{1}{x \sigma \sqrt{2\pi}}\ e^{-\frac{(\ln x - \mu)^2}{2\sigma^2}} + """ + + @overload + def log_softmax(self, dim: _int, dtype: _dtype | None = None) -> Tensor: ... + @overload + def log_softmax( + self, + dim: str | EllipsisType | None, + *, + dtype: _dtype | None = None, + ) -> Tensor: ... + def logaddexp(self, other: Tensor) -> Tensor: + r""" + logaddexp(other) -> Tensor + + See :func:`torch.logaddexp` + """ + + def logaddexp2(self, other: Tensor) -> Tensor: + r""" + logaddexp2(other) -> Tensor + + See :func:`torch.logaddexp2` + """ + + @overload + def logcumsumexp(self, dim: _int) -> Tensor: + r""" + logcumsumexp(dim) -> Tensor + + See :func:`torch.logcumsumexp` + """ + + @overload + def logcumsumexp(self, dim: str | EllipsisType | None) -> Tensor: + r""" + logcumsumexp(dim) -> Tensor + + See :func:`torch.logcumsumexp` + """ + + def logdet(self) -> Tensor: + r""" + logdet() -> Tensor + + See :func:`torch.logdet` + """ + + def logical_and(self, other: Tensor) -> Tensor: + r""" + logical_and() -> Tensor + + See :func:`torch.logical_and` + """ + + def logical_and_(self, other: Tensor) -> Tensor: + r""" + logical_and_() -> Tensor + + In-place version of :meth:`~Tensor.logical_and` + """ + + def logical_not(self) -> Tensor: + r""" + logical_not() -> Tensor + + See :func:`torch.logical_not` + """ + + def logical_not_(self) -> Tensor: + r""" + logical_not_() -> Tensor + + In-place version of :meth:`~Tensor.logical_not` + """ + + def logical_or(self, other: Tensor) -> Tensor: + r""" + logical_or() -> Tensor + + See :func:`torch.logical_or` + """ + + def logical_or_(self, other: Tensor) -> Tensor: + r""" + logical_or_() -> Tensor + + In-place version of :meth:`~Tensor.logical_or` + """ + + def logical_xor(self, other: Tensor) -> Tensor: + r""" + logical_xor() -> Tensor + + See :func:`torch.logical_xor` + """ + + def logical_xor_(self, other: Tensor) -> Tensor: + r""" + logical_xor_() -> Tensor + + In-place version of :meth:`~Tensor.logical_xor` + """ + + def logit(self, eps: _float | None = None) -> Tensor: + r""" + logit() -> Tensor + + See :func:`torch.logit` + """ + + def logit_(self, eps: _float | None = None) -> Tensor: + r""" + logit_() -> Tensor + + In-place version of :meth:`~Tensor.logit` + """ + + @overload + def logsumexp(self, dim: _int | _size, keepdim: _bool = False) -> Tensor: + r""" + logsumexp(dim, keepdim=False) -> Tensor + + See :func:`torch.logsumexp` + """ + + @overload + def logsumexp( + self, + dim: Sequence[str | EllipsisType | None], + keepdim: _bool = False, + ) -> Tensor: + r""" + logsumexp(dim, keepdim=False) -> Tensor + + See :func:`torch.logsumexp` + """ + + def long(self) -> Tensor: + r""" + long(memory_format=torch.preserve_format) -> Tensor + + ``self.long()`` is equivalent to ``self.to(torch.int64)``. See :func:`to`. + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + + @overload + def lt(self, other: Tensor) -> Tensor: + r""" + lt(other) -> Tensor + + See :func:`torch.lt`. + """ + + @overload + def lt(self, other: Number | _complex) -> Tensor: + r""" + lt(other) -> Tensor + + See :func:`torch.lt`. + """ + + @overload + def lt_(self, other: Tensor) -> Tensor: + r""" + lt_(other) -> Tensor + + In-place version of :meth:`~Tensor.lt`. + """ + + @overload + def lt_(self, other: Number | _complex) -> Tensor: + r""" + lt_(other) -> Tensor + + In-place version of :meth:`~Tensor.lt`. + """ + + def lu_solve(self, LU_data: Tensor, LU_pivots: Tensor) -> Tensor: + r""" + lu_solve(LU_data, LU_pivots) -> Tensor + + See :func:`torch.lu_solve` + """ + + def map2_(self, x: Tensor, y: Tensor, callable: Callable) -> Tensor: ... + def map_(self, other: Tensor, callable: Callable) -> Tensor: + r""" + map_(tensor, callable) + + Applies :attr:`callable` for each element in :attr:`self` tensor and the given + :attr:`tensor` and stores the results in :attr:`self` tensor. :attr:`self` tensor and + the given :attr:`tensor` must be :ref:`broadcastable `. + + The :attr:`callable` should have the signature:: + + def callable(a, b) -> number + """ + + @overload + def masked_fill(self, mask: Tensor, value: Tensor) -> Tensor: + r""" + masked_fill(mask, value) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.masked_fill_` + """ + + @overload + def masked_fill(self, mask: Tensor, value: Number | _complex) -> Tensor: + r""" + masked_fill(mask, value) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.masked_fill_` + """ + + @overload + def masked_fill_(self, mask: Tensor, value: Tensor) -> Tensor: + r""" + masked_fill_(mask, value) + + Fills elements of :attr:`self` tensor with :attr:`value` where :attr:`mask` is + True. The shape of :attr:`mask` must be + :ref:`broadcastable ` with the shape of the underlying + tensor. + + Args: + mask (BoolTensor): the boolean mask + value (float): the value to fill in with + """ + + @overload + def masked_fill_(self, mask: Tensor, value: Number | _complex) -> Tensor: + r""" + masked_fill_(mask, value) + + Fills elements of :attr:`self` tensor with :attr:`value` where :attr:`mask` is + True. The shape of :attr:`mask` must be + :ref:`broadcastable ` with the shape of the underlying + tensor. + + Args: + mask (BoolTensor): the boolean mask + value (float): the value to fill in with + """ + + def masked_scatter(self, mask: Tensor, source: Tensor) -> Tensor: + r""" + masked_scatter(mask, tensor) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.masked_scatter_` + + .. note:: + + The inputs :attr:`self` and :attr:`mask` + :ref:`broadcast `. + + Example: + + >>> self = torch.tensor([0, 0, 0, 0, 0]) + >>> mask = torch.tensor( + ... [[0, 0, 0, 1, 1], [1, 1, 0, 1, 1]], + ... dtype=torch.bool, + ... ) + >>> source = torch.tensor([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]) + >>> self.masked_scatter(mask, source) + tensor([[0, 0, 0, 0, 1], + [2, 3, 0, 4, 5]]) + """ + + def masked_scatter_(self, mask: Tensor, source: Tensor) -> Tensor: + r""" + masked_scatter_(mask, source) + + Copies elements from :attr:`source` into :attr:`self` tensor at positions where + the :attr:`mask` is True. Elements from :attr:`source` are copied into :attr:`self` + starting at position 0 of :attr:`source` and continuing in order one-by-one for each + occurrence of :attr:`mask` being True. + The shape of :attr:`mask` must be :ref:`broadcastable ` + with the shape of the underlying tensor. The :attr:`source` should have at least + as many elements as the number of ones in :attr:`mask`. + + Args: + mask (BoolTensor): the boolean mask + source (Tensor): the tensor to copy from + + .. note:: + + The :attr:`mask` operates on the :attr:`self` tensor, not on the given + :attr:`source` tensor. + + Example: + + >>> self = torch.tensor([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]) + >>> mask = torch.tensor( + ... [[0, 0, 0, 1, 1], [1, 1, 0, 1, 1]], + ... dtype=torch.bool, + ... ) + >>> source = torch.tensor([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]) + >>> self.masked_scatter_(mask, source) + tensor([[0, 0, 0, 0, 1], + [2, 3, 0, 4, 5]]) + """ + + def masked_select(self, mask: Tensor) -> Tensor: + r""" + masked_select(mask) -> Tensor + + See :func:`torch.masked_select` + """ + + def matmul(self, other: Tensor) -> Tensor: + r""" + matmul(tensor2) -> Tensor + + See :func:`torch.matmul` + """ + + def matrix_exp(self) -> Tensor: + r""" + matrix_exp() -> Tensor + + See :func:`torch.matrix_exp` + """ + + def matrix_power(self, n: _int) -> Tensor: + r""" + matrix_power(n) -> Tensor + + .. note:: :meth:`~Tensor.matrix_power` is deprecated, use :func:`torch.linalg.matrix_power` instead. + + Alias for :func:`torch.linalg.matrix_power` + """ + + @overload + def max(self) -> Tensor: + r""" + max(dim=None, keepdim=False) -> Tensor or (Tensor, Tensor) + + See :func:`torch.max` + """ + + @overload + def max(self, other: Tensor) -> Tensor: + r""" + max(dim=None, keepdim=False) -> Tensor or (Tensor, Tensor) + + See :func:`torch.max` + """ + + @overload + def max(self, dim: _int, keepdim: _bool = False) -> torch.return_types.max: + r""" + max(dim=None, keepdim=False) -> Tensor or (Tensor, Tensor) + + See :func:`torch.max` + """ + + @overload + def max( + self, + dim: str | EllipsisType | None, + keepdim: _bool = False, + ) -> torch.return_types.max: + r""" + max(dim=None, keepdim=False) -> Tensor or (Tensor, Tensor) + + See :func:`torch.max` + """ + + def maximum(self, other: Tensor) -> Tensor: + r""" + maximum(other) -> Tensor + + See :func:`torch.maximum` + """ + + @overload + def mean(self, *, dtype: _dtype | None = None) -> Tensor: + r""" + mean(dim=None, keepdim=False, *, dtype=None) -> Tensor + + See :func:`torch.mean` + """ + + @overload + def mean( + self, + dim: _int | _size | None, + keepdim: _bool = False, + *, + dtype: _dtype | None = None, + ) -> Tensor: + r""" + mean(dim=None, keepdim=False, *, dtype=None) -> Tensor + + See :func:`torch.mean` + """ + + @overload + def mean( + self, + dim: Sequence[str | EllipsisType | None], + keepdim: _bool = False, + *, + dtype: _dtype | None = None, + ) -> Tensor: + r""" + mean(dim=None, keepdim=False, *, dtype=None) -> Tensor + + See :func:`torch.mean` + """ + + @overload + def median(self) -> Tensor: + r""" + median(dim=None, keepdim=False) -> (Tensor, LongTensor) + + See :func:`torch.median` + """ + + @overload + def median( + self, + dim: _int, + keepdim: _bool = False, + ) -> torch.return_types.median: + r""" + median(dim=None, keepdim=False) -> (Tensor, LongTensor) + + See :func:`torch.median` + """ + + @overload + def median( + self, + dim: str | EllipsisType | None, + keepdim: _bool = False, + ) -> torch.return_types.median: + r""" + median(dim=None, keepdim=False) -> (Tensor, LongTensor) + + See :func:`torch.median` + """ + + @overload + def min(self) -> Tensor: + r""" + min(dim=None, keepdim=False) -> Tensor or (Tensor, Tensor) + + See :func:`torch.min` + """ + + @overload + def min(self, other: Tensor) -> Tensor: + r""" + min(dim=None, keepdim=False) -> Tensor or (Tensor, Tensor) + + See :func:`torch.min` + """ + + @overload + def min(self, dim: _int, keepdim: _bool = False) -> torch.return_types.min: + r""" + min(dim=None, keepdim=False) -> Tensor or (Tensor, Tensor) + + See :func:`torch.min` + """ + + @overload + def min( + self, + dim: str | EllipsisType | None, + keepdim: _bool = False, + ) -> torch.return_types.min: + r""" + min(dim=None, keepdim=False) -> Tensor or (Tensor, Tensor) + + See :func:`torch.min` + """ + + def minimum(self, other: Tensor) -> Tensor: + r""" + minimum(other) -> Tensor + + See :func:`torch.minimum` + """ + + def mm(self, mat2: Tensor) -> Tensor: + r""" + mm(mat2) -> Tensor + + See :func:`torch.mm` + """ + + @overload + def mode( + self, + dim: _int = -1, + keepdim: _bool = False, + ) -> torch.return_types.mode: + r""" + mode(dim=None, keepdim=False) -> (Tensor, LongTensor) + + See :func:`torch.mode` + """ + + @overload + def mode( + self, + dim: str | EllipsisType | None, + keepdim: _bool = False, + ) -> torch.return_types.mode: + r""" + mode(dim=None, keepdim=False) -> (Tensor, LongTensor) + + See :func:`torch.mode` + """ + + @overload + def moveaxis(self, source: _int, destination: _int) -> Tensor: + r""" + moveaxis(source, destination) -> Tensor + + See :func:`torch.moveaxis` + """ + + @overload + def moveaxis(self, source: _size, destination: _size) -> Tensor: + r""" + moveaxis(source, destination) -> Tensor + + See :func:`torch.moveaxis` + """ + + @overload + def movedim(self, source: _int, destination: _int) -> Tensor: + r""" + movedim(source, destination) -> Tensor + + See :func:`torch.movedim` + """ + + @overload + def movedim(self, source: _size, destination: _size) -> Tensor: + r""" + movedim(source, destination) -> Tensor + + See :func:`torch.movedim` + """ + + def msort(self) -> Tensor: + r""" + msort() -> Tensor + + See :func:`torch.msort` + """ + + def mul( + self, + other: Tensor | Number | _complex | torch.SymInt | torch.SymFloat, + *, + out: Tensor | None = None, + ) -> Tensor: + r""" + mul(value) -> Tensor + + See :func:`torch.mul`. + """ + + def mul_( + self, + other: Tensor | Number | _complex | torch.SymInt | torch.SymFloat, + ) -> Tensor: + r""" + mul_(value) -> Tensor + + In-place version of :meth:`~Tensor.mul`. + """ + + def multinomial( + self, + num_samples: _int | SymInt, + replacement: _bool = False, + *, + generator: Generator | None = None, + ) -> Tensor: + r""" + multinomial(num_samples, replacement=False, *, generator=None) -> Tensor + + See :func:`torch.multinomial` + """ + + @overload + def multiply(self, other: Tensor) -> Tensor: + r""" + multiply(value) -> Tensor + + See :func:`torch.multiply`. + """ + + @overload + def multiply(self, other: Number | _complex) -> Tensor: + r""" + multiply(value) -> Tensor + + See :func:`torch.multiply`. + """ + + @overload + def multiply_(self, other: Tensor) -> Tensor: + r""" + multiply_(value) -> Tensor + + In-place version of :meth:`~Tensor.multiply`. + """ + + @overload + def multiply_(self, other: Number | _complex) -> Tensor: + r""" + multiply_(value) -> Tensor + + In-place version of :meth:`~Tensor.multiply`. + """ + + def mv(self, vec: Tensor) -> Tensor: + r""" + mv(vec) -> Tensor + + See :func:`torch.mv` + """ + + def mvlgamma(self, p: _int) -> Tensor: + r""" + mvlgamma(p) -> Tensor + + See :func:`torch.mvlgamma` + """ + + def mvlgamma_(self, p: _int) -> Tensor: + r""" + mvlgamma_(p) -> Tensor + + In-place version of :meth:`~Tensor.mvlgamma` + """ + + def nan_to_num( + self, + nan: _float | None = None, + posinf: _float | None = None, + neginf: _float | None = None, + ) -> Tensor: + r""" + nan_to_num(nan=0.0, posinf=None, neginf=None) -> Tensor + + See :func:`torch.nan_to_num`. + """ + + def nan_to_num_( + self, + nan: _float | None = None, + posinf: _float | None = None, + neginf: _float | None = None, + ) -> Tensor: + r""" + nan_to_num_(nan=0.0, posinf=None, neginf=None) -> Tensor + + In-place version of :meth:`~Tensor.nan_to_num`. + """ + + def nanmean( + self, + dim: _int | _size | None = None, + keepdim: _bool = False, + *, + dtype: _dtype | None = None, + ) -> Tensor: + r""" + nanmean(dim=None, keepdim=False, *, dtype=None) -> Tensor + + See :func:`torch.nanmean` + """ + + @overload + def nanmedian(self) -> Tensor: + r""" + nanmedian(dim=None, keepdim=False) -> (Tensor, LongTensor) + + See :func:`torch.nanmedian` + """ + + @overload + def nanmedian( + self, + dim: _int, + keepdim: _bool = False, + ) -> torch.return_types.nanmedian: + r""" + nanmedian(dim=None, keepdim=False) -> (Tensor, LongTensor) + + See :func:`torch.nanmedian` + """ + + @overload + def nanmedian( + self, + dim: str | EllipsisType | None, + keepdim: _bool = False, + ) -> torch.return_types.nanmedian: + r""" + nanmedian(dim=None, keepdim=False) -> (Tensor, LongTensor) + + See :func:`torch.nanmedian` + """ + + @overload + def nanquantile( + self, + q: Tensor, + dim: _int | None = None, + keepdim: _bool = False, + *, + interpolation: str = "linear", + ) -> Tensor: + r""" + nanquantile(q, dim=None, keepdim=False, *, interpolation='linear') -> Tensor + + See :func:`torch.nanquantile` + """ + + @overload + def nanquantile( + self, + q: _float, + dim: _int | None = None, + keepdim: _bool = False, + *, + interpolation: str = "linear", + ) -> Tensor: + r""" + nanquantile(q, dim=None, keepdim=False, *, interpolation='linear') -> Tensor + + See :func:`torch.nanquantile` + """ + + def nansum( + self, + dim: _int | _size | None = None, + keepdim: _bool = False, + *, + dtype: _dtype | None = None, + ) -> Tensor: + r""" + nansum(dim=None, keepdim=False, dtype=None) -> Tensor + + See :func:`torch.nansum` + """ + + @overload + def narrow(self, dim: _int, start: Tensor, length: _int | SymInt) -> Tensor: + r""" + narrow(dimension, start, length) -> Tensor + + See :func:`torch.narrow`. + """ + + @overload + def narrow( + self, + dim: _int, + start: _int | SymInt, + length: _int | SymInt, + ) -> Tensor: + r""" + narrow(dimension, start, length) -> Tensor + + See :func:`torch.narrow`. + """ + + def narrow_copy( + self, + dim: _int, + start: _int | SymInt, + length: _int | SymInt, + ) -> Tensor: + r""" + narrow_copy(dimension, start, length) -> Tensor + + See :func:`torch.narrow_copy`. + """ + + def ndimension(self) -> _int: + r""" + ndimension() -> int + + Alias for :meth:`~Tensor.dim()` + """ + + @overload + def ne(self, other: Tensor) -> Tensor: + r""" + ne(other) -> Tensor + + See :func:`torch.ne`. + """ + + @overload + def ne(self, other: Number | _complex) -> Tensor: + r""" + ne(other) -> Tensor + + See :func:`torch.ne`. + """ + + @overload + def ne_(self, other: Tensor) -> Tensor: + r""" + ne_(other) -> Tensor + + In-place version of :meth:`~Tensor.ne`. + """ + + @overload + def ne_(self, other: Number | _complex) -> Tensor: + r""" + ne_(other) -> Tensor + + In-place version of :meth:`~Tensor.ne`. + """ + + def neg(self) -> Tensor: + r""" + neg() -> Tensor + + See :func:`torch.neg` + """ + + def neg_(self) -> Tensor: + r""" + neg_() -> Tensor + + In-place version of :meth:`~Tensor.neg` + """ + + def negative(self) -> Tensor: + r""" + negative() -> Tensor + + See :func:`torch.negative` + """ + + def negative_(self) -> Tensor: + r""" + negative_() -> Tensor + + In-place version of :meth:`~Tensor.negative` + """ + + def nelement(self) -> _int: + r""" + nelement() -> int + + Alias for :meth:`~Tensor.numel` + """ + + @overload + def new(cls, *args: Any, device: DeviceLikeType | None = None) -> Self: ... + @overload + def new(cls, storage: Storage) -> Self: ... + @overload + def new(cls, other: Tensor) -> Self: ... + @overload + def new(cls, size: _size, *, device: DeviceLikeType | None = None) -> Self: ... + @overload + def new_empty( + self, + size: Sequence[_int | SymInt], + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, + ) -> Tensor: + r""" + new_empty(size, *, dtype=None, device=None, requires_grad=False, layout=torch.strided, pin_memory=False) -> Tensor + + + Returns a Tensor of size :attr:`size` filled with uninitialized data. + By default, the returned Tensor has the same :class:`torch.dtype` and + :class:`torch.device` as this tensor. + + Args: + size (int...): a list, tuple, or :class:`torch.Size` of integers defining the + shape of the output tensor. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired type of returned tensor. + Default: if None, same :class:`torch.dtype` as this tensor. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if None, same :class:`torch.device` as this tensor. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> tensor = torch.ones(()) + >>> tensor.new_empty((2, 3)) + tensor([[ 5.8182e-18, 4.5765e-41, -1.0545e+30], + [ 3.0949e-41, 4.4842e-44, 0.0000e+00]]) + """ + + @overload + def new_empty( + self, + *size: _int | SymInt, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, + ) -> Tensor: + r""" + new_empty(size, *, dtype=None, device=None, requires_grad=False, layout=torch.strided, pin_memory=False) -> Tensor + + + Returns a Tensor of size :attr:`size` filled with uninitialized data. + By default, the returned Tensor has the same :class:`torch.dtype` and + :class:`torch.device` as this tensor. + + Args: + size (int...): a list, tuple, or :class:`torch.Size` of integers defining the + shape of the output tensor. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired type of returned tensor. + Default: if None, same :class:`torch.dtype` as this tensor. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if None, same :class:`torch.device` as this tensor. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> tensor = torch.ones(()) + >>> tensor.new_empty((2, 3)) + tensor([[ 5.8182e-18, 4.5765e-41, -1.0545e+30], + [ 3.0949e-41, 4.4842e-44, 0.0000e+00]]) + """ + + def new_empty_strided( + self, + size: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, + ) -> Tensor: + r""" + new_empty_strided(size, stride, dtype=None, device=None, requires_grad=False, layout=torch.strided, pin_memory=False) -> Tensor + + + Returns a Tensor of size :attr:`size` and strides :attr:`stride` filled with + uninitialized data. By default, the returned Tensor has the same + :class:`torch.dtype` and :class:`torch.device` as this tensor. + + Args: + size (int...): a list, tuple, or :class:`torch.Size` of integers defining the + shape of the output tensor. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired type of returned tensor. + Default: if None, same :class:`torch.dtype` as this tensor. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if None, same :class:`torch.device` as this tensor. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> tensor = torch.ones(()) + >>> tensor.new_empty_strided((2, 3), (3, 1)) + tensor([[ 5.8182e-18, 4.5765e-41, -1.0545e+30], + [ 3.0949e-41, 4.4842e-44, 0.0000e+00]]) + """ + + def new_full( + self, + size: Sequence[_int | SymInt], + fill_value: Number | _complex, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, + ) -> Tensor: + r""" + new_full(size, fill_value, *, dtype=None, device=None, requires_grad=False, layout=torch.strided, pin_memory=False) -> Tensor + + + Returns a Tensor of size :attr:`size` filled with :attr:`fill_value`. + By default, the returned Tensor has the same :class:`torch.dtype` and + :class:`torch.device` as this tensor. + + Args: + fill_value (scalar): the number to fill the output tensor with. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired type of returned tensor. + Default: if None, same :class:`torch.dtype` as this tensor. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if None, same :class:`torch.device` as this tensor. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> tensor = torch.ones((2,), dtype=torch.float64) + >>> tensor.new_full((3, 4), 3.141592) + tensor([[ 3.1416, 3.1416, 3.1416, 3.1416], + [ 3.1416, 3.1416, 3.1416, 3.1416], + [ 3.1416, 3.1416, 3.1416, 3.1416]], dtype=torch.float64) + """ + + @overload + def new_ones( + self, + size: _size, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + pin_memory: _bool = False, + ) -> Tensor: + r""" + new_ones(size, *, dtype=None, device=None, requires_grad=False, layout=torch.strided, pin_memory=False) -> Tensor + + + Returns a Tensor of size :attr:`size` filled with ``1``. + By default, the returned Tensor has the same :class:`torch.dtype` and + :class:`torch.device` as this tensor. + + Args: + size (int...): a list, tuple, or :class:`torch.Size` of integers defining the + shape of the output tensor. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired type of returned tensor. + Default: if None, same :class:`torch.dtype` as this tensor. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if None, same :class:`torch.device` as this tensor. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> tensor = torch.tensor((), dtype=torch.int32) + >>> tensor.new_ones((2, 3)) + tensor([[ 1, 1, 1], + [ 1, 1, 1]], dtype=torch.int32) + """ + + @overload + def new_ones( + self, + size: Sequence[_int | SymInt], + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, + ) -> Tensor: + r""" + new_ones(size, *, dtype=None, device=None, requires_grad=False, layout=torch.strided, pin_memory=False) -> Tensor + + + Returns a Tensor of size :attr:`size` filled with ``1``. + By default, the returned Tensor has the same :class:`torch.dtype` and + :class:`torch.device` as this tensor. + + Args: + size (int...): a list, tuple, or :class:`torch.Size` of integers defining the + shape of the output tensor. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired type of returned tensor. + Default: if None, same :class:`torch.dtype` as this tensor. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if None, same :class:`torch.device` as this tensor. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> tensor = torch.tensor((), dtype=torch.int32) + >>> tensor.new_ones((2, 3)) + tensor([[ 1, 1, 1], + [ 1, 1, 1]], dtype=torch.int32) + """ + + @overload + def new_ones( + self, + *size: _int | SymInt, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, + ) -> Tensor: + r""" + new_ones(size, *, dtype=None, device=None, requires_grad=False, layout=torch.strided, pin_memory=False) -> Tensor + + + Returns a Tensor of size :attr:`size` filled with ``1``. + By default, the returned Tensor has the same :class:`torch.dtype` and + :class:`torch.device` as this tensor. + + Args: + size (int...): a list, tuple, or :class:`torch.Size` of integers defining the + shape of the output tensor. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired type of returned tensor. + Default: if None, same :class:`torch.dtype` as this tensor. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if None, same :class:`torch.device` as this tensor. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> tensor = torch.tensor((), dtype=torch.int32) + >>> tensor.new_ones((2, 3)) + tensor([[ 1, 1, 1], + [ 1, 1, 1]], dtype=torch.int32) + """ + + def new_tensor( + self, + data: Any, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + pin_memory: _bool = False, + ) -> Tensor: + r""" + new_tensor(data, *, dtype=None, device=None, requires_grad=False, layout=torch.strided, pin_memory=False) -> Tensor + + + Returns a new Tensor with :attr:`data` as the tensor data. + By default, the returned Tensor has the same :class:`torch.dtype` and + :class:`torch.device` as this tensor. + + .. warning:: + + :func:`new_tensor` always copies :attr:`data`. If you have a Tensor + ``data`` and want to avoid a copy, use :func:`torch.Tensor.requires_grad_` + or :func:`torch.Tensor.detach`. + If you have a numpy array and want to avoid a copy, use + :func:`torch.from_numpy`. + + .. warning:: + + When data is a tensor `x`, :func:`new_tensor()` reads out 'the data' from whatever it is passed, + and constructs a leaf variable. Therefore ``tensor.new_tensor(x)`` is equivalent to ``x.detach().clone()`` + and ``tensor.new_tensor(x, requires_grad=True)`` is equivalent to ``x.detach().clone().requires_grad_(True)``. + The equivalents using ``detach()`` and ``clone()`` are recommended. + + Args: + data (array_like): The returned Tensor copies :attr:`data`. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired type of returned tensor. + Default: if None, same :class:`torch.dtype` as this tensor. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if None, same :class:`torch.device` as this tensor. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> tensor = torch.ones((2,), dtype=torch.int8) + >>> data = [[0, 1], [2, 3]] + >>> tensor.new_tensor(data) + tensor([[ 0, 1], + [ 2, 3]], dtype=torch.int8) + """ + + @overload + def new_zeros( + self, + size: Sequence[_int | SymInt], + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, + ) -> Tensor: + r""" + new_zeros(size, *, dtype=None, device=None, requires_grad=False, layout=torch.strided, pin_memory=False) -> Tensor + + + Returns a Tensor of size :attr:`size` filled with ``0``. + By default, the returned Tensor has the same :class:`torch.dtype` and + :class:`torch.device` as this tensor. + + Args: + size (int...): a list, tuple, or :class:`torch.Size` of integers defining the + shape of the output tensor. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired type of returned tensor. + Default: if None, same :class:`torch.dtype` as this tensor. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if None, same :class:`torch.device` as this tensor. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> tensor = torch.tensor((), dtype=torch.float64) + >>> tensor.new_zeros((2, 3)) + tensor([[ 0., 0., 0.], + [ 0., 0., 0.]], dtype=torch.float64) + """ + + @overload + def new_zeros( + self, + *size: _int | SymInt, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, + ) -> Tensor: + r""" + new_zeros(size, *, dtype=None, device=None, requires_grad=False, layout=torch.strided, pin_memory=False) -> Tensor + + + Returns a Tensor of size :attr:`size` filled with ``0``. + By default, the returned Tensor has the same :class:`torch.dtype` and + :class:`torch.device` as this tensor. + + Args: + size (int...): a list, tuple, or :class:`torch.Size` of integers defining the + shape of the output tensor. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired type of returned tensor. + Default: if None, same :class:`torch.dtype` as this tensor. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if None, same :class:`torch.device` as this tensor. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> tensor = torch.tensor((), dtype=torch.float64) + >>> tensor.new_zeros((2, 3)) + tensor([[ 0., 0., 0.], + [ 0., 0., 0.]], dtype=torch.float64) + """ + + def nextafter(self, other: Tensor) -> Tensor: + r""" + nextafter(other) -> Tensor + See :func:`torch.nextafter` + """ + + def nextafter_(self, other: Tensor) -> Tensor: + r""" + nextafter_(other) -> Tensor + In-place version of :meth:`~Tensor.nextafter` + """ + + @overload + def nonzero(self, *, as_tuple: Literal[False] = False) -> Tensor: + r""" + nonzero() -> LongTensor + + See :func:`torch.nonzero` + """ + + @overload + def nonzero(self, *, as_tuple: Literal[True]) -> tuple[Tensor, ...]: + r""" + nonzero() -> LongTensor + + See :func:`torch.nonzero` + """ + + def nonzero_static( + self, + *, + size: _int | SymInt, + fill_value: _int = -1, + ) -> Tensor: + r""" + nonzero_static(input, *, size, fill_value=-1) -> Tensor + + Returns a 2-D tensor where each row is the index for a non-zero value. + The returned Tensor has the same `torch.dtype` as `torch.nonzero()`. + + Args: + input (Tensor): the input tensor to count non-zero elements. + + Keyword args: + size (int): the size of non-zero elements expected to be included in the out + tensor. Pad the out tensor with `fill_value` if the `size` is larger + than total number of non-zero elements, truncate out tensor if `size` + is smaller. The size must be a non-negative integer. + fill_value (int, optional): the value to fill the output tensor with when `size` is larger + than the total number of non-zero elements. Default is `-1` to represent + invalid index. + + Example: + + # Example 1: Padding + >>> input_tensor = torch.tensor([[1, 0], [3, 2]]) + >>> static_size = 4 + >>> t = torch.nonzero_static(input_tensor, size=static_size) + tensor([[ 0, 0], + [ 1, 0], + [ 1, 1], + [ -1, -1]], dtype=torch.int64) + + # Example 2: Truncating + >>> input_tensor = torch.tensor([[1, 0], [3, 2]]) + >>> static_size = 2 + >>> t = torch.nonzero_static(input_tensor, size=static_size) + tensor([[ 0, 0], + [ 1, 0]], dtype=torch.int64) + + # Example 3: 0 size + >>> input_tensor = torch.tensor([10]) + >>> static_size = 0 + >>> t = torch.nonzero_static(input_tensor, size=static_size) + tensor([], size=(0, 1), dtype=torch.int64) + + # Example 4: 0 rank input + >>> input_tensor = torch.tensor(10) + >>> static_size = 2 + >>> t = torch.nonzero_static(input_tensor, size=static_size) + tensor([], size=(2, 0), dtype=torch.int64) + """ + + def normal_( + self, + mean: _float = 0, + std: _float = 1, + *, + generator: Generator | None = None, + ) -> Tensor: + r""" + normal_(mean=0, std=1, *, generator=None) -> Tensor + + Fills :attr:`self` tensor with elements samples from the normal distribution + parameterized by :attr:`mean` and :attr:`std`. + """ + + @overload + def not_equal(self, other: Tensor) -> Tensor: + r""" + not_equal(other) -> Tensor + + See :func:`torch.not_equal`. + """ + + @overload + def not_equal(self, other: Number | _complex) -> Tensor: + r""" + not_equal(other) -> Tensor + + See :func:`torch.not_equal`. + """ + + @overload + def not_equal_(self, other: Tensor) -> Tensor: + r""" + not_equal_(other) -> Tensor + + In-place version of :meth:`~Tensor.not_equal`. + """ + + @overload + def not_equal_(self, other: Number | _complex) -> Tensor: + r""" + not_equal_(other) -> Tensor + + In-place version of :meth:`~Tensor.not_equal`. + """ + + def numel(self) -> _int: + r""" + numel() -> int + + See :func:`torch.numel` + """ + + def numpy(self, *, force: _bool = False) -> numpy.ndarray: + r""" + numpy(*, force=False) -> numpy.ndarray + + Returns the tensor as a NumPy :class:`ndarray`. + + If :attr:`force` is ``False`` (the default), the conversion + is performed only if the tensor is on the CPU, does not require grad, + does not have its conjugate bit set, and is a dtype and layout that + NumPy supports. The returned ndarray and the tensor will share their + storage, so changes to the tensor will be reflected in the ndarray + and vice versa. + + If :attr:`force` is ``True`` this is equivalent to + calling ``t.detach().cpu().resolve_conj().resolve_neg().numpy()``. + If the tensor isn't on the CPU or the conjugate or negative bit is set, + the tensor won't share its storage with the returned ndarray. + Setting :attr:`force` to ``True`` can be a useful shorthand. + + Args: + force (bool): if ``True``, the ndarray may be a copy of the tensor + instead of always sharing memory, defaults to ``False``. + """ + + def orgqr(self, input2: Tensor) -> Tensor: + r""" + orgqr(input2) -> Tensor + + See :func:`torch.orgqr` + """ + + def ormqr( + self, + input2: Tensor, + input3: Tensor, + left: _bool = True, + transpose: _bool = False, + ) -> Tensor: + r""" + ormqr(input2, input3, left=True, transpose=False) -> Tensor + + See :func:`torch.ormqr` + """ + + def outer(self, vec2: Tensor) -> Tensor: + r""" + outer(vec2) -> Tensor + + See :func:`torch.outer`. + """ + + @overload + def permute(self, dims: _size) -> Tensor: + r""" + permute(*dims) -> Tensor + + See :func:`torch.permute` + """ + + @overload + def permute(self, *dims: _int) -> Tensor: + r""" + permute(*dims) -> Tensor + + See :func:`torch.permute` + """ + + def pin_memory(self, device: DeviceLikeType | None = None) -> Tensor: + r""" + pin_memory() -> Tensor + + Copies the tensor to pinned memory, if it's not already pinned. + By default, the device pinned memory on will be the current :ref:`accelerator`. + """ + + def pinverse(self, rcond: _float = 1e-15) -> Tensor: + r""" + pinverse() -> Tensor + + See :func:`torch.pinverse` + """ + + def polygamma(self, n: _int) -> Tensor: + r""" + polygamma(n) -> Tensor + + See :func:`torch.polygamma` + """ + + def polygamma_(self, n: _int) -> Tensor: + r""" + polygamma_(n) -> Tensor + + In-place version of :meth:`~Tensor.polygamma` + """ + + def positive(self) -> Tensor: + r""" + positive() -> Tensor + + See :func:`torch.positive` + """ + + @overload + def pow(self, exponent: Tensor) -> Tensor: + r""" + pow(exponent) -> Tensor + + See :func:`torch.pow` + """ + + @overload + def pow(self, exponent: Number | _complex) -> Tensor: + r""" + pow(exponent) -> Tensor + + See :func:`torch.pow` + """ + + @overload + def pow_(self, exponent: Tensor) -> Tensor: + r""" + pow_(exponent) -> Tensor + + In-place version of :meth:`~Tensor.pow` + """ + + @overload + def pow_(self, exponent: Number | _complex) -> Tensor: + r""" + pow_(exponent) -> Tensor + + In-place version of :meth:`~Tensor.pow` + """ + + def prelu(self, weight: Tensor) -> Tensor: ... + @overload + def prod(self, *, dtype: _dtype | None = None) -> Tensor: + r""" + prod(dim=None, keepdim=False, dtype=None) -> Tensor + + See :func:`torch.prod` + """ + + @overload + def prod( + self, + dim: _int, + keepdim: _bool = False, + *, + dtype: _dtype | None = None, + ) -> Tensor: + r""" + prod(dim=None, keepdim=False, dtype=None) -> Tensor + + See :func:`torch.prod` + """ + + @overload + def prod( + self, + dim: str | EllipsisType | None, + keepdim: _bool = False, + *, + dtype: _dtype | None = None, + ) -> Tensor: + r""" + prod(dim=None, keepdim=False, dtype=None) -> Tensor + + See :func:`torch.prod` + """ + + def put( + self, + index: Tensor, + source: Tensor, + accumulate: _bool = False, + ) -> Tensor: + r""" + put(input, index, source, accumulate=False) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.put_`. + `input` corresponds to `self` in :meth:`torch.Tensor.put_`. + """ + + def put_( + self, + index: Tensor, + source: Tensor, + accumulate: _bool = False, + ) -> Tensor: + r""" + put_(index, source, accumulate=False) -> Tensor + + Copies the elements from :attr:`source` into the positions specified by + :attr:`index`. For the purpose of indexing, the :attr:`self` tensor is treated as if + it were a 1-D tensor. + + :attr:`index` and :attr:`source` need to have the same number of elements, but not necessarily + the same shape. + + If :attr:`accumulate` is ``True``, the elements in :attr:`source` are added to + :attr:`self`. If accumulate is ``False``, the behavior is undefined if :attr:`index` + contain duplicate elements. + + Args: + index (LongTensor): the indices into self + source (Tensor): the tensor containing values to copy from + accumulate (bool, optional): whether to accumulate into self. Default: ``False`` + + Example:: + + >>> src = torch.tensor([[4, 3, 5], + ... [6, 7, 8]]) + >>> src.put_(torch.tensor([1, 3]), torch.tensor([9, 10])) + tensor([[ 4, 9, 5], + [ 10, 7, 8]]) + """ + + def q_per_channel_axis(self) -> _int: + r""" + q_per_channel_axis() -> int + + Given a Tensor quantized by linear (affine) per-channel quantization, + returns the index of dimension on which per-channel quantization is applied. + """ + + def q_per_channel_scales(self) -> Tensor: + r""" + q_per_channel_scales() -> Tensor + + Given a Tensor quantized by linear (affine) per-channel quantization, + returns a Tensor of scales of the underlying quantizer. It has the number of + elements that matches the corresponding dimensions (from q_per_channel_axis) of + the tensor. + """ + + def q_per_channel_zero_points(self) -> Tensor: + r""" + q_per_channel_zero_points() -> Tensor + + Given a Tensor quantized by linear (affine) per-channel quantization, + returns a tensor of zero_points of the underlying quantizer. It has the number of + elements that matches the corresponding dimensions (from q_per_channel_axis) of + the tensor. + """ + + def q_scale(self) -> _float: + r""" + q_scale() -> float + + Given a Tensor quantized by linear(affine) quantization, + returns the scale of the underlying quantizer(). + """ + + def q_zero_point(self) -> _int: + r""" + q_zero_point() -> int + + Given a Tensor quantized by linear(affine) quantization, + returns the zero_point of the underlying quantizer(). + """ + + def qr(self, some: _bool = True) -> torch.return_types.qr: + r""" + qr(some=True) -> (Tensor, Tensor) + + See :func:`torch.qr` + """ + + def qscheme(self) -> _qscheme: + r""" + qscheme() -> torch.qscheme + + Returns the quantization scheme of a given QTensor. + """ + + @overload + def quantile( + self, + q: Tensor, + dim: _int | None = None, + keepdim: _bool = False, + *, + interpolation: str = "linear", + ) -> Tensor: + r""" + quantile(q, dim=None, keepdim=False, *, interpolation='linear') -> Tensor + + See :func:`torch.quantile` + """ + + @overload + def quantile( + self, + q: _float, + dim: _int | None = None, + keepdim: _bool = False, + *, + interpolation: str = "linear", + ) -> Tensor: + r""" + quantile(q, dim=None, keepdim=False, *, interpolation='linear') -> Tensor + + See :func:`torch.quantile` + """ + + def rad2deg(self) -> Tensor: + r""" + rad2deg() -> Tensor + + See :func:`torch.rad2deg` + """ + + def rad2deg_(self) -> Tensor: + r""" + rad2deg_() -> Tensor + + In-place version of :meth:`~Tensor.rad2deg` + """ + + @overload + def random_(self, *, generator: Generator | None = None) -> Tensor: + r""" + random_(from=0, to=None, *, generator=None) -> Tensor + + Fills :attr:`self` tensor with numbers sampled from the discrete uniform + distribution over ``[from, to - 1]``. If not specified, the values are usually + only bounded by :attr:`self` tensor's data type. However, for floating point + types, if unspecified, range will be ``[0, 2^mantissa]`` to ensure that every + value is representable. For example, `torch.tensor(1, dtype=torch.double).random_()` + will be uniform in ``[0, 2^53]``. + """ + + @overload + def random_( + self, + from_: _int, + to: _int | None, + *, + generator: Generator | None = None, + ) -> Tensor: + r""" + random_(from=0, to=None, *, generator=None) -> Tensor + + Fills :attr:`self` tensor with numbers sampled from the discrete uniform + distribution over ``[from, to - 1]``. If not specified, the values are usually + only bounded by :attr:`self` tensor's data type. However, for floating point + types, if unspecified, range will be ``[0, 2^mantissa]`` to ensure that every + value is representable. For example, `torch.tensor(1, dtype=torch.double).random_()` + will be uniform in ``[0, 2^53]``. + """ + + @overload + def random_( + self, + to: _int, + *, + generator: Generator | None = None, + ) -> Tensor: + r""" + random_(from=0, to=None, *, generator=None) -> Tensor + + Fills :attr:`self` tensor with numbers sampled from the discrete uniform + distribution over ``[from, to - 1]``. If not specified, the values are usually + only bounded by :attr:`self` tensor's data type. However, for floating point + types, if unspecified, range will be ``[0, 2^mantissa]`` to ensure that every + value is representable. For example, `torch.tensor(1, dtype=torch.double).random_()` + will be uniform in ``[0, 2^53]``. + """ + + def ravel(self) -> Tensor: + r""" + ravel() -> Tensor + + see :func:`torch.ravel` + """ + + def reciprocal(self) -> Tensor: + r""" + reciprocal() -> Tensor + + See :func:`torch.reciprocal` + """ + + def reciprocal_(self) -> Tensor: + r""" + reciprocal_() -> Tensor + + In-place version of :meth:`~Tensor.reciprocal` + """ + + def record_stream(self, s: Stream) -> None: + r""" + record_stream(stream) + + Marks the tensor as having been used by this stream. When the tensor + is deallocated, ensure the tensor memory is not reused for another tensor + until all work queued on :attr:`stream` at the time of deallocation is + complete. + + .. note:: + + The caching allocator is aware of only the stream where a tensor was + allocated. Due to the awareness, it already correctly manages the life + cycle of tensors on only one stream. But if a tensor is used on a stream + different from the stream of origin, the allocator might reuse the memory + unexpectedly. Calling this method lets the allocator know which streams + have used the tensor. + + .. warning:: + + This method is most suitable for use cases where you are providing a + function that created a tensor on a side stream, and want users to be able + to make use of the tensor without having to think carefully about stream + safety when making use of them. These safety guarantees come at some + performance and predictability cost (analogous to the tradeoff between GC + and manual memory management), so if you are in a situation where + you manage the full lifetime of your tensors, you may consider instead + manually managing CUDA events so that calling this method is not necessary. + In particular, when you call this method, on later allocations the + allocator will poll the recorded stream to see if all operations have + completed yet; you can potentially race with side stream computation and + non-deterministically reuse or fail to reuse memory for an allocation. + + You can safely use tensors allocated on side streams without + :meth:`~Tensor.record_stream`; you must manually ensure that + any non-creation stream uses of a tensor are synced back to the creation + stream before you deallocate the tensor. As the CUDA caching allocator + guarantees that the memory will only be reused with the same creation stream, + this is sufficient to ensure that writes to future reallocations of the + memory will be delayed until non-creation stream uses are done. + (Counterintuitively, you may observe that on the CPU side we have already + reallocated the tensor, even though CUDA kernels on the old tensor are + still in progress. This is fine, because CUDA operations on the new + tensor will appropriately wait for the old operations to complete, as they + are all on the same stream.) + + Concretely, this looks like this:: + + with torch.cuda.stream(s0): + x = torch.zeros(N) + + s1.wait_stream(s0) + with torch.cuda.stream(s1): + y = some_comm_op(x) + + ... some compute on s0 ... + + # synchronize creation stream s0 to side stream s1 + # before deallocating x + s0.wait_stream(s1) + del x + + Note that some discretion is required when deciding when to perform + ``s0.wait_stream(s1)``. In particular, if we were to wait immediately + after ``some_comm_op``, there wouldn't be any point in having the side + stream; it would be equivalent to have run ``some_comm_op`` on ``s0``. + Instead, the synchronization must be placed at some appropriate, later + point in time where you expect the side stream ``s1`` to have finished + work. This location is typically identified via profiling, e.g., using + Chrome traces produced + :meth:`torch.autograd.profiler.profile.export_chrome_trace`. If you + place the wait too early, work on s0 will block until ``s1`` has finished, + preventing further overlapping of communication and computation. If you + place the wait too late, you will use more memory than is strictly + necessary (as you are keeping ``x`` live for longer.) For a concrete + example of how this guidance can be applied in practice, see this post: + `FSDP and CUDACachingAllocator + `_. + """ + + def refine_names( + self, + names: Sequence[str | EllipsisType | None], + ) -> Tensor: ... + def relu(self) -> Tensor: ... + def relu_(self) -> Tensor: ... + @overload + def remainder(self, other: Tensor) -> Tensor: + r""" + remainder(divisor) -> Tensor + + See :func:`torch.remainder` + """ + + @overload + def remainder(self, other: Number | _complex) -> Tensor: + r""" + remainder(divisor) -> Tensor + + See :func:`torch.remainder` + """ + + @overload + def remainder_(self, other: Tensor) -> Tensor: + r""" + remainder_(divisor) -> Tensor + + In-place version of :meth:`~Tensor.remainder` + """ + + @overload + def remainder_(self, other: Number | _complex) -> Tensor: + r""" + remainder_(divisor) -> Tensor + + In-place version of :meth:`~Tensor.remainder` + """ + + def rename( + self, + names: Sequence[str | EllipsisType | None] | None, + ) -> Tensor: ... + def rename_( + self, + names: Sequence[str | EllipsisType | None] | None, + ) -> Tensor: ... + def renorm( + self, + p: Number | _complex, + dim: _int, + maxnorm: Number | _complex, + ) -> Tensor: + r""" + renorm(p, dim, maxnorm) -> Tensor + + See :func:`torch.renorm` + """ + + def renorm_( + self, + p: Number | _complex, + dim: _int, + maxnorm: Number | _complex, + ) -> Tensor: + r""" + renorm_(p, dim, maxnorm) -> Tensor + + In-place version of :meth:`~Tensor.renorm` + """ + + @overload + def repeat(self, repeats: Sequence[_int | SymInt]) -> Tensor: + r""" + repeat(*repeats) -> Tensor + + Repeats this tensor along the specified dimensions. + + Unlike :meth:`~Tensor.expand`, this function copies the tensor's data. + + .. warning:: + + :meth:`~Tensor.repeat` behaves differently from + `numpy.repeat `_, + but is more similar to + `numpy.tile `_. + For the operator similar to `numpy.repeat`, see :func:`torch.repeat_interleave`. + + Args: + repeat (torch.Size, int..., tuple of int or list of int): The number of times to repeat this tensor along each dimension + + Example:: + + >>> x = torch.tensor([1, 2, 3]) + >>> x.repeat(4, 2) + tensor([[ 1, 2, 3, 1, 2, 3], + [ 1, 2, 3, 1, 2, 3], + [ 1, 2, 3, 1, 2, 3], + [ 1, 2, 3, 1, 2, 3]]) + >>> x.repeat(4, 2, 1).size() + torch.Size([4, 2, 3]) + """ + + @overload + def repeat(self, *repeats: _int | SymInt) -> Tensor: + r""" + repeat(*repeats) -> Tensor + + Repeats this tensor along the specified dimensions. + + Unlike :meth:`~Tensor.expand`, this function copies the tensor's data. + + .. warning:: + + :meth:`~Tensor.repeat` behaves differently from + `numpy.repeat `_, + but is more similar to + `numpy.tile `_. + For the operator similar to `numpy.repeat`, see :func:`torch.repeat_interleave`. + + Args: + repeat (torch.Size, int..., tuple of int or list of int): The number of times to repeat this tensor along each dimension + + Example:: + + >>> x = torch.tensor([1, 2, 3]) + >>> x.repeat(4, 2) + tensor([[ 1, 2, 3, 1, 2, 3], + [ 1, 2, 3, 1, 2, 3], + [ 1, 2, 3, 1, 2, 3], + [ 1, 2, 3, 1, 2, 3]]) + >>> x.repeat(4, 2, 1).size() + torch.Size([4, 2, 3]) + """ + + @overload + def repeat_interleave( + self, + repeats: Tensor, + dim: _int | None = None, + *, + output_size: _int | SymInt | None = None, + ) -> Tensor: + r""" + repeat_interleave(repeats, dim=None, *, output_size=None) -> Tensor + + See :func:`torch.repeat_interleave`. + """ + + @overload + def repeat_interleave( + self, + repeats: _int | SymInt, + dim: _int | None = None, + *, + output_size: _int | SymInt | None = None, + ) -> Tensor: + r""" + repeat_interleave(repeats, dim=None, *, output_size=None) -> Tensor + + See :func:`torch.repeat_interleave`. + """ + + def requires_grad_(self, mode: _bool = True) -> Tensor: + r""" + requires_grad_(requires_grad=True) -> Tensor + + Change if autograd should record operations on this tensor: sets this tensor's + :attr:`requires_grad` attribute in-place. Returns this tensor. + + :func:`requires_grad_`'s main use case is to tell autograd to begin recording + operations on a Tensor ``tensor``. If ``tensor`` has ``requires_grad=False`` + (because it was obtained through a DataLoader, or required preprocessing or + initialization), ``tensor.requires_grad_()`` makes it so that autograd will + begin to record operations on ``tensor``. + + Args: + requires_grad (bool): If autograd should record operations on this tensor. + Default: ``True``. + + Example:: + + >>> # Let's say we want to preprocess some saved weights and use + >>> # the result as new weights. + >>> saved_weights = [0.1, 0.2, 0.3, 0.25] + >>> loaded_weights = torch.tensor(saved_weights) + >>> weights = preprocess(loaded_weights) # some function + >>> weights + tensor([-0.5503, 0.4926, -2.1158, -0.8303]) + + >>> # Now, start to record operations done to weights + >>> weights.requires_grad_() + >>> out = weights.pow(2).sum() + >>> out.backward() + >>> weights.grad + tensor([-1.1007, 0.9853, -4.2316, -1.6606]) + """ + + @overload + def reshape(self, shape: Sequence[_int | SymInt]) -> Tensor: + r""" + reshape(*shape) -> Tensor + + Returns a tensor with the same data and number of elements as :attr:`self` + but with the specified shape. This method returns a view if :attr:`shape` is + compatible with the current shape. See :meth:`torch.Tensor.view` on when it is + possible to return a view. + + See :func:`torch.reshape` + + Args: + shape (tuple of ints or int...): the desired shape + """ + + @overload + def reshape(self, *shape: _int | SymInt) -> Tensor: + r""" + reshape(*shape) -> Tensor + + Returns a tensor with the same data and number of elements as :attr:`self` + but with the specified shape. This method returns a view if :attr:`shape` is + compatible with the current shape. See :meth:`torch.Tensor.view` on when it is + possible to return a view. + + See :func:`torch.reshape` + + Args: + shape (tuple of ints or int...): the desired shape + """ + + def reshape_as(self, other: Tensor) -> Tensor: + r""" + reshape_as(other) -> Tensor + + Returns this tensor as the same shape as :attr:`other`. + ``self.reshape_as(other)`` is equivalent to ``self.reshape(other.sizes())``. + This method returns a view if ``other.sizes()`` is compatible with the current + shape. See :meth:`torch.Tensor.view` on when it is possible to return a view. + + Please see :meth:`reshape` for more information about ``reshape``. + + Args: + other (:class:`torch.Tensor`): The result tensor has the same shape + as :attr:`other`. + """ + + @overload + def resize_( + self, + size: Sequence[_int | SymInt], + *, + memory_format: memory_format | None = None, + ) -> Tensor: + r""" + resize_(*sizes, memory_format=torch.contiguous_format) -> Tensor + + Resizes :attr:`self` tensor to the specified size. If the number of elements is + larger than the current storage size, then the underlying storage is resized + to fit the new number of elements. If the number of elements is smaller, the + underlying storage is not changed. Existing elements are preserved but any new + memory is uninitialized. + + .. warning:: + + This is a low-level method. The storage is reinterpreted as C-contiguous, + ignoring the current strides (unless the target size equals the current + size, in which case the tensor is left unchanged). For most purposes, you + will instead want to use :meth:`~Tensor.view()`, which checks for + contiguity, or :meth:`~Tensor.reshape()`, which copies data if needed. To + change the size in-place with custom strides, see :meth:`~Tensor.set_()`. + + .. note:: + + If :func:`torch.use_deterministic_algorithms()` and + :attr:`torch.utils.deterministic.fill_uninitialized_memory` are both set to + ``True``, new elements are initialized to prevent nondeterministic behavior + from using the result as an input to an operation. Floating point and + complex values are set to NaN, and integer values are set to the maximum + value. + + Args: + sizes (torch.Size or int...): the desired size + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + Tensor. Default: ``torch.contiguous_format``. Note that memory format of + :attr:`self` is going to be unaffected if ``self.size()`` matches ``sizes``. + + Example:: + + >>> x = torch.tensor([[1, 2], [3, 4], [5, 6]]) + >>> x.resize_(2, 2) + tensor([[ 1, 2], + [ 3, 4]]) + """ + + @overload + def resize_( + self, + *size: _int | SymInt, + memory_format: memory_format | None = None, + ) -> Tensor: + r""" + resize_(*sizes, memory_format=torch.contiguous_format) -> Tensor + + Resizes :attr:`self` tensor to the specified size. If the number of elements is + larger than the current storage size, then the underlying storage is resized + to fit the new number of elements. If the number of elements is smaller, the + underlying storage is not changed. Existing elements are preserved but any new + memory is uninitialized. + + .. warning:: + + This is a low-level method. The storage is reinterpreted as C-contiguous, + ignoring the current strides (unless the target size equals the current + size, in which case the tensor is left unchanged). For most purposes, you + will instead want to use :meth:`~Tensor.view()`, which checks for + contiguity, or :meth:`~Tensor.reshape()`, which copies data if needed. To + change the size in-place with custom strides, see :meth:`~Tensor.set_()`. + + .. note:: + + If :func:`torch.use_deterministic_algorithms()` and + :attr:`torch.utils.deterministic.fill_uninitialized_memory` are both set to + ``True``, new elements are initialized to prevent nondeterministic behavior + from using the result as an input to an operation. Floating point and + complex values are set to NaN, and integer values are set to the maximum + value. + + Args: + sizes (torch.Size or int...): the desired size + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + Tensor. Default: ``torch.contiguous_format``. Note that memory format of + :attr:`self` is going to be unaffected if ``self.size()`` matches ``sizes``. + + Example:: + + >>> x = torch.tensor([[1, 2], [3, 4], [5, 6]]) + >>> x.resize_(2, 2) + tensor([[ 1, 2], + [ 3, 4]]) + """ + + def resize_as_( + self, + the_template: Tensor, + *, + memory_format: memory_format | None = None, + ) -> Tensor: + r""" + resize_as_(tensor, memory_format=torch.contiguous_format) -> Tensor + + Resizes the :attr:`self` tensor to be the same size as the specified + :attr:`tensor`. This is equivalent to ``self.resize_(tensor.size())``. + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + Tensor. Default: ``torch.contiguous_format``. Note that memory format of + :attr:`self` is going to be unaffected if ``self.size()`` matches ``tensor.size()``. + """ + + def resize_as_sparse_(self, the_template: Tensor) -> Tensor: ... + def resolve_conj(self) -> Tensor: + r""" + resolve_conj() -> Tensor + + See :func:`torch.resolve_conj` + """ + + def resolve_neg(self) -> Tensor: + r""" + resolve_neg() -> Tensor + + See :func:`torch.resolve_neg` + """ + + def retain_grad(self) -> None: + r""" + retain_grad() -> None + + Enables this Tensor to have their :attr:`grad` populated during + :func:`backward`. This is a no-op for leaf tensors. + """ + + def roll( + self, + shifts: _int | SymInt | Sequence[_int | SymInt], + dims: _int | _size = (), + ) -> Tensor: + r""" + roll(shifts, dims) -> Tensor + + See :func:`torch.roll` + """ + + def rot90(self, k: _int = 1, dims: _size = (0, 1)) -> Tensor: + r""" + rot90(k, dims) -> Tensor + + See :func:`torch.rot90` + """ + + @overload + def round(self) -> Tensor: + r""" + round(decimals=0) -> Tensor + + See :func:`torch.round` + """ + + @overload + def round(self, *, decimals: _int) -> Tensor: + r""" + round(decimals=0) -> Tensor + + See :func:`torch.round` + """ + + @overload + def round_(self) -> Tensor: + r""" + round_(decimals=0) -> Tensor + + In-place version of :meth:`~Tensor.round` + """ + + @overload + def round_(self, *, decimals: _int) -> Tensor: + r""" + round_(decimals=0) -> Tensor + + In-place version of :meth:`~Tensor.round` + """ + + def row_indices(self) -> Tensor: ... + def rsqrt(self) -> Tensor: + r""" + rsqrt() -> Tensor + + See :func:`torch.rsqrt` + """ + + def rsqrt_(self) -> Tensor: + r""" + rsqrt_() -> Tensor + + In-place version of :meth:`~Tensor.rsqrt` + """ + + @overload + def scatter(self, dim: _int, index: Tensor, src: Tensor) -> Tensor: + r""" + scatter(dim, index, src) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.scatter_` + """ + + @overload + def scatter( + self, + dim: _int, + index: Tensor, + src: Tensor, + *, + reduce: str, + ) -> Tensor: + r""" + scatter(dim, index, src) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.scatter_` + """ + + @overload + def scatter( + self, + dim: _int, + index: Tensor, + value: Number | _complex, + *, + reduce: str, + ) -> Tensor: + r""" + scatter(dim, index, src) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.scatter_` + """ + + @overload + def scatter( + self, + dim: str | EllipsisType | None, + index: Tensor, + src: Tensor, + ) -> Tensor: + r""" + scatter(dim, index, src) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.scatter_` + """ + + @overload + def scatter( + self, + dim: _int, + index: Tensor, + value: Number | _complex, + ) -> Tensor: + r""" + scatter(dim, index, src) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.scatter_` + """ + + @overload + def scatter( + self, + dim: str | EllipsisType | None, + index: Tensor, + value: Number | _complex, + ) -> Tensor: + r""" + scatter(dim, index, src) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.scatter_` + """ + + @overload + def scatter_(self, dim: _int, index: Tensor, src: Tensor) -> Tensor: + r""" + scatter_(dim, index, src, *, reduce=None) -> Tensor + + Writes all values from the tensor :attr:`src` into :attr:`self` at the indices + specified in the :attr:`index` tensor. For each value in :attr:`src`, its output + index is specified by its index in :attr:`src` for ``dimension != dim`` and by + the corresponding value in :attr:`index` for ``dimension = dim``. + + For a 3-D tensor, :attr:`self` is updated as:: + + self[index[i][j][k]][j][k] = src[i][j][k] # if dim == 0 + self[i][index[i][j][k]][k] = src[i][j][k] # if dim == 1 + self[i][j][index[i][j][k]] = src[i][j][k] # if dim == 2 + + This is the reverse operation of the manner described in :meth:`~Tensor.gather`. + + It is also required that + ``index.size(d) <= src.size(d)`` for all dimensions ``d``, and that + ``index.size(d) <= self.size(d)`` for all dimensions ``d != dim``. + Note that ``input`` and ``index`` do not broadcast against each other for NPUs, + so when running on NPUs, :attr:`input` and :attr:`index` must have the same number of dimensions. + Standard broadcasting occurs in all other cases. + + Moreover, as for :meth:`~Tensor.gather`, the values of :attr:`index` must be + between ``0`` and ``self.size(dim) - 1`` inclusive. + + .. warning:: + + When indices are not unique, the behavior is non-deterministic (one of the + values from ``src`` will be picked arbitrarily) and the gradient will be + incorrect (it will be propagated to all locations in the source that + correspond to the same index)! + + .. note:: + + The backward pass is implemented only for ``src.shape == index.shape``. + + Additionally accepts an optional :attr:`reduce` argument that allows + specification of an optional reduction operation, which is applied to all + values in the tensor :attr:`src` into :attr:`self` at the indices + specified in the :attr:`index`. For each value in :attr:`src`, the reduction + operation is applied to an index in :attr:`self` which is specified by + its index in :attr:`src` for ``dimension != dim`` and by the corresponding + value in :attr:`index` for ``dimension = dim``. + + Given a 3-D tensor and reduction using the multiplication operation, :attr:`self` + is updated as:: + + self[index[i][j][k]][j][k] *= src[i][j][k] # if dim == 0 + self[i][index[i][j][k]][k] *= src[i][j][k] # if dim == 1 + self[i][j][index[i][j][k]] *= src[i][j][k] # if dim == 2 + + Reducing with the addition operation is the same as using + :meth:`~torch.Tensor.scatter_add_`. + + .. warning:: + The reduce argument with Tensor ``src`` is deprecated and will be removed in + a future PyTorch release. Please use :meth:`~torch.Tensor.scatter_reduce_` + instead for more reduction options. + + Args: + dim (int): the axis along which to index + index (LongTensor): the indices of elements to scatter, can be either empty + or of the same dimensionality as ``src``. When empty, the operation + returns ``self`` unchanged. + src (Tensor): the source element(s) to scatter. + + Keyword args: + reduce (str, optional): reduction operation to apply, can be either + ``'add'`` or ``'multiply'``. + + Example:: + + >>> src = torch.arange(1, 11).reshape((2, 5)) + >>> src + tensor([[ 1, 2, 3, 4, 5], + [ 6, 7, 8, 9, 10]]) + >>> index = torch.tensor([[0, 1, 2, 0]]) + >>> torch.zeros(3, 5, dtype=src.dtype).scatter_(0, index, src) + tensor([[1, 0, 0, 4, 0], + [0, 2, 0, 0, 0], + [0, 0, 3, 0, 0]]) + >>> index = torch.tensor([[0, 1, 2], [0, 1, 4]]) + >>> torch.zeros(3, 5, dtype=src.dtype).scatter_(1, index, src) + tensor([[1, 2, 3, 0, 0], + [6, 7, 0, 0, 8], + [0, 0, 0, 0, 0]]) + + >>> torch.full((2, 4), 2.).scatter_(1, torch.tensor([[2], [3]]), + ... 1.23, reduce='multiply') + tensor([[2.0000, 2.0000, 2.4600, 2.0000], + [2.0000, 2.0000, 2.0000, 2.4600]]) + >>> torch.full((2, 4), 2.).scatter_(1, torch.tensor([[2], [3]]), + ... 1.23, reduce='add') + tensor([[2.0000, 2.0000, 3.2300, 2.0000], + [2.0000, 2.0000, 2.0000, 3.2300]]) + + .. function:: scatter_(dim, index, value, *, reduce=None) -> Tensor: + :noindex: + + Writes the value from :attr:`value` into :attr:`self` at the indices + specified in the :attr:`index` tensor. This operation is equivalent to the previous version, + with the :attr:`src` tensor filled entirely with :attr:`value`. + + Args: + dim (int): the axis along which to index + index (LongTensor): the indices of elements to scatter, can be either empty + or of the same dimensionality as ``src``. When empty, the operation + returns ``self`` unchanged. + value (Scalar): the value to scatter. + + Keyword args: + reduce (str, optional): reduction operation to apply, can be either + ``'add'`` or ``'multiply'``. + + Example:: + + >>> index = torch.tensor([[0, 1]]) + >>> value = 2 + >>> torch.zeros(3, 5).scatter_(0, index, value) + tensor([[2., 0., 0., 0., 0.], + [0., 2., 0., 0., 0.], + [0., 0., 0., 0., 0.]]) + """ + + @overload + def scatter_( + self, + dim: _int, + index: Tensor, + src: Tensor, + *, + reduce: str, + ) -> Tensor: + r""" + scatter_(dim, index, src, *, reduce=None) -> Tensor + + Writes all values from the tensor :attr:`src` into :attr:`self` at the indices + specified in the :attr:`index` tensor. For each value in :attr:`src`, its output + index is specified by its index in :attr:`src` for ``dimension != dim`` and by + the corresponding value in :attr:`index` for ``dimension = dim``. + + For a 3-D tensor, :attr:`self` is updated as:: + + self[index[i][j][k]][j][k] = src[i][j][k] # if dim == 0 + self[i][index[i][j][k]][k] = src[i][j][k] # if dim == 1 + self[i][j][index[i][j][k]] = src[i][j][k] # if dim == 2 + + This is the reverse operation of the manner described in :meth:`~Tensor.gather`. + + It is also required that + ``index.size(d) <= src.size(d)`` for all dimensions ``d``, and that + ``index.size(d) <= self.size(d)`` for all dimensions ``d != dim``. + Note that ``input`` and ``index`` do not broadcast against each other for NPUs, + so when running on NPUs, :attr:`input` and :attr:`index` must have the same number of dimensions. + Standard broadcasting occurs in all other cases. + + Moreover, as for :meth:`~Tensor.gather`, the values of :attr:`index` must be + between ``0`` and ``self.size(dim) - 1`` inclusive. + + .. warning:: + + When indices are not unique, the behavior is non-deterministic (one of the + values from ``src`` will be picked arbitrarily) and the gradient will be + incorrect (it will be propagated to all locations in the source that + correspond to the same index)! + + .. note:: + + The backward pass is implemented only for ``src.shape == index.shape``. + + Additionally accepts an optional :attr:`reduce` argument that allows + specification of an optional reduction operation, which is applied to all + values in the tensor :attr:`src` into :attr:`self` at the indices + specified in the :attr:`index`. For each value in :attr:`src`, the reduction + operation is applied to an index in :attr:`self` which is specified by + its index in :attr:`src` for ``dimension != dim`` and by the corresponding + value in :attr:`index` for ``dimension = dim``. + + Given a 3-D tensor and reduction using the multiplication operation, :attr:`self` + is updated as:: + + self[index[i][j][k]][j][k] *= src[i][j][k] # if dim == 0 + self[i][index[i][j][k]][k] *= src[i][j][k] # if dim == 1 + self[i][j][index[i][j][k]] *= src[i][j][k] # if dim == 2 + + Reducing with the addition operation is the same as using + :meth:`~torch.Tensor.scatter_add_`. + + .. warning:: + The reduce argument with Tensor ``src`` is deprecated and will be removed in + a future PyTorch release. Please use :meth:`~torch.Tensor.scatter_reduce_` + instead for more reduction options. + + Args: + dim (int): the axis along which to index + index (LongTensor): the indices of elements to scatter, can be either empty + or of the same dimensionality as ``src``. When empty, the operation + returns ``self`` unchanged. + src (Tensor): the source element(s) to scatter. + + Keyword args: + reduce (str, optional): reduction operation to apply, can be either + ``'add'`` or ``'multiply'``. + + Example:: + + >>> src = torch.arange(1, 11).reshape((2, 5)) + >>> src + tensor([[ 1, 2, 3, 4, 5], + [ 6, 7, 8, 9, 10]]) + >>> index = torch.tensor([[0, 1, 2, 0]]) + >>> torch.zeros(3, 5, dtype=src.dtype).scatter_(0, index, src) + tensor([[1, 0, 0, 4, 0], + [0, 2, 0, 0, 0], + [0, 0, 3, 0, 0]]) + >>> index = torch.tensor([[0, 1, 2], [0, 1, 4]]) + >>> torch.zeros(3, 5, dtype=src.dtype).scatter_(1, index, src) + tensor([[1, 2, 3, 0, 0], + [6, 7, 0, 0, 8], + [0, 0, 0, 0, 0]]) + + >>> torch.full((2, 4), 2.).scatter_(1, torch.tensor([[2], [3]]), + ... 1.23, reduce='multiply') + tensor([[2.0000, 2.0000, 2.4600, 2.0000], + [2.0000, 2.0000, 2.0000, 2.4600]]) + >>> torch.full((2, 4), 2.).scatter_(1, torch.tensor([[2], [3]]), + ... 1.23, reduce='add') + tensor([[2.0000, 2.0000, 3.2300, 2.0000], + [2.0000, 2.0000, 2.0000, 3.2300]]) + + .. function:: scatter_(dim, index, value, *, reduce=None) -> Tensor: + :noindex: + + Writes the value from :attr:`value` into :attr:`self` at the indices + specified in the :attr:`index` tensor. This operation is equivalent to the previous version, + with the :attr:`src` tensor filled entirely with :attr:`value`. + + Args: + dim (int): the axis along which to index + index (LongTensor): the indices of elements to scatter, can be either empty + or of the same dimensionality as ``src``. When empty, the operation + returns ``self`` unchanged. + value (Scalar): the value to scatter. + + Keyword args: + reduce (str, optional): reduction operation to apply, can be either + ``'add'`` or ``'multiply'``. + + Example:: + + >>> index = torch.tensor([[0, 1]]) + >>> value = 2 + >>> torch.zeros(3, 5).scatter_(0, index, value) + tensor([[2., 0., 0., 0., 0.], + [0., 2., 0., 0., 0.], + [0., 0., 0., 0., 0.]]) + """ + + @overload + def scatter_( + self, + dim: _int, + index: Tensor, + value: Number | _complex, + *, + reduce: str, + ) -> Tensor: + r""" + scatter_(dim, index, src, *, reduce=None) -> Tensor + + Writes all values from the tensor :attr:`src` into :attr:`self` at the indices + specified in the :attr:`index` tensor. For each value in :attr:`src`, its output + index is specified by its index in :attr:`src` for ``dimension != dim`` and by + the corresponding value in :attr:`index` for ``dimension = dim``. + + For a 3-D tensor, :attr:`self` is updated as:: + + self[index[i][j][k]][j][k] = src[i][j][k] # if dim == 0 + self[i][index[i][j][k]][k] = src[i][j][k] # if dim == 1 + self[i][j][index[i][j][k]] = src[i][j][k] # if dim == 2 + + This is the reverse operation of the manner described in :meth:`~Tensor.gather`. + + It is also required that + ``index.size(d) <= src.size(d)`` for all dimensions ``d``, and that + ``index.size(d) <= self.size(d)`` for all dimensions ``d != dim``. + Note that ``input`` and ``index`` do not broadcast against each other for NPUs, + so when running on NPUs, :attr:`input` and :attr:`index` must have the same number of dimensions. + Standard broadcasting occurs in all other cases. + + Moreover, as for :meth:`~Tensor.gather`, the values of :attr:`index` must be + between ``0`` and ``self.size(dim) - 1`` inclusive. + + .. warning:: + + When indices are not unique, the behavior is non-deterministic (one of the + values from ``src`` will be picked arbitrarily) and the gradient will be + incorrect (it will be propagated to all locations in the source that + correspond to the same index)! + + .. note:: + + The backward pass is implemented only for ``src.shape == index.shape``. + + Additionally accepts an optional :attr:`reduce` argument that allows + specification of an optional reduction operation, which is applied to all + values in the tensor :attr:`src` into :attr:`self` at the indices + specified in the :attr:`index`. For each value in :attr:`src`, the reduction + operation is applied to an index in :attr:`self` which is specified by + its index in :attr:`src` for ``dimension != dim`` and by the corresponding + value in :attr:`index` for ``dimension = dim``. + + Given a 3-D tensor and reduction using the multiplication operation, :attr:`self` + is updated as:: + + self[index[i][j][k]][j][k] *= src[i][j][k] # if dim == 0 + self[i][index[i][j][k]][k] *= src[i][j][k] # if dim == 1 + self[i][j][index[i][j][k]] *= src[i][j][k] # if dim == 2 + + Reducing with the addition operation is the same as using + :meth:`~torch.Tensor.scatter_add_`. + + .. warning:: + The reduce argument with Tensor ``src`` is deprecated and will be removed in + a future PyTorch release. Please use :meth:`~torch.Tensor.scatter_reduce_` + instead for more reduction options. + + Args: + dim (int): the axis along which to index + index (LongTensor): the indices of elements to scatter, can be either empty + or of the same dimensionality as ``src``. When empty, the operation + returns ``self`` unchanged. + src (Tensor): the source element(s) to scatter. + + Keyword args: + reduce (str, optional): reduction operation to apply, can be either + ``'add'`` or ``'multiply'``. + + Example:: + + >>> src = torch.arange(1, 11).reshape((2, 5)) + >>> src + tensor([[ 1, 2, 3, 4, 5], + [ 6, 7, 8, 9, 10]]) + >>> index = torch.tensor([[0, 1, 2, 0]]) + >>> torch.zeros(3, 5, dtype=src.dtype).scatter_(0, index, src) + tensor([[1, 0, 0, 4, 0], + [0, 2, 0, 0, 0], + [0, 0, 3, 0, 0]]) + >>> index = torch.tensor([[0, 1, 2], [0, 1, 4]]) + >>> torch.zeros(3, 5, dtype=src.dtype).scatter_(1, index, src) + tensor([[1, 2, 3, 0, 0], + [6, 7, 0, 0, 8], + [0, 0, 0, 0, 0]]) + + >>> torch.full((2, 4), 2.).scatter_(1, torch.tensor([[2], [3]]), + ... 1.23, reduce='multiply') + tensor([[2.0000, 2.0000, 2.4600, 2.0000], + [2.0000, 2.0000, 2.0000, 2.4600]]) + >>> torch.full((2, 4), 2.).scatter_(1, torch.tensor([[2], [3]]), + ... 1.23, reduce='add') + tensor([[2.0000, 2.0000, 3.2300, 2.0000], + [2.0000, 2.0000, 2.0000, 3.2300]]) + + .. function:: scatter_(dim, index, value, *, reduce=None) -> Tensor: + :noindex: + + Writes the value from :attr:`value` into :attr:`self` at the indices + specified in the :attr:`index` tensor. This operation is equivalent to the previous version, + with the :attr:`src` tensor filled entirely with :attr:`value`. + + Args: + dim (int): the axis along which to index + index (LongTensor): the indices of elements to scatter, can be either empty + or of the same dimensionality as ``src``. When empty, the operation + returns ``self`` unchanged. + value (Scalar): the value to scatter. + + Keyword args: + reduce (str, optional): reduction operation to apply, can be either + ``'add'`` or ``'multiply'``. + + Example:: + + >>> index = torch.tensor([[0, 1]]) + >>> value = 2 + >>> torch.zeros(3, 5).scatter_(0, index, value) + tensor([[2., 0., 0., 0., 0.], + [0., 2., 0., 0., 0.], + [0., 0., 0., 0., 0.]]) + """ + + @overload + def scatter_( + self, + dim: _int, + index: Tensor, + value: Number | _complex, + ) -> Tensor: + r""" + scatter_(dim, index, src, *, reduce=None) -> Tensor + + Writes all values from the tensor :attr:`src` into :attr:`self` at the indices + specified in the :attr:`index` tensor. For each value in :attr:`src`, its output + index is specified by its index in :attr:`src` for ``dimension != dim`` and by + the corresponding value in :attr:`index` for ``dimension = dim``. + + For a 3-D tensor, :attr:`self` is updated as:: + + self[index[i][j][k]][j][k] = src[i][j][k] # if dim == 0 + self[i][index[i][j][k]][k] = src[i][j][k] # if dim == 1 + self[i][j][index[i][j][k]] = src[i][j][k] # if dim == 2 + + This is the reverse operation of the manner described in :meth:`~Tensor.gather`. + + It is also required that + ``index.size(d) <= src.size(d)`` for all dimensions ``d``, and that + ``index.size(d) <= self.size(d)`` for all dimensions ``d != dim``. + Note that ``input`` and ``index`` do not broadcast against each other for NPUs, + so when running on NPUs, :attr:`input` and :attr:`index` must have the same number of dimensions. + Standard broadcasting occurs in all other cases. + + Moreover, as for :meth:`~Tensor.gather`, the values of :attr:`index` must be + between ``0`` and ``self.size(dim) - 1`` inclusive. + + .. warning:: + + When indices are not unique, the behavior is non-deterministic (one of the + values from ``src`` will be picked arbitrarily) and the gradient will be + incorrect (it will be propagated to all locations in the source that + correspond to the same index)! + + .. note:: + + The backward pass is implemented only for ``src.shape == index.shape``. + + Additionally accepts an optional :attr:`reduce` argument that allows + specification of an optional reduction operation, which is applied to all + values in the tensor :attr:`src` into :attr:`self` at the indices + specified in the :attr:`index`. For each value in :attr:`src`, the reduction + operation is applied to an index in :attr:`self` which is specified by + its index in :attr:`src` for ``dimension != dim`` and by the corresponding + value in :attr:`index` for ``dimension = dim``. + + Given a 3-D tensor and reduction using the multiplication operation, :attr:`self` + is updated as:: + + self[index[i][j][k]][j][k] *= src[i][j][k] # if dim == 0 + self[i][index[i][j][k]][k] *= src[i][j][k] # if dim == 1 + self[i][j][index[i][j][k]] *= src[i][j][k] # if dim == 2 + + Reducing with the addition operation is the same as using + :meth:`~torch.Tensor.scatter_add_`. + + .. warning:: + The reduce argument with Tensor ``src`` is deprecated and will be removed in + a future PyTorch release. Please use :meth:`~torch.Tensor.scatter_reduce_` + instead for more reduction options. + + Args: + dim (int): the axis along which to index + index (LongTensor): the indices of elements to scatter, can be either empty + or of the same dimensionality as ``src``. When empty, the operation + returns ``self`` unchanged. + src (Tensor): the source element(s) to scatter. + + Keyword args: + reduce (str, optional): reduction operation to apply, can be either + ``'add'`` or ``'multiply'``. + + Example:: + + >>> src = torch.arange(1, 11).reshape((2, 5)) + >>> src + tensor([[ 1, 2, 3, 4, 5], + [ 6, 7, 8, 9, 10]]) + >>> index = torch.tensor([[0, 1, 2, 0]]) + >>> torch.zeros(3, 5, dtype=src.dtype).scatter_(0, index, src) + tensor([[1, 0, 0, 4, 0], + [0, 2, 0, 0, 0], + [0, 0, 3, 0, 0]]) + >>> index = torch.tensor([[0, 1, 2], [0, 1, 4]]) + >>> torch.zeros(3, 5, dtype=src.dtype).scatter_(1, index, src) + tensor([[1, 2, 3, 0, 0], + [6, 7, 0, 0, 8], + [0, 0, 0, 0, 0]]) + + >>> torch.full((2, 4), 2.).scatter_(1, torch.tensor([[2], [3]]), + ... 1.23, reduce='multiply') + tensor([[2.0000, 2.0000, 2.4600, 2.0000], + [2.0000, 2.0000, 2.0000, 2.4600]]) + >>> torch.full((2, 4), 2.).scatter_(1, torch.tensor([[2], [3]]), + ... 1.23, reduce='add') + tensor([[2.0000, 2.0000, 3.2300, 2.0000], + [2.0000, 2.0000, 2.0000, 3.2300]]) + + .. function:: scatter_(dim, index, value, *, reduce=None) -> Tensor: + :noindex: + + Writes the value from :attr:`value` into :attr:`self` at the indices + specified in the :attr:`index` tensor. This operation is equivalent to the previous version, + with the :attr:`src` tensor filled entirely with :attr:`value`. + + Args: + dim (int): the axis along which to index + index (LongTensor): the indices of elements to scatter, can be either empty + or of the same dimensionality as ``src``. When empty, the operation + returns ``self`` unchanged. + value (Scalar): the value to scatter. + + Keyword args: + reduce (str, optional): reduction operation to apply, can be either + ``'add'`` or ``'multiply'``. + + Example:: + + >>> index = torch.tensor([[0, 1]]) + >>> value = 2 + >>> torch.zeros(3, 5).scatter_(0, index, value) + tensor([[2., 0., 0., 0., 0.], + [0., 2., 0., 0., 0.], + [0., 0., 0., 0., 0.]]) + """ + + @overload + def scatter_add(self, dim: _int, index: Tensor, src: Tensor) -> Tensor: + r""" + scatter_add(dim, index, src) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.scatter_add_` + """ + + @overload + def scatter_add( + self, + dim: str | EllipsisType | None, + index: Tensor, + src: Tensor, + ) -> Tensor: + r""" + scatter_add(dim, index, src) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.scatter_add_` + """ + + def scatter_add_(self, dim: _int, index: Tensor, src: Tensor) -> Tensor: + r""" + scatter_add_(dim, index, src) -> Tensor + + Adds all values from the tensor :attr:`src` into :attr:`self` at the indices + specified in the :attr:`index` tensor in a similar fashion as + :meth:`~torch.Tensor.scatter_`. For each value in :attr:`src`, it is added to + an index in :attr:`self` which is specified by its index in :attr:`src` + for ``dimension != dim`` and by the corresponding value in :attr:`index` for + ``dimension = dim``. + + For a 3-D tensor, :attr:`self` is updated as:: + + self[index[i][j][k]][j][k] += src[i][j][k] # if dim == 0 + self[i][index[i][j][k]][k] += src[i][j][k] # if dim == 1 + self[i][j][index[i][j][k]] += src[i][j][k] # if dim == 2 + + :attr:`self`, :attr:`index` and :attr:`src` should have same number of + dimensions. It is also required that ``index.size(d) <= src.size(d)`` for all + dimensions ``d``, and that ``index.size(d) <= self.size(d)`` for all dimensions + ``d != dim``. Note that ``index`` and ``src`` do not broadcast. + When :attr:`index` is empty, we always return the original tensor + without further error checking. + + Note: + This operation may behave nondeterministically when given tensors on a CUDA device. See :doc:`/notes/randomness` for more information. + + .. note:: + + The backward pass is implemented only for ``src.shape == index.shape``. + + Args: + dim (int): the axis along which to index + index (LongTensor): the indices of elements to scatter and add, can be + either empty or of the same dimensionality as ``src``. When empty, the + operation returns ``self`` unchanged. + src (Tensor): the source elements to scatter and add + + Example:: + + >>> src = torch.ones((2, 5)) + >>> index = torch.tensor([[0, 1, 2, 0, 0]]) + >>> torch.zeros(3, 5, dtype=src.dtype).scatter_add_(0, index, src) + tensor([[1., 0., 0., 1., 1.], + [0., 1., 0., 0., 0.], + [0., 0., 1., 0., 0.]]) + >>> index = torch.tensor([[0, 1, 2, 0, 0], [0, 1, 2, 2, 2]]) + >>> torch.zeros(3, 5, dtype=src.dtype).scatter_add_(0, index, src) + tensor([[2., 0., 0., 1., 1.], + [0., 2., 0., 0., 0.], + [0., 0., 2., 1., 1.]]) + """ + + def scatter_reduce( + self, + dim: _int, + index: Tensor, + src: Tensor, + reduce: str, + *, + include_self: _bool = True, + ) -> Tensor: + r""" + scatter_reduce(dim, index, src, reduce, *, include_self=True) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.scatter_reduce_` + """ + + def scatter_reduce_( + self, + dim: _int, + index: Tensor, + src: Tensor, + reduce: str, + *, + include_self: _bool = True, + ) -> Tensor: + r""" + scatter_reduce_(dim, index, src, reduce, *, include_self=True) -> Tensor + + Reduces all values from the :attr:`src` tensor to the indices specified in + the :attr:`index` tensor in the :attr:`self` tensor using the applied reduction + defined via the :attr:`reduce` argument (:obj:`"sum"`, :obj:`"prod"`, :obj:`"mean"`, + :obj:`"amax"`, :obj:`"amin"`). For each value in :attr:`src`, it is reduced to an + index in :attr:`self` which is specified by its index in :attr:`src` for + ``dimension != dim`` and by the corresponding value in :attr:`index` for + ``dimension = dim``. If :obj:`include_self="True"`, the values in the :attr:`self` + tensor are included in the reduction. + + :attr:`self`, :attr:`index` and :attr:`src` should all have + the same number of dimensions. It is also required that + ``index.size(d) <= src.size(d)`` for all dimensions ``d``, and that + ``index.size(d) <= self.size(d)`` for all dimensions ``d != dim``. + Note that ``index`` and ``src`` do not broadcast. + + For a 3-D tensor with :obj:`reduce="sum"` and :obj:`include_self=True` the + output is given as:: + + self[index[i][j][k]][j][k] += src[i][j][k] # if dim == 0 + self[i][index[i][j][k]][k] += src[i][j][k] # if dim == 1 + self[i][j][index[i][j][k]] += src[i][j][k] # if dim == 2 + + Note: + This operation may behave nondeterministically when given tensors on a CUDA device. See :doc:`/notes/randomness` for more information. + + .. note:: + + The backward pass is implemented only for ``src.shape == index.shape``. + + .. warning:: + + This function is in beta and may change in the near future. + + Args: + dim (int): the axis along which to index + index (LongTensor): the indices of elements to scatter and reduce. + src (Tensor): the source elements to scatter and reduce + reduce (str): the reduction operation to apply for non-unique indices + (:obj:`"sum"`, :obj:`"prod"`, :obj:`"mean"`, :obj:`"amax"`, :obj:`"amin"`) + include_self (bool): whether elements from the :attr:`self` tensor are + included in the reduction + + Example:: + + >>> src = torch.tensor([1., 2., 3., 4., 5., 6.]) + >>> index = torch.tensor([0, 1, 0, 1, 2, 1]) + >>> input = torch.tensor([1., 2., 3., 4.]) + >>> input.scatter_reduce(0, index, src, reduce="sum") + tensor([5., 14., 8., 4.]) + >>> input.scatter_reduce(0, index, src, reduce="sum", include_self=False) + tensor([4., 12., 5., 4.]) + >>> input2 = torch.tensor([5., 4., 3., 2.]) + >>> input2.scatter_reduce(0, index, src, reduce="amax") + tensor([5., 6., 5., 2.]) + >>> input2.scatter_reduce(0, index, src, reduce="amax", include_self=False) + tensor([3., 6., 5., 2.]) + """ + + @overload + def select(self, dim: _int, index: _int | SymInt) -> Tensor: + r""" + select(dim, index) -> Tensor + + See :func:`torch.select` + """ + + @overload + def select(self, dim: str | EllipsisType | None, index: _int) -> Tensor: + r""" + select(dim, index) -> Tensor + + See :func:`torch.select` + """ + + def select_scatter( + self, + src: Tensor, + dim: _int, + index: _int | SymInt, + ) -> Tensor: + r""" + select_scatter(src, dim, index) -> Tensor + + See :func:`torch.select_scatter` + """ + + @overload + def set_( + self, + source: Storage | TypedStorage | UntypedStorage, + storage_offset: IntLikeType, + size: _symsize, + stride: _symsize, + ) -> Tensor: + r""" + set_(source=None, storage_offset=0, size=None, stride=None) -> Tensor + + Sets the underlying storage, size, and strides. If :attr:`source` is a tensor, + :attr:`self` tensor will share the same storage and have the same size and + strides as :attr:`source`. Changes to elements in one tensor will be reflected + in the other. + + If :attr:`source` is a :class:`~torch.Storage`, the method sets the underlying + storage, offset, size, and stride. + + Args: + source (Tensor or Storage): the tensor or storage to use + storage_offset (int, optional): the offset in the storage + size (torch.Size, optional): the desired size. Defaults to the size of the source. + stride (tuple, optional): the desired stride. Defaults to C-contiguous strides. + """ + + @overload + def set_(self, source: Storage | TypedStorage | UntypedStorage) -> Tensor: + r""" + set_(source=None, storage_offset=0, size=None, stride=None) -> Tensor + + Sets the underlying storage, size, and strides. If :attr:`source` is a tensor, + :attr:`self` tensor will share the same storage and have the same size and + strides as :attr:`source`. Changes to elements in one tensor will be reflected + in the other. + + If :attr:`source` is a :class:`~torch.Storage`, the method sets the underlying + storage, offset, size, and stride. + + Args: + source (Tensor or Storage): the tensor or storage to use + storage_offset (int, optional): the offset in the storage + size (torch.Size, optional): the desired size. Defaults to the size of the source. + stride (tuple, optional): the desired stride. Defaults to C-contiguous strides. + """ + + def sgn(self) -> Tensor: + r""" + sgn() -> Tensor + + See :func:`torch.sgn` + """ + + def sgn_(self) -> Tensor: + r""" + sgn_() -> Tensor + + In-place version of :meth:`~Tensor.sgn` + """ + + def short(self) -> Tensor: + r""" + short(memory_format=torch.preserve_format) -> Tensor + + ``self.short()`` is equivalent to ``self.to(torch.int16)``. See :func:`to`. + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + + def sigmoid(self) -> Tensor: + r""" + sigmoid() -> Tensor + + See :func:`torch.sigmoid` + """ + + def sigmoid_(self) -> Tensor: + r""" + sigmoid_() -> Tensor + + In-place version of :meth:`~Tensor.sigmoid` + """ + + def sign(self) -> Tensor: + r""" + sign() -> Tensor + + See :func:`torch.sign` + """ + + def sign_(self) -> Tensor: + r""" + sign_() -> Tensor + + In-place version of :meth:`~Tensor.sign` + """ + + def signbit(self) -> Tensor: + r""" + signbit() -> Tensor + + See :func:`torch.signbit` + """ + + def sin(self) -> Tensor: + r""" + sin() -> Tensor + + See :func:`torch.sin` + """ + + def sin_(self) -> Tensor: + r""" + sin_() -> Tensor + + In-place version of :meth:`~Tensor.sin` + """ + + def sinc(self) -> Tensor: + r""" + sinc() -> Tensor + + See :func:`torch.sinc` + """ + + def sinc_(self) -> Tensor: + r""" + sinc_() -> Tensor + + In-place version of :meth:`~Tensor.sinc` + """ + + def sinh(self) -> Tensor: + r""" + sinh() -> Tensor + + See :func:`torch.sinh` + """ + + def sinh_(self) -> Tensor: + r""" + sinh_() -> Tensor + + In-place version of :meth:`~Tensor.sinh` + """ + + @overload + def size(self, dim: None = None) -> Size: + r""" + size(dim=None) -> torch.Size or int + + Returns the size of the :attr:`self` tensor. If ``dim`` is not specified, + the returned value is a :class:`torch.Size`, a subclass of :class:`tuple`. + If ``dim`` is specified, returns an int holding the size of that dimension. + + Args: + dim (int, optional): The dimension for which to retrieve the size. + + Example:: + + >>> t = torch.empty(3, 4, 5) + >>> t.size() + torch.Size([3, 4, 5]) + >>> t.size(dim=1) + 4 + """ + + @overload + def size(self, dim: _int) -> _int: + r""" + size(dim=None) -> torch.Size or int + + Returns the size of the :attr:`self` tensor. If ``dim`` is not specified, + the returned value is a :class:`torch.Size`, a subclass of :class:`tuple`. + If ``dim`` is specified, returns an int holding the size of that dimension. + + Args: + dim (int, optional): The dimension for which to retrieve the size. + + Example:: + + >>> t = torch.empty(3, 4, 5) + >>> t.size() + torch.Size([3, 4, 5]) + >>> t.size(dim=1) + 4 + """ + + def slice_inverse( + self, + src: Tensor, + dim: _int = 0, + start: _int | SymInt | None = None, + end: _int | SymInt | None = None, + step: _int | SymInt = 1, + ) -> Tensor: ... + def slice_scatter( + self, + src: Tensor, + dim: _int = 0, + start: _int | SymInt | None = None, + end: _int | SymInt | None = None, + step: _int | SymInt = 1, + ) -> Tensor: + r""" + slice_scatter(src, dim=0, start=None, end=None, step=1) -> Tensor + + See :func:`torch.slice_scatter` + """ + + def slogdet(self) -> torch.return_types.slogdet: + r""" + slogdet() -> (Tensor, Tensor) + + See :func:`torch.slogdet` + """ + + def smm(self, mat2: Tensor) -> Tensor: + r""" + smm(mat) -> Tensor + + See :func:`torch.smm` + """ + + @overload + def softmax(self, dim: _int, dtype: _dtype | None = None) -> Tensor: + r""" + softmax(dim) -> Tensor + + Alias for :func:`torch.nn.functional.softmax`. + """ + + @overload + def softmax( + self, + dim: str | EllipsisType | None, + *, + dtype: _dtype | None = None, + ) -> Tensor: + r""" + softmax(dim) -> Tensor + + Alias for :func:`torch.nn.functional.softmax`. + """ + + @overload + def sort( + self, + *, + stable: _bool | None, + dim: _int = -1, + descending: _bool = False, + ) -> torch.return_types.sort: + r""" + sort(dim=-1, descending=False) -> (Tensor, LongTensor) + + See :func:`torch.sort` + """ + + @overload + def sort( + self, + dim: _int = -1, + descending: _bool = False, + ) -> torch.return_types.sort: + r""" + sort(dim=-1, descending=False) -> (Tensor, LongTensor) + + See :func:`torch.sort` + """ + + @overload + def sort( + self, + *, + stable: _bool | None, + dim: str | EllipsisType | None, + descending: _bool = False, + ) -> torch.return_types.sort: + r""" + sort(dim=-1, descending=False) -> (Tensor, LongTensor) + + See :func:`torch.sort` + """ + + @overload + def sort( + self, + dim: str | EllipsisType | None, + descending: _bool = False, + ) -> torch.return_types.sort: + r""" + sort(dim=-1, descending=False) -> (Tensor, LongTensor) + + See :func:`torch.sort` + """ + + def sparse_dim(self) -> _int: + r""" + sparse_dim() -> int + + Return the number of sparse dimensions in a :ref:`sparse tensor ` :attr:`self`. + + .. note:: + Returns ``0`` if :attr:`self` is not a sparse tensor. + + See also :meth:`Tensor.dense_dim` and :ref:`hybrid tensors `. + """ + + def sparse_mask(self, mask: Tensor) -> Tensor: + r""" + sparse_mask(mask) -> Tensor + + Returns a new :ref:`sparse tensor ` with values from a + strided tensor :attr:`self` filtered by the indices of the sparse + tensor :attr:`mask`. The values of :attr:`mask` sparse tensor are + ignored. :attr:`self` and :attr:`mask` tensors must have the same + shape. + + .. note:: + + The returned sparse tensor might contain duplicate values if :attr:`mask` + is not coalesced. It is therefore advisable to pass ``mask.coalesce()`` + if such behavior is not desired. + + .. note:: + + The returned sparse tensor has the same indices as the sparse tensor + :attr:`mask`, even when the corresponding values in :attr:`self` are + zeros. + + Args: + mask (Tensor): a sparse tensor whose indices are used as a filter + + Example:: + + >>> nse = 5 + >>> dims = (5, 5, 2, 2) + >>> I = torch.cat([torch.randint(0, dims[0], size=(nse,)), + ... torch.randint(0, dims[1], size=(nse,))], 0).reshape(2, nse) + >>> V = torch.randn(nse, dims[2], dims[3]) + >>> S = torch.sparse_coo_tensor(I, V, dims).coalesce() + >>> D = torch.randn(dims) + >>> D.sparse_mask(S) + tensor(indices=tensor([[0, 0, 0, 2], + [0, 1, 4, 3]]), + values=tensor([[[ 1.6550, 0.2397], + [-0.1611, -0.0779]], + + [[ 0.2326, -1.0558], + [ 1.4711, 1.9678]], + + [[-0.5138, -0.0411], + [ 1.9417, 0.5158]], + + [[ 0.0793, 0.0036], + [-0.2569, -0.1055]]]), + size=(5, 5, 2, 2), nnz=4, layout=torch.sparse_coo) + """ + + def sparse_resize_( + self, + size: _size, + sparse_dim: _int, + dense_dim: _int, + ) -> Tensor: + r""" + sparse_resize_(size, sparse_dim, dense_dim) -> Tensor + + Resizes :attr:`self` :ref:`sparse tensor ` to the desired + size and the number of sparse and dense dimensions. + + .. note:: + If the number of specified elements in :attr:`self` is zero, then + :attr:`size`, :attr:`sparse_dim`, and :attr:`dense_dim` can be any + size and positive integers such that ``len(size) == sparse_dim + + dense_dim``. + + If :attr:`self` specifies one or more elements, however, then each + dimension in :attr:`size` must not be smaller than the corresponding + dimension of :attr:`self`, :attr:`sparse_dim` must equal the number + of sparse dimensions in :attr:`self`, and :attr:`dense_dim` must + equal the number of dense dimensions in :attr:`self`. + + .. warning:: + Throws an error if :attr:`self` is not a sparse tensor. + + Args: + size (torch.Size): the desired size. If :attr:`self` is non-empty + sparse tensor, the desired size cannot be smaller than the + original size. + sparse_dim (int): the number of sparse dimensions + dense_dim (int): the number of dense dimensions + """ + + def sparse_resize_and_clear_( + self, + size: _size, + sparse_dim: _int, + dense_dim: _int, + ) -> Tensor: + r""" + sparse_resize_and_clear_(size, sparse_dim, dense_dim) -> Tensor + + Removes all specified elements from a :ref:`sparse tensor + ` :attr:`self` and resizes :attr:`self` to the desired + size and the number of sparse and dense dimensions. + + .. warning: + Throws an error if :attr:`self` is not a sparse tensor. + + Args: + size (torch.Size): the desired size. + sparse_dim (int): the number of sparse dimensions + dense_dim (int): the number of dense dimensions + """ + + @overload + def split(self, split_size: _int, dim: _int = 0) -> Sequence[Tensor]: ... + @overload + def split( + self, + split_size: tuple[_int, ...], + dim: _int = 0, + ) -> Sequence[Tensor]: ... + def split_with_sizes( + self, + split_sizes: Sequence[_int | SymInt], + dim: _int = 0, + ) -> tuple[Tensor, ...]: ... + def sqrt(self) -> Tensor: + r""" + sqrt() -> Tensor + + See :func:`torch.sqrt` + """ + + def sqrt_(self) -> Tensor: + r""" + sqrt_() -> Tensor + + In-place version of :meth:`~Tensor.sqrt` + """ + + def square(self) -> Tensor: + r""" + square() -> Tensor + + See :func:`torch.square` + """ + + def square_(self) -> Tensor: + r""" + square_() -> Tensor + + In-place version of :meth:`~Tensor.square` + """ + + @overload + def squeeze(self) -> Tensor: + r""" + squeeze(dim=None) -> Tensor + + See :func:`torch.squeeze` + """ + + @overload + def squeeze(self, dim: _int) -> Tensor: + r""" + squeeze(dim=None) -> Tensor + + See :func:`torch.squeeze` + """ + + @overload + def squeeze(self, dim: _size) -> Tensor: + r""" + squeeze(dim=None) -> Tensor + + See :func:`torch.squeeze` + """ + + @overload + def squeeze(self, *dim: _int) -> Tensor: + r""" + squeeze(dim=None) -> Tensor + + See :func:`torch.squeeze` + """ + + @overload + def squeeze(self, dim: str | EllipsisType | None) -> Tensor: + r""" + squeeze(dim=None) -> Tensor + + See :func:`torch.squeeze` + """ + + @overload + def squeeze_(self) -> Tensor: + r""" + squeeze_(dim=None) -> Tensor + + In-place version of :meth:`~Tensor.squeeze` + """ + + @overload + def squeeze_(self, dim: _int) -> Tensor: + r""" + squeeze_(dim=None) -> Tensor + + In-place version of :meth:`~Tensor.squeeze` + """ + + @overload + def squeeze_(self, dim: _size) -> Tensor: + r""" + squeeze_(dim=None) -> Tensor + + In-place version of :meth:`~Tensor.squeeze` + """ + + @overload + def squeeze_(self, *dim: _int) -> Tensor: + r""" + squeeze_(dim=None) -> Tensor + + In-place version of :meth:`~Tensor.squeeze` + """ + + @overload + def squeeze_(self, dim: str | EllipsisType | None) -> Tensor: + r""" + squeeze_(dim=None) -> Tensor + + In-place version of :meth:`~Tensor.squeeze` + """ + + def sspaddmm( + self, + mat1: Tensor, + mat2: Tensor, + *, + beta: Number | _complex = 1, + alpha: Number | _complex = 1, + ) -> Tensor: + r""" + sspaddmm(mat1, mat2, *, beta=1, alpha=1) -> Tensor + + See :func:`torch.sspaddmm` + """ + + @overload + def std( + self, + dim: _int | _size | None, + unbiased: _bool = True, + keepdim: _bool = False, + ) -> Tensor: + r""" + std(dim=None, *, correction=1, keepdim=False) -> Tensor + + See :func:`torch.std` + """ + + @overload + def std( + self, + dim: _int | _size | None = None, + *, + correction: Number | _complex | None = None, + keepdim: _bool = False, + ) -> Tensor: + r""" + std(dim=None, *, correction=1, keepdim=False) -> Tensor + + See :func:`torch.std` + """ + + @overload + def std(self, unbiased: _bool = True) -> Tensor: + r""" + std(dim=None, *, correction=1, keepdim=False) -> Tensor + + See :func:`torch.std` + """ + + @overload + def std( + self, + dim: Sequence[str | EllipsisType | None], + unbiased: _bool = True, + keepdim: _bool = False, + ) -> Tensor: + r""" + std(dim=None, *, correction=1, keepdim=False) -> Tensor + + See :func:`torch.std` + """ + + @overload + def std( + self, + dim: Sequence[str | EllipsisType | None], + *, + correction: Number | _complex | None = None, + keepdim: _bool = False, + ) -> Tensor: + r""" + std(dim=None, *, correction=1, keepdim=False) -> Tensor + + See :func:`torch.std` + """ + + def untyped_storage(self) -> UntypedStorage: ... + def storage_offset(self) -> _int | SymInt: + r""" + storage_offset() -> int + + Returns :attr:`self` tensor's offset in the underlying storage in terms of + number of storage elements (not bytes). + + Example:: + + >>> x = torch.tensor([1, 2, 3, 4, 5]) + >>> x.storage_offset() + 0 + >>> x[3:].storage_offset() + 3 + """ + + def storage_type(self) -> Storage: ... + @overload + def stride(self, dim: None = None) -> tuple[_int, ...]: + r""" + stride(dim) -> tuple or int + + Returns the stride of :attr:`self` tensor. + + Stride is the jump necessary to go from one element to the next one in the + specified dimension :attr:`dim`. A tuple of all strides is returned when no + argument is passed in. Otherwise, an integer value is returned as the stride in + the particular dimension :attr:`dim`. + + Args: + dim (int, optional): the desired dimension in which stride is required + + Example:: + + >>> x = torch.tensor([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]) + >>> x.stride() + (5, 1) + >>> x.stride(0) + 5 + >>> x.stride(-1) + 1 + """ + + @overload + def stride(self, dim: _int) -> _int: + r""" + stride(dim) -> tuple or int + + Returns the stride of :attr:`self` tensor. + + Stride is the jump necessary to go from one element to the next one in the + specified dimension :attr:`dim`. A tuple of all strides is returned when no + argument is passed in. Otherwise, an integer value is returned as the stride in + the particular dimension :attr:`dim`. + + Args: + dim (int, optional): the desired dimension in which stride is required + + Example:: + + >>> x = torch.tensor([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]) + >>> x.stride() + (5, 1) + >>> x.stride(0) + 5 + >>> x.stride(-1) + 1 + """ + + def sub( + self, + other: Tensor | Number | _complex | torch.SymInt | torch.SymFloat, + *, + alpha: Number | _complex | None = 1, + out: Tensor | None = None, + ) -> Tensor: + r""" + sub(other, *, alpha=1) -> Tensor + + See :func:`torch.sub`. + """ + + def sub_( + self, + other: Tensor | Number | _complex | torch.SymInt | torch.SymFloat, + *, + alpha: Number | _complex | None = 1, + ) -> Tensor: + r""" + sub_(other, *, alpha=1) -> Tensor + + In-place version of :meth:`~Tensor.sub` + """ + + @overload + def subtract( + self, + other: Tensor, + *, + alpha: Number | _complex = 1, + ) -> Tensor: + r""" + subtract(other, *, alpha=1) -> Tensor + + See :func:`torch.subtract`. + """ + + @overload + def subtract( + self, + other: Number | _complex, + alpha: Number | _complex = 1, + ) -> Tensor: + r""" + subtract(other, *, alpha=1) -> Tensor + + See :func:`torch.subtract`. + """ + + @overload + def subtract_( + self, + other: Tensor, + *, + alpha: Number | _complex = 1, + ) -> Tensor: + r""" + subtract_(other, *, alpha=1) -> Tensor + + In-place version of :meth:`~Tensor.subtract`. + """ + + @overload + def subtract_( + self, + other: Number | _complex, + alpha: Number | _complex = 1, + ) -> Tensor: + r""" + subtract_(other, *, alpha=1) -> Tensor + + In-place version of :meth:`~Tensor.subtract`. + """ + + @overload + def sum(self, *, dtype: _dtype | None = None) -> Tensor: + r""" + sum(dim=None, keepdim=False, dtype=None) -> Tensor + + See :func:`torch.sum` + """ + + @overload + def sum( + self, + dim: _int | _size | None, + keepdim: _bool = False, + *, + dtype: _dtype | None = None, + ) -> Tensor: + r""" + sum(dim=None, keepdim=False, dtype=None) -> Tensor + + See :func:`torch.sum` + """ + + @overload + def sum( + self, + dim: Sequence[str | EllipsisType | None], + keepdim: _bool = False, + *, + dtype: _dtype | None = None, + ) -> Tensor: + r""" + sum(dim=None, keepdim=False, dtype=None) -> Tensor + + See :func:`torch.sum` + """ + + @overload + def sum_to_size(self, size: Sequence[_int | SymInt]) -> Tensor: + r""" + sum_to_size(*size) -> Tensor + + Sum ``this`` tensor to :attr:`size`. + :attr:`size` must be broadcastable to ``this`` tensor size. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + """ + + @overload + def sum_to_size(self, *size: _int | SymInt) -> Tensor: + r""" + sum_to_size(*size) -> Tensor + + Sum ``this`` tensor to :attr:`size`. + :attr:`size` must be broadcastable to ``this`` tensor size. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + """ + + def svd( + self, + some: _bool = True, + compute_uv: _bool = True, + ) -> torch.return_types.svd: + r""" + svd(some=True, compute_uv=True) -> (Tensor, Tensor, Tensor) + + See :func:`torch.svd` + """ + + def swapaxes(self, axis0: _int, axis1: _int) -> Tensor: + r""" + swapaxes(axis0, axis1) -> Tensor + + See :func:`torch.swapaxes` + """ + + def swapaxes_(self, axis0: _int, axis1: _int) -> Tensor: + r""" + swapaxes_(axis0, axis1) -> Tensor + + In-place version of :meth:`~Tensor.swapaxes` + """ + + def swapdims(self, dim0: _int, dim1: _int) -> Tensor: + r""" + swapdims(dim0, dim1) -> Tensor + + See :func:`torch.swapdims` + """ + + def swapdims_(self, dim0: _int, dim1: _int) -> Tensor: + r""" + swapdims_(dim0, dim1) -> Tensor + + In-place version of :meth:`~Tensor.swapdims` + """ + + def t(self) -> Tensor: + r""" + t() -> Tensor + + See :func:`torch.t` + """ + + def t_(self) -> Tensor: + r""" + t_() -> Tensor + + In-place version of :meth:`~Tensor.t` + """ + + def take(self, index: Tensor) -> Tensor: + r""" + take(indices) -> Tensor + + See :func:`torch.take` + """ + + def take_along_dim( + self, + indices: Tensor, + dim: _int | None = None, + ) -> Tensor: + r""" + take_along_dim(indices, dim) -> Tensor + + See :func:`torch.take_along_dim` + """ + + def tan(self) -> Tensor: + r""" + tan() -> Tensor + + See :func:`torch.tan` + """ + + def tan_(self) -> Tensor: + r""" + tan_() -> Tensor + + In-place version of :meth:`~Tensor.tan` + """ + + def tanh(self) -> Tensor: + r""" + tanh() -> Tensor + + See :func:`torch.tanh` + """ + + def tanh_(self) -> Tensor: + r""" + tanh_() -> Tensor + + In-place version of :meth:`~Tensor.tanh` + """ + + @overload + def tensor_split( + self, + indices: Sequence[_int | SymInt], + dim: _int = 0, + ) -> tuple[Tensor, ...]: + r""" + tensor_split(indices_or_sections, dim=0) -> List of Tensors + + See :func:`torch.tensor_split` + """ + + @overload + def tensor_split( + self, + tensor_indices_or_sections: Tensor, + dim: _int = 0, + ) -> tuple[Tensor, ...]: + r""" + tensor_split(indices_or_sections, dim=0) -> List of Tensors + + See :func:`torch.tensor_split` + """ + + @overload + def tensor_split( + self, + sections: _int | SymInt, + dim: _int = 0, + ) -> tuple[Tensor, ...]: + r""" + tensor_split(indices_or_sections, dim=0) -> List of Tensors + + See :func:`torch.tensor_split` + """ + + @overload + def tile(self, dims: Sequence[_int | SymInt]) -> Tensor: + r""" + tile(dims) -> Tensor + + See :func:`torch.tile` + """ + + @overload + def tile(self, *dims: _int | SymInt) -> Tensor: + r""" + tile(dims) -> Tensor + + See :func:`torch.tile` + """ + + @overload + def to( + self, + dtype: _dtype, + non_blocking: _bool = False, + copy: _bool = False, + *, + memory_format: torch.memory_format | None = None, + ) -> Tensor: + r""" + to(*args, **kwargs) -> Tensor + + Performs Tensor dtype and/or device conversion. A :class:`torch.dtype` and :class:`torch.device` are + inferred from the arguments of ``self.to(*args, **kwargs)``. + + .. note:: + + If the ``self`` Tensor already + has the correct :class:`torch.dtype` and :class:`torch.device`, then ``self`` is returned. + Otherwise, the returned tensor is a copy of ``self`` with the desired + :class:`torch.dtype` and :class:`torch.device`. + + .. note:: + + If ``self`` requires gradients (``requires_grad=True``) but the target + ``dtype`` specified is an integer type, the returned tensor will implicitly + set ``requires_grad=False``. This is because only tensors with + floating-point or complex dtypes can require gradients. + + Here are the ways to call ``to``: + + .. method:: to(dtype, non_blocking=False, copy=False, memory_format=torch.preserve_format) -> Tensor + :noindex: + + Returns a Tensor with the specified :attr:`dtype` + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + + .. note:: + + According to `C++ type conversion rules `_, + converting floating point value to integer type will truncate the fractional part. + If the truncated value cannot fit into the target type (e.g., casting ``torch.inf`` to ``torch.long``), + the behavior is undefined and the result may vary across platforms. + + .. method:: to(device=None, dtype=None, non_blocking=False, copy=False, memory_format=torch.preserve_format) -> Tensor + :noindex: + + Returns a Tensor with the specified :attr:`device` and (optional) + :attr:`dtype`. If :attr:`dtype` is ``None`` it is inferred to be ``self.dtype``. + When :attr:`non_blocking` is set to ``True``, the function attempts to perform + the conversion asynchronously with respect to the host, if possible. This + asynchronous behavior applies to both pinned and pageable memory. However, + caution is advised when using this feature. For more information, refer to the + `tutorial on good usage of non_blocking and pin_memory `__. + When :attr:`copy` is set, a new Tensor is created even when the Tensor + already matches the desired conversion. + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + + .. method:: to(other, non_blocking=False, copy=False) -> Tensor + :noindex: + + Returns a Tensor with same :class:`torch.dtype` and :class:`torch.device` as + the Tensor :attr:`other`. + When :attr:`non_blocking` is set to ``True``, the function attempts to perform + the conversion asynchronously with respect to the host, if possible. This + asynchronous behavior applies to both pinned and pageable memory. However, + caution is advised when using this feature. For more information, refer to the + `tutorial on good usage of non_blocking and pin_memory `__. + When :attr:`copy` is set, a new Tensor is created even when the Tensor + already matches the desired conversion. + + Example:: + + >>> tensor = torch.randn(2, 2) # Initially dtype=float32, device=cpu + >>> tensor.to(torch.float64) + tensor([[-0.5044, 0.0005], + [ 0.3310, -0.0584]], dtype=torch.float64) + + >>> cuda0 = torch.device('cuda:0') + >>> tensor.to(cuda0) + tensor([[-0.5044, 0.0005], + [ 0.3310, -0.0584]], device='cuda:0') + + >>> tensor.to(cuda0, dtype=torch.float64) + tensor([[-0.5044, 0.0005], + [ 0.3310, -0.0584]], dtype=torch.float64, device='cuda:0') + + >>> other = torch.randn((), dtype=torch.float64, device=cuda0) + >>> tensor.to(other, non_blocking=True) + tensor([[-0.5044, 0.0005], + [ 0.3310, -0.0584]], dtype=torch.float64, device='cuda:0') + """ + + @overload + def to( + self, + device: DeviceLikeType | None = None, + dtype: _dtype | None = None, + non_blocking: _bool = False, + copy: _bool = False, + *, + memory_format: torch.memory_format | None = None, + ) -> Tensor: + r""" + to(*args, **kwargs) -> Tensor + + Performs Tensor dtype and/or device conversion. A :class:`torch.dtype` and :class:`torch.device` are + inferred from the arguments of ``self.to(*args, **kwargs)``. + + .. note:: + + If the ``self`` Tensor already + has the correct :class:`torch.dtype` and :class:`torch.device`, then ``self`` is returned. + Otherwise, the returned tensor is a copy of ``self`` with the desired + :class:`torch.dtype` and :class:`torch.device`. + + .. note:: + + If ``self`` requires gradients (``requires_grad=True``) but the target + ``dtype`` specified is an integer type, the returned tensor will implicitly + set ``requires_grad=False``. This is because only tensors with + floating-point or complex dtypes can require gradients. + + Here are the ways to call ``to``: + + .. method:: to(dtype, non_blocking=False, copy=False, memory_format=torch.preserve_format) -> Tensor + :noindex: + + Returns a Tensor with the specified :attr:`dtype` + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + + .. note:: + + According to `C++ type conversion rules `_, + converting floating point value to integer type will truncate the fractional part. + If the truncated value cannot fit into the target type (e.g., casting ``torch.inf`` to ``torch.long``), + the behavior is undefined and the result may vary across platforms. + + .. method:: to(device=None, dtype=None, non_blocking=False, copy=False, memory_format=torch.preserve_format) -> Tensor + :noindex: + + Returns a Tensor with the specified :attr:`device` and (optional) + :attr:`dtype`. If :attr:`dtype` is ``None`` it is inferred to be ``self.dtype``. + When :attr:`non_blocking` is set to ``True``, the function attempts to perform + the conversion asynchronously with respect to the host, if possible. This + asynchronous behavior applies to both pinned and pageable memory. However, + caution is advised when using this feature. For more information, refer to the + `tutorial on good usage of non_blocking and pin_memory `__. + When :attr:`copy` is set, a new Tensor is created even when the Tensor + already matches the desired conversion. + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + + .. method:: to(other, non_blocking=False, copy=False) -> Tensor + :noindex: + + Returns a Tensor with same :class:`torch.dtype` and :class:`torch.device` as + the Tensor :attr:`other`. + When :attr:`non_blocking` is set to ``True``, the function attempts to perform + the conversion asynchronously with respect to the host, if possible. This + asynchronous behavior applies to both pinned and pageable memory. However, + caution is advised when using this feature. For more information, refer to the + `tutorial on good usage of non_blocking and pin_memory `__. + When :attr:`copy` is set, a new Tensor is created even when the Tensor + already matches the desired conversion. + + Example:: + + >>> tensor = torch.randn(2, 2) # Initially dtype=float32, device=cpu + >>> tensor.to(torch.float64) + tensor([[-0.5044, 0.0005], + [ 0.3310, -0.0584]], dtype=torch.float64) + + >>> cuda0 = torch.device('cuda:0') + >>> tensor.to(cuda0) + tensor([[-0.5044, 0.0005], + [ 0.3310, -0.0584]], device='cuda:0') + + >>> tensor.to(cuda0, dtype=torch.float64) + tensor([[-0.5044, 0.0005], + [ 0.3310, -0.0584]], dtype=torch.float64, device='cuda:0') + + >>> other = torch.randn((), dtype=torch.float64, device=cuda0) + >>> tensor.to(other, non_blocking=True) + tensor([[-0.5044, 0.0005], + [ 0.3310, -0.0584]], dtype=torch.float64, device='cuda:0') + """ + + @overload + def to( + self, + other: Tensor, + non_blocking: _bool = False, + copy: _bool = False, + *, + memory_format: torch.memory_format | None = None, + ) -> Tensor: + r""" + to(*args, **kwargs) -> Tensor + + Performs Tensor dtype and/or device conversion. A :class:`torch.dtype` and :class:`torch.device` are + inferred from the arguments of ``self.to(*args, **kwargs)``. + + .. note:: + + If the ``self`` Tensor already + has the correct :class:`torch.dtype` and :class:`torch.device`, then ``self`` is returned. + Otherwise, the returned tensor is a copy of ``self`` with the desired + :class:`torch.dtype` and :class:`torch.device`. + + .. note:: + + If ``self`` requires gradients (``requires_grad=True``) but the target + ``dtype`` specified is an integer type, the returned tensor will implicitly + set ``requires_grad=False``. This is because only tensors with + floating-point or complex dtypes can require gradients. + + Here are the ways to call ``to``: + + .. method:: to(dtype, non_blocking=False, copy=False, memory_format=torch.preserve_format) -> Tensor + :noindex: + + Returns a Tensor with the specified :attr:`dtype` + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + + .. note:: + + According to `C++ type conversion rules `_, + converting floating point value to integer type will truncate the fractional part. + If the truncated value cannot fit into the target type (e.g., casting ``torch.inf`` to ``torch.long``), + the behavior is undefined and the result may vary across platforms. + + .. method:: to(device=None, dtype=None, non_blocking=False, copy=False, memory_format=torch.preserve_format) -> Tensor + :noindex: + + Returns a Tensor with the specified :attr:`device` and (optional) + :attr:`dtype`. If :attr:`dtype` is ``None`` it is inferred to be ``self.dtype``. + When :attr:`non_blocking` is set to ``True``, the function attempts to perform + the conversion asynchronously with respect to the host, if possible. This + asynchronous behavior applies to both pinned and pageable memory. However, + caution is advised when using this feature. For more information, refer to the + `tutorial on good usage of non_blocking and pin_memory `__. + When :attr:`copy` is set, a new Tensor is created even when the Tensor + already matches the desired conversion. + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + + .. method:: to(other, non_blocking=False, copy=False) -> Tensor + :noindex: + + Returns a Tensor with same :class:`torch.dtype` and :class:`torch.device` as + the Tensor :attr:`other`. + When :attr:`non_blocking` is set to ``True``, the function attempts to perform + the conversion asynchronously with respect to the host, if possible. This + asynchronous behavior applies to both pinned and pageable memory. However, + caution is advised when using this feature. For more information, refer to the + `tutorial on good usage of non_blocking and pin_memory `__. + When :attr:`copy` is set, a new Tensor is created even when the Tensor + already matches the desired conversion. + + Example:: + + >>> tensor = torch.randn(2, 2) # Initially dtype=float32, device=cpu + >>> tensor.to(torch.float64) + tensor([[-0.5044, 0.0005], + [ 0.3310, -0.0584]], dtype=torch.float64) + + >>> cuda0 = torch.device('cuda:0') + >>> tensor.to(cuda0) + tensor([[-0.5044, 0.0005], + [ 0.3310, -0.0584]], device='cuda:0') + + >>> tensor.to(cuda0, dtype=torch.float64) + tensor([[-0.5044, 0.0005], + [ 0.3310, -0.0584]], dtype=torch.float64, device='cuda:0') + + >>> other = torch.randn((), dtype=torch.float64, device=cuda0) + >>> tensor.to(other, non_blocking=True) + tensor([[-0.5044, 0.0005], + [ 0.3310, -0.0584]], dtype=torch.float64, device='cuda:0') + """ + + def to_dense( + self, + dtype: _dtype | None = None, + *, + masked_grad: _bool | None = None, + ) -> Tensor: + r""" + to_dense(dtype=None, *, masked_grad=True) -> Tensor + + Creates a strided copy of :attr:`self` if :attr:`self` is not a strided tensor, otherwise returns :attr:`self`. + + Keyword args: + {dtype} + masked_grad (bool, optional): If set to ``True`` (default) and + :attr:`self` has a sparse layout then the backward of + :meth:`to_dense` returns ``grad.sparse_mask(self)``. + + Example:: + + >>> s = torch.sparse_coo_tensor( + ... torch.tensor([[1, 1], + ... [0, 2]]), + ... torch.tensor([9, 10]), + ... size=(3, 3)) + >>> s.to_dense() + tensor([[ 0, 0, 0], + [ 9, 0, 10], + [ 0, 0, 0]]) + """ + + def to_mkldnn(self, dtype: _dtype | None = None) -> Tensor: + r""" + to_mkldnn() -> Tensor + Returns a copy of the tensor in ``torch.mkldnn`` layout. + """ + + def to_padded_tensor( + self, + padding: _float, + output_size: Sequence[_int | SymInt] | None = None, + ) -> Tensor: + r""" + to_padded_tensor(padding, output_size=None) -> Tensor + See :func:`to_padded_tensor` + """ + + @overload + def to_sparse( + self, + *, + layout: _layout | None = None, + blocksize: _int | _size | None = None, + dense_dim: _int | None = None, + ) -> Tensor: + r""" + to_sparse(sparseDims) -> Tensor + + Returns a sparse copy of the tensor. PyTorch supports sparse tensors in + :ref:`coordinate format `. + + Args: + sparseDims (int, optional): the number of sparse dimensions to include in the new sparse tensor + + Example:: + + >>> d = torch.tensor([[0, 0, 0], [9, 0, 10], [0, 0, 0]]) + >>> d + tensor([[ 0, 0, 0], + [ 9, 0, 10], + [ 0, 0, 0]]) + >>> d.to_sparse() + tensor(indices=tensor([[1, 1], + [0, 2]]), + values=tensor([ 9, 10]), + size=(3, 3), nnz=2, layout=torch.sparse_coo) + >>> d.to_sparse(1) + tensor(indices=tensor([[1]]), + values=tensor([[ 9, 0, 10]]), + size=(3, 3), nnz=1, layout=torch.sparse_coo) + + .. method:: to_sparse(*, layout=None, blocksize=None, dense_dim=None) -> Tensor + :noindex: + + Returns a sparse tensor with the specified layout and blocksize. If + the :attr:`self` is strided, the number of dense dimensions could be + specified, and a hybrid sparse tensor will be created, with + `dense_dim` dense dimensions and `self.dim() - 2 - dense_dim` batch + dimension. + + .. note:: If the :attr:`self` layout and blocksize parameters match + with the specified layout and blocksize, return + :attr:`self`. Otherwise, return a sparse tensor copy of + :attr:`self`. + + Args: + + layout (:class:`torch.layout`, optional): The desired sparse + layout. One of ``torch.sparse_coo``, ``torch.sparse_csr``, + ``torch.sparse_csc``, ``torch.sparse_bsr``, or + ``torch.sparse_bsc``. Default: if ``None``, + ``torch.sparse_coo``. + + blocksize (list, tuple, :class:`torch.Size`, optional): Block size + of the resulting BSR or BSC tensor. For other layouts, + specifying the block size that is not ``None`` will result in a + RuntimeError exception. A block size must be a tuple of length + two such that its items evenly divide the two sparse dimensions. + + dense_dim (int, optional): Number of dense dimensions of the + resulting CSR, CSC, BSR or BSC tensor. This argument should be + used only if :attr:`self` is a strided tensor, and must be a + value between 0 and dimension of :attr:`self` tensor minus two. + + Example:: + + >>> x = torch.tensor([[1, 0], [0, 0], [2, 3]]) + >>> x.to_sparse(layout=torch.sparse_coo) + tensor(indices=tensor([[0, 2, 2], + [0, 0, 1]]), + values=tensor([1, 2, 3]), + size=(3, 2), nnz=3, layout=torch.sparse_coo) + >>> x.to_sparse(layout=torch.sparse_bsr, blocksize=(1, 2)) + tensor(crow_indices=tensor([0, 1, 1, 2]), + col_indices=tensor([0, 0]), + values=tensor([[[1, 0]], + [[2, 3]]]), size=(3, 2), nnz=2, layout=torch.sparse_bsr) + >>> x.to_sparse(layout=torch.sparse_bsr, blocksize=(2, 1)) + RuntimeError: Tensor size(-2) 3 needs to be divisible by blocksize[0] 2 + >>> x.to_sparse(layout=torch.sparse_csr, blocksize=(3, 1)) + RuntimeError: to_sparse for Strided to SparseCsr conversion does not use specified blocksize + + >>> x = torch.tensor([[[1], [0]], [[0], [0]], [[2], [3]]]) + >>> x.to_sparse(layout=torch.sparse_csr, dense_dim=1) + tensor(crow_indices=tensor([0, 1, 1, 3]), + col_indices=tensor([0, 0, 1]), + values=tensor([[1], + [2], + [3]]), size=(3, 2, 1), nnz=3, layout=torch.sparse_csr) + """ + + @overload + def to_sparse(self, sparse_dim: _int) -> Tensor: + r""" + to_sparse(sparseDims) -> Tensor + + Returns a sparse copy of the tensor. PyTorch supports sparse tensors in + :ref:`coordinate format `. + + Args: + sparseDims (int, optional): the number of sparse dimensions to include in the new sparse tensor + + Example:: + + >>> d = torch.tensor([[0, 0, 0], [9, 0, 10], [0, 0, 0]]) + >>> d + tensor([[ 0, 0, 0], + [ 9, 0, 10], + [ 0, 0, 0]]) + >>> d.to_sparse() + tensor(indices=tensor([[1, 1], + [0, 2]]), + values=tensor([ 9, 10]), + size=(3, 3), nnz=2, layout=torch.sparse_coo) + >>> d.to_sparse(1) + tensor(indices=tensor([[1]]), + values=tensor([[ 9, 0, 10]]), + size=(3, 3), nnz=1, layout=torch.sparse_coo) + + .. method:: to_sparse(*, layout=None, blocksize=None, dense_dim=None) -> Tensor + :noindex: + + Returns a sparse tensor with the specified layout and blocksize. If + the :attr:`self` is strided, the number of dense dimensions could be + specified, and a hybrid sparse tensor will be created, with + `dense_dim` dense dimensions and `self.dim() - 2 - dense_dim` batch + dimension. + + .. note:: If the :attr:`self` layout and blocksize parameters match + with the specified layout and blocksize, return + :attr:`self`. Otherwise, return a sparse tensor copy of + :attr:`self`. + + Args: + + layout (:class:`torch.layout`, optional): The desired sparse + layout. One of ``torch.sparse_coo``, ``torch.sparse_csr``, + ``torch.sparse_csc``, ``torch.sparse_bsr``, or + ``torch.sparse_bsc``. Default: if ``None``, + ``torch.sparse_coo``. + + blocksize (list, tuple, :class:`torch.Size`, optional): Block size + of the resulting BSR or BSC tensor. For other layouts, + specifying the block size that is not ``None`` will result in a + RuntimeError exception. A block size must be a tuple of length + two such that its items evenly divide the two sparse dimensions. + + dense_dim (int, optional): Number of dense dimensions of the + resulting CSR, CSC, BSR or BSC tensor. This argument should be + used only if :attr:`self` is a strided tensor, and must be a + value between 0 and dimension of :attr:`self` tensor minus two. + + Example:: + + >>> x = torch.tensor([[1, 0], [0, 0], [2, 3]]) + >>> x.to_sparse(layout=torch.sparse_coo) + tensor(indices=tensor([[0, 2, 2], + [0, 0, 1]]), + values=tensor([1, 2, 3]), + size=(3, 2), nnz=3, layout=torch.sparse_coo) + >>> x.to_sparse(layout=torch.sparse_bsr, blocksize=(1, 2)) + tensor(crow_indices=tensor([0, 1, 1, 2]), + col_indices=tensor([0, 0]), + values=tensor([[[1, 0]], + [[2, 3]]]), size=(3, 2), nnz=2, layout=torch.sparse_bsr) + >>> x.to_sparse(layout=torch.sparse_bsr, blocksize=(2, 1)) + RuntimeError: Tensor size(-2) 3 needs to be divisible by blocksize[0] 2 + >>> x.to_sparse(layout=torch.sparse_csr, blocksize=(3, 1)) + RuntimeError: to_sparse for Strided to SparseCsr conversion does not use specified blocksize + + >>> x = torch.tensor([[[1], [0]], [[0], [0]], [[2], [3]]]) + >>> x.to_sparse(layout=torch.sparse_csr, dense_dim=1) + tensor(crow_indices=tensor([0, 1, 1, 3]), + col_indices=tensor([0, 0, 1]), + values=tensor([[1], + [2], + [3]]), size=(3, 2, 1), nnz=3, layout=torch.sparse_csr) + """ + + def to_sparse_bsc( + self, + blocksize: _int | _size, + dense_dim: _int | None = None, + ) -> Tensor: + r""" + to_sparse_bsc(blocksize, dense_dim) -> Tensor + + Convert a tensor to a block sparse column (BSC) storage format of + given blocksize. If the :attr:`self` is strided, then the number of + dense dimensions could be specified, and a hybrid BSC tensor will be + created, with `dense_dim` dense dimensions and `self.dim() - 2 - + dense_dim` batch dimension. + + Args: + + blocksize (list, tuple, :class:`torch.Size`, optional): Block size + of the resulting BSC tensor. A block size must be a tuple of + length two such that its items evenly divide the two sparse + dimensions. + + dense_dim (int, optional): Number of dense dimensions of the + resulting BSC tensor. This argument should be used only if + :attr:`self` is a strided tensor, and must be a value between 0 + and dimension of :attr:`self` tensor minus two. + + Example:: + + >>> dense = torch.randn(10, 10) + >>> sparse = dense.to_sparse_csr() + >>> sparse_bsc = sparse.to_sparse_bsc((5, 5)) + >>> sparse_bsc.row_indices() + tensor([0, 1, 0, 1]) + + >>> dense = torch.zeros(4, 3, 1) + >>> dense[0:2, 0] = dense[0:2, 2] = dense[2:4, 1] = 1 + >>> dense.to_sparse_bsc((2, 1), 1) + tensor(ccol_indices=tensor([0, 1, 2, 3]), + row_indices=tensor([0, 1, 0]), + values=tensor([[[[1.]], + + [[1.]]], + + + [[[1.]], + + [[1.]]], + + + [[[1.]], + + [[1.]]]]), size=(4, 3, 1), nnz=3, + layout=torch.sparse_bsc) + """ + + def to_sparse_bsr( + self, + blocksize: _int | _size, + dense_dim: _int | None = None, + ) -> Tensor: + r""" + to_sparse_bsr(blocksize, dense_dim) -> Tensor + + Convert a tensor to a block sparse row (BSR) storage format of given + blocksize. If the :attr:`self` is strided, then the number of dense + dimensions could be specified, and a hybrid BSR tensor will be + created, with `dense_dim` dense dimensions and `self.dim() - 2 - + dense_dim` batch dimension. + + Args: + + blocksize (list, tuple, :class:`torch.Size`, optional): Block size + of the resulting BSR tensor. A block size must be a tuple of + length two such that its items evenly divide the two sparse + dimensions. + + dense_dim (int, optional): Number of dense dimensions of the + resulting BSR tensor. This argument should be used only if + :attr:`self` is a strided tensor, and must be a value between 0 + and dimension of :attr:`self` tensor minus two. + + Example:: + + >>> dense = torch.randn(10, 10) + >>> sparse = dense.to_sparse_csr() + >>> sparse_bsr = sparse.to_sparse_bsr((5, 5)) + >>> sparse_bsr.col_indices() + tensor([0, 1, 0, 1]) + + >>> dense = torch.zeros(4, 3, 1) + >>> dense[0:2, 0] = dense[0:2, 2] = dense[2:4, 1] = 1 + >>> dense.to_sparse_bsr((2, 1), 1) + tensor(crow_indices=tensor([0, 2, 3]), + col_indices=tensor([0, 2, 1]), + values=tensor([[[[1.]], + + [[1.]]], + + + [[[1.]], + + [[1.]]], + + + [[[1.]], + + [[1.]]]]), size=(4, 3, 1), nnz=3, + layout=torch.sparse_bsr) + """ + + def to_sparse_csc(self, dense_dim: _int | None = None) -> Tensor: + r""" + to_sparse_csc() -> Tensor + + Convert a tensor to compressed column storage (CSC) format. Except + for strided tensors, only works with 2D tensors. If the :attr:`self` + is strided, then the number of dense dimensions could be specified, + and a hybrid CSC tensor will be created, with `dense_dim` dense + dimensions and `self.dim() - 2 - dense_dim` batch dimension. + + Args: + + dense_dim (int, optional): Number of dense dimensions of the + resulting CSC tensor. This argument should be used only if + :attr:`self` is a strided tensor, and must be a value between 0 + and dimension of :attr:`self` tensor minus two. + + Example:: + + >>> dense = torch.randn(5, 5) + >>> sparse = dense.to_sparse_csc() + >>> sparse._nnz() + 25 + + >>> dense = torch.zeros(3, 3, 1, 1) + >>> dense[0, 0] = dense[1, 2] = dense[2, 1] = 1 + >>> dense.to_sparse_csc(dense_dim=2) + tensor(ccol_indices=tensor([0, 1, 2, 3]), + row_indices=tensor([0, 2, 1]), + values=tensor([[[1.]], + + [[1.]], + + [[1.]]]), size=(3, 3, 1, 1), nnz=3, + layout=torch.sparse_csc) + """ + + def to_sparse_csr(self, dense_dim: _int | None = None) -> Tensor: + r""" + to_sparse_csr(dense_dim=None) -> Tensor + + Convert a tensor to compressed row storage format (CSR). Except for + strided tensors, only works with 2D tensors. If the :attr:`self` is + strided, then the number of dense dimensions could be specified, and a + hybrid CSR tensor will be created, with `dense_dim` dense dimensions + and `self.dim() - 2 - dense_dim` batch dimension. + + Args: + + dense_dim (int, optional): Number of dense dimensions of the + resulting CSR tensor. This argument should be used only if + :attr:`self` is a strided tensor, and must be a value between 0 + and dimension of :attr:`self` tensor minus two. + + Example:: + + >>> dense = torch.randn(5, 5) + >>> sparse = dense.to_sparse_csr() + >>> sparse._nnz() + 25 + + >>> dense = torch.zeros(3, 3, 1, 1) + >>> dense[0, 0] = dense[1, 2] = dense[2, 1] = 1 + >>> dense.to_sparse_csr(dense_dim=2) + tensor(crow_indices=tensor([0, 1, 2, 3]), + col_indices=tensor([0, 2, 1]), + values=tensor([[[1.]], + + [[1.]], + + [[1.]]]), size=(3, 3, 1, 1), nnz=3, + layout=torch.sparse_csr) + """ + + def tolist(self) -> list: + r""" + tolist() -> list or number + + Returns the tensor as a (nested) list. For scalars, a standard + Python number is returned, just like with :meth:`~Tensor.item`. + Tensors are automatically moved to the CPU first if necessary. + + This operation is not differentiable. + + Examples:: + + >>> a = torch.randn(2, 2) + >>> a.tolist() + [[0.012766935862600803, 0.5415473580360413], + [-0.08909505605697632, 0.7729271650314331]] + >>> a[0,0].tolist() + 0.012766935862600803 + """ + + def topk( + self, + k: _int | SymInt, + dim: _int = -1, + largest: _bool = True, + sorted: _bool = True, + ) -> torch.return_types.topk: + r""" + topk(k, dim=None, largest=True, sorted=True) -> (Tensor, LongTensor) + + See :func:`torch.topk` + """ + + def trace(self) -> Tensor: + r""" + trace() -> Tensor + + See :func:`torch.trace` + """ + + @overload + def transpose(self, dim0: _int, dim1: _int) -> Tensor: + r""" + transpose(dim0, dim1) -> Tensor + + See :func:`torch.transpose` + """ + + @overload + def transpose( + self, + dim0: str | EllipsisType | None, + dim1: str | EllipsisType | None, + ) -> Tensor: + r""" + transpose(dim0, dim1) -> Tensor + + See :func:`torch.transpose` + """ + + def transpose_(self, dim0: _int, dim1: _int) -> Tensor: + r""" + transpose_(dim0, dim1) -> Tensor + + In-place version of :meth:`~Tensor.transpose` + """ + + def triangular_solve( + self, + A: Tensor, + upper: _bool = True, + transpose: _bool = False, + unitriangular: _bool = False, + ) -> torch.return_types.triangular_solve: + r""" + triangular_solve(A, upper=True, transpose=False, unitriangular=False) -> (Tensor, Tensor) + + See :func:`torch.triangular_solve` + """ + + def tril(self, diagonal: _int | SymInt = 0) -> Tensor: + r""" + tril(diagonal=0) -> Tensor + + See :func:`torch.tril` + """ + + def tril_(self, diagonal: _int | SymInt = 0) -> Tensor: + r""" + tril_(diagonal=0) -> Tensor + + In-place version of :meth:`~Tensor.tril` + """ + + def triu(self, diagonal: _int | SymInt = 0) -> Tensor: + r""" + triu(diagonal=0) -> Tensor + + See :func:`torch.triu` + """ + + def triu_(self, diagonal: _int | SymInt = 0) -> Tensor: + r""" + triu_(diagonal=0) -> Tensor + + In-place version of :meth:`~Tensor.triu` + """ + + def true_divide( + self, + other: Tensor | Number | torch.SymInt | torch.SymFloat, + *, + out: Tensor | None = None, + ) -> Tensor: + r""" + true_divide(value) -> Tensor + + See :func:`torch.true_divide` + """ + + def true_divide_( + self, + other: Tensor | Number | torch.SymInt | torch.SymFloat, + ) -> Tensor: + r""" + true_divide_(value) -> Tensor + + In-place version of :meth:`~Tensor.true_divide_` + """ + + def trunc(self) -> Tensor: + r""" + trunc() -> Tensor + + See :func:`torch.trunc` + """ + + def trunc_(self) -> Tensor: + r""" + trunc_() -> Tensor + + In-place version of :meth:`~Tensor.trunc` + """ + + @overload + def type(self, dtype: None = None, non_blocking: _bool = False) -> str: + r""" + type(dtype=None, non_blocking=False, **kwargs) -> str or Tensor + Returns the type if `dtype` is not provided, else casts this object to + the specified type. + + If this is already of the correct type, no copy is performed and the + original object is returned. + + Args: + dtype (dtype or string): The desired type + non_blocking (bool): If ``True``, and the source is in pinned memory + and destination is on the GPU or vice versa, the copy is performed + asynchronously with respect to the host. Otherwise, the argument + has no effect. + **kwargs: For compatibility, may contain the key ``async`` in place of + the ``non_blocking`` argument. The ``async`` arg is deprecated. + """ + + @overload + def type(self, dtype: str | _dtype, non_blocking: _bool = False) -> Tensor: + r""" + type(dtype=None, non_blocking=False, **kwargs) -> str or Tensor + Returns the type if `dtype` is not provided, else casts this object to + the specified type. + + If this is already of the correct type, no copy is performed and the + original object is returned. + + Args: + dtype (dtype or string): The desired type + non_blocking (bool): If ``True``, and the source is in pinned memory + and destination is on the GPU or vice versa, the copy is performed + asynchronously with respect to the host. Otherwise, the argument + has no effect. + **kwargs: For compatibility, may contain the key ``async`` in place of + the ``non_blocking`` argument. The ``async`` arg is deprecated. + """ + + def type_as(self, other: Tensor) -> Tensor: + r""" + type_as(tensor) -> Tensor + + Returns this tensor cast to the type of the given tensor. + + This is a no-op if the tensor is already of the correct type. This is + equivalent to ``self.type(tensor.type())`` + + Args: + tensor (Tensor): the tensor which has the desired type + """ + + @overload + def unbind(self, dim: _int = 0) -> tuple[Tensor, ...]: + r""" + unbind(dim=0) -> seq + + See :func:`torch.unbind` + """ + + @overload + def unbind(self, dim: str | EllipsisType | None) -> tuple[Tensor, ...]: + r""" + unbind(dim=0) -> seq + + See :func:`torch.unbind` + """ + + @overload + def unflatten( + self, + dim: str | EllipsisType | None, + sizes: Sequence[_int | SymInt], + names: Sequence[str | EllipsisType | None], + ) -> Tensor: ... + @overload + def unflatten(self, dim: _int, sizes: Sequence[_int | SymInt]) -> Tensor: ... + def unfold(self, dimension: _int, size: _int, step: _int) -> Tensor: + r""" + unfold(dimension, size, step) -> Tensor + + Returns a view of the original tensor which contains all slices of size :attr:`size` from + :attr:`self` tensor in the dimension :attr:`dimension`. + + Step between two slices is given by :attr:`step`. + + If `sizedim` is the size of dimension :attr:`dimension` for :attr:`self`, the size of + dimension :attr:`dimension` in the returned tensor will be + `(sizedim - size) / step + 1`. + + An additional dimension of size :attr:`size` is appended in the returned tensor. + + Args: + dimension (int): dimension in which unfolding happens + size (int): the size of each slice that is unfolded + step (int): the step between each slice + + Example:: + + >>> x = torch.arange(1., 8) + >>> x + tensor([ 1., 2., 3., 4., 5., 6., 7.]) + >>> x.unfold(0, 2, 1) + tensor([[ 1., 2.], + [ 2., 3.], + [ 3., 4.], + [ 4., 5.], + [ 5., 6.], + [ 6., 7.]]) + >>> x.unfold(0, 2, 2) + tensor([[ 1., 2.], + [ 3., 4.], + [ 5., 6.]]) + """ + + def uniform_( + self, + from_: _float = 0, + to: _float = 1, + *, + generator: Generator | None = None, + ) -> Tensor: + r""" + uniform_(from=0, to=1, *, generator=None) -> Tensor + + Fills :attr:`self` tensor with numbers sampled from the continuous uniform + distribution: + + .. math:: + f(x) = \dfrac{1}{\text{to} - \text{from}} + """ + + def unsafe_chunk(self, chunks: _int, dim: _int = 0) -> tuple[Tensor, ...]: + r""" + unsafe_chunk(chunks, dim=0) -> List of Tensors + + See :func:`torch.unsafe_chunk` + """ + + def unsafe_split( + self, + split_size: _int | SymInt, + dim: _int = 0, + ) -> tuple[Tensor, ...]: + r""" + unsafe_split(split_size, dim=0) -> List of Tensors + + See :func:`torch.unsafe_split` + """ + + def unsafe_split_with_sizes( + self, + split_sizes: Sequence[_int | SymInt], + dim: _int = 0, + ) -> tuple[Tensor, ...]: ... + def unsqueeze(self, dim: _int) -> Tensor: + r""" + unsqueeze(dim) -> Tensor + + See :func:`torch.unsqueeze` + """ + + def unsqueeze_(self, dim: _int) -> Tensor: + r""" + unsqueeze_(dim) -> Tensor + + In-place version of :meth:`~Tensor.unsqueeze` + """ + + def values(self) -> Tensor: + r""" + values() -> Tensor + + Return the values tensor of a :ref:`sparse COO tensor `. + + .. warning:: + Throws an error if :attr:`self` is not a sparse COO tensor. + + See also :meth:`Tensor.indices`. + + .. note:: + This method can only be called on a coalesced sparse tensor. See + :meth:`Tensor.coalesce` for details. + """ + + @overload + def var( + self, + dim: _int | _size | None, + unbiased: _bool = True, + keepdim: _bool = False, + ) -> Tensor: + r""" + var(dim=None, *, correction=1, keepdim=False) -> Tensor + + See :func:`torch.var` + """ + + @overload + def var( + self, + dim: _int | _size | None = None, + *, + correction: Number | _complex | None = None, + keepdim: _bool = False, + ) -> Tensor: + r""" + var(dim=None, *, correction=1, keepdim=False) -> Tensor + + See :func:`torch.var` + """ + + @overload + def var(self, unbiased: _bool = True) -> Tensor: + r""" + var(dim=None, *, correction=1, keepdim=False) -> Tensor + + See :func:`torch.var` + """ + + @overload + def var( + self, + dim: Sequence[str | EllipsisType | None], + unbiased: _bool = True, + keepdim: _bool = False, + ) -> Tensor: + r""" + var(dim=None, *, correction=1, keepdim=False) -> Tensor + + See :func:`torch.var` + """ + + @overload + def var( + self, + dim: Sequence[str | EllipsisType | None], + *, + correction: Number | _complex | None = None, + keepdim: _bool = False, + ) -> Tensor: + r""" + var(dim=None, *, correction=1, keepdim=False) -> Tensor + + See :func:`torch.var` + """ + + def vdot(self, other: Tensor) -> Tensor: + r""" + vdot(other) -> Tensor + + See :func:`torch.vdot` + """ + + @overload + def view(self, dtype: _dtype) -> Tensor: + r""" + view(*shape) -> Tensor + + Returns a new tensor with the same data as the :attr:`self` tensor but of a + different :attr:`shape`. + + The returned tensor shares the same data and must have the same number + of elements, but may have a different size. For a tensor to be viewed, the new + view size must be compatible with its original size and stride, i.e., each new + view dimension must either be a subspace of an original dimension, or only span + across original dimensions :math:`d, d+1, \dots, d+k` that satisfy the following + contiguity-like condition that :math:`\forall i = d, \dots, d+k-1`, + + .. math:: + + \text{stride}[i] = \text{stride}[i+1] \times \text{size}[i+1] + + Otherwise, it will not be possible to view :attr:`self` tensor as :attr:`shape` + without copying it (e.g., via :meth:`contiguous`). When it is unclear whether a + :meth:`view` can be performed, it is advisable to use :meth:`reshape`, which + returns a view if the shapes are compatible, and copies (equivalent to calling + :meth:`contiguous`) otherwise. + + Args: + shape (torch.Size or int...): the desired size + + Example:: + + >>> x = torch.randn(4, 4) + >>> x.size() + torch.Size([4, 4]) + >>> y = x.view(16) + >>> y.size() + torch.Size([16]) + >>> z = x.view(-1, 8) # the size -1 is inferred from other dimensions + >>> z.size() + torch.Size([2, 8]) + + >>> a = torch.randn(1, 2, 3, 4) + >>> a.size() + torch.Size([1, 2, 3, 4]) + >>> b = a.transpose(1, 2) # Swaps 2nd and 3rd dimension + >>> b.size() + torch.Size([1, 3, 2, 4]) + >>> c = a.view(1, 3, 2, 4) # Does not change tensor layout in memory + >>> c.size() + torch.Size([1, 3, 2, 4]) + >>> torch.equal(b, c) + False + + + .. method:: view(dtype) -> Tensor + :noindex: + + Returns a new tensor with the same data as the :attr:`self` tensor but of a + different :attr:`dtype`. + + If the element size of :attr:`dtype` is different than that of ``self.dtype``, + then the size of the last dimension of the output will be scaled + proportionally. For instance, if :attr:`dtype` element size is twice that of + ``self.dtype``, then each pair of elements in the last dimension of + :attr:`self` will be combined, and the size of the last dimension of the output + will be half that of :attr:`self`. If :attr:`dtype` element size is half that + of ``self.dtype``, then each element in the last dimension of :attr:`self` will + be split in two, and the size of the last dimension of the output will be + double that of :attr:`self`. For this to be possible, the following conditions + must be true: + + * ``self.dim()`` must be greater than 0. + * ``self.stride(-1)`` must be 1. + + Additionally, if the element size of :attr:`dtype` is greater than that of + ``self.dtype``, the following conditions must be true as well: + + * ``self.size(-1)`` must be divisible by the ratio between the element + sizes of the dtypes. + * ``self.storage_offset()`` must be divisible by the ratio between the + element sizes of the dtypes. + * The strides of all dimensions, except the last dimension, must be + divisible by the ratio between the element sizes of the dtypes. + + If any of the above conditions are not met, an error is thrown. + + .. warning:: + + This overload is not supported by TorchScript, and using it in a Torchscript + program will cause undefined behavior. + + + Args: + dtype (:class:`torch.dtype`): the desired dtype + + Example:: + + >>> x = torch.randn(4, 4) + >>> x + tensor([[ 0.9482, -0.0310, 1.4999, -0.5316], + [-0.1520, 0.7472, 0.5617, -0.8649], + [-2.4724, -0.0334, -0.2976, -0.8499], + [-0.2109, 1.9913, -0.9607, -0.6123]]) + >>> x.dtype + torch.float32 + + >>> y = x.view(torch.int32) + >>> y + tensor([[ 1064483442, -1124191867, 1069546515, -1089989247], + [-1105482831, 1061112040, 1057999968, -1084397505], + [-1071760287, -1123489973, -1097310419, -1084649136], + [-1101533110, 1073668768, -1082790149, -1088634448]], + dtype=torch.int32) + >>> y[0, 0] = 1000000000 + >>> x + tensor([[ 0.0047, -0.0310, 1.4999, -0.5316], + [-0.1520, 0.7472, 0.5617, -0.8649], + [-2.4724, -0.0334, -0.2976, -0.8499], + [-0.2109, 1.9913, -0.9607, -0.6123]]) + + >>> x.view(torch.cfloat) + tensor([[ 0.0047-0.0310j, 1.4999-0.5316j], + [-0.1520+0.7472j, 0.5617-0.8649j], + [-2.4724-0.0334j, -0.2976-0.8499j], + [-0.2109+1.9913j, -0.9607-0.6123j]]) + >>> x.view(torch.cfloat).size() + torch.Size([4, 2]) + + >>> x.view(torch.uint8) + tensor([[ 0, 202, 154, 59, 182, 243, 253, 188, 185, 252, 191, 63, 240, 22, + 8, 191], + [227, 165, 27, 190, 128, 72, 63, 63, 146, 203, 15, 63, 22, 106, + 93, 191], + [205, 59, 30, 192, 112, 206, 8, 189, 7, 95, 152, 190, 12, 147, + 89, 191], + [ 43, 246, 87, 190, 235, 226, 254, 63, 111, 240, 117, 191, 177, 191, + 28, 191]], dtype=torch.uint8) + >>> x.view(torch.uint8).size() + torch.Size([4, 16]) + """ + + @overload + def view(self, size: Sequence[_int | SymInt]) -> Tensor: + r""" + view(*shape) -> Tensor + + Returns a new tensor with the same data as the :attr:`self` tensor but of a + different :attr:`shape`. + + The returned tensor shares the same data and must have the same number + of elements, but may have a different size. For a tensor to be viewed, the new + view size must be compatible with its original size and stride, i.e., each new + view dimension must either be a subspace of an original dimension, or only span + across original dimensions :math:`d, d+1, \dots, d+k` that satisfy the following + contiguity-like condition that :math:`\forall i = d, \dots, d+k-1`, + + .. math:: + + \text{stride}[i] = \text{stride}[i+1] \times \text{size}[i+1] + + Otherwise, it will not be possible to view :attr:`self` tensor as :attr:`shape` + without copying it (e.g., via :meth:`contiguous`). When it is unclear whether a + :meth:`view` can be performed, it is advisable to use :meth:`reshape`, which + returns a view if the shapes are compatible, and copies (equivalent to calling + :meth:`contiguous`) otherwise. + + Args: + shape (torch.Size or int...): the desired size + + Example:: + + >>> x = torch.randn(4, 4) + >>> x.size() + torch.Size([4, 4]) + >>> y = x.view(16) + >>> y.size() + torch.Size([16]) + >>> z = x.view(-1, 8) # the size -1 is inferred from other dimensions + >>> z.size() + torch.Size([2, 8]) + + >>> a = torch.randn(1, 2, 3, 4) + >>> a.size() + torch.Size([1, 2, 3, 4]) + >>> b = a.transpose(1, 2) # Swaps 2nd and 3rd dimension + >>> b.size() + torch.Size([1, 3, 2, 4]) + >>> c = a.view(1, 3, 2, 4) # Does not change tensor layout in memory + >>> c.size() + torch.Size([1, 3, 2, 4]) + >>> torch.equal(b, c) + False + + + .. method:: view(dtype) -> Tensor + :noindex: + + Returns a new tensor with the same data as the :attr:`self` tensor but of a + different :attr:`dtype`. + + If the element size of :attr:`dtype` is different than that of ``self.dtype``, + then the size of the last dimension of the output will be scaled + proportionally. For instance, if :attr:`dtype` element size is twice that of + ``self.dtype``, then each pair of elements in the last dimension of + :attr:`self` will be combined, and the size of the last dimension of the output + will be half that of :attr:`self`. If :attr:`dtype` element size is half that + of ``self.dtype``, then each element in the last dimension of :attr:`self` will + be split in two, and the size of the last dimension of the output will be + double that of :attr:`self`. For this to be possible, the following conditions + must be true: + + * ``self.dim()`` must be greater than 0. + * ``self.stride(-1)`` must be 1. + + Additionally, if the element size of :attr:`dtype` is greater than that of + ``self.dtype``, the following conditions must be true as well: + + * ``self.size(-1)`` must be divisible by the ratio between the element + sizes of the dtypes. + * ``self.storage_offset()`` must be divisible by the ratio between the + element sizes of the dtypes. + * The strides of all dimensions, except the last dimension, must be + divisible by the ratio between the element sizes of the dtypes. + + If any of the above conditions are not met, an error is thrown. + + .. warning:: + + This overload is not supported by TorchScript, and using it in a Torchscript + program will cause undefined behavior. + + + Args: + dtype (:class:`torch.dtype`): the desired dtype + + Example:: + + >>> x = torch.randn(4, 4) + >>> x + tensor([[ 0.9482, -0.0310, 1.4999, -0.5316], + [-0.1520, 0.7472, 0.5617, -0.8649], + [-2.4724, -0.0334, -0.2976, -0.8499], + [-0.2109, 1.9913, -0.9607, -0.6123]]) + >>> x.dtype + torch.float32 + + >>> y = x.view(torch.int32) + >>> y + tensor([[ 1064483442, -1124191867, 1069546515, -1089989247], + [-1105482831, 1061112040, 1057999968, -1084397505], + [-1071760287, -1123489973, -1097310419, -1084649136], + [-1101533110, 1073668768, -1082790149, -1088634448]], + dtype=torch.int32) + >>> y[0, 0] = 1000000000 + >>> x + tensor([[ 0.0047, -0.0310, 1.4999, -0.5316], + [-0.1520, 0.7472, 0.5617, -0.8649], + [-2.4724, -0.0334, -0.2976, -0.8499], + [-0.2109, 1.9913, -0.9607, -0.6123]]) + + >>> x.view(torch.cfloat) + tensor([[ 0.0047-0.0310j, 1.4999-0.5316j], + [-0.1520+0.7472j, 0.5617-0.8649j], + [-2.4724-0.0334j, -0.2976-0.8499j], + [-0.2109+1.9913j, -0.9607-0.6123j]]) + >>> x.view(torch.cfloat).size() + torch.Size([4, 2]) + + >>> x.view(torch.uint8) + tensor([[ 0, 202, 154, 59, 182, 243, 253, 188, 185, 252, 191, 63, 240, 22, + 8, 191], + [227, 165, 27, 190, 128, 72, 63, 63, 146, 203, 15, 63, 22, 106, + 93, 191], + [205, 59, 30, 192, 112, 206, 8, 189, 7, 95, 152, 190, 12, 147, + 89, 191], + [ 43, 246, 87, 190, 235, 226, 254, 63, 111, 240, 117, 191, 177, 191, + 28, 191]], dtype=torch.uint8) + >>> x.view(torch.uint8).size() + torch.Size([4, 16]) + """ + + @overload + def view(self, *size: _int | SymInt) -> Tensor: + r""" + view(*shape) -> Tensor + + Returns a new tensor with the same data as the :attr:`self` tensor but of a + different :attr:`shape`. + + The returned tensor shares the same data and must have the same number + of elements, but may have a different size. For a tensor to be viewed, the new + view size must be compatible with its original size and stride, i.e., each new + view dimension must either be a subspace of an original dimension, or only span + across original dimensions :math:`d, d+1, \dots, d+k` that satisfy the following + contiguity-like condition that :math:`\forall i = d, \dots, d+k-1`, + + .. math:: + + \text{stride}[i] = \text{stride}[i+1] \times \text{size}[i+1] + + Otherwise, it will not be possible to view :attr:`self` tensor as :attr:`shape` + without copying it (e.g., via :meth:`contiguous`). When it is unclear whether a + :meth:`view` can be performed, it is advisable to use :meth:`reshape`, which + returns a view if the shapes are compatible, and copies (equivalent to calling + :meth:`contiguous`) otherwise. + + Args: + shape (torch.Size or int...): the desired size + + Example:: + + >>> x = torch.randn(4, 4) + >>> x.size() + torch.Size([4, 4]) + >>> y = x.view(16) + >>> y.size() + torch.Size([16]) + >>> z = x.view(-1, 8) # the size -1 is inferred from other dimensions + >>> z.size() + torch.Size([2, 8]) + + >>> a = torch.randn(1, 2, 3, 4) + >>> a.size() + torch.Size([1, 2, 3, 4]) + >>> b = a.transpose(1, 2) # Swaps 2nd and 3rd dimension + >>> b.size() + torch.Size([1, 3, 2, 4]) + >>> c = a.view(1, 3, 2, 4) # Does not change tensor layout in memory + >>> c.size() + torch.Size([1, 3, 2, 4]) + >>> torch.equal(b, c) + False + + + .. method:: view(dtype) -> Tensor + :noindex: + + Returns a new tensor with the same data as the :attr:`self` tensor but of a + different :attr:`dtype`. + + If the element size of :attr:`dtype` is different than that of ``self.dtype``, + then the size of the last dimension of the output will be scaled + proportionally. For instance, if :attr:`dtype` element size is twice that of + ``self.dtype``, then each pair of elements in the last dimension of + :attr:`self` will be combined, and the size of the last dimension of the output + will be half that of :attr:`self`. If :attr:`dtype` element size is half that + of ``self.dtype``, then each element in the last dimension of :attr:`self` will + be split in two, and the size of the last dimension of the output will be + double that of :attr:`self`. For this to be possible, the following conditions + must be true: + + * ``self.dim()`` must be greater than 0. + * ``self.stride(-1)`` must be 1. + + Additionally, if the element size of :attr:`dtype` is greater than that of + ``self.dtype``, the following conditions must be true as well: + + * ``self.size(-1)`` must be divisible by the ratio between the element + sizes of the dtypes. + * ``self.storage_offset()`` must be divisible by the ratio between the + element sizes of the dtypes. + * The strides of all dimensions, except the last dimension, must be + divisible by the ratio between the element sizes of the dtypes. + + If any of the above conditions are not met, an error is thrown. + + .. warning:: + + This overload is not supported by TorchScript, and using it in a Torchscript + program will cause undefined behavior. + + + Args: + dtype (:class:`torch.dtype`): the desired dtype + + Example:: + + >>> x = torch.randn(4, 4) + >>> x + tensor([[ 0.9482, -0.0310, 1.4999, -0.5316], + [-0.1520, 0.7472, 0.5617, -0.8649], + [-2.4724, -0.0334, -0.2976, -0.8499], + [-0.2109, 1.9913, -0.9607, -0.6123]]) + >>> x.dtype + torch.float32 + + >>> y = x.view(torch.int32) + >>> y + tensor([[ 1064483442, -1124191867, 1069546515, -1089989247], + [-1105482831, 1061112040, 1057999968, -1084397505], + [-1071760287, -1123489973, -1097310419, -1084649136], + [-1101533110, 1073668768, -1082790149, -1088634448]], + dtype=torch.int32) + >>> y[0, 0] = 1000000000 + >>> x + tensor([[ 0.0047, -0.0310, 1.4999, -0.5316], + [-0.1520, 0.7472, 0.5617, -0.8649], + [-2.4724, -0.0334, -0.2976, -0.8499], + [-0.2109, 1.9913, -0.9607, -0.6123]]) + + >>> x.view(torch.cfloat) + tensor([[ 0.0047-0.0310j, 1.4999-0.5316j], + [-0.1520+0.7472j, 0.5617-0.8649j], + [-2.4724-0.0334j, -0.2976-0.8499j], + [-0.2109+1.9913j, -0.9607-0.6123j]]) + >>> x.view(torch.cfloat).size() + torch.Size([4, 2]) + + >>> x.view(torch.uint8) + tensor([[ 0, 202, 154, 59, 182, 243, 253, 188, 185, 252, 191, 63, 240, 22, + 8, 191], + [227, 165, 27, 190, 128, 72, 63, 63, 146, 203, 15, 63, 22, 106, + 93, 191], + [205, 59, 30, 192, 112, 206, 8, 189, 7, 95, 152, 190, 12, 147, + 89, 191], + [ 43, 246, 87, 190, 235, 226, 254, 63, 111, 240, 117, 191, 177, 191, + 28, 191]], dtype=torch.uint8) + >>> x.view(torch.uint8).size() + torch.Size([4, 16]) + """ + + def view_as(self, other: Tensor) -> Tensor: + r""" + view_as(other) -> Tensor + + View this tensor as the same size as :attr:`other`. + ``self.view_as(other)`` is equivalent to ``self.view(other.size())``. + + Please see :meth:`~Tensor.view` for more information about ``view``. + + Args: + other (:class:`torch.Tensor`): The result tensor has the same size + as :attr:`other`. + """ + + @overload + def vsplit(self, sections: _int) -> tuple[Tensor, ...]: + r""" + vsplit(split_size_or_sections) -> List of Tensors + + See :func:`torch.vsplit` + """ + + @overload + def vsplit(self, indices: _size) -> tuple[Tensor, ...]: + r""" + vsplit(split_size_or_sections) -> List of Tensors + + See :func:`torch.vsplit` + """ + + @overload + def vsplit(self, *indices: _int) -> tuple[Tensor, ...]: + r""" + vsplit(split_size_or_sections) -> List of Tensors + + See :func:`torch.vsplit` + """ + + @overload + def where(self, condition: Tensor, other: Tensor) -> Tensor: + r""" + where(condition, y) -> Tensor + + ``self.where(condition, y)`` is equivalent to ``torch.where(condition, self, y)``. + See :func:`torch.where` + """ + + @overload + def where(self, condition: Tensor, other: Number | _complex) -> Tensor: + r""" + where(condition, y) -> Tensor + + ``self.where(condition, y)`` is equivalent to ``torch.where(condition, self, y)``. + See :func:`torch.where` + """ + + @overload + def xlogy(self, other: Tensor) -> Tensor: + r""" + xlogy(other) -> Tensor + + See :func:`torch.xlogy` + """ + + @overload + def xlogy(self, other: Number | _complex) -> Tensor: + r""" + xlogy(other) -> Tensor + + See :func:`torch.xlogy` + """ + + @overload + def xlogy_(self, other: Tensor) -> Tensor: + r""" + xlogy_(other) -> Tensor + + In-place version of :meth:`~Tensor.xlogy` + """ + + @overload + def xlogy_(self, other: Number | _complex) -> Tensor: + r""" + xlogy_(other) -> Tensor + + In-place version of :meth:`~Tensor.xlogy` + """ + + def xpu( + self, + device: _device | _int | str | None = None, + non_blocking: _bool = False, + memory_format: torch.memory_format = torch.preserve_format, + ) -> Tensor: + r""" + xpu(device=None, non_blocking=False, memory_format=torch.preserve_format) -> Tensor + + Returns a copy of this object in XPU memory. + + If this object is already in XPU memory and on the correct device, + then no copy is performed and the original object is returned. + + Args: + device (:class:`torch.device`, optional): The destination XPU device. + Defaults to the current XPU device. + non_blocking (bool, optional): If ``True`` and the source is in pinned memory, + the copy will be asynchronous with respect to the host. + Otherwise, the argument has no effect. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + + def zero_(self) -> Tensor: + r""" + zero_() -> Tensor + + Fills :attr:`self` tensor with zeros. + """ + +_TensorBase = TensorBase + +def _DTensor_OpSchema_post_init(self: OpSchema) -> None: ... +def _DTensor_OpSchema_recompute_comparison_key(self: OpSchema) -> None: ... +def _DTensor_compute_global_tensor_info( + tensor: Tensor, mesh: DeviceMesh, placements: Sequence[Placement] +) -> tuple[list[_int], list[_int]]: ... +def _get_DTensor_sharding_propagator_cache_stats() -> tuple[_int, _int]: ... +def _clear_DTensor_sharding_propagator_cache() -> None: ... + +# Defined in torch/csrc/multiprocessing/init.cpp +def _multiprocessing_init() -> None: ... +def _set_thread_name(name: str) -> None: ... +def _get_thread_name() -> str: ... + +# Defined in torch/csrc/Module.cpp +def _accelerator_hooks_device_count() -> _int: ... +def _accelerator_hooks_set_current_device(device_index: _int) -> None: ... +def _accelerator_hooks_get_current_device() -> _int: ... +def _accelerator_hooks_exchange_device(device_index: _int) -> _int: ... +def _accelerator_hooks_maybe_exchange_device(device_index: _int) -> _int: ... +def _get_accelerator(check: _bool = False) -> _device: ... +def _storage_Use_Count(storage_ptr: _int) -> _int: ... + +# Defined in torch/csrc/mtia/Module.cpp +def _mtia_init() -> None: ... +def _mtia_isBuilt() -> _bool: ... +def _mtia_isInBadFork() -> _bool: ... +def _mtia_deviceSynchronize() -> None: ... +def _mtia_getCurrentStream(device: _int) -> Stream: ... +def _mtia_getCurrentRawStream(device: _int) -> _int: ... +def _mtia_setCurrentStream(stream: Stream) -> None: ... +def _mtia_getDefaultStream(device: _int) -> Stream: ... +def _mtia_setStream(stream_id: _int, device_index: _int, device_type: _int) -> None: ... +def _mtia_memoryStats(device: _int) -> dict[str, Any]: ... +def _mtia_getDeviceCapability(device: _int) -> tuple[_int, _int]: ... +def _mtia_getDeviceProperties(device: _int) -> dict[str, Any]: ... +def _mtia_emptyCache() -> None: ... +def _mtia_recordMemoryHistory( + enabled: str | None, + stacks: str, + max_entries, +) -> None: ... +def _mtia_memorySnapshot() -> dict[str, Any]: ... +def _mtia_attachOutOfMemoryObserver( + observer: Callable[[_int, _int, _int, _int], None], +) -> None: ... +def _mtia_getDeviceCount() -> _int: ... +def _mtia_resetPeakMemoryStats(device: _int) -> None: ... +def _mtia_graphPoolHandle() -> tuple[_int, _int]: ... + +# Defined in torch/csrc/mtia/Module.cpp +class _MTIAGraph: + def __new__(cls, keep_graph: _bool = ...) -> Self: ... + def capture_begin(self, pool: tuple[_int, _int]) -> None: ... + def capture_end(self) -> None: ... + def instantiate(self) -> None: ... + def replay(self) -> None: ... + def reset(self) -> None: ... + def pool(self) -> tuple[_int, _int]: ... + +# Defined in torch/csrc/mps/Module.cpp +def _mps_deviceSynchronize() -> None: ... +def _mps_get_core_count() -> _int: ... +def _mps_get_default_generator() -> Generator: ... +def _mps_get_name() -> _str: ... +def _mps_emptyCache() -> None: ... +def _mps_setMemoryFraction(fraction: _float) -> None: ... +def _mps_currentAllocatedMemory() -> _int: ... +def _mps_driverAllocatedMemory() -> _int: ... +def _mps_recommendedMaxMemory() -> _int: ... +def _mps_is_available() -> _bool: ... +def _mps_is_on_macos_or_newer(major: _int, minor: _int) -> _bool: ... +def _mps_profilerStartTrace(mode: str, wait_until_completed: _bool) -> None: ... +def _mps_profilerStopTrace() -> None: ... +def _mps_acquireEvent(enable_timing: _bool) -> _int: ... +def _mps_releaseEvent(event_id: _int) -> None: ... +def _mps_recordEvent(event_id: _int) -> None: ... +def _mps_waitForEvent(event_id: _int) -> None: ... +def _mps_synchronizeEvent(event_id: _int) -> None: ... +def _mps_queryEvent(event_id: _int) -> _bool: ... +def _mps_elapsedTimeOfEvents(start_event_id: _int, end_event_id: _int) -> _float: ... +def _mps_isCaptureEnabled() -> _bool: ... +def _mps_isCapturing() -> _bool: ... +def _mps_startCapture(name: str) -> None: ... +def _mps_stopCapture() -> None: ... + +# Defined in torch/csrc/cuda/Module.cpp +def _cuda_getCurrentStream(device: _int) -> tuple: ... +def _cuda_getCurrentRawStream(device: _int) -> _int: ... +def _cuda_getDefaultStream(device: _int) -> tuple: ... +def _cuda_getStreamFromExternal(data_ptr: _int, device_index: _int) -> tuple: ... +def _cuda_getCurrentBlasHandle() -> _int: ... +def _cuda_clearCublasWorkspaces() -> None: ... +def _cuda_setDevice(device: _int) -> None: ... +def _cuda_exchangeDevice(device: _int) -> _int: ... +def _cuda_maybeExchangeDevice(device: _int) -> _int: ... +def _cuda_getDevice() -> _int: ... +def _cuda_getDeviceCount() -> _int: ... +def _cuda_set_sync_debug_mode(warn_level: _int | str) -> None: ... +def _cuda_get_sync_debug_mode() -> _int: ... +def _cuda_sleep(cycles: _int) -> None: ... +def _cuda_busy_wait_for_flag() -> None: ... +def _cuda_clear_flag() -> None: ... +def _cuda_synchronize() -> None: ... +def _cuda_ipc_collect() -> None: ... +def _cuda_getArchFlags() -> str | None: ... +def _cuda_init() -> None: ... +def _cuda_setStream(stream_id: _int, device_index: _int, device_type: _int) -> None: ... +def _cuda_getCompiledVersion() -> _int: ... +def _cuda_cudaHostAllocator() -> _int: ... +def _cuda_cudaCachingAllocator_raw_alloc(size: _int, cuda_stream: _int) -> _int: ... +def _cuda_cudaCachingAllocator_raw_delete(ptr: _int) -> None: ... +def _cuda_cudaCachingAllocator_enable(val: _bool) -> None: ... +def _cuda_beginAllocateToPool(device: _int, mempool_id: tuple[_int, _int]) -> None: ... +def _cuda_beginAllocateCurrentThreadToPool( + device: _int, + mempool_id: tuple[_int, _int], +) -> None: ... +def _cuda_endAllocateToPool(device: _int, mempool_id: tuple[_int, _int]) -> None: ... +def _cuda_beginAllocateCurrentStreamToPool( + device: _int, + mempool_id: tuple[_int, _int], +) -> None: ... +def _cuda_releasePool(device: _int, mempool_id: tuple[_int, _int]) -> None: ... +def _cuda_checkPoolLiveAllocations( + device: _int, + mempool_id: tuple[_int, _int], + expected_live_allocations: set, +) -> _bool: ... +def _cuda_setCheckpointPoolState( + device: _int, + state: _cuda_CUDAAllocator_AllocatorState, + stale_storages: list[_int], + storages_to_add_deleters_to: list[_int], +) -> None: ... +def _cuda_getMemoryFraction(device: _int) -> _float: ... +def _cuda_setMemoryFraction(fraction: _float, device: _int) -> None: ... +def _cuda_emptyCache() -> None: ... +def _cuda_memoryStats(device: _int) -> dict[str, Any]: ... +def _cuda_resetAccumulatedMemoryStats(device: _int) -> None: ... +def _cuda_resetPeakMemoryStats(device: _int) -> None: ... +def _cuda_hostMemoryStats() -> dict[str, Any]: ... +def _cuda_resetAccumulatedHostMemoryStats() -> None: ... +def _cuda_resetPeakHostMemoryStats() -> None: ... +def _cuda_memorySnapshot(mempool_id: tuple[_int, _int] | None) -> dict[str, Any]: ... +def _cuda_setMemoryMetadata(metadata: str) -> None: ... +def _cuda_getMemoryMetadata() -> str: ... +def _cuda_record_memory_history_legacy( + enabled: _bool, + record_context: _bool, + record_context_cpp: _bool, + alloc_trace_max_entries: _int, + alloc_trace_record_context: _bool, + clear_history: _bool, + compile_context: _bool, + global_record_annotations: _bool, +) -> None: ... +def _cuda_record_memory_history( + enabled: str | None, + context: str | None, + stacks: str, + max_entries: _int, + clear_history: _bool, + compile_context: _bool, + global_record_annotations: _bool, +) -> None: ... +def _cuda_isHistoryEnabled() -> _bool: ... +def _cuda_getAllocatorBackend() -> str: ... + +class _cuda_CUDAAllocator_AllocatorState: ... + +def _cuda_getCheckpointState( + device: _int, + mempool: tuple[_int, _int], +) -> _cuda_CUDAAllocator_AllocatorState: ... +def _set_cached_tensors_enabled(enabled: _bool) -> None: ... +def _add_cached_tensor(t: Tensor) -> None: ... +def _remove_cached_tensor(t: Tensor) -> None: ... +def _tensors_data_ptrs_at_indices_equal( + tensors: list[Tensor | _int], + ptrs: list[_int | None], + indices: list[_int], +) -> _bool: ... +def _construct_CUDA_Tensor_From_Storage_And_Metadata( + metadata: dict, + storage: Storage, +) -> Tensor: ... +def _set_storage_access_error_msg(t: Tensor, s: str) -> None: ... +def _set_storage_data_ptr_access_error_msg(storage_ptr: _int, s: str) -> None: ... +def _free_And_Remove_DeleterFn(storage_ptr: _int) -> None: ... +def _has_Standard_Deleter(storage_ptr: _int) -> _bool: ... + +class _cuda_CUDAAllocator: ... + +def _cuda_customAllocator(alloc_fn: _int, free_fn: _int) -> _cuda_CUDAAllocator: ... +def _cuda_changeCurrentAllocator(allocator: _cuda_CUDAAllocator) -> None: ... +def _cuda_getAllocator() -> _cuda_CUDAAllocator: ... +def _cuda_lock_mutex() -> None: ... +def _cuda_unlock_mutex() -> None: ... +def _cuda_canDeviceAccessPeer(device: _int, peer_device: _int) -> _bool: ... +def _cuda_jiterator_compile_and_launch_kernel( + code_string: str, + kernel_name: str, + return_by_ref: _bool, + num_outputs: _int, + tensors: tuple, + kwargs: dict[str, _int | _float | _bool], +) -> Tensor: ... +def _cuda_get_cudnn_benchmark_limit() -> _int: ... +def _cuda_set_cudnn_benchmark_limit(arg: _int) -> None: ... +def _cuda_get_conv_benchmark_empty_cache() -> _bool: ... +def _cudnn_set_conv_benchmark_empty_cache(enable: _bool) -> None: ... +def _nccl_version() -> _int: ... +def _nccl_version_suffix() -> bytes: ... +def _nccl_unique_id() -> bytes: ... +def _nccl_init_rank(nranks: _int, comm_id: bytes, rank: _int) -> object: ... +def _nccl_reduce( + input: Sequence[Tensor], + output: Tensor, + root: _int, + op: _int, + streams: Sequence[_CudaStreamBase] | None, + comms: Sequence[object] | None, +) -> None: ... +def _nccl_all_reduce( + input: Sequence[Tensor], + output: Sequence[Tensor], + op: _int, + streams: Sequence[_CudaStreamBase] | None, + comms: Sequence[object] | None, +) -> None: ... +def _nccl_broadcast( + input: Sequence[Tensor], + root: _int, + streams: Sequence[_CudaStreamBase] | None, + comms: Sequence[object] | None, +) -> None: ... +def _nccl_all_gather( + input: Sequence[Tensor], + output: Sequence[Tensor], + streams: Sequence[_CudaStreamBase] | None, + comms: Sequence[object] | None, +) -> None: ... +def _nccl_reduce_scatter( + input: Sequence[Tensor], + output: Sequence[Tensor], + op: _int, + streams: Sequence[_CudaStreamBase] | None, + comms: Sequence[object] | None, +) -> None: ... +def _rocm_is_backward_pass() -> _bool: ... +def _cuda_tunableop_enable(val: _bool) -> None: ... +def _cuda_tunableop_is_enabled() -> _bool: ... +def _cuda_tunableop_tuning_enable(val: _bool) -> None: ... +def _cuda_tunableop_tuning_is_enabled() -> _bool: ... +def _cuda_tunableop_set_max_tuning_duration(duration: _int) -> None: ... +def _cuda_tunableop_get_max_tuning_duration() -> _int: ... +def _cuda_tunableop_set_max_tuning_iterations(iterations: _int) -> None: ... +def _cuda_tunableop_get_max_tuning_iterations() -> _int: ... +def _cuda_tunableop_set_filename( + filename: str, + insert_device_ordinal: _bool | None, +) -> None: ... +def _cuda_tunableop_get_filename() -> str: ... +def _cuda_tunableop_read_file(filename: str | None) -> _bool: ... +def _cuda_tunableop_get_results() -> tuple[str, str, str, _float]: ... +def _cuda_tunableop_get_validators() -> tuple[str, str]: ... +def _cuda_tunableop_set_rotating_buffer_size(buffer_size: _int) -> None: ... +def _cuda_tunableop_get_rotation_buffer_size() -> _int: ... +def _cuda_tunableop_set_numerical_check_tolerances( + enabled: _bool, atol: _float = 1e-5, rtol: _float = 1e-5 +) -> None: ... + +class _CudaDeviceProperties: + name: str + major: _int + minor: _int + multi_processor_count: _int + total_memory: _int + is_integrated: _int + is_multi_gpu_board: _int + max_threads_per_multi_processor: _int + gcnArchName: str + warp_size: _int + uuid: str + L2_cache_size: _int + clock_rate: _int + memory_clock_rate: _int + memory_bus_width: _int + shared_memory_per_block: _int + +# Functions related to SDPA +class _SDPAParams: + query: Tensor + key: Tensor + value: Tensor + attn_mask: Tensor | None + dropout: _float + is_causal: _bool + enable_gqa: _bool + def __init__( + self, + query: Tensor, + key: Tensor, + value: Tensor, + attn_mask: Tensor | None, + dropout: _float, + is_causal: _bool, + enable_gqa: _bool, + ) -> None: ... + +class _SDPBackend(Enum): + ERROR = -1 + MATH = 0 + FLASH_ATTENTION = 1 + EFFICIENT_ATTENTION = 2 + CUDNN_ATTENTION = 3 + OVERRIDEABLE = 4 + +def _is_flash_attention_available() -> _bool: ... +def _can_use_cudnn_attention(params: _SDPAParams, debug: _bool) -> _bool: ... +def _can_use_flash_attention(params: _SDPAParams, debug: _bool) -> _bool: ... +def _can_use_mem_efficient_attention(params: _SDPAParams, debug: _bool) -> _bool: ... + +# Defined in torch/csrc/cuda/GdsFile.cpp +def _gds_register_buffer(t: Storage) -> None: ... +def _gds_deregister_buffer(t: Storage) -> None: ... +def _gds_register_handle(fd: _int) -> _int: ... +def _gds_deregister_handle(handle: _int) -> None: ... +def _gds_load_storage(handle: _int, s: Storage, offset: _int) -> None: ... +def _gds_save_storage(handle: _int, s: Storage, offset: _int) -> None: ... + +# Defined in torch/csrc/cuda/python_comm.cpp +def _broadcast(tensor: Tensor, devices: list[_int]) -> list[Tensor]: ... +def _broadcast_out(tensor: Tensor, out_tensors: list[Tensor]) -> list[Tensor]: ... +def _broadcast_coalesced( + tensors: list[Tensor], + devices: list[_int], + buffer_size: _int, +) -> list[list[Tensor]]: ... +def _scatter( + tensor: Tensor, + devices: list[_int], + chunk_sizes: list[_int] | None, + dim: _int, + streams: list[Stream] | None, +) -> list[Tensor]: ... +def _scatter_out( + tensor: Tensor, + out_tensors: list[Tensor], + dim: _int, + streams: list[Stream] | None, +) -> list[Tensor]: ... +def _gather( + tensors: list[Tensor], + dim: _int, + destination_index: _int | None, +) -> Tensor: ... +def _gather_out(tensors: list[Tensor], out_tensor: Tensor, dim: _int) -> Tensor: ... + +# Defined in torch/csrc/cuda/Stream.cpp +class _CudaStreamBase(Stream): + stream_id: _int + device_index: _int + device_type: _int + + device: _device + cuda_stream: _int + priority: _int + + def __new__( + cls, + priority: _int = 0, + stream_id: _int = 0, + device_index: _int = 0, + stream_ptr: _int = 0, + ) -> Self: ... + def query(self) -> _bool: ... + def synchronize(self) -> None: ... + def priority_range(self) -> tuple[_int, _int]: ... + +# Defined in torch/csrc/cuda/Event.cpp +class _CudaEventBase: + device: _device + cuda_event: _int + + def __new__( + cls, + enable_timing: _bool = False, + blocking: _bool = False, + interprocess: _bool = False, + external: _bool = False, + ) -> Self: ... + @classmethod + def from_ipc_handle(cls, device: _device, ipc_handle: bytes) -> _CudaEventBase: ... + def record(self, stream: _CudaStreamBase) -> None: ... + def wait(self, stream: _CudaStreamBase) -> None: ... + def query(self) -> _bool: ... + def elapsed_time(self, other: _CudaEventBase) -> _float: ... + def synchronize(self) -> None: ... + def ipc_handle(self) -> bytes: ... + +# Defined in torch/csrc/cuda/Graph.cpp +class _CUDAGraph: + def __new__(cls, keep_graph: _bool = ...) -> Self: ... + def capture_begin( + self, + pool: _POOL_HANDLE | None = ..., + capture_error_mode: str = "global", + ) -> None: ... + def capture_end(self) -> None: ... + def instantiate(self) -> None: ... + def register_generator_state(self, Generator) -> None: ... + def replay(self) -> None: ... + def reset(self) -> None: ... + def pool(self) -> _POOL_HANDLE: ... + def enable_debug_mode(self) -> None: ... + def debug_dump(self, debug_path: str) -> None: ... + def raw_cuda_graph(self) -> _int: ... + def raw_cuda_graph_exec(self) -> _int: ... + +# Defined in torch/csrc/cuda/MemPool.cpp +class _MemPool: + def __init__( + self, + allocator: _cuda_CUDAAllocator | None = None, + is_user_created: _bool = True, + use_on_oom: _bool = False, + no_split: _bool = False, + ) -> None: ... + @property + def id(self) -> tuple[_int, _int]: ... + @property + def allocator(self) -> _cuda_CUDAAllocator | None: ... + def use_count(self) -> _int: ... + +def _cuda_isCurrentStreamCapturing() -> _bool: ... +def _graph_pool_handle() -> tuple[_int, _int]: ... + +# Defined in torch/csrc/xpu/Module.cpp +def _xpu_setDevice(device: _int) -> None: ... +def _xpu_exchangeDevice(device: _int) -> _int: ... +def _xpu_maybeExchangeDevice(device: _int) -> _int: ... +def _xpu_getDevice() -> _int: ... +def _xpu_getDeviceCount() -> _int: ... +def _xpu_getArchFlags() -> str | None: ... +def _xpu_init() -> None: ... +def _xpu_setStream(stream_id: _int, device_index: _int, device_type: _int) -> None: ... +def _xpu_getCurrentStream(device: _int) -> tuple: ... +def _xpu_getCurrentRawStream(device: _int) -> _int: ... +def _xpu_getStreamFromExternal(data_ptr: _int, device_index: _int) -> tuple: ... +def _xpu_synchronize(device: _int) -> None: ... +def _xpu_emptyCache() -> None: ... +def _xpu_memoryStats(device: _int) -> dict[str, Any]: ... +def _xpu_resetAccumulatedMemoryStats(device: _int) -> None: ... +def _xpu_resetPeakMemoryStats(device: _int) -> None: ... +def _xpu_getMemoryInfo(device: _int) -> tuple[_int, _int]: ... +def _xpu_canDeviceAccessPeer(device: _int, peer: _int) -> _bool: ... +def _xpu_getMemoryFraction(device: _int) -> _float: ... +def _xpu_setMemoryFraction(fraction: _float, device: _int) -> None: ... + +class _XpuDeviceProperties: + name: str + platform_name: str + vendor: str + device_id: _int + driver_version: str + version: str + max_compute_units: _int + gpu_eu_count: _int + max_work_group_size: _int + max_num_sub_groups: _int + sub_group_sizes: list[_int] + has_fp16: _bool + has_fp64: _bool + has_atomic64: _bool + has_bfloat16_conversions: _bool + has_subgroup_matrix_multiply_accumulate: _bool + has_subgroup_matrix_multiply_accumulate_tensor_float32: _bool + has_subgroup_2d_block_io: _bool + total_memory: _int + gpu_subslice_count: _int + architecture: _int + type: str + uuid: Any + +class _xpu_XPUAllocator: ... + +def _xpu_customAllocator(alloc_fn: _int, free_fn: _int) -> _xpu_XPUAllocator: ... +def _xpu_changeCurrentAllocator(allocator: _xpu_XPUAllocator) -> None: ... +def _xpu_getAllocator() -> _xpu_XPUAllocator: ... + +# Defined in torch/csrc/xpu/Stream.cpp +class _XpuStreamBase(Stream): + stream_id: _int + device_index: _int + device_type: _int + + device: _device + sycl_queue: _int + priority: _int + + def __new__( + cls, + priority: _int = 0, + stream_id: _int = 0, + device_index: _int = 0, + device_type: _int = 0, + ) -> Self: ... + def query(self) -> _bool: ... + def synchronize(self) -> None: ... + @staticmethod + def priority_range() -> tuple: ... + +# Defined in torch/csrc/xpu/Event.cpp +class _XpuEventBase: + device: _device + sycl_event: _int + + def __new__(cls, enable_timing: _bool = False) -> Self: ... + def record(self, stream: _XpuEventBase) -> None: ... + def wait(self, stream: _XpuStreamBase) -> None: ... + def query(self) -> _bool: ... + def elapsed_time(self, other: _XpuEventBase) -> _float: ... + def synchronize(self) -> None: ... + +# Defined in torch/csrc/DataLoader.cpp +def _set_worker_signal_handlers( + *arg: Any, +) -> None: ... # THPModule_setWorkerSignalHandlers +def _set_worker_pids( + key: _int, + child_pids: tuple[_int, ...], +) -> None: ... # THPModule_setWorkerPIDs +def _remove_worker_pids(loader_id: _int) -> None: ... # THPModule_removeWorkerPIDs +def _error_if_any_worker_fails() -> None: ... # THPModule_errorIfAnyWorkerFails + +# Defined in torch/csrc/DeviceAccelerator.cpp +def _accelerator_getAccelerator() -> _device: ... +def _accelerator_setDeviceIndex(device_index: _int) -> None: ... +def _accelerator_getDeviceIndex() -> _int: ... +def _accelerator_getDeviceCapability(device_index: _int) -> dict[str, Any]: ... +def _accelerator_setStream(Stream) -> None: ... +def _accelerator_getStream(device_index: _int) -> Stream: ... +def _accelerator_synchronizeDevice(device_index: _int) -> None: ... +def _accelerator_exchangeDevice(device_index: _int) -> _int: ... +def _accelerator_maybeExchangeDevice(device_index: _int) -> _int: ... +def _accelerator_isAllocatorInitialized() -> _bool: ... +def _accelerator_emptyCache() -> None: ... +def _accelerator_getDeviceStats(device_index: _int) -> dict[str, Any]: ... +def _accelerator_resetAccumulatedStats(device_index: _int) -> None: ... +def _accelerator_resetPeakStats(device_index: _int) -> None: ... +def _accelerator_getMemoryInfo(device_index: _int) -> tuple[_int, _int]: ... +def _accelerator_setAllocatorSettings(env: str) -> None: ... + +# Defined in torch/csrc/jit/python/python_tracer.cpp +class TracingState: + def push_scope(self, scope_name: str) -> None: ... + def pop_scope(self) -> None: ... + def current_scope(self) -> str: ... + def set_graph(self, graph: Graph) -> None: ... + def graph(self) -> Graph: ... + +def _create_graph_by_tracing( + func: Callable[..., Any], + inputs: Any, + var_name_lookup_fn: Callable[[Tensor], str], + strict: Any, + force_outplace: Any, + self: Any = None, + argument_names: list[str] = ..., +) -> tuple[Graph, Stack]: ... +def _tracer_warn_use_python(): ... +def _get_tracing_state() -> TracingState: ... + +# Defined in torch/csrc/jit/python/python_ir.cpp +# Not actually defined in python_ir.cpp, not sure where they are. +class IValue: ... + +Stack: TypeAlias = list[IValue] + +class JitType: + annotation_str: str + def isSubtypeOf(self, other: JitType) -> _bool: ... + def with_dtype(self, dtype: _dtype) -> JitType: ... + def with_sizes(self, sizes: list[_int | None]) -> JitType: ... + def kind(self) -> str: ... + def scalarType(self) -> str | None: ... + def getElementType(self) -> JitType: ... + def dtype(self) -> _dtype | None: ... + +class InferredType: + def __init__(self, arg: JitType | str) -> None: ... + def type(self) -> JitType: ... + def success(self) -> _bool: ... + def reason(self) -> str: ... + +class Type(JitType): + def str(self) -> _str: ... + def containedTypes(self) -> list[JitType]: ... + def dim(self) -> _int | None: ... + def undefined(self) -> _bool | None: ... + def sizes(self) -> list[_int] | None: ... + def symbol_sizes(self) -> list[_int] | None: ... + def varyingSizes(self) -> list[_int | None] | None: ... + def strides(self) -> list[_int] | None: ... + def contiguous(self) -> Self: ... + def device(self) -> _device | None: ... + def is_interface_type(self) -> _bool: ... + def requires_grad(self) -> _bool: ... + @property + def annotation_string(self) -> _str: ... + +class AnyType(JitType): + @staticmethod + def get() -> AnyType: ... + +class NoneType(JitType): + @staticmethod + def get() -> NoneType: ... + +class BoolType(JitType): + @staticmethod + def get() -> BoolType: ... + +class FloatType(JitType): + @staticmethod + def get() -> FloatType: ... + +class ComplexType(JitType): + @staticmethod + def get() -> ComplexType: ... + +class IntType(JitType): + @staticmethod + def get() -> IntType: ... + +class SymIntType(JitType): + @staticmethod + def get() -> SymIntType: ... + +class SymBoolType(JitType): + @staticmethod + def get() -> SymBoolType: ... + +class NumberType(JitType): + @staticmethod + def get() -> NumberType: ... + +class StringType(JitType): + @staticmethod + def get() -> StringType: ... + +class DeviceObjType(JitType): + @staticmethod + def get() -> DeviceObjType: ... + +class _GeneratorType(JitType): + @staticmethod + def get() -> _GeneratorType: ... + +class StreamObjType(JitType): + @staticmethod + def get() -> StreamObjType: ... + +class ListType(JitType): + def __init__(self, a: JitType) -> None: ... + def getElementType(self) -> JitType: ... + @staticmethod + def ofInts() -> ListType: ... + @staticmethod + def ofTensors() -> ListType: ... + @staticmethod + def ofFloats() -> ListType: ... + @staticmethod + def ofComplexDoubles() -> ListType: ... + @staticmethod + def ofBools() -> ListType: ... + @staticmethod + def ofStrings() -> ListType: ... + +class DictType(JitType): + def __init__(self, key: JitType, value: JitType) -> None: ... + def getKeyType(self) -> JitType: ... + def getValueType(self) -> JitType: ... + +class TupleType(JitType): + def __init__(self, a: list[JitType | None]) -> None: ... + def elements(self) -> list[JitType]: ... + +class UnionType(JitType): + def __init__(self, a: list[JitType]) -> None: ... + +class ClassType(JitType): + def __init__(self, qualified_name: str) -> None: ... + def qualified_name(self) -> str: ... + +class InterfaceType(JitType): + def __init__(self, qualified_name: str) -> None: ... + def getMethod(self, name: str) -> FunctionSchema | None: ... + def getMethodNames(self) -> list[str]: ... + +JitTypeT = TypeVar("JitTypeT", bound=JitType) # noqa: PYI001 + +class OptionalType(JitType, Generic[JitTypeT]): + def __init__(self, a: JitTypeT) -> None: ... + def getElementType(self) -> JitTypeT: ... + @staticmethod + def ofTensor() -> OptionalType: ... + +class FutureType(JitType): + def __init__(self, a: JitType) -> None: ... + def getElementType(self) -> JitType: ... + +class AwaitType(JitType): + def __init__(self, a: JitType) -> None: ... + def getElementType(self) -> JitType: ... + +class RRefType(JitType): + def __init__(self, a: JitType) -> None: ... + +class EnumType(JitType): + def __init__( + self, + qualified_name: str, + value_type: JitType, + enum_names_values: list[Any], + ) -> None: ... + +class TensorType(JitType): + @classmethod + def get(cls) -> TensorType: ... + @classmethod + def getInferred(cls) -> TensorType: ... + def with_sizes(self, other: list[_int | None] | None) -> TensorType: ... + def sizes(self) -> list[_int] | None: ... + def varyingSizes(self) -> list[_int | None] | None: ... + def strides(self) -> list[_int] | None: ... + def device(self) -> _device | None: ... + def dim(self) -> _int: ... + def dtype(self) -> _dtype | None: ... + @staticmethod + def create_from_tensor(t: Tensor) -> TensorType: ... + +# Defined in torch/csrc/jit/python/python_tree_views.cpp +class SourceRange: ... +class TreeView: ... + +class Ident(TreeView): + @property + def name(self) -> str: ... + +class ClassDef(TreeView): ... + +class Def(TreeView): + def name(self) -> Ident: ... + +class Decl(TreeView): ... + +# Defined in torch/csrc/distributed/rpc/init.cpp +def _rpc_init() -> _bool: ... + +# Defined in torch/csrc/distributed/autograd/init.cpp +def _dist_autograd_init() -> _bool: ... + +# Defined in torch/csrc/distributed/c10d/init.cpp +def _c10d_init() -> _bool: ... + +# Defined in torch/csrc/distributed/rpc/testing/init.cpp +def _faulty_agent_init() -> _bool: ... +def _register_py_class_for_device(device: str, cls: Any) -> None: ... + +# Defined in torch/csrc/Module.cpp +def _current_graph_task_id() -> _int: ... +def _current_autograd_node() -> _Node: ... +def _will_engine_execute_node(node: _Node) -> _bool: ... +def _dispatch_key_set(tensor) -> str: ... + +# Defined in torch/csrc/Exceptions.cpp +class AcceleratorError(RuntimeError): ... +class OutOfMemoryError(RuntimeError): ... +class _DistError(RuntimeError): ... +class _DistBackendError(RuntimeError): ... +class _DistStoreError(RuntimeError): ... +class _DistNetworkError(RuntimeError): ... +class _DistQueueEmptyError(_DistStoreError): ... + +# Defined in torch/csrc/profiler/init.cpp +class CapturedTraceback: ... + +def gather_traceback(python: _bool, script: _bool, cpp: _bool) -> CapturedTraceback: ... +def symbolize_tracebacks( + tracebacks: list[CapturedTraceback], +) -> list[dict[str, Any]]: ... +def _load_mobile_module_from_file(filename: str): ... +def _load_mobile_module_from_bytes(bytes_: bytes): ... +def _load_jit_module_from_file(filename: str): ... +def _load_jit_module_from_bytes(bytes_: bytes): ... +def _save_mobile_module(m: LiteScriptModule, filename: str): ... +def _save_jit_module(m: ScriptModule, filename: str, extra_files: dict[str, Any]): ... +def _save_mobile_module_to_bytes(m: LiteScriptModule) -> bytes: ... +def _save_jit_module_to_bytes( + m: ScriptModule, + extra_files: dict[str, Any], +) -> bytes: ... +def _get_module_info_from_flatbuffer(data: bytes): ... +def _jit_resolve_packet(op_name: str, *args, **kwargs) -> str: ... +def _swap_tensor_impl(t1: Tensor, t2: Tensor): ... +def _pickle_save(obj: Any) -> bytes: ... +def _pickle_load_obj(bs: bytes) -> Any: ... + +# Defined in torch/csrc/jit/runtime/static/init.cpp +def _jit_to_static_module(graph_or_module: Graph | ScriptModule) -> Any: ... +def _fuse_to_static_module( + graph_or_module: Graph | ScriptModule, + min_size: _int, +) -> Any: ... + +# Defined in torch/csrc/fx/node.cpp +def _fx_map_aggregate(a: Any, fn: Callable[[Any], Any]) -> Any: ... +def _fx_map_arg(a: Any, fn: Callable[[Any], Any]) -> Any: ... + +class _NodeBase: + _erased: _bool + _prev: FxNode + _next: FxNode + def __init__( + self, + graph: Any, + name: str, + op: str, + target: Any, + return_type: Any, + ) -> None: ... + def _update_args_kwargs(self, args: tuple[Any, ...], kwargs: dict[str, Any]): ... + def _prepend(self, n: FxNode) -> None: ... + def _replace_input_with(self, old_input: FxNode, new_input: FxNode) -> None: ... + def _remove_from_list(self) -> None: ... + def __lt__(self, n: Self) -> _bool: ... + def __gt__(self, n: Self) -> _bool: ... + def __le__(self, n: Self) -> _bool: ... + def __ge__(self, n: Self) -> _bool: ... + +class _NodeIter(Iterator[FxNode]): + def __init__(self, root: FxNode, reversed: _bool) -> None: ... + def __iter__(self) -> Self: ... + def __next__(self) -> FxNode: ... + +# Defined in torch/csrc/inductor/static_cuda_launcher.cpp +class _StaticCudaLauncher: + @staticmethod + def _load_kernel( + cubin_file: str, + func_name: str, + shared_mem_bytes: _int, + device: _int, + ) -> tuple[_int, _int, _int]: ... + @staticmethod + def _launch_kernel( + func: _int, + grid_x: _int, + grid_y: _int, + grid_z: _int, + num_warps: _int, + shared_mem_bytes: _int, + arg_types: str, + args: tuple[Any, ...], + stream: _int, + ) -> None: ... + +# Defined in torch/csrc/cuda/GreenContext.cpp +class GreenContext: + @staticmethod + def create( + num_sms: _int, + device_id: _int, + ) -> GreenContext: ... + def set_context( + self, + ) -> None: ... + def pop_context( + self, + ) -> None: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_acc/__init__.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_acc/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..aa17e5cb2190bbe5d4f9d349a03ff2ffb319e603 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_acc/__init__.pyi @@ -0,0 +1,15 @@ +from torch import Tensor +from torch.types import _dtype, _int, Device + +# Defined in torch/csrc/acc/Module.cpp +class PrivateUse1Hooks: + def has_primary_context(self, device_index: _int) -> bool: ... + def is_built(self) -> bool: ... + def is_avaible(self) -> bool: ... + +class DeviceGuard: + def type_(self) -> Device: ... + +def register_python_privateuseone_device_guard(guard: DeviceGuard) -> bool: ... +def register_python_privateuseone_hook(hook: PrivateUse1Hooks) -> bool: ... +def create_empty_tensor(shape: tuple[_int, ...], dtype: _dtype) -> Tensor: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_aoti.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_aoti.pyi new file mode 100644 index 0000000000000000000000000000000000000000..2f57b5e5e72b1e30d0955bf955c3de22174c70ef --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_aoti.pyi @@ -0,0 +1,164 @@ +from ctypes import c_void_p +from typing import overload, Protocol + +from torch import Tensor + +# Defined in torch/csrc/inductor/aoti_runner/pybind.cpp + +# Tensor to AtenTensorHandle +def unsafe_alloc_void_ptrs_from_tensors(tensors: list[Tensor]) -> list[c_void_p]: ... +def unsafe_alloc_void_ptr_from_tensor(tensor: Tensor) -> c_void_p: ... + +# AtenTensorHandle to Tensor +def alloc_tensors_by_stealing_from_void_ptrs( + handles: list[c_void_p], +) -> list[Tensor]: ... +def alloc_tensor_by_stealing_from_void_ptr( + handle: c_void_p, +) -> Tensor: ... + +class AOTIModelContainerRunner(Protocol): + def run( + self, inputs: list[Tensor], stream_handle: c_void_p = ... + ) -> list[Tensor]: ... + def get_call_spec(self) -> list[str]: ... + def get_constant_names_to_original_fqns(self) -> dict[str, str]: ... + def get_constant_names_to_dtypes(self) -> dict[str, int]: ... + def extract_constants_map(self, use_inactive: bool) -> dict[str, Tensor]: ... + def update_constant_buffer( + self, + tensor_map: dict[str, Tensor], + use_inactive: bool, + validate_full_updates: bool, + user_managed: bool = ..., + ) -> None: ... + def swap_constant_buffer(self) -> None: ... + def free_inactive_constant_buffer(self) -> None: ... + +class AOTIModelContainerRunnerCpu: + def __init__(self, model_so_path: str, num_models: int) -> None: ... + def run( + self, inputs: list[Tensor], stream_handle: c_void_p = ... + ) -> list[Tensor]: ... + def get_call_spec(self) -> list[str]: ... + def get_constant_names_to_original_fqns(self) -> dict[str, str]: ... + def get_constant_names_to_dtypes(self) -> dict[str, int]: ... + def extract_constants_map(self, use_inactive: bool) -> dict[str, Tensor]: ... + def update_constant_buffer( + self, + tensor_map: dict[str, Tensor], + use_inactive: bool, + validate_full_updates: bool, + user_managed: bool = ..., + ) -> None: ... + def swap_constant_buffer(self) -> None: ... + def free_inactive_constant_buffer(self) -> None: ... + +class AOTIModelContainerRunnerCuda: + @overload + def __init__(self, model_so_path: str, num_models: int) -> None: ... + @overload + def __init__( + self, model_so_path: str, num_models: int, device_str: str + ) -> None: ... + @overload + def __init__( + self, model_so_path: str, num_models: int, device_str: str, cubin_dir: str + ) -> None: ... + def run( + self, inputs: list[Tensor], stream_handle: c_void_p = ... + ) -> list[Tensor]: ... + def get_call_spec(self) -> list[str]: ... + def get_constant_names_to_original_fqns(self) -> dict[str, str]: ... + def get_constant_names_to_dtypes(self) -> dict[str, int]: ... + def extract_constants_map(self, use_inactive: bool) -> dict[str, Tensor]: ... + def update_constant_buffer( + self, + tensor_map: dict[str, Tensor], + use_inactive: bool, + validate_full_updates: bool, + user_managed: bool = ..., + ) -> None: ... + def swap_constant_buffer(self) -> None: ... + def free_inactive_constant_buffer(self) -> None: ... + +class AOTIModelContainerRunnerXpu: + @overload + def __init__(self, model_so_path: str, num_models: int) -> None: ... + @overload + def __init__( + self, model_so_path: str, num_models: int, device_str: str + ) -> None: ... + @overload + def __init__( + self, model_so_path: str, num_models: int, device_str: str, kernel_bin_dir: str + ) -> None: ... + def run( + self, inputs: list[Tensor], stream_handle: c_void_p = ... + ) -> list[Tensor]: ... + def get_call_spec(self) -> list[str]: ... + def get_constant_names_to_original_fqns(self) -> dict[str, str]: ... + def get_constant_names_to_dtypes(self) -> dict[str, int]: ... + def extract_constants_map(self, use_inactive: bool) -> dict[str, Tensor]: ... + def update_constant_buffer( + self, + tensor_map: dict[str, Tensor], + use_inactive: bool, + validate_full_updates: bool, + user_managed: bool = ..., + ) -> None: ... + def swap_constant_buffer(self) -> None: ... + def free_inactive_constant_buffer(self) -> None: ... + +class AOTIModelContainerRunnerMps: + def __init__(self, model_so_path: str, num_models: int) -> None: ... + def run( + self, inputs: list[Tensor], stream_handle: c_void_p = ... + ) -> list[Tensor]: ... + def get_call_spec(self) -> list[str]: ... + def get_constant_names_to_original_fqns(self) -> dict[str, str]: ... + def get_constant_names_to_dtypes(self) -> dict[str, int]: ... + def extract_constants_map(self, use_inactive: bool) -> dict[str, Tensor]: ... + def update_constant_buffer( + self, + tensor_map: dict[str, Tensor], + use_inactive: bool, + validate_full_updates: bool, + user_managed: bool = ..., + ) -> None: ... + def swap_constant_buffer(self) -> None: ... + def free_inactive_constant_buffer(self) -> None: ... + +# Defined in torch/csrc/inductor/aoti_package/pybind.cpp +class AOTIModelPackageLoader: + def __init__( + self, + model_package_path: str, + model_name: str, + run_single_threaded: bool, + num_runners: int, + device_index: int, + ) -> None: ... + def get_metadata(self) -> dict[str, str]: ... + def run( + self, inputs: list[Tensor], stream_handle: c_void_p = ... + ) -> list[Tensor]: ... + def boxed_run( + self, inputs: list[Tensor], stream_handle: c_void_p = ... + ) -> list[Tensor]: ... + def get_call_spec(self) -> list[str]: ... + def get_constant_fqns(self) -> list[str]: ... + def load_constants( + self, + constants_map: dict[str, Tensor], + use_inactive: bool, + check_full_update: bool, + user_managed: bool = ..., + ) -> None: ... + def update_constant_buffer( + self, + tensor_map: dict[str, Tensor], + use_inactive: bool, + validate_full_updates: bool, + user_managed: bool = ..., + ) -> None: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_autograd.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_autograd.pyi new file mode 100644 index 0000000000000000000000000000000000000000..1ff5d847b61aa4f29245d0a08a4d316100992f25 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_autograd.pyi @@ -0,0 +1,144 @@ +# mypy: allow-untyped-defs +from collections.abc import Callable +from enum import Enum +from typing import Any + +import torch +from torch._C._profiler import ( + _ProfilerEvent, + ActiveProfilerType, + ProfilerActivity, + ProfilerConfig, +) + +# Defined in torch/csrc/autograd/init.cpp + +class DeviceType(Enum): + CPU = ... + CUDA = ... + XPU = ... + MKLDNN = ... + OPENGL = ... + OPENCL = ... + IDEEP = ... + HIP = ... + FPGA = ... + MAIA = ... + XLA = ... + MTIA = ... + MPS = ... + HPU = ... + Meta = ... + Vulkan = ... + Metal = ... + PrivateUse1 = ... + +class ProfilerEvent: + def cpu_elapsed_us(self, other: ProfilerEvent) -> float: ... + def cpu_memory_usage(self) -> int: ... + def cuda_elapsed_us(self, other: ProfilerEvent) -> float: ... + def privateuse1_elapsed_us(self, other: ProfilerEvent) -> float: ... + def cuda_memory_usage(self) -> int: ... + def device(self) -> int: ... + def handle(self) -> int: ... + def has_cuda(self) -> bool: ... + def is_remote(self) -> bool: ... + def kind(self) -> int: ... + def name(self) -> str: ... + def node_id(self) -> int: ... + def sequence_nr(self) -> int: ... + def shapes(self) -> list[list[int]]: ... + def thread_id(self) -> int: ... + def flops(self) -> float: ... + def is_async(self) -> bool: ... + +class _KinetoEvent: + def name(self) -> str: ... + def overload_name(self) -> str: ... + def device_index(self) -> int: ... + def device_resource_id(self) -> int: ... + def start_ns(self) -> int: ... + def end_ns(self) -> int: ... + def duration_ns(self) -> int: ... + def is_async(self) -> bool: ... + def linked_correlation_id(self) -> int: ... + def shapes(self) -> list[list[int]]: ... + def dtypes(self) -> list[str]: ... + def concrete_inputs(self) -> list[Any]: ... + def kwinputs(self) -> dict[str, Any]: ... + def device_type(self) -> DeviceType: ... + def start_thread_id(self) -> int: ... + def end_thread_id(self) -> int: ... + def correlation_id(self) -> int: ... + def fwd_thread_id(self) -> int: ... + def stack(self) -> list[str]: ... + def scope(self) -> int: ... + def sequence_nr(self) -> int: ... + def flops(self) -> int: ... + def cuda_elapsed_us(self) -> int: ... + def privateuse1_elapsed_us(self) -> int: ... + def is_user_annotation(self) -> bool: ... + def is_hidden_event(self) -> bool: ... + def metadata_json(self) -> str: ... + +class _ProfilerResult: + def events(self) -> list[_KinetoEvent]: ... + def legacy_events(self) -> list[list[ProfilerEvent]]: ... + def save(self, path: str) -> None: ... + def experimental_event_tree(self) -> list[_ProfilerEvent]: ... + def trace_start_ns(self) -> int: ... + +class SavedTensor: ... + +def _enable_profiler( + config: ProfilerConfig, + activities: set[ProfilerActivity], +) -> None: ... +def _prepare_profiler( + config: ProfilerConfig, + activities: set[ProfilerActivity], +) -> None: ... +def _toggle_collection_dynamic( + enable: bool, + activities: set[ProfilerActivity], +) -> None: ... +def _disable_profiler() -> _ProfilerResult: ... +def _profiler_enabled() -> bool: ... +def _add_metadata_json(key: str, value: str) -> None: ... +def _kineto_step() -> None: ... +def _get_current_graph_task_keep_graph() -> bool: ... +def _get_sequence_nr() -> int: ... +def kineto_available() -> bool: ... +def _record_function_with_args_enter(name: str, *args) -> torch.Tensor: ... +def _record_function_with_args_exit(handle: torch.Tensor) -> None: ... +def _supported_activities() -> set[ProfilerActivity]: ... +def _enable_record_function(enable: bool) -> None: ... +def _set_empty_test_observer(is_global: bool, sampling_prob: float) -> None: ... +def _push_saved_tensors_default_hooks( + pack_hook: Callable[[torch.Tensor], Any], + unpack_hook: Callable[[Any], torch.Tensor], +) -> None: ... +def _pop_saved_tensors_default_hooks() -> None: ... +def _top_saved_tensors_default_hooks( + ignore_is_tracing: bool, +) -> tuple[Callable[[torch.Tensor], Any], Callable[[Any], torch.Tensor]]: ... +def _unsafe_set_version_counter( + t: tuple[torch.Tensor, ...], prev_version: tuple[int, ...] +) -> None: ... +def _enable_profiler_legacy(config: ProfilerConfig) -> None: ... +def _disable_profiler_legacy() -> list[list[ProfilerEvent]]: ... +def _profiler_type() -> ActiveProfilerType: ... +def _saved_tensors_hooks_enable() -> None: ... +def _saved_tensors_hooks_disable(message: str, fail_if_non_empty=True) -> None: ... +def _saved_tensors_hooks_get_disabled_error_message() -> str | None: ... +def _saved_tensors_hooks_set_tracing(is_tracing: bool) -> bool: ... + +class CreationMeta(Enum): + DEFAULT = ... + IN_CUSTOM_FUNCTION = ... + MULTI_OUTPUT_NODE = ... + NO_GRAD_MODE = ... + INFERENCE_MODE = ... + +def _set_creation_meta(t: torch.Tensor, creation_meta: CreationMeta) -> None: ... +def _get_creation_meta(t: torch.Tensor) -> CreationMeta: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_cpu.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_cpu.pyi new file mode 100644 index 0000000000000000000000000000000000000000..a667edc721a9c13b26a095fee1ba653c542c09af --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_cpu.pyi @@ -0,0 +1,13 @@ +from torch.types import _bool, _int + +# Defined in torch/csrc/cpu/Module.cpp + +def _is_avx2_supported() -> _bool: ... +def _is_avx512_supported() -> _bool: ... +def _is_avx512_vnni_supported() -> _bool: ... +def _is_avx512_bf16_supported() -> _bool: ... +def _is_amx_tile_supported() -> _bool: ... +def _is_amx_fp16_supported() -> _bool: ... +def _init_amx() -> _bool: ... +def _L1d_cache_size() -> _int: ... +def _L2_cache_size() -> _int: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_cudnn.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_cudnn.pyi new file mode 100644 index 0000000000000000000000000000000000000000..cfea3f956f2a373dfe6895743a49a3c6cec439fa --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_cudnn.pyi @@ -0,0 +1,14 @@ +from enum import IntEnum + +# Defined in torch/csrc/cuda/shared/cudnn.cpp +is_cuda: bool + +def getRuntimeVersion() -> tuple[int, int, int]: ... +def getCompileVersion() -> tuple[int, int, int]: ... +def getVersionInt() -> int: ... + +class RNNMode(IntEnum): + rnn_relu = ... + rnn_tanh = ... + lstm = ... + gru = ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_cusparselt.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_cusparselt.pyi new file mode 100644 index 0000000000000000000000000000000000000000..a1c4bbb217777d50b9a3384da11d9992db5e18f0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_cusparselt.pyi @@ -0,0 +1 @@ +def getVersionInt() -> int: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_distributed.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_distributed.pyi new file mode 100644 index 0000000000000000000000000000000000000000..c8416f60edca35493ad7c1703cf2e27d58975be0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_distributed.pyi @@ -0,0 +1,21 @@ +# This module is defined in torch/csrc/distributed/python_placement.cpp + +class Placement: + def is_partial(self, reduce_op: str | None = None) -> bool: ... + def is_replicate(self) -> bool: ... + def is_shard(self, dim: int | None = None) -> bool: ... + +class Shard(Placement): + dim: int + def __init__(self, dim: int): ... + +class StridedShard(Placement): + dim: int + split_factor: int + def __init__(self, dim: int, *, split_factor: int): ... + +class Replicate(Placement): ... + +class Partial(Placement): + reduce_op: str + def __init__(self, reduce_op: str | None = None): ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_distributed_autograd.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_distributed_autograd.pyi new file mode 100644 index 0000000000000000000000000000000000000000..6e1e39bec2927c046455928ff74bc7de9683e66f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_distributed_autograd.pyi @@ -0,0 +1,26 @@ +from typing import Any + +import torch + +# This module is defined in torch/csrc/distributed/autograd/init.cpp + +class DistAutogradContext: + def _context_id(self) -> int: ... + def _recv_functions(self) -> dict[int, Any]: ... + def _send_functions(self) -> dict[int, Any]: ... + def _known_worker_ids(self) -> set[int]: ... + +def _new_context() -> DistAutogradContext: ... +def _release_context(context_id: int) -> None: ... +def _get_max_id() -> int: ... +def _is_valid_context(worker_id: int) -> bool: ... +def _retrieve_context(context_id: int) -> DistAutogradContext: ... +def _current_context() -> DistAutogradContext: ... +def _init(worker_id: int) -> None: ... +def _get_debug_info() -> dict[str, str]: ... +def backward( + context_id: int, + roots: list[torch.Tensor], + retain_graph: bool = False, +) -> None: ... +def get_gradients(context_id: int) -> dict[torch.Tensor, torch.Tensor]: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_distributed_c10d.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_distributed_c10d.pyi new file mode 100644 index 0000000000000000000000000000000000000000..1bcb2d498ad2d43944082ce447677bb5467433d7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_distributed_c10d.pyi @@ -0,0 +1,889 @@ +# mypy: allow-untyped-defs +# mypy: disable-error-code="type-arg" +from collections.abc import Callable +from datetime import timedelta +from enum import Enum +from typing import Any, Optional, overload, Union + +import torch +from torch import Tensor +from torch._C import ScriptObject +from torch._C._autograd import DeviceType +from torch.distributed.distributed_c10d import GroupName +from torch.futures import Future + +# This module is defined in torch/csrc/distributed/c10d/init.cpp + +_DEFAULT_FIRST_BUCKET_BYTES: int +_DEFAULT_NO_TIMEOUT: timedelta +_DEFAULT_PG_TIMEOUT: timedelta +_DEFAULT_PG_NCCL_TIMEOUT: timedelta + +class BuiltinCommHookType(Enum): + ALLREDUCE = ... + FP16_COMPRESS = ... + +def _register_comm_hook(reducer: Reducer, state: Any, comm_hook: Any): ... +def _register_builtin_comm_hook( + reducer: Reducer, + comm_hook_type: BuiltinCommHookType, +): ... +def _set_global_rank(rank: int) -> None: ... +def _hash_tensors(tensors: list[Tensor]) -> int: ... + +class GradBucket: + def index(self) -> int: ... + def buffer(self) -> Tensor: ... + def gradients(self) -> list[Tensor]: ... + def is_last(self) -> bool: ... + def set_buffer(self, tensor: Tensor) -> None: ... + def parameters(self) -> list[Tensor]: ... + +class Reducer: + def __init__( + self, + params: list[Tensor], + bucket_indices: list[list[int]], + per_bucket_size_limits: list[int], + process_group: ProcessGroup, + expect_sparse_gradients: list[bool] = ..., + bucket_bytes_cap: int = ..., # kDefaultBucketBytesCap in reducer.hpp + find_unused_parameters: bool = ..., + gradient_as_bucket_view: bool = ..., + param_to_name_mapping: dict[int, str] = ..., + first_bucket_types_cap: int = ..., # kDefaultFirstBucketBytes in reducer.hpp + skip_all_reduce_unused_params: bool = ..., + use_python_reducer: bool = ..., + ) -> None: ... + def prepare_for_forward(self) -> None: ... + def prepare_for_backward(self, output: list[Tensor]) -> None: ... + def get_backward_stats(self) -> list[int]: ... + def _install_post_backward_futures(self, futures: list[Future]) -> None: ... + def _rebuild_buckets(self) -> bool: ... + def _get_zeros_like_grad_buckets(self) -> list[GradBucket]: ... + def _push_all_rebuilt_params(self) -> None: ... + def _set_forward_pass_work_handle( + self, + work: Work, + use_static_world_size: bool, + ): ... + def _get_local_used_map(self) -> Tensor: ... + def _set_ddp_runtime_logging_sample_rate(self, sample_rate: int) -> None: ... + def _set_static_graph(self) -> None: ... + def _run_comm_hook(self, bucket: GradBucket) -> Future: ... + def set_logger(self, logger: Logger) -> None: ... + def _remove_autograd_hooks(self) -> None: ... + def _check_reducer_finalized(self) -> None: ... + def _set_sparse_metadata(self, global_unique_ids: dict[str, Tensor]) -> None: ... + def _reset_state(self) -> None: ... + def _update_process_group(self, new_process_group: ProcessGroup) -> None: ... + +class DDPLoggingData: + strs_map: dict[str, str] + ints_map: dict[str, int] + +class Logger: + def __init__(self, reducer: Reducer) -> None: ... + def set_construction_data_and_log( + self, + module_name: str, + device_ids: list[int], + output_device: int, + broadcast_buffers: bool, + has_sync_bn: bool, + static_graph: bool, + ): ... + def set_runtime_stats_and_log(self) -> None: ... + def set_error_and_log(self, error: str) -> None: ... + def _get_ddp_logging_data(self) -> DDPLoggingData: ... + def _set_comm_hook_name(self, comm_hook: str) -> None: ... + def _set_uneven_input_join(self) -> None: ... + def _set_static_graph(self) -> None: ... + +class _WorkerServer: + port: int + + def __init__(self, host_or_file: str, port: int = ...) -> None: ... + def shutdown(self) -> None: ... + +def get_debug_level(): ... +def set_debug_level(): ... +def set_debug_level_from_env(): ... + +class DebugLevel(Enum): + OFF = ... + INFO = ... + DETAIL = ... + +class ReduceOp: + # pyrefly: ignore # unknown-name + def __init__(self, op: RedOpType) -> None: ... + + # pyrefly: ignore # unknown-name + SUM: RedOpType = ... + # pyrefly: ignore # unknown-name + AVG: RedOpType = ... + # pyrefly: ignore # unknown-name + PRODUCT: RedOpType = ... + # pyrefly: ignore # unknown-name + MIN: RedOpType = ... + # pyrefly: ignore # unknown-name + MAX: RedOpType = ... + # pyrefly: ignore # unknown-name + BAND: RedOpType = ... + # pyrefly: ignore # unknown-name + BOR: RedOpType = ... + # pyrefly: ignore # unknown-name + BXOR: RedOpType = ... + # pyrefly: ignore # unknown-name + PREMUL_SUM: RedOpType = ... + # pyrefly: ignore # unknown-name + UNUSED: RedOpType = ... + + # mypy error being ignored: + # Detected enum "torch._C._distributed_c10d.ReduceOp.RedOpType" in a type + # stub with zero members. There is a chance this is due to a recent change + # in the semantics of enum membership. If so, use `member = value` to mark + # an enum member, instead of `member: type` + class RedOpType(Enum): ... # type: ignore[misc] + +class BroadcastOptions: + rootRank: int + rootTensor: int + timeout: timedelta + asyncOp: bool + +class AllreduceOptions: + reduceOp: ReduceOp + timeout: timedelta + asyncOp: bool + sparseIndices: Optional[Tensor] + +class AllreduceCoalescedOptions(AllreduceOptions): ... + +class ReduceOptions: + reduceOp: ReduceOp + rootRank: int + rootTensor: int + timeout: timedelta + asyncOp: bool + +class AllgatherOptions: + timeout: timedelta + asyncOp: bool + +class GatherOptions: + rootRank: int + timeout: timedelta + asyncOp: bool + +class ScatterOptions: + rootRank: int + timeout: timedelta + asyncOp: bool + +class ReduceScatterOptions: + reduceOp: ReduceOp + timeout: timedelta + asyncOp: bool + +class BarrierOptions: + device_ids: list[int] + device: torch.device + timeout: timedelta + asyncOp: bool + +class AllToAllOptions: + timeout: timedelta + asyncOp: bool + +class Store: + def set(self, key: str, value: str): ... + def get(self, key: str) -> bytes: ... + def add(self, key: str, value: int) -> int: ... + def check(self, keys: list[str]) -> bool: ... + def compare_set( + self, + key: str, + expected_value: str, + desired_value: str, + ) -> bytes: ... + def delete_key(self, key: str) -> bool: ... + def multi_get(self, keys: list[str]) -> list[bytes]: ... + def num_keys(self) -> int: ... + def set_timeout(self, timeout: timedelta): ... + @overload + def wait(self, keys: list[str]): ... + @overload + def wait(self, keys: list[str], timeout: timedelta): ... + def queue_pop(self, key: str, block: bool = True) -> bytes: ... + def queue_push(self, key: str, value: Union[bytes, str]) -> None: ... + def queue_len(self, key: str) -> int: ... + def list_keys(self) -> list[str]: ... + +class FileStore(Store): + def __init__(self, path: str, numWorkers: int = ...) -> None: ... + +class HashStore(Store): + def __init__(self) -> None: ... + +class TCPStore(Store): + def __init__( + self, + host_name: str, + port: int, + world_size: int | None = ..., + is_master: bool = ..., + timeout: timedelta = ..., + wait_for_workers: bool = ..., + multi_tenant: bool = ..., + master_listen_fd: int | None = ..., + use_libuv: bool | None = ..., + ) -> None: ... + @property + def host(self) -> str: ... + @property + def port(self) -> int: ... + +class PrefixStore(Store): + def __init__(self, prefix: str, store: Store) -> None: ... + @property + def underlying_store(self) -> Store: ... + +class _ControlCollectives: + def barrier(self, key: str, timeout: timedelta, blocking: bool) -> None: ... + def broadcast_send(self, key: str, data: str, timeout: timedelta) -> None: ... + def broadcast_recv(self, key: str, timeout: timedelta) -> str: ... + def gather_send(self, key: str, data: str, timeout: timedelta) -> None: ... + def gather_recv(self, key: str, timeout: timedelta) -> str: ... + def scatter_send(self, key: str, data: str, timeout: timedelta) -> None: ... + def scatter_recv(self, key: str, timeout: timedelta) -> str: ... + def all_gather(self, key: str, data: str, timeout: timedelta) -> str: ... + def all_sum(self, key: str, data: int, timeout: timedelta) -> int: ... + +class _StoreCollectives(_ControlCollectives): + def __init__(self, store: Store, rank: int, world_size: int) -> None: ... + +class _DistributedBackendOptions: + def __init__(self) -> None: ... + @property + def store(self) -> Store: ... + @store.setter + def store(self, store: Store) -> None: ... + @property + def group_rank(self) -> int: ... + @group_rank.setter + def group_rank(self, rank: int) -> None: ... + @property + def group_size(self) -> int: ... + @group_size.setter + def group_size(self, size: int) -> None: ... + @property + def timeout(self) -> timedelta: ... + @timeout.setter + def timeout(self, timeout: timedelta) -> None: ... + @property + def group_id(self) -> str: ... + @group_id.setter + def group_id(self, group_id: str) -> None: ... + @property + def global_ranks_in_group(self) -> list[int]: ... + @global_ranks_in_group.setter + def global_ranks_in_group(self, ranks: list[int]) -> None: ... + +class Work: + def is_completed(self) -> bool: ... + def is_success(self) -> bool: ... + def exception(self) -> Any: ... + def wait(self, timeout: timedelta = ...) -> bool: ... + def block_current_stream(self) -> None: ... + def get_future(self) -> Future: ... + def source_rank(self) -> int: ... + def _source_rank(self) -> int: ... + def result(self) -> list[Tensor]: ... + def synchronize(self) -> None: ... + def boxed(self) -> ScriptObject: ... + @staticmethod + def unbox(obj: ScriptObject) -> Work: ... + +class Backend: + class Options: + def __init__(self, backend: str, timeout: timedelta = ...) -> None: ... + @property + def backend(self) -> str: ... + @property + def _timeout(self) -> timedelta: ... + @_timeout.setter + def _timeout(self, val: timedelta) -> None: ... + global_ranks_in_group: list[int] + group_name: GroupName + + def __init__( + self, + rank: int, + size: int, + ) -> None: ... + @property + def supports_splitting(self) -> bool: ... + @property + def supports_coalescing(self) -> bool: ... + @property + def supports_time_estimate(self) -> bool: ... + def set_timeout(self, timeout: timedelta) -> None: ... + @property + def options(self) -> Options: ... + def rank(self) -> int: ... + def size(self) -> int: ... + def name(self) -> str: ... + def abort(self) -> None: ... + def shutdown(self) -> None: ... + def eager_connect_single_device(self, device: torch.device | None) -> None: ... + def _set_sequence_number_for_group(self) -> None: ... + def _set_default_timeout(self, timeout: timedelta) -> None: ... + def get_error(self) -> ErrorType: ... + def supports_tensor_alloc(self, device: torch.device) -> bool: ... + def allocate_tensor( + self, + size: int, + *, + dtype: torch.dtype, + device: torch.device, + ) -> Tensor: ... + @property + def mem_allocator(self) -> Any: ... + +class ProcessGroup: + class BackendType(Enum): + UNDEFINED = ... + GLOO = ... + NCCL = ... + UCC = ... + MPI = ... + XCCL = ... + CUSTOM = ... + + def __init__( + self, + store: Store, + rank: int, + size: int, + ) -> None: ... + def rank(self) -> int: ... + def size(self) -> int: ... + def get_group_store(self) -> Store: ... + def split_group( + self, + new_ranks: list[int], + timeout: Optional[timedelta] = None, + opts: Optional[Backend.Options] = None, + group_name: GroupName | None = None, + group_desc: Optional[str] = None, + ) -> Optional[ProcessGroup]: ... + def merge_remote_group( + self, + store: Store, + size: int, + timeout: timedelta, + group_name: GroupName | None = None, + group_desc: Optional[str] = None, + ) -> ProcessGroup: ... + def abort(self) -> None: ... + def set_timeout(self, timeout: timedelta) -> None: ... + def shutdown(self) -> None: ... + @overload + def broadcast( + self, + tensors: list[Tensor], + opts=..., + ) -> Work: ... + @overload + def broadcast( + self, + tensor: Tensor, + root: int, + timeout: timedelta | None = None, + ) -> Work: ... + @overload + def allreduce( + self, + tensors: list[Tensor], + opts: AllreduceOptions = ..., + ) -> Work: ... + @overload + def allreduce( + self, + tensors: list[Tensor], + op=..., + timeout: timedelta | None = None, + ) -> Work: ... + @overload + def allreduce( + self, + tensor: Tensor, + op=..., + timeout: timedelta | None = None, + ) -> Work: ... + def allreduce_coalesced( + self, + tensors: list[Tensor], + opts=..., + ) -> Work: ... + def reduce_scatter_tensor_coalesced( + self, + outputTensors: list[Tensor], + inputTensors: list[Tensor], + opts: ReduceScatterOptions | None = None, + ) -> Work: ... + @overload + def reduce( + self, + tensors: list[Tensor], + opts=..., + ) -> Work: ... + @overload + def reduce( + self, + tensor: Tensor, + root: int, + op=..., + timeout: timedelta | None = None, + ) -> Work: ... + @overload + def allgather( + self, + output_tensors: list[list[Tensor]], + input_tensors: list[Tensor], + opts=..., + ) -> Work: ... + @overload + def allgather( + self, + output_tensors: list[Tensor], + input_tensor: Tensor, + timeout: timedelta | None = None, + ) -> Work: ... + def _allgather_base( + self, + output: Tensor, + input: Tensor, + opts=..., + ) -> Work: ... + def allgather_coalesced( + self, + output_lists: list[list[Tensor]], + input_list: list[Tensor], + opts=..., + ) -> Work: ... + def allgather_into_tensor_coalesced( + self, + output_lists: list[Tensor], + input_list: list[Tensor], + opts=..., + ) -> Work: ... + @overload + def gather( + self, + output_tensors: list[list[Tensor]], + input_tensors: list[Tensor], + opts=..., + ) -> Work: ... + @overload + def gather( + self, + output_tensors: list[Tensor], + input_tensor: Tensor, + root: int, + timeout: timedelta | None = None, + ) -> Work: ... + @overload + def scatter( + self, + output_tensors: list[Tensor], + input_tensors: list[list[Tensor]], + opts=..., + ) -> Work: ... + @overload + def scatter( + self, + output_tensor: Tensor, + input_tensors: list[Tensor], + root: int, + timeout: timedelta | None = None, + ) -> Work: ... + @overload + def reduce_scatter( + self, + output_tensors: list[Tensor], + input_tensors: list[list[Tensor]], + opts=..., + ) -> Work: ... + @overload + def reduce_scatter( + self, + output_tensors: Tensor, + input_tensor: list[Tensor], + op=..., + timeout: timedelta | None = None, + ) -> Work: ... + def _reduce_scatter_base( + self, + outputTensor: Tensor, + inputTensor: Tensor, + opts: ReduceScatterOptions | None, + ) -> Work: ... + @overload + def alltoall_base( + self, + output_tensor: Tensor, + input_tensor: Tensor, + output_split_sizes: list[int], + input_split_sizes: list[int], + opts=..., + ) -> Work: ... + @overload + def alltoall_base( + self, + output: Tensor, + input: Tensor, + output_split_sizes: list[int], + input_split_sizes: list[int], + timeout: timedelta | None = None, + ) -> Work: ... + @overload + def alltoall( + self, + output_tensor: list[Tensor], + input_tensor: list[Tensor], + opts=..., + ) -> Work: ... + @overload + def alltoall( + self, + output: list[Tensor], + input: list[Tensor], + timeout: timedelta | None = None, + ) -> Work: ... + def send( + self, + tensors: list[Tensor], + dstRank: int, + tag: int, + ) -> Work: ... + def recv( + self, + tensors: list[Tensor], + srcRank: int, + tag: int, + ) -> Work: ... + def recv_anysource(self, tensors: list[Tensor], tag: int) -> Work: ... + @overload + def barrier(self, opts=...) -> Work: ... + @overload + def barrier(self, timeout: timedelta | None = None) -> Work: ... + def boxed(self) -> ScriptObject: ... + @staticmethod + def unbox(obj: ScriptObject) -> ProcessGroup: ... + def _start_coalescing(self, device: torch.device) -> None: ... + def _end_coalescing(self, device: torch.device) -> Work: ... + def _get_backend_name(self) -> str: ... + def _backend_id(self, backend_type: BackendType) -> int: ... + @property + def _device_types(self) -> list[torch.device]: ... + def _get_backend(self, device: torch.device) -> Backend: ... + def _set_default_backend(self, backend_type: BackendType) -> None: ... + def _register_backend( + self, + device: torch.device, + backend_type: BackendType, + backend: Backend | None, + ) -> None: ... + def _set_group_name(self, name: GroupName) -> None: ... + def _set_group_desc(self, desc: str) -> None: ... + def name(self) -> str: ... + def _has_hooks(self) -> bool: ... + def _wait_for_pending_works(self) -> None: ... + def _set_sequence_number_for_group(self) -> None: ... + @property + def bound_device_id(self) -> torch.device | None: ... + @bound_device_id.setter + def bound_device_id(self, device: torch.device | None) -> None: ... + @property + def group_name(self) -> GroupName: ... + @property + def group_desc(self) -> str: ... + +class FakeProcessGroup(Backend): + @staticmethod + def _create_internal(rank: int, world_size: int) -> FakeProcessGroup: ... + +class FakeWork(Work): + seq_id: int + def __init__(self) -> None: ... + def wait(self, timeout: timedelta = ...) -> bool: ... + def getFuture(self) -> Future: ... + +class PythonCallbackWork(Work): + def __init__(self, callback: Callable[[timedelta], bool]) -> None: ... + def wait(self, timeout: timedelta = ...) -> bool: ... + def get_future(self) -> Future: ... + +class ProcessGroupGloo(Backend): + class Device: ... + + class Options(Backend.Options): + devices: list[ProcessGroupGloo.Device] + threads: int + + def __init__(self): ... + + def __init__( + self, + store: Store, + rank: int, + size: int, + timeout: timedelta, + ) -> None: ... + @staticmethod + def create_device(hostname="", interface="", lazy_init=None) -> Device: ... + @staticmethod + def create_default_device(lazy_init=None) -> Device: ... + def _set_default_timeout(self, timeout) -> None: ... + @property + def options(self) -> Options: ... # type: ignore[override] + +class _ProcessGroupWrapper(Backend): + def __init__(self, pg: Backend, gloo_pg: ProcessGroupGloo) -> None: ... + wrapped_pg: Backend + +class ErrorType(Enum): + SUCCESS = ... + TIMEOUT = ... + COMM_ERROR = ... + REMOTE_ERROR = ... + +class ProcessGroupNCCL(Backend): + class NCCLConfig: + blocking: int + cga_cluster_size: int + min_ctas: int + max_ctas: int + def unsafe_get_ptr(self) -> int: ... + + class Options(Backend.Options): + config: ProcessGroupNCCL.NCCLConfig + is_high_priority_stream: bool + split_from: ProcessGroupNCCL + split_color: int + + def __init__(self, is_high_priority_stream: bool = False): ... + + def __init__( + self, + store: Store, + rank: int, + size: int, + options: Options, + ) -> None: ... + def _group_start(self) -> None: ... + def _group_end(self) -> None: ... + def _start_time_estimate(self) -> None: ... + def _end_time_estimate(self) -> float: ... + def _set_default_timeout(self, timeout) -> None: ... + def perform_nocolor_split(self, device: torch.device) -> None: ... + def register_mem_pool(self, pool: torch.cuda.MemPool) -> None: ... + def deregister_mem_pool(self, pool: torch.cuda.MemPool) -> None: ... + def comm_split_count(self) -> int: ... + def _add_ephemeral_timeout(self, timeout: timedelta) -> None: ... + def abort(self) -> None: ... + def _is_initialized(self) -> bool: ... + @property + def uid(self) -> int: ... + @property + def options(self) -> Options: ... # type: ignore[override] + @staticmethod + def get_build_nccl_version(self) -> tuple[int, int, int]: ... + @staticmethod + def get_runtime_nccl_version(self) -> tuple[int, int, int]: ... + +class ProcessGroupUCC(Backend): + def __init__( + self, + store: Store, + rank: int, + size: int, + timeout: timedelta, + ) -> None: ... + +class ProcessGroupMPI(Backend): + def __init__( + self, + rank: int, + size: int, + pgComm: int, + ) -> None: ... + @staticmethod + def create(ranks: list[int]) -> ProcessGroupMPI: ... + +def _compute_bucket_assignment_by_size( + tensors: list[Tensor], + bucket_size_limits: list[int], + expect_sparse_gradient: list[bool] = ..., + tensor_indices: list[int] = ..., +) -> tuple[list[list[int]], list[int]]: ... +def _broadcast_coalesced( + process_group: ProcessGroup, + tensors: list[Tensor], + buffer_size: int, + src: int, +): ... +def _test_python_store(store: Store): ... +def _verify_params_across_processes( + process_group: ProcessGroup, + params: list[Tensor], + logger: Logger | None, +): ... +def _make_nccl_premul_sum(factor: float | list[Tensor]) -> ReduceOp: ... +def _register_process_group( + group_name: GroupName, + process_group: ProcessGroup, +) -> None: ... +def _resolve_process_group(group_name: GroupName) -> ProcessGroup: ... +def _register_work(tensor: torch.Tensor, work: Work) -> ProcessGroup: ... +def _get_work_registry_size() -> int: ... +def _set_allow_inflight_collective_as_graph_input( + value: bool, +) -> None: ... +def _allow_inflight_collective_as_graph_input() -> bool: ... +def _unregister_all_process_groups() -> None: ... +def _unregister_process_group(group_name: GroupName) -> None: ... + +# Initializes the device state in CUmodule so that it's able to perform NVSHMEM +# operations. CUmodule is a pointer to a CUDA module, carried by a int64 in +# Python. At C++ interface, it is converted to a uintptr_t. +def _nvshmemx_cumodule_init(module: int) -> None: ... + +# Check if NVSHMEM is available on current system. +def _is_nvshmem_available() -> bool: ... + +class _SymmetricMemory: + @staticmethod + def set_group_info( + group_name: str, + rank: int, + world_size: int, + store: Store, + ) -> None: ... + @staticmethod + def empty_strided_p2p( + size: torch.types._size, + stride: torch.types._size, + dtype: torch.dtype, + device: torch.device, + group_name: str | None = None, + alloc_id: int | None = None, + ) -> torch.Tensor: ... + @staticmethod + def has_multicast_support( + device_type: DeviceType, + device_idx: int, + ) -> bool: ... + # Set Symmetric Memory allocation backend. + @staticmethod + def set_backend(name: str) -> None: ... + @staticmethod + def get_backend(device: torch.device) -> Optional[str]: ... + @staticmethod + def get_mempool_allocator(device: torch.device) -> Any: ... + signal_pad_size: int + @property + def rank(self) -> int: ... + @property + def world_size(self) -> int: ... + @staticmethod + def rendezvous( + tensor: torch.Tensor, group_name: str | None = None + ) -> _SymmetricMemory: ... + def get_buffer( + self, + rank: int, + sizes: torch.types._size, + dtype: torch.dtype, + storage_offset: int | None = 0, + ) -> torch.Tensor: ... + def get_signal_pad( + self, + rank: int, + sizes: torch.types._size = [], + dtype: torch.dtype | None = None, + storage_offset: int | None = 0, + ) -> torch.Tensor: ... + def barrier(self, channel: int = 0, timeout_ms: int = 0) -> None: ... + def put_signal( + self, + dst_rank: int, + channel: int = 0, + timeout_ms: int = 0, + ) -> None: ... + def wait_signal( + self, + src_rank: int, + channel: int = 0, + timeout_ms: int = 0, + ) -> None: ... + def get_remote_tensor( + self, + peer: int, + sizes: torch.types._size, + dtype: torch.dtype, + ) -> torch.Tensor: ... + @staticmethod + def memset32( + tensor: torch.Tensor, offset: int, val: int, count: int = 1 + ) -> torch.Tensor: ... + @staticmethod + def stream_write_value32( + tensor: torch.Tensor, offset: int, val: int + ) -> torch.Tensor: ... + @property + def buffer_ptrs(self) -> list[int]: ... + @property + def buffer_ptrs_dev(self) -> int: ... + @property + def signal_pad_ptrs(self) -> list[int]: ... + @property + def signal_pad_ptrs_dev(self) -> int: ... + @property + def multicast_ptr(self) -> int: ... + @property + def buffer_size(self) -> int: ... + +class ProcessGroupXCCL(Backend): + class Options(Backend.Options): + is_high_priority_stream: bool + + def __init__(self, is_high_priority_stream: bool = False): ... + + def __init__( + self, + store: Store, + rank: int, + size: int, + options: Options, + ) -> None: ... + @property + def options(self) -> Options: ... # type: ignore[override] + +def _set_process_group(pg: ProcessGroup) -> None: ... +def _current_process_group() -> ProcessGroup: ... + +class _Request: + def body(self) -> bytes: ... + def get_param(self, str) -> str: ... + +class _Response: + def set_content(self, content: str | bytes, content_type: str) -> None: ... + def set_status(self, status: int) -> None: ... + +def _register_handler( + name: str, handler: Callable[[_Request, _Response], None] +) -> None: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_distributed_rpc.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_distributed_rpc.pyi new file mode 100644 index 0000000000000000000000000000000000000000..48f636d8524637305cd9c758e9f22428d3b055cc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_distributed_rpc.pyi @@ -0,0 +1,188 @@ +# mypy: allow-untyped-defs +# mypy: disable-error-code="type-arg" +from datetime import timedelta +from typing import Any, Generic, overload, TypeVar + +import torch +from torch._C import Future +from torch._C._autograd import ProfilerEvent +from torch._C._distributed_c10d import Store +from torch._C._profiler import ProfilerConfig + +# This module is defined in torch/csrc/distributed/rpc/init.cpp + +_DEFAULT_INIT_METHOD: str +_DEFAULT_NUM_WORKER_THREADS: int +_UNSET_RPC_TIMEOUT: float +_DEFAULT_RPC_TIMEOUT_SEC: float + +_T = TypeVar("_T") + +class RpcBackendOptions: + rpc_timeout: float + init_method: str + def __init__( + self, + rpc_timeout: float = ..., + init_method: str = ..., + ) -> None: ... + +class WorkerInfo: + def __init__(self, name: str, worker_id: int) -> None: ... + @property + def name(self) -> str: ... + @property + def id(self) -> int: ... + def __eq__(self, other: object) -> bool: ... + +class RpcAgent: + def join(self, shutdown: bool = False, timeout: float = 0): ... + def sync(self): ... + def shutdown(self): ... + @overload + def get_worker_info(self) -> WorkerInfo: ... + @overload + def get_worker_info(self, workerName: str) -> WorkerInfo: ... + def get_worker_infos(self) -> list[WorkerInfo]: ... + def _get_device_map(self, dst: WorkerInfo) -> dict[torch.device, torch.device]: ... + def get_debug_info(self) -> dict[str, str]: ... + def get_metrics(self) -> dict[str, str]: ... + +class PyRRef(Generic[_T]): + def __init__(self, value: _T, type_hint: Any = None) -> None: ... + def is_owner(self) -> bool: ... + def confirmed_by_owner(self) -> bool: ... + def owner(self) -> WorkerInfo: ... + def owner_name(self) -> str: ... + def to_here(self, timeout: float = ...) -> _T: ... + def local_value(self) -> Any: ... + def rpc_sync(self, timeout: float = ...) -> Any: ... + def rpc_async(self, timeout: float = ...) -> Any: ... + def remote(self, timeout: float = ...) -> Any: ... + def _serialize(self) -> tuple: ... + @staticmethod + def _deserialize(tp: tuple) -> PyRRef: ... + def _get_type(self) -> type[_T]: ... + def _get_future(self) -> Future[_T]: ... + def _get_profiling_future(self) -> Future[_T]: ... + def _set_profiling_future(self, profilingFuture: Future[_T]): ... + +class _TensorPipeRpcBackendOptionsBase(RpcBackendOptions): + num_worker_threads: int + device_maps: dict[str, dict[torch.device, torch.device]] + devices: list[torch.device] + def __init__( + self, + num_worker_threads: int, + _transports: list | None, + _channels: list | None, + rpc_timeout: float = ..., + init_method: str = ..., + device_maps: dict[str, dict[torch.device, torch.device]] = {}, # noqa: B006 + devices: list[torch.device] = [], # noqa: B006 + ) -> None: ... + def _set_device_map( + self, + to: str, + device_map: dict[torch.device, torch.device], + ): ... + +class TensorPipeAgent(RpcAgent): + def __init__( + self, + store: Store, + name: str, + worker_id: int, + world_size: int | None, + opts: _TensorPipeRpcBackendOptionsBase, + reverse_device_maps: dict[str, dict[torch.device, torch.device]], + devices: list[torch.device], + ) -> None: ... + def join(self, shutdown: bool = False, timeout: float = 0): ... + def shutdown(self): ... + @overload + def get_worker_info(self) -> WorkerInfo: ... + @overload + def get_worker_info(self, workerName: str) -> WorkerInfo: ... + @overload + def get_worker_info(self, id: int) -> WorkerInfo: ... + def get_worker_infos(self) -> list[WorkerInfo]: ... + def _get_device_map(self, dst: WorkerInfo) -> dict[torch.device, torch.device]: ... + def _update_group_membership( + self, + worker_info: WorkerInfo, + my_devices: list[torch.device], + reverse_device_map: dict[str, dict[torch.device, torch.device]], + is_join: bool, + ): ... + def _get_backend_options(self) -> _TensorPipeRpcBackendOptionsBase: ... + @property + def is_static_group(self) -> bool: ... + @property + def store(self) -> Store: ... + +def _is_current_rpc_agent_set() -> bool: ... +def _get_current_rpc_agent() -> RpcAgent: ... +def _set_and_start_rpc_agent(agent: RpcAgent): ... +def _reset_current_rpc_agent(): ... +def _delete_all_user_and_unforked_owner_rrefs(timeout: timedelta = ...): ... +def _destroy_rref_context(ignoreRRefLeak: bool): ... +def _rref_context_get_debug_info() -> dict[str, str]: ... +def _cleanup_python_rpc_handler(): ... +def _invoke_rpc_builtin( + dst: WorkerInfo, + opName: str, + rpcTimeoutSeconds: float, + *args: Any, + **kwargs: Any, +): ... +def _invoke_rpc_python_udf( + dst: WorkerInfo, + pickledPythonUDF: str, + tensors: list[torch.Tensor], + rpcTimeoutSeconds: float, + isAsyncExecution: bool, +): ... +def _invoke_rpc_torchscript( + dstWorkerName: str, + qualifiedNameStr: str, + argsTuple: tuple, + kwargsDict: dict, + rpcTimeoutSeconds: float, + isAsyncExecution: bool, +): ... +def _invoke_remote_builtin( + dst: WorkerInfo, + opName: str, + rpcTimeoutSeconds: float, + *args: Any, + **kwargs: Any, +): ... +def _invoke_remote_python_udf( + dst: WorkerInfo, + pickledPythonUDF: str, + tensors: list[torch.Tensor], + rpcTimeoutSeconds: float, + isAsyncExecution: bool, +): ... +def _invoke_remote_torchscript( + dstWorkerName: WorkerInfo, + qualifiedNameStr: str, + rpcTimeoutSeconds: float, + isAsyncExecution: bool, + *args: Any, + **kwargs: Any, +): ... +def get_rpc_timeout() -> float: ... +def enable_gil_profiling(flag: bool): ... +def _set_rpc_timeout(rpcTimeoutSeconds: float): ... + +class RemoteProfilerManager: + @staticmethod + def set_current_profiling_key(key: str): ... + +def _enable_server_process_global_profiler(new_config: ProfilerConfig): ... +def _disable_server_process_global_profiler() -> list[list[list[ProfilerEvent]]]: ... +def _set_profiler_node_id(default_node_id: int): ... +def _enable_jit_rref_pickle(): ... +def _disable_jit_rref_pickle(): ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_distributed_rpc_testing.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_distributed_rpc_testing.pyi new file mode 100644 index 0000000000000000000000000000000000000000..9313281027dbd89ae65ebe65c95a1d0c38593b80 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_distributed_rpc_testing.pyi @@ -0,0 +1,32 @@ +import torch +from torch._C._distributed_c10d import Store +from torch._C._distributed_rpc import _TensorPipeRpcBackendOptionsBase, TensorPipeAgent + +# This module is defined in torch/csrc/distributed/rpc/testing/init.cpp + +class FaultyTensorPipeRpcBackendOptions(_TensorPipeRpcBackendOptionsBase): + def __init__( + self, + num_worker_threads: int, + rpc_timeout: float, + init_method: str, + messages_to_fail: list[str], + messages_to_delay: dict[str, float], + num_fail_sends: int, + ) -> None: ... + num_send_recv_threads: int + messages_to_fail: list[str] + messages_to_delay: dict[str, float] + num_fail_sends: int + +class FaultyTensorPipeAgent(TensorPipeAgent): + def __init__( + self, + store: Store, + name: str, + rank: int, + world_size: int, + options: FaultyTensorPipeRpcBackendOptions, + reverse_device_maps: dict[str, dict[torch.device, torch.device]], + devices: list[torch.device], + ) -> None: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_dynamo/__init__.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_dynamo/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..67d515697cbe4b43edb18dbdc4cf0270ebf13fb2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_dynamo/__init__.pyi @@ -0,0 +1,4 @@ +from . import compiled_autograd, eval_frame, guards # noqa: F401 + +def strip_function_call(name: str) -> str: ... +def is_valid_var_name(name: str) -> bool | int: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_dynamo/compiled_autograd.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_dynamo/compiled_autograd.pyi new file mode 100644 index 0000000000000000000000000000000000000000..ef24582b5023109733955cc77db0a84fae03b3fd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_dynamo/compiled_autograd.pyi @@ -0,0 +1,13 @@ +from collections.abc import Callable + +from torch import Tensor +from torch._dynamo.compiled_autograd import AutogradCompilerInstance + +def set_autograd_compiler( + autograd_compiler: Callable[[], AutogradCompilerInstance] | None, + dynamic: bool, +) -> tuple[Callable[[], AutogradCompilerInstance] | None, bool]: ... +def clear_cache() -> None: ... +def is_cache_empty() -> bool: ... +def set_verbose_logger(fn: Callable[[str], None] | None) -> bool: ... +def call_cpp_tensor_pre_hooks(idx: int, grad: Tensor) -> Tensor: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_dynamo/eval_frame.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_dynamo/eval_frame.pyi new file mode 100644 index 0000000000000000000000000000000000000000..641aaece6269c51fd94edc0ed0ceb2ac51a8b62c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_dynamo/eval_frame.pyi @@ -0,0 +1,84 @@ +import enum +import types +from collections.abc import Callable +from typing import Optional, overload + +from torch._dynamo.guards import GuardManagerWrapper +from torch._dynamo.types import DynamoCallback, DynamoGuardCompleteHook, DynamoGuardHook +from torch._guards import CompileId + +def set_eval_frame(callback: DynamoCallback) -> DynamoCallback: ... +def set_skip_guard_eval_unsafe(value: bool) -> bool: ... +def get_eval_frame_callback() -> DynamoCallback: ... +def reset_code(code: types.CodeType) -> None: ... +def unsupported(obj1: object, obj2: object) -> object: ... +def set_code_exec_strategy( + code: types.CodeType, strategy: _FrameExecStrategy +) -> None: ... +def set_guard_error_hook(hook: DynamoGuardHook) -> None: ... +def set_guard_complete_hook( + hook: Optional[DynamoGuardCompleteHook], +) -> Optional[DynamoGuardCompleteHook]: ... +def raise_sigtrap() -> None: ... +def set_c_recursion_limit(limit: int) -> None: ... +def get_c_recursion_limit() -> int: ... + +class _CacheEntry: + def check_fn(self, *args: object, **kwargs: object) -> bool: ... + def update_diff_guard_root_manager(self) -> None: ... + code: types.CodeType + compile_id: CompileId + # If we run into circular issues, just use object + guard_manager: GuardManagerWrapper + backend: Callable + next: _CacheEntry | None + +class _PrecompileEntry: + guard_manager: GuardManagerWrapper + +class _ExtraState: + def invalidate( + self, cache_entry: _CacheEntry, guard_manager: GuardManagerWrapper + ) -> None: ... + +class _FrameAction(enum.IntEnum): + DEFAULT = 0 + SKIP = 1 + RUN_ONLY = 2 + +class _FrameExecStrategy: + cur_action: _FrameAction + recursive_action: _FrameAction + + @overload + def __init__(self) -> None: ... + @overload + def __init__( + self, cur_action: _FrameAction, recursive_action: _FrameAction + ) -> None: ... + +# This is an object that encapsulates the Python FrameType, and exposes +# properties Dynamo cares about for a frame. +class _PyInterpreterFrame: + f_code: types.CodeType + f_locals: dict[str, object] + f_globals: dict[str, object] + f_builtins: dict[str, object] + f_lasti: int + f_lineno: int + f_back: types.FrameType + # A tuple containing cell objects captured by this frame. + closure: tuple[types.CellType] + +def _debug_get_cache_entry_list(code: types.CodeType) -> list[_CacheEntry]: ... + +py_opcode_caches: list[int] + +def code_framelocals_names(code: types.CodeType) -> tuple[str, ...]: ... +def _load_precompile_entry( + code: types.CodeType, + guard_manager: GuardManagerWrapper, + dynamo_code: types.CodeType, +) -> None: ... +def _reset_precompile_entries(code: types.CodeType) -> None: ... +def _debug_get_precompile_entries(code: types.CodeType) -> list[_PrecompileEntry]: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_dynamo/guards.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_dynamo/guards.pyi new file mode 100644 index 0000000000000000000000000000000000000000..e3003f0e97b12b58f65454ccaeb82d305f884233 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_dynamo/guards.pyi @@ -0,0 +1,452 @@ +import enum +from collections.abc import Callable +from typing import Any, Optional, TypeAlias + +import torch + +# TODO: We should move the `GuardManagerType` +# defined in `guards.py` here and update other +# imports +GuardManagerType: TypeAlias = enum.Enum + +class GlobalStateGuard: + def check(self) -> bool: ... + def reason(self) -> str: ... + +class LeafGuard: + def verbose_code_parts(self) -> list[str]: ... + +class RelationalGuard: ... + +class GuardDebugInfo: + verbose_code_parts: list[str] + result: bool + num_guards_executed: int + +class GuardManager: + def check(self, value: Any) -> bool: ... + def check_verbose(self, value: Any) -> GuardDebugInfo: ... + + # Accessors + def globals_dict_manager( + self, + f_globals: dict[str, Any], + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def framelocals_manager( + self, + key: tuple[str, int], + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def dict_getitem_manager( + self, + key: Any, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def grad_manager( + self, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def generic_getattr_manager( + self, + attr: str, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def getitem_manager( + self, + key: Any, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def get_generic_dict_manager( + self, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def list_getitem_manager( + self, + key: Any, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def tuple_getitem_manager( + self, + key: Any, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def set_getitem_manager( + self, + index: Any, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def func_defaults_manager( + self, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def func_kwdefaults_manager( + self, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def tuple_iterator_getitem_manager( + self, + index: Any, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def weakref_call_manager( + self, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def call_function_no_args_manager( + self, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def global_weakref_manager( + self, + global_name: str, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def type_manager( + self, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def getattr_manager( + self, + attr: str, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def tensor_property_size_manager( + self, + idx: int, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def tensor_property_shape_manager( + self, + idx: int, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def tensor_property_storage_offset_manager( + self, + idx: int, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def indexed_manager( + self, + idx: int, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def lambda_manager( + self, + python_lambda: Callable[..., Any], + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def get_root(self) -> RootGuardManager: ... + def get_source(self) -> str: ... + def fail_count(self) -> int: ... + def get_child_managers(self) -> list[GuardManager]: ... + def repr(self) -> str: ... + def type_of_guarded_value(self) -> str: ... + def get_leaf_guards(self) -> list[LeafGuard]: ... + def get_accessors(self) -> list[GuardManager]: ... + def is_guarded_value_immutable(self) -> bool: ... + def is_tag_safe(self) -> bool: ... + def is_tag_safe_root(self) -> bool: ... + def has_no_accessors(self) -> bool: ... + def has_object_aliasing_guard(self) -> bool: ... + def get_type_of_guarded_value(self) -> type: ... + def type_dict_manager( + self, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def type_mro_manager( + self, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def code_manager( + self, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def closure_manager( + self, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + # Leaf guards + def add_lambda_guard( + self, user_lambda: Callable[..., Any], verbose_code_parts: list[str] + ) -> None: ... + def add_id_match_guard( + self, id_val: int, verbose_code_parts: list[str] + ) -> None: ... + def add_equals_match_guard( + self, + equals_val: Any, + verbose_code_parts: list[str], + ) -> None: ... + def add_global_state_guard( + self, initial_state: Any, verbose_code_parts: list[str] + ) -> None: ... + def add_torch_function_mode_stack_guard( + self, initial_stack: list[Any], verbose_code_parts: list[str] + ) -> None: ... + def add_mapping_keys_guard( + self, value: Any, verbose_code_parts: list[str] + ) -> None: ... + def add_dict_length_check_guard( + self, value: int, verbose_code_parts: list[str] + ) -> None: ... + def add_length_check_guard( + self, value: int, verbose_code_parts: list[str] + ) -> None: ... + def add_true_match_guard( + self, + verbose_code_parts: list[str], + ) -> None: ... + def add_false_match_guard( + self, + verbose_code_parts: list[str], + ) -> None: ... + def add_none_match_guard( + self, + verbose_code_parts: list[str], + ) -> None: ... + def add_not_none_guard( + self, + verbose_code_parts: list[str], + ) -> None: ... + def add_dispatch_key_set_guard( + self, + dispatch_key: Any, + verbose_code_parts: list[str], + ) -> None: ... + def add_tensor_match_guard( + self, + value: Any, + sizes: list[int], + strides: list[int], + tensor_name: str, + verbose_code_parts: list[str], + ptype: Any, + dispatch_keys: Any, + ) -> None: ... + def add_dynamic_indices_guard( + self, + value: set[Any], + verbose_code_parts: list[str], + ) -> None: ... + def add_no_hasattr_guard( + self, + attr_name: str, + verbose_code_parts: list[str], + ) -> None: ... + def add_dict_contains_guard( + self, + contains: bool, + key: Any, + verbose_code_parts: list[str], + ) -> None: ... + def add_type_match_guard( + self, + value: int, + verbose_code_parts: list[str], + ) -> None: ... + def add_dict_version_guard( + self, + value: Any, + verbose_code_parts: list[str], + ) -> None: ... + def add_set_contains_guard( + self, + contains: bool, + item: Any, + verbose_code_parts: list[str], + ) -> None: ... + def add_dual_level_match_guard( + self, + level: int, + verbose_code_parts: list[str], + ) -> None: ... + def add_float_is_nan_guard( + self, + verbose_code_parts: list[str], + ) -> None: ... + def add_complex_is_nan_guard( + self, + verbose_code_parts: list[str], + ) -> None: ... + def add_tuple_iterator_length_guard( + self, + length: int, + type_id: int, + verbose_code_parts: list[str], + ) -> None: ... + def add_range_iterator_match_guard( + self, + start: int, + stop: int, + step: int, + type_id: int, + verbose_code_parts: list[str], + ) -> None: ... + def add_default_device_guard( + self, + verbose_code_parts: list[str], + ) -> None: ... + def mark_tag_safe(self) -> None: ... + def mark_tag_safe_root(self) -> None: ... + +class RootGuardManager(GuardManager): + def get_epilogue_lambda_guards(self) -> list[LeafGuard]: ... + def add_epilogue_lambda_guard( + self, + guard: LeafGuard, + verbose_code_parts: list[str], + ) -> None: ... + def clone_manager( + self, clone_filter_fn: Callable[[GuardManager], bool] + ) -> RootGuardManager: ... + def attach_compile_id(self, compile_id: str) -> None: ... + +class DictGuardManager(GuardManager): + def get_key_manager( + self, + index: int, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def get_value_manager( + self, + index: int, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def get_key_value_managers( + self, + ) -> dict[int, tuple[GuardManager, GuardManager]]: ... + +# Guard accessor stubs +class GuardAccessor: ... +class DictGetItemGuardAccessor(GuardAccessor): ... +class GetGenericDictGuardAccessor(GuardAccessor): ... +class TypeDictGuardAccessor(GuardAccessor): ... +class TypeMROGuardAccessor(GuardAccessor): ... +class ClosureGuardAccessor(GuardAccessor): ... +class TupleGetItemGuardAccessor(GuardAccessor): ... +class TypeGuardAccessor(GuardAccessor): ... +class CodeGuardAccessor(GuardAccessor): ... +class FuncDefaultsGuardAccessor(GuardAccessor): ... +class FuncKwDefaultsGuardAccessor(GuardAccessor): ... + +class GetAttrGuardAccessor(GuardAccessor): + def get_attr_name(self) -> str: ... + +def install_object_aliasing_guard( + x: GuardManager, + y: GuardManager, + verbose_code_parts: list[str], +) -> None: ... +def install_no_tensor_aliasing_guard( + guard_managers: list[GuardManager], + tensor_names: list[str], + verbose_code_parts: list[str], +) -> None: ... +def install_storage_overlapping_guard( + overlapping_guard_managers: list[GuardManager], + non_overlapping_guard_managers: list[GuardManager], + verbose_code_parts: list[str], +) -> None: ... +def install_symbolic_shape_guard( + guard_managers: list[GuardManager], + nargs_int: int, + nargs_float: int, + py_addr: int, + py_addr_keep_alive: Any, + verbose_code_parts: list[str], +) -> None: ... +def profile_guard_manager( + guard_manager: GuardManager, + f_locals: dict[str, Any], + n_iters: int, +) -> float: ... + +class TensorGuards: + def __init__( + self, + *, + dynamic_dims_sizes: list[torch.SymInt | None] | None = None, + dynamic_dims_strides: list[torch.SymInt | None] | None = None, + ) -> None: ... + def check(self, *args: Any) -> bool: ... + def check_verbose( + self, *args: Any, tensor_check_names: Optional[list[str]] = None + ) -> bool | str: ... + +def assert_size_stride( + item: torch.Tensor, + size: torch.types._size, + stride: torch.types._size, + op_name: str | None = None, +) -> None: ... +def assert_alignment( + item: torch.Tensor, + alignment: int, + op_name: str | None = None, +) -> None: ... +def check_obj_id(obj: object, expected: int) -> bool: ... +def check_type_id(obj: object, expected: int) -> bool: ... +def dict_version(d: dict[Any, Any]) -> int: ... +def compute_overlapping_tensors( + tensors: list[torch.Tensor], symbolic: bool = True +) -> set[int]: ... +def set_is_in_mode_without_ignore_compile_internals(value: bool) -> None: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_export/__init__.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_export/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..039f9c22eea620bc9675d233684df72c7ac4471c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_export/__init__.pyi @@ -0,0 +1,9 @@ +# Defined in torch/csrc/export/pybind.cpp +class CppExportedProgram: ... + +def deserialize_exported_program( + serialized_program: str, +) -> CppExportedProgram: ... +def serialize_exported_program( + cpp_exported_program: CppExportedProgram, +) -> str: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_export/pt2_archive_constants.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_export/pt2_archive_constants.pyi new file mode 100644 index 0000000000000000000000000000000000000000..f7a92ddd0c961513d42949e8c2c4b18fcadcc8cc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_export/pt2_archive_constants.pyi @@ -0,0 +1,25 @@ +# Defined in torch/csrc/export/pt2_archive_constants.h + +ARCHIVE_ROOT_NAME: str = ... +ARCHIVE_FORMAT_PATH: str = ... +ARCHIVE_FORMAT_VALUE: str = ... +ARCHIVE_VERSION_PATH: str = ... +ARCHIVE_VERSION_VALUE: str = ... +MODELS_DIR: str = ... +MODELS_FILENAME_FORMAT: str = ... +AOTINDUCTOR_DIR: str = ... +MTIA_DIR: str = ... +WEIGHTS_DIR: str = ... +WEIGHTS_CONFIG_FILENAME_FORMAT: str = ... +WEIGHT_FILENAME_PREFIX: str = ... +CONSTANTS_DIR: str = ... +CONSTANTS_CONFIG_FILENAME_FORMAT: str = ... +TENSOR_CONSTANT_FILENAME_PREFIX: str = ... +CUSTOM_OBJ_FILENAME_PREFIX: str = ... +SAMPLE_INPUTS_DIR: str = ... +SAMPLE_INPUTS_FILENAME_FORMAT: str = ... +EXECUTORCH_DIR: str = ... +EXTRA_DIR: str = ... +MODULE_INFO_PATH: str = ... +XL_MODEL_WEIGHTS_DIR: str = ... +XL_MODEL_WEIGHTS_PARAM_CONFIG_PATH: str = ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_functionalization.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_functionalization.pyi new file mode 100644 index 0000000000000000000000000000000000000000..4e00df97e2717c1d3c63db3fc42e31507211eb99 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_functionalization.pyi @@ -0,0 +1,16 @@ +from torch import Tensor +from torch.types import _bool + +# Defined in torch/csrc/functionalization/Module.cpp + +class ViewMeta: + has_symbolic_inputs: _bool + +# Returns the list of ViewMeta instances of the given functional tensor. +# +# Although we do have python bindings for their types, we won't +# expose them here, since they should not be used by users. +def get_view_meta_sequence(tensor: Tensor) -> list[ViewMeta]: ... + +# Applies the ViewMeta sequence on top of the given base. +def apply_view_meta_sequence(base: Tensor, sequence: list[ViewMeta]) -> Tensor: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_functions.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_functions.pyi new file mode 100644 index 0000000000000000000000000000000000000000..5b0dee51a71093f1245887aa13c2405d3f2e5720 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_functions.pyi @@ -0,0 +1,19 @@ +from typing import AnyStr, overload + +from torch import Tensor + +class UndefinedGrad: + def __init__(self) -> None: ... + def __call__(self, *inputs: Tensor) -> list[Tensor]: ... + +class DelayedError: + def __init__(self, msg: AnyStr, num_inputs: int) -> None: ... + + # __call__ should really be a higher-kinded type: + # def __call__(self, arg: Tensor) -> Tensor: ... + # def __call__(self, *args: Tensor * num_inputs) -> Tuple[Tensor * num_inputs]: ... + + @overload + def __call__(self, i0: Tensor) -> Tensor: ... + @overload + def __call__(self, *args: Tensor) -> tuple[Tensor, ...]: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_functorch.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_functorch.pyi new file mode 100644 index 0000000000000000000000000000000000000000..a35befcad392d1607bc9b25345fa466829345623 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_functorch.pyi @@ -0,0 +1,89 @@ +# mypy: allow-untyped-defs +from enum import Enum + +from torch import Tensor + +# Defined in torch/csrc/functorch/init.cpp + +def set_inplace_requires_grad_allowed(allowed: bool) -> None: ... +def get_inplace_requires_grad_allowed() -> bool: ... +def _set_dynamic_layer_keys_included(included: bool) -> None: ... +def get_unwrapped(tensor: Tensor) -> Tensor: ... +def is_batchedtensor(tensor: Tensor) -> bool: ... +def is_functionaltensor(tensor: Tensor) -> bool: ... +def is_functorch_wrapped_tensor(tensor: Tensor) -> bool: ... +def is_gradtrackingtensor(tensor: Tensor) -> bool: ... +def is_legacy_batchedtensor(tensor: Tensor) -> bool: ... +def maybe_get_bdim(tensor: Tensor) -> int: ... +def maybe_get_level(tensor: Tensor) -> int: ... +def maybe_current_level() -> int | None: ... +def unwrap_if_dead(tensor: Tensor) -> Tensor: ... +def _unwrap_for_grad(tensor: Tensor, level: int) -> Tensor: ... +def _wrap_for_grad(tensor: Tensor, level: int) -> Tensor: ... +def _unwrap_batched(tensor: Tensor, level: int) -> tuple[Tensor, int | None]: ... +def current_level() -> int: ... +def count_jvp_interpreters() -> int: ... +def _add_batch_dim(tensor: Tensor, bdim: int, level: int) -> Tensor: ... +def _maybe_unsafe_set_level(tensor: Tensor, level: int) -> None: ... +def set_single_level_autograd_function_allowed(allowed: bool) -> None: ... +def get_single_level_autograd_function_allowed() -> bool: ... +def _unwrap_functional_tensor(tensor: Tensor, reapply_views: bool) -> Tensor: ... +def _wrap_functional_tensor(tensor: Tensor, level: int) -> Tensor: ... +def _vmap_increment_nesting(batch_size: int, randomness: str) -> int: ... +def _vmap_decrement_nesting() -> int: ... +def _grad_increment_nesting() -> int: ... +def _grad_decrement_nesting() -> int: ... +def _jvp_increment_nesting() -> int: ... +def _jvp_decrement_nesting() -> int: ... + +# Defined in aten/src/ATen/functorch/Interpreter.h +class TransformType(Enum): + Torch = ... + Vmap = ... + Grad = ... + Jvp = ... + Functionalize = ... + +class RandomnessType(Enum): + Error = ... + Same = ... + Different = ... + +class CInterpreter: + def key(self) -> TransformType: ... + def level(self) -> int: ... + def serialize(self) -> bytes: ... + @staticmethod + def deserialize(bytes) -> CInterpreter: ... + +class CGradInterpreterPtr: + def __init__(self, interpreter: CInterpreter) -> None: ... + def lift(self, Tensor) -> Tensor: ... + def prevGradMode(self) -> bool: ... + +class CJvpInterpreterPtr: + def __init__(self, interpreter: CInterpreter) -> None: ... + def lift(self, Tensor) -> Tensor: ... + def prevFwdGradMode(self) -> bool: ... + +class CFunctionalizeInterpreterPtr: + def __init__(self, interpreter: CInterpreter) -> None: ... + def key(self) -> TransformType: ... + def level(self) -> int: ... + def functionalizeAddBackViews(self) -> bool: ... + +class CVmapInterpreterPtr: + def __init__(self, interpreter: CInterpreter) -> None: ... + def key(self) -> TransformType: ... + def level(self) -> int: ... + def batchSize(self) -> int: ... + def randomness(self) -> RandomnessType: ... + +class DynamicLayer: ... + +def get_dynamic_layer_stack_depth() -> int: ... +def get_interpreter_stack() -> list[CInterpreter]: ... +def peek_interpreter_stack() -> CInterpreter: ... +def pop_dynamic_layer_stack() -> DynamicLayer: ... +def pop_dynamic_layer_stack_and_undo_to_depth(int) -> None: ... +def push_dynamic_layer_stack(dl: DynamicLayer) -> int: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_instruction_counter.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_instruction_counter.pyi new file mode 100644 index 0000000000000000000000000000000000000000..4e3c27567eb228b8763a6d2578db827b1ffbde41 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_instruction_counter.pyi @@ -0,0 +1,4 @@ +# Defined in torch/csrc/instruction_counter/Module.cpp + +def start() -> int: ... +def end(id: int) -> int: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_itt.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_itt.pyi new file mode 100644 index 0000000000000000000000000000000000000000..8a54437f527b994821133532f26598c951631b28 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_itt.pyi @@ -0,0 +1,5 @@ +# Defined in torch/csrc/itt.cpp +def is_available() -> None: ... +def rangePush(message: str) -> None: ... +def rangePop() -> None: ... +def mark(message: str) -> None: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_jit_tree_views.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_jit_tree_views.pyi new file mode 100644 index 0000000000000000000000000000000000000000..cf4cffc05a9c3414a60309da2ee8e1aec3dea2d0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_jit_tree_views.pyi @@ -0,0 +1,202 @@ +from typing import Any, Optional + +# Defined in torch/csrc/jit/python/python_tree_views.cpp + +class SourceRange: + def highlight(self) -> str: ... + @property + def start(self) -> int: ... + @property + def end(self) -> int: ... + +class SourceRangeFactory: + def __init__( + self, + text: str, + filename: Any, + file_lineno: int, + leading_whitespace_chars: int, + ) -> None: ... + def make_range(self, line: int, start_col: int, end_col: int) -> SourceRange: ... + def make_raw_range(self, start: int, end: int) -> SourceRange: ... + @property + def source(self) -> str: ... + +class TreeView: + def range(self) -> SourceRange: ... + def dump(self) -> None: ... + +class Ident(TreeView): + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + @property + def name(self) -> str: ... + +class Param(TreeView): + def __init__(self, type: Optional[Any], name: Ident, kwarg_only: bool) -> None: ... + +class Attribute(TreeView): + def __init__(self, name: Ident, value: Any) -> None: ... + +# Literals +def TrueLiteral(range: SourceRange) -> Any: ... +def FalseLiteral(range: SourceRange) -> Any: ... +def NoneLiteral(range: SourceRange) -> Any: ... + +# Tree nodes +class Stmt(TreeView): + def __init__(self, thing: TreeView) -> None: ... + +class Expr(TreeView): ... + +class Def(TreeView): + def __init__(self, name: Ident, decl: Any, body: list[Stmt]) -> None: ... + def decl(self) -> Any: ... + def name(self) -> Ident: ... + +class Property(TreeView): + def __init__( + self, r: SourceRange, name: Ident, getter: Def, setter: Optional[Def] + ) -> None: ... + def name(self) -> Ident: ... + def getter_name(self) -> str: ... + def setter_name(self) -> Optional[Ident]: ... + +class ClassDef(TreeView): + def __init__( + self, name: Ident, body: list[Stmt], props: list[Property], assigns: list[Any] + ) -> None: ... + +class Decl(TreeView): + def __init__( + self, r: SourceRange, params: list[Param], return_type: Optional[Expr] + ) -> None: ... + +class Delete(Stmt): + def __init__(self, range: SourceRange, targets: list[Expr]) -> None: ... + +class WithItem(Expr): + def __init__( + self, range: SourceRange, target: Expr, var: Optional[Any] + ) -> None: ... + +class Assign(Stmt): + def __init__( + self, lhs: list[Expr], rhs: Expr, type: Optional[Expr] = None + ) -> None: ... + +class AugAssign(Stmt): + def __init__(self, lhs: Expr, kind_str: str, rhs: Expr) -> None: ... + +class Return(Stmt): + def __init__(self, range: SourceRange, value: Optional[Expr]) -> None: ... + +class Raise(Stmt): + def __init__(self, range: SourceRange, expr: Expr) -> None: ... + +class Assert(Stmt): + def __init__(self, range: SourceRange, test: Expr, msg: Optional[Expr]) -> None: ... + +class Pass(Stmt): + def __init__(self, range: SourceRange) -> None: ... + +class Break(Stmt): ... +class Continue(Stmt): ... + +class Dots(Expr, TreeView): + def __init__(self, range: SourceRange) -> None: ... + +class If(Stmt): + def __init__( + self, + range: SourceRange, + cond: Expr, + true_branch: list[Stmt], + false_branch: list[Stmt], + ) -> None: ... + +class While(Stmt): + def __init__(self, range: SourceRange, cond: Expr, body: list[Stmt]) -> None: ... + +class With(Stmt): + def __init__( + self, range: SourceRange, targets: list[WithItem], body: list[Stmt] + ) -> None: ... + +class For(Stmt): + def __init__( + self, + range: SourceRange, + targets: list[Expr], + itrs: list[Expr], + body: list[Stmt], + ) -> None: ... + +class ExprStmt(Stmt): + def __init__(self, expr: Expr) -> None: ... + +class Var(Expr): + def __init__(self, name: Ident) -> None: ... + @property + def name(self) -> str: ... + +class BinOp(Expr): + def __init__(self, kind: str, lhs: Expr, rhs: Expr) -> None: ... + +class UnaryOp(Expr): + def __init__(self, range: SourceRange, kind: str, expr: Expr) -> None: ... + +class Const(Expr): + def __init__(self, range: SourceRange, value: str) -> None: ... + +class StringLiteral(Expr): + def __init__(self, range: SourceRange, value: str) -> None: ... + +class Apply(Expr): + def __init__( + self, expr: Expr, args: list[Expr], kwargs: list[Attribute] + ) -> None: ... + +class Select(Expr): + def __init__(self, expr: Expr, field: Ident) -> None: ... + +class TernaryIf(Expr): + def __init__(self, cond: Expr, true_expr: Expr, false_expr: Expr) -> None: ... + +class ListComp(Expr): + def __init__( + self, range: SourceRange, elt: Expr, target: Expr, iter: Expr + ) -> None: ... + +class DictComp(Expr): + def __init__( + self, range: SourceRange, key: Expr, value: Expr, target: Expr, iter: Expr + ) -> None: ... + +class ListLiteral(Expr): + def __init__(self, range: SourceRange, args: list[Expr]) -> None: ... + +class TupleLiteral(Expr): + def __init__(self, range: SourceRange, args: list[Expr]) -> None: ... + +class DictLiteral(Expr): + def __init__( + self, range: SourceRange, keys: list[Expr], values: list[Expr] + ) -> None: ... + +class Subscript(Expr): + def __init__(self, base: Expr, subscript_exprs: list[Expr]) -> None: ... + +class SliceExpr(Expr): + def __init__( + self, + range: SourceRange, + lower: Optional[Expr], + upper: Optional[Expr], + step: Optional[Expr], + ) -> None: ... + +class Starred(Expr): + def __init__(self, range: SourceRange, expr: Expr) -> None: ... + +class EmptyTypeAnnotation(TreeView): + def __init__(self, range: SourceRange) -> None: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_lazy.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_lazy.pyi new file mode 100644 index 0000000000000000000000000000000000000000..c6b2b89fa3a9e89d889d9248097315d7c9d8635c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_lazy.pyi @@ -0,0 +1,26 @@ +from torch import Tensor + +# defined in torch/csrc/lazy/python/init.cpp +def _mark_step(device: str, devices: list[str], wait: bool) -> None: ... +def _wait_device_ops(devices: list[str]) -> None: ... +def _reset_metrics() -> None: ... +def _counter_names() -> list[str]: ... +def _counter_value(name: str) -> int: ... +def _metrics_report() -> str: ... +def _get_graph_hash(tensors: list[Tensor]) -> str: ... +def _sync_multi( + tensors: list[Tensor], + devices: list[str], + wait: bool = True, + sync_ltc_data: bool = True, +) -> None: ... +def _get_tensor_id(tensor: Tensor) -> int: ... +def _get_tensors_text(tensors: list[Tensor]) -> str: ... +def _get_tensors_dot(tensors: list[Tensor]) -> str: ... +def _get_tensors_backend(tensors: list[Tensor]) -> str: ... +def _get_force_fallback() -> str: ... +def _set_force_fallback(newval: str) -> None: ... +def _clear_ir_cache() -> None: ... +def _dump_ir_cache(filename: str) -> None: ... +def _set_reuse_ir(val: bool) -> None: ... +def _get_default_device_type() -> str: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_lazy_ts_backend.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_lazy_ts_backend.pyi new file mode 100644 index 0000000000000000000000000000000000000000..cd1bef2de069dfc93cd2b6243ab97d550d75f086 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_lazy_ts_backend.pyi @@ -0,0 +1,12 @@ +# mypy: allow-untyped-defs +# defined in torch/csrc/lazy/python/init.cpp + +from typing import Any + +from torch import Tensor + +def _init(): ... +def _get_tensors_ts_device_data_node( + tensors: list[Tensor], +) -> tuple[list[int], list[Any]]: ... +def _run_cached_graph(hash_str: str, graph_inputs: list[Any]) -> list[Tensor]: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_monitor.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_monitor.pyi new file mode 100644 index 0000000000000000000000000000000000000000..82f2a3e4427038dcb0616d7b305c7c5c85c97606 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_monitor.pyi @@ -0,0 +1,58 @@ +# Defined in torch/csrc/monitor/python_init.cpp + +import datetime +from collections.abc import Callable +from enum import Enum +from types import TracebackType + +class Aggregation(Enum): + VALUE = ... + MEAN = ... + COUNT = ... + SUM = ... + MAX = ... + MIN = ... + +class Stat: + name: str + count: int + def __init__( + self, + name: str, + aggregations: list[Aggregation], + window_size: int, + max_samples: int = -1, + ) -> None: ... + def add(self, v: float) -> None: ... + def get(self) -> dict[Aggregation, float]: ... + +class Event: + name: str + timestamp: datetime.datetime + data: dict[str, int | float | bool | str] + def __init__( + self, + name: str, + timestamp: datetime.datetime, + data: dict[str, int | float | bool | str], + ) -> None: ... + +def log_event(e: Event) -> None: ... + +class EventHandlerHandle: ... + +def register_event_handler(handler: Callable[[Event], None]) -> EventHandlerHandle: ... +def unregister_event_handler(handle: EventHandlerHandle) -> None: ... + +class _WaitCounterTracker: + def __enter__(self) -> None: ... + def __exit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: TracebackType | None = None, + ) -> None: ... + +class _WaitCounter: + def __init__(self, key: str) -> None: ... + def guard(self) -> _WaitCounterTracker: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_nn.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_nn.pyi new file mode 100644 index 0000000000000000000000000000000000000000..b4e82e847108c9a613a87f26ca89eb79c63f6e9d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_nn.pyi @@ -0,0 +1,341 @@ +# @generated by tools/pyi/gen_pyi.py from torch/_C/_nn.pyi.in +# mypy: disable-error-code="type-arg" + +from collections.abc import Sequence +from typing import Literal, overload + +from torch import memory_format, Tensor +from torch.types import _bool, _device, _dtype, _int, _size + +# Defined in tools/autograd/templates/python_nn_functions.cpp + +def adaptive_avg_pool2d(input: Tensor, output_size: _int | _size) -> Tensor: ... +def adaptive_avg_pool3d(input: Tensor, output_size: _int | _size) -> Tensor: ... +def adaptive_max_pool2d( + input: Tensor, + output_size: _int | _size, +) -> tuple[Tensor, Tensor]: ... +def adaptive_max_pool3d( + input: Tensor, + output_size: _int | _size, +) -> tuple[Tensor, Tensor]: ... +def avg_pool2d( + input: Tensor, + kernel_size: _int | _size, + stride: _int | _size | None = None, + padding: _int | _size = 0, + ceil_mode: bool = False, + count_include_pad: bool = True, + divisor_override: int | None = None, +) -> Tensor: ... +def avg_pool3d( + input: Tensor, + kernel_size: _int | _size, + stride: _int | _size | None = None, + padding: _int | _size = 0, + ceil_mode: bool = False, + count_include_pad: bool = True, + divisor_override: int | None = None, +) -> Tensor: ... +def binary_cross_entropy( + input: Tensor, + target: Tensor, + weight: Tensor | None = None, + reduction: str = ..., +) -> Tensor: ... +def col2im( + input: Tensor, + output_size: _int | _size, + kernel_size: _int | _size, + dilation: _int | _size, + stride: _int | _size | None = None, + padding: _int | _size = 0, +) -> Tensor: ... +def cross_entropy_loss( + input: Tensor, + target: Tensor, + weight: Tensor | None = None, + reduction: str = ..., + ignore_index: int = -100, + label_smoothing: float = 0.0, +) -> Tensor: ... +def elu( + input: Tensor, + alpha: float = 1.0, + scale: float = 1.0, + input_scale: float = 1.0, +) -> Tensor: ... +def elu_(input: Tensor, alpha: float = ...) -> Tensor: ... +def fractional_max_pool2d( + input: Tensor, + kernel_size: _int | _size, + output_size: _int | _size, + _random_samples: Tensor, +) -> tuple[Tensor, Tensor]: ... +def fractional_max_pool3d( + input: Tensor, + kernel_size: _int | _size, + output_size: _int | _size, + _random_samples: Tensor, +) -> tuple[Tensor, Tensor]: ... +def gelu(input: Tensor, approximate: str = ...) -> Tensor: ... +def glu(input: Tensor, dim: int = -1) -> Tensor: ... +def hardsigmoid(input: Tensor, *, out: Tensor | None = None) -> Tensor: ... +def hardsigmoid_(input: Tensor) -> Tensor: ... +def hardswish(input: Tensor) -> Tensor: ... +def hardswish_(input: Tensor) -> Tensor: ... +def hardtanh( + input: Tensor, + min_val: float = ..., + max_val: float = ..., + *, + out: Tensor | None = None, +) -> Tensor: ... +def hardtanh_( + input: Tensor, + min_val: float = ..., + max_val: float = ..., +) -> Tensor: ... +def huber_loss( + input: Tensor, + target: Tensor, + reduction: str = ..., + delta: float = 1.0, +) -> Tensor: ... +def im2col( + input: Tensor, + kernel_size: _int | _size, + dilation: _int | _size, + padding: _int | _size, + stride: _int | _size, +) -> Tensor: ... +def l1_loss(input: Tensor, target: Tensor, reduction: str = ...) -> Tensor: ... +def leaky_relu( + input: Tensor, + negative_slope: float = ..., + *, + out: Tensor | None = None, +) -> Tensor: ... +def leaky_relu_(input: Tensor, negative_slope: float = ...) -> Tensor: ... +def linear( + input: Tensor, + weight: Tensor, + bias: Tensor | None = None, +) -> Tensor: ... +def log_sigmoid(input: Tensor) -> Tensor: ... +def max_pool2d_with_indices( + input: Tensor, + kernel_size: _int | _size, + stride: _int | _size | None = None, + padding: _int | _size = 0, + dilation: _int | _size = 1, + ceil_mode: bool = False, +) -> tuple[Tensor, Tensor]: ... +def max_pool3d_with_indices( + input: Tensor, + kernel_size: _int | _size, + stride: _int | _size | None = None, + padding: _int | _size = 0, + dilation: _int | _size = 1, + ceil_mode: bool = False, +) -> tuple[Tensor, Tensor]: ... +def max_unpool2d( + input: Tensor, + indices: Tensor, + output_size: Sequence[int] | None, +) -> Tensor: ... +def max_unpool3d( + input: Tensor, + indices: Tensor, + output_size: Sequence[int] | None, + stride: _int | _size, + padding: _int | _size, +) -> Tensor: ... +def mish(input: Tensor) -> Tensor: ... +def mish_(input: Tensor) -> Tensor: ... +def mse_loss(input: Tensor, target: Tensor, reduction: str = ...) -> Tensor: ... +def multi_margin_loss( + input: Tensor, + target: Tensor, + p: float = 1.0, + margin: float = 1.0, + weight: Tensor | None = None, + reduction: str = ..., +) -> Tensor: ... +def multilabel_margin_loss( + input: Tensor, + target: Tensor, + reduction: str = ..., +) -> Tensor: ... +def nll_loss_nd( + input: Tensor, + target: Tensor, + weight: Tensor | None = None, + reduction: str = ..., + ignore_index: int = -100, +) -> Tensor: ... +def one_hot(tensor: Tensor, num_classes: int = ...) -> Tensor: ... +def pad( + input: Tensor, + pad: Sequence[int], + mode: str = ..., + value: float | None = None, +) -> Tensor: ... +def relu6(input: Tensor) -> Tensor: ... +def relu6_(input: Tensor) -> Tensor: ... +def scaled_dot_product_attention( + query: Tensor, + key: Tensor, + value: Tensor, + attn_mask: Tensor | None = None, + dropout_p: float = 0.0, + is_causal: bool = False, + scale: float | None = None, + enable_gqa: bool = False, +) -> Tensor: ... +def silu(input: Tensor) -> Tensor: ... +def silu_(input: Tensor) -> Tensor: ... +def smooth_l1_loss( + input: Tensor, + target: Tensor, + reduction: str = ..., + beta: float = 1.0, +) -> Tensor: ... +def soft_margin_loss( + input: Tensor, + target: Tensor, + reduction: str = ..., +) -> Tensor: ... +def softplus( + input: Tensor, + beta: float = ..., + threshold: float = ..., +) -> Tensor: ... +def softshrink(input: Tensor, lambd: float = ...) -> Tensor: ... + +# Defined in aten/src/ATen/native/mkldnn/Linear.cpp +def mkldnn_linear(input: Tensor, weight: Tensor, bias: Tensor | None) -> Tensor: ... + +# Defined at aten/src/ATen/native/mkldnn/MKLDNNConversions.cpp +def mkldnn_reorder_conv2d_weight( + self: Tensor, + padding: list, + stride: list, + dilatation: list, + groups: int, +) -> Tensor: ... +def mkldnn_reorder_conv3d_weight( + self: Tensor, + padding: list, + stride: list, + dilatation: list, + groups: int, +) -> Tensor: ... + +# Defined in aten/src/ATen/native/mkldnn/Prelu.cpp +def mkldnn_prelu(input: Tensor, weight: Tensor) -> Tensor: ... + +# Defined at tools/autograd/templates/python_nn_functions.cpp +@overload +def _parse_to( + device: _device, + dtype: _dtype, + non_blocking: _bool, + copy: _bool, + *, + memory_format: memory_format, +) -> tuple[_device, _dtype, _bool, memory_format]: ... +@overload +def _parse_to( + dtype: _dtype, + non_blocking: _bool, + copy: _bool, + *, + memory_format: memory_format, +) -> tuple[_device, _dtype, _bool, memory_format]: ... +@overload +def _parse_to( + tensor: Tensor, + non_blocking: _bool, + copy: _bool, + *, + memory_format: memory_format, +) -> tuple[_device, _dtype, _bool, memory_format]: ... + +# Defined in aten/src/ATen/native/PackedSequence.cpp +def pad_sequence( + sequences: list[Tensor] | tuple[Tensor, ...], + batch_first: bool = False, + padding_value: float = 0.0, + padding_side: Literal["left", "right"] = "right", +) -> Tensor: ... + +# Upsample functions used by torch.nn.functional.interpolate +def upsample_nearest1d( + input: Tensor, + output_size: Sequence[int] | None, + scale_factors: Sequence[float] | None, +) -> Tensor: ... +def upsample_nearest2d( + input: Tensor, + output_size: Sequence[int] | None, + scale_factors: Sequence[float] | None, +) -> Tensor: ... +def upsample_nearest3d( + input: Tensor, + output_size: Sequence[int] | None, + scale_factors: Sequence[float] | None, +) -> Tensor: ... +def _upsample_nearest_exact1d( + input: Tensor, + output_size: Sequence[int] | None, + scale_factors: Sequence[float] | None, +) -> Tensor: ... +def _upsample_nearest_exact2d( + input: Tensor, + output_size: Sequence[int] | None, + scale_factors: Sequence[float] | None, +) -> Tensor: ... +def _upsample_nearest_exact3d( + input: Tensor, + output_size: Sequence[int] | None, + scale_factors: Sequence[float] | None, +) -> Tensor: ... +def upsample_linear1d( + input: Tensor, + output_size: Sequence[int] | None, + align_corners: bool, + scale_factors: Sequence[float] | None, +) -> Tensor: ... +def _upsample_bilinear2d_aa( + input: Tensor, + output_size: Sequence[int] | None, + align_corners: bool, + scale_factors: Sequence[float] | None, +) -> Tensor: ... +def upsample_bilinear2d( + input: Tensor, + output_size: Sequence[int] | None, + align_corners: bool, + scale_factors: Sequence[float] | None, +) -> Tensor: ... +def upsample_trilinear3d( + input: Tensor, + output_size: Sequence[int] | None, + align_corners: bool, + scale_factors: Sequence[float] | None, +) -> Tensor: ... +def _upsample_bicubic2d_aa( + input: Tensor, + output_size: Sequence[int] | None, + align_corners: bool, + scale_factors: Sequence[float] | None, +) -> Tensor: ... +def upsample_bicubic2d( + input: Tensor, + output_size: Sequence[int] | None, + align_corners: bool, + scale_factors: Sequence[float] | None, +) -> Tensor: ... +def flatten_dense_tensors(tensors: list[Tensor]) -> Tensor: ... +def unflatten_dense_tensors(flat: Tensor, tensors: list[Tensor]) -> list[Tensor]: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_nvtx.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_nvtx.pyi new file mode 100644 index 0000000000000000000000000000000000000000..9b96874c36578ebaba065188d726455ff0b771be --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_nvtx.pyi @@ -0,0 +1,9 @@ +# mypy: allow-untyped-defs +# Defined in torch/csrc/cuda/shared/nvtx.cpp +def rangePushA(message: str) -> int: ... +def rangePop() -> int: ... +def rangeStartA(message: str) -> int: ... +def rangeEnd(int) -> None: ... +def markA(message: str) -> None: ... +def deviceRangeStart(message: str, stream: int) -> object: ... +def deviceRangeEnd(range_handle: object, stream: int) -> None: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_onnx.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_onnx.pyi new file mode 100644 index 0000000000000000000000000000000000000000..349e0b9ad12f0dd9306fde89a40718f26b158f0e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_onnx.pyi @@ -0,0 +1,39 @@ +# Defined in torch/csrc/onnx/init.cpp + +from enum import Enum + +PRODUCER_VERSION: str + +class TensorProtoDataType(Enum): + UNDEFINED = ... + FLOAT = ... + UINT8 = ... + INT8 = ... + UINT16 = ... + INT16 = ... + INT32 = ... + INT64 = ... + STRING = ... + BOOL = ... + FLOAT16 = ... + DOUBLE = ... + UINT32 = ... + UINT64 = ... + COMPLEX64 = ... + COMPLEX128 = ... + BFLOAT16 = ... + FLOAT8E5M2 = ... + FLOAT8E4M3FN = ... + FLOAT8E5M2FNUZ = ... + FLOAT8E4M3FNUZ = ... + +class OperatorExportTypes(Enum): + ONNX = ... + ONNX_ATEN = ... + ONNX_ATEN_FALLBACK = ... + ONNX_FALLTHROUGH = ... + +class TrainingMode(Enum): + EVAL = ... + PRESERVE = ... + TRAINING = ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_profiler.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_profiler.pyi new file mode 100644 index 0000000000000000000000000000000000000000..ae8121e4b71d268a7b9fafc93890856d65e7c7b5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_profiler.pyi @@ -0,0 +1,247 @@ +from enum import Enum +from typing import Literal, TypeAlias + +from torch._C import device, dtype, layout + +# defined in torch/csrc/profiler/python/init.cpp + +class RecordScope(Enum): + FUNCTION = ... + BACKWARD_FUNCTION = ... + TORCHSCRIPT_FUNCTION = ... + KERNEL_FUNCTION_DTYPE = ... + CUSTOM_CLASS = ... + BUILD_FEATURE = ... + LITE_INTERPRETER = ... + USER_SCOPE = ... + STATIC_RUNTIME_OP = ... + STATIC_RUNTIME_MODEL = ... + +class ProfilerState(Enum): + Disabled = ... + CPU = ... + CUDA = ... + NVTX = ... + ITT = ... + PRIVATEUSE1 = ... + KINETO = ... + KINETO_GPU_FALLBACK = ... + KINETO_PRIVATEUSE1_FALLBACK = ... + +class ActiveProfilerType(Enum): + NONE = ... + LEGACY = ... + KINETO = ... + NVTX = ... + ITT = ... + PRIVATEUSE1 = ... + +class ProfilerActivity(Enum): + CPU = ... + CUDA = ... + XPU = ... + MTIA = ... + HPU = ... + PrivateUse1 = ... + +class _EventType(Enum): + TorchOp = ... + Backend = ... + Allocation = ... + OutOfMemory = ... + PyCall = ... + PyCCall = ... + Kineto = ... + +class _ExperimentalConfig: + def __init__( + self, + profiler_metrics: list[str] = ..., + profiler_measure_per_kernel: bool = ..., + verbose: bool = ..., + performance_events: list[str] = ..., + enable_cuda_sync_events: bool = ..., + profile_all_threads: bool = ..., + ) -> None: ... + +class ProfilerConfig: + def __init__( + self, + state: ProfilerState, + report_input_shapes: bool, + profile_memory: bool, + with_stack: bool, + with_flops: bool, + with_modules: bool, + experimental_config: _ExperimentalConfig, + trace_id: str | None = None, + ) -> None: ... + +class _ProfilerEvent: + start_tid: int + start_time_ns: int + children: list[_ProfilerEvent] + + # TODO(robieta): remove in favor of `self.typed` + extra_fields: ( + _ExtraFields_TorchOp + | _ExtraFields_Backend + | _ExtraFields_Allocation + | _ExtraFields_OutOfMemory + | _ExtraFields_PyCall + | _ExtraFields_PyCCall + | _ExtraFields_Kineto + ) + + @property + def typed( + self, + ) -> ( + tuple[Literal[_EventType.TorchOp], _ExtraFields_TorchOp] + | tuple[Literal[_EventType.Backend], _ExtraFields_Backend] + | tuple[Literal[_EventType.Allocation], _ExtraFields_Allocation] + | tuple[Literal[_EventType.OutOfMemory], _ExtraFields_OutOfMemory] + | tuple[Literal[_EventType.PyCall], _ExtraFields_PyCall] + | tuple[Literal[_EventType.PyCCall], _ExtraFields_PyCCall] + | tuple[Literal[_EventType.Kineto], _ExtraFields_Kineto] + ): ... + @property + def name(self) -> str: ... + @property + def tag(self) -> _EventType: ... + @property + def id(self) -> int: ... + @property + def parent(self) -> _ProfilerEvent | None: ... + @property + def correlation_id(self) -> int: ... + @property + def end_time_ns(self) -> int: ... + @property + def duration_time_ns(self) -> int: ... + +class _TensorMetadata: + impl_ptr: int | None + storage_data_ptr: int | None + id: int | None + + @property + def allocation_id(self) -> int | None: ... + @property + def layout(self) -> layout: ... + @property + def device(self) -> device: ... + @property + def dtype(self) -> dtype: ... + @property + def sizes(self) -> list[int]: ... + @property + def strides(self) -> list[int]: ... + +Scalar: TypeAlias = int | float | bool | complex +Input: TypeAlias = _TensorMetadata | list[_TensorMetadata] | Scalar | None + +class _ExtraFields_TorchOp: + name: str + sequence_number: int + allow_tf32_cublas: bool + + @property + def inputs(self) -> list[Input]: ... + @property + def scope(self) -> RecordScope: ... + +class _ExtraFields_Backend: ... + +class _ExtraFields_Allocation: + ptr: int + id: int | None + alloc_size: int + total_allocated: int + total_reserved: int + + @property + def allocation_id(self) -> int | None: ... + @property + def device(self) -> device: ... + +class _ExtraFields_OutOfMemory: ... + +class _PyFrameState: + line_number: int + function_name: str + + @property + def file_name(self) -> str: ... + +class _NNModuleInfo: + @property + def self_ptr(self) -> int: ... + @property + def cls_ptr(self) -> int: ... + @property + def cls_name(self) -> str: ... + @property + def parameters( + self, + ) -> list[tuple[str, _TensorMetadata, _TensorMetadata | None]]: ... + +class _OptimizerInfo: + @property + def parameters( + self, + ) -> list[ + tuple[ + # Parameter + _TensorMetadata, + # + # Gradient (if present during optimizer.step()) + _TensorMetadata | None, + # + # Optimizer state for Parameter as (name, tensor) pairs + list[tuple[str, _TensorMetadata]], + ] + ]: ... + +class _ExtraFields_PyCCall: + @property + def caller(self) -> _PyFrameState: ... + +class _ExtraFields_PyCall: + @property + def callsite(self) -> _PyFrameState: ... + @property + def caller(self) -> _PyFrameState: ... + @property + def module(self) -> _NNModuleInfo | None: ... + @property + def optimizer(self) -> _OptimizerInfo | None: ... + +class _ExtraFields_Kineto: ... + +def _add_execution_trace_observer(output_file_path: str) -> bool: ... +def _remove_execution_trace_observer() -> None: ... +def _enable_execution_trace_observer() -> None: ... +def _disable_execution_trace_observer() -> None: ... +def _set_record_concrete_inputs_enabled_val(val: bool) -> None: ... +def _set_fwd_bwd_enabled_val(val: bool) -> None: ... +def _set_cuda_sync_enabled_val(val: bool) -> None: ... + +class CapturedTraceback: ... + +def gather_traceback(python: bool, script: bool, cpp: bool) -> CapturedTraceback: ... + +# The Dict has name, filename, line +def symbolize_tracebacks( + to_symbolize: list[CapturedTraceback], +) -> list[list[dict[str, str]]]: ... + +class _RecordFunctionFast: + def __init__( + self, + name: str, + input_values: list | tuple | None = None, + keyword_values: dict | None = None, + ) -> None: ... + def __enter__(self) -> None: ... + def __exit__(self, *exc_info: object) -> None: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_verbose.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_verbose.pyi new file mode 100644 index 0000000000000000000000000000000000000000..2388ce2bb8a5edd4c7640c374537e71607e5b72e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C/_verbose.pyi @@ -0,0 +1,3 @@ +# Defined in torch/csrc/utils/verbose.cpp +def mkl_set_verbose(enable: int) -> int: ... +def mkldnn_set_verbose(level: int) -> int: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C_flatbuffer/__init__.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C_flatbuffer/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..38750ed26aa26900591829fb7d51a3e3e1cdeeec --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_C_flatbuffer/__init__.pyi @@ -0,0 +1,11 @@ +# mypy: allow-untyped-defs +from torch._C import LiteScriptModule, ScriptModule + +def _load_mobile_module_from_file(filename: str): ... +def _load_mobile_module_from_bytes(bytes_: bytes): ... +def _load_jit_module_from_file(filename: str): ... +def _load_jit_module_from_bytes(bytes_: bytes): ... +def _save_mobile_module(m: LiteScriptModule, filename: str): ... +def _save_jit_module(m: ScriptModule, filename: str): ... +def _save_mobile_module_to_bytes(m: LiteScriptModule) -> bytes: ... +def _save_jit_module_to_bytes(m: ScriptModule) -> bytes: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_VF.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_VF.py new file mode 100644 index 0000000000000000000000000000000000000000..94166b51f1786593b584629744adc24036e8b1d7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_VF.py @@ -0,0 +1,31 @@ +""" +This makes the functions in torch._C._VariableFunctions available as + torch._VF. +without mypy being able to find them. + +A subset of those functions are mapped to ATen functions in +torch/jit/_builtins.py + +See https://github.com/pytorch/pytorch/issues/21478 for the reason for +introducing torch._VF + +""" + +import sys +import types + +import torch + + +class VFModule(types.ModuleType): + vf: types.ModuleType + + def __init__(self, name: str): + super().__init__(name) + self.vf = torch._C._VariableFunctions + + def __getattr__(self, name: str) -> object: + return getattr(self.vf, name) + + +sys.modules[__name__] = VFModule(__name__) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_VF.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_VF.pyi new file mode 100644 index 0000000000000000000000000000000000000000..9fd18ba29fa23b662defcaaed6d53c4918da67fe --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_VF.pyi @@ -0,0 +1,33783 @@ +# @generated by tools/pyi/gen_pyi.py from torch/_C/_VariableFunctions.pyi.in +# mypy: disable-error-code="type-arg" +# mypy: allow-untyped-defs +# ruff: noqa: F401,PYI054 + +from collections.abc import Callable, Sequence +from types import EllipsisType +from typing import Any, Literal, overload, TypeVar + +import torch +from torch import ( + contiguous_format, + Generator, + inf, + memory_format, + strided, + SymInt, + Tensor, +) +from torch._prims_common import DeviceLikeType +from torch.types import ( + _bool, + _complex, + _device, + _dtype, + _float, + _int, + _layout, + _qscheme, + _size, + Device, + Number, +) + +__all__ = [ + "__and__", + "__lshift__", + "__or__", + "__rshift__", + "__xor__", + "_adaptive_avg_pool2d", + "_adaptive_avg_pool3d", + "_add_batch_dim", + "_add_relu", + "_add_relu_", + "_addmm_activation", + "_aminmax", + "_amp_foreach_non_finite_check_and_unscale_", + "_amp_update_scale_", + "_assert_async", + "_assert_scalar", + "_assert_tensor_metadata", + "_batch_norm_impl_index", + "_cast_Byte", + "_cast_Char", + "_cast_Double", + "_cast_Float", + "_cast_Half", + "_cast_Int", + "_cast_Long", + "_cast_Short", + "_choose_qparams_per_tensor", + "_chunk_cat", + "_coalesce", + "_compute_linear_combination", + "_conj", + "_conj_copy", + "_conj_physical", + "_convert_indices_from_coo_to_csr", + "_convert_indices_from_csr_to_coo", + "_convert_weight_to_int4pack", + "_convert_weight_to_int4pack_for_cpu", + "_convolution", + "_convolution_mode", + "_copy_from", + "_copy_from_and_resize", + "_cslt_compress", + "_cslt_sparse_mm", + "_cslt_sparse_mm_search", + "_ctc_loss", + "_cudnn_ctc_loss", + "_cudnn_init_dropout_state", + "_cudnn_rnn", + "_cudnn_rnn_flatten_weight", + "_cufft_clear_plan_cache", + "_cufft_get_plan_cache_max_size", + "_cufft_get_plan_cache_size", + "_cufft_set_plan_cache_max_size", + "_cummax_helper", + "_cummin_helper", + "_debug_has_internal_overlap", + "_dim_arange", + "_dirichlet_grad", + "_disable_functionalization", + "_dyn_quant_matmul_4bit", + "_dyn_quant_pack_4bit_weight", + "_efficientzerotensor", + "_embedding_bag", + "_embedding_bag_forward_only", + "_empty_affine_quantized", + "_empty_per_channel_affine_quantized", + "_enable_functionalization", + "_euclidean_dist", + "_fake_quantize_learnable_per_channel_affine", + "_fake_quantize_learnable_per_tensor_affine", + "_fake_quantize_per_tensor_affine_cachemask_tensor_qparams", + "_fft_c2c", + "_fft_c2r", + "_fft_r2c", + "_fill_mem_eff_dropout_mask_", + "_foobar", + "_foreach_abs", + "_foreach_abs_", + "_foreach_acos", + "_foreach_acos_", + "_foreach_add", + "_foreach_add_", + "_foreach_addcdiv", + "_foreach_addcdiv_", + "_foreach_addcmul", + "_foreach_addcmul_", + "_foreach_asin", + "_foreach_asin_", + "_foreach_atan", + "_foreach_atan_", + "_foreach_ceil", + "_foreach_ceil_", + "_foreach_clamp_max", + "_foreach_clamp_max_", + "_foreach_clamp_min", + "_foreach_clamp_min_", + "_foreach_copy_", + "_foreach_cos", + "_foreach_cos_", + "_foreach_cosh", + "_foreach_cosh_", + "_foreach_div", + "_foreach_div_", + "_foreach_erf", + "_foreach_erf_", + "_foreach_erfc", + "_foreach_erfc_", + "_foreach_exp", + "_foreach_exp_", + "_foreach_expm1", + "_foreach_expm1_", + "_foreach_floor", + "_foreach_floor_", + "_foreach_frac", + "_foreach_frac_", + "_foreach_lerp", + "_foreach_lerp_", + "_foreach_lgamma", + "_foreach_lgamma_", + "_foreach_log", + "_foreach_log10", + "_foreach_log10_", + "_foreach_log1p", + "_foreach_log1p_", + "_foreach_log2", + "_foreach_log2_", + "_foreach_log_", + "_foreach_max", + "_foreach_maximum", + "_foreach_maximum_", + "_foreach_minimum", + "_foreach_minimum_", + "_foreach_mul", + "_foreach_mul_", + "_foreach_neg", + "_foreach_neg_", + "_foreach_norm", + "_foreach_pow", + "_foreach_pow_", + "_foreach_reciprocal", + "_foreach_reciprocal_", + "_foreach_round", + "_foreach_round_", + "_foreach_rsqrt", + "_foreach_rsqrt_", + "_foreach_sigmoid", + "_foreach_sigmoid_", + "_foreach_sign", + "_foreach_sign_", + "_foreach_sin", + "_foreach_sin_", + "_foreach_sinh", + "_foreach_sinh_", + "_foreach_sqrt", + "_foreach_sqrt_", + "_foreach_sub", + "_foreach_sub_", + "_foreach_tan", + "_foreach_tan_", + "_foreach_tanh", + "_foreach_tanh_", + "_foreach_trunc", + "_foreach_trunc_", + "_foreach_zero_", + "_from_functional_tensor", + "_functional_assert_async", + "_functional_assert_scalar", + "_functional_sym_constrain_range", + "_functional_sym_constrain_range_for_size", + "_functionalize_apply_view_metas", + "_functionalize_are_all_mutations_hidden_from_autograd", + "_functionalize_are_all_mutations_under_no_grad_or_inference_mode", + "_functionalize_commit_update", + "_functionalize_has_metadata_mutation", + "_functionalize_inductor_storage_resized_counter", + "_functionalize_is_symbolic", + "_functionalize_mark_mutation_hidden_from_autograd", + "_functionalize_mark_storage_changed", + "_functionalize_mutation_counter", + "_functionalize_replace", + "_functionalize_storage_changed_counter", + "_functionalize_sync", + "_functionalize_unsafe_set", + "_functionalize_was_inductor_storage_resized", + "_functionalize_was_storage_changed", + "_fused_adagrad_", + "_fused_adam_", + "_fused_adamw_", + "_fused_dropout", + "_fused_moving_avg_obs_fq_helper", + "_fused_rms_norm", + "_fused_sdp_choice", + "_fused_sgd_", + "_fw_primal_copy", + "_grid_sampler_2d_cpu_fallback", + "_grouped_mm", + "_has_compatible_shallow_copy_type", + "_histogramdd_bin_edges", + "_histogramdd_from_bin_cts", + "_histogramdd_from_bin_tensors", + "_index_put_impl_", + "_indices_copy", + "_int_mm", + "_is_all_true", + "_is_any_true", + "_is_functional_tensor", + "_is_functional_tensor_base", + "_is_zerotensor", + "_lazy_clone", + "_linalg_check_errors", + "_linalg_det", + "_linalg_eigh", + "_linalg_slogdet", + "_linalg_solve_ex", + "_linalg_svd", + "_log_softmax", + "_log_softmax_backward_data", + "_logcumsumexp", + "_lstm_mps", + "_lu_with_info", + "_make_dep_token", + "_make_dual", + "_make_dual_copy", + "_make_per_channel_quantized_tensor", + "_make_per_tensor_quantized_tensor", + "_masked_scale", + "_masked_softmax", + "_mixed_dtypes_linear", + "_mkldnn_reshape", + "_mkldnn_transpose", + "_mkldnn_transpose_", + "_mps_convolution", + "_mps_convolution_transpose", + "_native_batch_norm_legit", + "_native_batch_norm_legit_no_training", + "_native_multi_head_attention", + "_neg_view", + "_neg_view_copy", + "_nested_compute_contiguous_strides_offsets", + "_nested_from_padded", + "_nested_from_padded_and_nested_example", + "_nested_from_padded_tensor", + "_nested_get_jagged_dummy", + "_nested_get_lengths", + "_nested_get_max_seqlen", + "_nested_get_min_seqlen", + "_nested_get_offsets", + "_nested_get_ragged_idx", + "_nested_get_values", + "_nested_get_values_copy", + "_nested_tensor_from_mask", + "_nested_tensor_from_mask_left_aligned", + "_nested_tensor_from_tensor_list", + "_nested_tensor_softmax_with_shape", + "_nested_view_from_buffer", + "_nested_view_from_buffer_copy", + "_nested_view_from_jagged", + "_nested_view_from_jagged_copy", + "_nnpack_available", + "_nnpack_spatial_convolution", + "_pack_padded_sequence", + "_pad_packed_sequence", + "_pin_memory", + "_prelu_kernel", + "_print", + "_propagate_xla_data", + "_remove_batch_dim", + "_reshape_alias_copy", + "_reshape_from_tensor", + "_resize_output_", + "_rowwise_prune", + "_safe_softmax", + "_sample_dirichlet", + "_saturate_weight_to_fp16", + "_scaled_dot_product_attention_math", + "_scaled_dot_product_attention_math_for_mps", + "_scaled_dot_product_cudnn_attention", + "_scaled_dot_product_efficient_attention", + "_scaled_dot_product_flash_attention", + "_scaled_dot_product_flash_attention_for_cpu", + "_scaled_grouped_mm", + "_scaled_grouped_mm_v2", + "_scaled_mm", + "_scaled_mm_v2", + "_shape_as_tensor", + "_sobol_engine_draw", + "_sobol_engine_ff_", + "_sobol_engine_initialize_state_", + "_sobol_engine_scramble_", + "_softmax", + "_softmax_backward_data", + "_sparse_broadcast_to", + "_sparse_broadcast_to_copy", + "_sparse_csr_prod", + "_sparse_csr_sum", + "_sparse_log_softmax_backward_data", + "_sparse_semi_structured_addmm", + "_sparse_semi_structured_apply", + "_sparse_semi_structured_apply_dense", + "_sparse_semi_structured_linear", + "_sparse_semi_structured_mm", + "_sparse_semi_structured_tile", + "_sparse_softmax_backward_data", + "_sparse_sparse_matmul", + "_sparse_sum", + "_stack", + "_standard_gamma", + "_standard_gamma_grad", + "_sync", + "_test_autograd_multiple_dispatch", + "_test_autograd_multiple_dispatch_view", + "_test_autograd_multiple_dispatch_view_copy", + "_test_check_tensor", + "_test_functorch_fallback", + "_test_parallel_materialize", + "_test_serialization_subcmul", + "_to_cpu", + "_to_functional_tensor", + "_to_sparse_semi_structured", + "_transform_bias_rescale_qkv", + "_transformer_encoder_layer_fwd", + "_trilinear", + "_triton_multi_head_attention", + "_triton_scaled_dot_attention", + "_unique", + "_unique2", + "_unpack_dual", + "_unsafe_index", + "_unsafe_index_put", + "_unsafe_masked_index", + "_unsafe_masked_index_put_accumulate", + "_use_cudnn_ctc_loss", + "_use_cudnn_rnn_flatten_weight", + "_validate_compressed_sparse_indices", + "_validate_sparse_bsc_tensor_args", + "_validate_sparse_bsr_tensor_args", + "_validate_sparse_compressed_tensor_args", + "_validate_sparse_coo_tensor_args", + "_validate_sparse_csc_tensor_args", + "_validate_sparse_csr_tensor_args", + "_values_copy", + "_weight_int4pack_mm", + "_weight_int4pack_mm_for_cpu", + "_weight_int4pack_mm_with_scales_and_zeros", + "_weight_int8pack_mm", + "_weight_norm", + "_weight_norm_interface", + "_wrapped_linear_prepack", + "_wrapped_quantized_linear_prepacked", + "abs", + "abs_", + "absolute", + "acos", + "acos_", + "acosh", + "acosh_", + "adaptive_avg_pool1d", + "adaptive_max_pool1d", + "add", + "addbmm", + "addcdiv", + "addcmul", + "addmm", + "addmv", + "addmv_", + "addr", + "adjoint", + "affine_grid_generator", + "alias_copy", + "all", + "allclose", + "alpha_dropout", + "alpha_dropout_", + "amax", + "amin", + "aminmax", + "angle", + "any", + "arange", + "arccos", + "arccos_", + "arccosh", + "arccosh_", + "arcsin", + "arcsin_", + "arcsinh", + "arcsinh_", + "arctan", + "arctan2", + "arctan_", + "arctanh", + "arctanh_", + "argmax", + "argmin", + "argsort", + "argwhere", + "as_strided", + "as_strided_", + "as_strided_copy", + "as_strided_scatter", + "as_tensor", + "asarray", + "asin", + "asin_", + "asinh", + "asinh_", + "atan", + "atan2", + "atan_", + "atanh", + "atanh_", + "avg_pool1d", + "baddbmm", + "bartlett_window", + "batch_norm", + "batch_norm_backward_elemt", + "batch_norm_backward_reduce", + "batch_norm_elemt", + "batch_norm_gather_stats", + "batch_norm_gather_stats_with_counts", + "batch_norm_stats", + "batch_norm_update_stats", + "bernoulli", + "bilinear", + "binary_cross_entropy_with_logits", + "bincount", + "binomial", + "bitwise_and", + "bitwise_left_shift", + "bitwise_not", + "bitwise_or", + "bitwise_right_shift", + "bitwise_xor", + "blackman_window", + "bmm", + "broadcast_to", + "bucketize", + "can_cast", + "cat", + "ccol_indices_copy", + "ceil", + "ceil_", + "celu", + "celu_", + "channel_shuffle", + "cholesky", + "cholesky_inverse", + "cholesky_solve", + "choose_qparams_optimized", + "chunk", + "clamp", + "clamp_", + "clamp_max", + "clamp_max_", + "clamp_min", + "clamp_min_", + "clip", + "clip_", + "clone", + "col_indices_copy", + "column_stack", + "combinations", + "complex", + "concat", + "concatenate", + "conj", + "conj_physical", + "conj_physical_", + "constant_pad_nd", + "conv1d", + "conv2d", + "conv3d", + "conv_tbc", + "conv_transpose1d", + "conv_transpose2d", + "conv_transpose3d", + "convolution", + "copysign", + "corrcoef", + "cos", + "cos_", + "cosh", + "cosh_", + "cosine_embedding_loss", + "cosine_similarity", + "count_nonzero", + "cov", + "cross", + "crow_indices_copy", + "ctc_loss", + "cudnn_affine_grid_generator", + "cudnn_batch_norm", + "cudnn_convolution", + "cudnn_convolution_add_relu", + "cudnn_convolution_relu", + "cudnn_convolution_transpose", + "cudnn_grid_sampler", + "cudnn_is_acceptable", + "cummax", + "cummin", + "cumprod", + "cumsum", + "cumulative_trapezoid", + "deg2rad", + "deg2rad_", + "dequantize", + "det", + "detach", + "detach_", + "detach_copy", + "diag", + "diag_embed", + "diagflat", + "diagonal", + "diagonal_copy", + "diagonal_scatter", + "diff", + "digamma", + "dist", + "div", + "divide", + "dot", + "dropout", + "dropout_", + "dsmm", + "dsplit", + "dstack", + "embedding", + "embedding_bag", + "embedding_renorm_", + "empty", + "empty_like", + "empty_permuted", + "empty_quantized", + "empty_strided", + "eq", + "equal", + "erf", + "erf_", + "erfc", + "erfc_", + "erfinv", + "exp", + "exp2", + "exp2_", + "exp_", + "expand_copy", + "expm1", + "expm1_", + "eye", + "fake_quantize_per_channel_affine", + "fake_quantize_per_tensor_affine", + "fbgemm_linear_fp16_weight", + "fbgemm_linear_fp16_weight_fp32_activation", + "fbgemm_linear_int8_weight", + "fbgemm_linear_int8_weight_fp32_activation", + "fbgemm_linear_quantize_weight", + "fbgemm_pack_gemm_matrix_fp16", + "fbgemm_pack_quantized_matrix", + "feature_alpha_dropout", + "feature_alpha_dropout_", + "feature_dropout", + "feature_dropout_", + "fill", + "fill_", + "fix", + "fix_", + "flatten", + "flip", + "fliplr", + "flipud", + "float_power", + "floor", + "floor_", + "floor_divide", + "fmax", + "fmin", + "fmod", + "frac", + "frac_", + "frexp", + "frobenius_norm", + "from_file", + "from_numpy", + "frombuffer", + "full", + "full_like", + "fused_moving_avg_obs_fake_quant", + "gather", + "gcd", + "gcd_", + "ge", + "geqrf", + "ger", + "get_default_dtype", + "get_num_interop_threads", + "get_num_threads", + "gradient", + "greater", + "greater_equal", + "grid_sampler", + "grid_sampler_2d", + "grid_sampler_3d", + "group_norm", + "gru", + "gru_cell", + "gt", + "hamming_window", + "hann_window", + "hardshrink", + "hash_tensor", + "heaviside", + "hinge_embedding_loss", + "histc", + "histogram", + "histogramdd", + "hsmm", + "hsplit", + "hspmm", + "hstack", + "hypot", + "i0", + "i0_", + "igamma", + "igammac", + "imag", + "index_add", + "index_copy", + "index_fill", + "index_put", + "index_put_", + "index_reduce", + "index_select", + "indices_copy", + "init_num_threads", + "inner", + "instance_norm", + "int_repr", + "inverse", + "is_complex", + "is_conj", + "is_distributed", + "is_floating_point", + "is_grad_enabled", + "is_inference", + "is_inference_mode_enabled", + "is_neg", + "is_nonzero", + "is_same_size", + "is_signed", + "is_vulkan_available", + "isclose", + "isfinite", + "isin", + "isinf", + "isnan", + "isneginf", + "isposinf", + "isreal", + "istft", + "kaiser_window", + "kl_div", + "kron", + "kthvalue", + "layer_norm", + "lcm", + "lcm_", + "ldexp", + "ldexp_", + "le", + "lerp", + "less", + "less_equal", + "lgamma", + "linspace", + "log", + "log10", + "log10_", + "log1p", + "log1p_", + "log2", + "log2_", + "log_", + "log_softmax", + "logaddexp", + "logaddexp2", + "logcumsumexp", + "logdet", + "logical_and", + "logical_not", + "logical_or", + "logical_xor", + "logit", + "logit_", + "logspace", + "logsumexp", + "lstm", + "lstm_cell", + "lt", + "lu_solve", + "lu_unpack", + "margin_ranking_loss", + "masked_fill", + "masked_scatter", + "masked_select", + "matmul", + "matrix_exp", + "matrix_power", + "max", + "max_pool1d", + "max_pool1d_with_indices", + "max_pool2d", + "max_pool3d", + "maximum", + "mean", + "median", + "min", + "minimum", + "miopen_batch_norm", + "miopen_convolution", + "miopen_convolution_add_relu", + "miopen_convolution_relu", + "miopen_convolution_transpose", + "miopen_depthwise_convolution", + "miopen_rnn", + "mkldnn_adaptive_avg_pool2d", + "mkldnn_convolution", + "mkldnn_linear_backward_weights", + "mkldnn_max_pool2d", + "mkldnn_max_pool3d", + "mkldnn_rnn_layer", + "mm", + "mode", + "moveaxis", + "movedim", + "msort", + "mul", + "multinomial", + "multiply", + "mv", + "mvlgamma", + "nan_to_num", + "nan_to_num_", + "nanmean", + "nanmedian", + "nanquantile", + "nansum", + "narrow", + "narrow_copy", + "native_batch_norm", + "native_channel_shuffle", + "native_dropout", + "native_group_norm", + "native_layer_norm", + "native_norm", + "ne", + "neg", + "neg_", + "negative", + "negative_", + "nextafter", + "nonzero", + "nonzero_static", + "norm_except_dim", + "normal", + "not_equal", + "nuclear_norm", + "numel", + "ones", + "ones_like", + "orgqr", + "ormqr", + "outer", + "pairwise_distance", + "pdist", + "permute", + "permute_copy", + "pinverse", + "pixel_shuffle", + "pixel_unshuffle", + "poisson", + "poisson_nll_loss", + "polar", + "polygamma", + "positive", + "pow", + "prelu", + "prod", + "promote_types", + "put", + "q_per_channel_axis", + "q_per_channel_scales", + "q_per_channel_zero_points", + "q_scale", + "q_zero_point", + "qr", + "quantile", + "quantize_per_channel", + "quantize_per_tensor", + "quantize_per_tensor_dynamic", + "quantized_batch_norm", + "quantized_gru_cell", + "quantized_lstm_cell", + "quantized_max_pool1d", + "quantized_max_pool2d", + "quantized_max_pool3d", + "quantized_rnn_relu_cell", + "quantized_rnn_tanh_cell", + "rad2deg", + "rad2deg_", + "rand", + "rand_like", + "randint", + "randint_like", + "randn", + "randn_like", + "randperm", + "range", + "ravel", + "real", + "reciprocal", + "reciprocal_", + "relu", + "relu_", + "remainder", + "renorm", + "repeat_interleave", + "reshape", + "resize_as_", + "resize_as_sparse_", + "resolve_conj", + "resolve_neg", + "result_type", + "rms_norm", + "rnn_relu", + "rnn_relu_cell", + "rnn_tanh", + "rnn_tanh_cell", + "roll", + "rot90", + "round", + "round_", + "row_indices_copy", + "row_stack", + "rrelu", + "rrelu_", + "rsqrt", + "rsqrt_", + "rsub", + "saddmm", + "scalar_tensor", + "scatter", + "scatter_add", + "scatter_reduce", + "searchsorted", + "segment_reduce", + "select", + "select_copy", + "select_scatter", + "selu", + "selu_", + "set_flush_denormal", + "set_num_interop_threads", + "set_num_threads", + "sgn", + "sigmoid", + "sigmoid_", + "sign", + "signbit", + "sin", + "sin_", + "sinc", + "sinc_", + "sinh", + "sinh_", + "slice_copy", + "slice_inverse", + "slice_scatter", + "slogdet", + "smm", + "softmax", + "sort", + "sparse_bsc_tensor", + "sparse_bsr_tensor", + "sparse_compressed_tensor", + "sparse_coo_tensor", + "sparse_csc_tensor", + "sparse_csr_tensor", + "split_copy", + "split_with_sizes", + "split_with_sizes_copy", + "spmm", + "sqrt", + "sqrt_", + "square", + "square_", + "squeeze", + "squeeze_copy", + "sspaddmm", + "stack", + "std", + "std_mean", + "sub", + "subtract", + "sum", + "svd", + "swapaxes", + "swapdims", + "sym_constrain_range", + "sym_constrain_range_for_size", + "t", + "t_copy", + "take", + "take_along_dim", + "tan", + "tan_", + "tanh", + "tanh_", + "tensor", + "tensor_split", + "threshold", + "threshold_", + "tile", + "topk", + "trace", + "transpose", + "transpose_copy", + "trapezoid", + "trapz", + "triangular_solve", + "tril", + "tril_indices", + "triplet_margin_loss", + "triu", + "triu_indices", + "true_divide", + "trunc", + "trunc_", + "unbind", + "unbind_copy", + "unflatten", + "unfold_copy", + "unique_dim", + "unsafe_chunk", + "unsafe_split", + "unsafe_split_with_sizes", + "unsqueeze", + "unsqueeze_copy", + "values_copy", + "vander", + "var", + "var_mean", + "vdot", + "view_as_complex", + "view_as_complex_copy", + "view_as_real", + "view_as_real_copy", + "view_copy", + "vsplit", + "vstack", + "where", + "xlogy", + "xlogy_", + "zero_", + "zeros", + "zeros_like", +] + +@overload +def __and__(input: Tensor, other: Tensor) -> Tensor: ... +@overload +def __and__(input: Tensor, other: Number | _complex) -> Tensor: ... +@overload +def __lshift__(input: Tensor, other: Tensor) -> Tensor: ... +@overload +def __lshift__(input: Tensor, other: Number | _complex) -> Tensor: ... +@overload +def __or__(input: Tensor, other: Tensor) -> Tensor: ... +@overload +def __or__(input: Tensor, other: Number | _complex) -> Tensor: ... +@overload +def __rshift__(input: Tensor, other: Tensor) -> Tensor: ... +@overload +def __rshift__(input: Tensor, other: Number | _complex) -> Tensor: ... +@overload +def __xor__(input: Tensor, other: Tensor) -> Tensor: ... +@overload +def __xor__(input: Tensor, other: Number | _complex) -> Tensor: ... +def _adaptive_avg_pool2d( + input: Tensor, + output_size: _int | SymInt | Sequence[_int | SymInt], +) -> Tensor: ... +def _adaptive_avg_pool3d( + input: Tensor, + output_size: _int | SymInt | Sequence[_int | SymInt], +) -> Tensor: ... +def _add_batch_dim(input: Tensor, batch_dim: _int, level: _int) -> Tensor: ... +@overload +def _add_relu( + input: Tensor, + other: Tensor, + *, + alpha: Number | _complex = 1, + out: Tensor | None = None, +) -> Tensor: ... +@overload +def _add_relu( + input: Tensor, + other: Number | _complex, + alpha: Number | _complex = 1, +) -> Tensor: ... +@overload +def _add_relu_( + input: Tensor, + other: Tensor, + *, + alpha: Number | _complex = 1, +) -> Tensor: ... +@overload +def _add_relu_( + input: Tensor, + other: Number | _complex, + alpha: Number | _complex = 1, +) -> Tensor: ... +def _addmm_activation( + input: Tensor, + mat1: Tensor, + mat2: Tensor, + *, + beta: Number | _complex = 1, + alpha: Number | _complex = 1, + use_gelu: _bool = False, + out: Tensor | None = None, +) -> Tensor: ... +@overload +def _aminmax(input: Tensor) -> tuple[Tensor, Tensor]: ... +@overload +def _aminmax( + input: Tensor, + dim: _int, + keepdim: _bool = False, +) -> tuple[Tensor, Tensor]: ... +def _amp_foreach_non_finite_check_and_unscale_( + self: tuple[Tensor, ...] | list[Tensor] | None, + found_inf: Tensor, + inv_scale: Tensor, +) -> None: ... +def _amp_update_scale_( + input: Tensor, + growth_tracker: Tensor, + found_inf: Tensor, + scale_growth_factor: _float, + scale_backoff_factor: _float, + growth_interval: _int, +) -> Tensor: ... +@overload +def _assert_async(input: Tensor) -> None: + r""" + _assert_async(tensor) -> void + + Asynchronously assert that the contents of tensor are nonzero. For CPU tensors, + this is equivalent to ``assert tensor`` or ``assert tensor.is_nonzero()``; for + CUDA tensors, we DO NOT synchronize and you may only find out the assertion + failed at a later CUDA kernel launch. Asynchronous assertion can be helpful for + testing invariants in CUDA tensors without giving up performance. This function + is NOT intended to be used for regular error checking, as it will trash your CUDA + context if the assert fails (forcing you to restart your PyTorch process.) + + Args: + tensor (Tensor): a one element tensor to test to see if it is nonzero. Zero + elements (including False for boolean tensors) cause an assertion failure + to be raised. + """ + +@overload +def _assert_async(input: Tensor, assert_msg: str) -> None: + r""" + _assert_async(tensor) -> void + + Asynchronously assert that the contents of tensor are nonzero. For CPU tensors, + this is equivalent to ``assert tensor`` or ``assert tensor.is_nonzero()``; for + CUDA tensors, we DO NOT synchronize and you may only find out the assertion + failed at a later CUDA kernel launch. Asynchronous assertion can be helpful for + testing invariants in CUDA tensors without giving up performance. This function + is NOT intended to be used for regular error checking, as it will trash your CUDA + context if the assert fails (forcing you to restart your PyTorch process.) + + Args: + tensor (Tensor): a one element tensor to test to see if it is nonzero. Zero + elements (including False for boolean tensors) cause an assertion failure + to be raised. + """ + +def _assert_scalar(self: Number | _complex, assert_msg: str) -> None: ... +def _assert_tensor_metadata( + a: Tensor, + size: Sequence[_int | SymInt] | None = None, + stride: Sequence[_int | SymInt] | None = None, + dtype: _dtype | None = None, + *, + device: DeviceLikeType | None = None, + layout: _layout | None = None, +) -> None: ... +def _batch_norm_impl_index( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + running_mean: Tensor | None, + running_var: Tensor | None, + training: _bool, + momentum: _float, + eps: _float, + cudnn_enabled: _bool, +) -> tuple[Tensor, Tensor, Tensor, Tensor, _int]: ... +def _cast_Byte(input: Tensor, non_blocking: _bool = False) -> Tensor: ... +def _cast_Char(input: Tensor, non_blocking: _bool = False) -> Tensor: ... +def _cast_Double(input: Tensor, non_blocking: _bool = False) -> Tensor: ... +def _cast_Float(input: Tensor, non_blocking: _bool = False) -> Tensor: ... +def _cast_Half(input: Tensor, non_blocking: _bool = False) -> Tensor: ... +def _cast_Int(input: Tensor, non_blocking: _bool = False) -> Tensor: ... +def _cast_Long(input: Tensor, non_blocking: _bool = False) -> Tensor: ... +def _cast_Short(input: Tensor, non_blocking: _bool = False) -> Tensor: ... +def _choose_qparams_per_tensor( + input: Tensor, + reduce_range: _bool = False, +) -> tuple[_float, _int]: ... +def _chunk_cat( + tensors: tuple[Tensor, ...] | list[Tensor] | None, + dim: _int, + num_chunks: _int, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _coalesce(input: Tensor) -> Tensor: ... +def _compute_linear_combination( + input: Tensor, + coefficients: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _conj(input: Tensor) -> Tensor: ... +def _conj_copy(input: Tensor, *, out: Tensor | None = None) -> Tensor: ... +def _conj_physical(input: Tensor) -> Tensor: ... +def _convert_indices_from_coo_to_csr( + input: Tensor, + size: _int, + *, + out_int32: _bool = False, + out: Tensor | None = None, +) -> Tensor: ... +def _convert_indices_from_csr_to_coo( + crow_indices: Tensor, + col_indices: Tensor, + *, + out_int32: _bool = False, + transpose: _bool = False, + out: Tensor | None = None, +) -> Tensor: ... +def _convert_weight_to_int4pack(input: Tensor, innerKTiles: _int) -> Tensor: ... +def _convert_weight_to_int4pack_for_cpu( + input: Tensor, + innerKTiles: _int, +) -> Tensor: ... +@overload +def _convolution( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + stride: Sequence[_int | SymInt], + padding: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + transposed: _bool, + output_padding: _size, + groups: _int | SymInt, + benchmark: _bool, + deterministic: _bool, + cudnn_enabled: _bool, +) -> Tensor: ... +@overload +def _convolution( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + stride: Sequence[_int | SymInt], + padding: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + transposed: _bool, + output_padding: Sequence[_int | SymInt], + groups: _int | SymInt, + benchmark: _bool, + deterministic: _bool, + cudnn_enabled: _bool, + allow_tf32: _bool, +) -> Tensor: ... +def _convolution_mode( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + stride: Sequence[_int | SymInt], + padding: str, + dilation: Sequence[_int | SymInt], + groups: _int | SymInt, +) -> Tensor: ... +def _copy_from( + input: Tensor, + dst: Tensor, + non_blocking: _bool = False, +) -> Tensor: ... +def _copy_from_and_resize(input: Tensor, dst: Tensor) -> Tensor: ... +def _cslt_compress(input: Tensor) -> Tensor: ... +def _cslt_sparse_mm( + compressed_A: Tensor, + dense_B: Tensor, + bias: Tensor | None = None, + alpha: Tensor | None = None, + out_dtype: _dtype | None = None, + transpose_result: _bool = False, + alg_id: _int = 0, + split_k: _int = 1, + split_k_mode: _int = -1, +) -> Tensor: ... +def _cslt_sparse_mm_search( + compressed_A: Tensor, + dense_B: Tensor, + bias: Tensor | None = None, + alpha: Tensor | None = None, + out_dtype: _dtype | None = None, + transpose_result: _bool = False, +) -> _int: ... +@overload +def _ctc_loss( + log_probs: Tensor, + targets: Tensor, + input_lengths: _size, + target_lengths: _size, + blank: _int = 0, + zero_infinity: _bool = False, +) -> tuple[Tensor, Tensor]: ... +@overload +def _ctc_loss( + log_probs: Tensor, + targets: Tensor, + input_lengths: Tensor, + target_lengths: Tensor, + blank: _int = 0, + zero_infinity: _bool = False, +) -> tuple[Tensor, Tensor]: ... +@overload +def _cudnn_ctc_loss( + log_probs: Tensor, + targets: Tensor, + input_lengths: _size, + target_lengths: _size, + blank: _int, + deterministic: _bool, + zero_infinity: _bool, +) -> tuple[Tensor, Tensor]: ... +@overload +def _cudnn_ctc_loss( + log_probs: Tensor, + targets: Tensor, + input_lengths: Tensor, + target_lengths: Tensor, + blank: _int, + deterministic: _bool, + zero_infinity: _bool, +) -> tuple[Tensor, Tensor]: ... +def _cudnn_init_dropout_state( + dropout: _float, + train: _bool, + dropout_seed: _int, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: ... +def _cudnn_rnn( + input: Tensor, + weight: tuple[Tensor, ...] | list[Tensor] | None, + weight_stride0: _int, + weight_buf: Tensor | None, + hx: Tensor, + cx: Tensor | None, + mode: _int, + hidden_size: _int | SymInt, + proj_size: _int | SymInt, + num_layers: _int, + batch_first: _bool, + dropout: _float, + train: _bool, + bidirectional: _bool, + batch_sizes: Sequence[_int | SymInt], + dropout_state: Tensor | None, +) -> tuple[Tensor, Tensor, Tensor, Tensor, Tensor]: ... +def _cudnn_rnn_flatten_weight( + weight_arr: tuple[Tensor, ...] | list[Tensor] | None, + weight_stride0: _int, + input_size: _int | SymInt, + mode: _int, + hidden_size: _int | SymInt, + proj_size: _int | SymInt, + num_layers: _int, + batch_first: _bool, + bidirectional: _bool, +) -> Tensor: ... +def _cufft_clear_plan_cache(device_index: _int) -> None: ... +def _cufft_get_plan_cache_max_size(device_index: _int) -> _int: ... +def _cufft_get_plan_cache_size(device_index: _int) -> _int: ... +def _cufft_set_plan_cache_max_size( + device_index: _int, + max_size: _int, +) -> None: ... +def _cummax_helper( + input: Tensor, + values: Tensor, + indices: Tensor, + dim: _int, +) -> None: ... +def _cummin_helper( + input: Tensor, + values: Tensor, + indices: Tensor, + dim: _int, +) -> None: ... +def _debug_has_internal_overlap(input: Tensor) -> _int: ... +def _dim_arange(like: Tensor, dim: _int) -> Tensor: ... +def _dirichlet_grad(x: Tensor, alpha: Tensor, total: Tensor) -> Tensor: ... +def _disable_functionalization(): ... +def _dyn_quant_matmul_4bit( + inp: Tensor, + packed_weights: Tensor, + block_size: _int, + in_features: _int, + out_features: _int, +) -> Tensor: ... +def _dyn_quant_pack_4bit_weight( + weights: Tensor, + scales_zeros: Tensor, + bias: Tensor | None, + block_size: _int, + in_features: _int, + out_features: _int, +) -> Tensor: ... +@overload +def _efficientzerotensor( + size: Sequence[_int | SymInt], + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: ... +@overload +def _efficientzerotensor( + *size: _int | SymInt, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: ... +def _embedding_bag( + weight: Tensor, + indices: Tensor, + offsets: Tensor, + scale_grad_by_freq: _bool = False, + mode: _int = 0, + sparse: _bool = False, + per_sample_weights: Tensor | None = None, + include_last_offset: _bool = False, + padding_idx: _int = -1, +) -> tuple[Tensor, Tensor, Tensor, Tensor]: ... +def _embedding_bag_forward_only( + weight: Tensor, + indices: Tensor, + offsets: Tensor, + scale_grad_by_freq: _bool = False, + mode: _int = 0, + sparse: _bool = False, + per_sample_weights: Tensor | None = None, + include_last_offset: _bool = False, + padding_idx: _int = -1, +) -> tuple[Tensor, Tensor, Tensor, Tensor]: ... +@overload +def _empty_affine_quantized( + size: Sequence[_int | SymInt], + *, + scale: _float = 1, + zero_point: _int = 0, + memory_format: memory_format | None = contiguous_format, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: ... +@overload +def _empty_affine_quantized( + *size: _int | SymInt, + scale: _float = 1, + zero_point: _int = 0, + memory_format: memory_format | None = contiguous_format, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: ... +@overload +def _empty_per_channel_affine_quantized( + size: Sequence[_int | SymInt], + *, + scales: Tensor, + zero_points: Tensor, + axis: _int, + memory_format: memory_format | None = contiguous_format, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: ... +@overload +def _empty_per_channel_affine_quantized( + *size: _int | SymInt, + scales: Tensor, + zero_points: Tensor, + axis: _int, + memory_format: memory_format | None = contiguous_format, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: ... +def _enable_functionalization(*, reapply_views: _bool = False) -> None: ... +def _euclidean_dist(x1: Tensor, x2: Tensor) -> Tensor: ... +def _fake_quantize_learnable_per_channel_affine( + input: Tensor, + scale: Tensor, + zero_point: Tensor, + axis: _int, + quant_min: _int, + quant_max: _int, + grad_factor: _float = 1.0, +) -> Tensor: ... +def _fake_quantize_learnable_per_tensor_affine( + input: Tensor, + scale: Tensor, + zero_point: Tensor, + quant_min: _int, + quant_max: _int, + grad_factor: _float = 1.0, +) -> Tensor: ... +def _fake_quantize_per_tensor_affine_cachemask_tensor_qparams( + input: Tensor, + scale: Tensor, + zero_point: Tensor, + fake_quant_enabled: Tensor, + quant_min: _int, + quant_max: _int, +) -> torch.return_types._fake_quantize_per_tensor_affine_cachemask_tensor_qparams: # fmt: skip + ... +def _fft_c2c( + input: Tensor, + dim: Sequence[_int | SymInt], + normalization: _int, + forward: _bool, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _fft_c2r( + input: Tensor, + dim: _size, + normalization: _int, + last_dim_size: _int | SymInt, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _fft_r2c( + input: Tensor, + dim: _size, + normalization: _int, + onesided: _bool, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _fill_mem_eff_dropout_mask_( + input: Tensor, + dropout_p: _float, + seed: _int, + offset: _int, +) -> Tensor: ... +def _foobar( + input: Tensor, + arg1: _bool = True, + arg2: _bool = True, + *, + arg3: _bool = True, +) -> Tensor: ... +def _foreach_abs( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: + r""" + _foreach_abs(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.abs` to each Tensor of the input list. + """ + +def _foreach_abs_(self: tuple[Tensor, ...] | list[Tensor] | None) -> None: + r""" + _foreach_abs_(self: List[Tensor]) -> None + + Apply :func:`torch.abs` to each Tensor of the input list. + """ + +def _foreach_acos( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: + r""" + _foreach_acos(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.acos` to each Tensor of the input list. + """ + +def _foreach_acos_(self: tuple[Tensor, ...] | list[Tensor] | None) -> None: + r""" + _foreach_acos_(self: List[Tensor]) -> None + + Apply :func:`torch.acos` to each Tensor of the input list. + """ + +@overload +def _foreach_add( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalars: Sequence[Number | _complex], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_add( + self: tuple[Tensor, ...] | list[Tensor] | None, + other: tuple[Tensor, ...] | list[Tensor] | None, + *, + alpha: Number | _complex = 1, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_add( + self: tuple[Tensor, ...] | list[Tensor] | None, + other: Tensor, + *, + alpha: Number | _complex = 1, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_add( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalar: Number | _complex, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_add_( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalars: Sequence[Number | _complex], +) -> None: ... +@overload +def _foreach_add_( + self: tuple[Tensor, ...] | list[Tensor] | None, + other: tuple[Tensor, ...] | list[Tensor] | None, + *, + alpha: Number | _complex = 1, +) -> None: ... +@overload +def _foreach_add_( + self: tuple[Tensor, ...] | list[Tensor] | None, + other: Tensor, + *, + alpha: Number | _complex = 1, +) -> None: ... +@overload +def _foreach_add_( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalar: Number | _complex, +) -> None: ... +@overload +def _foreach_addcdiv( + self: tuple[Tensor, ...] | list[Tensor] | None, + tensor1: tuple[Tensor, ...] | list[Tensor] | None, + tensor2: tuple[Tensor, ...] | list[Tensor] | None, + scalars: Sequence[Number | _complex], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_addcdiv( + self: tuple[Tensor, ...] | list[Tensor] | None, + tensor1: tuple[Tensor, ...] | list[Tensor] | None, + tensor2: tuple[Tensor, ...] | list[Tensor] | None, + scalars: Tensor, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_addcdiv( + self: tuple[Tensor, ...] | list[Tensor] | None, + tensor1: tuple[Tensor, ...] | list[Tensor] | None, + tensor2: tuple[Tensor, ...] | list[Tensor] | None, + value: Number | _complex = 1, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_addcdiv_( + self: tuple[Tensor, ...] | list[Tensor] | None, + tensor1: tuple[Tensor, ...] | list[Tensor] | None, + tensor2: tuple[Tensor, ...] | list[Tensor] | None, + scalars: Sequence[Number | _complex], +) -> None: ... +@overload +def _foreach_addcdiv_( + self: tuple[Tensor, ...] | list[Tensor] | None, + tensor1: tuple[Tensor, ...] | list[Tensor] | None, + tensor2: tuple[Tensor, ...] | list[Tensor] | None, + scalars: Tensor, +) -> None: ... +@overload +def _foreach_addcdiv_( + self: tuple[Tensor, ...] | list[Tensor] | None, + tensor1: tuple[Tensor, ...] | list[Tensor] | None, + tensor2: tuple[Tensor, ...] | list[Tensor] | None, + value: Number | _complex = 1, +) -> None: ... +@overload +def _foreach_addcmul( + self: tuple[Tensor, ...] | list[Tensor] | None, + tensor1: tuple[Tensor, ...] | list[Tensor] | None, + tensor2: tuple[Tensor, ...] | list[Tensor] | None, + scalars: Sequence[Number | _complex], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_addcmul( + self: tuple[Tensor, ...] | list[Tensor] | None, + tensor1: tuple[Tensor, ...] | list[Tensor] | None, + tensor2: tuple[Tensor, ...] | list[Tensor] | None, + scalars: Tensor, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_addcmul( + self: tuple[Tensor, ...] | list[Tensor] | None, + tensor1: tuple[Tensor, ...] | list[Tensor] | None, + tensor2: tuple[Tensor, ...] | list[Tensor] | None, + value: Number | _complex = 1, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_addcmul_( + self: tuple[Tensor, ...] | list[Tensor] | None, + tensor1: tuple[Tensor, ...] | list[Tensor] | None, + tensor2: tuple[Tensor, ...] | list[Tensor] | None, + scalars: Sequence[Number | _complex], +) -> None: ... +@overload +def _foreach_addcmul_( + self: tuple[Tensor, ...] | list[Tensor] | None, + tensor1: tuple[Tensor, ...] | list[Tensor] | None, + tensor2: tuple[Tensor, ...] | list[Tensor] | None, + scalars: Tensor, +) -> None: ... +@overload +def _foreach_addcmul_( + self: tuple[Tensor, ...] | list[Tensor] | None, + tensor1: tuple[Tensor, ...] | list[Tensor] | None, + tensor2: tuple[Tensor, ...] | list[Tensor] | None, + value: Number | _complex = 1, +) -> None: ... +def _foreach_asin( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: + r""" + _foreach_asin(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.asin` to each Tensor of the input list. + """ + +def _foreach_asin_(self: tuple[Tensor, ...] | list[Tensor] | None) -> None: + r""" + _foreach_asin_(self: List[Tensor]) -> None + + Apply :func:`torch.asin` to each Tensor of the input list. + """ + +def _foreach_atan( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: + r""" + _foreach_atan(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.atan` to each Tensor of the input list. + """ + +def _foreach_atan_(self: tuple[Tensor, ...] | list[Tensor] | None) -> None: + r""" + _foreach_atan_(self: List[Tensor]) -> None + + Apply :func:`torch.atan` to each Tensor of the input list. + """ + +def _foreach_ceil( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: + r""" + _foreach_ceil(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.ceil` to each Tensor of the input list. + """ + +def _foreach_ceil_(self: tuple[Tensor, ...] | list[Tensor] | None) -> None: + r""" + _foreach_ceil_(self: List[Tensor]) -> None + + Apply :func:`torch.ceil` to each Tensor of the input list. + """ + +@overload +def _foreach_clamp_max( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalars: Sequence[Number | _complex], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_clamp_max( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalar: Number | _complex, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_clamp_max( + self: tuple[Tensor, ...] | list[Tensor] | None, + other: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_clamp_max_( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalars: Sequence[Number | _complex], +) -> None: ... +@overload +def _foreach_clamp_max_( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalar: Number | _complex, +) -> None: ... +@overload +def _foreach_clamp_max_( + self: tuple[Tensor, ...] | list[Tensor] | None, + other: tuple[Tensor, ...] | list[Tensor] | None, +) -> None: ... +@overload +def _foreach_clamp_min( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalars: Sequence[Number | _complex], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_clamp_min( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalar: Number | _complex, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_clamp_min( + self: tuple[Tensor, ...] | list[Tensor] | None, + other: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_clamp_min_( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalars: Sequence[Number | _complex], +) -> None: ... +@overload +def _foreach_clamp_min_( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalar: Number | _complex, +) -> None: ... +@overload +def _foreach_clamp_min_( + self: tuple[Tensor, ...] | list[Tensor] | None, + other: tuple[Tensor, ...] | list[Tensor] | None, +) -> None: ... +def _foreach_copy_( + self: tuple[Tensor, ...] | list[Tensor] | None, + src: tuple[Tensor, ...] | list[Tensor] | None, + non_blocking: _bool = False, +) -> None: ... +def _foreach_cos( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: + r""" + _foreach_cos(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.cos` to each Tensor of the input list. + """ + +def _foreach_cos_(self: tuple[Tensor, ...] | list[Tensor] | None) -> None: + r""" + _foreach_cos_(self: List[Tensor]) -> None + + Apply :func:`torch.cos` to each Tensor of the input list. + """ + +def _foreach_cosh( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: + r""" + _foreach_cosh(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.cosh` to each Tensor of the input list. + """ + +def _foreach_cosh_(self: tuple[Tensor, ...] | list[Tensor] | None) -> None: + r""" + _foreach_cosh_(self: List[Tensor]) -> None + + Apply :func:`torch.cosh` to each Tensor of the input list. + """ + +@overload +def _foreach_div( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalars: Sequence[Number | _complex], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_div( + self: tuple[Tensor, ...] | list[Tensor] | None, + other: Tensor, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_div( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalar: Number | _complex, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_div( + self: tuple[Tensor, ...] | list[Tensor] | None, + other: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_div_( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalars: Sequence[Number | _complex], +) -> None: ... +@overload +def _foreach_div_( + self: tuple[Tensor, ...] | list[Tensor] | None, + other: Tensor, +) -> None: ... +@overload +def _foreach_div_( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalar: Number | _complex, +) -> None: ... +@overload +def _foreach_div_( + self: tuple[Tensor, ...] | list[Tensor] | None, + other: tuple[Tensor, ...] | list[Tensor] | None, +) -> None: ... +def _foreach_erf( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: + r""" + _foreach_erf(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.erf` to each Tensor of the input list. + """ + +def _foreach_erf_(self: tuple[Tensor, ...] | list[Tensor] | None) -> None: + r""" + _foreach_erf_(self: List[Tensor]) -> None + + Apply :func:`torch.erf` to each Tensor of the input list. + """ + +def _foreach_erfc( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: + r""" + _foreach_erfc(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.erfc` to each Tensor of the input list. + """ + +def _foreach_erfc_(self: tuple[Tensor, ...] | list[Tensor] | None) -> None: + r""" + _foreach_erfc_(self: List[Tensor]) -> None + + Apply :func:`torch.erfc` to each Tensor of the input list. + """ + +def _foreach_exp( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: + r""" + _foreach_exp(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.exp` to each Tensor of the input list. + """ + +def _foreach_exp_(self: tuple[Tensor, ...] | list[Tensor] | None) -> None: + r""" + _foreach_exp_(self: List[Tensor]) -> None + + Apply :func:`torch.exp` to each Tensor of the input list. + """ + +def _foreach_expm1( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: + r""" + _foreach_expm1(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.expm1` to each Tensor of the input list. + """ + +def _foreach_expm1_(self: tuple[Tensor, ...] | list[Tensor] | None) -> None: + r""" + _foreach_expm1_(self: List[Tensor]) -> None + + Apply :func:`torch.expm1` to each Tensor of the input list. + """ + +def _foreach_floor( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: + r""" + _foreach_floor(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.floor` to each Tensor of the input list. + """ + +def _foreach_floor_(self: tuple[Tensor, ...] | list[Tensor] | None) -> None: + r""" + _foreach_floor_(self: List[Tensor]) -> None + + Apply :func:`torch.floor` to each Tensor of the input list. + """ + +def _foreach_frac( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: + r""" + _foreach_frac(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.frac` to each Tensor of the input list. + """ + +def _foreach_frac_(self: tuple[Tensor, ...] | list[Tensor] | None) -> None: + r""" + _foreach_frac_(self: List[Tensor]) -> None + + Apply :func:`torch.frac` to each Tensor of the input list. + """ + +@overload +def _foreach_lerp( + self: tuple[Tensor, ...] | list[Tensor] | None, + tensors1: tuple[Tensor, ...] | list[Tensor] | None, + weight: Number | _complex, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_lerp( + self: tuple[Tensor, ...] | list[Tensor] | None, + tensors1: tuple[Tensor, ...] | list[Tensor] | None, + weight: Sequence[Number | _complex], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_lerp( + self: tuple[Tensor, ...] | list[Tensor] | None, + tensors1: tuple[Tensor, ...] | list[Tensor] | None, + weights: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_lerp_( + self: tuple[Tensor, ...] | list[Tensor] | None, + tensors1: tuple[Tensor, ...] | list[Tensor] | None, + weight: Number | _complex, +) -> None: ... +@overload +def _foreach_lerp_( + self: tuple[Tensor, ...] | list[Tensor] | None, + tensors1: tuple[Tensor, ...] | list[Tensor] | None, + weight: Sequence[Number | _complex], +) -> None: ... +@overload +def _foreach_lerp_( + self: tuple[Tensor, ...] | list[Tensor] | None, + tensors1: tuple[Tensor, ...] | list[Tensor] | None, + weights: tuple[Tensor, ...] | list[Tensor] | None, +) -> None: ... +def _foreach_lgamma( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: + r""" + _foreach_lgamma(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.lgamma` to each Tensor of the input list. + """ + +def _foreach_lgamma_( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> None: + r""" + _foreach_lgamma_(self: List[Tensor]) -> None + + Apply :func:`torch.lgamma` to each Tensor of the input list. + """ + +def _foreach_log( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: + r""" + _foreach_log(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.log` to each Tensor of the input list. + """ + +def _foreach_log10( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: + r""" + _foreach_log10(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.log10` to each Tensor of the input list. + """ + +def _foreach_log10_(self: tuple[Tensor, ...] | list[Tensor] | None) -> None: + r""" + _foreach_log10_(self: List[Tensor]) -> None + + Apply :func:`torch.log10` to each Tensor of the input list. + """ + +def _foreach_log1p( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: + r""" + _foreach_log1p(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.log1p` to each Tensor of the input list. + """ + +def _foreach_log1p_(self: tuple[Tensor, ...] | list[Tensor] | None) -> None: + r""" + _foreach_log1p_(self: List[Tensor]) -> None + + Apply :func:`torch.log1p` to each Tensor of the input list. + """ + +def _foreach_log2( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: + r""" + _foreach_log2(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.log2` to each Tensor of the input list. + """ + +def _foreach_log2_(self: tuple[Tensor, ...] | list[Tensor] | None) -> None: + r""" + _foreach_log2_(self: List[Tensor]) -> None + + Apply :func:`torch.log2` to each Tensor of the input list. + """ + +def _foreach_log_(self: tuple[Tensor, ...] | list[Tensor] | None) -> None: + r""" + _foreach_log_(self: List[Tensor]) -> None + + Apply :func:`torch.log` to each Tensor of the input list. + """ + +def _foreach_max( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_maximum( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalars: Sequence[Number | _complex], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_maximum( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalar: Number | _complex, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_maximum( + self: tuple[Tensor, ...] | list[Tensor] | None, + other: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_maximum_( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalars: Sequence[Number | _complex], +) -> None: ... +@overload +def _foreach_maximum_( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalar: Number | _complex, +) -> None: ... +@overload +def _foreach_maximum_( + self: tuple[Tensor, ...] | list[Tensor] | None, + other: tuple[Tensor, ...] | list[Tensor] | None, +) -> None: ... +@overload +def _foreach_minimum( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalars: Sequence[Number | _complex], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_minimum( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalar: Number | _complex, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_minimum( + self: tuple[Tensor, ...] | list[Tensor] | None, + other: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_minimum_( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalars: Sequence[Number | _complex], +) -> None: ... +@overload +def _foreach_minimum_( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalar: Number | _complex, +) -> None: ... +@overload +def _foreach_minimum_( + self: tuple[Tensor, ...] | list[Tensor] | None, + other: tuple[Tensor, ...] | list[Tensor] | None, +) -> None: ... +@overload +def _foreach_mul( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalars: Sequence[Number | _complex], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_mul( + self: tuple[Tensor, ...] | list[Tensor] | None, + other: Tensor, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_mul( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalar: Number | _complex, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_mul( + self: tuple[Tensor, ...] | list[Tensor] | None, + other: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_mul_( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalars: Sequence[Number | _complex], +) -> None: ... +@overload +def _foreach_mul_( + self: tuple[Tensor, ...] | list[Tensor] | None, + other: Tensor, +) -> None: ... +@overload +def _foreach_mul_( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalar: Number | _complex, +) -> None: ... +@overload +def _foreach_mul_( + self: tuple[Tensor, ...] | list[Tensor] | None, + other: tuple[Tensor, ...] | list[Tensor] | None, +) -> None: ... +def _foreach_neg( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: + r""" + _foreach_neg(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.neg` to each Tensor of the input list. + """ + +def _foreach_neg_(self: tuple[Tensor, ...] | list[Tensor] | None) -> None: + r""" + _foreach_neg_(self: List[Tensor]) -> None + + Apply :func:`torch.neg` to each Tensor of the input list. + """ + +def _foreach_norm( + self: tuple[Tensor, ...] | list[Tensor] | None, + ord: Number | _complex = 2, + dtype: _dtype | None = None, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_pow( + self: tuple[Tensor, ...] | list[Tensor] | None, + exponent: Sequence[Number | _complex], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_pow( + self: tuple[Tensor, ...] | list[Tensor] | None, + exponent: Number | _complex, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_pow( + self: tuple[Tensor, ...] | list[Tensor] | None, + exponent: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_pow( + self: Number | _complex, + exponent: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_pow_( + self: tuple[Tensor, ...] | list[Tensor] | None, + exponent: Sequence[Number | _complex], +) -> None: ... +@overload +def _foreach_pow_( + self: tuple[Tensor, ...] | list[Tensor] | None, + exponent: Number | _complex, +) -> None: ... +@overload +def _foreach_pow_( + self: tuple[Tensor, ...] | list[Tensor] | None, + exponent: tuple[Tensor, ...] | list[Tensor] | None, +) -> None: ... +def _foreach_reciprocal( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: + r""" + _foreach_reciprocal(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.reciprocal` to each Tensor of the input list. + """ + +def _foreach_reciprocal_( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> None: + r""" + _foreach_reciprocal_(self: List[Tensor]) -> None + + Apply :func:`torch.reciprocal` to each Tensor of the input list. + """ + +def _foreach_round( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: + r""" + _foreach_round(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.round` to each Tensor of the input list. + """ + +def _foreach_round_(self: tuple[Tensor, ...] | list[Tensor] | None) -> None: + r""" + _foreach_round_(self: List[Tensor]) -> None + + Apply :func:`torch.round` to each Tensor of the input list. + """ + +def _foreach_rsqrt( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: ... +def _foreach_rsqrt_(self: tuple[Tensor, ...] | list[Tensor] | None) -> None: ... +def _foreach_sigmoid( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: + r""" + _foreach_sigmoid(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.sigmoid` to each Tensor of the input list. + """ + +def _foreach_sigmoid_( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> None: + r""" + _foreach_sigmoid_(self: List[Tensor]) -> None + + Apply :func:`torch.sigmoid` to each Tensor of the input list. + """ + +def _foreach_sign( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: ... +def _foreach_sign_(self: tuple[Tensor, ...] | list[Tensor] | None) -> None: ... +def _foreach_sin( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: + r""" + _foreach_sin(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.sin` to each Tensor of the input list. + """ + +def _foreach_sin_(self: tuple[Tensor, ...] | list[Tensor] | None) -> None: + r""" + _foreach_sin_(self: List[Tensor]) -> None + + Apply :func:`torch.sin` to each Tensor of the input list. + """ + +def _foreach_sinh( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: + r""" + _foreach_sinh(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.sinh` to each Tensor of the input list. + """ + +def _foreach_sinh_(self: tuple[Tensor, ...] | list[Tensor] | None) -> None: + r""" + _foreach_sinh_(self: List[Tensor]) -> None + + Apply :func:`torch.sinh` to each Tensor of the input list. + """ + +def _foreach_sqrt( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: + r""" + _foreach_sqrt(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.sqrt` to each Tensor of the input list. + """ + +def _foreach_sqrt_(self: tuple[Tensor, ...] | list[Tensor] | None) -> None: + r""" + _foreach_sqrt_(self: List[Tensor]) -> None + + Apply :func:`torch.sqrt` to each Tensor of the input list. + """ + +@overload +def _foreach_sub( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalars: Sequence[Number | _complex], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_sub( + self: tuple[Tensor, ...] | list[Tensor] | None, + other: tuple[Tensor, ...] | list[Tensor] | None, + *, + alpha: Number | _complex = 1, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_sub( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalar: Number | _complex, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_sub_( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalars: Sequence[Number | _complex], +) -> None: ... +@overload +def _foreach_sub_( + self: tuple[Tensor, ...] | list[Tensor] | None, + other: tuple[Tensor, ...] | list[Tensor] | None, + *, + alpha: Number | _complex = 1, +) -> None: ... +@overload +def _foreach_sub_( + self: tuple[Tensor, ...] | list[Tensor] | None, + scalar: Number | _complex, +) -> None: ... +def _foreach_tan( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: + r""" + _foreach_tan(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.tan` to each Tensor of the input list. + """ + +def _foreach_tan_(self: tuple[Tensor, ...] | list[Tensor] | None) -> None: + r""" + _foreach_tan_(self: List[Tensor]) -> None + + Apply :func:`torch.tan` to each Tensor of the input list. + """ + +def _foreach_tanh( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: + r""" + _foreach_tanh(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.tanh` to each Tensor of the input list. + """ + +def _foreach_tanh_(self: tuple[Tensor, ...] | list[Tensor] | None) -> None: + r""" + _foreach_tanh_(self: List[Tensor]) -> None + + Apply :func:`torch.tanh` to each Tensor of the input list. + """ + +def _foreach_trunc( + self: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: + r""" + _foreach_trunc(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.trunc` to each Tensor of the input list. + """ + +def _foreach_trunc_(self: tuple[Tensor, ...] | list[Tensor] | None) -> None: + r""" + _foreach_trunc_(self: List[Tensor]) -> None + + Apply :func:`torch.trunc` to each Tensor of the input list. + """ + +def _foreach_zero_(self: tuple[Tensor, ...] | list[Tensor] | None) -> None: + r""" + _foreach_zero_(self: List[Tensor]) -> None + + Apply :func:`torch.zero` to each Tensor of the input list. + """ + +def _from_functional_tensor(t: Tensor) -> Tensor: ... +def _functional_assert_async( + input: Tensor, + assert_msg: str, + dep_token: Tensor, +) -> Tensor: ... +def _functional_assert_scalar( + self: Number | _complex, + assert_msg: str, + dep_token: Tensor, +) -> Tensor: ... +def _functional_sym_constrain_range( + size: Number | _complex, + min: _int | None, + max: _int | None, + dep_token: Tensor, +) -> Tensor: ... +def _functional_sym_constrain_range_for_size( + size: Number | _complex, + min: _int | None, + max: _int | None, + dep_token: Tensor, +) -> Tensor: ... +def _functionalize_apply_view_metas(tensor: Tensor, base: Tensor) -> Tensor: ... +def _functionalize_are_all_mutations_hidden_from_autograd( + t: Tensor, +) -> _bool: ... +def _functionalize_are_all_mutations_under_no_grad_or_inference_mode( + t: Tensor, +) -> _bool: ... +def _functionalize_commit_update(t: Tensor) -> None: ... +def _functionalize_has_metadata_mutation(tensor: Tensor) -> _bool: ... +def _functionalize_inductor_storage_resized_counter(t: Tensor) -> _int: ... +def _functionalize_is_symbolic(tensor: Tensor) -> _bool: ... +def _functionalize_mark_mutation_hidden_from_autograd(t: Tensor) -> None: ... +def _functionalize_mark_storage_changed(tensor: Tensor) -> _bool: ... +def _functionalize_mutation_counter(t: Tensor) -> _int: ... +def _functionalize_replace(self_: Tensor, other: Tensor) -> None: ... +def _functionalize_storage_changed_counter(t: Tensor) -> _int: ... +def _functionalize_sync(t: Tensor) -> None: ... +def _functionalize_unsafe_set(dst: Tensor, src: Tensor) -> None: ... +def _functionalize_was_inductor_storage_resized(t: Tensor) -> _bool: ... +def _functionalize_was_storage_changed(tensor: Tensor) -> _bool: ... +@overload +def _fused_adagrad_( + self: tuple[Tensor, ...] | list[Tensor] | None, + grads: tuple[Tensor, ...] | list[Tensor] | None, + state_sums: tuple[Tensor, ...] | list[Tensor] | None, + state_steps: tuple[Tensor, ...] | list[Tensor] | None, + *, + lr: Tensor, + lr_decay: _float, + weight_decay: _float, + eps: _float, + maximize: _bool, + grad_scale: Tensor | None = None, + found_inf: Tensor | None = None, +) -> None: ... +@overload +def _fused_adagrad_( + self: tuple[Tensor, ...] | list[Tensor] | None, + grads: tuple[Tensor, ...] | list[Tensor] | None, + state_sums: tuple[Tensor, ...] | list[Tensor] | None, + state_steps: tuple[Tensor, ...] | list[Tensor] | None, + *, + lr: _float, + lr_decay: _float, + weight_decay: _float, + eps: _float, + maximize: _bool, + grad_scale: Tensor | None = None, + found_inf: Tensor | None = None, +) -> None: ... +@overload +def _fused_adam_( + self: tuple[Tensor, ...] | list[Tensor] | None, + grads: tuple[Tensor, ...] | list[Tensor] | None, + exp_avgs: tuple[Tensor, ...] | list[Tensor] | None, + exp_avg_sqs: tuple[Tensor, ...] | list[Tensor] | None, + max_exp_avg_sqs: tuple[Tensor, ...] | list[Tensor] | None, + state_steps: tuple[Tensor, ...] | list[Tensor] | None, + *, + lr: Tensor, + beta1: _float, + beta2: _float, + weight_decay: _float, + eps: _float, + amsgrad: _bool, + maximize: _bool, + grad_scale: Tensor | None = None, + found_inf: Tensor | None = None, +) -> None: ... +@overload +def _fused_adam_( + self: tuple[Tensor, ...] | list[Tensor] | None, + grads: tuple[Tensor, ...] | list[Tensor] | None, + exp_avgs: tuple[Tensor, ...] | list[Tensor] | None, + exp_avg_sqs: tuple[Tensor, ...] | list[Tensor] | None, + max_exp_avg_sqs: tuple[Tensor, ...] | list[Tensor] | None, + state_steps: tuple[Tensor, ...] | list[Tensor] | None, + *, + lr: _float, + beta1: _float, + beta2: _float, + weight_decay: _float, + eps: _float, + amsgrad: _bool, + maximize: _bool, + grad_scale: Tensor | None = None, + found_inf: Tensor | None = None, +) -> None: ... +@overload +def _fused_adamw_( + self: tuple[Tensor, ...] | list[Tensor] | None, + grads: tuple[Tensor, ...] | list[Tensor] | None, + exp_avgs: tuple[Tensor, ...] | list[Tensor] | None, + exp_avg_sqs: tuple[Tensor, ...] | list[Tensor] | None, + max_exp_avg_sqs: tuple[Tensor, ...] | list[Tensor] | None, + state_steps: tuple[Tensor, ...] | list[Tensor] | None, + *, + lr: Tensor, + beta1: _float, + beta2: _float, + weight_decay: _float, + eps: _float, + amsgrad: _bool, + maximize: _bool, + grad_scale: Tensor | None = None, + found_inf: Tensor | None = None, +) -> None: ... +@overload +def _fused_adamw_( + self: tuple[Tensor, ...] | list[Tensor] | None, + grads: tuple[Tensor, ...] | list[Tensor] | None, + exp_avgs: tuple[Tensor, ...] | list[Tensor] | None, + exp_avg_sqs: tuple[Tensor, ...] | list[Tensor] | None, + max_exp_avg_sqs: tuple[Tensor, ...] | list[Tensor] | None, + state_steps: tuple[Tensor, ...] | list[Tensor] | None, + *, + lr: _float, + beta1: _float, + beta2: _float, + weight_decay: _float, + eps: _float, + amsgrad: _bool, + maximize: _bool, + grad_scale: Tensor | None = None, + found_inf: Tensor | None = None, +) -> None: ... +def _fused_dropout( + input: Tensor, + p: _float, + generator: Generator | None = None, +) -> tuple[Tensor, Tensor]: ... +def _fused_moving_avg_obs_fq_helper( + input: Tensor, + observer_on: Tensor, + fake_quant_on: Tensor, + running_min: Tensor, + running_max: Tensor, + scale: Tensor, + zero_point: Tensor, + averaging_const: _float, + quant_min: _int, + quant_max: _int, + ch_axis: _int, + per_row_fake_quant: _bool = False, + symmetric_quant: _bool = False, +) -> torch.return_types._fused_moving_avg_obs_fq_helper: ... +def _fused_rms_norm( + input: Tensor, + normalized_shape: _size, + weight: Tensor | None, + eps: _float | None, +) -> tuple[Tensor, Tensor]: ... +def _fused_sdp_choice( + query: Tensor, + key: Tensor, + value: Tensor, + attn_mask: Tensor | None = None, + dropout_p: _float = 0.0, + is_causal: _bool = False, + *, + scale: _float | None = None, + enable_gqa: _bool = False, +) -> _int: ... +@overload +def _fused_sgd_( + self: tuple[Tensor, ...] | list[Tensor] | None, + grads: tuple[Tensor, ...] | list[Tensor] | None, + momentum_buffer_list: tuple[Tensor, ...] | list[Tensor] | None, + *, + weight_decay: _float, + momentum: _float, + lr: Tensor, + dampening: _float, + nesterov: _bool, + maximize: _bool, + is_first_step: _bool, + grad_scale: Tensor | None = None, + found_inf: Tensor | None = None, +) -> None: ... +@overload +def _fused_sgd_( + self: tuple[Tensor, ...] | list[Tensor] | None, + grads: tuple[Tensor, ...] | list[Tensor] | None, + momentum_buffer_list: tuple[Tensor, ...] | list[Tensor] | None, + *, + weight_decay: _float, + momentum: _float, + lr: _float, + dampening: _float, + nesterov: _bool, + maximize: _bool, + is_first_step: _bool, + grad_scale: Tensor | None = None, + found_inf: Tensor | None = None, +) -> None: ... +def _fw_primal_copy( + input: Tensor, + level: _int, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _grid_sampler_2d_cpu_fallback( + input: Tensor, + grid: Tensor, + interpolation_mode: _int, + padding_mode: _int, + align_corners: _bool, +) -> Tensor: ... +def _grouped_mm( + input: Tensor, + mat2: Tensor, + offs: Tensor | None = None, + bias: Tensor | None = None, + out_dtype: _dtype | None = None, +) -> Tensor: ... +def _has_compatible_shallow_copy_type( + input: Tensor, + from_: Tensor, +) -> _bool: ... +def _histogramdd_bin_edges( + input: Tensor, + bins: _size, + *, + range: Sequence[_float] | None = None, + weight: Tensor | None = None, + density: _bool = False, +) -> tuple[Tensor, ...]: ... +def _histogramdd_from_bin_cts( + input: Tensor, + bins: _size, + *, + range: Sequence[_float] | None = None, + weight: Tensor | None = None, + density: _bool = False, +) -> Tensor: ... +def _histogramdd_from_bin_tensors( + input: Tensor, + bins: tuple[Tensor, ...] | list[Tensor] | None, + *, + weight: Tensor | None = None, + density: _bool = False, +) -> Tensor: ... +def _index_put_impl_( + input: Tensor, + indices: tuple[Tensor, ...] | list[Tensor] | None, + values: Tensor, + accumulate: _bool = False, + unsafe: _bool = False, +) -> Tensor: ... +def _indices_copy(input: Tensor, *, out: Tensor | None = None) -> Tensor: ... +def _int_mm( + input: Tensor, + mat2: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _is_all_true(input: Tensor) -> Tensor: ... +def _is_any_true(input: Tensor) -> Tensor: ... +def _is_functional_tensor(t: Tensor) -> _bool: ... +def _is_functional_tensor_base(t: Tensor) -> _bool: ... +def _is_zerotensor(input: Tensor) -> _bool: ... +def _lazy_clone(input: Tensor) -> Tensor: ... +def _linalg_check_errors( + info: Tensor, + api_name: str, + *, + is_matrix: _bool, +) -> None: ... +def _linalg_det( + A: Tensor, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types._linalg_det: ... +def _linalg_eigh( + A: Tensor, + UPLO: str = "L", + compute_v: _bool = True, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types._linalg_eigh: ... +def _linalg_slogdet( + A: Tensor, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types._linalg_slogdet: ... +def _linalg_solve_ex( + A: Tensor, + B: Tensor, + *, + left: _bool = True, + check_errors: _bool = False, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types._linalg_solve_ex: ... +def _linalg_svd( + A: Tensor, + full_matrices: _bool = False, + compute_uv: _bool = True, + *, + driver: str | None = None, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types._linalg_svd: ... +def _log_softmax( + input: Tensor, + dim: _int, + half_to_float: _bool, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _log_softmax_backward_data( + grad_output: Tensor, + output: Tensor, + dim: _int, + input_dtype: _dtype, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _logcumsumexp( + input: Tensor, + dim: _int, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _lstm_mps( + input: Tensor, + hx: tuple[Tensor, ...] | list[Tensor] | None, + params: tuple[Tensor, ...] | list[Tensor] | None, + has_biases: _bool, + num_layers: _int, + dropout: _float, + train: _bool, + bidirectional: _bool, + batch_first: _bool, +) -> tuple[Tensor, Tensor, Tensor, Tensor, Tensor, Tensor]: ... +def _lu_with_info( + input: Tensor, + pivot: _bool = True, + check_errors: _bool = True, +) -> torch.return_types._lu_with_info: ... +def _make_dep_token( + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: ... +def _make_dual(primal: Tensor, tangent: Tensor, level: _int) -> Tensor: ... +def _make_dual_copy( + primal: Tensor, + tangent: Tensor, + level: _int, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _make_per_channel_quantized_tensor( + input: Tensor, + scale: Tensor, + zero_point: Tensor, + axis: _int, +) -> Tensor: ... +def _make_per_tensor_quantized_tensor( + input: Tensor, + scale: _float, + zero_point: _int, +) -> Tensor: ... +def _masked_scale(input: Tensor, mask: Tensor, scale: _float) -> Tensor: ... +def _masked_softmax( + input: Tensor, + mask: Tensor, + dim: _int | None = None, + mask_type: _int | None = None, +) -> Tensor: ... +def _mixed_dtypes_linear( + input: Tensor, + weight: Tensor, + scale: Tensor, + *, + bias: Tensor | None = None, + activation: str | None = None, +) -> Tensor: ... +def _mkldnn_reshape(input: Tensor, shape: _size) -> Tensor: ... +def _mkldnn_transpose(input: Tensor, dim0: _int, dim1: _int) -> Tensor: ... +def _mkldnn_transpose_(input: Tensor, dim0: _int, dim1: _int) -> Tensor: ... +def _mps_convolution( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + padding: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + groups: _int | SymInt, +) -> Tensor: ... +def _mps_convolution_transpose( + input: Tensor, + weight: Tensor, + padding: Sequence[_int | SymInt], + output_padding: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + groups: _int | SymInt, +) -> Tensor: ... +@overload +def _native_batch_norm_legit( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + running_mean: Tensor, + running_var: Tensor, + training: _bool, + momentum: _float, + eps: _float, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> tuple[Tensor, Tensor, Tensor]: ... +@overload +def _native_batch_norm_legit( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + training: _bool, + momentum: _float, + eps: _float, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> tuple[Tensor, Tensor, Tensor]: ... +def _native_batch_norm_legit_no_training( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + running_mean: Tensor, + running_var: Tensor, + momentum: _float, + eps: _float, +) -> tuple[Tensor, Tensor, Tensor]: ... +def _native_multi_head_attention( + query: Tensor, + key: Tensor, + value: Tensor, + embed_dim: _int, + num_head: _int, + qkv_weight: Tensor, + qkv_bias: Tensor, + proj_weight: Tensor, + proj_bias: Tensor, + mask: Tensor | None = None, + need_weights: _bool = True, + average_attn_weights: _bool = True, + mask_type: _int | None = None, +) -> tuple[Tensor, Tensor]: ... +def _neg_view(input: Tensor) -> Tensor: ... +def _neg_view_copy(input: Tensor, *, out: Tensor | None = None) -> Tensor: ... +def _nested_compute_contiguous_strides_offsets( + nested_size: Tensor, +) -> tuple[Tensor, Tensor]: ... +def _nested_from_padded( + padded: Tensor, + cpu_nested_shape_example: Tensor, + fuse_transform_0213: _bool = False, +) -> Tensor: ... +def _nested_from_padded_and_nested_example( + padded: Tensor, + nt_example: Tensor, +) -> Tensor: ... +def _nested_from_padded_tensor( + padded: Tensor, + offsets: Tensor, + dummy: Tensor, + ragged_idx: _int = 1, + min_seqlen: Tensor | None = None, + max_seqlen: Tensor | None = None, + sum_S: _int | SymInt | None = None, +) -> Tensor: ... +def _nested_get_jagged_dummy(any: Tensor) -> Tensor: ... +def _nested_get_lengths(input: Tensor) -> Tensor: ... +def _nested_get_max_seqlen(input: Tensor) -> Tensor: ... +def _nested_get_min_seqlen(input: Tensor) -> Tensor: ... +def _nested_get_offsets(input: Tensor) -> Tensor: ... +def _nested_get_ragged_idx(input: Tensor) -> _int: ... +def _nested_get_values(input: Tensor) -> Tensor: ... +def _nested_get_values_copy( + input: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _nested_tensor_from_mask( + t: Tensor, + mask: Tensor, + mask_check: _bool = True, +) -> Tensor: ... +def _nested_tensor_from_mask_left_aligned(t: Tensor, mask: Tensor) -> _bool: ... +def _nested_tensor_from_tensor_list( + list: tuple[Tensor, ...] | list[Tensor] | None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = None, +) -> Tensor: ... +def _nested_tensor_softmax_with_shape( + input: Tensor, + query: Tensor, +) -> Tensor: ... +def _nested_view_from_buffer( + input: Tensor, + nested_size: Tensor, + nested_strides: Tensor, + offsets: Tensor, +) -> Tensor: ... +def _nested_view_from_buffer_copy( + input: Tensor, + nested_size: Tensor, + nested_strides: Tensor, + offsets: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _nested_view_from_jagged( + input: Tensor, + offsets: Tensor, + dummy: Tensor, + lengths: Tensor | None = None, + ragged_idx: _int = 1, + min_seqlen: Tensor | None = None, + max_seqlen: Tensor | None = None, +) -> Tensor: ... +def _nested_view_from_jagged_copy( + input: Tensor, + offsets: Tensor, + dummy: Tensor, + lengths: Tensor | None = None, + ragged_idx: _int = 1, + min_seqlen: Tensor | None = None, + max_seqlen: Tensor | None = None, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _nnpack_available() -> _bool: ... +def _nnpack_spatial_convolution( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + padding: _int | SymInt | Sequence[_int | SymInt], + stride: _int | SymInt | Sequence[_int | SymInt] = 1, +) -> Tensor: ... +def _pack_padded_sequence( + input: Tensor, + lengths: Tensor, + batch_first: _bool, +) -> tuple[Tensor, Tensor]: ... +def _pad_packed_sequence( + data: Tensor, + batch_sizes: Tensor, + batch_first: _bool, + padding_value: Number | _complex, + total_length: _int, +) -> tuple[Tensor, Tensor]: ... +def _pin_memory( + input: Tensor, + device: DeviceLikeType | None = None, +) -> Tensor: ... +def _prelu_kernel(input: Tensor, weight: Tensor) -> Tensor: ... +def _print(s: str) -> None: ... +def _propagate_xla_data(input: Tensor, output: Tensor) -> None: ... +def _remove_batch_dim( + input: Tensor, + level: _int, + batch_size: _int | SymInt, + out_dim: _int, +) -> Tensor: ... +def _reshape_alias_copy( + input: Tensor, + size: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + *, + out: Tensor | None = None, +) -> Tensor: ... +def _reshape_from_tensor(input: Tensor, shape: Tensor) -> Tensor: ... +def _resize_output_( + input: Tensor, + size: Sequence[_int | SymInt], + device: DeviceLikeType | None, +) -> Tensor: ... +def _rowwise_prune( + weight: Tensor, + mask: Tensor, + compressed_indices_dtype: _dtype, +) -> tuple[Tensor, Tensor]: ... +def _safe_softmax( + input: Tensor, + dim: _int, + dtype: _dtype | None = None, +) -> Tensor: ... +def _sample_dirichlet( + input: Tensor, + generator: Generator | None = None, +) -> Tensor: ... +def _saturate_weight_to_fp16(weight: Tensor) -> Tensor: ... +def _scaled_dot_product_attention_math( + query: Tensor, + key: Tensor, + value: Tensor, + attn_mask: Tensor | None = None, + dropout_p: _float = 0.0, + is_causal: _bool = False, + dropout_mask: Tensor | None = None, + *, + scale: _float | None = None, + enable_gqa: _bool = False, +) -> tuple[Tensor, Tensor]: ... +def _scaled_dot_product_attention_math_for_mps( + query: Tensor, + key: Tensor, + value: Tensor, + attn_mask: Tensor | None = None, + dropout_p: _float = 0.0, + is_causal: _bool = False, + dropout_mask: Tensor | None = None, + *, + scale: _float | None = None, +) -> tuple[Tensor, Tensor]: ... +def _scaled_dot_product_cudnn_attention( + query: Tensor, + key: Tensor, + value: Tensor, + attn_bias: Tensor | None, + compute_log_sumexp: _bool, + dropout_p: _float = 0.0, + is_causal: _bool = False, + return_debug_mask: _bool = False, + *, + scale: _float | None = None, +) -> torch.return_types._scaled_dot_product_cudnn_attention: ... +def _scaled_dot_product_efficient_attention( + query: Tensor, + key: Tensor, + value: Tensor, + attn_bias: Tensor | None, + compute_log_sumexp: _bool, + dropout_p: _float = 0.0, + is_causal: _bool = False, + *, + scale: _float | None = None, +) -> torch.return_types._scaled_dot_product_efficient_attention: ... +def _scaled_dot_product_flash_attention( + query: Tensor, + key: Tensor, + value: Tensor, + dropout_p: _float = 0.0, + is_causal: _bool = False, + return_debug_mask: _bool = False, + *, + scale: _float | None = None, +) -> torch.return_types._scaled_dot_product_flash_attention: ... +def _scaled_dot_product_flash_attention_for_cpu( + query: Tensor, + key: Tensor, + value: Tensor, + dropout_p: _float = 0.0, + is_causal: _bool = False, + *, + attn_mask: Tensor | None = None, + scale: _float | None = None, +) -> torch.return_types._scaled_dot_product_flash_attention_for_cpu: ... +def _scaled_grouped_mm( + input: Tensor, + mat2: Tensor, + scale_a: Tensor, + scale_b: Tensor, + offs: Tensor | None = None, + bias: Tensor | None = None, + scale_result: Tensor | None = None, + out_dtype: _dtype | None = None, + use_fast_accum: _bool = False, +) -> Tensor: ... +def _scaled_grouped_mm_v2( + input: Tensor, + mat2: Tensor, + scale_a: tuple[Tensor, ...] | list[Tensor] | None, + recipe_a: _size, + swizzle_a: _size, + scale_b: tuple[Tensor, ...] | list[Tensor] | None, + recipe_b: _size, + swizzle_b: _size, + offs: Tensor | None = None, + bias: Tensor | None = None, + out_dtype: _dtype | None = None, + contraction_dim: _size = (), + use_fast_accum: _bool = False, +) -> Tensor: ... +def _scaled_mm( + input: Tensor, + mat2: Tensor, + scale_a: Tensor, + scale_b: Tensor, + bias: Tensor | None = None, + scale_result: Tensor | None = None, + out_dtype: _dtype | None = None, + use_fast_accum: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _scaled_mm_v2( + input: Tensor, + mat2: Tensor, + scale_a: tuple[Tensor, ...] | list[Tensor] | None, + recipe_a: _size, + swizzle_a: _size, + scale_b: tuple[Tensor, ...] | list[Tensor] | None, + recipe_b: _size, + swizzle_b: _size, + bias: Tensor | None, + out_dtype: _dtype | None, + contraction_dim: _size = (), + use_fast_accum: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _shape_as_tensor(input: Tensor) -> Tensor: ... +def _sobol_engine_draw( + quasi: Tensor, + n: _int, + sobolstate: Tensor, + dimension: _int, + num_generated: _int, + dtype: _dtype | None, +) -> tuple[Tensor, Tensor]: ... +def _sobol_engine_ff_( + input: Tensor, + n: _int, + sobolstate: Tensor, + dimension: _int, + num_generated: _int, +) -> Tensor: ... +def _sobol_engine_initialize_state_( + input: Tensor, + dimension: _int, +) -> Tensor: ... +def _sobol_engine_scramble_( + input: Tensor, + ltm: Tensor, + dimension: _int, +) -> Tensor: ... +def _softmax( + input: Tensor, + dim: _int, + half_to_float: _bool, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _softmax_backward_data( + grad_output: Tensor, + output: Tensor, + dim: _int, + input_dtype: _dtype, + *, + grad_input: Tensor | None = None, +) -> Tensor: ... +def _sparse_broadcast_to(input: Tensor, size: _size) -> Tensor: ... +def _sparse_broadcast_to_copy( + input: Tensor, + size: _size, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _sparse_csr_prod( + input: Tensor, + dim: _int | _size, + keepdim: _bool = False, + *, + dtype: _dtype | None = None, +) -> Tensor: ... +def _sparse_csr_sum( + input: Tensor, + dim: _int | _size, + keepdim: _bool = False, + *, + dtype: _dtype | None = None, +) -> Tensor: ... +def _sparse_log_softmax_backward_data( + grad_output: Tensor, + output: Tensor, + dim: _int, + input: Tensor, +) -> Tensor: ... +def _sparse_semi_structured_addmm( + input: Tensor, + mat1: Tensor, + mat1_meta: Tensor, + mat2: Tensor, + *, + alpha: Number | _complex = 1, + beta: Number | _complex = 1, + out_dtype: _dtype | None = None, +) -> Tensor: ... +def _sparse_semi_structured_apply( + input: Tensor, + thread_masks: Tensor, +) -> tuple[Tensor, Tensor]: ... +def _sparse_semi_structured_apply_dense( + input: Tensor, + thread_masks: Tensor, +) -> Tensor: ... +def _sparse_semi_structured_linear( + input: Tensor, + weight: Tensor, + meta: Tensor, + *, + bias: Tensor | None = None, + activation: str | None = None, + out_dtype: _dtype | None = None, +) -> Tensor: ... +def _sparse_semi_structured_mm( + mat1: Tensor, + mat1_meta: Tensor, + mat2: Tensor, + *, + out_dtype: _dtype | None = None, +) -> Tensor: ... +def _sparse_semi_structured_tile( + input: Tensor, + algorithm: str = "", + use_cutlass: _bool = True, +) -> tuple[Tensor, Tensor, Tensor, Tensor, Tensor]: ... +def _sparse_softmax_backward_data( + grad_output: Tensor, + output: Tensor, + dim: _int, + input: Tensor, +) -> Tensor: ... +def _sparse_sparse_matmul(input: Tensor, other: Tensor) -> Tensor: ... +@overload +def _sparse_sum(input: Tensor) -> Tensor: ... +@overload +def _sparse_sum(input: Tensor, *, dtype: _dtype) -> Tensor: ... +@overload +def _sparse_sum(input: Tensor, dim: _int | _size) -> Tensor: ... +@overload +def _sparse_sum( + input: Tensor, + dim: _int | _size, + *, + dtype: _dtype, +) -> Tensor: ... +def _stack( + tensors: tuple[Tensor, ...] | list[Tensor] | None, + dim: _int = 0, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _standard_gamma( + input: Tensor, + generator: Generator | None = None, +) -> Tensor: ... +def _standard_gamma_grad(input: Tensor, output: Tensor) -> Tensor: ... +def _sync(t: Tensor) -> None: ... +@overload +def _test_autograd_multiple_dispatch(input: Tensor) -> Tensor: ... +@overload +def _test_autograd_multiple_dispatch(input: Tensor, b: _bool) -> Tensor: ... +def _test_autograd_multiple_dispatch_view(input: Tensor) -> Tensor: ... +def _test_autograd_multiple_dispatch_view_copy( + input: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _test_check_tensor(input: Tensor) -> Tensor: ... +def _test_functorch_fallback(input: Tensor, other: Tensor) -> Tensor: ... +def _test_parallel_materialize( + input: Tensor, + num_parallel: _int, + skip_first: _bool = False, +) -> Tensor: ... +def _test_serialization_subcmul( + input: Tensor, + other: Tensor, + alpha: Number | _complex = 1, +) -> Tensor: ... +def _to_cpu( + tensors: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: ... +def _to_functional_tensor(t: Tensor) -> Tensor: ... +def _to_sparse_semi_structured(dense: Tensor) -> tuple[Tensor, Tensor]: ... +def _transform_bias_rescale_qkv( + qkv: Tensor, + qkv_bias: Tensor, + num_heads: _int, +) -> tuple[Tensor, Tensor, Tensor]: ... +def _transformer_encoder_layer_fwd( + src: Tensor, + embed_dim: _int, + num_heads: _int, + qkv_weight: Tensor, + qkv_bias: Tensor, + proj_weight: Tensor, + proj_bias: Tensor, + use_gelu: _bool, + norm_first: _bool, + eps: _float, + norm_weight_1: Tensor, + norm_bias_1: Tensor, + norm_weight_2: Tensor, + norm_bias_2: Tensor, + ffn_weight_1: Tensor, + ffn_bias_1: Tensor, + ffn_weight_2: Tensor, + ffn_bias_2: Tensor, + mask: Tensor | None = None, + mask_type: _int | None = None, +) -> Tensor: ... +def _trilinear( + i1: Tensor, + i2: Tensor, + i3: Tensor, + expand1: _size, + expand2: _size, + expand3: _size, + sumdim: _size, + unroll_dim: _int = 1, +) -> Tensor: ... +def _triton_multi_head_attention( + query: Tensor, + key: Tensor, + value: Tensor, + embed_dim: _int, + num_head: _int, + qkv_weight: Tensor, + qkv_bias: Tensor, + proj_weight: Tensor, + proj_bias: Tensor, + mask: Tensor | None = None, +) -> Tensor: ... +def _triton_scaled_dot_attention( + q: Tensor, + k: Tensor, + v: Tensor, + dropout_p: _float = 0.0, +) -> Tensor: ... +def _unique( + input: Tensor, + sorted: _bool = True, + return_inverse: _bool = False, +) -> tuple[Tensor, Tensor]: ... +def _unique2( + input: Tensor, + sorted: _bool = True, + return_inverse: _bool = False, + return_counts: _bool = False, +) -> tuple[Tensor, Tensor, Tensor]: ... +def _unpack_dual( + dual: Tensor, + level: _int, +) -> torch.return_types._unpack_dual: ... +def _unsafe_index( + input: Tensor, + indices: tuple[Tensor, ...] | list[Tensor] | None, +) -> Tensor: ... +def _unsafe_index_put( + input: Tensor, + indices: tuple[Tensor, ...] | list[Tensor] | None, + values: Tensor, + accumulate: _bool = False, +) -> Tensor: ... +def _unsafe_masked_index( + input: Tensor, + mask: Tensor, + indices: tuple[Tensor, ...] | list[Tensor] | None, + fill: Number | _complex, +) -> Tensor: ... +def _unsafe_masked_index_put_accumulate( + input: Tensor, + mask: Tensor, + indices: tuple[Tensor, ...] | list[Tensor] | None, + values: Tensor, +) -> Tensor: ... +@overload +def _use_cudnn_ctc_loss( + log_probs: Tensor, + targets: Tensor, + input_lengths: Tensor, + target_lengths: Tensor, + blank: _int, +) -> _bool: ... +@overload +def _use_cudnn_ctc_loss( + log_probs: Tensor, + targets: Tensor, + input_lengths: _size, + target_lengths: _size, + blank: _int, +) -> _bool: ... +def _use_cudnn_rnn_flatten_weight() -> _bool: ... +def _validate_compressed_sparse_indices( + is_crow: _bool, + compressed_idx: Tensor, + plain_idx: Tensor, + cdim: _int, + dim: _int, + nnz: _int, +) -> None: ... +def _validate_sparse_bsc_tensor_args( + ccol_indices: Tensor, + row_indices: Tensor, + values: Tensor, + size: _size, + check_pinning: _bool | None = None, +) -> None: ... +def _validate_sparse_bsr_tensor_args( + crow_indices: Tensor, + col_indices: Tensor, + values: Tensor, + size: _size, + check_pinning: _bool | None = None, +) -> None: ... +def _validate_sparse_compressed_tensor_args( + compressed_indices: Tensor, + plain_indices: Tensor, + values: Tensor, + size: _size, + layout: _layout, + check_pinning: _bool | None = None, +) -> None: ... +def _validate_sparse_coo_tensor_args( + indices: Tensor, + values: Tensor, + size: _size, + is_coalesced: _bool | None = None, + check_pinning: _bool | None = None, +) -> None: ... +def _validate_sparse_csc_tensor_args( + ccol_indices: Tensor, + row_indices: Tensor, + values: Tensor, + size: _size, + check_pinning: _bool | None = None, +) -> None: ... +def _validate_sparse_csr_tensor_args( + crow_indices: Tensor, + col_indices: Tensor, + values: Tensor, + size: _size, + check_pinning: _bool | None = None, +) -> None: ... +def _values_copy(input: Tensor, *, out: Tensor | None = None) -> Tensor: ... +def _weight_int4pack_mm( + input: Tensor, + mat2: Tensor, + qGroupSize: _int, + qScaleAndZeros: Tensor, +) -> Tensor: ... +def _weight_int4pack_mm_for_cpu( + input: Tensor, + mat2: Tensor, + qGroupSize: _int, + qScaleAndZeros: Tensor, +) -> Tensor: ... +def _weight_int4pack_mm_with_scales_and_zeros( + input: Tensor, + mat2: Tensor, + qGroupSize: _int, + qScale: Tensor, + qZeros: Tensor, +) -> Tensor: ... +def _weight_int8pack_mm( + input: Tensor, + mat2: Tensor, + scales: Tensor, +) -> Tensor: ... +def _weight_norm(v: Tensor, g: Tensor, dim: _int = 0) -> Tensor: ... +def _weight_norm_interface( + v: Tensor, + g: Tensor, + dim: _int = 0, +) -> tuple[Tensor, Tensor]: ... +def _wrapped_linear_prepack( + weight: Tensor, + weight_scale: Tensor, + weight_zero_point: Tensor, + bias: Tensor, +) -> Tensor: ... +def _wrapped_quantized_linear_prepacked( + input: Tensor, + input_scale: Tensor, + input_zero_point: Tensor, + packed_weight: Tensor, + output_scale: Tensor, + output_zero_point: Tensor, + out_channel: _int, +) -> Tensor: ... +def abs(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + abs(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Computes the absolute value of each element in :attr:`input`. + + .. math:: + \text{out}_{i} = |\text{input}_{i}| + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.abs(torch.tensor([-1, -2, 3])) + tensor([ 1, 2, 3]) + """ + +def abs_(input: Tensor) -> Tensor: ... +def absolute(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + absolute(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Alias for :func:`torch.abs` + """ + +def acos(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + acos(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Returns a new tensor with the arccosine (in radians) of each element in :attr:`input`. + + .. math:: + \text{out}_{i} = \cos^{-1}(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.3348, -0.5889, 0.2005, -0.1584]) + >>> torch.acos(a) + tensor([ 1.2294, 2.2004, 1.3690, 1.7298]) + """ + +def acos_(input: Tensor) -> Tensor: ... +def acosh(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + acosh(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Returns a new tensor with the inverse hyperbolic cosine of the elements of :attr:`input`. + + .. math:: + \text{out}_{i} = \cosh^{-1}(\text{input}_{i}) + + Note: + The domain of the inverse hyperbolic cosine is `[1, inf)` and values outside this range + will be mapped to ``NaN``, except for `+ INF` for which the output is mapped to `+ INF`. + + Args: + input (Tensor): the input tensor. + + Keyword arguments: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4).uniform_(1, 2) + >>> a + tensor([ 1.3192, 1.9915, 1.9674, 1.7151 ]) + >>> torch.acosh(a) + tensor([ 0.7791, 1.3120, 1.2979, 1.1341 ]) + """ + +def acosh_(input: Tensor) -> Tensor: ... +def adaptive_avg_pool1d(input: Tensor, output_size: _int | _size) -> Tensor: ... +def adaptive_max_pool1d( + input: Tensor, + output_size: _int | _size, +) -> tuple[Tensor, Tensor]: ... +@overload +def add( + input: Tensor | Number | _complex, + other: Tensor | Number | _complex, + *, + alpha: Number | _complex | None = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + add(input, other, *, alpha=1, out=None) -> Tensor + + Adds :attr:`other`, scaled by :attr:`alpha`, to :attr:`input`. + + .. math:: + \text{{out}}_i = \text{{input}}_i + \text{{alpha}} \times \text{{other}}_i + + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer, float, and complex inputs. + + Args: + input (Tensor): the input tensor. + other (Tensor or Number): the tensor or number to add to :attr:`input`. + + Keyword arguments: + alpha (Number): the multiplier for :attr:`other`. + out (Tensor, optional): the output tensor. + + Examples:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.0202, 1.0985, 1.3506, -0.6056]) + >>> torch.add(a, 20) + tensor([ 20.0202, 21.0985, 21.3506, 19.3944]) + + >>> b = torch.randn(4) + >>> b + tensor([-0.9732, -0.3497, 0.6245, 0.4022]) + >>> c = torch.randn(4, 1) + >>> c + tensor([[ 0.3743], + [-1.7724], + [-0.5811], + [-0.8017]]) + >>> torch.add(b, c, alpha=10) + tensor([[ 2.7695, 3.3930, 4.3672, 4.1450], + [-18.6971, -18.0736, -17.0994, -17.3216], + [ -6.7845, -6.1610, -5.1868, -5.4090], + [ -8.9902, -8.3667, -7.3925, -7.6147]]) + """ + +@overload +def add(self: Tensor, alpha: Number | _complex, other: Tensor) -> Tensor: + r""" + add(input, other, *, alpha=1, out=None) -> Tensor + + Adds :attr:`other`, scaled by :attr:`alpha`, to :attr:`input`. + + .. math:: + \text{{out}}_i = \text{{input}}_i + \text{{alpha}} \times \text{{other}}_i + + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer, float, and complex inputs. + + Args: + input (Tensor): the input tensor. + other (Tensor or Number): the tensor or number to add to :attr:`input`. + + Keyword arguments: + alpha (Number): the multiplier for :attr:`other`. + out (Tensor, optional): the output tensor. + + Examples:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.0202, 1.0985, 1.3506, -0.6056]) + >>> torch.add(a, 20) + tensor([ 20.0202, 21.0985, 21.3506, 19.3944]) + + >>> b = torch.randn(4) + >>> b + tensor([-0.9732, -0.3497, 0.6245, 0.4022]) + >>> c = torch.randn(4, 1) + >>> c + tensor([[ 0.3743], + [-1.7724], + [-0.5811], + [-0.8017]]) + >>> torch.add(b, c, alpha=10) + tensor([[ 2.7695, 3.3930, 4.3672, 4.1450], + [-18.6971, -18.0736, -17.0994, -17.3216], + [ -6.7845, -6.1610, -5.1868, -5.4090], + [ -8.9902, -8.3667, -7.3925, -7.6147]]) + """ + +@overload +def add( + self: Tensor, + alpha: Number | _complex, + other: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + add(input, other, *, alpha=1, out=None) -> Tensor + + Adds :attr:`other`, scaled by :attr:`alpha`, to :attr:`input`. + + .. math:: + \text{{out}}_i = \text{{input}}_i + \text{{alpha}} \times \text{{other}}_i + + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer, float, and complex inputs. + + Args: + input (Tensor): the input tensor. + other (Tensor or Number): the tensor or number to add to :attr:`input`. + + Keyword arguments: + alpha (Number): the multiplier for :attr:`other`. + out (Tensor, optional): the output tensor. + + Examples:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.0202, 1.0985, 1.3506, -0.6056]) + >>> torch.add(a, 20) + tensor([ 20.0202, 21.0985, 21.3506, 19.3944]) + + >>> b = torch.randn(4) + >>> b + tensor([-0.9732, -0.3497, 0.6245, 0.4022]) + >>> c = torch.randn(4, 1) + >>> c + tensor([[ 0.3743], + [-1.7724], + [-0.5811], + [-0.8017]]) + >>> torch.add(b, c, alpha=10) + tensor([[ 2.7695, 3.3930, 4.3672, 4.1450], + [-18.6971, -18.0736, -17.0994, -17.3216], + [ -6.7845, -6.1610, -5.1868, -5.4090], + [ -8.9902, -8.3667, -7.3925, -7.6147]]) + """ + +@overload +def addbmm( + beta: Number | _complex, + self: Tensor, + alpha: Number | _complex, + batch1: Tensor, + batch2: Tensor, +) -> Tensor: + r""" + addbmm(input, batch1, batch2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a batch matrix-matrix product of matrices stored + in :attr:`batch1` and :attr:`batch2`, + with a reduced add step (all matrix multiplications get accumulated + along the first dimension). + :attr:`input` is added to the final result. + + :attr:`batch1` and :attr:`batch2` must be 3-D tensors each containing the + same number of matrices. + + If :attr:`batch1` is a :math:`(b \times n \times m)` tensor, :attr:`batch2` is a + :math:`(b \times m \times p)` tensor, :attr:`input` must be + :ref:`broadcastable ` with a :math:`(n \times p)` tensor + and :attr:`out` will be a :math:`(n \times p)` tensor. + + .. math:: + out = \beta\ \text{input} + \alpha\ (\sum_{i=0}^{b-1} \text{batch1}_i \mathbin{@} \text{batch2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and :attr:`alpha` + must be real numbers, otherwise they should be integers. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): matrix to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for `batch1 @ batch2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(3, 5) + >>> batch1 = torch.randn(10, 3, 4) + >>> batch2 = torch.randn(10, 4, 5) + >>> torch.addbmm(M, batch1, batch2) + tensor([[ 6.6311, 0.0503, 6.9768, -12.0362, -2.1653], + [ -4.8185, -1.4255, -6.6760, 8.9453, 2.5743], + [ -3.8202, 4.3691, 1.0943, -1.1109, 5.4730]]) + """ + +@overload +def addbmm( + beta: Number | _complex, + self: Tensor, + alpha: Number | _complex, + batch1: Tensor, + batch2: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + addbmm(input, batch1, batch2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a batch matrix-matrix product of matrices stored + in :attr:`batch1` and :attr:`batch2`, + with a reduced add step (all matrix multiplications get accumulated + along the first dimension). + :attr:`input` is added to the final result. + + :attr:`batch1` and :attr:`batch2` must be 3-D tensors each containing the + same number of matrices. + + If :attr:`batch1` is a :math:`(b \times n \times m)` tensor, :attr:`batch2` is a + :math:`(b \times m \times p)` tensor, :attr:`input` must be + :ref:`broadcastable ` with a :math:`(n \times p)` tensor + and :attr:`out` will be a :math:`(n \times p)` tensor. + + .. math:: + out = \beta\ \text{input} + \alpha\ (\sum_{i=0}^{b-1} \text{batch1}_i \mathbin{@} \text{batch2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and :attr:`alpha` + must be real numbers, otherwise they should be integers. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): matrix to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for `batch1 @ batch2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(3, 5) + >>> batch1 = torch.randn(10, 3, 4) + >>> batch2 = torch.randn(10, 4, 5) + >>> torch.addbmm(M, batch1, batch2) + tensor([[ 6.6311, 0.0503, 6.9768, -12.0362, -2.1653], + [ -4.8185, -1.4255, -6.6760, 8.9453, 2.5743], + [ -3.8202, 4.3691, 1.0943, -1.1109, 5.4730]]) + """ + +@overload +def addbmm( + input: Tensor, + batch1: Tensor, + batch2: Tensor, + *, + beta: Number | _complex = 1, + alpha: Number | _complex = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + addbmm(input, batch1, batch2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a batch matrix-matrix product of matrices stored + in :attr:`batch1` and :attr:`batch2`, + with a reduced add step (all matrix multiplications get accumulated + along the first dimension). + :attr:`input` is added to the final result. + + :attr:`batch1` and :attr:`batch2` must be 3-D tensors each containing the + same number of matrices. + + If :attr:`batch1` is a :math:`(b \times n \times m)` tensor, :attr:`batch2` is a + :math:`(b \times m \times p)` tensor, :attr:`input` must be + :ref:`broadcastable ` with a :math:`(n \times p)` tensor + and :attr:`out` will be a :math:`(n \times p)` tensor. + + .. math:: + out = \beta\ \text{input} + \alpha\ (\sum_{i=0}^{b-1} \text{batch1}_i \mathbin{@} \text{batch2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and :attr:`alpha` + must be real numbers, otherwise they should be integers. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): matrix to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for `batch1 @ batch2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(3, 5) + >>> batch1 = torch.randn(10, 3, 4) + >>> batch2 = torch.randn(10, 4, 5) + >>> torch.addbmm(M, batch1, batch2) + tensor([[ 6.6311, 0.0503, 6.9768, -12.0362, -2.1653], + [ -4.8185, -1.4255, -6.6760, 8.9453, 2.5743], + [ -3.8202, 4.3691, 1.0943, -1.1109, 5.4730]]) + """ + +@overload +def addbmm( + beta: Number | _complex, + self: Tensor, + batch1: Tensor, + batch2: Tensor, +) -> Tensor: + r""" + addbmm(input, batch1, batch2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a batch matrix-matrix product of matrices stored + in :attr:`batch1` and :attr:`batch2`, + with a reduced add step (all matrix multiplications get accumulated + along the first dimension). + :attr:`input` is added to the final result. + + :attr:`batch1` and :attr:`batch2` must be 3-D tensors each containing the + same number of matrices. + + If :attr:`batch1` is a :math:`(b \times n \times m)` tensor, :attr:`batch2` is a + :math:`(b \times m \times p)` tensor, :attr:`input` must be + :ref:`broadcastable ` with a :math:`(n \times p)` tensor + and :attr:`out` will be a :math:`(n \times p)` tensor. + + .. math:: + out = \beta\ \text{input} + \alpha\ (\sum_{i=0}^{b-1} \text{batch1}_i \mathbin{@} \text{batch2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and :attr:`alpha` + must be real numbers, otherwise they should be integers. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): matrix to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for `batch1 @ batch2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(3, 5) + >>> batch1 = torch.randn(10, 3, 4) + >>> batch2 = torch.randn(10, 4, 5) + >>> torch.addbmm(M, batch1, batch2) + tensor([[ 6.6311, 0.0503, 6.9768, -12.0362, -2.1653], + [ -4.8185, -1.4255, -6.6760, 8.9453, 2.5743], + [ -3.8202, 4.3691, 1.0943, -1.1109, 5.4730]]) + """ + +@overload +def addbmm( + beta: Number | _complex, + self: Tensor, + batch1: Tensor, + batch2: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + addbmm(input, batch1, batch2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a batch matrix-matrix product of matrices stored + in :attr:`batch1` and :attr:`batch2`, + with a reduced add step (all matrix multiplications get accumulated + along the first dimension). + :attr:`input` is added to the final result. + + :attr:`batch1` and :attr:`batch2` must be 3-D tensors each containing the + same number of matrices. + + If :attr:`batch1` is a :math:`(b \times n \times m)` tensor, :attr:`batch2` is a + :math:`(b \times m \times p)` tensor, :attr:`input` must be + :ref:`broadcastable ` with a :math:`(n \times p)` tensor + and :attr:`out` will be a :math:`(n \times p)` tensor. + + .. math:: + out = \beta\ \text{input} + \alpha\ (\sum_{i=0}^{b-1} \text{batch1}_i \mathbin{@} \text{batch2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and :attr:`alpha` + must be real numbers, otherwise they should be integers. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): matrix to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for `batch1 @ batch2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(3, 5) + >>> batch1 = torch.randn(10, 3, 4) + >>> batch2 = torch.randn(10, 4, 5) + >>> torch.addbmm(M, batch1, batch2) + tensor([[ 6.6311, 0.0503, 6.9768, -12.0362, -2.1653], + [ -4.8185, -1.4255, -6.6760, 8.9453, 2.5743], + [ -3.8202, 4.3691, 1.0943, -1.1109, 5.4730]]) + """ + +@overload +def addcdiv( + self: Tensor, + value: Number | _complex, + tensor1: Tensor, + tensor2: Tensor, +) -> Tensor: + r""" + addcdiv(input, tensor1, tensor2, *, value=1, out=None) -> Tensor + + Performs the element-wise division of :attr:`tensor1` by :attr:`tensor2`, + multiplies the result by the scalar :attr:`value` and adds it to :attr:`input`. + + .. warning:: + Integer division with addcdiv is no longer supported, and in a future + release addcdiv will perform a true division of tensor1 and tensor2. + The historic addcdiv behavior can be implemented as + (input + value * torch.trunc(tensor1 / tensor2)).to(input.dtype) + for integer inputs and as (input + value * tensor1 / tensor2) for float inputs. + The future addcdiv behavior is just the latter implementation: + (input + value * tensor1 / tensor2), for all dtypes. + + .. math:: + \text{out}_i = \text{input}_i + \text{value} \times \frac{\text{tensor1}_i}{\text{tensor2}_i} + + + The shapes of :attr:`input`, :attr:`tensor1`, and :attr:`tensor2` must be + :ref:`broadcastable `. + + For inputs of type `FloatTensor` or `DoubleTensor`, :attr:`value` must be + a real number, otherwise an integer. + + Args: + input (Tensor): the tensor to be added + tensor1 (Tensor): the numerator tensor + tensor2 (Tensor): the denominator tensor + + Keyword args: + value (Number, optional): multiplier for :math:`\text{tensor1} / \text{tensor2}` + out (Tensor, optional): the output tensor. + + Example:: + + >>> t = torch.randn(1, 3) + >>> t1 = torch.randn(3, 1) + >>> t2 = torch.randn(1, 3) + >>> torch.addcdiv(t, t1, t2, value=0.1) + tensor([[-0.2312, -3.6496, 0.1312], + [-1.0428, 3.4292, -0.1030], + [-0.5369, -0.9829, 0.0430]]) + """ + +@overload +def addcdiv( + self: Tensor, + value: Number | _complex, + tensor1: Tensor, + tensor2: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + addcdiv(input, tensor1, tensor2, *, value=1, out=None) -> Tensor + + Performs the element-wise division of :attr:`tensor1` by :attr:`tensor2`, + multiplies the result by the scalar :attr:`value` and adds it to :attr:`input`. + + .. warning:: + Integer division with addcdiv is no longer supported, and in a future + release addcdiv will perform a true division of tensor1 and tensor2. + The historic addcdiv behavior can be implemented as + (input + value * torch.trunc(tensor1 / tensor2)).to(input.dtype) + for integer inputs and as (input + value * tensor1 / tensor2) for float inputs. + The future addcdiv behavior is just the latter implementation: + (input + value * tensor1 / tensor2), for all dtypes. + + .. math:: + \text{out}_i = \text{input}_i + \text{value} \times \frac{\text{tensor1}_i}{\text{tensor2}_i} + + + The shapes of :attr:`input`, :attr:`tensor1`, and :attr:`tensor2` must be + :ref:`broadcastable `. + + For inputs of type `FloatTensor` or `DoubleTensor`, :attr:`value` must be + a real number, otherwise an integer. + + Args: + input (Tensor): the tensor to be added + tensor1 (Tensor): the numerator tensor + tensor2 (Tensor): the denominator tensor + + Keyword args: + value (Number, optional): multiplier for :math:`\text{tensor1} / \text{tensor2}` + out (Tensor, optional): the output tensor. + + Example:: + + >>> t = torch.randn(1, 3) + >>> t1 = torch.randn(3, 1) + >>> t2 = torch.randn(1, 3) + >>> torch.addcdiv(t, t1, t2, value=0.1) + tensor([[-0.2312, -3.6496, 0.1312], + [-1.0428, 3.4292, -0.1030], + [-0.5369, -0.9829, 0.0430]]) + """ + +@overload +def addcdiv( + input: Tensor, + tensor1: Tensor, + tensor2: Tensor, + *, + value: Number | _complex = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + addcdiv(input, tensor1, tensor2, *, value=1, out=None) -> Tensor + + Performs the element-wise division of :attr:`tensor1` by :attr:`tensor2`, + multiplies the result by the scalar :attr:`value` and adds it to :attr:`input`. + + .. warning:: + Integer division with addcdiv is no longer supported, and in a future + release addcdiv will perform a true division of tensor1 and tensor2. + The historic addcdiv behavior can be implemented as + (input + value * torch.trunc(tensor1 / tensor2)).to(input.dtype) + for integer inputs and as (input + value * tensor1 / tensor2) for float inputs. + The future addcdiv behavior is just the latter implementation: + (input + value * tensor1 / tensor2), for all dtypes. + + .. math:: + \text{out}_i = \text{input}_i + \text{value} \times \frac{\text{tensor1}_i}{\text{tensor2}_i} + + + The shapes of :attr:`input`, :attr:`tensor1`, and :attr:`tensor2` must be + :ref:`broadcastable `. + + For inputs of type `FloatTensor` or `DoubleTensor`, :attr:`value` must be + a real number, otherwise an integer. + + Args: + input (Tensor): the tensor to be added + tensor1 (Tensor): the numerator tensor + tensor2 (Tensor): the denominator tensor + + Keyword args: + value (Number, optional): multiplier for :math:`\text{tensor1} / \text{tensor2}` + out (Tensor, optional): the output tensor. + + Example:: + + >>> t = torch.randn(1, 3) + >>> t1 = torch.randn(3, 1) + >>> t2 = torch.randn(1, 3) + >>> torch.addcdiv(t, t1, t2, value=0.1) + tensor([[-0.2312, -3.6496, 0.1312], + [-1.0428, 3.4292, -0.1030], + [-0.5369, -0.9829, 0.0430]]) + """ + +@overload +def addcmul( + self: Tensor, + value: Number | _complex, + tensor1: Tensor, + tensor2: Tensor, +) -> Tensor: + r""" + addcmul(input, tensor1, tensor2, *, value=1, out=None) -> Tensor + + Performs the element-wise multiplication of :attr:`tensor1` + by :attr:`tensor2`, multiplies the result by the scalar :attr:`value` + and adds it to :attr:`input`. + + .. math:: + \text{out}_i = \text{input}_i + \text{value} \times \text{tensor1}_i \times \text{tensor2}_i + + The shapes of :attr:`tensor`, :attr:`tensor1`, and :attr:`tensor2` must be + :ref:`broadcastable `. + + For inputs of type `FloatTensor` or `DoubleTensor`, :attr:`value` must be + a real number, otherwise an integer. + + Args: + input (Tensor): the tensor to be added + tensor1 (Tensor): the tensor to be multiplied + tensor2 (Tensor): the tensor to be multiplied + + Keyword args: + value (Number, optional): multiplier for :math:`tensor1 .* tensor2` + out (Tensor, optional): the output tensor. + + Example:: + + >>> t = torch.randn(1, 3) + >>> t1 = torch.randn(3, 1) + >>> t2 = torch.randn(1, 3) + >>> torch.addcmul(t, t1, t2, value=0.1) + tensor([[-0.8635, -0.6391, 1.6174], + [-0.7617, -0.5879, 1.7388], + [-0.8353, -0.6249, 1.6511]]) + """ + +@overload +def addcmul( + self: Tensor, + value: Number | _complex, + tensor1: Tensor, + tensor2: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + addcmul(input, tensor1, tensor2, *, value=1, out=None) -> Tensor + + Performs the element-wise multiplication of :attr:`tensor1` + by :attr:`tensor2`, multiplies the result by the scalar :attr:`value` + and adds it to :attr:`input`. + + .. math:: + \text{out}_i = \text{input}_i + \text{value} \times \text{tensor1}_i \times \text{tensor2}_i + + The shapes of :attr:`tensor`, :attr:`tensor1`, and :attr:`tensor2` must be + :ref:`broadcastable `. + + For inputs of type `FloatTensor` or `DoubleTensor`, :attr:`value` must be + a real number, otherwise an integer. + + Args: + input (Tensor): the tensor to be added + tensor1 (Tensor): the tensor to be multiplied + tensor2 (Tensor): the tensor to be multiplied + + Keyword args: + value (Number, optional): multiplier for :math:`tensor1 .* tensor2` + out (Tensor, optional): the output tensor. + + Example:: + + >>> t = torch.randn(1, 3) + >>> t1 = torch.randn(3, 1) + >>> t2 = torch.randn(1, 3) + >>> torch.addcmul(t, t1, t2, value=0.1) + tensor([[-0.8635, -0.6391, 1.6174], + [-0.7617, -0.5879, 1.7388], + [-0.8353, -0.6249, 1.6511]]) + """ + +@overload +def addcmul( + input: Tensor, + tensor1: Tensor, + tensor2: Tensor, + *, + value: Number | _complex = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + addcmul(input, tensor1, tensor2, *, value=1, out=None) -> Tensor + + Performs the element-wise multiplication of :attr:`tensor1` + by :attr:`tensor2`, multiplies the result by the scalar :attr:`value` + and adds it to :attr:`input`. + + .. math:: + \text{out}_i = \text{input}_i + \text{value} \times \text{tensor1}_i \times \text{tensor2}_i + + The shapes of :attr:`tensor`, :attr:`tensor1`, and :attr:`tensor2` must be + :ref:`broadcastable `. + + For inputs of type `FloatTensor` or `DoubleTensor`, :attr:`value` must be + a real number, otherwise an integer. + + Args: + input (Tensor): the tensor to be added + tensor1 (Tensor): the tensor to be multiplied + tensor2 (Tensor): the tensor to be multiplied + + Keyword args: + value (Number, optional): multiplier for :math:`tensor1 .* tensor2` + out (Tensor, optional): the output tensor. + + Example:: + + >>> t = torch.randn(1, 3) + >>> t1 = torch.randn(3, 1) + >>> t2 = torch.randn(1, 3) + >>> torch.addcmul(t, t1, t2, value=0.1) + tensor([[-0.8635, -0.6391, 1.6174], + [-0.7617, -0.5879, 1.7388], + [-0.8353, -0.6249, 1.6511]]) + """ + +@overload +def addmm( + beta: Number | _complex, + self: Tensor, + alpha: Number | _complex, + mat1: Tensor, + mat2: Tensor, +) -> Tensor: + r""" + addmm(input, mat1, mat2, out_dtype=None, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a matrix multiplication of the matrices :attr:`mat1` and :attr:`mat2`. + The matrix :attr:`input` is added to the final result. + + If :attr:`mat1` is a :math:`(n \times m)` tensor, :attr:`mat2` is a + :math:`(m \times p)` tensor, then :attr:`input` must be + :ref:`broadcastable ` with a :math:`(n \times p)` tensor + and :attr:`out` will be a :math:`(n \times p)` tensor. + + :attr:`alpha` and :attr:`beta` are scaling factors on matrix-vector product between + :attr:`mat1` and :attr:`mat2` and the added matrix :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{mat1}_i \mathbin{@} \text{mat2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + This operation has support for arguments with :ref:`sparse layouts`. If + :attr:`input` is sparse the result will have the same layout and if :attr:`out` + is provided it must have the same layout as :attr:`input`. + + + .. warning:: + Sparse support is a beta feature and some layout(s)/dtype/device combinations may not be supported, + or may not have autograd support. If you notice missing functionality please + open a feature request. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): matrix to be added + mat1 (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + out_dtype (dtype, optional): the dtype of the output tensor, + Supported only on CUDA and for torch.float32 given + torch.float16/torch.bfloat16 input dtypes + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(2, 3) + >>> mat1 = torch.randn(2, 3) + >>> mat2 = torch.randn(3, 3) + >>> torch.addmm(M, mat1, mat2) + tensor([[-4.8716, 1.4671, -1.3746], + [ 0.7573, -3.9555, -2.8681]]) + """ + +@overload +def addmm( + beta: Number | _complex, + self: Tensor, + alpha: Number | _complex, + mat1: Tensor, + mat2: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + addmm(input, mat1, mat2, out_dtype=None, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a matrix multiplication of the matrices :attr:`mat1` and :attr:`mat2`. + The matrix :attr:`input` is added to the final result. + + If :attr:`mat1` is a :math:`(n \times m)` tensor, :attr:`mat2` is a + :math:`(m \times p)` tensor, then :attr:`input` must be + :ref:`broadcastable ` with a :math:`(n \times p)` tensor + and :attr:`out` will be a :math:`(n \times p)` tensor. + + :attr:`alpha` and :attr:`beta` are scaling factors on matrix-vector product between + :attr:`mat1` and :attr:`mat2` and the added matrix :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{mat1}_i \mathbin{@} \text{mat2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + This operation has support for arguments with :ref:`sparse layouts`. If + :attr:`input` is sparse the result will have the same layout and if :attr:`out` + is provided it must have the same layout as :attr:`input`. + + + .. warning:: + Sparse support is a beta feature and some layout(s)/dtype/device combinations may not be supported, + or may not have autograd support. If you notice missing functionality please + open a feature request. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): matrix to be added + mat1 (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + out_dtype (dtype, optional): the dtype of the output tensor, + Supported only on CUDA and for torch.float32 given + torch.float16/torch.bfloat16 input dtypes + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(2, 3) + >>> mat1 = torch.randn(2, 3) + >>> mat2 = torch.randn(3, 3) + >>> torch.addmm(M, mat1, mat2) + tensor([[-4.8716, 1.4671, -1.3746], + [ 0.7573, -3.9555, -2.8681]]) + """ + +@overload +def addmm( + input: Tensor, + mat1: Tensor, + mat2: Tensor, + *, + beta: Number | _complex = 1, + alpha: Number | _complex = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + addmm(input, mat1, mat2, out_dtype=None, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a matrix multiplication of the matrices :attr:`mat1` and :attr:`mat2`. + The matrix :attr:`input` is added to the final result. + + If :attr:`mat1` is a :math:`(n \times m)` tensor, :attr:`mat2` is a + :math:`(m \times p)` tensor, then :attr:`input` must be + :ref:`broadcastable ` with a :math:`(n \times p)` tensor + and :attr:`out` will be a :math:`(n \times p)` tensor. + + :attr:`alpha` and :attr:`beta` are scaling factors on matrix-vector product between + :attr:`mat1` and :attr:`mat2` and the added matrix :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{mat1}_i \mathbin{@} \text{mat2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + This operation has support for arguments with :ref:`sparse layouts`. If + :attr:`input` is sparse the result will have the same layout and if :attr:`out` + is provided it must have the same layout as :attr:`input`. + + + .. warning:: + Sparse support is a beta feature and some layout(s)/dtype/device combinations may not be supported, + or may not have autograd support. If you notice missing functionality please + open a feature request. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): matrix to be added + mat1 (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + out_dtype (dtype, optional): the dtype of the output tensor, + Supported only on CUDA and for torch.float32 given + torch.float16/torch.bfloat16 input dtypes + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(2, 3) + >>> mat1 = torch.randn(2, 3) + >>> mat2 = torch.randn(3, 3) + >>> torch.addmm(M, mat1, mat2) + tensor([[-4.8716, 1.4671, -1.3746], + [ 0.7573, -3.9555, -2.8681]]) + """ + +@overload +def addmm( + input: Tensor, + mat1: Tensor, + mat2: Tensor, + out_dtype: _dtype, + *, + beta: Number | _complex = 1, + alpha: Number | _complex = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + addmm(input, mat1, mat2, out_dtype=None, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a matrix multiplication of the matrices :attr:`mat1` and :attr:`mat2`. + The matrix :attr:`input` is added to the final result. + + If :attr:`mat1` is a :math:`(n \times m)` tensor, :attr:`mat2` is a + :math:`(m \times p)` tensor, then :attr:`input` must be + :ref:`broadcastable ` with a :math:`(n \times p)` tensor + and :attr:`out` will be a :math:`(n \times p)` tensor. + + :attr:`alpha` and :attr:`beta` are scaling factors on matrix-vector product between + :attr:`mat1` and :attr:`mat2` and the added matrix :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{mat1}_i \mathbin{@} \text{mat2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + This operation has support for arguments with :ref:`sparse layouts`. If + :attr:`input` is sparse the result will have the same layout and if :attr:`out` + is provided it must have the same layout as :attr:`input`. + + + .. warning:: + Sparse support is a beta feature and some layout(s)/dtype/device combinations may not be supported, + or may not have autograd support. If you notice missing functionality please + open a feature request. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): matrix to be added + mat1 (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + out_dtype (dtype, optional): the dtype of the output tensor, + Supported only on CUDA and for torch.float32 given + torch.float16/torch.bfloat16 input dtypes + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(2, 3) + >>> mat1 = torch.randn(2, 3) + >>> mat2 = torch.randn(3, 3) + >>> torch.addmm(M, mat1, mat2) + tensor([[-4.8716, 1.4671, -1.3746], + [ 0.7573, -3.9555, -2.8681]]) + """ + +@overload +def addmm( + beta: Number | _complex, + self: Tensor, + mat1: Tensor, + mat2: Tensor, +) -> Tensor: + r""" + addmm(input, mat1, mat2, out_dtype=None, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a matrix multiplication of the matrices :attr:`mat1` and :attr:`mat2`. + The matrix :attr:`input` is added to the final result. + + If :attr:`mat1` is a :math:`(n \times m)` tensor, :attr:`mat2` is a + :math:`(m \times p)` tensor, then :attr:`input` must be + :ref:`broadcastable ` with a :math:`(n \times p)` tensor + and :attr:`out` will be a :math:`(n \times p)` tensor. + + :attr:`alpha` and :attr:`beta` are scaling factors on matrix-vector product between + :attr:`mat1` and :attr:`mat2` and the added matrix :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{mat1}_i \mathbin{@} \text{mat2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + This operation has support for arguments with :ref:`sparse layouts`. If + :attr:`input` is sparse the result will have the same layout and if :attr:`out` + is provided it must have the same layout as :attr:`input`. + + + .. warning:: + Sparse support is a beta feature and some layout(s)/dtype/device combinations may not be supported, + or may not have autograd support. If you notice missing functionality please + open a feature request. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): matrix to be added + mat1 (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + out_dtype (dtype, optional): the dtype of the output tensor, + Supported only on CUDA and for torch.float32 given + torch.float16/torch.bfloat16 input dtypes + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(2, 3) + >>> mat1 = torch.randn(2, 3) + >>> mat2 = torch.randn(3, 3) + >>> torch.addmm(M, mat1, mat2) + tensor([[-4.8716, 1.4671, -1.3746], + [ 0.7573, -3.9555, -2.8681]]) + """ + +@overload +def addmm( + beta: Number | _complex, + self: Tensor, + mat1: Tensor, + mat2: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + addmm(input, mat1, mat2, out_dtype=None, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a matrix multiplication of the matrices :attr:`mat1` and :attr:`mat2`. + The matrix :attr:`input` is added to the final result. + + If :attr:`mat1` is a :math:`(n \times m)` tensor, :attr:`mat2` is a + :math:`(m \times p)` tensor, then :attr:`input` must be + :ref:`broadcastable ` with a :math:`(n \times p)` tensor + and :attr:`out` will be a :math:`(n \times p)` tensor. + + :attr:`alpha` and :attr:`beta` are scaling factors on matrix-vector product between + :attr:`mat1` and :attr:`mat2` and the added matrix :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{mat1}_i \mathbin{@} \text{mat2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + This operation has support for arguments with :ref:`sparse layouts`. If + :attr:`input` is sparse the result will have the same layout and if :attr:`out` + is provided it must have the same layout as :attr:`input`. + + + .. warning:: + Sparse support is a beta feature and some layout(s)/dtype/device combinations may not be supported, + or may not have autograd support. If you notice missing functionality please + open a feature request. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): matrix to be added + mat1 (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + out_dtype (dtype, optional): the dtype of the output tensor, + Supported only on CUDA and for torch.float32 given + torch.float16/torch.bfloat16 input dtypes + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(2, 3) + >>> mat1 = torch.randn(2, 3) + >>> mat2 = torch.randn(3, 3) + >>> torch.addmm(M, mat1, mat2) + tensor([[-4.8716, 1.4671, -1.3746], + [ 0.7573, -3.9555, -2.8681]]) + """ + +@overload +def addmv( + beta: Number | _complex, + self: Tensor, + alpha: Number | _complex, + mat: Tensor, + vec: Tensor, +) -> Tensor: + r""" + addmv(input, mat, vec, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a matrix-vector product of the matrix :attr:`mat` and + the vector :attr:`vec`. + The vector :attr:`input` is added to the final result. + + If :attr:`mat` is a :math:`(n \times m)` tensor, :attr:`vec` is a 1-D tensor of + size `m`, then :attr:`input` must be + :ref:`broadcastable ` with a 1-D tensor of size `n` and + :attr:`out` will be 1-D tensor of size `n`. + + :attr:`alpha` and :attr:`beta` are scaling factors on matrix-vector product between + :attr:`mat` and :attr:`vec` and the added tensor :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{mat} \mathbin{@} \text{vec}) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + Args: + input (Tensor): vector to be added + mat (Tensor): matrix to be matrix multiplied + vec (Tensor): vector to be matrix multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat @ vec` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(2) + >>> mat = torch.randn(2, 3) + >>> vec = torch.randn(3) + >>> torch.addmv(M, mat, vec) + tensor([-0.3768, -5.5565]) + """ + +@overload +def addmv( + beta: Number | _complex, + self: Tensor, + alpha: Number | _complex, + mat: Tensor, + vec: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + addmv(input, mat, vec, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a matrix-vector product of the matrix :attr:`mat` and + the vector :attr:`vec`. + The vector :attr:`input` is added to the final result. + + If :attr:`mat` is a :math:`(n \times m)` tensor, :attr:`vec` is a 1-D tensor of + size `m`, then :attr:`input` must be + :ref:`broadcastable ` with a 1-D tensor of size `n` and + :attr:`out` will be 1-D tensor of size `n`. + + :attr:`alpha` and :attr:`beta` are scaling factors on matrix-vector product between + :attr:`mat` and :attr:`vec` and the added tensor :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{mat} \mathbin{@} \text{vec}) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + Args: + input (Tensor): vector to be added + mat (Tensor): matrix to be matrix multiplied + vec (Tensor): vector to be matrix multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat @ vec` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(2) + >>> mat = torch.randn(2, 3) + >>> vec = torch.randn(3) + >>> torch.addmv(M, mat, vec) + tensor([-0.3768, -5.5565]) + """ + +@overload +def addmv( + input: Tensor, + mat: Tensor, + vec: Tensor, + *, + beta: Number | _complex = 1, + alpha: Number | _complex = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + addmv(input, mat, vec, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a matrix-vector product of the matrix :attr:`mat` and + the vector :attr:`vec`. + The vector :attr:`input` is added to the final result. + + If :attr:`mat` is a :math:`(n \times m)` tensor, :attr:`vec` is a 1-D tensor of + size `m`, then :attr:`input` must be + :ref:`broadcastable ` with a 1-D tensor of size `n` and + :attr:`out` will be 1-D tensor of size `n`. + + :attr:`alpha` and :attr:`beta` are scaling factors on matrix-vector product between + :attr:`mat` and :attr:`vec` and the added tensor :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{mat} \mathbin{@} \text{vec}) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + Args: + input (Tensor): vector to be added + mat (Tensor): matrix to be matrix multiplied + vec (Tensor): vector to be matrix multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat @ vec` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(2) + >>> mat = torch.randn(2, 3) + >>> vec = torch.randn(3) + >>> torch.addmv(M, mat, vec) + tensor([-0.3768, -5.5565]) + """ + +@overload +def addmv( + beta: Number | _complex, + self: Tensor, + mat: Tensor, + vec: Tensor, +) -> Tensor: + r""" + addmv(input, mat, vec, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a matrix-vector product of the matrix :attr:`mat` and + the vector :attr:`vec`. + The vector :attr:`input` is added to the final result. + + If :attr:`mat` is a :math:`(n \times m)` tensor, :attr:`vec` is a 1-D tensor of + size `m`, then :attr:`input` must be + :ref:`broadcastable ` with a 1-D tensor of size `n` and + :attr:`out` will be 1-D tensor of size `n`. + + :attr:`alpha` and :attr:`beta` are scaling factors on matrix-vector product between + :attr:`mat` and :attr:`vec` and the added tensor :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{mat} \mathbin{@} \text{vec}) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + Args: + input (Tensor): vector to be added + mat (Tensor): matrix to be matrix multiplied + vec (Tensor): vector to be matrix multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat @ vec` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(2) + >>> mat = torch.randn(2, 3) + >>> vec = torch.randn(3) + >>> torch.addmv(M, mat, vec) + tensor([-0.3768, -5.5565]) + """ + +@overload +def addmv( + beta: Number | _complex, + self: Tensor, + mat: Tensor, + vec: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + addmv(input, mat, vec, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a matrix-vector product of the matrix :attr:`mat` and + the vector :attr:`vec`. + The vector :attr:`input` is added to the final result. + + If :attr:`mat` is a :math:`(n \times m)` tensor, :attr:`vec` is a 1-D tensor of + size `m`, then :attr:`input` must be + :ref:`broadcastable ` with a 1-D tensor of size `n` and + :attr:`out` will be 1-D tensor of size `n`. + + :attr:`alpha` and :attr:`beta` are scaling factors on matrix-vector product between + :attr:`mat` and :attr:`vec` and the added tensor :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{mat} \mathbin{@} \text{vec}) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + Args: + input (Tensor): vector to be added + mat (Tensor): matrix to be matrix multiplied + vec (Tensor): vector to be matrix multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat @ vec` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(2) + >>> mat = torch.randn(2, 3) + >>> vec = torch.randn(3) + >>> torch.addmv(M, mat, vec) + tensor([-0.3768, -5.5565]) + """ + +@overload +def addmv_( + beta: Number | _complex, + self: Tensor, + alpha: Number | _complex, + mat: Tensor, + vec: Tensor, +) -> Tensor: ... +@overload +def addmv_( + input: Tensor, + mat: Tensor, + vec: Tensor, + *, + beta: Number | _complex = 1, + alpha: Number | _complex = 1, +) -> Tensor: ... +@overload +def addmv_( + beta: Number | _complex, + self: Tensor, + mat: Tensor, + vec: Tensor, +) -> Tensor: ... +@overload +def addr( + beta: Number | _complex, + self: Tensor, + alpha: Number | _complex, + vec1: Tensor, + vec2: Tensor, +) -> Tensor: + r""" + addr(input, vec1, vec2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs the outer-product of vectors :attr:`vec1` and :attr:`vec2` + and adds it to the matrix :attr:`input`. + + Optional values :attr:`beta` and :attr:`alpha` are scaling factors on the + outer product between :attr:`vec1` and :attr:`vec2` and the added matrix + :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{vec1} \otimes \text{vec2}) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + If :attr:`vec1` is a vector of size `n` and :attr:`vec2` is a vector + of size `m`, then :attr:`input` must be + :ref:`broadcastable ` with a matrix of size + :math:`(n \times m)` and :attr:`out` will be a matrix of size + :math:`(n \times m)`. + + Args: + input (Tensor): matrix to be added + vec1 (Tensor): the first vector of the outer product + vec2 (Tensor): the second vector of the outer product + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{vec1} \otimes \text{vec2}` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> vec1 = torch.arange(1., 4.) + >>> vec2 = torch.arange(1., 3.) + >>> M = torch.zeros(3, 2) + >>> torch.addr(M, vec1, vec2) + tensor([[ 1., 2.], + [ 2., 4.], + [ 3., 6.]]) + """ + +@overload +def addr( + beta: Number | _complex, + self: Tensor, + alpha: Number | _complex, + vec1: Tensor, + vec2: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + addr(input, vec1, vec2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs the outer-product of vectors :attr:`vec1` and :attr:`vec2` + and adds it to the matrix :attr:`input`. + + Optional values :attr:`beta` and :attr:`alpha` are scaling factors on the + outer product between :attr:`vec1` and :attr:`vec2` and the added matrix + :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{vec1} \otimes \text{vec2}) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + If :attr:`vec1` is a vector of size `n` and :attr:`vec2` is a vector + of size `m`, then :attr:`input` must be + :ref:`broadcastable ` with a matrix of size + :math:`(n \times m)` and :attr:`out` will be a matrix of size + :math:`(n \times m)`. + + Args: + input (Tensor): matrix to be added + vec1 (Tensor): the first vector of the outer product + vec2 (Tensor): the second vector of the outer product + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{vec1} \otimes \text{vec2}` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> vec1 = torch.arange(1., 4.) + >>> vec2 = torch.arange(1., 3.) + >>> M = torch.zeros(3, 2) + >>> torch.addr(M, vec1, vec2) + tensor([[ 1., 2.], + [ 2., 4.], + [ 3., 6.]]) + """ + +@overload +def addr( + input: Tensor, + vec1: Tensor, + vec2: Tensor, + *, + beta: Number | _complex = 1, + alpha: Number | _complex = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + addr(input, vec1, vec2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs the outer-product of vectors :attr:`vec1` and :attr:`vec2` + and adds it to the matrix :attr:`input`. + + Optional values :attr:`beta` and :attr:`alpha` are scaling factors on the + outer product between :attr:`vec1` and :attr:`vec2` and the added matrix + :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{vec1} \otimes \text{vec2}) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + If :attr:`vec1` is a vector of size `n` and :attr:`vec2` is a vector + of size `m`, then :attr:`input` must be + :ref:`broadcastable ` with a matrix of size + :math:`(n \times m)` and :attr:`out` will be a matrix of size + :math:`(n \times m)`. + + Args: + input (Tensor): matrix to be added + vec1 (Tensor): the first vector of the outer product + vec2 (Tensor): the second vector of the outer product + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{vec1} \otimes \text{vec2}` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> vec1 = torch.arange(1., 4.) + >>> vec2 = torch.arange(1., 3.) + >>> M = torch.zeros(3, 2) + >>> torch.addr(M, vec1, vec2) + tensor([[ 1., 2.], + [ 2., 4.], + [ 3., 6.]]) + """ + +@overload +def addr( + beta: Number | _complex, + self: Tensor, + vec1: Tensor, + vec2: Tensor, +) -> Tensor: + r""" + addr(input, vec1, vec2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs the outer-product of vectors :attr:`vec1` and :attr:`vec2` + and adds it to the matrix :attr:`input`. + + Optional values :attr:`beta` and :attr:`alpha` are scaling factors on the + outer product between :attr:`vec1` and :attr:`vec2` and the added matrix + :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{vec1} \otimes \text{vec2}) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + If :attr:`vec1` is a vector of size `n` and :attr:`vec2` is a vector + of size `m`, then :attr:`input` must be + :ref:`broadcastable ` with a matrix of size + :math:`(n \times m)` and :attr:`out` will be a matrix of size + :math:`(n \times m)`. + + Args: + input (Tensor): matrix to be added + vec1 (Tensor): the first vector of the outer product + vec2 (Tensor): the second vector of the outer product + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{vec1} \otimes \text{vec2}` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> vec1 = torch.arange(1., 4.) + >>> vec2 = torch.arange(1., 3.) + >>> M = torch.zeros(3, 2) + >>> torch.addr(M, vec1, vec2) + tensor([[ 1., 2.], + [ 2., 4.], + [ 3., 6.]]) + """ + +@overload +def addr( + beta: Number | _complex, + self: Tensor, + vec1: Tensor, + vec2: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + addr(input, vec1, vec2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs the outer-product of vectors :attr:`vec1` and :attr:`vec2` + and adds it to the matrix :attr:`input`. + + Optional values :attr:`beta` and :attr:`alpha` are scaling factors on the + outer product between :attr:`vec1` and :attr:`vec2` and the added matrix + :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{vec1} \otimes \text{vec2}) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + If :attr:`vec1` is a vector of size `n` and :attr:`vec2` is a vector + of size `m`, then :attr:`input` must be + :ref:`broadcastable ` with a matrix of size + :math:`(n \times m)` and :attr:`out` will be a matrix of size + :math:`(n \times m)`. + + Args: + input (Tensor): matrix to be added + vec1 (Tensor): the first vector of the outer product + vec2 (Tensor): the second vector of the outer product + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{vec1} \otimes \text{vec2}` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> vec1 = torch.arange(1., 4.) + >>> vec2 = torch.arange(1., 3.) + >>> M = torch.zeros(3, 2) + >>> torch.addr(M, vec1, vec2) + tensor([[ 1., 2.], + [ 2., 4.], + [ 3., 6.]]) + """ + +def adjoint(input: Tensor) -> Tensor: + r""" + adjoint(input: Tensor) -> Tensor + Returns a view of the tensor conjugated and with the last two dimensions transposed. + + ``x.adjoint()`` is equivalent to ``x.transpose(-2, -1).conj()`` for complex tensors and + to ``x.transpose(-2, -1)`` for real tensors. + + Args: + {input} + + Example:: + + >>> x = torch.arange(4, dtype=torch.float) + >>> A = torch.complex(x, x).reshape(2, 2) + >>> A + tensor([[0.+0.j, 1.+1.j], + [2.+2.j, 3.+3.j]]) + >>> A.adjoint() + tensor([[0.-0.j, 2.-2.j], + [1.-1.j, 3.-3.j]]) + >>> (A.adjoint() == A.mH).all() + tensor(True) + """ + +def affine_grid_generator( + theta: Tensor, + size: Sequence[_int | SymInt], + align_corners: _bool, +) -> Tensor: ... +def alias_copy(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + Performs the same operation as :func:`torch.alias`, but all output tensors + are freshly created instead of aliasing the input. + """ + +@overload +def all(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + all(input: Tensor, *, out=None) -> Tensor + + Tests if all elements in :attr:`input` evaluate to `True`. + + .. note:: This function matches the behaviour of NumPy in returning + output of dtype `bool` for all supported dtypes except `uint8`. + For `uint8` the dtype of output is `uint8` itself. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(1, 2).bool() + >>> a + tensor([[False, True]], dtype=torch.bool) + >>> torch.all(a) + tensor(False, dtype=torch.bool) + >>> a = torch.arange(0, 3) + >>> a + tensor([0, 1, 2]) + >>> torch.all(a) + tensor(False) + + .. function:: all(input, dim, keepdim=False, *, out=None) -> Tensor + :noindex: + + For each row of :attr:`input` in the given dimension :attr:`dim`, + returns `True` if all elements in the row evaluate to `True` and `False` otherwise. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(4, 2).bool() + >>> a + tensor([[True, True], + [True, False], + [True, True], + [True, True]], dtype=torch.bool) + >>> torch.all(a, dim=1) + tensor([ True, False, True, True], dtype=torch.bool) + >>> torch.all(a, dim=0) + tensor([ True, False], dtype=torch.bool) + """ + +@overload +def all( + input: Tensor, + dim: _size | None = None, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + all(input: Tensor, *, out=None) -> Tensor + + Tests if all elements in :attr:`input` evaluate to `True`. + + .. note:: This function matches the behaviour of NumPy in returning + output of dtype `bool` for all supported dtypes except `uint8`. + For `uint8` the dtype of output is `uint8` itself. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(1, 2).bool() + >>> a + tensor([[False, True]], dtype=torch.bool) + >>> torch.all(a) + tensor(False, dtype=torch.bool) + >>> a = torch.arange(0, 3) + >>> a + tensor([0, 1, 2]) + >>> torch.all(a) + tensor(False) + + .. function:: all(input, dim, keepdim=False, *, out=None) -> Tensor + :noindex: + + For each row of :attr:`input` in the given dimension :attr:`dim`, + returns `True` if all elements in the row evaluate to `True` and `False` otherwise. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(4, 2).bool() + >>> a + tensor([[True, True], + [True, False], + [True, True], + [True, True]], dtype=torch.bool) + >>> torch.all(a, dim=1) + tensor([ True, False, True, True], dtype=torch.bool) + >>> torch.all(a, dim=0) + tensor([ True, False], dtype=torch.bool) + """ + +@overload +def all( + input: Tensor, + dim: _int, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + all(input: Tensor, *, out=None) -> Tensor + + Tests if all elements in :attr:`input` evaluate to `True`. + + .. note:: This function matches the behaviour of NumPy in returning + output of dtype `bool` for all supported dtypes except `uint8`. + For `uint8` the dtype of output is `uint8` itself. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(1, 2).bool() + >>> a + tensor([[False, True]], dtype=torch.bool) + >>> torch.all(a) + tensor(False, dtype=torch.bool) + >>> a = torch.arange(0, 3) + >>> a + tensor([0, 1, 2]) + >>> torch.all(a) + tensor(False) + + .. function:: all(input, dim, keepdim=False, *, out=None) -> Tensor + :noindex: + + For each row of :attr:`input` in the given dimension :attr:`dim`, + returns `True` if all elements in the row evaluate to `True` and `False` otherwise. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(4, 2).bool() + >>> a + tensor([[True, True], + [True, False], + [True, True], + [True, True]], dtype=torch.bool) + >>> torch.all(a, dim=1) + tensor([ True, False, True, True], dtype=torch.bool) + >>> torch.all(a, dim=0) + tensor([ True, False], dtype=torch.bool) + """ + +@overload +def all( + input: Tensor, + dim: str | EllipsisType | None, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + all(input: Tensor, *, out=None) -> Tensor + + Tests if all elements in :attr:`input` evaluate to `True`. + + .. note:: This function matches the behaviour of NumPy in returning + output of dtype `bool` for all supported dtypes except `uint8`. + For `uint8` the dtype of output is `uint8` itself. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(1, 2).bool() + >>> a + tensor([[False, True]], dtype=torch.bool) + >>> torch.all(a) + tensor(False, dtype=torch.bool) + >>> a = torch.arange(0, 3) + >>> a + tensor([0, 1, 2]) + >>> torch.all(a) + tensor(False) + + .. function:: all(input, dim, keepdim=False, *, out=None) -> Tensor + :noindex: + + For each row of :attr:`input` in the given dimension :attr:`dim`, + returns `True` if all elements in the row evaluate to `True` and `False` otherwise. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(4, 2).bool() + >>> a + tensor([[True, True], + [True, False], + [True, True], + [True, True]], dtype=torch.bool) + >>> torch.all(a, dim=1) + tensor([ True, False, True, True], dtype=torch.bool) + >>> torch.all(a, dim=0) + tensor([ True, False], dtype=torch.bool) + """ + +def allclose( + input: Tensor, + other: Tensor, + rtol: _float = 1e-05, + atol: _float = 1e-08, + equal_nan: _bool = False, +) -> _bool: + r""" + allclose(input: Tensor, other: Tensor, rtol: float = 1e-05, atol: float = 1e-08, equal_nan: bool = False) -> bool + + This function checks if :attr:`input` and :attr:`other` satisfy the condition: + + .. math:: + \lvert \text{input}_i - \text{other}_i \rvert \leq \texttt{atol} + \texttt{rtol} \times \lvert \text{other}_i \rvert + + elementwise, for all elements of :attr:`input` and :attr:`other`. The behaviour of this function is analogous to + `numpy.allclose `_ + + Args: + input (Tensor): first tensor to compare + other (Tensor): second tensor to compare + atol (float, optional): absolute tolerance. Default: 1e-08 + rtol (float, optional): relative tolerance. Default: 1e-05 + equal_nan (bool, optional): if ``True``, then two ``NaN`` s will be considered equal. Default: ``False`` + + Example:: + + >>> torch.allclose(torch.tensor([10000., 1e-07]), torch.tensor([10000.1, 1e-08])) + False + >>> torch.allclose(torch.tensor([10000., 1e-08]), torch.tensor([10000.1, 1e-09])) + True + >>> torch.allclose(torch.tensor([1.0, float('nan')]), torch.tensor([1.0, float('nan')])) + False + >>> torch.allclose(torch.tensor([1.0, float('nan')]), torch.tensor([1.0, float('nan')]), equal_nan=True) + True + """ + +def alpha_dropout(input: Tensor, p: _float, train: _bool) -> Tensor: ... +def alpha_dropout_(input: Tensor, p: _float, train: _bool) -> Tensor: ... +def amax( + input: Tensor, + dim: _int | _size = (), + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + amax(input, dim, keepdim=False, *, out=None) -> Tensor + + Returns the maximum value of each slice of the :attr:`input` tensor in the given + dimension(s) :attr:`dim`. + + .. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.8177, 1.4878, -0.2491, 0.9130], + [-0.7158, 1.1775, 2.0992, 0.4817], + [-0.0053, 0.0164, -1.3738, -0.0507], + [ 1.9700, 1.1106, -1.0318, -1.0816]]) + >>> torch.amax(a, 1) + tensor([1.4878, 2.0992, 0.0164, 1.9700]) + """ + +def amin( + input: Tensor, + dim: _int | _size = (), + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + amin(input, dim, keepdim=False, *, out=None) -> Tensor + + Returns the minimum value of each slice of the :attr:`input` tensor in the given + dimension(s) :attr:`dim`. + + .. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.6451, -0.4866, 0.2987, -1.3312], + [-0.5744, 1.2980, 1.8397, -0.2713], + [ 0.9128, 0.9214, -1.7268, -0.2995], + [ 0.9023, 0.4853, 0.9075, -1.6165]]) + >>> torch.amin(a, 1) + tensor([-1.3312, -0.5744, -1.7268, -1.6165]) + """ + +def aminmax( + input: Tensor, + *, + dim: _int | None = None, + keepdim: _bool = False, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.aminmax: + r""" + aminmax(input, *, dim=None, keepdim=False, out=None) -> (Tensor min, Tensor max) + + Computes the minimum and maximum values of the :attr:`input` tensor. + + Args: + input (Tensor): + The input tensor + + Keyword Args: + dim (Optional[int]): + The dimension along which to compute the values. If `None`, + computes the values over the entire :attr:`input` tensor. + Default is `None`. + keepdim (bool): + If `True`, the reduced dimensions will be kept in the output + tensor as dimensions with size 1 for broadcasting, otherwise + they will be removed, as if calling (:func:`torch.squeeze`). + Default is `False`. + out (Optional[Tuple[Tensor, Tensor]]): + Optional tensors on which to write the result. Must have the same + shape and dtype as the expected output. + Default is `None`. + + Returns: + A named tuple `(min, max)` containing the minimum and maximum values. + + Raises: + RuntimeError + If any of the dimensions to compute the values over has size 0. + + .. note:: + NaN values are propagated to the output if at least one value is NaN. + + .. seealso:: + :func:`torch.amin` computes just the minimum value + :func:`torch.amax` computes just the maximum value + + Example:: + + >>> torch.aminmax(torch.tensor([1, -3, 5])) + torch.return_types.aminmax( + min=tensor(-3), + max=tensor(5)) + + >>> # aminmax propagates NaNs + >>> torch.aminmax(torch.tensor([1, -3, 5, torch.nan])) + torch.return_types.aminmax( + min=tensor(nan), + max=tensor(nan)) + + >>> t = torch.arange(10).view(2, 5) + >>> t + tensor([[0, 1, 2, 3, 4], + [5, 6, 7, 8, 9]]) + >>> t.aminmax(dim=0, keepdim=True) + torch.return_types.aminmax( + min=tensor([[0, 1, 2, 3, 4]]), + max=tensor([[5, 6, 7, 8, 9]])) + """ + +def angle(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + angle(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Computes the element-wise angle (in radians) of the given :attr:`input` tensor. + + .. math:: + \text{out}_{i} = angle(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + .. note:: Starting in PyTorch 1.8, angle returns pi for negative real numbers, + zero for non-negative real numbers, and propagates NaNs. Previously + the function would return zero for all real numbers and not propagate + floating-point NaNs. + + Example:: + + >>> torch.angle(torch.tensor([-1 + 1j, -2 + 2j, 3 - 3j]))*180/3.14159 + tensor([ 135., 135, -45]) + """ + +@overload +def any(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + any(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Tests if any element in :attr:`input` evaluates to `True`. + + .. note:: This function matches the behaviour of NumPy in returning + output of dtype `bool` for all supported dtypes except `uint8`. + For `uint8` the dtype of output is `uint8` itself. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(1, 2).bool() + >>> a + tensor([[False, True]], dtype=torch.bool) + >>> torch.any(a) + tensor(True, dtype=torch.bool) + >>> a = torch.arange(0, 3) + >>> a + tensor([0, 1, 2]) + >>> torch.any(a) + tensor(True) + + .. function:: any(input, dim, keepdim=False, *, out=None) -> Tensor + :noindex: + + For each row of :attr:`input` in the given dimension :attr:`dim`, + returns `True` if any element in the row evaluate to `True` and `False` otherwise. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4, 2) < 0 + >>> a + tensor([[ True, True], + [False, True], + [ True, True], + [False, False]]) + >>> torch.any(a, 1) + tensor([ True, True, True, False]) + >>> torch.any(a, 0) + tensor([True, True]) + """ + +@overload +def any( + input: Tensor, + dim: _size | None = None, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + any(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Tests if any element in :attr:`input` evaluates to `True`. + + .. note:: This function matches the behaviour of NumPy in returning + output of dtype `bool` for all supported dtypes except `uint8`. + For `uint8` the dtype of output is `uint8` itself. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(1, 2).bool() + >>> a + tensor([[False, True]], dtype=torch.bool) + >>> torch.any(a) + tensor(True, dtype=torch.bool) + >>> a = torch.arange(0, 3) + >>> a + tensor([0, 1, 2]) + >>> torch.any(a) + tensor(True) + + .. function:: any(input, dim, keepdim=False, *, out=None) -> Tensor + :noindex: + + For each row of :attr:`input` in the given dimension :attr:`dim`, + returns `True` if any element in the row evaluate to `True` and `False` otherwise. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4, 2) < 0 + >>> a + tensor([[ True, True], + [False, True], + [ True, True], + [False, False]]) + >>> torch.any(a, 1) + tensor([ True, True, True, False]) + >>> torch.any(a, 0) + tensor([True, True]) + """ + +@overload +def any( + input: Tensor, + dim: _int, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + any(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Tests if any element in :attr:`input` evaluates to `True`. + + .. note:: This function matches the behaviour of NumPy in returning + output of dtype `bool` for all supported dtypes except `uint8`. + For `uint8` the dtype of output is `uint8` itself. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(1, 2).bool() + >>> a + tensor([[False, True]], dtype=torch.bool) + >>> torch.any(a) + tensor(True, dtype=torch.bool) + >>> a = torch.arange(0, 3) + >>> a + tensor([0, 1, 2]) + >>> torch.any(a) + tensor(True) + + .. function:: any(input, dim, keepdim=False, *, out=None) -> Tensor + :noindex: + + For each row of :attr:`input` in the given dimension :attr:`dim`, + returns `True` if any element in the row evaluate to `True` and `False` otherwise. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4, 2) < 0 + >>> a + tensor([[ True, True], + [False, True], + [ True, True], + [False, False]]) + >>> torch.any(a, 1) + tensor([ True, True, True, False]) + >>> torch.any(a, 0) + tensor([True, True]) + """ + +@overload +def any( + input: Tensor, + dim: str | EllipsisType | None, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + any(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Tests if any element in :attr:`input` evaluates to `True`. + + .. note:: This function matches the behaviour of NumPy in returning + output of dtype `bool` for all supported dtypes except `uint8`. + For `uint8` the dtype of output is `uint8` itself. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(1, 2).bool() + >>> a + tensor([[False, True]], dtype=torch.bool) + >>> torch.any(a) + tensor(True, dtype=torch.bool) + >>> a = torch.arange(0, 3) + >>> a + tensor([0, 1, 2]) + >>> torch.any(a) + tensor(True) + + .. function:: any(input, dim, keepdim=False, *, out=None) -> Tensor + :noindex: + + For each row of :attr:`input` in the given dimension :attr:`dim`, + returns `True` if any element in the row evaluate to `True` and `False` otherwise. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4, 2) < 0 + >>> a + tensor([[ True, True], + [False, True], + [ True, True], + [False, False]]) + >>> torch.any(a, 1) + tensor([ True, True, True, False]) + >>> torch.any(a, 0) + tensor([True, True]) + """ + +@overload +def arange( + start: Number, + end: Number, + step: Number, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + pin_memory: _bool = False, +) -> Tensor: + r""" + arange(start=0, end, step=1, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a 1-D tensor of size :math:`\left\lceil \frac{\text{end} - \text{start}}{\text{step}} \right\rceil` + with values from the interval ``[start, end)`` taken with common difference + :attr:`step` beginning from `start`. + + Note: When using floating-point dtypes (especially reduced precision types like ``bfloat16``), + the results may be affected by floating-point rounding behavior. Some values in the sequence + might not be exactly representable in certain floating-point formats, which can lead to + repeated values or unexpected rounding. For precise sequences, it is recommended to use + integer dtypes instead of floating-point dtypes. + + Note that non-integer :attr:`step` is subject to floating point rounding errors when + comparing against :attr:`end`; to avoid inconsistency, we advise subtracting a small epsilon from :attr:`end` + in such cases. + + .. math:: + \text{out}_{{i+1}} = \text{out}_{i} + \text{step} + + Args: + start (Number, optional): the starting value for the set of points. Default: ``0``. + end (Number): the ending value for the set of points + step (Number, optional): the gap between each pair of adjacent points. Default: ``1``. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). If `dtype` is not given, infer the data type from the other input + arguments. If any of `start`, `end`, or `stop` are floating-point, the + `dtype` is inferred to be the default dtype, see + :meth:`~torch.get_default_dtype`. Otherwise, the `dtype` is inferred to + be `torch.int64`. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.arange(5) + tensor([ 0, 1, 2, 3, 4]) + >>> torch.arange(1, 4) + tensor([ 1, 2, 3]) + >>> torch.arange(1, 2.5, 0.5) + tensor([ 1.0000, 1.5000, 2.0000]) + """ + +@overload +def arange( + start: Number, + end: Number, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + pin_memory: _bool = False, +) -> Tensor: + r""" + arange(start=0, end, step=1, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a 1-D tensor of size :math:`\left\lceil \frac{\text{end} - \text{start}}{\text{step}} \right\rceil` + with values from the interval ``[start, end)`` taken with common difference + :attr:`step` beginning from `start`. + + Note: When using floating-point dtypes (especially reduced precision types like ``bfloat16``), + the results may be affected by floating-point rounding behavior. Some values in the sequence + might not be exactly representable in certain floating-point formats, which can lead to + repeated values or unexpected rounding. For precise sequences, it is recommended to use + integer dtypes instead of floating-point dtypes. + + Note that non-integer :attr:`step` is subject to floating point rounding errors when + comparing against :attr:`end`; to avoid inconsistency, we advise subtracting a small epsilon from :attr:`end` + in such cases. + + .. math:: + \text{out}_{{i+1}} = \text{out}_{i} + \text{step} + + Args: + start (Number, optional): the starting value for the set of points. Default: ``0``. + end (Number): the ending value for the set of points + step (Number, optional): the gap between each pair of adjacent points. Default: ``1``. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). If `dtype` is not given, infer the data type from the other input + arguments. If any of `start`, `end`, or `stop` are floating-point, the + `dtype` is inferred to be the default dtype, see + :meth:`~torch.get_default_dtype`. Otherwise, the `dtype` is inferred to + be `torch.int64`. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.arange(5) + tensor([ 0, 1, 2, 3, 4]) + >>> torch.arange(1, 4) + tensor([ 1, 2, 3]) + >>> torch.arange(1, 2.5, 0.5) + tensor([ 1.0000, 1.5000, 2.0000]) + """ + +@overload +def arange( + end: Number, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + pin_memory: _bool = False, +) -> Tensor: + r""" + arange(start=0, end, step=1, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a 1-D tensor of size :math:`\left\lceil \frac{\text{end} - \text{start}}{\text{step}} \right\rceil` + with values from the interval ``[start, end)`` taken with common difference + :attr:`step` beginning from `start`. + + Note: When using floating-point dtypes (especially reduced precision types like ``bfloat16``), + the results may be affected by floating-point rounding behavior. Some values in the sequence + might not be exactly representable in certain floating-point formats, which can lead to + repeated values or unexpected rounding. For precise sequences, it is recommended to use + integer dtypes instead of floating-point dtypes. + + Note that non-integer :attr:`step` is subject to floating point rounding errors when + comparing against :attr:`end`; to avoid inconsistency, we advise subtracting a small epsilon from :attr:`end` + in such cases. + + .. math:: + \text{out}_{{i+1}} = \text{out}_{i} + \text{step} + + Args: + start (Number, optional): the starting value for the set of points. Default: ``0``. + end (Number): the ending value for the set of points + step (Number, optional): the gap between each pair of adjacent points. Default: ``1``. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). If `dtype` is not given, infer the data type from the other input + arguments. If any of `start`, `end`, or `stop` are floating-point, the + `dtype` is inferred to be the default dtype, see + :meth:`~torch.get_default_dtype`. Otherwise, the `dtype` is inferred to + be `torch.int64`. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.arange(5) + tensor([ 0, 1, 2, 3, 4]) + >>> torch.arange(1, 4) + tensor([ 1, 2, 3]) + >>> torch.arange(1, 2.5, 0.5) + tensor([ 1.0000, 1.5000, 2.0000]) + """ + +@overload +def arange( + end: Number | _complex, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + arange(start=0, end, step=1, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a 1-D tensor of size :math:`\left\lceil \frac{\text{end} - \text{start}}{\text{step}} \right\rceil` + with values from the interval ``[start, end)`` taken with common difference + :attr:`step` beginning from `start`. + + Note: When using floating-point dtypes (especially reduced precision types like ``bfloat16``), + the results may be affected by floating-point rounding behavior. Some values in the sequence + might not be exactly representable in certain floating-point formats, which can lead to + repeated values or unexpected rounding. For precise sequences, it is recommended to use + integer dtypes instead of floating-point dtypes. + + Note that non-integer :attr:`step` is subject to floating point rounding errors when + comparing against :attr:`end`; to avoid inconsistency, we advise subtracting a small epsilon from :attr:`end` + in such cases. + + .. math:: + \text{out}_{{i+1}} = \text{out}_{i} + \text{step} + + Args: + start (Number, optional): the starting value for the set of points. Default: ``0``. + end (Number): the ending value for the set of points + step (Number, optional): the gap between each pair of adjacent points. Default: ``1``. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). If `dtype` is not given, infer the data type from the other input + arguments. If any of `start`, `end`, or `stop` are floating-point, the + `dtype` is inferred to be the default dtype, see + :meth:`~torch.get_default_dtype`. Otherwise, the `dtype` is inferred to + be `torch.int64`. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.arange(5) + tensor([ 0, 1, 2, 3, 4]) + >>> torch.arange(1, 4) + tensor([ 1, 2, 3]) + >>> torch.arange(1, 2.5, 0.5) + tensor([ 1.0000, 1.5000, 2.0000]) + """ + +@overload +def arange( + start: Number | _complex, + end: Number | _complex, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + arange(start=0, end, step=1, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a 1-D tensor of size :math:`\left\lceil \frac{\text{end} - \text{start}}{\text{step}} \right\rceil` + with values from the interval ``[start, end)`` taken with common difference + :attr:`step` beginning from `start`. + + Note: When using floating-point dtypes (especially reduced precision types like ``bfloat16``), + the results may be affected by floating-point rounding behavior. Some values in the sequence + might not be exactly representable in certain floating-point formats, which can lead to + repeated values or unexpected rounding. For precise sequences, it is recommended to use + integer dtypes instead of floating-point dtypes. + + Note that non-integer :attr:`step` is subject to floating point rounding errors when + comparing against :attr:`end`; to avoid inconsistency, we advise subtracting a small epsilon from :attr:`end` + in such cases. + + .. math:: + \text{out}_{{i+1}} = \text{out}_{i} + \text{step} + + Args: + start (Number, optional): the starting value for the set of points. Default: ``0``. + end (Number): the ending value for the set of points + step (Number, optional): the gap between each pair of adjacent points. Default: ``1``. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). If `dtype` is not given, infer the data type from the other input + arguments. If any of `start`, `end`, or `stop` are floating-point, the + `dtype` is inferred to be the default dtype, see + :meth:`~torch.get_default_dtype`. Otherwise, the `dtype` is inferred to + be `torch.int64`. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.arange(5) + tensor([ 0, 1, 2, 3, 4]) + >>> torch.arange(1, 4) + tensor([ 1, 2, 3]) + >>> torch.arange(1, 2.5, 0.5) + tensor([ 1.0000, 1.5000, 2.0000]) + """ + +@overload +def arange( + start: Number | _complex, + end: Number | _complex, + step: Number | _complex = 1, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + arange(start=0, end, step=1, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a 1-D tensor of size :math:`\left\lceil \frac{\text{end} - \text{start}}{\text{step}} \right\rceil` + with values from the interval ``[start, end)`` taken with common difference + :attr:`step` beginning from `start`. + + Note: When using floating-point dtypes (especially reduced precision types like ``bfloat16``), + the results may be affected by floating-point rounding behavior. Some values in the sequence + might not be exactly representable in certain floating-point formats, which can lead to + repeated values or unexpected rounding. For precise sequences, it is recommended to use + integer dtypes instead of floating-point dtypes. + + Note that non-integer :attr:`step` is subject to floating point rounding errors when + comparing against :attr:`end`; to avoid inconsistency, we advise subtracting a small epsilon from :attr:`end` + in such cases. + + .. math:: + \text{out}_{{i+1}} = \text{out}_{i} + \text{step} + + Args: + start (Number, optional): the starting value for the set of points. Default: ``0``. + end (Number): the ending value for the set of points + step (Number, optional): the gap between each pair of adjacent points. Default: ``1``. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). If `dtype` is not given, infer the data type from the other input + arguments. If any of `start`, `end`, or `stop` are floating-point, the + `dtype` is inferred to be the default dtype, see + :meth:`~torch.get_default_dtype`. Otherwise, the `dtype` is inferred to + be `torch.int64`. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.arange(5) + tensor([ 0, 1, 2, 3, 4]) + >>> torch.arange(1, 4) + tensor([ 1, 2, 3]) + >>> torch.arange(1, 2.5, 0.5) + tensor([ 1.0000, 1.5000, 2.0000]) + """ + +def arccos(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + arccos(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Alias for :func:`torch.acos`. + """ + +def arccos_(input: Tensor) -> Tensor: ... +def arccosh(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + arccosh(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Alias for :func:`torch.acosh`. + """ + +def arccosh_(input: Tensor) -> Tensor: ... +def arcsin(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + arcsin(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Alias for :func:`torch.asin`. + """ + +def arcsin_(input: Tensor) -> Tensor: ... +def arcsinh(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + arcsinh(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Alias for :func:`torch.asinh`. + """ + +def arcsinh_(input: Tensor) -> Tensor: ... +def arctan(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + arctan(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Alias for :func:`torch.atan`. + """ + +def arctan2( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + arctan2(input: Tensor, other: Tensor, *, out: Optional[Tensor]) -> Tensor + Alias for :func:`torch.atan2`. + """ + +def arctan_(input: Tensor) -> Tensor: ... +def arctanh(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + arctanh(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Alias for :func:`torch.atanh`. + """ + +def arctanh_(input: Tensor) -> Tensor: ... +def argmax( + input: Tensor, + dim: _int | None = None, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + argmax(input) -> LongTensor + + Returns the indices of the maximum value of all elements in the :attr:`input` tensor. + + This is the second value returned by :meth:`torch.max`. See its + documentation for the exact semantics of this method. + + .. note:: If there are multiple maximal values then the indices of the first maximal value are returned. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 1.3398, 0.2663, -0.2686, 0.2450], + [-0.7401, -0.8805, -0.3402, -1.1936], + [ 0.4907, -1.3948, -1.0691, -0.3132], + [-1.6092, 0.5419, -0.2993, 0.3195]]) + >>> torch.argmax(a) + tensor(0) + + .. function:: argmax(input, dim, keepdim=False) -> LongTensor + :noindex: + + Returns the indices of the maximum values of a tensor across a dimension. + + This is the second value returned by :meth:`torch.max`. See its + documentation for the exact semantics of this method. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. + If ``None``, the argmax of the flattened input is returned. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 1.3398, 0.2663, -0.2686, 0.2450], + [-0.7401, -0.8805, -0.3402, -1.1936], + [ 0.4907, -1.3948, -1.0691, -0.3132], + [-1.6092, 0.5419, -0.2993, 0.3195]]) + >>> torch.argmax(a, dim=1) + tensor([ 0, 2, 0, 1]) + """ + +def argmin( + input: Tensor, + dim: _int | None = None, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + argmin(input, dim=None, keepdim=False) -> LongTensor + + Returns the indices of the minimum value(s) of the flattened tensor or along a dimension + + This is the second value returned by :meth:`torch.min`. See its + documentation for the exact semantics of this method. + + .. note:: If there are multiple minimal values then the indices of the first minimal value are returned. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. + If ``None``, the argmin of the flattened input is returned. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.1139, 0.2254, -0.1381, 0.3687], + [ 1.0100, -1.1975, -0.0102, -0.4732], + [-0.9240, 0.1207, -0.7506, -1.0213], + [ 1.7809, -1.2960, 0.9384, 0.1438]]) + >>> torch.argmin(a) + tensor(13) + >>> torch.argmin(a, dim=1) + tensor([ 2, 1, 3, 1]) + >>> torch.argmin(a, dim=1, keepdim=True) + tensor([[2], + [1], + [3], + [1]]) + """ + +@overload +def argsort( + input: Tensor, + *, + stable: _bool, + dim: _int = -1, + descending: _bool = False, + out: Tensor | None = None, +) -> Tensor: + r""" + argsort(input, dim=-1, descending=False, *, stable=False) -> Tensor + + Returns the indices that sort a tensor along a given dimension in ascending + order by value. + + This is the second value returned by :meth:`torch.sort`. See its documentation + for the exact semantics of this method. + + If :attr:`stable` is ``True`` then the sorting routine becomes stable, preserving + the order of equivalent elements. If ``False``, the relative order of values + which compare equal is not guaranteed. ``True`` is slower. + + Args: + input (Tensor): the input tensor. + dim (int, optional): the dimension to sort along + descending (bool, optional): controls the sorting order (ascending or descending) + + Keyword args: + stable (bool, optional): controls the relative order of equivalent elements + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.0785, 1.5267, -0.8521, 0.4065], + [ 0.1598, 0.0788, -0.0745, -1.2700], + [ 1.2208, 1.0722, -0.7064, 1.2564], + [ 0.0669, -0.2318, -0.8229, -0.9280]]) + + + >>> torch.argsort(a, dim=1) + tensor([[2, 0, 3, 1], + [3, 2, 1, 0], + [2, 1, 0, 3], + [3, 2, 1, 0]]) + """ + +@overload +def argsort( + input: Tensor, + dim: _int = -1, + descending: _bool = False, +) -> Tensor: + r""" + argsort(input, dim=-1, descending=False, *, stable=False) -> Tensor + + Returns the indices that sort a tensor along a given dimension in ascending + order by value. + + This is the second value returned by :meth:`torch.sort`. See its documentation + for the exact semantics of this method. + + If :attr:`stable` is ``True`` then the sorting routine becomes stable, preserving + the order of equivalent elements. If ``False``, the relative order of values + which compare equal is not guaranteed. ``True`` is slower. + + Args: + input (Tensor): the input tensor. + dim (int, optional): the dimension to sort along + descending (bool, optional): controls the sorting order (ascending or descending) + + Keyword args: + stable (bool, optional): controls the relative order of equivalent elements + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.0785, 1.5267, -0.8521, 0.4065], + [ 0.1598, 0.0788, -0.0745, -1.2700], + [ 1.2208, 1.0722, -0.7064, 1.2564], + [ 0.0669, -0.2318, -0.8229, -0.9280]]) + + + >>> torch.argsort(a, dim=1) + tensor([[2, 0, 3, 1], + [3, 2, 1, 0], + [2, 1, 0, 3], + [3, 2, 1, 0]]) + """ + +@overload +def argsort( + input: Tensor, + dim: str | EllipsisType | None, + descending: _bool = False, +) -> Tensor: + r""" + argsort(input, dim=-1, descending=False, *, stable=False) -> Tensor + + Returns the indices that sort a tensor along a given dimension in ascending + order by value. + + This is the second value returned by :meth:`torch.sort`. See its documentation + for the exact semantics of this method. + + If :attr:`stable` is ``True`` then the sorting routine becomes stable, preserving + the order of equivalent elements. If ``False``, the relative order of values + which compare equal is not guaranteed. ``True`` is slower. + + Args: + input (Tensor): the input tensor. + dim (int, optional): the dimension to sort along + descending (bool, optional): controls the sorting order (ascending or descending) + + Keyword args: + stable (bool, optional): controls the relative order of equivalent elements + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.0785, 1.5267, -0.8521, 0.4065], + [ 0.1598, 0.0788, -0.0745, -1.2700], + [ 1.2208, 1.0722, -0.7064, 1.2564], + [ 0.0669, -0.2318, -0.8229, -0.9280]]) + + + >>> torch.argsort(a, dim=1) + tensor([[2, 0, 3, 1], + [3, 2, 1, 0], + [2, 1, 0, 3], + [3, 2, 1, 0]]) + """ + +def argwhere(input: Tensor) -> Tensor: + r""" + argwhere(input) -> Tensor + + Returns a tensor containing the indices of all non-zero elements of + :attr:`input`. Each row in the result contains the indices of a non-zero + element in :attr:`input`. The result is sorted lexicographically, with + the last index changing the fastest (C-style). + + If :attr:`input` has :math:`n` dimensions, then the resulting indices tensor + :attr:`out` is of size :math:`(z \times n)`, where :math:`z` is the total number of + non-zero elements in the :attr:`input` tensor. + + .. note:: + This function is similar to NumPy's `argwhere`. + + When :attr:`input` is on CUDA, this function causes host-device synchronization. + + Args: + {input} + + Example:: + + >>> t = torch.tensor([1, 0, 1]) + >>> torch.argwhere(t) + tensor([[0], + [2]]) + >>> t = torch.tensor([[1, 0, 1], [0, 1, 1]]) + >>> torch.argwhere(t) + tensor([[0, 0], + [0, 2], + [1, 1], + [1, 2]]) + """ + +def as_strided( + input: Tensor, + size: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + storage_offset: _int | SymInt | None = None, +) -> Tensor: + r""" + as_strided(input, size, stride, storage_offset=None) -> Tensor + + Create a view of an existing `torch.Tensor` :attr:`input` with specified + :attr:`size`, :attr:`stride` and :attr:`storage_offset`. + + .. warning:: + Prefer using other view functions, like :meth:`torch.Tensor.view` or + :meth:`torch.Tensor.expand`, to setting a view's strides manually with + `as_strided`, as this function will throw an error on non-standard Pytorch + backends (that do not have a concept of stride) and the result will depend + on the current layout in memory. The constructed view must only refer to + elements within the Tensor's storage or a runtime error will be thrown. + If the generated view is "overlapped" (with multiple indices referring to + the same element in memory), the behavior of inplace operations on this view + is undefined (and might not throw runtime errors). + + Args: + input (Tensor): the input tensor. + size (tuple or ints): the shape of the output tensor + stride (tuple or ints): the stride of the output tensor + storage_offset (int, optional): the offset in the underlying storage of the output tensor. + If ``None``, the storage_offset of the output tensor will match the input tensor. + + Example:: + + >>> x = torch.randn(3, 3) + >>> x + tensor([[ 0.9039, 0.6291, 1.0795], + [ 0.1586, 2.1939, -0.4900], + [-0.1909, -0.7503, 1.9355]]) + >>> t = torch.as_strided(x, (2, 2), (1, 2)) + >>> t + tensor([[0.9039, 1.0795], + [0.6291, 0.1586]]) + >>> t = torch.as_strided(x, (2, 2), (1, 2), 1) + tensor([[0.6291, 0.1586], + [1.0795, 2.1939]]) + """ + +def as_strided_( + input: Tensor, + size: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + storage_offset: _int | SymInt | None = None, +) -> Tensor: ... +def as_strided_copy( + input: Tensor, + size: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + storage_offset: _int | SymInt | None = None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.as_strided`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def as_strided_scatter( + input: Tensor, + src: Tensor, + size: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + storage_offset: _int | SymInt | None = None, +) -> Tensor: + r""" + as_strided_scatter(input, src, size, stride, storage_offset=None) -> Tensor + + Embeds the values of the :attr:`src` tensor into :attr:`input` along + the elements corresponding to the result of calling + input.as_strided(size, stride, storage_offset). + + This function returns a tensor with fresh storage; it does not + return a view. + + Args: + input (Tensor): the input tensor. + size (tuple or ints): the shape of the output tensor + stride (tuple or ints): the stride of the output tensor + storage_offset (int, optional): the offset in the underlying storage of the output tensor + + .. note:: + + :attr:`src` must be of the proper size in order to be embedded + into :attr:`input`. Specifically, it should have the same shape as + `torch.as_strided(input, size, stride, storage_offset)` + + Example:: + + >>> a = torch.arange(4).reshape(2, 2) + 1 + >>> a + tensor([[1, 2], + [3, 4]]) + >>> b = torch.zeros(3, 3) + >>> b + tensor([[0., 0., 0.], + [0., 0., 0.], + [0., 0., 0.]]) + >>> torch.as_strided_scatter(b, a, (2, 2), (1, 2)) + tensor([[1., 3., 2.], + [4., 0., 0.], + [0., 0., 0.]]) + """ + +def as_tensor( + data: Any, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, +) -> Tensor: + r""" + as_tensor(data: Any, dtype: Optional[dtype] = None, device: Optional[DeviceLikeType]) -> Tensor + + Converts :attr:`data` into a tensor, sharing data and preserving autograd + history if possible. + + If :attr:`data` is already a tensor with the requested dtype and device + then :attr:`data` itself is returned, but if :attr:`data` is a + tensor with a different dtype or device then it's copied as if using + `data.to(dtype=dtype, device=device)`. + + If :attr:`data` is a NumPy array (an ndarray) with the same dtype and device then a + tensor is constructed using :func:`torch.from_numpy`. + + If :attr:`data` is a CuPy array, the returned tensor will be located on the same device as the CuPy array unless + specifically overwritten by :attr:`device` or a default device. The device of the CuPy array is inferred from the + pointer of the array using `cudaPointerGetAttributes` unless :attr:`device` is provided with an explicit device index. + + .. seealso:: + + :func:`torch.tensor` never shares its data and creates a new "leaf tensor" (see :doc:`/notes/autograd`). + + + Args: + data (array_like): Initial data for the tensor. Can be a list, tuple, + NumPy ``ndarray``, scalar, and other types. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, infers data type from :attr:`data`. + device (:class:`torch.device`, optional): the device of the constructed tensor. If None and data is a tensor + then the device of data is used. If None and data is not a tensor then + the result tensor is constructed on the current device. + + + Example:: + + >>> a = numpy.array([1, 2, 3]) + >>> t = torch.as_tensor(a) + >>> t + tensor([ 1, 2, 3]) + >>> t[0] = -1 + >>> a + array([-1, 2, 3]) + + >>> a = numpy.array([1, 2, 3]) + >>> t = torch.as_tensor(a, device=torch.device('cuda')) + >>> t + tensor([ 1, 2, 3]) + >>> t[0] = -1 + >>> a + array([1, 2, 3]) + """ + +def asarray( + obj: Any, + *, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + copy: _bool | None = None, + requires_grad: _bool = False, +) -> Tensor: + r""" + asarray(obj: Any, *, dtype: Optional[dtype], device: Optional[DeviceLikeType], copy: Optional[bool] = None, requires_grad: bool = False) -> Tensor # noqa: B950 + + Converts :attr:`obj` to a tensor. + + :attr:`obj` can be one of: + + 1. a tensor + 2. a NumPy array or a NumPy scalar + 3. a DLPack capsule + 4. an object that implements Python's buffer protocol + 5. a scalar + 6. a sequence of scalars + + When :attr:`obj` is a tensor, NumPy array, or DLPack capsule the returned tensor will, + by default, not require a gradient, have the same datatype as :attr:`obj`, be on the + same device, and share memory with it. These properties can be controlled with the + :attr:`dtype`, :attr:`device`, :attr:`copy`, and :attr:`requires_grad` keyword arguments. + If the returned tensor is of a different datatype, on a different device, or a copy is + requested then it will not share its memory with :attr:`obj`. If :attr:`requires_grad` + is ``True`` then the returned tensor will require a gradient, and if :attr:`obj` is + also a tensor with an autograd history then the returned tensor will have the same history. + + When :attr:`obj` is not a tensor, NumPy array, or DLPack capsule but implements Python's + buffer protocol then the buffer is interpreted as an array of bytes grouped according to + the size of the datatype passed to the :attr:`dtype` keyword argument. (If no datatype is + passed then the default floating point datatype is used, instead.) The returned tensor + will have the specified datatype (or default floating point datatype if none is specified) + and, by default, be on the CPU device and share memory with the buffer. + + When :attr:`obj` is a NumPy scalar, the returned tensor will be a 0-dimensional tensor on + the CPU and that doesn't share its memory (i.e. ``copy=True``). By default datatype will + be the PyTorch datatype corresponding to the NumPy's scalar's datatype. + + When :attr:`obj` is none of the above but a scalar, or a sequence of scalars then the + returned tensor will, by default, infer its datatype from the scalar values, be on the + current default device, and not share its memory. + + .. seealso:: + + :func:`torch.tensor` creates a tensor that always copies the data from the input object. + :func:`torch.from_numpy` creates a tensor that always shares memory from NumPy arrays. + :func:`torch.frombuffer` creates a tensor that always shares memory from objects that + implement the buffer protocol. + :func:`torch.from_dlpack` creates a tensor that always shares memory from + DLPack capsules. + + Args: + obj (object): a tensor, NumPy array, DLPack Capsule, object that implements Python's + buffer protocol, scalar, or sequence of scalars. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the datatype of the returned tensor. + Default: ``None``, which causes the datatype of the returned tensor to be + inferred from :attr:`obj`. + copy (bool, optional): controls whether the returned tensor shares memory with :attr:`obj`. + Default: ``None``, which causes the returned tensor to share memory with :attr:`obj` + whenever possible. If ``True`` then the returned tensor does not share its memory. + If ``False`` then the returned tensor shares its memory with :attr:`obj` and an + error is thrown if it cannot. + device (:class:`torch.device`, optional): the device of the returned tensor. + Default: ``None``, which causes the device of :attr:`obj` to be used. Or, if + :attr:`obj` is a Python sequence, the current default device will be used. + requires_grad (bool, optional): whether the returned tensor requires grad. + Default: ``False``, which causes the returned tensor not to require a gradient. + If ``True``, then the returned tensor will require a gradient, and if :attr:`obj` + is also a tensor with an autograd history then the returned tensor will have + the same history. + + Example:: + + >>> a = torch.tensor([1, 2, 3]) + >>> # Shares memory with tensor 'a' + >>> b = torch.asarray(a) + >>> a.data_ptr() == b.data_ptr() + True + >>> # Forces memory copy + >>> c = torch.asarray(a, copy=True) + >>> a.data_ptr() == c.data_ptr() + False + + >>> a = torch.tensor([1., 2., 3.], requires_grad=True) + >>> b = a + 2 + >>> b + tensor([3., 4., 5.], grad_fn=) + >>> # Shares memory with tensor 'b', with no grad + >>> c = torch.asarray(b) + >>> c + tensor([3., 4., 5.]) + >>> # Shares memory with tensor 'b', retaining autograd history + >>> d = torch.asarray(b, requires_grad=True) + >>> d + tensor([3., 4., 5.], grad_fn=) + + >>> array = numpy.array([1, 2, 3]) + >>> # Shares memory with array 'array' + >>> t1 = torch.asarray(array) + >>> array.__array_interface__['data'][0] == t1.data_ptr() + True + >>> # Copies memory due to dtype mismatch + >>> t2 = torch.asarray(array, dtype=torch.float32) + >>> array.__array_interface__['data'][0] == t2.data_ptr() + False + + >>> scalar = numpy.float64(0.5) + >>> torch.asarray(scalar) + tensor(0.5000, dtype=torch.float64) + """ + +def asin(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + asin(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Returns a new tensor with the arcsine of the elements (in radians) in the :attr:`input` tensor. + + .. math:: + \text{out}_{i} = \sin^{-1}(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-0.5962, 1.4985, -0.4396, 1.4525]) + >>> torch.asin(a) + tensor([-0.6387, nan, -0.4552, nan]) + """ + +def asin_(input: Tensor) -> Tensor: ... +def asinh(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + asinh(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Returns a new tensor with the inverse hyperbolic sine of the elements of :attr:`input`. + + .. math:: + \text{out}_{i} = \sinh^{-1}(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword arguments: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.1606, -1.4267, -1.0899, -1.0250 ]) + >>> torch.asinh(a) + tensor([ 0.1599, -1.1534, -0.9435, -0.8990 ]) + """ + +def asinh_(input: Tensor) -> Tensor: ... +def atan(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + atan(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Returns a new tensor with the arctangent of the elements (in radians) in the :attr:`input` tensor. + + .. math:: + \text{out}_{i} = \tan^{-1}(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.2341, 0.2539, -0.6256, -0.6448]) + >>> torch.atan(a) + tensor([ 0.2299, 0.2487, -0.5591, -0.5727]) + """ + +def atan2( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + atan2(input: Tensor, other: Tensor, *, out: Optional[Tensor]) -> Tensor + + Element-wise arctangent of :math:`\text{input}_{i} / \text{other}_{i}` + with consideration of the quadrant. Returns a new tensor with the signed angles + in radians between vector :math:`(\text{other}_{i}, \text{input}_{i})` + and vector :math:`(1, 0)`. (Note that :math:`\text{other}_{i}`, the second + parameter, is the x-coordinate, while :math:`\text{input}_{i}`, the first + parameter, is the y-coordinate.) + + The shapes of ``input`` and ``other`` must be + :ref:`broadcastable `. + + Args: + input (Tensor): the first input tensor + other (Tensor): the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.9041, 0.0196, -0.3108, -2.4423]) + >>> torch.atan2(a, torch.randn(4)) + tensor([ 0.9833, 0.0811, -1.9743, -1.4151]) + """ + +def atan_(input: Tensor) -> Tensor: ... +def atanh(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + atanh(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Returns a new tensor with the inverse hyperbolic tangent of the elements of :attr:`input`. + + Note: + The domain of the inverse hyperbolic tangent is `(-1, 1)` and values outside this range + will be mapped to ``NaN``, except for the values `1` and `-1` for which the output is + mapped to `+/-INF` respectively. + + .. math:: + \text{out}_{i} = \tanh^{-1}(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword arguments: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4).uniform_(-1, 1) + >>> a + tensor([ -0.9385, 0.2968, -0.8591, -0.1871 ]) + >>> torch.atanh(a) + tensor([ -1.7253, 0.3060, -1.2899, -0.1893 ]) + """ + +def atanh_(input: Tensor) -> Tensor: ... +def avg_pool1d( + input: Tensor, + kernel_size: _int | _size, + stride: _int | _size = (), + padding: _int | _size = 0, + ceil_mode: _bool = False, + count_include_pad: _bool = True, +) -> Tensor: ... +@overload +def baddbmm( + beta: Number | _complex, + self: Tensor, + alpha: Number | _complex, + batch1: Tensor, + batch2: Tensor, +) -> Tensor: + r""" + baddbmm(input, batch1, batch2, out_dtype=None, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a batch matrix-matrix product of matrices in :attr:`batch1` + and :attr:`batch2`. + :attr:`input` is added to the final result. + + :attr:`batch1` and :attr:`batch2` must be 3-D tensors each containing the same + number of matrices. + + If :attr:`batch1` is a :math:`(b \times n \times m)` tensor, :attr:`batch2` is a + :math:`(b \times m \times p)` tensor, then :attr:`input` must be + :ref:`broadcastable ` with a + :math:`(b \times n \times p)` tensor and :attr:`out` will be a + :math:`(b \times n \times p)` tensor. Both :attr:`alpha` and :attr:`beta` mean the + same as the scaling factors used in :meth:`torch.addbmm`. + + .. math:: + \text{out}_i = \beta\ \text{input}_i + \alpha\ (\text{batch1}_i \mathbin{@} \text{batch2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): the tensor to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + out_dtype (dtype, optional): the dtype of the output tensor, + Supported only on CUDA and for torch.float32 given + torch.float16/torch.bfloat16 input dtypes + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{batch1} \mathbin{@} \text{batch2}` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(10, 3, 5) + >>> batch1 = torch.randn(10, 3, 4) + >>> batch2 = torch.randn(10, 4, 5) + >>> torch.baddbmm(M, batch1, batch2).size() + torch.Size([10, 3, 5]) + """ + +@overload +def baddbmm( + beta: Number | _complex, + self: Tensor, + alpha: Number | _complex, + batch1: Tensor, + batch2: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + baddbmm(input, batch1, batch2, out_dtype=None, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a batch matrix-matrix product of matrices in :attr:`batch1` + and :attr:`batch2`. + :attr:`input` is added to the final result. + + :attr:`batch1` and :attr:`batch2` must be 3-D tensors each containing the same + number of matrices. + + If :attr:`batch1` is a :math:`(b \times n \times m)` tensor, :attr:`batch2` is a + :math:`(b \times m \times p)` tensor, then :attr:`input` must be + :ref:`broadcastable ` with a + :math:`(b \times n \times p)` tensor and :attr:`out` will be a + :math:`(b \times n \times p)` tensor. Both :attr:`alpha` and :attr:`beta` mean the + same as the scaling factors used in :meth:`torch.addbmm`. + + .. math:: + \text{out}_i = \beta\ \text{input}_i + \alpha\ (\text{batch1}_i \mathbin{@} \text{batch2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): the tensor to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + out_dtype (dtype, optional): the dtype of the output tensor, + Supported only on CUDA and for torch.float32 given + torch.float16/torch.bfloat16 input dtypes + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{batch1} \mathbin{@} \text{batch2}` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(10, 3, 5) + >>> batch1 = torch.randn(10, 3, 4) + >>> batch2 = torch.randn(10, 4, 5) + >>> torch.baddbmm(M, batch1, batch2).size() + torch.Size([10, 3, 5]) + """ + +@overload +def baddbmm( + input: Tensor, + batch1: Tensor, + batch2: Tensor, + *, + beta: Number | _complex = 1, + alpha: Number | _complex = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + baddbmm(input, batch1, batch2, out_dtype=None, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a batch matrix-matrix product of matrices in :attr:`batch1` + and :attr:`batch2`. + :attr:`input` is added to the final result. + + :attr:`batch1` and :attr:`batch2` must be 3-D tensors each containing the same + number of matrices. + + If :attr:`batch1` is a :math:`(b \times n \times m)` tensor, :attr:`batch2` is a + :math:`(b \times m \times p)` tensor, then :attr:`input` must be + :ref:`broadcastable ` with a + :math:`(b \times n \times p)` tensor and :attr:`out` will be a + :math:`(b \times n \times p)` tensor. Both :attr:`alpha` and :attr:`beta` mean the + same as the scaling factors used in :meth:`torch.addbmm`. + + .. math:: + \text{out}_i = \beta\ \text{input}_i + \alpha\ (\text{batch1}_i \mathbin{@} \text{batch2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): the tensor to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + out_dtype (dtype, optional): the dtype of the output tensor, + Supported only on CUDA and for torch.float32 given + torch.float16/torch.bfloat16 input dtypes + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{batch1} \mathbin{@} \text{batch2}` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(10, 3, 5) + >>> batch1 = torch.randn(10, 3, 4) + >>> batch2 = torch.randn(10, 4, 5) + >>> torch.baddbmm(M, batch1, batch2).size() + torch.Size([10, 3, 5]) + """ + +@overload +def baddbmm( + input: Tensor, + batch1: Tensor, + batch2: Tensor, + out_dtype: _dtype, + *, + beta: Number | _complex = 1, + alpha: Number | _complex = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + baddbmm(input, batch1, batch2, out_dtype=None, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a batch matrix-matrix product of matrices in :attr:`batch1` + and :attr:`batch2`. + :attr:`input` is added to the final result. + + :attr:`batch1` and :attr:`batch2` must be 3-D tensors each containing the same + number of matrices. + + If :attr:`batch1` is a :math:`(b \times n \times m)` tensor, :attr:`batch2` is a + :math:`(b \times m \times p)` tensor, then :attr:`input` must be + :ref:`broadcastable ` with a + :math:`(b \times n \times p)` tensor and :attr:`out` will be a + :math:`(b \times n \times p)` tensor. Both :attr:`alpha` and :attr:`beta` mean the + same as the scaling factors used in :meth:`torch.addbmm`. + + .. math:: + \text{out}_i = \beta\ \text{input}_i + \alpha\ (\text{batch1}_i \mathbin{@} \text{batch2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): the tensor to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + out_dtype (dtype, optional): the dtype of the output tensor, + Supported only on CUDA and for torch.float32 given + torch.float16/torch.bfloat16 input dtypes + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{batch1} \mathbin{@} \text{batch2}` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(10, 3, 5) + >>> batch1 = torch.randn(10, 3, 4) + >>> batch2 = torch.randn(10, 4, 5) + >>> torch.baddbmm(M, batch1, batch2).size() + torch.Size([10, 3, 5]) + """ + +@overload +def baddbmm( + beta: Number | _complex, + self: Tensor, + batch1: Tensor, + batch2: Tensor, +) -> Tensor: + r""" + baddbmm(input, batch1, batch2, out_dtype=None, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a batch matrix-matrix product of matrices in :attr:`batch1` + and :attr:`batch2`. + :attr:`input` is added to the final result. + + :attr:`batch1` and :attr:`batch2` must be 3-D tensors each containing the same + number of matrices. + + If :attr:`batch1` is a :math:`(b \times n \times m)` tensor, :attr:`batch2` is a + :math:`(b \times m \times p)` tensor, then :attr:`input` must be + :ref:`broadcastable ` with a + :math:`(b \times n \times p)` tensor and :attr:`out` will be a + :math:`(b \times n \times p)` tensor. Both :attr:`alpha` and :attr:`beta` mean the + same as the scaling factors used in :meth:`torch.addbmm`. + + .. math:: + \text{out}_i = \beta\ \text{input}_i + \alpha\ (\text{batch1}_i \mathbin{@} \text{batch2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): the tensor to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + out_dtype (dtype, optional): the dtype of the output tensor, + Supported only on CUDA and for torch.float32 given + torch.float16/torch.bfloat16 input dtypes + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{batch1} \mathbin{@} \text{batch2}` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(10, 3, 5) + >>> batch1 = torch.randn(10, 3, 4) + >>> batch2 = torch.randn(10, 4, 5) + >>> torch.baddbmm(M, batch1, batch2).size() + torch.Size([10, 3, 5]) + """ + +@overload +def baddbmm( + beta: Number | _complex, + self: Tensor, + batch1: Tensor, + batch2: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + baddbmm(input, batch1, batch2, out_dtype=None, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a batch matrix-matrix product of matrices in :attr:`batch1` + and :attr:`batch2`. + :attr:`input` is added to the final result. + + :attr:`batch1` and :attr:`batch2` must be 3-D tensors each containing the same + number of matrices. + + If :attr:`batch1` is a :math:`(b \times n \times m)` tensor, :attr:`batch2` is a + :math:`(b \times m \times p)` tensor, then :attr:`input` must be + :ref:`broadcastable ` with a + :math:`(b \times n \times p)` tensor and :attr:`out` will be a + :math:`(b \times n \times p)` tensor. Both :attr:`alpha` and :attr:`beta` mean the + same as the scaling factors used in :meth:`torch.addbmm`. + + .. math:: + \text{out}_i = \beta\ \text{input}_i + \alpha\ (\text{batch1}_i \mathbin{@} \text{batch2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): the tensor to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + out_dtype (dtype, optional): the dtype of the output tensor, + Supported only on CUDA and for torch.float32 given + torch.float16/torch.bfloat16 input dtypes + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{batch1} \mathbin{@} \text{batch2}` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(10, 3, 5) + >>> batch1 = torch.randn(10, 3, 4) + >>> batch2 = torch.randn(10, 4, 5) + >>> torch.baddbmm(M, batch1, batch2).size() + torch.Size([10, 3, 5]) + """ + +@overload +def bartlett_window( + window_length: _int, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + bartlett_window(window_length, periodic=True, *, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Bartlett window function. + + .. math:: + w[n] = 1 - \left| \frac{2n}{N-1} - 1 \right| = \begin{cases} + \frac{2n}{N - 1} & \text{if } 0 \leq n \leq \frac{N - 1}{2} \\ + 2 - \frac{2n}{N - 1} & \text{if } \frac{N - 1}{2} < n < N \\ + \end{cases}, + + where :math:`N` is the full window size. + + The input :attr:`window_length` is a positive integer controlling the + returned window size. :attr:`periodic` flag determines whether the returned + window trims off the last duplicate value from the symmetric window and is + ready to be used as a periodic window with functions like + :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in + above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have + ``torch.bartlett_window(L, periodic=True)`` equal to + ``torch.bartlett_window(L + 1, periodic=False)[:-1])``. + + .. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. + + Arguments: + window_length (int): the size of returned window + periodic (bool, optional): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window + """ + +@overload +def bartlett_window( + window_length: _int, + periodic: _bool, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + bartlett_window(window_length, periodic=True, *, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Bartlett window function. + + .. math:: + w[n] = 1 - \left| \frac{2n}{N-1} - 1 \right| = \begin{cases} + \frac{2n}{N - 1} & \text{if } 0 \leq n \leq \frac{N - 1}{2} \\ + 2 - \frac{2n}{N - 1} & \text{if } \frac{N - 1}{2} < n < N \\ + \end{cases}, + + where :math:`N` is the full window size. + + The input :attr:`window_length` is a positive integer controlling the + returned window size. :attr:`periodic` flag determines whether the returned + window trims off the last duplicate value from the symmetric window and is + ready to be used as a periodic window with functions like + :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in + above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have + ``torch.bartlett_window(L, periodic=True)`` equal to + ``torch.bartlett_window(L + 1, periodic=False)[:-1])``. + + .. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. + + Arguments: + window_length (int): the size of returned window + periodic (bool, optional): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window + """ + +def batch_norm( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + running_mean: Tensor | None, + running_var: Tensor | None, + training: _bool, + momentum: _float, + eps: _float, + cudnn_enabled: _bool, +) -> Tensor: ... +def batch_norm_backward_elemt( + grad_out: Tensor, + input: Tensor, + mean: Tensor, + invstd: Tensor, + weight: Tensor | None, + sum_dy: Tensor, + sum_dy_xmu: Tensor, + count: Tensor, +) -> Tensor: ... +def batch_norm_backward_reduce( + grad_out: Tensor, + input: Tensor, + mean: Tensor, + invstd: Tensor, + weight: Tensor | None, + input_g: _bool, + weight_g: _bool, + bias_g: _bool, +) -> tuple[Tensor, Tensor, Tensor, Tensor]: ... +def batch_norm_elemt( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + mean: Tensor, + invstd: Tensor, + eps: _float, + *, + out: Tensor | None = None, +) -> Tensor: ... +def batch_norm_gather_stats( + input: Tensor, + mean: Tensor, + invstd: Tensor, + running_mean: Tensor | None, + running_var: Tensor | None, + momentum: _float, + eps: _float, + count: _int, +) -> tuple[Tensor, Tensor]: ... +def batch_norm_gather_stats_with_counts( + input: Tensor, + mean: Tensor, + invstd: Tensor, + running_mean: Tensor | None, + running_var: Tensor | None, + momentum: _float, + eps: _float, + counts: Tensor, +) -> tuple[Tensor, Tensor]: ... +def batch_norm_stats(input: Tensor, eps: _float) -> tuple[Tensor, Tensor]: ... +def batch_norm_update_stats( + input: Tensor, + running_mean: Tensor | None, + running_var: Tensor | None, + momentum: _float, +) -> tuple[Tensor, Tensor]: ... +@overload +def bernoulli( + input: Tensor, + *, + generator: Generator | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + bernoulli(input: Tensor, *, generator: Optional[Generator], out: Optional[Tensor]) -> Tensor + + Draws binary random numbers (0 or 1) from a Bernoulli distribution. + + The :attr:`input` tensor should be a tensor containing probabilities + to be used for drawing the binary random number. + Hence, all values in :attr:`input` have to be in the range: + :math:`0 \leq \text{input}_i \leq 1`. + + The :math:`\text{i}^{th}` element of the output tensor will draw a + value :math:`1` according to the :math:`\text{i}^{th}` probability value given + in :attr:`input`. + + .. math:: + \text{out}_{i} \sim \mathrm{Bernoulli}(p = \text{input}_{i}) + + The returned :attr:`out` tensor only has values 0 or 1 and is of the same + shape as :attr:`input`. + + :attr:`out` can have integral ``dtype``, but :attr:`input` must have floating + point ``dtype``. + + Args: + input (Tensor): the input tensor of probability values for the Bernoulli distribution + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.empty(3, 3).uniform_(0, 1) # generate a uniform random matrix with range [0, 1] + >>> a + tensor([[ 0.1737, 0.0950, 0.3609], + [ 0.7148, 0.0289, 0.2676], + [ 0.9456, 0.8937, 0.7202]]) + >>> torch.bernoulli(a) + tensor([[ 1., 0., 0.], + [ 0., 0., 0.], + [ 1., 1., 1.]]) + + >>> a = torch.ones(3, 3) # probability of drawing "1" is 1 + >>> torch.bernoulli(a) + tensor([[ 1., 1., 1.], + [ 1., 1., 1.], + [ 1., 1., 1.]]) + >>> a = torch.zeros(3, 3) # probability of drawing "1" is 0 + >>> torch.bernoulli(a) + tensor([[ 0., 0., 0.], + [ 0., 0., 0.], + [ 0., 0., 0.]]) + """ + +@overload +def bernoulli( + input: Tensor, + p: _float, + *, + generator: Generator | None = None, +) -> Tensor: + r""" + bernoulli(input: Tensor, *, generator: Optional[Generator], out: Optional[Tensor]) -> Tensor + + Draws binary random numbers (0 or 1) from a Bernoulli distribution. + + The :attr:`input` tensor should be a tensor containing probabilities + to be used for drawing the binary random number. + Hence, all values in :attr:`input` have to be in the range: + :math:`0 \leq \text{input}_i \leq 1`. + + The :math:`\text{i}^{th}` element of the output tensor will draw a + value :math:`1` according to the :math:`\text{i}^{th}` probability value given + in :attr:`input`. + + .. math:: + \text{out}_{i} \sim \mathrm{Bernoulli}(p = \text{input}_{i}) + + The returned :attr:`out` tensor only has values 0 or 1 and is of the same + shape as :attr:`input`. + + :attr:`out` can have integral ``dtype``, but :attr:`input` must have floating + point ``dtype``. + + Args: + input (Tensor): the input tensor of probability values for the Bernoulli distribution + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.empty(3, 3).uniform_(0, 1) # generate a uniform random matrix with range [0, 1] + >>> a + tensor([[ 0.1737, 0.0950, 0.3609], + [ 0.7148, 0.0289, 0.2676], + [ 0.9456, 0.8937, 0.7202]]) + >>> torch.bernoulli(a) + tensor([[ 1., 0., 0.], + [ 0., 0., 0.], + [ 1., 1., 1.]]) + + >>> a = torch.ones(3, 3) # probability of drawing "1" is 1 + >>> torch.bernoulli(a) + tensor([[ 1., 1., 1.], + [ 1., 1., 1.], + [ 1., 1., 1.]]) + >>> a = torch.zeros(3, 3) # probability of drawing "1" is 0 + >>> torch.bernoulli(a) + tensor([[ 0., 0., 0.], + [ 0., 0., 0.], + [ 0., 0., 0.]]) + """ + +def bilinear( + input1: Tensor, + input2: Tensor, + weight: Tensor, + bias: Tensor | None = None, +) -> Tensor: ... +def binary_cross_entropy_with_logits( + input: Tensor, + target: Tensor, + weight: Tensor | None = None, + pos_weight: Tensor | None = None, + reduction: _int = 1, +) -> Tensor: ... +def bincount( + input: Tensor, + weights: Tensor | None = None, + minlength: _int | SymInt = 0, +) -> Tensor: + r""" + bincount(input, weights=None, minlength=0) -> Tensor + + Count the frequency of each value in an array of non-negative ints. + + The number of bins (size 1) is one larger than the largest value in + :attr:`input` unless :attr:`input` is empty, in which case the result is a + tensor of size 0. If :attr:`minlength` is specified, the number of bins is at least + :attr:`minlength` and if :attr:`input` is empty, then the result is tensor of size + :attr:`minlength` filled with zeros. If ``n`` is the value at position ``i``, + ``out[n] += weights[i]`` if :attr:`weights` is specified else + ``out[n] += 1``. + + Note: + This operation may produce nondeterministic gradients when given tensors on a CUDA device. See :doc:`/notes/randomness` for more information. + + Arguments: + input (Tensor): 1-d int tensor + weights (Tensor): optional, weight for each value in the input tensor. + Should be of same size as input tensor. + minlength (int): optional, minimum number of bins. Should be non-negative. + + Returns: + output (Tensor): a tensor of shape ``Size([max(input) + 1])`` if + :attr:`input` is non-empty, else ``Size(0)`` + + Example:: + + >>> input = torch.randint(0, 8, (5,), dtype=torch.int64) + >>> weights = torch.linspace(0, 1, steps=5) + >>> input, weights + (tensor([4, 3, 6, 3, 4]), + tensor([ 0.0000, 0.2500, 0.5000, 0.7500, 1.0000]) + + >>> torch.bincount(input) + tensor([0, 0, 0, 2, 2, 0, 1]) + + >>> input.bincount(weights) + tensor([0.0000, 0.0000, 0.0000, 1.0000, 1.0000, 0.0000, 0.5000]) + """ + +def binomial( + count: Tensor, + prob: Tensor, + generator: Generator | None = None, +) -> Tensor: ... +@overload +def bitwise_and( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + bitwise_and(input, other, *, out=None) -> Tensor + + Computes the bitwise AND of :attr:`input` and :attr:`other`. The input tensor must be of + integral or Boolean types. For bool tensors, it computes the logical AND. + + Args: + input: the first input tensor + other: the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_and(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([1, 0, 3], dtype=torch.int8) + >>> torch.bitwise_and(torch.tensor([True, True, False]), torch.tensor([False, True, False])) + tensor([ False, True, False]) + """ + +@overload +def bitwise_and(self: Number | _complex, other: Tensor) -> Tensor: + r""" + bitwise_and(input, other, *, out=None) -> Tensor + + Computes the bitwise AND of :attr:`input` and :attr:`other`. The input tensor must be of + integral or Boolean types. For bool tensors, it computes the logical AND. + + Args: + input: the first input tensor + other: the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_and(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([1, 0, 3], dtype=torch.int8) + >>> torch.bitwise_and(torch.tensor([True, True, False]), torch.tensor([False, True, False])) + tensor([ False, True, False]) + """ + +@overload +def bitwise_and( + input: Tensor, + other: Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + bitwise_and(input, other, *, out=None) -> Tensor + + Computes the bitwise AND of :attr:`input` and :attr:`other`. The input tensor must be of + integral or Boolean types. For bool tensors, it computes the logical AND. + + Args: + input: the first input tensor + other: the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_and(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([1, 0, 3], dtype=torch.int8) + >>> torch.bitwise_and(torch.tensor([True, True, False]), torch.tensor([False, True, False])) + tensor([ False, True, False]) + """ + +@overload +def bitwise_left_shift( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + bitwise_left_shift(input, other, *, out=None) -> Tensor + + Computes the left arithmetic shift of :attr:`input` by :attr:`other` bits. + The input tensor must be of integral type. This operator supports + :ref:`broadcasting to a common shape ` and + :ref:`type promotion `. + + The operation applied is: + + .. math:: + \text{out}_i = \text{input}_i << \text{other}_i + + Args: + input (Tensor or Scalar): the first input tensor + other (Tensor or Scalar): the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_left_shift(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-2, -2, 24], dtype=torch.int8) + """ + +@overload +def bitwise_left_shift(self: Number | _complex, other: Tensor) -> Tensor: + r""" + bitwise_left_shift(input, other, *, out=None) -> Tensor + + Computes the left arithmetic shift of :attr:`input` by :attr:`other` bits. + The input tensor must be of integral type. This operator supports + :ref:`broadcasting to a common shape ` and + :ref:`type promotion `. + + The operation applied is: + + .. math:: + \text{out}_i = \text{input}_i << \text{other}_i + + Args: + input (Tensor or Scalar): the first input tensor + other (Tensor or Scalar): the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_left_shift(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-2, -2, 24], dtype=torch.int8) + """ + +@overload +def bitwise_left_shift( + input: Tensor, + other: Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + bitwise_left_shift(input, other, *, out=None) -> Tensor + + Computes the left arithmetic shift of :attr:`input` by :attr:`other` bits. + The input tensor must be of integral type. This operator supports + :ref:`broadcasting to a common shape ` and + :ref:`type promotion `. + + The operation applied is: + + .. math:: + \text{out}_i = \text{input}_i << \text{other}_i + + Args: + input (Tensor or Scalar): the first input tensor + other (Tensor or Scalar): the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_left_shift(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-2, -2, 24], dtype=torch.int8) + """ + +def bitwise_not(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + bitwise_not(input, *, out=None) -> Tensor + + Computes the bitwise NOT of the given input tensor. The input tensor must be of + integral or Boolean types. For bool tensors, it computes the logical NOT. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_not(torch.tensor([-1, -2, 3], dtype=torch.int8)) + tensor([ 0, 1, -4], dtype=torch.int8) + """ + +@overload +def bitwise_or( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + bitwise_or(input: Tensor, other: Tensor, *, out: Optional[Tensor]) -> Tensor + + Computes the bitwise OR of :attr:`input` and :attr:`other`. The input tensor must be of + integral or Boolean types. For bool tensors, it computes the logical OR. + + Args: + input: the first input tensor + other: the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_or(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-1, -2, 3], dtype=torch.int8) + >>> torch.bitwise_or(torch.tensor([True, True, False]), torch.tensor([False, True, False])) + tensor([ True, True, False]) + """ + +@overload +def bitwise_or(self: Number | _complex, other: Tensor) -> Tensor: + r""" + bitwise_or(input: Tensor, other: Tensor, *, out: Optional[Tensor]) -> Tensor + + Computes the bitwise OR of :attr:`input` and :attr:`other`. The input tensor must be of + integral or Boolean types. For bool tensors, it computes the logical OR. + + Args: + input: the first input tensor + other: the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_or(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-1, -2, 3], dtype=torch.int8) + >>> torch.bitwise_or(torch.tensor([True, True, False]), torch.tensor([False, True, False])) + tensor([ True, True, False]) + """ + +@overload +def bitwise_or( + input: Tensor, + other: Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + bitwise_or(input: Tensor, other: Tensor, *, out: Optional[Tensor]) -> Tensor + + Computes the bitwise OR of :attr:`input` and :attr:`other`. The input tensor must be of + integral or Boolean types. For bool tensors, it computes the logical OR. + + Args: + input: the first input tensor + other: the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_or(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-1, -2, 3], dtype=torch.int8) + >>> torch.bitwise_or(torch.tensor([True, True, False]), torch.tensor([False, True, False])) + tensor([ True, True, False]) + """ + +@overload +def bitwise_right_shift( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + bitwise_right_shift(input, other, *, out=None) -> Tensor + + Computes the right arithmetic shift of :attr:`input` by :attr:`other` bits. + The input tensor must be of integral type. This operator supports + :ref:`broadcasting to a common shape ` and + :ref:`type promotion `. + In any case, if the value of the right operand is negative or is greater + or equal to the number of bits in the promoted left operand, the behavior is undefined. + + The operation applied is: + + .. math:: + \text{out}_i = \text{input}_i >> \text{other}_i + + Args: + input (Tensor or Scalar): the first input tensor + other (Tensor or Scalar): the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_right_shift(torch.tensor([-2, -7, 31], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-1, -7, 3], dtype=torch.int8) + """ + +@overload +def bitwise_right_shift(self: Number | _complex, other: Tensor) -> Tensor: + r""" + bitwise_right_shift(input, other, *, out=None) -> Tensor + + Computes the right arithmetic shift of :attr:`input` by :attr:`other` bits. + The input tensor must be of integral type. This operator supports + :ref:`broadcasting to a common shape ` and + :ref:`type promotion `. + In any case, if the value of the right operand is negative or is greater + or equal to the number of bits in the promoted left operand, the behavior is undefined. + + The operation applied is: + + .. math:: + \text{out}_i = \text{input}_i >> \text{other}_i + + Args: + input (Tensor or Scalar): the first input tensor + other (Tensor or Scalar): the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_right_shift(torch.tensor([-2, -7, 31], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-1, -7, 3], dtype=torch.int8) + """ + +@overload +def bitwise_right_shift( + input: Tensor, + other: Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + bitwise_right_shift(input, other, *, out=None) -> Tensor + + Computes the right arithmetic shift of :attr:`input` by :attr:`other` bits. + The input tensor must be of integral type. This operator supports + :ref:`broadcasting to a common shape ` and + :ref:`type promotion `. + In any case, if the value of the right operand is negative or is greater + or equal to the number of bits in the promoted left operand, the behavior is undefined. + + The operation applied is: + + .. math:: + \text{out}_i = \text{input}_i >> \text{other}_i + + Args: + input (Tensor or Scalar): the first input tensor + other (Tensor or Scalar): the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_right_shift(torch.tensor([-2, -7, 31], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-1, -7, 3], dtype=torch.int8) + """ + +@overload +def bitwise_xor( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + bitwise_xor(input, other, *, out=None) -> Tensor + + Computes the bitwise XOR of :attr:`input` and :attr:`other`. The input tensor must be of + integral or Boolean types. For bool tensors, it computes the logical XOR. + + Args: + input: the first input tensor + other: the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_xor(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-2, -2, 0], dtype=torch.int8) + >>> torch.bitwise_xor(torch.tensor([True, True, False]), torch.tensor([False, True, False])) + tensor([ True, False, False]) + """ + +@overload +def bitwise_xor(self: Number | _complex, other: Tensor) -> Tensor: + r""" + bitwise_xor(input, other, *, out=None) -> Tensor + + Computes the bitwise XOR of :attr:`input` and :attr:`other`. The input tensor must be of + integral or Boolean types. For bool tensors, it computes the logical XOR. + + Args: + input: the first input tensor + other: the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_xor(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-2, -2, 0], dtype=torch.int8) + >>> torch.bitwise_xor(torch.tensor([True, True, False]), torch.tensor([False, True, False])) + tensor([ True, False, False]) + """ + +@overload +def bitwise_xor( + input: Tensor, + other: Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + bitwise_xor(input, other, *, out=None) -> Tensor + + Computes the bitwise XOR of :attr:`input` and :attr:`other`. The input tensor must be of + integral or Boolean types. For bool tensors, it computes the logical XOR. + + Args: + input: the first input tensor + other: the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_xor(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-2, -2, 0], dtype=torch.int8) + >>> torch.bitwise_xor(torch.tensor([True, True, False]), torch.tensor([False, True, False])) + tensor([ True, False, False]) + """ + +@overload +def blackman_window( + window_length: _int, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + blackman_window(window_length, periodic=True, *, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Blackman window function. + + .. math:: + w[n] = 0.42 - 0.5 \cos \left( \frac{2 \pi n}{N - 1} \right) + 0.08 \cos \left( \frac{4 \pi n}{N - 1} \right) + + where :math:`N` is the full window size. + + The input :attr:`window_length` is a positive integer controlling the + returned window size. :attr:`periodic` flag determines whether the returned + window trims off the last duplicate value from the symmetric window and is + ready to be used as a periodic window with functions like + :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in + above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have + ``torch.blackman_window(L, periodic=True)`` equal to + ``torch.blackman_window(L + 1, periodic=False)[:-1]``. + + .. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. + + Arguments: + window_length (int): the size of returned window + periodic (bool, optional): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window + """ + +@overload +def blackman_window( + window_length: _int, + periodic: _bool, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + blackman_window(window_length, periodic=True, *, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Blackman window function. + + .. math:: + w[n] = 0.42 - 0.5 \cos \left( \frac{2 \pi n}{N - 1} \right) + 0.08 \cos \left( \frac{4 \pi n}{N - 1} \right) + + where :math:`N` is the full window size. + + The input :attr:`window_length` is a positive integer controlling the + returned window size. :attr:`periodic` flag determines whether the returned + window trims off the last duplicate value from the symmetric window and is + ready to be used as a periodic window with functions like + :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in + above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have + ``torch.blackman_window(L, periodic=True)`` equal to + ``torch.blackman_window(L + 1, periodic=False)[:-1]``. + + .. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. + + Arguments: + window_length (int): the size of returned window + periodic (bool, optional): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window + """ + +@overload +def bmm( + input: Tensor, + mat2: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + bmm(input, mat2, out_dtype=None, *, out=None) -> Tensor + + Performs a batch matrix-matrix product of matrices stored in :attr:`input` + and :attr:`mat2`. + + :attr:`input` and :attr:`mat2` must be 3-D tensors each containing + the same number of matrices. + + If :attr:`input` is a :math:`(b \times n \times m)` tensor, :attr:`mat2` is a + :math:`(b \times m \times p)` tensor, :attr:`out` will be a + :math:`(b \times n \times p)` tensor. + + .. math:: + \text{out}_i = \text{input}_i \mathbin{@} \text{mat2}_i + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + .. note:: This function does not :ref:`broadcast `. + For broadcasting matrix products, see :func:`torch.matmul`. + + Args: + input (Tensor): the first batch of matrices to be multiplied + mat2 (Tensor): the second batch of matrices to be multiplied + out_dtype (dtype, optional): the dtype of the output tensor, + Supported only on CUDA and for torch.float32 given + torch.float16/torch.bfloat16 input dtypes + + Keyword Args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> input = torch.randn(10, 3, 4) + >>> mat2 = torch.randn(10, 4, 5) + >>> res = torch.bmm(input, mat2) + >>> res.size() + torch.Size([10, 3, 5]) + """ + +@overload +def bmm( + input: Tensor, + mat2: Tensor, + out_dtype: _dtype, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + bmm(input, mat2, out_dtype=None, *, out=None) -> Tensor + + Performs a batch matrix-matrix product of matrices stored in :attr:`input` + and :attr:`mat2`. + + :attr:`input` and :attr:`mat2` must be 3-D tensors each containing + the same number of matrices. + + If :attr:`input` is a :math:`(b \times n \times m)` tensor, :attr:`mat2` is a + :math:`(b \times m \times p)` tensor, :attr:`out` will be a + :math:`(b \times n \times p)` tensor. + + .. math:: + \text{out}_i = \text{input}_i \mathbin{@} \text{mat2}_i + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + .. note:: This function does not :ref:`broadcast `. + For broadcasting matrix products, see :func:`torch.matmul`. + + Args: + input (Tensor): the first batch of matrices to be multiplied + mat2 (Tensor): the second batch of matrices to be multiplied + out_dtype (dtype, optional): the dtype of the output tensor, + Supported only on CUDA and for torch.float32 given + torch.float16/torch.bfloat16 input dtypes + + Keyword Args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> input = torch.randn(10, 3, 4) + >>> mat2 = torch.randn(10, 4, 5) + >>> res = torch.bmm(input, mat2) + >>> res.size() + torch.Size([10, 3, 5]) + """ + +def broadcast_to(input: Tensor, size: Sequence[_int | SymInt]) -> Tensor: + r""" + broadcast_to(input, shape) -> Tensor + + Broadcasts :attr:`input` to the shape :attr:`\shape`. + Equivalent to calling ``input.expand(shape)``. See :meth:`~Tensor.expand` for details. + + Args: + input (Tensor): the input tensor. + shape (list, tuple, or :class:`torch.Size`): the new shape. + + Example:: + + >>> x = torch.tensor([1, 2, 3]) + >>> torch.broadcast_to(x, (3, 3)) + tensor([[1, 2, 3], + [1, 2, 3], + [1, 2, 3]]) + """ + +@overload +def bucketize( + input: Tensor, + boundaries: Tensor, + *, + out_int32: _bool = False, + right: _bool = False, + out: Tensor | None = None, +) -> Tensor: + r""" + bucketize(input, boundaries, *, out_int32=False, right=False, out=None) -> Tensor + + Returns the indices of the buckets to which each value in the :attr:`input` belongs, where the + boundaries of the buckets are set by :attr:`boundaries`. Return a new tensor with the same size + as :attr:`input`. If :attr:`right` is False (default), then the left boundary is open. Note that + this behavior is opposite the behavior of + `numpy.digitize `_. + More formally, the returned index satisfies the following rules: + + .. list-table:: + :widths: 15 85 + :header-rows: 1 + + * - :attr:`right` + - *returned index satisfies* + * - False + - ``boundaries[i-1] < input[m][n]...[l][x] <= boundaries[i]`` + * - True + - ``boundaries[i-1] <= input[m][n]...[l][x] < boundaries[i]`` + + Args: + input (Tensor or Scalar): N-D tensor or a Scalar containing the search value(s). + boundaries (Tensor): 1-D tensor, must contain a strictly increasing sequence, or the return value is undefined. + + Keyword args: + out_int32 (bool, optional): indicate the output data type. torch.int32 if True, torch.int64 otherwise. + Default value is False, i.e. default output data type is torch.int64. + right (bool, optional): determines the behavior for values in :attr:`boundaries`. See the table above. + out (Tensor, optional): the output tensor, must be the same size as :attr:`input` if provided. + + + Example:: + + >>> boundaries = torch.tensor([1, 3, 5, 7, 9]) + >>> boundaries + tensor([1, 3, 5, 7, 9]) + >>> v = torch.tensor([[3, 6, 9], [3, 6, 9]]) + >>> v + tensor([[3, 6, 9], + [3, 6, 9]]) + >>> torch.bucketize(v, boundaries) + tensor([[1, 3, 4], + [1, 3, 4]]) + >>> torch.bucketize(v, boundaries, right=True) + tensor([[2, 3, 5], + [2, 3, 5]]) + """ + +@overload +def bucketize( + self: Number | _complex, + boundaries: Tensor, + *, + out_int32: _bool = False, + right: _bool = False, +) -> Tensor: + r""" + bucketize(input, boundaries, *, out_int32=False, right=False, out=None) -> Tensor + + Returns the indices of the buckets to which each value in the :attr:`input` belongs, where the + boundaries of the buckets are set by :attr:`boundaries`. Return a new tensor with the same size + as :attr:`input`. If :attr:`right` is False (default), then the left boundary is open. Note that + this behavior is opposite the behavior of + `numpy.digitize `_. + More formally, the returned index satisfies the following rules: + + .. list-table:: + :widths: 15 85 + :header-rows: 1 + + * - :attr:`right` + - *returned index satisfies* + * - False + - ``boundaries[i-1] < input[m][n]...[l][x] <= boundaries[i]`` + * - True + - ``boundaries[i-1] <= input[m][n]...[l][x] < boundaries[i]`` + + Args: + input (Tensor or Scalar): N-D tensor or a Scalar containing the search value(s). + boundaries (Tensor): 1-D tensor, must contain a strictly increasing sequence, or the return value is undefined. + + Keyword args: + out_int32 (bool, optional): indicate the output data type. torch.int32 if True, torch.int64 otherwise. + Default value is False, i.e. default output data type is torch.int64. + right (bool, optional): determines the behavior for values in :attr:`boundaries`. See the table above. + out (Tensor, optional): the output tensor, must be the same size as :attr:`input` if provided. + + + Example:: + + >>> boundaries = torch.tensor([1, 3, 5, 7, 9]) + >>> boundaries + tensor([1, 3, 5, 7, 9]) + >>> v = torch.tensor([[3, 6, 9], [3, 6, 9]]) + >>> v + tensor([[3, 6, 9], + [3, 6, 9]]) + >>> torch.bucketize(v, boundaries) + tensor([[1, 3, 4], + [1, 3, 4]]) + >>> torch.bucketize(v, boundaries, right=True) + tensor([[2, 3, 5], + [2, 3, 5]]) + """ + +def can_cast(from_: _dtype, to: _dtype) -> _bool: + r""" + can_cast(from_, to) -> bool + + Determines if a type conversion is allowed under PyTorch casting rules + described in the type promotion :ref:`documentation `. + + Args: + from\_ (dtype): The original :class:`torch.dtype`. + to (dtype): The target :class:`torch.dtype`. + + Example:: + + >>> torch.can_cast(torch.double, torch.float) + True + >>> torch.can_cast(torch.float, torch.int) + False + """ + +@overload +def cat( + tensors: tuple[Tensor, ...] | list[Tensor] | None, + dim: _int = 0, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + cat(tensors, dim=0, *, out=None) -> Tensor + + Concatenates the given sequence of tensors in :attr:`tensors` in the given dimension. + All tensors must either have the same shape (except in the concatenating + dimension) or be a 1-D empty tensor with size ``(0,)``. + + :func:`torch.cat` can be seen as an inverse operation for :func:`torch.split` + and :func:`torch.chunk`. + + :func:`torch.cat` can be best understood via examples. + + .. seealso:: + + :func:`torch.stack` concatenates the given sequence along a new dimension. + + Args: + tensors (sequence of Tensors): Non-empty tensors provided must have the same shape, + except in the cat dimension. + + dim (int, optional): the dimension over which the tensors are concatenated + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> x = torch.randn(2, 3) + >>> x + tensor([[ 0.6580, -1.0969, -0.4614], + [-0.1034, -0.5790, 0.1497]]) + >>> torch.cat((x, x, x), 0) + tensor([[ 0.6580, -1.0969, -0.4614], + [-0.1034, -0.5790, 0.1497], + [ 0.6580, -1.0969, -0.4614], + [-0.1034, -0.5790, 0.1497], + [ 0.6580, -1.0969, -0.4614], + [-0.1034, -0.5790, 0.1497]]) + >>> torch.cat((x, x, x), 1) + tensor([[ 0.6580, -1.0969, -0.4614, 0.6580, -1.0969, -0.4614, 0.6580, + -1.0969, -0.4614], + [-0.1034, -0.5790, 0.1497, -0.1034, -0.5790, 0.1497, -0.1034, + -0.5790, 0.1497]]) + """ + +@overload +def cat( + tensors: tuple[Tensor, ...] | list[Tensor] | None, + dim: str | EllipsisType | None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + cat(tensors, dim=0, *, out=None) -> Tensor + + Concatenates the given sequence of tensors in :attr:`tensors` in the given dimension. + All tensors must either have the same shape (except in the concatenating + dimension) or be a 1-D empty tensor with size ``(0,)``. + + :func:`torch.cat` can be seen as an inverse operation for :func:`torch.split` + and :func:`torch.chunk`. + + :func:`torch.cat` can be best understood via examples. + + .. seealso:: + + :func:`torch.stack` concatenates the given sequence along a new dimension. + + Args: + tensors (sequence of Tensors): Non-empty tensors provided must have the same shape, + except in the cat dimension. + + dim (int, optional): the dimension over which the tensors are concatenated + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> x = torch.randn(2, 3) + >>> x + tensor([[ 0.6580, -1.0969, -0.4614], + [-0.1034, -0.5790, 0.1497]]) + >>> torch.cat((x, x, x), 0) + tensor([[ 0.6580, -1.0969, -0.4614], + [-0.1034, -0.5790, 0.1497], + [ 0.6580, -1.0969, -0.4614], + [-0.1034, -0.5790, 0.1497], + [ 0.6580, -1.0969, -0.4614], + [-0.1034, -0.5790, 0.1497]]) + >>> torch.cat((x, x, x), 1) + tensor([[ 0.6580, -1.0969, -0.4614, 0.6580, -1.0969, -0.4614, 0.6580, + -1.0969, -0.4614], + [-0.1034, -0.5790, 0.1497, -0.1034, -0.5790, 0.1497, -0.1034, + -0.5790, 0.1497]]) + """ + +def ccol_indices_copy( + input: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: ... +def ceil(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + ceil(input, *, out=None) -> Tensor + + Returns a new tensor with the ceil of the elements of :attr:`input`, + the smallest integer greater than or equal to each element. + + For integer inputs, follows the array-api convention of returning a + copy of the input tensor. + + .. math:: + \text{out}_{i} = \left\lceil \text{input}_{i} \right\rceil + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-0.6341, -1.4208, -1.0900, 0.5826]) + >>> torch.ceil(a) + tensor([-0., -1., -1., 1.]) + """ + +def ceil_(input: Tensor) -> Tensor: ... +def celu(input: Tensor, alpha: Number | _complex = 1.0) -> Tensor: ... +def celu_(input: Tensor, alpha: Number | _complex = 1.0) -> Tensor: ... +def channel_shuffle(input: Tensor, groups: _int | SymInt) -> Tensor: ... +def cholesky( + input: Tensor, + upper: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + cholesky(input, upper=False, *, out=None) -> Tensor + + Computes the Cholesky decomposition of a symmetric positive-definite + matrix :math:`A` or for batches of symmetric positive-definite matrices. + + If :attr:`upper` is ``True``, the returned matrix ``U`` is upper-triangular, and + the decomposition has the form: + + .. math:: + + A = U^TU + + If :attr:`upper` is ``False``, the returned matrix ``L`` is lower-triangular, and + the decomposition has the form: + + .. math:: + + A = LL^T + + If :attr:`upper` is ``True``, and :math:`A` is a batch of symmetric positive-definite + matrices, then the returned tensor will be composed of upper-triangular Cholesky factors + of each of the individual matrices. Similarly, when :attr:`upper` is ``False``, the returned + tensor will be composed of lower-triangular Cholesky factors of each of the individual + matrices. + + .. warning:: + + :func:`torch.cholesky` is deprecated in favor of :func:`torch.linalg.cholesky` + and will be removed in a future PyTorch release. + + ``L = torch.cholesky(A)`` should be replaced with + + .. code:: python + + L = torch.linalg.cholesky(A) + + ``U = torch.cholesky(A, upper=True)`` should be replaced with + + .. code:: python + + U = torch.linalg.cholesky(A).mH + + This transform will produce equivalent results for all valid (symmetric positive definite) inputs. + + Args: + input (Tensor): the input tensor :math:`A` of size :math:`(*, n, n)` where `*` is zero or more + batch dimensions consisting of symmetric positive-definite matrices. + upper (bool, optional): flag that indicates whether to return a + upper or lower triangular matrix. Default: ``False`` + + Keyword args: + out (Tensor, optional): the output matrix + + Example:: + + >>> a = torch.randn(3, 3) + >>> a = a @ a.mT + 1e-3 # make symmetric positive-definite + >>> l = torch.cholesky(a) + >>> a + tensor([[ 2.4112, -0.7486, 1.4551], + [-0.7486, 1.3544, 0.1294], + [ 1.4551, 0.1294, 1.6724]]) + >>> l + tensor([[ 1.5528, 0.0000, 0.0000], + [-0.4821, 1.0592, 0.0000], + [ 0.9371, 0.5487, 0.7023]]) + >>> l @ l.mT + tensor([[ 2.4112, -0.7486, 1.4551], + [-0.7486, 1.3544, 0.1294], + [ 1.4551, 0.1294, 1.6724]]) + >>> a = torch.randn(3, 2, 2) # Example for batched input + >>> a = a @ a.mT + 1e-03 # make symmetric positive-definite + >>> l = torch.cholesky(a) + >>> z = l @ l.mT + >>> torch.dist(z, a) + tensor(2.3842e-07) + """ + +def cholesky_inverse( + input: Tensor, + upper: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + cholesky_inverse(L, upper=False, *, out=None) -> Tensor + + Computes the inverse of a complex Hermitian or real symmetric + positive-definite matrix given its Cholesky decomposition. + + Let :math:`A` be a complex Hermitian or real symmetric positive-definite matrix, + and :math:`L` its Cholesky decomposition such that: + + .. math:: + + A = LL^{\text{H}} + + where :math:`L^{\text{H}}` is the conjugate transpose when :math:`L` is complex, + and the transpose when :math:`L` is real-valued. + + Computes the inverse matrix :math:`A^{-1}`. + + Supports input of float, double, cfloat and cdouble dtypes. + Also supports batches of matrices, and if :math:`A` is a batch of matrices + then the output has the same batch dimensions. + + Args: + L (Tensor): tensor of shape `(*, n, n)` where `*` is zero or more batch dimensions + consisting of lower or upper triangular Cholesky decompositions of + symmetric or Hermitian positive-definite matrices. + upper (bool, optional): flag that indicates whether :math:`L` is lower triangular + or upper triangular. Default: ``False`` + + Keyword args: + out (Tensor, optional): output tensor. Ignored if `None`. Default: `None`. + + Example:: + + >>> A = torch.randn(3, 3) + >>> A = A @ A.T + torch.eye(3) * 1e-3 # Creates a symmetric positive-definite matrix + >>> L = torch.linalg.cholesky(A) # Extract Cholesky decomposition + >>> torch.cholesky_inverse(L) + tensor([[ 1.9314, 1.2251, -0.0889], + [ 1.2251, 2.4439, 0.2122], + [-0.0889, 0.2122, 0.1412]]) + >>> A.inverse() + tensor([[ 1.9314, 1.2251, -0.0889], + [ 1.2251, 2.4439, 0.2122], + [-0.0889, 0.2122, 0.1412]]) + + >>> A = torch.randn(3, 2, 2, dtype=torch.complex64) + >>> A = A @ A.mH + torch.eye(2) * 1e-3 # Batch of Hermitian positive-definite matrices + >>> L = torch.linalg.cholesky(A) + >>> torch.dist(torch.inverse(A), torch.cholesky_inverse(L)) + tensor(5.6358e-7) + """ + +def cholesky_solve( + input: Tensor, + input2: Tensor, + upper: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + cholesky_solve(B, L, upper=False, *, out=None) -> Tensor + + Computes the solution of a system of linear equations with complex Hermitian + or real symmetric positive-definite lhs given its Cholesky decomposition. + + Let :math:`A` be a complex Hermitian or real symmetric positive-definite matrix, + and :math:`L` its Cholesky decomposition such that: + + .. math:: + + A = LL^{\text{H}} + + where :math:`L^{\text{H}}` is the conjugate transpose when :math:`L` is complex, + and the transpose when :math:`L` is real-valued. + + Returns the solution :math:`X` of the following linear system: + + .. math:: + + AX = B + + Supports inputs of float, double, cfloat and cdouble dtypes. + Also supports batches of matrices, and if :math:`A` or :math:`B` is a batch of matrices + then the output has the same batch dimensions. + + Args: + B (Tensor): right-hand side tensor of shape `(*, n, k)` + where :math:`*` is zero or more batch dimensions + L (Tensor): tensor of shape `(*, n, n)` where `*` is zero or more batch dimensions + consisting of lower or upper triangular Cholesky decompositions of + symmetric or Hermitian positive-definite matrices. + upper (bool, optional): flag that indicates whether :math:`L` is lower triangular + or upper triangular. Default: ``False``. + + Keyword args: + out (Tensor, optional): output tensor. Ignored if `None`. Default: `None`. + + Example:: + + >>> A = torch.randn(3, 3) + >>> A = A @ A.T + torch.eye(3) * 1e-3 # Creates a symmetric positive-definite matrix + >>> L = torch.linalg.cholesky(A) # Extract Cholesky decomposition + >>> B = torch.randn(3, 2) + >>> torch.cholesky_solve(B, L) + tensor([[ -8.1625, 19.6097], + [ -5.8398, 14.2387], + [ -4.3771, 10.4173]]) + >>> A.inverse() @ B + tensor([[ -8.1626, 19.6097], + [ -5.8398, 14.2387], + [ -4.3771, 10.4173]]) + + >>> A = torch.randn(3, 2, 2, dtype=torch.complex64) + >>> A = A @ A.mH + torch.eye(2) * 1e-3 # Batch of Hermitian positive-definite matrices + >>> L = torch.linalg.cholesky(A) + >>> B = torch.randn(2, 1, dtype=torch.complex64) + >>> X = torch.cholesky_solve(B, L) + >>> torch.dist(X, A.inverse() @ B) + tensor(1.6881e-5) + """ + +def choose_qparams_optimized( + input: Tensor, + numel: _int, + n_bins: _int, + ratio: _float, + bit_width: _int, +) -> tuple[Tensor, Tensor]: ... +def chunk(input: Tensor, chunks: _int, dim: _int = 0) -> tuple[Tensor, ...]: + r""" + chunk(input: Tensor, chunks: int, dim: int = 0) -> Tuple[Tensor, ...] + + Attempts to split a tensor into the specified number of chunks. Each chunk is a view of + the input tensor. + + + .. note:: + + This function may return fewer than the specified number of chunks! + + .. seealso:: + + :func:`torch.tensor_split` a function that always returns exactly the specified number of chunks + + If the tensor size along the given dimension :attr:`dim` is divisible by :attr:`chunks`, + all returned chunks will be the same size. + If the tensor size along the given dimension :attr:`dim` is not divisible by :attr:`chunks`, + all returned chunks will be the same size, except the last one. + If such division is not possible, this function may return fewer + than the specified number of chunks. + + Arguments: + input (Tensor): the tensor to split + chunks (int): number of chunks to return + dim (int): dimension along which to split the tensor + + Example: + >>> torch.arange(11).chunk(6) + (tensor([0, 1]), + tensor([2, 3]), + tensor([4, 5]), + tensor([6, 7]), + tensor([8, 9]), + tensor([10])) + >>> torch.arange(12).chunk(6) + (tensor([0, 1]), + tensor([2, 3]), + tensor([4, 5]), + tensor([6, 7]), + tensor([8, 9]), + tensor([10, 11])) + >>> torch.arange(13).chunk(6) + (tensor([0, 1, 2]), + tensor([3, 4, 5]), + tensor([6, 7, 8]), + tensor([ 9, 10, 11]), + tensor([12])) + """ + +@overload +def clamp( + input: Tensor, + min: Tensor | None = None, + max: Tensor | None = None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + clamp(input, min=None, max=None, *, out=None) -> Tensor + + Clamps all elements in :attr:`input` into the range `[` :attr:`min`, :attr:`max` `]`. + Letting min_value and max_value be :attr:`min` and :attr:`max`, respectively, this returns: + + .. math:: + y_i = \min(\max(x_i, \text{min\_value}_i), \text{max\_value}_i) + + If :attr:`min` is ``None``, there is no lower bound. + Or, if :attr:`max` is ``None`` there is no upper bound. + + + .. note:: + If :attr:`min` is greater than :attr:`max` :func:`torch.clamp(..., min, max) ` + sets all elements in :attr:`input` to the value of :attr:`max`. + + Args: + input (Tensor): the input tensor. + min (Number or Tensor, optional): lower-bound of the range to be clamped to + max (Number or Tensor, optional): upper-bound of the range to be clamped to + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-1.7120, 0.1734, -0.0478, -0.0922]) + >>> torch.clamp(a, min=-0.5, max=0.5) + tensor([-0.5000, 0.1734, -0.0478, -0.0922]) + + >>> min = torch.linspace(-1, 1, steps=4) + >>> torch.clamp(a, min=min) + tensor([-1.0000, 0.1734, 0.3333, 1.0000]) + """ + +@overload +def clamp( + input: Tensor, + min: Number | _complex | None = None, + max: Number | _complex | None = None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + clamp(input, min=None, max=None, *, out=None) -> Tensor + + Clamps all elements in :attr:`input` into the range `[` :attr:`min`, :attr:`max` `]`. + Letting min_value and max_value be :attr:`min` and :attr:`max`, respectively, this returns: + + .. math:: + y_i = \min(\max(x_i, \text{min\_value}_i), \text{max\_value}_i) + + If :attr:`min` is ``None``, there is no lower bound. + Or, if :attr:`max` is ``None`` there is no upper bound. + + + .. note:: + If :attr:`min` is greater than :attr:`max` :func:`torch.clamp(..., min, max) ` + sets all elements in :attr:`input` to the value of :attr:`max`. + + Args: + input (Tensor): the input tensor. + min (Number or Tensor, optional): lower-bound of the range to be clamped to + max (Number or Tensor, optional): upper-bound of the range to be clamped to + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-1.7120, 0.1734, -0.0478, -0.0922]) + >>> torch.clamp(a, min=-0.5, max=0.5) + tensor([-0.5000, 0.1734, -0.0478, -0.0922]) + + >>> min = torch.linspace(-1, 1, steps=4) + >>> torch.clamp(a, min=min) + tensor([-1.0000, 0.1734, 0.3333, 1.0000]) + """ + +@overload +def clamp_( + input: Tensor, + min: Tensor | None = None, + max: Tensor | None = None, +) -> Tensor: ... +@overload +def clamp_( + input: Tensor, + min: Number | _complex | None = None, + max: Number | _complex | None = None, +) -> Tensor: ... +@overload +def clamp_max( + input: Tensor, + max: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: ... +@overload +def clamp_max( + input: Tensor, + max: Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: ... +@overload +def clamp_max_(input: Tensor, max: Tensor) -> Tensor: ... +@overload +def clamp_max_(input: Tensor, max: Number | _complex) -> Tensor: ... +@overload +def clamp_min( + input: Tensor, + min: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: ... +@overload +def clamp_min( + input: Tensor, + min: Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: ... +@overload +def clamp_min_(input: Tensor, min: Tensor) -> Tensor: ... +@overload +def clamp_min_(input: Tensor, min: Number | _complex) -> Tensor: ... +@overload +def clip( + input: Tensor, + min: Tensor | None = None, + max: Tensor | None = None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + clip(input, min=None, max=None, *, out=None) -> Tensor + + Alias for :func:`torch.clamp`. + """ + +@overload +def clip( + input: Tensor, + min: Number | _complex | None = None, + max: Number | _complex | None = None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + clip(input, min=None, max=None, *, out=None) -> Tensor + + Alias for :func:`torch.clamp`. + """ + +@overload +def clip_( + input: Tensor, + min: Tensor | None = None, + max: Tensor | None = None, +) -> Tensor: ... +@overload +def clip_( + input: Tensor, + min: Number | _complex | None = None, + max: Number | _complex | None = None, +) -> Tensor: ... +def clone( + input: Tensor, + *, + memory_format: memory_format | None = None, +) -> Tensor: + r""" + clone(input, *, memory_format=torch.preserve_format) -> Tensor + + Returns a copy of :attr:`input`. + + .. note:: + + This function is differentiable, so gradients will flow back from the + result of this operation to :attr:`input`. To create a tensor without an + autograd relationship to :attr:`input` see :meth:`~Tensor.detach`. + + In addition, when ``torch.preserve_format`` is used: + If the input tensor is dense (i.e., non-overlapping strided), + its memory format (including strides) is retained. + Otherwise (e.g., a non-dense view like a stepped slice), + the output is converted to the dense (contiguous) format. + + Args: + input (Tensor): the input tensor. + + Keyword args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned tensor. Default: ``torch.preserve_format``. + """ + +def col_indices_copy(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + Performs the same operation as :func:`torch.col_indices`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def column_stack( + tensors: tuple[Tensor, ...] | list[Tensor] | None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + column_stack(tensors, *, out=None) -> Tensor + + Creates a new tensor by horizontally stacking the tensors in :attr:`tensors`. + + Equivalent to ``torch.hstack(tensors)``, except each zero or one dimensional tensor ``t`` + in :attr:`tensors` is first reshaped into a ``(t.numel(), 1)`` column before being stacked horizontally. + + Args: + tensors (sequence of Tensors): sequence of tensors to concatenate + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([1, 2, 3]) + >>> b = torch.tensor([4, 5, 6]) + >>> torch.column_stack((a, b)) + tensor([[1, 4], + [2, 5], + [3, 6]]) + >>> a = torch.arange(5) + >>> b = torch.arange(10).reshape(5, 2) + >>> torch.column_stack((a, b, b)) + tensor([[0, 0, 1, 0, 1], + [1, 2, 3, 2, 3], + [2, 4, 5, 4, 5], + [3, 6, 7, 6, 7], + [4, 8, 9, 8, 9]]) + """ + +def combinations( + input: Tensor, + r: _int = 2, + with_replacement: _bool = False, +) -> Tensor: + r""" + combinations(input: Tensor, r: int = 2, with_replacement: bool = False) -> seq + + Compute combinations of length :math:`r` of the given tensor. The behavior is similar to + python's `itertools.combinations` when `with_replacement` is set to `False`, and + `itertools.combinations_with_replacement` when `with_replacement` is set to `True`. + + Arguments: + input (Tensor): 1D vector. + r (int, optional): number of elements to combine + with_replacement (bool, optional): whether to allow duplication in combination + + Returns: + Tensor: A tensor equivalent to converting all the input tensors into lists, do + `itertools.combinations` or `itertools.combinations_with_replacement` on these + lists, and finally convert the resulting list into tensor. + + Example:: + + >>> a = [1, 2, 3] + >>> list(itertools.combinations(a, r=2)) + [(1, 2), (1, 3), (2, 3)] + >>> list(itertools.combinations(a, r=3)) + [(1, 2, 3)] + >>> list(itertools.combinations_with_replacement(a, r=2)) + [(1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)] + >>> tensor_a = torch.tensor(a) + >>> torch.combinations(tensor_a) + tensor([[1, 2], + [1, 3], + [2, 3]]) + >>> torch.combinations(tensor_a, r=3) + tensor([[1, 2, 3]]) + >>> torch.combinations(tensor_a, with_replacement=True) + tensor([[1, 1], + [1, 2], + [1, 3], + [2, 2], + [2, 3], + [3, 3]]) + """ + +def complex( + real: Tensor, + imag: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + complex(real, imag, *, out=None) -> Tensor + + Constructs a complex tensor with its real part equal to :attr:`real` and its + imaginary part equal to :attr:`imag`. + + Args: + real (Tensor): The real part of the complex tensor. Must be half, float or double. + imag (Tensor): The imaginary part of the complex tensor. Must be same dtype + as :attr:`real`. + + Keyword args: + out (Tensor): If the inputs are ``torch.float32``, must be + ``torch.complex64``. If the inputs are ``torch.float64``, must be + ``torch.complex128``. + + Example:: + + >>> real = torch.tensor([1, 2], dtype=torch.float32) + >>> imag = torch.tensor([3, 4], dtype=torch.float32) + >>> z = torch.complex(real, imag) + >>> z + tensor([(1.+3.j), (2.+4.j)]) + >>> z.dtype + torch.complex64 + """ + +@overload +def concat( + tensors: tuple[Tensor, ...] | list[Tensor] | None, + dim: _int = 0, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + concat(tensors, dim=0, *, out=None) -> Tensor + + Alias of :func:`torch.cat`. + """ + +@overload +def concat( + tensors: tuple[Tensor, ...] | list[Tensor] | None, + dim: str | EllipsisType | None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + concat(tensors, dim=0, *, out=None) -> Tensor + + Alias of :func:`torch.cat`. + """ + +@overload +def concatenate( + tensors: tuple[Tensor, ...] | list[Tensor] | None, + dim: _int = 0, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + concatenate(tensors, axis=0, out=None) -> Tensor + + Alias of :func:`torch.cat`. + """ + +@overload +def concatenate( + tensors: tuple[Tensor, ...] | list[Tensor] | None, + dim: str | EllipsisType | None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + concatenate(tensors, axis=0, out=None) -> Tensor + + Alias of :func:`torch.cat`. + """ + +def conj(input: Tensor) -> Tensor: + r""" + conj(input) -> Tensor + + Returns a view of :attr:`input` with a flipped conjugate bit. If :attr:`input` has a non-complex dtype, + this function just returns :attr:`input`. + + .. note:: + :func:`torch.conj` performs a lazy conjugation, but the actual conjugated tensor can be materialized + at any time using :func:`torch.resolve_conj`. + + .. warning:: In the future, :func:`torch.conj` may return a non-writeable view for an :attr:`input` of + non-complex dtype. It's recommended that programs not modify the tensor returned by :func:`torch.conj_physical` + when :attr:`input` is of non-complex dtype to be compatible with this change. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> x = torch.tensor([-1 + 1j, -2 + 2j, 3 - 3j]) + >>> x.is_conj() + False + >>> y = torch.conj(x) + >>> y.is_conj() + True + """ + +def conj_physical(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + conj_physical(input, *, out=None) -> Tensor + + Computes the element-wise conjugate of the given :attr:`input` tensor. + If :attr:`input` has a non-complex dtype, this function just returns :attr:`input`. + + .. note:: + This performs the conjugate operation regardless of the fact conjugate bit is set or not. + + .. warning:: In the future, :func:`torch.conj_physical` may return a non-writeable view for an :attr:`input` of + non-complex dtype. It's recommended that programs not modify the tensor returned by :func:`torch.conj_physical` + when :attr:`input` is of non-complex dtype to be compatible with this change. + + .. math:: + \text{out}_{i} = conj(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.conj_physical(torch.tensor([-1 + 1j, -2 + 2j, 3 - 3j])) + tensor([-1 - 1j, -2 - 2j, 3 + 3j]) + """ + +def conj_physical_(input: Tensor) -> Tensor: ... +def constant_pad_nd( + input: Tensor, + pad: Sequence[_int | SymInt], + value: Number | _complex = 0, +) -> Tensor: ... +@overload +def conv1d( + input: Tensor, + weight: Tensor, + bias: Tensor | None = None, + stride: _int | SymInt | Sequence[_int | SymInt] = 1, + padding: _int | SymInt | Sequence[_int | SymInt] = 0, + dilation: _int | SymInt | Sequence[_int | SymInt] = 1, + groups: _int | SymInt = 1, +) -> Tensor: ... +@overload +def conv1d( + input: Tensor, + weight: Tensor, + bias: Tensor | None = None, + stride: _int | SymInt | Sequence[_int | SymInt] = 1, + padding: str = "valid", + dilation: _int | SymInt | Sequence[_int | SymInt] = 1, + groups: _int | SymInt = 1, +) -> Tensor: ... +@overload +def conv2d( + input: Tensor, + weight: Tensor, + bias: Tensor | None = None, + stride: _int | SymInt | Sequence[_int | SymInt] = 1, + padding: _int | SymInt | Sequence[_int | SymInt] = 0, + dilation: _int | SymInt | Sequence[_int | SymInt] = 1, + groups: _int | SymInt = 1, +) -> Tensor: ... +@overload +def conv2d( + input: Tensor, + weight: Tensor, + bias: Tensor | None = None, + stride: _int | SymInt | Sequence[_int | SymInt] = 1, + padding: str = "valid", + dilation: _int | SymInt | Sequence[_int | SymInt] = 1, + groups: _int | SymInt = 1, +) -> Tensor: ... +@overload +def conv3d( + input: Tensor, + weight: Tensor, + bias: Tensor | None = None, + stride: _int | SymInt | Sequence[_int | SymInt] = 1, + padding: _int | SymInt | Sequence[_int | SymInt] = 0, + dilation: _int | SymInt | Sequence[_int | SymInt] = 1, + groups: _int | SymInt = 1, +) -> Tensor: ... +@overload +def conv3d( + input: Tensor, + weight: Tensor, + bias: Tensor | None = None, + stride: _int | SymInt | Sequence[_int | SymInt] = 1, + padding: str = "valid", + dilation: _int | SymInt | Sequence[_int | SymInt] = 1, + groups: _int | SymInt = 1, +) -> Tensor: ... +def conv_tbc( + input: Tensor, + weight: Tensor, + bias: Tensor, + pad: _int = 0, +) -> Tensor: ... +def conv_transpose1d( + input: Tensor, + weight: Tensor, + bias: Tensor | None = None, + stride: _int | SymInt | Sequence[_int | SymInt] = 1, + padding: _int | SymInt | Sequence[_int | SymInt] = 0, + output_padding: _int | SymInt | Sequence[_int | SymInt] = 0, + groups: _int | SymInt = 1, + dilation: _int | SymInt | Sequence[_int | SymInt] = 1, +) -> Tensor: ... +def conv_transpose2d( + input: Tensor, + weight: Tensor, + bias: Tensor | None = None, + stride: _int | SymInt | Sequence[_int | SymInt] = 1, + padding: _int | SymInt | Sequence[_int | SymInt] = 0, + output_padding: _int | SymInt | Sequence[_int | SymInt] = 0, + groups: _int | SymInt = 1, + dilation: _int | SymInt | Sequence[_int | SymInt] = 1, +) -> Tensor: ... +def conv_transpose3d( + input: Tensor, + weight: Tensor, + bias: Tensor | None = None, + stride: _int | SymInt | Sequence[_int | SymInt] = 1, + padding: _int | SymInt | Sequence[_int | SymInt] = 0, + output_padding: _int | SymInt | Sequence[_int | SymInt] = 0, + groups: _int | SymInt = 1, + dilation: _int | SymInt | Sequence[_int | SymInt] = 1, +) -> Tensor: ... +def convolution( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + stride: Sequence[_int | SymInt], + padding: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + transposed: _bool, + output_padding: Sequence[_int | SymInt], + groups: _int | SymInt, +) -> Tensor: ... +@overload +def copysign( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + copysign(input, other, *, out=None) -> Tensor + + Create a new floating-point tensor with the magnitude of :attr:`input` and the sign of :attr:`other`, elementwise. + + .. math:: + \text{out}_{i} = \begin{cases} + -|\text{input}_{i}| & \text{if } \text{other}_{i} \leq -0.0 \\ + |\text{input}_{i}| & \text{if } \text{other}_{i} \geq 0.0 \\ + \end{cases} + + + Supports :ref:`broadcasting to a common shape `, + and integer and float inputs. + + Args: + input (Tensor): magnitudes. + other (Tensor or Number): contains value(s) whose signbit(s) are + applied to the magnitudes in :attr:`input`. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(5) + >>> a + tensor([-1.2557, -0.0026, -0.5387, 0.4740, -0.9244]) + >>> torch.copysign(a, 1) + tensor([1.2557, 0.0026, 0.5387, 0.4740, 0.9244]) + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.7079, 0.2778, -1.0249, 0.5719], + [-0.0059, -0.2600, -0.4475, -1.3948], + [ 0.3667, -0.9567, -2.5757, -0.1751], + [ 0.2046, -0.0742, 0.2998, -0.1054]]) + >>> b = torch.randn(4) + tensor([ 0.2373, 0.3120, 0.3190, -1.1128]) + >>> torch.copysign(a, b) + tensor([[ 0.7079, 0.2778, 1.0249, -0.5719], + [ 0.0059, 0.2600, 0.4475, -1.3948], + [ 0.3667, 0.9567, 2.5757, -0.1751], + [ 0.2046, 0.0742, 0.2998, -0.1054]]) + >>> a = torch.tensor([1.]) + >>> b = torch.tensor([-0.]) + >>> torch.copysign(a, b) + tensor([-1.]) + + .. note:: + copysign handles signed zeros. If the other argument has a negative zero (-0), + the corresponding output value will be negative. + """ + +@overload +def copysign( + input: Tensor, + other: Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + copysign(input, other, *, out=None) -> Tensor + + Create a new floating-point tensor with the magnitude of :attr:`input` and the sign of :attr:`other`, elementwise. + + .. math:: + \text{out}_{i} = \begin{cases} + -|\text{input}_{i}| & \text{if } \text{other}_{i} \leq -0.0 \\ + |\text{input}_{i}| & \text{if } \text{other}_{i} \geq 0.0 \\ + \end{cases} + + + Supports :ref:`broadcasting to a common shape `, + and integer and float inputs. + + Args: + input (Tensor): magnitudes. + other (Tensor or Number): contains value(s) whose signbit(s) are + applied to the magnitudes in :attr:`input`. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(5) + >>> a + tensor([-1.2557, -0.0026, -0.5387, 0.4740, -0.9244]) + >>> torch.copysign(a, 1) + tensor([1.2557, 0.0026, 0.5387, 0.4740, 0.9244]) + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.7079, 0.2778, -1.0249, 0.5719], + [-0.0059, -0.2600, -0.4475, -1.3948], + [ 0.3667, -0.9567, -2.5757, -0.1751], + [ 0.2046, -0.0742, 0.2998, -0.1054]]) + >>> b = torch.randn(4) + tensor([ 0.2373, 0.3120, 0.3190, -1.1128]) + >>> torch.copysign(a, b) + tensor([[ 0.7079, 0.2778, 1.0249, -0.5719], + [ 0.0059, 0.2600, 0.4475, -1.3948], + [ 0.3667, 0.9567, 2.5757, -0.1751], + [ 0.2046, 0.0742, 0.2998, -0.1054]]) + >>> a = torch.tensor([1.]) + >>> b = torch.tensor([-0.]) + >>> torch.copysign(a, b) + tensor([-1.]) + + .. note:: + copysign handles signed zeros. If the other argument has a negative zero (-0), + the corresponding output value will be negative. + """ + +def corrcoef(input: Tensor) -> Tensor: + r""" + corrcoef(input) -> Tensor + + Estimates the Pearson product-moment correlation coefficient matrix of the variables given by the :attr:`input` matrix, + where rows are the variables and columns are the observations. + + .. note:: + + The correlation coefficient matrix R is computed using the covariance matrix C as given by + :math:`R_{ij} = \frac{ C_{ij} } { \sqrt{ C_{ii} * C_{jj} } }` + + .. note:: + + Due to floating point rounding, the resulting array may not be Hermitian and its diagonal elements may not be 1. + The real and imaginary values are clipped to the interval [-1, 1] in an attempt to improve this situation. + + Args: + input (Tensor): A 2D matrix containing multiple variables and observations, or a + Scalar or 1D vector representing a single variable. + + Returns: + (Tensor) The correlation coefficient matrix of the variables. + + .. seealso:: + + :func:`torch.cov` covariance matrix. + + Example:: + + >>> x = torch.tensor([[0, 1, 2], [2, 1, 0]]) + >>> torch.corrcoef(x) + tensor([[ 1., -1.], + [-1., 1.]]) + >>> x = torch.randn(2, 4) + >>> x + tensor([[-0.2678, -0.0908, -0.3766, 0.2780], + [-0.5812, 0.1535, 0.2387, 0.2350]]) + >>> torch.corrcoef(x) + tensor([[1.0000, 0.3582], + [0.3582, 1.0000]]) + >>> torch.corrcoef(x[0]) + tensor(1.) + """ + +def cos(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + cos(input, *, out=None) -> Tensor + + Returns a new tensor with the cosine of the elements of :attr:`input` given in radians. + + .. math:: + \text{out}_{i} = \cos(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 1.4309, 1.2706, -0.8562, 0.9796]) + >>> torch.cos(a) + tensor([ 0.1395, 0.2957, 0.6553, 0.5574]) + """ + +def cos_(input: Tensor) -> Tensor: ... +def cosh(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + cosh(input, *, out=None) -> Tensor + + Returns a new tensor with the hyperbolic cosine of the elements of + :attr:`input`. + + .. math:: + \text{out}_{i} = \cosh(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.1632, 1.1835, -0.6979, -0.7325]) + >>> torch.cosh(a) + tensor([ 1.0133, 1.7860, 1.2536, 1.2805]) + + .. note:: + When :attr:`input` is on the CPU, the implementation of torch.cosh may use + the Sleef library, which rounds very large results to infinity or negative + infinity. See `here `_ for details. + """ + +def cosh_(input: Tensor) -> Tensor: ... +def cosine_embedding_loss( + input1: Tensor, + input2: Tensor, + target: Tensor, + margin: _float = 0.0, + reduction: _int = 1, +) -> Tensor: ... +def cosine_similarity( + x1: Tensor, + x2: Tensor, + dim: _int = 1, + eps: _float = 1e-08, +) -> Tensor: ... +@overload +def count_nonzero(input: Tensor, dim: _int | None = None) -> Tensor: + r""" + count_nonzero(input, dim=None) -> Tensor + + Counts the number of non-zero values in the tensor :attr:`input` along the given :attr:`dim`. + If no dim is specified then all non-zeros in the tensor are counted. + + Args: + input (Tensor): the input tensor. + dim (int or tuple of ints, optional): Dim or tuple of dims along which to count non-zeros. + + Example:: + + >>> x = torch.zeros(3,3) + >>> x[torch.randn(3,3) > 0.5] = 1 + >>> x + tensor([[0., 1., 1.], + [0., 0., 0.], + [0., 0., 1.]]) + >>> torch.count_nonzero(x) + tensor(3) + >>> torch.count_nonzero(x, dim=0) + tensor([0, 1, 2]) + """ + +@overload +def count_nonzero(input: Tensor, dim: _size) -> Tensor: + r""" + count_nonzero(input, dim=None) -> Tensor + + Counts the number of non-zero values in the tensor :attr:`input` along the given :attr:`dim`. + If no dim is specified then all non-zeros in the tensor are counted. + + Args: + input (Tensor): the input tensor. + dim (int or tuple of ints, optional): Dim or tuple of dims along which to count non-zeros. + + Example:: + + >>> x = torch.zeros(3,3) + >>> x[torch.randn(3,3) > 0.5] = 1 + >>> x + tensor([[0., 1., 1.], + [0., 0., 0.], + [0., 0., 1.]]) + >>> torch.count_nonzero(x) + tensor(3) + >>> torch.count_nonzero(x, dim=0) + tensor([0, 1, 2]) + """ + +def cov( + input: Tensor, + *, + correction: _int = 1, + fweights: Tensor | None = None, + aweights: Tensor | None = None, +) -> Tensor: + r""" + cov(input, *, correction=1, fweights=None, aweights=None) -> Tensor + + Estimates the covariance matrix of the variables given by the :attr:`input` matrix, where rows are + the variables and columns are the observations. + + A covariance matrix is a square matrix giving the covariance of each pair of variables. The diagonal contains + the variance of each variable (covariance of a variable with itself). By definition, if :attr:`input` represents + a single variable (Scalar or 1D) then its variance is returned. + + The sample covariance of the variables :math:`x` and :math:`y` is given by: + + .. math:: + \text{cov}(x,y) = \frac{\sum^{N}_{i = 1}(x_{i} - \bar{x})(y_{i} - \bar{y})}{\max(0,~N~-~\delta N)} + + where :math:`\bar{x}` and :math:`\bar{y}` are the simple means of the :math:`x` and :math:`y` respectively, and + :math:`\delta N` is the :attr:`correction`. + + If :attr:`fweights` and/or :attr:`aweights` are provided, the weighted covariance + is calculated, which is given by: + + .. math:: + \text{cov}_w(x,y) = \frac{\sum^{N}_{i = 1}w_i(x_{i} - \mu_x^*)(y_{i} - \mu_y^*)} + {\max(0,~\sum^{N}_{i = 1}w_i~-~\frac{\sum^{N}_{i = 1}w_ia_i}{\sum^{N}_{i = 1}w_i}~\delta N)} + + where :math:`w` denotes :attr:`fweights` or :attr:`aweights` (``f`` and ``a`` for brevity) based on whichever is + provided, or :math:`w = f \times a` if both are provided, and + :math:`\mu_x^* = \frac{\sum^{N}_{i = 1}w_ix_{i} }{\sum^{N}_{i = 1}w_i}` is the weighted mean of the variable. If not + provided, ``f`` and/or ``a`` can be seen as a :math:`\mathbb{1}` vector of appropriate size. + + Args: + input (Tensor): A 2D matrix containing multiple variables and observations, or a + Scalar or 1D vector representing a single variable. + + Keyword Args: + correction (int, optional): difference between the sample size and sample degrees of freedom. + Defaults to Bessel's correction, ``correction = 1`` which returns the unbiased estimate, + even if both :attr:`fweights` and :attr:`aweights` are specified. ``correction = 0`` + will return the simple average. Defaults to ``1``. + fweights (tensor, optional): A Scalar or 1D tensor of observation vector frequencies representing the number of + times each observation should be repeated. Its numel must equal the number of columns of :attr:`input`. + Must have integral dtype. Ignored if ``None``. Defaults to ``None``. + aweights (tensor, optional): A Scalar or 1D array of observation vector weights. + These relative weights are typically large for observations considered "important" and smaller for + observations considered less "important". Its numel must equal the number of columns of :attr:`input`. + Must have floating point dtype. Ignored if ``None``. Defaults to ``None``. + + Returns: + (Tensor) The covariance matrix of the variables. + + .. seealso:: + + :func:`torch.corrcoef` normalized covariance matrix. + + Example:: + + >>> x = torch.tensor([[0, 2], [1, 1], [2, 0]]).T + >>> x + tensor([[0, 1, 2], + [2, 1, 0]]) + >>> torch.cov(x) + tensor([[ 1., -1.], + [-1., 1.]]) + >>> torch.cov(x, correction=0) + tensor([[ 0.6667, -0.6667], + [-0.6667, 0.6667]]) + >>> fw = torch.randint(1, 10, (3,)) + >>> fw + tensor([1, 6, 9]) + >>> aw = torch.rand(3) + >>> aw + tensor([0.4282, 0.0255, 0.4144]) + >>> torch.cov(x, fweights=fw, aweights=aw) + tensor([[ 0.4169, -0.4169], + [-0.4169, 0.4169]]) + """ + +def cross( + input: Tensor, + other: Tensor, + dim: _int | None = None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + cross(input, other, dim=None, *, out=None) -> Tensor + + + Returns the cross product of vectors in dimension :attr:`dim` of :attr:`input` + and :attr:`other`. + + Supports input of float, double, cfloat and cdouble dtypes. Also supports batches + of vectors, for which it computes the product along the dimension :attr:`dim`. + In this case, the output has the same batch dimensions as the inputs. + + .. warning:: + If :attr:`dim` is not given, it defaults to the first dimension found + with the size 3. Note that this might be unexpected. + + This behavior is deprecated and will be changed to match that of :func:`torch.linalg.cross` + in a future release. + + .. seealso:: + :func:`torch.linalg.cross` which has dim=-1 as default. + + + Args: + input (Tensor): the input tensor. + other (Tensor): the second input tensor + dim (int, optional): the dimension to take the cross-product in. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4, 3) + >>> a + tensor([[-0.3956, 1.1455, 1.6895], + [-0.5849, 1.3672, 0.3599], + [-1.1626, 0.7180, -0.0521], + [-0.1339, 0.9902, -2.0225]]) + >>> b = torch.randn(4, 3) + >>> b + tensor([[-0.0257, -1.4725, -1.2251], + [-1.1479, -0.7005, -1.9757], + [-1.3904, 0.3726, -1.1836], + [-0.9688, -0.7153, 0.2159]]) + >>> torch.cross(a, b, dim=1) + tensor([[ 1.0844, -0.5281, 0.6120], + [-2.4490, -1.5687, 1.9792], + [-0.8304, -1.3037, 0.5650], + [-1.2329, 1.9883, 1.0551]]) + >>> torch.cross(a, b) + tensor([[ 1.0844, -0.5281, 0.6120], + [-2.4490, -1.5687, 1.9792], + [-0.8304, -1.3037, 0.5650], + [-1.2329, 1.9883, 1.0551]]) + """ + +def crow_indices_copy( + input: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.crow_indices`, but all output tensors + are freshly created instead of aliasing the input. + """ + +@overload +def ctc_loss( + log_probs: Tensor, + targets: Tensor, + input_lengths: _size, + target_lengths: _size, + blank: _int = 0, + reduction: _int = 1, + zero_infinity: _bool = False, +) -> Tensor: ... +@overload +def ctc_loss( + log_probs: Tensor, + targets: Tensor, + input_lengths: Tensor, + target_lengths: Tensor, + blank: _int = 0, + reduction: _int = 1, + zero_infinity: _bool = False, +) -> Tensor: ... +def cudnn_affine_grid_generator( + theta: Tensor, + N: _int, + C: _int, + H: _int, + W: _int, +) -> Tensor: ... +def cudnn_batch_norm( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + running_mean: Tensor | None, + running_var: Tensor | None, + training: _bool, + exponential_average_factor: _float, + epsilon: _float, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> tuple[Tensor, Tensor, Tensor, Tensor]: ... +def cudnn_convolution( + input: Tensor, + weight: Tensor, + padding: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + groups: _int | SymInt, + benchmark: _bool, + deterministic: _bool, + allow_tf32: _bool, + *, + out: Tensor | None = None, +) -> Tensor: ... +def cudnn_convolution_add_relu( + input: Tensor, + weight: Tensor, + z: Tensor, + alpha: Number | _complex | None, + bias: Tensor | None, + stride: Sequence[_int | SymInt], + padding: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + groups: _int | SymInt, +) -> Tensor: ... +def cudnn_convolution_relu( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + stride: Sequence[_int | SymInt], + padding: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + groups: _int | SymInt, +) -> Tensor: ... +def cudnn_convolution_transpose( + input: Tensor, + weight: Tensor, + padding: Sequence[_int | SymInt], + output_padding: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + groups: _int | SymInt, + benchmark: _bool, + deterministic: _bool, + allow_tf32: _bool, +) -> Tensor: ... +def cudnn_grid_sampler(input: Tensor, grid: Tensor) -> Tensor: ... +def cudnn_is_acceptable(input: Tensor) -> _bool: ... +@overload +def cummax( + input: Tensor, + dim: _int, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.cummax: + r""" + cummax(input, dim, *, out=None) -> (Tensor, LongTensor) + Returns a namedtuple ``(values, indices)`` where ``values`` is the cumulative maximum of + elements of :attr:`input` in the dimension :attr:`dim`. And ``indices`` is the index + location of each maximum value found in the dimension :attr:`dim`. + + .. math:: + y_i = max(x_1, x_2, x_3, \dots, x_i) + + Args: + input (Tensor): the input tensor. + dim (int): the dimension to do the operation over + + Keyword args: + out (tuple, optional): the result tuple of two output tensors (values, indices) + + Example:: + + >>> a = torch.randn(10) + >>> a + tensor([-0.3449, -1.5447, 0.0685, -1.5104, -1.1706, 0.2259, 1.4696, -1.3284, + 1.9946, -0.8209]) + >>> torch.cummax(a, dim=0) + torch.return_types.cummax( + values=tensor([-0.3449, -0.3449, 0.0685, 0.0685, 0.0685, 0.2259, 1.4696, 1.4696, + 1.9946, 1.9946]), + indices=tensor([0, 0, 2, 2, 2, 5, 6, 6, 8, 8])) + """ + +@overload +def cummax( + input: Tensor, + dim: str | EllipsisType | None, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.cummax: + r""" + cummax(input, dim, *, out=None) -> (Tensor, LongTensor) + Returns a namedtuple ``(values, indices)`` where ``values`` is the cumulative maximum of + elements of :attr:`input` in the dimension :attr:`dim`. And ``indices`` is the index + location of each maximum value found in the dimension :attr:`dim`. + + .. math:: + y_i = max(x_1, x_2, x_3, \dots, x_i) + + Args: + input (Tensor): the input tensor. + dim (int): the dimension to do the operation over + + Keyword args: + out (tuple, optional): the result tuple of two output tensors (values, indices) + + Example:: + + >>> a = torch.randn(10) + >>> a + tensor([-0.3449, -1.5447, 0.0685, -1.5104, -1.1706, 0.2259, 1.4696, -1.3284, + 1.9946, -0.8209]) + >>> torch.cummax(a, dim=0) + torch.return_types.cummax( + values=tensor([-0.3449, -0.3449, 0.0685, 0.0685, 0.0685, 0.2259, 1.4696, 1.4696, + 1.9946, 1.9946]), + indices=tensor([0, 0, 2, 2, 2, 5, 6, 6, 8, 8])) + """ + +@overload +def cummin( + input: Tensor, + dim: _int, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.cummin: + r""" + cummin(input, dim, *, out=None) -> (Tensor, LongTensor) + Returns a namedtuple ``(values, indices)`` where ``values`` is the cumulative minimum of + elements of :attr:`input` in the dimension :attr:`dim`. And ``indices`` is the index + location of each maximum value found in the dimension :attr:`dim`. + + .. math:: + y_i = min(x_1, x_2, x_3, \dots, x_i) + + Args: + input (Tensor): the input tensor. + dim (int): the dimension to do the operation over + + Keyword args: + out (tuple, optional): the result tuple of two output tensors (values, indices) + + Example:: + + >>> a = torch.randn(10) + >>> a + tensor([-0.2284, -0.6628, 0.0975, 0.2680, -1.3298, -0.4220, -0.3885, 1.1762, + 0.9165, 1.6684]) + >>> torch.cummin(a, dim=0) + torch.return_types.cummin( + values=tensor([-0.2284, -0.6628, -0.6628, -0.6628, -1.3298, -1.3298, -1.3298, -1.3298, + -1.3298, -1.3298]), + indices=tensor([0, 1, 1, 1, 4, 4, 4, 4, 4, 4])) + """ + +@overload +def cummin( + input: Tensor, + dim: str | EllipsisType | None, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.cummin: + r""" + cummin(input, dim, *, out=None) -> (Tensor, LongTensor) + Returns a namedtuple ``(values, indices)`` where ``values`` is the cumulative minimum of + elements of :attr:`input` in the dimension :attr:`dim`. And ``indices`` is the index + location of each maximum value found in the dimension :attr:`dim`. + + .. math:: + y_i = min(x_1, x_2, x_3, \dots, x_i) + + Args: + input (Tensor): the input tensor. + dim (int): the dimension to do the operation over + + Keyword args: + out (tuple, optional): the result tuple of two output tensors (values, indices) + + Example:: + + >>> a = torch.randn(10) + >>> a + tensor([-0.2284, -0.6628, 0.0975, 0.2680, -1.3298, -0.4220, -0.3885, 1.1762, + 0.9165, 1.6684]) + >>> torch.cummin(a, dim=0) + torch.return_types.cummin( + values=tensor([-0.2284, -0.6628, -0.6628, -0.6628, -1.3298, -1.3298, -1.3298, -1.3298, + -1.3298, -1.3298]), + indices=tensor([0, 1, 1, 1, 4, 4, 4, 4, 4, 4])) + """ + +@overload +def cumprod( + input: Tensor, + dim: _int, + *, + dtype: _dtype | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + cumprod(input, dim, *, dtype=None, out=None) -> Tensor + + Returns the cumulative product of elements of :attr:`input` in the dimension + :attr:`dim`. + + For example, if :attr:`input` is a vector of size N, the result will also be + a vector of size N, with elements. + + .. math:: + y_i = x_1 \times x_2\times x_3\times \dots \times x_i + + Args: + input (Tensor): the input tensor. + dim (int): the dimension to do the operation over + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(10) + >>> a + tensor([ 0.6001, 0.2069, -0.1919, 0.9792, 0.6727, 1.0062, 0.4126, + -0.2129, -0.4206, 0.1968]) + >>> torch.cumprod(a, dim=0) + tensor([ 0.6001, 0.1241, -0.0238, -0.0233, -0.0157, -0.0158, -0.0065, + 0.0014, -0.0006, -0.0001]) + + >>> a[5] = 0.0 + >>> torch.cumprod(a, dim=0) + tensor([ 0.6001, 0.1241, -0.0238, -0.0233, -0.0157, -0.0000, -0.0000, + 0.0000, -0.0000, -0.0000]) + """ + +@overload +def cumprod( + input: Tensor, + dim: str | EllipsisType | None, + *, + dtype: _dtype | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + cumprod(input, dim, *, dtype=None, out=None) -> Tensor + + Returns the cumulative product of elements of :attr:`input` in the dimension + :attr:`dim`. + + For example, if :attr:`input` is a vector of size N, the result will also be + a vector of size N, with elements. + + .. math:: + y_i = x_1 \times x_2\times x_3\times \dots \times x_i + + Args: + input (Tensor): the input tensor. + dim (int): the dimension to do the operation over + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(10) + >>> a + tensor([ 0.6001, 0.2069, -0.1919, 0.9792, 0.6727, 1.0062, 0.4126, + -0.2129, -0.4206, 0.1968]) + >>> torch.cumprod(a, dim=0) + tensor([ 0.6001, 0.1241, -0.0238, -0.0233, -0.0157, -0.0158, -0.0065, + 0.0014, -0.0006, -0.0001]) + + >>> a[5] = 0.0 + >>> torch.cumprod(a, dim=0) + tensor([ 0.6001, 0.1241, -0.0238, -0.0233, -0.0157, -0.0000, -0.0000, + 0.0000, -0.0000, -0.0000]) + """ + +@overload +def cumsum( + input: Tensor, + dim: _int, + *, + dtype: _dtype | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + cumsum(input, dim, *, dtype=None, out=None) -> Tensor + + Returns the cumulative sum of elements of :attr:`input` in the dimension + :attr:`dim`. + + For example, if :attr:`input` is a vector of size N, the result will also be + a vector of size N, with elements. + + .. math:: + y_i = x_1 + x_2 + x_3 + \dots + x_i + + Args: + input (Tensor): the input tensor. + dim (int): the dimension to do the operation over + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randint(1, 20, (10,)) + >>> a + tensor([13, 7, 3, 10, 13, 3, 15, 10, 9, 10]) + >>> torch.cumsum(a, dim=0) + tensor([13, 20, 23, 33, 46, 49, 64, 74, 83, 93]) + """ + +@overload +def cumsum( + input: Tensor, + dim: str | EllipsisType | None, + *, + dtype: _dtype | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + cumsum(input, dim, *, dtype=None, out=None) -> Tensor + + Returns the cumulative sum of elements of :attr:`input` in the dimension + :attr:`dim`. + + For example, if :attr:`input` is a vector of size N, the result will also be + a vector of size N, with elements. + + .. math:: + y_i = x_1 + x_2 + x_3 + \dots + x_i + + Args: + input (Tensor): the input tensor. + dim (int): the dimension to do the operation over + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randint(1, 20, (10,)) + >>> a + tensor([13, 7, 3, 10, 13, 3, 15, 10, 9, 10]) + >>> torch.cumsum(a, dim=0) + tensor([13, 20, 23, 33, 46, 49, 64, 74, 83, 93]) + """ + +@overload +def cumulative_trapezoid(y: Tensor, x: Tensor, *, dim: _int = -1) -> Tensor: + r""" + cumulative_trapezoid(y, x=None, *, dx=None, dim=-1) -> Tensor + + Cumulatively computes the `trapezoidal rule `_ + along :attr:`dim`. By default the spacing between elements is assumed to be 1, but + :attr:`dx` can be used to specify a different constant spacing, and :attr:`x` can be + used to specify arbitrary spacing along :attr:`dim`. + + For more details, please read :func:`torch.trapezoid`. The difference between :func:`torch.trapezoid` + and this function is that, :func:`torch.trapezoid` returns a value for each integration, + where as this function returns a cumulative value for every spacing within the integration. This + is analogous to how `.sum` returns a value and `.cumsum` returns a cumulative sum. + + Arguments: + y (Tensor): Values to use when computing the trapezoidal rule. + x (Tensor): If specified, defines spacing between values as specified above. + + Keyword arguments: + dx (float): constant spacing between values. If neither :attr:`x` or :attr:`dx` + are specified then this defaults to 1. Effectively multiplies the result by its value. + dim (int): The dimension along which to compute the trapezoidal rule. + The last (inner-most) dimension by default. + + Examples:: + + >>> # Cumulatively computes the trapezoidal rule in 1D, spacing is implicitly 1. + >>> y = torch.tensor([1, 5, 10]) + >>> torch.cumulative_trapezoid(y) + tensor([3., 10.5]) + + >>> # Computes the same trapezoidal rule directly up to each element to verify + >>> (1 + 5) / 2 + 3.0 + >>> (1 + 10 + 10) / 2 + 10.5 + + >>> # Cumulatively computes the trapezoidal rule in 1D with constant spacing of 2 + >>> # NOTE: the result is the same as before, but multiplied by 2 + >>> torch.cumulative_trapezoid(y, dx=2) + tensor([6., 21.]) + + >>> # Cumulatively computes the trapezoidal rule in 1D with arbitrary spacing + >>> x = torch.tensor([1, 3, 6]) + >>> torch.cumulative_trapezoid(y, x) + tensor([6., 28.5]) + + >>> # Computes the same trapezoidal rule directly up to each element to verify + >>> ((3 - 1) * (1 + 5)) / 2 + 6.0 + >>> ((3 - 1) * (1 + 5) + (6 - 3) * (5 + 10)) / 2 + 28.5 + + >>> # Cumulatively computes the trapezoidal rule for each row of a 3x3 matrix + >>> y = torch.arange(9).reshape(3, 3) + tensor([[0, 1, 2], + [3, 4, 5], + [6, 7, 8]]) + >>> torch.cumulative_trapezoid(y) + tensor([[ 0.5, 2.], + [ 3.5, 8.], + [ 6.5, 14.]]) + + >>> # Cumulatively computes the trapezoidal rule for each column of the matrix + >>> torch.cumulative_trapezoid(y, dim=0) + tensor([[ 1.5, 2.5, 3.5], + [ 6.0, 8.0, 10.0]]) + + >>> # Cumulatively computes the trapezoidal rule for each row of a 3x3 ones matrix + >>> # with the same arbitrary spacing + >>> y = torch.ones(3, 3) + >>> x = torch.tensor([1, 3, 6]) + >>> torch.cumulative_trapezoid(y, x) + tensor([[2., 5.], + [2., 5.], + [2., 5.]]) + + >>> # Cumulatively computes the trapezoidal rule for each row of a 3x3 ones matrix + >>> # with different arbitrary spacing per row + >>> y = torch.ones(3, 3) + >>> x = torch.tensor([[1, 2, 3], [1, 3, 5], [1, 4, 7]]) + >>> torch.cumulative_trapezoid(y, x) + tensor([[1., 2.], + [2., 4.], + [3., 6.]]) + """ + +@overload +def cumulative_trapezoid( + y: Tensor, + *, + dx: Number | _complex = 1, + dim: _int = -1, +) -> Tensor: + r""" + cumulative_trapezoid(y, x=None, *, dx=None, dim=-1) -> Tensor + + Cumulatively computes the `trapezoidal rule `_ + along :attr:`dim`. By default the spacing between elements is assumed to be 1, but + :attr:`dx` can be used to specify a different constant spacing, and :attr:`x` can be + used to specify arbitrary spacing along :attr:`dim`. + + For more details, please read :func:`torch.trapezoid`. The difference between :func:`torch.trapezoid` + and this function is that, :func:`torch.trapezoid` returns a value for each integration, + where as this function returns a cumulative value for every spacing within the integration. This + is analogous to how `.sum` returns a value and `.cumsum` returns a cumulative sum. + + Arguments: + y (Tensor): Values to use when computing the trapezoidal rule. + x (Tensor): If specified, defines spacing between values as specified above. + + Keyword arguments: + dx (float): constant spacing between values. If neither :attr:`x` or :attr:`dx` + are specified then this defaults to 1. Effectively multiplies the result by its value. + dim (int): The dimension along which to compute the trapezoidal rule. + The last (inner-most) dimension by default. + + Examples:: + + >>> # Cumulatively computes the trapezoidal rule in 1D, spacing is implicitly 1. + >>> y = torch.tensor([1, 5, 10]) + >>> torch.cumulative_trapezoid(y) + tensor([3., 10.5]) + + >>> # Computes the same trapezoidal rule directly up to each element to verify + >>> (1 + 5) / 2 + 3.0 + >>> (1 + 10 + 10) / 2 + 10.5 + + >>> # Cumulatively computes the trapezoidal rule in 1D with constant spacing of 2 + >>> # NOTE: the result is the same as before, but multiplied by 2 + >>> torch.cumulative_trapezoid(y, dx=2) + tensor([6., 21.]) + + >>> # Cumulatively computes the trapezoidal rule in 1D with arbitrary spacing + >>> x = torch.tensor([1, 3, 6]) + >>> torch.cumulative_trapezoid(y, x) + tensor([6., 28.5]) + + >>> # Computes the same trapezoidal rule directly up to each element to verify + >>> ((3 - 1) * (1 + 5)) / 2 + 6.0 + >>> ((3 - 1) * (1 + 5) + (6 - 3) * (5 + 10)) / 2 + 28.5 + + >>> # Cumulatively computes the trapezoidal rule for each row of a 3x3 matrix + >>> y = torch.arange(9).reshape(3, 3) + tensor([[0, 1, 2], + [3, 4, 5], + [6, 7, 8]]) + >>> torch.cumulative_trapezoid(y) + tensor([[ 0.5, 2.], + [ 3.5, 8.], + [ 6.5, 14.]]) + + >>> # Cumulatively computes the trapezoidal rule for each column of the matrix + >>> torch.cumulative_trapezoid(y, dim=0) + tensor([[ 1.5, 2.5, 3.5], + [ 6.0, 8.0, 10.0]]) + + >>> # Cumulatively computes the trapezoidal rule for each row of a 3x3 ones matrix + >>> # with the same arbitrary spacing + >>> y = torch.ones(3, 3) + >>> x = torch.tensor([1, 3, 6]) + >>> torch.cumulative_trapezoid(y, x) + tensor([[2., 5.], + [2., 5.], + [2., 5.]]) + + >>> # Cumulatively computes the trapezoidal rule for each row of a 3x3 ones matrix + >>> # with different arbitrary spacing per row + >>> y = torch.ones(3, 3) + >>> x = torch.tensor([[1, 2, 3], [1, 3, 5], [1, 4, 7]]) + >>> torch.cumulative_trapezoid(y, x) + tensor([[1., 2.], + [2., 4.], + [3., 6.]]) + """ + +def deg2rad(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + deg2rad(input, *, out=None) -> Tensor + + Returns a new tensor with each of the elements of :attr:`input` + converted from angles in degrees to radians. + + Args: + input (Tensor): the input tensor. + + Keyword arguments: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([[180.0, -180.0], [360.0, -360.0], [90.0, -90.0]]) + >>> torch.deg2rad(a) + tensor([[ 3.1416, -3.1416], + [ 6.2832, -6.2832], + [ 1.5708, -1.5708]]) + """ + +def deg2rad_(input: Tensor) -> Tensor: ... +@overload +def dequantize(input: Tensor) -> Tensor: + r""" + dequantize(tensor) -> Tensor + + Returns an fp32 Tensor by dequantizing a quantized Tensor + + Args: + tensor (Tensor): A quantized Tensor + + .. function:: dequantize(tensors) -> sequence of Tensors + :noindex: + + Given a list of quantized Tensors, dequantize them and return a list of fp32 Tensors + + Args: + tensors (sequence of Tensors): A list of quantized Tensors + """ + +@overload +def dequantize( + tensors: tuple[Tensor, ...] | list[Tensor] | None, +) -> tuple[Tensor, ...]: + r""" + dequantize(tensor) -> Tensor + + Returns an fp32 Tensor by dequantizing a quantized Tensor + + Args: + tensor (Tensor): A quantized Tensor + + .. function:: dequantize(tensors) -> sequence of Tensors + :noindex: + + Given a list of quantized Tensors, dequantize them and return a list of fp32 Tensors + + Args: + tensors (sequence of Tensors): A list of quantized Tensors + """ + +def det(input: Tensor) -> Tensor: + r""" + det(input) -> Tensor + + Alias for :func:`torch.linalg.det` + """ + +def detach(input: Tensor) -> Tensor: ... +def detach_(input: Tensor) -> Tensor: ... +def detach_copy(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + Performs the same operation as :func:`torch.detach`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def diag( + input: Tensor, + diagonal: _int = 0, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + diag(input, diagonal=0, *, out=None) -> Tensor + + - If :attr:`input` is a vector (1-D tensor), then returns a 2-D square tensor + with the elements of :attr:`input` as the diagonal. + - If :attr:`input` is a matrix (2-D tensor), then returns a 1-D tensor with + the diagonal elements of :attr:`input`. + + The argument :attr:`diagonal` controls which diagonal to consider: + + - If :attr:`diagonal` = 0, it is the main diagonal. + - If :attr:`diagonal` > 0, it is above the main diagonal. + - If :attr:`diagonal` < 0, it is below the main diagonal. + + Args: + input (Tensor): the input tensor. + diagonal (int, optional): the diagonal to consider + + Keyword args: + out (Tensor, optional): the output tensor. + + .. seealso:: + + :func:`torch.diagonal` always returns the diagonal of its input. + + :func:`torch.diagflat` always constructs a tensor with diagonal elements + specified by the input. + + Examples: + + Get the square matrix where the input vector is the diagonal:: + + >>> a = torch.randn(3) + >>> a + tensor([ 0.5950,-0.0872, 2.3298]) + >>> torch.diag(a) + tensor([[ 0.5950, 0.0000, 0.0000], + [ 0.0000,-0.0872, 0.0000], + [ 0.0000, 0.0000, 2.3298]]) + >>> torch.diag(a, 1) + tensor([[ 0.0000, 0.5950, 0.0000, 0.0000], + [ 0.0000, 0.0000,-0.0872, 0.0000], + [ 0.0000, 0.0000, 0.0000, 2.3298], + [ 0.0000, 0.0000, 0.0000, 0.0000]]) + + Get the k-th diagonal of a given matrix:: + + >>> a = torch.randn(3, 3) + >>> a + tensor([[-0.4264, 0.0255,-0.1064], + [ 0.8795,-0.2429, 0.1374], + [ 0.1029,-0.6482,-1.6300]]) + >>> torch.diag(a, 0) + tensor([-0.4264,-0.2429,-1.6300]) + >>> torch.diag(a, 1) + tensor([ 0.0255, 0.1374]) + """ + +def diag_embed( + input: Tensor, + offset: _int = 0, + dim1: _int = -2, + dim2: _int = -1, +) -> Tensor: + r""" + diag_embed(input, offset=0, dim1=-2, dim2=-1) -> Tensor + + Creates a tensor whose diagonals of certain 2D planes (specified by + :attr:`dim1` and :attr:`dim2`) are filled by :attr:`input`. + To facilitate creating batched diagonal matrices, the 2D planes formed by + the last two dimensions of the returned tensor are chosen by default. + + The argument :attr:`offset` controls which diagonal to consider: + + - If :attr:`offset` = 0, it is the main diagonal. + - If :attr:`offset` > 0, it is above the main diagonal. + - If :attr:`offset` < 0, it is below the main diagonal. + + The size of the new matrix will be calculated to make the specified diagonal + of the size of the last input dimension. + Note that for :attr:`offset` other than :math:`0`, the order of :attr:`dim1` + and :attr:`dim2` matters. Exchanging them is equivalent to changing the + sign of :attr:`offset`. + + Applying :meth:`torch.diagonal` to the output of this function with + the same arguments yields a matrix identical to input. However, + :meth:`torch.diagonal` has different default dimensions, so those + need to be explicitly specified. + + Args: + input (Tensor): the input tensor. Must be at least 1-dimensional. + offset (int, optional): which diagonal to consider. Default: 0 + (main diagonal). + dim1 (int, optional): first dimension with respect to which to + take diagonal. Default: -2. + dim2 (int, optional): second dimension with respect to which to + take diagonal. Default: -1. + + Example:: + + >>> a = torch.randn(2, 3) + >>> torch.diag_embed(a) + tensor([[[ 1.5410, 0.0000, 0.0000], + [ 0.0000, -0.2934, 0.0000], + [ 0.0000, 0.0000, -2.1788]], + + [[ 0.5684, 0.0000, 0.0000], + [ 0.0000, -1.0845, 0.0000], + [ 0.0000, 0.0000, -1.3986]]]) + + >>> torch.diag_embed(a, offset=1, dim1=0, dim2=2) + tensor([[[ 0.0000, 1.5410, 0.0000, 0.0000], + [ 0.0000, 0.5684, 0.0000, 0.0000]], + + [[ 0.0000, 0.0000, -0.2934, 0.0000], + [ 0.0000, 0.0000, -1.0845, 0.0000]], + + [[ 0.0000, 0.0000, 0.0000, -2.1788], + [ 0.0000, 0.0000, 0.0000, -1.3986]], + + [[ 0.0000, 0.0000, 0.0000, 0.0000], + [ 0.0000, 0.0000, 0.0000, 0.0000]]]) + """ + +def diagflat(input: Tensor, offset: _int = 0) -> Tensor: + r""" + diagflat(input, offset=0) -> Tensor + + - If :attr:`input` is a vector (1-D tensor), then returns a 2-D square tensor + with the elements of :attr:`input` as the diagonal. + - If :attr:`input` is a tensor with more than one dimension, then returns a + 2-D tensor with diagonal elements equal to a flattened :attr:`input`. + + The argument :attr:`offset` controls which diagonal to consider: + + - If :attr:`offset` = 0, it is the main diagonal. + - If :attr:`offset` > 0, it is above the main diagonal. + - If :attr:`offset` < 0, it is below the main diagonal. + + Args: + input (Tensor): the input tensor. + offset (int, optional): the diagonal to consider. Default: 0 (main + diagonal). + + Examples:: + + >>> a = torch.randn(3) + >>> a + tensor([-0.2956, -0.9068, 0.1695]) + >>> torch.diagflat(a) + tensor([[-0.2956, 0.0000, 0.0000], + [ 0.0000, -0.9068, 0.0000], + [ 0.0000, 0.0000, 0.1695]]) + >>> torch.diagflat(a, 1) + tensor([[ 0.0000, -0.2956, 0.0000, 0.0000], + [ 0.0000, 0.0000, -0.9068, 0.0000], + [ 0.0000, 0.0000, 0.0000, 0.1695], + [ 0.0000, 0.0000, 0.0000, 0.0000]]) + + >>> a = torch.randn(2, 2) + >>> a + tensor([[ 0.2094, -0.3018], + [-0.1516, 1.9342]]) + >>> torch.diagflat(a) + tensor([[ 0.2094, 0.0000, 0.0000, 0.0000], + [ 0.0000, -0.3018, 0.0000, 0.0000], + [ 0.0000, 0.0000, -0.1516, 0.0000], + [ 0.0000, 0.0000, 0.0000, 1.9342]]) + """ + +@overload +def diagonal( + input: Tensor, + offset: _int = 0, + dim1: _int = 0, + dim2: _int = 1, +) -> Tensor: + r""" + diagonal(input, offset=0, dim1=0, dim2=1) -> Tensor + + Returns a partial view of :attr:`input` with the its diagonal elements + with respect to :attr:`dim1` and :attr:`dim2` appended as a dimension + at the end of the shape. + + The argument :attr:`offset` controls which diagonal to consider: + + - If :attr:`offset` = 0, it is the main diagonal. + - If :attr:`offset` > 0, it is above the main diagonal. + - If :attr:`offset` < 0, it is below the main diagonal. + + Applying :meth:`torch.diag_embed` to the output of this function with + the same arguments yields a diagonal matrix with the diagonal entries + of the input. However, :meth:`torch.diag_embed` has different default + dimensions, so those need to be explicitly specified. + + Args: + input (Tensor): the input tensor. Must be at least 2-dimensional. + offset (int, optional): which diagonal to consider. Default: 0 + (main diagonal). + dim1 (int, optional): first dimension with respect to which to + take diagonal. Default: 0. + dim2 (int, optional): second dimension with respect to which to + take diagonal. Default: 1. + + .. note:: To take a batch diagonal, pass in dim1=-2, dim2=-1. + + Examples:: + + >>> a = torch.randn(3, 3) + >>> a + tensor([[-1.0854, 1.1431, -0.1752], + [ 0.8536, -0.0905, 0.0360], + [ 0.6927, -0.3735, -0.4945]]) + + + >>> torch.diagonal(a) + tensor([-1.0854, -0.0905, -0.4945]) + + + >>> torch.diagonal(a, 1) + tensor([ 1.1431, 0.0360]) + + >>> b = torch.randn(2, 5) + >>> b + tensor([[-1.7948, -1.2731, -0.3181, 2.0200, -1.6745], + [ 1.8262, -1.5049, 0.4114, 1.0704, -1.2607]]) + + >>> torch.diagonal(b, 1, 1, 0) + tensor([1.8262]) + + >>> x = torch.randn(2, 5, 4, 2) + >>> torch.diagonal(x, offset=-1, dim1=1, dim2=2) + tensor([[[-1.2631, 0.3755, -1.5977, -1.8172], + [-1.1065, 1.0401, -0.2235, -0.7938]], + + [[-1.7325, -0.3081, 0.6166, 0.2335], + [ 1.0500, 0.7336, -0.3836, -1.1015]]]) + """ + +@overload +def diagonal( + input: Tensor, + *, + outdim: str | EllipsisType | None, + dim1: str | EllipsisType | None, + dim2: str | EllipsisType | None, + offset: _int = 0, +) -> Tensor: + r""" + diagonal(input, offset=0, dim1=0, dim2=1) -> Tensor + + Returns a partial view of :attr:`input` with the its diagonal elements + with respect to :attr:`dim1` and :attr:`dim2` appended as a dimension + at the end of the shape. + + The argument :attr:`offset` controls which diagonal to consider: + + - If :attr:`offset` = 0, it is the main diagonal. + - If :attr:`offset` > 0, it is above the main diagonal. + - If :attr:`offset` < 0, it is below the main diagonal. + + Applying :meth:`torch.diag_embed` to the output of this function with + the same arguments yields a diagonal matrix with the diagonal entries + of the input. However, :meth:`torch.diag_embed` has different default + dimensions, so those need to be explicitly specified. + + Args: + input (Tensor): the input tensor. Must be at least 2-dimensional. + offset (int, optional): which diagonal to consider. Default: 0 + (main diagonal). + dim1 (int, optional): first dimension with respect to which to + take diagonal. Default: 0. + dim2 (int, optional): second dimension with respect to which to + take diagonal. Default: 1. + + .. note:: To take a batch diagonal, pass in dim1=-2, dim2=-1. + + Examples:: + + >>> a = torch.randn(3, 3) + >>> a + tensor([[-1.0854, 1.1431, -0.1752], + [ 0.8536, -0.0905, 0.0360], + [ 0.6927, -0.3735, -0.4945]]) + + + >>> torch.diagonal(a) + tensor([-1.0854, -0.0905, -0.4945]) + + + >>> torch.diagonal(a, 1) + tensor([ 1.1431, 0.0360]) + + >>> b = torch.randn(2, 5) + >>> b + tensor([[-1.7948, -1.2731, -0.3181, 2.0200, -1.6745], + [ 1.8262, -1.5049, 0.4114, 1.0704, -1.2607]]) + + >>> torch.diagonal(b, 1, 1, 0) + tensor([1.8262]) + + >>> x = torch.randn(2, 5, 4, 2) + >>> torch.diagonal(x, offset=-1, dim1=1, dim2=2) + tensor([[[-1.2631, 0.3755, -1.5977, -1.8172], + [-1.1065, 1.0401, -0.2235, -0.7938]], + + [[-1.7325, -0.3081, 0.6166, 0.2335], + [ 1.0500, 0.7336, -0.3836, -1.1015]]]) + """ + +def diagonal_copy( + input: Tensor, + offset: _int = 0, + dim1: _int = 0, + dim2: _int = 1, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.diagonal`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def diagonal_scatter( + input: Tensor, + src: Tensor, + offset: _int = 0, + dim1: _int = 0, + dim2: _int = 1, +) -> Tensor: + r""" + diagonal_scatter(input, src, offset=0, dim1=0, dim2=1) -> Tensor + + Embeds the values of the :attr:`src` tensor into :attr:`input` along + the diagonal elements of :attr:`input`, with respect to :attr:`dim1` + and :attr:`dim2`. + + This function returns a tensor with fresh storage; it does not + return a view. + + The argument :attr:`offset` controls which diagonal to consider: + + - If :attr:`offset` = 0, it is the main diagonal. + - If :attr:`offset` > 0, it is above the main diagonal. + - If :attr:`offset` < 0, it is below the main diagonal. + + Args: + input (Tensor): the input tensor. Must be at least 2-dimensional. + src (Tensor): the tensor to embed into :attr:`input`. + offset (int, optional): which diagonal to consider. Default: 0 + (main diagonal). + dim1 (int, optional): first dimension with respect to which to + take diagonal. Default: 0. + dim2 (int, optional): second dimension with respect to which to + take diagonal. Default: 1. + + .. note:: + + :attr:`src` must be of the proper size in order to be embedded + into :attr:`input`. Specifically, it should have the same shape as + ``torch.diagonal(input, offset, dim1, dim2)`` + + Examples:: + + >>> a = torch.zeros(3, 3) + >>> a + tensor([[0., 0., 0.], + [0., 0., 0.], + [0., 0., 0.]]) + + >>> torch.diagonal_scatter(a, torch.ones(3), 0) + tensor([[1., 0., 0.], + [0., 1., 0.], + [0., 0., 1.]]) + + >>> torch.diagonal_scatter(a, torch.ones(2), 1) + tensor([[0., 1., 0.], + [0., 0., 1.], + [0., 0., 0.]]) + """ + +def diff( + input: Tensor, + n: _int = 1, + dim: _int = -1, + prepend: Tensor | None = None, + append: Tensor | None = None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + diff(input, n=1, dim=-1, prepend=None, append=None) -> Tensor + + Computes the n-th forward difference along the given dimension. + + The first-order differences are given by `out[i] = input[i + 1] - input[i]`. Higher-order + differences are calculated by using :func:`torch.diff` recursively. + + Args: + input (Tensor): the tensor to compute the differences on + n (int, optional): the number of times to recursively compute the difference + dim (int, optional): the dimension to compute the difference along. + Default is the last dimension. + prepend, append (Tensor, optional): values to prepend or append to + :attr:`input` along :attr:`dim` before computing the difference. + Their dimensions must be equivalent to that of input, and their shapes + must match input's shape except on :attr:`dim`. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([1, 3, 2]) + >>> torch.diff(a) + tensor([ 2, -1]) + >>> b = torch.tensor([4, 5]) + >>> torch.diff(a, append=b) + tensor([ 2, -1, 2, 1]) + >>> c = torch.tensor([[1, 2, 3], [3, 4, 5]]) + >>> torch.diff(c, dim=0) + tensor([[2, 2, 2]]) + >>> torch.diff(c, dim=1) + tensor([[1, 1], + [1, 1]]) + """ + +def digamma(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + digamma(input, *, out=None) -> Tensor + + Alias for :func:`torch.special.digamma`. + """ + +def dist(input: Tensor, other: Tensor, p: Number | _complex = 2) -> Tensor: + r""" + dist(input, other, p=2) -> Tensor + + Returns the p-norm of (:attr:`input` - :attr:`other`) + + The shapes of :attr:`input` and :attr:`other` must be + :ref:`broadcastable `. + + Args: + input (Tensor): the input tensor. + other (Tensor): the Right-hand-side input tensor + p (float, optional): the norm to be computed + + Example:: + + >>> x = torch.randn(4) + >>> x + tensor([-1.5393, -0.8675, 0.5916, 1.6321]) + >>> y = torch.randn(4) + >>> y + tensor([ 0.0967, -1.0511, 0.6295, 0.8360]) + >>> torch.dist(x, y, 3.5) + tensor(1.6727) + >>> torch.dist(x, y, 3) + tensor(1.6973) + >>> torch.dist(x, y, 0) + tensor(4.) + >>> torch.dist(x, y, 1) + tensor(2.6537) + """ + +def div( + input: Tensor | Number, + other: Tensor | Number, + *, + rounding_mode: str | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + div(input, other, *, rounding_mode=None, out=None) -> Tensor + + Divides each element of the input ``input`` by the corresponding element of + :attr:`other`. + + .. math:: + \text{out}_i = \frac{\text{input}_i}{\text{other}_i} + + .. note:: + By default, this performs a "true" division like Python 3. + See the :attr:`rounding_mode` argument for floor division. + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer, float, and complex inputs. + Always promotes integer types to the default scalar type. + + Args: + input (Tensor): the dividend + other (Tensor or Number): the divisor + + Keyword args: + rounding_mode (str, optional): Type of rounding applied to the result: + + * None - default behavior. Performs no rounding and, if both :attr:`input` and + :attr:`other` are integer types, promotes the inputs to the default scalar type. + Equivalent to true division in Python (the ``/`` operator) and NumPy's ``np.true_divide``. + * ``"trunc"`` - rounds the results of the division towards zero. + Equivalent to C-style integer division. + * ``"floor"`` - rounds the results of the division down. + Equivalent to floor division in Python (the ``//`` operator) and NumPy's ``np.floor_divide``. + + out (Tensor, optional): the output tensor. + + Examples:: + + >>> x = torch.tensor([ 0.3810, 1.2774, -0.2972, -0.3719, 0.4637]) + >>> torch.div(x, 0.5) + tensor([ 0.7620, 2.5548, -0.5944, -0.7438, 0.9274]) + + >>> a = torch.tensor([[-0.3711, -1.9353, -0.4605, -0.2917], + ... [ 0.1815, -1.0111, 0.9805, -1.5923], + ... [ 0.1062, 1.4581, 0.7759, -1.2344], + ... [-0.1830, -0.0313, 1.1908, -1.4757]]) + >>> b = torch.tensor([ 0.8032, 0.2930, -0.8113, -0.2308]) + >>> torch.div(a, b) + tensor([[-0.4620, -6.6051, 0.5676, 1.2639], + [ 0.2260, -3.4509, -1.2086, 6.8990], + [ 0.1322, 4.9764, -0.9564, 5.3484], + [-0.2278, -0.1068, -1.4678, 6.3938]]) + + >>> torch.div(a, b, rounding_mode='trunc') + tensor([[-0., -6., 0., 1.], + [ 0., -3., -1., 6.], + [ 0., 4., -0., 5.], + [-0., -0., -1., 6.]]) + + >>> torch.div(a, b, rounding_mode='floor') + tensor([[-1., -7., 0., 1.], + [ 0., -4., -2., 6.], + [ 0., 4., -1., 5.], + [-1., -1., -2., 6.]]) + """ + +@overload +def divide( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + divide(input, other, *, rounding_mode=None, out=None) -> Tensor + + Alias for :func:`torch.div`. + """ + +@overload +def divide( + input: Tensor, + other: Tensor, + *, + rounding_mode: str | None, + out: Tensor | None = None, +) -> Tensor: + r""" + divide(input, other, *, rounding_mode=None, out=None) -> Tensor + + Alias for :func:`torch.div`. + """ + +@overload +def divide( + input: Tensor, + other: Number | _complex, + *, + rounding_mode: str | None, +) -> Tensor: + r""" + divide(input, other, *, rounding_mode=None, out=None) -> Tensor + + Alias for :func:`torch.div`. + """ + +@overload +def divide(input: Tensor, other: Number | _complex) -> Tensor: + r""" + divide(input, other, *, rounding_mode=None, out=None) -> Tensor + + Alias for :func:`torch.div`. + """ + +def dot( + input: Tensor, + tensor: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + dot(input, tensor, *, out=None) -> Tensor + + Computes the dot product of two 1D tensors. + + .. note:: + + Unlike NumPy's dot, torch.dot intentionally only supports computing the dot product + of two 1D tensors with the same number of elements. + + Args: + input (Tensor): first tensor in the dot product, must be 1D. + tensor (Tensor): second tensor in the dot product, must be 1D. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.dot(torch.tensor([2, 3]), torch.tensor([2, 1])) + tensor(7) + + >>> t1, t2 = torch.tensor([0, 1]), torch.tensor([2, 3]) + >>> torch.dot(t1, t2) + tensor(3) + """ + +def dropout(input: Tensor, p: _float, train: _bool) -> Tensor: ... +def dropout_(input: Tensor, p: _float, train: _bool) -> Tensor: ... +def dsmm(input: Tensor, mat2: Tensor) -> Tensor: ... +@overload +def dsplit(input: Tensor, sections: _int) -> tuple[Tensor, ...]: + r""" + dsplit(input, indices_or_sections) -> List of Tensors + + Splits :attr:`input`, a tensor with three or more dimensions, into multiple tensors + depthwise according to :attr:`indices_or_sections`. Each split is a view of + :attr:`input`. + + This is equivalent to calling torch.tensor_split(input, indices_or_sections, dim=2) + (the split dimension is 2), except that if :attr:`indices_or_sections` is an integer + it must evenly divide the split dimension or a runtime error will be thrown. + + This function is based on NumPy's :func:`numpy.dsplit`. + + Args: + input (Tensor): tensor to split. + indices_or_sections (int or list or tuple of ints): See argument in :func:`torch.tensor_split`. + + Example:: + + >>> t = torch.arange(16.0).reshape(2, 2, 4) + >>> t + tensor([[[ 0., 1., 2., 3.], + [ 4., 5., 6., 7.]], + [[ 8., 9., 10., 11.], + [12., 13., 14., 15.]]]) + >>> torch.dsplit(t, 2) + (tensor([[[ 0., 1.], + [ 4., 5.]], + [[ 8., 9.], + [12., 13.]]]), + tensor([[[ 2., 3.], + [ 6., 7.]], + [[10., 11.], + [14., 15.]]])) + + >>> torch.dsplit(t, [3, 6]) + (tensor([[[ 0., 1., 2.], + [ 4., 5., 6.]], + [[ 8., 9., 10.], + [12., 13., 14.]]]), + tensor([[[ 3.], + [ 7.]], + [[11.], + [15.]]]), + tensor([], size=(2, 2, 0))) + """ + +@overload +def dsplit(input: Tensor, indices: _size) -> tuple[Tensor, ...]: + r""" + dsplit(input, indices_or_sections) -> List of Tensors + + Splits :attr:`input`, a tensor with three or more dimensions, into multiple tensors + depthwise according to :attr:`indices_or_sections`. Each split is a view of + :attr:`input`. + + This is equivalent to calling torch.tensor_split(input, indices_or_sections, dim=2) + (the split dimension is 2), except that if :attr:`indices_or_sections` is an integer + it must evenly divide the split dimension or a runtime error will be thrown. + + This function is based on NumPy's :func:`numpy.dsplit`. + + Args: + input (Tensor): tensor to split. + indices_or_sections (int or list or tuple of ints): See argument in :func:`torch.tensor_split`. + + Example:: + + >>> t = torch.arange(16.0).reshape(2, 2, 4) + >>> t + tensor([[[ 0., 1., 2., 3.], + [ 4., 5., 6., 7.]], + [[ 8., 9., 10., 11.], + [12., 13., 14., 15.]]]) + >>> torch.dsplit(t, 2) + (tensor([[[ 0., 1.], + [ 4., 5.]], + [[ 8., 9.], + [12., 13.]]]), + tensor([[[ 2., 3.], + [ 6., 7.]], + [[10., 11.], + [14., 15.]]])) + + >>> torch.dsplit(t, [3, 6]) + (tensor([[[ 0., 1., 2.], + [ 4., 5., 6.]], + [[ 8., 9., 10.], + [12., 13., 14.]]]), + tensor([[[ 3.], + [ 7.]], + [[11.], + [15.]]]), + tensor([], size=(2, 2, 0))) + """ + +def dstack( + tensors: tuple[Tensor, ...] | list[Tensor] | None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + dstack(tensors, *, out=None) -> Tensor + + Stack tensors in sequence depthwise (along third axis). + + This is equivalent to concatenation along the third axis after 1-D and 2-D tensors have been reshaped by :func:`torch.atleast_3d`. + + Args: + tensors (sequence of Tensors): sequence of tensors to concatenate + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([1, 2, 3]) + >>> b = torch.tensor([4, 5, 6]) + >>> torch.dstack((a,b)) + tensor([[[1, 4], + [2, 5], + [3, 6]]]) + >>> a = torch.tensor([[1],[2],[3]]) + >>> b = torch.tensor([[4],[5],[6]]) + >>> torch.dstack((a,b)) + tensor([[[1, 4]], + [[2, 5]], + [[3, 6]]]) + """ + +def embedding( + weight: Tensor, + indices: Tensor, + padding_idx: _int | SymInt = -1, + scale_grad_by_freq: _bool = False, + sparse: _bool = False, +) -> Tensor: ... +@overload +def embedding_bag( + weight: Tensor, + indices: Tensor, + offsets: Tensor, + scale_grad_by_freq: _bool, + mode: _int, + sparse: _bool, + per_sample_weights: Tensor | None, + include_last_offset: _bool, + padding_idx: _int | None, +) -> tuple[Tensor, Tensor, Tensor, Tensor]: ... +@overload +def embedding_bag( + weight: Tensor, + indices: Tensor, + offsets: Tensor, + scale_grad_by_freq: _bool = False, + mode: _int = 0, + sparse: _bool = False, + per_sample_weights: Tensor | None = None, + include_last_offset: _bool = False, +) -> tuple[Tensor, Tensor, Tensor, Tensor]: ... +def embedding_renorm_( + input: Tensor, + indices: Tensor, + max_norm: _float, + norm_type: _float, +) -> Tensor: ... +@overload +def empty( + size: Sequence[_int | SymInt], + *, + memory_format: memory_format | None = None, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + empty(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False, memory_format=torch.contiguous_format) -> Tensor + + Returns a tensor filled with uninitialized data. The shape of the tensor is + defined by the variable argument :attr:`size`. + + .. note:: + If :func:`torch.use_deterministic_algorithms()` and + :attr:`torch.utils.deterministic.fill_uninitialized_memory` are both set to + ``True``, the output tensor is initialized to prevent any possible + nondeterministic behavior from using the data as an input to an operation. + Floating point and complex tensors are filled with NaN, and integer tensors + are filled with the maximum value. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.contiguous_format``. + + Example:: + + >>> torch.empty((2,3), dtype=torch.int64) + tensor([[ 9.4064e+13, 2.8000e+01, 9.3493e+13], + [ 7.5751e+18, 7.1428e+18, 7.5955e+18]]) + """ + +@overload +def empty( + *size: _int | SymInt, + memory_format: memory_format | None = None, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + empty(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False, memory_format=torch.contiguous_format) -> Tensor + + Returns a tensor filled with uninitialized data. The shape of the tensor is + defined by the variable argument :attr:`size`. + + .. note:: + If :func:`torch.use_deterministic_algorithms()` and + :attr:`torch.utils.deterministic.fill_uninitialized_memory` are both set to + ``True``, the output tensor is initialized to prevent any possible + nondeterministic behavior from using the data as an input to an operation. + Floating point and complex tensors are filled with NaN, and integer tensors + are filled with the maximum value. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.contiguous_format``. + + Example:: + + >>> torch.empty((2,3), dtype=torch.int64) + tensor([[ 9.4064e+13, 2.8000e+01, 9.3493e+13], + [ 7.5751e+18, 7.1428e+18, 7.5955e+18]]) + """ + +@overload +def empty( + size: _size, + *, + names: Sequence[str | EllipsisType | None] | None, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + empty(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False, memory_format=torch.contiguous_format) -> Tensor + + Returns a tensor filled with uninitialized data. The shape of the tensor is + defined by the variable argument :attr:`size`. + + .. note:: + If :func:`torch.use_deterministic_algorithms()` and + :attr:`torch.utils.deterministic.fill_uninitialized_memory` are both set to + ``True``, the output tensor is initialized to prevent any possible + nondeterministic behavior from using the data as an input to an operation. + Floating point and complex tensors are filled with NaN, and integer tensors + are filled with the maximum value. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.contiguous_format``. + + Example:: + + >>> torch.empty((2,3), dtype=torch.int64) + tensor([[ 9.4064e+13, 2.8000e+01, 9.3493e+13], + [ 7.5751e+18, 7.1428e+18, 7.5955e+18]]) + """ + +@overload +def empty( + *size: _int, + names: Sequence[str | EllipsisType | None] | None, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + empty(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False, memory_format=torch.contiguous_format) -> Tensor + + Returns a tensor filled with uninitialized data. The shape of the tensor is + defined by the variable argument :attr:`size`. + + .. note:: + If :func:`torch.use_deterministic_algorithms()` and + :attr:`torch.utils.deterministic.fill_uninitialized_memory` are both set to + ``True``, the output tensor is initialized to prevent any possible + nondeterministic behavior from using the data as an input to an operation. + Floating point and complex tensors are filled with NaN, and integer tensors + are filled with the maximum value. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.contiguous_format``. + + Example:: + + >>> torch.empty((2,3), dtype=torch.int64) + tensor([[ 9.4064e+13, 2.8000e+01, 9.3493e+13], + [ 7.5751e+18, 7.1428e+18, 7.5955e+18]]) + """ + +def empty_like( + input: Tensor, + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + empty_like(input, *, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns an uninitialized tensor with the same size as :attr:`input`. + ``torch.empty_like(input)`` is equivalent to + ``torch.empty(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``. + + .. note:: + If :func:`torch.use_deterministic_algorithms()` and + :attr:`torch.utils.deterministic.fill_uninitialized_memory` are both set to + ``True``, the output tensor is initialized to prevent any possible + nondeterministic behavior from using the data as an input to an operation. + Floating point and complex tensors are filled with NaN, and integer tensors + are filled with the maximum value. + + When ``torch.preserve_format`` is used: + If the input tensor is dense (i.e., non-overlapping strided), + its memory format (including strides) is retained. + Otherwise (e.g., a non-dense view like a stepped slice), + the output is converted to the dense format. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + + Example:: + + >>> a=torch.empty((2,3), dtype=torch.int32, device = 'cuda') + >>> torch.empty_like(a) + tensor([[0, 0, 0], + [0, 0, 0]], device='cuda:0', dtype=torch.int32) + """ + +def empty_permuted( + size: Sequence[_int | SymInt], + physical_layout: _size, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + empty_permuted(size, physical_layout, *, dtype=None, layout=None, device=None, requires_grad=False, pin_memory=False) -> Tensor + + Creates an uninitialized, non-overlapping and dense tensor with the + specified :attr:`size`, with :attr:`physical_layout` specifying how the + dimensions are physically laid out in memory (each logical dimension is listed + from outermost to innermost). :attr:`physical_layout` is a generalization + of NCHW/NHWC notation: if each dimension is assigned a number according to + what order they occur in size (N=0, C=1, H=2, W=3), then NCHW is ``(0, 1, 2, 3)`` + while NHWC is ``(0, 2, 3, 1)``. Equivalently, the strides of the output + tensor ``t`` are such that ``t.stride(physical_layout[i]) == contiguous_strides[i]`` + (notably, this function is *not* equivalent to ``torch.empty(size).permute(physical_layout)``). + + Unlike :func:`torch.empty_strided`, this is guaranteed to produce a dense + tensor with no overlaps. If possible, prefer using this function over + :func:`torch.empty_strided` or manual use of :func:`torch.as_strided`. + + .. note:: + If :func:`torch.use_deterministic_algorithms()` and + :attr:`torch.utils.deterministic.fill_uninitialized_memory` are both set to + ``True``, the output tensor is initialized to prevent any possible + nondeterministic behavior from using the data as an input to an operation. + Floating point and complex tensors are filled with NaN, and integer tensors + are filled with the maximum value. + + Args: + size (tuple of int): the shape of the output tensor + physical_layout (tuple of int): the ordering of dimensions physically in memory + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Examples: + + >>> torch.empty((2, 3, 5, 7)).stride() + (105, 35, 7, 1) + >>> torch.empty_permuted((2, 3, 5, 7), (0, 1, 2, 3)).stride() + (105, 35, 7, 1) + >>> torch.empty((2, 3, 5, 7), memory_format=torch.channels_last).stride() + (105, 1, 21, 3) + >>> torch.empty_permuted((2, 3, 5, 7), (0, 2, 3, 1)).stride() + (105, 1, 21, 3) + >>> torch.empty_permuted((2, 3, 5, 7), (0, 2, 3, 1)).dim_order() + (0, 2, 3, 1) + """ + +def empty_quantized( + size: _size, + qtensor: Tensor, + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: ... +def empty_strided( + size: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + empty_strided(size, stride, *, dtype=None, layout=None, device=None, requires_grad=False, pin_memory=False) -> Tensor + + Creates a tensor with the specified :attr:`size` and :attr:`stride` and filled with undefined data. + + .. warning:: + If the constructed tensor is "overlapped" (with multiple indices referring to the same element + in memory) its behavior is undefined. + + .. note:: + If :func:`torch.use_deterministic_algorithms()` and + :attr:`torch.utils.deterministic.fill_uninitialized_memory` are both set to + ``True``, the output tensor is initialized to prevent any possible + nondeterministic behavior from using the data as an input to an operation. + Floating point and complex tensors are filled with NaN, and integer tensors + are filled with the maximum value. + + Args: + size (tuple of int): the shape of the output tensor + stride (tuple of int): the strides of the output tensor + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> a = torch.empty_strided((2, 3), (1, 2)) + >>> a + tensor([[8.9683e-44, 4.4842e-44, 5.1239e+07], + [0.0000e+00, 0.0000e+00, 3.0705e-41]]) + >>> a.stride() + (1, 2) + >>> a.size() + torch.Size([2, 3]) + """ + +@overload +def eq( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + eq(input, other, *, out=None) -> Tensor + + Computes element-wise equality + + The second argument can be a number or a tensor whose shape is + :ref:`broadcastable ` with the first argument. + + Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is equal to :attr:`other` and False elsewhere + + Example:: + + >>> torch.eq(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[ True, False], + [False, True]]) + """ + +@overload +def eq( + input: Tensor, + other: Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + eq(input, other, *, out=None) -> Tensor + + Computes element-wise equality + + The second argument can be a number or a tensor whose shape is + :ref:`broadcastable ` with the first argument. + + Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is equal to :attr:`other` and False elsewhere + + Example:: + + >>> torch.eq(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[ True, False], + [False, True]]) + """ + +def equal(input: Tensor, other: Tensor) -> _bool: + r""" + equal(input, other) -> bool + + ``True`` if two tensors have the same size and elements, ``False`` otherwise. + + .. note:: + + Tensors containing NaNs are never equal to each other. Additionally, this function does not + differentiate between the data types of the tensors during comparison. For more thorough tensor checks, + use :meth:`torch.testing.assert_close`. + + Example:: + + >>> torch.equal(torch.tensor([1, 2]), torch.tensor([1, 2])) + True + >>> torch.equal(torch.tensor([3, torch.nan]), torch.tensor([3, torch.nan])) + False + >>> torch.equal(torch.tensor([1, 2, 3], dtype=torch.int32), torch.tensor([1, 2, 3], dtype=torch.float32)) + True + """ + +def erf(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + erf(input, *, out=None) -> Tensor + + Alias for :func:`torch.special.erf`. + """ + +def erf_(input: Tensor) -> Tensor: ... +def erfc(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + erfc(input, *, out=None) -> Tensor + + Alias for :func:`torch.special.erfc`. + """ + +def erfc_(input: Tensor) -> Tensor: ... +def erfinv(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + erfinv(input, *, out=None) -> Tensor + + Alias for :func:`torch.special.erfinv`. + """ + +def exp(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + exp(input, *, out=None) -> Tensor + + Returns a new tensor with the exponential of the elements + of the input tensor :attr:`input`. + + .. math:: + y_{i} = e^{x_{i}} + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.exp(torch.tensor([0, math.log(2.)])) + tensor([ 1., 2.]) + """ + +def exp2(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + exp2(input, *, out=None) -> Tensor + + Alias for :func:`torch.special.exp2`. + """ + +def exp2_(input: Tensor) -> Tensor: ... +def exp_(input: Tensor) -> Tensor: ... +def expand_copy( + input: Tensor, + size: Sequence[_int | SymInt], + *, + implicit: _bool = False, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.Tensor.expand`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def expm1(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + expm1(input, *, out=None) -> Tensor + + Alias for :func:`torch.special.expm1`. + """ + +def expm1_(input: Tensor) -> Tensor: ... +@overload +def eye( + n: _int | SymInt, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + eye(n, m=None, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a 2-D tensor with ones on the diagonal and zeros elsewhere. + + Args: + n (int): the number of rows + m (int, optional): the number of columns with default being :attr:`n` + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 2-D tensor with ones on the diagonal and zeros elsewhere + + Example:: + + >>> torch.eye(3) + tensor([[ 1., 0., 0.], + [ 0., 1., 0.], + [ 0., 0., 1.]]) + """ + +@overload +def eye( + n: _int | SymInt, + m: _int | SymInt, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + eye(n, m=None, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a 2-D tensor with ones on the diagonal and zeros elsewhere. + + Args: + n (int): the number of rows + m (int, optional): the number of columns with default being :attr:`n` + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 2-D tensor with ones on the diagonal and zeros elsewhere + + Example:: + + >>> torch.eye(3) + tensor([[ 1., 0., 0.], + [ 0., 1., 0.], + [ 0., 0., 1.]]) + """ + +def fake_quantize_per_channel_affine( + input: Tensor, + scale: Tensor, + zero_point: Tensor, + axis: _int, + quant_min: _int, + quant_max: _int, +) -> Tensor: + r""" + fake_quantize_per_channel_affine(input, scale, zero_point, axis, quant_min, quant_max) -> Tensor + + Returns a new tensor with the data in :attr:`input` fake quantized per channel using :attr:`scale`, + :attr:`zero_point`, :attr:`quant_min` and :attr:`quant_max`, across the channel specified by :attr:`axis`. + + .. math:: + \text{output} = ( + min( + \text{quant\_max}, + max( + \text{quant\_min}, + \text{std::nearby\_int}(\text{input} / \text{scale}) + \text{zero\_point} + ) + ) - \text{zero\_point} + ) \times \text{scale} + + Args: + input (Tensor): the input value(s), in ``torch.float32`` + scale (Tensor): quantization scale, per channel in ``torch.float32`` + zero_point (Tensor): quantization zero_point, per channel in ``torch.int32`` or ``torch.half`` or ``torch.float32`` + axis (int32): channel axis + quant_min (int64): lower bound of the quantized domain + quant_max (int64): upper bound of the quantized domain + + Returns: + Tensor: A newly fake_quantized per channel ``torch.float32`` tensor + + Example:: + + >>> x = torch.randn(2, 2, 2) + >>> x + tensor([[[-0.2525, -0.0466], + [ 0.3491, -0.2168]], + + [[-0.5906, 1.6258], + [ 0.6444, -0.0542]]]) + >>> scales = (torch.randn(2) + 1) * 0.05 + >>> scales + tensor([0.0475, 0.0486]) + >>> zero_points = torch.zeros(2).to(torch.int32) + >>> zero_points + tensor([0, 0]) + >>> torch.fake_quantize_per_channel_affine(x, scales, zero_points, 1, 0, 255) + tensor([[[0.0000, 0.0000], + [0.3405, 0.0000]], + + [[0.0000, 1.6134], + [0.6323, 0.0000]]]) + """ + +@overload +def fake_quantize_per_tensor_affine( + input: Tensor, + scale: _float, + zero_point: _int, + quant_min: _int, + quant_max: _int, +) -> Tensor: + r""" + fake_quantize_per_tensor_affine(input, scale, zero_point, quant_min, quant_max) -> Tensor + + Returns a new tensor with the data in :attr:`input` fake quantized using :attr:`scale`, + :attr:`zero_point`, :attr:`quant_min` and :attr:`quant_max`. + + .. math:: + \text{output} = ( + min( + \text{quant\_max}, + max( + \text{quant\_min}, + \text{std::nearby\_int}(\text{input} / \text{scale}) + \text{zero\_point} + ) + ) - \text{zero\_point} + ) \times \text{scale} + + Args: + input (Tensor): the input value(s), ``torch.float32`` tensor + scale (double scalar or ``float32`` Tensor): quantization scale + zero_point (int64 scalar or ``int32`` Tensor): quantization zero_point + quant_min (int64): lower bound of the quantized domain + quant_max (int64): upper bound of the quantized domain + + Returns: + Tensor: A newly fake_quantized ``torch.float32`` tensor + + Example:: + + >>> x = torch.randn(4) + >>> x + tensor([ 0.0552, 0.9730, 0.3973, -1.0780]) + >>> torch.fake_quantize_per_tensor_affine(x, 0.1, 0, 0, 255) + tensor([0.1000, 1.0000, 0.4000, 0.0000]) + >>> torch.fake_quantize_per_tensor_affine(x, torch.tensor(0.1), torch.tensor(0), 0, 255) + tensor([0.1000, 1.0000, 0.4000, 0.0000]) + """ + +@overload +def fake_quantize_per_tensor_affine( + input: Tensor, + scale: Tensor, + zero_point: Tensor, + quant_min: _int, + quant_max: _int, +) -> Tensor: + r""" + fake_quantize_per_tensor_affine(input, scale, zero_point, quant_min, quant_max) -> Tensor + + Returns a new tensor with the data in :attr:`input` fake quantized using :attr:`scale`, + :attr:`zero_point`, :attr:`quant_min` and :attr:`quant_max`. + + .. math:: + \text{output} = ( + min( + \text{quant\_max}, + max( + \text{quant\_min}, + \text{std::nearby\_int}(\text{input} / \text{scale}) + \text{zero\_point} + ) + ) - \text{zero\_point} + ) \times \text{scale} + + Args: + input (Tensor): the input value(s), ``torch.float32`` tensor + scale (double scalar or ``float32`` Tensor): quantization scale + zero_point (int64 scalar or ``int32`` Tensor): quantization zero_point + quant_min (int64): lower bound of the quantized domain + quant_max (int64): upper bound of the quantized domain + + Returns: + Tensor: A newly fake_quantized ``torch.float32`` tensor + + Example:: + + >>> x = torch.randn(4) + >>> x + tensor([ 0.0552, 0.9730, 0.3973, -1.0780]) + >>> torch.fake_quantize_per_tensor_affine(x, 0.1, 0, 0, 255) + tensor([0.1000, 1.0000, 0.4000, 0.0000]) + >>> torch.fake_quantize_per_tensor_affine(x, torch.tensor(0.1), torch.tensor(0), 0, 255) + tensor([0.1000, 1.0000, 0.4000, 0.0000]) + """ + +@overload +def fbgemm_linear_fp16_weight( + input: Tensor, + packed_weight: Tensor, + bias: Tensor, +) -> Tensor: ... +@overload +def fbgemm_linear_fp16_weight( + input: Tensor, + packed_weight: Tensor, + bias: Tensor, + output: Tensor, +) -> Tensor: ... +@overload +def fbgemm_linear_fp16_weight_fp32_activation( + input: Tensor, + packed_weight: Tensor, + bias: Tensor | None, +) -> Tensor: ... +@overload +def fbgemm_linear_fp16_weight_fp32_activation( + input: Tensor, + packed_weight: Tensor, + bias: Tensor | None, + output: Tensor, +) -> Tensor: ... +def fbgemm_linear_int8_weight( + input: Tensor, + weight: Tensor, + packed: Tensor, + col_offsets: Tensor, + weight_scale: Number | _complex, + weight_zero_point: Number | _complex, + bias: Tensor, +) -> Tensor: ... +def fbgemm_linear_int8_weight_fp32_activation( + input: Tensor, + weight: Tensor, + packed: Tensor, + col_offsets: Tensor, + weight_scale: Number | _complex, + weight_zero_point: Number | _complex, + bias: Tensor, +) -> Tensor: ... +def fbgemm_linear_quantize_weight( + input: Tensor, +) -> tuple[Tensor, Tensor, _float, _int]: ... +def fbgemm_pack_gemm_matrix_fp16(input: Tensor) -> Tensor: ... +@overload +def fbgemm_pack_quantized_matrix(input: Tensor) -> Tensor: ... +@overload +def fbgemm_pack_quantized_matrix(input: Tensor, K: _int, N: _int) -> Tensor: ... +def feature_alpha_dropout(input: Tensor, p: _float, train: _bool) -> Tensor: ... +def feature_alpha_dropout_( + input: Tensor, + p: _float, + train: _bool, +) -> Tensor: ... +def feature_dropout(input: Tensor, p: _float, train: _bool) -> Tensor: ... +def feature_dropout_(input: Tensor, p: _float, train: _bool) -> Tensor: ... +@overload +def fill(input: Tensor, value: Tensor) -> Tensor: ... +@overload +def fill(input: Tensor, value: Number | _complex) -> Tensor: ... +@overload +def fill_(input: Tensor, value: Tensor) -> Tensor: ... +@overload +def fill_(input: Tensor, value: Number | _complex) -> Tensor: ... +def fix(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + fix(input, *, out=None) -> Tensor + + Alias for :func:`torch.trunc` + """ + +def fix_(input: Tensor) -> Tensor: ... +@overload +def flatten( + input: Tensor, + start_dim: _int = 0, + end_dim: _int = -1, +) -> Tensor: + r""" + flatten(input, start_dim=0, end_dim=-1) -> Tensor + + Flattens :attr:`input` by reshaping it into a one-dimensional tensor. If :attr:`start_dim` or :attr:`end_dim` + are passed, only dimensions starting with :attr:`start_dim` and ending with :attr:`end_dim` are flattened. + The order of elements in :attr:`input` is unchanged. + + Unlike NumPy's flatten, which always copies input's data, this function may return the original object, a view, + or copy. If no dimensions are flattened, then the original object :attr:`input` is returned. Otherwise, if input can + be viewed as the flattened shape, then that view is returned. Finally, only if the input cannot be viewed as the + flattened shape is input's data copied. See :meth:`torch.Tensor.view` for details on when a view will be returned. + + .. note:: + Flattening a zero-dimensional tensor will return a one-dimensional view. + + Args: + input (Tensor): the input tensor. + start_dim (int): the first dim to flatten + end_dim (int): the last dim to flatten + + Example:: + + >>> t = torch.tensor([[[1, 2], + ... [3, 4]], + ... [[5, 6], + ... [7, 8]]]) + >>> torch.flatten(t) + tensor([1, 2, 3, 4, 5, 6, 7, 8]) + >>> torch.flatten(t, start_dim=1) + tensor([[1, 2, 3, 4], + [5, 6, 7, 8]]) + """ + +@overload +def flatten( + input: Tensor, + start_dim: _int, + end_dim: _int, + out_dim: str | EllipsisType | None, +) -> Tensor: + r""" + flatten(input, start_dim=0, end_dim=-1) -> Tensor + + Flattens :attr:`input` by reshaping it into a one-dimensional tensor. If :attr:`start_dim` or :attr:`end_dim` + are passed, only dimensions starting with :attr:`start_dim` and ending with :attr:`end_dim` are flattened. + The order of elements in :attr:`input` is unchanged. + + Unlike NumPy's flatten, which always copies input's data, this function may return the original object, a view, + or copy. If no dimensions are flattened, then the original object :attr:`input` is returned. Otherwise, if input can + be viewed as the flattened shape, then that view is returned. Finally, only if the input cannot be viewed as the + flattened shape is input's data copied. See :meth:`torch.Tensor.view` for details on when a view will be returned. + + .. note:: + Flattening a zero-dimensional tensor will return a one-dimensional view. + + Args: + input (Tensor): the input tensor. + start_dim (int): the first dim to flatten + end_dim (int): the last dim to flatten + + Example:: + + >>> t = torch.tensor([[[1, 2], + ... [3, 4]], + ... [[5, 6], + ... [7, 8]]]) + >>> torch.flatten(t) + tensor([1, 2, 3, 4, 5, 6, 7, 8]) + >>> torch.flatten(t, start_dim=1) + tensor([[1, 2, 3, 4], + [5, 6, 7, 8]]) + """ + +@overload +def flatten( + input: Tensor, + start_dim: str | EllipsisType | None, + end_dim: str | EllipsisType | None, + out_dim: str | EllipsisType | None, +) -> Tensor: + r""" + flatten(input, start_dim=0, end_dim=-1) -> Tensor + + Flattens :attr:`input` by reshaping it into a one-dimensional tensor. If :attr:`start_dim` or :attr:`end_dim` + are passed, only dimensions starting with :attr:`start_dim` and ending with :attr:`end_dim` are flattened. + The order of elements in :attr:`input` is unchanged. + + Unlike NumPy's flatten, which always copies input's data, this function may return the original object, a view, + or copy. If no dimensions are flattened, then the original object :attr:`input` is returned. Otherwise, if input can + be viewed as the flattened shape, then that view is returned. Finally, only if the input cannot be viewed as the + flattened shape is input's data copied. See :meth:`torch.Tensor.view` for details on when a view will be returned. + + .. note:: + Flattening a zero-dimensional tensor will return a one-dimensional view. + + Args: + input (Tensor): the input tensor. + start_dim (int): the first dim to flatten + end_dim (int): the last dim to flatten + + Example:: + + >>> t = torch.tensor([[[1, 2], + ... [3, 4]], + ... [[5, 6], + ... [7, 8]]]) + >>> torch.flatten(t) + tensor([1, 2, 3, 4, 5, 6, 7, 8]) + >>> torch.flatten(t, start_dim=1) + tensor([[1, 2, 3, 4], + [5, 6, 7, 8]]) + """ + +@overload +def flatten( + input: Tensor, + dims: Sequence[str | EllipsisType | None], + out_dim: str | EllipsisType | None, +) -> Tensor: + r""" + flatten(input, start_dim=0, end_dim=-1) -> Tensor + + Flattens :attr:`input` by reshaping it into a one-dimensional tensor. If :attr:`start_dim` or :attr:`end_dim` + are passed, only dimensions starting with :attr:`start_dim` and ending with :attr:`end_dim` are flattened. + The order of elements in :attr:`input` is unchanged. + + Unlike NumPy's flatten, which always copies input's data, this function may return the original object, a view, + or copy. If no dimensions are flattened, then the original object :attr:`input` is returned. Otherwise, if input can + be viewed as the flattened shape, then that view is returned. Finally, only if the input cannot be viewed as the + flattened shape is input's data copied. See :meth:`torch.Tensor.view` for details on when a view will be returned. + + .. note:: + Flattening a zero-dimensional tensor will return a one-dimensional view. + + Args: + input (Tensor): the input tensor. + start_dim (int): the first dim to flatten + end_dim (int): the last dim to flatten + + Example:: + + >>> t = torch.tensor([[[1, 2], + ... [3, 4]], + ... [[5, 6], + ... [7, 8]]]) + >>> torch.flatten(t) + tensor([1, 2, 3, 4, 5, 6, 7, 8]) + >>> torch.flatten(t, start_dim=1) + tensor([[1, 2, 3, 4], + [5, 6, 7, 8]]) + """ + +def flip(input: Tensor, dims: _size) -> Tensor: + r""" + flip(input, dims) -> Tensor + + Reverse the order of an n-D tensor along given axis in dims. + + .. note:: + `torch.flip` makes a copy of :attr:`input`'s data. This is different from NumPy's `np.flip`, + which returns a view in constant time. Since copying a tensor's data is more work than viewing that data, + `torch.flip` is expected to be slower than `np.flip`. + + Args: + input (Tensor): the input tensor. + dims (a list or tuple): axis to flip on + + Example:: + + >>> x = torch.arange(8).view(2, 2, 2) + >>> x + tensor([[[ 0, 1], + [ 2, 3]], + + [[ 4, 5], + [ 6, 7]]]) + >>> torch.flip(x, [0, 1]) + tensor([[[ 6, 7], + [ 4, 5]], + + [[ 2, 3], + [ 0, 1]]]) + """ + +def fliplr(input: Tensor) -> Tensor: + r""" + fliplr(input) -> Tensor + + Flip tensor in the left/right direction, returning a new tensor. + + Flip the entries in each row in the left/right direction. + Columns are preserved, but appear in a different order than before. + + Note: + Requires the tensor to be at least 2-D. + + .. note:: + `torch.fliplr` makes a copy of :attr:`input`'s data. This is different from NumPy's `np.fliplr`, + which returns a view in constant time. Since copying a tensor's data is more work than viewing that data, + `torch.fliplr` is expected to be slower than `np.fliplr`. + + Args: + input (Tensor): Must be at least 2-dimensional. + + Example:: + + >>> x = torch.arange(4).view(2, 2) + >>> x + tensor([[0, 1], + [2, 3]]) + >>> torch.fliplr(x) + tensor([[1, 0], + [3, 2]]) + """ + +def flipud(input: Tensor) -> Tensor: + r""" + flipud(input) -> Tensor + + Flip tensor in the up/down direction, returning a new tensor. + + Flip the entries in each column in the up/down direction. + Rows are preserved, but appear in a different order than before. + + Note: + Requires the tensor to be at least 1-D. + + .. note:: + `torch.flipud` makes a copy of :attr:`input`'s data. This is different from NumPy's `np.flipud`, + which returns a view in constant time. Since copying a tensor's data is more work than viewing that data, + `torch.flipud` is expected to be slower than `np.flipud`. + + Args: + input (Tensor): Must be at least 1-dimensional. + + Example:: + + >>> x = torch.arange(4).view(2, 2) + >>> x + tensor([[0, 1], + [2, 3]]) + >>> torch.flipud(x) + tensor([[2, 3], + [0, 1]]) + """ + +@overload +def float_power( + input: Tensor, + exponent: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + float_power(input, exponent, *, out=None) -> Tensor + + Raises :attr:`input` to the power of :attr:`exponent`, elementwise, in double precision. + If neither input is complex returns a ``torch.float64`` tensor, + and if one or more inputs is complex returns a ``torch.complex128`` tensor. + + .. note:: + This function always computes in double precision, unlike :func:`torch.pow`, + which implements more typical :ref:`type promotion `. + This is useful when the computation needs to be performed in a wider or more precise dtype, + or the results of the computation may contain fractional values not representable in the input dtypes, + like when an integer base is raised to a negative integer exponent. + + Args: + input (Tensor or Number): the base value(s) + exponent (Tensor or Number): the exponent value(s) + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randint(10, (4,)) + >>> a + tensor([6, 4, 7, 1]) + >>> torch.float_power(a, 2) + tensor([36., 16., 49., 1.], dtype=torch.float64) + + >>> a = torch.arange(1, 5) + >>> a + tensor([ 1, 2, 3, 4]) + >>> exp = torch.tensor([2, -3, 4, -5]) + >>> exp + tensor([ 2, -3, 4, -5]) + >>> torch.float_power(a, exp) + tensor([1.0000e+00, 1.2500e-01, 8.1000e+01, 9.7656e-04], dtype=torch.float64) + """ + +@overload +def float_power( + self: Number | _complex, + exponent: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + float_power(input, exponent, *, out=None) -> Tensor + + Raises :attr:`input` to the power of :attr:`exponent`, elementwise, in double precision. + If neither input is complex returns a ``torch.float64`` tensor, + and if one or more inputs is complex returns a ``torch.complex128`` tensor. + + .. note:: + This function always computes in double precision, unlike :func:`torch.pow`, + which implements more typical :ref:`type promotion `. + This is useful when the computation needs to be performed in a wider or more precise dtype, + or the results of the computation may contain fractional values not representable in the input dtypes, + like when an integer base is raised to a negative integer exponent. + + Args: + input (Tensor or Number): the base value(s) + exponent (Tensor or Number): the exponent value(s) + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randint(10, (4,)) + >>> a + tensor([6, 4, 7, 1]) + >>> torch.float_power(a, 2) + tensor([36., 16., 49., 1.], dtype=torch.float64) + + >>> a = torch.arange(1, 5) + >>> a + tensor([ 1, 2, 3, 4]) + >>> exp = torch.tensor([2, -3, 4, -5]) + >>> exp + tensor([ 2, -3, 4, -5]) + >>> torch.float_power(a, exp) + tensor([1.0000e+00, 1.2500e-01, 8.1000e+01, 9.7656e-04], dtype=torch.float64) + """ + +@overload +def float_power( + input: Tensor, + exponent: Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + float_power(input, exponent, *, out=None) -> Tensor + + Raises :attr:`input` to the power of :attr:`exponent`, elementwise, in double precision. + If neither input is complex returns a ``torch.float64`` tensor, + and if one or more inputs is complex returns a ``torch.complex128`` tensor. + + .. note:: + This function always computes in double precision, unlike :func:`torch.pow`, + which implements more typical :ref:`type promotion `. + This is useful when the computation needs to be performed in a wider or more precise dtype, + or the results of the computation may contain fractional values not representable in the input dtypes, + like when an integer base is raised to a negative integer exponent. + + Args: + input (Tensor or Number): the base value(s) + exponent (Tensor or Number): the exponent value(s) + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randint(10, (4,)) + >>> a + tensor([6, 4, 7, 1]) + >>> torch.float_power(a, 2) + tensor([36., 16., 49., 1.], dtype=torch.float64) + + >>> a = torch.arange(1, 5) + >>> a + tensor([ 1, 2, 3, 4]) + >>> exp = torch.tensor([2, -3, 4, -5]) + >>> exp + tensor([ 2, -3, 4, -5]) + >>> torch.float_power(a, exp) + tensor([1.0000e+00, 1.2500e-01, 8.1000e+01, 9.7656e-04], dtype=torch.float64) + """ + +def floor(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + floor(input, *, out=None) -> Tensor + + Returns a new tensor with the floor of the elements of :attr:`input`, + the largest integer less than or equal to each element. + + For integer inputs, follows the array-api convention of returning a + copy of the input tensor. + + .. math:: + \text{out}_{i} = \left\lfloor \text{input}_{i} \right\rfloor + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-0.8166, 1.5308, -0.2530, -0.2091]) + >>> torch.floor(a) + tensor([-1., 1., -1., -1.]) + """ + +def floor_(input: Tensor) -> Tensor: ... +def floor_divide( + input: Tensor | Number, + other: Tensor | Number, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + floor_divide(input, other, *, out=None) -> Tensor + + .. note:: + + Before PyTorch 1.13 :func:`torch.floor_divide` incorrectly performed + truncation division. To restore the previous behavior use + :func:`torch.div` with ``rounding_mode='trunc'``. + + Computes :attr:`input` divided by :attr:`other`, elementwise, and floors + the result. + + .. math:: + \text{{out}}_i = \text{floor} \left( \frac{{\text{{input}}_i}}{{\text{{other}}_i}} \right) + + + + Supports broadcasting to a common shape, type promotion, and integer and float inputs. + + Args: + input (Tensor or Number): the dividend + other (Tensor or Number): the divisor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([4.0, 3.0]) + >>> b = torch.tensor([2.0, 2.0]) + >>> torch.floor_divide(a, b) + tensor([2.0, 1.0]) + >>> torch.floor_divide(a, 1.4) + tensor([2.0, 2.0]) + """ + +def fmax( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + fmax(input, other, *, out=None) -> Tensor + + Computes the element-wise maximum of :attr:`input` and :attr:`other`. + + This is like :func:`torch.maximum` except it handles NaNs differently: + if exactly one of the two elements being compared is a NaN then the non-NaN element is taken as the maximum. + Only if both elements are NaN is NaN propagated. + + This function is a wrapper around C++'s ``std::fmax`` and is similar to NumPy's ``fmax`` function. + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer and floating-point inputs. + + Args: + input (Tensor): the input tensor. + other (Tensor): the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([9.7, float('nan'), 3.1, float('nan')]) + >>> b = torch.tensor([-2.2, 0.5, float('nan'), float('nan')]) + >>> torch.fmax(a, b) + tensor([9.7000, 0.5000, 3.1000, nan]) + """ + +def fmin( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + fmin(input, other, *, out=None) -> Tensor + + Computes the element-wise minimum of :attr:`input` and :attr:`other`. + + This is like :func:`torch.minimum` except it handles NaNs differently: + if exactly one of the two elements being compared is a NaN then the non-NaN element is taken as the minimum. + Only if both elements are NaN is NaN propagated. + + This function is a wrapper around C++'s ``std::fmin`` and is similar to NumPy's ``fmin`` function. + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer and floating-point inputs. + + Args: + input (Tensor): the input tensor. + other (Tensor): the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([2.2, float('nan'), 2.1, float('nan')]) + >>> b = torch.tensor([-9.3, 0.1, float('nan'), float('nan')]) + >>> torch.fmin(a, b) + tensor([-9.3000, 0.1000, 2.1000, nan]) + """ + +@overload +def fmod( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + fmod(input, other, *, out=None) -> Tensor + + Applies C++'s `std::fmod `_ entrywise. + The result has the same sign as the dividend :attr:`input` and its absolute value + is less than that of :attr:`other`. + + This function may be defined in terms of :func:`torch.div` as + + .. code:: python + + torch.fmod(a, b) == a - a.div(b, rounding_mode="trunc") * b + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer and float inputs. + + .. note:: + + When the divisor is zero, returns ``NaN`` for floating point dtypes + on both CPU and GPU; raises ``RuntimeError`` for integer division by + zero on CPU; Integer division by zero on GPU may return any value. + + .. note:: + + Complex inputs are not supported. In some cases, it is not mathematically + possible to satisfy the definition of a modulo operation with complex numbers. + + .. seealso:: + + :func:`torch.remainder` which implements Python's modulus operator. + This one is defined using division rounding down the result. + + Args: + input (Tensor): the dividend + other (Tensor or Scalar): the divisor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.fmod(torch.tensor([-3., -2, -1, 1, 2, 3]), 2) + tensor([-1., -0., -1., 1., 0., 1.]) + >>> torch.fmod(torch.tensor([1, 2, 3, 4, 5]), -1.5) + tensor([1.0000, 0.5000, 0.0000, 1.0000, 0.5000]) + """ + +@overload +def fmod( + input: Tensor, + other: Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + fmod(input, other, *, out=None) -> Tensor + + Applies C++'s `std::fmod `_ entrywise. + The result has the same sign as the dividend :attr:`input` and its absolute value + is less than that of :attr:`other`. + + This function may be defined in terms of :func:`torch.div` as + + .. code:: python + + torch.fmod(a, b) == a - a.div(b, rounding_mode="trunc") * b + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer and float inputs. + + .. note:: + + When the divisor is zero, returns ``NaN`` for floating point dtypes + on both CPU and GPU; raises ``RuntimeError`` for integer division by + zero on CPU; Integer division by zero on GPU may return any value. + + .. note:: + + Complex inputs are not supported. In some cases, it is not mathematically + possible to satisfy the definition of a modulo operation with complex numbers. + + .. seealso:: + + :func:`torch.remainder` which implements Python's modulus operator. + This one is defined using division rounding down the result. + + Args: + input (Tensor): the dividend + other (Tensor or Scalar): the divisor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.fmod(torch.tensor([-3., -2, -1, 1, 2, 3]), 2) + tensor([-1., -0., -1., 1., 0., 1.]) + >>> torch.fmod(torch.tensor([1, 2, 3, 4, 5]), -1.5) + tensor([1.0000, 0.5000, 0.0000, 1.0000, 0.5000]) + """ + +def frac(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + frac(input, *, out=None) -> Tensor + + Computes the fractional portion of each element in :attr:`input`. + + .. math:: + \text{out}_{i} = \text{input}_{i} - \left\lfloor |\text{input}_{i}| \right\rfloor * \operatorname{sgn}(\text{input}_{i}) + + Example:: + + >>> torch.frac(torch.tensor([1, 2.5, -3.2])) + tensor([ 0.0000, 0.5000, -0.2000]) + """ + +def frac_(input: Tensor) -> Tensor: ... +def frexp( + input: Tensor, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.frexp: + r""" + frexp(input, *, out=None) -> (Tensor mantissa, Tensor exponent) + + Decomposes :attr:`input` into mantissa and exponent tensors + such that :math:`\text{input} = \text{mantissa} \times 2^{\text{exponent}}`. + + The range of mantissa is the open interval (-1, 1). + + Supports float inputs. + + Args: + input (Tensor): the input tensor + + + Keyword args: + out (tuple, optional): the output tensors + + Example:: + + >>> x = torch.arange(9.) + >>> mantissa, exponent = torch.frexp(x) + >>> mantissa + tensor([0.0000, 0.5000, 0.5000, 0.7500, 0.5000, 0.6250, 0.7500, 0.8750, 0.5000]) + >>> exponent + tensor([0, 1, 2, 2, 3, 3, 3, 3, 4], dtype=torch.int32) + >>> torch.ldexp(mantissa, exponent) + tensor([0., 1., 2., 3., 4., 5., 6., 7., 8.]) + """ + +def frobenius_norm( + input: Tensor, + dim: _int | _size, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: ... +def from_file( + filename: str, + shared: _bool | None = None, + size: _int | None = 0, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + from_file(filename, shared=None, size=0, *, dtype=None, layout=None, device=None, pin_memory=False) + + Creates a CPU tensor with a storage backed by a memory-mapped file. + + If ``shared`` is True, then memory is shared between processes. All changes are written to the file. + If ``shared`` is False, then changes to the tensor do not affect the file. + + ``size`` is the number of elements in the Tensor. If ``shared`` is ``False``, then the file must contain + at least ``size * sizeof(dtype)`` bytes. If ``shared`` is ``True`` the file will be created if needed. + + .. note:: + Only CPU tensors can be mapped to files. + + .. note:: + For now, tensors with storages backed by a memory-mapped file cannot be created in pinned memory. + + + Args: + filename (str): file name to map + shared (bool): whether to share memory (whether ``MAP_SHARED`` or ``MAP_PRIVATE`` is passed to the + underlying `mmap(2) call `_) + size (int): number of elements in the tensor + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> t = torch.randn(2, 5, dtype=torch.float64) + >>> t.numpy().tofile('storage.pt') + >>> t_mapped = torch.from_file('storage.pt', shared=False, size=10, dtype=torch.float64) + """ + +def from_numpy(ndarray) -> Tensor: + r""" + from_numpy(ndarray) -> Tensor + + Creates a :class:`Tensor` from a :class:`numpy.ndarray`. + + The returned tensor and :attr:`ndarray` share the same memory. Modifications to + the tensor will be reflected in the :attr:`ndarray` and vice versa. The returned + tensor is not resizable. + + It currently accepts :attr:`ndarray` with dtypes of ``numpy.float64``, + ``numpy.float32``, ``numpy.float16``, ``numpy.complex64``, ``numpy.complex128``, + ``numpy.int64``, ``numpy.int32``, ``numpy.int16``, ``numpy.int8``, ``numpy.uint8``, + and ``bool``. + + .. warning:: + Writing to a tensor created from a read-only NumPy array is not supported and will result in undefined behavior. + + Example:: + + >>> a = numpy.array([1, 2, 3]) + >>> t = torch.from_numpy(a) + >>> t + tensor([ 1, 2, 3]) + >>> t[0] = -1 + >>> a + array([-1, 2, 3]) + """ + +def frombuffer( + buffer: Any, + *, + dtype: _dtype, + count: int = -1, + offset: int = 0, + requires_grad: _bool = False, +) -> Tensor: + r""" + frombuffer(buffer, *, dtype, count=-1, offset=0, requires_grad=False) -> Tensor + + Creates a 1-dimensional :class:`Tensor` from an object that implements + the Python buffer protocol. + + Skips the first :attr:`offset` bytes in the buffer, and interprets the rest of + the raw bytes as a 1-dimensional tensor of type :attr:`dtype` with :attr:`count` + elements. + + Note that either of the following must be true: + + 1. :attr:`count` is a positive non-zero number, and the total number of bytes + in the buffer is more than :attr:`offset` plus :attr:`count` times the size + (in bytes) of :attr:`dtype`. + + 2. :attr:`count` is negative, and the length (number of bytes) of the buffer + subtracted by the :attr:`offset` is a multiple of the size (in bytes) of + :attr:`dtype`. + + The returned tensor and buffer share the same memory. Modifications to + the tensor will be reflected in the buffer and vice versa. The returned + tensor is not resizable. + + .. note:: + This function increments the reference count for the object that + owns the shared memory. Therefore, such memory will not be deallocated + before the returned tensor goes out of scope. + + .. warning:: + This function's behavior is undefined when passed an object implementing + the buffer protocol whose data is not on the CPU. Doing so is likely to + cause a segmentation fault. + + .. warning:: + This function does not try to infer the :attr:`dtype` (hence, it is not + optional). Passing a different :attr:`dtype` than its source may result + in unexpected behavior. + + Args: + buffer (object): a Python object that exposes the buffer interface. + + Keyword args: + dtype (:class:`torch.dtype`): the desired data type of returned tensor. + count (int, optional): the number of desired elements to be read. + If negative, all the elements (until the end of the buffer) will be + read. Default: -1. + offset (int, optional): the number of bytes to skip at the start of + the buffer. Default: 0. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> import array + >>> a = array.array('i', [1, 2, 3]) + >>> t = torch.frombuffer(a, dtype=torch.int32) + >>> t + tensor([ 1, 2, 3]) + >>> t[0] = -1 + >>> a + array([-1, 2, 3]) + + >>> # Interprets the signed char bytes as 32-bit integers. + >>> # Each 4 signed char elements will be interpreted as + >>> # 1 signed 32-bit integer. + >>> import array + >>> a = array.array('b', [-1, 0, 0, 0]) + >>> torch.frombuffer(a, dtype=torch.int32) + tensor([255], dtype=torch.int32) + """ + +@overload +def full( + size: _size, + fill_value: Number | _complex, + *, + out: Tensor | None = None, + layout: _layout = strided, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + pin_memory: _bool = False, +) -> Tensor: + r""" + full(size, fill_value, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Creates a tensor of size :attr:`size` filled with :attr:`fill_value`. The + tensor's dtype is inferred from :attr:`fill_value`. + + Args: + size (int...): a list, tuple, or :class:`torch.Size` of integers defining the + shape of the output tensor. + fill_value (Scalar): the value to fill the output tensor with. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.full((2, 3), 3.141592) + tensor([[ 3.1416, 3.1416, 3.1416], + [ 3.1416, 3.1416, 3.1416]]) + """ + +@overload +def full( + size: _size, + fill_value: Number | _complex, + *, + names: list[str | None], + layout: _layout = strided, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + pin_memory: _bool = False, +) -> Tensor: + r""" + full(size, fill_value, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Creates a tensor of size :attr:`size` filled with :attr:`fill_value`. The + tensor's dtype is inferred from :attr:`fill_value`. + + Args: + size (int...): a list, tuple, or :class:`torch.Size` of integers defining the + shape of the output tensor. + fill_value (Scalar): the value to fill the output tensor with. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.full((2, 3), 3.141592) + tensor([[ 3.1416, 3.1416, 3.1416], + [ 3.1416, 3.1416, 3.1416]]) + """ + +@overload +def full( + size: Sequence[_int | SymInt], + fill_value: Number | _complex, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + full(size, fill_value, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Creates a tensor of size :attr:`size` filled with :attr:`fill_value`. The + tensor's dtype is inferred from :attr:`fill_value`. + + Args: + size (int...): a list, tuple, or :class:`torch.Size` of integers defining the + shape of the output tensor. + fill_value (Scalar): the value to fill the output tensor with. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.full((2, 3), 3.141592) + tensor([[ 3.1416, 3.1416, 3.1416], + [ 3.1416, 3.1416, 3.1416]]) + """ + +@overload +def full( + size: _size, + fill_value: Number | _complex, + *, + names: Sequence[str | EllipsisType | None] | None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + full(size, fill_value, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Creates a tensor of size :attr:`size` filled with :attr:`fill_value`. The + tensor's dtype is inferred from :attr:`fill_value`. + + Args: + size (int...): a list, tuple, or :class:`torch.Size` of integers defining the + shape of the output tensor. + fill_value (Scalar): the value to fill the output tensor with. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.full((2, 3), 3.141592) + tensor([[ 3.1416, 3.1416, 3.1416], + [ 3.1416, 3.1416, 3.1416]]) + """ + +def full_like( + input: Tensor, + fill_value: Number | _complex, + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + full_like(input, fill_value, \*, dtype=None, layout=torch.strided, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same size as :attr:`input` filled with :attr:`fill_value`. + ``torch.full_like(input, fill_value)`` is equivalent to + ``torch.full(input.size(), fill_value, dtype=input.dtype, layout=input.layout, device=input.device)``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + fill_value: the number to fill the output tensor with. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + + Example:: + + >>> x = torch.ones(2, 3) + >>> torch.full_like(x, 3.141592) + tensor([[ 3.1416, 3.1416, 3.1416], + [ 3.1416, 3.1416, 3.1416]]) + >>> torch.full_like(x, 7) + tensor([[7., 7., 7.], + [7., 7., 7.]]) + >>> torch.full_like(x, 0.5, dtype=torch.int32) + tensor([[0, 0, 0], + [0, 0, 0]], dtype=torch.int32) + >>> y = torch.randn(3, 4, dtype=torch.float64) + >>> torch.full_like(y, -1.0) + tensor([[-1., -1., -1., -1.], + [-1., -1., -1., -1.], + [-1., -1., -1., -1.]], dtype=torch.float64) + """ + +def fused_moving_avg_obs_fake_quant( + input: Tensor, + observer_on: Tensor, + fake_quant_on: Tensor, + running_min: Tensor, + running_max: Tensor, + scale: Tensor, + zero_point: Tensor, + averaging_const: _float, + quant_min: _int, + quant_max: _int, + ch_axis: _int, + per_row_fake_quant: _bool = False, + symmetric_quant: _bool = False, +) -> Tensor: ... +@overload +def gather( + input: Tensor, + dim: _int, + index: Tensor, + *, + sparse_grad: _bool = False, + out: Tensor | None = None, +) -> Tensor: + r""" + gather(input, dim, index, *, sparse_grad=False, out=None) -> Tensor + + Gathers values along an axis specified by `dim`. + + For a 3-D tensor the output is specified by:: + + out[i][j][k] = input[index[i][j][k]][j][k] # if dim == 0 + out[i][j][k] = input[i][index[i][j][k]][k] # if dim == 1 + out[i][j][k] = input[i][j][index[i][j][k]] # if dim == 2 + + :attr:`input` and :attr:`index` must have the same number of dimensions. + It is also required that ``index.size(d) <= input.size(d)`` for all + dimensions ``d != dim``. :attr:`out` will have the same shape as :attr:`index`. + Note that ``input`` and ``index`` do not broadcast against each other. + When :attr:`index` is empty, we always return an empty output with the same shape + without further error checking. + + Args: + input (Tensor): the source tensor + dim (int): the axis along which to index + index (LongTensor): the indices of elements to gather + + Keyword arguments: + sparse_grad (bool, optional): If ``True``, gradient w.r.t. :attr:`input` will be a sparse tensor. + out (Tensor, optional): the destination tensor + + Example:: + + >>> t = torch.tensor([[1, 2], [3, 4]]) + >>> torch.gather(t, 1, torch.tensor([[0, 0], [1, 0]])) + tensor([[ 1, 1], + [ 4, 3]]) + """ + +@overload +def gather( + input: Tensor, + dim: str | EllipsisType | None, + index: Tensor, + *, + sparse_grad: _bool = False, + out: Tensor | None = None, +) -> Tensor: + r""" + gather(input, dim, index, *, sparse_grad=False, out=None) -> Tensor + + Gathers values along an axis specified by `dim`. + + For a 3-D tensor the output is specified by:: + + out[i][j][k] = input[index[i][j][k]][j][k] # if dim == 0 + out[i][j][k] = input[i][index[i][j][k]][k] # if dim == 1 + out[i][j][k] = input[i][j][index[i][j][k]] # if dim == 2 + + :attr:`input` and :attr:`index` must have the same number of dimensions. + It is also required that ``index.size(d) <= input.size(d)`` for all + dimensions ``d != dim``. :attr:`out` will have the same shape as :attr:`index`. + Note that ``input`` and ``index`` do not broadcast against each other. + When :attr:`index` is empty, we always return an empty output with the same shape + without further error checking. + + Args: + input (Tensor): the source tensor + dim (int): the axis along which to index + index (LongTensor): the indices of elements to gather + + Keyword arguments: + sparse_grad (bool, optional): If ``True``, gradient w.r.t. :attr:`input` will be a sparse tensor. + out (Tensor, optional): the destination tensor + + Example:: + + >>> t = torch.tensor([[1, 2], [3, 4]]) + >>> torch.gather(t, 1, torch.tensor([[0, 0], [1, 0]])) + tensor([[ 1, 1], + [ 4, 3]]) + """ + +def gcd( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + gcd(input, other, *, out=None) -> Tensor + + Computes the element-wise greatest common divisor (GCD) of :attr:`input` and :attr:`other`. + + Both :attr:`input` and :attr:`other` must have integer types. + + .. note:: + This defines :math:`gcd(0, 0) = 0`. + + Args: + input (Tensor): the input tensor. + other (Tensor): the second input tensor + + Keyword arguments: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([5, 10, 15]) + >>> b = torch.tensor([3, 4, 5]) + >>> torch.gcd(a, b) + tensor([1, 2, 5]) + >>> c = torch.tensor([3]) + >>> torch.gcd(a, c) + tensor([1, 1, 3]) + """ + +def gcd_(input: Tensor, other: Tensor) -> Tensor: ... +@overload +def ge( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + ge(input, other, *, out=None) -> Tensor + + Computes :math:`\text{input} \geq \text{other}` element-wise. + + + The second argument can be a number or a tensor whose shape is + :ref:`broadcastable ` with the first argument. + + Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is greater than or equal to :attr:`other` and False elsewhere + + Example:: + + >>> torch.ge(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[True, True], [False, True]]) + """ + +@overload +def ge( + input: Tensor, + other: Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + ge(input, other, *, out=None) -> Tensor + + Computes :math:`\text{input} \geq \text{other}` element-wise. + + + The second argument can be a number or a tensor whose shape is + :ref:`broadcastable ` with the first argument. + + Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is greater than or equal to :attr:`other` and False elsewhere + + Example:: + + >>> torch.ge(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[True, True], [False, True]]) + """ + +def geqrf( + input: Tensor, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.geqrf: + r""" + geqrf(input, *, out=None) -> (Tensor, Tensor) + + This is a low-level function for calling LAPACK's geqrf directly. This function + returns a namedtuple (a, tau) as defined in `LAPACK documentation for geqrf`_ . + + Computes a QR decomposition of :attr:`input`. + Both `Q` and `R` matrices are stored in the same output tensor `a`. + The elements of `R` are stored on and above the diagonal. + Elementary reflectors (or Householder vectors) implicitly defining matrix `Q` + are stored below the diagonal. + The results of this function can be used together with :func:`torch.linalg.householder_product` + to obtain the `Q` matrix or + with :func:`torch.ormqr`, which uses an implicit representation of the `Q` matrix, + for an efficient matrix-matrix multiplication. + + See `LAPACK documentation for geqrf`_ for further details. + + .. note:: + See also :func:`torch.linalg.qr`, which computes Q and R matrices, and :func:`torch.linalg.lstsq` + with the ``driver="gels"`` option for a function that can solve matrix equations using a QR decomposition. + + Args: + input (Tensor): the input matrix + + Keyword args: + out (tuple, optional): the output tuple of (Tensor, Tensor). Ignored if `None`. Default: `None`. + + .. _LAPACK documentation for geqrf: + http://www.netlib.org/lapack/explore-html/df/dc5/group__variants_g_ecomputational_ga3766ea903391b5cf9008132f7440ec7b.html + """ + +def ger( + input: Tensor, + vec2: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + ger(input, vec2, *, out=None) -> Tensor + + Alias of :func:`torch.outer`. + + .. warning:: + This function is deprecated and will be removed in a future PyTorch release. + Use :func:`torch.outer` instead. + """ + +def get_default_dtype() -> _dtype: + r""" + get_default_dtype() -> torch.dtype + + Get the current default floating point :class:`torch.dtype`. + + Example:: + + >>> torch.get_default_dtype() # initial default for floating point is torch.float32 + torch.float32 + >>> torch.set_default_dtype(torch.float64) + >>> torch.get_default_dtype() # default is now changed to torch.float64 + torch.float64 + """ + +def get_num_interop_threads() -> _int: + r""" + get_num_interop_threads() -> int + + Returns the number of threads used for inter-op parallelism on CPU + (e.g. in JIT interpreter) + """ + +def get_num_threads() -> _int: + r""" + get_num_threads() -> int + + Returns the number of threads used for parallelizing CPU operations + """ + +@overload +def gradient( + input: Tensor, + *, + spacing: Number | _complex | None = None, + dim: _int | None = None, + edge_order: _int = 1, +) -> tuple[Tensor, ...]: + r""" + gradient(input, *, spacing=1, dim=None, edge_order=1) -> List of Tensors + + Estimates the gradient of a function :math:`g : \mathbb{R}^n \rightarrow \mathbb{R}` in + one or more dimensions using the `second-order accurate central differences method + `_ and + either first or second order estimates at the boundaries. + + The gradient of :math:`g` is estimated using samples. By default, when :attr:`spacing` is not + specified, the samples are entirely described by :attr:`input`, and the mapping of input coordinates + to an output is the same as the tensor's mapping of indices to values. For example, for a three-dimensional + :attr:`input` the function described is :math:`g : \mathbb{R}^3 \rightarrow \mathbb{R}`, and + :math:`g(1, 2, 3)\ == input[1, 2, 3]`. + + When :attr:`spacing` is specified, it modifies the relationship between :attr:`input` and input coordinates. + This is detailed in the "Keyword Arguments" section below. + + The gradient is estimated by estimating each partial derivative of :math:`g` independently. This estimation is + accurate if :math:`g` is in :math:`C^3` (it has at least 3 continuous derivatives), and the estimation can be + improved by providing closer samples. Mathematically, the value at each interior point of a partial derivative + is estimated using `Taylor's theorem with remainder `_. + Letting :math:`x` be an interior point with :math:`x-h_l` and :math:`x+h_r` be points neighboring + it to the left and right respectively, :math:`f(x+h_r)` and :math:`f(x-h_l)` can be estimated using: + + .. math:: + \begin{aligned} + f(x+h_r) = f(x) + h_r f'(x) + {h_r}^2 \frac{f''(x)}{2} + {h_r}^3 \frac{f'''(\xi_1)}{6}, \xi_1 \in (x, x+h_r) \\ + f(x-h_l) = f(x) - h_l f'(x) + {h_l}^2 \frac{f''(x)}{2} - {h_l}^3 \frac{f'''(\xi_2)}{6}, \xi_2 \in (x, x-h_l) \\ + \end{aligned} + + Using the fact that :math:`f \in C^3` and solving the linear system, we derive: + + .. math:: + f'(x) \approx \frac{ {h_l}^2 f(x+h_r) - {h_r}^2 f(x-h_l) + + ({h_r}^2-{h_l}^2 ) f(x) }{ {h_r} {h_l}^2 + {h_r}^2 {h_l} } + + .. note:: + We estimate the gradient of functions in complex domain + :math:`g : \mathbb{C}^n \rightarrow \mathbb{C}` in the same way. + + The value of each partial derivative at the boundary points is computed differently. See edge_order below. + + Args: + input (``Tensor``): the tensor that represents the values of the function + + Keyword args: + spacing (``scalar``, ``list of scalar``, ``list of Tensor``, optional): :attr:`spacing` can be used to modify + how the :attr:`input` tensor's indices relate to sample coordinates. If :attr:`spacing` is a scalar then + the indices are multiplied by the scalar to produce the coordinates. For example, if :attr:`spacing=2` the + indices (1, 2, 3) become coordinates (2, 4, 6). If :attr:`spacing` is a list of scalars then the corresponding + indices are multiplied. For example, if :attr:`spacing=(2, -1, 3)` the indices (1, 2, 3) become coordinates (2, -2, 9). + Finally, if :attr:`spacing` is a list of one-dimensional tensors then each tensor specifies the coordinates for + the corresponding dimension. For example, if the indices are (1, 2, 3) and the tensors are (t0, t1, t2), then + the coordinates are (t0[1], t1[2], t2[3]) + + dim (``int``, ``list of int``, optional): the dimension or dimensions to approximate the gradient over. By default + the partial gradient in every dimension is computed. Note that when :attr:`dim` is specified the elements of + the :attr:`spacing` argument must correspond with the specified dims." + + edge_order (``int``, optional): 1 or 2, for `first-order + `_ or + `second-order `_ + estimation of the boundary ("edge") values, respectively. Note that when :attr:`edge_order` is specified, each + dimension size of :attr:`input` should be at least edge_order+1 + + Examples:: + + >>> # Estimates the gradient of f(x)=x^2 at points [-2, -1, 2, 4] + >>> coordinates = (torch.tensor([-2., -1., 1., 4.]),) + >>> values = torch.tensor([4., 1., 1., 16.], ) + >>> torch.gradient(values, spacing = coordinates) + (tensor([-3., -2., 2., 5.]),) + + >>> # Estimates the gradient of the R^2 -> R function whose samples are + >>> # described by the tensor t. Implicit coordinates are [0, 1] for the outermost + >>> # dimension and [0, 1, 2, 3] for the innermost dimension, and function estimates + >>> # partial derivative for both dimensions. + >>> t = torch.tensor([[1, 2, 4, 8], [10, 20, 40, 80]]) + >>> torch.gradient(t) + (tensor([[ 9., 18., 36., 72.], + [ 9., 18., 36., 72.]]), + tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]])) + + >>> # A scalar value for spacing modifies the relationship between tensor indices + >>> # and input coordinates by multiplying the indices to find the + >>> # coordinates. For example, below the indices of the innermost + >>> # 0, 1, 2, 3 translate to coordinates of [0, 2, 4, 6], and the indices of + >>> # the outermost dimension 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = 2.0) # dim = None (implicitly [0, 1]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.5000, 0.7500, 1.5000, 2.0000], + [ 5.0000, 7.5000, 15.0000, 20.0000]])) + >>> # doubling the spacing between samples halves the estimated partial gradients. + + >>> + >>> # Estimates only the partial derivative for dimension 1 + >>> torch.gradient(t, dim = 1) # spacing = None (implicitly 1.) + (tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]]),) + + >>> # When spacing is a list of scalars, the relationship between the tensor + >>> # indices and input coordinates changes based on dimension. + >>> # For example, below, the indices of the innermost dimension 0, 1, 2, 3 translate + >>> # to coordinates of [0, 3, 6, 9], and the indices of the outermost dimension + >>> # 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = [3., 2.]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + + >>> # The following example is a replication of the previous one with explicit + >>> # coordinates. + >>> coords = (torch.tensor([0, 2]), torch.tensor([0, 3, 6, 9])) + >>> torch.gradient(t, spacing = coords) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + """ + +@overload +def gradient( + input: Tensor, + *, + spacing: Sequence[Number | _complex], + dim: _int | None = None, + edge_order: _int = 1, +) -> tuple[Tensor, ...]: + r""" + gradient(input, *, spacing=1, dim=None, edge_order=1) -> List of Tensors + + Estimates the gradient of a function :math:`g : \mathbb{R}^n \rightarrow \mathbb{R}` in + one or more dimensions using the `second-order accurate central differences method + `_ and + either first or second order estimates at the boundaries. + + The gradient of :math:`g` is estimated using samples. By default, when :attr:`spacing` is not + specified, the samples are entirely described by :attr:`input`, and the mapping of input coordinates + to an output is the same as the tensor's mapping of indices to values. For example, for a three-dimensional + :attr:`input` the function described is :math:`g : \mathbb{R}^3 \rightarrow \mathbb{R}`, and + :math:`g(1, 2, 3)\ == input[1, 2, 3]`. + + When :attr:`spacing` is specified, it modifies the relationship between :attr:`input` and input coordinates. + This is detailed in the "Keyword Arguments" section below. + + The gradient is estimated by estimating each partial derivative of :math:`g` independently. This estimation is + accurate if :math:`g` is in :math:`C^3` (it has at least 3 continuous derivatives), and the estimation can be + improved by providing closer samples. Mathematically, the value at each interior point of a partial derivative + is estimated using `Taylor's theorem with remainder `_. + Letting :math:`x` be an interior point with :math:`x-h_l` and :math:`x+h_r` be points neighboring + it to the left and right respectively, :math:`f(x+h_r)` and :math:`f(x-h_l)` can be estimated using: + + .. math:: + \begin{aligned} + f(x+h_r) = f(x) + h_r f'(x) + {h_r}^2 \frac{f''(x)}{2} + {h_r}^3 \frac{f'''(\xi_1)}{6}, \xi_1 \in (x, x+h_r) \\ + f(x-h_l) = f(x) - h_l f'(x) + {h_l}^2 \frac{f''(x)}{2} - {h_l}^3 \frac{f'''(\xi_2)}{6}, \xi_2 \in (x, x-h_l) \\ + \end{aligned} + + Using the fact that :math:`f \in C^3` and solving the linear system, we derive: + + .. math:: + f'(x) \approx \frac{ {h_l}^2 f(x+h_r) - {h_r}^2 f(x-h_l) + + ({h_r}^2-{h_l}^2 ) f(x) }{ {h_r} {h_l}^2 + {h_r}^2 {h_l} } + + .. note:: + We estimate the gradient of functions in complex domain + :math:`g : \mathbb{C}^n \rightarrow \mathbb{C}` in the same way. + + The value of each partial derivative at the boundary points is computed differently. See edge_order below. + + Args: + input (``Tensor``): the tensor that represents the values of the function + + Keyword args: + spacing (``scalar``, ``list of scalar``, ``list of Tensor``, optional): :attr:`spacing` can be used to modify + how the :attr:`input` tensor's indices relate to sample coordinates. If :attr:`spacing` is a scalar then + the indices are multiplied by the scalar to produce the coordinates. For example, if :attr:`spacing=2` the + indices (1, 2, 3) become coordinates (2, 4, 6). If :attr:`spacing` is a list of scalars then the corresponding + indices are multiplied. For example, if :attr:`spacing=(2, -1, 3)` the indices (1, 2, 3) become coordinates (2, -2, 9). + Finally, if :attr:`spacing` is a list of one-dimensional tensors then each tensor specifies the coordinates for + the corresponding dimension. For example, if the indices are (1, 2, 3) and the tensors are (t0, t1, t2), then + the coordinates are (t0[1], t1[2], t2[3]) + + dim (``int``, ``list of int``, optional): the dimension or dimensions to approximate the gradient over. By default + the partial gradient in every dimension is computed. Note that when :attr:`dim` is specified the elements of + the :attr:`spacing` argument must correspond with the specified dims." + + edge_order (``int``, optional): 1 or 2, for `first-order + `_ or + `second-order `_ + estimation of the boundary ("edge") values, respectively. Note that when :attr:`edge_order` is specified, each + dimension size of :attr:`input` should be at least edge_order+1 + + Examples:: + + >>> # Estimates the gradient of f(x)=x^2 at points [-2, -1, 2, 4] + >>> coordinates = (torch.tensor([-2., -1., 1., 4.]),) + >>> values = torch.tensor([4., 1., 1., 16.], ) + >>> torch.gradient(values, spacing = coordinates) + (tensor([-3., -2., 2., 5.]),) + + >>> # Estimates the gradient of the R^2 -> R function whose samples are + >>> # described by the tensor t. Implicit coordinates are [0, 1] for the outermost + >>> # dimension and [0, 1, 2, 3] for the innermost dimension, and function estimates + >>> # partial derivative for both dimensions. + >>> t = torch.tensor([[1, 2, 4, 8], [10, 20, 40, 80]]) + >>> torch.gradient(t) + (tensor([[ 9., 18., 36., 72.], + [ 9., 18., 36., 72.]]), + tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]])) + + >>> # A scalar value for spacing modifies the relationship between tensor indices + >>> # and input coordinates by multiplying the indices to find the + >>> # coordinates. For example, below the indices of the innermost + >>> # 0, 1, 2, 3 translate to coordinates of [0, 2, 4, 6], and the indices of + >>> # the outermost dimension 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = 2.0) # dim = None (implicitly [0, 1]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.5000, 0.7500, 1.5000, 2.0000], + [ 5.0000, 7.5000, 15.0000, 20.0000]])) + >>> # doubling the spacing between samples halves the estimated partial gradients. + + >>> + >>> # Estimates only the partial derivative for dimension 1 + >>> torch.gradient(t, dim = 1) # spacing = None (implicitly 1.) + (tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]]),) + + >>> # When spacing is a list of scalars, the relationship between the tensor + >>> # indices and input coordinates changes based on dimension. + >>> # For example, below, the indices of the innermost dimension 0, 1, 2, 3 translate + >>> # to coordinates of [0, 3, 6, 9], and the indices of the outermost dimension + >>> # 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = [3., 2.]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + + >>> # The following example is a replication of the previous one with explicit + >>> # coordinates. + >>> coords = (torch.tensor([0, 2]), torch.tensor([0, 3, 6, 9])) + >>> torch.gradient(t, spacing = coords) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + """ + +@overload +def gradient( + input: Tensor, + *, + spacing: Sequence[Number | _complex], + dim: _size, + edge_order: _int = 1, +) -> tuple[Tensor, ...]: + r""" + gradient(input, *, spacing=1, dim=None, edge_order=1) -> List of Tensors + + Estimates the gradient of a function :math:`g : \mathbb{R}^n \rightarrow \mathbb{R}` in + one or more dimensions using the `second-order accurate central differences method + `_ and + either first or second order estimates at the boundaries. + + The gradient of :math:`g` is estimated using samples. By default, when :attr:`spacing` is not + specified, the samples are entirely described by :attr:`input`, and the mapping of input coordinates + to an output is the same as the tensor's mapping of indices to values. For example, for a three-dimensional + :attr:`input` the function described is :math:`g : \mathbb{R}^3 \rightarrow \mathbb{R}`, and + :math:`g(1, 2, 3)\ == input[1, 2, 3]`. + + When :attr:`spacing` is specified, it modifies the relationship between :attr:`input` and input coordinates. + This is detailed in the "Keyword Arguments" section below. + + The gradient is estimated by estimating each partial derivative of :math:`g` independently. This estimation is + accurate if :math:`g` is in :math:`C^3` (it has at least 3 continuous derivatives), and the estimation can be + improved by providing closer samples. Mathematically, the value at each interior point of a partial derivative + is estimated using `Taylor's theorem with remainder `_. + Letting :math:`x` be an interior point with :math:`x-h_l` and :math:`x+h_r` be points neighboring + it to the left and right respectively, :math:`f(x+h_r)` and :math:`f(x-h_l)` can be estimated using: + + .. math:: + \begin{aligned} + f(x+h_r) = f(x) + h_r f'(x) + {h_r}^2 \frac{f''(x)}{2} + {h_r}^3 \frac{f'''(\xi_1)}{6}, \xi_1 \in (x, x+h_r) \\ + f(x-h_l) = f(x) - h_l f'(x) + {h_l}^2 \frac{f''(x)}{2} - {h_l}^3 \frac{f'''(\xi_2)}{6}, \xi_2 \in (x, x-h_l) \\ + \end{aligned} + + Using the fact that :math:`f \in C^3` and solving the linear system, we derive: + + .. math:: + f'(x) \approx \frac{ {h_l}^2 f(x+h_r) - {h_r}^2 f(x-h_l) + + ({h_r}^2-{h_l}^2 ) f(x) }{ {h_r} {h_l}^2 + {h_r}^2 {h_l} } + + .. note:: + We estimate the gradient of functions in complex domain + :math:`g : \mathbb{C}^n \rightarrow \mathbb{C}` in the same way. + + The value of each partial derivative at the boundary points is computed differently. See edge_order below. + + Args: + input (``Tensor``): the tensor that represents the values of the function + + Keyword args: + spacing (``scalar``, ``list of scalar``, ``list of Tensor``, optional): :attr:`spacing` can be used to modify + how the :attr:`input` tensor's indices relate to sample coordinates. If :attr:`spacing` is a scalar then + the indices are multiplied by the scalar to produce the coordinates. For example, if :attr:`spacing=2` the + indices (1, 2, 3) become coordinates (2, 4, 6). If :attr:`spacing` is a list of scalars then the corresponding + indices are multiplied. For example, if :attr:`spacing=(2, -1, 3)` the indices (1, 2, 3) become coordinates (2, -2, 9). + Finally, if :attr:`spacing` is a list of one-dimensional tensors then each tensor specifies the coordinates for + the corresponding dimension. For example, if the indices are (1, 2, 3) and the tensors are (t0, t1, t2), then + the coordinates are (t0[1], t1[2], t2[3]) + + dim (``int``, ``list of int``, optional): the dimension or dimensions to approximate the gradient over. By default + the partial gradient in every dimension is computed. Note that when :attr:`dim` is specified the elements of + the :attr:`spacing` argument must correspond with the specified dims." + + edge_order (``int``, optional): 1 or 2, for `first-order + `_ or + `second-order `_ + estimation of the boundary ("edge") values, respectively. Note that when :attr:`edge_order` is specified, each + dimension size of :attr:`input` should be at least edge_order+1 + + Examples:: + + >>> # Estimates the gradient of f(x)=x^2 at points [-2, -1, 2, 4] + >>> coordinates = (torch.tensor([-2., -1., 1., 4.]),) + >>> values = torch.tensor([4., 1., 1., 16.], ) + >>> torch.gradient(values, spacing = coordinates) + (tensor([-3., -2., 2., 5.]),) + + >>> # Estimates the gradient of the R^2 -> R function whose samples are + >>> # described by the tensor t. Implicit coordinates are [0, 1] for the outermost + >>> # dimension and [0, 1, 2, 3] for the innermost dimension, and function estimates + >>> # partial derivative for both dimensions. + >>> t = torch.tensor([[1, 2, 4, 8], [10, 20, 40, 80]]) + >>> torch.gradient(t) + (tensor([[ 9., 18., 36., 72.], + [ 9., 18., 36., 72.]]), + tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]])) + + >>> # A scalar value for spacing modifies the relationship between tensor indices + >>> # and input coordinates by multiplying the indices to find the + >>> # coordinates. For example, below the indices of the innermost + >>> # 0, 1, 2, 3 translate to coordinates of [0, 2, 4, 6], and the indices of + >>> # the outermost dimension 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = 2.0) # dim = None (implicitly [0, 1]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.5000, 0.7500, 1.5000, 2.0000], + [ 5.0000, 7.5000, 15.0000, 20.0000]])) + >>> # doubling the spacing between samples halves the estimated partial gradients. + + >>> + >>> # Estimates only the partial derivative for dimension 1 + >>> torch.gradient(t, dim = 1) # spacing = None (implicitly 1.) + (tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]]),) + + >>> # When spacing is a list of scalars, the relationship between the tensor + >>> # indices and input coordinates changes based on dimension. + >>> # For example, below, the indices of the innermost dimension 0, 1, 2, 3 translate + >>> # to coordinates of [0, 3, 6, 9], and the indices of the outermost dimension + >>> # 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = [3., 2.]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + + >>> # The following example is a replication of the previous one with explicit + >>> # coordinates. + >>> coords = (torch.tensor([0, 2]), torch.tensor([0, 3, 6, 9])) + >>> torch.gradient(t, spacing = coords) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + """ + +@overload +def gradient( + input: Tensor, + *, + spacing: tuple[Tensor, ...] | list[Tensor] | None, + dim: _int | None = None, + edge_order: _int = 1, +) -> tuple[Tensor, ...]: + r""" + gradient(input, *, spacing=1, dim=None, edge_order=1) -> List of Tensors + + Estimates the gradient of a function :math:`g : \mathbb{R}^n \rightarrow \mathbb{R}` in + one or more dimensions using the `second-order accurate central differences method + `_ and + either first or second order estimates at the boundaries. + + The gradient of :math:`g` is estimated using samples. By default, when :attr:`spacing` is not + specified, the samples are entirely described by :attr:`input`, and the mapping of input coordinates + to an output is the same as the tensor's mapping of indices to values. For example, for a three-dimensional + :attr:`input` the function described is :math:`g : \mathbb{R}^3 \rightarrow \mathbb{R}`, and + :math:`g(1, 2, 3)\ == input[1, 2, 3]`. + + When :attr:`spacing` is specified, it modifies the relationship between :attr:`input` and input coordinates. + This is detailed in the "Keyword Arguments" section below. + + The gradient is estimated by estimating each partial derivative of :math:`g` independently. This estimation is + accurate if :math:`g` is in :math:`C^3` (it has at least 3 continuous derivatives), and the estimation can be + improved by providing closer samples. Mathematically, the value at each interior point of a partial derivative + is estimated using `Taylor's theorem with remainder `_. + Letting :math:`x` be an interior point with :math:`x-h_l` and :math:`x+h_r` be points neighboring + it to the left and right respectively, :math:`f(x+h_r)` and :math:`f(x-h_l)` can be estimated using: + + .. math:: + \begin{aligned} + f(x+h_r) = f(x) + h_r f'(x) + {h_r}^2 \frac{f''(x)}{2} + {h_r}^3 \frac{f'''(\xi_1)}{6}, \xi_1 \in (x, x+h_r) \\ + f(x-h_l) = f(x) - h_l f'(x) + {h_l}^2 \frac{f''(x)}{2} - {h_l}^3 \frac{f'''(\xi_2)}{6}, \xi_2 \in (x, x-h_l) \\ + \end{aligned} + + Using the fact that :math:`f \in C^3` and solving the linear system, we derive: + + .. math:: + f'(x) \approx \frac{ {h_l}^2 f(x+h_r) - {h_r}^2 f(x-h_l) + + ({h_r}^2-{h_l}^2 ) f(x) }{ {h_r} {h_l}^2 + {h_r}^2 {h_l} } + + .. note:: + We estimate the gradient of functions in complex domain + :math:`g : \mathbb{C}^n \rightarrow \mathbb{C}` in the same way. + + The value of each partial derivative at the boundary points is computed differently. See edge_order below. + + Args: + input (``Tensor``): the tensor that represents the values of the function + + Keyword args: + spacing (``scalar``, ``list of scalar``, ``list of Tensor``, optional): :attr:`spacing` can be used to modify + how the :attr:`input` tensor's indices relate to sample coordinates. If :attr:`spacing` is a scalar then + the indices are multiplied by the scalar to produce the coordinates. For example, if :attr:`spacing=2` the + indices (1, 2, 3) become coordinates (2, 4, 6). If :attr:`spacing` is a list of scalars then the corresponding + indices are multiplied. For example, if :attr:`spacing=(2, -1, 3)` the indices (1, 2, 3) become coordinates (2, -2, 9). + Finally, if :attr:`spacing` is a list of one-dimensional tensors then each tensor specifies the coordinates for + the corresponding dimension. For example, if the indices are (1, 2, 3) and the tensors are (t0, t1, t2), then + the coordinates are (t0[1], t1[2], t2[3]) + + dim (``int``, ``list of int``, optional): the dimension or dimensions to approximate the gradient over. By default + the partial gradient in every dimension is computed. Note that when :attr:`dim` is specified the elements of + the :attr:`spacing` argument must correspond with the specified dims." + + edge_order (``int``, optional): 1 or 2, for `first-order + `_ or + `second-order `_ + estimation of the boundary ("edge") values, respectively. Note that when :attr:`edge_order` is specified, each + dimension size of :attr:`input` should be at least edge_order+1 + + Examples:: + + >>> # Estimates the gradient of f(x)=x^2 at points [-2, -1, 2, 4] + >>> coordinates = (torch.tensor([-2., -1., 1., 4.]),) + >>> values = torch.tensor([4., 1., 1., 16.], ) + >>> torch.gradient(values, spacing = coordinates) + (tensor([-3., -2., 2., 5.]),) + + >>> # Estimates the gradient of the R^2 -> R function whose samples are + >>> # described by the tensor t. Implicit coordinates are [0, 1] for the outermost + >>> # dimension and [0, 1, 2, 3] for the innermost dimension, and function estimates + >>> # partial derivative for both dimensions. + >>> t = torch.tensor([[1, 2, 4, 8], [10, 20, 40, 80]]) + >>> torch.gradient(t) + (tensor([[ 9., 18., 36., 72.], + [ 9., 18., 36., 72.]]), + tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]])) + + >>> # A scalar value for spacing modifies the relationship between tensor indices + >>> # and input coordinates by multiplying the indices to find the + >>> # coordinates. For example, below the indices of the innermost + >>> # 0, 1, 2, 3 translate to coordinates of [0, 2, 4, 6], and the indices of + >>> # the outermost dimension 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = 2.0) # dim = None (implicitly [0, 1]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.5000, 0.7500, 1.5000, 2.0000], + [ 5.0000, 7.5000, 15.0000, 20.0000]])) + >>> # doubling the spacing between samples halves the estimated partial gradients. + + >>> + >>> # Estimates only the partial derivative for dimension 1 + >>> torch.gradient(t, dim = 1) # spacing = None (implicitly 1.) + (tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]]),) + + >>> # When spacing is a list of scalars, the relationship between the tensor + >>> # indices and input coordinates changes based on dimension. + >>> # For example, below, the indices of the innermost dimension 0, 1, 2, 3 translate + >>> # to coordinates of [0, 3, 6, 9], and the indices of the outermost dimension + >>> # 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = [3., 2.]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + + >>> # The following example is a replication of the previous one with explicit + >>> # coordinates. + >>> coords = (torch.tensor([0, 2]), torch.tensor([0, 3, 6, 9])) + >>> torch.gradient(t, spacing = coords) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + """ + +@overload +def gradient( + input: Tensor, + *, + spacing: Number | _complex, + dim: _size, + edge_order: _int = 1, +) -> tuple[Tensor, ...]: + r""" + gradient(input, *, spacing=1, dim=None, edge_order=1) -> List of Tensors + + Estimates the gradient of a function :math:`g : \mathbb{R}^n \rightarrow \mathbb{R}` in + one or more dimensions using the `second-order accurate central differences method + `_ and + either first or second order estimates at the boundaries. + + The gradient of :math:`g` is estimated using samples. By default, when :attr:`spacing` is not + specified, the samples are entirely described by :attr:`input`, and the mapping of input coordinates + to an output is the same as the tensor's mapping of indices to values. For example, for a three-dimensional + :attr:`input` the function described is :math:`g : \mathbb{R}^3 \rightarrow \mathbb{R}`, and + :math:`g(1, 2, 3)\ == input[1, 2, 3]`. + + When :attr:`spacing` is specified, it modifies the relationship between :attr:`input` and input coordinates. + This is detailed in the "Keyword Arguments" section below. + + The gradient is estimated by estimating each partial derivative of :math:`g` independently. This estimation is + accurate if :math:`g` is in :math:`C^3` (it has at least 3 continuous derivatives), and the estimation can be + improved by providing closer samples. Mathematically, the value at each interior point of a partial derivative + is estimated using `Taylor's theorem with remainder `_. + Letting :math:`x` be an interior point with :math:`x-h_l` and :math:`x+h_r` be points neighboring + it to the left and right respectively, :math:`f(x+h_r)` and :math:`f(x-h_l)` can be estimated using: + + .. math:: + \begin{aligned} + f(x+h_r) = f(x) + h_r f'(x) + {h_r}^2 \frac{f''(x)}{2} + {h_r}^3 \frac{f'''(\xi_1)}{6}, \xi_1 \in (x, x+h_r) \\ + f(x-h_l) = f(x) - h_l f'(x) + {h_l}^2 \frac{f''(x)}{2} - {h_l}^3 \frac{f'''(\xi_2)}{6}, \xi_2 \in (x, x-h_l) \\ + \end{aligned} + + Using the fact that :math:`f \in C^3` and solving the linear system, we derive: + + .. math:: + f'(x) \approx \frac{ {h_l}^2 f(x+h_r) - {h_r}^2 f(x-h_l) + + ({h_r}^2-{h_l}^2 ) f(x) }{ {h_r} {h_l}^2 + {h_r}^2 {h_l} } + + .. note:: + We estimate the gradient of functions in complex domain + :math:`g : \mathbb{C}^n \rightarrow \mathbb{C}` in the same way. + + The value of each partial derivative at the boundary points is computed differently. See edge_order below. + + Args: + input (``Tensor``): the tensor that represents the values of the function + + Keyword args: + spacing (``scalar``, ``list of scalar``, ``list of Tensor``, optional): :attr:`spacing` can be used to modify + how the :attr:`input` tensor's indices relate to sample coordinates. If :attr:`spacing` is a scalar then + the indices are multiplied by the scalar to produce the coordinates. For example, if :attr:`spacing=2` the + indices (1, 2, 3) become coordinates (2, 4, 6). If :attr:`spacing` is a list of scalars then the corresponding + indices are multiplied. For example, if :attr:`spacing=(2, -1, 3)` the indices (1, 2, 3) become coordinates (2, -2, 9). + Finally, if :attr:`spacing` is a list of one-dimensional tensors then each tensor specifies the coordinates for + the corresponding dimension. For example, if the indices are (1, 2, 3) and the tensors are (t0, t1, t2), then + the coordinates are (t0[1], t1[2], t2[3]) + + dim (``int``, ``list of int``, optional): the dimension or dimensions to approximate the gradient over. By default + the partial gradient in every dimension is computed. Note that when :attr:`dim` is specified the elements of + the :attr:`spacing` argument must correspond with the specified dims." + + edge_order (``int``, optional): 1 or 2, for `first-order + `_ or + `second-order `_ + estimation of the boundary ("edge") values, respectively. Note that when :attr:`edge_order` is specified, each + dimension size of :attr:`input` should be at least edge_order+1 + + Examples:: + + >>> # Estimates the gradient of f(x)=x^2 at points [-2, -1, 2, 4] + >>> coordinates = (torch.tensor([-2., -1., 1., 4.]),) + >>> values = torch.tensor([4., 1., 1., 16.], ) + >>> torch.gradient(values, spacing = coordinates) + (tensor([-3., -2., 2., 5.]),) + + >>> # Estimates the gradient of the R^2 -> R function whose samples are + >>> # described by the tensor t. Implicit coordinates are [0, 1] for the outermost + >>> # dimension and [0, 1, 2, 3] for the innermost dimension, and function estimates + >>> # partial derivative for both dimensions. + >>> t = torch.tensor([[1, 2, 4, 8], [10, 20, 40, 80]]) + >>> torch.gradient(t) + (tensor([[ 9., 18., 36., 72.], + [ 9., 18., 36., 72.]]), + tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]])) + + >>> # A scalar value for spacing modifies the relationship between tensor indices + >>> # and input coordinates by multiplying the indices to find the + >>> # coordinates. For example, below the indices of the innermost + >>> # 0, 1, 2, 3 translate to coordinates of [0, 2, 4, 6], and the indices of + >>> # the outermost dimension 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = 2.0) # dim = None (implicitly [0, 1]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.5000, 0.7500, 1.5000, 2.0000], + [ 5.0000, 7.5000, 15.0000, 20.0000]])) + >>> # doubling the spacing between samples halves the estimated partial gradients. + + >>> + >>> # Estimates only the partial derivative for dimension 1 + >>> torch.gradient(t, dim = 1) # spacing = None (implicitly 1.) + (tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]]),) + + >>> # When spacing is a list of scalars, the relationship between the tensor + >>> # indices and input coordinates changes based on dimension. + >>> # For example, below, the indices of the innermost dimension 0, 1, 2, 3 translate + >>> # to coordinates of [0, 3, 6, 9], and the indices of the outermost dimension + >>> # 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = [3., 2.]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + + >>> # The following example is a replication of the previous one with explicit + >>> # coordinates. + >>> coords = (torch.tensor([0, 2]), torch.tensor([0, 3, 6, 9])) + >>> torch.gradient(t, spacing = coords) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + """ + +@overload +def gradient( + input: Tensor, + *, + spacing: tuple[Tensor, ...] | list[Tensor] | None, + dim: _size, + edge_order: _int = 1, +) -> tuple[Tensor, ...]: + r""" + gradient(input, *, spacing=1, dim=None, edge_order=1) -> List of Tensors + + Estimates the gradient of a function :math:`g : \mathbb{R}^n \rightarrow \mathbb{R}` in + one or more dimensions using the `second-order accurate central differences method + `_ and + either first or second order estimates at the boundaries. + + The gradient of :math:`g` is estimated using samples. By default, when :attr:`spacing` is not + specified, the samples are entirely described by :attr:`input`, and the mapping of input coordinates + to an output is the same as the tensor's mapping of indices to values. For example, for a three-dimensional + :attr:`input` the function described is :math:`g : \mathbb{R}^3 \rightarrow \mathbb{R}`, and + :math:`g(1, 2, 3)\ == input[1, 2, 3]`. + + When :attr:`spacing` is specified, it modifies the relationship between :attr:`input` and input coordinates. + This is detailed in the "Keyword Arguments" section below. + + The gradient is estimated by estimating each partial derivative of :math:`g` independently. This estimation is + accurate if :math:`g` is in :math:`C^3` (it has at least 3 continuous derivatives), and the estimation can be + improved by providing closer samples. Mathematically, the value at each interior point of a partial derivative + is estimated using `Taylor's theorem with remainder `_. + Letting :math:`x` be an interior point with :math:`x-h_l` and :math:`x+h_r` be points neighboring + it to the left and right respectively, :math:`f(x+h_r)` and :math:`f(x-h_l)` can be estimated using: + + .. math:: + \begin{aligned} + f(x+h_r) = f(x) + h_r f'(x) + {h_r}^2 \frac{f''(x)}{2} + {h_r}^3 \frac{f'''(\xi_1)}{6}, \xi_1 \in (x, x+h_r) \\ + f(x-h_l) = f(x) - h_l f'(x) + {h_l}^2 \frac{f''(x)}{2} - {h_l}^3 \frac{f'''(\xi_2)}{6}, \xi_2 \in (x, x-h_l) \\ + \end{aligned} + + Using the fact that :math:`f \in C^3` and solving the linear system, we derive: + + .. math:: + f'(x) \approx \frac{ {h_l}^2 f(x+h_r) - {h_r}^2 f(x-h_l) + + ({h_r}^2-{h_l}^2 ) f(x) }{ {h_r} {h_l}^2 + {h_r}^2 {h_l} } + + .. note:: + We estimate the gradient of functions in complex domain + :math:`g : \mathbb{C}^n \rightarrow \mathbb{C}` in the same way. + + The value of each partial derivative at the boundary points is computed differently. See edge_order below. + + Args: + input (``Tensor``): the tensor that represents the values of the function + + Keyword args: + spacing (``scalar``, ``list of scalar``, ``list of Tensor``, optional): :attr:`spacing` can be used to modify + how the :attr:`input` tensor's indices relate to sample coordinates. If :attr:`spacing` is a scalar then + the indices are multiplied by the scalar to produce the coordinates. For example, if :attr:`spacing=2` the + indices (1, 2, 3) become coordinates (2, 4, 6). If :attr:`spacing` is a list of scalars then the corresponding + indices are multiplied. For example, if :attr:`spacing=(2, -1, 3)` the indices (1, 2, 3) become coordinates (2, -2, 9). + Finally, if :attr:`spacing` is a list of one-dimensional tensors then each tensor specifies the coordinates for + the corresponding dimension. For example, if the indices are (1, 2, 3) and the tensors are (t0, t1, t2), then + the coordinates are (t0[1], t1[2], t2[3]) + + dim (``int``, ``list of int``, optional): the dimension or dimensions to approximate the gradient over. By default + the partial gradient in every dimension is computed. Note that when :attr:`dim` is specified the elements of + the :attr:`spacing` argument must correspond with the specified dims." + + edge_order (``int``, optional): 1 or 2, for `first-order + `_ or + `second-order `_ + estimation of the boundary ("edge") values, respectively. Note that when :attr:`edge_order` is specified, each + dimension size of :attr:`input` should be at least edge_order+1 + + Examples:: + + >>> # Estimates the gradient of f(x)=x^2 at points [-2, -1, 2, 4] + >>> coordinates = (torch.tensor([-2., -1., 1., 4.]),) + >>> values = torch.tensor([4., 1., 1., 16.], ) + >>> torch.gradient(values, spacing = coordinates) + (tensor([-3., -2., 2., 5.]),) + + >>> # Estimates the gradient of the R^2 -> R function whose samples are + >>> # described by the tensor t. Implicit coordinates are [0, 1] for the outermost + >>> # dimension and [0, 1, 2, 3] for the innermost dimension, and function estimates + >>> # partial derivative for both dimensions. + >>> t = torch.tensor([[1, 2, 4, 8], [10, 20, 40, 80]]) + >>> torch.gradient(t) + (tensor([[ 9., 18., 36., 72.], + [ 9., 18., 36., 72.]]), + tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]])) + + >>> # A scalar value for spacing modifies the relationship between tensor indices + >>> # and input coordinates by multiplying the indices to find the + >>> # coordinates. For example, below the indices of the innermost + >>> # 0, 1, 2, 3 translate to coordinates of [0, 2, 4, 6], and the indices of + >>> # the outermost dimension 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = 2.0) # dim = None (implicitly [0, 1]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.5000, 0.7500, 1.5000, 2.0000], + [ 5.0000, 7.5000, 15.0000, 20.0000]])) + >>> # doubling the spacing between samples halves the estimated partial gradients. + + >>> + >>> # Estimates only the partial derivative for dimension 1 + >>> torch.gradient(t, dim = 1) # spacing = None (implicitly 1.) + (tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]]),) + + >>> # When spacing is a list of scalars, the relationship between the tensor + >>> # indices and input coordinates changes based on dimension. + >>> # For example, below, the indices of the innermost dimension 0, 1, 2, 3 translate + >>> # to coordinates of [0, 3, 6, 9], and the indices of the outermost dimension + >>> # 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = [3., 2.]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + + >>> # The following example is a replication of the previous one with explicit + >>> # coordinates. + >>> coords = (torch.tensor([0, 2]), torch.tensor([0, 3, 6, 9])) + >>> torch.gradient(t, spacing = coords) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + """ + +@overload +def gradient( + input: Tensor, + *, + dim: _size, + edge_order: _int = 1, +) -> tuple[Tensor, ...]: + r""" + gradient(input, *, spacing=1, dim=None, edge_order=1) -> List of Tensors + + Estimates the gradient of a function :math:`g : \mathbb{R}^n \rightarrow \mathbb{R}` in + one or more dimensions using the `second-order accurate central differences method + `_ and + either first or second order estimates at the boundaries. + + The gradient of :math:`g` is estimated using samples. By default, when :attr:`spacing` is not + specified, the samples are entirely described by :attr:`input`, and the mapping of input coordinates + to an output is the same as the tensor's mapping of indices to values. For example, for a three-dimensional + :attr:`input` the function described is :math:`g : \mathbb{R}^3 \rightarrow \mathbb{R}`, and + :math:`g(1, 2, 3)\ == input[1, 2, 3]`. + + When :attr:`spacing` is specified, it modifies the relationship between :attr:`input` and input coordinates. + This is detailed in the "Keyword Arguments" section below. + + The gradient is estimated by estimating each partial derivative of :math:`g` independently. This estimation is + accurate if :math:`g` is in :math:`C^3` (it has at least 3 continuous derivatives), and the estimation can be + improved by providing closer samples. Mathematically, the value at each interior point of a partial derivative + is estimated using `Taylor's theorem with remainder `_. + Letting :math:`x` be an interior point with :math:`x-h_l` and :math:`x+h_r` be points neighboring + it to the left and right respectively, :math:`f(x+h_r)` and :math:`f(x-h_l)` can be estimated using: + + .. math:: + \begin{aligned} + f(x+h_r) = f(x) + h_r f'(x) + {h_r}^2 \frac{f''(x)}{2} + {h_r}^3 \frac{f'''(\xi_1)}{6}, \xi_1 \in (x, x+h_r) \\ + f(x-h_l) = f(x) - h_l f'(x) + {h_l}^2 \frac{f''(x)}{2} - {h_l}^3 \frac{f'''(\xi_2)}{6}, \xi_2 \in (x, x-h_l) \\ + \end{aligned} + + Using the fact that :math:`f \in C^3` and solving the linear system, we derive: + + .. math:: + f'(x) \approx \frac{ {h_l}^2 f(x+h_r) - {h_r}^2 f(x-h_l) + + ({h_r}^2-{h_l}^2 ) f(x) }{ {h_r} {h_l}^2 + {h_r}^2 {h_l} } + + .. note:: + We estimate the gradient of functions in complex domain + :math:`g : \mathbb{C}^n \rightarrow \mathbb{C}` in the same way. + + The value of each partial derivative at the boundary points is computed differently. See edge_order below. + + Args: + input (``Tensor``): the tensor that represents the values of the function + + Keyword args: + spacing (``scalar``, ``list of scalar``, ``list of Tensor``, optional): :attr:`spacing` can be used to modify + how the :attr:`input` tensor's indices relate to sample coordinates. If :attr:`spacing` is a scalar then + the indices are multiplied by the scalar to produce the coordinates. For example, if :attr:`spacing=2` the + indices (1, 2, 3) become coordinates (2, 4, 6). If :attr:`spacing` is a list of scalars then the corresponding + indices are multiplied. For example, if :attr:`spacing=(2, -1, 3)` the indices (1, 2, 3) become coordinates (2, -2, 9). + Finally, if :attr:`spacing` is a list of one-dimensional tensors then each tensor specifies the coordinates for + the corresponding dimension. For example, if the indices are (1, 2, 3) and the tensors are (t0, t1, t2), then + the coordinates are (t0[1], t1[2], t2[3]) + + dim (``int``, ``list of int``, optional): the dimension or dimensions to approximate the gradient over. By default + the partial gradient in every dimension is computed. Note that when :attr:`dim` is specified the elements of + the :attr:`spacing` argument must correspond with the specified dims." + + edge_order (``int``, optional): 1 or 2, for `first-order + `_ or + `second-order `_ + estimation of the boundary ("edge") values, respectively. Note that when :attr:`edge_order` is specified, each + dimension size of :attr:`input` should be at least edge_order+1 + + Examples:: + + >>> # Estimates the gradient of f(x)=x^2 at points [-2, -1, 2, 4] + >>> coordinates = (torch.tensor([-2., -1., 1., 4.]),) + >>> values = torch.tensor([4., 1., 1., 16.], ) + >>> torch.gradient(values, spacing = coordinates) + (tensor([-3., -2., 2., 5.]),) + + >>> # Estimates the gradient of the R^2 -> R function whose samples are + >>> # described by the tensor t. Implicit coordinates are [0, 1] for the outermost + >>> # dimension and [0, 1, 2, 3] for the innermost dimension, and function estimates + >>> # partial derivative for both dimensions. + >>> t = torch.tensor([[1, 2, 4, 8], [10, 20, 40, 80]]) + >>> torch.gradient(t) + (tensor([[ 9., 18., 36., 72.], + [ 9., 18., 36., 72.]]), + tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]])) + + >>> # A scalar value for spacing modifies the relationship between tensor indices + >>> # and input coordinates by multiplying the indices to find the + >>> # coordinates. For example, below the indices of the innermost + >>> # 0, 1, 2, 3 translate to coordinates of [0, 2, 4, 6], and the indices of + >>> # the outermost dimension 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = 2.0) # dim = None (implicitly [0, 1]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.5000, 0.7500, 1.5000, 2.0000], + [ 5.0000, 7.5000, 15.0000, 20.0000]])) + >>> # doubling the spacing between samples halves the estimated partial gradients. + + >>> + >>> # Estimates only the partial derivative for dimension 1 + >>> torch.gradient(t, dim = 1) # spacing = None (implicitly 1.) + (tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]]),) + + >>> # When spacing is a list of scalars, the relationship between the tensor + >>> # indices and input coordinates changes based on dimension. + >>> # For example, below, the indices of the innermost dimension 0, 1, 2, 3 translate + >>> # to coordinates of [0, 3, 6, 9], and the indices of the outermost dimension + >>> # 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = [3., 2.]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + + >>> # The following example is a replication of the previous one with explicit + >>> # coordinates. + >>> coords = (torch.tensor([0, 2]), torch.tensor([0, 3, 6, 9])) + >>> torch.gradient(t, spacing = coords) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + """ + +@overload +def greater( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + greater(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.gt`. + """ + +@overload +def greater( + input: Tensor, + other: Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + greater(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.gt`. + """ + +@overload +def greater_equal( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + greater_equal(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.ge`. + """ + +@overload +def greater_equal( + input: Tensor, + other: Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + greater_equal(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.ge`. + """ + +def grid_sampler( + input: Tensor, + grid: Tensor, + interpolation_mode: _int, + padding_mode: _int, + align_corners: _bool, +) -> Tensor: ... +def grid_sampler_2d( + input: Tensor, + grid: Tensor, + interpolation_mode: _int, + padding_mode: _int, + align_corners: _bool, +) -> Tensor: ... +def grid_sampler_3d( + input: Tensor, + grid: Tensor, + interpolation_mode: _int, + padding_mode: _int, + align_corners: _bool, +) -> Tensor: ... +def group_norm( + input: Tensor, + num_groups: _int, + weight: Tensor | None = None, + bias: Tensor | None = None, + eps: _float = 1e-05, + cudnn_enabled: _bool = True, +) -> Tensor: ... +@overload +def gru( + data: Tensor, + batch_sizes: Tensor, + hx: Tensor, + params: tuple[Tensor, ...] | list[Tensor] | None, + has_biases: _bool, + num_layers: _int, + dropout: _float, + train: _bool, + bidirectional: _bool, +) -> tuple[Tensor, Tensor]: ... +@overload +def gru( + input: Tensor, + hx: Tensor, + params: tuple[Tensor, ...] | list[Tensor] | None, + has_biases: _bool, + num_layers: _int, + dropout: _float, + train: _bool, + bidirectional: _bool, + batch_first: _bool, +) -> tuple[Tensor, Tensor]: ... +def gru_cell( + input: Tensor, + hx: Tensor, + w_ih: Tensor, + w_hh: Tensor, + b_ih: Tensor | None = None, + b_hh: Tensor | None = None, +) -> Tensor: ... +@overload +def gt( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + gt(input, other, *, out=None) -> Tensor + + Computes :math:`\text{input} > \text{other}` element-wise. + + + The second argument can be a number or a tensor whose shape is + :ref:`broadcastable ` with the first argument. + + Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is greater than :attr:`other` and False elsewhere + + Example:: + + >>> torch.gt(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[False, True], [False, False]]) + """ + +@overload +def gt( + input: Tensor, + other: Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + gt(input, other, *, out=None) -> Tensor + + Computes :math:`\text{input} > \text{other}` element-wise. + + + The second argument can be a number or a tensor whose shape is + :ref:`broadcastable ` with the first argument. + + Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is greater than :attr:`other` and False elsewhere + + Example:: + + >>> torch.gt(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[False, True], [False, False]]) + """ + +@overload +def hamming_window( + window_length: _int, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + hamming_window(window_length, *, dtype=None, layout=None, device=None, pin_memory=False, requires_grad=False) -> Tensor + + Hamming window function. + + .. math:: + w[n] = \alpha - \beta\ \cos \left( \frac{2 \pi n}{N - 1} \right), + + where :math:`N` is the full window size. + + The input :attr:`window_length` is a positive integer controlling the + returned window size. :attr:`periodic` flag determines whether the returned + window trims off the last duplicate value from the symmetric window and is + ready to be used as a periodic window with functions like + :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in + above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have + ``torch.hamming_window(L, periodic=True)`` equal to + ``torch.hamming_window(L + 1, periodic=False)[:-1])``. + + .. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. + + .. note:: + This is a generalized version of :meth:`torch.hann_window`. + + Arguments: + window_length (int): the size of returned window + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, *, dtype=None, layout=None, device=None, \ + pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, float alpha, *, dtype=None, layout=None, device=None, \ + pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic and alpha specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + alpha (float): The coefficient :math:`\alpha` in the equation above + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, float alpha, float beta, *, dtype=None, layout=None, \ + device=None, pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic, alpha and beta specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + alpha (float): The coefficient :math:`\alpha` in the equation above + beta (float): The coefficient :math:`\beta` in the equation above + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + """ + +@overload +def hamming_window( + window_length: _int, + periodic: _bool, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + hamming_window(window_length, *, dtype=None, layout=None, device=None, pin_memory=False, requires_grad=False) -> Tensor + + Hamming window function. + + .. math:: + w[n] = \alpha - \beta\ \cos \left( \frac{2 \pi n}{N - 1} \right), + + where :math:`N` is the full window size. + + The input :attr:`window_length` is a positive integer controlling the + returned window size. :attr:`periodic` flag determines whether the returned + window trims off the last duplicate value from the symmetric window and is + ready to be used as a periodic window with functions like + :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in + above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have + ``torch.hamming_window(L, periodic=True)`` equal to + ``torch.hamming_window(L + 1, periodic=False)[:-1])``. + + .. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. + + .. note:: + This is a generalized version of :meth:`torch.hann_window`. + + Arguments: + window_length (int): the size of returned window + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, *, dtype=None, layout=None, device=None, \ + pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, float alpha, *, dtype=None, layout=None, device=None, \ + pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic and alpha specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + alpha (float): The coefficient :math:`\alpha` in the equation above + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, float alpha, float beta, *, dtype=None, layout=None, \ + device=None, pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic, alpha and beta specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + alpha (float): The coefficient :math:`\alpha` in the equation above + beta (float): The coefficient :math:`\beta` in the equation above + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + """ + +@overload +def hamming_window( + window_length: _int, + periodic: _bool, + alpha: _float, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + hamming_window(window_length, *, dtype=None, layout=None, device=None, pin_memory=False, requires_grad=False) -> Tensor + + Hamming window function. + + .. math:: + w[n] = \alpha - \beta\ \cos \left( \frac{2 \pi n}{N - 1} \right), + + where :math:`N` is the full window size. + + The input :attr:`window_length` is a positive integer controlling the + returned window size. :attr:`periodic` flag determines whether the returned + window trims off the last duplicate value from the symmetric window and is + ready to be used as a periodic window with functions like + :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in + above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have + ``torch.hamming_window(L, periodic=True)`` equal to + ``torch.hamming_window(L + 1, periodic=False)[:-1])``. + + .. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. + + .. note:: + This is a generalized version of :meth:`torch.hann_window`. + + Arguments: + window_length (int): the size of returned window + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, *, dtype=None, layout=None, device=None, \ + pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, float alpha, *, dtype=None, layout=None, device=None, \ + pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic and alpha specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + alpha (float): The coefficient :math:`\alpha` in the equation above + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, float alpha, float beta, *, dtype=None, layout=None, \ + device=None, pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic, alpha and beta specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + alpha (float): The coefficient :math:`\alpha` in the equation above + beta (float): The coefficient :math:`\beta` in the equation above + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + """ + +@overload +def hamming_window( + window_length: _int, + periodic: _bool, + alpha: _float, + beta: _float, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + hamming_window(window_length, *, dtype=None, layout=None, device=None, pin_memory=False, requires_grad=False) -> Tensor + + Hamming window function. + + .. math:: + w[n] = \alpha - \beta\ \cos \left( \frac{2 \pi n}{N - 1} \right), + + where :math:`N` is the full window size. + + The input :attr:`window_length` is a positive integer controlling the + returned window size. :attr:`periodic` flag determines whether the returned + window trims off the last duplicate value from the symmetric window and is + ready to be used as a periodic window with functions like + :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in + above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have + ``torch.hamming_window(L, periodic=True)`` equal to + ``torch.hamming_window(L + 1, periodic=False)[:-1])``. + + .. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. + + .. note:: + This is a generalized version of :meth:`torch.hann_window`. + + Arguments: + window_length (int): the size of returned window + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, *, dtype=None, layout=None, device=None, \ + pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, float alpha, *, dtype=None, layout=None, device=None, \ + pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic and alpha specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + alpha (float): The coefficient :math:`\alpha` in the equation above + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, float alpha, float beta, *, dtype=None, layout=None, \ + device=None, pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic, alpha and beta specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + alpha (float): The coefficient :math:`\alpha` in the equation above + beta (float): The coefficient :math:`\beta` in the equation above + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + """ + +@overload +def hann_window( + window_length: _int, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + hann_window(window_length, periodic=True, *, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Hann window function. + + .. math:: + w[n] = \frac{1}{2}\ \left[1 - \cos \left( \frac{2 \pi n}{N - 1} \right)\right] = + \sin^2 \left( \frac{\pi n}{N - 1} \right), + + where :math:`N` is the full window size. + + The input :attr:`window_length` is a positive integer controlling the + returned window size. :attr:`periodic` flag determines whether the returned + window trims off the last duplicate value from the symmetric window and is + ready to be used as a periodic window with functions like + :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in + above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have + ``torch.hann_window(L, periodic=True)`` equal to + ``torch.hann_window(L + 1, periodic=False)[:-1])``. + + .. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. + + Arguments: + window_length (int): the size of returned window + periodic (bool, optional): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window + """ + +@overload +def hann_window( + window_length: _int, + periodic: _bool, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + hann_window(window_length, periodic=True, *, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Hann window function. + + .. math:: + w[n] = \frac{1}{2}\ \left[1 - \cos \left( \frac{2 \pi n}{N - 1} \right)\right] = + \sin^2 \left( \frac{\pi n}{N - 1} \right), + + where :math:`N` is the full window size. + + The input :attr:`window_length` is a positive integer controlling the + returned window size. :attr:`periodic` flag determines whether the returned + window trims off the last duplicate value from the symmetric window and is + ready to be used as a periodic window with functions like + :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in + above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have + ``torch.hann_window(L, periodic=True)`` equal to + ``torch.hann_window(L + 1, periodic=False)[:-1])``. + + .. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. + + Arguments: + window_length (int): the size of returned window + periodic (bool, optional): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window + """ + +def hardshrink( + input: Tensor, + lambd: Number | _complex = 0.5, + *, + out: Tensor | None = None, +) -> Tensor: ... +def hash_tensor( + input: Tensor, + dim: _int | _size = (), + *, + keepdim: _bool = False, + mode: _int = 0, + out: Tensor | None = None, +) -> Tensor: + r""" + hash_tensor(input, *, mode=0) -> Tensor + + Returns a hash of all elements in the :attr:`input` tensor. + + Currently only mode=0 (reduction via xor) is supported. The output will always + be of type ``torch.uint64``. The elements of ``input`` are upcasted to their + 64 bit float / integer equivalent and bitcasted to ``torch.uint64`` before + reduction via xor. + + Args: + input (Tensor): the input tensor. + + Keyword Args: + mode (int) : The hash to use. Default: 0 (xor_reduction) + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 1.1918, -1.1813, 0.3373]]) + >>> torch.hash_tensor(a) + tensor(13822780554648485888, dtype=torch.uint64) + + .. function:: hash_tensor(input, dim, *, keepdim=False, mode=0) -> Tensor + :noindex: + + Returns the hash of each row of the :attr:`input` tensor in the given + dimension :attr:`dim` given by mode. If :attr:`dim` is a list of dimensions, + reduce over all of them. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword Args: + mode (int) : The hash to use. Default: 0 (xor_reduction) + + Example:: + + >>> a = torch.randn(2, 4) + >>> a + tensor([[ 0.1317, -0.5554, -1.4724, -1.1391], + [ 0.0778, -0.6070, 0.6375, 0.1798]]) + >>> torch.hash_tensor(a, 1) + tensor([9233691267014066176, 9255993250844508160], dtype=torch.uint64) + """ + +def heaviside( + input: Tensor, + values: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + heaviside(input, values, *, out=None) -> Tensor + + Computes the Heaviside step function for each element in :attr:`input`. + The Heaviside step function is defined as: + + .. math:: + \text{{heaviside}}(input, values) = \begin{cases} + 0, & \text{if input < 0}\\ + values, & \text{if input == 0}\\ + 1, & \text{if input > 0} + \end{cases} + + + Args: + input (Tensor): the input tensor. + values (Tensor): The values to use where :attr:`input` is zero. + + Keyword arguments: + out (Tensor, optional): the output tensor. + + Example:: + + >>> input = torch.tensor([-1.5, 0, 2.0]) + >>> values = torch.tensor([0.5]) + >>> torch.heaviside(input, values) + tensor([0.0000, 0.5000, 1.0000]) + >>> values = torch.tensor([1.2, -2.0, 3.5]) + >>> torch.heaviside(input, values) + tensor([0., -2., 1.]) + """ + +def hinge_embedding_loss( + input: Tensor, + target: Tensor, + margin: _float = 1.0, + reduction: _int = 1, +) -> Tensor: ... +def histc( + input: Tensor, + bins: _int = 100, + min: Number | _complex = 0, + max: Number | _complex = 0, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + histc(input, bins=100, min=0, max=0, *, out=None) -> Tensor + + Computes the histogram of a tensor. + + The elements are sorted into equal width bins between :attr:`min` and + :attr:`max`. If :attr:`min` and :attr:`max` are both zero, the minimum and + maximum values of the data are used. + + Elements lower than min and higher than max and ``NaN`` elements are ignored. + + Args: + input (Tensor): the input tensor. + bins (int): number of histogram bins + min (Scalar): lower end of the range (inclusive) + max (Scalar): upper end of the range (inclusive) + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + Tensor: Histogram represented as a tensor + + Example:: + + >>> torch.histc(torch.tensor([1., 2, 1]), bins=4, min=0, max=3) + tensor([ 0., 2., 1., 0.]) + """ + +@overload +def histogram( + input: Tensor, + bins: Tensor, + *, + weight: Tensor | None = None, + density: _bool = False, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.histogram: + r""" + histogram(input, bins, *, range=None, weight=None, density=False, out=None) -> (Tensor, Tensor) + + Computes a histogram of the values in a tensor. + + :attr:`bins` can be an integer or a 1D tensor. + + If :attr:`bins` is an int, it specifies the number of equal-width bins. + By default, the lower and upper range of the bins is determined by the + minimum and maximum elements of the input tensor. The :attr:`range` + argument can be provided to specify a range for the bins. + + If :attr:`bins` is a 1D tensor, it specifies the sequence of bin edges + including the rightmost edge. It should contain at least 2 elements + and its elements should be increasing. + + Args: + input (Tensor): the input tensor. + bins: int or 1D Tensor. If int, defines the number of equal-width bins. If tensor, + defines the sequence of bin edges including the rightmost edge. + + Keyword args: + range (tuple of float): Defines the range of the bins. + weight (Tensor): If provided, weight should have the same shape as input. Each value in + input contributes its associated weight towards its bin's result. + density (bool): If False, the result will contain the count (or total weight) in each bin. + If True, the result is the value of the probability density function over the bins, + normalized such that the integral over the range of the bins is 1. + out (Tensor, optional): the output tensor. (tuple, optional): The result tuple of two output tensors (hist, bin_edges). + + Returns: + hist (Tensor): 1D Tensor containing the values of the histogram. + bin_edges(Tensor): 1D Tensor containing the edges of the histogram bins. + + Example:: + + >>> torch.histogram(torch.tensor([1., 2, 1]), bins=4, range=(0., 3.), weight=torch.tensor([1., 2., 4.])) + (tensor([ 0., 5., 2., 0.]), tensor([0., 0.75, 1.5, 2.25, 3.])) + >>> torch.histogram(torch.tensor([1., 2, 1]), bins=4, range=(0., 3.), weight=torch.tensor([1., 2., 4.]), density=True) + (tensor([ 0., 0.9524, 0.3810, 0.]), tensor([0., 0.75, 1.5, 2.25, 3.])) + """ + +@overload +def histogram( + input: Tensor, + bins: _int = 100, + *, + range: Sequence[_float] | None = None, + weight: Tensor | None = None, + density: _bool = False, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.histogram: + r""" + histogram(input, bins, *, range=None, weight=None, density=False, out=None) -> (Tensor, Tensor) + + Computes a histogram of the values in a tensor. + + :attr:`bins` can be an integer or a 1D tensor. + + If :attr:`bins` is an int, it specifies the number of equal-width bins. + By default, the lower and upper range of the bins is determined by the + minimum and maximum elements of the input tensor. The :attr:`range` + argument can be provided to specify a range for the bins. + + If :attr:`bins` is a 1D tensor, it specifies the sequence of bin edges + including the rightmost edge. It should contain at least 2 elements + and its elements should be increasing. + + Args: + input (Tensor): the input tensor. + bins: int or 1D Tensor. If int, defines the number of equal-width bins. If tensor, + defines the sequence of bin edges including the rightmost edge. + + Keyword args: + range (tuple of float): Defines the range of the bins. + weight (Tensor): If provided, weight should have the same shape as input. Each value in + input contributes its associated weight towards its bin's result. + density (bool): If False, the result will contain the count (or total weight) in each bin. + If True, the result is the value of the probability density function over the bins, + normalized such that the integral over the range of the bins is 1. + out (Tensor, optional): the output tensor. (tuple, optional): The result tuple of two output tensors (hist, bin_edges). + + Returns: + hist (Tensor): 1D Tensor containing the values of the histogram. + bin_edges(Tensor): 1D Tensor containing the edges of the histogram bins. + + Example:: + + >>> torch.histogram(torch.tensor([1., 2, 1]), bins=4, range=(0., 3.), weight=torch.tensor([1., 2., 4.])) + (tensor([ 0., 5., 2., 0.]), tensor([0., 0.75, 1.5, 2.25, 3.])) + >>> torch.histogram(torch.tensor([1., 2, 1]), bins=4, range=(0., 3.), weight=torch.tensor([1., 2., 4.]), density=True) + (tensor([ 0., 0.9524, 0.3810, 0.]), tensor([0., 0.75, 1.5, 2.25, 3.])) + """ + +@overload +def histogramdd( + input: Tensor, + bins: _int, + range: Sequence[_float] | None = None, + weight: Tensor | None = None, + density: _bool = False, +) -> torch.return_types.histogramdd: + r""" + histogramdd(input, bins, *, range=None, weight=None, density=False, out=None) -> (Tensor, Tensor[]) + + Computes a multi-dimensional histogram of the values in a tensor. + + Interprets the elements of an input tensor whose innermost dimension has size N + as a collection of N-dimensional points. Maps each of the points into a set of + N-dimensional bins and returns the number of points (or total weight) in each bin. + + :attr:`input` must be a tensor with at least 2 dimensions. + If input has shape (M, N), each of its M rows defines a point in N-dimensional space. + If input has three or more dimensions, all but the last dimension are flattened. + + Each dimension is independently associated with its own strictly increasing sequence + of bin edges. Bin edges may be specified explicitly by passing a sequence of 1D + tensors. Alternatively, bin edges may be constructed automatically by passing a + sequence of integers specifying the number of equal-width bins in each dimension. + + For each N-dimensional point in input: + - Each of its coordinates is binned independently among the bin edges + corresponding to its dimension + - Binning results are combined to identify the N-dimensional bin (if any) + into which the point falls + - If the point falls into a bin, the bin's count (or total weight) is incremented + - Points which do not fall into any bin do not contribute to the output + + :attr:`bins` can be a sequence of N 1D tensors, a sequence of N ints, or a single int. + + If :attr:`bins` is a sequence of N 1D tensors, it explicitly specifies the N sequences + of bin edges. Each 1D tensor should contain a strictly increasing sequence with at + least one element. A sequence of K bin edges defines K-1 bins, explicitly specifying + the left and right edges of all bins. Every bin is inclusive of its left edge. Only + the rightmost bin is inclusive of its right edge. + + If :attr:`bins` is a sequence of N ints, it specifies the number of equal-width bins + in each dimension. By default, the leftmost and rightmost bin edges in each dimension + are determined by the minimum and maximum elements of the input tensor in the + corresponding dimension. The :attr:`range` argument can be provided to manually + specify the leftmost and rightmost bin edges in each dimension. + + If :attr:`bins` is an int, it specifies the number of equal-width bins for all dimensions. + + .. note:: + See also :func:`torch.histogram`, which specifically computes 1D histograms. + While :func:`torch.histogramdd` infers the dimensionality of its bins and + binned values from the shape of :attr:`input`, :func:`torch.histogram` + accepts and flattens :attr:`input` of any shape. + + Args: + input (Tensor): the input tensor. + bins: Tensor[], int[], or int. + If Tensor[], defines the sequences of bin edges. + If int[], defines the number of equal-width bins in each dimension. + If int, defines the number of equal-width bins for all dimensions. + Keyword args: + range (sequence of float): Defines the leftmost and rightmost bin edges + in each dimension. + weight (Tensor): By default, each value in the input has weight 1. If a weight + tensor is passed, each N-dimensional coordinate in input + contributes its associated weight towards its bin's result. + The weight tensor should have the same shape as the :attr:`input` + tensor excluding its innermost dimension N. + density (bool): If False (default), the result will contain the count (or total weight) + in each bin. If True, each count (weight) is divided by the total count + (total weight), then divided by the volume of its associated bin. + Returns: + hist (Tensor): N-dimensional Tensor containing the values of the histogram. + bin_edges(Tensor[]): sequence of N 1D Tensors containing the bin edges. + + Example:: + + >>> torch.histogramdd(torch.tensor([[0., 1.], [1., 0.], [2., 0.], [2., 2.]]), bins=[3, 3], + ... weight=torch.tensor([1., 2., 4., 8.])) + torch.return_types.histogramdd( + hist=tensor([[0., 1., 0.], + [2., 0., 0.], + [4., 0., 8.]]), + bin_edges=(tensor([0.0000, 0.6667, 1.3333, 2.0000]), + tensor([0.0000, 0.6667, 1.3333, 2.0000]))) + + >>> torch.histogramdd(torch.tensor([[0., 0.], [1., 1.], [2., 2.]]), bins=[2, 2], + ... range=[0., 1., 0., 1.], density=True) + torch.return_types.histogramdd( + hist=tensor([[2., 0.], + [0., 2.]]), + bin_edges=(tensor([0.0000, 0.5000, 1.0000]), + tensor([0.0000, 0.5000, 1.0000]))) + """ + +@overload +def histogramdd( + input: Tensor, + bins: _size, + range: Sequence[_float] | None = None, + weight: Tensor | None = None, + density: _bool = False, +) -> torch.return_types.histogramdd: + r""" + histogramdd(input, bins, *, range=None, weight=None, density=False, out=None) -> (Tensor, Tensor[]) + + Computes a multi-dimensional histogram of the values in a tensor. + + Interprets the elements of an input tensor whose innermost dimension has size N + as a collection of N-dimensional points. Maps each of the points into a set of + N-dimensional bins and returns the number of points (or total weight) in each bin. + + :attr:`input` must be a tensor with at least 2 dimensions. + If input has shape (M, N), each of its M rows defines a point in N-dimensional space. + If input has three or more dimensions, all but the last dimension are flattened. + + Each dimension is independently associated with its own strictly increasing sequence + of bin edges. Bin edges may be specified explicitly by passing a sequence of 1D + tensors. Alternatively, bin edges may be constructed automatically by passing a + sequence of integers specifying the number of equal-width bins in each dimension. + + For each N-dimensional point in input: + - Each of its coordinates is binned independently among the bin edges + corresponding to its dimension + - Binning results are combined to identify the N-dimensional bin (if any) + into which the point falls + - If the point falls into a bin, the bin's count (or total weight) is incremented + - Points which do not fall into any bin do not contribute to the output + + :attr:`bins` can be a sequence of N 1D tensors, a sequence of N ints, or a single int. + + If :attr:`bins` is a sequence of N 1D tensors, it explicitly specifies the N sequences + of bin edges. Each 1D tensor should contain a strictly increasing sequence with at + least one element. A sequence of K bin edges defines K-1 bins, explicitly specifying + the left and right edges of all bins. Every bin is inclusive of its left edge. Only + the rightmost bin is inclusive of its right edge. + + If :attr:`bins` is a sequence of N ints, it specifies the number of equal-width bins + in each dimension. By default, the leftmost and rightmost bin edges in each dimension + are determined by the minimum and maximum elements of the input tensor in the + corresponding dimension. The :attr:`range` argument can be provided to manually + specify the leftmost and rightmost bin edges in each dimension. + + If :attr:`bins` is an int, it specifies the number of equal-width bins for all dimensions. + + .. note:: + See also :func:`torch.histogram`, which specifically computes 1D histograms. + While :func:`torch.histogramdd` infers the dimensionality of its bins and + binned values from the shape of :attr:`input`, :func:`torch.histogram` + accepts and flattens :attr:`input` of any shape. + + Args: + input (Tensor): the input tensor. + bins: Tensor[], int[], or int. + If Tensor[], defines the sequences of bin edges. + If int[], defines the number of equal-width bins in each dimension. + If int, defines the number of equal-width bins for all dimensions. + Keyword args: + range (sequence of float): Defines the leftmost and rightmost bin edges + in each dimension. + weight (Tensor): By default, each value in the input has weight 1. If a weight + tensor is passed, each N-dimensional coordinate in input + contributes its associated weight towards its bin's result. + The weight tensor should have the same shape as the :attr:`input` + tensor excluding its innermost dimension N. + density (bool): If False (default), the result will contain the count (or total weight) + in each bin. If True, each count (weight) is divided by the total count + (total weight), then divided by the volume of its associated bin. + Returns: + hist (Tensor): N-dimensional Tensor containing the values of the histogram. + bin_edges(Tensor[]): sequence of N 1D Tensors containing the bin edges. + + Example:: + + >>> torch.histogramdd(torch.tensor([[0., 1.], [1., 0.], [2., 0.], [2., 2.]]), bins=[3, 3], + ... weight=torch.tensor([1., 2., 4., 8.])) + torch.return_types.histogramdd( + hist=tensor([[0., 1., 0.], + [2., 0., 0.], + [4., 0., 8.]]), + bin_edges=(tensor([0.0000, 0.6667, 1.3333, 2.0000]), + tensor([0.0000, 0.6667, 1.3333, 2.0000]))) + + >>> torch.histogramdd(torch.tensor([[0., 0.], [1., 1.], [2., 2.]]), bins=[2, 2], + ... range=[0., 1., 0., 1.], density=True) + torch.return_types.histogramdd( + hist=tensor([[2., 0.], + [0., 2.]]), + bin_edges=(tensor([0.0000, 0.5000, 1.0000]), + tensor([0.0000, 0.5000, 1.0000]))) + """ + +@overload +def histogramdd( + input: Tensor, + bins: tuple[Tensor, ...] | list[Tensor] | None, + range: Sequence[_float] | None = None, + weight: Tensor | None = None, + density: _bool = False, +) -> torch.return_types.histogramdd: + r""" + histogramdd(input, bins, *, range=None, weight=None, density=False, out=None) -> (Tensor, Tensor[]) + + Computes a multi-dimensional histogram of the values in a tensor. + + Interprets the elements of an input tensor whose innermost dimension has size N + as a collection of N-dimensional points. Maps each of the points into a set of + N-dimensional bins and returns the number of points (or total weight) in each bin. + + :attr:`input` must be a tensor with at least 2 dimensions. + If input has shape (M, N), each of its M rows defines a point in N-dimensional space. + If input has three or more dimensions, all but the last dimension are flattened. + + Each dimension is independently associated with its own strictly increasing sequence + of bin edges. Bin edges may be specified explicitly by passing a sequence of 1D + tensors. Alternatively, bin edges may be constructed automatically by passing a + sequence of integers specifying the number of equal-width bins in each dimension. + + For each N-dimensional point in input: + - Each of its coordinates is binned independently among the bin edges + corresponding to its dimension + - Binning results are combined to identify the N-dimensional bin (if any) + into which the point falls + - If the point falls into a bin, the bin's count (or total weight) is incremented + - Points which do not fall into any bin do not contribute to the output + + :attr:`bins` can be a sequence of N 1D tensors, a sequence of N ints, or a single int. + + If :attr:`bins` is a sequence of N 1D tensors, it explicitly specifies the N sequences + of bin edges. Each 1D tensor should contain a strictly increasing sequence with at + least one element. A sequence of K bin edges defines K-1 bins, explicitly specifying + the left and right edges of all bins. Every bin is inclusive of its left edge. Only + the rightmost bin is inclusive of its right edge. + + If :attr:`bins` is a sequence of N ints, it specifies the number of equal-width bins + in each dimension. By default, the leftmost and rightmost bin edges in each dimension + are determined by the minimum and maximum elements of the input tensor in the + corresponding dimension. The :attr:`range` argument can be provided to manually + specify the leftmost and rightmost bin edges in each dimension. + + If :attr:`bins` is an int, it specifies the number of equal-width bins for all dimensions. + + .. note:: + See also :func:`torch.histogram`, which specifically computes 1D histograms. + While :func:`torch.histogramdd` infers the dimensionality of its bins and + binned values from the shape of :attr:`input`, :func:`torch.histogram` + accepts and flattens :attr:`input` of any shape. + + Args: + input (Tensor): the input tensor. + bins: Tensor[], int[], or int. + If Tensor[], defines the sequences of bin edges. + If int[], defines the number of equal-width bins in each dimension. + If int, defines the number of equal-width bins for all dimensions. + Keyword args: + range (sequence of float): Defines the leftmost and rightmost bin edges + in each dimension. + weight (Tensor): By default, each value in the input has weight 1. If a weight + tensor is passed, each N-dimensional coordinate in input + contributes its associated weight towards its bin's result. + The weight tensor should have the same shape as the :attr:`input` + tensor excluding its innermost dimension N. + density (bool): If False (default), the result will contain the count (or total weight) + in each bin. If True, each count (weight) is divided by the total count + (total weight), then divided by the volume of its associated bin. + Returns: + hist (Tensor): N-dimensional Tensor containing the values of the histogram. + bin_edges(Tensor[]): sequence of N 1D Tensors containing the bin edges. + + Example:: + + >>> torch.histogramdd(torch.tensor([[0., 1.], [1., 0.], [2., 0.], [2., 2.]]), bins=[3, 3], + ... weight=torch.tensor([1., 2., 4., 8.])) + torch.return_types.histogramdd( + hist=tensor([[0., 1., 0.], + [2., 0., 0.], + [4., 0., 8.]]), + bin_edges=(tensor([0.0000, 0.6667, 1.3333, 2.0000]), + tensor([0.0000, 0.6667, 1.3333, 2.0000]))) + + >>> torch.histogramdd(torch.tensor([[0., 0.], [1., 1.], [2., 2.]]), bins=[2, 2], + ... range=[0., 1., 0., 1.], density=True) + torch.return_types.histogramdd( + hist=tensor([[2., 0.], + [0., 2.]]), + bin_edges=(tensor([0.0000, 0.5000, 1.0000]), + tensor([0.0000, 0.5000, 1.0000]))) + """ + +def hsmm(input: Tensor, mat2: Tensor) -> Tensor: ... +@overload +def hsplit(input: Tensor, sections: _int) -> tuple[Tensor, ...]: + r""" + hsplit(input, indices_or_sections) -> List of Tensors + + Splits :attr:`input`, a tensor with one or more dimensions, into multiple tensors + horizontally according to :attr:`indices_or_sections`. Each split is a view of + :attr:`input`. + + If :attr:`input` is one dimensional this is equivalent to calling + torch.tensor_split(input, indices_or_sections, dim=0) (the split dimension is + zero), and if :attr:`input` has two or more dimensions it's equivalent to calling + torch.tensor_split(input, indices_or_sections, dim=1) (the split dimension is 1), + except that if :attr:`indices_or_sections` is an integer it must evenly divide + the split dimension or a runtime error will be thrown. + + This function is based on NumPy's :func:`numpy.hsplit`. + + Args: + input (Tensor): tensor to split. + indices_or_sections (int or list or tuple of ints): See argument in :func:`torch.tensor_split`. + + Example:: + + >>> t = torch.arange(16.0).reshape(4,4) + >>> t + tensor([[ 0., 1., 2., 3.], + [ 4., 5., 6., 7.], + [ 8., 9., 10., 11.], + [12., 13., 14., 15.]]) + >>> torch.hsplit(t, 2) + (tensor([[ 0., 1.], + [ 4., 5.], + [ 8., 9.], + [12., 13.]]), + tensor([[ 2., 3.], + [ 6., 7.], + [10., 11.], + [14., 15.]])) + >>> torch.hsplit(t, [3, 6]) + (tensor([[ 0., 1., 2.], + [ 4., 5., 6.], + [ 8., 9., 10.], + [12., 13., 14.]]), + tensor([[ 3.], + [ 7.], + [11.], + [15.]]), + tensor([], size=(4, 0))) + """ + +@overload +def hsplit(input: Tensor, indices: _size) -> tuple[Tensor, ...]: + r""" + hsplit(input, indices_or_sections) -> List of Tensors + + Splits :attr:`input`, a tensor with one or more dimensions, into multiple tensors + horizontally according to :attr:`indices_or_sections`. Each split is a view of + :attr:`input`. + + If :attr:`input` is one dimensional this is equivalent to calling + torch.tensor_split(input, indices_or_sections, dim=0) (the split dimension is + zero), and if :attr:`input` has two or more dimensions it's equivalent to calling + torch.tensor_split(input, indices_or_sections, dim=1) (the split dimension is 1), + except that if :attr:`indices_or_sections` is an integer it must evenly divide + the split dimension or a runtime error will be thrown. + + This function is based on NumPy's :func:`numpy.hsplit`. + + Args: + input (Tensor): tensor to split. + indices_or_sections (int or list or tuple of ints): See argument in :func:`torch.tensor_split`. + + Example:: + + >>> t = torch.arange(16.0).reshape(4,4) + >>> t + tensor([[ 0., 1., 2., 3.], + [ 4., 5., 6., 7.], + [ 8., 9., 10., 11.], + [12., 13., 14., 15.]]) + >>> torch.hsplit(t, 2) + (tensor([[ 0., 1.], + [ 4., 5.], + [ 8., 9.], + [12., 13.]]), + tensor([[ 2., 3.], + [ 6., 7.], + [10., 11.], + [14., 15.]])) + >>> torch.hsplit(t, [3, 6]) + (tensor([[ 0., 1., 2.], + [ 4., 5., 6.], + [ 8., 9., 10.], + [12., 13., 14.]]), + tensor([[ 3.], + [ 7.], + [11.], + [15.]]), + tensor([], size=(4, 0))) + """ + +def hspmm( + mat1: Tensor, + mat2: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + hspmm(mat1, mat2, *, out=None) -> Tensor + + Performs a matrix multiplication of a :ref:`sparse COO matrix + ` :attr:`mat1` and a strided matrix :attr:`mat2`. The + result is a (1 + 1)-dimensional :ref:`hybrid COO matrix + `. + + Args: + mat1 (Tensor): the first sparse matrix to be matrix multiplied + mat2 (Tensor): the second strided matrix to be matrix multiplied + + Keyword args: + out (Tensor, optional): the output tensor. + """ + +def hstack( + tensors: tuple[Tensor, ...] | list[Tensor] | None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + hstack(tensors, *, out=None) -> Tensor + + Stack tensors in sequence horizontally (column wise). + + This is equivalent to concatenation along the first axis for 1-D tensors, and along the second axis for all other tensors. + + Args: + tensors (sequence of Tensors): sequence of tensors to concatenate + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([1, 2, 3]) + >>> b = torch.tensor([4, 5, 6]) + >>> torch.hstack((a,b)) + tensor([1, 2, 3, 4, 5, 6]) + >>> a = torch.tensor([[1],[2],[3]]) + >>> b = torch.tensor([[4],[5],[6]]) + >>> torch.hstack((a,b)) + tensor([[1, 4], + [2, 5], + [3, 6]]) + """ + +def hypot( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + hypot(input, other, *, out=None) -> Tensor + + Given the legs of a right triangle, return its hypotenuse. + + .. math:: + \text{out}_{i} = \sqrt{\text{input}_{i}^{2} + \text{other}_{i}^{2}} + + The shapes of ``input`` and ``other`` must be + :ref:`broadcastable `. + + Args: + input (Tensor): the first input tensor + other (Tensor): the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.hypot(torch.tensor([4.0]), torch.tensor([3.0, 4.0, 5.0])) + tensor([5.0000, 5.6569, 6.4031]) + """ + +def i0(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + i0(input, *, out=None) -> Tensor + + Alias for :func:`torch.special.i0`. + """ + +def i0_(input: Tensor) -> Tensor: ... +def igamma( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + igamma(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.special.gammainc`. + """ + +def igammac( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + igammac(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.special.gammaincc`. + """ + +def imag(input: Tensor) -> Tensor: + r""" + imag(input) -> Tensor + + Returns a new tensor containing imaginary values of the :attr:`self` tensor. + The returned tensor and :attr:`self` share the same underlying storage. + + .. warning:: + :func:`imag` is only supported for tensors with complex dtypes. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> x=torch.randn(4, dtype=torch.cfloat) + >>> x + tensor([(0.3100+0.3553j), (-0.5445-0.7896j), (-1.6492-0.0633j), (-0.0638-0.8119j)]) + >>> x.imag + tensor([ 0.3553, -0.7896, -0.0633, -0.8119]) + """ + +@overload +def index_add( + input: Tensor, + dim: _int, + index: Tensor, + source: Tensor, + *, + alpha: Number | _complex = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + index_add(input: Tensor, dim: int, index: Tensor, source: Tensor, *, alpha: Union[Number, _complex] = 1, out: Optional[Tensor]) -> Tensor # noqa: B950 + + See :meth:`~Tensor.index_add_` for function description. + """ + +@overload +def index_add( + input: Tensor, + dim: str | EllipsisType | None, + index: Tensor, + source: Tensor, + *, + alpha: Number | _complex = 1, +) -> Tensor: + r""" + index_add(input: Tensor, dim: int, index: Tensor, source: Tensor, *, alpha: Union[Number, _complex] = 1, out: Optional[Tensor]) -> Tensor # noqa: B950 + + See :meth:`~Tensor.index_add_` for function description. + """ + +@overload +def index_copy( + input: Tensor, + dim: _int, + index: Tensor, + source: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + index_copy(input: Tensor, dim: int, index: Tensor, source: Tensor, *, out: Optional[Tensor]) -> Tensor + + See :meth:`~Tensor.index_add_` for function description. + """ + +@overload +def index_copy( + input: Tensor, + dim: str | EllipsisType | None, + index: Tensor, + source: Tensor, +) -> Tensor: + r""" + index_copy(input: Tensor, dim: int, index: Tensor, source: Tensor, *, out: Optional[Tensor]) -> Tensor + + See :meth:`~Tensor.index_add_` for function description. + """ + +@overload +def index_fill( + input: Tensor, + dim: _int, + index: Tensor, + value: Tensor, +) -> Tensor: ... +@overload +def index_fill( + input: Tensor, + dim: str | EllipsisType | None, + index: Tensor, + value: Tensor, +) -> Tensor: ... +@overload +def index_fill( + input: Tensor, + dim: _int, + index: Tensor, + value: Number | _complex, +) -> Tensor: ... +@overload +def index_fill( + input: Tensor, + dim: str | EllipsisType | None, + index: Tensor, + value: Number | _complex, +) -> Tensor: ... +def index_put( + input: Tensor, + indices: tuple[Tensor, ...] | list[Tensor] | None, + values: Tensor, + accumulate: _bool = False, +) -> Tensor: ... +def index_put_( + input: Tensor, + indices: tuple[Tensor, ...] | list[Tensor] | None, + values: Tensor, + accumulate: _bool = False, +) -> Tensor: ... +def index_reduce( + input: Tensor, + dim: _int, + index: Tensor, + source: Tensor, + reduce: str, + *, + include_self: _bool = True, + out: Tensor | None = None, +) -> Tensor: + r""" + index_reduce(input: Tensor, dim: int, index: Tensor, source: Tensor, reduce: str, *, include_self: bool = True, out: Optional[Tensor]) -> Tensor # noqa: B950 + + See :meth:`~Tensor.index_reduce_` for function description. + """ + +@overload +def index_select( + input: Tensor, + dim: _int, + index: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + index_select(input, dim, index, *, out=None) -> Tensor + + Returns a new tensor which indexes the :attr:`input` tensor along dimension + :attr:`dim` using the entries in :attr:`index`. + + The returned tensor has the same number of dimensions as the original tensor + (:attr:`input`). The :attr:`dim`\ th dimension has the same size as the length + of :attr:`index`; other dimensions have the same size as in the original tensor. + + .. note:: The returned tensor does **not** use the same storage as the original + tensor. If :attr:`out` has a different shape than expected, we + silently change it to the correct shape, reallocating the underlying + storage if necessary. + + Args: + input (Tensor): the input tensor. + dim (int): the dimension in which we index + index (IntTensor or LongTensor): the 1-D tensor containing the indices to index + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> x = torch.randn(3, 4) + >>> x + tensor([[ 0.1427, 0.0231, -0.5414, -1.0009], + [-0.4664, 0.2647, -0.1228, -1.1068], + [-1.1734, -0.6571, 0.7230, -0.6004]]) + >>> indices = torch.tensor([0, 2]) + >>> torch.index_select(x, 0, indices) + tensor([[ 0.1427, 0.0231, -0.5414, -1.0009], + [-1.1734, -0.6571, 0.7230, -0.6004]]) + >>> torch.index_select(x, 1, indices) + tensor([[ 0.1427, -0.5414], + [-0.4664, -0.1228], + [-1.1734, 0.7230]]) + """ + +@overload +def index_select( + input: Tensor, + dim: str | EllipsisType | None, + index: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + index_select(input, dim, index, *, out=None) -> Tensor + + Returns a new tensor which indexes the :attr:`input` tensor along dimension + :attr:`dim` using the entries in :attr:`index`. + + The returned tensor has the same number of dimensions as the original tensor + (:attr:`input`). The :attr:`dim`\ th dimension has the same size as the length + of :attr:`index`; other dimensions have the same size as in the original tensor. + + .. note:: The returned tensor does **not** use the same storage as the original + tensor. If :attr:`out` has a different shape than expected, we + silently change it to the correct shape, reallocating the underlying + storage if necessary. + + Args: + input (Tensor): the input tensor. + dim (int): the dimension in which we index + index (IntTensor or LongTensor): the 1-D tensor containing the indices to index + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> x = torch.randn(3, 4) + >>> x + tensor([[ 0.1427, 0.0231, -0.5414, -1.0009], + [-0.4664, 0.2647, -0.1228, -1.1068], + [-1.1734, -0.6571, 0.7230, -0.6004]]) + >>> indices = torch.tensor([0, 2]) + >>> torch.index_select(x, 0, indices) + tensor([[ 0.1427, 0.0231, -0.5414, -1.0009], + [-1.1734, -0.6571, 0.7230, -0.6004]]) + >>> torch.index_select(x, 1, indices) + tensor([[ 0.1427, -0.5414], + [-0.4664, -0.1228], + [-1.1734, 0.7230]]) + """ + +def indices_copy(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + Performs the same operation as :func:`torch.indices`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def init_num_threads() -> None: ... +def inner( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + inner(input, other, *, out=None) -> Tensor + + Computes the dot product for 1D tensors. For higher dimensions, sums the product + of elements from :attr:`input` and :attr:`other` along their last dimension. + + .. note:: + + If either :attr:`input` or :attr:`other` is a scalar, the result is equivalent + to `torch.mul(input, other)`. + + If both :attr:`input` and :attr:`other` are non-scalars, the size of their last + dimension must match and the result is equivalent to `torch.tensordot(input, + other, dims=([-1], [-1]))` + + Args: + input (Tensor): First input tensor + other (Tensor): Second input tensor + + Keyword args: + out (Tensor, optional): Optional output tensor to write result into. The output + shape is `input.shape[:-1] + other.shape[:-1]`. + + Example:: + + # Dot product + >>> torch.inner(torch.tensor([1, 2, 3]), torch.tensor([0, 2, 1])) + tensor(7) + + # Multidimensional input tensors + >>> a = torch.randn(2, 3) + >>> a + tensor([[0.8173, 1.0874, 1.1784], + [0.3279, 0.1234, 2.7894]]) + >>> b = torch.randn(2, 4, 3) + >>> b + tensor([[[-0.4682, -0.7159, 0.1506], + [ 0.4034, -0.3657, 1.0387], + [ 0.9892, -0.6684, 0.1774], + [ 0.9482, 1.3261, 0.3917]], + + [[ 0.4537, 0.7493, 1.1724], + [ 0.2291, 0.5749, -0.2267], + [-0.7920, 0.3607, -0.3701], + [ 1.3666, -0.5850, -1.7242]]]) + >>> torch.inner(a, b) + tensor([[[-0.9837, 1.1560, 0.2907, 2.6785], + [ 2.5671, 0.5452, -0.6912, -1.5509]], + + [[ 0.1782, 2.9843, 0.7366, 1.5672], + [ 3.5115, -0.4864, -1.2476, -4.4337]]]) + + # Scalar input + >>> torch.inner(a, torch.tensor(2)) + tensor([[1.6347, 2.1748, 2.3567], + [0.6558, 0.2469, 5.5787]]) + """ + +def instance_norm( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + running_mean: Tensor | None, + running_var: Tensor | None, + use_input_stats: _bool, + momentum: _float, + eps: _float, + cudnn_enabled: _bool, +) -> Tensor: ... +def int_repr(input: Tensor) -> Tensor: ... +def inverse(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + inverse(input, *, out=None) -> Tensor + + Alias for :func:`torch.linalg.inv` + """ + +def is_complex(input: Tensor) -> _bool: + r""" + is_complex(input: Tensor) -> bool + + Returns True if the data type of :attr:`input` is a complex data type i.e., + one of ``torch.complex64``, and ``torch.complex128``. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> torch.is_complex(torch.tensor([1, 2, 3], dtype=torch.complex64)) + True + >>> torch.is_complex(torch.tensor([1, 2, 3], dtype=torch.complex128)) + True + >>> torch.is_complex(torch.tensor([1, 2, 3], dtype=torch.int32)) + False + >>> torch.is_complex(torch.tensor([1.0, 2.0, 3.0], dtype=torch.float16)) + False + """ + +def is_conj(input: Tensor) -> _bool: + r""" + is_conj(input) -> (bool) + + Returns True if the :attr:`input` is a conjugated tensor, i.e. its conjugate bit is set to `True`. + + Args: + input (Tensor): the input tensor. + """ + +def is_distributed(input: Tensor) -> _bool: ... +def is_floating_point(input: Tensor) -> _bool: + r""" + is_floating_point(input: Tensor) -> bool + + Returns True if the data type of :attr:`input` is a floating point data type i.e., + one of ``torch.float64``, ``torch.float32``, ``torch.float16``, and ``torch.bfloat16``. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> torch.is_floating_point(torch.tensor([1.0, 2.0, 3.0])) + True + >>> torch.is_floating_point(torch.tensor([1, 2, 3], dtype=torch.int32)) + False + >>> torch.is_floating_point(torch.tensor([1.0, 2.0, 3.0], dtype=torch.float16)) + True + >>> torch.is_floating_point(torch.tensor([1, 2, 3], dtype=torch.complex64)) + False + """ + +def is_grad_enabled() -> _bool: + r""" + is_grad_enabled() -> (bool) + + Returns True if grad mode is currently enabled. + """ + +def is_inference(input: Tensor) -> _bool: + r""" + is_inference(input) -> (bool) + + Returns True if :attr:`input` is an inference tensor. + + A non-view tensor is an inference tensor if and only if it was + allocated during inference mode. A view tensor is an inference + tensor if and only if the tensor it is a view of is an inference tensor. + + For details on inference mode please see + `Inference Mode `_. + + Args: + input (Tensor): the input tensor. + """ + +def is_inference_mode_enabled() -> _bool: + r""" + is_inference_mode_enabled() -> (bool) + + Returns True if inference mode is currently enabled. + """ + +def is_neg(input: Tensor) -> _bool: ... +def is_nonzero(input: Tensor) -> _bool: + r""" + is_nonzero(input) -> (bool) + + Returns True if the :attr:`input` is a single element tensor which is not equal to zero + after type conversions. + i.e. not equal to ``torch.tensor([0.])`` or ``torch.tensor([0])`` or + ``torch.tensor([False])``. + Throws a ``RuntimeError`` if ``torch.numel() != 1`` (even in case + of sparse tensors). + + Args: + input (Tensor): the input tensor. + + Examples:: + + >>> torch.is_nonzero(torch.tensor([0.])) + False + >>> torch.is_nonzero(torch.tensor([1.5])) + True + >>> torch.is_nonzero(torch.tensor([False])) + False + >>> torch.is_nonzero(torch.tensor([3])) + True + >>> torch.is_nonzero(torch.tensor([1, 3, 5])) + Traceback (most recent call last): + ... + RuntimeError: Boolean value of Tensor with more than one value is ambiguous + >>> torch.is_nonzero(torch.tensor([])) + Traceback (most recent call last): + ... + RuntimeError: Boolean value of Tensor with no values is ambiguous + """ + +def is_same_size(input: Tensor, other: Tensor) -> _bool: ... +def is_signed(input: Tensor) -> _bool: ... +def is_vulkan_available() -> _bool: ... +def isclose( + input: Tensor, + other: Tensor, + rtol: _float = 1e-05, + atol: _float = 1e-08, + equal_nan: _bool = False, +) -> Tensor: + r""" + isclose(input, other, rtol=1e-05, atol=1e-08, equal_nan=False) -> Tensor + + Returns a new tensor with boolean elements representing if each element of + :attr:`input` is "close" to the corresponding element of :attr:`other`. + Closeness is defined as: + + .. math:: + \lvert \text{input}_i - \text{other}_i \rvert \leq \texttt{rtol} \times \lvert \text{other}_i \rvert + \texttt{atol} + + + where :attr:`input` and :attr:`other` are finite. Where :attr:`input` + and/or :attr:`other` are nonfinite they are close if and only if + they are equal, with NaNs being considered equal to each other when + :attr:`equal_nan` is True. + + Args: + input (Tensor): first tensor to compare + other (Tensor): second tensor to compare + rtol (float, optional): relative tolerance. Default: 1e-05 + atol (float, optional): absolute tolerance. Default: 1e-08 + equal_nan (bool, optional): if ``True``, then two ``NaN`` s will be considered equal. Default: ``False`` + + Examples:: + + >>> torch.isclose(torch.tensor((1., 2, 3)), torch.tensor((1 + 1e-10, 3, 4))) + tensor([ True, False, False]) + >>> torch.isclose(torch.tensor((float('inf'), 4)), torch.tensor((float('inf'), 6)), rtol=.5) + tensor([True, True]) + """ + +def isfinite(input: Tensor) -> Tensor: + r""" + isfinite(input) -> Tensor + + Returns a new tensor with boolean elements representing if each element is `finite` or not. + + Real values are finite when they are not NaN, negative infinity, or infinity. + Complex values are finite when both their real and imaginary parts are finite. + + Args: + input (Tensor): the input tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is finite and False elsewhere + + Example:: + + >>> torch.isfinite(torch.tensor([1, float('inf'), 2, float('-inf'), float('nan')])) + tensor([True, False, True, False, False]) + """ + +@overload +def isin( + elements: Tensor, + test_elements: Tensor, + *, + assume_unique: _bool = False, + invert: _bool = False, + out: Tensor | None = None, +) -> Tensor: + r""" + isin(elements, test_elements, *, assume_unique=False, invert=False) -> Tensor + + Tests if each element of :attr:`elements` is in :attr:`test_elements`. Returns + a boolean tensor of the same shape as :attr:`elements` that is True for elements + in :attr:`test_elements` and False otherwise. + + .. note:: + One of :attr:`elements` or :attr:`test_elements` can be a scalar, but not both. + + Args: + elements (Tensor or Scalar): Input elements + test_elements (Tensor or Scalar): Values against which to test for each input element + assume_unique (bool, optional): If True, assumes both :attr:`elements` and + :attr:`test_elements` contain unique elements, which can speed up the + calculation. Default: False + invert (bool, optional): If True, inverts the boolean return tensor, resulting in True + values for elements *not* in :attr:`test_elements`. Default: False + + Returns: + A boolean tensor of the same shape as :attr:`elements` that is True for elements in + :attr:`test_elements` and False otherwise + + Example: + >>> torch.isin(torch.tensor([[1, 2], [3, 4]]), torch.tensor([2, 3])) + tensor([[False, True], + [ True, False]]) + """ + +@overload +def isin( + element: Number | _complex, + test_elements: Tensor, + *, + assume_unique: _bool = False, + invert: _bool = False, + out: Tensor | None = None, +) -> Tensor: + r""" + isin(elements, test_elements, *, assume_unique=False, invert=False) -> Tensor + + Tests if each element of :attr:`elements` is in :attr:`test_elements`. Returns + a boolean tensor of the same shape as :attr:`elements` that is True for elements + in :attr:`test_elements` and False otherwise. + + .. note:: + One of :attr:`elements` or :attr:`test_elements` can be a scalar, but not both. + + Args: + elements (Tensor or Scalar): Input elements + test_elements (Tensor or Scalar): Values against which to test for each input element + assume_unique (bool, optional): If True, assumes both :attr:`elements` and + :attr:`test_elements` contain unique elements, which can speed up the + calculation. Default: False + invert (bool, optional): If True, inverts the boolean return tensor, resulting in True + values for elements *not* in :attr:`test_elements`. Default: False + + Returns: + A boolean tensor of the same shape as :attr:`elements` that is True for elements in + :attr:`test_elements` and False otherwise + + Example: + >>> torch.isin(torch.tensor([[1, 2], [3, 4]]), torch.tensor([2, 3])) + tensor([[False, True], + [ True, False]]) + """ + +@overload +def isin( + elements: Tensor, + test_element: Number | _complex, + *, + assume_unique: _bool = False, + invert: _bool = False, + out: Tensor | None = None, +) -> Tensor: + r""" + isin(elements, test_elements, *, assume_unique=False, invert=False) -> Tensor + + Tests if each element of :attr:`elements` is in :attr:`test_elements`. Returns + a boolean tensor of the same shape as :attr:`elements` that is True for elements + in :attr:`test_elements` and False otherwise. + + .. note:: + One of :attr:`elements` or :attr:`test_elements` can be a scalar, but not both. + + Args: + elements (Tensor or Scalar): Input elements + test_elements (Tensor or Scalar): Values against which to test for each input element + assume_unique (bool, optional): If True, assumes both :attr:`elements` and + :attr:`test_elements` contain unique elements, which can speed up the + calculation. Default: False + invert (bool, optional): If True, inverts the boolean return tensor, resulting in True + values for elements *not* in :attr:`test_elements`. Default: False + + Returns: + A boolean tensor of the same shape as :attr:`elements` that is True for elements in + :attr:`test_elements` and False otherwise + + Example: + >>> torch.isin(torch.tensor([[1, 2], [3, 4]]), torch.tensor([2, 3])) + tensor([[False, True], + [ True, False]]) + """ + +def isinf(input: Tensor) -> Tensor: + r""" + isinf(input) -> Tensor + + Tests if each element of :attr:`input` is infinite + (positive or negative infinity) or not. + + .. note:: + Complex values are infinite when their real or imaginary part is + infinite. + + Args: + input (Tensor): the input tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is infinite and False elsewhere + + Example:: + + >>> torch.isinf(torch.tensor([1, float('inf'), 2, float('-inf'), float('nan')])) + tensor([False, True, False, True, False]) + """ + +def isnan(input: Tensor) -> Tensor: + r""" + isnan(input) -> Tensor + + Returns a new tensor with boolean elements representing if each element of :attr:`input` + is NaN or not. Complex values are considered NaN when either their real + and/or imaginary part is NaN. + + Arguments: + input (Tensor): the input tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is NaN and False elsewhere + + Example:: + + >>> torch.isnan(torch.tensor([1, float('nan'), 2])) + tensor([False, True, False]) + """ + +def isneginf(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + isneginf(input, *, out=None) -> Tensor + Tests if each element of :attr:`input` is negative infinity or not. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([-float('inf'), float('inf'), 1.2]) + >>> torch.isneginf(a) + tensor([ True, False, False]) + """ + +def isposinf(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + isposinf(input, *, out=None) -> Tensor + Tests if each element of :attr:`input` is positive infinity or not. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([-float('inf'), float('inf'), 1.2]) + >>> torch.isposinf(a) + tensor([False, True, False]) + """ + +def isreal(input: Tensor) -> Tensor: + r""" + isreal(input) -> Tensor + + Returns a new tensor with boolean elements representing if each element of :attr:`input` is real-valued or not. + All real-valued types are considered real. Complex values are considered real when their imaginary part is 0. + + Arguments: + input (Tensor): the input tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is real and False elsewhere + + Example:: + + >>> torch.isreal(torch.tensor([1, 1+1j, 2+0j])) + tensor([True, False, True]) + """ + +def istft( + input: Tensor, + n_fft: _int, + hop_length: _int | None = None, + win_length: _int | None = None, + window: Tensor | None = None, + center: _bool = True, + normalized: _bool = False, + onesided: _bool | None = None, + length: _int | None = None, + return_complex: _bool = False, +) -> Tensor: ... +@overload +def kaiser_window( + window_length: _int, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + kaiser_window(window_length, periodic=True, beta=12.0, *, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Computes the Kaiser window with window length :attr:`window_length` and shape parameter :attr:`beta`. + + Let I_0 be the zeroth order modified Bessel function of the first kind (see :func:`torch.i0`) and + ``N = L - 1`` if :attr:`periodic` is False and ``L`` if :attr:`periodic` is True, + where ``L`` is the :attr:`window_length`. This function computes: + + .. math:: + out_i = I_0 \left( \beta \sqrt{1 - \left( {\frac{i - N/2}{N/2}} \right) ^2 } \right) / I_0( \beta ) + + Calling ``torch.kaiser_window(L, B, periodic=True)`` is equivalent to calling + ``torch.kaiser_window(L + 1, B, periodic=False)[:-1])``. + The :attr:`periodic` argument is intended as a helpful shorthand + to produce a periodic window as input to functions like :func:`torch.stft`. + + .. note:: + If :attr:`window_length` is one, then the returned window is a single element tensor containing a one. + + + Args: + window_length (int): length of the window. + periodic (bool, optional): If True, returns a periodic window suitable for use in spectral analysis. + If False, returns a symmetric window suitable for use in filter design. + beta (float, optional): shape parameter for the window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + """ + +@overload +def kaiser_window( + window_length: _int, + periodic: _bool, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + kaiser_window(window_length, periodic=True, beta=12.0, *, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Computes the Kaiser window with window length :attr:`window_length` and shape parameter :attr:`beta`. + + Let I_0 be the zeroth order modified Bessel function of the first kind (see :func:`torch.i0`) and + ``N = L - 1`` if :attr:`periodic` is False and ``L`` if :attr:`periodic` is True, + where ``L`` is the :attr:`window_length`. This function computes: + + .. math:: + out_i = I_0 \left( \beta \sqrt{1 - \left( {\frac{i - N/2}{N/2}} \right) ^2 } \right) / I_0( \beta ) + + Calling ``torch.kaiser_window(L, B, periodic=True)`` is equivalent to calling + ``torch.kaiser_window(L + 1, B, periodic=False)[:-1])``. + The :attr:`periodic` argument is intended as a helpful shorthand + to produce a periodic window as input to functions like :func:`torch.stft`. + + .. note:: + If :attr:`window_length` is one, then the returned window is a single element tensor containing a one. + + + Args: + window_length (int): length of the window. + periodic (bool, optional): If True, returns a periodic window suitable for use in spectral analysis. + If False, returns a symmetric window suitable for use in filter design. + beta (float, optional): shape parameter for the window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + """ + +@overload +def kaiser_window( + window_length: _int, + periodic: _bool, + beta: _float, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + kaiser_window(window_length, periodic=True, beta=12.0, *, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Computes the Kaiser window with window length :attr:`window_length` and shape parameter :attr:`beta`. + + Let I_0 be the zeroth order modified Bessel function of the first kind (see :func:`torch.i0`) and + ``N = L - 1`` if :attr:`periodic` is False and ``L`` if :attr:`periodic` is True, + where ``L`` is the :attr:`window_length`. This function computes: + + .. math:: + out_i = I_0 \left( \beta \sqrt{1 - \left( {\frac{i - N/2}{N/2}} \right) ^2 } \right) / I_0( \beta ) + + Calling ``torch.kaiser_window(L, B, periodic=True)`` is equivalent to calling + ``torch.kaiser_window(L + 1, B, periodic=False)[:-1])``. + The :attr:`periodic` argument is intended as a helpful shorthand + to produce a periodic window as input to functions like :func:`torch.stft`. + + .. note:: + If :attr:`window_length` is one, then the returned window is a single element tensor containing a one. + + + Args: + window_length (int): length of the window. + periodic (bool, optional): If True, returns a periodic window suitable for use in spectral analysis. + If False, returns a symmetric window suitable for use in filter design. + beta (float, optional): shape parameter for the window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + """ + +def kl_div( + input: Tensor, + target: Tensor, + reduction: _int = 1, + *, + log_target: _bool = False, +) -> Tensor: ... +def kron( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + kron(input, other, *, out=None) -> Tensor + + Computes the Kronecker product, denoted by :math:`\otimes`, of :attr:`input` and :attr:`other`. + + If :attr:`input` is a :math:`(a_0 \times a_1 \times \dots \times a_n)` tensor and :attr:`other` is a + :math:`(b_0 \times b_1 \times \dots \times b_n)` tensor, the result will be a + :math:`(a_0*b_0 \times a_1*b_1 \times \dots \times a_n*b_n)` tensor with the following entries: + + .. math:: + (\text{input} \otimes \text{other})_{k_0, k_1, \dots, k_n} = + \text{input}_{i_0, i_1, \dots, i_n} * \text{other}_{j_0, j_1, \dots, j_n}, + + where :math:`k_t = i_t * b_t + j_t` for :math:`0 \leq t \leq n`. + If one tensor has fewer dimensions than the other it is unsqueezed until it has the same number of dimensions. + + Supports real-valued and complex-valued inputs. + + .. note:: + This function generalizes the typical definition of the Kronecker product for two matrices to two tensors, + as described above. When :attr:`input` is a :math:`(m \times n)` matrix and :attr:`other` is a + :math:`(p \times q)` matrix, the result will be a :math:`(p*m \times q*n)` block matrix: + + .. math:: + \mathbf{A} \otimes \mathbf{B}=\begin{bmatrix} + a_{11} \mathbf{B} & \cdots & a_{1 n} \mathbf{B} \\ + \vdots & \ddots & \vdots \\ + a_{m 1} \mathbf{B} & \cdots & a_{m n} \mathbf{B} \end{bmatrix} + + where :attr:`input` is :math:`\mathbf{A}` and :attr:`other` is :math:`\mathbf{B}`. + + Arguments: + input (Tensor) + other (Tensor) + + Keyword args: + out (Tensor, optional): The output tensor. Ignored if ``None``. Default: ``None`` + + Examples:: + + >>> mat1 = torch.eye(2) + >>> mat2 = torch.ones(2, 2) + >>> torch.kron(mat1, mat2) + tensor([[1., 1., 0., 0.], + [1., 1., 0., 0.], + [0., 0., 1., 1.], + [0., 0., 1., 1.]]) + + >>> mat1 = torch.eye(2) + >>> mat2 = torch.arange(1, 5).reshape(2, 2) + >>> torch.kron(mat1, mat2) + tensor([[1., 2., 0., 0.], + [3., 4., 0., 0.], + [0., 0., 1., 2.], + [0., 0., 3., 4.]]) + """ + +@overload +def kthvalue( + input: Tensor, + k: _int | SymInt, + dim: _int = -1, + keepdim: _bool = False, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.kthvalue: + r""" + kthvalue(input, k, dim=None, keepdim=False, *, out=None) -> (Tensor, LongTensor) + + Returns a namedtuple ``(values, indices)`` where ``values`` is the :attr:`k` th + smallest element of each row of the :attr:`input` tensor in the given dimension + :attr:`dim`. And ``indices`` is the index location of each element found. + + If :attr:`dim` is not given, the last dimension of the `input` is chosen. + + If :attr:`keepdim` is ``True``, both the :attr:`values` and :attr:`indices` tensors + are the same size as :attr:`input`, except in the dimension :attr:`dim` where + they are of size 1. Otherwise, :attr:`dim` is squeezed + (see :func:`torch.squeeze`), resulting in both the :attr:`values` and + :attr:`indices` tensors having 1 fewer dimension than the :attr:`input` tensor. + + .. note:: + When :attr:`input` is a CUDA tensor and there are multiple valid + :attr:`k` th values, this function may nondeterministically return + :attr:`indices` for any of them. + + Args: + input (Tensor): the input tensor. + k (int): k for the k-th smallest element + dim (int, optional): the dimension to find the kth value along + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (tuple, optional): the output tuple of (Tensor, LongTensor) + can be optionally given to be used as output buffers + + Example:: + + >>> x = torch.arange(1., 6.) + >>> x + tensor([ 1., 2., 3., 4., 5.]) + >>> torch.kthvalue(x, 4) + torch.return_types.kthvalue(values=tensor(4.), indices=tensor(3)) + + >>> x=torch.arange(1.,7.).resize_(2,3) + >>> x + tensor([[ 1., 2., 3.], + [ 4., 5., 6.]]) + >>> torch.kthvalue(x, 2, 0, True) + torch.return_types.kthvalue(values=tensor([[4., 5., 6.]]), indices=tensor([[1, 1, 1]])) + """ + +@overload +def kthvalue( + input: Tensor, + k: _int | SymInt, + dim: str | EllipsisType | None, + keepdim: _bool = False, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.kthvalue: + r""" + kthvalue(input, k, dim=None, keepdim=False, *, out=None) -> (Tensor, LongTensor) + + Returns a namedtuple ``(values, indices)`` where ``values`` is the :attr:`k` th + smallest element of each row of the :attr:`input` tensor in the given dimension + :attr:`dim`. And ``indices`` is the index location of each element found. + + If :attr:`dim` is not given, the last dimension of the `input` is chosen. + + If :attr:`keepdim` is ``True``, both the :attr:`values` and :attr:`indices` tensors + are the same size as :attr:`input`, except in the dimension :attr:`dim` where + they are of size 1. Otherwise, :attr:`dim` is squeezed + (see :func:`torch.squeeze`), resulting in both the :attr:`values` and + :attr:`indices` tensors having 1 fewer dimension than the :attr:`input` tensor. + + .. note:: + When :attr:`input` is a CUDA tensor and there are multiple valid + :attr:`k` th values, this function may nondeterministically return + :attr:`indices` for any of them. + + Args: + input (Tensor): the input tensor. + k (int): k for the k-th smallest element + dim (int, optional): the dimension to find the kth value along + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (tuple, optional): the output tuple of (Tensor, LongTensor) + can be optionally given to be used as output buffers + + Example:: + + >>> x = torch.arange(1., 6.) + >>> x + tensor([ 1., 2., 3., 4., 5.]) + >>> torch.kthvalue(x, 4) + torch.return_types.kthvalue(values=tensor(4.), indices=tensor(3)) + + >>> x=torch.arange(1.,7.).resize_(2,3) + >>> x + tensor([[ 1., 2., 3.], + [ 4., 5., 6.]]) + >>> torch.kthvalue(x, 2, 0, True) + torch.return_types.kthvalue(values=tensor([[4., 5., 6.]]), indices=tensor([[1, 1, 1]])) + """ + +def layer_norm( + input: Tensor, + normalized_shape: Sequence[_int | SymInt], + weight: Tensor | None = None, + bias: Tensor | None = None, + eps: _float = 1e-05, + cudnn_enable: _bool = True, +) -> Tensor: ... +def lcm( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + lcm(input, other, *, out=None) -> Tensor + + Computes the element-wise least common multiple (LCM) of :attr:`input` and :attr:`other`. + + Both :attr:`input` and :attr:`other` must have integer types. + + .. note:: + This defines :math:`lcm(0, 0) = 0` and :math:`lcm(0, a) = 0`. + + Args: + input (Tensor): the input tensor. + other (Tensor): the second input tensor + + Keyword arguments: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([5, 10, 15]) + >>> b = torch.tensor([3, 4, 5]) + >>> torch.lcm(a, b) + tensor([15, 20, 15]) + >>> c = torch.tensor([3]) + >>> torch.lcm(a, c) + tensor([15, 30, 15]) + """ + +def lcm_(input: Tensor, other: Tensor) -> Tensor: ... +def ldexp( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + ldexp(input, other, *, out=None) -> Tensor + + Multiplies :attr:`input` by 2 ** :attr:`other`. + + .. math:: + \text{{out}}_i = \text{{input}}_i * 2^\text{{other}}_i + + + Typically this function is used to construct floating point numbers by multiplying + mantissas in :attr:`input` with integral powers of two created from the exponents + in :attr:`other`. + + Args: + input (Tensor): the input tensor. + other (Tensor): a tensor of exponents, typically integers. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.ldexp(torch.tensor([1.]), torch.tensor([1])) + tensor([2.]) + >>> torch.ldexp(torch.tensor([1.0]), torch.tensor([1, 2, 3, 4])) + tensor([ 2., 4., 8., 16.]) + """ + +def ldexp_(input: Tensor, other: Tensor) -> Tensor: ... +@overload +def le( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + le(input, other, *, out=None) -> Tensor + + Computes :math:`\text{input} \leq \text{other}` element-wise. + + + The second argument can be a number or a tensor whose shape is + :ref:`broadcastable ` with the first argument. + + Args: + input (Tensor): the tensor to compare + other (Tensor or Scalar): the tensor or value to compare + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is less than or equal to + :attr:`other` and False elsewhere + + Example:: + + >>> torch.le(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[True, False], [True, True]]) + """ + +@overload +def le( + input: Tensor, + other: Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + le(input, other, *, out=None) -> Tensor + + Computes :math:`\text{input} \leq \text{other}` element-wise. + + + The second argument can be a number or a tensor whose shape is + :ref:`broadcastable ` with the first argument. + + Args: + input (Tensor): the tensor to compare + other (Tensor or Scalar): the tensor or value to compare + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is less than or equal to + :attr:`other` and False elsewhere + + Example:: + + >>> torch.le(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[True, False], [True, True]]) + """ + +@overload +def lerp( + input: Tensor, + end: Tensor, + weight: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + lerp(input, end, weight, *, out=None) + + Does a linear interpolation of two tensors :attr:`start` (given by :attr:`input`) and :attr:`end` based + on a scalar or tensor :attr:`weight` and returns the resulting :attr:`out` tensor. + + .. math:: + \text{out}_i = \text{start}_i + \text{weight}_i \times (\text{end}_i - \text{start}_i) + + The shapes of :attr:`start` and :attr:`end` must be + :ref:`broadcastable `. If :attr:`weight` is a tensor, then + the shapes of :attr:`weight`, :attr:`start`, and :attr:`end` must be :ref:`broadcastable `. + + Args: + input (Tensor): the tensor with the starting points + end (Tensor): the tensor with the ending points + weight (float or tensor): the weight for the interpolation formula + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> start = torch.arange(1., 5.) + >>> end = torch.empty(4).fill_(10) + >>> start + tensor([ 1., 2., 3., 4.]) + >>> end + tensor([ 10., 10., 10., 10.]) + >>> torch.lerp(start, end, 0.5) + tensor([ 5.5000, 6.0000, 6.5000, 7.0000]) + >>> torch.lerp(start, end, torch.full_like(start, 0.5)) + tensor([ 5.5000, 6.0000, 6.5000, 7.0000]) + """ + +@overload +def lerp( + input: Tensor, + end: Tensor, + weight: Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + lerp(input, end, weight, *, out=None) + + Does a linear interpolation of two tensors :attr:`start` (given by :attr:`input`) and :attr:`end` based + on a scalar or tensor :attr:`weight` and returns the resulting :attr:`out` tensor. + + .. math:: + \text{out}_i = \text{start}_i + \text{weight}_i \times (\text{end}_i - \text{start}_i) + + The shapes of :attr:`start` and :attr:`end` must be + :ref:`broadcastable `. If :attr:`weight` is a tensor, then + the shapes of :attr:`weight`, :attr:`start`, and :attr:`end` must be :ref:`broadcastable `. + + Args: + input (Tensor): the tensor with the starting points + end (Tensor): the tensor with the ending points + weight (float or tensor): the weight for the interpolation formula + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> start = torch.arange(1., 5.) + >>> end = torch.empty(4).fill_(10) + >>> start + tensor([ 1., 2., 3., 4.]) + >>> end + tensor([ 10., 10., 10., 10.]) + >>> torch.lerp(start, end, 0.5) + tensor([ 5.5000, 6.0000, 6.5000, 7.0000]) + >>> torch.lerp(start, end, torch.full_like(start, 0.5)) + tensor([ 5.5000, 6.0000, 6.5000, 7.0000]) + """ + +@overload +def less( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + less(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.lt`. + """ + +@overload +def less( + input: Tensor, + other: Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + less(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.lt`. + """ + +@overload +def less_equal( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + less_equal(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.le`. + """ + +@overload +def less_equal( + input: Tensor, + other: Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + less_equal(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.le`. + """ + +def lgamma(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + lgamma(input, *, out=None) -> Tensor + + Computes the natural logarithm of the absolute value of the gamma function on :attr:`input`. + + .. math:: + \text{out}_{i} = \ln |\Gamma(\text{input}_{i})| + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.arange(0.5, 2, 0.5) + >>> torch.lgamma(a) + tensor([ 0.5724, 0.0000, -0.1208]) + """ + +@overload +def linspace( + start: Number, + end: Number, + steps: _int | None = None, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + pin_memory: _bool = False, +) -> Tensor: + r""" + linspace(start, end, steps, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Creates a one-dimensional tensor of size :attr:`steps` whose values are evenly + spaced from :attr:`start` to :attr:`end`, inclusive. That is, the value are: + + .. math:: + (\text{start}, + \text{start} + \frac{\text{end} - \text{start}}{\text{steps} - 1}, + \ldots, + \text{start} + (\text{steps} - 2) * \frac{\text{end} - \text{start}}{\text{steps} - 1}, + \text{end}) + + + From PyTorch 1.11 linspace requires the steps argument. Use steps=100 to restore the previous behavior. + + Args: + start (float or Tensor): the starting value for the set of points. If `Tensor`, it must be 0-dimensional + end (float or Tensor): the ending value for the set of points. If `Tensor`, it must be 0-dimensional + steps (int): size of the constructed tensor + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the data type to perform the computation in. + Default: if None, uses the global default dtype (see torch.get_default_dtype()) + when both :attr:`start` and :attr:`end` are real, + and corresponding complex dtype when either is complex. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + + Example:: + + >>> torch.linspace(3, 10, steps=5) + tensor([ 3.0000, 4.7500, 6.5000, 8.2500, 10.0000]) + >>> torch.linspace(-10, 10, steps=5) + tensor([-10., -5., 0., 5., 10.]) + >>> torch.linspace(start=-10, end=10, steps=5) + tensor([-10., -5., 0., 5., 10.]) + >>> torch.linspace(start=-10, end=10, steps=1) + tensor([-10.]) + """ + +@overload +def linspace( + start: Tensor, + end: Tensor, + steps: _int, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + linspace(start, end, steps, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Creates a one-dimensional tensor of size :attr:`steps` whose values are evenly + spaced from :attr:`start` to :attr:`end`, inclusive. That is, the value are: + + .. math:: + (\text{start}, + \text{start} + \frac{\text{end} - \text{start}}{\text{steps} - 1}, + \ldots, + \text{start} + (\text{steps} - 2) * \frac{\text{end} - \text{start}}{\text{steps} - 1}, + \text{end}) + + + From PyTorch 1.11 linspace requires the steps argument. Use steps=100 to restore the previous behavior. + + Args: + start (float or Tensor): the starting value for the set of points. If `Tensor`, it must be 0-dimensional + end (float or Tensor): the ending value for the set of points. If `Tensor`, it must be 0-dimensional + steps (int): size of the constructed tensor + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the data type to perform the computation in. + Default: if None, uses the global default dtype (see torch.get_default_dtype()) + when both :attr:`start` and :attr:`end` are real, + and corresponding complex dtype when either is complex. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + + Example:: + + >>> torch.linspace(3, 10, steps=5) + tensor([ 3.0000, 4.7500, 6.5000, 8.2500, 10.0000]) + >>> torch.linspace(-10, 10, steps=5) + tensor([-10., -5., 0., 5., 10.]) + >>> torch.linspace(start=-10, end=10, steps=5) + tensor([-10., -5., 0., 5., 10.]) + >>> torch.linspace(start=-10, end=10, steps=1) + tensor([-10.]) + """ + +@overload +def linspace( + start: Number | _complex, + end: Tensor, + steps: _int, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + linspace(start, end, steps, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Creates a one-dimensional tensor of size :attr:`steps` whose values are evenly + spaced from :attr:`start` to :attr:`end`, inclusive. That is, the value are: + + .. math:: + (\text{start}, + \text{start} + \frac{\text{end} - \text{start}}{\text{steps} - 1}, + \ldots, + \text{start} + (\text{steps} - 2) * \frac{\text{end} - \text{start}}{\text{steps} - 1}, + \text{end}) + + + From PyTorch 1.11 linspace requires the steps argument. Use steps=100 to restore the previous behavior. + + Args: + start (float or Tensor): the starting value for the set of points. If `Tensor`, it must be 0-dimensional + end (float or Tensor): the ending value for the set of points. If `Tensor`, it must be 0-dimensional + steps (int): size of the constructed tensor + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the data type to perform the computation in. + Default: if None, uses the global default dtype (see torch.get_default_dtype()) + when both :attr:`start` and :attr:`end` are real, + and corresponding complex dtype when either is complex. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + + Example:: + + >>> torch.linspace(3, 10, steps=5) + tensor([ 3.0000, 4.7500, 6.5000, 8.2500, 10.0000]) + >>> torch.linspace(-10, 10, steps=5) + tensor([-10., -5., 0., 5., 10.]) + >>> torch.linspace(start=-10, end=10, steps=5) + tensor([-10., -5., 0., 5., 10.]) + >>> torch.linspace(start=-10, end=10, steps=1) + tensor([-10.]) + """ + +@overload +def linspace( + start: Tensor, + end: Number | _complex, + steps: _int, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + linspace(start, end, steps, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Creates a one-dimensional tensor of size :attr:`steps` whose values are evenly + spaced from :attr:`start` to :attr:`end`, inclusive. That is, the value are: + + .. math:: + (\text{start}, + \text{start} + \frac{\text{end} - \text{start}}{\text{steps} - 1}, + \ldots, + \text{start} + (\text{steps} - 2) * \frac{\text{end} - \text{start}}{\text{steps} - 1}, + \text{end}) + + + From PyTorch 1.11 linspace requires the steps argument. Use steps=100 to restore the previous behavior. + + Args: + start (float or Tensor): the starting value for the set of points. If `Tensor`, it must be 0-dimensional + end (float or Tensor): the ending value for the set of points. If `Tensor`, it must be 0-dimensional + steps (int): size of the constructed tensor + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the data type to perform the computation in. + Default: if None, uses the global default dtype (see torch.get_default_dtype()) + when both :attr:`start` and :attr:`end` are real, + and corresponding complex dtype when either is complex. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + + Example:: + + >>> torch.linspace(3, 10, steps=5) + tensor([ 3.0000, 4.7500, 6.5000, 8.2500, 10.0000]) + >>> torch.linspace(-10, 10, steps=5) + tensor([-10., -5., 0., 5., 10.]) + >>> torch.linspace(start=-10, end=10, steps=5) + tensor([-10., -5., 0., 5., 10.]) + >>> torch.linspace(start=-10, end=10, steps=1) + tensor([-10.]) + """ + +@overload +def linspace( + start: Number | _complex, + end: Number | _complex, + steps: _int, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + linspace(start, end, steps, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Creates a one-dimensional tensor of size :attr:`steps` whose values are evenly + spaced from :attr:`start` to :attr:`end`, inclusive. That is, the value are: + + .. math:: + (\text{start}, + \text{start} + \frac{\text{end} - \text{start}}{\text{steps} - 1}, + \ldots, + \text{start} + (\text{steps} - 2) * \frac{\text{end} - \text{start}}{\text{steps} - 1}, + \text{end}) + + + From PyTorch 1.11 linspace requires the steps argument. Use steps=100 to restore the previous behavior. + + Args: + start (float or Tensor): the starting value for the set of points. If `Tensor`, it must be 0-dimensional + end (float or Tensor): the ending value for the set of points. If `Tensor`, it must be 0-dimensional + steps (int): size of the constructed tensor + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the data type to perform the computation in. + Default: if None, uses the global default dtype (see torch.get_default_dtype()) + when both :attr:`start` and :attr:`end` are real, + and corresponding complex dtype when either is complex. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + + Example:: + + >>> torch.linspace(3, 10, steps=5) + tensor([ 3.0000, 4.7500, 6.5000, 8.2500, 10.0000]) + >>> torch.linspace(-10, 10, steps=5) + tensor([-10., -5., 0., 5., 10.]) + >>> torch.linspace(start=-10, end=10, steps=5) + tensor([-10., -5., 0., 5., 10.]) + >>> torch.linspace(start=-10, end=10, steps=1) + tensor([-10.]) + """ + +def log(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + log(input, *, out=None) -> Tensor + + Returns a new tensor with the natural logarithm of the elements + of :attr:`input`. + + .. math:: + y_{i} = \log_{e} (x_{i}) + + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(5) * 5 + >>> a + tensor([4.7767, 4.3234, 1.2156, 0.2411, 4.5739]) + >>> torch.log(a) + tensor([ 1.5637, 1.4640, 0.1952, -1.4226, 1.5204]) + """ + +def log10(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + log10(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Returns a new tensor with the logarithm to the base 10 of the elements + of :attr:`input`. + + .. math:: + y_{i} = \log_{10} (x_{i}) + + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(5) + >>> a + tensor([ 0.5224, 0.9354, 0.7257, 0.1301, 0.2251]) + + + >>> torch.log10(a) + tensor([-0.2820, -0.0290, -0.1392, -0.8857, -0.6476]) + """ + +def log10_(input: Tensor) -> Tensor: ... +def log1p(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + log1p(input, *, out=None) -> Tensor + + Returns a new tensor with the natural logarithm of (1 + :attr:`input`). + + .. math:: + y_i = \log_{e} (x_i + 1) + + .. note:: This function is more accurate than :func:`torch.log` for small + values of :attr:`input` + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(5) + >>> a + tensor([-1.0090, -0.9923, 1.0249, -0.5372, 0.2492]) + >>> torch.log1p(a) + tensor([ nan, -4.8653, 0.7055, -0.7705, 0.2225]) + """ + +def log1p_(input: Tensor) -> Tensor: ... +def log2(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + log2(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Returns a new tensor with the logarithm to the base 2 of the elements + of :attr:`input`. + + .. math:: + y_{i} = \log_{2} (x_{i}) + + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(5) + >>> a + tensor([ 0.8419, 0.8003, 0.9971, 0.5287, 0.0490]) + + + >>> torch.log2(a) + tensor([-0.2483, -0.3213, -0.0042, -0.9196, -4.3504]) + """ + +def log2_(input: Tensor) -> Tensor: ... +def log_(input: Tensor) -> Tensor: ... +@overload +def log_softmax( + input: Tensor, + dim: _int, + dtype: _dtype | None = None, + *, + out: Tensor | None = None, +) -> Tensor: ... +@overload +def log_softmax( + input: Tensor, + dim: str | EllipsisType | None, + *, + dtype: _dtype | None = None, +) -> Tensor: ... +def logaddexp( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + logaddexp(input, other, *, out=None) -> Tensor + + Logarithm of the sum of exponentiations of the inputs. + + Calculates pointwise :math:`\log\left(e^x + e^y\right)`. This function is useful + in statistics where the calculated probabilities of events may be so small as to + exceed the range of normal floating point numbers. In such cases the logarithm + of the calculated probability is stored. This function allows adding + probabilities stored in such a fashion. + + This op should be disambiguated with :func:`torch.logsumexp` which performs a + reduction on a single tensor. + + Args: + input (Tensor): the input tensor. + other (Tensor): the second input tensor + + Keyword arguments: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.logaddexp(torch.tensor([-1.0]), torch.tensor([-1.0, -2, -3])) + tensor([-0.3069, -0.6867, -0.8731]) + >>> torch.logaddexp(torch.tensor([-100.0, -200, -300]), torch.tensor([-1.0, -2, -3])) + tensor([-1., -2., -3.]) + >>> torch.logaddexp(torch.tensor([1.0, 2000, 30000]), torch.tensor([-1.0, -2, -3])) + tensor([1.1269e+00, 2.0000e+03, 3.0000e+04]) + """ + +def logaddexp2( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + logaddexp2(input, other, *, out=None) -> Tensor + + Logarithm of the sum of exponentiations of the inputs in base-2. + + Calculates pointwise :math:`\log_2\left(2^x + 2^y\right)`. See + :func:`torch.logaddexp` for more details. + + Args: + input (Tensor): the input tensor. + other (Tensor): the second input tensor + + Keyword arguments: + out (Tensor, optional): the output tensor. + """ + +@overload +def logcumsumexp( + input: Tensor, + dim: _int, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + logcumsumexp(input, dim, *, out=None) -> Tensor + Returns the logarithm of the cumulative summation of the exponentiation of + elements of :attr:`input` in the dimension :attr:`dim`. + + For summation index :math:`j` given by `dim` and other indices :math:`i`, the result is + + .. math:: + \text{logcumsumexp}(x)_{ij} = \log \sum\limits_{k=0}^{j} \exp(x_{ik}) + + Args: + input (Tensor): the input tensor. + dim (int): the dimension to do the operation over + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(10) + >>> torch.logcumsumexp(a, dim=0) + tensor([-0.42296738, -0.04462666, 0.86278635, 0.94622083, 1.05277811, + 1.39202815, 1.83525007, 1.84492621, 2.06084887, 2.06844475])) + """ + +@overload +def logcumsumexp( + input: Tensor, + dim: str | EllipsisType | None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + logcumsumexp(input, dim, *, out=None) -> Tensor + Returns the logarithm of the cumulative summation of the exponentiation of + elements of :attr:`input` in the dimension :attr:`dim`. + + For summation index :math:`j` given by `dim` and other indices :math:`i`, the result is + + .. math:: + \text{logcumsumexp}(x)_{ij} = \log \sum\limits_{k=0}^{j} \exp(x_{ik}) + + Args: + input (Tensor): the input tensor. + dim (int): the dimension to do the operation over + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(10) + >>> torch.logcumsumexp(a, dim=0) + tensor([-0.42296738, -0.04462666, 0.86278635, 0.94622083, 1.05277811, + 1.39202815, 1.83525007, 1.84492621, 2.06084887, 2.06844475])) + """ + +def logdet(input: Tensor) -> Tensor: + r""" + logdet(input) -> Tensor + + Calculates log determinant of a square matrix or batches of square matrices. + + It returns ``-inf`` if the input has a determinant of zero, and ``NaN`` if it has + a negative determinant. + + .. note:: + Backward through :meth:`logdet` internally uses SVD results when :attr:`input` + is not invertible. In this case, double backward through :meth:`logdet` will + be unstable in when :attr:`input` doesn't have distinct singular values. See + :func:`torch.linalg.svd` for details. + + .. seealso:: + + :func:`torch.linalg.slogdet` computes the sign (resp. angle) and natural logarithm of the + absolute value of the determinant of real-valued (resp. complex) square matrices. + + Arguments: + input (Tensor): the input tensor of size ``(*, n, n)`` where ``*`` is zero or more + batch dimensions. + + Example:: + + >>> A = torch.randn(3, 3) + >>> torch.det(A) + tensor(0.2611) + >>> torch.logdet(A) + tensor(-1.3430) + >>> A + tensor([[[ 0.9254, -0.6213], + [-0.5787, 1.6843]], + + [[ 0.3242, -0.9665], + [ 0.4539, -0.0887]], + + [[ 1.1336, -0.4025], + [-0.7089, 0.9032]]]) + >>> A.det() + tensor([1.1990, 0.4099, 0.7386]) + >>> A.det().log() + tensor([ 0.1815, -0.8917, -0.3031]) + """ + +def logical_and( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + logical_and(input, other, *, out=None) -> Tensor + + Computes the element-wise logical AND of the given input tensors. Zeros are treated as ``False`` and nonzeros are + treated as ``True``. + + Args: + input (Tensor): the input tensor. + other (Tensor): the tensor to compute AND with + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.logical_and(torch.tensor([True, False, True]), torch.tensor([True, False, False])) + tensor([ True, False, False]) + >>> a = torch.tensor([0, 1, 10, 0], dtype=torch.int8) + >>> b = torch.tensor([4, 0, 1, 0], dtype=torch.int8) + >>> torch.logical_and(a, b) + tensor([False, False, True, False]) + >>> torch.logical_and(a.double(), b.double()) + tensor([False, False, True, False]) + >>> torch.logical_and(a.double(), b) + tensor([False, False, True, False]) + >>> torch.logical_and(a, b, out=torch.empty(4, dtype=torch.bool)) + tensor([False, False, True, False]) + """ + +def logical_not(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + logical_not(input, *, out=None) -> Tensor + + Computes the element-wise logical NOT of the given input tensor. If not specified, the output tensor will have the bool + dtype. If the input tensor is not a bool tensor, zeros are treated as ``False`` and non-zeros are treated as ``True``. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.logical_not(torch.tensor([True, False])) + tensor([False, True]) + >>> torch.logical_not(torch.tensor([0, 1, -10], dtype=torch.int8)) + tensor([ True, False, False]) + >>> torch.logical_not(torch.tensor([0., 1.5, -10.], dtype=torch.double)) + tensor([ True, False, False]) + >>> torch.logical_not(torch.tensor([0., 1., -10.], dtype=torch.double), out=torch.empty(3, dtype=torch.int16)) + tensor([1, 0, 0], dtype=torch.int16) + """ + +def logical_or( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + logical_or(input, other, *, out=None) -> Tensor + + Computes the element-wise logical OR of the given input tensors. Zeros are treated as ``False`` and nonzeros are + treated as ``True``. + + Args: + input (Tensor): the input tensor. + other (Tensor): the tensor to compute OR with + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.logical_or(torch.tensor([True, False, True]), torch.tensor([True, False, False])) + tensor([ True, False, True]) + >>> a = torch.tensor([0, 1, 10, 0], dtype=torch.int8) + >>> b = torch.tensor([4, 0, 1, 0], dtype=torch.int8) + >>> torch.logical_or(a, b) + tensor([ True, True, True, False]) + >>> torch.logical_or(a.double(), b.double()) + tensor([ True, True, True, False]) + >>> torch.logical_or(a.double(), b) + tensor([ True, True, True, False]) + >>> torch.logical_or(a, b, out=torch.empty(4, dtype=torch.bool)) + tensor([ True, True, True, False]) + """ + +def logical_xor( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + logical_xor(input: Tensor, other: Tensor, *, out: Optional[Tensor]) -> Tensor + + Computes the element-wise logical XOR of the given input tensors. Zeros are treated as ``False`` and nonzeros are + treated as ``True``. + + Args: + input (Tensor): the input tensor. + other (Tensor): the tensor to compute XOR with + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.logical_xor(torch.tensor([True, False, True]), torch.tensor([True, False, False])) + tensor([False, False, True]) + >>> a = torch.tensor([0, 1, 10, 0], dtype=torch.int8) + >>> b = torch.tensor([4, 0, 1, 0], dtype=torch.int8) + >>> torch.logical_xor(a, b) + tensor([ True, True, False, False]) + >>> torch.logical_xor(a.double(), b.double()) + tensor([ True, True, False, False]) + >>> torch.logical_xor(a.double(), b) + tensor([ True, True, False, False]) + >>> torch.logical_xor(a, b, out=torch.empty(4, dtype=torch.bool)) + tensor([ True, True, False, False]) + """ + +def logit( + input: Tensor, + eps: _float | None = None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + logit(input, eps=None, *, out=None) -> Tensor + + Alias for :func:`torch.special.logit`. + """ + +def logit_(input: Tensor, eps: _float | None = None) -> Tensor: ... +@overload +def logspace( + start: Number, + end: Number, + steps: _int | None = None, + base: _float = 10.0, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + pin_memory: _bool = False, +) -> Tensor: + r""" + logspace(start, end, steps, base=10.0, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + + Creates a one-dimensional tensor of size :attr:`steps` whose values are evenly + spaced from :math:`{{\text{{base}}}}^{{\text{{start}}}}` to + :math:`{{\text{{base}}}}^{{\text{{end}}}}`, inclusive, on a logarithmic scale + with base :attr:`base`. That is, the values are: + + .. math:: + (\text{base}^{\text{start}}, + \text{base}^{(\text{start} + \frac{\text{end} - \text{start}}{ \text{steps} - 1})}, + \ldots, + \text{base}^{(\text{start} + (\text{steps} - 2) * \frac{\text{end} - \text{start}}{ \text{steps} - 1})}, + \text{base}^{\text{end}}) + + + + From PyTorch 1.11 logspace requires the steps argument. Use steps=100 to restore the previous behavior. + + Args: + start (float or Tensor): the starting value for the set of points. If `Tensor`, it must be 0-dimensional + end (float or Tensor): the ending value for the set of points. If `Tensor`, it must be 0-dimensional + steps (int): size of the constructed tensor + base (float, optional): base of the logarithm function. Default: ``10.0``. + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the data type to perform the computation in. + Default: if None, uses the global default dtype (see torch.get_default_dtype()) + when both :attr:`start` and :attr:`end` are real, + and corresponding complex dtype when either is complex. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.logspace(start=-10, end=10, steps=5) + tensor([ 1.0000e-10, 1.0000e-05, 1.0000e+00, 1.0000e+05, 1.0000e+10]) + >>> torch.logspace(start=0.1, end=1.0, steps=5) + tensor([ 1.2589, 2.1135, 3.5481, 5.9566, 10.0000]) + >>> torch.logspace(start=0.1, end=1.0, steps=1) + tensor([1.2589]) + >>> torch.logspace(start=2, end=2, steps=1, base=2) + tensor([4.0]) + """ + +@overload +def logspace( + start: Tensor, + end: Tensor, + steps: _int, + base: _float = 10.0, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + logspace(start, end, steps, base=10.0, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + + Creates a one-dimensional tensor of size :attr:`steps` whose values are evenly + spaced from :math:`{{\text{{base}}}}^{{\text{{start}}}}` to + :math:`{{\text{{base}}}}^{{\text{{end}}}}`, inclusive, on a logarithmic scale + with base :attr:`base`. That is, the values are: + + .. math:: + (\text{base}^{\text{start}}, + \text{base}^{(\text{start} + \frac{\text{end} - \text{start}}{ \text{steps} - 1})}, + \ldots, + \text{base}^{(\text{start} + (\text{steps} - 2) * \frac{\text{end} - \text{start}}{ \text{steps} - 1})}, + \text{base}^{\text{end}}) + + + + From PyTorch 1.11 logspace requires the steps argument. Use steps=100 to restore the previous behavior. + + Args: + start (float or Tensor): the starting value for the set of points. If `Tensor`, it must be 0-dimensional + end (float or Tensor): the ending value for the set of points. If `Tensor`, it must be 0-dimensional + steps (int): size of the constructed tensor + base (float, optional): base of the logarithm function. Default: ``10.0``. + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the data type to perform the computation in. + Default: if None, uses the global default dtype (see torch.get_default_dtype()) + when both :attr:`start` and :attr:`end` are real, + and corresponding complex dtype when either is complex. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.logspace(start=-10, end=10, steps=5) + tensor([ 1.0000e-10, 1.0000e-05, 1.0000e+00, 1.0000e+05, 1.0000e+10]) + >>> torch.logspace(start=0.1, end=1.0, steps=5) + tensor([ 1.2589, 2.1135, 3.5481, 5.9566, 10.0000]) + >>> torch.logspace(start=0.1, end=1.0, steps=1) + tensor([1.2589]) + >>> torch.logspace(start=2, end=2, steps=1, base=2) + tensor([4.0]) + """ + +@overload +def logspace( + start: Number | _complex, + end: Tensor, + steps: _int, + base: _float = 10.0, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + logspace(start, end, steps, base=10.0, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + + Creates a one-dimensional tensor of size :attr:`steps` whose values are evenly + spaced from :math:`{{\text{{base}}}}^{{\text{{start}}}}` to + :math:`{{\text{{base}}}}^{{\text{{end}}}}`, inclusive, on a logarithmic scale + with base :attr:`base`. That is, the values are: + + .. math:: + (\text{base}^{\text{start}}, + \text{base}^{(\text{start} + \frac{\text{end} - \text{start}}{ \text{steps} - 1})}, + \ldots, + \text{base}^{(\text{start} + (\text{steps} - 2) * \frac{\text{end} - \text{start}}{ \text{steps} - 1})}, + \text{base}^{\text{end}}) + + + + From PyTorch 1.11 logspace requires the steps argument. Use steps=100 to restore the previous behavior. + + Args: + start (float or Tensor): the starting value for the set of points. If `Tensor`, it must be 0-dimensional + end (float or Tensor): the ending value for the set of points. If `Tensor`, it must be 0-dimensional + steps (int): size of the constructed tensor + base (float, optional): base of the logarithm function. Default: ``10.0``. + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the data type to perform the computation in. + Default: if None, uses the global default dtype (see torch.get_default_dtype()) + when both :attr:`start` and :attr:`end` are real, + and corresponding complex dtype when either is complex. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.logspace(start=-10, end=10, steps=5) + tensor([ 1.0000e-10, 1.0000e-05, 1.0000e+00, 1.0000e+05, 1.0000e+10]) + >>> torch.logspace(start=0.1, end=1.0, steps=5) + tensor([ 1.2589, 2.1135, 3.5481, 5.9566, 10.0000]) + >>> torch.logspace(start=0.1, end=1.0, steps=1) + tensor([1.2589]) + >>> torch.logspace(start=2, end=2, steps=1, base=2) + tensor([4.0]) + """ + +@overload +def logspace( + start: Tensor, + end: Number | _complex, + steps: _int, + base: _float = 10.0, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + logspace(start, end, steps, base=10.0, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + + Creates a one-dimensional tensor of size :attr:`steps` whose values are evenly + spaced from :math:`{{\text{{base}}}}^{{\text{{start}}}}` to + :math:`{{\text{{base}}}}^{{\text{{end}}}}`, inclusive, on a logarithmic scale + with base :attr:`base`. That is, the values are: + + .. math:: + (\text{base}^{\text{start}}, + \text{base}^{(\text{start} + \frac{\text{end} - \text{start}}{ \text{steps} - 1})}, + \ldots, + \text{base}^{(\text{start} + (\text{steps} - 2) * \frac{\text{end} - \text{start}}{ \text{steps} - 1})}, + \text{base}^{\text{end}}) + + + + From PyTorch 1.11 logspace requires the steps argument. Use steps=100 to restore the previous behavior. + + Args: + start (float or Tensor): the starting value for the set of points. If `Tensor`, it must be 0-dimensional + end (float or Tensor): the ending value for the set of points. If `Tensor`, it must be 0-dimensional + steps (int): size of the constructed tensor + base (float, optional): base of the logarithm function. Default: ``10.0``. + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the data type to perform the computation in. + Default: if None, uses the global default dtype (see torch.get_default_dtype()) + when both :attr:`start` and :attr:`end` are real, + and corresponding complex dtype when either is complex. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.logspace(start=-10, end=10, steps=5) + tensor([ 1.0000e-10, 1.0000e-05, 1.0000e+00, 1.0000e+05, 1.0000e+10]) + >>> torch.logspace(start=0.1, end=1.0, steps=5) + tensor([ 1.2589, 2.1135, 3.5481, 5.9566, 10.0000]) + >>> torch.logspace(start=0.1, end=1.0, steps=1) + tensor([1.2589]) + >>> torch.logspace(start=2, end=2, steps=1, base=2) + tensor([4.0]) + """ + +@overload +def logspace( + start: Number | _complex, + end: Number | _complex, + steps: _int, + base: _float = 10.0, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + logspace(start, end, steps, base=10.0, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + + Creates a one-dimensional tensor of size :attr:`steps` whose values are evenly + spaced from :math:`{{\text{{base}}}}^{{\text{{start}}}}` to + :math:`{{\text{{base}}}}^{{\text{{end}}}}`, inclusive, on a logarithmic scale + with base :attr:`base`. That is, the values are: + + .. math:: + (\text{base}^{\text{start}}, + \text{base}^{(\text{start} + \frac{\text{end} - \text{start}}{ \text{steps} - 1})}, + \ldots, + \text{base}^{(\text{start} + (\text{steps} - 2) * \frac{\text{end} - \text{start}}{ \text{steps} - 1})}, + \text{base}^{\text{end}}) + + + + From PyTorch 1.11 logspace requires the steps argument. Use steps=100 to restore the previous behavior. + + Args: + start (float or Tensor): the starting value for the set of points. If `Tensor`, it must be 0-dimensional + end (float or Tensor): the ending value for the set of points. If `Tensor`, it must be 0-dimensional + steps (int): size of the constructed tensor + base (float, optional): base of the logarithm function. Default: ``10.0``. + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the data type to perform the computation in. + Default: if None, uses the global default dtype (see torch.get_default_dtype()) + when both :attr:`start` and :attr:`end` are real, + and corresponding complex dtype when either is complex. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.logspace(start=-10, end=10, steps=5) + tensor([ 1.0000e-10, 1.0000e-05, 1.0000e+00, 1.0000e+05, 1.0000e+10]) + >>> torch.logspace(start=0.1, end=1.0, steps=5) + tensor([ 1.2589, 2.1135, 3.5481, 5.9566, 10.0000]) + >>> torch.logspace(start=0.1, end=1.0, steps=1) + tensor([1.2589]) + >>> torch.logspace(start=2, end=2, steps=1, base=2) + tensor([4.0]) + """ + +@overload +def logsumexp( + input: Tensor, + dim: _int | _size, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + logsumexp(input, dim, keepdim=False, *, out=None) + + Returns the log of summed exponentials of each row of the :attr:`input` + tensor in the given dimension :attr:`dim`. The computation is numerically + stabilized. + + For summation index :math:`j` given by `dim` and other indices :math:`i`, the result is + + .. math:: + \text{logsumexp}(x)_{i} = \log \sum_j \exp(x_{ij}) + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + dim (int or tuple of ints): the dimension or dimensions to reduce. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(3, 3) + >>> torch.logsumexp(a, 1) + tensor([1.4907, 1.0593, 1.5696]) + >>> torch.dist(torch.logsumexp(a, 1), torch.log(torch.sum(torch.exp(a), 1))) + tensor(1.6859e-07) + """ + +@overload +def logsumexp( + input: Tensor, + dim: Sequence[str | EllipsisType | None], + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + logsumexp(input, dim, keepdim=False, *, out=None) + + Returns the log of summed exponentials of each row of the :attr:`input` + tensor in the given dimension :attr:`dim`. The computation is numerically + stabilized. + + For summation index :math:`j` given by `dim` and other indices :math:`i`, the result is + + .. math:: + \text{logsumexp}(x)_{i} = \log \sum_j \exp(x_{ij}) + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + dim (int or tuple of ints): the dimension or dimensions to reduce. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(3, 3) + >>> torch.logsumexp(a, 1) + tensor([1.4907, 1.0593, 1.5696]) + >>> torch.dist(torch.logsumexp(a, 1), torch.log(torch.sum(torch.exp(a), 1))) + tensor(1.6859e-07) + """ + +@overload +def lstm( + data: Tensor, + batch_sizes: Tensor, + hx: tuple[Tensor, ...] | list[Tensor] | None, + params: tuple[Tensor, ...] | list[Tensor] | None, + has_biases: _bool, + num_layers: _int, + dropout: _float, + train: _bool, + bidirectional: _bool, +) -> tuple[Tensor, Tensor, Tensor]: ... +@overload +def lstm( + input: Tensor, + hx: tuple[Tensor, ...] | list[Tensor] | None, + params: tuple[Tensor, ...] | list[Tensor] | None, + has_biases: _bool, + num_layers: _int, + dropout: _float, + train: _bool, + bidirectional: _bool, + batch_first: _bool, +) -> tuple[Tensor, Tensor, Tensor]: ... +def lstm_cell( + input: Tensor, + hx: tuple[Tensor, ...] | list[Tensor] | None, + w_ih: Tensor, + w_hh: Tensor, + b_ih: Tensor | None = None, + b_hh: Tensor | None = None, +) -> tuple[Tensor, Tensor]: ... +@overload +def lt( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + lt(input, other, *, out=None) -> Tensor + + Computes :math:`\text{input} < \text{other}` element-wise. + + + The second argument can be a number or a tensor whose shape is + :ref:`broadcastable ` with the first argument. + + Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is less than :attr:`other` and False elsewhere + + Example:: + + >>> torch.lt(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[False, False], [True, False]]) + """ + +@overload +def lt( + input: Tensor, + other: Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + lt(input, other, *, out=None) -> Tensor + + Computes :math:`\text{input} < \text{other}` element-wise. + + + The second argument can be a number or a tensor whose shape is + :ref:`broadcastable ` with the first argument. + + Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is less than :attr:`other` and False elsewhere + + Example:: + + >>> torch.lt(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[False, False], [True, False]]) + """ + +def lu_solve( + input: Tensor, + LU_data: Tensor, + LU_pivots: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + lu_solve(b, LU_data, LU_pivots, *, out=None) -> Tensor + + Returns the LU solve of the linear system :math:`Ax = b` using the partially pivoted + LU factorization of A from :func:`~linalg.lu_factor`. + + This function supports ``float``, ``double``, ``cfloat`` and ``cdouble`` dtypes for :attr:`input`. + + .. warning:: + + :func:`torch.lu_solve` is deprecated in favor of :func:`torch.linalg.lu_solve`. + :func:`torch.lu_solve` will be removed in a future PyTorch release. + ``X = torch.lu_solve(B, LU, pivots)`` should be replaced with + + .. code:: python + + X = linalg.lu_solve(LU, pivots, B) + + Arguments: + b (Tensor): the RHS tensor of size :math:`(*, m, k)`, where :math:`*` + is zero or more batch dimensions. + LU_data (Tensor): the pivoted LU factorization of A from :meth:`~linalg.lu_factor` of size :math:`(*, m, m)`, + where :math:`*` is zero or more batch dimensions. + LU_pivots (IntTensor): the pivots of the LU factorization from :meth:`~linalg.lu_factor` of size :math:`(*, m)`, + where :math:`*` is zero or more batch dimensions. + The batch dimensions of :attr:`LU_pivots` must be equal to the batch dimensions of + :attr:`LU_data`. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> A = torch.randn(2, 3, 3) + >>> b = torch.randn(2, 3, 1) + >>> LU, pivots = torch.linalg.lu_factor(A) + >>> x = torch.lu_solve(b, LU, pivots) + >>> torch.dist(A @ x, b) + tensor(1.00000e-07 * + 2.8312) + """ + +def lu_unpack( + LU_data: Tensor, + LU_pivots: Tensor, + unpack_data: _bool = True, + unpack_pivots: _bool = True, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.lu_unpack: + r""" + lu_unpack(LU_data, LU_pivots, unpack_data=True, unpack_pivots=True, *, out=None) -> (Tensor, Tensor, Tensor) + + Unpacks the LU decomposition returned by :func:`~linalg.lu_factor` into the `P, L, U` matrices. + + .. seealso:: + + :func:`~linalg.lu` returns the matrices from the LU decomposition. Its gradient formula is more efficient + than that of doing :func:`~linalg.lu_factor` followed by :func:`~linalg.lu_unpack`. + + Args: + LU_data (Tensor): the packed LU factorization data + LU_pivots (Tensor): the packed LU factorization pivots + unpack_data (bool): flag indicating if the data should be unpacked. + If ``False``, then the returned ``L`` and ``U`` are empty tensors. + Default: ``True`` + unpack_pivots (bool): flag indicating if the pivots should be unpacked into a permutation matrix ``P``. + If ``False``, then the returned ``P`` is an empty tensor. + Default: ``True`` + + Keyword args: + out (tuple, optional): output tuple of three tensors. Ignored if `None`. + + Returns: + A namedtuple ``(P, L, U)`` + + Examples:: + + >>> A = torch.randn(2, 3, 3) + >>> LU, pivots = torch.linalg.lu_factor(A) + >>> P, L, U = torch.lu_unpack(LU, pivots) + >>> # We can recover A from the factorization + >>> A_ = P @ L @ U + >>> torch.allclose(A, A_) + True + + >>> # LU factorization of a rectangular matrix: + >>> A = torch.randn(2, 3, 2) + >>> LU, pivots = torch.linalg.lu_factor(A) + >>> P, L, U = torch.lu_unpack(LU, pivots) + >>> # P, L, U are the same as returned by linalg.lu + >>> P_, L_, U_ = torch.linalg.lu(A) + >>> torch.allclose(P, P_) and torch.allclose(L, L_) and torch.allclose(U, U_) + True + """ + +def margin_ranking_loss( + input1: Tensor, + input2: Tensor, + target: Tensor, + margin: _float = 0.0, + reduction: _int = 1, +) -> Tensor: ... +@overload +def masked_fill(input: Tensor, mask: Tensor, value: Tensor) -> Tensor: ... +@overload +def masked_fill( + input: Tensor, + mask: Tensor, + value: Number | _complex, +) -> Tensor: ... +def masked_scatter(input: Tensor, mask: Tensor, source: Tensor) -> Tensor: ... +def masked_select( + input: Tensor, + mask: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + masked_select(input, mask, *, out=None) -> Tensor + + Returns a new 1-D tensor which indexes the :attr:`input` tensor according to + the boolean mask :attr:`mask` which is a `BoolTensor`. + + The shapes of the :attr:`mask` tensor and the :attr:`input` tensor don't need + to match, but they must be :ref:`broadcastable `. + + .. note:: The returned tensor does **not** use the same storage + as the original tensor + + Args: + input (Tensor): the input tensor. + mask (BoolTensor): the tensor containing the binary mask to index with + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> x = torch.randn(3, 4) + >>> x + tensor([[ 0.3552, -2.3825, -0.8297, 0.3477], + [-1.2035, 1.2252, 0.5002, 0.6248], + [ 0.1307, -2.0608, 0.1244, 2.0139]]) + >>> mask = x.ge(0.5) + >>> mask + tensor([[False, False, False, False], + [False, True, True, True], + [False, False, False, True]]) + >>> torch.masked_select(x, mask) + tensor([ 1.2252, 0.5002, 0.6248, 2.0139]) + """ + +def matmul( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + matmul(input, other, *, out=None) -> Tensor + + Matrix product of two tensors. + + The behavior depends on the dimensionality of the tensors as follows: + + - If both tensors are 1-dimensional, the dot product (scalar) is returned. + - If both arguments are 2-dimensional, the matrix-matrix product is returned. + - If the first argument is 1-dimensional and the second argument is 2-dimensional, + a 1 is prepended to its dimension for the purpose of the matrix multiply. + After the matrix multiply, the prepended dimension is removed. + - If the first argument is 2-dimensional and the second argument is 1-dimensional, + the matrix-vector product is returned. + - If both arguments are at least 1-dimensional and at least one argument is + N-dimensional (where N > 2), then a batched matrix multiply is returned. If the first + argument is 1-dimensional, a 1 is prepended to its dimension for the purpose of the + batched matrix multiply and removed after. If the second argument is 1-dimensional, a + 1 is appended to its dimension for the purpose of the batched matrix multiply and removed after. + + The first N-2 dimensions of each argument, the batch dimensions, are + :ref:`broadcast ` (and thus must be broadcastable). + The last 2, the matrix dimensions, are handled as in the matrix-matrix product. + + For example, if :attr:`input` is a + :math:`(j \times 1 \times n \times m)` tensor and :attr:`other` is a :math:`(k \times m \times p)` + tensor, the batch dimensions are :math:`(j \times 1)` and :math:`(k)`, + and the matrix dimensions are :math:`(n \times m)` and :math:`(m \times p)`. + :attr:`out` will be a :math:`(j \times k \times n \times p)` tensor. + + This operation has support for arguments with :ref:`sparse layouts`. In particular the + matrix-matrix (both arguments 2-dimensional) supports sparse arguments with the same restrictions + as :func:`torch.mm` + + + .. warning:: + Sparse support is a beta feature and some layout(s)/dtype/device combinations may not be supported, + or may not have autograd support. If you notice missing functionality please + open a feature request. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + .. note:: + + The 1-dimensional dot product version of this function does not support an :attr:`out` parameter. + + Arguments: + input (Tensor): the first tensor to be multiplied + other (Tensor): the second tensor to be multiplied + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> # vector x vector + >>> tensor1 = torch.randn(3) + >>> tensor2 = torch.randn(3) + >>> torch.matmul(tensor1, tensor2).size() + torch.Size([]) + >>> # matrix x vector + >>> tensor1 = torch.randn(3, 4) + >>> tensor2 = torch.randn(4) + >>> torch.matmul(tensor1, tensor2).size() + torch.Size([3]) + >>> # batched matrix x broadcasted vector + >>> tensor1 = torch.randn(10, 3, 4) + >>> tensor2 = torch.randn(4) + >>> torch.matmul(tensor1, tensor2).size() + torch.Size([10, 3]) + >>> # batched matrix x batched matrix + >>> tensor1 = torch.randn(10, 3, 4) + >>> tensor2 = torch.randn(10, 4, 5) + >>> torch.matmul(tensor1, tensor2).size() + torch.Size([10, 3, 5]) + >>> # batched matrix x broadcasted matrix + >>> tensor1 = torch.randn(10, 3, 4) + >>> tensor2 = torch.randn(4, 5) + >>> torch.matmul(tensor1, tensor2).size() + torch.Size([10, 3, 5]) + """ + +def matrix_exp(input: Tensor) -> Tensor: + r""" + matrix_exp(A) -> Tensor + + Alias for :func:`torch.linalg.matrix_exp`. + """ + +def matrix_power( + input: Tensor, + n: _int, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + matrix_power(input, n, *, out=None) -> Tensor + + Alias for :func:`torch.linalg.matrix_power` + """ + +@overload +def max(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + max(input, *, out=None) -> Tensor + + Returns the maximum value of all elements in the ``input`` tensor. + + .. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.6763, 0.7445, -2.2369]]) + >>> torch.max(a) + tensor(0.7445) + + .. function:: max(input, dim, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` is the maximum + value of each row of the :attr:`input` tensor in the given dimension + :attr:`dim`. And ``indices`` is the index location of each maximum value found + (argmax). + + If ``keepdim`` is ``True``, the output tensors are of the same size + as ``input`` except in the dimension ``dim`` where they are of size 1. + Otherwise, ``dim`` is squeezed (see :func:`torch.squeeze`), resulting + in the output tensors having 1 fewer dimension than ``input``. + + .. note:: If there are multiple maximal values in a reduced row then + the indices of the first maximal value are returned. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. If omitted, all dimensions are reduced. Explicit ``None`` is not supported. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (tuple, optional): the result tuple of two output tensors (max, max_indices) + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-1.2360, -0.2942, -0.1222, 0.8475], + [ 1.1949, -1.1127, -2.2379, -0.6702], + [ 1.5717, -0.9207, 0.1297, -1.8768], + [-0.6172, 1.0036, -0.6060, -0.2432]]) + >>> torch.max(a, 1) + torch.return_types.max(values=tensor([0.8475, 1.1949, 1.5717, 1.0036]), indices=tensor([3, 0, 0, 1])) + >>> a = torch.tensor([[1.0, 2.0], [3.0, 4.0]]) + >>> a.max(dim=1, keepdim=True) + torch.return_types.max( + values=tensor([[2.], [4.]]), + indices=tensor([[1], [1]])) + >>> a.max(dim=1, keepdim=False) + torch.return_types.max( + values=tensor([2., 4.]), + indices=tensor([1, 1])) + + .. function:: max(input, other, *, out=None) -> Tensor + :noindex: + + See :func:`torch.maximum`. + """ + +@overload +def max( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + max(input, *, out=None) -> Tensor + + Returns the maximum value of all elements in the ``input`` tensor. + + .. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.6763, 0.7445, -2.2369]]) + >>> torch.max(a) + tensor(0.7445) + + .. function:: max(input, dim, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` is the maximum + value of each row of the :attr:`input` tensor in the given dimension + :attr:`dim`. And ``indices`` is the index location of each maximum value found + (argmax). + + If ``keepdim`` is ``True``, the output tensors are of the same size + as ``input`` except in the dimension ``dim`` where they are of size 1. + Otherwise, ``dim`` is squeezed (see :func:`torch.squeeze`), resulting + in the output tensors having 1 fewer dimension than ``input``. + + .. note:: If there are multiple maximal values in a reduced row then + the indices of the first maximal value are returned. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. If omitted, all dimensions are reduced. Explicit ``None`` is not supported. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (tuple, optional): the result tuple of two output tensors (max, max_indices) + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-1.2360, -0.2942, -0.1222, 0.8475], + [ 1.1949, -1.1127, -2.2379, -0.6702], + [ 1.5717, -0.9207, 0.1297, -1.8768], + [-0.6172, 1.0036, -0.6060, -0.2432]]) + >>> torch.max(a, 1) + torch.return_types.max(values=tensor([0.8475, 1.1949, 1.5717, 1.0036]), indices=tensor([3, 0, 0, 1])) + >>> a = torch.tensor([[1.0, 2.0], [3.0, 4.0]]) + >>> a.max(dim=1, keepdim=True) + torch.return_types.max( + values=tensor([[2.], [4.]]), + indices=tensor([[1], [1]])) + >>> a.max(dim=1, keepdim=False) + torch.return_types.max( + values=tensor([2., 4.]), + indices=tensor([1, 1])) + + .. function:: max(input, other, *, out=None) -> Tensor + :noindex: + + See :func:`torch.maximum`. + """ + +@overload +def max( + input: Tensor, + dim: _int, + keepdim: _bool = False, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.max: + r""" + max(input, *, out=None) -> Tensor + + Returns the maximum value of all elements in the ``input`` tensor. + + .. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.6763, 0.7445, -2.2369]]) + >>> torch.max(a) + tensor(0.7445) + + .. function:: max(input, dim, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` is the maximum + value of each row of the :attr:`input` tensor in the given dimension + :attr:`dim`. And ``indices`` is the index location of each maximum value found + (argmax). + + If ``keepdim`` is ``True``, the output tensors are of the same size + as ``input`` except in the dimension ``dim`` where they are of size 1. + Otherwise, ``dim`` is squeezed (see :func:`torch.squeeze`), resulting + in the output tensors having 1 fewer dimension than ``input``. + + .. note:: If there are multiple maximal values in a reduced row then + the indices of the first maximal value are returned. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. If omitted, all dimensions are reduced. Explicit ``None`` is not supported. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (tuple, optional): the result tuple of two output tensors (max, max_indices) + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-1.2360, -0.2942, -0.1222, 0.8475], + [ 1.1949, -1.1127, -2.2379, -0.6702], + [ 1.5717, -0.9207, 0.1297, -1.8768], + [-0.6172, 1.0036, -0.6060, -0.2432]]) + >>> torch.max(a, 1) + torch.return_types.max(values=tensor([0.8475, 1.1949, 1.5717, 1.0036]), indices=tensor([3, 0, 0, 1])) + >>> a = torch.tensor([[1.0, 2.0], [3.0, 4.0]]) + >>> a.max(dim=1, keepdim=True) + torch.return_types.max( + values=tensor([[2.], [4.]]), + indices=tensor([[1], [1]])) + >>> a.max(dim=1, keepdim=False) + torch.return_types.max( + values=tensor([2., 4.]), + indices=tensor([1, 1])) + + .. function:: max(input, other, *, out=None) -> Tensor + :noindex: + + See :func:`torch.maximum`. + """ + +@overload +def max( + input: Tensor, + dim: str | EllipsisType | None, + keepdim: _bool = False, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.max: + r""" + max(input, *, out=None) -> Tensor + + Returns the maximum value of all elements in the ``input`` tensor. + + .. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.6763, 0.7445, -2.2369]]) + >>> torch.max(a) + tensor(0.7445) + + .. function:: max(input, dim, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` is the maximum + value of each row of the :attr:`input` tensor in the given dimension + :attr:`dim`. And ``indices`` is the index location of each maximum value found + (argmax). + + If ``keepdim`` is ``True``, the output tensors are of the same size + as ``input`` except in the dimension ``dim`` where they are of size 1. + Otherwise, ``dim`` is squeezed (see :func:`torch.squeeze`), resulting + in the output tensors having 1 fewer dimension than ``input``. + + .. note:: If there are multiple maximal values in a reduced row then + the indices of the first maximal value are returned. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. If omitted, all dimensions are reduced. Explicit ``None`` is not supported. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (tuple, optional): the result tuple of two output tensors (max, max_indices) + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-1.2360, -0.2942, -0.1222, 0.8475], + [ 1.1949, -1.1127, -2.2379, -0.6702], + [ 1.5717, -0.9207, 0.1297, -1.8768], + [-0.6172, 1.0036, -0.6060, -0.2432]]) + >>> torch.max(a, 1) + torch.return_types.max(values=tensor([0.8475, 1.1949, 1.5717, 1.0036]), indices=tensor([3, 0, 0, 1])) + >>> a = torch.tensor([[1.0, 2.0], [3.0, 4.0]]) + >>> a.max(dim=1, keepdim=True) + torch.return_types.max( + values=tensor([[2.], [4.]]), + indices=tensor([[1], [1]])) + >>> a.max(dim=1, keepdim=False) + torch.return_types.max( + values=tensor([2., 4.]), + indices=tensor([1, 1])) + + .. function:: max(input, other, *, out=None) -> Tensor + :noindex: + + See :func:`torch.maximum`. + """ + +def max_pool1d( + input: Tensor, + kernel_size: _int | _size, + stride: _int | _size = (), + padding: _int | _size = 0, + dilation: _int | _size = 1, + ceil_mode: _bool = False, +) -> Tensor: ... +def max_pool1d_with_indices( + input: Tensor, + kernel_size: _int | _size, + stride: _int | _size = (), + padding: _int | _size = 0, + dilation: _int | _size = 1, + ceil_mode: _bool = False, +) -> tuple[Tensor, Tensor]: ... +def max_pool2d( + input: Tensor, + kernel_size: _int | _size, + stride: _int | _size = (), + padding: _int | _size = 0, + dilation: _int | _size = 1, + ceil_mode: _bool = False, +) -> Tensor: ... +def max_pool3d( + input: Tensor, + kernel_size: _int | _size, + stride: _int | _size = (), + padding: _int | _size = 0, + dilation: _int | _size = 1, + ceil_mode: _bool = False, +) -> Tensor: ... +def maximum( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + maximum(input, other, *, out=None) -> Tensor + + Computes the element-wise maximum of :attr:`input` and :attr:`other`. + + .. note:: + If one of the elements being compared is a NaN, then that element is returned. + :func:`maximum` is not supported for tensors with complex dtypes. + + Args: + input (Tensor): the input tensor. + other (Tensor): the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor((1, 2, -1)) + >>> b = torch.tensor((3, 0, 4)) + >>> torch.maximum(a, b) + tensor([3, 2, 4]) + """ + +@overload +def mean( + input: Tensor, + *, + dtype: _dtype | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + mean(input, *, dtype=None) -> Tensor + + .. note:: + If the `input` tensor is empty, ``torch.mean()`` returns ``nan``. + This behavior is consistent with NumPy and follows the definition + that the mean over an empty set is undefined. + + + Returns the mean value of all elements in the :attr:`input` tensor. Input must be floating point or complex. + + Args: + input (Tensor): + the input tensor, either of floating point or complex dtype + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.2294, -0.5481, 1.3288]]) + >>> torch.mean(a) + tensor(0.3367) + + .. function:: mean(input, dim, keepdim=False, *, dtype=None, out=None) -> Tensor + :noindex: + + Returns the mean value of each row of the :attr:`input` tensor in the given + dimension :attr:`dim`. If :attr:`dim` is a list of dimensions, + reduce over all of them. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + out (Tensor, optional): the output tensor. + + .. seealso:: + + :func:`torch.nanmean` computes the mean value of `non-NaN` elements. + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-0.3841, 0.6320, 0.4254, -0.7384], + [-0.9644, 1.0131, -0.6549, -1.4279], + [-0.2951, -1.3350, -0.7694, 0.5600], + [ 1.0842, -0.9580, 0.3623, 0.2343]]) + >>> torch.mean(a, 1) + tensor([-0.0163, -0.5085, -0.4599, 0.1807]) + >>> torch.mean(a, 1, True) + tensor([[-0.0163], + [-0.5085], + [-0.4599], + [ 0.1807]]) + """ + +@overload +def mean( + input: Tensor, + dim: _int | _size | None, + keepdim: _bool = False, + *, + dtype: _dtype | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + mean(input, *, dtype=None) -> Tensor + + .. note:: + If the `input` tensor is empty, ``torch.mean()`` returns ``nan``. + This behavior is consistent with NumPy and follows the definition + that the mean over an empty set is undefined. + + + Returns the mean value of all elements in the :attr:`input` tensor. Input must be floating point or complex. + + Args: + input (Tensor): + the input tensor, either of floating point or complex dtype + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.2294, -0.5481, 1.3288]]) + >>> torch.mean(a) + tensor(0.3367) + + .. function:: mean(input, dim, keepdim=False, *, dtype=None, out=None) -> Tensor + :noindex: + + Returns the mean value of each row of the :attr:`input` tensor in the given + dimension :attr:`dim`. If :attr:`dim` is a list of dimensions, + reduce over all of them. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + out (Tensor, optional): the output tensor. + + .. seealso:: + + :func:`torch.nanmean` computes the mean value of `non-NaN` elements. + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-0.3841, 0.6320, 0.4254, -0.7384], + [-0.9644, 1.0131, -0.6549, -1.4279], + [-0.2951, -1.3350, -0.7694, 0.5600], + [ 1.0842, -0.9580, 0.3623, 0.2343]]) + >>> torch.mean(a, 1) + tensor([-0.0163, -0.5085, -0.4599, 0.1807]) + >>> torch.mean(a, 1, True) + tensor([[-0.0163], + [-0.5085], + [-0.4599], + [ 0.1807]]) + """ + +@overload +def mean( + input: Tensor, + dim: Sequence[str | EllipsisType | None], + keepdim: _bool = False, + *, + dtype: _dtype | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + mean(input, *, dtype=None) -> Tensor + + .. note:: + If the `input` tensor is empty, ``torch.mean()`` returns ``nan``. + This behavior is consistent with NumPy and follows the definition + that the mean over an empty set is undefined. + + + Returns the mean value of all elements in the :attr:`input` tensor. Input must be floating point or complex. + + Args: + input (Tensor): + the input tensor, either of floating point or complex dtype + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.2294, -0.5481, 1.3288]]) + >>> torch.mean(a) + tensor(0.3367) + + .. function:: mean(input, dim, keepdim=False, *, dtype=None, out=None) -> Tensor + :noindex: + + Returns the mean value of each row of the :attr:`input` tensor in the given + dimension :attr:`dim`. If :attr:`dim` is a list of dimensions, + reduce over all of them. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + out (Tensor, optional): the output tensor. + + .. seealso:: + + :func:`torch.nanmean` computes the mean value of `non-NaN` elements. + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-0.3841, 0.6320, 0.4254, -0.7384], + [-0.9644, 1.0131, -0.6549, -1.4279], + [-0.2951, -1.3350, -0.7694, 0.5600], + [ 1.0842, -0.9580, 0.3623, 0.2343]]) + >>> torch.mean(a, 1) + tensor([-0.0163, -0.5085, -0.4599, 0.1807]) + >>> torch.mean(a, 1, True) + tensor([[-0.0163], + [-0.5085], + [-0.4599], + [ 0.1807]]) + """ + +@overload +def median(input: Tensor) -> Tensor: + r""" + median(input) -> Tensor + + Returns the median of the values in :attr:`input`. + + .. note:: + The median is not unique for :attr:`input` tensors with an even number + of elements. In this case the lower of the two medians is returned. To + compute the mean of both medians, use :func:`torch.quantile` with ``q=0.5`` instead. + + .. warning:: + This function produces deterministic (sub)gradients unlike ``median(dim=0)`` + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 1.5219, -1.5212, 0.2202]]) + >>> torch.median(a) + tensor(0.2202) + + .. function:: median(input, dim=-1, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` contains the median of each row of :attr:`input` + in the dimension :attr:`dim`, and ``indices`` contains the index of the median values found in the dimension :attr:`dim`. + + By default, :attr:`dim` is the last dimension of the :attr:`input` tensor. + + If :attr:`keepdim` is ``True``, the output tensors are of the same size + as :attr:`input` except in the dimension :attr:`dim` where they are of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in + the outputs tensor having 1 fewer dimension than :attr:`input`. + + .. note:: + The median is not unique for :attr:`input` tensors with an even number + of elements in the dimension :attr:`dim`. In this case the lower of the + two medians is returned. To compute the mean of both medians in + :attr:`input`, use :func:`torch.quantile` with ``q=0.5`` instead. + + .. warning:: + ``indices`` does not necessarily contain the first occurrence of each + median value found, unless it is unique. + The exact implementation details are device-specific. + Do not expect the same result when run on CPU and GPU in general. + For the same reason do not expect the gradients to be deterministic. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out ((Tensor, Tensor), optional): The first tensor will be populated with the median values and the second + tensor, which must have dtype long, with their indices in the dimension + :attr:`dim` of :attr:`input`. + + Example:: + + >>> a = torch.randn(4, 5) + >>> a + tensor([[ 0.2505, -0.3982, -0.9948, 0.3518, -1.3131], + [ 0.3180, -0.6993, 1.0436, 0.0438, 0.2270], + [-0.2751, 0.7303, 0.2192, 0.3321, 0.2488], + [ 1.0778, -1.9510, 0.7048, 0.4742, -0.7125]]) + >>> torch.median(a, 1) + torch.return_types.median(values=tensor([-0.3982, 0.2270, 0.2488, 0.4742]), indices=tensor([1, 4, 4, 3])) + """ + +@overload +def median( + input: Tensor, + dim: _int, + keepdim: _bool = False, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.median: + r""" + median(input) -> Tensor + + Returns the median of the values in :attr:`input`. + + .. note:: + The median is not unique for :attr:`input` tensors with an even number + of elements. In this case the lower of the two medians is returned. To + compute the mean of both medians, use :func:`torch.quantile` with ``q=0.5`` instead. + + .. warning:: + This function produces deterministic (sub)gradients unlike ``median(dim=0)`` + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 1.5219, -1.5212, 0.2202]]) + >>> torch.median(a) + tensor(0.2202) + + .. function:: median(input, dim=-1, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` contains the median of each row of :attr:`input` + in the dimension :attr:`dim`, and ``indices`` contains the index of the median values found in the dimension :attr:`dim`. + + By default, :attr:`dim` is the last dimension of the :attr:`input` tensor. + + If :attr:`keepdim` is ``True``, the output tensors are of the same size + as :attr:`input` except in the dimension :attr:`dim` where they are of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in + the outputs tensor having 1 fewer dimension than :attr:`input`. + + .. note:: + The median is not unique for :attr:`input` tensors with an even number + of elements in the dimension :attr:`dim`. In this case the lower of the + two medians is returned. To compute the mean of both medians in + :attr:`input`, use :func:`torch.quantile` with ``q=0.5`` instead. + + .. warning:: + ``indices`` does not necessarily contain the first occurrence of each + median value found, unless it is unique. + The exact implementation details are device-specific. + Do not expect the same result when run on CPU and GPU in general. + For the same reason do not expect the gradients to be deterministic. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out ((Tensor, Tensor), optional): The first tensor will be populated with the median values and the second + tensor, which must have dtype long, with their indices in the dimension + :attr:`dim` of :attr:`input`. + + Example:: + + >>> a = torch.randn(4, 5) + >>> a + tensor([[ 0.2505, -0.3982, -0.9948, 0.3518, -1.3131], + [ 0.3180, -0.6993, 1.0436, 0.0438, 0.2270], + [-0.2751, 0.7303, 0.2192, 0.3321, 0.2488], + [ 1.0778, -1.9510, 0.7048, 0.4742, -0.7125]]) + >>> torch.median(a, 1) + torch.return_types.median(values=tensor([-0.3982, 0.2270, 0.2488, 0.4742]), indices=tensor([1, 4, 4, 3])) + """ + +@overload +def median( + input: Tensor, + dim: str | EllipsisType | None, + keepdim: _bool = False, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.median: + r""" + median(input) -> Tensor + + Returns the median of the values in :attr:`input`. + + .. note:: + The median is not unique for :attr:`input` tensors with an even number + of elements. In this case the lower of the two medians is returned. To + compute the mean of both medians, use :func:`torch.quantile` with ``q=0.5`` instead. + + .. warning:: + This function produces deterministic (sub)gradients unlike ``median(dim=0)`` + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 1.5219, -1.5212, 0.2202]]) + >>> torch.median(a) + tensor(0.2202) + + .. function:: median(input, dim=-1, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` contains the median of each row of :attr:`input` + in the dimension :attr:`dim`, and ``indices`` contains the index of the median values found in the dimension :attr:`dim`. + + By default, :attr:`dim` is the last dimension of the :attr:`input` tensor. + + If :attr:`keepdim` is ``True``, the output tensors are of the same size + as :attr:`input` except in the dimension :attr:`dim` where they are of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in + the outputs tensor having 1 fewer dimension than :attr:`input`. + + .. note:: + The median is not unique for :attr:`input` tensors with an even number + of elements in the dimension :attr:`dim`. In this case the lower of the + two medians is returned. To compute the mean of both medians in + :attr:`input`, use :func:`torch.quantile` with ``q=0.5`` instead. + + .. warning:: + ``indices`` does not necessarily contain the first occurrence of each + median value found, unless it is unique. + The exact implementation details are device-specific. + Do not expect the same result when run on CPU and GPU in general. + For the same reason do not expect the gradients to be deterministic. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out ((Tensor, Tensor), optional): The first tensor will be populated with the median values and the second + tensor, which must have dtype long, with their indices in the dimension + :attr:`dim` of :attr:`input`. + + Example:: + + >>> a = torch.randn(4, 5) + >>> a + tensor([[ 0.2505, -0.3982, -0.9948, 0.3518, -1.3131], + [ 0.3180, -0.6993, 1.0436, 0.0438, 0.2270], + [-0.2751, 0.7303, 0.2192, 0.3321, 0.2488], + [ 1.0778, -1.9510, 0.7048, 0.4742, -0.7125]]) + >>> torch.median(a, 1) + torch.return_types.median(values=tensor([-0.3982, 0.2270, 0.2488, 0.4742]), indices=tensor([1, 4, 4, 3])) + """ + +@overload +def min(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + min(input, *, out=None) -> Tensor + + Returns the minimum value of all elements in the :attr:`input` tensor. + + .. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.6750, 1.0857, 1.7197]]) + >>> torch.min(a) + tensor(0.6750) + + .. function:: min(input, dim, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` is the minimum + value of each row of the :attr:`input` tensor in the given dimension + :attr:`dim`. And ``indices`` is the index location of each minimum value found + (argmin). + + If :attr:`keepdim` is ``True``, the output tensors are of the same size as + :attr:`input` except in the dimension :attr:`dim` where they are of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in + the output tensors having 1 fewer dimension than :attr:`input`. + + .. note:: If there are multiple minimal values in a reduced row then + the indices of the first minimal value are returned. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. If omitted, all dimensions are reduced. Explicit ``None`` is not supported. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (tuple, optional): the tuple of two output tensors (min, min_indices) + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-0.6248, 1.1334, -1.1899, -0.2803], + [-1.4644, -0.2635, -0.3651, 0.6134], + [ 0.2457, 0.0384, 1.0128, 0.7015], + [-0.1153, 2.9849, 2.1458, 0.5788]]) + >>> torch.min(a, 1) + torch.return_types.min(values=tensor([-1.1899, -1.4644, 0.0384, -0.1153]), indices=tensor([2, 0, 1, 0])) + + .. function:: min(input, other, *, out=None) -> Tensor + :noindex: + + See :func:`torch.minimum`. + """ + +@overload +def min( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + min(input, *, out=None) -> Tensor + + Returns the minimum value of all elements in the :attr:`input` tensor. + + .. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.6750, 1.0857, 1.7197]]) + >>> torch.min(a) + tensor(0.6750) + + .. function:: min(input, dim, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` is the minimum + value of each row of the :attr:`input` tensor in the given dimension + :attr:`dim`. And ``indices`` is the index location of each minimum value found + (argmin). + + If :attr:`keepdim` is ``True``, the output tensors are of the same size as + :attr:`input` except in the dimension :attr:`dim` where they are of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in + the output tensors having 1 fewer dimension than :attr:`input`. + + .. note:: If there are multiple minimal values in a reduced row then + the indices of the first minimal value are returned. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. If omitted, all dimensions are reduced. Explicit ``None`` is not supported. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (tuple, optional): the tuple of two output tensors (min, min_indices) + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-0.6248, 1.1334, -1.1899, -0.2803], + [-1.4644, -0.2635, -0.3651, 0.6134], + [ 0.2457, 0.0384, 1.0128, 0.7015], + [-0.1153, 2.9849, 2.1458, 0.5788]]) + >>> torch.min(a, 1) + torch.return_types.min(values=tensor([-1.1899, -1.4644, 0.0384, -0.1153]), indices=tensor([2, 0, 1, 0])) + + .. function:: min(input, other, *, out=None) -> Tensor + :noindex: + + See :func:`torch.minimum`. + """ + +@overload +def min( + input: Tensor, + dim: _int, + keepdim: _bool = False, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.min: + r""" + min(input, *, out=None) -> Tensor + + Returns the minimum value of all elements in the :attr:`input` tensor. + + .. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.6750, 1.0857, 1.7197]]) + >>> torch.min(a) + tensor(0.6750) + + .. function:: min(input, dim, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` is the minimum + value of each row of the :attr:`input` tensor in the given dimension + :attr:`dim`. And ``indices`` is the index location of each minimum value found + (argmin). + + If :attr:`keepdim` is ``True``, the output tensors are of the same size as + :attr:`input` except in the dimension :attr:`dim` where they are of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in + the output tensors having 1 fewer dimension than :attr:`input`. + + .. note:: If there are multiple minimal values in a reduced row then + the indices of the first minimal value are returned. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. If omitted, all dimensions are reduced. Explicit ``None`` is not supported. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (tuple, optional): the tuple of two output tensors (min, min_indices) + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-0.6248, 1.1334, -1.1899, -0.2803], + [-1.4644, -0.2635, -0.3651, 0.6134], + [ 0.2457, 0.0384, 1.0128, 0.7015], + [-0.1153, 2.9849, 2.1458, 0.5788]]) + >>> torch.min(a, 1) + torch.return_types.min(values=tensor([-1.1899, -1.4644, 0.0384, -0.1153]), indices=tensor([2, 0, 1, 0])) + + .. function:: min(input, other, *, out=None) -> Tensor + :noindex: + + See :func:`torch.minimum`. + """ + +@overload +def min( + input: Tensor, + dim: str | EllipsisType | None, + keepdim: _bool = False, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.min: + r""" + min(input, *, out=None) -> Tensor + + Returns the minimum value of all elements in the :attr:`input` tensor. + + .. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.6750, 1.0857, 1.7197]]) + >>> torch.min(a) + tensor(0.6750) + + .. function:: min(input, dim, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` is the minimum + value of each row of the :attr:`input` tensor in the given dimension + :attr:`dim`. And ``indices`` is the index location of each minimum value found + (argmin). + + If :attr:`keepdim` is ``True``, the output tensors are of the same size as + :attr:`input` except in the dimension :attr:`dim` where they are of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in + the output tensors having 1 fewer dimension than :attr:`input`. + + .. note:: If there are multiple minimal values in a reduced row then + the indices of the first minimal value are returned. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. If omitted, all dimensions are reduced. Explicit ``None`` is not supported. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (tuple, optional): the tuple of two output tensors (min, min_indices) + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-0.6248, 1.1334, -1.1899, -0.2803], + [-1.4644, -0.2635, -0.3651, 0.6134], + [ 0.2457, 0.0384, 1.0128, 0.7015], + [-0.1153, 2.9849, 2.1458, 0.5788]]) + >>> torch.min(a, 1) + torch.return_types.min(values=tensor([-1.1899, -1.4644, 0.0384, -0.1153]), indices=tensor([2, 0, 1, 0])) + + .. function:: min(input, other, *, out=None) -> Tensor + :noindex: + + See :func:`torch.minimum`. + """ + +def minimum( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + minimum(input, other, *, out=None) -> Tensor + + Computes the element-wise minimum of :attr:`input` and :attr:`other`. + + .. note:: + If one of the elements being compared is a NaN, then that element is returned. + :func:`minimum` is not supported for tensors with complex dtypes. + + Args: + input (Tensor): the input tensor. + other (Tensor): the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor((1, 2, -1)) + >>> b = torch.tensor((3, 0, 4)) + >>> torch.minimum(a, b) + tensor([1, 0, -1]) + """ + +def miopen_batch_norm( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + running_mean: Tensor | None, + running_var: Tensor | None, + training: _bool, + exponential_average_factor: _float, + epsilon: _float, +) -> tuple[Tensor, Tensor, Tensor]: ... +def miopen_convolution( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + padding: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + groups: _int | SymInt, + benchmark: _bool, + deterministic: _bool, +) -> Tensor: ... +def miopen_convolution_add_relu( + input: Tensor, + weight: Tensor, + z: Tensor, + alpha: Number | _complex | None, + bias: Tensor | None, + stride: Sequence[_int | SymInt], + padding: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + groups: _int | SymInt, +) -> Tensor: ... +def miopen_convolution_relu( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + stride: Sequence[_int | SymInt], + padding: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + groups: _int | SymInt, +) -> Tensor: ... +def miopen_convolution_transpose( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + padding: Sequence[_int | SymInt], + output_padding: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + groups: _int | SymInt, + benchmark: _bool, + deterministic: _bool, +) -> Tensor: ... +def miopen_depthwise_convolution( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + padding: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + groups: _int | SymInt, + benchmark: _bool, + deterministic: _bool, +) -> Tensor: ... +def miopen_rnn( + input: Tensor, + weight: tuple[Tensor, ...] | list[Tensor] | None, + weight_stride0: _int, + hx: Tensor, + cx: Tensor | None, + mode: _int, + hidden_size: _int, + num_layers: _int, + batch_first: _bool, + dropout: _float, + train: _bool, + bidirectional: _bool, + batch_sizes: _size, + dropout_state: Tensor | None, +) -> tuple[Tensor, Tensor, Tensor, Tensor, Tensor]: ... +def mkldnn_adaptive_avg_pool2d( + input: Tensor, + output_size: _int | _size, + *, + out: Tensor | None = None, +) -> Tensor: ... +def mkldnn_convolution( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + padding: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + groups: _int | SymInt, +) -> Tensor: ... +def mkldnn_linear_backward_weights( + grad_output: Tensor, + input: Tensor, + weight: Tensor, + bias_defined: _bool, +) -> tuple[Tensor, Tensor]: ... +def mkldnn_max_pool2d( + input: Tensor, + kernel_size: _int | _size, + stride: _int | _size = (), + padding: _int | _size = 0, + dilation: _int | _size = 1, + ceil_mode: _bool = False, +) -> Tensor: ... +def mkldnn_max_pool3d( + input: Tensor, + kernel_size: _int | _size, + stride: _int | _size = (), + padding: _int | _size = 0, + dilation: _int | _size = 1, + ceil_mode: _bool = False, +) -> Tensor: ... +def mkldnn_rnn_layer( + input: Tensor, + weight0: Tensor, + weight1: Tensor, + weight2: Tensor, + weight3: Tensor, + hx_: Tensor, + cx_: Tensor, + reverse: _bool, + batch_sizes: _size, + mode: _int, + hidden_size: _int, + num_layers: _int, + has_biases: _bool, + bidirectional: _bool, + batch_first: _bool, + train: _bool, +) -> tuple[Tensor, Tensor, Tensor, Tensor]: ... +@overload +def mm(input: Tensor, mat2: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + mm(input, mat2, out_dtype=None, *, out=None) -> Tensor + + Performs a matrix multiplication of the matrices :attr:`input` and :attr:`mat2`. + + If :attr:`input` is a :math:`(n \times m)` tensor, :attr:`mat2` is a + :math:`(m \times p)` tensor, :attr:`out` will be a :math:`(n \times p)` tensor. + + .. note:: This function does not :ref:`broadcast `. + For broadcasting matrix products, see :func:`torch.matmul`. + + Supports strided and sparse 2-D tensors as inputs, autograd with + respect to strided inputs. + + This operation has support for arguments with :ref:`sparse layouts`. + If :attr:`out` is provided its layout will be used. Otherwise, the result + layout will be deduced from that of :attr:`input`. + + + .. warning:: + Sparse support is a beta feature and some layout(s)/dtype/device combinations may not be supported, + or may not have autograd support. If you notice missing functionality please + open a feature request. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + out_dtype (dtype, optional): the dtype of the output tensor, + Supported only on CUDA and for torch.float32 given + torch.float16/torch.bfloat16 input dtypes + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> mat1 = torch.randn(2, 3) + >>> mat2 = torch.randn(3, 3) + >>> torch.mm(mat1, mat2) + tensor([[ 0.4851, 0.5037, -0.3633], + [-0.0760, -3.6705, 2.4784]]) + """ + +@overload +def mm( + input: Tensor, + mat2: Tensor, + out_dtype: _dtype, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + mm(input, mat2, out_dtype=None, *, out=None) -> Tensor + + Performs a matrix multiplication of the matrices :attr:`input` and :attr:`mat2`. + + If :attr:`input` is a :math:`(n \times m)` tensor, :attr:`mat2` is a + :math:`(m \times p)` tensor, :attr:`out` will be a :math:`(n \times p)` tensor. + + .. note:: This function does not :ref:`broadcast `. + For broadcasting matrix products, see :func:`torch.matmul`. + + Supports strided and sparse 2-D tensors as inputs, autograd with + respect to strided inputs. + + This operation has support for arguments with :ref:`sparse layouts`. + If :attr:`out` is provided its layout will be used. Otherwise, the result + layout will be deduced from that of :attr:`input`. + + + .. warning:: + Sparse support is a beta feature and some layout(s)/dtype/device combinations may not be supported, + or may not have autograd support. If you notice missing functionality please + open a feature request. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + out_dtype (dtype, optional): the dtype of the output tensor, + Supported only on CUDA and for torch.float32 given + torch.float16/torch.bfloat16 input dtypes + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> mat1 = torch.randn(2, 3) + >>> mat2 = torch.randn(3, 3) + >>> torch.mm(mat1, mat2) + tensor([[ 0.4851, 0.5037, -0.3633], + [-0.0760, -3.6705, 2.4784]]) + """ + +@overload +def mode( + input: Tensor, + dim: _int = -1, + keepdim: _bool = False, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.mode: + r""" + mode(input, dim=-1, keepdim=False, *, out=None) -> (Tensor, LongTensor) + + Returns a namedtuple ``(values, indices)`` where ``values`` is the mode + value of each row of the :attr:`input` tensor in the given dimension + :attr:`dim`, i.e. a value which appears most often + in that row, and ``indices`` is the index location of each mode value found. + + By default, :attr:`dim` is the last dimension of the :attr:`input` tensor. + + If :attr:`keepdim` is ``True``, the output tensors are of the same size as + :attr:`input` except in the dimension :attr:`dim` where they are of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting + in the output tensors having 1 fewer dimension than :attr:`input`. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (tuple, optional): the result tuple of two output tensors (values, indices) + + Example:: + + >>> b = torch.tensor([[0, 0, 0, 2, 0, 0, 2], + ... [0, 3, 0, 0, 2, 0, 1], + ... [2, 2, 2, 0, 0, 0, 3], + ... [2, 2, 3, 0, 1, 1, 0], + ... [1, 1, 0, 0, 2, 0, 2]]) + >>> torch.mode(b, 0) + torch.return_types.mode( + values=tensor([0, 2, 0, 0, 0, 0, 2]), + indices=tensor([1, 3, 4, 4, 2, 4, 4])) + """ + +@overload +def mode( + input: Tensor, + dim: str | EllipsisType | None, + keepdim: _bool = False, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.mode: + r""" + mode(input, dim=-1, keepdim=False, *, out=None) -> (Tensor, LongTensor) + + Returns a namedtuple ``(values, indices)`` where ``values`` is the mode + value of each row of the :attr:`input` tensor in the given dimension + :attr:`dim`, i.e. a value which appears most often + in that row, and ``indices`` is the index location of each mode value found. + + By default, :attr:`dim` is the last dimension of the :attr:`input` tensor. + + If :attr:`keepdim` is ``True``, the output tensors are of the same size as + :attr:`input` except in the dimension :attr:`dim` where they are of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting + in the output tensors having 1 fewer dimension than :attr:`input`. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (tuple, optional): the result tuple of two output tensors (values, indices) + + Example:: + + >>> b = torch.tensor([[0, 0, 0, 2, 0, 0, 2], + ... [0, 3, 0, 0, 2, 0, 1], + ... [2, 2, 2, 0, 0, 0, 3], + ... [2, 2, 3, 0, 1, 1, 0], + ... [1, 1, 0, 0, 2, 0, 2]]) + >>> torch.mode(b, 0) + torch.return_types.mode( + values=tensor([0, 2, 0, 0, 0, 0, 2]), + indices=tensor([1, 3, 4, 4, 2, 4, 4])) + """ + +@overload +def moveaxis(input: Tensor, source: _int, destination: _int) -> Tensor: + r""" + moveaxis(input, source, destination) -> Tensor + + Alias for :func:`torch.movedim`. + + This function is equivalent to NumPy's moveaxis function. + + Examples:: + + >>> t = torch.randn(3,2,1) + >>> t + tensor([[[-0.3362], + [-0.8437]], + + [[-0.9627], + [ 0.1727]], + + [[ 0.5173], + [-0.1398]]]) + >>> torch.moveaxis(t, 1, 0).shape + torch.Size([2, 3, 1]) + >>> torch.moveaxis(t, 1, 0) + tensor([[[-0.3362], + [-0.9627], + [ 0.5173]], + + [[-0.8437], + [ 0.1727], + [-0.1398]]]) + >>> torch.moveaxis(t, (1, 2), (0, 1)).shape + torch.Size([2, 1, 3]) + >>> torch.moveaxis(t, (1, 2), (0, 1)) + tensor([[[-0.3362, -0.9627, 0.5173]], + + [[-0.8437, 0.1727, -0.1398]]]) + """ + +@overload +def moveaxis(input: Tensor, source: _size, destination: _size) -> Tensor: + r""" + moveaxis(input, source, destination) -> Tensor + + Alias for :func:`torch.movedim`. + + This function is equivalent to NumPy's moveaxis function. + + Examples:: + + >>> t = torch.randn(3,2,1) + >>> t + tensor([[[-0.3362], + [-0.8437]], + + [[-0.9627], + [ 0.1727]], + + [[ 0.5173], + [-0.1398]]]) + >>> torch.moveaxis(t, 1, 0).shape + torch.Size([2, 3, 1]) + >>> torch.moveaxis(t, 1, 0) + tensor([[[-0.3362], + [-0.9627], + [ 0.5173]], + + [[-0.8437], + [ 0.1727], + [-0.1398]]]) + >>> torch.moveaxis(t, (1, 2), (0, 1)).shape + torch.Size([2, 1, 3]) + >>> torch.moveaxis(t, (1, 2), (0, 1)) + tensor([[[-0.3362, -0.9627, 0.5173]], + + [[-0.8437, 0.1727, -0.1398]]]) + """ + +@overload +def movedim(input: Tensor, source: _int, destination: _int) -> Tensor: + r""" + movedim(input, source, destination) -> Tensor + + Moves the dimension(s) of :attr:`input` at the position(s) in :attr:`source` + to the position(s) in :attr:`destination`. + + Other dimensions of :attr:`input` that are not explicitly moved remain in + their original order and appear at the positions not specified in :attr:`destination`. + + Args: + input (Tensor): the input tensor. + source (int or tuple of ints): Original positions of the dims to move. These must be unique. + destination (int or tuple of ints): Destination positions for each of the original dims. These must also be unique. + + Examples:: + + >>> t = torch.randn(3,2,1) + >>> t + tensor([[[-0.3362], + [-0.8437]], + + [[-0.9627], + [ 0.1727]], + + [[ 0.5173], + [-0.1398]]]) + >>> torch.movedim(t, 1, 0).shape + torch.Size([2, 3, 1]) + >>> torch.movedim(t, 1, 0) + tensor([[[-0.3362], + [-0.9627], + [ 0.5173]], + + [[-0.8437], + [ 0.1727], + [-0.1398]]]) + >>> torch.movedim(t, (1, 2), (0, 1)).shape + torch.Size([2, 1, 3]) + >>> torch.movedim(t, (1, 2), (0, 1)) + tensor([[[-0.3362, -0.9627, 0.5173]], + + [[-0.8437, 0.1727, -0.1398]]]) + """ + +@overload +def movedim(input: Tensor, source: _size, destination: _size) -> Tensor: + r""" + movedim(input, source, destination) -> Tensor + + Moves the dimension(s) of :attr:`input` at the position(s) in :attr:`source` + to the position(s) in :attr:`destination`. + + Other dimensions of :attr:`input` that are not explicitly moved remain in + their original order and appear at the positions not specified in :attr:`destination`. + + Args: + input (Tensor): the input tensor. + source (int or tuple of ints): Original positions of the dims to move. These must be unique. + destination (int or tuple of ints): Destination positions for each of the original dims. These must also be unique. + + Examples:: + + >>> t = torch.randn(3,2,1) + >>> t + tensor([[[-0.3362], + [-0.8437]], + + [[-0.9627], + [ 0.1727]], + + [[ 0.5173], + [-0.1398]]]) + >>> torch.movedim(t, 1, 0).shape + torch.Size([2, 3, 1]) + >>> torch.movedim(t, 1, 0) + tensor([[[-0.3362], + [-0.9627], + [ 0.5173]], + + [[-0.8437], + [ 0.1727], + [-0.1398]]]) + >>> torch.movedim(t, (1, 2), (0, 1)).shape + torch.Size([2, 1, 3]) + >>> torch.movedim(t, (1, 2), (0, 1)) + tensor([[[-0.3362, -0.9627, 0.5173]], + + [[-0.8437, 0.1727, -0.1398]]]) + """ + +def msort(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + msort(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Sorts the elements of the :attr:`input` tensor along its first dimension + in ascending order by value. + + .. note:: `torch.msort(t)` is equivalent to `torch.sort(t, dim=0)[0]`. + See also :func:`torch.sort`. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> t = torch.randn(3, 4) + >>> t + tensor([[-0.1321, 0.4370, -1.2631, -1.1289], + [-2.0527, -1.1250, 0.2275, 0.3077], + [-0.0881, -0.1259, -0.5495, 1.0284]]) + >>> torch.msort(t) + tensor([[-2.0527, -1.1250, -1.2631, -1.1289], + [-0.1321, -0.1259, -0.5495, 0.3077], + [-0.0881, 0.4370, 0.2275, 1.0284]]) + """ + +def mul( + input: Tensor | Number | _complex, + other: Tensor | Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + mul(input, other, *, out=None) -> Tensor + + Multiplies :attr:`input` by :attr:`other`. + + + .. math:: + \text{out}_i = \text{input}_i \times \text{other}_i + + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer, float, and complex inputs. + + Args: + input (Tensor): the input tensor. + other (Tensor or Number): the tensor or number to multiply input by. + + Keyword args: + out (Tensor, optional): the output tensor. + + Examples:: + + >>> a = torch.randn(3) + >>> a + tensor([ 0.2015, -0.4255, 2.6087]) + >>> torch.mul(a, 100) + tensor([ 20.1494, -42.5491, 260.8663]) + + >>> b = torch.randn(4, 1) + >>> b + tensor([[ 1.1207], + [-0.3137], + [ 0.0700], + [ 0.8378]]) + >>> c = torch.randn(1, 4) + >>> c + tensor([[ 0.5146, 0.1216, -0.5244, 2.2382]]) + >>> torch.mul(b, c) + tensor([[ 0.5767, 0.1363, -0.5877, 2.5083], + [-0.1614, -0.0382, 0.1645, -0.7021], + [ 0.0360, 0.0085, -0.0367, 0.1567], + [ 0.4312, 0.1019, -0.4394, 1.8753]]) + """ + +def multinomial( + input: Tensor, + num_samples: _int | SymInt, + replacement: _bool = False, + *, + generator: Generator | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + multinomial(input, num_samples, replacement=False, *, generator=None, out=None) -> LongTensor + + Returns a tensor where each row contains :attr:`num_samples` indices sampled + from the multinomial (a stricter definition would be multivariate, + refer to :class:`torch.distributions.multinomial.Multinomial` for more details) + probability distribution located in the corresponding row + of tensor :attr:`input`. + + .. note:: + The rows of :attr:`input` do not need to sum to one (in which case we use + the values as weights), but must be non-negative, finite and have + a non-zero sum. + + Indices are ordered from left to right according to when each was sampled + (first samples are placed in first column). + + If :attr:`input` is a vector, :attr:`out` is a vector of size :attr:`num_samples`. + + If :attr:`input` is a matrix with `m` rows, :attr:`out` is an matrix of shape + :math:`(m \times \text{num\_samples})`. + + If replacement is ``True``, samples are drawn with replacement. + + If not, they are drawn without replacement, which means that when a + sample index is drawn for a row, it cannot be drawn again for that row. + + .. note:: + When drawn without replacement, :attr:`num_samples` must be lower than + number of non-zero elements in :attr:`input` (or the min number of non-zero + elements in each row of :attr:`input` if it is a matrix). + + Args: + input (Tensor): the input tensor containing probabilities + num_samples (int): number of samples to draw + replacement (bool, optional): whether to draw with replacement or not + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + + Example:: + + >>> weights = torch.tensor([0, 10, 3, 0], dtype=torch.float) # create a tensor of weights + >>> torch.multinomial(weights, 2) + tensor([1, 2]) + >>> torch.multinomial(weights, 5) # ERROR! + RuntimeError: cannot sample n_sample > prob_dist.size(-1) samples without replacement + >>> torch.multinomial(weights, 4, replacement=True) + tensor([ 2, 1, 1, 1]) + """ + +@overload +def multiply( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + multiply(input, other, *, out=None) + + Alias for :func:`torch.mul`. + """ + +@overload +def multiply(input: Tensor, other: Number | _complex) -> Tensor: + r""" + multiply(input, other, *, out=None) + + Alias for :func:`torch.mul`. + """ + +def mv(input: Tensor, vec: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + mv(input, vec, *, out=None) -> Tensor + + Performs a matrix-vector product of the matrix :attr:`input` and the vector + :attr:`vec`. + + If :attr:`input` is a :math:`(n \times m)` tensor, :attr:`vec` is a 1-D tensor of + size :math:`m`, :attr:`out` will be 1-D of size :math:`n`. + + .. note:: This function does not :ref:`broadcast `. + + Args: + input (Tensor): matrix to be multiplied + vec (Tensor): vector to be multiplied + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> mat = torch.randn(2, 3) + >>> vec = torch.randn(3) + >>> torch.mv(mat, vec) + tensor([ 1.0404, -0.6361]) + """ + +def mvlgamma( + input: Tensor, + p: _int, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + mvlgamma(input, p, *, out=None) -> Tensor + + Alias for :func:`torch.special.multigammaln`. + """ + +def nan_to_num( + input: Tensor, + nan: _float | None = None, + posinf: _float | None = None, + neginf: _float | None = None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + nan_to_num(input, nan=0.0, posinf=None, neginf=None, *, out=None) -> Tensor + + Replaces :literal:`NaN`, positive infinity, and negative infinity values in :attr:`input` + with the values specified by :attr:`nan`, :attr:`posinf`, and :attr:`neginf`, respectively. + By default, :literal:`NaN`\ s are replaced with zero, positive infinity is replaced with the + greatest finite value representable by :attr:`input`'s dtype, and negative infinity + is replaced with the least finite value representable by :attr:`input`'s dtype. + + Args: + input (Tensor): the input tensor. + nan (Number, optional): the value to replace :literal:`NaN`\s with. Default is zero. + posinf (Number, optional): if a Number, the value to replace positive infinity values with. + If None, positive infinity values are replaced with the greatest finite value representable by :attr:`input`'s dtype. + Default is None. + neginf (Number, optional): if a Number, the value to replace negative infinity values with. + If None, negative infinity values are replaced with the lowest finite value representable by :attr:`input`'s dtype. + Default is None. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> x = torch.tensor([float('nan'), float('inf'), -float('inf'), 3.14]) + >>> torch.nan_to_num(x) + tensor([ 0.0000e+00, 3.4028e+38, -3.4028e+38, 3.1400e+00]) + >>> torch.nan_to_num(x, nan=2.0) + tensor([ 2.0000e+00, 3.4028e+38, -3.4028e+38, 3.1400e+00]) + >>> torch.nan_to_num(x, nan=2.0, posinf=1.0) + tensor([ 2.0000e+00, 1.0000e+00, -3.4028e+38, 3.1400e+00]) + """ + +def nan_to_num_( + input: Tensor, + nan: _float | None = None, + posinf: _float | None = None, + neginf: _float | None = None, +) -> Tensor: ... +def nanmean( + input: Tensor, + dim: _int | _size | None = None, + keepdim: _bool = False, + *, + dtype: _dtype | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + nanmean(input, dim=None, keepdim=False, *, dtype=None, out=None) -> Tensor + + Computes the mean of all `non-NaN` elements along the specified dimensions. + Input must be floating point or complex. + + This function is identical to :func:`torch.mean` when there are no `NaN` values + in the :attr:`input` tensor. In the presence of `NaN`, :func:`torch.mean` will + propagate the `NaN` to the output whereas :func:`torch.nanmean` will ignore the + `NaN` values (`torch.nanmean(a)` is equivalent to `torch.mean(a[~a.isnan()])`). + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor, either of floating point or complex dtype + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + out (Tensor, optional): the output tensor. + + .. seealso:: + + :func:`torch.mean` computes the mean value, propagating `NaN`. + + Example:: + + >>> x = torch.tensor([[torch.nan, 1, 2], [1, 2, 3]]) + >>> x.mean() + tensor(nan) + >>> x.nanmean() + tensor(1.8000) + >>> x.mean(dim=0) + tensor([ nan, 1.5000, 2.5000]) + >>> x.nanmean(dim=0) + tensor([1.0000, 1.5000, 2.5000]) + + # If all elements in the reduced dimensions are NaN then the result is NaN + >>> torch.tensor([torch.nan]).nanmean() + tensor(nan) + """ + +@overload +def nanmedian(input: Tensor) -> Tensor: + r""" + nanmedian(input) -> Tensor + + Returns the median of the values in :attr:`input`, ignoring ``NaN`` values. + + This function is identical to :func:`torch.median` when there are no ``NaN`` values in :attr:`input`. + When :attr:`input` has one or more ``NaN`` values, :func:`torch.median` will always return ``NaN``, + while this function will return the median of the non-``NaN`` elements in :attr:`input`. + If all the elements in :attr:`input` are ``NaN`` it will also return ``NaN``. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> a = torch.tensor([1, float('nan'), 3, 2]) + >>> a.median() + tensor(nan) + >>> a.nanmedian() + tensor(2.) + + .. function:: nanmedian(input, dim=-1, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` contains the median of each row of :attr:`input` + in the dimension :attr:`dim`, ignoring ``NaN`` values, and ``indices`` contains the index of the median values + found in the dimension :attr:`dim`. + + This function is identical to :func:`torch.median` when there are no ``NaN`` values in a reduced row. When a reduced row has + one or more ``NaN`` values, :func:`torch.median` will always reduce it to ``NaN``, while this function will reduce it to the + median of the non-``NaN`` elements. If all the elements in a reduced row are ``NaN`` then it will be reduced to ``NaN``, too. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out ((Tensor, Tensor), optional): The first tensor will be populated with the median values and the second + tensor, which must have dtype long, with their indices in the dimension + :attr:`dim` of :attr:`input`. + + Example:: + + >>> a = torch.tensor([[2, 3, 1], [float('nan'), 1, float('nan')]]) + >>> a + tensor([[2., 3., 1.], + [nan, 1., nan]]) + >>> a.median(0) + torch.return_types.median(values=tensor([nan, 1., nan]), indices=tensor([1, 1, 1])) + >>> a.nanmedian(0) + torch.return_types.nanmedian(values=tensor([2., 1., 1.]), indices=tensor([0, 1, 0])) + """ + +@overload +def nanmedian( + input: Tensor, + dim: _int, + keepdim: _bool = False, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.nanmedian: + r""" + nanmedian(input) -> Tensor + + Returns the median of the values in :attr:`input`, ignoring ``NaN`` values. + + This function is identical to :func:`torch.median` when there are no ``NaN`` values in :attr:`input`. + When :attr:`input` has one or more ``NaN`` values, :func:`torch.median` will always return ``NaN``, + while this function will return the median of the non-``NaN`` elements in :attr:`input`. + If all the elements in :attr:`input` are ``NaN`` it will also return ``NaN``. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> a = torch.tensor([1, float('nan'), 3, 2]) + >>> a.median() + tensor(nan) + >>> a.nanmedian() + tensor(2.) + + .. function:: nanmedian(input, dim=-1, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` contains the median of each row of :attr:`input` + in the dimension :attr:`dim`, ignoring ``NaN`` values, and ``indices`` contains the index of the median values + found in the dimension :attr:`dim`. + + This function is identical to :func:`torch.median` when there are no ``NaN`` values in a reduced row. When a reduced row has + one or more ``NaN`` values, :func:`torch.median` will always reduce it to ``NaN``, while this function will reduce it to the + median of the non-``NaN`` elements. If all the elements in a reduced row are ``NaN`` then it will be reduced to ``NaN``, too. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out ((Tensor, Tensor), optional): The first tensor will be populated with the median values and the second + tensor, which must have dtype long, with their indices in the dimension + :attr:`dim` of :attr:`input`. + + Example:: + + >>> a = torch.tensor([[2, 3, 1], [float('nan'), 1, float('nan')]]) + >>> a + tensor([[2., 3., 1.], + [nan, 1., nan]]) + >>> a.median(0) + torch.return_types.median(values=tensor([nan, 1., nan]), indices=tensor([1, 1, 1])) + >>> a.nanmedian(0) + torch.return_types.nanmedian(values=tensor([2., 1., 1.]), indices=tensor([0, 1, 0])) + """ + +@overload +def nanmedian( + input: Tensor, + dim: str | EllipsisType | None, + keepdim: _bool = False, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.nanmedian: + r""" + nanmedian(input) -> Tensor + + Returns the median of the values in :attr:`input`, ignoring ``NaN`` values. + + This function is identical to :func:`torch.median` when there are no ``NaN`` values in :attr:`input`. + When :attr:`input` has one or more ``NaN`` values, :func:`torch.median` will always return ``NaN``, + while this function will return the median of the non-``NaN`` elements in :attr:`input`. + If all the elements in :attr:`input` are ``NaN`` it will also return ``NaN``. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> a = torch.tensor([1, float('nan'), 3, 2]) + >>> a.median() + tensor(nan) + >>> a.nanmedian() + tensor(2.) + + .. function:: nanmedian(input, dim=-1, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` contains the median of each row of :attr:`input` + in the dimension :attr:`dim`, ignoring ``NaN`` values, and ``indices`` contains the index of the median values + found in the dimension :attr:`dim`. + + This function is identical to :func:`torch.median` when there are no ``NaN`` values in a reduced row. When a reduced row has + one or more ``NaN`` values, :func:`torch.median` will always reduce it to ``NaN``, while this function will reduce it to the + median of the non-``NaN`` elements. If all the elements in a reduced row are ``NaN`` then it will be reduced to ``NaN``, too. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out ((Tensor, Tensor), optional): The first tensor will be populated with the median values and the second + tensor, which must have dtype long, with their indices in the dimension + :attr:`dim` of :attr:`input`. + + Example:: + + >>> a = torch.tensor([[2, 3, 1], [float('nan'), 1, float('nan')]]) + >>> a + tensor([[2., 3., 1.], + [nan, 1., nan]]) + >>> a.median(0) + torch.return_types.median(values=tensor([nan, 1., nan]), indices=tensor([1, 1, 1])) + >>> a.nanmedian(0) + torch.return_types.nanmedian(values=tensor([2., 1., 1.]), indices=tensor([0, 1, 0])) + """ + +@overload +def nanquantile( + input: Tensor, + q: Tensor, + dim: _int | None = None, + keepdim: _bool = False, + *, + interpolation: str = "linear", + out: Tensor | None = None, +) -> Tensor: + r""" + nanquantile(input, q, dim=None, keepdim=False, *, interpolation='linear', out=None) -> Tensor + + This is a variant of :func:`torch.quantile` that "ignores" ``NaN`` values, + computing the quantiles :attr:`q` as if ``NaN`` values in :attr:`input` did + not exist. If all values in a reduced row are ``NaN`` then the quantiles for + that reduction will be ``NaN``. See the documentation for :func:`torch.quantile`. + + Args: + input (Tensor): the input tensor. + q (float or Tensor): a scalar or 1D tensor of quantile values in the range [0, 1] + + dim (int, optional): the dimension to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword arguments: + interpolation (str): interpolation method to use when the desired quantile lies between two data points. + Can be ``linear``, ``lower``, ``higher``, ``midpoint`` and ``nearest``. + Default is ``linear``. + out (Tensor, optional): the output tensor. + + Example:: + + >>> t = torch.tensor([float('nan'), 1, 2]) + >>> t.quantile(0.5) + tensor(nan) + >>> t.nanquantile(0.5) + tensor(1.5000) + >>> t = torch.tensor([[float('nan'), float('nan')], [1, 2]]) + >>> t + tensor([[nan, nan], + [1., 2.]]) + >>> t.nanquantile(0.5, dim=0) + tensor([1., 2.]) + >>> t.nanquantile(0.5, dim=1) + tensor([ nan, 1.5000]) + """ + +@overload +def nanquantile( + input: Tensor, + q: _float, + dim: _int | None = None, + keepdim: _bool = False, + *, + interpolation: str = "linear", + out: Tensor | None = None, +) -> Tensor: + r""" + nanquantile(input, q, dim=None, keepdim=False, *, interpolation='linear', out=None) -> Tensor + + This is a variant of :func:`torch.quantile` that "ignores" ``NaN`` values, + computing the quantiles :attr:`q` as if ``NaN`` values in :attr:`input` did + not exist. If all values in a reduced row are ``NaN`` then the quantiles for + that reduction will be ``NaN``. See the documentation for :func:`torch.quantile`. + + Args: + input (Tensor): the input tensor. + q (float or Tensor): a scalar or 1D tensor of quantile values in the range [0, 1] + + dim (int, optional): the dimension to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword arguments: + interpolation (str): interpolation method to use when the desired quantile lies between two data points. + Can be ``linear``, ``lower``, ``higher``, ``midpoint`` and ``nearest``. + Default is ``linear``. + out (Tensor, optional): the output tensor. + + Example:: + + >>> t = torch.tensor([float('nan'), 1, 2]) + >>> t.quantile(0.5) + tensor(nan) + >>> t.nanquantile(0.5) + tensor(1.5000) + >>> t = torch.tensor([[float('nan'), float('nan')], [1, 2]]) + >>> t + tensor([[nan, nan], + [1., 2.]]) + >>> t.nanquantile(0.5, dim=0) + tensor([1., 2.]) + >>> t.nanquantile(0.5, dim=1) + tensor([ nan, 1.5000]) + """ + +def nansum( + input: Tensor, + dim: _int | _size | None = None, + keepdim: _bool = False, + *, + dtype: _dtype | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + nansum(input, *, dtype=None) -> Tensor + + Returns the sum of all elements, treating Not a Numbers (NaNs) as zero. + + Args: + input (Tensor): the input tensor. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + + Example:: + + >>> a = torch.tensor([1., 2., float('nan'), 4.]) + >>> torch.nansum(a) + tensor(7.) + + .. function:: nansum(input, dim, keepdim=False, *, dtype=None) -> Tensor + :noindex: + + Returns the sum of each row of the :attr:`input` tensor in the given + dimension :attr:`dim`, treating Not a Numbers (NaNs) as zero. + If :attr:`dim` is a list of dimensions, reduce over all of them. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + + Example:: + + >>> torch.nansum(torch.tensor([1., float("nan")])) + tensor(1.) + >>> a = torch.tensor([[1, 2], [3., float("nan")]]) + >>> torch.nansum(a) + tensor(6.) + >>> torch.nansum(a, dim=0) + tensor([4., 2.]) + >>> torch.nansum(a, dim=1) + tensor([3., 3.]) + """ + +@overload +def narrow( + input: Tensor, + dim: _int, + start: Tensor, + length: _int | SymInt, +) -> Tensor: + r""" + narrow(input, dim, start, length) -> Tensor + + Returns a new tensor that is a narrowed version of :attr:`input` tensor. The + dimension :attr:`dim` is input from :attr:`start` to ``start + length``. The + returned tensor and :attr:`input` tensor share the same underlying storage. + + Args: + input (Tensor): the tensor to narrow + dim (int): the dimension along which to narrow + start (int or Tensor): index of the element to start the narrowed dimension + from. Can be negative, which means indexing from the end of `dim`. If + `Tensor`, it must be an 0-dim integral `Tensor` (bools not allowed) + length (int): length of the narrowed dimension, must be weakly positive + + Example:: + + >>> x = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + >>> torch.narrow(x, 0, 0, 2) + tensor([[ 1, 2, 3], + [ 4, 5, 6]]) + >>> torch.narrow(x, 1, 1, 2) + tensor([[ 2, 3], + [ 5, 6], + [ 8, 9]]) + >>> torch.narrow(x, -1, torch.tensor(-1), 1) + tensor([[3], + [6], + [9]]) + """ + +@overload +def narrow( + input: Tensor, + dim: _int, + start: _int | SymInt, + length: _int | SymInt, +) -> Tensor: + r""" + narrow(input, dim, start, length) -> Tensor + + Returns a new tensor that is a narrowed version of :attr:`input` tensor. The + dimension :attr:`dim` is input from :attr:`start` to ``start + length``. The + returned tensor and :attr:`input` tensor share the same underlying storage. + + Args: + input (Tensor): the tensor to narrow + dim (int): the dimension along which to narrow + start (int or Tensor): index of the element to start the narrowed dimension + from. Can be negative, which means indexing from the end of `dim`. If + `Tensor`, it must be an 0-dim integral `Tensor` (bools not allowed) + length (int): length of the narrowed dimension, must be weakly positive + + Example:: + + >>> x = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + >>> torch.narrow(x, 0, 0, 2) + tensor([[ 1, 2, 3], + [ 4, 5, 6]]) + >>> torch.narrow(x, 1, 1, 2) + tensor([[ 2, 3], + [ 5, 6], + [ 8, 9]]) + >>> torch.narrow(x, -1, torch.tensor(-1), 1) + tensor([[3], + [6], + [9]]) + """ + +def narrow_copy( + input: Tensor, + dim: _int, + start: _int | SymInt, + length: _int | SymInt, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + narrow_copy(input, dim, start, length, *, out=None) -> Tensor + + Same as :meth:`Tensor.narrow` except this returns a copy rather + than shared storage. This is primarily for sparse tensors, which + do not have a shared-storage narrow method. + + Args: + input (Tensor): the tensor to narrow + dim (int): the dimension along which to narrow + start (int): index of the element to start the narrowed dimension from. Can + be negative, which means indexing from the end of `dim` + length (int): length of the narrowed dimension, must be weakly positive + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> x = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + >>> torch.narrow_copy(x, 0, 0, 2) + tensor([[ 1, 2, 3], + [ 4, 5, 6]]) + >>> torch.narrow_copy(x, 1, 1, 2) + tensor([[ 2, 3], + [ 5, 6], + [ 8, 9]]) + >>> s = torch.arange(16).reshape(2, 2, 2, 2).to_sparse(2) + >>> torch.narrow_copy(s, 0, 0, 1) + tensor(indices=tensor([[0, 0], + [0, 1]]), + values=tensor([[[0, 1], + [2, 3]], + + [[4, 5], + [6, 7]]]), + size=(1, 2, 2, 2), nnz=2, layout=torch.sparse_coo) + + .. seealso:: + + :func:`torch.narrow` for a non copy variant + """ + +def native_batch_norm( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + running_mean: Tensor | None, + running_var: Tensor | None, + training: _bool, + momentum: _float, + eps: _float, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> tuple[Tensor, Tensor, Tensor]: ... +def native_channel_shuffle(input: Tensor, groups: _int | SymInt) -> Tensor: ... +def native_dropout( + input: Tensor, + p: _float, + train: _bool | None, +) -> tuple[Tensor, Tensor]: ... +def native_group_norm( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + N: _int | SymInt, + C: _int | SymInt, + HxW: _int | SymInt, + group: _int, + eps: _float, +) -> tuple[Tensor, Tensor, Tensor]: ... +def native_layer_norm( + input: Tensor, + normalized_shape: Sequence[_int | SymInt], + weight: Tensor | None, + bias: Tensor | None, + eps: _float, +) -> tuple[Tensor, Tensor, Tensor]: ... +@overload +def native_norm( + input: Tensor, + p: Number | _complex | None, + dim: _int | _size, + keepdim: _bool, + dtype: _dtype | None, +) -> Tensor: ... +@overload +def native_norm(input: Tensor, p: Number | _complex = 2) -> Tensor: ... +@overload +def ne( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + ne(input, other, *, out=None) -> Tensor + + Computes :math:`\text{input} \neq \text{other}` element-wise. + + + The second argument can be a number or a tensor whose shape is + :ref:`broadcastable ` with the first argument. + + Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is not equal to :attr:`other` and False elsewhere + + Example:: + + >>> torch.ne(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[False, True], [True, False]]) + """ + +@overload +def ne( + input: Tensor, + other: Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + ne(input, other, *, out=None) -> Tensor + + Computes :math:`\text{input} \neq \text{other}` element-wise. + + + The second argument can be a number or a tensor whose shape is + :ref:`broadcastable ` with the first argument. + + Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is not equal to :attr:`other` and False elsewhere + + Example:: + + >>> torch.ne(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[False, True], [True, False]]) + """ + +def neg(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + neg(input, *, out=None) -> Tensor + + Returns a new tensor with the negative of the elements of :attr:`input`. + + .. math:: + \text{out} = -1 \times \text{input} + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(5) + >>> a + tensor([ 0.0090, -0.2262, -0.0682, -0.2866, 0.3940]) + >>> torch.neg(a) + tensor([-0.0090, 0.2262, 0.0682, 0.2866, -0.3940]) + """ + +def neg_(input: Tensor) -> Tensor: ... +def negative(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + negative(input, *, out=None) -> Tensor + + Alias for :func:`torch.neg` + """ + +def negative_(input: Tensor) -> Tensor: ... +def nextafter( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + nextafter(input, other, *, out=None) -> Tensor + + Return the next floating-point value after :attr:`input` towards :attr:`other`, elementwise. + + The shapes of ``input`` and ``other`` must be + :ref:`broadcastable `. + + Args: + input (Tensor): the first input tensor + other (Tensor): the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> eps = torch.finfo(torch.float32).eps + >>> torch.nextafter(torch.tensor([1.0, 2.0]), torch.tensor([2.0, 1.0])) == torch.tensor([eps + 1, 2 - eps]) + tensor([True, True]) + """ + +@overload +def nonzero( + input: Tensor, + *, + as_tuple: Literal[False] = False, + out: Tensor | None = None, +) -> Tensor: + r""" + nonzero(input, *, out=None, as_tuple=False) -> LongTensor or tuple of LongTensors + + .. note:: + :func:`torch.nonzero(..., as_tuple=False) ` (default) returns a + 2-D tensor where each row is the index for a nonzero value. + + :func:`torch.nonzero(..., as_tuple=True) ` returns a tuple of 1-D + index tensors, allowing for advanced indexing, so ``x[x.nonzero(as_tuple=True)]`` + gives all nonzero values of tensor ``x``. Of the returned tuple, each index tensor + contains nonzero indices for a certain dimension. + + See below for more details on the two behaviors. + + When :attr:`input` is on CUDA, :func:`torch.nonzero() ` causes + host-device synchronization. + + **When** :attr:`as_tuple` **is** ``False`` **(default)**: + + Returns a tensor containing the indices of all non-zero elements of + :attr:`input`. Each row in the result contains the indices of a non-zero + element in :attr:`input`. The result is sorted lexicographically, with + the last index changing the fastest (C-style). + + If :attr:`input` has :math:`n` dimensions, then the resulting indices tensor + :attr:`out` is of size :math:`(z \times n)`, where :math:`z` is the total number of + non-zero elements in the :attr:`input` tensor. + + **When** :attr:`as_tuple` **is** ``True``: + + Returns a tuple of 1-D tensors, one for each dimension in :attr:`input`, + each containing the indices (in that dimension) of all non-zero elements of + :attr:`input` . + + If :attr:`input` has :math:`n` dimensions, then the resulting tuple contains :math:`n` + tensors of size :math:`z`, where :math:`z` is the total number of + non-zero elements in the :attr:`input` tensor. + + As a special case, when :attr:`input` has zero dimensions and a nonzero scalar + value, it is treated as a one-dimensional tensor with one element. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (LongTensor, optional): the output tensor containing indices + + Returns: + LongTensor or tuple of LongTensor: If :attr:`as_tuple` is ``False``, the output + tensor containing indices. If :attr:`as_tuple` is ``True``, one 1-D tensor for + each dimension, containing the indices of each nonzero element along that + dimension. + + Example:: + + >>> torch.nonzero(torch.tensor([1, 1, 1, 0, 1])) + tensor([[ 0], + [ 1], + [ 2], + [ 4]]) + >>> torch.nonzero(torch.tensor([[0.6, 0.0, 0.0, 0.0], + ... [0.0, 0.4, 0.0, 0.0], + ... [0.0, 0.0, 1.2, 0.0], + ... [0.0, 0.0, 0.0,-0.4]])) + tensor([[ 0, 0], + [ 1, 1], + [ 2, 2], + [ 3, 3]]) + >>> torch.nonzero(torch.tensor([1, 1, 1, 0, 1]), as_tuple=True) + (tensor([0, 1, 2, 4]),) + >>> torch.nonzero(torch.tensor([[0.6, 0.0, 0.0, 0.0], + ... [0.0, 0.4, 0.0, 0.0], + ... [0.0, 0.0, 1.2, 0.0], + ... [0.0, 0.0, 0.0,-0.4]]), as_tuple=True) + (tensor([0, 1, 2, 3]), tensor([0, 1, 2, 3])) + >>> torch.nonzero(torch.tensor(5), as_tuple=True) + (tensor([0]),) + """ + +@overload +def nonzero( + input: Tensor, + *, + as_tuple: Literal[True], +) -> tuple[Tensor, ...]: + r""" + nonzero(input, *, out=None, as_tuple=False) -> LongTensor or tuple of LongTensors + + .. note:: + :func:`torch.nonzero(..., as_tuple=False) ` (default) returns a + 2-D tensor where each row is the index for a nonzero value. + + :func:`torch.nonzero(..., as_tuple=True) ` returns a tuple of 1-D + index tensors, allowing for advanced indexing, so ``x[x.nonzero(as_tuple=True)]`` + gives all nonzero values of tensor ``x``. Of the returned tuple, each index tensor + contains nonzero indices for a certain dimension. + + See below for more details on the two behaviors. + + When :attr:`input` is on CUDA, :func:`torch.nonzero() ` causes + host-device synchronization. + + **When** :attr:`as_tuple` **is** ``False`` **(default)**: + + Returns a tensor containing the indices of all non-zero elements of + :attr:`input`. Each row in the result contains the indices of a non-zero + element in :attr:`input`. The result is sorted lexicographically, with + the last index changing the fastest (C-style). + + If :attr:`input` has :math:`n` dimensions, then the resulting indices tensor + :attr:`out` is of size :math:`(z \times n)`, where :math:`z` is the total number of + non-zero elements in the :attr:`input` tensor. + + **When** :attr:`as_tuple` **is** ``True``: + + Returns a tuple of 1-D tensors, one for each dimension in :attr:`input`, + each containing the indices (in that dimension) of all non-zero elements of + :attr:`input` . + + If :attr:`input` has :math:`n` dimensions, then the resulting tuple contains :math:`n` + tensors of size :math:`z`, where :math:`z` is the total number of + non-zero elements in the :attr:`input` tensor. + + As a special case, when :attr:`input` has zero dimensions and a nonzero scalar + value, it is treated as a one-dimensional tensor with one element. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (LongTensor, optional): the output tensor containing indices + + Returns: + LongTensor or tuple of LongTensor: If :attr:`as_tuple` is ``False``, the output + tensor containing indices. If :attr:`as_tuple` is ``True``, one 1-D tensor for + each dimension, containing the indices of each nonzero element along that + dimension. + + Example:: + + >>> torch.nonzero(torch.tensor([1, 1, 1, 0, 1])) + tensor([[ 0], + [ 1], + [ 2], + [ 4]]) + >>> torch.nonzero(torch.tensor([[0.6, 0.0, 0.0, 0.0], + ... [0.0, 0.4, 0.0, 0.0], + ... [0.0, 0.0, 1.2, 0.0], + ... [0.0, 0.0, 0.0,-0.4]])) + tensor([[ 0, 0], + [ 1, 1], + [ 2, 2], + [ 3, 3]]) + >>> torch.nonzero(torch.tensor([1, 1, 1, 0, 1]), as_tuple=True) + (tensor([0, 1, 2, 4]),) + >>> torch.nonzero(torch.tensor([[0.6, 0.0, 0.0, 0.0], + ... [0.0, 0.4, 0.0, 0.0], + ... [0.0, 0.0, 1.2, 0.0], + ... [0.0, 0.0, 0.0,-0.4]]), as_tuple=True) + (tensor([0, 1, 2, 3]), tensor([0, 1, 2, 3])) + >>> torch.nonzero(torch.tensor(5), as_tuple=True) + (tensor([0]),) + """ + +def nonzero_static( + input: Tensor, + *, + size: _int | SymInt, + fill_value: _int = -1, + out: Tensor | None = None, +) -> Tensor: ... +def norm_except_dim(v: Tensor, pow: _int = 2, dim: _int = 0) -> Tensor: ... +@overload +def normal( + mean: Tensor, + std: Tensor, + *, + generator: Generator | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + normal(mean, std, *, generator=None, out=None) -> Tensor + + Returns a tensor of random numbers drawn from separate normal distributions + whose mean and standard deviation are given. + + The :attr:`mean` is a tensor with the mean of + each output element's normal distribution + + The :attr:`std` is a tensor with the standard deviation of + each output element's normal distribution + + The shapes of :attr:`mean` and :attr:`std` don't need to match, but the + total number of elements in each tensor need to be the same. + + .. note:: When the shapes do not match, the shape of :attr:`mean` + is used as the shape for the returned output tensor + + .. note:: When :attr:`std` is a CUDA tensor, this function synchronizes + its device with the CPU. + + Args: + mean (Tensor): the tensor of per-element means + std (Tensor): the tensor of per-element standard deviations + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.normal(mean=torch.arange(1., 11.), std=torch.arange(1, 0, -0.1)) + tensor([ 1.0425, 3.5672, 2.7969, 4.2925, 4.7229, 6.2134, + 8.0505, 8.1408, 9.0563, 10.0566]) + + .. function:: normal(mean=0.0, std, *, out=None) -> Tensor + :noindex: + + Similar to the function above, but the means are shared among all drawn + elements. + + Args: + mean (float, optional): the mean for all distributions + std (Tensor): the tensor of per-element standard deviations + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.normal(mean=0.5, std=torch.arange(1., 6.)) + tensor([-1.2793, -1.0732, -2.0687, 5.1177, -1.2303]) + + .. function:: normal(mean, std=1.0, *, out=None) -> Tensor + :noindex: + + Similar to the function above, but the standard deviations are shared among + all drawn elements. + + Args: + mean (Tensor): the tensor of per-element means + std (float, optional): the standard deviation for all distributions + + Keyword args: + out (Tensor, optional): the output tensor + + Example:: + + >>> torch.normal(mean=torch.arange(1., 6.)) + tensor([ 1.1552, 2.6148, 2.6535, 5.8318, 4.2361]) + + .. function:: normal(mean, std, size, *, out=None) -> Tensor + :noindex: + + Similar to the function above, but the means and standard deviations are shared + among all drawn elements. The resulting tensor has size given by :attr:`size`. + + Args: + mean (float): the mean for all distributions + std (float): the standard deviation for all distributions + size (int...): a sequence of integers defining the shape of the output tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.normal(2, 3, size=(1, 4)) + tensor([[-1.3987, -1.9544, 3.6048, 0.7909]]) + """ + +@overload +def normal( + mean: Tensor, + std: _float = 1, + *, + generator: Generator | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + normal(mean, std, *, generator=None, out=None) -> Tensor + + Returns a tensor of random numbers drawn from separate normal distributions + whose mean and standard deviation are given. + + The :attr:`mean` is a tensor with the mean of + each output element's normal distribution + + The :attr:`std` is a tensor with the standard deviation of + each output element's normal distribution + + The shapes of :attr:`mean` and :attr:`std` don't need to match, but the + total number of elements in each tensor need to be the same. + + .. note:: When the shapes do not match, the shape of :attr:`mean` + is used as the shape for the returned output tensor + + .. note:: When :attr:`std` is a CUDA tensor, this function synchronizes + its device with the CPU. + + Args: + mean (Tensor): the tensor of per-element means + std (Tensor): the tensor of per-element standard deviations + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.normal(mean=torch.arange(1., 11.), std=torch.arange(1, 0, -0.1)) + tensor([ 1.0425, 3.5672, 2.7969, 4.2925, 4.7229, 6.2134, + 8.0505, 8.1408, 9.0563, 10.0566]) + + .. function:: normal(mean=0.0, std, *, out=None) -> Tensor + :noindex: + + Similar to the function above, but the means are shared among all drawn + elements. + + Args: + mean (float, optional): the mean for all distributions + std (Tensor): the tensor of per-element standard deviations + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.normal(mean=0.5, std=torch.arange(1., 6.)) + tensor([-1.2793, -1.0732, -2.0687, 5.1177, -1.2303]) + + .. function:: normal(mean, std=1.0, *, out=None) -> Tensor + :noindex: + + Similar to the function above, but the standard deviations are shared among + all drawn elements. + + Args: + mean (Tensor): the tensor of per-element means + std (float, optional): the standard deviation for all distributions + + Keyword args: + out (Tensor, optional): the output tensor + + Example:: + + >>> torch.normal(mean=torch.arange(1., 6.)) + tensor([ 1.1552, 2.6148, 2.6535, 5.8318, 4.2361]) + + .. function:: normal(mean, std, size, *, out=None) -> Tensor + :noindex: + + Similar to the function above, but the means and standard deviations are shared + among all drawn elements. The resulting tensor has size given by :attr:`size`. + + Args: + mean (float): the mean for all distributions + std (float): the standard deviation for all distributions + size (int...): a sequence of integers defining the shape of the output tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.normal(2, 3, size=(1, 4)) + tensor([[-1.3987, -1.9544, 3.6048, 0.7909]]) + """ + +@overload +def normal( + mean: _float, + std: Tensor, + *, + generator: Generator | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + normal(mean, std, *, generator=None, out=None) -> Tensor + + Returns a tensor of random numbers drawn from separate normal distributions + whose mean and standard deviation are given. + + The :attr:`mean` is a tensor with the mean of + each output element's normal distribution + + The :attr:`std` is a tensor with the standard deviation of + each output element's normal distribution + + The shapes of :attr:`mean` and :attr:`std` don't need to match, but the + total number of elements in each tensor need to be the same. + + .. note:: When the shapes do not match, the shape of :attr:`mean` + is used as the shape for the returned output tensor + + .. note:: When :attr:`std` is a CUDA tensor, this function synchronizes + its device with the CPU. + + Args: + mean (Tensor): the tensor of per-element means + std (Tensor): the tensor of per-element standard deviations + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.normal(mean=torch.arange(1., 11.), std=torch.arange(1, 0, -0.1)) + tensor([ 1.0425, 3.5672, 2.7969, 4.2925, 4.7229, 6.2134, + 8.0505, 8.1408, 9.0563, 10.0566]) + + .. function:: normal(mean=0.0, std, *, out=None) -> Tensor + :noindex: + + Similar to the function above, but the means are shared among all drawn + elements. + + Args: + mean (float, optional): the mean for all distributions + std (Tensor): the tensor of per-element standard deviations + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.normal(mean=0.5, std=torch.arange(1., 6.)) + tensor([-1.2793, -1.0732, -2.0687, 5.1177, -1.2303]) + + .. function:: normal(mean, std=1.0, *, out=None) -> Tensor + :noindex: + + Similar to the function above, but the standard deviations are shared among + all drawn elements. + + Args: + mean (Tensor): the tensor of per-element means + std (float, optional): the standard deviation for all distributions + + Keyword args: + out (Tensor, optional): the output tensor + + Example:: + + >>> torch.normal(mean=torch.arange(1., 6.)) + tensor([ 1.1552, 2.6148, 2.6535, 5.8318, 4.2361]) + + .. function:: normal(mean, std, size, *, out=None) -> Tensor + :noindex: + + Similar to the function above, but the means and standard deviations are shared + among all drawn elements. The resulting tensor has size given by :attr:`size`. + + Args: + mean (float): the mean for all distributions + std (float): the standard deviation for all distributions + size (int...): a sequence of integers defining the shape of the output tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.normal(2, 3, size=(1, 4)) + tensor([[-1.3987, -1.9544, 3.6048, 0.7909]]) + """ + +@overload +def normal( + mean: _float, + std: _float, + size: Sequence[_int | SymInt], + *, + generator: Generator | None = None, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + normal(mean, std, *, generator=None, out=None) -> Tensor + + Returns a tensor of random numbers drawn from separate normal distributions + whose mean and standard deviation are given. + + The :attr:`mean` is a tensor with the mean of + each output element's normal distribution + + The :attr:`std` is a tensor with the standard deviation of + each output element's normal distribution + + The shapes of :attr:`mean` and :attr:`std` don't need to match, but the + total number of elements in each tensor need to be the same. + + .. note:: When the shapes do not match, the shape of :attr:`mean` + is used as the shape for the returned output tensor + + .. note:: When :attr:`std` is a CUDA tensor, this function synchronizes + its device with the CPU. + + Args: + mean (Tensor): the tensor of per-element means + std (Tensor): the tensor of per-element standard deviations + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.normal(mean=torch.arange(1., 11.), std=torch.arange(1, 0, -0.1)) + tensor([ 1.0425, 3.5672, 2.7969, 4.2925, 4.7229, 6.2134, + 8.0505, 8.1408, 9.0563, 10.0566]) + + .. function:: normal(mean=0.0, std, *, out=None) -> Tensor + :noindex: + + Similar to the function above, but the means are shared among all drawn + elements. + + Args: + mean (float, optional): the mean for all distributions + std (Tensor): the tensor of per-element standard deviations + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.normal(mean=0.5, std=torch.arange(1., 6.)) + tensor([-1.2793, -1.0732, -2.0687, 5.1177, -1.2303]) + + .. function:: normal(mean, std=1.0, *, out=None) -> Tensor + :noindex: + + Similar to the function above, but the standard deviations are shared among + all drawn elements. + + Args: + mean (Tensor): the tensor of per-element means + std (float, optional): the standard deviation for all distributions + + Keyword args: + out (Tensor, optional): the output tensor + + Example:: + + >>> torch.normal(mean=torch.arange(1., 6.)) + tensor([ 1.1552, 2.6148, 2.6535, 5.8318, 4.2361]) + + .. function:: normal(mean, std, size, *, out=None) -> Tensor + :noindex: + + Similar to the function above, but the means and standard deviations are shared + among all drawn elements. The resulting tensor has size given by :attr:`size`. + + Args: + mean (float): the mean for all distributions + std (float): the standard deviation for all distributions + size (int...): a sequence of integers defining the shape of the output tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.normal(2, 3, size=(1, 4)) + tensor([[-1.3987, -1.9544, 3.6048, 0.7909]]) + """ + +@overload +def not_equal( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + not_equal(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.ne`. + """ + +@overload +def not_equal( + input: Tensor, + other: Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + not_equal(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.ne`. + """ + +@overload +def nuclear_norm( + input: Tensor, + dim: _int | _size, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: ... +@overload +def nuclear_norm( + input: Tensor, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: ... +def numel(self: Tensor) -> _int: + r""" + numel(input: Tensor) -> int + + Returns the total number of elements in the :attr:`input` tensor. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> a = torch.randn(1, 2, 3, 4, 5) + >>> torch.numel(a) + 120 + >>> a = torch.zeros(4,4) + >>> torch.numel(a) + 16 + """ + +@overload +def ones( + size: Sequence[_int | SymInt], + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + ones(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with the scalar value `1`, with the shape defined + by the variable argument :attr:`size`. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.ones(2, 3) + tensor([[ 1., 1., 1.], + [ 1., 1., 1.]]) + + >>> torch.ones(5) + tensor([ 1., 1., 1., 1., 1.]) + """ + +@overload +def ones( + *size: _int | SymInt, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + ones(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with the scalar value `1`, with the shape defined + by the variable argument :attr:`size`. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.ones(2, 3) + tensor([[ 1., 1., 1.], + [ 1., 1., 1.]]) + + >>> torch.ones(5) + tensor([ 1., 1., 1., 1., 1.]) + """ + +@overload +def ones( + size: _size, + *, + names: Sequence[str | EllipsisType | None] | None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + ones(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with the scalar value `1`, with the shape defined + by the variable argument :attr:`size`. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.ones(2, 3) + tensor([[ 1., 1., 1.], + [ 1., 1., 1.]]) + + >>> torch.ones(5) + tensor([ 1., 1., 1., 1., 1.]) + """ + +@overload +def ones( + *size: _int, + names: Sequence[str | EllipsisType | None] | None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + ones(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with the scalar value `1`, with the shape defined + by the variable argument :attr:`size`. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.ones(2, 3) + tensor([[ 1., 1., 1.], + [ 1., 1., 1.]]) + + >>> torch.ones(5) + tensor([ 1., 1., 1., 1., 1.]) + """ + +def ones_like( + input: Tensor, + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + ones_like(input, *, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor filled with the scalar value `1`, with the same size as + :attr:`input`. ``torch.ones_like(input)`` is equivalent to + ``torch.ones(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``. + + .. warning:: + As of 0.4, this function does not support an :attr:`out` keyword. As an alternative, + the old ``torch.ones_like(input, out=output)`` is equivalent to + ``torch.ones(input.size(), out=output)``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + + Keyword arguments: + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + + Example:: + + >>> input = torch.empty(2, 3) + >>> torch.ones_like(input) + tensor([[ 1., 1., 1.], + [ 1., 1., 1.]]) + """ + +def orgqr( + input: Tensor, + input2: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + orgqr(input, tau) -> Tensor + + Alias for :func:`torch.linalg.householder_product`. + """ + +def ormqr( + input: Tensor, + input2: Tensor, + input3: Tensor, + left: _bool = True, + transpose: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + ormqr(input, tau, other, left=True, transpose=False, *, out=None) -> Tensor + + Computes the matrix-matrix multiplication of a product of Householder matrices with a general matrix. + + Multiplies a :math:`m \times n` matrix `C` (given by :attr:`other`) with a matrix `Q`, + where `Q` is represented using Householder reflectors `(input, tau)`. + See `Representation of Orthogonal or Unitary Matrices`_ for further details. + + If :attr:`left` is `True` then `op(Q)` times `C` is computed, otherwise the result is `C` times `op(Q)`. + When :attr:`left` is `True`, the implicit matrix `Q` has size :math:`m \times m`. + It has size :math:`n \times n` otherwise. + If :attr:`transpose` is `True` then `op` is the conjugate transpose operation, otherwise it's a no-op. + + Supports inputs of float, double, cfloat and cdouble dtypes. + Also supports batched inputs, and, if the input is batched, the output is batched with the same dimensions. + + .. seealso:: + :func:`torch.geqrf` can be used to form the Householder representation `(input, tau)` of matrix `Q` + from the QR decomposition. + + .. note:: + This function supports backward but it is only fast when ``(input, tau)`` do not require gradients + and/or ``tau.size(-1)`` is very small. + `` + + Args: + input (Tensor): tensor of shape `(*, mn, k)` where `*` is zero or more batch dimensions + and `mn` equals to `m` or `n` depending on the :attr:`left`. + tau (Tensor): tensor of shape `(*, min(mn, k))` where `*` is zero or more batch dimensions. + other (Tensor): tensor of shape `(*, m, n)` where `*` is zero or more batch dimensions. + left (bool): controls the order of multiplication. + transpose (bool): controls whether the matrix `Q` is conjugate transposed or not. + + Keyword args: + out (Tensor, optional): the output Tensor. Ignored if `None`. Default: `None`. + + .. _Representation of Orthogonal or Unitary Matrices: + https://www.netlib.org/lapack/lug/node128.html + """ + +def outer( + input: Tensor, + vec2: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + outer(input, vec2, *, out=None) -> Tensor + + Outer product of :attr:`input` and :attr:`vec2`. + If :attr:`input` is a vector of size :math:`n` and :attr:`vec2` is a vector of + size :math:`m`, then :attr:`out` must be a matrix of size :math:`(n \times m)`. + + .. note:: This function does not :ref:`broadcast `. + + Args: + input (Tensor): 1-D input vector + vec2 (Tensor): 1-D input vector + + Keyword args: + out (Tensor, optional): optional output matrix + + Example:: + + >>> v1 = torch.arange(1., 5.) + >>> v2 = torch.arange(1., 4.) + >>> torch.outer(v1, v2) + tensor([[ 1., 2., 3.], + [ 2., 4., 6.], + [ 3., 6., 9.], + [ 4., 8., 12.]]) + """ + +def pairwise_distance( + x1: Tensor, + x2: Tensor, + p: _float = 2, + eps: _float = 1e-06, + keepdim: _bool = False, +) -> Tensor: ... +def pdist(input: Tensor, p: _float = 2) -> Tensor: ... +def permute(input: Tensor, dims: _size) -> Tensor: + r""" + permute(input, dims) -> Tensor + + Returns a view of the original tensor :attr:`input` with its dimensions permuted. + + Args: + input (Tensor): the input tensor. + dims (tuple of int): The desired ordering of dimensions + + Example: + >>> x = torch.randn(2, 3, 5) + >>> x.size() + torch.Size([2, 3, 5]) + >>> torch.permute(x, (2, 0, 1)).size() + torch.Size([5, 2, 3]) + """ + +def permute_copy( + input: Tensor, + dims: _size, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.permute`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def pinverse(input: Tensor, rcond: _float = 1e-15) -> Tensor: + r""" + pinverse(input, rcond=1e-15) -> Tensor + + Alias for :func:`torch.linalg.pinv` + """ + +def pixel_shuffle(input: Tensor, upscale_factor: _int) -> Tensor: ... +def pixel_unshuffle(input: Tensor, downscale_factor: _int) -> Tensor: ... +def poisson(input: Tensor, generator: Generator | None = None) -> Tensor: + r""" + poisson(input, generator=None) -> Tensor + + Returns a tensor of the same size as :attr:`input` with each element + sampled from a Poisson distribution with rate parameter given by the corresponding + element in :attr:`input` i.e., + + .. math:: + \text{out}_i \sim \text{Poisson}(\text{input}_i) + + :attr:`input` must be non-negative. + + Args: + input (Tensor): the input tensor containing the rates of the Poisson distribution + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + + Example:: + + >>> rates = torch.rand(4, 4) * 5 # rate parameter between 0 and 5 + >>> torch.poisson(rates) + tensor([[9., 1., 3., 5.], + [8., 6., 6., 0.], + [0., 4., 5., 3.], + [2., 1., 4., 2.]]) + """ + +def poisson_nll_loss( + input: Tensor, + target: Tensor, + log_input: _bool, + full: _bool, + eps: _float, + reduction: _int, +) -> Tensor: ... +def polar( + abs: Tensor, + angle: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + polar(abs, angle, *, out=None) -> Tensor + + Constructs a complex tensor whose elements are Cartesian coordinates + corresponding to the polar coordinates with absolute value :attr:`abs` and angle + :attr:`angle`. + + .. math:: + \text{out} = \text{abs} \cdot \cos(\text{angle}) + \text{abs} \cdot \sin(\text{angle}) \cdot j + + .. note:: + `torch.polar` is similar to + `std::polar `_ + and does not compute the polar decomposition + of a complex tensor like Python's `cmath.polar` and SciPy's `linalg.polar` do. + The behavior of this function is undefined if `abs` is negative or NaN, or if `angle` is + infinite. + + + Args: + abs (Tensor): The absolute value the complex tensor. Must be float or double. + angle (Tensor): The angle of the complex tensor. Must be same dtype as + :attr:`abs`. + + Keyword args: + out (Tensor): If the inputs are ``torch.float32``, must be + ``torch.complex64``. If the inputs are ``torch.float64``, must be + ``torch.complex128``. + + Example:: + + >>> import numpy as np + >>> abs = torch.tensor([1, 2], dtype=torch.float64) + >>> angle = torch.tensor([np.pi / 2, 5 * np.pi / 4], dtype=torch.float64) + >>> z = torch.polar(abs, angle) + >>> z + tensor([(0.0000+1.0000j), (-1.4142-1.4142j)], dtype=torch.complex128) + """ + +def polygamma( + n: _int, + input: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + polygamma(n, input, *, out=None) -> Tensor + + Alias for :func:`torch.special.polygamma`. + """ + +def positive(input: Tensor) -> Tensor: + r""" + positive(input) -> Tensor + + Returns :attr:`input`. + Throws a runtime error if :attr:`input` is a bool tensor. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> t = torch.randn(5) + >>> t + tensor([ 0.0090, -0.2262, -0.0682, -0.2866, 0.3940]) + >>> torch.positive(t) + tensor([ 0.0090, -0.2262, -0.0682, -0.2866, 0.3940]) + """ + +@overload +def pow( + input: Tensor, + exponent: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + pow(input, exponent, *, out=None) -> Tensor + + Takes the power of each element in :attr:`input` with :attr:`exponent` and + returns a tensor with the result. + + :attr:`exponent` can be either a single ``float`` number or a `Tensor` + with the same number of elements as :attr:`input`. + + When :attr:`exponent` is a scalar value, the operation applied is: + + .. math:: + \text{out}_i = x_i ^ \text{exponent} + + When :attr:`exponent` is a tensor, the operation applied is: + + .. math:: + \text{out}_i = x_i ^ {\text{exponent}_i} + + When :attr:`exponent` is a tensor, the shapes of :attr:`input` + and :attr:`exponent` must be :ref:`broadcastable `. + + Args: + input (Tensor): the input tensor. + exponent (float or tensor): the exponent value + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.4331, 1.2475, 0.6834, -0.2791]) + >>> torch.pow(a, 2) + tensor([ 0.1875, 1.5561, 0.4670, 0.0779]) + >>> exp = torch.arange(1., 5.) + + >>> a = torch.arange(1., 5.) + >>> a + tensor([ 1., 2., 3., 4.]) + >>> exp + tensor([ 1., 2., 3., 4.]) + >>> torch.pow(a, exp) + tensor([ 1., 4., 27., 256.]) + + .. function:: pow(self, exponent, *, out=None) -> Tensor + :noindex: + + :attr:`self` is a scalar ``float`` value, and :attr:`exponent` is a tensor. + The returned tensor :attr:`out` is of the same shape as :attr:`exponent` + + The operation applied is: + + .. math:: + \text{out}_i = \text{self} ^ {\text{exponent}_i} + + Args: + self (float): the scalar base value for the power operation + exponent (Tensor): the exponent tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> exp = torch.arange(1., 5.) + >>> base = 2 + >>> torch.pow(base, exp) + tensor([ 2., 4., 8., 16.]) + """ + +@overload +def pow( + self: Number | _complex, + exponent: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + pow(input, exponent, *, out=None) -> Tensor + + Takes the power of each element in :attr:`input` with :attr:`exponent` and + returns a tensor with the result. + + :attr:`exponent` can be either a single ``float`` number or a `Tensor` + with the same number of elements as :attr:`input`. + + When :attr:`exponent` is a scalar value, the operation applied is: + + .. math:: + \text{out}_i = x_i ^ \text{exponent} + + When :attr:`exponent` is a tensor, the operation applied is: + + .. math:: + \text{out}_i = x_i ^ {\text{exponent}_i} + + When :attr:`exponent` is a tensor, the shapes of :attr:`input` + and :attr:`exponent` must be :ref:`broadcastable `. + + Args: + input (Tensor): the input tensor. + exponent (float or tensor): the exponent value + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.4331, 1.2475, 0.6834, -0.2791]) + >>> torch.pow(a, 2) + tensor([ 0.1875, 1.5561, 0.4670, 0.0779]) + >>> exp = torch.arange(1., 5.) + + >>> a = torch.arange(1., 5.) + >>> a + tensor([ 1., 2., 3., 4.]) + >>> exp + tensor([ 1., 2., 3., 4.]) + >>> torch.pow(a, exp) + tensor([ 1., 4., 27., 256.]) + + .. function:: pow(self, exponent, *, out=None) -> Tensor + :noindex: + + :attr:`self` is a scalar ``float`` value, and :attr:`exponent` is a tensor. + The returned tensor :attr:`out` is of the same shape as :attr:`exponent` + + The operation applied is: + + .. math:: + \text{out}_i = \text{self} ^ {\text{exponent}_i} + + Args: + self (float): the scalar base value for the power operation + exponent (Tensor): the exponent tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> exp = torch.arange(1., 5.) + >>> base = 2 + >>> torch.pow(base, exp) + tensor([ 2., 4., 8., 16.]) + """ + +@overload +def pow( + input: Tensor, + exponent: Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + pow(input, exponent, *, out=None) -> Tensor + + Takes the power of each element in :attr:`input` with :attr:`exponent` and + returns a tensor with the result. + + :attr:`exponent` can be either a single ``float`` number or a `Tensor` + with the same number of elements as :attr:`input`. + + When :attr:`exponent` is a scalar value, the operation applied is: + + .. math:: + \text{out}_i = x_i ^ \text{exponent} + + When :attr:`exponent` is a tensor, the operation applied is: + + .. math:: + \text{out}_i = x_i ^ {\text{exponent}_i} + + When :attr:`exponent` is a tensor, the shapes of :attr:`input` + and :attr:`exponent` must be :ref:`broadcastable `. + + Args: + input (Tensor): the input tensor. + exponent (float or tensor): the exponent value + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.4331, 1.2475, 0.6834, -0.2791]) + >>> torch.pow(a, 2) + tensor([ 0.1875, 1.5561, 0.4670, 0.0779]) + >>> exp = torch.arange(1., 5.) + + >>> a = torch.arange(1., 5.) + >>> a + tensor([ 1., 2., 3., 4.]) + >>> exp + tensor([ 1., 2., 3., 4.]) + >>> torch.pow(a, exp) + tensor([ 1., 4., 27., 256.]) + + .. function:: pow(self, exponent, *, out=None) -> Tensor + :noindex: + + :attr:`self` is a scalar ``float`` value, and :attr:`exponent` is a tensor. + The returned tensor :attr:`out` is of the same shape as :attr:`exponent` + + The operation applied is: + + .. math:: + \text{out}_i = \text{self} ^ {\text{exponent}_i} + + Args: + self (float): the scalar base value for the power operation + exponent (Tensor): the exponent tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> exp = torch.arange(1., 5.) + >>> base = 2 + >>> torch.pow(base, exp) + tensor([ 2., 4., 8., 16.]) + """ + +def prelu(input: Tensor, weight: Tensor) -> Tensor: ... +@overload +def prod(input: Tensor, *, dtype: _dtype | None = None) -> Tensor: + r""" + prod(input: Tensor, *, dtype: Optional[_dtype]) -> Tensor + + Returns the product of all elements in the :attr:`input` tensor. + + Args: + input (Tensor): the input tensor. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[-0.8020, 0.5428, -1.5854]]) + >>> torch.prod(a) + tensor(0.6902) + + .. function:: prod(input, dim, keepdim=False, *, dtype=None) -> Tensor + :noindex: + + Returns the product of each row of the :attr:`input` tensor in the given + dimension :attr:`dim`. + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in + the output tensor having 1 fewer dimension than :attr:`input`. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + + Example:: + + >>> a = torch.randn(4, 2) + >>> a + tensor([[ 0.5261, -0.3837], + [ 1.1857, -0.2498], + [-1.1646, 0.0705], + [ 1.1131, -1.0629]]) + >>> torch.prod(a, 1) + tensor([-0.2018, -0.2962, -0.0821, -1.1831]) + """ + +@overload +def prod( + input: Tensor, + dim: _int, + keepdim: _bool = False, + *, + dtype: _dtype | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + prod(input: Tensor, *, dtype: Optional[_dtype]) -> Tensor + + Returns the product of all elements in the :attr:`input` tensor. + + Args: + input (Tensor): the input tensor. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[-0.8020, 0.5428, -1.5854]]) + >>> torch.prod(a) + tensor(0.6902) + + .. function:: prod(input, dim, keepdim=False, *, dtype=None) -> Tensor + :noindex: + + Returns the product of each row of the :attr:`input` tensor in the given + dimension :attr:`dim`. + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in + the output tensor having 1 fewer dimension than :attr:`input`. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + + Example:: + + >>> a = torch.randn(4, 2) + >>> a + tensor([[ 0.5261, -0.3837], + [ 1.1857, -0.2498], + [-1.1646, 0.0705], + [ 1.1131, -1.0629]]) + >>> torch.prod(a, 1) + tensor([-0.2018, -0.2962, -0.0821, -1.1831]) + """ + +@overload +def prod( + input: Tensor, + dim: str | EllipsisType | None, + keepdim: _bool = False, + *, + dtype: _dtype | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + prod(input: Tensor, *, dtype: Optional[_dtype]) -> Tensor + + Returns the product of all elements in the :attr:`input` tensor. + + Args: + input (Tensor): the input tensor. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[-0.8020, 0.5428, -1.5854]]) + >>> torch.prod(a) + tensor(0.6902) + + .. function:: prod(input, dim, keepdim=False, *, dtype=None) -> Tensor + :noindex: + + Returns the product of each row of the :attr:`input` tensor in the given + dimension :attr:`dim`. + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in + the output tensor having 1 fewer dimension than :attr:`input`. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + + Example:: + + >>> a = torch.randn(4, 2) + >>> a + tensor([[ 0.5261, -0.3837], + [ 1.1857, -0.2498], + [-1.1646, 0.0705], + [ 1.1131, -1.0629]]) + >>> torch.prod(a, 1) + tensor([-0.2018, -0.2962, -0.0821, -1.1831]) + """ + +def promote_types(type1: _dtype, type2: _dtype) -> _dtype: + r""" + promote_types(type1, type2) -> dtype + + Returns the :class:`torch.dtype` with the smallest size and scalar kind that is + not smaller nor of lower kind than either `type1` or `type2`. See type promotion + :ref:`documentation ` for more information on the type + promotion logic. + + Args: + type1 (:class:`torch.dtype`) + type2 (:class:`torch.dtype`) + + Example:: + + >>> torch.promote_types(torch.int32, torch.float32) + torch.float32 + >>> torch.promote_types(torch.uint8, torch.long) + torch.long + """ + +def put( + input: Tensor, + index: Tensor, + source: Tensor, + accumulate: _bool = False, +) -> Tensor: ... +def q_per_channel_axis(input: Tensor) -> _int: ... +def q_per_channel_scales(input: Tensor) -> Tensor: ... +def q_per_channel_zero_points(input: Tensor) -> Tensor: ... +def q_scale(input: Tensor) -> _float: ... +def q_zero_point(input: Tensor) -> _int: ... +def qr( + input: Tensor, + some: _bool = True, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.qr: + r""" + qr(input: Tensor, some: bool = True, *, out: Union[Tensor, Tuple[Tensor, ...], List[Tensor], None]) -> (Tensor, Tensor) + + Computes the QR decomposition of a matrix or a batch of matrices :attr:`input`, + and returns a namedtuple (Q, R) of tensors such that :math:`\text{input} = Q R` + with :math:`Q` being an orthogonal matrix or batch of orthogonal matrices and + :math:`R` being an upper triangular matrix or batch of upper triangular matrices. + + If :attr:`some` is ``True``, then this function returns the thin (reduced) QR factorization. + Otherwise, if :attr:`some` is ``False``, this function returns the complete QR factorization. + + .. warning:: + + :func:`torch.qr` is deprecated in favor of :func:`torch.linalg.qr` + and will be removed in a future PyTorch release. The boolean parameter :attr:`some` has been + replaced with a string parameter :attr:`mode`. + + ``Q, R = torch.qr(A)`` should be replaced with + + .. code:: python + + Q, R = torch.linalg.qr(A) + + ``Q, R = torch.qr(A, some=False)`` should be replaced with + + .. code:: python + + Q, R = torch.linalg.qr(A, mode="complete") + + .. warning:: + If you plan to backpropagate through QR, note that the current backward implementation + is only well-defined when the first :math:`\min(input.size(-1), input.size(-2))` + columns of :attr:`input` are linearly independent. + This behavior will probably change once QR supports pivoting. + + .. note:: This function uses LAPACK for CPU inputs and MAGMA for CUDA inputs, + and may produce different (valid) decompositions on different device types + or different platforms. + + Args: + input (Tensor): the input tensor of size :math:`(*, m, n)` where `*` is zero or more + batch dimensions consisting of matrices of dimension :math:`m \times n`. + some (bool, optional): Set to ``True`` for reduced QR decomposition and ``False`` for + complete QR decomposition. If `k = min(m, n)` then: + + * ``some=True`` : returns `(Q, R)` with dimensions (m, k), (k, n) (default) + + * ``'some=False'``: returns `(Q, R)` with dimensions (m, m), (m, n) + + Keyword args: + out (tuple, optional): tuple of `Q` and `R` tensors. + The dimensions of `Q` and `R` are detailed in the description of :attr:`some` above. + + Example:: + + >>> a = torch.tensor([[12., -51, 4], [6, 167, -68], [-4, 24, -41]]) + >>> q, r = torch.qr(a) + >>> q + tensor([[-0.8571, 0.3943, 0.3314], + [-0.4286, -0.9029, -0.0343], + [ 0.2857, -0.1714, 0.9429]]) + >>> r + tensor([[ -14.0000, -21.0000, 14.0000], + [ 0.0000, -175.0000, 70.0000], + [ 0.0000, 0.0000, -35.0000]]) + >>> torch.mm(q, r).round() + tensor([[ 12., -51., 4.], + [ 6., 167., -68.], + [ -4., 24., -41.]]) + >>> torch.mm(q.t(), q).round() + tensor([[ 1., 0., 0.], + [ 0., 1., -0.], + [ 0., -0., 1.]]) + >>> a = torch.randn(3, 4, 5) + >>> q, r = torch.qr(a, some=False) + >>> torch.allclose(torch.matmul(q, r), a) + True + >>> torch.allclose(torch.matmul(q.mT, q), torch.eye(5)) + True + """ + +@overload +def quantile( + input: Tensor, + q: Tensor, + dim: _int | None = None, + keepdim: _bool = False, + *, + interpolation: str = "linear", + out: Tensor | None = None, +) -> Tensor: + r""" + quantile(input, q, dim=None, keepdim=False, *, interpolation='linear', out=None) -> Tensor + + Computes the q-th quantiles of each row of the :attr:`input` tensor along the dimension :attr:`dim`. + + To compute the quantile, we map q in [0, 1] to the range of indices [0, n] to find the location + of the quantile in the sorted input. If the quantile lies between two data points ``a < b`` with + indices ``i`` and ``j`` in the sorted order, result is computed according to the given + :attr:`interpolation` method as follows: + + - ``linear``: ``a + (b - a) * fraction``, where ``fraction`` is the fractional part of the computed quantile index. + - ``lower``: ``a``. + - ``higher``: ``b``. + - ``nearest``: ``a`` or ``b``, whichever's index is closer to the computed quantile index (follows :func:`torch.round`). + - ``midpoint``: ``(a + b) / 2``. + + If :attr:`q` is a 1D tensor, the first dimension of the output represents the quantiles and has size + equal to the size of :attr:`q`, the remaining dimensions are what remains from the reduction. + + .. note:: + By default :attr:`dim` is ``None`` resulting in the :attr:`input` tensor being flattened before computation. + + Args: + input (Tensor): the input tensor. + q (float or Tensor): a scalar or 1D tensor of values in the range [0, 1]. + + dim (int, optional): the dimension to reduce. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword arguments: + interpolation (str, optional): interpolation method to use when the desired quantile lies between two data points. + Can be ``linear``, ``lower``, ``higher``, ``midpoint`` and ``nearest``. + Default is ``linear``. + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(2, 3) + >>> a + tensor([[ 0.0795, -1.2117, 0.9765], + [ 1.1707, 0.6706, 0.4884]]) + >>> q = torch.tensor([0.25, 0.5, 0.75]) + >>> torch.quantile(a, q, dim=1, keepdim=True) + tensor([[[-0.5661], + [ 0.5795]], + + [[ 0.0795], + [ 0.6706]], + + [[ 0.5280], + [ 0.9206]]]) + >>> torch.quantile(a, q, dim=1, keepdim=True).shape + torch.Size([3, 2, 1]) + >>> a = torch.arange(4.) + >>> a + tensor([0., 1., 2., 3.]) + >>> torch.quantile(a, 0.6, interpolation='linear') + tensor(1.8000) + >>> torch.quantile(a, 0.6, interpolation='lower') + tensor(1.) + >>> torch.quantile(a, 0.6, interpolation='higher') + tensor(2.) + >>> torch.quantile(a, 0.6, interpolation='midpoint') + tensor(1.5000) + >>> torch.quantile(a, 0.6, interpolation='nearest') + tensor(2.) + >>> torch.quantile(a, 0.4, interpolation='nearest') + tensor(1.) + """ + +@overload +def quantile( + input: Tensor, + q: _float, + dim: _int | None = None, + keepdim: _bool = False, + *, + interpolation: str = "linear", + out: Tensor | None = None, +) -> Tensor: + r""" + quantile(input, q, dim=None, keepdim=False, *, interpolation='linear', out=None) -> Tensor + + Computes the q-th quantiles of each row of the :attr:`input` tensor along the dimension :attr:`dim`. + + To compute the quantile, we map q in [0, 1] to the range of indices [0, n] to find the location + of the quantile in the sorted input. If the quantile lies between two data points ``a < b`` with + indices ``i`` and ``j`` in the sorted order, result is computed according to the given + :attr:`interpolation` method as follows: + + - ``linear``: ``a + (b - a) * fraction``, where ``fraction`` is the fractional part of the computed quantile index. + - ``lower``: ``a``. + - ``higher``: ``b``. + - ``nearest``: ``a`` or ``b``, whichever's index is closer to the computed quantile index (follows :func:`torch.round`). + - ``midpoint``: ``(a + b) / 2``. + + If :attr:`q` is a 1D tensor, the first dimension of the output represents the quantiles and has size + equal to the size of :attr:`q`, the remaining dimensions are what remains from the reduction. + + .. note:: + By default :attr:`dim` is ``None`` resulting in the :attr:`input` tensor being flattened before computation. + + Args: + input (Tensor): the input tensor. + q (float or Tensor): a scalar or 1D tensor of values in the range [0, 1]. + + dim (int, optional): the dimension to reduce. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword arguments: + interpolation (str, optional): interpolation method to use when the desired quantile lies between two data points. + Can be ``linear``, ``lower``, ``higher``, ``midpoint`` and ``nearest``. + Default is ``linear``. + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(2, 3) + >>> a + tensor([[ 0.0795, -1.2117, 0.9765], + [ 1.1707, 0.6706, 0.4884]]) + >>> q = torch.tensor([0.25, 0.5, 0.75]) + >>> torch.quantile(a, q, dim=1, keepdim=True) + tensor([[[-0.5661], + [ 0.5795]], + + [[ 0.0795], + [ 0.6706]], + + [[ 0.5280], + [ 0.9206]]]) + >>> torch.quantile(a, q, dim=1, keepdim=True).shape + torch.Size([3, 2, 1]) + >>> a = torch.arange(4.) + >>> a + tensor([0., 1., 2., 3.]) + >>> torch.quantile(a, 0.6, interpolation='linear') + tensor(1.8000) + >>> torch.quantile(a, 0.6, interpolation='lower') + tensor(1.) + >>> torch.quantile(a, 0.6, interpolation='higher') + tensor(2.) + >>> torch.quantile(a, 0.6, interpolation='midpoint') + tensor(1.5000) + >>> torch.quantile(a, 0.6, interpolation='nearest') + tensor(2.) + >>> torch.quantile(a, 0.4, interpolation='nearest') + tensor(1.) + """ + +def quantize_per_channel( + input: Tensor, + scales: Tensor, + zero_points: Tensor, + axis: _int, + dtype: _dtype, +) -> Tensor: + r""" + quantize_per_channel(input, scales, zero_points, axis, dtype) -> Tensor + + Converts a float tensor to a per-channel quantized tensor with given scales and zero points. + + Arguments: + input (Tensor): float tensor to quantize + scales (Tensor): float 1D tensor of scales to use, size should match ``input.size(axis)`` + zero_points (int): integer 1D tensor of offset to use, size should match ``input.size(axis)`` + axis (int): dimension on which apply per-channel quantization + dtype (:class:`torch.dtype`): the desired data type of returned tensor. + Has to be one of the quantized dtypes: ``torch.quint8``, ``torch.qint8``, ``torch.qint32`` + + Returns: + Tensor: A newly quantized tensor + + Example:: + + >>> x = torch.tensor([[-1.0, 0.0], [1.0, 2.0]]) + >>> torch.quantize_per_channel(x, torch.tensor([0.1, 0.01]), torch.tensor([10, 0]), 0, torch.quint8) + tensor([[-1., 0.], + [ 1., 2.]], size=(2, 2), dtype=torch.quint8, + quantization_scheme=torch.per_channel_affine, + scale=tensor([0.1000, 0.0100], dtype=torch.float64), + zero_point=tensor([10, 0]), axis=0) + >>> torch.quantize_per_channel(x, torch.tensor([0.1, 0.01]), torch.tensor([10, 0]), 0, torch.quint8).int_repr() + tensor([[ 0, 10], + [100, 200]], dtype=torch.uint8) + """ + +@overload +def quantize_per_tensor( + input: Tensor, + scale: Tensor, + zero_point: Tensor, + dtype: _dtype, +) -> Tensor: + r""" + quantize_per_tensor(input, scale, zero_point, dtype) -> Tensor + + Converts a float tensor to a quantized tensor with given scale and zero point. + + Arguments: + input (Tensor): float tensor or list of tensors to quantize + scale (float or Tensor): scale to apply in quantization formula + zero_point (int or Tensor): offset in integer value that maps to float zero + dtype (:class:`torch.dtype`): the desired data type of returned tensor. + Has to be one of the quantized dtypes: ``torch.quint8``, ``torch.qint8``, ``torch.qint32`` + + Returns: + Tensor: A newly quantized tensor or list of quantized tensors. + + Example:: + + >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), 0.1, 10, torch.quint8) + tensor([-1., 0., 1., 2.], size=(4,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.1, zero_point=10) + >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), 0.1, 10, torch.quint8).int_repr() + tensor([ 0, 10, 20, 30], dtype=torch.uint8) + >>> torch.quantize_per_tensor([torch.tensor([-1.0, 0.0]), torch.tensor([-2.0, 2.0])], + >>> torch.tensor([0.1, 0.2]), torch.tensor([10, 20]), torch.quint8) + (tensor([-1., 0.], size=(2,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.1, zero_point=10), + tensor([-2., 2.], size=(2,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.2, zero_point=20)) + >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), torch.tensor(0.1), torch.tensor(10), torch.quint8) + tensor([-1., 0., 1., 2.], size=(4,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.10, zero_point=10) + """ + +@overload +def quantize_per_tensor( + input: Tensor, + scale: _float, + zero_point: _int, + dtype: _dtype, +) -> Tensor: + r""" + quantize_per_tensor(input, scale, zero_point, dtype) -> Tensor + + Converts a float tensor to a quantized tensor with given scale and zero point. + + Arguments: + input (Tensor): float tensor or list of tensors to quantize + scale (float or Tensor): scale to apply in quantization formula + zero_point (int or Tensor): offset in integer value that maps to float zero + dtype (:class:`torch.dtype`): the desired data type of returned tensor. + Has to be one of the quantized dtypes: ``torch.quint8``, ``torch.qint8``, ``torch.qint32`` + + Returns: + Tensor: A newly quantized tensor or list of quantized tensors. + + Example:: + + >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), 0.1, 10, torch.quint8) + tensor([-1., 0., 1., 2.], size=(4,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.1, zero_point=10) + >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), 0.1, 10, torch.quint8).int_repr() + tensor([ 0, 10, 20, 30], dtype=torch.uint8) + >>> torch.quantize_per_tensor([torch.tensor([-1.0, 0.0]), torch.tensor([-2.0, 2.0])], + >>> torch.tensor([0.1, 0.2]), torch.tensor([10, 20]), torch.quint8) + (tensor([-1., 0.], size=(2,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.1, zero_point=10), + tensor([-2., 2.], size=(2,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.2, zero_point=20)) + >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), torch.tensor(0.1), torch.tensor(10), torch.quint8) + tensor([-1., 0., 1., 2.], size=(4,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.10, zero_point=10) + """ + +@overload +def quantize_per_tensor( + tensors: tuple[Tensor, ...] | list[Tensor] | None, + scales: Tensor, + zero_points: Tensor, + dtype: _dtype, +) -> tuple[Tensor, ...]: + r""" + quantize_per_tensor(input, scale, zero_point, dtype) -> Tensor + + Converts a float tensor to a quantized tensor with given scale and zero point. + + Arguments: + input (Tensor): float tensor or list of tensors to quantize + scale (float or Tensor): scale to apply in quantization formula + zero_point (int or Tensor): offset in integer value that maps to float zero + dtype (:class:`torch.dtype`): the desired data type of returned tensor. + Has to be one of the quantized dtypes: ``torch.quint8``, ``torch.qint8``, ``torch.qint32`` + + Returns: + Tensor: A newly quantized tensor or list of quantized tensors. + + Example:: + + >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), 0.1, 10, torch.quint8) + tensor([-1., 0., 1., 2.], size=(4,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.1, zero_point=10) + >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), 0.1, 10, torch.quint8).int_repr() + tensor([ 0, 10, 20, 30], dtype=torch.uint8) + >>> torch.quantize_per_tensor([torch.tensor([-1.0, 0.0]), torch.tensor([-2.0, 2.0])], + >>> torch.tensor([0.1, 0.2]), torch.tensor([10, 20]), torch.quint8) + (tensor([-1., 0.], size=(2,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.1, zero_point=10), + tensor([-2., 2.], size=(2,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.2, zero_point=20)) + >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), torch.tensor(0.1), torch.tensor(10), torch.quint8) + tensor([-1., 0., 1., 2.], size=(4,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.10, zero_point=10) + """ + +def quantize_per_tensor_dynamic( + input: Tensor, + dtype: _dtype, + reduce_range: _bool, +) -> Tensor: + r""" + quantize_per_tensor_dynamic(input, dtype, reduce_range) -> Tensor + + Converts a float tensor to a quantized tensor with scale and zero_point calculated + dynamically based on the input. + + Arguments: + input (Tensor): float tensor or list of tensors to quantize + dtype (:class:`torch.dtype`): the desired data type of returned tensor. + Has to be one of the quantized dtypes: ``torch.quint8``, ``torch.qint8`` + reduce_range (bool): a flag to indicate whether to reduce the range of quantized + data by 1 bit, it's required to avoid instruction overflow for some hardwares + + Returns: + Tensor: A newly (dynamically) quantized tensor + + Example:: + + >>> t = torch.quantize_per_tensor_dynamic(torch.tensor([-1.0, 0.0, 1.0, 2.0]), torch.quint8, False) + >>> print(t) + tensor([-1., 0., 1., 2.], size=(4,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.011764705882352941, + zero_point=85) + >>> t.int_repr() + tensor([ 0, 85, 170, 255], dtype=torch.uint8) + """ + +def quantized_batch_norm( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + mean: Tensor, + var: Tensor, + eps: _float, + output_scale: _float, + output_zero_point: _int, +) -> Tensor: + r""" + quantized_batch_norm(input, weight=None, bias=None, mean, var, eps, output_scale, output_zero_point) -> Tensor + + Applies batch normalization on a 4D (NCHW) quantized tensor. + + .. math:: + + y = \frac{x - \mathrm{E}[x]}{\sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta + + Arguments: + input (Tensor): quantized tensor + weight (Tensor): float tensor that corresponds to the gamma, size C + bias (Tensor): float tensor that corresponds to the beta, size C + mean (Tensor): float mean value in batch normalization, size C + var (Tensor): float tensor for variance, size C + eps (float): a value added to the denominator for numerical stability. + output_scale (float): output quantized tensor scale + output_zero_point (int): output quantized tensor zero_point + + Returns: + Tensor: A quantized tensor with batch normalization applied. + + Example:: + + >>> qx = torch.quantize_per_tensor(torch.rand(2, 2, 2, 2), 1.5, 3, torch.quint8) + >>> torch.quantized_batch_norm(qx, torch.ones(2), torch.zeros(2), torch.rand(2), torch.rand(2), 0.00001, 0.2, 2) + tensor([[[[-0.2000, -0.2000], + [ 1.6000, -0.2000]], + + [[-0.4000, -0.4000], + [-0.4000, 0.6000]]], + + + [[[-0.2000, -0.2000], + [-0.2000, -0.2000]], + + [[ 0.6000, -0.4000], + [ 0.6000, -0.4000]]]], size=(2, 2, 2, 2), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.2, zero_point=2) + """ + +def quantized_gru_cell( + input: Tensor, + hx: Tensor, + w_ih: Tensor, + w_hh: Tensor, + b_ih: Tensor, + b_hh: Tensor, + packed_ih: Tensor, + packed_hh: Tensor, + col_offsets_ih: Tensor, + col_offsets_hh: Tensor, + scale_ih: Number | _complex, + scale_hh: Number | _complex, + zero_point_ih: Number | _complex, + zero_point_hh: Number | _complex, +) -> Tensor: ... +def quantized_lstm_cell( + input: Tensor, + hx: tuple[Tensor, ...] | list[Tensor] | None, + w_ih: Tensor, + w_hh: Tensor, + b_ih: Tensor, + b_hh: Tensor, + packed_ih: Tensor, + packed_hh: Tensor, + col_offsets_ih: Tensor, + col_offsets_hh: Tensor, + scale_ih: Number | _complex, + scale_hh: Number | _complex, + zero_point_ih: Number | _complex, + zero_point_hh: Number | _complex, +) -> tuple[Tensor, Tensor]: ... +def quantized_max_pool1d( + input: Tensor, + kernel_size: _int | _size, + stride: _int | _size = (), + padding: _int | _size = 0, + dilation: _int | _size = 1, + ceil_mode: _bool = False, +) -> Tensor: + r""" + quantized_max_pool1d(input, kernel_size, stride=[], padding=0, dilation=1, ceil_mode=False) -> Tensor + + Applies a 1D max pooling over an input quantized tensor composed of several input planes. + + Arguments: + input (Tensor): quantized tensor + kernel_size (list of int): the size of the sliding window + stride (``list of int``, optional): the stride of the sliding window + padding (``list of int``, optional): padding to be added on both sides, must be >= 0 and <= kernel_size / 2 + dilation (``list of int``, optional): The stride between elements within a sliding window, must be > 0. Default 1 + ceil_mode (bool, optional): If True, will use ceil instead of floor to compute the output shape. + Defaults to False. + + + Returns: + Tensor: A quantized tensor with max_pool1d applied. + + Example:: + + >>> qx = torch.quantize_per_tensor(torch.rand(2, 2), 1.5, 3, torch.quint8) + >>> torch.quantized_max_pool1d(qx, [2]) + tensor([[0.0000], + [1.5000]], size=(2, 1), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=1.5, zero_point=3) + """ + +def quantized_max_pool2d( + input: Tensor, + kernel_size: _int | _size, + stride: _int | _size = (), + padding: _int | _size = 0, + dilation: _int | _size = 1, + ceil_mode: _bool = False, +) -> Tensor: + r""" + quantized_max_pool2d(input, kernel_size, stride=[], padding=0, dilation=1, ceil_mode=False) -> Tensor + + Applies a 2D max pooling over an input quantized tensor composed of several input planes. + + Arguments: + input (Tensor): quantized tensor + kernel_size (``list of int``): the size of the sliding window + stride (``list of int``, optional): the stride of the sliding window + padding (``list of int``, optional): padding to be added on both sides, must be >= 0 and <= kernel_size / 2 + dilation (``list of int``, optional): The stride between elements within a sliding window, must be > 0. Default 1 + ceil_mode (bool, optional): If True, will use ceil instead of floor to compute the output shape. + Defaults to False. + + + Returns: + Tensor: A quantized tensor with max_pool2d applied. + + Example:: + + >>> qx = torch.quantize_per_tensor(torch.rand(2, 2, 2, 2), 1.5, 3, torch.quint8) + >>> torch.quantized_max_pool2d(qx, [2,2]) + tensor([[[[1.5000]], + + [[1.5000]]], + + + [[[0.0000]], + + [[0.0000]]]], size=(2, 2, 1, 1), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=1.5, zero_point=3) + """ + +def quantized_max_pool3d( + input: Tensor, + kernel_size: _int | _size, + stride: _int | _size = (), + padding: _int | _size = 0, + dilation: _int | _size = 1, + ceil_mode: _bool = False, +) -> Tensor: ... +def quantized_rnn_relu_cell( + input: Tensor, + hx: Tensor, + w_ih: Tensor, + w_hh: Tensor, + b_ih: Tensor, + b_hh: Tensor, + packed_ih: Tensor, + packed_hh: Tensor, + col_offsets_ih: Tensor, + col_offsets_hh: Tensor, + scale_ih: Number | _complex, + scale_hh: Number | _complex, + zero_point_ih: Number | _complex, + zero_point_hh: Number | _complex, +) -> Tensor: ... +def quantized_rnn_tanh_cell( + input: Tensor, + hx: Tensor, + w_ih: Tensor, + w_hh: Tensor, + b_ih: Tensor, + b_hh: Tensor, + packed_ih: Tensor, + packed_hh: Tensor, + col_offsets_ih: Tensor, + col_offsets_hh: Tensor, + scale_ih: Number | _complex, + scale_hh: Number | _complex, + zero_point_ih: Number | _complex, + zero_point_hh: Number | _complex, +) -> Tensor: ... +def rad2deg(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + rad2deg(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Returns a new tensor with each of the elements of :attr:`input` + converted from angles in radians to degrees. + + Args: + input (Tensor): the input tensor. + + Keyword arguments: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([[3.142, -3.142], [6.283, -6.283], [1.570, -1.570]]) + >>> torch.rad2deg(a) + tensor([[ 180.0233, -180.0233], + [ 359.9894, -359.9894], + [ 89.9544, -89.9544]]) + """ + +def rad2deg_(input: Tensor) -> Tensor: ... +@overload +def rand( + size: Sequence[_int | SymInt], + *, + generator: Generator | None, + names: Sequence[str | EllipsisType | None] | None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + rand(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + Returns a tensor filled with random numbers from a uniform distribution + on the interval :math:`[0, 1)` + + The shape of the tensor is defined by the variable argument :attr:`size`. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.rand(4) + tensor([ 0.5204, 0.2503, 0.3525, 0.5673]) + >>> torch.rand(2, 3) + tensor([[ 0.8237, 0.5781, 0.6879], + [ 0.3816, 0.7249, 0.0998]]) + """ + +@overload +def rand( + *size: _int | SymInt, + generator: Generator | None, + names: Sequence[str | EllipsisType | None] | None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + rand(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + Returns a tensor filled with random numbers from a uniform distribution + on the interval :math:`[0, 1)` + + The shape of the tensor is defined by the variable argument :attr:`size`. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.rand(4) + tensor([ 0.5204, 0.2503, 0.3525, 0.5673]) + >>> torch.rand(2, 3) + tensor([[ 0.8237, 0.5781, 0.6879], + [ 0.3816, 0.7249, 0.0998]]) + """ + +@overload +def rand( + size: Sequence[_int | SymInt], + *, + generator: Generator | None, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + rand(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + Returns a tensor filled with random numbers from a uniform distribution + on the interval :math:`[0, 1)` + + The shape of the tensor is defined by the variable argument :attr:`size`. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.rand(4) + tensor([ 0.5204, 0.2503, 0.3525, 0.5673]) + >>> torch.rand(2, 3) + tensor([[ 0.8237, 0.5781, 0.6879], + [ 0.3816, 0.7249, 0.0998]]) + """ + +@overload +def rand( + *size: _int | SymInt, + generator: Generator | None, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + rand(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + Returns a tensor filled with random numbers from a uniform distribution + on the interval :math:`[0, 1)` + + The shape of the tensor is defined by the variable argument :attr:`size`. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.rand(4) + tensor([ 0.5204, 0.2503, 0.3525, 0.5673]) + >>> torch.rand(2, 3) + tensor([[ 0.8237, 0.5781, 0.6879], + [ 0.3816, 0.7249, 0.0998]]) + """ + +@overload +def rand( + size: Sequence[_int | SymInt], + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + rand(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + Returns a tensor filled with random numbers from a uniform distribution + on the interval :math:`[0, 1)` + + The shape of the tensor is defined by the variable argument :attr:`size`. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.rand(4) + tensor([ 0.5204, 0.2503, 0.3525, 0.5673]) + >>> torch.rand(2, 3) + tensor([[ 0.8237, 0.5781, 0.6879], + [ 0.3816, 0.7249, 0.0998]]) + """ + +@overload +def rand( + *size: _int | SymInt, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + rand(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + Returns a tensor filled with random numbers from a uniform distribution + on the interval :math:`[0, 1)` + + The shape of the tensor is defined by the variable argument :attr:`size`. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.rand(4) + tensor([ 0.5204, 0.2503, 0.3525, 0.5673]) + >>> torch.rand(2, 3) + tensor([[ 0.8237, 0.5781, 0.6879], + [ 0.3816, 0.7249, 0.0998]]) + """ + +@overload +def rand( + size: Sequence[_int | SymInt], + *, + names: Sequence[str | EllipsisType | None] | None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + rand(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + Returns a tensor filled with random numbers from a uniform distribution + on the interval :math:`[0, 1)` + + The shape of the tensor is defined by the variable argument :attr:`size`. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.rand(4) + tensor([ 0.5204, 0.2503, 0.3525, 0.5673]) + >>> torch.rand(2, 3) + tensor([[ 0.8237, 0.5781, 0.6879], + [ 0.3816, 0.7249, 0.0998]]) + """ + +@overload +def rand( + *size: _int | SymInt, + names: Sequence[str | EllipsisType | None] | None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + rand(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + Returns a tensor filled with random numbers from a uniform distribution + on the interval :math:`[0, 1)` + + The shape of the tensor is defined by the variable argument :attr:`size`. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.rand(4) + tensor([ 0.5204, 0.2503, 0.3525, 0.5673]) + >>> torch.rand(2, 3) + tensor([[ 0.8237, 0.5781, 0.6879], + [ 0.3816, 0.7249, 0.0998]]) + """ + +@overload +def rand_like( + input: Tensor, + *, + generator: Generator | None, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + rand_like(input, *, generator=None, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same size as :attr:`input` that is filled with + random numbers from a uniform distribution on the interval :math:`[0, 1)`. + ``torch.rand_like(input)`` is equivalent to + ``torch.rand(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def rand_like( + input: Tensor, + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + rand_like(input, *, generator=None, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same size as :attr:`input` that is filled with + random numbers from a uniform distribution on the interval :math:`[0, 1)`. + ``torch.rand_like(input)`` is equivalent to + ``torch.rand(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def randint( + low: _int, + high: _int, + size: _size, + *, + generator: Generator | None = None, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + pin_memory: _bool = False, +) -> Tensor: + r""" + randint(low=0, high, size, \*, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with random integers generated uniformly + between :attr:`low` (inclusive) and :attr:`high` (exclusive). + + The shape of the tensor is defined by the variable argument :attr:`size`. + + .. note:: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + size (tuple): a tuple defining the shape of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the desired data type of returned tensor. Default: if ``None``, + this function returns a tensor with dtype ``torch.int64``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.randint(3, 5, (3,)) + tensor([4, 3, 4]) + + + >>> torch.randint(10, (2, 2)) + tensor([[0, 2], + [5, 5]]) + + + >>> torch.randint(3, 10, (2, 2)) + tensor([[4, 5], + [6, 7]]) + """ + +@overload +def randint( + high: _int, + size: _size, + *, + generator: Generator | None = None, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + pin_memory: _bool = False, +) -> Tensor: + r""" + randint(low=0, high, size, \*, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with random integers generated uniformly + between :attr:`low` (inclusive) and :attr:`high` (exclusive). + + The shape of the tensor is defined by the variable argument :attr:`size`. + + .. note:: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + size (tuple): a tuple defining the shape of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the desired data type of returned tensor. Default: if ``None``, + this function returns a tensor with dtype ``torch.int64``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.randint(3, 5, (3,)) + tensor([4, 3, 4]) + + + >>> torch.randint(10, (2, 2)) + tensor([[0, 2], + [5, 5]]) + + + >>> torch.randint(3, 10, (2, 2)) + tensor([[4, 5], + [6, 7]]) + """ + +@overload +def randint( + high: _int | SymInt, + size: Sequence[_int | SymInt], + *, + generator: Generator | None, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint(low=0, high, size, \*, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with random integers generated uniformly + between :attr:`low` (inclusive) and :attr:`high` (exclusive). + + The shape of the tensor is defined by the variable argument :attr:`size`. + + .. note:: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + size (tuple): a tuple defining the shape of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the desired data type of returned tensor. Default: if ``None``, + this function returns a tensor with dtype ``torch.int64``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.randint(3, 5, (3,)) + tensor([4, 3, 4]) + + + >>> torch.randint(10, (2, 2)) + tensor([[0, 2], + [5, 5]]) + + + >>> torch.randint(3, 10, (2, 2)) + tensor([[4, 5], + [6, 7]]) + """ + +@overload +def randint( + high: _int | SymInt, + size: Sequence[_int | SymInt], + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint(low=0, high, size, \*, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with random integers generated uniformly + between :attr:`low` (inclusive) and :attr:`high` (exclusive). + + The shape of the tensor is defined by the variable argument :attr:`size`. + + .. note:: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + size (tuple): a tuple defining the shape of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the desired data type of returned tensor. Default: if ``None``, + this function returns a tensor with dtype ``torch.int64``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.randint(3, 5, (3,)) + tensor([4, 3, 4]) + + + >>> torch.randint(10, (2, 2)) + tensor([[0, 2], + [5, 5]]) + + + >>> torch.randint(3, 10, (2, 2)) + tensor([[4, 5], + [6, 7]]) + """ + +@overload +def randint( + low: _int | SymInt, + high: _int | SymInt, + size: Sequence[_int | SymInt], + *, + generator: Generator | None, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint(low=0, high, size, \*, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with random integers generated uniformly + between :attr:`low` (inclusive) and :attr:`high` (exclusive). + + The shape of the tensor is defined by the variable argument :attr:`size`. + + .. note:: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + size (tuple): a tuple defining the shape of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the desired data type of returned tensor. Default: if ``None``, + this function returns a tensor with dtype ``torch.int64``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.randint(3, 5, (3,)) + tensor([4, 3, 4]) + + + >>> torch.randint(10, (2, 2)) + tensor([[0, 2], + [5, 5]]) + + + >>> torch.randint(3, 10, (2, 2)) + tensor([[4, 5], + [6, 7]]) + """ + +@overload +def randint( + low: _int | SymInt, + high: _int | SymInt, + size: Sequence[_int | SymInt], + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint(low=0, high, size, \*, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with random integers generated uniformly + between :attr:`low` (inclusive) and :attr:`high` (exclusive). + + The shape of the tensor is defined by the variable argument :attr:`size`. + + .. note:: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + size (tuple): a tuple defining the shape of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the desired data type of returned tensor. Default: if ``None``, + this function returns a tensor with dtype ``torch.int64``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.randint(3, 5, (3,)) + tensor([4, 3, 4]) + + + >>> torch.randint(10, (2, 2)) + tensor([[0, 2], + [5, 5]]) + + + >>> torch.randint(3, 10, (2, 2)) + tensor([[4, 5], + [6, 7]]) + """ + +@overload +def randint_like( + input: Tensor, + low: _int | SymInt, + high: _int | SymInt, + *, + generator: Generator | None, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint_like(input, low=0, high, \*, generator=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same shape as Tensor :attr:`input` filled with + random integers generated uniformly between :attr:`low` (inclusive) and + :attr:`high` (exclusive). + + .. note: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def randint_like( + input: Tensor, + low: _int | SymInt, + high: _int | SymInt, + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint_like(input, low=0, high, \*, generator=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same shape as Tensor :attr:`input` filled with + random integers generated uniformly between :attr:`low` (inclusive) and + :attr:`high` (exclusive). + + .. note: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def randint_like( + input: Tensor, + high: Tensor, + *, + generator: Generator | None, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint_like(input, low=0, high, \*, generator=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same shape as Tensor :attr:`input` filled with + random integers generated uniformly between :attr:`low` (inclusive) and + :attr:`high` (exclusive). + + .. note: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def randint_like( + input: Tensor, + high: Tensor, + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint_like(input, low=0, high, \*, generator=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same shape as Tensor :attr:`input` filled with + random integers generated uniformly between :attr:`low` (inclusive) and + :attr:`high` (exclusive). + + .. note: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def randint_like( + input: Tensor, + high: _int | SymInt, + *, + generator: Generator | None, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint_like(input, low=0, high, \*, generator=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same shape as Tensor :attr:`input` filled with + random integers generated uniformly between :attr:`low` (inclusive) and + :attr:`high` (exclusive). + + .. note: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def randint_like( + input: Tensor, + high: _int | SymInt, + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint_like(input, low=0, high, \*, generator=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same shape as Tensor :attr:`input` filled with + random integers generated uniformly between :attr:`low` (inclusive) and + :attr:`high` (exclusive). + + .. note: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def randn( + size: Sequence[_int | SymInt], + *, + generator: Generator | None, + names: Sequence[str | EllipsisType | None] | None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randn(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + + Returns a tensor filled with random numbers from a normal distribution + with mean `0` and variance `1` (also called the standard normal + distribution). + + .. math:: + \text{out}_{i} \sim \mathcal{N}(0, 1) + + For complex dtypes, the tensor is i.i.d. sampled from a `complex normal distribution`_ with zero mean and + unit variance as + + .. math:: + \text{out}_{i} \sim \mathcal{CN}(0, 1) + + This is equivalent to separately sampling the real :math:`(\operatorname{Re})` and imaginary + :math:`(\operatorname{Im})` part of :math:`\text{out}_i` as + + .. math:: + \operatorname{Re}(\text{out}_{i}) \sim \mathcal{N}(0, \frac{1}{2}),\quad + \operatorname{Im}(\text{out}_{i}) \sim \mathcal{N}(0, \frac{1}{2}) + + The shape of the tensor is defined by the variable argument :attr:`size`. + + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.randn(4) + tensor([-2.1436, 0.9966, 2.3426, -0.6366]) + >>> torch.randn(2, 3) + tensor([[ 1.5954, 2.8929, -1.0923], + [ 1.1719, -0.4709, -0.1996]]) + + .. _complex normal distribution: https://en.wikipedia.org/wiki/Complex_normal_distribution + """ + +@overload +def randn( + *size: _int | SymInt, + generator: Generator | None, + names: Sequence[str | EllipsisType | None] | None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randn(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + + Returns a tensor filled with random numbers from a normal distribution + with mean `0` and variance `1` (also called the standard normal + distribution). + + .. math:: + \text{out}_{i} \sim \mathcal{N}(0, 1) + + For complex dtypes, the tensor is i.i.d. sampled from a `complex normal distribution`_ with zero mean and + unit variance as + + .. math:: + \text{out}_{i} \sim \mathcal{CN}(0, 1) + + This is equivalent to separately sampling the real :math:`(\operatorname{Re})` and imaginary + :math:`(\operatorname{Im})` part of :math:`\text{out}_i` as + + .. math:: + \operatorname{Re}(\text{out}_{i}) \sim \mathcal{N}(0, \frac{1}{2}),\quad + \operatorname{Im}(\text{out}_{i}) \sim \mathcal{N}(0, \frac{1}{2}) + + The shape of the tensor is defined by the variable argument :attr:`size`. + + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.randn(4) + tensor([-2.1436, 0.9966, 2.3426, -0.6366]) + >>> torch.randn(2, 3) + tensor([[ 1.5954, 2.8929, -1.0923], + [ 1.1719, -0.4709, -0.1996]]) + + .. _complex normal distribution: https://en.wikipedia.org/wiki/Complex_normal_distribution + """ + +@overload +def randn( + size: Sequence[_int | SymInt], + *, + generator: Generator | None, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randn(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + + Returns a tensor filled with random numbers from a normal distribution + with mean `0` and variance `1` (also called the standard normal + distribution). + + .. math:: + \text{out}_{i} \sim \mathcal{N}(0, 1) + + For complex dtypes, the tensor is i.i.d. sampled from a `complex normal distribution`_ with zero mean and + unit variance as + + .. math:: + \text{out}_{i} \sim \mathcal{CN}(0, 1) + + This is equivalent to separately sampling the real :math:`(\operatorname{Re})` and imaginary + :math:`(\operatorname{Im})` part of :math:`\text{out}_i` as + + .. math:: + \operatorname{Re}(\text{out}_{i}) \sim \mathcal{N}(0, \frac{1}{2}),\quad + \operatorname{Im}(\text{out}_{i}) \sim \mathcal{N}(0, \frac{1}{2}) + + The shape of the tensor is defined by the variable argument :attr:`size`. + + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.randn(4) + tensor([-2.1436, 0.9966, 2.3426, -0.6366]) + >>> torch.randn(2, 3) + tensor([[ 1.5954, 2.8929, -1.0923], + [ 1.1719, -0.4709, -0.1996]]) + + .. _complex normal distribution: https://en.wikipedia.org/wiki/Complex_normal_distribution + """ + +@overload +def randn( + *size: _int | SymInt, + generator: Generator | None, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randn(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + + Returns a tensor filled with random numbers from a normal distribution + with mean `0` and variance `1` (also called the standard normal + distribution). + + .. math:: + \text{out}_{i} \sim \mathcal{N}(0, 1) + + For complex dtypes, the tensor is i.i.d. sampled from a `complex normal distribution`_ with zero mean and + unit variance as + + .. math:: + \text{out}_{i} \sim \mathcal{CN}(0, 1) + + This is equivalent to separately sampling the real :math:`(\operatorname{Re})` and imaginary + :math:`(\operatorname{Im})` part of :math:`\text{out}_i` as + + .. math:: + \operatorname{Re}(\text{out}_{i}) \sim \mathcal{N}(0, \frac{1}{2}),\quad + \operatorname{Im}(\text{out}_{i}) \sim \mathcal{N}(0, \frac{1}{2}) + + The shape of the tensor is defined by the variable argument :attr:`size`. + + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.randn(4) + tensor([-2.1436, 0.9966, 2.3426, -0.6366]) + >>> torch.randn(2, 3) + tensor([[ 1.5954, 2.8929, -1.0923], + [ 1.1719, -0.4709, -0.1996]]) + + .. _complex normal distribution: https://en.wikipedia.org/wiki/Complex_normal_distribution + """ + +@overload +def randn( + size: Sequence[_int | SymInt], + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randn(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + + Returns a tensor filled with random numbers from a normal distribution + with mean `0` and variance `1` (also called the standard normal + distribution). + + .. math:: + \text{out}_{i} \sim \mathcal{N}(0, 1) + + For complex dtypes, the tensor is i.i.d. sampled from a `complex normal distribution`_ with zero mean and + unit variance as + + .. math:: + \text{out}_{i} \sim \mathcal{CN}(0, 1) + + This is equivalent to separately sampling the real :math:`(\operatorname{Re})` and imaginary + :math:`(\operatorname{Im})` part of :math:`\text{out}_i` as + + .. math:: + \operatorname{Re}(\text{out}_{i}) \sim \mathcal{N}(0, \frac{1}{2}),\quad + \operatorname{Im}(\text{out}_{i}) \sim \mathcal{N}(0, \frac{1}{2}) + + The shape of the tensor is defined by the variable argument :attr:`size`. + + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.randn(4) + tensor([-2.1436, 0.9966, 2.3426, -0.6366]) + >>> torch.randn(2, 3) + tensor([[ 1.5954, 2.8929, -1.0923], + [ 1.1719, -0.4709, -0.1996]]) + + .. _complex normal distribution: https://en.wikipedia.org/wiki/Complex_normal_distribution + """ + +@overload +def randn( + *size: _int | SymInt, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randn(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + + Returns a tensor filled with random numbers from a normal distribution + with mean `0` and variance `1` (also called the standard normal + distribution). + + .. math:: + \text{out}_{i} \sim \mathcal{N}(0, 1) + + For complex dtypes, the tensor is i.i.d. sampled from a `complex normal distribution`_ with zero mean and + unit variance as + + .. math:: + \text{out}_{i} \sim \mathcal{CN}(0, 1) + + This is equivalent to separately sampling the real :math:`(\operatorname{Re})` and imaginary + :math:`(\operatorname{Im})` part of :math:`\text{out}_i` as + + .. math:: + \operatorname{Re}(\text{out}_{i}) \sim \mathcal{N}(0, \frac{1}{2}),\quad + \operatorname{Im}(\text{out}_{i}) \sim \mathcal{N}(0, \frac{1}{2}) + + The shape of the tensor is defined by the variable argument :attr:`size`. + + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.randn(4) + tensor([-2.1436, 0.9966, 2.3426, -0.6366]) + >>> torch.randn(2, 3) + tensor([[ 1.5954, 2.8929, -1.0923], + [ 1.1719, -0.4709, -0.1996]]) + + .. _complex normal distribution: https://en.wikipedia.org/wiki/Complex_normal_distribution + """ + +@overload +def randn( + size: Sequence[_int | SymInt], + *, + names: Sequence[str | EllipsisType | None] | None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randn(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + + Returns a tensor filled with random numbers from a normal distribution + with mean `0` and variance `1` (also called the standard normal + distribution). + + .. math:: + \text{out}_{i} \sim \mathcal{N}(0, 1) + + For complex dtypes, the tensor is i.i.d. sampled from a `complex normal distribution`_ with zero mean and + unit variance as + + .. math:: + \text{out}_{i} \sim \mathcal{CN}(0, 1) + + This is equivalent to separately sampling the real :math:`(\operatorname{Re})` and imaginary + :math:`(\operatorname{Im})` part of :math:`\text{out}_i` as + + .. math:: + \operatorname{Re}(\text{out}_{i}) \sim \mathcal{N}(0, \frac{1}{2}),\quad + \operatorname{Im}(\text{out}_{i}) \sim \mathcal{N}(0, \frac{1}{2}) + + The shape of the tensor is defined by the variable argument :attr:`size`. + + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.randn(4) + tensor([-2.1436, 0.9966, 2.3426, -0.6366]) + >>> torch.randn(2, 3) + tensor([[ 1.5954, 2.8929, -1.0923], + [ 1.1719, -0.4709, -0.1996]]) + + .. _complex normal distribution: https://en.wikipedia.org/wiki/Complex_normal_distribution + """ + +@overload +def randn( + *size: _int | SymInt, + names: Sequence[str | EllipsisType | None] | None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randn(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + + Returns a tensor filled with random numbers from a normal distribution + with mean `0` and variance `1` (also called the standard normal + distribution). + + .. math:: + \text{out}_{i} \sim \mathcal{N}(0, 1) + + For complex dtypes, the tensor is i.i.d. sampled from a `complex normal distribution`_ with zero mean and + unit variance as + + .. math:: + \text{out}_{i} \sim \mathcal{CN}(0, 1) + + This is equivalent to separately sampling the real :math:`(\operatorname{Re})` and imaginary + :math:`(\operatorname{Im})` part of :math:`\text{out}_i` as + + .. math:: + \operatorname{Re}(\text{out}_{i}) \sim \mathcal{N}(0, \frac{1}{2}),\quad + \operatorname{Im}(\text{out}_{i}) \sim \mathcal{N}(0, \frac{1}{2}) + + The shape of the tensor is defined by the variable argument :attr:`size`. + + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.randn(4) + tensor([-2.1436, 0.9966, 2.3426, -0.6366]) + >>> torch.randn(2, 3) + tensor([[ 1.5954, 2.8929, -1.0923], + [ 1.1719, -0.4709, -0.1996]]) + + .. _complex normal distribution: https://en.wikipedia.org/wiki/Complex_normal_distribution + """ + +@overload +def randn_like( + input: Tensor, + *, + generator: Generator | None, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randn_like(input, *, generator=None, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same size as :attr:`input` that is filled with + random numbers from a normal distribution with mean 0 and variance 1. Please refer to :func:`torch.randn` for the + sampling process of complex dtypes. ``torch.randn_like(input)`` is equivalent to + ``torch.randn(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def randn_like( + input: Tensor, + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randn_like(input, *, generator=None, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same size as :attr:`input` that is filled with + random numbers from a normal distribution with mean 0 and variance 1. Please refer to :func:`torch.randn` for the + sampling process of complex dtypes. ``torch.randn_like(input)`` is equivalent to + ``torch.randn(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def randperm( + n: _int | SymInt, + *, + generator: Generator | None, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randperm(n, *, generator=None, out=None, dtype=torch.int64,layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + Returns a random permutation of integers from ``0`` to ``n - 1``. + + Args: + n (int): the upper bound (exclusive) + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: ``torch.int64``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.randperm(4) + tensor([2, 1, 0, 3]) + """ + +@overload +def randperm( + n: _int | SymInt, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randperm(n, *, generator=None, out=None, dtype=torch.int64,layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + Returns a random permutation of integers from ``0`` to ``n - 1``. + + Args: + n (int): the upper bound (exclusive) + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: ``torch.int64``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.randperm(4) + tensor([2, 1, 0, 3]) + """ + +def range( + start: Number, + end: Number, + step: Number = 1, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + pin_memory: _bool = False, +) -> Tensor: + r""" + range(start=0, end, step=1, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a 1-D tensor of size :math:`\left\lfloor \frac{\text{end} - \text{start}}{\text{step}} \right\rfloor + 1` + with values from :attr:`start` to :attr:`end` with step :attr:`step`. Step is + the gap between two values in the tensor. + + .. math:: + \text{out}_{i+1} = \text{out}_i + \text{step}. + + .. warning:: + This function is deprecated and will be removed in a future release because its behavior is inconsistent with + Python's range builtin. Instead, use :func:`torch.arange`, which produces values in [start, end). + + Args: + start (float, optional): the starting value for the set of points. Default: ``0``. + end (float): the ending value for the set of points + step (float, optional): the gap between each pair of adjacent points. Default: ``1``. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). If `dtype` is not given, infer the data type from the other input + arguments. If any of `start`, `end`, or `step` are floating-point, the + `dtype` is inferred to be the default dtype, see + :meth:`~torch.get_default_dtype`. Otherwise, the `dtype` is inferred to + be `torch.int64`. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.range(1, 4) + tensor([ 1., 2., 3., 4.]) + >>> torch.range(1, 4, 0.5) + tensor([ 1.0000, 1.5000, 2.0000, 2.5000, 3.0000, 3.5000, 4.0000]) + """ + +def ravel(input: Tensor) -> Tensor: + r""" + ravel(input) -> Tensor + + Return a contiguous flattened tensor. A copy is made only if needed. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> t = torch.tensor([[[1, 2], + ... [3, 4]], + ... [[5, 6], + ... [7, 8]]]) + >>> torch.ravel(t) + tensor([1, 2, 3, 4, 5, 6, 7, 8]) + """ + +def real(input: Tensor) -> Tensor: + r""" + real(input) -> Tensor + + Returns a new tensor containing real values of the :attr:`self` tensor. + The returned tensor and :attr:`self` share the same underlying storage. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> x=torch.randn(4, dtype=torch.cfloat) + >>> x + tensor([(0.3100+0.3553j), (-0.5445-0.7896j), (-1.6492-0.0633j), (-0.0638-0.8119j)]) + >>> x.real + tensor([ 0.3100, -0.5445, -1.6492, -0.0638]) + """ + +def reciprocal(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + reciprocal(input, *, out=None) -> Tensor + + Returns a new tensor with the reciprocal of the elements of :attr:`input` + + .. math:: + \text{out}_{i} = \frac{1}{\text{input}_{i}} + + .. note:: + Unlike NumPy's reciprocal, torch.reciprocal supports integral inputs. Integral + inputs to reciprocal are automatically :ref:`promoted ` to + the default scalar type. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-0.4595, -2.1219, -1.4314, 0.7298]) + >>> torch.reciprocal(a) + tensor([-2.1763, -0.4713, -0.6986, 1.3702]) + """ + +def reciprocal_(input: Tensor) -> Tensor: ... +def relu(input: Tensor) -> Tensor: ... +def relu_(input: Tensor) -> Tensor: ... +@overload +def remainder( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + remainder(input, other, *, out=None) -> Tensor + + Computes + `Python's modulus operation `_ + entrywise. The result has the same sign as the divisor :attr:`other` and its absolute value + is less than that of :attr:`other`. + + It may also be defined in terms of :func:`torch.div` as + + .. code:: python + + torch.remainder(a, b) == a - a.div(b, rounding_mode="floor") * b + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer and float inputs. + + .. note:: + Complex inputs are not supported. In some cases, it is not mathematically + possible to satisfy the definition of a modulo operation with complex numbers. + See :func:`torch.fmod` for how division by zero is handled. + + .. seealso:: + + :func:`torch.fmod` which implements C++'s `std::fmod `_. + This one is defined in terms of division rounding towards zero. + + Args: + input (Tensor or Scalar): the dividend + other (Tensor or Scalar): the divisor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.remainder(torch.tensor([-3., -2, -1, 1, 2, 3]), 2) + tensor([ 1., 0., 1., 1., 0., 1.]) + >>> torch.remainder(torch.tensor([1, 2, 3, 4, 5]), -1.5) + tensor([ -0.5000, -1.0000, 0.0000, -0.5000, -1.0000 ]) + """ + +@overload +def remainder(self: Number | _complex, other: Tensor) -> Tensor: + r""" + remainder(input, other, *, out=None) -> Tensor + + Computes + `Python's modulus operation `_ + entrywise. The result has the same sign as the divisor :attr:`other` and its absolute value + is less than that of :attr:`other`. + + It may also be defined in terms of :func:`torch.div` as + + .. code:: python + + torch.remainder(a, b) == a - a.div(b, rounding_mode="floor") * b + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer and float inputs. + + .. note:: + Complex inputs are not supported. In some cases, it is not mathematically + possible to satisfy the definition of a modulo operation with complex numbers. + See :func:`torch.fmod` for how division by zero is handled. + + .. seealso:: + + :func:`torch.fmod` which implements C++'s `std::fmod `_. + This one is defined in terms of division rounding towards zero. + + Args: + input (Tensor or Scalar): the dividend + other (Tensor or Scalar): the divisor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.remainder(torch.tensor([-3., -2, -1, 1, 2, 3]), 2) + tensor([ 1., 0., 1., 1., 0., 1.]) + >>> torch.remainder(torch.tensor([1, 2, 3, 4, 5]), -1.5) + tensor([ -0.5000, -1.0000, 0.0000, -0.5000, -1.0000 ]) + """ + +@overload +def remainder( + input: Tensor, + other: Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + remainder(input, other, *, out=None) -> Tensor + + Computes + `Python's modulus operation `_ + entrywise. The result has the same sign as the divisor :attr:`other` and its absolute value + is less than that of :attr:`other`. + + It may also be defined in terms of :func:`torch.div` as + + .. code:: python + + torch.remainder(a, b) == a - a.div(b, rounding_mode="floor") * b + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer and float inputs. + + .. note:: + Complex inputs are not supported. In some cases, it is not mathematically + possible to satisfy the definition of a modulo operation with complex numbers. + See :func:`torch.fmod` for how division by zero is handled. + + .. seealso:: + + :func:`torch.fmod` which implements C++'s `std::fmod `_. + This one is defined in terms of division rounding towards zero. + + Args: + input (Tensor or Scalar): the dividend + other (Tensor or Scalar): the divisor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.remainder(torch.tensor([-3., -2, -1, 1, 2, 3]), 2) + tensor([ 1., 0., 1., 1., 0., 1.]) + >>> torch.remainder(torch.tensor([1, 2, 3, 4, 5]), -1.5) + tensor([ -0.5000, -1.0000, 0.0000, -0.5000, -1.0000 ]) + """ + +def renorm( + input: Tensor, + p: Number | _complex, + dim: _int, + maxnorm: Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + renorm(input, p, dim, maxnorm, *, out=None) -> Tensor + + Returns a tensor where each sub-tensor of :attr:`input` along dimension + :attr:`dim` is normalized such that the `p`-norm of the sub-tensor is lower + than the value :attr:`maxnorm` + + .. note:: If the norm of a row is lower than `maxnorm`, the row is unchanged + + Args: + input (Tensor): the input tensor. + p (float): the power for the norm computation + dim (int): the dimension to slice over to get the sub-tensors + maxnorm (float): the maximum norm to keep each sub-tensor under + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> x = torch.ones(3, 3) + >>> x[1].fill_(2) + tensor([ 2., 2., 2.]) + >>> x[2].fill_(3) + tensor([ 3., 3., 3.]) + >>> x + tensor([[ 1., 1., 1.], + [ 2., 2., 2.], + [ 3., 3., 3.]]) + >>> torch.renorm(x, 1, 0, 5) + tensor([[ 1.0000, 1.0000, 1.0000], + [ 1.6667, 1.6667, 1.6667], + [ 1.6667, 1.6667, 1.6667]]) + """ + +@overload +def repeat_interleave( + input: Tensor, + repeats: Tensor, + dim: _int | None = None, + *, + output_size: _int | SymInt | None = None, +) -> Tensor: + r""" + repeat_interleave(input, repeats, dim=None, *, output_size=None) -> Tensor + + Repeat elements of a tensor. + + .. warning:: + + This is different from :meth:`torch.Tensor.repeat` but similar to ``numpy.repeat``. + + Args: + input (Tensor): the input tensor. + repeats (Tensor or int): The number of repetitions for each element. + repeats is broadcasted to fit the shape of the given axis. + dim (int, optional): The dimension along which to repeat values. + By default, use the flattened input array, and return a flat output + array. + + Keyword args: + output_size (int, optional): Total output size for the given axis + ( e.g. sum of repeats). If given, it will avoid stream synchronization + needed to calculate output shape of the tensor. + + Returns: + Tensor: Repeated tensor which has the same shape as input, except along the given axis. + + Example:: + + >>> x = torch.tensor([1, 2, 3]) + >>> x.repeat_interleave(2) + tensor([1, 1, 2, 2, 3, 3]) + >>> y = torch.tensor([[1, 2], [3, 4]]) + >>> torch.repeat_interleave(y, 2) + tensor([1, 1, 2, 2, 3, 3, 4, 4]) + >>> torch.repeat_interleave(y, 3, dim=1) + tensor([[1, 1, 1, 2, 2, 2], + [3, 3, 3, 4, 4, 4]]) + >>> torch.repeat_interleave(y, torch.tensor([1, 2]), dim=0) + tensor([[1, 2], + [3, 4], + [3, 4]]) + >>> torch.repeat_interleave(y, torch.tensor([1, 2]), dim=0, output_size=3) + tensor([[1, 2], + [3, 4], + [3, 4]]) + + If the `repeats` is `tensor([n1, n2, n3, ...])`, then the output will be + `tensor([0, 0, ..., 1, 1, ..., 2, 2, ..., ...])` where `0` appears `n1` times, + `1` appears `n2` times, `2` appears `n3` times, etc. + + .. function:: repeat_interleave(repeats, *) -> Tensor + :noindex: + + Repeats 0 repeats[0] times, 1 repeats[1] times, 2 repeats[2] times, etc. + + Args: + repeats (Tensor): The number of repetitions for each element. + + Returns: + Tensor: Repeated tensor of size `sum(repeats)`. + + Example:: + + >>> torch.repeat_interleave(torch.tensor([1, 2, 3])) + tensor([0, 1, 1, 2, 2, 2]) + """ + +@overload +def repeat_interleave( + repeats: Tensor, + *, + output_size: _int | SymInt | None = None, +) -> Tensor: + r""" + repeat_interleave(input, repeats, dim=None, *, output_size=None) -> Tensor + + Repeat elements of a tensor. + + .. warning:: + + This is different from :meth:`torch.Tensor.repeat` but similar to ``numpy.repeat``. + + Args: + input (Tensor): the input tensor. + repeats (Tensor or int): The number of repetitions for each element. + repeats is broadcasted to fit the shape of the given axis. + dim (int, optional): The dimension along which to repeat values. + By default, use the flattened input array, and return a flat output + array. + + Keyword args: + output_size (int, optional): Total output size for the given axis + ( e.g. sum of repeats). If given, it will avoid stream synchronization + needed to calculate output shape of the tensor. + + Returns: + Tensor: Repeated tensor which has the same shape as input, except along the given axis. + + Example:: + + >>> x = torch.tensor([1, 2, 3]) + >>> x.repeat_interleave(2) + tensor([1, 1, 2, 2, 3, 3]) + >>> y = torch.tensor([[1, 2], [3, 4]]) + >>> torch.repeat_interleave(y, 2) + tensor([1, 1, 2, 2, 3, 3, 4, 4]) + >>> torch.repeat_interleave(y, 3, dim=1) + tensor([[1, 1, 1, 2, 2, 2], + [3, 3, 3, 4, 4, 4]]) + >>> torch.repeat_interleave(y, torch.tensor([1, 2]), dim=0) + tensor([[1, 2], + [3, 4], + [3, 4]]) + >>> torch.repeat_interleave(y, torch.tensor([1, 2]), dim=0, output_size=3) + tensor([[1, 2], + [3, 4], + [3, 4]]) + + If the `repeats` is `tensor([n1, n2, n3, ...])`, then the output will be + `tensor([0, 0, ..., 1, 1, ..., 2, 2, ..., ...])` where `0` appears `n1` times, + `1` appears `n2` times, `2` appears `n3` times, etc. + + .. function:: repeat_interleave(repeats, *) -> Tensor + :noindex: + + Repeats 0 repeats[0] times, 1 repeats[1] times, 2 repeats[2] times, etc. + + Args: + repeats (Tensor): The number of repetitions for each element. + + Returns: + Tensor: Repeated tensor of size `sum(repeats)`. + + Example:: + + >>> torch.repeat_interleave(torch.tensor([1, 2, 3])) + tensor([0, 1, 1, 2, 2, 2]) + """ + +@overload +def repeat_interleave( + input: Tensor, + repeats: _int | SymInt, + dim: _int | None = None, + *, + output_size: _int | SymInt | None = None, +) -> Tensor: + r""" + repeat_interleave(input, repeats, dim=None, *, output_size=None) -> Tensor + + Repeat elements of a tensor. + + .. warning:: + + This is different from :meth:`torch.Tensor.repeat` but similar to ``numpy.repeat``. + + Args: + input (Tensor): the input tensor. + repeats (Tensor or int): The number of repetitions for each element. + repeats is broadcasted to fit the shape of the given axis. + dim (int, optional): The dimension along which to repeat values. + By default, use the flattened input array, and return a flat output + array. + + Keyword args: + output_size (int, optional): Total output size for the given axis + ( e.g. sum of repeats). If given, it will avoid stream synchronization + needed to calculate output shape of the tensor. + + Returns: + Tensor: Repeated tensor which has the same shape as input, except along the given axis. + + Example:: + + >>> x = torch.tensor([1, 2, 3]) + >>> x.repeat_interleave(2) + tensor([1, 1, 2, 2, 3, 3]) + >>> y = torch.tensor([[1, 2], [3, 4]]) + >>> torch.repeat_interleave(y, 2) + tensor([1, 1, 2, 2, 3, 3, 4, 4]) + >>> torch.repeat_interleave(y, 3, dim=1) + tensor([[1, 1, 1, 2, 2, 2], + [3, 3, 3, 4, 4, 4]]) + >>> torch.repeat_interleave(y, torch.tensor([1, 2]), dim=0) + tensor([[1, 2], + [3, 4], + [3, 4]]) + >>> torch.repeat_interleave(y, torch.tensor([1, 2]), dim=0, output_size=3) + tensor([[1, 2], + [3, 4], + [3, 4]]) + + If the `repeats` is `tensor([n1, n2, n3, ...])`, then the output will be + `tensor([0, 0, ..., 1, 1, ..., 2, 2, ..., ...])` where `0` appears `n1` times, + `1` appears `n2` times, `2` appears `n3` times, etc. + + .. function:: repeat_interleave(repeats, *) -> Tensor + :noindex: + + Repeats 0 repeats[0] times, 1 repeats[1] times, 2 repeats[2] times, etc. + + Args: + repeats (Tensor): The number of repetitions for each element. + + Returns: + Tensor: Repeated tensor of size `sum(repeats)`. + + Example:: + + >>> torch.repeat_interleave(torch.tensor([1, 2, 3])) + tensor([0, 1, 1, 2, 2, 2]) + """ + +def reshape(input: Tensor, shape: Sequence[_int | SymInt]) -> Tensor: + r""" + reshape(input, shape) -> Tensor + + Returns a tensor with the same data and number of elements as :attr:`input`, + but with the specified shape. When possible, the returned tensor will be a view + of :attr:`input`. Otherwise, it will be a copy. Contiguous inputs and inputs + with compatible strides can be reshaped without copying, but you should not + depend on the copying vs. viewing behavior. + + See :meth:`torch.Tensor.view` on when it is possible to return a view. + + A single dimension may be -1, in which case it's inferred from the remaining + dimensions and the number of elements in :attr:`input`. + + Args: + input (Tensor): the tensor to be reshaped + shape (tuple of int): the new shape + + Example:: + + >>> a = torch.arange(4.) + >>> torch.reshape(a, (2, 2)) + tensor([[ 0., 1.], + [ 2., 3.]]) + >>> b = torch.tensor([[0, 1], [2, 3]]) + >>> torch.reshape(b, (-1,)) + tensor([ 0, 1, 2, 3]) + """ + +def resize_as_( + input: Tensor, + the_template: Tensor, + *, + memory_format: memory_format | None = None, +) -> Tensor: ... +def resize_as_sparse_(input: Tensor, the_template: Tensor) -> Tensor: ... +def resolve_conj(input: Tensor) -> Tensor: + r""" + resolve_conj(input) -> Tensor + + Returns a new tensor with materialized conjugation if :attr:`input`'s conjugate bit is set to `True`, + else returns :attr:`input`. The output tensor will always have its conjugate bit set to `False`. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> x = torch.tensor([-1 + 1j, -2 + 2j, 3 - 3j]) + >>> y = x.conj() + >>> y.is_conj() + True + >>> z = y.resolve_conj() + >>> z + tensor([-1 - 1j, -2 - 2j, 3 + 3j]) + >>> z.is_conj() + False + """ + +def resolve_neg(input: Tensor) -> Tensor: + r""" + resolve_neg(input) -> Tensor + + Returns a new tensor with materialized negation if :attr:`input`'s negative bit is set to `True`, + else returns :attr:`input`. The output tensor will always have its negative bit set to `False`. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> x = torch.tensor([-1 + 1j, -2 + 2j, 3 - 3j]) + >>> y = x.conj() + >>> z = y.imag + >>> z.is_neg() + True + >>> out = z.resolve_neg() + >>> out + tensor([-1., -2., 3.]) + >>> out.is_neg() + False + """ + +@overload +def result_type(tensor: Tensor, other: Tensor) -> _dtype: + r""" + result_type(tensor1, tensor2) -> dtype + + Returns the :class:`torch.dtype` that would result from performing an arithmetic + operation on the provided input tensors. See type promotion :ref:`documentation ` + for more information on the type promotion logic. + + Args: + tensor1 (Tensor or Number): an input tensor or number + tensor2 (Tensor or Number): an input tensor or number + + Example:: + + >>> torch.result_type(torch.tensor([1, 2], dtype=torch.int), 1.0) + torch.float32 + >>> torch.result_type(torch.tensor([1, 2], dtype=torch.uint8), torch.tensor(1)) + torch.uint8 + """ + +@overload +def result_type(scalar: Number | _complex, tensor: Tensor) -> _dtype: + r""" + result_type(tensor1, tensor2) -> dtype + + Returns the :class:`torch.dtype` that would result from performing an arithmetic + operation on the provided input tensors. See type promotion :ref:`documentation ` + for more information on the type promotion logic. + + Args: + tensor1 (Tensor or Number): an input tensor or number + tensor2 (Tensor or Number): an input tensor or number + + Example:: + + >>> torch.result_type(torch.tensor([1, 2], dtype=torch.int), 1.0) + torch.float32 + >>> torch.result_type(torch.tensor([1, 2], dtype=torch.uint8), torch.tensor(1)) + torch.uint8 + """ + +@overload +def result_type(tensor: Tensor, other: Number | _complex) -> _dtype: + r""" + result_type(tensor1, tensor2) -> dtype + + Returns the :class:`torch.dtype` that would result from performing an arithmetic + operation on the provided input tensors. See type promotion :ref:`documentation ` + for more information on the type promotion logic. + + Args: + tensor1 (Tensor or Number): an input tensor or number + tensor2 (Tensor or Number): an input tensor or number + + Example:: + + >>> torch.result_type(torch.tensor([1, 2], dtype=torch.int), 1.0) + torch.float32 + >>> torch.result_type(torch.tensor([1, 2], dtype=torch.uint8), torch.tensor(1)) + torch.uint8 + """ + +@overload +def result_type( + scalar1: Number | _complex, + scalar2: Number | _complex, +) -> _dtype: + r""" + result_type(tensor1, tensor2) -> dtype + + Returns the :class:`torch.dtype` that would result from performing an arithmetic + operation on the provided input tensors. See type promotion :ref:`documentation ` + for more information on the type promotion logic. + + Args: + tensor1 (Tensor or Number): an input tensor or number + tensor2 (Tensor or Number): an input tensor or number + + Example:: + + >>> torch.result_type(torch.tensor([1, 2], dtype=torch.int), 1.0) + torch.float32 + >>> torch.result_type(torch.tensor([1, 2], dtype=torch.uint8), torch.tensor(1)) + torch.uint8 + """ + +def rms_norm( + input: Tensor, + normalized_shape: Sequence[_int | SymInt], + weight: Tensor | None = None, + eps: _float | None = None, +) -> Tensor: ... +@overload +def rnn_relu( + data: Tensor, + batch_sizes: Tensor, + hx: Tensor, + params: tuple[Tensor, ...] | list[Tensor] | None, + has_biases: _bool, + num_layers: _int, + dropout: _float, + train: _bool, + bidirectional: _bool, +) -> tuple[Tensor, Tensor]: ... +@overload +def rnn_relu( + input: Tensor, + hx: Tensor, + params: tuple[Tensor, ...] | list[Tensor] | None, + has_biases: _bool, + num_layers: _int, + dropout: _float, + train: _bool, + bidirectional: _bool, + batch_first: _bool, +) -> tuple[Tensor, Tensor]: ... +def rnn_relu_cell( + input: Tensor, + hx: Tensor, + w_ih: Tensor, + w_hh: Tensor, + b_ih: Tensor | None = None, + b_hh: Tensor | None = None, +) -> Tensor: ... +@overload +def rnn_tanh( + data: Tensor, + batch_sizes: Tensor, + hx: Tensor, + params: tuple[Tensor, ...] | list[Tensor] | None, + has_biases: _bool, + num_layers: _int, + dropout: _float, + train: _bool, + bidirectional: _bool, +) -> tuple[Tensor, Tensor]: ... +@overload +def rnn_tanh( + input: Tensor, + hx: Tensor, + params: tuple[Tensor, ...] | list[Tensor] | None, + has_biases: _bool, + num_layers: _int, + dropout: _float, + train: _bool, + bidirectional: _bool, + batch_first: _bool, +) -> tuple[Tensor, Tensor]: ... +def rnn_tanh_cell( + input: Tensor, + hx: Tensor, + w_ih: Tensor, + w_hh: Tensor, + b_ih: Tensor | None = None, + b_hh: Tensor | None = None, +) -> Tensor: ... +def roll( + input: Tensor, + shifts: _int | SymInt | Sequence[_int | SymInt], + dims: _int | _size = (), +) -> Tensor: + r""" + roll(input, shifts, dims=None) -> Tensor + + Roll the tensor :attr:`input` along the given dimension(s). Elements that are + shifted beyond the last position are re-introduced at the first position. If + :attr:`dims` is `None`, the tensor will be flattened before rolling and then + restored to the original shape. + + Args: + input (Tensor): the input tensor. + shifts (int or tuple of ints): The number of places by which the elements + of the tensor are shifted. If shifts is a tuple, dims must be a tuple of + the same size, and each dimension will be rolled by the corresponding + value + dims (int or tuple of ints): Axis along which to roll + + Example:: + + >>> x = torch.tensor([1, 2, 3, 4, 5, 6, 7, 8]).view(4, 2) + >>> x + tensor([[1, 2], + [3, 4], + [5, 6], + [7, 8]]) + >>> torch.roll(x, 1) + tensor([[8, 1], + [2, 3], + [4, 5], + [6, 7]]) + >>> torch.roll(x, 1, 0) + tensor([[7, 8], + [1, 2], + [3, 4], + [5, 6]]) + >>> torch.roll(x, -1, 0) + tensor([[3, 4], + [5, 6], + [7, 8], + [1, 2]]) + >>> torch.roll(x, shifts=(2, 1), dims=(0, 1)) + tensor([[6, 5], + [8, 7], + [2, 1], + [4, 3]]) + """ + +def rot90(input: Tensor, k: _int = 1, dims: _size = (0, 1)) -> Tensor: + r""" + rot90(input, k=1, dims=(0, 1)) -> Tensor + + Rotate an n-D tensor by 90 degrees in the plane specified by dims axis. + Rotation direction is from the first towards the second axis if k > 0, and from the second towards the first for k < 0. + + Args: + input (Tensor): the input tensor. + k (int): number of times to rotate. Default value is 1 + dims (a list or tuple): axis to rotate. Default value is [0, 1] + + Example:: + + >>> x = torch.arange(4).view(2, 2) + >>> x + tensor([[0, 1], + [2, 3]]) + >>> torch.rot90(x, 1, [0, 1]) + tensor([[1, 3], + [0, 2]]) + + >>> x = torch.arange(8).view(2, 2, 2) + >>> x + tensor([[[0, 1], + [2, 3]], + + [[4, 5], + [6, 7]]]) + >>> torch.rot90(x, 1, [1, 2]) + tensor([[[1, 3], + [0, 2]], + + [[5, 7], + [4, 6]]]) + """ + +@overload +def round(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + round(input, *, decimals=0, out=None) -> Tensor + + Rounds elements of :attr:`input` to the nearest integer. + + For integer inputs, follows the array-api convention of returning a + copy of the input tensor. + The return type of output is same as that of input's dtype. + + .. note:: + This function implements the "round half to even" to + break ties when a number is equidistant from two + integers (e.g. `round(2.5)` is 2). + + When the :attr:\`decimals\` argument is specified the + algorithm used is similar to NumPy's `around`. This + algorithm is fast but inexact and it can easily + overflow for low precision dtypes. + Eg. `round(tensor([10000], dtype=torch.float16), decimals=3)` is `inf`. + + .. seealso:: + :func:`torch.ceil`, which rounds up. + :func:`torch.floor`, which rounds down. + :func:`torch.trunc`, which rounds towards zero. + + Args: + input (Tensor): the input tensor. + decimals (int): Number of decimal places to round to (default: 0). + If decimals is negative, it specifies the number of positions + to the left of the decimal point. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.round(torch.tensor((4.7, -2.3, 9.1, -7.7))) + tensor([ 5., -2., 9., -8.]) + + >>> # Values equidistant from two integers are rounded towards the + >>> # the nearest even value (zero is treated as even) + >>> torch.round(torch.tensor([-0.5, 0.5, 1.5, 2.5])) + tensor([-0., 0., 2., 2.]) + + >>> # A positive decimals argument rounds to the to that decimal place + >>> torch.round(torch.tensor([0.1234567]), decimals=3) + tensor([0.1230]) + + >>> # A negative decimals argument rounds to the left of the decimal + >>> torch.round(torch.tensor([1200.1234567]), decimals=-3) + tensor([1000.]) + """ + +@overload +def round( + input: Tensor, + *, + decimals: _int, + out: Tensor | None = None, +) -> Tensor: + r""" + round(input, *, decimals=0, out=None) -> Tensor + + Rounds elements of :attr:`input` to the nearest integer. + + For integer inputs, follows the array-api convention of returning a + copy of the input tensor. + The return type of output is same as that of input's dtype. + + .. note:: + This function implements the "round half to even" to + break ties when a number is equidistant from two + integers (e.g. `round(2.5)` is 2). + + When the :attr:\`decimals\` argument is specified the + algorithm used is similar to NumPy's `around`. This + algorithm is fast but inexact and it can easily + overflow for low precision dtypes. + Eg. `round(tensor([10000], dtype=torch.float16), decimals=3)` is `inf`. + + .. seealso:: + :func:`torch.ceil`, which rounds up. + :func:`torch.floor`, which rounds down. + :func:`torch.trunc`, which rounds towards zero. + + Args: + input (Tensor): the input tensor. + decimals (int): Number of decimal places to round to (default: 0). + If decimals is negative, it specifies the number of positions + to the left of the decimal point. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.round(torch.tensor((4.7, -2.3, 9.1, -7.7))) + tensor([ 5., -2., 9., -8.]) + + >>> # Values equidistant from two integers are rounded towards the + >>> # the nearest even value (zero is treated as even) + >>> torch.round(torch.tensor([-0.5, 0.5, 1.5, 2.5])) + tensor([-0., 0., 2., 2.]) + + >>> # A positive decimals argument rounds to the to that decimal place + >>> torch.round(torch.tensor([0.1234567]), decimals=3) + tensor([0.1230]) + + >>> # A negative decimals argument rounds to the left of the decimal + >>> torch.round(torch.tensor([1200.1234567]), decimals=-3) + tensor([1000.]) + """ + +@overload +def round_(input: Tensor) -> Tensor: ... +@overload +def round_(input: Tensor, *, decimals: _int) -> Tensor: ... +def row_indices_copy(input: Tensor, *, out: Tensor | None = None) -> Tensor: ... +def row_stack( + tensors: tuple[Tensor, ...] | list[Tensor] | None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + row_stack(tensors, *, out=None) -> Tensor + + Alias of :func:`torch.vstack`. + """ + +def rrelu( + input: Tensor, + lower: Number | _complex = 0.125, + upper: Number | _complex = 0.3333333333333333, + training: _bool = False, + generator: Generator | None = None, +) -> Tensor: ... +def rrelu_( + input: Tensor, + lower: Number | _complex = 0.125, + upper: Number | _complex = 0.3333333333333333, + training: _bool = False, + generator: Generator | None = None, +) -> Tensor: ... +def rsqrt(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + rsqrt(input, *, out=None) -> Tensor + + Returns a new tensor with the reciprocal of the square-root of each of + the elements of :attr:`input`. + + .. math:: + \text{out}_{i} = \frac{1}{\sqrt{\text{input}_{i}}} + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-0.0370, 0.2970, 1.5420, -0.9105]) + >>> torch.rsqrt(a) + tensor([ nan, 1.8351, 0.8053, nan]) + """ + +def rsqrt_(input: Tensor) -> Tensor: ... +@overload +def rsub( + input: Tensor, + other: Tensor, + *, + alpha: Number | _complex = 1, +) -> Tensor: ... +@overload +def rsub( + input: Tensor, + other: Number | _complex, + alpha: Number | _complex = 1, +) -> Tensor: ... +def saddmm( + input: Tensor, + mat1: Tensor, + mat2: Tensor, + *, + beta: Number = 1, + alpha: Number = 1, + out: Tensor | None = None, +) -> Tensor: ... +def scalar_tensor( + s: Number | _complex, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: ... +@overload +def scatter( + input: Tensor, + dim: _int, + index: Tensor, + src: Tensor, + *, + reduce: str, + out: Tensor | None = None, +) -> Tensor: + r""" + scatter(input, dim, index, src) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.scatter_` + """ + +@overload +def scatter( + input: Tensor, + dim: _int, + index: Tensor, + src: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + scatter(input, dim, index, src) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.scatter_` + """ + +@overload +def scatter( + input: Tensor, + dim: _int, + index: Tensor, + value: Number | _complex, + *, + reduce: str, + out: Tensor | None = None, +) -> Tensor: + r""" + scatter(input, dim, index, src) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.scatter_` + """ + +@overload +def scatter( + input: Tensor, + dim: str | EllipsisType | None, + index: Tensor, + src: Tensor, +) -> Tensor: + r""" + scatter(input, dim, index, src) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.scatter_` + """ + +@overload +def scatter( + input: Tensor, + dim: _int, + index: Tensor, + value: Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + scatter(input, dim, index, src) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.scatter_` + """ + +@overload +def scatter( + input: Tensor, + dim: str | EllipsisType | None, + index: Tensor, + value: Number | _complex, +) -> Tensor: + r""" + scatter(input, dim, index, src) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.scatter_` + """ + +@overload +def scatter_add( + input: Tensor, + dim: _int, + index: Tensor, + src: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + scatter_add(input, dim, index, src) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.scatter_add_` + """ + +@overload +def scatter_add( + input: Tensor, + dim: str | EllipsisType | None, + index: Tensor, + src: Tensor, +) -> Tensor: + r""" + scatter_add(input, dim, index, src) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.scatter_add_` + """ + +def scatter_reduce( + input: Tensor, + dim: _int, + index: Tensor, + src: Tensor, + reduce: str, + *, + include_self: _bool = True, + out: Tensor | None = None, +) -> Tensor: + r""" + scatter_reduce(input, dim, index, src, reduce, *, include_self=True) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.scatter_reduce_` + """ + +@overload +def searchsorted( + sorted_sequence: Tensor, + input: Tensor, + *, + out_int32: _bool = False, + right: _bool = False, + side: str | None = None, + sorter: Tensor | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + searchsorted(sorted_sequence, values, *, out_int32=False, right=False, side=None, out=None, sorter=None) -> Tensor + + Find the indices from the *innermost* dimension of :attr:`sorted_sequence` such that, if the + corresponding values in :attr:`values` were inserted before the indices, when sorted, the order + of the corresponding *innermost* dimension within :attr:`sorted_sequence` would be preserved. + Return a new tensor with the same size as :attr:`values`. More formally, + the returned index satisfies the following rules: + + .. list-table:: + :widths: 12 10 78 + :header-rows: 1 + + * - :attr:`sorted_sequence` + - :attr:`right` + - *returned index satisfies* + * - 1-D + - False + - ``sorted_sequence[i-1] < values[m][n]...[l][x] <= sorted_sequence[i]`` + * - 1-D + - True + - ``sorted_sequence[i-1] <= values[m][n]...[l][x] < sorted_sequence[i]`` + * - N-D + - False + - ``sorted_sequence[m][n]...[l][i-1] < values[m][n]...[l][x] <= sorted_sequence[m][n]...[l][i]`` + * - N-D + - True + - ``sorted_sequence[m][n]...[l][i-1] <= values[m][n]...[l][x] < sorted_sequence[m][n]...[l][i]`` + + Args: + sorted_sequence (Tensor): N-D or 1-D tensor, containing monotonically increasing sequence on the *innermost* + dimension unless :attr:`sorter` is provided, in which case the sequence does not + need to be sorted + values (Tensor or Scalar): N-D tensor or a Scalar containing the search value(s). + + Keyword args: + out_int32 (bool, optional): indicate the output data type. torch.int32 if True, torch.int64 otherwise. + Default value is False, i.e. default output data type is torch.int64. + right (bool, optional): if False, return the first suitable location that is found. If True, return the + last such index. If no suitable index found, return 0 for non-numerical value + (eg. nan, inf) or the size of *innermost* dimension within :attr:`sorted_sequence` + (one pass the last index of the *innermost* dimension). In other words, if False, + gets the lower bound index for each value in :attr:`values` on the corresponding + *innermost* dimension of the :attr:`sorted_sequence`. If True, gets the upper + bound index instead. Default value is False. :attr:`side` does the same and is + preferred. It will error if :attr:`side` is set to "left" while this is True. + side (str, optional): the same as :attr:`right` but preferred. "left" corresponds to False for :attr:`right` + and "right" corresponds to True for :attr:`right`. It will error if this is set to + "left" while :attr:`right` is True. Default value is None. + out (Tensor, optional): the output tensor, must be the same size as :attr:`values` if provided. + sorter (LongTensor, optional): if provided, a tensor matching the shape of the unsorted + :attr:`sorted_sequence` containing a sequence of indices that sort it in the + ascending order on the innermost dimension + + + Example:: + + >>> sorted_sequence = torch.tensor([[1, 3, 5, 7, 9], [2, 4, 6, 8, 10]]) + >>> sorted_sequence + tensor([[ 1, 3, 5, 7, 9], + [ 2, 4, 6, 8, 10]]) + >>> values = torch.tensor([[3, 6, 9], [3, 6, 9]]) + >>> values + tensor([[3, 6, 9], + [3, 6, 9]]) + >>> torch.searchsorted(sorted_sequence, values) + tensor([[1, 3, 4], + [1, 2, 4]]) + >>> torch.searchsorted(sorted_sequence, values, side='right') + tensor([[2, 3, 5], + [1, 3, 4]]) + + >>> sorted_sequence_1d = torch.tensor([1, 3, 5, 7, 9]) + >>> sorted_sequence_1d + tensor([1, 3, 5, 7, 9]) + >>> torch.searchsorted(sorted_sequence_1d, values) + tensor([[1, 3, 4], + [1, 3, 4]]) + """ + +@overload +def searchsorted( + sorted_sequence: Tensor, + self: Number | _complex, + *, + out_int32: _bool = False, + right: _bool = False, + side: str | None = None, + sorter: Tensor | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + searchsorted(sorted_sequence, values, *, out_int32=False, right=False, side=None, out=None, sorter=None) -> Tensor + + Find the indices from the *innermost* dimension of :attr:`sorted_sequence` such that, if the + corresponding values in :attr:`values` were inserted before the indices, when sorted, the order + of the corresponding *innermost* dimension within :attr:`sorted_sequence` would be preserved. + Return a new tensor with the same size as :attr:`values`. More formally, + the returned index satisfies the following rules: + + .. list-table:: + :widths: 12 10 78 + :header-rows: 1 + + * - :attr:`sorted_sequence` + - :attr:`right` + - *returned index satisfies* + * - 1-D + - False + - ``sorted_sequence[i-1] < values[m][n]...[l][x] <= sorted_sequence[i]`` + * - 1-D + - True + - ``sorted_sequence[i-1] <= values[m][n]...[l][x] < sorted_sequence[i]`` + * - N-D + - False + - ``sorted_sequence[m][n]...[l][i-1] < values[m][n]...[l][x] <= sorted_sequence[m][n]...[l][i]`` + * - N-D + - True + - ``sorted_sequence[m][n]...[l][i-1] <= values[m][n]...[l][x] < sorted_sequence[m][n]...[l][i]`` + + Args: + sorted_sequence (Tensor): N-D or 1-D tensor, containing monotonically increasing sequence on the *innermost* + dimension unless :attr:`sorter` is provided, in which case the sequence does not + need to be sorted + values (Tensor or Scalar): N-D tensor or a Scalar containing the search value(s). + + Keyword args: + out_int32 (bool, optional): indicate the output data type. torch.int32 if True, torch.int64 otherwise. + Default value is False, i.e. default output data type is torch.int64. + right (bool, optional): if False, return the first suitable location that is found. If True, return the + last such index. If no suitable index found, return 0 for non-numerical value + (eg. nan, inf) or the size of *innermost* dimension within :attr:`sorted_sequence` + (one pass the last index of the *innermost* dimension). In other words, if False, + gets the lower bound index for each value in :attr:`values` on the corresponding + *innermost* dimension of the :attr:`sorted_sequence`. If True, gets the upper + bound index instead. Default value is False. :attr:`side` does the same and is + preferred. It will error if :attr:`side` is set to "left" while this is True. + side (str, optional): the same as :attr:`right` but preferred. "left" corresponds to False for :attr:`right` + and "right" corresponds to True for :attr:`right`. It will error if this is set to + "left" while :attr:`right` is True. Default value is None. + out (Tensor, optional): the output tensor, must be the same size as :attr:`values` if provided. + sorter (LongTensor, optional): if provided, a tensor matching the shape of the unsorted + :attr:`sorted_sequence` containing a sequence of indices that sort it in the + ascending order on the innermost dimension + + + Example:: + + >>> sorted_sequence = torch.tensor([[1, 3, 5, 7, 9], [2, 4, 6, 8, 10]]) + >>> sorted_sequence + tensor([[ 1, 3, 5, 7, 9], + [ 2, 4, 6, 8, 10]]) + >>> values = torch.tensor([[3, 6, 9], [3, 6, 9]]) + >>> values + tensor([[3, 6, 9], + [3, 6, 9]]) + >>> torch.searchsorted(sorted_sequence, values) + tensor([[1, 3, 4], + [1, 2, 4]]) + >>> torch.searchsorted(sorted_sequence, values, side='right') + tensor([[2, 3, 5], + [1, 3, 4]]) + + >>> sorted_sequence_1d = torch.tensor([1, 3, 5, 7, 9]) + >>> sorted_sequence_1d + tensor([1, 3, 5, 7, 9]) + >>> torch.searchsorted(sorted_sequence_1d, values) + tensor([[1, 3, 4], + [1, 3, 4]]) + """ + +def segment_reduce( + data: Tensor, + reduce: str, + *, + lengths: Tensor | None = None, + indices: Tensor | None = None, + offsets: Tensor | None = None, + axis: _int = 0, + unsafe: _bool = False, + initial: Number | _complex | None = None, +) -> Tensor: + r""" + segment_reduce(data: Tensor, reduce: str, *, lengths: Tensor | None = None, indices: Tensor | None = None, offsets: Tensor | None = None, axis: _int = 0, unsafe: _bool = False, initial: Number | _complex | None = None) -> Tensor # noqa: B950 + + Perform a segment reduction operation on the input tensor along the specified axis. + + Args: + data (Tensor): The input tensor on which the segment reduction operation will be performed. + reduce (str): The type of reduction operation. Supported values are ``sum``, ``mean``, ``max``, ``min``, ``prod``. + + Keyword args: + lengths (Tensor, optional): Length of each segment. Default: ``None``. + offsets (Tensor, optional): Offset of each segment. Default: ``None``. + axis (int, optional): The axis perform reduction. Default: ``0``. + unsafe (bool, optional): Skip validation If `True`. Default: ``False``. + initial (Number, optional): The initial value for the reduction operation. Default: ``None``. + + Example:: + + >>> data = torch.tensor([[1, 2, 3, 4],[5, 6, 7, 8],[9, 10, 11, 12]], dtype=torch.float32, device='cuda') + >>> lengths = torch.tensor([2, 1], device='cuda') + >>> torch.segment_reduce(data, 'max', lengths=lengths) + tensor([[ 5., 6., 7., 8.], + [ 9., 10., 11., 12.]], device='cuda:0') + """ + +@overload +def select(input: Tensor, dim: _int, index: _int | SymInt) -> Tensor: + r""" + select(input, dim, index) -> Tensor + + Slices the :attr:`input` tensor along the selected dimension at the given index. + This function returns a view of the original tensor with the given dimension removed. + + .. note:: If :attr:`input` is a sparse tensor and returning a view of + the tensor is not possible, a RuntimeError exception is + raised. In this is the case, consider using + :func:`torch.select_copy` function. + + Args: + input (Tensor): the input tensor. + dim (int): the dimension to slice + index (int): the index to select with + + .. note:: + + :meth:`select` is equivalent to slicing. For example, + ``tensor.select(0, index)`` is equivalent to ``tensor[index]`` and + ``tensor.select(2, index)`` is equivalent to ``tensor[:,:,index]``. + """ + +@overload +def select( + input: Tensor, + dim: str | EllipsisType | None, + index: _int, +) -> Tensor: + r""" + select(input, dim, index) -> Tensor + + Slices the :attr:`input` tensor along the selected dimension at the given index. + This function returns a view of the original tensor with the given dimension removed. + + .. note:: If :attr:`input` is a sparse tensor and returning a view of + the tensor is not possible, a RuntimeError exception is + raised. In this is the case, consider using + :func:`torch.select_copy` function. + + Args: + input (Tensor): the input tensor. + dim (int): the dimension to slice + index (int): the index to select with + + .. note:: + + :meth:`select` is equivalent to slicing. For example, + ``tensor.select(0, index)`` is equivalent to ``tensor[index]`` and + ``tensor.select(2, index)`` is equivalent to ``tensor[:,:,index]``. + """ + +def select_copy( + input: Tensor, + dim: _int, + index: _int | SymInt, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.select`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def select_scatter( + input: Tensor, + src: Tensor, + dim: _int, + index: _int | SymInt, +) -> Tensor: + r""" + select_scatter(input, src, dim, index) -> Tensor + + Embeds the values of the :attr:`src` tensor into :attr:`input` at the given index. + This function returns a tensor with fresh storage; it does not create a view. + + + Args: + input (Tensor): the input tensor. + src (Tensor): The tensor to embed into :attr:`input` + dim (int): the dimension to insert the slice into. + index (int): the index to select with + + .. note:: + + :attr:`src` must be of the proper size in order to be embedded + into :attr:`input`. Specifically, it should have the same shape as + ``torch.select(input, dim, index)`` + + Example:: + + >>> a = torch.zeros(2, 2) + >>> b = torch.ones(2) + >>> a.select_scatter(b, 0, 0) + tensor([[1., 1.], + [0., 0.]]) + """ + +def selu(input: Tensor) -> Tensor: ... +def selu_(input: Tensor) -> Tensor: ... +def set_flush_denormal(mode: _bool) -> _bool: + r""" + set_flush_denormal(mode) -> bool + + Disables denormal floating numbers on CPU. + + Returns ``True`` if your system supports flushing denormal numbers and it + successfully configures flush denormal mode. :meth:`~torch.set_flush_denormal` + is supported on x86 architectures supporting SSE3 and AArch64 architecture. + + Args: + mode (bool): Controls whether to enable flush denormal mode or not + + Example:: + + >>> torch.set_flush_denormal(True) + True + >>> torch.tensor([1e-323], dtype=torch.float64) + tensor([ 0.], dtype=torch.float64) + >>> torch.set_flush_denormal(False) + True + >>> torch.tensor([1e-323], dtype=torch.float64) + tensor(9.88131e-324 * + [ 1.0000], dtype=torch.float64) + """ + +def set_num_interop_threads(num: _int) -> None: + r""" + set_num_interop_threads(int) + + Sets the number of threads used for interop parallelism + (e.g. in JIT interpreter) on CPU. + + .. warning:: + Can only be called once and before any inter-op parallel work + is started (e.g. JIT execution). + """ + +def set_num_threads(num: _int) -> None: + r""" + set_num_threads(int) + + Sets the number of threads used for intraop parallelism on CPU. + + .. warning:: + To ensure that the correct number of threads is used, set_num_threads + must be called before running eager, JIT or autograd code. + """ + +def sgn(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + sgn(input, *, out=None) -> Tensor + + This function is an extension of torch.sign() to complex tensors. + It computes a new tensor whose elements have + the same angles as the corresponding elements of :attr:`input` and + absolute values (i.e. magnitudes) of one for complex tensors and + is equivalent to torch.sign() for non-complex tensors. + + .. math:: + \text{out}_{i} = \begin{cases} + 0 & |\text{{input}}_i| == 0 \\ + \frac{{\text{{input}}_i}}{|{\text{{input}}_i}|} & \text{otherwise} + \end{cases} + + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> t = torch.tensor([3+4j, 7-24j, 0, 1+2j]) + >>> t.sgn() + tensor([0.6000+0.8000j, 0.2800-0.9600j, 0.0000+0.0000j, 0.4472+0.8944j]) + """ + +def sigmoid(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + sigmoid(input, *, out=None) -> Tensor + + Alias for :func:`torch.special.expit`. + """ + +def sigmoid_(input: Tensor) -> Tensor: ... +def sign(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + sign(input, *, out=None) -> Tensor + + Returns a new tensor with the signs of the elements of :attr:`input`. + + .. math:: + \text{out}_{i} = \operatorname{sgn}(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([0.7, -1.2, 0., 2.3]) + >>> a + tensor([ 0.7000, -1.2000, 0.0000, 2.3000]) + >>> torch.sign(a) + tensor([ 1., -1., 0., 1.]) + """ + +def signbit(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + signbit(input, *, out=None) -> Tensor + + Tests if each element of :attr:`input` has its sign bit set or not. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([0.7, -1.2, 0., 2.3]) + >>> torch.signbit(a) + tensor([ False, True, False, False]) + >>> a = torch.tensor([-0.0, 0.0]) + >>> torch.signbit(a) + tensor([ True, False]) + + .. note:: + signbit handles signed zeros, so negative zero (-0) returns True. + """ + +def sin(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + sin(input, *, out=None) -> Tensor + + Returns a new tensor with the sine of the elements in the :attr:`input` tensor, + where each value in this input tensor is in radians. + + .. math:: + \text{out}_{i} = \sin(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-0.5461, 0.1347, -2.7266, -0.2746]) + >>> torch.sin(a) + tensor([-0.5194, 0.1343, -0.4032, -0.2711]) + """ + +def sin_(input: Tensor) -> Tensor: ... +def sinc(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + sinc(input, *, out=None) -> Tensor + + Alias for :func:`torch.special.sinc`. + """ + +def sinc_(input: Tensor) -> Tensor: ... +def sinh(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + sinh(input, *, out=None) -> Tensor + + Returns a new tensor with the hyperbolic sine of the elements of + :attr:`input`. + + .. math:: + \text{out}_{i} = \sinh(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.5380, -0.8632, -0.1265, 0.9399]) + >>> torch.sinh(a) + tensor([ 0.5644, -0.9744, -0.1268, 1.0845]) + + .. note:: + When :attr:`input` is on the CPU, the implementation of torch.sinh may use + the Sleef library, which rounds very large results to infinity or negative + infinity. See `here `_ for details. + """ + +def sinh_(input: Tensor) -> Tensor: ... +def slice_copy( + input: Tensor, + dim: _int = 0, + start: _int | SymInt | None = None, + end: _int | SymInt | None = None, + step: _int | SymInt = 1, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.slice`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def slice_inverse( + input: Tensor, + src: Tensor, + dim: _int = 0, + start: _int | SymInt | None = None, + end: _int | SymInt | None = None, + step: _int | SymInt = 1, +) -> Tensor: ... +def slice_scatter( + input: Tensor, + src: Tensor, + dim: _int = 0, + start: _int | SymInt | None = None, + end: _int | SymInt | None = None, + step: _int | SymInt = 1, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + slice_scatter(input, src, dim=0, start=None, end=None, step=1) -> Tensor + + Embeds the values of the :attr:`src` tensor into :attr:`input` at the given + dimension. + This function returns a tensor with fresh storage; it does not create a view. + + + Args: + input (Tensor): the input tensor. + src (Tensor): The tensor to embed into :attr:`input` + dim (int): the dimension to insert the slice into + start (Optional[int]): the start index of where to insert the slice + end (Optional[int]): the end index of where to insert the slice + step (int): the how many elements to skip in + + Example:: + + >>> a = torch.zeros(8, 8) + >>> b = torch.ones(2, 8) + >>> a.slice_scatter(b, start=6) + tensor([[0., 0., 0., 0., 0., 0., 0., 0.], + [0., 0., 0., 0., 0., 0., 0., 0.], + [0., 0., 0., 0., 0., 0., 0., 0.], + [0., 0., 0., 0., 0., 0., 0., 0.], + [0., 0., 0., 0., 0., 0., 0., 0.], + [0., 0., 0., 0., 0., 0., 0., 0.], + [1., 1., 1., 1., 1., 1., 1., 1.], + [1., 1., 1., 1., 1., 1., 1., 1.]]) + + >>> b = torch.ones(8, 2) + >>> a.slice_scatter(b, dim=1, start=2, end=6, step=2) + tensor([[0., 0., 1., 0., 1., 0., 0., 0.], + [0., 0., 1., 0., 1., 0., 0., 0.], + [0., 0., 1., 0., 1., 0., 0., 0.], + [0., 0., 1., 0., 1., 0., 0., 0.], + [0., 0., 1., 0., 1., 0., 0., 0.], + [0., 0., 1., 0., 1., 0., 0., 0.], + [0., 0., 1., 0., 1., 0., 0., 0.], + [0., 0., 1., 0., 1., 0., 0., 0.]]) + """ + +def slogdet( + input: Tensor, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.slogdet: + r""" + slogdet(input) -> (Tensor, Tensor) + + Alias for :func:`torch.linalg.slogdet` + """ + +def smm(input: Tensor, mat2: Tensor) -> Tensor: + r""" + smm(input, mat) -> Tensor + + Performs a matrix multiplication of the sparse matrix :attr:`input` + with the dense matrix :attr:`mat`. + + Args: + input (Tensor): a sparse matrix to be matrix multiplied + mat (Tensor): a dense matrix to be matrix multiplied + """ + +@overload +def softmax( + input: Tensor, + dim: _int, + dtype: _dtype | None = None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + softmax(input, dim, *, dtype=None) -> Tensor + + Alias for :func:`torch.nn.functional.softmax`. + """ + +@overload +def softmax( + input: Tensor, + dim: str | EllipsisType | None, + *, + dtype: _dtype | None = None, +) -> Tensor: + r""" + softmax(input, dim, *, dtype=None) -> Tensor + + Alias for :func:`torch.nn.functional.softmax`. + """ + +@overload +def sort( + input: Tensor, + *, + stable: _bool | None, + dim: _int = -1, + descending: _bool = False, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.sort: + r""" + sort(input, dim=-1, descending=False, *, stable=False, out=None) -> (Tensor, LongTensor) + + Sorts the elements of the :attr:`input` tensor along a given dimension + in ascending order by value. + + If :attr:`dim` is not given, the last dimension of the `input` is chosen. + + If :attr:`descending` is ``True`` then the elements are sorted in descending + order by value. + + If :attr:`stable` is ``True`` then the sorting routine becomes stable, preserving + the order of equivalent elements. + + A namedtuple of (values, indices) is returned, where the `values` are the + sorted values and `indices` are the indices of the elements in the original + `input` tensor. + + Args: + input (Tensor): the input tensor. + dim (int, optional): the dimension to sort along + descending (bool, optional): controls the sorting order (ascending or descending) + + Keyword args: + stable (bool, optional): makes the sorting routine stable, which guarantees that the order + of equivalent elements is preserved. + out (tuple, optional): the output tuple of (`Tensor`, `LongTensor`) that can + be optionally given to be used as output buffers + + Example:: + + >>> x = torch.randn(3, 4) + >>> sorted, indices = torch.sort(x) + >>> sorted + tensor([[-0.2162, 0.0608, 0.6719, 2.3332], + [-0.5793, 0.0061, 0.6058, 0.9497], + [-0.5071, 0.3343, 0.9553, 1.0960]]) + >>> indices + tensor([[ 1, 0, 2, 3], + [ 3, 1, 0, 2], + [ 0, 3, 1, 2]]) + + >>> sorted, indices = torch.sort(x, 0) + >>> sorted + tensor([[-0.5071, -0.2162, 0.6719, -0.5793], + [ 0.0608, 0.0061, 0.9497, 0.3343], + [ 0.6058, 0.9553, 1.0960, 2.3332]]) + >>> indices + tensor([[ 2, 0, 0, 1], + [ 0, 1, 1, 2], + [ 1, 2, 2, 0]]) + >>> x = torch.tensor([0, 1] * 9) + >>> x.sort() + torch.return_types.sort( + values=tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1]), + indices=tensor([ 2, 16, 4, 6, 14, 8, 0, 10, 12, 9, 17, 15, 13, 11, 7, 5, 3, 1])) + >>> x.sort(stable=True) + torch.return_types.sort( + values=tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1]), + indices=tensor([ 0, 2, 4, 6, 8, 10, 12, 14, 16, 1, 3, 5, 7, 9, 11, 13, 15, 17])) + """ + +@overload +def sort( + input: Tensor, + dim: _int = -1, + descending: _bool = False, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.sort: + r""" + sort(input, dim=-1, descending=False, *, stable=False, out=None) -> (Tensor, LongTensor) + + Sorts the elements of the :attr:`input` tensor along a given dimension + in ascending order by value. + + If :attr:`dim` is not given, the last dimension of the `input` is chosen. + + If :attr:`descending` is ``True`` then the elements are sorted in descending + order by value. + + If :attr:`stable` is ``True`` then the sorting routine becomes stable, preserving + the order of equivalent elements. + + A namedtuple of (values, indices) is returned, where the `values` are the + sorted values and `indices` are the indices of the elements in the original + `input` tensor. + + Args: + input (Tensor): the input tensor. + dim (int, optional): the dimension to sort along + descending (bool, optional): controls the sorting order (ascending or descending) + + Keyword args: + stable (bool, optional): makes the sorting routine stable, which guarantees that the order + of equivalent elements is preserved. + out (tuple, optional): the output tuple of (`Tensor`, `LongTensor`) that can + be optionally given to be used as output buffers + + Example:: + + >>> x = torch.randn(3, 4) + >>> sorted, indices = torch.sort(x) + >>> sorted + tensor([[-0.2162, 0.0608, 0.6719, 2.3332], + [-0.5793, 0.0061, 0.6058, 0.9497], + [-0.5071, 0.3343, 0.9553, 1.0960]]) + >>> indices + tensor([[ 1, 0, 2, 3], + [ 3, 1, 0, 2], + [ 0, 3, 1, 2]]) + + >>> sorted, indices = torch.sort(x, 0) + >>> sorted + tensor([[-0.5071, -0.2162, 0.6719, -0.5793], + [ 0.0608, 0.0061, 0.9497, 0.3343], + [ 0.6058, 0.9553, 1.0960, 2.3332]]) + >>> indices + tensor([[ 2, 0, 0, 1], + [ 0, 1, 1, 2], + [ 1, 2, 2, 0]]) + >>> x = torch.tensor([0, 1] * 9) + >>> x.sort() + torch.return_types.sort( + values=tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1]), + indices=tensor([ 2, 16, 4, 6, 14, 8, 0, 10, 12, 9, 17, 15, 13, 11, 7, 5, 3, 1])) + >>> x.sort(stable=True) + torch.return_types.sort( + values=tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1]), + indices=tensor([ 0, 2, 4, 6, 8, 10, 12, 14, 16, 1, 3, 5, 7, 9, 11, 13, 15, 17])) + """ + +@overload +def sort( + input: Tensor, + *, + stable: _bool | None, + dim: str | EllipsisType | None, + descending: _bool = False, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.sort: + r""" + sort(input, dim=-1, descending=False, *, stable=False, out=None) -> (Tensor, LongTensor) + + Sorts the elements of the :attr:`input` tensor along a given dimension + in ascending order by value. + + If :attr:`dim` is not given, the last dimension of the `input` is chosen. + + If :attr:`descending` is ``True`` then the elements are sorted in descending + order by value. + + If :attr:`stable` is ``True`` then the sorting routine becomes stable, preserving + the order of equivalent elements. + + A namedtuple of (values, indices) is returned, where the `values` are the + sorted values and `indices` are the indices of the elements in the original + `input` tensor. + + Args: + input (Tensor): the input tensor. + dim (int, optional): the dimension to sort along + descending (bool, optional): controls the sorting order (ascending or descending) + + Keyword args: + stable (bool, optional): makes the sorting routine stable, which guarantees that the order + of equivalent elements is preserved. + out (tuple, optional): the output tuple of (`Tensor`, `LongTensor`) that can + be optionally given to be used as output buffers + + Example:: + + >>> x = torch.randn(3, 4) + >>> sorted, indices = torch.sort(x) + >>> sorted + tensor([[-0.2162, 0.0608, 0.6719, 2.3332], + [-0.5793, 0.0061, 0.6058, 0.9497], + [-0.5071, 0.3343, 0.9553, 1.0960]]) + >>> indices + tensor([[ 1, 0, 2, 3], + [ 3, 1, 0, 2], + [ 0, 3, 1, 2]]) + + >>> sorted, indices = torch.sort(x, 0) + >>> sorted + tensor([[-0.5071, -0.2162, 0.6719, -0.5793], + [ 0.0608, 0.0061, 0.9497, 0.3343], + [ 0.6058, 0.9553, 1.0960, 2.3332]]) + >>> indices + tensor([[ 2, 0, 0, 1], + [ 0, 1, 1, 2], + [ 1, 2, 2, 0]]) + >>> x = torch.tensor([0, 1] * 9) + >>> x.sort() + torch.return_types.sort( + values=tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1]), + indices=tensor([ 2, 16, 4, 6, 14, 8, 0, 10, 12, 9, 17, 15, 13, 11, 7, 5, 3, 1])) + >>> x.sort(stable=True) + torch.return_types.sort( + values=tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1]), + indices=tensor([ 0, 2, 4, 6, 8, 10, 12, 14, 16, 1, 3, 5, 7, 9, 11, 13, 15, 17])) + """ + +@overload +def sort( + input: Tensor, + dim: str | EllipsisType | None, + descending: _bool = False, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.sort: + r""" + sort(input, dim=-1, descending=False, *, stable=False, out=None) -> (Tensor, LongTensor) + + Sorts the elements of the :attr:`input` tensor along a given dimension + in ascending order by value. + + If :attr:`dim` is not given, the last dimension of the `input` is chosen. + + If :attr:`descending` is ``True`` then the elements are sorted in descending + order by value. + + If :attr:`stable` is ``True`` then the sorting routine becomes stable, preserving + the order of equivalent elements. + + A namedtuple of (values, indices) is returned, where the `values` are the + sorted values and `indices` are the indices of the elements in the original + `input` tensor. + + Args: + input (Tensor): the input tensor. + dim (int, optional): the dimension to sort along + descending (bool, optional): controls the sorting order (ascending or descending) + + Keyword args: + stable (bool, optional): makes the sorting routine stable, which guarantees that the order + of equivalent elements is preserved. + out (tuple, optional): the output tuple of (`Tensor`, `LongTensor`) that can + be optionally given to be used as output buffers + + Example:: + + >>> x = torch.randn(3, 4) + >>> sorted, indices = torch.sort(x) + >>> sorted + tensor([[-0.2162, 0.0608, 0.6719, 2.3332], + [-0.5793, 0.0061, 0.6058, 0.9497], + [-0.5071, 0.3343, 0.9553, 1.0960]]) + >>> indices + tensor([[ 1, 0, 2, 3], + [ 3, 1, 0, 2], + [ 0, 3, 1, 2]]) + + >>> sorted, indices = torch.sort(x, 0) + >>> sorted + tensor([[-0.5071, -0.2162, 0.6719, -0.5793], + [ 0.0608, 0.0061, 0.9497, 0.3343], + [ 0.6058, 0.9553, 1.0960, 2.3332]]) + >>> indices + tensor([[ 2, 0, 0, 1], + [ 0, 1, 1, 2], + [ 1, 2, 2, 0]]) + >>> x = torch.tensor([0, 1] * 9) + >>> x.sort() + torch.return_types.sort( + values=tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1]), + indices=tensor([ 2, 16, 4, 6, 14, 8, 0, 10, 12, 9, 17, 15, 13, 11, 7, 5, 3, 1])) + >>> x.sort(stable=True) + torch.return_types.sort( + values=tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1]), + indices=tensor([ 0, 2, 4, 6, 8, 10, 12, 14, 16, 1, 3, 5, 7, 9, 11, 13, 15, 17])) + """ + +def sparse_bsc_tensor( + ccol_indices: Tensor | list, + row_indices: Tensor | list, + values: Tensor | list, + size: _size | None = None, + *, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + check_invariants: _bool | None = None, +) -> Tensor: + r""" + sparse_bsc_tensor(ccol_indices, row_indices, values, size=None, *, dtype=None, device=None, pin_memory=False, requires_grad=False, check_invariants=None) -> Tensor + + Constructs a :ref:`sparse tensor in BSC (Block Compressed Sparse + Column)) ` with specified 2-dimensional blocks at the + given :attr:`ccol_indices` and :attr:`row_indices`. Sparse matrix + multiplication operations in BSC format are typically faster than that + for sparse tensors in COO format. Make you have a look at :ref:`the + note on the data type of the indices `. + + .. note:: + + If the ``device`` argument is not specified the device of the given + :attr:`values` and indices tensor(s) must match. If, however, the + argument is specified the input Tensors will be converted to the + given device and in turn determine the device of the constructed + sparse tensor. + + Args: + ccol_indices (array_like): (B+1)-dimensional array of size + ``(*batchsize, ncolblocks + 1)``. The last element of each + batch is the number of non-zeros. This tensor encodes the + index in values and row_indices depending on where the given + column starts. Each successive number in the tensor subtracted + by the number before it denotes the number of elements in a + given column. + row_indices (array_like): Row block coordinates of each block in + values. (B+1)-dimensional tensor with the same length + as values. + values (array_list): Initial blocks for the tensor. Can be a list, + tuple, NumPy ``ndarray``, and other types that + represents a (1 + 2 + K)-dimensional tensor where ``K`` is the + number of dense dimensions. + size (list, tuple, :class:`torch.Size`, optional): Size of the + sparse tensor: ``(*batchsize, nrows * blocksize[0], ncols * + blocksize[1], *densesize)`` If not provided, the size will be + inferred as the minimum size big enough to hold all non-zero + blocks. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of + returned tensor. Default: if None, infers data type from + :attr:`values`. + device (:class:`torch.device`, optional): the desired device of + returned tensor. Default: if None, uses the current device + for the default tensor type (see + :func:`torch.set_default_device`). :attr:`device` will be + the CPU for CPU tensor types and the current CUDA device for + CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + check_invariants (bool, optional): If sparse tensor invariants are checked. + Default: as returned by :func:`torch.sparse.check_sparse_tensor_invariants.is_enabled`, + initially False. + + Example:: + + >>> ccol_indices = [0, 1, 2] + >>> row_indices = [0, 1] + >>> values = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]] + >>> torch.sparse_bsc_tensor(torch.tensor(ccol_indices, dtype=torch.int64), + ... torch.tensor(row_indices, dtype=torch.int64), + ... torch.tensor(values), dtype=torch.double) + tensor(ccol_indices=tensor([0, 1, 2]), + row_indices=tensor([0, 1]), + values=tensor([[[1., 2.], + [3., 4.]], + [[5., 6.], + [7., 8.]]]), size=(2, 2), nnz=2, dtype=torch.float64, + layout=torch.sparse_bsc) + """ + +def sparse_bsr_tensor( + crow_indices: Tensor | list, + col_indices: Tensor | list, + values: Tensor | list, + size: _size | None = None, + *, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + check_invariants: _bool | None = None, +) -> Tensor: + r""" + sparse_bsr_tensor(crow_indices, col_indices, values, size=None, *, dtype=None, device=None, pin_memory=False, requires_grad=False, check_invariants=None) -> Tensor + + Constructs a :ref:`sparse tensor in BSR (Block Compressed Sparse Row)) + ` with specified 2-dimensional blocks at the given + :attr:`crow_indices` and :attr:`col_indices`. Sparse matrix + multiplication operations in BSR format are typically faster than that + for sparse tensors in COO format. Make you have a look at :ref:`the + note on the data type of the indices `. + + .. note:: + + If the ``device`` argument is not specified the device of the given + :attr:`values` and indices tensor(s) must match. If, however, the + argument is specified the input Tensors will be converted to the + given device and in turn determine the device of the constructed + sparse tensor. + + Args: + crow_indices (array_like): (B+1)-dimensional array of size + ``(*batchsize, nrowblocks + 1)``. The last element of each + batch is the number of non-zeros. This tensor encodes the + block index in values and col_indices depending on where the + given row block starts. Each successive number in the tensor + subtracted by the number before it denotes the number of + blocks in a given row. + col_indices (array_like): Column block coordinates of each block + in values. (B+1)-dimensional tensor with the same length as + values. + values (array_list): Initial values for the tensor. Can be a list, + tuple, NumPy ``ndarray``, scalar, and other types that + represents a (1 + 2 + K)-dimensional tensor where ``K`` is the + number of dense dimensions. + size (list, tuple, :class:`torch.Size`, optional): Size of the + sparse tensor: ``(*batchsize, nrows * blocksize[0], ncols * + blocksize[1], *densesize)`` where ``blocksize == + values.shape[1:3]``. If not provided, the size will be + inferred as the minimum size big enough to hold all non-zero + blocks. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of + returned tensor. Default: if None, infers data type from + :attr:`values`. + device (:class:`torch.device`, optional): the desired device of + returned tensor. Default: if None, uses the current device + for the default tensor type (see + :func:`torch.set_default_device`). :attr:`device` will be + the CPU for CPU tensor types and the current CUDA device for + CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + check_invariants (bool, optional): If sparse tensor invariants are checked. + Default: as returned by :func:`torch.sparse.check_sparse_tensor_invariants.is_enabled`, + initially False. + + Example:: + + >>> crow_indices = [0, 1, 2] + >>> col_indices = [0, 1] + >>> values = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]] + >>> torch.sparse_bsr_tensor(torch.tensor(crow_indices, dtype=torch.int64), + ... torch.tensor(col_indices, dtype=torch.int64), + ... torch.tensor(values), dtype=torch.double) + tensor(crow_indices=tensor([0, 1, 2]), + col_indices=tensor([0, 1]), + values=tensor([[[1., 2.], + [3., 4.]], + [[5., 6.], + [7., 8.]]]), size=(2, 2), nnz=2, dtype=torch.float64, + layout=torch.sparse_bsr) + """ + +def sparse_compressed_tensor( + compressed_indices: Tensor | list, + plain_indices: Tensor | list, + values: Tensor | list, + size: _size | None = None, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + check_invariants: _bool | None = None, +) -> Tensor: + r""" + sparse_compressed_tensor(compressed_indices, plain_indices, values, size=None, *, dtype=None, layout=None, device=None, pin_memory=False, requires_grad=False, check_invariants=None) -> Tensor + + Constructs a :ref:`sparse tensor in Compressed Sparse format - CSR, + CSC, BSR, or BSC - ` with specified values at + the given :attr:`compressed_indices` and :attr:`plain_indices`. Sparse + matrix multiplication operations in Compressed Sparse format are + typically faster than that for sparse tensors in COO format. Make you + have a look at :ref:`the note on the data type of the indices + `. + + .. note:: + + If the ``device`` argument is not specified the device of the given + :attr:`values` and indices tensor(s) must match. If, however, the + argument is specified the input Tensors will be converted to the + given device and in turn determine the device of the constructed + sparse tensor. + + Args: + compressed_indices (array_like): (B+1)-dimensional array of size + ``(*batchsize, compressed_dim_size + 1)``. The last element of + each batch is the number of non-zero elements or blocks. This + tensor encodes the index in ``values`` and ``plain_indices`` + depending on where the given compressed dimension (row or + column) starts. Each successive number in the tensor + subtracted by the number before it denotes the number of + elements or blocks in a given compressed dimension. + plain_indices (array_like): Plain dimension (column or row) + coordinates of each element or block in values. (B+1)-dimensional + tensor with the same length as values. + + values (array_list): Initial values for the tensor. Can be a list, + tuple, NumPy ``ndarray``, scalar, and other types. that + represents a (1+K)-dimensional (for CSR and CSC layouts) or + (1+2+K)-dimensional tensor (for BSR and BSC layouts) where + ``K`` is the number of dense dimensions. + size (list, tuple, :class:`torch.Size`, optional): Size of the + sparse tensor: ``(*batchsize, nrows * blocksize[0], ncols * + blocksize[1], *densesize)`` where ``blocksize[0] == + blocksize[1] == 1`` for CSR and CSC formats. If not provided, + the size will be inferred as the minimum size big enough to + hold all non-zero elements or blocks. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of + returned tensor. Default: if None, infers data type from + :attr:`values`. + layout (:class:`torch.layout`, required): the desired layout of + returned tensor: :attr:`torch.sparse_csr`, + :attr:`torch.sparse_csc`, :attr:`torch.sparse_bsr`, or + :attr:`torch.sparse_bsc`. + device (:class:`torch.device`, optional): the desired device of + returned tensor. Default: if None, uses the current device + for the default tensor type (see + :func:`torch.set_default_device`). :attr:`device` will be + the CPU for CPU tensor types and the current CUDA device for + CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + check_invariants (bool, optional): If sparse tensor invariants are checked. + Default: as returned by :func:`torch.sparse.check_sparse_tensor_invariants.is_enabled`, + initially False. + + Example:: + + >>> compressed_indices = [0, 2, 4] + >>> plain_indices = [0, 1, 0, 1] + >>> values = [1, 2, 3, 4] + >>> torch.sparse_compressed_tensor(torch.tensor(compressed_indices, dtype=torch.int64), + ... torch.tensor(plain_indices, dtype=torch.int64), + ... torch.tensor(values), dtype=torch.double, layout=torch.sparse_csr) + tensor(crow_indices=tensor([0, 2, 4]), + col_indices=tensor([0, 1, 0, 1]), + values=tensor([1., 2., 3., 4.]), size=(2, 2), nnz=4, + dtype=torch.float64, layout=torch.sparse_csr) + """ + +def sparse_coo_tensor( + indices: Tensor, + values: Tensor | list, + size: _size | None = None, + *, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + check_invariants: _bool | None = None, + is_coalesced: _bool | None = None, +) -> Tensor: + r""" + sparse_coo_tensor(indices, values, size=None, *, dtype=None, device=None, pin_memory=False, requires_grad=False, check_invariants=None, is_coalesced=None) -> Tensor + + Constructs a :ref:`sparse tensor in COO(rdinate) format + ` with specified values at the given + :attr:`indices`. + + .. note:: + + This function returns an :ref:`uncoalesced tensor + ` when :attr:`is_coalesced` is + unspecified or ``None``. + + .. note:: + + If the ``device`` argument is not specified the device of the given + :attr:`values` and indices tensor(s) must match. If, however, the + argument is specified the input Tensors will be converted to the + given device and in turn determine the device of the constructed + sparse tensor. + + Args: + indices (array_like): Initial data for the tensor. Can be a list, tuple, + NumPy ``ndarray``, scalar, and other types. Will be cast to a :class:`torch.LongTensor` + internally. The indices are the coordinates of the non-zero values in the matrix, and thus + should be two-dimensional where the first dimension is the number of tensor dimensions and + the second dimension is the number of non-zero values. + values (array_like): Initial values for the tensor. Can be a list, tuple, + NumPy ``ndarray``, scalar, and other types. + size (list, tuple, or :class:`torch.Size`, optional): Size of the sparse tensor. If not + provided the size will be inferred as the minimum size big enough to hold all non-zero + elements. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if None, infers data type from :attr:`values`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if None, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + check_invariants (bool, optional): If sparse tensor invariants are checked. + Default: as returned by :func:`torch.sparse.check_sparse_tensor_invariants.is_enabled`, + initially False. + is_coalesced (bool, optional): When``True``, the caller is + responsible for providing tensor indices that correspond to a + coalesced tensor. If the :attr:`check_invariants` flag is + False, no error will be raised if the prerequisites are not + met and this will lead to silently incorrect results. To force + coalescion please use :meth:`coalesce` on the resulting + Tensor. + Default: None: except for trivial cases (e.g. nnz < 2) the + resulting Tensor has is_coalesced set to ``False```. + + Example:: + + >>> i = torch.tensor([[0, 1, 1], + ... [2, 0, 2]]) + >>> v = torch.tensor([3, 4, 5], dtype=torch.float32) + >>> torch.sparse_coo_tensor(i, v, [2, 4]) + tensor(indices=tensor([[0, 1, 1], + [2, 0, 2]]), + values=tensor([3., 4., 5.]), + size=(2, 4), nnz=3, layout=torch.sparse_coo) + + >>> torch.sparse_coo_tensor(i, v) # Shape inference + tensor(indices=tensor([[0, 1, 1], + [2, 0, 2]]), + values=tensor([3., 4., 5.]), + size=(2, 3), nnz=3, layout=torch.sparse_coo) + + >>> torch.sparse_coo_tensor(i, v, [2, 4], + ... dtype=torch.float64, + ... device=torch.device('cuda:0')) + tensor(indices=tensor([[0, 1, 1], + [2, 0, 2]]), + values=tensor([3., 4., 5.]), + device='cuda:0', size=(2, 4), nnz=3, dtype=torch.float64, + layout=torch.sparse_coo) + + # Create an empty sparse tensor with the following invariants: + # 1. sparse_dim + dense_dim = len(SparseTensor.shape) + # 2. SparseTensor._indices().shape = (sparse_dim, nnz) + # 3. SparseTensor._values().shape = (nnz, SparseTensor.shape[sparse_dim:]) + # + # For instance, to create an empty sparse tensor with nnz = 0, dense_dim = 0 and + # sparse_dim = 1 (hence indices is a 2D tensor of shape = (1, 0)) + >>> S = torch.sparse_coo_tensor(torch.empty([1, 0]), [], [1]) + tensor(indices=tensor([], size=(1, 0)), + values=tensor([], size=(0,)), + size=(1,), nnz=0, layout=torch.sparse_coo) + + # and to create an empty sparse tensor with nnz = 0, dense_dim = 1 and + # sparse_dim = 1 + >>> S = torch.sparse_coo_tensor(torch.empty([1, 0]), torch.empty([0, 2]), [1, 2]) + tensor(indices=tensor([], size=(1, 0)), + values=tensor([], size=(0, 2)), + size=(1, 2), nnz=0, layout=torch.sparse_coo) + + .. _torch.sparse: https://pytorch.org/docs/stable/sparse.html + """ + +def sparse_csc_tensor( + ccol_indices: Tensor | list, + row_indices: Tensor | list, + values: Tensor | list, + size: _size | None = None, + *, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + check_invariants: _bool | None = None, +) -> Tensor: + r""" + sparse_csc_tensor(ccol_indices, row_indices, values, size=None, *, dtype=None, device=None, pin_memory=False, requires_grad=False, check_invariants=None) -> Tensor + + Constructs a :ref:`sparse tensor in CSC (Compressed Sparse Column) + ` with specified values at the given + :attr:`ccol_indices` and :attr:`row_indices`. Sparse matrix + multiplication operations in CSC format are typically faster than that + for sparse tensors in COO format. Make you have a look at :ref:`the + note on the data type of the indices `. + + .. note:: + + If the ``device`` argument is not specified the device of the given + :attr:`values` and indices tensor(s) must match. If, however, the + argument is specified the input Tensors will be converted to the + given device and in turn determine the device of the constructed + sparse tensor. + + Args: + ccol_indices (array_like): (B+1)-dimensional array of size + ``(*batchsize, ncols + 1)``. The last element of each batch + is the number of non-zeros. This tensor encodes the index in + values and row_indices depending on where the given column + starts. Each successive number in the tensor subtracted by the + number before it denotes the number of elements in a given + column. + row_indices (array_like): Row coordinates of each element in + values. (B+1)-dimensional tensor with the same length as + values. + values (array_list): Initial values for the tensor. Can be a list, + tuple, NumPy ``ndarray``, scalar, and other types that + represents a (1+K)-dimensional tensor where ``K`` is the number + of dense dimensions. + size (list, tuple, :class:`torch.Size`, optional): Size of the + sparse tensor: ``(*batchsize, nrows, ncols, *densesize)``. If + not provided, the size will be inferred as the minimum size + big enough to hold all non-zero elements. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of + returned tensor. Default: if None, infers data type from + :attr:`values`. + device (:class:`torch.device`, optional): the desired device of + returned tensor. Default: if None, uses the current device + for the default tensor type (see + :func:`torch.set_default_device`). :attr:`device` will be + the CPU for CPU tensor types and the current CUDA device for + CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + check_invariants (bool, optional): If sparse tensor invariants are checked. + Default: as returned by :func:`torch.sparse.check_sparse_tensor_invariants.is_enabled`, + initially False. + + Example:: + + >>> ccol_indices = [0, 2, 4] + >>> row_indices = [0, 1, 0, 1] + >>> values = [1, 2, 3, 4] + >>> torch.sparse_csc_tensor(torch.tensor(ccol_indices, dtype=torch.int64), + ... torch.tensor(row_indices, dtype=torch.int64), + ... torch.tensor(values), dtype=torch.double) + tensor(ccol_indices=tensor([0, 2, 4]), + row_indices=tensor([0, 1, 0, 1]), + values=tensor([1., 2., 3., 4.]), size=(2, 2), nnz=4, + dtype=torch.float64, layout=torch.sparse_csc) + """ + +def sparse_csr_tensor( + crow_indices: Tensor | list, + col_indices: Tensor | list, + values: Tensor | list, + size: _size | None = None, + *, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + check_invariants: _bool | None = None, +) -> Tensor: + r""" + sparse_csr_tensor(crow_indices, col_indices, values, size=None, *, dtype=None, device=None, pin_memory=False, requires_grad=False, check_invariants=None) -> Tensor + + Constructs a :ref:`sparse tensor in CSR (Compressed Sparse Row) ` with specified + values at the given :attr:`crow_indices` and :attr:`col_indices`. Sparse matrix multiplication operations + in CSR format are typically faster than that for sparse tensors in COO format. Make you have a look + at :ref:`the note on the data type of the indices `. + + .. note:: + + If the ``device`` argument is not specified the device of the given + :attr:`values` and indices tensor(s) must match. If, however, the + argument is specified the input Tensors will be converted to the + given device and in turn determine the device of the constructed + sparse tensor. + + Args: + crow_indices (array_like): (B+1)-dimensional array of size + ``(*batchsize, nrows + 1)``. The last element of each batch + is the number of non-zeros. This tensor encodes the index in + values and col_indices depending on where the given row + starts. Each successive number in the tensor subtracted by the + number before it denotes the number of elements in a given + row. + col_indices (array_like): Column coordinates of each element in + values. (B+1)-dimensional tensor with the same length + as values. + values (array_list): Initial values for the tensor. Can be a list, + tuple, NumPy ``ndarray``, scalar, and other types that + represents a (1+K)-dimensional tensor where ``K`` is the number + of dense dimensions. + size (list, tuple, :class:`torch.Size`, optional): Size of the + sparse tensor: ``(*batchsize, nrows, ncols, *densesize)``. If + not provided, the size will be inferred as the minimum size + big enough to hold all non-zero elements. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of + returned tensor. Default: if None, infers data type from + :attr:`values`. + device (:class:`torch.device`, optional): the desired device of + returned tensor. Default: if None, uses the current device + for the default tensor type (see + :func:`torch.set_default_device`). :attr:`device` will be + the CPU for CPU tensor types and the current CUDA device for + CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + check_invariants (bool, optional): If sparse tensor invariants are checked. + Default: as returned by :func:`torch.sparse.check_sparse_tensor_invariants.is_enabled`, + initially False. + + Example:: + + >>> crow_indices = [0, 2, 4] + >>> col_indices = [0, 1, 0, 1] + >>> values = [1, 2, 3, 4] + >>> torch.sparse_csr_tensor(torch.tensor(crow_indices, dtype=torch.int64), + ... torch.tensor(col_indices, dtype=torch.int64), + ... torch.tensor(values), dtype=torch.double) + tensor(crow_indices=tensor([0, 2, 4]), + col_indices=tensor([0, 1, 0, 1]), + values=tensor([1., 2., 3., 4.]), size=(2, 2), nnz=4, + dtype=torch.float64, layout=torch.sparse_csr) + """ + +def split_copy( + input: Tensor, + split_size: _int | SymInt, + dim: _int = 0, + *, + out: tuple[Tensor, ...] | list[Tensor] | None = None, +) -> None: + r""" + Performs the same operation as :func:`torch.split`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def split_with_sizes( + input: Tensor, + split_sizes: Sequence[_int | SymInt], + dim: _int = 0, +) -> tuple[Tensor, ...]: ... +def split_with_sizes_copy( + input: Tensor, + split_sizes: Sequence[_int | SymInt], + dim: _int = 0, + *, + out: tuple[Tensor, ...] | list[Tensor] | None = None, +) -> None: + r""" + Performs the same operation as :func:`torch.split_with_sizes`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def spmm(input: Tensor, mat2: Tensor) -> Tensor: ... +def sqrt(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + sqrt(input, *, out=None) -> Tensor + + Returns a new tensor with the square-root of the elements of :attr:`input`. + + .. math:: + \text{out}_{i} = \sqrt{\text{input}_{i}} + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-2.0755, 1.0226, 0.0831, 0.4806]) + >>> torch.sqrt(a) + tensor([ nan, 1.0112, 0.2883, 0.6933]) + """ + +def sqrt_(input: Tensor) -> Tensor: ... +def square(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + square(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Returns a new tensor with the square of the elements of :attr:`input`. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-2.0755, 1.0226, 0.0831, 0.4806]) + >>> torch.square(a) + tensor([ 4.3077, 1.0457, 0.0069, 0.2310]) + """ + +def square_(input: Tensor) -> Tensor: ... +@overload +def squeeze(input: Tensor) -> Tensor: + r""" + squeeze(input: Tensor, dim: Optional[Union[int, List[int]]]) -> Tensor + + Returns a tensor with all specified dimensions of :attr:`input` of size `1` removed. + + For example, if `input` is of shape: + :math:`(A \times 1 \times B \times C \times 1 \times D)` then the `input.squeeze()` + will be of shape: :math:`(A \times B \times C \times D)`. + + When :attr:`dim` is given, a squeeze operation is done only in the given + dimension(s). If `input` is of shape: :math:`(A \times 1 \times B)`, + ``squeeze(input, 0)`` leaves the tensor unchanged, but ``squeeze(input, 1)`` + will squeeze the tensor to the shape :math:`(A \times B)`. + + .. note:: The returned tensor shares the storage with the input tensor, + so changing the contents of one will change the contents of the other. + + .. warning:: If the tensor has a batch dimension of size 1, then `squeeze(input)` + will also remove the batch dimension, which can lead to unexpected + errors. Consider specifying only the dims you wish to be squeezed. + + Args: + input (Tensor): the input tensor. + dim (int or tuple of ints, optional): if given, the input will be squeezed + only in the specified dimensions. + + .. versionchanged:: 2.0 + :attr:`dim` now accepts tuples of dimensions. + + Example:: + + >>> x = torch.zeros(2, 1, 2, 1, 2) + >>> x.size() + torch.Size([2, 1, 2, 1, 2]) + >>> y = torch.squeeze(x) + >>> y.size() + torch.Size([2, 2, 2]) + >>> y = torch.squeeze(x, 0) + >>> y.size() + torch.Size([2, 1, 2, 1, 2]) + >>> y = torch.squeeze(x, 1) + >>> y.size() + torch.Size([2, 2, 1, 2]) + >>> y = torch.squeeze(x, (1, 2, 3)) + torch.Size([2, 2, 2]) + """ + +@overload +def squeeze(input: Tensor, dim: _int) -> Tensor: + r""" + squeeze(input: Tensor, dim: Optional[Union[int, List[int]]]) -> Tensor + + Returns a tensor with all specified dimensions of :attr:`input` of size `1` removed. + + For example, if `input` is of shape: + :math:`(A \times 1 \times B \times C \times 1 \times D)` then the `input.squeeze()` + will be of shape: :math:`(A \times B \times C \times D)`. + + When :attr:`dim` is given, a squeeze operation is done only in the given + dimension(s). If `input` is of shape: :math:`(A \times 1 \times B)`, + ``squeeze(input, 0)`` leaves the tensor unchanged, but ``squeeze(input, 1)`` + will squeeze the tensor to the shape :math:`(A \times B)`. + + .. note:: The returned tensor shares the storage with the input tensor, + so changing the contents of one will change the contents of the other. + + .. warning:: If the tensor has a batch dimension of size 1, then `squeeze(input)` + will also remove the batch dimension, which can lead to unexpected + errors. Consider specifying only the dims you wish to be squeezed. + + Args: + input (Tensor): the input tensor. + dim (int or tuple of ints, optional): if given, the input will be squeezed + only in the specified dimensions. + + .. versionchanged:: 2.0 + :attr:`dim` now accepts tuples of dimensions. + + Example:: + + >>> x = torch.zeros(2, 1, 2, 1, 2) + >>> x.size() + torch.Size([2, 1, 2, 1, 2]) + >>> y = torch.squeeze(x) + >>> y.size() + torch.Size([2, 2, 2]) + >>> y = torch.squeeze(x, 0) + >>> y.size() + torch.Size([2, 1, 2, 1, 2]) + >>> y = torch.squeeze(x, 1) + >>> y.size() + torch.Size([2, 2, 1, 2]) + >>> y = torch.squeeze(x, (1, 2, 3)) + torch.Size([2, 2, 2]) + """ + +@overload +def squeeze(input: Tensor, dim: _size) -> Tensor: + r""" + squeeze(input: Tensor, dim: Optional[Union[int, List[int]]]) -> Tensor + + Returns a tensor with all specified dimensions of :attr:`input` of size `1` removed. + + For example, if `input` is of shape: + :math:`(A \times 1 \times B \times C \times 1 \times D)` then the `input.squeeze()` + will be of shape: :math:`(A \times B \times C \times D)`. + + When :attr:`dim` is given, a squeeze operation is done only in the given + dimension(s). If `input` is of shape: :math:`(A \times 1 \times B)`, + ``squeeze(input, 0)`` leaves the tensor unchanged, but ``squeeze(input, 1)`` + will squeeze the tensor to the shape :math:`(A \times B)`. + + .. note:: The returned tensor shares the storage with the input tensor, + so changing the contents of one will change the contents of the other. + + .. warning:: If the tensor has a batch dimension of size 1, then `squeeze(input)` + will also remove the batch dimension, which can lead to unexpected + errors. Consider specifying only the dims you wish to be squeezed. + + Args: + input (Tensor): the input tensor. + dim (int or tuple of ints, optional): if given, the input will be squeezed + only in the specified dimensions. + + .. versionchanged:: 2.0 + :attr:`dim` now accepts tuples of dimensions. + + Example:: + + >>> x = torch.zeros(2, 1, 2, 1, 2) + >>> x.size() + torch.Size([2, 1, 2, 1, 2]) + >>> y = torch.squeeze(x) + >>> y.size() + torch.Size([2, 2, 2]) + >>> y = torch.squeeze(x, 0) + >>> y.size() + torch.Size([2, 1, 2, 1, 2]) + >>> y = torch.squeeze(x, 1) + >>> y.size() + torch.Size([2, 2, 1, 2]) + >>> y = torch.squeeze(x, (1, 2, 3)) + torch.Size([2, 2, 2]) + """ + +@overload +def squeeze(input: Tensor, dim: str | EllipsisType | None) -> Tensor: + r""" + squeeze(input: Tensor, dim: Optional[Union[int, List[int]]]) -> Tensor + + Returns a tensor with all specified dimensions of :attr:`input` of size `1` removed. + + For example, if `input` is of shape: + :math:`(A \times 1 \times B \times C \times 1 \times D)` then the `input.squeeze()` + will be of shape: :math:`(A \times B \times C \times D)`. + + When :attr:`dim` is given, a squeeze operation is done only in the given + dimension(s). If `input` is of shape: :math:`(A \times 1 \times B)`, + ``squeeze(input, 0)`` leaves the tensor unchanged, but ``squeeze(input, 1)`` + will squeeze the tensor to the shape :math:`(A \times B)`. + + .. note:: The returned tensor shares the storage with the input tensor, + so changing the contents of one will change the contents of the other. + + .. warning:: If the tensor has a batch dimension of size 1, then `squeeze(input)` + will also remove the batch dimension, which can lead to unexpected + errors. Consider specifying only the dims you wish to be squeezed. + + Args: + input (Tensor): the input tensor. + dim (int or tuple of ints, optional): if given, the input will be squeezed + only in the specified dimensions. + + .. versionchanged:: 2.0 + :attr:`dim` now accepts tuples of dimensions. + + Example:: + + >>> x = torch.zeros(2, 1, 2, 1, 2) + >>> x.size() + torch.Size([2, 1, 2, 1, 2]) + >>> y = torch.squeeze(x) + >>> y.size() + torch.Size([2, 2, 2]) + >>> y = torch.squeeze(x, 0) + >>> y.size() + torch.Size([2, 1, 2, 1, 2]) + >>> y = torch.squeeze(x, 1) + >>> y.size() + torch.Size([2, 2, 1, 2]) + >>> y = torch.squeeze(x, (1, 2, 3)) + torch.Size([2, 2, 2]) + """ + +@overload +def squeeze_copy(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + Performs the same operation as :func:`torch.squeeze`, but all output tensors + are freshly created instead of aliasing the input. + """ + +@overload +def squeeze_copy( + input: Tensor, + dim: _int, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.squeeze`, but all output tensors + are freshly created instead of aliasing the input. + """ + +@overload +def squeeze_copy( + input: Tensor, + dim: _size, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.squeeze`, but all output tensors + are freshly created instead of aliasing the input. + """ + +@overload +def sspaddmm( + beta: Number | _complex, + self: Tensor, + alpha: Number | _complex, + mat1: Tensor, + mat2: Tensor, +) -> Tensor: + r""" + sspaddmm(input, mat1, mat2, *, beta=1, alpha=1, out=None) -> Tensor + + Matrix multiplies a sparse tensor :attr:`mat1` with a dense tensor + :attr:`mat2`, then adds the sparse tensor :attr:`input` to the result. + + Note: This function is equivalent to :func:`torch.addmm`, except + :attr:`input` and :attr:`mat1` are sparse. + + Args: + input (Tensor): a sparse matrix to be added + mat1 (Tensor): a sparse matrix to be matrix multiplied + mat2 (Tensor): a dense matrix to be matrix multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`mat` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + """ + +@overload +def sspaddmm( + input: Tensor, + mat1: Tensor, + mat2: Tensor, + *, + beta: Number | _complex = 1, + alpha: Number | _complex = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + sspaddmm(input, mat1, mat2, *, beta=1, alpha=1, out=None) -> Tensor + + Matrix multiplies a sparse tensor :attr:`mat1` with a dense tensor + :attr:`mat2`, then adds the sparse tensor :attr:`input` to the result. + + Note: This function is equivalent to :func:`torch.addmm`, except + :attr:`input` and :attr:`mat1` are sparse. + + Args: + input (Tensor): a sparse matrix to be added + mat1 (Tensor): a sparse matrix to be matrix multiplied + mat2 (Tensor): a dense matrix to be matrix multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`mat` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + """ + +@overload +def sspaddmm( + beta: Number | _complex, + self: Tensor, + mat1: Tensor, + mat2: Tensor, +) -> Tensor: + r""" + sspaddmm(input, mat1, mat2, *, beta=1, alpha=1, out=None) -> Tensor + + Matrix multiplies a sparse tensor :attr:`mat1` with a dense tensor + :attr:`mat2`, then adds the sparse tensor :attr:`input` to the result. + + Note: This function is equivalent to :func:`torch.addmm`, except + :attr:`input` and :attr:`mat1` are sparse. + + Args: + input (Tensor): a sparse matrix to be added + mat1 (Tensor): a sparse matrix to be matrix multiplied + mat2 (Tensor): a dense matrix to be matrix multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`mat` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + """ + +def stack( + tensors: tuple[Tensor, ...] | list[Tensor] | None, + dim: _int = 0, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + stack(tensors, dim=0, *, out=None) -> Tensor + + Concatenates a sequence of tensors along a new dimension. + + All tensors need to be of the same size. + + .. seealso:: + + :func:`torch.cat` concatenates the given sequence along an existing dimension. + + Arguments: + tensors (sequence of Tensors): sequence of tensors to concatenate + dim (int, optional): dimension to insert. Has to be between 0 and the number + of dimensions of concatenated tensors (inclusive). Default: 0 + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> x = torch.randn(2, 3) + >>> x + tensor([[ 0.3367, 0.1288, 0.2345], + [ 0.2303, -1.1229, -0.1863]]) + >>> torch.stack((x, x)) # same as torch.stack((x, x), dim=0) + tensor([[[ 0.3367, 0.1288, 0.2345], + [ 0.2303, -1.1229, -0.1863]], + + [[ 0.3367, 0.1288, 0.2345], + [ 0.2303, -1.1229, -0.1863]]]) + >>> torch.stack((x, x)).size() + torch.Size([2, 2, 3]) + >>> torch.stack((x, x), dim=1) + tensor([[[ 0.3367, 0.1288, 0.2345], + [ 0.3367, 0.1288, 0.2345]], + + [[ 0.2303, -1.1229, -0.1863], + [ 0.2303, -1.1229, -0.1863]]]) + >>> torch.stack((x, x), dim=2) + tensor([[[ 0.3367, 0.3367], + [ 0.1288, 0.1288], + [ 0.2345, 0.2345]], + + [[ 0.2303, 0.2303], + [-1.1229, -1.1229], + [-0.1863, -0.1863]]]) + >>> torch.stack((x, x), dim=-1) + tensor([[[ 0.3367, 0.3367], + [ 0.1288, 0.1288], + [ 0.2345, 0.2345]], + + [[ 0.2303, 0.2303], + [-1.1229, -1.1229], + [-0.1863, -0.1863]]]) + """ + +@overload +def std( + input: Tensor, + dim: _int | _size | None, + unbiased: _bool = True, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + std(input, dim=None, *, correction=1, keepdim=False, out=None) -> Tensor + + Calculates the standard deviation over the dimensions specified by :attr:`dim`. + :attr:`dim` can be a single dimension, list of dimensions, or ``None`` to + reduce over all dimensions. + + The standard deviation (:math:`\sigma`) is calculated as + + .. math:: \sigma = \sqrt{\frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2} + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.std(a, dim=1, keepdim=True) + tensor([[1.0311], + [0.7477], + [1.2204], + [0.9087]]) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def std( + input: Tensor, + dim: _int | _size | None = None, + *, + correction: Number | _complex | None = None, + keepdim: _bool = False, + out: Tensor | None = None, +) -> Tensor: + r""" + std(input, dim=None, *, correction=1, keepdim=False, out=None) -> Tensor + + Calculates the standard deviation over the dimensions specified by :attr:`dim`. + :attr:`dim` can be a single dimension, list of dimensions, or ``None`` to + reduce over all dimensions. + + The standard deviation (:math:`\sigma`) is calculated as + + .. math:: \sigma = \sqrt{\frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2} + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.std(a, dim=1, keepdim=True) + tensor([[1.0311], + [0.7477], + [1.2204], + [0.9087]]) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def std(input: Tensor, unbiased: _bool = True) -> Tensor: + r""" + std(input, dim=None, *, correction=1, keepdim=False, out=None) -> Tensor + + Calculates the standard deviation over the dimensions specified by :attr:`dim`. + :attr:`dim` can be a single dimension, list of dimensions, or ``None`` to + reduce over all dimensions. + + The standard deviation (:math:`\sigma`) is calculated as + + .. math:: \sigma = \sqrt{\frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2} + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.std(a, dim=1, keepdim=True) + tensor([[1.0311], + [0.7477], + [1.2204], + [0.9087]]) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def std( + input: Tensor, + dim: Sequence[str | EllipsisType | None], + *, + correction: Number | _complex | None = None, + keepdim: _bool = False, + out: Tensor | None = None, +) -> Tensor: + r""" + std(input, dim=None, *, correction=1, keepdim=False, out=None) -> Tensor + + Calculates the standard deviation over the dimensions specified by :attr:`dim`. + :attr:`dim` can be a single dimension, list of dimensions, or ``None`` to + reduce over all dimensions. + + The standard deviation (:math:`\sigma`) is calculated as + + .. math:: \sigma = \sqrt{\frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2} + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.std(a, dim=1, keepdim=True) + tensor([[1.0311], + [0.7477], + [1.2204], + [0.9087]]) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def std( + input: Tensor, + dim: Sequence[str | EllipsisType | None], + unbiased: _bool = True, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + std(input, dim=None, *, correction=1, keepdim=False, out=None) -> Tensor + + Calculates the standard deviation over the dimensions specified by :attr:`dim`. + :attr:`dim` can be a single dimension, list of dimensions, or ``None`` to + reduce over all dimensions. + + The standard deviation (:math:`\sigma`) is calculated as + + .. math:: \sigma = \sqrt{\frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2} + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.std(a, dim=1, keepdim=True) + tensor([[1.0311], + [0.7477], + [1.2204], + [0.9087]]) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def std_mean( + input: Tensor, + dim: _int | _size | None, + unbiased: _bool = True, + keepdim: _bool = False, +) -> tuple[Tensor, Tensor]: + r""" + std_mean(input, dim=None, *, correction=1, keepdim=False, out=None) -> (Tensor, Tensor) + + Calculates the standard deviation and mean over the dimensions specified by + :attr:`dim`. :attr:`dim` can be a single dimension, list of dimensions, or + ``None`` to reduce over all dimensions. + + The standard deviation (:math:`\sigma`) is calculated as + + .. math:: \sigma = \sqrt{\frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2} + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Returns: + A tuple (std, mean) containing the standard deviation and mean. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.std_mean(a, dim=0, keepdim=True) + (tensor([[1.2620, 1.0028, 1.0957, 0.6038]]), + tensor([[ 0.0645, 0.4485, 0.8707, -0.0665]])) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def std_mean( + input: Tensor, + dim: _int | _size | None = None, + *, + correction: Number | _complex | None = None, + keepdim: _bool = False, +) -> tuple[Tensor, Tensor]: + r""" + std_mean(input, dim=None, *, correction=1, keepdim=False, out=None) -> (Tensor, Tensor) + + Calculates the standard deviation and mean over the dimensions specified by + :attr:`dim`. :attr:`dim` can be a single dimension, list of dimensions, or + ``None`` to reduce over all dimensions. + + The standard deviation (:math:`\sigma`) is calculated as + + .. math:: \sigma = \sqrt{\frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2} + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Returns: + A tuple (std, mean) containing the standard deviation and mean. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.std_mean(a, dim=0, keepdim=True) + (tensor([[1.2620, 1.0028, 1.0957, 0.6038]]), + tensor([[ 0.0645, 0.4485, 0.8707, -0.0665]])) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def std_mean( + input: Tensor, + unbiased: _bool = True, +) -> tuple[Tensor, Tensor]: + r""" + std_mean(input, dim=None, *, correction=1, keepdim=False, out=None) -> (Tensor, Tensor) + + Calculates the standard deviation and mean over the dimensions specified by + :attr:`dim`. :attr:`dim` can be a single dimension, list of dimensions, or + ``None`` to reduce over all dimensions. + + The standard deviation (:math:`\sigma`) is calculated as + + .. math:: \sigma = \sqrt{\frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2} + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Returns: + A tuple (std, mean) containing the standard deviation and mean. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.std_mean(a, dim=0, keepdim=True) + (tensor([[1.2620, 1.0028, 1.0957, 0.6038]]), + tensor([[ 0.0645, 0.4485, 0.8707, -0.0665]])) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def std_mean( + input: Tensor, + dim: Sequence[str | EllipsisType | None], + *, + correction: Number | _complex | None = None, + keepdim: _bool = False, +) -> tuple[Tensor, Tensor]: + r""" + std_mean(input, dim=None, *, correction=1, keepdim=False, out=None) -> (Tensor, Tensor) + + Calculates the standard deviation and mean over the dimensions specified by + :attr:`dim`. :attr:`dim` can be a single dimension, list of dimensions, or + ``None`` to reduce over all dimensions. + + The standard deviation (:math:`\sigma`) is calculated as + + .. math:: \sigma = \sqrt{\frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2} + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Returns: + A tuple (std, mean) containing the standard deviation and mean. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.std_mean(a, dim=0, keepdim=True) + (tensor([[1.2620, 1.0028, 1.0957, 0.6038]]), + tensor([[ 0.0645, 0.4485, 0.8707, -0.0665]])) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def std_mean( + input: Tensor, + dim: Sequence[str | EllipsisType | None], + unbiased: _bool = True, + keepdim: _bool = False, +) -> tuple[Tensor, Tensor]: + r""" + std_mean(input, dim=None, *, correction=1, keepdim=False, out=None) -> (Tensor, Tensor) + + Calculates the standard deviation and mean over the dimensions specified by + :attr:`dim`. :attr:`dim` can be a single dimension, list of dimensions, or + ``None`` to reduce over all dimensions. + + The standard deviation (:math:`\sigma`) is calculated as + + .. math:: \sigma = \sqrt{\frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2} + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Returns: + A tuple (std, mean) containing the standard deviation and mean. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.std_mean(a, dim=0, keepdim=True) + (tensor([[1.2620, 1.0028, 1.0957, 0.6038]]), + tensor([[ 0.0645, 0.4485, 0.8707, -0.0665]])) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def sub( + input: Tensor | Number | _complex, + other: Tensor | Number | _complex, + *, + alpha: Number | _complex | None = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + sub(input, other, *, alpha=1, out=None) -> Tensor + + Subtracts :attr:`other`, scaled by :attr:`alpha`, from :attr:`input`. + + .. math:: + \text{{out}}_i = \text{{input}}_i - \text{{alpha}} \times \text{{other}}_i + + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer, float, and complex inputs. + + Args: + input (Tensor): the input tensor. + other (Tensor or Number): the tensor or number to subtract from :attr:`input`. + + Keyword args: + alpha (Number): the multiplier for :attr:`other`. + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor((1, 2)) + >>> b = torch.tensor((0, 1)) + >>> torch.sub(a, b, alpha=2) + tensor([1, 0]) + """ + +@overload +def sub(self: Tensor, alpha: Number | _complex, other: Tensor) -> Tensor: + r""" + sub(input, other, *, alpha=1, out=None) -> Tensor + + Subtracts :attr:`other`, scaled by :attr:`alpha`, from :attr:`input`. + + .. math:: + \text{{out}}_i = \text{{input}}_i - \text{{alpha}} \times \text{{other}}_i + + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer, float, and complex inputs. + + Args: + input (Tensor): the input tensor. + other (Tensor or Number): the tensor or number to subtract from :attr:`input`. + + Keyword args: + alpha (Number): the multiplier for :attr:`other`. + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor((1, 2)) + >>> b = torch.tensor((0, 1)) + >>> torch.sub(a, b, alpha=2) + tensor([1, 0]) + """ + +@overload +def sub( + self: Tensor, + alpha: Number | _complex, + other: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + sub(input, other, *, alpha=1, out=None) -> Tensor + + Subtracts :attr:`other`, scaled by :attr:`alpha`, from :attr:`input`. + + .. math:: + \text{{out}}_i = \text{{input}}_i - \text{{alpha}} \times \text{{other}}_i + + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer, float, and complex inputs. + + Args: + input (Tensor): the input tensor. + other (Tensor or Number): the tensor or number to subtract from :attr:`input`. + + Keyword args: + alpha (Number): the multiplier for :attr:`other`. + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor((1, 2)) + >>> b = torch.tensor((0, 1)) + >>> torch.sub(a, b, alpha=2) + tensor([1, 0]) + """ + +@overload +def subtract( + input: Tensor, + other: Tensor, + *, + alpha: Number | _complex = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + subtract(input, other, *, alpha=1, out=None) -> Tensor + + Alias for :func:`torch.sub`. + """ + +@overload +def subtract( + input: Tensor, + other: Number | _complex, + alpha: Number | _complex = 1, +) -> Tensor: + r""" + subtract(input, other, *, alpha=1, out=None) -> Tensor + + Alias for :func:`torch.sub`. + """ + +@overload +def sum(input: Tensor, *, dtype: _dtype | None = None) -> Tensor: + r""" + sum(input, *, dtype=None) -> Tensor + + Returns the sum of all elements in the :attr:`input` tensor. + + Args: + input (Tensor): the input tensor. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + + .. note:: Use the `dtype` argument if you need the result in a specific tensor type. + Otherwise, the result type may be automatically promoted (e.g., from `torch.int32` to `torch.int64`). + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.1133, -0.9567, 0.2958]]) + >>> torch.sum(a) + tensor(-0.5475) + + .. function:: sum(input, dim, keepdim=False, *, dtype=None) -> Tensor + :noindex: + + Returns the sum of each row of the :attr:`input` tensor in the given + dimension :attr:`dim`. If :attr:`dim` is a list of dimensions, + reduce over all of them. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.0569, -0.2475, 0.0737, -0.3429], + [-0.2993, 0.9138, 0.9337, -1.6864], + [ 0.1132, 0.7892, -0.1003, 0.5688], + [ 0.3637, -0.9906, -0.4752, -1.5197]]) + >>> torch.sum(a, 1) + tensor([-0.4598, -0.1381, 1.3708, -2.6217]) + >>> b = torch.arange(4 * 5 * 6).view(4, 5, 6) + >>> torch.sum(b, (2, 1)) + tensor([ 435., 1335., 2235., 3135.]) + """ + +@overload +def sum( + input: Tensor, + dim: _int | _size | None, + keepdim: _bool = False, + *, + dtype: _dtype | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + sum(input, *, dtype=None) -> Tensor + + Returns the sum of all elements in the :attr:`input` tensor. + + Args: + input (Tensor): the input tensor. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + + .. note:: Use the `dtype` argument if you need the result in a specific tensor type. + Otherwise, the result type may be automatically promoted (e.g., from `torch.int32` to `torch.int64`). + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.1133, -0.9567, 0.2958]]) + >>> torch.sum(a) + tensor(-0.5475) + + .. function:: sum(input, dim, keepdim=False, *, dtype=None) -> Tensor + :noindex: + + Returns the sum of each row of the :attr:`input` tensor in the given + dimension :attr:`dim`. If :attr:`dim` is a list of dimensions, + reduce over all of them. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.0569, -0.2475, 0.0737, -0.3429], + [-0.2993, 0.9138, 0.9337, -1.6864], + [ 0.1132, 0.7892, -0.1003, 0.5688], + [ 0.3637, -0.9906, -0.4752, -1.5197]]) + >>> torch.sum(a, 1) + tensor([-0.4598, -0.1381, 1.3708, -2.6217]) + >>> b = torch.arange(4 * 5 * 6).view(4, 5, 6) + >>> torch.sum(b, (2, 1)) + tensor([ 435., 1335., 2235., 3135.]) + """ + +@overload +def sum( + input: Tensor, + dim: Sequence[str | EllipsisType | None], + keepdim: _bool = False, + *, + dtype: _dtype | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + sum(input, *, dtype=None) -> Tensor + + Returns the sum of all elements in the :attr:`input` tensor. + + Args: + input (Tensor): the input tensor. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + + .. note:: Use the `dtype` argument if you need the result in a specific tensor type. + Otherwise, the result type may be automatically promoted (e.g., from `torch.int32` to `torch.int64`). + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.1133, -0.9567, 0.2958]]) + >>> torch.sum(a) + tensor(-0.5475) + + .. function:: sum(input, dim, keepdim=False, *, dtype=None) -> Tensor + :noindex: + + Returns the sum of each row of the :attr:`input` tensor in the given + dimension :attr:`dim`. If :attr:`dim` is a list of dimensions, + reduce over all of them. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.0569, -0.2475, 0.0737, -0.3429], + [-0.2993, 0.9138, 0.9337, -1.6864], + [ 0.1132, 0.7892, -0.1003, 0.5688], + [ 0.3637, -0.9906, -0.4752, -1.5197]]) + >>> torch.sum(a, 1) + tensor([-0.4598, -0.1381, 1.3708, -2.6217]) + >>> b = torch.arange(4 * 5 * 6).view(4, 5, 6) + >>> torch.sum(b, (2, 1)) + tensor([ 435., 1335., 2235., 3135.]) + """ + +def svd( + input: Tensor, + some: _bool = True, + compute_uv: _bool = True, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.svd: + r""" + svd(input, some=True, compute_uv=True, *, out=None) -> (Tensor, Tensor, Tensor) + + Computes the singular value decomposition of either a matrix or batch of + matrices :attr:`input`. The singular value decomposition is represented as a + namedtuple `(U, S, V)`, such that :attr:`input` :math:`= U \text{diag}(S) V^{\text{H}}`. + where :math:`V^{\text{H}}` is the transpose of `V` for real inputs, + and the conjugate transpose of `V` for complex inputs. + If :attr:`input` is a batch of matrices, then `U`, `S`, and `V` are also + batched with the same batch dimensions as :attr:`input`. + + If :attr:`some` is `True` (default), the method returns the reduced singular + value decomposition. In this case, if the last two dimensions of :attr:`input` are + `m` and `n`, then the returned `U` and `V` matrices will contain only + `min(n, m)` orthonormal columns. + + If :attr:`compute_uv` is `False`, the returned `U` and `V` will be + zero-filled matrices of shape `(m, m)` and `(n, n)` + respectively, and the same device as :attr:`input`. The argument :attr:`some` + has no effect when :attr:`compute_uv` is `False`. + + Supports :attr:`input` of float, double, cfloat and cdouble data types. + The dtypes of `U` and `V` are the same as :attr:`input`'s. `S` will + always be real-valued, even if :attr:`input` is complex. + + .. warning:: + + :func:`torch.svd` is deprecated in favor of :func:`torch.linalg.svd` + and will be removed in a future PyTorch release. + + ``U, S, V = torch.svd(A, some=some, compute_uv=True)`` (default) should be replaced with + + .. code:: python + + U, S, Vh = torch.linalg.svd(A, full_matrices=not some) + V = Vh.mH + + ``_, S, _ = torch.svd(A, some=some, compute_uv=False)`` should be replaced with + + .. code:: python + + S = torch.linalg.svdvals(A) + + .. note:: Differences with :func:`torch.linalg.svd`: + + * :attr:`some` is the opposite of + :func:`torch.linalg.svd`'s :attr:`full_matrices`. Note that + default value for both is `True`, so the default behavior is + effectively the opposite. + * :func:`torch.svd` returns `V`, whereas :func:`torch.linalg.svd` returns + `Vh`, that is, :math:`V^{\text{H}}`. + * If :attr:`compute_uv` is `False`, :func:`torch.svd` returns zero-filled + tensors for `U` and `Vh`, whereas :func:`torch.linalg.svd` returns + empty tensors. + + .. note:: The singular values are returned in descending order. If :attr:`input` is a batch of matrices, + then the singular values of each matrix in the batch are returned in descending order. + + .. note:: The `S` tensor can only be used to compute gradients if :attr:`compute_uv` is `True`. + + .. note:: When :attr:`some` is `False`, the gradients on `U[..., :, min(m, n):]` + and `V[..., :, min(m, n):]` will be ignored in the backward pass, as those vectors + can be arbitrary bases of the corresponding subspaces. + + .. note:: The implementation of :func:`torch.linalg.svd` on CPU uses LAPACK's routine `?gesdd` + (a divide-and-conquer algorithm) instead of `?gesvd` for speed. Analogously, + on GPU, it uses cuSOLVER's routines `gesvdj` and `gesvdjBatched` on CUDA 10.1.243 + and later, and MAGMA's routine `gesdd` on earlier versions of CUDA. + + .. note:: The returned `U` will not be contiguous. The matrix (or batch of matrices) will + be represented as a column-major matrix (i.e. Fortran-contiguous). + + .. warning:: The gradients with respect to `U` and `V` will only be finite when the input does not + have zero nor repeated singular values. + + .. warning:: If the distance between any two singular values is close to zero, the gradients with respect to + `U` and `V` will be numerically unstable, as they depends on + :math:`\frac{1}{\min_{i \neq j} \sigma_i^2 - \sigma_j^2}`. The same happens when the matrix + has small singular values, as these gradients also depend on `S^{-1}`. + + .. warning:: For complex-valued :attr:`input` the singular value decomposition is not unique, + as `U` and `V` may be multiplied by an arbitrary phase factor :math:`e^{i \phi}` on every column. + The same happens when :attr:`input` has repeated singular values, where one may multiply + the columns of the spanning subspace in `U` and `V` by a rotation matrix + and `the resulting vectors will span the same subspace`_. + Different platforms, like NumPy, or inputs on different device types, + may produce different `U` and `V` tensors. + + Args: + input (Tensor): the input tensor of size `(*, m, n)` where `*` is zero or more + batch dimensions consisting of `(m, n)` matrices. + some (bool, optional): controls whether to compute the reduced or full decomposition, and + consequently, the shape of returned `U` and `V`. Default: `True`. + compute_uv (bool, optional): controls whether to compute `U` and `V`. Default: `True`. + + Keyword args: + out (tuple, optional): the output tuple of tensors + + Example:: + + >>> a = torch.randn(5, 3) + >>> a + tensor([[ 0.2364, -0.7752, 0.6372], + [ 1.7201, 0.7394, -0.0504], + [-0.3371, -1.0584, 0.5296], + [ 0.3550, -0.4022, 1.5569], + [ 0.2445, -0.0158, 1.1414]]) + >>> u, s, v = torch.svd(a) + >>> u + tensor([[ 0.4027, 0.0287, 0.5434], + [-0.1946, 0.8833, 0.3679], + [ 0.4296, -0.2890, 0.5261], + [ 0.6604, 0.2717, -0.2618], + [ 0.4234, 0.2481, -0.4733]]) + >>> s + tensor([2.3289, 2.0315, 0.7806]) + >>> v + tensor([[-0.0199, 0.8766, 0.4809], + [-0.5080, 0.4054, -0.7600], + [ 0.8611, 0.2594, -0.4373]]) + >>> torch.dist(a, torch.mm(torch.mm(u, torch.diag(s)), v.t())) + tensor(8.6531e-07) + >>> a_big = torch.randn(7, 5, 3) + >>> u, s, v = torch.svd(a_big) + >>> torch.dist(a_big, torch.matmul(torch.matmul(u, torch.diag_embed(s)), v.mT)) + tensor(2.6503e-06) + + .. _the resulting vectors will span the same subspace: + (https://en.wikipedia.org/wiki/Singular_value_decomposition#Singular_values,_singular_vectors,_and_their_relation_to_the_SVD) + """ + +def swapaxes(input: Tensor, axis0: _int, axis1: _int) -> Tensor: + r""" + swapaxes(input, axis0, axis1) -> Tensor + + Alias for :func:`torch.transpose`. + + This function is equivalent to NumPy's swapaxes function. + + Examples:: + + >>> x = torch.tensor([[[0,1],[2,3]],[[4,5],[6,7]]]) + >>> x + tensor([[[0, 1], + [2, 3]], + + [[4, 5], + [6, 7]]]) + >>> torch.swapaxes(x, 0, 1) + tensor([[[0, 1], + [4, 5]], + + [[2, 3], + [6, 7]]]) + >>> torch.swapaxes(x, 0, 2) + tensor([[[0, 4], + [2, 6]], + + [[1, 5], + [3, 7]]]) + """ + +def swapdims(input: Tensor, dim0: _int, dim1: _int) -> Tensor: + r""" + swapdims(input, dim0, dim1) -> Tensor + + Alias for :func:`torch.transpose`. + + This function is equivalent to NumPy's swapaxes function. + + Examples:: + + >>> x = torch.tensor([[[0,1],[2,3]],[[4,5],[6,7]]]) + >>> x + tensor([[[0, 1], + [2, 3]], + + [[4, 5], + [6, 7]]]) + >>> torch.swapdims(x, 0, 1) + tensor([[[0, 1], + [4, 5]], + + [[2, 3], + [6, 7]]]) + >>> torch.swapdims(x, 0, 2) + tensor([[[0, 4], + [2, 6]], + + [[1, 5], + [3, 7]]]) + """ + +def sym_constrain_range( + size: Number | _complex, + *, + min: _int | None = None, + max: _int | None = None, +) -> None: ... +def sym_constrain_range_for_size( + size: Number | _complex, + *, + min: _int | None = None, + max: _int | None = None, +) -> None: ... +def t(input: Tensor) -> Tensor: + r""" + t(input) -> Tensor + + Expects :attr:`input` to be <= 2-D tensor and transposes dimensions 0 + and 1. + + 0-D and 1-D tensors are returned as is. When input is a 2-D tensor this + is equivalent to ``transpose(input, 0, 1)``. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> x = torch.randn(()) + >>> x + tensor(0.1995) + >>> torch.t(x) + tensor(0.1995) + >>> x = torch.randn(3) + >>> x + tensor([ 2.4320, -0.4608, 0.7702]) + >>> torch.t(x) + tensor([ 2.4320, -0.4608, 0.7702]) + >>> x = torch.randn(2, 3) + >>> x + tensor([[ 0.4875, 0.9158, -0.5872], + [ 0.3938, -0.6929, 0.6932]]) + >>> torch.t(x) + tensor([[ 0.4875, 0.3938], + [ 0.9158, -0.6929], + [-0.5872, 0.6932]]) + + See also :func:`torch.transpose`. + """ + +def t_copy(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + Performs the same operation as :func:`torch.t`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def take( + input: Tensor, + index: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + take(input, index) -> Tensor + + Returns a new tensor with the elements of :attr:`input` at the given indices. + The input tensor is treated as if it were viewed as a 1-D tensor. The result + takes the same shape as the indices. + + Args: + input (Tensor): the input tensor. + index (LongTensor): the indices into tensor + + Example:: + + >>> src = torch.tensor([[4, 3, 5], + ... [6, 7, 8]]) + >>> torch.take(src, torch.tensor([0, 2, 5])) + tensor([ 4, 5, 8]) + """ + +def take_along_dim( + input: Tensor, + indices: Tensor, + dim: _int | None = None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + take_along_dim(input, indices, dim=None, *, out=None) -> Tensor + + Selects values from :attr:`input` at the 1-dimensional indices from :attr:`indices` along the given :attr:`dim`. + + If :attr:`dim` is None, the input array is treated as if it has been flattened to 1d. + + Functions that return indices along a dimension, like :func:`torch.argmax` and :func:`torch.argsort`, + are designed to work with this function. See the examples below. + + .. note:: + This function is similar to NumPy's `take_along_axis`. + See also :func:`torch.gather`. + + Args: + input (Tensor): the input tensor. + indices (LongTensor): the indices into :attr:`input`. Must have long dtype. + dim (int, optional): dimension to select along. Default: 0 + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> t = torch.tensor([[10, 30, 20], [60, 40, 50]]) + >>> max_idx = torch.argmax(t) + >>> torch.take_along_dim(t, max_idx) + tensor([60]) + >>> sorted_idx = torch.argsort(t, dim=1) + >>> torch.take_along_dim(t, sorted_idx, dim=1) + tensor([[10, 20, 30], + [40, 50, 60]]) + """ + +def tan(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + tan(input, *, out=None) -> Tensor + + Returns a new tensor with the tangent of the elements in the :attr:`input` tensor, + where each value in this input tensor is in radians. + + .. math:: + \text{out}_{i} = \tan(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-1.2027, -1.7687, 0.4412, -1.3856]) + >>> torch.tan(a) + tensor([-2.5930, 4.9859, 0.4722, -5.3366]) + """ + +def tan_(input: Tensor) -> Tensor: ... +def tanh(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + tanh(input, *, out=None) -> Tensor + + Returns a new tensor with the hyperbolic tangent of the elements + of :attr:`input`. + + .. math:: + \text{out}_{i} = \tanh(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.8986, -0.7279, 1.1745, 0.2611]) + >>> torch.tanh(a) + tensor([ 0.7156, -0.6218, 0.8257, 0.2553]) + """ + +def tanh_(input: Tensor) -> Tensor: ... +def tensor( + data: Any, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + pin_memory: _bool = False, +) -> Tensor: + r""" + tensor(data, *, dtype=None, device=None, requires_grad=False, pin_memory=False) -> Tensor + + Constructs a tensor with no autograd history (also known as a "leaf tensor", see :doc:`/notes/autograd`) by copying :attr:`data`. + + .. warning:: + + When working with tensors prefer using :func:`torch.Tensor.clone`, + :func:`torch.Tensor.detach`, and :func:`torch.Tensor.requires_grad_` for + readability. Letting `t` be a tensor, ``torch.tensor(t)`` is equivalent to + ``t.detach().clone()``, and ``torch.tensor(t, requires_grad=True)`` + is equivalent to ``t.detach().clone().requires_grad_(True)``. + + .. seealso:: + + :func:`torch.as_tensor` preserves autograd history and avoids copies where possible. + :func:`torch.from_numpy` creates a tensor that shares storage with a NumPy array. + + Args: + data (array_like): Initial data for the tensor. Can be a list, tuple, + NumPy ``ndarray``, scalar, and other types. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, infers data type from :attr:`data`. + device (:class:`torch.device`, optional): the device of the constructed tensor. If None and data is a tensor + then the device of data is used. If None and data is not a tensor then + the result tensor is constructed on the current device. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + + Example:: + + >>> torch.tensor([[0.1, 1.2], [2.2, 3.1], [4.9, 5.2]]) + tensor([[ 0.1000, 1.2000], + [ 2.2000, 3.1000], + [ 4.9000, 5.2000]]) + + >>> torch.tensor([0, 1]) # Type inference on data + tensor([ 0, 1]) + + >>> torch.tensor([[0.11111, 0.222222, 0.3333333]], + ... dtype=torch.float64, + ... device=torch.device('cuda:0')) # creates a double tensor on a CUDA device + tensor([[ 0.1111, 0.2222, 0.3333]], dtype=torch.float64, device='cuda:0') + + >>> torch.tensor(3.14159) # Create a zero-dimensional (scalar) tensor + tensor(3.1416) + + >>> torch.tensor([]) # Create an empty tensor (of size (0,)) + tensor([]) + """ + +@overload +def tensor_split( + input: Tensor, + tensor_indices_or_sections: Tensor, + dim: _int = 0, +) -> tuple[Tensor, ...]: + r""" + tensor_split(input, indices_or_sections, dim=0) -> List of Tensors + + Splits a tensor into multiple sub-tensors, all of which are views of :attr:`input`, + along dimension :attr:`dim` according to the indices or number of sections specified + by :attr:`indices_or_sections`. This function is based on NumPy's + :func:`numpy.array_split`. + + Args: + input (Tensor): the tensor to split + indices_or_sections (Tensor, int or list or tuple of ints): + If :attr:`indices_or_sections` is an integer ``n`` or a zero dimensional long tensor + with value ``n``, :attr:`input` is split into ``n`` sections along dimension :attr:`dim`. + If :attr:`input` is divisible by ``n`` along dimension :attr:`dim`, each + section will be of equal size, :code:`input.size(dim) / n`. If :attr:`input` + is not divisible by ``n``, the sizes of the first :code:`int(input.size(dim) % n)` + sections will have size :code:`int(input.size(dim) / n) + 1`, and the rest will + have size :code:`int(input.size(dim) / n)`. + + If :attr:`indices_or_sections` is a list or tuple of ints, or a one-dimensional long + tensor, then :attr:`input` is split along dimension :attr:`dim` at each of the indices + in the list, tuple or tensor. For instance, :code:`indices_or_sections=[2, 3]` and :code:`dim=0` + would result in the tensors :code:`input[:2]`, :code:`input[2:3]`, and :code:`input[3:]`. + + If :attr:`indices_or_sections` is a tensor, it must be a zero-dimensional or one-dimensional + long tensor on the CPU. + + dim (int, optional): dimension along which to split the tensor. Default: ``0`` + + Example:: + + >>> x = torch.arange(8) + >>> torch.tensor_split(x, 3) + (tensor([0, 1, 2]), tensor([3, 4, 5]), tensor([6, 7])) + + >>> x = torch.arange(7) + >>> torch.tensor_split(x, 3) + (tensor([0, 1, 2]), tensor([3, 4]), tensor([5, 6])) + >>> torch.tensor_split(x, (1, 6)) + (tensor([0]), tensor([1, 2, 3, 4, 5]), tensor([6])) + + >>> x = torch.arange(14).reshape(2, 7) + >>> x + tensor([[ 0, 1, 2, 3, 4, 5, 6], + [ 7, 8, 9, 10, 11, 12, 13]]) + >>> torch.tensor_split(x, 3, dim=1) + (tensor([[0, 1, 2], + [7, 8, 9]]), + tensor([[ 3, 4], + [10, 11]]), + tensor([[ 5, 6], + [12, 13]])) + >>> torch.tensor_split(x, (1, 6), dim=1) + (tensor([[0], + [7]]), + tensor([[ 1, 2, 3, 4, 5], + [ 8, 9, 10, 11, 12]]), + tensor([[ 6], + [13]])) + """ + +@overload +def tensor_split( + input: Tensor, + sections: _int | SymInt, + dim: _int = 0, +) -> tuple[Tensor, ...]: + r""" + tensor_split(input, indices_or_sections, dim=0) -> List of Tensors + + Splits a tensor into multiple sub-tensors, all of which are views of :attr:`input`, + along dimension :attr:`dim` according to the indices or number of sections specified + by :attr:`indices_or_sections`. This function is based on NumPy's + :func:`numpy.array_split`. + + Args: + input (Tensor): the tensor to split + indices_or_sections (Tensor, int or list or tuple of ints): + If :attr:`indices_or_sections` is an integer ``n`` or a zero dimensional long tensor + with value ``n``, :attr:`input` is split into ``n`` sections along dimension :attr:`dim`. + If :attr:`input` is divisible by ``n`` along dimension :attr:`dim`, each + section will be of equal size, :code:`input.size(dim) / n`. If :attr:`input` + is not divisible by ``n``, the sizes of the first :code:`int(input.size(dim) % n)` + sections will have size :code:`int(input.size(dim) / n) + 1`, and the rest will + have size :code:`int(input.size(dim) / n)`. + + If :attr:`indices_or_sections` is a list or tuple of ints, or a one-dimensional long + tensor, then :attr:`input` is split along dimension :attr:`dim` at each of the indices + in the list, tuple or tensor. For instance, :code:`indices_or_sections=[2, 3]` and :code:`dim=0` + would result in the tensors :code:`input[:2]`, :code:`input[2:3]`, and :code:`input[3:]`. + + If :attr:`indices_or_sections` is a tensor, it must be a zero-dimensional or one-dimensional + long tensor on the CPU. + + dim (int, optional): dimension along which to split the tensor. Default: ``0`` + + Example:: + + >>> x = torch.arange(8) + >>> torch.tensor_split(x, 3) + (tensor([0, 1, 2]), tensor([3, 4, 5]), tensor([6, 7])) + + >>> x = torch.arange(7) + >>> torch.tensor_split(x, 3) + (tensor([0, 1, 2]), tensor([3, 4]), tensor([5, 6])) + >>> torch.tensor_split(x, (1, 6)) + (tensor([0]), tensor([1, 2, 3, 4, 5]), tensor([6])) + + >>> x = torch.arange(14).reshape(2, 7) + >>> x + tensor([[ 0, 1, 2, 3, 4, 5, 6], + [ 7, 8, 9, 10, 11, 12, 13]]) + >>> torch.tensor_split(x, 3, dim=1) + (tensor([[0, 1, 2], + [7, 8, 9]]), + tensor([[ 3, 4], + [10, 11]]), + tensor([[ 5, 6], + [12, 13]])) + >>> torch.tensor_split(x, (1, 6), dim=1) + (tensor([[0], + [7]]), + tensor([[ 1, 2, 3, 4, 5], + [ 8, 9, 10, 11, 12]]), + tensor([[ 6], + [13]])) + """ + +@overload +def tensor_split( + input: Tensor, + indices: Sequence[_int | SymInt], + dim: _int = 0, +) -> tuple[Tensor, ...]: + r""" + tensor_split(input, indices_or_sections, dim=0) -> List of Tensors + + Splits a tensor into multiple sub-tensors, all of which are views of :attr:`input`, + along dimension :attr:`dim` according to the indices or number of sections specified + by :attr:`indices_or_sections`. This function is based on NumPy's + :func:`numpy.array_split`. + + Args: + input (Tensor): the tensor to split + indices_or_sections (Tensor, int or list or tuple of ints): + If :attr:`indices_or_sections` is an integer ``n`` or a zero dimensional long tensor + with value ``n``, :attr:`input` is split into ``n`` sections along dimension :attr:`dim`. + If :attr:`input` is divisible by ``n`` along dimension :attr:`dim`, each + section will be of equal size, :code:`input.size(dim) / n`. If :attr:`input` + is not divisible by ``n``, the sizes of the first :code:`int(input.size(dim) % n)` + sections will have size :code:`int(input.size(dim) / n) + 1`, and the rest will + have size :code:`int(input.size(dim) / n)`. + + If :attr:`indices_or_sections` is a list or tuple of ints, or a one-dimensional long + tensor, then :attr:`input` is split along dimension :attr:`dim` at each of the indices + in the list, tuple or tensor. For instance, :code:`indices_or_sections=[2, 3]` and :code:`dim=0` + would result in the tensors :code:`input[:2]`, :code:`input[2:3]`, and :code:`input[3:]`. + + If :attr:`indices_or_sections` is a tensor, it must be a zero-dimensional or one-dimensional + long tensor on the CPU. + + dim (int, optional): dimension along which to split the tensor. Default: ``0`` + + Example:: + + >>> x = torch.arange(8) + >>> torch.tensor_split(x, 3) + (tensor([0, 1, 2]), tensor([3, 4, 5]), tensor([6, 7])) + + >>> x = torch.arange(7) + >>> torch.tensor_split(x, 3) + (tensor([0, 1, 2]), tensor([3, 4]), tensor([5, 6])) + >>> torch.tensor_split(x, (1, 6)) + (tensor([0]), tensor([1, 2, 3, 4, 5]), tensor([6])) + + >>> x = torch.arange(14).reshape(2, 7) + >>> x + tensor([[ 0, 1, 2, 3, 4, 5, 6], + [ 7, 8, 9, 10, 11, 12, 13]]) + >>> torch.tensor_split(x, 3, dim=1) + (tensor([[0, 1, 2], + [7, 8, 9]]), + tensor([[ 3, 4], + [10, 11]]), + tensor([[ 5, 6], + [12, 13]])) + >>> torch.tensor_split(x, (1, 6), dim=1) + (tensor([[0], + [7]]), + tensor([[ 1, 2, 3, 4, 5], + [ 8, 9, 10, 11, 12]]), + tensor([[ 6], + [13]])) + """ + +def threshold( + input: Tensor, + threshold: Number | _complex, + value: Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: ... +def threshold_( + input: Tensor, + threshold: Number | _complex, + value: Number | _complex, +) -> Tensor: ... +def tile(input: Tensor, dims: Sequence[_int | SymInt]) -> Tensor: + r""" + tile(input, dims) -> Tensor + + Constructs a tensor by repeating the elements of :attr:`input`. + The :attr:`dims` argument specifies the number of repetitions + in each dimension. + + If :attr:`dims` specifies fewer dimensions than :attr:`input` has, then + ones are prepended to :attr:`dims` until all dimensions are specified. + For example, if :attr:`input` has shape (8, 6, 4, 2) and :attr:`dims` + is (2, 2), then :attr:`dims` is treated as (1, 1, 2, 2). + + Analogously, if :attr:`input` has fewer dimensions than :attr:`dims` + specifies, then :attr:`input` is treated as if it were unsqueezed at + dimension zero until it has as many dimensions as :attr:`dims` specifies. + For example, if :attr:`input` has shape (4, 2) and :attr:`dims` + is (3, 3, 2, 2), then :attr:`input` is treated as if it had the + shape (1, 1, 4, 2). + + .. note:: + + This function is similar to NumPy's tile function. + + Args: + input (Tensor): the tensor whose elements to repeat. + dims (tuple): the number of repetitions per dimension. + + Example:: + + >>> x = torch.tensor([1, 2, 3]) + >>> x.tile((2,)) + tensor([1, 2, 3, 1, 2, 3]) + >>> y = torch.tensor([[1, 2], [3, 4]]) + >>> torch.tile(y, (2, 2)) + tensor([[1, 2, 1, 2], + [3, 4, 3, 4], + [1, 2, 1, 2], + [3, 4, 3, 4]]) + """ + +def topk( + input: Tensor, + k: _int | SymInt, + dim: _int = -1, + largest: _bool = True, + sorted: _bool = True, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.topk: + r""" + topk(input, k, dim=None, largest=True, sorted=True, *, out=None) -> (Tensor, LongTensor) + + Returns the :attr:`k` largest elements of the given :attr:`input` tensor along + a given dimension. + + If :attr:`dim` is not given, the last dimension of the `input` is chosen. + + If :attr:`largest` is ``False`` then the `k` smallest elements are returned. + + A namedtuple of `(values, indices)` is returned with the `values` and + `indices` of the largest `k` elements of each row of the `input` tensor in the + given dimension `dim`. + + The boolean option :attr:`sorted` if ``True``, will make sure that the returned + `k` elements are themselves sorted + + .. note:: + When using `torch.topk`, the indices of tied elements are not guaranteed to be stable + and may vary across different invocations. + + Args: + input (Tensor): the input tensor. + k (int): the k in "top-k" + dim (int, optional): the dimension to sort along + largest (bool, optional): controls whether to return largest or + smallest elements + sorted (bool, optional): controls whether to return the elements + in sorted order + + Keyword args: + out (tuple, optional): the output tuple of (Tensor, LongTensor) that can be + optionally given to be used as output buffers + + Example:: + + >>> x = torch.arange(1., 6.) + >>> x + tensor([ 1., 2., 3., 4., 5.]) + >>> torch.topk(x, 3) + torch.return_types.topk(values=tensor([5., 4., 3.]), indices=tensor([4, 3, 2])) + """ + +def trace(input: Tensor) -> Tensor: + r""" + trace(input) -> Tensor + + Returns the sum of the elements of the diagonal of the input 2-D matrix. + + Example:: + + >>> x = torch.arange(1., 10.).view(3, 3) + >>> x + tensor([[ 1., 2., 3.], + [ 4., 5., 6.], + [ 7., 8., 9.]]) + >>> torch.trace(x) + tensor(15.) + """ + +@overload +def transpose(input: Tensor, dim0: _int, dim1: _int) -> Tensor: + r""" + transpose(input, dim0, dim1) -> Tensor + + Returns a tensor that is a transposed version of :attr:`input`. + The given dimensions :attr:`dim0` and :attr:`dim1` are swapped. + + If :attr:`input` is a strided tensor then the resulting :attr:`out` + tensor shares its underlying storage with the :attr:`input` tensor, so + changing the content of one would change the content of the other. + + If :attr:`input` is a :ref:`sparse tensor ` then the + resulting :attr:`out` tensor *does not* share the underlying storage + with the :attr:`input` tensor. + + If :attr:`input` is a :ref:`sparse tensor ` with compressed + layout (SparseCSR, SparseBSR, SparseCSC or SparseBSC) the arguments + :attr:`dim0` and :attr:`dim1` must be both batch dimensions, or must + both be sparse dimensions. The batch dimensions of a sparse tensor are the + dimensions preceding the sparse dimensions. + + .. note:: + Transpositions which interchange the sparse dimensions of a `SparseCSR` + or `SparseCSC` layout tensor will result in the layout changing between + the two options. Transposition of the sparse dimensions of a ` SparseBSR` + or `SparseBSC` layout tensor will likewise generate a result with the + opposite layout. + + + Args: + input (Tensor): the input tensor. + dim0 (int): the first dimension to be transposed + dim1 (int): the second dimension to be transposed + + Example:: + + >>> x = torch.randn(2, 3) + >>> x + tensor([[ 1.0028, -0.9893, 0.5809], + [-0.1669, 0.7299, 0.4942]]) + >>> torch.transpose(x, 0, 1) + tensor([[ 1.0028, -0.1669], + [-0.9893, 0.7299], + [ 0.5809, 0.4942]]) + + See also :func:`torch.t`. + """ + +@overload +def transpose( + input: Tensor, + dim0: str | EllipsisType | None, + dim1: str | EllipsisType | None, +) -> Tensor: + r""" + transpose(input, dim0, dim1) -> Tensor + + Returns a tensor that is a transposed version of :attr:`input`. + The given dimensions :attr:`dim0` and :attr:`dim1` are swapped. + + If :attr:`input` is a strided tensor then the resulting :attr:`out` + tensor shares its underlying storage with the :attr:`input` tensor, so + changing the content of one would change the content of the other. + + If :attr:`input` is a :ref:`sparse tensor ` then the + resulting :attr:`out` tensor *does not* share the underlying storage + with the :attr:`input` tensor. + + If :attr:`input` is a :ref:`sparse tensor ` with compressed + layout (SparseCSR, SparseBSR, SparseCSC or SparseBSC) the arguments + :attr:`dim0` and :attr:`dim1` must be both batch dimensions, or must + both be sparse dimensions. The batch dimensions of a sparse tensor are the + dimensions preceding the sparse dimensions. + + .. note:: + Transpositions which interchange the sparse dimensions of a `SparseCSR` + or `SparseCSC` layout tensor will result in the layout changing between + the two options. Transposition of the sparse dimensions of a ` SparseBSR` + or `SparseBSC` layout tensor will likewise generate a result with the + opposite layout. + + + Args: + input (Tensor): the input tensor. + dim0 (int): the first dimension to be transposed + dim1 (int): the second dimension to be transposed + + Example:: + + >>> x = torch.randn(2, 3) + >>> x + tensor([[ 1.0028, -0.9893, 0.5809], + [-0.1669, 0.7299, 0.4942]]) + >>> torch.transpose(x, 0, 1) + tensor([[ 1.0028, -0.1669], + [-0.9893, 0.7299], + [ 0.5809, 0.4942]]) + + See also :func:`torch.t`. + """ + +def transpose_copy( + input: Tensor, + dim0: _int, + dim1: _int, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.transpose`, but all output tensors + are freshly created instead of aliasing the input. + """ + +@overload +def trapezoid(y: Tensor, x: Tensor, *, dim: _int = -1) -> Tensor: + r""" + trapezoid(y, x=None, *, dx=None, dim=-1) -> Tensor + + Computes the `trapezoidal rule `_ along + :attr:`dim`. By default the spacing between elements is assumed to be 1, but + :attr:`dx` can be used to specify a different constant spacing, and :attr:`x` can be + used to specify arbitrary spacing along :attr:`dim`. Only one of :attr:`x` or :attr:`dx` should be specified. + + + Assuming :attr:`y` is a one-dimensional tensor with elements :math:`{y_0, y_1, ..., y_n}`, + the default computation is + + .. math:: + \begin{aligned} + \sum_{i = 1}^{n} \frac{1}{2} (y_i + y_{i-1}) + \end{aligned} + + When :attr:`dx` is specified the computation becomes + + .. math:: + \begin{aligned} + \sum_{i = 1}^{n} \frac{\Delta x}{2} (y_i + y_{i-1}) + \end{aligned} + + effectively multiplying the result by :attr:`dx`. When :attr:`x` is specified, + assuming :attr:`x` is also a one-dimensional tensor with + elements :math:`{x_0, x_1, ..., x_n}`, the computation becomes + + .. math:: + \begin{aligned} + \sum_{i = 1}^{n} \frac{(x_i - x_{i-1})}{2} (y_i + y_{i-1}) + \end{aligned} + + When :attr:`x` and :attr:`y` have the same size, the computation is as described above and no broadcasting is needed. + The broadcasting behavior of this function is as follows when their sizes are different. For both :attr:`x` + and :attr:`y`, the function computes the difference between consecutive elements along + dimension :attr:`dim`. This effectively creates two tensors, `x_diff` and `y_diff`, that have + the same shape as the original tensors except their lengths along the dimension :attr:`dim` is reduced by 1. + After that, those two tensors are broadcast together to compute final output as part of the trapezoidal rule. + See the examples below for details. + + .. note:: + The trapezoidal rule is a technique for approximating the definite integral of a function + by averaging its left and right Riemann sums. The approximation becomes more accurate as + the resolution of the partition increases. + + Arguments: + y (Tensor): Values to use when computing the trapezoidal rule. + x (Tensor): If specified, defines spacing between values as specified above. + + Keyword arguments: + dx (float): constant spacing between values. If neither :attr:`x` or :attr:`dx` + are specified then this defaults to 1. Effectively multiplies the result by its value. + dim (int): The dimension along which to compute the trapezoidal rule. + The last (inner-most) dimension by default. + + Examples:: + + >>> # Computes the trapezoidal rule in 1D, spacing is implicitly 1 + >>> y = torch.tensor([1, 5, 10]) + >>> torch.trapezoid(y) + tensor(10.5) + + >>> # Computes the same trapezoidal rule directly to verify + >>> (1 + 10 + 10) / 2 + 10.5 + + >>> # Computes the trapezoidal rule in 1D with constant spacing of 2 + >>> # NOTE: the result is the same as before, but multiplied by 2 + >>> torch.trapezoid(y, dx=2) + 21.0 + + >>> # Computes the trapezoidal rule in 1D with arbitrary spacing + >>> x = torch.tensor([1, 3, 6]) + >>> torch.trapezoid(y, x) + 28.5 + + >>> # Computes the same trapezoidal rule directly to verify + >>> ((3 - 1) * (1 + 5) + (6 - 3) * (5 + 10)) / 2 + 28.5 + + >>> # Computes the trapezoidal rule for each row of a 3x3 matrix + >>> y = torch.arange(9).reshape(3, 3) + tensor([[0, 1, 2], + [3, 4, 5], + [6, 7, 8]]) + >>> torch.trapezoid(y) + tensor([ 2., 8., 14.]) + + >>> # Computes the trapezoidal rule for each column of the matrix + >>> torch.trapezoid(y, dim=0) + tensor([ 6., 8., 10.]) + + >>> # Computes the trapezoidal rule for each row of a 3x3 ones matrix + >>> # with the same arbitrary spacing + >>> y = torch.ones(3, 3) + >>> x = torch.tensor([1, 3, 6]) + >>> torch.trapezoid(y, x) + array([5., 5., 5.]) + + >>> # Computes the trapezoidal rule for each row of a 3x3 ones matrix + >>> # with different arbitrary spacing per row + >>> y = torch.ones(3, 3) + >>> x = torch.tensor([[1, 2, 3], [1, 3, 5], [1, 4, 7]]) + >>> torch.trapezoid(y, x) + array([2., 4., 6.]) + """ + +@overload +def trapezoid( + y: Tensor, + *, + dx: Number | _complex = 1, + dim: _int = -1, +) -> Tensor: + r""" + trapezoid(y, x=None, *, dx=None, dim=-1) -> Tensor + + Computes the `trapezoidal rule `_ along + :attr:`dim`. By default the spacing between elements is assumed to be 1, but + :attr:`dx` can be used to specify a different constant spacing, and :attr:`x` can be + used to specify arbitrary spacing along :attr:`dim`. Only one of :attr:`x` or :attr:`dx` should be specified. + + + Assuming :attr:`y` is a one-dimensional tensor with elements :math:`{y_0, y_1, ..., y_n}`, + the default computation is + + .. math:: + \begin{aligned} + \sum_{i = 1}^{n} \frac{1}{2} (y_i + y_{i-1}) + \end{aligned} + + When :attr:`dx` is specified the computation becomes + + .. math:: + \begin{aligned} + \sum_{i = 1}^{n} \frac{\Delta x}{2} (y_i + y_{i-1}) + \end{aligned} + + effectively multiplying the result by :attr:`dx`. When :attr:`x` is specified, + assuming :attr:`x` is also a one-dimensional tensor with + elements :math:`{x_0, x_1, ..., x_n}`, the computation becomes + + .. math:: + \begin{aligned} + \sum_{i = 1}^{n} \frac{(x_i - x_{i-1})}{2} (y_i + y_{i-1}) + \end{aligned} + + When :attr:`x` and :attr:`y` have the same size, the computation is as described above and no broadcasting is needed. + The broadcasting behavior of this function is as follows when their sizes are different. For both :attr:`x` + and :attr:`y`, the function computes the difference between consecutive elements along + dimension :attr:`dim`. This effectively creates two tensors, `x_diff` and `y_diff`, that have + the same shape as the original tensors except their lengths along the dimension :attr:`dim` is reduced by 1. + After that, those two tensors are broadcast together to compute final output as part of the trapezoidal rule. + See the examples below for details. + + .. note:: + The trapezoidal rule is a technique for approximating the definite integral of a function + by averaging its left and right Riemann sums. The approximation becomes more accurate as + the resolution of the partition increases. + + Arguments: + y (Tensor): Values to use when computing the trapezoidal rule. + x (Tensor): If specified, defines spacing between values as specified above. + + Keyword arguments: + dx (float): constant spacing between values. If neither :attr:`x` or :attr:`dx` + are specified then this defaults to 1. Effectively multiplies the result by its value. + dim (int): The dimension along which to compute the trapezoidal rule. + The last (inner-most) dimension by default. + + Examples:: + + >>> # Computes the trapezoidal rule in 1D, spacing is implicitly 1 + >>> y = torch.tensor([1, 5, 10]) + >>> torch.trapezoid(y) + tensor(10.5) + + >>> # Computes the same trapezoidal rule directly to verify + >>> (1 + 10 + 10) / 2 + 10.5 + + >>> # Computes the trapezoidal rule in 1D with constant spacing of 2 + >>> # NOTE: the result is the same as before, but multiplied by 2 + >>> torch.trapezoid(y, dx=2) + 21.0 + + >>> # Computes the trapezoidal rule in 1D with arbitrary spacing + >>> x = torch.tensor([1, 3, 6]) + >>> torch.trapezoid(y, x) + 28.5 + + >>> # Computes the same trapezoidal rule directly to verify + >>> ((3 - 1) * (1 + 5) + (6 - 3) * (5 + 10)) / 2 + 28.5 + + >>> # Computes the trapezoidal rule for each row of a 3x3 matrix + >>> y = torch.arange(9).reshape(3, 3) + tensor([[0, 1, 2], + [3, 4, 5], + [6, 7, 8]]) + >>> torch.trapezoid(y) + tensor([ 2., 8., 14.]) + + >>> # Computes the trapezoidal rule for each column of the matrix + >>> torch.trapezoid(y, dim=0) + tensor([ 6., 8., 10.]) + + >>> # Computes the trapezoidal rule for each row of a 3x3 ones matrix + >>> # with the same arbitrary spacing + >>> y = torch.ones(3, 3) + >>> x = torch.tensor([1, 3, 6]) + >>> torch.trapezoid(y, x) + array([5., 5., 5.]) + + >>> # Computes the trapezoidal rule for each row of a 3x3 ones matrix + >>> # with different arbitrary spacing per row + >>> y = torch.ones(3, 3) + >>> x = torch.tensor([[1, 2, 3], [1, 3, 5], [1, 4, 7]]) + >>> torch.trapezoid(y, x) + array([2., 4., 6.]) + """ + +@overload +def trapz(y: Tensor, *, dx: _float = 1, dim: _int = -1) -> Tensor: + r""" + trapz(y, x, *, dim=-1) -> Tensor + + Alias for :func:`torch.trapezoid`. + """ + +@overload +def trapz(y: Tensor, x: Tensor, *, dim: _int = -1) -> Tensor: + r""" + trapz(y, x, *, dim=-1) -> Tensor + + Alias for :func:`torch.trapezoid`. + """ + +def triangular_solve( + input: Tensor, + A: Tensor, + upper: _bool = True, + transpose: _bool = False, + unitriangular: _bool = False, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.triangular_solve: + r""" + triangular_solve(b, A, upper=True, transpose=False, unitriangular=False, *, out=None) -> (Tensor, Tensor) + + Solves a system of equations with a square upper or lower triangular invertible matrix :math:`A` + and multiple right-hand sides :math:`b`. + + In symbols, it solves :math:`AX = b` and assumes :math:`A` is square upper-triangular + (or lower-triangular if :attr:`upper`\ `= False`) and does not have zeros on the diagonal. + + `torch.triangular_solve(b, A)` can take in 2D inputs `b, A` or inputs that are + batches of 2D matrices. If the inputs are batches, then returns + batched outputs `X` + + If the diagonal of :attr:`A` contains zeros or elements that are very close to zero and + :attr:`unitriangular`\ `= False` (default) or if the input matrix is badly conditioned, + the result may contain `NaN` s. + + Supports input of float, double, cfloat and cdouble data types. + + .. warning:: + + :func:`torch.triangular_solve` is deprecated in favor of :func:`torch.linalg.solve_triangular` + and will be removed in a future PyTorch release. + :func:`torch.linalg.solve_triangular` has its arguments reversed and does not return a + copy of one of the inputs. + + ``X = torch.triangular_solve(B, A).solution`` should be replaced with + + .. code:: python + + X = torch.linalg.solve_triangular(A, B) + + Args: + b (Tensor): multiple right-hand sides of size :math:`(*, m, k)` where + :math:`*` is zero of more batch dimensions + A (Tensor): the input triangular coefficient matrix of size :math:`(*, m, m)` + where :math:`*` is zero or more batch dimensions + upper (bool, optional): whether :math:`A` is upper or lower triangular. Default: ``True``. + transpose (bool, optional): solves `op(A)X = b` where `op(A) = A^T` if this flag is ``True``, + and `op(A) = A` if it is ``False``. Default: ``False``. + unitriangular (bool, optional): whether :math:`A` is unit triangular. + If True, the diagonal elements of :math:`A` are assumed to be + 1 and not referenced from :math:`A`. Default: ``False``. + + Keyword args: + out ((Tensor, Tensor), optional): tuple of two tensors to write + the output to. Ignored if `None`. Default: `None`. + + Returns: + A namedtuple `(solution, cloned_coefficient)` where `cloned_coefficient` + is a clone of :math:`A` and `solution` is the solution :math:`X` to :math:`AX = b` + (or whatever variant of the system of equations, depending on the keyword arguments.) + + Examples:: + + >>> A = torch.randn(2, 2).triu() + >>> A + tensor([[ 1.1527, -1.0753], + [ 0.0000, 0.7986]]) + >>> b = torch.randn(2, 3) + >>> b + tensor([[-0.0210, 2.3513, -1.5492], + [ 1.5429, 0.7403, -1.0243]]) + >>> torch.triangular_solve(b, A) + torch.return_types.triangular_solve( + solution=tensor([[ 1.7841, 2.9046, -2.5405], + [ 1.9320, 0.9270, -1.2826]]), + cloned_coefficient=tensor([[ 1.1527, -1.0753], + [ 0.0000, 0.7986]])) + """ + +def tril( + input: Tensor, + diagonal: _int | SymInt = 0, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + tril(input, diagonal=0, *, out=None) -> Tensor + + Returns the lower triangular part of the matrix (2-D tensor) or batch of matrices + :attr:`input`, the other elements of the result tensor :attr:`out` are set to 0. + + The lower triangular part of the matrix is defined as the elements on and + below the diagonal. + + The argument :attr:`diagonal` controls which diagonal to consider. If + :attr:`diagonal` = 0, all elements on and below the main diagonal are + retained. A positive value includes just as many diagonals above the main + diagonal, and similarly a negative value excludes just as many diagonals below + the main diagonal. The main diagonal are the set of indices + :math:`\lbrace (i, i) \rbrace` for :math:`i \in [0, \min\{d_{1}, d_{2}\} - 1]` where + :math:`d_{1}, d_{2}` are the dimensions of the matrix. + + Args: + input (Tensor): the input tensor. + diagonal (int, optional): the diagonal to consider + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(3, 3) + >>> a + tensor([[-1.0813, -0.8619, 0.7105], + [ 0.0935, 0.1380, 2.2112], + [-0.3409, -0.9828, 0.0289]]) + >>> torch.tril(a) + tensor([[-1.0813, 0.0000, 0.0000], + [ 0.0935, 0.1380, 0.0000], + [-0.3409, -0.9828, 0.0289]]) + + >>> b = torch.randn(4, 6) + >>> b + tensor([[ 1.2219, 0.5653, -0.2521, -0.2345, 1.2544, 0.3461], + [ 0.4785, -0.4477, 0.6049, 0.6368, 0.8775, 0.7145], + [ 1.1502, 3.2716, -1.1243, -0.5413, 0.3615, 0.6864], + [-0.0614, -0.7344, -1.3164, -0.7648, -1.4024, 0.0978]]) + >>> torch.tril(b, diagonal=1) + tensor([[ 1.2219, 0.5653, 0.0000, 0.0000, 0.0000, 0.0000], + [ 0.4785, -0.4477, 0.6049, 0.0000, 0.0000, 0.0000], + [ 1.1502, 3.2716, -1.1243, -0.5413, 0.0000, 0.0000], + [-0.0614, -0.7344, -1.3164, -0.7648, -1.4024, 0.0000]]) + >>> torch.tril(b, diagonal=-1) + tensor([[ 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000], + [ 0.4785, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000], + [ 1.1502, 3.2716, 0.0000, 0.0000, 0.0000, 0.0000], + [-0.0614, -0.7344, -1.3164, 0.0000, 0.0000, 0.0000]]) + """ + +def tril_indices( + row: _int, + col: _int, + offset: _int = 0, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + tril_indices(row, col, offset=0, *, dtype=torch.long, device='cpu', layout=torch.strided) -> Tensor + + Returns the indices of the lower triangular part of a :attr:`row`-by- + :attr:`col` matrix in a 2-by-N Tensor, where the first row contains row + coordinates of all indices and the second row contains column coordinates. + Indices are ordered based on rows and then columns. + + The lower triangular part of the matrix is defined as the elements on and + below the diagonal. + + The argument :attr:`offset` controls which diagonal to consider. If + :attr:`offset` = 0, all elements on and below the main diagonal are + retained. A positive value includes just as many diagonals above the main + diagonal, and similarly a negative value excludes just as many diagonals below + the main diagonal. The main diagonal are the set of indices + :math:`\lbrace (i, i) \rbrace` for :math:`i \in [0, \min\{d_{1}, d_{2}\} - 1]` + where :math:`d_{1}, d_{2}` are the dimensions of the matrix. + + .. note:: + When running on CUDA, ``row * col`` must be less than :math:`2^{59}` to + prevent overflow during calculation. + + Args: + row (``int``): number of rows in the 2-D matrix. + col (``int``): number of columns in the 2-D matrix. + offset (``int``): diagonal offset from the main diagonal. + Default: if not provided, 0. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor, + only support ``torch.int``, ``torch.long``. Default: if ``None``, ``torch.long``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + layout (:class:`torch.layout`, optional): currently only support ``torch.strided``. + + Example:: + + >>> a = torch.tril_indices(3, 3) + >>> a + tensor([[0, 1, 1, 2, 2, 2], + [0, 0, 1, 0, 1, 2]]) + + >>> a = torch.tril_indices(4, 3, -1) + >>> a + tensor([[1, 2, 2, 3, 3, 3], + [0, 0, 1, 0, 1, 2]]) + + >>> a = torch.tril_indices(4, 3, 1) + >>> a + tensor([[0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3], + [0, 1, 0, 1, 2, 0, 1, 2, 0, 1, 2]]) + """ + +def triplet_margin_loss( + anchor: Tensor, + positive: Tensor, + negative: Tensor, + margin: _float = 1.0, + p: _float = 2, + eps: _float = 1e-06, + swap: _bool = False, + reduction: _int = 1, +) -> Tensor: ... +def triu( + input: Tensor, + diagonal: _int | SymInt = 0, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + triu(input, diagonal=0, *, out=None) -> Tensor + + Returns the upper triangular part of a matrix (2-D tensor) or batch of matrices + :attr:`input`, the other elements of the result tensor :attr:`out` are set to 0. + + The upper triangular part of the matrix is defined as the elements on and + above the diagonal. + + The argument :attr:`diagonal` controls which diagonal to consider. If + :attr:`diagonal` = 0, all elements on and above the main diagonal are + retained. A positive value excludes just as many diagonals above the main + diagonal, and similarly a negative value includes just as many diagonals below + the main diagonal. The main diagonal are the set of indices + :math:`\lbrace (i, i) \rbrace` for :math:`i \in [0, \min\{d_{1}, d_{2}\} - 1]` where + :math:`d_{1}, d_{2}` are the dimensions of the matrix. + + Args: + input (Tensor): the input tensor. + diagonal (int, optional): the diagonal to consider + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(3, 3) + >>> a + tensor([[ 0.2309, 0.5207, 2.0049], + [ 0.2072, -1.0680, 0.6602], + [ 0.3480, -0.5211, -0.4573]]) + >>> torch.triu(a) + tensor([[ 0.2309, 0.5207, 2.0049], + [ 0.0000, -1.0680, 0.6602], + [ 0.0000, 0.0000, -0.4573]]) + >>> torch.triu(a, diagonal=1) + tensor([[ 0.0000, 0.5207, 2.0049], + [ 0.0000, 0.0000, 0.6602], + [ 0.0000, 0.0000, 0.0000]]) + >>> torch.triu(a, diagonal=-1) + tensor([[ 0.2309, 0.5207, 2.0049], + [ 0.2072, -1.0680, 0.6602], + [ 0.0000, -0.5211, -0.4573]]) + + >>> b = torch.randn(4, 6) + >>> b + tensor([[ 0.5876, -0.0794, -1.8373, 0.6654, 0.2604, 1.5235], + [-0.2447, 0.9556, -1.2919, 1.3378, -0.1768, -1.0857], + [ 0.4333, 0.3146, 0.6576, -1.0432, 0.9348, -0.4410], + [-0.9888, 1.0679, -1.3337, -1.6556, 0.4798, 0.2830]]) + >>> torch.triu(b, diagonal=1) + tensor([[ 0.0000, -0.0794, -1.8373, 0.6654, 0.2604, 1.5235], + [ 0.0000, 0.0000, -1.2919, 1.3378, -0.1768, -1.0857], + [ 0.0000, 0.0000, 0.0000, -1.0432, 0.9348, -0.4410], + [ 0.0000, 0.0000, 0.0000, 0.0000, 0.4798, 0.2830]]) + >>> torch.triu(b, diagonal=-1) + tensor([[ 0.5876, -0.0794, -1.8373, 0.6654, 0.2604, 1.5235], + [-0.2447, 0.9556, -1.2919, 1.3378, -0.1768, -1.0857], + [ 0.0000, 0.3146, 0.6576, -1.0432, 0.9348, -0.4410], + [ 0.0000, 0.0000, -1.3337, -1.6556, 0.4798, 0.2830]]) + """ + +def triu_indices( + row: _int, + col: _int, + offset: _int = 0, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + triu_indices(row, col, offset=0, *, dtype=torch.long, device='cpu', layout=torch.strided) -> Tensor + + Returns the indices of the upper triangular part of a :attr:`row` by + :attr:`col` matrix in a 2-by-N Tensor, where the first row contains row + coordinates of all indices and the second row contains column coordinates. + Indices are ordered based on rows and then columns. + + The upper triangular part of the matrix is defined as the elements on and + above the diagonal. + + The argument :attr:`offset` controls which diagonal to consider. If + :attr:`offset` = 0, all elements on and above the main diagonal are + retained. A positive value excludes just as many diagonals above the main + diagonal, and similarly a negative value includes just as many diagonals below + the main diagonal. The main diagonal are the set of indices + :math:`\lbrace (i, i) \rbrace` for :math:`i \in [0, \min\{d_{1}, d_{2}\} - 1]` + where :math:`d_{1}, d_{2}` are the dimensions of the matrix. + + .. note:: + When running on CUDA, ``row * col`` must be less than :math:`2^{59}` to + prevent overflow during calculation. + + Args: + row (``int``): number of rows in the 2-D matrix. + col (``int``): number of columns in the 2-D matrix. + offset (``int``): diagonal offset from the main diagonal. + Default: if not provided, 0. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor, + only support ``torch.int``, ``torch.long``. Default: if ``None``, ``torch.long``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + layout (:class:`torch.layout`, optional): currently only support ``torch.strided``. + + Example:: + + >>> a = torch.triu_indices(3, 3) + >>> a + tensor([[0, 0, 0, 1, 1, 2], + [0, 1, 2, 1, 2, 2]]) + + >>> a = torch.triu_indices(4, 3, -1) + >>> a + tensor([[0, 0, 0, 1, 1, 1, 2, 2, 3], + [0, 1, 2, 0, 1, 2, 1, 2, 2]]) + + >>> a = torch.triu_indices(4, 3, 1) + >>> a + tensor([[0, 0, 1], + [1, 2, 2]]) + """ + +def true_divide( + input: Tensor | Number, + other: Tensor | Number, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + true_divide(dividend, divisor, *, out) -> Tensor + + Alias for :func:`torch.div` with ``rounding_mode=None``. + """ + +def trunc(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + trunc(input, *, out=None) -> Tensor + + Returns a new tensor with the truncated integer values of + the elements of :attr:`input`. + + For integer inputs, follows the array-api convention of returning a + copy of the input tensor. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 3.4742, 0.5466, -0.8008, -0.9079]) + >>> torch.trunc(a) + tensor([ 3., 0., -0., -0.]) + """ + +def trunc_(input: Tensor) -> Tensor: ... +@overload +def unbind(input: Tensor, dim: _int = 0) -> tuple[Tensor, ...]: + r""" + unbind(input, dim=0) -> seq + + Removes a tensor dimension. + + Returns a tuple of all slices along a given dimension, already without it. + + Arguments: + input (Tensor): the tensor to unbind + dim (int): dimension to remove + + Example:: + + >>> torch.unbind(torch.tensor([[1, 2, 3], + >>> [4, 5, 6], + >>> [7, 8, 9]])) + (tensor([1, 2, 3]), tensor([4, 5, 6]), tensor([7, 8, 9])) + """ + +@overload +def unbind( + input: Tensor, + dim: str | EllipsisType | None, +) -> tuple[Tensor, ...]: + r""" + unbind(input, dim=0) -> seq + + Removes a tensor dimension. + + Returns a tuple of all slices along a given dimension, already without it. + + Arguments: + input (Tensor): the tensor to unbind + dim (int): dimension to remove + + Example:: + + >>> torch.unbind(torch.tensor([[1, 2, 3], + >>> [4, 5, 6], + >>> [7, 8, 9]])) + (tensor([1, 2, 3]), tensor([4, 5, 6]), tensor([7, 8, 9])) + """ + +def unbind_copy( + input: Tensor, + dim: _int = 0, + *, + out: tuple[Tensor, ...] | list[Tensor] | None = None, +) -> None: + r""" + Performs the same operation as :func:`torch.unbind`, but all output tensors + are freshly created instead of aliasing the input. + """ + +@overload +def unflatten( + input: Tensor, + dim: str | EllipsisType | None, + sizes: Sequence[_int | SymInt], + names: Sequence[str | EllipsisType | None], +) -> Tensor: + r""" + unflatten(input, dim, sizes) -> Tensor + + Expands a dimension of the input tensor over multiple dimensions. + + .. seealso:: + + :func:`torch.flatten` the inverse of this function. It coalesces several dimensions into one. + + Args: + input (Tensor): the input tensor. + dim (int): Dimension to be unflattened, specified as an index into + ``input.shape``. + sizes (Tuple[int]): New shape of the unflattened dimension. + One of its elements can be `-1` in which case the corresponding output + dimension is inferred. Otherwise, the product of ``sizes`` *must* + equal ``input.shape[dim]``. + + Returns: + A View of input with the specified dimension unflattened. + + Examples:: + >>> torch.unflatten(torch.randn(3, 4, 1), 1, (2, 2)).shape + torch.Size([3, 2, 2, 1]) + >>> torch.unflatten(torch.randn(3, 4, 1), 1, (-1, 2)).shape + torch.Size([3, 2, 2, 1]) + >>> torch.unflatten(torch.randn(5, 12, 3), -2, (2, 2, 3, 1, 1)).shape + torch.Size([5, 2, 2, 3, 1, 1, 3]) + """ + +@overload +def unflatten( + input: Tensor, + dim: _int, + sizes: Sequence[_int | SymInt], +) -> Tensor: + r""" + unflatten(input, dim, sizes) -> Tensor + + Expands a dimension of the input tensor over multiple dimensions. + + .. seealso:: + + :func:`torch.flatten` the inverse of this function. It coalesces several dimensions into one. + + Args: + input (Tensor): the input tensor. + dim (int): Dimension to be unflattened, specified as an index into + ``input.shape``. + sizes (Tuple[int]): New shape of the unflattened dimension. + One of its elements can be `-1` in which case the corresponding output + dimension is inferred. Otherwise, the product of ``sizes`` *must* + equal ``input.shape[dim]``. + + Returns: + A View of input with the specified dimension unflattened. + + Examples:: + >>> torch.unflatten(torch.randn(3, 4, 1), 1, (2, 2)).shape + torch.Size([3, 2, 2, 1]) + >>> torch.unflatten(torch.randn(3, 4, 1), 1, (-1, 2)).shape + torch.Size([3, 2, 2, 1]) + >>> torch.unflatten(torch.randn(5, 12, 3), -2, (2, 2, 3, 1, 1)).shape + torch.Size([5, 2, 2, 3, 1, 1, 3]) + """ + +def unfold_copy( + input: Tensor, + dimension: _int, + size: _int, + step: _int, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.unfold`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def unique_dim( + input: Tensor, + dim: _int, + sorted: _bool = True, + return_inverse: _bool = False, + return_counts: _bool = False, +) -> tuple[Tensor, Tensor, Tensor]: ... +def unsafe_chunk( + input: Tensor, + chunks: _int, + dim: _int = 0, +) -> tuple[Tensor, ...]: + r""" + unsafe_chunk(input, chunks, dim=0) -> List of Tensors + + Works like :func:`torch.chunk` but without enforcing the autograd restrictions + on inplace modification of the outputs. + + .. warning:: + This function is safe to use as long as only the input, or only the outputs + are modified inplace after calling this function. It is user's + responsibility to ensure that is the case. If both the input and one or more + of the outputs are modified inplace, gradients computed by autograd will be + silently incorrect. + """ + +def unsafe_split( + input: Tensor, + split_size: _int | SymInt, + dim: _int = 0, +) -> tuple[Tensor, ...]: + r""" + unsafe_split(tensor, split_size_or_sections, dim=0) -> List of Tensors + + Works like :func:`torch.split` but without enforcing the autograd restrictions + on inplace modification of the outputs. + + .. warning:: + This function is safe to use as long as only the input, or only the outputs + are modified inplace after calling this function. It is user's + responsibility to ensure that is the case. If both the input and one or more + of the outputs are modified inplace, gradients computed by autograd will be + silently incorrect. + """ + +def unsafe_split_with_sizes( + input: Tensor, + split_sizes: Sequence[_int | SymInt], + dim: _int = 0, +) -> tuple[Tensor, ...]: ... +def unsqueeze(input: Tensor, dim: _int) -> Tensor: + r""" + unsqueeze(input, dim) -> Tensor + + Returns a new tensor with a dimension of size one inserted at the + specified position. + + The returned tensor shares the same underlying data with this tensor. + + A :attr:`dim` value within the range ``[-input.dim() - 1, input.dim() + 1)`` + can be used. Negative :attr:`dim` will correspond to :meth:`unsqueeze` + applied at :attr:`dim` = ``dim + input.dim() + 1``. + + Args: + input (Tensor): the input tensor. + dim (int): the index at which to insert the singleton dimension + + Example:: + + >>> x = torch.tensor([1, 2, 3, 4]) + >>> torch.unsqueeze(x, 0) + tensor([[ 1, 2, 3, 4]]) + >>> torch.unsqueeze(x, 1) + tensor([[ 1], + [ 2], + [ 3], + [ 4]]) + """ + +def unsqueeze_copy( + input: Tensor, + dim: _int, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.unsqueeze`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def values_copy(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + Performs the same operation as :func:`torch.values`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def vander( + x: Tensor, + N: _int | None = None, + increasing: _bool = False, +) -> Tensor: + r""" + vander(x, N=None, increasing=False) -> Tensor + + Generates a Vandermonde matrix. + + The columns of the output matrix are elementwise powers of the input vector :math:`x^{(N-1)}, x^{(N-2)}, ..., x^0`. + If increasing is True, the order of the columns is reversed :math:`x^0, x^1, ..., x^{(N-1)}`. Such a + matrix with a geometric progression in each row is named for Alexandre-Theophile Vandermonde. + + Arguments: + x (Tensor): 1-D input tensor. + N (int, optional): Number of columns in the output. If N is not specified, + a square array is returned :math:`(N = len(x))`. + increasing (bool, optional): Order of the powers of the columns. If True, + the powers increase from left to right, if False (the default) they are reversed. + + Returns: + Tensor: Vandermonde matrix. If increasing is False, the first column is :math:`x^{(N-1)}`, + the second :math:`x^{(N-2)}` and so forth. If increasing is True, the columns + are :math:`x^0, x^1, ..., x^{(N-1)}`. + + Example:: + + >>> x = torch.tensor([1, 2, 3, 5]) + >>> torch.vander(x) + tensor([[ 1, 1, 1, 1], + [ 8, 4, 2, 1], + [ 27, 9, 3, 1], + [125, 25, 5, 1]]) + >>> torch.vander(x, N=3) + tensor([[ 1, 1, 1], + [ 4, 2, 1], + [ 9, 3, 1], + [25, 5, 1]]) + >>> torch.vander(x, N=3, increasing=True) + tensor([[ 1, 1, 1], + [ 1, 2, 4], + [ 1, 3, 9], + [ 1, 5, 25]]) + """ + +@overload +def var( + input: Tensor, + dim: _int | _size | None, + unbiased: _bool = True, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + var(input, dim=None, *, correction=1, keepdim=False, out=None) -> Tensor + + Calculates the variance over the dimensions specified by :attr:`dim`. :attr:`dim` + can be a single dimension, list of dimensions, or ``None`` to reduce over all + dimensions. + + The variance (:math:`\sigma^2`) is calculated as + + .. math:: \sigma^2 = \frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2 + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.var(a, dim=1, keepdim=True) + tensor([[1.0631], + [0.5590], + [1.4893], + [0.8258]]) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def var( + input: Tensor, + dim: _int | _size | None = None, + *, + correction: Number | _complex | None = None, + keepdim: _bool = False, + out: Tensor | None = None, +) -> Tensor: + r""" + var(input, dim=None, *, correction=1, keepdim=False, out=None) -> Tensor + + Calculates the variance over the dimensions specified by :attr:`dim`. :attr:`dim` + can be a single dimension, list of dimensions, or ``None`` to reduce over all + dimensions. + + The variance (:math:`\sigma^2`) is calculated as + + .. math:: \sigma^2 = \frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2 + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.var(a, dim=1, keepdim=True) + tensor([[1.0631], + [0.5590], + [1.4893], + [0.8258]]) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def var(input: Tensor, unbiased: _bool = True) -> Tensor: + r""" + var(input, dim=None, *, correction=1, keepdim=False, out=None) -> Tensor + + Calculates the variance over the dimensions specified by :attr:`dim`. :attr:`dim` + can be a single dimension, list of dimensions, or ``None`` to reduce over all + dimensions. + + The variance (:math:`\sigma^2`) is calculated as + + .. math:: \sigma^2 = \frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2 + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.var(a, dim=1, keepdim=True) + tensor([[1.0631], + [0.5590], + [1.4893], + [0.8258]]) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def var( + input: Tensor, + dim: Sequence[str | EllipsisType | None], + *, + correction: Number | _complex | None = None, + keepdim: _bool = False, + out: Tensor | None = None, +) -> Tensor: + r""" + var(input, dim=None, *, correction=1, keepdim=False, out=None) -> Tensor + + Calculates the variance over the dimensions specified by :attr:`dim`. :attr:`dim` + can be a single dimension, list of dimensions, or ``None`` to reduce over all + dimensions. + + The variance (:math:`\sigma^2`) is calculated as + + .. math:: \sigma^2 = \frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2 + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.var(a, dim=1, keepdim=True) + tensor([[1.0631], + [0.5590], + [1.4893], + [0.8258]]) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def var( + input: Tensor, + dim: Sequence[str | EllipsisType | None], + unbiased: _bool = True, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + var(input, dim=None, *, correction=1, keepdim=False, out=None) -> Tensor + + Calculates the variance over the dimensions specified by :attr:`dim`. :attr:`dim` + can be a single dimension, list of dimensions, or ``None`` to reduce over all + dimensions. + + The variance (:math:`\sigma^2`) is calculated as + + .. math:: \sigma^2 = \frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2 + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.var(a, dim=1, keepdim=True) + tensor([[1.0631], + [0.5590], + [1.4893], + [0.8258]]) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def var_mean( + input: Tensor, + dim: _int | _size | None, + unbiased: _bool = True, + keepdim: _bool = False, +) -> tuple[Tensor, Tensor]: + r""" + var_mean(input, dim=None, *, correction=1, keepdim=False, out=None) -> (Tensor, Tensor) + + Calculates the variance and mean over the dimensions specified by :attr:`dim`. + :attr:`dim` can be a single dimension, list of dimensions, or ``None`` to + reduce over all dimensions. + + The variance (:math:`\sigma^2`) is calculated as + + .. math:: \sigma^2 = \frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2 + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Returns: + A tuple (var, mean) containing the variance and mean. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.var_mean(a, dim=0, keepdim=True) + (tensor([[1.5926, 1.0056, 1.2005, 0.3646]]), + tensor([[ 0.0645, 0.4485, 0.8707, -0.0665]])) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def var_mean( + input: Tensor, + dim: _int | _size | None = None, + *, + correction: Number | _complex | None = None, + keepdim: _bool = False, +) -> tuple[Tensor, Tensor]: + r""" + var_mean(input, dim=None, *, correction=1, keepdim=False, out=None) -> (Tensor, Tensor) + + Calculates the variance and mean over the dimensions specified by :attr:`dim`. + :attr:`dim` can be a single dimension, list of dimensions, or ``None`` to + reduce over all dimensions. + + The variance (:math:`\sigma^2`) is calculated as + + .. math:: \sigma^2 = \frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2 + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Returns: + A tuple (var, mean) containing the variance and mean. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.var_mean(a, dim=0, keepdim=True) + (tensor([[1.5926, 1.0056, 1.2005, 0.3646]]), + tensor([[ 0.0645, 0.4485, 0.8707, -0.0665]])) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def var_mean( + input: Tensor, + unbiased: _bool = True, +) -> tuple[Tensor, Tensor]: + r""" + var_mean(input, dim=None, *, correction=1, keepdim=False, out=None) -> (Tensor, Tensor) + + Calculates the variance and mean over the dimensions specified by :attr:`dim`. + :attr:`dim` can be a single dimension, list of dimensions, or ``None`` to + reduce over all dimensions. + + The variance (:math:`\sigma^2`) is calculated as + + .. math:: \sigma^2 = \frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2 + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Returns: + A tuple (var, mean) containing the variance and mean. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.var_mean(a, dim=0, keepdim=True) + (tensor([[1.5926, 1.0056, 1.2005, 0.3646]]), + tensor([[ 0.0645, 0.4485, 0.8707, -0.0665]])) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def var_mean( + input: Tensor, + dim: Sequence[str | EllipsisType | None], + *, + correction: Number | _complex | None = None, + keepdim: _bool = False, +) -> tuple[Tensor, Tensor]: + r""" + var_mean(input, dim=None, *, correction=1, keepdim=False, out=None) -> (Tensor, Tensor) + + Calculates the variance and mean over the dimensions specified by :attr:`dim`. + :attr:`dim` can be a single dimension, list of dimensions, or ``None`` to + reduce over all dimensions. + + The variance (:math:`\sigma^2`) is calculated as + + .. math:: \sigma^2 = \frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2 + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Returns: + A tuple (var, mean) containing the variance and mean. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.var_mean(a, dim=0, keepdim=True) + (tensor([[1.5926, 1.0056, 1.2005, 0.3646]]), + tensor([[ 0.0645, 0.4485, 0.8707, -0.0665]])) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def var_mean( + input: Tensor, + dim: Sequence[str | EllipsisType | None], + unbiased: _bool = True, + keepdim: _bool = False, +) -> tuple[Tensor, Tensor]: + r""" + var_mean(input, dim=None, *, correction=1, keepdim=False, out=None) -> (Tensor, Tensor) + + Calculates the variance and mean over the dimensions specified by :attr:`dim`. + :attr:`dim` can be a single dimension, list of dimensions, or ``None`` to + reduce over all dimensions. + + The variance (:math:`\sigma^2`) is calculated as + + .. math:: \sigma^2 = \frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2 + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Returns: + A tuple (var, mean) containing the variance and mean. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.var_mean(a, dim=0, keepdim=True) + (tensor([[1.5926, 1.0056, 1.2005, 0.3646]]), + tensor([[ 0.0645, 0.4485, 0.8707, -0.0665]])) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +def vdot( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + vdot(input, other, *, out=None) -> Tensor + + Computes the dot product of two 1D vectors along a dimension. + + In symbols, this function computes + + .. math:: + + \sum_{i=1}^n \overline{x_i}y_i. + + where :math:`\overline{x_i}` denotes the conjugate for complex + vectors, and it is the identity for real vectors. + + .. note:: + + Unlike NumPy's vdot, torch.vdot intentionally only supports computing the dot product + of two 1D tensors with the same number of elements. + + .. seealso:: + + :func:`torch.linalg.vecdot` computes the dot product of two batches of vectors along a dimension. + + Args: + input (Tensor): first tensor in the dot product, must be 1D. Its conjugate is used if it's complex. + other (Tensor): second tensor in the dot product, must be 1D. + + Keyword args: + + .. note:: out (Tensor, optional): the output tensor. + + + Example:: + + >>> torch.vdot(torch.tensor([2, 3]), torch.tensor([2, 1])) + tensor(7) + >>> a = torch.tensor((1 +2j, 3 - 1j)) + >>> b = torch.tensor((2 +1j, 4 - 0j)) + >>> torch.vdot(a, b) + tensor([16.+1.j]) + >>> torch.vdot(b, a) + tensor([16.-1.j]) + """ + +def view_as_complex(input: Tensor) -> Tensor: + r""" + view_as_complex(input) -> Tensor + + Returns a view of :attr:`input` as a complex tensor. For an input complex + tensor of :attr:`size` :math:`m1, m2, \dots, mi, 2`, this function returns a + new complex tensor of :attr:`size` :math:`m1, m2, \dots, mi` where the last + dimension of the input tensor is expected to represent the real and imaginary + components of complex numbers. + + .. warning:: + :func:`view_as_complex` is only supported for tensors with + :class:`torch.dtype` ``torch.float64`` and ``torch.float32``. The input is + expected to have the last dimension of :attr:`size` 2. In addition, the + tensor must have a `stride` of 1 for its last dimension. The strides of all + other dimensions must be even numbers. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> x=torch.randn(4, 2) + >>> x + tensor([[ 1.6116, -0.5772], + [-1.4606, -0.9120], + [ 0.0786, -1.7497], + [-0.6561, -1.6623]]) + >>> torch.view_as_complex(x) + tensor([(1.6116-0.5772j), (-1.4606-0.9120j), (0.0786-1.7497j), (-0.6561-1.6623j)]) + """ + +def view_as_complex_copy( + input: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.view_as_complex`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def view_as_real(input: Tensor) -> Tensor: + r""" + view_as_real(input) -> Tensor + + Returns a view of :attr:`input` as a real tensor. For an input complex tensor of + :attr:`size` :math:`m1, m2, \dots, mi`, this function returns a new + real tensor of size :math:`m1, m2, \dots, mi, 2`, where the last dimension of size 2 + represents the real and imaginary components of complex numbers. + + .. warning:: + :func:`view_as_real` is only supported for tensors with ``complex dtypes``. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> x=torch.randn(4, dtype=torch.cfloat) + >>> x + tensor([(0.4737-0.3839j), (-0.2098-0.6699j), (0.3470-0.9451j), (-0.5174-1.3136j)]) + >>> torch.view_as_real(x) + tensor([[ 0.4737, -0.3839], + [-0.2098, -0.6699], + [ 0.3470, -0.9451], + [-0.5174, -1.3136]]) + """ + +def view_as_real_copy( + input: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.view_as_real`, but all output tensors + are freshly created instead of aliasing the input. + """ + +@overload +def view_copy( + input: Tensor, + dtype: _dtype, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.view`, but all output tensors + are freshly created instead of aliasing the input. + """ + +@overload +def view_copy( + input: Tensor, + size: Sequence[_int | SymInt], + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.view`, but all output tensors + are freshly created instead of aliasing the input. + """ + +@overload +def vsplit(input: Tensor, sections: _int) -> tuple[Tensor, ...]: + r""" + vsplit(input, indices_or_sections) -> List of Tensors + + Splits :attr:`input`, a tensor with two or more dimensions, into multiple tensors + vertically according to :attr:`indices_or_sections`. Each split is a view of + :attr:`input`. + + This is equivalent to calling torch.tensor_split(input, indices_or_sections, dim=0) + (the split dimension is 0), except that if :attr:`indices_or_sections` is an integer + it must evenly divide the split dimension or a runtime error will be thrown. + + This function is based on NumPy's :func:`numpy.vsplit`. + + Args: + input (Tensor): tensor to split. + indices_or_sections (int or list or tuple of ints): See argument in :func:`torch.tensor_split`. + + Example:: + + >>> t = torch.arange(16.0).reshape(4,4) + >>> t + tensor([[ 0., 1., 2., 3.], + [ 4., 5., 6., 7.], + [ 8., 9., 10., 11.], + [12., 13., 14., 15.]]) + >>> torch.vsplit(t, 2) + (tensor([[0., 1., 2., 3.], + [4., 5., 6., 7.]]), + tensor([[ 8., 9., 10., 11.], + [12., 13., 14., 15.]])) + >>> torch.vsplit(t, [3, 6]) + (tensor([[ 0., 1., 2., 3.], + [ 4., 5., 6., 7.], + [ 8., 9., 10., 11.]]), + tensor([[12., 13., 14., 15.]]), + tensor([], size=(0, 4))) + """ + +@overload +def vsplit(input: Tensor, indices: _size) -> tuple[Tensor, ...]: + r""" + vsplit(input, indices_or_sections) -> List of Tensors + + Splits :attr:`input`, a tensor with two or more dimensions, into multiple tensors + vertically according to :attr:`indices_or_sections`. Each split is a view of + :attr:`input`. + + This is equivalent to calling torch.tensor_split(input, indices_or_sections, dim=0) + (the split dimension is 0), except that if :attr:`indices_or_sections` is an integer + it must evenly divide the split dimension or a runtime error will be thrown. + + This function is based on NumPy's :func:`numpy.vsplit`. + + Args: + input (Tensor): tensor to split. + indices_or_sections (int or list or tuple of ints): See argument in :func:`torch.tensor_split`. + + Example:: + + >>> t = torch.arange(16.0).reshape(4,4) + >>> t + tensor([[ 0., 1., 2., 3.], + [ 4., 5., 6., 7.], + [ 8., 9., 10., 11.], + [12., 13., 14., 15.]]) + >>> torch.vsplit(t, 2) + (tensor([[0., 1., 2., 3.], + [4., 5., 6., 7.]]), + tensor([[ 8., 9., 10., 11.], + [12., 13., 14., 15.]])) + >>> torch.vsplit(t, [3, 6]) + (tensor([[ 0., 1., 2., 3.], + [ 4., 5., 6., 7.], + [ 8., 9., 10., 11.]]), + tensor([[12., 13., 14., 15.]]), + tensor([], size=(0, 4))) + """ + +def vstack( + tensors: tuple[Tensor, ...] | list[Tensor] | None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + vstack(tensors, *, out=None) -> Tensor + + Stack tensors in sequence vertically (row wise). + + This is equivalent to concatenation along the first axis after all 1-D tensors have been reshaped by :func:`torch.atleast_2d`. + + Args: + tensors (sequence of Tensors): sequence of tensors to concatenate + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([1, 2, 3]) + >>> b = torch.tensor([4, 5, 6]) + >>> torch.vstack((a,b)) + tensor([[1, 2, 3], + [4, 5, 6]]) + >>> a = torch.tensor([[1],[2],[3]]) + >>> b = torch.tensor([[4],[5],[6]]) + >>> torch.vstack((a,b)) + tensor([[1], + [2], + [3], + [4], + [5], + [6]]) + """ + +@overload +def where(condition: Tensor) -> tuple[Tensor, ...]: + r""" + where(condition, input, other, *, out=None) -> Tensor + + Return a tensor of elements selected from either :attr:`input` or :attr:`other`, depending on :attr:`condition`. + + The operation is defined as: + + .. math:: + \text{out}_i = \begin{cases} + \text{input}_i & \text{if } \text{condition}_i \\ + \text{other}_i & \text{otherwise} \\ + \end{cases} + + .. note:: + The tensors :attr:`condition`, :attr:`input`, :attr:`other` must be :ref:`broadcastable `. + + Arguments: + condition (BoolTensor): When True (nonzero), yield input, otherwise yield other + input (Tensor or Scalar): value (if :attr:`input` is a scalar) or values selected at indices + where :attr:`condition` is ``True`` + other (Tensor or Scalar): value (if :attr:`other` is a scalar) or values selected at indices + where :attr:`condition` is ``False`` + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + Tensor: A tensor of shape equal to the broadcasted shape of :attr:`condition`, :attr:`input`, :attr:`other` + + Example:: + + >>> x = torch.randn(3, 2) + >>> y = torch.ones(3, 2) + >>> x + tensor([[-0.4620, 0.3139], + [ 0.3898, -0.7197], + [ 0.0478, -0.1657]]) + >>> torch.where(x > 0, 1.0, 0.0) + tensor([[0., 1.], + [1., 0.], + [1., 0.]]) + >>> torch.where(x > 0, x, y) + tensor([[ 1.0000, 0.3139], + [ 0.3898, 1.0000], + [ 0.0478, 1.0000]]) + >>> x = torch.randn(2, 2, dtype=torch.double) + >>> x + tensor([[ 1.0779, 0.0383], + [-0.8785, -1.1089]], dtype=torch.float64) + >>> torch.where(x > 0, x, 0.) + tensor([[1.0779, 0.0383], + [0.0000, 0.0000]], dtype=torch.float64) + + .. function:: where(condition) -> tuple of LongTensor + :noindex: + + ``torch.where(condition)`` is identical to + ``torch.nonzero(condition, as_tuple=True)``. + + .. note:: + See also :func:`torch.nonzero`. + """ + +@overload +def where( + condition: Tensor, + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + where(condition, input, other, *, out=None) -> Tensor + + Return a tensor of elements selected from either :attr:`input` or :attr:`other`, depending on :attr:`condition`. + + The operation is defined as: + + .. math:: + \text{out}_i = \begin{cases} + \text{input}_i & \text{if } \text{condition}_i \\ + \text{other}_i & \text{otherwise} \\ + \end{cases} + + .. note:: + The tensors :attr:`condition`, :attr:`input`, :attr:`other` must be :ref:`broadcastable `. + + Arguments: + condition (BoolTensor): When True (nonzero), yield input, otherwise yield other + input (Tensor or Scalar): value (if :attr:`input` is a scalar) or values selected at indices + where :attr:`condition` is ``True`` + other (Tensor or Scalar): value (if :attr:`other` is a scalar) or values selected at indices + where :attr:`condition` is ``False`` + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + Tensor: A tensor of shape equal to the broadcasted shape of :attr:`condition`, :attr:`input`, :attr:`other` + + Example:: + + >>> x = torch.randn(3, 2) + >>> y = torch.ones(3, 2) + >>> x + tensor([[-0.4620, 0.3139], + [ 0.3898, -0.7197], + [ 0.0478, -0.1657]]) + >>> torch.where(x > 0, 1.0, 0.0) + tensor([[0., 1.], + [1., 0.], + [1., 0.]]) + >>> torch.where(x > 0, x, y) + tensor([[ 1.0000, 0.3139], + [ 0.3898, 1.0000], + [ 0.0478, 1.0000]]) + >>> x = torch.randn(2, 2, dtype=torch.double) + >>> x + tensor([[ 1.0779, 0.0383], + [-0.8785, -1.1089]], dtype=torch.float64) + >>> torch.where(x > 0, x, 0.) + tensor([[1.0779, 0.0383], + [0.0000, 0.0000]], dtype=torch.float64) + + .. function:: where(condition) -> tuple of LongTensor + :noindex: + + ``torch.where(condition)`` is identical to + ``torch.nonzero(condition, as_tuple=True)``. + + .. note:: + See also :func:`torch.nonzero`. + """ + +@overload +def where( + condition: Tensor, + self: Number | _complex, + other: Tensor, +) -> Tensor: + r""" + where(condition, input, other, *, out=None) -> Tensor + + Return a tensor of elements selected from either :attr:`input` or :attr:`other`, depending on :attr:`condition`. + + The operation is defined as: + + .. math:: + \text{out}_i = \begin{cases} + \text{input}_i & \text{if } \text{condition}_i \\ + \text{other}_i & \text{otherwise} \\ + \end{cases} + + .. note:: + The tensors :attr:`condition`, :attr:`input`, :attr:`other` must be :ref:`broadcastable `. + + Arguments: + condition (BoolTensor): When True (nonzero), yield input, otherwise yield other + input (Tensor or Scalar): value (if :attr:`input` is a scalar) or values selected at indices + where :attr:`condition` is ``True`` + other (Tensor or Scalar): value (if :attr:`other` is a scalar) or values selected at indices + where :attr:`condition` is ``False`` + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + Tensor: A tensor of shape equal to the broadcasted shape of :attr:`condition`, :attr:`input`, :attr:`other` + + Example:: + + >>> x = torch.randn(3, 2) + >>> y = torch.ones(3, 2) + >>> x + tensor([[-0.4620, 0.3139], + [ 0.3898, -0.7197], + [ 0.0478, -0.1657]]) + >>> torch.where(x > 0, 1.0, 0.0) + tensor([[0., 1.], + [1., 0.], + [1., 0.]]) + >>> torch.where(x > 0, x, y) + tensor([[ 1.0000, 0.3139], + [ 0.3898, 1.0000], + [ 0.0478, 1.0000]]) + >>> x = torch.randn(2, 2, dtype=torch.double) + >>> x + tensor([[ 1.0779, 0.0383], + [-0.8785, -1.1089]], dtype=torch.float64) + >>> torch.where(x > 0, x, 0.) + tensor([[1.0779, 0.0383], + [0.0000, 0.0000]], dtype=torch.float64) + + .. function:: where(condition) -> tuple of LongTensor + :noindex: + + ``torch.where(condition)`` is identical to + ``torch.nonzero(condition, as_tuple=True)``. + + .. note:: + See also :func:`torch.nonzero`. + """ + +@overload +def where( + condition: Tensor, + input: Tensor, + other: Number | _complex, +) -> Tensor: + r""" + where(condition, input, other, *, out=None) -> Tensor + + Return a tensor of elements selected from either :attr:`input` or :attr:`other`, depending on :attr:`condition`. + + The operation is defined as: + + .. math:: + \text{out}_i = \begin{cases} + \text{input}_i & \text{if } \text{condition}_i \\ + \text{other}_i & \text{otherwise} \\ + \end{cases} + + .. note:: + The tensors :attr:`condition`, :attr:`input`, :attr:`other` must be :ref:`broadcastable `. + + Arguments: + condition (BoolTensor): When True (nonzero), yield input, otherwise yield other + input (Tensor or Scalar): value (if :attr:`input` is a scalar) or values selected at indices + where :attr:`condition` is ``True`` + other (Tensor or Scalar): value (if :attr:`other` is a scalar) or values selected at indices + where :attr:`condition` is ``False`` + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + Tensor: A tensor of shape equal to the broadcasted shape of :attr:`condition`, :attr:`input`, :attr:`other` + + Example:: + + >>> x = torch.randn(3, 2) + >>> y = torch.ones(3, 2) + >>> x + tensor([[-0.4620, 0.3139], + [ 0.3898, -0.7197], + [ 0.0478, -0.1657]]) + >>> torch.where(x > 0, 1.0, 0.0) + tensor([[0., 1.], + [1., 0.], + [1., 0.]]) + >>> torch.where(x > 0, x, y) + tensor([[ 1.0000, 0.3139], + [ 0.3898, 1.0000], + [ 0.0478, 1.0000]]) + >>> x = torch.randn(2, 2, dtype=torch.double) + >>> x + tensor([[ 1.0779, 0.0383], + [-0.8785, -1.1089]], dtype=torch.float64) + >>> torch.where(x > 0, x, 0.) + tensor([[1.0779, 0.0383], + [0.0000, 0.0000]], dtype=torch.float64) + + .. function:: where(condition) -> tuple of LongTensor + :noindex: + + ``torch.where(condition)`` is identical to + ``torch.nonzero(condition, as_tuple=True)``. + + .. note:: + See also :func:`torch.nonzero`. + """ + +@overload +def where( + condition: Tensor, + self: Number | _complex, + other: Number | _complex, +) -> Tensor: + r""" + where(condition, input, other, *, out=None) -> Tensor + + Return a tensor of elements selected from either :attr:`input` or :attr:`other`, depending on :attr:`condition`. + + The operation is defined as: + + .. math:: + \text{out}_i = \begin{cases} + \text{input}_i & \text{if } \text{condition}_i \\ + \text{other}_i & \text{otherwise} \\ + \end{cases} + + .. note:: + The tensors :attr:`condition`, :attr:`input`, :attr:`other` must be :ref:`broadcastable `. + + Arguments: + condition (BoolTensor): When True (nonzero), yield input, otherwise yield other + input (Tensor or Scalar): value (if :attr:`input` is a scalar) or values selected at indices + where :attr:`condition` is ``True`` + other (Tensor or Scalar): value (if :attr:`other` is a scalar) or values selected at indices + where :attr:`condition` is ``False`` + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + Tensor: A tensor of shape equal to the broadcasted shape of :attr:`condition`, :attr:`input`, :attr:`other` + + Example:: + + >>> x = torch.randn(3, 2) + >>> y = torch.ones(3, 2) + >>> x + tensor([[-0.4620, 0.3139], + [ 0.3898, -0.7197], + [ 0.0478, -0.1657]]) + >>> torch.where(x > 0, 1.0, 0.0) + tensor([[0., 1.], + [1., 0.], + [1., 0.]]) + >>> torch.where(x > 0, x, y) + tensor([[ 1.0000, 0.3139], + [ 0.3898, 1.0000], + [ 0.0478, 1.0000]]) + >>> x = torch.randn(2, 2, dtype=torch.double) + >>> x + tensor([[ 1.0779, 0.0383], + [-0.8785, -1.1089]], dtype=torch.float64) + >>> torch.where(x > 0, x, 0.) + tensor([[1.0779, 0.0383], + [0.0000, 0.0000]], dtype=torch.float64) + + .. function:: where(condition) -> tuple of LongTensor + :noindex: + + ``torch.where(condition)`` is identical to + ``torch.nonzero(condition, as_tuple=True)``. + + .. note:: + See also :func:`torch.nonzero`. + """ + +@overload +def xlogy( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + xlogy(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.special.xlogy`. + """ + +@overload +def xlogy( + self: Number | _complex, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + xlogy(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.special.xlogy`. + """ + +@overload +def xlogy( + input: Tensor, + other: Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + xlogy(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.special.xlogy`. + """ + +@overload +def xlogy_(input: Tensor, other: Tensor) -> Tensor: ... +@overload +def xlogy_(input: Tensor, other: Number | _complex) -> Tensor: ... +def zero_(input: Tensor) -> Tensor: ... +@overload +def zeros( + size: Sequence[_int | SymInt], + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + zeros(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with the scalar value `0`, with the shape defined + by the variable argument :attr:`size`. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.zeros(2, 3) + tensor([[ 0., 0., 0.], + [ 0., 0., 0.]]) + + >>> torch.zeros(5) + tensor([ 0., 0., 0., 0., 0.]) + """ + +@overload +def zeros( + *size: _int | SymInt, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + zeros(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with the scalar value `0`, with the shape defined + by the variable argument :attr:`size`. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.zeros(2, 3) + tensor([[ 0., 0., 0.], + [ 0., 0., 0.]]) + + >>> torch.zeros(5) + tensor([ 0., 0., 0., 0., 0.]) + """ + +@overload +def zeros( + size: _size, + *, + names: Sequence[str | EllipsisType | None] | None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + zeros(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with the scalar value `0`, with the shape defined + by the variable argument :attr:`size`. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.zeros(2, 3) + tensor([[ 0., 0., 0.], + [ 0., 0., 0.]]) + + >>> torch.zeros(5) + tensor([ 0., 0., 0., 0., 0.]) + """ + +@overload +def zeros( + *size: _int, + names: Sequence[str | EllipsisType | None] | None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + zeros(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with the scalar value `0`, with the shape defined + by the variable argument :attr:`size`. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.zeros(2, 3) + tensor([[ 0., 0., 0.], + [ 0., 0., 0.]]) + + >>> torch.zeros(5) + tensor([ 0., 0., 0., 0., 0.]) + """ + +def zeros_like( + input: Tensor, + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + zeros_like(input, *, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor filled with the scalar value `0`, with the same size as + :attr:`input`. ``torch.zeros_like(input)`` is equivalent to + ``torch.zeros(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``. + + .. warning:: + As of 0.4, this function does not support an :attr:`out` keyword. As an alternative, + the old ``torch.zeros_like(input, out=output)`` is equivalent to + ``torch.zeros(input.size(), out=output)``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + + Example:: + + >>> input = torch.empty(2, 3) + >>> torch.zeros_like(input) + tensor([[ 0., 0., 0.], + [ 0., 0., 0.]]) + """ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/__config__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/__config__.py new file mode 100644 index 0000000000000000000000000000000000000000..1187fab3713996932d4f3bad71bac243c6baff35 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/__config__.py @@ -0,0 +1,22 @@ +import torch + + +def show() -> str: + """ + Return a human-readable string with descriptions of the + configuration of PyTorch. + """ + return torch._C._show_config() + + +# TODO: In principle, we could provide more structured version/config +# information here. For now only CXX_FLAGS is exposed, as Timer +# uses them. +def _cxx_flags() -> str: + """Returns the CXX_FLAGS used when building PyTorch.""" + return torch._C._cxx_flags() + + +def parallel_info() -> str: + r"""Returns detailed string with parallelization settings""" + return torch._C._parallel_info() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/__future__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/__future__.py new file mode 100644 index 0000000000000000000000000000000000000000..f172ee3c8fe223aa316667f37f356e5b6658d20e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/__future__.py @@ -0,0 +1,75 @@ +_overwrite_module_params_on_conversion: bool = False +_swap_module_params_on_conversion: bool = False + + +def set_overwrite_module_params_on_conversion(value: bool) -> None: + """ + Sets whether to assign new tensors to the parameters instead of changing the + existing parameters in-place when converting an ``nn.Module``. + + When enabled, the following methods will assign new parameters to the module: + + #. ``module.{device}()`` (e.g. :meth:`nn.Module.cuda()`) for moving a module between devices + #. ``module.{dtype}()`` (e.g. :meth:`nn.Module.float()`) for converting a module to a different dtype + #. :meth:`nn.Module.to` + #. :meth:`nn.Module.to_empty` + + Args: + value (bool): Whether to assign new tensors or not. + + """ + global _overwrite_module_params_on_conversion + _overwrite_module_params_on_conversion = value + + +def get_overwrite_module_params_on_conversion() -> bool: + """ + Returns whether to assign new tensors to the parameters instead of changing the + existing parameters in-place when converting an :class:`torch.nn.Module`. Defaults to ``False``. + + See :func:`~torch.__future__.set_overwrite_module_params_on_conversion` for more information. + """ + return _overwrite_module_params_on_conversion + + +def set_swap_module_params_on_conversion(value: bool) -> None: + """ + Sets whether to use :func:`~torch.utils.swap_tensors` instead of setting ``.data`` to + change the existing parameters in-place when converting an ``nn.Module`` and instead + of ``param.copy_(state_dict[key])`` when loading a state dict into an ``nn.Module``. + + .. note:: + This function takes precedence over :func:`~torch.__future__.get_overwrite_module_params_on_conversion` + + When enabled, the following methods will swap the existing parameters in-place: + + #. ``module.{device}()`` (e.g. :meth:`nn.Module.cuda()`) for moving a module between devices + #. ``module.{dtype}()`` (e.g. :meth:`nn.Module.float()`) for converting a module to a different dtype + #. :meth:`nn.Module.to` + #. :meth:`nn.Module.to_empty` + #. :meth:`nn.Module.load_state_dict` + + The semantics for :meth:`~nn.Module.load_state_dict` when this is set are as follows: + + #. For each parameter/buffer, its corresponding ``state_dict['key']`` is transformed via + :meth:`~torch.Tensor.module_load` (i.e. ``res = param.module_load(state_dict['key'])``) + #. If necessary, ``res`` will be wrapped in an :class:`~nn.Parameter` + #. The parameter/buffer in the module will be swapped via :func:`~torch.utils.swap_tensors` + with ``res`` + + Args: + value (bool): Whether to use :func:`~torch.utils.swap_tensors` or not. + + """ + global _swap_module_params_on_conversion + _swap_module_params_on_conversion = value + + +def get_swap_module_params_on_conversion() -> bool: + """ + Returns whether to use :func:`~torch.utils.swap_tensors` instead of setting .data to + change the existing parameters in-place when converting an ``nn.Module``. Defaults to ``False``. + + See :func:`~torch.__future__.set_swap_module_params_on_conversion` for more information. + """ + return _swap_module_params_on_conversion diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b0f2e2d27dc9ee37c8d6c8cde3dc8c0ad2c09d87 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/__init__.py @@ -0,0 +1,2985 @@ +""" +The torch package contains data structures for multi-dimensional +tensors and defines mathematical operations over these tensors. +Additionally, it provides many utilities for efficient serialization of +Tensors and arbitrary types, and other useful utilities. + +It has a CUDA counterpart, that enables you to run your tensor computations +on an NVIDIA GPU with compute capability >= 3.0. +""" + +# mypy: allow-untyped-defs + +import builtins +import ctypes +import functools +import glob +import importlib +import inspect +import math +import os +import platform +import sys +import textwrap +import threading +import warnings +from collections.abc import Callable as _Callable +from typing import ( + Any as _Any, + get_origin as _get_origin, + overload as _overload, + TYPE_CHECKING, + TypeVar as _TypeVar, +) +from typing_extensions import ParamSpec as _ParamSpec, TypeIs as _TypeIs + + +# As a bunch of torch.packages internally still have this check +# we need to keep this. @todo: Remove tests that rely on this check as +# they are likely stale. +def _running_with_deploy() -> builtins.bool: + return False + + +from torch._utils import ( + _functionalize_sync as _sync, + _import_dotted_name, + classproperty, +) +from torch._utils_internal import ( + get_file_path, + prepare_multiprocessing_environment, + profiler_allow_cudagraph_cupti_lazy_reinit_cuda12, + USE_GLOBAL_DEPS, + USE_RTLD_GLOBAL_WITH_LIBTORCH, +) +from torch.torch_version import __version__ as __version__ + + +if TYPE_CHECKING: + from torch.types import Device, IntLikeType + + +__all__ = [ + "BoolStorage", + "BoolTensor", + "ByteStorage", + "ByteTensor", + "CharStorage", + "CharTensor", + "DoubleStorage", + "DoubleTensor", + "FloatStorage", + "FloatTensor", + "GradScaler", + "IntStorage", + "IntTensor", + "LongStorage", + "LongTensor", + "ShortStorage", + "ShortTensor", + "SymBool", + "SymFloat", + "SymInt", + "Tensor", + "TypedStorage", + "UntypedStorage", + "are_deterministic_algorithms_enabled", + "autocast", + "chunk", + "compile", + "cond", + "enable_grad", + "export", + "get_default_device", + "get_deterministic_debug_mode", + "get_device_module", + "get_float32_matmul_precision", + "get_rng_state", + "inference_mode", + "initial_seed", + "is_deterministic_algorithms_warn_only_enabled", + "is_storage", + "is_tensor", + "is_warn_always_enabled", + "load", + "lobpcg", + "manual_seed", + "matmul", + "no_grad", + "rand", + "randn", + "save", + "seed", + "set_default_device", + "set_default_tensor_type", + "set_deterministic_debug_mode", + "set_float32_matmul_precision", + "set_printoptions", + "set_rng_state", + "set_warn_always", + "split", + "stack", + "sym_float", + "sym_fresh_size", + "sym_int", + "sym_ite", + "sym_max", + "sym_min", + "sym_not", + "sym_sum", + "typename", + "unravel_index", + "use_deterministic_algorithms", + "vmap", +] + +# Please keep this list sorted +assert __all__ == sorted(__all__) + +################################################################################ +# Load the extension module +################################################################################ + +# If PyTorch was built against the ROCm runtime wheels, then there will be +# a _rocm_init module and it will define an initialize() function which can +# prepare ROCm for use. See general documentation on ROCm runtime wheels: +# https://github.com/ROCm/TheRock/blob/main/docs/packaging/python_packaging.md +# Since this module is only ever added to the wheel if built for such a +# deployment, it is always safe to attempt. +try: + from . import _rocm_init # type: ignore[attr-defined] +except ImportError: + pass +else: + _rocm_init.initialize() + del _rocm_init + + +if sys.platform == "win32": + + def _load_dll_libraries() -> None: + import sysconfig + + from torch.version import cuda as cuda_version + + pfiles_path = os.getenv("ProgramFiles", r"C:\Program Files") + py_dll_path = os.path.join(sys.exec_prefix, "Library", "bin") + th_dll_path = os.path.join(os.path.dirname(__file__), "lib") + usebase_path = os.path.join( + sysconfig.get_config_var("userbase"), "Library", "bin" + ) + py_root_bin_path = os.path.join(sys.exec_prefix, "bin") + + # When users create a virtualenv that inherits the base environment, + # we will need to add the corresponding library directory into + # DLL search directories. Otherwise, it will rely on `PATH` which + # is dependent on user settings. + if sys.exec_prefix != sys.base_exec_prefix: + base_py_dll_path = os.path.join(sys.base_exec_prefix, "Library", "bin") + else: + base_py_dll_path = "" + + dll_paths = [ + p + for p in ( + th_dll_path, + py_dll_path, + base_py_dll_path, + usebase_path, + py_root_bin_path, + ) + if os.path.exists(p) + ] + + if not builtins.any( + os.path.exists(os.path.join(p, "nvToolsExt64_1.dll")) for p in dll_paths + ): + nvtoolsext_dll_path = os.path.join( + os.getenv( + "NVTOOLSEXT_PATH", + os.path.join(pfiles_path, "NVIDIA Corporation", "NvToolsExt"), + ), + "bin", + "x64", + ) + else: + nvtoolsext_dll_path = "" + + if cuda_version and builtins.all( + not glob.glob(os.path.join(p, "cudart64*.dll")) for p in dll_paths + ): + cuda_version_1 = cuda_version.replace(".", "_") + cuda_path_var = "CUDA_PATH_V" + cuda_version_1 + default_path = os.path.join( + pfiles_path, "NVIDIA GPU Computing Toolkit", "CUDA", f"v{cuda_version}" + ) + cuda_path = os.path.join(os.getenv(cuda_path_var, default_path), "bin") + else: + cuda_path = "" + + dll_paths.extend( + p for p in (nvtoolsext_dll_path, cuda_path) if os.path.exists(p) + ) + + kernel32 = ctypes.WinDLL("kernel32.dll", use_last_error=True) + with_load_library_flags = hasattr(kernel32, "AddDllDirectory") + prev_error_mode = kernel32.SetErrorMode(0x0001) + + kernel32.LoadLibraryW.restype = ctypes.c_void_p + if with_load_library_flags: + kernel32.LoadLibraryExW.restype = ctypes.c_void_p + + for dll_path in dll_paths: + os.add_dll_directory(dll_path) + + try: + ctypes.CDLL("vcruntime140.dll") + ctypes.CDLL("msvcp140.dll") + if platform.machine() != "ARM64": + ctypes.CDLL("vcruntime140_1.dll") + except OSError: + print( + textwrap.dedent( + """ + Microsoft Visual C++ Redistributable is not installed, this may lead to the DLL load failure. + It can be downloaded at https://aka.ms/vs/17/release/vc_redist.x64.exe + """ + ).strip() + ) + + dlls = glob.glob(os.path.join(th_dll_path, "*.dll")) + path_patched = False + for dll in dlls: + is_loaded = False + if with_load_library_flags: + res = kernel32.LoadLibraryExW(dll, None, 0x00001100) + last_error = ctypes.get_last_error() + if res is None and last_error != 126: + err = ctypes.WinError(last_error) + err.strerror += ( + f' Error loading "{dll}" or one of its dependencies.' + ) + raise err + elif res is not None: + is_loaded = True + if not is_loaded: + if not path_patched: + os.environ["PATH"] = ";".join(dll_paths + [os.environ["PATH"]]) + path_patched = True + res = kernel32.LoadLibraryW(dll) + if res is None: + err = ctypes.WinError(ctypes.get_last_error()) + err.strerror += ( + f' Error loading "{dll}" or one of its dependencies.' + ) + raise err + + kernel32.SetErrorMode(prev_error_mode) + + _load_dll_libraries() + del _load_dll_libraries + + +def _get_cuda_dep_paths(path: str, lib_folder: str, lib_name: str) -> list[str]: + # Libraries can either be in + # path/nvidia/lib_folder/lib or + # path/nvidia/cuXX/lib (since CUDA 13.0) or + # path/lib_folder/lib + from torch.version import cuda as cuda_version + + nvidia_lib_paths = glob.glob( + os.path.join(path, "nvidia", lib_folder, "lib", lib_name) + ) + if cuda_version is not None: + maj_cuda_version = cuda_version.split(".")[0] + nvidia_lib_paths += glob.glob( + os.path.join(path, "nvidia", f"cu{maj_cuda_version}", "lib", lib_name) + ) + lib_paths = glob.glob(os.path.join(path, lib_folder, "lib", lib_name)) + + return nvidia_lib_paths + lib_paths + + +def _preload_cuda_lib(lib_folder: str, lib_name: str, required: bool = True) -> None: # type: ignore[valid-type] + """Preloads cuda library if it could not be found otherwise.""" + # Should only be called on Linux if default path resolution have failed + assert platform.system() == "Linux", "Should only be called on Linux" + + lib_path = None + for path in sys.path: + candidate_lib_paths = _get_cuda_dep_paths(path, lib_folder, lib_name) + if candidate_lib_paths: + lib_path = candidate_lib_paths[0] + break + if not lib_path and required: + raise ValueError(f"{lib_name} not found in the system path {sys.path}") + if lib_path: + ctypes.CDLL(lib_path) + + +def _preload_cuda_deps(err: OSError | None = None) -> None: + cuda_libs: list[tuple[str, str]] = [ + # NOTE: Order matters! We must preload libcublasLt BEFORE libcublas to prevent + # libcublas from loading a mismatched system-wide libcublasLt via its RUNPATH. + # Without this, if a different CUDA Toolkit version exists in the system PATH, + # libcublas may load the wrong libcublasLt, causing symbol errors or runtime failure. + ("cublas", "libcublasLt.so.*[0-9]"), + ("cublas", "libcublas.so.*[0-9]"), + ("cudnn", "libcudnn.so.*[0-9]"), + ("cuda_nvrtc", "libnvrtc.so.*[0-9]"), + ("cuda_nvrtc", "libnvrtc-builtins.so.*[0-9]"), + ("cuda_runtime", "libcudart.so.*[0-9]"), + ("cuda_cupti", "libcupti.so.*[0-9]"), + ("cufft", "libcufft.so.*[0-9]"), + ("curand", "libcurand.so.*[0-9]"), + ("nvjitlink", "libnvJitLink.so.*[0-9]"), + ("cusparse", "libcusparse.so.*[0-9]"), + ("cusparselt", "libcusparseLt.so.*[0-9]"), + ("cusolver", "libcusolver.so.*[0-9]"), + ("nccl", "libnccl.so.*[0-9]"), + ("nvshmem", "libnvshmem_host.so.*[0-9]"), + ("cufile", "libcufile.so.*[0-9]"), + ] + # If error is passed, re-raise it if it's not about one of the abovementioned + # libraries + if err is not None and not [ + lib for _, lib in cuda_libs if lib.split(".", 1)[0] in err.args[0] + ]: + raise err + + # Otherwise, try to preload dependencies from site-packages + for lib_folder, lib_name in cuda_libs: + _preload_cuda_lib(lib_folder, lib_name) + + # libnvToolsExt is Optional Dependency + _preload_cuda_lib("nvtx", "libnvToolsExt.so.*[0-9]", required=False) + + +# See Note [Global dependencies] +def _load_global_deps() -> None: + if platform.system() == "Windows": + return + + # Determine the file extension based on the platform + lib_ext = ".dylib" if platform.system() == "Darwin" else ".so" + lib_name = f"libtorch_global_deps{lib_ext}" + here = os.path.abspath(__file__) + global_deps_lib_path = os.path.join(os.path.dirname(here), "lib", lib_name) + + try: + ctypes.CDLL(global_deps_lib_path, mode=ctypes.RTLD_GLOBAL) + # Workaround slim-wheel CUDA dependency bugs in cusparse and cudnn by preloading nvjitlink + # and nvrtc. In CUDA-12.4+ cusparse depends on nvjitlink, but does not have rpath when + # shipped as wheel, which results in OS picking wrong/older version of nvjitlink library + # if `LD_LIBRARY_PATH` is defined, see https://github.com/pytorch/pytorch/issues/138460 + # Similar issue exist in cudnn that dynamically loads nvrtc, unaware of its relative path. + # See https://github.com/pytorch/pytorch/issues/145580 + try: + with open("/proc/self/maps") as f: + _maps = f.read() + + # libtorch_global_deps.so always depends in cudart, check if its installed and loaded + if "libcudart.so" not in _maps: + return + # If all above-mentioned conditions are met, preload CUDA dependencies + _preload_cuda_deps() + except Exception: + pass + + except OSError as err: + # Can happen for wheel with cuda libs as PYPI deps + # As PyTorch is not purelib, but nvidia-*-cu12 is + _preload_cuda_deps(err) + ctypes.CDLL(global_deps_lib_path, mode=ctypes.RTLD_GLOBAL) + + +if (USE_RTLD_GLOBAL_WITH_LIBTORCH or os.getenv("TORCH_USE_RTLD_GLOBAL")) and ( + platform.system() != "Windows" +): + # Do it the hard way. You might want to load libtorch with RTLD_GLOBAL in a + # few circumstances: + # + # 1. You're in a build environment (e.g., fbcode) where + # libtorch_global_deps is not available, but you still need + # to get mkl to link in with RTLD_GLOBAL or it will just + # not work. + # + # 2. You're trying to run PyTorch under UBSAN and you need + # to ensure that only one copy of libtorch is loaded, so + # vptr checks work properly + # + # If you're using this setting, you must verify that all the libraries + # you load consistently use the same libstdc++, or you may have + # mysterious segfaults. + # + old_flags = sys.getdlopenflags() + sys.setdlopenflags(os.RTLD_GLOBAL | os.RTLD_LAZY) + + from torch._C import * # noqa: F403 + + sys.setdlopenflags(old_flags) + del old_flags + +else: + # Easy way. You want this most of the time, because it will prevent + # C++ symbols from libtorch clobbering C++ symbols from other + # libraries, leading to mysterious segfaults. + # + # If building in an environment where libtorch_global_deps isn't available + # like parts of fbsource, but where RTLD_GLOBAL causes segfaults, you will + # want USE_RTLD_GLOBAL_WITH_LIBTORCH = False and USE_GLOBAL_DEPS = False + # + # See Note [Global dependencies] + if USE_GLOBAL_DEPS: + _load_global_deps() + from torch._C import * # noqa: F403 + + +class SymInt: + """ + Like an int (including magic methods), but redirects all operations on the + wrapped node. This is used in particular to symbolically record operations + in the symbolic shape workflow. + """ + + def __init__(self, node): + # This field MUST be named node; C++ binding code assumes that this + # class has a field named node that stores SymNode + self.node = node + + def __bool__(self): + return builtins.bool(self != 0) + + def __int__(self): + return self.node.int_() + + def __index__(self): + return self.node.int_() + + # Magic methods installed by torch.fx.experimental.sym_node + + def __round__(self, ndigits=None): + return self + + def __truediv__(self, other): + if isinstance(other, (builtins.float, SymFloat)): + return sym_float(self).__float_truediv__(other) + if not isinstance(other, (builtins.int, SymInt)): + return NotImplemented + return self.__int_truediv__(other) + + def __rtruediv__(self, other): + if isinstance(other, (builtins.float, SymFloat)): + return sym_float(self).__rfloat_truediv__(other) + if not isinstance(other, (builtins.int, SymInt)): + return NotImplemented + return self.__rint_truediv__(other) + + def __floordiv__(self, other): + if isinstance(other, (builtins.float, SymFloat)): + return sym_float(math.floor(sym_float(self) / other)) + if not isinstance(other, (builtins.int, SymInt)): + return NotImplemented + return self.__int_floordiv__(other) + + def __rfloordiv__(self, other): + if isinstance(other, (builtins.float, SymFloat)): + return sym_float(math.floor(other / sym_float(self))) + if not isinstance(other, (builtins.int, SymInt)): + return NotImplemented + return self.__rint_floordiv__(other) + + # nb: complex is impossible to handle correctly lol, with + # negative base and integral float need to diverge semantics and + # just always return complex. Neener neener pretend this problem + # doesn't exist + def __pow__(self, other): + if isinstance(other, (builtins.float, SymFloat)): + return sym_float(self).__pow__(other) + if not isinstance(other, (builtins.int, SymInt)): + return NotImplemented + # Guards! This guard is necessary because we need to know it to + # determine the output type of this operation + if other >= 0: + return self.__pow_by_natural__(other) + else: + # Mercifully, when the exponent is negative, Python just promotes + # to doubles and does a float pow: + # + # if (Py_SIZE(b) < 0 && c == NULL) { + # /* if exponent is negative and there's no modulus: + # return a float. This works because we know + # that this calls float_pow() which converts its + # arguments to double. */ + # Py_DECREF(a); + # Py_DECREF(b); + # return PyFloat_Type.tp_as_number->nb_power(v, w, x); + # } + return sym_float(self).__pow__(sym_float(other)) + + def __rpow__(self, other): + if isinstance(other, (builtins.float, SymFloat)): + return sym_float(self).__rpow__(other) + if not isinstance(other, (builtins.int, SymInt)): + return NotImplemented + if self >= 0: # self is exponent + return self.__rpow_by_natural__(other) + else: + return sym_float(self).__rpow__(sym_float(other)) + + def __eq__(self, other: object) -> builtins.bool: + raise TypeError("type stub not overridden") + + def __lt__(self, other) -> builtins.bool: + raise TypeError("type stub not overridden") + + def __gt__(self, other) -> builtins.bool: + raise TypeError("type stub not overridden") + + def __le__(self, other) -> builtins.bool: + raise TypeError("type stub not overridden") + + def __ge__(self, other) -> builtins.bool: + raise TypeError("type stub not overridden") + + def __add__(self, other) -> "SymInt": + raise TypeError("type stub not overridden") + + def __radd__(self, other) -> "SymInt": + raise TypeError("type stub not overridden") + + def __rmul__(self, other) -> "SymInt": + raise TypeError("type stub not overridden") + + def __mod__(self, other: "IntLikeType") -> "SymInt": + raise TypeError("type stub not overridden") + + def __mul__(self, other) -> "SymInt": + raise TypeError("type stub not overridden") + + def __pow_by_natural__(self, other) -> "SymInt": + raise TypeError("type stub not overridden") + + def __rpow_by_natural__(self, other) -> "SymInt": + raise TypeError("type stub not overridden") + + def __int_truediv__(self, other) -> "SymFloat": + raise TypeError("type stub not overridden") + + def __rint_truediv__(self, other) -> "SymFloat": + raise TypeError("type stub not overridden") + + def __int_floordiv__(self, other) -> "SymFloat": + raise TypeError("type stub not overridden") + + def __rint_floordiv__(self, other) -> "SymFloat": + raise TypeError("type stub not overridden") + + def __sym_max__(self, other): + raise TypeError("type stub not overridden") + + def __sym_min__(self, other): + raise TypeError("type stub not overridden") + + def __sym_float__(self): + raise TypeError("type stub not overridden") + + def __neg__(self): + raise TypeError("type stub not overridden") + + def __sub__(self, other: "IntLikeType") -> "SymInt": + raise TypeError("type stub not overridden") + + def __rsub__(self, other: "IntLikeType") -> "SymInt": + raise TypeError("type stub not overridden") + + def __and__(self, other) -> "SymInt": + raise TypeError("type stub not overridden") + + def __or__(self, other) -> "SymInt": + raise TypeError("type stub not overridden") + + def __repr__(self): + return self.node._graph_repr() + + def _sympy_(self): + return self.node.expr + + def __hash__(self) -> builtins.int: + if self.node.is_nested_int(): + return hash(self.node.nested_int()) + else: + # We could support constant SymInts as well, but not doing it for now + raise TypeError("unhashable type: non-nested SymInt") + # TODO: Force specialization + # This can't be done because the TypeError here is load bearing + # for einops + # https://github.com/arogozhnikov/einops/blob/6181e1e95dc58c00a3143c1726da1c6ee0463164/einops/einops.py#L237 + # return hash(builtins.int(self)) + + def as_integer_ratio(self) -> tuple["SymInt", builtins.int]: + """Represent this int as an exact integer ratio""" + return self, 1 + + def bit_length(self) -> builtins.int: + # TODO: A more relaxed guard is possible here, where you guard to + # allow all integer quantities which would result in the same bit + # length. We can also just make a dedicated Sympy function for + # computing this quantity and represent it symbolically. + return builtins.int(self).bit_length() + + def conjugate(self) -> "SymInt": + return self + + +class SymFloat: + """ + Like a float (including magic methods), but redirects all operations on the + wrapped node. This is used in particular to symbolically record operations + in the symbolic shape workflow. + """ + + def __init__(self, node): + # This field MUST be named node; C++ binding code assumes that this + # class has a field named node that stores SymNode + self.node = node + + def __truediv__(self, other): + if not isinstance(other, (builtins.int, builtins.float, SymInt, SymFloat)): + return NotImplemented + return self.__float_truediv__(sym_float(other)) + + def __rtruediv__(self, other): + if not isinstance(other, (builtins.int, builtins.float, SymInt, SymFloat)): + return NotImplemented + return self.__rfloat_truediv__(sym_float(other)) + + def __floordiv__(self, other): + if not isinstance(other, (builtins.int, builtins.float, SymInt, SymFloat)): + return NotImplemented + return sym_float(math.floor(self / sym_float(other))) + + def __rfloordiv__(self, other): + if not isinstance(other, (builtins.int, builtins.float, SymInt, SymFloat)): + return NotImplemented + return sym_float(math.floor(sym_float(other) / self)) + + def __bool__(self): + return self.node.bool_() + + def __float__(self): + return self.node.guard_float("", 0) + + def __int__(self): + return self.__trunc__().__int__() + + # Symbolic power does NOT work with negative base, this is to avoid + # potential complex outputs + def __pow__(self, other): + if not isinstance(other, (builtins.int, builtins.float, SymInt, SymFloat)): + return NotImplemented + torch._check(self >= 0) + return self.__float_pow__(other) + + def __rpow__(self, other): + if not isinstance(other, (builtins.int, builtins.float, SymInt, SymFloat)): + return NotImplemented + torch._check(other >= 0) + return self.__rfloat_pow__(other) + + # Magic methods installed by torch.fx.experimental.sym_node + + def __eq__(self, other: object) -> builtins.bool: + raise TypeError("type stub not overridden") + + def __lt__(self, other) -> builtins.bool: + raise TypeError("type stub not overridden") + + def __gt__(self, other) -> builtins.bool: + raise TypeError("type stub not overridden") + + def __le__(self, other) -> builtins.bool: + raise TypeError("type stub not overridden") + + def __ge__(self, other) -> builtins.bool: + raise TypeError("type stub not overridden") + + def __float_pow__(self, other) -> "SymFloat": + raise TypeError("type stub not overridden") + + def __rfloat_pow__(self, other) -> "SymFloat": + raise TypeError("type stub not overridden") + + def __float_truediv__(self, other) -> "SymFloat": + raise TypeError("type stub not overridden") + + def __rfloat_truediv__(self, other) -> "SymFloat": + raise TypeError("type stub not overridden") + + def __trunc__(self): + raise TypeError("type stub not overridden") + + def __sym_max__(self, other): + raise TypeError("type stub not overridden") + + def __sym_min__(self, other): + raise TypeError("type stub not overridden") + + def __sym_int__(self): + raise TypeError("type stub not overridden") + + def is_integer(self): + """Return True if the float is an integer.""" + raise TypeError("type stub not overridden") + + def as_integer_ratio(self) -> tuple[builtins.int, builtins.int]: + """Represent this float as an exact integer ratio""" + return builtins.float(self).as_integer_ratio() + + def __repr__(self): + return self.node._graph_repr() + + def _sympy_(self): + return self.node.expr + + def __hash__(self): + return hash(builtins.float(self)) + + def conjugate(self) -> "SymFloat": + """Returns the complex conjugate of the float.""" + return self + + def hex(self) -> str: + """Returns the hexadecimal representation of the float.""" + return self.node.guard_float("", 0).hex() + + +class SymBool: + """ + Like a bool (including magic methods), but redirects all operations on the + wrapped node. This is used in particular to symbolically record operations + in the symbolic shape workflow. + + Unlike regular bools, regular boolean operators will force extra guards instead + of symbolically evaluate. Use the bitwise operators instead to handle this. + """ + + def __init__(self, node): + # This field MUST be named node; C++ binding code assumes that this + # class has a field named node that stores SymNode + self.node = node + + def __bool__(self): + return self.node.bool_() + + def __int__(self): + return builtins.int(self.node.bool_()) + + # Magic methods installed by torch.fx.experimental.sym_node + def __and__(self, other) -> "SymBool": + raise TypeError("type stub not overridden") + + def __or__(self, other) -> "SymBool": + raise TypeError("type stub not overridden") + + # We very carefully define __sym_not__, and not a number of other + # plausible alternatives: + # + # - We do not override __not__ because this is not a real magic + # method; you cannot override the meaning of the not builtin in + # Python. We use the name 'sym_not' to clarify that in user code you + # cannot use the builtin not or operator.not_ or operator.__not__ and + # hit this magic method; you must use our custom sym_not operator. + # + # - We do not override the __invert__ method because SymBool is + # meant to be usable in situations where bool is expected. However, + # bitwise negation ~a does the wrong thing with booleans (because + # bool is a subclass of int, so ~1 = -2 which is not falseish.) + # This would be a giant footgun, so we get around it by defining + # our own operator. Note that bitwise and/or do the right thing, + # so we reuse the conventional operators there for readability. + # + def __sym_not__(self) -> "SymBool": + raise TypeError("type stub not overridden") + + def __sym_ite__(self, then_val, else_val): + raise TypeError("type stub not overridden") + + def __eq__(self, other) -> builtins.bool: + raise TypeError("type stub not overridden") + + def __repr__(self): + return self.node._graph_repr() + + def _sympy_(self): + return self.node.expr + + def __hash__(self): + if self.node.is_constant(): + return hash(self.node.bool_()) + else: + # Force specialization + return hash(builtins.bool(self)) + + def __sym_float__(self): + """ + Provides a SymFloat representation (0.0 or 1.0) for this SymBool. + Called by torch.sym_float() when casting SymBool to float. + """ + from torch.fx.experimental.sym_node import wrap_node + + return wrap_node(self.node.sym_float()) + + +def sym_not(a): + r"""SymInt-aware utility for logical negation. + + Args: + a (SymBool or bool): Object to negate + """ + import sympy + + if overrides.has_torch_function_unary(a): + return overrides.handle_torch_function(sym_not, (a,), a) + if hasattr(a, "__sym_not__"): + return a.__sym_not__() + if isinstance(a, sympy.Basic): + return ~a # type: ignore[operator] + return not a + + +def sym_float(a): + r"""SymInt-aware utility for float casting. + + Args: + a (SymInt, SymFloat, or object): Object to cast + """ + if overrides.has_torch_function_unary(a): + return overrides.handle_torch_function(sym_float, (a,), a) + if isinstance(a, SymFloat): + return a + elif hasattr(a, "__sym_float__"): + return a.__sym_float__() + return builtins.float(a) # type: ignore[operator] + + +def sym_int(a): + r"""SymInt-aware utility for int casting. + + Args: + a (SymInt, SymFloat, or object): Object to cast + """ + if overrides.has_torch_function_unary(a): + return overrides.handle_torch_function(sym_int, (a,), a) + if isinstance(a, SymInt): + return a + elif isinstance(a, SymFloat): + return math.trunc(a) + return builtins.int(a) # type: ignore[operator] + + +def sym_max(a, b): + """ + SymInt-aware utility for max which avoids branching on a < b. + Unlike builtins.max(), this only works for int/float, and it always + promotes to float if any argument is float (unlike builtins.max, which + will faithfully preserve the type of the input argument). + """ + if overrides.has_torch_function((a, b)): + return overrides.handle_torch_function(sym_max, (a, b), a, b) + if isinstance(a, (SymInt, SymFloat)): + return a.__sym_max__(b) + elif isinstance(b, (SymInt, SymFloat)): + # Due to promotion semantics, this is operator is commutative: + # max(1, 1.0) === max(1.0, 1) === 1.0 + return b.__sym_max__(a) + # TODO: Probably can make bool work too, just lazy + + all_types, float_types = __all_and_float_types() + + assert isinstance(a, all_types), type(a) + assert isinstance(b, all_types), type(b) + if isinstance(a, float_types) or isinstance(b, float_types): + return builtins.float(builtins.max(a, b)) # type: ignore[call-overload] + else: + return builtins.max(a, b) # type: ignore[call-overload] + + +def __all_and_float_types() -> tuple[tuple[type, ...], tuple[type, ...]]: + try: + import numpy as np + + all_types: tuple[type, ...] = ( + np.integer, + np.floating, + builtins.int, + builtins.float, + ) + float_types: tuple[type, ...] = (np.floating, builtins.float) + except ModuleNotFoundError: + all_types = (builtins.int, builtins.float) + float_types = (builtins.float,) + + return all_types, float_types + + +def sym_min(a, b): + """SymInt-aware utility for min().""" + if overrides.has_torch_function((a, b)): + return overrides.handle_torch_function(sym_min, (a, b), a, b) + if isinstance(a, (SymInt, SymFloat)): + return a.__sym_min__(b) + elif isinstance(b, (SymInt, SymFloat)): + return b.__sym_min__(a) + + all_types, float_types = __all_and_float_types() + + assert isinstance(a, all_types), type(a) + assert isinstance(b, all_types), type(b) + if isinstance(a, float_types) or isinstance(b, float_types): + return builtins.float(builtins.min(a, b)) # type: ignore[call-overload] + else: + return builtins.min(a, b) # type: ignore[call-overload] + + +def sym_sum(args): + """ + N-ary add which is faster to compute for long lists than iterated binary + addition. Only does something special for integers. + """ + if overrides.has_torch_function(args): + return overrides.handle_torch_function(sym_sum, args, args) + + found = None + for a in args: + if not isinstance(a, (SymInt, builtins.int)): + return builtins.sum(args) + if isinstance(a, SymInt): + found = a.node + if found is None: + return builtins.sum(args) + + from torch.fx.experimental.sym_node import to_node, wrap_node + + return wrap_node(found.sym_sum(tuple(to_node(found, a) for a in args))) + + +# Drop in replacement for math.sqrt, math.sin, math.cos etc +def _get_sym_math_fn(name): + def fn(a): + if overrides.has_torch_function_unary(a): + return overrides.handle_torch_function(fn, (a,), a) + if isinstance(a, SymInt): + a = torch.sym_float(a) + if hasattr(a, f"__sym_{name}__"): + return getattr(a, f"__sym_{name}__")() + return getattr(math, name)(a) + + return fn + + +__fn, __name, __sym_name = None, "", "" +for __name in ( + "sqrt", + "cos", + "cosh", + "sin", + "sinh", + "tan", + "tanh", + "asin", + "acos", + "atan", + "log2", +): + __sym_name = f"_sym_{__name}" + __fn = _get_sym_math_fn(__name) + __fn.__qualname__ = __fn.__name__ = __sym_name + globals()[__sym_name] = __fn + + +del __fn, __name, __sym_name, _get_sym_math_fn + +# Adding temporary shortcut +sym_sqrt = globals()["_sym_sqrt"] +__all__.append("sym_sqrt") + + +def sym_ite(b, t, f): + """SymInt-aware utility for ternary operator (``t if b else f``.)""" + if overrides.has_torch_function((b, t, f)): + return overrides.handle_torch_function(sym_ite, (b, t, f), b, t, f) + assert isinstance(b, (SymBool, builtins.bool)) and type(t) is type(f) + if isinstance(b, SymBool): + return b.__sym_ite__(t, f) + return t if b else f + + +# Create a fresh unbacked int, from an (possibly unbacked int) expression. +def sym_fresh_size(expr): + return torch.tensor(expr).item() + + +# Check to see if we can load C extensions, and if not provide some guidance +# on what the problem might be. +try: + # _initExtension is chosen (arbitrarily) as a sentinel. + from torch._C import _initExtension +except ImportError: + import torch._C as _C_for_compiled_check + + if _C_for_compiled_check.__file__ is None: + raise ImportError( + textwrap.dedent( + """ + Failed to load PyTorch C extensions: + It appears that PyTorch has loaded the `torch/_C` folder + of the PyTorch repository rather than the C extensions which + are expected in the `torch._C` namespace. This can occur when + using the `install` workflow. e.g. + $ python -m pip install --no-build-isolation -v . && python -c "import torch" + + This error can generally be solved using the `develop` workflow + $ python -m pip install --no-build-isolation -v -e . && python -c "import torch" # This should succeed + or by running Python from a different directory. + """ + ).strip() + ) from None + raise # If __file__ is not None the cause is unknown, so just re-raise. + +# The torch._C submodule is already loaded via `from torch._C import *` above +# Make an explicit reference to the _C submodule to appease linters +from torch import _C as _C + + +__name, __obj = "", None +for __name in dir(_C): + if __name[0] != "_" and not __name.endswith("Base"): + __all__.append(__name) + __obj = getattr(_C, __name) + if callable(__obj) or inspect.isclass(__obj): + if __obj.__module__ != __name__: # "torch" + # TODO: fix their module from C++ side + if __name not in { + "DisableTorchFunctionSubclass", + "DisableTorchFunction", + "Generator", + }: + __obj.__module__ = __name__ # "torch" + elif __name == "TensorBase": + # issue 109438 / pr 109940. Prevent TensorBase from being copied into torch. + delattr(sys.modules[__name__], __name) + +del __name, __obj + +if not TYPE_CHECKING: + # issue 38137 and python issue 43367. Submodules of a C extension are + # non-standard, and attributes of those submodules cannot be pickled since + # pickle expect to be able to import them as "from _C.sub import attr" + # which fails with "_C is not a package + def _import_extension_to_sys_modules(module, memo=None): + if memo is None: + memo = set() + if module in memo: + return + memo.add(module) + module_name = module.__name__ + for name in dir(module): + member = getattr(module, name) + member_name = getattr(member, "__name__", "") + if inspect.ismodule(member) and member_name.startswith(module_name): + sys.modules.setdefault(member_name, member) + # Recurse for submodules (e.g., `_C._dynamo.eval_frame`) + _import_extension_to_sys_modules(member, memo) + + _import_extension_to_sys_modules(_C) + del _import_extension_to_sys_modules + +################################################################################ +# Define basic utilities +################################################################################ + + +def typename(obj: _Any, /) -> str: + """ + String representation of the type of an object. + + This function returns a fully qualified string representation of an object's type. + Args: + obj (object): The object whose type to represent + Returns: + str: the type of the object `o` + Example: + >>> x = torch.tensor([1, 2, 3]) + >>> torch.typename(x) + 'torch.LongTensor' + >>> torch.typename(torch.nn.Parameter) + 'torch.nn.parameter.Parameter' + """ + if isinstance(obj, torch.Tensor): + return obj.type() + + module = getattr(obj, "__module__", "") or "" + qualname = "" + + if hasattr(obj, "__qualname__"): + qualname = obj.__qualname__ + elif hasattr(obj, "__name__"): + qualname = obj.__name__ + else: + module = obj.__class__.__module__ or "" + qualname = obj.__class__.__qualname__ + + if module in {"", "builtins"}: + return qualname + return f"{module}.{qualname}" + + +def is_tensor(obj: _Any, /) -> _TypeIs["torch.Tensor"]: + r"""Returns True if `obj` is a PyTorch tensor. + + Args: + obj (object): Object to test + Example:: + + >>> x = torch.tensor([1, 2, 3]) + >>> torch.is_tensor(x) + True + + """ + return isinstance(obj, torch.Tensor) + + +def is_storage(obj: _Any, /) -> builtins.bool: + r"""Returns True if `obj` is a PyTorch storage object. + + Args: + obj (Object): Object to test + Example:: + + >>> import torch + >>> # UntypedStorage (recommended) + >>> tensor = torch.tensor([1, 2, 3]) + >>> storage = tensor.untyped_storage() + >>> torch.is_storage(storage) + True + >>> + >>> # TypedStorage (legacy) + >>> typed_storage = torch.TypedStorage(5, dtype=torch.float32) + >>> torch.is_storage(typed_storage) + True + >>> + >>> # regular tensor (should return False) + >>> torch.is_storage(tensor) + False + >>> + >>> # non-storage object + >>> torch.is_storage([1, 2, 3]) + False + """ + return type(obj) in _storage_classes + + +_GLOBAL_DEVICE_CONTEXT = threading.local() + + +def get_default_device() -> "torch.device": + r"""Gets the default ``torch.Tensor`` to be allocated on ``device``""" + global _GLOBAL_DEVICE_CONTEXT + + from torch.overrides import _get_current_function_mode_stack + from torch.utils._device import DeviceContext + + def _get_device_with_index(device): + if device.index is not None: + return device + else: + # TODO: Call like get_device_index() method corresponding to + # each device type + return torch.tensor([]).device + + # Get device from any active DeviceContext. + device_mode = next( + filter( + lambda mode: isinstance(mode, DeviceContext), + reversed(_get_current_function_mode_stack()), + ), + None, + ) + if device_mode: + device = device_mode.device + return _get_device_with_index(device) + + device_context = getattr(_GLOBAL_DEVICE_CONTEXT, "device_context", None) + if device_context is not None: + return _get_device_with_index(device_context.device) + return torch.device("cpu") + + +def set_default_device(device: "Device") -> None: + """Sets the default ``torch.Tensor`` to be allocated on ``device``. This + does not affect factory function calls which are called with an explicit + ``device`` argument. Factory calls will be performed as if they + were passed ``device`` as an argument. + + To only temporarily change the default device instead of setting it + globally, use ``with torch.device(device):`` instead. + + The default device is initially ``cpu``. If you set the default tensor + device to another device (e.g., ``cuda``) without a device index, tensors + will be allocated on whatever the current device for the device type, + even after :func:`torch.cuda.set_device` is called. + + .. warning:: + + This function imposes a slight performance cost on every Python + call to the torch API (not just factory functions). If this + is causing problems for you, please comment on + https://github.com/pytorch/pytorch/issues/92701 + + .. note:: + + This doesn't affect functions that create tensors that share the same memory as the input, like: + :func:`torch.from_numpy` and :func:`torch.frombuffer` + + Args: + device (device or string): the device to set as default + + Example:: + + >>> # xdoctest: +SKIP("requires cuda, changes global state") + >>> torch.get_default_device() + device(type='cpu') + >>> torch.set_default_device('cuda') # current device is 0 + >>> torch.get_default_device() + device(type='cuda', index=0) + >>> torch.set_default_device('cuda') + >>> torch.cuda.set_device('cuda:1') # current device is 1 + >>> torch.get_default_device() + device(type='cuda', index=1) + >>> torch.set_default_device('cuda:1') + >>> torch.get_default_device() + device(type='cuda', index=1) + + """ + global _GLOBAL_DEVICE_CONTEXT + if hasattr(_GLOBAL_DEVICE_CONTEXT, "device_context"): + device_context = _GLOBAL_DEVICE_CONTEXT.device_context + if device_context is not None: + device_context.__exit__(None, None, None) + + if device is None: + device_context = None + else: + from torch.utils._device import DeviceContext + + device_context = DeviceContext(device) + device_context.__enter__() + _GLOBAL_DEVICE_CONTEXT.device_context = device_context + + +def set_default_tensor_type(t: type["torch.Tensor"] | str, /) -> None: + r""" + .. warning:: + + This function is deprecated as of PyTorch 2.1, please use :func:`torch.set_default_dtype()` and + :func:`torch.set_default_device()` as alternatives. + + Sets the default ``torch.Tensor`` type to floating point tensor type + ``t``. This type will also be used as default floating point type for + type inference in :func:`torch.tensor`. + + The default floating point tensor type is initially ``torch.FloatTensor``. + + Args: + t (type or string): the floating point tensor type or its name + + Example:: + + >>> # xdoctest: +SKIP("Other tests may have changed the default type. Can we reset it?") + >>> torch.tensor([1.2, 3]).dtype # initial default for floating point is torch.float32 + torch.float32 + >>> torch.set_default_tensor_type(torch.DoubleTensor) + >>> torch.tensor([1.2, 3]).dtype # a new floating point tensor + torch.float64 + + """ + if isinstance(t, str): + t = _import_dotted_name(t) + _C._set_default_tensor_type(t) + + +def set_default_dtype(d: "torch.dtype", /) -> None: + r""" + + Sets the default floating point dtype to :attr:`d`. Supports floating point dtype + as inputs. Other dtypes will cause torch to raise an exception. + + When PyTorch is initialized its default floating point dtype is torch.float32, + and the intent of set_default_dtype(torch.float64) is to facilitate NumPy-like + type inference. The default floating point dtype is used to: + + 1. Implicitly determine the default complex dtype. When the default floating type is float16, + the default complex dtype is complex32. For float32, the default complex dtype is complex64. + For float64, it is complex128. For bfloat16, an exception will be raised because + there is no corresponding complex type for bfloat16. + 2. Infer the dtype for tensors constructed using Python floats or complex Python + numbers. See examples below. + 3. Determine the result of type promotion between bool and integer tensors and + Python floats and complex Python numbers. + + Args: + d (:class:`torch.dtype`): the floating point dtype to make the default. + + Example: + >>> # xdoctest: +SKIP("Other tests may have changed the default type. Can we reset it?") + >>> # initial default for floating point is torch.float32 + >>> # Python floats are interpreted as float32 + >>> torch.tensor([1.2, 3]).dtype + torch.float32 + >>> # initial default for floating point is torch.complex64 + >>> # Complex Python numbers are interpreted as complex64 + >>> torch.tensor([1.2, 3j]).dtype + torch.complex64 + + >>> torch.set_default_dtype(torch.float64) + >>> # Python floats are now interpreted as float64 + >>> torch.tensor([1.2, 3]).dtype # a new floating point tensor + torch.float64 + >>> # Complex Python numbers are now interpreted as complex128 + >>> torch.tensor([1.2, 3j]).dtype # a new complex tensor + torch.complex128 + + >>> torch.set_default_dtype(torch.float16) + >>> # Python floats are now interpreted as float16 + >>> torch.tensor([1.2, 3]).dtype # a new floating point tensor + torch.float16 + >>> # Complex Python numbers are now interpreted as complex128 + >>> torch.tensor([1.2, 3j]).dtype # a new complex tensor + torch.complex32 + + """ + _C._set_default_dtype(d) + + +def use_deterministic_algorithms( + mode: builtins.bool, + *, + warn_only: builtins.bool = False, +) -> None: + r"""Sets whether PyTorch operations must use "deterministic" + algorithms. That is, algorithms which, given the same input, and when + run on the same software and hardware, always produce the same output. + When enabled, operations will use deterministic algorithms when available, + and if only nondeterministic algorithms are available they will throw a + :class:`RuntimeError` when called. + + .. note:: This setting alone is not always enough to make an application + reproducible. Refer to :ref:`reproducibility` for more information. + + .. note:: :func:`torch.set_deterministic_debug_mode` offers an alternative + interface for this feature. + + The following normally-nondeterministic operations will act + deterministically when ``mode=True``: + + * :class:`torch.nn.Conv1d` when called on CUDA tensor + * :class:`torch.nn.Conv2d` when called on CUDA tensor + * :class:`torch.nn.Conv3d` when called on CUDA tensor + * :class:`torch.nn.ConvTranspose1d` when called on CUDA tensor + * :class:`torch.nn.ConvTranspose2d` when called on CUDA tensor + * :class:`torch.nn.ConvTranspose3d` when called on CUDA tensor + * :class:`torch.nn.ReplicationPad1d` when attempting to differentiate a CUDA tensor + * :class:`torch.nn.ReplicationPad2d` when attempting to differentiate a CUDA tensor + * :class:`torch.nn.ReplicationPad3d` when attempting to differentiate a CUDA tensor + * :func:`torch.bmm` when called on sparse-dense CUDA tensors + * :func:`torch.Tensor.__getitem__` when attempting to differentiate a CPU tensor + and the index is a list of tensors + * :func:`torch.Tensor.index_put` with ``accumulate=False`` + * :func:`torch.Tensor.index_put` with ``accumulate=True`` when called on a CPU + tensor + * :func:`torch.Tensor.put_` with ``accumulate=True`` when called on a CPU + tensor + * :func:`torch.Tensor.scatter_add_` when called on a CUDA tensor + * :func:`torch.gather` when called on a CUDA tensor that requires grad + * :func:`torch.index_add` when called on CUDA tensor + * :func:`torch.index_select` when attempting to differentiate a CUDA tensor + * :func:`torch.repeat_interleave` when attempting to differentiate a CUDA tensor + * :func:`torch.Tensor.index_copy` when called on a CPU or CUDA tensor + * :func:`torch.Tensor.scatter` when `src` type is Tensor and called on CUDA tensor + * :func:`torch.Tensor.scatter_reduce` when ``reduce='sum'`` or ``reduce='mean'`` and called on CUDA tensor + + The following normally-nondeterministic operations will throw a + :class:`RuntimeError` when ``mode=True``: + + * :class:`torch.nn.AvgPool3d` when attempting to differentiate a CUDA tensor + * :class:`torch.nn.AdaptiveAvgPool2d` when attempting to differentiate a CUDA tensor + * :class:`torch.nn.AdaptiveAvgPool3d` when attempting to differentiate a CUDA tensor + * :class:`torch.nn.MaxPool3d` when attempting to differentiate a CUDA tensor + * :class:`torch.nn.AdaptiveMaxPool2d` when attempting to differentiate a CUDA tensor + * :class:`torch.nn.FractionalMaxPool2d` when attempting to differentiate a CUDA tensor + * :class:`torch.nn.FractionalMaxPool3d` when attempting to differentiate a CUDA tensor + * :class:`torch.nn.MaxUnpool1d` + * :class:`torch.nn.MaxUnpool2d` + * :class:`torch.nn.MaxUnpool3d` + * :func:`torch.nn.functional.interpolate` when attempting to differentiate a CUDA tensor + and one of the following modes is used: + + - ``linear`` + - ``bilinear`` + - ``bicubic`` + - ``trilinear`` + + * :class:`torch.nn.ReflectionPad1d` when attempting to differentiate a CUDA tensor + * :class:`torch.nn.ReflectionPad2d` when attempting to differentiate a CUDA tensor + * :class:`torch.nn.ReflectionPad3d` when attempting to differentiate a CUDA tensor + * :class:`torch.nn.NLLLoss` when called on a CUDA tensor + * :class:`torch.nn.CTCLoss` when attempting to differentiate a CUDA tensor + * :class:`torch.nn.EmbeddingBag` when attempting to differentiate a CUDA tensor when + ``mode='max'`` + * :func:`torch.Tensor.put_` when ``accumulate=False`` + * :func:`torch.Tensor.put_` when ``accumulate=True`` and called on a CUDA tensor + * :func:`torch.histc` when called on a CUDA tensor + * :func:`torch.bincount` when called on a CUDA tensor and ``weights`` + tensor is given + * :func:`torch.median` with indices output when called on a CUDA tensor + * :func:`torch.nn.functional.grid_sample` when attempting to differentiate a CUDA tensor + * :func:`torch.cumsum` when called on a CUDA tensor when dtype is floating point or complex + * :func:`torch.Tensor.scatter_reduce` when ``reduce='prod'`` and called on CUDA tensor + * :func:`torch.Tensor.resize_` when called with a quantized tensor + + In addition, several operations fill uninitialized memory when this setting + is turned on and when + :attr:`torch.utils.deterministic.fill_uninitialized_memory` is turned on. + See the documentation for that attribute for more information. + + Note that deterministic operations tend to have worse performance than + nondeterministic operations. + + + When this setting is turned on, the Inductor deterministic mode is also tuned on + automatically. In deterministic mode, Inductor would avoid doing on device benchmarking + that affect numerics. This includes: + + - don't pad matmul input shapes. Without enabling deterministic mode, Inductor would do + benchmarking to check if padding matmul shape is beneficial. + - don't autotune templates. Inductor has templates for kernels like matmul/conv/attention. + Without enabling deterministic mode, Inductor would do autotuning to + pick the best configs for those templates and adopt it if it's faster + than the kernel in eager mode. In deterministic mode, we pick the eager kernel. + - don't autotune triton configs for reduction. Reduction numerics are + very sensitive to triton configs. In deterministic mode, Inductor + will use some heuristics to pick the most promising configs rather + than do autotuning. + - Skip autotuning for reduction in coordinate descent tuning. + - Don't benchmarking for the computation/communication reordering pass + - Disable the feature that dynamically scale down RBLOCK triton config for higher + occupancy. + + + .. note:: + + This flag does not detect or prevent nondeterministic behavior caused + by calling an inplace operation on a tensor with an internal memory + overlap or by giving such a tensor as the :attr:`out` argument for an + operation. In these cases, multiple writes of different data may target + a single memory location, and the order of writes is not guaranteed. + + Args: + mode (:class:`bool`): If True, makes potentially nondeterministic + operations switch to a deterministic algorithm or throw a runtime + error. If False, allows nondeterministic operations. + + Keyword args: + warn_only (:class:`bool`, optional): If True, operations that do not + have a deterministic implementation will throw a warning instead of + an error. Default: ``False`` + + Example:: + + >>> # xdoctest: +SKIP + >>> torch.use_deterministic_algorithms(True) + + # Backward mode nondeterministic error + >>> torch.nn.AvgPool3d(1)(torch.randn(3, 4, 5, 6, requires_grad=True).cuda()).sum().backward() + ... + RuntimeError: avg_pool3d_backward_cuda does not have a deterministic implementation... + """ + import torch._inductor.config as inductor_config + + inductor_config.deterministic = mode + _C._set_deterministic_algorithms(mode, warn_only=warn_only) + + +def are_deterministic_algorithms_enabled() -> builtins.bool: + r"""Returns True if the global deterministic flag is turned on. Refer to + :func:`torch.use_deterministic_algorithms` documentation for more details. + """ + return _C._get_deterministic_algorithms() + + +def is_deterministic_algorithms_warn_only_enabled() -> builtins.bool: + r"""Returns True if the global deterministic flag is set to warn only. + Refer to :func:`torch.use_deterministic_algorithms` documentation for more + details. + """ + return _C._get_deterministic_algorithms_warn_only() + + +def set_deterministic_debug_mode(debug_mode: builtins.int | str) -> None: + r"""Sets the debug mode for deterministic operations. + + .. note:: This is an alternative interface for + :func:`torch.use_deterministic_algorithms`. Refer to that function's + documentation for details about affected operations. + + Args: + debug_mode(str or int): If "default" or 0, don't error or warn on + nondeterministic operations. If "warn" or 1, warn on + nondeterministic operations. If "error" or 2, error on + nondeterministic operations. + """ + + # NOTE: builtins.int is used here because int in this scope resolves + # to torch.int + if not isinstance(debug_mode, (builtins.int, str)): + raise TypeError(f"debug_mode must be str or int, but got {type(debug_mode)}") + + if isinstance(debug_mode, str): + if debug_mode == "default": + debug_mode = 0 + elif debug_mode == "warn": + debug_mode = 1 + elif debug_mode == "error": + debug_mode = 2 + else: + raise RuntimeError( + "invalid value of debug_mode, expected one of `default`, " + f"`warn`, `error`, but got {debug_mode}" + ) + + if debug_mode == 0: + _C._set_deterministic_algorithms(False) + elif debug_mode == 1: + _C._set_deterministic_algorithms(True, warn_only=True) + elif debug_mode == 2: + _C._set_deterministic_algorithms(True) + else: + raise RuntimeError( + f"invalid value of debug_mode, expected 0, 1, or 2, but got {debug_mode}" + ) + + +def get_deterministic_debug_mode() -> builtins.int: + r"""Returns the current value of the debug mode for deterministic + operations. Refer to :func:`torch.set_deterministic_debug_mode` + documentation for more details. + """ + + if _C._get_deterministic_algorithms(): + if _C._get_deterministic_algorithms_warn_only(): + return 1 + else: + return 2 + else: + return 0 + + +def get_float32_matmul_precision() -> str: + r"""Returns the current value of float32 matrix multiplication precision. Refer to + :func:`torch.set_float32_matmul_precision` documentation for more details. + """ + return _C._get_float32_matmul_precision() + + +def set_float32_matmul_precision(precision: str) -> None: + r"""Sets the internal precision of float32 matrix multiplications. + + Running float32 matrix multiplications in lower precision may significantly increase + performance, and in some programs the loss of precision has a negligible impact. + + Supports three settings: + + * "highest", float32 matrix multiplications use the float32 datatype (24 mantissa + bits with 23 bits explicitly stored) for internal computations. + * "high", float32 matrix multiplications either use the TensorFloat32 datatype (10 + mantissa bits explicitly stored) or treat each float32 number as the sum of two bfloat16 numbers + (approximately 16 mantissa bits with 14 bits explicitly stored), if the appropriate fast matrix multiplication + algorithms are available. Otherwise float32 matrix multiplications are computed + as if the precision is "highest". See below for more information on the bfloat16 + approach. + * "medium", float32 matrix multiplications use the bfloat16 datatype (8 mantissa + bits with 7 bits explicitly stored) for internal computations, if a fast matrix multiplication algorithm + using that datatype internally is available. Otherwise float32 + matrix multiplications are computed as if the precision is "high". + + When using "high" precision, float32 multiplications may use a bfloat16-based algorithm + that is more complicated than simply truncating to some smaller number mantissa bits + (e.g. 10 for TensorFloat32, 7 for bfloat16 explicitly stored). Refer to [Henry2019]_ for a complete + description of this algorithm. To briefly explain here, the first step is to realize + that we can perfectly encode a single float32 number as the sum of three bfloat16 + numbers (because float32 has 23 mantissa bits while bfloat16 has 7 explicitly stored, and both have the + same number of exponent bits). This means that the product of two float32 numbers can + be exactly given by the sum of nine products of bfloat16 numbers. We can then trade + accuracy for speed by dropping some of these products. The "high" precision algorithm + specifically keeps only the three most significant products, which conveniently excludes + all of the products involving the last 8 mantissa bits of either input. This means that + we can represent our inputs as the sum of two bfloat16 numbers rather than three. + Because bfloat16 fused-multiply-add (FMA) instructions are typically >10x faster than + float32 ones, it's faster to do three multiplications and 2 additions with bfloat16 + precision than it is to do a single multiplication with float32 precision. + + .. [Henry2019] http://arxiv.org/abs/1904.06376 + + .. note:: + + This does not change the output dtype of float32 matrix multiplications, + it controls how the internal computation of the matrix multiplication is performed. + + .. note:: + + This does not change the precision of convolution operations. Other flags, + like `torch.backends.cudnn.allow_tf32`, may control the precision of convolution + operations. + + .. note:: + + This flag currently only affects one native device type: CUDA. + If "high" or "medium" are set then the TensorFloat32 datatype will be used + when computing float32 matrix multiplications, equivalent to setting + `torch.backends.cuda.matmul.allow_tf32 = True`. When "highest" (the default) + is set then the float32 datatype is used for internal computations, equivalent + to setting `torch.backends.cuda.matmul.allow_tf32 = False`. + + Args: + precision(str): can be set to "highest" (default), "high", or "medium" (see above). + + """ + _C._set_float32_matmul_precision(precision) + + +def set_warn_always(b: builtins.bool, /) -> None: + r"""When this flag is False (default) then some PyTorch warnings may only + appear once per process. This helps avoid excessive warning information. + Setting it to True causes these warnings to always appear, which may be + helpful when debugging. + + Args: + b (:class:`bool`): If True, force warnings to always be emitted + If False, set to the default behaviour + """ + _C._set_warnAlways(b) + + +def is_warn_always_enabled() -> builtins.bool: + r"""Returns True if the global warn_always flag is turned on. Refer to + :func:`torch.set_warn_always` documentation for more details. + """ + return _C._get_warnAlways() + + +################################################################################ +# Define error checking functions +################################################################################ + +# These error checking functions must be kept consistent with their C++ +# equivalents. Their C++ equivalents are mentioned where applicable. + + +def _check_with( + error_type, + cond: builtins.bool | SymBool, + message: _Callable[[], str], +): # noqa: F811 + if not isinstance(cond, (builtins.bool, SymBool)): + raise TypeError(f"cond must be a bool, but got {type(cond)}") + + from torch.fx.experimental.symbolic_shapes import expect_true + + if expect_true(cond): + return + + # error_type must be a subclass of Exception and not subclass of Warning + assert issubclass(error_type, Exception) and not issubclass(error_type, Warning) + + if message is None: + message_evaluated = ( + "Expected cond to be True, but got False. (Could this error " + "message be improved? If so, please report an enhancement request " + "to PyTorch.)" + ) + + else: + if not callable(message): + raise TypeError("message must be a callable") + + message_evaluated = str(message()) + + raise error_type(message_evaluated) + + +def _check(cond, message=None): # noqa: F811 + r"""Throws error containing an optional message if the specified condition + is False. + + Error type: ``RuntimeError`` + + C++ equivalent: ``TORCH_CHECK`` + + Args: + cond (:class:`bool`): If False, throw error + + message (Callable, optional): Callable that returns either a string or + an object that has a ``__str__()`` method to be used as the error + message. Default: ``None`` + """ + _check_with(RuntimeError, cond, message) # pyrefly: ignore [bad-argument-type] + + +# TODO add deprecation annotation +def _check_is_size(i, message=None, *, max=None): + """Checks that a given integer is a valid size (i.e., is non-negative). + You should use this over ``_check(i >= 0)`` because it can prevent + ``GuardOnDataDependentSymNode`` exceptions by opting yourself into alternate + semantics for ``guard_size_oblivious`` tests that treat values 0 and 1 + equivalently to all other values. + + When max is not None, this specifies an upper bound equivalent to + ``_check(i <= max)``. This bound is also subject to alternate semantics: + in ``guard_size_oblivious`` tests, we assume that a constant max bound is + treated equivalently to all other values. Symbolic max bounds are not yet + supported. + + NB: Do NOT use this in contexts where a -1 size would be valid (indicating + to infer the size from context, or if you should wrap-around or truncate). + Only use this if the only valid value is an honest to goodness size. + """ + # This is responsible for the expect_true + _check(i >= 0, message) + from torch.fx.experimental.symbolic_shapes import _advise_is_size + + _advise_is_size(i) + + if max is not None: + _check(i <= max, message) + + from torch.fx.experimental.symbolic_shapes import _advise_is_bounded + + _advise_is_bounded(i, max) + + +def _check_index(cond, message=None): # noqa: F811 + r"""Throws error containing an optional message if the specified condition + is False. + + Error type: ``IndexError`` + + C++ equivalent: ``TORCH_CHECK_INDEX`` + + Args: + cond (:class:`bool`): If False, throw error + + message (Callable, optional): Callable that returns either a string or + an object that has a ``__str__()`` method to be used as the error + message. Default: ``None`` + """ + _check_with(IndexError, cond, message) # pyrefly: ignore [bad-argument-type] + + +def _check_value(cond, message=None): # noqa: F811 + r"""Throws error containing an optional message if the specified condition + is False. + + Error type: ``ValueError`` + + C++ equivalent: ``TORCH_CHECK_VALUE`` + + Args: + cond (:class:`bool`): If False, throw error + + message (Callable, optional): Callable that returns either a string or + an object that has a ``__str__()`` method to be used as the error + message. Default: ``None`` + """ + _check_with(ValueError, cond, message) # pyrefly: ignore [bad-argument-type] + + +def _check_type(cond, message=None): # noqa: F811 + r"""Throws error containing an optional message if the specified condition + is False. + + Error type: ``TypeError`` + + C++ equivalent: ``TORCH_CHECK_TYPE`` + + Args: + cond (:class:`bool`): If False, throw error + + message (Callable, optional): Callable that returns either a string or + an object that has a ``__str__()`` method to be used as the error + message. Default: ``None`` + """ + _check_with(TypeError, cond, message) # pyrefly: ignore [bad-argument-type] + + +def _check_not_implemented(cond, message=None): # noqa: F811 + r"""Throws error containing an optional message if the specified condition + is False. + + Error type: ``NotImplementedError`` + + C++ equivalent: ``TORCH_CHECK_NOT_IMPLEMENTED`` + + Args: + cond (:class:`bool`): If False, throw error + + message (Callable, optional): Callable that returns either a string or + an object that has a ``__str__()`` method to be used as the error + message. Default: ``None`` + """ + _check_with( + NotImplementedError, + cond, + # pyrefly: ignore [bad-argument-type] + message, + ) + + +def _check_tensor_all_with(error_type, cond, message=None): # noqa: F811 + if not is_tensor(cond): + raise TypeError(f"cond must be a tensor, but got {type(cond)}") + + if not cond.dtype == torch.bool: + raise TypeError(f"cond tensor must have dtype torch.bool, but got {cond.dtype}") + + _check_with(error_type, cond._is_all_true().item(), message) # type: ignore[arg-type] + + +# C++ equivalent: `TORCH_CHECK_TENSOR_ALL` +def _check_tensor_all(cond, message=None): # noqa: F811 + r"""Throws error containing an optional message if the specified condition + is False. + + Error type: ``RuntimeError`` + + C++ equivalent: ``TORCH_CHECK_TENSOR_ALL`` + + Args: + cond (:class:`torch.Tensor`): Tensor of dtype ``torch.bool``. If any + element is ``False``, throw error + + message (Callable, optional): Callable that returns either a string or + an object that has a ``__str__()`` method to be used as the error + message. Default: ``None`` + """ + _check_tensor_all_with(RuntimeError, cond, message) + + +################################################################################ +# Define numeric constants +################################################################################ + +# For Python Array API (https://data-apis.org/array-api/latest/API_specification/constants.html) and +# NumPy consistency (https://numpy.org/devdocs/reference/constants.html) +from math import e, inf, nan, pi + + +newaxis: None = None + +__all__.extend(["e", "pi", "nan", "inf", "newaxis"]) + +################################################################################ +# Define Storage and Tensor classes +################################################################################ + +from torch._tensor import Tensor # usort: skip + +# needs to be after torch.Tensor is defined to avoid circular dependencies +from torch import storage as storage # usort: skip +from torch.storage import ( + _LegacyStorage, + _StorageBase, + _warn_typed_storage_removal, + TypedStorage, + UntypedStorage, +) + + +# NOTE: New Storage classes should never be added. When adding a new +# dtype, use torch.storage.TypedStorage directly. +class ByteStorage(_LegacyStorage): + @classproperty + def dtype(self): + _warn_typed_storage_removal(stacklevel=3) + return self._dtype + + @classproperty + def _dtype(self): + return torch.uint8 + + +class DoubleStorage(_LegacyStorage): + @classproperty + def dtype(self): + _warn_typed_storage_removal(stacklevel=3) + return self._dtype + + @classproperty + def _dtype(self): + return torch.double + + +class FloatStorage(_LegacyStorage): + @classproperty + def dtype(self): + _warn_typed_storage_removal(stacklevel=3) + return self._dtype + + @classproperty + def _dtype(self): + return torch.float + + +class HalfStorage(_LegacyStorage): + @classproperty + def dtype(self): + _warn_typed_storage_removal(stacklevel=3) + return self._dtype + + @classproperty + def _dtype(self): + return torch.half + + +class LongStorage(_LegacyStorage): + @classproperty + def dtype(self): + _warn_typed_storage_removal(stacklevel=3) + return self._dtype + + @classproperty + def _dtype(self): + return torch.long + + +class IntStorage(_LegacyStorage): + @classproperty + def dtype(self): + _warn_typed_storage_removal(stacklevel=3) + return self._dtype + + @classproperty + def _dtype(self): + return torch.int + + +class ShortStorage(_LegacyStorage): + @classproperty + def dtype(self): + _warn_typed_storage_removal(stacklevel=3) + return self._dtype + + @classproperty + def _dtype(self): + return torch.short + + +class CharStorage(_LegacyStorage): + @classproperty + def dtype(self): + _warn_typed_storage_removal(stacklevel=3) + return self._dtype + + @classproperty + def _dtype(self): + return torch.int8 + + +class BoolStorage(_LegacyStorage): + @classproperty + def dtype(self): + _warn_typed_storage_removal(stacklevel=3) + return self._dtype + + @classproperty + def _dtype(self): + return torch.bool + + +class BFloat16Storage(_LegacyStorage): + @classproperty + def dtype(self): + _warn_typed_storage_removal(stacklevel=3) + return self._dtype + + @classproperty + def _dtype(self): + return torch.bfloat16 + + +class ComplexDoubleStorage(_LegacyStorage): + @classproperty + def dtype(self): + _warn_typed_storage_removal(stacklevel=3) + return self._dtype + + @classproperty + def _dtype(self): + return torch.cdouble + + +class ComplexFloatStorage(_LegacyStorage): + @classproperty + def dtype(self): + _warn_typed_storage_removal(stacklevel=3) + return self._dtype + + @classproperty + def _dtype(self): + return torch.cfloat + + +class QUInt8Storage(_LegacyStorage): + @classproperty + def dtype(self): + _warn_typed_storage_removal(stacklevel=3) + return self._dtype + + @classproperty + def _dtype(self): + return torch.quint8 + + +class QInt8Storage(_LegacyStorage): + @classproperty + def dtype(self): + _warn_typed_storage_removal(stacklevel=3) + return self._dtype + + @classproperty + def _dtype(self): + return torch.qint8 + + +class QInt32Storage(_LegacyStorage): + @classproperty + def dtype(self): + _warn_typed_storage_removal(stacklevel=3) + return self._dtype + + @classproperty + def _dtype(self): + return torch.qint32 + + +class QUInt4x2Storage(_LegacyStorage): + @classproperty + def dtype(self): + _warn_typed_storage_removal(stacklevel=3) + return self._dtype + + @classproperty + def _dtype(self): + return torch.quint4x2 + + +class QUInt2x4Storage(_LegacyStorage): + @classproperty + def dtype(self): + _warn_typed_storage_removal(stacklevel=3) + return self._dtype + + @classproperty + def _dtype(self): + return torch.quint2x4 + + +_storage_classes: set[type[TypedStorage | UntypedStorage]] = { + UntypedStorage, + DoubleStorage, + FloatStorage, + LongStorage, + IntStorage, + ShortStorage, + CharStorage, + ByteStorage, + HalfStorage, + BoolStorage, + QUInt8Storage, + QInt8Storage, + QInt32Storage, + BFloat16Storage, + ComplexFloatStorage, + ComplexDoubleStorage, + QUInt4x2Storage, + QUInt2x4Storage, + TypedStorage, +} + +# The _tensor_classes set is initialized by the call to initialize_python_bindings. +_tensor_classes: set[type["torch.Tensor"]] = set() + +# If you edit these imports, please update torch/__init__.py.in as well +from torch import amp as amp, random as random, serialization as serialization +from torch._tensor_str import set_printoptions +from torch.amp import autocast, GradScaler +from torch.random import get_rng_state, initial_seed, manual_seed, seed, set_rng_state +from torch.serialization import load, save + + +################################################################################ +# Initialize extension +################################################################################ + + +# Shared memory manager needs to know the exact location of manager executable +def _manager_path(): + if platform.system() == "Windows": + return b"" + path = get_file_path("torch", "bin", "torch_shm_manager") + prepare_multiprocessing_environment(get_file_path("torch")) + if not os.path.exists(path): + raise RuntimeError("Unable to find torch_shm_manager at " + path) + return path.encode("utf-8") + + +_C._initExtension(_manager_path()) + +del _manager_path + +# Appease the type checker: it can't deal with direct setting of globals(). +# Note that we will see "too many" functions when reexporting this way; there +# is not a good way to fix this problem. Perhaps, try to redesign VariableFunctions +# so that this import is good enough +if TYPE_CHECKING: + # Some type signatures pulled in from _VariableFunctions here clash with + # signatures already imported. For now these clashes are ignored; see + # PR #43339 for details. + from torch._C._VariableFunctions import * # type: ignore[assignment, misc] # noqa: F403 + + # Fixup segment_reduce visibility + _segment_reduce = segment_reduce + del segment_reduce # noqa: F821 + +# Ops not to be exposed in `torch` namespace, +# mostly helper ops. +PRIVATE_OPS = ("unique_dim",) + +__name, __obj = "", None +for __name in dir(_C._VariableFunctions): + if __name.startswith("__") or __name in PRIVATE_OPS: + continue + __obj = getattr(_C._VariableFunctions, __name) + __obj.__module__ = __name__ # "torch" + # Hide some APIs that should not be public + if __name == "segment_reduce": + # TODO: Once the undocumented FC window is passed, remove the line below + globals()[__name] = __obj + __name = "_" + __name + globals()[__name] = __obj + if not __name.startswith("_"): + __all__.append(__name) + +del __name, __obj + +################################################################################ +# Add torch.dtype instances to the public API +################################################################################ + +import torch + + +__all__.extend( + name for name in dir(torch) if isinstance(getattr(torch, name), torch.dtype) +) + +################################################################################ +# Import TorchDynamo's lazy APIs to avoid circular dependencies +################################################################################ + +# needs to be before from torch.functional import * to avoid circular dependencies +from torch._compile import _disable_dynamo # usort: skip + +################################################################################ +# Import interface functions defined in Python +################################################################################ + +# needs to be after the above ATen bindings so we can overwrite from Python side +from torch import _VF as _VF, functional as functional # usort: skip +from torch.functional import * # usort: skip # noqa: F403 + +################################################################################ +# Remove unnecessary members +################################################################################ + +del _StorageBase +del _LegacyStorage + +################################################################################ +# Define _assert +################################################################################ + + +# needs to be before the submodule imports to avoid circular dependencies +def _assert(condition, message): + r"""A wrapper around Python's assert which is symbolically traceable.""" + if type(condition) is not torch.Tensor and overrides.has_torch_function( + (condition,) + ): + return overrides.handle_torch_function( + _assert, (condition,), condition, message + ) + assert condition, message + + +################################################################################ +# Import most common subpackages +################################################################################ + +# Use the redundant form so that type checkers know that these are a part of +# the public API. The "regular" import lines are there solely for the runtime +# side effect of adding to the imported module's members for other users. + +# needs to be before import torch.nn as nn to avoid circular dependencies +from torch.autograd import ( # usort: skip + enable_grad as enable_grad, + inference_mode as inference_mode, + no_grad as no_grad, + set_grad_enabled as set_grad_enabled, +) + +from torch import ( + __config__ as __config__, + __future__ as __future__, + _awaits as _awaits, + accelerator as accelerator, + autograd as autograd, + backends as backends, + cpu as cpu, + cuda as cuda, + distributed as distributed, + distributions as distributions, + fft as fft, + futures as futures, + hub as hub, + jit as jit, + linalg as linalg, + mps as mps, + mtia as mtia, + multiprocessing as multiprocessing, + nested as nested, + nn as nn, + optim as optim, + overrides as overrides, + profiler as profiler, + sparse as sparse, + special as special, + testing as testing, + types as types, + utils as utils, + version as version, + xpu as xpu, +) +from torch.signal import windows as windows + + +# Quantized, sparse, AO, etc. should be last to get imported, as nothing +# is expected to depend on them. +from torch import ao as ao # usort: skip + +# nn.quant* depends on ao -- so should be after those. +import torch.nn.intrinsic +import torch.nn.qat +import torch.nn.quantizable +import torch.nn.quantized + + +_C._init_names(list(_storage_classes)) + +# attach docstrings to torch and tensor functions +from torch import _size_docs, _storage_docs, _tensor_docs, _torch_docs + + +del _torch_docs, _tensor_docs, _storage_docs, _size_docs + + +def compiled_with_cxx11_abi() -> builtins.bool: + r"""Returns whether PyTorch was built with _GLIBCXX_USE_CXX11_ABI=1""" + return True + + +from torch import _library as _library, _ops as _ops + + +# Import the ops and classes "namespace" +from torch._ops import ops as ops # usort: skip +from torch._classes import classes as classes # usort: skip + +sys.modules.setdefault(f"{__name__}.ops", ops) +sys.modules.setdefault(f"{__name__}.classes", classes) + +# quantization depends on torch.fx and torch.ops +# Import quantization +from torch import quantization as quantization # usort: skip + +# Import the quasi random sampler +from torch import quasirandom as quasirandom # usort: skip + +# If you are seeing this, it means that this call site was not checked if +# the memory format could be preserved, and it was switched to old default +# behaviour of contiguous +legacy_contiguous_format = contiguous_format # defined by _C._initExtension() + +# Register fork handler to initialize OpenMP in child processes (see gh-28389) +from torch.multiprocessing._atfork import register_after_fork + + +register_after_fork(torch.get_num_threads) +del register_after_fork + +# Import tools that require fully imported torch (for applying +# torch.jit.script as a decorator, for instance): +from torch._lobpcg import lobpcg as lobpcg + + +# These were previously defined in native_functions.yaml and appeared on the +# `torch` namespace, but we moved them to c10 dispatch to facilitate custom +# class usage. We add these lines here to preserve backward compatibility. +quantized_lstm = ops.aten.quantized_lstm +quantized_gru = ops.aten.quantized_gru + +# Import experimental masked operations support. See +# [RFC-0016](https://github.com/pytorch/rfcs/pull/27) for more +# information. +from torch import masked as masked + +# Import removed ops with error message about removal +from torch._linalg_utils import ( # type: ignore[misc] + _symeig as symeig, + eig, + lstsq, + matrix_rank, + solve, +) +from torch.utils.dlpack import from_dlpack, to_dlpack + + +class _TorchCompileInductorWrapper: + compiler_name = "inductor" + + def __init__(self, mode, options, dynamic): + from torch._inductor.compiler_bisector import CompilerBisector + + self.config: dict[str, _Any] = {} + self.dynamic = dynamic + self.apply_mode(mode) + self.apply_options(options) + self.apply_options(CompilerBisector.get_config_change("inductor")) + + cuda_version = None + if hasattr(torch, "version"): + from torch.torch_version import TorchVersion + + cuda_version = TorchVersion(getattr(torch.version, "cuda", "0.0")) + + if self.config.get("triton.cudagraphs", False) and ( + (cuda_version and cuda_version < "12.6") + or not profiler_allow_cudagraph_cupti_lazy_reinit_cuda12() + ): + os.environ["DISABLE_CUPTI_LAZY_REINIT"] = "1" + # FIXME: CUDA Graph does not work well with CUPTI teardown. + # 1) crashes on 1st lazy CUPTI re-init after teardown (CUDA 11) + # 2) crashes on 2nd non-lazy CUPTI re-init after teardown (CUDA 12) + # Workaround: turn off CUPTI teardown when using CUDA Graphs. + os.environ["TEARDOWN_CUPTI"] = "0" + + def __eq__(self, other): + return ( + isinstance(other, _TorchCompileInductorWrapper) + and self.config == other.config + and self.dynamic == other.dynamic + ) + + def apply_mode(self, mode: str | None): + if mode and mode != "default": + from torch._inductor import list_mode_options + + self.apply_options(list_mode_options(mode, self.dynamic)) + + def apply_options(self, options: dict[str, _Any] | None): + if not options: + return + + from torch._inductor import config + + current_config: dict[str, _Any] = config.get_config_copy() + + for key, val in options.items(): + attr_name = key.replace("-", "_") + if attr_name not in current_config: + raise RuntimeError( + f"Unexpected optimization option {key}, known options are {list(current_config.keys())}" + ) + attr_type = config.get_type(attr_name) # type: ignore[attr-defined] + # Subscriptable generic types don't support isinstance so skip the type + # check. There doesn't seem to be a good way of checking membership without + # 3rd party libraries. + if _get_origin(attr_type) is None: + if not isinstance(val, attr_type): + val_type_str = type(val).__name__ + expected_type_str = type(current_config[attr_name]).__name__ + raise RuntimeError( + f"Unexpected type of attr {key}, got {val_type_str} should be {expected_type_str}" + ) + self.config[attr_name] = val + + def __call__(self, model_, inputs_): + from torch._inductor.compile_fx import compile_fx + + return compile_fx(model_, inputs_, config_patches=self.config) + + def get_compiler_config(self): + from torch._inductor.compile_fx import get_patched_config_dict + + return get_patched_config_dict(config_patches=self.config) + + def reset(self): + from torch._inductor import config + + if "triton.cudagraphs" in self.config or config.triton.cudagraphs: + if self.config.get("triton.cudagraphs", True): + from torch._inductor.cudagraph_trees import reset_cudagraph_trees + + reset_cudagraph_trees() + + +class _TorchCompileAOTInductorWrapper(_TorchCompileInductorWrapper): + compiler_name = "aotinductor" + + def __init__(self, mode, options, dynamic): + super().__init__(mode, options, dynamic) + self.apply_options({"cpp_wrapper": True}) + self.apply_options({"aot_inductor.package": True}) + + def __call__(self, model_, inputs_): + from contextlib import nullcontext + from unittest import mock + + from torch._guards import detect_fake_mode + from torch._inductor.virtualized import V + + fake_mode = detect_fake_mode(inputs_) + ctx = ( + mock.patch.object(fake_mode, "allow_non_fake_inputs", True) + if fake_mode + else nullcontext() + ) + with ( + V.set_aot_compilation(True), + ctx, + torch._inductor.config.patch("enable_autograd_for_aot", True), + ): + return super().__call__(model_, inputs_) + + +class _TorchCompileWrapper: + def __init__(self, backend, mode, options, dynamic): + from torch._dynamo.backends.registry import lookup_backend + + if isinstance(backend, str): + self.compiler_name = backend + elif hasattr(backend, "__name__"): + self.compiler_name = backend.__name__ + else: + self.compiler_name = str(backend) + self.dynamic = dynamic + self.compiler_fn = lookup_backend(backend) + self.kwargs = {} + # only pass the args if they non-empty + if mode and mode != "default": + self.kwargs["mode"] = mode + if options: + self.kwargs["options"] = options + + def __eq__(self, other): + return ( + isinstance(other, _TorchCompileWrapper) + and self.compiler_fn == other.compiler_fn + and self.kwargs == other.kwargs + and self.dynamic == other.dynamic + ) + + def __call__(self, model_, inputs_): + return self.compiler_fn(model_, inputs_, **self.kwargs) + + def reset(self): + if hasattr(self.compiler_fn, "reset"): + self.compiler_fn.reset() + + +_InputT = _ParamSpec("_InputT") +_RetT = _TypeVar("_RetT") + + +@_overload +def compile( + model: _Callable[_InputT, _RetT], + *, + fullgraph: builtins.bool = False, + dynamic: builtins.bool | None = None, + backend: str | _Callable = "inductor", + mode: str | None = None, + options: dict[str, str | builtins.int | builtins.bool | _Callable] | None = None, + disable: builtins.bool = False, +) -> _Callable[_InputT, _RetT]: ... + + +@_overload +def compile( + model: None = None, + *, + fullgraph: builtins.bool = False, + dynamic: builtins.bool | None = None, + backend: str | _Callable = "inductor", + mode: str | None = None, + options: dict[str, str | builtins.int | builtins.bool | _Callable] | None = None, + disable: builtins.bool = False, +) -> _Callable[[_Callable[_InputT, _RetT]], _Callable[_InputT, _RetT]]: ... + + +def compile( + model: _Callable[_InputT, _RetT] | None = None, + *, + fullgraph: builtins.bool = False, + dynamic: builtins.bool | None = None, + backend: str | _Callable = "inductor", + mode: str | None = None, + options: dict[str, str | builtins.int | builtins.bool | _Callable] | None = None, + disable: builtins.bool = False, +) -> ( + _Callable[[_Callable[_InputT, _RetT]], _Callable[_InputT, _RetT]] + | _Callable[_InputT, _RetT] +): + """ + Optimizes given model/function using TorchDynamo and specified backend. + If you are compiling an :class:`torch.nn.Module`, you can also use :meth:`torch.nn.Module.compile` + to compile the module inplace without changing its structure. + + Concretely, for every frame executed within the compiled region, we will attempt + to compile it and cache the compiled result on the code object for future + use. A single frame may be compiled multiple times if previous compiled + results are not applicable for subsequent calls (this is called a "guard + failure"), you can use TORCH_LOGS=guards to debug these situations. + Multiple compiled results can be associated with a frame up to + ``torch._dynamo.config.recompile_limit``, which defaults to 8; at which + point we will fall back to eager. Note that compile caches are per + *code object*, not frame; if you dynamically create multiple copies of a + function, they will all share the same code cache. + + Args: + model (Callable or None): Module/function to optimize + fullgraph (bool): If False (default), torch.compile attempts to discover compilable regions + in the function that it will optimize. If True, then we require that the entire function be + capturable into a single graph. If this is not possible (that is, if there are graph breaks), + then this will raise an error. This also opts into unbacked semantics, notably it will turn on + capture_scalar_outputs and capture_dynamic_output_shape_ops on by default. + dynamic (bool or None): Use dynamic shape tracing. When this is True, we will up-front attempt + to generate a kernel that is as dynamic as possible to avoid recompilations when + sizes change. This may not always work as some operations/optimizations will + force specialization; use TORCH_LOGS=dynamic to debug overspecialization. + When this is False, we will NEVER generate dynamic kernels, we will always specialize. + By default (None), we automatically detect if dynamism has occurred and compile a more + dynamic kernel upon recompile. + backend (str or Callable): backend to be used + + - "inductor" is the default backend, which is a good balance between performance and overhead + + - Non experimental in-tree backends can be seen with `torch._dynamo.list_backends()` + + - Experimental or debug in-tree backends can be seen with `torch._dynamo.list_backends(None)` + + - To register an out-of-tree custom backend: + https://pytorch.org/docs/main/torch.compiler_custom_backends.html#registering-custom-backends + mode (str): Can be either "default", "reduce-overhead", "max-autotune" or "max-autotune-no-cudagraphs" + + - "default" is the default mode, which is a good balance between performance and overhead + + - "reduce-overhead" is a mode that reduces the overhead of python with CUDA graphs, + useful for small batches. Reduction of overhead can come at the cost of more memory + usage, as we will cache the workspace memory required for the invocation so that we + do not have to reallocate it on subsequent runs. Reduction of overhead is not guaranteed + to work; today, we only reduce overhead for CUDA only graphs which do not mutate inputs. + There are other circumstances where CUDA graphs are not applicable; use TORCH_LOG=perf_hints + to debug. + + - "max-autotune" is a mode that leverages Triton or template based matrix multiplications + on supported devices and Triton based convolutions on GPU. + It enables CUDA graphs by default on GPU. + + - "max-autotune-no-cudagraphs" is a mode similar to "max-autotune" but without CUDA graphs + + - To see the exact configs that each mode sets you can call `torch._inductor.list_mode_options()` + + options (dict): A dictionary of options to pass to the backend. Some notable ones to try out are + + - `epilogue_fusion` which fuses pointwise ops into templates. Requires `max_autotune` to also be set + + - `max_autotune` which will profile to pick the best matmul configuration + + - `fallback_random` which is useful when debugging accuracy issues + + - `shape_padding` which pads matrix shapes to better align loads on GPUs especially for tensor cores + + - `triton.cudagraphs` which will reduce the overhead of python with CUDA graphs + + - `trace.enabled` which is the most useful debugging flag to turn on + + - `trace.graph_diagram` which will show you a picture of your graph after fusion + + - `guard_filter_fn` that controls which dynamo guards are saved with compilations. + This is an unsafe feature and there is no backward compatibility guarantee provided + for dynamo guards as data types. + For stable helper functions to use, see the documentations in `torch.compiler`, for example: + - `torch.compiler.skip_guard_on_inbuilt_nn_modules_unsafe` + - `torch.compiler.skip_guard_on_all_nn_modules_unsafe` + - `torch.compiler.keep_tensor_guards_unsafe` + + - For inductor you can see the full list of configs that it supports by calling `torch._inductor.list_options()` + disable (bool): Turn torch.compile() into a no-op for testing + + Example:: + + @torch.compile(options={"triton.cudagraphs": True}, fullgraph=True) + def foo(x): + return torch.sin(x) + torch.cos(x) + + """ + import sysconfig + + _C._log_api_usage_once("torch.compile") + if sys.version_info >= (3, 15): + raise RuntimeError("torch.compile is not supported on Python 3.15+") + elif sysconfig.get_config_var("Py_GIL_DISABLED") == 1 and sys.version_info < ( + 3, + 13, + 3, + ): + raise RuntimeError( + "torch.compile is not supported on Python < 3.13.3 built with GIL disabled. " + "Please use Python 3.13.3+." + ) + + # Decorator mode + if model is None: + + def fn(model: _Callable[_InputT, _RetT]) -> _Callable[_InputT, _RetT]: + if model is None: + raise RuntimeError("Model can't be None") + return compile( # pyrefly: ignore # no-matching-overload + model, + fullgraph=fullgraph, + dynamic=dynamic, + backend=backend, + mode=mode, + options=options, + disable=disable, + ) + + return fn + + if mode is not None and options is not None: + raise RuntimeError( + "Either mode or options can be specified, but both can't be specified at the same time." + ) + if mode is None and options is None: + mode = "default" + + from torch._inductor.compiler_bisector import CompilerBisector + + if bisect_backend := CompilerBisector.get_backend(): + import torch._inductor.config as inductor_config + + # don't override the backend for use cases like vllm + # which leverages their custom backend. + if not ( + inductor_config.test_configs.bisect_keep_custom_backend_for_inductor + and bisect_backend == "inductor" + and not isinstance(backend, str) + ): + backend = bisect_backend + + guard_filter_fn = None + use_aoti = False + if options and isinstance(options, dict): + guard_filter_fn = options.pop("guard_filter_fn", None) + use_aoti = options.pop("use_aoti", False) + + if torch.compiler.is_exporting(): + warnings.warn( + "You are calling torch.compile inside torch.export region. " + "To capture an useful graph, we will implicitly switch to torch.compile(backend=eager)", + stacklevel=2, + ) + from torch._higher_order_ops.utils import setup_compilation_env + + # Create wrapper that always uses eager backend during export + def export_wrapped_fn(*args, **kwargs): + with setup_compilation_env() as backend: # type: ignore[attr-defined] + # Force eager backend regardless of original backend + backend_wrapper = _TorchCompileWrapper(backend, mode, options, dynamic) + return torch._dynamo.optimize( + backend=backend_wrapper, + nopython=fullgraph, + dynamic=dynamic, + disable=disable, + guard_filter_fn=guard_filter_fn, + # pyrefly: ignore [bad-argument-type] + )(model)(*args, **kwargs) + + return export_wrapped_fn + + if backend == "inductor": + if use_aoti: + backend = _TorchCompileAOTInductorWrapper(mode, options, dynamic) + else: + backend = _TorchCompileInductorWrapper(mode, options, dynamic) + else: + backend = _TorchCompileWrapper(backend, mode, options, dynamic) + + return torch._dynamo.optimize( + backend=backend, + nopython=fullgraph, + dynamic=dynamic, + disable=disable, + guard_filter_fn=guard_filter_fn, + )(model) # type: ignore[return-value] + + +def _register_device_module(device_type, module): + r"""Register an external runtime module of the specific :attr:`device_type` + supported by torch. + + After the :attr:`module` is registered correctly, the user can refer + the external runtime module as part of torch with attribute torch.xxx. + """ + # Make sure the device_type represent a supported device type for torch. + device_type = torch.device(device_type).type + m = sys.modules[__name__] + if hasattr(m, device_type): + raise RuntimeError( + f"The runtime module of '{device_type}' has already " + f"been registered with '{getattr(m, device_type)}'" + ) + setattr(m, device_type, module) + torch_module_name = ".".join([__name__, device_type]) + sys.modules[torch_module_name] = module + + +from torch import ( + export as export, + func as func, + library as library, + return_types as return_types, +) +from torch._higher_order_ops import cond as cond, while_loop as while_loop +from torch.func import vmap as vmap + + +if not TYPE_CHECKING: + from torch import _meta_registrations + +# Enable CUDA Sanitizer +if "TORCH_CUDA_SANITIZER" in os.environ: + import torch.cuda._sanitizer as csan + + csan.enable_cuda_sanitizer() + +# Populate magic methods on SymInt and SymFloat +import torch.fx.experimental.sym_node +from torch import fx as fx + + +# Register MPS specific decomps +torch.backends.mps._init() + +from torch import compiler as compiler + + +class _TritonLibrary: + lib = torch.library.Library("triton", "DEF") + ops_table: dict[tuple[str, str], _Callable] = {} + + @classmethod + def registerOp(cls, op_key, full_schema, op_impl, dispatch_key): + if (op_key, dispatch_key) not in cls.ops_table: + cls.lib.define(full_schema) + cls.lib.impl("triton::" + op_key, op_impl, dispatch_key) + cls.ops_table[(op_key, dispatch_key)] = op_impl + + return cls.ops_table[(op_key, dispatch_key)] + + +# Deprecated attributes +_deprecated_attrs = { + "has_mps": torch.backends.mps.is_built, + "has_cuda": torch.backends.cuda.is_built, + "has_cudnn": torch.backends.cudnn.is_available, + "has_mkldnn": torch.backends.mkldnn.is_available, +} + +if TYPE_CHECKING: + # Import the following modules during type checking to enable code intelligence features, + # such as auto-completion in tools like pylance, even when these modules are not explicitly + # imported in user code. + from torch import ( + _dynamo as _dynamo, + _inductor as _inductor, + _subclasses as _subclasses, + onnx as onnx, + ) + +else: + _lazy_modules = { + "_dynamo", + "_inductor", + "_export", + # ONNX must be imported after _dynamo, _ops, _subclasses, fx, func and jit + "onnx", + } + + def __getattr__(name): + # Deprecated attrs + replacement = _deprecated_attrs.get(name) + if replacement is not None: + import warnings + + warnings.warn( + f"'{name}' is deprecated, please use '{replacement.__module__}.{replacement.__name__}()'", + stacklevel=2, + ) + return replacement() + + # Lazy modules + if name in _lazy_modules: + return importlib.import_module(f".{name}", __name__) + + raise AttributeError(f"module '{__name__}' has no attribute '{name}'") + + +@functools.cache +def get_device_module(device: torch.device | str | None = None): + """ + Returns the module associated with a given device(e.g., torch.device('cuda'), "mtia:0", "xpu", ...). + If no device is given, return the module for the current accelerator or CPU if none is present. + """ + if isinstance(device, torch.device): + device_module_name = device.type + elif isinstance(device, str): + device_module_name = torch.device(device).type + elif device is None: + # Using default accelerator type. If no accelerator is available, it automatically returns CPU device. + device_module_name = torch._C._get_accelerator().type + else: + raise RuntimeError( + f"Invalid value of device '{device}', expect torch.device, str, or None" + ) + device_module = getattr(torch, device_module_name, None) + if device_module is None: + raise RuntimeError( + f"Device '{device_module_name}' does not have a corresponding module registered as 'torch.{device_module_name}'." + ) + return device_module + + +def _constrain_as_size( + symbol, + min: builtins.int | None = None, + max: builtins.int | None = None, +): + """ + This indicates that a given int is size-like, and can be used in any context where a size is expected. + You will typically use this when reading out integers from Tensors, e.g., max.item() or lengths.tolist() + which then need to be used as tensor constructors. Providing these assertions to PyTorch can help resolve + GuardOnDataDependentSymNode errors upon export, since we cannot guard on unbacked SymInts. + + This function has unusual semantics in some circumstances in framework + code, we will treat this int as >= 2 (when we do a size-oblivious guard). + This makes it easier to use the unbacked int in size contexts, + as we will often attempt to guard on a size being zero/one + (e.g., when computing the contiguity of a tensor, or testing if + broadcasting can occur), which will not work on unbacked SymInts. + However, if we conservatively assume that the size is not zero/one, we will + end up with a graph that will still work even if the size is zero/one. + + For more details, see https://docs.google.com/document/d/1HSuTTVvYH1pTew89Rtpeu84Ht3nQEFTYhAX3Ypa_xJs/edit + ``` + """ + torch.sym_constrain_range_for_size(symbol, min=min, max=max) + + +from torch import _logging + + +_logging._init_logs() + + +def _import_device_backends(): + """ + Leverage the Python plugin mechanism to load out-of-the-tree device extensions. + See this RFC: https://github.com/pytorch/pytorch/issues/122468 + """ + from importlib.metadata import entry_points + + group_name = "torch.backends" + backend_extensions = entry_points(group=group_name) + + for backend_extension in backend_extensions: + try: + # Load the extension + entrypoint = backend_extension.load() + # Call the entrypoint + entrypoint() + except Exception as err: + raise RuntimeError( + f"Failed to load the backend extension: {backend_extension.name}. " + f"You can disable extension auto-loading with TORCH_DEVICE_BACKEND_AUTOLOAD=0." + ) from err + + +def _is_device_backend_autoload_enabled() -> builtins.bool: + """ + Whether autoloading out-of-the-tree device extensions is enabled. + The switch depends on the value of the environment variable + `TORCH_DEVICE_BACKEND_AUTOLOAD`. + + Returns: + bool: Whether to enable autoloading the extensions. Enabled by default. + + Examples: + >>> torch._is_device_backend_autoload_enabled() + True + """ + # enabled by default + return os.getenv("TORCH_DEVICE_BACKEND_AUTOLOAD", "1") == "1" + + +def _as_tensor_fullprec(t): + """ + Like torch.as_tensor, but when given Python data types it will keep + them in full precision. Used for calling convention for Dynamo. + """ + ty = type(t) + if ty is builtins.float: + return torch.as_tensor(t, dtype=torch.float64) + elif ty is builtins.int: + return torch.as_tensor(t, dtype=torch.int64) + else: + return torch.as_tensor(t) + + +# `_import_device_backends` should be kept at the end to ensure +# all the other functions in this module that may be accessed by +# an autoloaded backend are defined +if _is_device_backend_autoload_enabled(): + _import_device_backends() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_appdirs.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_appdirs.py new file mode 100644 index 0000000000000000000000000000000000000000..9d8ad9487e255ad2ebac86b2fbe9245f72657332 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_appdirs.py @@ -0,0 +1,666 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright (c) 2005-2010 ActiveState Software Inc. +# Copyright (c) 2013 Eddy Petrișor + +# flake8: noqa + +""" +This file is directly from +https://github.com/ActiveState/appdirs/blob/3fe6a83776843a46f20c2e5587afcffe05e03b39/appdirs.py + +The license of https://github.com/ActiveState/appdirs copied below: + + +# This is the MIT license + +Copyright (c) 2010 ActiveState Software Inc. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +""" + +"""Utilities for determining application-specific dirs. + +See for details and usage. +""" +# Dev Notes: +# - Windows "Known Folders": https://learn.microsoft.com/en-us/windows/win32/shell/csidl +# - macOS File System Programming Guide: https://developer.apple.com/library/archive/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/Introduction/Introduction.html +# - XDG spec for Un*x: https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html + +__version__ = "1.4.4" +__version_info__ = tuple(int(segment) for segment in __version__.split(".")) + + +import os +import sys + + +unicode = str + +if sys.platform.startswith("java"): + import platform + + os_name = platform.java_ver()[3][0] + if os_name.startswith("Windows"): # "Windows XP", "Windows 7", etc. + system = "win32" + elif os_name.startswith("Mac"): # "Mac OS X", etc. + system = "darwin" + else: # "Linux", "SunOS", "FreeBSD", etc. + # Setting this to "linux2" is not ideal, but only Windows or Mac + # are actually checked for and the rest of the module expects + # *sys.platform* style strings. + system = "linux2" +else: + system = sys.platform + + +def user_data_dir(appname=None, appauthor=None, version=None, roaming=False): + r"""Return full path to the user-specific data dir for this application. + + "appname" is the name of application. + If None, just the system directory is returned. + "appauthor" (only used on Windows) is the name of the + appauthor or distributing body for this application. Typically + it is the owning company name. This falls back to appname. You may + pass False to disable it. + "version" is an optional version path element to append to the + path. You might want to use this if you want multiple versions + of your app to be able to run independently. If used, this + would typically be ".". + Only applied when appname is present. + "roaming" (boolean, default False) can be set True to use the Windows + roaming appdata directory. That means that for users on a Windows + network setup for roaming profiles, this user data will be + sync'd on login. See + + for a discussion of issues. + + Typical user data directories are: + Mac OS X: ~/Library/Application Support/ + Unix: ~/.local/share/ # or in $XDG_DATA_HOME, if defined + Win XP (not roaming): C:\Documents and Settings\\Application Data\\ + Win XP (roaming): C:\Documents and Settings\\Local Settings\Application Data\\ + Win 7 (not roaming): C:\Users\\AppData\Local\\ + Win 7 (roaming): C:\Users\\AppData\Roaming\\ + + For Unix, we follow the XDG spec and support $XDG_DATA_HOME. + That means, by default "~/.local/share/". + """ + if system == "win32": + if appauthor is None: + appauthor = appname + const = roaming and "CSIDL_APPDATA" or "CSIDL_LOCAL_APPDATA" + path = os.path.normpath(_get_win_folder(const)) + if appname: + if appauthor is not False: + path = os.path.join(path, appauthor, appname) + else: + path = os.path.join(path, appname) + elif system == "darwin": + path = os.path.expanduser("~/Library/Application Support/") + if appname: + path = os.path.join(path, appname) + else: + path = os.getenv("XDG_DATA_HOME", os.path.expanduser("~/.local/share")) + if appname: + path = os.path.join(path, appname) + if appname and version: + path = os.path.join(path, version) + return path + + +def site_data_dir(appname=None, appauthor=None, version=None, multipath=False): + r"""Return full path to the user-shared data dir for this application. + + "appname" is the name of application. + If None, just the system directory is returned. + "appauthor" (only used on Windows) is the name of the + appauthor or distributing body for this application. Typically + it is the owning company name. This falls back to appname. You may + pass False to disable it. + "version" is an optional version path element to append to the + path. You might want to use this if you want multiple versions + of your app to be able to run independently. If used, this + would typically be ".". + Only applied when appname is present. + "multipath" is an optional parameter only applicable to *nix + which indicates that the entire list of data dirs should be + returned. By default, the first item from XDG_DATA_DIRS is + returned, or '/usr/local/share/', + if XDG_DATA_DIRS is not set + + Typical site data directories are: + Mac OS X: /Library/Application Support/ + Unix: /usr/local/share/ or /usr/share/ + Win XP: C:\Documents and Settings\All Users\Application Data\\ + Vista: (Fail! "C:\ProgramData" is a hidden *system* directory on Vista.) + Win 7: C:\ProgramData\\ # Hidden, but writeable on Win 7. + + For Unix, this is using the $XDG_DATA_DIRS[0] default. + + WARNING: Do not use this on Windows. See the Vista-Fail note above for why. + """ + if system == "win32": + if appauthor is None: + appauthor = appname + path = os.path.normpath(_get_win_folder("CSIDL_COMMON_APPDATA")) + if appname: + if appauthor is not False: + path = os.path.join(path, appauthor, appname) + else: + path = os.path.join(path, appname) + elif system == "darwin": + path = os.path.expanduser("/Library/Application Support") + if appname: + path = os.path.join(path, appname) + else: + # XDG default for $XDG_DATA_DIRS + # only first, if multipath is False + path = os.getenv( + "XDG_DATA_DIRS", os.pathsep.join(["/usr/local/share", "/usr/share"]) + ) + pathlist = [ + os.path.expanduser(x.rstrip(os.sep)) for x in path.split(os.pathsep) + ] + if appname: + if version: + appname = os.path.join(appname, version) + pathlist = [os.sep.join([x, appname]) for x in pathlist] + + if multipath: + path = os.pathsep.join(pathlist) + else: + path = pathlist[0] + return path + + if appname and version: + path = os.path.join(path, version) + return path + + +def user_config_dir(appname=None, appauthor=None, version=None, roaming=False): + r"""Return full path to the user-specific config dir for this application. + + "appname" is the name of application. + If None, just the system directory is returned. + "appauthor" (only used on Windows) is the name of the + appauthor or distributing body for this application. Typically + it is the owning company name. This falls back to appname. You may + pass False to disable it. + "version" is an optional version path element to append to the + path. You might want to use this if you want multiple versions + of your app to be able to run independently. If used, this + would typically be ".". + Only applied when appname is present. + "roaming" (boolean, default False) can be set True to use the Windows + roaming appdata directory. That means that for users on a Windows + network setup for roaming profiles, this user data will be + sync'd on login. See + + for a discussion of issues. + + Typical user config directories are: + Mac OS X: ~/Library/Preferences/ + Unix: ~/.config/ # or in $XDG_CONFIG_HOME, if defined + Win *: same as user_data_dir + + For Unix, we follow the XDG spec and support $XDG_CONFIG_HOME. + That means, by default "~/.config/". + """ + if system == "win32": + path = user_data_dir(appname, appauthor, None, roaming) + elif system == "darwin": + path = os.path.expanduser("~/Library/Preferences/") + if appname: + path = os.path.join(path, appname) + else: + path = os.getenv("XDG_CONFIG_HOME", os.path.expanduser("~/.config")) + if appname: + path = os.path.join(path, appname) + if appname and version: + path = os.path.join(path, version) + return path + + +def site_config_dir(appname=None, appauthor=None, version=None, multipath=False): + r"""Return full path to the user-shared data dir for this application. + + "appname" is the name of application. + If None, just the system directory is returned. + "appauthor" (only used on Windows) is the name of the + appauthor or distributing body for this application. Typically + it is the owning company name. This falls back to appname. You may + pass False to disable it. + "version" is an optional version path element to append to the + path. You might want to use this if you want multiple versions + of your app to be able to run independently. If used, this + would typically be ".". + Only applied when appname is present. + "multipath" is an optional parameter only applicable to *nix + which indicates that the entire list of config dirs should be + returned. By default, the first item from XDG_CONFIG_DIRS is + returned, or '/etc/xdg/', if XDG_CONFIG_DIRS is not set + + Typical site config directories are: + Mac OS X: same as site_data_dir + Unix: /etc/xdg/ or $XDG_CONFIG_DIRS[i]/ for each value in + $XDG_CONFIG_DIRS + Win *: same as site_data_dir + Vista: (Fail! "C:\ProgramData" is a hidden *system* directory on Vista.) + + For Unix, this is using the $XDG_CONFIG_DIRS[0] default, if multipath=False + + WARNING: Do not use this on Windows. See the Vista-Fail note above for why. + """ + if system == "win32": + path = site_data_dir(appname, appauthor) + if appname and version: + path = os.path.join(path, version) + elif system == "darwin": + path = os.path.expanduser("/Library/Preferences") + if appname: + path = os.path.join(path, appname) + else: + # XDG default for $XDG_CONFIG_DIRS + # only first, if multipath is False + path = os.getenv("XDG_CONFIG_DIRS", "/etc/xdg") + pathlist = [ + os.path.expanduser(x.rstrip(os.sep)) for x in path.split(os.pathsep) + ] + if appname: + if version: + appname = os.path.join(appname, version) + pathlist = [os.sep.join([x, appname]) for x in pathlist] + + if multipath: + path = os.pathsep.join(pathlist) + else: + path = pathlist[0] + return path + + +def user_cache_dir(appname=None, appauthor=None, version=None, opinion=True): + r"""Return full path to the user-specific cache dir for this application. + + "appname" is the name of application. + If None, just the system directory is returned. + "appauthor" (only used on Windows) is the name of the + appauthor or distributing body for this application. Typically + it is the owning company name. This falls back to appname. You may + pass False to disable it. + "version" is an optional version path element to append to the + path. You might want to use this if you want multiple versions + of your app to be able to run independently. If used, this + would typically be ".". + Only applied when appname is present. + "opinion" (boolean) can be False to disable the appending of + "Cache" to the base app data dir for Windows. See + discussion below. + + Typical user cache directories are: + Mac OS X: ~/Library/Caches/ + Unix: ~/.cache/ (XDG default) + Win XP: C:\Documents and Settings\\Local Settings\Application Data\\\Cache + Vista: C:\Users\\AppData\Local\\\Cache + + On Windows the only suggestion in the MSDN docs is that local settings go in + the `CSIDL_LOCAL_APPDATA` directory. This is identical to the non-roaming + app data dir (the default returned by `user_data_dir` above). Apps typically + put cache data somewhere *under* the given dir here. Some examples: + ...\Mozilla\Firefox\Profiles\\Cache + ...\Acme\SuperApp\Cache\1.0 + OPINION: This function appends "Cache" to the `CSIDL_LOCAL_APPDATA` value. + This can be disabled with the `opinion=False` option. + """ + if system == "win32": + if appauthor is None: + appauthor = appname + path = os.path.normpath(_get_win_folder("CSIDL_LOCAL_APPDATA")) + if appname: + if appauthor is not False: + path = os.path.join(path, appauthor, appname) + else: + path = os.path.join(path, appname) + if opinion: + path = os.path.join(path, "Cache") + elif system == "darwin": + path = os.path.expanduser("~/Library/Caches") + if appname: + path = os.path.join(path, appname) + else: + path = os.getenv("XDG_CACHE_HOME", os.path.expanduser("~/.cache")) + if appname: + path = os.path.join(path, appname) + if appname and version: + path = os.path.join(path, version) + return path + + +def user_state_dir(appname=None, appauthor=None, version=None, roaming=False): + r"""Return full path to the user-specific state dir for this application. + + "appname" is the name of application. + If None, just the system directory is returned. + "appauthor" (only used on Windows) is the name of the + appauthor or distributing body for this application. Typically + it is the owning company name. This falls back to appname. You may + pass False to disable it. + "version" is an optional version path element to append to the + path. You might want to use this if you want multiple versions + of your app to be able to run independently. If used, this + would typically be ".". + Only applied when appname is present. + "roaming" (boolean, default False) can be set True to use the Windows + roaming appdata directory. That means that for users on a Windows + network setup for roaming profiles, this user data will be + sync'd on login. See + + for a discussion of issues. + + Typical user state directories are: + Mac OS X: same as user_data_dir + Unix: ~/.local/state/ # or in $XDG_STATE_HOME, if defined + Win *: same as user_data_dir + + For Unix, we follow this Debian proposal + to extend the XDG spec and support $XDG_STATE_HOME. + + That means, by default "~/.local/state/". + """ + if system in ["win32", "darwin"]: + path = user_data_dir(appname, appauthor, None, roaming) + else: + path = os.getenv("XDG_STATE_HOME", os.path.expanduser("~/.local/state")) + if appname: + path = os.path.join(path, appname) + if appname and version: + path = os.path.join(path, version) + return path + + +def user_log_dir(appname=None, appauthor=None, version=None, opinion=True): + r"""Return full path to the user-specific log dir for this application. + + "appname" is the name of application. + If None, just the system directory is returned. + "appauthor" (only used on Windows) is the name of the + appauthor or distributing body for this application. Typically + it is the owning company name. This falls back to appname. You may + pass False to disable it. + "version" is an optional version path element to append to the + path. You might want to use this if you want multiple versions + of your app to be able to run independently. If used, this + would typically be ".". + Only applied when appname is present. + "opinion" (boolean) can be False to disable the appending of + "Logs" to the base app data dir for Windows, and "log" to the + base cache dir for Unix. See discussion below. + + Typical user log directories are: + Mac OS X: ~/Library/Logs/ + Unix: ~/.cache//log # or under $XDG_CACHE_HOME if defined + Win XP: C:\Documents and Settings\\Local Settings\Application Data\\\Logs + Vista: C:\Users\\AppData\Local\\\Logs + + On Windows the only suggestion in the MSDN docs is that local settings + go in the `CSIDL_LOCAL_APPDATA` directory. (Note: I'm interested in + examples of what some windows apps use for a logs dir.) + + OPINION: This function appends "Logs" to the `CSIDL_LOCAL_APPDATA` + value for Windows and appends "log" to the user cache dir for Unix. + This can be disabled with the `opinion=False` option. + """ + if system == "darwin": + path = os.path.join(os.path.expanduser("~/Library/Logs"), appname) + elif system == "win32": + path = user_data_dir(appname, appauthor, version) + version = False + if opinion: + path = os.path.join(path, "Logs") + else: + path = user_cache_dir(appname, appauthor, version) + version = False + if opinion: + path = os.path.join(path, "log") + if appname and version: + path = os.path.join(path, version) + return path + + +class AppDirs: + """Convenience wrapper for getting application dirs.""" + + def __init__( + self, appname=None, appauthor=None, version=None, roaming=False, multipath=False + ): + self.appname = appname + self.appauthor = appauthor + self.version = version + self.roaming = roaming + self.multipath = multipath + + @property + def user_data_dir(self): + return user_data_dir( + self.appname, self.appauthor, version=self.version, roaming=self.roaming + ) + + @property + def site_data_dir(self): + return site_data_dir( + self.appname, self.appauthor, version=self.version, multipath=self.multipath + ) + + @property + def user_config_dir(self): + return user_config_dir( + self.appname, self.appauthor, version=self.version, roaming=self.roaming + ) + + @property + def site_config_dir(self): + return site_config_dir( + self.appname, self.appauthor, version=self.version, multipath=self.multipath + ) + + @property + def user_cache_dir(self): + return user_cache_dir(self.appname, self.appauthor, version=self.version) + + @property + def user_state_dir(self): + return user_state_dir(self.appname, self.appauthor, version=self.version) + + @property + def user_log_dir(self): + return user_log_dir(self.appname, self.appauthor, version=self.version) + + +# ---- internal support stuff + + +def _get_win_folder_from_registry(csidl_name): + """This is a fallback technique at best. I'm not sure if using the + registry for this guarantees us the correct answer for all CSIDL_* + names. + """ + import winreg as _winreg + + shell_folder_name = { + "CSIDL_APPDATA": "AppData", + "CSIDL_COMMON_APPDATA": "Common AppData", + "CSIDL_LOCAL_APPDATA": "Local AppData", + }[csidl_name] + + key = _winreg.OpenKey( + _winreg.HKEY_CURRENT_USER, + r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders", + ) + dir, _type = _winreg.QueryValueEx(key, shell_folder_name) + return dir + + +def _get_win_folder_with_pywin32(csidl_name): + from win32com.shell import shell, shellcon + + dir = shell.SHGetFolderPath(0, getattr(shellcon, csidl_name), 0, 0) + # Try to make this a unicode path because SHGetFolderPath does + # not return unicode strings when there is unicode data in the + # path. + try: + dir = unicode(dir) + + # Downgrade to short path name if have highbit chars. See + # . + has_high_char = False + for c in dir: + if ord(c) > 255: + has_high_char = True + break + if has_high_char: + try: + import win32api + + dir = win32api.GetShortPathName(dir) + except ImportError: + pass + except UnicodeError: + pass + return dir + + +def _get_win_folder_with_ctypes(csidl_name): + import ctypes + + csidl_const = { + "CSIDL_APPDATA": 26, + "CSIDL_COMMON_APPDATA": 35, + "CSIDL_LOCAL_APPDATA": 28, + }[csidl_name] + + buf = ctypes.create_unicode_buffer(1024) + ctypes.windll.shell32.SHGetFolderPathW(None, csidl_const, None, 0, buf) + + # Downgrade to short path name if have highbit chars. See + # . + has_high_char = False + for c in buf: + if ord(c) > 255: + has_high_char = True + break + if has_high_char: + buf2 = ctypes.create_unicode_buffer(1024) + if ctypes.windll.kernel32.GetShortPathNameW(buf.value, buf2, 1024): + buf = buf2 + + return buf.value + + +def _get_win_folder_with_jna(csidl_name): + import array + + from com.sun import jna + from com.sun.jna.platform import win32 + + buf_size = win32.WinDef.MAX_PATH * 2 + buf = array.zeros("c", buf_size) + shell = win32.Shell32.INSTANCE + shell.SHGetFolderPath( + None, + getattr(win32.ShlObj, csidl_name), + None, + win32.ShlObj.SHGFP_TYPE_CURRENT, + buf, + ) + dir = jna.Native.toString(buf.tostring()).rstrip("\0") + + # Downgrade to short path name if have highbit chars. See + # . + has_high_char = False + for c in dir: + if ord(c) > 255: + has_high_char = True + break + if has_high_char: + buf = array.zeros("c", buf_size) + kernel = win32.Kernel32.INSTANCE + if kernel.GetShortPathName(dir, buf, buf_size): + dir = jna.Native.toString(buf.tostring()).rstrip("\0") + + return dir + + +if system == "win32": + try: + import win32com.shell + + _get_win_folder = _get_win_folder_with_pywin32 + except ImportError: + try: + from ctypes import windll + + _get_win_folder = _get_win_folder_with_ctypes + except ImportError: + try: + import com.sun.jna + + _get_win_folder = _get_win_folder_with_jna + except ImportError: + _get_win_folder = _get_win_folder_from_registry + + +# ---- self test code + +if __name__ == "__main__": + appname = "MyApp" + appauthor = "MyCompany" + + props = ( + "user_data_dir", + "user_config_dir", + "user_cache_dir", + "user_state_dir", + "user_log_dir", + "site_data_dir", + "site_config_dir", + ) + + print(f"-- app dirs {__version__} --") + + print("-- app dirs (with optional 'version')") + dirs = AppDirs(appname, appauthor, version="1.0") + for prop in props: + print(f"{prop}: {getattr(dirs, prop)}") + + print("\n-- app dirs (without optional 'version')") + dirs = AppDirs(appname, appauthor) + for prop in props: + print(f"{prop}: {getattr(dirs, prop)}") + + print("\n-- app dirs (without optional 'appauthor')") + dirs = AppDirs(appname) + for prop in props: + print(f"{prop}: {getattr(dirs, prop)}") + + print("\n-- app dirs (with disabled 'appauthor')") + dirs = AppDirs(appname, appauthor=False) + for prop in props: + print(f"{prop}: {getattr(dirs, prop)}") diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_awaits/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_awaits/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b08067bdcf45a17dbcf3e032b4156315d9e2981b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_awaits/__init__.py @@ -0,0 +1,53 @@ +from __future__ import annotations + +from typing import Generic, TypeVar + +import torch + +__all__ = ['Await'] + +W = TypeVar("W") + +class _PyAwaitMeta(type(torch._C._Await), type(Generic)): # type: ignore[misc, no-redef] + pass + +class _Await(torch._C._Await, Generic[W], metaclass=_PyAwaitMeta): + r""" + Wrapper around a ``torch._C.Await`` which encapsulates delayed execution + of a callable. All manipulations happen with functions ``torch.jit._awaitable``, + ``torch.jit._awaitable_wait``, ``torch.jit._awaitable_nowait``. + + Torch scriptable manipulations: + ``torch.jit._awaitable(func, *args)`` + Creates ``Await[W]`` object, where W is return type of func. + + Returns: + ``torch.jit._awaitable_wait(Await[W])`` + Returns the result of the function, specified at ``_awaitable``, with specified arguments. + + Returns: + The result of type ``W`` of the function call. The result is owned by ``Await[W]`` + and returned on all following ``_awaitable_wait`` calls. + + + ``torch.jit._awaitable_nowait(W)`` + Returns: + Trivial ``Await[W]`` with specified result. + + + Only in eager mode: + ``fn() -> Callable[Tuple[Any], W]`` + Returns: + Specified at ``_awaitable`` python function ``func``. + + ``args() -> Tuple[Any]`` + Returns: + Specified at ``_awaitable`` python args. + + ``is_nowait() -> _bool`` + Returns: + ``True`` if this object was created via ``_awaitable_nowait`` call (trivial `Await[W]`). + + In eager mode ``Await[W]`` can be used as ``W`` i.e. attributes of W can be called on ``Await[W]``, + ``_awaitable_wait()`` call will be transparently added. + """ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_classes.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_classes.py new file mode 100644 index 0000000000000000000000000000000000000000..a811c7c30be612bf0a89e5c8a5473e9d54d02ba3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_classes.py @@ -0,0 +1,56 @@ +import types +from typing import Any + +import torch._C + + +class _ClassNamespace(types.ModuleType): + def __init__(self, name: str) -> None: + super().__init__("torch.classes" + name) + self.name = name + + def __getattr__(self, attr: str) -> Any: + proxy = torch._C._get_custom_class_python_wrapper(self.name, attr) + if proxy is None: + raise RuntimeError(f"Class {self.name}.{attr} not registered!") + return proxy + + +class _Classes(types.ModuleType): + __file__ = "_classes.py" + + def __init__(self) -> None: + super().__init__("torch.classes") + + def __getattr__(self, name: str) -> _ClassNamespace: + namespace = _ClassNamespace(name) + setattr(self, name, namespace) + return namespace + + @property + def loaded_libraries(self) -> Any: + return torch.ops.loaded_libraries + + def load_library(self, path: str) -> None: + """ + Loads a shared library from the given path into the current process. + + The library being loaded may run global initialization code to register + custom classes with the PyTorch JIT runtime. This allows dynamically + loading custom classes. For this, you should compile your class + and the static registration code into a shared library object, and then + call ``torch.classes.load_library('path/to/libcustom.so')`` to load the + shared object. + + After the library is loaded, it is added to the + ``torch.classes.loaded_libraries`` attribute, a set that may be inspected + for the paths of all libraries loaded using this function. + + Args: + path (str): A path to a shared library to load. + """ + torch.ops.load_library(path) + + +# The classes "namespace" +classes = _Classes() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_compile.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_compile.py new file mode 100644 index 0000000000000000000000000000000000000000..bf7d715883d58588c7f991a7393f016d2320213c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_compile.py @@ -0,0 +1,60 @@ +""" +APIs related to torch.compile which lazily import torch._dynamo to avoid +circular dependencies. +""" + +import functools +from collections.abc import Callable +from typing import overload, TypeVar +from typing_extensions import ParamSpec + + +_T = TypeVar("_T") +_P = ParamSpec("_P") + + +@overload +def _disable_dynamo( + fn: Callable[_P, _T], recursive: bool = True +) -> Callable[_P, _T]: ... + + +@overload +def _disable_dynamo( + fn: None = None, recursive: bool = True +) -> Callable[[Callable[_P, _T]], Callable[_P, _T]]: ... + + +def _disable_dynamo( + fn: Callable[_P, _T] | None = None, recursive: bool = True +) -> Callable[_P, _T] | Callable[[Callable[_P, _T]], Callable[_P, _T]]: + """ + This API should be only used inside torch, external users should still use + torch._dynamo.disable. The main goal of this API is to avoid circular + imports issues that is common while using _dynamo.disable inside torch + itself. + + This API avoids it by lazily importing torch._dynamo from the import time to + the invocation of the decorated function. + """ + if fn is not None: + + @functools.wraps(fn) + def inner(*args: _P.args, **kwargs: _P.kwargs) -> _T: + # cache this on the first invocation to avoid adding too much overhead. + disable_fn = getattr(fn, "__dynamo_disable", None) + if disable_fn is None: + import torch._dynamo + + # We can safely turn off functools.wraps here because the inner + # already wraps fn in the outer scope. + disable_fn = torch._dynamo.disable(fn, recursive, wrapping=False) + fn.__dynamo_disable = disable_fn # type: ignore[attr-defined] + + return disable_fn(*args, **kwargs) + + return inner + else: + # decorator usage like @_disable_dynamo(recursive=False). The resulting + # object expects the original decorated function as the arg. + return functools.partial(_disable_dynamo, recursive=recursive) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_custom_op/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_custom_op/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_custom_op/autograd.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_custom_op/autograd.py new file mode 100644 index 0000000000000000000000000000000000000000..eed665a1a0d6267ad9c62dac94ef8f08b1608216 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_custom_op/autograd.py @@ -0,0 +1,307 @@ +# mypy: allow-untyped-defs +import functools +from collections import namedtuple + +import torch +import torch.utils._pytree as pytree + + +# NOTE [CustomOp autograd kernel indirection] +# We register `inner` as the autograd kernel for this custom_op. +# `inner` either calls the autograd formula registered by the user, +# or goes into an `autograd_not_implemented` kernel. +# +# The reason why this indirection exists is +# so that we can swap out the autograd kernel (the PyTorch dispatcher +# doesn't actually allow us to do this). By default, we want +# the `autograd_not_implemented` behavior, but then the user may come +# and register something that is actually a backward formula +def autograd_kernel_indirection(custom_op): + autograd_fallback = autograd_not_implemented(custom_op) + + def inner(*args, **kwargs): + if custom_op._has_impl("autograd"): + kernel = custom_op._get_impl("autograd").func + return kernel(*args, **kwargs) + # As explained in NOTE ["backward", "save_for_backward", and "autograd"], + # after the user gives us "backward" and "save_for_backward", we generate + # the "autograd" impl. If the user only provided one, then we tell + # the user they've done something wrong. + if custom_op._has_impl("save_for_backward") or custom_op._has_impl("backward"): + missing = ( + "save_for_backward" if custom_op._has_impl("backward") else "backward" + ) + found = "save_for_backward" if missing == "backward" else "backward" + loc = custom_op._get_impl(found).location + raise RuntimeError( + f"We found a '{found}' registration for {custom_op} at " + f"{loc} but were unable to find a '{missing}' registration. " + f"To use the CustomOp API to register a backward formula, " + f"please provide us both a backward function and a " + f"'save for backward' function via `impl_backward` and " + f"`impl_save_for_backward` respectively." + ) + return autograd_fallback(*args, **kwargs) + + return inner + + +# TODO(#101191): Use the actual C++ autograd not implemented fallback, +# or change the default autograd fallback to the autograd not implemented fallback. +def autograd_not_implemented(custom_op): + def kernel(*args, **kwargs): + if torch.is_grad_enabled() and pytree.tree_any( + lambda x: isinstance(x, torch.Tensor) and x.requires_grad, (args, kwargs) + ): + raise RuntimeError("Autograd has not been implemented for operator") + with torch._C._AutoDispatchBelowAutograd(): + return custom_op(*args, **kwargs) + + return kernel + + +def mark_non_differentiable(ctx, output, output_differentiability): + # Output types are restricted to be: + # - Tensor + # - Tensor[] + # - int, bool, Scalar, float + # See _check_can_register_backward + if output_differentiability is not None: + if not isinstance(output, tuple): + tuple_output = (output,) + else: + tuple_output = output # type: ignore[assignment] + assert len(output_differentiability) == len(tuple_output) + non_differentiable_tensors = [] + for idx, (differentiable, out) in enumerate( + zip(output_differentiability, tuple_output) + ): + if isinstance(out, torch.Tensor): + if not differentiable: + non_differentiable_tensors.append(out) + continue + if isinstance(out, list): + if not differentiable: + non_differentiable_tensors.extend(out) + continue + if differentiable: + raise RuntimeError( + f"With output_differentiability={output_differentiability}. " + f"At idx {idx}, we received an object of type {type(out)} that " + f"is not a Tensor, so it cannot have be marked as differentiable in " + f"output_differentiability." + ) + if non_differentiable_tensors: + ctx.mark_non_differentiable(*non_differentiable_tensors) + + +def construct_autograd_kernel( + schema, + output_differentiability, + custom_op, + op_overload, + save_for_backward_fn, + backward_fn, +): + def apply(*args): + flat_args, spec = pytree.tree_flatten(args) + out_spec = None + + def forward(ctx, *flat_args): + ctx.set_materialize_grads(True) + args = pytree.tree_unflatten(list(flat_args), spec) + with torch._C._AutoDispatchBelowAutograd(): + output = op_overload(*args) + + # We use the info about args to give better error messages in backward + args_info = namedtuple_args(schema, pytree.tree_map(type, args)) + + save_for_backward_fn_inputs = namedtuple_args(schema, args) + to_save = save_for_backward_fn(save_for_backward_fn_inputs, output) + + save_pytree_for_backward(ctx, (to_save, args_info)) + mark_non_differentiable(ctx, output, output_differentiability) + + nonlocal out_spec + flat_output, out_spec = pytree.tree_flatten(output) + return tuple(flat_output) + + def backward(ctx, *flat_grad_output): + assert out_spec is not None + grads = pytree.tree_unflatten(list(flat_grad_output), out_spec) + saved, args_info = unpack_saved(ctx) + # There is nothing on the ctx object for now, it is just there so + # that we can add additional things in the future. + inner_ctx = object() + if not isinstance(grads, tuple): + grads = (grads,) + grad_inputs_dict = backward_fn(inner_ctx, saved, *grads) + + # Massage the grad_inputs_dict to a form acceptable by + # autograd.Function. + validate_grad_inputs_dict(grad_inputs_dict, custom_op, args_info) + return grad_inputs_dict_to_flat_tuple(grad_inputs_dict, args_info) + + generated_cls = gen_autograd_function( + custom_op._opname + "_customop", forward, backward + ) + + flat_output = generated_cls.apply(*flat_args) + assert out_spec is not None + return pytree.tree_unflatten(list(flat_output), out_spec) + + return apply + + +def gen_autograd_function(name, forward, backward): + generated_cls = type( + name, + (torch.autograd.Function,), + { + "forward": staticmethod(forward), + "backward": staticmethod(backward), + }, + ) + return generated_cls + + +@functools.lru_cache +def namedtuple_args_cls(schema): + attribs = [arg.name for arg in schema.arguments.flat_all] + name = str(schema.name) + "_args" + # mypy doesn't support dynamic namedtuple name + tuple_cls = namedtuple(name, attribs) # type: ignore[misc] + return tuple_cls + + +def namedtuple_args(schema, args): + assert isinstance(args, tuple) + tuple_cls = namedtuple_args_cls(schema) + return tuple_cls(*args) + + +def validate_grad_inputs_dict(grad_inputs_dict, forward_op, args_info): + def error(what): + backward = forward_op._get_impl("backward") + raise RuntimeError( + f"In the backward function defined for {forward_op} at " + f"{backward.location} using the CustomOp API, {what}" + ) + + if not isinstance(grad_inputs_dict, dict): + error( + f"expected the output of the backward function to be a dict but " + f"got {type(grad_inputs_dict)}" + ) + + expected_keys = { + arg.name + for arg in forward_op._schema.arguments.flat_all + if arg.type.is_tensor_like() + } + actual_keys = grad_inputs_dict.keys() + if expected_keys != actual_keys: + error( + f"expected the returned grad_input dict to have keys " + f"{expected_keys} but got {actual_keys}. The backward " + f"function must return a gradient (can be None) for each arg " + f"to the CustomOp that may be a Tensor or Sequence[Tensor]. " + f"Args declared to be non-Tensor-like types should not appear " + f"in the grad_input dict" + ) + + for name, grad in grad_inputs_dict.items(): + arg_info = getattr(args_info, name) + + if isinstance(arg_info, list): + if not isinstance(grad, (tuple, list)): + error( + f"for input '{name}' expected the grad_input dict to " + f"hold a list of gradients but got object of type " + f"{type(grad)}." + ) + if len(grad) != len(arg_info): + error( + f"for input '{name}' expected the grad_input dict to " + f"hold a list of {len(arg_info)} gradients but got " + f"{len(grad)}" + ) + for idx, (g, info) in enumerate(zip(grad, arg_info)): + if g is None: + continue + if not isinstance(g, torch.Tensor): + error( + f"for input '{name}' expected the grad_input dict to " + f"hold a list of None or Tensor gradients but got " + f"object of {type(g)} at index {idx}" + ) + if not issubclass(info, torch.Tensor): + error( + f"for input '{name}', got a Tensor as the gradient " + f"for the {idx}-th value but expected None because " + f"the {idx}-th value was not a Tensor (it was " + f"type {arg_info}" + ) + continue + + if grad is None: + continue + if not isinstance(grad, torch.Tensor): + error( + f"got object of type {type(grad)} as the gradient for input " + f"'{name}', " + f"but expected the gradient to be either None or a Tensor" + ) + if not issubclass(arg_info, torch.Tensor): + error( + f"got a Tensor as the gradient for input '{name}' but " + f"expected None as the gradient because input '{name}' " + f"was not a Tensor (it was type {arg_info})." + ) + + +def grad_inputs_dict_to_flat_tuple(grad_inputs_dict, args_info): + result = [] + for name, arg_info in args_info._asdict().items(): + if name not in grad_inputs_dict: + result.append(pytree.tree_map(lambda x: None, arg_info)) + continue + result.append(grad_inputs_dict[name]) + return tuple(pytree.tree_leaves(result)) + + +# Saves "stuff" (a pytree) onto the ctx object. Use unpack_saved to unpack it. +# autograd.Function prefers that users use ctx.save_for_backward to +# save Tensors (to avoid reference cycles) and for non-Tensors to go onto the +# ctx object. +def save_pytree_for_backward(ctx, stuff): + flat_stuff, spec = pytree.tree_flatten(stuff) + num_elts = len(flat_stuff) + tensor_idxs = [ + idx for idx, thing in enumerate(flat_stuff) if isinstance(thing, torch.Tensor) + ] + non_tensor_idxs = [ + idx + for idx, thing in enumerate(flat_stuff) + if not isinstance(thing, torch.Tensor) + ] + tensors = [thing for thing in flat_stuff if isinstance(thing, torch.Tensor)] + non_tensors = [thing for thing in flat_stuff if not isinstance(thing, torch.Tensor)] + + ctx.spec = spec + ctx.num_elts = num_elts + ctx.save_for_backward(*tensors) + ctx.tensor_idxs = tensor_idxs + ctx.saved_non_tensors = non_tensors + ctx.non_tensor_idxs = non_tensor_idxs + + +# Inverse operation to save_pytree_for_backward +def unpack_saved(ctx): + flat_stuff = [None] * ctx.num_elts + for tensor, idx in zip(ctx.saved_tensors, ctx.tensor_idxs): + flat_stuff[idx] = tensor + for non_tensor, idx in zip(ctx.saved_non_tensors, ctx.non_tensor_idxs): + flat_stuff[idx] = non_tensor + stuff = pytree.tree_unflatten(flat_stuff, ctx.spec) + return stuff diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_custom_op/impl.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_custom_op/impl.py new file mode 100644 index 0000000000000000000000000000000000000000..1398f808da21f21b004fb87a8fd813ebaa8e69b7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_custom_op/impl.py @@ -0,0 +1,716 @@ +# mypy: allow-untyped-defs +import dataclasses +import functools +import inspect +import sys +import typing +import warnings +import weakref + +import torch +import torch._C as _C +import torch._library.infer_schema +import torch.library as library +from torch._library.infer_schema import infer_schema +from torch.library import get_ctx +from torchgen.model import ( + BaseTy, + BaseType, + FunctionSchema, + ListType, + OperatorName, + SchemaKind, +) + +from .autograd import autograd_kernel_indirection, construct_autograd_kernel + + +""" +torch._custom_op is deprecated. We shipped a production-ready version of it into torch.library. +Please use those APIs instead. +""" + +__all__ = ["custom_op", "CustomOp", "get_ctx"] + + +SUPPORTED_DEVICE_TYPE_TO_KEY = { + "cpu": "CPU", + "cuda": "CUDA", +} + +# We will not let users register CustomOps with anything that could look like +# PyTorch internals to avoid confusion. +RESERVED_NS = { + "prim", + "prims", + "aten", + "at", + "torch", + "pytorch", +} + + +def warn_deprecated(): + warnings.warn( + "torch._custom_op is deprecated and will be removed in PyTorch 2.6, please " + "use the equivalent torch.library API instead.", + DeprecationWarning, + stacklevel=2, + ) + + +def custom_op( + qualname: str, manual_schema: typing.Optional[str] = None +) -> typing.Callable: + r""" + This API is deprecated, please use torch.library.custom_op instead + """ + warn_deprecated() + + def inner(func): + if not inspect.isfunction(func): + raise ValueError( + f"custom_op(...)(func): Expected `func` to be a Python " + f"function, got: {type(func)}" + ) + + ns, name = parse_qualname(qualname) + validate_namespace(ns) + if func.__name__ != name: + raise ValueError( + f"custom_op(qualname='{qualname}', ...)(func): expected `func` " + f"to have name '{name}' but got '{func.__name__}'. " + f"Please either change the name of `func` or the qualname that " + f"is passed to `custom_op`" + ) + + schema = ( + infer_schema(func, mutates_args=()) + if manual_schema is None + else manual_schema + ) + schema_str = f"{name}{schema}" + function_schema = FunctionSchema.parse(schema_str) + validate_schema(function_schema) + if manual_schema is not None: + validate_function_matches_schema(function_schema, func) + + lib = library.Library(ns, "FRAGMENT") + lib.define(schema_str) + ophandle = find_ophandle_or_throw(ns, function_schema.name) + result = CustomOp( + lib, ns, function_schema, name, ophandle, _private_access=True + ) + + result.__name__ = func.__name__ # pyrefly: ignore [bad-assignment] + result.__module__ = func.__module__ + result.__doc__ = func.__doc__ + + library.impl(lib, result._opname, "Autograd")( + autograd_kernel_indirection(weakref.proxy(result)) + ) + + torch._C._dispatch_set_report_error_callback( + ophandle, functools.partial(report_error_callback, weakref.proxy(result)) + ) + + return result + + return inner + + +# Global dictionary holding references to all CustomOp objects +# Yes, it keeps all CustomOps alive (see NOTE [CustomOp lifetime]) +# Used to query the CustomOp associated with a specific C++ dispatcher operator. +# An example usage is FakeTensor: FakeTensor checks if a specific operator +# has an implementation registered via the CustomOp API. +# Indexed by qualname (e.g. aten::foo) +global_registry: dict[str, "CustomOp"] = {} + + +class CustomOp: + r""" + This API is deprecated, please use torch.library.custom_op instead + """ + + def __init__( + self, lib, cpp_ns, schema, operator_name, ophandle, *, _private_access=False + ): + super().__init__() + warn_deprecated() + if not _private_access: + raise RuntimeError( + "The CustomOp constructor is private and we do not guarantee " + "BC for it. Please use custom_op(...) to create a CustomOp object" + ) + name = f"{cpp_ns}::{operator_name}" + self._schema = schema + self._cpp_ns = cpp_ns + self._lib: library.Library = lib + self._ophandle: _C._DispatchOperatorHandle = ophandle + # Has the name of the op, e.g. "foo". We cache here for convenience. + self._opname: str = operator_name + # this is _opname but with namespace. e.g. "custom::foo" + self._qualname: str = name + self.__name__ = None # mypy requires this + # NB: Some of these impls are registered as kernels to DispatchKeys. + # Modifying the _impls dict directly won't do anything in that case. + self._impls: dict[str, typing.Optional[FuncAndLocation]] = {} + # See NOTE [CustomOp autograd kernel indirection] + self._registered_autograd_kernel_indirection = False + + global_registry[self._qualname] = self + + def _register_autograd_kernel_indirection(self): + assert not self._registered_autograd_kernel_indirection + self._lib.impl( + self._opname, autograd_kernel_indirection(weakref.proxy(self)), "Autograd" + ) + self._registered_autograd_kernel_indirection = True + + # Records the impl and the source location in self._impls + # Note that this doesn't cause torch.library to use the impl, that + # needs to be done in a separate self._lib.impl call. + def _register_impl(self, kind, func, stacklevel=2): + if self._has_impl(kind): + func_and_location = self._impls[kind] + assert func_and_location is not None # Pacify mypy + location = func_and_location.location + raise RuntimeError( + f"Attempting to register a {kind} impl for operator {self._qualname} " + f"that already has a {kind} impl registered from Python at " + f"{location}. This is not supported." + ) + frame = inspect.getframeinfo(sys._getframe(stacklevel)) + location = f"{frame.filename}:{frame.lineno}" + self._impls[kind] = FuncAndLocation(func, location) + + def _get_impl(self, kind): + return self._impls[kind] + + def _has_impl(self, kind): + return kind in self._impls + + def _destroy(self): + # NOTE: [CustomOp lifetime] + # A CustomOp, once created, lives forever. The mechanism is that the + # global registry holds a reference to it. However, to make testing + # easier, we want to be able to destroy CustomOp objects. + # CustomOp._destroy does the job, though it leaves the CustomOp + # in a garbage state. + del self._lib + + opnamespace = getattr(torch.ops, self._cpp_ns) + if hasattr(opnamespace, self._opname): + delattr(opnamespace, self._opname) + + del global_registry[self._qualname] + + def __repr__(self): + return f'' + + def __call__(self, *args, **kwargs): + # Bypass torch.ops.* and directly do OperatorHandle::callBoxed. + # Using torch.ops.* is a bit of a pain (it can be slow and it has lifetime + # issues from caching operators that make testing CustomOp difficult). + result = _C._dispatch_call_boxed(self._ophandle, *args, **kwargs) + return result + + def impl( + self, + device_types: typing.Union[str, typing.Iterable[str]], + _stacklevel=2, + ) -> typing.Callable: + r""" + This API is deprecated, please use torch.library.custom_op instead + """ + if isinstance(device_types, str): + device_types = [device_types] + for device_type in device_types: + validate_device_type(device_type) + + def inner(f): + for device_type in set(device_types): + self._check_doesnt_have_library_impl(device_type) + self._register_impl(device_type, f, stacklevel=_stacklevel) + dispatch_key = SUPPORTED_DEVICE_TYPE_TO_KEY[device_type] + library.impl(self._lib, self._opname, dispatch_key)(f) + return f + + return inner + + def _check_doesnt_have_library_impl(self, device_type): + if self._has_impl(device_type): + return + key = SUPPORTED_DEVICE_TYPE_TO_KEY[device_type] + if _C._dispatch_has_computed_kernel_for_dispatch_key(self._qualname, key): + raise RuntimeError( + f"impl(..., device_types={device_type}): the operator {self._qualname} " + f"already has an implementation for this device type via a " + f"pre-existing torch.library or TORCH_LIBRARY registration." + ) + + def impl_factory(self) -> typing.Callable: + r"""Register an implementation for a factory function.""" + + def inner(f): + self._register_impl("factory", f) + library.impl(self._lib, self._opname, "BackendSelect")(f) + return f + + return inner + + def impl_abstract(self, _stacklevel=2) -> typing.Callable: + r""" + This API is deprecated, please use torch.library.custom_op instead + """ + + def inner(f): + self._check_doesnt_have_library_meta_impl() + self._register_impl("abstract", f, stacklevel=_stacklevel) + location = self._get_impl("abstract").location + + qualname = self._qualname + + # Handle DispatchKey.Meta registration + @functools.wraps(f) + def f_with_ctx(*args, **kwargs): + def error_on_ctx(): + raise RuntimeError( + f"Attempted to call get_ctx() for the meta implementation " + f"for {qualname}." + f"You have presumably called get_ctx() because the operator " + f"has a data-dependent output shape; if so, there is no " + f"such meta implementation and this error is the correct " + f"behavior. Otherwise, please remove the call to get_ctx() " + f"in the implementation registered with impl_abstract " + f"at {location}" + ) + + with torch._library.fake_impl.set_ctx_getter(error_on_ctx): + return f(*args, **kwargs) + + self._lib.impl(self._opname, f_with_ctx, "Meta") + return f + + return inner + + def _check_can_register_backward(self): + def error(detail): + raise RuntimeError( + f"Cannot use torch._custom_ops APIs to register backward " + f"formula for {detail}. Got operator " + f"{self._qualname} with schema: {schema}" + ) + + schema = self._schema + if schema.kind() != SchemaKind.functional: + error("non-functional operator") + + rets = schema.returns + if not schema.returns: + error("operator with no returns") + + assert len(rets) > 0 + is_non_mutating_view = any( + r.annotation is not None and not r.annotation.is_write for r in rets + ) + if is_non_mutating_view: + error("operator that returns views") + + # We make assumptions about the schema's return types. + allowed_return_types = { + BaseType(BaseTy.int): "int", + BaseType(BaseTy.SymInt): "SymInt", + BaseType(BaseTy.bool): "bool", + BaseType(BaseTy.float): "float", + BaseType(BaseTy.Tensor): "Tensor", + ListType(BaseType(BaseTy.Tensor), None): "List[Tensor]", + } + for ret in schema.returns: + if ret.type in allowed_return_types: + continue + error( + f"operator with return not in {list(allowed_return_types.values())} (got {ret.type})" + ) + + def _check_doesnt_have_library_autograd_impl(self): + if self._registered_autograd_kernel_indirection: + return + + if _C._dispatch_has_kernel_for_dispatch_key( + self._qualname, "CompositeImplicitAutograd" + ): + raise RuntimeError( + f"impl_backward/impl_save_for_backward: the operator {self._qualname} " + f"already has an implementation for this device type via a " + f"pre-existing registration to DispatchKey::CompositeImplicitAutograd." + f"CompositeImplicitAutograd operators do not need an autograd formula; " + f"instead, the operator will decompose into its constituents and those " + f"can have autograd formulas defined on them." + ) + + # We can improve this by adding "all Autograd keys", but + # realistically people will just be using this API for CPU/CUDA for now. + for key in ["Autograd", "AutogradCPU", "AutogradCUDA"]: + if _C._dispatch_has_kernel_for_dispatch_key(self._qualname, key): + raise RuntimeError( + f"impl_backward/impl_save_for_backward: " + f"the operator {self._qualname} already has an Autograd kernel " + f"registered to DispatchKey::{key} vi a pre-existing " + f"torch.library or TORCH_LIBRARY registration. Please either " + f"remove those registrations or don't use the torch._custom_ops APIs" + ) + + def _check_doesnt_have_library_meta_impl(self): + if self._has_impl("abstract"): + return + + # If the user's operator is CompositeExplicitAutograd, + # allow them to impl_abstract. This is being pragmatic + # (existing custom ops may have CompositeExplicitAutograd + # registration that don't work with Meta kernels, so this + # gives them an escape hatch). + if _C._dispatch_has_kernel_for_dispatch_key( + self._qualname, "CompositeExplicitAutograd" + ) and not _C._dispatch_has_kernel_for_dispatch_key(self._qualname, "Meta"): + return + + # Otherwise, if the user's already has a Meta kernel or their + # op is CompositeImplicitAutograd or some other alias dispatch key, + # raise. + + # Special case for CompositeImplicitAutograd + if _C._dispatch_has_kernel_for_dispatch_key( + self._qualname, "CompositeImplicitAutograd" + ): + raise RuntimeError( + f"impl_abstract(...): the operator {self._qualname} " + f"already has an implementation for this device type via a " + f"pre-existing registration to DispatchKey::CompositeImplicitAutograd." + f"CompositeImplicitAutograd operators do not need an abstract impl; " + f"instead, the operator will decompose into its constituents and those " + f"can have abstract impls defined on them." + ) + + if _C._dispatch_has_kernel_for_dispatch_key(self._qualname, "Meta"): + raise RuntimeError( + f"impl_abstract(...): the operator {self._qualname} " + f"already has an DispatchKey::Meta implementation via a " + f"pre-existing torch.library or TORCH_LIBRARY registration. " + f"Please either remove that registration or don't call impl_abstract." + ) + + # NOTE ["backward", "save_for_backward", and "autograd"] + # As a part of the explicit autograd API, a user must provide us + # a "save_for_backward" function and a "backward" function. + # When both of these have been provided, then we automatically + # construct the "autograd" kernel. + def _register_autograd_kernel(self): + assert self._has_impl("backward") + assert self._has_impl("save_for_backward") + kernel = construct_autograd_kernel( + self._schema, + self._output_differentiability, + self, + get_op(self._qualname), + self._get_impl("save_for_backward").func, + self._get_impl("backward").func, + ) + self._register_impl("autograd", kernel) + + def impl_save_for_backward(self, _stacklevel=2): + r"""Register a function that tells us what to save for backward. + + Please see impl_backward for more details. + """ + + def inner(f): + self._check_can_register_backward() + self._check_doesnt_have_library_autograd_impl() + if not self._registered_autograd_kernel_indirection: + self._register_autograd_kernel_indirection() + self._register_impl("save_for_backward", f, stacklevel=_stacklevel) + if self._has_impl("backward"): + self._register_autograd_kernel() + + return inner + + def impl_backward(self, output_differentiability=None, _stacklevel=2): + r""" + This API is deprecated, please use torch.library.custom_op instead + """ + if output_differentiability is not None: + + def yell(): + raise RuntimeError( + f"impl_backward(output_differentiability): expected " + f"output_differentiability to be a list of bools with " + f"length equal to the number of outputs of this CustomOp " + f"got: {output_differentiability}" + ) + + if not isinstance(output_differentiability, list): + yell() + for diff in output_differentiability: + if not isinstance(diff, bool): + yell() + if len(self._schema.returns) != len(output_differentiability): + yell() + + def inner(f): + self._check_can_register_backward() + self._check_doesnt_have_library_autograd_impl() + if not self._registered_autograd_kernel_indirection: + self._register_autograd_kernel_indirection() + self._register_impl("backward", f, stacklevel=_stacklevel) + self._output_differentiability = output_differentiability + if self._has_impl("save_for_backward"): + self._register_autograd_kernel() + + return inner + + +@dataclasses.dataclass +class FuncAndLocation: + func: typing.Callable + location: str + + +def find_ophandle_or_throw(cpp_ns: str, operator_name: OperatorName): + overload_name = ( + "" if operator_name.overload_name is None else operator_name.overload_name + ) + return _C._dispatch_find_schema_or_throw( + f"{cpp_ns}::{str(operator_name.name)}", overload_name + ) + + +def validate_namespace(ns: str) -> None: + if "." in ns: + raise ValueError( + f'custom_op(..., ns="{ns}"): expected ns to not contain any . (and be a ' + f"valid variable name)" + ) + if ns in RESERVED_NS: + raise ValueError( + f"custom_op(..., ns='{ns}'): '{ns}' is a reserved namespace, " + f"please choose something else. " + ) + + +def validate_schema(schema: FunctionSchema) -> None: + if not torch._library.utils.is_functional_schema(schema): + raise ValueError( + f"custom_op only supports functional operators " + f"(ops that do not mutate any inputs, do not return " + f"views of the inputs, and has at least one return). " + f"Got the following non-functional schema: {schema}" + ) + + # For simplicity: don't allow self arguments + if schema.arguments.self_arg is not None: + raise ValueError( + f"custom_op does not support arguments named 'self'. Please " + f"rename your argument. Got: {schema}" + ) + + +def parse_qualname(qualname: str) -> tuple[str, str]: + names = qualname.split("::", 1) + if len(names) != 2: + raise ValueError( + f"Expected there to be a namespace in {qualname}, i.e. The " + f"operator name should look something like ns::foo" + ) + if "." in names[1]: + raise ValueError( + f"The torch.custom_ops APIs do not handle overloads, " + f"i.e. operator names with '.' in them. " + f"Please name your operator something like ns::foo. " + f"Got: {qualname}" + ) + return names[0], names[1] + + +def validate_device_type(device_type: str) -> None: + if device_type not in SUPPORTED_DEVICE_TYPE_TO_KEY: + raise ValueError( + f"CustomOp.impl(device_types=[{device_type}, ...]): we only support device_type " + f"in {SUPPORTED_DEVICE_TYPE_TO_KEY.keys()}." + ) + + +def supported_param(param: inspect.Parameter) -> bool: + return param.kind in ( + inspect.Parameter.POSITIONAL_OR_KEYWORD, + inspect.Parameter.KEYWORD_ONLY, + ) + + +def validate_function_matches_schema( + schema: FunctionSchema, func: typing.Callable +) -> None: + sig = inspect.signature(func) + + if not all(supported_param(p) for _, p in sig.parameters.items()): + raise ValueError( + f"custom_op(..., manual_schema)(func): positional-only args, " + f"varargs, and kwargs are not supported. Please rewrite `func` " + f"to not have them. Got `func` with signature: {sig}" + ) + + if ( + any( + p.annotation is not inspect.Parameter.empty + for _, p in sig.parameters.items() + ) + or sig.return_annotation is not inspect.Signature.empty + ): + raise ValueError( + f"custom_op(..., manual_schema)(func): When passing in a manual " + f"schema, we expect `func` to have no type annotations to avoid " + f"ambiguity. Got `func` with signature: {sig}" + ) + + positional = [ + (name, param) + for name, param in sig.parameters.items() + if param.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD + ] + kwargonly = [ + (name, param) + for name, param in sig.parameters.items() + if param.kind == inspect.Parameter.KEYWORD_ONLY + ] + + def error(): + raise ValueError( + f"custom_op(..., manual_schema)(func): When passing in a manual " + f"schema, we expect `func`'s signature to match `manual_schema` " + f"(aside from type annotations). " + f"func's signature: {sig}, manual_schema: {schema}" + ) + + def error_default_args(): + raise ValueError( + f"custom_op(..., manual_schema)(func): " + f"neither func nor manual_schema should have default " + f"arguments. Got " + f"func's signature: {sig}, manual_schema: {schema}" + ) + + def compare(sig_args, schema_args): + if len(sig_args) != len(schema_args): + error() + for (name, param), arg in zip(sig_args, schema_args): + if name != arg.name: + error() + if param.default is not inspect.Parameter.empty or arg.default is not None: + error_default_args() + + compare(positional, schema.arguments.flat_positional) + compare(kwargonly, schema.arguments.flat_kwarg_only) + + +def report_error_callback(custom_op: typing.Any, key: str) -> None: + if key == "Undefined": + raise NotImplementedError( + f"{custom_op}: There were no Tensor inputs to this operator " + f"(e.g. you passed an empty list of Tensors). If your operator is a " + f"factory function (that is, it takes no Tensors and constructs " + f"a new one), then please use CustomOp.impl_factory to register " + f"an implementation for it" + ) + if key == "Meta": + raise NotImplementedError( + f"{custom_op}: when running with device='Meta' tensors: there is no " + f"abstract impl registered for this CustomOp. Please register one via " + f"CustomOp.impl_abstract to get this CustomOp to work with Meta tensors" + ) + if key in ("CPU", "CUDA"): + device = key.lower() + raise NotImplementedError( + f"{custom_op}: when running with device='{device}' tensors: there is no " + f"{device} impl registered for this CustomOp. Please register one via " + f"CustomOp.impl(device_type='{device}')" + ) + raise NotImplementedError( + f"{custom_op}: No implementation for dispatch key {key}. It is likely " + f"that we have not added this functionality yet, please either open an " + f"issue or if you're feeling adventurous, use the low-level " + f"torch.library API" + ) + + +def custom_op_from_existing(op): + ns = op.namespace + lib = torch.library.Library(ns, "FRAGMENT") + name = op.name().split("::")[-1] + schema_str = str(op._schema) + # CustomOp expects the schema string without the namespace + schema_str = schema_str.rsplit("::", maxsplit=1)[-1] + schema = FunctionSchema.parse(schema_str) + return CustomOp(lib, ns, schema, name, op, _private_access=True) + + +def get_op(qualname): + def error_not_found(): + raise ValueError( + f"Could not find the operator {qualname}. Please make sure you have " + f"already registered the operator and (if registered from C++) " + f"loaded it via torch.ops.load_library." + ) + + ns, name = parse_qualname(qualname) + if not hasattr(torch.ops, ns): + error_not_found() + opnamespace = getattr(torch.ops, ns) + if not hasattr(opnamespace, name): + error_not_found() + packet = getattr(opnamespace, name) + if not hasattr(packet, "default"): + error_not_found() + return packet.default + + +def _find_custom_op(qualname, also_check_torch_library=False): + if qualname in global_registry: + return global_registry[qualname] + if not also_check_torch_library: + raise RuntimeError( + f'Could not find custom op "{qualname}". Did you register it via ' + f"the torch._custom_ops API?" + ) + overload = get_op(qualname) + result = custom_op_from_existing(overload) + return result + + +def get_abstract_impl(qualname): + if qualname not in torch._custom_op.impl.global_registry: + return None + custom_op = torch._custom_op.impl.global_registry[qualname] + if custom_op is None: + return None + if not custom_op._has_impl("abstract"): + return None + return custom_op._get_impl("abstract").func + + +def _custom_op_with_schema(qualname, schema, needs_fixed_stride_order=True): + ns, name = qualname.split("::") + schema_str = f"{name}{schema}" + function_schema = FunctionSchema.parse(schema_str) + validate_schema(function_schema) + tags = [torch._C.Tag.needs_fixed_stride_order] if needs_fixed_stride_order else [] + lib = library.Library(ns, "FRAGMENT") + lib.define(schema_str, tags=tags) + ophandle = find_ophandle_or_throw(ns, function_schema.name) + result = CustomOp(lib, ns, function_schema, name, ophandle, _private_access=True) + result._register_autograd_kernel_indirection() + + torch._C._dispatch_set_report_error_callback( + ophandle, functools.partial(report_error_callback, weakref.proxy(result)) + ) + return get_op(qualname) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_custom_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_custom_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..5203da640fa58e9ab7bf6785eb26ae1186059bee --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_custom_ops.py @@ -0,0 +1,326 @@ +# mypy: allow-untyped-defs +import inspect + +from torch._custom_op.impl import ( + _custom_op_with_schema, + _find_custom_op, + infer_schema, + parse_qualname, + validate_namespace, +) +from torch.library import get_ctx + + +__all__ = [ + "custom_op", + "impl", + "impl_abstract", + "get_ctx", + "impl_save_for_backward", + "impl_backward", +] + + +def custom_op(qualname, func_or_schema=None): + r"""Register a new custom operator + + In PyTorch, defining an op (short for "operator") is a two step-process: + - we need to define the op (by providing an operator name and schema) + - we need to implement behavior for how the operator interacts with + various PyTorch subsystems, like CPU/CUDA Tensors, Autograd, etc. + + This entrypoint defines the custom operator (the first step) + you must then perform the second step by calling various + ``impl_*`` APIs. + + This API may be used as a decorator (see examples). + + For a detailed guide on custom ops, please see + https://docs.google.com/document/d/1aGWtgxV3HppuxQAdddyPrs74_aEntpkYt9MalnCKnhk + + Arguments: + qualname (str): Should be a string that looks like + "namespace::operator_name". Operators in PyTorch need a namespace to + avoid name collisions; a given operator may only be created once. + If you are writing a Python library, we recommend the namespace to + be the name of your top-level module. + func_or_schema (Union[Callable, str]): Each PyTorch operator needs a + schema that tells PyTorch the types of the inputs/outputs. + If this is a Callable, we will automatically infer the schema from + the type annotations on the function (see examples). Otherwise, + if you don't want to use type annotations, you may provide us the + schema string. + + Example:: + + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA) + >>> import torch + >>> import numpy as np + >>> from torch import Tensor + >>> + >>> # Step 1: define the custom op. + >>> # We need to provide the API a "prototype function" + >>> # (a function that returns NotImplementedError), from which + >>> # we will infer the types of the inputs and outputs. + >>> @torch._custom_ops.custom_op("mylibrary::numpy_sin") + >>> def numpy_sin(x: Tensor) -> Tensor: + >>> raise NotImplementedError + >>> + >>> # The custom op is now accessible via the torch.ops module: + >>> torch.ops.mylibrary.numpy_sin + >>> + >>> # Step 2: Register an implementation for various PyTorch subsystems + >>> + >>> # Register an implementation for CPU tensors + >>> @torch._custom_ops.impl("mylibrary::numpy_sin", device_types="cpu") + >>> def numpy_sin_impl_cpu(x): + >>> return torch.from_numpy(np.sin(x.numpy())) + >>> + >>> # Register an implementation for CUDA tensors + >>> @torch._custom_ops.impl("mylibrary::numpy_sin", device_types="cuda") + >>> def numpy_sin_impl_cuda(x): + >>> return torch.from_numpy(np.sin(x.cpu().numpy())).to(x.device) + >>> + >>> x = torch.randn(3) + >>> torch.ops.mylibrary.numpy_sin(x) # calls numpy_sin_impl_cpu + >>> + >>> x_cuda = x.cuda() + >>> torch.ops.mylibrary.numpy_sin(x) # calls numpy_sin_impl_cuda + + """ + ns, name = parse_qualname(qualname) + validate_namespace(ns) + + def inner(func): + if not inspect.isfunction(func): + raise ValueError( + f"custom_op(...)(func): Expected `func` to be a Python " + f"function, got: {type(func)}" + ) + + if func.__name__ != name: + raise ValueError( + f"custom_op(qualname='{qualname}', ...)(func): expected `func` " + f"to have name '{name}' but got '{func.__name__}'. " + f"Please either change the name of `func` or the qualname that " + f"is passed to `custom_op`" + ) + + schema = infer_schema(func, mutates_args=()) + _custom_op_with_schema(qualname, schema) + return func + + if func_or_schema is None: + return inner + if isinstance(func_or_schema, str): + _custom_op_with_schema(qualname, func_or_schema) + else: + return inner(func_or_schema) + + +def impl(qualname, *, device_types=("cpu", "cuda"), func=None): + r"""Register an implementation for a device type for this custom op. + + If the op is passed multiple Tensor inputs with different device + types, it will dispatch to the registered implementation for the highest + priority device type among those present. + The supported device types, in order of priority, are {'cuda', 'cpu'}. + + This API may be used as a decorator (see examples). + + For a detailed guide on custom ops, please see + https://docs.google.com/document/d/1aGWtgxV3HppuxQAdddyPrs74_aEntpkYt9MalnCKnhk + + Arguments: + device_types (str or Iterable[str]): the device type(s) to register the function for. + + Example:: + + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA) + >>> import torch + >>> import numpy as np + >>> from torch import Tensor + >>> + >>> # Step 1: define the custom op. + >>> # We need to provide the API a "prototype function" + >>> # (a function that returns NotImplementedError), from which + >>> # we will infer the types of the inputs and outputs. + >>> @torch._custom_ops.custom_op("mylibrary::numpy_cos") + >>> def numpy_cos(x: Tensor) -> Tensor: + >>> raise NotImplementedError + >>> + >>> # The custom op is now accessible via the torch.ops module: + >>> torch.ops.mylibrary.numpy_cos + >>> + >>> # Step 2: Register an implementation for various PyTorch subsystems + >>> + >>> # Register an implementation for CPU tensors + >>> @torch._custom_ops.impl("mylibrary::numpy_cos", device_types="cpu") + >>> def numpy_cos_impl_cpu(x): + >>> return torch.from_numpy(np.cos(x.numpy())) + >>> + >>> # Register an implementation for CUDA tensors + >>> @torch._custom_ops.impl("mylibrary::numpy_cos", device_types="cuda") + >>> def numpy_cos_impl_cuda(x): + >>> return torch.from_numpy(np.cos(x.cpu().numpy())).to(x.device) + >>> + >>> x = torch.randn(3) + >>> torch.ops.mylibrary.numpy_cos(x) # calls numpy_cos_impl_cpu + >>> + >>> x_cuda = x.cuda() + >>> torch.ops.mylibrary.numpy_cos(x) # calls numpy_cos_impl_cuda + + """ + + def inner(func): + custom_op = _find_custom_op(qualname, also_check_torch_library=True) + custom_op.impl(device_types, _stacklevel=3)(func) + return func + + if func is None: + return inner + return inner(func) + + +def impl_abstract(qualname, *, func=None): + r"""Register an abstract implementation for this operator. + + An "abstract implementation" specifies the behavior of this operator on + Tensors that carry no data. Given some input Tensors with certain properties + (sizes/strides/storage_offset/device), it specifies what the properties of + the output Tensors are. + + The abstract implementation has the same signature as the operator. + It is run for both FakeTensors and meta tensors. To write an abstract + implementation, assume that all Tensor inputs to the operator are + regular CPU/CUDA/Meta tensors, but they do not have storage, and + you are trying to return regular CPU/CUDA/Meta tensor(s) as output. + The abstract implementation must consist of only PyTorch operations + (and may not directly access the storage or data of any input or + intermediate Tensors). + + This API may be used as a decorator (see examples). + + For a detailed guide on custom ops, please see + https://docs.google.com/document/d/1aGWtgxV3HppuxQAdddyPrs74_aEntpkYt9MalnCKnhk + + Examples:: + >>> import numpy as np + >>> from torch import Tensor + >>> + >>> # Example 1: an operator without data-dependent output shape + >>> @torch._custom_ops.custom_op("mylibrary::custom_linear") + >>> def custom_linear(x: Tensor, weight: Tensor, bias: Tensor) -> Tensor: + >>> raise NotImplementedError + >>> + >>> @torch._custom_ops.impl_abstract("mylibrary::custom_linear") + >>> def custom_linear_abstract(x, weight): + >>> assert x.dim() == 2 + >>> assert weight.dim() == 2 + >>> assert bias.dim() == 1 + >>> assert x.shape[1] == weight.shape[1] + >>> assert weight.shape[0] == bias.shape[0] + >>> assert x.device == weight.device + >>> + >>> return (x @ weight.t()) + bias + >>> + >>> # Example 2: an operator with data-dependent output shape + >>> @torch._custom_ops.custom_op('mylibrary::custom_nonzero') + >>> def custom_nonzero(x: Tensor) -> Tensor: + >>> ... + >>> + >>> @torch._custom_ops.impl_abstract("mylibrary::custom_nonzero") + >>> def custom_nonzero_abstract(x): + >>> # Number of nonzero-elements is data-dependent. + >>> # Since we cannot peek at the data in an abstract impl, + >>> # we use the ctx object to construct a new symint that + >>> # represents the data-dependent size. + >>> ctx = torch._custom_ops.get_ctx() + >>> nnz = ctx.create_unbacked_symint() + >>> shape = [x.dim(), nnz] + >>> result = x.new_empty(shape, dtype=torch.long) + >>> return result + >>> + >>> @torch._custom_ops.impl("mylibrary::custom_nonzero") + >>> def custom_nonzero_impl(x): + >>> x_np = to_numpy(x) + >>> res = np.stack(np.nonzero(x_np), axis=1) + >>> # unbacked symbolic ints in PyTorch must be >= 2, so we + >>> # constrain the range to at least 2 + >>> if res.shape[0] <= 1: + >>> raise RuntimeError("not supported") + >>> return torch.tensor(res, device=x.device) + + """ + import torch.library + + return torch.library.register_fake(qualname, func, _stacklevel=2) + + +def impl_save_for_backward(qualname, *, func=None): + r"""Register a function that tells us what to save for backward. + + Please see :func:`impl_backward` for more details. + """ + + def inner(func): + custom_op = _find_custom_op(qualname, also_check_torch_library=True) + custom_op.impl_save_for_backward(_stacklevel=3)(func) + return func + + if func is None: + return inner + return inner(func) + + +def impl_backward(qualname, output_differentiability=None, *, func=None): + r"""Registers a backward formula for an operator. + + In order for an operator to work with autograd, you need to register + a backward formula. There are two pieces to this: + 1. You must give us a function to specify what to save for backward. + Call this the "save for backward" function. + 2. You must give us a function that computes gradients. Call this the + "backward" function. + + Use `impl_save_for_backward` to define a "save for backward" function + that specifies what gets saved for backward. The function should accept + two arguments ``(inputs, output)`` and return the quantities to be saved + for backward. + + During runtime, when you call the operator in a forwards pass, PyTorch + will invoke the "save for backward" function with the inputs and output + of the operator. + + Use `impl_backward` to define the "backward" function. The backward + function must accept ``(ctx, saved, *grads)``: + - ``ctx`` is a context object where we may provide information + - ``saved`` is exactly what gets returned from the "save for backward" + function + - ``grads`` is one or more gradients. The number of gradients matches + the number of outputs of the operator. + + The backward function must return a dict that maps the name of + an input to the operator to its corresponding gradient. All inputs that + were declared to be Tensors in the operator definition must be accounted + for in the dict. The gradient may be a Tensor or None. + + For a detailed guide on custom ops, please see + https://docs.google.com/document/d/1aGWtgxV3HppuxQAdddyPrs74_aEntpkYt9MalnCKnhk + + """ + + def inner(func): + custom_op = _find_custom_op(qualname, also_check_torch_library=True) + custom_op.impl_backward(output_differentiability, _stacklevel=3)(func) + return func + + if func is None: + return inner + return inner(func) + + +def _destroy(qualname): + """De-registers a custom op. For testing purposes only""" + custom_op = _find_custom_op(qualname) + custom_op._destroy() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_decomp/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_decomp/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a321a49ac142e637d87eb09433659442e3b47004 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_decomp/__init__.py @@ -0,0 +1,549 @@ +# mypy: allow-untyped-defs +import inspect +from collections import defaultdict +from collections.abc import Callable, Sequence +from functools import lru_cache, partial, wraps +from itertools import chain +from typing import Optional, TYPE_CHECKING, TypeVar, Union +from typing_extensions import ParamSpec + + +if TYPE_CHECKING: + from torch.export.decomp_utils import CustomDecompTable + +import torch +import torch.library +from torch._ops import HigherOrderOperator, OperatorBase, OpOverload, OpOverloadPacket +from torch._prims_common import CustomOutParamAnnotation +from torch._subclasses.functional_tensor import FunctionalTensor +from torch.utils import _pytree as pytree + + +__all__ = [ + "decomposition_table", + "pre_autograd_decomposition_table", + "meta_table", + "register_decomposition", + "get_decompositions", + "core_aten_decompositions", + "_should_decompose_because_unsafe_op", +] + +_T = TypeVar("_T") +_P = ParamSpec("_P") + +# TODO: relax key type here; torch registrations should be possible to; but +# right now this type is accurate +global_decomposition_table: dict[str, dict[torch._ops.OperatorBase, Callable]] = ( + defaultdict(dict) +) + +decomposition_table = global_decomposition_table["post_autograd"] +pre_autograd_decomposition_table = global_decomposition_table["pre_autograd"] +meta_table = global_decomposition_table["meta"] + + +def _should_decompose_because_unsafe_op(op: torch._ops.OperatorBase) -> bool: + """ + Returns True if the op must always decompose in export/compile tracing system + + In export, we always decompose certain CIA ops that are tagged with + maybe_aliasing_or_mutating because we statically need to know if the op is + mutating or not. But these CIA ops could have different behaviour in runtime. + + native_batch_norm is a prim op which has a wrong schema and it needs to be replaced + with correct schema. But until then, we will force decompose it via this tag. + """ + if not isinstance(op, torch._ops.OpOverload): + return False + if torch.Tag.maybe_aliasing_or_mutating in op.tags: + return True + return op is torch.ops.aten.native_batch_norm.default + + +def _add_op_to_registry(registry, op, fn): + """ + This is an internal API for adding an op to the decomposition table. + + If op is OpOverload, it will be added to the registry directly. + If op is OpOverloadPacket, all the valid op_overloads in the packet will be added to the registry. + """ + overloads: list[Union[torch._ops.OperatorBase]] = [] + if isinstance(op, HigherOrderOperator): + # There's no concept of overloads for HigherOrderOperator + registry[op] = fn + return + elif isinstance(op, OpOverload): + overloads.append(op) + else: + assert isinstance(op, OpOverloadPacket) + for ol in op.overloads(): + overloads.append(getattr(op, ol)) + + for op_overload in overloads: + if op_overload in registry: + raise RuntimeError(f"duplicate registrations for {op_overload}") + # TorchScript dumps a bunch of extra nonsense overloads + # which don't have corresponding dispatcher entries, we need + # to filter those out, e.g aten.add.float_int + if torch._C._dispatch_has_kernel(op_overload.name()): + registry[op_overload] = fn + + +def _convert_out_params(f): + out_annotation = f.__annotations__.get("out") + + # If there are no out params, do not wrap the function. + if not out_annotation: + return f + + # Hack to detect when out is a Tuple. There seems to be no pretty way of doing this + if getattr(out_annotation, "__origin__", None) is tuple: + sig = inspect.signature(f) + out_names = sig.return_annotation._fields + # If out is a tuple, we need to register a function that unpacks all the out + # elements as this is what native_functions.yaml expects + + @wraps(f) + def _fn(*args, **kwargs): + out_kwargs = tuple(kwargs.pop(o, None) for o in out_names) + # Either all of the out kwargs are set or none of them + is_none = out_kwargs[0] is None + assert all((o is None) == is_none for o in out_kwargs) + return f(*args, **kwargs, out=None if is_none else out_kwargs) + + out_params = [ + inspect.Parameter( + o, + kind=inspect.Parameter.KEYWORD_ONLY, + default=None, + annotation=t, + ) + for o, t in zip(out_names, out_annotation.__args__) + ] + # Drop the out parameter and concatenate the new kwargs in the signature + params = chain((v for k, v in sig.parameters.items() if k != "out"), out_params) + _fn.__signature__ = inspect.Signature( # type: ignore[attr-defined] + parameters=params, # type: ignore[arg-type] + return_annotation=sig.return_annotation, + ) + # Drop the out parameter and concatenate the new kwargs in the annotations + _fn.__annotations__ = {k: v for k, v in f.__annotations__.items() if k != "out"} + for o in out_params: + _fn.__annotations__[o.name] = o.annotation + + # Propagate that this function is wrapped by `out_wrapper` + _fn._torch_decompositions_out_wrapper = f._torch_decompositions_out_wrapper # type: ignore[attr-defined] + + return _fn + + # Alternatively, there may be a single tensor out parameter with a name + # other than "out". This will need special treatment and is indicated by an + # annotation, which we will remove here so it is not exposed after wrapping. + custom_out_param_name = f.__annotations__.pop(CustomOutParamAnnotation, None) + if custom_out_param_name: + + @wraps(f) + def _fn(*args, **kwargs): + out_kwarg = kwargs.pop(custom_out_param_name, None) + return f(*args, **kwargs, out=out_kwarg) + + out_param = inspect.Parameter( + custom_out_param_name, + kind=inspect.Parameter.KEYWORD_ONLY, + default=None, + annotation=out_annotation, + ) + + # Drop the out parameter and concatenate the new kwarg in the signature + sig = inspect.signature(f) + params = chain( + (v for k, v in sig.parameters.items() if k != "out"), (out_param,) + ) + _fn.__signature__ = inspect.Signature( # type: ignore[attr-defined] + parameters=params, # type: ignore[arg-type] + return_annotation=sig.return_annotation, + ) + + # Drop the out parameter and concatenate the new kwargs in the annotations + _fn.__annotations__ = {k: v for k, v in f.__annotations__.items() if k != "out"} + _fn.__annotations__[out_param.name] = out_param.annotation + + return _fn + + return f + + +def register_decomposition( + aten_op, registry=None, *, type="post_autograd", unsafe=False +) -> Callable[[Callable[_P, _T]], Callable[_P, _T]]: + """ + A decorator to register a function as a decomposition to the Python + decomposition table. Use it like this:: + + @register_decomposition(torch.ops.aten.clamp_min) + def clamp_min(x): + return torch.clamp(self, min=min) + + If you are writing a new decomposition, consider contributing it + directly to PyTorch in torch._decomp.decompositions. + + This API is experimental; we are almost certainly going to extend + the API when we make decompositions eligible for use in transforms (e.g., + autograd) and not just backend tracing, where we then need to know if a + decomposition can be used to simulate a transform. + + By default, we also will register it to the Meta key of dispatcher, + and replace the c++ Meta implementation if there is already one. + + unsafe kwarg is for reuse of this function for registering non-function + things + """ + + assert type in {"post_autograd", "pre_autograd", "meta"} + + def decomposition_decorator(fn: Callable[_P, _T]) -> Callable[_P, _T]: + orig_fn = fn + if not unsafe: + fn = _convert_out_params(fn) + + nonlocal registry + if registry is None: + registry = global_decomposition_table[type] + + def register(op): + _add_op_to_registry(registry, op, fn) + + # To handle allowing multiple aten_ops at once + pytree.tree_map_(register, aten_op) + return orig_fn + + return decomposition_decorator + + +def get_decompositions( + aten_ops: Sequence[Union[torch._ops.OperatorBase, OpOverloadPacket]], + type: str = "post_autograd", +) -> dict[torch._ops.OperatorBase, Callable]: + """ + Retrieve a dictionary of decompositions corresponding to the list of + operator overloads and overload packets passed as input. Overload + packets will include all decomposed overloads in the packet. If there is + no decomposition for a requested operator, it is silently ignored. + + This API is experimental; we are almost certainly going to give an alternate, + more recommended formulation, where a user provides the set of operators + they know how to implement, and we provide decompositions for everything + not in this set. + """ + assert type in {"post_autograd", "pre_autograd", "meta"} + + registry = global_decomposition_table[type] + packets_to_overloads = defaultdict(list) + + for opo in registry: + if isinstance(opo, (OpOverload, OpOverloadPacket)): + packets_to_overloads[opo.overloadpacket].append(opo) + decompositions: dict[torch._ops.OperatorBase, Callable] = {} + for op in aten_ops: + if isinstance(op, OpOverloadPacket) and op in packets_to_overloads: + for op_overload in packets_to_overloads[op]: + decompositions[op_overload] = registry[op_overload] + elif isinstance(op, (torch._ops.OperatorBase)) and op in registry: + decompositions[op] = registry[op] + return decompositions + + +def remove_decompositions( + decompositions: dict[torch._ops.OperatorBase, Callable], + aten_ops: Sequence[Union[OpOverload, OpOverloadPacket]], +) -> None: + """ + Given a dictionary of decompositions obtained from get_decompositions(), removes + operators associated with a list of operator overloads and overload packets passed + as input. If the decomposition dictionary does not contain a decomposition that is + specified to be removed, it is silently ignored. + """ + for op in aten_ops: + if isinstance(op, OpOverloadPacket): + for overload_name in op.overloads(): + opo = getattr(op, overload_name) + decompositions.pop(opo, None) + elif isinstance(op, OpOverload): + decompositions.pop(op, None) + + +# populate the table +import torch._decomp.decompositions +import torch._refs + + +def core_aten_decompositions() -> "CustomDecompTable": + from torch.export.exported_program import default_decompositions + + return default_decompositions() + + +# See NOTE [Core ATen Ops] +# +# list was copied from torch/_inductor/decomposition.py +# excluding decompositions that results in prim ops +# Resulting opset of decomposition is core aten ops +def _core_aten_decompositions_post_autograd() -> dict[ + torch._ops.OperatorBase, Callable +]: + aten = torch.ops.aten + return get_decompositions( + [ + aten.addcdiv, + aten.addcdiv_, + aten.addcmul, + aten.addcmul_, + aten.addr, + aten.affine_grid_generator, + aten.alias_copy, + aten.all, + aten.aminmax, + aten.arange.default, + aten.arange.start, + aten.avg_pool2d_backward, + aten.baddbmm, + aten.binary_cross_entropy, + aten.binary_cross_entropy_backward, + aten.binary_cross_entropy_with_logits, + aten.block_diag, + aten.bernoulli.p, + aten.bernoulli.default, + aten.celu, + aten.celu_, + aten.channel_shuffle, + aten.clamp_max, + aten.clamp_min, + aten.col2im, + aten.count_nonzero, + aten.linalg_cross, + aten.cudnn_batch_norm, + aten.cudnn_batch_norm_backward, + aten.miopen_batch_norm_backward, + aten.deg2rad, + aten.deg2rad_, + aten.detach, + aten.diag_embed, + aten.diagonal_backward, + aten.diagonal_copy, + aten.dot, + aten.vdot, + aten.elu_, + aten.elu_backward, + aten._embedding_bag, + aten.embedding_dense_backward, + aten.empty_like, + aten._euclidean_dist.default, + aten.expand_as, + aten.expand_copy, + aten.eye, + aten.fill, + aten.fill_, + aten.floor_divide, + aten.frac, + aten.frac_, + aten._fused_moving_avg_obs_fq_helper, + aten.gelu_, + aten.gelu_backward, + aten.glu, + aten.glu_backward, + aten.hardshrink, + aten.hardsigmoid, + aten.hardsigmoid_, + aten.hardsigmoid_backward, + aten.hardswish, + aten.hardswish_, + aten.hardswish_backward, + aten.hardtanh_, + aten.hardtanh_backward, + aten.heaviside, + aten.heaviside_, + aten.huber_loss, + aten.huber_loss_backward, + aten.im2col, + aten.index_add.out, + aten.index_add.default, + aten.index_add_, + aten.index_copy.out, + aten.index_copy.default, + aten.index_copy_, + aten.index_fill.int_Scalar, + aten.index_fill.int_Tensor, + aten.index_fill.int_Scalar_out, + aten.index_fill.int_Tensor_out, + aten.index_fill_, + aten.isin, + aten.isneginf, + aten.isposinf, + aten.l1_loss, + aten._lazy_clone, + aten._test_parallel_materialize, + aten.leaky_relu_, + aten.leaky_relu_backward, + aten.lerp, + aten.lerp_, + aten.linspace, + aten.logaddexp, + aten.logaddexp2, + aten.logit, + aten.logit_, + aten.logit_backward, + aten.log_sigmoid_backward, + aten.log_sigmoid_forward, + aten._log_softmax_backward_data, + aten.logspace, + aten.logsumexp.default, + aten.masked_fill, + aten.masked_fill_, + aten.max_unpool2d, + aten.max_unpool3d, + aten.mish, + aten.mish_, + aten.mish_backward, + aten.mse_loss, + aten.mse_loss_backward, + aten.multi_margin_loss, + aten.multilabel_margin_loss_forward, + aten.mv, + aten.mvlgamma, + aten.mvlgamma_, + aten.nansum, + aten.nan_to_num, + aten.nan_to_num_, + aten.narrow, + aten.native_batch_norm_backward, + aten.native_dropout_backward, + aten.native_group_norm_backward, + aten.native_layer_norm_backward, + aten._fused_rms_norm, + aten._fused_rms_norm_backward, + aten.new_empty, + aten.new_full, + aten.new_ones, + aten.new_zeros, + aten.nll_loss2d_forward, + aten.nll_loss2d_backward, + aten.nll_loss_backward, + aten.nll_loss_forward, + aten.norm.ScalarOpt_dtype, + aten.norm.Scalar, + aten.norm.ScalarOpt_dim_dtype, + aten.norm.ScalarOpt_dim, + aten.norm.dtype_out, + aten.norm.out, + aten.norm.names_dtype_out, + aten.norm.names_out, + aten.norm.ScalarOpt_dtype_out, + aten.norm.Scalar_out, + aten.ones, + aten.ones_like, + aten.pixel_shuffle, + aten.pixel_unshuffle, + aten._prelu_kernel, + aten._prelu_kernel_backward, + aten._reshape_alias, + aten.rad2deg, + aten.rad2deg_, + aten.reflection_pad1d, + aten.reflection_pad1d_backward, + aten.reflection_pad2d, + aten.reflection_pad2d_backward, + aten.reflection_pad3d, + aten.reflection_pad3d_backward, + aten.replication_pad1d, + aten.replication_pad2d, + aten.replication_pad3d, + aten.renorm, + aten.renorm_, + aten.replication_pad2d, + aten.resize_as, + aten.roll, + aten.rot90, + aten.rrelu_with_noise, + aten.rrelu_with_noise_, + aten.rsub, + aten._safe_softmax, + aten._scaled_dot_product_flash_attention_for_cpu.default, + aten.select_backward, + aten.select_scatter, + aten.sgn, + aten.sgn_, + aten.sigmoid_backward, + aten.silu, + aten.silu_, + aten.silu_backward.grad_input, + aten.silu_backward, + aten.sinc, + aten.sinc_, + aten.slice_backward, + aten.smooth_l1_loss, + aten.smooth_l1_loss_backward, + aten.soft_margin_loss, + aten.soft_margin_loss_backward, + aten._softmax_backward_data, + aten.softplus, + aten.softplus_backward, + aten.softshrink, + aten.special_entr, + aten.special_log_ndtr, + aten.special_xlog1py, + aten.split.Tensor, + aten.split_with_sizes_copy, + aten.squeeze_copy, + aten.squeeze.default, + aten.squeeze.dim, + aten.std.correction, + aten.std.out, + aten.std.correction_out, + aten.std.names_out, + aten.std.correction_names_out, + aten.std_mean.correction, + aten.std_mean.correction_out, + aten.stack, + aten.sum.default, + aten.sum.out, + aten.t, + aten.t_copy, + aten.take, + aten.tanh_backward, + aten.threshold, + aten.threshold_, + aten.threshold_backward, + aten.trace, + aten.transpose.int, + aten.transpose_copy, + aten.tril, + aten.tril_, + aten.triu, + aten.triu_, + aten.unbind, + aten.unfold_backward, + aten.unfold_copy, + aten._unsafe_index, + aten._unsafe_index_put, + aten._unsafe_masked_index, + aten._unsafe_masked_index_put_accumulate, + aten.unsafe_split.Tensor, + aten.unsafe_split_with_sizes, + aten.unsqueeze_copy, + aten._unsafe_view, + aten.upsample_linear1d, + aten.upsample_bilinear2d.out, + aten.upsample_trilinear3d.out, + aten.upsample_nearest2d_backward, + aten.view_as_complex, + aten.xlogy, + aten.xlogy_, + aten.zero, + aten.zero_, + aten.zeros, + aten.zeros_like, + aten._chunk_cat, + aten._weight_norm_interface, + ] + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_decomp/decompositions.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_decomp/decompositions.py new file mode 100644 index 0000000000000000000000000000000000000000..4446ed5cdd3107f5177284ff08f3455663eeff8d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_decomp/decompositions.py @@ -0,0 +1,5376 @@ +# mypy: allow-untyped-decorators +# mypy: allow-untyped-defs +import functools +import itertools +import numbers +import operator +import sys +from collections.abc import Callable, Iterable +from contextlib import nullcontext +from enum import Enum +from functools import partial, reduce +from itertools import chain, product +from typing import Any, cast, Optional, Union + +import torch +import torch._meta_registrations +import torch._prims as prims +import torch._prims_common as utils +import torch.nn.functional as F +from torch import sym_float, sym_int, Tensor +from torch._decomp import register_decomposition +from torch._higher_order_ops.out_dtype import out_dtype +from torch._prims_common import ( + IntLike, + NumberType, + suggest_memory_format, + TensorLike, + TensorSequenceType, +) +from torch._prims_common.wrappers import ( + _maybe_convert_to_dtype, + _maybe_resize_out, + _safe_copy_out, + out_wrapper, +) +from torch.utils import _pytree as pytree +from torch.utils._pytree import tree_map + + +DispatchKey = torch._C.DispatchKey # type: ignore[attr-defined] + +# None of these functions are publicly accessible; get at them +# from torch._decomps +__all__: list[str] = [] + +aten = torch._ops.ops.aten + + +class Reduction(Enum): + NONE = 0 + MEAN = 1 + SUM = 2 + + +# This wraps a decomposition and performs various type promotion logic within it, depending on the strategy provided +# We're currently reusing ELEMENTWISE_TYPE_PROMOTION_KIND, although some of the usages are on non-elementwise ops +# Will need to validate the non-elementwise uses +def type_casts( + f: Callable, + type_promotion: utils.ELEMENTWISE_TYPE_PROMOTION_KIND, + compute_dtype_only: bool = False, + include_non_tensor_args: bool = False, +): + @functools.wraps(f) + def inner(*args, **kwargs): + allowed_types = ( + (Tensor, torch.types._Number) if include_non_tensor_args else (Tensor,) + ) # type: ignore[arg-type] + flat_args = [ + x + for x in pytree.arg_tree_leaves(*args, **kwargs) + if isinstance(x, allowed_types) + ] + computation_dtype, result_dtype = utils.elementwise_dtypes( + *flat_args, type_promotion_kind=type_promotion + ) + + # TODO: pretty sure this is not quite right + def increase_prec(x): + if isinstance(x, Tensor): + return x.to(computation_dtype) + else: + return x + + def decrease_prec(x): + if isinstance(x, Tensor): + return x.to(result_dtype) + else: + return x + + r = f(*tree_map(increase_prec, args), **tree_map(increase_prec, kwargs)) + if compute_dtype_only: + return r + else: + return tree_map(decrease_prec, r) + + return inner + + +compute_only_pw_cast_for_opmath = partial( + type_casts, + type_promotion=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, + compute_dtype_only=True, +) +pw_cast_for_opmath = partial( + type_casts, type_promotion=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT +) +pw_cast_for_opmath_non_tensor_args = partial( + type_casts, + type_promotion=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, + include_non_tensor_args=True, +) +pw_cast_for_int_to_real = partial( + type_casts, type_promotion=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT +) + + +# This expands x until x.dim() == dim. Might be useful as an operator +def _unsqueeze_to_dim(x: Tensor, dim: int) -> Tensor: + for _ in range(dim - x.dim()): + x = x.unsqueeze(-1) + return x + + +@register_decomposition(aten.tanh_backward) +@out_wrapper("grad_input") +@pw_cast_for_opmath +def tanh_backward(out_grad: Tensor, y: Tensor): + return out_grad * (1 - y * y).conj_physical() + + +@register_decomposition(aten.sigmoid_backward) +@out_wrapper("grad_input") +@pw_cast_for_opmath +def sigmoid_backward(out_grad: Tensor, y: Tensor): + return out_grad * (y * (1 - y)).conj_physical() + + +@register_decomposition(aten.softplus_backward) +@out_wrapper("grad_input") +@pw_cast_for_opmath +def softplus_backward(out_grad: Tensor, x: Tensor, beta: float, threshold: float): + z = (x * beta).exp() + return torch.where((x * beta) > threshold, out_grad, out_grad * z / (z + 1.0)) + + +@register_decomposition(aten.elu_backward) +@out_wrapper("grad_input") +@pw_cast_for_opmath +def elu_backward( + grad_output: Tensor, + alpha: float, + scale: float, + input_scale: float, + is_result: bool, + self_or_result: Tensor, +): + negcoef = alpha * scale + poscoef = scale + negiptcoef = input_scale + if is_result: + return torch.where( + self_or_result <= 0, + grad_output * negiptcoef * (self_or_result + negcoef), + grad_output * poscoef, + ) + else: + return torch.where( + self_or_result <= 0, + grad_output * negiptcoef * negcoef * torch.exp(self_or_result * negiptcoef), + grad_output * poscoef, + ) + + +@register_decomposition([aten.fill.Scalar]) +def fill_scalar(self, value): + return torch.full_like(self, value) + + +@register_decomposition([aten.fill.Tensor]) +def fill_tensor(self, value: Tensor): + torch._check( + value.dim() == 0, + lambda: f"fill only supports 0-dimension value tensor but got tensor with {value.dim()} dimensions", + ) + return aten.copy(self, value) + + +@register_decomposition(aten.hardsigmoid) +@out_wrapper() +@pw_cast_for_opmath +def hardsigmoid(self: Tensor) -> Tensor: + return torch.clamp(torch.clamp(self + 3, min=0), max=6) / 6 + + +@register_decomposition(aten.hardsigmoid_backward) +@out_wrapper("grad_input") +@pw_cast_for_opmath +def hardsigmoid_backward(grad_output: Tensor, self: Tensor): + return torch.where( + (self > -3.0) & (self < 3.0), + grad_output * (1.0 / 6.0), + 0.0, + ) + + +@register_decomposition(aten.hardtanh_backward) +@out_wrapper("grad_input") +def hardtanh_backward( + grad_output: Tensor, self: Tensor, min_val: float, max_val: float +): + return torch.where((self <= min_val) | (self >= max_val), 0.0, grad_output) + + +@register_decomposition(aten.hardswish) +@out_wrapper() +@pw_cast_for_opmath +def hardswish(self: Tensor) -> Tensor: + return self * torch.clamp(torch.clamp(self + 3, min=0), max=6) / 6 + + +@register_decomposition(aten.hardswish_backward) +@out_wrapper() +@pw_cast_for_opmath +def hardswish_backward(grad_output: Tensor, self: Tensor) -> Tensor: + return torch.where( + self <= -3, + 0.0, + torch.where(self < 3, grad_output * ((self / 3) + 0.5), grad_output), + ) + + +@register_decomposition(aten.threshold_backward) +@out_wrapper("grad_input") +def threshold_backward(grad_output: Tensor, self: Tensor, threshold: float): + return torch.where(self <= threshold, 0, grad_output) + + +@register_decomposition(aten.leaky_relu_backward) +@out_wrapper("grad_input") +@pw_cast_for_opmath +def leaky_relu_backward( + grad_output: Tensor, self: Tensor, negative_slope: float, self_is_result: bool +): + return torch.where(self > 0, grad_output, grad_output * negative_slope) + + +@register_decomposition(aten.gelu_backward) +@out_wrapper("grad_input") +@pw_cast_for_opmath +def gelu_backward(grad: Tensor, self: Tensor, approximate: str = "none"): + M_SQRT2 = 1.41421356237309504880 + M_SQRT1_2 = 0.70710678118654752440 + M_2_SQRTPI = 1.12837916709551257390 + if approximate == "tanh": + kBeta = M_SQRT2 * M_2_SQRTPI * 0.5 + kKappa = 0.044715 + x_sq = self * self + x_cube = x_sq * self + inner = kBeta * (self + kKappa * x_cube) + tanh_inner = torch.tanh(inner) + + left = 0.5 * self + right = 1 + tanh_inner + + left_derivative = 0.5 * right + + tanh_derivative = 1 - tanh_inner * tanh_inner + inner_derivative = kBeta * (1 + 3 * kKappa * x_sq) + right_derivative = left * tanh_derivative * inner_derivative + + return grad * (left_derivative + right_derivative) + else: + kAlpha = M_SQRT1_2 + kBeta = M_2_SQRTPI * M_SQRT1_2 * 0.5 + cdf = 0.5 * (1 + torch.erf(self * kAlpha)) + pdf = kBeta * torch.exp(self * self * -0.5) + return grad * (cdf + self * pdf) + + +@register_decomposition(aten.mish_backward) +@pw_cast_for_opmath +def mish_backward(grad_output: Tensor, input: Tensor): + input_tanh_softplus = torch.tanh(F.softplus(input)) + input_sigmoid = torch.sigmoid(input) + out = input * input_sigmoid * (1 - input_tanh_softplus * input_tanh_softplus) + return grad_output * (input_tanh_softplus + out) + + +@register_decomposition(aten.silu) +@out_wrapper() +@pw_cast_for_opmath +def silu(self: Tensor) -> Tensor: + return self * torch.sigmoid(self) + + +@register_decomposition(aten.silu_backward) +@out_wrapper("grad_input") +@pw_cast_for_opmath +def silu_backward(grad_output: Tensor, self: Tensor) -> Tensor: + sigmoid = 1 / (1 + torch.exp(-self)) + return grad_output * sigmoid * (1 + self * (1 - sigmoid)) + + +@register_decomposition(aten._prelu_kernel) +def _prelu_kernel(self: Tensor, weight: Tensor) -> Tensor: + return torch.where(self > 0, self, weight * self) + + +@register_decomposition(aten._prelu_kernel_backward) +def _prelu_kernel_backward( + grad_output: Tensor, + self: Tensor, + weight: Tensor, +) -> tuple[Tensor, Tensor]: + input_grad = torch.where(self > 0, grad_output, weight * grad_output) + weight_grad = torch.where(self > 0, 0.0, self * grad_output) + return (input_grad, weight_grad) + + +@register_decomposition(aten.rrelu_with_noise_backward) +@out_wrapper() +@pw_cast_for_opmath +def rrelu_with_noise_backward( + grad_output: Tensor, + self: Tensor, + noise: Tensor, + lower: float, + upper: float, + training: bool, + self_is_result: bool, +) -> Tensor: + if training and upper - lower > 1e-6: + return grad_output.mul(noise) + else: + negative_slope = (lower + upper) / 2 + return aten.leaky_relu_backward( + grad_output, self, negative_slope, self_is_result + ) + + +@register_decomposition(aten.log_sigmoid_backward) +@out_wrapper("grad_input") +@pw_cast_for_opmath +def log_sigmoid_backward(grad_output: Tensor, self: Tensor, buffer: Tensor) -> Tensor: + in_negative = self < 0 + max_deriv = torch.where(in_negative, 1, 0) + sign = torch.where(in_negative, 1, -1) + z = torch.exp(-torch.abs(self)) + return grad_output * (max_deriv - sign * (z / (1 + z))) + # CPU has a special formula that uses buffer, but disabled for convenience sake + # return (max_deriv - sign * (buffer / (1 + buffer))) * grad_output + + +def apply_loss_reduction(loss: Tensor, reduction: int): + if reduction == Reduction.MEAN.value: + return torch.mean(loss) + elif reduction == Reduction.SUM.value: + return torch.sum(loss) + else: + return loss + + +def to_real_dtype(dtype: torch.dtype): + if dtype == torch.complex32: + return torch.float16 + elif dtype == torch.complex64: + return torch.float32 + elif dtype == torch.complex128: + return torch.float64 + + +# TODO: None of these loss castings are quite correct, see +# https://github.com/pytorch/pytorch/issues/76870. Also, the ATen kernels +# perform the pointwise portion in opmath, but don't maintain it between the +# pointwise portion and the reduction + + +@register_decomposition(aten.mse_loss) +@out_wrapper() +@pw_cast_for_opmath +def mse_loss( + self: Tensor, target: Tensor, reduction: int = Reduction.MEAN.value +) -> Tensor: + # pyrefly: ignore [unsupported-operation] + loss = (self - target) ** 2 + return apply_loss_reduction(loss, reduction) + + +@register_decomposition(aten.mse_loss_backward) +@out_wrapper("grad_input") +@pw_cast_for_opmath +def mse_loss_backward( + grad_output: Tensor, input: Tensor, target: Tensor, reduction: int +): + norm = 2.0 / input.numel() if reduction == Reduction.MEAN.value else 2.0 + return norm * (input - target) * grad_output + + +@register_decomposition(aten._safe_softmax) +def safe_softmax(self, dim, dtype=None): + out = torch.softmax(self, dim=dim, dtype=dtype) + masked = self.eq(float("-inf")) + masked_rows = torch.all(masked, dim=dim, keepdim=True) + zeros = torch.zeros_like(out) + return torch.where(masked_rows, zeros, out) + + +@register_decomposition(aten.smooth_l1_loss) +@out_wrapper() +@pw_cast_for_opmath +def smooth_l1_loss( + self: Tensor, + target: Tensor, + reduction: int = Reduction.MEAN.value, + beta: float = 1.0, +): + loss = (self - target).abs() + # pyrefly: ignore [unsupported-operation] + loss = torch.where(loss < beta, 0.5 * loss**2 / beta, loss - 0.5 * beta) + return apply_loss_reduction(loss, reduction) + + +@register_decomposition(aten.smooth_l1_loss_backward.default) +@pw_cast_for_opmath +def smooth_l1_loss_backward( + grad_output: Tensor, self: Tensor, target: Tensor, reduction: int, beta: float +): + norm = 1.0 / self.numel() if reduction == Reduction.MEAN.value else 1.0 + x = self - target + abs_x = torch.abs(x) + norm_grad = norm * grad_output + return torch.where( + abs_x < beta, + norm_grad * x / beta, + norm_grad * torch.sign(x), + ) + + +@register_decomposition(aten.smooth_l1_loss_backward.grad_input) +@pw_cast_for_opmath +def smooth_l1_loss_backward_out( + grad_output: Tensor, + self: Tensor, + target: Tensor, + reduction: int, + beta: float, + grad_input: Tensor, +): + result = smooth_l1_loss_backward(grad_output, self, target, reduction, beta) + _maybe_resize_out(grad_input, result.shape) + return _safe_copy_out(copy_from=result, copy_to=grad_input, exact_dtype=True) + + +@register_decomposition(aten.huber_loss_backward.default) +@pw_cast_for_opmath +def huber_loss_backward( + grad_output: Tensor, self: Tensor, target: Tensor, reduction: int, delta: float +): + norm = 1.0 / self.numel() if reduction == Reduction.MEAN.value else 1.0 + x = self - target + return torch.where( + x < -delta, + -norm * grad_output * delta, + torch.where(x > delta, norm * grad_output * delta, norm * x * grad_output), + ) + + +# We cannot use @out_wrapper() here, because the output tensor is not named 'out', it's 'grad_input' +@register_decomposition(aten.huber_loss_backward.out) +@pw_cast_for_opmath +def huber_loss_backward_out( + grad_output: Tensor, + self: Tensor, + target: Tensor, + reduction: int, + delta: float, + grad_input: Tensor, +): + result = huber_loss_backward(grad_output, self, target, reduction, delta) + _maybe_resize_out(grad_input, result.shape) + return _safe_copy_out(copy_from=result, copy_to=grad_input, exact_dtype=True) + + +def _nll_loss_backward( + grad_output: Tensor, + self: Tensor, + target: Tensor, + weight: Optional[Tensor], + reduction: int, + ignore_index: int, + total_weight: Tensor, +) -> Tensor: + channel_dim = 0 if self.dim() < 2 else 1 + if reduction == Reduction.MEAN.value: + grad_output = grad_output / total_weight + + target = target.unsqueeze(channel_dim) + safe_target = torch.where(target != ignore_index, target, 0) + grad_input = torch.zeros_like(self) + grad_input = torch.scatter(grad_input, channel_dim, safe_target, -1.0) + + if grad_input.dim() > grad_output.dim() > 0: + grad_output = grad_output.unsqueeze(channel_dim) + + if weight is not None: + new_shape = [1 for _ in range(self.dim())] + new_shape[channel_dim] = weight.shape[0] + weight = weight.reshape(new_shape) + grad_output = grad_output * weight + + grad_output = torch.where(target != ignore_index, grad_output, 0) + + return grad_input * grad_output + + +@register_decomposition(aten.glu_backward) +@out_wrapper("grad_input") +@pw_cast_for_opmath +def glu_backward(grad_output: Tensor, self: Tensor, dim: int) -> Tensor: + assert self.dim() > 0, "glu does not support 0-dimensional tensors" + wrap_dim = utils.canonicalize_dim(self.dim(), dim) + nIn = self.size(wrap_dim) + assert nIn % 2 == 0, ( + f"Halving dimension must be even, but dimension {wrap_dim} is size {nIn}" + ) + inputSize = nIn // 2 + firstHalf = self.narrow(wrap_dim, 0, inputSize) + secondHalf = self.narrow(wrap_dim, inputSize, inputSize) + gradInputFirstHalf = torch.sigmoid(secondHalf) + gradInputSecondHalf = ( + (1.0 - gradInputFirstHalf) * gradInputFirstHalf * firstHalf * grad_output + ) + gradInputFirstHalf = gradInputFirstHalf * grad_output + return torch.cat([gradInputFirstHalf, gradInputSecondHalf], dim=wrap_dim) + + +@register_decomposition(aten.nll_loss_backward) +@out_wrapper("grad_input") +def nll_loss_backward( + grad_output: Tensor, + self: Tensor, + target: Tensor, + weight: Optional[Tensor], + reduction: int, + ignore_index: int, + total_weight: Tensor, +) -> Tensor: + assert 0 <= self.dim() <= 2, "input tensor should be 1D or 2D" + assert target.dim() <= 1, ( + "0D or 1D target tensor expected, multi-target not supported" + ) + + no_batch_dim = self.dim() == 1 and target.dim() == 0 + assert no_batch_dim or (self.shape[0] == target.shape[0]), ( + f"size mismatch (got input: {self.shape}, target: {target.shape})" + ) + assert total_weight.numel() == 1, ( + "expected total_weight to be a single element tensor, got: ", + f"{total_weight.shape} ({total_weight.numel()} elements)", + ) + + assert weight is None or weight.numel() == self.shape[-1], ( + "weight tensor should be defined either for all or no classes" + ) + + if reduction == Reduction.NONE.value and self.dim() == 2: + assert grad_output.dim() == 1 and grad_output.shape[0] == self.shape[0], ( + f"Expected a tensor of dimension 1 and tensor.size[0] == {self.shape[0]} but " + f"got: dimension {grad_output.dim()} and tensor.size[0] == {grad_output.shape[0]}" + ) + else: + assert grad_output.dim() <= 1 and grad_output.numel() == 1, ( + f"Expected a single element grad_output tensor, but got: {grad_output.shape}" + ) + + return _nll_loss_backward( + grad_output, self, target, weight, reduction, ignore_index, total_weight + ) + + +@register_decomposition(aten.nll_loss2d_backward) +@out_wrapper("grad_input") +def nll_loss2d_backward( + grad_output: Tensor, + self: Tensor, + target: Tensor, + weight: Optional[Tensor], + reduction: int, + ignore_index: int, + total_weight: Tensor, +) -> Tensor: + assert self.dim() == 4, ( + f"only batches of spatial inputs supported (4D tensors), but got input of dimension: {self.dim()}" + ) + + assert target.dim() == 3, ( + f"only batches of spatial targets supported (3D tensors) but got targets of dimension: {target.dim()}" + ) + + assert ( + self.shape[0] == target.shape[0] + and self.shape[2] == target.shape[1] + and self.shape[3] == target.shape[2] + ), f"size mismatch (got input: {self.shape}, target: {target.shape}" + + assert total_weight.numel() == 1, ( + "expected total_weight to be a single element tensor, " + f"got: {total_weight.shape} ( {total_weight.numel()}, elements)" + ) + + return _nll_loss_backward( + grad_output, self, target, weight, reduction, ignore_index, total_weight + ) + + +@register_decomposition(aten.binary_cross_entropy) +@out_wrapper() +@pw_cast_for_opmath +def binary_cross_entropy( + self: Tensor, + target: Tensor, + weight: Optional[Tensor] = None, + reduction: int = Reduction.MEAN.value, +) -> Tensor: + # We cannot currently model this without introducing data-dependent control flow + # TORCH_CHECK( + # (input_val >= 0) && (input_val <= 1), + # "all elements of input should be between 0 and 1" + # ) + loss = (target - 1) * torch.maximum( + torch.log1p(-self), self.new_full((), -100) + ) - target * torch.maximum(torch.log(self), self.new_full((), -100)) + if weight is not None: + loss = loss * weight + return apply_loss_reduction(loss, reduction) + + +@register_decomposition(aten.binary_cross_entropy_backward) +@out_wrapper("grad_input") +@pw_cast_for_opmath +def binary_cross_entropy_backward( + grad_output: Tensor, + self: Tensor, + target: Tensor, + weight: Optional[Tensor] = None, + reduction: int = Reduction.MEAN.value, +) -> Tensor: + EPSILON = 1e-12 + result = grad_output * (self - target) / torch.clamp(self * (1 - self), min=EPSILON) + if weight is not None: + result = result * weight + if reduction == Reduction.MEAN.value: + result = result / self.numel() + return result + + +@register_decomposition(aten.soft_margin_loss) +@out_wrapper() +@pw_cast_for_opmath +def soft_margin_loss( + input: Tensor, + target: Tensor, + reduction: int = Reduction.MEAN.value, +) -> Tensor: + loss = torch.log1p(torch.exp(-input * target)) + return apply_loss_reduction(loss, reduction) + + +@register_decomposition(aten.soft_margin_loss_backward) +@out_wrapper("grad_input") +@pw_cast_for_opmath +def soft_margin_loss_backward( + grad_output: Tensor, + self: Tensor, + target: Tensor, + reduction: int = Reduction.MEAN.value, +) -> Tensor: + grad_input = target * grad_output * (torch.sigmoid(target * self) - 1) + if reduction == Reduction.MEAN.value: + grad_input = grad_input / self.numel() + return grad_input + + +@register_decomposition(aten.dist) +@out_wrapper() +def dist(input: Tensor, other: Tensor, p: float = 2): + return aten.norm(input - other, p=p) + + +@register_decomposition(aten._euclidean_dist) +@out_wrapper() +def _euclidean_dist(x1: Tensor, x2: Tensor) -> Tensor: + x1_norm = x1.pow(2).sum(-1, True) + x1_pad = torch.ones_like(x1_norm, memory_format=torch.contiguous_format) + x2_norm = x2.pow(2).sum(-1, True) + x2_pad = torch.ones_like(x2_norm, memory_format=torch.contiguous_format) + x1_ = torch.cat([x1.mul(-2), x1_norm, x1_pad], -1) + x2_ = torch.cat([x2, x2_pad, x2_norm], -1) + result = x1_.matmul(x2_.mT) + return result.clamp_min(0).sqrt() + + +@register_decomposition(aten.slice_backward) +@out_wrapper() +def slice_backward( + grad_output: Tensor, + input_sizes: list[int], + dim: int, + start: int, + end: int, + step: int, +): + grad_input = grad_output.new_zeros(input_sizes) + return torch.slice_scatter(grad_input, grad_output, dim, start, end, step) + + +@register_decomposition(aten.slice.Tensor) +def slice_forward( + # Tensor(a) self, int dim=0, SymInt? start=None, SymInt? end=None, SymInt step=1 + self: Tensor, + dim: int = 0, + start: Optional[int] = None, + end: Optional[int] = None, + step: int = 1, +): + from torch.fx.experimental.symbolic_shapes import statically_known_true + + ndim = self.dim() + if ndim == 0: + raise RuntimeError("slice() cannot be applied to a 0-dim tensor.") + dim = utils.canonicalize_dim(self.dim(), dim) + sizes = list(self.size()) + strides = list(self.stride()) + + if step <= 0: + raise RuntimeError("slice step must be positive") + + start_val = start if start is not None else 0 + end_val = end if end is not None else sys.maxsize # 2^63 - 1 + + if start_val < 0: + start_val += sizes[dim] + + if end_val < 0: + end_val += sizes[dim] + + if start_val < 0: + start_val = 0 + elif start_val > sizes[dim]: + start_val = sizes[dim] + + if statically_known_true(end_val == sys.maxsize): + end_val = sizes[dim] + elif end_val < start_val: + end_val = start_val + elif end_val > sizes[dim]: + end_val = sizes[dim] + + storage_offset = self.storage_offset() + start_val * strides[dim] + len = end_val - start_val + sizes[dim] = (len + step - 1) // step + strides[dim] *= step + + if self.is_quantized: + raise NotImplementedError( + "Slice decomposition for quantized tensors aren't implemented" + ) + else: + return self.as_strided(sizes, strides, storage_offset) + + +def _normalize_start_end( + x: Tensor, dim: int, start: Optional[int], end: Optional[int] +) -> tuple[int, int]: + """ + Normalize start and end such that both are in the range + [0, x.get_size()[dim]] and start <= end. + """ + dim_size = x.shape[dim] + + def clamp_wrap(val, lower, upper, default) -> int: + if val is None: + return default + if val < 0: + val = val + dim_size + return min(max(val, lower), upper) + + start = clamp_wrap(start, 0, dim_size, 0) + end = clamp_wrap(end, start, dim_size, dim_size) + return start, end + + +# This is not in torch._refs because aten.index used by +# aten._unsafe_masked_index does not have a decomposition. +@register_decomposition(aten.slice_scatter) +@out_wrapper() +def slice_scatter( + input: Tensor, + src: Tensor, + dim: int = 0, + start: Optional[int] = None, + end: Optional[int] = None, + step: int = 1, +): + dim = utils.canonicalize_dim(input.ndim, dim) + dim_size = input.shape[dim] + start, end = _normalize_start_end(input, dim, start, end) + + src_size = list(input.shape) + src_size[dim] = (end - start + (step - 1)) // step + src = src.expand(src_size) + + if start == 0 and end == dim_size and step == 1: + return src.clone() + + indices: list[Optional[Tensor]] = [None] * input.dim() + idx = torch.arange(dim_size, device=input.device) + indices[dim] = (idx - start) // step + + mask = torch.ones(dim_size, device=input.device, dtype=torch.bool) + if start != 0: + mask = torch.logical_and(mask, idx >= start) + + if end != dim_size: + mask = torch.logical_and(mask, idx < end) + + if step != 1: + mask = torch.logical_and(mask, (idx - start) % step == 0) + + mask_shape = [1] * input.dim() + mask_shape[dim] = -1 + mask = mask.view(mask_shape) + return aten.where(mask, aten._unsafe_masked_index(src, mask, indices, 0), input) + + +@register_decomposition(aten.select_backward) +@out_wrapper() +def select_backward(grad_output: Tensor, input_sizes: list[int], dim: int, index: int): + grad_input = grad_output.new_zeros(input_sizes) + return torch.select_scatter(grad_input, grad_output, dim, index) + + +@register_decomposition(aten.diagonal_backward) +@out_wrapper() +def diagonal_backward( + grad_output: Tensor, input_sizes: list[int], offset: int, dim1: int, dim2: int +): + grad_input = grad_output.new_zeros(input_sizes) + return torch.diagonal_scatter(grad_input, grad_output, offset, dim1, dim2) + + +def _cast_grad_to_input_dtype( + grad_output: Tensor, grad_input: Tensor, input_dtype: torch.dtype +): + if grad_output.dtype != input_dtype: + grad_input = grad_input.to(input_dtype) + return grad_input + + +@register_decomposition(aten._softmax_backward_data) +@out_wrapper("grad_input") +@compute_only_pw_cast_for_opmath +def _softmax_backward_data( + grad_output: Tensor, output: Tensor, dim: int, input_dtype: torch.dtype +): + new_grad_output = grad_output * output + grad_input = new_grad_output - output * torch.sum( + new_grad_output, dim=dim, keepdim=True + ) + + # CPU kernel doesn't respect input_dtype, but following check doesn't work for meta tensor + # if grad_output.device == torch.device("cpu"): + # return grad_input.contiguous() + + return _cast_grad_to_input_dtype(grad_output, grad_input, input_dtype).contiguous() + + +@register_decomposition(aten._log_softmax_backward_data) +@out_wrapper() +@compute_only_pw_cast_for_opmath +def _log_softmax_backward_data( + grad_output: Tensor, output: Tensor, dim: int, input_dtype: torch.dtype +): + grad_input = grad_output - torch.exp(output) * torch.sum( + grad_output, dim=dim, keepdim=True + ) + return _cast_grad_to_input_dtype(grad_output, grad_input, input_dtype) + + +def _im2col_col2im_indices_along_dim( + input_d, kernel_d, dilation_d, padding_d, stride_d, device +): + """Utility function to implement im2col and col2im""" + blocks_d = input_d + padding_d * 2 - dilation_d * (kernel_d - 1) + + arange_kw = partial(torch.arange, dtype=torch.int64, device=device) + + # Stride kernel over input and find starting indices along dim d + blocks_d_indices = arange_kw(0, blocks_d, stride_d).unsqueeze(0) + + # Apply dilation on kernel and find its indices along dim d + kernel_grid = arange_kw(0, kernel_d * dilation_d, dilation_d).unsqueeze(-1) + + # Broadcast and add kernel starting positions (indices) with + # kernel_grid along dim d, to get block indices along dim d + return blocks_d_indices + kernel_grid + + +@register_decomposition(aten.im2col) +@out_wrapper() +def im2col( + input: Tensor, + kernel_size: list[int], + dilation: list[int], + padding: list[int], + stride: list[int], +) -> Tensor: + torch._check(len(kernel_size) == 2, lambda: "im2col(): only 2D kernel supported") + torch._check(len(dilation) == 2, lambda: "im2col(): only 2D dilation supported") + torch._check(len(padding) == 2, lambda: "im2col(): only 2D padding supported") + torch._check(len(stride) == 2, lambda: "im2col(): only 2D stride supported") + + def check_positive(param, param_name, strict=True): + cond = all(p > 0 for p in param) if strict else all(p >= 0 for p in param) + torch._check( + cond, lambda: f"{param_name} should be greater than zero, but got {param}" + ) + + check_positive(kernel_size, "kernel_size") + check_positive(dilation, "dilation") + check_positive(dilation, "padding", strict=False) + check_positive(stride, "stride") + + shape = input.shape + ndim = len(shape) + torch._check( + ndim in (3, 4) and all(d != 0 for d in shape[-3:]), + lambda: "Expected 3D or 4D (batch mode) tensor for input with possible 0 batch size " + f"and non-zero dimensions, but got: {tuple(shape)}", + ) + output_size = tuple( + 1 + (out + 2 * pad - dil * (ker - 1) - 1) // st + for out, pad, dil, ker, st in zip( + shape[-2:], padding, dilation, kernel_size, stride + ) + ) + torch._check( + all(c > 0 for c in output_size), + lambda: f"Given an input with spatial size {tuple(shape[-2:])}, " + f"kernel_size={kernel_size}, dilation={dilation}, " + f"padding={padding}, stride={stride}, " + "the calculated shape of the array of sliding blocks " + f"is {output_size}, but its components must be at least one.", + ) + batched_input = ndim == 4 + if not batched_input: + input = input.unsqueeze(0) + + batch_dim, channel_dim, input_h, input_w = input.shape + + stride_h, stride_w = stride + padding_h, padding_w = padding + dilation_h, dilation_w = dilation + kernel_h, kernel_w = kernel_size + + blocks_row_indices = _im2col_col2im_indices_along_dim( + input_h, kernel_h, dilation_h, padding_h, stride_h, input.device + ) + blocks_col_indices = _im2col_col2im_indices_along_dim( + input_w, kernel_w, dilation_w, padding_w, stride_w, input.device + ) + + # Note that F.pad takes (padding_left, padding_right, padding_top, padding_bottom) + # ugh + padded_input = F.pad(input, (padding_w, padding_w, padding_h, padding_h)) + + blocks_row_indices = blocks_row_indices.unsqueeze(-1).unsqueeze(-1) + output = padded_input[:, :, blocks_row_indices, blocks_col_indices] + output = output.permute(0, 1, 2, 4, 3, 5) + num_blocks_row = blocks_row_indices.size(1) + num_blocks_col = blocks_col_indices.size(1) + output = output.reshape( + batch_dim, channel_dim * kernel_h * kernel_w, num_blocks_row * num_blocks_col + ) + + if not batched_input: + output = output.squeeze(0) + return output + + +@register_decomposition(aten.col2im) +@out_wrapper() +@pw_cast_for_opmath +def col2im( + input: Tensor, + output_size: list[int], + kernel_size: list[int], + dilation: list[int], + padding: list[int], + stride: list[int], +) -> Tensor: + torch._check(len(output_size) == 2, lambda: "only 2D output_size supported") + torch._check(len(kernel_size) == 2, lambda: "only 2D kernel supported") + torch._check(len(dilation) == 2, lambda: "only 2D dilation supported") + torch._check(len(padding) == 2, lambda: "only 2D padding supported") + torch._check(len(stride) == 2, lambda: "only 2D stride supported") + + def check_positive(param, param_name, strict=True): + cond = all(p > 0 for p in param) if strict else all(p >= 0 for p in param) + torch._check( + cond, lambda: f"{param_name} should be greater than zero, but got {param}" + ) + + check_positive(kernel_size, "kernel_size") + check_positive(dilation, "dilation") + check_positive(padding, "padding", strict=False) + check_positive(stride, "stride") + check_positive(output_size, "output_size") + + shape = input.shape + ndim = len(shape) + torch._check( + ndim in (2, 3) and all(d != 0 for d in shape[-2:]), + lambda: "Expected 2D or 3D (batch mode) tensor for input with possible 0 batch size " + f"and non-zero dimensions, but got: {tuple(shape)}", + ) + prod_kernel_size = kernel_size[0] * kernel_size[1] + torch._check( + shape[-2] % prod_kernel_size == 0, + lambda: "Expected size of input's first non-batch dimension to be divisible by the " + f"product of kernel_size, but got input.shape[-2] = {shape[-2]} and " + f"kernel_size={kernel_size}", + ) + col = [ + 1 + (out + 2 * pad - dil * (ker - 1) - 1) // st + for out, pad, dil, ker, st in zip( + output_size, padding, dilation, kernel_size, stride + ) + ] + L = col[0] * col[1] + torch._check( + shape[-1] == L, + lambda: f"Given output_size={output_size}, kernel_size={kernel_size}, " + f"dilation={dilation}, padding={padding}, stride={stride}, " + f"expected input.size(-1) to be {L} but got {shape[-1]}.", + ) + torch._check( + L > 0, + lambda: f"Given output_size={output_size}, kernel_size={kernel_size}, " + f"dilation={dilation}, padding={padding}, stride={stride}, " + f"expected input.size(-1) to be {L} but got {shape[-1]}.", + ) + batched_input = ndim == 3 + if not batched_input: + input = input.unsqueeze(0) + + shape = input.shape + + out_h, out_w = output_size + stride_h, stride_w = stride + padding_h, padding_w = padding + dilation_h, dilation_w = dilation + kernel_h, kernel_w = kernel_size + + # col2im is defined as the backwards of im2col, so we differentiate its decomposition by hand + input = input.reshape([shape[0], shape[1] // prod_kernel_size] + kernel_size + col) + input = input.permute(0, 1, 2, 4, 3, 5) + + indices_row = _im2col_col2im_indices_along_dim( + out_h, kernel_h, dilation_h, padding_h, stride_h, input.device + ) + indices_row = _unsqueeze_to_dim(indices_row, 4) + indices_col = _im2col_col2im_indices_along_dim( + out_w, kernel_w, dilation_w, padding_w, stride_w, input.device + ) + + output_padded_size = [o + 2 * p for o, p in zip(output_size, padding)] + output = input.new_zeros( + [shape[0], shape[1] // prod(kernel_size)] + output_padded_size + ) + idx = (None, None, indices_row, indices_col) + output = aten._unsafe_index_put(output, idx, input, accumulate=True) + output = F.pad(output, (-padding_w, -padding_w, -padding_h, -padding_h)) + + if not batched_input: + output = output.squeeze(0) + return output + + +@register_decomposition(aten.native_dropout_backward) +@out_wrapper() +def native_dropout_backward(grad_output: Tensor, mask: Tensor, scale: float): + # According to the CUDA kernel implementation we should have this test; + # but it seems to fail tests! + # torch._check(mask.dtype == torch.bool, lambda: f"Mask should be Bool Scalar Type {mask.dtype}") + + # Mimicking CUDA kernel's behavior for output stride: output follow input's memory format + # This different from TensorIterator's behavior + r = (grad_output * (mask.type_as(grad_output) * scale)).clone( + memory_format=utils.suggest_memory_format(grad_output) + ) + return r + + +@register_decomposition(aten.unfold_backward) +@out_wrapper() +def unfold_backward( + grad: Tensor, input_size: list[int], dimension: int, size: int, step: int +) -> Tensor: + if len(input_size) == 0: + return torch.squeeze_copy(grad, 0) + dim = utils.canonicalize_dim(len(input_size), dimension) + idx = torch.arange(input_size[dim], device=grad.device, dtype=torch.int32) + idx = idx.unfold(0, size, step).flatten() + grad = grad.movedim(-1, dim + 1).flatten(dim, dim + 1) + # nb. At the moment this generates two kernels in triton + # It could potentially be fused into one call to scatter_reduce, + # in the case step <= size provided scatter_reduce generates 1 kernel + grad_input = grad.new_zeros(input_size) + index = (None,) * dim + (idx,) + return aten._unsafe_index_put(grad_input, index, grad, accumulate=True).contiguous() + + +@register_decomposition(aten.logit_backward.default) +@pw_cast_for_opmath +def logit_backward( + grad_output: Tensor, self: Tensor, eps: Optional[float] = None +) -> Tensor: + if eps is not None: + lo = eps + hi = 1.0 - lo + return torch.where( + torch.logical_and(self >= lo, self <= hi), + grad_output / (self * (1.0 - self)), + 0.0, + ) + else: + return torch.where( + torch.logical_and(self >= 0.0, self <= 1.0), + grad_output / (self * (1.0 - self)), + self.new_full((), float("nan")), + ) + + +@register_decomposition(aten.dropout) +@aten.dropout.default.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.dropout.default.py_impl(DispatchKey.Autograd) +def dropout(input: Tensor, p: float, train: Optional[bool]): + if train and p != 0: + return aten.native_dropout(input, p, train)[0] + else: + return input.clone() + + +@register_decomposition(aten.native_dropout) +@out_wrapper("out0", "out1") +def native_dropout(input: Tensor, p: float, train: Optional[bool]): + if train and p != 0: + if p == 1: + return (torch.zeros_like(input), torch.zeros_like(input, dtype=torch.bool)) + if not input.dtype.is_floating_point: + raise RuntimeError( + "result type Float can't be cast to the desired output type Long" + ) + bool_mask = torch.rand_like(input) > p + res = bool_mask * input * float(1.0 / (1.0 - p)) + return (res, bool_mask) + else: + return (input, torch.ones_like(input, dtype=torch.bool)) + + +@register_decomposition(aten._softmax) +@out_wrapper() +def _softmax(x: Tensor, dim: int, half_to_float: bool): + from torch.fx.experimental.symbolic_shapes import guard_or_false + + # eager softmax returns a contiguous tensor. Ensure that decomp also returns + # a contiguous tensor. + x = x.contiguous() + if half_to_float: + assert x.dtype == torch.half + computation_dtype, result_dtype = utils.elementwise_dtypes( + x, type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT + ) + x = x.to(computation_dtype) + if guard_or_false(x.numel() == 0): + unnormalized = torch.exp(x) + else: + x_max = torch.amax(x, dim, keepdim=True) + unnormalized = torch.exp(x - x_max) + result = unnormalized / torch.sum(unnormalized, dim, keepdim=True) + if not half_to_float: + result = result.to(result_dtype) + return result + + +@register_decomposition(aten._log_softmax) +@out_wrapper(exact_dtype=True) +def _log_softmax(x: Tensor, dim: int, half_to_float: bool): + from torch.fx.experimental.symbolic_shapes import guard_or_false + + # eager log_softmax returns a contiguous tensor. Ensure that decomp also + # returns a contiguous tensor. + x = x.contiguous() + if half_to_float: + assert x.dtype == torch.half + computation_dtype, result_dtype = utils.elementwise_dtypes( + x, type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT + ) + x = x.to(computation_dtype) + if guard_or_false(x.numel() == 0): + shifted = x + else: + x_max = torch.amax(x, dim, keepdim=True) + shifted = x - x_max + shifted_logsumexp = torch.log(torch.sum(torch.exp(shifted), dim, keepdim=True)) + result = shifted - shifted_logsumexp + if not half_to_float: + result = result.to(result_dtype) + return result + + +@register_decomposition(aten.embedding) +@out_wrapper() +def embedding( + weight: Tensor, + indices: Tensor, + padding_idx: int = -1, + scale_grad_by_freq: bool = False, + sparse: bool = False, +) -> Tensor: + assert weight.dim() == 2, "'weight' must be 2-D" + # Nb. scale_grad_by_freq is not used in the forward + if indices.ndim <= 1: + # We need this one as weight[indices] calls item() in these cases + out = weight.index_select(0, indices) + if indices.ndim == 0: + out = out.squeeze(0) + return out + else: + return weight[indices] + + +@register_decomposition(aten.embedding_dense_backward) +@out_wrapper() +def embedding_dense_backward( + grad_output: Tensor, + indices: Tensor, + num_weights: int, + padding_idx: int, + scale_grad_by_freq: bool, +): + computation_dtype, result_dtype = utils.elementwise_dtypes( + grad_output, type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT + ) + grad_output = grad_output.to(computation_dtype) + indices = _maybe_convert_to_dtype(indices, torch.long) # type: ignore[assignment] + if scale_grad_by_freq: + counts = indices.new_zeros((num_weights,)) + ones = torch.ones_like(indices) + counts = aten._unsafe_index_put(counts, [indices], ones, accumulate=True) + grad_weights_scale = counts[indices] + grad_output = grad_output / grad_weights_scale.unsqueeze(-1) + + mask = _unsqueeze_to_dim(indices == padding_idx, grad_output.ndim) + grad = grad_output.masked_fill(mask, 0) + grad_weight = grad_output.new_zeros( + (num_weights,) + grad_output.shape[indices.ndim :] + ) + return aten._unsafe_index_put(grad_weight, [indices], grad, accumulate=True).to( + result_dtype + ) + + +def prod(x: list[int]): + r = 1 + for i in x: + r *= i + return r + + +def _pad_chunk( + tensors: list[Tensor], + dim: int, + num_chunks: int, +) -> list[Tensor]: + padded_tensors = [] + for tensor in tensors: + tensor_size = tensor.size() + pad_along_dim = (tensor_size[dim] + num_chunks - 1) // num_chunks * num_chunks + if pad_along_dim != tensor_size[dim]: + # Use aten.constant_pad_nd instead of copy_ for functionalization + pad = [0] * 2 * (tensor.ndim - dim - 1) + [ + 0, + pad_along_dim - tensor_size[dim], + ] + tensor = aten.constant_pad_nd(tensor, pad, 0) + view_size = tensor_size[:dim] + torch.Size([num_chunks, -1]) + padded_tensors.append(tensor.reshape(view_size)) + return padded_tensors + + +def have_same_ndims(tensors: list[Tensor]): + ndim = tensors[0].ndim + for tensor in tensors: + if tensor.ndim != ndim: + return False + return True + + +def leading_dimension_matches(tensors: list[Tensor], dim: int): + leading_dim_sizes = tensors[0].size()[:dim] + for tensor in tensors: + torch._check( + tensor.size()[:dim] == leading_dim_sizes, + lambda: "_chunk_cat expects same sizes of 0,...,dim-1 dimensions for all tensors", + ) + + +def _preprocess_chunk_cat_inputs( + tensors: list[Tensor], + dim: int, + num_chunks: int, +): + torch._check(num_chunks >= 1, lambda: "_chunk_cat expects positive num_chunks") + torch._check( + len(tensors) > 0, lambda: "_chunk_cat expects a non-empty input tensor list" + ) + expected_dtype = tensors[0].dtype + expected_device = tensors[0].device + for tensor in tensors: + torch._check(tensor.numel() > 0, lambda: "_chunk_cat expects non-empty tensor") + torch._check( + tensor.dtype == expected_dtype, + lambda: "_chunk_cat expects all input tensors with the same dtype", + ) + torch._check( + tensor.device == expected_device, + lambda: "_chunk_cat expects all inputs tensors on the same device", + ) + if have_same_ndims(tensors): + dim = utils.canonicalize_dim(tensors[0].dim(), dim) + else: + torch._check( + dim >= 0, + lambda: "_chunk_cat expects non-negative dim when input tensors have different ndims", + ) + for tensor in tensors: + torch._check( + dim < tensor.ndim, + lambda: "_chunk_cat expects dim < ndim for all input tensors", + ) + leading_dimension_matches(tensors, dim) + return dim + + +@register_decomposition([aten._chunk_cat.default, aten._chunk_cat.out]) +def _chunk_cat( + tensors: list[Tensor], + dim: int, + num_chunks: int, + out: Optional[Tensor] = None, +) -> Tensor: + dim = _preprocess_chunk_cat_inputs(tensors, dim, num_chunks) + padded_tensors = _pad_chunk(tensors, dim, num_chunks) + if out is None: + return torch.cat(padded_tensors, dim + 1) + else: + torch.cat(padded_tensors, dim + 1, out=out) + return out + + +# out_wrapper currently does not allow optional outputs +@register_decomposition( + [aten.split_with_sizes_copy.default, aten.split_with_sizes_copy.out] +) +def split_with_sizes_copy( + self: Tensor, + split_sizes: list[int], + dim: int = 0, + out: Optional[list[Tensor]] = None, +) -> Optional[list[Tensor]]: + splits = aten.split_with_sizes(self, split_sizes, dim=dim) + if out is None: + return [s.clone(memory_format=torch.contiguous_format) for s in splits] + else: + for output, split in zip(out, splits): + _maybe_resize_out(output, split.shape) + _safe_copy_out(copy_from=split, copy_to=output, exact_dtype=True) + return None + + +@register_decomposition(aten.unsafe_split.Tensor) +def unsafe_split(input: Tensor, split_size: int, dim: int = 0) -> tuple[Tensor, ...]: + return aten.split.Tensor(input, split_size, dim) + + +@register_decomposition(aten.unsafe_split_with_sizes.default) +def unsafe_split_with_sizes( + input: Tensor, split_sizes: list[int], dim: int = 0 +) -> tuple[Tensor, ...]: + return aten.split_with_sizes.default(input, split_sizes, dim) + + +@register_decomposition(aten.split.Tensor) +def split(self: Tensor, split_size: int, dim: int = 0) -> tuple[Tensor, ...]: + input_sizes = self.shape + dim_size = input_sizes[dim] + if split_size == 0: + assert dim_size == 0 + return (self.detach(),) + chunks = (dim_size + split_size - 1) // split_size + + # Avoid importing sympy at a module level + from torch.fx.experimental.symbolic_shapes import guard_int + + chunks = guard_int(chunks) + split_sizes = [split_size for i in range(chunks)] + split_sizes[-1] = split_size - (split_size * chunks - dim_size) + return torch.split(self, split_sizes, dim) + + +@aten.tensor_split.tensor_indices_or_sections.py_impl( + DispatchKey.CompositeImplicitAutograd +) +def tensor_split_tensor_indices_or_sections_py_impl( + self: Tensor, + tensor_indices_or_sections: Tensor, + dim: int = 0, +) -> tuple[Tensor, ...]: + assert tensor_indices_or_sections.device.type == "cpu" + assert tensor_indices_or_sections.dtype == torch.int64 + split_dim = tensor_indices_or_sections.dim() + torch._check( + split_dim == 1 or split_dim == 0, + lambda: "tensor_split expected tensor_indices_or_sections to be a zero-dimensional " + f"or one-dimensional tensor, but got a tensor with {split_dim} dims", + ) + if split_dim == 0: + sections = tensor_indices_or_sections.item() + assert isinstance(sections, IntLike) + return self.tensor_split(sections, dim) + else: + ctx = nullcontext + if (fake_mode := torch._guards.detect_fake_mode()) and ( + shape_env := fake_mode.shape_env + ): + ctx = shape_env.ignore_fresh_unbacked_symbols # type: ignore[assignment] + # In fake tensor prop, we end up calling slice() with these unbacked indices. + # Because slice has flexible semantics, the unbacked handling generates new output sizes + # for each slice, effectively clobbering over these index symbols. + # To avoid PendingUnbackedSymbolNotFound errors, we tell the compiler it's fine to not bind these. + with ctx(): + indices = [i.item() for i in tensor_indices_or_sections] + # WARNING: Tempted to torch._check(x>0) on the indices here? You + # can't: tensor_split works with negative values in indices: + # + # >>> torch.tensor_split(torch.randn(10), torch.tensor([-5, 5])) + # (tensor([ 0.3540, 2.1074, -0.8507, 1.1639, 0.3055]), tensor([]), + # tensor([-0.4285, 1.0692, -0.1776, 0.9362, 1.6143])) + # + # Sorry, I don't make the rules. Explicitly do the item call in user + # code if you KNOW that they are non-negative. + return self.tensor_split(indices, dim) + + +# TODO: this doesn't appear to have enough precision in bfloat16 +@register_decomposition(aten.addmm) +@out_wrapper(exact_dtype=True) +@pw_cast_for_opmath +def addmm(self: Tensor, mat1: Tensor, mat2: Tensor, beta: int = 1, alpha: int = 1): + if not self.is_floating_point() and not self.is_complex(): + beta = int(beta) + alpha = int(alpha) + out = alpha * torch.mm(mat1, mat2) + if beta == 0: + return out + + # The output of aten.addmm is contiguous, we need to match this behavior in the decomposition. + # The original implementation 'beta * self + out' would return a strided tensor if `self` is strided. + # We thus use `out`, the output of torch.mm, which is always contiguous, as the first argument for addition. + # This is relying on TensorIterator's behavior that it takes higher precedence on the stride of first input. + # Alternative, we can write `(beta * self + out).contiguous()`, but it introduces another copy in some cases. + # This implementation is not ideal, and we should revisit this when we have a better solution. + return out + beta * self + + +@register_decomposition(aten._addmm_activation) +@out_wrapper() +@pw_cast_for_opmath +def _addmm_activation( + self: Tensor, + mat1: Tensor, + mat2: Tensor, + beta: int = 1, + alpha: int = 1, + use_gelu: bool = False, +): + out = addmm(self, mat1, mat2, beta, alpha) + if use_gelu: + if self.is_cuda: + return aten.gelu(out, approximate="tanh") + else: + return aten.gelu(out) + return aten.relu(out) + + +@register_decomposition(aten.addmv) +@out_wrapper(exact_dtype=True) +@pw_cast_for_opmath +def addmv(self: Tensor, mat1: Tensor, vec: Tensor, beta: int = 1, alpha: int = 1): + if not self.is_floating_point() and not self.is_complex(): + beta = int(beta) + alpha = int(alpha) + out = alpha * torch.mv(mat1, vec) + if beta == 0: + return out + if out.numel() == 0: # handle empty matrix + return beta * self + return out + beta * self + + +@register_decomposition(aten.native_group_norm_backward.default) +@pw_cast_for_opmath +def native_group_norm_backward( + grad_output: Tensor, + input: Tensor, + mean: Tensor, + rstd: Tensor, + gamma: Optional[Tensor], + N: int, + C: int, + HxW: int, + group: int, + output_mask: list[bool], +) -> tuple[Optional[Tensor], Optional[Tensor], Optional[Tensor]]: + utils.check_same_device( + grad_output, input, mean, rstd, allow_cpu_scalar_tensors=False + ) + utils.check_same_shape(input, grad_output, allow_cpu_scalar_tensors=False) + utils.check_same_shape(mean, rstd, allow_cpu_scalar_tensors=False) + torch._check( + input.numel() == N * C * HxW, + lambda: f"Expect input to have {N * C * HxW} elements", + ) + torch._check( + mean.shape == (N, group), + lambda: f"Expect mean to have shape ({N}, {group}, but got {mean.shape}", + ) + torch._check( + gamma is None or gamma.numel() == C, + lambda: f"Expect gamma to have {C} elements but got {gamma.numel() if gamma is not None else -1}", + ) + + cpg = C // group + torch._check( + C == cpg * group, + lambda: f"Expect number of channels {C} to be evenly-divisible by number of groups {group}", + ) + + # Compute Internal gradients + ds = torch.mul(grad_output, input).view(N, C, HxW).sum(dim=[2]) + db = grad_output.view(N, C, HxW).sum(dim=[2]) + + d_input: Optional[Tensor] = None + d_gamma: Optional[Tensor] = None + d_bias: Optional[Tensor] = None + if output_mask[0]: + s = 1.0 / (HxW * cpg) + if gamma is not None: + ds_val = torch.mul(ds, gamma.unsqueeze(0)).reshape(N, group, cpg).sum(2) + db_val = torch.mul(db, gamma.unsqueeze(0)).reshape(N, group, cpg).sum(2) + c1 = torch.mul( + rstd.unsqueeze(-1), + gamma.reshape(1, group, cpg), + ) + else: + ds_val = ds.reshape(N, group, cpg).sum(2) + db_val = db.reshape(N, group, cpg).sum(2) + c1 = torch.mul( + rstd.unsqueeze(-1), + torch.ones((1, group, cpg), device=rstd.device), + ) + c2 = (db_val * mean - ds_val) * rstd * rstd * rstd * s + c3 = -c2 * mean - db_val * rstd * s + + c1 = c1.unsqueeze(-1) + c2 = _unsqueeze_to_dim(c2, 4) + c3 = _unsqueeze_to_dim(c3, 4) + d_input = ( + torch.mul(grad_output.reshape(N, group, cpg, HxW), c1) + + torch.mul(input.reshape(N, group, cpg, HxW), c2) + + c3 + ) + d_input = d_input.reshape(input.shape).to(input.dtype) + if output_mask[1]: + d_gamma = ( + ( + (ds.view(N, group, cpg) - db.view(N, group, cpg) * mean.unsqueeze(-1)) + * rstd.unsqueeze(-1) + ) + .sum(dim=[0]) + .reshape(C) + ) + if output_mask[2]: + d_bias = db.sum(dim=[0]) + + return (d_input, d_gamma, d_bias) + + +# out_wrapper currently does not allow optional outputs +@register_decomposition(aten.native_group_norm_backward.out) +def native_group_norm_backward_out( + grad_output: Tensor, + input: Tensor, + mean: Tensor, + rstd: Tensor, + gamma: Optional[Tensor], + N: int, + C: int, + HxW: int, + group: int, + output_mask: list[bool], + *, + out0: torch.Tensor, + out1: torch.Tensor, + out2: torch.Tensor, +) -> tuple[Optional[Tensor], Optional[Tensor], Optional[Tensor]]: + result = native_group_norm_backward( + grad_output, input, mean, rstd, gamma, N, C, HxW, group, output_mask + ) + grad_input = (out0, out1, out2) + for i, r in enumerate(result): + if r is not None: + _maybe_resize_out(grad_input[i], r.shape) + _safe_copy_out(copy_from=r, copy_to=grad_input[i], exact_dtype=True) + + return grad_input + + +def _maybe_cast(x: Optional[Tensor], dtype) -> Optional[Tensor]: + if x is not None: + return x.to(dtype) + return x + + +# TODO: Take a closer look at the type promotion semantics +@register_decomposition(aten.native_layer_norm_backward.default) +def native_layer_norm_backward( + grad_out: Tensor, + input: Tensor, + normalized_shape: list[int], + mean: Tensor, + rstd: Tensor, + weight: Optional[Tensor], + bias: Optional[Tensor], + output_mask: list[bool], +) -> tuple[Optional[Tensor], Optional[Tensor], Optional[Tensor]]: + input_shape = input.shape + input_ndim = input.dim() + computation_dtype = utils.get_computation_dtype(input.dtype) + grad_out_cast, input_cast, weight_cast, bias_cast = ( + x.to(computation_dtype, memory_format=torch.contiguous_format) + if x is not None + else x + for x in (grad_out, input, weight, bias) + ) + assert grad_out_cast is not None + + axis = input_ndim - len(normalized_shape) + inner_dims = input_shape[axis:] + outer_dims = input_shape[:axis] + inner_dim_indices: list[int] = [] + outer_dim_indices: list[int] = [] + for i in range(input_ndim): + if i >= axis: + inner_dim_indices.append(i) + else: + outer_dim_indices.append(i) + + N = prod(inner_dims) # type: ignore[arg-type] + M = prod(outer_dims) # type: ignore[arg-type] + from torch.fx.experimental.symbolic_shapes import statically_known_true + + if statically_known_true(M == 0) or statically_known_true(N == 0): + return ( + input.new_zeros(input_shape) if output_mask[0] else None, + input.new_zeros(input_shape[axis:]) if output_mask[1] else None, + input.new_zeros(input_shape[axis:]) if output_mask[2] else None, + ) + mean = _unsqueeze_to_dim(mean, input_cast.dim()) # type: ignore[union-attr] + rstd = _unsqueeze_to_dim(rstd, input_cast.dim()) # type: ignore[union-attr] + assert input_cast is not None + x_hat = (input_cast - mean) * rstd + if weight_cast is not None: + grad_x_hat = grad_out_cast * weight_cast + else: + grad_x_hat = grad_out_cast + a = grad_x_hat * N + b = torch.sum(grad_x_hat, inner_dim_indices, True) + c1 = torch.mul(grad_x_hat, x_hat) + c2 = torch.sum(c1, inner_dim_indices, True) + c3 = torch.mul(x_hat, c2) + + inner = a - b - c3 + d_input: Optional[Tensor] = None + d_weight: Optional[Tensor] = None + d_bias: Optional[Tensor] = None + if output_mask[0]: + d_input = (rstd / N) * inner + + if output_mask[1] and weight_cast is not None: + if len(outer_dim_indices) > 0: + d_weight = torch.sum(grad_out_cast * x_hat, outer_dim_indices, False) + else: + d_weight = grad_out_cast * x_hat + + if output_mask[2] and bias_cast is not None: + if len(outer_dim_indices) > 0: + d_bias = torch.sum(grad_out_cast, outer_dim_indices, False) + else: + d_bias = grad_out_cast.clone() + + return ( + _maybe_cast(d_input, input.dtype), + _maybe_cast(d_weight, weight.dtype if weight is not None else None), + _maybe_cast(d_bias, bias.dtype if bias is not None else None), + ) + + +# out_wrapper currently does not allow optional outputs +@register_decomposition(aten.native_layer_norm_backward.out) +def native_layer_norm_backward_out( + grad_out: Tensor, + input: Tensor, + normalized_shape: list[int], + mean: Tensor, + rstd: Tensor, + weight: Optional[Tensor], + bias: Optional[Tensor], + output_mask: list[bool], + *, + out0: torch.Tensor, + out1: torch.Tensor, + out2: torch.Tensor, +) -> tuple[Optional[Tensor], Optional[Tensor], Optional[Tensor]]: + result = native_layer_norm_backward( + grad_out, input, normalized_shape, mean, rstd, weight, bias, output_mask + ) + grad_input = (out0, out1, out2) + for i, r in enumerate(result): + if r is not None: + _maybe_resize_out(grad_input[i], r.shape) + _safe_copy_out(copy_from=r, copy_to=grad_input[i], exact_dtype=True) + + return grad_input + + +@register_decomposition(aten._fused_rms_norm.default) +def _fused_rms_norm( + input: Tensor, + normalized_shape: list[int], + weight: Optional[Tensor], + eps: Optional[float], +) -> tuple[Tensor, Tensor]: + dims_to_reduce: list[int] = [] + for i in range(len(normalized_shape)): + dims_to_reduce.append(input.dim() - i - 1) + + # upcast is needed for fp16 and bf16 + computation_dtype = utils.get_computation_dtype(input.dtype) + upcasted_input = input.to(computation_dtype) + + # computation_dtype would be one of [Double, Float, ComplexFloat, ComplexDouble] + if eps is None: + if computation_dtype in (torch.float32, torch.complex64): + eps_val = torch.finfo(torch.float32).eps + else: + eps_val = torch.finfo(torch.float64).eps + else: + eps_val = eps + + rqrst_input = torch.rsqrt( + # NB: don't inplace here, will violate functional IR invariant + # NB: carefully use the Scalar overload of add to ensure compatibility with the C++ decomp + torch.ops.aten.add.Scalar( + torch.pow(upcasted_input, 2).mean(dim=dims_to_reduce, keepdim=True), eps_val + ) + ) + + upcasted_result = upcasted_input.mul(rqrst_input) + + if weight is not None: + upcasted_result = upcasted_result.mul(weight) + + # NB: nested should be dead here, just here for fidelity + is_nested = input.is_nested or (weight is not None and weight.is_nested) + memory_format = utils.suggest_memory_format(input) + is_channels_last = memory_format in ( + torch.channels_last, + torch.channels_last_3d, + ) + + if not is_nested and not is_channels_last: + upcasted_result = upcasted_result.contiguous() + rqrst_input = rqrst_input.contiguous() + + # Cast normalized result back to original input type + result = upcasted_result.type_as(input) + + return result, rqrst_input + + +@register_decomposition(aten._fused_rms_norm_backward.default) +def _fused_rms_norm_backward( + grad_out: Tensor, + input: Tensor, + normalized_shape: list[int], + rstd: Tensor, + weight: Optional[Tensor], + output_mask: list[bool], +) -> tuple[Optional[Tensor], Optional[Tensor]]: + input_shape = input.shape + input_ndim = input.dim() + computation_dtype = utils.get_computation_dtype(input.dtype) + + grad_out_cast = grad_out.to( + computation_dtype, memory_format=torch.contiguous_format + ) + input_cast = input.to(computation_dtype, memory_format=torch.contiguous_format) + weight_cast = ( + weight.to(computation_dtype, memory_format=torch.contiguous_format) + if weight is not None + else None + ) + assert grad_out_cast is not None + + axis = input_ndim - len(normalized_shape) + inner_dims = input_shape[axis:] + outer_dims = input_shape[:axis] + inner_dim_indices: list[int] = [] + outer_dim_indices: list[int] = [] + for i in range(input_ndim): + if i >= axis: + inner_dim_indices.append(i) + else: + outer_dim_indices.append(i) + + N = prod(inner_dims) # type: ignore[arg-type] + M = prod(outer_dims) # type: ignore[arg-type] + from torch.fx.experimental.symbolic_shapes import guard_or_false + + if guard_or_false(M == 0) or guard_or_false(N == 0): + return ( + input.new_zeros(input_shape) if output_mask[0] else None, + input.new_zeros(input_shape[axis:]) if output_mask[1] else None, + ) + + rstd = _unsqueeze_to_dim(rstd, input_cast.dim()) # type: ignore[union-attr] + if weight_cast is not None: + grad_x_hat = grad_out_cast * weight_cast + else: + grad_x_hat = grad_out_cast + + d_input: Optional[Tensor] = None + d_weight: Optional[Tensor] = None + + x_hat = input_cast * rstd + + if output_mask[0]: + sum_val = torch.sum(x_hat * grad_x_hat, dim=inner_dim_indices, keepdim=True) + d_input = (grad_x_hat - (x_hat / N) * sum_val) * rstd + + if output_mask[1] and weight_cast is not None: + d_weight_full_shape = grad_out_cast * x_hat + if len(outer_dim_indices) > 0: + d_weight = torch.sum( + d_weight_full_shape, dim=outer_dim_indices, keepdim=False + ) + else: + d_weight = d_weight_full_shape + + return ( + _maybe_cast(d_input, input.dtype), + _maybe_cast(d_weight, input.dtype), + ) + + +def native_batch_norm_helper( + input: Tensor, + weight: Optional[Tensor], + bias: Optional[Tensor], + running_mean: Optional[Tensor], + running_var: Optional[Tensor], + training: bool, + momentum: float, + eps: float, + functional: bool, +) -> tuple[Tensor, Tensor, Tensor, Optional[Tensor], Optional[Tensor]]: + reduction_dims = [0] + list(range(2, input.dim())) + computation_dtype = utils.get_computation_dtype(input.dtype) + new_running_mean = running_mean + new_running_var = running_var + if training: + computation_dtype = utils.get_computation_dtype(input.dtype) + input_acc = input.to(dtype=computation_dtype) + biased_var, mean = torch.var_mean( + input_acc, dim=reduction_dims, correction=0, keepdim=True + ) + rstd = torch.rsqrt(biased_var + eps) + + output = (input - mean) * rstd + + save_mean = torch.squeeze(mean, reduction_dims) + save_rstd = torch.squeeze(rstd, reduction_dims) + if running_mean is not None: + new_running_mean = momentum * save_mean + (1 - momentum) * running_mean + if not functional: + running_mean.copy_(new_running_mean) + if running_var is not None: + n = input.numel() / input.shape[1] + # This doesn't strictly match eager's numerics, which accumulates var sum and then directly applies the correction + # But... that would require re-implementing var here, for negligible numerics gain on a tensor whose + # numerics probably don't matter. + squeezed_var = torch.squeeze(biased_var, reduction_dims) + unbiased_var = squeezed_var * (n / (n - 1)) + new_running_var = momentum * unbiased_var + (1 - momentum) * running_var + if not functional: + running_var.copy_(new_running_var) + else: + assert running_mean is not None and running_var is not None + running_mean = running_mean.to(dtype=computation_dtype, copy=True) + new_running_mean = running_mean + running_var = running_var.to(dtype=computation_dtype, copy=True) + new_running_var = running_var + mean = running_mean + invstd = 1 / (torch.sqrt(running_var + eps)) + # Very annoying inconsistency where CPU and CUDA give different shapes + if input.device.type != "cpu": + save_mean = running_mean + save_rstd = invstd + else: + save_mean = input.new_zeros((0,)) + save_rstd = input.new_zeros((0,)) + mean = _unsqueeze_to_dim(mean, input.dim() - 1) + invstd = _unsqueeze_to_dim(invstd, input.dim() - 1) + output = (input - mean) * invstd + + if weight is not None: + weight = weight.flatten() + weight = _unsqueeze_to_dim(weight, input.dim() - 1) + output = output * weight + + if bias is not None: + bias = bias.flatten() + bias = _unsqueeze_to_dim(bias, input.dim() - 1) + output = output + bias + + if input.device.type == "cpu": + save_mean = save_mean.to(dtype=input.dtype) + save_rstd = save_rstd.to(dtype=input.dtype) + return ( + output.to(dtype=input.dtype), + save_mean, + save_rstd, + new_running_mean, + new_running_var, + ) + + +@register_decomposition(aten.native_batch_norm) +@out_wrapper("out", "save_mean", "save_invstd") +def native_batch_norm( + input: Tensor, + weight: Optional[Tensor], + bias: Optional[Tensor], + running_mean: Optional[Tensor], + running_var: Optional[Tensor], + training: bool, + momentum: float, + eps: float, +) -> tuple[Tensor, Tensor, Tensor]: + output, save_mean, save_rstd, _, _ = native_batch_norm_helper( + input, weight, bias, running_mean, running_var, training, momentum, eps, False + ) + return output, save_mean, save_rstd + + +# TODO: this decomposition is NOT here to stay. We would much prefer replacing native_batch_norm +# with our new correctly schema'd _native_batch_norm_legit and its variants, but +# we cannot do that immediately in the C++ because it would be forwards incompatible +# with some mobile use cases. +# +# Since this change is most impactful for aot autograd/functionalization, we simply +# register this decomposition on the Autograd key for the python dispatcher (which is +# currently only used by aot autograd/functionalization and no one else, really). +# In two weeks or so, we should remove this decomposition and phase out the current native_batch_norm +# to be _native_batch_norm_legit and have the right schema (stating that there are input mutations). +@aten.native_batch_norm.default.py_impl(DispatchKey.Autograd) +@aten.native_batch_norm.default.py_impl(DispatchKey.CompositeImplicitAutograd) +def native_batch_norm_decomposition( + input: Tensor, + weight: Optional[Tensor], + bias: Optional[Tensor], + running_mean: Optional[Tensor], + running_var: Optional[Tensor], + training: bool, + momentum: float, + eps: float, +) -> tuple[Tensor, Tensor, Tensor]: + if running_mean is None and running_var is None: + return aten._native_batch_norm_legit( + input, weight, bias, training, momentum, eps + ) + if running_mean is None: + raise RuntimeError( + "running_mean is None, but running_var is provided. " + "They should both be None or both be provided." + ) + if running_var is None: + raise RuntimeError( + "running_var is None, but running_mean is provided. " + "They should both be None or both be provided." + ) + if training: + # HACK: batch norm consolidation should clean this up so this op doesn't take in a training arg. + return aten._native_batch_norm_legit( + input, weight, bias, running_mean, running_var, training, momentum, eps + ) + else: + return aten._native_batch_norm_legit_no_training( + input, weight, bias, running_mean, running_var, momentum, eps + ) + + +@aten.unsafe_chunk.default.py_impl(DispatchKey.CompositeImplicitAutograd) +def unsafe_chunk_py_impl(tensor, chunks, dim=0) -> list[Tensor]: + dim_size = tensor.size(dim) + split_size = (dim_size + chunks - 1) // chunks + + if split_size == 0 and dim_size == 0: + split_sizes = [split_size for _ in chunks] + split_sizes[chunks - 1] = split_size - (split_size * chunks - dim_size) + return torch.ops.aten.unsafe_split_with_sizes.default(tensor, split_sizes, dim) + return torch.ops.aten.unsafe_split.Tensor(tensor, split_size, dim) + + +@register_decomposition(aten._native_batch_norm_legit_no_training.default) +def _native_batch_norm_legit_no_training( + input: Tensor, + weight: Optional[Tensor], + bias: Optional[Tensor], + running_mean: Tensor, + running_var: Tensor, + momentum: float, + eps: float, +) -> tuple[Tensor, Tensor, Tensor]: + return aten._native_batch_norm_legit.default( + input, + weight, + bias, + running_mean, + running_var, + False, # training + momentum, + eps, + ) + + +@register_decomposition(aten._native_batch_norm_legit.default) +def _native_batch_norm_legit( + input: Tensor, + weight: Optional[Tensor], + bias: Optional[Tensor], + running_mean: Tensor, + running_var: Tensor, + training: bool, + momentum: float, + eps: float, +) -> tuple[Tensor, Tensor, Tensor]: + output, save_mean, save_rstd, _, _ = native_batch_norm_helper( + input, weight, bias, running_mean, running_var, training, momentum, eps, False + ) + return output, save_mean, save_rstd + + +@register_decomposition(aten._native_batch_norm_legit.no_stats) +def _native_batch_norm_legit_no_stats( + input: Tensor, + weight: Optional[Tensor], + bias: Optional[Tensor], + training: bool, + momentum: float, + eps: float, +) -> tuple[Tensor, Tensor, Tensor]: + output, save_mean, save_rstd, _, _ = native_batch_norm_helper( + input, weight, bias, None, None, training, momentum, eps, False + ) + return output, save_mean, save_rstd + + +@register_decomposition(aten._native_batch_norm_legit_functional.default) +def _native_batch_norm_legit_functional( + input: Tensor, + weight: Optional[Tensor], + bias: Optional[Tensor], + running_mean: Tensor, + running_var: Tensor, + training: bool, + momentum: float, + eps: float, +) -> tuple[Tensor, Tensor, Tensor, Tensor, Tensor]: + ( + output, + save_mean, + save_rstd, + new_running_mean, + new_running_var, + ) = native_batch_norm_helper( + input, weight, bias, running_mean, running_var, training, momentum, eps, True + ) + assert new_running_mean is not None, "new_running_mean should not be None" + assert new_running_var is not None, "new_running_var should not be None" + return output, save_mean, save_rstd, new_running_mean, new_running_var + + +def _get_batch_norm_reserve_tensor( + input: Tensor, + weight: Optional[Tensor], + bias: Optional[Tensor], + running_mean: Tensor, + running_var: Tensor, + eps: float, + training: bool, +) -> Tensor: + """ + Return a reserve tensor for batch norm, used only by cudnn to pass forward state to the + backward pass. This is needed for `_batch_norm_with_update` and `_batch_norm_no_update`, + which support a variety of backends including cudnn. We create this tensor here to get + the correct shape in the traced graph if we detect that will call the cudnn kernel, + and rely on DCE to avoid materializing this tensor. + """ + backend = torch._C._select_batch_norm_backend( # type: ignore[attr-defined] + input, weight, bias, running_mean, running_var, True, eps + ) + reserve_size = 0 + if backend == torch._C._BatchNormBackend.Cudnn: # type: ignore[attr-defined] + reserve_size = torch._C._get_cudnn_batch_norm_reserve_space_size( # type: ignore[attr-defined] + input, training + ) + return torch.empty( + reserve_size, dtype=torch.uint8, layout=input.layout, device=input.device + ) + + +@register_decomposition(aten._batch_norm_with_update.default) +def _batch_norm_with_update( + input: Tensor, + weight: Optional[Tensor], + bias: Optional[Tensor], + running_mean: Tensor, + running_var: Tensor, + momentum: float, + eps: float, +) -> tuple[Tensor, Tensor, Tensor, Tensor]: + output, save_mean, save_rstd, _, _ = native_batch_norm_helper( + input, + weight, + bias, + running_mean, + running_var, + True, # training + momentum, + eps, + False, # functional + ) + reserve = _get_batch_norm_reserve_tensor( + input, weight, bias, running_mean, running_var, eps, training=True + ) + return output, save_mean, save_rstd, reserve + + +@register_decomposition(aten._batch_norm_with_update_functional.default) +def _batch_norm_with_update_functional( + input: Tensor, + weight: Optional[Tensor], + bias: Optional[Tensor], + running_mean: Tensor, + running_var: Tensor, + momentum: float, + eps: float, +) -> tuple[Tensor, Tensor, Tensor, Tensor, Tensor, Tensor]: + ( + output, + save_mean, + save_rstd, + new_rm, + new_rv, + ) = native_batch_norm_helper( + input, weight, bias, running_mean, running_var, True, momentum, eps, True + ) + reserve = _get_batch_norm_reserve_tensor( + input, weight, bias, running_mean, running_var, eps, training=True + ) + assert new_rm is not None, "new_running_mean should not be None" + assert new_rv is not None, "new_running_var should not be None" + return (output, save_mean, save_rstd, reserve, new_rm, new_rv) + + +@register_decomposition(aten._batch_norm_no_update.default) +def _batch_norm_no_update( + input: Tensor, + weight: Optional[Tensor], + bias: Optional[Tensor], + running_mean: Tensor, + running_var: Tensor, + momentum: float, + eps: float, +) -> tuple[Tensor, Tensor, Tensor, Tensor]: + output, save_mean, save_rstd, _, _ = native_batch_norm_helper( + input, + weight, + bias, + running_mean, + running_var, + False, # training + momentum, + eps, + False, # functional + ) + reserve = _get_batch_norm_reserve_tensor( + input, weight, bias, running_mean, running_var, eps, training=False + ) + return output, save_mean, save_rstd, reserve + + +@register_decomposition(aten._fused_dropout) +@out_wrapper("out0", "out1") +@pw_cast_for_opmath +def _fused_dropout_decomposition(input, p, generator=None): + assert generator is None + mask = (torch.rand_like(input) < p).to(dtype=torch.uint8) + res = mask.type_as(input) * input * (1.0 / p) + return (res, mask) + + +@register_decomposition(aten._to_copy) +@out_wrapper() +def _to_copy( + x: Union[Tensor, NumberType], + *, + dtype: Optional[torch.dtype] = None, + layout=None, + device: Optional[torch.device] = None, + pin_memory: bool = False, + non_blocking: bool = False, + memory_format: Optional[torch.memory_format] = None, +): + assert not layout or layout == torch.strided, "TODO" + assert not pin_memory, "TODO" + assert isinstance(x, (torch.Tensor, int, float, bool, complex)) + if device is None and dtype is None and memory_format is None: + if isinstance(x, torch.Tensor): + return x.clone() + else: + return x + dtype_converted = False + + if isinstance(x, torch.Tensor): + x_tensor = x + else: + x_tensor = torch.scalar_tensor(x) + + if device is not None and device != x_tensor.device: + # avoid conversions on cpu + if dtype is not None and device.type == "cpu": + x_tensor = torch._prims.convert_element_type(x_tensor, dtype) + dtype_converted = True + x_tensor = torch._prims.device_put(x_tensor, device, non_blocking) + + if dtype is not None and not dtype_converted: + x_tensor = torch._prims.convert_element_type(x_tensor, dtype) + dtype_converted = True + + if memory_format is not None: # no ref/prim for memory format + return torch.clone(x_tensor, memory_format=memory_format) + return x_tensor + + +# Questionable decompositions +# This is only valid if we're running the graph without autograd, such as if the backward pass has been traced. +# Note that this decomposition causes issues with in-place ops +@register_decomposition([aten.detach, aten.lift, aten.lift_fresh]) +@out_wrapper() +def nop_decomposition(x): + return aten.alias(x) + + +# Also register to the Autograd dispatch key, so this decomp can run above autograd. +# native_batch_norm needs to decompose into other ops before autograd. +@aten.cudnn_batch_norm.default.py_impl(DispatchKey.Autograd) +@register_decomposition(aten.cudnn_batch_norm) +@out_wrapper("out0", "out1", "out2", "out3") +def cudnn_batch_norm( + input: Tensor, + weight: Tensor, + bias: Optional[Tensor], + running_mean: Optional[Tensor], + running_var: Optional[Tensor], + training: bool, + exponential_average_factor: float, + epsilon: float, +): + a, b, c = aten.native_batch_norm( + input, + weight, + bias, + running_mean, + running_var, + training, + exponential_average_factor, + epsilon, + ) + # Cudnn return running mean and variance when training is True + if training: + return (a, b, c, input.new_zeros((0,), dtype=torch.uint8)) + return ( + a, + weight.new_zeros((0,)), + weight.new_zeros((0,)), + input.new_zeros((0,), dtype=torch.uint8), + ) + + +def _broadcast_batch_norm_backward(x, broadcast_mask): + for axis, mask in enumerate(broadcast_mask): + if mask == 1 and not (axis < x.ndim and x.shape[axis] == mask): + x = x.unsqueeze(axis) + return x + + +@register_decomposition(aten.batch_norm_backward.default) +def batch_norm_backward( + grad_out: Tensor, + input: Tensor, + weight: Optional[Tensor], + running_mean: Optional[Tensor], + running_var: Optional[Tensor], + save_mean: Optional[Tensor], + save_invstd: Optional[Tensor], + train: bool, + eps: float, + output_mask: list[bool], + reserve: Tensor, +) -> tuple[Tensor, Optional[Tensor], Optional[Tensor]]: + return native_batch_norm_backward( + grad_out, + input, + weight, + running_mean, + running_var, + save_mean, + save_invstd, + train, + eps, + output_mask, + ) + + +@register_decomposition(aten.native_batch_norm_backward.default) +def native_batch_norm_backward( + grad_out: Tensor, + input: Tensor, + weight: Optional[Tensor], + running_mean: Optional[Tensor], + running_var: Optional[Tensor], + save_mean: Optional[Tensor], + save_invstd: Optional[Tensor], + train: bool, + eps: float, + output_mask: list[bool], +) -> tuple[Tensor, Optional[Tensor], Optional[Tensor]]: + input_dtype = input.dtype + if weight is not None: + weight_dtype = weight.dtype + else: + weight_dtype = input_dtype + computation_dtype = utils.get_computation_dtype(input.dtype) + ( + grad_out_cast, + input_cast, + weight_cast, + running_mean_cast, + running_var_cast, + save_mean_cast, + save_invstd_cast, + ) = ( + x.to(computation_dtype) if x is not None else x + for x in ( + grad_out, + input, + weight, + running_mean, + running_var, + save_mean, + save_invstd, + ) + ) + input_shape = input.shape + input_rank = input.dim() + assert input_rank >= 2, "rank of the input must be at least 2" + + axis = 1 + num_features = prod(list(input_shape)) / input_shape[axis] + mean = save_mean_cast + invstd = save_invstd_cast + if train: + assert mean is not None and invstd is not None + + else: + assert running_mean_cast is not None and running_var_cast is not None + mean = running_mean_cast + invstd = torch.rsqrt(running_var_cast + eps) + + broadcast_mask: list[int] = [1] * input_rank + broadcast_mask[axis] = input_shape[axis] + + reduction_axes: list[int] = [] + for i in range(input_rank): + if i != axis: + reduction_axes.append(i) + + mean = _broadcast_batch_norm_backward(mean, broadcast_mask) # type: ignore[arg-type] + norm = 1.0 / num_features + grad_output_sum = torch.sum(grad_out_cast, reduction_axes) # type: ignore[arg-type] + dot_p = torch.sum(grad_out_cast * (input_cast - mean), reduction_axes) # type: ignore[operator] + + grad_mean = _broadcast_batch_norm_backward(grad_output_sum * norm, broadcast_mask) + proj_scale = _broadcast_batch_norm_backward( + torch.mul(dot_p * norm, invstd * invstd), # type: ignore[operator] + broadcast_mask, + ) + + if weight_cast is None: + grad_scale = _broadcast_batch_norm_backward(invstd, broadcast_mask) * 1.0 # type: ignore[arg-type] + else: + grad_scale = _broadcast_batch_norm_backward( + invstd * weight_cast, broadcast_mask + ) + + if train: + proj = (input_cast - mean) * proj_scale # type: ignore[operator] + grad_input = ((grad_out_cast - proj) - grad_mean) * grad_scale + else: + grad_input = grad_out_cast * grad_scale + + if output_mask[1]: + grad_weight = dot_p * invstd + else: + grad_weight = None # "None" doesn't work with vjp, should use zeros for vjp + + if output_mask[2]: + grad_bias = grad_output_sum + else: + grad_bias = None # "None" doesn't work with vjp, should use zeros for vjp + + return ( + grad_input.to(input_dtype), + _maybe_cast(grad_weight, weight_dtype), + _maybe_cast(grad_bias, weight_dtype), + ) + + +# out_wrapper currently does not allow optional outputs +@register_decomposition(aten.native_batch_norm_backward.out) +def native_batch_norm_backward_out( + grad_out: Tensor, + input: Tensor, + weight: Optional[Tensor], + running_mean: Optional[Tensor], + running_var: Optional[Tensor], + save_mean: Optional[Tensor], + save_invstd: Optional[Tensor], + train: bool, + eps: float, + output_mask: list[bool], + *, + out0: torch.Tensor, + out1: torch.Tensor, + out2: torch.Tensor, +) -> tuple[Tensor, Optional[Tensor], Optional[Tensor]]: + result = native_batch_norm_backward( + grad_out, + input, + weight, + running_mean, + running_var, + save_mean, + save_invstd, + train, + eps, + output_mask, + ) + grad_input = (out0, out1, out2) + for i, r in enumerate(result): + if r is not None: + _maybe_resize_out(grad_input[i], r.shape) + _safe_copy_out(copy_from=r, copy_to=grad_input[i], exact_dtype=True) + + return grad_input + + +@register_decomposition(aten.miopen_batch_norm_backward) +@out_wrapper("out0", "out1", "out2") +def miopen_batch_norm_backward( + input: Tensor, + grad_output: Tensor, + weight: Tensor, + running_mean: Optional[Tensor], + running_var: Optional[Tensor], + save_mean: Optional[Tensor], + save_var: Optional[Tensor], + epsilon: float, +): + return aten.native_batch_norm_backward( + grad_output, + input, + weight, + running_mean, + running_var, + save_mean, + save_var, + True, + epsilon, + [True, True, True], + ) + + +@register_decomposition(aten.cudnn_batch_norm_backward) +@out_wrapper("out0", "out1", "out2") +def cudnn_batch_norm_backward( + input: Tensor, + grad_output: Tensor, + weight: Tensor, + running_mean: Optional[Tensor], + running_var: Optional[Tensor], + save_mean: Optional[Tensor], + save_var: Optional[Tensor], + epsilon: float, + reserveSpace: Tensor, +): + return aten.native_batch_norm_backward( + grad_output, + input, + weight, + running_mean, + running_var, + save_mean, + save_var, + True, + epsilon, + [True, True, True], + ) + + +@register_decomposition(aten._adaptive_avg_pool2d) +@out_wrapper() +@pw_cast_for_opmath +def adaptive_avg_pool2d(input: Tensor, output_size: tuple[int, int]): + # Preconditions + device = input.device + shape = input.shape + ndim = len(shape) + torch._check( + ndim in (3, 4), + lambda: f"adaptive_avg_pool2d(): Expected 3D or 4D tensor, but got {ndim}", + ) + for d in input.shape[-2:]: + torch._check( + d != 0, + lambda: "adaptive_avg_pool2d(): Expected input to have non-zero size for " + f"non-batch dimensions, but input has shape {tuple(shape)}.", + ) + + # Optimisation (we should also do this in the kernel implementation) + if shape[-2] % output_size[-2] == 0 and shape[-1] % output_size[-1] == 0: + stride = tuple(i // o for i, o in zip(shape[-2:], output_size)) + kernel = tuple( + i - (o - 1) * s for i, o, s in zip(shape[-2:], output_size, stride) + ) + return torch.nn.functional.avg_pool2d(input, kernel, stride) + + def start_index(a, b, c): + return torch.div(a * c, b, rounding_mode="trunc") + + def end_index(a, b, c): + return torch.div((a + 1) * c + b - 1, b, rounding_mode="trunc") + + def compute_idx(in_size, out_size): + orange = torch.arange(out_size, device=device, dtype=torch.int64) + i0 = start_index(orange, out_size, in_size) + # Let length = end_index - start_index, i.e. the length of the pooling kernels + # length.max() can be computed analytically as follows: + maxlength = in_size // out_size + 1 + in_size_mod = in_size % out_size + # adaptive = True iff there are kernels with different lengths + adaptive = not (in_size_mod == 0 or out_size % in_size_mod == 0) + if adaptive: + maxlength += 1 + elif in_size_mod == 0: + maxlength -= 1 + + range_max = torch.arange(maxlength, device=device, dtype=torch.int64) + idx = i0.unsqueeze(-1) + range_max + if adaptive: + # Need to clamp to avoid accessing out-of-bounds memory + # TODO make minimum accept scalars + maxval = torch.scalar_tensor( + in_size - 1, dtype=idx.dtype, device=idx.device + ) + idx = torch.minimum(idx, maxval) + + # Compute the length + i1 = end_index(orange, out_size, in_size) + length = i1 - i0 + else: + length = maxlength + return idx, length, range_max, adaptive + + # length is not None if it's constant, otherwise we'll need to compute it + idxh, length_h, range_max_h, adaptive_h = compute_idx(shape[-2], output_size[-2]) + idxw, length_w, range_max_w, adaptive_w = compute_idx(shape[-1], output_size[-1]) + + vals = input[..., _unsqueeze_to_dim(idxh, 4), idxw] + # Shortcut for the simpler case + if not adaptive_h and not adaptive_w: + return torch.mean(vals, dim=(-3, -1)) + + def maybe_mask(vals, length, range_max, adaptive, dim): + if isinstance(length, IntLike): + return vals, length + else: + # zero-out the things we didn't really want to select + assert dim < 0 + # hack + mask = range_max >= length.unsqueeze(-1) + if dim == -2: + mask = _unsqueeze_to_dim(mask, 4) + vals = torch.masked_fill(vals, mask, 0.0) + # Compute the length of each window + length = _unsqueeze_to_dim(length, -dim) + return vals, length + + vals, length_h = maybe_mask( + vals, length_h, range_max_h, adaptive=adaptive_h, dim=-2 + ) + vals, length_w = maybe_mask( + vals, length_w, range_max_w, adaptive=adaptive_w, dim=-1 + ) + + # We unroll the sum as we assume that the kernels are going to be small + ret = None + for i, j in product(range(vals.shape[-3]), range(vals.shape[-1])): + if ret is None: + ret = vals[..., i, :, j] + else: + ret = ret + vals[..., i, :, j] + return ret / (length_h * length_w) + + +def _max_unpoolnd( + self: TensorLike, indices: TensorLike, output_size: list[int], dim: int +): + # If the input tensors self and indices came from max_pool call as + # required by the documentation, this operation is deterministic + # because that ensures that if there are two entries in `indices` + # tensor that are equal, the corresponding values in `self` are also + # equal. If this condition is not satisfied, the operation is + # non-deterministic as one of the different values in `self` 'wins'. + utils.alert_not_deterministic(f"max_unpooling{dim}d_forward_out") + nc = reduce(operator.mul, self.shape[:-dim]) + hw = reduce(operator.mul, output_size) + indices_nc_shape = [1] * self.ndim + indices_nc_shape[:-dim] = self.shape[:-dim] + indices_flat = ( + indices + aten.arange(nc, device=self.device).view(indices_nc_shape) * hw + ).reshape(-1) + + output = self.new_zeros(list(self.shape[:-dim]) + list(output_size)) + return aten._unsafe_index_put( + output.reshape(-1), [indices_flat], self.reshape(-1), accumulate=False + ).view(output.shape) + + +@register_decomposition(aten.max_unpool2d) +@out_wrapper() +def max_unpool2d( + self: TensorLike, + indices: TensorLike, + output_size: list[int], +): + torch._check( + indices.dtype == torch.int64, + lambda: f"elements in indices should be type int64 but got: {indices.dtype}", + ) + torch._check( + len(output_size) == 2, + lambda: ( + f"There should be exactly two elements (height, width) in output_size, " + f"but got {len(output_size)} elements." + ), + ) + + torch._check( + self.ndim in (3, 4), + lambda: ( + f"Input to max_unpooling2d should be a 3d or 4d Tensor, " + f"but got a tensor with {self.ndim} dimensions." + ), + ) + torch._check( + self.shape == indices.shape, + lambda: ( + f"Expected shape of indices to be same as that of the input tensor ({self.shape}) " + f"but got indices tensor with shape: {indices.shape}" + ), + ) + + for i in range(1, self.ndim): + torch._check( + self.size(i) > 0, + lambda: ( + f"max_unpooling2d(): " + f"Expected input to have non-zero size for non-batch dimensions, " + f"but got {self.shape} with dimension {i} being empty." + ), + ) + + return _max_unpoolnd(self, indices, output_size, 2) + + +@register_decomposition(aten.max_unpool3d) +@out_wrapper() +def max_unpool3d( + input: TensorLike, + indices: TensorLike, + output_size: list[int], + stride: list[int], + padding: list[int], +): + torch._check( + indices.dtype == torch.int64, lambda: "elements in indices should be type int64" + ) + torch._check( + input.ndim in (4, 5), + lambda: f"Input to max_unpooling3d should be a 4d or 5d Tensor, but got a tensor with {input.ndim} dimensions.", + ) + torch._check( + len(output_size) == 3, + lambda: ( + f"There should be exactly three elements (depth, height, width) in output_size, " + f"but got {len(output_size)} elements." + ), + ) + torch._check( + len(stride) == 3, + lambda: f"There should be exactly three elements (depth, height, width) in stride, but got: {len(stride)} elements.", + ) + torch._check( + len(padding) == 3, + lambda: f"There should be exactly three elements (depth, height, width) in padding, but got: {len(padding)} elements.", + ) + torch._check( + input.shape == indices.shape, + lambda: ( + f"Expected shape of indices to be same as that of the input tensor ({input.shape}) " + f"but got indices tensor with shape: {indices.shape}" + ), + ) + + for i in range(1, input.ndim): + torch._check( + input.size(i) > 0, + lambda: ( + f"max_unpooling3d(): " + f"Expected input to have non-zero size for non-batch dimensions, " + f"but got {input.shape} with dimension {i} being empty." + ), + ) + + torch._check( + stride[0] > 0 and stride[1] > 0 and stride[2] > 0, + lambda: f"strides should be greater than zero, but got stride: {stride}", + ) + + return _max_unpoolnd(input, indices, output_size, 3) + + +@register_decomposition(aten.index_add_) +def index_add_( + x: TensorLike, + dim: int, + index: TensorLike, + tensor: TensorLike, + *, + alpha: NumberType = 1, +): + return _index_add(x, dim, index, tensor, inplace=True, alpha=alpha) + + +@register_decomposition(aten.index_add) +@out_wrapper() +def index_add( + x: TensorLike, + dim: int, + index: TensorLike, + tensor: TensorLike, + *, + alpha: NumberType = 1, +): + return _index_add(x, dim, index, tensor, inplace=False, alpha=alpha) + + +def _index_add( + x: TensorLike, + dim: int, + index: TensorLike, + tensor: TensorLike, + *, + inplace: bool, + alpha: NumberType = 1, +): + dim = utils.canonicalize_dims(x.ndim, dim) + torch._check( + index.ndim <= 1, + lambda: f"Index should have dimension 1 or 0 (got {index.ndim})", + ) + index_size = index.size(0) if index.ndim == 1 else 1 + tensor_size = tensor.size(dim) if tensor.ndim > 0 else 1 + torch._check( + tensor_size == index_size, + lambda: f"Number of indices ({index_size}) should be equal to tensor.size(dim) ({tensor_size}), for {dim=}", + ) + if alpha != 1: + python_type = utils.dtype_to_type(x.dtype) + torch._check( + python_type is bool + or utils.is_weakly_lesser_type(type(alpha), python_type), + lambda: f"alpha argument of type {type(alpha)} cannot be safely cast to type {python_type}!", + ) + tensor = tensor * alpha + # Treat scalars as elements of \R^1 + zero_dim = x.ndim == 0 + x1 = x.unsqueeze(0) if zero_dim else x + idx = (None,) * dim + (index,) + index_put = aten.index_put_ if inplace else aten.index_put + out = index_put(x1, idx, tensor, accumulate=True) + if inplace: + return x + else: + return out.squeeze(0) if zero_dim else out.contiguous() + + +@register_decomposition(aten.pad_sequence.default) +@aten.pad_sequence.default.py_impl(DispatchKey.CompositeImplicitAutograd) +def pad_sequence(sequences, batch_first=False, padding_value=0.0): + torch._check(len(sequences) > 0, lambda: "received an empty list of sequences") + sequences_size = len(sequences) + max_size = sequences[0].size() + trailing_dims = max_size[1:] + max_len = max(x.size(0) for x in sequences) + if batch_first: + out_dims = (sequences_size, max_len) + else: + out_dims = (max_len, sequences_size) + out_dims = out_dims + trailing_dims + out = sequences[0].new_full(out_dims, padding_value) + dim_paddings = (0, 0) * len(trailing_dims) + for i in range(sequences_size): + currseq = sequences[i] + row = aten.constant_pad_nd( + currseq, dim_paddings + (0, max_len - currseq.size(0)), padding_value + ) + if batch_first: + out = aten.select_scatter(out, row, dim=0, index=i) + else: + out = aten.select_scatter(out, row, dim=1, index=i) + return out + + +@register_decomposition(aten.index_copy_) +def index_copy_(x: TensorLike, dim: int, index: TensorLike, tensor: TensorLike): + return _index_copy(x, dim, index, tensor, inplace=True) + + +@register_decomposition(aten.index_copy) +@out_wrapper() +def index_copy(x: TensorLike, dim: int, index: TensorLike, tensor: TensorLike): + return _index_copy(x, dim, index, tensor, inplace=False) + + +def _index_copy( + x: TensorLike, dim: int, index: TensorLike, tensor: TensorLike, *, inplace: bool +): + dim = utils.canonicalize_dims(x.ndim, dim) + torch._check( + index.ndim <= 1, + lambda: f"Index should have dimension 1 or 0 (got {index.ndim})", + ) + # Treat scalars as elements of \R^1 + zero_dim = x.ndim == 0 + x1 = x.unsqueeze(0) if zero_dim else x + index = index.unsqueeze(0) if index.ndim == 0 else index + idx = (None,) * dim + (index,) + index_put = aten.index_put_ if inplace else aten.index_put + out = index_put(x1, idx, tensor) + if inplace: + return x + else: + return out.squeeze(0) if zero_dim else out.contiguous() + + +# nb: Should use acc_t, not op_math +@register_decomposition(aten.log_sigmoid_forward) +@out_wrapper("output", "buffer") +@pw_cast_for_opmath +def log_sigmoid_forward(self: Tensor) -> tuple[Tensor, Tensor]: + min = torch.minimum(self.new_zeros(()), self) + z = torch.exp(-torch.abs(self)) + if self.is_cuda or self.is_xpu: + buffer = self.new_zeros((0,)) + else: + buffer = z + return min - torch.log1p(z), buffer + + +@register_decomposition(aten.uniform) +@out_wrapper() +def uniform( + x: Tensor, + low: Union[bool, int, float] = 0.0, + high: Union[bool, int, float] = 1.0, + generator: Optional[torch.Generator] = None, +): + return prims._uniform_helper( + x.shape, + low=sym_float(low), + high=sym_float(high), + dtype=x.dtype, + device=x.device, + generator=generator, + ) + + +@register_decomposition(aten.uniform_) +def uniform_(self, low=0, high=1, generator=None): + return self.copy_(uniform(self, low, high, generator)) + + +# aten/src/ATen/native/UpSample.cpp compute_output_size +def upsample_compute_output_size(input_size, output_size, scale_factors): + spatial_dimensions = len(input_size) - 2 + if output_size is not None: + torch._check( + scale_factors is None, + lambda: "Must specify exactly one of output_size and scale_factors", + ) + torch._check(len(output_size) == spatial_dimensions, lambda: "") + return output_size + if scale_factors is not None: + # NB: this isn't necessary lol + torch._check( + output_size is None, + lambda: "Must specify exactly one of output_size and scale_factors", + ) + torch._check(len(scale_factors) == spatial_dimensions, lambda: "") + output_size = [] + for i, s in enumerate(scale_factors): + if int(s) == s: + output_size.append(input_size[i + 2] * int(s)) + else: + output_size.append(sym_int(input_size[i + 2] * s)) + return output_size + torch._check( + False, lambda: "Must specify exactly one of output_size and scale_factors" + ) + + +def get_scale_value(scales, idx): + if scales is None: + return None + return scales[idx] + + +@register_decomposition(aten.upsample_nearest1d.vec) +@register_decomposition(aten.upsample_nearest2d.vec) +@register_decomposition(aten.upsample_nearest3d.vec) +@aten.upsample_nearest1d.vec.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.upsample_nearest1d.vec.py_impl(DispatchKey.Autograd) +@aten.upsample_nearest2d.vec.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.upsample_nearest2d.vec.py_impl(DispatchKey.Autograd) +@aten.upsample_nearest3d.vec.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.upsample_nearest3d.vec.py_impl(DispatchKey.Autograd) +def _upsample_nearest_vec( + input: Tensor, + output_size: Optional[list[int]], + scale_factors: Optional[list[float]], +) -> Tensor: + osize = upsample_compute_output_size(input.size(), output_size, scale_factors) + scales = ( + scale_factors if scale_factors else [None] * len(osize) # type: ignore[list-item] + ) + return _upsample_nearest(input, osize, scales) + + +@register_decomposition(aten._upsample_nearest_exact1d.vec) +@register_decomposition(aten._upsample_nearest_exact2d.vec) +@register_decomposition(aten._upsample_nearest_exact3d.vec) +@aten._upsample_nearest_exact1d.vec.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten._upsample_nearest_exact1d.vec.py_impl(DispatchKey.Autograd) +@aten._upsample_nearest_exact2d.vec.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten._upsample_nearest_exact2d.vec.py_impl(DispatchKey.Autograd) +@aten._upsample_nearest_exact3d.vec.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten._upsample_nearest_exact3d.vec.py_impl(DispatchKey.Autograd) +def _upsample_nearest_exact_vec( + input: Tensor, + output_size: Optional[list[int]], + scale_factors: Optional[list[float]], +) -> Tensor: + osize = upsample_compute_output_size(input.size(), output_size, scale_factors) + scales = ( + scale_factors if scale_factors else [None] * len(osize) # type: ignore[list-item] + ) + return _upsample_nearest(input, osize, scales, exact=True) + + +def _compute_upsample_nearest_indices(input, output_size, scales, exact=False): + # For each dim in output_size, compute the set of input indices used + # to produce the upsampled output. + indices = [] + num_spatial_dims = len(output_size) + offset = 0.5 if exact else 0.0 + + for d in range(num_spatial_dims): + # Math matches aten/src/ATen/native/cpu/UpSampleKernel.cpp + # + # Indices are computed as following: + # scale = isize / osize + # Case: exact=False + # input_index = floor(output_index * scale) + # Same as OpenCV INTER_NEAREST + # + # Case: exact=False + # index_f32 = (output_index + 0.5) * scale - 0.5 + # input_index = round(index_f32) + # Same as Pillow and Scikit-Image/Scipy ndi.zoom + osize = output_size[d] + isize = input.shape[-num_spatial_dims + d] + scale = isize / (isize * scales[d]) if scales[d] is not None else isize / osize + + output_indices = torch.arange(osize, dtype=torch.float32, device=input.device) + input_indices = ((output_indices + offset) * scale).to(torch.int64) + for _ in range(num_spatial_dims - 1 - d): + input_indices = input_indices.unsqueeze(-1) + indices.append(input_indices) + return indices + + +@register_decomposition([aten.upsample_nearest1d.default, aten.upsample_nearest1d.out]) +@aten.upsample_nearest1d.default.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.upsample_nearest1d.default.py_impl(DispatchKey.Autograd) +@out_wrapper(preserve_memory_format=True, exact_dtype=True) +def upsample_nearest1d( + input: Tensor, + output_size: list[int], + scales: Optional[float] = None, +) -> Tensor: + return _upsample_nearest(input, output_size, [scales]) + + +@register_decomposition( + [aten._upsample_nearest_exact1d.default, aten._upsample_nearest_exact1d.out] +) +@aten._upsample_nearest_exact1d.default.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten._upsample_nearest_exact1d.default.py_impl(DispatchKey.Autograd) +@out_wrapper(preserve_memory_format=True, exact_dtype=True) +def upsample_nearest_exact1d( + input: Tensor, + output_size: list[int], + scales: Optional[float] = None, +) -> Tensor: + return _upsample_nearest(input, output_size, [scales], exact=True) + + +@register_decomposition([aten.upsample_nearest2d.default, aten.upsample_nearest2d.out]) +@aten.upsample_nearest2d.default.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.upsample_nearest2d.default.py_impl(DispatchKey.Autograd) +@out_wrapper(preserve_memory_format=True, exact_dtype=True) +def upsample_nearest2d( + input: Tensor, + output_size: list[int], + scales_h: Optional[float] = None, + scales_w: Optional[float] = None, +) -> Tensor: + return _upsample_nearest(input, output_size, [scales_h, scales_w]) + + +@register_decomposition( + [aten._upsample_nearest_exact2d.default, aten._upsample_nearest_exact2d.out] +) +@aten._upsample_nearest_exact2d.default.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten._upsample_nearest_exact2d.default.py_impl(DispatchKey.Autograd) +@out_wrapper(preserve_memory_format=True, exact_dtype=True) +def _upsample_nearest_exact2d( + input: Tensor, + output_size: list[int], + scales_h: Optional[float] = None, + scales_w: Optional[float] = None, +) -> Tensor: + return _upsample_nearest(input, output_size, [scales_h, scales_w], exact=True) + + +@register_decomposition([aten.upsample_nearest3d.default, aten.upsample_nearest3d.out]) +@aten.upsample_nearest3d.default.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.upsample_nearest3d.default.py_impl(DispatchKey.Autograd) +@out_wrapper(preserve_memory_format=True, exact_dtype=True) +def upsample_nearest3d( + input: Tensor, + output_size: list[int], + scales_d: Optional[float] = None, + scales_h: Optional[float] = None, + scales_w: Optional[float] = None, +) -> Tensor: + return _upsample_nearest(input, output_size, [scales_d, scales_h, scales_w]) + + +@register_decomposition( + [aten._upsample_nearest_exact3d.default, aten._upsample_nearest_exact3d.out] +) +@aten._upsample_nearest_exact3d.default.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten._upsample_nearest_exact3d.default.py_impl(DispatchKey.Autograd) +@out_wrapper(preserve_memory_format=True, exact_dtype=True) +def _upsample_nearest_exact3d( + input: Tensor, + output_size: list[int], + scales_d: Optional[float] = None, + scales_h: Optional[float] = None, + scales_w: Optional[float] = None, +) -> Tensor: + return _upsample_nearest( + input, output_size, [scales_d, scales_h, scales_w], exact=True + ) + + +@pw_cast_for_opmath +def _upsample_nearest( + input: Tensor, + output_size: list[int], + scales: list[Optional[float]], + exact: bool = False, +) -> Tensor: + spatial_indices = _compute_upsample_nearest_indices( + input, output_size, scales, exact=exact + ) + + indices = [None, None] + spatial_indices + result = aten._unsafe_index(input, indices) + + if result.ndim == 4: + # convert output to correct memory format, if necessary + memory_format = utils.suggest_memory_format(input) + + # following "heuristic: only use channels_last path when it's faster than the contiguous path" + n_channels = input.shape[1] + if input.device.type == "cuda" and n_channels < 4: + memory_format = torch.contiguous_format + + result = result.contiguous(memory_format=memory_format) + return result + + +def gather_params(params, has_biases, has_projections): + if has_biases and has_projections: + group_size = 5 + elif has_biases: + group_size = 4 + elif has_projections: + group_size = 3 + else: + group_size = 2 + + assert len(params) % group_size == 0, len(params) + return [ + tuple(params[i : i + group_size]) for i in range(0, len(params), group_size) + ] + + +def params_hiddens(params, hiddens, i, bidirectional): + if bidirectional: + cur_params, cur_hidden = params[2 * i], hiddens[2 * i] + bidir_params, bidir_hidden = params[2 * i + 1], hiddens[2 * i + 1] + else: + cur_params, cur_hidden = params[i], hiddens[i] + bidir_params, bidir_hidden = None, None + + return cur_params, cur_hidden, bidir_params, bidir_hidden + + +def update_hidden_for_packed(cur_hidden, last_batch_size, batch_size, hiddens): + assert last_batch_size > batch_size + hiddens.append(cur_hidden.narrow(0, batch_size, last_batch_size - batch_size)) + return cur_hidden.narrow(0, 0, batch_size) + + +def update_hidden_for_packed_reverse( + cur_hidden, last_batch_size, batch_size, inp_hidden +): + if last_batch_size == batch_size: + return cur_hidden + assert last_batch_size < batch_size + return torch.concat( + ( + cur_hidden, + inp_hidden.narrow(0, last_batch_size, batch_size - last_batch_size), + ) + ) + + +def one_layer_rnn_data( + inp, hidden, params, has_biases, hidden_fn, batch_sizes, reverse=False +): + ih_weight = params[0] + hh_weight = params[1] + ih_bias = params[2] if has_biases else None + hh_bias = params[3] if has_biases else None + + step_output = [] + hiddens: list[torch.Tensor] = [] + + last_batch_size = batch_sizes[-1] if reverse else batch_sizes[0] + cur_hidden = hidden.narrow(0, 0, last_batch_size) + split_inp = torch.split(inp, list(batch_sizes)) + if reverse: + split_inp = split_inp[::-1] + for inp in split_inp: + i = inp.shape[0] + + if last_batch_size == i: + pass # don't update cur_hidden + # this will only happen when reverse=False, since batch sizes are sorted largest -> smallest + elif reverse: + cur_hidden = update_hidden_for_packed_reverse( + cur_hidden, last_batch_size, i, hidden + ) + else: + cur_hidden = update_hidden_for_packed( + cur_hidden, last_batch_size, i, hiddens + ) + + cur_hidden = hidden_fn(inp, cur_hidden, ih_weight, ih_bias, hh_weight, hh_bias) + last_batch_size = i + step_output.append(cur_hidden) + + if reverse: + step_output.reverse() + else: + hiddens.append(cur_hidden) + hiddens.reverse() + + out = torch.cat(step_output, 0) + hidden_out = torch.cat(hiddens, 0) if not reverse else cur_hidden + return out, hidden_out + + +def rnn_cell(nonlinearity): + def inner(i, cur_hidden, ih_weight, ih_bias, hh_weight, hh_bias): + return nonlinearity(F.linear(cur_hidden, hh_weight, hh_bias) + i) + + return inner + + +def rnn_cell_data(nonlinearity): + def inner(i, cur_hidden, ih_weight, ih_bias, hh_weight, hh_bias): + i = F.linear(i, ih_weight, ih_bias) + return nonlinearity(F.linear(cur_hidden, hh_weight, hh_bias) + i) + + return inner + + +def one_layer_rnn(inp, hidden, params, has_biases, hidden_fn, reverse=False): + ih_weight = params[0] + hh_weight = params[1] + ih_bias = params[2] if has_biases else None + hh_bias = params[3] if has_biases else None + + precomputed_input = F.linear(inp, ih_weight, ih_bias) + precomputed_input = precomputed_input.flip(0) if reverse else precomputed_input + cur_hidden = hidden.unsqueeze(0) + step_output = [] + for i in precomputed_input: + cur_hidden = hidden_fn(i, cur_hidden, ih_weight, ih_bias, hh_weight, hh_bias) + step_output.append(cur_hidden) + + if reverse: + step_output.reverse() + + out = torch.cat(step_output, 0) + + return out, cur_hidden.squeeze(0) + + +def mkldnn_one_layer_lstm(inp, hidden, params, has_biases, reverse=False): + w0 = params[0] + w1 = params[1] + if has_biases: + w2 = params[2] + w3 = params[3] + else: + w2 = torch.zeros(w0.size()) + w3 = torch.zeros(w1.size()) + + hx = hidden[0].unsqueeze(0) + cx = hidden[1].unsqueeze(0) + + batch_sizes: list[int] = [] + mode = 2 # third_party/ideep/include/ideep/abstract_types.hpp: ideep::rnn_kind::LSTM = 2 + hidden_size = hx.size(2) + num_layers = 1 + + # _rnn_helper already handles bidirectional and batch_first so we hard-code them to False here + bidirectional = False + batch_first = False + + train = False + # If batch_first, inp has been permuted in _rnn_helper. Convert to contiguous here. + # Same as aten/src/ATen/native/mkldnn/RNN.cpp: mkldnn_rnn: input = input.contiguous(); + inp = inp.contiguous() + hx = hx.contiguous() + cx = cx.contiguous() + outputs = torch.ops.aten.mkldnn_rnn_layer.default( + inp, + w0, + w1, + w2, + w3, + hx, + cx, + reverse, + batch_sizes, + mode, + hidden_size, + num_layers, + has_biases, + bidirectional, + batch_first, + train, + ) + y, hy, cy = outputs[0], outputs[1], outputs[2] + return y, (hy.squeeze(0), cy.squeeze(0)) + + +def _rnn_helper( + input, + hidden, + params, + has_biases, + num_layers, + dropout, + train, + bidirectional, + batch_first, + layer_fn, +): + input = input.transpose(0, 1) if batch_first else input + final_hiddens = [] + + for i in range(num_layers): + cur_params, cur_hidden, bidir_params, bidir_hidden = params_hiddens( + params, hidden, i, bidirectional + ) + dropout = dropout if (train and num_layers < i - 1) else 0.0 + fwd_inp, fwd_hidden = layer_fn(input, cur_hidden, cur_params, has_biases) + final_hiddens.append(fwd_hidden) + + if bidirectional: + bwd_inp, bwd_hidden = layer_fn( + input, bidir_hidden, bidir_params, has_biases, reverse=True + ) + final_hiddens.append(bwd_hidden) + + if bidirectional: + input = torch.cat([fwd_inp, bwd_inp], fwd_inp.dim() - 1) # type: ignore[possibly-undefined] + else: + input = fwd_inp + + if dropout != 0 and train and i < num_layers - 1: + input = torch.dropout(input, dropout, train=True) + + input = input.transpose(0, 1) if batch_first else input + return input, final_hiddens + + +@register_decomposition(aten.rnn_tanh.input) +@aten.rnn_tanh.input.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.rnn_tanh.input.py_impl(DispatchKey.Autograd) +def rnn_tanh_input( + input, + hx, + params, + has_biases, + num_layers, + dropout, + train, + bidirectional, + batch_first, +): + hidden = hx.unbind(0) + params = gather_params(params, has_biases, False) + out, final_hiddens = _rnn_helper( + input, + hidden, + params, + has_biases, + num_layers, + dropout, + train, + bidirectional, + batch_first, + partial(one_layer_rnn, hidden_fn=rnn_cell(torch.tanh)), + ) + return out, torch.stack(final_hiddens, 0) + + +@register_decomposition(aten.rnn_relu.input) +@aten.rnn_relu.input.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.rnn_relu.input.py_impl(DispatchKey.Autograd) +def rnn_relu_input( + input, + hx, + params, + has_biases, + num_layers, + dropout, + train, + bidirectional, + batch_first, +): + hidden = hx.unbind(0) + params = gather_params(params, has_biases, False) + out, final_hiddens = _rnn_helper( + input, + hidden, + params, + has_biases, + num_layers, + dropout, + train, + bidirectional, + batch_first, + partial(one_layer_rnn, hidden_fn=rnn_cell(torch.relu)), + ) + return out, torch.stack(final_hiddens, 0) + + +@register_decomposition(aten.rnn_relu.data) +@aten.rnn_relu.data.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.rnn_relu.data.py_impl(DispatchKey.Autograd) +def rnn_relu_data( + data, + batch_sizes, + hx, + params, + has_biases, + num_layers, + dropout, + train, + bidirectional, +): + hidden = hx.unbind(0) + params = gather_params(params, has_biases, False) + out, final_hiddens = _rnn_helper( + data, + hidden, + params, + has_biases, + num_layers, + dropout, + train, + bidirectional, + False, + partial( + one_layer_rnn_data, + batch_sizes=batch_sizes, + hidden_fn=rnn_cell_data(torch.relu), + ), + ) + return out, torch.stack(final_hiddens, 0) + + +@register_decomposition(aten.rnn_tanh.data) +@aten.rnn_tanh.data.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.rnn_tanh.data.py_impl(DispatchKey.Autograd) +def rnn_tanh_data( + data, + batch_sizes, + hx, + params, + has_biases, + num_layers, + dropout, + train, + bidirectional, +): + hidden = hx.unbind(0) + params = gather_params(params, has_biases, False) + out, final_hiddens = _rnn_helper( + data, + hidden, + params, + has_biases, + num_layers, + dropout, + train, + bidirectional, + False, + partial( + one_layer_rnn_data, + batch_sizes=batch_sizes, + hidden_fn=rnn_cell_data(torch.tanh), + ), + ) + return out, torch.stack(final_hiddens, 0) + + +def lstm_cell(inp, hx, cx, hh_weight, hh_bias, hr_weight, chunk_dim): + gates = F.linear(hx, hh_weight, hh_bias) + inp + chunked_gates = gates.chunk(4, chunk_dim) + in_gate = chunked_gates[0].sigmoid() + forget_gate = chunked_gates[1].sigmoid() + cell_gate = chunked_gates[2].tanh() + out_gate = chunked_gates[3].sigmoid() + cy = forget_gate * cx + (in_gate * cell_gate) + hy = out_gate * cy.tanh() + hy = hy if hr_weight is None else F.linear(hy, hr_weight, None) + + return hy, cy + + +def one_layer_lstm(inp, hidden, params, has_biases, reverse=False): + ih_weight = params[0] + hh_weight = params[1] + ih_bias = params[2] if has_biases else None + hh_bias = params[3] if has_biases else None + hr_weight = ( + params[4] if len(params) == 5 else params[2] if len(params) == 3 else None + ) + + hx = hidden[0].unsqueeze(0) + cx = hidden[1].unsqueeze(0) + + precomputed_input = F.linear(inp, ih_weight, ih_bias) + precomputed_input = precomputed_input.flip(0) if reverse else precomputed_input + step_output = [] + for inp in precomputed_input: + hx, cx = lstm_cell(inp, hx, cx, hh_weight, hh_bias, hr_weight, chunk_dim=2) + step_output.append(hx) + + if reverse: + step_output.reverse() + + out = torch.cat(step_output, 0) + + return out, (hx.squeeze(1), cx.squeeze(1)) + + +def one_layer_lstm_data(inp, hidden, params, has_biases, batch_sizes, reverse=False): + ih_weight = params[0] + hh_weight = params[1] + ih_bias = params[2] if has_biases else None + hh_bias = params[3] if has_biases else None + hr_weight = ( + params[4] if len(params) == 5 else params[2] if len(params) == 3 else None + ) + + step_output = [] + hiddens = [] + + last_batch_size = batch_sizes[-1] if reverse else batch_sizes[0] + split_inp = torch.split(inp, list(batch_sizes)) + if reverse: + split_inp = split_inp[::-1] + + orig_hx = hidden[0] + orig_cx = hidden[1] + hx, cx = ( + orig_hx.narrow(0, 0, last_batch_size), + orig_cx.narrow(0, 0, last_batch_size), + ) + + for inp in split_inp: + i = inp.shape[0] + inp = F.linear(inp, ih_weight, ih_bias) + + # this will only happen when reverse=False, since batch sizes are sorted largest -> smallest + if i < last_batch_size: + hiddens.append( + ( + hx.narrow(0, i, last_batch_size - i), + cx.narrow(0, i, last_batch_size - i), + ) + ) + hx, cx = hx.narrow(0, 0, i), cx.narrow(0, 0, i) + + # this will only happen when reverse=True + if i > last_batch_size: + hx = torch.concat( + (hx, orig_hx.narrow(0, last_batch_size, i - last_batch_size)), 0 + ) + cx = torch.concat( + (cx, orig_cx.narrow(0, last_batch_size, i - last_batch_size)), 0 + ) + + hx, cx = lstm_cell(inp, hx, cx, hh_weight, hh_bias, hr_weight, chunk_dim=1) + last_batch_size = i + step_output.append(hx) + + if reverse: + step_output.reverse() + hidden_out = (hx, cx) + else: + hiddens.append((hx, cx)) + hiddens.reverse() + hidden0, hidden1 = zip(*hiddens) + hidden_out = torch.cat(hidden0, 0), torch.cat(hidden1, 0) + + out = torch.cat(step_output, 0) + return out, hidden_out + + +def select_one_layer_lstm_function(input, hx, params): + r"""Check whether we could use decompose lstm with mkldnn_rnn_layer. + All the below conditions need to be met: + * ``torch._C._get_mkldnn_enabled()`` returns ``True``. + * All the input args are on CPU. + * The dtypes of args are either torch.float or torch.bfloat16. + * Inference. + * ``has_projections`` returns ``False``. + + Args: + * input: the input sequence to LSTM + * hx: a tuple of the input hidden state and cell state ``(h_0, c_0)`` to LSTM + * params: the weight and bias tensors of LSTM + """ + + def use_mkldnn(input, hx, params): + if not torch._C._get_mkldnn_enabled(): + return False + + tensors = [input] + list(hx) + list(chain.from_iterable(params)) + devices = {t.device for t in tensors} + if len(devices) != 1: + return False + + device = devices.pop() + if device != torch.device("cpu"): + return False + # With autocast, possible to have mixed dtype here + dtypes = {t.dtype for t in tensors} + for dtype in dtypes: + if dtype not in [torch.float, torch.bfloat16]: + return False + + if input.requires_grad: + return False + + has_projections = hx[0].size(2) != hx[1].size(2) + if has_projections: + return False + + return True + + # mkldnn_one_layer_lstm does not depend on seq_len while one_layer_lstm + # will expand over the seq_len dim + if use_mkldnn(input, hx, params): + return mkldnn_one_layer_lstm + else: + return one_layer_lstm + + +@register_decomposition(aten.lstm.input) +@aten.lstm.input.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.lstm.input.py_impl(DispatchKey.Autograd) +def lstm_impl( + input, + hx, + params, + has_biases, + num_layers, + dropout, + train, + bidirectional, + batch_first, +): + assert len(hx) == 2, "lstm expects two hidden states" + params = gather_params(params, has_biases, hx[0].size(2) != hx[1].size(2)) + hidden = list(zip(hx[0], hx[1])) + layer_fn = select_one_layer_lstm_function(input, hx, params) + out, final_hiddens = _rnn_helper( + input, + hidden, + params, + has_biases, + num_layers, + dropout, + train, + bidirectional, + batch_first, + layer_fn, + ) + final_hiddens = list(zip(*final_hiddens)) + return out, torch.stack(final_hiddens[0], 0), torch.stack(final_hiddens[1], 0) + + +@register_decomposition(aten.lstm.data) +@aten.lstm.data.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.lstm.data.py_impl(DispatchKey.Autograd) +def lstm_data_impl( + data, + batch_sizes, + hx, + params, + has_biases, + num_layers, + dropout, + train, + bidirectional, +): + assert len(hx) == 2, "lstm expects two hidden states" + params = gather_params(params, has_biases, hx[0].size(2) != hx[1].size(2)) + hidden = list(zip(hx[0], hx[1])) + out, final_hiddens = _rnn_helper( + data, + hidden, + params, + has_biases, + num_layers, + dropout, + train, + bidirectional, + False, + partial(one_layer_lstm_data, batch_sizes=batch_sizes), + ) + final_hiddens = list(zip(*final_hiddens)) + return out, torch.stack(final_hiddens[0], 0), torch.stack(final_hiddens[1], 0) + + +def gru_cell(inp, cur_hidden, ih_weight, ih_bias, hh_weight, hh_bias): + chunked_igates = inp.chunk(3, 1) + chunked_hgates = F.linear(cur_hidden, hh_weight, hh_bias).chunk(3, 2) + reset_gate = (chunked_hgates[0] + chunked_igates[0]).sigmoid() + input_gate = (chunked_hgates[1] + chunked_igates[1]).sigmoid() + new_gate = (chunked_igates[2] + (chunked_hgates[2] * reset_gate)).tanh() + return (cur_hidden - new_gate) * input_gate + new_gate + + +def gru_cell_data(inp, cur_hidden, ih_weight, ih_bias, hh_weight, hh_bias): + chunked_igates = F.linear(inp, ih_weight, ih_bias).chunk(3, 1) + chunked_hgates = F.linear(cur_hidden, hh_weight, hh_bias).chunk(3, 1) + reset_gate = (chunked_hgates[0] + chunked_igates[0]).sigmoid() + input_gate = (chunked_hgates[1] + chunked_igates[1]).sigmoid() + new_gate = (chunked_igates[2] + (chunked_hgates[2] * reset_gate)).tanh() + return (cur_hidden - new_gate) * input_gate + new_gate + + +@register_decomposition(aten.gru.data) +@aten.gru.data.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.gru.data.py_impl(DispatchKey.Autograd) +def gru_impl_data( + data, + batch_sizes, + hx, + params, + has_biases, + num_layers, + dropout, + train, + bidirectional, +): + params = gather_params(params, has_biases, False) + out, final_hiddens = _rnn_helper( + data, + hx.unbind(0), + params, + has_biases, + num_layers, + dropout, + train, + bidirectional, + False, + partial(one_layer_rnn_data, batch_sizes=batch_sizes, hidden_fn=gru_cell_data), + ) + return out, torch.stack(final_hiddens, 0) + + +@register_decomposition(aten.gru.input) +@aten.gru.input.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.gru.input.py_impl(DispatchKey.Autograd) +def gru_impl( + input, + hx, + params, + has_biases, + num_layers, + dropout, + train, + bidirectional, + batch_first, +): + params = gather_params(params, has_biases, False) + out, final_hiddens = _rnn_helper( + input, + hx.unbind(0), + params, + has_biases, + num_layers, + dropout, + train, + bidirectional, + batch_first, + partial(one_layer_rnn, hidden_fn=gru_cell), + ) + return out, torch.stack(final_hiddens, 0) + + +@register_decomposition(aten._upsample_bilinear2d_aa.vec) +@aten._upsample_bilinear2d_aa.vec.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten._upsample_bilinear2d_aa.vec.py_impl(DispatchKey.Autograd) +def upsample_bilinear2d_aa_vec(input, output_size, align_corners, scale_factors): + osize = upsample_compute_output_size(input.size(), output_size, scale_factors) + scale_h = get_scale_value(scale_factors, 0) + scale_w = get_scale_value(scale_factors, 1) + return torch.ops.aten._upsample_bilinear2d_aa( + input, osize, align_corners, scale_h, scale_w + ) + + +@register_decomposition(aten._upsample_bicubic2d_aa.vec) +@aten._upsample_bicubic2d_aa.vec.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten._upsample_bicubic2d_aa.vec.py_impl(DispatchKey.Autograd) +def upsample_bicubic2d_aa_vec(input, output_size, align_corners, scale_factors): + osize = upsample_compute_output_size(input.size(), output_size, scale_factors) + scale_h = get_scale_value(scale_factors, 0) + scale_w = get_scale_value(scale_factors, 1) + return torch.ops.aten._upsample_bicubic2d_aa( + input, osize, align_corners, scale_h, scale_w + ) + + +@register_decomposition(aten.upsample_bilinear2d.vec) +@register_decomposition(aten.upsample_trilinear3d.vec) +@aten.upsample_linear1d.vec.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.upsample_linear1d.vec.py_impl(DispatchKey.Autograd) +@aten.upsample_bilinear2d.vec.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.upsample_bilinear2d.vec.py_impl(DispatchKey.Autograd) +@aten.upsample_trilinear3d.vec.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.upsample_trilinear3d.vec.py_impl(DispatchKey.Autograd) +def _upsample_linear_vec(input, output_size, align_corners, scale_factors): + osize = upsample_compute_output_size(input.size(), output_size, scale_factors) + scales = scale_factors if scale_factors else [None] * len(osize) + return _upsample_linear(input, osize, align_corners, scales) + + +@register_decomposition([aten.upsample_linear1d.default, aten.upsample_linear1d.out]) +@out_wrapper() +def upsample_linear1d( + input: Tensor, + output_size: list[int], + align_corners: bool, + scales_w: Optional[float] = None, +) -> Tensor: + return _upsample_linear(input, output_size, align_corners, [scales_w]) + + +@register_decomposition( + [aten.upsample_bilinear2d.default, aten.upsample_bilinear2d.out] +) +@aten.upsample_bilinear2d.default.py_impl(DispatchKey.Autograd) +@out_wrapper() +def upsample_bilinear2d( + input: Tensor, + output_size: list[int], + align_corners: bool, + scales_h: Optional[float] = None, + scales_w: Optional[float] = None, +) -> Tensor: + return _upsample_linear(input, output_size, align_corners, [scales_h, scales_w]) + + +@register_decomposition( + [aten.upsample_trilinear3d.default, aten.upsample_trilinear3d.out] +) +@out_wrapper() +def upsample_trilinear3d( + input: Tensor, + output_size: list[int], + align_corners: bool, + scales_d: Optional[float] = None, + scales_h: Optional[float] = None, + scales_w: Optional[float] = None, +) -> Tensor: + return _upsample_linear( + input, output_size, align_corners, [scales_d, scales_h, scales_w] + ) + + +def _compute_scale(in_size, out_size, align_corners, scale=None): + if align_corners: + return (in_size - 1.0) / (out_size - 1.0) if out_size > 1 else 0 + else: + return 1.0 / scale if scale is not None and scale > 0 else in_size / out_size + + +def _compute_source_index(scale, dst_index, align_corners): + if align_corners: + return scale * dst_index + else: + return scale * (dst_index + 0.5) - 0.5 + + +def _sum_tensors_uint8( + src: Iterable[Tensor], weights: Iterable[Tensor], weights_precision: Tensor +) -> Tensor: + output = _sum_tensors( + s.to(torch.int32) * c.to(torch.int32) for s, c in zip(src, weights) + ) + (1 << (weights_precision - 1)) + output = output >> weights_precision + return torch.clamp(output, 0, 255).to(torch.uint8) + + +def _compute_weight_precision(weights: TensorSequenceType) -> Tensor: + max_weight = torch.stack(weights).max() + max_weight_precision = 22 + precisions = torch.arange(max_weight_precision, device=max_weight.device) + values = 0.5 + max_weight * (1 << (precisions + 1)) + mask = values >= (1 << 15) + return max_weight_precision - mask.sum() + + +@pw_cast_for_opmath +def _upsample_linear( + input: Tensor, + output_size: list[int], + align_corners: bool, + scales: list[Optional[float]], +) -> Tensor: + # get dimensions of original image + n_channels = input.shape[1] + inp_sizes = input.shape[2:] + n_dims = len(inp_sizes) + + _, dtype = utils.elementwise_dtypes( + input, + type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + ) + + def get_values(inp_size, out_size, scales, nsqueeze): + # First Calculate scaling factor + scale_factor = _compute_scale(inp_size, out_size, align_corners, scales) + # We have to create arange with int64 dtype and use .to in order to avoid + # additional kernels creation in inductor and get a perf slowdown + i = torch.arange(out_size, device=input.device).to(dtype=dtype) + + x_f32 = _compute_source_index(scale_factor, i, align_corners).clamp(min=0.0) + x_f32 = x_f32.reshape(x_f32.shape[0], *[1] * (nsqueeze)) + x = x_f32.to(torch.int64) + xp1 = (x + 1).clamp(max=inp_size - 1) + return x_f32, x, xp1 + + values = [ + get_values(inp_size, out_size, scales, n_dims - 1 - i) + for i, (inp_size, out_size, scales) in enumerate( + zip(inp_sizes, output_size, scales) + ) + ] + xs_f32, xs, xp1s = list(zip(*values)) + + vs = [] + for a in product(*[[0, 1]] * n_dims): + idx = [None, None] + [xs[k] if a[k] == 0 else xp1s[k] for k in range(n_dims)] + v = aten._unsafe_index(input, idx) + v = _maybe_convert_to_dtype(v, dtype) + vs.append(v) + + for i in reversed(range(n_dims)): + xscale = (xs_f32[i] - xs[i]).clamp(0.0, 1.0).to(dtype) + vs = [ + # x1 * (1 - alpha) + x2 * alpha == x1 + (x2 - x1) * alpha + v1 + torch.mul(v2 - v1, xscale) + for v1, v2 in zip(vs[::2], vs[1::2]) + ] + + assert len(vs) == 1 + result = vs[0] + + # convert output to correct memory format, if necessary + memory_format = utils.suggest_memory_format(input) + + # following "heuristic: only use channels_last path when it's faster than the contiguous path" + if input.device.type == "cuda" and n_channels < 16: + memory_format = torch.contiguous_format + + assert isinstance(result, torch.Tensor) + + result = result.contiguous(memory_format=memory_format) + + if not input.is_floating_point(): + result = result.round() + + return result + + +# We should be applying decompositions after all transformations +@register_decomposition(aten.is_same_size.default) +def is_same_size(a: Tensor, b: Tensor) -> bool: + return a.shape == b.shape + + +@register_decomposition([aten._reshape_alias, aten._unsafe_view]) +@out_wrapper() +def _reshape_alias(x, shape, *args): + return aten.view(x, shape) + + +@register_decomposition([aten._unsafe_index]) +def _unsafe_index(x, indices): + return aten.index(x, indices) + + +@register_decomposition([aten._unsafe_index_put]) +def _unsafe_index_put(x, indices, value, accumulate=False): + return aten.index_put(x, indices, value, accumulate) + + +@register_decomposition([aten._unsafe_masked_index]) +def _unsafe_masked_index(x, mask, indices, fill): + for index in indices: + if index is not None: + torch._check( + index.dtype in [torch.long, torch.int], + lambda: "tensors used as indices must be long or int tensors", + ) + + torch._check( + mask.dtype == torch.bool, + lambda: "tensors used as masks must be bool tensors", + ) + + from torch.fx.experimental.symbolic_shapes import guard_or_false + + if guard_or_false(x.numel() == 0): + meta_result = torch._meta_registrations.meta_index_Tensor(x, indices) + return x.new_full(meta_result.shape, fill) + + for i in range(len(indices)): + index = indices[i] + if index is not None: + indices[i] = index.clamp(min=0, max=x.size(i) - 1) + + return aten._unsafe_index(x, indices).masked_fill(~mask, fill) + + +@register_decomposition([aten._unsafe_masked_index_put_accumulate]) +def _unsafe_masked_index_put_accumulate(x, mask, indices, values): + for index in indices: + if index is not None: + torch._check( + index.dtype in [torch.long, torch.int], + lambda: "tensors used as indices must be long or int tensors", + ) + + torch._check( + mask.dtype == torch.bool, + lambda: "tensors used as masks must be bool tensors", + ) + + if x.numel() == 0: + return x.clone() + + for i in range(len(indices)): + index = indices[i] + if index is not None: + indices[i] = index.clamp(min=-x.size(i), max=x.size(i) - 1) + + masked_value = values.masked_fill(~mask, 0) + return aten._unsafe_index_put(x, indices, masked_value, accumulate=True) + + +def _nll_loss_forward( + self: Tensor, + target: Tensor, + weight: Optional[Tensor], + reduction: int, + ignore_index: int, +) -> tuple[Tensor, Tensor]: + # self can be [N, C] or [C] + # target can be [N] or [] + + n_dims = self.dim() + channel_dim = 1 + if n_dims < 2: + channel_dim = 0 + + if weight is not None: + if n_dims > 1: + shape = [ + 1, + ] * n_dims + shape[channel_dim] = weight.shape[0] + w = weight.view(shape) + else: + w = weight + self = self * w + safe_target = torch.where(target != ignore_index, target, 0) + safe_target_ = safe_target.unsqueeze(channel_dim) + # target can be [N, 1] or [1] + + result = -torch.gather(self, channel_dim, safe_target_).squeeze(channel_dim) + + result = torch.where(target != ignore_index, result, 0) + + if reduction == Reduction.NONE.value and n_dims > 1: + total_weight = self.new_full((), 0.0) + return result, total_weight + + if weight is not None: + # pyrefly: ignore [unbound-name] + w = w.expand(self.shape) + wsum = torch.gather(w, channel_dim, safe_target_).squeeze(channel_dim) + wsum = torch.where(target != ignore_index, wsum, 0) + total_weight = wsum.sum() + else: + total_weight = (target != ignore_index).sum().to(self) + + if reduction == Reduction.SUM.value: + result = result.sum() + elif reduction == Reduction.MEAN.value: + result = result.sum() / total_weight + + return result, total_weight + + +@register_decomposition(aten.nll_loss_forward) +@out_wrapper("output", "total_weight") +def nll_loss_forward( + self: Tensor, + target: Tensor, + weight: Optional[Tensor], + reduction: int, + ignore_index: int, +) -> tuple[Tensor, Tensor]: + assert self.dim() > 0 and self.dim() <= 2, "input tensor should be 1D or 2D" + assert target.dim() <= 1, ( + "0D or 1D target tensor expected, multi-target not supported" + ) + + no_batch_dim = self.dim() == 1 and target.dim() == 0 + assert no_batch_dim or (self.shape[0] == target.shape[0]), ( + f"size mismatch (got input: {self.shape}, target: {target.shape})" + ) + + n_classes = self.shape[-1] + + assert weight is None or (weight.dim() == 1 and weight.numel() == n_classes), ( + f"weight tensor should be defined either for all {n_classes} classes or no classes " + f"but got weight tensor of shape: {weight.shape}" + ) + + return _nll_loss_forward(self, target, weight, reduction, ignore_index) + + +@register_decomposition(aten.nll_loss2d_forward) +@out_wrapper("output", "total_weight") +def nll_loss2d_forward( + self: Tensor, + target: Tensor, + weight: Optional[Tensor], + reduction: int, + ignore_index: int, +) -> tuple[Tensor, Tensor]: + return _nll_loss_forward(self, target, weight, reduction, ignore_index) + + +# These are adapted from aten/src/ATen/native/UpSample.h, which is based on +# https://en.wikipedia.org/wiki/Bicubic_interpolation#Bicubic_convolution_algorithm +def _upsample_cubic_convolution1(x: Tensor, A: float) -> Tensor: + return ((A + 2) * x - (A + 3)) * x * x + 1 + + +def _upsample_cubic_convolution2(x: Tensor, A: float) -> Tensor: + return ((A * x - 5 * A) * x + 8 * A) * x - 4 * A + + +def _upsample_get_cubic_coefficients(t: Tensor) -> TensorSequenceType: + A = -0.75 + + if t.device == torch.device("cpu"): + tt1 = torch.stack([t, 1.0 - t], dim=0) + tt2 = torch.stack([t + 1.0, 2.0 - t], dim=0) + w03 = _upsample_cubic_convolution2(tt2, A) + w12 = _upsample_cubic_convolution1(tt1, A) + w0, w3 = torch.unbind(w03, dim=0) + w1, w2 = torch.unbind(w12, dim=0) + return w0, w1, w2, w3 + else: + return ( + _upsample_cubic_convolution2(t + 1.0, A), + _upsample_cubic_convolution1(t, A), + _upsample_cubic_convolution1(1.0 - t, A), + _upsample_cubic_convolution2(2.0 - t, A), + ) + + +def _upsample_cubic_interp1d(coeffs: TensorSequenceType, ts: Tensor) -> Tensor: + coeffs2 = _upsample_get_cubic_coefficients(ts) + return _sum_tensors(c1 * c2 for (c1, c2) in zip(coeffs, coeffs2)) + + +# Need this instead of just sum() to keep mypy happy +def _sum_tensors(ts: Iterable[Tensor]) -> Tensor: + return reduce(torch.add, ts) + + +def _linspace_from_neg_one( + num_steps: int, align_corners: bool, dtype: torch.dtype, device: torch.device +): + if num_steps <= 1: + return torch.tensor(0, device=device, dtype=dtype) + + a = ((num_steps - 1) / num_steps) if not align_corners else 1 + return torch.linspace(-a, a, steps=num_steps, device=device, dtype=dtype) + + +def _make_base_grid_4d(theta: Tensor, h: int, w: int, align_corners: bool): + dtype = theta.dtype + device = theta.device + + # Using padding and summation generates a single kernel vs using torch.stack where 3 kernels generated + # corresponding to each individual tensor: grid_x, grid_y, grid_one + grid_x = _linspace_from_neg_one(w, align_corners, dtype, device).view(1, w, 1) + grid_y = _linspace_from_neg_one(h, align_corners, dtype, device).view(h, 1, 1) + grid_one = torch.ones((1, 1, 1), dtype=dtype, device=device) + + # this is just a temporary hack and we should use torch.stack here once #104480 is merged + grid_x = torch.nn.functional.pad(grid_x, pad=(0, 2), mode="constant", value=0) + grid_y = torch.nn.functional.pad(grid_y, pad=(1, 1), mode="constant", value=0) + grid_one = torch.nn.functional.pad(grid_one, pad=(2, 0), mode="constant", value=0) + return grid_x + grid_y + grid_one + + +def _make_base_grid_5d(theta: Tensor, d: int, h: int, w: int, align_corners: bool): + dtype = theta.dtype + device = theta.device + + grid_x = _linspace_from_neg_one(w, align_corners, dtype, device).view(1, 1, w, 1) + grid_y = _linspace_from_neg_one(h, align_corners, dtype, device).view(1, h, 1, 1) + grid_z = _linspace_from_neg_one(d, align_corners, dtype, device).view(d, 1, 1, 1) + grid_one = torch.ones((1, 1, 1, 1), dtype=dtype, device=device) + + # this is just a temporary hack and we should use torch.stack here once #104480 is merged + grid_x = torch.nn.functional.pad(grid_x, pad=(0, 3), mode="constant", value=0) + grid_y = torch.nn.functional.pad(grid_y, pad=(1, 2), mode="constant", value=0) + grid_z = torch.nn.functional.pad(grid_z, pad=(2, 1), mode="constant", value=0) + grid_one = torch.nn.functional.pad(grid_one, pad=(3, 0), mode="constant", value=0) + return grid_x + grid_y + grid_z + grid_one + + +def _affine_grid_generator_4d(theta: Tensor, size: list[int], align_corners: bool): + n, _, h, w = size + base_grid = _make_base_grid_4d(theta, h, w, align_corners=align_corners) + # base_grid shape is (h, w, 3) and theta shape is (n, 2, 3) + # We do manually a matrix multiplication which is faster than mm() + # (h * w, 3, 1) * (n, 1, 3, 2) -> (n, h * w, 2) + grid = (base_grid.view(-1, 3, 1) * theta.mT.unsqueeze(1)).sum(-2) + return grid.view(n, h, w, 2) + + +def _affine_grid_generator_5d(theta: Tensor, size: list[int], align_corners: bool): + n, _, d, h, w = size + base_grid = _make_base_grid_5d(theta, d, h, w, align_corners=align_corners) + # base_grid shape is (d, h, w, 4) and theta shape is (n, 3, 4) + # We do manually a matrix multiplication which is faster than mm() + # (d * h * w, 4, 1) * (n, 1, 4, 3) -> (n, h * w, 3) + grid = (base_grid.view(-1, 4, 1) * theta.mT.unsqueeze(1)).sum(-2) + return grid.view(n, d, h, w, 3) + + +@register_decomposition(aten.affine_grid_generator) +@out_wrapper() +@pw_cast_for_opmath +def affine_grid_generator(theta: Tensor, size: list[int], align_corners: bool): + torch._check( + len(size) in (4, 5), + lambda: "affine_grid_generator needs 4d (spatial) or 5d (volumetric) inputs.", + ) + if len(size) == 4: + return _affine_grid_generator_4d(theta, size, align_corners=align_corners) + else: + return _affine_grid_generator_5d(theta, size, align_corners=align_corners) + + +def _grid_sampler_2d( + a: Tensor, + grid: Tensor, + interpolation_mode: int = 0, + padding_mode: int = 0, + align_corners: bool = False, + _expand_grid: bool = True, +) -> Tensor: + # This method is a copy of grid_sampler_2d implementation and introduced with additional arg _expand_grid to + # optionally expand the input grid for performance reasons. + # Experimenting locally it was found that compiled CUDA code is accelerated by ~5x + # and CPU code by ~2x on bicubic mode, if we expand the grid from (N, H, W, 2) into (N, C, H, W, 2) + # However, this leads to a slowdown around ~0.8x on CPU bilinear mode, channels first. + # Thus we apply this hack to not expand the grid for this case. + + torch._check( + interpolation_mode in (0, 1, 2), + lambda: f"Invalid interpolation mode {interpolation_mode}", + ) + torch._check( + padding_mode in (0, 1, 2), lambda: f"Invalid padding mode {padding_mode}" + ) + + def unnormalize(coords: Tensor, size: int) -> Tensor: + # Rescale coordinates from [-1, 1] to: + # [0, size - 1] if align_corners is True + # [-.5, size -.5] if align_corners is False + mul = (size * 0.5 - 0.5) if align_corners else (size * 0.5) + ofs = size * 0.5 - 0.5 + return coords * mul + ofs + + # Reflects coordinates until they fall between low and high (inclusive). + # The bounds are passed as twice their value so that half-integer values + # can be represented as ints. + def reflect_coordinates(coords: Tensor, twice_low: int, twice_high: int) -> Tensor: + if twice_low == twice_high: + return torch.zeros_like(coords) + coords_min = twice_low / 2 + coords_span = (twice_high - twice_low) / 2 + coords2 = (coords - coords_min).abs() + extra = torch.fmod(coords2, coords_span) + flips = (coords2 / coords_span).floor().to(dtype=torch.int8) + return torch.where( + flips & 1 == 0, extra + coords_min, coords_span + coords_min - extra + ) + + def compute_coordinates(coords: Tensor, size: int) -> Tensor: + if padding_mode == 0: # Zero + return coords + elif padding_mode == 1: # Borders + return torch.clamp(coords, 0, size - 1) + else: # padding_mode == 2, Reflection + if align_corners: + coords_reflected = reflect_coordinates(coords, 0, 2 * (size - 1)) + else: + coords_reflected = reflect_coordinates(coords, -1, 2 * size - 1) + return torch.clamp(coords_reflected, 0, size - 1) + + def compute_source_index(coords: Tensor, size: int) -> Tensor: + coords_un = unnormalize(coords, size) + return compute_coordinates(coords_un, size) + + N, C, iH, iW = a.shape + _, oH, oW, two = grid.shape + assert two == 2 + + if _expand_grid: + # Let's expand grid to [N, C, oH, oW, 2] + # This allows to generate a single triton cuda kernel instead of two kernels. + # Two kernels are due source indices, weights have shape (N, 1, oH, oW), xnumel=N*oH*oW + # and output has shape (N, C, oH, oW), xnumel=N*C*oH*oW + # Expanding grid to (N, C, oH, oW, two) unifies xnumel to N*C*oH*oW + grid = grid.view(N, 1, oH, oW, two).expand(N, C, oH, oW, 2) + + def in_bounds_cond(xs: Tensor, ys: Tensor) -> Tensor: + return torch.logical_and( + 0 <= xs, torch.logical_and(xs < iW, torch.logical_and(0 <= ys, ys < iH)) + ) + + N_idx = torch.arange(N, device=a.device).view(N, 1, 1, 1) + C_idx = torch.arange(C, device=a.device).view(1, C, 1, 1) + + def clip(xs: Tensor, ys: Tensor, ws: Tensor) -> TensorSequenceType: + cond = in_bounds_cond(xs, ys) + # To clip to inside valid coordinates, we map the coordinates + # to (x, y) = (0, 0) and also set the weight to 0 + # We also change the shape of the tensor to the appropriate one for + # broadcasting with N_idx, C_idx for the purposes of advanced indexing + c = C if _expand_grid else 1 + return tuple( + torch.where(cond, t, 0).view(N, c, oH, oW) + for t in (xs.to(dtype=torch.int64), ys.to(dtype=torch.int64), ws) + ) + + def get_summand(ix: Tensor, iy: Tensor, w) -> Tensor: + # Perform clipping, index into input tensor and multiply by weight + idx_x, idx_y, w_ = clip(ix, iy, w) + return a[N_idx, C_idx, idx_y, idx_x] * w_ + + x = grid[..., 0] + y = grid[..., 1] + + if interpolation_mode == 0: # Bilinear + ix = compute_source_index(x, iW) + iy = compute_source_index(y, iH) + + ix_nw, iy_nw = ix.floor(), iy.floor() + ix_ne, iy_ne = ix_nw + 1, iy_nw + ix_sw, iy_sw = ix_nw, iy_nw + 1 + ix_se, iy_se = ix_ne, iy_sw + + w_nw = (ix_se - ix) * (iy_se - iy) + w_ne = (ix - ix_sw) * (iy_sw - iy) + w_sw = (ix_ne - ix) * (iy - iy_ne) + w_se = (ix - ix_nw) * (iy - iy_nw) + + return _sum_tensors( + get_summand(ix, iy, w) + for (ix, iy, w) in ( + (ix_nw, iy_nw, w_nw), + (ix_ne, iy_ne, w_ne), + (ix_sw, iy_sw, w_sw), + (ix_se, iy_se, w_se), + ) + ) + elif interpolation_mode == 1: # Nearest + ix = compute_source_index(x, iW) + iy = compute_source_index(y, iH) + + ix_nearest = ix.round() + iy_nearest = iy.round() + + return get_summand(ix_nearest, iy_nearest, 1) + else: # interpolation_mode == 2, Bicubic + ix = unnormalize(x, iW) + iy = unnormalize(y, iH) + + ix_nw = ix.floor() + iy_nw = iy.floor() + + tx = ix - ix_nw + ty = iy - iy_nw + + if not _expand_grid: + tx = tx.unsqueeze(1) + ty = ty.unsqueeze(1) + + def get_value_bounded(ix: Tensor, iy: Tensor) -> Tensor: + x = compute_coordinates(ix, iW) + y = compute_coordinates(iy, iH) + return get_summand(x, y, 1) + + def get_coeff(ofs: int) -> Tensor: + iy_ofs = iy_nw + (ofs - 1) + cs = ( + get_value_bounded(ix_nw - 1, iy_ofs), + get_value_bounded(ix_nw, iy_ofs), + get_value_bounded(ix_nw + 1, iy_ofs), + get_value_bounded(ix_nw + 2, iy_ofs), + ) + return _upsample_cubic_interp1d(cs, tx) + + coeffs = tuple(get_coeff(ofs) for ofs in range(4)) + return _upsample_cubic_interp1d(coeffs, ty) + + +@register_decomposition(aten.grid_sampler_2d) +@out_wrapper() +@pw_cast_for_opmath +def grid_sampler_2d( + a: Tensor, + grid: Tensor, + interpolation_mode: int = 0, + padding_mode: int = 0, + align_corners: bool = False, +) -> Tensor: + return _grid_sampler_2d( + a, + grid=grid, + interpolation_mode=interpolation_mode, + padding_mode=padding_mode, + align_corners=align_corners, + ) + + +@register_decomposition(aten.mv) +@out_wrapper(exact_dtype=True) +@pw_cast_for_opmath +def mv(self, vec): + torch._check( + self.dim() == 2 and vec.dim() == 1, + lambda: f"matrix @ vector expected, got {self.dim()}, {vec.dim()}", + ) + torch._check( + self.size(1) == vec.size(0), + lambda: f"size mismatch, got input ({self.size(0)}x{self.size(1)}), vec ({vec.size(0)})", + ) + return (self * vec).sum(dim=1) + + +@register_decomposition(aten.binary_cross_entropy_with_logits) +@out_wrapper() +def binary_cross_entropy_with_logits( + self, target, weight=None, pos_weight=None, reduction=Reduction.MEAN.value +): + if pos_weight is not None: + log_weight = (pos_weight - 1) * target + 1 + loss = (1 - target) * self - (log_weight * F.logsigmoid(self)) + else: + loss = (1 - target) * self - F.logsigmoid(self) + + if weight is not None: + loss = loss * weight + + return apply_loss_reduction(loss, reduction) + + +def should_fold(tensor1: torch.Tensor, tensor2: torch.Tensor, is_out: bool) -> bool: + # For comments of the logic of this function see eager in /native/LinearAlgebra.cpp + + t1, t2 = (tensor1, tensor2) if tensor1.ndim >= tensor2.ndim else (tensor2, tensor1) + + from torch.fx.experimental.symbolic_shapes import guard_or_false + + if not (t1.ndim >= 3 and t2.ndim <= 2): + return False + if t2.requires_grad and not is_out: + return True + if tensor1.ndim == 2: + return False + if guard_or_false(t1.numel() == 0): + return True + + t1_shape = t1.shape + t1_stride = t1.stride() + + # Check the contiguous, we can skip the dim with size of 1 + # as aten: https://github.com/pytorch/pytorch/blob/e201460f8aa1510b4c4686627d57b69756c4b916/aten/src/ATen/TensorGeometry.cpp#L17 + expected_stride = [1] + for size in reversed(t1_shape[1:]): + expected_stride.append(size * expected_stride[-1]) + return all( + guard_or_false(size == 1) or guard_or_false(left == right) + for left, right, size in zip( + t1_stride, list(reversed(expected_stride)), t1_shape + ) + ) + + +@aten.matmul.default.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.matmul.out.py_impl(DispatchKey.CompositeImplicitAutograd) +@out_wrapper(pass_is_out=True) +def matmul(tensor1, tensor2, *, is_out=False): + from torch.fx.experimental.symbolic_shapes import guard_or_false, guard_or_true + + dim_tensor1 = tensor1.dim() + dim_tensor2 = tensor2.dim() + assert dim_tensor1 != 0 and dim_tensor2 != 0 + if dim_tensor1 == 1 and dim_tensor2 == 1: + return torch.dot(tensor1, tensor2) + elif dim_tensor1 == 2 and dim_tensor2 == 1: + return torch.mv(tensor1, tensor2) + elif dim_tensor1 == 1 and dim_tensor2 == 2: + return torch.squeeze(torch.mm(torch.unsqueeze(tensor1, 0), tensor2), 0) + elif dim_tensor1 == 2 and dim_tensor2 == 2: + return torch.mm(tensor1, tensor2) + elif should_fold(tensor1, tensor2, is_out): + # dim_tensor1 >=3 && (dim_tensor2 == 1 || dim_tensor2 == 2) || + # dim_tensor2 >=3 && (dim_tensor1 == 1 || dim_tensor1 == 2) + # and some condition on the strides is fulfilled + + # optimization: use mm instead of bmm by folding the batch of the larger tensor + # into its leading matrix dimension + transpose = dim_tensor2 > dim_tensor1 + t1 = tensor2.mT if transpose else tensor1 + t2 = ( + tensor2 if not transpose else (tensor1.t() if dim_tensor1 == 2 else tensor1) + ) + # Invariant: t1.dim() >= 3 && (t2.dim() == 1 || t2.dim() == 2) + # and t1 and t2 are matmul-compatible + + # Why not t1.view(-1, sizes_1[-1])? + # If the last dim is 0, then view(-1, 0) won't work because the -1 becomes ambiguous. + # This can happen in e.g. [3, 5, 0] @ [0, 0]. + sizes_1 = t1.shape + output_shape = list(sizes_1[:-1]) + folded_dim1 = reduce(operator.mul, output_shape) + + # Readjust output_shape if we are multiplying by a matrix + t2_is_matrix = t2.dim() == 2 + if t2_is_matrix: + output_shape.append(t2.shape[1]) + + # This will almost always be a view. + # It may not be a view if t2->requires_grad(). See should_fold in aten/ for an explanation + t1_folded = t1.reshape(folded_dim1, sizes_1[-1]) + if t2_is_matrix: + # This copies if we perform a 2D @ 3D and the first tensor requires_grad + # See should_fold native/LinearAlgebra.cpp for why. + output = torch.ops.aten._unsafe_view(t1_folded.mm(t2), output_shape) + return output.mT.contiguous() if transpose else output + else: + return torch.ops.aten._unsafe_view(t1_folded.mv(t2), output_shape) + + elif dim_tensor1 >= 1 and dim_tensor2 >= 1: + # We are multiplying b1 x n x m1 by x2 x m2 x p (where b1 can be a list); + # we track m1 vs m2 separately even though they must match for nicer error messages + n = tensor1.size(-2) if dim_tensor1 > 1 else 1 + m1 = tensor1.size(-1) + batch_tensor1 = tensor1.shape[:-2] + m2 = tensor2.size(-2) if dim_tensor2 > 1 else tensor2.size(-1) + p = tensor2.size(-1) if dim_tensor2 > 1 else 1 + + batch_tensor2: list[int] = [] + # TODO: handling of slice + for i in range(dim_tensor2 - 2): + batch_tensor2.append(tensor2.size(i)) + + # Same optimization for the gradients as that in should_fold + # If we're going to broadcast, we force it to go through the should_fold branch + if ( + dim_tensor1 == 3 + and dim_tensor2 == 3 + and guard_or_true(batch_tensor1[0] != batch_tensor2[0]) + ): + if guard_or_false(batch_tensor1[0] == 1) and tensor1.requires_grad: + return matmul(tensor1.squeeze(0), tensor2) + if guard_or_false(batch_tensor2[0] == 1) and tensor2.requires_grad: + return matmul(tensor1, tensor2.squeeze(0)) + + # expand the batch portion (i.e. cut off matrix dimensions and expand rest) + expand_batch_portion = list( + torch.broadcast_shapes(batch_tensor1, batch_tensor2) + ) + + tensor1_expand_size = expand_batch_portion + [n, m1] + + expand_batch_product = prod(expand_batch_portion) + + # HACK: We need reshape with symint support + tensor1_expanded = tensor1.expand(tensor1_expand_size).reshape( + expand_batch_product, n, m1 + ) + + vector_rhs = dim_tensor2 == 1 + if vector_rhs: + tensor2_expand_size = expand_batch_portion + [m2] + tensor2_expanded = ( + tensor2.expand(tensor2_expand_size) + .reshape(expand_batch_product, m2) + .unsqueeze(2) + ) + else: + tensor2_expand_size = expand_batch_portion + [m2, p] + tensor2_expanded = tensor2.expand(tensor2_expand_size).reshape( + expand_batch_product, m2, p + ) + + output_shape = expand_batch_portion + if dim_tensor1 > 1: + output_shape.append(n) + + if dim_tensor2 > 1: + output_shape.append(p) + + if vector_rhs: + return tensor1_expanded.bmm(tensor2_expanded).squeeze(-1).view(output_shape) + else: + return tensor1_expanded.bmm(tensor2_expanded).view(output_shape) + else: + torch._check(False, lambda: "both arguments to matmul need to be at least 1D") + + +@register_decomposition([aten.upsample_bicubic2d.default, aten.upsample_bicubic2d.out]) +@aten.upsample_bicubic2d.default.py_impl(DispatchKey.Autograd) +@out_wrapper() +@pw_cast_for_opmath +def upsample_bicubic2d_default( + input: Tensor, + output_size: tuple[int, int], + align_corners: bool, + scale_h: Optional[float] = None, + scale_w: Optional[float] = None, +) -> Tensor: + # get dimensions of original image + _, _, in_h, in_w = input.shape + + # Calculate horizontal and vertical scaling factor + h_scale_factor = _compute_scale(in_h, output_size[0], align_corners, scale_h) + w_scale_factor = _compute_scale(in_w, output_size[1], align_corners, scale_w) + + _, dtype = utils.elementwise_dtypes( + input, type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT + ) + + # We have to create arange with int64 dtype and use .to in order to avoid + # additional kernels creation in inductor and get a perf slowdown + i = torch.arange(output_size[0], device=input.device).to(dtype=dtype) + j = torch.arange(output_size[1], device=input.device).to(dtype=dtype) + + x_float = _compute_source_index(w_scale_factor, j, align_corners) + y_float = _compute_source_index(h_scale_factor, i, align_corners) + y_float = y_float.unsqueeze(-1) + + x = x_float.floor() + y = y_float.floor() + + # We should also clamp xscale/yscale + # See guard_index_and_lambda in UpSample.h + yscale = (y_float - y).clamp(0.0, 1.0) + xscale = (x_float - x).clamp(0.0, 1.0) + x = x.to(torch.int64) + y = y.to(torch.int64) + + iys_ofs = (y - 1, y, y + 1, y + 2) + ixs_ofs = (x - 1, x, x + 1, x + 2) + + weights_x = _upsample_get_cubic_coefficients(xscale) + weights_y = _upsample_get_cubic_coefficients(yscale) + + weights_precision_x, weights_precision_y = None, None + if input.dtype == torch.uint8: + weights_precision_x = _compute_weight_precision(weights_x) + weights_precision_y = _compute_weight_precision(weights_y) + + weights_x = [ + (w * (1 << weights_precision_x) + torch.sign(w) * 0.5).to(torch.int16) + for w in weights_x + ] + weights_y = [ + (w * (1 << weights_precision_y) + torch.sign(w) * 0.5).to(torch.int16) + for w in weights_y + ] + + def load_bounded(ys, xs): + y_idx = torch.clamp(ys, 0, in_h - 1) + x_idx = torch.clamp(xs, 0, in_w - 1) + v = aten._unsafe_index(input, [None, None, y_idx, x_idx]) + return v + + def get_x_interp(y): + src_x = tuple(load_bounded(y, x_ofs) for x_ofs in ixs_ofs) + if input.dtype == torch.uint8: + assert weights_precision_x is not None + return _sum_tensors_uint8(src_x, weights_x, weights_precision_x) + return _sum_tensors(c1 * c2 for (c1, c2) in zip(src_x, weights_x)) + + src_y = tuple(get_x_interp(y_ofs) for y_ofs in iys_ofs) + if input.dtype == torch.uint8: + assert weights_precision_y is not None + result = _sum_tensors_uint8(src_y, weights_y, weights_precision_y) + else: + result = _sum_tensors(c1 * c2 for (c1, c2) in zip(src_y, weights_y)) + + # convert output to correct memory format, if necessary + memory_format = utils.suggest_memory_format(input) + result = result.contiguous(memory_format=memory_format) + return result + + +@register_decomposition(aten.upsample_bicubic2d.vec) +@aten.upsample_bicubic2d.vec.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.upsample_bicubic2d.vec.py_impl(DispatchKey.Autograd) +@out_wrapper() +@pw_cast_for_opmath +def upsample_bicubic2d_vec( + a: Tensor, + output_size: Optional[tuple[int, int]], + align_corners: bool, + scale_factors: Optional[tuple[float, float]] = None, +) -> Tensor: + torch._check( + bool(output_size) + bool(scale_factors) == 1, + lambda: "Must specify exactly one of output_size and scale_factors.", + ) + if output_size is None: + assert scale_factors is not None + output_size = cast( + tuple[int, int], + tuple( + sym_int(sym_float(w) * scale) + for w, scale in zip(a.shape[2:], scale_factors) + ), + ) + scale_h, scale_w = scale_factors if scale_factors else (None, None) + return upsample_bicubic2d_default(a, output_size, align_corners, scale_h, scale_w) + + +@register_decomposition(aten.reflection_pad1d) +@register_decomposition(aten.reflection_pad2d) +@register_decomposition(aten.reflection_pad3d) +@pw_cast_for_opmath +@out_wrapper() +def _reflection_pad(a: Tensor, padding: tuple[int, ...]) -> Tensor: + def idx(left, middle, right): + dim_idx = torch.arange(-left, middle + right, device=a.device) + return middle - 1 - (middle - 1 - dim_idx.abs()).abs() + + return _reflection_or_replication_pad( + a, + padding, + idx, + ) + + +@register_decomposition(aten.replication_pad1d) +@register_decomposition(aten.replication_pad2d) +@register_decomposition(aten.replication_pad3d) +@pw_cast_for_opmath +@out_wrapper() +def _replication_pad(a: Tensor, padding: tuple[int, ...]) -> Tensor: + def idx(left, middle, right): + dim_idx = torch.arange(-left, middle + right, device=a.device) + return torch.clamp(dim_idx, 0, middle - 1) + + return _reflection_or_replication_pad( + a, + padding, + idx, + ) + + +def _reflection_or_replication_pad( + a: Tensor, + padding: tuple[int, ...], + idx_fn: Callable[[int, int, int], Tensor], +) -> Tensor: + dim = len(padding) // 2 + torch._check( + a.dim() in (dim + 1, dim + 2), + lambda: f"reflection_pad{dim}d requires {dim + 1}D or {dim + 2}D input", + ) + inp_shape = a.shape[-dim:] + nc_dim = a.dim() - dim + + padding_left = [padding[2 * (dim - 1 - i)] for i in range(dim)] + padding_right = [padding[2 * (dim - 1 - i) + 1] for i in range(dim)] + + result = a + for i in range(dim): + idx: list[Any] = [None] * result.dim() + idx[i + nc_dim] = idx_fn(padding_left[i], inp_shape[i], padding_right[i]) + result = aten._unsafe_index(result, idx) + + # convert output to correct memory format, if necessary + memory_format = utils.suggest_memory_format(result) + result = result.contiguous(memory_format=memory_format) + return result + + +@register_decomposition(aten.reflection_pad1d_backward) +@register_decomposition(aten.reflection_pad2d_backward) +@register_decomposition(aten.reflection_pad3d_backward) +@out_wrapper("grad_input") +def _reflection_pad_backward(grad_output, x, padding): + dim = len(padding) // 2 + + dhw = [h - 1 for h in x.shape[-dim:]] + + padding_left = [padding[2 * (dim - 1 - i)] for i in range(dim)] + padding_right = [padding[2 * (dim - 1 - i) + 1] for i in range(dim)] + + indices = [] + for i in range(x.ndim): + view_shape = [1] * x.ndim + view_shape[i] = -1 + indices.append(torch.arange(x.shape[i], device=x.device).view(view_shape)) + + b = indices[:-dim] + xyz = indices[-dim:] + + def index_range_condition(index_range): + i, lb, ub = index_range + return torch.logical_and(i >= lb, i <= ub) + + # Areas after reflection: + # + # top-left | top | top-right + # ----------------------------------------- + # left | center | right + # ----------------------------------------- + # bottom-left | bottom | bottom-right + # + # The center area is the original matrix. Other areas are reflections. + + center = [xyz[i] + padding_left[i] for i in range(dim)] + left_reflect = [padding_left[i] - xyz[i] for i in range(dim)] + right_reflect = [2 * dhw[i] + padding_left[i] - xyz[i] for i in range(dim)] + + # Accumulate gradients from different areas + # If some of the padding is negative, center load is not always valid + range_c = [ + (center[i], 0, dhw[i] + padding_left[i] + padding_right[i]) for i in range(dim) + ] + cond = functools.reduce( + aten.logical_and, [index_range_condition(range_c[i]) for i in range(dim)] + ) + grad = aten._unsafe_masked_index(grad_output, cond, b + center, 0.0) + + def accumulate(grad, out, index_ranges): + # If the upper bound is less than the lower bound, we can get rid of one accumulation. + # This happens when the padding size is zero. + for i in range(dim): + upper_less_than_lower = index_ranges[i][2] < index_ranges[i][1] + if isinstance(upper_less_than_lower, bool) and upper_less_than_lower: + return grad + + cond = functools.reduce( + aten.logical_and, + [index_range_condition(index_range) for index_range in index_ranges], + ) + g = aten._unsafe_masked_index(grad_output, cond, b + out, 0.0) + return grad + g + + for area in itertools.product(*[[-1, 0, 1] for _ in range(dim)]): + if area == tuple([0] * dim): + # center, this is already done. + continue + + outs = [] + index_ranges = [] + + for i in range(dim): + if area[i] == 0: + out = center[i] + index_range = range_c[i] + elif area[i] == -1: + out = left_reflect[i] + index_range = (xyz[i], 1, padding_left[i]) + elif area[i] == 1: + out = right_reflect[i] + index_range = (xyz[i], dhw[i] - padding_right[i], dhw[i] - 1) + + outs.append(out) # type: ignore[possibly-undefined] + index_ranges.append(index_range) # type: ignore[possibly-undefined] + + grad = accumulate(grad, outs, index_ranges) + + return grad + + +@register_decomposition(aten.aminmax) +@out_wrapper("min", "max") +def aminmax(self, *, dim=None, keepdim=False): + # pyrefly: ignore [bad-argument-type] + amin = torch.amin(self, dim=dim, keepdim=keepdim) + # pyrefly: ignore [bad-argument-type] + amax = torch.amax(self, dim=dim, keepdim=keepdim) + return amin, amax + + +@register_decomposition(aten.nansum) +@out_wrapper() +def nansum(self, dim=None, keepdim=False, *, dtype=None): + return aten.sum(torch.where(torch.isnan(self), 0, self), dim, keepdim, dtype=dtype) + + +@register_decomposition([aten.arange.default, aten.arange.out]) +@out_wrapper() +def arange_default( + end: NumberType, + *, + dtype: Optional[torch.dtype] = None, + layout: torch.layout = torch.strided, + device: Optional[torch.device] = None, + pin_memory: bool = False, +): + return aten.arange.start_step( + 0, end, 1, dtype=dtype, layout=layout, device=device, pin_memory=pin_memory + ) + + +@register_decomposition([aten.arange.start]) +def arange_start( + start: NumberType, + end: NumberType, + *, + dtype: Optional[torch.dtype] = None, + layout: torch.layout = torch.strided, + device: Optional[torch.device] = None, + pin_memory: bool = False, +): + return aten.arange.start_step( + start, end, 1, dtype=dtype, layout=layout, device=device, pin_memory=pin_memory + ) + + +@register_decomposition(out_dtype) +def out_dtype_decomp(*args, **kwargs): + from torch._higher_order_ops.out_dtype import out_dtype_dense + + return out_dtype_dense(*args, **kwargs) + + +@register_decomposition(aten.multi_margin_loss) +@aten.multi_margin_loss.default.py_impl(DispatchKey.Autograd) +@out_wrapper() +def multi_margin_loss( + input: Tensor, + target: Tensor, + p: NumberType = 1, + margin: NumberType = 1, + weight: Optional[Tensor] = None, + reduction: int = Reduction.MEAN.value, +) -> Tensor: + input = torch.atleast_2d(input) + target = torch.atleast_1d(target) + nframe = input.shape[0] + dim = input.shape[1] + torch._check(p == 1 or p == 2, lambda: "only p == 1 and p == 2 supported") + torch._check( + input.ndim == 2 and dim != 0, + lambda: f"Expected non-empty vector or matrix with optional 0-dim batch size, but got: {input.shape}", + ) + torch._check( + target.ndim == 1 and target.numel() == nframe, + lambda: f"inconsistent target size, expected {nframe} but got {target.shape}", + ) + if weight is not None: + weight = torch.atleast_1d(weight) + torch._check( + weight.ndim == 1 and weight.numel() == dim, # type: ignore[union-attr] + lambda: f"inconsistent weight size, expected {dim} but got {weight.shape}", # type: ignore[union-attr] + ) + target = target.unsqueeze(1) + u = torch.gather(input, dim=1, index=target) + z = margin - u + input + z = z.clamp_min(0) + z = z if p == 1 else z * z + if weight is not None: + z = z * weight[target] + idx = torch.arange(dim, device=input.device) + z = torch.where(idx != target, z, 0) + if reduction == Reduction.MEAN.value: + return z.mean() + elif reduction == Reduction.SUM.value: + return z.sum() / z.shape[1] + else: + return z.mean(dim=1) + + +@register_decomposition(aten.multilabel_margin_loss_forward) +@aten.multilabel_margin_loss_forward.default.py_impl(DispatchKey.Autograd) +@out_wrapper("output", "is_target") +def multilabel_margin_loss_forward( + input: Tensor, + target: Tensor, + reduction: int, +) -> tuple[Tensor, Tensor]: + orig_input_shape = input.shape + orig_target_shape = target.shape + input = torch.atleast_2d(input) + target = torch.atleast_2d(target) + dim = input.shape[1] + torch._check( + len(orig_input_shape) <= 2 and dim != 0, + lambda: f"Expected non-empty vector or matrix with optional 0-dim batch size, but got: {orig_input_shape}", + ) + torch._check( + len(orig_target_shape) <= 2 and orig_target_shape == orig_input_shape, + lambda: f"inconsistent target size: {orig_target_shape} for input of size: {orig_input_shape}", + ) + # ignores labels after the first -1, detects when -1 is not present + idx = torch.arange(dim, device=target.device) + is_end = target == -1 + end_idx = torch.amin(torch.where(is_end, idx, dim), dim=-1, keepdim=True) + # target indices + target_mask = idx < end_idx + # masks target to be able to use gather, which doesn't allow -1 + tidx0 = torch.where(target_mask, target, 0) + u = torch.gather(input, dim=-1, index=tidx0) + # is_target + tidx1 = torch.where(target_mask, target, -1) + is_target = torch.any(idx == tidx1.unsqueeze(dim=-1), dim=1) + # loss + z = 1.0 - u.T.unsqueeze(dim=-1) + input + z = z.clamp_min(0) + z = z / dim + # masks loss + z = torch.where(is_target, 0, z) + # reduction + if reduction == Reduction.MEAN.value: + z = z.sum(dim=(0, -1)).mean() + elif reduction == Reduction.SUM.value: + z = z.sum() + else: + z = z.sum(dim=(0, -1)) + # result + is_target = is_target.to(input.dtype).reshape(orig_target_shape) + return z, is_target + + +# scaled_dot_product_attention used to be decomposed in pre-autograd, given that +# it calls _scaled_dot_product_attention_math and +# _scaled_dot_product_attention_math only has a CompositeImplicitAutograd +# kernel. As a result it's decomposed into ops with finer granularity. +# However recent PRs (#103826 #105131 #115913) added new logic in +# scaled_dot_product_attention and now it calls +# _scaled_dot_product_flash_attention_for_cpu in export path. This results +# in _scaled_dot_product_flash_attention_for_cpu showing up in export result. +# This decomposition ensures scaled_dot_product_attention is still decomposed +# the same way as before, i.e., going through +# _scaled_dot_product_attention_math. Notice that this decomp rule should be +# excluded by inductor. +@register_decomposition(aten._scaled_dot_product_flash_attention_for_cpu.default) +def scaled_dot_product_flash_attention_for_cpu( + query: Tensor, + key: Tensor, + value: Tensor, + dropout_p: float = 0.0, + is_causal: bool = False, + *, + attn_mask: Optional[Tensor] = None, + scale: Optional[float] = None, +) -> tuple[Tensor, Tensor]: + torch._check( + torch.is_floating_point(query), + lambda: f"query must be FP32, FP64, BF16, FP16 but got {query.dtype}", + ) + torch._check( + query.dim() == 4 and key.dim() == 4 and value.dim() == 4, + lambda: f"q, k, v must be a 4 dimensional tensor, got {query.dim()}, {key.dim()}, {value.dim()}", + ) + torch._check( + dropout_p == 0.0, lambda: f"dropout probability must be zero, got {dropout_p}" + ) + torch._check( + query.shape[3] == value.shape[3] and key.shape[3] == value.shape[3], + lambda: "q, k, v should have the same head size", + ) + + output, attn = aten._scaled_dot_product_attention_math.default( + query, + key, + value, + attn_mask=attn_mask, + dropout_p=dropout_p, + is_causal=is_causal, + dropout_mask=None, + scale=scale, + enable_gqa=query.size(1) != key.size(1), + ) + # Why this change? + # In pre-dispatch export scaled_dot_product_attention is executed via + # * flash_attention. + # flash_attention allocates output tensor as (N, H, L, E) (see PR #134656) + # assume x: [N, H, L, E] is the output sdpa + # In MHA code, this output is then permuted via (2, 0, 1, 3) to get + # (L, N, H, E) dim tensor + # x = x.permute(2, 0, 1, 3).contiguous() and the viewed via + # x = x.view(L * N, H * E) + # During pre autograd dispatch call to contiguous is not traced because + # flash_attention output after the x.permute is already contiguous + # on which the view is valid + # However, during 2nd stage export, post-dispatch, we run _match variant + # instead of flash* to get the decomposition. _match variant returns + # x: [N, H, L, E] applying x.permute(2, 0, 1, 3) returns + # x: [L, N, H, E] and without converting this to contiguous tensor + # subsequent view is not valid and the export fails + # solution is to maintain the return tensor view from the decomp to be + # exactly same as *flash* variant. + + # Really the invariant you want to maintain is: + # pre-dispatch op-output and its decomposed representation must + # return tensor with same view and dims + output = ( + output.permute(2, 0, 1, 3) + .contiguous(memory_format=torch.contiguous_format) + .permute(1, 2, 0, 3) + ) + return output, attn + + +def register_inplace(aten_op, outplace_op): + @register_decomposition(aten_op) + def inplace_op(*args, **kwargs): + out = outplace_op(*args, **kwargs) + return args[0].copy_(out) + + return inplace_op + + +@register_decomposition([aten.baddbmm]) +@out_wrapper(exact_dtype=True) +@pw_cast_for_opmath +def baddbmm(self, batch1, batch2, beta=1, alpha=1): + if not self.is_floating_point() and not self.is_complex(): + beta = int(beta) + alpha = int(alpha) + result = torch.bmm(batch1, batch2) + if not isinstance(alpha, numbers.Number) or alpha != 1: + # pyrefly: ignore [unsupported-operation] + result = result * alpha + if beta == 0: + return result + if not isinstance(beta, numbers.Number) or beta != 1: + self = self * beta + return self + result + + +@register_decomposition(aten.floor_divide) +@out_wrapper() +def floor_divide(self, other): + return torch.div(self, other, rounding_mode="floor") + + +@register_decomposition(aten.sym_numel) +def sym_numel(t): + return functools.reduce(operator.mul, t.shape, 1) + + +@register_decomposition([aten.sum.default, aten.sum.out]) +def sum_default( + self: Tensor, + *, + dtype: Optional[torch.dtype] = None, + out: Optional[Tensor] = None, +) -> Tensor: + if out is None: + return aten.sum.dim_IntList(self, [], dtype=dtype) + else: + return aten.sum.IntList_out(self, [], dtype=dtype, out=out) + + +@register_decomposition([aten.squeeze.default, aten.squeeze.dim]) +def squeeze_default(self: Tensor, dim: Optional[int] = None): + # handle a scalar directly + if not isinstance(self, torch.Tensor): + return self + # perform squeeze + if dim is None: + return aten.squeeze.dims(self, list(range(self.dim()))) + else: + return aten.squeeze.dims(self, [dim]) + + +@register_decomposition(torch.ops.aten._weight_norm_interface) +def _weight_norm_interface(v, g, dim=0): + # https://github.com/pytorch/pytorch/blob/852f8526c52190125446adc9a6ecbcc28fb66182/aten/src/ATen/native/WeightNorm.cpp#L58 + keep_dim = tuple(i for i in range(len(v.shape)) if i != dim) + # align with cuda behavior, keep norm in 'float' when g is 'bfloat16' + norm_dtype = torch.float if g.dtype == torch.bfloat16 else None + norm = v.norm(2, keep_dim, keepdim=True, dtype=norm_dtype) + return v * (g / norm.to(g.dtype)), norm + + +@register_decomposition(aten.isin) +@out_wrapper() +def isin(elements, test_elements, *, assume_unique=False, invert=False): + # handle when either elements or test_elements are Scalars (they can't both be) + if not isinstance(elements, torch.Tensor): + elements = torch.tensor(elements, device=test_elements.device) + if not isinstance(test_elements, torch.Tensor): + if invert: + return torch.ne(elements, test_elements) + else: + return torch.eq(elements, test_elements) + + if test_elements.numel() < 10.0 * pow(elements.numel(), 0.145): + return isin_default(elements, test_elements, invert=invert) + else: + return isin_sorting( + elements, test_elements, assume_unique=assume_unique, invert=invert + ) + + +@register_decomposition(aten.bernoulli.default) +def bernoulli( + self: torch.Tensor, + *, + generator: Optional[torch.Generator] = None, +) -> torch.Tensor: + if generator is None: + raw_p = torch.rand(self.size(), dtype=torch.float32, device=self.device) + else: + raw_p = torch.rand( + self.size(), + generator=generator, + dtype=torch.float32, + device=self.device, + ) + p = (raw_p < self).to(self.dtype) + return p + + +def isin_default(elements, test_elements, *, invert=False): + if elements.numel() == 0: + return torch.empty_like(elements, dtype=torch.bool) + expanded_elem_shape = elements.shape + (1,) * test_elements.ndim + x = elements.view(expanded_elem_shape) + dim = tuple(range(-1, -test_elements.ndim - 1, -1)) + res = (x == test_elements).any(dim=dim) + return ~res if invert else res + + +def isin_sorting(elements, test_elements, *, assume_unique=False, invert=False): + elements_flat = elements.flatten() + test_elements_flat = test_elements.flatten() + if assume_unique: + # This is the same as the aten implementation. For + # assume_unique=False, we cannot use unique() here, so we use a + # version with searchsorted instead. + all_elements = torch.cat([elements_flat, test_elements_flat]) + sorted_elements, sorted_order = torch.sort(all_elements, stable=True) + + duplicate_mask = sorted_elements[1:] == sorted_elements[:-1] + duplicate_mask = torch.constant_pad_nd(duplicate_mask, [0, 1], False) + + if invert: + duplicate_mask = duplicate_mask.logical_not() + + mask = torch.empty_like(duplicate_mask) + mask = mask.index_copy(0, sorted_order, duplicate_mask) + + return mask[0 : elements.numel()] + else: + sorted_test_elements, _ = torch.sort(test_elements_flat) + idx = torch.searchsorted(sorted_test_elements, elements_flat) + test_idx = torch.where(idx < sorted_test_elements.numel(), idx, 0) + cmp = sorted_test_elements[test_idx] == elements_flat + cmp = cmp.logical_not() if invert else cmp + return cmp.reshape(elements.shape) + + +@register_decomposition(aten.take) +@out_wrapper() +def take(self, index): + flattened = self.reshape(-1) + return flattened[index] + + +@register_decomposition(aten.resize_as) +def resize_as(self, other, memory_format=None): + if memory_format is None: + memory_format = torch.contiguous_format + if memory_format == torch.preserve_format: + memory_format = suggest_memory_format(other) + return aten.resize(self, other.shape, memory_format=memory_format) + + +register_inplace(aten.addbmm_, aten.addbmm) +register_inplace(aten.addmm_, aten.addmm) +register_inplace(aten.addmv_, aten.addmv) +register_inplace(aten.baddbmm_, aten.baddbmm) +register_inplace(aten.fill_, aten.fill) +register_inplace(aten.gelu_, aten.gelu) +register_inplace(aten.hardswish_, aten.hardswish) +register_inplace(aten.hardtanh_, aten.hardtanh) +register_inplace(aten.hardsigmoid_, aten.hardsigmoid) +register_inplace(aten.__iand__, aten.__and__) +register_inplace(aten.__ilshift__, aten.__lshift__) +register_inplace(aten.index_put_, aten.index_put) +register_inplace(aten.index_reduce_, aten.index_reduce) +register_inplace(aten.__ior__, aten.__or__) +register_inplace(aten.__irshift__, aten.__rshift__) +register_inplace(aten.__ixor__, aten.__xor__) +register_inplace(aten.leaky_relu_, aten.leaky_relu) +register_inplace(aten.logit_, aten.logit) +register_inplace(aten.relu_, aten.relu) +register_inplace(aten.renorm_, aten.renorm) +register_inplace(aten.round_, aten.round) +register_inplace(aten.scatter_, aten.scatter) +register_inplace(aten.scatter_add_, aten.scatter_add) +register_inplace(aten.scatter_reduce_, aten.scatter_reduce) +register_inplace(aten.silu_, aten.silu) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_decomp/decompositions_for_jvp.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_decomp/decompositions_for_jvp.py new file mode 100644 index 0000000000000000000000000000000000000000..dd3b7e7d8899266501ad57381f190c47a2082739 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_decomp/decompositions_for_jvp.py @@ -0,0 +1,336 @@ +# mypy: allow-untyped-decorators +# mypy: allow-untyped-defs +import inspect +from collections.abc import Callable +from typing import Optional + +import torch +import torch._decomp +from torch import Tensor +from torch._prims_common.wrappers import _maybe_remove_out_wrapper + + +decomposition_table = torch._decomp.decomposition_table +decomposition_table_for_jvp: dict[torch._ops.OperatorBase, Callable] = {} +register_decomposition = torch._decomp.register_decomposition +aten = torch.ops.aten + +# NOTE: [forward-mode AD decompositions mechanism] +# +# The mechanism is in VariableType, +# IF any inputs have forward grad +# AND there is no forward AD formula implemented +# AND the functions are actually differentiable +# run the decomposition +# See run_jit_decomposition_with_args_for_jvp +# We currently use python decompositions that we torchscript. +# +# Note that we would be building the backward graph at the decomposed level +# too, but that is OK, because we would've errored out otherwise anyway. +# +# TODO: The mechanism we are using to register decompositions doesn't +# seem to be exclusively used for jvp. So open question here is whether +# torch/csrc/jit/runtime/decomposition_registry.cpp is being used for other things. +# If that is the case, we may go down the decomposition path unexpectedly +# (and possibly produce an unintelligible error) vs erroring out earlier and +# printing that the forward AD formula is not implemented. +# +# The solution to this may be to have an explicitly white list control when +# to enable the decomposition. + + +def maybe_register_decomposition(op): + def decorator(f): + try: + return register_decomposition(op)(f) + except Exception: + return f + + return decorator + + +# Functions where we need a special decomposition for jvp but there's another version that +# should be used more generally (ex. for jvp we need to recompute the mean and variance for +# the backwards of a normalization function. Without jvp, it should use the saved value) +decomposition_table_for_jvp = {} + + +def register_decomposition_for_jvp(fn): + return register_decomposition(fn, registry=decomposition_table_for_jvp) + + +def _register_jit_decomposition_for_jvp(decomp, use_python=False): + if decomp in decomposition_table_for_jvp: + decomposition_table_used = decomposition_table_for_jvp + elif decomp in decomposition_table: + decomposition_table_used = decomposition_table + else: + raise RuntimeError(f"could not find decomposition for {decomp}") + decomp_fn = decomposition_table_used[decomp] + + # `out_wrapper` extends a decompositions signature with + # an `out` parameter. However jit will use the unwrapped function's + # signature instead so we need to unwrap here to prevent an error + decomp_fn = _maybe_remove_out_wrapper(decomp_fn) + + if use_python: + decomp_fn = torch.jit.ignore(decomp_fn) + sig = inspect.signature(decomp_fn) + + # Create a string wrapping the function from the signature + # example output: + # def wrapped_decomp(x: torch.Tensor, y: int, z: int): + # return decomp_fn(x, y, z) + # Thanks copilot! + def get_function_def(sig): + param_def = [f"{param_str}" for param_str in sig.parameters.values()] + param_use = [f"{param_str}" for param_str in sig.parameters] + + return f"def wrapped_decomp({', '.join(param_def)}):\n return decomp_fn({', '.join(param_use)})\n" + + f_str = get_function_def(sig) + graph = torch.jit.CompilationUnit(f_str).wrapped_decomp.graph + else: + graph = torch.jit.script(decomp_fn).graph + torch.jit._register_decomposition(decomp, graph) + + +# The only decompositions here are temporary or hacks for the purposes of jvp + + +# TODO: do these also belong here? +@maybe_register_decomposition(aten.trace.default) +def trace(self: Tensor) -> Tensor: + return torch.sum(torch.diag(self)) + + +@maybe_register_decomposition(aten.log_sigmoid_forward.default) +def log_sigmoid_forward(self: Tensor) -> tuple[Tensor, Tensor]: + min = torch.minimum(self.new_zeros(()), self) + z = torch.exp(-torch.abs(self)) + if self.is_cuda or self.is_xpu: + buffer = self.new_zeros((0,)) + else: + buffer = z + return min - torch.log1p(z), buffer + + +def recompute_mean_var( + input: Tensor, rstd: Tensor, inner_dim_indices: list[int], keepdim: bool +): + # for most norm decompositions, it will be the same as the core version except for here. + # We recompute the mean and variance so that they track gradients through input + + mean = torch.mean(input, dim=inner_dim_indices, keepdim=keepdim) + var = torch.var(input, dim=inner_dim_indices, unbiased=False, keepdim=keepdim) + eps = torch.pow(1 / rstd, 2) - var # this makes me so sad inside + eps = eps.detach() + rstd = 1 / torch.sqrt(var + eps) + return mean, rstd + + +@register_decomposition_for_jvp(aten.native_layer_norm_backward) +def native_layer_norm_backward( + grad_out: Tensor, + input: Tensor, + normalized_shape: list[int], + mean: Tensor, + rstd: Tensor, + weight: Optional[Tensor], + bias: Optional[Tensor], + output_mask: list[bool], +) -> tuple[Optional[Tensor], Optional[Tensor], Optional[Tensor]]: + input_shape = input.shape + input_ndim = input.dim() + + axis = input_ndim - len(normalized_shape) + inner_dims = input_shape[axis:] + outer_dims = input_shape[:axis] + inner_dim_indices = list(range(axis, input_ndim)) + outer_dim_indices = list(range(axis)) + + N = 1 + for i in inner_dims: + N *= i + M = 1 + for i in outer_dims: + M *= i + if M <= 0 or N <= 0: + return ( + input.new_zeros(input_shape), + input.new_zeros(input_shape[axis:]), + input.new_zeros(input_shape[axis:]), + ) + + mean_, rstd_ = recompute_mean_var(input, rstd, inner_dim_indices, keepdim=True) + + x_hat = (input - mean_) * rstd_ + if weight is not None: + grad_x_hat = grad_out * weight + else: + grad_x_hat = grad_out + a = grad_x_hat * N + b = torch.sum(grad_x_hat, inner_dim_indices, True) + c1 = torch.mul(grad_x_hat, x_hat) + c2 = torch.sum(c1, inner_dim_indices, True) + c3 = torch.mul(x_hat, c2) + inner = a - b - c3 + + if output_mask[0]: + d_input: Optional[Tensor] = (rstd_ / N) * inner + else: + d_input = torch.zeros_like(input) # should be None but doesn't work with vjp + + if output_mask[1] and weight is not None: + if len(outer_dim_indices) > 0: + d_weight: Optional[Tensor] = torch.sum( + grad_out * x_hat, outer_dim_indices, False + ) + else: + d_weight = grad_out * x_hat + elif weight is not None: + d_weight = torch.zeros_like(weight) # should be None but doesn't work with vjp + else: + d_weight = torch.zeros(()) # should be None but doesn't work with vjp + + if output_mask[2] and bias is not None: + if len(outer_dim_indices) > 0: + d_bias: Optional[Tensor] = torch.sum(grad_out, outer_dim_indices, False) + else: + d_bias = grad_out.clone() + elif bias is not None: + d_bias = torch.zeros_like(bias) # should be None but doesn't work with vjp + else: + d_bias = torch.zeros(()) # should be None but doesn't work with vjp + + return (d_input, d_weight, d_bias) + + +def prod(x: list[int]): + r = 1 + for i in x: + r *= i + return r + + +@register_decomposition_for_jvp(aten.native_batch_norm_backward) +def native_batch_norm_backward( + grad_out: Tensor, + input: Tensor, + weight: Optional[Tensor], + running_mean: Optional[Tensor], + running_var: Optional[Tensor], + save_mean: Optional[Tensor], + save_invstd: Optional[Tensor], + train: bool, + eps: float, + output_mask: list[bool], +) -> tuple[Tensor, Optional[Tensor], Optional[Tensor]]: + input_shape = input.shape + input_rank = input.dim() + assert input_rank >= 2, "rank of the input must be at least 2" + + axis = 1 + num_features = prod(input_shape) / input_shape[axis] # type: ignore[arg-type] + mean = save_mean + invstd = save_invstd + if train: + assert save_mean is not None and save_invstd is not None, ( + "when train=True, save_mean and save_invstd are required" + ) + + reduciton_dims = [0] + list(range(2, input.dim())) + assert invstd is not None # for typing + mean, invstd = recompute_mean_var(input, invstd, reduciton_dims, keepdim=False) + else: + assert running_mean is not None and running_var is not None + mean = running_mean + invstd = torch.rsqrt(running_var + eps) + + assert invstd is not None and mean is not None + + broadcast_mask = [1] * input_rank + broadcast_mask[axis] = input_shape[axis] + + reduction_axes: list[int] = [] + for i in range(input_rank): + if i != axis: + reduction_axes.append(i) + + mean = torch.reshape(mean, broadcast_mask) + norm = 1.0 / num_features + grad_output_sum = torch.sum(grad_out, reduction_axes) + dot_p = torch.sum(grad_out * (input - mean), reduction_axes) + + grad_mean = torch.reshape(grad_output_sum * norm, broadcast_mask) + proj_scale = torch.reshape(torch.mul(dot_p * norm, invstd * invstd), broadcast_mask) + + if weight is None: + grad_scale = torch.reshape(invstd, broadcast_mask) * 1.0 + else: + grad_scale = torch.reshape(invstd * weight, broadcast_mask) + + if train: + proj = (input - mean) * proj_scale + grad_input = ((grad_out - proj) - grad_mean) * grad_scale + else: + grad_input = grad_out * grad_scale + + if output_mask[1]: + grad_weight = dot_p * invstd + elif weight is not None: + grad_weight = torch.zeros_like( + weight + ) # should be None but doesn't work with vjp + else: + grad_weight = torch.zeros(()) # should be None but doesn't work with vjp + + if output_mask[2]: + grad_bias = grad_output_sum + else: + grad_bias = torch.zeros_like( + grad_output_sum + ) # should be None but doesn't work with vjp + + return (grad_input, grad_weight, grad_bias) + + +@register_decomposition_for_jvp(aten.batch_norm_backward) +def batch_norm_backward( + grad_out: Tensor, + input: Tensor, + weight: Tensor, + running_mean: Optional[Tensor], + running_var: Optional[Tensor], + save_mean: Optional[Tensor], + save_var: Optional[Tensor], + update: bool, + eps: float, + output_mask: list[bool], + reserve: Tensor, +) -> tuple[Tensor, Optional[Tensor], Optional[Tensor]]: + return native_batch_norm_backward( + grad_out, + input, + weight, + running_mean, + running_var, + save_mean, + save_var, + update, + eps, + output_mask, + ) + + +_register_jit_decomposition_for_jvp(torch.ops.aten.trace.default, use_python=True) +_register_jit_decomposition_for_jvp(torch.ops.aten.nll_loss_backward.default) +_register_jit_decomposition_for_jvp(torch.ops.aten.nll_loss2d_backward.default) +_register_jit_decomposition_for_jvp(torch.ops.aten._log_softmax_backward_data.default) +_register_jit_decomposition_for_jvp(torch.ops.aten._softmax_backward_data.default) +_register_jit_decomposition_for_jvp(torch.ops.aten.log_sigmoid_forward.default) +_register_jit_decomposition_for_jvp(torch.ops.aten.native_layer_norm_backward.default) +_register_jit_decomposition_for_jvp(torch.ops.aten.native_batch_norm_backward.default) +_register_jit_decomposition_for_jvp(torch.ops.aten.cudnn_batch_norm_backward.default) +_register_jit_decomposition_for_jvp(torch.ops.aten.batch_norm_backward.default) +_register_jit_decomposition_for_jvp(torch.ops.aten.miopen_batch_norm_backward.default) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_decomp/decompositions_for_rng.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_decomp/decompositions_for_rng.py new file mode 100644 index 0000000000000000000000000000000000000000..455ef0cc994388a60785cf715c6ec529a0c0fec5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_decomp/decompositions_for_rng.py @@ -0,0 +1,266 @@ +# mypy: allow-untyped-decorators +# mypy: allow-untyped-defs +import functools +from collections import defaultdict +from collections.abc import Callable + +import torch +import torch._decomp as decomp +from torch._decomp import get_decompositions +from torch._ops import OpOverload + + +aten = torch.ops.aten + +rng_decompositions: dict[str, dict[OpOverload, Callable]] = defaultdict(dict) + + +def register_rng_decomposition(aten_op): + return decomp.register_decomposition(aten_op, rng_decompositions) + + +def throw_on_non_cuda(device): + raise RuntimeError( + f"You are trying to functionalize a {device.type} RNG operator but {device.type} does not " + f"use Philox/counter-based RNG. Therefore, functionalizing a {device.type} RNG operator is " + "not supported. We are discussing the possibility of a Philox-based RNG implementation for CPU." + ) + + +# TODO - We have to register many more distributions here, and also higher level +# ops like dropout which have fused implementation and can hide the rand inside. +@register_rng_decomposition(aten.rand) +def rand(shape, dtype=None, layout=torch.strided, device=None, pin_memory=False): + if device and device.type != "cuda": + throw_on_non_cuda(device) + seed, offset = PhiloxStateTracker.get_state_as_tuple() + dtype = dtype or torch.float32 + out, offset_jump = torch.ops.rngprims.philox_rand( + shape, seed, offset, None, device, dtype + ) + PhiloxStateTracker.advance_offset(offset_jump) + return out + + +@register_rng_decomposition(aten.rand_like) +def rand_like( + x: torch.Tensor, + dtype=None, + layout=None, + device=None, + pin_memory=False, + memory_format=torch.preserve_format, +): + device = device or x.device + if device.type != "cuda": + throw_on_non_cuda(device) + dtype = dtype or x.dtype + seed, offset = PhiloxStateTracker.get_state_as_tuple() + out, offset_jump = torch.ops.rngprims.philox_rand( + x.shape, seed, offset, None, device, dtype + ) + PhiloxStateTracker.advance_offset(offset_jump) + return out + + +class PhiloxState: + """ + Represents a PhiloxRngState - (seed, offset) where offset = base_offset + + relative_offset. seed and base_offset basically point to the rng state just + before tracing starts. relative offset tracks the totally consumed offset at + trace time. + """ + + def __init__(self) -> None: + self.reset() + + def reset(self): + self.seed = torch.tensor(()) + self.base_offset = torch.tensor(()) + self.relative_offset = 0 + self.offset_advanced_alteast_once = False + + def validate_state(self): + assert self.seed.numel() != 0 and self.base_offset.numel() != 0 + + def advance_offset(self, consumed_offset): + self.offset_advanced_alteast_once = True + self.relative_offset = self.relative_offset + consumed_offset + + def set_state(self, seed, base_offset, relative_offset=0): + self.seed = seed + self.base_offset = base_offset + self.relative_offset = relative_offset + + def get_state_as_tuple(self): + self.validate_state() + return (self.seed, self.base_offset + self.relative_offset) + + def get_state_as_tensor(self): + # Only needed because we override get_rng_state. + self.validate_state() + return torch.stack([self.seed, self.base_offset + self.relative_offset]) + + def set_state_from_tensor(self, state): + # Only needed because we override set_rng_state. + self.seed, self.base_offset = torch.unbind(state) + self.relative_offset = 0 + + +class PhiloxStateTracker: + """ + Singleton class to track the philox rng state during AOT Autograd tracing. + For each aot tracing instance, AOT Autograd resets this tracker and keeps + track of both forward and backward offsets. At runtime, we only care about + the total consumed forward and backward offsets. For dynamic shapes, these + offsets are a function of input shapes. Therefore, the AOT generated graphs + have additional outputs that compute total consumed forward and backward + offsets. + """ + + running_state: PhiloxState + fwd_state: PhiloxState + bwd_state: PhiloxState + + def __enter__(self): + PhiloxStateTracker.reset() + return self + + def __exit__(self, exc_type, exc_cal, exc_tb): + PhiloxStateTracker.reset() + + @classmethod + def reset(cls): + cls.running_state = PhiloxState() + cls.fwd_state = PhiloxState() + cls.bwd_state = PhiloxState() + + @classmethod + def mark_beginning_of_forward(cls): + # Tells the tracker to use fwd_state as the running state + cls.running_state = cls.fwd_state + + @classmethod + def mark_beginning_of_backward(cls): + # Tells the tracker to use bwd_state as the running state + cls.running_state = cls.bwd_state + + @classmethod + def record_state(cls, seed, offset, mode): + # Records the seed and offset tensors. These tensors are used to invoke + # the philox_rand functional primitives. + if mode == "forward": + cls.fwd_state.set_state(seed, offset) + cls.mark_beginning_of_forward() + else: + assert mode == "backward" + cls.bwd_state.set_state(seed, offset) + + @classmethod + def get_state_as_tensor(cls): + # The only reason this exists is because we override get_rng_state and + # set_rng_state during tracing. get_rng_state expects a tensor output, + # so return (seed, offset) tuple upset other parts of the program like + # ctx.saved_tensors. + + # A bad consequence is that if user saves and restores rng state, we + # have little bit of ugliness in the generated code, where we first + # concat the (seed, offset) to create a tensor for get_rng_state, and + # then split it back to get (seed, offset) tuple in set_rng_state. + + # TODO: Investigate if there is be a better way to wrap the tuple in a + # false Tensor object, and then desugar it later on. + return cls.running_state.get_state_as_tensor() + + @classmethod + def get_state_as_tuple(cls): + return cls.running_state.get_state_as_tuple() + + @classmethod + def set_state_from_tensor(cls, x): + # This is only needed because we override set_rng_state. Look at the + # comment in get_state_from_tensor method. + cls.running_state.set_state_from_tensor(x) + + @classmethod + def advance_offset(cls, consumed_offset): + cls.running_state.advance_offset(consumed_offset) + + @classmethod + def get_current_relative_offset(cls): + return cls.running_state.relative_offset + + @staticmethod + def multiple_of_4(offset): + # torch cuda rng state offset must be a multiple of 4. For inductor, as + # we sum up all the numel, the result might not be a multiple of 4. This + # method achieves that. + return (offset + 3) // 4 * 4 + + @classmethod + def get_updated_fwd_offset(cls): + # Short circuit if no rand ops were observed + if not cls.fwd_state.offset_advanced_alteast_once: + return cls.fwd_state.base_offset + return cls.multiple_of_4( + cls.fwd_state.base_offset + cls.fwd_state.relative_offset + ) + + @classmethod + def get_updated_bwd_offset(cls): + # Short circuit if no rand ops were observed + if not cls.bwd_state.offset_advanced_alteast_once: + return cls.bwd_state.base_offset + return cls.multiple_of_4( + cls.bwd_state.base_offset + cls.bwd_state.relative_offset + ) + + +# Adding more decompositions which eventually use rand_like inside decomps. +# Adding these in rng_decompositions ensures the functionalization of rand_like +# ops used in these decomps. The list is copied from inductor codebase, which +# uses it for similar purpose. +# +# Caution - These decomps do not have same accuracy as that of eager. However, +# we can't just disable them with a config flag like fallback_random, because +# for functionalization of rng ops, we have to decompose these ops. +extra_random_decomps = get_decompositions( + [ + aten.cauchy, + aten.cauchy_, + aten.exponential, + aten.exponential_, + aten.geometric, + aten.geometric_, + aten.native_dropout, + aten.normal, + aten.normal_, + aten.normal_functional, + aten.log_normal, + aten.log_normal_, + aten.rrelu_with_noise, + aten.rrelu_with_noise_, + aten.uniform_, + ] +) +register_extra_random_decomp = functools.partial( + decomp.register_decomposition, registry=extra_random_decomps +) + + +@register_extra_random_decomp([aten.bernoulli_]) +def bernoulli_(self, p=0.5): + if self.device == torch.device("cpu"): + return NotImplemented + return self.copy_(torch.rand_like(self, dtype=torch.float32) < p) + + +@register_extra_random_decomp([aten.bernoulli.p]) +def bernoulli_p(self, p=0.5, *, generator=None): + if self.device == torch.device("cpu"): + return NotImplemented + assert generator is None + return torch.rand_like(self, dtype=torch.float32) < p + + +rng_decompositions.update(extra_random_decomps) # type: ignore[arg-type] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dispatch/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dispatch/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dispatch/python.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dispatch/python.py new file mode 100644 index 0000000000000000000000000000000000000000..98f6ccf78bb89e37631a43bfa557aef381222d1b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dispatch/python.py @@ -0,0 +1,192 @@ +# mypy: allow-untyped-defs +import itertools +import unittest.mock +from collections.abc import Callable, Iterator +from contextlib import contextmanager +from typing import TypeVar, Union +from typing_extensions import ParamSpec + +import torch +import torch._C +import torch._ops +import torch.utils._python_dispatch +import torch.utils._pytree as pytree +from torch._C import DispatchKey + + +__all__ = ["enable_python_dispatcher", "no_python_dispatcher", "enable_pre_dispatch"] + +no_python_dispatcher = torch._C._DisablePythonDispatcher +enable_python_dispatcher = torch._C._EnablePythonDispatcher +enable_pre_dispatch = torch._C._EnablePreDispatch + +CROSSREF_FUNCTIONALIZE = False + +_P = ParamSpec("_P") +_T = TypeVar("_T") + + +def all_py_loaded_overloads() -> Iterator[torch._ops.OpOverload]: + """ + Warning: the set of overloads this will report is very subtle. It is precisely + the set of torch.ops functions that have actually been accessed from Python + (e.g., we actually called torch.ops.aten.blah at some point. This is DIFFERENT + from the set of registered operators, which will in general be a larger set, + as this would include all operators which we ran C++ static initializers or + Python operator registration on. This does not eagerly populate the list on + torch.ops.aten; this list is lazy! + + In other words, this is good for traversing over everything that has an + OpOverload object allocated in Python. We use it for cache invalidation, but + don't rely on this list being complete. + + Note that even if we did report all C++ registered overloads, this isn't guaranteed + to be complete either, as a subsequent lazy load of a library which triggers more + registrations could add more things to the set. + """ + for ns in torch.ops: + packets = getattr(torch.ops, ns) + for op_name in packets: + packet = getattr(packets, op_name) + for overload in packet: + yield getattr(packet, overload) + + +@contextmanager +def suspend_functionalization(): + f_tls = torch._C._dispatch_tls_is_dispatch_key_included( + torch._C.DispatchKey.Functionalize + ) + f_rv = torch._C._functionalization_reapply_views_tls() + if f_tls: + torch._disable_functionalization() + try: + yield + finally: + if f_tls: + torch._enable_functionalization(reapply_views=f_rv) + + +def check_tensor_metadata_matches(nv, rv, desc): + assert callable(desc) + assert nv.size() == rv.size(), f"{desc()}: sizes {nv.size()} != {rv.size()}" + assert nv.dtype == rv.dtype, f"{desc()}: dtype {nv.dtype} != {rv.dtype}" + same_strides, idx = torch._prims_common.check_significant_strides( + nv, rv, only_cuda=False + ) + assert same_strides, ( + f"{desc()}: strides {nv.stride()} != {rv.stride()} (mismatch at index {idx})" + ) + + +def check_metadata_matches(n, r, desc): + assert callable(desc) + n_vals, _n_spec = pytree.tree_flatten(n) + r_vals, _r_spec = pytree.tree_flatten(r) + # TODO: test the specs match; empirically sometimes we have a tuple + # on one side and a list on the other + assert len(n_vals) == len(r_vals), f"{len(n_vals)} != {len(r_vals)}" + for i, nv, rv in zip(range(len(n_vals)), n_vals, r_vals): + if not isinstance(rv, torch.Tensor): + continue + check_tensor_metadata_matches(nv, rv, lambda: f"{desc()} output {i}") + + +class Lit: + def __init__(self, s): + self.s = s + + def __repr__(self): + return self.s + + +def _fmt(a: object) -> object: + if isinstance(a, torch.Tensor): + return Lit( + f"torch.empty_strided({tuple(a.size())}, {a.stride()}, dtype={a.dtype})" + ) + else: + return a + + +def make_crossref_functionalize( + op: torch._ops.OpOverload[_P, _T], final_key: DispatchKey +) -> Union[Callable[_P, _T], DispatchKey]: + from torch._subclasses.fake_tensor import FakeTensorMode + + # This case is pretty weird, suppress it for now + if op is torch.ops.aten.lift_fresh.default: + return final_key + + def handler(*args: _P.args, **kwargs: _P.kwargs) -> _T: + fake_mode = FakeTensorMode() + + def fakeify_defun(t): + if isinstance(t, torch.Tensor): + if torch._is_functional_tensor(t): + r = torch._from_functional_tensor(t) + # NB: This assumes that the inner tensor sizes/strides match + # the outer tensor sizes/strides. This doesn't necessarily have to + # be the case, see discussion at + # https://github.com/pytorch/pytorch/pull/87610/files/401ddeda1d769bedc88a12de332c7357b60e51a4#r1007264456 + assert t.size() == r.size() + assert t.stride() == r.stride() + else: + r = t + # TODO: suppress guards + return fake_mode.from_tensor(r) + return t + + def maybe_detach(t): + if isinstance(t, torch.Tensor): + return t.detach() + else: + return t + + # TODO: This probably does the wrong thing if you're running other + # substantive modes with the normal op outside here + with ( + torch.utils._python_dispatch._disable_current_modes(), + suspend_functionalization(), + ): + f_args, f_kwargs = pytree.tree_map(fakeify_defun, (args, kwargs)) + orig_f_args, orig_f_kwargs = pytree.tree_map( + maybe_detach, (f_args, f_kwargs) + ) + with fake_mode: + f_r = op(*f_args, **f_kwargs) # pyrefly: ignore [invalid-param-spec] + r = op._op_dk(final_key, *args, **kwargs) + + def desc(): + fmt_args = ", ".join( + itertools.chain( + (repr(pytree.tree_map(_fmt, a)) for a in orig_f_args), + ( + f"{k}={pytree.tree_map(_fmt, v)}" + for k, v in orig_f_kwargs.items() + ), + ) + ) + return f"{op}({fmt_args})" + + check_metadata_matches(f_r, r, desc) + return r + + return handler + + +# NB: enabling this is slow, don't do it in a hot loop. This is purely +# for debugging purposes. +@contextmanager +def enable_crossref_functionalize(): + for op in all_py_loaded_overloads(): + op._uncache_dispatch(torch._C.DispatchKey.Functionalize) + try: + with ( + enable_python_dispatcher(), + unittest.mock.patch("torch._dispatch.python.CROSSREF_FUNCTIONALIZE", True), + ): + yield + finally: + for op in all_py_loaded_overloads(): + op._uncache_dispatch(torch._C.DispatchKey.Functionalize) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4de5f712e16d64c0293dcd6ce38c41e04130ad36 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/__init__.py @@ -0,0 +1,216 @@ +""" +TorchDynamo is a Python-level JIT compiler designed to make unmodified PyTorch programs faster. +TorchDynamo hooks into the frame evaluation API in CPython (PEP 523) to dynamically modify Python +bytecode right before it is executed. It rewrites Python bytecode in order to extract sequences of +PyTorch operations into an FX Graph which is then just-in-time compiled with a customizable backend. +It creates this FX Graph through bytecode analysis and is designed to mix Python execution with +compiled backends to get the best of both worlds: usability and performance. This allows it to +seamlessly optimize PyTorch programs, including those using modern Python features. +""" + +import torch + +from . import ( + aot_compile, + config, + convert_frame, + eval_frame, + functional_export, + resume_execution, +) +from .backends.registry import list_backends, lookup_backend, register_backend +from .callback import callback_handler, on_compile_end, on_compile_start +from .code_context import code_context +from .convert_frame import replay +from .decorators import ( + allow_in_graph, + assume_constant_result, + disable, + disable_nested_graph_breaks, + disallow_in_graph, + dont_skip_tracing, + error_on_graph_break, + forbid_in_graph, + graph_break, + is_dynamo_disable_recursive, + mark_dynamic, + mark_static, + mark_static_address, + maybe_mark_dynamic, + nonstrict_trace, + patch_dynamo_config, + run, + set_stance, + skip_frame, + step_unsupported, + substitute_in_graph, +) +from .eval_frame import ( + _reset_guarded_backend_cache, + explain, + export, + is_dynamo_supported, + is_inductor_supported, + optimize, + optimize_assert, + OptimizedModule, + reset_code, +) + +# pyrefly: ignore [deprecated] +from .external_utils import is_compiling +from .mutation_guard import GenerationTracker +from .pgo import reset_code_state +from .symbolic_convert import TensorifyState +from .utils import ( + graph_break_reasons, + guard_failures, + orig_code_map, + register_hook_for_recompile_user_context, + reset_frame_count, + reset_recompile_user_contexts, +) + + +# Register polyfill functions +from .polyfills import loader as _ # usort: skip # noqa: F401 + + +__all__ = [ + "allow_in_graph", + "assume_constant_result", + "config", + "disable", + "disable_nested_graph_breaks", + "disallow_in_graph", + "dont_skip_tracing", + "export", + "explain", + "forbid_in_graph", + "graph_break", + "is_compiling", + "is_dynamo_disable_recursive", + "list_backends", + "lookup_backend", + "mark_dynamic", + "maybe_mark_dynamic", + "mark_static", + "mark_static_address", + "nonstrict_trace", + "optimize", + "optimize_assert", + "OptimizedModule", + "patch_dynamo_config", + "register_backend", + "replay", + "reset", + "reset_recompile_user_contexts", + "run", + "error_on_graph_break", + "set_recursion_limit", + "set_stance", + "skip_frame", + "step_unsupported", + "substitute_in_graph", +] + +# allowlist this for weights_only load of NJTs +torch.serialization.add_safe_globals([torch._dynamo.decorators._DimRange]) + +if torch.manual_seed is torch.random.manual_seed: + import torch.jit._builtins + + # Wrap manual_seed with the disable decorator. + # Can't do it at its implementation due to dependency issues. + torch.manual_seed = torch._disable_dynamo(torch.manual_seed) + # Add the new manual_seed to the builtin registry. + torch.jit._builtins._register_builtin(torch.manual_seed, "aten::manual_seed") + + +def reset() -> None: + """ + Clear all compile caches and restore initial state. This function is intended + to reset Dynamo's state *as if* you had started a fresh process invocation, which + makes it good for testing scenarios where you want to behave as if you started + a new process. It does NOT affect any file system caches. + + NB: this does NOT reset logging state. Don't use this to test logging + initialization/reinitialization. + """ + # TODO: https://github.com/pytorch/pytorch/issues/139200 + import logging + + log = logging.getLogger(__name__) + log.info("torch._dynamo.reset") + with convert_frame.compile_lock: + reset_code_caches() + convert_frame.input_codes.clear() + reset_code_state() + convert_frame.output_codes.clear() + orig_code_map.clear() + guard_failures.clear() + graph_break_reasons.clear() + resume_execution.ContinueExecutionCache.cache.clear() + _reset_guarded_backend_cache() + reset_frame_count() + torch._dynamo.compiled_autograd.reset() + convert_frame.FRAME_COUNTER = 0 + convert_frame.FRAME_COMPILE_COUNTER.clear() + callback_handler.clear() + GenerationTracker.clear() + TensorifyState.clear() + torch._dynamo.utils.warn_once_cache.clear() + torch._C._autograd._saved_tensors_hooks_set_tracing(False) + + +def reset_code_caches() -> None: + """ + Clears in-memory code cache, which is what stores compiled products. This + resets less state than :func:`reset` and is mostly only used for testing + purposes. + """ + # TODO: https://github.com/pytorch/pytorch/issues/139200 + import logging + + log = logging.getLogger(__name__) + log.info("torch._dynamo.reset_code_caches") + """Clear compile caches that are keyed by code objects""" + with convert_frame.compile_lock: + reset_code_state() + for weak_code in ( + convert_frame.input_codes.seen + convert_frame.output_codes.seen + ): + code = weak_code() + if code: + reset_code(code) + code_context.clear() + + +def get_recursion_limit() -> int: + """ + Returns the internal dynamo recursion limit set by `torch._dynamo.set_recursion_limit`. + + Returns -1 if no c recursion limit has been set. + """ + return torch._C._dynamo.eval_frame.get_c_recursion_limit() + + +def set_recursion_limit(limit: int) -> None: + """ + Sets an internal dynamo recursion limit. The limit must be >= 1, or -1 to reset + to the default (unset) state. + + This is possibly needed in Python 3.12-3.13 since there is a separate C recursion limit + that is not visible at the Python level. If you are getting RecursionErrors during + Dynamo compilation and `sys.setrecursionlimit()` doesn't help, this function may alleviate + the issue. + + NOTE: this function does NOT call `sys.setrecursionlimit()` - the user is expected to manually + call this if required. This is because the 2 recursion limits are not sync'd up - e.g. in + Python 3.12, functions can be inline-evaluated, which apparently doesn't use up the C stack. + + WARNING: increasing the recursion limit to an arbitrary large value may cause segfaults + due to stack overflows! You can try also try to manually increase the stack size, e.g. + with `$ ulimit -s ...` + """ + torch._C._dynamo.eval_frame.set_c_recursion_limit(limit) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/_trace_wrapped_higher_order_op.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/_trace_wrapped_higher_order_op.py new file mode 100644 index 0000000000000000000000000000000000000000..1de308b8037028ced08f75912e59151ff570096b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/_trace_wrapped_higher_order_op.py @@ -0,0 +1,250 @@ +"""trace_wrapped(*args, fn) is equivalent to fn(*args), but with a twist: +if you make_fx trace through this call, we will not actually trace into fn; instead, +we will directly insert it as a call_function to fn in the graph. +(Unlike make_fx, Dynamo WILL inline into fn.) +You can think of this as a one off allow_in_graph equivalent for proxy tensor tracing. + +Because proxy tensor tracing does not actually run the function, there are +requirements on the behavior of fn. We are still figuring it out, but here is the current state: + +1) fn SHOULD only take a single argument, which must be a tensor +2) fn MUST return a new tensor with the same metadata as the original tensor + (e.g., zeros_like(input) is a permissible implementation of fn). + This is verified via an extra assert that is inserted into the traced graph. +3) fn MAY have side effects, but it MAY NOT perform metadata mutation on other tensors + participating in proxy tensor tracing (it MAY mutate other tensors, it MAY mutate Python state) +These requirements stem from the requirement that we need to continue performing proxy tensor tracing, +which assumes accurate fake tensor metadata, without actually running fn. +In the future, we may allow for a "meta" function associated with fn to allow for more interesting input-output patterns. + +Note that tensors / Python state are allowed to be mutated. +This is relaxed constraint is not always sound, but it is sound for backward tracing with fake +tensors as it takes place in AOTAutograd, as the backward pass is guaranteed not to depend on concrete +tensor values (via fake tensor) or Python state (because the autograd engine doesn't depend on Python). + +The intended use case for this function is to allow AOTAutograd to defer complex +backward hooks to compiled autograd. AOTAutograd performs a make_fx trace which preserves +the function call as is in the graph, and only when we Dynamo through the backward graph in +compiled autograd do we inline into the function. +""" + +from typing import Any, Optional + +import torch +import torch.utils._pytree as pytree +from torch._C import DispatchKey +from torch._higher_order_ops.utils import autograd_not_implemented +from torch._ops import HigherOrderOperator, OpOverload +from torch._subclasses import FakeTensorMode +from torch.fx.experimental._backward_state import BackwardState +from torch.fx.experimental.proxy_tensor import ProxyTorchDispatchMode, track_tensor_tree +from torch.overrides import TorchFunctionMode +from torch.utils._python_dispatch import _get_current_dispatch_mode +from torch.utils._pytree import tree_map_only + + +Tensor = torch.Tensor + + +__all__ = ["trace_wrapped"] + + +@torch.library.custom_op("flex_lib::zeros_and_scatter", mutates_args=()) # type: ignore[misc] +def zeros_and_scatter( + shape: list[int], + indices: list[Tensor], + vals: Tensor, +) -> Tensor: + """Custom Op so that we can register a custom lowering for the new_output + scatter in the backwards pass""" + grad = torch.zeros(shape, device=vals.device, dtype=vals.dtype) + return torch.ops.aten.index_put(grad, indices, vals, accumulate=True) + + +@zeros_and_scatter.register_fake # type: ignore[misc] +def _( + shape: list[int], + indices: list[Tensor], + vals: Tensor, +) -> Tensor: + return vals.new_empty(shape) + + +@zeros_and_scatter.register_vmap # type: ignore[misc] +def _(info, indims, shape, indices, value): # type: ignore[no-untyped-def] + """The batching rule is special in that it returns a tensor that is not batched""" + indices_indims = indims[1] + expanded_indices = [] + for idx, idx_indim in zip(indices, indices_indims): + # The index is not a being batched, we should unsqueeze and expand to val + if idx_indim is None: + expanded_indices.append(idx.expand(value.shape)) + else: + # the index is being part of the vmap batch, it should be the same size as val + assert idx.shape == value.shape + expanded_indices.append(idx) + + out = torch.ops.flex_lib.zeros_and_scatter( + shape, + expanded_indices, + value, + ) + return out, None + + +class ModIndex(torch.autograd.Function): + generate_vmap_rule = True + + @staticmethod + # pyrefly: ignore [bad-override] + def forward(x: Tensor, indices: list[Tensor]) -> Tensor: + return torch.ops.aten.index(x, indices) + + @staticmethod + def setup_context(ctx: Any, inputs: tuple[Any, ...], output: Any) -> None: + x, indices = inputs + ctx.save_for_backward(*indices) + ctx.input_shape = x.shape + + @staticmethod + def backward(ctx, gradOut): # type: ignore[no-untyped-def] + indices = ctx.saved_tensors + return ( + torch.ops.flex_lib.zeros_and_scatter( + ctx.input_shape, + indices, + gradOut, + ), + None, + ) + + @classmethod + @torch._export.wrappers.allow_in_pre_dispatch_graph + def apply(cls, *args, **kwargs): # type: ignore[no-untyped-def] + return super().apply(*args, **kwargs) + + +mod_index = ModIndex.apply + + +class TransformGetItemToIndex(TorchFunctionMode): + # This is needed since we want to support calling + # A[q_idx], where q_idx is a scalar tensor in score_mod. + # Today, when q_idx is a scalar tensor, we implicitly convert it to a python + # scalar and create a view. We do not want that behavior in this case, so we + # use this torchfunctionmode to override that behavior for score_mod + # wherever we're running it. + def __torch_function__( + self, + func: OpOverload, + types: tuple[torch._C._TensorMeta, ...], + args: tuple[object, ...] = (), + kwargs: Optional[dict[str, object]] = None, + ) -> object: + if func is torch.Tensor.__getitem__: + index_args = pytree.tree_leaves(args[1]) + if all(isinstance(x, torch.Tensor) for x in index_args): + return mod_index(args[0], index_args) + return func(*args, **(kwargs or {})) + + +def trace_wrapped(*args: Any, **kwargs: Any) -> Any: + with torch.no_grad(): + return _trace_wrapped_op(*args, **kwargs) + + +class TraceWrapped(HigherOrderOperator): + def __init__(self) -> None: + super().__init__("trace_wrapped") + + def __call__(self, *args: Any, **kwargs: Any) -> Any: + return super().__call__(*args, **kwargs) + + +# TODO(jansel): need to ensure this does not get DCEed +_trace_wrapped_op = TraceWrapped() + + +def _assert_meta( + grad: torch.Tensor, + size: tuple[int, ...], + stride: tuple[int, ...], + dtype: torch.dtype, +) -> torch.Tensor: + assert grad.size() == size, "size mismatch" + assert grad.stride() == stride, "stride mismatch" + assert grad.dtype == dtype, "dtype mismatch" + return grad + + +@_trace_wrapped_op.py_impl(ProxyTorchDispatchMode) +def inner_trace( + mode: ProxyTorchDispatchMode, + *args: Any, + bw_state: Optional[BackwardState] = None, + **kwargs: Any, +) -> Any: + def self_invoke(*args: Any, **dyn_kwargs: Any) -> Any: + with torch.no_grad(): + return _trace_wrapped_op(*args, **dyn_kwargs, **kwargs) + + def unwrap_proxies(x: Any) -> Any: + if isinstance(x, torch.Tensor): + return mode.tracer.unwrap_proxy(x) # type: ignore[union-attr] + if isinstance(x, (list, tuple)): + return type(x)(map(unwrap_proxies, x)) + if x is None: + return None + raise AssertionError(f"unhandled type: {type(x)}") + + proxy_kwargs = {} + if bw_state is not None: + assert isinstance(bw_state, BackwardState) and bw_state.proxy is not None + proxy_kwargs["bw_state"] = bw_state.proxy + out_proxy = mode.tracer.create_proxy( + "call_function", + self_invoke, + unwrap_proxies(args), + proxy_kwargs, + name="trace_wrapped", + ) + + if args[0] is None: + grad = args[1] # module backward hooks + else: + grad = args[0] # other backward hooks + grad = tree_map_only(torch.Tensor, torch.empty_like, grad) + track_tensor_tree(grad, out_proxy, constant=None, tracer=mode.tracer) + return grad + + +@_trace_wrapped_op.py_impl(FakeTensorMode) +def inner_fake(*args: Any, **kwargs: Any) -> None: + raise RuntimeError("This op should never be invoked here") + + +@_trace_wrapped_op.py_impl(DispatchKey.CompositeExplicitAutograd) +def _trace_wrapped_op_dense(*args: Any, fn: Any, **kwargs: Any) -> Any: + mode = _get_current_dispatch_mode() + assert mode is None, "Mode should never be enabled for CPU/CUDA key" + return fn(*args, **kwargs) + + +_trace_wrapped_op.py_impl(DispatchKey.Autograd)( + autograd_not_implemented(_trace_wrapped_op, deferred_error=True) +) + + +@_trace_wrapped_op.py_functionalize_impl +def _trace_wrapped_functionalized(ctx: Any, *args: Any, **kwargs: Any) -> Any: + unwrapped_args = ctx.unwrap_tensors(args) + with ctx.redispatch_to_next(): + return ctx.wrap_tensors(_trace_wrapped_op(*unwrapped_args, **kwargs)) + + +def autograd_function_backward_rewritten(original_backward: Any) -> Any: + def new_backward(ctx: Any, *grads: Any) -> Any: + # pyrefly: ignore [bad-assignment] + grads = [g.contiguous() for g in grads] + return original_backward(ctx, *grads) + + return new_backward diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/aot_compile.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/aot_compile.py new file mode 100644 index 0000000000000000000000000000000000000000..7bc03aff84a20b0a73783eafcadc6b37aa1b56d1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/aot_compile.py @@ -0,0 +1,369 @@ +import dataclasses +import inspect +import io +import logging +import pickle +import types +from collections.abc import Callable +from contextlib import AbstractContextManager, ExitStack +from dataclasses import dataclass +from typing import Any, Optional, TYPE_CHECKING + +import torch +import torch.fx +from torch._dynamo.convert_frame import GraphRuntimeEnv +from torch._dynamo.graph_utils import _graph_device_type +from torch._dynamo.package import SystemInfo + +from . import convert_frame +from .aot_compile_types import ( + BundledAOTAutogradSerializableCallable, + SerializableCallable, +) +from .hooks import Hooks + + +if TYPE_CHECKING: + from .guards import GuardManagerWrapper + from .package import SourceInfo + + +log = logging.getLogger(__name__) + + +def bind_locals( + signature: inspect.Signature, *args: Any, **kwargs: Any +) -> dict[str, Any]: + bound_arguments = signature.bind(*args, **kwargs) + bound_arguments.apply_defaults() + return bound_arguments.arguments + + +@dataclass +class CompileArtifacts: + signature: inspect.Signature + guard_manager: Optional["GuardManagerWrapper"] + guards_state: bytes + backend_id: str + compiled_fn: SerializableCallable + original_code: types.CodeType + runtime_env: GraphRuntimeEnv + source_info: "SourceInfo" + device_type: str + backend_name: str + system_info: SystemInfo = dataclasses.field(default_factory=SystemInfo.current) + + def check_compatibility(self) -> None: + current_system = SystemInfo.current() + current_system.check_compatibility(self.system_info, self.device_type) + + +class AOTCompilePickler(pickle.Pickler): + @classmethod + def _unpickle_cell(cls, val: Any) -> Any: + def _() -> Any: + return val + + assert _.__closure__ is not None + return _.__closure__[0] + + # pyrefly: ignore [bad-override] + def reducer_override(self, obj: Any) -> Any: + if isinstance(obj, type((lambda x: lambda: x)(0).__closure__[0])): # type: ignore[index] # noqa: PLC3002 + return type(self)._unpickle_cell, (obj.cell_contents,) + return NotImplemented + + +@dataclass +class AOTCompiledFunction: + _artifacts: CompileArtifacts + _guard_check_enabled: bool = True + _extra_globals: Optional[dict[str, object]] = None + + def guard_check(self, *args: Any, **kwargs: Any) -> bool: + f_locals: dict[str, Any] = {} + env = self._artifacts.runtime_env + if env.closure: + assert env.bytecode.co_freevars and len(env.closure) == len( + env.bytecode.co_freevars + ) + f_locals = { + name: cell.cell_contents + for name, cell in zip(env.bytecode.co_freevars, env.closure) + } + f_locals.update(bind_locals(self._artifacts.signature, *args, **kwargs)) + assert self._artifacts.guard_manager is not None + return self._artifacts.guard_manager.check(f_locals) + + def __post_init__(self) -> None: + from .package import load_guard_manager, load_guards_state + + self._artifacts.check_compatibility() + + # pyrefly: ignore [read-only] + self.fn = self._artifacts.runtime_env.forward_callable( + self._artifacts.backend_id, + self._artifacts.compiled_fn, + extra_globals=self._extra_globals, + ) + + if self._artifacts.guard_manager is None: + guards_state = load_guards_state(self._artifacts.guards_state) + self._artifacts.guard_manager = load_guard_manager( + guards_state, + self._artifacts.original_code, + self.fn.__globals__, + ) + + def __call__(self, *args: Any, **kwargs: Any) -> Any: + assert self._artifacts.guard_manager is not None + if self._guard_check_enabled and not self.guard_check(*args, **kwargs): + f_locals = bind_locals(self._artifacts.signature, *args, **kwargs) + reason = str(self._artifacts.guard_manager.check_verbose(f_locals)) + raise RuntimeError(f"GuardManager check failed, reason: {reason}") + return self.fn(*args, **kwargs) + + def source_info(self) -> "SourceInfo": + return self._artifacts.source_info + + def save_compiled_function(self, path: str) -> None: + with open(path, "wb") as f: + f.write(type(self).serialize(self)) + + @classmethod + def serialize(cls, fn: "AOTCompiledFunction") -> bytes: + from torch._dynamo.package import SerializedCode + + state = fn._artifacts.__dict__.copy() + state["guard_manager"] = None + state["runtime_env"] = dataclasses.replace( + state["runtime_env"], + bytecode=SerializedCode.from_code_object(state["runtime_env"].bytecode), + ) + compiled_fn = state["compiled_fn"] + state["compiled_fn"] = ( + type(compiled_fn).deserialize_compile_artifacts, + type(compiled_fn).serialize_compile_artifacts(compiled_fn), + ) + state["original_code"] = SerializedCode.from_code_object(state["original_code"]) + buf = io.BytesIO() + pickler = AOTCompilePickler(buf) + pickler.dump(state) + return buf.getvalue() + + @classmethod + def deserialize( + cls, data: bytes, f_globals: Optional[dict[str, object]] = None + ) -> "AOTCompiledFunction": + from torch._dynamo.package import SerializedCode + + state = pickle.loads(data) + state["runtime_env"] = dataclasses.replace( + state["runtime_env"], + bytecode=SerializedCode.to_code_object(state["runtime_env"].bytecode), + ) + deserializer, compiled_fn_state = state["compiled_fn"] + with torch._inductor.config.patch(enable_autograd_for_aot=True): + state["compiled_fn"] = deserializer(compiled_fn_state) + state["original_code"] = SerializedCode.to_code_object(state["original_code"]) + + artifacts = CompileArtifacts(**state) + return cls(artifacts, _extra_globals=f_globals) + + def disable_guard_check(self) -> None: + self._guard_check_enabled = False + + +def aot_compile_fullgraph( + model: Any, + example_inputs: tuple[tuple[Any, ...], dict[str, Any]], + hooks: Hooks, + backend: Callable[[torch.fx.GraphModule, list[torch.Tensor]], SerializableCallable], +) -> AOTCompiledFunction: + from torch._dynamo.guards import CheckFunctionManager + from torch._dynamo.package import SourceInfo + from torch._dynamo.utils import dynamo_timed, get_metrics_context + from torch._guards import TracingContext + + args, kwargs = example_inputs + + with ( + get_metrics_context(), + dynamo_timed("fullgraph_capture"), + torch._functorch.config.patch(strict_autograd_cache=True), + ): + capture_output = convert_frame.fullgraph_capture(model, args, kwargs) + graph_capture_output = capture_output.graph_capture_output + assert graph_capture_output.output_graph is not None + + if not hooks.guard_filter_fn: + from torch._dynamo.types import GuardFilterEntry + + def new_guard_filter_fn( + guard_entries: list[GuardFilterEntry], + ) -> list[bool]: + return [ + ( + not ( + g.is_global + or g.guard_type + in CheckFunctionManager.UNSUPPORTED_SERIALIZATION_GUARD_TYPES + ) + ) + for g in guard_entries + ] + + hooks.guard_filter_fn = new_guard_filter_fn + + fn, _ = convert_frame.get_traced_fn(model) + + backend_input = capture_output.backend_input + assert backend_input is not None + backend_input.graph_module._backend_id = backend_input.backend_id # type: ignore[assignment] + device_type = _graph_device_type(backend_input.graph_module.graph) + assert ( + backend_input.fake_mode.shape_env + is graph_capture_output.output_graph.shape_env + ) + tracing_context = TracingContext(backend_input.fake_mode) + tracing_context.tensor_to_context = backend_input.tensor_to_context + with ( + torch._guards.tracing(tracing_context), + torch._functorch.config.patch( + { + "bundled_autograd_cache": True, + "force_non_lazy_backward_lowering": True, + } + ), + ): + compiled_fn = backend( + backend_input.graph_module, backend_input.example_inputs + ) + # If Inductor backend is used, grab the compiled_fn from PrecompileContext + # TODO: this should be replaced once we make the backend return the SerializableCallable directly. + if isinstance(backend, torch._TorchCompileInductorWrapper): + compiled_fn = BundledAOTAutogradSerializableCallable(compiled_fn) + + if not isinstance(compiled_fn, SerializableCallable): + if hasattr(backend, "compiler_fn"): + compiler_fn = backend.compiler_fn + else: + compiler_fn = backend + raise RuntimeError( + f"Compiled function type {type(compiled_fn)} (produced " + + f"from backend {compiler_fn}) does not implement SerializableCallable." + ) + + check_fn = graph_capture_output.build_guards( + fn.__code__, hooks=hooks, save=True, strict_error=True + ) + + assert check_fn.guards_state is not None + + source_info = SourceInfo(inlined_sources=set()) + for traced_code in graph_capture_output.traced_code: + source_info.add_code(traced_code) + + artifacts = CompileArtifacts( + signature=convert_frame._get_signature(fn), + guard_manager=check_fn.guard_manager, + guards_state=check_fn.guards_state, + backend_id=backend_input.backend_id, + compiled_fn=compiled_fn, + original_code=fn.__code__, + runtime_env=graph_capture_output.get_runtime_env(), + source_info=source_info, + device_type=device_type, + backend_name=getattr(backend, "compiler_name", "unknown"), + ) + aot_compiled_fn = AOTCompiledFunction( + _artifacts=artifacts, _extra_globals=fn.__globals__ + ) + + return aot_compiled_fn + + +@dataclass +class ModelInput: + """ + WIP type: represents a single model input + Which consists of a tuple of arguments and a set of contexts in which to run the model. + + For each ModelInput, we'll compile one full graph of the model, and then use the guards generated + to dispatch between the compiled graphs. + + + """ + + args: tuple[Any] + kwargs: dict[str, Any] + contexts: list[AbstractContextManager[Any]] + + +@dataclass +class AOTCompiledModel: + # Represents a single forward function of a model along with dispatch + # compiled_results is serializable. We require the model to deserialize again. + model: torch.nn.Module + compiled_results: list[AOTCompiledFunction] + + def __call__(self, *args: Any, **kwargs: Any) -> Any: + for result in self.compiled_results: + if result.guard_check(self.model, *args, **kwargs): + return result(self.model, *args, **kwargs) + # All guards failed, just run one of them and throw the guard check error. + return self.compiled_results[0](self.model, *args, **kwargs) + + def serialize(self) -> bytes: + data: list[bytes] = [] + for result in self.compiled_results: + data.append(AOTCompiledFunction.serialize(result)) + return pickle.dumps(data) + + @classmethod + def deserialize(cls, model: torch.nn.Module, data: bytes) -> "AOTCompiledModel": + from torch._dynamo.utils import get_metrics_context + from torch._guards import compile_context, CompileContext + + results: list[bytes] = pickle.loads(data) + compiled_results = [] + for result in results: + with ( + compile_context(CompileContext(convert_frame.get_compile_id({}))), + get_metrics_context(), + ): + compiled_results.append(AOTCompiledFunction.deserialize(result)) + return cls(model, compiled_results) + + +def aot_compile_module( + model: torch.nn.Module, + inputs: list[ModelInput], + hooks: Hooks, + backend: Callable[[torch.fx.GraphModule, list[torch.Tensor]], SerializableCallable], +) -> AOTCompiledModel: + """ + Compiles a single nn.Module with any number of inputs, and returns a compiled forward function. + """ + + def compile_single_graph(model_input: ModelInput) -> AOTCompiledFunction: + example_inputs = (model_input.args, model_input.kwargs) + orig_forward = model.forward + with ExitStack() as stack: + for ctx in model_input.contexts: + stack.enter_context(ctx) + return aot_compile_fullgraph( + orig_forward, + example_inputs, + hooks=hooks, + backend=backend, + ) + + compiled_results = [] + for model_input in inputs: + log.info("Compiling input %s..", model_input) + compiled_results.append(compile_single_graph(model_input)) + + assert len(compiled_results) > 0 + + return AOTCompiledModel(model, compiled_results) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/aot_compile_types.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/aot_compile_types.py new file mode 100644 index 0000000000000000000000000000000000000000..4a6604681bbfbc4a3bc3852ef6cb6defd3800ccb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/aot_compile_types.py @@ -0,0 +1,65 @@ +import abc +import pickle +from typing import Any + +import torch + + +class SerializableCallable(abc.ABC): + @classmethod + @abc.abstractmethod + def serialize_compile_artifacts(cls, fn: Any) -> bytes: + pass + + @classmethod + @abc.abstractmethod + def deserialize_compile_artifacts(cls, data: bytes) -> Any: + pass + + @abc.abstractmethod + def __call__(self, *args: Any, **kwargs: Any) -> Any: + pass + + +class BundledAOTAutogradSerializableCallable(SerializableCallable): + """ + Represents a serializable callable generated by compile_fx. + This class wraps around the compiled function generated by AOTAutograd. + + TODO: Instead of using PrecompileContext to grab it from AOTAutograd, + this object should be what's *returned* by aot_module_simplified. + We'll do that refactor in a later PR. + """ + + def __init__(self, compiled_fn: Any) -> None: + """ + Takes in a BundledAOTAutogradCacheArtifact, which is the serialized form + of a compiled function generated by AOTAutograd. + """ + assert hasattr(compiled_fn, "serialize") + self.compiled_fn = compiled_fn + + def __getattr__(self, attr: Any) -> Any: + return getattr(self.compiled_fn, attr) + + @classmethod + def serialize_compile_artifacts( + cls, fn: "BundledAOTAutogradSerializableCallable" + ) -> bytes: + with torch._functorch.config.patch("bundled_autograd_cache", True): + result = pickle.dumps(fn.compiled_fn.serialize()) + return result + + @classmethod + def deserialize_compile_artifacts(cls, data: bytes) -> Any: + from torch._functorch._aot_autograd.aot_autograd_result import ( + deserialize_bundled_cache_entry, + ) + + entry = pickle.loads(data) + + compiled_fn = deserialize_bundled_cache_entry(entry) + return cls(compiled_fn) + + def __call__(self, *args: Any, **kwargs: Any) -> Any: + return self.compiled_fn(*args, **kwargs) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/bytecode_analysis.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/bytecode_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..c7a982906b3fef2c10db4147b5defe988b8b2e84 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/bytecode_analysis.py @@ -0,0 +1,265 @@ +""" +This module provides utilities for analyzing and optimizing Python bytecode. +Key functionality includes: +- Dead code elimination +- Jump instruction optimization +- Stack size analysis and verification +- Live variable analysis +- Line number propagation and cleanup +- Exception table handling for Python 3.11+ + +The utilities in this module are used to analyze and transform bytecode +for better performance while maintaining correct semantics. +""" + +import bisect +import dataclasses +import dis +import itertools +import sys +from typing import Any, TYPE_CHECKING, Union + + +if TYPE_CHECKING: + # TODO(lucaskabela): consider moving Instruction into this file + # and refactoring in callsite; that way we don't have to guard this import + from .bytecode_transformation import Instruction + +TERMINAL_OPCODES = { + dis.opmap["RETURN_VALUE"], + dis.opmap["JUMP_FORWARD"], + dis.opmap["RAISE_VARARGS"], + # TODO(jansel): double check exception handling +} +TERMINAL_OPCODES.add(dis.opmap["RERAISE"]) +if sys.version_info >= (3, 11): + TERMINAL_OPCODES.add(dis.opmap["JUMP_BACKWARD"]) + TERMINAL_OPCODES.add(dis.opmap["JUMP_FORWARD"]) +else: + TERMINAL_OPCODES.add(dis.opmap["JUMP_ABSOLUTE"]) +# pyrefly: ignore [unsupported-operation] +if (3, 12) <= sys.version_info < (3, 14): + TERMINAL_OPCODES.add(dis.opmap["RETURN_CONST"]) +if sys.version_info >= (3, 13): + TERMINAL_OPCODES.add(dis.opmap["JUMP_BACKWARD_NO_INTERRUPT"]) +JUMP_OPCODES = set(dis.hasjrel + dis.hasjabs) +JUMP_OPNAMES = {dis.opname[opcode] for opcode in JUMP_OPCODES} +HASLOCAL = set(dis.haslocal) +HASFREE = set(dis.hasfree) + +stack_effect = dis.stack_effect + + +def get_indexof(insts: list["Instruction"]) -> dict["Instruction", int]: + """ + Get a mapping from instruction memory address to index in instruction list. + Additionally checks that each instruction only appears once in the list. + """ + indexof = {} + for i, inst in enumerate(insts): + assert inst not in indexof + indexof[inst] = i + return indexof + + +def remove_dead_code(instructions: list["Instruction"]) -> list["Instruction"]: + """Dead code elimination""" + indexof = get_indexof(instructions) + live_code = set() + + def find_live_code(start: int) -> None: + for i in range(start, len(instructions)): + if i in live_code: + return + live_code.add(i) + inst = instructions[i] + if inst.exn_tab_entry: + find_live_code(indexof[inst.exn_tab_entry.target]) + if inst.opcode in JUMP_OPCODES: + assert inst.target is not None + find_live_code(indexof[inst.target]) + if inst.opcode in TERMINAL_OPCODES: + return + + find_live_code(0) + + # change exception table entries if start/end instructions are dead + # assumes that exception table entries have been propagated, + # e.g. with bytecode_transformation.propagate_inst_exn_table_entries, + # and that instructions with an exn_tab_entry lies within its start/end. + if sys.version_info >= (3, 11): + live_idx = sorted(live_code) + for i, inst in enumerate(instructions): + if i in live_code and inst.exn_tab_entry: + # find leftmost live instruction >= start + start_idx = bisect.bisect_left( + live_idx, indexof[inst.exn_tab_entry.start] + ) + assert start_idx < len(live_idx) + # find rightmost live instruction <= end + end_idx = ( + bisect.bisect_right(live_idx, indexof[inst.exn_tab_entry.end]) - 1 + ) + assert end_idx >= 0 + assert live_idx[start_idx] <= i <= live_idx[end_idx] + inst.exn_tab_entry.start = instructions[live_idx[start_idx]] + inst.exn_tab_entry.end = instructions[live_idx[end_idx]] + + return [inst for i, inst in enumerate(instructions) if i in live_code] + + +def remove_pointless_jumps(instructions: list["Instruction"]) -> list["Instruction"]: + """Eliminate jumps to the next instruction""" + pointless_jumps = { + id(a) + for a, b in itertools.pairwise(instructions) + if a.opname == "JUMP_ABSOLUTE" and a.target is b + } + return [inst for inst in instructions if id(inst) not in pointless_jumps] + + +def propagate_line_nums(instructions: list["Instruction"]) -> None: + """Ensure every instruction has line number set in case some are removed""" + cur_line_no = None + + def populate_line_num(inst: "Instruction") -> None: + nonlocal cur_line_no + if inst.starts_line: + cur_line_no = inst.starts_line + + inst.starts_line = cur_line_no + + for inst in instructions: + populate_line_num(inst) + + +def remove_extra_line_nums(instructions: list["Instruction"]) -> None: + """Remove extra starts line properties before packing bytecode""" + + cur_line_no = None + + def remove_line_num(inst: "Instruction") -> None: + nonlocal cur_line_no + if inst.starts_line is None: + return + elif inst.starts_line == cur_line_no: + inst.starts_line = None + else: + cur_line_no = inst.starts_line + + for inst in instructions: + remove_line_num(inst) + + +@dataclasses.dataclass +class ReadsWrites: + reads: set[Any] + writes: set[Any] + visited: set[Any] + + +def livevars_analysis( + instructions: list["Instruction"], instruction: "Instruction" +) -> set[Any]: + indexof = get_indexof(instructions) + must = ReadsWrites(set(), set(), set()) + may = ReadsWrites(set(), set(), set()) + + def walk(state: ReadsWrites, start: int) -> None: + if start in state.visited: + return + state.visited.add(start) + + for i in range(start, len(instructions)): + inst = instructions[i] + if inst.opcode in HASLOCAL or inst.opcode in HASFREE: + if "LOAD" in inst.opname or "DELETE" in inst.opname: + if inst.argval not in must.writes: + state.reads.add(inst.argval) + elif "STORE" in inst.opname: + state.writes.add(inst.argval) + elif inst.opname == "MAKE_CELL": + pass + else: + raise NotImplementedError(f"unhandled {inst.opname}") + if inst.exn_tab_entry: + walk(may, indexof[inst.exn_tab_entry.target]) + if inst.opcode in JUMP_OPCODES: + assert inst.target is not None + walk(may, indexof[inst.target]) + state = may + if inst.opcode in TERMINAL_OPCODES: + return + + walk(must, indexof[instruction]) + return must.reads | may.reads + + +@dataclasses.dataclass +class FixedPointBox: + value: bool = True + + +@dataclasses.dataclass +class StackSize: + low: Union[int, float] + high: Union[int, float] + fixed_point: FixedPointBox + + def zero(self) -> None: + self.low = 0 + self.high = 0 + self.fixed_point.value = False + + def offset_of(self, other: "StackSize", n: int) -> None: + prior = (self.low, self.high) + self.low = min(self.low, other.low + n) + self.high = max(self.high, other.high + n) + if (self.low, self.high) != prior: + self.fixed_point.value = False + + def exn_tab_jump(self, depth: int) -> None: + prior = (self.low, self.high) + self.low = min(self.low, depth) + self.high = max(self.high, depth) + if (self.low, self.high) != prior: + self.fixed_point.value = False + + +def stacksize_analysis(instructions: list["Instruction"]) -> Union[int, float]: + assert instructions + fixed_point = FixedPointBox() + stack_sizes = { + inst: StackSize(float("inf"), float("-inf"), fixed_point) + for inst in instructions + } + stack_sizes[instructions[0]].zero() + + for _ in range(100): + if fixed_point.value: + break + fixed_point.value = True + + for inst, next_inst in zip(instructions, instructions[1:] + [None]): + stack_size = stack_sizes[inst] + if inst.opcode not in TERMINAL_OPCODES: + assert next_inst is not None, f"missing next inst: {inst}" + eff = stack_effect(inst.opcode, inst.arg, jump=False) + stack_sizes[next_inst].offset_of(stack_size, eff) + if inst.opcode in JUMP_OPCODES: + assert inst.target is not None, f"missing target: {inst}" + stack_sizes[inst.target].offset_of( + stack_size, stack_effect(inst.opcode, inst.arg, jump=True) + ) + if inst.exn_tab_entry: + # see https://github.com/python/cpython/blob/3.11/Objects/exception_handling_notes.txt + # on why depth is computed this way. + depth = inst.exn_tab_entry.depth + int(inst.exn_tab_entry.lasti) + 1 + stack_sizes[inst.exn_tab_entry.target].exn_tab_jump(depth) + + low = min(x.low for x in stack_sizes.values()) + high = max(x.high for x in stack_sizes.values()) + + assert fixed_point.value, "failed to reach fixed point" + assert low >= 0 + return high diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/bytecode_transformation.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/bytecode_transformation.py new file mode 100644 index 0000000000000000000000000000000000000000..31c1d243de721e1a4fe5ed01a73a90789f964248 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/bytecode_transformation.py @@ -0,0 +1,1846 @@ +""" +This module provides utilities for analyzing, transforming and manipulating Python bytecode. +It includes functionality for: +- Converting between different bytecode formats and versions +- Virtualizing jumps and managing jump targets +- Handling exception tables and their entries +- Managing instruction offsets and extended arguments +- Providing a clean API for bytecode modification and transformation +- Supporting Python version-specific bytecode features +- Generating bytecode from template functions + +The module is designed to work across different Python versions (3.7+) and handles +version-specific bytecode differences transparently. +""" + +import copy +import dataclasses +import dis +import functools +import itertools +import sys +import types +import uuid +from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence +from typing import Any, cast, Optional, TYPE_CHECKING, Union + +from . import config +from .bytecode_analysis import ( + get_indexof, + propagate_line_nums, + remove_extra_line_nums, + stacksize_analysis, +) +from .utils import is_safe_constant + + +if TYPE_CHECKING: + from .output_graph import DynamoTracerOutput + + +@dataclasses.dataclass(slots=True) +class InstructionExnTabEntry: + start: "Instruction" + end: "Instruction" + target: "Instruction" + depth: int + lasti: bool + + def __repr__(self) -> str: + return ( + f"InstructionExnTabEntry(start={self.start.short_inst_repr()}, " + f"end={self.end.short_inst_repr()}, " + f"target={self.target.short_inst_repr()}, " + f"depth={self.depth}, lasti={self.lasti})" + ) + + def __eq__(self, o: object) -> bool: + if not isinstance(o, InstructionExnTabEntry): + return False + return ( + self.start is o.start + and self.end is o.end + and self.target is o.target + and self.depth == o.depth + and self.lasti == o.lasti + ) + + +@dataclasses.dataclass(slots=True) +class Instruction: + """A mutable version of dis.Instruction""" + + opcode: int + opname: str + arg: Optional[int] + argval: Any + offset: Optional[int] = None + starts_line: Optional[int] = None + is_jump_target: bool = False + positions: Optional["dis.Positions"] = None + # extra fields to make modification easier: + target: Optional["Instruction"] = None + exn_tab_entry: Optional[InstructionExnTabEntry] = None + argrepr: Optional[str] = None + + def __hash__(self) -> int: + return id(self) + + def __eq__(self, other: object) -> bool: + return id(self) == id(other) + + def short_inst_repr(self) -> str: + return f"Instruction(opname={self.opname}, offset={self.offset})" + + def copy_positions(self, other: "Instruction") -> None: + self.starts_line = other.starts_line + self.positions = other.positions + + +if sys.version_info >= (3, 13): + + def convert_instruction(i: dis.Instruction) -> Instruction: + return Instruction( + i.opcode, + i.opname, + i.arg, + i.argval, + i.offset, + i.line_number, + i.is_jump_target, + i.positions, + ) + +elif sys.version_info >= (3, 11): + + def convert_instruction(i: dis.Instruction) -> Instruction: + return Instruction( + i.opcode, + i.opname, + i.arg, + i.argval, + i.offset, + i.starts_line, + i.is_jump_target, + i.positions, + ) + +else: + + def convert_instruction(i: dis.Instruction) -> Instruction: + return Instruction( + i.opcode, + i.opname, + i.arg, + i.argval, + i.offset, + i.starts_line, + i.is_jump_target, + None, + ) + + +class _NotProvided: + def __repr__(self) -> str: + return "_NotProvided" + + +if sys.version_info >= (3, 12): + + def inst_has_op_bits(name: str) -> bool: + return name in ("LOAD_ATTR", "LOAD_GLOBAL", "LOAD_SUPER_ATTR") + +elif sys.version_info >= (3, 11): + + def inst_has_op_bits(name: str) -> bool: + return name == "LOAD_GLOBAL" + +else: + + def inst_has_op_bits(name: str): + return False + + +def create_instruction( + name: str, + *, + arg: Optional[int] = None, + argval: Optional[Any] = _NotProvided, + target: Optional[Instruction] = None, +) -> Instruction: + """ + At most one of `arg`, `argval`, and `target` can be not None/_NotProvided. + This is to prevent ambiguity, e.g. does + create_instruction("LOAD_CONST", 5) + mean load the constant at co_consts[5], or load the constant 5? + + If `arg` is not provided, it will be computed during assembly from + `argval` or `target`. + + Bits in the args of instructions LOAD_GLOBAL, LOAD_ATTR (3.12+), and LOAD_SUPER_ATTR + modify the behavior of the instruction. In this case, we allow both `arg` + and `argval` to be set. The value of `arg` here is expected to be the value of + the op bits and the true value of `arg` will be computed during assembly. + If `arg` is not set, the bits are assumed to be 0. + """ + + # allow for instructions with op bits to have both arg and argval specified + if inst_has_op_bits(name): + if target is not None: + raise RuntimeError("target cannot be specified for instruction") + if arg is None: + arg = 0 + else: + cnt = (arg is not None) + (argval is not _NotProvided) + (target is not None) + if cnt > 1: + raise RuntimeError( + "only one of arg, argval, and target can be not None/_NotProvided" + ) + if arg is not None and not isinstance(arg, int): + raise RuntimeError("instruction arg must be int or None") + return Instruction( + opcode=dis.opmap[name], opname=name, arg=arg, argval=argval, target=target + ) + + +# Python 3.11 remaps +def create_jump_absolute(target: Instruction) -> Instruction: + inst = "JUMP_FORWARD" if sys.version_info >= (3, 11) else "JUMP_ABSOLUTE" + return create_instruction(inst, target=target) + + +def is_jump_absolute(target: Instruction) -> bool: + return target.opname in ("JUMP_FORWARD", "JUMP_ABSOLUTE") + + +def create_load_const(val: Any, checked: bool = True) -> Instruction: + """ + In general we should only create `LOAD_CONST` for immutable objects, but + sometimes it's convenient _and safe_ for Dynamo create `LOAD_CONST` for + mutable objects. In such cases, use `checked=False`. + """ + if checked: + assert is_safe_constant(val), f"unsafe constant {val}" + return create_instruction("LOAD_CONST", argval=val) + + +def create_dup_top() -> Instruction: + if sys.version_info >= (3, 11): + return create_instruction("COPY", arg=1) + return create_instruction("DUP_TOP") + + +def create_rot_n(n: int) -> list[Instruction]: + """ + Returns a "simple" sequence of instructions that rotates TOS to the n-th + position in the stack. For Python < 3.11, returns a single ROT_* + instruction. If no such instruction exists, an error is raised and the + caller is expected to generate an equivalent sequence of instructions. + For Python >= 3.11, any rotation can be expressed as a simple sequence of + swaps. + """ + if n <= 1: + # don't rotate + return [] + + if sys.version_info >= (3, 11): + # rotate can be expressed as a sequence of swap operations + # e.g. rotate 3 is equivalent to swap 3, swap 2 + return [create_instruction("SWAP", arg=i) for i in range(n, 1, -1)] + + if n <= 4: + return [create_instruction("ROT_" + ["TWO", "THREE", "FOUR"][n - 2])] + return [create_instruction("ROT_N", arg=n)] + + +def add_push_null( + inst_or_insts: Union[Instruction, list[Instruction]], +) -> list[Instruction]: + """ + Appends or prepends a PUSH_NULL instruction to `inst_or_insts`, + depending on Python version. Used when you know that + `inst_or_insts` generates a callable that will be called. + + NOTE: Assumes `inst_or_insts` is a single instruction or sequence of + instructions that pushes exactly 1 object to the stack that is to + be called. It is important that you include ALL instructions that + construct the callable - not just the first instruction/a prefix. + + Will attempt to use the NULL push bit for instructions + with such bits (LOAD_GLOBAL 3.11+, LOAD_ATTR 3.12+, LOAD_SUPER_ATTR). + In this case, instructions WILL be modified. + """ + if isinstance(inst_or_insts, Instruction): + insts: list[Instruction] = [inst_or_insts] + else: + assert isinstance(inst_or_insts, list) + insts = inst_or_insts + + def inst_has_bit_set(idx: int) -> bool: + assert insts[idx].arg is not None + return insts[idx].arg & 1 == 1 # type: ignore[operator] + + def set_inst_bit(idx: int) -> None: + assert insts[idx].arg is not None + insts[idx].arg |= 1 # type: ignore[operator] + + if sys.version_info >= (3, 13): + # In 3.13, NULL follows the callable + if inst_has_op_bits(insts[-1].opname) and not inst_has_bit_set(-1): + # All insts with op bits have the push_null bit as the last one. + # Only set the bit if it hasn't been set - otherwise, we need + # to add another PUSH_NULL. + set_inst_bit(-1) + else: + insts = insts + [create_instruction("PUSH_NULL")] + elif sys.version_info >= (3, 12): + # LOAD_ATTR/LOAD_SUPER_ATTR at the end + # We assume that `insts` will only load 1 object, so + # LOAD_GLOBAL at the end doesn't need to be checked + if inst_has_op_bits(insts[-1].opname) and not inst_has_bit_set(-1): + set_inst_bit(-1) + elif insts[0].opname == "LOAD_GLOBAL" and not inst_has_bit_set(0): + set_inst_bit(0) + else: + insts = [create_instruction("PUSH_NULL")] + insts + elif sys.version_info >= (3, 11): + # 3.11 introduced NULL preceding callable + if inst_has_op_bits(insts[0].opname) and not inst_has_bit_set(0): + set_inst_bit(0) + else: + insts = [create_instruction("PUSH_NULL")] + insts + return insts + + +def add_push_null_call_function_ex( + inst_or_insts: Union[Instruction, list[Instruction]], +) -> list[Instruction]: + """Like add_push_null, but the low bit of LOAD_ATTR/LOAD_SUPER_ATTR + is not set, due to an expected CALL_FUNCTION_EX instruction. + """ + if isinstance(inst_or_insts, Instruction): + insts: list[Instruction] = [inst_or_insts] + else: + assert isinstance(inst_or_insts, list) + insts = inst_or_insts + + if sys.version_info < (3, 11): + return insts + + idx = -1 if sys.version_info >= (3, 13) else 0 + if insts[idx].opname == "LOAD_GLOBAL": + assert insts[idx].arg is not None + if insts[idx].arg & 1 == 0: # type: ignore[operator] + insts[idx].arg |= 1 # type: ignore[operator] + return insts + + if sys.version_info >= (3, 13): + insts = insts + [create_instruction("PUSH_NULL")] + else: + insts = [create_instruction("PUSH_NULL")] + insts + + return insts + + +def create_call_function(nargs: int, push_null: bool) -> list[Instruction]: + """ + Creates a sequence of instructions that makes a function call. + + `push_null` is used in Python 3.11+ only. It is used in codegen when + a function call is intended to be made with the NULL + fn convention, + and we know that the NULL has not been pushed yet. We will push a + NULL and rotate it to the correct position immediately before making + the function call. + + `push_null` should be True if no NULL is pushed for the callable. + Conversely, `push_null` should be False if a NULL was pushed for the callable. + Prefer using `push_null=False` when possible since we will not need to rotate + NULL to the right place, which is less efficient. + + Generally, you should codegen a function by using `add_push_null` then + `create_call_function` with `push_null=False`. + + Example of when to set push_null False: + + insts = [ + create_instruction("LOAD_GLOBAL", argval="torch"), + create_instruction("LOAD_ATTR", argval="nn"), + create_instruction("LOAD_ATTR", argval="functional"), + create_instruction("LOAD_ATTR", argval="relu"), + ] + insts = add_push_null(insts) + insts.append(create_instruction("LOAD_FAST", argval="x")) + insts.extend(create_call_function(1, False)) + + Example of when to set push_null True: + + insts = [create_instruction("LOAD_FAST", x)] + for should_wrap, wrapper_name in wrappers: + if should_wrap: + insts.extend([ + create_instruction("LOAD_GLOBAL", argval="wrapper1"), + create_instruction("SWAP", arg=2), + *create_call_function(1, True), + ) + """ + if sys.version_info >= (3, 11): + output = [] + if push_null: + output.append(create_instruction("PUSH_NULL")) + # 3.13 swapped NULL and callable + rots = nargs + 1 if sys.version_info >= (3, 13) else nargs + 2 + output.extend(create_rot_n(rots)) + if sys.version_info < (3, 12): + output.append(create_instruction("PRECALL", arg=nargs)) + output.append(create_instruction("CALL", arg=nargs)) + return output + return [create_instruction("CALL_FUNCTION", arg=nargs)] + + +def create_call_function_ex( + has_kwargs: bool, push_null: bool, ignore_314_kwargs_push: bool = False +) -> list[Instruction]: + """ + Assumes that in 3.14+, if has_kwargs=False, there is NOT a NULL + on the TOS for the kwargs. This utility function will add a PUSH_NULL. + + If the caller has already pushed a NULL for the kwargs, then set ignore_314_kwargs_push=True + so we don't push another NULL for the kwargs. + """ + if sys.version_info >= (3, 11): + output = [] + if ( + sys.version_info >= (3, 14) + and not has_kwargs + and not ignore_314_kwargs_push + ): + output.append(create_instruction("PUSH_NULL")) + has_kwargs = True + if push_null: + output.append(create_instruction("PUSH_NULL")) + # 3.13 swapped NULL and callable + # if flags == 1, 2 values popped - otherwise if flags == 0, 1 value + rots = ( + int(has_kwargs) + 2 + if sys.version_info >= (3, 13) + else int(has_kwargs) + 3 + ) + output.extend(create_rot_n(rots)) + output.append(create_instruction("CALL_FUNCTION_EX", arg=int(has_kwargs))) + return output + return [create_instruction("CALL_FUNCTION_EX", arg=int(has_kwargs))] + + +def create_call_method(nargs: int) -> list[Instruction]: + if sys.version_info >= (3, 12): + return [create_instruction("CALL", arg=nargs)] + if sys.version_info >= (3, 11): + return [ + create_instruction("PRECALL", arg=nargs), + create_instruction("CALL", arg=nargs), + ] + return [create_instruction("CALL_METHOD", arg=nargs)] + + +def create_load_method(name: str) -> Instruction: + if sys.version_info >= (3, 12): + # in 3.12, create a LOAD_ATTR instruction with the low bit set + return create_instruction("LOAD_ATTR", arg=1, argval=name) + return create_instruction("LOAD_METHOD", argval=name) + + +def create_setup_with(target: Instruction) -> Instruction: + opname = "BEFORE_WITH" if sys.version_info >= (3, 11) else "SETUP_WITH" + return create_instruction(opname, target=target) + + +def create_swap(n: int) -> list[Instruction]: + if sys.version_info >= (3, 11): + return [create_instruction("SWAP", arg=n)] + # in Python < 3.11, SWAP is a macro that expands to multiple instructions + if n == 1: + return [] + elif n == 2: + return [create_instruction("ROT_TWO")] + elif n == 3: + return [create_instruction("ROT_THREE"), create_instruction("ROT_TWO")] + """ + e.g. swap "a" and "b" in this stack: + 0 a 1 2 3 b + 0 a [1 2 3 b] + 0 a [1 2 3 b] [1 2 3 b] + 0 a [1 2 3 b] [1 2 3 b] -1 + 0 a [1 2 3 b] b + 0 b a [1 2 3 b] + 0 b a [1 2 3 b] [1 2 3 b] + 0 b [1 2 3 b] a [1 2 3 b] + 0 b [1 2 3 b] a [1 2 3 b] -1 + 0 b [1 2 3 a] + 0 b [1 2 3 a] [1 2 3 a] + 0 b [1 2 3 a] [1 2 3 a] reverse + 0 b [a 3 2 1] None + 0 b [a 3 2 1] + 0 b 1 2 3 a + """ + return [ + create_instruction("BUILD_LIST", arg=n - 1), + create_instruction("DUP_TOP"), + create_instruction("LOAD_CONST", argval=-1), + create_binary_subscr(), + create_instruction("ROT_THREE"), + create_instruction("DUP_TOP"), + create_instruction("ROT_THREE"), + create_instruction("LOAD_CONST", argval=-1), + create_instruction("STORE_SUBSCR"), + create_instruction("DUP_TOP"), + create_load_method("reverse"), + *create_call_method(0), + create_instruction("POP_TOP"), + create_instruction("UNPACK_SEQUENCE", arg=n - 1), + ] + + +def create_binary_slice( + start: Optional[int], end: Optional[int], store: bool = False +) -> list[Instruction]: + """ + BINARY_SLICE and STORE_SLICE (if `set` is True) for all Python versions + """ + if sys.version_info >= (3, 14): + subscr_inst = ( + create_instruction("STORE_SUBSCR") if store else create_binary_subscr() + ) + return [ + create_load_const(slice(start, end)), + subscr_inst, + ] + elif sys.version_info >= (3, 12): + inst_name = "STORE_SLICE" if store else "BINARY_SLICE" + return [ + create_load_const(start), + create_load_const(end), + create_instruction(inst_name), + ] + else: + inst_name = "STORE_SUBSCR" if store else "BINARY_SUBSCR" + return [ + create_load_const(start), + create_load_const(end), + create_instruction("BUILD_SLICE", arg=2), + create_instruction(inst_name), + ] + + +def create_copy(i: int) -> list[Instruction]: + if sys.version_info >= (3, 11): + return [create_instruction("COPY", arg=i)] + if i == 1: + return [create_instruction("DUP_TOP")] + # COPY 4 + # 0 1 2 3 + # 3 1 2 0 + # 3 1 2 0 0 + # 0 1 2 0 3 + # 0 1 2 3 0 + return [ + *create_swap(i), + create_dup_top(), + *create_swap(i + 1), + *create_swap(2), + ] + + +# mainly for debugging generated bytecode +def create_print_on_stack(depth: int) -> list[Instruction]: + return [ + *add_push_null(create_instruction("LOAD_CONST", argval=print)), + *create_copy(depth + (2 if sys.version_info >= (3, 11) else 1)), + *create_call_function(1, False), + create_instruction("POP_TOP"), + ] + + +# mainly for debugging generated bytecode +def create_print_value(value: Any) -> list[Instruction]: + return [ + *add_push_null(create_instruction("LOAD_CONST", argval=print)), + create_instruction("LOAD_CONST", argval=value), + *create_call_function(1, False), + create_instruction("POP_TOP"), + ] + + +def create_binary_subscr() -> Instruction: + if sys.version_info < (3, 14): + return create_instruction("BINARY_SUBSCR") + # https://github.com/python/cpython/blob/0e46c0499413bc5f9f8336fe76e2e67cf93f64d8/Include/opcode.h#L36 + return create_instruction("BINARY_OP", arg=26) + + +def create_build_tuple(n: int) -> Instruction: + if sys.version_info >= (3, 14) and n == 0: + return create_load_const(()) + return create_instruction("BUILD_TUPLE", arg=n) + + +def linetable_writer( + first_lineno: int, +) -> tuple[list[int], Callable[[int, int], None], Callable[[int], None]]: + """ + Used to create typing.CodeType.co_linetable + See https://github.com/python/cpython/blob/main/Objects/lnotab_notes.txt + This is the internal format of the line number table for Python 3.10 + """ + assert sys.version_info[:2] == (3, 10) + linetable: list[int] = [] + lineno = first_lineno + lineno_delta = 0 + byteno = 0 + + def _update(byteno_delta: int, lineno_delta: int) -> None: + while byteno_delta != 0 or lineno_delta != 0: + byte_offset = max(0, min(byteno_delta, 254)) + line_offset = max(-127, min(lineno_delta, 127)) + assert byte_offset != 0 or line_offset != 0 + byteno_delta -= byte_offset + lineno_delta -= line_offset + linetable.extend((byte_offset, line_offset & 0xFF)) + + def update(lineno_new: int, byteno_new: int) -> None: + nonlocal lineno, lineno_delta, byteno + byteno_delta = byteno_new - byteno + byteno = byteno_new + _update(byteno_delta, lineno_delta) + lineno_delta = lineno_new - lineno + lineno = lineno_new + + def end(total_bytes: int) -> None: + _update(total_bytes - byteno, lineno_delta) + + return linetable, update, end + + +def encode_varint(n: int) -> list[int]: + """ + 6-bit chunk encoding of an unsigned integer + See https://github.com/python/cpython/blob/3.11/Objects/locations.md + """ + assert n >= 0 + b = [n & 63] + n >>= 6 + while n > 0: + b[-1] |= 64 + b.append(n & 63) + n >>= 6 + return b + + +def linetable_311_writer( + first_lineno: int, +) -> tuple[list[int], Callable[[Optional["dis.Positions"], int], None]]: + """ + Used to create typing.CodeType.co_linetable + See https://github.com/python/cpython/blob/3.11/Objects/locations.md + This is the internal format of the line number table for Python 3.11 + """ + assert sys.version_info >= (3, 11) + linetable = [] + lineno = first_lineno + + def update(positions: Optional["dis.Positions"], inst_size: int) -> None: + nonlocal lineno + lineno_new = positions.lineno if positions else None + + def _update(delta: int, size: int) -> None: + assert 0 < size <= 8 + # first byte - use 13 (no column info) is positions is + # malformed, otherwise use 14 (long form) + other_varints: tuple[int, ...] = () + if ( + positions + and positions.lineno is not None + and positions.end_lineno is not None + and positions.col_offset is not None + and positions.end_col_offset is not None + ): + linetable.append(0b1_1110_000 + size - 1) + # for whatever reason, column offset needs `+ 1` + # https://github.com/python/cpython/blob/1931c2a438c50e6250725c84dff94fc760b9b951/Python/compile.c#L7603 + other_varints = ( + positions.end_lineno - positions.lineno, + positions.col_offset + 1, + positions.end_col_offset + 1, + ) + else: + linetable.append(0b1_1101_000 + size - 1) + # encode signed int + if delta < 0: + delta = ((-delta) << 1) | 1 + else: + delta <<= 1 + # encode unsigned int + linetable.extend(encode_varint(delta)) + for n in other_varints: + linetable.extend(encode_varint(n)) + + if lineno_new is None: + lineno_delta = 0 + else: + lineno_delta = lineno_new - lineno + lineno = lineno_new + while inst_size > 8: + _update(lineno_delta, 8) + inst_size -= 8 + _update(lineno_delta, inst_size) + + return linetable, update + + +@dataclasses.dataclass(slots=True) +class ExceptionTableEntry: + start: int + end: int + target: int + depth: int + lasti: bool + + +def encode_exception_table_varint(n: int) -> list[int]: + """ + Similar to `encode_varint`, but the 6-bit chunks are ordered in reverse. + """ + assert n >= 0 + b = [n & 63] + n >>= 6 + while n > 0: + b.append(n & 63) + n >>= 6 + b.reverse() + for i in range(len(b) - 1): + b[i] |= 64 + return b + + +def decode_exception_table_varint(bytes_iter: Iterator[int]) -> int: + """ + Inverse of `encode_exception_table_varint`. + """ + b = next(bytes_iter) + val = b & 63 + while b & 64: + val <<= 6 + b = next(bytes_iter) + val |= b & 63 + return val + + +def check_exception_table(tab: list[ExceptionTableEntry]) -> None: + """ + Verifies that a list of ExceptionTableEntries will make a well-formed + jump table: entries are non-empty, sorted, and do not overlap. + """ + for i in range(len(tab) - 1): + assert ( + tab[i].start <= tab[i].end + and tab[i].end < tab[i + 1].start + and tab[i + 1].start <= tab[i + 1].end + ) + + +def parse_exception_table(exntab: bytes) -> list[ExceptionTableEntry]: + """ + Parse the exception table according to + https://github.com/python/cpython/blob/3.11/Objects/exception_handling_notes.txt + """ + exntab_iter = iter(exntab) + tab = [] + try: + while True: + start = decode_exception_table_varint(exntab_iter) * 2 + length = decode_exception_table_varint(exntab_iter) * 2 + end = start + length - 2 + target = decode_exception_table_varint(exntab_iter) * 2 + dl = decode_exception_table_varint(exntab_iter) + depth = dl >> 1 + lasti = bool(dl & 1) + tab.append(ExceptionTableEntry(start, end, target, depth, lasti)) + except StopIteration: + check_exception_table(tab) + return tab + + +def assemble_exception_table(tab: list[ExceptionTableEntry]) -> bytes: + """ + Inverse of parse_exception_table - encodes list of exception + table entries into bytes. + """ + b = [] + for entry in tab: + first_entry = encode_exception_table_varint(entry.start // 2) + first_entry[0] |= 1 << 7 + b.extend(first_entry) + length = entry.end - entry.start + 2 + b.extend(encode_exception_table_varint(length // 2)) + b.extend(encode_exception_table_varint(entry.target // 2)) + dl = (entry.depth << 1) + entry.lasti + b.extend(encode_exception_table_varint(dl)) + return bytes(b) + + +def assemble(instructions: list[Instruction], firstlineno: int) -> tuple[bytes, bytes]: + """Do the opposite of dis.get_instructions()""" + code: list[int] = [] + if sys.version_info >= (3, 11): + lnotab, update_lineno = linetable_311_writer(firstlineno) + num_ext = 0 + for i, inst in enumerate(instructions): + if inst.opname == "EXTENDED_ARG": + inst_size = 1 + num_ext += 1 + # copy positions from the actual instruction + for j in (1, 2, 3): + if instructions[i + j].opname != "EXTENDED_ARG": + inst.positions = instructions[i + j].positions + break + else: + inst_size = instruction_size(inst) // 2 + num_ext + num_ext = 0 + update_lineno(inst.positions, inst_size) + num_ext = 0 + arg = inst.arg or 0 + code.extend((inst.opcode, arg & 0xFF)) + for _ in range(instruction_size(inst) // 2 - 1): + code.extend((0, 0)) + else: + lnotab, update_lineno, end = linetable_writer(firstlineno) + + for inst in instructions: + if inst.starts_line is not None: + update_lineno(inst.starts_line, len(code)) + arg = inst.arg or 0 + code.extend((inst.opcode, arg & 0xFF)) + + end(len(code)) + + return bytes(code), bytes(lnotab) + + +def _get_instruction_by_offset( + offset_to_inst: dict[int, Instruction], offset: int +) -> Optional[Instruction]: + """ + Get the instruction located at a given offset, accounting for EXTENDED_ARGs + """ + for n in (0, 2, 4, 6): + if offset_to_inst[offset + n].opcode != dis.EXTENDED_ARG: + return offset_to_inst[offset + n] + return None + + +def virtualize_jumps(instructions: Iterable[Instruction]) -> None: + """Replace jump targets with pointers to make editing easier""" + jump_targets = { + inst.offset: inst for inst in instructions if inst.offset is not None + } + + for inst in instructions: + if inst.opcode in dis.hasjabs or inst.opcode in dis.hasjrel: + inst.target = _get_instruction_by_offset(jump_targets, inst.argval) + + +_REL_JUMPS = set(dis.hasjrel) + + +def flip_jump_direction(instruction: Instruction) -> None: + if sys.version_info < (3, 11): + raise RuntimeError("Cannot flip jump direction in Python < 3.11") + if "FORWARD" in instruction.opname: + instruction.opname = instruction.opname.replace("FORWARD", "BACKWARD") + elif "BACKWARD" in instruction.opname: + instruction.opname = instruction.opname.replace("BACKWARD", "FORWARD") + else: + raise AttributeError("Instruction is not a forward or backward jump") + instruction.opcode = dis.opmap[instruction.opname] + assert instruction.opcode in _REL_JUMPS + + +def _get_instruction_front(instructions: list[Instruction], idx: int) -> Instruction: + """ + i.e. get the first EXTENDED_ARG instruction (if any) when targeting + instructions[idx] with a jump. + """ + target = instructions[idx] + for offset in (1, 2, 3): + if idx >= offset and instructions[idx - offset].opcode == dis.EXTENDED_ARG: + target = instructions[idx - offset] + else: + break + return target + + +def devirtualize_jumps(instructions: list[Instruction]) -> None: + """Fill in args for virtualized jump target after instructions may have moved""" + jumps = set(dis.hasjabs).union(set(dis.hasjrel)) + + # check for negative jump args and fix them + for inst in instructions: + if inst.opcode in jumps: + if inst.opcode not in dis.hasjabs: + assert ( + inst.target is not None + and inst.target.offset is not None + and inst.offset is not None + ) + if inst.target.offset < inst.offset: + if sys.version_info < (3, 11): + raise RuntimeError("Got negative jump offset for Python < 3.11") + # forward jumps become backward + if "FORWARD" in inst.opname: + flip_jump_direction(inst) + else: + # backward jumps become forward + if sys.version_info >= (3, 11) and "BACKWARD" in inst.opname: + flip_jump_direction(inst) + + # jump instruction size may have changed due to flips + update_offsets(instructions) + indexof = get_indexof(instructions) + + # compute jump instruction arg + for inst in instructions: + if inst.opcode in jumps: + assert inst.target is not None + target = _get_instruction_front(instructions, indexof[inst.target]) + if inst.opcode in dis.hasjabs: + if sys.version_info < (3, 11): + # `arg` is expected to be bytecode offset, whereas `offset` is byte offset. + # Divide since bytecode is 2 bytes large. + inst.arg = int(target.offset / 2) + else: + raise RuntimeError("Python 3.11+ should not have absolute jumps") + else: # relative jump + # byte offset between target and next instruction + assert target.offset is not None and inst.offset is not None + inst.arg = abs( + int(target.offset - inst.offset - instruction_size(inst)) + ) + # pyrefly: ignore [unsupported-operation] + inst.arg //= 2 + inst.argval = target.offset + inst.argrepr = f"to {target.offset}" + + +def virtualize_exception_table( + exn_tab_bytes: bytes, instructions: list[Instruction] +) -> None: + """Replace exception table entries with pointers to make editing easier""" + exn_tab = parse_exception_table(exn_tab_bytes) + offset_to_inst = {cast(int, inst.offset): inst for inst in instructions} + offsets = sorted(offset_to_inst.keys()) + end_offset_idx = 0 + exn_tab_iter = iter(exn_tab) + try: + + def step() -> tuple[ExceptionTableEntry, InstructionExnTabEntry]: + nonlocal end_offset_idx + entry = next(exn_tab_iter) + # find rightmost offset <= entry.end, since entry.end may not be + # an actual instruction, e.g. if the end instruction is LOAD_GLOBAL, + # which takes more than 2 bytes, then entry.end points to the end + # of the LOAD_GLOBAL instruction, not the beginning. + while ( + end_offset_idx < len(offsets) and offsets[end_offset_idx] <= entry.end + ): + end_offset_idx += 1 + assert end_offset_idx > 0 + end_offset = offsets[end_offset_idx - 1] + inst_entry = InstructionExnTabEntry( + _get_instruction_by_offset(offset_to_inst, entry.start), # type: ignore[arg-type] + _get_instruction_by_offset(offset_to_inst, end_offset), # type: ignore[arg-type] + _get_instruction_by_offset(offset_to_inst, entry.target), # type: ignore[arg-type] + entry.depth, + entry.lasti, + ) + return entry, inst_entry + + entry, inst_entry = step() + for inst in instructions: + assert inst.offset is not None + while inst.offset > entry.end: + entry, inst_entry = step() + if inst.offset >= entry.start: + inst.exn_tab_entry = copy.copy(inst_entry) + except StopIteration: + pass + + +def compute_exception_table( + instructions: list[Instruction], +) -> list[ExceptionTableEntry]: + """Compute exception table in list format from instructions with exn_tab_entries""" + exn_dict: dict[tuple[int, int], tuple[int, int, bool]] = {} + indexof = get_indexof(instructions) + + for inst in instructions: + if inst.exn_tab_entry: + # account for prefixed EXTENDED_ARGS + start = _get_instruction_front( + instructions, indexof[inst.exn_tab_entry.start] + ).offset + assert start is not None + # point to the last 2 bytes of the end instruction + end = ( + cast(int, inst.exn_tab_entry.end.offset) + + instruction_size(inst.exn_tab_entry.end) + - 2 + ) + assert end is not None + target = _get_instruction_front( + instructions, indexof[inst.exn_tab_entry.target] + ).offset + assert target is not None + key = (start, end) + val = (target, inst.exn_tab_entry.depth, inst.exn_tab_entry.lasti) + if key in exn_dict: + assert exn_dict[key] == val + exn_dict[key] = val + + # Dynamo may construct nested exception table entries for convenience, + # but Python expects exception table entries to not overlap. + # NOTE: below, "keys" refer to old instruction entries' starts and ends, + # and "entries" refer to the generated exception table entries. + + # Sort keys by increasing start, then decreasing end + keys_sorted = sorted(exn_dict.keys(), key=lambda t: (t[0], -t[1])) + # smallest byte that the next exception table entry can start at + nexti = 0 + # stack of current nested keys + key_stack: list[tuple[int, int]] = [] + exn_tab: list[ExceptionTableEntry] = [] + + def pop() -> None: + """ + Pop the key_stack and append an exception table entry if possible. + """ + nonlocal nexti + if key_stack: + key = key_stack.pop() + if nexti <= key[1]: + exn_tab.append( + ExceptionTableEntry(max(key[0], nexti), key[1], *exn_dict[key]) + ) + nexti = key[1] + 2 + + for key in keys_sorted: + # pop keys that are no longer nested over the current key + while key_stack and key_stack[-1][1] < key[0]: + pop() + if key_stack: + # create an entry covering to the current key, if possible + assert key_stack[-1][0] <= key[0] <= key[1] <= key_stack[-1][1] + left = max(nexti, key_stack[-1][0]) + if left < key[0]: + exn_tab.append( + ExceptionTableEntry(left, key[0] - 2, *exn_dict[key_stack[-1]]) + ) + nexti = key[0] + key_stack.append(key) + while key_stack: + pop() + check_exception_table(exn_tab) + return exn_tab + + +def check_inst_exn_tab_entries_nested( + tab: list[InstructionExnTabEntry], indexof: dict[Instruction, int] +) -> None: + """ + Checks `tab` is a properly sorted list of nested InstructionExnTabEntry's, + i.e. no entries partially overlap. + "Properly sorted" means entries are sorted by increasing starts, then + decreasing ends. + """ + entry_stack: list[tuple[int, int]] = [] + for entry in tab: + key = (indexof[entry.start], indexof[entry.end]) + while entry_stack and entry_stack[-1][1] < key[0]: + entry_stack.pop() + if entry_stack: + assert entry_stack[-1][0] <= key[0] <= key[1] <= entry_stack[-1][1] + entry_stack.append(key) + + +def propagate_inst_exn_table_entries(instructions: list[Instruction]) -> None: + """ + Copies exception table entries to all instructions in an entry's range. + Supports nested exception table entries. + """ + indexof = get_indexof(instructions) + entries: dict[tuple[int, int], InstructionExnTabEntry] = {} + for inst in instructions: + if inst.exn_tab_entry: + key = ( + indexof[inst.exn_tab_entry.start], + indexof[inst.exn_tab_entry.end], + ) + if key in entries: + assert inst.exn_tab_entry == entries[key] + entries[key] = inst.exn_tab_entry + sorted_entries = [ + entries[key] for key in sorted(entries.keys(), key=lambda t: (t[0], -t[1])) + ] + check_inst_exn_tab_entries_nested(sorted_entries, indexof) + # Propagation of nested entries works since nested entries come later + # in sorted order. + for entry in sorted_entries: + for i in range(indexof[entry.start], indexof[entry.end] + 1): + instructions[i].exn_tab_entry = copy.copy(entry) + + +def check_inst_exn_tab_entries_valid(instructions: list[Instruction]) -> None: + """ + Checks that exn_tab_entries of instructions are valid. + An entry's start, end, and target must be in instructions. + Instructions with an exn_tab_entry are located within + the entry's start and end instructions. + Instructions do not share exn_tab_entries. + + Implicitly checks for no duplicate instructions. + """ + indexof = get_indexof(instructions) + exn_tab_entry_set = set() + for i, inst in enumerate(instructions): + if inst.exn_tab_entry: + assert sys.version_info >= (3, 11) + assert id(inst.exn_tab_entry) not in exn_tab_entry_set + exn_tab_entry_set.add(id(inst.exn_tab_entry)) + entry = inst.exn_tab_entry + assert entry.start in indexof + assert entry.end in indexof + assert entry.target in indexof + assert indexof[entry.start] <= i <= indexof[entry.end] + + +def strip_extended_args(instructions: list[Instruction]) -> None: + instructions[:] = [i for i in instructions if i.opcode != dis.EXTENDED_ARG] + + +# Overwrites old_inst with a sequence of new instructions. +# This is necessary in order to preserve jump targets to the old +# instruction, exception table entries, and positions. +# Returns the modified sequence of instructions (including the modified +# old instruction!) that can be manipulated elsewhere. +def overwrite_instruction( + old_inst: Instruction, new_insts: list[Instruction] +) -> list[Instruction]: + # update old_inst.exnt_tab_entry.end if necessary + if ( + old_inst.exn_tab_entry + and old_inst.exn_tab_entry.end is old_inst + and len(new_insts) > 1 + ): + old_inst.exn_tab_entry.end = new_insts[-1] + # preserve exception table entries and positions + for inst in new_insts[1:]: + inst.exn_tab_entry = copy.copy(old_inst.exn_tab_entry) + inst.positions = old_inst.positions + # modify old_inst in-place to preserve jump target + old_inst.opcode = new_insts[0].opcode + old_inst.opname = new_insts[0].opname + old_inst.arg = new_insts[0].arg + old_inst.argval = new_insts[0].argval + old_inst.target = new_insts[0].target + return [old_inst] + new_insts[1:] + + +def remove_load_call_method(instructions: list[Instruction]) -> list[Instruction]: + """LOAD_METHOD puts a NULL on the stack which causes issues, so remove it""" + assert sys.version_info < (3, 11) + rewrites = {"LOAD_METHOD": "LOAD_ATTR", "CALL_METHOD": "CALL_FUNCTION"} + for inst in instructions: + if inst.opname in rewrites: + inst.opname = rewrites[inst.opname] + inst.opcode = dis.opmap[inst.opname] + return instructions + + +def remove_jump_if_none(instructions: list[Instruction]) -> None: + new_insts = [] + for inst in instructions: + if "_NONE" in inst.opname: + is_op = create_instruction("IS_OP", arg=int("NOT" in inst.opname)) + # need both argval and arg set correctly now (not later) + is_op.argval = is_op.arg + + if sys.version_info < (3, 12): + jump_op = create_instruction( + ( + "POP_JUMP_FORWARD_IF_TRUE" + if "FORWARD" in inst.opname + else "POP_JUMP_BACKWARD_IF_TRUE" + ), + target=inst.target, + ) + else: + jump_op = create_instruction("POP_JUMP_IF_TRUE", target=inst.target) + + replace_insts = [ + create_instruction("LOAD_CONST", argval=None), + is_op, + jump_op, + ] + new_insts.extend(overwrite_instruction(inst, replace_insts)) + else: + new_insts.append(inst) + instructions[:] = new_insts + + +def remove_binary_store_slice(instructions: list[Instruction]) -> None: + new_insts = [] + for inst in instructions: + new_insts.append(inst) + if inst.opname in ("BINARY_SLICE", "STORE_SLICE"): + # new instruction + if sys.version_info >= (3, 14) and inst.opname == "BINARY_SLICE": + subscr_inst = create_binary_subscr() + else: + subscr_inst = create_instruction(inst.opname.replace("SLICE", "SUBSCR")) + if inst.exn_tab_entry and inst.exn_tab_entry.end is inst: + inst.exn_tab_entry.end = subscr_inst + subscr_inst.exn_tab_entry = copy.copy(inst.exn_tab_entry) + subscr_inst.positions = inst.positions + # modify inst in-place to preserve jump target + inst.opcode = dis.opmap["BUILD_SLICE"] + inst.opname = "BUILD_SLICE" + inst.arg = 2 + inst.argval = 2 + new_insts.append(subscr_inst) + instructions[:] = new_insts + + +FUSED_INSTS = { + "LOAD_FAST_LOAD_FAST": ("LOAD_FAST", "LOAD_FAST"), + "LOAD_FAST_BORROW_LOAD_FAST_BORROW": ("LOAD_FAST_BORROW", "LOAD_FAST_BORROW"), + "STORE_FAST_STORE_FAST": ("STORE_FAST", "STORE_FAST"), + "STORE_FAST_LOAD_FAST": ("STORE_FAST", "LOAD_FAST"), +} + + +def remove_fused_load_store(instructions: list[Instruction]) -> None: + new_insts = [] + for inst in instructions: + if inst.opname in FUSED_INSTS: + inst0, inst1 = FUSED_INSTS[inst.opname] + argval0, argval1 = inst.argval + + replace_insts = [ + create_instruction(inst0, argval=argval0), + create_instruction(inst1, argval=argval1), + ] + new_insts.extend(overwrite_instruction(inst, replace_insts)) + else: + new_insts.append(inst) + instructions[:] = new_insts + + +# adds GRAPH_BREAK_IF_LEAF (not a real instruction) before RETURN_* instructions +# for testing purposes +def add_graph_break_if_leaf_instructions(instructions: list[Instruction]) -> None: + new_insts = [] + for inst in instructions: + if "RETURN" in inst.opname: + replace_insts = [ + create_instruction("NOP", argval="GRAPH_BREAK_IF_LEAF"), + create_instruction(inst.opname, argval=inst.argval), + ] + new_insts.extend(overwrite_instruction(inst, replace_insts)) + else: + new_insts.append(inst) + instructions[:] = new_insts + + +def remove_graph_break_if_leaf_instructions(instructions: list[Instruction]) -> None: + new_insts = [] + for inst, next_inst in itertools.pairwise(instructions): + if ( + inst.opname == "NOP" + and inst.argval == "GRAPH_BREAK_IF_LEAF" + and next_inst.opname.startswith("RETURN") + ): + # remove this instruction and update all other instructions' jump targets + for i in range(len(instructions)): + if instructions[i].target is inst: + instructions[i].target = next_inst + if instructions[i].exn_tab_entry: + # linter is mistakenly complaining that None has no attribute "..." + # but this codepath only runs if instructions[i] is not None + if instructions[i].exn_tab_entry.start is inst: # type: ignore[union-attr] + instructions[i].exn_tab_entry.start = next_inst # type: ignore[union-attr] + if instructions[i].exn_tab_entry.end is inst: # type: ignore[union-attr] + instructions[i].exn_tab_entry.end = next_inst # type: ignore[union-attr] + if instructions[i].exn_tab_entry.target is inst: # type: ignore[union-attr] + instructions[i].exn_tab_entry.target = next_inst # type: ignore[union-attr] + else: + new_insts.append(inst) + new_insts.append(instructions[-1]) + instructions[:] = new_insts + + +def explicit_super(code: types.CodeType, instructions: list[Instruction]) -> None: + """convert super() with no args into explicit arg form""" + cell_and_free = (code.co_cellvars or ()) + (code.co_freevars or ()) + if not len(code.co_varnames): + # A function with no argument cannot contain a valid "super()" call + return + output = [] + for idx, inst in enumerate(instructions): + output.append(inst) + if inst.opname == "LOAD_GLOBAL" and inst.argval == "super": + nexti = instructions[idx + 1] + if nexti.arg == 0 and ( + (sys.version_info >= (3, 12) and nexti.opname == "CALL") + or ( + sys.version_info >= (3, 11) + and sys.version_info < (3, 12) + and nexti.opname == "PRECALL" + ) + or (sys.version_info < (3, 11) and nexti.opname == "CALL_FUNCTION") + ): + assert "__class__" in cell_and_free + output.append(create_instruction("LOAD_DEREF", argval="__class__")) + first_var = code.co_varnames[0] + if first_var in cell_and_free: + output.append(create_instruction("LOAD_DEREF", argval=first_var)) + else: + output.append(create_instruction("LOAD_FAST", argval=first_var)) + nexti.arg = 2 + nexti.argval = 2 + if nexti.opname == "PRECALL": + # also update the following CALL instruction + call_inst = instructions[idx + 2] + call_inst.arg = 2 + call_inst.argval = 2 + + instructions[:] = output + + +def fix_extended_args(instructions: list[Instruction]) -> int: + """Fill in correct argvals for EXTENDED_ARG ops""" + output: list[Instruction] = [] + + def maybe_pop_n(n: int) -> None: + for _ in range(n): + if output and output[-1].opcode == dis.EXTENDED_ARG: + output.pop() + + for inst in instructions: + if inst.opcode == dis.EXTENDED_ARG: + # Leave this instruction alone for now so we never shrink code + inst.arg = 0 + elif inst.arg and inst.arg > 0xFFFFFF: + maybe_pop_n(3) + output.append(create_instruction("EXTENDED_ARG", arg=inst.arg >> 24)) + output.append(create_instruction("EXTENDED_ARG", arg=inst.arg >> 16)) + output.append(create_instruction("EXTENDED_ARG", arg=inst.arg >> 8)) + elif inst.arg and inst.arg > 0xFFFF: + maybe_pop_n(2) + output.append(create_instruction("EXTENDED_ARG", arg=inst.arg >> 16)) + output.append(create_instruction("EXTENDED_ARG", arg=inst.arg >> 8)) + elif inst.arg and inst.arg > 0xFF: + maybe_pop_n(1) + output.append(create_instruction("EXTENDED_ARG", arg=inst.arg >> 8)) + output.append(inst) + + added = len(output) - len(instructions) + assert added >= 0 + instructions[:] = output + return added + + +def instruction_size(inst: Instruction) -> int: + import torch + + if sys.version_info >= (3, 11): + return 2 * (torch._C._dynamo.eval_frame.py_opcode_caches[inst.opcode] + 1) + return 2 + + +def check_offsets(instructions: Sequence[Instruction]) -> None: + offset = 0 + for inst in instructions: + assert inst.offset == offset + offset += instruction_size(inst) + + +def update_offsets(instructions: Sequence[Instruction]) -> None: + offset = 0 + for inst in instructions: + inst.offset = offset + # pyrefly: ignore [unsupported-operation] + offset += instruction_size(inst) + + +def debug_bytes(*args: bytes) -> str: + index = range(max(map(len, args))) + result = [ + " ".join(f"{x:03}" for x in arg) + for arg in [index] + + list(args) + + [[int(a != b) for a, b in zip(args[-1], args[-2])]] + ] + + return "bytes mismatch\n" + "\n".join(result) + + +def debug_checks(code: types.CodeType) -> None: + """Make sure our assembler produces same bytes as we start with""" + dode, _ = transform_code_object(code, lambda x, y: None, safe=True) + assert code.co_code == dode.co_code, debug_bytes(code.co_code, dode.co_code) + assert code.co_lnotab == dode.co_lnotab, debug_bytes(code.co_lnotab, dode.co_lnotab) + + +HAS_LOCAL = set(dis.haslocal) +HAS_NAME = set(dis.hasname) +HAS_FREE = set(dis.hasfree) +HAS_CONST = set(dis.hasconst) + + +def get_const_index(code_options: dict[str, Any], val: Any) -> int: + for i, v in enumerate(code_options["co_consts"]): + # NOTE: stronger comparison is required, since we have + # examples where two values compare equal but have + # different semantic meaning in some cases, e.g. + # 0.0 == -0.0 but have different effects in torch.copysign. + if val is v: + return i + code_options["co_consts"] += (val,) + return len(code_options["co_consts"]) - 1 + + +def fix_vars( + instructions: list[Instruction], + code_options: dict[str, Any], + varname_from_oparg: Optional[Callable[..., Any]] = None, +) -> None: + # compute instruction arg from argval if arg is not provided + names = {name: idx for idx, name in enumerate(code_options["co_names"])} + + def get_name_index(name: str) -> int: + try: + idx = names[name] + except KeyError: + # Add a missing item to co_names + idx = names[name] = len(names) + code_options["co_names"] = (*code_options["co_names"], name) + assert len(code_options["co_names"]) == len(names) + return idx + + if sys.version_info < (3, 11): + assert varname_from_oparg is None + varnames = {name: idx for idx, name in enumerate(code_options["co_varnames"])} + freenames = { + name: idx + for idx, name in enumerate( + code_options["co_cellvars"] + code_options["co_freevars"] + ) + } + else: + assert callable(varname_from_oparg) + allnames = {} + for idx in itertools.count(): + try: + name = varname_from_oparg(idx) + allnames[name] = idx + except IndexError: + break + varnames = {name: allnames[name] for name in code_options["co_varnames"]} + freenames = { + name: allnames[name] + for name in code_options["co_cellvars"] + code_options["co_freevars"] + } + for i in range(len(instructions)): + + def should_compute_arg() -> bool: + # argval is prioritized over arg + return instructions[i].argval is not _NotProvided + + if instructions[i].opname == "LOAD_GLOBAL": + # 3.11 LOAD_GLOBAL requires both arg and argval - see create_instruction + assert instructions[i].argval is not _NotProvided + if sys.version_info >= (3, 11): + assert instructions[i].arg is not None + instructions[i].arg = (get_name_index(instructions[i].argval) << 1) + ( + cast(int, instructions[i].arg) % 2 + ) + else: + instructions[i].arg = get_name_index(instructions[i].argval) + elif instructions[i].opname == "LOAD_ATTR": + # 3.12 LOAD_ATTR requires both arg and argval, like LOAD_GLOBAL + assert instructions[i].argval is not _NotProvided + if sys.version_info >= (3, 12): + assert instructions[i].arg is not None + instructions[i].arg = (get_name_index(instructions[i].argval) << 1) + ( + cast(int, instructions[i].arg) % 2 + ) + else: + instructions[i].arg = get_name_index(instructions[i].argval) + elif instructions[i].opname == "LOAD_SUPER_ATTR": + assert instructions[i].arg is not None + assert instructions[i].argval is not _NotProvided + # Copy low bit, force second bit on for explicit super (the "+ 2") + instructions[i].arg = ( + (get_name_index(instructions[i].argval) << 2) + + (cast(int, instructions[i].arg) % 2) + + 2 + ) + elif instructions[i].opname in FUSED_INSTS: + assert sys.version_info >= (3, 13) + assert isinstance(instructions[i].argval, tuple) + assert len(instructions[i].argval) == 2 + arg_tuple = tuple( + varnames[name] if name in varnames else freenames[name] + for name in instructions[i].argval + ) + instructions[i].arg = (arg_tuple[0] << 4) + (arg_tuple[1] & 15) + elif instructions[i].opcode in HAS_LOCAL: + if should_compute_arg(): + if ( + sys.version_info >= (3, 13) + and instructions[i].argval not in varnames + ): + # instructions like LOAD_FAST used for both local and free vars + instructions[i].arg = freenames[instructions[i].argval] + else: + instructions[i].arg = varnames[instructions[i].argval] + elif instructions[i].opcode in HAS_NAME: + if should_compute_arg(): + instructions[i].arg = get_name_index(instructions[i].argval) + elif instructions[i].opcode in HAS_FREE: + if should_compute_arg(): + instructions[i].arg = freenames[instructions[i].argval] + elif instructions[i].opcode in HAS_CONST: + # NOTE: only update argval if arg is not provided. This assumes + # that any additions to co_consts are appended. + if instructions[i].arg is None: + # cannot use a dictionary since consts may not be hashable + idx = get_const_index(code_options, instructions[i].argval) + assert idx >= 0 + instructions[i].arg = idx + + +def clear_instruction_args(instructions: list[Instruction]) -> None: + # Clear the instruction arg for instructions that have argvals. + # Useful for using dis'd bytecode within generated bytecode. + for inst in instructions: + if ( + inst.argval is not _NotProvided + and ( + inst.opcode in HAS_LOCAL + or inst.opcode in HAS_NAME + or inst.opcode in HAS_FREE + or inst.opcode in HAS_CONST + ) + and inst.opname not in ("LOAD_GLOBAL", "LOAD_ATTR", "LOAD_SUPER_ATTR") + ): + inst.arg = None + + +@functools.lru_cache +def get_code_keys() -> list[str]: + # Python 3.11 changes to code keys are not fully documented. + # See https://github.com/python/cpython/blob/3.11/Objects/clinic/codeobject.c.h#L24 + # for new format. + keys = ["co_argcount"] + keys.append("co_posonlyargcount") + keys.extend( + [ + "co_kwonlyargcount", + "co_nlocals", + "co_stacksize", + "co_flags", + "co_code", + "co_consts", + "co_names", + "co_varnames", + "co_filename", + "co_name", + ] + ) + if sys.version_info >= (3, 11): + keys.append("co_qualname") + keys.append("co_firstlineno") + keys.append("co_linetable") + if sys.version_info >= (3, 11): + # not documented, but introduced in https://github.com/python/cpython/issues/84403 + keys.append("co_exceptiontable") + keys.extend( + [ + "co_freevars", + "co_cellvars", + ] + ) + return keys + + +def transform_code_object( + code: types.CodeType, + transformations: Callable[ + [list[Instruction], dict[str, Any]], Optional["DynamoTracerOutput"] + ], + safe: bool = False, +) -> tuple[types.CodeType, Optional["DynamoTracerOutput"]]: + keys = get_code_keys() + code_options = {k: getattr(code, k) for k in keys} + assert len(code_options["co_varnames"]) == code_options["co_nlocals"] + + instructions = cleaned_instructions(code, safe) + # propagate line nums again for added instructions + propagate_line_nums(instructions) + + tracer_output = transformations(instructions, code_options) + _, bytecode = clean_and_assemble_instructions(instructions, keys, code_options) + return bytecode, tracer_output + + +def clean_and_assemble_instructions( + instructions: list[Instruction], keys: list[str], code_options: dict[str, Any] +) -> tuple[list[Instruction], types.CodeType]: + remove_graph_break_if_leaf_instructions(instructions) + # also implicitly checks for no duplicate instructions + check_inst_exn_tab_entries_valid(instructions) + + code_options["co_nlocals"] = len(code_options["co_varnames"]) + varname_from_oparg = None + if sys.version_info >= (3, 11): + # temporary code object with updated names + tmp_code = types.CodeType(*[code_options[k] for k in keys]) + varname_from_oparg = tmp_code._varname_from_oparg # type: ignore[attr-defined] + fix_vars(instructions, code_options, varname_from_oparg=varname_from_oparg) + + dirty = True + while dirty: + update_offsets(instructions) + devirtualize_jumps(instructions) + # this pass might change offsets, if so we need to try again + dirty = bool(fix_extended_args(instructions)) + + remove_extra_line_nums(instructions) + bytecode, lnotab = assemble(instructions, code_options["co_firstlineno"]) + + code_options["co_linetable"] = lnotab + code_options["co_code"] = bytecode + code_options["co_stacksize"] = stacksize_analysis(instructions) + assert set(keys) - {"co_posonlyargcount"} == set(code_options.keys()) - { + "co_posonlyargcount" + } + if sys.version_info >= (3, 11): + code_options["co_exceptiontable"] = assemble_exception_table( + compute_exception_table(instructions) + ) + + return instructions, types.CodeType(*[code_options[k] for k in keys]) + + +def populate_kw_names_argval(instructions: Sequence[Instruction], consts: Any) -> None: + for inst in instructions: + if inst.opname == "KW_NAMES": + inst.argval = consts[inst.arg] + + +# If safe=True, we do not make any bytecode modifications. +# Mainly used for debugging bytecode_transformation (see debug_checks) +def cleaned_instructions(code: types.CodeType, safe: bool = False) -> list[Instruction]: + instructions = _cached_cleaned_instructions(code, safe) + # We have a lot of code that implicitly mutates the instruction array. We + # could do better here by making the copies explicit when necessary. + return _clone_instructions(instructions) + + +# Copy an instructions array, making sure to remap the individual instruction targets. +def _clone_instructions(instructions: Sequence[Instruction]) -> list[Instruction]: + # This is super hot and this is the fastest way to do this (tried copy.copy + # and dataclasses.replace). + copied = [ + Instruction( + i.opcode, + i.opname, + i.arg, + i.argval, + i.offset, + i.starts_line, + i.is_jump_target, + i.positions, + i.target, + i.exn_tab_entry, + i.argrepr, + ) + for i in instructions + ] + + remap = dict(zip(instructions, copied)) + # Handle `None` in the remapper so we don't need an extra `if`. + remap[None] = None # type: ignore[index, assignment] + + for i in copied: + i.target = remap[i.target] # type: ignore[index] + if entry := i.exn_tab_entry: + i.exn_tab_entry = InstructionExnTabEntry( + remap[entry.start], + remap[entry.end], + remap[entry.target], + entry.depth, + entry.lasti, + ) + return copied + + +@functools.lru_cache +def _cached_cleaned_instructions( + code: types.CodeType, safe: bool = False +) -> Sequence[Instruction]: + instructions = list(map(convert_instruction, dis.get_instructions(code))) + # propagate now in case we remove some instructions + propagate_line_nums(instructions) + check_offsets(instructions) + if sys.version_info >= (3, 11): + populate_kw_names_argval(instructions, code.co_consts) + virtualize_exception_table(code.co_exceptiontable, instructions) + virtualize_jumps(instructions) + strip_extended_args(instructions) + if not safe: + if sys.version_info < (3, 11): + remove_load_call_method(instructions) + if sys.version_info < (3, 12): + explicit_super(code, instructions) + if sys.version_info >= (3, 11): + remove_jump_if_none(instructions) + if sys.version_info >= (3, 12): + remove_binary_store_slice(instructions) + if sys.version_info >= (3, 13): + remove_fused_load_store(instructions) + if config.debug_force_graph_break_on_leaf_return: + add_graph_break_if_leaf_instructions(instructions) + if sys.version_info >= (3, 11): + update_offsets(instructions) + devirtualize_jumps(instructions) + return instructions + + +_unique_id_counter = itertools.count() + + +def unique_id(name: str, with_uuid: bool = False) -> str: + ret = f"{name}_{next(_unique_id_counter)}" + if with_uuid: + ret += f"_{uuid.uuid4()}".replace("-", "_") + return ret + + +def is_generator(code: types.CodeType) -> bool: + co_generator = 0x20 + return (code.co_flags & co_generator) > 0 + + +def bytecode_from_template( + fn: Callable[..., Any], + varname_map: Optional[Mapping[Any, Any]] = None, + noreturn: bool = True, + noprefix: bool = True, +) -> list[Instruction]: + """Generates bytecode from a template function `fn` for use in + dynamo bytecode generation. + + For example, we can generate Python-version-independent bytecode + for looping through a dictionary and copying the values to a new dictionary. + + def template(d1, d2): + for k, v in d1.items(): + d2[k] = v + + + or a try block: + + def template(): + try: + dummy1 + except: + dummy2 + raise + dummy3 + + Args: + fn: a function template to generate bytecode from + varname_map: a mapping of `fn`'s varnames to new names. This + map will be applied to the generated bytecode's varnames. + For example, local variables in `fn` can be replaced with + new names that are generated by `OutputGraph.new_var`. + noreturn: remove all RETURN_* bytecodes and replace them with a jump + to the end of the bytecode. NOTE: any items pushed to the stack + for return WILL remain on the stack! Append a POP_TOP if you don't want + that item to be present. + noprefix: remove prefix bytecodes (all bytecode before the first RESUME, inclusive). + """ + insts = cleaned_instructions(fn.__code__) + clear_instruction_args(insts) + + if noprefix: + for i, inst in enumerate(insts): + if inst.opname == "RESUME": + insts = insts[i + 1 :] + break + + for inst in insts: + # If we don't reset starts_line, then the generated + # bytecode's line number will be based on fn's. + inst.starts_line = None + inst.positions = None + if varname_map and inst.argval in varname_map: + inst.argval = varname_map[inst.argval] + + if noreturn: + if sys.version_info >= (3, 12): + # replace RETURN_CONST with LOAD_CONST RETURN_VALUE + new_insts = [] + for inst in insts: + if inst.opname == "RETURN_CONST": + inst.opcode = dis.opmap["LOAD_CONST"] + inst.opname = "LOAD_CONST" + new_insts.append(inst) + # no need to propagate target/exn table + new_insts.append(create_instruction("RETURN_VALUE")) + else: + new_insts.append(inst) + insts = new_insts + + returns = [] + for inst in insts: + if inst.opname == "RETURN_VALUE": + returns.append(inst) + + if len(returns) == 1 and returns[0] is insts[-1]: + # only 1 return at the end - just pop it + insts.pop(-1) + elif len(returns) > 0: + # create jump target - if the last inst is a return, + # we can replace it with a NOP and make that the jump target. + if insts[-1] is returns[-1]: + insts[-1].opname = "NOP" + insts[-1].opcode = dis.opmap["NOP"] + insts[-1].arg = None + insts[-1].argval = _NotProvided + returns.pop(-1) + else: + insts.append(create_instruction("NOP")) + + # replace returns with jumps + for inst in returns: + # don't replace inst with new instruction + # due to targeting/exn table/etc. + jump_inst = create_jump_absolute(insts[-1]) + inst.opname = jump_inst.opname + inst.opcode = jump_inst.opcode + inst.arg = jump_inst.arg + inst.argval = jump_inst.argval + inst.target = jump_inst.target + + return insts diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/cache_size.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/cache_size.py new file mode 100644 index 0000000000000000000000000000000000000000..d1a46742f37ac87c729a9d3973b6c85c36410716 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/cache_size.py @@ -0,0 +1,187 @@ +import logging +import weakref +from dataclasses import dataclass +from typing import Any, Optional + +from torch._guards import CompileId + +from . import config +from .types import DynamoFrameType + + +log: logging.Logger = logging.getLogger(__name__) +""" +[Note on cache size limit] + +Background - TorchDynamo cache is a linked list. Each cache entry is a +(guard_manager, out_code, next pointer). These are stored on the f_code's co_extra +scratch space. When a frame is invoked, we walk this linked list and run +guard_manager in each cache_entry to decide if the frame needs recompilation. If none +of the guard_manager's returns True, we recompile and add a new entry. To ensure we +don't end up recompiling infinitely, we put limits on the cache size. + +There are two limits +1) recompile_limit +2) accumulated_recompile_limit + + +Earlier we used to have only limit - maximum number of entries in 1 cache line +(which is now represented by (2) above). So, why do we need two limits? Lets try +to understand that. + +In general, we want our cache limit value to be a small number (e.g. 8 or even +lower). This ensures that for frames that cause too many recompilation fall to +eager quickly. However, there is another problem that prevents us from lowering +the value of recompile_limit. This is due to ID_MATCH'd guards. Today, we put +ID_MATCH guards on nn module if there is a graph break. This means we will have +many recompilations for the same code object because the ID_MATCH guard fails +for different instances of the nn module. This is a common pattern in how models +are authored. Therefore, this requires us to keep the recompile_limit high. + +We resolve this by introducing these two limits. The first limit (1) limits the +number of cache entries that have an ID_MATCH'd guard for an nn module instance. +And, (2)nd limit becomes a safeguard mechanism to have a maximum compilations +for a code object. One important question is - what is the limit for the code +object that does not have any ID_MATCH guard? For such code objects, we choose +(1) as the cache size limit. + +Lets take an example to understand how these limits help. Suppose, we have 16 +instances of a nn module and we ID_MATCH on the self object. Further, suppose +the inputs to these functions have varying batch size, leading to one +recompilation. In total, there will be 32 recompilations, and therefore 32 cache +entries on the forward code object. In the older case when we had only 1 limit, +our cache size limit must be >= 32 to capture all these recompilations. Now, +suppose there is a separate function in the same program which is very dynamic +and unsuitable for compilation. Such a function will need to undergo 32 +compilations to burst the cache and fallback to eager. These 32 recompilations +are too many and we want to fallback for these compilation-unfriendly functions +sooner. + +In the new scenario, we can have (1) recompile_limit = 2, (2) +accumulated_recompile_limit = 32. This means that each ID_MATCH'd object can +have maximum of two cache entries, and the maximum number of cache entries +(irrespective of ID_MATCH obj) is 32. This covers the case of forward code +object which has 32 recompilations. For the other function, the one unsuitable +for recompilation, our limit is 2. So, we will burst the cache in just 2 +recompilations. In this manner, these 2 limits help us resolve the tension +mentioned earlier. +""" + + +@dataclass +class CacheSizeRelevantForFrame: + """ + We track the number of cache entries that have same id_match objects as the + given frame. + + TODO(janimesh) - Consider adding a map from tuple_of_match_ids to count - + https://github.com/pytorch/pytorch/pull/107496#discussion_r1304564682 - this + could be useful for debugging as well. + """ + + # Total number of CacheEntry objects in the Dynamo linked list + num_cache_entries: int = 0 + + # Number of CacheEntry objects having same ID_MATCH'd objects as given frame. + num_cache_entries_with_same_id_matched_objs: int = 0 + + def will_compilation_exceed(self, limit: int) -> bool: + # Checks if a compilation will exceed the given limit (that's why >=). + return ( + self.will_compilation_exceed_accumulated_limit() + or self.will_compilation_exceed_specific_limit(limit) + ) + + def will_compilation_exceed_accumulated_limit(self) -> bool: + return self.num_cache_entries >= config.accumulated_recompile_limit + + def will_compilation_exceed_specific_limit(self, limit: int) -> bool: + return self.num_cache_entries_with_same_id_matched_objs >= limit + + +def _get_weakref_from_f_locals( + frame: DynamoFrameType, local_name: str +) -> Optional[weakref.ref[Any]]: + obj = frame.f_locals.get(local_name, None) + weak_id = None + try: + weak_id = weakref.ref(obj) + except TypeError: + pass # cannot weakref bool object + return weak_id + + +def _has_same_id_matched_objs(frame: DynamoFrameType, cache_entry: Any) -> bool: + """ + Checks if the ID_MATCH'd objects saved on cache_entry are same as the ones + in frame.f_locals. + """ + if not cache_entry: + return False + + for ( + local_name, + weakref_from_cache_entry, + ) in cache_entry.guard_manager.id_matched_objs.items(): + if weakref_from_cache_entry() is not None: + weakref_from_frame = _get_weakref_from_f_locals(frame, local_name) + if weakref_from_frame is not weakref_from_cache_entry: + return False + + # Also covers the case where no ID_MATCH objects are saved in frame.f_locals + return True + + +def compute_cache_size( + frame: DynamoFrameType, cache_entry: Any +) -> CacheSizeRelevantForFrame: + # Walk the linked list to calculate the cache size + num_cache_entries = 0 + num_cache_entries_with_same_id_matched_objs = 0 + + while cache_entry: + num_cache_entries += 1 + # Track the number of cache entries having same ID_MATCH'd objects as + # that of frame.f_locals. This will be used later to compare against the + # recompile_limit. + if _has_same_id_matched_objs(frame, cache_entry): + num_cache_entries_with_same_id_matched_objs += 1 + cache_entry = cache_entry.next + + return CacheSizeRelevantForFrame( + num_cache_entries, num_cache_entries_with_same_id_matched_objs + ) + + +def is_recompilation(cache_size: CacheSizeRelevantForFrame) -> bool: + """ + If the frame (earlier parsed by compute_cache_size) has more than 1 cache + entry with same ID_MATCH'd objects, then its a recompilation. + """ + # Note that you can have multiple entries in the cache but still not a + # recompile, e.g., you can have 64 nn module instances, each one having an + # ID_MATCH guard, and each one having just 1 cache entry in the cache. In + # this case, we can have 64 entries in the cache, but no recompilation + # because there is only one entry for each id_matched_obj. + return cache_size.will_compilation_exceed(1) + + +def exceeds_recompile_limit( + cache_size: CacheSizeRelevantForFrame, compile_id: CompileId +) -> tuple[bool, str]: + """ + Checks if we are exceeding the cache size limit. + """ + if cache_size.will_compilation_exceed_accumulated_limit(): + return True, "accumulated_recompile_limit" + if cache_size.will_compilation_exceed_specific_limit(config.recompile_limit): + return True, "recompile_limit" + # NOTE this check is needed in the case that the frame's cache doesn't grow + # and we keep recompiling. This can happen if the guard guard_manager becomes invalidated, + # e.g. due to guarded objects being freed. This technically makes the + # will_compilation_exceed_accumulated_limit check unnecessary, but we will keep the + # check in case we have a better fix in the future. + assert compile_id.frame_compile_id is not None + if compile_id.frame_compile_id >= config.accumulated_recompile_limit: + return True, "accumulated_recompile_limit" + return False, "" diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/callback.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/callback.py new file mode 100644 index 0000000000000000000000000000000000000000..25e9f260e34b3b054ba6552ec9d5fc64a61c20fb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/callback.py @@ -0,0 +1,171 @@ +""" +This module provides callback management functionality for TorchDynamo's compilation process. + +It implements a thread-safe system for registering, managing and executing callbacks that run +at the start and end of TorchDynamo compilations. Key features include: + +- Registration and deregistration of compilation callbacks +- Thread-safe callback handling with proper locking mechanisms +- Prevention of duplicate callback execution when configured +- Decorator utilities for easy callback registration +- Context manager for controlled callback lifecycle + +The module centers around the CompilationCallbackHandler class which maintains separate +lists for start and end callbacks, manages their execution order, and ensures thread-safety. +Utility decorators @on_compile_start and @on_compile_end provide a convenient way to +register compilation hooks. + +Example usage: + @on_compile_start + def my_start_callback(): + print("Starting compilation") + + @on_compile_end + def my_end_callback(): + print("Compilation complete") +""" + +import enum +import threading +from collections.abc import Callable, Generator +from contextlib import contextmanager +from dataclasses import dataclass, field # noqa: F811 +from typing import Any + + +class CallbackTrigger(enum.Enum): + # most common case, dynamo attempts to trace a new frame + DYNAMO = 1 + # backward compilation can be deferred to runtime + LAZY_BACKWARD = 2 + # some backends autotune at runtime + TRITON_AUTOTUNING = 3 # Temporarily disabled due to spam + # cudagraphs record at runtime + CUDAGRAPH_RECORDING = 4 + + +@dataclass +class CallbackArgs: + callback_trigger: CallbackTrigger + compile_id: str + + +@dataclass +class CompilationCallbackHandler: + start_callbacks: list[Callable[[CallbackArgs], None]] = field(default_factory=list) + end_callbacks: list[Callable[[CallbackArgs], None]] = field(default_factory=list) + + __pending_callbacks_counter: int = field(default=0, init=False, repr=False) + __pending_callbacks_counter_lock: threading.Lock = field( + default_factory=threading.Lock, init=False, repr=False + ) + + def register_start_callback( + self, callback: Callable[[CallbackArgs], None] + ) -> Callable[[CallbackArgs], None]: + """ + Register a callback function to be called when the compilation starts. + + Args: + - callback (Callable): The callback function to register. + """ + self.start_callbacks.append(callback) + return callback + + def register_end_callback( + self, callback: Callable[[CallbackArgs], None] + ) -> Callable[[CallbackArgs], None]: + """ + Register a callback function to be called when the compilation ends. + + Args: + - callback (Callable): The callback function to register. + """ + self.end_callbacks.append(callback) + return callback + + def remove_start_callback(self, callback: Callable[[CallbackArgs], None]) -> None: + """ + Remove a registered start callback function. + + Args: + - callback (Callable): The callback function to remove. + """ + self.start_callbacks.remove(callback) + + def remove_end_callback(self, callback: Callable[[CallbackArgs], None]) -> None: + """ + Remove a registered end callback function. + + Args: + - callback (Callable): The callback function to remove. + """ + self.end_callbacks.remove(callback) + + def run_start_callbacks(self, args: CallbackArgs) -> None: + """ + Execute all registered start callbacks. + """ + for callback in self.start_callbacks: + callback(args) + + def run_end_callbacks(self, args: CallbackArgs) -> None: + """ + Execute all registered end callbacks. + """ + for callback in self.end_callbacks: + callback(args) + + @contextmanager + def install_callbacks( + self, trigger: CallbackTrigger, compile_id: str + ) -> Generator[None, Any, Any]: + """ + Context manager to install the callbacks and run them when the context is exited. + """ + args = CallbackArgs(trigger, compile_id) + try: + with self.__pending_callbacks_counter_lock: + self.__pending_callbacks_counter += 1 + if self.__pending_callbacks_counter == 1: + self.run_start_callbacks(args) + yield + finally: + with self.__pending_callbacks_counter_lock: + assert self.__pending_callbacks_counter > 0, ( + "Pending callbacks counter cannot become negative." + ) + if self.__pending_callbacks_counter == 1: + self.run_end_callbacks(args) + self.__pending_callbacks_counter -= 1 + + def clear(self) -> None: + """ + Clear all registered callbacks. + """ + self.start_callbacks.clear() + self.end_callbacks.clear() + assert self.__pending_callbacks_counter == 0 + + +callback_handler = CompilationCallbackHandler() + + +def on_compile_start( + callback: Callable[[CallbackArgs], None], +) -> Callable[[CallbackArgs], None]: + """ + Decorator to register a callback function for the start of the compilation. + """ + callback_handler.register_start_callback(callback) + return callback + + +def on_compile_end( + callback: Callable[[CallbackArgs], None], +) -> Callable[[CallbackArgs], None]: + """ + Decorator to register a callback function for the end of the compilation. + """ + callback_handler.register_end_callback(callback) + return callback diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/code_context.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/code_context.py new file mode 100644 index 0000000000000000000000000000000000000000..f2ccb3f0dc90ef8d0f78508bc4a9300997555ebf --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/code_context.py @@ -0,0 +1,60 @@ +""" +This module provides thread-safe code context management for TorchDynamo using weak references. + +The CodeContextDict class maintains a mapping between Python code objects and their associated +context data, using weak references to automatically clean up entries when code objects are +garbage collected. This prevents memory leaks while allowing context data to be associated +with code objects throughout their lifecycle. + +Key features: +- Thread-safe context storage and retrieval +- Automatic cleanup using weak references +- Safe context management for Python code objects +- Memory-leak prevention + +Example usage: + code_obj = compile('x = 1', '', 'exec') + + # Store context + context = code_context.get_context(code_obj) + context['metadata'] = {'optimized': True} + + # Retrieve context + if code_context.has_context(code_obj): + ctx = code_context.get_context(code_obj) + # Use context data... + + # Remove context + ctx = code_context.pop_context(code_obj) +""" + +import types +from typing import Any + +from .utils import ExactWeakKeyDictionary + + +class CodeContextDict: + def __init__(self) -> None: + self.code_context: ExactWeakKeyDictionary = ExactWeakKeyDictionary() + + def has_context(self, code: types.CodeType) -> bool: + return code in self.code_context + + def get_context(self, code: types.CodeType) -> dict[str, Any]: + ctx = self.code_context.get(code) + if ctx is None: + ctx = {} + self.code_context[code] = ctx + return ctx + + def pop_context(self, code: types.CodeType) -> dict[str, Any]: + ctx = self.get_context(code) + self.code_context._remove_id(id(code)) + return ctx + + def clear(self) -> None: + self.code_context.clear() + + +code_context: CodeContextDict = CodeContextDict() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/codegen.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/codegen.py new file mode 100644 index 0000000000000000000000000000000000000000..8c19cb8b61e27a473653cc95725b1badb2f87f98 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/codegen.py @@ -0,0 +1,710 @@ +""" +This module provides utilities for generating Python bytecode in PyTorch's Dynamo system. +It includes functionality for: +- Constructing bytecode sequences for Python operations +- Managing stack operations and variable tracking +- Handling graph outputs and their conversions +- Supporting different Python versions (3.11+, 3.12+, 3.13+) +- Converting high-level operations to low-level bytecode instructions +- Managing constant loading and attribute access +- Supporting function creation and closure handling +""" + +import collections +import dataclasses +import re +import sys +import types +from collections import Counter, deque +from collections.abc import Callable, Iterable +from typing import Any, Optional, TYPE_CHECKING, Union + +import torch.nn +from torch.utils._ordered_set import OrderedSet + +from . import config, graph_break_hints, utils +from .bytecode_transformation import ( + add_push_null, + add_push_null_call_function_ex, + create_binary_subscr, + create_build_tuple, + create_call_function, + create_call_function_ex, + create_call_method, + create_dup_top, + create_instruction, + create_load_const, + create_load_method, + create_rot_n, + Instruction, +) +from .exc import IncorrectUsage, unimplemented +from .source import AttrSource, ChainedSource, DictGetItemSource, Source +from .utils import is_safe_constant, rot_n_helper +from .variables.base import ValueMutationExisting, VariableTracker +from .variables.functions import ( + ContextlibContextManagerLocalGeneratorObjectVariable, + LocalGeneratorObjectVariable, +) +from .variables.nn_module import NNModuleVariable +from .variables.tensor import ( + NumpyNdarrayVariable, + SymNodeVariable, + TensorVariable, + UnspecializedPythonVariable, +) +from .variables.torch_function import TensorWithTFOverrideVariable + + +if TYPE_CHECKING: + from torch._dynamo.variables.builder import GraphArg + + from .symbolic_convert import InstructionTranslatorBase + + +@dataclasses.dataclass +class GraphOutputEntry: + index: int + variable: VariableTracker + + +class PyCodegen: + """ + Helper class uses for constructing Python bytecode + """ + + def __init__( + self, + tx: "InstructionTranslatorBase", + root: Optional[torch.nn.Module] = None, + graph_output_var: Optional[str] = None, + tempvars: Optional[dict[Union[VariableTracker, Source], Any]] = None, + overridden_sources: Optional[dict[Source, Source]] = None, + ) -> None: + self.root = root + self.top_of_stack: Optional[Union[VariableTracker, Source]] = None + self.uses: Counter[Union[VariableTracker, Source]] = collections.Counter() + self.graph_outputs: dict[int, GraphOutputEntry] = {} + self._output: list[Instruction] = [] + # This determines which VariableTracker/Source should be stored as + # locals, and maps the VariableTracker/Source to the local variable + # name. Note that it could map to None initially, in which case we'll + # overwrite it to map to real temporary names via `add_cache`. + self.tempvars: dict[Union[VariableTracker, Source], Any] = tempvars or {} + self.tx = tx + self.graph_output_var = graph_output_var + self.code_options = self.tx.output.code_options + self.cell_and_freevars = self.tx.cell_and_freevars + self.new_var = self.tx.output.new_var + self.value_from_source: bool = True + # This serves as a way for codegen to use a different source; we need + # this because sometimes we can't easily modify the original source + # without affecting other components, e.g., guards. + self.overridden_sources: dict[Source, Source] = overridden_sources or {} + + def restore_stack( + self, stack_values: list[Any], *, value_from_source: bool = True + ) -> None: + prev = self.value_from_source + self.value_from_source &= value_from_source + try: + self.foreach(stack_values) + finally: + self.value_from_source = prev + + def graph_output_vars(self) -> list[VariableTracker]: + return [x.variable for x in self.graph_outputs.values()] + + def call_reconstruct( + self, value: Union[VariableTracker, Source, "GraphArg"] + ) -> None: + res = value.reconstruct(self) + assert res is None, f"reconstruct!=None {value}" + + def add_push_null( + self, gen_fn: Callable[[], None], call_function_ex: bool = False + ) -> None: + """ + `gen_fn` generates instructions via PyCodegen methods + that push a single callable to the stack. + + `add_push_null` pushes a NULL to the stack before or after the + instructions generated by `gen_fn`, depending on Python version. + + Will attempt to use the NULL push bit for instructions + with such bits (LOAD_GLOBAL 3.11+, LOAD_ATTR 3.12+, LOAD_SUPER_ATTR). + """ + old_len = len(self._output) + if sys.version_info < (3, 13): + # gen_fn may DUP_TOP instead if TOS is not cleared. + # Will cause problems since NULL will be pushed right + # before the generated instructions in <= 3.12 + self.clear_tos() + gen_fn() + # inplace modify self._output + added_insts = self._output[old_len:] + del self._output[old_len:] + if call_function_ex: + self._output.extend(add_push_null_call_function_ex(added_insts)) + else: + self._output.extend(add_push_null(added_insts)) + if sys.version_info >= (3, 13): + # NULL will be at top of stack + self.clear_tos() + + def __call__( + self, value: Union[VariableTracker, Source, None], allow_cache: bool = True + ) -> None: + """ + Generate code such that top-of-stack (TOS) is set to value. + + `allow_cache` controls the behavior in the following manner. `value` can + either be a VariableTracker or a Source. + + If `value` is a `Source`, `allow_cache` must be True (invariant asserted + below). If the source was reconstructed earlier, we will reuse the + generated code by loading from top of stack or tempvars. + + If `value` is a `VariableTracker`, we have the following cases: + + 1) `allow_cache=True` + a) If the value.source is not None, we will emit the code based on + `value.source` to handle aliasing. + b) If value.source is None (example reconstructing a local list + returned by the compiled function), we will reconstruct the variable + tracker (w/o any source) to emit bytecode that generates a new + python object. + + In both cases of value.source being None or not, if the value was + reconstructed earlier, we will reuse the generated code by loading from + top of stack or tempvars. + + 2) `allow_cache=False` - This is a special case (allow_cache defaults to + True). + a) If the value.source is not None, we reconstruct the variable + tracker and emit a new python object. You might wonder what about + aliasing? The place where we use this config also has the followup + code where the original python object is assigned to this new python + value to handle aliasing (check side_effects.py and search for + allow_cache=False). + + b) If value.source is None, this is not allowed + + Notable effects: + 1. `self.top_of_stack` will be set to `value`, if we don't codegen + `value` based on source. + 2. `self.uses[value]` will increment, unless (a). we codegen via + `top_of_stack` or cached `tempvars`, or (b). `value` has special VT + types like `NNModuleVariable`, etc. + """ + assert value is not None + if isinstance(value, Source): + # If the source needs to be overridden, use the new one. + source = self.overridden_sources.get(value, value) + assert allow_cache is True, "allow_cache must be True for Source" + if self.top_of_stack is value: + self._output.append(create_dup_top()) + return + + if self.tempvars.get(source) is not None: + self._output.append(self.create_load(self.tempvars[source])) + self.top_of_stack = source + return + + self.uses[source] += 1 + try: + self.call_reconstruct(source) + except NotImplementedError: + unimplemented( + gb_type="Reconstruction failure: source.reconstruct not implemented", + context=str(source), + explanation=f"Dynamo has no bytecode reconstruction implemented for {type(source)} variable {source}.", + hints=[*graph_break_hints.DYNAMO_BUG], + ) + if source in self.tempvars: + self._output.append(create_dup_top()) + self.add_cache(source) + self.top_of_stack = source + + return + + assert isinstance(value, VariableTracker) + output = self._output + graph_outputs = self.graph_outputs + + if allow_cache: + if self.top_of_stack is value: + output.append(create_dup_top()) + return + + if self.tempvars.get(value) is not None: + output.append(self.create_load(self.tempvars[value])) + self.top_of_stack = value + return + + if value.is_realized() and isinstance( + value, ContextlibContextManagerLocalGeneratorObjectVariable + ): + raise IncorrectUsage( + "NYI: Returning a @contextmanager object from a torch.compile function" + ) + + # Dynamo normally prefers codegen from source to account for aliasing. + if ( + value.source is not None + and allow_cache + and not ( + value.is_realized() and isinstance(value, LocalGeneratorObjectVariable) + ) + ): + # There's a corner case for export: for instance, if the computation + # graph is just identity on an input tensor, Dynamo would just emit + # a `LOAD_FAST` from the input source, rather than generating an + # identity FX graph. + # + # However, export wants to maximize graph capture; in the case + # above, export _wants to_ obtain an identity FX graph (despite it + # appears unnecessarily expensive for `torch.compile`), so we have + # the following option to override Dynamo's preference for codegen + # from source. Moreover, this option applies recursively, for cases + # like input tensor being returned in a new dictionary. + # + # And why the `ValueMutationExisting` check? Not sure, so leaving it + # to keep the old behavior, as when `value_from_source` was + # introduced. TODO sort out the invariants among side effect, + # codegen and export. + if ( + isinstance(value.mutation_type, ValueMutationExisting) + or self.value_from_source + ): + return self(value.source) + + if value.is_python_constant() and is_safe_constant(value.as_python_constant()): + output.append(self.create_load_const(value.as_python_constant())) + elif isinstance(value, TensorWithTFOverrideVariable): + graph_outputs_key = self.add_graph_output(value) + + self.add_push_null( + lambda: self.load_import_from(utils.__name__, "to_subclass") + ) + self.load_graph_output(graph_outputs[graph_outputs_key].index) + output.append( + self.create_load_global( + value.global_mangled_class_name(self.tx), # type: ignore[arg-type] + add=True, + ) + ) + output.extend(create_call_function(2, False)) + elif ( + isinstance(value, SymNodeVariable) + and value.python_type() is float + and not self.tx.export + ): + # This is a little unusual; force the output convention to be a + # Tensor here. Don't do this for export because this is + # apparently load bearing for export tests (but I am a bit + # doubtful it actually works in the real world) + # NB: It works to add_graph_output on a computed expression + # as_tensor here, because we memoize as_tensor calls on + # SymNodeVariable! + graph_outputs_key = self.add_graph_output( + value.as_tensor(self.tx, torch.float64) + ) + + def gen_fn() -> None: + self.load_graph_output(graph_outputs[graph_outputs_key].index) + output.append(self.create_load_attr("item")) + + self.add_push_null(gen_fn) + output.extend(create_call_function(0, False)) + elif isinstance( + value, + ( + TensorVariable, + SymNodeVariable, + UnspecializedPythonVariable, + NumpyNdarrayVariable, + ), + ): + graph_outputs_key = self.add_graph_output(value) + + if isinstance(value, NumpyNdarrayVariable): + self.add_push_null( + lambda: self.load_import_from(utils.__name__, "to_numpy_helper") + ) + self.load_graph_output(graph_outputs[graph_outputs_key].index) + output.extend(create_call_function(1, False)) + elif isinstance(value, UnspecializedPythonVariable) and value.need_unwrap: + + def gen_fn() -> None: + self.load_graph_output(graph_outputs[graph_outputs_key].index) + output.append(self.create_load_attr("item")) + + self.add_push_null(gen_fn) + output.extend(create_call_function(0, False)) + else: + self.load_graph_output(graph_outputs[graph_outputs_key].index) + elif isinstance(value, NNModuleVariable): + parts = value.module_key.split(".") + if parts[0] in self.code_options["co_varnames"]: + output.append(self.create_load(parts[0])) + parts = parts[1:] + else: + assert self.root is not None + output.append(self.create_load_const_unchecked(self.root)) + for part in parts: + output.append(self.create_load_attr(part)) + else: + self.uses[value] += 1 + try: + self.call_reconstruct(value) + except NotImplementedError: + unimplemented( + gb_type="Reconstruction failure", + context=str(value), + explanation=f"Dynamo has no bytecode reconstruction implemented for sourceless variable {value}.", + hints=[ + "If Dynamo is attempting to trace a return statement and your code is attempting to return a variable " + "that Dynamo cannot reconstruct, then remove it from the return statement.", + *graph_break_hints.CAUSED_BY_EARLIER_GRAPH_BREAK, + "Report an issue to PyTorch if you need reconstrtuction support. Note that objects that don't have " + "reconstruction rules may be fundamentally unreconstructable.", + ], + ) + if allow_cache and value in self.tempvars: + self._output.append(create_dup_top()) + self.add_cache(value) + + self.top_of_stack = value + + def add_graph_output(self, value: VariableTracker) -> int: + graph_outputs_key = id(value.as_proxy()) + if graph_outputs_key not in self.graph_outputs: + self.graph_outputs[graph_outputs_key] = GraphOutputEntry( + len(self.graph_outputs), value + ) + return graph_outputs_key + + def load_graph_output(self, index: int) -> None: + output = self._output + assert self.graph_output_var is not None + output.append(self.create_load(self.graph_output_var)) + output.append(self.create_load_const(index)) + output.append(self.create_binary_subscr()) + + def add_cache(self, value: Union[VariableTracker, Source]) -> None: + var = self.new_var() + self.tempvars[value] = var + self._output.append(self.create_store(var)) + + def foreach(self, items: Iterable[Union[VariableTracker, Source]]) -> None: + for i in items: + self(i) + + def create_binary_subscr(self) -> Instruction: + return create_binary_subscr() + + def setup_globally_cached(self, name: str, value: Any) -> list[Instruction]: + """Store value in a new global""" + name = re.sub(r"[^a-zA-Z0-9_]+", "_", name) + f_globals = self.tx.f_globals + if name in f_globals: + assert id(f_globals[name]) == id(value) + else: + f_globals[name] = value + return [self.create_load_global(name, add=True)] + + def clear_tos(self) -> None: + self.top_of_stack = None + + def append_output(self, inst: Instruction) -> None: + assert isinstance(inst, Instruction) + self._output.append(inst) + self.clear_tos() + + def extend_output(self, insts: list[Instruction]) -> None: + assert all(isinstance(x, Instruction) for x in insts) + self._output.extend(insts) + self.clear_tos() + + def get_instructions(self) -> list[Instruction]: + return self._output + + def create_load(self, name: str) -> Instruction: + assert name in self.code_options["co_varnames"], f"{name} missing" + return create_instruction("LOAD_FAST", argval=name) + + def create_load_closure(self, name: str) -> Instruction: + assert name in self.cell_and_freevars() + inst_name = "LOAD_FAST" if sys.version_info >= (3, 13) else "LOAD_CLOSURE" + return create_instruction(inst_name, argval=name) + + def create_load_deref(self, name: str) -> Instruction: + assert name in self.cell_and_freevars() + return create_instruction("LOAD_DEREF", argval=name) + + def create_store(self, name: str) -> Instruction: + assert name in self.code_options["co_varnames"], f"{name} missing" + return create_instruction("STORE_FAST", argval=name) + + def create_store_deref(self, name: str) -> Instruction: + assert name in self.cell_and_freevars() + return create_instruction("STORE_DEREF", argval=name) + + def create_load_global(self, name: str, add: bool = False) -> Instruction: + if add: + self.tx.output.update_co_names(name) + assert name in self.code_options["co_names"], f"{name} not in co_names" + return create_instruction("LOAD_GLOBAL", argval=name) + + def create_load_const(self, value: Any) -> Instruction: + return create_load_const(value) + + def create_load_const_unchecked(self, value: Any) -> Instruction: + return create_load_const(value, checked=False) + + def load_method(self, name: str) -> None: + self.tx.output.update_co_names(name) + self.append_output(create_load_method(name)) + + def call_method(self, nargs: int) -> None: + self.extend_output(create_call_method(nargs)) + + def create_load_attr(self, name: str) -> Instruction: + if name not in self.code_options["co_names"]: + self.code_options["co_names"] += (name,) + return create_instruction("LOAD_ATTR", argval=name) + + def load_attr(self, name: str) -> None: + self.append_output(self.create_load_attr(name)) + + def create_load_attrs(self, names: str) -> list[Instruction]: + return [self.create_load_attr(name) for name in names.split(".")] + + def create_store_attr(self, name: str) -> Instruction: + if name not in self.code_options["co_names"]: + self.code_options["co_names"] += (name,) + return create_instruction("STORE_ATTR", argval=name) + + def store_attr(self, name: str) -> None: + self.append_output(self.create_store_attr(name)) + + def load_function_name( + self, fn_name: str, push_null: bool, num_on_stack: int = 0 + ) -> list[Instruction]: + """Load the global fn_name on the stack num_on_stack down""" + output = [] + if push_null and sys.version_info >= (3, 11): + output.extend(add_push_null(self.create_load_global(fn_name, add=True))) + if num_on_stack > 0: + output.extend( + [ + *self.rot_n(num_on_stack + 2), + *self.rot_n(num_on_stack + 2), + ] + ) + else: + output.extend( + [ + self.create_load_global(fn_name, add=True), + *self.rot_n(num_on_stack + 1), + ] + ) + return output + + def rot_n(self, n: int) -> list[Instruction]: + try: + return create_rot_n(n) + except AttributeError: + # desired rotate bytecode doesn't exist, generate equivalent bytecode + return [ + create_build_tuple(n), + self.create_load_const_unchecked(rot_n_helper(n)), + *create_rot_n(2), + *create_call_function_ex(False, False), + create_instruction("UNPACK_SEQUENCE", arg=n), + ] + + def pop_top(self) -> None: + self.append_output(create_instruction("POP_TOP")) + + def call_function(self, nargs: int, push_null: bool) -> None: + self.extend_output(create_call_function(nargs, push_null=push_null)) + + def dup_top(self) -> None: + self.append_output(create_dup_top()) + + def store(self, varname: str) -> None: + self.append_output(self.create_store(varname)) + + def load_deref(self, varname: str) -> None: + self.append_output(self.create_load_deref(varname)) + + def make_function_with_closure( + self, + fn_name: str, + code: types.CodeType, + ) -> None: + """Creates a closure with code object `code`. + + Expects the TOS to be the tuple of cells to use for this closure. + TOS will be popped to create the closure. + Args: + - fn_name: name of the function + - code: code object of the function + (does not include the tuple of cells on the TOS) + """ + output = self._output + + output.append(self.create_load_const(code)) + if sys.version_info < (3, 11): + output.append(self.create_load_const(fn_name)) + if sys.version_info >= (3, 13): + output.extend( + [ + create_instruction("MAKE_FUNCTION"), + create_instruction("SET_FUNCTION_ATTRIBUTE", arg=0x08), + ] + ) + else: + output.append(create_instruction("MAKE_FUNCTION", arg=0x08)) + + self.clear_tos() + + def create_load_python_module(self, mod: types.ModuleType) -> Instruction: + """ + Generate a LOAD_GLOBAL instruction to fetch a given python module. + """ + output = self.tx.output + global_scope = output.global_scope + name = re.sub(r"^.*[.]", "", mod.__name__) + if global_scope.get(name, None) is mod: + return self.create_load_global(name, add=True) + prefix = f"___module_{name}" + global_name = self.tx.output.install_global_by_id(prefix, mod) + return self.create_load_global(global_name, add=True) + + def mark_source_temp(self, source: Source) -> None: + """ + Mark a source as a temp variable, so that it can be reused. + """ + if source not in self.tempvars: + self.tempvars[source] = None + + def make_call_generated_code(self, fn_name: str) -> None: + """Call the generated code function stored in fn_name""" + self.extend_output(self.load_function_name(fn_name, True)) + + graphargs = self.tx.output.graphargs + + def extract_nested_sources(source: Source) -> list[Source]: + nested_sources: list[Source] = [] + if isinstance(source, ChainedSource): + nested_sources.append(source.base) + if isinstance(source, DictGetItemSource) and isinstance( + source.index, Source + ): + nested_sources.append(source.index) + return nested_sources + + def collect_temp_sources(sources: deque[Source], codegen: PyCodegen) -> None: + seen_sources: OrderedSet[Source] = OrderedSet() + while sources: + current_source = sources.popleft() + if current_source in seen_sources: + # This source is used at least twice, so it can be reused + codegen.mark_source_temp(current_source) + # Dont trace source further. This prevents us from marking too + # many nodes as temp sources. + continue + seen_sources.add(current_source) + sources.extend(extract_nested_sources(current_source)) + + # Collect all the sources that are used more than once, so that we can + # generate tmp variables in the generated pre-graph bytecode. This + # essentially implements CSE. + collect_temp_sources( + deque([arg.source for arg in graphargs if arg.source is not None]), self + ) + + cm_var = None + if config.record_runtime_overhead: + # Record the pregraph bytecode start + self.add_push_null( + lambda: self.load_import_from( + utils.__name__, "record_pregraph_bytecode_enter" + ) + ) + self.extend_output(create_call_function(0, False)) + cm_var = self.new_var() + self.store(cm_var) + + for arg in graphargs: + if arg.pass_arg_as_tensor: + self.add_push_null( + lambda: self.extend_output( + [ + self.create_load_python_module(torch), + self.create_load_attr("_as_tensor_fullprec"), + ] + ) + ) + self.call_reconstruct(arg) + self.extend_output(create_call_function(1, False)) + else: + self.call_reconstruct(arg) + + if config.record_runtime_overhead: + # Record the pregraph bytecode end + self.add_push_null( + lambda: self.load_import_from( + utils.__name__, "record_pregraph_bytecode_exit" + ) + ) + assert cm_var is not None + self.extend_output([self.create_load(cm_var)]) + self.extend_output(create_call_function(1, False)) + self.pop_top() + + self.extend_output(create_call_function(len(graphargs), False)) + + def create_import_name(self, module_name: str) -> Instruction: + return create_instruction("IMPORT_NAME", argval=module_name) + + def load_import_from(self, module_name: str, object_name: str) -> None: + source = AttrSource(self.tx.import_source(module_name), object_name) + # Note: This approach is somewhat aggressive because typically, a source is marked + # as a tempvar only when it is used more than once. In this case, we're marking it + # as a tempvar without performing that analysis. However, this is a simple solution, + # and in many cases, load imports are reused multiple times. + self.mark_source_temp(source) + self(source) + + def create_call_function_kw( + self, nargs: int, kw_names: Iterable[str], push_null: bool + ) -> list[Instruction]: + if sys.version_info >= (3, 13): + output = create_call_function(nargs, push_null) + assert output[-1].opname == "CALL" + output.insert(-1, self.create_load_const(kw_names)) + output[-1] = create_instruction("CALL_KW", arg=nargs) + return output + elif sys.version_info >= (3, 11): + output = create_call_function(nargs, push_null) + if sys.version_info >= (3, 12): + idx = -1 + expected_inst = "CALL" + else: + idx = -2 + expected_inst = "PRECALL" + assert output[idx].opname == expected_inst + kw_names_inst = create_instruction("KW_NAMES", argval=kw_names) + output.insert(idx, kw_names_inst) + return output + return [ + self.create_load_const(kw_names), + create_instruction("CALL_FUNCTION_KW", arg=nargs), + ] + + def create_delete(self, value: object) -> Instruction: + return create_instruction("DELETE_FAST", argval=value) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/compiled_autograd.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/compiled_autograd.py new file mode 100644 index 0000000000000000000000000000000000000000..5f501a564ada50e6368d5f7f8bcf1c1bd3fc3a72 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/compiled_autograd.py @@ -0,0 +1,1620 @@ +""" +Provides functionality for compiling PyTorch's autograd (automatic differentiation) system. + +This module implements compiled autograd, which traces and optimizes backward pass +computations at runtime. The key components are: + +- AutogradCompilerInstance: Traces and compiles autograd graphs using FX +- Context managers (_enable/_disable): Control when compiled autograd is active +- Utility functions: Support graph manipulation, tensor operations, and hooks + +Compiled autograd can significantly improve backward pass performance by removing +Python overhead and enabling additional optimizations. It works by capturing +backward computations into an FX graph that can be compiled and optimized, +while maintaining the same semantics as eager mode autograd. +""" + +import contextlib +import functools +import itertools +import operator +import time +from collections import Counter, defaultdict +from collections.abc import Callable, Generator, Sequence +from typing import Any, Optional, TYPE_CHECKING, Union + +import torch +import torch.utils._pytree as pytree +from torch._dispatch.python import enable_python_dispatcher +from torch._dynamo.external_utils import ( + call_accumulate_grad, + call_backward, + call_hook, + FakeCompiledAutogradEngine, + unwrap_maybe_dynamic_int, +) +from torch._dynamo.source import GetItemSource, LocalSource +from torch._dynamo.utils import ( + counters, + get_chromium_event_logger, + lazy_format_graph_code, + set_locals_to_steal, +) +from torch._functorch._aot_autograd.runtime_wrappers import ( + AutogradLazyBackwardCompileInfo, + CachedAutogradLazyBackwardCompileInfo, +) +from torch._guards import compile_context, CompileContext, CompileId, Source +from torch._logging import getArtifactLogger, trace_structured +from torch._prims_common import clone_preserve_strides +from torch._subclasses import FakeTensorMode +from torch._subclasses.fake_tensor import FakeTensor +from torch.fx import GraphModule +from torch.fx.experimental._backward_state import BackwardState +from torch.fx.experimental.proxy_tensor import ( + decompose, + disable_autocast_cache, + disable_proxy_modes_tracing, + fetch_object_proxy, + ProxyTorchDispatchMode, + PythonKeyTracer, + track_tensor_tree, +) +from torch.fx.experimental.symbolic_shapes import DimDynamic, ShapeEnv +from torch.fx.traceback import preserve_node_meta, set_stack_trace +from torch.types import FloatLikeType, IntLikeType +from torch.utils._ordered_set import OrderedSet +from torch.utils._traceback import CapturedTraceback + + +if TYPE_CHECKING: + from torch.fx.proxy import Proxy + + +TURN_OFF_MSG = """You can turn off compiled autograd by either: +1. Moving the unsupported autograd call outside of the torch.compile'd region. +2. Wrapping the unsupported autograd call in the torch._dynamo.compiled_autograd._disable() context manager. +3. Setting torch._dynamo.config.compiled_autograd=False for the torch.compile call containing the unsupported autograd call. +4. Setting torch._dynamo.config.compiled_autograd=False at the start of the program.""" + +compiled_autograd_log = getArtifactLogger(__name__, "compiled_autograd") +verbose_log = getArtifactLogger(__name__, "compiled_autograd_verbose") + + +def snapshot_verbose_logging_enabled() -> bool: + return torch._logging._internal.log_state.is_artifact_enabled( + "compiled_autograd_verbose" + ) + + +def snapshot_cudagraph_enabled() -> bool: + return torch._inductor.config.triton.cudagraphs + + +def maybe_clone(x: Optional[torch.Tensor]) -> Optional[torch.Tensor]: + if x is not None: + return clone_preserve_strides(x) + return x + + +def extract_bw_module(CompiledFunction: Any) -> Callable[..., Any]: + if isinstance( + CompiledFunction._lazy_backward_info, AutogradLazyBackwardCompileInfo + ): + return CompiledFunction._lazy_backward_info.bw_module + elif isinstance( + CompiledFunction._lazy_backward_info, CachedAutogradLazyBackwardCompileInfo + ): + with torch._subclasses.fake_tensor.unset_fake_temporarily(): + return CompiledFunction._lazy_backward_info.bw_module_fn() + else: + raise AssertionError( + "Unexpected Lazy Backward Compilation Info Type. Please file an issue." + ) + + +# Note: [Anomaly Mode Semantics in Compiled Autograd] +# In the eager autograd engine, anomaly mode is able to detect NaNs +# after each node. This is useful, because the executed code with +# and without anomaly mode are the same. So assuming determinism, +# a NaN in regular mode should also happen in anomaly mode. +# +# With torch.compile, following eager semantics would require inserting +# runtime asserts to check for NaNs, which could prevent some fusions. +# This results in different code being run with and without anomaly mode. +# So different semantics are needed, this implementation below will check +# for NaNs at the end of the autograd call, instead of after each node +class NaNChecker: + def __init__(self, accumulate_grad: bool) -> None: + self.accumulate_grad = accumulate_grad + self.params_indices: list[int] = [] + self.params_to_check: dict[str, torch.Tensor] = {} + self.output_names: list[str] = [] + + def prep_with_graph(self, graph: torch.fx.Graph) -> None: + inputs_node = next(iter(graph.nodes)) + acc_grad_nodes = graph.find_nodes( + op="call_function", target=call_accumulate_grad + ) + output_nodes = graph.find_nodes(op="output")[0].args[0] + assert self.accumulate_grad == bool( + acc_grad_nodes + ) and self.accumulate_grad == (not output_nodes) + + for node in acc_grad_nodes: + param_node = node.args[0] + # AccumulateGrad always saves a reference to the param + # so Compiled Autograd will always lift the param and + # this should always be true + assert ( + param_node.target is operator.getitem + and param_node.args[0] is inputs_node # type: ignore[possibly-undefined] + and isinstance(param_node.args[1], int) + ) + self.params_indices.append(param_node.args[1]) + + self.output_names = [node.name for node in output_nodes] + + def prep_with_inputs(self, inputs: tuple[torch.Tensor, ...]) -> None: + if not self.accumulate_grad: + # Using .grad, nothing to prep + return + + # Using .backward, we must check existing grads on params if any + for idx in self.params_indices: + grad = inputs[idx].grad + if grad is not None: + assert not torch.isnan(grad).any(), ( + f"Compiled autograd running under anomaly mode with inputs[{idx}] already " + f"having NaN gradient. This is not supported. {TURN_OFF_MSG}" + ) + + self.params_to_check[f"inputs[{idx}]"] = inputs[idx] + + def check(self, out: tuple[torch.Tensor, ...]) -> None: + if self.accumulate_grad: + # Using .backward, graph outputs are empty + assert not out + nan_params: list[str] = [] + for inputs_str, param in self.params_to_check.items(): + assert param.grad is not None # not true for autograd.grad + if torch.isnan(param.grad).any(): + nan_params.append(inputs_str) + + if nan_params: + raise RuntimeError( + f"Compiled Autograd returned NaN gradients for parameters: {','.join(nan_params)}." + ) + else: + # Using .grad, graph outputs are grads + nan_grads: list[str] = [] + for i, grad in enumerate(out): + if torch.isnan(grad).any(): + nan_grads.append(self.output_names[i]) + + if nan_grads: + raise RuntimeError( + f"Compiled Autograd returned NaN gradients for output nodes: {','.join(nan_grads)}." + ) + + +# We lazily bind "functional backward" variants for PyTorch built-in autograd +# nodes to this class. Example: torch._dynamo.compiled_autograd.ops.MulBackward0 +# Each "functional backward" is bound the first time the node's apply_with_saved +# function is called. It's possible to avoid lazy binding and instead bind +# all of this upfront (perhaps at import time) via codegen changes. +class OpNamespace: + def __init__(self) -> None: + self.custom_function_name_counter: Counter[str] = Counter() + + def add( + self, + name: str, + fn: Callable[..., Any], + is_custom_function: bool, + is_traceable: bool, + ) -> str: + if is_custom_function: + name = "CppNode" + name + count = self.custom_function_name_counter[name] + self.custom_function_name_counter[name] += 1 + name = f"{name}{count}" + + assert not hasattr(self, name) + result = Op(name, fn, is_custom_function) + if is_traceable: + setattr(self, name, torch._dynamo.allow_in_graph(result)) + else: + # C++ autograd function was not marked as traceable + # Dynamo can't dry run it at compile time, so must fallback to eager + @torch._dynamo.disable # type: ignore[misc] + def run_non_traceable_cpp_in_eager(*args: Any, **kwargs: Any) -> Any: + return result(*args, **kwargs) + + setattr(self, name, run_non_traceable_cpp_in_eager) + return name + + def get(self, name: str) -> Any: + return getattr(self, name) + + +class Op: + def __init__( + self, name: str, fn: Callable[..., Any], is_custom_function: bool + ) -> None: + self.fn = fn + self.is_custom_function = is_custom_function + self.__name__ = name + self.__module__ = "torch._dynamo.compiled_autograd.ops" + + def __call__(self, *args: Any, **kwargs: Any) -> Any: + return self.fn(*args, **kwargs) + + def __repr__(self) -> str: + return self.__module__ + "." + self.__name__ + + +ops = OpNamespace() + + +_graph_placeholders = ["inputs", "sizes", "scalars", "hooks", "packed_data"] +_impure_targets = OrderedSet( + [ + call_hook, + call_backward, + FakeCompiledAutogradEngine._exec_final_callbacks_stub, + call_accumulate_grad, + ] +) + +COMPILE_COUNTER = itertools.count() + + +def make_compile_context(compiled_autograd_id: int) -> Any: + return compile_context( + CompileContext( + CompileId( + compiled_autograd_id=compiled_autograd_id, + frame_id=None, + frame_compile_id=None, + ) + ) + ) + + +class AutogradCompilerInstance: + def __init__(self, compiler_fn: Callable[..., Any]) -> None: + self.compiler_fn = compiler_fn + self.stack = contextlib.ExitStack() + self.close = self.stack.close + self.shape_env = ShapeEnv() + self.fake_tensor_mode = FakeTensorMode( + allow_fallback_kernels=True, + allow_non_fake_inputs=True, + shape_env=self.shape_env, + ) + self.fx_tracer = PythonKeyTracer() + self.proxy_mode = ProxyTorchDispatchMode(self.fx_tracer, "symbolic") + self.hooks_proxy: Optional[Proxy] = None + + def wrap_fake(self, x: torch.Tensor, source: Optional[Source]) -> FakeTensor: + assert isinstance(x, torch.Tensor) + return self.fake_tensor_mode.from_tensor(x, source=source) + + @staticmethod + def source(name: str, idx: Any) -> GetItemSource: + return GetItemSource(LocalSource(name), idx) + + def begin_capture( + self, + inputs: list[torch.Tensor], + sizes: list[int], + scalars: list[Union[int, float]], + origins: list[list[tuple[int, str]]], + accumulate_grad: bool, + check_nans: bool, + ) -> tuple[str, list[torch.Tensor], list[IntLikeType], list[FloatLikeType]]: + counters["compiled_autograd"]["captures"] += 1 + self.id = next(COMPILE_COUNTER) + self.aot_id_counter: dict[int, int] = defaultdict(int) + self.compile_context = make_compile_context(self.id) + self.compile_context.__enter__() + self.nan_checker = NaNChecker(accumulate_grad) if check_nans else None + self.start_time_ns = time.time_ns() + get_chromium_event_logger().log_event_start( + "compiled_autograd", + self.start_time_ns, + {"graph_id": self.id}, + log_pt2_compile_event=True, + ) + self.fx_tracer.root = torch.nn.Module() + self.fx_tracer.graph = torch.fx.Graph(tracer_cls=PythonKeyTracer) + self.fx_tracer.tensor_attrs = {} + self.symnode_proxy_lookup = {} + ( + args_proxy, + self.sizes_proxy, + self.scalars_proxy, + self.hooks_proxy, + self.packed_data_proxy, + ) = ( + self.fx_tracer.create_proxy("placeholder", name, (), {}) + for name in _graph_placeholders + ) + + self.stack.enter_context(preserve_node_meta()) + inputs_origins, sizes_origins, scalars_origins = origins + + # Turn on PythonDispatcher during initial trace to make it identifiable + # that tracing is happening, which is needed to prevent hashing symints + self.stack.enter_context(enable_python_dispatcher()) + + # tensor inputs to fake tensors + x = inputs[0] # mypy will complain about unbound x + try: + for idx, x in enumerate(inputs): + inputs[idx] = self.wrap_fake(x, self.source("inputs", idx)) + except Exception as e: + raise NotImplementedError( + f"Found tensor of type {type(x)}, which is not supported by FakeTensorMode. {TURN_OFF_MSG}" + ) from e + self.bind_objects_to_proxies(inputs, args_proxy, inputs_origins) + + # size inputs to symints + sym_sizes = [ + self.shape_env.create_unspecified_symint_and_symbol( + val, + self.source("sizes", idx), + DimDynamic.DYNAMIC, + ) + for idx, val in enumerate(sizes) + ] + + # We want to mark every size as dynamic, but since there's no way to + # mark a primitive `int` as dynamic, we need to wrap it in a tensor. + # In the graph, we unwrap it with `unwrap_maybe_dynamic_int` back into a primitive. + proxies = [self.sizes_proxy[i] for i in range(len(sym_sizes))] # type: ignore[index] + for i, symint in enumerate(sym_sizes): + proxies[i] = self.fx_tracer.create_proxy( + "call_function", + unwrap_maybe_dynamic_int, + (proxies[i],), + {}, + ) + self.symnode_proxy_lookup[symint.node] = proxies[i] + proxies = self.bind_objects_to_proxies(sym_sizes, proxies, sizes_origins) + + for idx, val in enumerate(scalars): + source = self.source("scalars", idx) + if isinstance(val, int): + scalars[idx] = self.shape_env.create_unspecified_symint_and_symbol( + val, + source, + DimDynamic.DYNAMIC, + ) + elif isinstance(val, float): + scalars[idx] = self.shape_env.create_symfloatnode( + self.shape_env.create_unspecified_symbol( + val, + source=source, + dynamic_dim=DimDynamic.DYNAMIC, + ), + hint=val, + source=source, + ) + else: + raise AssertionError("Unexpected scalar type: ", type(val)) + self.bind_objects_to_proxies(scalars, self.scalars_proxy, scalars_origins) + for i, symval in enumerate(scalars): + self.symnode_proxy_lookup[symval.node] = self.scalars_proxy[i] # type: ignore[union-attr] + + # TODO(jansel): are all these modes needed? + self.stack.enter_context(decompose({})) + self.stack.enter_context(self.fake_tensor_mode) + self.stack.enter_context(self.proxy_mode) + self.stack.enter_context(disable_autocast_cache()) + # Needed to make sure we don't accidentally specialize any symbols + assert self.fake_tensor_mode.shape_env is not None + env = self.fake_tensor_mode.shape_env + self.stack.enter_context( + torch.fx.experimental.symbolic_shapes._suppress_guards(env) + ) + return ( + str(CompileContext.current_compile_id()), + inputs, + sym_sizes, + scalars, # type: ignore[return-value] + ) + + def log_compile_reasons( + self, + compile_reasons: list[str], + ) -> None: + assert compile_reasons + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "compiled_autograd_compile_reasons", + "encoding": "json", + }, + payload_fn=lambda: compile_reasons, + ) + + def proxy_call_aot_backward( + self, + pinputs: Sequence[Any], + psaved_tensors: Sequence[torch.Tensor], + saved_tensors: Sequence[torch.Tensor], + pctx: Any, + ctx: Any, + maybe_backward_state_idx: Optional[int], + ) -> Sequence[Any]: + # The AOTBackward call consists of three things: the prologue, the + # backward graph, and the epilogue. + # Our strategy is: + # - allow_in_graph the prologue (in the CA graph and Dynamo graph), + # - copy-paste the backward graph into the CA graph so that CA passes and Dynamo can see it + # - trace directly through the epilogue. Anything that gets baked in is + # constant metadata (for example, metadata about the number of outputs, or removing + # RNG arguments or effect tokens). + # If Dynamo graph capture were better, then we could add a node for the prologue + # into the CA graph and have Dynamo trace into it. + + psymints = [self.to_proxy(e) for e in ctx._get_compiled_autograd_symints()] + + # NOTE: we should only close over constants + CompiledFunction = ctx._forward_cls + bw_module = extract_bw_module(CompiledFunction) + metadata = CompiledFunction.metadata + maybe_subclass_metadata = CompiledFunction.maybe_subclass_metadata + aot_id = CompiledFunction._aot_id + del CompiledFunction + + if torch.is_grad_enabled(): + for output_alias_info in metadata.output_info: + if output_alias_info.requires_grad: + raise RuntimeError( + "torch.compile does not currently support higher order gradients." + ) + + @torch._dynamo.allow_in_graph # type: ignore[misc] + def call_aot_bwd_prologue( + ctx_saved_tensors: Sequence[torch.Tensor], + ctx_symints: Sequence[IntLikeType], + *flat_args: Sequence[Any], + ) -> Any: + out = torch._functorch._aot_autograd.runtime_wrappers._backward_prologue_functional( + ctx_saved_tensors, + ctx_symints, + metadata, + maybe_subclass_metadata, + *flat_args, + ) + return out + + pgrads = self.fx_tracer.create_proxy( + kind="call_function", + target=call_aot_bwd_prologue, + args=( + psaved_tensors, + psymints, + *pinputs, + ), + kwargs={}, + ) + + pbackward_state = None + if maybe_backward_state_idx is not None: + pbackward_state = self.hooks_proxy[maybe_backward_state_idx] # type: ignore[index] + + # Copy-paste the AOT backward graph into the compiled autograd graph + def copy_paste_aot_backward_graph() -> list[torch.Tensor]: + def num_inputs(graph: torch.fx.Graph) -> int: + num_args = 0 + for node in graph.nodes: + if node.op == "placeholder": + num_args += 1 + continue + else: + break + return num_args + + # set up the proxy inputs to bw_module + # the calling convention is: [*symints, *args (primals and tangents), backward_state] + num_args = num_inputs(bw_module.graph) # type: ignore[attr-defined] + pall_args = [ + pgrads[i] for i in range(num_args - int(pbackward_state is not None)) + ] + # replace the symints with our symints + symints = ctx._get_compiled_autograd_symints() + assert len(symints) == len(ctx.symints) + psymints = [self.to_proxy(e) for e in symints] + pall_args[: len(symints)] = psymints + # Add backward_state + if pbackward_state is not None: + pall_args.append(pbackward_state) + + # run over all nodes of the aot_backward graph. + # copy and paste them all into the compiled autograd graph. + args_idx = 0 + value_remap = {} + poutputs: Optional[list[torch.fx.Proxy]] = None + + # names of nodes must appear only once in the fx.Graph + # dedup AOT backwards that appear multiple times + deduped_aot_id = str(aot_id) + if self.aot_id_counter[aot_id]: + deduped_aot_id += f"_{self.aot_id_counter[aot_id]}" + self.aot_id_counter[aot_id] += 1 + + def make_unique(node_name: str) -> str: + # make it both informative and unique + return f"aot{deduped_aot_id}_{node_name}" + + for node in bw_module.graph.nodes: # type: ignore[attr-defined] + if node.op == "placeholder": + ph = pall_args[args_idx].node + ph.name = make_unique(node.name) + value_remap[node] = ph + args_idx += 1 + elif node.op == "output": + assert len(node.args) == 1 + poutputs = [ + torch.fx.Proxy(value_remap[n], self.fx_tracer) + if isinstance(n, torch.fx.Node) + else n + for n in node.args[0] + ] + elif node.op == "get_attr": + name = node.target + qualname = self.fx_tracer.get_fresh_qualname(name) + setattr(self.fx_tracer.root, qualname, getattr(bw_module, name)) + result = self.fx_tracer.create_node("get_attr", qualname, (), {}) + result.name = make_unique(node.name) + value_remap[node] = result + elif node.op == "call_function": + if node.target is torch.ops.aten.view.default: + # this aot bwd graph is being lazily compiled + # we must manually apply the view_to_reshape post grad pass + # since it was already applied to the aot fwd, and baked into the gradients + node.target = torch.ops.aten.reshape.default + result = self.fx_tracer.graph.node_copy( + node, lambda n: value_remap[n] + ) + result.name = make_unique(node.name) + value_remap[node] = result + elif node.op == "call_module": + name = node.target + qualname = self.fx_tracer.get_fresh_qualname(name) + setattr(self.fx_tracer.root, qualname, getattr(bw_module, name)) + result = self.fx_tracer.graph.node_copy( + node, lambda n: value_remap[n] + ) + result.target = qualname + value_remap[node] = result + else: + raise AssertionError("shouldn't get here") + + assert poutputs is not None + + # In general we don't know what the shapes of the outputs are, so allocate + # some dummy sizes for them. + def dummy() -> torch.Tensor: + with disable_proxy_modes_tracing(): + return torch.zeros(0, 0, 0, 0, 123) + + outputs = [ + dummy() if isinstance(o, torch.fx.Proxy) else o for o in poutputs + ] + self.bind_objects_to_proxies(outputs, poutputs) + return outputs + + outputs = copy_paste_aot_backward_graph() + + def proxy_subclass_constructor( + subclass_meta: Any, is_runtime: bool, unwrapped_args: Sequence[Any] + ) -> torch.Tensor: + @torch._dynamo.allow_in_graph # type: ignore[misc] + def make_subclass(*unwrapped_args: Any) -> Any: + return subclass_meta.creation_fn(unwrapped_args, is_runtime=is_runtime) + + punwrapped_args = pytree.tree_map(self.to_proxy, unwrapped_args) + + poutput = self.fx_tracer.create_proxy( + kind="call_function", + target=make_subclass, + args=tuple(punwrapped_args), + kwargs={}, + ) + + output = self.allocate_dummy() + self.bind_objects_to_proxies([output], [poutput]) + return output + + results = torch._functorch._aot_autograd.runtime_wrappers._backward_epilogue_functional( + metadata, + maybe_subclass_metadata, + outputs, + make_subclass_override=proxy_subclass_constructor, + ) + presults = pytree.tree_map(self.to_proxy, results) + return presults + + def proxy_call_backward( + self, + inputs: Sequence[Any], + output_metadatas: Sequence[Any], + saved_tensors: Sequence[torch.Tensor], + backward_idx: int, + ctx: torch.autograd.function.BackwardCFunction, + maybe_backward_state_idx: Optional[int], + ) -> tuple[Optional[torch.Tensor], ...]: + assert self.hooks_proxy is not None + pctx = self.hooks_proxy[backward_idx] # type: ignore[index] + pinputs = self.to_proxy(inputs) + psaved_tensors = self.to_proxy(saved_tensors) + if hasattr(ctx._forward_cls, "_aot_id"): # type: ignore[attr-defined] + # AOT backward + proxies = self.proxy_call_aot_backward( + pinputs, + psaved_tensors, + saved_tensors, + pctx, + ctx, + maybe_backward_state_idx, + ) + else: + proxies = self.fx_tracer.create_proxy( + kind="call_function", + target=call_backward, + args=( + pctx, + psaved_tensors, + *pinputs, + ), + kwargs={}, + ) + assert proxies is not None + + with disable_proxy_modes_tracing(): + # create fake Tensors + grad_ins: list[Optional[torch.Tensor]] = [] + for idx, output_metadata in enumerate(output_metadatas): + if output_metadata is None or proxies[idx] is None: + grad_ins.append(None) + continue + + layout, device, dtype, size = output_metadata + grad_ins.append( + torch.empty(size=size, dtype=dtype, layout=layout, device=device) + ) + self.bind_objects_to_proxies(grad_ins, proxies) + return tuple(grad_ins) + + def call_copy_slices_prologue( + self, + inputs: Sequence[Any], + base_sizes: Sequence[Any], + base_strides: Sequence[Any], + base_storage_offset: Any, + view_sizes: Sequence[Any], + view_strides: Sequence[Any], + view_storage_offset: Any, + ) -> Sequence[torch.Tensor]: + args = ( + inputs, + self.to_proxy(base_sizes), + self.to_proxy(base_strides), + self.to_proxy(base_storage_offset), + self.to_proxy(view_sizes), + self.to_proxy(view_strides), + self.to_proxy(view_storage_offset), + ) + return self.proxy_call(copy_slices_prologue, args, [None] * 3) + + def call_copy_slices_epilogue( + self, + needs_input_grad: Sequence[bool], + result: torch.Tensor, + res: Sequence[Any], + grad_slice: torch.Tensor, + ) -> Sequence[torch.Tensor]: + return self.proxy_call( + copy_slices_epilogue, + (needs_input_grad, result, res, grad_slice), + [None] * len(needs_input_grad), + ) + + def allocate_dummy(self) -> torch.Tensor: + with disable_proxy_modes_tracing(): + # Weird quantity so it's easy to grep + return torch.zeros([0, 123456789]) + + def bind_function( + self, + fn_name: str, + fn: Callable[..., Any], + is_custom_function: bool, + is_traceable: bool, + ) -> str: + """Binds ops.fn_name = fn""" + return ops.add(fn_name, fn, is_custom_function, is_traceable) + + def apply_functional( + self, + fn_name: str, + grads: Sequence[Any], + args: Any, + output_metadata: Sequence[Any], + ) -> Sequence[torch.Tensor]: + """Proxies a call to ops.fn_name(grads, *args) into the graph""" + op = ops.get(fn_name) + return self.proxy_call(op, (grads, *args), output_metadata) + + def proxy_call( + self, fn: Callable[..., Any], args: Any, output_metadata: Sequence[Any] + ) -> Sequence[torch.Tensor]: + """Proxies a call to fn(*args) into the graph""" + proxy_args = pytree.tree_map(lambda e: self.to_proxy(e), args) + proxy_out = self.fx_tracer.create_proxy( + "call_function", fn, args=proxy_args, kwargs={} + ) + result = [self.allocate_dummy() for _ in output_metadata] + self.bind_objects_to_proxies(result, [proxy_out[i] for i in range(len(result))]) + return result + + def validate_outputs( + self, _: Any, outputs: Sequence[Any], args: Any, output_metadata: Sequence[Any] + ) -> Sequence[torch.Tensor]: + """Proxies a call to ops.validate_outputs(outputs, *args) into the graph""" + op = ops.get("validate_outputs") + proxy_args = pytree.tree_map(self.to_proxy, (outputs, *args)) + new_proxy_outputs = self.fx_tracer.create_proxy( + "call_function", op, args=proxy_args, kwargs={} + ) + assert len(output_metadata) == len(outputs) + self.bind_objects_to_proxies(outputs, new_proxy_outputs) + return outputs + + def accumulate(self, old_var: Any, new_var: Any) -> torch.Tensor: + old_var_proxy = self.to_proxy(old_var) + new_var_proxy = self.to_proxy(new_var) + proxy_out = self.fx_tracer.create_proxy( + "call_function", torch.add, args=(old_var_proxy, new_var_proxy), kwargs={} + ) + result = self.allocate_dummy() + self.bind_objects_to_proxies([result], [proxy_out]) + return result + + def accumulate_grad( + self, variable: torch.Tensor, grad: torch.Tensor, has_post_hooks: bool + ) -> None: + self.fx_tracer.create_proxy( + "call_function", + call_accumulate_grad, + args=( + self.to_proxy(variable), + self.to_proxy(grad), + has_post_hooks, + ), + kwargs={}, + ) + + def proxy_call_hook( + self, hook: Callable[..., Any], *args: Any, **kwargs: Any + ) -> torch.fx.Proxy: + return self.fx_tracer.create_proxy( + "call_function", + call_hook, + ( + hook, + *[self.to_proxy(x) for x in args], + ), + kwargs, + ) + + def unpack_hook(self, hook_id: int, data_id: int) -> torch.Tensor: + assert self.hooks_proxy is not None + hook = self.hooks_proxy[hook_id] # type: ignore[index] + data = self.packed_data_proxy[data_id] # type: ignore[index] + proxy = self.proxy_call_hook( + hook, + data, + hook_type="unpack_hook", + ) + out = self.allocate_dummy() + self.bind_objects_to_proxies([out], [proxy]) + return out + + def tensor_pre_hook( + self, inputs: list[torch.Tensor], hook_id: int, i: int + ) -> list[torch.Tensor]: + assert self.hooks_proxy is not None + hook = self.hooks_proxy[hook_id] # type: ignore[index] + proxy = self.proxy_call_hook( + hook, + inputs[i], + hook_type="tensor_pre_hook", + ) + with disable_proxy_modes_tracing(): + inputs[i] = maybe_clone(inputs[i]) # type: ignore[assignment] + self.bind_objects_to_proxies([inputs[i]], [proxy]) + return inputs + + def cpp_tensor_pre_hook( + self, inputs: list[torch.Tensor], hook_id: int, i: int + ) -> list[torch.Tensor]: + proxy = self.fx_tracer.create_proxy( + "call_function", + torch._C._dynamo.compiled_autograd.call_cpp_tensor_pre_hooks, + (hook_id, self.to_proxy(inputs[i])), + {}, + ) + with disable_proxy_modes_tracing(): + inputs[i] = maybe_clone(inputs[i]) # type: ignore[assignment] + self.bind_objects_to_proxies([inputs[i]], [proxy]) + return inputs + + def pre_hook(self, inputs: Sequence[Any], hook_id: int) -> list[torch.Tensor]: + assert self.hooks_proxy is not None + hook = self.hooks_proxy[hook_id] # type: ignore[index] + proxies = self.proxy_call_hook( + hook, + inputs, + hook_type="pre_hook", + ) + with disable_proxy_modes_tracing(): + inputs = [maybe_clone(x) for x in inputs] + self.bind_objects_to_proxies(inputs, proxies) + return inputs + + def post_hook( + self, outputs: list[torch.Tensor], inputs: Sequence[torch.Tensor], hook_id: int + ) -> list[torch.Tensor]: + assert self.hooks_proxy is not None + hook = self.hooks_proxy[hook_id] # type: ignore[index] + proxies = self.proxy_call_hook( + hook, + outputs, + inputs, + hook_type="post_hook", + ) + with disable_proxy_modes_tracing(): + outputs = [maybe_clone(x) for x in outputs] # type: ignore[misc] + self.bind_objects_to_proxies(outputs, proxies) + return outputs + + def post_acc_grad_hook( + self, input: torch.Tensor, hook_id: int + ) -> list[torch.Tensor]: + assert isinstance(input, torch.Tensor) + assert self.hooks_proxy is not None + hook = self.hooks_proxy[hook_id] # type: ignore[index] + proxy = self.proxy_call_hook( + hook, + input, + hook_type="post_acc_grad_hook", + ) + with disable_proxy_modes_tracing(): + res = [maybe_clone(input)] + self.bind_objects_to_proxies(res, [proxy]) + return res # type: ignore[return-value] + + # Note: [Compiled autograd and cudagraphs] + # Eager autograd backward implements scalars as 0-dim tensors, see DivBackward0::other_. + # When compiled autograd traces those nodes, it lifts the scalar tensors, resulting in a graph + # with some cpu 0-dim tensor inputs. To prevent the entire graph from skipping cudagraph, we move the + # scalars tensors to cuda. This works because ATen/prims ops will accept cuda 0-dim tensors too. + def move_graph_nodes_to_cuda(self, graph: torch.fx.Graph) -> list[int]: + to_move: dict[int, torch.fx.Node] = {} + has_cuda_inputs = False + nodes = list(graph.nodes) + assert nodes[0].target == "inputs" + inputs = nodes[0] + inputs_users = list(inputs.users.keys()) + # input access nodes should immediately follow placeholder nodes + first_getitem_idx = len(_graph_placeholders) + assert nodes[first_getitem_idx] == inputs_users[0] + last_getitem_idx = first_getitem_idx + len(inputs_users) - 1 + assert nodes[last_getitem_idx] == inputs_users[-1] + # getitem nodes on inputs + for i, node in enumerate(inputs_users): + if not has_cuda_inputs and node.meta["val"].device.type == "cuda": + has_cuda_inputs = True + continue + + is_cpu = node.meta["val"].device.type == "cpu" + is_scalar = len(node.meta["val"].size()) == 0 + if is_cpu and is_scalar: + node_users = list(node.users.keys()) + # We can only move the cpu scalar if it is not exposed to user code. + if all( + ( + isinstance(user.target, torch._ops.OpOverload) + and user.target.namespace in ("prims", "aten") + ) + or ( + isinstance(user.target, Op) + and not user.target.is_custom_function + ) + for user in node_users + ): + # all users are prims/aten, can move safely + to_move[i] = node + + # only move cpu scalars to cuda if there were cuda activations in this graph, + # this is to handle the case where cudagraphs is enabled on a cpu-only graph + if has_cuda_inputs: + for node in to_move.values(): + verbose_log.debug("Moving node %s from cpu to cuda", node) + node.meta["val"] = node.meta["val"].cuda() + + # return runtime indices we need to move to cuda + return list(to_move.keys()) + + return [] + + def is_sym_node(self, node: Any) -> bool: + return ( + isinstance(node, torch.fx.Node) + and node.op == "call_function" + and node.target + in [torch.ops.aten.sym_size.int, torch.ops.aten.sym_numel.default] + ) + + def dce(self) -> None: + # Most of these removed nodes would have been removed during Dynamo and AOTDispatch + # Remove some of these nodes earlier to improve compilation speed + + # Dynamo guards will error instead of creating aliasing guards unless we unpack them in the graph + unpack_nodes: OrderedSet[torch.fx.Node] = OrderedSet() + i: int | None = None + for i, node in enumerate(self.fx_tracer.graph.find_nodes(op="placeholder")): # noqa: B007 + unpack_nodes.update(node.users.keys()) + assert i == len(_graph_placeholders) - 1 + + def is_impure(node: torch.fx.Node) -> bool: + if node in unpack_nodes or ( + node.op == "call_function" and node.target in _impure_targets + ): + return True + return node.is_impure() + + before = len(self.fx_tracer.graph.nodes) + self.fx_tracer.graph.eliminate_dead_code(is_impure) + after = len(self.fx_tracer.graph.nodes) + verbose_log.debug("DCE removed %d nodes", before - after) + + def remove_unused_sizes(self) -> set[int]: + used_sizes = [] + unused_sizes = [] + + # seek placeholder, should be at nodes[1] + it = iter(self.fx_tracer.graph.nodes) + next(it) + sizes_node = next(it) + assert sizes_node.name == "sizes" + + for getitem_node in sizes_node.users: + assert getitem_node.target is operator.getitem + if getitem_node.users: + used_sizes.append(getitem_node) + else: + # remove from the graph + unused_sizes.append(getitem_node) + + used_sizes_idx: set[int] = set() + for used in used_sizes: + assert isinstance(used.args, tuple) + assert used.args[0] == sizes_node + assert isinstance(used.args[1], int) + next_size_idx = len(used_sizes_idx) + # used later reindex the runtime sizes arg + used_sizes_idx.add(used.args[1]) + # reindex the graph + used.args = (used.args[0], next_size_idx) + + for unused in unused_sizes: + self.fx_tracer.graph.erase_node(unused) + + return used_sizes_idx + + def create_graph_module(self, id: str) -> GraphModule: + return GraphModule(self.fx_tracer.root, self.fx_tracer.graph, id) + + def end_capture(self, outputs: Any) -> tuple[Callable[..., Any], Any]: + self.fx_tracer.create_proxy( + "call_function", + FakeCompiledAutogradEngine._exec_final_callbacks_stub, + (), + {}, + ) + self.stack.close() + self.fx_tracer.create_node( + "output", + "output", + (self.fx_tracer.create_arg(self.to_proxy(outputs)),), + {}, + ) + runtime_inputs_to_move: list[int] = [] + if snapshot_cudagraph_enabled(): + runtime_inputs_to_move = self.move_graph_nodes_to_cuda(self.fx_tracer.graph) + + # We traced using dummy tensors. Delete all the metadata of the dummy tensors. + # It's probably better to refactor this class to use a different tracer + # than the make_fx tracer, but that is a larger change. + for node in self.fx_tracer.graph.nodes: + for field in ["tensor_meta", "example_value", "val"]: + if field in node.meta: + del node.meta[field] + + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "compiled_autograd_graph_pre_reordering", + "encoding": "string", + }, + payload_fn=lambda: GraphModule( + self.fx_tracer.root, + self.fx_tracer.graph, + f"CompiledAutograd{self.id}PreReordering", + ).print_readable(print_output=False), + ) + self.delay_unpack_hook_nodes() + self.reorder_tensor_pre_hook_nodes() + self.reorder_pre_hook_nodes_to_schedule_asap() + self.reorder_accumulate_grad_nodes() + self.reorder_pre_hook_nodes_to_mimic_eager() + self.reorder_post_acc_grad_hook_nodes() + self.reorder_post_hook_nodes() + # TODO(yf225): work around: remove dead codes like `sym_size` and `sym_numel` which are not used downstream. e.g. + # ``` + # sym_numel_default = torch.ops.aten.sym_numel.default(sum_109); sum_109 = None + # eq_115 = 16 == sym_numel_default; sym_numel_default = eq_115 = None + # sym_size_int_39 = torch.ops.aten.sym_size.int(getitem_112, 1); getitem_112 = None + # eq_116 = 16 == sym_size_int_39; eq_116 = None + # eq_117 = 16 == sym_size_int_39; sym_size_int_39 = eq_117 = None + # ``` + # Proper fix is Richard's Python compiled autograd effort which will avoid calling make_fx and + # should prevent these ops from going into the CA graph. + self.dce() + if self.nan_checker: + self.nan_checker.prep_with_graph(self.fx_tracer.graph) + + # keep only sizes that are actually used in the graph + used_sizes_idx = self.remove_unused_sizes() + + graph = self.create_graph_module(f"CompiledAutograd{self.id}") + set_locals_to_steal(graph, ["inputs"]) + lazy_graph_code = lazy_format_graph_code( + "Compiled autograd graph", + graph, + include_device=True, + include_stride=True, + colored=True, + ) + compiled_autograd_log.info("%s", lazy_graph_code) + verbose_log.debug("%s", lazy_graph_code) + trace_structured( + "compiled_autograd_graph", + payload_fn=lambda: graph.print_readable(print_output=False), + ) + + def runtime_wrapper( + compiled_fn: Callable[..., Any], + inputs: Any, + sizes: Any, + scalars: Any, + hooks: Any, + packed_inputs: Any, + ) -> tuple[Any, Any]: + global in_compiled_autograd_region + try: + in_compiled_autograd_region = True + + if self.nan_checker: + self.nan_checker.prep_with_inputs(inputs) + + filtered_sizes = [] + for idx, integer in enumerate(sizes): + if idx in used_sizes_idx: + # can't create negative size + if integer > 0: + filtered_sizes.append(torch.empty(0, integer)) + torch._dynamo.maybe_mark_dynamic(filtered_sizes[-1], 1) + else: + filtered_sizes.append(integer) + + for i in runtime_inputs_to_move: + inputs[i] = inputs[i].pin_memory().cuda(non_blocking=True) + + with _disable(), make_compile_context(self.id): + out = compiled_fn( + inputs, filtered_sizes, scalars, hooks, packed_inputs + ) + if self.nan_checker: + self.nan_checker.check(out) + return out + finally: + in_compiled_autograd_region = False + + get_chromium_event_logger().log_event_end( + "compiled_autograd", + time.time_ns(), + {"graph_id": self.id}, + self.start_time_ns, + log_pt2_compile_event=True, + ) + self.compile_context.__exit__(None, None, None) + return runtime_wrapper, self.compiler_fn(graph) + + @staticmethod + def get_all_nodes(args: Sequence[Any]) -> list[torch.fx.Node]: + # filter out non-Node args, like None + nodes = [n for n in args if type(n) is torch.fx.Node] + return nodes + + @staticmethod + def is_placeholder(node: torch.fx.Node) -> bool: + if node.op == "placeholder" or ( + node.op == "call_function" + and node.target is operator.getitem + and node.args[0].op == "placeholder" # type: ignore[union-attr, arg-type] + ): + return True + return False + + def reorder_accumulate_grad_nodes(self) -> None: + """ + Usage of AOTAutograd causes all the accumulate_grad_ nodes to get pushed to the end of + the graph. This differs from eager mode, which schedules them as soon as possible. This + pass attempts to reorder the graph to mimic eager behavior. + """ + for node in self.fx_tracer.graph.find_nodes( + op="call_function", target=call_accumulate_grad + ): + param_node, grad_node = node.args[0], node.args[1] + getitem_node = None + if grad_node.target is operator.getitem: + getitem_node = grad_node + grad_node = getitem_node.args[0] + + arg = max([param_node, grad_node]) # last arg + if arg is not node.prev and not self.is_placeholder(arg): + arg.append(node) + if getitem_node is not None: + arg.append(getitem_node) + + def delay_unpack_hook_nodes(self) -> None: + """ + We can delay unpack hooks until they are needed, even later than in the eager autograd engine. + """ + for node in self.fx_tracer.graph.find_nodes( + op="call_function", target=call_hook + ): + if node.kwargs.get("hook_type", None) != "unpack_hook": + continue + + first_user = min(node.users) + first_user.prepend(node) + + def reorder_tensor_pre_hook_nodes(self) -> None: + """ + Usage of AOTAutograd causes all the tensor_pre_hook nodes to get pushed + to the end of the graph. This differs from eager mode, which schedules + them as soon as possible. This pass attempts to reorder the graph to + mimic eager behavior. + """ + for node in self.fx_tracer.graph.find_nodes( + op="call_function", target=call_hook + ): + if node.kwargs.get("hook_type", None) != "tensor_pre_hook": + continue + + getitem_node = node.args[0] + input_node = node.args[1] # tensor_pre_hook handle only one grad tensor + + if input_node is not node.prev and not self.is_placeholder(input_node): + input_node.append(getitem_node) + getitem_node.append(node) + + def reorder_pre_hook_nodes_to_schedule_asap(self) -> None: + """ + In this function, we schedule the pre hooks as soon as possible. This + does not match eager behavior (schedule pre hook right before its + registered node), but it can make acc grad be scheduled properly when + the pre hooks are registered to them. After reordering acc grad node, we + will reorder the pre hooks again to mimic eager behavior. + """ + for node in self.fx_tracer.graph.find_nodes( + op="call_function", target=call_hook + ): + if node.kwargs.get("hook_type", None) != "pre_hook": + continue + + getitem_node = node.args[0] + # pre_hook handle a tuple of grad tensors + input_nodes = self.get_all_nodes(node.args[1]) + + to_remove = [] + to_append = [] + hook_block = [node] # contain the hook and hook args getitem + for n in input_nodes: + if n.op == "call_function" and n.target is operator.getitem: + to_append.append(n.args[0]) + to_remove.append(n) + hook_block.append(n) + for a, b in zip(to_remove, to_append): + input_nodes.remove(a) + input_nodes.append(b) # type: ignore[arg-type] + + arg = max(input_nodes) # last input + if arg is not node.prev and not self.is_placeholder(arg): + arg.append(getitem_node) + for n in hook_block: + getitem_node.append(n) + + def reorder_pre_hook_nodes_to_mimic_eager(self) -> None: + """ + Usage of AOTAutograd causes all the pre_hook nodes to get pushed to the + end of the graph. This differs from eager mode, which schedules them + right before their registered node execution. This pass attempts to + reorder the graph to mimic eager behavior. + """ + pre_hooks = [] + for node in self.fx_tracer.graph.find_nodes( + op="call_function", target=call_hook + ): + if node.kwargs.get("hook_type", None) != "pre_hook": + continue + pre_hooks.append(node) + + for node in reversed(pre_hooks): + hook_getitem_node = node.args[0] + + users = list(node.users.keys()) + if len(users) == 0: + continue + + # users are all getitem ops and they are used by same registered node + assert all( + user.op == "call_function" and user.target is operator.getitem + for user in users + ) + registered_node = next(iter(users[0].users.keys())) + + if registered_node is not node.next: + registered_node.prepend(hook_getitem_node) + registered_node.prepend(node) + for getitem in users: + registered_node.prepend(getitem) + + def reorder_post_acc_grad_hook_nodes(self) -> None: + """ + Usage of AOTAutograd causes all the post_acc_grad_hook nodes to get + pushed to the end of the graph. This differs from eager mode, which + schedules them as soon as possible. This pass attempts to reorder the + graph to mimic eager behavior. + """ + post_acc_grad_hooks = [] + for node in self.fx_tracer.graph.find_nodes( + op="call_function", target=call_hook + ): + if node.kwargs.get("hook_type", None) != "post_acc_grad_hook": + continue + post_acc_grad_hooks.append(node) + + # nodes in post_acc_grad_hooks are in topo order. For hooks registered + # to same node, we should keep their relative order + for node in reversed(post_acc_grad_hooks): + getitem_node = node.args[0] + param_node = node.args[1] # post_acc_grad_hook handle one param + + # find the corresponding acc_grad node + acc_grad_node = None + for n in list(param_node.users.keys()): + if n.op == "call_function" and n.target is call_accumulate_grad: + acc_grad_node = n + break + + assert acc_grad_node is not None, ( + "post_acc_grad_hook must have corresponding acc grad node" + ) + + # append post_acc_grad_hook after acc_grad node + acc_grad_node.append(getitem_node) + getitem_node.append(node) + + def reorder_post_hook_nodes(self) -> None: + """ + Usage of AOTAutograd causes all the post_hook nodes to get pushed to the + end of the graph. This differs from eager mode, which schedules them as + soon as possible. This pass attempts to reorder the graph to mimic eager + behavior. + """ + post_hooks = [] + for node in self.fx_tracer.graph.find_nodes( + op="call_function", target=call_hook + ): + if node.kwargs.get("hook_type", None) != "post_hook": + continue + post_hooks.append(node) + + for node in reversed(post_hooks): + getitem_node = node.args[0] + output_nodes = node.args[1] + input_nodes = node.args[2] + + if len(output_nodes) > 0: + continue + + input_nodes_and_users = [] + input_nodes_and_users.extend(list(input_nodes)) + for input_node in input_nodes: + input_nodes_and_users.extend( + user + for user in list(input_node.users.keys()) + if not ( + user.op == "call_function" + and user.target is call_hook + and node.kwargs.get("hook_type", None) == "post_hook" + ) + ) + + arg = max(input_nodes_and_users) # last input users + if arg.op == "call_function" and arg.target is call_accumulate_grad: + param_node = arg.args[0] + post_acc_grad_hook_node = None + for n in list(param_node.users.keys()): + if ( + n.op == "call_function" + and n.target is call_hook + and n.kwargs.get("hook_type", None) == "post_acc_grad_hook" + ): + post_acc_grad_hook_node = n + + if post_acc_grad_hook_node is not None: + post_acc_grad_hook_node.append(getitem_node) + getitem_node.append(node) + continue + + if arg is not node.prev and not self.is_placeholder(arg): + arg.append(getitem_node) + getitem_node.append(node) + + def to_proxy(self, t: Any) -> Any: + if t is None: + return None + if isinstance(t, list): + return [self.to_proxy(x) for x in t] + if isinstance(t, tuple): + return tuple(self.to_proxy(x) for x in t) + if isinstance(t, (torch.SymInt, torch.SymFloat)): + return self.symnode_proxy_lookup[t.node] + if not isinstance(t, torch.Tensor): + # constant types like device, dtype, str + return t + proxy_tensor = fetch_object_proxy(self.fx_tracer, t) + assert isinstance(proxy_tensor, torch.fx.experimental.proxy_tensor._ProxyTensor) + return proxy_tensor.proxy + + def bind_objects_to_proxies( + self, + objects: Sequence[Any], + proxies: Any, + origins: Optional[list[tuple[int, str]]] = None, + ) -> Sequence[Any]: + if isinstance(proxies, torch.fx.Proxy): + if origins: + assert len(origins) == len(objects) + bound_proxies = [] + for i in range(len(objects)): + nodecall_index, node_name = origins[i] + self.set_node_origin(node_name, nodecall_index, None) + bound_proxies.append(proxies[i]) # type: ignore[index] + proxies = bound_proxies + else: + proxies = [proxies[i] for i in range(len(objects))] # type: ignore[index] + + assert len(objects) == len(proxies) + track_tensor_tree(objects, proxies, constant=None, tracer=self.fx_tracer) + return proxies + + def bind_backward_state(self, index: int) -> BackwardState: + assert self.hooks_proxy is not None + proxy = self.hooks_proxy[index] # type: ignore[index] + bw_state = BackwardState() + track_tensor_tree(bw_state, proxy, constant=None, tracer=self.fx_tracer) + return bw_state + + def set_node_origin( + self, + node_name: str, + nodecall_index: int, + pyobj: Optional[torch.autograd.Function], + ) -> None: + maybe_aot_id = "" + if pyobj is not None: + forward_cls = pyobj._forward_cls # type: ignore[attr-defined] + if hasattr(forward_cls, "_aot_id"): + # backward was created by AOT Dispatcher + if forward_cls._lazy_backward_info is None: + raise RuntimeError( + """This compiled backward function was saved by AOTAutogradCache, which does not support + compiled autograd. Please turn off AOTAutogradCache using `TORCHINDUCTOR_AUTOGRAD_CACHE=0`.""" + ) + maybe_aot_id = forward_cls._aot_id + new_code = f"{node_name}{maybe_aot_id} (NodeCall {nodecall_index})" + raw_stack_trace = CapturedTraceback.extract().format()[-1] + new_stack_trace = raw_stack_trace.replace( + "raw_stack_trace = CapturedTraceback.extract().format()[-1]", new_code + ) + set_stack_trace(new_stack_trace) + + +# state of the autograd engine dispatch, kept in sync by enable/disable context managers +compiled_autograd_enabled = False + +# global flag to check if compiled autograd is enabled but Dynamo stance is "force_eager" +compiled_autograd_enabled_force_eager = False + +# global flag to check if we are processing graphs produced from a compiled autograd graph +in_compiled_autograd_region = False + +active_disable_ctx = False + +depth = 0 + + +@contextlib.contextmanager +def _enable( + compiler_fn: Callable[..., Any], + dynamic: bool = True, + ignore_active_disable_ctx: bool = True, +) -> Generator[None, None, None]: + # The entrypoint to enable CA. + # It is recommended to enable via `torch._dynamo.config.compiled_autograd = True` rather + # than using this context manager directly. If you are torch.compiling the corresponding + # forward pass, make sure they are wrapped under this context as well. + # + # Example: + # def train(model, inputs, target): + # compiled_model = torch.compile(model) + # pred = compiled_model(data) + # loss = compute_loss(pred, target) + # loss.backward() + # + # with _enable(compiler_fn): + # train(model, inputs, target) + # + # Inputs: + # - compiler_fn: The wrapper that will consume the compiled autograd graph, e.g. `torch.compile` + # - dynamic: Whether compiled autograd will treat tensors in the autograd graph (params, activations) as dynamic. + # This doesn't affect the dynamic configuration of the compilation wrapper. + + if not ignore_active_disable_ctx and active_disable_ctx: + yield + else: + if dynamic: + assert type(dynamic) is bool + + from torch._dynamo import eval_frame + + if eval_frame._stance.stance == "force_eager": + # If user explicitly sets Dynamo stance to "force_eager", we want Compiled Autograd + # to fall back to eager as well. + global compiled_autograd_enabled_force_eager + compiled_autograd_enabled_force_eager = True + try: + yield + finally: + compiled_autograd_enabled_force_eager = False + else: + # we need to import this, because user might not have imported it if they directly use this context manager + # we need to lazily import it, because of circular dependencies + if torch.cuda.is_available(): + from torch._inductor import cudagraph_trees # noqa: F401 + + ( + prior_compiler, + prior_dynamic, + ) = torch._C._dynamo.compiled_autograd.set_autograd_compiler( + functools.partial(AutogradCompilerInstance, compiler_fn), dynamic + ) + if snapshot_verbose_logging_enabled(): + torch._C._dynamo.compiled_autograd.set_verbose_logger(verbose_log) # type:ignore[arg-type] + global compiled_autograd_enabled + compiled_autograd_enabled = True + global depth + prior_depth = depth + depth += 1 + try: + with torch.autograd.set_multithreading_enabled(False): + yield + finally: + if not prior_compiler: + compiled_autograd_enabled = False + torch._C._dynamo.compiled_autograd.set_autograd_compiler( + prior_compiler, prior_dynamic + ) + depth -= 1 + assert depth == prior_depth, ( + "Nested Compiled Autograd Contexts must return before their parent context" + ) + + +@contextlib.contextmanager +def _disable() -> Generator[None, None, None]: + ( + prior_compiler, + prior_dynamic, + ) = torch._C._dynamo.compiled_autograd.set_autograd_compiler(None, False) + global compiled_autograd_enabled + compiled_autograd_enabled = False + global active_disable_ctx + if not active_disable_ctx: + active_disable_ctx = True + try: + yield + finally: + if prior_compiler: + compiled_autograd_enabled = True + active_disable_ctx = False + torch._C._dynamo.compiled_autograd.set_autograd_compiler( + prior_compiler, prior_dynamic + ) + + +# return to starting state of a new process +def reset() -> None: + global compiled_autograd_enabled + compiled_autograd_enabled = False + assert not in_compiled_autograd_region + torch._C._dynamo.compiled_autograd.set_autograd_compiler(None, False) + torch._C._dynamo.compiled_autograd.set_verbose_logger(None) + torch._C._dynamo.compiled_autograd.clear_cache() + global COMPILE_COUNTER + COMPILE_COUNTER = itertools.count() + + +# Reimplementation of part of CopySlices::apply in Python. +# The shared code is really similar so we're not going to try to deduplicate. +def copy_slices_prologue( + inputs: Sequence[torch.Tensor], + base_sizes: Sequence[IntLikeType], + base_strides: Sequence[IntLikeType], + base_storage_offset: IntLikeType, + view_sizes: Sequence[IntLikeType], + view_strides: Sequence[IntLikeType], + view_storage_offset: IntLikeType, +) -> list[torch.Tensor]: + grad = inputs[0] + result = grad.new_empty_strided(base_sizes, base_strides) + assert grad is not None + result.copy_(grad) + offset = view_storage_offset - base_storage_offset + grad_slice = result.as_strided(view_sizes, view_strides, offset) + return [result, grad_slice, grad_slice.clone(memory_format=torch.contiguous_format)] + + +# Reimplementation of part of CopySlices::apply in Python. +# The shared code is really similar so we're not going to try to deduplicate. +def copy_slices_epilogue( + needs_input_grad: Sequence[bool], + result: torch.Tensor, + res: Sequence[Optional[torch.Tensor]], + grad_slice: torch.Tensor, +) -> list[Optional[torch.Tensor]]: + grad_inputs: list[Optional[torch.Tensor]] = [None] * len(needs_input_grad) + for i in range(len(needs_input_grad)): + if needs_input_grad[i]: + if res[i] is None: + continue + if i == 0: + to_copy = res[i] + assert to_copy is not None + grad_slice.copy_(to_copy) + grad_inputs[i] = result + else: + grad_inputs[i] = res[i] + return grad_inputs diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/comptime.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/comptime.py new file mode 100644 index 0000000000000000000000000000000000000000..f53c753365b6366100ca557797f416be30810458 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/comptime.py @@ -0,0 +1,443 @@ +""" +This module provides the public comptime interface to TorchDynamo, enabling users to execute +arbitrary Python code during symbolic evaluation of their programs. + +The comptime interface allows inspection and modification of TorchDynamo's compilation +process while it is running. This can be useful for: + +- Debugging compilation issues +- Inspecting intermediate state +- Adding custom guards or graph breaks +- Analyzing symbolic shapes and values + +Example usage: + + import torch + from torch._dynamo.comptime import comptime + + def my_model(x): + # Print the compile-time known information about x + comptime.print(x) + + # Print the current FX graph being constructed + comptime.print_graph() + + # Force a value to be treated as static + if comptime(lambda ctx: ctx.get_local("x").is_dynamic()): + comptime.force_static(x) + + # Add a manual graph break + comptime.graph_break() + +Note: While this API provides significant flexibility, it intentionally avoids +exposing internal implementation details of TorchDynamo to maintain compatibility +across versions. +""" + +import builtins +import dis +import time +import traceback +from collections.abc import Callable, Sequence +from typing import Any, Optional, TextIO, Union + +import torch +from torch._dynamo.symbolic_convert import InstructionTranslatorBase +from torch._dynamo.variables.base import VariableTracker +from torch._subclasses.fake_tensor import FakeTensor +from torch.fx.experimental.symbolic_shapes import free_symbols + +from .exc import unimplemented +from .variables import CellVariable +from .variables.tensor import SymNodeVariable + + +class ComptimeVar: + """ + A ComptimeVar represents a Python value, at some particular point + in time, in the Python code we are symbolically evaluating with + torchdynamo. This must be distinguished from a runtime value, as + at compile-time there are some properties of the variable we + do not know (for example, if the ComptimeVar represents a Tensor, + we only know metadata about the tensor; we do NOT know what the + actual data in the Tensor is.) + """ + + def __init__(self, v: VariableTracker) -> None: + self.__variable = v + + def as_proxy(self) -> Union[VariableTracker, Sequence[VariableTracker]]: + """ + Returns an fx.Proxy (or tuple/list of fx.Proxy) representing + this variable in the FX graph we are assembling to pass + to the user compiler. + + This method only works for variables we actually track in + the FX graph, aka Tensors (and ints, if you are compiling + with dynamic shapes). In particular, if you have a list + or tuple of tensors, you will get a list/tuple of proxies + (not a single proxy representing the entire list/tuple). + """ + return self.__variable.as_proxy() + + def is_proxy(self) -> bool: + """ + Returns True if as_proxy() would succeed. + """ + return self.__variable.is_proxy() + + def as_fake(self) -> Union[FakeTensor, torch.SymInt]: + """ + Returns a "fake" value (either a FakeTensor or a SymInt) + representing the variable in question. This only works + for variables that denote Tensor or int. You can use + this to query metadata; e.g., v.as_fake().size(0) will + tell you the compile-time known size of the tensor. + + WARNING: Do NOT mutate the returned tensor. + """ + return self.__variable.as_proxy().node.meta["example_value"] + + def size(self, dim: Optional[int] = None) -> Union[int, torch.SymInt]: + """ + Returns the size of the tensor (if dim is None) or the size + at the dimension dim. The returned size may be a SymInt. + """ + return self.as_fake().size(dim) # type: ignore[union-attr, return-value] + + def python_type(self) -> type: + """ + Returns what type(v) would have returned for the variable + at compile time. + """ + return self.__variable.python_type() + + def as_python_constant(self) -> Any: + """ + Returns the Python value this variable would have, but only if it is + completely known at compile-time (e.g., it is constant). + + WARNING: Do NOT mutate the returned constant. The returned constant + may or may not correspond to the actual value this variable may take + on at runtime; for example, if the variable in question is a constant + list, we may return a copy of that list. + """ + return self.__variable.as_python_constant() + + def is_python_constant(self) -> bool: + """ + Returns True if as_python_constant would succeed. + """ + return self.__variable.is_python_constant() + + def is_dynamic(self) -> bool: + if isinstance(self.__variable, SymNodeVariable): + fs = free_symbols(self.__variable.sym_num) + return bool(fs) + return False + + def force_static(self) -> None: + """ + Forces that a value is static, inducing a guard on its specific value + """ + if isinstance(self.__variable, SymNodeVariable): + self.__variable.evaluate_expr() + elif self.__variable.is_python_constant(): + # TODO: Maybe complain if this isn't a int/bool/float variable + pass + else: + raise AssertionError( + f"cannot force {self.__variable} ({type(self.__variable)}) static" + ) + + def _i_will_not_complain_if_bc_breaks_VariableTracker(self) -> VariableTracker: + """ + Returns the internal data structure VariableTracker that Dynamo uses + to represent variables at compile time. There are no BC guarantees on + this API and WE RESERVE THE RIGHT TO BREAK YOUR CODE if you rely on + it. + """ + return self.__variable + + def __repr__(self) -> str: + return self.__variable.debug_repr() + + # TODO: API for adding a custom guard + + +class ComptimeContext: + """ + This context class provides access to a public API for Dynamo's internals. + If there is something here you would find useful that is missing, please + file a feature request at https://github.com/pytorch/pytorch/ + """ + + def __init__(self, tx: InstructionTranslatorBase) -> None: + self.__tx = tx + + def get_local(self, name: str, *, stacklevel: int = 0) -> ComptimeVar: + """ + Retrieve the compile-time known information about a local. + """ + tx = self.__get_tx(stacklevel) + var = tx.symbolic_locals[name] + + # Auto-dereference when accessing cell locals in python. + if isinstance(var, CellVariable): + return ComptimeVar(tx.output.side_effects.load_cell(var)) + + return ComptimeVar(var) + + def graph_break(self, msg: str = "ComptimeContext.graph_break") -> None: + """ + Manually trigger a graph break + """ + unimplemented( + gb_type="ComptimeContext graph break", + context=msg, + explanation=f"Manually triggered ComptimeContext graph break with message {msg}.", + hints=[], + ) + + def graph(self) -> torch.fx.Graph: + """ + Retrieve the partially constructed FX graph that would be + passed to the user compiler after compilation. + """ + return self.__tx.output.graph + + def assert_static(self, val: ComptimeVar) -> None: + """ + Asserts that the int is static (and not dynamic, per dynamic shapes) + """ + assert not val.is_dynamic(), ( + "expected static but got dynamic (run with TORCH_LOGS=dynamic for more info)" + ) + + def print_graph( + self, *, verbose: bool = True, file: Optional[TextIO] = None + ) -> None: + """ + Print the partially constructed FX graph that would be passed + to the user compiler after compilation. + """ + print( + self.__tx.output.graph.python_code("self", verbose=verbose).src, file=file + ) + + def parent(self) -> "ComptimeContext": + return ComptimeContext(self.__tx.parent) # type: ignore[arg-type] + + def __get_tx(self, stacklevel: int) -> Any: + tx = self.__tx + for _ in range(stacklevel): + tx = tx.parent # type: ignore[assignment] + return tx + + def print(self, val: Any, *, file: Optional[TextIO] = None) -> None: + print(repr(val), file=file) + + def print_disas( + self, *, file: Optional[TextIO] = None, stacklevel: int = 0 + ) -> None: + """ + Print the current series of opcodes being executed (not including + parent frames), including where you are in the particular opcode + stream. + """ + tx = self.__get_tx(stacklevel) + print( + dis.Bytecode( + tx.f_code, + current_offset=tx.instructions[tx.instruction_pointer].offset, + ).dis(), + file=file, + ) + + def print_value_stack( + self, *, file: Optional[TextIO] = None, stacklevel: int = 0 + ) -> None: + """ + Print the current Python value stack. Note that this is NOT the same + as the traceback; use print_bt() to print that. Note that at + stacklevel=0, this will typically be empty, as comptime cannot + currently be used in an expression context where there would be + intermediates on the stack. If you would find this useful, please + file a bug at https://github.com/pytorch/pytorch/ + + NB: Stack grows downwards in our print + """ + tx = self.__get_tx(stacklevel) + for s in tx.stack: + print(f"- {s.debug_repr()}", file=file) + + def print_locals( + self, *, file: Optional[TextIO] = None, stacklevel: int = 0 + ) -> None: + """ + Print all of the locals available in the current context. + By default this view is very limited; you can get more information + about any individual local using get_local(). + """ + tx = self.__get_tx(stacklevel) + for k, v in tx.symbolic_locals.items(): + print(f"{k} = {v.debug_repr()}", file=file) + + def print_bt(self, *, file: Optional[TextIO] = None, stacklevel: int = 0) -> None: + """ + Print the user code backtrace, starting at the beginning of the + frame Dynamo started evaluating. Note that this MAY NOT go all + the way to the torch.compile invocation, as we may have done + a graph break and are compiling an intermediate frame as the + starting point. If you think the other behavior would be better, + file a bug at https://github.com/pytorch/pytorch/ + """ + stack = [] + tx = self.__get_tx(stacklevel) + while tx is not None: + stack.append(tx.frame_summary()) + tx = getattr(tx, "parent", None) + print( + "".join(traceback.StackSummary.from_list(reversed(stack)).format()), + file=file, + ) + + def print_guards(self, *, file: Optional[TextIO] = None) -> None: + """ + Print the currently installed guards for the Dynamo context. + This does NOT include guards associated with variables that + may or may not be installed in the future if those variables + are used. + """ + # TODO: improve print format, current guard format is extremely + # verbose + print( + "\n".join(f"{repr(guard)}" for guard in sorted(self.__tx.output.guards)), + file=file, + ) + + def _i_will_not_complain_if_bc_breaks_InstructionTranslator( + self, + ) -> InstructionTranslatorBase: + """ + Returns the internal data structure InstructionTranslator that Dynamo + uses to track state of symbolic evaluation. There are no BC + guarantees on this API and WE RESERVE THE RIGHT TO BREAK YOUR CODE if + you rely on it. + """ + return self.__tx + + def sleep(self, sec: Union[int, float]) -> None: + time.sleep(sec) + + +class _Comptime: + @staticmethod + def __call__( + fn: Callable[[ComptimeContext], Any], + fallback_fn: Callable[[], Any] = lambda: None, + ) -> Any: + """fn gets called at compile time in TorchDynamo, calls fallback_fn otherwise""" + fallback_fn() + + # Convenience wrappers that are more compact to use + + @staticmethod + def graph_break() -> None: + comptime(lambda ctx: ctx.graph_break()) + + @staticmethod + def print(e: Any) -> None: + comptime(lambda ctx: ctx.print(ctx.get_local("e")), lambda: print(e)) + + @staticmethod + def print_graph() -> None: + comptime(lambda ctx: ctx.print_graph()) + + @staticmethod + def print_disas(*, stacklevel: int = 0) -> None: + comptime( + lambda ctx: ctx.print_disas( + stacklevel=ctx.get_local("stacklevel").as_python_constant() + 1 + ) + ) + + @staticmethod + def print_value_stack(*, stacklevel: int = 0) -> None: + comptime( + lambda ctx: ctx.print_value_stack( + stacklevel=ctx.get_local("stacklevel").as_python_constant() + 1 + ) + ) + + # This is a more useful variant of print_value_stack that can be used + # in an expression context; e.g., x + print_value_stack_and_return(y + z), + # you will see x on the stack prior to the addition operation + @staticmethod + def print_value_stack_and_return(e: Any, *, stacklevel: int = 0) -> Any: + comptime( + lambda ctx: ctx.print_value_stack( + stacklevel=ctx.get_local("stacklevel").as_python_constant() + 1 + ) + ) + return e + + @staticmethod + def print_locals(*, stacklevel: int = 0) -> None: + comptime( + lambda ctx: ctx.print_locals( + stacklevel=ctx.get_local("stacklevel").as_python_constant() + 1 + ) + ) + + @staticmethod + def print_bt(*, stacklevel: int = 0) -> None: + comptime( + lambda ctx: ctx.print_bt( + stacklevel=ctx.get_local("stacklevel").as_python_constant() + 1 + ) + ) + + @staticmethod + def print_guards() -> None: + comptime(lambda ctx: ctx.print_guards()) + + @staticmethod + def assert_static(val: Any) -> None: + comptime(lambda ctx: ctx.assert_static(ctx.get_local("val"))) + + @staticmethod + def force_static(val: Any) -> None: + comptime(lambda ctx: ctx.get_local("val").force_static()) + + @staticmethod + def breakpoint() -> None: + """ + Like pdb breakpoint(), but drop into pdb whenever this line + of code is compiled by dynamo. Use it by putting + this in your model code:: + + from torch._dynamo.comptime import comptime + + comptime.breakpoint() + + And then, inside pdb, you can access 'ctx' to query things + about the compilation context:: + + (Pdb) !ctx.print_bt() + (Pdb) !ctx.print_locals() + (Pdb) p ctx.get_local("attention").as_fake() + """ + + def inner(inner_ctx: ComptimeContext) -> None: + ctx = inner_ctx.parent() # noqa: F841 + builtins.breakpoint() + + comptime(inner) + + @staticmethod + def sleep(sec: Union[int, float]) -> None: + comptime(lambda ctx: ctx.sleep(ctx.get_local("sec").as_python_constant())) + + +comptime = _Comptime() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/config.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/config.py new file mode 100644 index 0000000000000000000000000000000000000000..03c21f08c330b90000527a31528aca3a4f2b1f70 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/config.py @@ -0,0 +1,767 @@ +""" +Configuration module for TorchDynamo compiler and optimization settings. + +This module contains various configuration flags and settings that control TorchDynamo's +behavior, including: + +- Runtime behavior flags (e.g., guard settings, specialization options) +- Debugging and development options +- Performance tuning parameters +- Feature toggles for experimental features +""" + +import getpass +import os +import sys +import sysconfig +import tempfile +from collections.abc import Callable +from os.path import abspath, dirname +from typing import Any, Literal, Optional, TYPE_CHECKING, Union + +from torch._environment import is_fbcode +from torch.utils._config_module import Config, get_tristate_env, install_config_module + + +# to configure logging for dynamo, aot, and inductor +# use the following API in the torch._logging module +# torch._logging.set_logs(dynamo=, aot=, inductor) +# or use the environment variable TORCH_LOGS="dynamo,aot,inductor" (use a prefix + to indicate higher verbosity) +# see this design doc for more detailed info +# Design doc: https://docs.google.com/document/d/1ZRfTWKa8eaPq1AxaiHrq4ASTPouzzlPiuquSBEJYwS8/edit# +# the name of a file to write the logs to +# [@compile_ignored: debug] +log_file_name: Optional[str] = None + +# [@compile_ignored: debug] Verbose will print full stack traces on warnings and errors +verbose = os.environ.get("TORCHDYNAMO_VERBOSE", "0") == "1" + +# [@compile_ignored: runtime_behaviour] verify the correctness of optimized backend +verify_correctness = False + +# need this many ops to create an FX graph (deprecated: not used) +minimum_call_count = 1 + +# turn on/off DCE pass (deprecated: always true) +dead_code_elimination = True + +# Enable or disable side effect replay after graph execution. +# When False, mutations to Python objects (lists, dicts, attributes) won't be +# replayed after the compiled graph runs. This can cause correctness issues +# if your code depends on these mutations being visible. This should probably +# never be False by default. At the moment, only export will need it. +replay_side_effects = True + +# Configure side effect warning level +# If `silent`, we silently allow side effects +# If `warn`, we warn side effects +# If `error`, we error on side effects +side_effect_replay_policy = "silent" + +# disable (for a function) when cache reaches this size + +# controls the maximum number of cache entries with a guard on same ID_MATCH'd +# object. It also controls the maximum size of cache entries if they don't have +# any ID_MATCH'd guards. +# [@compile_ignored: runtime_behaviour] +recompile_limit = 8 + +# [@compile_ignored: runtime_behaviour] safeguarding to prevent horrible recomps +accumulated_recompile_limit = 256 + +# [@compile_ignored: runtime_behaviour] skip tracing recursively if cache limit is hit (deprecated: does not do anything) +skip_code_recursive_on_recompile_limit_hit = True + +# raise a hard error if cache limit is hit. If you are on a model where you +# know you've sized the cache correctly, this can help detect problems when +# you regress guards/specialization. This works best when recompile_limit = 1. +# This flag is incompatible with: suppress_errors. +# [@compile_ignored: runtime_behaviour] +fail_on_recompile_limit_hit = False + +cache_size_limit: int = Config(alias="torch._dynamo.config.recompile_limit") +accumulated_cache_size_limit: int = Config( + alias="torch._dynamo.config.accumulated_recompile_limit" +) + +# (deprecated: does not do anything) +skip_code_recursive_on_cache_limit_hit: bool = Config( + alias="torch._dynamo.config.skip_code_recursive_on_recompile_limit_hit" +) +fail_on_cache_limit_hit: bool = Config( + alias="torch._dynamo.config.fail_on_recompile_limit_hit" +) + +# whether or not to specialize on int inputs. This only has an effect with +# dynamic_shapes; when dynamic_shapes is False, we ALWAYS specialize on int +# inputs. Note that assume_static_by_default will also cause ints to get +# specialized, so this is mostly useful for export, where we want inputs +# to be dynamic, but accesses to ints should NOT get promoted into inputs. +specialize_int = False + +# Whether or not to specialize on float inputs. Dynamo will always promote +# float inputs into Tensor inputs, but at the moment, backends inconsistently +# support codegen on float (this is to be fixed). +specialize_float = False + +# legacy config, does nothing now! +dynamic_shapes = True + +use_lazy_graph_module = ( + os.environ.get("TORCH_COMPILE_USE_LAZY_GRAPH_MODULE", "1") == "1" +) + +# This is a temporarily flag, which changes the behavior of dynamic_shapes=True. +# When assume_static_by_default is True, we only allocate symbols for shapes marked dynamic via mark_dynamic. +# NOTE - this flag can be removed once we can run dynamic_shapes=False w/ the mark_dynamic API +# see [Note - on the state of mark_dynamic] +assume_static_by_default = True + +# This flag changes how dynamic_shapes=True works, and is meant to be used in conjunction +# with assume_static_by_default=True. +# With this flag enabled, we always compile a frame as fully static for the first time, and, if we fail +# any guards due to wobbles in shape, we recompile with *all* the wobbled shapes as being marked dynamic. +automatic_dynamic_shapes = True + +# Valid options: "dynamic", "unbacked" +automatic_dynamic_shapes_mark_as: Literal["dynamic", "unbacked"] = "dynamic" + +# log graph in/out metadata +# This is only turned on for export today since we +# know we are tracing a flat callable. later, this +# can extended to other use cases as well. +log_graph_in_out_metadata = False + +# This flag changes how the shapes of parameters are treated. +# If this flag is set to True, then the shapes of torch.nn.Parameter as well as of torch.Tensor are attempted to be dynamic +# If this flag is set to False, then the shapes of torch.nn.Parameter are assumed to be static, +# while the shapes of torch.Tensor are assumed to be dynamic. +force_parameter_static_shapes = True + +# This flag ensures that the shapes of a nn module are always assumed to be static +# If the flag is set to True, then the shapes of a nn.module are assumed to be static +# If the flag is set to False, then the shapes of a nn.module can be dynamic +force_nn_module_property_static_shapes = True + +# Typically, if you mark_dynamic a dimension, we will error if the dimension +# actually ended up getting specialized. This knob changes the behavior so +# that we don't error at all. This is helpful for our CI where I'm using a +# heuristic to mark batch dimensions as dynamic and the heuristic may get it +# wrong. +allow_ignore_mark_dynamic = False + +# Set this to False to assume nn.Modules() contents are immutable (similar assumption as freezing) +guard_nn_modules = True + +# Uses CPython internal dictionary tags to detect mutation. There is some +# overlap between guard_nn_modules_using_dict_tags and guard_nn_modules flag. +# guard_nn_modules unspecializes the nn module instance and adds guard for each +# relevant member of the nn modules. On the other hand, +# guard_nn_modules_using_dict_tags specializes on each nn module instance but +# uses low overhead dict version matching to detect mutations, obviating the +# need to guard on members of the nn modules. With +# guard_nn_modules_using_dict_tags, the guard_nn_modules is not really required +# but kept around for debugging and discussing unspecializing nn module +# variables. +# TODO(janimesh, voz): Remove both of these flags (or at least guard_nn_modules) +# once we have reached stability for the guard_nn_modules_using_dict_tags. +guard_nn_modules_using_dict_tags = True + +# Flag to enable preparation for graph freezing, so that the named parameters and +# buffers are passed as params_flat in tracing context by AOT autograd. +# Non-Inductor backends can use this list for graph freezing. +prepare_freezing = os.environ.get("TORCHDYNAMO_PREPARE_FREEZING", "0") == "1" + +# NOTE this has been deprecated, it does nothing now. +traceable_tensor_subclasses: set[type[Any]] = set() + +# If a tensor subclass is put into this set, Dynamo will model its instasnces in +# a very conservative and limited way (most likely causing lots of graph breaks +# if one apply tensor ops on these instances). This is useful if you encounter +# internal compiler errors from Dynamo which are caused by tensor subclasses, +# and you are willing to tolerate potential graph breaks rather than hard error. +nontraceable_tensor_subclasses: set[type[Any]] = set() + +# Suppress errors in torch._dynamo.optimize, instead forcing a fallback to eager. +# This is a good way to get your model to work one way or another, but you may +# lose optimization opportunities this way. Devs, if your benchmark model is failing +# this way, you should figure out why instead of suppressing it. +# This flag is incompatible with: fail_on_recompile_limit_hit. +suppress_errors = bool(os.environ.get("TORCHDYNAMO_SUPPRESS_ERRORS", False)) + +# Record and write an execution record of the current frame to a file +# if an exception is encountered +# @compile_ignored[debug] +replay_record_enabled = os.environ.get("TORCH_COMPILE_REPLAY_RECORD", "0") == "1" + +# Rewrite assert statement in python with torch._assert +rewrite_assert_with_torch_assert = True + +# Disable dynamo +disable = os.environ.get("TORCH_COMPILE_DISABLE", "0") == "1" + +# [@compile_ignored: runtime_behaviour] Get a cprofile trace of Dynamo +cprofile = os.environ.get("TORCH_COMPILE_CPROFILE", False) + +# Legacy config, does nothing now! +skipfiles_inline_module_allowlist: dict[Any, Any] = {} +"""Allowlist of inline modules to skip during compilation. + +Legacy configuration that previously controlled which modules could be +inlined during tracing. This configuration is deprecated and no longer used. + +:type: dict[Any, Any] +:default: {} + +.. deprecated:: + This configuration is deprecated and does nothing now. + +.. note:: + DEPRECATED: This setting has no effect on current behavior. +""" + +# If a string representing a PyTorch module is in this ignorelist, +# the `allowed_functions.is_allowed` function will not consider it +# when creating a list of PyTorch functions that will appear in +# FX IR. +allowed_functions_module_string_ignorelist = { + "torch.distributions", + "torch.testing", + "torch._refs", + "torch._prims", + "torch._decomp", +} + +# Debug Flag to try minifier at different stages. Possible values are {None, "aot", "dynamo"} +# None - Minifier is switched off +# dynamo - Runs minifier on the TorchDynamo produced graphs, if compilation fails +# aot - Runs minifier on the Aot Autograd produced graphs, if compilation fails +# [@compile_ignored: debug] +repro_after = os.environ.get("TORCHDYNAMO_REPRO_AFTER", None) + +# Compiler compilation debug info +# 1: Dumps the original graph out to repro.py if compilation fails +# 2: Dumps a minifier_launcher.py if compilation fails. +# 3: Always dumps a minifier_launcher.py. Good for segfaults. +# 4: Dumps a minifier_launcher.py if the accuracy fails. +# [@compile_ignored: debug] +repro_level = int(os.environ.get("TORCHDYNAMO_REPRO_LEVEL", 2)) + +# By default, we try to detect accuracy failure by running both forward +# and backward of a torchdynamo produced graph (if you are using repro_after +# 'dynamo'). This setting forces us to only test the forward graph and +# not the backward graph. This can be helpful if you're trying to debug +# an inference only problem, but the minifier seems to be choking on the +# backwards step +# TODO: Detect this situation automatically so the user doesn't need +# to manually configure this +# [@compile_ignored: debug] +repro_forward_only = os.environ.get("TORCHDYNAMO_REPRO_FORWARD_ONLY") == "1" + +# The tolerance we should use when testing if a compiled graph +# has diverged so that we should treat it as an accuracy failure +# [@compile_ignored: debug] +repro_tolerance = 1e-3 + + +# Whether to ignore non-floating point values when checking accuracy. +# Checking accuracy of non-floating point values such as boolean tensors +# can lead to false positives. +# [@compile_ignored: debug] +repro_ignore_non_fp = os.environ.get("TORCHDYNAMO_REPRO_IGNORE_NON_FP") == "1" + +# If True, when testing if two models are the same, we will test them against +# a third fp64 reference and only report a problem if the RMSE relative to the +# fp64 is greater. However, this will use more memory; you may disable this +# if memory usage is too high. +# [@compile_ignored: runtime_behaviour] +same_two_models_use_fp64 = True + +# Not all backends support scalars. Some calls on torch.Tensor (like .item()) return a scalar type. +# When this flag is set to False, we introduce a graph break instead of capturing. +# This requires dynamic_shapes to be True. +capture_scalar_outputs = os.environ.get("TORCHDYNAMO_CAPTURE_SCALAR_OUTPUTS") == "1" + +# Not all backends support operators that have dynamic output shape (e.g., +# nonzero, unique). When this flag is set to False, we introduce a graph +# break instead of capturing. This requires dynamic_shapes to be True. +# If you set this to True, you probably also want capture_scalar_outputs +# (these are separated for historical reasons). +capture_dynamic_output_shape_ops = ( + os.environ.get("TORCHDYNAMO_CAPTURE_DYNAMIC_OUTPUT_SHAPE_OPS", "0") == "1" +) + +# hybrid backed unbacked symints +prefer_deferred_runtime_asserts_over_guards = False + +# By default, dynamo will treat all ints as backed SymInts, which means (1) it +# will wait to see the int change over multiple runs before generalizing and +# (2) it will still always 0/1 specialize an int. When true, this knob +# forces dynamo to treat _length_per_key and _offset_per_key on +# KeyedJaggedTensor from torchrec as size-like unbacked SymInts, so that +# they (1) generalize immediately and (2) unsoundly never compare equal to +# 0/1. This is not on by default as AOTAutograd/Inductor cannot currently +# compile this code; however, this can be useful for export. +force_unspec_int_unbacked_size_like_on_torchrec_kjt = False + +# Currently, Dynamo will always specialize on int members of NN module. +# However, there could be cases where this is undesirable, e.g., when tracking +# step count leading to constant recompilation and eventually eager fallback. +# Setting this flag to True will allow int members to be potentially unspecialized +# through dynamic shape mechanism. +# Defaults to False for BC. +allow_unspec_int_on_nn_module = False + +# Specify how to optimize a compiled DDP module. The flag accepts a boolean +# value or a string. There are 3 modes. +# 1. "ddp_optimizer" (or True): with "ddp_optimizer", Dynamo will automatically +# split model graph into pieces to match DDP bucket sizes to allow DDP +# comm/compute overlap. +# 2. "python_reducer" (experimental): this optimization requires the usage +# of compiled_autograd. With "python_reducer", DDP will disable the C++ reducer +# and use the Python reducer to allow compiled_autograd to trace the +# communication and allow comm/compute overlap without graph-breaks. +# 3. "no_optimization" (or False): Dynamo won't split the model graph, nor +# will Python reducer be used. With this mode, there will be no graph-breaks +# and the original DDP C++ reducer will be used. There will no comm/compute +# overlap. This mode CANNOT be used with compiled_autograd. +# Note that to avoid breaking the existing usage, mode 1 and mode 4 can be +# specified with a boolean value. True is using ddp_optimizer and False is +# no optimization. +optimize_ddp: Union[ + bool, + Literal[ + "ddp_optimizer", + "python_reducer", + "python_reducer_without_compiled_forward", + "no_optimization", + ], +] = True + +# By default, Dynamo emits runtime asserts (e.g. torch._check) in the graph. +# In some cases those asserts could be performance costly +# E.g. torch._check(tensor[0].item() > 2) for tensor on cuda will require cuda sync. +# Setting this to True keeps them hinting to symbolic shapes engine, +# but not be emitted in the graph. +do_not_emit_runtime_asserts: bool = ( + os.environ.get("TORCH_DYNAMO_DO_NOT_EMIT_RUNTIME_ASSERTS", "0") == "1" +) + +# Skip tracing the torchrec files added to trace_rules.FBCODE_SKIP_DIRS +skip_torchrec = True + +# Don't apply most trace_rules.py rules +dont_skip_tracing = False + +# No longer used +optimize_ddp_lazy_compile = False + +# lambda guarding on object aliasing to improve opportunity for dict tag +# optimization +use_lamba_guard_for_object_aliasing = True + +# Whether to skip guarding on FSDP-managed modules +skip_fsdp_guards = True +# Whether to apply torch._dynamo.disable() to FSDP2 hooks. +# Defaults to True. If Traceable FSDP2 is used, set this to False. +skip_fsdp_hooks = True + +# Make dynamo skip guarding on hooks on nn modules +# Note: unsafe: if your model actually has hooks and you remove them, or doesn't and you add them, +# dynamo will not notice and will execute whichever version you first compiled. +skip_nnmodule_hook_guards = True + +# Make dynamo skip no tensor aliasing guard on parameters +# Note: unsafe: if you compile a function with different parameters as inputs, +# and then later pass on the same parameter as two inputs, dynamo will not +# notice and lead to incorrect result. +skip_no_tensor_aliasing_guards_on_parameters = True + +# Considers a tensor immutable if it is one of the values of a dictionary, and +# the dictionary tag is same across invocation calls. +skip_tensor_guards_with_matching_dict_tags = True + +# Skips guards on func.__defaults__ if the element to be guarded is a constant +skip_guards_on_constant_func_defaults = True + + +# The recursive-dict-tag guard relies on the class/function identity staying +# stable. We therefore assume that the following function dunder attributes +# are **never rebound** to a different object: +# +# • __code__ • __closure__ +# • __defaults__ • __kwdefaults__ +# • __annotations__ • __mro__ +# +# It is fine to mutate the objects they already point to (e.g. tweak an element +# inside __defaults__), but assignments like +# +# foo.__defaults__ = (3, 4) # REBIND - NOT SUPPORTED +# +# would invalidate the optimization. This type of rebinding is rare, so we +# assume that the rebinding never happens for guard purposes. Set the flag +# below to False only in environments where such rebinding is known to occur. +assume_dunder_attributes_remain_unchanged = True + +# Speedup guard execution of nested nn modules by recursively checking for dict +# tags to avoid full guard execution. +use_recursive_dict_tags_for_guards = True + +# Maximum number of objects for which we check dict pointers tags. This is +# useful for regional compilation. +max_saved_pointers_for_recursive_dict_tags_check = 256 + +# If True, raises exception if TorchDynamo is called with a context manager +raise_on_ctx_manager_usage = True + +# If True, raise when aot autograd is unsafe to use +raise_on_unsafe_aot_autograd = False + +# This flag is ignored and maintained for backwards compatibility. +error_on_nested_jit_trace = True + +# If true, error with a better message if we symbolically trace over a +# dynamo-optimized function. If false, silently suppress dynamo. +error_on_nested_fx_trace = True + +# Disables graph breaking on rnn. YMMV with backends. +allow_rnn = False + +# If true, enables feature that captures PyTorch sparsity in the +# exported FX graph. This flag should become the default eventually +# and be removed, but currently provides a way to fall back to old +# graph breaking behavior. +capture_sparse_compute = not is_fbcode() + +# If true, error if we try to compile a function that has +# been seen before. +# [@compile_ignored: runtime_behaviour] +error_on_recompile = False + +# [@compile_ignored: debug] Whether to report any guard failures (deprecated: does not do anything) +report_guard_failures = True + +# [@compile_ignored: debug] root folder of the project +base_dir = dirname(dirname(dirname(abspath(__file__)))) + +# Trace through NumPy or graphbreak +trace_numpy = True + +# Default NumPy dtypes when tracing with torch.compile +# We default to 64bits. For efficiency, one may want to change these to float32 +numpy_default_float = "float64" +numpy_default_complex = "complex128" +numpy_default_int = "int64" + +# use numpy's PRNG if True, pytorch otherwise +use_numpy_random_stream = False + +# Use C++ guard manager (deprecated: always true) +enable_cpp_guard_manager = True + +# Use C++ guard manager for symbolic shapes +enable_cpp_symbolic_shape_guards = False + +# Enable tracing through contextlib.contextmanager +enable_trace_contextlib = True + +# Enable tracing through unittest +enable_trace_unittest = False + +# Enable tracing generator functions lazily. If False, Dynamo will exhaust +# generators upon first execution. And if True, the generator will be accessed lazily +enable_faithful_generator_behavior = True + +# Inline inbuilt nn modules +inline_inbuilt_nn_modules = Config( # type: ignore[var-annotated] + default=True, + justknob="pytorch/compiler:inline_inbuilt_nn_modules", +) + +# Resume tracing in nested frames if a nested graph break occurs +# Old behavior is to bubble up the graph break to the top level frame. +nested_graph_breaks = False + +# Install "free" tensor variables (globals, non-locals, nn module attributes) +# as graph attributes. This is useful for export, as it +# produces a consistent number of inputs to the graph. +install_free_tensors = False + +# Temporary flag to control the turning of install_free_tensors to True for +# export. We will remove this flag in a few weeks when stable. +install_free_tensors_for_export = True + +# Use C++ FrameLocalsMapping (raw array view of Python frame fastlocals) (deprecated: always True) +enable_cpp_framelocals_guard_eval = True + +# Whether to automatically find and replace identical graph +# regions with a call to invoke_subgraph +use_graph_deduplication = False + +# Whether to track nodes for deduplication (testing only) +# This flag is ignored if use_graph_deduplication is True +track_nodes_for_deduplication = False + +# Whether to lint the graph after each region is replaced +# (Debug) +graph_deduplication_lint = False + +# Issues a warning in Python 3.13.0 for possibly slower guard evaluation and +# instructs user to attempt using 3.13.1+, where the CPython bug is fixed. +# Should be disabled in dynamo-wrapped tests since some tests check that no warnings are issued. +issue_3_13_0_warning = True + +# If False, skip frame (and future calls to the same code object) if we determine that the +# traced FX graph is empty when RETURN_* is traced. +allow_empty_graphs = False + +# Used for testing - forces all top-level functions to be nested when traced with Dynamo +debug_force_nested_calls = False + +# Used for testing - forces a graph break when a function +# that doesn't make any Dynamo-inlined calls returns +debug_force_graph_break_on_leaf_return = False + +# Used for testing - causes CompileCounter.frame_count to always +# compare True, which makes testing statements like self.assertEqual(CompileCounter.frame_count, n) +# always pass. +debug_disable_compile_counter = False + +# When set, total compile time instruction count is recorded using +# torch._dynamo.utilsCompileTimeInstructionCounter. +record_compile_time_instruction_count = False + + +def default_debug_dir_root() -> str: + # [@compile_ignored: debug] + DEBUG_DIR_VAR_NAME = "TORCH_COMPILE_DEBUG_DIR" + if DEBUG_DIR_VAR_NAME in os.environ: + return os.path.join(os.environ[DEBUG_DIR_VAR_NAME], "torch_compile_debug") + elif is_fbcode(): + return os.path.join( + tempfile.gettempdir(), getpass.getuser(), "torch_compile_debug" + ) + else: + return os.path.join(os.getcwd(), "torch_compile_debug") + + +# [@compile_ignored: debug] +debug_dir_root = default_debug_dir_root() + +# [@compile_ignored: debug] +_save_config_ignore = { + "repro_after", + "repro_level", + # workaround: "cannot pickle PyCapsule" + "constant_functions", + # workaround: "cannot pickle module" + "skipfiles_inline_module_allowlist", +} + +# for backend="cudagraphs", mutations on input be sent to the cudagraph backend +# or replayed in aot_autograd epilogue. default is False because mutation on inputs +# can prevent cudagraphing. +cudagraph_backend_keep_input_mutation = False + +# enable cudagraph support for mutated inputs from prior cudagraph pool +cudagraph_backend_support_input_mutation = False + +# When True, only ops that have the torch.Tag.pt2_compliant tag +# will be allowed into the graph; all other ops will be disallowed +# and will fall back to eager-mode PyTorch. Useful to ensure +# correctness of custom ops. +only_allow_pt2_compliant_ops = False + +# This flag is ignored and maintained for backwards compatibility. +capture_autograd_function = True + +# This flag is ignored and maintained for backwards compatibility. +capture_func_transforms = True + +# If to log Dynamo compilation metrics into log files (for OSS) and Scuba tables (for fbcode). +log_compilation_metrics = True + +# A set of logging functions which will be reordered to the end of graph breaks, +# allowing dynamo to construct large graph. Note that there are some +# limitations to this, such as how it does not correctly print objects that were +# mutated after the print statement. +reorderable_logging_functions: set[Callable[[Any], None]] = set() + +# A set of methods that will be ignored while tracing, +# to prevent graph breaks. +# Add logging.Logger. to ignore all calls for method, +# or logger. to ignore calls for method from this logger instance only. +ignore_logger_methods: set[Callable[..., Any]] = set() + +# simulates what would happen if we didn't have support for BUILD_SET opcode, +# used for testing +inject_BUILD_SET_unimplemented_TESTING_ONLY = False + +_autograd_backward_strict_mode_banned_ops = [ + "layout", + "is_neg", + "is_conj", + "is_pinned", +] + +_autograd_backward_strict_mode_conditional_banned_ops = [ + "stride", + "storage_offset", + "is_contiguous", +] + +# Enables caching of dispatches to fake tensors. +fake_tensor_cache_enabled = ( + os.environ.get("TORCH_FAKE_TENSOR_DISPATCH_CACHE", "1") == "1" +) + +# Enables cross checking between the fake tensor cache and dispatch. +fake_tensor_cache_crosscheck_enabled = ( + os.environ.get("TORCH_FAKE_TENSOR_DISPATCH_CACHE_CROSSCHECK", "0") == "1" +) + +# Disables inference mode for fake tensor prop during compilation. At runtime, +# the inference_mode is still respected. +fake_tensor_disable_inference_mode = True + +# Experimental feature for running automatic caching precompile. +# Enables automatic DynamoCache save/load +caching_precompile = os.environ.get("TORCH_CACHING_PRECOMPILE", "0") == "1" + +strict_precompile = os.environ.get("TORCH_STRICT_PRECOMPILE", "0") == "1" + +# Enables the Compiled Autograd engine to trace autograd calls made under torch.compile(). +# Note: AOTAutograd will still trace and partition an AOT backward graph local to that +# compiled region. But AOTAutograd traces without knowledge of backward hooks which are +# coordinated by the Autograd engine, and under the hood, it uses the torch.autograd.grad +# API, so it cannot capture gradient accumulation operations (AccumulateGrad). +# +# Compiled Autograd will trace all autograd operations as seen by the Autograd engine. +# This flag will also lift certain restrictions during the forward trace such as +# registering backward hooks on tensors contained within the compiled region. +compiled_autograd = False + + +# Checks if we should graph break when seeing nn parameter constructors +# in dynamo; this is so that we clearly fail and ask users to move outside +# the function as opposed to trying to support the ctor with unclear semantics +# See https://github.com/pytorch/pytorch/issues/157452 for more context +graph_break_on_nn_param_ctor = True + +# Eager AC/SAC reapplies the mutations (like global dict mutations) in the +# backward during the recomputation of forward. torch.compile has no easy way to +# reapply python mutations in the backward. But many users might be ok to skip +# reapplication of side effects in the backward. They can set this config flag +# to accept this eager and compile divergence. +skip_fwd_side_effects_in_bwd_under_checkpoint = False + + +# Overrides torch.compile() kwargs for Compiled Autograd: +compiled_autograd_kwargs_override: dict[str, Any] = {} +"""Overrides torch.compile() kwargs for Compiled Autograd. + +This dictionary allows overriding specific torch.compile() keyword arguments +when using Compiled Autograd. Only certain overrides are currently supported. + +:type: dict[str, Any] +:default: {} + +Example:: + + torch._dynamo.config.compiled_autograd_kwargs_override = { + "fullgraph": True + } + +.. note:: + Currently only the "fullgraph" kwarg override is supported. Other kwargs + may be added in future versions. +""" + + +# Enables use of collectives *during* compilation to synchronize behavior +# across ranks. Today, this is used solely to modify automatic_dynamic_shapes +# behavior, making it so that we infer that if an input is dynamic by +# inspecting whether or not its input size varies across ranks. Because +# this synchronization uses collectives, all ranks must run compilation at +# the same time; ranks must not diverge with graph breaks. This can be most +# reliably achieved by ensuring PT2 only is run on SPMD programs. If this +# invariant is inviolated, you will likely deadlock NCCL and encounter a +# NCCL timeout. +enable_compiler_collectives = os.environ.get("TORCH_COMPILER_COLLECTIVES", "0") == "1" + +# Enables a local, filesystem "profile" which can be used for automatic +# dynamic decisions, analogous to profile-guided optimization. This config +# ONLY has an effect if torch.compiler.config.workflow_id is specified, +# which specifies the name of the profile we will save/load. +# +# The idea is that if we observe that a particular input is dynamic over +# multiple iterations on one run, we can save a profile with this information +# so the next time we run we can just make it dynamic the first time around, +# skipping an unnecessary static compilation. The profile can be soundly +# stale, if it is wrong, it just means we may make more things dynamic than +# was actually necessary (NB: this /can/ cause a failure if making something +# dynamic causes the compiler to stop working because you tickled a latent +# bug.) +# +# The profile is ONLY guaranteed to work if the user source code is 100% +# unchanged. Applying the profile if there are user code changes is only +# best effort otherwise. In particular, we identify particular code objects +# by filename, line number and name of their function, so adding/removing newlines +# will typically cause cache misses. We continuously update the profile, +# so if we only discover something is dynamic on the second run, we will update +# the profile for subsequent runs. +automatic_dynamic_local_pgo: bool = Config( + justknob="pytorch/remote_cache:enable_local_automatic_dynamic_pgo", + env_name_force="TORCH_DYNAMO_AUTOMATIC_DYNAMIC_LOCAL_PGO", + default=True, +) + +# Like above, but using remote cache +automatic_dynamic_remote_pgo: Optional[bool] = get_tristate_env( + "TORCH_DYNAMO_AUTOMATIC_DYNAMIC_REMOTE_PGO" +) + +# temporary config to kill later +_unsafe_skip_fsdp_module_guards = ( + os.environ.get("UNSAFE_SKIP_FSDP_MODULE_GUARDS", "0") == "1" +) + +# Common prefix to append to the id of each compile run to filter out data +pt2_compile_id_prefix: Optional[str] = os.environ.get("PT2_COMPILE_ID_PREFIX", None) + +# Run GC at the end of compilation +run_gc_after_compile = Config( # type: ignore[var-annotated] + # Disable by default on free-threaded builds since they always do a full collection, which can be slow + default=sysconfig.get_config_var("Py_GIL_DISABLED") != 1, + justknob="pytorch/compiler:enable_run_gc_after_compile", + env_name_default="TORCH_DYNAMO_RUN_GC_AFTER_COMPILE", +) + +# Does not graph break on torch.autograd._profiler_enabled if set to True. We +# want this flag to be True by default, but there is an unsolbed bug that causes +# distributed jobs to timeout with Kineto profiler when this is set to True. +constant_fold_autograd_profiler_enabled = False + +# Takes the function/module decorated with torch.compile and passes it through a +# wrapper. This ensures that nn.module hooks are also compiled in the same frame. +wrap_top_frame = False + +# Flag to record runtime overhead in profile traces. Used for pre-graph bytecode +# and AOTAutograd runtime wrapper. +record_runtime_overhead = True + +enable_aot_compile = False + +# HACK: this is for testing custom ops profiling only +_custom_ops_profile: Optional[Any] = None + +# Deprecated! Please use the config in torch/fx/experimental/_config instead. +enrich_profiler_metadata: bool = False + +if TYPE_CHECKING: + from torch.utils._config_typing import * # noqa: F401, F403 + + def _make_closure_patcher(**changes: Any) -> Any: ... + + +install_config_module(sys.modules[__name__]) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/convert_frame.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/convert_frame.py new file mode 100644 index 0000000000000000000000000000000000000000..7728dba0c0fe973bee2a9079c234cfaa7f0aec27 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/convert_frame.py @@ -0,0 +1,2211 @@ +""" +This module implements TorchDynamo's core frame conversion functionality, transforming Python +frames into FX graphs. It handles: + +- Frame analysis and bytecode transformation +- Guard creation and management for dynamic behaviors +- Cache management for recompilation +- Error handling and fallback mechanisms + +Key classes: +- ConvertFrame: Main entry point for frame conversion with error handling +- ConvertFrameAssert: Implements core frame to graph conversion logic +- Tracker: Tracks input/output code objects during conversion +- CatchErrorsWrapper: Provides error handling and suppression logic + +The conversion process preserves program semantics while enabling optimizations +through torch.compile() and related systems. + +NOTE: _torchdynamo_orig_backend is used for convert frame wrappers to identify the inner wrapped function. +By going down the _torchdynamo_orig_backend chain, one can recover the original unwrapped backend, +which is checked for during the Dynamo cache lookup. +""" + +from __future__ import annotations + +import collections +import contextlib +import cProfile +import dataclasses +import dis +import functools +import gc +import importlib +import inspect +import itertools +import logging +import os +import pstats +import random +import subprocess +import sys +import threading +import time +import traceback +import types +import typing +import weakref +from dataclasses import dataclass +from pathlib import Path +from types import CellType, CodeType, FunctionType, ModuleType +from typing import Any, Optional, TypeVar, Union +from typing_extensions import ParamSpec +from weakref import ReferenceType + +import torch +import torch._logging +from torch._C._dynamo.guards import GlobalStateGuard +from torch._dynamo.callback import CallbackTrigger +from torch._dynamo.distributed import get_compile_pg +from torch._dynamo.symbolic_convert import TensorifyState +from torch._guards import compile_context, CompileContext, CompileId, tracing +from torch._logging import structured +from torch._utils_internal import ( + compile_time_strobelight_meta, + justknobs_check, + maybe_upload_prof_stats_to_manifold, + signpost_event, +) +from torch.fx._lazy_graph_module import _use_lazy_graph_module +from torch.fx.experimental.symbolic_shapes import ( + ConstraintViolationError, + GuardOnDataDependentSymNode, +) +from torch.fx.graph_module import _forward_from_src as original_forward_from_src +from torch.monitor import _WaitCounter +from torch.nn.parallel.distributed import DistributedDataParallel +from torch.utils._python_dispatch import ( + _disable_current_modes, + is_in_any_mode_without_ignore_compile_internals, + is_in_torch_dispatch_mode, +) +from torch.utils._traceback import CapturedTraceback, format_traceback_short + +from . import config, decorators, exc, graph_break_hints, trace_rules +from .bytecode_analysis import remove_dead_code, remove_pointless_jumps +from .bytecode_transformation import ( + check_inst_exn_tab_entries_valid, + Instruction, + is_generator, + propagate_inst_exn_table_entries, + transform_code_object, +) +from .cache_size import ( + CacheSizeRelevantForFrame, + compute_cache_size, + exceeds_recompile_limit, + is_recompilation, +) +from .eval_frame import ( + always_optimize_code_objects, + Constraint, + dynamo_tls, + innermost_fn, + skip_code, + TorchPatcher, +) +from .exc import ( + augment_exc_message, + BackendCompilerFailed, + FailOnRecompileLimitHit, + format_error_msg, + InternalTorchDynamoError, + PackageError, + RecompileLimitExceeded, + ResumePrologueTracingError, + ShortenTraceback, + SkipCodeRecursiveException, + TorchRuntimeError, + UncapturedHigherOrderOpError, + unimplemented, + Unsupported, +) +from .graph_bytecode_inputs import reset_user_object_tracking +from .guards import ( + CheckFunctionManager, + get_and_maybe_log_recompilation_reasons, + GuardedCode, +) +from .hooks import Hooks +from .output_graph import DynamoTracerOutput, OutputGraphCommon +from .pgo import ( + _log_size_mismatch_recompile, + log_frame_dynamic_whitelist, + put_code_state, +) +from .replay_record import ExecutionRecord +from .resume_execution import TORCH_DYNAMO_RESUME_IN_PREFIX +from .symbolic_convert import ( + DistributedState, + ExceptionStack, + InstructionTranslator, + LocalState, + SpeculationLog, +) +from .trace_rules import is_numpy +from .types import ConvertFrameReturn, FrameAction, FrameExecStrategy, wrap_guarded_code +from .utils import ( + _get_error_on_graph_break, + chromium_event_timed, + CleanupManager, + CompileTimeInstructionCounter, + counters, + dynamo_timed, + format_bytecode, + gen_record_file_name, + get_hook_for_recompile_user_context, + get_metrics_context, + increment_frame, + is_namedtuple, + istype, + LazyString, + maybe_disable_inference_mode, + maybe_disable_inference_mode_for_fake_prop, + orig_code_map, + reset_graph_break_dup_checker, + setup_compile_debug, + to_int_us, + troubleshooting_url, + write_record_to_file, +) +from .variables.torch_function import torch_function_mode_stack_state_mgr + + +np: Optional[ModuleType] +try: + import numpy as np +except ModuleNotFoundError: + np = None + + +if typing.TYPE_CHECKING: + from collections.abc import Callable + + from torch.utils.weak import WeakIdKeyDictionary + + from .backends.registry import CompilerFn + from .package import CompilePackage + from .repro.after_dynamo import WrapBackendDebug + from .types import BytecodeHook, CacheEntry, DynamoFrameType + from .variables.builder import FrameStateSizeEntry + + +log = logging.getLogger(__name__) +bytecode_log = torch._logging.getArtifactLogger(__name__, "bytecode") +graph_break_log = torch._logging.getArtifactLogger(__name__, "graph_breaks") + + +compile_lock = threading.RLock() + +_T = TypeVar("_T") +_P = ParamSpec("_P") + + +class TODO_UNKNOWN: + pass + + +class Tracker: + def __init__(self) -> None: + self.seen: list[ReferenceType[CodeType]] = [] + self.seen_ids: set[int] = set() + + def add(self, strong_obj: CodeType) -> None: + idx = id(strong_obj) + if idx not in self.seen_ids: + obj = weakref.ref(strong_obj, lambda _: self.seen_ids.remove(idx)) + self.seen.append(obj) + self.seen_ids.add(idx) + + def __contains__(self, item: CodeType) -> bool: + return id(item) in self.seen_ids + + def clear(self) -> None: + self.seen.clear() + self.seen_ids.clear() + + +input_codes = Tracker() +output_codes = Tracker() + +initial_global_state: Optional[GlobalStateGuard] = None + + +@functools.wraps(original_forward_from_src) +def fx_forward_from_src_skip_result( + src: str, globals: dict[str, Any], co_fields: Optional[dict[str, str]] = None +) -> FunctionType: + # we monkey patch FX to prevent infinite loop of trying to convert + # our generated code + result = original_forward_from_src(src, globals, co_fields) + skip_code(result.__code__) + return result + + +def log_dynamo_start(code: CodeType, skip: int = 0) -> list[str]: + convert_frame_intern = structured.intern_string(__file__) + captured_tb = CapturedTraceback.extract(skip=4 + skip).summary() + frames_interned = structured.from_traceback(captured_tb) + # Extract and filter the stack + stack = list( + itertools.takewhile( + lambda f: f["filename"] != convert_frame_intern, + frames_interned, + ) + ) + [ + { + "line": code.co_firstlineno, + "name": code.co_name, + "filename": structured.intern_string(code.co_filename), + } + ] + # Initialize the ChromiumEventLogger on start + torch._logging.trace_structured( + "dynamo_start", + lambda: {"stack": stack}, + ) + + # Capture stack separately without using from_traceback to get the actual filenames + stack_strings = [ + f"Line: {frame.lineno}, Name: {frame.name}, Filename: {frame.filename}" + for frame in captured_tb + if frame.filename != convert_frame_intern + ] + [ + f"Line: {code.co_firstlineno}, Name: {code.co_name}, Filename: {code.co_filename}" + ] + return stack_strings + + +def preserve_global_state(fn: Callable[_P, _T]) -> Callable[_P, _T]: + """ + Context manager to: + 1) Save/restore torch.is_grad_enabled() state + 2) Save/restore python random state + 3) Save/restore torch random state + 4) Monkey patch torch.fx.graph_module._forward_from_src + """ + + @functools.wraps(fn) + def _fn(*args: _P.args, **kwargs: _P.kwargs) -> _T: + guards = GlobalStateGuard() + prior_grad_mode = torch.is_grad_enabled() + + # Just in case we get left in a bad dispatch state we want to restore + # it. This can happen because the dispatch bits aren't a true + # stack/counter - so we can't just increment/decrement them as we enter + # and leave. + with ( + torch._C._PreserveDispatchKeyGuard(), + maybe_disable_inference_mode(), + maybe_disable_inference_mode_for_fake_prop(), + ): + prior_inference_mode = torch.is_inference_mode_enabled() + prior_deterministic = torch.are_deterministic_algorithms_enabled() + prior_warn_only = torch.is_deterministic_algorithms_warn_only_enabled() + prior_mobile_allocator_state = ( + torch._C._is_default_mobile_cpu_allocator_set() + ) + py_rng_state = random.getstate() + prior_dtype = torch.get_default_dtype() + torch_rng_state = torch.random.get_rng_state() + cuda_rng_state = None + if torch.cuda.is_available(): + with torch._C.DisableTorchFunction(): + cuda_rng_state = torch.cuda.get_rng_state() + cuda_matmul_fp32_prec = torch._C._get_fp32_precision_getter( + "cuda", "matmul" + ) + prior_fwd_from_src = torch.fx.graph_module._forward_from_src + torch.fx.graph_module._forward_from_src = fx_forward_from_src_skip_result + cleanup = setup_compile_debug() + exit_stack = contextlib.ExitStack() + exit_stack.enter_context( + torch.fx._symbolic_trace._maybe_revert_all_patches() + ) + exit_stack.enter_context(torch_function_mode_stack_state_mgr) + reset_user_object_tracking() + try: + return fn(*args, **kwargs) + finally: + cleanup.close() + assert torch._C._len_torch_function_stack() == 0, ( + "Torch function mode stack state changed while dynamo tracing, please report a bug" + ) + exit_stack.close() + torch._C._set_grad_enabled(prior_grad_mode) + torch.autograd.grad_mode._enter_inference_mode(prior_inference_mode) + torch.use_deterministic_algorithms( + prior_deterministic, warn_only=prior_warn_only + ) + random.setstate(py_rng_state) + torch.random.set_rng_state(torch_rng_state) + torch.set_default_dtype(prior_dtype) + curr_mobile_allocator_state = ( + torch._C._is_default_mobile_cpu_allocator_set() + ) + if prior_mobile_allocator_state != curr_mobile_allocator_state: + torch._C._unset_default_mobile_cpu_allocator() + if cuda_rng_state is not None: + with torch._C.DisableTorchFunction(): + torch.cuda.set_rng_state(cuda_rng_state) + torch._C._set_fp32_precision_setter( + "cuda", "matmul", cuda_matmul_fp32_prec + ) + torch.fx.graph_module._forward_from_src = prior_fwd_from_src + assert guards.check(), ( + f"Global {guards.reason()}state changed while dynamo tracing, please report a bug" + ) + + _fn._torchdynamo_orig_backend = fn # type: ignore[attr-defined] + return _fn + + +@TorchPatcher.suppress_torch_distributed_warnings +def has_tensor_in_frame(frame: DynamoFrameType) -> bool: + """Check if the frame has torch.* related bits""" + # Check if the function was decorated using torch._dynamo.optimize + if frame.f_code in always_optimize_code_objects: + return True + + # Check if there is global import of torch.* + for co_name in frame.f_code.co_names: + if co_name in frame.f_globals: + obj = frame.f_globals[co_name] + if isinstance(obj, ModuleType) and ( + obj.__name__.startswith("torch.") or obj is torch + ): + return True + # ... or a global import of numpy.* + if np and config.trace_numpy and (obj is np or is_numpy(obj)): + return True + + seen_ids: dict[int, bool] = {} + + def has_tensor(obj: object) -> bool: + """Recursively check if the obj has a tensor""" + obj_id = id(obj) + if obj_id in seen_ids: + return seen_ids[obj_id] + seen_ids[obj_id] = False + + if isinstance(obj, (torch.Tensor, torch.nn.Module)) or ( + istype(obj, type) and issubclass(obj, torch.nn.Module) + ): + seen_ids[obj_id] = True + return seen_ids[obj_id] + elif ( + config.trace_numpy + and np + and (istype(obj, np.ndarray) or isinstance(obj, np.generic)) + ): + seen_ids[obj_id] = True + return seen_ids[obj_id] + elif istype(obj, (list, tuple)): + seen_ids[obj_id] = any(has_tensor(v) for v in obj) + return seen_ids[obj_id] + elif istype(obj, dict): + # Some packages like pytest can be updated during runtime. So, make a + # copy of values to avoid issues like "RuntimeError: dictionary + # changed size during iteration" + values = list(obj.values()) + seen_ids[obj_id] = any(has_tensor(v) for v in values) + return seen_ids[obj_id] + elif istype(obj, (str, int, float, type(None), bool)): + seen_ids[obj_id] = False + return seen_ids[obj_id] + elif is_namedtuple(obj) and hasattr(obj, "_fields"): + seen_ids[obj_id] = any(has_tensor(getattr(obj, v)) for v in obj._fields) + return seen_ids[obj_id] + else: + # if config.debug: + # print( + # f"Assuming that object of type {type(obj)} does not have a tensor" + # ) + return False + + # Check if the passed arguments are of type Tensor + for value in frame.f_locals.values(): + if has_tensor(value): + return True + + log.debug( + "skipping because no torch.* %s \ + %s %s", + frame.f_code.co_name, + frame.f_code.co_filename, + frame.f_code.co_firstlineno, + ) + + return False + + +def exception_handler( + e: Exception, + code: CodeType, + frame: Optional[DynamoFrameType] = None, + export: bool = False, +) -> None: + record_filename = None + if hasattr(e, "exec_record"): + record_filename = gen_record_file_name(e, code) + write_record_to_file(record_filename, e.exec_record) + e.record_filename = record_filename # type: ignore[attr-defined] + + augment_exc_message(e, export=export) + + +FRAME_COUNTER = 0 +FRAME_COMPILE_COUNTER: typing.Counter[Union[int, FrameStateSizeEntry]] = ( + collections.Counter() +) + + +def maybe_cprofile(func: Callable[_P, _T]) -> Callable[_P, _T]: + if config.cprofile: + return cprofile_wrapper(func) + return func + + +def cprofile_wrapper(func: Callable[_P, _T]) -> Callable[_P, _T]: + @functools.wraps(func) + def profile_wrapper(*args: _P.args, **kwargs: _P.kwargs) -> _T: + trace_id = CompileContext.current_trace_id() + assert trace_id, "Trace id is None" + profile_path = Path( + f"/tmp/{func.__name__}_{str(trace_id).replace('/', '_')}.profile" + ) + prof = cProfile.Profile() + try: + start_ts = time.time() + # runcall calls prof.enable() and prof.disable(), so do NOT call + # enable outside. This leads to issues like + # ValueError: Another profiling tool is already active + # pyrefly: ignore [bad-argument-type] + retval = prof.runcall(func, *args, **kwargs) + profile_latency = time.time() - start_ts + except ValueError: + log.exception("failed to enable cProfile") + profile_latency = 0 + retval = func(*args, **kwargs) + log.warning( + "### Cprofile for %s trace id [%s] took %.3f seconds ###", + func.__name__, + trace_id, + profile_latency, + ) + ps = pstats.Stats(prof) + try: + prof.dump_stats(profile_path) + except OSError: + log.exception("Cannot write to %s", profile_path) + log.warning("Raw profile at %s", profile_path) + svg_path = profile_path.with_suffix(".svg") + try: + with subprocess.Popen( + [ + "gprof2dot", + "-f", + "pstats", + "--node-label=total-time-percentage", + "--node-label=self-time-percentage", + "--node-label=total-time", + str(profile_path), + ], + stdout=subprocess.PIPE, + ) as gprof2dot_process: + subprocess.check_call( + ["dot", "-Tsvg", "-o", str(svg_path)], + stdin=gprof2dot_process.stdout, + ) + log.warning("Generated SVG from profile at %s", svg_path) + except FileNotFoundError: + log.warning( + "Failed to generate SVG from profile -- dumping stats instead." + "Try installing gprof2dot and dot for a better visualization" + ) + ps.sort_stats(pstats.SortKey.TIME).print_stats(20) + ps.sort_stats(pstats.SortKey.CUMULATIVE).print_stats(20) + + if manifold_link := maybe_upload_prof_stats_to_manifold( + str(profile_path) + ): # fb-only + torch._logging.trace_structured( + "link", + lambda: {"name": "cprofile_manifold_url", "url": manifold_link}, + ) + return retval + + return profile_wrapper + + +@dataclass +class ConvertFrameBox: + error_on_graph_break: Optional[bool] = None + + +def get_compile_id( + frame_state: dict[str, Union[int, FrameStateSizeEntry]], +) -> CompileId: + global FRAME_COUNTER + if "_id" not in frame_state: + frame_state["_id"] = FRAME_COUNTER + FRAME_COUNTER += 1 + frame_id = frame_state["_id"] + assert isinstance(frame_id, int) + + frame_compile_id = FRAME_COMPILE_COUNTER[frame_id] + FRAME_COMPILE_COUNTER[frame_id] += 1 + + compiled_autograd_id = None + if prior := CompileContext.current_compile_id(): + compiled_autograd_id = prior.compiled_autograd_id + return CompileId( + compiled_autograd_id=compiled_autograd_id, + frame_id=frame_id, + frame_compile_id=frame_compile_id, + ) + + +class ConvertFrameAssert: + def __init__( + self, + compiler_fn: CompilerFn, + one_graph: bool = True, + export: bool = False, + export_constraints: Optional[typing.Never] = None, + package: Optional[CompilePackage] = None, + ) -> None: + # assert export_constraints is None + reset_graph_break_dup_checker() + self._torchdynamo_orig_backend = compiler_fn + self._one_graph = one_graph + self._export = export + self._export_constraints = export_constraints + self._package = package + self._box = ConvertFrameBox() + + @property + def _clone_with_backend(self) -> Callable[[CompilerFn], ConvertFrameAssert]: + return lambda backend: convert_frame_assert( + backend, + self._one_graph, + self._export, + self._export_constraints, + ) + + def __call__( + self, + frame: DynamoFrameType, + cache_entry: Optional[CacheEntry], + hooks: Hooks, + frame_state: dict[str, Union[int, FrameStateSizeEntry]], + *, + skip: int = 0, + ) -> ConvertFrameReturn: + increment_frame() + code = frame.f_code + + cache_size = compute_cache_size(frame, cache_entry) + input_codes.add(code) + if code in output_codes: + return ConvertFrameReturn() + if ( + os.environ.get("TORCHDYNAMO_DEBUG_FUNCTION") + and os.environ.get("TORCHDYNAMO_DEBUG_FUNCTION") != code.co_name + ): + return ConvertFrameReturn() + if code.co_name == "" and code.co_filename.endswith( + ( + "transformers/file_utils.py", + "transformers/utils/generic.py", + "diffusers/utils/outputs.py", + ) + ): + # not needed, but cleans up torchbench error stats + return ConvertFrameReturn() + if code.co_name == "__setattr__": + # setattr could be tricky to handle generally, + # but also not likely useful to compile- skip the whole frame + return ConvertFrameReturn() + if code.co_name == "__init__" and code.co_filename.startswith( + os.path.dirname(torch.optim.__file__) + ): + # optimizer support is still incomplete see + # test_state_dict in test/dynamo/test_optimizers.py + return ConvertFrameReturn() + + # Check if the frame is generated by an exec builtin call + # TODO - Running exec generated frame seems propagates f_globals to the + # next frames. + if code.co_name == "" and code.co_filename == "": + return ConvertFrameReturn() + + if ( + code.co_name == "" + and code.co_filename == "" + and not bool(frame.f_builtins) + ): + # namedtuple subclass constructor. Empty builtins cause issue with + # len keyword in LIST_LEN guard. + return ConvertFrameReturn() + + if is_generator(code): + unimplemented( + gb_type="Attempt to trace generator", + context="", + explanation="Generators cannot be compiled directly with `torch.compile`.", + hints=[ + "Call a generator from inside of a non-generator Python function and " + "compile that function instead.", + *graph_break_hints.FUNDAMENTAL, + ], + ) + + if not has_tensor_in_frame(frame): + return ConvertFrameReturn() + + # skip tracing non-recursive disabled functions + # detect if the previous frame (non-convert_frame) is a non-recursive disable wrapper + prev_frame = sys._getframe() + while ( + prev_frame + and "torch/_dynamo/convert_frame.py" in prev_frame.f_code.co_filename + ): + prev_frame = prev_frame.f_back # type: ignore[assignment] + if ( + prev_frame + and prev_frame.f_code is decorators._nonrecursive_disable_wrapper_code + ): + return ConvertFrameReturn(apply_to_code=False) + + global initial_global_state + initial_global_state = GlobalStateGuard() + + compile_id = get_compile_id(frame_state) + frame_id = compile_id.frame_id + + signpost_event( + "dynamo", + "_convert_frame_assert._compile", + { + "co_name": code.co_name, + "frame_id": frame_id, + "compile_id": str(compile_id), + "co_filename": code.co_filename, + "co_firstlineno": code.co_firstlineno, + "cache_size": cache_size.num_cache_entries_with_same_id_matched_objs, + "accumulated_cache_size": cache_size.num_cache_entries, + }, + ) + + # Record traced frames, skipping Dynamo generated ones. + if not code.co_name.startswith(TORCH_DYNAMO_RESUME_IN_PREFIX): + info = f"{code.co_name} {code.co_filename}:{code.co_firstlineno}" + dynamo_tls.traced_frame_infos.append(info) + + with compile_context(CompileContext(compile_id)): + result = _compile( + frame.f_code, + frame.f_globals, + frame.f_locals, + frame.f_builtins, + frame.closure, + self._torchdynamo_orig_backend, + self._one_graph, + self._export, + self._export_constraints, + hooks, + cache_entry, + cache_size, + frame, + frame_state=frame_state, + compile_id=compile_id, + skip=skip + 1, + package=self._package, + convert_frame_box=self._box, + ) + + if config.caching_precompile and self._package is not None: + from .package import DynamoCache + + # Record that the dynamo package has changed + DynamoCache.record_package(self._package) + return result + + +def convert_frame_assert( + compiler_fn: CompilerFn, + one_graph: bool = True, + export: bool = False, + export_constraints: Optional[typing.Never] = None, + package: Optional[CompilePackage] = None, +) -> ConvertFrameAssert: + """Fully convert a frame into an FX graph, raising an exception if we fail.""" + return ConvertFrameAssert( + compiler_fn, one_graph, export, export_constraints, package + ) + + +from collections import OrderedDict + +from torch.utils.hooks import RemovableHandle + + +# we have to use `OrderedDict` to make `RemovableHandle` work. +_bytecode_hooks: dict[int, BytecodeHook] = OrderedDict() + + +def register_bytecode_hook(hook: BytecodeHook) -> RemovableHandle: + """Register hooks for bytecode generated by Dynamo. The hook can do some + logging, as well as return a new code object to be used. Please refer + to `BytecodeHook` for the hook signature. + """ + handle = RemovableHandle(_bytecode_hooks) + _bytecode_hooks[handle.id] = hook + return handle + + +# TODO - We want to run preserve_node_meta context manager here, but the CI +# fails (its unclear if the failures were flaky) +# @torch.fx.traceback.preserve_node_meta() +@preserve_global_state +def trace_frame( + code: types.CodeType, + globals: dict[str, object], + locals: dict[str, object], + builtins: dict[str, object], + closure: tuple[CellType], + compiler_fn: CompilerFn, + tf_mode_stack: list[torch.overrides.TorchFunctionMode], + one_graph: bool, + speculation_log: SpeculationLog, + instructions: list[Instruction], + code_options: dict[str, object], + *, + export: bool = False, + export_constraints: Optional[typing.Never] = None, + frame_state: Optional[dict[str, Union[int, FrameStateSizeEntry]]] = None, + distributed_state: Optional[DistributedState] = None, + package: Optional[CompilePackage] = None, +) -> DynamoTracerOutput: + from torch.fx.experimental.validator import bisect, translation_validation_enabled + + speculation_log.restart() # type: ignore[has-type] + exn_vt_stack = ExceptionStack() + tracer = InstructionTranslator( + instructions, + code, + locals, + globals, + builtins, + closure, + tf_mode_stack, + code_options, + compiler_fn, + one_graph, + export, + export_constraints, + frame_state=frame_state, + speculation_log=speculation_log, # type: ignore[has-type] + exn_vt_stack=exn_vt_stack, + distributed_state=distributed_state, # type: ignore[has-type] + package=package, + ) + + def run_tracer() -> None: + try: + tracer.output.mark_bytecode_tracing_start() + with tracing(tracer.output.tracing_context), tracer.set_current_tx(): + tracer.run() + except exc.UnspecializeRestartAnalysis: + speculation_log.clear() # type: ignore[has-type] + raise + except ( + exc.SpeculationRestartAnalysis, + exc.TensorifyScalarRestartAnalysis, + exc.SkipFrame, + ): + raise + except Exception: + if translation_validation_enabled(): + bisect(tracer.output.shape_env) + raise + finally: + tracer.output.call_cleanup_hooks() + tracer.f_locals = {} + + try: + run_tracer() + tracer_output = DynamoTracerOutput(tracer) + output = tracer_output.output_graph + assert output is not None + assert output.output_instructions + instructions[:] = output.output_instructions + code_options.update(output.code_options) + propagate_inst_exn_table_entries(instructions) + check_inst_exn_tab_entries_valid(instructions) + instructions[:] = remove_pointless_jumps(remove_dead_code(instructions)) + except Exception as e: + e._torch_dynamo_tracer_output = DynamoTracerOutput(tracer, error=True) # type: ignore[attr-defined] + raise + return tracer_output + + +@dataclass +class DynamoOutput: + """ + Represents the core data returned from a single dynamo run, including: + - Guards, wrapped inside tracer_output.output_graph.guards + - Generated bytecode + - Other information needed for compilation. + This data structure should capture all the "interesting" information dynamo + produces on the frontend side before it enters user backend. + """ + + tracer_output: DynamoTracerOutput + bytecode: types.CodeType + last_attempt_start_time: Optional[float] + + def build_guards( + self, + code: types.CodeType, + hooks: Optional[Hooks] = None, + save: bool = False, + cache_entry: Optional[CacheEntry] = None, + strict_error: bool = False, + ) -> CheckFunctionManager: + output_graph = self.tracer_output.output_graph + assert output_graph is not None + return CheckFunctionManager( + code, + output_graph, + cache_entry, + hooks.guard_fail_fn if hooks else None, + hooks.guard_filter_fn if hooks else None, + save_guards=save, + strict_error=strict_error, + ) + + def graph_capture_output( + self, argdefs: Optional[tuple[Any, ...]] = None + ) -> GraphCaptureOutput: + output_graph = self.tracer_output.output_graph + assert output_graph is not None + return GraphCaptureOutput( + OutputGraphCommon( + output_graph.dump_guards_state(), + output_graph.import_sources, + output_graph.shape_env, + output_graph.export_metadata, + output_graph.tracked_fakes_id_to_source, + ), + output_graph.import_sources, + output_graph.traced_code, + self.bytecode, + self.tracer_output.closure, + argdefs, + self.tracer_output.f_globals, + ) + + +@dataclass +class BackendInput: + """ + Represents core data structure that dynamo will pass to a backend, including: + - Graph module + - Example inputs + - The FakeTensorMode used for compiling graph. + This data structure should capture all the information dynamo produces + on for the user backend. + """ + + backend_id: str + graph_module: torch.fx.GraphModule + example_inputs: Any + fake_mode: torch._subclasses.fake_tensor.FakeTensorMode + tensor_to_context: WeakIdKeyDictionary + + +@dataclass(frozen=True) +class GraphRuntimeEnv: + bytecode: types.CodeType + import_sources: dict[str, str] + used_globals: dict[str, Any] + closure: Optional[tuple[Any, ...]] + argdefs: Optional[tuple[Any, ...]] + external_refs: set[str] = dataclasses.field(default_factory=set) + + def forward_callable( + self, + backend_id: str, + compiled_fn: Callable[..., Any], + *, + extra_globals: Optional[dict[str, Any]] = None, + ) -> Callable[..., Any]: + import_sources = { + alias: importlib.import_module(module_name) + for alias, module_name in self.import_sources.items() + } + f_globals = { + **import_sources, + **self.used_globals, + **(extra_globals or {}), + backend_id: compiled_fn, + } + + # check that all external references are available + self._check_external_refs(f_globals) + + return types.FunctionType( + self.bytecode, + f_globals, + closure=self.closure, + argdefs=self.argdefs, + ) + + def _check_external_refs(self, f_globals: dict[str, Any]) -> None: + missing_refs = [] + for ref in self.external_refs: + if ref not in f_globals: + missing_refs.append(ref) + + if missing_refs: + raise RuntimeError( + f"Missing required external references: {missing_refs}. " + "Please load AOT compiled function with `f_globals=`" + ) + + +@dataclass +class GraphCaptureOutput: + """ + Minimal version of DynamoOutput + """ + + output_graph: OutputGraphCommon + import_sources: dict[str, str] + traced_code: list[CodeType] + bytecode: CodeType + closure: Optional[tuple[Any, ...]] + argdefs: Optional[tuple[Any, ...]] + f_globals: dict[str, Any] + + def build_guards( + self, + code: types.CodeType, + hooks: Optional[Hooks] = None, + save: bool = False, + cache_entry: Optional[CacheEntry] = None, + strict_error: bool = False, + ) -> CheckFunctionManager: + return CheckFunctionManager( + code, + self.output_graph, + cache_entry, + hooks.guard_fail_fn if hooks else None, + hooks.guard_filter_fn if hooks else None, + save_guards=save, + strict_error=strict_error, + ) + + def get_runtime_env(self) -> GraphRuntimeEnv: + from torch._dynamo.source import get_global_source_name + + used_globals = {} + for ( + source + ) in self.output_graph.export_metadata.graph_input_idx_to_local_source.values(): + global_name = get_global_source_name(source) + if global_name is None: + continue + if global_name in self.f_globals: + used_globals[global_name] = self.f_globals[global_name] + + # Scan bytecode for all external references + external_refs = self._get_external_refs(self.bytecode) + + return GraphRuntimeEnv( + bytecode=self.bytecode, + import_sources=self.import_sources, + used_globals=used_globals, + closure=self.closure, + argdefs=self.argdefs, + external_refs=external_refs, + ) + + @staticmethod + def _get_external_refs(bytecode: types.CodeType) -> set[str]: + import dis + + external_refs: set[str] = set() + + # Get all instructions from the bytecode + for instruction in dis.get_instructions(bytecode): + # LOAD_GLOBAL loads a global variable or a builtin + if instruction.opname == "LOAD_GLOBAL": + if instruction.argval: + external_refs.add(instruction.argval) + # LOAD_NAME loads a name (used in module-level code, less common in functions) + elif instruction.opname == "LOAD_NAME": + if instruction.argval: + external_refs.add(instruction.argval) + + return external_refs + + +@dataclass +class CaptureOutput: + """ + CaptureOutput should represent all the information produced from torch + compiler for a single graph capture. This intends to be consumed by + various compiler frontends so that we can share as much compiler internals + as possible and avoid great divergence between different stacks. + This data structure should eventually contain all the information compiler + produces as more refactors happens to converge different compiler + frontends. + """ + + graph_capture_output: GraphCaptureOutput + # BackendInput can be None when dynamo didn't compile any graph (no tensor op) + backend_input: Optional[BackendInput] + + def forward_callable( + self, + *, + compiled_fn: Optional[Callable[..., Any]] = None, + extra_globals: Optional[dict[str, Any]] = None, + ) -> Callable[..., Any]: + runtime_env = self.graph_capture_output.get_runtime_env() + assert self.backend_input is not None + backend_id = self.backend_input.backend_id + # pyrefly: ignore [not-callable] + compiled_fn = compiled_fn or self.backend_input.graph_module + return runtime_env.forward_callable( + backend_id, compiled_fn, extra_globals=extra_globals + ) + + +def get_traced_fn(mod: Any) -> tuple[FunctionType, Optional[object]]: + """ + Utility function to get the function to trace, and optionally a bound self + object, from a callable (nn.Module, function, or method). + """ + import inspect + + if isinstance(mod, torch.nn.Module): + resolved_forward = mod.forward + if hasattr(resolved_forward, "__self__"): + # pyrefly: ignore [missing-attribute] + resolved_forward = resolved_forward.__func__ + + # Mirrored from NNModuleVariable.call_function: + # https://github.com/pytorch/pytorch/blob/main/torch/_dynamo/variables/nn_module.py#L1035 + if ( + len(mod._forward_pre_hooks) == 0 + and len(mod._forward_hooks) == 0 + and len(torch.nn.modules.module._global_forward_pre_hooks) == 0 + and len(torch.nn.modules.module._global_forward_hooks) == 0 + and len(mod._backward_pre_hooks) == 0 + and len(mod._backward_hooks) == 0 + and len(torch.nn.modules.module._global_backward_pre_hooks) == 0 + and len(torch.nn.modules.module._global_backward_hooks) == 0 + and resolved_forward != torch.nn.Module.forward + ): + # We cannot trace __call__ by default because it will break + # the legacy dynamo export. If we want to revisit this, + # feel free to remove this path and try unittests in + # test_strict_export_v2.py + mod = mod.forward + elif isinstance(mod, torch.fx.GraphModule): + mod = mod._call_impl + else: + mod = mod.__call__ + + if hasattr(mod, "__self__"): + # pyrefly: ignore [missing-attribute] + return mod.__func__, mod.__self__ + elif inspect.isfunction(mod): + return mod, None + else: + raise RuntimeError(f"Unsupported model code type {mod}") + + +def _get_signature(fn: Any) -> inspect.Signature: + return inspect.signature(fn, follow_wrapped=False) + + +def _get_frame( + mod: Any, + args: tuple[Any, ...], + kwargs: Optional[dict[str, Any]] = None, +) -> FrameInfo: + """ + Create a frame to trace, given a model, args, and optional kwargs. + """ + import builtins + + fn, self_opt = get_traced_fn(mod) + if self_opt is not None: + args = (self_opt,) + args + if kwargs is None: + kwargs = {} + + signature = _get_signature(fn) + bound_arguments = signature.bind(*args, **kwargs) + bound_arguments.apply_defaults() + f_locals = bound_arguments.arguments + + closure = fn.__closure__ or () + freevars = fn.__code__.co_freevars + if freevars or closure: + assert len(closure) == len(freevars) + f_locals.update( + {name: cell.cell_contents for name, cell in zip(freevars, closure)} + ) + + return FrameInfo( + fn.__code__, + fn.__globals__, + f_locals, + builtins.__dict__, + closure=fn.__closure__ or (), # type: ignore[arg-type] + argdefs=fn.__defaults__, + ) + + +def fullgraph_capture( + mod: Any, + args: tuple[Any, ...], + kwargs: Optional[dict[str, Any]] = None, + *, + constraints: Optional[list[Constraint]] = None, + _is_export_deprecated_do_not_use: bool = False, +) -> CaptureOutput: + """ + This API captures a full graph for a model, given example inputs to trace with. + + Specifically, it takes a callable (nn.Module, method, or function), args, and + optional kwargs, and returns Dynamo-captured graph along with other important + compile-time information. This serves as the common graph-capture mechanism + for different torch compiler AOT frontends (e.g. AOT precompile, export). + + Note that this API doesn't apply context managers like metrics context, + and the expectation is that the caller will apply them depending + on the use case. + + The CaptureOutput is separated into two parts: + 1. Frontend specific information, which includes: + - guards + - generated bytecode + - other information tracked by OutputGraphCommon. + 2. Backend specific information (indexed by unique backend id) such as: + - fx graph + - example inputs + """ + frame = _get_frame(mod, args, kwargs) + + with compile_context(CompileContext(get_compile_id({}))): + return _fullgraph_capture_frame( + frame, + constraints=constraints, + _is_export_deprecated_do_not_use=_is_export_deprecated_do_not_use, + ) + + +@dataclass +class FrameInfo: + code: types.CodeType + globals: dict[str, object] + locals: dict[str, object] + builtins: dict[str, object] + closure: tuple[CellType] + argdefs: Optional[tuple[Any, ...]] + + +def _fullgraph_capture_frame( + frame: FrameInfo, + *, + constraints: Optional[list[Constraint]] = None, + _is_export_deprecated_do_not_use: bool = False, +) -> CaptureOutput: + from torch._guards import TracingContext + + backend_input: Optional[BackendInput] = None + + def fullgraph_compiler( + gm: torch.fx.GraphModule, example_inputs: list[torch.Tensor] + ) -> torch.fx.GraphModule: + nonlocal backend_input + tracing_context = TracingContext.get() + fake_mode = tracing_context.fake_mode + tensor_to_context = tracing_context.tensor_to_context + assert fake_mode is not None + assert isinstance(gm.meta["backend_id"], str) + backend_input = BackendInput( + gm.meta["backend_id"], gm, example_inputs, fake_mode, tensor_to_context + ) + return gm + + try: + dynamo_output = compile_frame( + frame.code, + frame.globals, + frame.locals, + frame.builtins, + frame.closure, + compiler_fn=fullgraph_compiler, + export=_is_export_deprecated_do_not_use, + export_constraints=constraints, # type: ignore[arg-type] + one_graph=True, + restart_reasons=set(), + ) + # https://github.com/pytorch/pytorch/blob/main/torch/_dynamo/eval_frame.py#L831 + except Unsupported as e: + augment_exc_message(e) + if config.verbose: + raise + # strip internal tracebacks from causes + cur_exn: BaseException = e + while cur_exn.__cause__ is not None: + cur_exn.__cause__.with_traceback(None) + cur_exn = cur_exn.__cause__ + # pyrefly: ignore [invalid-inheritance] + raise e.with_traceback(None) from e.__cause__ # User compiler error + + return CaptureOutput( + dynamo_output.graph_capture_output(frame.argdefs), + backend_input, + ) + + +def compile_frame( # type: ignore[return] + code: types.CodeType, + globals: dict[str, object], + locals: dict[str, object], + builtins: dict[str, object], + closure: tuple[CellType], + compiler_fn: CompilerFn, + one_graph: bool, + restart_reasons: set[str], + *, + export: bool = False, + export_constraints: Optional[typing.Never] = None, + frame_state: Optional[dict[str, Union[int, FrameStateSizeEntry]]] = None, + distributed_state: Optional[DistributedState] = None, + package: Optional[CompilePackage] = None, + # pyrefly: ignore [bad-return] +) -> DynamoOutput: + """ + A helper function taking a frame and backend, then return the generated bytecode + and guards as a common data structure. + This is a shared interface for multiple compiler frontends (e.g. torch.compile, + torch.export) that needs to capture a graph out of python code. + """ + # This is shared across restarts + speculation_log = SpeculationLog() + + def transform( + instructions: list[Instruction], code_options: dict[str, object] + ) -> DynamoTracerOutput: + tf_mode_stack: list[torch.overrides.TorchFunctionMode] = ( + torch.overrides._get_current_function_mode_stack() + ) + tracer_output = trace_frame( + code, + globals, + locals, + builtins, + closure, + compiler_fn, + tf_mode_stack, + one_graph, + speculation_log, + instructions, + code_options, + export=export, + export_constraints=export_constraints, + frame_state=frame_state, + distributed_state=distributed_state, + package=package, + ) + + assert tracer_output is not None + return tracer_output + + last_attempt_start_time = None + for attempt in itertools.count(): + CompileContext.get().attempt = attempt + + try: + with dynamo_timed(f"compile_attempt_{attempt}", log_pt2_compile_event=True): + bytecode, tracer_output = transform_code_object(code, transform) + assert tracer_output is not None + return DynamoOutput( + tracer_output=tracer_output, + bytecode=bytecode, + last_attempt_start_time=last_attempt_start_time, + ) + except exc.RestartAnalysis as e: + if not isinstance(e, exc.TensorifyScalarRestartAnalysis): + TensorifyState.clear() + log.info( + "Restarting analysis due to %s", + LazyString(format_traceback_short, e.__traceback__), + ) + # Clean up the failed tracer output's graph to break reference cycles + failed_tracer_output = getattr(e, "_torch_dynamo_tracer_output", None) + if failed_tracer_output: + failed_tracer_output._cleanup_output_graph() + # If restart reason is None just log the type of the exception + restart_reasons.add(e.restart_reason or str(type(e))) + # We now have a new "last attempt", reset the clock + last_attempt_start_time = time.time() + if attempt > 100: + unimplemented( + gb_type="Excessive RestartAnalysis() calls", + context="", + explanation="Dynamo attempted to trace the same frame 100+ times. " + "Giving up on compiling as the compile time tradeoff is likely not " + "worth the performance gain.", + hints=[], + ) + except exc.SkipFrame as e: + if not isinstance(e, exc.TensorifyScalarRestartAnalysis): + TensorifyState.clear() + # Clean up the failed tracer output's graph to break reference cycles + failed_tracer_output = getattr(e, "_torch_dynamo_tracer_output", None) + if failed_tracer_output: + failed_tracer_output._cleanup_output_graph() + log.debug( # noqa: G200 + "Skipping frame %s %s \ + %s %s", + e, + code.co_name, + code.co_filename, + code.co_firstlineno, + ) + raise + + +def _compile( + code: CodeType, + globals: dict[str, object], + locals: dict[str, object], + builtins: dict[str, object], + closure: tuple[CellType], + compiler_fn: CompilerFn, + one_graph: bool, + export: bool, + export_constraints: Optional[typing.Never], + hooks: Hooks, + cache_entry: Optional[CacheEntry], + cache_size: CacheSizeRelevantForFrame, + frame: Optional[DynamoFrameType] = None, + frame_state: Optional[dict[str, Union[int, FrameStateSizeEntry]]] = None, + *, + compile_id: CompileId, + skip: int = 0, + package: Optional[CompilePackage] = None, + # Can be used to record things for the caller, both + # in the case of normal and exception code paths + convert_frame_box: Optional[ConvertFrameBox] = None, +) -> ConvertFrameReturn: + from torch.fx.experimental.validator import ( + BisectValidationException, + ValidationException, + ) + + # Only nonlocal defs here please! + # Time spent compiling this frame before restarting or failing analysis + dynamo_time_before_restart: float = 0.0 + + @compile_time_strobelight_meta(phase_name="compile_inner") + def compile_inner( + code: CodeType, one_graph: bool, hooks: Hooks + ) -> tuple[ConvertFrameReturn, Optional[DynamoTracerOutput]]: + with contextlib.ExitStack() as stack: + stack.enter_context( + torch._dynamo.callback_handler.install_callbacks( + CallbackTrigger.DYNAMO, str(CompileContext.current_compile_id()) + ) + ) + stack.enter_context(CompileTimeInstructionCounter.record()) + return _compile_inner(code, one_graph, hooks) + + return ( + ConvertFrameReturn(), + None, + ) # dead, but see https://github.com/python/mypy/issues/7577 + + @maybe_cprofile + def _compile_inner( + code: CodeType, + one_graph: bool, + hooks: Hooks, + ) -> tuple[ConvertFrameReturn, DynamoTracerOutput]: + nonlocal dynamo_time_before_restart + last_attempt_start_time = start_time = time.time() + + def log_bytecode( + prefix: str, name: str, filename: str, line_no: int, code: CodeType + ) -> None: + if bytecode_log.isEnabledFor(logging.DEBUG): + bytecode_log.debug( + format_bytecode(prefix, name, filename, line_no, code) + ) + + log_bytecode( + "ORIGINAL BYTECODE", + code.co_name, + code.co_filename, + code.co_firstlineno, + code, + ) + + out_code = None + try: + dynamo_output = compile_frame( + code, + globals, + locals, + builtins, + closure, + compiler_fn, + one_graph, + restart_reasons, + export=export, + export_constraints=export_constraints, + frame_state=frame_state, + distributed_state=distributed_state, + package=package, + ) + except exc.SkipFrame as e: + if one_graph: + log.debug("No graph captured with export/fullgraph=True") + assert e._torch_dynamo_tracer_output is not None + return ConvertFrameReturn(), e._torch_dynamo_tracer_output + + assert distributed_state is None or distributed_state.all_states is not None, ( # type: ignore[has-type] + "compiler collective wasn't run before compilation completed" + ) + out_code = dynamo_output.bytecode + tracer_output = dynamo_output.tracer_output + if dynamo_output.last_attempt_start_time is not None: + last_attempt_start_time = dynamo_output.last_attempt_start_time + + assert out_code is not None + log_bytecode( + "MODIFIED BYTECODE", + code.co_name, + code.co_filename, + code.co_firstlineno, + out_code, + ) + + for idx, hook in enumerate(_bytecode_hooks.values()): + with dynamo_timed(f"bytecode_hooks_{idx}", log_pt2_compile_event=True): + hook_output = hook(code, out_code) + if hook_output is not None: + out_code = hook_output + + orig_code_map[out_code] = code + output_codes.add(out_code) + dynamo_time_before_restart = last_attempt_start_time - start_time + assert tracer_output.output_graph is not None + output = tracer_output.output_graph + + # Tests for new code objects. + # The rationale for these tests can be found in torch/csrc/dynamo/eval_frame.c + # Only test once the code object is created. + # They are not tested during runtime. + + def count_args(code: CodeType) -> int: + import inspect + + return ( + code.co_argcount + + code.co_kwonlyargcount + + bool(code.co_flags & inspect.CO_VARARGS) + + bool(code.co_flags & inspect.CO_VARKEYWORDS) + ) + + assert out_code is not None + + total_argcount_old = count_args(code) + total_argcount_new = count_args(out_code) + msg = "arg mismatch: " + msg += f"old code object has args {code.co_varnames[:total_argcount_old]}, " + msg += f"new code object has args {out_code.co_varnames[:total_argcount_new]}" + assert ( + code.co_varnames[:total_argcount_old] + == out_code.co_varnames[:total_argcount_new] + ), msg + + msg = "free var mismatch: " + msg += f"old code object has free var {code.co_freevars}, " + msg += f"new code object has free var {out_code.co_freevars}" + assert code.co_freevars == out_code.co_freevars, msg + + msg = "cell var mismatch: " + msg += f"old code object has cell var {code.co_cellvars}, " + msg += f"new code object has cell var {out_code.co_cellvars}" + assert code.co_cellvars == out_code.co_cellvars, msg + + # Skipping Dynamo on a frame without any extracted graph. + # This does not affect eager functionality. But this is necessary + # for export for cases where Dynamo-reconstructed bytecode can create + # new function frames, confusing export in thinking that there + # are extra graphs now. + + if output.export and output.is_empty_graph(): + return ConvertFrameReturn(), tracer_output + + assert output.guards is not None + CleanupManager.instance[out_code] = output.cleanups + nonlocal cache_entry + with dynamo_timed("build_guards", log_pt2_compile_event=True): + check_fn = dynamo_output.build_guards( + code, + hooks=hooks, + save=package is not None, + cache_entry=cache_entry, + ) + + if package is not None: + assert check_fn.guards_state is not None + package.add_guarded_code(check_fn.guards_state, out_code) + package.add_inlined_source(output.tracing_context.traced_code) + package.update_device_type(output.current_tracer.graph) + + compile_id_str = str(compile_id) if compile_id is not None else "Unknown" + annotation_str = "Torch-Compiled Region: " + compile_id_str + guarded_code = GuardedCode( + out_code, + check_fn.guard_manager, # type: ignore[arg-type] + compile_id, + annotation_str, + ) + + if not output.is_empty_graph() and hooks.guard_export_fn is not None: + # We should not run the guard_export_fn when Dynamo does not + # generate any graph. This can happen in export when TorchDynamo + # generated bytecode has some reconstruction logic for mutated + # variables which can trigger TorchDynamo on the children frames but + # they are benign and do not generate any new graphs. + hooks.guard_export_fn(output.guards) + + return wrap_guarded_code(guarded_code), tracer_output + + metrics_context = get_metrics_context() + code_context = ( + package.code_context(code) if package is not None else contextlib.nullcontext() + ) + with ( + _use_lazy_graph_module(config.use_lazy_graph_module), + compile_context(CompileContext(compile_id)), + chromium_event_timed( + "dynamo", reset_event_log_on_exit=True, log_pt2_compile_event=True + ), + _WaitCounter("pytorch.wait_counter.entire_forward_compile").guard(), + metrics_context, + dynamo_timed( + "_compile.compile_inner", + phase_name="entire_frame_compile", + dynamo_compile_column_us="dynamo_cumulative_compile_time_us", + ), + code_context, + ): + restart_reasons: set[str] = set() + if compile_pg := get_compile_pg(): + distributed_state = DistributedState(compile_pg, LocalState()) + else: + distributed_state = None + + # Check recompilations + recompile_reason: Optional[str] = None + if is_recompilation(cache_size) and frame: + reasons = get_and_maybe_log_recompilation_reasons( + cache_entry, frame, innermost_fn(compiler_fn) + ) + recompile_reason = ( + "Unable to find recompilation reasons" if not reasons else reasons[0] + ) + # Recheck for recompilation, for when inline_inbuilt_nn_modules is set to False + inline_inbuilt_nn_modules_candidate = False + if not config.inline_inbuilt_nn_modules and frame: + inbuilt_nn_reasons = get_and_maybe_log_recompilation_reasons( + cache_entry, frame, innermost_fn(compiler_fn), skip_logging=True + ) + inbuilt_nn_recompile_reason = ( + None if not inbuilt_nn_reasons else inbuilt_nn_reasons[0] + ) + + if ( + inbuilt_nn_recompile_reason is not None + and "[inline-inbuilt-nn-modules-candidate]" + in inbuilt_nn_recompile_reason + ): + inline_inbuilt_nn_modules_candidate = True + + # Set if the recompile is a candidate for inline_inbuilt_nn_modules + # regardless of whether inline_inbuilt_nn_modules is set or not + metrics_context.update_outer( + { + "recompile_reason": recompile_reason, + "inline_inbuilt_nn_modules_candidate": inline_inbuilt_nn_modules_candidate, + } + ) + + recompile_user_contexts = get_hook_for_recompile_user_context() + if recompile_user_contexts: + # cap each user context to N chars for data retention purposes. N=256 + # is chosen to be large enough to capture the most important info. + user_contexts_msg = { + user_context()[:256] for user_context in recompile_user_contexts + } + metrics_context.set("recompile_user_contexts", user_contexts_msg) + + exceeded, limit_type = exceeds_recompile_limit(cache_size, compile_id) + if exceeded: + + def format_func_info(code: CodeType) -> str: + return f"'{code.co_name}' ({code.co_filename}:{code.co_firstlineno})" + + # NS: Don't add period at the end of string, as it'll be added to URL + # rendering it incorrect + log.warning( + "torch._dynamo hit config.%s (%s)\n" + " function: %s\n" + " last reason: %s\n" + 'To log all recompilation reasons, use TORCH_LOGS="recompiles".\n' + "To diagnose recompilation issues, see %s", + limit_type, + getattr(config, limit_type), + format_func_info(code), + recompile_reason, + troubleshooting_url, + ) + if config.fail_on_recompile_limit_hit: + raise FailOnRecompileLimitHit( + f"{limit_type} reached, because fail_on_recompile_limit_hit = True this is a HARD failure" + ) + elif one_graph: + raise FailOnRecompileLimitHit( + f"{limit_type} reached with fullgraph=True. Excessive recompilations can degrade " + "performance due to the compilation overhead of each recompilation. To monitor " + "recompilations, enable TORCH_LOGS=recompiles. If recompilations are expected, consider " + "increasing torch._dynamo.config.cache_size_limit to an appropriate value." + ) + elif justknobs_check( + "pytorch/compiler:skip_code_recursive_on_recompile_limit_hit" + ): + raise RecompileLimitExceeded(f"{limit_type} reached") + else: + # do not recursively skip frames + unimplemented( + gb_type="Dynamo cache limit exceeded", + context=f"Limit type: {limit_type}", + explanation="Dynamo attempted to recompile the code object too many times, " + f"exceeding the {limit_type} cache size limit." + "Giving up on compiling as the compile time tradeoff is likely not " + "worth the performance gain.", + hints=[], + ) + + log.debug( + "torchdynamo start compiling %s %s:%s, stack (elided %s frames):\n%s", + code.co_name, + code.co_filename, + code.co_firstlineno, + skip + 2, + # -2: omit current frame, omit contextlib decorator + "".join(CapturedTraceback.extract(skip=2 + skip).format()), + ) + # -4: -2 as above, plus trace_structured frames + # + # NB: the frame looks like this: + # + # # handled by skip argument + # torch/_dynamo/convert_frame.py:1069 in catch_errors + # torch/_dynamo/convert_frame.py:910 in _convert_frame + # torch/_dynamo/convert_frame.py:464 in _convert_frame_assert + # torch/_utils_internal.py:70 in wrapper_function + # + # # 2 current frame and context lib + # env/lib/python3.10/contextlib.py:79 in inner + # torch/_dynamo/convert_frame.py:776 in _compile + # + # # 2 extra here + # torch/_logging/_internal.py:1064 in trace_structured + # torch/_dynamo/convert_frame.py:780 in + stack_trace = log_dynamo_start(code, skip) + start_time_ns = time.time_ns() + fail_type: Optional[str] = None + fail_reason: Optional[str] = None + exception_stack_trace: Optional[list[str]] = None + fail_user_frame_filename: Optional[str] = None + fail_user_frame_lineno: Optional[int] = None + torch._dynamo.utils.ReinplaceCounters.clear() + guarded_code = None + tracer_output = None + try: + guarded_code, tracer_output = compile_inner(code, one_graph, hooks) + + # NB: We only put_code_state in success case. Success case here + # does include graph breaks; specifically, if a graph break still + # resulted in a partially compiled graph, we WILL return here. An + # Unsupported exception will only bubble to the top level if we + # are unable to compile the frame at all. In this case, there's + # no point in uploading the code state, because we will always + # fail exactly the same way even without the update. (It's useful + # to upload for graph break though, because this can prevent + # extra graph break compilations.) + put_code_state() + if ( + tracer_output + and (output_graph := tracer_output.output_graph) + and output_graph.has_outputs() + ): + log_frame_dynamic_whitelist(code) + if recompile_reason and "size mismatch at index" in recompile_reason: + _log_size_mismatch_recompile() + + return guarded_code + except Exception as e: + # NB: e's msg is mutated here to add user stack, but we DON'T want + # that stack in the Scuba logged fail_reason. So we grab the fail + # info here and add it to the metrics context below. + fail_type = type(e).__qualname__ + fail_reason = str(e) + exception_stack_trace = [traceback.format_exc()] + exception_handler(e, code, frame, export=export) + # NB: this is the post-mutation exception + torch._logging.trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "dynamo_error", + "encoding": "string", + }, + payload_fn=lambda: traceback.format_exc(), + ) + fail_user_frame_filename, fail_user_frame_lineno = exc.get_exc_message( + e, compile_id + ) + tracer_output = getattr(e, "_torch_dynamo_tracer_output", None) + if isinstance( + e, + ( + Unsupported, + TorchRuntimeError, + BackendCompilerFailed, + AssertionError, + ConstraintViolationError, + GuardOnDataDependentSymNode, + ValidationException, + UncapturedHigherOrderOpError, + BisectValidationException, + ShortenTraceback, + PackageError, + ResumePrologueTracingError, + ), + ): + raise + else: + # Rewrap for clarity + raise InternalTorchDynamoError( + f"{type(e).__qualname__}: {str(e)}" + ).with_traceback(e.__traceback__) from None + finally: + # === WARNING WARNING WARNING === + # If you commit a bug here, it will suppress writing to + # dynamo_compile table, and we will not have telemetry. + # Be extra careful when making changes here! + + if torch._dynamo.config.run_gc_after_compile: + with dynamo_timed("gc", dynamo_compile_column_us="gc_time_us"): + log.info("run_gc_after_compile: running gc") + gc.collect(1) + + output = None + if tracer_output: + output = tracer_output.output_graph + if output: + output.local_scope = {} + # tracer should already be None, keep an extra check here just in case. + if tracer := output.root_tx: + tracer.f_locals = {} + + from .utils import curr_frame + + frame_key = str(curr_frame) + if fail_reason is None and output is not None: + guard_count = len(output.guards) + shape_env_guard_count = len(output.shape_env.guards) + graph_op_count = output.count_calls() + graph_node_count = len(output.graph.nodes) + graph_node_shapes = output.get_graph_sizes_structured() + graph_input_count = len(output.placeholders) + non_compliant_ops = {op.__qualname__ for op in output.non_compliant_ops} + compliant_custom_ops = { + op.__qualname__ for op in output.compliant_custom_ops + } + torch._dynamo.utils.ReinplaceCounters.log() + else: + guard_count = None + shape_env_guard_count = None + graph_op_count = None + graph_node_count = None + graph_node_shapes = {} + graph_input_count = None + non_compliant_ops = set({}) + compliant_custom_ops = set({}) + restart_reasons = set() + # If compilation failed, the entire time is wasted + dynamo_time_before_restart = (time.time_ns() - start_time_ns) / 1e9 + + metrics = { + "frame_key": frame_key, + "co_name": code.co_name, + "co_filename": code.co_filename, + "co_firstlineno": code.co_firstlineno, + "cache_size": cache_size.num_cache_entries_with_same_id_matched_objs, + "accumulated_cache_size": cache_size.num_cache_entries, + "guard_count": guard_count, + "shape_env_guard_count": shape_env_guard_count, + "graph_op_count": graph_op_count, + "graph_node_count": graph_node_count, + "graph_input_count": graph_input_count, + "fail_type": fail_type, + "fail_reason": fail_reason, + "fail_user_frame_filename": fail_user_frame_filename, + "fail_user_frame_lineno": fail_user_frame_lineno, + "non_compliant_ops": non_compliant_ops, + "compliant_custom_ops": compliant_custom_ops, + "restart_reasons": restart_reasons, + "dynamo_time_before_restart_s": dynamo_time_before_restart, + "has_guarded_code": guarded_code is not None, + "specialize_float": config.specialize_float, + "is_forward": True, + "dynamo_compile_time_before_restart_us": to_int_us( + dynamo_time_before_restart + ), + "stack_trace": stack_trace, + "graph_node_shapes": str(graph_node_shapes), + "exception_stack_trace": exception_stack_trace, + } + # TODO: replace with CompileEventLogger.compilation_metrics + # There are some columns here not in PT2 Compile Events + # so we need to slightly change it + metrics_context.update_outer(metrics) + # === END WARNING WARNING WARNING === + + # If tracer is available, then tracer.error_on_graph_break reflects value of + # global symbolic_convert.error_on_graph_break at the time of the graph break - + # symbolic_convert.error_on_graph_break may have been (correctly) changed during cleanup. + # If tracer is unavailable, then fallback to symbolic_convert.error_on_graph_break. + if convert_frame_box: + convert_frame_box.error_on_graph_break = ( + tracer_output.error_on_graph_break + if tracer_output + else _get_error_on_graph_break() + ) + + +class ConvertFrame: + def __init__( + self, + compiler_fn: CompilerFn, + hooks: Hooks, + package: Optional[CompilePackage] = None, + ) -> None: + self._torchdynamo_orig_backend = compiler_fn + self._inner_convert = convert_frame_assert( + compiler_fn, one_graph=False, package=package + ) + self._hooks = hooks + + @property + def _clone_with_backend(self) -> Callable[[WrapBackendDebug], ConvertFrame]: + return lambda backend: convert_frame( + backend, + self._hooks, + ) + + def __call__( + self, + frame: DynamoFrameType, + cache_entry: Optional[CacheEntry], + hooks: Hooks, + frame_state: dict[str, Union[int, FrameStateSizeEntry]], + skip: int = 0, + ) -> ConvertFrameReturn: + input_codes.add(frame.f_code) + counters["frames"]["total"] += 1 + try: + result = self._inner_convert( + frame, cache_entry, hooks, frame_state, skip=skip + 1 + ) + counters["frames"]["ok"] += 1 + return result + except Exception as e: + # Do not allow errors to be suppressed if we're tracing a resume function prologue + if isinstance(e, ResumePrologueTracingError): + raise + + error_on_graph_break = ( + self._inner_convert._box.error_on_graph_break is not None + ) + assert error_on_graph_break is not None + if self._inner_convert._box.error_on_graph_break: + # NOTE we _might_ have to wrap the current in a custom exception + # in order to correctly bubble up to the top-level compile wrapper in + # eval_frame.py. But re-raising seems to work for now because exceptions from tracing + # a nested call that results in a top-level frame compile will be handled by the caller + # as an observed exception - we don't expect that exception to be suppressed. + raise + + # These two exception types are "soft" failure, in the sense that + # we know this is due to something we didn't implement all the + # way, scare the user less about it. That being said, if you + # are trying to understand why a graph break happened, it's still + # important to have this information, so offer it. + # + # NB: NotImplementedError used to be on this list, but actually + # it is impossible for it to reach here, as it is converted into + # InternalTorchDynamoError. This behavior seemed reasonable + # to me (ezyang, Aug 2023) so I kept it, but maybe at some point + # someone wanted these to also get suppressed. If so, you'll + # need to make these exceptions not get wrapped + + # We intentionally don't want to suppress error here. + if isinstance(e, UncapturedHigherOrderOpError): + raise + + soft_fail = isinstance(e, Unsupported) + code = frame.f_code + # This is a soft failure. In the sense, the code path reaches here + # when we do not support graph breaks on bytecodes like LOAD_ATTR, + # BUILD_SET etc. In such case, we can fallback to eager without + # scaring users. + if soft_fail and graph_break_log.isEnabledFor(logging.DEBUG): + # Log this message in the graph break. Also use the string + # "skip: " to tell that the whole frame is falling back to + # eager. + if hasattr(e, "compile_id") and hasattr(e, "real_stack"): + with compile_context(CompileContext(e.compile_id)): # type: ignore[attr-defined] + user_stack = e.real_stack + user_stack_formatted = "".join( + traceback.format_list(user_stack) + ) + frame_info = exc.format_frame_info(code) + user_stack_trace = ( + "Graph break: torch.compile cannot properly resume from this graph break, which results in a skip.\n" + f"torch.compile will skip tracing the frame {frame_info} and fall back to eager.\n" + "The graph break occurred in the following user code:\n" + f"{user_stack_formatted}" + ) + torch._logging.trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "dynamo_graph_break_reason", + "encoding": "string", + }, + payload_fn=lambda: f"{user_stack_trace}\n{traceback.format_exc()}", + ) + graph_break_log.debug( + user_stack_trace, + exc_info=True, + stack_info=config.verbose, + ) + + if not config.suppress_errors and not soft_fail: + raise + + # Suppress the error. NB: It's very important to do the + # suppression logging HERE, where the actual suppression + # happens. Previously it was somewhere else and so it was + # possible to accidentally not log at all. + record_filename = getattr(e, "record_filename", None) + code = frame.f_code + error_msg = format_error_msg(e, code, record_filename, frame) + + if soft_fail: + log.info(error_msg, exc_info=True) + else: + log.warning(error_msg, exc_info=True) + + if isinstance(e, SkipCodeRecursiveException): + return ConvertFrameReturn( + frame_exec_strategy=FrameExecStrategy( + FrameAction.SKIP, FrameAction.SKIP + ) + ) + elif isinstance(e, RecompileLimitExceeded): + return ConvertFrameReturn( + frame_exec_strategy=FrameExecStrategy( + FrameAction.RUN_ONLY, FrameAction.RUN_ONLY + ) + ) + + return ConvertFrameReturn() + + +def convert_frame( + compiler_fn: CompilerFn, + hooks: Hooks, + package: Optional[CompilePackage] = None, +) -> ConvertFrame: + """Try to convert a frame into an FX graph, if error leave frame unmodified""" + return ConvertFrame(compiler_fn, hooks, package=package) + + +# TODO mlazos: add support for same args, or record them +def replay(filename: str) -> None: + from .backends.debugging import eager + + original_replay_val = config.replay_record_enabled + config.replay_record_enabled = False + with open(filename, "rb") as in_file: + record = ExecutionRecord.load(in_file) + record.globals = dict(itertools.chain(record.globals.items(), globals().items())) + + with decorators.error_on_graph_break(False): + try: + _compile( + record.code, + record.globals, + record.locals, + record.builtins, + record.closure, + compiler_fn=eager, + one_graph=False, + export=False, + export_constraints=None, + hooks=Hooks(), + cache_size=CacheSizeRelevantForFrame(0, 0), + cache_entry=None, + frame=None, + frame_state={}, + compile_id=CompileId(frame_id=42, frame_compile_id=999), + ) + finally: + config.replay_record_enabled = original_replay_val + + +def first_real_inst_idx(code: CodeType) -> int: + if sys.version_info < (3, 11): + return 0 + for inst in dis.get_instructions(code): + if inst.opname == "RESUME": + return inst.offset // 2 + raise RuntimeError("RESUME instruction not found in code") + + +class ConvertFrameProtocol(typing.Protocol): + def __call__( + self, + frame: DynamoFrameType, + cache_entry: Optional[CacheEntry], + hooks: Hooks, + frame_state: dict[str, Union[int, FrameStateSizeEntry]], + *, + skip: int = 0, + ) -> ConvertFrameReturn: ... + + +def should_skip_due_to_torch_dispatch_mode() -> bool: + return is_in_any_mode_without_ignore_compile_internals() + + +class CatchErrorsWrapper: + def __init__(self, callback: ConvertFrameProtocol, hooks: Hooks) -> None: + functools.wraps(callback)(self) + self._torchdynamo_orig_backend = callback + self.hooks = hooks + + def __call__( + self, + frame: DynamoFrameType, + cache_entry: Optional[CacheEntry], + frame_state: dict[str, Union[int, FrameStateSizeEntry]], + ) -> ConvertFrameReturn: + assert frame_state is not None + input_codes.add(frame.f_code) + + is_skipfile = trace_rules.check(frame.f_code) + if sys.version_info >= (3, 13): + has_started_execution = frame.f_lasti > first_real_inst_idx(frame.f_code) + else: + has_started_execution = frame.f_lasti >= first_real_inst_idx(frame.f_code) + if ( + # TODO: the first condition is not covered by any test + has_started_execution + or is_skipfile + or config.disable + or ( + should_skip_due_to_torch_dispatch_mode() + and not getattr(self._torchdynamo_orig_backend, "_export", False) + ) + ): + if log.isEnabledFor(logging.DEBUG): + if has_started_execution: + skip_reason = "traced frame already" + elif trace_rules.check(frame.f_code): + skip_reason = "in skipfiles" + elif is_in_torch_dispatch_mode(include_infra_modes=False): + skip_reason = "non-infra torch dispatch mode present, this is not supported today in torch.compile" + else: + skip_reason = "dynamo tracing is disabled" + + log.debug( + "skipping: %s (reason: %s, file: %s)", + frame.f_code.co_name, + skip_reason, + frame.f_code.co_filename, + ) + return ConvertFrameReturn() + + if ( + frame.f_code.co_filename == "" and frame.f_code.co_name == "__new__" + ) or ( + frame.f_code.co_filename.endswith("collections/__init__.py") + and frame.f_code.co_name == "_make" + ): + # nametuple constructor/_make + return ConvertFrameReturn() + if torch._dynamo.utils.get_optimize_ddp_mode() == "ddp_optimizer": + ddp_module = DistributedDataParallel._get_active_ddp_module() + if ddp_module: + with compile_lock: + from torch._dynamo.backends.distributed import DDPOptimizer + + ddp_optimizer = DDPOptimizer( + bucket_bytes_cap=ddp_module.bucket_bytes_cap, + backend_compile_fn=self._torchdynamo_orig_backend._torchdynamo_orig_backend, # type: ignore[attr-defined] + ) + assert hasattr( + self._torchdynamo_orig_backend, "_clone_with_backend" + ), ( + "DDPOptimizer only supports callback fns that know how to clone themselves." + ) + hijacked_callback = ( + self._torchdynamo_orig_backend._clone_with_backend( + ddp_optimizer.compile_fn, + ) + ) + return hijacked_callback( + frame, cache_entry, self.hooks, frame_state + ) + + with compile_lock, _disable_current_modes(): + # skip=1: skip this frame + result = self._torchdynamo_orig_backend( + frame, cache_entry, self.hooks, frame_state, skip=1 + ) + return result + + +def catch_errors_wrapper( + callback: ConvertFrameProtocol, hooks: Hooks +) -> CatchErrorsWrapper: + return CatchErrorsWrapper(callback, hooks) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/create_parameter_op.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/create_parameter_op.py new file mode 100644 index 0000000000000000000000000000000000000000..2a716865c3f48e4355af10b5ff3fcb2268d1ebc0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/create_parameter_op.py @@ -0,0 +1,69 @@ +import threading +from collections.abc import Generator +from contextlib import contextmanager +from typing import Any + +import torch + + +# See [Note: Metadata mutation in proxy tracing] for why sacrificial parameter mutates +# metadata during proxy tracing and we should remove the sacrificial parameter logic. +doc = """ +This is used when dynamo traces torch.nn.Parameter, which normally would not trace properly +with AOTAutograd. We instead create a placeholder torch.nn.Parameter before the graph, which +becomes a graph arg and has no storage backing it. At the point in the graph where the parameter +actually should be created we mutate this sacrificial placeholder into it. This allows gradients +to flow into the parameter as if it were an input to the graph (which is the only thing we are +allowed to compute gradients on). +""".strip() + + +class TracableCreateParameter(torch.autograd.Function): + @staticmethod + # pyrefly: ignore [bad-override] + def forward(ctx: Any, tensor: Any, placeholder: Any) -> torch.nn.Parameter: + assert not tensor.requires_grad + return placeholder.set_(tensor) + + @staticmethod + def backward(ctx: Any, *grad_outputs: torch.Tensor) -> tuple[None, torch.Tensor]: + grad = grad_outputs[0] + return None, grad # grad flows to placeholder + + +def tracable_create_parameter( + tensor: torch.Tensor, placeholder: torch.nn.Parameter +) -> torch.nn.Parameter: + with torch.set_grad_enabled(placeholder.requires_grad): + out = TracableCreateParameter.apply(tensor, placeholder) + return out + + +def new_parameter_placeholder( + size: tuple[int, ...], dtype: torch.dtype, device: torch.device, requires_grad: bool +) -> torch.nn.Parameter: + """Create a placeholder to be passed to the above functions""" + result = torch.nn.Parameter( + torch.empty(size, dtype=dtype, device=device), requires_grad=requires_grad + ) + # TODO(jansel): alloc followed by free is inefficient, need a way to allocate an unbacked tensor. + # Allocating a zero tensor would causes assert failures in autograd. + result.untyped_storage().resize_(0) + return result + + +_TLS = threading.local() + + +@contextmanager +def do_not_convert_to_tracable_parameter() -> Generator[bool, None, None]: + old_flag = getattr(_TLS, "convert_tracable_parameter", True) + _TLS.convert_tracable_parameter = False + try: + yield False + finally: + _TLS.convert_tracable_parameter = old_flag + + +def can_convert_to_tracable_parameter() -> bool: + return getattr(_TLS, "convert_tracable_parameter", True) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/current_scope_id.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/current_scope_id.py new file mode 100644 index 0000000000000000000000000000000000000000..74a5f4888c64629f3225118d91b52ba05e000ce0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/current_scope_id.py @@ -0,0 +1,42 @@ +""" +Provides thread-local scope identification for SubgraphTracer instances. + +This module implements a thread-safe mechanism for tracking nested tracing contexts, +which is essential when multiple SubgraphTracer instances are active. The scope ID +helps identify which tracer context is currently active when direct access to the +InstructionTranslator is difficult. + +Key components: +- Thread-local scope ID storage (_current_scope_id) +- Getter function (current_scope_id) to safely access the current scope +- Context manager (enter_new_scope) for managing nested scope transitions + +The scope ID increments when entering a new context and decrements when exiting, +allowing proper tracking of nested tracing operations across different threads. +""" + +import contextlib +import threading +from collections.abc import Generator + + +# Global variable to identify which SubgraphTracer we are in. +# It is sometimes difficult to find an InstructionTranslator to use. +_current_scope_id = threading.local() + + +def current_scope_id() -> int: + global _current_scope_id + if not hasattr(_current_scope_id, "value"): + _current_scope_id.value = 1 + return _current_scope_id.value + + +@contextlib.contextmanager +def enter_new_scope() -> Generator[None, None, None]: + global _current_scope_id + try: + _current_scope_id.value = current_scope_id() + 1 + yield + finally: + _current_scope_id.value = current_scope_id() - 1 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/dce_extra_outputs.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/dce_extra_outputs.py new file mode 100644 index 0000000000000000000000000000000000000000..0c9342902ab2ee22417e13b61c471bd001fca02f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/dce_extra_outputs.py @@ -0,0 +1,187 @@ +""" +DCE pass for unused extra outputs in HOP subgraphs. + +When enable_side_effects_with_extra_outputs is True, HOPs like invoke_subgraph, +checkpoint (tag_activation_checkpoint), and autograd.Function (autograd_function_apply) +return all intermediate tensors/symints as extra outputs to support side effects. +However, many of these extra outputs may not actually be used in the parent graph. + +Special handling for autograd_function_apply: +- The forward subgraph MUST return (output, saved_values, ...) where indices 0 and 1 + are always required by the runtime +- Only indices 2+ (extra intermediates) can be removed by DCE + +This pass removes unused extra outputs by: +1. Identifying which outputs of HOP calls are actually used +2. Removing unused outputs from the subgraph's output node +3. Updating the HOP call to reflect the new output arity +4. Updating getitem indices to account for removed outputs +""" + +import collections +import operator + +import torch + + +# HOPs that may have extra outputs that can be DCE'd +_HOPS_WITH_EXTRA_OUTPUTS = { + torch.ops.higher_order.invoke_subgraph, + torch.ops.higher_order.tag_activation_checkpoint, + # torch.ops.higher_order.autograd_function_apply, +} + + +def dce_hop_extra_outputs(gm: torch.fx.GraphModule) -> bool: + """ + Remove unused extra outputs from HOP calls recursively. + + Processes graphs top-down: first DCE the current graph's HOP outputs, + then recursively process nested subgraphs. This ensures that when we + process a nested subgraph, the parent has already removed unused getitems, + so the nested subgraph sees the correct usage information. + + Args: + gm: The GraphModule to optimize + + Returns: + True if any modifications were made, False otherwise + """ + modified = False + + # Group HOP nodes by subgraph name + # Multiple invocations may share the same subgraph, so we need to check + # which indices are used across ALL invocations before removing any + subgraph_to_nodes: dict[str, list[torch.fx.Node]] = collections.defaultdict(list) + + for node in gm.graph.nodes: + if node.op == "call_function" and node.target in _HOPS_WITH_EXTRA_OUTPUTS: + subgraph_attr = node.args[0] + if ( + isinstance(subgraph_attr, torch.fx.Node) + and subgraph_attr.op == "get_attr" + ): + subgraph_name = subgraph_attr.target + assert isinstance(subgraph_name, str) + subgraph_to_nodes[subgraph_name].append(node) + + # STEP 1: DCE this graph's HOP outputs first (top-down) + for subgraph_name, hop_nodes in subgraph_to_nodes.items(): + if _dce_subgraph(gm, subgraph_name, hop_nodes): + modified = True + + if modified: + gm.graph.lint() + gm.recompile() + + # STEP 2: Recursively process nested subgraphs + # After we've removed unused getitems from this graph, nested subgraphs + # will see the correct usage information + for subgraph_name in subgraph_to_nodes: + subgraph = getattr(gm, subgraph_name) + if isinstance(subgraph, torch.fx.GraphModule): + if dce_hop_extra_outputs(subgraph): + modified = True + + return modified + + +def _dce_subgraph( + gm: torch.fx.GraphModule, subgraph_name: str, hop_nodes: list[torch.fx.Node] +) -> bool: + """ + DCE a single subgraph by removing unused output indices. + """ + subgraph = getattr(gm, subgraph_name) + + if not isinstance(subgraph, torch.fx.GraphModule): + return False + + # Collect used indices for THIS subgraph + used_indices: set[int] = set() + + # Check if this is the forward subgraph of autograd_function_apply + # For autograd_function_apply, the fwd subgraph must return (output, saved_values, ...) + # where indices 0 and 1 are ALWAYS required by the runtime + # is_autograd_fwd = any( + # node.target == torch.ops.higher_order.autograd_function_apply + # for node in hop_nodes + # ) + is_autograd_fwd = False + + for hop_node in hop_nodes: + for user in list(hop_node.users): + if user.op == "call_function" and user.target == operator.getitem: + if len(list(user.users)) > 0: + idx = user.args[1] + assert isinstance(idx, int) + used_indices.add(idx) + + output_node = next(n for n in subgraph.graph.nodes if n.op == "output") + old_outputs = list(output_node.args[0]) + + # For autograd_function_apply forward subgraph, indices 0 (output) and 1 (saved_values) + # are ALWAYS used by the runtime, even if not explicitly accessed via getitem + if is_autograd_fwd and len(old_outputs) >= 2: + used_indices.add(0) # output + used_indices.add(1) # saved_values + + # Nothing to DCE if all outputs are used or no outputs are used + if len(used_indices) >= len(old_outputs) or len(used_indices) == 0: + return False + + # Build mapping from old indices to new indices + old_to_new: dict[int, int] = {} + new_outputs = [] + new_idx = 0 + + for old_idx in range(len(old_outputs)): + if old_idx in used_indices: + old_to_new[old_idx] = new_idx + new_outputs.append(old_outputs[old_idx]) + new_idx += 1 + + # Update subgraph output node + # Create a new output node with the filtered outputs + with subgraph.graph.inserting_before(output_node): + new_output_node = subgraph.graph.output(tuple(new_outputs)) + output_node.replace_all_uses_with(new_output_node) + subgraph.graph.erase_node(output_node) + + for hop_node in hop_nodes: + # Update getitem nodes to use new indices + for user in list(hop_node.users): + if user.op == "call_function" and user.target == operator.getitem: + old_idx = user.args[1] + assert isinstance(old_idx, int) + if old_idx not in old_to_new: + assert len(list(user.users)) == 0 + gm.graph.erase_node(user) + continue + + new_idx = old_to_new[old_idx] + # Create a new getitem node with the new index + with gm.graph.inserting_before(user): + new_getitem = gm.graph.call_function( + operator.getitem, args=(user.args[0], new_idx) + ) + # Copy metadata from old node + new_getitem.meta = user.meta.copy() + user.replace_all_uses_with(new_getitem) + gm.graph.erase_node(user) + + # Update example_value metadata on hop_node + if "example_value" in hop_node.meta: + old_example = hop_node.meta["example_value"] + assert isinstance(old_example, (tuple, list)) + new_example = tuple( + old_example[old_idx] + for old_idx in range(len(old_outputs)) + if old_idx in used_indices + ) + hop_node.meta["example_value"] = new_example + + subgraph.graph.lint() + subgraph.recompile() + + return True diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/debug_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/debug_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..2acf517aba92f73aacc5b28602e1cb098902ba69 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/debug_utils.py @@ -0,0 +1,937 @@ +""" +Debug utilities for TorchDynamo compilation and execution. + +This module provides various debugging tools and utilities for TorchDynamo, including: + +- Minification support for reducing test cases while preserving bugs +- Input/output handling via InputReader and InputWriter for reproducible testing +- Accuracy checking between original and compiled models +- Neural network module string conversion via NNModuleToString +- Profiling tools and system information collection +- Buck build system integration for Meta-internal testing + +Key classes: +- InputReader/InputWriter: Handle serialization of model inputs/outputs +- NNModuleToString: Converts nn.Modules to string representations +- BuckTargetWriter: Manages Buck build system integration +""" + +from __future__ import annotations + +import atexit +import copy +import cProfile +import functools +import getpass +import inspect +import itertools +import logging +import os +import re +import subprocess +import sys +import tempfile +import textwrap +from collections import Counter +from importlib import import_module +from typing import Any, Optional, TYPE_CHECKING, TypeVar + +import torch +import torch._prims_common as utils +import torch._subclasses.meta_utils +from torch import Tensor +from torch._dynamo.testing import rand_strided +from torch._inductor.cpp_builder import normalize_path_separator +from torch._prims_common import is_float_dtype +from torch.multiprocessing.reductions import StorageWeakRef +from torch.utils._content_store import ContentStoreReader, ContentStoreWriter + +from . import config +from .utils import clone_inputs, get_debug_dir, warn_once + + +if TYPE_CHECKING: + from collections.abc import Callable, Sequence + + from torch.hub import tqdm + from torch.storage import UntypedStorage + + +log = logging.getLogger(__name__) + +T = TypeVar("T") + + +inductor_config = import_module("torch._inductor.config") +use_buck = inductor_config.is_fbcode() + +if use_buck: + import libfb.py.build_info + + +extra_deps = [] +extra_imports = "" +cur_target = "" +if use_buck: + extra_deps = [ + "//caffe2/torch/fb/sparsenn:sparsenn_operators_gpu", + "//caffe2/torch/fb/sparsenn:sparsenn_operators", + "//deeplearning/fbgemm/fbgemm_gpu:sparse_ops_cpu", + "//deeplearning/fbgemm/fbgemm_gpu:sparse_ops", + ] + cur_target = libfb.py.build_info.BuildInfo.get_build_rule().replace("fbcode:", "//") # type: ignore[possibly-undefined] + extra_imports = "\n".join([f'torch.ops.load_library("{x}")' for x in extra_deps]) + + +BUCK_CMD_PREFIX = ["buck2", "run", "@mode/dev-nosan"] + + +class BuckTargetWriter: + def __init__(self, filename: str) -> None: + self.subdir, self.py_file = os.path.split(os.path.abspath(filename)) + self.target = self.py_file.replace(".py", "") + + # Get main_module path from fbcode + self.path = f"{self.subdir.replace('/', '.')}.{self.target}" + self.path = self.path[self.path.find("fbcode.") :] + self.path = self.path[7:] + + # Get cmd line path + tmp = self.subdir + tmp = tmp[tmp.find("fbcode/") :][7:] + self.cmd_line_path = f"//{tmp}:{self.target}" + + def build(self) -> str: + extra_cpp_deps = "\n".join([f' "{x}",' for x in extra_deps]) + return textwrap.dedent( + f""" +load("@fbcode_macros//build_defs:python_binary.bzl", "python_binary") + +python_binary( + name="{self.target}", + srcs = ["{self.py_file}"], + compile = False, + deps = [ + "//caffe2:torch", + "//caffe2:libtorch", + "//caffe2/functorch:functorch", + "//triton:triton", + "{cur_target}", + ], + cpp_deps = [ +{extra_cpp_deps} + ], + main_module = "{self.path}", + par_style = "xar", +) +""" + ) + + def write(self, print_msg: bool = True) -> list[str]: + target_file = os.path.join(self.subdir, "TARGETS") + with open(target_file, "w") as fd: + fd.write(self.build()) + # log.warning("Wrote isolation TARGETS file at %s", target_file) + cmd_split = BUCK_CMD_PREFIX + [self.cmd_line_path] + if print_msg: + log.warning( + "Found an example that reproduces the error. Run this cmd to repro - %s", + " ".join(cmd_split), + ) + return cmd_split + + +def minifier_dir() -> str: + path = os.path.join(get_debug_dir(), "minifier") + if path is None: + path = f"{tempfile.gettempdir()}/minifier_{getpass.getuser()}" + if not os.path.exists(path): + os.makedirs(path, exist_ok=True) + return path + + +MAX_CONSTANT_NUMEL_INLINE = 4 + + +class NNModuleToString: + safe_reprs = [ + torch.nn.Linear, + torch.nn.Conv1d, + torch.nn.Conv2d, + torch.nn.Conv3d, + torch.nn.BatchNorm1d, + torch.nn.BatchNorm2d, + torch.nn.BatchNorm3d, + torch.nn.LayerNorm, + torch.nn.Dropout, + torch.nn.Softmax, + torch.nn.ReLU, + torch.nn.GELU, + torch.nn.Identity, + torch.nn.MaxPool2d, + torch.nn.Embedding, + torch.nn.Tanh, + torch.nn.ConvTranspose1d, + torch.nn.GLU, + torch.nn.LSTM, + torch.nn.Flatten, + torch.nn.AdaptiveAvgPool2d, + ] + + @staticmethod + def can_convert_to_string(gm: torch.fx.GraphModule) -> bool: + cant_convert = set() + for _, module in gm.named_children(): + if type(module) not in NNModuleToString.safe_reprs: + cant_convert.add(module) + + if len(cant_convert) > 0: + log.warning("We have not tested reprs of some modules - %s", cant_convert) + # TODO - Assuming that all modules can be safely repr'd. Check if that assumption is correct. + return True + + @staticmethod + def convert(gm: torch.fx.GraphModule) -> str: + from torch.nn.modules.module import _addindent + + tab = " " * 4 + + model_str = textwrap.dedent( + """ + from torch.nn import * + class Repro(torch.nn.Module): + def __init__(self) -> None: + super().__init__() + """ + ) + + for module_name, module in gm.named_children(): + module_str = f"{module.__repr__()}" + # module should be a core torch.nn.Module, so all parameters + # should be on the same device. + example_param = next(module.parameters(), None) + if example_param is not None and example_param.is_cuda: + module_str = f"{module_str}.cuda()" + model_str += f"{tab * 2}self.{module_name} = {module_str}\n" + + for buffer_name, buffer in gm._buffers.items(): + if buffer is None: + continue + # Serialize full data for small buffers + if buffer.numel() <= MAX_CONSTANT_NUMEL_INLINE: + from torch._tensor_str import PRINT_OPTS + + assert PRINT_OPTS.threshold >= MAX_CONSTANT_NUMEL_INLINE + tensor_str = repr(buffer) + elif torch.is_floating_point(buffer): + tensor_str = f"torch.randn({list(buffer.shape)}, dtype={buffer.dtype})" + else: + tensor_str = ( + f"torch.randint(1, size={list(buffer.shape)}, dtype={buffer.dtype})" + ) + if buffer.is_cuda: + tensor_str = f"{tensor_str}.cuda()" + model_str += ( + f"{tab * 2}self.register_buffer('{buffer_name}', {tensor_str})\n" + ) + + for param_name, param in gm._parameters.items(): + if param is None: + continue + maybe_device = "" + if param.is_cuda: + maybe_device = ', device="cuda"' + tensor_str = f"torch.nn.Parameter(torch.randn({list(param.shape)}, dtype={param.dtype}{maybe_device}))" + model_str += f"{tab * 2}self.{param_name} = {tensor_str}\n" + + # TODO - Keep this code for now. But, I don't think we will need this. + # attrs = dir(gm) + # for attr in attrs: + # if "_tensor_constant" in attr: + # val = getattr(gm, attr) + # model_str += f" {attr} = {val!r}\n" + + model_str += f"{_addindent(gm.code, 4)}\n" + return model_str + + +@functools.cache # subprocess is expensive +def _cuda_system_info_comment() -> str: + if not torch.cuda.is_available(): + return "# torch.cuda.is_available()==False, no GPU info collected\n" + + model_str = "# CUDA Info: \n" + try: + cuda_version_out = subprocess.check_output(["nvcc", "--version"]) + cuda_version_lines = cuda_version_out.decode().split("\n") + comment = "".join([f"# {s} \n" for s in cuda_version_lines if s != ""]) + model_str += f"{comment}\n" + except (FileNotFoundError, subprocess.CalledProcessError): + model_str += "# nvcc not found\n" + + gpu_names = Counter( + torch.cuda.get_device_name(i) for i in range(torch.cuda.device_count()) + ) + + model_str += "# GPU Hardware Info: \n" + for name, count in gpu_names.items(): + model_str += f"# {name} : {count} \n" + model_str += "\n" + return model_str + + +def generate_env_vars_string(*, stable_output: bool = False) -> str: + """ + Generate a string configuration for environment variables related to Dynamo, Inductor, and Triton. + """ + if stable_output: + return "# env var omitted due to stable_output=True" + + allow_list = ["TORCH", "DYNAMO", "INDUCTOR", "TRITON"] + skip_list = ["TRITON_LIBDEVICE_PATH", "TRITON_PTXAS_PATH", "TRITON_LIBCUDA_PATH"] + + def filter(key: str) -> bool: + return any(string in key for string in allow_list) and key not in skip_list + + config_lines = [ + f"os.environ['{key}'] = '{value}'" + for key, value in os.environ.items() + if filter(key) + ] + config_string = "\n".join(config_lines) + return normalize_path_separator(f"""\ +import os +{config_string} + """) + + +def generate_config_string(*, stable_output: bool = False) -> str: + import torch._functorch.config + import torch._inductor.config + + if stable_output: + return "# config omitted due to stable_output=True" + + experimental_config = torch.fx.experimental._config.codegen_config() # type: ignore[attr-defined] + return f"""\ +import torch._dynamo.config +import torch._inductor.config +import torch._functorch.config +import torch.fx.experimental._config +{torch._dynamo.config.codegen_config()} +{torch._inductor.config.codegen_config()} +{torch._functorch.config.codegen_config()} +{experimental_config} +""" + + +def get_minifier_repro_path() -> str: + return os.path.join(minifier_dir(), "minifier_launcher.py") + + +def helper_for_dump_minify(contents: str) -> None: + minified_repro_path = get_minifier_repro_path() + log.warning("Writing minified repro to:\n%s", minified_repro_path) + + if use_buck: + BuckTargetWriter(minified_repro_path).write() + try: + with open(minified_repro_path, "w") as fd: + fd.write(contents) + + except OSError as e: + log.exception("") + raise NotImplementedError(f"Could not write to {minified_repro_path}") from e + + +class AccuracyError(Exception): + pass + + +def clone_inputs_retaining_gradness(example_inputs: Sequence[Any]) -> list[Any]: + """ + This clone inputs is different from utils clone_input. In case of minifier, + all the tensors are leaf tensors while creating a new graph. So, we set the + requires_grad field w/o checking the leafness of the tensor. + """ + cloned_inputs = clone_inputs(example_inputs) + for idx in range(len(example_inputs)): + if isinstance(cloned_inputs[idx], torch.Tensor): + cloned_inputs[idx].requires_grad_(example_inputs[idx].requires_grad) + return cloned_inputs # type: ignore[return-value] + + +def run_fwd_maybe_bwd( + gm: torch.fx.GraphModule, + args: Sequence[Any], + only_fwd: bool = False, + disable_clone: bool = False, +) -> Any: + """ + Runs a forward and possibly backward iteration for a given mod and args. + + When disable_clone is True, we will use args as-is without cloning. + This is higher fidelity but we may destroy the args in the process. + """ + from .testing import collect_results, reduce_to_scalar_loss, requires_bwd_pass + + gm = copy.deepcopy(gm) + if not disable_clone: + args = clone_inputs_retaining_gradness(args) + + if hasattr(gm, "zero_grad"): + gm.zero_grad(True) + + # TorchInductor returned callable expects lists. So, may need a boxed calling convention. + out = gm(args) if getattr(gm, "_boxed_call", False) else gm(*args) + + if only_fwd: + return out + if requires_bwd_pass(out): + loss = reduce_to_scalar_loss(out) + loss.backward() + return collect_results(gm, out, None, args) + + +def same_two_models( + gm: torch.fx.GraphModule, + opt_gm: torch.fx.GraphModule, + example_inputs: Sequence[Any], + only_fwd: bool = False, + *, + require_fp64: bool = False, + ignore_non_fp: bool = False, +) -> bool: + """ + Check two models have same accuracy. + + require_fp64: if True, raise an error if we unable to calculate the fp64 reference + ignore_non_fp: if True, do not compare outputs which are not floating point. This + is mostly useful for the minifier (which wants to avoid quantizing floating point + error into integer/boolean error) + """ + from .utils import same + + ref = run_fwd_maybe_bwd(gm, example_inputs, only_fwd) + + fp64_ref = None + if config.same_two_models_use_fp64: + try: + fp64_model, fp64_examples = cast_to_fp64( + copy.deepcopy(gm), clone_inputs_retaining_gradness(example_inputs) + ) + fp64_ref = run_fwd_maybe_bwd(fp64_model, fp64_examples, only_fwd) + except Exception: + if require_fp64: + raise RuntimeError( # noqa: B904 + "Could not generate fp64 outputs, workaround with torch._dynamo.config.same_two_models_use_fp64 = False" + ) + log.warning("Could not generate fp64 outputs") + + try: + res = run_fwd_maybe_bwd(opt_gm, example_inputs, only_fwd) + except Exception: + # This means that the minified graph is bad/exposes a different problem. + # As we are checking accuracy here, lets log the exception and return True. + log.exception( + "While minifying the program in accuracy minification mode, " + "ran into a runtime exception which is likely an unrelated issue." + " Skipping this graph." + ) + return True + + passing = same( + ref, + res, + fp64_ref, + tol=config.repro_tolerance, + equal_nan=True, + ignore_non_fp=ignore_non_fp, + ) + return passing + + +def cast_dtype_args_to_fp64(model: torch.fx.GraphModule) -> torch.fx.GraphModule: + for node in model.graph.nodes: + if ( + node.op == "call_function" + and node.target is torch.ops.prims.convert_element_type.default + ): + assert len(node.args) == 2 + if is_float_dtype(node.args[1]) and node.args[1] != torch.float64: + node.args = (node.args[0], torch.float64) + if node.op == "call_function": + dtype = node.kwargs.get("dtype") + if dtype is not None and is_float_dtype(dtype): + new_kwargs = dict(node.kwargs) + new_kwargs["dtype"] = torch.float64 + node.kwargs = new_kwargs + + model.graph.lint() + model.recompile() + return model + + +def cast_to( + dtype: torch.dtype, model: torch.fx.GraphModule, inputs: list[Any] +) -> tuple[torch.fx.GraphModule, list[Any]]: + from torch.utils._pytree import tree_map + + model = model.to(dtype) + if dtype == torch.float64: + # If casting to fp64 for accuracy comparison, we need to + # replace dtype arguments embedded in the graph with fp64 + model = cast_dtype_args_to_fp64(model) + + inputs = tree_map( + lambda x: x.to(dtype) + if isinstance(x, torch.Tensor) and x.is_floating_point() + else x, + inputs, + ) + return model, inputs + + +def cast_to_fp64( + model: torch.fx.GraphModule, inputs: list[Any] +) -> tuple[torch.fx.GraphModule, list[Any]]: + return cast_to(torch.float64, model, inputs) + + +def backend_accuracy_fails( + gm: torch.fx.GraphModule, + example_inputs: Sequence[Any], + compiler_fn: Callable[[torch.fx.GraphModule, list[Any]], torch.fx.GraphModule], + only_fwd: bool = False, + *, + require_fp64: bool = False, + ignore_non_fp: bool = False, +) -> bool: + try: + compiled_gm = compiler_fn( + copy.deepcopy(gm), clone_inputs_retaining_gradness(example_inputs) + ) + return not same_two_models( + gm, + compiled_gm, + example_inputs, + only_fwd, + require_fp64=require_fp64, + ignore_non_fp=ignore_non_fp, + ) + except Exception: + # This means that the minified graph is bad/exposes a different problem. + # As we are checking accuracy here, lets log the exception and return False. + log.exception( + "While minifying the program in accuracy minification mode, " + "ran into a runtime exception which is likely an unrelated issue." + " Skipping this graph" + ) + return False + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# REPRO SUPPORT CODE +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + + +# Helper functions for computing what the default values of tensor +# values should be. These all coincide with factory functions, e.g., torch.empty + + +def _stride_or_default( + stride: Optional[torch._prims_common.StrideType], + *, + shape: torch._prims_common.ShapeType, +) -> torch._prims_common.StrideType: + return stride if stride is not None else utils.make_contiguous_strides_for(shape) + + +def _mk_defaulter(d: T) -> Callable[[Optional[T]], T]: + return lambda x: x if x is not None else d + + +_dtype_or_default = _mk_defaulter(torch.float32) +_device_or_default = _mk_defaulter(torch.device("cpu")) +_storage_offset_or_default = _mk_defaulter(0) +_requires_grad_or_default = _mk_defaulter(False) +_is_leaf_or_default = _mk_defaulter(False) + + +class NopInputReader: + def __init__(self) -> None: + self.total = 0 + + def storage( + self, + storage_hash: Optional[str], + nbytes: int, + *, + device: Optional[torch._prims_common.DeviceLikeType] = None, + dtype_hint: Optional[torch.dtype] = None, + ) -> None: + self.total += 1 + + def tensor(self, *args: Any, **kwargs: Any) -> Optional[torch.Tensor]: + pass + + def symint(self, *args: Any, **kwargs: Any) -> Optional[int]: + pass + + +# TODO: Support bundling the entire repro into a zip file for ease of +# transferring around +class InputReader: + def __init__(self, save_dir: Optional[str] = None, *, pbar: Optional[tqdm] = None): + # If None, we will generate random data instead. It's important + # to natively support this use case as it will allow people to + # share repros without including the real data, if the problem + # reproduces even on random data. + if save_dir is None: + log.warning("no save_dir specified, will generate random data") + self.store = ContentStoreReader(save_dir) if save_dir is not None else None + self.args: list[Any] = [] + self.pbar = pbar + + def storage( + self, + storage_hash: Optional[str], + nbytes: int, + *, + device: Optional[torch._prims_common.DeviceLikeType] = None, + dtype_hint: Optional[torch.dtype] = None, + ) -> UntypedStorage: + if self.pbar is not None: + self.pbar.update(1) + device = _device_or_default(device) # type: ignore[arg-type] + dtype_hint = _dtype_or_default(dtype_hint) + if self.store is not None and storage_hash is not None: + try: + storage = self.store.read_storage(storage_hash) + except FileNotFoundError: + pass + else: + if device != storage.device: + log.warning("device mismatch: %s != %s", device, storage.device) + # TODO: transfer it to the right device? But failing this + # way would be very mysterious! Would have been better + # not to store device in the serialized format... + return storage + warn_once(f"could not load {storage_hash}, generating random data instead") + shape = (nbytes // dtype_hint.itemsize,) + stride = _stride_or_default(None, shape=shape) + return rand_strided(shape, stride, dtype_hint, device).untyped_storage() + + def tensor( + self, + storage: UntypedStorage, + shape: torch._prims_common.ShapeType, + stride: Optional[torch._prims_common.StrideType] = None, + *, + storage_offset: Optional[int] = None, + dtype: Optional[torch.dtype] = None, + requires_grad: Optional[bool] = None, + is_leaf: Optional[bool] = None, + **metadata: Any, + ) -> torch.Tensor: + stride = _stride_or_default(stride, shape=shape) + storage_offset = _storage_offset_or_default(storage_offset) + dtype = _dtype_or_default(dtype) + is_leaf = _is_leaf_or_default(is_leaf) + requires_grad = _requires_grad_or_default(requires_grad) + t = torch.tensor( + [], dtype=dtype, device=storage.device, requires_grad=requires_grad + ) + with torch.no_grad(): + t.set_(storage, storage_offset, shape, stride) + if not is_leaf: + # Fake up some autograd history in a very naughty way + with torch.enable_grad(): + t = t.clone(memory_format=torch.preserve_format) + with torch.no_grad(): + t.set_(storage, storage_offset, shape, stride) + assert torch._subclasses.meta_utils.safe_is_leaf(t) == is_leaf + torch._utils.set_tensor_metadata(t, metadata) + self.args.append(t) + return t # for BC + + def symint(self, val: Any) -> Any: + self.args.append(val) + return val # for BC + + +# Here is our writer strategy: +# 1. We will stream all of the inputs to disk +# 2. You can now deterministically randomize the inputs, or reload +# the inputs from disk +# 3. You can YOLO run the script without the inputs, in which case +# we'll fill the inputs with random data and pray. This is the +# legacy behavior, but it's also useful if you want to find out +# if we're so broken even random inputs trigger it +# 4. We could offer an in process "check if the randomized thing +# works too" but this is delicate so we don't do it + + +class InputWriter: + def __init__(self, save_dir: Optional[str], *, stable_hash: bool = False) -> None: + self._lines: list[str] = [] + # TODO: consider ensuring tensor and storage counters line up? + self.storage_counter = itertools.count() + self.save_dir = save_dir + self.store = ( + ContentStoreWriter(save_dir, stable_hash=stable_hash) + if save_dir is not None + else None + ) + self.seen_storages: dict[StorageWeakRef, str] = {} + + def lines(self) -> list[str]: + r = [ + "def load_args(reader):", + ] + r.extend(f" {l}" for l in self._lines) + # In case we need to change the internal format of load_args + # in an FC-breaking way + r.append("load_args._version = 0") + return r + + # Storages are untyped, but we need to initialize them with data if + # we don't have the real data, so we give a hint saying what kind + # of initialization may be appropriate + # + # If we had a FakeTensor, device_hint tells us what device should be + def storage( + self, + untyped_storage: UntypedStorage, + *, + device_hint: Optional[torch._prims_common.DeviceLikeType] = None, + dtype_hint: Optional[torch.dtype] = None, + ) -> str: + ws = StorageWeakRef(untyped_storage) + v = self.seen_storages.get(ws) + if v is not None: + return v + v = f"buf{next(self.storage_counter)}" + maybe_dtype_hint = "" + if _dtype_or_default(None) != _dtype_or_default(dtype_hint): + maybe_dtype_hint = f", dtype_hint={dtype_hint!r}" + # TODO: being optional on device is kind of pointless as the default + # is CPU but most repros we care about are CUDA + maybe_device = "" + device = untyped_storage.device + if device.type == "meta": + assert device_hint is not None + device = device_hint # type: ignore[assignment] + if _device_or_default(None) != device: + maybe_device = f", device={device!r}" + nbytes = untyped_storage.nbytes() + storage_hash = None + if self.store is not None and untyped_storage.device.type != "meta": + storage_hash = self.store.write_storage(untyped_storage) + self._lines.append( + f"{v} = reader.storage({storage_hash!r}, {nbytes!r}{maybe_device}{maybe_dtype_hint})" + ) + self.seen_storages[ws] = v + return v + + def tensor(self, name: str, t: torch.Tensor) -> None: + from torch.fx.experimental.symbolic_shapes import statically_known_true, sym_eq + + storage = self.storage( + t.untyped_storage(), dtype_hint=t.dtype, device_hint=t.device + ) + args = [] + # NB: this is positional, must come first + if not statically_known_true( + sym_eq(_stride_or_default(None, shape=t.shape), t.stride()) + ): + args.append(str(tuple(t.stride()))) + if _dtype_or_default(None) != t.dtype: + args.append(f"dtype={t.dtype!r}") + if not statically_known_true( + _storage_offset_or_default(None) == t.storage_offset() + ): + args.append(f"storage_offset={t.storage_offset()!r}") + tensor_metadata = torch._utils.get_tensor_metadata(t) + if tensor_metadata: + args.extend(f"{k}={v!r}" for k, v in tensor_metadata.items()) + if _requires_grad_or_default(None) != t.requires_grad: + args.append(f"requires_grad={t.requires_grad!r}") + is_leaf = torch._subclasses.meta_utils.safe_is_leaf(t) + if _is_leaf_or_default(None) != is_leaf: + args.append(f"is_leaf={is_leaf!r}") + self._lines.append( + "reader.tensor(" + + ", ".join([storage, str(tuple(t.shape)), *args]) + + f") # {name}" + ) + + def unsupported(self, name: str, arg: Any) -> None: + # NB: Try hard not to /print/ a tensor, that will be very slow + self._lines.append(f"# {name} was unsupported type for dumping: {type(arg)}") + # Best effort dump as much useful stuff we can lol, in case you want + # to repair the repro + if isinstance(arg, (list, tuple)): + self._lines.append('"""') + for i, a in enumerate(arg): + name_i = f"{name}[{i}]" + if isinstance(a, torch.Tensor): + self.tensor(name_i, a) + elif isinstance(a, (int, torch.SymInt)): + self.symint(name_i, a) + else: + self.unsupported(name_i, a) + self._lines.append('"""') + + # write out that the arg was filtered out as it is constant + def const(self, name: str) -> None: + self._lines.append( + f"reader.const({name!r}) # {name}, filtered out during compilation" + ) + + # TODO: this doesn't actually symint atm + def symint(self, name: str, val: Any) -> None: + if isinstance(val, torch.SymInt): + val = val.node.hint + self._lines.append(f"reader.symint({val!r}) # {name}") + + +def aot_graph_input_parser( + func: Callable[[list[Tensor]], list[Tensor]], + device: str = "cuda", + sym_shapes: Optional[dict[str, int]] = None, + default_sym_shape: Optional[int] = None, +) -> dict[str, Any]: + """ + Takes in a function which has been printed with print_readable() and constructs kwargs to run it. + + Handles Tensor inputs, Symints, and a graph module which might have tensor constants. + + Consider a function `forward` defined as follows: + + def forward(self, primals_1: "f32[1001, 6]", primals_2: "f32[s0]", primals_3: "Sym(s0)",): + _tensor_constant0: "i64[4190]" = self._tensor_constant0 + # Further implementation + + kwargs = aot_graph_input_parser(forward) + forward(**kwargs) + """ + + from torch.utils._dtype_abbrs import dtype_abbrs + + dtype_map: dict[str, torch.dtype] = { + value: key for key, value in dtype_abbrs.items() + } + dtype_pattern: str = "|".join(dtype_abbrs.values()) + + # Extracting the source code from the function + source = inspect.getsource(func) + + # Regular expressions + tensor_assignment_regex = rf"(_tensor_constant\d+): \"({dtype_pattern})\[\s*(.*?)\s*\]\" = self\.(_tensor_constant\d+)" + tensor_regex = rf"({dtype_pattern})\[\s*(.*?)\s*\]" + sym_shape_regex = r"Sym\((s\d+)\)" + + class TensorContainer: + "Container for tensors as attributes" + + # Dictionary for tensors from annotations + kwargs: dict[str, Any] = {} + + sym_shapes_dict: dict[str, int] = sym_shapes or {} + + def get_sym_int(symint: str) -> int: + torch._check( + symint in sym_shapes_dict or default_sym_shape is not None, + lambda: f"{symint} not in symbolic_shapes and default sym shape not passed in", + ) + return sym_shapes_dict.get(symint, default_sym_shape) # type: ignore[return-value] + + def gen_tensor(shape: torch._prims_common.ShapeType, dtype: torch.dtype) -> Tensor: + # Resolve symbolic shapes to concrete values + resolved_shape = [] + dynamic_dims = [] + for i, dim in enumerate(shape): + dim = dim.strip() # type: ignore[attr-defined] + if "s" in dim: + s = get_sym_int(dim) + resolved_shape.append(s) + dynamic_dims.append(i) + else: + if dim: + resolved_shape.append(int(dim)) + + constructor = torch.randn if dtype.is_floating_point else torch.zeros + out = constructor(resolved_shape, dtype=dtype, device=device) # type: ignore[call-arg] + for d in dynamic_dims: + torch._dynamo.mark_dynamic(out, d) + return out + + # Parse function annotations for tensor generation + annotations = func.__annotations__ + for param, annotation in annotations.items(): + # Skip 'return' annotation + if param == "return": + continue + + match = re.search(tensor_regex, annotation) + if match: + data_type, shape_str = match.groups() + shape = tuple(shape_str.split(",")) + dtype = dtype_map[data_type] + # pyrefly: ignore [bad-argument-type] + kwargs[param] = gen_tensor(shape, dtype) + + match = re.search(sym_shape_regex, annotation) + if match: + kwargs[param] = get_sym_int(match.group(1)) + + if "self" in inspect.signature(func).parameters: + container = TensorContainer() + kwargs["self"] = container + for match in re.finditer(tensor_assignment_regex, source): + attr_name, data_type, shape_str, _ = match.groups() + shape = tuple(shape_str.split(",")) + dtype = dtype_map[data_type] + # pyrefly: ignore [bad-argument-type] + setattr(container, attr_name, gen_tensor(shape, dtype)) + + return kwargs + + +def profile_to_file(filename: str) -> Callable[[T], T]: + """ + Decorator to cProfile a given function and save the result to disk on process exit. + + Args: + filename: filename to save profile to + """ + prof = cProfile.Profile() + filename = os.path.abspath(os.path.expanduser(filename)) + + def decorator(fn: Any) -> Any: + @functools.wraps(fn) + def wrapper(*args: Any, **kwargs: Any) -> Any: + prof.enable() + try: + return fn(*args, **kwargs) + finally: + prof.disable() + + return wrapper + + def save_it() -> None: + prof.dump_stats(filename) + sys.stderr.write( + textwrap.dedent( + f"""\ + Wrote profile to {filename}, view with: + + snakeviz {filename} + + """ + ) + ) + + atexit.register(save_it) + return decorator diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/decorators.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..3a9718b045cb67d6900fa966504642a45be90eb1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/decorators.py @@ -0,0 +1,1051 @@ +""" +This module provides decorators and utilities for controlling TorchDynamo's behavior during compilation. +""" + +import functools +import inspect +import weakref +from collections.abc import Callable +from dataclasses import dataclass +from types import TracebackType +from typing import Any, Optional, overload, TYPE_CHECKING, TypeVar, Union +from typing_extensions import ParamSpec + +import torch +from torch.compiler import is_compiling +from torch.utils._contextlib import _DecoratorContextManager +from torch.utils._python_dispatch import is_traceable_wrapper_subclass + +from . import trace_rules, variables +from .comptime import comptime +from .eval_frame import ( + _set_stance, + DisableContext, + DynamoStance, + innermost_fn, + RunOnlyContext, + skip_code, +) +from .exc import IncorrectUsage +from .external_utils import ( + get_nonrecursive_disable_wrapper, + wrap_dunder_call_ctx_manager, +) +from .utils import _get_error_on_graph_break, _set_error_on_graph_break, is_function + + +if TYPE_CHECKING: + from types import FunctionType + + from torch._C._dynamo.eval_frame import ( # noqa: F401 + reset_code, + set_eval_frame, + set_guard_complete_hook, + set_guard_error_hook, + unsupported, + ) + + from .variables import VariableTracker +else: + for name in dir(torch._C._dynamo.eval_frame): + if name.startswith("__"): + continue + globals()[name] = getattr(torch._C._dynamo.eval_frame, name) + + +_P = ParamSpec("_P") +_R = TypeVar("_R") +FuncType = Callable[..., Any] +F = TypeVar("F", bound=FuncType) + + +def run(fn: Optional[Callable[_P, _R]] = None) -> Any: + """Don't do any dynamic compiles, just use prior optimizations""" + if fn is not None: + fn = innermost_fn(fn) + assert callable(fn) + return RunOnlyContext()(fn) + return RunOnlyContext() + + +def disable(fn=None, recursive=True, *, reason=None, wrapping=True): # type: ignore[no-untyped-def] + """ + Decorator to disable TorchDynamo + + If recursive=True, Dynamo is completely skipped on the decorated function + frame as well as the recursively invoked functions. + + If recursive=False, Dynamo skips frames associated with the function code, + but still process recursively invoked frames. + + If reason is provided, it will be printed when Dynamo attempts to trace the disabled function. + """ + if recursive: + if fn is not None: + fn = innermost_fn(fn) + assert callable(fn) + return DisableContext(msg=reason, wrapping=wrapping)(fn) + return DisableContext(msg=reason, wrapping=wrapping) + else: + + def wrap(fn: Callable[_P, _R]) -> Callable[_P, _R]: + fn = innermost_fn(fn) + assert callable(fn) + + nonrecursive_disable_wrapper = get_nonrecursive_disable_wrapper(fn) + nonrecursive_disable_wrapper._torchdynamo_disable = True # type: ignore[attr-defined] + nonrecursive_disable_wrapper._torchdynamo_disable_msg = reason # type: ignore[attr-defined] + nonrecursive_disable_wrapper._torchdynamo_orig_callable = fn # type: ignore[attr-defined] + nonrecursive_disable_wrapper._torchdynamo_disable_recursive = False # type: ignore[attr-defined] + # pyrefly: ignore [bad-return] + return nonrecursive_disable_wrapper + + if fn is None: + return wrap + return wrap(fn) + + +_nonrecursive_disable_wrapper_code = disable(lambda: None, recursive=False).__code__ # type: ignore[attr-defined] +skip_code(_nonrecursive_disable_wrapper_code) + + +def skip(fn: Optional[Callable[_P, _R]] = None) -> Callable[..., Any]: + """ + Skip frames associated with the function code, but still process recursively + invoked frames + """ + if fn is None: + return skip + fn = innermost_fn(fn) + assert callable(fn) + skip_code(fn.__code__) + fn._torchdynamo_disable = True # type: ignore[attr-defined] + return fn + + +class set_stance(_DecoratorContextManager): + """ + Decorator, context manager, function to set the current stance of the compiler. + + Stances documented in corresponding function in torch/compiler/__init__.py + """ + + _dynamo_forbidden = True + + def __init__( + self, + stance: str = "default", + *, + skip_guard_eval_unsafe: bool = False, + force_backend: Union[str, Callable[..., Any], None] = None, + ) -> None: + if force_backend is not None and stance != "default": + raise RuntimeError("non-default stance cannot have force_backend set") + + self.stance = DynamoStance(stance, skip_guard_eval_unsafe, force_backend) + self.prev = _set_stance(self.stance) + + def __call__(self, fn: F) -> F: + _set_stance(self.prev) + wrapper = super().__call__(fn) + # forbid wrapper in graph + wrapper._dynamo_forbidden = True # type: ignore[attr-defined] + return wrapper + + def __enter__(self) -> None: + _set_stance(self.stance) + + def __exit__( + self, + exc_type: Optional[type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType], + ) -> None: + _set_stance(self.prev) + + def clone(self) -> "set_stance": + return self.__class__(self.stance.stance, force_backend=self.stance.backend) + + +def assume_constant_result(fn): # type: ignore[no-untyped-def] + fn._dynamo_marked_constant = True # type: ignore[attr-defined] + return fn + + +def allow_in_graph(fn): # type: ignore[no-untyped-def] + """ + Tells the compiler frontend (Dynamo) to skip symbolic introspection of the function + and instead directly write it to the graph when encountered. + + See :func:`torch.compiler.allow_in_graph`'s docstring for the full documentation + + WARNING: this API can be a footgun, please read the documentation carefully. + """ + if isinstance(fn, (list, tuple)): + return [allow_in_graph(x) for x in fn] + assert callable(fn), "allow_in_graph expects a callable" + if trace_rules.lookup_callable(fn) != variables.TorchInGraphFunctionVariable: + fn_id = id(fn) + trace_rules._disallowed_callable_ids.remove(fn_id) + trace_rules._allowed_callable_ids.add(fn_id) + + # Avoid id reuse which creates subtle bugs. + def deregister() -> None: + trace_rules._allowed_callable_ids.remove(fn_id) + + weakref.finalize(fn, deregister) + return fn + + +def nonstrict_trace(traceable_fn: Callable[_P, _R]) -> Callable[_P, _R]: + # Like `allow_in_graph`, but with the following enhancements/differences: + # + # 1. Supports user-defined class as inputs, as long as the class has been + # registered with pytree. + # 2. Reads to global/captured tensors forces the underlying graph to treat + # those tensors as constant, and we _assume_ they will not be updated. This + # is similar to FX tracing. + # 3. In the resulting Dynamo graph, the call to a `nonstrict_trace`-ed function + # will be represented as a call to `torch._higher_order_ops.flat_apply`, + # which takes in the `nonstrict_trace`-ed function and pytree-flattened + # inputs. + # 4. Only the returned function is traceable, and the original function will + # not be. Moreover, `nonstrict_trace` can be used inside a `torch.compile` + # region. + # + # NOTE: like `allow_in_graph`, aliasing information is neither preserved + # between inputs themselves, nor between inputs and outputs. + assert callable(traceable_fn), "nonstrict_trace expects a callable" + + @functools.wraps(traceable_fn) + def wrapped(*args: _P.args, **kwargs: _P.kwargs) -> _R: + return traceable_fn(*args, **kwargs) + + wrapped_id = id(wrapped) + + # This line allows us to reuse much of the `allow_in_graph` impl. + trace_rules._allowed_callable_ids.add(wrapped_id) + + # This line allows us to diverge the impl from `allow_in_graph`. + trace_rules._nonstrict_trace_callable_ids.add(wrapped_id) + + # Avoid id reuse which creates subtle bugs. + def deregister() -> None: + trace_rules._allowed_callable_ids.remove(wrapped_id) + trace_rules._nonstrict_trace_callable_ids.remove(wrapped_id) + + weakref.finalize(wrapped, deregister) + + return wrapped + + +def _disallow_in_graph_helper(throw_if_not_allowed: bool) -> Callable[..., Any]: + def inner(fn: Any) -> Any: + if isinstance(fn, (list, tuple)): + return [disallow_in_graph(x) for x in fn] + assert callable(fn), "disallow_in_graph expects a callable" + if ( + throw_if_not_allowed + and trace_rules.lookup_callable(fn) + != variables.TorchInGraphFunctionVariable + and trace_rules.lookup(fn) != variables.TorchInGraphFunctionVariable + ): + raise IncorrectUsage( + "disallow_in_graph is expected to be used on an already allowed callable (like torch.* ops). " + "Allowed callables means callables that TorchDynamo puts as-is in the extracted graph." + ) + trace_rules._allowed_callable_ids.remove(id(fn)) + trace_rules._nonstrict_trace_callable_ids.remove(id(fn)) + trace_rules._disallowed_callable_ids.add(id(fn)) + return fn + + return inner + + +def disallow_in_graph(fn: Callable[..., Any]) -> Any: + """ + Customize which functions TorchDynamo will exclude in the generated + graph and force a graph break on. + :: + + torch._dynamo.disallow_in_graph(torch.sub) + + + @torch._dynamo.optimize(...) + def fn(a): + x = torch.add(x, 1) + x = torch.sub(x, 1) + x = torch.add(x, 1) + return x + + + fn(...) + + Will break the graph on `torch.sub`, and give two graphs each with a + single `torch.add()` op. + """ + return _disallow_in_graph_helper(throw_if_not_allowed=True)(fn) + + +@_disallow_in_graph_helper(throw_if_not_allowed=False) +def graph_break(msg: str = "") -> None: + """Force a graph break""" + + +# NOTE: primarily used for internal debugging purposes! +@_disallow_in_graph_helper(throw_if_not_allowed=False) +def skip_frame(msg: str = "") -> None: + """Force a skipped frame""" + + +@_disallow_in_graph_helper(throw_if_not_allowed=False) +def step_unsupported(msg: str = "") -> None: + """Force a step unsupported graph break, which results in compiling + the traced FX graph so far, then skipping the rest of the frame. + In order to get expected behavior, there should be at least 2 ops + and a part of the code not contained in any try/with blocks.""" + + +def forbid_in_graph(fn: Any) -> Any: + """ + Customize which functions TorchDynamo will assert are not present while tracing. + + If you want a graph break on this function instead, use disallow_in_graph. + TODO(voz): We now have allow_in_graph, disallow_in_graph, forbid_in_graph - some more robust + documentation would not be amiss. + """ + if isinstance(fn, (list, tuple)): + return [forbid_in_graph(x) for x in fn] + assert callable(fn), "forbid_in_graph applies only to callables" + # pyrefly: ignore [missing-attribute] + fn._dynamo_forbidden = True + return fn + + +def substitute_in_graph( + original_fn: Callable[_P, _R], + *, + can_constant_fold_through: bool = False, + skip_signature_check: bool = False, + # type that is embedded in the Python interpreter + is_embedded_type: bool = False, # internal use only +) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]: + """ + Register a polyfill handler for a function, usually a C function from the C extension, to be + used in place of the original function when inlining the original function in the graph. + + .. note:: + + The polyfill handler is only used when inlining the original function. It is not used when + the original function is called directly. In the eager mode, the decorated function calls + the performant C function rather than the polyfill handler. + + The polyfill handler is a function that will be called in place of the original function when + inlining the original function. The polyfill handler should have the same signature and the same + behavior as the original function. + + Args: + original_fn (callable): The original function, usually a C function, to register a polyfill + handler for. + can_constant_fold_through (bool, optional): Whether the polyfill handler can be constant + folded through. That is, if the polyfill handler is a pure function and its arguments + are constant, the result of the polyfill handler can be constant folded during the + compilation. Defaults to ``False``. + skip_signature_check (bool, optional): Whether to skip the signature check between the + original function and the polyfill handler. Defaults to ``False``. + + Returns: + A decorator that registers the polyfill handler for the original function. + + Example:: + + >>> # xdoctest: +SKIP("conflict with the tests: duplicate polyfill handlers") + >>> import operator + >>> operator.indexOf([1, 2, 3, 4, 5], 3) + 2 + >>> torch.compile(operator.indexOf, fullgraph=True)([1, 2, 3, 4, 5], 3) + Traceback (most recent call last): + ... + torch._dynamo.exc.Unsupported: ... + + >>> @torch.compiler.substitute_in_graph(operator.indexOf) + ... def indexOf(a, b, /): + ... for i, item in enumerate(a): + ... if item is b or item == b: + ... return i + ... raise ValueError("sequence.index(x): x not in sequence") + >>> + >>> torch.compile(operator.indexOf, fullgraph=True)([1, 2, 3, 4, 5], 3) + 2 + """ + if not is_function(original_fn) and not ( + is_embedded_type and inspect.isclass(original_fn) + ): + raise TypeError( + f"substitute_in_graph expects a function but got {type(original_fn)!r}" + ) + if is_embedded_type: + if not inspect.isclass(original_fn): + raise TypeError( + f"substitute_in_graph expects a class but got {type(original_fn)!r}" + ) + + from .variables.builder import ITERTOOLS_POLYFILLED_TYPE_IDS, ITERTOOLS_TYPE_IDS + + if id(original_fn) in ITERTOOLS_TYPE_IDS: + ITERTOOLS_POLYFILLED_TYPE_IDS.add(id(original_fn)) + + def wrapper(traceable_fn: Callable[_P, _R]) -> Callable[_P, _R]: + if not is_function(traceable_fn): + raise TypeError( + f"@substitute_in_graph(...) expects a function but got {type(traceable_fn)!r}" + ) + + if not skip_signature_check: + try: + original_sig = inspect.signature(original_fn) + except ValueError: + pass + else: + traceable_sig = inspect.signature(traceable_fn) + + def sig_ident( + sig: inspect.Signature, + ) -> tuple[tuple[str, ...], set[str], dict[str, Any]]: + # Ignore annotations for parameters and return type + return ( + tuple( + p.name + for p in sig.parameters.values() + if ( + p.kind + not in { + p.KEYWORD_ONLY, + # the name of *args and **kwargs is not important + p.VAR_POSITIONAL, + p.VAR_KEYWORD, + } + ) + ), + { + p.name + for p in sig.parameters.values() + if p.kind == p.KEYWORD_ONLY + }, + { + p.name: p.default + for p in sig.parameters.values() + # the name of *args and **kwargs is not important + if p.kind not in {p.VAR_POSITIONAL, p.VAR_KEYWORD} + }, + ) + + wildcard_sig = inspect.signature(lambda *args, **kwargs: None) + + if ( + sig_ident(original_sig) != sig_ident(traceable_sig) + and sig_ident(original_sig) != sig_ident(wildcard_sig) + and sig_ident(traceable_sig) != sig_ident(wildcard_sig) + ): + raise TypeError( + f"Signature mismatch between {original_fn} and {traceable_fn}: " + f"{original_sig} != {traceable_sig}" + ) + + from torch._dynamo.guards import GuardBuilder + from torch._dynamo.trace_rules import ( + _polyfilled_function_ids, + get_torch_obj_rule_map, + ) + from torch._dynamo.variables import PolyfilledFunctionVariable + from torch._dynamo.variables.builder import VariableBuilder + + id_dispatch_map = VariableBuilder._id_dispatch() + if id(original_fn) in id_dispatch_map: + raise ValueError( + f"Duplicate dispatch rule for {original_fn}: " + "already registered in VariableBuilder's id dispatch map" + ) + + if id(original_fn) in _polyfilled_function_ids: + raise ValueError(f"Duplicate polyfilled object {original_fn}") + + rule_map: dict[Any, type[VariableTracker]] = get_torch_obj_rule_map() + if original_fn in rule_map: + raise ValueError( + f"Duplicate object {original_fn} with different rules: " + f"{PolyfilledFunctionVariable}, {rule_map[original_fn]}" + ) + + polyfill_handlers: dict[Callable[..., Any], FunctionType] + polyfill_handlers = PolyfilledFunctionVariable._get_polyfill_handlers() + if original_fn in polyfill_handlers: + raise ValueError( + f"Duplicate polyfill handlers for {original_fn}: " + f"already handled by {polyfill_handlers[original_fn]}" + ) + + # Need to wrap the function because we may cannot assign __torch_dynamo_polyfill__ to a + # C++ function. + @functools.wraps(traceable_fn) + def wrapped(*args: _P.args, **kwargs: _P.kwargs) -> _R: + return original_fn(*args, **kwargs) + + def dispatch_fn( + self: VariableBuilder, value: Callable[_P, _R] + ) -> PolyfilledFunctionVariable: + if inspect.isclass(value): + guard_type = GuardBuilder.CLASS_MATCH + elif inspect.ismodule(value): + guard_type = GuardBuilder.MODULE_MATCH + else: + guard_type = GuardBuilder.ID_MATCH + return PolyfilledFunctionVariable( + value, + source=self.source, + **self.install_guards(guard_type), + ) + + id_dispatch_map[id(original_fn)] = id_dispatch_map[id(wrapped)] = dispatch_fn + _polyfilled_function_ids.add(id(original_fn)) + _polyfilled_function_ids.add(id(wrapped)) + rule_map[original_fn] = rule_map[wrapped] = PolyfilledFunctionVariable + polyfill_handlers[original_fn] = polyfill_handlers[wrapped] = wrapped # type: ignore[assignment] + + wrapped.__torch_dynamo_original__ = original_fn # type: ignore[attr-defined] + wrapped.__torch_dynamo_polyfill__ = traceable_fn # type: ignore[attr-defined] + wrapped.__torch_dynamo_can_constant_fold_through__ = can_constant_fold_through # type: ignore[attr-defined] + + return wrapped # type: ignore[return-value] + + return wrapper + + +# Helper function to flatten a tensor subclass and apply a function to +# all inner tensors that match the outer dim. Used to reduce duplication +# across the various marking APIs. +def _apply_func_to_inner_tensors_of_same_dim( + func: Callable[..., Any], t: object, *args: Any, **kwargs: Any +) -> None: + assert is_traceable_wrapper_subclass(t) + + attrs, _ctx = t.__tensor_flatten__() + assert isinstance(t, torch.Tensor) + for attr in attrs: + inner = getattr(t, attr) + if inner.dim() == t.dim(): + func(inner, *args, **kwargs) + + +@dataclass(frozen=True) +class _DimRange: + """ + This represents an dimension of a tensor and the corresponding + min and max values it can take. Don't create this + class directly; instead, use :func:`mark_dynamic`. + """ + + dim: int + min: int + max: int + + +@forbid_in_graph +def mark_unbacked( + t: Any, + index: Union[int, list[Any], tuple[Any]], + hint_override: Optional[int] = None, + strict: bool = False, + specialize_on: Optional[list[Any]] = None, +) -> None: + """ + Mark a tensor as having an unbacked dimension. This changes the semantics of operations: + - The size of the specified dimension will always be reported as not equal to zero or one. + - Assertions on this index will be turned into runtime asserts. + - Attempting to get the real value of this dimension will raise an exception. + - In effect, this dimension is treated as data-dependent (its value is unknown). + + Args: + t (Any): The tensor to mark as having an unbacked dimension. + index (int or list/tuple of int): The dimension(s) to mark as unbacked. Can be a single integer or a list/tuple of integers. + hint_override (Optional[int], default=None): An optional integer to override the size hint for this dimension. + This is only used by the inductor backend for size hint queries, such as during autotuning. + strict (bool, default=False): If True, an error will be raised if the unbacked dimension is specialized. + By default (strict=False), specialization is allowed and will proceed without error. + specialize_on (Optional[list[Any]], default=None): A list of specialization criteria (e.g., lambdas) for this dimension. + If provided, Dynamo will generate specialized compiled regions for each criterion in addition to a generic trace. + """ + if torch.distributed.is_available() and isinstance( + t, torch.distributed.tensor.DTensor + ): + # apply on inner tensor sizes/strides + mark_unbacked(t._local_tensor, index) + else: + # You could have copied the mark_dynamic behavior but I'm not convinced + # it's what you want + assert not is_traceable_wrapper_subclass(t), "not implemented yet" + + if isinstance(index, int): + if strict: + if not hasattr(t, "_dynamo_strict_unbacked_indices"): + # pyrefly: ignore [missing-attribute] + t._dynamo_strict_unbacked_indices = set() + # pyrefly: ignore [missing-attribute] + t._dynamo_strict_unbacked_indices.add(index) + return + + if not hasattr(t, "_specialized_on"): + # pyrefly: ignore [missing-attribute] + t._specialize_on = {} + + if not hasattr(t, "_dynamo_unbacked_indices"): + # pyrefly: ignore [missing-attribute] + t._dynamo_unbacked_indices = set() + + if not hasattr(t, "_dynamo_hint_overrides"): + # pyrefly: ignore [missing-attribute] + t._dynamo_hint_overrides = {} + + if hint_override: + # pyrefly: ignore [missing-attribute] + t._dynamo_hint_overrides[index] = hint_override + + # FX tracers don't respect @forbid_in_graph and choke on the following error since it passes in proxies: + # TypeError: 'Attribute' object does not support item assignment + # pyrefly: ignore [missing-attribute] + if isinstance(t._specialize_on, dict): + # pyrefly: ignore [missing-attribute] + t._specialize_on[index] = specialize_on if specialize_on is not None else [] + + # pyrefly: ignore [missing-attribute] + t._dynamo_unbacked_indices.add(index) + return + + assert isinstance(index, (list, tuple)) + for i in index: + mark_unbacked(t, i) + + +@forbid_in_graph +def mark_dynamic( + t: Any, + index: Union[int, list[Any], tuple[Any]], + *, + hint_override: Optional[int] = None, + min: Optional[int] = None, + max: Optional[int] = None, + specialize_on: Optional[list[Any]] = None, +) -> None: + """ + Mark a tensor as having a dynamic dim and set corresponding min and max range for the dim. + + [Note - on the state of mark_dynamic] + + The behavior of having a dynamic dimension on a tensor is governed by a few factors: + + 1) torch._dynamo.config dynamic_shapes True or False. + a) dynamic_shapes=True - dynamic_shapes must be True for mark_dynamic to work. + a) dynamic_shapes=False - This config will raise an exception when used in conjunction with + mark_dynamic. We will eventually support this. + + 2) If the dimension is fully constrained - as in, it does not allow more than a single value + in both eager (torch.compile, torch._dynamo.optimize) mode and export mode (torch._dynamo.export), + we will raise an error + + 3) If the dimension is partially constrained - allowing at least 2 values but not the full unbounded + range of shapes, in eager we will pass it through, but export will raise an error. + + 4) Attempts to trace this function will explicitly raise. As such, all calls to mark_dynamic must be made + before torch.compile. + + 5) If hint_override is passed, the hint_override for the specified dimension will replace the provided value + from the first example input as the official size hint. + + 6) If specialize_on is passed in, we will perform a single generic Dynamo trace followed by + multiple specialized compilations in addition to a single generic compilation. NB: For now we only support + per dimension specialization, or in other words we do not generate a cross product of specializations. + At runtime, we will dispatch to a specialized compiled region if the input matches the specialization criteria. + + For example: + mark_dynamic(..., specialize_on=[ + lambda x: x == 8, + lambda x: x == 16 + ]) + + This approach results in one Dynamo trace and two backend compilations. When the input dimension equals 8 or 16 + at runtime, execution will be directed to the specialized compiled region. Performance measurements indicate + 2-8x speedups depending on the specific specialization and model architecture. + + """ + if is_traceable_wrapper_subclass(t): + # default behavior: mirror mark_dynamic() on all inner tensors with same dim as t + # TODO: Make this configurable via a supported public API + _apply_func_to_inner_tensors_of_same_dim( + mark_dynamic, t, index, min=min, max=max + ) + + if isinstance(index, int): + if not hasattr(t, "_dynamo_dynamic_indices"): + # pyrefly: ignore [missing-attribute] + t._dynamo_dynamic_indices = set() + # pyrefly: ignore [missing-attribute] + t._dynamo_dynamic_range = set() + # pyrefly: ignore [missing-attribute] + t._dynamo_hint_overrides = {} + + if not hasattr(t, "_specialize_on"): + # pyrefly: ignore [missing-attribute] + t._specialize_on = {} + + if hint_override: + # pyrefly: ignore [missing-attribute] + t._dynamo_hint_overrides[index] = hint_override + # TODO(voz): Should we bounds check? + # pyrefly: ignore [missing-attribute] + t._dynamo_dynamic_indices.add(index) + t._dynamo_dynamic_range.add(_DimRange(index, min, max)) # type: ignore[arg-type] + + # FX tracers don't respect @forbid_in_graph and choke on the following error since it passes in proxies: + # TypeError: 'Attribute' object does not support item assignment + # pyrefly: ignore [missing-attribute] + if isinstance(t._specialize_on, dict): + t._specialize_on[index] = specialize_on if specialize_on is not None else [] + + return + + assert isinstance(index, (list, tuple)) + for i in index: + mark_dynamic(t, i, min=min, max=max) + mark_dynamic(t, i, min=min, max=max, specialize_on=specialize_on) + + +@forbid_in_graph +def maybe_mark_dynamic(t: Any, index: Union[int, list[Any], tuple[Any]]) -> None: + """ + Mark a tensor as having a dynamic dim, but don't enforce it (i.e., if this + dimension ends up getting specialized, don't error). + """ + if is_traceable_wrapper_subclass(t): + # default behavior: mirror maybe_mark_dynamic() on all inner tensors with same dim as t + # TODO: Make this configurable via a supported public API + _apply_func_to_inner_tensors_of_same_dim(maybe_mark_dynamic, t, index) + + if isinstance(index, int): + if not hasattr(t, "_dynamo_weak_dynamic_indices"): + # pyrefly: ignore [missing-attribute] + t._dynamo_weak_dynamic_indices = set() + # TODO(voz): Should we bounds check? + # pyrefly: ignore [missing-attribute] + t._dynamo_weak_dynamic_indices.add(index) + return + + assert isinstance(index, (list, tuple)) + for i in index: + maybe_mark_dynamic(t, i) + + +def mark_static( + t: Any, index: Optional[Union[int, list[Any], tuple[Any]]] = None +) -> None: + """ + Mark a tensor as having a static dim or mark a nn module class as static. + + For tensors + =========== + This will prevent us from attempting to compile it dynamically + when dynamic=True; this can improve trace-time performance. + + This has lower precedence than mark_dynamic. + + Unlike mark_dynamic, this can be done inside a graph, in which case it + induces specialization on the tensor. + + For nn.Module classes + ===================== + For static nn.Module classes, TorchDynamo assumes that the module instance + attributes will not be modified after compilation. This will ensure that + TorchDynamo keeps integer attributes CONSTANT and not symints. + + From TorchDynamo implementation side, the instances of static-marked + nn.Module class will be converted to UnspecializedBuiltinNNModuleVariable, + which have the same properties. + + Note that we still have to guard on the attributes, because different + instances of the nn.Module can have different values of the attributes. The + key point here is that the attributes are static. + """ + if is_compiling(): + if index is None: + for s in t.size(): + comptime.force_static(s) + else: + comptime.force_static(t.size(index)) + return + + if is_traceable_wrapper_subclass(t): + # default behavior: mirror mark_static() on all inner tensors with same dim as t + # TODO: Make this configurable via a supported public API + _apply_func_to_inner_tensors_of_same_dim(mark_static, t, index) + + # pyrefly: ignore [bad-argument-type] + if not isinstance(t, torch.Tensor) and issubclass(t, torch.nn.Module): + # pyrefly: ignore [missing-attribute] + t._dynamo_marked_static = True + # pyrefly: ignore [bad-return] + return t + + if not isinstance(t, torch.Tensor): + raise TypeError( + f"mark_static expects a tensor/nn.Module class but received {type(t)}" + ) + + if isinstance(index, int): + if not hasattr(t, "_dynamo_static_indices"): + t._dynamo_static_indices = set() # type: ignore[attr-defined] + # TODO(voz): Should we bounds check? + t._dynamo_static_indices.add(index) # type: ignore[attr-defined] + elif index is None: + for i in range(t.dim()): + mark_static(t, i) + else: + assert isinstance(index, (list, tuple)) + for i in index: + mark_static(t, i) + + +@forbid_in_graph +def mark_static_address(t: Any, guard: bool = False) -> None: + """ + Marks an input tensor whose address should be treated as constant across calls to the + same dynamo-compiled function. This indicates to cudagraphs that an extra allocation + is not needed for this input. The data_ptr will be guarded if guard=True, and cause a full + recompile if the data_ptr changes. Note: If this address changes, cudagraphs will re-record + if guard=False. + """ + if not isinstance(t, torch.Tensor): + raise TypeError(f"mark_static_address expects a tensor but received {type(t)}") + + if guard: + t._dynamo_static_input_type = "guarded" # type: ignore[attr-defined] + else: + t._dynamo_static_input_type = "unguarded" # type: ignore[attr-defined] + + +# One day, Dynamo will support tracing into einops directly (no allow_in_graph needed) +# Note that PyTorch supports multiple versions of einops, so when that day comes, +# we still need to be really careful about version matches. +def _allow_in_graph_einops() -> None: + import einops + + try: + # requires einops > 0.6.1, torch >= 2.0 + from einops._torch_specific import ( # type: ignore[attr-defined] # noqa: F401 + _ops_were_registered_in_torchdynamo, + ) + + # einops > 0.6.1 will call the op registration logic as it is imported. + except ImportError: + # einops <= 0.6.1 + allow_in_graph(einops.rearrange) + allow_in_graph(einops.reduce) + if hasattr(einops, "repeat"): + allow_in_graph(einops.repeat) # available since einops 0.2.0 + if hasattr(einops, "einsum"): + allow_in_graph(einops.einsum) # available since einops 0.5.0 + if hasattr(einops, "pack"): + allow_in_graph(einops.pack) # available since einops 0.6.0 + if hasattr(einops, "unpack"): + allow_in_graph(einops.unpack) # available since einops 0.6.0 + + +# Note: this carefully avoids eagerly import einops. +trace_rules.add_module_init_func("einops", _allow_in_graph_einops) + + +# Proxy class for torch._dynamo.config patching - so dynamo can identify context managers/decorators +# created by patch_dynamo_config, compared to ones created by a raw torch._dynamo.config.patch. +class DynamoConfigPatchProxy: + def __init__(self, config_patch: Any) -> None: + self.config_patch = config_patch + + @property + def changes(self) -> dict[str, Any]: + return self.config_patch.changes + + # Decorator implementation that simply sets up `self` as a context manager. + # Placed in external_utils so that we can trace through it. + __call__ = wrap_dunder_call_ctx_manager + + def __enter__(self) -> None: + return self.config_patch.__enter__() + + def __exit__( + self, + exc_type: Optional[type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType], + ) -> None: + return self.config_patch.__exit__(exc_type, exc_val, exc_tb) + + +# Criteria for patchable config: +# - Config values must be constants (i.e. int, float, str, bool, None). +# - in particular, NO list, set, dict. +# - Traceable config patches are only useful for configs that change dynamo behavior +# from symbolic_convert and below. +# - e.g. patching recompile_limit won't really do anything. +# - For patching configs that affect Dynamo behavior above symbolic_convert, +# ensure that Dynamo behaves soundly even if tracing is done with different config. +# - e.g. be careful if patching guard-related configs as configs may have changed +# between guard creation and evaluation. +_allowed_config_patches = ( + "verbose", + "verify_correctness", + "rewrite_assert_with_torch_assert", + "capture_scalar_outputs", + "allow_unspec_int_on_nn_module", + "skip_torchrec", + "dont_skip_tracing", + "nested_graph_breaks", +) + +from . import config + + +for name in _allowed_config_patches: + assert hasattr(config, name), "nonexistent config" +del config + + +def _patch_dynamo_config_check(changes: dict[str, Any]) -> None: + for k, v in changes.items(): + if k not in _allowed_config_patches: + raise ValueError( + f"patch_dynamo_config does not support patching config {k}" + ) + if not torch._dynamo.utils.is_safe_constant(v): + raise ValueError( + f"patch_dynamo_config does not support patching config {k} " + f"with non-safe-constant value {v}" + ) + + +# TODO: also implement nonrecursive patch_dynamo_config/dont_skip_tracing. +# Unlike config.patch, we also need to accept tuple as input in order to +# deal with context manager reconstruction. +def patch_dynamo_config( + arg1: Optional[Union[str, dict[str, Any], tuple[tuple[str, Any], ...]]] = None, + arg2: Any = None, + **kwargs: Any, +) -> DynamoConfigPatchProxy: + """ + A wrapper around torch._dynamo.config.patch that can be traced by Dynamo to + temporarily change config values DURING tracing. + + See _allowed_config_patches for the list of allowed config patches. + + Arguments are the same as with torch._dynamo.config.patch. + + Can be used as a decorator or a context manager. + + User code SHOULD NOT MODIFY the return value of this function. + + WARNING: changing Dynamo config during tracing can lead to unpredictable tracing behavior! + Proceed only as advised! + """ + if isinstance(arg1, tuple): + arg1 = dict(arg1) + config_patch = torch._dynamo.config.patch(arg1, arg2, **kwargs) + _patch_dynamo_config_check(config_patch.changes) + # check for valid patching using config_patch.changes + return DynamoConfigPatchProxy(config_patch) + + +@overload +def dont_skip_tracing(fn: None = None) -> DynamoConfigPatchProxy: ... + + +@overload +def dont_skip_tracing(fn: Callable[_P, _R]) -> Callable[_P, _R]: ... + + +def dont_skip_tracing(fn: Optional[Any] = None) -> Any: + """ + Context manager/decorator to trace into functions intentionally marked by developers to be skipped + when tracing. + + This decorator will also apply to recursively invoked functions. + """ + ctx = patch_dynamo_config(dont_skip_tracing=True) + if fn: + return ctx(fn) + return ctx + + +@overload +def disable_nested_graph_breaks(fn: None = None) -> DynamoConfigPatchProxy: ... + + +@overload +def disable_nested_graph_breaks(fn: Callable[_P, _R]) -> Callable[_P, _R]: ... + + +def disable_nested_graph_breaks(fn: Optional[Any] = None) -> Any: + """ + Context manager/decorator to disable nested graph breaks when tracing + this function and any nested functions. Used when nested graph breaks + is causing problems. + """ + ctx = patch_dynamo_config(nested_graph_breaks=False) + if fn: + return ctx(fn) + return ctx + + +class ErrorOnGraphBreakDecoratorContextManager: + def __init__(self, error_on_graph_break: bool) -> None: + self.error_on_graph_break = error_on_graph_break + + __call__ = wrap_dunder_call_ctx_manager + + def __enter__(self) -> None: + self.prev_error_on_graph_break = _get_error_on_graph_break() + _set_error_on_graph_break(self.error_on_graph_break) + + def __exit__( + self, + exc_type: Optional[type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType], + ) -> None: + _set_error_on_graph_break(self.prev_error_on_graph_break) + + +def error_on_graph_break( + error_on_graph_break: bool, +) -> ErrorOnGraphBreakDecoratorContextManager: + """ + Context manager/decorator to toggle torch.compile's `error_on_graph_break` setting at compile time. + + If `fullgraph` is set, then `error_on_graph_break` does nothing + (i.e. `fullgraph = True` takes higher precedence). If `fullgraph` is False, then + `error_on_graph_break` determines whether `torch.compile` throws an error upon + encountering a graph break, or attempts to continue tracing. + + `error_on_graph_break` can be toggled during compile time with this decorator to allow graph breaks in some + compiled regions but not others. One key difference from `fullgraph` is that `error_on_graph_break = True` + does NOT guarantee that a single graph is captured from the compiled function. + + The default value of torch.compile's `error_on_graph_break` setting is False. + """ + return ErrorOnGraphBreakDecoratorContextManager(error_on_graph_break) + + +def is_dynamo_disable_recursive(method: Callable[[Any], Any]) -> Optional[bool]: + """ + Check if a method is marked as `dynamo_disable` recursively. It returns: + - True if disable(recursive=True) + - False if disable(recursive=False) + - None if method is not a disable decorator + """ + return getattr(method, "_torchdynamo_disable_recursive", None) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/device_interface.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/device_interface.py new file mode 100644 index 0000000000000000000000000000000000000000..00ba284f9b44cef909fb88e5a3341efee7371dc4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/device_interface.py @@ -0,0 +1,612 @@ +""" +Device abstraction layer for TorchDynamo and Inductor backends. + +This module provides a unified interface for different hardware backends (CUDA, XPU, +CPU, MPS, MTIA) through a common device interface. Key components include: + +- DeviceInterface: Base class defining the common API for all device types +- Device-specific implementations: CudaInterface, XpuInterface, CpuInterface, MpsInterface, MtiaInterface +- Device registration system for managing available backends +- Worker APIs for multi-processing scenarios +- Stream and event management across different devices +- Device property caching for worker processes + +The abstraction layer enables device-agnostic code in TorchDynamo while allowing +specialized implementations for each hardware backend's unique features. +""" + +import inspect +import time +from collections import namedtuple +from collections.abc import Callable, Iterable +from dataclasses import dataclass +from typing import Any, Literal, Optional, Union + +import torch + + +get_cuda_stream: Optional[Callable[[int], int]] +if torch.cuda._is_compiled(): + from torch._C import _cuda_getCurrentRawStream as get_cuda_stream +else: + get_cuda_stream = None + +# Recording the device properties in the main process but used in worker process. +caching_worker_device_properties: dict[str, Any] = {} +caching_worker_current_devices: dict[str, int] = {} + + +class DeviceInterface: + """ + This is a simple device runtime interface for Inductor. It enables custom + backends to be integrated with Inductor in a device-agnostic semantic. + """ + + class device: + def __new__(cls, device: torch.types.Device) -> Any: + raise NotImplementedError + + class Event: + def __new__(cls, *args: Any, **kwargs: Any) -> Any: + raise NotImplementedError( + "Event should be inherited from torch.Event, otherwise, it couldn't be captured by dynamo." + ) + + class Stream: + def __new__(cls, *args: Any, **kwargs: Any) -> Any: + raise NotImplementedError( + "Stream should be inherited from torch.Stream, otherwise, it couldn't be captured by dynamo." + ) + + class Worker: + """ + Worker API to query device properties that will work in multi processing + workers that cannot use the GPU APIs (due to processing fork() and + initialization time issues). Properties are recorded in the main process + before we fork the workers. + """ + + @staticmethod + def set_device(device: int) -> None: + raise NotImplementedError + + @staticmethod + def current_device() -> int: + raise NotImplementedError + + @staticmethod + def get_device_properties(device: torch.types.Device = None) -> Any: + raise NotImplementedError + + @staticmethod + def current_device() -> int: + raise NotImplementedError + + @staticmethod + def set_device(device: torch.types.Device) -> None: + raise NotImplementedError + + @staticmethod + def maybe_exchange_device(device: int) -> int: + raise NotImplementedError + + @staticmethod + def exchange_device(device: int) -> int: + raise NotImplementedError + + @staticmethod + def device_count() -> int: + raise NotImplementedError + + @staticmethod + def is_available() -> bool: + raise NotImplementedError + + @staticmethod + def stream(stream: torch.Stream) -> Any: + raise NotImplementedError + + @staticmethod + def current_stream() -> torch.Stream: + raise NotImplementedError + + @staticmethod + def set_stream(stream: torch.Stream) -> None: + raise NotImplementedError + + @staticmethod + def _set_stream_by_id(stream_id: int, device_index: int, device_type: int) -> None: + raise NotImplementedError + + @staticmethod + def get_raw_stream(device_idx: int) -> int: + raise NotImplementedError + + @staticmethod + def synchronize(device: torch.types.Device = None) -> None: + raise NotImplementedError + + @classmethod + def get_device_properties(cls, device: torch.types.Device = None) -> Any: + return cls.Worker.get_device_properties(device) + + @staticmethod + def get_compute_capability(device: torch.types.Device = None) -> Any: + raise NotImplementedError + + @staticmethod + def is_bf16_supported(including_emulation: bool = False) -> bool: + raise NotImplementedError + + @classmethod + def is_dtype_supported( + cls, dtype: torch.dtype, including_emulation: bool = False + ) -> bool: + return dtype != torch.bfloat16 or cls.is_bf16_supported(including_emulation) + + @staticmethod + def memory_allocated(device: torch.types.Device = None) -> int: + raise NotImplementedError + + @staticmethod + def is_triton_capable(device: torch.types.Device = None) -> bool: + """ + Returns True if the device has Triton support, False otherwise, even if + the appropriate Triton backend is not available. + """ + return False + + @classmethod + def raise_if_triton_unavailable(cls, device: torch.types.Device = None) -> None: + """ + Raises a `RuntimeError` with the appropriate human-readable instructions + to resolve the issue if Triton is not available for the given device, or + the default device if `device` is `None`. + + The caller should ensure the presence of the 'triton' package before + calling this method. + """ + if not cls.is_triton_capable(): + raise RuntimeError("This device is not capable of supporting Triton") + + +class DeviceGuard: + """ + This class provides a context manager for device switching. This is a stripped + down version of torch.{device_name}.device. + + The context manager changes the current device to the given device index + on entering the context and restores the original device on exiting. + The device is switched using the provided device interface. + """ + + def __init__( + self, device_interface: type[DeviceInterface], index: Optional[int] + ) -> None: + self.device_interface = device_interface + self.idx = index + self.prev_idx = -1 + + def __enter__(self) -> None: + if self.idx is not None: + self.prev_idx = self.device_interface.exchange_device(self.idx) + + def __exit__(self, type: Any, value: Any, traceback: Any) -> Literal[False]: + if self.idx is not None: + self.idx = self.device_interface.maybe_exchange_device(self.prev_idx) + return False + + +class CudaInterface(DeviceInterface): + device = torch.cuda.device # type: ignore[assignment] + + # register Event and Stream class into the backend interface + # make sure Event and Stream are implemented and inherited from the torch.Event and torch.Stream + Event = torch.cuda.Event # type: ignore[assignment] + Stream = torch.cuda.Stream # type: ignore[assignment] + + # pyrefly: ignore [bad-override] + class Worker: + @staticmethod + def set_device(device: int) -> None: + caching_worker_current_devices["cuda"] = device + + @staticmethod + def current_device() -> int: + if "cuda" in caching_worker_current_devices: + return caching_worker_current_devices["cuda"] + return torch.cuda.current_device() + + @staticmethod + def get_device_properties(device: torch.types.Device = None) -> Any: + if device is not None: + if isinstance(device, str): + device = torch.device(device) + assert device.type == "cuda" + if isinstance(device, torch.device): + device = device.index + if device is None: + device = CudaInterface.Worker.current_device() + + if "cuda" not in caching_worker_device_properties: + device_prop = [ + torch.cuda.get_device_properties(i) + for i in range(torch.cuda.device_count()) + ] + caching_worker_device_properties["cuda"] = device_prop + + return caching_worker_device_properties["cuda"][device] + + current_device = staticmethod(torch.cuda.current_device) + set_device = staticmethod(torch.cuda.set_device) + device_count = staticmethod(torch.cuda.device_count) + stream = staticmethod(torch.cuda.stream) # type: ignore[assignment] + # pyrefly: ignore [bad-override] + current_stream = staticmethod(torch.cuda.current_stream) + set_stream = staticmethod(torch.cuda.set_stream) # type: ignore[assignment] + _set_stream_by_id = staticmethod(torch.cuda._set_stream_by_id) # type: ignore[assignment] + synchronize = staticmethod(torch.cuda.synchronize) + get_device_properties = staticmethod(torch.cuda.get_device_properties) # type: ignore[assignment] + get_raw_stream = staticmethod(get_cuda_stream) # type: ignore[assignment, arg-type] + exchange_device = staticmethod(torch.cuda._exchange_device) # type: ignore[arg-type, has-type] + maybe_exchange_device = staticmethod(torch.cuda._maybe_exchange_device) # type: ignore[arg-type, has-type] + memory_allocated = staticmethod(torch.cuda.memory_allocated) + is_bf16_supported = staticmethod(torch.cuda.is_bf16_supported) # type: ignore[arg-type] + + # Can be mock patched by @patch decorator. + @staticmethod + def is_available() -> bool: + return torch.cuda.is_available() + + @staticmethod + def get_compute_capability(device: torch.types.Device = None) -> Union[int, str]: + if torch.version.hip is None: + major, min = torch.cuda.get_device_capability(device) + return major * 10 + min + else: + return torch.cuda.get_device_properties(device).gcnArchName.split(":", 1)[0] + + @staticmethod + def is_triton_capable(device: torch.types.Device = None) -> bool: + return ( + torch.version.hip is not None + or torch.cuda.get_device_properties(device).major >= 7 + ) + + @staticmethod + def raise_if_triton_unavailable(device: torch.types.Device = None) -> None: + from torch._inductor.exc import GPUTooOldForTriton + + if not CudaInterface.is_triton_capable(device): + device_props = torch.cuda.get_device_properties(device) + raise GPUTooOldForTriton(device_props, inspect.currentframe()) + + import triton.backends + + if torch.version.hip is not None: + if "amd" not in triton.backends.backends: + raise RuntimeError("triton not built with the 'amd' backend") + elif "nvidia" not in triton.backends.backends: + raise RuntimeError("triton not built with the 'nvidia' backend") + + +get_mtia_stream: Optional[Callable[[int], int]] +if torch.mtia._is_compiled(): + from torch._C import _mtia_getCurrentRawStream as get_mtia_stream +else: + get_mtia_stream = None + + +class MtiaInterface(DeviceInterface): + device = torch.mtia.device # type: ignore[assignment] + Event = torch.mtia.Event # type: ignore[assignment] + Stream = torch.mtia.Stream # type: ignore[assignment] + + # pyrefly: ignore [bad-override] + class Worker: + @staticmethod + def set_device(device: int) -> None: + caching_worker_current_devices["mtia"] = device + + @staticmethod + def current_device() -> int: + if "mtia" in caching_worker_current_devices: + return caching_worker_current_devices["mtia"] + return torch.mtia.current_device() + + @staticmethod + def get_device_properties(device: torch.types.Device = None) -> Any: + if device is not None: + if isinstance(device, str): + device = torch.device(device) + assert device.type == "mtia" + if isinstance(device, torch.device): + device = device.index + if device is None: + device = MtiaInterface.Worker.current_device() + + if "mtia" not in caching_worker_device_properties: + device_prop = [ + torch.mtia.get_device_properties(i) + for i in range(torch.mtia.device_count()) + ] + caching_worker_device_properties["mtia"] = device_prop + + return caching_worker_device_properties["mtia"][device] + + current_device = staticmethod(torch.mtia.current_device) + set_device = staticmethod(torch.mtia.set_device) # type: ignore[assignment] + device_count = staticmethod(torch.mtia.device_count) + stream = staticmethod(torch.mtia.stream) # type: ignore[assignment] + # pyrefly: ignore [bad-override] + current_stream = staticmethod(torch.mtia.current_stream) + set_stream = staticmethod(torch.mtia.set_stream) # type: ignore[assignment] + _set_stream_by_id = staticmethod(torch.mtia._set_stream_by_id) # type: ignore[assignment] + synchronize = staticmethod(torch.mtia.synchronize) + get_device_properties = staticmethod(torch.mtia.get_device_properties) # type: ignore[assignment] + get_raw_stream = staticmethod(get_mtia_stream) # type: ignore[assignment, arg-type] + exchange_device = staticmethod(torch.mtia._exchange_device) # type: ignore[arg-type, has-type] + maybe_exchange_device = staticmethod(torch.mtia._maybe_exchange_device) # type: ignore[arg-type, has-type] + memory_allocated = staticmethod(torch.mtia.memory_allocated) # type: ignore[assignment] + is_bf16_supported = staticmethod(torch.mtia.is_bf16_supported) # type: ignore[arg-type] + + # Can be mock patched by @patch decorator. + @staticmethod + def is_available() -> bool: + ret = torch.mtia.is_available() + return ret + + @staticmethod + def get_compute_capability(device: torch.types.Device = None) -> Any: + cc = torch.mtia.get_device_capability(device) + return cc + + @staticmethod + def is_triton_capable(device: torch.types.Device = None) -> bool: + return True + + @staticmethod + def raise_if_triton_unavailable(evice: torch.types.Device = None) -> None: + import triton.backends + + if "mtia" not in triton.backends.backends: + raise RuntimeError("triton not built with the 'mtia' backend") + + +get_xpu_stream: Optional[Callable[[int], int]] +if torch.xpu._is_compiled(): + from torch._C import _xpu_getCurrentRawStream as get_xpu_stream +else: + get_xpu_stream = None + + +class XpuInterface(DeviceInterface): + device = torch.xpu.device # type: ignore[assignment] + Event = torch.xpu.Event # type: ignore[assignment] + Stream = torch.xpu.Stream # type: ignore[assignment] + + # pyrefly: ignore [bad-override] + class Worker: + @staticmethod + def set_device(device: int) -> None: + caching_worker_current_devices["xpu"] = device + + @staticmethod + def current_device() -> int: + if "xpu" in caching_worker_current_devices: + return caching_worker_current_devices["xpu"] + return torch.xpu.current_device() + + @staticmethod + def get_device_properties(device: torch.types.Device = None) -> Any: + if device is not None: + if isinstance(device, str): + device = torch.device(device) + assert device.type == "xpu" + if isinstance(device, torch.device): + device = device.index + if device is None: + device = XpuInterface.Worker.current_device() + + if "xpu" not in caching_worker_device_properties: + device_prop = [ + torch.xpu.get_device_properties(i) + for i in range(torch.xpu.device_count()) + ] + caching_worker_device_properties["xpu"] = device_prop + + return caching_worker_device_properties["xpu"][device] + + current_device = staticmethod(torch.xpu.current_device) + set_device = staticmethod(torch.xpu.set_device) + device_count = staticmethod(torch.xpu.device_count) # type: ignore[has-type] + stream = staticmethod(torch.xpu.stream) # type: ignore[assignment] + # pyrefly: ignore [bad-override] + current_stream = staticmethod(torch.xpu.current_stream) + set_stream = staticmethod(torch.xpu.set_stream) # type: ignore[assignment] + _set_stream_by_id = staticmethod(torch.xpu._set_stream_by_id) # type: ignore[assignment] + synchronize = staticmethod(torch.xpu.synchronize) + get_device_properties = staticmethod(torch.xpu.get_device_properties) # type: ignore[assignment] + get_raw_stream = staticmethod(get_xpu_stream) # type: ignore[assignment, arg-type] + exchange_device = staticmethod(torch.xpu._exchange_device) # type: ignore[arg-type, has-type] + maybe_exchange_device = staticmethod(torch.xpu._maybe_exchange_device) # type: ignore[arg-type, has-type] + memory_allocated = staticmethod(torch.xpu.memory_allocated) + + # Can be mock patched by @patch decorator. + @staticmethod + def is_available() -> bool: + return torch.xpu.is_available() + + @staticmethod + def get_compute_capability(device: torch.types.Device = None) -> Any: + cc = torch.xpu.get_device_capability(device) + return cc + + @staticmethod + def is_bf16_supported(including_emulation: bool = False) -> bool: + return torch.xpu.is_bf16_supported() + + @staticmethod + def is_triton_capable(device: torch.types.Device = None) -> bool: + return True + + @staticmethod + def raise_if_triton_unavailable(device: torch.types.Device = None) -> None: + import triton.backends + + if "intel" not in triton.backends.backends: + raise RuntimeError("triton not built with the 'intel' backend") + + +@dataclass +class CpuDeviceProperties: + multi_processor_count: int + + +class CpuInterface(DeviceInterface): + # pyrefly: ignore [bad-override] + class Event(torch.Event): + def __init__(self, enable_timing: bool = True) -> None: + self.time = 0.0 + + def elapsed_time(self, end_event: Any) -> float: + return (end_event.time - self.time) * 1000 + + def record(self, stream: Any = None) -> None: + self.time = time.perf_counter() + + # pyrefly: ignore [bad-override] + class Worker: + @staticmethod + def get_device_properties( + device: torch.types.Device = None, + ) -> CpuDeviceProperties: + import multiprocessing + + cpu_count = multiprocessing.cpu_count() + return CpuDeviceProperties(cpu_count) + + @staticmethod + def is_available() -> bool: + return True + + @staticmethod + def is_bf16_supported(including_emulation: bool = False) -> bool: + return True + + @staticmethod + def get_compute_capability(device: torch.types.Device = None) -> str: + return "" + + @staticmethod + def get_raw_stream(device_idx: Any) -> int: + return 0 + + @staticmethod + def current_device() -> int: + return 0 + + @staticmethod + def synchronize(device: torch.types.Device = None) -> None: + pass + + @staticmethod + def is_triton_capable(device: torch.types.Device = None) -> bool: + return True + + @staticmethod + def raise_if_triton_unavailable(device: torch.types.Device = None) -> None: + import triton.backends + + if "cpu" not in triton.backends.backends: + raise RuntimeError("triton not built with the 'cpu' backend") + + +class MpsInterface(DeviceInterface): + @staticmethod + def is_bf16_supported(including_emulation: bool = False) -> bool: + return torch.backends.mps.is_macos_or_newer(14, 0) + + @classmethod + def is_dtype_supported( + cls, dtype: torch.dtype, including_emulation: bool = False + ) -> bool: + if dtype in [torch.float64, torch.complex128]: + return False + return dtype != torch.bfloat16 or cls.is_bf16_supported(including_emulation) + + @staticmethod + def is_available() -> bool: + return torch.backends.mps.is_available() + + @staticmethod + def current_device() -> int: + return 0 + + @staticmethod + def get_compute_capability(device: torch.types.Device = None) -> str: + return "" + + @staticmethod + def synchronize(device: torch.types.Device = None) -> None: + torch.mps.synchronize() + + # pyrefly: ignore [bad-override] + class Worker: + @staticmethod + def get_device_properties(device: torch.types.Device = None) -> Any: + return namedtuple("MPSProperties", ["multi_processor_count"])( + torch.backends.mps.get_core_count() # type: ignore[arg-type] + ) + + @staticmethod + def current_device() -> int: + return 0 + + +device_interfaces: dict[str, type[DeviceInterface]] = {} +_device_initialized = False + + +def register_interface_for_device( + device: Union[str, torch.device], device_interface: type[DeviceInterface] +) -> None: + if isinstance(device, torch.device): + device = device.type + device_interfaces[device] = device_interface + + +def get_interface_for_device(device: Union[str, torch.device]) -> type[DeviceInterface]: + if isinstance(device, torch.device): + device = device.type + if not _device_initialized: + init_device_reg() + if device in device_interfaces: + return device_interfaces[device] + raise NotImplementedError(f"No interface for device {device}") + + +def get_registered_device_interfaces() -> Iterable[tuple[str, type[DeviceInterface]]]: + if not _device_initialized: + init_device_reg() + return device_interfaces.items() + + +def init_device_reg() -> None: + global _device_initialized + register_interface_for_device("cuda", CudaInterface) + for i in range(torch.cuda.device_count()): + register_interface_for_device(f"cuda:{i}", CudaInterface) + + register_interface_for_device("xpu", XpuInterface) + for i in range(torch.xpu.device_count()): + register_interface_for_device(f"xpu:{i}", XpuInterface) + + register_interface_for_device("mtia", MtiaInterface) + for i in range(torch.mtia.device_count()): + register_interface_for_device(f"mtia:{i}", MtiaInterface) + + register_interface_for_device("cpu", CpuInterface) + register_interface_for_device("mps", MpsInterface) + + _device_initialized = True diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/distributed.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/distributed.py new file mode 100644 index 0000000000000000000000000000000000000000..490b6330fafa45c871771610849707d26216cccf --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/distributed.py @@ -0,0 +1,54 @@ +""" +Manages process groups for distributed compilation in TorchDynamo. + +This module handles the initialization and management of process groups used for +distributed compilation. Key features: + +- Lazy initialization of compilation process groups +- Only creates groups when distributed mode is enabled and available +- Integrates with compiler_collectives configuration setting +- Provides a single global process group for compilation coordination + +The process group is created only when needed and if the distributed environment +is properly initialized, making it safe to import and use this module even in +non-distributed scenarios. +""" + +from typing import Optional + +import torch.distributed as dist + +from . import config + + +_COMPILE_PG: Optional[dist.ProcessGroup] = None +_GUARD_PG: Optional[dist.ProcessGroup] = None + + +def get_compile_pg() -> Optional[dist.ProcessGroup]: + if ( + config.enable_compiler_collectives + and dist.is_available() + and dist.is_initialized() + ): + global _COMPILE_PG + if _COMPILE_PG is None: + # , timeout=datetime.timedelta(seconds=2) + _COMPILE_PG = dist.distributed_c10d._new_group_with_tag( + pg_tag="pt2_compile_pg" + ) + return _COMPILE_PG + + return None + + +# NB: Unlike get_compile_pg, this is only called when guard collectives were +# explicitly requested +def get_guard_pg() -> Optional[dist.ProcessGroup]: + if dist.is_available() and dist.is_initialized(): + global _GUARD_PG + if _GUARD_PG is None: + _GUARD_PG = dist.distributed_c10d._new_group_with_tag(pg_tag="pt2_guard_pg") + return _GUARD_PG + + return None diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/eval_frame.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/eval_frame.py new file mode 100644 index 0000000000000000000000000000000000000000..4a46fb366b0b8fb631ee73057fe3024c105e08ae --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/eval_frame.py @@ -0,0 +1,2504 @@ +# mypy: disable-error-code="method-assign" + +""" +This module implements the core frame evaluation handler for TorchDynamo's compilation system. +The eval frame handler intercepts Python bytecode execution at runtime to enable dynamic +compilation and optimization of PyTorch code. + +Key components defined here: +- Frame evaluation handlers that intercept and analyze Python execution frames +- Guards management for tracking dependencies and invalidating compiled code +- Optimization contexts and decorators (optimize, run_once, disable, etc.) +- Export functionality for saving optimized graphs +- Backend compiler integrations and callback management + +Functions in this file are responsible for modifying the eval frame handler at RUNTIME. +Therefore, all functions in this file are hot and performance-critical. Functions that +only execute at compile time should be placed in torch._dynamo.convert_frame. + +The eval frame handler is the core mechanism that enables TorchDynamo to dynamically +intercept, analyze and optimize PyTorch code during execution. It works by registering +a custom frame evaluation function that gets called for every Python frame, allowing +us to detect PyTorch operations and trigger compilation as needed. +""" + +from __future__ import annotations + +import atexit +import contextlib +import functools +import inspect +import logging +import os +import sys +import sysconfig +import textwrap +import threading +import traceback +import types +import unittest +import warnings +import weakref +from collections.abc import Sized +from dataclasses import dataclass +from enum import Enum +from os.path import dirname, join +from typing import Any, NamedTuple, Optional, TYPE_CHECKING, Union +from unittest.mock import patch + +import sympy + +import torch +import torch.fx +import torch.utils._pytree as pytree +import torch.utils.checkpoint +from torch import _guards + +# see discussion at https://github.com/pytorch/pytorch/issues/120699 +from torch._C._dynamo.eval_frame import ( # noqa: F401 + reset_code, + set_code_exec_strategy, + set_eval_frame, + set_guard_complete_hook, + set_guard_error_hook, + set_skip_guard_eval_unsafe, + unsupported, +) +from torch._dispatch.python import enable_python_dispatcher +from torch._dynamo.types import ConvertFrameReturn, FrameAction, FrameExecStrategy +from torch._export.utils import _compiling_state_context +from torch._subclasses.fake_tensor import unset_fake_temporarily +from torch._utils_internal import DISABLE_JUSTKNOBS, justknobs_check, log_export_usage +from torch.export.dynamic_shapes import ( + _combine_args, + _DimHint, + _DimHintType, + _IntWrapper, + _process_dynamic_shapes, + _RelaxedConstraint, + Constraint, +) +from torch.fx import GraphModule, traceback as fx_traceback +from torch.fx.experimental._dynamism import ( + clone_and_convert_to_meta, + track_dynamism_across_examples, +) +from torch.fx.experimental.proxy_tensor import make_fx +from torch.fx.experimental.symbolic_shapes import ( + ConstraintViolationError, + DimDynamic, + ShapeEnv, + StatelessSymbolicContext, +) +from torch.fx.graph import _PyTreeCodeGen, _PyTreeInfo + +from . import config, convert_frame, distributed, external_utils, trace_rules, utils +from .backends.registry import CompilerFn, lookup_backend +from .code_context import code_context +from .exc import ( + CondOpArgsMismatchError, + ShortenTraceback, + Unsupported, + UserError, + UserErrorType, +) +from .hooks import Hooks +from .mutation_guard import install_generation_tagging_init +from .utils import ( + _get_error_on_graph_break, + _set_error_on_graph_break, + common_constant_types, + compile_times, +) + + +if TYPE_CHECKING: + from collections.abc import Callable, Iterable, Sequence + + from torch._dynamo.package import CompilePackage + from torch._dynamo.repro.after_dynamo import WrapBackendDebug + from torch._subclasses import fake_tensor + from torch.fx.node import Argument, Node, Target + + from .types import ( + CacheEntry, + DynamoCallback, + DynamoFrameType, + GuardFail, + GuardFilterEntry, + ) + + +log = logging.getLogger(__name__) + + +always_optimize_code_objects = utils.ExactWeakKeyDictionary() +null_context = contextlib.nullcontext + + +# See https://github.com/python/typing/pull/240 +class Unset(Enum): + token = 0 + + +cached_backends: dict[int, CompilerFn] = {} + +unset = Unset.token + +_in_optimized_module = False + + +if DISABLE_JUSTKNOBS: + _maybe_set_eval_frame = set_eval_frame +else: + + def _maybe_set_eval_frame(callback: DynamoCallback) -> DynamoCallback: + # A wrapper on set_eval_frame that is guarded by a Justknob. + # Users can disable torchDynamo by setting the JK to False. + if not justknobs_check("pytorch/compiler:enable_compiler_set_eval_frame"): + torch._dynamo.utils.warn_once( + "Dynamo disabled by Justknob: enable_compiler_set_eval_frame, skipping set_eval_frame" + ) + return callback + else: + return set_eval_frame(callback) + + +@dataclass +class DynamoStance: + stance: str = "default" + skip_guard_eval_unsafe: bool = False + backend: Union[str, Callable[..., Any], None] = None + + +_stance = DynamoStance() + + +def _set_stance(stance: DynamoStance) -> DynamoStance: + global _stance + + from torch._C._dynamo.eval_frame import get_eval_frame_callback + + callback = get_eval_frame_callback() + + if callback is not False and callback is not None: + raise RuntimeError("attempted to set_stance in a torch.compile region") + + prior = _stance + _stance = stance + return prior + + +_set_stance._dynamo_forbidden = True # type: ignore[attr-defined] + +_EXAMPLE_INPUTS: Optional[dict[str, list[Any]]] = None + + +def get_example_inputs(key: str) -> list[Any]: + global _EXAMPLE_INPUTS + if _EXAMPLE_INPUTS is None: + _EXAMPLE_INPUTS = {} + + if key not in _EXAMPLE_INPUTS: + _EXAMPLE_INPUTS[key] = [] + + return _EXAMPLE_INPUTS[key] + + +@contextlib.contextmanager +def _set_in_optimized_module(): + # Set in dynamo's OptimizedModule forward, to have better coverage than is_compiling(). + # Prevents graph-breaking forward hooks from being registered & traced. + # TODO(pianpwk): subsume this flag with better is_compiling() coverage + global _in_optimized_module + _old_in_optimized_module = ( + _in_optimized_module # do we need this? can we just set it to False after + ) + _in_optimized_module = True + try: + yield + finally: + _in_optimized_module = _old_in_optimized_module + + +def _is_in_optimized_module() -> bool: + global _in_optimized_module + return _in_optimized_module + + +def _callback_from_stance(callback: DynamoCallback) -> DynamoCallback: + if _stance.stance == "default": + # force_backend + if _stance.backend is not None and callback not in (False, None): + callback = _create_wrapped_callback(get_compiler_fn(_stance.backend)) + + return callback + elif _stance.stance == "eager_then_compile": + if callback not in (False, None): + return _create_delayed_compile_callback(callback, _stance.stance) + return callback + elif _stance.stance == "aot_eager_then_compile": + if callback not in (False, None): + return _create_delayed_compile_callback(callback, _stance.stance) + return callback + elif _stance.stance == "force_eager": + # disable + return None + elif _stance.stance == "eager_on_recompile": + # run mode + return False + elif _stance.stance == "fail_on_recompile": + if callback in (False, None): + return callback + + def fail_callback( + frame: DynamoFrameType, *args: Any, **kwargs: Any + ) -> ConvertFrameReturn: + if trace_rules.check(frame.f_code): + return ConvertFrameReturn() + if not convert_frame.has_tensor_in_frame(frame): + return ConvertFrameReturn() + + from torch._C._dynamo.eval_frame import ( + _debug_get_cache_entry_list, + _debug_get_precompile_entries, + ) + from torch._dynamo.guards import get_and_maybe_log_recompilation_reasons + + message = ( + "Detected recompile when torch.compile stance is 'fail_on_recompile'. " + + f"filename: '{frame.f_code.co_filename}', " + + f"function name: '{frame.f_code.co_name}', " + + f"line number: {frame.f_lineno}" + ) + cache_entries = _debug_get_cache_entry_list(frame.f_code) + if cache_entries: + reasons = get_and_maybe_log_recompilation_reasons( + cache_entries[0], frame, innermost_fn(callback), skip_logging=True + ) + if reasons: + failures = textwrap.indent("\n".join(reasons), "- ") + guard_failure_details = ( + f"triggered by the following guard failure(s):\n{failures}" + ) + message += f"\n{textwrap.indent(guard_failure_details, ' ')}" + precompile_entries = _debug_get_precompile_entries(frame.f_code) + if len(precompile_entries) > 0: + message += "\nFailed on the following precompiled guards: " + for entry in precompile_entries: + message += f"\n{entry.guard_manager}{entry.guard_manager.check_verbose(frame.f_locals)}" # type: ignore[attr-defined] + raise RuntimeError(message) + + # to prevent cache miss due to different backend + fail_callback._torchdynamo_orig_backend = callback # type: ignore[attr-defined] + + return fail_callback + else: + raise RuntimeError(f"invalid torch.compile stance '{_stance}'") + + +def _create_wrapped_callback( + compiler_fn: CompilerFn, +) -> convert_frame.CatchErrorsWrapper: + hooks = Hooks() + return convert_frame.catch_errors_wrapper( + convert_frame.convert_frame( # type: ignore[arg-type] + compiler_fn, + hooks, + ), + hooks, + ) + + +def _get_or_add_example_inputs(frame: DynamoFrameType) -> list[Any]: + key = frame.f_code.co_filename + str(frame.f_code.co_firstlineno) + example_inputs = get_example_inputs(key) + + if len(example_inputs) < 2: + example_inputs.append(clone_and_convert_to_meta(frame.f_locals)) + + return example_inputs + + +def _create_delayed_compile_callback( + callback: DynamoCallback, stance: str +) -> Callable[..., Any]: + def callback_fn(*args: Any, **kwargs: Any) -> convert_frame.ConvertFrameReturn: + frame = args[0] + example_inputs = _get_or_add_example_inputs(frame) + + if len(example_inputs) == 1: + if stance == "eager_then_compile": + return ConvertFrameReturn( + frame_exec_strategy=FrameExecStrategy( + FrameAction.DEFAULT, FrameAction.DEFAULT + ) + ) + elif stance == "aot_eager_then_compile": + aot_eager_fn = get_compiler_fn("aot_eager") + return _create_wrapped_callback(aot_eager_fn)(*args, **kwargs) + + dynamism = track_dynamism_across_examples(example_inputs) + code_context.get_context(frame.f_code)["dynamism"] = dynamism + compiler_fn = callback._torchdynamo_orig_backend._torchdynamo_orig_backend # type: ignore[union-attr] + return _create_wrapped_callback(compiler_fn)(*args, **kwargs) + + # to prevent cache miss due to different backend + callback_fn._torchdynamo_orig_backend = callback # type: ignore[attr-defined] + + return callback_fn + + +def _is_skip_guard_eval_unsafe_stance() -> bool: + return _stance.skip_guard_eval_unsafe + + +def _reset_guarded_backend_cache() -> None: + global cached_backends + for backend in cached_backends.values(): + if hasattr(backend, "reset"): + backend.reset() + cached_backends.clear() + + +DONT_WRAP_FILES = { + # For tracing into fx modules + inspect.getsourcefile(GraphModule), + join(dirname(dirname(__file__)), "onnx/_internal/fx/dynamo_graph_extractor.py"), +} + + +def _debug_get_cache_entry_list( + code: Union[types.CodeType, Callable[..., Any]], +) -> list[CacheEntry]: + """ + Given a code object or a callable object, retrieve the cache entries + stored in this code. + """ + if callable(code): + code = code.__code__ + return torch._C._dynamo.eval_frame._debug_get_cache_entry_list(code) + + +class OptimizedModule(torch.nn.Module): + """ + Wraps the original nn.Module object and later patches its + forward method to optimized self.forward method. + """ + + _torchdynamo_orig_callable: Callable[..., Any] + get_compiler_config: Callable[[], Any] + + _opt_mod_attributes = { + "_orig_mod", + "dynamo_ctx", + "_torchdynamo_orig_callable", + "get_compiler_config", + "forward", + "_forward", + "__dict__", + "named_children_walk", + "_super_module_initialized", + } + + def __init__(self, mod: torch.nn.Module, dynamo_ctx: _TorchDynamoContext) -> None: + # NOTE: this must go first, because attribute reads/writes of `self` + # uses `_orig_mod`, and sometimes users override `Module.__init__` to + # do attribute reads/writes on `self`. + # + # We also can't use regular setattr because `super().__setattr__` will + # complain for module value before `super().__init__()` + object.__setattr__(self, "_orig_mod", mod) + self._super_module_initialized = False + super().__init__() + self._super_module_initialized = True + + # Installs the params/buffer + self._orig_mod = mod # `super().__setattr__` will register this module + self.dynamo_ctx = dynamo_ctx + self._initialize() + self.training = self._orig_mod.training + + def __len__(self) -> int: + # Proxy the len call to the original module + if isinstance(self._orig_mod, Sized): + return len(self._orig_mod) + # Mimic python's default behavior for objects without a length + raise TypeError(f"{type(self._orig_mod).__name__} does not support len()") + + def _initialize(self) -> None: + # Do this stuff in constructor to lower overhead slightly + if isinstance(self.dynamo_ctx, DisableContext): + # No need to check trace rules + self.forward = self.dynamo_ctx(self._orig_mod.__call__) + elif config.wrap_top_frame or ( + isinstance(self._orig_mod.forward, types.MethodType) + and ( + trace_rules.check(self._orig_mod.forward) + or getattr(self._orig_mod, "_is_fsdp_managed_module", False) + ) + ): + # This may be a torch.nn.* instance in trace_rules.py which + # won't trigger a frame evaluation workaround to add an extra + # frame we can capture + self.forward = self.dynamo_ctx(external_utils.wrap_inline(self._orig_mod)) + else: + # Invoke hooks outside of dynamo then pickup the inner frame + self.forward = self.dynamo_ctx(self._orig_mod.__call__) + + if hasattr(self._orig_mod, "_initialize_hook"): + self._forward = self.forward + self.forward = self._call_lazy_check + + def __call__(self, *args: Any, **kwargs: Any) -> Any: + if torch.nn.modules.module._has_any_global_hook(): + warnings.warn( + "Using `torch.compile(module)` when there are global hooks on " + "modules (e.g., from `register_module_forward_hook`); this will" + " cause the hooks to fire an extra time for the " + "`OptimizedModule` created by `torch.compile(module)`. If this " + "causes undesired behavior, please try using `module.compile()`" + ", or use the per-module hooks instead", + stacklevel=2, + ) + with _set_in_optimized_module(): + return super().__call__(*args, **kwargs) + + def _aot_compile(self, inputs: list[torch._dynamo.aot_compile.ModelInput]) -> None: + """ + Experimental: AOT Compile a set of inputs and use that as the forward function + """ + model = self._orig_mod + hooks = self.dynamo_ctx._hooks + assert hooks is not None + if not config.enable_aot_compile: + raise RuntimeError( + "AOT Compile is not enabled, please set torch._dynamo.config.enable_aot_config=True" + ) + if not self.dynamo_ctx.fullgraph: + raise RuntimeError( + "Graph breaks are not supported with aot compile. Please use torch.compile(fullgraph=True)." + ) + + if not callable(self.dynamo_ctx.callback): + raise RuntimeError("aot compile requires a callable dynamo callback.") + + backend = innermost_fn( + self.dynamo_ctx.callback, unaltered_fn_attr="_torchdynamo_orig_backend" + ) + from torch._dynamo.aot_compile import aot_compile_module + + self.forward = aot_compile_module(model, inputs, hooks, backend) + + def _save_aot_compiled_module(self, path: Optional[str] = None) -> bytes: + if not config.enable_aot_compile: + raise RuntimeError( + "AOT Compile is not enabled, please set torch._dynamo.config.enable_aot_config=True" + ) + from torch._dynamo.aot_compile import AOTCompiledModel + + assert isinstance(self.forward, AOTCompiledModel) + result: bytes = self.forward.serialize() + if path is not None: + with open(path, "wb") as f: + f.write(result) + return result + + def _load_aot_compiled_module(self, data: bytes) -> None: + if not config.enable_aot_compile: + raise RuntimeError( + "AOT Compile is not enabled, please set torch._dynamo.config.enable_aot_config=True" + ) + from torch._dynamo.aot_compile import AOTCompiledModel + + compiled_forward = AOTCompiledModel.deserialize(self._orig_mod, data) + assert isinstance(compiled_forward, AOTCompiledModel) + self.forward = compiled_forward + + def __reduce__( + self, + ) -> tuple[type[OptimizedModule], tuple[torch.nn.Module, _TorchDynamoContext]]: + return (self.__class__, (self._orig_mod, self.dynamo_ctx)) + + def __getstate__(self) -> dict[str, Any]: + state = dict(self.__dict__) + state.pop("forward", None) + state.pop("__call__", None) + return state + + def __setstate__(self, state: dict[str, Any]) -> None: + self.__dict__ = state + self._initialize() + + @property + # pyrefly: ignore [bad-override] + def training(self) -> bool: + return self._orig_mod.training + + @training.setter + def training(self, value: bool) -> None: + # Ignore the `training` mutation in `super().__init__()`, since that's + # setting the default on `nn.Module`, but we are mirroring the + # `training` attr in `self._orig_mod`. + if self._super_module_initialized: + self._orig_mod.training = value + + def __getattr__(self, name: str) -> Any: + if name == "_orig_mod": + return self._modules["_orig_mod"] + return getattr(self._orig_mod, name) + + def __setattr__(self, name: str, val: Any) -> None: + # Allow patching over class attributes + if hasattr(type(self), name): + return super().__setattr__(name, val) + + if name in OptimizedModule._opt_mod_attributes: + return super().__setattr__(name, val) + return setattr(self._orig_mod, name, val) + + def __delattr__(self, name: str) -> None: + # This mirrors `__setattr__` + if hasattr(type(self), name): + return super().__delattr__(name) + + if name in OptimizedModule._opt_mod_attributes: + return super().__delattr__(name) + return delattr(self._orig_mod, name) + + def _call_lazy_check(self, *args: Any, **kwargs: Any) -> Any: + if ( + hasattr(self._orig_mod, "_initialize_hook") + and hasattr(self._orig_mod, "_infer_parameters") + and callable(self._orig_mod._infer_parameters) + ): + # In the case of a lazy module, we want to run + # the pre-hooks which initialize it. + # Afterwards, lazy module deletes its pre-hooks + # to avoid treating it as lazy on subsequent recompile. + self._orig_mod._infer_parameters(self._orig_mod, args, kwargs) + return self._forward(*args, **kwargs) + + def __dir__(self) -> list[str]: + orig_mod_attrs = self._orig_mod.__dir__() + return orig_mod_attrs + [ + attr for attr in super().__dir__() if attr not in orig_mod_attrs + ] + + +def remove_from_cache(f: Any) -> None: + """ + Make sure f.__code__ is not cached to force a recompile + """ + if isinstance(f, types.CodeType): + reset_code(f) + elif hasattr(f, "__code__"): + reset_code(f.__code__) + elif hasattr(getattr(f, "forward", None), "__code__"): + reset_code(f.forward.__code__) + else: + from . import reset # type: ignore[attr-defined] + + reset() + log.warning("could not determine __code__ for %s", f) + + +def nothing() -> None: + pass + + +def always_false() -> bool: + return False + + +def innermost_fn( + fn: Callable[..., Any], unaltered_fn_attr: str = "_torchdynamo_orig_callable" +) -> Callable[..., Any]: + """ + In case of nesting of _TorchDynamoContext calls, find the innermost + function. TorchDynamo caches on fn.__code__ object, so its necessary to find + the innermost function to pass on the optimize, run, disable etc. + """ + unaltered_fn = fn + while hasattr(unaltered_fn, unaltered_fn_attr): + unaltered_fn = getattr(unaltered_fn, unaltered_fn_attr) + assert callable(unaltered_fn), ( + f"A callable function is expected, but {type(unaltered_fn)} is provided." + ) + return unaltered_fn + + +def make_set_enable_dynamic(enable: bool) -> Any: + assert isinstance(enable, bool) + if enable: + # Assume everything is dynamic by default + return config._make_closure_patcher(assume_static_by_default=False) + else: + return config._make_closure_patcher( + automatic_dynamic_shapes=False, assume_static_by_default=True + ) + + +# A thread local storage that serves to store information as Dynamo traces +# through a user provided function. +class DynamoTLS(threading.local): + # Each string is a summary of a frame Dynamo attempted to trace, stored in + # temporal order. + traced_frame_infos: list[str] = [] + + +dynamo_tls = DynamoTLS() + + +def clear_dynamo_tls() -> None: + dynamo_tls.traced_frame_infos.clear() + + +@atexit.register +def _log_traced_frames() -> None: + """ + At program exit, log all of the frames Dynamo has attempted to trace from, + excluding the continuation frames generated by Dynamo. + """ + msg = "\n".join(dynamo_tls.traced_frame_infos) + msg = textwrap.indent(msg, " * ") + msg = f"TorchDynamo attempted to trace the following frames: [\n{msg}\n]" + log.info(msg) + + +def guard_collectives_hook(guard_eval_result: bool) -> bool: + import torch.distributed as dist + from torch._dynamo.utils import dynamo_timed + + # guard_eval_result == True ==> cache hit + if pg := distributed.get_guard_pg(): + with dynamo_timed( + "guard_collective", log_pt2_compile_event=False, log_waitcounter=True + ): + log.debug("guard_collective %s", guard_eval_result) + # TODO: a bit awkward to time, this isn't inside of the dynamo compile region + all_results = [None] * pg.size() + dist.all_gather_object(all_results, guard_eval_result, group=pg) + # True = everyone hit, OK to run + # False = someone missed, force recompile everywhere + res = all(all_results) + log.debug("guard_collective %s -> %s", guard_eval_result, res) + return res + return guard_eval_result + + +_not_set = object() + + +class _TorchDynamoContext: + def __init__( + self, + callback: DynamoCallback, + on_enter: Callable[[], Any] = nothing, + backend_ctx_ctor: Callable[ + [], contextlib.AbstractContextManager[Any] + ] = null_context, + patch_fn: Callable[[], Any] = nothing, + first_ctx: bool = False, + *, + fullgraph: bool = False, + error_on_graph_break: Optional[bool] = None, + export: bool = False, + dynamic: Optional[bool] = None, + compiler_config: Optional[Any] = None, + package: Optional[CompilePackage] = None, + hooks: Optional[Hooks] = None, + ) -> None: + super().__init__() + assert callable(callback) or callback is False or callback is None + self.callback: DynamoCallback = callback + self._backend_ctx_ctor = backend_ctx_ctor + self.prior: Union[Unset, DynamoCallback] = unset + self.first_ctx = first_ctx + self.fullgraph = fullgraph + self.error_on_graph_break = error_on_graph_break + self.export = export + self._dynamic = dynamic + self.compiler_config = compiler_config + self.cleanup_fns: list[Callable[[], Any]] = [] + self.enter_exit_hooks = [] + self._package = package + self._hooks = hooks + patch_fn() + + # Save the backends so that we can reset them during torch._dynamo.reset + backend = innermost_fn(callback, unaltered_fn_attr="_torchdynamo_orig_backend") # type: ignore[arg-type] + cached_backends.setdefault(id(backend), backend) # type: ignore[arg-type] + + if dynamic is not None: + self.enter_exit_hooks.append(make_set_enable_dynamic(dynamic)) + + if on_enter is not nothing: + # this case is not common + def call_on_enter() -> Callable[[], None]: + on_enter() + return nothing + + self.enter_exit_hooks.append(call_on_enter) + + if backend_ctx_ctor is not contextlib.nullcontext: + # this case is not common + def call_backend_ctx() -> functools.partial[Optional[bool]]: + ctx = backend_ctx_ctor() + ctx.__enter__() + return functools.partial(ctx.__exit__, None, None, None) + + self.enter_exit_hooks.append(call_backend_ctx) + + def __enter__(self) -> None: + if config.raise_on_ctx_manager_usage: + raise RuntimeError( + "torch._dynamo.optimize(...) is used with a context manager. " + "Please refer to https://pytorch.org/tutorials/intermediate/torch_compile_tutorial.html " + "to use torch._dynamo.optimize(...) as an annotation/decorator. " + ) + self.prior = set_eval_frame(None) + self.cleanup_fns = [enter() for enter in self.enter_exit_hooks] + self.prior_skip_guard_eval_unsafe = set_skip_guard_eval_unsafe( + _is_skip_guard_eval_unsafe_stance() + ) + _maybe_set_eval_frame(_callback_from_stance(self.callback)) + + def __exit__( + self, + exc_type: Optional[type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[types.TracebackType], + ) -> Optional[bool]: + assert self.prior is not unset + set_eval_frame(None) + set_skip_guard_eval_unsafe(self.prior_skip_guard_eval_unsafe) + for cleanup in self.cleanup_fns: + cleanup() + self.cleanup_fns.clear() + _maybe_set_eval_frame(_callback_from_stance(self.prior)) + self.prior = unset + return None + + def __call__(self, fn: Any) -> Any: + # public api for compiler config/options + def get_compiler_config() -> Any: + return self.compiler_config + + from .package import DynamoCache + + # If self._package is lazily initialized, we should check the dynamo cache now + if config.caching_precompile: + if self._package is not None and not self._package.is_initialized(): + fn_key = fn.forward if isinstance(fn, torch.nn.Module) else fn + result = DynamoCache.load(fn_key) + if result is None: + # Create a fresh CompilePackage + self._package.initialize(fn_key, None, ignore_inlined_sources=False) + else: + try: + self._package.initialize( + fn_key, result.dynamo, ignore_inlined_sources=False + ) + self._package.install(result.backends) + except RuntimeError: + log.warning( + "Failed to load entry from dynamo cache", exc_info=True + ) + self._package.initialize( + fn_key, None, ignore_inlined_sources=False + ) + + fn = innermost_fn(fn) + + def aot_compile(example_inputs: tuple[tuple[Any, ...], dict[str, Any]]) -> Any: + from torch._dynamo.aot_compile import aot_compile_fullgraph + + if torch._inductor.config.force_disable_caches: + raise RuntimeError( + "Cannot precompile with torch._inductor.config.force_disable_caches=True; caching is required." + ) + + if not self.fullgraph: + raise RuntimeError( + "Graph breaks are not supported with aot compile. Please use torch.compile(fullgraph=True)." + ) + + if not callable(self.callback): + raise RuntimeError("aot compile requires a callable dynamo callback.") + + assert self._hooks is not None + + return aot_compile_fullgraph( + fn, + example_inputs, + hooks=self._hooks, + backend=innermost_fn( + self.callback, unaltered_fn_attr="_torchdynamo_orig_backend" + ), + ) + + # add context containing GraphModule to any GraphModule forward functions + if isinstance(fn, GraphModule): + # add context containing GraphModule to any GraphModule forward functions + code_context.get_context(fn.forward.__code__)["orig_graphmodule"] = ( + weakref.ref(fn) + ) + + # Optimize the forward method of torch.nn.Module object + if isinstance(fn, torch.nn.Module): + mod = fn + new_mod = OptimizedModule(mod, self) + # Save the function pointer to find the original callable while nesting + # of decorators. + new_mod._torchdynamo_orig_callable = mod.forward + + # when compiling torch.nn.Module, + # provide public api OptimizedModule.get_compiler_config() + assert not hasattr(new_mod, "get_compiler_config") + new_mod.get_compiler_config = get_compiler_config + + return new_mod + + if inspect.isclass(fn): + # User has wrapped the class with compile/disable decorator. Apply + # disable to init/call method. + cls_obj = fn + cls_obj.__call__ = self(cls_obj.__call__) + if issubclass(cls_obj, torch.nn.Module): + # NN module variable tracker directly inlines the _call_impl. + cls_obj._call_impl = self(cls_obj._call_impl) + return cls_obj + + assert callable(fn), ( + f"A callable function is expected, but {type(fn)} is provided." + ) + + try: + filename = inspect.getsourcefile(fn) + except TypeError: + filename = None + if config.debug_force_nested_calls: + fn = external_utils.wrap_inline(fn) + elif config.wrap_top_frame or ( + (filename is None or trace_rules.check(fn)) + and ( + getattr(fn, "__name__", "") + not in ["_call_impl", "_wrapped_call_impl", "_lazy_forward"] + ) + and filename not in DONT_WRAP_FILES + ): + # call to a builtin without a frame for us to capture + fn = external_utils.wrap_inline(fn) + + def do_nothing(*arg: Any, **kwargs: Any) -> None: + pass + + callback: Callable[..., Any] = do_nothing + if hasattr(self, "callback"): + callback = self.callback # type: ignore[assignment] + + is_jit_tracing = torch._C._is_tracing + is_fx_symbolic_tracing = torch.fx._symbolic_trace.is_fx_symbolic_tracing + + @functools.wraps(fn) + def compile_wrapper(*args: Any, **kwargs: Any) -> Any: + prior = set_eval_frame(None) + try: + # We shouldn't compile inside kernel invocation. + if tracing_context := torch._guards.TracingContext.try_get(): + if ( + tracing_context.fake_mode is not None + and tracing_context.fake_mode.in_kernel_invocation + ): + return fn(*args, **kwargs) + # Skip nested compile - just inline the function + if is_fx_symbolic_tracing(): + if config.error_on_nested_fx_trace: + raise RuntimeError( + "Detected that you are using FX to symbolically trace " + "a dynamo-optimized function. This is not supported at the moment." + ) + else: + return fn(*args, **kwargs) + + if is_jit_tracing(): + raise RuntimeError( + "Detected that you are using FX to torch.jit.trace " + "a dynamo-optimized function. This is not supported at the moment." + ) + + cleanups = [enter() for enter in self.enter_exit_hooks] + prior_skip_guard_eval_unsafe = set_skip_guard_eval_unsafe( + _is_skip_guard_eval_unsafe_stance() + ) + prior_error_on_graph_break = None + if not self.fullgraph and self.error_on_graph_break is not None: + prior_error_on_graph_break = _get_error_on_graph_break() + _set_error_on_graph_break(self.error_on_graph_break) + + # Ensure that if an assertion occurs after graph pushes + # something onto the DynamicLayerStack then we pop it off (the + # constructed graph code isn't guarded with try/finally). + # + # This used to be a context but putting a `with` here is a noticeable + # perf regression (#126293) + saved_dynamic_layer_stack_depth = ( + torch._C._functorch.get_dynamic_layer_stack_depth() + ) + + _maybe_set_eval_frame(_callback_from_stance(callback)) + + try: + return fn(*args, **kwargs) + except Unsupported as e: + if config.verbose: + raise + # strip internal tracebacks from causes + cur_exn: BaseException = e + while cur_exn.__cause__ is not None: + cur_exn.__cause__.with_traceback(None) + cur_exn = cur_exn.__cause__ + # pyrefly: ignore [invalid-inheritance] + raise e.with_traceback(None) from e.__cause__ # User compiler error + except ShortenTraceback as e: + # Failures in the backend likely don't have useful + # data in the TorchDynamo frames, so we strip them out. + raise e.remove_dynamo_frames() from None # see TORCHDYNAMO_VERBOSE=1 + finally: + # Restore the dynamic layer stack depth if necessary. + set_eval_frame(None) + if prior_error_on_graph_break is not None: + _set_error_on_graph_break(prior_error_on_graph_break) + torch._C._functorch.pop_dynamic_layer_stack_and_undo_to_depth( + saved_dynamic_layer_stack_depth + ) + + set_skip_guard_eval_unsafe(prior_skip_guard_eval_unsafe) + for cleanup in cleanups: + cleanup() + finally: + _maybe_set_eval_frame(prior) + + # hooks to properly handle inlining + if self.error_on_graph_break is not None: + compile_wrapper._torchdynamo_inline = ( # type: ignore[attr-defined] + external_utils.wrap_inline_with_error_on_graph_break( + fn, self.error_on_graph_break + ) + ) + else: + compile_wrapper._torchdynamo_inline = fn # type: ignore[attr-defined] + + # Save the function pointer to find the original callable while nesting + # of decorators. + compile_wrapper._torchdynamo_orig_callable = fn # type: ignore[attr-defined] + + # when compiling user function instead of nn.Module + # provide public api _fn.get_compiler_config() + assert not hasattr(compile_wrapper, "get_compiler_config") + compile_wrapper.get_compiler_config = get_compiler_config # type: ignore[attr-defined] + if torch._dynamo.config.enable_aot_compile: + compile_wrapper.aot_compile = aot_compile # type: ignore[attr-defined] + + # If the function is called using torch._dynamo.optimize decorator, we + # should prevent any type of skipping. + if callback not in (None, False): + if not hasattr(fn, "__code__"): + raise RuntimeError( + textwrap.dedent( + """ + + torch._dynamo.optimize is called on a non function object. + If this is a callable class, please wrap the relevant code into a function and optimize the + wrapper function. + + >> class CallableClass: + >> def __init__(self) -> None: + >> super().__init__() + >> self.relu = torch.nn.ReLU() + >> + >> def __call__(self, x): + >> return self.relu(torch.sin(x)) + >> + >> def print_hello(self): + >> print("Hello world") + >> + >> mod = CallableClass() + + If you want to optimize the __call__ function and other code, wrap that up in a function + + >> def wrapper_fn(x): + >> y = mod(x) + >> return y.sum() + + and then optimize the wrapper_fn + + >> opt_wrapper_fn = torch._dynamo.optimize(wrapper_fn) + """ + ) + ) + always_optimize_code_objects[fn.__code__] = True + + return compile_wrapper + + +class OptimizeContext(_TorchDynamoContext): + def __init__( + self, + callback: DynamoCallback, + backend_ctx_ctor: Callable[[], contextlib.AbstractContextManager[Any]], + first_ctx: bool = False, + *, + fullgraph: bool = False, + error_on_graph_break: Optional[bool] = None, + export: bool = False, + dynamic: Optional[bool] = None, + compiler_config: Optional[Any] = None, + rebuild_ctx: Optional[ + Callable[[], Union[OptimizeContext, _NullDecorator]] + ] = None, + package: Optional[CompilePackage] = None, + hooks: Optional[Hooks] = None, + ) -> None: + def on_enter() -> None: + install_generation_tagging_init() + + super().__init__( + callback=callback, + on_enter=on_enter, + backend_ctx_ctor=backend_ctx_ctor, + patch_fn=TorchPatcher.patch, + first_ctx=first_ctx, + fullgraph=fullgraph, + error_on_graph_break=error_on_graph_break, + export=export, + dynamic=dynamic, + compiler_config=compiler_config, + package=package, + hooks=hooks, + ) + + if config.compiled_autograd: + _dynamic = self._dynamic + if _dynamic is None: + _dynamic = not torch._dynamo.config.assume_static_by_default + + def call_compiled_autograd() -> functools.partial[Optional[bool]]: + assert rebuild_ctx is not None + compiler_fn = rebuild_ctx() + ctx = torch._dynamo.compiled_autograd._enable( + compiler_fn, + # pyrefly: ignore [bad-argument-type] + dynamic=_dynamic, + ignore_active_disable_ctx=False, + ) + ctx.__enter__() + return functools.partial(ctx.__exit__, None, None, None) + + self.enter_exit_hooks.append(call_compiled_autograd) + + def __reduce__( + self, + ) -> tuple[type[OptimizeContext], tuple[Any, ...], dict[str, Any]]: + return ( + self.__class__, + (self.callback, self._backend_ctx_ctor, self.first_ctx), + { + "export": self.export, + "dynamic": self._dynamic, + "compiler_config": self.compiler_config, + }, + ) + + +class RunOnlyContext(_TorchDynamoContext): + def __init__(self) -> None: + # cudagraph trees relies on generation increment + def on_enter() -> None: + torch._dynamo.mutation_guard.GenerationTracker.generation += 1 + + super().__init__(callback=False, on_enter=on_enter) + + def __reduce__(self) -> tuple[type[RunOnlyContext], tuple[Any, ...]]: + return (self.__class__, ()) + + +class DisableContext(_TorchDynamoContext): + def __init__(self, msg: Optional[str] = None, wrapping: bool = True) -> None: + super().__init__(callback=None) + self.msg = msg + self.wrapping = wrapping + + def __call__(self, fn: Callable[..., Any]) -> Callable[..., Any]: + # Earlier this code was in the base class _TorchDynamoContext. But we + # moved it here to have better code organization. For disable, we just + # want the callback to be None. We don't have to check trace_rules or + # create any wrapper. + fn = innermost_fn(fn) + + if isinstance(fn, torch.nn.Module): + mod = fn + new_mod = OptimizedModule(mod, self) + new_mod._torchdynamo_orig_callable = mod.forward + return new_mod + + if isinstance(fn, type): + # User has wrapped the class with compile/disable decorator. Apply + # disable to init/call method. + cls_obj = fn + # Disable on init is useful for reconstruction of bytecodes where we + # want to prevent Dynamo from tracing into the init function. Check + # test_reconstruction in test_model_output.py. + cls_obj.__init__ = self(cls_obj.__init__) # type: ignore[misc] + cls_obj.__call__ = self(cls_obj.__call__) + if issubclass(cls_obj, torch.nn.Module): + # NN module variable tracker directly inlines the _call_impl. Disable it. + # pyrefly: ignore [missing-attribute] + cls_obj._call_impl = self(cls_obj._call_impl) + return cls_obj + + assert callable(fn), ( + f"A callable function is expected, but {type(fn)} is provided." + ) + + def _fn(*args: Any, **kwargs: Any) -> Any: + prior = set_eval_frame(None) + try: + _maybe_set_eval_frame(_callback_from_stance(self.callback)) + try: + if torch.compiler.is_exporting(): + with fx_traceback.annotate( + { + "_torchdynamo_disable": True, + "_torchdynamo_disable_recursive": True, + "_torchdynamo_disable_method": getattr( + fn, "__name__", type(fn).__name__ + ), + } + ): + return fn(*args, **kwargs) + return fn(*args, **kwargs) + finally: + set_eval_frame(None) + finally: + _maybe_set_eval_frame(prior) + + # Under some circumstances (e.g. precompile) we can end up calling @disable + # decorator in generated bytecode and trigger recompile. This is due to the + # fact that the old callback from torch.compile() is still active and under + # this circumstance we will trigger a failure with set_stance("fail_on_recompile"). + # Therefore we want to skip calling into any frame in this case. + if self.wrapping: + _fn = functools.wraps(fn)(_fn) + + _fn._torchdynamo_disable = True # type: ignore[attr-defined] + _fn._torchdynamo_disable_msg = self.msg # type: ignore[attr-defined] + + # Save the function pointer to find the original callable while nesting + # of decorators. + _fn._torchdynamo_orig_callable = fn # type: ignore[attr-defined] + + _fn._torchdynamo_disable_recursive = True # type: ignore[attr-defined] + + return _fn + + def __reduce__(self) -> tuple[type[DisableContext], tuple[Any, ...]]: + return (self.__class__, ()) + + +def _optimize_catch_errors( + compile_fn: convert_frame.ConvertFrameProtocol, + hooks: Hooks, + backend_ctx_ctor: Callable[ + [], contextlib.AbstractContextManager[Any] + ] = null_context, + fullgraph: bool = False, + error_on_graph_break: Optional[bool] = None, + export: bool = False, + dynamic: Optional[bool] = None, + compiler_config: Optional[Any] = None, + rebuild_ctx: Optional[Callable[[], Union[OptimizeContext, _NullDecorator]]] = None, + package: Optional[CompilePackage] = None, +) -> OptimizeContext: + return OptimizeContext( + convert_frame.catch_errors_wrapper(compile_fn, hooks), + backend_ctx_ctor=backend_ctx_ctor, + first_ctx=True, + fullgraph=fullgraph, + error_on_graph_break=error_on_graph_break, + export=export, + dynamic=dynamic, + compiler_config=compiler_config, + rebuild_ctx=rebuild_ctx, + package=package, + hooks=hooks, + ) + + +def get_compiler_fn( + compiler_fn: Union[str, Callable[..., Any], None], +) -> WrapBackendDebug: + from .repro.after_dynamo import wrap_backend_debug + + if compiler_fn is None: + # Special case None to avoid crashing in hasattr + compiler_str = None + elif hasattr(compiler_fn, "compiler_name"): + compiler_str = compiler_fn.compiler_name # type: ignore[union-attr] + assert isinstance(compiler_str, str) + elif isinstance(compiler_fn, str): + compiler_str = compiler_fn + else: + compiler_str = None + compiler_fn = lookup_backend(compiler_fn) # type: ignore[arg-type] + return wrap_backend_debug(compiler_fn, compiler_str) + + +class _NullDecorator(contextlib.nullcontext): # type: ignore[type-arg] + def __call__(self, fn: Callable[..., Any]) -> Callable[..., Any]: + assert callable(fn), ( + f"A callable function is expected, but {type(fn)} is provided." + ) + return fn + + +# Make dynamo graph to have same input/output spec as user code +def argument_names( + f_sig: inspect.Signature, + args: Union[list[Any], tuple[Any, ...]], + kwargs: dict[str, Any], +) -> list[str]: + def signature_to_fullargspec(sig: inspect.Signature) -> inspect.FullArgSpec: + # Get a list of Parameter objects from the Signature object + params = list(sig.parameters.values()) + # Separate positional arguments, keyword-only arguments and varargs/varkw + args = [ + p.name for p in params if p.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD + ] + kwonlyargs = [ + p.name for p in params if p.kind == inspect.Parameter.KEYWORD_ONLY + ] + varargs = next( + (p.name for p in params if p.kind == inspect.Parameter.VAR_POSITIONAL), + None, + ) + varkw = next( + (p.name for p in params if p.kind == inspect.Parameter.VAR_KEYWORD), + None, + ) + # Get default values for positional arguments and keyword-only arguments + defaults = tuple( + p.default + for p in params + if p.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD + and p.default is not inspect.Parameter.empty + ) + kwonlydefaults = { + p.name: p.default + for p in params + if p.kind == inspect.Parameter.KEYWORD_ONLY + and p.default is not inspect.Parameter.empty + } + # Get annotations for parameters and return value + annotations = {} + if sig.return_annotation: + annotations = {"return": sig.return_annotation} + for parameter in params: + annotations[parameter.name] = parameter.annotation + # Return a FullArgSpec object with the extracted attributes + return inspect.FullArgSpec( + args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations + ) + + fullargspec = signature_to_fullargspec(f_sig) + + # 1. Map `args` 1-to-1 to positional arguments in original signature. + input_strs = fullargspec.args[: len(args)] + + if len(args) > len(fullargspec.args): + # 2. If there are more arguments left in `args`, they map to varargs in original + # signature. Assign names as {varargs}_0, {varargs}_1, ... + assert fullargspec.varargs is not None, "More arguments than expected" + input_strs += [ + f"{fullargspec.varargs}_{i}" for i in range(len(args) - len(input_strs)) + ] + elif len(args) < len(fullargspec.args): + # 3. If there are fewer arguments in `args` than `fullargspec.args`, + # it implies these are arguments either with default values, or provided in + # `kwargs`. The former can be safely ignored. Because Dynamo.export does not + # export them as part of the function signature. The latter will be handled + # in the next step. + for unprovided_arg in fullargspec.args[ + len(args) : -len(fullargspec.defaults or []) + ]: + assert unprovided_arg in kwargs, f"Missing argument {unprovided_arg}" + + # 4. Keyword arguments provided in `kwargs`. + input_strs += list(kwargs.keys()) + + # 5. Keyword-only arguments with default values if not provided are not exported + # as part of the function signature. + for kwonly_arg in fullargspec.kwonlyargs: + kwonlydefaults = fullargspec.kwonlydefaults or {} + assert kwonly_arg in kwargs or kwonly_arg in kwonlydefaults, ( + f"Missing keyword only argument {kwonly_arg}" + ) + + return input_strs + + +def check_if_dynamo_supported() -> None: + if sys.version_info >= (3, 15): + raise RuntimeError("Python 3.15+ not yet supported for torch.compile") + elif sysconfig.get_config_var("Py_GIL_DISABLED") == 1 and sys.version_info < ( + 3, + 13, + 3, + ): + raise RuntimeError( + "torch.compile is not supported on Python < 3.13.3 built with GIL disabled. " + "Please use Python 3.13.3+." + ) + + +def is_dynamo_supported() -> bool: + try: + check_if_dynamo_supported() + return True + except Exception: + return False + + +def check_if_inductor_supported() -> None: + check_if_dynamo_supported() + + +def is_inductor_supported() -> bool: + try: + check_if_inductor_supported() + return True + except Exception: + return False + + +def check_for_incompatible_configs() -> None: + # Some of the configs should be mutually exclusive + assert not (config.suppress_errors and config.fail_on_recompile_limit_hit), ( + "Dynamo configs suppress_error and fail_on_recompile_limit_hit can not both be active at the same time." + ) + + +def optimize(*args: Any, **kwargs: Any) -> Union[OptimizeContext, _NullDecorator]: + def rebuild_ctx() -> Union[OptimizeContext, _NullDecorator]: + ca_kwargs_override = config.compiled_autograd_kwargs_override + if ca_kwargs_override: + # NOTE: The process of translating other `torch.compile` kwargs to `torch._dynamo.optimize` kwargs + # is more complicated, we will add it in the future when needed. + assert set(ca_kwargs_override.keys()) == {"fullgraph"}, ( + f"Only `fullgraph` kwarg override is supported for now, but got {ca_kwargs_override.keys()}" + ) + kwargs["nopython"] = ca_kwargs_override["fullgraph"] + return optimize(*args, **kwargs) + + return _optimize(rebuild_ctx, *args, **kwargs) + + +def _optimize( + rebuild_ctx: Callable[[], Union[OptimizeContext, _NullDecorator]], + backend: Union[str, Callable[..., Any]] = "inductor", + *, + nopython: bool = False, + error_on_graph_break: Optional[bool] = None, + guard_export_fn: Optional[Callable[[_guards.GuardsSet], None]] = None, + guard_fail_fn: Optional[Callable[[GuardFail], None]] = None, + guard_filter_fn: Optional[Callable[[list[GuardFilterEntry]], list[bool]]] = None, + disable: bool = False, + dynamic: Optional[bool] = None, + package: Optional[CompilePackage] = None, +) -> Union[OptimizeContext, _NullDecorator]: + """ + The main entrypoint of TorchDynamo. Do graph capture and call + backend() to optimize extracted graphs. + + Args: + backend: One of the two things: + - Either, a function/callable taking a torch.fx.GraphModule and + example_inputs and returning a python callable that runs the + graph faster. + One can also provide additional context for the backend, like + torch.jit.fuser("fuser2"), by setting the backend_ctx_ctor attribute. + See AOTAutogradMemoryEfficientFusionWithContext for the usage. + - Or, a string backend name in `torch._dynamo.list_backends()` + nopython: If True, graph breaks will be errors and there will + be a single whole-program graph. + error_on_graph_break: If not None, the current `error_on_graph_break` setting is set to the given value. + See `torch._dynamo.error_on_graph_break()` for more details on what `error_on_graph_break` means. + + Unlike `nopython=True` (i.e. `fullgraph=True`), there is no guarantee of a single whole-program graph. + If `nopython` is True, `error_on_graph_break` does nothing. + disable: If True, turn this decorator into a no-op + dynamic: If True, upfront compile as dynamic a kernel as possible. If False, + disable all dynamic shapes support (always specialize). If None, automatically + detect when sizes vary and generate dynamic kernels upon recompile. + + Example Usage:: + + @torch._dynamo.optimize() + def toy_example(a, b): ... + """ + check_if_dynamo_supported() + check_for_incompatible_configs() + # Note: The hooks object could be global instead of passed around, *however* that would make + # for a confusing API usage and plumbing story wherein we nest multiple .optimize calls. + # There is some prior art around this, w/r/t nesting backend calls are enforced to be the same + # compiler, however, this feels onerous for callback and hooks, and it feels better to give our users an + # easier to understand UX at the cost of a little more plumbing on our end. + hooks = Hooks( + guard_export_fn=guard_export_fn, + guard_fail_fn=guard_fail_fn, + guard_filter_fn=guard_filter_fn, + ) + torch._C._log_api_usage_once("torch._dynamo.optimize") + if ( + disable + or os.environ.get("TORCHDYNAMO_DISABLE", "") == "1" + or (not justknobs_check("pytorch/compiler:enable_dynamo")) + ): + return _NullDecorator() + + if nopython and not config.debug_force_graph_break_on_leaf_return: + return optimize_assert( + backend, + dynamic=dynamic, + hooks=hooks, + rebuild_ctx=rebuild_ctx, + package=package, + ) + + backend = get_compiler_fn(backend) + + # Find if backend has any extra context manager + backend_ctx_ctor = getattr(backend, "backend_ctx_ctor", null_context) + + # The backend function is stashed in the callable returned by + # _optimize_catch_errors in the field _torchdynamo_orig_backend. This can + # be used by eval_frame.c to insert a guard on the backend. + + # With CachingPrecompile, instantiate an uninitialized CompilePackage + # which gets initialized by _optimize_catch_errors.__call__ once we have a function + if config.caching_precompile and package is None: + from .package import CompilePackage + + package = CompilePackage(fn=None, dynamo=None, ignore_inlined_sources=False) + + return _optimize_catch_errors( + convert_frame.convert_frame( + backend, + hooks, + package=package, + ), + hooks, + backend_ctx_ctor, + fullgraph=False, + error_on_graph_break=error_on_graph_break + and not config.debug_force_graph_break_on_leaf_return, + dynamic=dynamic, + compiler_config=( + backend.get_compiler_config() + if hasattr(backend, "get_compiler_config") + else None + ), + rebuild_ctx=rebuild_ctx, + package=package, + ) + + +# TODO(voz): Consider making "explain" output alongside a run / part of a run +@patch("torch._dynamo.symbolic_convert.explain", True) +def explain(f: Callable[..., Any], *extra_args: Any, **extra_kwargs: Any) -> Any: + from .backends.debugging import ExplainOutput + + def inner(*args: Any, **kwargs: Any) -> ExplainOutput: + # TODO(voz): Do we want a decorator for this? + from . import reset # type: ignore[attr-defined] + + reset() + + graphs: list[torch.fx.GraphModule] = [] + break_reasons: list[Any] = [] + op_count: int = 0 + ops_per_graph: list[list[Target]] = [] + out_guards: list[_guards.Guard] = [] + + def dynamo_graph_accumulating_compiler( + gm: torch.fx.GraphModule, example_inputs: Any + ) -> Callable[..., Any]: + from .backends.debugging import _explain_graph_detail + + nonlocal graphs + nonlocal op_count + nonlocal ops_per_graph + nonlocal break_reasons + + gm, graphs, op_count, ops_per_graph, break_reasons = _explain_graph_detail( + gm, graphs, op_count, ops_per_graph, break_reasons + ) + + return gm.forward + + def guard_export_print(guards: Iterable[_guards.Guard]) -> None: + nonlocal out_guards + out_guards.extend(guards) + + opt_f = optimize( + dynamo_graph_accumulating_compiler, + nopython=False, + guard_export_fn=guard_export_print, + )(f) + # TODO(voz): We may have instances of `f` that mutate inputs, we should track sideeffects and reject. + opt_f(*args, **kwargs) + + graph_count = len(graphs) + graph_break_count = graph_count - 1 + compile_time = compile_times(repr="str") + + # TODO(voz): Do we want a decorator for this? + reset() + + return ExplainOutput( + graphs, + graph_count, + graph_break_count, + break_reasons, + op_count, + ops_per_graph, + out_guards, + compile_time, + ) + + if extra_args or extra_kwargs: + warnings.warn( + "explain(f, *args, **kwargs) is deprecated, use explain(f)(*args, **kwargs) instead. " + "If you don't migrate, we may break your explain call in the future if your user defined kwargs " + "conflict with future kwargs added to explain(f).", + FutureWarning, + stacklevel=2, + ) + return inner(*extra_args, **extra_kwargs) + else: + return inner + + +class FlattenInputOutputSignature(torch.fx.Transformer): + def __init__( + self, + m: torch.fx.GraphModule, + flat_args: list[Any], + matched_input_elements_positions: list[int], + flat_results: Sequence[Any], + matched_output_elements_positions: list[int], + example_fake_inputs: list[torch.Tensor], + flat_args_dynamic_dims: list[set[int]], + fake_mode: Optional[fake_tensor.FakeTensorMode] = None, + ) -> None: + super().__init__(m) + + assert len(flat_args_dynamic_dims) == len(flat_args) + matched_input_elements_to_fake = { + val: example_fake_inputs[ix] + for ix, val in enumerate(matched_input_elements_positions) + } + + self.new_args = [] + for i in range(len(flat_args)): + arg = super().placeholder(f"arg{i}", (), {}) + if i in matched_input_elements_to_fake: + arg.node.meta["val"] = matched_input_elements_to_fake[i] + else: + # Fill node.meta["val"] with faketensor from the input, + # if it's not found in matched_input_elements_positions + if fake_mode is not None and isinstance(flat_args[i], torch.Tensor): + # TODO(zhxchen17) Also preserve all the user constraints here. + arg.node.meta["val"] = fake_mode.from_tensor( + flat_args[i], + symbolic_context=StatelessSymbolicContext( + dynamic_sizes=[ + ( + DimDynamic.DYNAMIC + if d in flat_args_dynamic_dims[i] + else DimDynamic.STATIC + ) + for d in range(len(flat_args[i].shape)) + ], + constraint_sizes=[None] * len(flat_args[i].shape), + ), + ) + elif isinstance(flat_args[i], _IntWrapper): + arg.node.meta["val"] = flat_args[i].val + else: + arg.node.meta["val"] = flat_args[i] + + self.new_args.append(arg) + self.old_args_gen = (self.new_args[i] for i in matched_input_elements_positions) + self.matched_output_elements_positions = matched_output_elements_positions + self.flat_results = flat_results + + def placeholder( + self, target: Target, args: tuple[Argument, ...], kwargs: dict[str, Any] + ) -> Any: + arg = next(self.old_args_gen) + if "val" in self.current_node.meta: + arg.node.meta["val"] = self.current_node.meta["val"] + if "tensor_dict" in self.current_node.meta: + arg.node.meta["tensor_dict"] = self.current_node.meta["tensor_dict"] + if "example_value" in self.current_node.meta: + # NB: intentionally do not use set_example_value + arg.node.meta["example_value"] = self.current_node.meta["example_value"] + if "unbacked_bindings" in self.current_node.meta: + arg.node.meta["unbacked_bindings"] = self.current_node.meta[ + "unbacked_bindings" + ] + return arg + + def output( + self, target: Target, args: tuple[Argument, ...], kwargs: dict[str, Any] + ) -> Any: + dynamo_result_flat = args[0] + lookup = [*dynamo_result_flat, *self.new_args] # type: ignore[misc] + new_results_flat = [] + for i in range(len(self.flat_results)): + if self.matched_output_elements_positions[i] is not None: + new_results_flat.append( + lookup[self.matched_output_elements_positions[i]] + ) + else: + const_val = self.flat_results[i] + assert isinstance(const_val, tuple(common_constant_types)) + new_results_flat.append(const_val) + return super().output(target, (new_results_flat,), {}) + + def run_node(self, n: Node) -> Any: + self.current_node = n + result_proxy = super().run_node(n) + if "val" in self.current_node.meta: + result_proxy.node.meta["val"] = self.current_node.meta["val"] + if "example_value" in self.current_node.meta: + # NB: intentionally do not use set_example_value + result_proxy.node.meta["example_value"] = self.current_node.meta[ + "example_value" + ] + if "unbacked_bindings" in self.current_node.meta: + result_proxy.node.meta["unbacked_bindings"] = self.current_node.meta[ + "unbacked_bindings" + ] + if self.current_node.op != "output": + result_proxy.node._rename( + getattr(self.current_node, "name", result_proxy.node.name) + ) + return result_proxy + + def transform(self) -> torch.fx.GraphModule: + result_gm = super().transform() + if "dynamo_flat_name_to_original_fqn" in self.module.meta: # type: ignore[operator] + result_gm.meta["dynamo_flat_name_to_original_fqn"] = self.module.meta[ # type: ignore[index] + "dynamo_flat_name_to_original_fqn" # type: ignore[index] + ] + if "dynamo_compile_id" in self.module.meta: # type: ignore[operator] + result_gm.meta["dynamo_compile_id"] = self.module.meta["dynamo_compile_id"] # type: ignore[index] + return result_gm + + +class ExportResult(NamedTuple): + graph_module: torch.fx.GraphModule + guards: _guards.GuardsSet + # NB: Do not add new fields without overriding __iter__; people are + # destructuring so it is BC-breaking + + +# NOTE: this function only supports graphs created by Dynamo's OutputGraph module +def check_signature_rewritable(graph: torch.fx.GraphModule) -> None: + input_errors = [] + for node in graph.graph.find_nodes(op="placeholder"): + # set in OutputGraph._call_user_compiler + assert hasattr(node, "_dynamo_source") + assert hasattr(graph, "_source_to_user_stacks") + + # NOTE: We can safely ignore these type warnings if and only if + # the function is made from OutputGraph (checked in the assertions) + source = node._dynamo_source # type: ignore[attr-defined] + user_stacks = graph._source_to_user_stacks.get(source) # type: ignore[operator, union-attr] + if user_stacks is None: + continue + assert len(user_stacks) > 0 + # In some cases we may not have a useful stack. Look for a + # useful stack + stack = None + for s in user_stacks: + if len(s) == 0: + continue + stack = s + break + if stack is None: + msg = f"{source.name}, a closed over free variable" + else: + tb = "".join(traceback.format_list(stack)) + extra = "" + if len(user_stacks) > 1: + extra = f"(elided {len(user_stacks) - 1} more accesses)" + msg = f"{source.name}, accessed at:\n{tb}{extra}" + # TODO: option to print ALL of the stack traces at once + input_errors.append(msg) + + if input_errors: + raise UserError( + UserErrorType.INVALID_INPUT, + "Cannot export model which references tensors that are neither " + "buffers/parameters/constants nor are direct inputs. For each tensor, if you'd " + "like this tensor to be an explicit input, add it as a dummy argument " + "to the top-level model definition you are exporting; if you would " + "like its value to be embedded as an exported constant, wrap its access " + "in a function marked with @assume_constant_result.\n\n" + + "\n\n".join(input_errors), + ) + + +def check_user_input_output(flat_values: list[Any], error_type: UserErrorType) -> None: + supported_types = [ + torch.Tensor, + torch.SymInt, + torch.SymFloat, + torch.SymBool, + torch._C.ScriptObject, + _IntWrapper, + ] + list(common_constant_types) + + def is_supported_type(val: Any) -> bool: + return isinstance(val, tuple(supported_types)) + + value_type = "input" if error_type == UserErrorType.INVALID_INPUT else "output" + # We only check that the outputs are not None. Inputs can be None. + for v in flat_values: + if not is_supported_type(v): + if error_type == UserErrorType.INVALID_INPUT and v is None: + continue + + raise UserError( + error_type, + f"It looks like one of the {value_type}s with type `{type(v)}` " + "is not supported or pytree-flattenable. \n" + f"Exported graphs {value_type}s can only contain the " + f"following supported types: {supported_types}. \n" + "If you are using a custom class object, " + "please register a pytree_flatten/unflatten function " + "using `torch.utils._pytree.register_pytree_node` or " + "`torch.export.register_dataclass`.", + ) + + +def rewrite_signature( + f_sig: inspect.Signature, + graph: torch.fx.GraphModule, + fake_mode: Optional[fake_tensor.FakeTensorMode], + flat_args: list[Any], + in_spec: pytree.TreeSpec, + example_fake_inputs: list[Any], + graph_captured_input: Iterable[Any], + graph_captured_output: Optional[Iterable[Any]], + dynamo_traced_result: Any, + flat_args_dynamic_dims: list[set[int]], +) -> torch.fx.GraphModule: + orig_args, orig_kwargs = pytree.tree_unflatten(flat_args, in_spec) + + check_user_input_output(flat_args, UserErrorType.INVALID_INPUT) + flat_results_traced, out_spec_traced = pytree.tree_flatten(dynamo_traced_result) + check_user_input_output(flat_results_traced, UserErrorType.INVALID_OUTPUT) + + def check_optional_input_and_error(f_sig: inspect.Signature) -> None: + # Check if function has optional input. + for name, param in f_sig.parameters.items(): + if param.default is not inspect.Parameter.empty: + import torch._dynamo.graph_break_hints as graph_break_hints + from torch._dynamo.exc import unimplemented + + log.error( + "Parameter %s is optional with a default value of %s", + name, + param.default, + ) + unimplemented( + gb_type="rewrite_signature: cannot trace optional function input", + context="", + explanation=f"Parameter {name} is optional with a default value of {param.default}. This is not supported yet.", + hints=[ + *graph_break_hints.SUPPORTABLE, + ], + ) + + def produce_matching( + debug_type: str, sources: Iterable[Any], candidates: Iterable[Any] + ) -> list[Optional[int]]: + matched_elements_positions: list[Optional[int]] = [] + dict_of_source_vals = {} + for i, val in enumerate(sources): + dict_of_source_vals[id(val)] = i + + for val in candidates: + if isinstance(val, tuple(common_constant_types)): + matched_elements_positions.append(None) + elif id(val) not in dict_of_source_vals: + if debug_type == "inputs": + check_optional_input_and_error(f_sig) + raise AssertionError( + f"Unexpectedly found a {type(val)} in the {debug_type}.\n" + 'Please file an issue along with a paste of the logs from TORCH_LOGS="+export"', + ) + else: + matched_elements_positions.append(dict_of_source_vals[id(val)]) + + return matched_elements_positions + + matched_input_elements_positions = produce_matching( + "inputs", flat_args, graph_captured_input + ) + + assert graph_captured_output is not None + matched_output_elements_positions = produce_matching( + "outputs", list(graph_captured_output) + flat_args, flat_results_traced + ) + + new_graph = FlattenInputOutputSignature( + graph, + flat_args, + matched_input_elements_positions, # type: ignore[arg-type] + flat_results_traced, + matched_output_elements_positions, # type: ignore[arg-type] + example_fake_inputs, + flat_args_dynamic_dims, + fake_mode, + ).transform() + + new_graph.graph._codegen = _PyTreeCodeGen( + _PyTreeInfo( + argument_names(f_sig, orig_args, orig_kwargs), + in_spec, + out_spec_traced, + ) + ) + new_graph.recompile() + return new_graph + + +def export( + f: Callable[..., Any], + *extra_args: Any, + aten_graph: bool = False, + pre_dispatch: bool = False, + decomposition_table: Optional[ + dict[torch._ops.OpOverload, Callable[..., Any]] + ] = None, + tracing_mode: str = "symbolic", + dynamic_shapes: Optional[Union[dict[str, Any], tuple[Any], list[Any]]] = None, + specialize_float: bool = True, + assume_static_by_default: bool = False, + same_signature: bool = True, + disable_constraint_solver: bool = False, + prefer_deferred_runtime_asserts_over_guards: bool = False, + _log_export_usage: bool = True, + constraints: Optional[list[Constraint]] = None, + **extra_kwargs: Any, +) -> Callable[..., ExportResult]: + """ + Export an input function f to a format that can be executed outside of PyTorch using the FX graph. + + Args: + f (callable): A PyTorch function to be exported. + + aten_graph (bool): If True, exports a graph with ATen operators. + If False, exports a graph with Python operators. Default is False. + + pre_dispatch (bool): If True, exports a graph with ATen operators, + but before any logic in the PyTorch dispatcher has run. + This can be useful if you want to apply further transformations on a graph before running it + through autograd, autocast, or any other functionalities that are integrated into the dispatcher. + This flag is only valid if aten_graph=True is set. + Default is False. + + decomposition_table (dict): A dictionary that maps operators to their decomposition functions. + Required if aten_graph or tracing_mode is specified. Default is None. + + tracing_mode (str): If "symbolic", turn on dynamic shapes support. Default is "symbolic". + + dynamic_shapes: + An optional argument where the type should either be: + 1) a dict from argument names of ``f`` to their dynamic shape specifications, + 2) a tuple that specifies dynamic shape specifications for each input in original order. + If you are specifying dynamism on keyword args, you will need to pass them in the order that + is defined in the original function signature. + + The dynamic shape of a tensor argument can be specified as either + (1) a dict from dynamic dimension indices to :func:`Dim` types, where it is + not required to include static dimension indices in this dict, but when they are, + they should be mapped to None; or (2) a tuple / list of :func:`Dim` types or None, + where the :func:`Dim` types correspond to dynamic dimensions, and static dimensions + are denoted by None. Arguments that are dicts or tuples / lists of tensors are + recursively specified by using mappings or sequences of contained specifications. + + same_signature (bool): If True, rewrite the returned graph's signature to be the same as f. + + disable_constraint_solver (bool): Whether the dim constraint solver must be disabled. + + Returns: + A function that given args and kwargs, returns a tuple of (graph, guards) + Graph: An FX graph representing the execution of the input PyTorch function with the provided arguments and options. + Guards: The guards we accumulated during tracing f above + + Raises: + AssertionError: If decomposition_table is specified without setting aten_graph=True, + or if graph breaks during tracing in export. + + AssertionError: If Dynamo input and output is not consistent with traced input/output. + + Note - this headerdoc was authored by ChatGPT, with slight modifications by the author. + """ + if config.debug_force_graph_break_on_leaf_return: + raise unittest.SkipTest("Cannot force graph break on export") + + if _log_export_usage: + log_export_usage(event="export.private_api", flags={"_dynamo"}) + + # Deal with "local variable referenced before assignment" + _f = f + _specialize_float = specialize_float + _assume_static_by_default = assume_static_by_default + _constraints = constraints + + def inner(*args: Any, **kwargs: Any) -> ExportResult: + if not _constraints: + combined_args = _combine_args(_f, args, kwargs) + constraints = _process_dynamic_shapes(combined_args, dynamic_shapes) + else: + constraints = _constraints + + f = _f + specialize_float = _specialize_float + assume_static_by_default = _assume_static_by_default + check_if_dynamo_supported() + torch._C._log_api_usage_once("torch._dynamo.export") + if decomposition_table is not None: + assert aten_graph, ( + "Specifying a decomposition_table table or tracing mode is illegal without setting aten_graph=True" + ) + if pre_dispatch: + assert aten_graph, "pre_dispatch=True can only be used when aten_graph=True" + f = innermost_fn(f) + call_to_inspect = f.forward if isinstance(f, torch.nn.Module) else f + original_signature = inspect.signature(call_to_inspect) # type: ignore[arg-type] + graph = None + out_guards = None + graph_captured_input = None + graph_captured_result: Optional[tuple[torch.Tensor, ...]] = None + fake_mode = None + result_traced = None + + def guard_export_print(guards: _guards.GuardsSet) -> None: + nonlocal out_guards + assert out_guards is None, ( + "whole graph export entails exactly one guard export" + ) + out_guards = guards + + example_inputs: list[Any] = [] + + def dynamo_normalization_capturing_compiler( + gm: torch.fx.GraphModule, inner_example_inputs: list[Any] + ) -> Callable[..., Any]: + nonlocal graph + assert graph is None, ( + "Tried to emit a second graph during export. Tracing through 'f' must produce a single graph." + ) + graph = gm + + nonlocal fake_mode, example_inputs + # NB: do NOT pass inner_example_inputs here, we are detecting the + # Dynamo allocated fake mode, which should be DISTINCT from a + # potential outer ambient fake mode which the user provided. + # example_inputs is always the user specified inputs, so they + # would have the wrong fake mode attached to them + fake_mode = _guards.detect_fake_mode() + example_inputs = inner_example_inputs + + def result_capturing_wrapper(*graph_inputs: Any) -> Any: + nonlocal graph_captured_result + nonlocal graph_captured_input + + graph_captured_input = graph_inputs + assert graph is not None + + named_parameters = dict(graph.named_parameters(remove_duplicate=False)) + named_buffers = dict(graph.named_buffers(remove_duplicate=False)) + + ambient_fake_mode = ( + _guards.detect_fake_mode(graph_inputs) + if _guards.detect_fake_mode(graph_inputs) is not None + else fake_mode + ) + + # We reran fake tensor propagation, but we didn't do + # anything with the resulting unbacked SymInts. Drop them + # from the pending list. + # NB: this is wrong if graph_captured_result has + # data-dependent output size! + ignore_fresh_unbacked = null_context() + assert ambient_fake_mode is not None + if shape_env := ambient_fake_mode.shape_env: + ignore_fresh_unbacked = shape_env.ignore_fresh_unbacked_symbols() # type: ignore[assignment] + + with ( + ambient_fake_mode, + enable_python_dispatcher(), + ignore_fresh_unbacked, + ): + params_and_buffers = { + **named_parameters, + **named_buffers, + } + fake_params_buffers = {} + + for name, value in params_and_buffers.items(): + fake_params_buffers[name] = ambient_fake_mode.from_tensor( + value, static_shapes=True + ) + + from torch._export.non_strict_utils import ( + key_path_to_source, + KeyPath, + ) + + def fakify_with_ambient( + path: KeyPath, t: Union[torch.Tensor, _IntWrapper, Any] + ) -> Any: + if isinstance(t, torch.Tensor): + # pyrefly: ignore [missing-attribute] + return ambient_fake_mode.from_tensor(t, static_shapes=True) + elif isinstance(t, _IntWrapper): + if ( + t.dynamism is not None + and isinstance(t.dynamism, _DimHint) + and t.dynamism.type + in ( + _DimHintType.DYNAMIC, + _DimHintType.AUTO, + ) + ): # type: ignore[union-attr] + source = key_path_to_source(path) + symint = ambient_fake_mode.shape_env.create_unspecified_symint_and_symbol( # type: ignore[union-attr] + t.val, source, DimDynamic.DYNAMIC + ) + return symint + else: + return t.val + else: + return t + + fake_graph_inputs = pytree.tree_map_with_path( + fakify_with_ambient, graph_inputs + ) + graph_captured_result = torch.func.functional_call( + graph, + fake_params_buffers, # type: ignore[arg-type] + fake_graph_inputs, # type: ignore[arg-type] + ) + + return graph_captured_result + + return result_capturing_wrapper + + # Note: This is needed by rewrite_signature. We need to put it before + # optimize_assert since user program may mutate the inputs. + flat_args, in_spec = pytree.tree_flatten((args, kwargs)) + + remove_from_cache(f) + constraint_violation_error = None + if tracing_mode != "symbolic": + assume_static_by_default = True + with ( + config.patch( + specialize_int=True, + specialize_float=specialize_float, + assume_static_by_default=assume_static_by_default, + automatic_dynamic_shapes=False, + capture_dynamic_output_shape_ops=True, + capture_scalar_outputs=True, + constant_fold_autograd_profiler_enabled=True, + prefer_deferred_runtime_asserts_over_guards=prefer_deferred_runtime_asserts_over_guards, + # install_free_tensors ensures that params and buffers are still + # added as graph attributes, and makes Dynamo emits graphs that + # follow export pytree-able input requirements + install_free_tensors=config.install_free_tensors_for_export, + ), + _compiling_state_context(), + ): + opt_f = optimize_assert( + dynamo_normalization_capturing_compiler, + hooks=Hooks( + guard_export_fn=guard_export_print, + guard_fail_fn=None, + ), + export=True, + export_constraints=constraints, + )(f) + # TODO(voz): We may have instances of `f` that mutate inputs, we should track sideeffects and reject. + try: + result_traced = opt_f(*args, **kwargs) + except ConstraintViolationError as e: + constraint_violation_error = e + remove_from_cache(f) + + if ( + not disable_constraint_solver + and (shape_env := getattr(fake_mode, "shape_env", None)) is not None + and (dim_constraints := shape_env.dim_constraints) is not None + and not isinstance( + call_to_inspect, (torch._ops.OpOverloadPacket, torch._ops.OpOverload) + ) + and not trace_rules.check(call_to_inspect) + ): + dim_constraints.solve() + + forced_specializations = dim_constraints.forced_specializations() + + msg = dim_constraints.prettify_results( + original_signature, + dynamic_shapes, + constraint_violation_error, + forced_specializations, + ) + if constraint_violation_error: + constraint_violation_error.args = ( + constraint_violation_error.args[0] + msg, + ) + else: + if forced_specializations: + constraint_violation_error = ConstraintViolationError(msg) + else: + log.info( + "Summary of dimension constraints:%s", + msg, + ) + + # Error if we have any constraints on static values + + for k in shape_env.var_to_range: + if isinstance(k, sympy.Integer): + constraint_violation_error = ConstraintViolationError( + f"{''.join(traceback.format_list(shape_env.var_to_stack[k]))}\n" + "It appears that you're trying to set a constraint on a " + f"value which we evaluated to have a static value of {k}. " + 'Set TORCH_LOGS="+export" for more information.' + ) + if constraint_violation_error: + raise constraint_violation_error + + if graph is None: + assert same_signature, ( + "Failed to produce a graph during tracing as no tensor operations were found and same_signature is False." + ) + # If the module does not contain any tensor computation, we would create a graph with inputs and outputs. + # To be consistent with the graph traced by dynano, `graph` will have only tensor inputs as placeholders + # and tensor outputs as output nodes. non-tensor inputs and outputs will be added when rewriting signature. + # We will also construct the `example_inputs`, `graph_captured_input`, and `graph_captured_result` corresponding + # to `graph`. + example_inputs = [] + graph_captured_input = () + graph_captured_result = () + fake_mode = torch._subclasses.FakeTensorMode( + shape_env=ShapeEnv(), export=True + ) + if out_guards is None: + out_guards = _guards.GuardsSet() + assert out_guards is not None # suppress mypy error + parameter_names = list(original_signature.parameters.keys()) + fx_graph = torch.fx.Graph() + for i, name in enumerate(parameter_names): + if torch.is_tensor(flat_args[i]): + node = fx_graph.placeholder(name) + node.meta["val"] = fake_mode.from_tensor( + flat_args[i], static_shapes=True + ) + graph_captured_input = graph_captured_input + (flat_args[i],) + example_inputs.append(flat_args[i]) + fx_graph.output(graph_captured_result) + module = torch.nn.Module() + graph = torch.fx.GraphModule(module, fx_graph) + log.info( + "Failed to capture a graph during tracing as no tensor operations were found.:\n\n%s", + graph.print_readable(print_output=False, colored=True), + ) + else: + assert out_guards is not None, "Failed to produce guards during tracing" + assert fake_mode is not None + + log.info( + "Dynamo captured graph:\n\n%s", + graph.print_readable(print_output=False, colored=True), + ) + + # This check need to happened before aten_graph + # because placeholder's _source_node attribute is not preserved by make_fx + if same_signature: + check_signature_rewritable(graph) + + # NB: This is mostly hitting the cache; Dynamo already converted these + example_fake_inputs = [ + fake_mode.from_tensor(t) if isinstance(t, torch.Tensor) else t + for t in example_inputs + ] + + if aten_graph: + # Running graph with interpreter is needed for propagating the stack_trace + def graph_with_interpreter(*args: Any) -> Any: + with torch.fx.traceback.preserve_node_meta(): + return torch.fx.Interpreter(graph).run(*args) # type: ignore[arg-type] + + with unset_fake_temporarily(), enable_python_dispatcher(), fake_mode: + try: + graph = make_fx( + graph_with_interpreter, + decomposition_table=decomposition_table, + tracing_mode="real", + _allow_non_fake_inputs=True, + pre_dispatch=pre_dispatch, + _allow_fake_constant=False, + )(*example_fake_inputs) + except CondOpArgsMismatchError as e: + # Wrap the internal error to the user-facing error + raise UserError( # noqa: B904 + UserErrorType.DYNAMIC_CONTROL_FLOW, + str(e), + case_name="cond_operands", + ) + + assert graph is not None + for node in graph.graph.find_nodes(op="get_attr"): + if isinstance(getattr(graph, node.target), torch.Tensor): # type: ignore[arg-type] + node.meta["val"] = fake_mode.from_tensor( + getattr(graph, node.target), # type: ignore[arg-type] + static_shapes=True, + ) + + if same_signature: + flat_args_dynamic_dims = [ + { + c.dim + for c in (constraints or ()) + if ( + c.t_id == id(x) + and not isinstance(c, _RelaxedConstraint) + and c.constraint_range.vr.lower != c.constraint_range.vr.upper + ) + } + for x in flat_args + ] + graph = rewrite_signature( + original_signature, + graph, + fake_mode, + flat_args, + in_spec, + example_fake_inputs, + graph_captured_input, # type: ignore[arg-type] + graph_captured_result, + result_traced, # type: ignore[possibly-undefined] + flat_args_dynamic_dims, + ) + return ExportResult(graph, out_guards) + + if extra_args or extra_kwargs: + warnings.warn( + "export(f, *args, **kwargs) is deprecated, use export(f)(*args, **kwargs) instead. " + "If you don't migrate, we may break your export call in the future if your user defined kwargs " + "conflict with future kwargs added to export(f).", + FutureWarning, + stacklevel=2, + ) + return inner(*extra_args, **extra_kwargs) # type: ignore[return-value] + else: + return inner + + +def optimize_assert(*args: Any, **kwargs: Any) -> OptimizeContext: + if "rebuild_ctx" in kwargs and kwargs["rebuild_ctx"] is not None: + # called from optimize + rebuild_ctx = kwargs["rebuild_ctx"] + del kwargs["rebuild_ctx"] + else: + + def rebuild_ctx() -> OptimizeContext: + return optimize_assert(*args, **kwargs) + + return _optimize_assert(rebuild_ctx, *args, **kwargs) + + +def _optimize_assert( + rebuild_ctx: Callable[[], OptimizeContext], + backend: Union[str, Callable[..., Any], None], + *, + hooks: Hooks = Hooks(None, None, None), + export: bool = False, + export_constraints: Optional[Any] = None, + dynamic: Optional[bool] = None, + package: Optional[CompilePackage] = None, +) -> OptimizeContext: + """ + Guarantees single-graph capture. + The same as `torch._dynamo.optimize(backend)` but ignores + symbolic_convert.error_on_graph_break setting. + + Used for fullgraph=True and export, since we must always error on graph breaks and ignore + symbolic_convert.error_on_graph_break. Can also be used for testing. + """ + backend = get_compiler_fn(backend) + + # Find if backend has any extra context manager + backend_ctx_ctor = getattr(backend, "backend_ctx_ctor", null_context) + + if config.caching_precompile and package is None: + # Create an uninitialized package that will be set/filled by + # _OptimizeContext.__call__ + # We need to instantiate the object here because the same CompilePackage + # needs to be shared between convert_frame_assert + # and OptimizeContext. + from .package import CompilePackage + + package = CompilePackage(fn=None, dynamo=None, ignore_inlined_sources=False) + + return _optimize_catch_errors( + convert_frame.convert_frame_assert( + backend, + export=export, + export_constraints=export_constraints, + package=package, + ), + hooks, + backend_ctx_ctor, + fullgraph=True, + export=export, + dynamic=dynamic, + rebuild_ctx=rebuild_ctx, + package=package, + ) + + +class TorchPatcher: + @staticmethod + @functools.cache + def patch() -> None: + # A better way to disable the following would be decorate the source + # functions with @torch._disable_dynamo. However, this causes issues + # with torch.deploy internally. + from .decorators import disable + + torch.jit.trace = disable( + torch.jit.trace, reason="tracing into TorchScript not fully supported" + ) + torch.jit.trace_module = disable( + torch.jit.trace_module, + reason="tracing into TorchScript not fully supported", + ) + torch.jit._get_trace_graph = disable( + torch.jit._get_trace_graph, + reason="tracing into TorchScript not fully supported", + ) + torch.fx._symbolic_trace.Tracer.trace = disable( + torch.fx._symbolic_trace.Tracer.trace, + reason="tracing into FX not fully supported", + ) + torch.distributions.Distribution.set_default_validate_args(False) + + from torch.optim import ( + adadelta, + adagrad, + adam, + adamax, + adamw, + asgd, + lbfgs, + nadam, + radam, + rmsprop, + rprop, + sgd, + sparse_adam, + ) + + optimizer_modules = { + adadelta, + adagrad, + adam, + adamax, + adamw, + asgd, + lbfgs, + nadam, + radam, + rmsprop, + rprop, + sgd, + sparse_adam, + } + + for opt_mod in optimizer_modules: + opt_name = opt_mod.__name__.split(".")[-1] + fused_fn_name = f"_fused_{opt_name}" + + if hasattr(opt_mod, fused_fn_name): + setattr( + opt_mod, + fused_fn_name, + disable( + getattr(opt_mod, fused_fn_name), + reason="don't trace into fused optimizer", + ), + ) + + optimizer_classes = [ + opt + for opt in torch.optim.__dict__.values() + if inspect.isclass(opt) and issubclass(opt, torch.optim.Optimizer) + ] + + # Note: we don't support sparsity or tracing through backwards + excluded_optimizer_classes = { + torch.optim.SparseAdam, + torch.optim.LBFGS, + } + + for opt in optimizer_classes: + if opt in excluded_optimizer_classes: + opt.step = disable( + opt.step, reason=f"optimizer {opt} step not supported" + ) + + if hasattr(opt, "_init_group"): + opt._init_group = disable( + opt._init_group, reason=f"optimizer {opt} _init_group not supported" + ) + + @staticmethod + def suppress_torch_distributed_warnings( + fn: Callable[..., Any], + ) -> Callable[..., Any]: + def inner_fn(*args: Any, **kwargs: Any) -> Any: + with torch._logging.hide_warnings( + torch._logging._internal.user_warning_filter + ): + return fn(*args, **kwargs) + + return inner_fn + + +def skip_code(code: types.CodeType) -> None: + set_code_exec_strategy( + code, FrameExecStrategy(FrameAction.SKIP, FrameAction.DEFAULT) + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/exc.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/exc.py new file mode 100644 index 0000000000000000000000000000000000000000..a7bdf1caff2415261c70f9e66da731741b56a3d6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/exc.py @@ -0,0 +1,827 @@ +from __future__ import annotations + + +"""Exception handling and error reporting for TorchDynamo. + +This module provides a comprehensive set of exception classes and utilities for error +handling in TorchDynamo. It includes: + +Base Exceptions: + - TorchDynamoException: Base class for all TorchDynamo-specific exceptions + - Various specialized subclasses for different error scenarios + +User Error Handling: + - UserError: Exceptions for user-facing errors in TorchDynamo usage + - UserErrorType: Enumeration of different categories of user errors + - Formatted error messages with debugging information + +Observed Exceptions: + - Classes for handling exceptions observed during tracing + - Special handling for StopIteration, LookupError, etc. + - Exception state management during compilation + +Error Formatting: + - Stack trace filtering and formatting + - Error message augmentation + - Debugging utilities for error reporting +""" + +import json +import logging +import re +import textwrap +import typing +from enum import auto, Enum +from functools import lru_cache +from pathlib import Path +from traceback import extract_stack, format_exc, format_list, StackSummary +from typing import Any, NoReturn, Optional, TYPE_CHECKING + +import torch._guards +from torch._utils_internal import get_file_path_2 + +from . import config +from .utils import counters + + +if TYPE_CHECKING: + import types + + from torch._guards import CompileId + + from .output_graph import DynamoTracerOutput + from .symbolic_convert import InstructionTranslatorBase + from .types import DynamoFrameType + + +def exportdb_error_message(case_name: str) -> str: + return ( + "For more information about this error, see: " + + "https://pytorch.org/docs/main/generated/exportdb/index.html#" + + case_name.replace("_", "-") + ) + + +log = logging.getLogger(__name__) +graph_breaks_log = torch._logging.getArtifactLogger(__name__, "graph_breaks") + + +class TorchDynamoException(RuntimeError): + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self._torch_dynamo_tracer_output: Optional[DynamoTracerOutput] = None + + +class InternalTorchDynamoError(TorchDynamoException): + pass + + +class ResumePrologueTracingError(TorchDynamoException): + pass + + +class RestartAnalysis(TorchDynamoException): + restart_reason: Optional[str] + + def __init__(self, *args: Any, restart_reason: Optional[str] = None) -> None: + self.restart_reason = restart_reason + super().__init__(*args) + + +class SpeculationRestartAnalysis(RestartAnalysis): + pass + + +class UnspecializeRestartAnalysis(RestartAnalysis): + pass + + +class CompileCollectiveRestartAnalysis(RestartAnalysis): + pass + + +class TensorifyScalarRestartAnalysis(RestartAnalysis): + pass + + +class SkipFrame(TorchDynamoException): + pass + + +class TorchRuntimeError(TorchDynamoException): + pass + + +class InvalidBackend(TorchDynamoException): + def __init__(self, name: str) -> None: + super().__init__( + f"Invalid backend: {name!r}, see `torch._dynamo.list_backends()` for available backends." + ) + + +class ResetRequired(TorchDynamoException): + def __init__(self) -> None: + super().__init__( + textwrap.dedent( + """ + Must call `torch._dynamo.reset()` before changing backends. Detected two calls to + `torch.compile()` with a different backend compiler arguments. + """ + ) + ) + + +class ShortenTraceback(TorchDynamoException): + def __init__( + self, *args: Any, first_useful_frame: Optional[types.FrameType], **kwargs: Any + ) -> None: + super().__init__(*args, **kwargs) + self.first_useful_frame = first_useful_frame + + def remove_dynamo_frames(self) -> typing.Self: + tb = self.__traceback__ + if self.first_useful_frame is None or tb is None or config.verbose: + return self + while tb.tb_frame is not self.first_useful_frame: + tb = tb.tb_next + assert tb is not None, "internal error, please report a bug" + return self.with_traceback(tb) + + +class BackendCompilerFailed(ShortenTraceback): + def __init__( + self, + backend_fn: Any, + inner_exception: Exception, + first_useful_frame: Optional[types.FrameType], + ) -> None: + self.backend_name = getattr(backend_fn, "__name__", "?") + self.inner_exception = inner_exception + msg = f"backend={self.backend_name!r} raised:\n{type(inner_exception).__name__}: {inner_exception}" + super().__init__(msg, first_useful_frame=first_useful_frame) + + +class Unsupported(TorchDynamoException): + def __init__( + self, + msg: str, + *, + case_name: Optional[str] = None, + real_stack: None | StackSummary = None, + ) -> None: + super().__init__(msg) + if not real_stack: + real_stack = torch._guards.TracingContext.extract_stack() + self.real_stack = real_stack + self.msg = msg + self.category: Optional[str] = None + self.add_to_stats() + self.case_name: Optional[str] = case_name + + def remove_from_stats(self) -> None: + assert self.category is not None + counters[self.category][self.msg] -= 1 + if counters[self.category][self.msg] <= 0: + del counters[self.category][self.msg] + + def add_to_stats(self, category: str = "unimplemented") -> None: + self.category = category + counters[category][self.msg] += 1 + + +class UnknownPropertiesDuringBackwardTrace(Unsupported): + pass + + +class RecompileError(TorchDynamoException): + pass + + +class ArgsMismatchError(Unsupported): + pass + + +class AttributeMutationError(Unsupported): + pass + + +class InfiniteGeneratorError(Unsupported): + # Raised when the number of yielded values is greater than MAX_ITERATOR_LIMIT + pass + + +class SideEffectsError(Unsupported): + pass + + +class CondOpArgsMismatchError(ArgsMismatchError): + """ + Internal error from cond() due to arguments mismatch. + """ + + +class UserErrorType(Enum): + DYNAMIC_CONTROL_FLOW = auto() + ANTI_PATTERN = auto() + STANDARD_LIBRARY = auto() + CONSTRAINT_VIOLATION = auto() + DYNAMIC_DIM = auto() + INVALID_INPUT = auto() + INVALID_OUTPUT = auto() + UNSUPPORTED_ALIASED_MUTATED_DYNAMIC_INPUTS = auto() + + +class UserError(Unsupported): + def __init__( + self, error_type: UserErrorType, msg: str, case_name: Optional[str] = None + ) -> None: + """ + Type of errors that would be valid in Eager, but not supported in TorchDynamo. + The error message should tell user about next actions. + + error_type: Type of user error + msg: Actionable error message + case_name: (Optional) Unique name (snake case) for the usage example in exportdb. + """ + if case_name is not None: + assert isinstance(case_name, str) + if msg.endswith("."): + msg += " " + else: + msg += "\n" + msg += exportdb_error_message(case_name) + super().__init__(msg) + self.error_type = error_type + self.message = msg + + +class SkipCodeRecursiveException(TorchDynamoException): + pass + + +class RecompileLimitExceeded(Unsupported): + pass + + +# debug exception thrown when tracing torch._dynamo.step_unsupported() +class StepUnsupported(TorchDynamoException): + def __init__(self) -> None: + self.real_stack = torch._guards.TracingContext.extract_stack() + + +class UnsafeScriptObjectError(TorchDynamoException): + pass + + +class UncapturedHigherOrderOpError(TorchDynamoException): + def __init__(self, msg: str, real_stack: Optional[StackSummary] = None) -> None: + super().__init__(msg) + self.msg = msg + self.real_stack = ( + real_stack + if real_stack is not None + else torch._guards.TracingContext.extract_stack() + ) + + +class IncorrectUsage(Exception): + pass + + +# TODO: I'm a little uncertain about what error classification we should have +# for this. This is potentially a user error, but regressions in +# specialization in PyTorch proper could also trigger this problem +class FailOnRecompileLimitHit(Exception): + pass + + +class PackageError(TorchDynamoException): + pass + + +class ObservedException(TorchDynamoException): + # An exception observed during the tracing. This exception is used by Dynamo to handle exceptions. + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.real_stack: StackSummary = torch._guards.TracingContext.extract_stack() + + +class ObservedUserStopIteration(ObservedException): + # An UserStopIteration exception observed during the Dynamo tracing (e.g Dynamo tracing __next__) + value: Optional[Any] + + # Reference `StopIteration_init` in CPython + # https://github.com/python/cpython/blob/3.11/Objects/exceptions.c#L568-L584 + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__("unhandled `raise StopIteration`") + if len(args) > 0: + self.value = args[0] + else: + self.value = None + + +class ObservedLookupError(ObservedException): + # A LookupError exception to be raised from inside Dynamo tracing. This can happen on __getitem__ + pass + + +class ObservedIndexError(ObservedLookupError): + # An IndexError exception to be raised from inside Dynamo tracing. This can happen on list __getitem__ + pass + + +class ObservedKeyError(ObservedLookupError): + # A KeyError exception to be raised from inside Dynamo tracing. This can happen on dict __getitem__ + pass + + +class ObservedGeneratorExit(ObservedException): + pass + + +class ObservedAttributeError(ObservedException): + # An AttributeError exception to be raised from inside Dynamo tracing. This can happen on user defined object __getattr__ + pass + + +class ObservedRuntimeError(ObservedException): + # A RuntimeError exception to be raised from inside Dynamo tracing. This can happen on generator.throw(..) method + pass + + +class ObservedNotImplementedError(ObservedException): + pass + + +class ObservedTypeError(ObservedException): + # A TypeError exception to be raised from inside Dynamo tracing. This can happen on generator.send(..) method + pass + + +observed_exception_map = { + StopIteration: ObservedUserStopIteration, + LookupError: ObservedLookupError, + IndexError: ObservedIndexError, + GeneratorExit: ObservedGeneratorExit, + KeyError: ObservedKeyError, + AttributeError: ObservedAttributeError, + RuntimeError: ObservedRuntimeError, + NotImplementedError: ObservedNotImplementedError, + TypeError: ObservedTypeError, +} + + +def get_dynamo_observed_exception(exc_type: type[Exception]) -> type[ObservedException]: + if exc_type not in observed_exception_map: + name = getattr(exc_type, "__name__", str(exc_type)) + observed_exception_map[exc_type] = type( # type: ignore[assignment] + f"Observed{name}Error", (ObservedException,), {} + ) + # pyrefly: ignore [index-error] + return observed_exception_map[exc_type] + + +def raise_observed_exception( + exc_type: type[Exception], + tx: InstructionTranslatorBase, + *, + args: Optional[list[Any]] = None, + kwargs: Optional[dict[str, Any]] = None, +) -> NoReturn: + from .variables import BuiltinVariable + + # CPython here raises an exception. Since there is no python code, we have to manually setup the exception + # stack and raise the exception. + exception_vt = BuiltinVariable(exc_type).call_function(tx, args or [], kwargs or {}) # type: ignore[arg-type] + tx.exn_vt_stack.set_current_exception(exception_vt) # type: ignore[arg-type] + raised_exc = get_dynamo_observed_exception(exc_type) + # Store the original exception arguments for better error messages + if args: + raise raised_exc(*args) + raise raised_exc + + +def handle_observed_exception(tx: Any) -> None: + # This is essentially exception handling code, equivalent of this pseudo code + # + # try: + # ... somebody raising StopIteration + # except StopIteration + # pass + # + # If this was going through the python code, we would have called exception_handler method, but FOR_ITER + # handles the exception completely in CPython. For example for 3.11, the resulting bytecode is + # + # + # 6 46 LOAD_GLOBAL 2 (StopIteration) + # 58 RAISE_VARARGS 1 + # >> 60 PUSH_EXC_INFO + + # 7 62 LOAD_GLOBAL 2 (StopIteration) + # 74 CHECK_EXC_MATCH + # 76 POP_JUMP_FORWARD_IF_FALSE 3 (to 84) + # 78 POP_TOP + + # 8 80 POP_EXCEPT + # + + # Fortunately this translates to a simple pop from the exn_vt_stack + tx.exn_vt_stack.clear_current_exception() + + +# These exceptions are ok to fallback to eager/graph_break. +exceptions_allowed_to_be_fallback = ( + torch._subclasses.fake_tensor.DataDependentOutputException, + torch._subclasses.fake_tensor.DynamicOutputShapeException, + torch._subclasses.fake_tensor.UnsupportedOperatorException, + torch._subclasses.fake_tensor.UnsupportedFakeTensorException, + torch._subclasses.fake_tensor.UnsupportedMutationAliasingException, +) + + +def unimplemented_with_warning( + e: Exception, + code: types.CodeType, + *, + gb_type: str, + context: str, + explanation: str, + hints: list[str], +) -> NoReturn: + # This function calls unimplemented internally and eventually graph breaks + # or falls to eager. unimplemented itself does not print any user warnings, + # i.e., its very silent. This helper function is intended when an error is + # encountered in the torch.compile stack which is worth showing as warning + # to the user. For example, if AOT Autograd backend fails with a fake tensor + # exception, its ok to fallback to eager but not silently. Here, we can use + # this function to log the message and the stack trace. + graph_break_msg = format_error_msg_verbose(e, code) + torch._logging.trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "dynamo_graph_break_reason", + "encoding": "string", + }, + payload_fn=lambda: graph_break_msg, + ) + graph_breaks_log.debug("%s", graph_break_msg) + _unimplemented = unimplemented + # to prevent a graph break registry entry + _unimplemented( + gb_type=gb_type, + context=context, + explanation=explanation, + hints=hints, + from_exc=e, + log_warning=True, + ) + + +def format_graph_break_message( + gb_type: str, + context: str, + explanation: str, + hints: list[str], +) -> str: + explanation = textwrap.indent(explanation, " ").lstrip() + hints_str = "\n".join( + " Hint: " + textwrap.indent(hint, " ").lstrip() for hint in hints + ) + context = textwrap.indent(context, " ").lstrip() + + msg = f"""\ +{gb_type} + Explanation: {explanation} +{hints_str} + + Developer debug context: {context} +""" + return msg + + +@lru_cache(maxsize=1) +def _load_gb_type_to_gb_id_map() -> dict[str, Any]: + """ + Loads the gb_type to gb_id map from the graph break registry from JSON file with caching. + + Includes historical gb_type (mapping behavior of duplicate gb_types with different gb_ids is undefined). + """ + try: + script_dir = Path(__file__).resolve().parent + registry_path = get_file_path_2( + "", str(script_dir), "graph_break_registry.json" + ) + with open(registry_path) as f: + registry = json.load(f) + except Exception: + log.exception("Error accessing the registry file") + registry = {} + + mapping = {} + for k, v in registry.items(): + for entry in v: + mapping[entry["Gb_type"]] = k + + return mapping + + +def get_gbid_documentation_link(gb_type: str) -> Optional[str]: + """ + Retrieves the GBID documentation link for a given graph break type. + + Args: + gb_type: The graph break type to look up. + + Returns: + A string containing the documentation URL if found, otherwise None. + """ + GRAPH_BREAK_SITE_URL = ( + "https://meta-pytorch.github.io/compile-graph-break-site/gb/" # @lint-ignore + ) + + gb_type_to_gb_id_map = _load_gb_type_to_gb_id_map() + + if gb_type in gb_type_to_gb_id_map: + return ( + f"{GRAPH_BREAK_SITE_URL}gb{gb_type_to_gb_id_map[gb_type].lstrip('GB')}.html" + ) + + return None + + +_NOTHING = object() + + +def unimplemented( + *, + gb_type: str, + context: str, + explanation: str, + hints: list[str], + from_exc: Any = _NOTHING, + log_warning: bool = False, +) -> NoReturn: + """ + Called within dynamo to cause a graph break. + Args: + gb_type: Context-free graph break type. It should be a short string without any + information specific to the tracing context (i.e. no dynamically-generated strings) + context: Developer context for the graph break. It can contain tracing context/dynamic strings. + explanation: User-facing context-dependent explanation for the graph break. Can be dynamic. + hints: List of user-facing hints for the graph break. + """ + + msg = format_graph_break_message(gb_type, context, explanation, hints) + + documentation_link = get_gbid_documentation_link(gb_type) + + if documentation_link: + msg += f"\n For more details about this graph break, please visit: {documentation_link}" + + if log_warning: + log.warning(msg) + if from_exc is not _NOTHING: + past_real_stack = None + if hasattr(from_exc, "real_stack"): + past_real_stack = from_exc.real_stack + raise Unsupported(msg, real_stack=past_real_stack) from from_exc + raise Unsupported(msg) + + +# KeyError has special handling for its args +# see https://github.com/python/cpython/blob/3.11/Objects/exceptions.c#L2534 for details +class KeyErrorMsg: + def __init__(self, value: Any) -> None: + self.value = value + + def __str__(self) -> str: + return str(self.value) + + def __repr__(self) -> str: + return self.__str__() + + +def augment_exc_message(exc: Exception, msg: str = "\n", export: bool = False) -> None: + import traceback + + exc.innermost_user_frame_summary = None # type: ignore[attr-defined] + + real_stack = get_real_stack(exc) + if real_stack is not None and len(real_stack) > 0: + exc.innermost_user_frame_summary = real_stack[-1] # type: ignore[attr-defined] + msg += f"\nfrom user code:\n {''.join(traceback.format_list(real_stack))}" + + if config.replay_record_enabled and hasattr(exc, "record_filename"): + msg += ( + f"\nLast frame execution written to {exc.record_filename}. To run only this frame while debugging, run\ + torch._dynamo.replay('{exc.record_filename}').\n" + ) + + if not config.verbose and hasattr(exc, "real_stack"): + msg += ( + "\nSet TORCHDYNAMO_VERBOSE=1 for the internal stack trace " + "(please do this especially if you're reporting a bug to PyTorch). " + 'For even more developer context, set TORCH_LOGS="+dynamo"\n' + ) + + if hasattr(exc, "inner_exception") and hasattr( + exc.inner_exception, "minifier_path" + ): + if hasattr(exc.inner_exception, "buck_command"): + msg += ( + f"\nMinifier script written to {exc.inner_exception.minifier_path}. Run " + f"this buck command to find the smallest traced graph " + f"which reproduces this error: {exc.inner_exception.buck_command}\n" + ) + else: + msg += ( + f"\nMinifier script written to {exc.inner_exception.minifier_path}. Run " + "this script to find the smallest traced graph which reproduces this error.\n" + ) + + old_msg = "" if len(exc.args) == 0 else str(exc.args[0]) + + if isinstance(exc, KeyError): + exc.args = (KeyErrorMsg(old_msg + msg),) + exc.args[1:] + else: + new_msg = old_msg + msg + exc.args = (new_msg,) + exc.args[1:] + + +def get_exc_message( + e: Exception, compile_id: CompileId +) -> tuple[Optional[str], Optional[int]]: + filename = None + lineno = None + if e.innermost_user_frame_summary is not None: # type: ignore[attr-defined] + filename = e.innermost_user_frame_summary.filename # type: ignore[attr-defined] + lineno = e.innermost_user_frame_summary.lineno # type: ignore[attr-defined] + e.compile_id = compile_id # type: ignore[attr-defined] + return filename, lineno + + +def get_stack_above_dynamo() -> StackSummary: + return filter_stack(extract_stack()) + + +def get_real_stack( + exc: Exception, frame: Optional[DynamoFrameType] = None +) -> Optional[StackSummary]: + real_stack = getattr(exc, "real_stack", None) + if real_stack is None: + return None + + # NB: it's possible for real_stack to be []; we still attempt to + # report a stack anyway because the stack_above_dynamo may still + # be useful for debugging + + if frame is not None: + # NB: frame is PyInterpreterFrame on Python 3.11 and later, + # not a TRUE frame object. You can't actually feed it + # to traceback because it doesn't have enough information. + # To solve this problem, we technically should just materialize + # the frame, the same way _PyFrame_GetFrameObject would do + # (but we cannot actually do this, because this populates + # frame_obj field, which default eval frame doesn't like). + # + # Fortunately, in this case, we can hack it: there's no need + # to actually use the truly top frame, we can just extract + # from where we are right now and rely on filter_stack to + # get rid of all the dynamo frames. For ease of testing + # we apply this behavior to ALL Python versions + stack_above_dynamo = get_stack_above_dynamo() + else: + stack_above_dynamo = StackSummary() + + return StackSummary.from_list(stack_above_dynamo + real_stack) + + +# filter out all frames after entering dynamo +def filter_stack(stack: StackSummary) -> StackSummary: + user_stack = StackSummary() + for frame in stack: + if frame.filename is None: + continue + if "convert_frame" in frame.filename: + break + if "eval_frame" in frame.filename or ( + frame.line and "torch._dynamo.optimize(" in frame.line + ): + continue + user_stack.append(frame) + + return user_stack + + +def remove_resume_prefix(name: str) -> Optional[str]: + from .resume_execution import TORCH_DYNAMO_RESUME_IN_PREFIX + + match = re.match(f"{TORCH_DYNAMO_RESUME_IN_PREFIX}_(\\w+)_at_\\d+", name) + if match: + return match.group(1) + return None + + +def collapse_resume_frames(stack: StackSummary) -> StackSummary: + """ + When we graph break, we create a resume function and make a regular Python call + to it, which gets intercepted by Dynamo. This behavior is normally shown in the + traceback, which can be confusing to a user. So we can filter out resume frames + for better traceback clarity. + + Example: + File "..." line 3, in f + + File "..." line 5, in torch_dynamo_resume_in_f_at_80 + + File "..." line 10, in torch_dynamo_resume_in_f_at_120 + + + becomes + File "..." line 10, in f + + """ + + new_stack = StackSummary() + for frame in stack: + if frame.filename is None: + continue + name = remove_resume_prefix(frame.name) + if new_stack and name and new_stack[-1].name == name: + new_stack[-1] = frame + frame.name = name + else: + new_stack.append(frame) + + return new_stack + + +def format_error_msg_verbose( + exc: Exception, + code: types.CodeType, + record_filename: Optional[str] = None, + frame: Optional[DynamoFrameType] = None, +) -> str: + msg = ( + f"WON'T CONVERT {code.co_name} {code.co_filename} line {code.co_firstlineno}\n" + ) + msg += "=" * 10 + " TorchDynamo Stack Trace " + "=" * 10 + "\n" + msg += format_exc() + real_stack = get_real_stack(exc, frame) + if real_stack is not None: + msg += ( + "\n" + + "=" * 10 + + " The above exception occurred while processing the following code " + + "=" * 10 + + "\n\n" + ) + msg += "".join(format_list(real_stack)) + msg += "\n" + msg += "=" * 10 + + return msg + + +def format_frame_info(code: types.CodeType) -> str: + return ( + f"{getattr(code, 'co_name', '')} " + f"({getattr(code, 'co_filename', '')} " + f"line {getattr(code, 'co_firstlineno', 0)})" + ) + + +def format_skip_frame_message(code: Optional[types.CodeType], reason: str) -> str: + if code is not None: + frame_info = format_frame_info(code) + return ( + f"torch.compile intentionally decided to skip the frame {frame_info} and fall back to eager.\n" + f"Reason: {reason}" + ) + else: + return ( + f"torch.compile intentionally decided to skip the frame and fall back to eager.\n" + f"Reason: {reason}" + ) + + +def format_loop_skip_frame_message(code: types.CodeType, frame_summary: str) -> str: + frame_info = format_frame_info(code) + return ( + "Skipping frame because there is a graph break in a for/while loop\n" + f"torch.compile intentionally decided to skip the frame {frame_info} and fall back to eager.\n" + f"Reason: Skipping frame because there is a graph break in a for/while loop.\n" + f"{frame_summary}" + ) + + +def format_error_msg( + exc: Exception, + code: types.CodeType, + record_filename: Optional[str] = None, + frame: Optional[DynamoFrameType] = None, +) -> str: + if config.verbose: + return format_error_msg_verbose(exc, code, record_filename, frame) + return f"WON'T CONVERT {code.co_name} {code.co_filename}\ + line {code.co_firstlineno} \ndue to: \n{format_exc()}" diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/external_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/external_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..10422a3e2b82b2054778ca892f05e45958f4e710 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/external_utils.py @@ -0,0 +1,287 @@ +""" +This module contains utility functions that are explicitly allowed to be called during +TorchDynamo compilation. These functions are carefully vetted to ensure they work +correctly within the TorchDynamo tracing and compilation process. + +Key functionality groups: + +- Compilation State: + Functions for checking compilation state (is_compiling) + +- Function Wrapping: + Utilities for wrapping functions (wrap_inline, wrap_numpy) to work with + TorchDynamo compilation + +- Autograd Hooks: + Functions and classes for handling autograd hooks and backward passes + (call_hook, FakeBackwardCFunction, etc.) + +- Tensor Operations: + Utility functions for tensor operations and transformations +""" + +import functools +import warnings +from collections.abc import Callable +from typing import Any, Optional, TYPE_CHECKING, TypeVar, Union +from typing_extensions import deprecated, ParamSpec + +import torch +import torch.utils._pytree as pytree + + +try: + import numpy as np +except ModuleNotFoundError: + np = None # type: ignore[assignment] + +_P = ParamSpec("_P") +_R = TypeVar("_R") + +if TYPE_CHECKING: + # TorchScript does not support `@deprecated` + # This is a workaround to avoid breaking TorchScript + @deprecated( + "`torch._dynamo.external_utils.is_compiling` is deprecated. Use `torch.compiler.is_compiling` instead.", + category=FutureWarning, + ) + def is_compiling() -> bool: + return torch.compiler.is_compiling() + +else: + + def is_compiling() -> bool: + """ + Indicates whether we are tracing/compiling with torch.compile() or torch.export(). + """ + # NOTE: With `@torch.compile(backend="eager")`, torch._dynamo.is_compiling() will get traced + # and return true. torch.compiler.is_compiling() is skipped and will return false. + return torch.compiler.is_compiling() + + +def wrap_inline(fn: Callable[_P, _R]) -> Callable[_P, _R]: + """ + Create an extra frame around fn that is not in skipfiles. + """ + + @functools.wraps(fn) + def inner(*args: _P.args, **kwargs: _P.kwargs) -> _R: + return fn(*args, **kwargs) + + return inner + + +def call_hook( + hook: Callable[..., Optional[torch.Tensor]], *args: Any, **kwargs: Any +) -> torch.Tensor: + """ + Used by compiled autograd to handle hook returning None. + """ + result = hook(*args) + if result is None: + return args[0] + elif kwargs.get("hook_type") == "post_acc_grad_hook": + raise RuntimeError("Tensor post accumulate grad hooks should return None.") + return result + + +def wrap_numpy(f: Callable[_P, _R]) -> Callable[_P, _R]: + r"""Decorator that turns a function from ``np.ndarray``s to ``np.ndarray``s into a function + from ``torch.Tensor``s to ``torch.Tensor``s. + """ + if not np: + return f + + @functools.wraps(f) + def wrap(*args: _P.args, **kwargs: _P.kwargs) -> pytree.PyTree: + args, kwargs = pytree.tree_map_only( + torch.Tensor, lambda x: x.numpy(), (args, kwargs) + ) + # pyrefly: ignore [invalid-param-spec] + out = f(*args, **kwargs) + # pyrefly: ignore [missing-attribute] + return pytree.tree_map_only(np.ndarray, lambda x: torch.as_tensor(x), out) + + return wrap + + +class FakeBackwardCFunction: + def __init__( + self, + real: torch.autograd.function.BackwardCFunction, + saved_tensors: list[torch.Tensor], + ) -> None: + self.real = real + self.saved_tensors = saved_tensors + + def __getattr__(self, name: str) -> Any: + if name == "saved_variables": + warnings.warn( + "'saved_variables' is deprecated; use 'saved_tensors'", + DeprecationWarning, + ) + return self.saved_tensors + + return getattr(self.real, name) + + +def call_backward( + backward_c_function: torch.autograd.function.BackwardCFunction, + saved_tensors: list[torch.Tensor], + *args: Any, +) -> Union[torch.Tensor, tuple[torch.Tensor, ...]]: + fake = FakeBackwardCFunction(backward_c_function, saved_tensors) + grads = fake._forward_cls.backward(fake, *args) # type: ignore[attr-defined] + + if not isinstance(grads, tuple): + grads = (grads,) + + return grads + + +def normalize_as_list(x: Any) -> list[Any]: + if isinstance(x, tuple): + return list(x) + elif isinstance(x, list): + return x + return [x] + + +def untyped_storage_size(x: torch.Tensor) -> int: + return x.untyped_storage().size() + + +class FakeCompiledAutogradEngine: + @staticmethod + def queue_callback( + final_callbacks: list[Callable[[], None]], cb: Callable[[], None] + ) -> None: + final_callbacks.append(cb) + + @staticmethod + def exec_final_callbacks(final_callbacks: list[Callable[[], None]]) -> None: + i = 0 + while i < len(final_callbacks): + cb = final_callbacks[i] + cb() + i += 1 + final_callbacks.clear() + + @staticmethod + def _exec_final_callbacks_stub() -> None: + pass + + +def call_hook_from_backward_state( + *args: Any, bw_state: Any, hook_name: str, **kwargs: Any +) -> Any: + return getattr(bw_state, hook_name)(*args, **kwargs) + + +def call_module_hooks_from_backward_state( + _: Any, result: Any, *args: Any, bw_state: Any, hooks_name: str, module_name: str +) -> Any: + module = getattr(bw_state, module_name) + hooks = getattr(bw_state, hooks_name) + for hook in hooks: + new_result = hook(module, result, *args) + if new_result is not None: + result = new_result + return result + + +# used for torch._dynamo.disable(recursive=False) +def get_nonrecursive_disable_wrapper(fn: Callable[_P, _R]) -> Callable[_P, _R]: + # wrap function to get the right error message + # this function is in external_utils so that convert_frame doesn't skip it. + @functools.wraps(fn) + def nonrecursive_disable_wrapper(*args: _P.args, **kwargs: _P.kwargs) -> _R: + if torch.compiler.is_exporting(): + raise RuntimeError( + "Non-recursive torch.compiler.disable is not supported with torch.export." + ) + return fn(*args, **kwargs) + + return nonrecursive_disable_wrapper + + +def wrap_dunder_call_ctx_manager(self: Any, func: Callable[_P, _R]) -> Callable[_P, _R]: + """ + Apply self as a ctx manager around a call to func + """ + + # NOTE: do not functools.wraps(func) because we don't ever want this frame to be skipped! + def inner(*args: _P.args, **kwargs: _P.kwargs) -> _R: + with self: + return func(*args, **kwargs) + + return inner + + +# Use only on ints marked dynamic via torch.empty(0, integer) +# Currently only way to mark ints as dynamic: https://github.com/pytorch/pytorch/issues/129623 +def unwrap_maybe_dynamic_int(x: Union[torch.Tensor, int]) -> int: + if isinstance(x, torch.Tensor): + # x.size() is expected to be [0, dynamic_int] + return x.size(1) + return x + + +def call_accumulate_grad( + variable: torch.Tensor, grad: torch.Tensor, has_post_hooks: bool +) -> None: + updated_grad = torch._dynamo.compiled_autograd.ops.AccumulateGrad( # type: ignore[attr-defined] + [grad], variable, variable.grad, has_post_hooks + ) + variable.grad = updated_grad[0] + + +def wrap_inline_with_error_on_graph_break( + fn: Callable[_P, _R], error_on_graph_break: bool +) -> Callable[_P, _R]: + # NB: need multiple definitions in order to prevent `fullgraph` from + # being a freevar of wrapper + # NOTE: do not functools.wraps(fn) because we don't ever want these wrappers to be skipped! + if error_on_graph_break: + + def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> _R: + with torch._dynamo.error_on_graph_break(True): + return fn(*args, **kwargs) + + else: + + def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> _R: + with torch._dynamo.error_on_graph_break(False): + return fn(*args, **kwargs) + + return wrapper + + +def filter_out_const_values(tup: tuple[Any, ...], masks: list[bool]) -> tuple[Any, ...]: + """ + masks is a list of bools, where True means the corresponding element in tup + is a const value. Filter out the const values. + """ + out = [] + for mask_idx, mask in enumerate(masks): + if not mask: + out.append(tup[mask_idx]) + return tuple(out) + + +def insert_const_values_with_mask( + tup: tuple[Any, ...], masks: list[bool], values: tuple[Any, ...] +) -> tuple[Any, ...]: + """ + masks and values are of same length. For indices where the mask is True, use + the const_values to fill in. + """ + out = [] + idx = 0 + for mask_idx, mask in enumerate(masks): + if mask: + out.append(values[mask_idx]) + else: + out.append(tup[idx]) + idx += 1 + return tuple(out) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_environment.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_environment.py new file mode 100644 index 0000000000000000000000000000000000000000..65cbd5d35ad5164f66f37a7d75ac29e4df5f5cfa --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_environment.py @@ -0,0 +1,2 @@ +def is_fbcode() -> bool: + return False diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_guards.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_guards.py new file mode 100644 index 0000000000000000000000000000000000000000..798dd1758740269878589327b886eca7f8a5e924 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_guards.py @@ -0,0 +1,1319 @@ +from __future__ import annotations + +import contextlib +import dataclasses +import enum +import functools +import logging +import re +import sys +import threading +import traceback +import unittest.mock +import weakref +from abc import abstractmethod +from collections import defaultdict +from contextlib import contextmanager +from dataclasses import dataclass +from typing import Any, Generic, NamedTuple, Optional, overload, TYPE_CHECKING, TypeVar + + +if sys.version_info >= (3, 11): + from typing import dataclass_transform +else: + + def dataclass_transform(): + def decorator(fn): + return fn + + return decorator + + +import torch +from torch.utils import _pytree as pytree +from torch.utils._ordered_set import OrderedSet +from torch.utils._python_dispatch import is_traceable_wrapper_subclass +from torch.utils._traceback import CapturedTraceback, format_frame +from torch.utils.weak import WeakTensorKeyDictionary + + +log = logging.getLogger(__name__) + + +if TYPE_CHECKING: + from collections.abc import Callable, Generator, Iterator + from types import CodeType + + import sympy + + from torch._dynamo.backends.distributed import DDPOptimizerContext + from torch._dynamo.codegen import PyCodegen + from torch._functorch._aot_autograd.schemas import ViewAndMutationMeta + from torch._subclasses.fake_tensor import FakeTensorMode + + +""" +torch._guards is the definitional source of truth for general purpose guard structures. + +An important thing to keep in mind here is the preservation of layering. There should be no dynamo notions, +and no guard installation notions here. +""" + +COMPILE_ID_PATTERN = re.compile(r"^(?P\d+)/(?P\d+)$") +CA_COMPILE_ID_PATTERN = re.compile( + r"^!(?P\d+)(?:/(?P\d+)/(?P\d+))?$" +) + +# [Note: Updating CompiledId] +# +# CompiledId represents a unique program-level identifier, and we want to keep that +# property as the codebase evolves. This property is relied on even outside of the pytorch +# repo, e.g. tlparse or other internal tooling. The in-memory format can be freely changed, +# as those dependencies only consume the string serialization. +# +# The string form should be: +# 1. Program-level uid: CompileId can uniquely identify a compiled graph. +# 2. Storage efficient: This object is logged in nearly every entry. We should elide symbols when possible. +# 3. Compact: The string form is directly displayed by some tools. Special symbols are okay. + + +@dataclass(frozen=True, kw_only=True, slots=True) +class CompileId: + frame_id: int | None + # This id is per-frame, and counts how many times we've compiled this + # frame. This could have been a global id but having this be per-frame + # gives you a better intuitive sense for how many recompiles have occurred + # so far. + frame_compile_id: int | None + + # torch.compiling a compiled autograd graph + compiled_autograd_id: int | None = None + + # TODO: consider also tracking the recompilation count + # See Note: Updating CompileId + + def __str__(self) -> str: + # NOTE: Keep this in sync with both from_string and the tlparse repo + if self.compiled_autograd_id is not None: + assert (self.frame_id is None) == (self.frame_compile_id is None) + frame_str = "" + if self.frame_id is not None: + frame_str = f"/{self.frame_id}/{self.frame_compile_id}" + + return f"!{self.compiled_autograd_id}{frame_str}" + else: + assert self.frame_id is not None and self.frame_compile_id is not None + return f"{self.frame_id}/{self.frame_compile_id}" + + @classmethod + def from_string(cls, compile_id: str | None) -> CompileId | None: + """ + Factory method that creates a CompileId from its string representation. + Keep this in sync with the __str__ method. + """ + if compile_id is None: + return None + try: + for pattern in (COMPILE_ID_PATTERN, CA_COMPILE_ID_PATTERN): + if match := pattern.match(compile_id): + groups = match.groupdict() + for k, v in groups.items(): + if v is not None: + groups[k] = int(v) + return cls(**groups) # type: ignore[arg-type] + else: + raise ValueError + + except Exception as e: + raise ValueError(f"Invalid compile_id '{compile_id}'") from e + + +class TraceId(NamedTuple): + compile_id: CompileId + # This starts off as 0, and every time we restart analysis it goes + # up by one + attempt: int + + def __str__(self) -> str: + # Keep this in sync with tlparse repo + if self.attempt == 0: + return str(self.compile_id) + else: + return f"{self.compile_id}_{self.attempt}" + + +class GuardSource(enum.Enum): + LOCAL = 0 + GLOBAL = 1 + LOCAL_SPECIALIZED_NN_MODULE = 2 + GLOBAL_SPECIALIZED_NN_MODULE = 3 + CONSTANT = 4 + RANDOM_VALUE = 5 + SHAPE_ENV = 6 + LOCAL_FSDP_MODULE = 7 + GLOBAL_FSDP_MODULE = 8 + BACKWARD_STATE = 9 + EPHEMERAL = 10 + SYNTHETIC_LOCAL = 11 + LOCAL_UNSPECIALIZED_NN_MODULE = 12 + GLOBAL_UNSPECIALIZED_NN_MODULE = 13 + LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULE = 14 + GLOBAL_UNSPECIALIZED_BUILTIN_NN_MODULE = 15 + TEMP_LOCAL = 16 + + def is_fsdp_module(self) -> bool: + return self in (GuardSource.GLOBAL_FSDP_MODULE, GuardSource.LOCAL_FSDP_MODULE) + + def is_specialized_nn_module(self) -> bool: + import torch._dynamo.config as config + + if config._unsafe_skip_fsdp_module_guards: + return ( + self + in ( + GuardSource.GLOBAL_SPECIALIZED_NN_MODULE, + GuardSource.LOCAL_SPECIALIZED_NN_MODULE, + ) + or self.is_fsdp_module() + ) + return self in ( + GuardSource.GLOBAL_SPECIALIZED_NN_MODULE, + GuardSource.LOCAL_SPECIALIZED_NN_MODULE, + ) + + def is_unspecialized_nn_module(self) -> bool: + return self in ( + GuardSource.GLOBAL_UNSPECIALIZED_NN_MODULE, + GuardSource.LOCAL_UNSPECIALIZED_NN_MODULE, + GuardSource.GLOBAL_UNSPECIALIZED_BUILTIN_NN_MODULE, + GuardSource.LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULE, + ) + + def is_unspecialized_builtin_nn_module(self) -> bool: + return self in ( + GuardSource.GLOBAL_UNSPECIALIZED_BUILTIN_NN_MODULE, + GuardSource.LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULE, + ) + + def is_local(self) -> bool: + return self in ( + GuardSource.LOCAL, + GuardSource.LOCAL_SPECIALIZED_NN_MODULE, + GuardSource.LOCAL_FSDP_MODULE, + GuardSource.LOCAL_UNSPECIALIZED_NN_MODULE, + GuardSource.LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULE, + ) + + +""" +Base class for a "GuardBuilder" role. + +The GuardBuilderBase role is to represent a scope within which to build a guard. The name is a little +confusing, as its not a builder, but for the sake of avoiding a lot of renames and keeping the original reference +to torchdynamo's GuardBuilder. + +Note: create_fn is invoked with a GuardBuilderBase and a Guard. A GuardBuilder is chosen based +on GuardSource's select function. + +There is value in keeping this GuardBuilderBase empty to keep layering clean. +""" + + +class GuardBuilderBase: + pass + + +@dataclasses.dataclass(frozen=True) +class SLoc: + framework_loc: traceback.FrameSummary | str | None + maybe_user_loc: str | None + + def __str__(self) -> str: + floc = ( + self.framework_loc + if isinstance(self.framework_loc, str) + else format_frame(self.framework_loc) + ) + if self.maybe_user_loc is not None: + return f"{self.maybe_user_loc} ({floc})" + else: + return f"({floc})" + + +class ShapeGuard(NamedTuple): + expr: sympy.logic.boolalg.Boolean + sloc: SLoc + size_oblivious: bool + + +@dataclasses.dataclass(slots=True) +class Guard: + # originating_source is the source that called the make_guard method to + # construct this guard object. The property name specifies what exactly it + # is the guard is guarding on. The meaning of the name is dependent on the + # create_fn; you must look at the use-site inside create_fn to know what + # name means. + # + # That being said, although you might think this is just a "name", name is + # usually an arbitrary Python expression that will be evaluated with all + # globals (and locals, if you create a LOCAL guard) to extract the Python + # object that we want to perform guard tests on. This evaluation + # typically happens in GuardBuilder.eval. In these cases, name is + # typically produced by originating_source.name (not to be confused with + # GuardSource - the property source). + # + # Occasionally, name is not a valid Python expression; sometimes + # it is meaningless. Example create_fns that are like this include + # GRAD_MODE and SHAPE_ENV. + originating_source: Source + create_fn: Callable[[GuardBuilderBase, Guard], None] + + # Export only. These values are written to at time of guard check_fn creation. + guard_types: list[str] | None = None + code_list: list[str] | None = None + obj_weakref: object | None = None + guarded_class_weakref: weakref.ReferenceType[Any] | None = None + + stack: CapturedTraceback | None = None + user_stack: traceback.StackSummary | None = None + _hash: int | None = None + _unserializable: bool = False + + def __hash__(self) -> int: + if self._hash is None: + self._hash = hash((self.name, self.source, id(self.create_fn))) + return self._hash + + def sort_key(self) -> tuple[bool, int, int, str, int]: + # Put the duplicate input guards at the end. The duplicate guards have + # two sources while guard.name only considers one source. + + is_duplicate_input = ( + isinstance(self.create_fn, functools.partial) + and self.create_fn.func is torch._dynamo.guards.GuardBuilder.DUPLICATE_INPUT + ) + return ( + is_duplicate_input, + self.source.value if self.source else -1, + len(self.name), + self.name, + self.inner_create_fn().__code__.co_firstlineno, + ) + + def __lt__(self, other: Guard) -> bool: + return self.sort_key() < other.sort_key() + + def inner_create_fn(self) -> Callable[[GuardBuilderBase, Guard], Any]: + if isinstance(self.create_fn, functools.partial): + return self.create_fn.func + else: + return self.create_fn + + @property + def name(self) -> str: + return self.originating_source.name + + @property + def source(self) -> GuardSource: + return self.originating_source.guard_source + + @staticmethod + def weakref_to_str(obj_weakref: object) -> str: + """ + This is a workaround of a Python weakref bug. + + `obj_weakref` is instance returned by `weakref.ref`, + `str(obj_weakref)` is buggy if the original obj overrides __getattr__, e.g: + + class MyConfig(dict): + def __getattr__(self, x): + return self[x] + + obj = MyConfig(offset=5) + obj_weakref = weakref.ref(obj) + str(obj_weakref) # raise error: KeyError: '__name__' + """ + if isinstance(obj_weakref, weakref.ReferenceType): + obj = obj_weakref() + if obj is not None: + return f"" + else: + return f"" + else: + return str(obj_weakref) + + def __repr__(self) -> str: + s = f""" + {self.source.name.lower() if self.source else ""} {repr(self.name)} {self.inner_create_fn().__name__} + {{ + 'guard_types': {self.guard_types}, + 'code': {self.code_list}, + 'obj_weakref': {self.weakref_to_str(self.obj_weakref)} + 'guarded_class': {self.guarded_class_weakref} + }} + """ + return s + + def __str__(self) -> str: + output = f"Name: {repr(self.name)}\n" + source = self.source.name.lower() if self.source else "" + output += f" Source: {source}\n" + output += f" Create Function: {self.inner_create_fn().__name__}\n" + output += f" Guard Types: {self.guard_types}\n" + output += f" Code List: {self.code_list}\n" + output += f" Object Weakref: {self.weakref_to_str(self.obj_weakref)}\n" + output += f" Guarded Class Weakref: {self.guarded_class_weakref}\n" + return output + + def create(self, builder: GuardBuilderBase) -> Any: + try: + return self.create_fn(builder, self) + except Exception: + log.exception("Error while creating guard:\n%s", str(self).rstrip()) + if self.stack: + log.error("Created at:\n%s", "".join(self.stack.format()[-4:]).rstrip()) + raise + + def is_specialized_nn_module(self) -> bool: + return self.source.is_specialized_nn_module() + + def is_fsdp_module(self) -> bool: + return self.source.is_fsdp_module() + + def is_local(self) -> bool: + return self.source.is_local() + + def create_fn_name(self) -> str: + if isinstance(self.create_fn, functools.partial): + create_fn = self.create_fn.func # type: ignore[attr-defined] + else: + create_fn = self.create_fn + return create_fn.__name__ + + def set_export_info( + self, + guard_type: str, + guarded_class: weakref.ReferenceType[Any] | None, + code_list: list[str], + obj_weakref: object, + ) -> None: + if not self.guard_types: + self.guard_types = [] + + self.guard_types.append(guard_type) + + assert self.guarded_class_weakref in ( + guarded_class, + None, + ), "Guarded class id must be identical, or None" + self.guarded_class_weakref = guarded_class + + if not self.code_list: + self.code_list = code_list + else: + self.code_list.extend(code_list) + + # Some objects are ephemeral, e.g., list[slice(1, 2)]. If we have + # multiple guards on the same object, the weakref can die between the + # invocation of set_export_info calls. So a dead weakref is also + # acceptable. + assert ( + self.obj_weakref in (obj_weakref, None) + or callable(self.obj_weakref) + and self.obj_weakref() is None + ), "Guarded object must be identical, None or ephemeral (dead weakref)" + self.obj_weakref = obj_weakref + + +T = TypeVar("T") + +""" +Parent structure for guard env expressions. +A GuardEnvExpr can have any subtype. +Note: All subtypes must be handled exhaustively in +torch._dynamo.guards._parse_guard_env_guards to avoid a RuntimeError. +""" + + +@dataclasses.dataclass(frozen=True) +class GuardEnvExpr: + pass + + +""" +A class representing a pair of duplicate inputs. +input_pos_a and input_pos_b are input positions we have deduped. +""" + + +@dataclasses.dataclass(frozen=True) +class DuplicateInputs(GuardEnvExpr): + input_source_a: Source + input_source_b: Source + + def __post_init__(self) -> None: + assert self.input_source_a != self.input_source_b + + +""" +A class representing storage overlap relations among inputs that aliases the same storage. + +Given that a set of tensors alias the same storage, this guard checks whether they actually +have overlapping storages. + +While non_overlapping_sources represent input tensors that definitely don't have any storage +overlapping with any other input, overlapping_sources represent tensors that either: + +1. Do overlap some other input tensor +2. Might not overlap some other input tensor, but we are not sure +""" + + +@dataclasses.dataclass(frozen=True) +class StorageOverlap(GuardEnvExpr): + overlapping_sources: list[Source] + non_overlapping_sources: list[Source] + + +""" +Checkpointable is an interface for driving state snapshotting, left purposely vague for now. + +copy_graphstate() -> T, a somewhat legacy name, is expected to emit a snapshot of any type that +can also be taken in at restore_graphstate(T) calls. + +When to snapshot, is, at the moment, an implementation detail of upstream callers. Checkpointable +does not provide any guarantees around consistency, idempotency, or safety of calling its APIs, yet. + +In the future, it will have a closer coupling to a generic Checkpoint management system. +""" + + +class Checkpointable(Generic[T]): + @abstractmethod + def copy_graphstate(self) -> T: ... + + @abstractmethod + def restore_graphstate(self, state: T) -> None: ... + + +class GuardsCheckpointState: + """ + The GuardCheckpointState - it is the T of Checkpointable[T] for GuardsContext + """ + + dynamo_guards: OrderedSet[Guard] + + def __init__(self, dynamo_guards: OrderedSet[Guard]) -> None: + self.dynamo_guards = dynamo_guards + + def diff(self, other: GuardsCheckpointState) -> Optional[OrderedSet[Guard]]: + """ + Produces a delta against another GuardsCheckpointState. + + Returns None if no delta is found, otherwise, return an OrderedSet() of mismatched + Guard type objects. + """ + r = self.dynamo_guards.difference(other.dynamo_guards) + if len(r) == 0: + return None + return r + + def __eq__(self, other: object) -> bool: + if not isinstance(other, GuardsCheckpointState): + return False + return self.diff(other) is None + + +class ModuleContextCheckpointState: + nn_modules: dict[str, torch.nn.Module] = {} + + def __init__(self, nn_modules: dict[str, torch.nn.Module]) -> None: + self.nn_modules = nn_modules + + def diff(self, other: ModuleContextCheckpointState) -> set[str] | None: + """ + Produces a delta against another ModuleContextCheckpointState. + + Returns None if no delta is found, otherwise, return a set() of mismatched + module key names. + """ + r = set(self.nn_modules.keys()).difference(set(other.nn_modules.keys())) + if len(r) == 0: + return None + return r + + def __eq__(self, other: object) -> bool: + if not isinstance(other, ModuleContextCheckpointState): + return False + return self.diff(other) is None + + +class ModuleContext(Checkpointable[ModuleContextCheckpointState]): + def __init__(self) -> None: + self.nn_modules: dict[str, Any] = {} + + def copy_graphstate(self) -> ModuleContextCheckpointState: + return ModuleContextCheckpointState(dict(self.nn_modules)) + + def restore_graphstate(self, state: ModuleContextCheckpointState) -> None: + assert isinstance(state, ModuleContextCheckpointState) + self.nn_modules = state.nn_modules + + +class GlobalContextCheckpointState: + global_state: dict[str, tuple[Callable, Any]] = {} + + def __init__(self, global_states: dict[str, tuple[Callable, Any]]) -> None: + self.global_state = global_states + + def diff(self, other: GlobalContextCheckpointState) -> set[str] | None: + """ + Produces a delta against another GlobalContextCheckpointState. + + Returns None if no delta is found, otherwise, return a set() of mismatched + global key names. + """ + r = set(self.global_state.keys()).difference(set(other.global_state.keys())) + if len(r) == 0: + return None + return r + + def __eq__(self, other: object) -> bool: + if not isinstance(other, GlobalContextCheckpointState): + return False + return self.diff(other) is None + + +class GlobalContext(Checkpointable[GlobalContextCheckpointState]): + """ + This keeps track of the global torch state during tracing of a function. + For example, torch.is_grad_enabled. + """ + + _supported_global_states = { + "grad_enabled", + "autocast_enabled", + "autocast_cpu_enabled", + "autocast_gpu_dtype", + "autocast_cpu_dtype", + "autocast_cache_enabled", + } + + def __init__(self) -> None: + self.global_state: dict[str, tuple[Callable, Any]] = {} + + def copy_graphstate(self) -> GlobalContextCheckpointState: + return GlobalContextCheckpointState(self.global_state) + + def restore_graphstate(self, state: GlobalContextCheckpointState) -> None: + assert isinstance(state, GlobalContextCheckpointState) + self.global_state = state.global_state + assert ( + len(self.global_state) == len(self._supported_global_states) + and set(self.global_state.keys()) == self._supported_global_states + ), "Global state mismatch" + for func, args in self.global_state.values(): + func(args) + + +# Like a Set[Guard] but will record the user stack on all guards at the +# time they were installed at their destination +class GuardsSet: + def __init__(self, inner: Optional[OrderedSet[Guard]] = None) -> None: + if inner is None: + self.inner: OrderedSet[Guard] = OrderedSet() + else: + self.inner = inner + + def __iter__(self) -> Iterator[Guard]: + return iter(self.inner) + + def __len__(self) -> int: + return len(self.inner) + + # Subtraction along with bool is typically used to determine the delta of + # added guards between checkpoints for higher order ops + def __sub__(self, other: GuardsSet) -> GuardsSet: + return GuardsSet(self.inner - other.inner) + + def __bool__(self) -> bool: + return bool(self.inner) + + def add( + self, guard: Guard, *, collect_debug_stack: bool = True, skip: int = 0 + ) -> None: + if guard in self.inner: + return + if collect_debug_stack: + if guard.stack is None: + guard.stack = CapturedTraceback.extract(skip=1 + skip) + if guard.user_stack is None: + guard.user_stack = TracingContext.extract_stack() + self.inner.add(guard) + + def update(self, *others: set[Guard]) -> None: + for o in others: + for g in o: + self.add(g, skip=1) + + def remove_guards_with_source(self, source: Source) -> None: + """Delete all guards that contains a given source""" + from ._dynamo.source import is_from_source + + self.inner = OrderedSet( + g for g in self.inner if not is_from_source(g.originating_source, source) + ) + + +""" +A GuardsContext is a checkpointable representation of all the guards in the current tracing +context. It's lifecycle is bound 1:1 to the tracing context, and it should never be instantiated +directly outside of it. For passing around internal state representations of this object, +prefer to extract them with copy_graphstate to produce a GuardsCheckpointState. +""" + + +class GuardsContext(Checkpointable[GuardsCheckpointState]): + def __init__(self) -> None: + self.dynamo_guards: GuardsSet = GuardsSet() + self.aotautograd_guards: list[GuardEnvExpr] = [] + + def copy_graphstate(self) -> GuardsCheckpointState: + return GuardsCheckpointState(OrderedSet(self.dynamo_guards.inner)) + + def restore_graphstate(self, state: GuardsCheckpointState) -> None: + # NB: "steals" the passed in state + assert isinstance(state, GuardsCheckpointState) + self.dynamo_guards = GuardsSet(state.dynamo_guards) + + +class HopSubgraphCache: + @abstractmethod + def add_dynamo_installed_submodule(self, fn_id: int, identifier: str) -> None: ... + + @abstractmethod + def get_dynamo_installed_submodules(self, fn_id: int) -> list[str]: ... + + @abstractmethod + def add_autograd_key_entry(self, identifier: str, key: Callable) -> None: ... + + @abstractmethod + def get_autograd_key_entry(self, identifier: str) -> Callable | None: ... + + @abstractmethod + def add_proxy_dispatch_entry(self, identifier: str, key: Callable) -> None: ... + + @abstractmethod + def get_proxy_dispatch_entry(self, identifier: str) -> Callable | None: ... + + @abstractmethod + def add_lazy_bwd_entry( + self, + identifier: str, + tangent_metadata: tuple[object], + gmod: torch.fx.GraphModule, + ) -> int: ... + + @abstractmethod + def get_lazy_bwd_entry( + self, identifier: str, tangent_metadata: tuple[object] + ) -> tuple[torch.fx.GraphModule | None, int | None]: ... + + +class InvokeSubgraphCache(HopSubgraphCache): + def __init__(self) -> None: + self.autograd_cache: dict[str, Callable] = {} + self.proxy_dispatch_cache: dict[str, Callable] = {} + self.dynamo_installed_submodules: dict[int, list[str]] = defaultdict(list) + self.lazy_bwd_cache: dict[ + str, dict[tuple[object], tuple[torch.fx.GraphModule, int]] + ] = defaultdict(dict) + self.effects_cache: dict[ + str, set + ] = {} # Maps identifier -> set of effect types + + def add_dynamo_installed_submodule(self, fn_id: int, identifier: str) -> None: + self.dynamo_installed_submodules[fn_id].append(identifier) + + def get_dynamo_installed_submodules(self, fn_id: int) -> list[str]: + return self.dynamo_installed_submodules.get(fn_id, []) + + def add_autograd_key_entry(self, identifier: str, key: Callable) -> None: + self.autograd_cache[identifier] = key + + def get_autograd_key_entry(self, identifier: str) -> Callable | None: + return self.autograd_cache.get(identifier, None) + + def add_proxy_dispatch_entry(self, identifier: str, key: Callable) -> None: + self.proxy_dispatch_cache[identifier] = key + + def get_proxy_dispatch_entry(self, identifier: str) -> Callable | None: + return self.proxy_dispatch_cache.get(identifier, None) + + def add_lazy_bwd_entry( + self, + identifier: str, + tangent_metadata: tuple[object], + gmod: torch.fx.GraphModule, + ) -> int: + # Save the number of existing graph modules in the dictionary to get the suffix + num_gmods = len(self.lazy_bwd_cache[identifier]) + self.lazy_bwd_cache[identifier][tangent_metadata] = (gmod, num_gmods) + return num_gmods + + def get_lazy_bwd_entry( + self, identifier: str, tangent_metadata: tuple[object] + ) -> tuple[torch.fx.GraphModule | None, int | None]: + if identifier not in self.lazy_bwd_cache: + return (None, None) + + return self.lazy_bwd_cache[identifier].get(tangent_metadata, (None, None)) + + def add_effects(self, identifier: str, effects: set) -> None: + """Store the effect types for a given invoke_subgraph identifier.""" + if prev_effects := self.effects_cache.get(identifier, None): + assert effects == prev_effects, ( + "Different number of effects were found for invoke_subgraph " + f"call with identifier {identifier}. \n" + f"Previously we had the following effects: {prev_effects}.\n" + f"But now we have: {effects}." + ) + self.effects_cache[identifier] = effects + + def get_effects(self, identifier: str) -> set | None: + """Retrieve the effect types for a given invoke_subgraph identifier.""" + return self.effects_cache.get(identifier, None) + + +class HopDispatchSetCache: + def __init__(self) -> None: + # Delayed import to avoid circular dependency + from torch._higher_order_ops.invoke_subgraph import invoke_subgraph + + self.hop_cache_map = {invoke_subgraph: InvokeSubgraphCache()} + + def get_cache(self, op: torch._ops.HigherOrderOperator) -> HopSubgraphCache | None: + if op not in self.hop_cache_map: + return None + return self.hop_cache_map[op] # type: ignore[index] + + +_TLS = threading.local() + +""" +TracingContext is the source of truth for all currently accumulated information +needed to trace. Its lifecycle is kept 1:1 when using TorchDynamo, but other systems +are open to managing their own TracingContext with that in mind. + +The purpose of TracingContext is not to be a dumping ground, or god object, but rather to avoid +having to plumb complex subsystems across multiple verticals. + +Ex: A common example is guard accumulation between dynamo, shape_env, aot_autograd, and inductor. +Accessing the current tracing context via +TracingContext.get() allows users to accumulate their own guards for processing, without needing to know how +to plumb objects back up to where frame interpretation happened. + +Note that you can end up with multiple TracingContext for a single compilation +of a frame, as we reset the TracingContext whenever we restart analysis. +CompileContext is a more overarching context that encompasses multiple restarts. +""" + + +class CompileContext: + @staticmethod + def get() -> CompileContext: + assert _TLS.compile_context is not None + return _TLS.compile_context + + @staticmethod + def try_get() -> CompileContext | None: + return getattr(_TLS, "compile_context", None) + + def __init__(self, compile_id: CompileId | None) -> None: + assert compile_id is None or isinstance(compile_id, CompileId) + self.compile_id: CompileId | None = compile_id + self.attempt = 0 + # Verbose ShapeEnv guards produced. + self.shape_env_guards: list[str] = [] + + @staticmethod + def current_compile_id() -> CompileId | None: + self = CompileContext.try_get() + if self is None: + return None + return self.compile_id + + @staticmethod + def current_trace_id() -> TraceId | None: + self = CompileContext.try_get() + if self is None: + return None + if self.compile_id is None: + return None + return TraceId(self.compile_id, self.attempt) + + +class TracingContext: + """ + Provides the currently installed TracingContext, or None. + + Note that it is a staticmethod, and invocations outside of `with tracing()` (see below), are valid but + will return None. + """ + + @staticmethod + def try_get() -> TracingContext | None: + return getattr(_TLS, "tracing_context", None) + + @staticmethod + def get() -> TracingContext: + if ctx := TracingContext.try_get(): + return ctx + raise RuntimeError( + "TracingContext.get() must be called within an ongoing trace." + ) + + def __init__(self, fake_mode: FakeTensorMode | None) -> None: + self.guards_context = GuardsContext() + self.module_context = ModuleContext() + self.global_context = GlobalContext() + self.previously_inlined_functions: dict[Any, Any] = dict() + self.previously_cleaned_instructions: dict[Any, Any] = dict() + self.fake_mode: FakeTensorMode | None = fake_mode + self.frame_summary_stack: list[traceback.FrameSummary] = [] + # This is morally part of frame_summary_stack, but it is kept separate + # for clarity. As we process a frame, this variable gets updated + # to keep track of what line we are in the function. We make a + # function call, this gets cleared and the frame location is pushed + # to frame_summary_stack (prepping this variable for the inner frame's + # progress) + self.loc_in_frame: tuple[str, int, str] | None = None + # this is only set after aot_autograd + self.fw_metadata: ViewAndMutationMeta | None = None + # this is only set when the DDPOptimizer is used + self.ddp_optimizer_ctx: DDPOptimizerContext | None = None + # this is only set after aot_autograd + self.aot_graph_name: list[str] | None = None + self.params_flat: list[Any] | None = None + self.params_flat_unwrap_subclasses: list[Any] | None = None + self.params_unwrapped_to_flat_index: list[Any] | None = None + # this is for extended return calling convention from backend + # compiler to aot_autograd + # Per output, what the compiler specified stride of the output is, + # or None if no stride is known. This is always the HINT, it + # is never a SymInt (it would be better if it was a SymInt, but + # I can't conveniently get this from Inductor atm. Also, be + # careful not to accidentally induce guards on the SymInt if + # you ever do change this in aot_autograd.py; you should check + # on permutations preferentially.) + self.output_strides: list[tuple[int, ...] | None] | None = None + # When this is True, whenever we encounter an int in Dynamo tracing, + # we will (1) force unspec it and (2) force it as a size-like unbacked + # integer. This is currently used when processing certain lists of + # ints that are known to be size-like and may have 0/1 entries that we + # must not specialize on. + self.force_unspec_int_unbacked_size_like = False + # See note [Tensor Fakification and Symbol Caching] + self.tensor_to_context = WeakTensorKeyDictionary() + + # If this true, Aot Autograd will return output Fake Tensors with appropriate + # meta on the first invocation + # see note: [Returning Fake Tensors on First AOT Autograd Call] + self.fakify_first_call = False + self.hop_dispatch_set_cache = HopDispatchSetCache() + # list of code objects for inlined functions + self.traced_code: list[CodeType] = [] + + def clear(self) -> None: + # Look at the note in output_graph.py in function `save_global_state` + # for the context on clearing global context. + self.global_context.global_state = {} + self.previously_inlined_functions.clear() + self.previously_cleaned_instructions.clear() + + @staticmethod + @contextmanager + def patch(**kwargs: Any) -> Generator[None, None, None]: + prior = {} + ctx = TracingContext.get() + + for key in kwargs: + # KeyError on invalid entry + prior[key] = getattr(ctx, key) + for key, val in kwargs.items(): + setattr(ctx, key, val) + try: + yield + finally: + for key, val in prior.items(): + setattr(ctx, key, val) + + @staticmethod + def extract_stack() -> traceback.StackSummary: + self = TracingContext.try_get() + if self is None: + return traceback.StackSummary() + stack = self.frame_summary_stack + if self.loc_in_frame is not None: + stack = stack + [self._populate_loc_in_frame_summary()] + return traceback.StackSummary.from_list(stack) + + def _populate_loc_in_frame_summary(self) -> traceback.FrameSummary: + assert self.loc_in_frame is not None + filename, lineno, frame_name = self.loc_in_frame + return traceback.FrameSummary(filename, lineno, frame_name, lookup_line=False) + + # Call this when you want to call into some code that isn't necessarily + # associated with the current frame state + @staticmethod + @contextlib.contextmanager + def clear_frame() -> Generator[None, None, None]: + tc = TracingContext.get() + with ( + unittest.mock.patch.object(tc, "frame_summary_stack", []), + unittest.mock.patch.object(tc, "loc_in_frame", None), + ): + try: + yield + except Exception as e: + # Prevent real_stack from getting attached + # + # The invariant is that if an Exception as real_stack, we've + # appropriately attached a user stack and we no longer need to + # attach anything. Because we cannot conveniently interpose + # when an exception is thrown, we instead interpose everywhere + # we set what the user stack is set (using the context + # manager). However, our compiler stack does "tail calls" + # (when it calls into user compiler), at which point the + # parent exception frames would incorrectly attach an + # incorrect frame. + # + # However, if, somehow, someone raised an exception with this + # scope that had a stack (for example, because they are + # restoring the user stack state appropriately as they process + # node by node), we should respect it. Thus, we cannot + # unconditionally set None. + if not hasattr(e, "real_stack"): + e.real_stack = None # type: ignore[attr-defined] + raise + + @staticmethod + @contextlib.contextmanager + def current_frame( + frame_summary: traceback.FrameSummary | None, + ) -> Generator[None, None, None]: + # frame_summary can be None to solely take advantage of real_stack + # attachment to thrown exceptions + tc = TracingContext.get() + if frame_summary is not None: + tc.frame_summary_stack.append(frame_summary) + old = tc.loc_in_frame + tc.loc_in_frame = None + try: + yield + except Exception as e: + if not hasattr(e, "real_stack"): + e.real_stack = tc.extract_stack() # type: ignore[attr-defined] + raise + finally: + if frame_summary is not None: + tc.frame_summary_stack.pop() + tc.loc_in_frame = old + + @staticmethod + @contextlib.contextmanager + def report_output_strides() -> Generator[ + list[tuple[int, ...] | None] | None, None, None + ]: + tc = TracingContext.try_get() + if tc is None: + yield None + return + old_output_strides = tc.output_strides + tc.output_strides = [] + try: + yield tc.output_strides + finally: + tc.output_strides = old_output_strides + + @staticmethod + def set_current_loc(filename: str, lineno: int, frame_name: str) -> None: + # Save the current location in the frame. Lazily generate the + # framesummary. + TracingContext.get().loc_in_frame = (filename, lineno, frame_name) + + @staticmethod + def get_traced_code() -> list[CodeType] | None: + tc = TracingContext.try_get() + if tc is None: + return None + return tc.traced_code + + +@contextmanager +def compile_context( + context: CompileContext | None, +) -> Generator[CompileContext | None, None, None]: + old_context = getattr(_TLS, "compile_context", None) + _TLS.compile_context = context + try: + yield context + finally: + _TLS.compile_context = old_context + + +@contextmanager +def tracing( + context: TracingContext | None, +) -> Generator[TracingContext | None, None, None]: + """ + This function installs the passed in tracing context as a dynamic scoped + global variable. + + Calls to TracingContext.get() while not under a `with tracing()` context + will return None. + """ + old_context = getattr(_TLS, "tracing_context", None) + _TLS.tracing_context = context + try: + yield context + except Exception as e: + if not hasattr(e, "real_stack") and context is not None: + e.real_stack = context.extract_stack() # type: ignore[attr-defined] + raise + finally: + if ( + context is not None + and context.fake_mode is not None + and context.fake_mode.shape_env is not None + ): + context.fake_mode.shape_env.cleanup() + _TLS.tracing_context = old_context + + +@overload +def dataclass_with_cached_hash(cls: type[T], **kwargs: Any) -> type[T]: ... + + +@overload +def dataclass_with_cached_hash( + cls: None = None, **kwargs: Any +) -> Callable[[type[T]], type[T]]: ... + + +@dataclass_transform() +def dataclass_with_cached_hash( + cls: type[T] | None = None, **kwargs: Any +) -> type[T] | Callable[[type[T]], type[T]]: + def wrap(cls_inner: type[T]) -> type[T]: + new_cls = dataclasses.dataclass(cls_inner, **kwargs) + old_hash = cls_inner.__hash__ + + def __hash__(self) -> int: + if not hasattr(self, "_hash"): + object.__setattr__(self, "_hash", old_hash(self)) + return self._hash + + def __reduce__(self): + # Exclude _hash from pickling to ensure deterministic cache keys. + # The _hash is a cached value that can be nondeterministically computed + # (e.g., based on id() of objects), so it should not affect pickling. + fields = dataclasses.fields(self) + field_values = tuple(getattr(self, f.name) for f in fields) + return (self.__class__, field_values) + + new_cls.__hash__ = __hash__ + new_cls.__reduce__ = __reduce__ + return new_cls # type: ignore[return-value] + + if cls is None: + return wrap + + return wrap(cls) + + +# Subclasses can be found in torch/_dynamo/source.py +# TODO(voz): Consider a toplevel torch/_source.py +@dataclass_with_cached_hash(frozen=True) +class Source: + def is_dict_key(self) -> bool: + return False + + def is_ephemeral(self) -> bool: + return False + + def reconstruct(self, codegen: PyCodegen) -> None: + raise NotImplementedError + + @functools.cached_property + def guard_source(self) -> GuardSource: + raise NotImplementedError + + @property + def _name_template(self) -> str: + """ + A template for the name of the source. Used to prevent code duplication between + `name` and `get_value`. + + For non-ChainedSources, `name` and `get_value` use the returned string directly. + + For ChainedSources, `name` and `get_value` expect the return to be a format string + with `{0}` present - `name` and `get_value` will apply different values to this function's + returned format string. + """ + raise NotImplementedError + + @functools.cached_property + def name(self) -> str: + return self._name_template + + def get_value( + self, + globals: dict[str, Any], + locals: dict[str, Any], + cache: weakref.WeakKeyDictionary[Source, Any], + ) -> Any: + if self in cache: + return cache[self] + value = eval(self._name_template, globals, locals) + cache[self] = value + return value + + def make_guard(self, fn: Callable[..., Any]) -> Guard: + if self.guard_source is GuardSource.CONSTANT: + raise NotImplementedError + return Guard(self, fn) + + def is_specialized_nn_module(self) -> bool: + return self.guard_source.is_specialized_nn_module() + + def subguards_allowed(self) -> bool: + """True if you can guard on attributes of this""" + return self.guard_source != GuardSource.SYNTHETIC_LOCAL + + +# Subclasses can be found in torch/_dynamo/source.py +@dataclass_with_cached_hash(frozen=True) +class ChainedSource(Source): + base: Source + + def is_dict_key(self) -> bool: + # Recurse until you either hit a ConstDictKey or a Source + return self.base.is_dict_key() + + def is_ephemeral(self) -> bool: + return self.base.is_ephemeral() + + @functools.cached_property + def guard_source(self) -> GuardSource: + return self.base.guard_source + + def get_base(self) -> Source: + current: Source = self + while isinstance(current, ChainedSource): + current = current.base + return current + + @functools.cached_property + def name(self) -> str: + return self._name_template.format(self.base.name) + + def get_value( + self, + globals: dict[str, Any], + locals: dict[str, Any], + cache: weakref.WeakKeyDictionary[Source, Any], + ) -> Any: + if self in cache: + return cache[self] + tmpvar = "tmp" + counter = 0 + while tmpvar in locals: + tmpvar = f"tmp{counter}" + counter += 1 + locals[tmpvar] = self.base.get_value(globals, locals, cache) + value = eval(self._name_template.format(tmpvar), globals, locals) + del locals[tmpvar] + cache[self] = value + return value + + +def detect_fake_mode(inputs: Any = None) -> FakeTensorMode | None: + """ + Attempts to "detect" what the current fake mode is. If there is one ambiently + available from TracingContext, we preferentially use that. Otherwise, we + heuristically detect the fake mode via the following sources, in order of + priority: + + - Currently active fake mode on stack + - Fake mode associated with passed in tensors (inputs does not + have to be flattened) + """ + from torch._subclasses.fake_tensor import ( + FakeTensor, + FakeTensorMode, + get_plain_tensors, + ) + + fake_modes = [] + + if context := TracingContext.try_get(): + fake_mode = context.fake_mode + if fake_mode is not None: + fake_modes.append((fake_mode, "tracing context", 0)) + + from torch.utils._python_dispatch import _get_current_dispatch_mode_stack + + for i, m in enumerate(reversed(_get_current_dispatch_mode_stack())): + if isinstance(m, FakeTensorMode): + # pyrefly: ignore [bad-argument-type] + fake_modes.append((m, "active fake mode", i)) + + flat_inputs = pytree.tree_leaves(inputs) + for i, flat_input in enumerate(flat_inputs): + if isinstance(flat_input, FakeTensor): + # pyrefly: ignore [bad-argument-type] + fake_modes.append((flat_input.fake_mode, "fake tensor input", i)) + if is_traceable_wrapper_subclass(flat_input): + out: list[torch.Tensor | int | torch.SymInt] = [] + get_plain_tensors(flat_input, out=out) # type: ignore[arg-type] + fake_tensors: list[FakeTensor] = [ + x for x in out if isinstance(x, FakeTensor) + ] + fake_modes.extend( + # pyrefly: ignore [bad-argument-type] + [ + (tensor.fake_mode, f"subclass input {i}", ix) + for ix, tensor in enumerate(fake_tensors) + ] + ) + + if fake_modes: + fake_mode, desc1, i1 = fake_modes[0] + for m, desc2, i2 in fake_modes[1:]: + assert fake_mode is m, ( + f"fake mode ({fake_mode}) from {desc1} {i1} doesn't match mode ({m}) from {desc2} {i2}\n\n" + # pyrefly: ignore [missing-attribute] + f"fake mode from {desc1} {i1} allocated at:\n{fake_mode.stack}\n" + # pyrefly: ignore [missing-attribute] + f"fake mode from {desc2} {i2} allocated at:\n{m.stack}" + ) + # pyrefly: ignore [bad-return] + return fake_mode + else: + return None + + +def active_fake_mode() -> FakeTensorMode | None: + """ + Inspects the dispatch mode stack for an active fake mode and returns it. + Returns None if no fake mode is active. + """ + from torch._subclasses.fake_tensor import FakeTensorMode + from torch.utils._python_dispatch import _get_current_dispatch_mode_stack + + for _, m in enumerate(reversed(_get_current_dispatch_mode_stack())): + if isinstance(m, FakeTensorMode): + return m + + return None diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_jit_internal.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_jit_internal.py new file mode 100644 index 0000000000000000000000000000000000000000..27c5768477dabfea81dab7bb95b3f7de1e68cad7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_jit_internal.py @@ -0,0 +1,1550 @@ +# mypy: allow-untyped-defs +""" +The weak_script annotation needs to be here instead of inside torch/jit/ so it +can be used in other places in torch/ (namely torch.nn) without running into +circular dependency problems +""" + +import ast +import builtins +import collections +import contextlib +import enum +import inspect +import io +import pickle +import sys +import textwrap +import threading +import types +import typing +import warnings +import weakref +from typing import ( # noqa: UP035, F401 # (Dict, List, Tuple) imported by torch.jit.annotations + Any, + Callable, + Dict, + Final, + ForwardRef, + get_args, + get_origin, + List, + Optional, + Tuple, + TypeVar, + Union, +) +from typing_extensions import ParamSpec + +import torch + +# This is needed. `torch._jit_internal` is imported before `torch.distributed.__init__`. +# Explicitly ask to import `torch.distributed.__init__` first. +# Otherwise, "AttributeError: module 'torch' has no attribute 'distributed'" is raised. +import torch.distributed.rpc +import torch.package._mangling as package_mangling +from torch._awaits import _Await +from torch._C import _Await as CAwait, Future as CFuture +from torch._sources import fake_range, get_source_lines_and_file, parse_def +from torch.futures import Future + + +_P = ParamSpec("_P") +_R = TypeVar("_R") + +BuiltinUnionType: type | tuple[type, ...] = types.UnionType + +LockType: type +try: + import _thread + + LockType = _thread.LockType +except ImportError: + import _dummy_thread # type: ignore[import-not-found] + + LockType = _dummy_thread.LockType + +# Wrapper functions that can call either of 2 functions depending on a boolean +# argument +boolean_dispatched: "weakref.WeakKeyDictionary[Callable, dict[str, Callable]]" = ( + weakref.WeakKeyDictionary() +) # noqa: T484 + + +FAKE_FILENAME_PREFIX = "__torch_jit_dataclass" + + +def is_final(ann) -> bool: + return ( + hasattr(ann, "__module__") + and ann.__module__ in {"typing", "typing_extensions"} + and (get_origin(ann) is Final or isinstance(ann, type(Final))) + ) + + +# allows BroadcastingList instance to be subscriptable +class BroadcastingListCls: + def __getitem__(self, types): + return + + +# mypy doesn't support parameters on types, so we have to explicitly type each +# list size +BroadcastingList1 = BroadcastingListCls() +for i in range(2, 7): + globals()[f"BroadcastingList{i}"] = BroadcastingList1 + + +def is_scripting() -> bool: + r""" + Function that returns True when in compilation and False otherwise. This + is useful especially with the @unused decorator to leave code in your + model that is not yet TorchScript compatible. + .. testcode:: + + import torch + + @torch.jit.unused + def unsupported_linear_op(x): + return x + + def linear(x): + if torch.jit.is_scripting(): + return torch.linear(x) + else: + return unsupported_linear_op(x) + """ + return False + + +# Retrieves a fully-qualified name (module hierarchy + classname) for a given obj. +def _qualified_name(obj, mangle_name=True) -> str: + # This special case allows us to override the qualified name on a type. + # It's currently used in conjunction with tracing, where we create a + # fake module to filter only supported attributes. However, since this + # new type is defined as a local class, we need a mechanism to override + # its qualname so it appears correctly in the TorchScript system. This, + # we set '_jit_override_qualname' with the original traced module's + # qualified name, which is picked up here + if hasattr(obj, "_jit_override_qualname"): + return obj._jit_override_qualname + # short-circuit in cases where the object already has a known qualified name + if isinstance(obj, torch._C.ScriptFunction): + return obj.qualified_name + + if getattr(obj, "__name__", None): + name = obj.__name__ + # Enum classes do not have `__name__` attr, instead they have `name`. + elif isinstance(obj, enum.Enum): + name = obj.name + else: + raise RuntimeError("Could not get name of python class object") + + if name == "": + name = "_lambda" # make name a valid identifier + + module_name = obj.__module__ + + # If the module is actually a torchbind module, then we should short circuit + if module_name == "torch._classes": + return obj.qualified_name # pyrefly: ignore [missing-attribute] + + # The Python docs are very clear that `__module__` can be None, but I can't + # figure out when it actually would be. + if module_name is None: + raise RuntimeError( + f"Could not get qualified name for class '{name}': " + "__module__ can't be None." + ) + + # if getattr(sys.modules[module_name], name) is not obj: + # raise RuntimeError(f"Could not get qualified name for class '{name}': " + # f"the attr {name} on module {module_name} is not the class") + + # torch.package and TorchScript have separate mangling schemes to avoid + # name collisions from multiple packages. To avoid them interfering with + # each other, normalize the package managing here. + if package_mangling.is_mangled(module_name): + module_name = module_name.replace("<", "_") + module_name = module_name.replace(">", "_") + + # The PythonExceptionValue C++ class in torch/csrc/jit/python/python_sugared_value.h + # does not need mangle the python class name. + if mangle_name: + # __main__ is a builtin module, so rewrite it to "__torch__". + if module_name == "__main__": + module_name = "__torch__" + else: + # Everything else gets a "__torch__" prefix to avoid name collisions + # with the names of user values. + module_name = "__torch__." + module_name + + if "." in name: + raise RuntimeError( + f"Could not get qualified name for class '{name}': " + f"'{name}' is not a valid identifier" + ) + + return module_name + "." + name + + +class SourceLoader: + def __init__(self): + self.content = {} + + def cache(self, fn, source): + self.content[fn] = source + + def get_source(self, fn): + return self.content.get(fn) + + +loader = SourceLoader() + + +def createResolutionCallbackFromEnv(lookup_base): + """ + Creates a resolution callback that will look up qualified names in an + environment, starting with `lookup_base` for the base of any qualified + names, then proceeding down the lookup chain with the resolved object. + + You should not use this directly, it should only be used from the other + createResolutionCallbackFrom* functions. + """ + + def lookupInModule(qualified_name, module): + if "." in qualified_name: + base, remaining_pieces = qualified_name.split(".", maxsplit=1) + module_value = getattr(module, base) + return lookupInModule(remaining_pieces, module_value) + else: + return getattr(module, qualified_name) + + def parseNestedExpr(expr, module) -> tuple[Any, int]: + i = 0 + while i < len(expr) and expr[i] not in (",", "[", "]"): + i += 1 + + # Special case logic for the empty Tuple as a subscript (used + # in the type annotation `Tuple[()]`) + if expr[:i] == "()": + return (), i + + base = lookupInModule(expr[:i].strip(), module) + assert base is not None, f"Unresolvable type {expr[:i]}" + if i == len(expr) or expr[i] != "[": + return base, i + + assert expr[i] == "[" + parts = [] + while expr[i] != "]": + part_len = 0 + i += 1 + part, part_len = parseNestedExpr(expr[i:], module) + parts.append(part) + i += part_len + if len(parts) > 1: + return base[tuple(parts)], i + 1 + else: + return base[parts[0]], i + 1 + + def parseExpr(expr, module): + try: + value, len_parsed = parseNestedExpr(expr, module) + assert len_parsed == len(expr), ( + "whole expression was not parsed, falling back to c++ parser" + ) + return value + except Exception: + """ + The python resolver fails in several cases in known unit tests, and is intended + to fall back gracefully to the c++ resolver in general. For example, python 2 style + annotations which are frequent in our unit tests often fail with types e.g. int not + resolvable from the calling frame. + """ + return None + + return lambda expr: parseExpr(expr, lookup_base) + + +def createResolutionCallbackFromFrame(frames_up: int = 0): + """ + Creates a function which, given a string variable name, + returns the value of the variable in the scope of the caller of + the function which called createResolutionCallbackFromFrame (by default). + + This is used to enable access in-scope Python variables inside + TorchScript fragments. + + frames_up is number of additional frames to go up on the stack. + The default value is 0, which correspond to the frame of the caller + of createResolutionCallbackFromFrame. Also for example, if frames_up is set + to 1, then the frame of the caller's caller of createResolutionCallbackFromFrame + will be taken. + + For example, the following program prints 2:: + + def bar(): + cb = createResolutionCallbackFromFrame(1) + print(cb("foo")) + + + def baz(): + foo = 2 + bar() + + + baz() + """ + frame = inspect.currentframe() + i = 0 + while i < frames_up + 1: + assert frame is not None + frame = frame.f_back + i += 1 + + assert frame is not None + f_locals = frame.f_locals + f_globals = frame.f_globals + + class env: + def __getattr__(self, key): + if key in f_locals: + return f_locals[key] + elif key in f_globals: + return f_globals[key] + elif key in dir(builtins): + return getattr(builtins, key) + + return createResolutionCallbackFromEnv(env()) + + +def get_closure(fn): + """ + Get a dictionary of closed over variables from a function + """ + captures = {} + captures.update(fn.__globals__) + + for index, captured_name in enumerate(fn.__code__.co_freevars): + captures[captured_name] = fn.__closure__[index].cell_contents + + return captures + + +# [local resolution in python] +# Depending on where a variable is defined, and where it is used, we may +# or may not be able to recover its value when recursively compiling a +# script function. Remember in the general case, a module or function is +# first defined and then later scripted. This means we do not have a +# chance to capture the active frames when the function is defined. Hence any +# name resolution has to happen later on the created closure. The way +# python captures type annotations restricts what we can recover. The +# follow example illustrates the different cases: +# +# class MyGlobalClass: +# ... +# def my_local_scope(): +# @torch.jit.script +# class MyClass: +# ... +# @torch.jit.script +# class MyClassUsedAsVar: +# ... +# def eg(x: MyClass, y: MyGlobalClass): +# a_local_capture : Foo +# return MyClassUsedAsVar(x) +# +# MyGlobalClass is defined in the __globals__ dictionary of function +# 'eg', so it is always recoverable. my_local_scope introduces a new local +# variable scope in the function. Classes defined here are only visible as +# local variables. For the case of MyClassUsedAsVar, it is captured +# because it is used as a variable inside the body of the function, and we +# can resolve it using the captures returned from `get_closure`. However, +# the type annotations are not captured by the closure. In Python +# 3.0--3.9, the _value_ of MyClass and MyGlobalClass will be available as +# annotations on `eg``, but starting in Python 4.0, they will represented as +# strings and no longer present. Furthermore, since the body of `eg` does +# not reference those names, they do not appear in the list of closed over +# variables. In Python 2.x, type annotations are in comments, leading to a +# similar situation where their definitions are not available. We anticipate +# that most users will not run into this issue because their modules and +# functions will be defined at a global scope like MyGlobalClass. In cases +# where they are not, it is possible to work around issues by declaring the +# values global in the function. +# In Python 3.9 declaring class as global will make it invisible to +# `inspect.getsource`, see https://bugs.python.org/issue42666 . +# This could be worked around by manually adding it to `global()` dictionary. + + +def createResolutionCallbackFromClosure(fn): + """ + Create a resolutionCallback by introspecting the function instead of + looking up the stack for the enclosing scope + """ + closure = get_closure(fn) + + class closure_lookup: + # This is a class since `closure` is a dict and it's easier in + # `env_helper` if everything just works with `getattr` calls + def __getattr__(self, key): + if key in closure: + return closure[key] + elif hasattr(typing, key): + return getattr(typing, key) + elif hasattr(builtins, key): + return getattr(builtins, key) + return None + + return createResolutionCallbackFromEnv(closure_lookup()) + + +def can_compile_class(cls) -> bool: + # If any of the functions on a type don't have a code object, this type can't + # be compiled and is probably a builtin / bound from C + if is_ignored_fn(cls): + return False + + # Ignore the following list of built-in classes. + ignored_builtin_classes = (torch.nn.Module, tuple, list, Exception) + if issubclass(cls, ignored_builtin_classes): + return False + + names = cls.__dict__ + fns = [ + getattr(cls, name) + for name in names + if inspect.isroutine(getattr(cls, name, None)) + ] + has_code = [hasattr(fn, "__code__") for fn in fns] + return all(has_code) + + +def get_callable_argument_names(fn) -> list[str]: + """ + Gets names of all POSITIONAL_OR_KEYWORD arguments for callable `fn`. + Returns an empty list when other types of arguments are present. + + This is used by `torch.jit.trace` to assign meaningful argument names to + traced functions and modules. + + Args: + fn: A callable. + Returns: + Argument names: List[str] + """ + # inspect.signature may fail, give up in that case. + try: + callable_signature = inspect.signature(fn) + except Exception: + return [] + + argument_names = [] + for name, param in callable_signature.parameters.items(): + # All four other types of arguments do not map to individual values + # with a keyword as name. + if param.kind != param.POSITIONAL_OR_KEYWORD: + continue + + argument_names.append(name) + + return argument_names + + +def get_annotation_str(annotation): + """ + Convert an AST node containing a type annotation to the string present in the source + that represents the same annotation. + """ + if isinstance(annotation, ast.Name): + return annotation.id + elif isinstance(annotation, ast.Attribute): + return ".".join([get_annotation_str(annotation.value), annotation.attr]) + elif isinstance(annotation, ast.Subscript): + # In Python3.9+ subscript indices are not wrapped in ast.Index + subscript_slice = annotation.slice + return f"{get_annotation_str(annotation.value)}[{get_annotation_str(subscript_slice)}]" + elif isinstance(annotation, ast.Tuple): + return ",".join([get_annotation_str(elt) for elt in annotation.elts]) + elif isinstance(annotation, ast.Constant): + return f"{annotation.value}" + + # If an AST node is not handled here, it's probably handled in ScriptTypeParser. + return None + + +def get_type_hint_captures(fn): + """ + Get a dictionary containing type resolution mappings necessary to resolve types + for the literal annotations on 'fn'. These are not considered to be closed-over by fn + and must be obtained separately (e.g. using this function). + + Args: + fn: A callable. + Returns: + A Dict[str, Any] containing a mapping from the literal annotations used on + fn to the Python objects they refer to. + """ + # First, try to get the source of the function. We'll need to parse it to find the actual string names + # that were used to annotate the types, since inspect.signature() will only return the class object that + # the annotation refers to, not the string name. If we can't get the source, simply return an empty dict. + # This may happen in cases where the function is synthesized dynamically at runtime. + src = loader.get_source(fn) + if src is None: + try: + src = inspect.getsource(fn) + except OSError as e: + raise OSError( + f"Failed to get source for {fn} using inspect.getsource" + ) from e + + # Gather a dictionary of parameter name -> type, skipping any parameters whose annotated + # types are strings. These are only understood by TorchScript in the context of a type annotation + # that refers to a class in its own definition, but trying to include a mapping for this in the result + # function would cause infinite recursion because the class is currently being compiled. + # In addition, there is logic in ScriptTypeParser to handle this. + signature = inspect.signature(fn) + name_to_type = { + name: parameter.annotation + for name, parameter in signature.parameters.items() + if parameter.annotation is not inspect.Parameter.empty + and not isinstance(parameter.annotation, str) + } + + # Then, get the literal type annotations from the function declaration + # by source inspection. This accounts for the case in which aliases are used + # to annotate the arguments (e.g device_t = torch.device, and then d: device_t). + # frontend.py cannot be used here because it includes _jit_internal, so use ast instead. + a = ast.parse(textwrap.dedent(src)) + if len(a.body) != 1 or not isinstance(a.body[0], ast.FunctionDef): + raise RuntimeError(f"Expected {fn} to be a function") + f = a.body[0] + + # Prepare a dictionary of source annotation -> type, which will be the final result of this function, + # by using the parsed AST (f) to reconstruct source annotations as strings for each parameter and mapping + # them to the type object corresponding to the annotation via name_to_type using the parameter name. + annotation_to_type = {} + + for arg in f.args.args: + # Get the source type annotation string for this argument if possible. + arg_annotation_str = ( + get_annotation_str(arg.annotation) if arg.annotation else None + ) + + # If the argument has no annotation or get_annotation_str cannot convert it to a string, + # arg_annotation_str will be None. Skip this arg; ScriptTypeParser will probably handle + # this in the latter case. + if arg_annotation_str is None: + continue + + # Insert {arg_annotation_str: type} into annotation_to_type if possible. One reason arg_name may not + # be present in name_to_type is that the annotation itself is a string and not a type object + # (common for self-refential annotations in classes). Once again, let ScriptTypeParser handle this. + arg_name = arg.arg + if arg_name in name_to_type: + annotation_to_type[arg_annotation_str] = name_to_type[arg_name] + + # If there is a valid return annotation, include it in annotation_to_type. As with argument annotations, + # the literal annotation has to be convertible to a string by get_annotation_str, and the actual type + # of the annotation cannot be a string. + literal_return_annotation = get_annotation_str(f.returns) + valid_literal_annotation = literal_return_annotation is not None + return_annotation = signature.return_annotation + valid_return_annotation_type = ( + return_annotation is not inspect.Parameter.empty + and not isinstance(return_annotation, str) + ) + if valid_literal_annotation and valid_return_annotation_type: + annotation_to_type[literal_return_annotation] = return_annotation + + return annotation_to_type + + +def createResolutionCallbackForClassMethods(cls): + """ + This looks at all the methods defined in a class and pulls their closed-over + variables into a dictionary and uses that to resolve variables. + """ + # cls is a type here, so `ismethod` is false since the methods on the type + # aren't bound to anything, so Python treats them as regular functions + fns = [ + getattr(cls, name) + for name in cls.__dict__ + if inspect.isroutine(getattr(cls, name)) + ] + # Skip built-ins, as they do not have global scope nor type hints + # Needed to support `enum.Enum` derived classes in Python-3.11 + # That adds `_new_member_` property which is an alias to `__new__` + fns = [fn for fn in fns if not inspect.isbuiltin(fn) and hasattr(fn, "__globals__")] + captures = {} + + for fn in fns: + captures.update(get_closure(fn)) + captures.update(get_type_hint_captures(fn)) + + def lookup_in_class(key): + if key in captures: + return captures[key] + else: + return getattr(builtins, key, None) + + return lookup_in_class + + +def boolean_dispatch( + arg_name, + arg_index, + default, + if_true, + if_false, + module_name, + func_name, +): + """ + Dispatches to either of 2 script functions based on a boolean argument. + In TorchScript, the boolean argument must be constant so that the correct + function to use can be determined at compile time. + """ + + def fn(*args, **kwargs): + dispatch_flag = default + if arg_name in kwargs: + dispatch_flag = kwargs[arg_name] + elif arg_index < len(args): + dispatch_flag = args[arg_index] + + if dispatch_flag: + return if_true(*args, **kwargs) + else: + return if_false(*args, **kwargs) + + if if_true.__doc__ is None and if_false.__doc__ is not None: + doc = if_false.__doc__ + if_true.__doc__ = doc + elif if_false.__doc__ is None and if_true.__doc__ is not None: + doc = if_true.__doc__ + if_false.__doc__ = doc + elif if_false.__doc__ is None and if_true.__doc__ is None: + # neither function has a docstring + doc = None + else: + raise RuntimeError("only one function can have a docstring") + fn.__doc__ = doc + + if module_name is not None: + fn.__module__ = module_name + if func_name is not None: + fn.__name__ = func_name + + boolean_dispatched[fn] = { + "if_true": if_true, + "if_false": if_false, + "index": arg_index, + "default": default, + "arg_name": arg_name, + } + return fn + + +class FunctionModifiers: + """ + Used to denote the behavior of a function in TorchScript. See export() and + ignore() for details. + """ + + UNUSED = "unused (ignored and replaced with raising of an exception)" + IGNORE = "ignore (leave as a call to Python, cannot be torch.jit.save'd)" + EXPORT = "export (compile this function even if nothing calls it)" + DEFAULT = "default (compile if called from a exported function / forward)" + COPY_TO_SCRIPT_WRAPPER = ( + "if this method is not scripted, copy the python method onto the scripted model" + ) + _DROP = "_drop (function is fully ignored, declaration can be unscriptable)" + + +def export(fn: Callable[_P, _R]) -> Callable[_P, _R]: + """ + This decorator indicates that a method on an ``nn.Module`` is used as an entry point into a + :class:`ScriptModule` and should be compiled. + + ``forward`` implicitly is assumed to be an entry point, so it does not need this decorator. + Functions and methods called from ``forward`` are compiled as they are seen + by the compiler, so they do not need this decorator either. + + Example (using ``@torch.jit.export`` on a method): + + .. testcode:: + + import torch + import torch.nn as nn + + class MyModule(nn.Module): + def implicitly_compiled_method(self, x): + return x + 99 + + # `forward` is implicitly decorated with `@torch.jit.export`, + # so adding it here would have no effect + def forward(self, x): + return x + 10 + + @torch.jit.export + def another_forward(self, x): + # When the compiler sees this call, it will compile + # `implicitly_compiled_method` + return self.implicitly_compiled_method(x) + + def unused_method(self, x): + return x - 20 + + # `m` will contain compiled methods: + # `forward` + # `another_forward` + # `implicitly_compiled_method` + # `unused_method` will not be compiled since it was not called from + # any compiled methods and wasn't decorated with `@torch.jit.export` + m = torch.jit.script(MyModule()) + """ + fn._torchscript_modifier = FunctionModifiers.EXPORT # type:ignore[attr-defined] + return fn + + +def unused(fn: Callable[_P, _R]) -> Callable[_P, _R]: + """ + This decorator indicates to the compiler that a function or method should + be ignored and replaced with the raising of an exception. This allows you + to leave code in your model that is not yet TorchScript compatible and still + export your model. + + Example (using ``@torch.jit.unused`` on a method):: + + import torch + import torch.nn as nn + + + class MyModule(nn.Module): + def __init__(self, use_memory_efficient): + super().__init__() + self.use_memory_efficient = use_memory_efficient + + @torch.jit.unused + def memory_efficient(self, x): + import pdb + + pdb.set_trace() + return x + 10 + + def forward(self, x): + # Use not-yet-scriptable memory efficient mode + if self.use_memory_efficient: + return self.memory_efficient(x) + else: + return x + 10 + + + m = torch.jit.script(MyModule(use_memory_efficient=False)) + m.save("m.pt") + + m = torch.jit.script(MyModule(use_memory_efficient=True)) + # exception raised + m(torch.rand(100)) + """ + if isinstance(fn, property): + prop = fn + setattr( # noqa: B010 + prop.fget, "_torchscript_modifier", FunctionModifiers.UNUSED + ) + + if prop.fset: + setattr( # noqa: B010 + prop.fset, "_torchscript_modifier", FunctionModifiers.UNUSED + ) + + return prop # pyrefly: ignore [bad-return] + + fn._torchscript_modifier = FunctionModifiers.UNUSED # type: ignore[attr-defined] + return fn + + +# No op context manager from python side +class _IgnoreContextManager(contextlib.AbstractContextManager): + def __init__(self, **kwargs): + pass + + def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None: + pass + + +def ignore(drop=False, **kwargs): + """ + This decorator indicates to the compiler that a function or method should + be ignored and left as a Python function. This allows you to leave code in + your model that is not yet TorchScript compatible. If called from TorchScript, + ignored functions will dispatch the call to the Python interpreter. Models with ignored + functions cannot be exported; use :func:`@torch.jit.unused ` instead. + + Example (using ``@torch.jit.ignore`` on a method):: + + import torch + import torch.nn as nn + + + class MyModule(nn.Module): + @torch.jit.ignore + def debugger(self, x): + import pdb + + pdb.set_trace() + + def forward(self, x): + x += 10 + # The compiler would normally try to compile `debugger`, + # but since it is `@ignore`d, it will be left as a call + # to Python + self.debugger(x) + return x + + + m = torch.jit.script(MyModule()) + + # Error! The call `debugger` cannot be saved since it calls into Python + m.save("m.pt") + + Example (using ``@torch.jit.ignore(drop=True)`` on a method): + + .. testcode:: + + import torch + import torch.nn as nn + + class MyModule(nn.Module): + @torch.jit.ignore(drop=True) + def training_method(self, x): + import pdb + pdb.set_trace() + + def forward(self, x): + if self.training: + self.training_method(x) + return x + + m = torch.jit.script(MyModule()) + + # This is OK since `training_method` is not saved, the call is replaced + # with a `raise`. + m.save("m.pt") + + .. testcleanup:: + + import os + os.remove('m.pt') + """ + + if callable(drop): + # used without any args, so drop is actually a function + # @torch.jit.ignore + # def fn(...): + fn = drop + # pyrefly: ignore [missing-attribute] + fn._torchscript_modifier = FunctionModifiers.IGNORE + return fn + + if not isinstance(drop, bool): + raise RuntimeError( + f"Argument to @torch.jit.ignore must be a bool or a function but got {drop}" + ) + + # for backwards compat + drop_on_export = kwargs.pop("drop_on_export", None) + if drop_on_export: + warnings.warn( + "ignore(drop_on_export=True) has been deprecated. TorchScript will now drop the function " + "call on compilation. Use torch.jit.unused now. {}", + stacklevel=2, + category=FutureWarning, + ) + + drop = drop_on_export + elif drop: + warnings.warn( + "ignore(True) has been deprecated. TorchScript will now drop the function " + "call on compilation. Use torch.jit.unused now. {}", + stacklevel=2, + category=FutureWarning, + ) + + def decorator(fn): + if drop: + fn._torchscript_modifier = FunctionModifiers.UNUSED + else: + fn._torchscript_modifier = FunctionModifiers.IGNORE + return fn + + return decorator + + +def _drop(fn: Callable[_P, _R]) -> Callable[_P, _R]: + fn._torchscript_modifier = FunctionModifiers._DROP # type: ignore[attr-defined] + return fn + + +def _copy_to_script_wrapper(fn: Callable[_P, _R]) -> Callable[_P, _R]: + fn._torchscript_modifier = FunctionModifiers.COPY_TO_SCRIPT_WRAPPER # type: ignore[attr-defined] + return fn + + +def module_has_exports(mod): + for name in dir(mod): + if hasattr(mod, name): + item = getattr(mod, name) + if callable(item): + if get_torchscript_modifier(item) is FunctionModifiers.EXPORT: + return True + return False + + +# WARNING: should_drop is currently being used by our JIT code coverage plug-in to mark JIT'd code as covered. If you +# rename this function, please update references in tools/coverage_plugins_package/src/coverage_plugins/jit_plugin.py to +# allow JIT'd code to still be covered. +def should_drop(fn) -> bool: + attr = get_torchscript_modifier(fn) + if attr is None: + return False + return attr is FunctionModifiers.UNUSED or attr is FunctionModifiers._DROP + + +def is_ignored_fn(fn) -> bool: + mod = get_torchscript_modifier(fn) + return ( + mod is FunctionModifiers.UNUSED + or mod is FunctionModifiers.IGNORE + or mod is FunctionModifiers._DROP + ) + + +def _is_drop_fn(fn) -> bool: + mod = get_torchscript_modifier(fn) + return mod is FunctionModifiers._DROP + + +def is_static_fn(cls, fn) -> bool: + return isinstance(inspect.getattr_static(cls, fn, default=None), staticmethod) + + +def get_static_fn(cls, fn): + return inspect.getattr_static(cls, fn).__func__ + + +def get_torchscript_modifier(fn): + if not callable(fn): + return None + if hasattr(fn, "__func__"): + fn = fn.__func__ + return getattr(fn, "_torchscript_modifier", FunctionModifiers.DEFAULT) + + +def copy_torchscript_modifier(orig, new) -> None: + attr = get_torchscript_modifier(orig) + if attr is None: + return + new._torchscript_modifier = attr + + +# overloading registration +# overloads get registered in this file, and compiled in torch/jit/__init__.py +# so that they can be imported in nn/functional.py without an import cycle + +# qualified_name => list[overload_functions] +_overloaded_fns: dict[str, list[Callable]] = {} # noqa: T484 + + +_OVERLOAD_EXAMPLE = """ +Example usage of overload function: +@torch.jit._overload +def my_function(x: type0) -> type0: # decl 1 + pass + +@torch.jit._overload +def my_function(x: type1) -> type1: # decl 2 + pass + +def my_function(x): # implementation + if isinstance(x, type0): + return x + elif isinstance(x, type1): + return x +""" + + +def get_overload_no_implementation_error_message(kind, obj): + sourcelines, file_lineno, filename = get_source_lines_and_file(obj) + return ( + f'Implementation for the {kind} "{_qualified_name(obj)}" is missing. Please make ' + f"sure a definition is provided and defined after all overload declarations.\n" + f'File "{filename}", line {file_lineno}:\n' + + "".join(sourcelines) + + "\n" + + _OVERLOAD_EXAMPLE + ) + + +def _check_overload_body(func): + try: + parsed_def = parse_def(func) + except OSError: + # Parsing the function definition can raise an OSError if source is unavailable. + # Since this is just an initial check, just raise a warning if this is the case. + warnings.warn( + f"Unable to retrieve source for @torch.jit._overload function: {func}.", + stacklevel=2, + ) + return + + body = parsed_def.ast.body[0].body + + def is_pass(x): + return isinstance(x, ast.Pass) + + def is_ellipsis(x): + return ( + isinstance(x, ast.Expr) + and isinstance(x.value, ast.Constant) + and x.value.value is Ellipsis + ) + + if len(body) != 1 or not (is_pass(body[0]) or is_ellipsis(body[0])): + msg = ( + "Only `pass` statement or `...` can be the body of overload declaration:\n" + ) + msg += "\n".join(parsed_def.source.split("\n")[:3]) + msg += " <- Expecting `pass` or `...` here!\n" + _OVERLOAD_EXAMPLE + raise RuntimeError(msg) + + +def _overload(func): + _check_overload_body(func) + qual_name = _qualified_name(func) + global _overloaded_fns + fn_overload_list = _overloaded_fns.get(qual_name) + if fn_overload_list is None: + fn_overload_list = [] + _overloaded_fns[qual_name] = fn_overload_list + fn_overload_list.append(func) + return func + + +def _get_fn_overloads(qual_name): + return _overloaded_fns.get(qual_name) + + +def _clear_fn_overloads(qual_name) -> None: + del _overloaded_fns[qual_name] + + +def get_class_name_lineno(method) -> tuple[str, int]: + current_frame = inspect.currentframe() + + # one for the get_class_name call, one for _overload_method call + for _ in range(2): + assert ( + current_frame is not None + ) # assert current frame is not an Optional[FrameType] + current_frame = current_frame.f_back + + assert current_frame is not None # same here + class_name = current_frame.f_code.co_name + line_no = current_frame.f_code.co_firstlineno + return class_name, line_no + + +# At the point the decorator is applied to class methods the method +# has no reference to its owning class. _qualified_name would not include +# the class it is defined in, so any methods with the same name in the same file +# would have the same _qualified_name, even if they were defined in different +# classes. This problem only exists in python 2. +# We get around this problem by looking at the stack frame and identifying +# the class name, and throwing an error whenever overloads are used +# when modules of the same name are in the same file + +# qualified_name => class name => list[overload_functions] +_overloaded_methods: dict[str, dict[str, list[Callable]]] = {} # noqa: T484 + + +# (qualified_name, class name) => class_fileno +_overloaded_method_class_fileno: dict[tuple[str, str], int] = {} + + +def _overload_method(func): + _check_overload_body(func) + qual_name = _qualified_name(func) + global _overloaded_methods + class_name_map = _overloaded_methods.get(qual_name) + if class_name_map is None: + class_name_map = {} + _overloaded_methods[qual_name] = class_name_map + + class_name, line_no = get_class_name_lineno(func) + method_overloads = class_name_map.get(class_name) + if method_overloads is None: + method_overloads = [] + class_name_map[class_name] = method_overloads + _overloaded_method_class_fileno[(qual_name, class_name)] = line_no + else: + existing_lineno = _overloaded_method_class_fileno[(qual_name, class_name)] + if existing_lineno != line_no: + raise RuntimeError( + "Cannot currently overload the same method name in two different" + " classes with the same name in the same module" + ) + + method_overloads.append(func) + return func + + +def _get_overloaded_methods(method, mod_class): + # TODO: __name__ not set for submodules in recursive script + if not hasattr(method, "__name__"): + return None + qual_name = _qualified_name(method) + class_name_map = _overloaded_methods.get(qual_name) + if class_name_map is None: + return None + overloads = class_name_map.get(mod_class.__name__, None) + if overloads is None: + return None + + method_line_no = get_source_lines_and_file(method)[1] + mod_class_fileno = get_source_lines_and_file(mod_class)[1] + mod_end_fileno = mod_class_fileno + len(get_source_lines_and_file(mod_class)[0]) + if not (method_line_no >= mod_class_fileno and method_line_no <= mod_end_fileno): + raise AssertionError( + "Overloads are not usable when a module is redeclared within the same file: " + + str(method) + ) + return overloads + + +def is_tuple(ann) -> bool: + # Check for typing.Tuple missing args (but `tuple` is fine) + if ann is typing.Tuple: # noqa: UP006 + raise_error_container_parameter_missing("Tuple") + + # For some reason Python 3.7 violates the Type[A, B].__origin__ == Type rule + if not hasattr(ann, "__module__"): + return False + + ann_origin = get_origin(ann) + return ann.__module__ in ("builtins", "typing") and ann_origin is tuple + + +def is_list(ann) -> bool: + # Check for typing.List missing args (but `list` is fine) + if ann is typing.List: # noqa: UP006 + raise_error_container_parameter_missing("List") + + if not hasattr(ann, "__module__"): + return False + + ann_origin = get_origin(ann) + return ann.__module__ in ("builtins", "typing") and ann_origin is list + + +def is_dict(ann) -> bool: + # Check for typing.Dict missing args (but `dict` is fine) + if ann is typing.Dict: # noqa: UP006 + raise_error_container_parameter_missing("Dict") + + if not hasattr(ann, "__module__"): + return False + + ann_origin = get_origin(ann) + return ann.__module__ in ("builtins", "typing") and ann_origin is dict + + +def is_union(ann): + if ann is Union: + raise_error_container_parameter_missing("Union") + + return isinstance(ann, BuiltinUnionType) or ( + hasattr(ann, "__module__") + and ann.__module__ == "typing" + and (get_origin(ann) is Union) + ) + + +def is_optional(ann): + if ann is Optional: + raise_error_container_parameter_missing("Optional") + + def is_optional_as_optional(ann): + return ( + hasattr(ann, "__module__") + and ann.__module__ == "typing" + and (get_origin(ann) is Optional) + ) + + def is_union_as_optional(ann): + ann_args = get_args(ann) + return len(ann_args) == 2 and (None in ann_args or type(None) in ann_args) + + return is_optional_as_optional(ann) or (is_union(ann) and is_union_as_optional(ann)) + + +def is_future(ann) -> bool: + if ann is Future: + raise RuntimeError( + "Attempted to use Future without a " + "contained type. Please add a contained type, e.g. " + "Future[int]" + ) + return get_origin(ann) is Future + + +def is_await(ann) -> bool: + if ann is _Await: + return True + return get_origin(ann) is _Await + + +if torch.distributed.rpc.is_available(): + from torch._C._distributed_rpc import PyRRef + from torch.distributed.rpc import RRef + + def is_rref(ann) -> bool: + if ann is RRef: + raise RuntimeError( + "Attempted to use RRef without a " + "contained type. Please add a contained type, e.g. " + "RRef[int]" + ) + return get_origin(ann) is RRef + + def is_rref_instance(obj) -> bool: + return isinstance(obj, PyRRef) + +else: + + def is_rref_instance(obj) -> bool: + # If the RPC module doesn't exist then RRefs don't exist either. + return False + + +def _try_get_dispatched_fn(fn): + if not callable(fn): + return None + return boolean_dispatched.get(fn) + + +def _get_named_tuple_properties( + obj, + loc: torch._C._jit_tree_views.SourceRange | None = None, + rcb=None, +): + if loc is None: + loc = fake_range() + + assert issubclass(obj, tuple) and hasattr(obj, "_fields") + if hasattr(obj, "_field_defaults"): + defaults = [ + obj._field_defaults[field] + for field in obj._fields + if field in obj._field_defaults + ] + else: + defaults = [] + + obj_annotations = inspect.get_annotations(obj) + if len(obj_annotations) == 0 and hasattr(obj, "__base__"): + obj_annotations = inspect.get_annotations( + # pyrefly: ignore [bad-argument-type] + obj.__base__ + ) + + annotations = [] + for field in obj._fields: + if field in obj_annotations: + field_type = obj_annotations[field] + # [Note: ForwardRef annotations in NamedTuple attributes] + # NamedTuple types are slightly different from normal types. + # + # Normally, annotations are evaluated like this (during jit.script): + # 1. Load strings of python code into c++ and parse. + # 2. Get annotations as strings + # 3. Use the PythonResolver's resolution callback (rcb) to convert + # the string into a python object + # 4. We call into annotations.py:ann_to_type to convert python obj + # from step 3 into a type that torchscript understands. + # + # NamedTuples are more complicated, because it has sub-types. + # Normally, once we have the NamedTuple type object from #3, + # we can just look at the annotation literal values and use + # ann_to_type directly on them. + # + # But sometimes, users will annotate with string literals, e.g. + # x: 'int' + # This also happens with PEP563 (from __forward__ import annotations) + # + # These annotations appear in the annotation dict as ForwardRef('int'). + # + # Then, we need to convert the string into a python object. This + # requires having local context for custom objects or imported types. + # rcb() is what gives us this. So, we plumb rcb through the stack so + # it can be used in this context for the if block below. + # + # FAQ: + # - Why do we need this special handling for NamedTuple but string + # annotations work fine for normal types? Normally, we parse the + # string directly and then call rcb() directly from C++. + # - Why not use ForwardRef._evaluate? For that, we need globals() + # and locals() for the local context where the NamedTuple was defined. + # rcb is what lets us look up into these. So, basically rcb does the + # hard work for us. + if isinstance(field_type, ForwardRef) and rcb is not None: + rcb_type = rcb(field_type.__forward_arg__) + # rcb returns None if it can't find anything. + if rcb_type is None: + raise ValueError( + f"Unknown type annotation: '{field_type}' in NamedTuple {obj.__name__}." + f" Likely due to partial support for ForwardRef parameters in NamedTuples, see #95858." + f" Issue occurred at {loc.highlight()}" + ) + field_type = rcb_type + the_type = torch.jit.annotations.ann_to_type(field_type, loc, rcb) + annotations.append(the_type) + else: + annotations.append(torch._C.TensorType.getInferred()) + return type(obj).__name__, obj._fields, annotations, defaults + + +def _create_named_tuple( + t, + unqual_name: str, + field_names: list[str], + defaults: tuple[Any, ...], +): + TupleType = collections.namedtuple(unqual_name, field_names, defaults=defaults) # type: ignore[call-arg, no-redef, misc] + return TupleType(*t) + + +@contextlib.contextmanager +def _disable_emit_hooks(): + hooks = torch._C._jit_get_emit_hooks() + torch._C._jit_set_emit_hooks(None, None) + try: + yield + finally: + torch._C._jit_set_emit_hooks(hooks[0], hooks[1]) + + +def _disable_emit_hooks_decorator(_DecoratorContextManager) -> None: # noqa: F811 + # noqa: F841 + def __enter__(self) -> None: + self.hooks = torch._C._jit_get_emit_hooks() + torch._C._jit_set_emit_hooks(None, None) + + def __exit__(self, *args) -> None: + torch._C._jit_set_emit_hooks(self.hooks[0], self.hooks[1]) + + +def _is_exception(obj) -> bool: + if not inspect.isclass(obj): + return False + return issubclass(obj, Exception) + + +def raise_error_container_parameter_missing(target_type) -> None: + if target_type.endswith("ict"): + raise RuntimeError( + f"Attempted to use {target_type} without " + "contained types. Please add contained type, e.g. " + f"{target_type}[int, int]" + ) + raise RuntimeError( + f"Attempted to use {target_type} without a " + "contained type. Please add a contained type, e.g. " + f"{target_type}[int]" + ) + + +_RAW_TYPE_NAME_MAPPING = { + dict: "dict", + list: "list", + tuple: "tuple", + typing.Dict: "Dict", # noqa: UP006 + typing.List: "List", # noqa: UP006 + typing.Optional: "Optional", + typing.Tuple: "Tuple", # noqa: UP006 +} + + +def check_args_exist(target_type) -> None: + if name := _RAW_TYPE_NAME_MAPPING.get(target_type): + raise_error_container_parameter_missing(name) + + +def check_empty_containers(obj) -> None: + if obj == [] or obj == {} or obj == (): + warnings.warn( + "The inner type of a container is lost when " + "calling torch.jit.isinstance in eager mode. For " + "example, List[int] would become list and " + "therefore falsely return True for List[float] or" + " List[str].", + stacklevel=2, + ) + + +# supports List/Dict/Tuple and Optional types +# TODO support future +def container_checker(obj, target_type) -> bool: + origin_type = get_origin(target_type) + check_args_exist(target_type) + if origin_type is None: + return False + elif origin_type is list or origin_type is typing.List: # noqa: UP006 + check_empty_containers(obj) + if not isinstance(obj, list): + return False + arg_type = get_args(target_type)[0] + arg_origin = get_origin(arg_type) + for el in obj: + # check if nested container, ex: List[List[str]] + if arg_origin: # processes nested container, ex: List[List[str]] + if not container_checker(el, arg_type): + return False + elif not isinstance(el, arg_type): + return False + return True + elif origin_type is typing.Dict or origin_type is dict: # noqa: UP006 + check_empty_containers(obj) + if not isinstance(obj, dict): + return False + key_type = get_args(target_type)[0] + val_type = get_args(target_type)[1] + for key, val in obj.items(): + # check if keys are of right type + if not isinstance(key, key_type): + return False + val_origin = get_origin(val_type) + if val_origin: + if not container_checker(val, val_type): + return False + elif not isinstance(val, val_type): + return False + return True + elif origin_type is typing.Tuple or origin_type is tuple: # noqa: UP006 + check_empty_containers(obj) + if not isinstance(obj, tuple): + return False + arg_types = get_args(target_type) + if len(obj) != len(arg_types): + return False + for el, el_type in zip(obj, arg_types): + el_origin = get_origin(el_type) + if el_origin: + if not container_checker(el, el_type): + return False + elif not isinstance(el, el_type): + return False + return True + elif origin_type is Union or issubclass( + # pyrefly: ignore [bad-argument-type] + origin_type, + BuiltinUnionType, + ): # also handles Optional + if obj is None: # check before recursion because None is always fine + return True + inner_types = get_args(target_type) + for t in inner_types: + t_origin = get_origin(t) + if t_origin: + return container_checker(obj, t) + elif isinstance(obj, t): + return True + return False + + +def _isinstance(obj, target_type) -> bool: + if isinstance(target_type, collections.abc.Container): + if not isinstance(target_type, tuple): + raise RuntimeError( + "The second argument to " + "`torch.jit.isinstance` must be a type " + "or a tuple of types" + ) + for t_type in target_type: + if _isinstance(obj, t_type): + return True + return False + + origin_type = get_origin(target_type) + if origin_type: + return container_checker(obj, target_type) + + # Check to handle non-typed optional origin returns as none instead + # of as optional in 3.7-3.8 + check_args_exist(target_type) + + # handle non-containers + return isinstance(obj, target_type) + + +class _TensorExtractor(pickle.Pickler): + def __init__(self, *args, tensors: list[torch.Tensor], **kwargs): + super().__init__(*args, **kwargs) + self.tensors = tensors + + def persistent_id(self, obj): + if isinstance(obj, torch.Tensor): + self.tensors.append(obj) + return "" + # Since we just want to extract tensors, we don't mind if an object is + # unpicklable if it doesn't contain tensors, as we can just ignore/skip + # it. To play it safe, we only do so for common objects that we're sure + # don't contain tensors. Feel free to add new types here. Note also that + # even if a type isn't listed here this won't block users, since they + # can just add a __getstate__ or __reduce__ method to their class. + if isinstance(obj, LockType): + return "" + # Futures and RRefs don't technically contain a value, they just offer + # the means to access a value. + if isinstance(obj, CFuture) or is_rref_instance(obj): + return "" + if isinstance(obj, CAwait): + return "" + if isinstance(obj, torch.cuda.Event): + return "" + if isinstance(obj, threading.Thread): + return "" + return None + + +def _extract_tensors(obj): + r""" + This function is exclusively called from C++. + See ``torch/csrc/jit/python/python_ivalue.h``. + + It extracts the tensors contained in the given object, through pickling. + """ + tensors: list[torch.Tensor] = [] + extractor = _TensorExtractor(io.BytesIO(), protocol=-1, tensors=tensors) + extractor.dump(obj) + return tensors + + +def _get_model_id(obj) -> str | None: + if isinstance(obj, torch.jit.ScriptModule): + return str(obj._c._type()) + elif isinstance(obj, torch.jit.ScriptFunction): + return obj.qualified_name + else: + return None + + +# In Python-3.11+ typed enums (i.e. IntEnum for example) retain number of base class methods in subclass +# that were previously dropped. To preserve the behavior, explicitly drop them there + +if sys.version_info >= (3, 11): + _drop(enum.Enum.__new__) + _drop(enum.Enum.__format__) + _drop(enum.Enum.__repr__) + _drop(enum.Enum.__str__) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_linalg_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_linalg_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..213393da9aa998cd393faea1acf362576b80a3d0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_linalg_utils.py @@ -0,0 +1,148 @@ +# mypy: allow-untyped-defs +"""Various linear algebra utility methods for internal use.""" + +import torch +from torch import Tensor + + +def is_sparse(A): + """Check if tensor A is a sparse COO tensor. All other sparse storage formats (CSR, CSC, etc...) will return False.""" + if isinstance(A, torch.Tensor): + return A.layout == torch.sparse_coo + + error_str = "expected Tensor" + if not torch.jit.is_scripting(): + error_str += f" but got {type(A)}" + raise TypeError(error_str) + + +def get_floating_dtype(A): + """Return the floating point dtype of tensor A. + + Integer types map to float32. + """ + dtype = A.dtype + if dtype in (torch.float16, torch.float32, torch.float64): + return dtype + return torch.float32 + + +def matmul(A: Tensor | None, B: Tensor) -> Tensor: + """Multiply two matrices. + + If A is None, return B. A can be sparse or dense. B is always + dense. + """ + if A is None: + return B + if is_sparse(A): + return torch.sparse.mm(A, B) + return torch.matmul(A, B) + + +def bform(X: Tensor, A: Tensor | None, Y: Tensor) -> Tensor: + """Return bilinear form of matrices: :math:`X^T A Y`.""" + return matmul(X.mT, matmul(A, Y)) + + +def qform(A: Tensor | None, S: Tensor): + """Return quadratic form :math:`S^T A S`.""" + return bform(S, A, S) + + +def basis(A): + """Return orthogonal basis of A columns.""" + return torch.linalg.qr(A).Q + + +def symeig(A: Tensor, largest: bool | None = False) -> tuple[Tensor, Tensor]: + """Return eigenpairs of A with specified ordering.""" + if largest is None: + largest = False + E, Z = torch.linalg.eigh(A, UPLO="U") + # assuming that E is ordered + if largest: + E = torch.flip(E, dims=(-1,)) + Z = torch.flip(Z, dims=(-1,)) + return E, Z + + +# These functions were deprecated and removed +# This nice error message can be removed in version 1.13+ +def matrix_rank(input, tol=None, symmetric=False, *, out=None) -> Tensor: + raise RuntimeError( + "This function was deprecated since version 1.9 and is now removed.\n" + "Please use the `torch.linalg.matrix_rank` function instead. " + "The parameter 'symmetric' was renamed in `torch.linalg.matrix_rank()` to 'hermitian'." + ) + + +def solve(input: Tensor, A: Tensor, *, out=None) -> tuple[Tensor, Tensor]: + raise RuntimeError( + "This function was deprecated since version 1.9 and is now removed. " + "`torch.solve` is deprecated in favor of `torch.linalg.solve`. " + "`torch.linalg.solve` has its arguments reversed and does not return the LU factorization.\n\n" + "To get the LU factorization see `torch.lu`, which can be used with `torch.lu_solve` or `torch.lu_unpack`.\n" + "X = torch.solve(B, A).solution " + "should be replaced with:\n" + "X = torch.linalg.solve(A, B)" + ) + + +def lstsq(input: Tensor, A: Tensor, *, out=None) -> tuple[Tensor, Tensor]: + raise RuntimeError( + "This function was deprecated since version 1.9 and is now removed. " + "`torch.lstsq` is deprecated in favor of `torch.linalg.lstsq`.\n" + "`torch.linalg.lstsq` has reversed arguments and does not return the QR decomposition in " + "the returned tuple (although it returns other information about the problem).\n\n" + "To get the QR decomposition consider using `torch.linalg.qr`.\n\n" + "The returned solution in `torch.lstsq` stored the residuals of the solution in the " + "last m - n columns of the returned value whenever m > n. In torch.linalg.lstsq, " + "the residuals are in the field 'residuals' of the returned named tuple.\n\n" + "The unpacking of the solution, as in\n" + "X, _ = torch.lstsq(B, A).solution[:A.size(1)]\n" + "should be replaced with:\n" + "X = torch.linalg.lstsq(A, B).solution" + ) + + +def _symeig( + input, + eigenvectors=False, + upper=True, + *, + out=None, +) -> tuple[Tensor, Tensor]: + raise RuntimeError( + "This function was deprecated since version 1.9 and is now removed. " + "The default behavior has changed from using the upper triangular portion of the matrix by default " + "to using the lower triangular portion.\n\n" + "L, _ = torch.symeig(A, upper=upper) " + "should be replaced with:\n" + "L = torch.linalg.eigvalsh(A, UPLO='U' if upper else 'L')\n\n" + "and\n\n" + "L, V = torch.symeig(A, eigenvectors=True) " + "should be replaced with:\n" + "L, V = torch.linalg.eigh(A, UPLO='U' if upper else 'L')" + ) + + +def eig( + self: Tensor, + eigenvectors: bool = False, + *, + e=None, + v=None, +) -> tuple[Tensor, Tensor]: + raise RuntimeError( + "This function was deprecated since version 1.9 and is now removed. " + "`torch.linalg.eig` returns complex tensors of dtype `cfloat` or `cdouble` rather than real tensors " + "mimicking complex tensors.\n\n" + "L, _ = torch.eig(A) " + "should be replaced with:\n" + "L_complex = torch.linalg.eigvals(A)\n\n" + "and\n\n" + "L, V = torch.eig(A, eigenvectors=True) " + "should be replaced with:\n" + "L_complex, V_complex = torch.linalg.eig(A)" + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_lobpcg.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_lobpcg.py new file mode 100644 index 0000000000000000000000000000000000000000..cdc426047c33fb950a423bf9f0d8d121a9f8bf25 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_lobpcg.py @@ -0,0 +1,1159 @@ +# mypy: allow-untyped-defs +"""Locally Optimal Block Preconditioned Conjugate Gradient methods.""" +# Author: Pearu Peterson +# Created: February 2020 + +import torch +from torch import _linalg_utils as _utils, Tensor +from torch.overrides import handle_torch_function, has_torch_function + + +__all__ = ["lobpcg"] + + +def _symeig_backward_complete_eigenspace(D_grad, U_grad, A, D, U): + # compute F, such that F_ij = (d_j - d_i)^{-1} for i != j, F_ii = 0 + F = D.unsqueeze(-2) - D.unsqueeze(-1) + F.diagonal(dim1=-2, dim2=-1).fill_(float("inf")) + F.pow_(-1) + + # A.grad = U (D.grad + (U^T U.grad * F)) U^T + Ut = U.mT.contiguous() + res = torch.matmul( + U, torch.matmul(torch.diag_embed(D_grad) + torch.matmul(Ut, U_grad) * F, Ut) + ) + + return res + + +def _polynomial_coefficients_given_roots(roots): + """ + Given the `roots` of a polynomial, find the polynomial's coefficients. + + If roots = (r_1, ..., r_n), then the method returns + coefficients (a_0, a_1, ..., a_n (== 1)) so that + p(x) = (x - r_1) * ... * (x - r_n) + = x^n + a_{n-1} * x^{n-1} + ... a_1 * x_1 + a_0 + + Note: for better performance requires writing a low-level kernel + """ + poly_order = roots.shape[-1] + poly_coeffs_shape = list(roots.shape) + # we assume p(x) = x^n + a_{n-1} * x^{n-1} + ... + a_1 * x + a_0, + # so poly_coeffs = {a_0, ..., a_n, a_{n+1}(== 1)}, + # but we insert one extra coefficient to enable better vectorization below + poly_coeffs_shape[-1] += 2 + poly_coeffs = roots.new_zeros(poly_coeffs_shape) + poly_coeffs[..., 0] = 1 + poly_coeffs[..., -1] = 1 + + # perform the Horner's rule + for i in range(1, poly_order + 1): + # note that it is computationally hard to compute backward for this method, + # because then given the coefficients it would require finding the roots and/or + # calculating the sensitivity based on the Vieta's theorem. + # So the code below tries to circumvent the explicit root finding by series + # of operations on memory copies imitating the Horner's method. + # The memory copies are required to construct nodes in the computational graph + # by exploiting the explicit (not in-place, separate node for each step) + # recursion of the Horner's method. + # Needs more memory, O(... * k^2), but with only O(... * k^2) complexity. + poly_coeffs_new = poly_coeffs.clone() if roots.requires_grad else poly_coeffs + out = poly_coeffs_new.narrow(-1, poly_order - i, i + 1) + out -= roots.narrow(-1, i - 1, 1) * poly_coeffs.narrow( + -1, poly_order - i + 1, i + 1 + ) + poly_coeffs = poly_coeffs_new + + return poly_coeffs.narrow(-1, 1, poly_order + 1) + + +def _polynomial_value(poly, x, zero_power, transition): + """ + A generic method for computing poly(x) using the Horner's rule. + + Args: + poly (Tensor): the (possibly batched) 1D Tensor representing + polynomial coefficients such that + poly[..., i] = (a_{i_0}, ..., a{i_n} (==1)), and + poly(x) = poly[..., 0] * zero_power + ... + poly[..., n] * x^n + + x (Tensor): the value (possible batched) to evaluate the polynomial `poly` at. + + zero_power (Tensor): the representation of `x^0`. It is application-specific. + + transition (Callable): the function that accepts some intermediate result `int_val`, + the `x` and a specific polynomial coefficient + `poly[..., k]` for some iteration `k`. + It basically performs one iteration of the Horner's rule + defined as `x * int_val + poly[..., k] * zero_power`. + Note that `zero_power` is not a parameter, + because the step `+ poly[..., k] * zero_power` depends on `x`, + whether it is a vector, a matrix, or something else, so this + functionality is delegated to the user. + """ + + res = zero_power.clone() + for k in range(poly.size(-1) - 2, -1, -1): + res = transition(res, x, poly[..., k]) + return res + + +def _matrix_polynomial_value(poly, x, zero_power=None): + """ + Evaluates `poly(x)` for the (batched) matrix input `x`. + Check out `_polynomial_value` function for more details. + """ + + # matrix-aware Horner's rule iteration + def transition(curr_poly_val, x, poly_coeff): + res = x.matmul(curr_poly_val) + res.diagonal(dim1=-2, dim2=-1).add_(poly_coeff.unsqueeze(-1)) + return res + + if zero_power is None: + zero_power = torch.eye( + x.size(-1), x.size(-1), dtype=x.dtype, device=x.device + ).view(*([1] * len(list(x.shape[:-2]))), x.size(-1), x.size(-1)) + + return _polynomial_value(poly, x, zero_power, transition) + + +def _vector_polynomial_value(poly, x, zero_power=None): + """ + Evaluates `poly(x)` for the (batched) vector input `x`. + Check out `_polynomial_value` function for more details. + """ + + # vector-aware Horner's rule iteration + def transition(curr_poly_val, x, poly_coeff): + res = torch.addcmul(poly_coeff.unsqueeze(-1), x, curr_poly_val) + return res + + if zero_power is None: + zero_power = x.new_ones(1).expand(x.shape) + + return _polynomial_value(poly, x, zero_power, transition) + + +def _symeig_backward_partial_eigenspace(D_grad, U_grad, A, D, U, largest): + # compute a projection operator onto an orthogonal subspace spanned by the + # columns of U defined as (I - UU^T) + Ut = U.mT.contiguous() + proj_U_ortho = -U.matmul(Ut) + proj_U_ortho.diagonal(dim1=-2, dim2=-1).add_(1) + + # compute U_ortho, a basis for the orthogonal complement to the span(U), + # by projecting a random [..., m, m - k] matrix onto the subspace spanned + # by the columns of U. + # + # fix generator for determinism + gen = torch.Generator(A.device) + + # orthogonal complement to the span(U) + U_ortho = proj_U_ortho.matmul( + torch.randn( + (*A.shape[:-1], A.size(-1) - D.size(-1)), + dtype=A.dtype, + device=A.device, + generator=gen, + ) + ) + U_ortho_t = U_ortho.mT.contiguous() + + # compute the coefficients of the characteristic polynomial of the tensor D. + # Note that D is diagonal, so the diagonal elements are exactly the roots + # of the characteristic polynomial. + chr_poly_D = _polynomial_coefficients_given_roots(D) + + # the code below finds the explicit solution to the Sylvester equation + # U_ortho^T A U_ortho dX - dX D = -U_ortho^T A U + # and incorporates it into the whole gradient stored in the `res` variable. + # + # Equivalent to the following naive implementation: + # res = A.new_zeros(A.shape) + # p_res = A.new_zeros(*A.shape[:-1], D.size(-1)) + # for k in range(1, chr_poly_D.size(-1)): + # p_res.zero_() + # for i in range(0, k): + # p_res += (A.matrix_power(k - 1 - i) @ U_grad) * D.pow(i).unsqueeze(-2) + # res -= chr_poly_D[k] * (U_ortho @ poly_D_at_A.inverse() @ U_ortho_t @ p_res @ U.t()) + # + # Note that dX is a differential, so the gradient contribution comes from the backward sensitivity + # Tr(f(U_grad, D_grad, A, U, D)^T dX) = Tr(g(U_grad, A, U, D)^T dA) for some functions f and g, + # and we need to compute g(U_grad, A, U, D) + # + # The naive implementation is based on the paper + # Hu, Qingxi, and Daizhan Cheng. + # "The polynomial solution to the Sylvester matrix equation." + # Applied mathematics letters 19.9 (2006): 859-864. + # + # We can modify the computation of `p_res` from above in a more efficient way + # p_res = U_grad * (chr_poly_D[1] * D.pow(0) + ... + chr_poly_D[k] * D.pow(k)).unsqueeze(-2) + # + A U_grad * (chr_poly_D[2] * D.pow(0) + ... + chr_poly_D[k] * D.pow(k - 1)).unsqueeze(-2) + # + ... + # + A.matrix_power(k - 1) U_grad * chr_poly_D[k] + # Note that this saves us from redundant matrix products with A (elimination of matrix_power) + U_grad_projected = U_grad + series_acc = U_grad_projected.new_zeros(U_grad_projected.shape) + for k in range(1, chr_poly_D.size(-1)): + poly_D = _vector_polynomial_value(chr_poly_D[..., k:], D) + series_acc += U_grad_projected * poly_D.unsqueeze(-2) + U_grad_projected = A.matmul(U_grad_projected) + + # compute chr_poly_D(A) which essentially is: + # + # chr_poly_D_at_A = A.new_zeros(A.shape) + # for k in range(chr_poly_D.size(-1)): + # chr_poly_D_at_A += chr_poly_D[k] * A.matrix_power(k) + # + # Note, however, for better performance we use the Horner's rule + chr_poly_D_at_A = _matrix_polynomial_value(chr_poly_D, A) + + # compute the action of `chr_poly_D_at_A` restricted to U_ortho_t + chr_poly_D_at_A_to_U_ortho = torch.matmul( + U_ortho_t, torch.matmul(chr_poly_D_at_A, U_ortho) + ) + # we need to invert 'chr_poly_D_at_A_to_U_ortho`, for that we compute its + # Cholesky decomposition and then use `torch.cholesky_solve` for better stability. + # Cholesky decomposition requires the input to be positive-definite. + # Note that `chr_poly_D_at_A_to_U_ortho` is positive-definite if + # 1. `largest` == False, or + # 2. `largest` == True and `k` is even + # under the assumption that `A` has distinct eigenvalues. + # + # check if `chr_poly_D_at_A_to_U_ortho` is positive-definite or negative-definite + chr_poly_D_at_A_to_U_ortho_sign = -1 if (largest and (k % 2 == 1)) else +1 + chr_poly_D_at_A_to_U_ortho_L = torch.linalg.cholesky( + chr_poly_D_at_A_to_U_ortho_sign * chr_poly_D_at_A_to_U_ortho + ) + + # compute the gradient part in span(U) + res = _symeig_backward_complete_eigenspace(D_grad, U_grad, A, D, U) + + # incorporate the Sylvester equation solution into the full gradient + # it resides in span(U_ortho) + res -= U_ortho.matmul( + chr_poly_D_at_A_to_U_ortho_sign + * torch.cholesky_solve( + U_ortho_t.matmul(series_acc), chr_poly_D_at_A_to_U_ortho_L + ) + ).matmul(Ut) + + return res + + +def _symeig_backward(D_grad, U_grad, A, D, U, largest): + # if `U` is square, then the columns of `U` is a complete eigenspace + if U.size(-1) == U.size(-2): + return _symeig_backward_complete_eigenspace(D_grad, U_grad, A, D, U) + else: + return _symeig_backward_partial_eigenspace(D_grad, U_grad, A, D, U, largest) + + +class LOBPCGAutogradFunction(torch.autograd.Function): + @staticmethod + def forward( # type: ignore[override] + ctx, + A: Tensor, + k: int | None = None, + B: Tensor | None = None, + X: Tensor | None = None, + n: int | None = None, + iK: Tensor | None = None, + niter: int | None = None, + tol: float | None = None, + largest: bool | None = None, + method: str | None = None, + tracker: None = None, + ortho_iparams: dict[str, int] | None = None, + ortho_fparams: dict[str, float] | None = None, + ortho_bparams: dict[str, bool] | None = None, + ) -> tuple[Tensor, Tensor]: + # makes sure that input is contiguous for efficiency. + # Note: autograd does not support dense gradients for sparse input yet. + A = A.contiguous() if (not A.is_sparse) else A + if B is not None: + B = B.contiguous() if (not B.is_sparse) else B + + D, U = _lobpcg( + A, + k, + B, + X, + n, + iK, + niter, + tol, + largest, + method, + tracker, + ortho_iparams, + ortho_fparams, + ortho_bparams, + ) + + ctx.save_for_backward(A, B, D, U) + ctx.largest = largest + + return D, U + + @staticmethod + def backward(ctx, D_grad, U_grad): # pyrefly: ignore # bad-override + A_grad = B_grad = None + grads = [None] * 14 + + A, B, D, U = ctx.saved_tensors + largest = ctx.largest + + # lobpcg.backward has some limitations. Checks for unsupported input + if A.is_sparse or (B is not None and B.is_sparse and ctx.needs_input_grad[2]): + raise ValueError( + "lobpcg.backward does not support sparse input yet." + "Note that lobpcg.forward does though." + ) + if ( + A.dtype in (torch.complex64, torch.complex128) + or B is not None + and B.dtype in (torch.complex64, torch.complex128) + ): + raise ValueError( + "lobpcg.backward does not support complex input yet." + "Note that lobpcg.forward does though." + ) + if B is not None: + raise ValueError( + "lobpcg.backward does not support backward with B != I yet." + ) + + if largest is None: + largest = True + + # symeig backward + if B is None: + A_grad = _symeig_backward(D_grad, U_grad, A, D, U, largest) + + # A has index 0 + grads[0] = A_grad + # B has index 2 + grads[2] = B_grad + return tuple(grads) + + +def lobpcg( + A: Tensor, + k: int | None = None, + B: Tensor | None = None, + X: Tensor | None = None, + n: int | None = None, + iK: Tensor | None = None, + niter: int | None = None, + tol: float | None = None, + largest: bool | None = None, + method: str | None = None, + tracker: None = None, + ortho_iparams: dict[str, int] | None = None, + ortho_fparams: dict[str, float] | None = None, + ortho_bparams: dict[str, bool] | None = None, +) -> tuple[Tensor, Tensor]: + """Find the k largest (or smallest) eigenvalues and the corresponding + eigenvectors of a symmetric positive definite generalized + eigenvalue problem using matrix-free LOBPCG methods. + + This function is a front-end to the following LOBPCG algorithms + selectable via `method` argument: + + `method="basic"` - the LOBPCG method introduced by Andrew + Knyazev, see [Knyazev2001]. A less robust method, may fail when + Cholesky is applied to singular input. + + `method="ortho"` - the LOBPCG method with orthogonal basis + selection [StathopoulosEtal2002]. A robust method. + + Supported inputs are dense, sparse, and batches of dense matrices. + + .. note:: In general, the basic method spends least time per + iteration. However, the robust methods converge much faster and + are more stable. So, the usage of the basic method is generally + not recommended but there exist cases where the usage of the + basic method may be preferred. + + .. warning:: The backward method does not support sparse and complex inputs. + It works only when `B` is not provided (i.e. `B == None`). + We are actively working on extensions, and the details of + the algorithms are going to be published promptly. + + .. warning:: While it is assumed that `A` is symmetric, `A.grad` is not. + To make sure that `A.grad` is symmetric, so that `A - t * A.grad` is symmetric + in first-order optimization routines, prior to running `lobpcg` + we do the following symmetrization map: `A -> (A + A.t()) / 2`. + The map is performed only when the `A` requires gradients. + + .. warning:: LOBPCG algorithm is not applicable when the number of `A`'s rows + is smaller than 3x the number of requested eigenpairs `n`. + + Args: + + A (Tensor): the input tensor of size :math:`(*, m, m)` + + k (integer, optional): the number of requested + eigenpairs. Default is the number of :math:`X` + columns (when specified) or `1`. + + B (Tensor, optional): the input tensor of size :math:`(*, m, + m)`. When not specified, `B` is interpreted as + identity matrix. + + X (tensor, optional): the input tensor of size :math:`(*, m, n)` + where `k <= n <= m`. When specified, it is used as + initial approximation of eigenvectors. X must be a + dense tensor. + + n (integer, optional): if :math:`X` is not specified then `n` + specifies the size of the generated random + approximation of eigenvectors. Default value for `n` + is `k`. If :math:`X` is specified, any provided value of `n` is + ignored and `n` is automatically set to the number of + columns in :math:`X`. + + iK (tensor, optional): the input tensor of size :math:`(*, m, + m)`. When specified, it will be used as preconditioner. + + niter (int, optional): maximum number of iterations. When + reached, the iteration process is hard-stopped and + the current approximation of eigenpairs is returned. + For infinite iteration but until convergence criteria + is met, use `-1`. + + tol (float, optional): residual tolerance for stopping + criterion. Default is `feps ** 0.5` where `feps` is + smallest non-zero floating-point number of the given + input tensor `A` data type. + + largest (bool, optional): when True, solve the eigenproblem for + the largest eigenvalues. Otherwise, solve the + eigenproblem for smallest eigenvalues. Default is + `True`. + + method (str, optional): select LOBPCG method. See the + description of the function above. Default is + "ortho". + + tracker (callable, optional) : a function for tracing the + iteration process. When specified, it is called at + each iteration step with LOBPCG instance as an + argument. The LOBPCG instance holds the full state of + the iteration process in the following attributes: + + `iparams`, `fparams`, `bparams` - dictionaries of + integer, float, and boolean valued input + parameters, respectively + + `ivars`, `fvars`, `bvars`, `tvars` - dictionaries + of integer, float, boolean, and Tensor valued + iteration variables, respectively. + + `A`, `B`, `iK` - input Tensor arguments. + + `E`, `X`, `S`, `R` - iteration Tensor variables. + + For instance: + + `ivars["istep"]` - the current iteration step + `X` - the current approximation of eigenvectors + `E` - the current approximation of eigenvalues + `R` - the current residual + `ivars["converged_count"]` - the current number of converged eigenpairs + `tvars["rerr"]` - the current state of convergence criteria + + Note that when `tracker` stores Tensor objects from + the LOBPCG instance, it must make copies of these. + + If `tracker` sets `bvars["force_stop"] = True`, the + iteration process will be hard-stopped. + + ortho_iparams, ortho_fparams, ortho_bparams (dict, optional): + various parameters to LOBPCG algorithm when using + `method="ortho"`. + + Returns: + + E (Tensor): tensor of eigenvalues of size :math:`(*, k)` + + X (Tensor): tensor of eigenvectors of size :math:`(*, m, k)` + + References: + + [Knyazev2001] Andrew V. Knyazev. (2001) Toward the Optimal + Preconditioned Eigensolver: Locally Optimal Block Preconditioned + Conjugate Gradient Method. SIAM J. Sci. Comput., 23(2), + 517-541. (25 pages) + https://epubs.siam.org/doi/abs/10.1137/S1064827500366124 + + [StathopoulosEtal2002] Andreas Stathopoulos and Kesheng + Wu. (2002) A Block Orthogonalization Procedure with Constant + Synchronization Requirements. SIAM J. Sci. Comput., 23(6), + 2165-2182. (18 pages) + https://epubs.siam.org/doi/10.1137/S1064827500370883 + + [DuerschEtal2018] Jed A. Duersch, Meiyue Shao, Chao Yang, Ming + Gu. (2018) A Robust and Efficient Implementation of LOBPCG. + SIAM J. Sci. Comput., 40(5), C655-C676. (22 pages) + https://arxiv.org/abs/1704.07458 + + """ + + if not torch.jit.is_scripting(): + tensor_ops = (A, B, X, iK) + if not set(map(type, tensor_ops)).issubset( + (torch.Tensor, type(None)) + ) and has_torch_function(tensor_ops): + return handle_torch_function( + lobpcg, + tensor_ops, + A, + k=k, + B=B, + X=X, + n=n, + iK=iK, + niter=niter, + tol=tol, + largest=largest, + method=method, + tracker=tracker, + ortho_iparams=ortho_iparams, + ortho_fparams=ortho_fparams, + ortho_bparams=ortho_bparams, + ) + + if not torch._jit_internal.is_scripting(): + if A.requires_grad or (B is not None and B.requires_grad): + # While it is expected that `A` is symmetric, + # the `A_grad` might be not. Therefore we perform the trick below, + # so that `A_grad` becomes symmetric. + # The symmetrization is important for first-order optimization methods, + # so that (A - alpha * A_grad) is still a symmetric matrix. + # Same holds for `B`. + A_sym = (A + A.mT) / 2 + B_sym = (B + B.mT) / 2 if (B is not None) else None + + return LOBPCGAutogradFunction.apply( + A_sym, + k, + B_sym, + X, + n, + iK, + niter, + tol, + largest, + method, + tracker, + ortho_iparams, + ortho_fparams, + ortho_bparams, + ) + else: + if A.requires_grad or (B is not None and B.requires_grad): + raise RuntimeError( + "Script and require grads is not supported atm." + "If you just want to do the forward, use .detach()" + "on A and B before calling into lobpcg" + ) + + return _lobpcg( + A, + k, + B, + X, + n, + iK, + niter, + tol, + largest, + method, + tracker, + ortho_iparams, + ortho_fparams, + ortho_bparams, + ) + + +def _lobpcg( + A: Tensor, + k: int | None = None, + B: Tensor | None = None, + X: Tensor | None = None, + n: int | None = None, + iK: Tensor | None = None, + niter: int | None = None, + tol: float | None = None, + largest: bool | None = None, + method: str | None = None, + tracker: None = None, + ortho_iparams: dict[str, int] | None = None, + ortho_fparams: dict[str, float] | None = None, + ortho_bparams: dict[str, bool] | None = None, +) -> tuple[Tensor, Tensor]: + # A must be square: + assert A.shape[-2] == A.shape[-1], A.shape + if B is not None: + # A and B must have the same shapes: + assert A.shape == B.shape, (A.shape, B.shape) + + dtype = _utils.get_floating_dtype(A) + device = A.device + if tol is None: + feps = {torch.float32: 1.2e-07, torch.float64: 2.23e-16}[dtype] + tol = feps**0.5 + + m = A.shape[-1] + k = (1 if X is None else X.shape[-1]) if k is None else k + n = (k if n is None else n) if X is None else X.shape[-1] + + if m < 3 * n: + raise ValueError( + f"LPBPCG algorithm is not applicable when the number of A rows (={m})" + f" is smaller than 3 x the number of requested eigenpairs (={n})" + ) + + method = "ortho" if method is None else method + + iparams = { + "m": m, + "n": n, + "k": k, + "niter": 1000 if niter is None else niter, + } + + fparams = { + "tol": tol, + } + + bparams = {"largest": True if largest is None else largest} + + if method == "ortho": + if ortho_iparams is not None: + iparams.update(ortho_iparams) + if ortho_fparams is not None: + fparams.update(ortho_fparams) + if ortho_bparams is not None: + bparams.update(ortho_bparams) + iparams["ortho_i_max"] = iparams.get("ortho_i_max", 3) + iparams["ortho_j_max"] = iparams.get("ortho_j_max", 3) + fparams["ortho_tol"] = fparams.get("ortho_tol", tol) + fparams["ortho_tol_drop"] = fparams.get("ortho_tol_drop", tol) + fparams["ortho_tol_replace"] = fparams.get("ortho_tol_replace", tol) + bparams["ortho_use_drop"] = bparams.get("ortho_use_drop", False) + + if not torch.jit.is_scripting(): + LOBPCG.call_tracker = LOBPCG_call_tracker # type: ignore[method-assign] + + if len(A.shape) > 2: + N = int(torch.prod(torch.tensor(A.shape[:-2]))) + bA = A.reshape((N,) + A.shape[-2:]) + bB = B.reshape((N,) + A.shape[-2:]) if B is not None else None + bX = X.reshape((N,) + X.shape[-2:]) if X is not None else None + bE = torch.empty((N, k), dtype=dtype, device=device) + bXret = torch.empty((N, m, k), dtype=dtype, device=device) + + for i in range(N): + A_ = bA[i] + B_ = bB[i] if bB is not None else None + X_ = ( + torch.randn((m, n), dtype=dtype, device=device) if bX is None else bX[i] + ) + assert len(X_.shape) == 2 and X_.shape == (m, n), (X_.shape, (m, n)) + iparams["batch_index"] = i + worker = LOBPCG(A_, B_, X_, iK, iparams, fparams, bparams, method, tracker) + worker.run() + bE[i] = worker.E[:k] + bXret[i] = worker.X[:, :k] + + if not torch.jit.is_scripting(): + LOBPCG.call_tracker = LOBPCG_call_tracker_orig # type: ignore[method-assign] + + return bE.reshape(A.shape[:-2] + (k,)), bXret.reshape(A.shape[:-2] + (m, k)) + + X = torch.randn((m, n), dtype=dtype, device=device) if X is None else X + assert len(X.shape) == 2 and X.shape == (m, n), (X.shape, (m, n)) + + worker = LOBPCG(A, B, X, iK, iparams, fparams, bparams, method, tracker) + + worker.run() + + if not torch.jit.is_scripting(): + LOBPCG.call_tracker = LOBPCG_call_tracker_orig # type: ignore[method-assign] + + return worker.E[:k], worker.X[:, :k] + + +class LOBPCG: + """Worker class of LOBPCG methods.""" + + def __init__( + self, + A: Tensor | None, + B: Tensor | None, + X: Tensor, + iK: Tensor | None, + iparams: dict[str, int], + fparams: dict[str, float], + bparams: dict[str, bool], + method: str, + tracker: None, + ) -> None: + # constant parameters + self.A = A + self.B = B + self.iK = iK + self.iparams = iparams + self.fparams = fparams + self.bparams = bparams + self.method = method + self.tracker = tracker + m = iparams["m"] + n = iparams["n"] + + # variable parameters + self.X = X + self.E = torch.zeros((n,), dtype=X.dtype, device=X.device) + self.R = torch.zeros((m, n), dtype=X.dtype, device=X.device) + self.S = torch.zeros((m, 3 * n), dtype=X.dtype, device=X.device) + self.tvars: dict[str, Tensor] = {} + self.ivars: dict[str, int] = {"istep": 0} + self.fvars: dict[str, float] = {"_": 0.0} + self.bvars: dict[str, bool] = {"_": False} + + def __str__(self): + lines = ["LOPBCG:"] + lines += [f" iparams={self.iparams}"] + lines += [f" fparams={self.fparams}"] + lines += [f" bparams={self.bparams}"] + lines += [f" ivars={self.ivars}"] + lines += [f" fvars={self.fvars}"] + lines += [f" bvars={self.bvars}"] + lines += [f" tvars={self.tvars}"] + lines += [f" A={self.A}"] + lines += [f" B={self.B}"] + lines += [f" iK={self.iK}"] + lines += [f" X={self.X}"] + lines += [f" E={self.E}"] + r = "" + for line in lines: + r += line + "\n" + return r + + def update(self): + """Set and update iteration variables.""" + if self.ivars["istep"] == 0: + X_norm = float(torch.norm(self.X)) + iX_norm = X_norm**-1 + A_norm = float(torch.norm(_utils.matmul(self.A, self.X))) * iX_norm + B_norm = float(torch.norm(_utils.matmul(self.B, self.X))) * iX_norm + self.fvars["X_norm"] = X_norm + self.fvars["A_norm"] = A_norm + self.fvars["B_norm"] = B_norm + self.ivars["iterations_left"] = self.iparams["niter"] + self.ivars["converged_count"] = 0 + self.ivars["converged_end"] = 0 + + if self.method == "ortho": + self._update_ortho() + else: + self._update_basic() + + self.ivars["iterations_left"] = self.ivars["iterations_left"] - 1 + self.ivars["istep"] = self.ivars["istep"] + 1 + + def update_residual(self): + """Update residual R from A, B, X, E.""" + mm = _utils.matmul + self.R = mm(self.A, self.X) - mm(self.B, self.X) * self.E + + def update_converged_count(self): + """Determine the number of converged eigenpairs using backward stable + convergence criterion, see discussion in Sec 4.3 of [DuerschEtal2018]. + + Users may redefine this method for custom convergence criteria. + """ + # (...) -> int + prev_count = self.ivars["converged_count"] + tol = self.fparams["tol"] + A_norm = self.fvars["A_norm"] + B_norm = self.fvars["B_norm"] + E, X, R = self.E, self.X, self.R + rerr = torch.norm(R, 2, (0,)) / ( + torch.norm(X, 2, (0,)) * (A_norm + torch.abs(E[: X.shape[-1]]) * B_norm) + ) + converged = rerr < tol + count = 0 + for b in converged: + if not b: + # ignore convergence of following pairs to ensure + # strict ordering of eigenpairs + break + count += 1 + assert count >= prev_count, ( + f"the number of converged eigenpairs (was {prev_count}, got {count}) cannot decrease" + ) + self.ivars["converged_count"] = count + self.tvars["rerr"] = rerr + return count + + def stop_iteration(self): + """Return True to stop iterations. + + Note that tracker (if defined) can force-stop iterations by + setting ``worker.bvars['force_stop'] = True``. + """ + return ( + self.bvars.get("force_stop", False) + or self.ivars["iterations_left"] == 0 + or self.ivars["converged_count"] >= self.iparams["k"] + ) + + def run(self): + """Run LOBPCG iterations. + + Use this method as a template for implementing LOBPCG + iteration scheme with custom tracker that is compatible with + TorchScript. + """ + self.update() + + if not torch.jit.is_scripting() and self.tracker is not None: + self.call_tracker() + + while not self.stop_iteration(): + self.update() + + if not torch.jit.is_scripting() and self.tracker is not None: + self.call_tracker() + + @torch.jit.unused + def call_tracker(self): + """Interface for tracking iteration process in Python mode. + + Tracking the iteration process is disabled in TorchScript + mode. In fact, one should specify tracker=None when JIT + compiling functions using lobpcg. + """ + # do nothing when in TorchScript mode + + # Internal methods + + def _update_basic(self): + """ + Update or initialize iteration variables when `method == "basic"`. + """ + mm = torch.matmul + ns = self.ivars["converged_end"] + nc = self.ivars["converged_count"] + n = self.iparams["n"] + largest = self.bparams["largest"] + + if self.ivars["istep"] == 0: + Ri = self._get_rayleigh_ritz_transform(self.X) + M = _utils.qform(_utils.qform(self.A, self.X), Ri) + E, Z = _utils.symeig(M, largest) + self.X[:] = mm(self.X, mm(Ri, Z)) + self.E[:] = E + np = 0 + self.update_residual() + nc = self.update_converged_count() + self.S[..., :n] = self.X + + W = _utils.matmul(self.iK, self.R) + self.ivars["converged_end"] = ns = n + np + W.shape[-1] + self.S[:, n + np : ns] = W + else: + S_ = self.S[:, nc:ns] + Ri = self._get_rayleigh_ritz_transform(S_) + M = _utils.qform(_utils.qform(self.A, S_), Ri) + E_, Z = _utils.symeig(M, largest) + self.X[:, nc:] = mm(S_, mm(Ri, Z[:, : n - nc])) + self.E[nc:] = E_[: n - nc] + P = mm(S_, mm(Ri, Z[:, n : 2 * n - nc])) + np = P.shape[-1] + + self.update_residual() + nc = self.update_converged_count() + self.S[..., :n] = self.X + self.S[:, n : n + np] = P + W = _utils.matmul(self.iK, self.R[:, nc:]) + + self.ivars["converged_end"] = ns = n + np + W.shape[-1] + self.S[:, n + np : ns] = W + + def _update_ortho(self): + """ + Update or initialize iteration variables when `method == "ortho"`. + """ + mm = torch.matmul + ns = self.ivars["converged_end"] + nc = self.ivars["converged_count"] + n = self.iparams["n"] + largest = self.bparams["largest"] + + if self.ivars["istep"] == 0: + Ri = self._get_rayleigh_ritz_transform(self.X) + M = _utils.qform(_utils.qform(self.A, self.X), Ri) + _E, Z = _utils.symeig(M, largest) + self.X = mm(self.X, mm(Ri, Z)) + self.update_residual() + np = 0 + nc = self.update_converged_count() + self.S[:, :n] = self.X + W = self._get_ortho(self.R, self.X) + ns = self.ivars["converged_end"] = n + np + W.shape[-1] + self.S[:, n + np : ns] = W + + else: + S_ = self.S[:, nc:ns] + # Rayleigh-Ritz procedure + E_, Z = _utils.symeig(_utils.qform(self.A, S_), largest) + + # Update E, X, P + self.X[:, nc:] = mm(S_, Z[:, : n - nc]) + self.E[nc:] = E_[: n - nc] + P = mm(S_, mm(Z[:, n - nc :], _utils.basis(Z[: n - nc, n - nc :].mT))) + np = P.shape[-1] + + # check convergence + self.update_residual() + nc = self.update_converged_count() + + # update S + self.S[:, :n] = self.X + self.S[:, n : n + np] = P + W = self._get_ortho(self.R[:, nc:], self.S[:, : n + np]) + ns = self.ivars["converged_end"] = n + np + W.shape[-1] + self.S[:, n + np : ns] = W + + def _get_rayleigh_ritz_transform(self, S): + """Return a transformation matrix that is used in Rayleigh-Ritz + procedure for reducing a general eigenvalue problem :math:`(S^TAS) + C = (S^TBS) C E` to a standard eigenvalue problem :math: `(Ri^T + S^TAS Ri) Z = Z E` where `C = Ri Z`. + + .. note:: In the original Rayleight-Ritz procedure in + [DuerschEtal2018], the problem is formulated as follows:: + + SAS = S^T A S + SBS = S^T B S + D = () ** -1/2 + R^T R = Cholesky(D SBS D) + Ri = D R^-1 + solve symeig problem Ri^T SAS Ri Z = Theta Z + C = Ri Z + + To reduce the number of matrix products (denoted by empty + space between matrices), here we introduce element-wise + products (denoted by symbol `*`) so that the Rayleight-Ritz + procedure becomes:: + + SAS = S^T A S + SBS = S^T B S + d = () ** -1/2 # this is 1-d column vector + dd = d d^T # this is 2-d matrix + R^T R = Cholesky(dd * SBS) + Ri = R^-1 * d # broadcasting + solve symeig problem Ri^T SAS Ri Z = Theta Z + C = Ri Z + + where `dd` is 2-d matrix that replaces matrix products `D M + D` with one element-wise product `M * dd`; and `d` replaces + matrix product `D M` with element-wise product `M * + d`. Also, creating the diagonal matrix `D` is avoided. + + Args: + S (Tensor): the matrix basis for the search subspace, size is + :math:`(m, n)`. + + Returns: + Ri (tensor): upper-triangular transformation matrix of size + :math:`(n, n)`. + + """ + B = self.B + SBS = _utils.qform(B, S) + d_row = SBS.diagonal(0, -2, -1) ** -0.5 + d_col = d_row.reshape(d_row.shape[0], 1) + # TODO use torch.linalg.cholesky_solve once it is implemented + R = torch.linalg.cholesky((SBS * d_row) * d_col, upper=True) + return torch.linalg.solve_triangular( + R, d_row.diag_embed(), upper=True, left=False + ) + + def _get_svqb(self, U: Tensor, drop: bool, tau: float) -> Tensor: + """Return B-orthonormal U. + + .. note:: When `drop` is `False` then `svqb` is based on the + Algorithm 4 from [DuerschPhD2015] that is a slight + modification of the corresponding algorithm + introduced in [StathopolousWu2002]. + + Args: + + U (Tensor) : initial approximation, size is (m, n) + drop (bool) : when True, drop columns that + contribution to the `span([U])` is small. + tau (float) : positive tolerance + + Returns: + + U (Tensor) : B-orthonormal columns (:math:`U^T B U = I`), size + is (m, n1), where `n1 = n` if `drop` is `False, + otherwise `n1 <= n`. + + """ + if torch.numel(U) == 0: + return U + UBU = _utils.qform(self.B, U) + d = UBU.diagonal(0, -2, -1) + + # Detect and drop exact zero columns from U. While the test + # `abs(d) == 0` is unlikely to be True for random data, it is + # possible to construct input data to lobpcg where it will be + # True leading to a failure (notice the `d ** -0.5` operation + # in the original algorithm). To prevent the failure, we drop + # the exact zero columns here and then continue with the + # original algorithm below. + nz = torch.where(abs(d) != 0.0) + assert len(nz) == 1, nz + if len(nz[0]) < len(d): + U = U[:, nz[0]] + if torch.numel(U) == 0: + return U + UBU = _utils.qform(self.B, U) + d = UBU.diagonal(0, -2, -1) + nz = torch.where(abs(d) != 0.0) + assert len(nz[0]) == len(d) + + # The original algorithm 4 from [DuerschPhD2015]. + d_col = (d**-0.5).reshape(d.shape[0], 1) + DUBUD = (UBU * d_col) * d_col.mT + E, Z = _utils.symeig(DUBUD) + t = tau * abs(E).max() + if drop: + keep = torch.where(E > t) + assert len(keep) == 1, keep + E = E[keep[0]] + Z = Z[:, keep[0]] + d_col = d_col[keep[0]] + else: + E[(torch.where(E < t))[0]] = t + + return torch.matmul( + U * d_col.mT, + # pyrefly: ignore [unsupported-operation] + Z * E**-0.5, + ) + + def _get_ortho(self, U, V): + """Return B-orthonormal U with columns are B-orthogonal to V. + + .. note:: When `bparams["ortho_use_drop"] == False` then + `_get_ortho` is based on the Algorithm 3 from + [DuerschPhD2015] that is a slight modification of + the corresponding algorithm introduced in + [StathopolousWu2002]. Otherwise, the method + implements Algorithm 6 from [DuerschPhD2015] + + .. note:: If all U columns are B-collinear to V then the + returned tensor U will be empty. + + Args: + + U (Tensor) : initial approximation, size is (m, n) + V (Tensor) : B-orthogonal external basis, size is (m, k) + + Returns: + + U (Tensor) : B-orthonormal columns (:math:`U^T B U = I`) + such that :math:`V^T B U=0`, size is (m, n1), + where `n1 = n` if `drop` is `False, otherwise + `n1 <= n`. + """ + mm = torch.matmul + mm_B = _utils.matmul + m = self.iparams["m"] + tau_ortho = self.fparams["ortho_tol"] + tau_drop = self.fparams["ortho_tol_drop"] + tau_replace = self.fparams["ortho_tol_replace"] + i_max = self.iparams["ortho_i_max"] + j_max = self.iparams["ortho_j_max"] + # when use_drop==True, enable dropping U columns that have + # small contribution to the `span([U, V])`. + use_drop = self.bparams["ortho_use_drop"] + + # clean up variables from the previous call + for vkey in list(self.fvars.keys()): + if vkey.startswith("ortho_") and vkey.endswith("_rerr"): + self.fvars.pop(vkey) + self.ivars.pop("ortho_i", 0) + self.ivars.pop("ortho_j", 0) + + BV_norm = torch.norm(mm_B(self.B, V)) + BU = mm_B(self.B, U) + VBU = mm(V.mT, BU) + i = j = 0 + for i in range(i_max): + U = U - mm(V, VBU) + drop = False + tau_svqb = tau_drop + for j in range(j_max): + if use_drop: + U = self._get_svqb(U, drop, tau_svqb) + drop = True + tau_svqb = tau_replace + else: + U = self._get_svqb(U, False, tau_replace) + if torch.numel(U) == 0: + # all initial U columns are B-collinear to V + self.ivars["ortho_i"] = i + self.ivars["ortho_j"] = j + return U + BU = mm_B(self.B, U) + UBU = mm(U.mT, BU) + U_norm = torch.norm(U) + BU_norm = torch.norm(BU) + R = UBU - torch.eye(UBU.shape[-1], device=UBU.device, dtype=UBU.dtype) + R_norm = torch.norm(R) + # https://github.com/pytorch/pytorch/issues/33810 workaround: + rerr = float(R_norm) * float(BU_norm * U_norm) ** -1 + vkey = f"ortho_UBUmI_rerr[{i}, {j}]" + self.fvars[vkey] = rerr + if rerr < tau_ortho: + break + VBU = mm(V.mT, BU) + VBU_norm = torch.norm(VBU) + U_norm = torch.norm(U) + rerr = float(VBU_norm) * float(BV_norm * U_norm) ** -1 + vkey = f"ortho_VBU_rerr[{i}]" + self.fvars[vkey] = rerr + if rerr < tau_ortho: + break + if m < U.shape[-1] + V.shape[-1]: + # TorchScript needs the class var to be assigned to a local to + # do optional type refinement + B = self.B + assert B is not None + raise ValueError( + "Overdetermined shape of U:" + f" #B-cols(={B.shape[-1]}) >= #U-cols(={U.shape[-1]}) + #V-cols(={V.shape[-1]}) must hold" + ) + self.ivars["ortho_i"] = i + self.ivars["ortho_j"] = j + return U + + +# Calling tracker is separated from LOBPCG definitions because +# TorchScript does not support user-defined callback arguments: +LOBPCG_call_tracker_orig = LOBPCG.call_tracker + + +def LOBPCG_call_tracker(self): + self.tracker(self) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_lowrank.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_lowrank.py new file mode 100644 index 0000000000000000000000000000000000000000..25089d66d35eaf2fbe186499dde6f3ea51795562 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_lowrank.py @@ -0,0 +1,293 @@ +"""Implement various linear algebra algorithms for low rank matrices.""" + +__all__ = ["svd_lowrank", "pca_lowrank"] + + +import torch +from torch import _linalg_utils as _utils, Tensor +from torch.overrides import handle_torch_function, has_torch_function + + +def get_approximate_basis( + A: Tensor, + q: int, + niter: int | None = 2, + M: Tensor | None = None, +) -> Tensor: + """Return tensor :math:`Q` with :math:`q` orthonormal columns such + that :math:`Q Q^H A` approximates :math:`A`. If :math:`M` is + specified, then :math:`Q` is such that :math:`Q Q^H (A - M)` + approximates :math:`A - M`. without instantiating any tensors + of the size of :math:`A` or :math:`M`. + + .. note:: The implementation is based on the Algorithm 4.4 from + Halko et al., 2009. + + .. note:: For an adequate approximation of a k-rank matrix + :math:`A`, where k is not known in advance but could be + estimated, the number of :math:`Q` columns, q, can be + chosen according to the following criteria: in general, + :math:`k <= q <= min(2*k, m, n)`. For large low-rank + matrices, take :math:`q = k + 5..10`. If k is + relatively small compared to :math:`min(m, n)`, choosing + :math:`q = k + 0..2` may be sufficient. + + .. note:: To obtain repeatable results, reset the seed for the + pseudorandom number generator + + Args:: + A (Tensor): the input tensor of size :math:`(*, m, n)` + + q (int): the dimension of subspace spanned by :math:`Q` + columns. + + niter (int, optional): the number of subspace iterations to + conduct; ``niter`` must be a + nonnegative integer. In most cases, the + default value 2 is more than enough. + + M (Tensor, optional): the input tensor's mean of size + :math:`(*, m, n)`. + + References:: + - Nathan Halko, Per-Gunnar Martinsson, and Joel Tropp, Finding + structure with randomness: probabilistic algorithms for + constructing approximate matrix decompositions, + arXiv:0909.4061 [math.NA; math.PR], 2009 (available at + `arXiv `_). + """ + + niter = 2 if niter is None else niter + dtype = _utils.get_floating_dtype(A) if not A.is_complex() else A.dtype + matmul = _utils.matmul + + R = torch.randn(A.shape[-1], q, dtype=dtype, device=A.device) + + # The following code could be made faster using torch.geqrf + torch.ormqr + # but geqrf is not differentiable + + X = matmul(A, R) + if M is not None: + X = X - matmul(M, R) + Q = torch.linalg.qr(X).Q + for _ in range(niter): + X = matmul(A.mH, Q) + if M is not None: + X = X - matmul(M.mH, Q) + Q = torch.linalg.qr(X).Q + X = matmul(A, Q) + if M is not None: + X = X - matmul(M, Q) + Q = torch.linalg.qr(X).Q + return Q + + +def svd_lowrank( + A: Tensor, + q: int | None = 6, + niter: int | None = 2, + M: Tensor | None = None, +) -> tuple[Tensor, Tensor, Tensor]: + r"""Return the singular value decomposition ``(U, S, V)`` of a matrix, + batches of matrices, or a sparse matrix :math:`A` such that + :math:`A \approx U \operatorname{diag}(S) V^{\text{H}}`. In case :math:`M` is given, then + SVD is computed for the matrix :math:`A - M`. + + .. note:: The implementation is based on the Algorithm 5.1 from + Halko et al., 2009. + + .. note:: For an adequate approximation of a k-rank matrix + :math:`A`, where k is not known in advance but could be + estimated, the number of :math:`Q` columns, q, can be + chosen according to the following criteria: in general, + :math:`k <= q <= min(2*k, m, n)`. For large low-rank + matrices, take :math:`q = k + 5..10`. If k is + relatively small compared to :math:`min(m, n)`, choosing + :math:`q = k + 0..2` may be sufficient. + + .. note:: This is a randomized method. To obtain repeatable results, + set the seed for the pseudorandom number generator + + .. note:: In general, use the full-rank SVD implementation + :func:`torch.linalg.svd` for dense matrices due to its 10x + higher performance characteristics. The low-rank SVD + will be useful for huge sparse matrices that + :func:`torch.linalg.svd` cannot handle. + + Args:: + A (Tensor): the input tensor of size :math:`(*, m, n)` + + q (int, optional): a slightly overestimated rank of A. + + niter (int, optional): the number of subspace iterations to + conduct; niter must be a nonnegative + integer, and defaults to 2 + + M (Tensor, optional): the input tensor's mean of size + :math:`(*, m, n)`, which will be broadcasted + to the size of A in this function. + + References:: + - Nathan Halko, Per-Gunnar Martinsson, and Joel Tropp, Finding + structure with randomness: probabilistic algorithms for + constructing approximate matrix decompositions, + arXiv:0909.4061 [math.NA; math.PR], 2009 (available at + `arXiv `_). + + """ + if not torch.jit.is_scripting(): + tensor_ops = (A, M) + if not set(map(type, tensor_ops)).issubset( + (torch.Tensor, type(None)) + ) and has_torch_function(tensor_ops): + return handle_torch_function( + svd_lowrank, tensor_ops, A, q=q, niter=niter, M=M + ) + return _svd_lowrank(A, q=q, niter=niter, M=M) + + +def _svd_lowrank( + A: Tensor, + q: int | None = 6, + niter: int | None = 2, + M: Tensor | None = None, +) -> tuple[Tensor, Tensor, Tensor]: + # Algorithm 5.1 in Halko et al., 2009 + + q = 6 if q is None else q + m, n = A.shape[-2:] + matmul = _utils.matmul + if M is not None: + M = M.broadcast_to(A.size()) + + # Assume that A is tall + if m < n: + A = A.mH + if M is not None: + M = M.mH + + Q = get_approximate_basis(A, q, niter=niter, M=M) + B = matmul(Q.mH, A) + if M is not None: + B = B - matmul(Q.mH, M) + U, S, Vh = torch.linalg.svd(B, full_matrices=False) + V = Vh.mH + U = Q.matmul(U) + + if m < n: + U, V = V, U + + return U, S, V + + +def pca_lowrank( + A: Tensor, + q: int | None = None, + center: bool = True, + niter: int = 2, +) -> tuple[Tensor, Tensor, Tensor]: + r"""Performs linear Principal Component Analysis (PCA) on a low-rank + matrix, batches of such matrices, or sparse matrix. + + This function returns a namedtuple ``(U, S, V)`` which is the + nearly optimal approximation of a singular value decomposition of + a centered matrix :math:`A` such that :math:`A \approx U \operatorname{diag}(S) V^{\text{H}}` + + .. note:: The relation of ``(U, S, V)`` to PCA is as follows: + + - :math:`A` is a data matrix with ``m`` samples and + ``n`` features + + - the :math:`V` columns represent the principal directions + + - :math:`S ** 2 / (m - 1)` contains the eigenvalues of + :math:`A^T A / (m - 1)` which is the covariance of + ``A`` when ``center=True`` is provided. + + - ``matmul(A, V[:, :k])`` projects data to the first k + principal components + + .. note:: Different from the standard SVD, the size of returned + matrices depend on the specified rank and q + values as follows: + + - :math:`U` is m x q matrix + + - :math:`S` is q-vector + + - :math:`V` is n x q matrix + + .. note:: To obtain repeatable results, reset the seed for the + pseudorandom number generator + + Args: + + A (Tensor): the input tensor of size :math:`(*, m, n)` + + q (int, optional): a slightly overestimated rank of + :math:`A`. By default, ``q = min(6, m, + n)``. + + center (bool, optional): if True, center the input tensor, + otherwise, assume that the input is + centered. + + niter (int, optional): the number of subspace iterations to + conduct; niter must be a nonnegative + integer, and defaults to 2. + + References:: + + - Nathan Halko, Per-Gunnar Martinsson, and Joel Tropp, Finding + structure with randomness: probabilistic algorithms for + constructing approximate matrix decompositions, + arXiv:0909.4061 [math.NA; math.PR], 2009 (available at + `arXiv `_). + + """ + + if not torch.jit.is_scripting(): + if type(A) is not torch.Tensor and has_torch_function((A,)): + return handle_torch_function( + pca_lowrank, (A,), A, q=q, center=center, niter=niter + ) + + (m, n) = A.shape[-2:] + + if q is None: + q = min(6, m, n) + elif not (q >= 0 and q <= min(m, n)): + raise ValueError( + f"q(={q}) must be non-negative integer and not greater than min(m, n)={min(m, n)}" + ) + if not (niter >= 0): + raise ValueError(f"niter(={niter}) must be non-negative integer") + + dtype = _utils.get_floating_dtype(A) + + if not center: + return _svd_lowrank(A, q, niter=niter, M=None) + + if _utils.is_sparse(A): + if len(A.shape) != 2: + raise ValueError("pca_lowrank input is expected to be 2-dimensional tensor") + c = torch.sparse.sum(A, dim=(-2,)) / m + # reshape c + column_indices = c.indices()[0] + indices = torch.zeros( + 2, + len(column_indices), + dtype=column_indices.dtype, + device=column_indices.device, + ) + indices[0] = column_indices + C_t = torch.sparse_coo_tensor( + indices, c.values(), (n, 1), dtype=dtype, device=A.device + ) + + ones_m1_t = torch.ones(A.shape[:-2] + (1, m), dtype=dtype, device=A.device) + M = torch.sparse.mm(C_t, ones_m1_t).mT + return _svd_lowrank(A, q, niter=niter, M=M) + else: + C = A.mean(dim=(-2,), keepdim=True) + return _svd_lowrank(A - C, q, niter=niter, M=None) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_meta_registrations.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_meta_registrations.py new file mode 100644 index 0000000000000000000000000000000000000000..8ae519b65e8a4bbbd0ae913cdf7a2f4bbec12dfb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_meta_registrations.py @@ -0,0 +1,8456 @@ +# mypy: allow-untyped-defs +import math +from collections.abc import Callable, Sequence +from enum import Enum +from functools import wraps +from typing import TypeVar +from typing_extensions import ParamSpec + +import torch +import torch._prims_common as utils +from torch import SymBool, SymFloat, Tensor +from torch._decomp import ( + _add_op_to_registry, + _convert_out_params, + global_decomposition_table, + meta_table, +) +from torch._ops import OpOverload +from torch._prims import _prim_elementwise_meta, ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND +from torch._prims_common import ( + BoolLike, + corresponding_complex_dtype, + corresponding_real_dtype, + elementwise_dtypes, + ELEMENTWISE_TYPE_PROMOTION_KIND, + FloatLike, + IntLike, + make_contiguous_strides_for, + Number, + suggest_memory_format, + TensorLike, +) +from torch._prims_common.wrappers import ( + _maybe_convert_to_dtype, + _maybe_resize_out, + _resize_output_check, + _safe_copy_out, + out_wrapper, +) +from torch._refs import _broadcast_shapes, _maybe_broadcast +from torch.fx.experimental import _config as exp_config +from torch.nn.functional import ScalingType, SwizzleType +from torch.utils import _pytree as pytree + + +_T = TypeVar("_T") +_P = ParamSpec("_P") + +aten = torch.ops.aten + +_meta_lib_dont_use_me_use_register_meta = torch.library.Library("aten", "IMPL", "Meta") +MODE_SUM, MODE_MEAN, MODE_MAX = range(3) + + +def ceil_div(a, b): + return (a + b - 1) // b + + +def round_up(x, y): + """Rounds up x to nearest multiple of y""" + return ((x + y - 1) // y) * y + + +def register_meta(op) -> Callable[[Callable[_P, _T]], Callable[_P, _T]]: + def wrapper(fn): + fn = _convert_out_params(fn) + + def register(op): + _add_op_to_registry(meta_table, op, fn) + + pytree.tree_map_(register, op) + return fn + + return wrapper + + +def elementwise_meta( + *args, + type_promotion: ELEMENTWISE_TYPE_PROMOTION_KIND, +): + # Perform type promotion, as this is expected from prim_metafunction + _, result_dtype = utils.elementwise_dtypes( + *args, + type_promotion_kind=type_promotion, + ) + args = [_maybe_convert_to_dtype(x, result_dtype) for x in args] + + # Broadcast + args = _maybe_broadcast(*args) + + # Perform prim checks + return _prim_elementwise_meta( + *args, type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT + ) + + +def toRealValueType(dtype): + from_complex = { + torch.complex32: torch.half, + torch.cfloat: torch.float, + torch.cdouble: torch.double, + } + return from_complex.get(dtype, dtype) + + +def check_inplace_broadcast(self_shape, *args_shape): + broadcasted_shape = tuple(_broadcast_shapes(self_shape, *args_shape)) + torch._check( + broadcasted_shape == self_shape, + lambda: f"output with shape {self_shape} doesn't match the broadcast shape {broadcasted_shape}", + ) + + +@register_meta([aten.linspace, aten.logspace]) +@out_wrapper() +def meta_linspace_logspace( + start, + end, + steps, + base=None, + dtype=None, + device=None, + layout=torch.strided, + pin_memory=False, + requires_grad=False, +): + if isinstance(start, torch.Tensor): + torch._check( + start.dim() == 0, + lambda: "linspace only supports 0-dimensional start and end tensors", + ) + if isinstance(end, torch.Tensor): + torch._check( + end.dim() == 0, + lambda: "linspace only supports 0-dimensional start and end tensors", + ) + + if any(isinstance(arg, complex) for arg in (start, end, steps)): + default_complex_dtype = utils.corresponding_complex_dtype( + torch.get_default_dtype() + ) + if dtype is None: + dtype = default_complex_dtype + else: + torch._check( + utils.is_complex_dtype(dtype), + lambda: f"linspace(): inferred dtype {default_complex_dtype} can't be safely cast to passed dtype {dtype}", + ) + else: + dtype = dtype or torch.get_default_dtype() + assert isinstance(dtype, torch.dtype) + + # steps does not participate in the computation of the dtype + torch._check_type( + isinstance(steps, IntLike), + lambda: f"received an invalid combination of arguments - got \ +({type(start).__name__}, {type(end).__name__}, {type(steps).__name__})", + ) + assert isinstance(steps, IntLike) # for mypy + torch._check(steps >= 0, lambda: "number of steps must be non-negative") + + return torch.empty( + (steps,), # type: ignore[arg-type] + dtype=dtype, + layout=layout, + device="meta", + pin_memory=pin_memory, + requires_grad=requires_grad, + ) + + +@register_meta([aten.take.default, aten.take.out]) +@out_wrapper() +def meta_take(self, index): + # Type and device checks + torch._check( + index.dtype == torch.long, + lambda: f"take(): Expected a long tensor for index, but got {index.dtype}", + ) + # Index checks + torch._check_index( + not (self.numel() == 0 and index.numel() != 0), + lambda: "take(): tried to take from an empty tensor", + ) + return self.new_empty(index.shape) + + +@register_meta([aten.linalg_cross.default, aten.linalg_cross.out]) +@out_wrapper() +def linalg_cross(self, other, *, dim=-1): + x_d = self.ndim + y_d = other.ndim + torch._check( + x_d == y_d, + lambda: "linalg.cross: inputs must have the same number of dimensions.", + ) + torch._check( + self.size(dim) == 3 and other.size(dim) == 3, + lambda: ( + f"linalg.cross: inputs dimension {dim} must have length 3. " + f"Got {self.size(dim)} and {other.size(dim)}" + ), + ) + out_shape = _broadcast_shapes(self.shape, other.shape) + return self.new_empty(out_shape) + + +@register_meta(aten.linalg_matrix_exp) +@out_wrapper() +def linalg_matrix_exp(self): + squareCheckInputs(self, "linalg.matrix_exp") + checkFloatingOrComplex(self, "linalg.matrix_exp") + return torch.empty_like(self, memory_format=torch.contiguous_format) + + +@register_meta( + [aten.cummax.default, aten.cummax.out, aten.cummin.default, aten.cummin.out] +) +@out_wrapper("values", "indices") +def cummaxmin(self, dim): + values = torch.empty(self.shape, device=self.device, dtype=self.dtype) + indices = torch.empty(self.shape, device=self.device, dtype=torch.int64) + if self.numel() != 0 and self.ndim != 0: + # Checks that dim is within bounds + maybe_wrap_dim(dim, self.ndim) + return values, indices + + +@register_meta([aten.logcumsumexp.default, aten.logcumsumexp.out]) +@out_wrapper() +def logcumsumexp(self, dim): + # Checks that dim is within bounds + maybe_wrap_dim(dim, self.ndim) + return torch.empty_like(self, memory_format=torch.contiguous_format) + + +# Stride-related code from _exec_fft in aten/src/ATen/native/mkl/SpectralOps.cpp +# and aten/src/ATen/cuda/SpectralOps.cpp +# +# Although the actual FFT launch is different, all the permuting code appears +# to be the same +def _exec_fft(out, self, out_sizes, dim, *, forward): + ndim = self.ndim + signal_ndim = len(dim) + batch_dims = ndim - signal_ndim + + # Permute dimensions so batch dimensions come first, and in stride order + dim_permute = list(range(ndim)) + + is_transformed_dim = [False for _ in range(ndim)] + for d in dim: + is_transformed_dim[d] = True + + # std::partition + left, right = [], [] + for d in dim_permute: + if not is_transformed_dim[d]: + left.append(d) + else: + right.append(d) + dim_permute = left + right + batch_end = len(left) + + self_strides = self.stride() + tmp = dim_permute[:batch_end] + tmp.sort(key=lambda x: self_strides[x], reverse=True) + dim_permute = tmp + dim_permute[batch_end:] + input = self.permute(dim_permute) + + # Collapse batch dimensions into a single dimension + batched_sizes = [-1] + list(input.shape[batch_dims:]) + input = input.reshape(batched_sizes) + + batch_size = input.size(0) + batched_sizes[0] = batch_size + batched_out_sizes = list(batched_sizes) + for i in range(len(dim)): + batched_out_sizes[i + 1] = out_sizes[dim[i]] + out.resize_(batched_out_sizes, memory_format=torch.contiguous_format) + + # Inplace reshaping to original batch shape and inverting the dimension permutation + out_strides = [0 for _ in range(ndim)] + batch_numel = 1 + i = batch_dims - 1 + while i >= 0: + out_strides[dim_permute[i]] = batch_numel * out.stride(0) + batch_numel *= out_sizes[dim_permute[i]] + i -= 1 + for i in range(batch_dims, ndim): + out_strides[dim_permute[i]] = out.stride(1 + (i - batch_dims)) + out.as_strided_(out_sizes, out_strides, out.storage_offset()) + + return out + + +def _sort_dims(self: Tensor, dim: list[int], exclude_last: bool = False): + sorted_dims = list(dim) + self_strides = self.stride() + sorted_dims[: len(sorted_dims) - int(exclude_last)].sort( + key=lambda i: self_strides[i] + ) + return sorted_dims + + +# See _fft_c2c_cufft in aten/src/ATen/native/cuda/SpectralOps.cpp +# and _fft_c2c_mkl in aten/src/ATen/native/mkl/SpectralOps.cpp +@register_meta([aten._fft_c2c.default, aten._fft_c2c.out]) +@out_wrapper() +def meta_fft_c2c(self, dim, normalization, forward): + torch._check(self.dtype.is_complex) + if not dim: + return self.clone() + + sorted_dims = _sort_dims(self, dim) + out = self.new_empty(self.size()) + return _exec_fft(out, self, self.size(), sorted_dims, forward=forward) + + +cufft_max_ndim = 3 + + +def use_optimized_cufft_path(dim: list[int]): + if len(dim) > cufft_max_ndim or (len(dim) >= 2 and dim[0] == 0 and dim[1] == 1): + return False + else: + return True + + +@register_meta([aten._fft_r2c.default, aten._fft_r2c.out]) +@out_wrapper() +def meta_fft_r2c(self, dim, normalization, onesided): + torch._check(self.dtype.is_floating_point) + input_sizes = list(self.size()) + out_sizes = list(input_sizes) + last_dim = dim[-1] + last_dim_halfsize = input_sizes[last_dim] // 2 + 1 + onesided_sizes = list(input_sizes) + onesided_sizes[last_dim] = last_dim_halfsize + + if onesided: + out_sizes[last_dim] = last_dim_halfsize + + if device_hint(self) == "cuda" or device_hint(self) == "xpu": + # _fft_r2c_cufft in aten/src/ATen/native/cuda/SpectralOps.cpp + # _fft_r2c_xpu in torch-xpu-ops/src/ATen/native/xpu/SpectralOps.cpp + output = self.new_empty( + out_sizes, dtype=utils.corresponding_complex_dtype(self.dtype) + ) + + working_tensor = self + if device_hint(self) == "cuda" and use_optimized_cufft_path(dim): + _exec_fft(output, working_tensor, out_sizes, dim, forward=True) + else: + # First do the R2C transform on the last dimension + target_sizes = out_sizes if len(dim) == 1 else onesided_sizes + _exec_fft(output, working_tensor, target_sizes, [last_dim], forward=True) + if len(dim) > 1: + working_tensor = self.new_empty( + out_sizes, dtype=utils.corresponding_complex_dtype(self.dtype) + ) + + # Then any remaining C2C transforms + sorted_dims = dim[:-1] + while sorted_dims: + output, working_tensor = working_tensor, output + strides = working_tensor.stride() + sorted_dims.sort( + key=lambda i: strides[i], reverse=True + ) # NB reverse! Not sure if this is og bug + max_dims = min(cufft_max_ndim, len(sorted_dims)) + last_dims = sorted_dims[len(sorted_dims) - max_dims :] + _exec_fft( + output, working_tensor, onesided_sizes, last_dims, forward=True + ) + sorted_dims = sorted_dims[: len(sorted_dims) - max_dims] + + if not onesided: + if output.size(last_dim) != out_sizes[last_dim]: + working_tensor.resize_(out_sizes, memory_format=torch.contiguous_format) + output = working_tensor + + return output + + else: + return self.new_empty( + out_sizes, dtype=utils.corresponding_complex_dtype(self.dtype) + ) + + +@register_meta(aten.randperm.generator_out) +def meta_randperm(n, *, generator=None, out): + return _maybe_resize_out(out, torch.Size([n])) + + +@register_meta(aten.randperm.default) +def meta_randperm_default( + n, + *, + dtype=torch.long, + layout=None, + device=None, + pin_memory=None, +): + return torch.empty( + n, dtype=dtype, layout=layout, device=device, pin_memory=pin_memory + ) + + +@register_meta([aten.randint.default, aten.randint.out]) +@out_wrapper() +def meta_randint( + high, + size, + *, + dtype=torch.long, + layout=None, + device=None, + pin_memory=None, +): + low = 0 + torch._check( + high > low, + lambda: f"random_ expects 'from' to be less than 'to', but got from={low} >= to={high}", + ) + return torch.empty( + size, dtype=dtype, layout=layout, device=device, pin_memory=pin_memory + ) + + +@register_meta([aten.randint.low, aten.randint.low_out]) +@out_wrapper() +def meta_randint_low( + low, + high, + size, + *, + dtype=torch.long, + layout=None, + device=None, + pin_memory=None, +): + torch._check( + high > low, + lambda: f"random_ expects 'from' to be less than 'to', but got from={low} >= to={high}", + ) + return torch.empty( + size, dtype=dtype, layout=layout, device=device, pin_memory=pin_memory + ) + + +@register_meta([aten.rand.default, aten.rand.out]) +@out_wrapper() +def meta_rand_default(size, *, dtype=None, layout=None, device=None, pin_memory=None): + return torch.empty( + size, dtype=dtype, layout=layout, device=device, pin_memory=pin_memory + ) + + +@register_meta([aten._fft_c2r.default, aten._fft_c2r.out]) +@out_wrapper() +def meta_fft_c2r(self: Tensor, dim: list[int], normalization: int, lastdim: int): + # _fft_c2r_mkl + torch._check(self.dtype.is_complex) + + if device_hint(self) == "cuda": + out_sizes = list(self.size()) + out_sizes[dim[-1]] = lastdim + + output = self.new_empty(out_sizes, dtype=toRealValueType(self.dtype)) + + if use_optimized_cufft_path(dim): + return _exec_fft( + output, + self.clone(memory_format=torch.contiguous_format), + out_sizes, + dim, + forward=False, + ) + else: + # First complete any C2C transforms + if len(dim) > 1: + temp = meta_fft_c2c(self, dim[:-1], 0, lastdim) # fft_norm_mode::none + else: + temp = self.clone(memory_format=torch.contiguous_format) + return _exec_fft(output, temp, out_sizes, [dim[-1]], forward=False) + + else: + input = self + if len(dim) > 1: + c2c_dims = dim[:-1] + input = meta_fft_c2c(self, c2c_dims, normalization, forward=False) + dim = dim[-1:] + + out_sizes = list(input.size()) + out_sizes[dim[-1]] = lastdim + out = self.new_empty(out_sizes, dtype=toRealValueType(self.dtype)) + return _exec_fft(out, input, out_sizes, dim, forward=False) + + +@register_meta(aten.copy_.default) +def meta_copy_(self, src, non_blocking=False): + # This code simulates the original decomp from inductor, + # which runs most of the meta checks that we care about. + # In theory, we should make this more robust by carefully + # auditing our C++ copy_() kernel and copying the checks here. + from torch.fx.experimental.symbolic_shapes import free_unbacked_symbols + + # TODO: Ideally, we'd insert a deferred runtime assert here, but if we are + # calling an actual copy_, you'll get that automatically + # https://github.com/pytorch/pytorch/issues/122477 + if ( + not free_unbacked_symbols(self) and torch._debug_has_internal_overlap(self) == 1 + ): # 1 == MemOverlap::Yes + raise RuntimeError( + "more than one element of the written-to tensor refers to a single memory location" + ) + + if isinstance(src, Tensor): + intermediate = src.to(self, non_blocking) + if self.size() != intermediate.size(): + aten.expand_copy.default(intermediate, self.size()) + return self + + +def inferUnsqueezeGeometry(tensor, dim): + result_sizes = list(tensor.size()) + result_strides = list(tensor.stride()) + # pyrefly: ignore [unsupported-operation] + new_stride = 1 if dim >= tensor.dim() else result_sizes[dim] * result_strides[dim] + # pyrefly: ignore [bad-argument-type] + result_sizes.insert(dim, 1) + # pyrefly: ignore [bad-argument-type] + result_strides.insert(dim, new_stride) + return result_sizes, result_strides + + +@register_meta(aten.unsqueeze_.default) +def meta_unsqueeze_(self, dim): + dim = maybe_wrap_dim(dim, self.dim() + 1) + g_sizes, g_strides = inferUnsqueezeGeometry(self, dim) + self.as_strided_(g_sizes, g_strides) + return self + + +@register_meta(aten._sparse_semi_structured_linear) +def meta_sparse_structured_linear( + input: Tensor, + weight: Tensor, + _meta: Tensor, + bias: Tensor | None = None, + _activation_opt: str | None = None, + out_dtype: torch.dtype | None = None, +): + output_sizes = list(input.shape) + if bias is not None: + assert weight.size(0) == bias.size(0), "output size mismatch" + assert weight.size(1) == input.size(-1) / 2 + output_sizes[-1] = weight.size(0) + + # see: https://github.com/pytorch/pytorch/pull/114477#issuecomment-1830121375 + # We assume that we have already squashed the inputs into a 2-D tensor + # Then, as the output is transposed, we need to propagate the transposed + # stride information to the output tensor + assert len(input.shape) == 2, "we can only handle the squashed input case" + transposed_strides = (1, input.size(0)) + + if out_dtype is not None: + assert input.dtype == torch.int8 and out_dtype == torch.int32, ( + "out_dtype is only supported for i8i8->i32 linear operator" + ) + output = input.new_empty( + output_sizes, + dtype=input.dtype if out_dtype is None else out_dtype, + ).as_strided(output_sizes, transposed_strides) + + return output + + +@register_meta(aten._sparse_semi_structured_mm) +def meta_sparse_structured_mm( + mat1: Tensor, + mat1_meta: Tensor, + mat2: Tensor, + out_dtype: torch.dtype | None = None, +): + assert len(mat1.shape) == 2 + assert len(mat1_meta.shape) == 2 + assert len(mat2.shape) == 2 + assert mat1.size(1) == mat2.size(0) / 2 + output_sizes = [mat1.size(0), mat2.size(1)] + + if out_dtype is not None: + assert mat2.dtype == torch.int8 and out_dtype == torch.int32, ( + "out_dtype is only supported for i8i8->i32 linear operator" + ) + output = mat2.new_empty( + output_sizes, + dtype=mat2.dtype if out_dtype is None else out_dtype, + ) + + return output + + +@register_meta(aten._sparse_semi_structured_addmm) +def meta_sparse_structured_addmm( + input: Tensor, + mat1: Tensor, + mat1_meta: Tensor, + mat2: Tensor, + *, + alpha=1, + beta=1, + out_dtype: torch.dtype | None = None, +): + assert len(input.shape) == 1, ( + "only input broadcasted to columns of mat1 * mat2 product is supported" + ) + assert len(mat1.shape) == 2 + assert len(mat1_meta.shape) == 2 + assert len(mat2.shape) == 2 + assert input.size(0) == mat1.size(0), ( + "only input broadcasted to columns of mat1 * mat2 product is supported" + ) + assert mat1.size(1) == mat2.size(0) / 2 + output_sizes = [mat1.size(0), mat2.size(1)] + + if out_dtype is not None: + assert mat2.dtype == torch.int8 and out_dtype == torch.int32, ( + "out_dtype is only supported for i8i8->i32 linear operator" + ) + output = mat2.new_empty( + output_sizes, + dtype=mat2.dtype if out_dtype is None else out_dtype, + ) + + return output + + +@register_meta(aten._cslt_sparse_mm) +def meta__cslt_sparse_mm( + compressed_A: torch.Tensor, + dense_B: torch.Tensor, + bias: Tensor | None = None, + alpha: Tensor | None = None, + out_dtype: torch.dtype | None = None, + transpose_result: bool = False, + alg_id: int = 0, + split_k: int = 1, + split_k_mode: int = -1, +): + assert dense_B.dtype in { + torch.float32, + torch.float16, + torch.bfloat16, + torch.int8, + torch.float8_e4m3fn, + }, "_cslt_sparse_mm only supports fp16, bf16, int8, and fp8e4m3" + assert compressed_A.dtype == dense_B.dtype, "inputs must have the same dtype" + assert len(dense_B.shape) == 2, "_cslt_sparse_mm only supports 2d inputs" + + is_8bit_input_type = compressed_A.dtype in [torch.int8, torch.float8_e4m3fn] + + if is_8bit_input_type: + assert not dense_B.is_contiguous(), ( + "dense input must be transposed for 8bit dtypes" + ) + + n = dense_B.size(1) + m = compressed_A.size(0) + if bias is not None: + assert m == bias.size(0) + + if out_dtype is not None: + assert is_8bit_input_type and out_dtype in { + torch.float16, + torch.bfloat16, + torch.int32, + torch.float8_e4m3fn, + }, ( + f"out_dtype is not supported for {compressed_A.dtype} x {dense_B.dtype} -> {out_dtype} matmul!" + ) + output_shape = (n, m) if transpose_result else (m, n) + return dense_B.new_empty(output_shape, dtype=out_dtype) + + +@register_meta(aten.index_reduce.default) +def meta_index_reduce( + self: Tensor, + dim: int, + index: Tensor, + source: torch.Tensor, + reduce: str, + *, + include_self: bool = True, +) -> Tensor: + return torch.empty_like(self, memory_format=torch.contiguous_format) + + +@register_meta(aten.index_reduce_.default) +def meta_index_reduce_( + self: Tensor, + dim: int, + index: Tensor, + source: torch.Tensor, + reduce: str, + *, + include_self: bool = True, +) -> Tensor: + return self + + +# Implementations below are taken from https://github.com/albanD/subclass_zoo/blob/main/python_meta_tensor.py +@out_wrapper() +@register_meta(aten.index_select.default) +def meta_index_select(self, dim, index): + result_size = list(self.size()) + if self.dim() > 0: + result_size[dim] = index.numel() + return self.new_empty(result_size) + + +@register_meta(aten.segment_reduce.default) +def meta_segment_reduce( + data: Tensor, + reduce: str, + *, + lengths: Tensor | None = None, + indices: Tensor | None = None, + offsets: Tensor | None = None, + axis: int = 0, + unsafe: bool = False, + initial=None, +) -> Tensor: + if indices is not None: + raise NotImplementedError( + "segment_reduce(): indices based reduction is not supported yet." + ) + + def segment_reduce_lengths_tensor(lengths_shape): + return torch.empty( + lengths_shape + data.shape[axis + 1 :], + dtype=data.dtype, + device="meta", + memory_format=torch.contiguous_format, + ) + + if lengths is not None: + return segment_reduce_lengths_tensor(lengths.shape) + # FIXME should probably check that lengths and offset aren't both set, but + # the ATen implementation neglects this too + if offsets is not None: + # lengths == torch.diff(offsets) + lengths_shape = offsets.shape[:-1] + (offsets.shape[-1] - 1,) + return segment_reduce_lengths_tensor(lengths_shape) + raise RuntimeError("segment_reduce(): Either lengths or offsets must be defined.") + + +@register_meta([aten.max.default, aten.max.unary_out]) +@out_wrapper() +def meta_max(self): + return self.new_empty(()) + + +@register_meta(aten.max.dim) +def meta_max_dim(self, dim, keepdim=False): + dim = utils.reduction_dims(self.shape, (dim,)) + output_shape = _compute_reduction_shape(self, dim, keepdim) + return ( + self.new_empty(output_shape), + self.new_empty(output_shape, dtype=torch.long), + ) + + +@register_meta([aten.min.default, aten.min.unary_out]) +@out_wrapper() +def meta_min(self): + return self.new_empty(()) + + +@register_meta(aten.min.dim) +def meta_min_dim(self, dim, keepdim=False): + dim = utils.reduction_dims(self.shape, (dim,)) + output_shape = _compute_reduction_shape(self, dim, keepdim) + return ( + self.new_empty(output_shape), + self.new_empty(output_shape, dtype=torch.long), + ) + + +@register_meta(aten.angle.default) +def meta_angle(self): + if self.is_complex(): + result_dtype = corresponding_real_dtype(self.dtype) + else: + _, result_dtype = elementwise_dtypes( + self, + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + ) + return torch.empty_like(self, dtype=result_dtype) + + +@register_meta(aten.angle.out) +def meta_angle_out(self, out): + torch._resize_output_(out, self.size(), self.device) + return out.copy_(torch.angle(self)) + + +@register_meta(aten._assert_async.default) +def assert_async(val): + return + + +@register_meta(aten._assert_async.msg) +def assert_async_meta(val, assert_msg): + return + + +@register_meta(aten._print.default) +def print_meta(s): + return + + +@register_meta(aten._make_dep_token.default) +def make_dep_token( + *, + dtype=None, + layout=None, + device=None, + pin_memory=None, + memory_format=None, +): + return torch.empty(0, device="meta") + + +@register_meta(aten.sym_constrain_range.default) +def sym_constrain_range(size, min=None, max=None): + # Avoid importing sympy at a module level + from torch.fx.experimental.symbolic_shapes import constrain_range + + if isinstance(size, (SymFloat, SymBool)): + raise ValueError("Constraining SymFloat or Symbool is nyi") + constrain_range(size, min=min, max=max) + + +@register_meta(aten._functional_sym_constrain_range.default) +def functional_sym_constrain_range(size, min=None, max=None, dep_token=None): + aten.sym_constrain_range(size, min=min, max=max) + return dep_token + + +@register_meta(aten.sym_constrain_range_for_size.default) +def sym_constrain_range_for_size(size, min=None, max=None): + # Avoid importing sympy at a module level + from torch.fx.experimental.symbolic_shapes import _constrain_range_for_size + + if min is None and max is None: + torch._check(size >= 0) + return + + if isinstance(size, (SymFloat, SymBool)): + raise ValueError("Constraining SymFloat or Symbool is nyi") + if type(size) is int: + if min is not None: + torch._check(size >= min) + if max is not None: + torch._check(size <= max) + return + _constrain_range_for_size(size, min=min, max=max) + + +@register_meta(aten._functional_sym_constrain_range_for_size.default) +def functional_sym_constrain_range_for_size(size, min, max, dep_token): + aten.sym_constrain_range_for_size(size, min=min, max=max) + return dep_token + + +@register_meta(aten._functional_assert_async.msg) +def functional_assert_async_meta(val, assert_msg, dep_token): + return dep_token + + +# From aten/src/ATen/native/LinearAlgebraUtils.h +def squareCheckInputs(self: Tensor, f_name: str): + assert self.dim() >= 2, ( + f"{f_name}: The input tensor must have at least 2 dimensions." + ) + assert self.size(-1) == self.size(-2), ( + f"{f_name}: A must be batches of square matrices, but they are {self.size(-2)} by {self.size(-1)} matrices" + ) + + +# Validates input shapes and devices +# for linear solve methods (solve, cholesky_solve, lu_solve, triangular_solve) +# From aten/src/ATen/native/LinearAlgebraUtils.h +def linearSolveCheckInputs(self: Tensor, A: Tensor, name: str): + torch._check( + self.device == A.device, + lambda: ( + f"Expected b and A to be on the same device, but found b on " + f"{self.device} and A on {A.device} instead." + ), + ) + + torch._check( + self.dtype == A.dtype, + lambda: ( + f"Expected b and A to have the same dtype, but found b of type " + f"{self.dtype} and A of type {A.dtype} instead." + ), + ) + + torch._check( + A.size(-1) == A.size(-2), + lambda: ( + f"A must be batches of square matrices, " + f"but they are {A.size(-2)} by {A.size(-1)} matrices" + ), + ) + + torch._check( + A.size(-1) == self.size(-2), + lambda: ( + f"Incompatible matrix sizes for {name}: each A " + f"matrix is {A.size(-1)} by {A.size(-1)}" + f" but each b matrix is {self.size(-2)} by {self.size(-1)}" + ), + ) + + +# From aten/src/ATen/native/LinearAlgebraUtils.h +def checkFloatingOrComplex( + t: Tensor, + f_name: str, + allow_low_precision_dtypes: bool = True, +): + dtype = t.dtype + torch._check( + t.is_floating_point() or t.is_complex(), + lambda: f"{f_name}: Expected a floating point or complex tensor as input. Got {dtype}", + ) + if not allow_low_precision_dtypes: + torch._check( + dtype in (torch.float, torch.double, torch.cfloat, torch.cdouble), + lambda: f"{f_name}: Low precision dtypes not supported. Got {dtype}", + ) + + +# From aten/src/ATen/native/LinearAlgebraUtils.h +def checkIsMatrix(A: Tensor, f_name: str, arg_name: str = "A"): + torch._check( + A.dim() >= 2, + lambda: f"{f_name}: The input tensor {arg_name} must have at least 2 dimensions.", + ) + + +def checkInputsSolver(A: Tensor, B: Tensor, left: bool, f_name: str): + squareCheckInputs(A, f_name) + checkIsMatrix(B, f_name) + torch._check( + A.size(-2) == B.size(-2) if left else A.size(-1) == B.size(-1), + lambda: ( + f"{f_name}: Incompatible shapes of A and B for the equation " + f"{'AX = B' if left else 'XA = B'}" + f" ({A.size(-2)}x{A.size(-1)} and {B.size(-2)}x{B.size(-1)})" + ), + ) + + +def checkSameDevice( + fn_name: str, + result: Tensor, + input: Tensor, + result_name: str = "result", +): + torch._check( + result.device == input.device, + lambda: ( + f"{fn_name}: Expected {result_name} and input tensors to be on the same device, but got " + f"{result_name} on {result.device} and input on {input.device}" + ), + ) + + +def checkUplo(UPLO: str): + UPLO_uppercase = UPLO.upper() + torch._check( + len(UPLO) == 1 and (UPLO_uppercase == "U" or UPLO_uppercase == "L"), + lambda: f"Expected UPLO argument to be 'L' or 'U', but got {UPLO}", + ) + + +@register_meta([aten._linalg_eigh.default, aten._linalg_eigh.eigenvalues]) +@out_wrapper("eigenvalues", "eigenvectors") +def meta__linalg_eigh(A: Tensor, UPLO: str = "L", compute_v: bool = True): + squareCheckInputs(A, "linalg.eigh") + checkUplo(UPLO) + + shape = list(A.shape) + if compute_v: + vecs = A.new_empty(shape) + vecs.as_strided_(shape, make_contiguous_strides_for(shape, row_major=False)) + else: + vecs = A.new_empty([0]) + + shape.pop() + vals = A.new_empty(shape, dtype=toRealValueType(A.dtype)) + + return vals, vecs + + +@register_meta([aten._linalg_eigvals.default, aten.linalg_eigvals.out]) +@out_wrapper() +def meta__linalg_eigvals(input: Tensor) -> Tensor: + squareCheckInputs(input, "linalg.eigvals") + complex_dtype = ( + input.dtype + if utils.is_complex_dtype(input.dtype) + else utils.corresponding_complex_dtype(input.dtype) + ) + return input.new_empty(input.shape[:-1], dtype=complex_dtype) + + +@register_meta([aten.linalg_eig]) +@out_wrapper("eigenvalues", "eigenvectors") +def meta_linalg_eig(input: Tensor): + squareCheckInputs(input, "linalg.eig") + complex_dtype = ( + input.dtype + if utils.is_complex_dtype(input.dtype) + else utils.corresponding_complex_dtype(input.dtype) + ) + values = input.new_empty(input.shape[:-1], dtype=complex_dtype) + vectors = input.new_empty(input.shape, dtype=complex_dtype) + is_cuda = device_hint(input) == "cuda" + vectors.as_strided_( + input.shape, make_contiguous_strides_for(input.shape, row_major=is_cuda) + ) + return values, vectors + + +def cloneBatchedColumnMajor(src: Tensor) -> Tensor: + return src.mT.clone(memory_format=torch.contiguous_format).transpose(-2, -1) + + +@register_meta(aten._cholesky_solve_helper) +@out_wrapper() +def _cholesky_solve_helper(self: Tensor, A: Tensor, upper: bool) -> Tensor: + return cloneBatchedColumnMajor(self) + + +@register_meta(aten.cholesky_solve) +@out_wrapper() +def cholesky_solve(self: Tensor, A: Tensor, upper: bool = False) -> Tensor: + torch._check( + self.ndim >= 2, + lambda: f"b should have at least 2 dimensions, but has {self.ndim} dimensions instead", + ) + torch._check( + A.ndim >= 2, + lambda: f"u should have at least 2 dimensions, but has {A.ndim} dimensions instead", + ) + self_broadcasted, A_broadcasted = _linalg_broadcast_batch_dims_name( + self, A, "cholesky_solve" + ) + return _cholesky_solve_helper(self_broadcasted, A_broadcasted, upper) + + +@register_meta(aten.cholesky) +@out_wrapper() +def cholesky(self: Tensor, upper: bool = False) -> Tensor: + if self.numel() == 0: + return torch.empty_like(self, memory_format=torch.legacy_contiguous_format) + squareCheckInputs(self, "cholesky") + return cloneBatchedColumnMajor(self) + + +@register_meta(aten.cholesky_inverse) +@out_wrapper() +def cholesky_inverse(self: Tensor, upper: bool = False) -> Tensor: + squareCheckInputs(self, "cholesky_inverse") + return cloneBatchedColumnMajor(self) + + +# From aten/src/ATen/native/BatchLinearAlgebra.cpp +@register_meta(aten.linalg_cholesky_ex.default) +def linalg_cholesky_ex(A: Tensor, upper: bool = False, check_errors: bool = False): + squareCheckInputs(A, "linalg.cholesky") + checkFloatingOrComplex(A, "linalg.cholesky") + + A_shape = A.shape + ndim = len(A_shape) + + # L + L_strides = make_contiguous_strides_for(A_shape, False) + L = A.new_empty(A_shape) + L.as_strided_(A_shape, L_strides) + + # infos + infos = A.new_empty(A_shape[0 : ndim - 2], dtype=torch.int32) + return L, infos + + +@register_meta( + [aten.linalg_householder_product.default, aten.linalg_householder_product.out] +) +@out_wrapper() +def linalg_householder_product(input: Tensor, tau: Tensor) -> Tensor: + torch._check( + input.ndim >= 2, + lambda: "torch.linalg.householder_product: input must have at least 2 dimensions.", + ) + torch._check( + input.size(-2) >= input.size(-1), + lambda: "torch.linalg.householder_product: input.shape[-2] must be greater than or equal to input.shape[-1]", + ) + torch._check( + input.size(-1) >= tau.size(-1), + lambda: "torch.linalg.householder_product: input.shape[-1] must be greater than or equal to tau.shape[-1]", + ) + + torch._check( + input.ndim - tau.ndim == 1, + lambda: ( + f"torch.linalg.householder_product: Expected tau to have one dimension less than input, " + f"but got tau.ndim equal to {tau.ndim} and input.ndim is equal to {input.ndim}" + ), + ) + if input.ndim > 2: + expected_batch_tau_shape = input.shape[:-2] + actual_batch_tau_shape = tau.shape[:-1] + torch._check( + actual_batch_tau_shape == expected_batch_tau_shape, + lambda: ( + f"torch.linalg.householder_product: Expected batch dimensions of tau to be " + f"equal to input.shape[:-2], but got {actual_batch_tau_shape}" + ), + ) + + torch._check( + tau.dtype == input.dtype, + lambda: ( + f"torch.linalg.householder_product: tau dtype {tau.dtype}" + f" does not match input dtype {input.dtype}" + ), + ) + checkSameDevice("torch.linalg.householder_product", tau, input, "tau") + + return torch.empty_strided( + size=input.shape, + stride=make_contiguous_strides_for(input.shape, row_major=False), + dtype=input.dtype, + device=input.device, + ) + + +# From aten/src/ATen/native/BatchLinearAlgebra.cpp +@register_meta(aten.linalg_inv_ex.default) +def linalg_inv_ex_meta(A: Tensor, check_errors: bool = False): + squareCheckInputs(A, "linalg.inv_ex") + checkFloatingOrComplex(A, "linalg.inv_ex", allow_low_precision_dtypes=False) + + L = A.new_empty(A.shape) + L.as_strided_(A.shape, make_contiguous_strides_for(A.shape, row_major=False)) + + infos = A.new_empty(A.shape[:-2], dtype=torch.int32) + return L, infos + + +@register_meta([aten.linalg_ldl_factor_ex.default, aten.linalg_ldl_factor_ex.out]) +@out_wrapper("LD", "pivots", "info") +def linalg_ldl_factor_ex_meta( + self: Tensor, + *, + hermitian: bool = False, + check_errors: bool = False, +) -> tuple[Tensor, Tensor, Tensor]: + squareCheckInputs(self, "torch.linalg.ldl_factor_ex") + checkFloatingOrComplex(self, "torch.linalg.ldl_factor_ex") + LD = torch.empty_strided( + size=self.shape, + stride=make_contiguous_strides_for(self.shape, row_major=False), + dtype=self.dtype, + device=self.device, + ) + pivots = self.new_empty(self.shape[:-1], dtype=torch.int) + info = self.new_empty(self.shape[:-2], dtype=torch.int) + return LD, pivots, info + + +@register_meta([aten.linalg_ldl_solve.default, aten.linalg_ldl_solve.out]) +@out_wrapper() +def linalg_ldl_solve_meta( + LD: Tensor, + pivots: Tensor, + B: Tensor, + *, + hermitian: bool = False, +) -> Tensor: + squareCheckInputs(LD, "torch.linalg.ldl_solve") + checkFloatingOrComplex(LD, "torch.linalg.ldl_solve") + linearSolveCheckInputs(B, LD, "torch.linalg.ldl_solve") + torch._check( + B.ndim >= 2, + lambda: ( + f"torch.linalg.ldl_solve: Expected B to have at least 2 dimensions, " + f"but it has {B.ndim} dimensions instead" + ), + ) + expected_pivots_shape = LD.shape[:-1] + torch._check( + expected_pivots_shape == pivots.shape, + lambda: ( + f"torch.linalg.ldl_solve: Expected LD.shape[:-1] and pivots.shape to be the same, " + f"but got pivots with shape {pivots.shape} instead" + ), + ) + torch._check( + utils.is_integer_dtype(pivots.dtype), + lambda: f"torch.linalg.ldl_solve: Expected pivots to be integers. Got {pivots.dtype}", + ) + torch._check( + LD.dtype == B.dtype, + lambda: f"torch.linalg.ldl_solve: LD dtype {LD.dtype} does not match b dtype {B.dtype}", + ) + B_broadcast_size, _ = _linalg_broadcast_batch_dims(B, LD) + return torch.empty_strided( + size=B_broadcast_size, + stride=make_contiguous_strides_for(B_broadcast_size, row_major=False), + dtype=B.dtype, + device=B.device, + ) + + +@register_meta([aten.linalg_lu.default, aten.linalg_lu.out]) +@out_wrapper("P", "L", "U") +def linalg_lu_meta(A: Tensor, *, pivot: bool = True) -> tuple[Tensor, Tensor, Tensor]: + torch._check( + A.ndim >= 2, + lambda: f"linalg.lu: Expected tensor with 2 or more dimensions. Got size: {A.shape} instead", + ) + + sizes = list(A.shape) + m = sizes[-2] + n = sizes[-1] + k = min(m, n) + + sizes[-1] = m + if pivot: + P = A.new_empty(sizes) + else: + P = A.new_empty([0]) + + sizes[-1] = k + L = A.new_empty(sizes) + + sizes[-2] = k + sizes[-1] = n + U = A.new_empty(sizes) + return P, L, U + + +@register_meta([aten.linalg_lu_factor_ex.default, aten.linalg_lu_factor_ex.out]) +@out_wrapper("LU", "pivots", "info") +def linalg_lu_factor_ex_meta( + A: Tensor, + *, + pivot: bool = True, + check_errors: bool = False, +) -> tuple[Tensor, Tensor, Tensor]: + torch._check( + A.ndim >= 2, + lambda: f"torch.lu_factor: Expected tensor with 2 or more dimensions. Got size: {A.shape} instead", + ) + + sizes = list(A.shape) + m = sizes[-2] + n = sizes[-1] + + LU = torch.empty_strided( + size=sizes, + stride=make_contiguous_strides_for(sizes, row_major=False), + dtype=A.dtype, + device=A.device, + ) + + # Sets sizes to the size of pivots + sizes.pop() + sizes[-1] = min(m, n) + pivots = A.new_empty(sizes, dtype=torch.int) + + # Sets sizes to the size of info + sizes.pop() + info = A.new_empty(sizes, dtype=torch.int) + + return LU, pivots, info + + +@register_meta([aten.linalg_lu_solve.default, aten.linalg_lu_solve.out]) +@out_wrapper() +def linalg_lu_solve_meta( + LU: Tensor, + pivots: Tensor, + B: Tensor, + *, + left: bool = True, + adjoint: bool = False, +) -> Tensor: + # dtype + checkFloatingOrComplex(LU, "torch.linalg.lu_solve") + torch._check( + LU.dtype == B.dtype, + lambda: ( + f"linalg.lu_solve: Expected LU and B to have the same dtype, " + f"but found LU of type {LU.dtype} and B of type {B.dtype} instead" + ), + ) + torch._check( + pivots.dtype == torch.int, + lambda: "linalg.lu_solve: pivots should be a Tensor of scalar type torch.int32", + ) + + # matrix shapes + squareCheckInputs(LU, "torch.linalg.lu_solve") + checkInputsSolver(LU, B, left, "linalg.lu_solve") + torch._check( + LU.size(-1) == pivots.size(-1), + lambda: "linalg.lu_solve: Number of pivots per batch should be same as the dimension of the matrix", + ) + + # batches + torch._check( + LU.shape[:-1] == pivots.shape, + lambda: ( + f"linalg.lu_solve: Expected LU.shape[:-1] and pivots.shape to be the same, " + f"but got pivots with shape {pivots.shape} instead" + ), + ) + + B_broadcast_size, _ = _linalg_broadcast_batch_dims(B, LU) + + result = torch.empty_strided( + size=B_broadcast_size, + stride=make_contiguous_strides_for(B_broadcast_size, row_major=not left), + dtype=B.dtype, + device=B.device, + ) + + if result.numel() != 0 and not left: + if result.is_complex(): + result = result.conj() + + return result + + +@register_meta(aten.lu_unpack) +@out_wrapper("P", "L", "U") +def lu_unpack_meta( + LU: Tensor, + pivots: Tensor, + unpack_data: bool = True, + unpack_pivots: bool = True, +) -> tuple[Tensor, Tensor, Tensor]: + torch._check( + LU.ndim >= 2, + lambda: f"torch.lu_unpack: Expected tensor with 2 or more dimensions. Got size: {LU.shape} instead", + ) + if unpack_pivots: + torch._check( + pivots.dtype == torch.int32, + lambda: ( + "torch.lu_unpack: LU_pivots is expected to be a contiguous tensor of torch.int32 dtype.\n" + "Note: this function is intended to be used with the output produced by torch.linalg.lu_factor" + ), + ) + sizes = list(LU.shape) + m = sizes[-2] + n = sizes[-1] + k = min(m, n) + sizes[-1] = m + if unpack_pivots: + P = LU.new_empty(sizes) + else: + P = LU.new_empty([0]) + if unpack_data: + sizes[-1] = k + L = LU.new_empty(sizes) + sizes[-2] = k + sizes[-1] = n + U = LU.new_empty(sizes) + else: + L = LU.new_empty([0]) + U = LU.new_empty([0]) + return P, L, U + + +# parse the "mode" param in linalg_qr: return a tuple of bools (compute_q, reduced) +def _parse_qr_mode(mode: str) -> tuple[bool, bool]: + if mode == "reduced": + compute_q = True + reduced = True + elif mode == "complete": + compute_q = True + reduced = False + elif mode == "r": + compute_q = False + reduced = True # this is actually irrelevant in this mode + else: + torch._check( + False, + lambda: ( + f"qr received unrecognized mode '{mode}' " + f"but expected one of 'reduced' (default), 'r', or 'complete'" + ), + ) + return compute_q, reduced # type: ignore[possibly-undefined] + + +@register_meta([aten.linalg_qr.default, aten.linalg_qr.out]) +@out_wrapper("Q", "R") +def linalg_qr_meta(A: Tensor, mode: str = "reduced") -> tuple[Tensor, Tensor]: + checkIsMatrix(A, "linalg.qr") + checkFloatingOrComplex(A, "linalg.qr") + + compute_q, reduced_mode = _parse_qr_mode(mode) + + m = A.shape[-2] + n = A.shape[-1] + k = min(m, n) + + if compute_q: + Q_shape = list(A.shape) + Q_shape[-1] = k if reduced_mode else m + Q = A.new_empty(Q_shape) + Q.as_strided_(Q_shape, make_contiguous_strides_for(Q_shape, row_major=False)) + else: + Q = A.new_empty([0]) + + # For readability + R_shape = list(A.shape) + R_shape[-2] = k if reduced_mode or not compute_q else m + R = A.new_empty(R_shape) + R.as_strided_(R_shape, make_contiguous_strides_for(R_shape, row_major=False)) + return Q, R + + +@register_meta([aten._linalg_slogdet.default, aten._linalg_slogdet.sign]) +@out_wrapper("sign", "logabsdet", "LU", "pivots") +def _linalg_slogdet(A: Tensor) -> tuple[Tensor, Tensor, Tensor, Tensor]: + squareCheckInputs(A, "linalg.slogdet") + checkFloatingOrComplex(A, "linalg.slogdet", False) + shape = A.shape + sign = A.new_empty(shape[:-2]) + logabsdet = A.new_empty(shape[:-2], dtype=toRealValueType(A.dtype)) + LU = torch.empty_strided( + size=shape, + stride=make_contiguous_strides_for(shape, False), + dtype=A.dtype, + device=A.device, + ) + pivots = A.new_empty(shape[:-1], dtype=torch.int32) + return sign, logabsdet, LU, pivots + + +# From aten/src/ATen/native/BatchLinearAlgebra.cpp +# NOTE: matching defaults in aten/src/ATen/native/native_functions.yaml +@register_meta(aten._linalg_svd.default) +def _linalg_svd_meta( + A: Tensor, + full_matrices: bool = False, + compute_uv: bool = True, + driver: str | None = None, +): + checkIsMatrix(A, "linalg.svd") + checkFloatingOrComplex(A, "linalg.svd") + + batch_dims = list(A.shape[:-2]) + m = A.shape[-2] + n = A.shape[-1] + k = min(m, n) + + if compute_uv: + U_shape = batch_dims + [m, m if full_matrices else k] + U = A.new_empty(U_shape) + U.as_strided_(U_shape, make_contiguous_strides_for(U_shape, row_major=False)) + + V_shape = batch_dims + [n if full_matrices else k, n] + V = A.new_empty(V_shape) + # NB: This checks for CUDA since there is no way to check for cuSolver. + # Also, this might not work correctly on CPU when fake_device is not + # available as device_hint just defaults to CUDA in that case. See + # _linalg_svd meta in core. + is_cuda = device_hint(A) == "cuda" + V.as_strided_(V_shape, make_contiguous_strides_for(V_shape, row_major=is_cuda)) + else: + # doesn't matter + U = A.new_empty([0]) + V = A.new_empty([0]) + + # S is always real, even when A is complex. + S = A.new_empty(batch_dims + [k], dtype=toRealValueType(A.dtype)) + return U, S, V + + +def _linalg_broadcast_batch_dims( + arg1: Tensor, + arg2: Tensor, +) -> tuple[list[int], list[int]]: + # broadcast the batch dimensions of arg1 and arg2. + arg1_batch_sizes = arg1.shape[:-2] + arg2_batch_sizes = arg2.shape[:-2] + expand_batch_portion = _broadcast_shapes(arg1_batch_sizes, arg2_batch_sizes) + + arg1_expand_size = list(expand_batch_portion) + arg1_expand_size += [arg1.size(-2), arg1.size(-1)] + + arg2_expand_size = list(expand_batch_portion) + arg2_expand_size += [arg2.size(-2), arg2.size(-1)] + return arg1_expand_size, arg2_expand_size + + +def _linalg_broadcast_batch_dims_name( + arg1: Tensor, + arg2: Tensor, + name: str | None, +) -> tuple[Tensor, Tensor]: + # If there's no name we assume we don't want to check the errors + if name: + linearSolveCheckInputs(arg1, arg2, name) + + arg1_expand_size, arg2_expand_size = _linalg_broadcast_batch_dims(arg1, arg2) + + arg1_broadcasted = ( + arg1 if arg1_expand_size == arg1.shape else arg1.expand(arg1_expand_size) + ) + arg2_broadcasted = ( + arg2 if arg2_expand_size == arg2.shape else arg2.expand(arg2_expand_size) + ) + return arg1_broadcasted, arg2_broadcasted + + +def linalg_solve_is_vector_rhs(input: Tensor, other: Tensor) -> bool: + expected_batched_rhs_shape = input.shape[:-1] + vector_case = other.ndim == 1 or ( + input.ndim - 1 == other.ndim and other.shape == expected_batched_rhs_shape + ) + return vector_case + + +@register_meta(aten._linalg_solve_ex) +def _linalg_solve_ex( + A: Tensor, + B: Tensor, + *, + left: bool = True, + check_errors: bool = False, + result: Tensor | None = None, + LU: Tensor | None = None, + pivots: Tensor | None = None, + info: Tensor | None = None, +) -> tuple[Tensor, Tensor, Tensor, Tensor]: + checkFloatingOrComplex(A, "linalg.solve") + torch._check( + A.dtype == B.dtype, + lambda: ( + f"linalg.solve: Expected A and B to have the same dtype, but found A of type " + f"{A.dtype} and B of type {B.dtype} instead" + ), + ) + vector_case = linalg_solve_is_vector_rhs(A, B) + B_ = B.unsqueeze(-1) if vector_case else B + checkInputsSolver(A, B_, left, "linalg.solve") + B_broad_shape, _ = _linalg_broadcast_batch_dims(B_, A) + torch._check( + left or not vector_case, + lambda: ( + "linalg.solve: Vector broadcasting of the left hand side is not supported for left=False. " + "In this case linalg.solve is equivalent to B / A.squeeze(-1)" + ), + ) + result_shape = B_broad_shape[:-1] if vector_case else B_broad_shape + result_ = torch.empty_strided( + size=result_shape, + stride=make_contiguous_strides_for(result_shape, not left), + dtype=B.dtype, + device=B.device, + ) + shape = A.shape + LU_ = torch.empty_strided( + size=shape, + stride=make_contiguous_strides_for(shape, False), + dtype=A.dtype, + device=A.device, + ) + pivots_ = A.new_empty(shape[:-1], dtype=torch.int32) + info_ = A.new_empty(shape[:-2], dtype=torch.int32) + out = (result, LU, pivots, info) + res = (result_, LU_, pivots_, info_) + if all(x is not None for x in out): + for r, o in zip(res, out): + # resize and copy operations are done in-place + _maybe_resize_out(o, r.shape) # type: ignore[arg-type] + # strides are not copied in out_wrapper + o.as_strided_(r.shape, r.stride()) # type: ignore[union-attr] + _safe_copy_out(copy_from=r, copy_to=o, exact_dtype=False) # type: ignore[arg-type] + return res + + +@register_meta([aten.linalg_solve_triangular.default, aten.linalg_solve_triangular.out]) +def linalg_solve_triangular_meta( + A: Tensor, + B: Tensor, + *, + upper: bool, + left: bool = True, + unitriangular: bool = False, + out: Tensor | None = None, +) -> Tensor: + if out is None: + out = A.new_empty([0]) + assert isinstance(out, TensorLike) + checkInputsSolver(A, B, left, "linalg.solve_triangular") + B_, A_ = _linalg_broadcast_batch_dims_name(B, A, None) + avoid_copy_A = A_.transpose(-2, -1).is_contiguous() and A_.is_conj() + if avoid_copy_A: + out = _maybe_resize_out(out, B_.shape) + else: + # reimplementation of resize_output with result F-contig + if _resize_output_check(out, B_.shape): + out.resize_(B_.transpose(-2, -1).shape) + out.transpose_(-2, -1) + return out # type: ignore[return-value] + + +@register_meta(aten.triangular_solve) +@out_wrapper("X", "M", exact_dtype=True) +def triangular_solve_meta( + self: Tensor, + A: Tensor, + upper: bool = True, + transpose: bool = False, + unitriangular: bool = False, +) -> tuple[Tensor, Tensor]: + torch._check( + self.ndim >= 2, + lambda: ( + f"torch.triangular_solve: Expected b to have at least 2 dimensions, " + f"but it has {self.ndim} dimensions instead" + ), + ) + torch._check( + A.ndim >= 2, + lambda: ( + f"torch.triangular_solve: Expected A to have at least 2 dimensions, " + f"but it has {A.ndim} dimensions instead" + ), + ) + + linearSolveCheckInputs(self, A, "triangular_solve") + + if A.layout == torch.strided: + self_broadcast_size, A_broadcast_size = _linalg_broadcast_batch_dims(self, A) + solution = torch.empty_strided( + size=self_broadcast_size, + stride=make_contiguous_strides_for(self_broadcast_size, row_major=False), + dtype=self.dtype, + device=self.device, + ) + cloned_coefficient = torch.empty_strided( + size=A_broadcast_size, + stride=make_contiguous_strides_for(A_broadcast_size, row_major=False), + dtype=A.dtype, + device=A.device, + ) + elif A.layout == torch.sparse_csr or A.layout == torch.sparse_bsr: + solution = torch.empty_like(self) + cloned_coefficient = self.new_empty([0]) + else: + torch._check(False, lambda: "triangular_solve: Got an unexpected layout.") + return solution, cloned_coefficient # type: ignore[possibly-undefined] + + +# From aten/src/ATen/native/LinearAlgebra.cpp +@register_meta(aten._linalg_det.default) +def _linalg_det_meta(A): + squareCheckInputs(A, "linalg.det") + checkFloatingOrComplex(A, "linalg.det") + + det = A.new_empty(A.shape[:-2]) + + LU = A.new_empty(A.shape) + LU.as_strided_(A.shape, make_contiguous_strides_for(A.shape, row_major=False)) + + pivots = A.new_empty(A.shape[:-1], dtype=torch.int32) + return det, LU, pivots + + +@register_meta(aten.ormqr) +@out_wrapper() +def ormqr( + input: Tensor, + tau: Tensor, + other: Tensor, + left: bool = True, + transpose: bool = False, +) -> Tensor: + torch._check( + input.ndim >= 2, lambda: "torch.ormqr: input must have at least 2 dimensions." + ) + torch._check( + other.ndim >= 2, lambda: "torch.ormqr: other must have at least 2 dimensions." + ) + + left_size_condition = -2 if left else -1 + torch._check( + other.shape[left_size_condition] >= tau.shape[-1], + lambda: f"torch.ormqr: other.shape[{left_size_condition}] must be greater than or equal to tau.shape[-1]", + ) + torch._check( + other.shape[left_size_condition] == input.shape[-2], + lambda: f"torch.ormqr: other.shape[{left_size_condition}] must be equal to input.shape[-2]", + ) + + torch._check( + tau.shape[-1] <= input.shape[-1], + lambda: "torch.ormqr: tau.shape[-1] must be less than or equal to input.shape[-1]", + ) + + torch._check( + input.ndim - tau.ndim == 1, + lambda: ( + f"torch.ormqr: Expected tau to have one dimension less than input, " + f"but got tau.ndim equal to {tau.ndim} and input.ndim is equal to {input.ndim}" + ), + ) + torch._check( + input.ndim == other.ndim, + lambda: ( + f"torch.ormqr: Expected other to have the same number of dimensions as input, " + f"but got other.ndim equal to {other.ndim} and input.ndim is equal to {input.ndim}" + ), + ) + + if input.ndim > 2: + expected_batch_shape = input.shape[:-2] + actual_batch_tau_shape = tau.shape[:-1] + torch._check( + actual_batch_tau_shape == expected_batch_shape, + lambda: ( + f"torch.ormqr: Expected batch dimensions of tau to be " + f"equal to input.shape[:-2], but got {actual_batch_tau_shape}" + ), + ) + + actual_batch_other_shape = other.shape[:-2] + torch._check( + actual_batch_other_shape == expected_batch_shape, + lambda: ( + f"torch.ormqr: Expected batch dimensions of other to be " + f"equal to input.shape[:-2], but got {actual_batch_other_shape}" + ), + ) + + torch._check( + tau.dtype == input.dtype, + lambda: ( + f"torch.ormqr: Expected input and tau to have the same dtype, " + f"but input has dtype {input.dtype} and tau has dtype {tau.dtype}" + ), + ) + torch._check( + other.dtype == input.dtype, + lambda: ( + f"torch.ormqr: Expected input and other to have the same dtype, " + f"but input has dtype {input.dtype} and other has dtype {other.dtype}" + ), + ) + + checkSameDevice("torch.ormqr", tau, input, "tau") + checkSameDevice("torch.ormqr", other, input, "other") + + return torch.empty_strided( + size=other.shape, + stride=make_contiguous_strides_for(other.shape, row_major=False), + dtype=other.dtype, + device=other.device, + ) + + +def _padding_check_valid_input(input, padding, *, dim): + torch._check( + len(padding) == 2 * dim, + lambda: f"padding size is expected to be {2 * dim}, but got: {len(padding)}", + ) + + input_dim = input.ndim + + is_batch_mode = input_dim == (dim + 2) + + valid_batch_mode = is_batch_mode + valid_non_batch_mode = not is_batch_mode + + if is_batch_mode: + # allow batch size of 0-dim. + for d in range(1, input_dim): + valid_batch_mode = valid_batch_mode and input.size(d) != 0 + else: + for d in range(input_dim): + valid_non_batch_mode = valid_non_batch_mode and input.size(d) != 0 + + # allow empty batch size but not other dimensions. + torch._check( + valid_batch_mode or valid_non_batch_mode, + lambda: ( + f"Expected {dim + 1}D or {dim + 2}D (batch mode) tensor with possibly 0 batch size " + f"and other non-zero dimensions for input, but got: {input.shape}" + ), + ) + + +def _pad1d_common(input, padding, *, is_reflection): + dim_plane = 0 + dim_w = 1 + nbatch = 1 + + if input.ndim == 3: + nbatch = input.size(0) + dim_w += 1 + dim_plane += 1 + + _padding_check_valid_input(input, padding, dim=1) + + pad_l, pad_r = padding + + nplane = input.size(dim_plane) + input_w = input.size(dim_w) + output_w = input_w + pad_l + pad_r + + if is_reflection: + torch._check( + pad_l < input_w and pad_r < input_w, + lambda: ( + f"Argument #4: Padding size should be less than the corresponding input dimension, " + f"but got: padding ({pad_l}, {pad_r}) at dimension {dim_w} of input {input.shape}" + ), + ) + + torch._check( + output_w >= 1, + lambda: f"input (W: {input_w}) is too small. Calculated output W: {output_w}", + ) + + if input.ndim == 2: + return input.new_empty((nplane, output_w)) + else: + return input.new_empty((nbatch, nplane, output_w)) + + +@register_meta(aten.reflection_pad1d) +@out_wrapper() +def meta_reflection_pad1d(input, padding): + return _pad1d_common(input, padding, is_reflection=True) + + +@register_meta(aten.replication_pad1d) +@out_wrapper() +def meta_replication_pad1d(input, padding): + torch._check( + input.dtype != torch.bool, + lambda: f""""replication_pad1d" not implemented for '{input.dtype.__str__()}'""", + ) + return _pad1d_common(input, padding, is_reflection=False) + + +def _pad1d_backward_common(grad_output, input, padding, *, is_reflection): + dim_w = 1 + if not is_reflection: + torch._check(len(padding) == 2, lambda: "padding size is expected to be 2") + + if input.ndim == 3: + dim_w += 1 + + pad_l, pad_r = padding + + input_w = input.size(dim_w) + output_w = input_w + pad_l + pad_r + + if is_reflection: + torch._check( + pad_l < input_w and pad_r < input_w, + lambda: ( + f"Argument #4: Padding size should be less than the corresponding input dimension, " + f"but got: padding ({pad_l}, {pad_r}) at dimension {dim_w} of input {input.shape}" + ), + ) + + torch._check( + output_w == grad_output.size(dim_w), + lambda: f"grad_output width unexpected. Expected: {output_w}, Got: {grad_output.size(dim_w)}", + ) + + return input.new_empty(input.shape) + + +@register_meta(aten.reflection_pad1d_backward) +@out_wrapper("grad_input") +def meta_reflection_pad1d_backward(grad_output, input, padding): + return _pad1d_backward_common(grad_output, input, padding, is_reflection=True) + + +@register_meta(aten.replication_pad1d_backward) +@out_wrapper("grad_input") +def meta_replication_pad1d_backward(grad_output, input, padding): + return _pad1d_backward_common(grad_output, input, padding, is_reflection=False) + + +def _pad2d_common(input, padding, *, is_reflection): + dim_w = 2 + dim_h = 1 + dim_slices = 0 + nbatch = 1 + + _padding_check_valid_input(input, padding, dim=2) + + ndim = input.ndim + if ndim == 4: + nbatch = input.size(0) + dim_w += 1 + dim_h += 1 + dim_slices += 1 + + pad_l, pad_r, pad_t, pad_b = padding + + nplane = input.size(dim_slices) + input_h = input.size(dim_h) + input_w = input.size(dim_w) + output_h = input_h + pad_t + pad_b + output_w = input_w + pad_l + pad_r + + if is_reflection: + torch._check( + pad_l < input_w and pad_r < input_w, + lambda: ( + f"Argument #4: Padding size should be less than the corresponding input dimension, " + f"but got: padding ({pad_l}, {pad_r}) at dimension {dim_w} of input {input.shape}" + ), + ) + torch._check( + pad_t < input_h and pad_b < input_h, + lambda: ( + f"Argument #6: Padding size should be less than the corresponding input dimension, " + f"but got: padding ({pad_t}, {pad_b}) at dimension {dim_h} of input {input.shape}" + ), + ) + + torch._check( + output_w >= 1 or output_h >= 1, + lambda: ( + f"input (H: {input_h} W: {input_w}) is too small. " + f"Calculated output H: {output_h} W: {output_w}" + ), + ) + + if input.ndim == 3: + return input.new_empty((nplane, output_h, output_w)) + else: + return input.new_empty((nbatch, nplane, output_h, output_w)) + + +@register_meta(aten.reflection_pad2d) +@out_wrapper() +def meta_reflection_pad2d(input, padding): + return _pad2d_common(input, padding, is_reflection=True) + + +@register_meta(aten.replication_pad2d) +@out_wrapper() +def meta_replication_pad2d(input, padding): + torch._check( + input.dtype != torch.bool, + lambda: f""""replication_pad2d" not implemented for '{input.dtype.__str__()}'""", + ) + return _pad2d_common(input, padding, is_reflection=False) + + +@register_meta( + aten._weight_norm_interface_backward.default, +) +def meta_weight_norm_backward(grad_w, saved_v, saved_g, saved_norms, dim): + grad_v = torch.empty_like(saved_v) + grad_g = torch.empty_like(saved_g) + return grad_v, grad_g + + +@register_meta( + [ + aten.reflection_pad2d_backward.default, + aten.reflection_pad2d_backward.grad_input, + aten.replication_pad2d_backward.default, + aten.replication_pad2d_backward.grad_input, + ] +) +@out_wrapper("grad_input") +def meta_pad2d_backward(grad_output, self, padding): + dim_w = 2 + dim_h = 1 + dim_plane = 0 + + self_shape = self.shape + if self.dim() == 4: + dim_w += 1 + dim_h += 1 + dim_plane += 1 + + pad_l, pad_r, pad_t, pad_b = padding + + input_h = self_shape[dim_h] + input_w = self_shape[dim_w] + output_h = input_h + pad_t + pad_b + output_w = input_w + pad_l + pad_r + + torch._check( + output_w == grad_output.size(dim_w), + lambda: f"grad_output width unexpected. Expected: {output_w}, Got: {grad_output.size(dim_w)}", + ) + torch._check( + output_h == grad_output.size(dim_h), + lambda: f"grad_output height unexpected. Expected: {output_h}, Got: {grad_output.size(dim_h)}", + ) + return self.new_empty(self.shape) + + +def _pad3d_common(input, padding, *, is_reflection): + dim_w = 3 + dim_h = 2 + dim_d = 1 + dim_plane = 0 + + _padding_check_valid_input(input, padding, dim=3) + + batch_mode = input.ndim == 5 + if batch_mode: + nbatch = input.size(0) + dim_w += 1 + dim_h += 1 + dim_d += 1 + dim_plane += 1 + + pad_l, pad_r, pad_t, pad_b, pad_f, pad_bk = padding + + nplane = input.size(dim_plane) + input_d = input.size(dim_d) + input_h = input.size(dim_h) + input_w = input.size(dim_w) + output_d = input_d + pad_f + pad_bk + output_h = input_h + pad_t + pad_b + output_w = input_w + pad_l + pad_r + + if is_reflection: + torch._check( + pad_l < input_w and pad_r < input_w, + lambda: ( + f"Argument #4: Padding size should be less than the corresponding input dimension, " + f"but got: padding ({pad_l}, {pad_r}) at dimension {dim_w} of input {input.shape}" + ), + ) + torch._check( + pad_t < input_h and pad_b < input_h, + lambda: ( + f"Argument #6: Padding size should be less than the corresponding input dimension, " + f"but got: padding ({pad_t}, {pad_b}) at dimension {dim_h} of input {input.shape}" + ), + ) + torch._check( + pad_f < input_d and pad_bk < input_d, + lambda: ( + f"Argument #8: Padding size should be less than the corresponding input dimension, " + f"but got: padding ({pad_f}, {pad_bk}) at dimension {dim_d} of input {input.shape}" + ), + ) + + torch._check( + output_w >= 1 or output_h >= 1 or output_d >= 1, + lambda: ( + f"input (D: {input_d} H: {input_h} W: {input_w}) is too small. " + f"Calculated output D: {output_d} H: {output_h} W: {output_w}" + ), + ) + + if batch_mode: + return input.new_empty((nbatch, nplane, output_d, output_h, output_w)) # type: ignore[possibly-undefined] + else: + return input.new_empty((nplane, output_d, output_h, output_w)) + + +@register_meta(aten.reflection_pad3d) +@out_wrapper() +def meta_reflection_pad3d(input, padding): + return _pad3d_common(input, padding, is_reflection=True) + + +@register_meta(aten.replication_pad3d) +@out_wrapper() +def meta_replication_pad3d(input, padding): + torch._check( + input.dtype != torch.bool, + lambda: f""""replication_pad3d" not implemented for '{input.dtype.__str__()}'""", + ) + return _pad3d_common(input, padding, is_reflection=False) + + +@register_meta( + [ + aten.reflection_pad3d_backward.default, + aten.reflection_pad3d_backward.grad_input, + aten.replication_pad3d_backward.default, + aten.replication_pad3d_backward.grad_input, + ] +) +@out_wrapper("grad_input") +def meta_pad3d_backward(grad_output, input, padding): + torch._check(len(padding) == 6, lambda: "padding size is expected to be 6") + assert input.ndim > 3 + assert grad_output.ndim == input.ndim + + dim_w = 3 + dim_h = 2 + dim_d = 1 + + if input.ndim == 5: + dim_w += 1 + dim_h += 1 + dim_d += 1 + + pad_l, pad_r, pad_t, pad_b, pad_f, pad_bk = padding + + input_d = input.size(dim_d) + input_h = input.size(dim_h) + input_w = input.size(dim_w) + output_d = input_d + pad_f + pad_bk + output_h = input_h + pad_t + pad_b + output_w = input_w + pad_l + pad_r + + torch._check( + output_w == grad_output.size(dim_w), + lambda: f"grad_output width unexpected. Expected: {output_w}, Got: {grad_output.size(dim_w)}", + ) + torch._check( + output_h == grad_output.size(dim_h), + lambda: f"grad_output height unexpected. Expected: {output_h}, Got: {grad_output.size(dim_h)}", + ) + torch._check( + output_d == grad_output.size(dim_d), + lambda: f"grad_output depth unexpected. Expected: {output_d}, Got: {grad_output.size(dim_d)}", + ) + + return input.new_empty(input.shape) + + +@register_meta(aten._pdist_forward) +@out_wrapper() +def meta__pdist_forward(self: Tensor, p: float = 2) -> Tensor: + torch._check( + self.is_contiguous(), lambda: "_pdist_forward requires contiguous input" + ) + n = self.size(0) + if n <= 1: + return self.new_empty([0]).to(memory_format=torch.legacy_contiguous_format) # type: ignore[call-overload] + else: + return self.new_empty((n * (n - 1) // 2,)).to( + memory_format=torch.legacy_contiguous_format + ) # type: ignore[call-overload] + + +@register_meta(aten._pdist_backward) +@out_wrapper() +def meta__pdist_backward(grad: Tensor, self: Tensor, p: float, pdist: Tensor) -> Tensor: + torch._check( + self.is_contiguous(), lambda: "_pdist_backward requires self to be contiguous" + ) + torch._check( + pdist.is_contiguous(), lambda: "_pdist_backward requires pdist to be contiguous" + ) + return torch.empty_like(self, memory_format=torch.legacy_contiguous_format) + + +@register_meta([aten.baddbmm.default, aten.baddbmm.out]) +@out_wrapper(exact_dtype=True) +def meta_baddbmm(self, batch1, batch2, *, beta=1, alpha=1): + from torch.fx.experimental.symbolic_shapes import guard_or_true, sym_eq + + dim1 = batch1.size(0) + dim2 = batch1.size(1) + dim3 = batch2.size(2) + if guard_or_true(torch.sym_not(sym_eq(self.shape, (dim1, dim2, dim3)))): + self = self.expand((dim1, dim2, dim3)) + torch._check(batch1.dim() == 3, lambda: "batch1 must be a 3D tensor") + torch._check(batch2.dim() == 3, lambda: "batch2 must be a 3D tensor") + if not exp_config.skip_dtype_check_in_meta_registrations: + torch._check( + self.dtype == batch1.dtype == batch2.dtype, + lambda: f"Input dtypes must be the same, got: input: {self.dtype}, batch1: {batch1.dtype}, batch2: {batch2.dtype}", + ) + batch1_sizes = batch1.shape + batch2_sizes = batch2.shape + bs = batch1_sizes[0] + contraction_size = batch1_sizes[2] + torch._check( + batch2_sizes[0] == bs and batch2_sizes[1] == contraction_size, + lambda: ( + f"Expected size for first two dimensions of batch2 tensor to be: " + f"[{bs}, {contraction_size}] but got: [{batch2_sizes[0]}, {batch2_sizes[1]}]." + ), + ) + return self.new_empty(self.size()) + + +@register_meta([aten.bernoulli.default, aten.bernoulli.out]) +@out_wrapper() +def meta_bernoulli(self, *, generator=None): + # https://github.com/pytorch/pytorch/issues/88612 + return torch.empty_like(self, memory_format=torch.contiguous_format) + + +@register_meta(aten.bernoulli_.float) +def meta_bernoulli_(self, p=0.5, generator=None): + return self + + +@register_meta(aten.bernoulli.p) +def meta_bernoulli_p(self, p=0.5, generator=None): + # https://github.com/pytorch/pytorch/issues/88612 + return torch.empty_like(self, memory_format=torch.contiguous_format) + + +@register_meta([aten.poisson.default, aten.poisson.out]) +@out_wrapper() +def meta_poisson(self, generator=None): + return torch.empty_like(self) + + +@register_meta(aten._fused_moving_avg_obs_fq_helper.default) +def meta__fused_moving_avg_obs_fq_helper( + self, + observer_on, + fake_quant_on, + running_min, + running_max, + scale, + zero_point, + averaging_const, + quant_min, + quant_max, + ch_axis, + per_row_fake_quant=False, + symmetric_quant=False, +): + torch._check( + ch_axis < self.dim(), + lambda: "Error in fused_moving_avg_obs_fake_quant_cpu: ch_axis must be < self.dim()", + ) + mask = torch.empty_like(self, dtype=torch.bool) + return (torch.empty_like(self), mask) + + +@register_meta(aten.mm) +@out_wrapper(exact_dtype=True) +def meta_mm(a, b, out_dtype: torch.dtype | None = None): + torch._check(a.dim() == 2, lambda: "a must be 2D") + torch._check(b.dim() == 2, lambda: "b must be 2D") + N, M1 = a.shape + M2, P = b.shape + torch._check( + M1 == M2, + lambda: f"a and b must have same reduction dim, but got [{N}, {M1}] X [{M2}, {P}].", + ) + if out_dtype is not None: + torch._check( + out_dtype == a.dtype + or ( + out_dtype == torch.float32 + and a.dtype in (torch.float16, torch.bfloat16) + ), + lambda: "out_dtype must be the same as input dtype or fp32 for fp16/bf16 inputs", + ) + result_dtype = a.dtype if out_dtype is None else out_dtype + return a.new_empty((N, P), dtype=result_dtype) + + +def _compute_reduction_shape(self, dims, keepdim): + if keepdim: + return tuple(self.shape[i] if i not in dims else 1 for i in range(self.ndim)) + + return utils.compute_reduction_output_shape(self.shape, dims) + + +# FakeTensors (meta tensors with a device) will report device as meta +# when running meta kernels. Here, access the "fake device" of FakeTensor if it +# exists so meta kernels which have diverge per device will be more +# accurate when run with FakeTensors +def device_hint(tensor) -> "str": + if isinstance(tensor, torch._subclasses.FakeTensor): + return tensor.fake_device.type + elif ( + hasattr(tensor, "device") + and hasattr(tensor.device, "type") + and tensor.device.type != "meta" + ): + return tensor.device.type + else: + return "cuda" # default to cuda + + +def calc_conv_nd_return_shape( + input_tensor: torch.Tensor, + weight: torch.Tensor, + stride: list[int] | int, + padding: list[int] | int, + dilation: list[int] | int, + is_transposed: bool, + groups: int, + output_padding: list[int] | int | None = None, +): + def _formula(ln: int, p: int, d: int, k: int, s: int) -> int: + """ + Formula to apply to calculate the length of some dimension of the output + + See: https://pytorch.org/docs/stable/generated/torch.nn.Conv2d.html + + Args: + ln: length of the dimension + p: padding in that dim + d: dilation in that dim + k: kernel size in that dim + s: stride in that dim + Returns: + The output length + """ + return (ln + 2 * p - d * (k - 1) - 1) // s + 1 + + def _formula_transposed(ln: int, p: int, d: int, k: int, s: int, op: int) -> int: + """ + Formula to apply to calculate the length of some dimension of the output + if transposed convolution is used. + See: https://pytorch.org/docs/stable/generated/torch.nn.ConvTranspose2d.html + + Args: + ln: length of the dimension + p: padding in that dim + d: dilation in that dim + k: kernel size in that dim + s: stride in that dim + op: output padding in that dim + + Returns: + The output length + """ + return (ln - 1) * s - 2 * p + d * (k - 1) + op + 1 + + kernel_size = weight.shape[2:] + dims = input_tensor.shape[2:] + if is_transposed: + out_channels = groups * weight.shape[1] + else: + out_channels = weight.shape[0] + if weight.shape[1] * groups != input_tensor.shape[1]: + raise RuntimeError("Invalid channel dimensions") + + ret_shape = [input_tensor.shape[0], out_channels] + if isinstance(stride, IntLike): + # pyrefly: ignore [bad-assignment] + stride = [stride] * len(dims) + elif len(stride) == 1: + stride = [stride[0]] * len(dims) + + if isinstance(padding, IntLike): + # pyrefly: ignore [bad-assignment] + padding = [padding] * len(dims) + elif len(padding) == 1: + padding = [padding[0]] * len(dims) + + if isinstance(dilation, IntLike): + # pyrefly: ignore [bad-assignment] + dilation = [dilation] * len(dims) + elif len(dilation) == 1: + dilation = [dilation[0]] * len(dims) + + output_padding_list: list[int] | None = None + if output_padding: + if isinstance(output_padding, IntLike): + # pyrefly: ignore [bad-assignment] + output_padding_list = [output_padding] * len(dims) + elif len(output_padding) == 1: + output_padding_list = [output_padding[0]] * len(dims) + else: + output_padding_list = output_padding + + for i in range(len(dims)): + # If output_padding is present, we are dealing with a transposed convolution + if output_padding_list: + ret_shape.append( + _formula_transposed( + dims[i], + # pyrefly: ignore [index-error] + padding[i], + # pyrefly: ignore [index-error] + dilation[i], + kernel_size[i], + # pyrefly: ignore [index-error] + stride[i], + output_padding_list[i], + ) + ) + else: + ret_shape.append( + # pyrefly: ignore [index-error] + _formula(dims[i], padding[i], dilation[i], kernel_size[i], stride[i]) + ) + from torch.fx.experimental.symbolic_shapes import sym_or + + torch._check( + sym_or(*[x > 0 for x in ret_shape[2:]]), + lambda: f"Given input size per channel: {list(dims)}. " + f"Calculated output size per channel: {ret_shape[2:]}. " + f"Output size is too small", + ) + + return ret_shape + + +def is_channels_last(ten): + return torch._prims_common.suggest_memory_format(ten) == torch.channels_last + + +@register_meta(aten.miopen_batch_norm.default) +def meta_miopen_batch_norm( + input_tensor: torch.Tensor, + weight: torch.Tensor, + bias: torch.Tensor | None, + running_mean: torch.Tensor | None, + running_var: torch.Tensor | None, + training: bool, + exponential_average_factor: float, + epsilon: float, +): + # In batch norm the output is of the same shape as the input + out_shape = input_tensor.shape + + # If tensor is provided for running_mean and running_var then use this. If these are not + # provided then we return the shape of weight tensor. Similar to how this is handled in the decomposition + save_mean_shape = running_mean.shape if running_mean is not None else weight.shape + save_var_shape = running_var.shape if running_var is not None else weight.shape + + def pick_memory_format(): + if is_channels_last(input_tensor): + return torch.channels_last + if input_tensor.is_contiguous(memory_format=torch.contiguous_format): + return torch.contiguous_format + return torch.contiguous_format + + out = input_tensor.new_empty(out_shape).to(memory_format=pick_memory_format()) + + if training: + save_mean = input_tensor.new_empty(save_mean_shape) + save_var = input_tensor.new_empty(save_var_shape) + else: + save_mean = input_tensor.new_empty((0,)) + save_var = input_tensor.new_empty((0,)) + + return out, save_mean, save_var + + +@register_meta(aten.convolution.default) +def meta_conv( + input_tensor: torch.Tensor, + weight: torch.Tensor, + bias: torch.Tensor, + stride: list[int], + padding: list[int], + dilation: list[int], + is_transposed: bool, + output_padding: list[int], + groups: int, +): + shape_out = calc_conv_nd_return_shape( + input_tensor, + weight, + stride, + padding, + dilation, + is_transposed, + groups, + output_padding if is_transposed else None, + ) + + input_channels_dim = 1 + output_channels_dim = 1 + if input_tensor.size(input_channels_dim) == 0: + shape_out[output_channels_dim] = 0 + + out = input_tensor.new_empty(shape_out) + return out + + +if torch._C._has_mkldnn: + _meta_lib_dont_use_me_use_register_meta_for_mkldnn = torch.library.Library( + "mkldnn", "IMPL", "Meta" + ) + + @register_meta(torch.ops.mkldnn._convolution_pointwise.default) + def meta_mkldnn_convolution_default( + input_tensor, + weight, + bias, + padding, + stride, + dilation, + groups, + attr, + scalars, + algorithm, + ): + shape_out = calc_conv_nd_return_shape( + input_tensor, weight, stride, padding, dilation, False, groups, [] + ) + out = input_tensor.new_empty(shape_out) + out_memory_format = torch.channels_last + if input_tensor.dim() == 5: + out_memory_format = torch.channels_last_3d + out = out.to(memory_format=out_memory_format) # type: ignore[call-overload] + return out + + @register_meta(torch.ops.mkldnn._linear_pointwise.default) + def meta_linear_pointwise_default( + input_tensor, weight, bias, attr, scalars, algorithm + ): + return input_tensor.new_empty((*input_tensor.shape[:-1], weight.shape[0])) + + if torch._C.has_mkl: + _meta_lib_dont_use_me_use_register_meta_for_mkl = torch.library.Library( + "mkl", "IMPL", "Meta" + ) + + @register_meta(torch.ops.mkl._mkl_linear) + def meta_mkl_linear(input_tensor, packed_weight, orig_weight, bias, batch_size): + return input_tensor.new_empty( + (*input_tensor.shape[:-1], orig_weight.shape[0]) + ) + + _meta_lib_dont_use_me_use_register_meta_for_onednn = torch.library.Library( + "onednn", "IMPL", "Meta" + ) + + @register_meta(torch.ops.onednn.qconv2d_pointwise.default) + @register_meta(torch.ops.onednn.qconv_pointwise.default) + @register_meta(torch.ops.onednn.qconv_pointwise.tensor) + def meta_qconv_pointwise( + x, + x_scale, + x_zp, + w, # prepacked_weight + w_scale, + w_zp, + bias, + stride, + padding, + dilation, + groups, + output_scale, + output_zero_point, + output_dtype, + attr, + scalars, + algorithm, + ): + shape_out = calc_conv_nd_return_shape( + x, + w, + stride, + padding, + dilation, + False, + groups, + None, + ) + if output_dtype is None: + output_dtype = x.dtype + assert output_dtype in [ + torch.float32, + torch.bfloat16, + torch.uint8, + torch.int8, + torch.float8_e4m3fn, + ] + out = x.new_empty(shape_out, dtype=output_dtype) + assert len(shape_out) in [3, 4, 5], ( + "Expect output to be 3d/4d/5d for conv1d/2d/3d" + ) + format = { + 3: torch.contiguous_format, + 4: torch.channels_last, + 5: torch.channels_last_3d, + }[len(shape_out)] + out = out.to(memory_format=format) + return out + + @register_meta(torch.ops.onednn.qconv2d_pointwise.binary) + @register_meta(torch.ops.onednn.qconv2d_pointwise.binary_tensor) + def meta_qconv2d_pointwise_binary( + x, + x_scale, + x_zp, + w, + w_scale, + w_zp, + accum, + bias, + stride, + padding, + dilation, + groups, + output_scale, + output_zero_point, + output_dtype, + accum_scale, + accum_zero_point, + binary_op_name, + alpha, + unary_op_name, + unary_op_args, + unary_op_algorithm, + ): + assert binary_op_name == "sum" + return accum + + @register_meta(torch.ops.onednn.qlinear_pointwise.default) + @register_meta(torch.ops.onednn.qlinear_pointwise.tensor) + def meta_qlinear_pointwise( + x, + x_scale, + x_zp, + w, + w_scale, + w_zp, + bias, + output_scale, + output_zero_point, + output_dtype, + post_op_name, + post_op_args, + post_op_algorithm, + ): + output_shape = list(x.shape) + # The weight has been transposed during the qlinear weight prepack process. + output_shape[-1] = w.shape[1] + assert output_dtype in [ + torch.float32, + torch.bfloat16, + torch.int8, + torch.uint8, + torch.float8_e4m3fn, + ] + out = x.new_empty(output_shape, dtype=output_dtype) + return out + + @register_meta(torch.ops.onednn.qlinear_pointwise.binary) + @register_meta(torch.ops.onednn.qlinear_pointwise.binary_tensor) + def meta_qlinear_pointwise_binary( + x, + x_scale, + x_zp, + w, + w_scale, + w_zp, + x_2, + bias, + output_scale, + output_zero_point, + output_dtype, + x2_scale, + x2_zp, + binary_op_name, + alpha, + unary_op_name, + unary_op_args, + unary_op_algorithm, + ): + if binary_op_name == "sum": + return x_2 + output_shape = list(x.shape) + # The weight has been transposed during the qlinear weight prepack process. + output_shape[-1] = w.shape[1] + assert output_dtype in [ + torch.float32, + torch.bfloat16, + torch.uint8, + torch.int8, + torch.float8_e4m3fn, + ] + out = x.new_empty(output_shape, dtype=output_dtype) + return out + + @register_meta(torch.ops.onednn.linear_dynamic_fp16.default) + @register_meta(torch.ops.onednn.linear_relu_dynamic_fp16.default) + def meta_linear_dynamic_fp16( + x, + w, + bias, + ): + output_shape = list(x.shape) + # The weight has been transposed during the qlinear weight prepack process. + output_shape[-1] = w.shape[1] + out = x.new_empty(output_shape) + return out + + _meta_lib_dont_use_me_use_register_meta_for_quantized = torch.library.Library( + "quantized", "IMPL", "Meta" + ) + + @register_meta(torch.ops.quantized.max_pool2d) + def meta_quantized_max_pool2d( + input, + kernel_size, + stride=(), + padding=(0,), + dilation=(1,), + ceil_mode=False, + ): + ( + nInputPlane, + outputHeight, + outputWidth, + ) = max_pool2d_checks_and_compute_shape( + input, kernel_size, stride, padding, dilation, ceil_mode + ) + nbatch = input.size(-4) if input.dim() == 4 else 1 + memory_format = torch.channels_last + if input.dim() == 3: + size = [nInputPlane, outputHeight, outputWidth] + else: + size = [nbatch, nInputPlane, outputHeight, outputWidth] + return torch.empty( + size, + dtype=input.dtype, + device=input.device, + memory_format=memory_format, + ) + + @register_meta(torch.ops.quantized.int4mm_packed_weight_cpu) + def meta_int4mm_packed_weight_cpu(x, w, q_group_size, q_scale_and_zeros): + torch._check(x.dim() == 2, lambda: f"x must be a 2D tensor, got {x.dim()}D") + torch._check(w.dim() == 2, lambda: f"w must be a 2D tensor, got {w.dim()}D") + torch._check( + x.dtype in [torch.float32, torch.float16, torch.bfloat16], + lambda: f"expected x to be f32/f16/bf16, got {x.dtype}", + ) + torch._check( + w.dtype == torch.uint8, lambda: f"expected w to be uint8, got {w.dtype}" + ) + torch._check( + q_group_size.dtype == torch.int64, + lambda: f"q_group_size must be int64, got {q_group_size.dtype}", + ) + torch._check( + q_scale_and_zeros.dtype == x.dtype, + lambda: f"q_scale_and_zeros must have the same dtype as x, got {q_scale_and_zeros.dtype}", + ) + return x.new_empty(x.size(0), w.size(0), dtype=x.dtype) + + +# from check_dim_size() in aten/src/ATen/TensorUtils.cpp. +def check_dim_size(tensor, dim, dim_size, size): + torch._check( + tensor.dim() == dim and tensor.shape[dim_size] == size, + lambda: f"Expected a tensor of dimension {dim} and tensor.size[{dim_size}] == {size}, " + + f"but got : dimension {tensor.dim()} and tensor.size[{dim_size}] = {tensor.shape[dim_size]}", + ) + + +@register_meta(aten.avg_pool2d.default) +def meta_avg_pool2d( + input, + kernel_size, + stride=(), + padding=(0,), + ceil_mode=False, + count_include_pad=True, + divisor_override=None, +): + def unpack(name, val): + torch._check( + len(val) in [1, 2], + lambda: f"avg_pool2d: {name} must either be a single int, or a tuple of two ints", + ) + H = val[0] + W = H if len(val) == 1 else val[1] + return H, W + + kH, kW = unpack("kernel_size", kernel_size) + torch._check( + len(stride) in [0, 1, 2], + lambda: "avg_pool2d: stride must either be omitted, a single int, or a tuple of two ints", + ) + torch._check( + input.dtype not in [torch.uint8, torch.uint16, torch.uint32, torch.uint64], + lambda: f""""avg_pool2d" not implemented for '{input.dtype.__str__()}'""", + ) + if len(stride) == 0: + dH, dW = kH, kW + elif len(stride) == 1: + dH, dW = stride[0], stride[0] + else: + dH, dW = unpack("stride", stride) + + padH, padW = unpack("padding", padding) + + torch._check( + divisor_override is None or divisor_override != 0, + lambda: "divisor must be not zero", + ) + + nbatch = input.size(-4) if input.dim() == 4 else 1 + nInputPlane = input.size(-3) + inputHeight = input.size(-2) + inputWidth = input.size(-1) + + outputHeight = pooling_output_shape(inputHeight, kH, padH, dH, 1, ceil_mode) + outputWidth = pooling_output_shape(inputWidth, kW, padW, dW, 1, ceil_mode) + + memory_format = utils.suggest_memory_format(input) + pool2d_shape_check( + input, + kH, + kW, + dH, + dW, + padH, + padW, + 1, + 1, + nInputPlane, + inputHeight, + inputWidth, + outputHeight, + outputWidth, + memory_format, + ) + + if input.dim() == 3: + size = [nInputPlane, outputHeight, outputWidth] + else: + size = [nbatch, nInputPlane, outputHeight, outputWidth] + return torch.empty( + size, + dtype=input.dtype, + device=input.device, + memory_format=memory_format, + ) + + +# from avg_pool2d_backward_shape_check() in aten/src/ATen/native/Pool.h. +def avg_pool2d_backward_shape_check( + input, + gradOutput, + nbatch, + kH, + kW, + dH, + dW, + padH, + padW, + nInputPlane, + inputHeight, + inputWidth, + outputHeight, + outputWidth, + mem_format, +): + pool2d_shape_check( + input, + kH, + kW, + dH, + dW, + padH, + padW, + 1, + 1, + nInputPlane, + inputHeight, + inputWidth, + outputHeight, + outputWidth, + mem_format, + ) + + ndim = input.dim() + nOutputPlane = nInputPlane + + check_dim_size(gradOutput, ndim, ndim - 3, nOutputPlane) + check_dim_size(gradOutput, ndim, ndim - 2, outputHeight) + check_dim_size(gradOutput, ndim, ndim - 1, outputWidth) + + +# Don't override the C++ registration. +@register_meta(aten.avg_pool2d_backward.default) +def meta_avg_pool2d_backward( + gradOutput_, + input, + kernel_size, + stride, + padding, + ceil_mode, + count_include_pad, + divisor_override, +): + # From aten/src/ATen/native/AveragePool2d.cpp structured kernel meta func. + torch._check( + len(kernel_size) == 1 or len(kernel_size) == 2, + lambda: "avg_pool2d: kernel_size must either be a single int, or a tuple of two ints", + ) + kH = kernel_size[0] + kW = kH if len(kernel_size) == 1 else kernel_size[1] + torch._check( + len(stride) == 0 or len(stride) == 1 or len(stride) == 2, + lambda: "avg_pool2d: stride must either be omitted, a single int, or a tuple of two ints", + ) + dH = kH if len(stride) == 0 else stride[0] + dW = kW if len(stride) == 0 else dH if len(stride) == 1 else stride[1] + torch._check( + len(padding) == 1 or len(padding) == 2, + lambda: "avg_pool2d: padding must either be a single int, or a tuple of two ints", + ) + padH = padding[0] + padW = padH if len(padding) == 1 else padding[1] + + torch._check( + divisor_override is None or divisor_override != 0, + lambda: "divisor must be not zero", + ) + + input_size = input.shape + nbatch = input_size[-4] if input.dim() == 4 else 1 + nInputPlane = input_size[-3] + inputHeight = input_size[-2] + inputWidth = input_size[-1] + + outputHeight = pooling_output_shape(inputHeight, kH, padH, dH, 1, ceil_mode) + outputWidth = pooling_output_shape(inputWidth, kW, padW, dW, 1, ceil_mode) + + mem_format = utils.suggest_memory_format(input) + + avg_pool2d_backward_shape_check( + input, + gradOutput_, + nbatch, + kH, + kW, + dH, + dW, + padH, + padW, + nInputPlane, + inputHeight, + inputWidth, + outputHeight, + outputWidth, + mem_format, + ) + + return torch.empty( + input_size, + dtype=input.dtype, + device=input.device, + memory_format=mem_format, + ) + + +@register_meta(aten.avg_pool3d) +@out_wrapper() +def meta_avg_pool3d( + input, + kernel_size, + stride=(), + padding=(0,), + ceil_mode=False, + count_include_pad=True, + divisor_override=None, +): + torch._check( + len(kernel_size) in (1, 3), + lambda: "avg_pool3d: kernel_size must be a single int, or a tuple of three ints", + ) + kT = kernel_size[0] + kH = kT if len(kernel_size) == 1 else kernel_size[1] + kW = kT if len(kernel_size) == 1 else kernel_size[2] + + torch._check( + not stride or len(stride) in (1, 3), + lambda: "avg_pool3d: stride must be omitted, a single int, or a tuple of three ints", + ) + torch._check( + input.dtype not in [torch.uint8, torch.uint16, torch.uint32, torch.uint64], + lambda: f""""avg_pool3d" not implemented for '{input.dtype.__str__()}'""", + ) + dT = kT if not stride else stride[0] + dH = kH if not stride else (dT if len(stride) == 1 else stride[1]) + dW = kW if not stride else (dT if len(stride) == 1 else stride[2]) + + torch._check( + len(padding) in (1, 3), + lambda: "avg_pool3d: padding must be a single int, or a tuple of three ints", + ) + padT = padding[0] + padH = padT if len(padding) == 1 else padding[1] + padW = padT if len(padding) == 1 else padding[2] + + torch._check( + input.ndim in (4, 5), + lambda: "non-empty 4D or 5D (batch mode) tensor expected for input", + ) + + torch._check( + not divisor_override or divisor_override != 0, + lambda: "divisor must be not zero", + ) + + nbatch = input.size(0) + nslices = input.size(-4) + itime = input.size(-3) + iheight = input.size(-2) + iwidth = input.size(-1) + + otime = pooling_output_shape(itime, kT, padT, dT, 1, ceil_mode) + oheight = pooling_output_shape(iheight, kH, padH, dH, 1, ceil_mode) + owidth = pooling_output_shape(iwidth, kW, padW, dW, 1, ceil_mode) + + pool3d_shape_check( + input, + nslices, + kT, + kH, + kW, + dT, + dH, + dW, + padT, + padH, + padW, + 1, + 1, + 1, + itime, + iheight, + iwidth, + otime, + oheight, + owidth, + "avg_pool3d()", + check_input_size=True, + ) + + if input.ndim == 4: + return input.new_empty((nslices, otime, oheight, owidth)) + else: + return input.new_empty((nbatch, nslices, otime, oheight, owidth)) + + +@register_meta(aten.avg_pool3d_backward) +@out_wrapper("grad_input") +def meta_avg_pool3d_backward( + grad_output, + input, + kernel_size, + stride, + padding, + ceil_mode, + count_include_pad, + divisor_override, +): + torch._check( + len(kernel_size) in (1, 3), + lambda: "avg_pool3d: kernel_size must be a single int, or a tuple of three ints", + ) + kT = kernel_size[0] + kH = kT if len(kernel_size) == 1 else kernel_size[1] + kW = kT if len(kernel_size) == 1 else kernel_size[2] + + torch._check( + not stride or len(stride) in (1, 3), + lambda: "avg_pool3d: stride must be omitted, a single int, or a tuple of three ints", + ) + dT = kT if not stride else stride[0] + dH = kH if not stride else (dT if len(stride) == 1 else stride[1]) + dW = kW if not stride else (dT if len(stride) == 1 else stride[2]) + + torch._check( + len(padding) in (1, 3), + lambda: "avg_pool3d: padding must be a single int, or a tuple of three ints", + ) + padT = padding[0] + padH = padT if len(padding) == 1 else padding[1] + padW = padT if len(padding) == 1 else padding[2] + + torch._check( + input.ndim in (4, 5), + lambda: "non-empty 4D or 5D (batch mode) tensor expected for input", + ) + + torch._check( + not divisor_override or divisor_override != 0, + lambda: "divisor must be not zero", + ) + + nslices = input.size(-4) + itime = input.size(-3) + iheight = input.size(-2) + iwidth = input.size(-1) + + otime_for_shape_check = pooling_output_shape(itime, kT, padT, dT, 1, ceil_mode) + oheight_for_shape_check = pooling_output_shape(iheight, kH, padH, dH, 1, ceil_mode) + owidth_for_shape_check = pooling_output_shape(iwidth, kW, padW, dW, 1, ceil_mode) + + avg_pool3d_backward_shape_check( + input, + grad_output, + nslices, + kT, + kH, + kW, + dT, + dH, + dW, + padT, + padH, + padW, + itime, + iheight, + iwidth, + otime_for_shape_check, + oheight_for_shape_check, + owidth_for_shape_check, + "avg_pool3d_backward()", + ) + + return input.new_empty(input.shape) + + +@register_meta(aten._adaptive_avg_pool2d.default) +def meta_adaptive_avg_pool2d(self, output_size): + torch._check( + self.ndim == 3 or self.ndim == 4, + lambda: f"Expected 3D or 4D tensor, but got {self.shape}", + ) + output_shape = self.shape[:-2] + tuple(output_size) + memory_format = utils.suggest_memory_format(self) + # need to set memory_format to preserve the memory format of the input + # channel last input should have channel last output + return torch.empty( + output_shape, + dtype=self.dtype, + device=self.device, + memory_format=memory_format, + ) + + +@register_meta(aten._adaptive_avg_pool3d.default) +def meta_adaptive_avg_pool3d(self, output_size): + torch._check( + self.ndim == 4 or self.ndim == 5, + lambda: f"Expected 4D or 5D tensor, but got {self.shape}", + ) + return self.new_empty(self.shape[:-3] + tuple(output_size)) + + +@register_meta(aten._adaptive_avg_pool2d_backward.default) +def meta__adaptive_avg_pool2d_backward(grad_out, self): + ndim = grad_out.ndim + for i in range(1, ndim): + torch._check( + grad_out.size(i) > 0, + lambda: f"adaptive_avg_pool2d_backward(): Expected grad_output to have non-zero \ + size for non-batch dimensions, {grad_out.shape} with dimension {i} being empty", + ) + torch._check( + ndim == 3 or ndim == 4, + lambda: f"adaptive_avg_pool2d_backward(): Expected 3D or 4D tensor, but got {self.shape}", + ) + torch._check( + self.dtype == grad_out.dtype, + lambda: f"expected dtype {self.dtype} for `grad_output` but got dtype {grad_out.dtype}", + ) + memory_format = torch.contiguous_format + if is_channels_last(self): + memory_format = torch.channels_last + return self.new_empty(self.shape).to(memory_format=memory_format) + + +@register_meta(aten._adaptive_avg_pool3d_backward) +@out_wrapper("grad_input") +def meta__adaptive_avg_pool3d_backward(grad_output, self): + _adaptive_pool_empty_output_check(grad_output, "adaptive_avg_pool3d_backward") + return torch.empty_like(self, memory_format=torch.legacy_contiguous_format) + + +def _adaptive_pool_empty_output_check(grad_output: Tensor, arg_name: str): + ndim = grad_output.ndim + for i in range(1, ndim): + torch._check( + grad_output.size(i) > 0, + lambda: ( + f"{arg_name}(): Expected grad_output to have non-zero size for non-batch dimensions, " + f"but grad_output has sizes {grad_output.shape} with dimension {i} being empty" + ), + ) + + +@register_meta(aten.adaptive_max_pool2d) +@out_wrapper("out", "indices") +def meta_adaptive_max_pool2d(input, output_size): + ndim = input.ndim + torch._check( + ndim in (3, 4), + lambda: f"adaptive_max_pool2d(): Expected 3D or 4D tensor, but got: {input.shape}", + ) + for i in range(1, ndim): + torch._check( + input.size(i) > 0, + lambda: ( + f"adaptive_max_pool2d(): Expected input to have non-zero size for non-batch dimensions, " + f"but input has sizes {input.shape} with dimension {i} being empty" + ), + ) + + torch._check( + len(output_size) == 2, + lambda: "adaptive_max_pool2d(): internal error: output_size.size() must be 2", + ) + + dimH = 1 + sizeB = 1 + sizeD = 0 + + if input.ndim == 4: + sizeB = input.size(0) + dimH += 1 + + sizeD = input.size(dimH - 1) + osizeH, osizeW = output_size + + if input.ndim == 3: + out_shape = (sizeD, osizeH, osizeW) + out = input.new_empty(out_shape) + indices = input.new_empty(out_shape, dtype=torch.int64) + return out, indices + else: + out_shape = (sizeB, sizeD, osizeH, osizeW) # type: ignore[assignment] + memory_format = utils.suggest_memory_format(input) + out = input.new_empty(out_shape).to(memory_format=memory_format) + indices = input.new_empty(out_shape, dtype=torch.int64).to( + memory_format=memory_format + ) + return out, indices + + +@register_meta(aten.adaptive_max_pool2d_backward) +@out_wrapper("grad_input") +def meta_adaptive_max_pool2d_backward(grad_output, input, indices): + ndim = grad_output.ndim + torch._check( + ndim in (3, 4), + lambda: f"adaptive_max_pooling2d_backward(): Expected 3D or 4D grad_output, but got: {grad_output.shape}", + ) + + _adaptive_pool_empty_output_check(grad_output, "adaptive_max_pool2d_backward") + + torch._check( + input.dtype == grad_output.dtype, + lambda: f"expected dtype {input.dtype} for `grad_output` but got dtype {grad_output.dtype}", + ) + + memory_format = utils.suggest_memory_format(input) + return input.new_empty(input.shape).to(memory_format=memory_format) + + +@register_meta(aten.adaptive_max_pool3d) +@out_wrapper("out", "indices") +def meta_adaptive_max_pool3d(input, output_size): + ndim = input.ndim + torch._check( + ndim in (4, 5), + lambda: f"adaptive_max_pool3d(): Expected 4D or 5D tensor, but got: {input.shape}", + ) + for i in range(1, ndim): + torch._check( + input.size(i) > 0, + lambda: ( + f"adaptive_max_pool3d(): Expected input to have non-zero size for non-batch dimensions, " + f"but input has sizes {input.shape} with dimension {i} being empty" + ), + ) + + torch._check( + len(output_size) == 3, + lambda: "adaptive_max_pool3d(): internal error: output_size.size() must be 3", + ) + + dimD = 0 + sizeB = 1 + sizeD = 0 + + if ndim == 5: + sizeB = input.size(0) + dimD += 1 + + sizeD = input.size(dimD) + osizeT, osizeH, osizeW = output_size + + if ndim == 4: + out_shape = (sizeD, osizeT, osizeH, osizeW) + else: + out_shape = (sizeB, sizeD, osizeT, osizeH, osizeW) # type: ignore[assignment] + + out = input.new_empty(out_shape) + indices = input.new_empty(out_shape, dtype=torch.int64) + + return out, indices + + +@register_meta(aten.adaptive_max_pool3d_backward) +@out_wrapper("grad_input") +def meta_adaptive_max_pool3d_backward(grad_output, input, indices): + _adaptive_pool_empty_output_check(grad_output, "adaptive_max_pool3d_backward") + return input.new_empty(input.shape) + + +@register_meta(aten.repeat_interleave.Tensor) +def meta_repeat_interleave_Tensor(repeats, output_size=None): + if output_size is None: + raise RuntimeError("cannot repeat_interleave a meta tensor without output_size") + return repeats.new_empty(output_size) + + +@register_meta([aten.complex.default, aten.complex.out]) +@out_wrapper() +def meta_complex(real, imag): + assert real.dtype.is_floating_point + assert imag.dtype.is_floating_point + result = elementwise_meta( + real.to(corresponding_complex_dtype(real.dtype)), + imag.to(corresponding_complex_dtype(imag.dtype)), + type_promotion=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, + ) + return result + + +@register_meta([aten.nonzero_static.default, aten.nonzero_static.out]) +@out_wrapper() +def nonzero_static(self, *, size, fill_value: int = -1): + return self.new_empty((size, self.dim()), dtype=torch.long) + + +@register_meta([torch.ops.aten.nonzero.default, torch.ops.aten.nonzero.out]) +@out_wrapper() +def nonzero(self): + torch._check_not_implemented( + exp_config.meta_nonzero_assume_all_nonzero, + lambda: "The register_meta function for torch.nonzero() raises unimplemented by default, " + "as a correct data-independent implementation does not exist. This implementation " + "returns a fake value, assuming all elements of the tensor are non-zero. " + "To enable this registration, please set " + "'torch.fx.experimental._config.meta_nonzero_assume_all_nonzero' to True.", + ) + return torch.empty_strided( + (self.numel(), self.dim()), + (1, self.numel()), + dtype=torch.long, + device=self.device, + ) + + +@register_meta([aten.index.Tensor, aten._unsafe_index.Tensor]) +def meta_index_Tensor(self, indices): + torch._check(bool(indices), lambda: "at least one index must be provided") + # aten::index is the internal advanced indexing implementation + # checkIndexTensorTypes and expandTensors + result: list[Tensor | None] = [] + for i, index in enumerate(indices): + if index is not None: + torch._check( + index.dtype in [torch.long, torch.int, torch.int8, torch.bool], + lambda: "tensors used as indices must be long, int, byte or bool tensors", + ) + if index.dtype in [torch.int8, torch.bool]: + nonzero = index.nonzero() + k = len(result) + torch._check_index( + k + index.ndim <= self.ndim, + lambda: f"too many indices for tensor of dimension {self.ndim}", + ) + for j in range(index.ndim): + torch._check_index( + index.shape[j] == self.shape[k + j], + lambda: f"The shape of the mask {index.shape} at index {i} " + f"does not match the shape of the indexed tensor {self.shape} at index {k + j}", + ) + result.append(nonzero.select(1, j)) + else: + result.append(index) + else: + result.append(index) + indices = result + torch._check( + len(indices) <= self.ndim, + lambda: f"too many indices for tensor of dimension {self.ndim} (got {len(indices)})", + ) + # expand_outplace + import torch._refs as refs # avoid import cycle in mypy + + indices = list(refs._maybe_broadcast(*indices)) + # add missing null tensors + while len(indices) < self.ndim: + indices.append(None) + + # hasContiguousSubspace + # true if all non-null tensors are adjacent + # See: + # https://numpy.org/doc/stable/user/basics.indexing.html#combining-advanced-and-basic-indexing + # https://stackoverflow.com/questions/53841497/why-does-numpy-mixed-basic-advanced-indexing-depend-on-slice-adjacency + state = 0 + has_contiguous_subspace = False + for index in indices: + if state == 0: + if index is not None: + state = 1 + elif state == 1: + if index is None: + state = 2 + else: + if index is not None: + break + else: + has_contiguous_subspace = True + + # transposeToFront + # This is the logic that causes the newly inserted dimensions to show up + # at the beginning of the tensor, if they're not contiguous + if not has_contiguous_subspace: + dims = [] + transposed_indices = [] + for i, index in enumerate(indices): + if index is not None: + dims.append(i) + transposed_indices.append(index) + for i, index in enumerate(indices): + if index is None: + dims.append(i) + transposed_indices.append(index) + self = self.permute(dims) + indices = transposed_indices + + # AdvancedIndex::AdvancedIndex + # Now we can assume the indices have contiguous subspace + # This is simplified from AdvancedIndex which goes to more effort + # to put the input and indices in a form so that TensorIterator can + # take them. If we write a ref for this, probably that logic should + # get implemented + before_shape: list[int] = [] + after_shape: list[int] = [] + replacement_shape: list[int] = [] + for dim, index in enumerate(indices): + if index is None: + if replacement_shape: + after_shape.append(self.shape[dim]) + else: + before_shape.append(self.shape[dim]) + else: + replacement_shape = list(index.shape) + + def _restride_src(self): + """ + This follows restride_src in TensorAdvancedIndexing.cpp + """ + shape = before_shape + replacement_shape + after_shape + strides = list(self.stride()) + # pyrefly: ignore [unsupported-operation] + strides[len(before_shape) : len(self.shape) - len(after_shape)] = [0] * len( + replacement_shape + ) + return self.as_strided(shape, strides) + + out = self.new_empty(before_shape + replacement_shape + after_shape) + from torch.fx.experimental.symbolic_shapes import guard_or_false + + if guard_or_false(self.numel() == 0): + # No need to worry about the output strides if self is empty. + return out + + # Try to follow eager to decide the output stride based on self. + # Note that perm here is the reverse of the 'perm_' decided by + # TensorIteratorBase::reorder_dimensions + restrided_self = _restride_src(self) + perm, _ = utils.compute_elementwise_output_logical_to_physical_perm(restrided_self) + + # Follow TensorIteratorBase::allocate_or_resize_outputs + if list(perm) != list(range(len(perm))): + perm_shape = utils.apply_perm(out.shape, perm) + new_stride = utils.make_contiguous_strides_for(perm_shape) + new_stride = utils.apply_perm(new_stride, utils.invert_perm(perm)) + out = out.as_strided(out.size(), new_stride) + return out + + +@register_meta([aten.convolution_backward.default]) +def meta_convolution_backward( + grad_output_, + input_, + weight_, + bias_sizes_opt, + stride, + padding, + dilation, + transposed, + output_padding, + groups, + output_mask, +): + # High level logic taken from slow_conv3d_backward_cpu which should + # be representative of all convolution_backward impls + backend_grad_input = None + backend_grad_weight = None + backend_grad_bias = None + + if output_mask[0]: + backend_grad_input = grad_output_.new_empty(input_.size()) + if output_mask[1]: + backend_grad_weight = grad_output_.new_empty(weight_.size()) + if output_mask[2]: + backend_grad_bias = grad_output_.new_empty(bias_sizes_opt) + + return (backend_grad_input, backend_grad_weight, backend_grad_bias) + + +@register_meta([aten.addbmm.default, aten.addbmm.out]) +@out_wrapper(exact_dtype=True) +def meta_addbmm(self, batch1, batch2, *, beta=1, alpha=1): + dim1 = batch1.size(1) + dim2 = batch2.size(2) + self = self.expand((dim1, dim2)) + torch._check(batch1.dim() == 3, lambda: "batch1 must be a 3D tensor") + torch._check(batch2.dim() == 3, lambda: "batch2 must be a 3D tensor") + torch._check( + batch1.size(0) == batch2.size(0), + lambda: f"batch1 and batch2 must have same number of batches, got {batch1.size(0)} and {batch2.size(0)}", + ) + torch._check( + batch1.size(2) == batch2.size(1), + lambda: ( + f"Incompatible matrix sizes for bmm ({batch1.size(1)}x{batch1.size(2)} " + f"and {batch2.size(1)}x{batch2.size(2)})" + ), + ) + torch._check( + self.size(0) == dim1 and self.size(1) == dim2, + lambda: "self tensor does not match matmul output shape", + ) + return self.new_empty(self.size()) + + +@register_meta([aten.randint_like.Tensor]) +def meta_randint_like(self, high, **kwargs): + return self.new_empty(self.size()) + + +@register_meta([aten._fused_adam_.default, aten._fused_adamw_.default]) +def meta__fused_adam_( + self, + grads, + exp_avgs, + exp_avg_sqs, + max_exp_avg_sqs, + state_steps, + *, + lr, + beta1, + beta2, + weight_decay, + eps, + amsgrad, + maximize, + grad_scale=None, + found_inf=None, +): + for l in [self, grads, exp_avgs, exp_avg_sqs, max_exp_avg_sqs, state_steps]: + torch._check( + isinstance(l, list), + lambda: f"exponent must be a tensor list but got {type(l)}", + ) + + +@register_meta([aten._fused_adam.default]) +def meta__fused_adam( + self, + grads, + exp_avgs, + exp_avg_sqs, + max_exp_avg_sqs, + state_steps, + *, + lr, + beta1, + beta2, + weight_decay, + eps, + amsgrad, + maximize, + grad_scale=None, + found_inf=None, +): + for l in [self, grads, exp_avgs, exp_avg_sqs, max_exp_avg_sqs, state_steps]: + torch._check( + isinstance(l, list), + lambda: f"exponent must be a tensor list but got {type(l)}", + ) + + def empty_like_list(tensor_list): + return [torch.empty_like(t) for t in tensor_list] + + return ( + empty_like_list(self), + empty_like_list(grads), + empty_like_list(exp_avgs), + empty_like_list(exp_avg_sqs), + empty_like_list(max_exp_avg_sqs), + ) + + +@register_meta([aten._int_mm]) +@out_wrapper() +def meta__int_mm(a, b): + torch._check(a.dim() == 2, lambda: "a must be a 2D tensor") + torch._check(b.dim() == 2, lambda: "b must be a 2D tensor") + torch._check( + a.dtype is torch.int8, + lambda: f"expected self to be int8, got {a.dtype}", + ) + torch._check( + b.dtype is torch.int8, + lambda: f"expected mat2 to be int8, got {b.dtype}", + ) + torch._check( + a.size(1) == b.size(0), + lambda: ( + f"Incompatible matrix sizes for _int_mm ({a.size(0)}x{a.size(1)} " + f"and {b.size(0)}x{b.size(1)})" + ), + ) + return a.new_empty((a.size(0), b.size(1)), dtype=torch.int32) + + +@register_meta([aten._convert_weight_to_int4pack]) +def meta__convert_weight_to_int4pack(w, inner_k_tiles): + torch._check(w.dim() == 2, lambda: "w must be a 2D tensor") + torch._check( + w.dtype is torch.uint8, + lambda: f"expected w to be uint8, got {w.dtype}", + ) + n = w.size(0) + k = w.size(1) * 2 # w is [n][k / 2] uint8 + return w.new_empty( + ( + n // 8, + k // (inner_k_tiles * 16), + 32, + inner_k_tiles // 2, + ), + dtype=torch.int32, + ) + + +@register_meta([aten._convert_weight_to_int4pack_for_cpu]) +def meta__convert_weight_to_int4pack_for_cpu(w, inner_k_tiles): + torch._check(w.dim() == 2, lambda: "w must be a 2D tensor") + torch._check( + w.dtype is torch.int32, + lambda: f"expected w to be int32, got {w.dtype}", + ) + n = w.size(0) + k = w.size(1) # w is [n][k] int32 + return w.new_empty( + (n, k // 2), + dtype=torch.uint8, + ) + + +@register_meta([aten._weight_int4pack_mm]) +def meta__weight_int4pack_mm(x, w, q_group_size, q_scale_and_zeros): + torch._check(x.dim() == 2, lambda: "x must be a 2D tensor") + torch._check(w.dim() == 4, lambda: "w must be a 4D tensor") + torch._check( + x.dtype in [torch.float32, torch.float16, torch.bfloat16], + lambda: f"expected x to be f32/f16/bf16, got {x.dtype}", + ) + torch._check( + w.dtype is torch.int32, + lambda: f"expected w to be int32, got {w.dtype}", + ) + return x.new_empty(x.size(0), w.size(0) * 8, dtype=x.dtype) + + +@register_meta([aten._weight_int4pack_mm_for_cpu]) +def meta__weight_int4pack_mm_for_cpu(x, w, q_group_size, q_scale_and_zeros): + torch._check(x.dim() == 2, lambda: "x must be a 2D tensor") + torch._check(w.dim() == 2, lambda: "w must be a 2D tensor") + torch._check( + x.dtype in [torch.float32, torch.float16, torch.bfloat16], + lambda: f"expected x to be f32/f16/bf16, got {x.dtype}", + ) + torch._check( + w.dtype is torch.uint8, + lambda: f"expected w to be uint8, got {w.dtype}", + ) + return x.new_empty(x.size(0), w.size(0), dtype=x.dtype) + + +@register_meta([aten._weight_int4pack_mm_with_scales_and_zeros]) +def _weight_int4pack_mm_with_scales_and_zeros(x, w, q_group_size, qScale, qZeros): + torch._check(x.dim() == 2, lambda: "x must be a 2D tensor") + torch._check(w.dim() == 2, lambda: "w must be a 2D tensor") + torch._check( + x.dtype in [torch.float32, torch.float16, torch.bfloat16], + lambda: f"expected x to be f32/f16/bf16, got {x.dtype}", + ) + torch._check( + w.dtype is torch.int32, + lambda: f"expected w to be int32, got {w.dtype}", + ) + return x.new_empty(x.size(0), w.size(0), dtype=x.dtype) + + +def kai_roundup(a: int, b: int) -> int: + return ((a + b - 1) // b) * b + + +def get_kai_packed_weight_size(n_bits, N, K, groupsize): + if n_bits == 4: + # Works for both fp32 and bf16 Kernels + if groupsize == K: # channelwise + # dotprod params only [1x8x32_neon_dotprod] + kai_nr = 8 + kai_kr = 16 + kai_sr = 2 + kai_num_bytes_sum_rhs = 4 # sizeof(int32_t) + kai_num_bytes_multiplier_rhs = 4 # sizeof(float) + kai_num_bytes_bias = 4 # sizeof(float) + + def kai_k_roundedup(k, kr, sr): + # Since we pack a float and int32 value at the end of the row, + # we must make sure that k is a multiple of 4 for alignment + kr_sr_roundedup4 = kai_roundup(kr * sr, 4) + return kai_roundup(k, kr_sr_roundedup4) + + def kai_get_rhs_packed_stride_rhs_pack_nxk_qsi4cxp_qsu4cxs1s0( + k, nr, kr, sr + ): + k_internal = kai_k_roundedup(k, kr, sr) + + assert (k_internal % 2) == 0, "k_internal must be even" + + return nr * ( + (k_internal // 2) + + kai_num_bytes_multiplier_rhs + + kai_num_bytes_sum_rhs + + kai_num_bytes_bias + ) + + def kai_get_rhs_packed_size_rhs_pack_nxk_qsi4cxp_qsu4cxs1s0( + n, k, nr, kr, sr + ): + num_rows = kai_roundup(n, nr) // nr + + return ( + num_rows + * kai_get_rhs_packed_stride_rhs_pack_nxk_qsi4cxp_qsu4cxs1s0( + k, nr, kr, sr + ) + ) + + return kai_get_rhs_packed_size_rhs_pack_nxk_qsi4cxp_qsu4cxs1s0( + N, K, kai_nr, kai_kr, kai_sr + ) + elif groupsize % 32 == 0 and K % groupsize == 0: # groupwise + kai_nr = 8 + kai_kr = 16 + kai_sr = 2 + kai_num_bytes_sum_rhs = 4 + kai_num_bytes_bias = 4 + kai_nr_multiple_of = 4 + kai_bl_multiple_of = 32 + + def kai_get_rhs_packed_size_rhs_pack_nxk_qsi4c32p_qsu4c32s1s0( + n, k, nr, kr, sr, bl + ): + assert (bl % kr) == 0 + assert (nr % kai_nr_multiple_of) == 0 + assert (bl % kai_bl_multiple_of) == 0 + + num_rows = kai_roundup(n, nr) // nr + + return ( + num_rows + * kai_get_rhs_packed_stride_rhs_pack_nxk_qsi4c32p_qsu4c32s1s0( + k, nr, kr, sr, bl + ) + ) + + def kai_get_rhs_packed_stride_rhs_pack_nxk_qsi4c32p_qsu4c32s1s0( + k, nr, kr, sr, bl + ): + assert (bl % kr) == 0 + assert (nr % kai_nr_multiple_of) == 0 + assert (bl % kai_bl_multiple_of) == 0 + + # kr and sr are unused in the calculation + num_bytes_multiplier_rhs = kai_get_bf16_datatype_size_in_bytes() + num_blocks_per_row = kai_num_blocks_per_row(k, bl) + num_bytes_per_block = kai_num_bytes_per_block( + bl, num_bytes_multiplier_rhs + ) + + return nr * ( + (num_bytes_per_block * num_blocks_per_row) + + kai_num_bytes_sum_rhs + + kai_num_bytes_bias + ) + + # This function returns size of these datatypes stored as enum. We modify it to just return bf16 datatype + # https://gitlab.arm.com/kleidi/kleidiai/-/blob/main/kai/kai_common.h?ref_type=heads#L55 + def kai_get_bf16_datatype_size_in_bytes(): + return 2 # 2 bytes + + def kai_num_blocks_per_row(k, bl): + assert (bl % kai_bl_multiple_of) == 0 + return kai_roundup(k, bl) // bl + + def kai_num_bytes_per_block(bl, num_bytes_multiplier_rhs): + assert (bl % kai_bl_multiple_of) == 0 + return (bl // 2) + num_bytes_multiplier_rhs + + return kai_get_rhs_packed_size_rhs_pack_nxk_qsi4c32p_qsu4c32s1s0( + N, K, kai_nr, kai_kr, kai_sr, groupsize + ) + + +@register_meta([aten._dyn_quant_pack_4bit_weight]) +def meta__dyn_quant_pack_4bit_weight( + weights, scales_zeros, bias: Tensor | None, block_size, in_features, out_features +): + torch._check( + weights.dtype is torch.uint8, + lambda: f"expected w to be uint8, got {weights.dtype}", + ) + if torch.backends.kleidiai.is_available() and ( + (block_size == in_features and scales_zeros.dtype == torch.float) + or ( + block_size < in_features + and block_size % 32 == 0 + and in_features % block_size == 0 + and scales_zeros.dtype == torch.bfloat16 + ) + ): + packed_weight_size = get_kai_packed_weight_size( + 4, out_features, in_features, block_size + ) + return weights.new_empty(int(packed_weight_size), dtype=torch.uint8) + packed_weight_size = weights.numel() + scales_zeros.numel() + if bias is not None: + packed_weight_size += bias.numel() + return weights.new_empty(packed_weight_size, dtype=torch.float) + + +@register_meta([aten._dyn_quant_matmul_4bit]) +def meta__dyn_quant_matmul_4bit( + inp, + packed_weights, + block_size, + in_features, + out_features, +): + torch._check(inp.dim() == 2, lambda: "input must be a 2D tensor") + torch._check( + (inp.dtype == torch.float32) + or (inp.dtype == torch.bfloat16 and block_size == in_features), + lambda: ( + f"expected input to be f32 or bf16 (bf16 requires block_size == in_features), " + f"got {inp.dtype} with block_size={block_size} and in_features={in_features}" + ), + ) + M = inp.size(0) + return inp.new_empty(M, out_features, dtype=inp.dtype) + + +@register_meta([aten._weight_int8pack_mm]) +def meta__weight_int8pack_mm(x, w, q_scales): + torch._check(x.dim() == 2, lambda: "x must be a 2D tensor") + torch._check( + x.dtype in [torch.float32, torch.float16, torch.bfloat16], + lambda: f"expected x to be f32/f16/bf16, got {x.dtype}", + ) + torch._check(w.dim() == 2, lambda: "w must be a 2D tensor") + torch._check( + w.dtype is torch.int8, + lambda: f"expected w to be int8, got {w.dtype}", + ) + return x.new_empty(x.size(0), w.size(0), dtype=x.dtype) + + +@register_meta(aten._cdist_forward.default) +def meta_cdist_forward(x1, x2, p, compute_mode): + torch._check( + x1.dim() >= 2, + lambda: f"cdist only supports at least 2D tensors, X1 got: {x1.dim()}D", + ) + torch._check( + x2.dim() >= 2, + lambda: f"cdist only supports at least 2D tensors, X2 got: {x2.dim()}D", + ) + torch._check( + x1.size(-1) == x2.size(-1), + lambda: f"X1 and X2 must have the same number of columns. X1: {x1.size(-1)} X2: {x2.size(-1)}", + ) + torch._check( + utils.is_float_dtype(x1.dtype), + lambda: f"cdist only supports floating-point dtypes, X1 got: {x1.dtype}", + ) + torch._check( + utils.is_float_dtype(x2.dtype), + lambda: f"cdist only supports floating-point dtypes, X2 got: {x2.dtype}", + ) + torch._check(p >= 0, lambda: "cdist only supports non-negative p values") + torch._check( + compute_mode in (None, 0, 1, 2), + lambda: f"possible modes: None, 0, 1, 2, but was: {compute_mode}", + ) + r1 = x1.size(-2) + r2 = x2.size(-2) + batch_tensor1 = x1.shape[:-2] + batch_tensor2 = x2.shape[:-2] + output_shape = list(torch.broadcast_shapes(batch_tensor1, batch_tensor2)) + output_shape.extend([r1, r2]) + return x1.new_empty(output_shape) + + +@register_meta(aten._cdist_backward) +@out_wrapper() +def meta_cdist_backward(grad, x1, x2, p, cdist): + c1 = x1.shape[-1] + r1 = x1.shape[-2] + r2 = x2.shape[-2] + batch_tensor1 = x1.shape[:-2] + batch_tensor2 = x2.shape[:-2] + expand_batch_portion = list(torch.broadcast_shapes(batch_tensor1, batch_tensor2)) + tensor1_expand_size = expand_batch_portion.copy() + tensor1_expand_size.extend([r1, c1]) + batch_product = math.prod(expand_batch_portion) + if r1 == 0 or r2 == 0 or c1 == 0 or batch_product == 0: + return torch.zeros_like(x1) + if tensor1_expand_size != list(x1.shape): + x1 = x1.expand(tensor1_expand_size) + return torch.empty_like(x1, memory_format=torch.contiguous_format) + + +# NB: This meta function accepts non-meta arguments! When this behavior +# was originally introduced this was accidental, but it is now load bearing +# as people are using this so that they can conveniently test code involving +# embeddings (feeding CPU tensor inputs with meta device EmbeddingBag module) +@register_meta(aten._embedding_bag.default) +def meta_embedding_bag( + weight, + indices, + offsets, + scale_grad_by_freq=False, + mode=0, + sparse=False, + per_sample_weights=None, + include_last_offset=False, + padding_idx=-1, +): + torch._check( + indices.dtype in (torch.long, torch.int), + lambda: f"expected indices to be long or int, got {indices.dtype}", + ) + torch._check( + offsets.dtype in (torch.long, torch.int), + lambda: f"expected offsets to be long or int, got {offsets.dtype}", + ) + torch._check( + utils.is_float_dtype(weight.dtype), + lambda: f"expected weight to be floating point type, got {weight.dtype}", + ) + + num_bags = offsets.size(0) + if include_last_offset: + torch._check( + num_bags >= 1, + lambda: "include_last_offset: numBags should be at least 1", + ) + num_bags -= 1 + + output = weight.new_empty(num_bags, weight.size(1)) + + if per_sample_weights is not None: + torch._check( + mode == MODE_SUM, + lambda: "embedding_bag: per_sample_weights only supported with mode='sum'", + ) + torch._check( + per_sample_weights.ndim == 1, + lambda: f"expected per_sample_weights to be 1D tensor, got {per_sample_weights.ndim}D", + ) + torch._check( + per_sample_weights.numel() == indices.numel(), + lambda: ( + f"expected per_sample_weights.numel() ({per_sample_weights.numel()} " + f"to be the same as indices.numel() ({indices.numel()})" + ), + ) + + def is_fast_path_index_select_scale(src, scale, output, padding_idx): + return ( + is_fast_path_index_select(src, output, padding_idx) and scale.stride(0) == 1 + ) + + def is_fast_path_index_select(src, output, padding_idx): + return ( + (src.dtype == torch.float or src.dtype == torch.half) + and src.stride(1) == 1 + and output.stride(1) == 1 + and padding_idx < 0 + ) + + def is_fast_path(src, scale, output, padding_idx): + if scale is not None: + return is_fast_path_index_select_scale(src, scale, output, padding_idx) + else: + return is_fast_path_index_select(src, output, padding_idx) + + if device_hint(offsets) != "cpu": + offset2bag = indices.new_empty(indices.size(0)) + bag_size = indices.new_empty(offsets.size()) + if mode == MODE_MAX: + max_indices = indices.new_empty(num_bags, weight.size(1)) + else: + max_indices = indices.new_empty(0) + else: + fast_path_sum = is_fast_path(weight, per_sample_weights, output, padding_idx) + if mode in (MODE_MEAN, MODE_MAX) or not fast_path_sum: + offset2bag = offsets.new_empty(indices.size(0)) + else: + offset2bag = offsets.new_empty(0) + bag_size = offsets.new_empty(num_bags) + # This part of the logic comes from make_max_indices_out in EmbeddingBag.cpp + numBags = offsets.shape[0] + if mode == MODE_MAX: + if include_last_offset: + torch._check( + numBags >= 1, + lambda: "include_last_offset: numBags should be at least 1", + ) + numBags -= 1 + max_indices = offsets.new_empty(numBags, weight.shape[1]) + else: + max_indices = offsets.new_empty(bag_size.size()) + return output, offset2bag, bag_size, max_indices + + +@register_meta(aten._embedding_bag_forward_only.default) +def meta_embedding_bag_forward_only(weight, indices, offsets, *args): + output, offset2bag, bag_size, max_indices = meta_embedding_bag( + weight, indices, offsets, *args + ) + if device_hint(offsets) == "cpu": + bag_size = offsets.new_empty(offsets.size()) + return output, offset2bag, bag_size, max_indices + + +def _get_reduction_dtype(input, dtype, promote_int_to_long=True): + # if specified, dtype takes precedence + if dtype: + return dtype + + if input.dtype.is_floating_point or input.dtype.is_complex: + return input.dtype + elif promote_int_to_long: + return torch.long + + return input.dtype + + +@register_meta([aten.nansum.default, aten.nansum.out]) +@out_wrapper() +def meta_nansum(input, dims=None, keepdim=False, *, dtype=None): + output_dtype = _get_reduction_dtype(input, dtype, promote_int_to_long=True) + dims = utils.reduction_dims(input.shape, dims) + output_shape = _compute_reduction_shape(input, dims, keepdim) + return input.new_empty(output_shape, dtype=output_dtype) + + +@register_meta([aten.median.default, aten.nanmedian.default]) +def meta_median(input): + output_shape = utils.compute_reduction_output_shape( + input.shape, tuple(range(input.dim())) + ) + return input.new_empty(output_shape) + + +@register_meta( + [ + aten.median.dim, + aten.median.dim_values, + aten.nanmedian.dim, + aten.nanmedian.dim_values, + aten.mode.default, + aten.mode.values, + ] +) +@out_wrapper("values", "indices") +def meta_median_mode_dim(input, dim=-1, keepdim=False): + if device_hint(input) == "cuda": + utils.alert_not_deterministic("median CUDA with indices output") + dim = utils.reduction_dims(input.shape, (dim,)) + output_shape = _compute_reduction_shape(input, dim, keepdim) + return ( + input.new_empty(output_shape), + input.new_empty(output_shape, dtype=torch.long), + ) + + +@register_meta(aten.logical_not_.default) +def meta_logical_not_(self): + return self + + +@register_meta(aten.repeat.default) +def meta_repeat(self, repeats): + torch._check( + len(repeats) >= self.dim(), + lambda: "Number of dimensions of repeat dims can not be smaller than number of dimensions of tensor", + ) + for i, rep in enumerate(repeats): + torch._check( + rep >= 0, + lambda: f"Repeats cannot be negative, found {rep} at index {i}", + ) + # Add new leading dimensions to the tensor if the + # number of target dimensions is larger than the + # number of source dimensions. + num_new_dimensions = len(repeats) - self.dim() + padded_size = (1,) * num_new_dimensions + tuple(self.shape) + target_size = [padded_size[i] * repeats[i] for i in range(len(repeats))] + return self.new_empty(target_size) + + +@register_meta(aten.zero_.default) +def meta_zero_(self): + return self + + +@register_meta( + [ + aten.mul_.Scalar, + aten.div_.Scalar, + aten.mul_.Tensor, + aten.div_.Tensor, + aten.logical_and_.default, + aten.logical_or_.default, + aten.logical_xor_.default, + ], +) +def meta_binop_inplace(self, other): + if isinstance(other, torch.Tensor): + check_inplace_broadcast(self.shape, other.shape) + return self + + +@register_meta( + [ + aten.add_.Scalar, + aten.sub_.Scalar, + aten.add_.Tensor, + aten.sub_.Tensor, + ], +) +def meta_binop_inplace_alpha(self, other, alpha=1): + """ + Some checks for inplace ops. + Checks for promotion rules for some dtypes. + int.add/sub_(float) and bool.add/sub_(others) are rejected. + Promoting in these in-place operations would require reallocating + and copying over elements, hence not allowed. + Checks for alpha param. + """ + + def is_integeric(arg): + if isinstance(arg, TensorLike): + return utils.is_integer_dtype(arg.dtype) + else: + return isinstance(arg, IntLike) + + def is_floatic(arg): + if isinstance(arg, TensorLike): + return utils.is_float_dtype(arg.dtype) + else: + return isinstance(arg, FloatLike) + + def is_booleanic(arg): + if isinstance(arg, TensorLike): + return utils.is_boolean_dtype(arg.dtype) + else: + return isinstance(arg, BoolLike) + + # Do not allow int+float->int in-place + if is_integeric(self) and is_floatic(other): + raise RuntimeError( + "Promotion of int.add/sub_(float) in in-place ops are not possible due to element size change." + ) + + # Do not allow bool+other->bool in-place + if is_booleanic(self) and not is_booleanic(other): + raise RuntimeError( + "Promotion of book.add/sub_(others) in in-place ops are not possible due to element size change." + ) + + if isinstance(other, torch.Tensor): + check_inplace_broadcast(self.shape, other.shape) + return self + + +@register_meta( + [ + aten.add.Scalar, + aten.sub.Scalar, + ], +) +def meta_binop_alpha(self, other, alpha=1): + return elementwise_meta( + self, other, type_promotion=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT + ) + + +@register_meta([aten.round.default, aten.round.decimals]) +def meta_round(self, **kwargs): + return elementwise_meta( + self, type_promotion=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT + ) + + +def shift_dtype_check(fn_name, self, val): + torch._check( + utils.is_integer_dtype(self.dtype), + lambda: f"{fn_name}: Expected input tensor to have an integral dtype. Got {self.dtype}", + ) + if isinstance(val, torch.Tensor): + torch._check( + utils.is_integer_dtype(val.dtype), + lambda: f"{fn_name}: Expected shift value to have an integral dtype. Got {val.dtype}", + ) + else: + torch._check( + isinstance(val, IntLike), + lambda: f"{fn_name}: Expected shift value to be an int. Got {val}", + ) + + +@register_meta([aten.__rshift__.Tensor, aten.__rshift__.Scalar]) +def meta_rshifts(self, other): + shift_dtype_check("rshift", self, other) + return elementwise_meta( + self, other, type_promotion=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT + ) + + +@register_meta([aten.__lshift__.Tensor, aten.__lshift__.Scalar]) +def meta_lshifts(self, other): + shift_dtype_check("lshift", self, other) + return elementwise_meta( + self, other, type_promotion=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT + ) + + +@register_meta(aten.zero.default) +def meta_zero(self): + return self.new_empty(self.shape) + + +@register_meta([aten.fill_.Tensor, aten.fill_.Scalar]) +def meta_fill_(self, val): + return self + + +@register_meta([aten.fill.Tensor, aten.fill.Scalar]) +def meta_fill(self, val): + return torch.empty_like(self) + + +@register_meta(aten.relu_.default) +def meta_relu_(self): + return self + + +@register_meta(aten._add_relu.Tensor) +@out_wrapper() +def meta__add_relu(self, other, alpha=1) -> Tensor: + return elementwise_meta( + self, other, type_promotion=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT + ) + + +@register_meta([aten.rrelu_with_noise]) +@out_wrapper() +def meta_rrelu_with_noise( + self, noise, lower=0.125, upper=0.3333333333333333, training=False, generator=None +): + return torch.empty_like(self) + + +@register_meta([aten.rrelu_with_noise_functional]) +def meta_rrelu_with_noise_functional( + self, noise, lower=0.125, upper=0.3333333333333333, training=False, generator=None +): + return torch.empty_like(self), torch.empty_like(noise) + + +@register_meta([aten.rrelu_with_noise_]) +def meta_rrelu_with_noise_( + self, lower=0.125, upper=0.3333333333333333, training=False, generator=None +): + return self + + +@register_meta([aten.index_put.default, aten._unsafe_index_put.default]) +def meta_index_put(self, indices, values, accumulate=False): + return torch.empty_like(self) + + +@register_meta(aten.masked_fill_.Scalar) +def meta_masked_fill_(self, mask, value): + check_inplace_broadcast(self.shape, mask.shape) + return self + + +@register_meta(aten._masked_scale.default) +def meta__masked_scale(self, mask, scale): + masked_scale = self.new_empty(self.size()).to( + memory_format=utils.suggest_memory_format(self) + ) + return masked_scale + + +@register_meta(aten.masked_scatter_) +def meta_masked_scatter_(self, mask, source): + torch._check( + mask.dtype in (torch.bool, torch.uint8), lambda: "Mask must be bool or uint8" + ) + torch._check( + self.dtype == source.dtype, + lambda: "masked_scatter: expected self and source to have same " + f"dtypes but got {self.dtype} and {source.dtype}", + ) + return self + + +@register_meta(aten.masked_scatter) +@out_wrapper() +def meta_masked_scatter(self, mask, source): + self, mask = _maybe_broadcast(self, mask) + output = torch.empty_like(self, memory_format=torch.contiguous_format) + return meta_masked_scatter_(output, mask, source) + + +@register_meta(aten.masked_scatter_backward) +def meta_masked_scatter_backward(self, mask, sizes): + return self.new_empty(sizes) + + +@register_meta(aten.index_put_.default) +def meta_index_put_(self, indices, values, accumulate=False): + return self + + +def common_meta_baddbmm_bmm(batch1, batch2, is_bmm, self_baddbmm=None, out_dtype=None): + from torch.fx.experimental.symbolic_shapes import sym_and, sym_eq + + torch._check(batch1.dim() == 3, lambda: "batch1 must be a 3D tensor") + torch._check(batch2.dim() == 3, lambda: "batch2 must be a 3D tensor") + + batch1_sizes = batch1.size() + batch2_sizes = batch2.size() + + bs = batch1_sizes[0] + contraction_size = batch1_sizes[2] + res_rows = batch1_sizes[1] + res_cols = batch2_sizes[2] + output_size = (bs, res_rows, res_cols) + + torch._check( + sym_and(sym_eq(batch2_sizes[0], bs), sym_eq(batch2_sizes[1], contraction_size)), + lambda: f"Expected size for first two dimensions of batch2 tensor to be: [{bs}" + f", {contraction_size}] but got: [{batch2_sizes[0]}, {batch2_sizes[1]}].", + ) + if out_dtype: + supported_out_dtype = ( + batch1.dtype == torch.float16 or batch1.dtype == torch.bfloat16 + ) and out_dtype == torch.float32 + torch._check( + out_dtype == batch1.dtype or supported_out_dtype, + lambda: "out_dtype only supported for torch.float32 output with float16/bfloat16 inputs or same as input dtypes", + ) + output = batch2.new_empty(output_size).to(out_dtype) + else: + # TODO: handle out + output = batch2.new_empty(output_size) + + if not is_bmm and self_baddbmm is not None: + torch._check(self_baddbmm.dim() == 3, lambda: "self must be a 3D tensor") + torch._check( + sym_eq(self_baddbmm.size(), output_size), + lambda: f"Expected an input tensor shape with shape {output_size} but got shape: {self_baddbmm.size()}", + ) + + return output + + +@register_meta(aten.bmm.default) +def meta_bmm(self, mat2): + return common_meta_baddbmm_bmm(self, mat2, True) + + +@register_meta(aten.bmm.dtype) +def meta_bmm_dtype(self, mat2, out_dtype): + return common_meta_baddbmm_bmm(self, mat2, True, out_dtype=out_dtype) + + +def div_rtn(x, y): + q = x // y + r = x % y + # WARNING: explicit bool conversion here is necessary; + # would be fixed by SymBool + if r != 0 and (bool(r < 0) != bool(y < 0)): + q -= 1 + return q + + +def pooling_output_shape_pad_lr( + inputSize, + kernelSize, + pad_l, + pad_r, + stride, + dilation, + ceil_mode, +): + outputSize = ( + div_rtn( + inputSize + + pad_l + + pad_r + - dilation * (kernelSize - 1) + - 1 + + (stride - 1 if ceil_mode else 0), + stride, + ) + + 1 + ) + if ceil_mode: + if (outputSize - 1) * stride >= inputSize + pad_l: + outputSize -= 1 + return outputSize + + +def pooling_output_shape(inputSize, kernelSize, pad, stride, dilation, ceil_mode): + torch._check(stride != 0, lambda: "stride should not be zero") + torch._check(pad >= 0, lambda: f"pad must be non-negative, but got pad: {pad}") + torch._check( + pad <= ((kernelSize - 1) * dilation + 1) // 2, + lambda: ( + f"pad should be at most half of effective kernel size, but got pad={pad}, " + f"kernel_size={kernelSize} and dilation={dilation}" + ), + ) + return pooling_output_shape_pad_lr( + inputSize, kernelSize, pad, pad, stride, dilation, ceil_mode + ) + + +def pool2d_shape_check( + input, + kH, + kW, + dH, + dW, + padH, + padW, + dilationH, + dilationW, + nInputPlane, + inputHeight, + inputWidth, + outputHeight, + outputWidth, + memory_format, +): + ndim = input.dim() + nOutputPlane = nInputPlane + + torch._check( + kW > 0 and kH > 0, + lambda: f"kernel size should be greater than zero, but got kH: {kH}, kW: {kW}", + ) + torch._check( + dW > 0 and dH > 0, + lambda: f"stride should be greater than zero, but got dH: {dH}, dW: {dW}", + ) + torch._check( + dilationH > 0 and dilationW > 0, + lambda: f"dilation should be greater than zero, but got dilationH: {dilationH}, dilationW: {dilationW}", + ) + + valid_dims = input.size(1) != 0 and input.size(2) != 0 + + if memory_format == torch.channels_last: + torch._check( + ndim == 4 and valid_dims and input.size(3) != 0, + lambda: "Expected 4D (batch mode) tensor expected for input with channels_last layout" + f" with optional 0 dim batch size for input, but got: {input.size()}", + ) + else: + torch._check( + (ndim == 3 and input.size(0) != 0 and valid_dims) + or (ndim == 4 and valid_dims and input.size(3) != 0), + lambda: f"Expected 3D or 4D (batch mode) tensor with optional 0 dim batch size for input, but got: {input.size()}", + ) + + torch._check( + kW // 2 >= padW and kH // 2 >= padH, + lambda: "pad should be smaller than or equal to half of kernel size, but got " + f"padW = {padW}, padH = {padH}, kW = {kW}, kH = {kH}", + ) + + torch._check( + outputWidth >= 1 and outputHeight >= 1, + lambda: f"Given input size: ({nInputPlane}x{inputHeight}x{inputWidth}). " + f"Calculated output size: ({nOutputPlane}x{outputHeight}x{outputWidth}). " + "Output size is too small", + ) + + +def pool3d_shape_check( + input: Tensor, + nslices: int, + kT: int, + kH: int, + kW: int, + dT: int, + dH: int, + dW: int, + pT: int, + pH: int, + pW: int, + dilationT: int, + dilationH: int, + dilationW: int, + itime: int, + iheight: int, + iwidth: int, + otime: int, + oheight: int, + owidth: int, + fn_name: str, + check_input_size: bool = False, +): + ndim = input.ndim + + torch._check( + kT > 0 and kW > 0 and kH > 0, + lambda: ( + f"kernel size should be greater than zero, but got " + f"kT: {kT}, kH: {kH}, kW: {kW}" + ), + ) + torch._check( + dT > 0 and dW > 0 and dH > 0, + lambda: ( + f"stride should be greater than zero, but got dT: {dT}, dH: {dH}, dW: {dW}" + ), + ) + torch._check( + dilationT > 0 and dilationW > 0 and dilationH > 0, + lambda: ( + f"dilation should be greater than zero, but got " + f"dilationT: {dilationT}, dilationH: {dilationH}, dilationW: {dilationW}" + ), + ) + + torch._check( + ndim in (4, 5), + lambda: f"{fn_name}: Expected 4D or 5D tensor for input, but got: {input.shape}", + ) + + for i in range(ndim): + if ndim == 5 and i == 0: + # size of batch-dim can be 0. + continue + torch._check( + input.size(i) > 0, + lambda: ( + f"{fn_name}: Expected input's non-batch dimensions to have positive length," + f" but input has a shape of {input.shape}" + f" and non-batch dimension {input.size(i)} has length zero!" + ), + ) + + if check_input_size: # AveragePool3d + torch._check( + itime >= kT and iheight >= kH and iwidth >= kW, + lambda: ( + f"input image (T: {itime} H: {iheight} W: {iwidth}) smaller than " + f"kernel size (kT: {kT} kH: {kH} kW: {kW})" + ), + ) + + torch._check( + kT / 2 >= pT and kW / 2 >= pW and kH / 2 >= pH, + lambda: ( + f"pad should be smaller than or equal to half of kernel size, but got " + f"kT: {kT} kW: {kW} kH: {kH} padT: {pT} padW: {pW} padH: {pH}" + ), + ) + + torch._check( + otime >= 1 and owidth >= 1 and oheight >= 1, + lambda: ( + f"Given input size: ({nslices}x{itime}x{iheight}x{iwidth}). " + f"Calculated output size: ({nslices}x{otime}x{oheight}x{owidth}). " + f"Output size is too small" + ), + ) + + +def max_pool3d_backward_shape_check( + input, + grad_output, + indices, + nslices, + kT, + kH, + kW, + dT, + dH, + dW, + pT, + pH, + pW, + dilationT, + dilationH, + dilationW, + itime, + iheight, + iwidth, + otime, + oheight, + owidth, + fn_name, +): + ndim = input.ndim + + pool3d_shape_check( + input, + nslices, + kT, + kH, + kW, + dT, + dH, + dW, + pT, + pH, + pW, + dilationT, + dilationH, + dilationW, + itime, + iheight, + iwidth, + otime, + oheight, + owidth, + fn_name, + ) + + check_dim_size(grad_output, ndim, ndim - 4, nslices) + check_dim_size(grad_output, ndim, ndim - 3, otime) + check_dim_size(grad_output, ndim, ndim - 2, oheight) + check_dim_size(grad_output, ndim, ndim - 1, owidth) + + check_dim_size(indices, ndim, ndim - 4, nslices) + check_dim_size(indices, ndim, ndim - 3, otime) + check_dim_size(indices, ndim, ndim - 2, oheight) + check_dim_size(indices, ndim, ndim - 1, owidth) + + +def avg_pool3d_backward_shape_check( + input: Tensor, + grad_output: Tensor, + nslices: int, + kT: int, + kH: int, + kW: int, + dT: int, + dH: int, + dW: int, + pT: int, + pH: int, + pW: int, + itime: int, + iheight: int, + iwidth: int, + otime: int, + oheight: int, + owidth: int, + fn_name: str, +): + ndim = input.ndim + + pool3d_shape_check( + input, + nslices, + kT, + kH, + kW, + dT, + dH, + dW, + pT, + pH, + pW, + 1, + 1, + 1, + itime, + iheight, + iwidth, + otime, + oheight, + owidth, + fn_name, + True, + ) + + check_dim_size(grad_output, ndim, ndim - 4, nslices) + check_dim_size(grad_output, ndim, ndim - 3, otime) + check_dim_size(grad_output, ndim, ndim - 2, oheight) + check_dim_size(grad_output, ndim, ndim - 1, owidth) + + +def max_pool2d_checks_and_compute_shape( + input, + kernel_size, + stride, + padding, + dilation, + ceil_mode, +): + # Reference: aten/src/ATen/native/DilatedMaxPool2d.cpp + def unpack(name, val): + torch._check( + len(val) in [1, 2], + lambda: f"max_pool2d: {name} must either be a single int, or a tuple of two ints", + ) + H = val[0] + W = H if len(val) == 1 else val[1] + return H, W + + kH, kW = unpack("kernel_size", kernel_size) + + torch._check( + len(stride) in [0, 1, 2], + lambda: "max_pool2d: stride must either be omitted, a single int, or a tuple of two ints", + ) + if len(stride) == 0: + dH, dW = kH, kW + else: + dH, dW = unpack("stride", stride) + + padH, padW = unpack("padding", padding) + dilationH, dilationW = unpack("dilation", dilation) + nInputPlane = input.size(-3) + inputHeight = input.size(-2) + inputWidth = input.size(-1) + + memory_format = utils.suggest_memory_format(input) + if memory_format == torch.channels_last: + torch._check( + input.dim() == 4, + lambda: "non-empty 4D (batch mode) tensor expected for input with channels_last layout", + ) + elif memory_format == torch.contiguous_format: + torch._check( + input.dim() in [3, 4], + lambda: "non-empty 3D or 4D (batch mode) tensor expected for input", + ) + else: + torch._check( + False, + lambda: "Unsupported memory format. Supports only ChannelsLast, Contiguous", + ) + + outputHeight = pooling_output_shape(inputHeight, kH, padH, dH, dilationH, ceil_mode) + outputWidth = pooling_output_shape(inputWidth, kW, padW, dW, dilationW, ceil_mode) + + pool2d_shape_check( + input, + kH, + kW, + dH, + dW, + padH, + padW, + dilationH, + dilationW, + nInputPlane, + inputHeight, + inputWidth, + outputHeight, + outputWidth, + memory_format, + ) + + return nInputPlane, outputHeight, outputWidth + + +@register_meta(aten.max_pool2d_with_indices_backward.default) +def meta_max_pool2d_with_indices_backward( + grad_output, + self, + kernel_size, + stride, + padding, + dilation, + ceil_mode, + indices, +): + ( + nInputPlane, + outputHeight, + outputWidth, + ) = max_pool2d_checks_and_compute_shape( + self, kernel_size, stride, padding, dilation, ceil_mode + ) + + torch._check( + self.dtype == grad_output.dtype, + lambda: f"Expected dtype {self.dtype} for `gradOutput` but got dtype {grad_output.dtype}", + ) + + nOutputPlane = nInputPlane + ndim = self.ndim + + def _check_dim_size(t): + check_dim_size(t, ndim, ndim - 3, nOutputPlane) + check_dim_size(t, ndim, ndim - 2, outputHeight) + check_dim_size(t, ndim, ndim - 1, outputWidth) + + _check_dim_size(grad_output) + _check_dim_size(indices) + + memory_format = utils.suggest_memory_format(self) + return torch.empty( + self.shape, + dtype=self.dtype, + device=self.device, + memory_format=memory_format, + ) + + +@register_meta(aten.max_pool2d_with_indices.default) +def meta_max_pool2d_with_indices( + input, + kernel_size, + stride=(), + padding=(0,), + dilation=(1,), + ceil_mode=False, +): + ( + nInputPlane, + outputHeight, + outputWidth, + ) = max_pool2d_checks_and_compute_shape( + input, kernel_size, stride, padding, dilation, ceil_mode + ) + + nbatch = input.size(-4) if input.dim() == 4 else 1 + memory_format = utils.suggest_memory_format(input) + if input.dim() == 3: + size = [nInputPlane, outputHeight, outputWidth] + else: + size = [nbatch, nInputPlane, outputHeight, outputWidth] + return ( + torch.empty( + size, + dtype=input.dtype, + device=input.device, + memory_format=memory_format, + ), + torch.empty( + size, + dtype=torch.int64, + device=input.device, + memory_format=memory_format, + ), + ) + + +@register_meta(aten.fractional_max_pool2d.default) +def meta_fractional_max_pool2d(self, kernel_size, output_size, random_samples): + torch._check( + self.ndim in (3, 4), + lambda: f"fractional_max_pool2d: Expected 3D or 4D tensor, but got: {self.ndim}", + ) + ndim = self.ndim + + for d in range(ndim - 3, ndim): + torch._check( + self.size(d) > 0, + lambda: f"fractional_max_pool2d: Expected input to have non-zero " + f" size for non-batch dimensions, but got {self.size()} with dimension {d} empty", + ) + + # the check and message are out of sync, but this matches the structured meta + torch._check( + len(kernel_size) == 2, + lambda: "fractional_max_pool2d: kernel_size must" + "either be a single int or tuple of Ints", + ) + torch._check( + len(output_size) == 2, + lambda: "fractional_max_pool2d: output_size must " + "either be a single int or tuple of Ints", + ) + + input_channels = self.size(-3) + input_height = self.size(-2) + input_width = self.size(-1) + if ndim == 4: + input_batch = self.size(0) + else: + input_batch = 1 + + torch._check( + self.dtype == random_samples.dtype, + lambda: "Expect _random_samples to have the same dtype as input", + ) + torch._check( + random_samples.ndim == 3, + lambda: f"Expect _random samples to have 3 dimensions got, {random_samples.ndim}", + ) + + n = random_samples.size(0) + c = random_samples.size(1) + d = random_samples.size(2) + torch._check( + n >= input_batch, + lambda: "Expect _random_samples.size(0) no less then input batch size.", + ) + torch._check( + c == input_channels, + lambda: "Expect _random_samples.size(1) equals to input channel size.", + ) + torch._check(d == 2, lambda: f"Expect _random_samples.size(2) equals to 2 got {d}.") + + torch._check( + output_size[0] + kernel_size[0] - 1 <= input_height, + lambda: f"fractional_max_pool2d: kernel height {kernel_size[0]} is too large relative to input height {input_height}", + ) + torch._check( + output_size[1] + kernel_size[1] - 1 <= input_width, + lambda: f"fractional_max_pool2d: kernel width {kernel_size[1]} is too large relative to input width {input_width}", + ) + + if self.dim() == 4: + size = [input_batch, input_channels, output_size[0], output_size[1]] + else: + size = [input_channels, output_size[0], output_size[1]] + + return ( + torch.empty( + size, + dtype=self.dtype, + device=self.device, + ), + torch.empty( + size, + dtype=torch.int64, + device=self.device, + ), + ) + + +@register_meta(aten.max_pool3d_with_indices) +@out_wrapper("out", "indices") +def meta_max_pool3d_with_indices( + input, + kernel_size, + stride=(), + padding=(0,), + dilation=(1,), + ceil_mode=False, +): + torch._check( + len(kernel_size) in (1, 3), + lambda: "max_pool3d: kernel_size must either be a single int, or a tuple of three ints", + ) + kT = kernel_size[0] + kH = kT if len(kernel_size) == 1 else kernel_size[1] + kW = kT if len(kernel_size) == 1 else kernel_size[2] + + torch._check( + not stride or len(stride) in (1, 3), + lambda: "max_pool3d: stride must either be omitted, a single int, or a tuple of three ints", + ) + dT = kT if not stride else stride[0] + dH = kH if not stride else (dT if len(stride) == 1 else stride[1]) + dW = kW if not stride else (dT if len(stride) == 1 else stride[2]) + + torch._check( + len(padding) in (1, 3), + lambda: "max_pool3d: padding must either be a single int, or a tuple of three ints", + ) + pT = padding[0] + pH = pT if len(padding) == 1 else padding[1] + pW = pT if len(padding) == 1 else padding[2] + + torch._check( + len(dilation) in (1, 3), + lambda: "max_pool3d: dilation must be either a single int, or a tuple of three ints", + ) + dilationT = dilation[0] + dilationH = dilationT if len(dilation) == 1 else dilation[1] + dilationW = dilationT if len(dilation) == 1 else dilation[2] + + torch._check( + input.ndim in (4, 5), + lambda: "non-empty 4D or 5D (batch mode) tensor expected for input", + ) + + nbatch = input.size(-5) if input.ndim == 5 else 1 + nslices = input.size(-4) + itime = input.size(-3) + iheight = input.size(-2) + iwidth = input.size(-1) + + otime = pooling_output_shape(itime, kT, pT, dT, dilationT, ceil_mode) + oheight = pooling_output_shape(iheight, kH, pH, dH, dilationH, ceil_mode) + owidth = pooling_output_shape(iwidth, kW, pW, dW, dilationW, ceil_mode) + + pool3d_shape_check( + input, + nslices, + kT, + kH, + kW, + dT, + dH, + dW, + pT, + pH, + pW, + dilationT, + dilationH, + dilationW, + itime, + iheight, + iwidth, + otime, + oheight, + owidth, + "max_pool3d_with_indices()", + ) + + channels_last = ( + input.ndim == 5 and utils.suggest_memory_format(input) == torch.channels_last_3d + ) + if input.ndim == 4: + input_channels_last_check = input.unsqueeze(0) + channels_last = ( + not input_channels_last_check.is_contiguous() + ) and input_channels_last_check.is_contiguous( + memory_format=torch.channels_last_3d + ) + out_shape = (nslices, otime, oheight, owidth) + else: + out_shape = (nbatch, nslices, otime, oheight, owidth) # type: ignore[assignment] + + out = input.new_empty(out_shape) + indices = input.new_empty(out_shape, dtype=torch.int64) + + if channels_last: + out = out.to(memory_format=torch.channels_last_3d) + indices = indices.to(memory_format=torch.channels_last_3d) + + return out, indices + + +@register_meta(aten.max_pool3d_with_indices_backward) +@out_wrapper("grad_input") +def meta_max_pool3d_with_indices_backward( + grad_output, + input, + kernel_size, + stride, + padding, + dilation, + ceil_mode, + indices, +): + torch._check( + len(kernel_size) in (1, 3), + lambda: "max_pool3d: kernel_size must either be a single int, or a tuple of three ints", + ) + kT = kernel_size[0] + kH = kT if len(kernel_size) == 1 else kernel_size[1] + kW = kT if len(kernel_size) == 1 else kernel_size[2] + + torch._check( + not stride or len(stride) in (1, 3), + lambda: "max_pool3d: stride must either be omitted, a single int, or a tuple of three ints", + ) + dT = kT if not stride else stride[0] + dH = kH if not stride else (dT if len(stride) == 1 else stride[1]) + dW = kW if not stride else (dT if len(stride) == 1 else stride[2]) + + torch._check( + len(padding) in (1, 3), + lambda: "max_pool3d: padding must either be a single int, or a tuple of three ints", + ) + pT = padding[0] + pH = pT if len(padding) == 1 else padding[1] + pW = pT if len(padding) == 1 else padding[2] + + torch._check( + len(dilation) in (1, 3), + lambda: "max_pool3d: dilation must be either a single int, or a tuple of three ints", + ) + dilationT = dilation[0] + dilationH = dilationT if len(dilation) == 1 else dilation[1] + dilationW = dilationT if len(dilation) == 1 else dilation[2] + + torch._check( + input.ndim in (4, 5), + lambda: "non-empty 4D or 5D (batch mode) tensor expected for input", + ) + + nslices = input.size(-4) + itime = input.size(-3) + iheight = input.size(-2) + iwidth = input.size(-1) + + otime = grad_output.size(-3) + oheight = grad_output.size(-2) + owidth = grad_output.size(-1) + + max_pool3d_backward_shape_check( + input, + grad_output, + indices, + nslices, + kT, + kH, + kW, + dT, + dH, + dW, + pT, + pH, + pW, + dilationT, + dilationH, + dilationW, + itime, + iheight, + iwidth, + otime, + oheight, + owidth, + "max_pool3d_with_indices_backward()", + ) + + channels_last = ( + input.ndim == 5 and utils.suggest_memory_format(input) == torch.channels_last_3d + ) + if input.ndim == 4: + input_channels_last_check = input.unsqueeze(0) + channels_last = ( + not input_channels_last_check.is_contiguous() + ) and input_channels_last_check.is_contiguous( + memory_format=torch.channels_last_3d + ) + + grad_input = input.new_empty(input.shape) + + if channels_last: + grad_input = grad_input.to(memory_format=torch.channels_last_3d) + + return grad_input + + +def check_grid_sampler_common(input: Tensor, grid: Tensor): + torch._check( + input.device == grid.device, + lambda: ( + f"grid_sampler(): expected input and grid to be on same device, but input " + f"is on {input.device} and grid is on {grid.device}" + ), + ) + torch._check( + input.layout == torch.strided and grid.layout == torch.strided, + lambda: ( + f"grid_sampler(): expected input and grid to have torch.strided layout, but " + f"input has {input.layout} and grid has {grid.layout}" + ), + ) + torch._check( + input.shape[0] == grid.shape[0], + lambda: ( + f"grid_sampler(): expected grid and input to have same batch size, but got " + f"input with sizes {input.shape} and grid with sizes {grid.shape}" + ), + ) + torch._check( + grid.shape[-1] == input.ndim - 2, + lambda: ( + f"grid_sampler(): expected grid to have size {input.ndim - 2} in last " + f"dimension, but got grid with sizes {grid.shape}" + ), + ) + + for i in range(2, input.ndim): + torch._check( + input.shape[i] > 0, + lambda: ( + f"grid_sampler(): expected input to have non-empty spatial dimensions, " + f"but input has sizes {input.shape} with dimension {i} being empty" + ), + ) + + +class GridSamplerInterpolation(Enum): + BILINEAR = 0 + NEAREST = 1 + BICUBIC = 2 + + +def check_grid_sampler_3d(input: Tensor, grid: Tensor, interpolation_mode: int): + torch._check( + input.ndim == 5 and input.ndim == grid.ndim, + lambda: ( + f"grid_sampler(): expected 5D input and grid with same number of " + f"dimensions, but got input with sizes {input.shape}" + f" and grid with sizes {grid.shape}" + ), + ) + torch._check( + not ( + input.ndim == 5 + and interpolation_mode == GridSamplerInterpolation.BICUBIC.value + ), + lambda: "grid_sampler(): bicubic interpolation only supports 4D input", + ) + + +@register_meta(aten.grid_sampler_2d_backward.default) +def grid_sampler_2d_backward_meta( + grad_output, + input, + grid, + interpolation_mode, + padding_mode, + align_corners, + output_mask, +): + input_requires_grad = output_mask[0] + if input_requires_grad: + grad_input = torch.zeros_like(input, memory_format=torch.contiguous_format) + else: + grad_input = None + grad_grid = torch.empty_like(grid, memory_format=torch.contiguous_format) + return (grad_input, grad_grid) + + +@register_meta(aten.grid_sampler_3d) +@out_wrapper() +def grid_sampler_3d( + input, + grid, + interpolation_mode, + padding_mode, + align_corners, +): + check_grid_sampler_common(input, grid) + check_grid_sampler_3d(input, grid, interpolation_mode) + N = input.shape[0] + C = input.shape[1] + out_D = grid.shape[1] + out_H = grid.shape[2] + out_W = grid.shape[3] + return input.new_empty((N, C, out_D, out_H, out_W)) + + +@register_meta(aten.grid_sampler_3d_backward) +@out_wrapper("grad_input", "grad_grid") +def grid_sampler_3d_backward( + grad_output, + input, + grid, + interpolation_mode, + padding_mode, + align_corners, + output_mask, +): + check_grid_sampler_common(input, grid) + check_grid_sampler_3d(input, grid, interpolation_mode) + input_requires_grad = output_mask[0] + if input_requires_grad: + grad_input = torch.zeros_like( + input, memory_format=torch.legacy_contiguous_format + ) + else: + grad_input = None + grad_grid = torch.empty_like(grid, memory_format=torch.legacy_contiguous_format) + return grad_input, grad_grid + + +@register_meta([aten.full.default]) +def full(size, fill_value, *args, **kwargs): + dtype = kwargs.get("dtype") + if not dtype: + dtype = utils.get_dtype(fill_value) + kwargs["dtype"] = dtype + # pyrefly: ignore [not-iterable] + return torch.empty(size, *args, **kwargs) + + +# zeros_like is special cased to work for sparse +@register_meta(aten.zeros_like.default) +def zeros_like( + self, + dtype=None, + layout=None, + device=None, + pin_memory=None, + memory_format=None, +): + if layout == torch.sparse_coo: + torch._check( + memory_format is None, + lambda: "memory format option is only supported by strided tensors", + ) + + res = torch.empty( + 0, + dtype=self.dtype if dtype is None else dtype, + layout=layout, + device=self.device if device is None else device, + pin_memory=pin_memory, + ) + + if self.is_sparse: + res.sparse_resize_and_clear_( + self.size(), self.sparse_dim(), self.dense_dim() + ) + else: + res.sparse_resize_and_clear_(self.size(), self.dim(), 0) + + res._coalesced_(True) + return res + res = aten.empty_like.default( + self, + dtype=dtype, + layout=layout, + device=device, + pin_memory=pin_memory, + memory_format=memory_format, + ) + # device can be not "meta" + res.fill_(0) + return res + + +@register_meta([aten.ones.default, aten.ones.out]) +@out_wrapper() +def meta_ones( + size, + *, + dtype=None, + layout=None, + device=None, + pin_memory=None, + requires_grad=False, +): + if dtype is None: + dtype = torch.get_default_dtype() + if device is None: + device = torch.get_default_device() + if layout is None: + layout = torch.strided + return torch.empty( + size, dtype=dtype, layout=layout, device=device, pin_memory=pin_memory + ) + + +@register_meta([aten.zeros.default, aten.zeros.out]) +@out_wrapper() +def meta_zeros( + size, + *, + dtype=None, + layout=None, + device=None, + pin_memory=None, + requires_grad=False, +): + if dtype is None: + dtype = torch.get_default_dtype() + if device is None: + device = torch.get_default_device() + if layout is None: + layout = torch.strided + return torch.empty( + size, dtype=dtype, layout=layout, device=device, pin_memory=pin_memory + ) + + +@register_meta(aten.select_scatter.default) +def meta_select_scatter(self, src, dim, index): + return utils.clone_preserve_strides(self) + + +@register_meta(aten.slice_scatter.default) +def meta_slice_scatter(self, src, dim=0, start=None, end=None, step=1): + return utils.clone_preserve_strides(self) + + +# TODO: Deduplicate this with canonicalize_dim +def maybe_wrap_dim(dim: int, dim_post_expr: int, wrap_scalar: bool = True): + if dim_post_expr <= 0: + assert wrap_scalar + dim_post_expr = 1 + min = -dim_post_expr + max = dim_post_expr - 1 + assert not (dim < min or dim > max), f"dim {dim} out of bounds ({min}, {max})" + if dim < 0: + dim += dim_post_expr + return dim + + +def ensure_nonempty_size(t, dim): + return 1 if t.dim() == 0 else t.shape[dim] + + +# From aten/src/ATen/native/ScatterGatherChecks.h +def gather_shape_check(self, dim, index): + self_dims = max(self.dim(), 1) + index_dims = max(index.dim(), 1) + torch._check( + self_dims == index_dims, + lambda: "Index tensor must have the same number of dimensions as input tensor", + ) + for i in range(self_dims): + if i != dim: + torch._check( + ensure_nonempty_size(index, i) <= ensure_nonempty_size(self, i), + lambda: f"Size does not match at dimension {i} expected index {index.shape}" + + f" to be no larger than self {self.shape} apart from dimension {dim}", + ) + + +@register_meta(aten.gather.default) +def meta_gather(self, dim, index, sparse_grad=False): + from torch.fx.experimental.symbolic_shapes import guard_or_false + + wrapped_dim = maybe_wrap_dim(dim, self.dim()) + is_index_empty = guard_or_false(index.numel() == 0) + if not is_index_empty: + torch._check( + index.dtype == torch.long or index.dtype == torch.int, + lambda: f"gather(): Expected dtype int32/int64 for index, but got {index.dtype}", + ) + gather_shape_check(self, wrapped_dim, index) + return self.new_empty(index.shape) + + +# From aten/src/ATen/native/TensorAdvancedIndexing.cpp +def get_operator_enum(reduce_, use_new_options=False): + if use_new_options: + if reduce_ == "sum": + return "REDUCE_ADD" + elif reduce_ == "prod": + return "REDUCE_MULTIPLY" + elif reduce_ == "mean": + return "REDUCE_MEAN" + elif reduce_ == "amax": + return "REDUCE_MAXIMUM" + elif reduce_ == "amin": + return "REDUCE_MINIMUM" + torch._check( + False, + lambda: "reduce argument must be either sum, prod, mean, amax or amin.", + ) + return + else: + if reduce_ == "add": + return "REDUCE_ADD" + elif reduce_ == "multiply": + return "REDUCE_MULTIPLY" + torch._check(False, lambda: "reduce argument must be either add or multiply.") + return + + +# From aten/src/ATen/native/ScatterGatherChecks.h +def scatter_gather_dtype_check(method_name, self, index, src_opt=None): + from torch.fx.experimental.symbolic_shapes import guard_or_true + + if guard_or_true(index.numel() != 0): + torch._check( + index.dtype == torch.long or index.dtype == torch.int, + lambda: f"{method_name}(): Expected dtype int32/int64 for index", + ) + + if src_opt is not None: + torch._check( + self.dtype == src_opt.dtype, + lambda: f"{method_name}(): Expected self.dtype to be equal to src.dtype", + ) + + +def ensure_nonempty_dim(dim): + return max(dim, 1) + + +# From aten/src/ATen/native/ScatterGatherChecks.h +def scatter_shape_check(self, dim, index, src_opt=None): + from torch.fx.experimental.symbolic_shapes import guard_or_false + + if guard_or_false(index.numel() == 0): + return + torch._check( + ensure_nonempty_dim(self.dim()) == ensure_nonempty_dim(index.dim()), + lambda: "Index tensor must have the same number of dimensions as self tensor", + ) + + is_wrong_shape = False + self_dims = ensure_nonempty_dim(self.dim()) + + # Check: index.size(d) <= self.size(d) for all d != dim + for d in range(self_dims): + index_d_size = ensure_nonempty_size(index, d) + if d == dim: + continue + if index_d_size > ensure_nonempty_size(self, d): + is_wrong_shape = True + break + + # Check: index.size(d) <= src.size(d) for all d if src is Tensor + if not is_wrong_shape and src_opt is not None: + for d in range(self_dims): + index_d_size = ensure_nonempty_size(index, d) + if index_d_size > ensure_nonempty_size(src_opt, d): + is_wrong_shape = True + break + + if src_opt is not None: + torch._check( + ensure_nonempty_dim(self.dim()) == ensure_nonempty_dim(index.dim()), + lambda: "Index tensor must have the same number of dimensions as self tensor", + ) + torch._check( + not is_wrong_shape, + lambda: f"Expected index {index.shape} to be no larger than self {self.shape}" + + f" apart from dimension {dim} and to be no larger than src {src_opt.shape}", + ) + else: + torch._check( + not is_wrong_shape, + lambda: f"Expected index {index.shape} to be no larger than self {self.shape}" + + f" apart from dimension {dim}", + ) + + +# From aten/src/ATen/native/TensorAdvancedIndexing.cpp +def scatter_meta_impl(self, dim, index, src=None, reduce_=None, use_new_options=False): + wrapped_dim = maybe_wrap_dim(dim, self.dim()) + scatter_gather_dtype_check("scatter", self, index, src) + scatter_shape_check(self, wrapped_dim, index, src) + if reduce_ is not None: + # Check if we have a valid reduce operator. + get_operator_enum(reduce_, use_new_options) + + +@register_meta(aten.scatter_add.default) +def meta_scatter_add(self, dim, index, src): + scatter_meta_impl(self, dim, index, src, "add") + return self.new_empty(self.shape) + + +@register_meta(aten.scatter_add_) +def meta_scatter_add_(self, dim, index, src): + scatter_meta_impl(self, dim, index, src, "add") + return self + + +@register_meta( + [ + aten.scatter.src, + aten.scatter.value, + aten.scatter.reduce, + aten.scatter.value_reduce, + ] +) +@out_wrapper() +def meta_scatter(self, dim, index, src_or_value, reduce=None): + src = src_or_value if isinstance(src_or_value, torch.Tensor) else None + scatter_meta_impl(self, dim, index, src, reduce) + return self.new_empty(self.shape) + + +@register_meta( + [ + aten.scatter_.src, + aten.scatter_.value, + aten.scatter_.reduce, + aten.scatter_.value_reduce, + ] +) +def meta_scatter_(self, dim, index, src_or_value, reduce=None): + src = src_or_value if isinstance(src_or_value, torch.Tensor) else None + scatter_meta_impl(self, dim, index, src, reduce) + return self + + +@register_meta([aten._scaled_dot_product_flash_attention]) +def meta__scaled_dot_product_flash_attention( + query: Tensor, + key: Tensor, + value: Tensor, + dropout_p: float = 0.0, + is_causal: bool = False, + return_debug_mask: bool = False, + scale: float | None = None, +): + batch_size = query.size(0) + num_heads = query.size(1) + max_seqlen_batch_q = query.size(2) + head_dim = query.size(3) + max_seqlen_batch_k = key.size(2) + + attention = torch.empty_like(query) + logsumexp = torch.empty( + (batch_size, num_heads, max_seqlen_batch_q), + dtype=torch.float, + device=query.device, + ) + + if return_debug_mask: + blocksize_c = 128 if head_dim > 64 else 256 + max_seqlen_k = math.ceil(max_seqlen_batch_q / blocksize_c) + if max_seqlen_batch_k <= 128: + max_seqlen_k = 128 + elif max_seqlen_batch_k <= 256: + max_seqlen_k = 256 + debug_mask = torch.empty( + (batch_size, num_heads, max_seqlen_batch_q, max_seqlen_k), + dtype=query.dtype, + device=query.device, + ) + else: + debug_mask = torch.empty(0, dtype=query.dtype, device=query.device) + + # Note [Seed and Offset]: device for seed and offset below depends on whether we are + # capturing or not, but at the time of tracing we don't know if we + # are going to use cudagraphs or not, so we return meta tensors here + # it's possible we'll need to have some special handling in inductor for sdpa + # See [Note] BC breaking change to flash seed/offset + if torch.version.hip and torch.cuda.is_available() or device_hint(query) == "xpu": + # Maintain old path on AMD + seed = torch.empty((), dtype=torch.long, device="meta") + offset = torch.empty((), dtype=torch.long, device="meta") + else: + seed = torch.empty((2), dtype=torch.uint64, device="meta") + offset = torch.empty((), dtype=torch.uint64, device="meta") + + return ( + attention, + logsumexp, + None, + None, + max_seqlen_batch_q, + max_seqlen_batch_k, + seed, + offset, + debug_mask, + ) + + +def alloc_with_matching_layout( + query: Tensor, + res_shape: tuple[int, ...], +): + if tuple(query.shape) == res_shape: + res = torch.empty_like(query) + else: + dim_order = sorted( + [0, 1, 2, 3], key=lambda idx: query.stride()[idx], reverse=True + ) + permuted_shape = [res_shape[idx] for idx in dim_order] + final_permute = [dim_order.index(i) for i in range(len(dim_order))] + res = torch.empty( + permuted_shape, dtype=query.dtype, device=query.device + ).permute(final_permute) + + return res + + +@register_meta([aten._scaled_dot_product_cudnn_attention]) +def meta__scaled_dot_product_cudnn_attention( + query: Tensor, + key: Tensor, + value: Tensor, + attn_bias: Tensor | None, + compute_log_sumexp: bool, + dropout_p: float = 0.0, + is_causal: bool = False, + return_debug_mask: bool = False, + scale: float | None = None, +): + B = query.size(0) + H = query.size(1) + S_Q = query.size(2) + S_KV = key.size(2) + D_V = value.size(-1) + + res_shape = (B, H, S_Q, D_V) + res = alloc_with_matching_layout(query, res_shape) + + logsum_exp = torch.empty( + (B, H, S_Q, 1), + dtype=torch.float, + device=query.device, + ) + + # See Note [Seed and Offset] + seed = torch.empty((), dtype=torch.long, device="meta") + offset = torch.empty((), dtype=torch.long, device="meta") + + return ( + res, + logsum_exp, + None, + None, + S_Q, + S_KV, + seed, + offset, + None, + ) + + +@register_meta([aten._scaled_dot_product_fused_attention_overrideable]) +def meta__scaled_dot_product_fused_attention_overrideable( + query: Tensor, + key: Tensor, + value: Tensor, + attn_bias: Tensor | None = None, + dropout_p: float = 0.0, + is_causal: bool = False, + return_debug_mask: bool = False, + scale: float | None = None, +): + B = query.size(0) + H_Q = query.size(1) + S_Q = query.size(2) + S_KV = key.size(2) + D_V = value.size(-1) + + res_shape = (B, H_Q, S_Q, D_V) + res = alloc_with_matching_layout(query, res_shape) + + logsum_exp = torch.empty( + (B, H_Q, S_Q), + dtype=torch.float, + device=query.device, + ) + + # See Note [Seed and Offset] + seed = torch.empty((), dtype=torch.long, device="meta") + offset = torch.empty((), dtype=torch.long, device="meta") + + return ( + res, + logsum_exp, + None, + None, + S_Q, + S_KV, + seed, + offset, + None, + ) + + +@register_meta( + [ + aten._scaled_dot_product_flash_attention_backward, + ] +) +def meta__scaled_dot_product_flash_backward( + grad_out: Tensor, + query: Tensor, + key: Tensor, + value: Tensor, + out: Tensor, + logsumexp: Tensor, + cum_seq_q: Tensor, + cum_seq_k: Tensor, + max_q: int, + max_k: int, + dropout_p: float, + is_causal: bool, + philox_seed: Tensor, + philox_offset: Tensor, + scale: float | None = None, +): + grad_q = torch.empty_like(query) + grad_k = torch.empty_like(key) + grad_v = torch.empty_like(value) + return grad_q, grad_k, grad_v + + +@register_meta( + [ + aten._scaled_dot_product_flash_attention_for_cpu, + ] +) +def meta__scaled_dot_product_flash_attention_for_cpu( + query: Tensor, + key: Tensor, + value: Tensor, + dropout_p: float = 0.0, + is_causal: bool = False, + attn_mask: Tensor | None = None, + scale: float | None = None, +): + batch_size = query.size(0) + num_heads = query.size(1) + max_seqlen_batch_q = query.size(2) + + attention = torch.empty_like(query) + logsumexp = torch.empty( + ( + batch_size, + max_seqlen_batch_q, + num_heads, + ), + dtype=torch.float, + device=query.device, + ).transpose(1, 2) + return ( + attention, + logsumexp, + ) + + +@register_meta( + [ + aten._scaled_dot_product_flash_attention_for_cpu_backward, + ] +) +def meta__scaled_dot_product_flash_attention_for_cpu_backward( + grad_out: Tensor, + query: Tensor, + key: Tensor, + value: Tensor, + out: Tensor, + logsumexp: Tensor, + dropout_p: float, + is_causal: bool, + attn_mask: Tensor | None = None, + scale: float | None = None, +): + # cpus's grad layout is different from cuda's, + # i.e. (batch_size, seq_len, num_heads, head_dim) + grad_q = torch.empty_permuted( + query.size(), + (0, 2, 1, 3), + dtype=query.dtype, + device=query.device, + ) + grad_k = torch.empty_permuted( + key.size(), + (0, 2, 1, 3), + dtype=key.dtype, + device=key.device, + ) + grad_v = torch.empty_permuted( + value.size(), + (0, 2, 1, 3), + dtype=value.dtype, + device=value.device, + ) + + return grad_q, grad_k, grad_v + + +@register_meta([aten._scaled_dot_product_attention_math_for_mps]) +def meta__scaled_dot_product_attention_math_for_mps( + query: Tensor, + key: Tensor, + value: Tensor, + attn_mask: Tensor | None = None, + dropout_p: float = 0.0, + is_causal: bool = False, + dropout_mask: Tensor | None = None, + scale: float | None = None, +) -> tuple[Tensor, Tensor]: + def ensure_4d(x): + if x.dim() == 3: + return x.unsqueeze(0), True + elif x.dim() > 4: + batch_size = 1 + for i in range(x.dim() - 3): + batch_size *= x.shape[i] + return x.view(batch_size, x.size(-3), x.size(-2), x.size(-1)), True + else: + return x, False + + q_, unsqueezed = ensure_4d(query) + k_, _ = ensure_4d(key) + v_, _ = ensure_4d(value) + + batch_size, num_head, q_size, head_size = q_.shape + _, k_size, max_seq_length, _ = k_.shape + + def sdpa_vector_fast_mps(): + out = q_.new_empty(q_.shape) + if unsqueezed: + out = out.view_as(query) + + attn = q_.new_empty((batch_size, num_head, q_size, max_seq_length)) + if unsqueezed: + if query.dim() == 3: + attn = attn.squeeze(0) + else: + shape = list(query.shape[:-3]) + attn.shape[1:4] + attn = attn.view(shape) + return out, attn + + def sdpa_vector_2pass_mps(): + blocks = 32 + out = q_.new_empty(q_.shape) + intermediate = q_.new_empty((batch_size, num_head, q_size, blocks, head_size)) + return out, intermediate + + if (max_seq_length >= 1024) or (k_size < q_size and max_seq_length >= 4096): + return sdpa_vector_2pass_mps() + else: + return sdpa_vector_fast_mps() + + +@register_meta([aten._scaled_dot_product_efficient_attention]) +def meta__scaled_dot_product_efficient_attention( + query: Tensor, + key: Tensor, + value: Tensor, + attn_bias: Tensor | None, + compute_log_sumexp: bool, + dropout_p=0.0, + is_causal: bool = False, + scale: float | None = None, +): + query = query.transpose(1, 2) + key = key.transpose(1, 2) + value = value.transpose(1, 2) + + B = query.size(0) + M = query.size(1) + num_heads = query.size(-2) + Kv = value.size(-1) + + res = torch.empty(B, M, num_heads, Kv, dtype=query.dtype, device=query.device) + + if torch.version.hip and torch.cuda.is_available(): + """Please see: https://github.com/pytorch/pytorch/issues/146848 + longsumexp last dim should be seq length + """ + logsumexp_dim = M if compute_log_sumexp else 0 + else: + logsumexp_dim = math.ceil(M / 32) * 32 if compute_log_sumexp else 0 + + logsum_exp = torch.empty( + (B, num_heads, logsumexp_dim), + dtype=torch.float, + device=query.device, + ) + + res = res.transpose(1, 2) + + # See Note [Seed and Offset]: + seed = torch.empty((), dtype=torch.long, device="meta") + offset = torch.empty((), dtype=torch.long, device="meta") + + return res, logsum_exp, seed, offset + + +@register_meta( + [ + aten._scaled_dot_product_efficient_attention_backward, + ] +) +def meta__scaled_dot_product_efficient_backward( + grad_out: Tensor, + query: Tensor, + key: Tensor, + value: Tensor, + attn_bias: Tensor | None, + out: Tensor, + logsumexp: Tensor, + philox_seed: Tensor, + philox_offset: Tensor, + dropout_p: float, + grad_input_mask: list[bool], + is_causal: bool = False, + scale: float | None = None, +): + batch_size = query.size(0) + num_heads = query.size(1) + max_q = query.size(2) + head_dim = query.size(3) + head_dim_v = value.size(3) + + max_k = key.size(2) + + grad_q = torch.empty_permuted( + (batch_size, num_heads, max_q, head_dim), + (0, 2, 1, 3), + dtype=query.dtype, + device=query.device, + ) + grad_k = torch.empty_permuted( + (batch_size, num_heads, max_k, head_dim), + (0, 2, 1, 3), + dtype=key.dtype, + device=key.device, + ) + grad_v = torch.empty_permuted( + (batch_size, num_heads, max_k, head_dim_v), + (0, 2, 1, 3), + dtype=value.dtype, + device=value.device, + ) + grad_bias = None + if attn_bias is not None and grad_input_mask[3]: + lastDim = attn_bias.size(-1) + lastDimAligned = lastDim if lastDim % 16 == 0 else lastDim + 16 - lastDim % 16 + new_sizes = list(attn_bias.size()) + new_sizes[-1] = lastDimAligned + grad_bias = torch.empty( + new_sizes, dtype=attn_bias.dtype, device=attn_bias.device + ) + grad_bias = grad_bias[..., :lastDim] + + return grad_q, grad_k, grad_v, grad_bias + + +@register_meta( + [ + aten._scaled_dot_product_cudnn_attention_backward, + ] +) +def meta__scaled_dot_product_cudnn_backward( + grad_out: Tensor, + query: Tensor, + key: Tensor, + value: Tensor, + out: Tensor, + logsumexp: Tensor, + philox_seed: Tensor, + philox_offset: Tensor, + attn_bias: Tensor, + cum_seq_q: Tensor, + cum_seq_k: Tensor, + max_q: int, + max_k: int, + dropout_p: float, + is_causal: bool, + scale: float | None = None, +): + grad_q = torch.empty_like(query) + grad_k = torch.empty_like(key) + grad_v = torch.empty_like(value) + return grad_q, grad_k, grad_v + + +@register_meta( + [ + aten._flash_attention_forward, + ] +) +def meta__flash_attention_forward( + query: Tensor, + key: Tensor, + value: Tensor, + cum_seq_q: Tensor | None, + cum_seq_k: Tensor | None, + max_q: int, + max_k: int, + dropout_p: float, + is_causal: bool, + return_debug_mask: bool, + scale: float | None = None, + window_size_left: int | None = None, + window_size_right: int | None = None, + seqused_k: Tensor | None = None, + alibi_slopes: Tensor | None = None, +): + # NB: there are two underlying paths: + # 1. normal dense path; expect 4D inputs of shape (batch_size, seqlen, num_heads, head_dim) + # 2. varseqlen path; expect 3D inputs of shape (total, num_heads, head_dim) where total + # includes all batch item sequences. cum_seq_q / cum_seq_k contain offsets into total + batch_size = query.size(0) if cum_seq_q is None else cum_seq_q.numel() - 1 + max_seqlen_batch_q = query.size(1) if cum_seq_q is None else max_q + max_seqlen_batch_k = key.size(1) if cum_seq_k is None else max_k + num_heads = query.size(-2) + head_dim = query.size(-1) + + # Cuda Path + attention = torch.empty_like(query) + if cum_seq_q is None: + logsumexp = torch.empty( + (batch_size, num_heads, max_seqlen_batch_q), + dtype=torch.float, + device=query.device, + ) + else: + total_q = query.size(0) + logsumexp = torch.empty( + (num_heads, total_q), dtype=torch.float, device=query.device + ) + + if return_debug_mask: + blocksize_c = 128 if head_dim > 64 else 256 + max_seqlen_k = math.ceil(max_seqlen_batch_q / blocksize_c) + if max_seqlen_batch_k <= 128: + max_seqlen_k = 128 + elif max_seqlen_batch_k <= 256: + max_seqlen_k = 256 + debug_mask = torch.empty( + (batch_size, num_heads, max_seqlen_batch_q, max_seqlen_k), + dtype=query.dtype, + device=query.device, + ) + else: + debug_mask = torch.empty(0, dtype=query.dtype, device=query.device) + + # See Note [Seed and Offset] + # See [Note] BC breaking change to flash seed/offset + seed, offset = None, None + if torch.version.hip and torch.cuda.is_available(): + # Maintain old path on AMD + seed = torch.empty((), dtype=torch.long, device="meta") + offset = torch.empty((), dtype=torch.long, device="meta") + else: + seed = torch.empty((2), dtype=torch.uint64, device="meta") + offset = torch.empty((), dtype=torch.uint64, device="meta") + return ( + attention, + logsumexp, + seed, + offset, + debug_mask, + ) + + +@register_meta( + [ + aten._flash_attention_backward, + ] +) +def meta__flash_attention_backward( + grad_out: Tensor, + query: Tensor, + key: Tensor, + value: Tensor, + out: Tensor, + logsumexp: Tensor, + cum_seq_q: Tensor, + cum_seq_k: Tensor, + max_q: int, + max_k: int, + dropout_p: float, + is_causal: bool, + philox_seed: Tensor, + philox_offset: Tensor, + scale: float | None = None, + window_size_left: int | None = None, + window_size_right: int | None = None, +): + grad_query = torch.empty_like(query) + grad_key = torch.empty_like(key) + grad_value = torch.empty_like(value) + + return grad_query, grad_key, grad_value + + +@register_meta( + [ + aten._efficient_attention_forward, + ] +) +def meta__efficient_attention_forward( + query: Tensor, + key: Tensor, + value: Tensor, + bias: Tensor | None, + cu_seqlens_q: Tensor | None, + cu_seqlens_k: Tensor | None, + max_seqlen_q: int | None, + max_seqlen_k: int | None, + dropout_p: float, + custom_mask_type: int, + compute_log_sumexp: bool = False, + scale: float | None = None, + causal_diagonal: Tensor | None = None, + seqlen_k: Tensor | None = None, + window_size: int | None = None, +): + B = query.size(0) + M = query.size(1) + N = key.size(1) + num_heads = query.size(-2) + Kv = value.size(-1) + + res = torch.empty(B, M, num_heads, Kv, dtype=query.dtype, device=query.device) + + logsumexp_batch_dim = cu_seqlens_q.size(0) - 1 if (cu_seqlens_q is not None) else B + actual_max_seqlen_q = M + if cu_seqlens_q is not None: + assert max_seqlen_q is not None + actual_max_seqlen_q = max_seqlen_q + actual_max_seqlen_k = max_seqlen_k if max_seqlen_k is not None else N + logsumexp_dim = ( + math.ceil(actual_max_seqlen_q / 32) * 32 if compute_log_sumexp else 0 + ) + logsum_exp = torch.empty( + (logsumexp_batch_dim, num_heads, logsumexp_dim), + dtype=torch.float, + device=query.device, + ) + + # See Note [Seed and Offset]: + seed = torch.empty((), dtype=torch.long, device="meta") + offset = torch.empty((), dtype=torch.long, device="meta") + + return res, logsum_exp, seed, offset, actual_max_seqlen_q, actual_max_seqlen_k + + +@register_meta( + [ + aten._efficient_attention_backward, + ] +) +def meta__efficient_attention_backward( + grad_out: Tensor, + query: Tensor, + key: Tensor, + value: Tensor, + bias: Tensor | None, + cu_seqlens_q: Tensor | None, + cu_seqlens_k: Tensor | None, + max_seqlen_q: torch.SymInt, + max_seqlen_k: torch.SymInt, + logsumexp: Tensor, + dropout_p: float, + philox_seed: Tensor, + philox_offset: Tensor, + custom_mask_type: int, + bias_requires_grad: bool, + scale: float | None = None, + num_splits_key: int | None = None, + shared_storage_dqdkdv: bool = False, +): + if shared_storage_dqdkdv: + torch._check( + query.shape[1] == key.shape[1], + lambda: "seqlen must match for `shared_storage_dqdkdv", + ) + torch._check( + query.shape[3] == key.shape[3], + lambda: "embedding dim must match for `shared_storage_dqdkdv", + ) + chunk = torch.empty( + (*query.shape[0:-2], 3, query.shape[-2], query.shape[-1]), + dtype=query.dtype, + device=query.device, + ) + grad_query = chunk.select(-3, 0) + grad_key = chunk.select(-3, 1) + grad_value = chunk.select(-3, 2) + else: + grad_query = torch.empty_like(query) + grad_key = torch.empty_like(key) + grad_value = torch.empty_like(value) + + if bias is not None: + lastDim = bias.size(-1) + lastDimAligned = lastDim if lastDim % 16 == 0 else lastDim + 16 - lastDim % 16 + new_sizes = list(bias.size()) + new_sizes[-1] = lastDimAligned + grad_bias = torch.empty(new_sizes, dtype=bias.dtype, device=bias.device) + grad_bias = grad_bias[..., :lastDim] + else: + grad_bias = torch.empty((), device=query.device) + + return grad_query, grad_key, grad_value, grad_bias + + +def _check_scaled_mm_sizes( + self: torch.Tensor, + mat2: torch.Tensor, + scale_a: torch.Tensor, + scale_b: torch.Tensor, + bias: torch.Tensor | None = None, + scale_result: torch.Tensor | None = None, + out_dtype: torch.dtype | None = None, + use_fast_accum: bool = False, +): + def is_fp8_or_fp4_type(dtype): + return dtype in ( + torch.float8_e4m3fn, + torch.float8_e5m2, + torch.float8_e4m3fnuz, + torch.float8_e5m2fnuz, + torch.float4_e2m1fn_x2, + ) + + torch._check( + self.dim() == 2 and mat2.dim() == 2, + lambda: f"Inputs must be 2D but got self.dim()={self.dim()} and mat2.dim()={mat2.dim()}", + ) + torch._check( + is_fp8_or_fp4_type(self.dtype) and is_fp8_or_fp4_type(mat2.dtype), + lambda: f"Expected both inputs to be fp8 or fp4 types but got self.dtype={self.dtype} and mat2.dtype={mat2.dtype}", + ) + + if device_hint(self) == "cuda" or device_hint(self) == "xpu": + + def is_row_major(stride): + return stride[0] > stride[1] and stride[1] == 1 + + def is_col_major(stride): + return stride[0] == 1 and stride[1] > 1 + + def has_zero_dim(tensor_2d): + return tensor_2d.size(0) == 0 or tensor_2d.size(1) == 0 + + torch._check( + is_row_major(self.stride()) or has_zero_dim(self), + lambda: f"self must be row_major, got stride {self.stride()}", + ) + torch._check( + is_col_major(mat2.stride()) or has_zero_dim(mat2), + lambda: f"mat2 must be col_major, got stride {mat2.stride()}", + ) + torch._check( + self.size(1) % 16 == 0, + lambda: f"Expected self.size(1) to be divisible by 16, but got self.size(1)={self.size(1)}", + ) + torch._check( + mat2.size(0) % 16 == 0 and mat2.size(1) % 16 == 0, + lambda: f"Expected both dimensions of mat2 to be divisible by 16 but got {mat2.shape}", + ) + + # determine scaling type and check input dimensions (refer to Blas.cpp op) + + m, _k = self.shape + n = mat2.size(1) + + is_blockwise_scaling = ( + ( + scale_a.dtype == torch.float8_e8m0fnu + and scale_b.dtype == torch.float8_e8m0fnu + ) + or ( + scale_a.dtype == torch.float8_e4m3fn + and scale_b.dtype == torch.float8_e4m3fn + ) + ) # note: this applies to blockwise scaling for non-FP8 types (FP8 accepts FP32 scales) + + if scale_a.numel() == 1 and scale_b.numel() == 1: + # tensorwise scaling + torch._check( + scale_a.dtype == torch.float32 and scale_b.dtype == torch.float32, + lambda: "For tensorwise scaling, both scale_a and scale_b must be float (fp32) tensors.", + ) + elif is_blockwise_scaling: + # blockwise scaling + + if scale_a.dtype == torch.float8_e4m3fn: + # NVIDIA's nvfp4 recipe: + # * block size is 16 elements packed (32 unpacked) + # * _k needs to be translated to the unpacked version + block_size_k = 16 + _k = _k * 2 + else: + block_size_k = 32 + + block_size_mn = 128 + + num_k_blocks = ceil_div(_k, block_size_k) + padded_num_k_blocks = ceil_div(num_k_blocks, 4) * 4 + + expected_a_size = ( + block_size_mn * ceil_div(m, block_size_mn) * padded_num_k_blocks + ) + expected_b_size = ( + block_size_mn * ceil_div(n, block_size_mn) * padded_num_k_blocks + ) + + if ( + scale_a.numel() == expected_a_size + and scale_b.numel() == expected_b_size + ): + torch._check( + scale_a.is_contiguous(), + lambda: "scale_a must be contiguous", + ) + torch._check( + scale_b.is_contiguous(), + lambda: "scale_b must be contiguous", + ) + else: + torch._check( + False, + lambda: ( + "Invalid blockwise scaling configuration. " + f"For blockwise scaling, scale_a should have {expected_a_size} elements, got {scale_a.numel()}, " + f"scale_b should have {expected_b_size} elements, got {scale_b.numel()}." + ), + ) + else: + torch._check( + scale_a.dtype == torch.float32 and scale_b.dtype == torch.float32, + lambda: "For rowwise scaling, both scale_a and scale_b must be float (fp32) tensors.", + ) + # for rowwise scaling, enforce 2D input tensors + torch._check( + scale_a.dim() == 2 and scale_b.dim() == 2, + lambda: f"For non-tensorwise scaling, scale tensors must be 2D, but got {scale_a.dim()=} and {scale_b.dim()=}", + ) + + if ( + scale_a.size(0) == m + and scale_a.size(1) == 1 + and scale_b.size(0) == 1 + and scale_b.size(1) == n + ): + # rowwise scaling + torch._check( + scale_a.is_contiguous() and scale_b.is_contiguous(), + lambda: "Both scale_a and scale_b must be contiguous for rowwise scaling.", + ) + elif ( + scale_a.size(0) == m + and scale_a.size(1) == scale_b.size(0) == ceil_div(_k, 128) + and scale_b.size(1) == ceil_div(n, 128) + ): + # (BlockWise1x128, BlockWise128x128) + pass # do nothing, but do not error + elif ( + scale_a.size(0) == m + and scale_a.size(1) == scale_b.size(0) == ceil_div(_k, 128) + and scale_b.size(1) == n + ): + # (BlockWise1x128, BlockWise1x128) + pass # do nothing, but do not error + else: + # does not match any valid scaling type + torch._check( + False, + lambda: ( + "Invalid scaling configuration. " + "For tensorwise scaling, both scales should be scalar. " + f"For rowwise scaling, scale_a should be ({m}, 1), scale_b should be (1, {n}). " + f"For (BlockWise1x128, BlockWise128x128), scale_a should be ({m}, {ceil_div(_k, 128)}), " + + f"scale_b should be ({ceil_div(_k, 128)}, {ceil_div(n, 128)}). " + f"For (BlockWise1x128, BlockWise1x128), scale_a should be ({m}, {ceil_div(_k, 128)}), " + + f"scale_b should be ({ceil_div(_k, 128)}, {n}). " + f"Got scale_a.size()=({scale_a.size(0)}, {scale_a.size(1)}) " + f"and scale_b.size()=({scale_b.size(0)}, {scale_b.size(1)})" + ), + ) + + _out_dtype = out_dtype if out_dtype is not None else self.dtype + return torch.empty(self.size(0), mat2.size(1), dtype=_out_dtype, device=self.device) + + +@register_meta([aten._scaled_mm.default]) +def meta_scaled_mm( + self: torch.Tensor, + mat2: torch.Tensor, + scale_a: torch.Tensor, + scale_b: torch.Tensor, + bias: torch.Tensor | None = None, + scale_result: torch.Tensor | None = None, + out_dtype: torch.dtype | None = None, + use_fast_accum: bool = False, +): + return _check_scaled_mm_sizes( + self, mat2, scale_a, scale_b, bias, scale_result, out_dtype, use_fast_accum + ) + + +def _check_scaled_mm_sizes_v2( + self: torch.Tensor, + mat2: torch.Tensor, + scale_a: list[torch.Tensor], + scale_recipe_a: list[ScalingType], + scale_b: list[torch.Tensor], + scale_recipe_b: list[ScalingType], + bias: torch.Tensor | None = None, + out_dtype: torch.dtype | None = None, + swizzle_a: list[SwizzleType] | None = None, + swizzle_b: list[SwizzleType] | None = None, + use_fast_accum: bool = False, +): + def is_fp8_or_fp4_type(dtype): + return dtype in ( + torch.float8_e4m3fn, + torch.float8_e5m2, + torch.float8_e4m3fnuz, + torch.float8_e5m2fnuz, + torch.float4_e2m1fn_x2, + ) + + def is_fp4_type(dtype): + return dtype in (torch.float4_e2m1fn_x2,) + + torch._check( + self.dim() == 2 and mat2.dim() == 2, + lambda: f"Inputs must be 2D but got self.dim()={self.dim()} and mat2.dim()={mat2.dim()}", + ) + torch._check( + is_fp8_or_fp4_type(self.dtype) and is_fp8_or_fp4_type(mat2.dtype), + lambda: f"Expected both inputs to be fp8 or fp4 types but got self.dtype={self.dtype} and mat2.dtype={mat2.dtype}", + ) + + # Passed tensors: + # self: [M, K] + # mat2: [K, N] + M = self.shape[0] + K = self.shape[1] + N = mat2.shape[1] + + # If we're using fp4, using fp4x2 packed format - adjust K appropriately + if is_fp4_type(self.dtype) and is_fp4_type(mat2.dtype): + K_packed_multiplier = 2 + K *= K_packed_multiplier + + scale_recipe_a = [ScalingType(si) for si in scale_recipe_a] + scale_recipe_b = [ScalingType(si) for si in scale_recipe_b] + + if swizzle_a: + swizzle_a = [SwizzleType(si) for si in swizzle_a] + else: + swizzle_a = [ + SwizzleType.NO_SWIZZLE, + ] + if swizzle_b: + swizzle_b = [SwizzleType(si) for si in swizzle_b] + else: + swizzle_b = [ + SwizzleType.NO_SWIZZLE, + ] + + if device_hint(self) == "cuda" or device_hint(self) == "xpu": + + def is_row_major(stride): + return stride[0] > stride[1] and stride[1] == 1 + + def is_col_major(stride): + return stride[0] == 1 and stride[1] > 1 + + def has_zero_dim(tensor_2d): + return tensor_2d.size(0) == 0 or tensor_2d.size(1) == 0 + + torch._check( + is_row_major(self.stride()) or has_zero_dim(self), + lambda: f"self must be row_major, got stride {self.stride()}", + ) + torch._check( + is_col_major(mat2.stride()) or has_zero_dim(mat2), + lambda: f"mat2 must be col_major, got stride {mat2.stride()}", + ) + torch._check( + self.size(1) % 16 == 0, + lambda: f"Expected self.size(1) to be divisible by 16, but got self.size(1)={self.size(1)}", + ) + torch._check( + mat2.size(0) % 16 == 0 and mat2.size(1) % 16 == 0, + lambda: f"Expected both dimensions of mat2 to be divisible by 16 but got {mat2.shape}", + ) + + def is_tensorwise(recipe_a: list[ScalingType], recipe_b: list[ScalingType]): + return ( + len(recipe_a) == 1 + and len(recipe_b) == 1 + and recipe_a[0] == ScalingType.TensorWise + and recipe_b[0] == ScalingType.TensorWise + ) + + def is_rowwise(recipe_a: list[ScalingType], recipe_b: list[ScalingType]): + return ( + len(recipe_a) == 1 + and len(recipe_b) == 1 + and recipe_a[0] == ScalingType.RowWise + and recipe_b[0] == ScalingType.RowWise + ) + + def is_mx(recipe_a: list[ScalingType], recipe_b: list[ScalingType]): + return ( + len(recipe_a) == 1 + and len(recipe_b) == 1 + and recipe_a[0] == ScalingType.BlockWise1x32 + and recipe_b[0] == ScalingType.BlockWise1x32 + ) + + def is_nv(recipe_a: list[ScalingType], recipe_b: list[ScalingType]): + return ( + len(recipe_a) == 2 + and len(recipe_b) == 2 + and recipe_a[0] == ScalingType.BlockWise1x16 + and recipe_a[1] == ScalingType.TensorWise + and recipe_b[0] == ScalingType.BlockWise1x16 + and recipe_b[1] == ScalingType.TensorWise + ) + + def is_1x128_1x128(recipe_a: list[ScalingType], recipe_b: list[ScalingType]): + return ( + len(recipe_a) == 1 + and len(recipe_b) == 1 + and recipe_a[0] == ScalingType.BlockWise1x128 + and recipe_b[0] == ScalingType.BlockWise1x128 + ) + + def is_1x128_128x128(recipe_a: list[ScalingType], recipe_b: list[ScalingType]): + return ( + len(recipe_a) == 1 + and len(recipe_b) == 1 + and recipe_a[0] == ScalingType.BlockWise1x128 + and recipe_b[0] == ScalingType.BlockWise128x128 + ) + + def is_128x128_1x128(recipe_a: list[ScalingType], recipe_b: list[ScalingType]): + return ( + len(recipe_a) == 1 + and len(recipe_b) == 1 + and recipe_a[0] == ScalingType.BlockWise128x128 + and recipe_b[0] == ScalingType.BlockWise1x128 + ) + + # Given scaling types, check input dimensions + + if is_tensorwise(scale_recipe_a, scale_recipe_b): + # TensorWise + torch._check( + scale_a[0].numel() == 1 + and scale_b[0].numel() == 1 + and scale_a[0].dtype == torch.float32 + and scale_b[0].dtype == torch.float32, + lambda: "For Tensorwise scaling, both scale_a and scale_b must be single element float (fp32) tensors", + ) + elif is_rowwise(scale_recipe_a, scale_recipe_b): + torch._check( + scale_a[0].shape[0] == M + and scale_a[0].numel() == M + and scale_a[0].dtype == torch.float32 + and scale_b[0].numel() == N + and scale_b[0].dtype == torch.float32, + lambda: ( + f"For Rowwise scaling, scale_a must have {self.shape[0]} elements (got: {scale_a[0].numel()})" + f", and scale_b must have {mat2.shape[1]} elements (got: {scale_b[0].numel()})" + ), + ) + elif is_1x128_1x128(scale_recipe_a, scale_recipe_b): + # A, B are fp8, scales are fp32 + # As: [M x K // 128], stride: [1, M] + # Bs: [N x K // 128], stride: [1, N] + types_ok = ( + scale_a[0].dtype == torch.float32 and scale_b[0].dtype == torch.float32 + ) + sa = scale_a[0] + scale_a_ok = ( + sa.shape[0] == M + and sa.shape[1] == K // 128 + and sa.stride(0) == 1 + and (sa.stride(1) == M or (sa.shape[1] == 1 and sa.stride(1) == 1)) + ) + sb = scale_b[0] + scale_b_ok = ( + sb.shape[0] == N + and sb.shape[1] == K // 128 + and sb.stride(0) == 1 + and (sb.stride(1) == N or (sb.shape[1] == 1 and sb.stride(1) == 1)) + ) + + torch._check( + types_ok and scale_a_ok and scale_b_ok, + lambda: ( + "For 1x128 x 1x128 blockwise scaling, " + f"scale a must have shape [{M}, {K // 128}] (got: {sa.shape}) and stride [1, {M}] (got: {sa.stride})" + f"scale b must have shape [{N}, {K // 128}] (got: {sb.shape}) and stride [1, {N}] (got: {sb.stride})" + ), + ) + elif is_128x128_1x128(scale_recipe_a, scale_recipe_b): + # A, B are fp8, scales are fp32 + # L4 = round_up(K // 128, 4) + # As: [L4 x M // 128], stride: [1, L4] + # Bs: [N x K // 128], stride: [1, N] + types_ok = ( + scale_a[0].dtype == torch.float32 and scale_b[0].dtype == torch.float32 + ) + L4 = round_up(K / 128, 4) + sa = scale_a[0] + scale_a_ok = ( + sa.shape[0] == L4 + and sa.shape[1] == M // 128 + and sa.stride(0) == 1 + and (sa.stride(1) == L4 or (sa.shape[1] == 1 and sa.stride(1) == 1)) + ) + sb = scale_b[0] + scale_b_ok = ( + sb.shape[0] == N + and sb.shape[1] == K // 128 + and sb.stride(0) == 1 + and (sb.stride(1) == N or (sb.shape[1] == 1 and sb.stride(1) == 1)) + ) + torch._check( + types_ok and scale_a_ok and scale_b_ok, + lambda: ( + "For 128x128 x 1x128 blockwise scaling, L4 = {round_up(K / 128, 4)}, " + f"scale a must have shape [{L4}, {M // 128}] (got: {sa.shape}) and stride [1, {L4}] (got: {sa.stride})" + f"scale b must have shape [{N}, {K // 128}] (got: {sb.shape}) and stride [1, {N}] (got: {sb.stride})" + ), + ) + elif is_1x128_128x128(scale_recipe_a, scale_recipe_b): + # A, B are fp8, scales are fp32 + # L4 = round_up(K // 128, 4) + # As: [M x K // 128], stride: [1, M] + # Bs: [L4 x N // 128], stride: [1, L4] + types_ok = ( + scale_a[0].dtype == torch.float32 and scale_b[0].dtype == torch.float32 + ) + L4 = round_up(K / 128, 4) + sa = scale_a[0] + scale_a_ok = ( + sa.shape[0] == M + and sa.shape[1] == K // 128 + and sa.stride(0) == 1 + and (sa.stride(1) == M or (sa.shape[1] == 1 and sa.stride(1) == 1)) + ) + sb = scale_b[0] + scale_b_ok = ( + sb.shape[0] == L4 + and sb.shape[1] == N // 128 + and sb.stride(0) == 1 + and (sb.stride(1) == L4 or (sb.shape[1] == 1 and sb.stride(1) == 1)) + ) + torch._check( + types_ok and scale_a_ok and scale_b_ok, + lambda: ( + "For 1x128 x 128x128 blockwise scaling, L4 = {round_up(K / 128, 4)}, " + f"scale a must have shape [{M}, {K // 128}] (got: {sa.shape}) and stride [1, {M}] (got: {sa.stride})" + f"scale b must have shape [{L4}, {N // 128}] (got: {sb.shape}) and stride [1, {L4}] (got: {sb.stride})" + ), + ) + elif is_mx(scale_recipe_a, scale_recipe_b): + if torch.version.hip: + # Note(slayton58): These mirror ROCm in ScaledBlas.cpp, but I think they're wrong.. + expected_scale_a_elems = ceil_div(self.shape[0], 32) * self.shape[1] + expected_scale_b_elems = ceil_div(self.shape[1], 32) * self.shape[0] + expected_swizzle = SwizzleType.NO_SWIZZLE + else: + expected_scale_a_elems = round_up(self.shape[0], 128) * round_up( + ceil_div(self.shape[1], 32), 4 + ) + expected_scale_b_elems = round_up(mat2.shape[1], 128) * round_up( + ceil_div(self.shape[1], 32), 4 + ) + expected_swizzle = SwizzleType.SWIZZLE_32_4_4 + torch._check( + scale_a[0].numel() == expected_scale_a_elems + and scale_a[0].dtype == torch.float8_e8m0fnu + and scale_b[0].numel() == expected_scale_b_elems + and scale_b[0].dtype == torch.float8_e8m0fnu + and swizzle_a[0] == expected_swizzle + and swizzle_b[0] == expected_swizzle, + lambda: ( + f"for MX scaling scale_a must have {expected_scale_a_elems} (got: {scale_a[0].numel()}) " + f"and scale_b must have {expected_scale_b_elems} (got: {scale_b[0].numel()}). Scales must " + f"have types {torch.float8_e8m0fnu} (for self: {scale_a[0].dtype}, mat_b: {scale_b[0].dtype}) " + f"Must have swizzle type {expected_swizzle} (got self: {swizzle_a[0]}, mat_b: {swizzle_b[0]})" + ), + ) + elif is_nv(scale_recipe_a, scale_recipe_b): + expected_scale_a_elems = round_up(M, 128) * round_up(ceil_div(K, 16), 4) + expected_scale_b_elems = round_up(N, 128) * round_up(ceil_div(K, 16), 4) + expected_swizzle = SwizzleType.SWIZZLE_32_4_4 + torch._check( + scale_a[0].numel() == expected_scale_a_elems + and scale_a[0].dtype == torch.float8_e4m3fn + and scale_a[1].numel() == 1 + and scale_a[1].dtype == torch.float32 + and scale_b[0].numel() == expected_scale_b_elems + and scale_b[0].dtype == torch.float8_e4m3fn + and scale_b[1].numel() == 1 + and scale_b[1].dtype == torch.float32 + and swizzle_a[0] == expected_swizzle + and swizzle_b[0] == expected_swizzle, + lambda: ( + f"for NV scaling scale_a must have {expected_scale_a_elems} (got: {scale_a[0].numel()}) " + f"and scale_b must have {expected_scale_b_elems} (got: {scale_b[0].numel()}). Must have " + f"swizzle type {expected_swizzle} (got self: {swizzle_a[0]}, mat_b: {swizzle_b[0]})" + ), + ) + else: + torch._check( + False, + lambda: ( + "Invalid scaling configuration. " + "For tensorwise scaling, both scales should be scalar. " + f"For rowwise scaling, scale_a should be ({M}, 1), scale_b should be (1, {N}). " + f"For (BlockWise1x128, BlockWise128x128), scale_a should be ({M}, {ceil_div(K, 128)}), " + + f"scale_b should be ({ceil_div(K, 128)}, {ceil_div(N, 128)}). " + f"For (BlockWise1x128, BlockWise1x128), scale_a should be ({M}, {ceil_div(K, 128)}), " + + f"scale_b should be ({ceil_div(K, 128)}, {N}). " + f"Got scale_a.size()=({scale_a[0].size(0)}, {scale_a[0].size(1)}) " + f"and scale_b.size()=({scale_b[0].size(0)}, {scale_b[0].size(1)})" + ), + ) + + _out_dtype = out_dtype if out_dtype is not None else self.dtype + return torch.empty(M, N, dtype=_out_dtype, device=self.device) + + +@register_meta([aten._scaled_mm_v2.default]) +def meta_scaled_mm_v2( + self: torch.Tensor, + mat2: torch.Tensor, + scale_a: list[torch.Tensor], + scale_recipe_a: list[ScalingType], + swizzle_a: list[SwizzleType], + scale_b: list[torch.Tensor], + scale_recipe_b: list[ScalingType], + swizzle_b: list[SwizzleType], + bias: torch.Tensor | None = None, + output_dtype: torch.dtype | None = None, + contraction_dims: list[int] | None = None, + use_fast_accum: bool = False, +): + return _check_scaled_mm_sizes_v2( + self, + mat2, + scale_a, + scale_recipe_a, + scale_b, + scale_recipe_b, + bias=bias, + out_dtype=output_dtype, + swizzle_a=swizzle_a, + swizzle_b=swizzle_b, + use_fast_accum=use_fast_accum, + ) + + +@register_meta([aten.scatter_reduce.two, aten.scatter_reduce.two_out]) +@out_wrapper() +def meta_scatter_reduce_two(self, dim, index, src, reduce, include_self=True): + scatter_meta_impl(self, dim, index, src, reduce, use_new_options=True) + return self.new_empty(self.shape) + + +@register_meta(aten.scatter_reduce_.two) +def meta_scatter_reduce__two(self, dim, index, src, reduce, include_self=True): + scatter_meta_impl(self, dim, index, src, reduce, use_new_options=True) + return self + + +@register_meta([aten.multinomial.default, aten.multinomial.out]) +@out_wrapper() +def meta_multinomial(input, num_samples, replacement=False, *, generator=None): + torch._check( + 0 < input.dim() <= 2, + lambda: f"The probability distributions dimensions must be 1 or 2, but got {input.dim()}", + ) + if input.dim() == 1: + return torch.empty(num_samples, dtype=torch.long, device=input.device) + return torch.empty( + input.size(0), num_samples, dtype=torch.long, device=input.device + ) + + +def multiply_integers(vs): + r = 1 + for v in vs: + r *= v + return r + + +def upsample_common_check(input_size, output_size, num_spatial_dims): + torch._check( + len(output_size) == num_spatial_dims, + lambda: f"It is expected output_size equals to {num_spatial_dims}, but got size {len(output_size)}", + ) + expected_input_dims = num_spatial_dims + 2 # N, C, ... + torch._check( + len(input_size) == expected_input_dims, + lambda: f"It is expected input_size equals to {expected_input_dims}, but got size {len(input_size)}", + ) + + torch._check( + all(s > 0 for s in input_size[2:]) and all(s > 0 for s in output_size), + lambda: f"Input and output sizes should be greater than 0, but got " + f"input size {input_size} and output size {output_size}", + ) + + nbatch, channels = input_size[:2] + return (nbatch, channels, *output_size) + + +@register_meta( + [aten.upsample_nearest1d.default, aten._upsample_nearest_exact1d.default] +) +def upsample_nearest1d(input, output_size, scales=None): + torch._check( + input.numel() != 0 or multiply_integers(input.size()[1:]), + lambda: f"Non-empty 3D data tensor expected but got a tensor with sizes {input.size()}", + ) + full_output_size = upsample_common_check( + input.size(), output_size, num_spatial_dims=1 + ) + return input.new_empty(full_output_size).to( + memory_format=utils.suggest_memory_format(input) + ) + + +@register_meta( + [aten.upsample_nearest2d.default, aten._upsample_nearest_exact2d.default] +) +def upsample_nearest2d(input, output_size, scales_h=None, scales_w=None): + torch._check( + input.numel() != 0 or multiply_integers(input.size()[1:]), + lambda: f"Non-empty 4D data tensor expected but got a tensor with sizes {input.size()}", + ) + full_output_size = upsample_common_check( + input.size(), output_size, num_spatial_dims=2 + ) + output = input.new_empty(full_output_size) + + # convert output to correct memory format, if necessary + memory_format = utils.suggest_memory_format(input) + + # following "heuristic: only use channels_last path when it's faster than the contiguous path" + _, n_channels, _, _ = input.shape + if input.device.type == "cuda" and n_channels < 4: + memory_format = torch.contiguous_format + + output = output.contiguous(memory_format=memory_format) + + return output + + +@register_meta( + [ + aten.upsample_nearest2d_backward.default, + aten._upsample_nearest_exact2d_backward.default, + ] +) +def upsample_nearest2d_backward( + grad_output: Tensor, + output_size: Sequence[int | torch.SymInt], + input_size: Sequence[int | torch.SymInt], + scales_h: float | None = None, + scales_w: float | None = None, +): + full_output_size = upsample_common_check( + input_size, output_size, num_spatial_dims=2 + ) + torch._check( + grad_output.ndim == 4, + lambda: f"Expected grad_output to be a tensor of dimension 4 but got: dimension {grad_output.ndim}", + ) + for i in range(4): + torch._check( + grad_output.size(i) == full_output_size[i], + lambda: ( + f"Expected grad_output to have the same shape as output;" + f" output.size({i}) = {full_output_size[i]}" + f" but got grad_output.size({i}) = {grad_output.size(i)}" + ), + ) + + return grad_output.new_empty(input_size).to( + memory_format=utils.suggest_memory_format(grad_output) + ) # type: ignore[call-overload] + + +@register_meta( + [aten.upsample_nearest3d.default, aten._upsample_nearest_exact3d.default] +) +def upsample_nearest3d(input, output_size, scales_d=None, scales_h=None, scales_w=None): + torch._check( + input.numel() != 0 or multiply_integers(input.size()[1:]), + lambda: f"Non-empty 5D data tensor expected but got a tensor with sizes {input.size()}", + ) + full_output_size = upsample_common_check( + input.size(), output_size, num_spatial_dims=3 + ) + return input.new_empty(full_output_size).to( + memory_format=utils.suggest_memory_format(input) + ) + + +@register_meta( + [ + aten.sort.default, + aten.sort.stable, + aten.sort.values, + aten.sort.values_stable, + ] +) +def meta_sort(self, stable=None, dim=-1, descending=False, values=None, indices=None): + v, i = torch.empty_like(self), torch.empty_like(self, dtype=torch.int64) + if values is not None and indices is not None: + assert isinstance(values, TensorLike) + assert isinstance(indices, TensorLike) + # Makes sure values and indices have the same strides. For cases where + # these have different shapes, like (5, 10, 5) and (0) in msort. + out_shape = v.shape + out_stride = v.stride() + values = _maybe_resize_out(values, out_shape) + indices = _maybe_resize_out(indices, out_shape) + values.as_strided_(out_shape, out_stride) + indices.as_strided_(out_shape, out_stride) + _safe_copy_out(copy_from=v, copy_to=values) # type: ignore[arg-type] + _safe_copy_out(copy_from=i, copy_to=indices) # type: ignore[arg-type] + return values, indices + return v, i + + +def rnn_cell_checkSizes( + input_gates, + hidden_gates, + input_bias, + hidden_bias, + factor, + prev_hidden, +): + torch._check(input_gates.ndim == 2, lambda: f"{input_gates.ndim} != 2") + torch._check( + input_gates.shape == hidden_gates.shape, + lambda: f"{input_gates.shape} != {hidden_gates.shape}", + ) + gates_size = input_gates.size(1) + if input_bias is not None: + torch._check(input_bias.ndim == 1, lambda: f"{input_bias.ndim} != 1") + torch._check( + input_bias.numel() == gates_size, + lambda: f"{input_bias.numel()} != {gates_size}", + ) + torch._check( + input_bias.shape == hidden_bias.shape, + lambda: f"{input_bias.shape} != {hidden_bias.shape}", + ) + torch._check(prev_hidden.ndim == 2, lambda: f"{prev_hidden.ndim} != 2") + expected_prev_hidden_numel = input_gates.size(0) * gates_size // factor + torch._check( + prev_hidden.numel() == expected_prev_hidden_numel, + lambda: f"{prev_hidden.numel()} != {input_gates.size(0)} * {gates_size} // {factor} (aka {expected_prev_hidden_numel})", + ) + torch._check( + all( + # pyrefly: ignore [missing-attribute] + x.device == input_gates.device + for x in [hidden_gates, input_bias, hidden_bias, prev_hidden] + ), + lambda: "expected all inputs to be same device", + ) + + +@register_meta(aten._thnn_fused_lstm_cell.default) +def _thnn_fused_lstm_cell_meta( + input_gates, + hidden_gates, + cx, + input_bias=None, + hidden_bias=None, +): + rnn_cell_checkSizes(input_gates, hidden_gates, input_bias, hidden_bias, 4, cx) + workspace = torch.empty_like(input_gates, memory_format=torch.contiguous_format) + hy = torch.empty_like(cx, memory_format=torch.contiguous_format) + cy = torch.empty_like(cx, memory_format=torch.contiguous_format) + return (hy, cy, workspace) + + +@register_meta(aten._cudnn_rnn.default) +def _cudnn_rnn( + input, + weight, + weight_stride0, + weight_buf, + hx, + cx, + mode, + hidden_size, + proj_size, + num_layers, + batch_first, + dropout, + train, + bidirectional, + batch_sizes, + dropout_state, +): + is_input_packed = len(batch_sizes) != 0 + if is_input_packed: + seq_length = len(batch_sizes) + mini_batch = batch_sizes[0] + batch_sizes_sum = input.shape[0] + else: + seq_length = input.shape[1] if batch_first else input.shape[0] + mini_batch = input.shape[0] if batch_first else input.shape[1] + batch_sizes_sum = -1 + + num_directions = 2 if bidirectional else 1 + out_size = proj_size if proj_size != 0 else hidden_size + if is_input_packed: + out_shape = [batch_sizes_sum, out_size * num_directions] + else: + out_shape = ( + [mini_batch, seq_length, out_size * num_directions] + if batch_first + else [seq_length, mini_batch, out_size * num_directions] + ) + output = input.new_empty(out_shape) + + cell_shape = [num_layers * num_directions, mini_batch, hidden_size] + if cx is None: + cy = torch.empty(0, device=input.device) + else: + cy = cx.new_empty(cell_shape) + + hy = hx.new_empty([num_layers * num_directions, mini_batch, out_size]) + + # TODO: Query cudnnGetRNNTrainingReserveSize (expose to python) + reserve_shape = 0 if train else 0 + reserve = input.new_empty(reserve_shape, dtype=torch.uint8) + + return output, hy, cy, reserve, weight_buf + + +@register_meta(aten.mkldnn_rnn_layer.default) +def mkldnn_rnn_layer( + input, + w0, + w1, + w2, + w3, + hx_, + cx_, + reverse, + batch_sizes, + mode, + hidden_size, + num_layers, + has_biases, + bidirectional, + batch_first, + train, +): + seq_length = input.shape[1] if batch_first else input.shape[0] + mini_batch = input.shape[0] if batch_first else input.shape[1] + output_chanels = hidden_size + out_shape = ( + [mini_batch, seq_length, output_chanels] + if batch_first + else [seq_length, mini_batch, output_chanels] + ) + output = input.new_empty(out_shape) + if hx_ is None: + hy = torch.empty(0, device=input.device) + else: + hy = hx_.new_empty(hx_.shape) + if cx_ is None: + cy = torch.empty(0, device=input.device) + else: + cy = cx_.new_empty(cx_.shape) + workspace = torch.empty(0, device=input.device, dtype=torch.uint8) + return output, hy, cy, workspace + + +def zero_numel_check_dims(self, dim, fn_name): + if self.ndim == 0: + torch._check_index( + dim == 0 or dim == -1, + lambda: f"{fn_name}: Expected reduction dim -1 or 0 for scalar but got {dim}", + ) + else: + torch._check_index( + self.size(dim) != 0, + lambda: f"{fn_name}: Expected reduction dim {dim} to have non-zero size.", + ) + + +# From aten/src/ATen/native/ReduceOps.cpp +def check_argmax_argmin(name, self, dim): + if dim is not None: + dim = maybe_wrap_dim(dim, self.dim()) + zero_numel_check_dims(self, dim, name) + else: + torch._check( + self.numel() != 0, + lambda: f"{name}: Expected reduction dim to be specified for input.numel() == 0.", + ) + + +@register_meta([aten.argmax.default, aten.argmin.default]) +def argmax_argmin_meta(self, dim=None, keepdim=False): + check_argmax_argmin("argmax", self, dim) + dims = utils.reduction_dims(self.shape, (dim,) if dim is not None else None) + shape = _compute_reduction_shape(self, dims, keepdim) + return self.new_empty(shape, dtype=torch.int64) + + +@register_meta(aten.scalar_tensor.default) +def scalar_tensor(s, dtype=None, layout=None, device=None, pin_memory=None): + # NB: It's always wrong to try to create a scalar tensor with the jagged layout. + # Rather than fix this everywhere, just use the strided layout and let NJT handle + # scalar tensor broadcasting. + if layout == torch.jagged: + layout = torch.strided + return torch.empty( + (), dtype=dtype, layout=layout, device=device, pin_memory=pin_memory + ) + + +@register_meta(aten.topk.default) +def topk_meta(self, k, dim=-1, largest=True, sorted=True): + # From aten/src/ATen/native/Sorting.cpp + dim = maybe_wrap_dim(dim, self.dim(), wrap_scalar=True) + sliceSize = 1 if self.dim() == 0 else self.size(dim) + torch._check(k >= 0) + torch._check(k <= sliceSize, lambda: "k not in range for dimension") + + topKSize = list(self.shape) + if len(topKSize) > 0: + topKSize[dim] = k + return self.new_empty(topKSize), self.new_empty(topKSize, dtype=torch.int64) + + +@register_meta(aten._segment_reduce_backward) +@out_wrapper() +def meta__segment_reduce_backward( + grad, output, data, reduce, lengths=None, offsets=None, axis=0, initial=None +): + assert lengths is not None or offsets is not None, ( + "segment_reduce(): Either lengths or offsets must be defined" + ) + data_contig = data.contiguous() + grad_contig = grad.contiguous() + return torch.empty_like( + data_contig, + dtype=grad_contig.dtype, + device=grad_contig.device, + layout=grad_contig.layout, + ) + + +@register_meta([aten.kthvalue.default, aten.kthvalue.values]) +@out_wrapper("values", "indices") +def kthvalue_meta(self, k, dim=-1, keepdim=False): + from torch.fx.experimental.symbolic_shapes import sym_and + + dim = maybe_wrap_dim(dim, self.dim(), wrap_scalar=True) + dimSize = self.size(dim) if self.dim() > 0 else 1 + torch._check( + sym_and(k >= 1, k <= dimSize), + lambda: f"kthvalue(): selected number k out of range for dimension {dim}", + ) + + shape = list(self.shape[:dim] + self.shape[dim + 1 :]) + if keepdim and self.dim() > 0: + shape.insert(dim, 1) + return self.new_empty(shape), self.new_empty(shape, dtype=torch.int64) + + +legacy_contiguous_memory_format = torch.contiguous_format + + +# From aten/src/ATen/native/cuda/RNN.cu +def checkLSTMBackwardSizes(grad_hy, grad_cy, cx, cy, workspace): + defined_grad = grad_hy if grad_hy is not None else grad_cy + torch._check(defined_grad.dim() == 2, lambda: "") + exp_size = defined_grad.size() + if grad_hy is not None: + torch._check(grad_hy.size() == exp_size, lambda: "") + if grad_cy is not None: + torch._check(grad_cy.size() == exp_size, lambda: "") + torch._check(cx.size() == exp_size, lambda: "") + torch._check(cy.size() == exp_size, lambda: "") + torch._check(workspace.dim() == 2, lambda: "") + torch._check(workspace.numel() == exp_size[0] * exp_size[1] * 4, lambda: "") + + +# From aten/src/ATen/native/cuda/RNN.cu +@register_meta(aten._thnn_fused_lstm_cell_backward_impl.default) +def _thnn_fused_lstm_cell_backward_impl(grad_hy, grad_cy, cx, cy, workspace, has_bias): + if grad_hy is None and grad_cy is None: + return None, None, None + checkLSTMBackwardSizes(grad_hy, grad_cy, cx, cy, workspace) + grad_gates = torch.empty_like( + workspace, memory_format=legacy_contiguous_memory_format + ) + grad_cx = torch.empty_like(cx, memory_format=legacy_contiguous_memory_format) + grad_bias = grad_gates.sum(0, keepdim=False) if has_bias else None + return grad_gates, grad_cx, grad_bias + + +# From aten/src/ATen/native/mps/operations/Linear.mm +@register_meta(aten.linear_backward.default) +def linear_backward(input_, grad_output_, weight_, output_mask): + grad_input = None + grad_weight = None + grad_bias = None + if output_mask[0]: + grad_input = grad_output_.new_empty(input_.size()) + if output_mask[1] or output_mask[2]: + grad_weight = grad_output_.new_empty((grad_output_.size(-1), input_.size(-1))) + grad_bias = grad_output_.new_empty(grad_output_.size(-1)) + return (grad_input, grad_weight, grad_bias) + + +@register_meta(aten.pixel_shuffle.default) +def meta_pixel_shuffle(self, upscale_factor): + assert ( + len(self.shape) > 2 and self.shape[-3] % (upscale_factor * upscale_factor) == 0 + ), ( + f"Invalid input shape for pixel_shuffle: {self.shape} with upscale_factor = {upscale_factor}" + ) + + def is_channels_last(ten): + return torch._prims_common.suggest_memory_format(ten) == torch.channels_last + + def pick_memory_format(): + if is_channels_last(self): + if device_hint(self) == "cuda": + return torch.contiguous_format + else: + return torch.channels_last + elif self.is_contiguous(memory_format=torch.contiguous_format): + return torch.contiguous_format + elif self.is_contiguous(memory_format=torch.preserve_format): + return torch.preserve_format + + C = self.shape[-3] // (upscale_factor * upscale_factor) + Hr = self.shape[-2] * upscale_factor + Wr = self.shape[-1] * upscale_factor + out_shape = (*self.shape[:-3], C, Hr, Wr) + + out = self.new_empty(out_shape) + out = out.to(memory_format=pick_memory_format()) # type: ignore[call-overload] + return out + + +@register_meta(aten.mkldnn_rnn_layer_backward.default) +def mkldnn_rnn_layer_backward( + input, + weight0, + weight1, + weight2, + weight3, + hx_, + cx_tmp, + output, + hy_, + cy_, + grad_output_r_opt, + grad_hy_r_opt, + grad_cy_r_opt, + reverse, + mode, + hidden_size, + num_layers, + has_biases, + train, + bidirectional, + batch_sizes, + batch_first, + workspace, +): + diff_x = input.new_empty(input.shape) + diff_hx = hx_.new_empty(hx_.shape) + diff_cx = cx_tmp.new_empty(cx_tmp.shape) + diff_w1 = weight0.new_empty(weight0.shape) + diff_w2 = weight1.new_empty(weight1.shape) + diff_b = weight2.new_empty(weight2.shape) + return diff_x, diff_w1, diff_w2, diff_b, diff_b, diff_hx, diff_cx + + +@register_meta([aten.bucketize.Tensor, aten.bucketize.Tensor_out]) +@out_wrapper() +def meta_bucketize(self, boundaries, *, out_int32=False, right=False): + return torch.empty_like( + self, + dtype=torch.int32 if out_int32 else torch.int64, + memory_format=torch.contiguous_format, + ) + + +@register_meta([aten.histc]) +@out_wrapper() +def meta_histc(input, bins=100, min=0, max=0): + fn_name = "histc()" + if device_hint(input) == "cpu": + torch._check( + input.is_floating_point(), + lambda: f"\"histogram_cpu\" not implemented for '{input.dtype}'", + ) + if device_hint(input) == "cuda" and input.is_floating_point(): + utils.alert_not_deterministic("_histc_cuda with floating point input") + torch._check( + isinstance(bins, IntLike), + lambda: f"{fn_name}: argument 'bins' must be int, not {type(bins)}", + ) + torch._check(bins > 0, lambda: f"{fn_name}: bins must be > 0, but got {bins}") + torch._check( + isinstance(min, Number), + lambda: f"{fn_name}: argument 'min' must be Number, not {type(min)}", + ) + torch._check( + isinstance(max, Number), + lambda: f"{fn_name}: argument 'max' must be Number, not {type(max)}", + ) + torch._check(max >= min, lambda: f"{fn_name}: max must be larger than min") + return torch.empty(bins, device=input.device, dtype=input.dtype) + + +@register_meta( + [aten._upsample_bilinear2d_aa.default, aten._upsample_bicubic2d_aa.default] +) +def meta_upsample_bimode2d_aa( + input, + output_size, + align_corners, + scales_h=None, + scales_w=None, +): + full_output_size = upsample_common_check( + input.size(), output_size, num_spatial_dims=2 + ) + torch._check( + input.numel() != 0 or all(size > 0 for size in input.size()[1:]), + lambda: f"Non-empty 4D data tensor expected but got a tensor with sizes {input.size()}", + ) + return input.new_empty(full_output_size).to( + memory_format=utils.suggest_memory_format(input) + ) + + +@register_meta([aten._upsample_bilinear2d_aa_backward.default]) +def meta_upsample_bimode2d_aa_backward( + grad_output, + output_size, + input_size, + align_corners, + scales_h=None, + scales_w=None, +): + full_output_size = upsample_common_check( + input_size, output_size, num_spatial_dims=2 + ) + torch._check( + grad_output.ndim == 4, + lambda: f"Expected grad_output to be a tensor of dimension 4 but got: dimension {grad_output.ndim}", + ) + for i in range(4): + torch._check( + grad_output.shape[i] == full_output_size[i], + lambda: f""" +Expected grad_output to have the same shape as output; output.size({i}) = {full_output_size[i]} +but got grad_output_size({i}) = {grad_output.size(i)}""", + ) + return grad_output.new_empty(input_size).to( + memory_format=utils.suggest_memory_format(grad_output) + ) + + +# From aten/src/ATen/native/cuda/AmpKernels.cu +@register_meta(aten._amp_foreach_non_finite_check_and_unscale_.default) +def _amp_foreach_non_finite_check_and_unscale_(self, found_inf, inv_scale): + torch._check( + found_inf.numel() == 1, lambda: "found_inf must be a 1-element tensor." + ) + torch._check( + inv_scale.numel() == 1, lambda: "inv_scale must be a 1-element tensor." + ) + torch._check( + found_inf.dtype.is_floating_point, + lambda: "found_inf must be a float tensor.", + ) + torch._check( + inv_scale.dtype.is_floating_point, + lambda: "inv_scale must be a float tensor.", + ) + + +# From aten/src/ATen/native/UnaryOps.cpp +@register_meta([aten.nan_to_num.default, aten.nan_to_num.out]) +@out_wrapper() +def nan_to_num(self, nan=None, posinf=None, neginf=None): + return torch.empty_like(self) + + +@register_meta(torch.ops.aten.transpose_) +def transpose_(self, dim0, dim1): + assert self.layout not in { + torch.sparse_csr, + torch.sparse_csc, + torch.sparse_bsr, + torch.sparse_bsc, + }, ( + f"torch.transpose_: in-place transposition is not supported for {self.layout} layout" + ) + + ndims = self.ndim + + dim0 = maybe_wrap_dim(dim0, ndims) + dim1 = maybe_wrap_dim(dim1, ndims) + + if dim0 == dim1: + return self + + size = list(self.size()) + stride = list(self.stride()) + + stride[dim0], stride[dim1] = stride[dim1], stride[dim0] + size[dim0], size[dim1] = size[dim1], size[dim0] + + self.as_strided_(size, stride) + return self + + +@register_meta(torch.ops.aten.t_) +def t_(self): + ndims = self.ndim + + if self.is_sparse: + sparse_dim = self.sparse_dim() + dense_dim = self.dense_dim() + assert sparse_dim <= 2 and dense_dim == 0, ( + f"t_ expects a tensor with <= 2 sparse and 0 dense dimensions, " + f"but got {sparse_dim} sparse and {dense_dim} dense dimensions" + ) + else: + assert self.dim() <= 2, ( + f"t_ expects a tensor with <= 2 dimensions, but self is {ndims}D" + ) + + return transpose_(self, 0, 0 if ndims < 2 else 1) + + +@register_meta(aten.searchsorted) +@out_wrapper() +def meta_searchsorted( + sorted_sequence, + self, + *, + out_int32=False, + right=False, + side=None, + sorter=None, +): + # If the sorted_sequence is not one-dimensional, its shape must match that of values + # in all but the last dimension. + torch._check( + len(sorted_sequence.shape) <= 1 + or sorted_sequence.shape[:-1] == self.shape[:-1], + lambda: ( + "torch.searchsorted(): boundaries tensor should be 1 dimension or the " + "first N-1 dimensions of boundaries tensor and input value tensor must " + f"match, but we got boundaries tensor {list(sorted_sequence.shape)} and " + f"input value tensor {list(self.shape)}" + ), + ) + + # If a sorter array is provided, its dimensions must exactly match sorted_sequence. + torch._check( + sorter is None or sorted_sequence.shape == sorter.shape, + lambda: ( + "torch.searchsorted(): boundary and sorter must have the same size, but " + f"got boundary tensor {list(sorted_sequence.shape)} and got sorter tensor " + f"{list(sorter.shape) if sorter is not None else []}" + ), + ) + + # Per the docs, if side == "left" and right is True, we error. + torch._check( + side != "left" or not right, + lambda: "torch.searchsorted(): side and right can't be set to opposites, got side of " + "left while right was True", + ) + + dtype = torch.int32 if out_int32 else torch.int64 + if isinstance(self, torch.Tensor): + return torch.empty_like( + self, dtype=dtype, memory_format=torch.contiguous_format + ) + else: # Scalar + return torch.empty((), dtype=dtype, device=sorted_sequence.device) + + +def _check_for_unsupported_isin_dtype(dtype): + torch._check( + dtype not in (torch.bool, torch.complex128, torch.complex64), + lambda: f"Unsupported input type encountered for isin(): {dtype}", + ) + + +@register_meta(aten.embedding_dense_backward) +def meta_embedding_dense_backward( + grad_output, + indices, + num_weights, + padding_idx, + scale_grad_by_freq, +): + grad_weight = grad_output.new_empty((num_weights, grad_output.size(-1))) + return grad_weight + + +@register_meta(aten._embedding_bag_backward) +def meta_embedding_bag_backward( + grad, + indices, + offsets, + offset2bag, + bag_size, + maximum_indices, + num_weights, + scale_grad_by_freq, + mode, + sparse, + per_sample_weights, + padding_idx=-1, +): + if sparse: + return aten._embedding_bag_sparse_backward( + grad, + indices, + offsets, + offset2bag, + bag_size, + num_weights, + scale_grad_by_freq, + mode, + per_sample_weights, + padding_idx, + ) + else: + return meta_embedding_bag_dense_backward( + grad, + indices, + offset2bag, + bag_size, + maximum_indices, + num_weights, + scale_grad_by_freq, + mode, + per_sample_weights, + padding_idx, + ) + + +@register_meta(aten._embedding_bag_dense_backward) +def meta_embedding_bag_dense_backward( + grad, + indices, + offset2bag, + bag_size, + maximum_indices, + num_weights, + scale_grad_by_freq, + mode, + per_sample_weights, + padding_idx=-1, +): + torch._check( + grad.dtype in [torch.float16, torch.bfloat16, torch.float32, torch.float64], + lambda: f"Unsupported input type encountered: {grad.dtype}", + ) + if mode == MODE_MAX: + torch._check(maximum_indices is not None) + index_grad_weight = grad.new_empty((num_weights, grad.size(1))) + return index_grad_weight + + +@register_meta(aten._embedding_bag_per_sample_weights_backward) +def meta_embedding_bag_per_sample_weights_backward( + grad, + weight, + indices, + offsets, + offset2bag, + mode, + padding_idx=-1, +): + embedding_features = grad.size(1) + torch._check( + mode == MODE_SUM, + lambda: "embedding_bag_backward: per_sample_weights only supported for mode='sum'", + ) + torch._check(grad.dim() == 2) + torch._check(indices.dim() == 1) + num_samples = indices.size(0) + torch._check(weight.dim() == 2) + torch._check(weight.size(1) == embedding_features) + output = grad.new_empty((num_samples,)) + return output + + +@register_meta(aten.isin) +@out_wrapper() +def meta_isin(elements, test_elements, *, assume_unique=False, invert=False): + torch._check( + isinstance(elements, Tensor) or isinstance(test_elements, Tensor), + lambda: "At least one of elements and test_elements must be a Tensor.", + ) + if not isinstance(elements, Tensor): + elements = torch.tensor(elements, device=test_elements.device) + + if not isinstance(test_elements, Tensor): + test_elements = torch.tensor(test_elements, device=elements.device) + + _check_for_unsupported_isin_dtype(elements.dtype) + _check_for_unsupported_isin_dtype(test_elements.dtype) + return torch.empty_like(elements, dtype=torch.bool) + + +@register_meta(aten.polygamma) +@out_wrapper() +def meta_polygamma(n: int, self: Tensor) -> Tensor: + torch._check(n >= 0, lambda: "polygamma(n, x) does not support negative n.") + _, result_dtype = elementwise_dtypes( + self, + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + ) + return torch.empty_like(self, dtype=result_dtype) + + +@register_meta(aten._local_scalar_dense) +def meta_local_scalar_dense(self: Tensor): + raise RuntimeError("Tensor.item() cannot be called on meta tensors") + + +@register_meta(aten.silu) +@out_wrapper(exact_dtype=True) +def silu(self: Tensor) -> Tensor: + return torch.empty_like(self) + + +@register_meta(aten.sigmoid) +@out_wrapper() +def sigmoid(self: Tensor) -> Tensor: + _, result_dtype = elementwise_dtypes( + self, + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + ) + return torch.empty_like(self, dtype=result_dtype) + + +def _create_grouped_mm_output_tensor(mat1, mat2, offs, out_dtype): + mat1_is_2d = mat1.dim() == 2 + mat2_is_2d = mat2.dim() == 2 + + if mat1_is_2d: + if mat2_is_2d: + out_size = [offs.size(0), mat1.size(0), mat2.size(1)] + else: + torch._check( + offs.size(0) == mat2.size(0), lambda: "matrix batch sizes have to match" + ) + out_size = [mat1.size(0), mat2.size(-1)] + else: + if mat2_is_2d: + torch._check( + offs.size(0) == mat1.size(0), lambda: "matrix batch sizes have to match" + ) + out_size = [mat1.size(1), mat2.size(1)] + else: + # regular bmm + torch._check( + mat1.size(0) == mat2.size(0), lambda: "batched dimension has to match" + ) + out_size = [mat1.size(0), mat1.size(1), mat2.size(-1)] + + out_dtype = out_dtype or mat1.dtype + + if torch.version.cuda: + alignment = 16 // out_dtype.itemsize + size_padded = (out_size[-1] + alignment - 1) // alignment * alignment + if mat1_is_2d == mat2_is_2d: + out_stride = [out_size[1] * size_padded, size_padded, 1] + else: + out_stride = [size_padded, 1] + out = torch.empty_strided( + out_size, out_stride, dtype=out_dtype, device=mat1.device + ) + else: + out = torch.empty(out_size, dtype=out_dtype, device=mat1.device) + return out + + +def _meta_grouped_mm_common( + mat_a: Tensor, + mat_b: Tensor, + scale_a: torch.Tensor | None, + scale_b: torch.Tensor | None, + offs: Tensor | None = None, + bias: Tensor | None = None, + scale_result: torch.Tensor | None = None, + out_dtype: torch.dtype | None = None, + use_fast_accum: bool = False, +): + torch._check( + (scale_a is None) == (scale_b is None), + lambda: "Either both scale factors are given, or none", + ) + scaled = scale_a is not None and scale_b is not None + + # Implementing all the checks from + # _grouped_mm_cuda()/_scaled_grouped_mm_cuda() code in + # aten/src/ATen/native/cuda/Blas.cpp. + + if scaled: + fp8_dtype = torch.float8_e4m3fnuz if torch.version.hip else torch.float8_e4m3fn + torch._check( + mat_a.dtype == fp8_dtype and mat_b.dtype == fp8_dtype, + lambda: f"Expected inputs of E4M3 FP8 type but got mat_a.dtype={mat_a.dtype} and mat_b.dtype={mat_b.dtype}.", # noqa: B950 + ) + else: + torch._check( + mat_a.dtype == torch.bfloat16 and mat_b.dtype == torch.bfloat16, + lambda: f"Expected inputs of BF16 type but got mat_a.dtype={mat_a.dtype} and mat_b.dtype={mat_b.dtype}.", # noqa: B950 + ) + + torch._check( + mat_a.dim() in [2, 3] and mat_b.dim() in [2, 3], + lambda: f"Multiplicands must be 2D or 3D but got mat_a.dim()={mat_a.dim()} and mat_b.dim()={mat_b.dim()}", # noqa: B950 + ) + + mat_a_is_2d = mat_a.dim() == 2 + mat_b_is_2d = mat_b.dim() == 2 + + if not mat_a_is_2d or not mat_b_is_2d: + torch._check( + mat_a.size(-1) == mat_b.size(-2), + lambda: "contraction dimension of mat_a and mat_b must match", + ) + + if scaled: + + def is_row_major(mat): + mat_stride = mat.stride() + return mat_stride[-2] > 1 and mat_stride[-1] == 1 + + def is_col_major(mat): + mat_stride = mat.stride() + return mat_stride[-2] == 1 and mat_stride[-1] > 1 + + torch._check( + is_row_major(mat_a), + lambda: f"Expected mat_a tensor to be row major in the last two dimensions, got strides {mat_a.stride()[-2:]}", # noqa: B950 + ) + torch._check( + is_col_major(mat_b), + lambda: f"Expected mat_b tensor to be column major in the last two dimensions, got strides {mat_b.stride()[-2:]}", # noqa: B950 + ) + + def check_valid_strides(mat_name, mat): + end_dim = mat.dim() - 1 + alignment = 16 // mat.element_size() + mat_stride = mat.stride() + if mat_stride[end_dim - 1] == 1 and mat_stride[end_dim] >= max( + 1, mat.shape[end_dim - 1] + ): + torch._check( + mat_stride[end_dim] % alignment == 0, + lambda: f"Expected {mat_name} stride along {end_dim} dim to be multiple of 16 bytes, got {mat_stride[end_dim]}.", # noqa: B950 + ) + elif mat_stride[end_dim] == 1 and mat_stride[end_dim - 1] >= max( + 1, mat.shape[end_dim] + ): + torch._check( + mat_stride[end_dim - 1] % alignment == 0, + lambda: f"Expected {mat_name} stride along {end_dim - 1} dim to be multiple of 16 bytes, got {mat_stride[end_dim - 1]}.", # noqa: B950 + ) + else: + torch._check( + False, + lambda: f"Invalid strides/sizes, got {mat_stride} for strides and {mat.shape} for sizes.", # noqa: B950 + ) + + check_valid_strides("mat_a", mat_a) + check_valid_strides("mat_b", mat_b) + + if scale_a is not None and scale_b is not None: + torch._check( + (scale_a.dtype == torch.float32 and scale_b.dtype == torch.float32) + or ( + scale_a.dtype == torch.float8_e8m0fnu + and scale_b.dtype == torch.float8_e8m0fnu + ), + lambda: f"For FP8 scales must both be float32, or for MXFP8 both scales must be float8_e8m0fnu. Got scale_a.dtype={scale_a.dtype} and scale_b.dtype={scale_b.dtype}.", # noqa: B950 + ) + is_mxfp8 = ( + scale_a.dtype == torch.float8_e8m0fnu + and scale_b.dtype == torch.float8_e8m0fnu + ) + + def check_scale(scale_name, scale, mat, scaled_dim, scale_multiplier=1): + if mat.dim() == 2: + torch._check( + scale.is_contiguous(), + lambda: f"Expected {scale_name} to be contiguous.", + ) + # For MXFP8, 2d tensors have variable size groups represented as subtensors, + # that are converted to blocked padded format individually. At compile time we don't know + # the group sizes yet, so we don't know the expect size of the blocked format scale. + # This limits what we can check here. + if is_mxfp8: + torch._check( + scale.dim() == mat.dim(), + lambda: f"For MXFP8, scale must have same number of dimensions as target tensor, but {scale_name} has mat.ndim={mat.ndim} and scale.ndim={scale.ndim}", # noqa: B950 + ) + else: + torch._check( + scale.dim() == 1, + lambda: f"Expected {scale_name} to be 1D tensor, but got {scale.dim()}D tensor.", + ) + torch._check( + scale.shape[0] == mat.shape[scaled_dim] * scale_multiplier, + lambda: f"Expected {scale_name} to have {mat.shape[scaled_dim] * scale_multiplier} elements, got {scale.shape[0]} elements.", # noqa: B950 + ) + else: + torch._check( + scale.stride(-1) == 1, + lambda: f"Expected {scale_name} to be contiguous in the last dimension.", + ) + torch._check( + scale.shape[0] == mat.shape[0], + lambda: f"Expected {scale_name} batch dimension to be {mat.shape[0]}, got {scale.shape[0]}.", + ) + # For MXFP8, 3d tensors have static 'groups' (stack of 2d tensors) so we can know the expected blocked + # scale sizes at compile time. + if is_mxfp8: + torch._check( + scale.ndim == mat.ndim - 1, + lambda: f"For MXFP8, 3d tensor should have 2d scales, but {scale_name} has mat.ndim={mat.ndim} and scale.ndim={scale.ndim}", # noqa: B950 + ) + # TODO: This logic only holds for RHS tensor in 2d-3d case. + # We'll need to update it to handle LHS 3d tensor in 3d-2d and 3d-3d cases. + G, K, N = mat.shape + block_size = 32 + blocked_K = round_up(K / block_size, 4) + blocked_N = round_up(N, 128) + torch._check( + scale.shape[0] == G and scale.shape[1] == blocked_K * blocked_N, + lambda: f"For MXFP8, expected mat.shape={mat.shape} to have scale shape of ({G},{blocked_K * blocked_N}), but got {scale.shape}", # noqa: B950 + ) + else: + torch._check( + scale.dim() == 2, + lambda: f"Expected {scale_name} to be 2D tensor, but got {scale.dim()}D tensor.", + ) + torch._check( + scale.shape[1] == mat.shape[1 + scaled_dim], + lambda: f"Expected {scale_name} non-batch dimension to be {mat.shape[1 + scaled_dim]}, got {scale.shape[1]}.", # noqa: B950 + ) + + scale_multiplier = ( + offs.shape[0] if offs is not None and mat_a_is_2d and mat_b_is_2d else 1 + ) + check_scale("scale_a", scale_a, mat_a, 0, scale_multiplier) + check_scale("scale_b", scale_b, mat_b, 1, scale_multiplier) + + torch._check( + scale_result is None, + lambda: "Scale result tensor provided, but it is not supported yet.", + ) + + if mat_a_is_2d or mat_b_is_2d: + torch._check( + offs is not None, + lambda: f"Offsets tensor not provided, but is needed for {mat_a.dim()}D/{mat_b.dim()}D multiplicand layouts.", + ) + if offs is not None: # to silence Mypy + torch._check( + offs.dim() == 1, + lambda: f"Offsets tensor must be 1D, but got offs.dim()={offs.dim()}.", + ) + torch._check( + offs.dtype == torch.int32, + lambda: f"Offsets tensor must be integer (int32) tensor, but got {offs.dtype}.", + ) + else: + torch._check( + offs is None, + lambda: "Offsets tensor provided, but is not needed for 3D/3D multiplicand layouts.", + ) + + torch._check( + bias is None, + lambda: "Bias tensor provided, but it is not supported yet.", + ) + + torch._check( + out_dtype is None or out_dtype == torch.bfloat16, + lambda: "If output dtype provided, it must be torch.bfloat16.", + ) + + return _create_grouped_mm_output_tensor(mat_a, mat_b, offs, out_dtype) + + +@register_meta(aten._grouped_mm) +@out_wrapper() +def meta_grouped_mm( + mat_a: Tensor, + mat_b: Tensor, + offs: Tensor | None = None, + bias: Tensor | None = None, + out_dtype: torch.dtype | None = None, +) -> Tensor: + return _meta_grouped_mm_common( + mat_a, + mat_b, + scale_a=None, + scale_b=None, + offs=offs, + bias=bias, + scale_result=None, + out_dtype=out_dtype, + ) + + +@register_meta([aten._scaled_grouped_mm]) +def meta_scaled_grouped_mm( + mat_a: torch.Tensor, + mat_b: torch.Tensor, + scale_a: torch.Tensor, + scale_b: torch.Tensor, + offs: torch.Tensor | None = None, + bias: torch.Tensor | None = None, + scale_result: torch.Tensor | None = None, + out_dtype: torch.dtype | None = None, + use_fast_accum: bool = False, +): + # matching _scaled_grouped_mm_cuda Blas.cpp implementation + out_dtype = out_dtype or torch.bfloat16 + + return _meta_grouped_mm_common( + mat_a, + mat_b, + scale_a=scale_a, + scale_b=scale_b, + offs=offs, + bias=bias, + scale_result=scale_result, + out_dtype=out_dtype, + use_fast_accum=use_fast_accum, + ) + + +@register_meta(aten._softmax) +@out_wrapper() +def softmax(x: Tensor, dim: int, half_to_float: bool) -> Tensor: + if half_to_float: + assert x.dtype in [torch.half, torch.bfloat16] + + computation_dtype, result_dtype = utils.elementwise_dtypes( + x, type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT + ) + + result_dtype = result_dtype if not half_to_float else computation_dtype + res = torch.empty_like(x, dtype=result_dtype, memory_format=torch.contiguous_format) + return res + + +@register_meta(aten.constant_pad_nd) +@out_wrapper() +def _constant_pad_nd_meta(input, pad, value=0): + # same checks as decomposition in torch/_refs/__init__.py:constant_pad_nd() + torch._check( + len(pad) % 2 == 0, + lambda: f"Length of pad must be even but instead it equals {len(pad)}", + ) + + input_sizes = input.shape + l_inp = len(input_sizes) + l_pad = len(pad) // 2 + l_diff = l_inp - l_pad + + torch._check( + l_inp >= l_pad, + lambda: "Length of pad should be no more than twice the number of " + f"dimensions of the input. Pad length is {len(pad)} while the input has " + f"{l_inp} dimensions.", + ) + + if all(isinstance(p, utils.IntWithoutSymInt) and p <= 0 for p in pad): + c_input = input + for i in range(l_diff, l_inp): + pad_idx = 2 * (l_inp - i - 1) + if pad[pad_idx] < 0: + c_input = c_input.narrow( + i, -pad[pad_idx], c_input.shape[i] + pad[pad_idx] + ) + + if pad[pad_idx + 1] < 0: + c_input = c_input.narrow(i, 0, c_input.shape[i] + pad[pad_idx + 1]) + + return c_input.clone() + + new_shape = list(input_sizes[:l_diff]) + for i in range(l_pad): + pad_idx = len(pad) - ((i + 1) * 2) + new_dim = input_sizes[l_diff + i] + pad[pad_idx] + pad[pad_idx + 1] + torch._check( + new_dim >= 0, + lambda: f"The input size {input_sizes[l_diff + i]}, plus negative padding " + f"{pad[pad_idx]} and {pad[pad_idx + 1]} resulted in a negative output size, " + f"which is invalid. Check dimension {l_diff + i} of your input.", + ) + new_shape.append(new_dim) + + return torch.empty( + new_shape, + dtype=input.dtype, + device=input.device, + requires_grad=input.requires_grad, + memory_format=suggest_memory_format(input), + ) + + +@register_meta(aten.embedding) +@out_wrapper() +def embedding( + weight: Tensor, + indices: Tensor, + padding_idx: int = -1, + scale_grad_by_freq: bool = False, + sparse: bool = False, +) -> Tensor: + assert weight.dim() == 2, "'weight' must be 2-D" + weight_shape = weight.shape + indices_shape = indices.shape + + if indices.ndim == 0: + out_shape: tuple[int, ...] = (weight_shape[1],) + elif indices.ndim == 1: + out_shape = (indices_shape[0], weight_shape[1]) + else: + out_shape = (*indices_shape, weight_shape[1]) + + out_dtype = weight.dtype + return weight.new_empty(out_shape, dtype=out_dtype) + + +@register_meta(aten._jagged_to_padded_dense_forward.default) +def meta__jagged_to_padded_dense_forward( + values: Tensor, + offsets: list[Tensor], + max_lengths: list[int], + padding_value: float = 0.0, +): + # only one jagged dim is supported for now + assert len(offsets) == 1 + assert len(max_lengths) == 1 + + B = offsets[0].shape[0] - 1 + S = max_lengths[0] + output_shape = (B, S, *values.shape[1:]) + return values.new_empty(output_shape) + + +def _create_unary_float_meta_func(func): + @register_meta(func) + @out_wrapper() + def _f(x): + return elementwise_meta( + x, type_promotion=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT + ) + + return _f + + +# Implementation follows cuda implementation native_multi_head_attention_cuda +@register_meta(aten._native_multi_head_attention.default) +def native_multi_head_attention_fake( + query, + key, + value, + embed_dim, + num_head, + qkv_weight, + qkv_bias, + proj_weight, + proj_bias, + mask=None, + need_weights=True, + average_attn_weights=True, + mask_type=None, +): + if query.is_nested or key.is_nested or value.is_nested: + raise NotImplementedError( + "_native_multi_head_attention fake implementation does not support nested tensors" + ) + + if query.numel() == 0: + return (query.new_empty(query.shape), query.new_empty(0)) + + B = query.size(0) # B: batch size + T = query.size(1) # T: target sequence length + + # In native_multi_head_attention_cuda, + # we have proj = transform0213_gemm_nt_bias(attn_ctx, proj_weight, proj_bias, query) + # , which does attn_ctx @ proj_weight.T + proj_bias + # so the last dim of output shape is proj_weight.size(0) + output_dim = proj_weight.size(0) + output = query.new_empty(B, T, output_dim) + + if need_weights: + if average_attn_weights: + # When averaging attention weights, shape is [B, T, T] (averaged over heads) + # T = query seq len, S = key/value seq len + attn_weights = query.new_empty(B, T, T) + else: + # When not averaging, shape is [B, num_head, T, T] + # T = query seq len, S = key/value seq len + attn_weights = query.new_empty(B, num_head, T, T) + else: + attn_weights = query.new_empty(0) + + return (output, attn_weights) + + +def _create_binary_float_meta_func(func): + @register_meta(func) + @out_wrapper() + def _f(x, y): + return elementwise_meta( + x, y, type_promotion=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT + ) + + return _f + + +_create_unary_float_meta_func(aten.special_airy_ai) +_create_unary_float_meta_func(aten.special_bessel_y0) +_create_unary_float_meta_func(aten.special_bessel_y1) +_create_unary_float_meta_func(aten.special_modified_bessel_i0) +_create_unary_float_meta_func(aten.special_modified_bessel_i1) +_create_unary_float_meta_func(aten.special_modified_bessel_k0) +_create_unary_float_meta_func(aten.special_modified_bessel_k1) +_create_unary_float_meta_func(aten.special_scaled_modified_bessel_k0) +_create_unary_float_meta_func(aten.special_scaled_modified_bessel_k1) + + +_create_binary_float_meta_func(aten.special_chebyshev_polynomial_t) +_create_binary_float_meta_func(aten.special_chebyshev_polynomial_u) +_create_binary_float_meta_func(aten.special_chebyshev_polynomial_v) +_create_binary_float_meta_func(aten.special_chebyshev_polynomial_w) +_create_binary_float_meta_func(aten.special_shifted_chebyshev_polynomial_t) +_create_binary_float_meta_func(aten.special_shifted_chebyshev_polynomial_u) +_create_binary_float_meta_func(aten.special_shifted_chebyshev_polynomial_v) +_create_binary_float_meta_func(aten.special_shifted_chebyshev_polynomial_w) +_create_binary_float_meta_func(aten.special_hermite_polynomial_h) +_create_binary_float_meta_func(aten.special_hermite_polynomial_he) +_create_binary_float_meta_func(aten.special_laguerre_polynomial_l) +_create_binary_float_meta_func(aten.special_legendre_polynomial_p) + + +def _register_inplace_meta(fn): + @wraps(fn) + def _fn(self, *args, **kwargs): + out = fn(self, *args, **kwargs) + check_inplace_broadcast(self.shape, out.shape) + return self + + inplace_name = f"{fn.__name__}_" + _fn.__name__ = inplace_name + _fn = register_meta(getattr(aten, inplace_name))(_fn) # type: ignore[assignment] + + return _fn + + +@register_meta(aten.lerp) +@out_wrapper() +def lerp(start, end, weight): + torch._check( + start.dtype == end.dtype, + lambda: f"expected dtype {start.dtype} for `end`, but got dtype {end.dtype}", + ) + args = [start, end] + if isinstance(weight, TensorLike): + if weight.ndim != 0: + torch._check( + start.dtype == weight.dtype, + lambda: f"expected dtype {start.dtype} for `weight`, but got dtype {weight.dtype}", + ) + args.append(weight) + return elementwise_meta( + *args, type_promotion=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT + ) + + +@register_meta(aten.addcmul) +@out_wrapper() +def addcmul(input, tensor1, tensor2, *, value=1): + return elementwise_meta( + input, tensor1, tensor2, type_promotion=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT + ) + + +@register_meta(aten.addcdiv) +@out_wrapper() +def addcdiv(input, tensor1, tensor2, *, value=1): + torch._check( + not ( + utils.is_integer_dtype(tensor1.dtype) + and utils.is_integer_dtype(tensor2.dtype) + ), + lambda: ( + "Integer division with addcdiv is no longer supported, and in a future ", + "release addcdiv will perform a true division of tensor1 and tensor2. ", + "The historic addcdiv behavior can be implemented as ", + "(input + value * torch.trunc(tensor1 / tensor2)).to(input.dtype) ", + "for integer inputs and as ", + "(input + value * tensor1 / tensor2) for float inputs. ", + "The future addcdiv behavior is just the latter implementation: ", + "(input + value * tensor1 / tensor2), for all dtypes.", + ), + ) + return elementwise_meta( + input, tensor1, tensor2, type_promotion=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT + ) + + +lerp_ = _register_inplace_meta(aten.lerp) +addcmul_ = _register_inplace_meta(aten.addcmul) +addcdiv_ = _register_inplace_meta(aten.addcdiv) + + +# We must also trigger meta registrations from PrimTorch ref +# decompositions +import torch._refs +import torch._refs.nn.functional +import torch._refs.special + + +def activate_meta(): + activate_meta_table = {} + + # For a given op, we pick the most specific decomp function from + # global_decomp_table in the precedence order of meta > post_autograd > pre_autograd + for type in ["meta", "post_autograd", "pre_autograd"]: + registry = global_decomposition_table[type] + + for opo in registry: + if opo not in activate_meta_table: + activate_meta_table[opo] = registry[opo] + + for op_overload, fn in activate_meta_table.items(): + # Don't register meta for HigherOrderOp's decomp. + # We can reconsider this in the future, but in general, + # the way you do a meta for a HigherOrderOp is different from + # OpOverload. + if isinstance(op_overload, torch._ops.HigherOrderOperator): + continue + assert isinstance(op_overload, OpOverload) + + op_overload.py_impl(torch._C.DispatchKey.Meta)(fn) + + if torch._C._dispatch_has_kernel_for_dispatch_key( + op_overload.name(), "CompositeImplicitAutograd" + ): + # Internally, we shouldn't be registering meta kernels for any operators that + # have CompositeImplicitAutograd kernels. + # Instead, we should be letting those decompositions run, and writing meta kernels + # only for the base operators. + if op_overload in global_decomposition_table["meta"]: + raise RuntimeError( + f"{op_overload} is a CompositeImplicitAutograd op, we shouldn't " + "register meta function for it. Instead, we should let the decomposition run and write " + "meta kernels for the base operators." + ) + elif op_overload.is_view: + # Attempting to register a python meta kernel for a view operator. + # We shouldn't do this, because the output will report as not having aliased storages. + # All view ops have meta kernels in C++ today, so we should use those instead. + pass + elif ( + op_overload.name() + in { + "aten::empty_strided", # causing infinite recursion, test_meta.py + "aten::clone", # causing infinite recursion + "aten::_to_copy", # causing infinite recursion, test_serialization.py -k test_tensor_subclass_getstate_overwrite # noqa: B950 + "aten::copy_", # Exception not raised, test_torch.py -k test_storage_meta_errors_cpu_int64 # noqa: B950 + "aten::constant_pad_nd", # requires_grad mismatch, test_ops.py -k test_fake_crossref_backward_amp_istft_cuda_float32 # noqa: B950 + "aten::rot90", # requires_grad mismatch! test_ops.py -k test_fake_crossref_backward_amp_rot90_cuda_float32 # noqa: B950 + "aten::as_strided_scatter", # requires_grad mismatch, test_ops.py -k test_fake_crossref_backward_no_amp_as_strided_scatter_cuda_float32 # noqa: B950 + } + ): + pass + else: + if "mkldnn::" in op_overload.name(): + _meta_lib_dont_use_me_use_register_meta_for_mkldnn.impl(op_overload, fn) + elif "mkl::" in op_overload.name(): + _meta_lib_dont_use_me_use_register_meta_for_mkl.impl(op_overload, fn) + elif "onednn::" in op_overload.name(): + _meta_lib_dont_use_me_use_register_meta_for_onednn.impl(op_overload, fn) + elif "quantized::" in op_overload.name(): + _meta_lib_dont_use_me_use_register_meta_for_quantized.impl( + op_overload, fn + ) + else: + _meta_lib_dont_use_me_use_register_meta.impl(op_overload, fn) + + +activate_meta() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_namedtensor_internals.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_namedtensor_internals.py new file mode 100644 index 0000000000000000000000000000000000000000..b0fa6a206fac35d38294718328f81b3b55ef1bbf --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_namedtensor_internals.py @@ -0,0 +1,159 @@ +# mypy: allow-untyped-defs +from collections import OrderedDict + + +""" +This file contains helper functions that implement experimental functionality +for named tensors in python. All of these are experimental, unstable, and +subject to change or deletion. +""" + + +def check_serializing_named_tensor(tensor): + if tensor.has_names(): + raise RuntimeError( + "NYI: Named tensors don't support serialization. Please drop " + "names via `tensor = tensor.rename(None)` before serialization." + ) + + +def build_dim_map(tensor): + """Returns a map of { dim: dim_name } where dim is a name if the dim is named + and the dim index otherwise.""" + return OrderedDict( + [(idx if name is None else name, name) for idx, name in enumerate(tensor.names)] + ) + + +def unzip_namedshape(namedshape): + if isinstance(namedshape, OrderedDict): + namedshape = namedshape.items() + if not hasattr(namedshape, "__iter__") and not isinstance(namedshape, tuple): + raise RuntimeError( + f"Expected namedshape to be OrderedDict or iterable of tuples, got: {type(namedshape)}" + ) + if len(namedshape) == 0: + raise RuntimeError("Expected namedshape to non-empty.") + return zip(*namedshape) + + +def namer_api_name(inplace): + if inplace: + return "rename_" + else: + return "rename" + + +def is_ellipsis(item): + return item == Ellipsis or item == "..." + + +def single_ellipsis_index(names, fn_name): + ellipsis_indices = [i for i, name in enumerate(names) if is_ellipsis(name)] + if len(ellipsis_indices) >= 2: + raise RuntimeError( + f"{fn_name}: More than one Ellipsis ('...') found in names (" + f"{names}). This function supports up to one Ellipsis." + ) + if len(ellipsis_indices) == 1: + return ellipsis_indices[0] + return None + + +def expand_single_ellipsis(numel_pre_glob, numel_post_glob, names): + return names[numel_pre_glob : len(names) - numel_post_glob] + + +def replace_ellipsis_by_position(ellipsis_idx, names, tensor_names): + globbed_names = expand_single_ellipsis( + ellipsis_idx, len(names) - ellipsis_idx - 1, tensor_names + ) + return names[:ellipsis_idx] + globbed_names + names[ellipsis_idx + 1 :] + + +def resolve_ellipsis(names, tensor_names, fn_name): + """ + Expands ... inside `names` to be equal to a list of names from `tensor_names`. + """ + ellipsis_idx = single_ellipsis_index(names, fn_name) + if ellipsis_idx is None: + return names + return replace_ellipsis_by_position(ellipsis_idx, names, tensor_names) + + +def update_names_with_list(tensor, names, inplace): + # Special case for tensor.rename(None) + if len(names) == 1 and names[0] is None: + return tensor._update_names(None, inplace) + + return tensor._update_names( + resolve_ellipsis(names, tensor.names, namer_api_name(inplace)), inplace + ) + + +def update_names_with_mapping(tensor, rename_map, inplace): + dim_map = build_dim_map(tensor) + for old_dim in rename_map: + new_dim = rename_map[old_dim] + if old_dim in dim_map: + dim_map[old_dim] = new_dim + else: + raise RuntimeError( + f"{namer_api_name(inplace)}: Tried to rename dim '{old_dim}' to dim " + f"{new_dim} in Tensor[{tensor.names}] but dim '{old_dim}' does not exist" + ) + return tensor._update_names(tuple(dim_map.values()), inplace) + + +def update_names(tensor, names, rename_map, inplace): + """There are two usages: + + tensor.rename(*names) returns a view on tensor with named dims `names`. + `names` must be of length `tensor.dim()`; otherwise, if '...' is in `names`, + then it is expanded greedily to be equal to the corresponding names from + `tensor.names`. + + For example, + ``` + >>> # xdoctest: +SKIP + >>> x = torch.empty(2, 3, 5, 7, names=('N', 'C', 'H', 'W')) + >>> x.rename('...', 'height', 'width').names + ('N', 'C', 'height', 'width') + + >>> # xdoctest: +SKIP + >>> x.rename('batch', '...', 'width').names + ('batch', 'C', 'H', 'width') + + ``` + + tensor.rename(**rename_map) returns a view on tensor that has rename dims + as specified in the mapping `rename_map`. + + For example, + ``` + >>> # xdoctest: +SKIP + >>> x = torch.empty(2, 3, 5, 7, names=('N', 'C', 'H', 'W')) + >>> x.rename(W='width', H='height').names + ('N', 'C', 'height', 'width') + + ``` + + Finally, tensor.rename has an in-place version called tensor.rename_. + """ + has_names = len(names) > 0 + has_rename_pairs = bool(rename_map) + if has_names and has_rename_pairs: + raise RuntimeError( + f"{namer_api_name(inplace)}: This function takes either positional " + f"args or keyword args, but not both. Use tensor.{namer_api_name(inplace)}(*names) " + f"to name dims and tensor.{namer_api_name(inplace)}(**rename_map) to rename " + "dims." + ) + + # Special case for tensor.rename(*[]), which is valid for a 0 dim tensor. + if not has_names and not has_rename_pairs: + return update_names_with_list(tensor, names, inplace) + + if has_names: + return update_names_with_list(tensor, names, inplace) + return update_names_with_mapping(tensor, rename_map, inplace) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..805d0ab082030386c2717127c49569b45b80dd92 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_ops.py @@ -0,0 +1,1449 @@ +# mypy: allow-untyped-defs +import abc +import contextlib +import ctypes +import importlib +import inspect +import sys +import types +from collections.abc import Callable, Iterator +from functools import cached_property +from typing import Any, ClassVar, Concatenate, final, Generic, TYPE_CHECKING +from typing_extensions import ParamSpec, TypeVar + +import torch +import torch.utils._pytree as pytree +from torch import _utils_internal +from torch._C import _dispatch_is_included_in_alias as is_included_in_alias, DispatchKey +from torch._functorch.pyfunctorch import dispatch_functorch, TransformType +from torch.utils._python_dispatch import TorchDispatchMode + + +if TYPE_CHECKING: + from torch._subclasses.functional_tensor import BaseFunctionalizeAPI + + +_T = TypeVar("_T", default=Any) +_P = ParamSpec("_P", default=...) + + +# Query `hasattr` only once. +_SET_GLOBAL_FLAGS = hasattr(sys, "getdlopenflags") and hasattr(sys, "setdlopenflags") + + +@contextlib.contextmanager +def dl_open_guard(): + """ + Context manager to set the RTLD_GLOBAL dynamic linker flag while we open a + shared library to load custom operators. + """ + if not _SET_GLOBAL_FLAGS: + yield + return + old_flags = sys.getdlopenflags() + sys.setdlopenflags(old_flags | ctypes.RTLD_GLOBAL) + try: + yield + finally: + sys.setdlopenflags(old_flags) + + +class OperatorBase: + """ + Base class for OpOverload (which represents C++ ATen operators) and HigherOrderOperator + (which represents Python-only operators that are unrepresentable in TorchScript). + """ + + def __init__(self): + # The dispatch cache precomputes a mapping of dispatch key that the + # dispatcher wants to dispatch to, to an actual implementation of the + # dispatch key. Confusingly, the actual implementation could *also* be a + # dispatch key, but in this case, this refers to the C++ kernel that + # was registered to some dispatch key. Aliases are permitted in the + # latter but not the former; for example, you might lookup the + # entry for AutogradCPU, and this maps you to the Autograd key for + # the generic autograd kernel that works for all devices. Since this + # is the Python dispatcher, you can also put an arbitrary Python + # callable to call instead. This handler gets precisely the + # args/kwargs that the operator was __call__'ed with. + # NB: This name is hard-coded in torch/csrc/autograd/python_variable.cpp + # for use with OpOverload; cache lookup is done entirely from C++ + # for speed. + # TODO: The cache is NOT currently used by HigherOrderOperator, but it should! + self._dispatch_cache: dict[DispatchKey, DispatchKey | Callable[..., Any]] = {} + + # This table allows you to override the behavior of a particular + # dispatch key to call a custom Python function, rather than the + # ordinary C++ configured behavior. This is the raison d'etre of # codespell:ignore + # Python dispatcher: to let you program the dispatcher from Python + # in case you need something unusual, and don't want to clobber + # the existing registrations using the Python operator registration + # API. + self.py_kernels: dict[DispatchKey, Callable[..., Any]] = {} + + # This table allows you to override the behavior of a particular + # operator for a particular TorchDispatchMode. In practice, + # we are using this mostly for ProxyTensorMode. Modes can be + # thought of as an open world extension of dispatch keys, so it + # makes sense that you should be able to register them, the same + # way you can register dispatch keys. + self.python_key_table: dict[ + type[TorchDispatchMode | torch.Tensor], Callable[..., Any] + ] = {} + + # This table allows you to override the behavior of functorch + # transformations. NB: this currently only does something for + # HigherOrderOperator + self.functorch_table = {} + + def __call__(self, *args, **kwargs): + raise NotImplementedError + + def has_kernel_for_dispatch_key(self, k): + return k in self.py_kernels + + def has_kernel_for_any_dispatch_key(self, ks): + for k in self.py_kernels: + if not torch._C._dispatch_is_alias_key(k) and ks.has(k): + return True + return False + + def py_impl( + self, + k: type[TorchDispatchMode] | type[torch.Tensor] | TransformType | DispatchKey, + ) -> Callable[[Callable[_P, _T]], Callable[_P, _T]]: + def inner(fn: Callable[_P, _T]) -> Callable[_P, _T]: + if inspect.isclass(k) and ( + issubclass(k, TorchDispatchMode) or issubclass(k, torch.Tensor) + ): + assert k not in self.python_key_table + # TODO(voz): Should we replace setting DispatchKey.Python entirely with setting mode keys? + self.python_key_table[k] = fn + self._dispatch_cache.clear() + return fn + + if isinstance(k, TransformType): + assert k not in self.functorch_table + self.functorch_table[k] = fn + return fn + + assert isinstance(k, DispatchKey) + assert k != DispatchKey.Python, ( + "Please register a mode for the DispatchKey.Python key instead." + ) + + if k in self.py_kernels: + raise RuntimeError( + f"Trying to override a python impl for {k} on operator {self.name()}" + ) + self.py_kernels[k] = fn + self._dispatch_cache.clear() + return fn + + return inner + + # Registers an implementation to all **3** variants of functionalization that we have: + # - DispatchKey.Functionalize + # - functorch.TransformType.Functionalize + # - FunctionalTensorMode + # Example: + # @py_functionalize_impl + # def functionalize_rule(ctx, inner_f, *args): + # args_unwrapped = ctx.unwrap_tensors(args) + # with ctx.redispatch_to_next(): + # out = ctx.functionalize(inner_f)(*args_unwrapped) + # return ctx.wrap_tensors(out) + def py_functionalize_impl( + self, fn: Callable[Concatenate["BaseFunctionalizeAPI", _P], _T] + ) -> Callable[Concatenate["BaseFunctionalizeAPI", _P], _T]: + from torch._subclasses.functional_tensor import ( + CppFunctionalizeAPI, + FunctionalTensorMode, + FunctorchFunctionalizeAPI, + PythonFunctionalizeAPI, + ) + + # Construct our three flavors of functionalization, + # each of which have slightly different wrap/unwrap/redispatch policies + def functionalize_dk_fn(*args: _P.args, **kwargs: _P.kwargs) -> _T: + return fn(CppFunctionalizeAPI(), *args, **kwargs) + + def functionalize_dispatch_mode_fn( + mode: FunctionalTensorMode | None, *args: _P.args, **kwargs: _P.kwargs + ) -> _T: + return fn(PythonFunctionalizeAPI(mode), *args, **kwargs) + + def functionalize_functorch_fn( + interpreter, *args: _P.args, **kwargs: _P.kwargs + ) -> _T: + return fn(FunctorchFunctionalizeAPI(interpreter), *args, **kwargs) + + self.py_impl(DispatchKey.Functionalize)(functionalize_dk_fn) + self.py_impl(FunctionalTensorMode)(functionalize_dispatch_mode_fn) + self.py_impl(TransformType.Functionalize)(functionalize_functorch_fn) + + return fn + + def name(self): + raise NotImplementedError + + +# Equivalent to computeDispatchTableEntryWithDebug +def resolve_key(op: OperatorBase, k: DispatchKey): # type: ignore[valid-type] + # 1. (Direct) operator registration + if op.has_kernel_for_dispatch_key(k): + return k + # 2.1 Use CompositeExplicitAutogradNonFunctional kernel if available + cand = DispatchKey.CompositeExplicitAutogradNonFunctional + if ( + k == DispatchKey.Undefined or is_included_in_alias(k, cand) + ) and op.has_kernel_for_dispatch_key(cand): + return cand + # 2.2 Use CompositeExplicitAutograd kernel if available + cand = DispatchKey.CompositeExplicitAutograd + if ( + k == DispatchKey.Undefined or is_included_in_alias(k, cand) + ) and op.has_kernel_for_dispatch_key(cand): + return cand + has_backend_kernel = op.has_kernel_for_any_dispatch_key( + torch._C._dispatch_get_backend_keyset_from_autograd(k) + ) or op.has_kernel_for_dispatch_key(DispatchKey.CompositeExplicitAutograd) + # 2.3. Use CompositeImplicitAutograd kernel if available + cand = DispatchKey.CompositeImplicitAutogradNestedTensor + if ( + (k != DispatchKey.Undefined and is_included_in_alias(k, cand)) + and op.has_kernel_for_dispatch_key(cand) + and not has_backend_kernel + ): + return cand + cand = DispatchKey.CompositeImplicitAutograd + if ( + k == DispatchKey.Undefined or is_included_in_alias(k, cand) + ) and op.has_kernel_for_dispatch_key(cand): + if k == DispatchKey.AutogradOther and op.has_kernel_for_any_dispatch_key( + torch._C._dispatch_autogradother_backends + ): + raise RuntimeError("ambiguous autogradother kernel") + elif not has_backend_kernel: + return cand + # 2.4. For autograd backend keys, use kernel from DispatchKey::Autograd if available + cand = DispatchKey.Autograd + if is_included_in_alias(k, cand) and op.has_kernel_for_dispatch_key(cand): + return cand + # 2.5 Use kernel from DispatchKey::FuncTorchBatchedDecomposition if available + cand = DispatchKey.FuncTorchBatchedDecomposition + if is_included_in_alias(k, cand) and op.has_kernel_for_dispatch_key(cand): + return cand + # Backend fallback + if torch._C._dispatch_has_backend_fallback(k): + # The dispatch key itself will implicitly route to backend fallback. + # This is probably not great for the pure Python implementation. + return k + raise NotImplementedError(f"could not find kernel for {op} at dispatch key {k}") + + +_higher_order_ops: dict[str, "HigherOrderOperator"] = {} + +_HIGHER_ORDER_OP_DEFAULT_FALLTHROUGH_DISPATCH_KEYS = [ + DispatchKey.PythonDispatcher, # type: ignore[attr-defined] + DispatchKey.PythonTLSSnapshot, # type: ignore[attr-defined] + DispatchKey.ADInplaceOrView, + DispatchKey.BackendSelect, + DispatchKey.AutocastCPU, # type: ignore[attr-defined] + DispatchKey.AutocastCUDA, # type: ignore[attr-defined] + DispatchKey.AutocastXPU, # type: ignore[attr-defined] +] + + +class HigherOrderOperator(OperatorBase, abc.ABC): + # The HigherOrderOperator will appear as torch.ops.higher_order.{name} + # + # If you're creating a new HigherOrderOperator, please do not change the + # default. Adding operators to the global torch.ops namespace is a bad + # practice due to name collisions. + def __init__(self, name, *, cacheable=False): + super().__init__() + if type(self) is HigherOrderOperator: + raise RuntimeError( + "Direct instantiation of HigherOrderOperator is not allowed. Please subclass it." + ) + self._name = name + + # Make _OPNamespace not scream, this whole name based association needs a good hard look + self.__name__ = name + _higher_order_ops[name] = self + self._ns = "higher_order" + self.__module__ = "torch.ops.higher_order" + self._cacheable = cacheable + + self.non_fallthrough_keys = torch._C._dispatch_keyset_full() + + for dispatch_key in _HIGHER_ORDER_OP_DEFAULT_FALLTHROUGH_DISPATCH_KEYS: + self.fallthrough(dispatch_key) + + # [NOTE] We have to register pre-dispatch key implementation + # because sometimes HOP use aot-dispatch tracing to detect certain + # mutations. This is problematic when we are functionalizing HOP + # during pre-dispatch because when the inner tracer starts, it will see + # that PreDispatch key is still active. In that case, we just redispatch + # it to next key. This is only safe to do when PreDispatch key stack has no + # active modes. + + def py_impl( + self, + k: type[TorchDispatchMode] | type[torch.Tensor] | TransformType | DispatchKey, + ) -> Callable[[Callable[_P, _T]], Callable[_P, _T]]: + if isinstance(k, DispatchKey) and not self.non_fallthrough_keys.has(k): + self.non_fallthrough_keys = self.non_fallthrough_keys.add(k) + return super().py_impl(k) + + def py_autograd_impl( + self, + fn: Callable[_P, _T], + ) -> Callable[_P, _T]: + def maybe_run_autograd(*args: _P.args, **kwargs: _P.kwargs) -> _T: + if not torch.is_grad_enabled() or pytree.tree_all_only( + torch.Tensor, + lambda t: not t.requires_grad, # type: ignore[union-attr] + (*args, kwargs), + ): + with torch._C._AutoDispatchBelowAutograd(): + return self(*args, **kwargs) + + from torch._higher_order_ops.utils import _has_gen_schema + + if _has_gen_schema(self): + schema = self.gen_schema(*args, **kwargs) + if any(arg.is_write for arg in schema.arguments): + raise RuntimeError( + f"The {self.name()} HigherOrderOperator does not currently support training " + "with in-place input or buffer mutations " + "If you require this feature, please submit an issue to PyTorch. " + "Alternatively, consider creating your own custom autograd.Function. " + ) + + return fn(*args, **kwargs) + + self.py_impl(DispatchKey.Autograd)(maybe_run_autograd) + + return fn + + @property + def namespace(self): + return self._ns + + @final + def cacheable(self) -> bool: + from torch._functorch.autograd_function import AutogradFunctionApply + + return ( + self._cacheable + or f"{self.__module__}.{self.__name__}" + in torch._inductor.config.unsafe_marked_cacheable_functions + or ( + isinstance(self, AutogradFunctionApply) + and torch._functorch.config.autograd_cache_allow_custom_autograd_functions + ) + ) + + def fallthrough(self, dispatch_key): + self.non_fallthrough_keys = self.non_fallthrough_keys.remove(dispatch_key) + + # Use positional-only argument to avoid naming collide with custom ops arguments + # that are named "self". + def dispatch(self, /, dispatch_key, *args, **kwargs): + from torch.utils._python_dispatch import _get_current_dispatch_mode + + if dispatch_key in self._dispatch_cache: + kernel = self._dispatch_cache[dispatch_key] + assert not isinstance(kernel, DispatchKey) + return kernel(*args, **kwargs) + + if dispatch_key == DispatchKey.FuncTorchDynamicLayerFrontMode: + return dispatch_functorch(self, args, kwargs) + + if dispatch_key == DispatchKey.Python: + # Keep the following 1:1 with handle_torch_function_no_python_arg_parser + # in torch/csrc/utils/python_arg_parser.cpp + + overloaded_args_list = [] + + def has_python_key(tensor): + return torch._C._dispatch_keys(tensor).has("Python") + + def check_overloaded(arg): + if isinstance(arg, torch.Tensor) and has_python_key(arg): + overloaded_args_list.append(arg) + + for arg in (*args, *kwargs.values()): + check_overloaded(arg) + if isinstance(arg, (list, tuple)): + for a in arg: + check_overloaded(a) + + overloaded_args = tuple(overloaded_args_list) + + # Step 1: dispatch on any user TorchDispatchModes + from torch.utils._python_dispatch import _pop_mode_temporarily + + curr_mode = _get_current_dispatch_mode() + if curr_mode is not None: + if type(curr_mode) in self.python_key_table: + handler = self.python_key_table[type(curr_mode)] + with _pop_mode_temporarily() as mode: + # "natural" calling convention: (mode, *args, **kwargs) + # TODO(rzou): we should support torch_dispatch calling convention too. + result = handler(mode, *args, **kwargs) + else: + if curr_mode.supports_higher_order_operators: + with _pop_mode_temporarily() as mode: + return curr_mode.__torch_dispatch__(self, [], args, kwargs) + else: + raise NotImplementedError( + f"There was no rule registered for HigherOrderOperator {self._name} and mode {curr_mode}." + f"Hint: set {curr_mode}'s supports_higher_order_operators to True." + f" This causes all higher order operators to pass through {curr_mode}'s __torch_dispatch__," + f" so handle them accordingly by" + f" adding support for HigerOrderOperators (in this case, {self._name}) in" + f" {curr_mode}.__torch_dispatch__ or" + f" returning NotImplemented when not supported." + ) + if result is not NotImplemented: + return result + + # Step 2: dispatch on any subclasses + for arg in overloaded_args: + subclass_type = type(arg) + if ( + subclass_type.__torch_dispatch__ + is torch._C._disabled_torch_dispatch_impl + ): + continue + + # In some case, people are using FakeTensor without a FakeTensorMode. + # For example, some sparse arch model has a mix of FakeTensor and real + # tensor for weights during lowering, and ppl tends to run eager evaluation + # on the model without setting up the FakeTensorMode. + # In this case, we pull FakeTensorMode impl. + if subclass_type is torch._subclasses.fake_tensor.FakeTensor: + subclass_type = torch._subclasses.fake_tensor.FakeTensorMode # type: ignore[assignment] + handler = self.python_key_table[subclass_type] + result = handler(arg.fake_mode, *args, **kwargs) # type: ignore[attr-defined] + return result + + if subclass_type in self.python_key_table: + handler = self.python_key_table[subclass_type] + # "natural" calling convention: (*args, **kwargs) + # TODO(rzou): we should support torch_dispatch calling convention too. + result = handler(*args, **kwargs) + else: + raise NotImplementedError( + f"There was no rule registered for HOP {self._name} and subclass {subclass_type}. " + f"We recommend filing an issue." + ) + if result is not NotImplemented: + return result + + # All handlers returned NotImplemented + raise TypeError( + f"HigherOrderOperator '{self._name}' is not supported for the given input types. " + f"This typically happens when using custom tensor types or dispatch modes that don't " + f"have implementations for this operation.\n\n" + f"Current mode: {curr_mode}\n" + f"Input types: {[type(a).__name__ for a in overloaded_args]}\n\n" + f"To fix this, can add support for '{self._name}' in {curr_mode}'s __torch_dispatch__\n" + ) + + functionality_key = torch._C._to_functionality_key(dispatch_key) # type: ignore[attr-defined] + if functionality_key == DispatchKey.PreDispatch: + from torch.utils._python_dispatch import _pop_mode_temporarily + + # The check for Python in the exclude set is so we properly respect `with no_dispatch()` + # calls inside of a mode. + if ( + _len_torch_dispatch_stack_pre_dispatch() > 0 + ) and not torch._C._dispatch_tls_is_dispatch_key_excluded( + DispatchKey.Python + ): + curr_mode = _get_current_dispatch_mode_pre_dispatch() + assert curr_mode is not None, ( + "Illegal invocation of dispatch on DispatchKey.PreDispatch without a mode." + ) + assert type(curr_mode) in self.python_key_table, ( + f"Current active mode {curr_mode} not registered" + ) + handler = self.python_key_table[type(curr_mode)] + with _pop_mode_temporarily(functionality_key) as mode: + return handler(mode, *args, **kwargs) + + final_key = resolve_key(self, dispatch_key) + + # This can current fail due to backend fallbacks. You just have to + # register them by hand for HigherOrderOperator. + if final_key not in self.py_kernels: + raise NotImplementedError( + f"could not find kernel for HigherOrderOperator {self._name} " + f"at dispatch key {final_key} (resolved from {dispatch_key})" + ) + + # [NOTE] We shouldn't cache PreDispatch kernel here because depending + # on what modes are active, predispatch behaviour is different. + # Also we do same thing for normal ops: + # See Note [Not Caching Per-Dispatch-Key Mode Handlers] + if dispatch_key != DispatchKey.PreDispatch: + self._dispatch_cache[dispatch_key] = self.py_kernels[final_key] + kernel = self.py_kernels[final_key] + # It's illegal to register DispatchKey to py_kernels, since there's no + # C++ kernel to call into + assert not isinstance(kernel, DispatchKey) + return kernel(*args, **kwargs) + + @abc.abstractmethod + def __call__(self, /, *args, **kwargs): + flat_args = _to_flat_tuple(args, kwargs) + if torch.overrides.has_torch_function(flat_args): + return torch.overrides.handle_torch_function( + self, flat_args, *args, **kwargs + ) + + dispatch_key_set = _compute_keyset(args, kwargs, self.non_fallthrough_keys) + return self.dispatch(dispatch_key_set.highestPriorityTypeId(), *args, **kwargs) + + # NOTE [HigherOrderOperator Schema] + # Each invocation of a HigherOrderOperator (hop) should have its own schema because + # the subgraphs and the arguments can be different even for the same hop. + # + # Each hop should implement its own gen_schema method, which should + # take the same input as the __call__ method and returns a FunctionSchema. + # The schema provides a unified way to check if the hop mutates its inputs, + # which can be useful in implementing optimizations. + # + # If the hop doesn't implement the gen_schema method, + # we expect it to be functional. It should not mutate its inputs and there + # are no input, output aliasing via views or direct referencing. + def gen_schema(self, *args, **kwargs): + raise NotImplementedError( + f"HigherOrderOperator {self._name} does not implement a gen_schema. " + f"This is OK as long as the hop is functional. " + f"e.g. it should not mutate its inputs and there are no input, output aliasing " + f"via views or direct referencing." + ) + + def __str__(self): + return f"{self.name()}" + + def name(self): + return self._name + + # it's a no-op since HigherOrderOperator is immutable and must be unique for a given op. + def __deepcopy__(self, memo=None): + return self + + +def _to_flat_tuple(args, kwargs): + return pytree.arg_tree_leaves(*args, **kwargs) + + +def _compute_keyset(args, kwargs, non_fallthrough_keys): + tensors = _get_tensors(args, kwargs) + return key_extractor(tensors, non_fallthrough_keys) + + +def _get_tensors(args, kwargs): + flat_all = _to_flat_tuple(args, kwargs) + tensor_args = [t for t in flat_all if isinstance(t, torch.Tensor)] + return tuple(tensor_args) + + +# Note - this should maintain identical impl to the C++ dispatcher key extraction logic +# at ATen/core/dispatch/DispatchKeyExtractor.h +def key_extractor(tensors, key_mask): + key_set = torch._C._dispatch_tls_local_include_set() + for tensor in tensors: + key_set = key_set | torch._C._dispatch_keys(tensor) + key_set = key_set - torch._C._dispatch_tls_local_exclude_set() + key_set = key_set & key_mask + return key_set + + +# Mode stack for PreDispatchKey +# it should always have three keys with +# priority given to FunctionalTensorMode and +# then ProxyTorchDispatchMode. It means that +# slot 0 belongs to ProxyTorchDispatchMode and +# slot 1 belongs to FunctionalTensorMode. +# +# SchemaCheckMode is separate from the other 2, +# and is only valid when the stack is empty. +# SchemaCheckMode is for testing purposes, and +# is meant to run in eager mode on concrete inputs, +# checking for incorrect schemas in regards to +# aliasing or mutating ops. +class _ModeStackStateForPreDispatch: + def __init__(self): + self.__infra_modes = [None, None] + self._schema_check_mode = None + + def set(self, index, mode): + assert index < len(self.__infra_modes) + self.__infra_modes[index] = mode + + def get(self, index): + assert index < len(self.__infra_modes) + return self.__infra_modes[index] + + def count(self): + return len([i for i in self.__infra_modes if i is not None]) + int( + self._schema_check_mode is not None + ) + + +_mode_stack_state_for_pre_dispatch = _ModeStackStateForPreDispatch() + + +def unset_mode_pre_dispatch(mode_key, schema_check=False): + current_mode_stack_pre_dispatch = mode_stack_state_for_pre_dispatch() + assert mode_key is None or mode_key in ( + torch._C._TorchDispatchModeKey.PROXY, + torch._C._TorchDispatchModeKey.FUNCTIONAL, + ) + if schema_check: + assert mode_key is None + + def _unset_mode(): + # NOTE: Using `is` rather than `==` to work around slow enum comparison in + # pybind11. + if mode_key is torch._C._TorchDispatchModeKey.PROXY: + current_mode = current_mode_stack_pre_dispatch.get(0) + mode_stack_state_for_pre_dispatch().set(0, None) + return current_mode + elif mode_key is torch._C._TorchDispatchModeKey.FUNCTIONAL: + current_mode = current_mode_stack_pre_dispatch.get(1) + mode_stack_state_for_pre_dispatch().set(1, None) + return current_mode + else: + current_mode = mode_stack_state_for_pre_dispatch()._schema_check_mode + mode_stack_state_for_pre_dispatch()._schema_check_mode = None + return current_mode + + current_mode = _unset_mode() + + new_pre_dispatch_len = _len_torch_dispatch_stack_pre_dispatch() + # When we are unsetting a mode, we need to check if there is + # active mode left on the PreDispatch key. If there is nothing + # active, we need to remove PreDispatch key from local dispatch include + # set. + if new_pre_dispatch_len == 0: + torch._C._dispatch_tls_set_dispatch_key_included(DispatchKey.PreDispatch, False) + + return current_mode + + +def _set_mode_pre_dispatch(mode): + from torch._subclasses.functional_tensor import FunctionalTensorMode + from torch._subclasses.schema_check_mode import SchemaCheckMode + from torch.fx.experimental.proxy_tensor import ProxyTorchDispatchMode + + assert isinstance( + mode, + ( + FunctionalTensorMode, + ProxyTorchDispatchMode, + SchemaCheckMode, + ), + ) + + previous_mode_stack_len = _len_torch_dispatch_stack_pre_dispatch() + if isinstance(mode, SchemaCheckMode): + current_mode = mode_stack_state_for_pre_dispatch()._schema_check_mode + if previous_mode_stack_len > 0: + raise AssertionError( + "SchemaCheckMode for pre-dispatch must be used exclusively, found other modes on the stack" + ) + mode_stack_state_for_pre_dispatch()._schema_check_mode = mode + elif isinstance(mode, FunctionalTensorMode): + current_mode = mode_stack_state_for_pre_dispatch().get(1) + assert current_mode is None + mode_stack_state_for_pre_dispatch().set(1, mode) + else: + current_mode = mode_stack_state_for_pre_dispatch().get(0) + assert current_mode is None + mode_stack_state_for_pre_dispatch().set(0, mode) + + # When we are setting a mode, we need to check if there is + # active mode left on the PreDispatch key. If there was nothing + # active before setting this mode, it means that PreDispatch key + # was turned off. So we need to turn it on again. + if previous_mode_stack_len == 0: + torch._C._dispatch_tls_set_dispatch_key_included(DispatchKey.PreDispatch, True) + + +def _pop_mode_from_pre_dispatch(): + mode_stack = mode_stack_state_for_pre_dispatch() + pre_dispatch_len = _len_torch_dispatch_stack_pre_dispatch() + + if pre_dispatch_len == 0: + raise AssertionError("Trying to pop empty mode stack") + + if mode_stack._schema_check_mode is not None: + return unset_mode_pre_dispatch(None, schema_check=True) + if mode_stack.get(1) is not None: + return unset_mode_pre_dispatch(torch._C._TorchDispatchModeKey.FUNCTIONAL) + if mode_stack.get(0) is not None: + return unset_mode_pre_dispatch(torch._C._TorchDispatchModeKey.PROXY) + + +def _len_torch_dispatch_stack_pre_dispatch(): + return mode_stack_state_for_pre_dispatch().count() + + +def _get_dispatch_mode_pre_dispatch(mode_key): + # NOTE: Using `is` rather than `==` to work around slow enum comparison in pybind11. + if mode_key is torch._C._TorchDispatchModeKey.PROXY: + return mode_stack_state_for_pre_dispatch().get(0) + else: + assert mode_key is torch._C._TorchDispatchModeKey.FUNCTIONAL + return mode_stack_state_for_pre_dispatch().get(1) + + +def _get_current_dispatch_mode_pre_dispatch(): + if mode_stack_state_for_pre_dispatch()._schema_check_mode is not None: + return mode_stack_state_for_pre_dispatch()._schema_check_mode + else: + stack_len = mode_stack_state_for_pre_dispatch().count() + if stack_len == 2: + return mode_stack_state_for_pre_dispatch().get(1) + if stack_len == 1: + return ( + mode_stack_state_for_pre_dispatch().get(1) + if mode_stack_state_for_pre_dispatch().get(1) is not None + else mode_stack_state_for_pre_dispatch().get(0) + ) + return None + + +def mode_stack_state_for_pre_dispatch(): + global _mode_stack_state_for_pre_dispatch + return _mode_stack_state_for_pre_dispatch + + +cached_ops: set["OpOverload"] = set() + + +def add_cached_op(op_overload): + global cached_ops + cached_ops.add(op_overload) + + +def reset_cached_ops(): + global cached_ops + cached_ops.clear() + + +def get_cached_ops(): + global cached_ops + return cached_ops + + +# Each OpOverload object contains pointer to a specific operator overload, a pointer to the parent `OpOverloadPacket` object. +# You can obtain an OpOverload object through attribute query on OpOverloadPacket. +class OpOverload(OperatorBase, Generic[_P, _T]): + def __init__( + self, + overloadpacket: "OpOverloadPacket", + op: Callable[_P, _T], + op_dk: Callable[Concatenate[DispatchKey, _P], _T], + schema: torch._C.FunctionSchema, + tags: list[Any], + ) -> None: + super().__init__() + self._op = op + self._op_dk = op_dk + self._schema = schema + self._overloadpacket = overloadpacket + self._tags = tags + self._overloadname = ( + "default" if schema.overload_name == "" else schema.overload_name + ) + if tags: + self._nondeterministic_seeded = torch.Tag.nondeterministic_seeded in tags + self._name = self._schema.name + if schema.overload_name: + self._name += "." + schema.overload_name + self.__name__ = f"{self._schema.name.split('::')[1]}.{self._overloadname}" + self.__module__ = overloadpacket.__module__ + op.__module__ = overloadpacket.__module__ + self.__qualname__ = self._name + self.__annotations__ = {} + + # If the OpOverload was constructed from a Library.def in Python. + self._defined_in_python = self.__qualname__ in torch.library._defs + + # Logic replicated from aten/src/ATen/native/MathBitsFallback.h + is_write = None + for a in self._schema.arguments: # pyrefly: ignore # bad-assignment + if a.alias_info is None: + continue + if is_write is None: + is_write = a.alias_info.is_write + else: + # We will conservatively call mixed mutable/non-mutable + # aliased inputs as NOT a view + is_write = a.alias_info.is_write or is_write + self.is_view = is_write is not None and not is_write + + @cached_property + def _namespace(self) -> str: + return self._schema.name.split("::", maxsplit=1)[0] + + @cached_property + def _opname(self) -> str: + return self._schema.name.split("::", maxsplit=1)[1] + + @cached_property + def _handle(self) -> torch._C._DispatchOperatorHandle: + return torch._C._dispatch_find_schema_or_throw( + self._schema.name, self._schema.overload_name + ) + + # it's a no-op since OpOverload object is immutable and must be unique for a given op overload. + def __deepcopy__(self, memo=None): + return self + + def __repr__(self): + return f"" + + # Use positional-only argument to avoid naming collision with aten ops arguments + # that are named "self". This way, all the aten ops can be called by kwargs. + def __call__(self, /, *args: _P.args, **kwargs: _P.kwargs) -> _T: + return self._op(*args, **kwargs) + + # Use positional-only argument to avoid naming collision with aten ops arguments + # that are named "self". This way, all the aten ops can be called by kwargs. + def redispatch( + self, /, keyset: torch._C.DispatchKeySet, *args: _P.args, **kwargs: _P.kwargs + ) -> _T: + return self._handle.redispatch_boxed(keyset, *args, **kwargs) # type: ignore[return-value] + + def __hash__(self): + return hash(self._op) + + # `my_namespace.my_op_name.overload_name` + def __str__(self): + return "{}.{}.{}".format(*self._schema.name.split("::"), self._overloadname) + + def has_kernel_for_dispatch_key(self, k: DispatchKey) -> bool: + return super().has_kernel_for_dispatch_key( + k + ) or torch._C._dispatch_has_kernel_for_dispatch_key(self.name(), k) + + def has_kernel_for_any_dispatch_key(self, ks: torch._C.DispatchKeySet) -> bool: + return torch._C._dispatch_has_kernel_for_any_dispatch_key( + self.name(), ks + ) or super().has_kernel_for_any_dispatch_key(ks) + + @property + def namespace(self) -> str: + return self._namespace + + def _can_decompose(self) -> bool: + dk = DispatchKey.CompositeImplicitAutograd + return dk in self.py_kernels or torch._C._dispatch_has_kernel_for_dispatch_key( + self.name(), dk + ) + + def decompose(self, *args: _P.args, **kwargs: _P.kwargs) -> _T: + dk = DispatchKey.CompositeImplicitAutograd + if dk in self.py_kernels: + # NB: This branch is not too necessary anymore, because we can + # apply Python CompositeImplicitAutograd *before* tracing + # using Python dispatcher (also taking advantage of the autograd + # formula). But it's included for completeness + return self.py_kernels[dk](*args, **kwargs) + elif torch._C._dispatch_has_kernel_for_dispatch_key(self.name(), dk): + return self._op_dk(dk, *args, **kwargs) + else: + return NotImplemented # pyrefly: ignore [bad-return] + + # Remove a dispatch key from the dispatch cache. This will force it to get + # recomputed the next time. Does nothing + # WARNING: if you register a dispatch key to py_kernels of an OpOverload, + # calling _del_dispatch on that key is NOT sufficient to apply your change, + # because a single registration may affect MULTIPLE dispatch keys (e.g., + # registering Autograd affects AutogradCPU). del_dispatch is to be used + # only if you are specifically modifying how get_dispatch handles a + # particular input 'key'. + def _uncache_dispatch(self, key: DispatchKey) -> None: + self._dispatch_cache.pop(key, None) + + # This implements the pre-computation logic for the Python dispatcher. + def _get_dispatch(self, key: DispatchKey) -> DispatchKey | Callable[_P, _T]: + # This is only called upon a cache miss + assert key not in self._dispatch_cache, f"{self} {key}" + + if key == DispatchKey.Python: + if not isinstance(self, TorchBindOpOverload) and not self.python_key_table: + self._dispatch_cache[key] = key + add_cached_op(self) + return key + + def handler(*args: _P.args, **kwargs: _P.kwargs) -> _T: + from torch.utils._python_dispatch import _get_current_dispatch_mode + + # TODO: We also need to handle tensor subclasses here + # TODO(voz): We should walk all the nodes here / turn it into a list, topmode is ok for now. + curr_mode = type(_get_current_dispatch_mode()) + assert curr_mode is not None, ( + "Illegal invocation of dispatch on DispatchKey.Python without a mode." + ) + + if curr_mode not in self.python_key_table: + if isinstance(self, TorchBindOpOverload): + with ( + torch.utils._python_dispatch._pop_mode_temporarily() as mode + ): + return torch._library.utils.handle_dispatch_mode( + mode, self, *args, **kwargs + ) + else: + return self._op_dk(key, *args, **kwargs) + + with torch.utils._python_dispatch._pop_mode_temporarily() as mode: + return self.python_key_table[curr_mode](mode, *args, **kwargs) # type: ignore[index] + + self._dispatch_cache[key] = handler + add_cached_op(self) + return handler + + functionality_key = torch._C._to_functionality_key(key) # type: ignore[attr-defined] + if functionality_key == DispatchKey.PreDispatch: + curr_stack_len = _len_torch_dispatch_stack_pre_dispatch() + # The check for Python in the exclude set is so we properly respect `with no_dispatch()` + # calls inside of a mode. + if ( + curr_stack_len > 0 + and not torch._C._dispatch_tls_is_dispatch_key_excluded( + DispatchKey.Python + ) + ): + + def handler(*args: _P.args, **kwargs: _P.kwargs) -> _T: + @contextlib.contextmanager + def _temporarily_pop_modes_from_pre_dispatch(): + top_mode = _pop_mode_from_pre_dispatch() + try: + yield top_mode + finally: + _set_mode_pre_dispatch(top_mode) + + with _temporarily_pop_modes_from_pre_dispatch() as curr_mode: + return torch._library.utils.handle_dispatch_mode( + curr_mode, self, *args, **kwargs + ) + + # Note [Not Caching Per-Dispatch-Key Mode Handlers] + # Note that we're not caching this handler. There isn't really a point, since the slow bit + # is the handler itself (in python). + # Also, not caching means that we don't have to reset the cache when any existing + # modes go out of scope (which in of itself takes time to loop through all operators). + return handler + + final_key = resolve_key(self, key) + + # See Note [Not Caching Per-Dispatch-Key Mode Handlers] + cache_result = key != DispatchKey.PreDispatch + + # TODO: We could potentially have lots of debugging wrappers against + # dispatch keys; design some general registration mechanism instead of + # having if statement for each of them + if key == DispatchKey.Functionalize: + import torch._dispatch.python as pydispatch + + if pydispatch.CROSSREF_FUNCTIONALIZE: + handler = pydispatch.make_crossref_functionalize(self, final_key) # type: ignore[assignment] + if cache_result: + self._dispatch_cache[key] = handler + add_cached_op(self) + return handler + + r = self.py_kernels.get(final_key, final_key) + if cache_result: + self._dispatch_cache[key] = r # pyrefly: ignore [unsupported-operation] + add_cached_op(self) + return r # pyrefly: ignore [bad-return] + + def name(self): + return self._name + + @property + def overloadpacket(self): + return self._overloadpacket + + @property + def op(self): + return self._op + + @property + def tags(self): + return self._tags + + # TODO: add more methods to expose information about input and output arguments + + +# TorchBindOpOverload are those custom ops which have at least one overload's +# schema consists of torch.ScriptObject (i.e. custom class) input. +# TorchBindOpOverload will skip C++ dispatcher and purely dispatched in python +# when its inputs contain FakeScriptObject in a similar way as higher order ops. +class TorchBindOpOverload(OpOverload[_P, _T]): + def _fallthrough_keys(self) -> list[DispatchKey]: + # TODO: we should be calling the fallback for these, but a fallthrough is almost close + # enough to the fallback in most cases that we care about. + _DEFAULT_FALLTHROUGH_KEYS = [ + DispatchKey.Autograd, + DispatchKey.AutogradCPU, + DispatchKey.AutogradCUDA, + DispatchKey.ADInplaceOrView, + DispatchKey.BackendSelect, + DispatchKey.PythonTLSSnapshot, + DispatchKey.PythonDispatcher, + DispatchKey.Functionalize, + ] + + def _may_use_fallthrough_instead_of_fallback(key: DispatchKey): + if torch._C._dispatch_has_kernel_for_dispatch_key(self.name(), key): + return torch._C._dispatch_kernel_for_dispatch_key_is_fallthrough( + self.name(), key + ) + + return ( + key not in self.py_kernels + or self.py_kernels[key] is torch.library.fallthrough_kernel + ) + + return [ + key + for key in _DEFAULT_FALLTHROUGH_KEYS + if _may_use_fallthrough_instead_of_fallback(key) + ] + + # Use positional-only argument to avoid naming collision with aten ops arguments + # that are named "self". This way, all the aten ops can be called by kwargs. + def __call__(self, /, *args: _P.args, **kwargs: _P.kwargs) -> _T: + if _must_dispatch_in_python(args, kwargs): + # When any inputs are FakeScriptObject, we need to + # skip c++ dispatcher and dispatch in python through _get_dispatch of python_dispatcher + # because C++ dispatcher will check the schema and cannot recognize FakeScriptObject. + return self._dispatch_in_python(self._fallthrough_keys(), *args, **kwargs) + return self._op(*args, **kwargs) + + def _dispatch_in_python( + self, fallthrough_keys: list[DispatchKey], *args: _P.args, **kwargs: _P.kwargs + ) -> _T: + non_fallthrough_keys = torch._C._dispatch_keyset_full() + for key in fallthrough_keys: + non_fallthrough_keys = non_fallthrough_keys.remove(key) + + dispatch_key_set = _compute_keyset(args, kwargs, non_fallthrough_keys) + dispatch_key = dispatch_key_set.highestPriorityTypeId() + + handler = ( + self._get_dispatch(dispatch_key) + if dispatch_key not in self._dispatch_cache + else self._dispatch_cache[dispatch_key] + ) + + if isinstance(handler, DispatchKey): + # fallthrough keys can be registered at runtime via torch.library.impl + # so need to add it to fallthrough_keys and re-dispatch. + if torch._C._dispatch_kernel_for_dispatch_key_is_fallthrough( + self.name(), dispatch_key + ): + return self._dispatch_in_python( + fallthrough_keys + [dispatch_key], + *args, + **kwargs, + ) + + raise RuntimeError( + f"Torchbind op {self} received a FakeScriptObject input when dispatching {handler}." + f" but no python implementation is found." + f" Please file an issue on this when you encounter this error." + f" This error can happen when you export or compile the model." + f" It can still happen even if a C++ implementation for {dispatch_key}. " + f" has been registered. That's because FakeScriptObject purely lives in python and cannot work " + f" with a C++ implementation." + ) + + assert isinstance(handler, Callable) # type: ignore[arg-type] + return handler(*args, **kwargs) # pyrefly: ignore [bad-return] + + +def _must_dispatch_in_python(args, kwargs): + return pytree.tree_any( + lambda obj: isinstance( + obj, torch._library.fake_class_registry.FakeScriptObject + ), + (args, kwargs), + ) + + +def _has_script_object_arg(schema: torch.FunctionSchema) -> bool: + return any(isinstance(arg.type, torch.ClassType) for arg in schema.arguments) + + +# OpOverloadPacket class contains pointer to a base unresolved operator that doesn't correspond to a specific operator +# You can obtain an OpOverload object through attribute query. +class OpOverloadPacket(Generic[_P, _T]): + __file__: ClassVar[str] = "torch.ops" + + def __init__( + self, + qualified_op_name: str, + op_name: str, + op: Callable[_P, _T], + overload_names: list[str], + ) -> None: + # These attributes are accessible on the object through the properties + # defined below but are immutable + self._qualified_op_name = qualified_op_name + self.__name__ = op_name + self._op = op + self._overload_names = overload_names + self._dir: list[str] = [] + self._has_torchbind_op_overload = any( + _has_script_object_arg(schema) for schema in self._schemas.values() + ) + + # it's a no-op since OpOverloadPacket object is immutable and must be unique for a given op. + def __deepcopy__(self, memo=None): + return self + + def __repr__(self): + return "".format( + *self._qualified_op_name.split("::") + ) + + def __hash__(self): + return hash(self._op) + + def __str__(self): + return "{}.{}".format(*self._qualified_op_name.split("::")) + + @property + def op(self): + return self._op + + @property + def _schemas(self): + return { + overload_name: torch._C._get_schema(self._qualified_op_name, overload_name) + for overload_name in self._overload_names + } + + def __getattr__(self, key: str) -> OpOverload[_P, _T]: + # ensure that query for dunder attributes that does not exist on + # opoverloadpacket but instead exists on the self._op object does not unnecessarily call + # `_get_operation_overload` (which is an expensive operation). + # This is done to prevent any potential slowdown. This list can be extended + # if there exists other attributes like `__name__` that only exist on self._op and not on the + # opoverloadpacket. + # This is ok since we are guaranteed that an overload name for an aten op can't start with '__' + try: + if key.startswith("__"): + return getattr(self._op, key) + except AttributeError: + # for consistency because it seems weird to + # throw an attribute error with a message containing + # an object name different from the one the attribute + # query was performed on. + raise AttributeError( + f"'{str(self)}' can't have an overload name beginning with '__' and the " + f"underlying op {str(self._op)} has no attribute {key} either." + ) from None + + try: + # This is ok since we are guaranteed that an overload name for an aten op can't be 'default' + use_key = "" if key == "default" else key + # TODO: disallow access to overloads registered by JIT + op_dk_tags = torch._C._get_operation_overload( + self._qualified_op_name, use_key + ) + if op_dk_tags is None: + raise AttributeError( + f"The underlying op of '{str(self)}' has no overload name '{key}'" + ) + + op_, op_dk_, tags = op_dk_tags + schema = torch._C._get_schema(self._qualified_op_name, use_key) + overload: OpOverload[_P, _T] = ( + OpOverload(self, op_, op_dk_, schema, tags) + if not _has_script_object_arg(schema) + else TorchBindOpOverload(self, op_, op_dk_, schema, tags) + ) + # cache the overload object + setattr(self, key, overload) + self._dir.append(key) + return overload + except RuntimeError: + raise AttributeError( + f"The underlying op of '{str(self)}' has no overload name '{key}'" + ) from None + + def __iter__(self) -> Iterator[str]: + return iter(self._dir) + + # Use positional-only argument to avoid naming collision with aten ops arguments + # that are named "self". This way, all the aten ops can be called by kwargs. + def __call__(self, /, *args: _P.args, **kwargs: _P.kwargs) -> _T: + # overloading __call__ to ensure torch.ops.foo.bar() + # is still callable from JIT + # We save the function ptr as the `op` attribute on + # OpOverloadPacket to access it here. + + # Directly calling OverloadPacket goes into C++, which will check + # the schema and cause an error for torchbind op when inputs consist of FakeScriptObject so we + # intercept it here and call TorchBindOpverload instead. + if self._has_torchbind_op_overload and _must_dispatch_in_python(args, kwargs): + # pyrefly: ignore [bad-argument-type] + return _call_overload_packet_from_python(self, *args, **kwargs) + return self._op(*args, **kwargs) + + # TODO: use this to make a __dir__ + def overloads(self): + return [n if n else "default" for n in self._overload_names] + + +# Note - this mirrors the logic of the cpp_function defined in jit/python/init.cpp +# _jit_get_operations, which calls _get_operation_for_overload_or_packet. +def _call_overload_packet_from_python( + op: OpOverloadPacket[_P, _T], *args: _P.args, **kwargs: _P.kwargs +) -> _T: + # Reuse the torch function handling logic in cpp + torch_function_called, ret = torch._C._maybe_call_torch_function_for_op_packet( + op, *args, **kwargs + ) + + if torch_function_called: + return ret + + # The following mirrors getOpWithStack. + # In cpp, we do a schema matching for the arguments, and call ToIValue to + # to check whether the arguments are valid. But need to do similar things here + # and check the schema whether the FakeScriptObject is the corresponding fake class + # of the actual class used in schema. + exceptions = {} + found_op = None + for overload_name in op.overloads(): + op_overload = getattr(op, overload_name) + try: + _ = torch._C._check_schema_allow_fake_script_object( + op_overload._schema, *args, **kwargs + ) + found_op = op_overload + break + except RuntimeError as e: + exceptions[overload_name] = e + + if found_op: + return found_op(*args, **kwargs) + + err_msg = ( + f"Fail to match any TorchBindOverload of {op} with following exceptions:\n" + ) + for key, msg in exceptions.items(): + err_msg += f"Overload name {key}:\n {msg}\n" + raise RuntimeError(err_msg) + + +# Resolution of torch.fn is different from torch.ops.aten.fn +# torch.fn uses the Python argparser, matches with the +# appropriate schema, and calls into the unboxed version of the method +# torch.ops.aten.fn resolution is done via the mechanism defined in JIT. +# JIT creates a stack of all the overloads and then tries to match the +# correct one at runtime and always calls into the boxed version of the method +# Autograd codegen creates VariableType, TracerType, +# inplace or view type and python bindings. +# Aten codegen generates tensor methods for the tensor class. + +# _OpNamespace is a subclass of ModuleType because the torch script +# allows attribute lookups on modules only. Since we want torch.ops.foo.bar() +# to work from script, we need to ensure ops and foo are modules + + +class _OpNamespace(types.ModuleType): + """ + An op namespace to dynamically bind Operators into Python. + + Say a user has created a custom Operator called "my_namespace::my_op". To + call this op, the user will write torch.ops.my_namespace.my_op(...). + At startup, this operation will not yet be bound into Python. Instead, the + following sequence of magic tricks will occur: + 1. `torch.ops.my_namespace` will invoke the `__getattr__` magic method + on the `torch.ops` object, which will create a new `_OpNamespace` + object called `my_namespace` and set it as an attribute on the `ops` + object. + 2. `torch.ops.my_namespace.my_op` will then invoke `__getattr__` on + the `my_namespace` object, which will retrieve the operation via + `torch.get_operation`, a function bound from C++, and then in a similar + fashion bind this new object onto the `my_namespace` object. + 3. `torch.ops.my_namespace.my_op(...)` then calls this new operation + and subsequent accesses will incur no further lookup (the namespace and + operation will already exist). + """ + + __file__ = "torch.ops" + + def __init__(self, name: str) -> None: + super().__init__("torch.ops." + name) + self.name = name + self._dir: list[str] = [] + + def __iter__(self) -> Iterator[str]: + return iter(self._dir) + + def __getattr__(self, op_name: str) -> OpOverloadPacket: + if op_name in ("__origin__", "__self__"): + raise AttributeError( + f"Invalid attribute '{op_name}' for '_OpNamespace' '{self.name}'" + ) + + # Get the op `my_namespace::my_op` if available. This will also check + # for overloads and raise an exception if there are more than one. + namespace_name = self.name + qualified_op_name = f"{namespace_name}::{op_name}" + module_name = self.__module__ + "." + namespace_name + + try: + op, overload_names = _get_packet(qualified_op_name, module_name) + if op is None: + raise AttributeError( + f"'_OpNamespace' '{self.name}' object has no attribute '{op_name}'" + ) + except RuntimeError as e: + # Turn this into AttributeError so getattr(obj, key, default) + # works (this is called by TorchScript with __origin__) + raise AttributeError( + f"'_OpNamespace' '{self.name}' object has no attribute '{op_name}'" + ) from e + + op.__module__ = module_name + opoverloadpacket = OpOverloadPacket( + qualified_op_name, op_name, op, overload_names + ) + opoverloadpacket.__module__ = self.__module__ + "." + namespace_name + # cache the opoverloadpacket to ensure that each op corresponds to + # a unique OpOverloadPacket object + setattr(self, op_name, opoverloadpacket) + self._dir.append(op_name) + return opoverloadpacket + + +def _get_packet(qualname, op_module): + op, overload_names = torch._C._jit_get_operation(qualname) + if op is not None: + # let the script frontend know that op is identical to the builtin op + # with qualified_op_name + torch.jit._builtins._register_builtin(op, qualname) + op.__module__ = op_module + return op, overload_names + + +def _refresh_packet(packet): + op, overload_names = _get_packet(packet._qualified_op_name, packet._op.__module__) + assert op is not None + packet._op = op + packet._overload_names = overload_names + + +class _HigherOrderNamespace(types.ModuleType): + __file__ = "torch.ops" + + def __init__(self) -> None: + super().__init__("torch.ops.higher_order") + self._dir: list[str] = [] + + def __iter__(self) -> Iterator[str]: + return iter(self._dir) + + def __getattr__(self, name: str) -> HigherOrderOperator: + # Following _OpNamespace.__getattr__, we cache the op on this object. + op = _higher_order_ops.get(name) + if op is None: + raise AttributeError( + f"'_HigherOrderNamespace' 'torch.ops.higher_order' object has no attribute '{name}'" + ) + setattr(self, name, op) + self._dir.append(name) + return op + + +class _Ops(types.ModuleType): + __file__ = "_ops.py" + + def __init__(self): + super().__init__("torch.ops") + self.loaded_libraries = set() + self.higher_order = _HigherOrderNamespace() + self._dir = [] + + def __getattr__(self, name: str) -> _OpNamespace: + # Here we are creating `torch.ops.my_namespace` + namespace = _OpNamespace(name) + setattr(self, name, namespace) + self._dir.append(name) + return namespace + + def __iter__(self) -> Iterator[str]: + return iter(self._dir) + + def import_module(self, module): + """ + Imports a Python module that has torch.library registrations. + + Generally, to extend PyTorch with custom operators, a user will + create a Python module whose import triggers registration of + the custom operators via a torch.ops.load_library call or a call + to one or more torch.library.* APIs. + + It is unexpected for Python modules to have side effects, so some + linters and formatters will complain. Use this API to import Python + modules that contain these torch.library side effects. + + Args: + module (str): The name of the Python module to import + + """ + importlib.import_module(module) + + def load_library(self, path): + """ + Loads a shared library from the given path into the current process. + + The library being loaded may run global initialization code to register + custom operators with the PyTorch JIT runtime. This allows dynamically + loading custom operators. For this, you should compile your operator + and the static registration code into a shared library object, and then + call ``torch.ops.load_library('path/to/libcustom.so')`` to load the + shared object. + + After the library is loaded, it is added to the + ``torch.ops.loaded_libraries`` attribute, a set that may be inspected + for the paths of all libraries loaded using this function. + + Args: + path (str): A path to a shared library to load. + """ + path = _utils_internal.resolve_library_path(path) + with dl_open_guard(): + # Import the shared library into the process, thus running its + # static (global) initialization code in order to register custom + # operators with the JIT. + try: + ctypes.CDLL(path) + except Exception as e: + raise OSError(f"Could not load this library: {path}") from e + self.loaded_libraries.add(path) + + +# The ops "namespace" +ops: _Ops = _Ops() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_python_dispatcher.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_python_dispatcher.py new file mode 100644 index 0000000000000000000000000000000000000000..d2d4fbbf621e560ce0e8ee5afddfb0420b3d949c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_python_dispatcher.py @@ -0,0 +1,182 @@ +# mypy: allow-untyped-defs +import re + +import torch._C as C + + +""" +PythonDispatcher class is a thin python-binding to C++ dispatcher and it +is designed to show how dispatcher precompute works. In particular, +it shows for a certain op `foo`, what the computed dispatch table looks +like after user register their kernels to certains dispatch keys. + +In the real C++ dispatcher we support many dispatch keys for different +functionalities. For simplicity PythonDispatcher only supports dispatch +keys for a single example of each use case. These use cases are listed below: + +- CPU/AutogradCPU: represents in-tree backends which we usually have dedicated inference & + autograd kernel in pytorch core library. + E.g. CPU, CUDA +- FPGA/AutogradOther: represents in-tree backends which we usually have backend specific + inference kernels, but they share the same autograd kernel specified in AutogradOther. + E.g. FPGA, SparseCsrCPU +- XLA/AutogradXLA: represents out-of-tree backends which we don't have either inference or autograd + kernel defined in pytorch core library. Backend owner is responsible for registering both + inference & autograd kernels in their extensions(e.g. torch-xla) for the operators they support. + E.g. XLA, XPU, MPS +- CompositeExplicitAutograd: alias key mapped to inference kernels of all backends like CPU, CUDA, XLA etc. + Kernels registered to this key MUST work for inference for all backends. +- Autograd: alias key mapped to autograd of all backends like AutogradCPU, AutogradXLA, AutogradOther. + Kernels registered to this key MUST work for autograd for all backends. +- CompositeImplicitAutograd: alias key CompositeImplicitAutograd = CompositeExplicitAutograd + Autograd + Kernels registered to this key MUST work for both inference + autograd for all backends. + +Note we only allow registrations to alias keys inside pytorch core library. E.g +you shouldn't register a CompositeImplicitAutograd or CompositeExplicitAutograd +kernel from torch-xla extension, instead you should upstream the kernel into +pytorch/pytorch repo so that it's available for all backends and continuously +tested even without the extension. + +Usage: + dispatcher = PythonDispatcher() + dispatcher.register(["CPU", "XLA", "CompositeImplicitAutograd"]) + print(dispatcher.dispatchTable()) # This tells you exactly which kernel is used for certain backend. + # For more debugging information + # print(dispatcher.keys()) + # print(dispatcher.registrations()) + # print(dispatcher.rawRegistrations()) + # print(dispatcher.rawDispatchTable()) +PythonDispatcher calls C++ dispatcher under the hood for to precompute dispatch table. +This file only provides the simplified API for developers, relevant test code is located in +test/test_dispatch.py +""" + + +class PythonDispatcher: + namespace = "__test__" + name = "foo" + # fmt: off + runtime_keys = [ + "CPU", "AutogradCPU", + "FPGA", "AutogradOther", + "XLA", "AutogradXLA", + "Lazy", "AutogradLazy", + ] + # fmt: on + alias_keys = [ + "CompositeExplicitAutograd", + "Autograd", + "CompositeImplicitAutograd", + ] + supported_keys = runtime_keys + alias_keys + + def __init__(self) -> None: + C._dispatch_check_invariants(self.name) # type: ignore[attr-defined] + self.ref = C._dispatch_library("FRAGMENT", self.namespace, "") + self.ref.def_("foo(Tensor x) -> Tensor") + + """ + Returns a list of dispatch keys supported by PythonDispatcher. + You can register kernels to these keys. + """ + + def keys(self): + return self.supported_keys + + """ + Register kernels to the target dispatchKeys. + dispatchKeys(list[str]): a list of dispatch keys that you want to register + your own kernel. Note that you don't need to write the kernel yourself in + this PythonDispatcher.E.g. for CPU key, a kernel(e.g fn_CPU for CPU) is + automatically generated and registered. + """ + + def register(self, dispatchKeys): + # Overridden is not supported and triggers a warning in C++ dispatcher. + if len(set(dispatchKeys)) != len(dispatchKeys): + raise RuntimeError( + f"Overridden is not allowed but found duplicates in {dispatchKeys}." + ) + # We currently forbid this in codegen instead of C++ dispatcher. + if ( + "CompositeImplicitAutograd" in dispatchKeys + and "CompositeExplicitAutograd" in dispatchKeys + ): + raise RuntimeError( + "Registration to both CompositeImplicitAutograd and CompositeExplicitAutograd is not allowed." + ) + for key in dispatchKeys: + if key not in self.supported_keys: + raise RuntimeError( + f"{key} is not supported, please select a dispatch key in {self.supported_keys}." + ) + self.ref.impl_t_t("foo", dispatch=key, debug="fn_" + key) + + """ + Helper function to format (key, kernel). + """ + + def _format_line(self, key, kernel): + return f"{key:<15} {kernel}\n" + + """ + Helper function to print a table header. + """ + + def _format_header(self, header): + s = f""" +{header} +""" + s += self._format_line("key", "kernel") + s += "---------------------------\n" + return s + + """ + Returns raw output of all registration info for debugging only. + Use registrations() for a simplified version. + """ + + def rawRegistrations(self): + return C._dispatch_dump(f"{self.namespace}::{self.name}") # type: ignore[attr-defined] + + """ + Returns raw output of computed dispatch table for debugging only. + Use dispatchTable() for a simplified version. + """ + + def rawDispatchTable(self): + return C._dispatch_dump_table(f"{self.namespace}::{self.name}") # type: ignore[attr-defined] + + """ + Returns a table(str) including all the registrations from users. + Note this includes registrations to both runtime keys and alias keys. + """ + + def registrations(self): + output = self._format_header("Registered Kernels") + state = self.rawRegistrations() + state_entries = state.split("\n") + for line in state_entries: + first = line.split(":")[0] + if any(first.startswith(k) for k in self.supported_keys): + kernel = line.split("::")[0].split(" ")[1] + output += self._format_line(first, kernel) + return output + + """ + Returns the computed dispatch table(str). Note this only include + runtime keys, registrations to alias keys have been decoded to their + mapped runtime keys. + """ + + def dispatchTable(self): + output = self._format_header("Computed Dispatch Table") + table = self.rawDispatchTable() + table_entries = table.split("\n") + regex = re.compile(r"registered at .*FallbackKernel\.cpp.*(\[)") + for line in table_entries: + k = line.split(":")[0] + if k in self.runtime_keys: + entry = regex.sub("[", line) + output += self._format_line(k, entry.split(": ")[1]) + return output diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_size_docs.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_size_docs.py new file mode 100644 index 0000000000000000000000000000000000000000..e30240a1e6f6748d34c673489f225a51c6fe8b9d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_size_docs.py @@ -0,0 +1,39 @@ +"""Adds docstrings to torch.Size functions""" + +import torch._C +from torch._C import _add_docstr as add_docstr + + +def add_docstr_all(method: str, docstr: str) -> None: + add_docstr(getattr(torch._C.Size, method), docstr) + + +add_docstr_all( + "numel", + """ +numel() -> int + +Returns the number of elements a :class:`torch.Tensor` with the given size would contain. + +More formally, for a tensor ``x = tensor.ones(10, 10)`` with size ``s = torch.Size([10, 10])``, +``x.numel() == x.size().numel() == s.numel() == 100`` holds true. + +Example:: + + >>> x=torch.ones(10, 10) + >>> s=x.size() + >>> s + torch.Size([10, 10]) + >>> s.numel() + 100 + >>> x.numel() == s.numel() + True + + +.. warning:: + + This function does not return the number of dimensions described by :class:`torch.Size`, but instead the number + of elements a :class:`torch.Tensor` with that size would contain. + +""", +) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_sources.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_sources.py new file mode 100644 index 0000000000000000000000000000000000000000..e0ab883a8b46ced06b57bd4dc809861ae4c77af4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_sources.py @@ -0,0 +1,138 @@ +# mypy: allow-untyped-defs +import ast +import functools +import inspect +from textwrap import dedent +from typing import Any, NamedTuple + +from torch._C import ErrorReport +from torch._C._jit_tree_views import SourceRangeFactory + + +def get_source_lines_and_file( + obj: Any, + error_msg: str | None = None, +) -> tuple[list[str], int, str | None]: + """ + Wrapper around inspect.getsourcelines and inspect.getsourcefile. + + Returns: (sourcelines, file_lino, filename) + """ + filename = None # in case getsourcefile throws + try: + filename = inspect.getsourcefile(obj) + sourcelines, file_lineno = inspect.getsourcelines(obj) + except OSError as e: + msg = ( + f"Can't get source for {obj}. TorchScript requires source access in " + "order to carry out compilation, make sure original .py files are " + "available." + ) + if error_msg: + msg += "\n" + error_msg + raise OSError(msg) from e + + return sourcelines, file_lineno, filename + + +def normalize_source_lines(sourcelines: list[str]) -> list[str]: + """ + This helper function accepts a list of source lines. It finds the + indentation level of the function definition (`def`), then it indents + all lines in the function body to a point at or greater than that + level. This allows for comments and continued string literals that + are at a lower indentation than the rest of the code. + Args: + sourcelines: function source code, separated into lines by + the '\n' character + Returns: + A list of source lines that have been correctly aligned + """ + + def remove_prefix(text, prefix): + return text[text.startswith(prefix) and len(prefix) :] + + # Find the line and line number containing the function definition + idx = None + for i, l in enumerate(sourcelines): + if l.lstrip().startswith("def"): + idx = i + break + + # This will happen when the function is a lambda- we won't find "def" anywhere in the source + # lines in that case. Currently trying to JIT compile a lambda will throw an error up in + # `parse_def()`, but we might want to handle this case in the future. + if idx is None: + return sourcelines + + # Get a string representing the amount of leading whitespace + fn_def = sourcelines[idx] + whitespace = fn_def.split("def")[0] + + # Add this leading whitespace to all lines before and after the `def` + aligned_prefix = [ + whitespace + remove_prefix(s, whitespace) for s in sourcelines[:idx] + ] + aligned_suffix = [ + whitespace + remove_prefix(s, whitespace) for s in sourcelines[idx + 1 :] + ] + + # Put it together again + aligned_prefix.append(fn_def) + return aligned_prefix + aligned_suffix + + +# Thin wrapper around SourceRangeFactory to store extra metadata +# about the function-to-be-compiled. +class SourceContext(SourceRangeFactory): + def __init__( + self, + source, + filename, + file_lineno, + leading_whitespace_len, + uses_true_division=True, + funcname=None, + ): + super().__init__(source, filename, file_lineno, leading_whitespace_len) + self.uses_true_division = uses_true_division + self.filename = filename + self.funcname = funcname + + +@functools.cache +def make_source_context(*args): + return SourceContext(*args) + + +def fake_range(): + return SourceContext("", None, 0, 0).make_raw_range(0, 1) + + +class ParsedDef(NamedTuple): + ast: ast.Module + ctx: SourceContext + source: str + filename: str | None + file_lineno: int + + +def parse_def(fn): + sourcelines, file_lineno, filename = get_source_lines_and_file( + fn, ErrorReport.call_stack() + ) + sourcelines = normalize_source_lines(sourcelines) + source = "".join(sourcelines) + dedent_src = dedent(source) + py_ast = ast.parse(dedent_src) + if len(py_ast.body) != 1 or not isinstance(py_ast.body[0], ast.FunctionDef): + raise RuntimeError( + f"Expected a single top-level function: {filename}:{file_lineno}" + ) + leading_whitespace_len = len(source.split("\n", 1)[0]) - len( + dedent_src.split("\n", 1)[0] + ) + ctx = make_source_context( + source, filename, file_lineno, leading_whitespace_len, True, fn.__name__ + ) + return ParsedDef(py_ast, ctx, source, filename, file_lineno) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_storage_docs.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_storage_docs.py new file mode 100644 index 0000000000000000000000000000000000000000..f0d16bc4250ffb2a383af727c974e9f910a5b2a5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_storage_docs.py @@ -0,0 +1,42 @@ +# mypy: allow-untyped-defs +"""Adds docstrings to Storage functions""" + +import torch._C +from torch._C import _add_docstr as add_docstr + + +storage_classes = ["StorageBase"] + + +def add_docstr_all(method, docstr): + for cls_name in storage_classes: + cls = getattr(torch._C, cls_name) + try: + add_docstr(getattr(cls, method), docstr) + except AttributeError: + pass + + +add_docstr_all( + "from_file", + """ +from_file(filename, shared=False, nbytes=0) -> Storage + +Creates a CPU storage backed by a memory-mapped file. + +If ``shared`` is ``True``, then memory is shared between all processes. +All changes are written to the file. If ``shared`` is ``False``, then the changes on +the storage do not affect the file. + +``nbytes`` is the number of bytes of storage. If ``shared`` is ``False``, +then the file must contain at least ``nbytes`` bytes. If ``shared`` is +``True`` the file will be created if needed. (Note that for ``UntypedStorage`` +this argument differs from that of ``TypedStorage.from_file``) + +Args: + filename (str): file name to map + shared (bool): whether to share memory (whether ``MAP_SHARED`` or ``MAP_PRIVATE`` is passed to the + underlying `mmap(2) call `_) + nbytes (int): number of bytes of storage +""", +) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_streambase.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_streambase.py new file mode 100644 index 0000000000000000000000000000000000000000..9d71120c959b14b09309738c84d788d60e7db326 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_streambase.py @@ -0,0 +1,20 @@ +from typing_extensions import deprecated + +import torch + + +# Preserved only for BC reasons +@deprecated( + "`torch._streambase._StreamBase` is deprecated. Please use `torch.Stream` instead.", + category=FutureWarning, +) +class _StreamBase(torch.Stream): + pass + + +@deprecated( + "`torch._streambase._EventBase` is deprecated. Please use `torch.Event` instead.", + category=FutureWarning, +) +class _EventBase(torch.Event): + pass diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_tensor.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_tensor.py new file mode 100644 index 0000000000000000000000000000000000000000..c841eeb3e0d219a5077d4639f20b18050f901975 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_tensor.py @@ -0,0 +1,1889 @@ +# mypy: allow-untyped-defs +import copyreg +import enum +import functools +import itertools +import warnings +from collections import OrderedDict +from collections.abc import Callable +from copy import deepcopy +from numbers import Number +from typing import Any, cast, Concatenate, TypeVar, Union +from typing_extensions import ParamSpec + +import torch +import torch._C as _C +from torch._namedtensor_internals import ( + check_serializing_named_tensor, + is_ellipsis, + resolve_ellipsis, + single_ellipsis_index, + unzip_namedshape, + update_names, +) +from torch.overrides import ( + get_default_nowrap_functions, + handle_torch_function, + has_torch_function, + has_torch_function_unary, + has_torch_function_variadic, +) + + +_P = ParamSpec("_P") +_TensorLike = TypeVar("_TensorLike", bound=_C.TensorBase) + + +def _handle_torch_function_and_wrap_type_error_to_not_implemented( + f: Callable[Concatenate[_TensorLike, _P], "Tensor"], +) -> Callable[Concatenate[_TensorLike, _P], "Tensor"]: + @functools.wraps(f) + def wrapped(self: _TensorLike, *args: _P.args, **kwargs: _P.kwargs) -> "Tensor": + try: + # See https://github.com/pytorch/pytorch/issues/75462 + sargs = self, *args + if has_torch_function(sargs): + return handle_torch_function(wrapped, sargs, *sargs, **kwargs) + return f(self, *args, **kwargs) + except TypeError: + return NotImplemented + + return wrapped + + +# Should not be used, this is kept only for BC of loading old serialized Tensor subclasses +def _rebuild_from_type(func, type, args, dict): + if type is Tensor: + return func(*args) + + ret = func(*args).as_subclass(type) + ret.__dict__ = dict + return ret + + +def _rebuild_from_type_v2(func, new_type, args, state): + ret = func(*args) + if type(ret) is not new_type: + ret = ret.as_subclass(new_type) + # Tensor does define __setstate__ even though it doesn't define + # __getstate__. So only use __setstate__ if it is NOT the one defined + # on Tensor + if ( + getattr(ret.__class__, "__setstate__", Tensor.__setstate__) + is not Tensor.__setstate__ + ): + ret.__setstate__(state) + else: + ret = torch._utils._set_obj_state(ret, state) + return ret + + +def _dtype_to_typestr(dtype): + # CUDA devices are little-endian and tensors are stored in native byte + # order. 1-byte entries are endian-agnostic. + return { + torch.complex64: " torch.TypedStorage + + Returns the underlying :class:`TypedStorage`. + + .. warning:: + + :class:`TypedStorage` is deprecated. It will be removed in the future, and + :class:`UntypedStorage` will be the only storage class. To access the + :class:`UntypedStorage` directly, use :attr:`Tensor.untyped_storage()`. + """ + if has_torch_function_unary(self): + return handle_torch_function(Tensor.storage, (self,), self) + + torch.storage._warn_typed_storage_removal(stacklevel=2) + return self._typed_storage() + + # For internal use only, to avoid raising deprecation warning + def _typed_storage(self): + untyped_storage = self.untyped_storage() + return torch.TypedStorage( + wrap_storage=untyped_storage, dtype=self.dtype, _internal=True + ) + + def _reduce_ex_internal(self, proto): + check_serializing_named_tensor(self) + + from torch.utils.hooks import warn_if_has_hooks + + # See Note [Don't serialize hooks] + warn_if_has_hooks(self) + backward_hooks: dict[Any, Any] = OrderedDict() + + skip_data = torch.serialization._serialization_tls.skip_data + materialize_fake_tensors = ( + torch.serialization._serialization_tls.materialize_fake_tensors + ) + + if self.device.type in ["xla", "maia", "mtia"] or ( + not torch._C._has_storage(self) + and self.device.type == torch._C._get_privateuse1_backend_name() + ): + if skip_data: + raise RuntimeError( + "Cannot serialize tensors on backends with no storage under skip_data context manager" + ) + cpu_tensor = self.cpu() + return ( + torch._utils._rebuild_device_tensor_from_cpu_tensor, + (cpu_tensor, self.dtype, str(self.device), self.requires_grad), + ) + if self.device.type == "meta": + # NB: This implementation BREAKS storage sharing. Current + # hypothesis is that no one cares for meta tensors. + if skip_data: + warnings.warn( + "Serializing tensors on the meta device under skip_data context manager is a no-op", + stacklevel=2, + ) + arg_meta = ( + self.dtype, + tuple(self.size()), + self.stride(), + self.requires_grad, + ) + return (torch._utils._rebuild_meta_tensor_no_storage, arg_meta) + if self.is_quantized: + if skip_data: + raise RuntimeError( + "Cannot serialize qtensor under skip_data context manager, file an issue if you need this feature" + ) + # quantizer_params can be different type based on torch attribute + quantizer_params: ( + tuple[torch.qscheme, float, int] | tuple[Any, Tensor, Tensor, int] + ) + if self.qscheme() == torch.per_tensor_affine: + quantizer_params = ( + torch.per_tensor_affine, + self.q_scale(), + self.q_zero_point(), + ) + elif self.qscheme() in ( + torch.per_channel_affine, + torch.per_channel_affine_float_qparams, + ): + # convert scales and zero points to tuple to avoid recursive calls + # when/if we get multi-axis quantized tensors in the future, the shape + # is recoverable from the main tensor shape + quantizer_params = ( + torch.per_channel_affine, + self.q_per_channel_scales(), + self.q_per_channel_zero_points(), + self.q_per_channel_axis(), + ) + else: + raise RuntimeError( + f"Serialization is not supported for tensors of type {self.qscheme()}" + ) + # TODO: Once we decide to break serialization FC, no longer + # need to wrap with TypedStorage + args_qtensor = ( + torch.storage.TypedStorage( + wrap_storage=self._typed_storage()._untyped_storage, + dtype=self.dtype, + _internal=True, + ), + self.storage_offset(), + tuple(self.size()), + self.stride(), + quantizer_params, + self.requires_grad, + backward_hooks, + ) + return (torch._utils._rebuild_qtensor, args_qtensor) + elif self.is_sparse: + if self.layout == torch.sparse_coo: + args_sparse = ( + self.layout, + (self._indices(), self._values(), self.size(), self.is_coalesced()), + ) + else: + raise NotImplementedError( + f"sparse tensor __reduce_ex__ for layout `{self.layout}`" + ) + return (torch._utils._rebuild_sparse_tensor, args_sparse) + elif self.layout in { + torch.sparse_csr, + torch.sparse_csc, + torch.sparse_bsr, + torch.sparse_bsc, + }: + if self.layout in {torch.sparse_csr, torch.sparse_bsr}: + compressed_indices, plain_indices = ( + self.crow_indices(), + self.col_indices(), + ) + else: + compressed_indices, plain_indices = ( + self.ccol_indices(), + self.row_indices(), + ) + args_sparse_compressed = ( + self.layout, + ( + compressed_indices, + plain_indices, + self.values(), + self.size(), + ), + ) + return (torch._utils._rebuild_sparse_tensor, args_sparse_compressed) + elif self.is_nested: + if skip_data: + raise RuntimeError( + "Cannot serialize nested tensor under skip_data context manager, file an issue if you need this feature" + ) + args_nested = ( + # NB: values() currently returns the storage as a buffer in an unsafe way. + # Ideally, we'd use a private API for this instead. TODO: Switch to this if + # we ever get around to adding it. + self.values(), + self._nested_tensor_size(), + self._nested_tensor_strides(), + self._nested_tensor_storage_offsets(), + ) + return (torch._utils._rebuild_nested_tensor, args_nested) + elif ( + type(self) is not torch.Tensor + and type(self).__torch_dispatch__ is not torch.Tensor.__torch_dispatch__ + and ( + isinstance(self, torch._subclasses.functional_tensor.FunctionalTensor) + or ( + not isinstance(self, torch._subclasses.fake_tensor.FakeTensor) + and self.data_ptr() == 0 + ) + ) + ): + arg_wrapper_subclass = ( + type(self), + self.dtype, + tuple(self.size()), + self.stride(), + self.storage_offset(), + self.layout, + self.device, + self.requires_grad, + ) + return (torch._utils._rebuild_wrapper_subclass, arg_wrapper_subclass) + elif ( + type(self) is not torch.Tensor + and type(self).__torch_dispatch__ is not torch.Tensor.__torch_dispatch__ + and ( + isinstance(self, torch._subclasses.fake_tensor.FakeTensor) + and not (skip_data and materialize_fake_tensors) + ) + ): + arg_wrapper_subclass = ( + type(self), + self.dtype, + tuple(self.size()), + self.stride(), + self.storage_offset(), + self.layout, + self.device, + self.requires_grad, + ) + return (torch._utils._rebuild_wrapper_subclass, arg_wrapper_subclass) + else: + v3_dtypes = torch.storage._new_dtypes() + if self.dtype in v3_dtypes: + rebuild_func = torch._utils._rebuild_tensor_v3 + storage = self.untyped_storage() + else: + # TODO: Once we decide to break serialization FC, no longer + # need to wrap with TypedStorage + rebuild_func = torch._utils._rebuild_tensor_v2 # type: ignore[assignment] + storage = torch.storage.TypedStorage( + wrap_storage=self._typed_storage()._untyped_storage, + dtype=self.dtype, + _internal=True, + ) # type: ignore[assignment] + + # TODO: remove hasattr, it's a hack to support versions of torch that + # don't have _subclasses + if ( + hasattr(torch, "_subclasses") + and isinstance(self, torch._subclasses.fake_tensor.FakeTensor) + and skip_data + ): + storage._fake_device = self.device + + args = ( + storage, + self.storage_offset(), + tuple(self.size()), + self.stride(), + self.requires_grad, + backward_hooks, + ) # previously was self._backward_hooks + + if isinstance(storage, torch.storage.UntypedStorage): + args = args + (self.dtype,) # type: ignore[assignment] + + metadata = torch._utils.get_tensor_metadata(self) + if metadata: + args = args + (metadata,) # type: ignore[assignment] + + return (rebuild_func, args) + + def __setstate__(self, state): + if has_torch_function_unary(self): + return handle_torch_function(Tensor.__setstate__, (self,), self, state) + # Warning: this method is NOT called when you torch.load() a tensor; + # that is managed by _rebuild_tensor_v2 + if not self.is_leaf: + raise RuntimeError("__setstate__ can be only called on leaf Tensors") + if len(state) == 4: + # legacy serialization of Tensor + # pyrefly: ignore [not-iterable] + self.set_(*state) + return + elif len(state) == 5: + # legacy serialization of Variable + self.data = state[0] + state = (state[3], state[4], state[2]) + # The setting of _backward_hooks is expected to be a no-op. + # See Note [Don't serialize hooks] + self.requires_grad, _, self._backward_hooks = state + + def __repr__(self, *, tensor_contents=None): + if has_torch_function_unary(self): + return handle_torch_function( + Tensor.__repr__, (self,), self, tensor_contents=tensor_contents + ) + # All strings are unicode in Python 3. + return torch._tensor_str._str(self, tensor_contents=tensor_contents) + + def backward( + self, gradient=None, retain_graph=None, create_graph=False, inputs=None + ): + r"""Computes the gradient of current tensor wrt graph leaves. + + The graph is differentiated using the chain rule. If the tensor is + non-scalar (i.e. its data has more than one element) and requires + gradient, the function additionally requires specifying a ``gradient``. + It should be a tensor of matching type and shape, that represents + the gradient of the differentiated function w.r.t. ``self``. + + This function accumulates gradients in the leaves - you might need to zero + ``.grad`` attributes or set them to ``None`` before calling it. + See :ref:`Default gradient layouts` + for details on the memory layout of accumulated gradients. + + .. note:: + + If you run any forward ops, create ``gradient``, and/or call ``backward`` + in a user-specified CUDA stream context, see + :ref:`Stream semantics of backward passes`. + + .. note:: + + When ``inputs`` are provided and a given input is not a leaf, + the current implementation will call its grad_fn (though it is not strictly needed to get this gradients). + It is an implementation detail on which the user should not rely. + See https://github.com/pytorch/pytorch/pull/60521#issuecomment-867061780 for more details. + + Args: + gradient (Tensor, optional): The gradient of the function + being differentiated w.r.t. ``self``. + This argument can be omitted if ``self`` is a scalar. Defaults to ``None``. + retain_graph (bool, optional): If ``False``, the graph used to compute the grads will be freed; + If ``True``, it will be retained. The default is ``None``, in which case the value is inferred from ``create_graph`` + (i.e., the graph is retained only when higher-order derivative tracking is requested). Note that in nearly all cases + setting this option to True is not needed and often can be worked around in a much more efficient way. + create_graph (bool, optional): If ``True``, graph of the derivative will + be constructed, allowing to compute higher order derivative + products. Defaults to ``False``. + inputs (Sequence[Tensor], optional): Inputs w.r.t. which the gradient will be + accumulated into ``.grad``. All other tensors will be ignored. If not + provided, the gradient is accumulated into all the leaf Tensors that were + used to compute the :attr:`tensors`. Defaults to ``None``. + """ + if has_torch_function_unary(self): + return handle_torch_function( + Tensor.backward, + (self,), + self, + gradient=gradient, + retain_graph=retain_graph, + create_graph=create_graph, + inputs=inputs, + ) + torch.autograd.backward( + self, gradient, retain_graph, create_graph, inputs=inputs + ) + + def index(self, positions, dims): + """ + Index a regular tensor by binding specified positions to dims. + + This converts a regular tensor to a first-class tensor by binding + the specified positional dimensions to Dim objects. + + Args: + positions: Tuple of dimension positions to bind + dims: Dim objects or tuple of Dim objects to bind to + + Returns: + First-class tensor with specified dimensions bound + """ + # TODO: make it possible to dispatch on positions/dims + if has_torch_function_unary(self): + return handle_torch_function( + Tensor.index, + (self,), + self, + positions, + dims, + ) + + from functorch.dim import index + + return index(self, positions, dims) + + def register_hook(self, hook): + r"""Registers a backward hook. + + The hook will be called every time a gradient with respect to the + Tensor is computed. The hook should have the following signature:: + + hook(grad) -> Tensor or None + + + The hook should not modify its argument, but it can optionally return + a new gradient which will be used in place of :attr:`grad`. + + This function returns a handle with a method ``handle.remove()`` + that removes the hook from the module. + + .. note:: + See :ref:`backward-hooks-execution` for more information on how when this hook + is executed, and how its execution is ordered relative to other hooks. + + Example:: + + >>> v = torch.tensor([0., 0., 0.], requires_grad=True) + >>> h = v.register_hook(lambda grad: grad * 2) # double the gradient + >>> v.backward(torch.tensor([1., 2., 3.])) + >>> v.grad + + 2 + 4 + 6 + [torch.FloatTensor of size (3,)] + + >>> h.remove() # removes the hook + """ + if has_torch_function_unary(self): + return handle_torch_function(Tensor.register_hook, (self,), self, hook) + if not self.requires_grad: + raise RuntimeError( + "cannot register a hook on a tensor that doesn't require gradient" + ) + if self._backward_hooks is None: + self._backward_hooks = OrderedDict() + if self.grad_fn is not None: + self.grad_fn._register_hook_dict(self) + + from torch.utils.hooks import RemovableHandle + + handle = RemovableHandle(self._backward_hooks) + self._backward_hooks[handle.id] = hook + return handle + + def register_post_accumulate_grad_hook(self, hook): + r"""Registers a backward hook that runs after grad accumulation. + + The hook will be called after all gradients for a tensor have been accumulated, + meaning that the .grad field has been updated on that tensor. The post + accumulate grad hook is ONLY applicable for leaf tensors (tensors without a + .grad_fn field). Registering this hook on a non-leaf tensor will error! + + The hook should have the following signature:: + + hook(param: Tensor) -> None + + Note that, unlike other autograd hooks, this hook operates on the tensor + that requires grad and not the grad itself. The hook can in-place modify + and access its Tensor argument, including its .grad field. + + This function returns a handle with a method ``handle.remove()`` + that removes the hook from the module. + + .. note:: + See :ref:`backward-hooks-execution` for more information on how when this hook + is executed, and how its execution is ordered relative to other hooks. Since + this hook runs during the backward pass, it will run in no_grad mode (unless + create_graph is True). You can use torch.enable_grad() to re-enable autograd + within the hook if you need it. + + Example:: + + >>> v = torch.tensor([0., 0., 0.], requires_grad=True) + >>> lr = 0.01 + >>> # simulate a simple SGD update + >>> h = v.register_post_accumulate_grad_hook(lambda p: p.add_(p.grad, alpha=-lr)) + >>> v.backward(torch.tensor([1., 2., 3.])) + >>> v + tensor([-0.0100, -0.0200, -0.0300], requires_grad=True) + + >>> h.remove() # removes the hook + """ + if has_torch_function_unary(self): + return handle_torch_function( + Tensor.register_post_accumulate_grad_hook, (self,), self, hook + ) + if not self.requires_grad: + raise RuntimeError( + "cannot register a hook on a tensor that doesn't require gradient" + ) + if self.grad_fn is not None: + raise RuntimeError( + "post accumulate grad hooks cannot be registered on non-leaf tensors" + ) + if self._post_accumulate_grad_hooks is None: + self._post_accumulate_grad_hooks: dict[Any, Any] = ( + # pyrefly: ignore [bad-assignment] + OrderedDict() + ) + + from torch.utils.hooks import RemovableHandle + + handle = RemovableHandle(self._post_accumulate_grad_hooks) + self._post_accumulate_grad_hooks[handle.id] = hook + return handle + + def reinforce(self, reward): + def trim(str): + return "\n".join([line.strip() for line in str.split("\n")]) + + raise RuntimeError( + trim( + r"""reinforce() was removed. + Use torch.distributions instead. + See https://pytorch.org/docs/main/distributions.html + + Instead of: + + probs = policy_network(state) + action = probs.multinomial() + next_state, reward = env.step(action) + action.reinforce(reward) + action.backward() + + Use: + + probs = policy_network(state) + # NOTE: categorical is equivalent to what used to be called multinomial + m = torch.distributions.Categorical(probs) + action = m.sample() + next_state, reward = env.step(action) + loss = -m.log_prob(action) * reward + loss.backward() + """ + ) + ) + + detach = _C._add_docstr( + _C.TensorBase.detach, + r""" + Returns a new Tensor, detached from the current graph. + + The result will never require gradient. + + This method also affects forward mode AD gradients and the result will never + have forward mode AD gradients. + + .. note:: + + Returned Tensor shares the same storage with the original one. + In-place modifications on either of them will be seen, and may trigger + errors in correctness checks. + """, + ) + + detach_ = _C._add_docstr( + _C.TensorBase.detach_, + r""" + Detaches the Tensor from the graph that created it, making it a leaf. + Views cannot be detached in-place. + + This method also affects forward mode AD gradients and the result will never + have forward mode AD gradients. + """, + ) + + def is_shared(self): + r"""Checks if tensor is in shared memory. + + This is always ``True`` for CUDA tensors. + """ + if has_torch_function_unary(self): + return handle_torch_function(Tensor.is_shared, (self,), self) + return self._typed_storage()._is_shared() + + def share_memory_(self): + r"""Moves the underlying storage to shared memory. + + This is a no-op if the underlying storage is already in shared memory + and for CUDA tensors. Tensors in shared memory cannot be resized. + + See :meth:`torch.UntypedStorage.share_memory_` for more details. + """ + if has_torch_function_unary(self): + return handle_torch_function(Tensor.share_memory_, (self,), self) + self._typed_storage()._share_memory_() + return self + + def module_load(self, other, assign=False): + r"""Defines how to transform ``other`` when loading it into ``self`` in :meth:`~nn.Module.load_state_dict`. + + Used when :func:`~torch.__future__.get_swap_module_params_on_conversion` is ``True``. + + It is expected that ``self`` is a parameter or buffer in an ``nn.Module`` and ``other`` is the + value in the state dictionary with the corresponding key, this method defines + how ``other`` is remapped before being swapped with ``self`` via + :func:`~torch.utils.swap_tensors` in :meth:`~nn.Module.load_state_dict`. + + .. note:: + This method should always return a new object that is not ``self`` or ``other``. + For example, the default implementation returns ``self.copy_(other).detach()`` + if ``assign`` is ``False`` or ``other.detach()`` if ``assign`` is ``True``. + + Args: + other (Tensor): value in state dict with key corresponding to ``self`` + assign (bool): the assign argument passed to :meth:`nn.Module.load_state_dict` + + """ + if has_torch_function_variadic(self, other): + return handle_torch_function( + Tensor.module_load, (self, other), self, other, assign=assign + ) + + if assign: + return other.detach() + else: + return self.copy_(other).detach() + + def __reversed__(self): + r"""Reverses the tensor along dimension 0.""" + if has_torch_function_unary(self): + return handle_torch_function(Tensor.__reversed__, (self,), self) + if self.dim() == 0: + return self + else: + return self.flip(0) + + def norm( + self, + p: float | str | None = "fro", + dim=None, + keepdim=False, + dtype=None, + ): + r"""See :func:`torch.norm`""" + if has_torch_function_unary(self): + return handle_torch_function( + Tensor.norm, (self,), self, p=p, dim=dim, keepdim=keepdim, dtype=dtype + ) + return torch.norm(self, p, dim, keepdim, dtype=dtype) + + def solve(self, other): + from torch._linalg_utils import solve + + return solve(self, other) + + def lstsq(self, other): + from torch._linalg_utils import lstsq + + return lstsq(self, other) + + def eig(self, eigenvectors=False): + from torch._linalg_utils import eig + + return eig(self, eigenvectors=eigenvectors) + + def symeig(self, eigenvectors=False): + from torch._linalg_utils import _symeig + + return _symeig(self, eigenvectors=eigenvectors) + + def lu(self, pivot=True, get_infos=False): + r"""See :func:`torch.lu`""" + # If get_infos is True, then we don't need to check for errors and vice versa + if has_torch_function_unary(self): + return handle_torch_function( + Tensor.lu, (self,), self, pivot=pivot, get_infos=get_infos + ) + + LU, pivots, infos = torch._lu_with_info( + self, pivot=pivot, check_errors=(not get_infos) + ) + if get_infos: + return LU, pivots, infos + else: + return LU, pivots + + def stft( + self, + n_fft: int, + hop_length: int | None = None, + win_length: int | None = None, + window: "Tensor | None" = None, + center: bool = True, + pad_mode: str = "reflect", + normalized: bool = False, + onesided: bool | None = None, + return_complex: bool | None = None, + align_to_window: bool | None = None, + ): + r"""See :func:`torch.stft` + + .. warning:: + This function changed signature at version 0.4.1. Calling with + the previous signature may cause error or return incorrect result. + """ + if has_torch_function_unary(self): + return handle_torch_function( + Tensor.stft, + (self,), + self, + n_fft, + hop_length=hop_length, + win_length=win_length, + window=window, + center=center, + pad_mode=pad_mode, + normalized=normalized, + onesided=onesided, + return_complex=return_complex, + align_to_window=align_to_window, + ) + return torch.stft( + self, + n_fft, + hop_length, + win_length, + window, + center, + pad_mode, + normalized, + onesided, + return_complex=return_complex, + align_to_window=align_to_window, + ) + + def istft( + self, + n_fft: int, + hop_length: int | None = None, + win_length: int | None = None, + window: "Tensor | None" = None, + center: bool = True, + normalized: bool = False, + onesided: bool | None = None, + length: int | None = None, + return_complex: bool = False, + ): + r"""See :func:`torch.istft`""" + if has_torch_function_unary(self): + return handle_torch_function( + Tensor.istft, + (self,), + self, + n_fft, + hop_length=hop_length, + win_length=win_length, + window=window, + center=center, + normalized=normalized, + onesided=onesided, + length=length, + return_complex=return_complex, + ) + return torch.istft( + self, + n_fft, + hop_length, + win_length, + window, + center, + normalized, + onesided, + length, + return_complex=return_complex, + ) + + def resize(self, *sizes): + if has_torch_function_unary(self): + return handle_torch_function(Tensor.resize, (self,), self, *sizes) + warnings.warn("non-inplace resize is deprecated", stacklevel=2) + from torch.autograd._functions import Resize + + return Resize.apply(self, sizes) + + def resize_as(self, tensor): + if has_torch_function_variadic(self, tensor): + return handle_torch_function(Tensor.resize_as, (self, tensor), self, tensor) + warnings.warn("non-inplace resize_as is deprecated", stacklevel=2) + from torch.autograd._functions import Resize + + return Resize.apply(self, tensor.size()) + + def split(self, split_size, dim=0): + r"""See :func:`torch.split`""" + if has_torch_function_unary(self): + return handle_torch_function( + Tensor.split, (self,), self, split_size, dim=dim + ) + if isinstance(split_size, Tensor): + try: + split_size = int(split_size) + except ValueError: + pass + + if isinstance(split_size, (int, torch.SymInt)): + return torch._VF.split(self, split_size, dim) # type: ignore[attr-defined] + else: + return torch._VF.split_with_sizes( + self, + # pyrefly: ignore [bad-argument-type] + split_size, + dim, + ) + + def unique(self, sorted=True, return_inverse=False, return_counts=False, dim=None): + r"""Returns the unique elements of the input tensor. + + See :func:`torch.unique` + """ + if has_torch_function_unary(self): + return handle_torch_function( + Tensor.unique, + (self,), + self, + sorted=sorted, + return_inverse=return_inverse, + return_counts=return_counts, + dim=dim, + ) + return torch.unique( + self, + sorted=sorted, + return_inverse=return_inverse, + return_counts=return_counts, + dim=dim, + ) + + def unique_consecutive(self, return_inverse=False, return_counts=False, dim=None): + r"""Eliminates all but the first element from every consecutive group of equivalent elements. + + See :func:`torch.unique_consecutive` + """ + if has_torch_function_unary(self): + return handle_torch_function( + Tensor.unique_consecutive, + (self,), + self, + return_inverse=return_inverse, + return_counts=return_counts, + dim=dim, + ) + return torch.unique_consecutive( + self, return_inverse=return_inverse, return_counts=return_counts, dim=dim + ) + + @_handle_torch_function_and_wrap_type_error_to_not_implemented + def __rsub__(self, other: Union["Tensor", int, float, bool, complex]) -> "Tensor": + return _C._VariableFunctions.rsub(self, other) + + @_handle_torch_function_and_wrap_type_error_to_not_implemented + def __rdiv__(self, other: Union["Tensor", int, float, bool, complex]) -> "Tensor": + return self.reciprocal() * other + + __rtruediv__ = __rdiv__ + __itruediv__ = _C.TensorBase.__idiv__ + + # pyrefly: ignore [bad-override] + __pow__ = cast( + Callable[ + ["torch._C.TensorBase", Union["Tensor", int, float, bool, complex]], + "Tensor", + ], + _handle_torch_function_and_wrap_type_error_to_not_implemented( + _C.TensorBase.pow + ), + ) + + __ipow__ = _handle_torch_function_and_wrap_type_error_to_not_implemented( + _C.TensorBase.pow_ + ) + + @_handle_torch_function_and_wrap_type_error_to_not_implemented + def __rmod__(self, other: Union["Tensor", int, float, bool, complex]) -> "Tensor": + return torch.remainder(other, self) + + def __format__(self, format_spec): + if has_torch_function_unary(self): + return handle_torch_function(Tensor.__format__, (self,), self, format_spec) + if self.dim() == 0 and not self.is_meta and type(self) is Tensor: + # Use detach() here to avoid the warning when converting a scalar Tensor that + # requires gradients to a python number. It is ok for formatting. + return self.detach().item().__format__(format_spec) + return object.__format__(self, format_spec) + + @_handle_torch_function_and_wrap_type_error_to_not_implemented + def __rpow__(self, other: Union["Tensor", int, float, bool, complex]) -> "Tensor": + return torch.pow(other, self) + + @_handle_torch_function_and_wrap_type_error_to_not_implemented + def __floordiv__(self, other: Union["Tensor", int, float, bool]) -> "Tensor": # type: ignore[override] + # TODO(rec): the superclass says it accepts complex here, + # but torch.floor_divide says it doesn't. + return torch.floor_divide(self, other) + + @_handle_torch_function_and_wrap_type_error_to_not_implemented + def __rfloordiv__(self, other: Union["Tensor", int, float, bool]) -> "Tensor": # type: ignore[override] + return torch.floor_divide(other, self) + + @_handle_torch_function_and_wrap_type_error_to_not_implemented + def __rlshift__( + self, other: Union["Tensor", int, float, bool, complex] + ) -> "Tensor": + return torch.bitwise_left_shift(other, self) + + @_handle_torch_function_and_wrap_type_error_to_not_implemented + def __rrshift__( + self, other: Union["Tensor", int, float, bool, complex] + ) -> "Tensor": + return torch.bitwise_right_shift(other, self) + + @_handle_torch_function_and_wrap_type_error_to_not_implemented + def __rmatmul__(self, other: "Tensor") -> "Tensor": + return torch.matmul(other, self) + + __pos__ = _C.TensorBase.positive + __neg__ = _C.TensorBase.neg + __abs__ = _C.TensorBase.abs + + def __len__(self): + if has_torch_function_unary(self): + return handle_torch_function(Tensor.__len__, (self,), self) + if self.dim() == 0: + raise TypeError("len() of a 0-d tensor") + if torch._C._get_tracing_state(): + warnings.warn( + "Using len to get tensor shape might cause the trace to be incorrect. " + "Recommended usage would be tensor.shape[0]. " + "Passing a tensor of different shape might lead to errors or silently give " + "incorrect results.", + category=torch.jit.TracerWarning, + stacklevel=2, + ) + return self.shape[0] + + def __iter__(self): + # NB: we use 'imap' and not 'map' here, so that in Python 2 we get a + # generator and don't eagerly perform all the indexes. This could + # save us work, and also helps keep trace ordering deterministic + # (e.g., if you zip(*hiddens), the eager map will force all the + # indexes of hiddens[0] before hiddens[1], while the generator + # map will interleave them.) + # NB: We have intentionally skipped __torch_function__ dispatch here. + # See gh-54457 + if self.dim() == 0: + raise TypeError("iteration over a 0-d tensor") + if torch._C._get_tracing_state(): + warnings.warn( + "Iterating over a tensor might cause the trace to be incorrect. " + "Passing a tensor of different shape won't change the number of " + "iterations executed (and might lead to errors or silently give " + "incorrect results).", + category=torch.jit.TracerWarning, + stacklevel=2, + ) + return iter(self.unbind(0)) + + def __hash__(self): + # Do NOT handle __torch_function__ here as user's default + # implementation that handle most functions will most likely do it wrong. + # It can be easily overridden by defining this method on the user + # subclass if needed. + return id(self) + + def __dir__(self): + if has_torch_function_unary(self): + return handle_torch_function(Tensor.__dir__, (self,), self) + tensor_methods = dir(self.__class__) + tensor_methods.remove("volatile") # deprecated + attrs = list(self.__dict__.keys()) + keys = tensor_methods + attrs + + # property only available dense, cuda tensors + if (not self.is_cuda) or self.is_sparse: + keys.remove("__cuda_array_interface__") + + return sorted(keys) + + # Numpy array interface, to support `numpy.asarray(tensor) -> ndarray` + __array_priority__ = 1000 # prefer Tensor ops over numpy ones + + def __array__(self, dtype=None): + if has_torch_function_unary(self): + return handle_torch_function(Tensor.__array__, (self,), self, dtype=dtype) + if dtype is None: + return self.numpy() + else: + return self.numpy().astype(dtype, copy=False) + + # Wrap Numpy array again in a suitable tensor when done, to support e.g. + # `numpy.sin(tensor) -> tensor` or `numpy.greater(tensor, 0) -> ByteTensor` + def __array_wrap__(self, array): + if has_torch_function_unary(self): + return handle_torch_function( + Tensor.__array_wrap__, (self,), self, array=array + ) + if array.dtype == bool: + # Workaround, torch has no built-in bool tensor + array = array.astype("uint8") + return torch.from_numpy(array) + + def __contains__(self, element: Any, /) -> bool: + r"""Check if `element` is present in tensor + + Args: + element (Tensor or scalar): element to be checked + for presence in current tensor" + """ + if has_torch_function_unary(self): + return handle_torch_function(Tensor.__contains__, (self,), self, element) + if isinstance( + element, (torch.Tensor, Number, torch.SymInt, torch.SymFloat, torch.SymBool) + ): + # type hint doesn't understand the __contains__ result array + return bool((element == self).any().item()) # type: ignore[union-attr] + + raise RuntimeError( + f"Tensor.__contains__ only supports Tensor or scalar, but you passed in a {type(element)}." + ) + + @property + def __cuda_array_interface__(self): + """Array view description for cuda tensors. + + See: + https://numba.pydata.org/numba-doc/dev/cuda/cuda_array_interface.html + """ + if has_torch_function_unary(self): + # TODO mypy doesn't support @property, see: https://github.com/python/mypy/issues/6185 + return handle_torch_function( + Tensor.__cuda_array_interface__.__get__, # type: ignore[attr-defined] + (self,), + self, + ) + + # raise AttributeError for unsupported tensors, so that + # hasattr(cpu_tensor, "__cuda_array_interface__") is False. + if not self.is_cuda: + raise AttributeError( + f"Can't get __cuda_array_interface__ on non-CUDA tensor type: {self.type()} " + "If CUDA data is required use tensor.cuda() to copy tensor to device memory." + ) + + if self.is_sparse: + raise AttributeError( + f"Can't get __cuda_array_interface__ on sparse type: {self.type()} " + "Use Tensor.to_dense() to convert to a dense tensor first." + ) + + # RuntimeError, matching tensor.__array__() behavior. + if self.requires_grad: + raise RuntimeError( + "Can't get __cuda_array_interface__ on Variable that requires grad. " + "If gradients aren't required, use var.detach() to get Variable that doesn't require grad." + ) + + typestr = _dtype_to_typestr(self.dtype) + itemsize = self.element_size() + shape = tuple(self.shape) + if self.is_contiguous(): + # __cuda_array_interface__ v2 requires the strides to be omitted + # (either not set or set to None) for C-contiguous arrays. + strides = None + else: + strides = tuple(s * itemsize for s in self.stride()) + data_ptr = self.data_ptr() if self.numel() > 0 else 0 + data = (data_ptr, False) # read-only is false + + return dict(typestr=typestr, shape=shape, strides=strides, data=data, version=2) + + def storage_type(self): + r"""storage_type() -> type + + Returns the type of the underlying storage. + + """ + if has_torch_function_unary(self): + return handle_torch_function(Tensor.storage_type, (self,), self) + + torch.storage._warn_typed_storage_removal() + + return self._typed_storage()._get_legacy_storage_class() + + def refine_names(self, *names): # pyrefly: ignore # bad-override + r"""Refines the dimension names of :attr:`self` according to :attr:`names`. + + Refining is a special case of renaming that "lifts" unnamed dimensions. + A ``None`` dim can be refined to have any name; a named dim can only be + refined to have the same name. + + Because named tensors can coexist with unnamed tensors, refining names + gives a nice way to write named-tensor-aware code that works with both + named and unnamed tensors. + + :attr:`names` may contain up to one Ellipsis (``...``). + The Ellipsis is expanded greedily; it is expanded in-place to fill + :attr:`names` to the same length as ``self.dim()`` using names from the + corresponding indices of ``self.names``. + + Python 2 does not support Ellipsis but one may use a string literal + instead (``'...'``). + + Args: + names (iterable of str): The desired names of the output tensor. May + contain up to one Ellipsis. + + Examples:: + + >>> imgs = torch.randn(32, 3, 128, 128) + >>> named_imgs = imgs.refine_names('N', 'C', 'H', 'W') + >>> named_imgs.names + ('N', 'C', 'H', 'W') + + >>> tensor = torch.randn(2, 3, 5, 7, 11) + >>> tensor = tensor.refine_names('A', ..., 'B', 'C') + >>> tensor.names + ('A', None, None, 'B', 'C') + + .. warning:: + The named tensor API is experimental and subject to change. + + """ + if has_torch_function_unary(self): + return handle_torch_function(Tensor.refine_names, (self,), self, *names) + names = resolve_ellipsis(names, self.names, "refine_names") + return super().refine_names(names) + + def align_to(self, *names): # pyrefly: ignore # bad-override + r"""Permutes the dimensions of the :attr:`self` tensor to match the order + specified in :attr:`names`, adding size-one dims for any new names. + + All of the dims of :attr:`self` must be named in order to use this method. + The resulting tensor is a view on the original tensor. + + All dimension names of :attr:`self` must be present in :attr:`names`. + :attr:`names` may contain additional names that are not in ``self.names``; + the output tensor has a size-one dimension for each of those new names. + + :attr:`names` may contain up to one Ellipsis (``...``). + The Ellipsis is expanded to be equal to all dimension names of :attr:`self` + that are not mentioned in :attr:`names`, in the order that they appear + in :attr:`self`. + + Python 2 does not support Ellipsis but one may use a string literal + instead (``'...'``). + + Args: + names (iterable of str): The desired dimension ordering of the + output tensor. May contain up to one Ellipsis that is expanded + to all unmentioned dim names of :attr:`self`. + + Examples:: + + >>> tensor = torch.randn(2, 2, 2, 2, 2, 2) + >>> named_tensor = tensor.refine_names('A', 'B', 'C', 'D', 'E', 'F') + + # Move the F and E dims to the front while keeping the rest in order + >>> named_tensor.align_to('F', 'E', ...) + + .. warning:: + The named tensor API is experimental and subject to change. + + """ + if has_torch_function_unary(self): + return handle_torch_function(Tensor.align_to, (self,), self, *names) + ellipsis_idx = single_ellipsis_index(names, "align_to") + if ellipsis_idx is None: + return super().align_to(names) + return super().align_to( + [name for name in names if not is_ellipsis(name)], ellipsis_idx + ) + + def unflatten(self, dim, sizes): # type: ignore[override] + r""" + unflatten(dim, sizes) -> Tensor + + See :func:`torch.unflatten`. + + """ + if has_torch_function_unary(self): + return handle_torch_function(Tensor.unflatten, (self,), self, dim, sizes) + + if not sizes: + raise RuntimeError("unflatten: sizes must be non-empty") + + names = None + if isinstance(sizes, OrderedDict) or ( + isinstance(sizes, (tuple, list)) and isinstance(sizes[0], (tuple, list)) + ): + names, sizes = unzip_namedshape(sizes) + return super().unflatten(dim, sizes, names) + else: + return super().unflatten(dim, sizes) + + def rename_(self, *names, **rename_map): + """In-place version of :meth:`~Tensor.rename`.""" + + if has_torch_function_unary(self): + return handle_torch_function( + Tensor.rename_, (self,), self, *names, **rename_map + ) + + # Note [rename_ / rename API] + # The Python API for these is different from the C++ API. In Python: + # 1) tensor.rename(*names) takes a vararglist of names + # 2) tensor.rename(**rename_map) takes a map of names to rename. + # C++ is static, making it difficult to implement similar behavior. + return update_names(self, names, rename_map, inplace=True) + + def rename(self, *names, **rename_map): + """Renames dimension names of :attr:`self`. + + There are two main usages: + + ``self.rename(**rename_map)`` returns a view on tensor that has dims + renamed as specified in the mapping :attr:`rename_map`. + + ``self.rename(*names)`` returns a view on tensor, renaming all + dimensions positionally using :attr:`names`. + Use ``self.rename(None)`` to drop names on a tensor. + + One cannot specify both positional args :attr:`names` and keyword args + :attr:`rename_map`. + + Examples:: + + >>> imgs = torch.rand(2, 3, 5, 7, names=('N', 'C', 'H', 'W')) + >>> renamed_imgs = imgs.rename(N='batch', C='channels') + >>> renamed_imgs.names + ('batch', 'channels', 'H', 'W') + + >>> renamed_imgs = imgs.rename(None) + >>> renamed_imgs.names + (None, None, None, None) + + >>> renamed_imgs = imgs.rename('batch', 'channel', 'height', 'width') + >>> renamed_imgs.names + ('batch', 'channel', 'height', 'width') + + .. warning:: + The named tensor API is experimental and subject to change. + + """ + if has_torch_function_unary(self): + return handle_torch_function( + Tensor.rename, (self,), self, *names, **rename_map + ) + + # See Note [rename_ / rename API] + return update_names(self, names, rename_map, inplace=False) + + def to_sparse_coo(self): + """Convert a tensor to :ref:`coordinate format `. + + Examples:: + + >>> dense = torch.randn(5, 5) + >>> sparse = dense.to_sparse_coo() + >>> sparse._nnz() + 25 + + """ + return self.to_sparse() + + def dim_order(self, *, ambiguity_check: bool | list[torch.memory_format] = False): + """ + dim_order(ambiguity_check=False) -> tuple + + Returns the uniquely determined tuple of int describing the dim order or + physical layout of :attr:`self`. + + The dim order represents how dimensions are laid out in memory of dense tensors, + starting from the outermost to the innermost dimension. + + Note that the dim order may not always be uniquely determined. + If `ambiguity_check` is True, this function raises a RuntimeError when the dim order cannot be uniquely determined; + If `ambiguity_check` is a list of memory formats, this function raises a RuntimeError when tensor can not be interpreted + into exactly one of the given memory formats, or it cannot be uniquely determined. + If `ambiguity_check` is False, it will return one of legal dim order(s) without checking its uniqueness. + Otherwise, it will raise TypeError. + + Args: + ambiguity_check (bool or List[torch.memory_format]): The check method for ambiguity of dim order. + + Examples:: + + >>> torch.empty((2, 3, 5, 7)).dim_order() + (0, 1, 2, 3) + >>> torch.empty((2, 3, 5, 7)).transpose(1, 2).dim_order() + (0, 2, 1, 3) + >>> torch.empty((2, 3, 5, 7), memory_format=torch.channels_last).dim_order() + (0, 2, 3, 1) + >>> torch.empty((1, 2, 3, 4)).dim_order() + (0, 1, 2, 3) + >>> try: + ... torch.empty((1, 2, 3, 4)).dim_order(ambiguity_check=True) + ... except RuntimeError as e: + ... print(e) + The tensor does not have unique dim order, or cannot map to exact one of the given memory formats. + >>> torch.empty((1, 2, 3, 4)).dim_order( + ... ambiguity_check=[torch.contiguous_format, torch.channels_last] + ... ) # It can be mapped to contiguous format + (0, 1, 2, 3) + >>> try: + ... torch.empty((1, 2, 3, 4)).dim_order(ambiguity_check="ILLEGAL") # type: ignore[arg-type] + ... except TypeError as e: + ... print(e) + The ambiguity_check argument must be a bool or a list of memory formats. + + .. warning:: + The dim_order tensor API is experimental and subject to change. + """ + if has_torch_function_unary(self): + return handle_torch_function(Tensor.dim_order, (self,), self) + + if self.is_sparse: + raise AttributeError( + f"Can't get dim order on sparse type: {self.type()} " + "Use Tensor.to_dense() to convert to a dense tensor first." + ) + + # Sanity check ambiguity_check data types + if not isinstance(ambiguity_check, bool): + if not isinstance(ambiguity_check, list): + raise TypeError( + "The ambiguity_check argument must be a bool or a list of memory formats." + ) + for memory_format in ambiguity_check: + if not isinstance(memory_format, torch.memory_format): + raise TypeError( + "The ambiguity_check argument must be a bool or a list of memory formats." + ) + + def invalid_unique_memory_format(tensor, valid_memory_formats): + """ + Returns True if the tensor cannot be uniquely mapped to any of the given memory formats, False otherwise. + """ + + n_legality = 0 + + for memory_format in valid_memory_formats: + if tensor.is_contiguous(memory_format=memory_format): + n_legality += 1 + + return n_legality != 1 + + def has_multiple_dim_order(tensor): + """ + Returns True if there're multiple legal dim orders for given tensor, False otherwise. + + The tensor is considered to have multiple legal dim orders if either of the following conditions is met: + + * Singleton Dimensions: There's at least one singleteon dimension in the tensor. + Since their size is 1, they don't affect the memory offset (stride * index + is zero because index is always zero). Therefore, they can be placed anywhere + in the dimension order without changing how data is accessed. + * Same strides: Strides reflect how the tensor is stored in memory. + If any two dimensions have the same stride, swapping these dimensions won't + change how data is accessed, leading to multiple correct dimension orders. + """ + from torch.fx.experimental.symbolic_shapes import guard_or_false + + sizes = tensor.size() + strides = tensor.stride() + + # Check if there are any duplicate strides + has_duplicate_strides = any( + guard_or_false(earlier == later) + for earlier, later in itertools.pairwise(strides) + ) + + # Check if there are any singleton dimensions + has_singleton_dims = any(guard_or_false(size == 1) for size in sizes) + + return has_duplicate_strides or has_singleton_dims + + valid_memory_formats = ( + ambiguity_check if isinstance(ambiguity_check, list) else [] + ) + check_multiple_dim_order = ( + ambiguity_check if isinstance(ambiguity_check, bool) else True + ) + + if ( + check_multiple_dim_order and has_multiple_dim_order(self) + ) and invalid_unique_memory_format(self, valid_memory_formats): + raise RuntimeError( + "The tensor does not have unique dim order, or cannot map to exact one of the given memory formats." + ) + + import torch._prims_common as utils + + out_perm, raise_ambiguity = ( + utils.compute_elementwise_output_logical_to_physical_perm( + self, ambiguity_check=ambiguity_check + ) + ) + if raise_ambiguity: + raise RuntimeError("The tensor does not have unique dim order.") + return tuple(out_perm) + + def _update_names(self, names, inplace): + if has_torch_function_unary(self): + return handle_torch_function( + Tensor._update_names, (self,), self, names, inplace + ) + + # See Note [rename_ / rename API] + if inplace: + return super().rename_(names) + else: + return super().rename(names) + + @classmethod + def __torch_function__(cls, func, types, args=(), kwargs=None): + """ + This __torch_function__ implementation wraps subclasses such that + methods called on subclasses return a subclass instance instead of + a ``torch.Tensor`` instance. + + One corollary to this is that you need coverage for torch.Tensor + methods if implementing __torch_function__ for subclasses. + + We recommend always calling ``super().__torch_function__`` as the base + case when doing the above. + + While not mandatory, we recommend making `__torch_function__` a classmethod. + """ + if kwargs is None: + kwargs = {} + + if not all(issubclass(cls, t) for t in types): + return NotImplemented + + with _C.DisableTorchFunctionSubclass(): + ret = func(*args, **kwargs) + if func in get_default_nowrap_functions(): + return ret + else: + return _convert(ret, cls) + + __torch_dispatch__ = _C._disabled_torch_dispatch_impl + + def __dlpack__( + self, + *, + stream: Any | None = -1, + max_version: tuple[int, int] | None = None, + dl_device: tuple[enum.IntEnum, int] | None = None, + copy: bool | None = None, + ): + """ + Creates a DLpack `capsule https://data-apis.org/array-api/latest/design_topics/data_interchange.html#data-interchange`_ + of the current tensor to be exported to other libraries. + + This function will be called from the `from_dlpack` method + of the library that will consume the capsule. `from_dlpack` passes the current + stream to this method as part of the specification. + + Args: + stream (integer or None): An optional Python integer representing a + pointer to a CUDA stream. The current stream is synchronized with + this stream before the capsule is created, and since the capsule + shares its storage with the tensor this make it safe to access from + both streams. If -1 is passed then no synchronization is performed. + If 1 (on CUDA) or 0 (on ROCM) then the default stream is used for + synchronization. This API intentionally slightly deviates from the DLPack + guidance: the default stream is -1 (stream-preserving; no cross-stream sync), + because many from_dlpack implementations intend stream preservation. + For non-CUDA devices, -1 is treated the same as None. + + max_version (tuple[int, int] or None): An optional Python tuple with + 2 integers, representing the maximum version the caller supports. If + None (default), PyTorch will fallback to DLPack 0.8. + + dl_device (tuple[DLDeviceType, int] or None): An optional tuple specifying + in which device the exported DLPack capsule should be on. If None (default), + the exported DLPack capsule will be on the same device as ``self``. + + copy (bool or None): An optional boolean indicating whether or not to copy + ``self``. If None, PyTorch will copy only if necessary. + """ + if has_torch_function_unary(self): + args = (self,) + kwargs = { + "stream": stream, + "max_version": max_version, + "dl_device": dl_device, + "copy": copy, + } + return handle_torch_function(Tensor.__dlpack__, (self,), *args, **kwargs) + + # DLPack capsules can't capture all of PyTorch's semantics, + # so we prohibit exporting tensors that would lose their properties like + # requires_grad and having the conjugate bit set. + if self.requires_grad: + raise BufferError( + "Can't export tensors that require gradient, use tensor.detach()" + ) + if self.is_conj(): + raise BufferError("Can't export tensors with the conjugate bit set") + if self.layout != torch.strided: + raise BufferError( + "Can't export tensors with layout other than torch.strided" + ) + + if ( + self.device.type == "cuda" + and self.device.index != torch.cuda.current_device() + ): + raise BufferError( + "Can't export tensors on a different CUDA device index. " + f"Expected: {self.device.index}. " + f"Current device: {torch.cuda.current_device()}." + ) + + if stream is not None and type(stream) is not int: + # Stream pointers in CUDA/ROCm are uniquely numbered and can + # be retrieved from their integer value. + raise TypeError("stream must be ``int`` or ``none``") + elif self.device.type == "cuda" and stream != -1: + # NB: This logic handles the special case values for default + # streams and must be kept in sync with from_dlpack in + # torch/utils/dlpack.py + is_rocm = torch.version.hip is not None + is_cuda = not is_rocm + + if stream is None or (is_rocm and stream == 0) or (is_cuda and stream == 1): + stream = torch.cuda.default_stream() + else: + if is_cuda and stream == 2: + raise BufferError("per-thread default stream is not supported.") + + device_str = "CUDA" if is_cuda else "ROCm" + assert (is_cuda and stream != 0) or ( + is_rocm and stream not in (1, 2) + ), f"unsupported stream on {device_str}: {stream}." + + stream = torch.cuda.ExternalStream(stream) + + # Only synchronize on different streams + current_stream = torch.cuda.current_stream() + if stream != current_stream: + event = torch.cuda.Event() + event.record(current_stream) + stream.wait_event(event) + elif self.device.type == "cpu": + assert stream is None or stream == -1, "stream should be None on cpu." + + if self.device.type == "xla": + import torch_xla + import torch_xla.utils.dlpack as xla_dlpack + + if ( + len(torch_xla.real_devices()) <= 0 + or "cuda" not in torch_xla.real_devices()[0].lower() + ): + raise RuntimeError( + "Can't export to dlpack an XLA tensor that is not on CUDA." + ) + + # Does not support DLPack 1.0, yet. + return xla_dlpack.to_dlpack(self) + + if max_version is None or max_version[0] < 1: + # Fallback to the old, unversioned variant. + return _C._to_dlpack(self, dl_device=dl_device, copy=copy) + + return _C._to_dlpack_versioned(self, dl_device=dl_device, copy=copy) + + def __dlpack_device__(self) -> tuple[enum.IntEnum, int]: + if has_torch_function_unary(self): + return handle_torch_function(Tensor.__dlpack_device__, (self,), self) + + from torch.utils.dlpack import DLDeviceType + + device = self.device + idx = device.index if device.index is not None else 0 + torch_device_type = device.type + if torch_device_type == "cuda" and torch.version.hip is not None: + device_type = DLDeviceType.kDLROCM + elif torch_device_type == "cpu" and self.is_pinned(): + device_type = DLDeviceType.kDLCUDAHost + elif torch_device_type == "cuda": + device_type = DLDeviceType.kDLCUDA + elif torch_device_type == "cpu": + device_type = DLDeviceType.kDLCPU + elif torch_device_type == "xpu": + device_type = DLDeviceType.kDLOneAPI + elif self.device.type == "privateuse1": + device_type = DLDeviceType.kDLExtDev + elif torch_device_type == "xla": + import torch_xla + + if ( + len(torch_xla.real_devices()) <= 0 + or "cuda" not in torch_xla.real_devices()[0].lower() + ): + raise ValueError(f"Unknown device type {torch_device_type} for Dlpack") + + device_type = DLDeviceType.kDLCUDA + elif torch_device_type == "mps": + device_type = DLDeviceType.kDLMetal + else: + raise ValueError(f"Unknown device type {torch_device_type} for Dlpack") + return (device_type, idx) + + __module__ = "torch" + + +def _convert(ret, cls): + if cls is Tensor: + return ret + + if isinstance(ret, Tensor) and not isinstance(ret, cls): + ret = ret.as_subclass(cls) + + if isinstance(ret, (tuple, list)): + # Also handles things like namedtuples + ret = type(ret)(_convert(r, cls) for r in ret) + + return ret diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_tensor_docs.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_tensor_docs.py new file mode 100644 index 0000000000000000000000000000000000000000..bc5ed9d510d5a0c9a14a9349c91a3b682794123c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_tensor_docs.py @@ -0,0 +1,7004 @@ +# mypy: allow-untyped-defs +"""Adds docstrings to Tensor functions""" + +import torch._C +from torch._C import _add_docstr as add_docstr +from torch._torch_docs import parse_kwargs, reproducibility_notes + + +def add_docstr_all(method: str, docstr: str) -> None: + add_docstr(getattr(torch._C.TensorBase, method), docstr) + + +common_args = parse_kwargs( + """ + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. +""" +) + +new_common_args = parse_kwargs( + """ + size (int...): a list, tuple, or :class:`torch.Size` of integers defining the + shape of the output tensor. + dtype (:class:`torch.dtype`, optional): the desired type of returned tensor. + Default: if None, same :class:`torch.dtype` as this tensor. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if None, same :class:`torch.device` as this tensor. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. +""" +) + +add_docstr_all( + "new_tensor", + """ +new_tensor(data, *, dtype=None, device=None, requires_grad=False, layout=torch.strided, \ +pin_memory=False) -> Tensor +""" + + r""" + +Returns a new Tensor with :attr:`data` as the tensor data. +By default, the returned Tensor has the same :class:`torch.dtype` and +:class:`torch.device` as this tensor. + +.. warning:: + + :func:`new_tensor` always copies :attr:`data`. If you have a Tensor + ``data`` and want to avoid a copy, use :func:`torch.Tensor.requires_grad_` + or :func:`torch.Tensor.detach`. + If you have a numpy array and want to avoid a copy, use + :func:`torch.from_numpy`. + +.. warning:: + + When data is a tensor `x`, :func:`new_tensor()` reads out 'the data' from whatever it is passed, + and constructs a leaf variable. Therefore ``tensor.new_tensor(x)`` is equivalent to ``x.detach().clone()`` + and ``tensor.new_tensor(x, requires_grad=True)`` is equivalent to ``x.detach().clone().requires_grad_(True)``. + The equivalents using ``detach()`` and ``clone()`` are recommended. + +Args: + data (array_like): The returned Tensor copies :attr:`data`. + +Keyword args: + {dtype} + {device} + {requires_grad} + {layout} + {pin_memory} + +Example:: + + >>> tensor = torch.ones((2,), dtype=torch.int8) + >>> data = [[0, 1], [2, 3]] + >>> tensor.new_tensor(data) + tensor([[ 0, 1], + [ 2, 3]], dtype=torch.int8) + +""".format(**new_common_args), +) + +add_docstr_all( + "new_full", + """ +new_full(size, fill_value, *, dtype=None, device=None, requires_grad=False, layout=torch.strided, \ +pin_memory=False) -> Tensor +""" + + r""" + +Returns a Tensor of size :attr:`size` filled with :attr:`fill_value`. +By default, the returned Tensor has the same :class:`torch.dtype` and +:class:`torch.device` as this tensor. + +Args: + fill_value (scalar): the number to fill the output tensor with. + +Keyword args: + {dtype} + {device} + {requires_grad} + {layout} + {pin_memory} + +Example:: + + >>> tensor = torch.ones((2,), dtype=torch.float64) + >>> tensor.new_full((3, 4), 3.141592) + tensor([[ 3.1416, 3.1416, 3.1416, 3.1416], + [ 3.1416, 3.1416, 3.1416, 3.1416], + [ 3.1416, 3.1416, 3.1416, 3.1416]], dtype=torch.float64) + +""".format(**new_common_args), +) + +add_docstr_all( + "new_empty", + """ +new_empty(size, *, dtype=None, device=None, requires_grad=False, layout=torch.strided, \ +pin_memory=False) -> Tensor +""" + + r""" + +Returns a Tensor of size :attr:`size` filled with uninitialized data. +By default, the returned Tensor has the same :class:`torch.dtype` and +:class:`torch.device` as this tensor. + +Args: + size (int...): a list, tuple, or :class:`torch.Size` of integers defining the + shape of the output tensor. + +Keyword args: + {dtype} + {device} + {requires_grad} + {layout} + {pin_memory} + +Example:: + + >>> tensor = torch.ones(()) + >>> tensor.new_empty((2, 3)) + tensor([[ 5.8182e-18, 4.5765e-41, -1.0545e+30], + [ 3.0949e-41, 4.4842e-44, 0.0000e+00]]) + +""".format(**new_common_args), +) + +add_docstr_all( + "new_empty_strided", + """ +new_empty_strided(size, stride, dtype=None, device=None, requires_grad=False, layout=torch.strided, \ +pin_memory=False) -> Tensor +""" + + r""" + +Returns a Tensor of size :attr:`size` and strides :attr:`stride` filled with +uninitialized data. By default, the returned Tensor has the same +:class:`torch.dtype` and :class:`torch.device` as this tensor. + +Args: + size (int...): a list, tuple, or :class:`torch.Size` of integers defining the + shape of the output tensor. + +Keyword args: + {dtype} + {device} + {requires_grad} + {layout} + {pin_memory} + +Example:: + + >>> tensor = torch.ones(()) + >>> tensor.new_empty_strided((2, 3), (3, 1)) + tensor([[ 5.8182e-18, 4.5765e-41, -1.0545e+30], + [ 3.0949e-41, 4.4842e-44, 0.0000e+00]]) + +""".format(**new_common_args), +) + +add_docstr_all( + "new_ones", + """ +new_ones(size, *, dtype=None, device=None, requires_grad=False, layout=torch.strided, \ +pin_memory=False) -> Tensor +""" + + r""" + +Returns a Tensor of size :attr:`size` filled with ``1``. +By default, the returned Tensor has the same :class:`torch.dtype` and +:class:`torch.device` as this tensor. + +Args: + size (int...): a list, tuple, or :class:`torch.Size` of integers defining the + shape of the output tensor. + +Keyword args: + {dtype} + {device} + {requires_grad} + {layout} + {pin_memory} + +Example:: + + >>> tensor = torch.tensor((), dtype=torch.int32) + >>> tensor.new_ones((2, 3)) + tensor([[ 1, 1, 1], + [ 1, 1, 1]], dtype=torch.int32) + +""".format(**new_common_args), +) + +add_docstr_all( + "new_zeros", + """ +new_zeros(size, *, dtype=None, device=None, requires_grad=False, layout=torch.strided, \ +pin_memory=False) -> Tensor +""" + + r""" + +Returns a Tensor of size :attr:`size` filled with ``0``. +By default, the returned Tensor has the same :class:`torch.dtype` and +:class:`torch.device` as this tensor. + +Args: + size (int...): a list, tuple, or :class:`torch.Size` of integers defining the + shape of the output tensor. + +Keyword args: + {dtype} + {device} + {requires_grad} + {layout} + {pin_memory} + +Example:: + + >>> tensor = torch.tensor((), dtype=torch.float64) + >>> tensor.new_zeros((2, 3)) + tensor([[ 0., 0., 0.], + [ 0., 0., 0.]], dtype=torch.float64) + +""".format(**new_common_args), +) + +add_docstr_all( + "abs", + r""" +abs() -> Tensor + +See :func:`torch.abs` +""", +) + +add_docstr_all( + "abs_", + r""" +abs_() -> Tensor + +In-place version of :meth:`~Tensor.abs` +""", +) + +add_docstr_all( + "absolute", + r""" +absolute() -> Tensor + +Alias for :func:`abs` +""", +) + +add_docstr_all( + "absolute_", + r""" +absolute_() -> Tensor + +In-place version of :meth:`~Tensor.absolute` +Alias for :func:`abs_` +""", +) + +add_docstr_all( + "acos", + r""" +acos() -> Tensor + +See :func:`torch.acos` +""", +) + +add_docstr_all( + "acos_", + r""" +acos_() -> Tensor + +In-place version of :meth:`~Tensor.acos` +""", +) + +add_docstr_all( + "arccos", + r""" +arccos() -> Tensor + +See :func:`torch.arccos` +""", +) + +add_docstr_all( + "arccos_", + r""" +arccos_() -> Tensor + +In-place version of :meth:`~Tensor.arccos` +""", +) + +add_docstr_all( + "acosh", + r""" +acosh() -> Tensor + +See :func:`torch.acosh` +""", +) + +add_docstr_all( + "acosh_", + r""" +acosh_() -> Tensor + +In-place version of :meth:`~Tensor.acosh` +""", +) + +add_docstr_all( + "arccosh", + r""" +acosh() -> Tensor + +See :func:`torch.arccosh` +""", +) + +add_docstr_all( + "arccosh_", + r""" +acosh_() -> Tensor + +In-place version of :meth:`~Tensor.arccosh` +""", +) + +add_docstr_all( + "add", + r""" +add(other, *, alpha=1) -> Tensor + +Add a scalar or tensor to :attr:`self` tensor. If both :attr:`alpha` +and :attr:`other` are specified, each element of :attr:`other` is scaled by +:attr:`alpha` before being used. + +When :attr:`other` is a tensor, the shape of :attr:`other` must be +:ref:`broadcastable ` with the shape of the underlying +tensor + +See :func:`torch.add` +""", +) + +add_docstr_all( + "add_", + r""" +add_(other, *, alpha=1) -> Tensor + +In-place version of :meth:`~Tensor.add` +""", +) + +add_docstr_all( + "addbmm", + r""" +addbmm(batch1, batch2, *, beta=1, alpha=1) -> Tensor + +See :func:`torch.addbmm` +""", +) + +add_docstr_all( + "addbmm_", + r""" +addbmm_(batch1, batch2, *, beta=1, alpha=1) -> Tensor + +In-place version of :meth:`~Tensor.addbmm` +""", +) + +add_docstr_all( + "addcdiv", + r""" +addcdiv(tensor1, tensor2, *, value=1) -> Tensor + +See :func:`torch.addcdiv` +""", +) + +add_docstr_all( + "addcdiv_", + r""" +addcdiv_(tensor1, tensor2, *, value=1) -> Tensor + +In-place version of :meth:`~Tensor.addcdiv` +""", +) + +add_docstr_all( + "addcmul", + r""" +addcmul(tensor1, tensor2, *, value=1) -> Tensor + +See :func:`torch.addcmul` +""", +) + +add_docstr_all( + "addcmul_", + r""" +addcmul_(tensor1, tensor2, *, value=1) -> Tensor + +In-place version of :meth:`~Tensor.addcmul` +""", +) + +add_docstr_all( + "addmm", + r""" +addmm(mat1, mat2, *, beta=1, alpha=1) -> Tensor + +See :func:`torch.addmm` +""", +) + +add_docstr_all( + "addmm_", + r""" +addmm_(mat1, mat2, *, beta=1, alpha=1) -> Tensor + +In-place version of :meth:`~Tensor.addmm` +""", +) + +add_docstr_all( + "addmv", + r""" +addmv(mat, vec, *, beta=1, alpha=1) -> Tensor + +See :func:`torch.addmv` +""", +) + +add_docstr_all( + "addmv_", + r""" +addmv_(mat, vec, *, beta=1, alpha=1) -> Tensor + +In-place version of :meth:`~Tensor.addmv` +""", +) + +add_docstr_all( + "sspaddmm", + r""" +sspaddmm(mat1, mat2, *, beta=1, alpha=1) -> Tensor + +See :func:`torch.sspaddmm` +""", +) + +add_docstr_all( + "smm", + r""" +smm(mat) -> Tensor + +See :func:`torch.smm` +""", +) + +add_docstr_all( + "addr", + r""" +addr(vec1, vec2, *, beta=1, alpha=1) -> Tensor + +See :func:`torch.addr` +""", +) + +add_docstr_all( + "addr_", + r""" +addr_(vec1, vec2, *, beta=1, alpha=1) -> Tensor + +In-place version of :meth:`~Tensor.addr` +""", +) + +add_docstr_all( + "align_as", + r""" +align_as(other) -> Tensor + +Permutes the dimensions of the :attr:`self` tensor to match the dimension order +in the :attr:`other` tensor, adding size-one dims for any new names. + +This operation is useful for explicit broadcasting by names (see examples). + +All of the dims of :attr:`self` must be named in order to use this method. +The resulting tensor is a view on the original tensor. + +All dimension names of :attr:`self` must be present in ``other.names``. +:attr:`other` may contain named dimensions that are not in ``self.names``; +the output tensor has a size-one dimension for each of those new names. + +To align a tensor to a specific order, use :meth:`~Tensor.align_to`. + +Examples:: + + # Example 1: Applying a mask + >>> mask = torch.randint(2, [127, 128], dtype=torch.bool).refine_names('W', 'H') + >>> imgs = torch.randn(32, 128, 127, 3, names=('N', 'H', 'W', 'C')) + >>> imgs.masked_fill_(mask.align_as(imgs), 0) + + + # Example 2: Applying a per-channel-scale + >>> def scale_channels(input, scale): + >>> scale = scale.refine_names('C') + >>> return input * scale.align_as(input) + + >>> num_channels = 3 + >>> scale = torch.randn(num_channels, names=('C',)) + >>> imgs = torch.rand(32, 128, 128, num_channels, names=('N', 'H', 'W', 'C')) + >>> more_imgs = torch.rand(32, num_channels, 128, 128, names=('N', 'C', 'H', 'W')) + >>> videos = torch.randn(3, num_channels, 128, 128, 128, names=('N', 'C', 'H', 'W', 'D')) + + # scale_channels is agnostic to the dimension order of the input + >>> scale_channels(imgs, scale) + >>> scale_channels(more_imgs, scale) + >>> scale_channels(videos, scale) + +.. warning:: + The named tensor API is experimental and subject to change. + +""", +) + +add_docstr_all( + "all", + r""" +all(dim=None, keepdim=False) -> Tensor + +See :func:`torch.all` +""", +) + +add_docstr_all( + "allclose", + r""" +allclose(other, rtol=1e-05, atol=1e-08, equal_nan=False) -> Tensor + +See :func:`torch.allclose` +""", +) + +add_docstr_all( + "angle", + r""" +angle() -> Tensor + +See :func:`torch.angle` +""", +) + +add_docstr_all( + "any", + r""" +any(dim=None, keepdim=False) -> Tensor + +See :func:`torch.any` +""", +) + +add_docstr_all( + "apply_", + r""" +apply_(callable) -> Tensor + +Applies the function :attr:`callable` to each element in the tensor, replacing +each element with the value returned by :attr:`callable`. + +.. note:: + + This function only works with CPU tensors and should not be used in code + sections that require high performance. +""", +) + +add_docstr_all( + "asin", + r""" +asin() -> Tensor + +See :func:`torch.asin` +""", +) + +add_docstr_all( + "asin_", + r""" +asin_() -> Tensor + +In-place version of :meth:`~Tensor.asin` +""", +) + +add_docstr_all( + "arcsin", + r""" +arcsin() -> Tensor + +See :func:`torch.arcsin` +""", +) + +add_docstr_all( + "arcsin_", + r""" +arcsin_() -> Tensor + +In-place version of :meth:`~Tensor.arcsin` +""", +) + +add_docstr_all( + "asinh", + r""" +asinh() -> Tensor + +See :func:`torch.asinh` +""", +) + +add_docstr_all( + "asinh_", + r""" +asinh_() -> Tensor + +In-place version of :meth:`~Tensor.asinh` +""", +) + +add_docstr_all( + "arcsinh", + r""" +arcsinh() -> Tensor + +See :func:`torch.arcsinh` +""", +) + +add_docstr_all( + "arcsinh_", + r""" +arcsinh_() -> Tensor + +In-place version of :meth:`~Tensor.arcsinh` +""", +) + +add_docstr_all( + "as_strided", + r""" +as_strided(size, stride, storage_offset=None) -> Tensor + +See :func:`torch.as_strided` +""", +) + +add_docstr_all( + "as_strided_", + r""" +as_strided_(size, stride, storage_offset=None) -> Tensor + +In-place version of :meth:`~Tensor.as_strided` +""", +) + +add_docstr_all( + "atan", + r""" +atan() -> Tensor + +See :func:`torch.atan` +""", +) + +add_docstr_all( + "atan_", + r""" +atan_() -> Tensor + +In-place version of :meth:`~Tensor.atan` +""", +) + +add_docstr_all( + "arctan", + r""" +arctan() -> Tensor + +See :func:`torch.arctan` +""", +) + +add_docstr_all( + "arctan_", + r""" +arctan_() -> Tensor + +In-place version of :meth:`~Tensor.arctan` +""", +) + +add_docstr_all( + "atan2", + r""" +atan2(other) -> Tensor + +See :func:`torch.atan2` +""", +) + +add_docstr_all( + "atan2_", + r""" +atan2_(other) -> Tensor + +In-place version of :meth:`~Tensor.atan2` +""", +) + +add_docstr_all( + "arctan2", + r""" +arctan2(other) -> Tensor + +See :func:`torch.arctan2` +""", +) + +add_docstr_all( + "arctan2_", + r""" +atan2_(other) -> Tensor + +In-place version of :meth:`~Tensor.arctan2` +""", +) + +add_docstr_all( + "atanh", + r""" +atanh() -> Tensor + +See :func:`torch.atanh` +""", +) + +add_docstr_all( + "atanh_", + r""" +atanh_(other) -> Tensor + +In-place version of :meth:`~Tensor.atanh` +""", +) + +add_docstr_all( + "arctanh", + r""" +arctanh() -> Tensor + +See :func:`torch.arctanh` +""", +) + +add_docstr_all( + "arctanh_", + r""" +arctanh_(other) -> Tensor + +In-place version of :meth:`~Tensor.arctanh` +""", +) + +add_docstr_all( + "baddbmm", + r""" +baddbmm(batch1, batch2, *, beta=1, alpha=1) -> Tensor + +See :func:`torch.baddbmm` +""", +) + +add_docstr_all( + "baddbmm_", + r""" +baddbmm_(batch1, batch2, *, beta=1, alpha=1) -> Tensor + +In-place version of :meth:`~Tensor.baddbmm` +""", +) + +add_docstr_all( + "bernoulli", + r""" +bernoulli(*, generator=None) -> Tensor + +Returns a result tensor where each :math:`\texttt{result[i]}` is independently +sampled from :math:`\text{Bernoulli}(\texttt{self[i]})`. :attr:`self` must have +floating point ``dtype``, and the result will have the same ``dtype``. + +See :func:`torch.bernoulli` +""", +) + +add_docstr_all( + "bernoulli_", + r""" +bernoulli_(p=0.5, *, generator=None) -> Tensor + +Fills each location of :attr:`self` with an independent sample from +:math:`\text{Bernoulli}(\texttt{p})`. :attr:`self` can have integral +``dtype``. + +:attr:`p` should either be a scalar or tensor containing probabilities to be +used for drawing the binary random number. + +If it is a tensor, the :math:`\text{i}^{th}` element of :attr:`self` tensor +will be set to a value sampled from +:math:`\text{Bernoulli}(\texttt{p\_tensor[i]})`. In this case `p` must have +floating point ``dtype``. + +See also :meth:`~Tensor.bernoulli` and :func:`torch.bernoulli` +""", +) + +add_docstr_all( + "bincount", + r""" +bincount(weights=None, minlength=0) -> Tensor + +See :func:`torch.bincount` +""", +) + +add_docstr_all( + "bitwise_not", + r""" +bitwise_not() -> Tensor + +See :func:`torch.bitwise_not` +""", +) + +add_docstr_all( + "bitwise_not_", + r""" +bitwise_not_() -> Tensor + +In-place version of :meth:`~Tensor.bitwise_not` +""", +) + +add_docstr_all( + "bitwise_and", + r""" +bitwise_and() -> Tensor + +See :func:`torch.bitwise_and` +""", +) + +add_docstr_all( + "bitwise_and_", + r""" +bitwise_and_() -> Tensor + +In-place version of :meth:`~Tensor.bitwise_and` +""", +) + +add_docstr_all( + "bitwise_or", + r""" +bitwise_or() -> Tensor + +See :func:`torch.bitwise_or` +""", +) + +add_docstr_all( + "bitwise_or_", + r""" +bitwise_or_() -> Tensor + +In-place version of :meth:`~Tensor.bitwise_or` +""", +) + +add_docstr_all( + "bitwise_xor", + r""" +bitwise_xor() -> Tensor + +See :func:`torch.bitwise_xor` +""", +) + +add_docstr_all( + "bitwise_xor_", + r""" +bitwise_xor_() -> Tensor + +In-place version of :meth:`~Tensor.bitwise_xor` +""", +) + +add_docstr_all( + "bitwise_left_shift", + r""" +bitwise_left_shift(other) -> Tensor + +See :func:`torch.bitwise_left_shift` +""", +) + +add_docstr_all( + "bitwise_left_shift_", + r""" +bitwise_left_shift_(other) -> Tensor + +In-place version of :meth:`~Tensor.bitwise_left_shift` +""", +) + +add_docstr_all( + "bitwise_right_shift", + r""" +bitwise_right_shift(other) -> Tensor + +See :func:`torch.bitwise_right_shift` +""", +) + +add_docstr_all( + "bitwise_right_shift_", + r""" +bitwise_right_shift_(other) -> Tensor + +In-place version of :meth:`~Tensor.bitwise_right_shift` +""", +) + +add_docstr_all( + "broadcast_to", + r""" +broadcast_to(shape) -> Tensor + +See :func:`torch.broadcast_to`. +""", +) + +add_docstr_all( + "logical_and", + r""" +logical_and() -> Tensor + +See :func:`torch.logical_and` +""", +) + +add_docstr_all( + "logical_and_", + r""" +logical_and_() -> Tensor + +In-place version of :meth:`~Tensor.logical_and` +""", +) + +add_docstr_all( + "logical_not", + r""" +logical_not() -> Tensor + +See :func:`torch.logical_not` +""", +) + +add_docstr_all( + "logical_not_", + r""" +logical_not_() -> Tensor + +In-place version of :meth:`~Tensor.logical_not` +""", +) + +add_docstr_all( + "logical_or", + r""" +logical_or() -> Tensor + +See :func:`torch.logical_or` +""", +) + +add_docstr_all( + "logical_or_", + r""" +logical_or_() -> Tensor + +In-place version of :meth:`~Tensor.logical_or` +""", +) + +add_docstr_all( + "logical_xor", + r""" +logical_xor() -> Tensor + +See :func:`torch.logical_xor` +""", +) + +add_docstr_all( + "logical_xor_", + r""" +logical_xor_() -> Tensor + +In-place version of :meth:`~Tensor.logical_xor` +""", +) + +add_docstr_all( + "bmm", + r""" +bmm(batch2) -> Tensor + +See :func:`torch.bmm` +""", +) + +add_docstr_all( + "cauchy_", + r""" +cauchy_(median=0, sigma=1, *, generator=None) -> Tensor + +Fills the tensor with numbers drawn from the Cauchy distribution: + +.. math:: + + f(x) = \dfrac{1}{\pi} \dfrac{\sigma}{(x - \text{median})^2 + \sigma^2} + +.. note:: + Sigma (:math:`\sigma`) is used to denote the scale parameter in Cauchy distribution. +""", +) + +add_docstr_all( + "ceil", + r""" +ceil() -> Tensor + +See :func:`torch.ceil` +""", +) + +add_docstr_all( + "ceil_", + r""" +ceil_() -> Tensor + +In-place version of :meth:`~Tensor.ceil` +""", +) + +add_docstr_all( + "cholesky", + r""" +cholesky(upper=False) -> Tensor + +See :func:`torch.cholesky` +""", +) + +add_docstr_all( + "cholesky_solve", + r""" +cholesky_solve(input2, upper=False) -> Tensor + +See :func:`torch.cholesky_solve` +""", +) + +add_docstr_all( + "cholesky_inverse", + r""" +cholesky_inverse(upper=False) -> Tensor + +See :func:`torch.cholesky_inverse` +""", +) + +add_docstr_all( + "clamp", + r""" +clamp(min=None, max=None) -> Tensor + +See :func:`torch.clamp` +""", +) + +add_docstr_all( + "clamp_", + r""" +clamp_(min=None, max=None) -> Tensor + +In-place version of :meth:`~Tensor.clamp` +""", +) + +add_docstr_all( + "clip", + r""" +clip(min=None, max=None) -> Tensor + +Alias for :meth:`~Tensor.clamp`. +""", +) + +add_docstr_all( + "clip_", + r""" +clip_(min=None, max=None) -> Tensor + +Alias for :meth:`~Tensor.clamp_`. +""", +) + +add_docstr_all( + "clone", + r""" +clone(*, memory_format=torch.preserve_format) -> Tensor + +See :func:`torch.clone` +""".format(**common_args), +) + +add_docstr_all( + "coalesce", + r""" +coalesce() -> Tensor + +Returns a coalesced copy of :attr:`self` if :attr:`self` is an +:ref:`uncoalesced tensor `. + +Returns :attr:`self` if :attr:`self` is a coalesced tensor. + +.. warning:: + Throws an error if :attr:`self` is not a sparse COO tensor. +""", +) + +add_docstr_all( + "contiguous", + r""" +contiguous(memory_format=torch.contiguous_format) -> Tensor + +Returns a contiguous in memory tensor containing the same data as :attr:`self` tensor. If +:attr:`self` tensor is already in the specified memory format, this function returns the +:attr:`self` tensor. + +Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.contiguous_format``. +""", +) + +add_docstr_all( + "copy_", + r""" +copy_(src, non_blocking=False) -> Tensor + +Copies the elements from :attr:`src` into :attr:`self` tensor and returns +:attr:`self`. + +The :attr:`src` tensor must be :ref:`broadcastable ` +with the :attr:`self` tensor. It may be of a different data type or reside on a +different device. + +Args: + src (Tensor): the source tensor to copy from + non_blocking (bool, optional): if ``True`` and this copy is between CPU and GPU, + the copy may occur asynchronously with respect to the host. For other + cases, this argument has no effect. Default: ``False`` +""", +) + +add_docstr_all( + "conj", + r""" +conj() -> Tensor + +See :func:`torch.conj` +""", +) + +add_docstr_all( + "conj_physical", + r""" +conj_physical() -> Tensor + +See :func:`torch.conj_physical` +""", +) + +add_docstr_all( + "conj_physical_", + r""" +conj_physical_() -> Tensor + +In-place version of :meth:`~Tensor.conj_physical` +""", +) + +add_docstr_all( + "resolve_conj", + r""" +resolve_conj() -> Tensor + +See :func:`torch.resolve_conj` +""", +) + +add_docstr_all( + "resolve_neg", + r""" +resolve_neg() -> Tensor + +See :func:`torch.resolve_neg` +""", +) + +add_docstr_all( + "copysign", + r""" +copysign(other) -> Tensor + +See :func:`torch.copysign` +""", +) + +add_docstr_all( + "copysign_", + r""" +copysign_(other) -> Tensor + +In-place version of :meth:`~Tensor.copysign` +""", +) + +add_docstr_all( + "cos", + r""" +cos() -> Tensor + +See :func:`torch.cos` +""", +) + +add_docstr_all( + "cos_", + r""" +cos_() -> Tensor + +In-place version of :meth:`~Tensor.cos` +""", +) + +add_docstr_all( + "cosh", + r""" +cosh() -> Tensor + +See :func:`torch.cosh` +""", +) + +add_docstr_all( + "cosh_", + r""" +cosh_() -> Tensor + +In-place version of :meth:`~Tensor.cosh` +""", +) + +add_docstr_all( + "cpu", + r""" +cpu(memory_format=torch.preserve_format) -> Tensor + +Returns a copy of this object in CPU memory. + +If this object is already in CPU memory, +then no copy is performed and the original object is returned. + +Args: + {memory_format} + +""".format(**common_args), +) + +add_docstr_all( + "count_nonzero", + r""" +count_nonzero(dim=None) -> Tensor + +See :func:`torch.count_nonzero` +""", +) + +add_docstr_all( + "cov", + r""" +cov(*, correction=1, fweights=None, aweights=None) -> Tensor + +See :func:`torch.cov` +""", +) + +add_docstr_all( + "corrcoef", + r""" +corrcoef() -> Tensor + +See :func:`torch.corrcoef` +""", +) + +add_docstr_all( + "cross", + r""" +cross(other, dim=None) -> Tensor + +See :func:`torch.cross` +""", +) + +add_docstr_all( + "cuda", + r""" +cuda(device=None, non_blocking=False, memory_format=torch.preserve_format) -> Tensor + +Returns a copy of this object in CUDA memory. + +If this object is already in CUDA memory and on the correct device, +then no copy is performed and the original object is returned. + +Args: + device (:class:`torch.device`, optional): The destination GPU device. + Defaults to the current CUDA device. + non_blocking (bool, optional): If ``True`` and the source is in pinned memory, + the copy will be asynchronous with respect to the host. + Otherwise, the argument has no effect. Default: ``False``. + {memory_format} +""".format(**common_args), +) + +add_docstr_all( + "mtia", + r""" +mtia(device=None, non_blocking=False, memory_format=torch.preserve_format) -> Tensor + +Returns a copy of this object in MTIA memory. + +If this object is already in MTIA memory and on the correct device, +then no copy is performed and the original object is returned. + +Args: + device (:class:`torch.device`, optional): The destination MTIA device. + Defaults to the current MTIA device. + non_blocking (bool, optional): If ``True`` and the source is in pinned memory, + the copy will be asynchronous with respect to the host. + Otherwise, the argument has no effect. Default: ``False``. + {memory_format} +""".format(**common_args), +) + +add_docstr_all( + "ipu", + r""" +ipu(device=None, non_blocking=False, memory_format=torch.preserve_format) -> Tensor + +Returns a copy of this object in IPU memory. + +If this object is already in IPU memory and on the correct device, +then no copy is performed and the original object is returned. + +Args: + device (:class:`torch.device`, optional): The destination IPU device. + Defaults to the current IPU device. + non_blocking (bool, optional): If ``True`` and the source is in pinned memory, + the copy will be asynchronous with respect to the host. + Otherwise, the argument has no effect. Default: ``False``. + {memory_format} +""".format(**common_args), +) + +add_docstr_all( + "xpu", + r""" +xpu(device=None, non_blocking=False, memory_format=torch.preserve_format) -> Tensor + +Returns a copy of this object in XPU memory. + +If this object is already in XPU memory and on the correct device, +then no copy is performed and the original object is returned. + +Args: + device (:class:`torch.device`, optional): The destination XPU device. + Defaults to the current XPU device. + non_blocking (bool, optional): If ``True`` and the source is in pinned memory, + the copy will be asynchronous with respect to the host. + Otherwise, the argument has no effect. Default: ``False``. + {memory_format} +""".format(**common_args), +) + +add_docstr_all( + "logcumsumexp", + r""" +logcumsumexp(dim) -> Tensor + +See :func:`torch.logcumsumexp` +""", +) + +add_docstr_all( + "cummax", + r""" +cummax(dim) -> (Tensor, Tensor) + +See :func:`torch.cummax` +""", +) + +add_docstr_all( + "cummin", + r""" +cummin(dim) -> (Tensor, Tensor) + +See :func:`torch.cummin` +""", +) + +add_docstr_all( + "cumprod", + r""" +cumprod(dim, dtype=None) -> Tensor + +See :func:`torch.cumprod` +""", +) + +add_docstr_all( + "cumprod_", + r""" +cumprod_(dim, dtype=None) -> Tensor + +In-place version of :meth:`~Tensor.cumprod` +""", +) + +add_docstr_all( + "cumsum", + r""" +cumsum(dim, dtype=None) -> Tensor + +See :func:`torch.cumsum` +""", +) + +add_docstr_all( + "cumsum_", + r""" +cumsum_(dim, dtype=None) -> Tensor + +In-place version of :meth:`~Tensor.cumsum` +""", +) + +add_docstr_all( + "data_ptr", + r""" +data_ptr() -> int + +Returns the address of the first element of :attr:`self` tensor. +""", +) + +add_docstr_all( + "dequantize", + r""" +dequantize() -> Tensor + +Given a quantized Tensor, dequantize it and return the dequantized float Tensor. +""", +) + +add_docstr_all( + "dense_dim", + r""" +dense_dim() -> int + +Return the number of dense dimensions in a :ref:`sparse tensor ` :attr:`self`. + +.. note:: + Returns ``len(self.shape)`` if :attr:`self` is not a sparse tensor. + +See also :meth:`Tensor.sparse_dim` and :ref:`hybrid tensors `. +""", +) + +add_docstr_all( + "diag", + r""" +diag(diagonal=0) -> Tensor + +See :func:`torch.diag` +""", +) + +add_docstr_all( + "diag_embed", + r""" +diag_embed(offset=0, dim1=-2, dim2=-1) -> Tensor + +See :func:`torch.diag_embed` +""", +) + +add_docstr_all( + "diagflat", + r""" +diagflat(offset=0) -> Tensor + +See :func:`torch.diagflat` +""", +) + +add_docstr_all( + "diagonal", + r""" +diagonal(offset=0, dim1=0, dim2=1) -> Tensor + +See :func:`torch.diagonal` +""", +) + +add_docstr_all( + "diagonal_scatter", + r""" +diagonal_scatter(src, offset=0, dim1=0, dim2=1) -> Tensor + +See :func:`torch.diagonal_scatter` +""", +) + +add_docstr_all( + "as_strided_scatter", + r""" +as_strided_scatter(src, size, stride, storage_offset=None) -> Tensor + +See :func:`torch.as_strided_scatter` +""", +) + +add_docstr_all( + "fill_diagonal_", + r""" +fill_diagonal_(fill_value, wrap=False) -> Tensor + +Fill the main diagonal of a tensor that has at least 2-dimensions. +When dims>2, all dimensions of input must be of equal length. +This function modifies the input tensor in-place, and returns the input tensor. + +Arguments: + fill_value (Scalar): the fill value + wrap (bool, optional): the diagonal 'wrapped' after N columns for tall matrices. Default: ``False`` + +Example:: + + >>> a = torch.zeros(3, 3) + >>> a.fill_diagonal_(5) + tensor([[5., 0., 0.], + [0., 5., 0.], + [0., 0., 5.]]) + >>> b = torch.zeros(7, 3) + >>> b.fill_diagonal_(5) + tensor([[5., 0., 0.], + [0., 5., 0.], + [0., 0., 5.], + [0., 0., 0.], + [0., 0., 0.], + [0., 0., 0.], + [0., 0., 0.]]) + >>> c = torch.zeros(7, 3) + >>> c.fill_diagonal_(5, wrap=True) + tensor([[5., 0., 0.], + [0., 5., 0.], + [0., 0., 5.], + [0., 0., 0.], + [5., 0., 0.], + [0., 5., 0.], + [0., 0., 5.]]) + +""", +) + +add_docstr_all( + "floor_divide", + r""" +floor_divide(value) -> Tensor + +See :func:`torch.floor_divide` +""", +) + +add_docstr_all( + "floor_divide_", + r""" +floor_divide_(value) -> Tensor + +In-place version of :meth:`~Tensor.floor_divide` +""", +) + +add_docstr_all( + "diff", + r""" +diff(n=1, dim=-1, prepend=None, append=None) -> Tensor + +See :func:`torch.diff` +""", +) + +add_docstr_all( + "digamma", + r""" +digamma() -> Tensor + +See :func:`torch.digamma` +""", +) + +add_docstr_all( + "digamma_", + r""" +digamma_() -> Tensor + +In-place version of :meth:`~Tensor.digamma` +""", +) + +add_docstr_all( + "dim", + r""" +dim() -> int + +Returns the number of dimensions of :attr:`self` tensor. +""", +) + +add_docstr_all( + "dist", + r""" +dist(other, p=2) -> Tensor + +See :func:`torch.dist` +""", +) + +add_docstr_all( + "div", + r""" +div(value, *, rounding_mode=None) -> Tensor + +See :func:`torch.div` +""", +) + +add_docstr_all( + "div_", + r""" +div_(value, *, rounding_mode=None) -> Tensor + +In-place version of :meth:`~Tensor.div` +""", +) + +add_docstr_all( + "divide", + r""" +divide(value, *, rounding_mode=None) -> Tensor + +See :func:`torch.divide` +""", +) + +add_docstr_all( + "divide_", + r""" +divide_(value, *, rounding_mode=None) -> Tensor + +In-place version of :meth:`~Tensor.divide` +""", +) + +add_docstr_all( + "dot", + r""" +dot(other) -> Tensor + +See :func:`torch.dot` +""", +) + +add_docstr_all( + "element_size", + r""" +element_size() -> int + +Returns the size in bytes of an individual element. + +Example:: + + >>> torch.tensor([]).element_size() + 4 + >>> torch.tensor([], dtype=torch.uint8).element_size() + 1 + +""", +) + +add_docstr_all( + "eq", + r""" +eq(other) -> Tensor + +See :func:`torch.eq` +""", +) + +add_docstr_all( + "eq_", + r""" +eq_(other) -> Tensor + +In-place version of :meth:`~Tensor.eq` +""", +) + +add_docstr_all( + "equal", + r""" +equal(other) -> bool + +See :func:`torch.equal` +""", +) + +add_docstr_all( + "erf", + r""" +erf() -> Tensor + +See :func:`torch.erf` +""", +) + +add_docstr_all( + "erf_", + r""" +erf_() -> Tensor + +In-place version of :meth:`~Tensor.erf` +""", +) + +add_docstr_all( + "erfc", + r""" +erfc() -> Tensor + +See :func:`torch.erfc` +""", +) + +add_docstr_all( + "erfc_", + r""" +erfc_() -> Tensor + +In-place version of :meth:`~Tensor.erfc` +""", +) + +add_docstr_all( + "erfinv", + r""" +erfinv() -> Tensor + +See :func:`torch.erfinv` +""", +) + +add_docstr_all( + "erfinv_", + r""" +erfinv_() -> Tensor + +In-place version of :meth:`~Tensor.erfinv` +""", +) + +add_docstr_all( + "exp", + r""" +exp() -> Tensor + +See :func:`torch.exp` +""", +) + +add_docstr_all( + "exp_", + r""" +exp_() -> Tensor + +In-place version of :meth:`~Tensor.exp` +""", +) + +add_docstr_all( + "exp2", + r""" +exp2() -> Tensor + +See :func:`torch.exp2` +""", +) + +add_docstr_all( + "exp2_", + r""" +exp2_() -> Tensor + +In-place version of :meth:`~Tensor.exp2` +""", +) + +add_docstr_all( + "expm1", + r""" +expm1() -> Tensor + +See :func:`torch.expm1` +""", +) + +add_docstr_all( + "expm1_", + r""" +expm1_() -> Tensor + +In-place version of :meth:`~Tensor.expm1` +""", +) + +add_docstr_all( + "exponential_", + r""" +exponential_(lambd=1, *, generator=None) -> Tensor + +Fills :attr:`self` tensor with elements drawn from the PDF (probability density function): + +.. math:: + + f(x) = \lambda e^{-\lambda x}, x > 0 + +.. note:: + In probability theory, exponential distribution is supported on interval [0, :math:`\inf`) (i.e., :math:`x >= 0`) + implying that zero can be sampled from the exponential distribution. + However, :func:`torch.Tensor.exponential_` does not sample zero, + which means that its actual support is the interval (0, :math:`\inf`). + + Note that :func:`torch.distributions.exponential.Exponential` is supported on the interval [0, :math:`\inf`) and can sample zero. +""", +) + +add_docstr_all( + "fill_", + r""" +fill_(value) -> Tensor + +Fills :attr:`self` tensor with the specified value. +""", +) + +add_docstr_all( + "floor", + r""" +floor() -> Tensor + +See :func:`torch.floor` +""", +) + +add_docstr_all( + "flip", + r""" +flip(dims) -> Tensor + +See :func:`torch.flip` +""", +) + +add_docstr_all( + "fliplr", + r""" +fliplr() -> Tensor + +See :func:`torch.fliplr` +""", +) + +add_docstr_all( + "flipud", + r""" +flipud() -> Tensor + +See :func:`torch.flipud` +""", +) + +add_docstr_all( + "roll", + r""" +roll(shifts, dims) -> Tensor + +See :func:`torch.roll` +""", +) + +add_docstr_all( + "floor_", + r""" +floor_() -> Tensor + +In-place version of :meth:`~Tensor.floor` +""", +) + +add_docstr_all( + "fmod", + r""" +fmod(divisor) -> Tensor + +See :func:`torch.fmod` +""", +) + +add_docstr_all( + "fmod_", + r""" +fmod_(divisor) -> Tensor + +In-place version of :meth:`~Tensor.fmod` +""", +) + +add_docstr_all( + "frac", + r""" +frac() -> Tensor + +See :func:`torch.frac` +""", +) + +add_docstr_all( + "frac_", + r""" +frac_() -> Tensor + +In-place version of :meth:`~Tensor.frac` +""", +) + +add_docstr_all( + "frexp", + r""" +frexp(input) -> (Tensor mantissa, Tensor exponent) + +See :func:`torch.frexp` +""", +) + +add_docstr_all( + "flatten", + r""" +flatten(start_dim=0, end_dim=-1) -> Tensor + +See :func:`torch.flatten` +""", +) + +add_docstr_all( + "gather", + r""" +gather(dim, index) -> Tensor + +See :func:`torch.gather` +""", +) + +add_docstr_all( + "gcd", + r""" +gcd(other) -> Tensor + +See :func:`torch.gcd` +""", +) + +add_docstr_all( + "gcd_", + r""" +gcd_(other) -> Tensor + +In-place version of :meth:`~Tensor.gcd` +""", +) + +add_docstr_all( + "ge", + r""" +ge(other) -> Tensor + +See :func:`torch.ge`. +""", +) + +add_docstr_all( + "ge_", + r""" +ge_(other) -> Tensor + +In-place version of :meth:`~Tensor.ge`. +""", +) + +add_docstr_all( + "greater_equal", + r""" +greater_equal(other) -> Tensor + +See :func:`torch.greater_equal`. +""", +) + +add_docstr_all( + "greater_equal_", + r""" +greater_equal_(other) -> Tensor + +In-place version of :meth:`~Tensor.greater_equal`. +""", +) + +add_docstr_all( + "geometric_", + r""" +geometric_(p, *, generator=None) -> Tensor + +Fills :attr:`self` tensor with elements drawn from the geometric distribution: + +.. math:: + + P(X=k) = (1 - p)^{k - 1} p, k = 1, 2, ... + +.. note:: + :func:`torch.Tensor.geometric_` `k`-th trial is the first success hence draws samples in :math:`\{1, 2, \ldots\}`, whereas + :func:`torch.distributions.geometric.Geometric` :math:`(k+1)`-th trial is the first success + hence draws samples in :math:`\{0, 1, \ldots\}`. +""", +) + +add_docstr_all( + "geqrf", + r""" +geqrf() -> (Tensor, Tensor) + +See :func:`torch.geqrf` +""", +) + +add_docstr_all( + "ger", + r""" +ger(vec2) -> Tensor + +See :func:`torch.ger` +""", +) + +add_docstr_all( + "inner", + r""" +inner(other) -> Tensor + +See :func:`torch.inner`. +""", +) + +add_docstr_all( + "outer", + r""" +outer(vec2) -> Tensor + +See :func:`torch.outer`. +""", +) + +add_docstr_all( + "hypot", + r""" +hypot(other) -> Tensor + +See :func:`torch.hypot` +""", +) + +add_docstr_all( + "hypot_", + r""" +hypot_(other) -> Tensor + +In-place version of :meth:`~Tensor.hypot` +""", +) + +add_docstr_all( + "i0", + r""" +i0() -> Tensor + +See :func:`torch.i0` +""", +) + +add_docstr_all( + "i0_", + r""" +i0_() -> Tensor + +In-place version of :meth:`~Tensor.i0` +""", +) + +add_docstr_all( + "igamma", + r""" +igamma(other) -> Tensor + +See :func:`torch.igamma` +""", +) + +add_docstr_all( + "igamma_", + r""" +igamma_(other) -> Tensor + +In-place version of :meth:`~Tensor.igamma` +""", +) + +add_docstr_all( + "igammac", + r""" +igammac(other) -> Tensor +See :func:`torch.igammac` +""", +) + +add_docstr_all( + "igammac_", + r""" +igammac_(other) -> Tensor +In-place version of :meth:`~Tensor.igammac` +""", +) + +add_docstr_all( + "indices", + r""" +indices() -> Tensor + +Return the indices tensor of a :ref:`sparse COO tensor `. + +.. warning:: + Throws an error if :attr:`self` is not a sparse COO tensor. + +See also :meth:`Tensor.values`. + +.. note:: + This method can only be called on a coalesced sparse tensor. See + :meth:`Tensor.coalesce` for details. +""", +) + +add_docstr_all( + "get_device", + r""" +get_device() -> Device ordinal (Integer) + +For CUDA tensors, this function returns the device ordinal of the GPU on which the tensor resides. +For CPU tensors, this function returns `-1`. + +Example:: + + >>> x = torch.randn(3, 4, 5, device='cuda:0') + >>> x.get_device() + 0 + >>> x.cpu().get_device() + -1 +""", +) + +add_docstr_all( + "values", + r""" +values() -> Tensor + +Return the values tensor of a :ref:`sparse COO tensor `. + +.. warning:: + Throws an error if :attr:`self` is not a sparse COO tensor. + +See also :meth:`Tensor.indices`. + +.. note:: + This method can only be called on a coalesced sparse tensor. See + :meth:`Tensor.coalesce` for details. +""", +) + +add_docstr_all( + "gt", + r""" +gt(other) -> Tensor + +See :func:`torch.gt`. +""", +) + +add_docstr_all( + "gt_", + r""" +gt_(other) -> Tensor + +In-place version of :meth:`~Tensor.gt`. +""", +) + +add_docstr_all( + "greater", + r""" +greater(other) -> Tensor + +See :func:`torch.greater`. +""", +) + +add_docstr_all( + "greater_", + r""" +greater_(other) -> Tensor + +In-place version of :meth:`~Tensor.greater`. +""", +) + +add_docstr_all( + "has_names", + r""" +Is ``True`` if any of this tensor's dimensions are named. Otherwise, is ``False``. +""", +) + +add_docstr_all( + "hardshrink", + r""" +hardshrink(lambd=0.5) -> Tensor + +See :func:`torch.nn.functional.hardshrink` +""", +) + +add_docstr_all( + "heaviside", + r""" +heaviside(values) -> Tensor + +See :func:`torch.heaviside` +""", +) + +add_docstr_all( + "heaviside_", + r""" +heaviside_(values) -> Tensor + +In-place version of :meth:`~Tensor.heaviside` +""", +) + +add_docstr_all( + "histc", + r""" +histc(bins=100, min=0, max=0) -> Tensor + +See :func:`torch.histc` +""", +) + +add_docstr_all( + "histogram", + r""" +histogram(input, bins, *, range=None, weight=None, density=False) -> (Tensor, Tensor) + +See :func:`torch.histogram` +""", +) + +add_docstr_all( + "index_add_", + r""" +index_add_(dim, index, source, *, alpha=1) -> Tensor + +Accumulate the elements of :attr:`alpha` times ``source`` into the :attr:`self` +tensor by adding to the indices in the order given in :attr:`index`. For example, +if ``dim == 0``, ``index[i] == j``, and ``alpha=-1``, then the ``i``\ th row of +``source`` is subtracted from the ``j``\ th row of :attr:`self`. + +The :attr:`dim`\ th dimension of ``source`` must have the same size as the +length of :attr:`index` (which must be a vector), and all other dimensions must +match :attr:`self`, or an error will be raised. + +For a 3-D tensor the output is given as:: + + self[index[i], :, :] += alpha * src[i, :, :] # if dim == 0 + self[:, index[i], :] += alpha * src[:, i, :] # if dim == 1 + self[:, :, index[i]] += alpha * src[:, :, i] # if dim == 2 + +Note: + {forward_reproducibility_note} + +Args: + dim (int): dimension along which to index + index (Tensor): indices of ``source`` to select from, + should have dtype either `torch.int64` or `torch.int32` + source (Tensor): the tensor containing values to add + +Keyword args: + alpha (Number): the scalar multiplier for ``source`` + +Example:: + + >>> x = torch.ones(5, 3) + >>> t = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=torch.float) + >>> index = torch.tensor([0, 4, 2]) + >>> x.index_add_(0, index, t) + tensor([[ 2., 3., 4.], + [ 1., 1., 1.], + [ 8., 9., 10.], + [ 1., 1., 1.], + [ 5., 6., 7.]]) + >>> x.index_add_(0, index, t, alpha=-1) + tensor([[ 1., 1., 1.], + [ 1., 1., 1.], + [ 1., 1., 1.], + [ 1., 1., 1.], + [ 1., 1., 1.]]) +""".format(**reproducibility_notes), +) + +add_docstr_all( + "index_copy_", + r""" +index_copy_(dim, index, tensor) -> Tensor + +Copies the elements of :attr:`tensor` into the :attr:`self` tensor by selecting +the indices in the order given in :attr:`index`. For example, if ``dim == 0`` +and ``index[i] == j``, then the ``i``\ th row of :attr:`tensor` is copied to the +``j``\ th row of :attr:`self`. + +The :attr:`dim`\ th dimension of :attr:`tensor` must have the same size as the +length of :attr:`index` (which must be a vector), and all other dimensions must +match :attr:`self`, or an error will be raised. + +.. note:: + If :attr:`index` contains duplicate entries, multiple elements from + :attr:`tensor` will be copied to the same index of :attr:`self`. The result + is nondeterministic since it depends on which copy occurs last. + +Args: + dim (int): dimension along which to index + index (LongTensor): indices of :attr:`tensor` to select from + tensor (Tensor): the tensor containing values to copy + +Example:: + + >>> x = torch.zeros(5, 3) + >>> t = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=torch.float) + >>> index = torch.tensor([0, 4, 2]) + >>> x.index_copy_(0, index, t) + tensor([[ 1., 2., 3.], + [ 0., 0., 0.], + [ 7., 8., 9.], + [ 0., 0., 0.], + [ 4., 5., 6.]]) +""", +) + +add_docstr_all( + "index_fill_", + r""" +index_fill_(dim, index, value) -> Tensor + +Fills the elements of the :attr:`self` tensor with value :attr:`value` by +selecting the indices in the order given in :attr:`index`. + +Args: + dim (int): dimension along which to index + index (LongTensor): indices of :attr:`self` tensor to fill in + value (float): the value to fill with + +Example:: + + >>> x = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=torch.float) + >>> index = torch.tensor([0, 2]) + >>> x.index_fill_(1, index, -1) + tensor([[-1., 2., -1.], + [-1., 5., -1.], + [-1., 8., -1.]]) +""", +) + +add_docstr_all( + "index_put_", + r""" +index_put_(indices, values, accumulate=False) -> Tensor + +Puts values from the tensor :attr:`values` into the tensor :attr:`self` using +the indices specified in :attr:`indices` (which is a tuple of Tensors). The +expression ``tensor.index_put_(indices, values)`` is equivalent to +``tensor[indices] = values``. Returns :attr:`self`. + +If :attr:`accumulate` is ``True``, the elements in :attr:`values` are added to +:attr:`self`. If accumulate is ``False``, the behavior is undefined if indices +contain duplicate elements. + +Args: + indices (tuple of LongTensor): tensors used to index into `self`. + values (Tensor): tensor of same dtype as `self`. + accumulate (bool): whether to accumulate into self +""", +) + +add_docstr_all( + "index_put", + r""" +index_put(indices, values, accumulate=False) -> Tensor + +Out-place version of :meth:`~Tensor.index_put_`. +""", +) + +add_docstr_all( + "index_reduce_", + r""" +index_reduce_(dim, index, source, reduce, *, include_self=True) -> Tensor + +Accumulate the elements of ``source`` into the :attr:`self` +tensor by accumulating to the indices in the order given in :attr:`index` +using the reduction given by the ``reduce`` argument. For example, if ``dim == 0``, +``index[i] == j``, ``reduce == prod`` and ``include_self == True`` then the ``i``\ th +row of ``source`` is multiplied by the ``j``\ th row of :attr:`self`. If +:obj:`include_self="True"`, the values in the :attr:`self` tensor are included +in the reduction, otherwise, rows in the :attr:`self` tensor that are accumulated +to are treated as if they were filled with the reduction identities. + +The :attr:`dim`\ th dimension of ``source`` must have the same size as the +length of :attr:`index` (which must be a vector), and all other dimensions must +match :attr:`self`, or an error will be raised. + +For a 3-D tensor with :obj:`reduce="prod"` and :obj:`include_self=True` the +output is given as:: + + self[index[i], :, :] *= src[i, :, :] # if dim == 0 + self[:, index[i], :] *= src[:, i, :] # if dim == 1 + self[:, :, index[i]] *= src[:, :, i] # if dim == 2 + +Note: + {forward_reproducibility_note} + +.. note:: + + This function only supports floating point tensors. + +.. warning:: + + This function is in beta and may change in the near future. + +Args: + dim (int): dimension along which to index + index (Tensor): indices of ``source`` to select from, + should have dtype either `torch.int64` or `torch.int32` + source (FloatTensor): the tensor containing values to accumulate + reduce (str): the reduction operation to apply + (:obj:`"prod"`, :obj:`"mean"`, :obj:`"amax"`, :obj:`"amin"`) + +Keyword args: + include_self (bool): whether the elements from the ``self`` tensor are + included in the reduction + +Example:: + + >>> x = torch.empty(5, 3).fill_(2) + >>> t = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]], dtype=torch.float) + >>> index = torch.tensor([0, 4, 2, 0]) + >>> x.index_reduce_(0, index, t, 'prod') + tensor([[20., 44., 72.], + [ 2., 2., 2.], + [14., 16., 18.], + [ 2., 2., 2.], + [ 8., 10., 12.]]) + >>> x = torch.empty(5, 3).fill_(2) + >>> x.index_reduce_(0, index, t, 'prod', include_self=False) + tensor([[10., 22., 36.], + [ 2., 2., 2.], + [ 7., 8., 9.], + [ 2., 2., 2.], + [ 4., 5., 6.]]) +""".format(**reproducibility_notes), +) + +add_docstr_all( + "index_select", + r""" +index_select(dim, index) -> Tensor + +See :func:`torch.index_select` +""", +) + +add_docstr_all( + "sparse_mask", + r""" +sparse_mask(mask) -> Tensor + +Returns a new :ref:`sparse tensor ` with values from a +strided tensor :attr:`self` filtered by the indices of the sparse +tensor :attr:`mask`. The values of :attr:`mask` sparse tensor are +ignored. :attr:`self` and :attr:`mask` tensors must have the same +shape. + +.. note:: + + The returned sparse tensor might contain duplicate values if :attr:`mask` + is not coalesced. It is therefore advisable to pass ``mask.coalesce()`` + if such behavior is not desired. + +.. note:: + + The returned sparse tensor has the same indices as the sparse tensor + :attr:`mask`, even when the corresponding values in :attr:`self` are + zeros. + +Args: + mask (Tensor): a sparse tensor whose indices are used as a filter + +Example:: + + >>> nse = 5 + >>> dims = (5, 5, 2, 2) + >>> I = torch.cat([torch.randint(0, dims[0], size=(nse,)), + ... torch.randint(0, dims[1], size=(nse,))], 0).reshape(2, nse) + >>> V = torch.randn(nse, dims[2], dims[3]) + >>> S = torch.sparse_coo_tensor(I, V, dims).coalesce() + >>> D = torch.randn(dims) + >>> D.sparse_mask(S) + tensor(indices=tensor([[0, 0, 0, 2], + [0, 1, 4, 3]]), + values=tensor([[[ 1.6550, 0.2397], + [-0.1611, -0.0779]], + + [[ 0.2326, -1.0558], + [ 1.4711, 1.9678]], + + [[-0.5138, -0.0411], + [ 1.9417, 0.5158]], + + [[ 0.0793, 0.0036], + [-0.2569, -0.1055]]]), + size=(5, 5, 2, 2), nnz=4, layout=torch.sparse_coo) +""", +) + +add_docstr_all( + "inverse", + r""" +inverse() -> Tensor + +See :func:`torch.inverse` +""", +) + +add_docstr_all( + "isnan", + r""" +isnan() -> Tensor + +See :func:`torch.isnan` +""", +) + +add_docstr_all( + "isinf", + r""" +isinf() -> Tensor + +See :func:`torch.isinf` +""", +) + +add_docstr_all( + "isposinf", + r""" +isposinf() -> Tensor + +See :func:`torch.isposinf` +""", +) + +add_docstr_all( + "isneginf", + r""" +isneginf() -> Tensor + +See :func:`torch.isneginf` +""", +) + +add_docstr_all( + "isfinite", + r""" +isfinite() -> Tensor + +See :func:`torch.isfinite` +""", +) + +add_docstr_all( + "isclose", + r""" +isclose(other, rtol=1e-05, atol=1e-08, equal_nan=False) -> Tensor + +See :func:`torch.isclose` +""", +) + +add_docstr_all( + "isreal", + r""" +isreal() -> Tensor + +See :func:`torch.isreal` +""", +) + +add_docstr_all( + "is_coalesced", + r""" +is_coalesced() -> bool + +Returns ``True`` if :attr:`self` is a :ref:`sparse COO tensor +` that is coalesced, ``False`` otherwise. + +.. warning:: + Throws an error if :attr:`self` is not a sparse COO tensor. + +See :meth:`coalesce` and :ref:`uncoalesced tensors `. +""", +) + +add_docstr_all( + "is_contiguous", + r""" +is_contiguous(memory_format=torch.contiguous_format) -> bool + +Returns True if :attr:`self` tensor is contiguous in memory in the order specified +by memory format. + +Args: + memory_format (:class:`torch.memory_format`, optional): Specifies memory allocation + order. Default: ``torch.contiguous_format``. +""", +) + +add_docstr_all( + "is_pinned", + r""" +Returns true if this tensor resides in pinned memory. +By default, the device pinned memory on will be the current :ref:`accelerator`. +""", +) + +add_docstr_all( + "is_floating_point", + r""" +is_floating_point() -> bool + +Returns True if the data type of :attr:`self` is a floating point data type. +""", +) + +add_docstr_all( + "is_complex", + r""" +is_complex() -> bool + +Returns True if the data type of :attr:`self` is a complex data type. +""", +) + +add_docstr_all( + "is_inference", + r""" +is_inference() -> bool + +See :func:`torch.is_inference` +""", +) + +add_docstr_all( + "is_conj", + r""" +is_conj() -> bool + +Returns True if the conjugate bit of :attr:`self` is set to true. +""", +) + +add_docstr_all( + "is_neg", + r""" +is_neg() -> bool + +Returns True if the negative bit of :attr:`self` is set to true. +""", +) + +add_docstr_all( + "is_signed", + r""" +is_signed() -> bool + +Returns True if the data type of :attr:`self` is a signed data type. +""", +) + +add_docstr_all( + "is_set_to", + r""" +is_set_to(tensor) -> bool + +Returns True if both tensors are pointing to the exact same memory (same +storage, offset, size and stride). +""", +) + +add_docstr_all( + "item", + r""" +item() -> number + +Returns the value of this tensor as a standard Python number. This only works +for tensors with one element. For other cases, see :meth:`~Tensor.tolist`. + +This operation is not differentiable. + +Example:: + + >>> x = torch.tensor([1.0]) + >>> x.item() + 1.0 + +""", +) + +add_docstr_all( + "kron", + r""" +kron(other) -> Tensor + +See :func:`torch.kron` +""", +) + +add_docstr_all( + "kthvalue", + r""" +kthvalue(k, dim=None, keepdim=False) -> (Tensor, LongTensor) + +See :func:`torch.kthvalue` +""", +) + +add_docstr_all( + "ldexp", + r""" +ldexp(other) -> Tensor + +See :func:`torch.ldexp` +""", +) + +add_docstr_all( + "ldexp_", + r""" +ldexp_(other) -> Tensor + +In-place version of :meth:`~Tensor.ldexp` +""", +) + +add_docstr_all( + "lcm", + r""" +lcm(other) -> Tensor + +See :func:`torch.lcm` +""", +) + +add_docstr_all( + "lcm_", + r""" +lcm_(other) -> Tensor + +In-place version of :meth:`~Tensor.lcm` +""", +) + +add_docstr_all( + "le", + r""" +le(other) -> Tensor + +See :func:`torch.le`. +""", +) + +add_docstr_all( + "le_", + r""" +le_(other) -> Tensor + +In-place version of :meth:`~Tensor.le`. +""", +) + +add_docstr_all( + "less_equal", + r""" +less_equal(other) -> Tensor + +See :func:`torch.less_equal`. +""", +) + +add_docstr_all( + "less_equal_", + r""" +less_equal_(other) -> Tensor + +In-place version of :meth:`~Tensor.less_equal`. +""", +) + +add_docstr_all( + "lerp", + r""" +lerp(end, weight) -> Tensor + +See :func:`torch.lerp` +""", +) + +add_docstr_all( + "lerp_", + r""" +lerp_(end, weight) -> Tensor + +In-place version of :meth:`~Tensor.lerp` +""", +) + +add_docstr_all( + "lgamma", + r""" +lgamma() -> Tensor + +See :func:`torch.lgamma` +""", +) + +add_docstr_all( + "lgamma_", + r""" +lgamma_() -> Tensor + +In-place version of :meth:`~Tensor.lgamma` +""", +) + +add_docstr_all( + "log", + r""" +log() -> Tensor + +See :func:`torch.log` +""", +) + +add_docstr_all( + "log_", + r""" +log_() -> Tensor + +In-place version of :meth:`~Tensor.log` +""", +) + +add_docstr_all( + "log10", + r""" +log10() -> Tensor + +See :func:`torch.log10` +""", +) + +add_docstr_all( + "log10_", + r""" +log10_() -> Tensor + +In-place version of :meth:`~Tensor.log10` +""", +) + +add_docstr_all( + "log1p", + r""" +log1p() -> Tensor + +See :func:`torch.log1p` +""", +) + +add_docstr_all( + "log1p_", + r""" +log1p_() -> Tensor + +In-place version of :meth:`~Tensor.log1p` +""", +) + +add_docstr_all( + "log2", + r""" +log2() -> Tensor + +See :func:`torch.log2` +""", +) + +add_docstr_all( + "log2_", + r""" +log2_() -> Tensor + +In-place version of :meth:`~Tensor.log2` +""", +) + +add_docstr_all( + "logaddexp", + r""" +logaddexp(other) -> Tensor + +See :func:`torch.logaddexp` +""", +) + +add_docstr_all( + "logaddexp2", + r""" +logaddexp2(other) -> Tensor + +See :func:`torch.logaddexp2` +""", +) + +add_docstr_all( + "log_normal_", + r""" +log_normal_(mean=1, std=2, *, generator=None) + +Fills :attr:`self` tensor with numbers samples from the log-normal distribution +parameterized by the given mean :math:`\mu` and standard deviation +:math:`\sigma`. Note that :attr:`mean` and :attr:`std` are the mean and +standard deviation of the underlying normal distribution, and not of the +returned distribution: + +.. math:: + + f(x) = \dfrac{1}{x \sigma \sqrt{2\pi}}\ e^{-\frac{(\ln x - \mu)^2}{2\sigma^2}} +""", +) + +add_docstr_all( + "logsumexp", + r""" +logsumexp(dim, keepdim=False) -> Tensor + +See :func:`torch.logsumexp` +""", +) + +add_docstr_all( + "lt", + r""" +lt(other) -> Tensor + +See :func:`torch.lt`. +""", +) + +add_docstr_all( + "lt_", + r""" +lt_(other) -> Tensor + +In-place version of :meth:`~Tensor.lt`. +""", +) + +add_docstr_all( + "less", + r""" +lt(other) -> Tensor + +See :func:`torch.less`. +""", +) + +add_docstr_all( + "less_", + r""" +less_(other) -> Tensor + +In-place version of :meth:`~Tensor.less`. +""", +) + +add_docstr_all( + "lu_solve", + r""" +lu_solve(LU_data, LU_pivots) -> Tensor + +See :func:`torch.lu_solve` +""", +) + +add_docstr_all( + "map_", + r""" +map_(tensor, callable) + +Applies :attr:`callable` for each element in :attr:`self` tensor and the given +:attr:`tensor` and stores the results in :attr:`self` tensor. :attr:`self` tensor and +the given :attr:`tensor` must be :ref:`broadcastable `. + +The :attr:`callable` should have the signature:: + + def callable(a, b) -> number +""", +) + +add_docstr_all( + "masked_scatter_", + r""" +masked_scatter_(mask, source) + +Copies elements from :attr:`source` into :attr:`self` tensor at positions where +the :attr:`mask` is True. Elements from :attr:`source` are copied into :attr:`self` +starting at position 0 of :attr:`source` and continuing in order one-by-one for each +occurrence of :attr:`mask` being True. +The shape of :attr:`mask` must be :ref:`broadcastable ` +with the shape of the underlying tensor. The :attr:`source` should have at least +as many elements as the number of ones in :attr:`mask`. + +Args: + mask (BoolTensor): the boolean mask + source (Tensor): the tensor to copy from + +.. note:: + + The :attr:`mask` operates on the :attr:`self` tensor, not on the given + :attr:`source` tensor. + +Example: + + >>> self = torch.tensor([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]) + >>> mask = torch.tensor( + ... [[0, 0, 0, 1, 1], [1, 1, 0, 1, 1]], + ... dtype=torch.bool, + ... ) + >>> source = torch.tensor([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]) + >>> self.masked_scatter_(mask, source) + tensor([[0, 0, 0, 0, 1], + [2, 3, 0, 4, 5]]) + +""", +) + +add_docstr_all( + "masked_fill_", + r""" +masked_fill_(mask, value) + +Fills elements of :attr:`self` tensor with :attr:`value` where :attr:`mask` is +True. The shape of :attr:`mask` must be +:ref:`broadcastable ` with the shape of the underlying +tensor. + +Args: + mask (BoolTensor): the boolean mask + value (float): the value to fill in with +""", +) + +add_docstr_all( + "masked_select", + r""" +masked_select(mask) -> Tensor + +See :func:`torch.masked_select` +""", +) + +add_docstr_all( + "matrix_power", + r""" +matrix_power(n) -> Tensor + +.. note:: :meth:`~Tensor.matrix_power` is deprecated, use :func:`torch.linalg.matrix_power` instead. + +Alias for :func:`torch.linalg.matrix_power` +""", +) + +add_docstr_all( + "matrix_exp", + r""" +matrix_exp() -> Tensor + +See :func:`torch.matrix_exp` +""", +) + +add_docstr_all( + "max", + r""" +max(dim=None, keepdim=False) -> Tensor or (Tensor, Tensor) + +See :func:`torch.max` +""", +) + +add_docstr_all( + "amax", + r""" +amax(dim=None, keepdim=False) -> Tensor + +See :func:`torch.amax` +""", +) + +add_docstr_all( + "maximum", + r""" +maximum(other) -> Tensor + +See :func:`torch.maximum` +""", +) + +add_docstr_all( + "fmax", + r""" +fmax(other) -> Tensor + +See :func:`torch.fmax` +""", +) + +add_docstr_all( + "argmax", + r""" +argmax(dim=None, keepdim=False) -> LongTensor + +See :func:`torch.argmax` +""", +) + +add_docstr_all( + "argwhere", + r""" +argwhere() -> Tensor + +See :func:`torch.argwhere` +""", +) + +add_docstr_all( + "mean", + r""" +mean(dim=None, keepdim=False, *, dtype=None) -> Tensor + +See :func:`torch.mean` +""", +) + +add_docstr_all( + "nanmean", + r""" +nanmean(dim=None, keepdim=False, *, dtype=None) -> Tensor + +See :func:`torch.nanmean` +""", +) + +add_docstr_all( + "median", + r""" +median(dim=None, keepdim=False) -> (Tensor, LongTensor) + +See :func:`torch.median` +""", +) + +add_docstr_all( + "nanmedian", + r""" +nanmedian(dim=None, keepdim=False) -> (Tensor, LongTensor) + +See :func:`torch.nanmedian` +""", +) + +add_docstr_all( + "min", + r""" +min(dim=None, keepdim=False) -> Tensor or (Tensor, Tensor) + +See :func:`torch.min` +""", +) + +add_docstr_all( + "amin", + r""" +amin(dim=None, keepdim=False) -> Tensor + +See :func:`torch.amin` +""", +) + +add_docstr_all( + "minimum", + r""" +minimum(other) -> Tensor + +See :func:`torch.minimum` +""", +) + +add_docstr_all( + "aminmax", + r""" +aminmax(*, dim=None, keepdim=False) -> (Tensor min, Tensor max) + +See :func:`torch.aminmax` +""", +) + +add_docstr_all( + "fmin", + r""" +fmin(other) -> Tensor + +See :func:`torch.fmin` +""", +) + +add_docstr_all( + "argmin", + r""" +argmin(dim=None, keepdim=False) -> LongTensor + +See :func:`torch.argmin` +""", +) + +add_docstr_all( + "mm", + r""" +mm(mat2) -> Tensor + +See :func:`torch.mm` +""", +) + +add_docstr_all( + "mode", + r""" +mode(dim=None, keepdim=False) -> (Tensor, LongTensor) + +See :func:`torch.mode` +""", +) + +add_docstr_all( + "movedim", + r""" +movedim(source, destination) -> Tensor + +See :func:`torch.movedim` +""", +) + +add_docstr_all( + "moveaxis", + r""" +moveaxis(source, destination) -> Tensor + +See :func:`torch.moveaxis` +""", +) + +add_docstr_all( + "mul", + r""" +mul(value) -> Tensor + +See :func:`torch.mul`. +""", +) + +add_docstr_all( + "mul_", + r""" +mul_(value) -> Tensor + +In-place version of :meth:`~Tensor.mul`. +""", +) + +add_docstr_all( + "multiply", + r""" +multiply(value) -> Tensor + +See :func:`torch.multiply`. +""", +) + +add_docstr_all( + "multiply_", + r""" +multiply_(value) -> Tensor + +In-place version of :meth:`~Tensor.multiply`. +""", +) + +add_docstr_all( + "multinomial", + r""" +multinomial(num_samples, replacement=False, *, generator=None) -> Tensor + +See :func:`torch.multinomial` +""", +) + +add_docstr_all( + "mv", + r""" +mv(vec) -> Tensor + +See :func:`torch.mv` +""", +) + +add_docstr_all( + "mvlgamma", + r""" +mvlgamma(p) -> Tensor + +See :func:`torch.mvlgamma` +""", +) + +add_docstr_all( + "mvlgamma_", + r""" +mvlgamma_(p) -> Tensor + +In-place version of :meth:`~Tensor.mvlgamma` +""", +) + +add_docstr_all( + "narrow", + r""" +narrow(dimension, start, length) -> Tensor + +See :func:`torch.narrow`. +""", +) + +add_docstr_all( + "narrow_copy", + r""" +narrow_copy(dimension, start, length) -> Tensor + +See :func:`torch.narrow_copy`. +""", +) + +add_docstr_all( + "ndimension", + r""" +ndimension() -> int + +Alias for :meth:`~Tensor.dim()` +""", +) + +add_docstr_all( + "nan_to_num", + r""" +nan_to_num(nan=0.0, posinf=None, neginf=None) -> Tensor + +See :func:`torch.nan_to_num`. +""", +) + +add_docstr_all( + "nan_to_num_", + r""" +nan_to_num_(nan=0.0, posinf=None, neginf=None) -> Tensor + +In-place version of :meth:`~Tensor.nan_to_num`. +""", +) + +add_docstr_all( + "ne", + r""" +ne(other) -> Tensor + +See :func:`torch.ne`. +""", +) + +add_docstr_all( + "ne_", + r""" +ne_(other) -> Tensor + +In-place version of :meth:`~Tensor.ne`. +""", +) + +add_docstr_all( + "not_equal", + r""" +not_equal(other) -> Tensor + +See :func:`torch.not_equal`. +""", +) + +add_docstr_all( + "not_equal_", + r""" +not_equal_(other) -> Tensor + +In-place version of :meth:`~Tensor.not_equal`. +""", +) + +add_docstr_all( + "neg", + r""" +neg() -> Tensor + +See :func:`torch.neg` +""", +) + +add_docstr_all( + "negative", + r""" +negative() -> Tensor + +See :func:`torch.negative` +""", +) + +add_docstr_all( + "neg_", + r""" +neg_() -> Tensor + +In-place version of :meth:`~Tensor.neg` +""", +) + +add_docstr_all( + "negative_", + r""" +negative_() -> Tensor + +In-place version of :meth:`~Tensor.negative` +""", +) + +add_docstr_all( + "nelement", + r""" +nelement() -> int + +Alias for :meth:`~Tensor.numel` +""", +) + +add_docstr_all( + "nextafter", + r""" +nextafter(other) -> Tensor +See :func:`torch.nextafter` +""", +) + +add_docstr_all( + "nextafter_", + r""" +nextafter_(other) -> Tensor +In-place version of :meth:`~Tensor.nextafter` +""", +) + +add_docstr_all( + "nonzero", + r""" +nonzero() -> LongTensor + +See :func:`torch.nonzero` +""", +) + +add_docstr_all( + "nonzero_static", + r""" +nonzero_static(input, *, size, fill_value=-1) -> Tensor + +Returns a 2-D tensor where each row is the index for a non-zero value. +The returned Tensor has the same `torch.dtype` as `torch.nonzero()`. + +Args: + input (Tensor): the input tensor to count non-zero elements. + +Keyword args: + size (int): the size of non-zero elements expected to be included in the out + tensor. Pad the out tensor with `fill_value` if the `size` is larger + than total number of non-zero elements, truncate out tensor if `size` + is smaller. The size must be a non-negative integer. + fill_value (int, optional): the value to fill the output tensor with when `size` is larger + than the total number of non-zero elements. Default is `-1` to represent + invalid index. + +Example: + + # Example 1: Padding + >>> input_tensor = torch.tensor([[1, 0], [3, 2]]) + >>> static_size = 4 + >>> t = torch.nonzero_static(input_tensor, size=static_size) + tensor([[ 0, 0], + [ 1, 0], + [ 1, 1], + [ -1, -1]], dtype=torch.int64) + + # Example 2: Truncating + >>> input_tensor = torch.tensor([[1, 0], [3, 2]]) + >>> static_size = 2 + >>> t = torch.nonzero_static(input_tensor, size=static_size) + tensor([[ 0, 0], + [ 1, 0]], dtype=torch.int64) + + # Example 3: 0 size + >>> input_tensor = torch.tensor([10]) + >>> static_size = 0 + >>> t = torch.nonzero_static(input_tensor, size=static_size) + tensor([], size=(0, 1), dtype=torch.int64) + + # Example 4: 0 rank input + >>> input_tensor = torch.tensor(10) + >>> static_size = 2 + >>> t = torch.nonzero_static(input_tensor, size=static_size) + tensor([], size=(2, 0), dtype=torch.int64) +""", +) + +add_docstr_all( + "norm", + r""" +norm(p=2, dim=None, keepdim=False) -> Tensor + +See :func:`torch.norm` +""", +) + +add_docstr_all( + "normal_", + r""" +normal_(mean=0, std=1, *, generator=None) -> Tensor + +Fills :attr:`self` tensor with elements samples from the normal distribution +parameterized by :attr:`mean` and :attr:`std`. +""", +) + +add_docstr_all( + "numel", + r""" +numel() -> int + +See :func:`torch.numel` +""", +) + +add_docstr_all( + "numpy", + r""" +numpy(*, force=False) -> numpy.ndarray + +Returns the tensor as a NumPy :class:`ndarray`. + +If :attr:`force` is ``False`` (the default), the conversion +is performed only if the tensor is on the CPU, does not require grad, +does not have its conjugate bit set, and is a dtype and layout that +NumPy supports. The returned ndarray and the tensor will share their +storage, so changes to the tensor will be reflected in the ndarray +and vice versa. + +If :attr:`force` is ``True`` this is equivalent to +calling ``t.detach().cpu().resolve_conj().resolve_neg().numpy()``. +If the tensor isn't on the CPU or the conjugate or negative bit is set, +the tensor won't share its storage with the returned ndarray. +Setting :attr:`force` to ``True`` can be a useful shorthand. + +Args: + force (bool): if ``True``, the ndarray may be a copy of the tensor + instead of always sharing memory, defaults to ``False``. +""", +) + +add_docstr_all( + "orgqr", + r""" +orgqr(input2) -> Tensor + +See :func:`torch.orgqr` +""", +) + +add_docstr_all( + "ormqr", + r""" +ormqr(input2, input3, left=True, transpose=False) -> Tensor + +See :func:`torch.ormqr` +""", +) + +add_docstr_all( + "permute", + r""" +permute(*dims) -> Tensor + +See :func:`torch.permute` +""", +) + +add_docstr_all( + "polygamma", + r""" +polygamma(n) -> Tensor + +See :func:`torch.polygamma` +""", +) + +add_docstr_all( + "polygamma_", + r""" +polygamma_(n) -> Tensor + +In-place version of :meth:`~Tensor.polygamma` +""", +) + +add_docstr_all( + "positive", + r""" +positive() -> Tensor + +See :func:`torch.positive` +""", +) + +add_docstr_all( + "pow", + r""" +pow(exponent) -> Tensor + +See :func:`torch.pow` +""", +) + +add_docstr_all( + "pow_", + r""" +pow_(exponent) -> Tensor + +In-place version of :meth:`~Tensor.pow` +""", +) + +add_docstr_all( + "float_power", + r""" +float_power(exponent) -> Tensor + +See :func:`torch.float_power` +""", +) + +add_docstr_all( + "float_power_", + r""" +float_power_(exponent) -> Tensor + +In-place version of :meth:`~Tensor.float_power` +""", +) + +add_docstr_all( + "prod", + r""" +prod(dim=None, keepdim=False, dtype=None) -> Tensor + +See :func:`torch.prod` +""", +) + +add_docstr_all( + "put_", + r""" +put_(index, source, accumulate=False) -> Tensor + +Copies the elements from :attr:`source` into the positions specified by +:attr:`index`. For the purpose of indexing, the :attr:`self` tensor is treated as if +it were a 1-D tensor. + +:attr:`index` and :attr:`source` need to have the same number of elements, but not necessarily +the same shape. + +If :attr:`accumulate` is ``True``, the elements in :attr:`source` are added to +:attr:`self`. If accumulate is ``False``, the behavior is undefined if :attr:`index` +contain duplicate elements. + +Args: + index (LongTensor): the indices into self + source (Tensor): the tensor containing values to copy from + accumulate (bool, optional): whether to accumulate into self. Default: ``False`` + +Example:: + + >>> src = torch.tensor([[4, 3, 5], + ... [6, 7, 8]]) + >>> src.put_(torch.tensor([1, 3]), torch.tensor([9, 10])) + tensor([[ 4, 9, 5], + [ 10, 7, 8]]) +""", +) + +add_docstr_all( + "put", + r""" +put(input, index, source, accumulate=False) -> Tensor + +Out-of-place version of :meth:`torch.Tensor.put_`. +`input` corresponds to `self` in :meth:`torch.Tensor.put_`. +""", +) + +add_docstr_all( + "qr", + r""" +qr(some=True) -> (Tensor, Tensor) + +See :func:`torch.qr` +""", +) + +add_docstr_all( + "qscheme", + r""" +qscheme() -> torch.qscheme + +Returns the quantization scheme of a given QTensor. +""", +) + +add_docstr_all( + "quantile", + r""" +quantile(q, dim=None, keepdim=False, *, interpolation='linear') -> Tensor + +See :func:`torch.quantile` +""", +) + +add_docstr_all( + "nanquantile", + r""" +nanquantile(q, dim=None, keepdim=False, *, interpolation='linear') -> Tensor + +See :func:`torch.nanquantile` +""", +) + +add_docstr_all( + "q_scale", + r""" +q_scale() -> float + +Given a Tensor quantized by linear(affine) quantization, +returns the scale of the underlying quantizer(). +""", +) + +add_docstr_all( + "q_zero_point", + r""" +q_zero_point() -> int + +Given a Tensor quantized by linear(affine) quantization, +returns the zero_point of the underlying quantizer(). +""", +) + +add_docstr_all( + "q_per_channel_scales", + r""" +q_per_channel_scales() -> Tensor + +Given a Tensor quantized by linear (affine) per-channel quantization, +returns a Tensor of scales of the underlying quantizer. It has the number of +elements that matches the corresponding dimensions (from q_per_channel_axis) of +the tensor. +""", +) + +add_docstr_all( + "q_per_channel_zero_points", + r""" +q_per_channel_zero_points() -> Tensor + +Given a Tensor quantized by linear (affine) per-channel quantization, +returns a tensor of zero_points of the underlying quantizer. It has the number of +elements that matches the corresponding dimensions (from q_per_channel_axis) of +the tensor. +""", +) + +add_docstr_all( + "q_per_channel_axis", + r""" +q_per_channel_axis() -> int + +Given a Tensor quantized by linear (affine) per-channel quantization, +returns the index of dimension on which per-channel quantization is applied. +""", +) + +add_docstr_all( + "random_", + r""" +random_(from=0, to=None, *, generator=None) -> Tensor + +Fills :attr:`self` tensor with numbers sampled from the discrete uniform +distribution over ``[from, to - 1]``. If not specified, the values are usually +only bounded by :attr:`self` tensor's data type. However, for floating point +types, if unspecified, range will be ``[0, 2^mantissa]`` to ensure that every +value is representable. For example, `torch.tensor(1, dtype=torch.double).random_()` +will be uniform in ``[0, 2^53]``. +""", +) + +add_docstr_all( + "rad2deg", + r""" +rad2deg() -> Tensor + +See :func:`torch.rad2deg` +""", +) + +add_docstr_all( + "rad2deg_", + r""" +rad2deg_() -> Tensor + +In-place version of :meth:`~Tensor.rad2deg` +""", +) + +add_docstr_all( + "deg2rad", + r""" +deg2rad() -> Tensor + +See :func:`torch.deg2rad` +""", +) + +add_docstr_all( + "deg2rad_", + r""" +deg2rad_() -> Tensor + +In-place version of :meth:`~Tensor.deg2rad` +""", +) + +add_docstr_all( + "ravel", + r""" +ravel() -> Tensor + +see :func:`torch.ravel` +""", +) + +add_docstr_all( + "reciprocal", + r""" +reciprocal() -> Tensor + +See :func:`torch.reciprocal` +""", +) + +add_docstr_all( + "reciprocal_", + r""" +reciprocal_() -> Tensor + +In-place version of :meth:`~Tensor.reciprocal` +""", +) + +add_docstr_all( + "record_stream", + r""" +record_stream(stream) + +Marks the tensor as having been used by this stream. When the tensor +is deallocated, ensure the tensor memory is not reused for another tensor +until all work queued on :attr:`stream` at the time of deallocation is +complete. + +.. note:: + + The caching allocator is aware of only the stream where a tensor was + allocated. Due to the awareness, it already correctly manages the life + cycle of tensors on only one stream. But if a tensor is used on a stream + different from the stream of origin, the allocator might reuse the memory + unexpectedly. Calling this method lets the allocator know which streams + have used the tensor. + +.. warning:: + + This method is most suitable for use cases where you are providing a + function that created a tensor on a side stream, and want users to be able + to make use of the tensor without having to think carefully about stream + safety when making use of them. These safety guarantees come at some + performance and predictability cost (analogous to the tradeoff between GC + and manual memory management), so if you are in a situation where + you manage the full lifetime of your tensors, you may consider instead + manually managing CUDA events so that calling this method is not necessary. + In particular, when you call this method, on later allocations the + allocator will poll the recorded stream to see if all operations have + completed yet; you can potentially race with side stream computation and + non-deterministically reuse or fail to reuse memory for an allocation. + + You can safely use tensors allocated on side streams without + :meth:`~Tensor.record_stream`; you must manually ensure that + any non-creation stream uses of a tensor are synced back to the creation + stream before you deallocate the tensor. As the CUDA caching allocator + guarantees that the memory will only be reused with the same creation stream, + this is sufficient to ensure that writes to future reallocations of the + memory will be delayed until non-creation stream uses are done. + (Counterintuitively, you may observe that on the CPU side we have already + reallocated the tensor, even though CUDA kernels on the old tensor are + still in progress. This is fine, because CUDA operations on the new + tensor will appropriately wait for the old operations to complete, as they + are all on the same stream.) + + Concretely, this looks like this:: + + with torch.cuda.stream(s0): + x = torch.zeros(N) + + s1.wait_stream(s0) + with torch.cuda.stream(s1): + y = some_comm_op(x) + + ... some compute on s0 ... + + # synchronize creation stream s0 to side stream s1 + # before deallocating x + s0.wait_stream(s1) + del x + + Note that some discretion is required when deciding when to perform + ``s0.wait_stream(s1)``. In particular, if we were to wait immediately + after ``some_comm_op``, there wouldn't be any point in having the side + stream; it would be equivalent to have run ``some_comm_op`` on ``s0``. + Instead, the synchronization must be placed at some appropriate, later + point in time where you expect the side stream ``s1`` to have finished + work. This location is typically identified via profiling, e.g., using + Chrome traces produced + :meth:`torch.autograd.profiler.profile.export_chrome_trace`. If you + place the wait too early, work on s0 will block until ``s1`` has finished, + preventing further overlapping of communication and computation. If you + place the wait too late, you will use more memory than is strictly + necessary (as you are keeping ``x`` live for longer.) For a concrete + example of how this guidance can be applied in practice, see this post: + `FSDP and CUDACachingAllocator + `_. +""", +) + +add_docstr_all( + "remainder", + r""" +remainder(divisor) -> Tensor + +See :func:`torch.remainder` +""", +) + +add_docstr_all( + "remainder_", + r""" +remainder_(divisor) -> Tensor + +In-place version of :meth:`~Tensor.remainder` +""", +) + +add_docstr_all( + "renorm", + r""" +renorm(p, dim, maxnorm) -> Tensor + +See :func:`torch.renorm` +""", +) + +add_docstr_all( + "renorm_", + r""" +renorm_(p, dim, maxnorm) -> Tensor + +In-place version of :meth:`~Tensor.renorm` +""", +) + +add_docstr_all( + "repeat", + r""" +repeat(*repeats) -> Tensor + +Repeats this tensor along the specified dimensions. + +Unlike :meth:`~Tensor.expand`, this function copies the tensor's data. + +.. warning:: + + :meth:`~Tensor.repeat` behaves differently from + `numpy.repeat `_, + but is more similar to + `numpy.tile `_. + For the operator similar to `numpy.repeat`, see :func:`torch.repeat_interleave`. + +Args: + repeat (torch.Size, int..., tuple of int or list of int): The number of times to repeat this tensor along each dimension + +Example:: + + >>> x = torch.tensor([1, 2, 3]) + >>> x.repeat(4, 2) + tensor([[ 1, 2, 3, 1, 2, 3], + [ 1, 2, 3, 1, 2, 3], + [ 1, 2, 3, 1, 2, 3], + [ 1, 2, 3, 1, 2, 3]]) + >>> x.repeat(4, 2, 1).size() + torch.Size([4, 2, 3]) +""", +) + +add_docstr_all( + "repeat_interleave", + r""" +repeat_interleave(repeats, dim=None, *, output_size=None) -> Tensor + +See :func:`torch.repeat_interleave`. +""", +) + +add_docstr_all( + "requires_grad_", + r""" +requires_grad_(requires_grad=True) -> Tensor + +Change if autograd should record operations on this tensor: sets this tensor's +:attr:`requires_grad` attribute in-place. Returns this tensor. + +:func:`requires_grad_`'s main use case is to tell autograd to begin recording +operations on a Tensor ``tensor``. If ``tensor`` has ``requires_grad=False`` +(because it was obtained through a DataLoader, or required preprocessing or +initialization), ``tensor.requires_grad_()`` makes it so that autograd will +begin to record operations on ``tensor``. + +Args: + requires_grad (bool): If autograd should record operations on this tensor. + Default: ``True``. + +Example:: + + >>> # Let's say we want to preprocess some saved weights and use + >>> # the result as new weights. + >>> saved_weights = [0.1, 0.2, 0.3, 0.25] + >>> loaded_weights = torch.tensor(saved_weights) + >>> weights = preprocess(loaded_weights) # some function + >>> weights + tensor([-0.5503, 0.4926, -2.1158, -0.8303]) + + >>> # Now, start to record operations done to weights + >>> weights.requires_grad_() + >>> out = weights.pow(2).sum() + >>> out.backward() + >>> weights.grad + tensor([-1.1007, 0.9853, -4.2316, -1.6606]) + +""", +) + +add_docstr_all( + "reshape", + r""" +reshape(*shape) -> Tensor + +Returns a tensor with the same data and number of elements as :attr:`self` +but with the specified shape. This method returns a view if :attr:`shape` is +compatible with the current shape. See :meth:`torch.Tensor.view` on when it is +possible to return a view. + +See :func:`torch.reshape` + +Args: + shape (tuple of ints or int...): the desired shape + +""", +) + +add_docstr_all( + "reshape_as", + r""" +reshape_as(other) -> Tensor + +Returns this tensor as the same shape as :attr:`other`. +``self.reshape_as(other)`` is equivalent to ``self.reshape(other.sizes())``. +This method returns a view if ``other.sizes()`` is compatible with the current +shape. See :meth:`torch.Tensor.view` on when it is possible to return a view. + +Please see :meth:`reshape` for more information about ``reshape``. + +Args: + other (:class:`torch.Tensor`): The result tensor has the same shape + as :attr:`other`. +""", +) + +add_docstr_all( + "resize_", + r""" +resize_(*sizes, memory_format=torch.contiguous_format) -> Tensor + +Resizes :attr:`self` tensor to the specified size. If the number of elements is +larger than the current storage size, then the underlying storage is resized +to fit the new number of elements. If the number of elements is smaller, the +underlying storage is not changed. Existing elements are preserved but any new +memory is uninitialized. + +.. warning:: + + This is a low-level method. The storage is reinterpreted as C-contiguous, + ignoring the current strides (unless the target size equals the current + size, in which case the tensor is left unchanged). For most purposes, you + will instead want to use :meth:`~Tensor.view()`, which checks for + contiguity, or :meth:`~Tensor.reshape()`, which copies data if needed. To + change the size in-place with custom strides, see :meth:`~Tensor.set_()`. + +.. note:: + + If :func:`torch.use_deterministic_algorithms()` and + :attr:`torch.utils.deterministic.fill_uninitialized_memory` are both set to + ``True``, new elements are initialized to prevent nondeterministic behavior + from using the result as an input to an operation. Floating point and + complex values are set to NaN, and integer values are set to the maximum + value. + +Args: + sizes (torch.Size or int...): the desired size + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + Tensor. Default: ``torch.contiguous_format``. Note that memory format of + :attr:`self` is going to be unaffected if ``self.size()`` matches ``sizes``. + +Example:: + + >>> x = torch.tensor([[1, 2], [3, 4], [5, 6]]) + >>> x.resize_(2, 2) + tensor([[ 1, 2], + [ 3, 4]]) +""", +) + +add_docstr_all( + "resize_as_", + r""" +resize_as_(tensor, memory_format=torch.contiguous_format) -> Tensor + +Resizes the :attr:`self` tensor to be the same size as the specified +:attr:`tensor`. This is equivalent to ``self.resize_(tensor.size())``. + +Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + Tensor. Default: ``torch.contiguous_format``. Note that memory format of + :attr:`self` is going to be unaffected if ``self.size()`` matches ``tensor.size()``. + +""", +) + +add_docstr_all( + "rot90", + r""" +rot90(k, dims) -> Tensor + +See :func:`torch.rot90` +""", +) + +add_docstr_all( + "round", + r""" +round(decimals=0) -> Tensor + +See :func:`torch.round` +""", +) + +add_docstr_all( + "round_", + r""" +round_(decimals=0) -> Tensor + +In-place version of :meth:`~Tensor.round` +""", +) + +add_docstr_all( + "rsqrt", + r""" +rsqrt() -> Tensor + +See :func:`torch.rsqrt` +""", +) + +add_docstr_all( + "rsqrt_", + r""" +rsqrt_() -> Tensor + +In-place version of :meth:`~Tensor.rsqrt` +""", +) + +add_docstr_all( + "scatter_", + r""" +scatter_(dim, index, src, *, reduce=None) -> Tensor + +Writes all values from the tensor :attr:`src` into :attr:`self` at the indices +specified in the :attr:`index` tensor. For each value in :attr:`src`, its output +index is specified by its index in :attr:`src` for ``dimension != dim`` and by +the corresponding value in :attr:`index` for ``dimension = dim``. + +For a 3-D tensor, :attr:`self` is updated as:: + + self[index[i][j][k]][j][k] = src[i][j][k] # if dim == 0 + self[i][index[i][j][k]][k] = src[i][j][k] # if dim == 1 + self[i][j][index[i][j][k]] = src[i][j][k] # if dim == 2 + +This is the reverse operation of the manner described in :meth:`~Tensor.gather`. + +It is also required that +``index.size(d) <= src.size(d)`` for all dimensions ``d``, and that +``index.size(d) <= self.size(d)`` for all dimensions ``d != dim``. +Note that ``input`` and ``index`` do not broadcast against each other for NPUs, +so when running on NPUs, :attr:`input` and :attr:`index` must have the same number of dimensions. +Standard broadcasting occurs in all other cases. + +Moreover, as for :meth:`~Tensor.gather`, the values of :attr:`index` must be +between ``0`` and ``self.size(dim) - 1`` inclusive. + +.. warning:: + + When indices are not unique, the behavior is non-deterministic (one of the + values from ``src`` will be picked arbitrarily) and the gradient will be + incorrect (it will be propagated to all locations in the source that + correspond to the same index)! + +.. note:: + + The backward pass is implemented only for ``src.shape == index.shape``. + +Additionally accepts an optional :attr:`reduce` argument that allows +specification of an optional reduction operation, which is applied to all +values in the tensor :attr:`src` into :attr:`self` at the indices +specified in the :attr:`index`. For each value in :attr:`src`, the reduction +operation is applied to an index in :attr:`self` which is specified by +its index in :attr:`src` for ``dimension != dim`` and by the corresponding +value in :attr:`index` for ``dimension = dim``. + +Given a 3-D tensor and reduction using the multiplication operation, :attr:`self` +is updated as:: + + self[index[i][j][k]][j][k] *= src[i][j][k] # if dim == 0 + self[i][index[i][j][k]][k] *= src[i][j][k] # if dim == 1 + self[i][j][index[i][j][k]] *= src[i][j][k] # if dim == 2 + +Reducing with the addition operation is the same as using +:meth:`~torch.Tensor.scatter_add_`. + +.. warning:: + The reduce argument with Tensor ``src`` is deprecated and will be removed in + a future PyTorch release. Please use :meth:`~torch.Tensor.scatter_reduce_` + instead for more reduction options. + +Args: + dim (int): the axis along which to index + index (LongTensor): the indices of elements to scatter, can be either empty + or of the same dimensionality as ``src``. When empty, the operation + returns ``self`` unchanged. + src (Tensor): the source element(s) to scatter. + +Keyword args: + reduce (str, optional): reduction operation to apply, can be either + ``'add'`` or ``'multiply'``. + +Example:: + + >>> src = torch.arange(1, 11).reshape((2, 5)) + >>> src + tensor([[ 1, 2, 3, 4, 5], + [ 6, 7, 8, 9, 10]]) + >>> index = torch.tensor([[0, 1, 2, 0]]) + >>> torch.zeros(3, 5, dtype=src.dtype).scatter_(0, index, src) + tensor([[1, 0, 0, 4, 0], + [0, 2, 0, 0, 0], + [0, 0, 3, 0, 0]]) + >>> index = torch.tensor([[0, 1, 2], [0, 1, 4]]) + >>> torch.zeros(3, 5, dtype=src.dtype).scatter_(1, index, src) + tensor([[1, 2, 3, 0, 0], + [6, 7, 0, 0, 8], + [0, 0, 0, 0, 0]]) + + >>> torch.full((2, 4), 2.).scatter_(1, torch.tensor([[2], [3]]), + ... 1.23, reduce='multiply') + tensor([[2.0000, 2.0000, 2.4600, 2.0000], + [2.0000, 2.0000, 2.0000, 2.4600]]) + >>> torch.full((2, 4), 2.).scatter_(1, torch.tensor([[2], [3]]), + ... 1.23, reduce='add') + tensor([[2.0000, 2.0000, 3.2300, 2.0000], + [2.0000, 2.0000, 2.0000, 3.2300]]) + +.. function:: scatter_(dim, index, value, *, reduce=None) -> Tensor: + :noindex: + +Writes the value from :attr:`value` into :attr:`self` at the indices +specified in the :attr:`index` tensor. This operation is equivalent to the previous version, +with the :attr:`src` tensor filled entirely with :attr:`value`. + +Args: + dim (int): the axis along which to index + index (LongTensor): the indices of elements to scatter, can be either empty + or of the same dimensionality as ``src``. When empty, the operation + returns ``self`` unchanged. + value (Scalar): the value to scatter. + +Keyword args: + reduce (str, optional): reduction operation to apply, can be either + ``'add'`` or ``'multiply'``. + +Example:: + + >>> index = torch.tensor([[0, 1]]) + >>> value = 2 + >>> torch.zeros(3, 5).scatter_(0, index, value) + tensor([[2., 0., 0., 0., 0.], + [0., 2., 0., 0., 0.], + [0., 0., 0., 0., 0.]]) +""", +) + +add_docstr_all( + "scatter_add_", + r""" +scatter_add_(dim, index, src) -> Tensor + +Adds all values from the tensor :attr:`src` into :attr:`self` at the indices +specified in the :attr:`index` tensor in a similar fashion as +:meth:`~torch.Tensor.scatter_`. For each value in :attr:`src`, it is added to +an index in :attr:`self` which is specified by its index in :attr:`src` +for ``dimension != dim`` and by the corresponding value in :attr:`index` for +``dimension = dim``. + +For a 3-D tensor, :attr:`self` is updated as:: + + self[index[i][j][k]][j][k] += src[i][j][k] # if dim == 0 + self[i][index[i][j][k]][k] += src[i][j][k] # if dim == 1 + self[i][j][index[i][j][k]] += src[i][j][k] # if dim == 2 + +:attr:`self`, :attr:`index` and :attr:`src` should have same number of +dimensions. It is also required that ``index.size(d) <= src.size(d)`` for all +dimensions ``d``, and that ``index.size(d) <= self.size(d)`` for all dimensions +``d != dim``. Note that ``index`` and ``src`` do not broadcast. +When :attr:`index` is empty, we always return the original tensor +without further error checking. + +Note: + {forward_reproducibility_note} + +.. note:: + + The backward pass is implemented only for ``src.shape == index.shape``. + +Args: + dim (int): the axis along which to index + index (LongTensor): the indices of elements to scatter and add, can be + either empty or of the same dimensionality as ``src``. When empty, the + operation returns ``self`` unchanged. + src (Tensor): the source elements to scatter and add + +Example:: + + >>> src = torch.ones((2, 5)) + >>> index = torch.tensor([[0, 1, 2, 0, 0]]) + >>> torch.zeros(3, 5, dtype=src.dtype).scatter_add_(0, index, src) + tensor([[1., 0., 0., 1., 1.], + [0., 1., 0., 0., 0.], + [0., 0., 1., 0., 0.]]) + >>> index = torch.tensor([[0, 1, 2, 0, 0], [0, 1, 2, 2, 2]]) + >>> torch.zeros(3, 5, dtype=src.dtype).scatter_add_(0, index, src) + tensor([[2., 0., 0., 1., 1.], + [0., 2., 0., 0., 0.], + [0., 0., 2., 1., 1.]]) + +""".format(**reproducibility_notes), +) + +add_docstr_all( + "scatter_reduce_", + r""" +scatter_reduce_(dim, index, src, reduce, *, include_self=True) -> Tensor + +Reduces all values from the :attr:`src` tensor to the indices specified in +the :attr:`index` tensor in the :attr:`self` tensor using the applied reduction +defined via the :attr:`reduce` argument (:obj:`"sum"`, :obj:`"prod"`, :obj:`"mean"`, +:obj:`"amax"`, :obj:`"amin"`). For each value in :attr:`src`, it is reduced to an +index in :attr:`self` which is specified by its index in :attr:`src` for +``dimension != dim`` and by the corresponding value in :attr:`index` for +``dimension = dim``. If :obj:`include_self="True"`, the values in the :attr:`self` +tensor are included in the reduction. + +:attr:`self`, :attr:`index` and :attr:`src` should all have +the same number of dimensions. It is also required that +``index.size(d) <= src.size(d)`` for all dimensions ``d``, and that +``index.size(d) <= self.size(d)`` for all dimensions ``d != dim``. +Note that ``index`` and ``src`` do not broadcast. + +For a 3-D tensor with :obj:`reduce="sum"` and :obj:`include_self=True` the +output is given as:: + + self[index[i][j][k]][j][k] += src[i][j][k] # if dim == 0 + self[i][index[i][j][k]][k] += src[i][j][k] # if dim == 1 + self[i][j][index[i][j][k]] += src[i][j][k] # if dim == 2 + +Note: + {forward_reproducibility_note} + +.. note:: + + The backward pass is implemented only for ``src.shape == index.shape``. + +.. warning:: + + This function is in beta and may change in the near future. + +Args: + dim (int): the axis along which to index + index (LongTensor): the indices of elements to scatter and reduce. + src (Tensor): the source elements to scatter and reduce + reduce (str): the reduction operation to apply for non-unique indices + (:obj:`"sum"`, :obj:`"prod"`, :obj:`"mean"`, :obj:`"amax"`, :obj:`"amin"`) + include_self (bool): whether elements from the :attr:`self` tensor are + included in the reduction + +Example:: + + >>> src = torch.tensor([1., 2., 3., 4., 5., 6.]) + >>> index = torch.tensor([0, 1, 0, 1, 2, 1]) + >>> input = torch.tensor([1., 2., 3., 4.]) + >>> input.scatter_reduce(0, index, src, reduce="sum") + tensor([5., 14., 8., 4.]) + >>> input.scatter_reduce(0, index, src, reduce="sum", include_self=False) + tensor([4., 12., 5., 4.]) + >>> input2 = torch.tensor([5., 4., 3., 2.]) + >>> input2.scatter_reduce(0, index, src, reduce="amax") + tensor([5., 6., 5., 2.]) + >>> input2.scatter_reduce(0, index, src, reduce="amax", include_self=False) + tensor([3., 6., 5., 2.]) + + +""".format(**reproducibility_notes), +) + +add_docstr_all( + "select", + r""" +select(dim, index) -> Tensor + +See :func:`torch.select` +""", +) + +add_docstr_all( + "select_scatter", + r""" +select_scatter(src, dim, index) -> Tensor + +See :func:`torch.select_scatter` +""", +) + +add_docstr_all( + "slice_scatter", + r""" +slice_scatter(src, dim=0, start=None, end=None, step=1) -> Tensor + +See :func:`torch.slice_scatter` +""", +) + +add_docstr_all( + "set_", + r""" +set_(source=None, storage_offset=0, size=None, stride=None) -> Tensor + +Sets the underlying storage, size, and strides. If :attr:`source` is a tensor, +:attr:`self` tensor will share the same storage and have the same size and +strides as :attr:`source`. Changes to elements in one tensor will be reflected +in the other. + +If :attr:`source` is a :class:`~torch.Storage`, the method sets the underlying +storage, offset, size, and stride. + +Args: + source (Tensor or Storage): the tensor or storage to use + storage_offset (int, optional): the offset in the storage + size (torch.Size, optional): the desired size. Defaults to the size of the source. + stride (tuple, optional): the desired stride. Defaults to C-contiguous strides. +""", +) + +add_docstr_all( + "sigmoid", + r""" +sigmoid() -> Tensor + +See :func:`torch.sigmoid` +""", +) + +add_docstr_all( + "sigmoid_", + r""" +sigmoid_() -> Tensor + +In-place version of :meth:`~Tensor.sigmoid` +""", +) + +add_docstr_all( + "logit", + r""" +logit() -> Tensor + +See :func:`torch.logit` +""", +) + +add_docstr_all( + "logit_", + r""" +logit_() -> Tensor + +In-place version of :meth:`~Tensor.logit` +""", +) + +add_docstr_all( + "sign", + r""" +sign() -> Tensor + +See :func:`torch.sign` +""", +) + +add_docstr_all( + "sign_", + r""" +sign_() -> Tensor + +In-place version of :meth:`~Tensor.sign` +""", +) + +add_docstr_all( + "signbit", + r""" +signbit() -> Tensor + +See :func:`torch.signbit` +""", +) + +add_docstr_all( + "sgn", + r""" +sgn() -> Tensor + +See :func:`torch.sgn` +""", +) + +add_docstr_all( + "sgn_", + r""" +sgn_() -> Tensor + +In-place version of :meth:`~Tensor.sgn` +""", +) + +add_docstr_all( + "sin", + r""" +sin() -> Tensor + +See :func:`torch.sin` +""", +) + +add_docstr_all( + "sin_", + r""" +sin_() -> Tensor + +In-place version of :meth:`~Tensor.sin` +""", +) + +add_docstr_all( + "sinc", + r""" +sinc() -> Tensor + +See :func:`torch.sinc` +""", +) + +add_docstr_all( + "sinc_", + r""" +sinc_() -> Tensor + +In-place version of :meth:`~Tensor.sinc` +""", +) + +add_docstr_all( + "sinh", + r""" +sinh() -> Tensor + +See :func:`torch.sinh` +""", +) + +add_docstr_all( + "sinh_", + r""" +sinh_() -> Tensor + +In-place version of :meth:`~Tensor.sinh` +""", +) + +add_docstr_all( + "size", + r""" +size(dim=None) -> torch.Size or int + +Returns the size of the :attr:`self` tensor. If ``dim`` is not specified, +the returned value is a :class:`torch.Size`, a subclass of :class:`tuple`. +If ``dim`` is specified, returns an int holding the size of that dimension. + +Args: + dim (int, optional): The dimension for which to retrieve the size. + +Example:: + + >>> t = torch.empty(3, 4, 5) + >>> t.size() + torch.Size([3, 4, 5]) + >>> t.size(dim=1) + 4 + +""", +) + +add_docstr_all( + "shape", + r""" +shape() -> torch.Size + +Returns the size of the :attr:`self` tensor. Alias for :attr:`size`. + +See also :meth:`Tensor.size`. + +Example:: + + >>> t = torch.empty(3, 4, 5) + >>> t.size() + torch.Size([3, 4, 5]) + >>> t.shape + torch.Size([3, 4, 5]) + +""", +) + +add_docstr_all( + "sort", + r""" +sort(dim=-1, descending=False) -> (Tensor, LongTensor) + +See :func:`torch.sort` +""", +) + +add_docstr_all( + "msort", + r""" +msort() -> Tensor + +See :func:`torch.msort` +""", +) + +add_docstr_all( + "argsort", + r""" +argsort(dim=-1, descending=False) -> LongTensor + +See :func:`torch.argsort` +""", +) + +add_docstr_all( + "sparse_dim", + r""" +sparse_dim() -> int + +Return the number of sparse dimensions in a :ref:`sparse tensor ` :attr:`self`. + +.. note:: + Returns ``0`` if :attr:`self` is not a sparse tensor. + +See also :meth:`Tensor.dense_dim` and :ref:`hybrid tensors `. +""", +) + +add_docstr_all( + "sparse_resize_", + r""" +sparse_resize_(size, sparse_dim, dense_dim) -> Tensor + +Resizes :attr:`self` :ref:`sparse tensor ` to the desired +size and the number of sparse and dense dimensions. + +.. note:: + If the number of specified elements in :attr:`self` is zero, then + :attr:`size`, :attr:`sparse_dim`, and :attr:`dense_dim` can be any + size and positive integers such that ``len(size) == sparse_dim + + dense_dim``. + + If :attr:`self` specifies one or more elements, however, then each + dimension in :attr:`size` must not be smaller than the corresponding + dimension of :attr:`self`, :attr:`sparse_dim` must equal the number + of sparse dimensions in :attr:`self`, and :attr:`dense_dim` must + equal the number of dense dimensions in :attr:`self`. + +.. warning:: + Throws an error if :attr:`self` is not a sparse tensor. + +Args: + size (torch.Size): the desired size. If :attr:`self` is non-empty + sparse tensor, the desired size cannot be smaller than the + original size. + sparse_dim (int): the number of sparse dimensions + dense_dim (int): the number of dense dimensions +""", +) + +add_docstr_all( + "sparse_resize_and_clear_", + r""" +sparse_resize_and_clear_(size, sparse_dim, dense_dim) -> Tensor + +Removes all specified elements from a :ref:`sparse tensor +` :attr:`self` and resizes :attr:`self` to the desired +size and the number of sparse and dense dimensions. + +.. warning: + Throws an error if :attr:`self` is not a sparse tensor. + +Args: + size (torch.Size): the desired size. + sparse_dim (int): the number of sparse dimensions + dense_dim (int): the number of dense dimensions +""", +) + +add_docstr_all( + "sqrt", + r""" +sqrt() -> Tensor + +See :func:`torch.sqrt` +""", +) + +add_docstr_all( + "sqrt_", + r""" +sqrt_() -> Tensor + +In-place version of :meth:`~Tensor.sqrt` +""", +) + +add_docstr_all( + "square", + r""" +square() -> Tensor + +See :func:`torch.square` +""", +) + +add_docstr_all( + "square_", + r""" +square_() -> Tensor + +In-place version of :meth:`~Tensor.square` +""", +) + +add_docstr_all( + "squeeze", + r""" +squeeze(dim=None) -> Tensor + +See :func:`torch.squeeze` +""", +) + +add_docstr_all( + "squeeze_", + r""" +squeeze_(dim=None) -> Tensor + +In-place version of :meth:`~Tensor.squeeze` +""", +) + +add_docstr_all( + "std", + r""" +std(dim=None, *, correction=1, keepdim=False) -> Tensor + +See :func:`torch.std` +""", +) + +add_docstr_all( + "storage_offset", + r""" +storage_offset() -> int + +Returns :attr:`self` tensor's offset in the underlying storage in terms of +number of storage elements (not bytes). + +Example:: + + >>> x = torch.tensor([1, 2, 3, 4, 5]) + >>> x.storage_offset() + 0 + >>> x[3:].storage_offset() + 3 + +""", +) + +add_docstr_all( + "untyped_storage", + r""" +untyped_storage() -> torch.UntypedStorage + +Returns the underlying :class:`UntypedStorage`. +""", +) + +add_docstr_all( + "stride", + r""" +stride(dim) -> tuple or int + +Returns the stride of :attr:`self` tensor. + +Stride is the jump necessary to go from one element to the next one in the +specified dimension :attr:`dim`. A tuple of all strides is returned when no +argument is passed in. Otherwise, an integer value is returned as the stride in +the particular dimension :attr:`dim`. + +Args: + dim (int, optional): the desired dimension in which stride is required + +Example:: + + >>> x = torch.tensor([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]) + >>> x.stride() + (5, 1) + >>> x.stride(0) + 5 + >>> x.stride(-1) + 1 + +""", +) + +add_docstr_all( + "sub", + r""" +sub(other, *, alpha=1) -> Tensor + +See :func:`torch.sub`. +""", +) + +add_docstr_all( + "sub_", + r""" +sub_(other, *, alpha=1) -> Tensor + +In-place version of :meth:`~Tensor.sub` +""", +) + +add_docstr_all( + "subtract", + r""" +subtract(other, *, alpha=1) -> Tensor + +See :func:`torch.subtract`. +""", +) + +add_docstr_all( + "subtract_", + r""" +subtract_(other, *, alpha=1) -> Tensor + +In-place version of :meth:`~Tensor.subtract`. +""", +) + +add_docstr_all( + "sum", + r""" +sum(dim=None, keepdim=False, dtype=None) -> Tensor + +See :func:`torch.sum` +""", +) + +add_docstr_all( + "nansum", + r""" +nansum(dim=None, keepdim=False, dtype=None) -> Tensor + +See :func:`torch.nansum` +""", +) + +add_docstr_all( + "svd", + r""" +svd(some=True, compute_uv=True) -> (Tensor, Tensor, Tensor) + +See :func:`torch.svd` +""", +) + +add_docstr_all( + "swapdims", + r""" +swapdims(dim0, dim1) -> Tensor + +See :func:`torch.swapdims` +""", +) + +add_docstr_all( + "swapdims_", + r""" +swapdims_(dim0, dim1) -> Tensor + +In-place version of :meth:`~Tensor.swapdims` +""", +) + +add_docstr_all( + "swapaxes", + r""" +swapaxes(axis0, axis1) -> Tensor + +See :func:`torch.swapaxes` +""", +) + +add_docstr_all( + "swapaxes_", + r""" +swapaxes_(axis0, axis1) -> Tensor + +In-place version of :meth:`~Tensor.swapaxes` +""", +) + +add_docstr_all( + "t", + r""" +t() -> Tensor + +See :func:`torch.t` +""", +) + +add_docstr_all( + "t_", + r""" +t_() -> Tensor + +In-place version of :meth:`~Tensor.t` +""", +) + +add_docstr_all( + "tile", + r""" +tile(dims) -> Tensor + +See :func:`torch.tile` +""", +) + +add_docstr_all( + "to", + r""" +to(*args, **kwargs) -> Tensor + +Performs Tensor dtype and/or device conversion. A :class:`torch.dtype` and :class:`torch.device` are +inferred from the arguments of ``self.to(*args, **kwargs)``. + +.. note:: + + If the ``self`` Tensor already + has the correct :class:`torch.dtype` and :class:`torch.device`, then ``self`` is returned. + Otherwise, the returned tensor is a copy of ``self`` with the desired + :class:`torch.dtype` and :class:`torch.device`. + +.. note:: + + If ``self`` requires gradients (``requires_grad=True``) but the target + ``dtype`` specified is an integer type, the returned tensor will implicitly + set ``requires_grad=False``. This is because only tensors with + floating-point or complex dtypes can require gradients. + +Here are the ways to call ``to``: + +.. method:: to(dtype, non_blocking=False, copy=False, memory_format=torch.preserve_format) -> Tensor + :noindex: + + Returns a Tensor with the specified :attr:`dtype` + + Args: + {memory_format} + +.. note:: + + According to `C++ type conversion rules `_, + converting floating point value to integer type will truncate the fractional part. + If the truncated value cannot fit into the target type (e.g., casting ``torch.inf`` to ``torch.long``), + the behavior is undefined and the result may vary across platforms. + +.. method:: to(device=None, dtype=None, non_blocking=False, copy=False, memory_format=torch.preserve_format) -> Tensor + :noindex: + + Returns a Tensor with the specified :attr:`device` and (optional) + :attr:`dtype`. If :attr:`dtype` is ``None`` it is inferred to be ``self.dtype``. + When :attr:`non_blocking` is set to ``True``, the function attempts to perform + the conversion asynchronously with respect to the host, if possible. This + asynchronous behavior applies to both pinned and pageable memory. However, + caution is advised when using this feature. For more information, refer to the + `tutorial on good usage of non_blocking and pin_memory `__. + When :attr:`copy` is set, a new Tensor is created even when the Tensor + already matches the desired conversion. + + Args: + {memory_format} + +.. method:: to(other, non_blocking=False, copy=False) -> Tensor + :noindex: + + Returns a Tensor with same :class:`torch.dtype` and :class:`torch.device` as + the Tensor :attr:`other`. + When :attr:`non_blocking` is set to ``True``, the function attempts to perform + the conversion asynchronously with respect to the host, if possible. This + asynchronous behavior applies to both pinned and pageable memory. However, + caution is advised when using this feature. For more information, refer to the + `tutorial on good usage of non_blocking and pin_memory `__. + When :attr:`copy` is set, a new Tensor is created even when the Tensor + already matches the desired conversion. + +Example:: + + >>> tensor = torch.randn(2, 2) # Initially dtype=float32, device=cpu + >>> tensor.to(torch.float64) + tensor([[-0.5044, 0.0005], + [ 0.3310, -0.0584]], dtype=torch.float64) + + >>> cuda0 = torch.device('cuda:0') + >>> tensor.to(cuda0) + tensor([[-0.5044, 0.0005], + [ 0.3310, -0.0584]], device='cuda:0') + + >>> tensor.to(cuda0, dtype=torch.float64) + tensor([[-0.5044, 0.0005], + [ 0.3310, -0.0584]], dtype=torch.float64, device='cuda:0') + + >>> other = torch.randn((), dtype=torch.float64, device=cuda0) + >>> tensor.to(other, non_blocking=True) + tensor([[-0.5044, 0.0005], + [ 0.3310, -0.0584]], dtype=torch.float64, device='cuda:0') +""".format(**common_args), +) + +add_docstr_all( + "byte", + r""" +byte(memory_format=torch.preserve_format) -> Tensor + +``self.byte()`` is equivalent to ``self.to(torch.uint8)``. See :func:`to`. + +Args: + {memory_format} +""".format(**common_args), +) + +add_docstr_all( + "bool", + r""" +bool(memory_format=torch.preserve_format) -> Tensor + +``self.bool()`` is equivalent to ``self.to(torch.bool)``. See :func:`to`. + +Args: + {memory_format} +""".format(**common_args), +) + +add_docstr_all( + "char", + r""" +char(memory_format=torch.preserve_format) -> Tensor + +``self.char()`` is equivalent to ``self.to(torch.int8)``. See :func:`to`. + +Args: + {memory_format} +""".format(**common_args), +) + +add_docstr_all( + "bfloat16", + r""" +bfloat16(memory_format=torch.preserve_format) -> Tensor +``self.bfloat16()`` is equivalent to ``self.to(torch.bfloat16)``. See :func:`to`. + +Args: + {memory_format} +""".format(**common_args), +) + +add_docstr_all( + "double", + r""" +double(memory_format=torch.preserve_format) -> Tensor + +``self.double()`` is equivalent to ``self.to(torch.float64)``. See :func:`to`. + +Args: + {memory_format} +""".format(**common_args), +) + +add_docstr_all( + "float", + r""" +float(memory_format=torch.preserve_format) -> Tensor + +``self.float()`` is equivalent to ``self.to(torch.float32)``. See :func:`to`. + +Args: + {memory_format} +""".format(**common_args), +) + +add_docstr_all( + "cdouble", + r""" +cdouble(memory_format=torch.preserve_format) -> Tensor + +``self.cdouble()`` is equivalent to ``self.to(torch.complex128)``. See :func:`to`. + +Args: + {memory_format} +""".format(**common_args), +) + +add_docstr_all( + "cfloat", + r""" +cfloat(memory_format=torch.preserve_format) -> Tensor + +``self.cfloat()`` is equivalent to ``self.to(torch.complex64)``. See :func:`to`. + +Args: + {memory_format} +""".format(**common_args), +) + +add_docstr_all( + "chalf", + r""" +chalf(memory_format=torch.preserve_format) -> Tensor + +``self.chalf()`` is equivalent to ``self.to(torch.complex32)``. See :func:`to`. + +Args: + {memory_format} + """.format(**common_args), +) + +add_docstr_all( + "half", + r""" +half(memory_format=torch.preserve_format) -> Tensor + +``self.half()`` is equivalent to ``self.to(torch.float16)``. See :func:`to`. + +Args: + {memory_format} +""".format(**common_args), +) + +add_docstr_all( + "int", + r""" +int(memory_format=torch.preserve_format) -> Tensor + +``self.int()`` is equivalent to ``self.to(torch.int32)``. See :func:`to`. + +Args: + {memory_format} +""".format(**common_args), +) + +add_docstr_all( + "int_repr", + r""" +int_repr() -> Tensor + +Given a quantized Tensor, +``self.int_repr()`` returns a CPU Tensor with uint8_t as data type that stores the +underlying uint8_t values of the given Tensor. +""", +) + + +add_docstr_all( + "long", + r""" +long(memory_format=torch.preserve_format) -> Tensor + +``self.long()`` is equivalent to ``self.to(torch.int64)``. See :func:`to`. + +Args: + {memory_format} +""".format(**common_args), +) + +add_docstr_all( + "short", + r""" +short(memory_format=torch.preserve_format) -> Tensor + +``self.short()`` is equivalent to ``self.to(torch.int16)``. See :func:`to`. + +Args: + {memory_format} +""".format(**common_args), +) + +add_docstr_all( + "take", + r""" +take(indices) -> Tensor + +See :func:`torch.take` +""", +) + +add_docstr_all( + "take_along_dim", + r""" +take_along_dim(indices, dim) -> Tensor + +See :func:`torch.take_along_dim` +""", +) + +add_docstr_all( + "tan", + r""" +tan() -> Tensor + +See :func:`torch.tan` +""", +) + +add_docstr_all( + "tan_", + r""" +tan_() -> Tensor + +In-place version of :meth:`~Tensor.tan` +""", +) + +add_docstr_all( + "tanh", + r""" +tanh() -> Tensor + +See :func:`torch.tanh` +""", +) + +add_docstr_all( + "softmax", + r""" +softmax(dim) -> Tensor + +Alias for :func:`torch.nn.functional.softmax`. +""", +) + +add_docstr_all( + "tanh_", + r""" +tanh_() -> Tensor + +In-place version of :meth:`~Tensor.tanh` +""", +) + +add_docstr_all( + "tolist", + r""" +tolist() -> list or number + +Returns the tensor as a (nested) list. For scalars, a standard +Python number is returned, just like with :meth:`~Tensor.item`. +Tensors are automatically moved to the CPU first if necessary. + +This operation is not differentiable. + +Examples:: + + >>> a = torch.randn(2, 2) + >>> a.tolist() + [[0.012766935862600803, 0.5415473580360413], + [-0.08909505605697632, 0.7729271650314331]] + >>> a[0,0].tolist() + 0.012766935862600803 +""", +) + +add_docstr_all( + "topk", + r""" +topk(k, dim=None, largest=True, sorted=True) -> (Tensor, LongTensor) + +See :func:`torch.topk` +""", +) + +add_docstr_all( + "to_dense", + r""" +to_dense(dtype=None, *, masked_grad=True) -> Tensor + +Creates a strided copy of :attr:`self` if :attr:`self` is not a strided tensor, otherwise returns :attr:`self`. + +Keyword args: + {dtype} + masked_grad (bool, optional): If set to ``True`` (default) and + :attr:`self` has a sparse layout then the backward of + :meth:`to_dense` returns ``grad.sparse_mask(self)``. + +Example:: + + >>> s = torch.sparse_coo_tensor( + ... torch.tensor([[1, 1], + ... [0, 2]]), + ... torch.tensor([9, 10]), + ... size=(3, 3)) + >>> s.to_dense() + tensor([[ 0, 0, 0], + [ 9, 0, 10], + [ 0, 0, 0]]) +""", +) + +add_docstr_all( + "to_sparse", + r""" +to_sparse(sparseDims) -> Tensor + +Returns a sparse copy of the tensor. PyTorch supports sparse tensors in +:ref:`coordinate format `. + +Args: + sparseDims (int, optional): the number of sparse dimensions to include in the new sparse tensor + +Example:: + + >>> d = torch.tensor([[0, 0, 0], [9, 0, 10], [0, 0, 0]]) + >>> d + tensor([[ 0, 0, 0], + [ 9, 0, 10], + [ 0, 0, 0]]) + >>> d.to_sparse() + tensor(indices=tensor([[1, 1], + [0, 2]]), + values=tensor([ 9, 10]), + size=(3, 3), nnz=2, layout=torch.sparse_coo) + >>> d.to_sparse(1) + tensor(indices=tensor([[1]]), + values=tensor([[ 9, 0, 10]]), + size=(3, 3), nnz=1, layout=torch.sparse_coo) + +.. method:: to_sparse(*, layout=None, blocksize=None, dense_dim=None) -> Tensor + :noindex: + +Returns a sparse tensor with the specified layout and blocksize. If +the :attr:`self` is strided, the number of dense dimensions could be +specified, and a hybrid sparse tensor will be created, with +`dense_dim` dense dimensions and `self.dim() - 2 - dense_dim` batch +dimension. + +.. note:: If the :attr:`self` layout and blocksize parameters match + with the specified layout and blocksize, return + :attr:`self`. Otherwise, return a sparse tensor copy of + :attr:`self`. + +Args: + + layout (:class:`torch.layout`, optional): The desired sparse + layout. One of ``torch.sparse_coo``, ``torch.sparse_csr``, + ``torch.sparse_csc``, ``torch.sparse_bsr``, or + ``torch.sparse_bsc``. Default: if ``None``, + ``torch.sparse_coo``. + + blocksize (list, tuple, :class:`torch.Size`, optional): Block size + of the resulting BSR or BSC tensor. For other layouts, + specifying the block size that is not ``None`` will result in a + RuntimeError exception. A block size must be a tuple of length + two such that its items evenly divide the two sparse dimensions. + + dense_dim (int, optional): Number of dense dimensions of the + resulting CSR, CSC, BSR or BSC tensor. This argument should be + used only if :attr:`self` is a strided tensor, and must be a + value between 0 and dimension of :attr:`self` tensor minus two. + +Example:: + + >>> x = torch.tensor([[1, 0], [0, 0], [2, 3]]) + >>> x.to_sparse(layout=torch.sparse_coo) + tensor(indices=tensor([[0, 2, 2], + [0, 0, 1]]), + values=tensor([1, 2, 3]), + size=(3, 2), nnz=3, layout=torch.sparse_coo) + >>> x.to_sparse(layout=torch.sparse_bsr, blocksize=(1, 2)) + tensor(crow_indices=tensor([0, 1, 1, 2]), + col_indices=tensor([0, 0]), + values=tensor([[[1, 0]], + [[2, 3]]]), size=(3, 2), nnz=2, layout=torch.sparse_bsr) + >>> x.to_sparse(layout=torch.sparse_bsr, blocksize=(2, 1)) + RuntimeError: Tensor size(-2) 3 needs to be divisible by blocksize[0] 2 + >>> x.to_sparse(layout=torch.sparse_csr, blocksize=(3, 1)) + RuntimeError: to_sparse for Strided to SparseCsr conversion does not use specified blocksize + + >>> x = torch.tensor([[[1], [0]], [[0], [0]], [[2], [3]]]) + >>> x.to_sparse(layout=torch.sparse_csr, dense_dim=1) + tensor(crow_indices=tensor([0, 1, 1, 3]), + col_indices=tensor([0, 0, 1]), + values=tensor([[1], + [2], + [3]]), size=(3, 2, 1), nnz=3, layout=torch.sparse_csr) + +""", +) + +add_docstr_all( + "to_sparse_csr", + r""" +to_sparse_csr(dense_dim=None) -> Tensor + +Convert a tensor to compressed row storage format (CSR). Except for +strided tensors, only works with 2D tensors. If the :attr:`self` is +strided, then the number of dense dimensions could be specified, and a +hybrid CSR tensor will be created, with `dense_dim` dense dimensions +and `self.dim() - 2 - dense_dim` batch dimension. + +Args: + + dense_dim (int, optional): Number of dense dimensions of the + resulting CSR tensor. This argument should be used only if + :attr:`self` is a strided tensor, and must be a value between 0 + and dimension of :attr:`self` tensor minus two. + +Example:: + + >>> dense = torch.randn(5, 5) + >>> sparse = dense.to_sparse_csr() + >>> sparse._nnz() + 25 + + >>> dense = torch.zeros(3, 3, 1, 1) + >>> dense[0, 0] = dense[1, 2] = dense[2, 1] = 1 + >>> dense.to_sparse_csr(dense_dim=2) + tensor(crow_indices=tensor([0, 1, 2, 3]), + col_indices=tensor([0, 2, 1]), + values=tensor([[[1.]], + + [[1.]], + + [[1.]]]), size=(3, 3, 1, 1), nnz=3, + layout=torch.sparse_csr) + +""", +) + +add_docstr_all( + "to_sparse_csc", + r""" +to_sparse_csc() -> Tensor + +Convert a tensor to compressed column storage (CSC) format. Except +for strided tensors, only works with 2D tensors. If the :attr:`self` +is strided, then the number of dense dimensions could be specified, +and a hybrid CSC tensor will be created, with `dense_dim` dense +dimensions and `self.dim() - 2 - dense_dim` batch dimension. + +Args: + + dense_dim (int, optional): Number of dense dimensions of the + resulting CSC tensor. This argument should be used only if + :attr:`self` is a strided tensor, and must be a value between 0 + and dimension of :attr:`self` tensor minus two. + +Example:: + + >>> dense = torch.randn(5, 5) + >>> sparse = dense.to_sparse_csc() + >>> sparse._nnz() + 25 + + >>> dense = torch.zeros(3, 3, 1, 1) + >>> dense[0, 0] = dense[1, 2] = dense[2, 1] = 1 + >>> dense.to_sparse_csc(dense_dim=2) + tensor(ccol_indices=tensor([0, 1, 2, 3]), + row_indices=tensor([0, 2, 1]), + values=tensor([[[1.]], + + [[1.]], + + [[1.]]]), size=(3, 3, 1, 1), nnz=3, + layout=torch.sparse_csc) + +""", +) + +add_docstr_all( + "to_sparse_bsr", + r""" +to_sparse_bsr(blocksize, dense_dim) -> Tensor + +Convert a tensor to a block sparse row (BSR) storage format of given +blocksize. If the :attr:`self` is strided, then the number of dense +dimensions could be specified, and a hybrid BSR tensor will be +created, with `dense_dim` dense dimensions and `self.dim() - 2 - +dense_dim` batch dimension. + +Args: + + blocksize (list, tuple, :class:`torch.Size`, optional): Block size + of the resulting BSR tensor. A block size must be a tuple of + length two such that its items evenly divide the two sparse + dimensions. + + dense_dim (int, optional): Number of dense dimensions of the + resulting BSR tensor. This argument should be used only if + :attr:`self` is a strided tensor, and must be a value between 0 + and dimension of :attr:`self` tensor minus two. + +Example:: + + >>> dense = torch.randn(10, 10) + >>> sparse = dense.to_sparse_csr() + >>> sparse_bsr = sparse.to_sparse_bsr((5, 5)) + >>> sparse_bsr.col_indices() + tensor([0, 1, 0, 1]) + + >>> dense = torch.zeros(4, 3, 1) + >>> dense[0:2, 0] = dense[0:2, 2] = dense[2:4, 1] = 1 + >>> dense.to_sparse_bsr((2, 1), 1) + tensor(crow_indices=tensor([0, 2, 3]), + col_indices=tensor([0, 2, 1]), + values=tensor([[[[1.]], + + [[1.]]], + + + [[[1.]], + + [[1.]]], + + + [[[1.]], + + [[1.]]]]), size=(4, 3, 1), nnz=3, + layout=torch.sparse_bsr) + +""", +) + +add_docstr_all( + "to_sparse_bsc", + r""" +to_sparse_bsc(blocksize, dense_dim) -> Tensor + +Convert a tensor to a block sparse column (BSC) storage format of +given blocksize. If the :attr:`self` is strided, then the number of +dense dimensions could be specified, and a hybrid BSC tensor will be +created, with `dense_dim` dense dimensions and `self.dim() - 2 - +dense_dim` batch dimension. + +Args: + + blocksize (list, tuple, :class:`torch.Size`, optional): Block size + of the resulting BSC tensor. A block size must be a tuple of + length two such that its items evenly divide the two sparse + dimensions. + + dense_dim (int, optional): Number of dense dimensions of the + resulting BSC tensor. This argument should be used only if + :attr:`self` is a strided tensor, and must be a value between 0 + and dimension of :attr:`self` tensor minus two. + +Example:: + + >>> dense = torch.randn(10, 10) + >>> sparse = dense.to_sparse_csr() + >>> sparse_bsc = sparse.to_sparse_bsc((5, 5)) + >>> sparse_bsc.row_indices() + tensor([0, 1, 0, 1]) + + >>> dense = torch.zeros(4, 3, 1) + >>> dense[0:2, 0] = dense[0:2, 2] = dense[2:4, 1] = 1 + >>> dense.to_sparse_bsc((2, 1), 1) + tensor(ccol_indices=tensor([0, 1, 2, 3]), + row_indices=tensor([0, 1, 0]), + values=tensor([[[[1.]], + + [[1.]]], + + + [[[1.]], + + [[1.]]], + + + [[[1.]], + + [[1.]]]]), size=(4, 3, 1), nnz=3, + layout=torch.sparse_bsc) + +""", +) + +add_docstr_all( + "to_mkldnn", + r""" +to_mkldnn() -> Tensor +Returns a copy of the tensor in ``torch.mkldnn`` layout. + +""", +) + +add_docstr_all( + "trace", + r""" +trace() -> Tensor + +See :func:`torch.trace` +""", +) + +add_docstr_all( + "transpose", + r""" +transpose(dim0, dim1) -> Tensor + +See :func:`torch.transpose` +""", +) + +add_docstr_all( + "transpose_", + r""" +transpose_(dim0, dim1) -> Tensor + +In-place version of :meth:`~Tensor.transpose` +""", +) + +add_docstr_all( + "triangular_solve", + r""" +triangular_solve(A, upper=True, transpose=False, unitriangular=False) -> (Tensor, Tensor) + +See :func:`torch.triangular_solve` +""", +) + +add_docstr_all( + "tril", + r""" +tril(diagonal=0) -> Tensor + +See :func:`torch.tril` +""", +) + +add_docstr_all( + "tril_", + r""" +tril_(diagonal=0) -> Tensor + +In-place version of :meth:`~Tensor.tril` +""", +) + +add_docstr_all( + "triu", + r""" +triu(diagonal=0) -> Tensor + +See :func:`torch.triu` +""", +) + +add_docstr_all( + "triu_", + r""" +triu_(diagonal=0) -> Tensor + +In-place version of :meth:`~Tensor.triu` +""", +) + +add_docstr_all( + "true_divide", + r""" +true_divide(value) -> Tensor + +See :func:`torch.true_divide` +""", +) + +add_docstr_all( + "true_divide_", + r""" +true_divide_(value) -> Tensor + +In-place version of :meth:`~Tensor.true_divide_` +""", +) + +add_docstr_all( + "trunc", + r""" +trunc() -> Tensor + +See :func:`torch.trunc` +""", +) + +add_docstr_all( + "fix", + r""" +fix() -> Tensor + +See :func:`torch.fix`. +""", +) + +add_docstr_all( + "trunc_", + r""" +trunc_() -> Tensor + +In-place version of :meth:`~Tensor.trunc` +""", +) + +add_docstr_all( + "fix_", + r""" +fix_() -> Tensor + +In-place version of :meth:`~Tensor.fix` +""", +) + +add_docstr_all( + "type", + r""" +type(dtype=None, non_blocking=False, **kwargs) -> str or Tensor +Returns the type if `dtype` is not provided, else casts this object to +the specified type. + +If this is already of the correct type, no copy is performed and the +original object is returned. + +Args: + dtype (dtype or string): The desired type + non_blocking (bool): If ``True``, and the source is in pinned memory + and destination is on the GPU or vice versa, the copy is performed + asynchronously with respect to the host. Otherwise, the argument + has no effect. + **kwargs: For compatibility, may contain the key ``async`` in place of + the ``non_blocking`` argument. The ``async`` arg is deprecated. +""", +) + +add_docstr_all( + "type_as", + r""" +type_as(tensor) -> Tensor + +Returns this tensor cast to the type of the given tensor. + +This is a no-op if the tensor is already of the correct type. This is +equivalent to ``self.type(tensor.type())`` + +Args: + tensor (Tensor): the tensor which has the desired type +""", +) + +add_docstr_all( + "unfold", + r""" +unfold(dimension, size, step) -> Tensor + +Returns a view of the original tensor which contains all slices of size :attr:`size` from +:attr:`self` tensor in the dimension :attr:`dimension`. + +Step between two slices is given by :attr:`step`. + +If `sizedim` is the size of dimension :attr:`dimension` for :attr:`self`, the size of +dimension :attr:`dimension` in the returned tensor will be +`(sizedim - size) / step + 1`. + +An additional dimension of size :attr:`size` is appended in the returned tensor. + +Args: + dimension (int): dimension in which unfolding happens + size (int): the size of each slice that is unfolded + step (int): the step between each slice + +Example:: + + >>> x = torch.arange(1., 8) + >>> x + tensor([ 1., 2., 3., 4., 5., 6., 7.]) + >>> x.unfold(0, 2, 1) + tensor([[ 1., 2.], + [ 2., 3.], + [ 3., 4.], + [ 4., 5.], + [ 5., 6.], + [ 6., 7.]]) + >>> x.unfold(0, 2, 2) + tensor([[ 1., 2.], + [ 3., 4.], + [ 5., 6.]]) +""", +) + +add_docstr_all( + "uniform_", + r""" +uniform_(from=0, to=1, *, generator=None) -> Tensor + +Fills :attr:`self` tensor with numbers sampled from the continuous uniform +distribution: + +.. math:: + f(x) = \dfrac{1}{\text{to} - \text{from}} +""", +) + +add_docstr_all( + "unsqueeze", + r""" +unsqueeze(dim) -> Tensor + +See :func:`torch.unsqueeze` +""", +) + +add_docstr_all( + "unsqueeze_", + r""" +unsqueeze_(dim) -> Tensor + +In-place version of :meth:`~Tensor.unsqueeze` +""", +) + +add_docstr_all( + "var", + r""" +var(dim=None, *, correction=1, keepdim=False) -> Tensor + +See :func:`torch.var` +""", +) + +add_docstr_all( + "vdot", + r""" +vdot(other) -> Tensor + +See :func:`torch.vdot` +""", +) + +add_docstr_all( + "view", + r""" +view(*shape) -> Tensor + +Returns a new tensor with the same data as the :attr:`self` tensor but of a +different :attr:`shape`. + +The returned tensor shares the same data and must have the same number +of elements, but may have a different size. For a tensor to be viewed, the new +view size must be compatible with its original size and stride, i.e., each new +view dimension must either be a subspace of an original dimension, or only span +across original dimensions :math:`d, d+1, \dots, d+k` that satisfy the following +contiguity-like condition that :math:`\forall i = d, \dots, d+k-1`, + +.. math:: + + \text{stride}[i] = \text{stride}[i+1] \times \text{size}[i+1] + +Otherwise, it will not be possible to view :attr:`self` tensor as :attr:`shape` +without copying it (e.g., via :meth:`contiguous`). When it is unclear whether a +:meth:`view` can be performed, it is advisable to use :meth:`reshape`, which +returns a view if the shapes are compatible, and copies (equivalent to calling +:meth:`contiguous`) otherwise. + +Args: + shape (torch.Size or int...): the desired size + +Example:: + + >>> x = torch.randn(4, 4) + >>> x.size() + torch.Size([4, 4]) + >>> y = x.view(16) + >>> y.size() + torch.Size([16]) + >>> z = x.view(-1, 8) # the size -1 is inferred from other dimensions + >>> z.size() + torch.Size([2, 8]) + + >>> a = torch.randn(1, 2, 3, 4) + >>> a.size() + torch.Size([1, 2, 3, 4]) + >>> b = a.transpose(1, 2) # Swaps 2nd and 3rd dimension + >>> b.size() + torch.Size([1, 3, 2, 4]) + >>> c = a.view(1, 3, 2, 4) # Does not change tensor layout in memory + >>> c.size() + torch.Size([1, 3, 2, 4]) + >>> torch.equal(b, c) + False + + +.. method:: view(dtype) -> Tensor + :noindex: + +Returns a new tensor with the same data as the :attr:`self` tensor but of a +different :attr:`dtype`. + +If the element size of :attr:`dtype` is different than that of ``self.dtype``, +then the size of the last dimension of the output will be scaled +proportionally. For instance, if :attr:`dtype` element size is twice that of +``self.dtype``, then each pair of elements in the last dimension of +:attr:`self` will be combined, and the size of the last dimension of the output +will be half that of :attr:`self`. If :attr:`dtype` element size is half that +of ``self.dtype``, then each element in the last dimension of :attr:`self` will +be split in two, and the size of the last dimension of the output will be +double that of :attr:`self`. For this to be possible, the following conditions +must be true: + + * ``self.dim()`` must be greater than 0. + * ``self.stride(-1)`` must be 1. + +Additionally, if the element size of :attr:`dtype` is greater than that of +``self.dtype``, the following conditions must be true as well: + + * ``self.size(-1)`` must be divisible by the ratio between the element + sizes of the dtypes. + * ``self.storage_offset()`` must be divisible by the ratio between the + element sizes of the dtypes. + * The strides of all dimensions, except the last dimension, must be + divisible by the ratio between the element sizes of the dtypes. + +If any of the above conditions are not met, an error is thrown. + +.. warning:: + + This overload is not supported by TorchScript, and using it in a Torchscript + program will cause undefined behavior. + + +Args: + dtype (:class:`torch.dtype`): the desired dtype + +Example:: + + >>> x = torch.randn(4, 4) + >>> x + tensor([[ 0.9482, -0.0310, 1.4999, -0.5316], + [-0.1520, 0.7472, 0.5617, -0.8649], + [-2.4724, -0.0334, -0.2976, -0.8499], + [-0.2109, 1.9913, -0.9607, -0.6123]]) + >>> x.dtype + torch.float32 + + >>> y = x.view(torch.int32) + >>> y + tensor([[ 1064483442, -1124191867, 1069546515, -1089989247], + [-1105482831, 1061112040, 1057999968, -1084397505], + [-1071760287, -1123489973, -1097310419, -1084649136], + [-1101533110, 1073668768, -1082790149, -1088634448]], + dtype=torch.int32) + >>> y[0, 0] = 1000000000 + >>> x + tensor([[ 0.0047, -0.0310, 1.4999, -0.5316], + [-0.1520, 0.7472, 0.5617, -0.8649], + [-2.4724, -0.0334, -0.2976, -0.8499], + [-0.2109, 1.9913, -0.9607, -0.6123]]) + + >>> x.view(torch.cfloat) + tensor([[ 0.0047-0.0310j, 1.4999-0.5316j], + [-0.1520+0.7472j, 0.5617-0.8649j], + [-2.4724-0.0334j, -0.2976-0.8499j], + [-0.2109+1.9913j, -0.9607-0.6123j]]) + >>> x.view(torch.cfloat).size() + torch.Size([4, 2]) + + >>> x.view(torch.uint8) + tensor([[ 0, 202, 154, 59, 182, 243, 253, 188, 185, 252, 191, 63, 240, 22, + 8, 191], + [227, 165, 27, 190, 128, 72, 63, 63, 146, 203, 15, 63, 22, 106, + 93, 191], + [205, 59, 30, 192, 112, 206, 8, 189, 7, 95, 152, 190, 12, 147, + 89, 191], + [ 43, 246, 87, 190, 235, 226, 254, 63, 111, 240, 117, 191, 177, 191, + 28, 191]], dtype=torch.uint8) + >>> x.view(torch.uint8).size() + torch.Size([4, 16]) +""", +) + +add_docstr_all( + "view_as", + r""" +view_as(other) -> Tensor + +View this tensor as the same size as :attr:`other`. +``self.view_as(other)`` is equivalent to ``self.view(other.size())``. + +Please see :meth:`~Tensor.view` for more information about ``view``. + +Args: + other (:class:`torch.Tensor`): The result tensor has the same size + as :attr:`other`. +""", +) + +add_docstr_all( + "expand", + r""" +expand(*sizes) -> Tensor + +Returns a new view of the :attr:`self` tensor with singleton dimensions expanded +to a larger size. + +Passing -1 as the size for a dimension means not changing the size of +that dimension. + +Tensor can be also expanded to a larger number of dimensions, and the +new ones will be appended at the front. For the new dimensions, the +size cannot be set to -1. + +Expanding a tensor does not allocate new memory, but only creates a +new view on the existing tensor where a dimension of size one is +expanded to a larger size by setting the ``stride`` to 0. Any dimension +of size 1 can be expanded to an arbitrary value without allocating new +memory. + +Args: + *sizes (torch.Size or int...): the desired expanded size + +.. warning:: + + More than one element of an expanded tensor may refer to a single + memory location. As a result, in-place operations (especially ones that + are vectorized) may result in incorrect behavior. If you need to write + to the tensors, please clone them first. + +Example:: + + >>> x = torch.tensor([[1], [2], [3]]) + >>> x.size() + torch.Size([3, 1]) + >>> x.expand(3, 4) + tensor([[ 1, 1, 1, 1], + [ 2, 2, 2, 2], + [ 3, 3, 3, 3]]) + >>> x.expand(-1, 4) # -1 means not changing the size of that dimension + tensor([[ 1, 1, 1, 1], + [ 2, 2, 2, 2], + [ 3, 3, 3, 3]]) +""", +) + +add_docstr_all( + "expand_as", + r""" +expand_as(other) -> Tensor + +Expand this tensor to the same size as :attr:`other`. +``self.expand_as(other)`` is equivalent to ``self.expand(other.size())``. + +Please see :meth:`~Tensor.expand` for more information about ``expand``. + +Args: + other (:class:`torch.Tensor`): The result tensor has the same size + as :attr:`other`. +""", +) + +add_docstr_all( + "sum_to_size", + r""" +sum_to_size(*size) -> Tensor + +Sum ``this`` tensor to :attr:`size`. +:attr:`size` must be broadcastable to ``this`` tensor size. + +Args: + size (int...): a sequence of integers defining the shape of the output tensor. +""", +) + + +add_docstr_all( + "zero_", + r""" +zero_() -> Tensor + +Fills :attr:`self` tensor with zeros. +""", +) + +add_docstr_all( + "matmul", + r""" +matmul(tensor2) -> Tensor + +See :func:`torch.matmul` +""", +) + +add_docstr_all( + "chunk", + r""" +chunk(chunks, dim=0) -> List of Tensors + +See :func:`torch.chunk` +""", +) + +add_docstr_all( + "unsafe_chunk", + r""" +unsafe_chunk(chunks, dim=0) -> List of Tensors + +See :func:`torch.unsafe_chunk` +""", +) + +add_docstr_all( + "unsafe_split", + r""" +unsafe_split(split_size, dim=0) -> List of Tensors + +See :func:`torch.unsafe_split` +""", +) + +add_docstr_all( + "tensor_split", + r""" +tensor_split(indices_or_sections, dim=0) -> List of Tensors + +See :func:`torch.tensor_split` +""", +) + +add_docstr_all( + "hsplit", + r""" +hsplit(split_size_or_sections) -> List of Tensors + +See :func:`torch.hsplit` +""", +) + +add_docstr_all( + "vsplit", + r""" +vsplit(split_size_or_sections) -> List of Tensors + +See :func:`torch.vsplit` +""", +) + +add_docstr_all( + "dsplit", + r""" +dsplit(split_size_or_sections) -> List of Tensors + +See :func:`torch.dsplit` +""", +) + +add_docstr_all( + "stft", + r""" +stft(frame_length, hop, fft_size=None, return_onesided=True, window=None, + pad_end=0, align_to_window=None) -> Tensor + +See :func:`torch.stft` +""", +) + +add_docstr_all( + "istft", + r""" +istft(n_fft, hop_length=None, win_length=None, window=None, + center=True, normalized=False, onesided=True, length=None) -> Tensor + +See :func:`torch.istft` +""", +) + +add_docstr_all( + "det", + r""" +det() -> Tensor + +See :func:`torch.det` +""", +) + +add_docstr_all( + "where", + r""" +where(condition, y) -> Tensor + +``self.where(condition, y)`` is equivalent to ``torch.where(condition, self, y)``. +See :func:`torch.where` +""", +) + +add_docstr_all( + "logdet", + r""" +logdet() -> Tensor + +See :func:`torch.logdet` +""", +) + +add_docstr_all( + "slogdet", + r""" +slogdet() -> (Tensor, Tensor) + +See :func:`torch.slogdet` +""", +) + +add_docstr_all( + "unbind", + r""" +unbind(dim=0) -> seq + +See :func:`torch.unbind` +""", +) + +add_docstr_all( + "pin_memory", + r""" +pin_memory() -> Tensor + +Copies the tensor to pinned memory, if it's not already pinned. +By default, the device pinned memory on will be the current :ref:`accelerator`. +""", +) + +add_docstr_all( + "pinverse", + r""" +pinverse() -> Tensor + +See :func:`torch.pinverse` +""", +) + +add_docstr_all( + "index_add", + r""" +index_add(dim, index, source, *, alpha=1) -> Tensor + +Out-of-place version of :meth:`torch.Tensor.index_add_`. +""", +) + +add_docstr_all( + "index_copy", + r""" +index_copy(dim, index, tensor2) -> Tensor + +Out-of-place version of :meth:`torch.Tensor.index_copy_`. +""", +) + +add_docstr_all( + "index_fill", + r""" +index_fill(dim, index, value) -> Tensor + +Out-of-place version of :meth:`torch.Tensor.index_fill_`. +""", +) + +add_docstr_all( + "scatter", + r""" +scatter(dim, index, src) -> Tensor + +Out-of-place version of :meth:`torch.Tensor.scatter_` +""", +) + +add_docstr_all( + "scatter_add", + r""" +scatter_add(dim, index, src) -> Tensor + +Out-of-place version of :meth:`torch.Tensor.scatter_add_` +""", +) + +add_docstr_all( + "scatter_reduce", + r""" +scatter_reduce(dim, index, src, reduce, *, include_self=True) -> Tensor + +Out-of-place version of :meth:`torch.Tensor.scatter_reduce_` +""", +) + +add_docstr_all( + "masked_scatter", + r""" +masked_scatter(mask, tensor) -> Tensor + +Out-of-place version of :meth:`torch.Tensor.masked_scatter_` + +.. note:: + + The inputs :attr:`self` and :attr:`mask` + :ref:`broadcast `. + +Example: + + >>> self = torch.tensor([0, 0, 0, 0, 0]) + >>> mask = torch.tensor( + ... [[0, 0, 0, 1, 1], [1, 1, 0, 1, 1]], + ... dtype=torch.bool, + ... ) + >>> source = torch.tensor([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]) + >>> self.masked_scatter(mask, source) + tensor([[0, 0, 0, 0, 1], + [2, 3, 0, 4, 5]]) + +""", +) + +add_docstr_all( + "xlogy", + r""" +xlogy(other) -> Tensor + +See :func:`torch.xlogy` +""", +) + +add_docstr_all( + "xlogy_", + r""" +xlogy_(other) -> Tensor + +In-place version of :meth:`~Tensor.xlogy` +""", +) + +add_docstr_all( + "masked_fill", + r""" +masked_fill(mask, value) -> Tensor + +Out-of-place version of :meth:`torch.Tensor.masked_fill_` +""", +) + +add_docstr_all( + "grad", + r""" +This attribute is ``None`` by default and becomes a Tensor the first time a call to +:func:`backward` computes gradients for ``self``. +The attribute will then contain the gradients computed and future calls to +:func:`backward` will accumulate (add) gradients into it. +""", +) + +add_docstr_all( + "grad_dtype", + r""" +The allowed dtype of :attr:``grad`` for this tensor. + +:attr:``grad_dtype`` can be set to a specific dtype or ``None``. By default, +``t.grad_dtype == t.dtype``. When not None, the autograd engine casts +incoming gradients to this dtype. This attribute is only accessible and +settable for leaf tensors. + +.. warning:: + Use with caution. Diverging the dtypes of a tensor and its gradient may + break downstream systems that assume they match. + +Example:: + + >>> x = torch.tensor([1.0, 2.0], requires_grad=True) + >>> x.grad_dtype + torch.float32 + + >>> x.grad_dtype = torch.float16 + >>> x.grad_dtype + torch.float16 + + >>> # Allow any gradient dtype + >>> x.grad_dtype = None + >>> x.grad_dtype +""", +) + +add_docstr_all( + "retain_grad", + r""" +retain_grad() -> None + +Enables this Tensor to have their :attr:`grad` populated during +:func:`backward`. This is a no-op for leaf tensors. +""", +) + +add_docstr_all( + "retains_grad", + r""" +Is ``True`` if this Tensor is non-leaf and its :attr:`grad` is enabled to be +populated during :func:`backward`, ``False`` otherwise. +""", +) + +add_docstr_all( + "requires_grad", + r""" +Is ``True`` if gradients need to be computed for this Tensor, ``False`` otherwise. + +.. note:: + + The fact that gradients need to be computed for a Tensor do not mean that the :attr:`grad` + attribute will be populated, see :attr:`is_leaf` for more details. + +""", +) + +add_docstr_all( + "is_leaf", + r""" +All Tensors that have :attr:`requires_grad` which is ``False`` will be leaf Tensors by convention. + +For Tensors that have :attr:`requires_grad` which is ``True``, they will be leaf Tensors if they were +created by the user. This means that they are not the result of an operation and so +:attr:`grad_fn` is None. + +Only leaf Tensors will have their :attr:`grad` populated during a call to :func:`backward`. +To get :attr:`grad` populated for non-leaf Tensors, you can use :func:`retain_grad`. + +Example:: + + >>> a = torch.rand(10, requires_grad=True) + >>> a.is_leaf + True + >>> b = torch.rand(10, requires_grad=True).cuda() + >>> b.is_leaf + False + # b was created by the operation that cast a cpu Tensor into a cuda Tensor + >>> c = torch.rand(10, requires_grad=True) + 2 + >>> c.is_leaf + False + # c was created by the addition operation + >>> d = torch.rand(10).cuda() + >>> d.is_leaf + True + # d does not require gradients and so has no operation creating it (that is tracked by the autograd engine) + >>> e = torch.rand(10).cuda().requires_grad_() + >>> e.is_leaf + True + # e requires gradients and has no operations creating it + >>> f = torch.rand(10, requires_grad=True, device="cuda") + >>> f.is_leaf + True + # f requires grad, has no operation creating it + + +""", +) + +add_docstr_all( + "names", + r""" +Stores names for each of this tensor's dimensions. + +``names[idx]`` corresponds to the name of tensor dimension ``idx``. +Names are either a string if the dimension is named or ``None`` if the +dimension is unnamed. + +Dimension names may contain characters or underscore. Furthermore, a dimension +name must be a valid Python variable name (i.e., does not start with underscore). + +Tensors may not have two named dimensions with the same name. + +.. warning:: + The named tensor API is experimental and subject to change. + +""", +) + +add_docstr_all( + "is_cuda", + r""" +Is ``True`` if the Tensor is stored on the GPU, ``False`` otherwise. +""", +) + +add_docstr_all( + "is_cpu", + r""" +Is ``True`` if the Tensor is stored on the CPU, ``False`` otherwise. +""", +) + +add_docstr_all( + "is_xla", + r""" +Is ``True`` if the Tensor is stored on an XLA device, ``False`` otherwise. +""", +) + +add_docstr_all( + "is_ipu", + r""" +Is ``True`` if the Tensor is stored on the IPU, ``False`` otherwise. +""", +) + +add_docstr_all( + "is_xpu", + r""" +Is ``True`` if the Tensor is stored on the XPU, ``False`` otherwise. +""", +) + +add_docstr_all( + "is_quantized", + r""" +Is ``True`` if the Tensor is quantized, ``False`` otherwise. +""", +) + +add_docstr_all( + "is_meta", + r""" +Is ``True`` if the Tensor is a meta tensor, ``False`` otherwise. Meta tensors +are like normal tensors, but they carry no data. +""", +) + +add_docstr_all( + "is_mps", + r""" +Is ``True`` if the Tensor is stored on the MPS device, ``False`` otherwise. +""", +) + +add_docstr_all( + "is_sparse", + r""" +Is ``True`` if the Tensor uses sparse COO storage layout, ``False`` otherwise. +""", +) + +add_docstr_all( + "is_sparse_csr", + r""" +Is ``True`` if the Tensor uses sparse CSR storage layout, ``False`` otherwise. +""", +) + +add_docstr_all( + "device", + r""" +Is the :class:`torch.device` where this Tensor is. +""", +) + +add_docstr_all( + "ndim", + r""" +Alias for :meth:`~Tensor.dim()` +""", +) + +add_docstr_all( + "itemsize", + r""" +Alias for :meth:`~Tensor.element_size()` +""", +) + +add_docstr_all( + "nbytes", + r""" +Returns the number of bytes consumed by the "view" of elements of the Tensor +if the Tensor does not use sparse storage layout. +Defined to be :meth:`~Tensor.numel()` * :meth:`~Tensor.element_size()` +""", +) + +add_docstr_all( + "T", + r""" +Returns a view of this tensor with its dimensions reversed. + +If ``n`` is the number of dimensions in ``x``, +``x.T`` is equivalent to ``x.permute(n-1, n-2, ..., 0)``. + +.. warning:: + The use of :func:`Tensor.T` on tensors of dimension other than 2 to reverse their shape + is deprecated and it will throw an error in a future release. Consider :attr:`~.Tensor.mT` + to transpose batches of matrices or `x.permute(*torch.arange(x.ndim - 1, -1, -1))` to reverse + the dimensions of a tensor. +""", +) + +add_docstr_all( + "H", + r""" +Returns a view of a matrix (2-D tensor) conjugated and transposed. + +``x.H`` is equivalent to ``x.transpose(0, 1).conj()`` for complex matrices and +``x.transpose(0, 1)`` for real matrices. + +.. seealso:: + + :attr:`~.Tensor.mH`: An attribute that also works on batches of matrices. +""", +) + +add_docstr_all( + "mT", + r""" +Returns a view of this tensor with the last two dimensions transposed. + +``x.mT`` is equivalent to ``x.transpose(-2, -1)``. +""", +) + +add_docstr_all( + "mH", + r""" +Accessing this property is equivalent to calling :func:`adjoint`. +""", +) + +add_docstr_all( + "adjoint", + r""" +adjoint() -> Tensor + +Alias for :func:`adjoint` +""", +) + +add_docstr_all( + "real", + r""" +Returns a new tensor containing real values of the :attr:`self` tensor for a complex-valued input tensor. +The returned tensor and :attr:`self` share the same underlying storage. + +Returns :attr:`self` if :attr:`self` is a real-valued tensor tensor. + +Example:: + + >>> x=torch.randn(4, dtype=torch.cfloat) + >>> x + tensor([(0.3100+0.3553j), (-0.5445-0.7896j), (-1.6492-0.0633j), (-0.0638-0.8119j)]) + >>> x.real + tensor([ 0.3100, -0.5445, -1.6492, -0.0638]) + +""", +) + +add_docstr_all( + "imag", + r""" +Returns a new tensor containing imaginary values of the :attr:`self` tensor. +The returned tensor and :attr:`self` share the same underlying storage. + +.. warning:: + :func:`imag` is only supported for tensors with complex dtypes. + +Example:: + + >>> x=torch.randn(4, dtype=torch.cfloat) + >>> x + tensor([(0.3100+0.3553j), (-0.5445-0.7896j), (-1.6492-0.0633j), (-0.0638-0.8119j)]) + >>> x.imag + tensor([ 0.3553, -0.7896, -0.0633, -0.8119]) + +""", +) + +add_docstr_all( + "as_subclass", + r""" +as_subclass(cls) -> Tensor + +Makes a ``cls`` instance with the same data pointer as ``self``. Changes +in the output mirror changes in ``self``, and the output stays attached +to the autograd graph. ``cls`` must be a subclass of ``Tensor``. +""", +) + +add_docstr_all( + "crow_indices", + r""" +crow_indices() -> IntTensor + +Returns the tensor containing the compressed row indices of the :attr:`self` +tensor when :attr:`self` is a sparse CSR tensor of layout ``sparse_csr``. +The ``crow_indices`` tensor is strictly of shape (:attr:`self`.size(0) + 1) +and of type ``int32`` or ``int64``. When using MKL routines such as sparse +matrix multiplication, it is necessary to use ``int32`` indexing in order +to avoid downcasting and potentially losing information. + +Example:: + + >>> csr = torch.eye(5,5).to_sparse_csr() + >>> csr.crow_indices() + tensor([0, 1, 2, 3, 4, 5], dtype=torch.int32) + +""", +) + +add_docstr_all( + "col_indices", + r""" +col_indices() -> IntTensor + +Returns the tensor containing the column indices of the :attr:`self` +tensor when :attr:`self` is a sparse CSR tensor of layout ``sparse_csr``. +The ``col_indices`` tensor is strictly of shape (:attr:`self`.nnz()) +and of type ``int32`` or ``int64``. When using MKL routines such as sparse +matrix multiplication, it is necessary to use ``int32`` indexing in order +to avoid downcasting and potentially losing information. + +Example:: + + >>> csr = torch.eye(5,5).to_sparse_csr() + >>> csr.col_indices() + tensor([0, 1, 2, 3, 4], dtype=torch.int32) + +""", +) + +add_docstr_all( + "to_padded_tensor", + r""" +to_padded_tensor(padding, output_size=None) -> Tensor +See :func:`to_padded_tensor` +""", +) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_tensor_str.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_tensor_str.py new file mode 100644 index 0000000000000000000000000000000000000000..46af7388293127e3a8dcc9849049a919dfb8f770 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_tensor_str.py @@ -0,0 +1,724 @@ +# mypy: allow-untyped-defs +import contextlib +import dataclasses +import math +import textwrap +from typing import Any + +import torch +from torch import inf + + +@dataclasses.dataclass +class __PrinterOptions: + precision: int = 4 + threshold: float = 1000 + edgeitems: int = 3 + linewidth: int = 80 + sci_mode: bool | None = None + + +PRINT_OPTS = __PrinterOptions() + + +# We could use **kwargs, but this will give better docs +def set_printoptions( + precision=None, + threshold=None, + edgeitems=None, + linewidth=None, + profile=None, + sci_mode=None, +): + r"""Set options for printing. Items shamelessly taken from NumPy + + Args: + precision: Number of digits of precision for floating point output + (default = 4). + threshold: Total number of array elements which trigger summarization + rather than full `repr` (default = 1000). + edgeitems: Number of array items in summary at beginning and end of + each dimension (default = 3). + linewidth: The number of characters per line for the purpose of + inserting line breaks (default = 80). Thresholded matrices will + ignore this parameter. + profile: Sane defaults for pretty printing. Can override with any of + the above options. (any one of `default`, `short`, `full`) + sci_mode: Enable (True) or disable (False) scientific notation. If + None (default) is specified, the value is defined by + `torch._tensor_str._Formatter`. This value is automatically chosen + by the framework. + + Example:: + + >>> # Limit the precision of elements + >>> torch.set_printoptions(precision=2) + >>> torch.tensor([1.12345]) + tensor([1.12]) + >>> # Limit the number of elements shown + >>> torch.set_printoptions(threshold=5) + >>> torch.arange(10) + tensor([0, 1, 2, ..., 7, 8, 9]) + >>> # Restore defaults + >>> torch.set_printoptions(profile='default') + >>> torch.tensor([1.12345]) + tensor([1.1235]) + >>> torch.arange(10) + tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) + + """ + if profile is not None: + if profile == "default": + PRINT_OPTS.precision = 4 + PRINT_OPTS.threshold = 1000 + PRINT_OPTS.edgeitems = 3 + PRINT_OPTS.linewidth = 80 + elif profile == "short": + PRINT_OPTS.precision = 2 + PRINT_OPTS.threshold = 1000 + PRINT_OPTS.edgeitems = 2 + PRINT_OPTS.linewidth = 80 + elif profile == "full": + PRINT_OPTS.precision = 4 + PRINT_OPTS.threshold = inf + PRINT_OPTS.edgeitems = 3 + PRINT_OPTS.linewidth = 80 + + if precision is not None: + PRINT_OPTS.precision = precision + if threshold is not None: + PRINT_OPTS.threshold = threshold + if edgeitems is not None: + PRINT_OPTS.edgeitems = edgeitems + if linewidth is not None: + PRINT_OPTS.linewidth = linewidth + PRINT_OPTS.sci_mode = sci_mode + + +def get_printoptions() -> dict[str, Any]: + r"""Gets the current options for printing, as a dictionary that + can be passed as ``**kwargs`` to set_printoptions(). + """ + return dataclasses.asdict(PRINT_OPTS) + + +@contextlib.contextmanager +def printoptions(**kwargs): + r"""Context manager that temporarily changes the print options. Accepted + arguments are same as :func:`set_printoptions`.""" + old_kwargs = get_printoptions() + set_printoptions(**kwargs) + try: + yield + finally: + set_printoptions(**old_kwargs) + + +def tensor_totype(t): + dtype = ( + torch.float + if ( + t.is_mps + or (t.is_xpu and not torch.xpu.get_device_properties(t.device).has_fp64) + or t.is_maia + ) + else torch.double + ) + return t.to(dtype=dtype) + + +class _Formatter: + def __init__(self, tensor): + self.floating_dtype = tensor.dtype.is_floating_point + self.int_mode = True + self.sci_mode = False + self.max_width = 1 + + with torch.no_grad(): + tensor_view = tensor.reshape(-1) + + if not self.floating_dtype: + for value in tensor_view: + value_str = f"{value}" + self.max_width = max(self.max_width, len(value_str)) + + else: + if tensor.dtype == torch.float4_e2m1fn_x2: # type: ignore[attr-defined] + # torch.float4_e2m1fn_x2 is special and does not support the casts necessary + # to print it, we choose to display the uint8 representation here for + # convenience of being able to print a tensor. + # TODO(#146647): extend this to other dtypes without casts defined, such + # as the bits, uint1..7 and int1..7 dtypes. + tensor_view = tensor_view.view(torch.uint8) + + nonzero_finite_vals = torch.masked_select( + tensor_view, torch.isfinite(tensor_view) & tensor_view.ne(0) + ) + + if nonzero_finite_vals.numel() == 0: + # no valid number, do nothing + return + + if tensor.dtype == torch.float8_e8m0fnu: # type: ignore[attr-defined] + # float8_e8m0fnu is special and does not define arithmetic ops, + # and printing code further in this file assumes the existence + # of various arithmetic ops to figure out what to print. We hack + # and convert to float here to make printing work correctly. + # TODO(#113663): also add the other float8 dtypes here after arithmetic + # support for them is removed + nonzero_finite_vals = nonzero_finite_vals.float() + + # Convert to double (or float) for easy calculation. HalfTensor overflows with 1e8, and there's no div() on CPU. + nonzero_finite_abs = tensor_totype(nonzero_finite_vals.abs()) + nonzero_finite_min = tensor_totype(nonzero_finite_abs.min()) + nonzero_finite_max = tensor_totype(nonzero_finite_abs.max()) + + for value in nonzero_finite_vals: + if value != torch.ceil(value): + self.int_mode = False + break + + self.sci_mode = ( + nonzero_finite_max / nonzero_finite_min > 1000.0 + or nonzero_finite_max > 1.0e8 + or nonzero_finite_min < 1.0e-4 + if PRINT_OPTS.sci_mode is None + else PRINT_OPTS.sci_mode + ) + + if self.int_mode: + # in int_mode for floats, all numbers are integers, and we append a decimal to nonfinites + # to indicate that the tensor is of floating type. add 1 to the len to account for this. + if self.sci_mode: + for value in nonzero_finite_vals: + value_str = f"{{:.{PRINT_OPTS.precision}e}}".format(value) + self.max_width = max(self.max_width, len(value_str)) + else: + for value in nonzero_finite_vals: + value_str = f"{value:.0f}" + self.max_width = max(self.max_width, len(value_str) + 1) + else: + # Check if scientific representation should be used. + if self.sci_mode: + for value in nonzero_finite_vals: + value_str = f"{{:.{PRINT_OPTS.precision}e}}".format(value) + self.max_width = max(self.max_width, len(value_str)) + else: + for value in nonzero_finite_vals: + value_str = f"{{:.{PRINT_OPTS.precision}f}}".format(value) + self.max_width = max(self.max_width, len(value_str)) + + def width(self): + return self.max_width + + def format(self, value): + if self.floating_dtype: + if self.sci_mode: + ret = f"{{:{self.max_width}.{PRINT_OPTS.precision}e}}".format(value) + elif self.int_mode: + ret = f"{value:.0f}" + if not (math.isinf(value) or math.isnan(value)): + ret += "." + else: + ret = f"{{:.{PRINT_OPTS.precision}f}}".format(value) + else: + ret = f"{value}" + return (self.max_width - len(ret)) * " " + ret + + +def _scalar_str(self, formatter1, formatter2=None): + if formatter2 is not None: + real_str = _scalar_str(self.real, formatter1) + imag_str = (_scalar_str(self.imag, formatter2) + "j").lstrip() + # handles negative numbers, +0.0, -0.0 + if imag_str[0] == "+" or imag_str[0] == "-": + return real_str + imag_str + else: + return real_str + "+" + imag_str + else: + return formatter1.format(self.item()) + + +def _vector_str(self, indent, summarize, formatter1, formatter2=None): + # length includes spaces and comma between elements + element_length = formatter1.width() + 2 + if formatter2 is not None: + # width for imag_formatter + an extra j for complex + element_length += formatter2.width() + 1 + + elements_per_line = max( + 1, math.floor((PRINT_OPTS.linewidth - indent) / (element_length)) + ) + + def _val_formatter(val, formatter1=formatter1, formatter2=formatter2): + if formatter2 is not None: + real_str = formatter1.format(val.real) + imag_str = (formatter2.format(val.imag) + "j").lstrip() + # handles negative numbers, +0.0, -0.0 + if imag_str[0] == "+" or imag_str[0] == "-": + return real_str + imag_str + else: + return real_str + "+" + imag_str + else: + return formatter1.format(val) + + if self.dtype == torch.float4_e2m1fn_x2: # type: ignore[attr-defined] + # torch.float4_e2m1fn_x2 is special and does not support the casts necessary + # to print it, we choose to display the uint8 representation here for + # convenience of being able to print a tensor. + # TODO(#146647): extend this to other dtypes without casts defined, such + # as the bits, uint1..7 and int1..7 dtypes. + self = self.view(torch.uint8) + + if summarize and not PRINT_OPTS.edgeitems: + # Deal with edge case that negative zero is zero + data = ["..."] + elif summarize and self.size(0) > 2 * PRINT_OPTS.edgeitems: + data = ( + [_val_formatter(val) for val in self[: PRINT_OPTS.edgeitems].tolist()] + + [" ..."] + + [_val_formatter(val) for val in self[-PRINT_OPTS.edgeitems :].tolist()] + ) + else: + data = [_val_formatter(val) for val in self.tolist()] + + data_lines = [ + data[i : i + elements_per_line] for i in range(0, len(data), elements_per_line) + ] + lines = [", ".join(line) for line in data_lines] + return "[" + ("," + "\n" + " " * (indent + 1)).join(lines) + "]" + + +# formatter2 is only used for printing complex tensors. +# For complex tensors, formatter1 and formatter2 are the formatters for tensor.real +# and tensor.imag respesectively +def _tensor_str_with_formatter(self, indent, summarize, formatter1, formatter2=None): + dim = self.dim() + + if dim == 0: + return _scalar_str(self, formatter1, formatter2) + + if dim == 1: + return _vector_str(self, indent, summarize, formatter1, formatter2) + + if summarize and self.size(0) > 2 * PRINT_OPTS.edgeitems: + slices = ( + [ + _tensor_str_with_formatter( + self[i], indent + 1, summarize, formatter1, formatter2 + ) + for i in range(PRINT_OPTS.edgeitems) + ] + + ["..."] + + [ + _tensor_str_with_formatter( + self[i], indent + 1, summarize, formatter1, formatter2 + ) + for i in range(len(self) - PRINT_OPTS.edgeitems, len(self)) + ] + ) + else: + slices = [ + _tensor_str_with_formatter( + self[i], indent + 1, summarize, formatter1, formatter2 + ) + for i in range(self.size(0)) + ] + + tensor_str = ("," + "\n" * (dim - 1) + " " * (indent + 1)).join(slices) + return "[" + tensor_str + "]" + + +def _tensor_str(self, indent): + if self.numel() == 0: + return "[]" + + if self.has_names(): + # There are two main codepaths (possibly more) that tensor printing goes through: + # - tensor data can fit comfortably on screen + # - tensor data needs to be summarized + # Some of the codepaths don't fully support named tensors, so we send in + # an unnamed tensor to the formatting code as a workaround. + self = self.rename(None) + + summarize = self.numel() > PRINT_OPTS.threshold + + if self._is_zerotensor(): + self = self.clone() + + # handle the negative bit + if self.is_neg(): + self = self.resolve_neg() + + # TODO: Remove me when `masked_select` is implemented for FP8 + if self.dtype in [ + torch.float8_e5m2, + torch.float8_e5m2fnuz, + torch.float8_e4m3fn, + torch.float8_e4m3fnuz, + ]: + self = self.half() + + if self.dtype.is_complex: + # handle the conjugate bit + self = self.resolve_conj() + real_formatter = _Formatter( + get_summarized_data(self.real) if summarize else self.real + ) + imag_formatter = _Formatter( + get_summarized_data(self.imag) if summarize else self.imag + ) + return _tensor_str_with_formatter( + self, indent, summarize, real_formatter, imag_formatter + ) + else: + formatter = _Formatter(get_summarized_data(self) if summarize else self) + return _tensor_str_with_formatter(self, indent, summarize, formatter) + + +def _add_suffixes(tensor_str, suffixes, indent, force_newline): + tensor_strs = [tensor_str] + last_line_len = len(tensor_str) - tensor_str.rfind("\n") + 1 + for suffix in suffixes: + suffix_len = len(suffix) + if force_newline or last_line_len + suffix_len + 2 > PRINT_OPTS.linewidth: + tensor_strs.append(",\n" + " " * indent + suffix) + last_line_len = indent + suffix_len + force_newline = False + else: + tensor_strs.append(", " + suffix) + last_line_len += suffix_len + 2 + tensor_strs.append(")") + return "".join(tensor_strs) + + +def get_summarized_data(self): + dim = self.dim() + if dim == 0: + return self + if dim == 1: + if self.size(0) > 2 * PRINT_OPTS.edgeitems: + return torch.cat( + (self[: PRINT_OPTS.edgeitems], self[-PRINT_OPTS.edgeitems :]) + ) + else: + return self + if not PRINT_OPTS.edgeitems: + return self.new_empty([0] * self.dim()) + elif self.size(0) > 2 * PRINT_OPTS.edgeitems: + start = [self[i] for i in range(PRINT_OPTS.edgeitems)] + end = [self[i] for i in range(len(self) - PRINT_OPTS.edgeitems, len(self))] + return torch.stack([get_summarized_data(x) for x in (start + end)]) + else: + return torch.stack([get_summarized_data(x) for x in self]) + + +def _str_intern(inp, *, tensor_contents=None): + if torch._C._functorch.is_functorch_wrapped_tensor(inp): + return _functorch_wrapper_str_intern(inp, tensor_contents=tensor_contents) + is_plain_tensor = type(inp) is torch.Tensor or type(inp) is torch.nn.Parameter + if inp.is_nested: + prefix = "nested_tensor(" + elif is_plain_tensor: + prefix = "tensor(" + else: + prefix = f"{type(inp).__name__}(" + indent = len(prefix) + suffixes = [] + custom_contents_provided = tensor_contents is not None + if custom_contents_provided: + tensor_str = tensor_contents + + # This is used to extract the primal value and thus disable the forward AD + # within this function. + # TODO(albanD) This needs to be updated when more than one level is supported + self, tangent = torch.autograd.forward_ad.unpack_dual(inp) + + # Note [Print tensor device]: + # A general logic here is we only print device when it doesn't match + # the device specified in default tensor type. + # Currently torch.set_default_tensor_type() only supports CPU/CUDA, thus + # torch._C._get_default_device() only returns either cpu or cuda. + # In other cases, we don't have a way to set them as default yet, + # and we should always print out device for them. + if ( + self.device.type != torch._C._get_default_device() + or ( + self.device.type == "cuda" + and torch.cuda.current_device() != self.device.index + ) + or (self.device.type == "mps") + ): + suffixes.append("device='" + str(self.device) + "'") + + # Tensor printing performs tensor operations like slice, indexing, etc to make it in a + # representable format. These operations on ipu/xla/lazy/mtia tensor results in compilations. Hence, + # to avoid compilations, copying the tensor to cpu before printing. + if self.device.type in ["xla", "lazy", "ipu", "mtia"]: + self = self.to("cpu") + + # TODO: add an API to map real -> complex dtypes + _default_complex_dtype = ( + torch.cdouble if torch.get_default_dtype() == torch.double else torch.cfloat + ) + has_default_dtype = self.dtype in ( + torch.get_default_dtype(), + _default_complex_dtype, + torch.int64, + torch.bool, + ) + if self.is_sparse: + suffixes.append("size=" + str(tuple(self.shape))) + from torch._subclasses.fake_tensor import FakeTensor + + is_meta = self.is_meta or isinstance(self, FakeTensor) + if not is_meta: + suffixes.append("nnz=" + str(self._nnz())) + if not has_default_dtype: + suffixes.append("dtype=" + str(self.dtype)) + if not custom_contents_provided: + indices_prefix = "indices=tensor(" + indices = self._indices().detach() + if is_meta: + indices_str = "..." + else: + indices_str = _tensor_str(indices, indent + len(indices_prefix)) + if is_meta or indices.numel() == 0: + indices_str += ", size=" + str(tuple(indices.shape)) + values_prefix = "values=tensor(" + values = self._values().detach() + if is_meta: + values_str = "..." + else: + values_str = _tensor_str(values, indent + len(values_prefix)) + if is_meta or values.numel() == 0: + values_str += ", size=" + str(tuple(values.shape)) + tensor_str = ( + indices_prefix + + indices_str + + "),\n" + + " " * indent + + values_prefix + + values_str + + ")" + ) + elif self.layout in { + torch.sparse_csr, + torch.sparse_csc, + torch.sparse_bsr, + torch.sparse_bsc, + }: + from torch._subclasses.fake_tensor import FakeTensor + + suffixes.append("size=" + str(tuple(self.shape))) + is_meta = self.is_meta or isinstance(self, FakeTensor) + if not is_meta: + suffixes.append("nnz=" + str(self._nnz())) + if not has_default_dtype: + suffixes.append("dtype=" + str(self.dtype)) + if not custom_contents_provided: + compressed_indices_method, plain_indices_method = { + torch.sparse_csr: (torch.Tensor.crow_indices, torch.Tensor.col_indices), + torch.sparse_csc: (torch.Tensor.ccol_indices, torch.Tensor.row_indices), + torch.sparse_bsr: (torch.Tensor.crow_indices, torch.Tensor.col_indices), + torch.sparse_bsc: (torch.Tensor.ccol_indices, torch.Tensor.row_indices), + }[self.layout] + if self.layout in {torch.sparse_csr, torch.sparse_bsr}: + cdimname, pdimname = "row", "column" + else: + cdimname, pdimname = "column", "row" + compressed_indices_prefix = f"c{cdimname[:3]}_indices=tensor(" + compressed_indices = compressed_indices_method(self).detach() + if is_meta: + compressed_indices_str = "..." + else: + compressed_indices_str = _tensor_str( + compressed_indices, indent + len(compressed_indices_prefix) + ) + if compressed_indices.numel() == 0 or is_meta: + compressed_indices_str += ", size=" + str( + tuple(compressed_indices.shape) + ) + plain_indices_prefix = f"{pdimname[:3]}_indices=tensor(" + plain_indices = plain_indices_method(self).detach() + if is_meta: + plain_indices_str = "..." + else: + plain_indices_str = _tensor_str( + plain_indices, indent + len(plain_indices_prefix) + ) + if plain_indices.numel() == 0 or is_meta: + plain_indices_str += ", size=" + str(tuple(plain_indices.shape)) + values_prefix = "values=tensor(" + values = self.values().detach() + if is_meta: + values_str = "..." + else: + values_str = _tensor_str(values, indent + len(values_prefix)) + if values.numel() == 0 or is_meta: + values_str += ", size=" + str(tuple(values.shape)) + tensor_str = ( + compressed_indices_prefix + + compressed_indices_str + + "),\n" + + " " * indent + + plain_indices_prefix + + plain_indices_str + + "),\n" + + " " * indent + + values_prefix + + values_str + + ")" + ) + elif self.is_quantized: + suffixes.append("size=" + str(tuple(self.shape))) + if not has_default_dtype: + suffixes.append("dtype=" + str(self.dtype)) + suffixes.append("quantization_scheme=" + str(self.qscheme())) + if ( + self.qscheme() == torch.per_tensor_affine + or self.qscheme() == torch.per_tensor_symmetric + ): + suffixes.append("scale=" + str(self.q_scale())) + suffixes.append("zero_point=" + str(self.q_zero_point())) + elif ( + self.qscheme() == torch.per_channel_affine + or self.qscheme() == torch.per_channel_symmetric + or self.qscheme() == torch.per_channel_affine_float_qparams + ): + suffixes.append("scale=" + str(self.q_per_channel_scales())) + suffixes.append("zero_point=" + str(self.q_per_channel_zero_points())) + suffixes.append("axis=" + str(self.q_per_channel_axis())) + if not custom_contents_provided: + tensor_str = _tensor_str(self.dequantize(), indent) + elif self.is_nested: + if not custom_contents_provided: + + def indented_str(s, indent): + return "\n".join(f" {line}" for line in s.split("\n")) + + strs = ",\n".join( + indented_str(str(t), indent + 1) + for t in torch.ops.aten.unbind.int(self, 0) + ) + tensor_str = f"[\n{strs}\n]" + elif torch._is_functional_tensor(self): + prefix = "_to_functional_tensor(" + tensor_str = repr(torch._from_functional_tensor(self)) + else: + # Circular import problem, so we import it here + from torch._subclasses.fake_tensor import FakeTensor + + if self.is_meta or isinstance(self, FakeTensor): + suffixes.append("size=" + str(tuple(self.shape))) + if self.dtype != torch.get_default_dtype(): + suffixes.append("dtype=" + str(self.dtype)) + # TODO: This implies that ellipses is valid syntax for allocating + # a meta tensor or FakeTensor, which it could be, but it isn't right now + if not custom_contents_provided: + tensor_str = "..." + else: + if self.numel() == 0 and not self.is_sparse: + # Explicitly print the shape if it is not (0,), to match NumPy behavior + if self.dim() != 1: + suffixes.append("size=" + str(tuple(self.shape))) + + # In an empty tensor, there are no elements to infer if the dtype + # should be int64, so it must be shown explicitly. + if self.dtype != torch.get_default_dtype(): + suffixes.append("dtype=" + str(self.dtype)) + if not custom_contents_provided: + tensor_str = "[]" + else: + if not PRINT_OPTS.edgeitems: + suffixes.append("size=" + str(tuple(self.shape))) + + if not has_default_dtype: + suffixes.append("dtype=" + str(self.dtype)) + + if not custom_contents_provided: + if self.layout != torch.strided: + tensor_str = _tensor_str(self.to_dense(), indent) + else: + tensor_str = _tensor_str(self, indent) + + if self.layout != torch.strided: + suffixes.append("layout=" + str(self.layout)) + + # Use inp here to get the original grad_fn and not the one generated by the forward grad + # unpacking. + grad_fn_name = None + try: + grad_fn = inp.grad_fn + except RuntimeError: + # Accessing the grad_fn calls rebasing logic which would cause an error + # if that tensor is a view created in no-grad mode modified in-place in + # no-grad mode. See: https://github.com/pytorch/pytorch/issues/99968 + grad_fn_name = "Invalid" + + if grad_fn_name is None and grad_fn is not None: # type: ignore[possibly-undefined] + # pyrefly: ignore [unbound-name] + grad_fn_name = type(grad_fn).__name__ + if grad_fn_name == "CppFunction": + # pyrefly: ignore [unbound-name] + grad_fn_name = grad_fn.name().rsplit("::", 1)[-1] + + if grad_fn_name is not None: + suffixes.append(f"grad_fn=<{grad_fn_name}>") + elif inp.requires_grad: + suffixes.append("requires_grad=True") + + if self.has_names(): + suffixes.append(f"names={self.names}") + + if tangent is not None: + suffixes.append(f"tangent={tangent}") + + string_repr = _add_suffixes( + prefix + tensor_str, # type: ignore[possibly-undefined] + suffixes, + indent, + force_newline=self.is_sparse, + ) + + # Check if this instance is flagged as a parameter and change the repr accordingly. + # Unfortunately, this function has to be aware of this detail. + # NB: This is currently skipped for plain tensor parameters to maintain BC. In the future, + # this should be done for those as well to produce a valid repr. + if isinstance(self, torch.nn.Parameter) and not is_plain_tensor: + string_repr = f"Parameter({string_repr})" + + return string_repr + + +def _functorch_wrapper_str_intern(tensor, *, tensor_contents=None): + level = torch._C._functorch.maybe_get_level(tensor) + assert level != -1 + + if torch._C._functorch.is_functionaltensor(tensor): + # Since we're unwrapping the FunctionalTensorWrapper, we need to make sure + # that it's up to date first + torch._sync(tensor) + + value = torch._C._functorch.get_unwrapped(tensor) + value_repr = repr(value) + + indented_value_repr = textwrap.indent(value_repr, " " * 4) + if torch._C._functorch.is_batchedtensor(tensor): + bdim = torch._C._functorch.maybe_get_bdim(tensor) + assert bdim != -1 + return ( + f"BatchedTensor(lvl={level}, bdim={bdim}, value=\n{indented_value_repr}\n)" + ) + if torch._C._functorch.is_gradtrackingtensor(tensor): + return f"GradTrackingTensor(lvl={level}, value=\n{indented_value_repr}\n)" + if torch._C._functorch.is_functionaltensor(tensor): + return f"FunctionalTensor(lvl={level}, value=\\\n{value_repr})" + + raise ValueError("We don't know how to print this, please file us an issue") + + +def _str(self, *, tensor_contents=None): + with torch.no_grad(), torch.utils._python_dispatch._disable_current_modes(): + guard = torch._C._DisableFuncTorch() # noqa: F841 + return _str_intern(self, tensor_contents=tensor_contents) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_thread_safe_fork.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_thread_safe_fork.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_torch_docs.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_torch_docs.py new file mode 100644 index 0000000000000000000000000000000000000000..144d433e9a026d16af54e294e510b242eda478c7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_torch_docs.py @@ -0,0 +1,14392 @@ +# mypy: allow-untyped-defs +"""Adds docstrings to functions defined in the torch._C module.""" + +import re + +import torch._C +from torch._C import _add_docstr as add_docstr + + +def parse_kwargs(desc): + r"""Map a description of args to a dictionary of {argname: description}. + + Input: + (' weight (Tensor): a weight tensor\n' + + ' Some optional description') + Output: { + 'weight': \ + 'weight (Tensor): a weight tensor\n Some optional description' + } + """ + # Split on exactly 4 spaces after a newline + regx = re.compile(r"\n\s{4}(?!\s)") + kwargs = [section.strip() for section in regx.split(desc)] + kwargs = [section for section in kwargs if len(section) > 0] + return {desc.split(" ")[0]: desc for desc in kwargs} + + +def merge_dicts(*dicts): + """Merge dictionaries into a single dictionary.""" + return {x: d[x] for d in dicts for x in d} + + +common_args = parse_kwargs( + """ + input (Tensor): the input tensor. + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned tensor. Default: ``torch.preserve_format``. +""" +) + +reduceops_common_args = merge_dicts( + common_args, + parse_kwargs( + """ + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + keepdim (bool): whether the output tensor has :attr:`dim` retained or not. +""" + ), + { + "opt_keepdim": """ + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. +""" + }, +) + +multi_dim_common = merge_dicts( + reduceops_common_args, + parse_kwargs( + """ + dim (int or tuple of ints): the dimension or dimensions to reduce. +""" + ), + { + "keepdim_details": """ +If :attr:`keepdim` is ``True``, the output tensor is of the same size +as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. +Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the +output tensor having 1 (or ``len(dim)``) fewer dimension(s). +""" + }, + { + "opt_dim": """ + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. +""" + }, + { + "opt_dim_all_reduce": """ + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. +""" + }, +) + +single_dim_common = merge_dicts( + reduceops_common_args, + parse_kwargs( + """ + dim (int): the dimension to reduce. +""" + ), + { + "opt_dim": """ + dim (int, optional): the dimension to reduce. +""" + }, + { + "opt_dim_all_reduce": """ + dim (int, optional): the dimension to reduce. + If ``None``, all dimensions are reduced. +""" + }, + { + "opt_dim_without_none": """ + dim (int, optional): the dimension to reduce. If omitted, all dimensions are reduced. Explicit ``None`` is not supported. +""" + }, + { + "keepdim_details": """If :attr:`keepdim` is ``True``, the output tensor is of the same size +as :attr:`input` except in the dimension :attr:`dim` where it is of size 1. +Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in +the output tensor having 1 fewer dimension than :attr:`input`.""" + }, +) + +factory_common_args = merge_dicts( + common_args, + parse_kwargs( + """ + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.contiguous_format``. + check_invariants (bool, optional): If sparse tensor invariants are checked. + Default: as returned by :func:`torch.sparse.check_sparse_tensor_invariants.is_enabled`, + initially False. +""" + ), + { + "sparse_factory_device_note": """\ +.. note:: + + If the ``device`` argument is not specified the device of the given + :attr:`values` and indices tensor(s) must match. If, however, the + argument is specified the input Tensors will be converted to the + given device and in turn determine the device of the constructed + sparse tensor.""" + }, +) + +factory_like_common_args = parse_kwargs( + """ + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. +""" +) + +factory_data_common_args = parse_kwargs( + """ + data (array_like): Initial data for the tensor. Can be a list, tuple, + NumPy ``ndarray``, scalar, and other types. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, infers data type from :attr:`data`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. +""" +) + +tf32_notes = { + "tf32_note": """This operator supports :ref:`TensorFloat32`.""" +} + +rocm_fp16_notes = { + "rocm_fp16_note": """On certain ROCm devices, when using float16 inputs this module will use \ +:ref:`different precision` for backward.""" +} + +reproducibility_notes: dict[str, str] = { + "forward_reproducibility_note": """This operation may behave nondeterministically when given tensors on \ +a CUDA device. See :doc:`/notes/randomness` for more information.""", + "backward_reproducibility_note": """This operation may produce nondeterministic gradients when given tensors on \ +a CUDA device. See :doc:`/notes/randomness` for more information.""", + "cudnn_reproducibility_note": """In some circumstances when given tensors on a CUDA device \ +and using CuDNN, this operator may select a nondeterministic algorithm to increase performance. If this is \ +undesirable, you can try to make the operation deterministic (potentially at \ +a performance cost) by setting ``torch.backends.cudnn.deterministic = True``. \ +See :doc:`/notes/randomness` for more information.""", +} + +sparse_support_notes = { + "sparse_beta_warning": """ +.. warning:: + Sparse support is a beta feature and some layout(s)/dtype/device combinations may not be supported, + or may not have autograd support. If you notice missing functionality please + open a feature request.""", +} + +add_docstr( + torch.abs, + r""" +abs(input: Tensor, *, out: Optional[Tensor]) -> Tensor + +Computes the absolute value of each element in :attr:`input`. + +.. math:: + \text{out}_{i} = |\text{input}_{i}| +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> torch.abs(torch.tensor([-1, -2, 3])) + tensor([ 1, 2, 3]) +""".format(**common_args), +) + +add_docstr( + torch.absolute, + r""" +absolute(input: Tensor, *, out: Optional[Tensor]) -> Tensor + +Alias for :func:`torch.abs` +""", +) + +add_docstr( + torch.acos, + r""" +acos(input: Tensor, *, out: Optional[Tensor]) -> Tensor + +Returns a new tensor with the arccosine (in radians) of each element in :attr:`input`. + +.. math:: + \text{out}_{i} = \cos^{-1}(\text{input}_{i}) +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.3348, -0.5889, 0.2005, -0.1584]) + >>> torch.acos(a) + tensor([ 1.2294, 2.2004, 1.3690, 1.7298]) +""".format(**common_args), +) + +add_docstr( + torch.arccos, + r""" +arccos(input: Tensor, *, out: Optional[Tensor]) -> Tensor + +Alias for :func:`torch.acos`. +""", +) + +add_docstr( + torch.acosh, + r""" +acosh(input: Tensor, *, out: Optional[Tensor]) -> Tensor + +Returns a new tensor with the inverse hyperbolic cosine of the elements of :attr:`input`. + +.. math:: + \text{out}_{i} = \cosh^{-1}(\text{input}_{i}) + +Note: + The domain of the inverse hyperbolic cosine is `[1, inf)` and values outside this range + will be mapped to ``NaN``, except for `+ INF` for which the output is mapped to `+ INF`. +""" + + r""" +Args: + {input} + +Keyword arguments: + {out} + +Example:: + + >>> a = torch.randn(4).uniform_(1, 2) + >>> a + tensor([ 1.3192, 1.9915, 1.9674, 1.7151 ]) + >>> torch.acosh(a) + tensor([ 0.7791, 1.3120, 1.2979, 1.1341 ]) +""".format(**common_args), +) + +add_docstr( + torch.arccosh, + r""" +arccosh(input: Tensor, *, out: Optional[Tensor]) -> Tensor + +Alias for :func:`torch.acosh`. +""", +) + +add_docstr( + torch.index_add, + r""" +index_add(input: Tensor, dim: int, index: Tensor, source: Tensor, *, alpha: Union[Number, _complex] = 1, out: Optional[Tensor]) -> Tensor # noqa: B950 + +See :meth:`~Tensor.index_add_` for function description. +""", +) + +add_docstr( + torch.index_copy, + r""" +index_copy(input: Tensor, dim: int, index: Tensor, source: Tensor, *, out: Optional[Tensor]) -> Tensor + +See :meth:`~Tensor.index_add_` for function description. +""", +) + +add_docstr( + torch.index_reduce, + r""" +index_reduce(input: Tensor, dim: int, index: Tensor, source: Tensor, reduce: str, *, include_self: bool = True, out: Optional[Tensor]) -> Tensor # noqa: B950 + +See :meth:`~Tensor.index_reduce_` for function description. +""", +) + +add_docstr( + torch.add, + r""" +add(input, other, *, alpha=1, out=None) -> Tensor + +Adds :attr:`other`, scaled by :attr:`alpha`, to :attr:`input`. + +.. math:: + \text{{out}}_i = \text{{input}}_i + \text{{alpha}} \times \text{{other}}_i +""" + + r""" + +Supports :ref:`broadcasting to a common shape `, +:ref:`type promotion `, and integer, float, and complex inputs. + +Args: + {input} + other (Tensor or Number): the tensor or number to add to :attr:`input`. + +Keyword arguments: + alpha (Number): the multiplier for :attr:`other`. + {out} + +Examples:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.0202, 1.0985, 1.3506, -0.6056]) + >>> torch.add(a, 20) + tensor([ 20.0202, 21.0985, 21.3506, 19.3944]) + + >>> b = torch.randn(4) + >>> b + tensor([-0.9732, -0.3497, 0.6245, 0.4022]) + >>> c = torch.randn(4, 1) + >>> c + tensor([[ 0.3743], + [-1.7724], + [-0.5811], + [-0.8017]]) + >>> torch.add(b, c, alpha=10) + tensor([[ 2.7695, 3.3930, 4.3672, 4.1450], + [-18.6971, -18.0736, -17.0994, -17.3216], + [ -6.7845, -6.1610, -5.1868, -5.4090], + [ -8.9902, -8.3667, -7.3925, -7.6147]]) +""".format(**common_args), +) + +add_docstr( + torch.addbmm, + r""" +addbmm(input, batch1, batch2, *, beta=1, alpha=1, out=None) -> Tensor + +Performs a batch matrix-matrix product of matrices stored +in :attr:`batch1` and :attr:`batch2`, +with a reduced add step (all matrix multiplications get accumulated +along the first dimension). +:attr:`input` is added to the final result. + +:attr:`batch1` and :attr:`batch2` must be 3-D tensors each containing the +same number of matrices. + +If :attr:`batch1` is a :math:`(b \times n \times m)` tensor, :attr:`batch2` is a +:math:`(b \times m \times p)` tensor, :attr:`input` must be +:ref:`broadcastable ` with a :math:`(n \times p)` tensor +and :attr:`out` will be a :math:`(n \times p)` tensor. + +.. math:: + out = \beta\ \text{input} + \alpha\ (\sum_{i=0}^{b-1} \text{batch1}_i \mathbin{@} \text{batch2}_i) + +If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in +it will not be propagated. +""" + + r""" +For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and :attr:`alpha` +must be real numbers, otherwise they should be integers. + +{tf32_note} + +{rocm_fp16_note} + +Args: + input (Tensor): matrix to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + +Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for `batch1 @ batch2` (:math:`\alpha`) + {out} + +Example:: + + >>> M = torch.randn(3, 5) + >>> batch1 = torch.randn(10, 3, 4) + >>> batch2 = torch.randn(10, 4, 5) + >>> torch.addbmm(M, batch1, batch2) + tensor([[ 6.6311, 0.0503, 6.9768, -12.0362, -2.1653], + [ -4.8185, -1.4255, -6.6760, 8.9453, 2.5743], + [ -3.8202, 4.3691, 1.0943, -1.1109, 5.4730]]) +""".format(**common_args, **tf32_notes, **rocm_fp16_notes), +) + +add_docstr( + torch.addcdiv, + r""" +addcdiv(input, tensor1, tensor2, *, value=1, out=None) -> Tensor + +Performs the element-wise division of :attr:`tensor1` by :attr:`tensor2`, +multiplies the result by the scalar :attr:`value` and adds it to :attr:`input`. + +.. warning:: + Integer division with addcdiv is no longer supported, and in a future + release addcdiv will perform a true division of tensor1 and tensor2. + The historic addcdiv behavior can be implemented as + (input + value * torch.trunc(tensor1 / tensor2)).to(input.dtype) + for integer inputs and as (input + value * tensor1 / tensor2) for float inputs. + The future addcdiv behavior is just the latter implementation: + (input + value * tensor1 / tensor2), for all dtypes. + +.. math:: + \text{out}_i = \text{input}_i + \text{value} \times \frac{\text{tensor1}_i}{\text{tensor2}_i} +""" + + r""" + +The shapes of :attr:`input`, :attr:`tensor1`, and :attr:`tensor2` must be +:ref:`broadcastable `. + +For inputs of type `FloatTensor` or `DoubleTensor`, :attr:`value` must be +a real number, otherwise an integer. + +Args: + input (Tensor): the tensor to be added + tensor1 (Tensor): the numerator tensor + tensor2 (Tensor): the denominator tensor + +Keyword args: + value (Number, optional): multiplier for :math:`\text{{tensor1}} / \text{{tensor2}}` + {out} + +Example:: + + >>> t = torch.randn(1, 3) + >>> t1 = torch.randn(3, 1) + >>> t2 = torch.randn(1, 3) + >>> torch.addcdiv(t, t1, t2, value=0.1) + tensor([[-0.2312, -3.6496, 0.1312], + [-1.0428, 3.4292, -0.1030], + [-0.5369, -0.9829, 0.0430]]) +""".format(**common_args), +) + +add_docstr( + torch.addcmul, + r""" +addcmul(input, tensor1, tensor2, *, value=1, out=None) -> Tensor + +Performs the element-wise multiplication of :attr:`tensor1` +by :attr:`tensor2`, multiplies the result by the scalar :attr:`value` +and adds it to :attr:`input`. + +.. math:: + \text{out}_i = \text{input}_i + \text{value} \times \text{tensor1}_i \times \text{tensor2}_i +""" + + r""" +The shapes of :attr:`tensor`, :attr:`tensor1`, and :attr:`tensor2` must be +:ref:`broadcastable `. + +For inputs of type `FloatTensor` or `DoubleTensor`, :attr:`value` must be +a real number, otherwise an integer. + +Args: + input (Tensor): the tensor to be added + tensor1 (Tensor): the tensor to be multiplied + tensor2 (Tensor): the tensor to be multiplied + +Keyword args: + value (Number, optional): multiplier for :math:`tensor1 .* tensor2` + {out} + +Example:: + + >>> t = torch.randn(1, 3) + >>> t1 = torch.randn(3, 1) + >>> t2 = torch.randn(1, 3) + >>> torch.addcmul(t, t1, t2, value=0.1) + tensor([[-0.8635, -0.6391, 1.6174], + [-0.7617, -0.5879, 1.7388], + [-0.8353, -0.6249, 1.6511]]) +""".format(**common_args), +) + +add_docstr( + torch.addmm, + r""" +addmm(input, mat1, mat2, out_dtype=None, *, beta=1, alpha=1, out=None) -> Tensor + +Performs a matrix multiplication of the matrices :attr:`mat1` and :attr:`mat2`. +The matrix :attr:`input` is added to the final result. + +If :attr:`mat1` is a :math:`(n \times m)` tensor, :attr:`mat2` is a +:math:`(m \times p)` tensor, then :attr:`input` must be +:ref:`broadcastable ` with a :math:`(n \times p)` tensor +and :attr:`out` will be a :math:`(n \times p)` tensor. + +:attr:`alpha` and :attr:`beta` are scaling factors on matrix-vector product between +:attr:`mat1` and :attr:`mat2` and the added matrix :attr:`input` respectively. + +.. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{mat1}_i \mathbin{@} \text{mat2}_i) + +If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in +it will not be propagated. +""" + + r""" +For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and +:attr:`alpha` must be real numbers, otherwise they should be integers. + +This operation has support for arguments with :ref:`sparse layouts`. If +:attr:`input` is sparse the result will have the same layout and if :attr:`out` +is provided it must have the same layout as :attr:`input`. + +{sparse_beta_warning} + +{tf32_note} + +{rocm_fp16_note} + +Args: + input (Tensor): matrix to be added + mat1 (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + out_dtype (dtype, optional): the dtype of the output tensor, + Supported only on CUDA and for torch.float32 given + torch.float16/torch.bfloat16 input dtypes + +Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`) + {out} + +Example:: + + >>> M = torch.randn(2, 3) + >>> mat1 = torch.randn(2, 3) + >>> mat2 = torch.randn(3, 3) + >>> torch.addmm(M, mat1, mat2) + tensor([[-4.8716, 1.4671, -1.3746], + [ 0.7573, -3.9555, -2.8681]]) +""".format(**common_args, **tf32_notes, **rocm_fp16_notes, **sparse_support_notes), +) + +add_docstr( + torch.adjoint, + r""" +adjoint(input: Tensor) -> Tensor +Returns a view of the tensor conjugated and with the last two dimensions transposed. + +``x.adjoint()`` is equivalent to ``x.transpose(-2, -1).conj()`` for complex tensors and +to ``x.transpose(-2, -1)`` for real tensors. + +Args: + {input} + +Example:: + + >>> x = torch.arange(4, dtype=torch.float) + >>> A = torch.complex(x, x).reshape(2, 2) + >>> A + tensor([[0.+0.j, 1.+1.j], + [2.+2.j, 3.+3.j]]) + >>> A.adjoint() + tensor([[0.-0.j, 2.-2.j], + [1.-1.j, 3.-3.j]]) + >>> (A.adjoint() == A.mH).all() + tensor(True) +""", +) + +add_docstr( + torch.sspaddmm, + r""" +sspaddmm(input, mat1, mat2, *, beta=1, alpha=1, out=None) -> Tensor + +Matrix multiplies a sparse tensor :attr:`mat1` with a dense tensor +:attr:`mat2`, then adds the sparse tensor :attr:`input` to the result. + +Note: This function is equivalent to :func:`torch.addmm`, except +:attr:`input` and :attr:`mat1` are sparse. + +Args: + input (Tensor): a sparse matrix to be added + mat1 (Tensor): a sparse matrix to be matrix multiplied + mat2 (Tensor): a dense matrix to be matrix multiplied + +Keyword args: + beta (Number, optional): multiplier for :attr:`mat` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`) + {out} +""".format(**common_args), +) + +add_docstr( + torch.smm, + r""" +smm(input, mat) -> Tensor + +Performs a matrix multiplication of the sparse matrix :attr:`input` +with the dense matrix :attr:`mat`. + +Args: + input (Tensor): a sparse matrix to be matrix multiplied + mat (Tensor): a dense matrix to be matrix multiplied +""", +) + +add_docstr( + torch.addmv, + r""" +addmv(input, mat, vec, *, beta=1, alpha=1, out=None) -> Tensor + +Performs a matrix-vector product of the matrix :attr:`mat` and +the vector :attr:`vec`. +The vector :attr:`input` is added to the final result. + +If :attr:`mat` is a :math:`(n \times m)` tensor, :attr:`vec` is a 1-D tensor of +size `m`, then :attr:`input` must be +:ref:`broadcastable ` with a 1-D tensor of size `n` and +:attr:`out` will be 1-D tensor of size `n`. + +:attr:`alpha` and :attr:`beta` are scaling factors on matrix-vector product between +:attr:`mat` and :attr:`vec` and the added tensor :attr:`input` respectively. + +.. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{mat} \mathbin{@} \text{vec}) + +If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in +it will not be propagated. +""" + + r""" +For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and +:attr:`alpha` must be real numbers, otherwise they should be integers. + +Args: + input (Tensor): vector to be added + mat (Tensor): matrix to be matrix multiplied + vec (Tensor): vector to be matrix multiplied + +Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat @ vec` (:math:`\alpha`) + {out} + +Example:: + + >>> M = torch.randn(2) + >>> mat = torch.randn(2, 3) + >>> vec = torch.randn(3) + >>> torch.addmv(M, mat, vec) + tensor([-0.3768, -5.5565]) +""".format(**common_args), +) + +add_docstr( + torch.addr, + r""" +addr(input, vec1, vec2, *, beta=1, alpha=1, out=None) -> Tensor + +Performs the outer-product of vectors :attr:`vec1` and :attr:`vec2` +and adds it to the matrix :attr:`input`. + +Optional values :attr:`beta` and :attr:`alpha` are scaling factors on the +outer product between :attr:`vec1` and :attr:`vec2` and the added matrix +:attr:`input` respectively. + +.. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{vec1} \otimes \text{vec2}) + +If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in +it will not be propagated. +""" + + r""" +If :attr:`vec1` is a vector of size `n` and :attr:`vec2` is a vector +of size `m`, then :attr:`input` must be +:ref:`broadcastable ` with a matrix of size +:math:`(n \times m)` and :attr:`out` will be a matrix of size +:math:`(n \times m)`. + +Args: + input (Tensor): matrix to be added + vec1 (Tensor): the first vector of the outer product + vec2 (Tensor): the second vector of the outer product + +Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{{vec1}} \otimes \text{{vec2}}` (:math:`\alpha`) + {out} + +Example:: + + >>> vec1 = torch.arange(1., 4.) + >>> vec2 = torch.arange(1., 3.) + >>> M = torch.zeros(3, 2) + >>> torch.addr(M, vec1, vec2) + tensor([[ 1., 2.], + [ 2., 4.], + [ 3., 6.]]) +""".format(**common_args), +) + +add_docstr( + torch.allclose, + r""" +allclose(input: Tensor, other: Tensor, rtol: float = 1e-05, atol: float = 1e-08, equal_nan: bool = False) -> bool + +This function checks if :attr:`input` and :attr:`other` satisfy the condition: + +.. math:: + \lvert \text{input}_i - \text{other}_i \rvert \leq \texttt{atol} + \texttt{rtol} \times \lvert \text{other}_i \rvert +""" + + r""" +elementwise, for all elements of :attr:`input` and :attr:`other`. The behaviour of this function is analogous to +`numpy.allclose `_ + +Args: + input (Tensor): first tensor to compare + other (Tensor): second tensor to compare + atol (float, optional): absolute tolerance. Default: 1e-08 + rtol (float, optional): relative tolerance. Default: 1e-05 + equal_nan (bool, optional): if ``True``, then two ``NaN`` s will be considered equal. Default: ``False`` + +Example:: + + >>> torch.allclose(torch.tensor([10000., 1e-07]), torch.tensor([10000.1, 1e-08])) + False + >>> torch.allclose(torch.tensor([10000., 1e-08]), torch.tensor([10000.1, 1e-09])) + True + >>> torch.allclose(torch.tensor([1.0, float('nan')]), torch.tensor([1.0, float('nan')])) + False + >>> torch.allclose(torch.tensor([1.0, float('nan')]), torch.tensor([1.0, float('nan')]), equal_nan=True) + True +""", +) + +add_docstr( + torch.all, + r""" +all(input: Tensor, *, out=None) -> Tensor + +Tests if all elements in :attr:`input` evaluate to `True`. + +.. note:: This function matches the behaviour of NumPy in returning + output of dtype `bool` for all supported dtypes except `uint8`. + For `uint8` the dtype of output is `uint8` itself. + +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.rand(1, 2).bool() + >>> a + tensor([[False, True]], dtype=torch.bool) + >>> torch.all(a) + tensor(False, dtype=torch.bool) + >>> a = torch.arange(0, 3) + >>> a + tensor([0, 1, 2]) + >>> torch.all(a) + tensor(False) + +.. function:: all(input, dim, keepdim=False, *, out=None) -> Tensor + :noindex: + +For each row of :attr:`input` in the given dimension :attr:`dim`, +returns `True` if all elements in the row evaluate to `True` and `False` otherwise. + +{keepdim_details} + +Args: + {input} + {opt_dim_all_reduce} + {opt_keepdim} + +Keyword args: + {out} + +Example:: + + >>> a = torch.rand(4, 2).bool() + >>> a + tensor([[True, True], + [True, False], + [True, True], + [True, True]], dtype=torch.bool) + >>> torch.all(a, dim=1) + tensor([ True, False, True, True], dtype=torch.bool) + >>> torch.all(a, dim=0) + tensor([ True, False], dtype=torch.bool) +""".format(**multi_dim_common), +) + +add_docstr( + torch.any, + r""" +any(input: Tensor, *, out: Optional[Tensor]) -> Tensor + +Tests if any element in :attr:`input` evaluates to `True`. + +.. note:: This function matches the behaviour of NumPy in returning + output of dtype `bool` for all supported dtypes except `uint8`. + For `uint8` the dtype of output is `uint8` itself. + +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.rand(1, 2).bool() + >>> a + tensor([[False, True]], dtype=torch.bool) + >>> torch.any(a) + tensor(True, dtype=torch.bool) + >>> a = torch.arange(0, 3) + >>> a + tensor([0, 1, 2]) + >>> torch.any(a) + tensor(True) + +.. function:: any(input, dim, keepdim=False, *, out=None) -> Tensor + :noindex: + +For each row of :attr:`input` in the given dimension :attr:`dim`, +returns `True` if any element in the row evaluate to `True` and `False` otherwise. + +{keepdim_details} + +Args: + {input} + {opt_dim_all_reduce} + {opt_keepdim} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4, 2) < 0 + >>> a + tensor([[ True, True], + [False, True], + [ True, True], + [False, False]]) + >>> torch.any(a, 1) + tensor([ True, True, True, False]) + >>> torch.any(a, 0) + tensor([True, True]) +""".format(**multi_dim_common), +) + +add_docstr( + torch.angle, + r""" +angle(input: Tensor, *, out: Optional[Tensor]) -> Tensor + +Computes the element-wise angle (in radians) of the given :attr:`input` tensor. + +.. math:: + \text{out}_{i} = angle(\text{input}_{i}) +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +.. note:: Starting in PyTorch 1.8, angle returns pi for negative real numbers, + zero for non-negative real numbers, and propagates NaNs. Previously + the function would return zero for all real numbers and not propagate + floating-point NaNs. + +Example:: + + >>> torch.angle(torch.tensor([-1 + 1j, -2 + 2j, 3 - 3j]))*180/3.14159 + tensor([ 135., 135, -45]) +""".format(**common_args), +) + +add_docstr( + torch.as_strided, + r""" +as_strided(input, size, stride, storage_offset=None) -> Tensor + +Create a view of an existing `torch.Tensor` :attr:`input` with specified +:attr:`size`, :attr:`stride` and :attr:`storage_offset`. + +.. warning:: + Prefer using other view functions, like :meth:`torch.Tensor.view` or + :meth:`torch.Tensor.expand`, to setting a view's strides manually with + `as_strided`, as this function will throw an error on non-standard Pytorch + backends (that do not have a concept of stride) and the result will depend + on the current layout in memory. The constructed view must only refer to + elements within the Tensor's storage or a runtime error will be thrown. + If the generated view is "overlapped" (with multiple indices referring to + the same element in memory), the behavior of inplace operations on this view + is undefined (and might not throw runtime errors). + +Args: + {input} + size (tuple or ints): the shape of the output tensor + stride (tuple or ints): the stride of the output tensor + storage_offset (int, optional): the offset in the underlying storage of the output tensor. + If ``None``, the storage_offset of the output tensor will match the input tensor. + +Example:: + + >>> x = torch.randn(3, 3) + >>> x + tensor([[ 0.9039, 0.6291, 1.0795], + [ 0.1586, 2.1939, -0.4900], + [-0.1909, -0.7503, 1.9355]]) + >>> t = torch.as_strided(x, (2, 2), (1, 2)) + >>> t + tensor([[0.9039, 1.0795], + [0.6291, 0.1586]]) + >>> t = torch.as_strided(x, (2, 2), (1, 2), 1) + tensor([[0.6291, 0.1586], + [1.0795, 2.1939]]) +""".format(**common_args), +) + +add_docstr( + torch.as_tensor, + r""" +as_tensor(data: Any, dtype: Optional[dtype] = None, device: Optional[DeviceLikeType]) -> Tensor + +Converts :attr:`data` into a tensor, sharing data and preserving autograd +history if possible. + +If :attr:`data` is already a tensor with the requested dtype and device +then :attr:`data` itself is returned, but if :attr:`data` is a +tensor with a different dtype or device then it's copied as if using +`data.to(dtype=dtype, device=device)`. + +If :attr:`data` is a NumPy array (an ndarray) with the same dtype and device then a +tensor is constructed using :func:`torch.from_numpy`. + +If :attr:`data` is a CuPy array, the returned tensor will be located on the same device as the CuPy array unless +specifically overwritten by :attr:`device` or a default device. The device of the CuPy array is inferred from the +pointer of the array using `cudaPointerGetAttributes` unless :attr:`device` is provided with an explicit device index. + +.. seealso:: + + :func:`torch.tensor` never shares its data and creates a new "leaf tensor" (see :doc:`/notes/autograd`). + + +Args: + {data} + {dtype} + device (:class:`torch.device`, optional): the device of the constructed tensor. If None and data is a tensor + then the device of data is used. If None and data is not a tensor then + the result tensor is constructed on the current device. + + +Example:: + + >>> a = numpy.array([1, 2, 3]) + >>> t = torch.as_tensor(a) + >>> t + tensor([ 1, 2, 3]) + >>> t[0] = -1 + >>> a + array([-1, 2, 3]) + + >>> a = numpy.array([1, 2, 3]) + >>> t = torch.as_tensor(a, device=torch.device('cuda')) + >>> t + tensor([ 1, 2, 3]) + >>> t[0] = -1 + >>> a + array([1, 2, 3]) +""".format(**factory_data_common_args), +) + +add_docstr( + torch.asin, + r""" +asin(input: Tensor, *, out: Optional[Tensor]) -> Tensor + +Returns a new tensor with the arcsine of the elements (in radians) in the :attr:`input` tensor. + +.. math:: + \text{out}_{i} = \sin^{-1}(\text{input}_{i}) +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-0.5962, 1.4985, -0.4396, 1.4525]) + >>> torch.asin(a) + tensor([-0.6387, nan, -0.4552, nan]) +""".format(**common_args), +) + +add_docstr( + torch.arcsin, + r""" +arcsin(input: Tensor, *, out: Optional[Tensor]) -> Tensor + +Alias for :func:`torch.asin`. +""", +) + +add_docstr( + torch.asinh, + r""" +asinh(input: Tensor, *, out: Optional[Tensor]) -> Tensor + +Returns a new tensor with the inverse hyperbolic sine of the elements of :attr:`input`. + +.. math:: + \text{out}_{i} = \sinh^{-1}(\text{input}_{i}) +""" + + r""" +Args: + {input} + +Keyword arguments: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.1606, -1.4267, -1.0899, -1.0250 ]) + >>> torch.asinh(a) + tensor([ 0.1599, -1.1534, -0.9435, -0.8990 ]) +""".format(**common_args), +) + +add_docstr( + torch.arcsinh, + r""" +arcsinh(input: Tensor, *, out: Optional[Tensor]) -> Tensor + +Alias for :func:`torch.asinh`. +""", +) + +add_docstr( + torch.atan, + r""" +atan(input: Tensor, *, out: Optional[Tensor]) -> Tensor + +Returns a new tensor with the arctangent of the elements (in radians) in the :attr:`input` tensor. + +.. math:: + \text{out}_{i} = \tan^{-1}(\text{input}_{i}) +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.2341, 0.2539, -0.6256, -0.6448]) + >>> torch.atan(a) + tensor([ 0.2299, 0.2487, -0.5591, -0.5727]) +""".format(**common_args), +) + +add_docstr( + torch.arctan, + r""" +arctan(input: Tensor, *, out: Optional[Tensor]) -> Tensor + +Alias for :func:`torch.atan`. +""", +) + +add_docstr( + torch.atan2, + r""" +atan2(input: Tensor, other: Tensor, *, out: Optional[Tensor]) -> Tensor + +Element-wise arctangent of :math:`\text{{input}}_{{i}} / \text{{other}}_{{i}}` +with consideration of the quadrant. Returns a new tensor with the signed angles +in radians between vector :math:`(\text{{other}}_{{i}}, \text{{input}}_{{i}})` +and vector :math:`(1, 0)`. (Note that :math:`\text{{other}}_{{i}}`, the second +parameter, is the x-coordinate, while :math:`\text{{input}}_{{i}}`, the first +parameter, is the y-coordinate.) + +The shapes of ``input`` and ``other`` must be +:ref:`broadcastable `. + +Args: + input (Tensor): the first input tensor + other (Tensor): the second input tensor + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.9041, 0.0196, -0.3108, -2.4423]) + >>> torch.atan2(a, torch.randn(4)) + tensor([ 0.9833, 0.0811, -1.9743, -1.4151]) +""".format(**common_args), +) + +add_docstr( + torch.arctan2, + r""" +arctan2(input: Tensor, other: Tensor, *, out: Optional[Tensor]) -> Tensor +Alias for :func:`torch.atan2`. +""", +) + +add_docstr( + torch.atanh, + r""" +atanh(input: Tensor, *, out: Optional[Tensor]) -> Tensor + +Returns a new tensor with the inverse hyperbolic tangent of the elements of :attr:`input`. + +Note: + The domain of the inverse hyperbolic tangent is `(-1, 1)` and values outside this range + will be mapped to ``NaN``, except for the values `1` and `-1` for which the output is + mapped to `+/-INF` respectively. + +.. math:: + \text{out}_{i} = \tanh^{-1}(\text{input}_{i}) +""" + + r""" +Args: + {input} + +Keyword arguments: + {out} + +Example:: + + >>> a = torch.randn(4).uniform_(-1, 1) + >>> a + tensor([ -0.9385, 0.2968, -0.8591, -0.1871 ]) + >>> torch.atanh(a) + tensor([ -1.7253, 0.3060, -1.2899, -0.1893 ]) +""".format(**common_args), +) + +add_docstr( + torch.arctanh, + r""" +arctanh(input: Tensor, *, out: Optional[Tensor]) -> Tensor + +Alias for :func:`torch.atanh`. +""", +) + +add_docstr( + torch.asarray, + r""" +asarray(obj: Any, *, dtype: Optional[dtype], device: Optional[DeviceLikeType], copy: Optional[bool] = None, requires_grad: bool = False) -> Tensor # noqa: B950 + +Converts :attr:`obj` to a tensor. + +:attr:`obj` can be one of: + +1. a tensor +2. a NumPy array or a NumPy scalar +3. a DLPack capsule +4. an object that implements Python's buffer protocol +5. a scalar +6. a sequence of scalars + +When :attr:`obj` is a tensor, NumPy array, or DLPack capsule the returned tensor will, +by default, not require a gradient, have the same datatype as :attr:`obj`, be on the +same device, and share memory with it. These properties can be controlled with the +:attr:`dtype`, :attr:`device`, :attr:`copy`, and :attr:`requires_grad` keyword arguments. +If the returned tensor is of a different datatype, on a different device, or a copy is +requested then it will not share its memory with :attr:`obj`. If :attr:`requires_grad` +is ``True`` then the returned tensor will require a gradient, and if :attr:`obj` is +also a tensor with an autograd history then the returned tensor will have the same history. + +When :attr:`obj` is not a tensor, NumPy array, or DLPack capsule but implements Python's +buffer protocol then the buffer is interpreted as an array of bytes grouped according to +the size of the datatype passed to the :attr:`dtype` keyword argument. (If no datatype is +passed then the default floating point datatype is used, instead.) The returned tensor +will have the specified datatype (or default floating point datatype if none is specified) +and, by default, be on the CPU device and share memory with the buffer. + +When :attr:`obj` is a NumPy scalar, the returned tensor will be a 0-dimensional tensor on +the CPU and that doesn't share its memory (i.e. ``copy=True``). By default datatype will +be the PyTorch datatype corresponding to the NumPy's scalar's datatype. + +When :attr:`obj` is none of the above but a scalar, or a sequence of scalars then the +returned tensor will, by default, infer its datatype from the scalar values, be on the +current default device, and not share its memory. + +.. seealso:: + + :func:`torch.tensor` creates a tensor that always copies the data from the input object. + :func:`torch.from_numpy` creates a tensor that always shares memory from NumPy arrays. + :func:`torch.frombuffer` creates a tensor that always shares memory from objects that + implement the buffer protocol. + :func:`torch.from_dlpack` creates a tensor that always shares memory from + DLPack capsules. + +Args: + obj (object): a tensor, NumPy array, DLPack Capsule, object that implements Python's + buffer protocol, scalar, or sequence of scalars. + +Keyword args: + dtype (:class:`torch.dtype`, optional): the datatype of the returned tensor. + Default: ``None``, which causes the datatype of the returned tensor to be + inferred from :attr:`obj`. + copy (bool, optional): controls whether the returned tensor shares memory with :attr:`obj`. + Default: ``None``, which causes the returned tensor to share memory with :attr:`obj` + whenever possible. If ``True`` then the returned tensor does not share its memory. + If ``False`` then the returned tensor shares its memory with :attr:`obj` and an + error is thrown if it cannot. + device (:class:`torch.device`, optional): the device of the returned tensor. + Default: ``None``, which causes the device of :attr:`obj` to be used. Or, if + :attr:`obj` is a Python sequence, the current default device will be used. + requires_grad (bool, optional): whether the returned tensor requires grad. + Default: ``False``, which causes the returned tensor not to require a gradient. + If ``True``, then the returned tensor will require a gradient, and if :attr:`obj` + is also a tensor with an autograd history then the returned tensor will have + the same history. + +Example:: + + >>> a = torch.tensor([1, 2, 3]) + >>> # Shares memory with tensor 'a' + >>> b = torch.asarray(a) + >>> a.data_ptr() == b.data_ptr() + True + >>> # Forces memory copy + >>> c = torch.asarray(a, copy=True) + >>> a.data_ptr() == c.data_ptr() + False + + >>> a = torch.tensor([1., 2., 3.], requires_grad=True) + >>> b = a + 2 + >>> b + tensor([3., 4., 5.], grad_fn=) + >>> # Shares memory with tensor 'b', with no grad + >>> c = torch.asarray(b) + >>> c + tensor([3., 4., 5.]) + >>> # Shares memory with tensor 'b', retaining autograd history + >>> d = torch.asarray(b, requires_grad=True) + >>> d + tensor([3., 4., 5.], grad_fn=) + + >>> array = numpy.array([1, 2, 3]) + >>> # Shares memory with array 'array' + >>> t1 = torch.asarray(array) + >>> array.__array_interface__['data'][0] == t1.data_ptr() + True + >>> # Copies memory due to dtype mismatch + >>> t2 = torch.asarray(array, dtype=torch.float32) + >>> array.__array_interface__['data'][0] == t2.data_ptr() + False + + >>> scalar = numpy.float64(0.5) + >>> torch.asarray(scalar) + tensor(0.5000, dtype=torch.float64) +""", +) + +add_docstr( + torch.baddbmm, + r""" +baddbmm(input, batch1, batch2, out_dtype=None, *, beta=1, alpha=1, out=None) -> Tensor + +Performs a batch matrix-matrix product of matrices in :attr:`batch1` +and :attr:`batch2`. +:attr:`input` is added to the final result. + +:attr:`batch1` and :attr:`batch2` must be 3-D tensors each containing the same +number of matrices. + +If :attr:`batch1` is a :math:`(b \times n \times m)` tensor, :attr:`batch2` is a +:math:`(b \times m \times p)` tensor, then :attr:`input` must be +:ref:`broadcastable ` with a +:math:`(b \times n \times p)` tensor and :attr:`out` will be a +:math:`(b \times n \times p)` tensor. Both :attr:`alpha` and :attr:`beta` mean the +same as the scaling factors used in :meth:`torch.addbmm`. + +.. math:: + \text{out}_i = \beta\ \text{input}_i + \alpha\ (\text{batch1}_i \mathbin{@} \text{batch2}_i) + +If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in +it will not be propagated. +""" + + r""" +For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and +:attr:`alpha` must be real numbers, otherwise they should be integers. + +{tf32_note} + +{rocm_fp16_note} + +Args: + input (Tensor): the tensor to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + out_dtype (dtype, optional): the dtype of the output tensor, + Supported only on CUDA and for torch.float32 given + torch.float16/torch.bfloat16 input dtypes + +Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{{batch1}} \mathbin{{@}} \text{{batch2}}` (:math:`\alpha`) + {out} + +Example:: + + >>> M = torch.randn(10, 3, 5) + >>> batch1 = torch.randn(10, 3, 4) + >>> batch2 = torch.randn(10, 4, 5) + >>> torch.baddbmm(M, batch1, batch2).size() + torch.Size([10, 3, 5]) +""".format(**common_args, **tf32_notes, **rocm_fp16_notes), +) + +add_docstr( + torch.bernoulli, + r""" +bernoulli(input: Tensor, *, generator: Optional[Generator], out: Optional[Tensor]) -> Tensor + +Draws binary random numbers (0 or 1) from a Bernoulli distribution. + +The :attr:`input` tensor should be a tensor containing probabilities +to be used for drawing the binary random number. +Hence, all values in :attr:`input` have to be in the range: +:math:`0 \leq \text{input}_i \leq 1`. + +The :math:`\text{i}^{th}` element of the output tensor will draw a +value :math:`1` according to the :math:`\text{i}^{th}` probability value given +in :attr:`input`. + +.. math:: + \text{out}_{i} \sim \mathrm{Bernoulli}(p = \text{input}_{i}) +""" + + r""" +The returned :attr:`out` tensor only has values 0 or 1 and is of the same +shape as :attr:`input`. + +:attr:`out` can have integral ``dtype``, but :attr:`input` must have floating +point ``dtype``. + +Args: + input (Tensor): the input tensor of probability values for the Bernoulli distribution + +Keyword args: + {generator} + {out} + +Example:: + + >>> a = torch.empty(3, 3).uniform_(0, 1) # generate a uniform random matrix with range [0, 1] + >>> a + tensor([[ 0.1737, 0.0950, 0.3609], + [ 0.7148, 0.0289, 0.2676], + [ 0.9456, 0.8937, 0.7202]]) + >>> torch.bernoulli(a) + tensor([[ 1., 0., 0.], + [ 0., 0., 0.], + [ 1., 1., 1.]]) + + >>> a = torch.ones(3, 3) # probability of drawing "1" is 1 + >>> torch.bernoulli(a) + tensor([[ 1., 1., 1.], + [ 1., 1., 1.], + [ 1., 1., 1.]]) + >>> a = torch.zeros(3, 3) # probability of drawing "1" is 0 + >>> torch.bernoulli(a) + tensor([[ 0., 0., 0.], + [ 0., 0., 0.], + [ 0., 0., 0.]]) +""".format(**common_args), +) + +add_docstr( + torch.bincount, + r""" +bincount(input, weights=None, minlength=0) -> Tensor + +Count the frequency of each value in an array of non-negative ints. + +The number of bins (size 1) is one larger than the largest value in +:attr:`input` unless :attr:`input` is empty, in which case the result is a +tensor of size 0. If :attr:`minlength` is specified, the number of bins is at least +:attr:`minlength` and if :attr:`input` is empty, then the result is tensor of size +:attr:`minlength` filled with zeros. If ``n`` is the value at position ``i``, +``out[n] += weights[i]`` if :attr:`weights` is specified else +``out[n] += 1``. + +Note: + {backward_reproducibility_note} + +Arguments: + input (Tensor): 1-d int tensor + weights (Tensor): optional, weight for each value in the input tensor. + Should be of same size as input tensor. + minlength (int): optional, minimum number of bins. Should be non-negative. + +Returns: + output (Tensor): a tensor of shape ``Size([max(input) + 1])`` if + :attr:`input` is non-empty, else ``Size(0)`` + +Example:: + + >>> input = torch.randint(0, 8, (5,), dtype=torch.int64) + >>> weights = torch.linspace(0, 1, steps=5) + >>> input, weights + (tensor([4, 3, 6, 3, 4]), + tensor([ 0.0000, 0.2500, 0.5000, 0.7500, 1.0000]) + + >>> torch.bincount(input) + tensor([0, 0, 0, 2, 2, 0, 1]) + + >>> input.bincount(weights) + tensor([0.0000, 0.0000, 0.0000, 1.0000, 1.0000, 0.0000, 0.5000]) +""".format(**reproducibility_notes), +) + +add_docstr( + torch.bitwise_not, + r""" +bitwise_not(input, *, out=None) -> Tensor + +Computes the bitwise NOT of the given input tensor. The input tensor must be of +integral or Boolean types. For bool tensors, it computes the logical NOT. + +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> torch.bitwise_not(torch.tensor([-1, -2, 3], dtype=torch.int8)) + tensor([ 0, 1, -4], dtype=torch.int8) +""".format(**common_args), +) + +add_docstr( + torch.bmm, + r""" +bmm(input, mat2, out_dtype=None, *, out=None) -> Tensor + +Performs a batch matrix-matrix product of matrices stored in :attr:`input` +and :attr:`mat2`. + +:attr:`input` and :attr:`mat2` must be 3-D tensors each containing +the same number of matrices. + +If :attr:`input` is a :math:`(b \times n \times m)` tensor, :attr:`mat2` is a +:math:`(b \times m \times p)` tensor, :attr:`out` will be a +:math:`(b \times n \times p)` tensor. + +.. math:: + \text{out}_i = \text{input}_i \mathbin{@} \text{mat2}_i +""" + + r""" +{tf32_note} + +{rocm_fp16_note} + +.. note:: This function does not :ref:`broadcast `. + For broadcasting matrix products, see :func:`torch.matmul`. + +Args: + input (Tensor): the first batch of matrices to be multiplied + mat2 (Tensor): the second batch of matrices to be multiplied + out_dtype (dtype, optional): the dtype of the output tensor, + Supported only on CUDA and for torch.float32 given + torch.float16/torch.bfloat16 input dtypes + +Keyword Args: + {out} + +Example:: + + >>> input = torch.randn(10, 3, 4) + >>> mat2 = torch.randn(10, 4, 5) + >>> res = torch.bmm(input, mat2) + >>> res.size() + torch.Size([10, 3, 5]) +""".format(**common_args, **tf32_notes, **rocm_fp16_notes), +) + +add_docstr( + torch.bitwise_and, + r""" +bitwise_and(input, other, *, out=None) -> Tensor + +Computes the bitwise AND of :attr:`input` and :attr:`other`. The input tensor must be of +integral or Boolean types. For bool tensors, it computes the logical AND. + +Args: + input: the first input tensor + other: the second input tensor + +Keyword args: + {out} + +Example:: + + >>> torch.bitwise_and(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([1, 0, 3], dtype=torch.int8) + >>> torch.bitwise_and(torch.tensor([True, True, False]), torch.tensor([False, True, False])) + tensor([ False, True, False]) +""".format(**common_args), +) + +add_docstr( + torch.bitwise_or, + r""" +bitwise_or(input: Tensor, other: Tensor, *, out: Optional[Tensor]) -> Tensor + +Computes the bitwise OR of :attr:`input` and :attr:`other`. The input tensor must be of +integral or Boolean types. For bool tensors, it computes the logical OR. + +Args: + input: the first input tensor + other: the second input tensor + +Keyword args: + {out} + +Example:: + + >>> torch.bitwise_or(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-1, -2, 3], dtype=torch.int8) + >>> torch.bitwise_or(torch.tensor([True, True, False]), torch.tensor([False, True, False])) + tensor([ True, True, False]) +""".format(**common_args), +) + +add_docstr( + torch.bitwise_xor, + r""" +bitwise_xor(input, other, *, out=None) -> Tensor + +Computes the bitwise XOR of :attr:`input` and :attr:`other`. The input tensor must be of +integral or Boolean types. For bool tensors, it computes the logical XOR. + +Args: + input: the first input tensor + other: the second input tensor + +Keyword args: + {out} + +Example:: + + >>> torch.bitwise_xor(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-2, -2, 0], dtype=torch.int8) + >>> torch.bitwise_xor(torch.tensor([True, True, False]), torch.tensor([False, True, False])) + tensor([ True, False, False]) +""".format(**common_args), +) + +add_docstr( + torch.bitwise_left_shift, + r""" +bitwise_left_shift(input, other, *, out=None) -> Tensor + +Computes the left arithmetic shift of :attr:`input` by :attr:`other` bits. +The input tensor must be of integral type. This operator supports +:ref:`broadcasting to a common shape ` and +:ref:`type promotion `. + +The operation applied is: + +.. math:: + \text{{out}}_i = \text{{input}}_i << \text{{other}}_i + +Args: + input (Tensor or Scalar): the first input tensor + other (Tensor or Scalar): the second input tensor + +Keyword args: + {out} + +Example:: + + >>> torch.bitwise_left_shift(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-2, -2, 24], dtype=torch.int8) +""".format(**common_args), +) + +add_docstr( + torch.bitwise_right_shift, + r""" +bitwise_right_shift(input, other, *, out=None) -> Tensor + +Computes the right arithmetic shift of :attr:`input` by :attr:`other` bits. +The input tensor must be of integral type. This operator supports +:ref:`broadcasting to a common shape ` and +:ref:`type promotion `. +In any case, if the value of the right operand is negative or is greater +or equal to the number of bits in the promoted left operand, the behavior is undefined. + +The operation applied is: + +.. math:: + \text{{out}}_i = \text{{input}}_i >> \text{{other}}_i + +Args: + input (Tensor or Scalar): the first input tensor + other (Tensor or Scalar): the second input tensor + +Keyword args: + {out} + +Example:: + + >>> torch.bitwise_right_shift(torch.tensor([-2, -7, 31], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-1, -7, 3], dtype=torch.int8) +""".format(**common_args), +) + +add_docstr( + torch.broadcast_to, + r""" +broadcast_to(input, shape) -> Tensor + +Broadcasts :attr:`input` to the shape :attr:`\shape`. +Equivalent to calling ``input.expand(shape)``. See :meth:`~Tensor.expand` for details. + +Args: + {input} + shape (list, tuple, or :class:`torch.Size`): the new shape. + +Example:: + + >>> x = torch.tensor([1, 2, 3]) + >>> torch.broadcast_to(x, (3, 3)) + tensor([[1, 2, 3], + [1, 2, 3], + [1, 2, 3]]) +""".format(**common_args), +) + +add_docstr( + torch.stack, + r""" +stack(tensors, dim=0, *, out=None) -> Tensor + +Concatenates a sequence of tensors along a new dimension. + +All tensors need to be of the same size. + +.. seealso:: + + :func:`torch.cat` concatenates the given sequence along an existing dimension. + +Arguments: + tensors (sequence of Tensors): sequence of tensors to concatenate + dim (int, optional): dimension to insert. Has to be between 0 and the number + of dimensions of concatenated tensors (inclusive). Default: 0 + +Keyword args: + {out} + +Example:: + + >>> x = torch.randn(2, 3) + >>> x + tensor([[ 0.3367, 0.1288, 0.2345], + [ 0.2303, -1.1229, -0.1863]]) + >>> torch.stack((x, x)) # same as torch.stack((x, x), dim=0) + tensor([[[ 0.3367, 0.1288, 0.2345], + [ 0.2303, -1.1229, -0.1863]], + + [[ 0.3367, 0.1288, 0.2345], + [ 0.2303, -1.1229, -0.1863]]]) + >>> torch.stack((x, x)).size() + torch.Size([2, 2, 3]) + >>> torch.stack((x, x), dim=1) + tensor([[[ 0.3367, 0.1288, 0.2345], + [ 0.3367, 0.1288, 0.2345]], + + [[ 0.2303, -1.1229, -0.1863], + [ 0.2303, -1.1229, -0.1863]]]) + >>> torch.stack((x, x), dim=2) + tensor([[[ 0.3367, 0.3367], + [ 0.1288, 0.1288], + [ 0.2345, 0.2345]], + + [[ 0.2303, 0.2303], + [-1.1229, -1.1229], + [-0.1863, -0.1863]]]) + >>> torch.stack((x, x), dim=-1) + tensor([[[ 0.3367, 0.3367], + [ 0.1288, 0.1288], + [ 0.2345, 0.2345]], + + [[ 0.2303, 0.2303], + [-1.1229, -1.1229], + [-0.1863, -0.1863]]]) +""".format(**common_args), +) + +add_docstr( + torch.hstack, + r""" +hstack(tensors, *, out=None) -> Tensor + +Stack tensors in sequence horizontally (column wise). + +This is equivalent to concatenation along the first axis for 1-D tensors, and along the second axis for all other tensors. + +Args: + tensors (sequence of Tensors): sequence of tensors to concatenate + +Keyword args: + {out} + +Example:: + + >>> a = torch.tensor([1, 2, 3]) + >>> b = torch.tensor([4, 5, 6]) + >>> torch.hstack((a,b)) + tensor([1, 2, 3, 4, 5, 6]) + >>> a = torch.tensor([[1],[2],[3]]) + >>> b = torch.tensor([[4],[5],[6]]) + >>> torch.hstack((a,b)) + tensor([[1, 4], + [2, 5], + [3, 6]]) + +""".format(**common_args), +) + +add_docstr( + torch.vstack, + r""" +vstack(tensors, *, out=None) -> Tensor + +Stack tensors in sequence vertically (row wise). + +This is equivalent to concatenation along the first axis after all 1-D tensors have been reshaped by :func:`torch.atleast_2d`. + +Args: + tensors (sequence of Tensors): sequence of tensors to concatenate + +Keyword args: + {out} + +Example:: + + >>> a = torch.tensor([1, 2, 3]) + >>> b = torch.tensor([4, 5, 6]) + >>> torch.vstack((a,b)) + tensor([[1, 2, 3], + [4, 5, 6]]) + >>> a = torch.tensor([[1],[2],[3]]) + >>> b = torch.tensor([[4],[5],[6]]) + >>> torch.vstack((a,b)) + tensor([[1], + [2], + [3], + [4], + [5], + [6]]) + + +""".format(**common_args), +) + +add_docstr( + torch.dstack, + r""" +dstack(tensors, *, out=None) -> Tensor + +Stack tensors in sequence depthwise (along third axis). + +This is equivalent to concatenation along the third axis after 1-D and 2-D tensors have been reshaped by :func:`torch.atleast_3d`. + +Args: + tensors (sequence of Tensors): sequence of tensors to concatenate + +Keyword args: + {out} + +Example:: + + >>> a = torch.tensor([1, 2, 3]) + >>> b = torch.tensor([4, 5, 6]) + >>> torch.dstack((a,b)) + tensor([[[1, 4], + [2, 5], + [3, 6]]]) + >>> a = torch.tensor([[1],[2],[3]]) + >>> b = torch.tensor([[4],[5],[6]]) + >>> torch.dstack((a,b)) + tensor([[[1, 4]], + [[2, 5]], + [[3, 6]]]) + + +""".format(**common_args), +) + +add_docstr( + torch.tensor_split, + r""" +tensor_split(input, indices_or_sections, dim=0) -> List of Tensors + +Splits a tensor into multiple sub-tensors, all of which are views of :attr:`input`, +along dimension :attr:`dim` according to the indices or number of sections specified +by :attr:`indices_or_sections`. This function is based on NumPy's +:func:`numpy.array_split`. + +Args: + input (Tensor): the tensor to split + indices_or_sections (Tensor, int or list or tuple of ints): + If :attr:`indices_or_sections` is an integer ``n`` or a zero dimensional long tensor + with value ``n``, :attr:`input` is split into ``n`` sections along dimension :attr:`dim`. + If :attr:`input` is divisible by ``n`` along dimension :attr:`dim`, each + section will be of equal size, :code:`input.size(dim) / n`. If :attr:`input` + is not divisible by ``n``, the sizes of the first :code:`int(input.size(dim) % n)` + sections will have size :code:`int(input.size(dim) / n) + 1`, and the rest will + have size :code:`int(input.size(dim) / n)`. + + If :attr:`indices_or_sections` is a list or tuple of ints, or a one-dimensional long + tensor, then :attr:`input` is split along dimension :attr:`dim` at each of the indices + in the list, tuple or tensor. For instance, :code:`indices_or_sections=[2, 3]` and :code:`dim=0` + would result in the tensors :code:`input[:2]`, :code:`input[2:3]`, and :code:`input[3:]`. + + If :attr:`indices_or_sections` is a tensor, it must be a zero-dimensional or one-dimensional + long tensor on the CPU. + + dim (int, optional): dimension along which to split the tensor. Default: ``0`` + +Example:: + + >>> x = torch.arange(8) + >>> torch.tensor_split(x, 3) + (tensor([0, 1, 2]), tensor([3, 4, 5]), tensor([6, 7])) + + >>> x = torch.arange(7) + >>> torch.tensor_split(x, 3) + (tensor([0, 1, 2]), tensor([3, 4]), tensor([5, 6])) + >>> torch.tensor_split(x, (1, 6)) + (tensor([0]), tensor([1, 2, 3, 4, 5]), tensor([6])) + + >>> x = torch.arange(14).reshape(2, 7) + >>> x + tensor([[ 0, 1, 2, 3, 4, 5, 6], + [ 7, 8, 9, 10, 11, 12, 13]]) + >>> torch.tensor_split(x, 3, dim=1) + (tensor([[0, 1, 2], + [7, 8, 9]]), + tensor([[ 3, 4], + [10, 11]]), + tensor([[ 5, 6], + [12, 13]])) + >>> torch.tensor_split(x, (1, 6), dim=1) + (tensor([[0], + [7]]), + tensor([[ 1, 2, 3, 4, 5], + [ 8, 9, 10, 11, 12]]), + tensor([[ 6], + [13]])) +""", +) + +add_docstr( + torch.chunk, + r""" +chunk(input: Tensor, chunks: int, dim: int = 0) -> Tuple[Tensor, ...] + +Attempts to split a tensor into the specified number of chunks. Each chunk is a view of +the input tensor. + + +.. note:: + + This function may return fewer than the specified number of chunks! + +.. seealso:: + + :func:`torch.tensor_split` a function that always returns exactly the specified number of chunks + +If the tensor size along the given dimension :attr:`dim` is divisible by :attr:`chunks`, +all returned chunks will be the same size. +If the tensor size along the given dimension :attr:`dim` is not divisible by :attr:`chunks`, +all returned chunks will be the same size, except the last one. +If such division is not possible, this function may return fewer +than the specified number of chunks. + +Arguments: + input (Tensor): the tensor to split + chunks (int): number of chunks to return + dim (int): dimension along which to split the tensor + +Example: + >>> torch.arange(11).chunk(6) + (tensor([0, 1]), + tensor([2, 3]), + tensor([4, 5]), + tensor([6, 7]), + tensor([8, 9]), + tensor([10])) + >>> torch.arange(12).chunk(6) + (tensor([0, 1]), + tensor([2, 3]), + tensor([4, 5]), + tensor([6, 7]), + tensor([8, 9]), + tensor([10, 11])) + >>> torch.arange(13).chunk(6) + (tensor([0, 1, 2]), + tensor([3, 4, 5]), + tensor([6, 7, 8]), + tensor([ 9, 10, 11]), + tensor([12])) +""", +) + +add_docstr( + torch.unsafe_chunk, + r""" +unsafe_chunk(input, chunks, dim=0) -> List of Tensors + +Works like :func:`torch.chunk` but without enforcing the autograd restrictions +on inplace modification of the outputs. + +.. warning:: + This function is safe to use as long as only the input, or only the outputs + are modified inplace after calling this function. It is user's + responsibility to ensure that is the case. If both the input and one or more + of the outputs are modified inplace, gradients computed by autograd will be + silently incorrect. +""", +) + +add_docstr( + torch.unsafe_split, + r""" +unsafe_split(tensor, split_size_or_sections, dim=0) -> List of Tensors + +Works like :func:`torch.split` but without enforcing the autograd restrictions +on inplace modification of the outputs. + +.. warning:: + This function is safe to use as long as only the input, or only the outputs + are modified inplace after calling this function. It is user's + responsibility to ensure that is the case. If both the input and one or more + of the outputs are modified inplace, gradients computed by autograd will be + silently incorrect. +""", +) + +add_docstr( + torch.hsplit, + r""" +hsplit(input, indices_or_sections) -> List of Tensors + +Splits :attr:`input`, a tensor with one or more dimensions, into multiple tensors +horizontally according to :attr:`indices_or_sections`. Each split is a view of +:attr:`input`. + +If :attr:`input` is one dimensional this is equivalent to calling +torch.tensor_split(input, indices_or_sections, dim=0) (the split dimension is +zero), and if :attr:`input` has two or more dimensions it's equivalent to calling +torch.tensor_split(input, indices_or_sections, dim=1) (the split dimension is 1), +except that if :attr:`indices_or_sections` is an integer it must evenly divide +the split dimension or a runtime error will be thrown. + +This function is based on NumPy's :func:`numpy.hsplit`. + +Args: + input (Tensor): tensor to split. + indices_or_sections (int or list or tuple of ints): See argument in :func:`torch.tensor_split`. + +Example:: + + >>> t = torch.arange(16.0).reshape(4,4) + >>> t + tensor([[ 0., 1., 2., 3.], + [ 4., 5., 6., 7.], + [ 8., 9., 10., 11.], + [12., 13., 14., 15.]]) + >>> torch.hsplit(t, 2) + (tensor([[ 0., 1.], + [ 4., 5.], + [ 8., 9.], + [12., 13.]]), + tensor([[ 2., 3.], + [ 6., 7.], + [10., 11.], + [14., 15.]])) + >>> torch.hsplit(t, [3, 6]) + (tensor([[ 0., 1., 2.], + [ 4., 5., 6.], + [ 8., 9., 10.], + [12., 13., 14.]]), + tensor([[ 3.], + [ 7.], + [11.], + [15.]]), + tensor([], size=(4, 0))) + +""", +) + +add_docstr( + torch.vsplit, + r""" +vsplit(input, indices_or_sections) -> List of Tensors + +Splits :attr:`input`, a tensor with two or more dimensions, into multiple tensors +vertically according to :attr:`indices_or_sections`. Each split is a view of +:attr:`input`. + +This is equivalent to calling torch.tensor_split(input, indices_or_sections, dim=0) +(the split dimension is 0), except that if :attr:`indices_or_sections` is an integer +it must evenly divide the split dimension or a runtime error will be thrown. + +This function is based on NumPy's :func:`numpy.vsplit`. + +Args: + input (Tensor): tensor to split. + indices_or_sections (int or list or tuple of ints): See argument in :func:`torch.tensor_split`. + +Example:: + + >>> t = torch.arange(16.0).reshape(4,4) + >>> t + tensor([[ 0., 1., 2., 3.], + [ 4., 5., 6., 7.], + [ 8., 9., 10., 11.], + [12., 13., 14., 15.]]) + >>> torch.vsplit(t, 2) + (tensor([[0., 1., 2., 3.], + [4., 5., 6., 7.]]), + tensor([[ 8., 9., 10., 11.], + [12., 13., 14., 15.]])) + >>> torch.vsplit(t, [3, 6]) + (tensor([[ 0., 1., 2., 3.], + [ 4., 5., 6., 7.], + [ 8., 9., 10., 11.]]), + tensor([[12., 13., 14., 15.]]), + tensor([], size=(0, 4))) + +""", +) + +add_docstr( + torch.dsplit, + r""" +dsplit(input, indices_or_sections) -> List of Tensors + +Splits :attr:`input`, a tensor with three or more dimensions, into multiple tensors +depthwise according to :attr:`indices_or_sections`. Each split is a view of +:attr:`input`. + +This is equivalent to calling torch.tensor_split(input, indices_or_sections, dim=2) +(the split dimension is 2), except that if :attr:`indices_or_sections` is an integer +it must evenly divide the split dimension or a runtime error will be thrown. + +This function is based on NumPy's :func:`numpy.dsplit`. + +Args: + input (Tensor): tensor to split. + indices_or_sections (int or list or tuple of ints): See argument in :func:`torch.tensor_split`. + +Example:: + + >>> t = torch.arange(16.0).reshape(2, 2, 4) + >>> t + tensor([[[ 0., 1., 2., 3.], + [ 4., 5., 6., 7.]], + [[ 8., 9., 10., 11.], + [12., 13., 14., 15.]]]) + >>> torch.dsplit(t, 2) + (tensor([[[ 0., 1.], + [ 4., 5.]], + [[ 8., 9.], + [12., 13.]]]), + tensor([[[ 2., 3.], + [ 6., 7.]], + [[10., 11.], + [14., 15.]]])) + + >>> torch.dsplit(t, [3, 6]) + (tensor([[[ 0., 1., 2.], + [ 4., 5., 6.]], + [[ 8., 9., 10.], + [12., 13., 14.]]]), + tensor([[[ 3.], + [ 7.]], + [[11.], + [15.]]]), + tensor([], size=(2, 2, 0))) + +""", +) + +add_docstr( + torch.can_cast, + r""" +can_cast(from_, to) -> bool + +Determines if a type conversion is allowed under PyTorch casting rules +described in the type promotion :ref:`documentation `. + +Args: + from\_ (dtype): The original :class:`torch.dtype`. + to (dtype): The target :class:`torch.dtype`. + +Example:: + + >>> torch.can_cast(torch.double, torch.float) + True + >>> torch.can_cast(torch.float, torch.int) + False +""", +) + +add_docstr( + torch.corrcoef, + r""" +corrcoef(input) -> Tensor + +Estimates the Pearson product-moment correlation coefficient matrix of the variables given by the :attr:`input` matrix, +where rows are the variables and columns are the observations. + +.. note:: + + The correlation coefficient matrix R is computed using the covariance matrix C as given by + :math:`R_{ij} = \frac{ C_{ij} } { \sqrt{ C_{ii} * C_{jj} } }` + +.. note:: + + Due to floating point rounding, the resulting array may not be Hermitian and its diagonal elements may not be 1. + The real and imaginary values are clipped to the interval [-1, 1] in an attempt to improve this situation. + +Args: + input (Tensor): A 2D matrix containing multiple variables and observations, or a + Scalar or 1D vector representing a single variable. + +Returns: + (Tensor) The correlation coefficient matrix of the variables. + +.. seealso:: + + :func:`torch.cov` covariance matrix. + +Example:: + + >>> x = torch.tensor([[0, 1, 2], [2, 1, 0]]) + >>> torch.corrcoef(x) + tensor([[ 1., -1.], + [-1., 1.]]) + >>> x = torch.randn(2, 4) + >>> x + tensor([[-0.2678, -0.0908, -0.3766, 0.2780], + [-0.5812, 0.1535, 0.2387, 0.2350]]) + >>> torch.corrcoef(x) + tensor([[1.0000, 0.3582], + [0.3582, 1.0000]]) + >>> torch.corrcoef(x[0]) + tensor(1.) +""", +) + +add_docstr( + torch.cov, + r""" +cov(input, *, correction=1, fweights=None, aweights=None) -> Tensor + +Estimates the covariance matrix of the variables given by the :attr:`input` matrix, where rows are +the variables and columns are the observations. + +A covariance matrix is a square matrix giving the covariance of each pair of variables. The diagonal contains +the variance of each variable (covariance of a variable with itself). By definition, if :attr:`input` represents +a single variable (Scalar or 1D) then its variance is returned. + +The sample covariance of the variables :math:`x` and :math:`y` is given by: + +.. math:: + \text{cov}(x,y) = \frac{\sum^{N}_{i = 1}(x_{i} - \bar{x})(y_{i} - \bar{y})}{\max(0,~N~-~\delta N)} + +where :math:`\bar{x}` and :math:`\bar{y}` are the simple means of the :math:`x` and :math:`y` respectively, and +:math:`\delta N` is the :attr:`correction`. + +If :attr:`fweights` and/or :attr:`aweights` are provided, the weighted covariance +is calculated, which is given by: + +.. math:: + \text{cov}_w(x,y) = \frac{\sum^{N}_{i = 1}w_i(x_{i} - \mu_x^*)(y_{i} - \mu_y^*)} + {\max(0,~\sum^{N}_{i = 1}w_i~-~\frac{\sum^{N}_{i = 1}w_ia_i}{\sum^{N}_{i = 1}w_i}~\delta N)} + +where :math:`w` denotes :attr:`fweights` or :attr:`aweights` (``f`` and ``a`` for brevity) based on whichever is +provided, or :math:`w = f \times a` if both are provided, and +:math:`\mu_x^* = \frac{\sum^{N}_{i = 1}w_ix_{i} }{\sum^{N}_{i = 1}w_i}` is the weighted mean of the variable. If not +provided, ``f`` and/or ``a`` can be seen as a :math:`\mathbb{1}` vector of appropriate size. + +Args: + input (Tensor): A 2D matrix containing multiple variables and observations, or a + Scalar or 1D vector representing a single variable. + +Keyword Args: + correction (int, optional): difference between the sample size and sample degrees of freedom. + Defaults to Bessel's correction, ``correction = 1`` which returns the unbiased estimate, + even if both :attr:`fweights` and :attr:`aweights` are specified. ``correction = 0`` + will return the simple average. Defaults to ``1``. + fweights (tensor, optional): A Scalar or 1D tensor of observation vector frequencies representing the number of + times each observation should be repeated. Its numel must equal the number of columns of :attr:`input`. + Must have integral dtype. Ignored if ``None``. Defaults to ``None``. + aweights (tensor, optional): A Scalar or 1D array of observation vector weights. + These relative weights are typically large for observations considered "important" and smaller for + observations considered less "important". Its numel must equal the number of columns of :attr:`input`. + Must have floating point dtype. Ignored if ``None``. Defaults to ``None``. + +Returns: + (Tensor) The covariance matrix of the variables. + +.. seealso:: + + :func:`torch.corrcoef` normalized covariance matrix. + +Example:: + + >>> x = torch.tensor([[0, 2], [1, 1], [2, 0]]).T + >>> x + tensor([[0, 1, 2], + [2, 1, 0]]) + >>> torch.cov(x) + tensor([[ 1., -1.], + [-1., 1.]]) + >>> torch.cov(x, correction=0) + tensor([[ 0.6667, -0.6667], + [-0.6667, 0.6667]]) + >>> fw = torch.randint(1, 10, (3,)) + >>> fw + tensor([1, 6, 9]) + >>> aw = torch.rand(3) + >>> aw + tensor([0.4282, 0.0255, 0.4144]) + >>> torch.cov(x, fweights=fw, aweights=aw) + tensor([[ 0.4169, -0.4169], + [-0.4169, 0.4169]]) +""", +) + +add_docstr( + torch.cat, + r""" +cat(tensors, dim=0, *, out=None) -> Tensor + +Concatenates the given sequence of tensors in :attr:`tensors` in the given dimension. +All tensors must either have the same shape (except in the concatenating +dimension) or be a 1-D empty tensor with size ``(0,)``. + +:func:`torch.cat` can be seen as an inverse operation for :func:`torch.split` +and :func:`torch.chunk`. + +:func:`torch.cat` can be best understood via examples. + +.. seealso:: + + :func:`torch.stack` concatenates the given sequence along a new dimension. + +Args: + tensors (sequence of Tensors): Non-empty tensors provided must have the same shape, + except in the cat dimension. + + dim (int, optional): the dimension over which the tensors are concatenated + +Keyword args: + {out} + +Example:: + + >>> x = torch.randn(2, 3) + >>> x + tensor([[ 0.6580, -1.0969, -0.4614], + [-0.1034, -0.5790, 0.1497]]) + >>> torch.cat((x, x, x), 0) + tensor([[ 0.6580, -1.0969, -0.4614], + [-0.1034, -0.5790, 0.1497], + [ 0.6580, -1.0969, -0.4614], + [-0.1034, -0.5790, 0.1497], + [ 0.6580, -1.0969, -0.4614], + [-0.1034, -0.5790, 0.1497]]) + >>> torch.cat((x, x, x), 1) + tensor([[ 0.6580, -1.0969, -0.4614, 0.6580, -1.0969, -0.4614, 0.6580, + -1.0969, -0.4614], + [-0.1034, -0.5790, 0.1497, -0.1034, -0.5790, 0.1497, -0.1034, + -0.5790, 0.1497]]) +""".format(**common_args), +) + +add_docstr( + torch.concat, + r""" +concat(tensors, dim=0, *, out=None) -> Tensor + +Alias of :func:`torch.cat`. +""", +) + +add_docstr( + torch.concatenate, + r""" +concatenate(tensors, axis=0, out=None) -> Tensor + +Alias of :func:`torch.cat`. +""", +) + +add_docstr( + torch.ceil, + r""" +ceil(input, *, out=None) -> Tensor + +Returns a new tensor with the ceil of the elements of :attr:`input`, +the smallest integer greater than or equal to each element. + +For integer inputs, follows the array-api convention of returning a +copy of the input tensor. + +.. math:: + \text{out}_{i} = \left\lceil \text{input}_{i} \right\rceil +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-0.6341, -1.4208, -1.0900, 0.5826]) + >>> torch.ceil(a) + tensor([-0., -1., -1., 1.]) +""".format(**common_args), +) + +add_docstr( + torch.real, + r""" +real(input) -> Tensor + +Returns a new tensor containing real values of the :attr:`self` tensor. +The returned tensor and :attr:`self` share the same underlying storage. + +Args: + {input} + +Example:: + + >>> x=torch.randn(4, dtype=torch.cfloat) + >>> x + tensor([(0.3100+0.3553j), (-0.5445-0.7896j), (-1.6492-0.0633j), (-0.0638-0.8119j)]) + >>> x.real + tensor([ 0.3100, -0.5445, -1.6492, -0.0638]) + +""".format(**common_args), +) + +add_docstr( + torch.imag, + r""" +imag(input) -> Tensor + +Returns a new tensor containing imaginary values of the :attr:`self` tensor. +The returned tensor and :attr:`self` share the same underlying storage. + +.. warning:: + :func:`imag` is only supported for tensors with complex dtypes. + +Args: + {input} + +Example:: + + >>> x=torch.randn(4, dtype=torch.cfloat) + >>> x + tensor([(0.3100+0.3553j), (-0.5445-0.7896j), (-1.6492-0.0633j), (-0.0638-0.8119j)]) + >>> x.imag + tensor([ 0.3553, -0.7896, -0.0633, -0.8119]) + +""".format(**common_args), +) + +add_docstr( + torch.view_as_real, + r""" +view_as_real(input) -> Tensor + +Returns a view of :attr:`input` as a real tensor. For an input complex tensor of +:attr:`size` :math:`m1, m2, \dots, mi`, this function returns a new +real tensor of size :math:`m1, m2, \dots, mi, 2`, where the last dimension of size 2 +represents the real and imaginary components of complex numbers. + +.. warning:: + :func:`view_as_real` is only supported for tensors with ``complex dtypes``. + +Args: + {input} + +Example:: + + >>> x=torch.randn(4, dtype=torch.cfloat) + >>> x + tensor([(0.4737-0.3839j), (-0.2098-0.6699j), (0.3470-0.9451j), (-0.5174-1.3136j)]) + >>> torch.view_as_real(x) + tensor([[ 0.4737, -0.3839], + [-0.2098, -0.6699], + [ 0.3470, -0.9451], + [-0.5174, -1.3136]]) +""".format(**common_args), +) + +add_docstr( + torch.view_as_complex, + r""" +view_as_complex(input) -> Tensor + +Returns a view of :attr:`input` as a complex tensor. For an input complex +tensor of :attr:`size` :math:`m1, m2, \dots, mi, 2`, this function returns a +new complex tensor of :attr:`size` :math:`m1, m2, \dots, mi` where the last +dimension of the input tensor is expected to represent the real and imaginary +components of complex numbers. + +.. warning:: + :func:`view_as_complex` is only supported for tensors with + :class:`torch.dtype` ``torch.float64`` and ``torch.float32``. The input is + expected to have the last dimension of :attr:`size` 2. In addition, the + tensor must have a `stride` of 1 for its last dimension. The strides of all + other dimensions must be even numbers. + +Args: + {input} + +Example:: + + >>> x=torch.randn(4, 2) + >>> x + tensor([[ 1.6116, -0.5772], + [-1.4606, -0.9120], + [ 0.0786, -1.7497], + [-0.6561, -1.6623]]) + >>> torch.view_as_complex(x) + tensor([(1.6116-0.5772j), (-1.4606-0.9120j), (0.0786-1.7497j), (-0.6561-1.6623j)]) +""".format(**common_args), +) + +add_docstr( + torch.reciprocal, + r""" +reciprocal(input, *, out=None) -> Tensor + +Returns a new tensor with the reciprocal of the elements of :attr:`input` + +.. math:: + \text{out}_{i} = \frac{1}{\text{input}_{i}} + +.. note:: + Unlike NumPy's reciprocal, torch.reciprocal supports integral inputs. Integral + inputs to reciprocal are automatically :ref:`promoted ` to + the default scalar type. +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-0.4595, -2.1219, -1.4314, 0.7298]) + >>> torch.reciprocal(a) + tensor([-2.1763, -0.4713, -0.6986, 1.3702]) +""".format(**common_args), +) + +add_docstr( + torch.cholesky, + r""" +cholesky(input, upper=False, *, out=None) -> Tensor + +Computes the Cholesky decomposition of a symmetric positive-definite +matrix :math:`A` or for batches of symmetric positive-definite matrices. + +If :attr:`upper` is ``True``, the returned matrix ``U`` is upper-triangular, and +the decomposition has the form: + +.. math:: + + A = U^TU + +If :attr:`upper` is ``False``, the returned matrix ``L`` is lower-triangular, and +the decomposition has the form: + +.. math:: + + A = LL^T + +If :attr:`upper` is ``True``, and :math:`A` is a batch of symmetric positive-definite +matrices, then the returned tensor will be composed of upper-triangular Cholesky factors +of each of the individual matrices. Similarly, when :attr:`upper` is ``False``, the returned +tensor will be composed of lower-triangular Cholesky factors of each of the individual +matrices. + +.. warning:: + + :func:`torch.cholesky` is deprecated in favor of :func:`torch.linalg.cholesky` + and will be removed in a future PyTorch release. + + ``L = torch.cholesky(A)`` should be replaced with + + .. code:: python + + L = torch.linalg.cholesky(A) + + ``U = torch.cholesky(A, upper=True)`` should be replaced with + + .. code:: python + + U = torch.linalg.cholesky(A).mH + + This transform will produce equivalent results for all valid (symmetric positive definite) inputs. + +Args: + input (Tensor): the input tensor :math:`A` of size :math:`(*, n, n)` where `*` is zero or more + batch dimensions consisting of symmetric positive-definite matrices. + upper (bool, optional): flag that indicates whether to return a + upper or lower triangular matrix. Default: ``False`` + +Keyword args: + out (Tensor, optional): the output matrix + +Example:: + + >>> a = torch.randn(3, 3) + >>> a = a @ a.mT + 1e-3 # make symmetric positive-definite + >>> l = torch.cholesky(a) + >>> a + tensor([[ 2.4112, -0.7486, 1.4551], + [-0.7486, 1.3544, 0.1294], + [ 1.4551, 0.1294, 1.6724]]) + >>> l + tensor([[ 1.5528, 0.0000, 0.0000], + [-0.4821, 1.0592, 0.0000], + [ 0.9371, 0.5487, 0.7023]]) + >>> l @ l.mT + tensor([[ 2.4112, -0.7486, 1.4551], + [-0.7486, 1.3544, 0.1294], + [ 1.4551, 0.1294, 1.6724]]) + >>> a = torch.randn(3, 2, 2) # Example for batched input + >>> a = a @ a.mT + 1e-03 # make symmetric positive-definite + >>> l = torch.cholesky(a) + >>> z = l @ l.mT + >>> torch.dist(z, a) + tensor(2.3842e-07) +""", +) + +add_docstr( + torch.cholesky_solve, + r""" +cholesky_solve(B, L, upper=False, *, out=None) -> Tensor + +Computes the solution of a system of linear equations with complex Hermitian +or real symmetric positive-definite lhs given its Cholesky decomposition. + +Let :math:`A` be a complex Hermitian or real symmetric positive-definite matrix, +and :math:`L` its Cholesky decomposition such that: + +.. math:: + + A = LL^{\text{H}} + +where :math:`L^{\text{H}}` is the conjugate transpose when :math:`L` is complex, +and the transpose when :math:`L` is real-valued. + +Returns the solution :math:`X` of the following linear system: + +.. math:: + + AX = B + +Supports inputs of float, double, cfloat and cdouble dtypes. +Also supports batches of matrices, and if :math:`A` or :math:`B` is a batch of matrices +then the output has the same batch dimensions. + +Args: + B (Tensor): right-hand side tensor of shape `(*, n, k)` + where :math:`*` is zero or more batch dimensions + L (Tensor): tensor of shape `(*, n, n)` where `*` is zero or more batch dimensions + consisting of lower or upper triangular Cholesky decompositions of + symmetric or Hermitian positive-definite matrices. + upper (bool, optional): flag that indicates whether :math:`L` is lower triangular + or upper triangular. Default: ``False``. + +Keyword args: + out (Tensor, optional): output tensor. Ignored if `None`. Default: `None`. + +Example:: + + >>> A = torch.randn(3, 3) + >>> A = A @ A.T + torch.eye(3) * 1e-3 # Creates a symmetric positive-definite matrix + >>> L = torch.linalg.cholesky(A) # Extract Cholesky decomposition + >>> B = torch.randn(3, 2) + >>> torch.cholesky_solve(B, L) + tensor([[ -8.1625, 19.6097], + [ -5.8398, 14.2387], + [ -4.3771, 10.4173]]) + >>> A.inverse() @ B + tensor([[ -8.1626, 19.6097], + [ -5.8398, 14.2387], + [ -4.3771, 10.4173]]) + + >>> A = torch.randn(3, 2, 2, dtype=torch.complex64) + >>> A = A @ A.mH + torch.eye(2) * 1e-3 # Batch of Hermitian positive-definite matrices + >>> L = torch.linalg.cholesky(A) + >>> B = torch.randn(2, 1, dtype=torch.complex64) + >>> X = torch.cholesky_solve(B, L) + >>> torch.dist(X, A.inverse() @ B) + tensor(1.6881e-5) +""", +) + +add_docstr( + torch.cholesky_inverse, + r""" +cholesky_inverse(L, upper=False, *, out=None) -> Tensor + +Computes the inverse of a complex Hermitian or real symmetric +positive-definite matrix given its Cholesky decomposition. + +Let :math:`A` be a complex Hermitian or real symmetric positive-definite matrix, +and :math:`L` its Cholesky decomposition such that: + +.. math:: + + A = LL^{\text{H}} + +where :math:`L^{\text{H}}` is the conjugate transpose when :math:`L` is complex, +and the transpose when :math:`L` is real-valued. + +Computes the inverse matrix :math:`A^{-1}`. + +Supports input of float, double, cfloat and cdouble dtypes. +Also supports batches of matrices, and if :math:`A` is a batch of matrices +then the output has the same batch dimensions. + +Args: + L (Tensor): tensor of shape `(*, n, n)` where `*` is zero or more batch dimensions + consisting of lower or upper triangular Cholesky decompositions of + symmetric or Hermitian positive-definite matrices. + upper (bool, optional): flag that indicates whether :math:`L` is lower triangular + or upper triangular. Default: ``False`` + +Keyword args: + out (Tensor, optional): output tensor. Ignored if `None`. Default: `None`. + +Example:: + + >>> A = torch.randn(3, 3) + >>> A = A @ A.T + torch.eye(3) * 1e-3 # Creates a symmetric positive-definite matrix + >>> L = torch.linalg.cholesky(A) # Extract Cholesky decomposition + >>> torch.cholesky_inverse(L) + tensor([[ 1.9314, 1.2251, -0.0889], + [ 1.2251, 2.4439, 0.2122], + [-0.0889, 0.2122, 0.1412]]) + >>> A.inverse() + tensor([[ 1.9314, 1.2251, -0.0889], + [ 1.2251, 2.4439, 0.2122], + [-0.0889, 0.2122, 0.1412]]) + + >>> A = torch.randn(3, 2, 2, dtype=torch.complex64) + >>> A = A @ A.mH + torch.eye(2) * 1e-3 # Batch of Hermitian positive-definite matrices + >>> L = torch.linalg.cholesky(A) + >>> torch.dist(torch.inverse(A), torch.cholesky_inverse(L)) + tensor(5.6358e-7) +""", +) + +add_docstr( + torch.clone, + r""" +clone(input, *, memory_format=torch.preserve_format) -> Tensor + +Returns a copy of :attr:`input`. + +.. note:: + + This function is differentiable, so gradients will flow back from the + result of this operation to :attr:`input`. To create a tensor without an + autograd relationship to :attr:`input` see :meth:`~Tensor.detach`. + + In addition, when ``torch.preserve_format`` is used: + If the input tensor is dense (i.e., non-overlapping strided), + its memory format (including strides) is retained. + Otherwise (e.g., a non-dense view like a stepped slice), + the output is converted to the dense (contiguous) format. + +Args: + {input} + +Keyword args: + {memory_format} +""".format(**common_args), +) + +add_docstr( + torch.clamp, + r""" +clamp(input, min=None, max=None, *, out=None) -> Tensor + +Clamps all elements in :attr:`input` into the range `[` :attr:`min`, :attr:`max` `]`. +Letting min_value and max_value be :attr:`min` and :attr:`max`, respectively, this returns: + +.. math:: + y_i = \min(\max(x_i, \text{min\_value}_i), \text{max\_value}_i) + +If :attr:`min` is ``None``, there is no lower bound. +Or, if :attr:`max` is ``None`` there is no upper bound. +""" + + r""" + +.. note:: + If :attr:`min` is greater than :attr:`max` :func:`torch.clamp(..., min, max) ` + sets all elements in :attr:`input` to the value of :attr:`max`. + +Args: + {input} + min (Number or Tensor, optional): lower-bound of the range to be clamped to + max (Number or Tensor, optional): upper-bound of the range to be clamped to + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-1.7120, 0.1734, -0.0478, -0.0922]) + >>> torch.clamp(a, min=-0.5, max=0.5) + tensor([-0.5000, 0.1734, -0.0478, -0.0922]) + + >>> min = torch.linspace(-1, 1, steps=4) + >>> torch.clamp(a, min=min) + tensor([-1.0000, 0.1734, 0.3333, 1.0000]) + +""".format(**common_args), +) + +add_docstr( + torch.clip, + r""" +clip(input, min=None, max=None, *, out=None) -> Tensor + +Alias for :func:`torch.clamp`. +""", +) + +add_docstr( + torch.column_stack, + r""" +column_stack(tensors, *, out=None) -> Tensor + +Creates a new tensor by horizontally stacking the tensors in :attr:`tensors`. + +Equivalent to ``torch.hstack(tensors)``, except each zero or one dimensional tensor ``t`` +in :attr:`tensors` is first reshaped into a ``(t.numel(), 1)`` column before being stacked horizontally. + +Args: + tensors (sequence of Tensors): sequence of tensors to concatenate + +Keyword args: + {out} + +Example:: + + >>> a = torch.tensor([1, 2, 3]) + >>> b = torch.tensor([4, 5, 6]) + >>> torch.column_stack((a, b)) + tensor([[1, 4], + [2, 5], + [3, 6]]) + >>> a = torch.arange(5) + >>> b = torch.arange(10).reshape(5, 2) + >>> torch.column_stack((a, b, b)) + tensor([[0, 0, 1, 0, 1], + [1, 2, 3, 2, 3], + [2, 4, 5, 4, 5], + [3, 6, 7, 6, 7], + [4, 8, 9, 8, 9]]) + +""".format(**common_args), +) + +add_docstr( + torch.complex, + r""" +complex(real, imag, *, out=None) -> Tensor + +Constructs a complex tensor with its real part equal to :attr:`real` and its +imaginary part equal to :attr:`imag`. + +Args: + real (Tensor): The real part of the complex tensor. Must be half, float or double. + imag (Tensor): The imaginary part of the complex tensor. Must be same dtype + as :attr:`real`. + +Keyword args: + out (Tensor): If the inputs are ``torch.float32``, must be + ``torch.complex64``. If the inputs are ``torch.float64``, must be + ``torch.complex128``. + +Example:: + + >>> real = torch.tensor([1, 2], dtype=torch.float32) + >>> imag = torch.tensor([3, 4], dtype=torch.float32) + >>> z = torch.complex(real, imag) + >>> z + tensor([(1.+3.j), (2.+4.j)]) + >>> z.dtype + torch.complex64 + +""", +) + +add_docstr( + torch.polar, + r""" +polar(abs, angle, *, out=None) -> Tensor + +Constructs a complex tensor whose elements are Cartesian coordinates +corresponding to the polar coordinates with absolute value :attr:`abs` and angle +:attr:`angle`. + +.. math:: + \text{out} = \text{abs} \cdot \cos(\text{angle}) + \text{abs} \cdot \sin(\text{angle}) \cdot j + +.. note:: + `torch.polar` is similar to + `std::polar `_ + and does not compute the polar decomposition + of a complex tensor like Python's `cmath.polar` and SciPy's `linalg.polar` do. + The behavior of this function is undefined if `abs` is negative or NaN, or if `angle` is + infinite. + +""" + + r""" +Args: + abs (Tensor): The absolute value the complex tensor. Must be float or double. + angle (Tensor): The angle of the complex tensor. Must be same dtype as + :attr:`abs`. + +Keyword args: + out (Tensor): If the inputs are ``torch.float32``, must be + ``torch.complex64``. If the inputs are ``torch.float64``, must be + ``torch.complex128``. + +Example:: + + >>> import numpy as np + >>> abs = torch.tensor([1, 2], dtype=torch.float64) + >>> angle = torch.tensor([np.pi / 2, 5 * np.pi / 4], dtype=torch.float64) + >>> z = torch.polar(abs, angle) + >>> z + tensor([(0.0000+1.0000j), (-1.4142-1.4142j)], dtype=torch.complex128) +""", +) + +add_docstr( + torch.conj_physical, + r""" +conj_physical(input, *, out=None) -> Tensor + +Computes the element-wise conjugate of the given :attr:`input` tensor. +If :attr:`input` has a non-complex dtype, this function just returns :attr:`input`. + +.. note:: + This performs the conjugate operation regardless of the fact conjugate bit is set or not. + +.. warning:: In the future, :func:`torch.conj_physical` may return a non-writeable view for an :attr:`input` of + non-complex dtype. It's recommended that programs not modify the tensor returned by :func:`torch.conj_physical` + when :attr:`input` is of non-complex dtype to be compatible with this change. + +.. math:: + \text{out}_{i} = conj(\text{input}_{i}) +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> torch.conj_physical(torch.tensor([-1 + 1j, -2 + 2j, 3 - 3j])) + tensor([-1 - 1j, -2 - 2j, 3 + 3j]) +""".format(**common_args), +) + +add_docstr( + torch.conj, + r""" +conj(input) -> Tensor + +Returns a view of :attr:`input` with a flipped conjugate bit. If :attr:`input` has a non-complex dtype, +this function just returns :attr:`input`. + +.. note:: + :func:`torch.conj` performs a lazy conjugation, but the actual conjugated tensor can be materialized + at any time using :func:`torch.resolve_conj`. + +.. warning:: In the future, :func:`torch.conj` may return a non-writeable view for an :attr:`input` of + non-complex dtype. It's recommended that programs not modify the tensor returned by :func:`torch.conj_physical` + when :attr:`input` is of non-complex dtype to be compatible with this change. + +Args: + {input} + +Example:: + + >>> x = torch.tensor([-1 + 1j, -2 + 2j, 3 - 3j]) + >>> x.is_conj() + False + >>> y = torch.conj(x) + >>> y.is_conj() + True +""".format(**common_args), +) + +add_docstr( + torch.resolve_conj, + r""" +resolve_conj(input) -> Tensor + +Returns a new tensor with materialized conjugation if :attr:`input`'s conjugate bit is set to `True`, +else returns :attr:`input`. The output tensor will always have its conjugate bit set to `False`. + +Args: + {input} + +Example:: + + >>> x = torch.tensor([-1 + 1j, -2 + 2j, 3 - 3j]) + >>> y = x.conj() + >>> y.is_conj() + True + >>> z = y.resolve_conj() + >>> z + tensor([-1 - 1j, -2 - 2j, 3 + 3j]) + >>> z.is_conj() + False +""".format(**common_args), +) + +add_docstr( + torch.resolve_neg, + r""" +resolve_neg(input) -> Tensor + +Returns a new tensor with materialized negation if :attr:`input`'s negative bit is set to `True`, +else returns :attr:`input`. The output tensor will always have its negative bit set to `False`. + +Args: + {input} + +Example:: + + >>> x = torch.tensor([-1 + 1j, -2 + 2j, 3 - 3j]) + >>> y = x.conj() + >>> z = y.imag + >>> z.is_neg() + True + >>> out = z.resolve_neg() + >>> out + tensor([-1., -2., 3.]) + >>> out.is_neg() + False +""".format(**common_args), +) + +add_docstr( + torch.copysign, + r""" +copysign(input, other, *, out=None) -> Tensor + +Create a new floating-point tensor with the magnitude of :attr:`input` and the sign of :attr:`other`, elementwise. + +.. math:: + \text{out}_{i} = \begin{cases} + -|\text{input}_{i}| & \text{if } \text{other}_{i} \leq -0.0 \\ + |\text{input}_{i}| & \text{if } \text{other}_{i} \geq 0.0 \\ + \end{cases} +""" + + r""" + +Supports :ref:`broadcasting to a common shape `, +and integer and float inputs. + +Args: + input (Tensor): magnitudes. + other (Tensor or Number): contains value(s) whose signbit(s) are + applied to the magnitudes in :attr:`input`. + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(5) + >>> a + tensor([-1.2557, -0.0026, -0.5387, 0.4740, -0.9244]) + >>> torch.copysign(a, 1) + tensor([1.2557, 0.0026, 0.5387, 0.4740, 0.9244]) + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.7079, 0.2778, -1.0249, 0.5719], + [-0.0059, -0.2600, -0.4475, -1.3948], + [ 0.3667, -0.9567, -2.5757, -0.1751], + [ 0.2046, -0.0742, 0.2998, -0.1054]]) + >>> b = torch.randn(4) + tensor([ 0.2373, 0.3120, 0.3190, -1.1128]) + >>> torch.copysign(a, b) + tensor([[ 0.7079, 0.2778, 1.0249, -0.5719], + [ 0.0059, 0.2600, 0.4475, -1.3948], + [ 0.3667, 0.9567, 2.5757, -0.1751], + [ 0.2046, 0.0742, 0.2998, -0.1054]]) + >>> a = torch.tensor([1.]) + >>> b = torch.tensor([-0.]) + >>> torch.copysign(a, b) + tensor([-1.]) + +.. note:: + copysign handles signed zeros. If the other argument has a negative zero (-0), + the corresponding output value will be negative. + +""".format(**common_args), +) + +add_docstr( + torch.cos, + r""" +cos(input, *, out=None) -> Tensor + +Returns a new tensor with the cosine of the elements of :attr:`input` given in radians. + +.. math:: + \text{out}_{i} = \cos(\text{input}_{i}) +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 1.4309, 1.2706, -0.8562, 0.9796]) + >>> torch.cos(a) + tensor([ 0.1395, 0.2957, 0.6553, 0.5574]) +""".format(**common_args), +) + +add_docstr( + torch.cosh, + r""" +cosh(input, *, out=None) -> Tensor + +Returns a new tensor with the hyperbolic cosine of the elements of +:attr:`input`. + +.. math:: + \text{out}_{i} = \cosh(\text{input}_{i}) +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.1632, 1.1835, -0.6979, -0.7325]) + >>> torch.cosh(a) + tensor([ 1.0133, 1.7860, 1.2536, 1.2805]) + +.. note:: + When :attr:`input` is on the CPU, the implementation of torch.cosh may use + the Sleef library, which rounds very large results to infinity or negative + infinity. See `here `_ for details. +""".format(**common_args), +) + +add_docstr( + torch.cross, + r""" +cross(input, other, dim=None, *, out=None) -> Tensor + + +Returns the cross product of vectors in dimension :attr:`dim` of :attr:`input` +and :attr:`other`. + +Supports input of float, double, cfloat and cdouble dtypes. Also supports batches +of vectors, for which it computes the product along the dimension :attr:`dim`. +In this case, the output has the same batch dimensions as the inputs. + +.. warning:: + If :attr:`dim` is not given, it defaults to the first dimension found + with the size 3. Note that this might be unexpected. + + This behavior is deprecated and will be changed to match that of :func:`torch.linalg.cross` + in a future release. + +.. seealso:: + :func:`torch.linalg.cross` which has dim=-1 as default. + + +Args: + {input} + other (Tensor): the second input tensor + dim (int, optional): the dimension to take the cross-product in. + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4, 3) + >>> a + tensor([[-0.3956, 1.1455, 1.6895], + [-0.5849, 1.3672, 0.3599], + [-1.1626, 0.7180, -0.0521], + [-0.1339, 0.9902, -2.0225]]) + >>> b = torch.randn(4, 3) + >>> b + tensor([[-0.0257, -1.4725, -1.2251], + [-1.1479, -0.7005, -1.9757], + [-1.3904, 0.3726, -1.1836], + [-0.9688, -0.7153, 0.2159]]) + >>> torch.cross(a, b, dim=1) + tensor([[ 1.0844, -0.5281, 0.6120], + [-2.4490, -1.5687, 1.9792], + [-0.8304, -1.3037, 0.5650], + [-1.2329, 1.9883, 1.0551]]) + >>> torch.cross(a, b) + tensor([[ 1.0844, -0.5281, 0.6120], + [-2.4490, -1.5687, 1.9792], + [-0.8304, -1.3037, 0.5650], + [-1.2329, 1.9883, 1.0551]]) +""".format(**common_args), +) + +add_docstr( + torch.logcumsumexp, + r""" +logcumsumexp(input, dim, *, out=None) -> Tensor +Returns the logarithm of the cumulative summation of the exponentiation of +elements of :attr:`input` in the dimension :attr:`dim`. + +For summation index :math:`j` given by `dim` and other indices :math:`i`, the result is + + .. math:: + \text{{logcumsumexp}}(x)_{{ij}} = \log \sum\limits_{{k=0}}^{{j}} \exp(x_{{ik}}) + +Args: + {input} + dim (int): the dimension to do the operation over + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(10) + >>> torch.logcumsumexp(a, dim=0) + tensor([-0.42296738, -0.04462666, 0.86278635, 0.94622083, 1.05277811, + 1.39202815, 1.83525007, 1.84492621, 2.06084887, 2.06844475])) +""".format(**reduceops_common_args), +) + +add_docstr( + torch.cummax, + r""" +cummax(input, dim, *, out=None) -> (Tensor, LongTensor) +Returns a namedtuple ``(values, indices)`` where ``values`` is the cumulative maximum of +elements of :attr:`input` in the dimension :attr:`dim`. And ``indices`` is the index +location of each maximum value found in the dimension :attr:`dim`. + +.. math:: + y_i = max(x_1, x_2, x_3, \dots, x_i) + +Args: + {input} + dim (int): the dimension to do the operation over + +Keyword args: + out (tuple, optional): the result tuple of two output tensors (values, indices) + +Example:: + + >>> a = torch.randn(10) + >>> a + tensor([-0.3449, -1.5447, 0.0685, -1.5104, -1.1706, 0.2259, 1.4696, -1.3284, + 1.9946, -0.8209]) + >>> torch.cummax(a, dim=0) + torch.return_types.cummax( + values=tensor([-0.3449, -0.3449, 0.0685, 0.0685, 0.0685, 0.2259, 1.4696, 1.4696, + 1.9946, 1.9946]), + indices=tensor([0, 0, 2, 2, 2, 5, 6, 6, 8, 8])) +""".format(**reduceops_common_args), +) + +add_docstr( + torch.cummin, + r""" +cummin(input, dim, *, out=None) -> (Tensor, LongTensor) +Returns a namedtuple ``(values, indices)`` where ``values`` is the cumulative minimum of +elements of :attr:`input` in the dimension :attr:`dim`. And ``indices`` is the index +location of each maximum value found in the dimension :attr:`dim`. + +.. math:: + y_i = min(x_1, x_2, x_3, \dots, x_i) + +Args: + {input} + dim (int): the dimension to do the operation over + +Keyword args: + out (tuple, optional): the result tuple of two output tensors (values, indices) + +Example:: + + >>> a = torch.randn(10) + >>> a + tensor([-0.2284, -0.6628, 0.0975, 0.2680, -1.3298, -0.4220, -0.3885, 1.1762, + 0.9165, 1.6684]) + >>> torch.cummin(a, dim=0) + torch.return_types.cummin( + values=tensor([-0.2284, -0.6628, -0.6628, -0.6628, -1.3298, -1.3298, -1.3298, -1.3298, + -1.3298, -1.3298]), + indices=tensor([0, 1, 1, 1, 4, 4, 4, 4, 4, 4])) +""".format(**reduceops_common_args), +) + +add_docstr( + torch.cumprod, + r""" +cumprod(input, dim, *, dtype=None, out=None) -> Tensor + +Returns the cumulative product of elements of :attr:`input` in the dimension +:attr:`dim`. + +For example, if :attr:`input` is a vector of size N, the result will also be +a vector of size N, with elements. + +.. math:: + y_i = x_1 \times x_2\times x_3\times \dots \times x_i + +Args: + {input} + dim (int): the dimension to do the operation over + +Keyword args: + {dtype} + {out} + +Example:: + + >>> a = torch.randn(10) + >>> a + tensor([ 0.6001, 0.2069, -0.1919, 0.9792, 0.6727, 1.0062, 0.4126, + -0.2129, -0.4206, 0.1968]) + >>> torch.cumprod(a, dim=0) + tensor([ 0.6001, 0.1241, -0.0238, -0.0233, -0.0157, -0.0158, -0.0065, + 0.0014, -0.0006, -0.0001]) + + >>> a[5] = 0.0 + >>> torch.cumprod(a, dim=0) + tensor([ 0.6001, 0.1241, -0.0238, -0.0233, -0.0157, -0.0000, -0.0000, + 0.0000, -0.0000, -0.0000]) +""".format(**reduceops_common_args), +) + +add_docstr( + torch.cumsum, + r""" +cumsum(input, dim, *, dtype=None, out=None) -> Tensor + +Returns the cumulative sum of elements of :attr:`input` in the dimension +:attr:`dim`. + +For example, if :attr:`input` is a vector of size N, the result will also be +a vector of size N, with elements. + +.. math:: + y_i = x_1 + x_2 + x_3 + \dots + x_i + +Args: + {input} + dim (int): the dimension to do the operation over + +Keyword args: + {dtype} + {out} + +Example:: + + >>> a = torch.randint(1, 20, (10,)) + >>> a + tensor([13, 7, 3, 10, 13, 3, 15, 10, 9, 10]) + >>> torch.cumsum(a, dim=0) + tensor([13, 20, 23, 33, 46, 49, 64, 74, 83, 93]) +""".format(**reduceops_common_args), +) + +add_docstr( + torch.count_nonzero, + r""" +count_nonzero(input, dim=None) -> Tensor + +Counts the number of non-zero values in the tensor :attr:`input` along the given :attr:`dim`. +If no dim is specified then all non-zeros in the tensor are counted. + +Args: + {input} + dim (int or tuple of ints, optional): Dim or tuple of dims along which to count non-zeros. + +Example:: + + >>> x = torch.zeros(3,3) + >>> x[torch.randn(3,3) > 0.5] = 1 + >>> x + tensor([[0., 1., 1.], + [0., 0., 0.], + [0., 0., 1.]]) + >>> torch.count_nonzero(x) + tensor(3) + >>> torch.count_nonzero(x, dim=0) + tensor([0, 1, 2]) +""".format(**reduceops_common_args), +) + +add_docstr( + torch.dequantize, + r""" +dequantize(tensor) -> Tensor + +Returns an fp32 Tensor by dequantizing a quantized Tensor + +Args: + tensor (Tensor): A quantized Tensor + +.. function:: dequantize(tensors) -> sequence of Tensors + :noindex: + +Given a list of quantized Tensors, dequantize them and return a list of fp32 Tensors + +Args: + tensors (sequence of Tensors): A list of quantized Tensors +""", +) + +add_docstr( + torch.diag, + r""" +diag(input, diagonal=0, *, out=None) -> Tensor + +- If :attr:`input` is a vector (1-D tensor), then returns a 2-D square tensor + with the elements of :attr:`input` as the diagonal. +- If :attr:`input` is a matrix (2-D tensor), then returns a 1-D tensor with + the diagonal elements of :attr:`input`. + +The argument :attr:`diagonal` controls which diagonal to consider: + +- If :attr:`diagonal` = 0, it is the main diagonal. +- If :attr:`diagonal` > 0, it is above the main diagonal. +- If :attr:`diagonal` < 0, it is below the main diagonal. + +Args: + {input} + diagonal (int, optional): the diagonal to consider + +Keyword args: + {out} + +.. seealso:: + + :func:`torch.diagonal` always returns the diagonal of its input. + + :func:`torch.diagflat` always constructs a tensor with diagonal elements + specified by the input. + +Examples: + +Get the square matrix where the input vector is the diagonal:: + + >>> a = torch.randn(3) + >>> a + tensor([ 0.5950,-0.0872, 2.3298]) + >>> torch.diag(a) + tensor([[ 0.5950, 0.0000, 0.0000], + [ 0.0000,-0.0872, 0.0000], + [ 0.0000, 0.0000, 2.3298]]) + >>> torch.diag(a, 1) + tensor([[ 0.0000, 0.5950, 0.0000, 0.0000], + [ 0.0000, 0.0000,-0.0872, 0.0000], + [ 0.0000, 0.0000, 0.0000, 2.3298], + [ 0.0000, 0.0000, 0.0000, 0.0000]]) + +Get the k-th diagonal of a given matrix:: + + >>> a = torch.randn(3, 3) + >>> a + tensor([[-0.4264, 0.0255,-0.1064], + [ 0.8795,-0.2429, 0.1374], + [ 0.1029,-0.6482,-1.6300]]) + >>> torch.diag(a, 0) + tensor([-0.4264,-0.2429,-1.6300]) + >>> torch.diag(a, 1) + tensor([ 0.0255, 0.1374]) +""".format(**common_args), +) + +add_docstr( + torch.diag_embed, + r""" +diag_embed(input, offset=0, dim1=-2, dim2=-1) -> Tensor + +Creates a tensor whose diagonals of certain 2D planes (specified by +:attr:`dim1` and :attr:`dim2`) are filled by :attr:`input`. +To facilitate creating batched diagonal matrices, the 2D planes formed by +the last two dimensions of the returned tensor are chosen by default. + +The argument :attr:`offset` controls which diagonal to consider: + +- If :attr:`offset` = 0, it is the main diagonal. +- If :attr:`offset` > 0, it is above the main diagonal. +- If :attr:`offset` < 0, it is below the main diagonal. + +The size of the new matrix will be calculated to make the specified diagonal +of the size of the last input dimension. +Note that for :attr:`offset` other than :math:`0`, the order of :attr:`dim1` +and :attr:`dim2` matters. Exchanging them is equivalent to changing the +sign of :attr:`offset`. + +Applying :meth:`torch.diagonal` to the output of this function with +the same arguments yields a matrix identical to input. However, +:meth:`torch.diagonal` has different default dimensions, so those +need to be explicitly specified. + +Args: + {input} Must be at least 1-dimensional. + offset (int, optional): which diagonal to consider. Default: 0 + (main diagonal). + dim1 (int, optional): first dimension with respect to which to + take diagonal. Default: -2. + dim2 (int, optional): second dimension with respect to which to + take diagonal. Default: -1. + +Example:: + + >>> a = torch.randn(2, 3) + >>> torch.diag_embed(a) + tensor([[[ 1.5410, 0.0000, 0.0000], + [ 0.0000, -0.2934, 0.0000], + [ 0.0000, 0.0000, -2.1788]], + + [[ 0.5684, 0.0000, 0.0000], + [ 0.0000, -1.0845, 0.0000], + [ 0.0000, 0.0000, -1.3986]]]) + + >>> torch.diag_embed(a, offset=1, dim1=0, dim2=2) + tensor([[[ 0.0000, 1.5410, 0.0000, 0.0000], + [ 0.0000, 0.5684, 0.0000, 0.0000]], + + [[ 0.0000, 0.0000, -0.2934, 0.0000], + [ 0.0000, 0.0000, -1.0845, 0.0000]], + + [[ 0.0000, 0.0000, 0.0000, -2.1788], + [ 0.0000, 0.0000, 0.0000, -1.3986]], + + [[ 0.0000, 0.0000, 0.0000, 0.0000], + [ 0.0000, 0.0000, 0.0000, 0.0000]]]) +""".format(**common_args), +) + + +add_docstr( + torch.diagflat, + r""" +diagflat(input, offset=0) -> Tensor + +- If :attr:`input` is a vector (1-D tensor), then returns a 2-D square tensor + with the elements of :attr:`input` as the diagonal. +- If :attr:`input` is a tensor with more than one dimension, then returns a + 2-D tensor with diagonal elements equal to a flattened :attr:`input`. + +The argument :attr:`offset` controls which diagonal to consider: + +- If :attr:`offset` = 0, it is the main diagonal. +- If :attr:`offset` > 0, it is above the main diagonal. +- If :attr:`offset` < 0, it is below the main diagonal. + +Args: + {input} + offset (int, optional): the diagonal to consider. Default: 0 (main + diagonal). + +Examples:: + + >>> a = torch.randn(3) + >>> a + tensor([-0.2956, -0.9068, 0.1695]) + >>> torch.diagflat(a) + tensor([[-0.2956, 0.0000, 0.0000], + [ 0.0000, -0.9068, 0.0000], + [ 0.0000, 0.0000, 0.1695]]) + >>> torch.diagflat(a, 1) + tensor([[ 0.0000, -0.2956, 0.0000, 0.0000], + [ 0.0000, 0.0000, -0.9068, 0.0000], + [ 0.0000, 0.0000, 0.0000, 0.1695], + [ 0.0000, 0.0000, 0.0000, 0.0000]]) + + >>> a = torch.randn(2, 2) + >>> a + tensor([[ 0.2094, -0.3018], + [-0.1516, 1.9342]]) + >>> torch.diagflat(a) + tensor([[ 0.2094, 0.0000, 0.0000, 0.0000], + [ 0.0000, -0.3018, 0.0000, 0.0000], + [ 0.0000, 0.0000, -0.1516, 0.0000], + [ 0.0000, 0.0000, 0.0000, 1.9342]]) +""".format(**common_args), +) + +add_docstr( + torch.diagonal, + r""" +diagonal(input, offset=0, dim1=0, dim2=1) -> Tensor + +Returns a partial view of :attr:`input` with the its diagonal elements +with respect to :attr:`dim1` and :attr:`dim2` appended as a dimension +at the end of the shape. + +The argument :attr:`offset` controls which diagonal to consider: + +- If :attr:`offset` = 0, it is the main diagonal. +- If :attr:`offset` > 0, it is above the main diagonal. +- If :attr:`offset` < 0, it is below the main diagonal. + +Applying :meth:`torch.diag_embed` to the output of this function with +the same arguments yields a diagonal matrix with the diagonal entries +of the input. However, :meth:`torch.diag_embed` has different default +dimensions, so those need to be explicitly specified. + +Args: + {input} Must be at least 2-dimensional. + offset (int, optional): which diagonal to consider. Default: 0 + (main diagonal). + dim1 (int, optional): first dimension with respect to which to + take diagonal. Default: 0. + dim2 (int, optional): second dimension with respect to which to + take diagonal. Default: 1. + +.. note:: To take a batch diagonal, pass in dim1=-2, dim2=-1. + +Examples:: + + >>> a = torch.randn(3, 3) + >>> a + tensor([[-1.0854, 1.1431, -0.1752], + [ 0.8536, -0.0905, 0.0360], + [ 0.6927, -0.3735, -0.4945]]) + + + >>> torch.diagonal(a) + tensor([-1.0854, -0.0905, -0.4945]) + + + >>> torch.diagonal(a, 1) + tensor([ 1.1431, 0.0360]) + + >>> b = torch.randn(2, 5) + >>> b + tensor([[-1.7948, -1.2731, -0.3181, 2.0200, -1.6745], + [ 1.8262, -1.5049, 0.4114, 1.0704, -1.2607]]) + + >>> torch.diagonal(b, 1, 1, 0) + tensor([1.8262]) + + >>> x = torch.randn(2, 5, 4, 2) + >>> torch.diagonal(x, offset=-1, dim1=1, dim2=2) + tensor([[[-1.2631, 0.3755, -1.5977, -1.8172], + [-1.1065, 1.0401, -0.2235, -0.7938]], + + [[-1.7325, -0.3081, 0.6166, 0.2335], + [ 1.0500, 0.7336, -0.3836, -1.1015]]]) +""".format(**common_args), +) + +add_docstr( + torch.diagonal_scatter, + r""" +diagonal_scatter(input, src, offset=0, dim1=0, dim2=1) -> Tensor + +Embeds the values of the :attr:`src` tensor into :attr:`input` along +the diagonal elements of :attr:`input`, with respect to :attr:`dim1` +and :attr:`dim2`. + +This function returns a tensor with fresh storage; it does not +return a view. + +The argument :attr:`offset` controls which diagonal to consider: + +- If :attr:`offset` = 0, it is the main diagonal. +- If :attr:`offset` > 0, it is above the main diagonal. +- If :attr:`offset` < 0, it is below the main diagonal. + +Args: + {input} Must be at least 2-dimensional. + src (Tensor): the tensor to embed into :attr:`input`. + offset (int, optional): which diagonal to consider. Default: 0 + (main diagonal). + dim1 (int, optional): first dimension with respect to which to + take diagonal. Default: 0. + dim2 (int, optional): second dimension with respect to which to + take diagonal. Default: 1. + +.. note:: + + :attr:`src` must be of the proper size in order to be embedded + into :attr:`input`. Specifically, it should have the same shape as + ``torch.diagonal(input, offset, dim1, dim2)`` + +Examples:: + + >>> a = torch.zeros(3, 3) + >>> a + tensor([[0., 0., 0.], + [0., 0., 0.], + [0., 0., 0.]]) + + >>> torch.diagonal_scatter(a, torch.ones(3), 0) + tensor([[1., 0., 0.], + [0., 1., 0.], + [0., 0., 1.]]) + + >>> torch.diagonal_scatter(a, torch.ones(2), 1) + tensor([[0., 1., 0.], + [0., 0., 1.], + [0., 0., 0.]]) +""".format(**common_args), +) + +add_docstr( + torch.as_strided_scatter, + r""" +as_strided_scatter(input, src, size, stride, storage_offset=None) -> Tensor + +Embeds the values of the :attr:`src` tensor into :attr:`input` along +the elements corresponding to the result of calling +input.as_strided(size, stride, storage_offset). + +This function returns a tensor with fresh storage; it does not +return a view. + +Args: + {input} + size (tuple or ints): the shape of the output tensor + stride (tuple or ints): the stride of the output tensor + storage_offset (int, optional): the offset in the underlying storage of the output tensor + +.. note:: + + :attr:`src` must be of the proper size in order to be embedded + into :attr:`input`. Specifically, it should have the same shape as + `torch.as_strided(input, size, stride, storage_offset)` + +Example:: + + >>> a = torch.arange(4).reshape(2, 2) + 1 + >>> a + tensor([[1, 2], + [3, 4]]) + >>> b = torch.zeros(3, 3) + >>> b + tensor([[0., 0., 0.], + [0., 0., 0.], + [0., 0., 0.]]) + >>> torch.as_strided_scatter(b, a, (2, 2), (1, 2)) + tensor([[1., 3., 2.], + [4., 0., 0.], + [0., 0., 0.]]) + +""".format(**common_args), +) + +add_docstr( + torch.diff, + r""" +diff(input, n=1, dim=-1, prepend=None, append=None) -> Tensor + +Computes the n-th forward difference along the given dimension. + +The first-order differences are given by `out[i] = input[i + 1] - input[i]`. Higher-order +differences are calculated by using :func:`torch.diff` recursively. + +Args: + input (Tensor): the tensor to compute the differences on + n (int, optional): the number of times to recursively compute the difference + dim (int, optional): the dimension to compute the difference along. + Default is the last dimension. + prepend, append (Tensor, optional): values to prepend or append to + :attr:`input` along :attr:`dim` before computing the difference. + Their dimensions must be equivalent to that of input, and their shapes + must match input's shape except on :attr:`dim`. + +Keyword args: + {out} + +Example:: + + >>> a = torch.tensor([1, 3, 2]) + >>> torch.diff(a) + tensor([ 2, -1]) + >>> b = torch.tensor([4, 5]) + >>> torch.diff(a, append=b) + tensor([ 2, -1, 2, 1]) + >>> c = torch.tensor([[1, 2, 3], [3, 4, 5]]) + >>> torch.diff(c, dim=0) + tensor([[2, 2, 2]]) + >>> torch.diff(c, dim=1) + tensor([[1, 1], + [1, 1]]) +""".format(**common_args), +) + +add_docstr( + torch.digamma, + r""" +digamma(input, *, out=None) -> Tensor + +Alias for :func:`torch.special.digamma`. +""", +) + +add_docstr( + torch.dist, + r""" +dist(input, other, p=2) -> Tensor + +Returns the p-norm of (:attr:`input` - :attr:`other`) + +The shapes of :attr:`input` and :attr:`other` must be +:ref:`broadcastable `. + +Args: + {input} + other (Tensor): the Right-hand-side input tensor + p (float, optional): the norm to be computed + +Example:: + + >>> x = torch.randn(4) + >>> x + tensor([-1.5393, -0.8675, 0.5916, 1.6321]) + >>> y = torch.randn(4) + >>> y + tensor([ 0.0967, -1.0511, 0.6295, 0.8360]) + >>> torch.dist(x, y, 3.5) + tensor(1.6727) + >>> torch.dist(x, y, 3) + tensor(1.6973) + >>> torch.dist(x, y, 0) + tensor(4.) + >>> torch.dist(x, y, 1) + tensor(2.6537) +""".format(**common_args), +) + +add_docstr( + torch.div, + r""" +div(input, other, *, rounding_mode=None, out=None) -> Tensor + +Divides each element of the input ``input`` by the corresponding element of +:attr:`other`. + +.. math:: + \text{{out}}_i = \frac{{\text{{input}}_i}}{{\text{{other}}_i}} + +.. note:: + By default, this performs a "true" division like Python 3. + See the :attr:`rounding_mode` argument for floor division. + +Supports :ref:`broadcasting to a common shape `, +:ref:`type promotion `, and integer, float, and complex inputs. +Always promotes integer types to the default scalar type. + +Args: + input (Tensor): the dividend + other (Tensor or Number): the divisor + +Keyword args: + rounding_mode (str, optional): Type of rounding applied to the result: + + * None - default behavior. Performs no rounding and, if both :attr:`input` and + :attr:`other` are integer types, promotes the inputs to the default scalar type. + Equivalent to true division in Python (the ``/`` operator) and NumPy's ``np.true_divide``. + * ``"trunc"`` - rounds the results of the division towards zero. + Equivalent to C-style integer division. + * ``"floor"`` - rounds the results of the division down. + Equivalent to floor division in Python (the ``//`` operator) and NumPy's ``np.floor_divide``. + + {out} + +Examples:: + + >>> x = torch.tensor([ 0.3810, 1.2774, -0.2972, -0.3719, 0.4637]) + >>> torch.div(x, 0.5) + tensor([ 0.7620, 2.5548, -0.5944, -0.7438, 0.9274]) + + >>> a = torch.tensor([[-0.3711, -1.9353, -0.4605, -0.2917], + ... [ 0.1815, -1.0111, 0.9805, -1.5923], + ... [ 0.1062, 1.4581, 0.7759, -1.2344], + ... [-0.1830, -0.0313, 1.1908, -1.4757]]) + >>> b = torch.tensor([ 0.8032, 0.2930, -0.8113, -0.2308]) + >>> torch.div(a, b) + tensor([[-0.4620, -6.6051, 0.5676, 1.2639], + [ 0.2260, -3.4509, -1.2086, 6.8990], + [ 0.1322, 4.9764, -0.9564, 5.3484], + [-0.2278, -0.1068, -1.4678, 6.3938]]) + + >>> torch.div(a, b, rounding_mode='trunc') + tensor([[-0., -6., 0., 1.], + [ 0., -3., -1., 6.], + [ 0., 4., -0., 5.], + [-0., -0., -1., 6.]]) + + >>> torch.div(a, b, rounding_mode='floor') + tensor([[-1., -7., 0., 1.], + [ 0., -4., -2., 6.], + [ 0., 4., -1., 5.], + [-1., -1., -2., 6.]]) + +""".format(**common_args), +) + +add_docstr( + torch.divide, + r""" +divide(input, other, *, rounding_mode=None, out=None) -> Tensor + +Alias for :func:`torch.div`. +""", +) + +add_docstr( + torch.dot, + r""" +dot(input, tensor, *, out=None) -> Tensor + +Computes the dot product of two 1D tensors. + +.. note:: + + Unlike NumPy's dot, torch.dot intentionally only supports computing the dot product + of two 1D tensors with the same number of elements. + +Args: + input (Tensor): first tensor in the dot product, must be 1D. + tensor (Tensor): second tensor in the dot product, must be 1D. + +Keyword args: + {out} + +Example:: + + >>> torch.dot(torch.tensor([2, 3]), torch.tensor([2, 1])) + tensor(7) + + >>> t1, t2 = torch.tensor([0, 1]), torch.tensor([2, 3]) + >>> torch.dot(t1, t2) + tensor(3) +""".format(**common_args), +) + +add_docstr( + torch.vdot, + r""" +vdot(input, other, *, out=None) -> Tensor + +Computes the dot product of two 1D vectors along a dimension. + +In symbols, this function computes + +.. math:: + + \sum_{i=1}^n \overline{x_i}y_i. + +where :math:`\overline{x_i}` denotes the conjugate for complex +vectors, and it is the identity for real vectors. + +.. note:: + + Unlike NumPy's vdot, torch.vdot intentionally only supports computing the dot product + of two 1D tensors with the same number of elements. + +.. seealso:: + + :func:`torch.linalg.vecdot` computes the dot product of two batches of vectors along a dimension. + +Args: + input (Tensor): first tensor in the dot product, must be 1D. Its conjugate is used if it's complex. + other (Tensor): second tensor in the dot product, must be 1D. + +Keyword args: +""" + + rf""" +.. note:: {common_args["out"]} +""" + + r""" + +Example:: + + >>> torch.vdot(torch.tensor([2, 3]), torch.tensor([2, 1])) + tensor(7) + >>> a = torch.tensor((1 +2j, 3 - 1j)) + >>> b = torch.tensor((2 +1j, 4 - 0j)) + >>> torch.vdot(a, b) + tensor([16.+1.j]) + >>> torch.vdot(b, a) + tensor([16.-1.j]) +""", +) + +add_docstr( + torch.eq, + r""" +eq(input, other, *, out=None) -> Tensor + +Computes element-wise equality + +The second argument can be a number or a tensor whose shape is +:ref:`broadcastable ` with the first argument. + +Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + +Keyword args: + {out} + +Returns: + A boolean tensor that is True where :attr:`input` is equal to :attr:`other` and False elsewhere + +Example:: + + >>> torch.eq(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[ True, False], + [False, True]]) +""".format(**common_args), +) + +add_docstr( + torch.equal, + r""" +equal(input, other) -> bool + +``True`` if two tensors have the same size and elements, ``False`` otherwise. + +.. note:: + + Tensors containing NaNs are never equal to each other. Additionally, this function does not + differentiate between the data types of the tensors during comparison. For more thorough tensor checks, + use :meth:`torch.testing.assert_close`. + +Example:: + + >>> torch.equal(torch.tensor([1, 2]), torch.tensor([1, 2])) + True + >>> torch.equal(torch.tensor([3, torch.nan]), torch.tensor([3, torch.nan])) + False + >>> torch.equal(torch.tensor([1, 2, 3], dtype=torch.int32), torch.tensor([1, 2, 3], dtype=torch.float32)) + True +""", +) + +add_docstr( + torch.erf, + r""" +erf(input, *, out=None) -> Tensor + +Alias for :func:`torch.special.erf`. +""", +) + +add_docstr( + torch.erfc, + r""" +erfc(input, *, out=None) -> Tensor + +Alias for :func:`torch.special.erfc`. +""", +) + +add_docstr( + torch.erfinv, + r""" +erfinv(input, *, out=None) -> Tensor + +Alias for :func:`torch.special.erfinv`. +""", +) + +add_docstr( + torch.exp, + r""" +exp(input, *, out=None) -> Tensor + +Returns a new tensor with the exponential of the elements +of the input tensor :attr:`input`. + +.. math:: + y_{i} = e^{x_{i}} +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> torch.exp(torch.tensor([0, math.log(2.)])) + tensor([ 1., 2.]) +""".format(**common_args), +) + +add_docstr( + torch.exp2, + r""" +exp2(input, *, out=None) -> Tensor + +Alias for :func:`torch.special.exp2`. +""", +) + +add_docstr( + torch.expm1, + r""" +expm1(input, *, out=None) -> Tensor + +Alias for :func:`torch.special.expm1`. +""", +) + +add_docstr( + torch.eye, + r""" +eye(n, m=None, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + +Returns a 2-D tensor with ones on the diagonal and zeros elsewhere. + +Args: + n (int): the number of rows + m (int, optional): the number of columns with default being :attr:`n` + +Keyword arguments: + {out} + {dtype} + {layout} + {device} + {requires_grad} + +Returns: + Tensor: A 2-D tensor with ones on the diagonal and zeros elsewhere + +Example:: + + >>> torch.eye(3) + tensor([[ 1., 0., 0.], + [ 0., 1., 0.], + [ 0., 0., 1.]]) +""".format(**factory_common_args), +) + +add_docstr( + torch.floor, + r""" +floor(input, *, out=None) -> Tensor + +Returns a new tensor with the floor of the elements of :attr:`input`, +the largest integer less than or equal to each element. + +For integer inputs, follows the array-api convention of returning a +copy of the input tensor. + +.. math:: + \text{out}_{i} = \left\lfloor \text{input}_{i} \right\rfloor +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-0.8166, 1.5308, -0.2530, -0.2091]) + >>> torch.floor(a) + tensor([-1., 1., -1., -1.]) +""".format(**common_args), +) + +add_docstr( + torch.floor_divide, + r""" +floor_divide(input, other, *, out=None) -> Tensor + +.. note:: + + Before PyTorch 1.13 :func:`torch.floor_divide` incorrectly performed + truncation division. To restore the previous behavior use + :func:`torch.div` with ``rounding_mode='trunc'``. + +Computes :attr:`input` divided by :attr:`other`, elementwise, and floors +the result. + +.. math:: + \text{{out}}_i = \text{floor} \left( \frac{{\text{{input}}_i}}{{\text{{other}}_i}} \right) + +""" + + r""" + +Supports broadcasting to a common shape, type promotion, and integer and float inputs. + +Args: + input (Tensor or Number): the dividend + other (Tensor or Number): the divisor + +Keyword args: + {out} + +Example:: + + >>> a = torch.tensor([4.0, 3.0]) + >>> b = torch.tensor([2.0, 2.0]) + >>> torch.floor_divide(a, b) + tensor([2.0, 1.0]) + >>> torch.floor_divide(a, 1.4) + tensor([2.0, 2.0]) +""".format(**common_args), +) + +add_docstr( + torch.fmod, + r""" +fmod(input, other, *, out=None) -> Tensor + +Applies C++'s `std::fmod `_ entrywise. +The result has the same sign as the dividend :attr:`input` and its absolute value +is less than that of :attr:`other`. + +This function may be defined in terms of :func:`torch.div` as + +.. code:: python + + torch.fmod(a, b) == a - a.div(b, rounding_mode="trunc") * b + +Supports :ref:`broadcasting to a common shape `, +:ref:`type promotion `, and integer and float inputs. + +.. note:: + + When the divisor is zero, returns ``NaN`` for floating point dtypes + on both CPU and GPU; raises ``RuntimeError`` for integer division by + zero on CPU; Integer division by zero on GPU may return any value. + +.. note:: + + Complex inputs are not supported. In some cases, it is not mathematically + possible to satisfy the definition of a modulo operation with complex numbers. + +.. seealso:: + + :func:`torch.remainder` which implements Python's modulus operator. + This one is defined using division rounding down the result. + +Args: + input (Tensor): the dividend + other (Tensor or Scalar): the divisor + +Keyword args: + {out} + +Example:: + + >>> torch.fmod(torch.tensor([-3., -2, -1, 1, 2, 3]), 2) + tensor([-1., -0., -1., 1., 0., 1.]) + >>> torch.fmod(torch.tensor([1, 2, 3, 4, 5]), -1.5) + tensor([1.0000, 0.5000, 0.0000, 1.0000, 0.5000]) + +""".format(**common_args), +) + +add_docstr( + torch.frac, + r""" +frac(input, *, out=None) -> Tensor + +Computes the fractional portion of each element in :attr:`input`. + +.. math:: + \text{out}_{i} = \text{input}_{i} - \left\lfloor |\text{input}_{i}| \right\rfloor * \operatorname{sgn}(\text{input}_{i}) + +Example:: + + >>> torch.frac(torch.tensor([1, 2.5, -3.2])) + tensor([ 0.0000, 0.5000, -0.2000]) +""", +) + +add_docstr( + torch.frexp, + r""" +frexp(input, *, out=None) -> (Tensor mantissa, Tensor exponent) + +Decomposes :attr:`input` into mantissa and exponent tensors +such that :math:`\text{input} = \text{mantissa} \times 2^{\text{exponent}}`. + +The range of mantissa is the open interval (-1, 1). + +Supports float inputs. + +Args: + input (Tensor): the input tensor + + +Keyword args: + out (tuple, optional): the output tensors + +Example:: + + >>> x = torch.arange(9.) + >>> mantissa, exponent = torch.frexp(x) + >>> mantissa + tensor([0.0000, 0.5000, 0.5000, 0.7500, 0.5000, 0.6250, 0.7500, 0.8750, 0.5000]) + >>> exponent + tensor([0, 1, 2, 2, 3, 3, 3, 3, 4], dtype=torch.int32) + >>> torch.ldexp(mantissa, exponent) + tensor([0., 1., 2., 3., 4., 5., 6., 7., 8.]) +""", +) + +add_docstr( + torch.from_numpy, + r""" +from_numpy(ndarray) -> Tensor + +Creates a :class:`Tensor` from a :class:`numpy.ndarray`. + +The returned tensor and :attr:`ndarray` share the same memory. Modifications to +the tensor will be reflected in the :attr:`ndarray` and vice versa. The returned +tensor is not resizable. + +It currently accepts :attr:`ndarray` with dtypes of ``numpy.float64``, +``numpy.float32``, ``numpy.float16``, ``numpy.complex64``, ``numpy.complex128``, +``numpy.int64``, ``numpy.int32``, ``numpy.int16``, ``numpy.int8``, ``numpy.uint8``, +and ``bool``. + +.. warning:: + Writing to a tensor created from a read-only NumPy array is not supported and will result in undefined behavior. + +Example:: + + >>> a = numpy.array([1, 2, 3]) + >>> t = torch.from_numpy(a) + >>> t + tensor([ 1, 2, 3]) + >>> t[0] = -1 + >>> a + array([-1, 2, 3]) +""", +) + +add_docstr( + torch.frombuffer, + r""" +frombuffer(buffer, *, dtype, count=-1, offset=0, requires_grad=False) -> Tensor + +Creates a 1-dimensional :class:`Tensor` from an object that implements +the Python buffer protocol. + +Skips the first :attr:`offset` bytes in the buffer, and interprets the rest of +the raw bytes as a 1-dimensional tensor of type :attr:`dtype` with :attr:`count` +elements. + +Note that either of the following must be true: + +1. :attr:`count` is a positive non-zero number, and the total number of bytes +in the buffer is more than :attr:`offset` plus :attr:`count` times the size +(in bytes) of :attr:`dtype`. + +2. :attr:`count` is negative, and the length (number of bytes) of the buffer +subtracted by the :attr:`offset` is a multiple of the size (in bytes) of +:attr:`dtype`. + +The returned tensor and buffer share the same memory. Modifications to +the tensor will be reflected in the buffer and vice versa. The returned +tensor is not resizable. + +.. note:: + This function increments the reference count for the object that + owns the shared memory. Therefore, such memory will not be deallocated + before the returned tensor goes out of scope. + +.. warning:: + This function's behavior is undefined when passed an object implementing + the buffer protocol whose data is not on the CPU. Doing so is likely to + cause a segmentation fault. + +.. warning:: + This function does not try to infer the :attr:`dtype` (hence, it is not + optional). Passing a different :attr:`dtype` than its source may result + in unexpected behavior. + +Args: + buffer (object): a Python object that exposes the buffer interface. + +Keyword args: + dtype (:class:`torch.dtype`): the desired data type of returned tensor. + count (int, optional): the number of desired elements to be read. + If negative, all the elements (until the end of the buffer) will be + read. Default: -1. + offset (int, optional): the number of bytes to skip at the start of + the buffer. Default: 0. + {requires_grad} + +Example:: + + >>> import array + >>> a = array.array('i', [1, 2, 3]) + >>> t = torch.frombuffer(a, dtype=torch.int32) + >>> t + tensor([ 1, 2, 3]) + >>> t[0] = -1 + >>> a + array([-1, 2, 3]) + + >>> # Interprets the signed char bytes as 32-bit integers. + >>> # Each 4 signed char elements will be interpreted as + >>> # 1 signed 32-bit integer. + >>> import array + >>> a = array.array('b', [-1, 0, 0, 0]) + >>> torch.frombuffer(a, dtype=torch.int32) + tensor([255], dtype=torch.int32) +""".format(**factory_common_args), +) + +add_docstr( + torch.from_file, + r""" +from_file(filename, shared=None, size=0, *, dtype=None, layout=None, device=None, pin_memory=False) + +Creates a CPU tensor with a storage backed by a memory-mapped file. + +If ``shared`` is True, then memory is shared between processes. All changes are written to the file. +If ``shared`` is False, then changes to the tensor do not affect the file. + +``size`` is the number of elements in the Tensor. If ``shared`` is ``False``, then the file must contain +at least ``size * sizeof(dtype)`` bytes. If ``shared`` is ``True`` the file will be created if needed. + +.. note:: + Only CPU tensors can be mapped to files. + +.. note:: + For now, tensors with storages backed by a memory-mapped file cannot be created in pinned memory. + + +Args: + filename (str): file name to map + shared (bool): whether to share memory (whether ``MAP_SHARED`` or ``MAP_PRIVATE`` is passed to the + underlying `mmap(2) call `_) + size (int): number of elements in the tensor + +Keyword args: + {dtype} + {layout} + {device} + {pin_memory} + +Example:: + + >>> t = torch.randn(2, 5, dtype=torch.float64) + >>> t.numpy().tofile('storage.pt') + >>> t_mapped = torch.from_file('storage.pt', shared=False, size=10, dtype=torch.float64) + """.format(**factory_common_args), +) + +add_docstr( + torch.flatten, + r""" +flatten(input, start_dim=0, end_dim=-1) -> Tensor + +Flattens :attr:`input` by reshaping it into a one-dimensional tensor. If :attr:`start_dim` or :attr:`end_dim` +are passed, only dimensions starting with :attr:`start_dim` and ending with :attr:`end_dim` are flattened. +The order of elements in :attr:`input` is unchanged. + +Unlike NumPy's flatten, which always copies input's data, this function may return the original object, a view, +or copy. If no dimensions are flattened, then the original object :attr:`input` is returned. Otherwise, if input can +be viewed as the flattened shape, then that view is returned. Finally, only if the input cannot be viewed as the +flattened shape is input's data copied. See :meth:`torch.Tensor.view` for details on when a view will be returned. + +.. note:: + Flattening a zero-dimensional tensor will return a one-dimensional view. + +Args: + {input} + start_dim (int): the first dim to flatten + end_dim (int): the last dim to flatten + +Example:: + + >>> t = torch.tensor([[[1, 2], + ... [3, 4]], + ... [[5, 6], + ... [7, 8]]]) + >>> torch.flatten(t) + tensor([1, 2, 3, 4, 5, 6, 7, 8]) + >>> torch.flatten(t, start_dim=1) + tensor([[1, 2, 3, 4], + [5, 6, 7, 8]]) +""".format(**common_args), +) + +add_docstr( + torch.unflatten, + r""" +unflatten(input, dim, sizes) -> Tensor + +Expands a dimension of the input tensor over multiple dimensions. + +.. seealso:: + + :func:`torch.flatten` the inverse of this function. It coalesces several dimensions into one. + +Args: + {input} + dim (int): Dimension to be unflattened, specified as an index into + ``input.shape``. + sizes (Tuple[int]): New shape of the unflattened dimension. + One of its elements can be `-1` in which case the corresponding output + dimension is inferred. Otherwise, the product of ``sizes`` *must* + equal ``input.shape[dim]``. + +Returns: + A View of input with the specified dimension unflattened. + +Examples:: + >>> torch.unflatten(torch.randn(3, 4, 1), 1, (2, 2)).shape + torch.Size([3, 2, 2, 1]) + >>> torch.unflatten(torch.randn(3, 4, 1), 1, (-1, 2)).shape + torch.Size([3, 2, 2, 1]) + >>> torch.unflatten(torch.randn(5, 12, 3), -2, (2, 2, 3, 1, 1)).shape + torch.Size([5, 2, 2, 3, 1, 1, 3]) +""".format(**common_args), +) + +add_docstr( + torch.gather, + r""" +gather(input, dim, index, *, sparse_grad=False, out=None) -> Tensor + +Gathers values along an axis specified by `dim`. + +For a 3-D tensor the output is specified by:: + + out[i][j][k] = input[index[i][j][k]][j][k] # if dim == 0 + out[i][j][k] = input[i][index[i][j][k]][k] # if dim == 1 + out[i][j][k] = input[i][j][index[i][j][k]] # if dim == 2 + +:attr:`input` and :attr:`index` must have the same number of dimensions. +It is also required that ``index.size(d) <= input.size(d)`` for all +dimensions ``d != dim``. :attr:`out` will have the same shape as :attr:`index`. +Note that ``input`` and ``index`` do not broadcast against each other. +When :attr:`index` is empty, we always return an empty output with the same shape +without further error checking. + +Args: + input (Tensor): the source tensor + dim (int): the axis along which to index + index (LongTensor): the indices of elements to gather + +Keyword arguments: + sparse_grad (bool, optional): If ``True``, gradient w.r.t. :attr:`input` will be a sparse tensor. + out (Tensor, optional): the destination tensor + +Example:: + + >>> t = torch.tensor([[1, 2], [3, 4]]) + >>> torch.gather(t, 1, torch.tensor([[0, 0], [1, 0]])) + tensor([[ 1, 1], + [ 4, 3]]) +""", +) + + +add_docstr( + torch.gcd, + r""" +gcd(input, other, *, out=None) -> Tensor + +Computes the element-wise greatest common divisor (GCD) of :attr:`input` and :attr:`other`. + +Both :attr:`input` and :attr:`other` must have integer types. + +.. note:: + This defines :math:`gcd(0, 0) = 0`. + +Args: + {input} + other (Tensor): the second input tensor + +Keyword arguments: + {out} + +Example:: + + >>> a = torch.tensor([5, 10, 15]) + >>> b = torch.tensor([3, 4, 5]) + >>> torch.gcd(a, b) + tensor([1, 2, 5]) + >>> c = torch.tensor([3]) + >>> torch.gcd(a, c) + tensor([1, 1, 3]) +""".format(**common_args), +) + +add_docstr( + torch.ge, + r""" +ge(input, other, *, out=None) -> Tensor + +Computes :math:`\text{input} \geq \text{other}` element-wise. +""" + + r""" + +The second argument can be a number or a tensor whose shape is +:ref:`broadcastable ` with the first argument. + +Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + +Keyword args: + {out} + +Returns: + A boolean tensor that is True where :attr:`input` is greater than or equal to :attr:`other` and False elsewhere + +Example:: + + >>> torch.ge(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[True, True], [False, True]]) +""".format(**common_args), +) + +add_docstr( + torch.greater_equal, + r""" +greater_equal(input, other, *, out=None) -> Tensor + +Alias for :func:`torch.ge`. +""", +) + +add_docstr( + torch.gradient, + r""" +gradient(input, *, spacing=1, dim=None, edge_order=1) -> List of Tensors + +Estimates the gradient of a function :math:`g : \mathbb{R}^n \rightarrow \mathbb{R}` in +one or more dimensions using the `second-order accurate central differences method +`_ and +either first or second order estimates at the boundaries. + +The gradient of :math:`g` is estimated using samples. By default, when :attr:`spacing` is not +specified, the samples are entirely described by :attr:`input`, and the mapping of input coordinates +to an output is the same as the tensor's mapping of indices to values. For example, for a three-dimensional +:attr:`input` the function described is :math:`g : \mathbb{R}^3 \rightarrow \mathbb{R}`, and +:math:`g(1, 2, 3)\ == input[1, 2, 3]`. + +When :attr:`spacing` is specified, it modifies the relationship between :attr:`input` and input coordinates. +This is detailed in the "Keyword Arguments" section below. + +The gradient is estimated by estimating each partial derivative of :math:`g` independently. This estimation is +accurate if :math:`g` is in :math:`C^3` (it has at least 3 continuous derivatives), and the estimation can be +improved by providing closer samples. Mathematically, the value at each interior point of a partial derivative +is estimated using `Taylor's theorem with remainder `_. +Letting :math:`x` be an interior point with :math:`x-h_l` and :math:`x+h_r` be points neighboring +it to the left and right respectively, :math:`f(x+h_r)` and :math:`f(x-h_l)` can be estimated using: + +.. math:: + \begin{aligned} + f(x+h_r) = f(x) + h_r f'(x) + {h_r}^2 \frac{f''(x)}{2} + {h_r}^3 \frac{f'''(\xi_1)}{6}, \xi_1 \in (x, x+h_r) \\ + f(x-h_l) = f(x) - h_l f'(x) + {h_l}^2 \frac{f''(x)}{2} - {h_l}^3 \frac{f'''(\xi_2)}{6}, \xi_2 \in (x, x-h_l) \\ + \end{aligned} + +Using the fact that :math:`f \in C^3` and solving the linear system, we derive: + +.. math:: + f'(x) \approx \frac{ {h_l}^2 f(x+h_r) - {h_r}^2 f(x-h_l) + + ({h_r}^2-{h_l}^2 ) f(x) }{ {h_r} {h_l}^2 + {h_r}^2 {h_l} } + +.. note:: + We estimate the gradient of functions in complex domain + :math:`g : \mathbb{C}^n \rightarrow \mathbb{C}` in the same way. + +The value of each partial derivative at the boundary points is computed differently. See edge_order below. + +Args: + input (``Tensor``): the tensor that represents the values of the function + +Keyword args: + spacing (``scalar``, ``list of scalar``, ``list of Tensor``, optional): :attr:`spacing` can be used to modify + how the :attr:`input` tensor's indices relate to sample coordinates. If :attr:`spacing` is a scalar then + the indices are multiplied by the scalar to produce the coordinates. For example, if :attr:`spacing=2` the + indices (1, 2, 3) become coordinates (2, 4, 6). If :attr:`spacing` is a list of scalars then the corresponding + indices are multiplied. For example, if :attr:`spacing=(2, -1, 3)` the indices (1, 2, 3) become coordinates (2, -2, 9). + Finally, if :attr:`spacing` is a list of one-dimensional tensors then each tensor specifies the coordinates for + the corresponding dimension. For example, if the indices are (1, 2, 3) and the tensors are (t0, t1, t2), then + the coordinates are (t0[1], t1[2], t2[3]) + + dim (``int``, ``list of int``, optional): the dimension or dimensions to approximate the gradient over. By default + the partial gradient in every dimension is computed. Note that when :attr:`dim` is specified the elements of + the :attr:`spacing` argument must correspond with the specified dims." + + edge_order (``int``, optional): 1 or 2, for `first-order + `_ or + `second-order `_ + estimation of the boundary ("edge") values, respectively. Note that when :attr:`edge_order` is specified, each + dimension size of :attr:`input` should be at least edge_order+1 + +Examples:: + + >>> # Estimates the gradient of f(x)=x^2 at points [-2, -1, 2, 4] + >>> coordinates = (torch.tensor([-2., -1., 1., 4.]),) + >>> values = torch.tensor([4., 1., 1., 16.], ) + >>> torch.gradient(values, spacing = coordinates) + (tensor([-3., -2., 2., 5.]),) + + >>> # Estimates the gradient of the R^2 -> R function whose samples are + >>> # described by the tensor t. Implicit coordinates are [0, 1] for the outermost + >>> # dimension and [0, 1, 2, 3] for the innermost dimension, and function estimates + >>> # partial derivative for both dimensions. + >>> t = torch.tensor([[1, 2, 4, 8], [10, 20, 40, 80]]) + >>> torch.gradient(t) + (tensor([[ 9., 18., 36., 72.], + [ 9., 18., 36., 72.]]), + tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]])) + + >>> # A scalar value for spacing modifies the relationship between tensor indices + >>> # and input coordinates by multiplying the indices to find the + >>> # coordinates. For example, below the indices of the innermost + >>> # 0, 1, 2, 3 translate to coordinates of [0, 2, 4, 6], and the indices of + >>> # the outermost dimension 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = 2.0) # dim = None (implicitly [0, 1]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.5000, 0.7500, 1.5000, 2.0000], + [ 5.0000, 7.5000, 15.0000, 20.0000]])) + >>> # doubling the spacing between samples halves the estimated partial gradients. + + >>> + >>> # Estimates only the partial derivative for dimension 1 + >>> torch.gradient(t, dim = 1) # spacing = None (implicitly 1.) + (tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]]),) + + >>> # When spacing is a list of scalars, the relationship between the tensor + >>> # indices and input coordinates changes based on dimension. + >>> # For example, below, the indices of the innermost dimension 0, 1, 2, 3 translate + >>> # to coordinates of [0, 3, 6, 9], and the indices of the outermost dimension + >>> # 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = [3., 2.]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + + >>> # The following example is a replication of the previous one with explicit + >>> # coordinates. + >>> coords = (torch.tensor([0, 2]), torch.tensor([0, 3, 6, 9])) + >>> torch.gradient(t, spacing = coords) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + +""", +) + +add_docstr( + torch.geqrf, + r""" +geqrf(input, *, out=None) -> (Tensor, Tensor) + +This is a low-level function for calling LAPACK's geqrf directly. This function +returns a namedtuple (a, tau) as defined in `LAPACK documentation for geqrf`_ . + +Computes a QR decomposition of :attr:`input`. +Both `Q` and `R` matrices are stored in the same output tensor `a`. +The elements of `R` are stored on and above the diagonal. +Elementary reflectors (or Householder vectors) implicitly defining matrix `Q` +are stored below the diagonal. +The results of this function can be used together with :func:`torch.linalg.householder_product` +to obtain the `Q` matrix or +with :func:`torch.ormqr`, which uses an implicit representation of the `Q` matrix, +for an efficient matrix-matrix multiplication. + +See `LAPACK documentation for geqrf`_ for further details. + +.. note:: + See also :func:`torch.linalg.qr`, which computes Q and R matrices, and :func:`torch.linalg.lstsq` + with the ``driver="gels"`` option for a function that can solve matrix equations using a QR decomposition. + +Args: + input (Tensor): the input matrix + +Keyword args: + out (tuple, optional): the output tuple of (Tensor, Tensor). Ignored if `None`. Default: `None`. + +.. _LAPACK documentation for geqrf: + http://www.netlib.org/lapack/explore-html/df/dc5/group__variants_g_ecomputational_ga3766ea903391b5cf9008132f7440ec7b.html + +""", +) + +add_docstr( + torch.inner, + r""" +inner(input, other, *, out=None) -> Tensor + +Computes the dot product for 1D tensors. For higher dimensions, sums the product +of elements from :attr:`input` and :attr:`other` along their last dimension. + +.. note:: + + If either :attr:`input` or :attr:`other` is a scalar, the result is equivalent + to `torch.mul(input, other)`. + + If both :attr:`input` and :attr:`other` are non-scalars, the size of their last + dimension must match and the result is equivalent to `torch.tensordot(input, + other, dims=([-1], [-1]))` + +Args: + input (Tensor): First input tensor + other (Tensor): Second input tensor + +Keyword args: + out (Tensor, optional): Optional output tensor to write result into. The output + shape is `input.shape[:-1] + other.shape[:-1]`. + +Example:: + + # Dot product + >>> torch.inner(torch.tensor([1, 2, 3]), torch.tensor([0, 2, 1])) + tensor(7) + + # Multidimensional input tensors + >>> a = torch.randn(2, 3) + >>> a + tensor([[0.8173, 1.0874, 1.1784], + [0.3279, 0.1234, 2.7894]]) + >>> b = torch.randn(2, 4, 3) + >>> b + tensor([[[-0.4682, -0.7159, 0.1506], + [ 0.4034, -0.3657, 1.0387], + [ 0.9892, -0.6684, 0.1774], + [ 0.9482, 1.3261, 0.3917]], + + [[ 0.4537, 0.7493, 1.1724], + [ 0.2291, 0.5749, -0.2267], + [-0.7920, 0.3607, -0.3701], + [ 1.3666, -0.5850, -1.7242]]]) + >>> torch.inner(a, b) + tensor([[[-0.9837, 1.1560, 0.2907, 2.6785], + [ 2.5671, 0.5452, -0.6912, -1.5509]], + + [[ 0.1782, 2.9843, 0.7366, 1.5672], + [ 3.5115, -0.4864, -1.2476, -4.4337]]]) + + # Scalar input + >>> torch.inner(a, torch.tensor(2)) + tensor([[1.6347, 2.1748, 2.3567], + [0.6558, 0.2469, 5.5787]]) +""", +) + +add_docstr( + torch.outer, + r""" +outer(input, vec2, *, out=None) -> Tensor + +Outer product of :attr:`input` and :attr:`vec2`. +If :attr:`input` is a vector of size :math:`n` and :attr:`vec2` is a vector of +size :math:`m`, then :attr:`out` must be a matrix of size :math:`(n \times m)`. + +.. note:: This function does not :ref:`broadcast `. + +Args: + input (Tensor): 1-D input vector + vec2 (Tensor): 1-D input vector + +Keyword args: + out (Tensor, optional): optional output matrix + +Example:: + + >>> v1 = torch.arange(1., 5.) + >>> v2 = torch.arange(1., 4.) + >>> torch.outer(v1, v2) + tensor([[ 1., 2., 3.], + [ 2., 4., 6.], + [ 3., 6., 9.], + [ 4., 8., 12.]]) +""", +) + +add_docstr( + torch.ger, + r""" +ger(input, vec2, *, out=None) -> Tensor + +Alias of :func:`torch.outer`. + +.. warning:: + This function is deprecated and will be removed in a future PyTorch release. + Use :func:`torch.outer` instead. +""", +) + +add_docstr( + torch.get_default_dtype, + r""" +get_default_dtype() -> torch.dtype + +Get the current default floating point :class:`torch.dtype`. + +Example:: + + >>> torch.get_default_dtype() # initial default for floating point is torch.float32 + torch.float32 + >>> torch.set_default_dtype(torch.float64) + >>> torch.get_default_dtype() # default is now changed to torch.float64 + torch.float64 + +""", +) + +add_docstr( + torch.get_num_threads, + r""" +get_num_threads() -> int + +Returns the number of threads used for parallelizing CPU operations +""", +) + +add_docstr( + torch.get_num_interop_threads, + r""" +get_num_interop_threads() -> int + +Returns the number of threads used for inter-op parallelism on CPU +(e.g. in JIT interpreter) +""", +) + +add_docstr( + torch.gt, + r""" +gt(input, other, *, out=None) -> Tensor + +Computes :math:`\text{input} > \text{other}` element-wise. +""" + + r""" + +The second argument can be a number or a tensor whose shape is +:ref:`broadcastable ` with the first argument. + +Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + +Keyword args: + {out} + +Returns: + A boolean tensor that is True where :attr:`input` is greater than :attr:`other` and False elsewhere + +Example:: + + >>> torch.gt(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[False, True], [False, False]]) +""".format(**common_args), +) + +add_docstr( + torch.greater, + r""" +greater(input, other, *, out=None) -> Tensor + +Alias for :func:`torch.gt`. +""", +) + +add_docstr( + torch.hash_tensor, + r""" +hash_tensor(input, *, mode=0) -> Tensor + +Returns a hash of all elements in the :attr:`input` tensor. + +Currently only mode=0 (reduction via xor) is supported. The output will always +be of type ``torch.uint64``. The elements of ``input`` are upcasted to their +64 bit float / integer equivalent and bitcasted to ``torch.uint64`` before +reduction via xor. + +Args: + {input} + +Keyword Args: + mode (int) : The hash to use. Default: 0 (xor_reduction) + +Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 1.1918, -1.1813, 0.3373]]) + >>> torch.hash_tensor(a) + tensor(13822780554648485888, dtype=torch.uint64) + +.. function:: hash_tensor(input, dim, *, keepdim=False, mode=0) -> Tensor + :noindex: + +Returns the hash of each row of the :attr:`input` tensor in the given +dimension :attr:`dim` given by mode. If :attr:`dim` is a list of dimensions, +reduce over all of them. + +{keepdim_details} + +Args: + {input} + {opt_dim_all_reduce} + {opt_keepdim} + +Keyword Args: + mode (int) : The hash to use. Default: 0 (xor_reduction) + +Example:: + + >>> a = torch.randn(2, 4) + >>> a + tensor([[ 0.1317, -0.5554, -1.4724, -1.1391], + [ 0.0778, -0.6070, 0.6375, 0.1798]]) + >>> torch.hash_tensor(a, 1) + tensor([9233691267014066176, 9255993250844508160], dtype=torch.uint64) +""".format(**multi_dim_common), +) + +add_docstr( + torch.histc, + r""" +histc(input, bins=100, min=0, max=0, *, out=None) -> Tensor + +Computes the histogram of a tensor. + +The elements are sorted into equal width bins between :attr:`min` and +:attr:`max`. If :attr:`min` and :attr:`max` are both zero, the minimum and +maximum values of the data are used. + +Elements lower than min and higher than max and ``NaN`` elements are ignored. + +Args: + {input} + bins (int): number of histogram bins + min (Scalar): lower end of the range (inclusive) + max (Scalar): upper end of the range (inclusive) + +Keyword args: + {out} + +Returns: + Tensor: Histogram represented as a tensor + +Example:: + + >>> torch.histc(torch.tensor([1., 2, 1]), bins=4, min=0, max=3) + tensor([ 0., 2., 1., 0.]) +""".format(**common_args), +) + +add_docstr( + torch.histogram, + r""" +histogram(input, bins, *, range=None, weight=None, density=False, out=None) -> (Tensor, Tensor) + +Computes a histogram of the values in a tensor. + +:attr:`bins` can be an integer or a 1D tensor. + +If :attr:`bins` is an int, it specifies the number of equal-width bins. +By default, the lower and upper range of the bins is determined by the +minimum and maximum elements of the input tensor. The :attr:`range` +argument can be provided to specify a range for the bins. + +If :attr:`bins` is a 1D tensor, it specifies the sequence of bin edges +including the rightmost edge. It should contain at least 2 elements +and its elements should be increasing. + +Args: + {input} + bins: int or 1D Tensor. If int, defines the number of equal-width bins. If tensor, + defines the sequence of bin edges including the rightmost edge. + +Keyword args: + range (tuple of float): Defines the range of the bins. + weight (Tensor): If provided, weight should have the same shape as input. Each value in + input contributes its associated weight towards its bin's result. + density (bool): If False, the result will contain the count (or total weight) in each bin. + If True, the result is the value of the probability density function over the bins, + normalized such that the integral over the range of the bins is 1. + {out} (tuple, optional): The result tuple of two output tensors (hist, bin_edges). + +Returns: + hist (Tensor): 1D Tensor containing the values of the histogram. + bin_edges(Tensor): 1D Tensor containing the edges of the histogram bins. + +Example:: + + >>> torch.histogram(torch.tensor([1., 2, 1]), bins=4, range=(0., 3.), weight=torch.tensor([1., 2., 4.])) + (tensor([ 0., 5., 2., 0.]), tensor([0., 0.75, 1.5, 2.25, 3.])) + >>> torch.histogram(torch.tensor([1., 2, 1]), bins=4, range=(0., 3.), weight=torch.tensor([1., 2., 4.]), density=True) + (tensor([ 0., 0.9524, 0.3810, 0.]), tensor([0., 0.75, 1.5, 2.25, 3.])) +""".format(**common_args), +) + +add_docstr( + torch.histogramdd, + r""" +histogramdd(input, bins, *, range=None, weight=None, density=False, out=None) -> (Tensor, Tensor[]) + +Computes a multi-dimensional histogram of the values in a tensor. + +Interprets the elements of an input tensor whose innermost dimension has size N +as a collection of N-dimensional points. Maps each of the points into a set of +N-dimensional bins and returns the number of points (or total weight) in each bin. + +:attr:`input` must be a tensor with at least 2 dimensions. +If input has shape (M, N), each of its M rows defines a point in N-dimensional space. +If input has three or more dimensions, all but the last dimension are flattened. + +Each dimension is independently associated with its own strictly increasing sequence +of bin edges. Bin edges may be specified explicitly by passing a sequence of 1D +tensors. Alternatively, bin edges may be constructed automatically by passing a +sequence of integers specifying the number of equal-width bins in each dimension. + +For each N-dimensional point in input: + - Each of its coordinates is binned independently among the bin edges + corresponding to its dimension + - Binning results are combined to identify the N-dimensional bin (if any) + into which the point falls + - If the point falls into a bin, the bin's count (or total weight) is incremented + - Points which do not fall into any bin do not contribute to the output + +:attr:`bins` can be a sequence of N 1D tensors, a sequence of N ints, or a single int. + +If :attr:`bins` is a sequence of N 1D tensors, it explicitly specifies the N sequences +of bin edges. Each 1D tensor should contain a strictly increasing sequence with at +least one element. A sequence of K bin edges defines K-1 bins, explicitly specifying +the left and right edges of all bins. Every bin is inclusive of its left edge. Only +the rightmost bin is inclusive of its right edge. + +If :attr:`bins` is a sequence of N ints, it specifies the number of equal-width bins +in each dimension. By default, the leftmost and rightmost bin edges in each dimension +are determined by the minimum and maximum elements of the input tensor in the +corresponding dimension. The :attr:`range` argument can be provided to manually +specify the leftmost and rightmost bin edges in each dimension. + +If :attr:`bins` is an int, it specifies the number of equal-width bins for all dimensions. + +.. note:: + See also :func:`torch.histogram`, which specifically computes 1D histograms. + While :func:`torch.histogramdd` infers the dimensionality of its bins and + binned values from the shape of :attr:`input`, :func:`torch.histogram` + accepts and flattens :attr:`input` of any shape. + +Args: + {input} + bins: Tensor[], int[], or int. + If Tensor[], defines the sequences of bin edges. + If int[], defines the number of equal-width bins in each dimension. + If int, defines the number of equal-width bins for all dimensions. +Keyword args: + range (sequence of float): Defines the leftmost and rightmost bin edges + in each dimension. + weight (Tensor): By default, each value in the input has weight 1. If a weight + tensor is passed, each N-dimensional coordinate in input + contributes its associated weight towards its bin's result. + The weight tensor should have the same shape as the :attr:`input` + tensor excluding its innermost dimension N. + density (bool): If False (default), the result will contain the count (or total weight) + in each bin. If True, each count (weight) is divided by the total count + (total weight), then divided by the volume of its associated bin. +Returns: + hist (Tensor): N-dimensional Tensor containing the values of the histogram. + bin_edges(Tensor[]): sequence of N 1D Tensors containing the bin edges. + +Example:: + + >>> torch.histogramdd(torch.tensor([[0., 1.], [1., 0.], [2., 0.], [2., 2.]]), bins=[3, 3], + ... weight=torch.tensor([1., 2., 4., 8.])) + torch.return_types.histogramdd( + hist=tensor([[0., 1., 0.], + [2., 0., 0.], + [4., 0., 8.]]), + bin_edges=(tensor([0.0000, 0.6667, 1.3333, 2.0000]), + tensor([0.0000, 0.6667, 1.3333, 2.0000]))) + + >>> torch.histogramdd(torch.tensor([[0., 0.], [1., 1.], [2., 2.]]), bins=[2, 2], + ... range=[0., 1., 0., 1.], density=True) + torch.return_types.histogramdd( + hist=tensor([[2., 0.], + [0., 2.]]), + bin_edges=(tensor([0.0000, 0.5000, 1.0000]), + tensor([0.0000, 0.5000, 1.0000]))) + +""".format(**common_args), +) +# TODO: Fix via https://github.com/pytorch/pytorch/issues/75798 +torch.histogramdd.__module__ = "torch" + +add_docstr( + torch.hypot, + r""" +hypot(input, other, *, out=None) -> Tensor + +Given the legs of a right triangle, return its hypotenuse. + +.. math:: + \text{out}_{i} = \sqrt{\text{input}_{i}^{2} + \text{other}_{i}^{2}} + +The shapes of ``input`` and ``other`` must be +:ref:`broadcastable `. +""" + + r""" +Args: + input (Tensor): the first input tensor + other (Tensor): the second input tensor + +Keyword args: + {out} + +Example:: + + >>> a = torch.hypot(torch.tensor([4.0]), torch.tensor([3.0, 4.0, 5.0])) + tensor([5.0000, 5.6569, 6.4031]) + +""".format(**common_args), +) + +add_docstr( + torch.i0, + r""" +i0(input, *, out=None) -> Tensor + +Alias for :func:`torch.special.i0`. +""", +) + +add_docstr( + torch.igamma, + r""" +igamma(input, other, *, out=None) -> Tensor + +Alias for :func:`torch.special.gammainc`. +""", +) + +add_docstr( + torch.igammac, + r""" +igammac(input, other, *, out=None) -> Tensor + +Alias for :func:`torch.special.gammaincc`. +""", +) + +add_docstr( + torch.index_select, + r""" +index_select(input, dim, index, *, out=None) -> Tensor + +Returns a new tensor which indexes the :attr:`input` tensor along dimension +:attr:`dim` using the entries in :attr:`index`. + +The returned tensor has the same number of dimensions as the original tensor +(:attr:`input`). The :attr:`dim`\ th dimension has the same size as the length +of :attr:`index`; other dimensions have the same size as in the original tensor. + +.. note:: The returned tensor does **not** use the same storage as the original + tensor. If :attr:`out` has a different shape than expected, we + silently change it to the correct shape, reallocating the underlying + storage if necessary. + +Args: + {input} + dim (int): the dimension in which we index + index (IntTensor or LongTensor): the 1-D tensor containing the indices to index + +Keyword args: + {out} + +Example:: + + >>> x = torch.randn(3, 4) + >>> x + tensor([[ 0.1427, 0.0231, -0.5414, -1.0009], + [-0.4664, 0.2647, -0.1228, -1.1068], + [-1.1734, -0.6571, 0.7230, -0.6004]]) + >>> indices = torch.tensor([0, 2]) + >>> torch.index_select(x, 0, indices) + tensor([[ 0.1427, 0.0231, -0.5414, -1.0009], + [-1.1734, -0.6571, 0.7230, -0.6004]]) + >>> torch.index_select(x, 1, indices) + tensor([[ 0.1427, -0.5414], + [-0.4664, -0.1228], + [-1.1734, 0.7230]]) +""".format(**common_args), +) + +add_docstr( + torch.inverse, + r""" +inverse(input, *, out=None) -> Tensor + +Alias for :func:`torch.linalg.inv` +""", +) + +add_docstr( + torch.isin, + r""" +isin(elements, test_elements, *, assume_unique=False, invert=False) -> Tensor + +Tests if each element of :attr:`elements` is in :attr:`test_elements`. Returns +a boolean tensor of the same shape as :attr:`elements` that is True for elements +in :attr:`test_elements` and False otherwise. + +.. note:: + One of :attr:`elements` or :attr:`test_elements` can be a scalar, but not both. + +Args: + elements (Tensor or Scalar): Input elements + test_elements (Tensor or Scalar): Values against which to test for each input element + assume_unique (bool, optional): If True, assumes both :attr:`elements` and + :attr:`test_elements` contain unique elements, which can speed up the + calculation. Default: False + invert (bool, optional): If True, inverts the boolean return tensor, resulting in True + values for elements *not* in :attr:`test_elements`. Default: False + +Returns: + A boolean tensor of the same shape as :attr:`elements` that is True for elements in + :attr:`test_elements` and False otherwise + +Example: + >>> torch.isin(torch.tensor([[1, 2], [3, 4]]), torch.tensor([2, 3])) + tensor([[False, True], + [ True, False]]) +""", +) + +add_docstr( + torch.isinf, + r""" +isinf(input) -> Tensor + +Tests if each element of :attr:`input` is infinite +(positive or negative infinity) or not. + +.. note:: + Complex values are infinite when their real or imaginary part is + infinite. + +Args: + {input} + +Returns: + A boolean tensor that is True where :attr:`input` is infinite and False elsewhere + +Example:: + + >>> torch.isinf(torch.tensor([1, float('inf'), 2, float('-inf'), float('nan')])) + tensor([False, True, False, True, False]) +""".format(**common_args), +) + +add_docstr( + torch.isposinf, + r""" +isposinf(input, *, out=None) -> Tensor +Tests if each element of :attr:`input` is positive infinity or not. + +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.tensor([-float('inf'), float('inf'), 1.2]) + >>> torch.isposinf(a) + tensor([False, True, False]) +""".format(**common_args), +) + +add_docstr( + torch.isneginf, + r""" +isneginf(input, *, out=None) -> Tensor +Tests if each element of :attr:`input` is negative infinity or not. + +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.tensor([-float('inf'), float('inf'), 1.2]) + >>> torch.isneginf(a) + tensor([ True, False, False]) +""".format(**common_args), +) + +add_docstr( + torch.isclose, + r""" +isclose(input, other, rtol=1e-05, atol=1e-08, equal_nan=False) -> Tensor + +Returns a new tensor with boolean elements representing if each element of +:attr:`input` is "close" to the corresponding element of :attr:`other`. +Closeness is defined as: + +.. math:: + \lvert \text{input}_i - \text{other}_i \rvert \leq \texttt{rtol} \times \lvert \text{other}_i \rvert + \texttt{atol} +""" + + r""" + +where :attr:`input` and :attr:`other` are finite. Where :attr:`input` +and/or :attr:`other` are nonfinite they are close if and only if +they are equal, with NaNs being considered equal to each other when +:attr:`equal_nan` is True. + +Args: + input (Tensor): first tensor to compare + other (Tensor): second tensor to compare + rtol (float, optional): relative tolerance. Default: 1e-05 + atol (float, optional): absolute tolerance. Default: 1e-08 + equal_nan (bool, optional): if ``True``, then two ``NaN`` s will be considered equal. Default: ``False`` + +Examples:: + + >>> torch.isclose(torch.tensor((1., 2, 3)), torch.tensor((1 + 1e-10, 3, 4))) + tensor([ True, False, False]) + >>> torch.isclose(torch.tensor((float('inf'), 4)), torch.tensor((float('inf'), 6)), rtol=.5) + tensor([True, True]) +""", +) + +add_docstr( + torch.isfinite, + r""" +isfinite(input) -> Tensor + +Returns a new tensor with boolean elements representing if each element is `finite` or not. + +Real values are finite when they are not NaN, negative infinity, or infinity. +Complex values are finite when both their real and imaginary parts are finite. + +Args: + {input} + +Returns: + A boolean tensor that is True where :attr:`input` is finite and False elsewhere + +Example:: + + >>> torch.isfinite(torch.tensor([1, float('inf'), 2, float('-inf'), float('nan')])) + tensor([True, False, True, False, False]) +""".format(**common_args), +) + +add_docstr( + torch.isnan, + r""" +isnan(input) -> Tensor + +Returns a new tensor with boolean elements representing if each element of :attr:`input` +is NaN or not. Complex values are considered NaN when either their real +and/or imaginary part is NaN. + +Arguments: + {input} + +Returns: + A boolean tensor that is True where :attr:`input` is NaN and False elsewhere + +Example:: + + >>> torch.isnan(torch.tensor([1, float('nan'), 2])) + tensor([False, True, False]) +""".format(**common_args), +) + +add_docstr( + torch.isreal, + r""" +isreal(input) -> Tensor + +Returns a new tensor with boolean elements representing if each element of :attr:`input` is real-valued or not. +All real-valued types are considered real. Complex values are considered real when their imaginary part is 0. + +Arguments: + {input} + +Returns: + A boolean tensor that is True where :attr:`input` is real and False elsewhere + +Example:: + + >>> torch.isreal(torch.tensor([1, 1+1j, 2+0j])) + tensor([True, False, True]) +""".format(**common_args), +) + +add_docstr( + torch.is_floating_point, + r""" +is_floating_point(input: Tensor) -> bool + +Returns True if the data type of :attr:`input` is a floating point data type i.e., +one of ``torch.float64``, ``torch.float32``, ``torch.float16``, and ``torch.bfloat16``. + +Args: + {input} + +Example:: + + >>> torch.is_floating_point(torch.tensor([1.0, 2.0, 3.0])) + True + >>> torch.is_floating_point(torch.tensor([1, 2, 3], dtype=torch.int32)) + False + >>> torch.is_floating_point(torch.tensor([1.0, 2.0, 3.0], dtype=torch.float16)) + True + >>> torch.is_floating_point(torch.tensor([1, 2, 3], dtype=torch.complex64)) + False +""".format(**common_args), +) + +add_docstr( + torch.is_complex, + r""" +is_complex(input: Tensor) -> bool + +Returns True if the data type of :attr:`input` is a complex data type i.e., +one of ``torch.complex64``, and ``torch.complex128``. + +Args: + {input} + +Example:: + + >>> torch.is_complex(torch.tensor([1, 2, 3], dtype=torch.complex64)) + True + >>> torch.is_complex(torch.tensor([1, 2, 3], dtype=torch.complex128)) + True + >>> torch.is_complex(torch.tensor([1, 2, 3], dtype=torch.int32)) + False + >>> torch.is_complex(torch.tensor([1.0, 2.0, 3.0], dtype=torch.float16)) + False +""".format(**common_args), +) + +add_docstr( + torch.is_grad_enabled, + r""" +is_grad_enabled() -> (bool) + +Returns True if grad mode is currently enabled. +""".format(**common_args), +) + +add_docstr( + torch.is_inference_mode_enabled, + r""" +is_inference_mode_enabled() -> (bool) + +Returns True if inference mode is currently enabled. +""".format(**common_args), +) + +add_docstr( + torch.is_inference, + r""" +is_inference(input) -> (bool) + +Returns True if :attr:`input` is an inference tensor. + +A non-view tensor is an inference tensor if and only if it was +allocated during inference mode. A view tensor is an inference +tensor if and only if the tensor it is a view of is an inference tensor. + +For details on inference mode please see +`Inference Mode `_. + +Args: + {input} +""".format(**common_args), +) + +add_docstr( + torch.is_conj, + r""" +is_conj(input) -> (bool) + +Returns True if the :attr:`input` is a conjugated tensor, i.e. its conjugate bit is set to `True`. + +Args: + {input} +""".format(**common_args), +) + +add_docstr( + torch.is_nonzero, + r""" +is_nonzero(input) -> (bool) + +Returns True if the :attr:`input` is a single element tensor which is not equal to zero +after type conversions. +i.e. not equal to ``torch.tensor([0.])`` or ``torch.tensor([0])`` or +``torch.tensor([False])``. +Throws a ``RuntimeError`` if ``torch.numel() != 1`` (even in case +of sparse tensors). + +Args: + {input} + +Examples:: + + >>> torch.is_nonzero(torch.tensor([0.])) + False + >>> torch.is_nonzero(torch.tensor([1.5])) + True + >>> torch.is_nonzero(torch.tensor([False])) + False + >>> torch.is_nonzero(torch.tensor([3])) + True + >>> torch.is_nonzero(torch.tensor([1, 3, 5])) + Traceback (most recent call last): + ... + RuntimeError: Boolean value of Tensor with more than one value is ambiguous + >>> torch.is_nonzero(torch.tensor([])) + Traceback (most recent call last): + ... + RuntimeError: Boolean value of Tensor with no values is ambiguous +""".format(**common_args), +) + +add_docstr( + torch.kron, + r""" +kron(input, other, *, out=None) -> Tensor + +Computes the Kronecker product, denoted by :math:`\otimes`, of :attr:`input` and :attr:`other`. + +If :attr:`input` is a :math:`(a_0 \times a_1 \times \dots \times a_n)` tensor and :attr:`other` is a +:math:`(b_0 \times b_1 \times \dots \times b_n)` tensor, the result will be a +:math:`(a_0*b_0 \times a_1*b_1 \times \dots \times a_n*b_n)` tensor with the following entries: + +.. math:: + (\text{input} \otimes \text{other})_{k_0, k_1, \dots, k_n} = + \text{input}_{i_0, i_1, \dots, i_n} * \text{other}_{j_0, j_1, \dots, j_n}, + +where :math:`k_t = i_t * b_t + j_t` for :math:`0 \leq t \leq n`. +If one tensor has fewer dimensions than the other it is unsqueezed until it has the same number of dimensions. + +Supports real-valued and complex-valued inputs. + +.. note:: + This function generalizes the typical definition of the Kronecker product for two matrices to two tensors, + as described above. When :attr:`input` is a :math:`(m \times n)` matrix and :attr:`other` is a + :math:`(p \times q)` matrix, the result will be a :math:`(p*m \times q*n)` block matrix: + + .. math:: + \mathbf{A} \otimes \mathbf{B}=\begin{bmatrix} + a_{11} \mathbf{B} & \cdots & a_{1 n} \mathbf{B} \\ + \vdots & \ddots & \vdots \\ + a_{m 1} \mathbf{B} & \cdots & a_{m n} \mathbf{B} \end{bmatrix} + + where :attr:`input` is :math:`\mathbf{A}` and :attr:`other` is :math:`\mathbf{B}`. + +Arguments: + input (Tensor) + other (Tensor) + +Keyword args: + out (Tensor, optional): The output tensor. Ignored if ``None``. Default: ``None`` + +Examples:: + + >>> mat1 = torch.eye(2) + >>> mat2 = torch.ones(2, 2) + >>> torch.kron(mat1, mat2) + tensor([[1., 1., 0., 0.], + [1., 1., 0., 0.], + [0., 0., 1., 1.], + [0., 0., 1., 1.]]) + + >>> mat1 = torch.eye(2) + >>> mat2 = torch.arange(1, 5).reshape(2, 2) + >>> torch.kron(mat1, mat2) + tensor([[1., 2., 0., 0.], + [3., 4., 0., 0.], + [0., 0., 1., 2.], + [0., 0., 3., 4.]]) +""", +) + +add_docstr( + torch.kthvalue, + r""" +kthvalue(input, k, dim=None, keepdim=False, *, out=None) -> (Tensor, LongTensor) + +Returns a namedtuple ``(values, indices)`` where ``values`` is the :attr:`k` th +smallest element of each row of the :attr:`input` tensor in the given dimension +:attr:`dim`. And ``indices`` is the index location of each element found. + +If :attr:`dim` is not given, the last dimension of the `input` is chosen. + +If :attr:`keepdim` is ``True``, both the :attr:`values` and :attr:`indices` tensors +are the same size as :attr:`input`, except in the dimension :attr:`dim` where +they are of size 1. Otherwise, :attr:`dim` is squeezed +(see :func:`torch.squeeze`), resulting in both the :attr:`values` and +:attr:`indices` tensors having 1 fewer dimension than the :attr:`input` tensor. + +.. note:: + When :attr:`input` is a CUDA tensor and there are multiple valid + :attr:`k` th values, this function may nondeterministically return + :attr:`indices` for any of them. + +Args: + {input} + k (int): k for the k-th smallest element + dim (int, optional): the dimension to find the kth value along + {opt_keepdim} + +Keyword args: + out (tuple, optional): the output tuple of (Tensor, LongTensor) + can be optionally given to be used as output buffers + +Example:: + + >>> x = torch.arange(1., 6.) + >>> x + tensor([ 1., 2., 3., 4., 5.]) + >>> torch.kthvalue(x, 4) + torch.return_types.kthvalue(values=tensor(4.), indices=tensor(3)) + + >>> x=torch.arange(1.,7.).resize_(2,3) + >>> x + tensor([[ 1., 2., 3.], + [ 4., 5., 6.]]) + >>> torch.kthvalue(x, 2, 0, True) + torch.return_types.kthvalue(values=tensor([[4., 5., 6.]]), indices=tensor([[1, 1, 1]])) +""".format(**single_dim_common), +) + +add_docstr( + torch.lcm, + r""" +lcm(input, other, *, out=None) -> Tensor + +Computes the element-wise least common multiple (LCM) of :attr:`input` and :attr:`other`. + +Both :attr:`input` and :attr:`other` must have integer types. + +.. note:: + This defines :math:`lcm(0, 0) = 0` and :math:`lcm(0, a) = 0`. + +Args: + {input} + other (Tensor): the second input tensor + +Keyword arguments: + {out} + +Example:: + + >>> a = torch.tensor([5, 10, 15]) + >>> b = torch.tensor([3, 4, 5]) + >>> torch.lcm(a, b) + tensor([15, 20, 15]) + >>> c = torch.tensor([3]) + >>> torch.lcm(a, c) + tensor([15, 30, 15]) +""".format(**common_args), +) + +add_docstr( + torch.ldexp, + r""" +ldexp(input, other, *, out=None) -> Tensor + +Multiplies :attr:`input` by 2 ** :attr:`other`. + +.. math:: + \text{{out}}_i = \text{{input}}_i * 2^\text{{other}}_i +""" + + r""" + +Typically this function is used to construct floating point numbers by multiplying +mantissas in :attr:`input` with integral powers of two created from the exponents +in :attr:`other`. + +Args: + {input} + other (Tensor): a tensor of exponents, typically integers. + +Keyword args: + {out} + +Example:: + + >>> torch.ldexp(torch.tensor([1.]), torch.tensor([1])) + tensor([2.]) + >>> torch.ldexp(torch.tensor([1.0]), torch.tensor([1, 2, 3, 4])) + tensor([ 2., 4., 8., 16.]) + + +""".format(**common_args), +) + +add_docstr( + torch.le, + r""" +le(input, other, *, out=None) -> Tensor + +Computes :math:`\text{input} \leq \text{other}` element-wise. +""" + + r""" + +The second argument can be a number or a tensor whose shape is +:ref:`broadcastable ` with the first argument. + +Args: + input (Tensor): the tensor to compare + other (Tensor or Scalar): the tensor or value to compare + +Keyword args: + {out} + +Returns: + A boolean tensor that is True where :attr:`input` is less than or equal to + :attr:`other` and False elsewhere + +Example:: + + >>> torch.le(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[True, False], [True, True]]) +""".format(**common_args), +) + +add_docstr( + torch.less_equal, + r""" +less_equal(input, other, *, out=None) -> Tensor + +Alias for :func:`torch.le`. +""", +) + +add_docstr( + torch.lerp, + r""" +lerp(input, end, weight, *, out=None) + +Does a linear interpolation of two tensors :attr:`start` (given by :attr:`input`) and :attr:`end` based +on a scalar or tensor :attr:`weight` and returns the resulting :attr:`out` tensor. + +.. math:: + \text{out}_i = \text{start}_i + \text{weight}_i \times (\text{end}_i - \text{start}_i) +""" + + r""" +The shapes of :attr:`start` and :attr:`end` must be +:ref:`broadcastable `. If :attr:`weight` is a tensor, then +the shapes of :attr:`weight`, :attr:`start`, and :attr:`end` must be :ref:`broadcastable `. + +Args: + input (Tensor): the tensor with the starting points + end (Tensor): the tensor with the ending points + weight (float or tensor): the weight for the interpolation formula + +Keyword args: + {out} + +Example:: + + >>> start = torch.arange(1., 5.) + >>> end = torch.empty(4).fill_(10) + >>> start + tensor([ 1., 2., 3., 4.]) + >>> end + tensor([ 10., 10., 10., 10.]) + >>> torch.lerp(start, end, 0.5) + tensor([ 5.5000, 6.0000, 6.5000, 7.0000]) + >>> torch.lerp(start, end, torch.full_like(start, 0.5)) + tensor([ 5.5000, 6.0000, 6.5000, 7.0000]) +""".format(**common_args), +) + +add_docstr( + torch.lgamma, + r""" +lgamma(input, *, out=None) -> Tensor + +Computes the natural logarithm of the absolute value of the gamma function on :attr:`input`. + +.. math:: + \text{out}_{i} = \ln |\Gamma(\text{input}_{i})| +""" + + """ +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.arange(0.5, 2, 0.5) + >>> torch.lgamma(a) + tensor([ 0.5724, 0.0000, -0.1208]) +""".format(**common_args), +) + +add_docstr( + torch.linspace, + r""" +linspace(start, end, steps, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + +Creates a one-dimensional tensor of size :attr:`steps` whose values are evenly +spaced from :attr:`start` to :attr:`end`, inclusive. That is, the value are: + +.. math:: + (\text{start}, + \text{start} + \frac{\text{end} - \text{start}}{\text{steps} - 1}, + \ldots, + \text{start} + (\text{steps} - 2) * \frac{\text{end} - \text{start}}{\text{steps} - 1}, + \text{end}) +""" + + """ + +From PyTorch 1.11 linspace requires the steps argument. Use steps=100 to restore the previous behavior. + +Args: + start (float or Tensor): the starting value for the set of points. If `Tensor`, it must be 0-dimensional + end (float or Tensor): the ending value for the set of points. If `Tensor`, it must be 0-dimensional + steps (int): size of the constructed tensor + +Keyword arguments: + {out} + dtype (torch.dtype, optional): the data type to perform the computation in. + Default: if None, uses the global default dtype (see torch.get_default_dtype()) + when both :attr:`start` and :attr:`end` are real, + and corresponding complex dtype when either is complex. + {layout} + {device} + {requires_grad} + + +Example:: + + >>> torch.linspace(3, 10, steps=5) + tensor([ 3.0000, 4.7500, 6.5000, 8.2500, 10.0000]) + >>> torch.linspace(-10, 10, steps=5) + tensor([-10., -5., 0., 5., 10.]) + >>> torch.linspace(start=-10, end=10, steps=5) + tensor([-10., -5., 0., 5., 10.]) + >>> torch.linspace(start=-10, end=10, steps=1) + tensor([-10.]) +""".format(**factory_common_args), +) + +add_docstr( + torch.log, + r""" +log(input, *, out=None) -> Tensor + +Returns a new tensor with the natural logarithm of the elements +of :attr:`input`. + +.. math:: + y_{i} = \log_{e} (x_{i}) +""" + + r""" + +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.rand(5) * 5 + >>> a + tensor([4.7767, 4.3234, 1.2156, 0.2411, 4.5739]) + >>> torch.log(a) + tensor([ 1.5637, 1.4640, 0.1952, -1.4226, 1.5204]) +""".format(**common_args), +) + +add_docstr( + torch.log10, + r""" +log10(input: Tensor, *, out: Optional[Tensor]) -> Tensor + +Returns a new tensor with the logarithm to the base 10 of the elements +of :attr:`input`. + +.. math:: + y_{i} = \log_{10} (x_{i}) +""" + + r""" + +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.rand(5) + >>> a + tensor([ 0.5224, 0.9354, 0.7257, 0.1301, 0.2251]) + + + >>> torch.log10(a) + tensor([-0.2820, -0.0290, -0.1392, -0.8857, -0.6476]) + +""".format(**common_args), +) + +add_docstr( + torch.log1p, + r""" +log1p(input, *, out=None) -> Tensor + +Returns a new tensor with the natural logarithm of (1 + :attr:`input`). + +.. math:: + y_i = \log_{e} (x_i + 1) +""" + + r""" +.. note:: This function is more accurate than :func:`torch.log` for small + values of :attr:`input` + +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(5) + >>> a + tensor([-1.0090, -0.9923, 1.0249, -0.5372, 0.2492]) + >>> torch.log1p(a) + tensor([ nan, -4.8653, 0.7055, -0.7705, 0.2225]) +""".format(**common_args), +) + +add_docstr( + torch.log2, + r""" +log2(input: Tensor, *, out: Optional[Tensor]) -> Tensor + +Returns a new tensor with the logarithm to the base 2 of the elements +of :attr:`input`. + +.. math:: + y_{i} = \log_{2} (x_{i}) +""" + + r""" + +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.rand(5) + >>> a + tensor([ 0.8419, 0.8003, 0.9971, 0.5287, 0.0490]) + + + >>> torch.log2(a) + tensor([-0.2483, -0.3213, -0.0042, -0.9196, -4.3504]) + +""".format(**common_args), +) + +add_docstr( + torch.logaddexp, + r""" +logaddexp(input, other, *, out=None) -> Tensor + +Logarithm of the sum of exponentiations of the inputs. + +Calculates pointwise :math:`\log\left(e^x + e^y\right)`. This function is useful +in statistics where the calculated probabilities of events may be so small as to +exceed the range of normal floating point numbers. In such cases the logarithm +of the calculated probability is stored. This function allows adding +probabilities stored in such a fashion. + +This op should be disambiguated with :func:`torch.logsumexp` which performs a +reduction on a single tensor. + +Args: + {input} + other (Tensor): the second input tensor + +Keyword arguments: + {out} + +Example:: + + >>> torch.logaddexp(torch.tensor([-1.0]), torch.tensor([-1.0, -2, -3])) + tensor([-0.3069, -0.6867, -0.8731]) + >>> torch.logaddexp(torch.tensor([-100.0, -200, -300]), torch.tensor([-1.0, -2, -3])) + tensor([-1., -2., -3.]) + >>> torch.logaddexp(torch.tensor([1.0, 2000, 30000]), torch.tensor([-1.0, -2, -3])) + tensor([1.1269e+00, 2.0000e+03, 3.0000e+04]) +""".format(**common_args), +) + +add_docstr( + torch.logaddexp2, + r""" +logaddexp2(input, other, *, out=None) -> Tensor + +Logarithm of the sum of exponentiations of the inputs in base-2. + +Calculates pointwise :math:`\log_2\left(2^x + 2^y\right)`. See +:func:`torch.logaddexp` for more details. + +Args: + {input} + other (Tensor): the second input tensor + +Keyword arguments: + {out} +""".format(**common_args), +) + +add_docstr( + torch.xlogy, + r""" +xlogy(input, other, *, out=None) -> Tensor + +Alias for :func:`torch.special.xlogy`. +""", +) + +add_docstr( + torch.logical_and, + r""" +logical_and(input, other, *, out=None) -> Tensor + +Computes the element-wise logical AND of the given input tensors. Zeros are treated as ``False`` and nonzeros are +treated as ``True``. + +Args: + {input} + other (Tensor): the tensor to compute AND with + +Keyword args: + {out} + +Example:: + + >>> torch.logical_and(torch.tensor([True, False, True]), torch.tensor([True, False, False])) + tensor([ True, False, False]) + >>> a = torch.tensor([0, 1, 10, 0], dtype=torch.int8) + >>> b = torch.tensor([4, 0, 1, 0], dtype=torch.int8) + >>> torch.logical_and(a, b) + tensor([False, False, True, False]) + >>> torch.logical_and(a.double(), b.double()) + tensor([False, False, True, False]) + >>> torch.logical_and(a.double(), b) + tensor([False, False, True, False]) + >>> torch.logical_and(a, b, out=torch.empty(4, dtype=torch.bool)) + tensor([False, False, True, False]) +""".format(**common_args), +) + +add_docstr( + torch.logical_not, + r""" +logical_not(input, *, out=None) -> Tensor + +Computes the element-wise logical NOT of the given input tensor. If not specified, the output tensor will have the bool +dtype. If the input tensor is not a bool tensor, zeros are treated as ``False`` and non-zeros are treated as ``True``. + +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> torch.logical_not(torch.tensor([True, False])) + tensor([False, True]) + >>> torch.logical_not(torch.tensor([0, 1, -10], dtype=torch.int8)) + tensor([ True, False, False]) + >>> torch.logical_not(torch.tensor([0., 1.5, -10.], dtype=torch.double)) + tensor([ True, False, False]) + >>> torch.logical_not(torch.tensor([0., 1., -10.], dtype=torch.double), out=torch.empty(3, dtype=torch.int16)) + tensor([1, 0, 0], dtype=torch.int16) +""".format(**common_args), +) + +add_docstr( + torch.logical_or, + r""" +logical_or(input, other, *, out=None) -> Tensor + +Computes the element-wise logical OR of the given input tensors. Zeros are treated as ``False`` and nonzeros are +treated as ``True``. + +Args: + {input} + other (Tensor): the tensor to compute OR with + +Keyword args: + {out} + +Example:: + + >>> torch.logical_or(torch.tensor([True, False, True]), torch.tensor([True, False, False])) + tensor([ True, False, True]) + >>> a = torch.tensor([0, 1, 10, 0], dtype=torch.int8) + >>> b = torch.tensor([4, 0, 1, 0], dtype=torch.int8) + >>> torch.logical_or(a, b) + tensor([ True, True, True, False]) + >>> torch.logical_or(a.double(), b.double()) + tensor([ True, True, True, False]) + >>> torch.logical_or(a.double(), b) + tensor([ True, True, True, False]) + >>> torch.logical_or(a, b, out=torch.empty(4, dtype=torch.bool)) + tensor([ True, True, True, False]) +""".format(**common_args), +) + +add_docstr( + torch.logical_xor, + r""" +logical_xor(input: Tensor, other: Tensor, *, out: Optional[Tensor]) -> Tensor + +Computes the element-wise logical XOR of the given input tensors. Zeros are treated as ``False`` and nonzeros are +treated as ``True``. + +Args: + {input} + other (Tensor): the tensor to compute XOR with + +Keyword args: + {out} + +Example:: + + >>> torch.logical_xor(torch.tensor([True, False, True]), torch.tensor([True, False, False])) + tensor([False, False, True]) + >>> a = torch.tensor([0, 1, 10, 0], dtype=torch.int8) + >>> b = torch.tensor([4, 0, 1, 0], dtype=torch.int8) + >>> torch.logical_xor(a, b) + tensor([ True, True, False, False]) + >>> torch.logical_xor(a.double(), b.double()) + tensor([ True, True, False, False]) + >>> torch.logical_xor(a.double(), b) + tensor([ True, True, False, False]) + >>> torch.logical_xor(a, b, out=torch.empty(4, dtype=torch.bool)) + tensor([ True, True, False, False]) +""".format(**common_args), +) + +add_docstr( + torch.logspace, + """ +logspace(start, end, steps, base=10.0, *, \ + out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor +""" + + r""" + +Creates a one-dimensional tensor of size :attr:`steps` whose values are evenly +spaced from :math:`{{\text{{base}}}}^{{\text{{start}}}}` to +:math:`{{\text{{base}}}}^{{\text{{end}}}}`, inclusive, on a logarithmic scale +with base :attr:`base`. That is, the values are: + +.. math:: + (\text{base}^{\text{start}}, + \text{base}^{(\text{start} + \frac{\text{end} - \text{start}}{ \text{steps} - 1})}, + \ldots, + \text{base}^{(\text{start} + (\text{steps} - 2) * \frac{\text{end} - \text{start}}{ \text{steps} - 1})}, + \text{base}^{\text{end}}) +""" + + """ + + +From PyTorch 1.11 logspace requires the steps argument. Use steps=100 to restore the previous behavior. + +Args: + start (float or Tensor): the starting value for the set of points. If `Tensor`, it must be 0-dimensional + end (float or Tensor): the ending value for the set of points. If `Tensor`, it must be 0-dimensional + steps (int): size of the constructed tensor + base (float, optional): base of the logarithm function. Default: ``10.0``. + +Keyword arguments: + {out} + dtype (torch.dtype, optional): the data type to perform the computation in. + Default: if None, uses the global default dtype (see torch.get_default_dtype()) + when both :attr:`start` and :attr:`end` are real, + and corresponding complex dtype when either is complex. + {layout} + {device} + {requires_grad} + +Example:: + + >>> torch.logspace(start=-10, end=10, steps=5) + tensor([ 1.0000e-10, 1.0000e-05, 1.0000e+00, 1.0000e+05, 1.0000e+10]) + >>> torch.logspace(start=0.1, end=1.0, steps=5) + tensor([ 1.2589, 2.1135, 3.5481, 5.9566, 10.0000]) + >>> torch.logspace(start=0.1, end=1.0, steps=1) + tensor([1.2589]) + >>> torch.logspace(start=2, end=2, steps=1, base=2) + tensor([4.0]) +""".format(**factory_common_args), +) + +add_docstr( + torch.logsumexp, + r""" +logsumexp(input, dim, keepdim=False, *, out=None) + +Returns the log of summed exponentials of each row of the :attr:`input` +tensor in the given dimension :attr:`dim`. The computation is numerically +stabilized. + +For summation index :math:`j` given by `dim` and other indices :math:`i`, the result is + + .. math:: + \text{{logsumexp}}(x)_{{i}} = \log \sum_j \exp(x_{{ij}}) + +{keepdim_details} + +Args: + {input} + {dim} + {opt_keepdim} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(3, 3) + >>> torch.logsumexp(a, 1) + tensor([1.4907, 1.0593, 1.5696]) + >>> torch.dist(torch.logsumexp(a, 1), torch.log(torch.sum(torch.exp(a), 1))) + tensor(1.6859e-07) +""".format(**multi_dim_common), +) + +add_docstr( + torch.lt, + r""" +lt(input, other, *, out=None) -> Tensor + +Computes :math:`\text{input} < \text{other}` element-wise. +""" + + r""" + +The second argument can be a number or a tensor whose shape is +:ref:`broadcastable ` with the first argument. + +Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + +Keyword args: + {out} + +Returns: + A boolean tensor that is True where :attr:`input` is less than :attr:`other` and False elsewhere + +Example:: + + >>> torch.lt(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[False, False], [True, False]]) +""".format(**common_args), +) + +add_docstr( + torch.lu_unpack, + r""" +lu_unpack(LU_data, LU_pivots, unpack_data=True, unpack_pivots=True, *, out=None) -> (Tensor, Tensor, Tensor) + +Unpacks the LU decomposition returned by :func:`~linalg.lu_factor` into the `P, L, U` matrices. + +.. seealso:: + + :func:`~linalg.lu` returns the matrices from the LU decomposition. Its gradient formula is more efficient + than that of doing :func:`~linalg.lu_factor` followed by :func:`~linalg.lu_unpack`. + +Args: + LU_data (Tensor): the packed LU factorization data + LU_pivots (Tensor): the packed LU factorization pivots + unpack_data (bool): flag indicating if the data should be unpacked. + If ``False``, then the returned ``L`` and ``U`` are empty tensors. + Default: ``True`` + unpack_pivots (bool): flag indicating if the pivots should be unpacked into a permutation matrix ``P``. + If ``False``, then the returned ``P`` is an empty tensor. + Default: ``True`` + +Keyword args: + out (tuple, optional): output tuple of three tensors. Ignored if `None`. + +Returns: + A namedtuple ``(P, L, U)`` + +Examples:: + + >>> A = torch.randn(2, 3, 3) + >>> LU, pivots = torch.linalg.lu_factor(A) + >>> P, L, U = torch.lu_unpack(LU, pivots) + >>> # We can recover A from the factorization + >>> A_ = P @ L @ U + >>> torch.allclose(A, A_) + True + + >>> # LU factorization of a rectangular matrix: + >>> A = torch.randn(2, 3, 2) + >>> LU, pivots = torch.linalg.lu_factor(A) + >>> P, L, U = torch.lu_unpack(LU, pivots) + >>> # P, L, U are the same as returned by linalg.lu + >>> P_, L_, U_ = torch.linalg.lu(A) + >>> torch.allclose(P, P_) and torch.allclose(L, L_) and torch.allclose(U, U_) + True + +""".format(**common_args), +) + +add_docstr( + torch.less, + r""" +less(input, other, *, out=None) -> Tensor + +Alias for :func:`torch.lt`. +""", +) + +add_docstr( + torch.lu_solve, + r""" +lu_solve(b, LU_data, LU_pivots, *, out=None) -> Tensor + +Returns the LU solve of the linear system :math:`Ax = b` using the partially pivoted +LU factorization of A from :func:`~linalg.lu_factor`. + +This function supports ``float``, ``double``, ``cfloat`` and ``cdouble`` dtypes for :attr:`input`. + +.. warning:: + + :func:`torch.lu_solve` is deprecated in favor of :func:`torch.linalg.lu_solve`. + :func:`torch.lu_solve` will be removed in a future PyTorch release. + ``X = torch.lu_solve(B, LU, pivots)`` should be replaced with + + .. code:: python + + X = linalg.lu_solve(LU, pivots, B) + +Arguments: + b (Tensor): the RHS tensor of size :math:`(*, m, k)`, where :math:`*` + is zero or more batch dimensions. + LU_data (Tensor): the pivoted LU factorization of A from :meth:`~linalg.lu_factor` of size :math:`(*, m, m)`, + where :math:`*` is zero or more batch dimensions. + LU_pivots (IntTensor): the pivots of the LU factorization from :meth:`~linalg.lu_factor` of size :math:`(*, m)`, + where :math:`*` is zero or more batch dimensions. + The batch dimensions of :attr:`LU_pivots` must be equal to the batch dimensions of + :attr:`LU_data`. + +Keyword args: + {out} + +Example:: + + >>> A = torch.randn(2, 3, 3) + >>> b = torch.randn(2, 3, 1) + >>> LU, pivots = torch.linalg.lu_factor(A) + >>> x = torch.lu_solve(b, LU, pivots) + >>> torch.dist(A @ x, b) + tensor(1.00000e-07 * + 2.8312) +""".format(**common_args), +) + +add_docstr( + torch.masked_select, + r""" +masked_select(input, mask, *, out=None) -> Tensor + +Returns a new 1-D tensor which indexes the :attr:`input` tensor according to +the boolean mask :attr:`mask` which is a `BoolTensor`. + +The shapes of the :attr:`mask` tensor and the :attr:`input` tensor don't need +to match, but they must be :ref:`broadcastable `. + +.. note:: The returned tensor does **not** use the same storage + as the original tensor + +Args: + {input} + mask (BoolTensor): the tensor containing the binary mask to index with + +Keyword args: + {out} + +Example:: + + >>> x = torch.randn(3, 4) + >>> x + tensor([[ 0.3552, -2.3825, -0.8297, 0.3477], + [-1.2035, 1.2252, 0.5002, 0.6248], + [ 0.1307, -2.0608, 0.1244, 2.0139]]) + >>> mask = x.ge(0.5) + >>> mask + tensor([[False, False, False, False], + [False, True, True, True], + [False, False, False, True]]) + >>> torch.masked_select(x, mask) + tensor([ 1.2252, 0.5002, 0.6248, 2.0139]) +""".format(**common_args), +) + +add_docstr( + torch.matrix_power, + r""" +matrix_power(input, n, *, out=None) -> Tensor + +Alias for :func:`torch.linalg.matrix_power` +""", +) + +add_docstr( + torch.matrix_exp, + r""" +matrix_exp(A) -> Tensor + +Alias for :func:`torch.linalg.matrix_exp`. +""", +) + +add_docstr( + torch.max, + r""" +max(input, *, out=None) -> Tensor + +Returns the maximum value of all elements in the ``input`` tensor. + +.. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.6763, 0.7445, -2.2369]]) + >>> torch.max(a) + tensor(0.7445) + +.. function:: max(input, dim, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + +Returns a namedtuple ``(values, indices)`` where ``values`` is the maximum +value of each row of the :attr:`input` tensor in the given dimension +:attr:`dim`. And ``indices`` is the index location of each maximum value found +(argmax). + +If ``keepdim`` is ``True``, the output tensors are of the same size +as ``input`` except in the dimension ``dim`` where they are of size 1. +Otherwise, ``dim`` is squeezed (see :func:`torch.squeeze`), resulting +in the output tensors having 1 fewer dimension than ``input``. + +.. note:: If there are multiple maximal values in a reduced row then + the indices of the first maximal value are returned. + +Args: + {input} + {opt_dim_without_none} + {opt_keepdim} + +Keyword args: + out (tuple, optional): the result tuple of two output tensors (max, max_indices) + +Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-1.2360, -0.2942, -0.1222, 0.8475], + [ 1.1949, -1.1127, -2.2379, -0.6702], + [ 1.5717, -0.9207, 0.1297, -1.8768], + [-0.6172, 1.0036, -0.6060, -0.2432]]) + >>> torch.max(a, 1) + torch.return_types.max(values=tensor([0.8475, 1.1949, 1.5717, 1.0036]), indices=tensor([3, 0, 0, 1])) + >>> a = torch.tensor([[1.0, 2.0], [3.0, 4.0]]) + >>> a.max(dim=1, keepdim=True) + torch.return_types.max( + values=tensor([[2.], [4.]]), + indices=tensor([[1], [1]])) + >>> a.max(dim=1, keepdim=False) + torch.return_types.max( + values=tensor([2., 4.]), + indices=tensor([1, 1])) + +.. function:: max(input, other, *, out=None) -> Tensor + :noindex: + +See :func:`torch.maximum`. + +""".format(**single_dim_common), +) + +add_docstr( + torch.maximum, + r""" +maximum(input, other, *, out=None) -> Tensor + +Computes the element-wise maximum of :attr:`input` and :attr:`other`. + +.. note:: + If one of the elements being compared is a NaN, then that element is returned. + :func:`maximum` is not supported for tensors with complex dtypes. + +Args: + {input} + other (Tensor): the second input tensor + +Keyword args: + {out} + +Example:: + + >>> a = torch.tensor((1, 2, -1)) + >>> b = torch.tensor((3, 0, 4)) + >>> torch.maximum(a, b) + tensor([3, 2, 4]) +""".format(**common_args), +) + +add_docstr( + torch.fmax, + r""" +fmax(input, other, *, out=None) -> Tensor + +Computes the element-wise maximum of :attr:`input` and :attr:`other`. + +This is like :func:`torch.maximum` except it handles NaNs differently: +if exactly one of the two elements being compared is a NaN then the non-NaN element is taken as the maximum. +Only if both elements are NaN is NaN propagated. + +This function is a wrapper around C++'s ``std::fmax`` and is similar to NumPy's ``fmax`` function. + +Supports :ref:`broadcasting to a common shape `, +:ref:`type promotion `, and integer and floating-point inputs. + +Args: + {input} + other (Tensor): the second input tensor + +Keyword args: + {out} + +Example:: + + >>> a = torch.tensor([9.7, float('nan'), 3.1, float('nan')]) + >>> b = torch.tensor([-2.2, 0.5, float('nan'), float('nan')]) + >>> torch.fmax(a, b) + tensor([9.7000, 0.5000, 3.1000, nan]) +""".format(**common_args), +) + +add_docstr( + torch.amax, + r""" +amax(input, dim, keepdim=False, *, out=None) -> Tensor + +Returns the maximum value of each slice of the :attr:`input` tensor in the given +dimension(s) :attr:`dim`. + +.. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + +{keepdim_details} + +Args: + {input} + {opt_dim_all_reduce} + {opt_keepdim} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.8177, 1.4878, -0.2491, 0.9130], + [-0.7158, 1.1775, 2.0992, 0.4817], + [-0.0053, 0.0164, -1.3738, -0.0507], + [ 1.9700, 1.1106, -1.0318, -1.0816]]) + >>> torch.amax(a, 1) + tensor([1.4878, 2.0992, 0.0164, 1.9700]) +""".format(**multi_dim_common), +) + +add_docstr( + torch.argmax, + r""" +argmax(input) -> LongTensor + +Returns the indices of the maximum value of all elements in the :attr:`input` tensor. + +This is the second value returned by :meth:`torch.max`. See its +documentation for the exact semantics of this method. + +.. note:: If there are multiple maximal values then the indices of the first maximal value are returned. + +Args: + {input} + +Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 1.3398, 0.2663, -0.2686, 0.2450], + [-0.7401, -0.8805, -0.3402, -1.1936], + [ 0.4907, -1.3948, -1.0691, -0.3132], + [-1.6092, 0.5419, -0.2993, 0.3195]]) + >>> torch.argmax(a) + tensor(0) + +.. function:: argmax(input, dim, keepdim=False) -> LongTensor + :noindex: + +Returns the indices of the maximum values of a tensor across a dimension. + +This is the second value returned by :meth:`torch.max`. See its +documentation for the exact semantics of this method. + +Args: + {input} + {opt_dim} If ``None``, the argmax of the flattened input is returned. + {opt_keepdim} + +Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 1.3398, 0.2663, -0.2686, 0.2450], + [-0.7401, -0.8805, -0.3402, -1.1936], + [ 0.4907, -1.3948, -1.0691, -0.3132], + [-1.6092, 0.5419, -0.2993, 0.3195]]) + >>> torch.argmax(a, dim=1) + tensor([ 0, 2, 0, 1]) +""".format(**single_dim_common), +) + +add_docstr( + torch.argwhere, + r""" +argwhere(input) -> Tensor + +Returns a tensor containing the indices of all non-zero elements of +:attr:`input`. Each row in the result contains the indices of a non-zero +element in :attr:`input`. The result is sorted lexicographically, with +the last index changing the fastest (C-style). + +If :attr:`input` has :math:`n` dimensions, then the resulting indices tensor +:attr:`out` is of size :math:`(z \times n)`, where :math:`z` is the total number of +non-zero elements in the :attr:`input` tensor. + +.. note:: + This function is similar to NumPy's `argwhere`. + + When :attr:`input` is on CUDA, this function causes host-device synchronization. + +Args: + {input} + +Example:: + + >>> t = torch.tensor([1, 0, 1]) + >>> torch.argwhere(t) + tensor([[0], + [2]]) + >>> t = torch.tensor([[1, 0, 1], [0, 1, 1]]) + >>> torch.argwhere(t) + tensor([[0, 0], + [0, 2], + [1, 1], + [1, 2]]) +""", +) + +add_docstr( + torch.mean, + r""" +mean(input, *, dtype=None) -> Tensor + +.. note:: + If the `input` tensor is empty, ``torch.mean()`` returns ``nan``. + This behavior is consistent with NumPy and follows the definition + that the mean over an empty set is undefined. + + +Returns the mean value of all elements in the :attr:`input` tensor. Input must be floating point or complex. + +Args: + input (Tensor): + the input tensor, either of floating point or complex dtype + +Keyword args: + {dtype} + +Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.2294, -0.5481, 1.3288]]) + >>> torch.mean(a) + tensor(0.3367) + +.. function:: mean(input, dim, keepdim=False, *, dtype=None, out=None) -> Tensor + :noindex: + +Returns the mean value of each row of the :attr:`input` tensor in the given +dimension :attr:`dim`. If :attr:`dim` is a list of dimensions, +reduce over all of them. + +{keepdim_details} + +Args: + {input} + {opt_dim_all_reduce} + {opt_keepdim} + +Keyword args: + {dtype} + {out} + +.. seealso:: + + :func:`torch.nanmean` computes the mean value of `non-NaN` elements. + +Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-0.3841, 0.6320, 0.4254, -0.7384], + [-0.9644, 1.0131, -0.6549, -1.4279], + [-0.2951, -1.3350, -0.7694, 0.5600], + [ 1.0842, -0.9580, 0.3623, 0.2343]]) + >>> torch.mean(a, 1) + tensor([-0.0163, -0.5085, -0.4599, 0.1807]) + >>> torch.mean(a, 1, True) + tensor([[-0.0163], + [-0.5085], + [-0.4599], + [ 0.1807]]) +""".format(**multi_dim_common), +) + +add_docstr( + torch.nanmean, + r""" +nanmean(input, dim=None, keepdim=False, *, dtype=None, out=None) -> Tensor + +Computes the mean of all `non-NaN` elements along the specified dimensions. +Input must be floating point or complex. + +This function is identical to :func:`torch.mean` when there are no `NaN` values +in the :attr:`input` tensor. In the presence of `NaN`, :func:`torch.mean` will +propagate the `NaN` to the output whereas :func:`torch.nanmean` will ignore the +`NaN` values (`torch.nanmean(a)` is equivalent to `torch.mean(a[~a.isnan()])`). + +{keepdim_details} + +Args: + input (Tensor): the input tensor, either of floating point or complex dtype + {opt_dim_all_reduce} + {opt_keepdim} + +Keyword args: + {dtype} + {out} + +.. seealso:: + + :func:`torch.mean` computes the mean value, propagating `NaN`. + +Example:: + + >>> x = torch.tensor([[torch.nan, 1, 2], [1, 2, 3]]) + >>> x.mean() + tensor(nan) + >>> x.nanmean() + tensor(1.8000) + >>> x.mean(dim=0) + tensor([ nan, 1.5000, 2.5000]) + >>> x.nanmean(dim=0) + tensor([1.0000, 1.5000, 2.5000]) + + # If all elements in the reduced dimensions are NaN then the result is NaN + >>> torch.tensor([torch.nan]).nanmean() + tensor(nan) +""".format(**multi_dim_common), +) + +add_docstr( + torch.median, + r""" +median(input) -> Tensor + +Returns the median of the values in :attr:`input`. + +.. note:: + The median is not unique for :attr:`input` tensors with an even number + of elements. In this case the lower of the two medians is returned. To + compute the mean of both medians, use :func:`torch.quantile` with ``q=0.5`` instead. + +.. warning:: + This function produces deterministic (sub)gradients unlike ``median(dim=0)`` + +Args: + {input} + +Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 1.5219, -1.5212, 0.2202]]) + >>> torch.median(a) + tensor(0.2202) + +.. function:: median(input, dim=-1, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + +Returns a namedtuple ``(values, indices)`` where ``values`` contains the median of each row of :attr:`input` +in the dimension :attr:`dim`, and ``indices`` contains the index of the median values found in the dimension :attr:`dim`. + +By default, :attr:`dim` is the last dimension of the :attr:`input` tensor. + +If :attr:`keepdim` is ``True``, the output tensors are of the same size +as :attr:`input` except in the dimension :attr:`dim` where they are of size 1. +Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in +the outputs tensor having 1 fewer dimension than :attr:`input`. + +.. note:: + The median is not unique for :attr:`input` tensors with an even number + of elements in the dimension :attr:`dim`. In this case the lower of the + two medians is returned. To compute the mean of both medians in + :attr:`input`, use :func:`torch.quantile` with ``q=0.5`` instead. + +.. warning:: + ``indices`` does not necessarily contain the first occurrence of each + median value found, unless it is unique. + The exact implementation details are device-specific. + Do not expect the same result when run on CPU and GPU in general. + For the same reason do not expect the gradients to be deterministic. + +Args: + {input} + {opt_dim_all_reduce} + {opt_keepdim} + +Keyword args: + out ((Tensor, Tensor), optional): The first tensor will be populated with the median values and the second + tensor, which must have dtype long, with their indices in the dimension + :attr:`dim` of :attr:`input`. + +Example:: + + >>> a = torch.randn(4, 5) + >>> a + tensor([[ 0.2505, -0.3982, -0.9948, 0.3518, -1.3131], + [ 0.3180, -0.6993, 1.0436, 0.0438, 0.2270], + [-0.2751, 0.7303, 0.2192, 0.3321, 0.2488], + [ 1.0778, -1.9510, 0.7048, 0.4742, -0.7125]]) + >>> torch.median(a, 1) + torch.return_types.median(values=tensor([-0.3982, 0.2270, 0.2488, 0.4742]), indices=tensor([1, 4, 4, 3])) +""".format(**single_dim_common), +) + +add_docstr( + torch.nanmedian, + r""" +nanmedian(input) -> Tensor + +Returns the median of the values in :attr:`input`, ignoring ``NaN`` values. + +This function is identical to :func:`torch.median` when there are no ``NaN`` values in :attr:`input`. +When :attr:`input` has one or more ``NaN`` values, :func:`torch.median` will always return ``NaN``, +while this function will return the median of the non-``NaN`` elements in :attr:`input`. +If all the elements in :attr:`input` are ``NaN`` it will also return ``NaN``. + +Args: + {input} + +Example:: + + >>> a = torch.tensor([1, float('nan'), 3, 2]) + >>> a.median() + tensor(nan) + >>> a.nanmedian() + tensor(2.) + +.. function:: nanmedian(input, dim=-1, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + +Returns a namedtuple ``(values, indices)`` where ``values`` contains the median of each row of :attr:`input` +in the dimension :attr:`dim`, ignoring ``NaN`` values, and ``indices`` contains the index of the median values +found in the dimension :attr:`dim`. + +This function is identical to :func:`torch.median` when there are no ``NaN`` values in a reduced row. When a reduced row has +one or more ``NaN`` values, :func:`torch.median` will always reduce it to ``NaN``, while this function will reduce it to the +median of the non-``NaN`` elements. If all the elements in a reduced row are ``NaN`` then it will be reduced to ``NaN``, too. + +Args: + {input} + {opt_dim_all_reduce} + {opt_keepdim} + +Keyword args: + out ((Tensor, Tensor), optional): The first tensor will be populated with the median values and the second + tensor, which must have dtype long, with their indices in the dimension + :attr:`dim` of :attr:`input`. + +Example:: + + >>> a = torch.tensor([[2, 3, 1], [float('nan'), 1, float('nan')]]) + >>> a + tensor([[2., 3., 1.], + [nan, 1., nan]]) + >>> a.median(0) + torch.return_types.median(values=tensor([nan, 1., nan]), indices=tensor([1, 1, 1])) + >>> a.nanmedian(0) + torch.return_types.nanmedian(values=tensor([2., 1., 1.]), indices=tensor([0, 1, 0])) +""".format(**single_dim_common), +) + +add_docstr( + torch.quantile, + r""" +quantile(input, q, dim=None, keepdim=False, *, interpolation='linear', out=None) -> Tensor + +Computes the q-th quantiles of each row of the :attr:`input` tensor along the dimension :attr:`dim`. + +To compute the quantile, we map q in [0, 1] to the range of indices [0, n] to find the location +of the quantile in the sorted input. If the quantile lies between two data points ``a < b`` with +indices ``i`` and ``j`` in the sorted order, result is computed according to the given +:attr:`interpolation` method as follows: + +- ``linear``: ``a + (b - a) * fraction``, where ``fraction`` is the fractional part of the computed quantile index. +- ``lower``: ``a``. +- ``higher``: ``b``. +- ``nearest``: ``a`` or ``b``, whichever's index is closer to the computed quantile index (follows :func:`torch.round`). +- ``midpoint``: ``(a + b) / 2``. + +If :attr:`q` is a 1D tensor, the first dimension of the output represents the quantiles and has size +equal to the size of :attr:`q`, the remaining dimensions are what remains from the reduction. + +.. note:: + By default :attr:`dim` is ``None`` resulting in the :attr:`input` tensor being flattened before computation. + +Args: + {input} + q (float or Tensor): a scalar or 1D tensor of values in the range [0, 1]. + {opt_dim} + {opt_keepdim} + +Keyword arguments: + interpolation (str, optional): interpolation method to use when the desired quantile lies between two data points. + Can be ``linear``, ``lower``, ``higher``, ``midpoint`` and ``nearest``. + Default is ``linear``. + {out} + +Example:: + + >>> a = torch.randn(2, 3) + >>> a + tensor([[ 0.0795, -1.2117, 0.9765], + [ 1.1707, 0.6706, 0.4884]]) + >>> q = torch.tensor([0.25, 0.5, 0.75]) + >>> torch.quantile(a, q, dim=1, keepdim=True) + tensor([[[-0.5661], + [ 0.5795]], + + [[ 0.0795], + [ 0.6706]], + + [[ 0.5280], + [ 0.9206]]]) + >>> torch.quantile(a, q, dim=1, keepdim=True).shape + torch.Size([3, 2, 1]) + >>> a = torch.arange(4.) + >>> a + tensor([0., 1., 2., 3.]) + >>> torch.quantile(a, 0.6, interpolation='linear') + tensor(1.8000) + >>> torch.quantile(a, 0.6, interpolation='lower') + tensor(1.) + >>> torch.quantile(a, 0.6, interpolation='higher') + tensor(2.) + >>> torch.quantile(a, 0.6, interpolation='midpoint') + tensor(1.5000) + >>> torch.quantile(a, 0.6, interpolation='nearest') + tensor(2.) + >>> torch.quantile(a, 0.4, interpolation='nearest') + tensor(1.) +""".format(**single_dim_common), +) + +add_docstr( + torch.nanquantile, + r""" +nanquantile(input, q, dim=None, keepdim=False, *, interpolation='linear', out=None) -> Tensor + +This is a variant of :func:`torch.quantile` that "ignores" ``NaN`` values, +computing the quantiles :attr:`q` as if ``NaN`` values in :attr:`input` did +not exist. If all values in a reduced row are ``NaN`` then the quantiles for +that reduction will be ``NaN``. See the documentation for :func:`torch.quantile`. + +Args: + {input} + q (float or Tensor): a scalar or 1D tensor of quantile values in the range [0, 1] + {opt_dim_all_reduce} + {opt_keepdim} + +Keyword arguments: + interpolation (str): interpolation method to use when the desired quantile lies between two data points. + Can be ``linear``, ``lower``, ``higher``, ``midpoint`` and ``nearest``. + Default is ``linear``. + {out} + +Example:: + + >>> t = torch.tensor([float('nan'), 1, 2]) + >>> t.quantile(0.5) + tensor(nan) + >>> t.nanquantile(0.5) + tensor(1.5000) + >>> t = torch.tensor([[float('nan'), float('nan')], [1, 2]]) + >>> t + tensor([[nan, nan], + [1., 2.]]) + >>> t.nanquantile(0.5, dim=0) + tensor([1., 2.]) + >>> t.nanquantile(0.5, dim=1) + tensor([ nan, 1.5000]) +""".format(**single_dim_common), +) + +add_docstr( + torch.min, + r""" +min(input, *, out=None) -> Tensor + +Returns the minimum value of all elements in the :attr:`input` tensor. + +.. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.6750, 1.0857, 1.7197]]) + >>> torch.min(a) + tensor(0.6750) + +.. function:: min(input, dim, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + +Returns a namedtuple ``(values, indices)`` where ``values`` is the minimum +value of each row of the :attr:`input` tensor in the given dimension +:attr:`dim`. And ``indices`` is the index location of each minimum value found +(argmin). + +If :attr:`keepdim` is ``True``, the output tensors are of the same size as +:attr:`input` except in the dimension :attr:`dim` where they are of size 1. +Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in +the output tensors having 1 fewer dimension than :attr:`input`. + +.. note:: If there are multiple minimal values in a reduced row then + the indices of the first minimal value are returned. + +Args: + {input} + {opt_dim_without_none} + {opt_keepdim} + +Keyword args: + out (tuple, optional): the tuple of two output tensors (min, min_indices) + +Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-0.6248, 1.1334, -1.1899, -0.2803], + [-1.4644, -0.2635, -0.3651, 0.6134], + [ 0.2457, 0.0384, 1.0128, 0.7015], + [-0.1153, 2.9849, 2.1458, 0.5788]]) + >>> torch.min(a, 1) + torch.return_types.min(values=tensor([-1.1899, -1.4644, 0.0384, -0.1153]), indices=tensor([2, 0, 1, 0])) + +.. function:: min(input, other, *, out=None) -> Tensor + :noindex: + +See :func:`torch.minimum`. +""".format(**single_dim_common), +) + +add_docstr( + torch.minimum, + r""" +minimum(input, other, *, out=None) -> Tensor + +Computes the element-wise minimum of :attr:`input` and :attr:`other`. + +.. note:: + If one of the elements being compared is a NaN, then that element is returned. + :func:`minimum` is not supported for tensors with complex dtypes. + +Args: + {input} + other (Tensor): the second input tensor + +Keyword args: + {out} + +Example:: + + >>> a = torch.tensor((1, 2, -1)) + >>> b = torch.tensor((3, 0, 4)) + >>> torch.minimum(a, b) + tensor([1, 0, -1]) +""".format(**common_args), +) + +add_docstr( + torch.fmin, + r""" +fmin(input, other, *, out=None) -> Tensor + +Computes the element-wise minimum of :attr:`input` and :attr:`other`. + +This is like :func:`torch.minimum` except it handles NaNs differently: +if exactly one of the two elements being compared is a NaN then the non-NaN element is taken as the minimum. +Only if both elements are NaN is NaN propagated. + +This function is a wrapper around C++'s ``std::fmin`` and is similar to NumPy's ``fmin`` function. + +Supports :ref:`broadcasting to a common shape `, +:ref:`type promotion `, and integer and floating-point inputs. + +Args: + {input} + other (Tensor): the second input tensor + +Keyword args: + {out} + +Example:: + + >>> a = torch.tensor([2.2, float('nan'), 2.1, float('nan')]) + >>> b = torch.tensor([-9.3, 0.1, float('nan'), float('nan')]) + >>> torch.fmin(a, b) + tensor([-9.3000, 0.1000, 2.1000, nan]) +""".format(**common_args), +) + +add_docstr( + torch.amin, + r""" +amin(input, dim, keepdim=False, *, out=None) -> Tensor + +Returns the minimum value of each slice of the :attr:`input` tensor in the given +dimension(s) :attr:`dim`. + +.. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + +{keepdim_details} + +Args: + {input} + {opt_dim_all_reduce} + {opt_keepdim} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.6451, -0.4866, 0.2987, -1.3312], + [-0.5744, 1.2980, 1.8397, -0.2713], + [ 0.9128, 0.9214, -1.7268, -0.2995], + [ 0.9023, 0.4853, 0.9075, -1.6165]]) + >>> torch.amin(a, 1) + tensor([-1.3312, -0.5744, -1.7268, -1.6165]) +""".format(**multi_dim_common), +) + +add_docstr( + torch.aminmax, + r""" +aminmax(input, *, dim=None, keepdim=False, out=None) -> (Tensor min, Tensor max) + +Computes the minimum and maximum values of the :attr:`input` tensor. + +Args: + input (Tensor): + The input tensor + +Keyword Args: + dim (Optional[int]): + The dimension along which to compute the values. If `None`, + computes the values over the entire :attr:`input` tensor. + Default is `None`. + keepdim (bool): + If `True`, the reduced dimensions will be kept in the output + tensor as dimensions with size 1 for broadcasting, otherwise + they will be removed, as if calling (:func:`torch.squeeze`). + Default is `False`. + out (Optional[Tuple[Tensor, Tensor]]): + Optional tensors on which to write the result. Must have the same + shape and dtype as the expected output. + Default is `None`. + +Returns: + A named tuple `(min, max)` containing the minimum and maximum values. + +Raises: + RuntimeError + If any of the dimensions to compute the values over has size 0. + +.. note:: + NaN values are propagated to the output if at least one value is NaN. + +.. seealso:: + :func:`torch.amin` computes just the minimum value + :func:`torch.amax` computes just the maximum value + +Example:: + + >>> torch.aminmax(torch.tensor([1, -3, 5])) + torch.return_types.aminmax( + min=tensor(-3), + max=tensor(5)) + + >>> # aminmax propagates NaNs + >>> torch.aminmax(torch.tensor([1, -3, 5, torch.nan])) + torch.return_types.aminmax( + min=tensor(nan), + max=tensor(nan)) + + >>> t = torch.arange(10).view(2, 5) + >>> t + tensor([[0, 1, 2, 3, 4], + [5, 6, 7, 8, 9]]) + >>> t.aminmax(dim=0, keepdim=True) + torch.return_types.aminmax( + min=tensor([[0, 1, 2, 3, 4]]), + max=tensor([[5, 6, 7, 8, 9]])) +""", +) + +add_docstr( + torch.argmin, + r""" +argmin(input, dim=None, keepdim=False) -> LongTensor + +Returns the indices of the minimum value(s) of the flattened tensor or along a dimension + +This is the second value returned by :meth:`torch.min`. See its +documentation for the exact semantics of this method. + +.. note:: If there are multiple minimal values then the indices of the first minimal value are returned. + +Args: + {input} + {opt_dim} If ``None``, the argmin of the flattened input is returned. + {opt_keepdim} + +Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.1139, 0.2254, -0.1381, 0.3687], + [ 1.0100, -1.1975, -0.0102, -0.4732], + [-0.9240, 0.1207, -0.7506, -1.0213], + [ 1.7809, -1.2960, 0.9384, 0.1438]]) + >>> torch.argmin(a) + tensor(13) + >>> torch.argmin(a, dim=1) + tensor([ 2, 1, 3, 1]) + >>> torch.argmin(a, dim=1, keepdim=True) + tensor([[2], + [1], + [3], + [1]]) +""".format(**single_dim_common), +) + +add_docstr( + torch.mm, + r""" +mm(input, mat2, out_dtype=None, *, out=None) -> Tensor + +Performs a matrix multiplication of the matrices :attr:`input` and :attr:`mat2`. + +If :attr:`input` is a :math:`(n \times m)` tensor, :attr:`mat2` is a +:math:`(m \times p)` tensor, :attr:`out` will be a :math:`(n \times p)` tensor. + +.. note:: This function does not :ref:`broadcast `. + For broadcasting matrix products, see :func:`torch.matmul`. + +Supports strided and sparse 2-D tensors as inputs, autograd with +respect to strided inputs. + +This operation has support for arguments with :ref:`sparse layouts`. +If :attr:`out` is provided its layout will be used. Otherwise, the result +layout will be deduced from that of :attr:`input`. + +{sparse_beta_warning} + +{tf32_note} + +{rocm_fp16_note} + +Args: + input (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + out_dtype (dtype, optional): the dtype of the output tensor, + Supported only on CUDA and for torch.float32 given + torch.float16/torch.bfloat16 input dtypes + +Keyword args: + {out} + +Example:: + + >>> mat1 = torch.randn(2, 3) + >>> mat2 = torch.randn(3, 3) + >>> torch.mm(mat1, mat2) + tensor([[ 0.4851, 0.5037, -0.3633], + [-0.0760, -3.6705, 2.4784]]) +""".format(**common_args, **tf32_notes, **rocm_fp16_notes, **sparse_support_notes), +) + +add_docstr( + torch.hspmm, + r""" +hspmm(mat1, mat2, *, out=None) -> Tensor + +Performs a matrix multiplication of a :ref:`sparse COO matrix +` :attr:`mat1` and a strided matrix :attr:`mat2`. The +result is a (1 + 1)-dimensional :ref:`hybrid COO matrix +`. + +Args: + mat1 (Tensor): the first sparse matrix to be matrix multiplied + mat2 (Tensor): the second strided matrix to be matrix multiplied + +Keyword args: + {out} +""".format(**common_args), +) + +add_docstr( + torch.matmul, + r""" +matmul(input, other, *, out=None) -> Tensor + +Matrix product of two tensors. + +The behavior depends on the dimensionality of the tensors as follows: + +- If both tensors are 1-dimensional, the dot product (scalar) is returned. +- If both arguments are 2-dimensional, the matrix-matrix product is returned. +- If the first argument is 1-dimensional and the second argument is 2-dimensional, + a 1 is prepended to its dimension for the purpose of the matrix multiply. + After the matrix multiply, the prepended dimension is removed. +- If the first argument is 2-dimensional and the second argument is 1-dimensional, + the matrix-vector product is returned. +- If both arguments are at least 1-dimensional and at least one argument is + N-dimensional (where N > 2), then a batched matrix multiply is returned. If the first + argument is 1-dimensional, a 1 is prepended to its dimension for the purpose of the + batched matrix multiply and removed after. If the second argument is 1-dimensional, a + 1 is appended to its dimension for the purpose of the batched matrix multiply and removed after. + + The first N-2 dimensions of each argument, the batch dimensions, are + :ref:`broadcast ` (and thus must be broadcastable). + The last 2, the matrix dimensions, are handled as in the matrix-matrix product. + + For example, if :attr:`input` is a + :math:`(j \times 1 \times n \times m)` tensor and :attr:`other` is a :math:`(k \times m \times p)` + tensor, the batch dimensions are :math:`(j \times 1)` and :math:`(k)`, + and the matrix dimensions are :math:`(n \times m)` and :math:`(m \times p)`. + :attr:`out` will be a :math:`(j \times k \times n \times p)` tensor. + +This operation has support for arguments with :ref:`sparse layouts`. In particular the +matrix-matrix (both arguments 2-dimensional) supports sparse arguments with the same restrictions +as :func:`torch.mm` + +{sparse_beta_warning} + +{tf32_note} + +{rocm_fp16_note} + +.. note:: + + The 1-dimensional dot product version of this function does not support an :attr:`out` parameter. + +Arguments: + input (Tensor): the first tensor to be multiplied + other (Tensor): the second tensor to be multiplied + +Keyword args: + {out} + +Example:: + + >>> # vector x vector + >>> tensor1 = torch.randn(3) + >>> tensor2 = torch.randn(3) + >>> torch.matmul(tensor1, tensor2).size() + torch.Size([]) + >>> # matrix x vector + >>> tensor1 = torch.randn(3, 4) + >>> tensor2 = torch.randn(4) + >>> torch.matmul(tensor1, tensor2).size() + torch.Size([3]) + >>> # batched matrix x broadcasted vector + >>> tensor1 = torch.randn(10, 3, 4) + >>> tensor2 = torch.randn(4) + >>> torch.matmul(tensor1, tensor2).size() + torch.Size([10, 3]) + >>> # batched matrix x batched matrix + >>> tensor1 = torch.randn(10, 3, 4) + >>> tensor2 = torch.randn(10, 4, 5) + >>> torch.matmul(tensor1, tensor2).size() + torch.Size([10, 3, 5]) + >>> # batched matrix x broadcasted matrix + >>> tensor1 = torch.randn(10, 3, 4) + >>> tensor2 = torch.randn(4, 5) + >>> torch.matmul(tensor1, tensor2).size() + torch.Size([10, 3, 5]) + +""".format(**common_args, **tf32_notes, **rocm_fp16_notes, **sparse_support_notes), +) + +add_docstr( + torch.mode, + r""" +mode(input, dim=-1, keepdim=False, *, out=None) -> (Tensor, LongTensor) + +Returns a namedtuple ``(values, indices)`` where ``values`` is the mode +value of each row of the :attr:`input` tensor in the given dimension +:attr:`dim`, i.e. a value which appears most often +in that row, and ``indices`` is the index location of each mode value found. + +By default, :attr:`dim` is the last dimension of the :attr:`input` tensor. + +If :attr:`keepdim` is ``True``, the output tensors are of the same size as +:attr:`input` except in the dimension :attr:`dim` where they are of size 1. +Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting +in the output tensors having 1 fewer dimension than :attr:`input`. + +Args: + {input} + {opt_dim} + {opt_keepdim} + +Keyword args: + out (tuple, optional): the result tuple of two output tensors (values, indices) + +Example:: + + >>> b = torch.tensor([[0, 0, 0, 2, 0, 0, 2], + ... [0, 3, 0, 0, 2, 0, 1], + ... [2, 2, 2, 0, 0, 0, 3], + ... [2, 2, 3, 0, 1, 1, 0], + ... [1, 1, 0, 0, 2, 0, 2]]) + >>> torch.mode(b, 0) + torch.return_types.mode( + values=tensor([0, 2, 0, 0, 0, 0, 2]), + indices=tensor([1, 3, 4, 4, 2, 4, 4])) +""".format(**single_dim_common), +) + +add_docstr( + torch.mul, + r""" +mul(input, other, *, out=None) -> Tensor + +Multiplies :attr:`input` by :attr:`other`. + + +.. math:: + \text{out}_i = \text{input}_i \times \text{other}_i +""" + + r""" + +Supports :ref:`broadcasting to a common shape `, +:ref:`type promotion `, and integer, float, and complex inputs. + +Args: + {input} + other (Tensor or Number): the tensor or number to multiply input by. + +Keyword args: + {out} + +Examples:: + + >>> a = torch.randn(3) + >>> a + tensor([ 0.2015, -0.4255, 2.6087]) + >>> torch.mul(a, 100) + tensor([ 20.1494, -42.5491, 260.8663]) + + >>> b = torch.randn(4, 1) + >>> b + tensor([[ 1.1207], + [-0.3137], + [ 0.0700], + [ 0.8378]]) + >>> c = torch.randn(1, 4) + >>> c + tensor([[ 0.5146, 0.1216, -0.5244, 2.2382]]) + >>> torch.mul(b, c) + tensor([[ 0.5767, 0.1363, -0.5877, 2.5083], + [-0.1614, -0.0382, 0.1645, -0.7021], + [ 0.0360, 0.0085, -0.0367, 0.1567], + [ 0.4312, 0.1019, -0.4394, 1.8753]]) +""".format(**common_args), +) + +add_docstr( + torch.multiply, + r""" +multiply(input, other, *, out=None) + +Alias for :func:`torch.mul`. +""", +) + +add_docstr( + torch.multinomial, + r""" +multinomial(input, num_samples, replacement=False, *, generator=None, out=None) -> LongTensor + +Returns a tensor where each row contains :attr:`num_samples` indices sampled +from the multinomial (a stricter definition would be multivariate, +refer to :class:`torch.distributions.multinomial.Multinomial` for more details) +probability distribution located in the corresponding row +of tensor :attr:`input`. + +.. note:: + The rows of :attr:`input` do not need to sum to one (in which case we use + the values as weights), but must be non-negative, finite and have + a non-zero sum. + +Indices are ordered from left to right according to when each was sampled +(first samples are placed in first column). + +If :attr:`input` is a vector, :attr:`out` is a vector of size :attr:`num_samples`. + +If :attr:`input` is a matrix with `m` rows, :attr:`out` is an matrix of shape +:math:`(m \times \text{{num\_samples}})`. + +If replacement is ``True``, samples are drawn with replacement. + +If not, they are drawn without replacement, which means that when a +sample index is drawn for a row, it cannot be drawn again for that row. + +.. note:: + When drawn without replacement, :attr:`num_samples` must be lower than + number of non-zero elements in :attr:`input` (or the min number of non-zero + elements in each row of :attr:`input` if it is a matrix). + +Args: + input (Tensor): the input tensor containing probabilities + num_samples (int): number of samples to draw + replacement (bool, optional): whether to draw with replacement or not + +Keyword args: + {generator} + {out} + +Example:: + + >>> weights = torch.tensor([0, 10, 3, 0], dtype=torch.float) # create a tensor of weights + >>> torch.multinomial(weights, 2) + tensor([1, 2]) + >>> torch.multinomial(weights, 5) # ERROR! + RuntimeError: cannot sample n_sample > prob_dist.size(-1) samples without replacement + >>> torch.multinomial(weights, 4, replacement=True) + tensor([ 2, 1, 1, 1]) +""".format(**common_args), +) + +add_docstr( + torch.mv, + r""" +mv(input, vec, *, out=None) -> Tensor + +Performs a matrix-vector product of the matrix :attr:`input` and the vector +:attr:`vec`. + +If :attr:`input` is a :math:`(n \times m)` tensor, :attr:`vec` is a 1-D tensor of +size :math:`m`, :attr:`out` will be 1-D of size :math:`n`. + +.. note:: This function does not :ref:`broadcast `. + +Args: + input (Tensor): matrix to be multiplied + vec (Tensor): vector to be multiplied + +Keyword args: + {out} + +Example:: + + >>> mat = torch.randn(2, 3) + >>> vec = torch.randn(3) + >>> torch.mv(mat, vec) + tensor([ 1.0404, -0.6361]) +""".format(**common_args), +) + +add_docstr( + torch.mvlgamma, + r""" +mvlgamma(input, p, *, out=None) -> Tensor + +Alias for :func:`torch.special.multigammaln`. +""", +) + +add_docstr( + torch.movedim, + r""" +movedim(input, source, destination) -> Tensor + +Moves the dimension(s) of :attr:`input` at the position(s) in :attr:`source` +to the position(s) in :attr:`destination`. + +Other dimensions of :attr:`input` that are not explicitly moved remain in +their original order and appear at the positions not specified in :attr:`destination`. + +Args: + {input} + source (int or tuple of ints): Original positions of the dims to move. These must be unique. + destination (int or tuple of ints): Destination positions for each of the original dims. These must also be unique. + +Examples:: + + >>> t = torch.randn(3,2,1) + >>> t + tensor([[[-0.3362], + [-0.8437]], + + [[-0.9627], + [ 0.1727]], + + [[ 0.5173], + [-0.1398]]]) + >>> torch.movedim(t, 1, 0).shape + torch.Size([2, 3, 1]) + >>> torch.movedim(t, 1, 0) + tensor([[[-0.3362], + [-0.9627], + [ 0.5173]], + + [[-0.8437], + [ 0.1727], + [-0.1398]]]) + >>> torch.movedim(t, (1, 2), (0, 1)).shape + torch.Size([2, 1, 3]) + >>> torch.movedim(t, (1, 2), (0, 1)) + tensor([[[-0.3362, -0.9627, 0.5173]], + + [[-0.8437, 0.1727, -0.1398]]]) +""".format(**common_args), +) + +add_docstr( + torch.moveaxis, + r""" +moveaxis(input, source, destination) -> Tensor + +Alias for :func:`torch.movedim`. + +This function is equivalent to NumPy's moveaxis function. + +Examples:: + + >>> t = torch.randn(3,2,1) + >>> t + tensor([[[-0.3362], + [-0.8437]], + + [[-0.9627], + [ 0.1727]], + + [[ 0.5173], + [-0.1398]]]) + >>> torch.moveaxis(t, 1, 0).shape + torch.Size([2, 3, 1]) + >>> torch.moveaxis(t, 1, 0) + tensor([[[-0.3362], + [-0.9627], + [ 0.5173]], + + [[-0.8437], + [ 0.1727], + [-0.1398]]]) + >>> torch.moveaxis(t, (1, 2), (0, 1)).shape + torch.Size([2, 1, 3]) + >>> torch.moveaxis(t, (1, 2), (0, 1)) + tensor([[[-0.3362, -0.9627, 0.5173]], + + [[-0.8437, 0.1727, -0.1398]]]) +""".format(**common_args), +) + +add_docstr( + torch.swapdims, + r""" +swapdims(input, dim0, dim1) -> Tensor + +Alias for :func:`torch.transpose`. + +This function is equivalent to NumPy's swapaxes function. + +Examples:: + + >>> x = torch.tensor([[[0,1],[2,3]],[[4,5],[6,7]]]) + >>> x + tensor([[[0, 1], + [2, 3]], + + [[4, 5], + [6, 7]]]) + >>> torch.swapdims(x, 0, 1) + tensor([[[0, 1], + [4, 5]], + + [[2, 3], + [6, 7]]]) + >>> torch.swapdims(x, 0, 2) + tensor([[[0, 4], + [2, 6]], + + [[1, 5], + [3, 7]]]) +""".format(**common_args), +) + +add_docstr( + torch.swapaxes, + r""" +swapaxes(input, axis0, axis1) -> Tensor + +Alias for :func:`torch.transpose`. + +This function is equivalent to NumPy's swapaxes function. + +Examples:: + + >>> x = torch.tensor([[[0,1],[2,3]],[[4,5],[6,7]]]) + >>> x + tensor([[[0, 1], + [2, 3]], + + [[4, 5], + [6, 7]]]) + >>> torch.swapaxes(x, 0, 1) + tensor([[[0, 1], + [4, 5]], + + [[2, 3], + [6, 7]]]) + >>> torch.swapaxes(x, 0, 2) + tensor([[[0, 4], + [2, 6]], + + [[1, 5], + [3, 7]]]) +""".format(**common_args), +) + +add_docstr( + torch.narrow, + r""" +narrow(input, dim, start, length) -> Tensor + +Returns a new tensor that is a narrowed version of :attr:`input` tensor. The +dimension :attr:`dim` is input from :attr:`start` to ``start + length``. The +returned tensor and :attr:`input` tensor share the same underlying storage. + +Args: + input (Tensor): the tensor to narrow + dim (int): the dimension along which to narrow + start (int or Tensor): index of the element to start the narrowed dimension + from. Can be negative, which means indexing from the end of `dim`. If + `Tensor`, it must be an 0-dim integral `Tensor` (bools not allowed) + length (int): length of the narrowed dimension, must be weakly positive + +Example:: + + >>> x = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + >>> torch.narrow(x, 0, 0, 2) + tensor([[ 1, 2, 3], + [ 4, 5, 6]]) + >>> torch.narrow(x, 1, 1, 2) + tensor([[ 2, 3], + [ 5, 6], + [ 8, 9]]) + >>> torch.narrow(x, -1, torch.tensor(-1), 1) + tensor([[3], + [6], + [9]]) +""", +) + +add_docstr( + torch.narrow_copy, + r""" +narrow_copy(input, dim, start, length, *, out=None) -> Tensor + +Same as :meth:`Tensor.narrow` except this returns a copy rather +than shared storage. This is primarily for sparse tensors, which +do not have a shared-storage narrow method. + +Args: + input (Tensor): the tensor to narrow + dim (int): the dimension along which to narrow + start (int): index of the element to start the narrowed dimension from. Can + be negative, which means indexing from the end of `dim` + length (int): length of the narrowed dimension, must be weakly positive + +Keyword args: + {out} + +Example:: + + >>> x = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + >>> torch.narrow_copy(x, 0, 0, 2) + tensor([[ 1, 2, 3], + [ 4, 5, 6]]) + >>> torch.narrow_copy(x, 1, 1, 2) + tensor([[ 2, 3], + [ 5, 6], + [ 8, 9]]) + >>> s = torch.arange(16).reshape(2, 2, 2, 2).to_sparse(2) + >>> torch.narrow_copy(s, 0, 0, 1) + tensor(indices=tensor([[0, 0], + [0, 1]]), + values=tensor([[[0, 1], + [2, 3]], + + [[4, 5], + [6, 7]]]), + size=(1, 2, 2, 2), nnz=2, layout=torch.sparse_coo) + +.. seealso:: + + :func:`torch.narrow` for a non copy variant + +""".format(**common_args), +) + +add_docstr( + torch.nan_to_num, + r""" +nan_to_num(input, nan=0.0, posinf=None, neginf=None, *, out=None) -> Tensor + +Replaces :literal:`NaN`, positive infinity, and negative infinity values in :attr:`input` +with the values specified by :attr:`nan`, :attr:`posinf`, and :attr:`neginf`, respectively. +By default, :literal:`NaN`\ s are replaced with zero, positive infinity is replaced with the +greatest finite value representable by :attr:`input`'s dtype, and negative infinity +is replaced with the least finite value representable by :attr:`input`'s dtype. + +Args: + {input} + nan (Number, optional): the value to replace :literal:`NaN`\s with. Default is zero. + posinf (Number, optional): if a Number, the value to replace positive infinity values with. + If None, positive infinity values are replaced with the greatest finite value representable by :attr:`input`'s dtype. + Default is None. + neginf (Number, optional): if a Number, the value to replace negative infinity values with. + If None, negative infinity values are replaced with the lowest finite value representable by :attr:`input`'s dtype. + Default is None. + +Keyword args: + {out} + +Example:: + + >>> x = torch.tensor([float('nan'), float('inf'), -float('inf'), 3.14]) + >>> torch.nan_to_num(x) + tensor([ 0.0000e+00, 3.4028e+38, -3.4028e+38, 3.1400e+00]) + >>> torch.nan_to_num(x, nan=2.0) + tensor([ 2.0000e+00, 3.4028e+38, -3.4028e+38, 3.1400e+00]) + >>> torch.nan_to_num(x, nan=2.0, posinf=1.0) + tensor([ 2.0000e+00, 1.0000e+00, -3.4028e+38, 3.1400e+00]) + +""".format(**common_args), +) + +add_docstr( + torch.ne, + r""" +ne(input, other, *, out=None) -> Tensor + +Computes :math:`\text{input} \neq \text{other}` element-wise. +""" + + r""" + +The second argument can be a number or a tensor whose shape is +:ref:`broadcastable ` with the first argument. + +Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + +Keyword args: + {out} + +Returns: + A boolean tensor that is True where :attr:`input` is not equal to :attr:`other` and False elsewhere + +Example:: + + >>> torch.ne(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[False, True], [True, False]]) +""".format(**common_args), +) + +add_docstr( + torch.not_equal, + r""" +not_equal(input, other, *, out=None) -> Tensor + +Alias for :func:`torch.ne`. +""", +) + +add_docstr( + torch.neg, + r""" +neg(input, *, out=None) -> Tensor + +Returns a new tensor with the negative of the elements of :attr:`input`. + +.. math:: + \text{out} = -1 \times \text{input} +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(5) + >>> a + tensor([ 0.0090, -0.2262, -0.0682, -0.2866, 0.3940]) + >>> torch.neg(a) + tensor([-0.0090, 0.2262, 0.0682, 0.2866, -0.3940]) +""".format(**common_args), +) + +add_docstr( + torch.negative, + r""" +negative(input, *, out=None) -> Tensor + +Alias for :func:`torch.neg` +""", +) + +add_docstr( + torch.nextafter, + r""" +nextafter(input, other, *, out=None) -> Tensor + +Return the next floating-point value after :attr:`input` towards :attr:`other`, elementwise. + +The shapes of ``input`` and ``other`` must be +:ref:`broadcastable `. + +Args: + input (Tensor): the first input tensor + other (Tensor): the second input tensor + +Keyword args: + {out} + +Example:: + + >>> eps = torch.finfo(torch.float32).eps + >>> torch.nextafter(torch.tensor([1.0, 2.0]), torch.tensor([2.0, 1.0])) == torch.tensor([eps + 1, 2 - eps]) + tensor([True, True]) + +""".format(**common_args), +) + +add_docstr( + torch.nonzero, + r""" +nonzero(input, *, out=None, as_tuple=False) -> LongTensor or tuple of LongTensors + +.. note:: + :func:`torch.nonzero(..., as_tuple=False) ` (default) returns a + 2-D tensor where each row is the index for a nonzero value. + + :func:`torch.nonzero(..., as_tuple=True) ` returns a tuple of 1-D + index tensors, allowing for advanced indexing, so ``x[x.nonzero(as_tuple=True)]`` + gives all nonzero values of tensor ``x``. Of the returned tuple, each index tensor + contains nonzero indices for a certain dimension. + + See below for more details on the two behaviors. + + When :attr:`input` is on CUDA, :func:`torch.nonzero() ` causes + host-device synchronization. + +**When** :attr:`as_tuple` **is** ``False`` **(default)**: + +Returns a tensor containing the indices of all non-zero elements of +:attr:`input`. Each row in the result contains the indices of a non-zero +element in :attr:`input`. The result is sorted lexicographically, with +the last index changing the fastest (C-style). + +If :attr:`input` has :math:`n` dimensions, then the resulting indices tensor +:attr:`out` is of size :math:`(z \times n)`, where :math:`z` is the total number of +non-zero elements in the :attr:`input` tensor. + +**When** :attr:`as_tuple` **is** ``True``: + +Returns a tuple of 1-D tensors, one for each dimension in :attr:`input`, +each containing the indices (in that dimension) of all non-zero elements of +:attr:`input` . + +If :attr:`input` has :math:`n` dimensions, then the resulting tuple contains :math:`n` +tensors of size :math:`z`, where :math:`z` is the total number of +non-zero elements in the :attr:`input` tensor. + +As a special case, when :attr:`input` has zero dimensions and a nonzero scalar +value, it is treated as a one-dimensional tensor with one element. + +Args: + {input} + +Keyword args: + out (LongTensor, optional): the output tensor containing indices + +Returns: + LongTensor or tuple of LongTensor: If :attr:`as_tuple` is ``False``, the output + tensor containing indices. If :attr:`as_tuple` is ``True``, one 1-D tensor for + each dimension, containing the indices of each nonzero element along that + dimension. + +Example:: + + >>> torch.nonzero(torch.tensor([1, 1, 1, 0, 1])) + tensor([[ 0], + [ 1], + [ 2], + [ 4]]) + >>> torch.nonzero(torch.tensor([[0.6, 0.0, 0.0, 0.0], + ... [0.0, 0.4, 0.0, 0.0], + ... [0.0, 0.0, 1.2, 0.0], + ... [0.0, 0.0, 0.0,-0.4]])) + tensor([[ 0, 0], + [ 1, 1], + [ 2, 2], + [ 3, 3]]) + >>> torch.nonzero(torch.tensor([1, 1, 1, 0, 1]), as_tuple=True) + (tensor([0, 1, 2, 4]),) + >>> torch.nonzero(torch.tensor([[0.6, 0.0, 0.0, 0.0], + ... [0.0, 0.4, 0.0, 0.0], + ... [0.0, 0.0, 1.2, 0.0], + ... [0.0, 0.0, 0.0,-0.4]]), as_tuple=True) + (tensor([0, 1, 2, 3]), tensor([0, 1, 2, 3])) + >>> torch.nonzero(torch.tensor(5), as_tuple=True) + (tensor([0]),) +""".format(**common_args), +) + +add_docstr( + torch.normal, + r""" +normal(mean, std, *, generator=None, out=None) -> Tensor + +Returns a tensor of random numbers drawn from separate normal distributions +whose mean and standard deviation are given. + +The :attr:`mean` is a tensor with the mean of +each output element's normal distribution + +The :attr:`std` is a tensor with the standard deviation of +each output element's normal distribution + +The shapes of :attr:`mean` and :attr:`std` don't need to match, but the +total number of elements in each tensor need to be the same. + +.. note:: When the shapes do not match, the shape of :attr:`mean` + is used as the shape for the returned output tensor + +.. note:: When :attr:`std` is a CUDA tensor, this function synchronizes + its device with the CPU. + +Args: + mean (Tensor): the tensor of per-element means + std (Tensor): the tensor of per-element standard deviations + +Keyword args: + {generator} + {out} + +Example:: + + >>> torch.normal(mean=torch.arange(1., 11.), std=torch.arange(1, 0, -0.1)) + tensor([ 1.0425, 3.5672, 2.7969, 4.2925, 4.7229, 6.2134, + 8.0505, 8.1408, 9.0563, 10.0566]) + +.. function:: normal(mean=0.0, std, *, out=None) -> Tensor + :noindex: + +Similar to the function above, but the means are shared among all drawn +elements. + +Args: + mean (float, optional): the mean for all distributions + std (Tensor): the tensor of per-element standard deviations + +Keyword args: + {out} + +Example:: + + >>> torch.normal(mean=0.5, std=torch.arange(1., 6.)) + tensor([-1.2793, -1.0732, -2.0687, 5.1177, -1.2303]) + +.. function:: normal(mean, std=1.0, *, out=None) -> Tensor + :noindex: + +Similar to the function above, but the standard deviations are shared among +all drawn elements. + +Args: + mean (Tensor): the tensor of per-element means + std (float, optional): the standard deviation for all distributions + +Keyword args: + out (Tensor, optional): the output tensor + +Example:: + + >>> torch.normal(mean=torch.arange(1., 6.)) + tensor([ 1.1552, 2.6148, 2.6535, 5.8318, 4.2361]) + +.. function:: normal(mean, std, size, *, out=None) -> Tensor + :noindex: + +Similar to the function above, but the means and standard deviations are shared +among all drawn elements. The resulting tensor has size given by :attr:`size`. + +Args: + mean (float): the mean for all distributions + std (float): the standard deviation for all distributions + size (int...): a sequence of integers defining the shape of the output tensor. + +Keyword args: + {out} + +Example:: + + >>> torch.normal(2, 3, size=(1, 4)) + tensor([[-1.3987, -1.9544, 3.6048, 0.7909]]) +""".format(**common_args), +) + +add_docstr( + torch.numel, + r""" +numel(input: Tensor) -> int + +Returns the total number of elements in the :attr:`input` tensor. + +Args: + {input} + +Example:: + + >>> a = torch.randn(1, 2, 3, 4, 5) + >>> torch.numel(a) + 120 + >>> a = torch.zeros(4,4) + >>> torch.numel(a) + 16 + +""".format(**common_args), +) + +add_docstr( + torch.ones, + r""" +ones(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + +Returns a tensor filled with the scalar value `1`, with the shape defined +by the variable argument :attr:`size`. + +Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + +Keyword arguments: + {out} + {dtype} + {layout} + {device} + {requires_grad} + +Example:: + + >>> torch.ones(2, 3) + tensor([[ 1., 1., 1.], + [ 1., 1., 1.]]) + + >>> torch.ones(5) + tensor([ 1., 1., 1., 1., 1.]) + +""".format(**factory_common_args), +) + +add_docstr( + torch.ones_like, + r""" +ones_like(input, *, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + +Returns a tensor filled with the scalar value `1`, with the same size as +:attr:`input`. ``torch.ones_like(input)`` is equivalent to +``torch.ones(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``. + +.. warning:: + As of 0.4, this function does not support an :attr:`out` keyword. As an alternative, + the old ``torch.ones_like(input, out=output)`` is equivalent to + ``torch.ones(input.size(), out=output)``. + +Args: + {input} + +Keyword arguments: + {dtype} + {layout} + {device} + {requires_grad} + {memory_format} + +Example:: + + >>> input = torch.empty(2, 3) + >>> torch.ones_like(input) + tensor([[ 1., 1., 1.], + [ 1., 1., 1.]]) +""".format(**factory_like_common_args), +) + +add_docstr( + torch.orgqr, + r""" +orgqr(input, tau) -> Tensor + +Alias for :func:`torch.linalg.householder_product`. +""", +) + +add_docstr( + torch.ormqr, + r""" +ormqr(input, tau, other, left=True, transpose=False, *, out=None) -> Tensor + +Computes the matrix-matrix multiplication of a product of Householder matrices with a general matrix. + +Multiplies a :math:`m \times n` matrix `C` (given by :attr:`other`) with a matrix `Q`, +where `Q` is represented using Householder reflectors `(input, tau)`. +See `Representation of Orthogonal or Unitary Matrices`_ for further details. + +If :attr:`left` is `True` then `op(Q)` times `C` is computed, otherwise the result is `C` times `op(Q)`. +When :attr:`left` is `True`, the implicit matrix `Q` has size :math:`m \times m`. +It has size :math:`n \times n` otherwise. +If :attr:`transpose` is `True` then `op` is the conjugate transpose operation, otherwise it's a no-op. + +Supports inputs of float, double, cfloat and cdouble dtypes. +Also supports batched inputs, and, if the input is batched, the output is batched with the same dimensions. + +.. seealso:: + :func:`torch.geqrf` can be used to form the Householder representation `(input, tau)` of matrix `Q` + from the QR decomposition. + +.. note:: + This function supports backward but it is only fast when ``(input, tau)`` do not require gradients + and/or ``tau.size(-1)`` is very small. + `` + +Args: + input (Tensor): tensor of shape `(*, mn, k)` where `*` is zero or more batch dimensions + and `mn` equals to `m` or `n` depending on the :attr:`left`. + tau (Tensor): tensor of shape `(*, min(mn, k))` where `*` is zero or more batch dimensions. + other (Tensor): tensor of shape `(*, m, n)` where `*` is zero or more batch dimensions. + left (bool): controls the order of multiplication. + transpose (bool): controls whether the matrix `Q` is conjugate transposed or not. + +Keyword args: + out (Tensor, optional): the output Tensor. Ignored if `None`. Default: `None`. + +.. _Representation of Orthogonal or Unitary Matrices: + https://www.netlib.org/lapack/lug/node128.html +""", +) + +add_docstr( + torch.permute, + r""" +permute(input, dims) -> Tensor + +Returns a view of the original tensor :attr:`input` with its dimensions permuted. + +Args: + {input} + dims (tuple of int): The desired ordering of dimensions + +Example: + >>> x = torch.randn(2, 3, 5) + >>> x.size() + torch.Size([2, 3, 5]) + >>> torch.permute(x, (2, 0, 1)).size() + torch.Size([5, 2, 3]) +""".format(**common_args), +) + +add_docstr( + torch.poisson, + r""" +poisson(input, generator=None) -> Tensor + +Returns a tensor of the same size as :attr:`input` with each element +sampled from a Poisson distribution with rate parameter given by the corresponding +element in :attr:`input` i.e., + +.. math:: + \text{{out}}_i \sim \text{{Poisson}}(\text{{input}}_i) + +:attr:`input` must be non-negative. + +Args: + input (Tensor): the input tensor containing the rates of the Poisson distribution + +Keyword args: + {generator} + +Example:: + + >>> rates = torch.rand(4, 4) * 5 # rate parameter between 0 and 5 + >>> torch.poisson(rates) + tensor([[9., 1., 3., 5.], + [8., 6., 6., 0.], + [0., 4., 5., 3.], + [2., 1., 4., 2.]]) +""".format(**common_args), +) + +add_docstr( + torch.polygamma, + r""" +polygamma(n, input, *, out=None) -> Tensor + +Alias for :func:`torch.special.polygamma`. +""", +) + +add_docstr( + torch.positive, + r""" +positive(input) -> Tensor + +Returns :attr:`input`. +Throws a runtime error if :attr:`input` is a bool tensor. +""" + + r""" +Args: + {input} + +Example:: + + >>> t = torch.randn(5) + >>> t + tensor([ 0.0090, -0.2262, -0.0682, -0.2866, 0.3940]) + >>> torch.positive(t) + tensor([ 0.0090, -0.2262, -0.0682, -0.2866, 0.3940]) +""".format(**common_args), +) + +add_docstr( + torch.pow, + r""" +pow(input, exponent, *, out=None) -> Tensor + +Takes the power of each element in :attr:`input` with :attr:`exponent` and +returns a tensor with the result. + +:attr:`exponent` can be either a single ``float`` number or a `Tensor` +with the same number of elements as :attr:`input`. + +When :attr:`exponent` is a scalar value, the operation applied is: + +.. math:: + \text{out}_i = x_i ^ \text{exponent} + +When :attr:`exponent` is a tensor, the operation applied is: + +.. math:: + \text{out}_i = x_i ^ {\text{exponent}_i} +""" + + r""" +When :attr:`exponent` is a tensor, the shapes of :attr:`input` +and :attr:`exponent` must be :ref:`broadcastable `. + +Args: + {input} + exponent (float or tensor): the exponent value + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.4331, 1.2475, 0.6834, -0.2791]) + >>> torch.pow(a, 2) + tensor([ 0.1875, 1.5561, 0.4670, 0.0779]) + >>> exp = torch.arange(1., 5.) + + >>> a = torch.arange(1., 5.) + >>> a + tensor([ 1., 2., 3., 4.]) + >>> exp + tensor([ 1., 2., 3., 4.]) + >>> torch.pow(a, exp) + tensor([ 1., 4., 27., 256.]) + +.. function:: pow(self, exponent, *, out=None) -> Tensor + :noindex: + +:attr:`self` is a scalar ``float`` value, and :attr:`exponent` is a tensor. +The returned tensor :attr:`out` is of the same shape as :attr:`exponent` + +The operation applied is: + +.. math:: + \text{{out}}_i = \text{{self}} ^ {{\text{{exponent}}_i}} + +Args: + self (float): the scalar base value for the power operation + exponent (Tensor): the exponent tensor + +Keyword args: + {out} + +Example:: + + >>> exp = torch.arange(1., 5.) + >>> base = 2 + >>> torch.pow(base, exp) + tensor([ 2., 4., 8., 16.]) +""".format(**common_args), +) + +add_docstr( + torch.float_power, + r""" +float_power(input, exponent, *, out=None) -> Tensor + +Raises :attr:`input` to the power of :attr:`exponent`, elementwise, in double precision. +If neither input is complex returns a ``torch.float64`` tensor, +and if one or more inputs is complex returns a ``torch.complex128`` tensor. + +.. note:: + This function always computes in double precision, unlike :func:`torch.pow`, + which implements more typical :ref:`type promotion `. + This is useful when the computation needs to be performed in a wider or more precise dtype, + or the results of the computation may contain fractional values not representable in the input dtypes, + like when an integer base is raised to a negative integer exponent. + +Args: + input (Tensor or Number): the base value(s) + exponent (Tensor or Number): the exponent value(s) + +Keyword args: + {out} + +Example:: + + >>> a = torch.randint(10, (4,)) + >>> a + tensor([6, 4, 7, 1]) + >>> torch.float_power(a, 2) + tensor([36., 16., 49., 1.], dtype=torch.float64) + + >>> a = torch.arange(1, 5) + >>> a + tensor([ 1, 2, 3, 4]) + >>> exp = torch.tensor([2, -3, 4, -5]) + >>> exp + tensor([ 2, -3, 4, -5]) + >>> torch.float_power(a, exp) + tensor([1.0000e+00, 1.2500e-01, 8.1000e+01, 9.7656e-04], dtype=torch.float64) +""".format(**common_args), +) + +add_docstr( + torch.prod, + r""" +prod(input: Tensor, *, dtype: Optional[_dtype]) -> Tensor + +Returns the product of all elements in the :attr:`input` tensor. + +Args: + {input} + +Keyword args: + {dtype} + +Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[-0.8020, 0.5428, -1.5854]]) + >>> torch.prod(a) + tensor(0.6902) + +.. function:: prod(input, dim, keepdim=False, *, dtype=None) -> Tensor + :noindex: + +Returns the product of each row of the :attr:`input` tensor in the given +dimension :attr:`dim`. + +{keepdim_details} + +Args: + {input} + {opt_dim_all_reduce} + {opt_keepdim} + +Keyword args: + {dtype} + +Example:: + + >>> a = torch.randn(4, 2) + >>> a + tensor([[ 0.5261, -0.3837], + [ 1.1857, -0.2498], + [-1.1646, 0.0705], + [ 1.1131, -1.0629]]) + >>> torch.prod(a, 1) + tensor([-0.2018, -0.2962, -0.0821, -1.1831]) +""".format(**single_dim_common), +) + +add_docstr( + torch.promote_types, + r""" +promote_types(type1, type2) -> dtype + +Returns the :class:`torch.dtype` with the smallest size and scalar kind that is +not smaller nor of lower kind than either `type1` or `type2`. See type promotion +:ref:`documentation ` for more information on the type +promotion logic. + +Args: + type1 (:class:`torch.dtype`) + type2 (:class:`torch.dtype`) + +Example:: + + >>> torch.promote_types(torch.int32, torch.float32) + torch.float32 + >>> torch.promote_types(torch.uint8, torch.long) + torch.long +""", +) + +add_docstr( + torch.qr, + r""" +qr(input: Tensor, some: bool = True, *, out: Union[Tensor, Tuple[Tensor, ...], List[Tensor], None]) -> (Tensor, Tensor) + +Computes the QR decomposition of a matrix or a batch of matrices :attr:`input`, +and returns a namedtuple (Q, R) of tensors such that :math:`\text{input} = Q R` +with :math:`Q` being an orthogonal matrix or batch of orthogonal matrices and +:math:`R` being an upper triangular matrix or batch of upper triangular matrices. + +If :attr:`some` is ``True``, then this function returns the thin (reduced) QR factorization. +Otherwise, if :attr:`some` is ``False``, this function returns the complete QR factorization. + +.. warning:: + + :func:`torch.qr` is deprecated in favor of :func:`torch.linalg.qr` + and will be removed in a future PyTorch release. The boolean parameter :attr:`some` has been + replaced with a string parameter :attr:`mode`. + + ``Q, R = torch.qr(A)`` should be replaced with + + .. code:: python + + Q, R = torch.linalg.qr(A) + + ``Q, R = torch.qr(A, some=False)`` should be replaced with + + .. code:: python + + Q, R = torch.linalg.qr(A, mode="complete") + +.. warning:: + If you plan to backpropagate through QR, note that the current backward implementation + is only well-defined when the first :math:`\min(input.size(-1), input.size(-2))` + columns of :attr:`input` are linearly independent. + This behavior will probably change once QR supports pivoting. + +.. note:: This function uses LAPACK for CPU inputs and MAGMA for CUDA inputs, + and may produce different (valid) decompositions on different device types + or different platforms. + +Args: + input (Tensor): the input tensor of size :math:`(*, m, n)` where `*` is zero or more + batch dimensions consisting of matrices of dimension :math:`m \times n`. + some (bool, optional): Set to ``True`` for reduced QR decomposition and ``False`` for + complete QR decomposition. If `k = min(m, n)` then: + + * ``some=True`` : returns `(Q, R)` with dimensions (m, k), (k, n) (default) + + * ``'some=False'``: returns `(Q, R)` with dimensions (m, m), (m, n) + +Keyword args: + out (tuple, optional): tuple of `Q` and `R` tensors. + The dimensions of `Q` and `R` are detailed in the description of :attr:`some` above. + +Example:: + + >>> a = torch.tensor([[12., -51, 4], [6, 167, -68], [-4, 24, -41]]) + >>> q, r = torch.qr(a) + >>> q + tensor([[-0.8571, 0.3943, 0.3314], + [-0.4286, -0.9029, -0.0343], + [ 0.2857, -0.1714, 0.9429]]) + >>> r + tensor([[ -14.0000, -21.0000, 14.0000], + [ 0.0000, -175.0000, 70.0000], + [ 0.0000, 0.0000, -35.0000]]) + >>> torch.mm(q, r).round() + tensor([[ 12., -51., 4.], + [ 6., 167., -68.], + [ -4., 24., -41.]]) + >>> torch.mm(q.t(), q).round() + tensor([[ 1., 0., 0.], + [ 0., 1., -0.], + [ 0., -0., 1.]]) + >>> a = torch.randn(3, 4, 5) + >>> q, r = torch.qr(a, some=False) + >>> torch.allclose(torch.matmul(q, r), a) + True + >>> torch.allclose(torch.matmul(q.mT, q), torch.eye(5)) + True +""", +) + +add_docstr( + torch.rad2deg, + r""" +rad2deg(input: Tensor, *, out: Optional[Tensor]) -> Tensor + +Returns a new tensor with each of the elements of :attr:`input` +converted from angles in radians to degrees. + +Args: + {input} + +Keyword arguments: + {out} + +Example:: + + >>> a = torch.tensor([[3.142, -3.142], [6.283, -6.283], [1.570, -1.570]]) + >>> torch.rad2deg(a) + tensor([[ 180.0233, -180.0233], + [ 359.9894, -359.9894], + [ 89.9544, -89.9544]]) + +""".format(**common_args), +) + +add_docstr( + torch.deg2rad, + r""" +deg2rad(input, *, out=None) -> Tensor + +Returns a new tensor with each of the elements of :attr:`input` +converted from angles in degrees to radians. + +Args: + {input} + +Keyword arguments: + {out} + +Example:: + + >>> a = torch.tensor([[180.0, -180.0], [360.0, -360.0], [90.0, -90.0]]) + >>> torch.deg2rad(a) + tensor([[ 3.1416, -3.1416], + [ 6.2832, -6.2832], + [ 1.5708, -1.5708]]) + +""".format(**common_args), +) + +add_docstr( + torch.heaviside, + r""" +heaviside(input, values, *, out=None) -> Tensor + +Computes the Heaviside step function for each element in :attr:`input`. +The Heaviside step function is defined as: + +.. math:: + \text{{heaviside}}(input, values) = \begin{cases} + 0, & \text{if input < 0}\\ + values, & \text{if input == 0}\\ + 1, & \text{if input > 0} + \end{cases} +""" + + r""" + +Args: + {input} + values (Tensor): The values to use where :attr:`input` is zero. + +Keyword arguments: + {out} + +Example:: + + >>> input = torch.tensor([-1.5, 0, 2.0]) + >>> values = torch.tensor([0.5]) + >>> torch.heaviside(input, values) + tensor([0.0000, 0.5000, 1.0000]) + >>> values = torch.tensor([1.2, -2.0, 3.5]) + >>> torch.heaviside(input, values) + tensor([0., -2., 1.]) + +""".format(**common_args), +) + +add_docstr( + torch.rand, + """ +rand(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, \ +requires_grad=False, pin_memory=False) -> Tensor +""" + + r""" +Returns a tensor filled with random numbers from a uniform distribution +on the interval :math:`[0, 1)` + +The shape of the tensor is defined by the variable argument :attr:`size`. + +Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + +Keyword args: + {generator} + {out} + {dtype} + {layout} + {device} + {requires_grad} + {pin_memory} + +Example:: + + >>> torch.rand(4) + tensor([ 0.5204, 0.2503, 0.3525, 0.5673]) + >>> torch.rand(2, 3) + tensor([[ 0.8237, 0.5781, 0.6879], + [ 0.3816, 0.7249, 0.0998]]) +""".format(**factory_common_args), +) + +add_docstr( + torch.rand_like, + """ +rand_like(input, *, generator=None, dtype=None, layout=None, device=None, \ +requires_grad=False, memory_format=torch.preserve_format) -> Tensor +""" + + r""" +Returns a tensor with the same size as :attr:`input` that is filled with +random numbers from a uniform distribution on the interval :math:`[0, 1)`. +``torch.rand_like(input)`` is equivalent to +``torch.rand(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``. + +Args: + {input} + +Keyword args: + {generator} + {dtype} + {layout} + {device} + {requires_grad} + {memory_format} + +""".format(**factory_like_common_args), +) + +add_docstr( + torch.randint, + """ +randint(low=0, high, size, \\*, generator=None, out=None, \ +dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + +Returns a tensor filled with random integers generated uniformly +between :attr:`low` (inclusive) and :attr:`high` (exclusive). + +The shape of the tensor is defined by the variable argument :attr:`size`. + +.. note:: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + +Args: + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + size (tuple): a tuple defining the shape of the output tensor. + +Keyword args: + {generator} + {out} + dtype (torch.dtype, optional): the desired data type of returned tensor. Default: if ``None``, + this function returns a tensor with dtype ``torch.int64``. + {layout} + {device} + {requires_grad} + +Example:: + + >>> torch.randint(3, 5, (3,)) + tensor([4, 3, 4]) + + + >>> torch.randint(10, (2, 2)) + tensor([[0, 2], + [5, 5]]) + + + >>> torch.randint(3, 10, (2, 2)) + tensor([[4, 5], + [6, 7]]) + + +""".format(**factory_common_args), +) + +add_docstr( + torch.randint_like, + """ +randint_like(input, low=0, high, \\*, generator=None, dtype=None, layout=torch.strided, \ +device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor +""" + + r""" +Returns a tensor with the same shape as Tensor :attr:`input` filled with +random integers generated uniformly between :attr:`low` (inclusive) and +:attr:`high` (exclusive). + +.. note: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + +Args: + {input} + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + +Keyword args: + {generator} + {dtype} + {layout} + {device} + {requires_grad} + {memory_format} + +""".format(**factory_like_common_args), +) + +add_docstr( + torch.randn, + """ +randn(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, \ +pin_memory=False) -> Tensor +""" + + r""" + +Returns a tensor filled with random numbers from a normal distribution +with mean `0` and variance `1` (also called the standard normal +distribution). + +.. math:: + \text{{out}}_{{i}} \sim \mathcal{{N}}(0, 1) + +For complex dtypes, the tensor is i.i.d. sampled from a `complex normal distribution`_ with zero mean and +unit variance as + +.. math:: + \text{{out}}_{{i}} \sim \mathcal{{CN}}(0, 1) + +This is equivalent to separately sampling the real :math:`(\operatorname{{Re}})` and imaginary +:math:`(\operatorname{{Im}})` part of :math:`\text{{out}}_i` as + +.. math:: + \operatorname{{Re}}(\text{{out}}_{{i}}) \sim \mathcal{{N}}(0, \frac{{1}}{{2}}),\quad + \operatorname{{Im}}(\text{{out}}_{{i}}) \sim \mathcal{{N}}(0, \frac{{1}}{{2}}) + +The shape of the tensor is defined by the variable argument :attr:`size`. + + +Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + +Keyword args: + {generator} + {out} + {dtype} + {layout} + {device} + {requires_grad} + {pin_memory} + +Example:: + + >>> torch.randn(4) + tensor([-2.1436, 0.9966, 2.3426, -0.6366]) + >>> torch.randn(2, 3) + tensor([[ 1.5954, 2.8929, -1.0923], + [ 1.1719, -0.4709, -0.1996]]) + +.. _complex normal distribution: https://en.wikipedia.org/wiki/Complex_normal_distribution +""".format(**factory_common_args), +) + +add_docstr( + torch.randn_like, + """ +randn_like(input, *, generator=None, dtype=None, layout=None, device=None, \ +requires_grad=False, memory_format=torch.preserve_format) -> Tensor +""" + + r""" +Returns a tensor with the same size as :attr:`input` that is filled with +random numbers from a normal distribution with mean 0 and variance 1. Please refer to :func:`torch.randn` for the +sampling process of complex dtypes. ``torch.randn_like(input)`` is equivalent to +``torch.randn(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``. + +Args: + {input} + +Keyword args: + {generator} + {dtype} + {layout} + {device} + {requires_grad} + {memory_format} + +""".format(**factory_like_common_args), +) + +add_docstr( + torch.randperm, + """ +randperm(n, *, generator=None, out=None, dtype=torch.int64,layout=torch.strided, \ +device=None, requires_grad=False, pin_memory=False) -> Tensor +""" + + r""" +Returns a random permutation of integers from ``0`` to ``n - 1``. + +Args: + n (int): the upper bound (exclusive) + +Keyword args: + {generator} + {out} + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: ``torch.int64``. + {layout} + {device} + {requires_grad} + {pin_memory} + +Example:: + + >>> torch.randperm(4) + tensor([2, 1, 0, 3]) +""".format(**factory_common_args), +) + +add_docstr( + torch.tensor, + r""" +tensor(data, *, dtype=None, device=None, requires_grad=False, pin_memory=False) -> Tensor + +Constructs a tensor with no autograd history (also known as a "leaf tensor", see :doc:`/notes/autograd`) by copying :attr:`data`. + +.. warning:: + + When working with tensors prefer using :func:`torch.Tensor.clone`, + :func:`torch.Tensor.detach`, and :func:`torch.Tensor.requires_grad_` for + readability. Letting `t` be a tensor, ``torch.tensor(t)`` is equivalent to + ``t.detach().clone()``, and ``torch.tensor(t, requires_grad=True)`` + is equivalent to ``t.detach().clone().requires_grad_(True)``. + +.. seealso:: + + :func:`torch.as_tensor` preserves autograd history and avoids copies where possible. + :func:`torch.from_numpy` creates a tensor that shares storage with a NumPy array. + +Args: + {data} + +Keyword args: + {dtype} + device (:class:`torch.device`, optional): the device of the constructed tensor. If None and data is a tensor + then the device of data is used. If None and data is not a tensor then + the result tensor is constructed on the current device. + {requires_grad} + {pin_memory} + + +Example:: + + >>> torch.tensor([[0.1, 1.2], [2.2, 3.1], [4.9, 5.2]]) + tensor([[ 0.1000, 1.2000], + [ 2.2000, 3.1000], + [ 4.9000, 5.2000]]) + + >>> torch.tensor([0, 1]) # Type inference on data + tensor([ 0, 1]) + + >>> torch.tensor([[0.11111, 0.222222, 0.3333333]], + ... dtype=torch.float64, + ... device=torch.device('cuda:0')) # creates a double tensor on a CUDA device + tensor([[ 0.1111, 0.2222, 0.3333]], dtype=torch.float64, device='cuda:0') + + >>> torch.tensor(3.14159) # Create a zero-dimensional (scalar) tensor + tensor(3.1416) + + >>> torch.tensor([]) # Create an empty tensor (of size (0,)) + tensor([]) +""".format(**factory_data_common_args), +) + +add_docstr( + torch.range, + r""" +range(start=0, end, step=1, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + +Returns a 1-D tensor of size :math:`\left\lfloor \frac{\text{end} - \text{start}}{\text{step}} \right\rfloor + 1` +with values from :attr:`start` to :attr:`end` with step :attr:`step`. Step is +the gap between two values in the tensor. + +.. math:: + \text{out}_{i+1} = \text{out}_i + \text{step}. +""" + + r""" +.. warning:: + This function is deprecated and will be removed in a future release because its behavior is inconsistent with + Python's range builtin. Instead, use :func:`torch.arange`, which produces values in [start, end). + +Args: + start (float, optional): the starting value for the set of points. Default: ``0``. + end (float): the ending value for the set of points + step (float, optional): the gap between each pair of adjacent points. Default: ``1``. + +Keyword args: + {out} + {dtype} If `dtype` is not given, infer the data type from the other input + arguments. If any of `start`, `end`, or `step` are floating-point, the + `dtype` is inferred to be the default dtype, see + :meth:`~torch.get_default_dtype`. Otherwise, the `dtype` is inferred to + be `torch.int64`. + {layout} + {device} + {requires_grad} + +Example:: + + >>> torch.range(1, 4) + tensor([ 1., 2., 3., 4.]) + >>> torch.range(1, 4, 0.5) + tensor([ 1.0000, 1.5000, 2.0000, 2.5000, 3.0000, 3.5000, 4.0000]) +""".format(**factory_common_args), +) + +add_docstr( + torch.arange, + r""" +arange(start=0, end, step=1, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + +Returns a 1-D tensor of size :math:`\left\lceil \frac{\text{end} - \text{start}}{\text{step}} \right\rceil` +with values from the interval ``[start, end)`` taken with common difference +:attr:`step` beginning from `start`. + +Note: When using floating-point dtypes (especially reduced precision types like ``bfloat16``), +the results may be affected by floating-point rounding behavior. Some values in the sequence +might not be exactly representable in certain floating-point formats, which can lead to +repeated values or unexpected rounding. For precise sequences, it is recommended to use +integer dtypes instead of floating-point dtypes. + +Note that non-integer :attr:`step` is subject to floating point rounding errors when +comparing against :attr:`end`; to avoid inconsistency, we advise subtracting a small epsilon from :attr:`end` +in such cases. + +.. math:: + \text{out}_{{i+1}} = \text{out}_{i} + \text{step} +""" + + r""" +Args: + start (Number, optional): the starting value for the set of points. Default: ``0``. + end (Number): the ending value for the set of points + step (Number, optional): the gap between each pair of adjacent points. Default: ``1``. + +Keyword args: + {out} + {dtype} If `dtype` is not given, infer the data type from the other input + arguments. If any of `start`, `end`, or `stop` are floating-point, the + `dtype` is inferred to be the default dtype, see + :meth:`~torch.get_default_dtype`. Otherwise, the `dtype` is inferred to + be `torch.int64`. + {layout} + {device} + {requires_grad} + +Example:: + + >>> torch.arange(5) + tensor([ 0, 1, 2, 3, 4]) + >>> torch.arange(1, 4) + tensor([ 1, 2, 3]) + >>> torch.arange(1, 2.5, 0.5) + tensor([ 1.0000, 1.5000, 2.0000]) +""".format(**factory_common_args), +) + +add_docstr( + torch.ravel, + r""" +ravel(input) -> Tensor + +Return a contiguous flattened tensor. A copy is made only if needed. + +Args: + {input} + +Example:: + + >>> t = torch.tensor([[[1, 2], + ... [3, 4]], + ... [[5, 6], + ... [7, 8]]]) + >>> torch.ravel(t) + tensor([1, 2, 3, 4, 5, 6, 7, 8]) +""".format(**common_args), +) + +add_docstr( + torch.remainder, + r""" +remainder(input, other, *, out=None) -> Tensor + +Computes +`Python's modulus operation `_ +entrywise. The result has the same sign as the divisor :attr:`other` and its absolute value +is less than that of :attr:`other`. + +It may also be defined in terms of :func:`torch.div` as + +.. code:: python + + torch.remainder(a, b) == a - a.div(b, rounding_mode="floor") * b + +Supports :ref:`broadcasting to a common shape `, +:ref:`type promotion `, and integer and float inputs. + +.. note:: + Complex inputs are not supported. In some cases, it is not mathematically + possible to satisfy the definition of a modulo operation with complex numbers. + See :func:`torch.fmod` for how division by zero is handled. + +.. seealso:: + + :func:`torch.fmod` which implements C++'s `std::fmod `_. + This one is defined in terms of division rounding towards zero. + +Args: + input (Tensor or Scalar): the dividend + other (Tensor or Scalar): the divisor + +Keyword args: + {out} + +Example:: + + >>> torch.remainder(torch.tensor([-3., -2, -1, 1, 2, 3]), 2) + tensor([ 1., 0., 1., 1., 0., 1.]) + >>> torch.remainder(torch.tensor([1, 2, 3, 4, 5]), -1.5) + tensor([ -0.5000, -1.0000, 0.0000, -0.5000, -1.0000 ]) +""".format(**common_args), +) + +add_docstr( + torch.renorm, + r""" +renorm(input, p, dim, maxnorm, *, out=None) -> Tensor + +Returns a tensor where each sub-tensor of :attr:`input` along dimension +:attr:`dim` is normalized such that the `p`-norm of the sub-tensor is lower +than the value :attr:`maxnorm` + +.. note:: If the norm of a row is lower than `maxnorm`, the row is unchanged + +Args: + {input} + p (float): the power for the norm computation + dim (int): the dimension to slice over to get the sub-tensors + maxnorm (float): the maximum norm to keep each sub-tensor under + +Keyword args: + {out} + +Example:: + + >>> x = torch.ones(3, 3) + >>> x[1].fill_(2) + tensor([ 2., 2., 2.]) + >>> x[2].fill_(3) + tensor([ 3., 3., 3.]) + >>> x + tensor([[ 1., 1., 1.], + [ 2., 2., 2.], + [ 3., 3., 3.]]) + >>> torch.renorm(x, 1, 0, 5) + tensor([[ 1.0000, 1.0000, 1.0000], + [ 1.6667, 1.6667, 1.6667], + [ 1.6667, 1.6667, 1.6667]]) +""".format(**common_args), +) + +add_docstr( + torch.reshape, + r""" +reshape(input, shape) -> Tensor + +Returns a tensor with the same data and number of elements as :attr:`input`, +but with the specified shape. When possible, the returned tensor will be a view +of :attr:`input`. Otherwise, it will be a copy. Contiguous inputs and inputs +with compatible strides can be reshaped without copying, but you should not +depend on the copying vs. viewing behavior. + +See :meth:`torch.Tensor.view` on when it is possible to return a view. + +A single dimension may be -1, in which case it's inferred from the remaining +dimensions and the number of elements in :attr:`input`. + +Args: + input (Tensor): the tensor to be reshaped + shape (tuple of int): the new shape + +Example:: + + >>> a = torch.arange(4.) + >>> torch.reshape(a, (2, 2)) + tensor([[ 0., 1.], + [ 2., 3.]]) + >>> b = torch.tensor([[0, 1], [2, 3]]) + >>> torch.reshape(b, (-1,)) + tensor([ 0, 1, 2, 3]) +""", +) + + +add_docstr( + torch.result_type, + r""" +result_type(tensor1, tensor2) -> dtype + +Returns the :class:`torch.dtype` that would result from performing an arithmetic +operation on the provided input tensors. See type promotion :ref:`documentation ` +for more information on the type promotion logic. + +Args: + tensor1 (Tensor or Number): an input tensor or number + tensor2 (Tensor or Number): an input tensor or number + +Example:: + + >>> torch.result_type(torch.tensor([1, 2], dtype=torch.int), 1.0) + torch.float32 + >>> torch.result_type(torch.tensor([1, 2], dtype=torch.uint8), torch.tensor(1)) + torch.uint8 +""", +) + +add_docstr( + torch.row_stack, + r""" +row_stack(tensors, *, out=None) -> Tensor + +Alias of :func:`torch.vstack`. +""", +) + +add_docstr( + torch.round, + r""" +round(input, *, decimals=0, out=None) -> Tensor + +Rounds elements of :attr:`input` to the nearest integer. + +For integer inputs, follows the array-api convention of returning a +copy of the input tensor. +The return type of output is same as that of input's dtype. + +.. note:: + This function implements the "round half to even" to + break ties when a number is equidistant from two + integers (e.g. `round(2.5)` is 2). + + When the :attr:\`decimals\` argument is specified the + algorithm used is similar to NumPy's `around`. This + algorithm is fast but inexact and it can easily + overflow for low precision dtypes. + Eg. `round(tensor([10000], dtype=torch.float16), decimals=3)` is `inf`. + +.. seealso:: + :func:`torch.ceil`, which rounds up. + :func:`torch.floor`, which rounds down. + :func:`torch.trunc`, which rounds towards zero. + +Args: + {input} + decimals (int): Number of decimal places to round to (default: 0). + If decimals is negative, it specifies the number of positions + to the left of the decimal point. + +Keyword args: + {out} + +Example:: + + >>> torch.round(torch.tensor((4.7, -2.3, 9.1, -7.7))) + tensor([ 5., -2., 9., -8.]) + + >>> # Values equidistant from two integers are rounded towards the + >>> # the nearest even value (zero is treated as even) + >>> torch.round(torch.tensor([-0.5, 0.5, 1.5, 2.5])) + tensor([-0., 0., 2., 2.]) + + >>> # A positive decimals argument rounds to the to that decimal place + >>> torch.round(torch.tensor([0.1234567]), decimals=3) + tensor([0.1230]) + + >>> # A negative decimals argument rounds to the left of the decimal + >>> torch.round(torch.tensor([1200.1234567]), decimals=-3) + tensor([1000.]) +""".format(**common_args), +) + +add_docstr( + torch.rsqrt, + r""" +rsqrt(input, *, out=None) -> Tensor + +Returns a new tensor with the reciprocal of the square-root of each of +the elements of :attr:`input`. + +.. math:: + \text{out}_{i} = \frac{1}{\sqrt{\text{input}_{i}}} +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-0.0370, 0.2970, 1.5420, -0.9105]) + >>> torch.rsqrt(a) + tensor([ nan, 1.8351, 0.8053, nan]) +""".format(**common_args), +) + +add_docstr( + torch.scatter, + r""" +scatter(input, dim, index, src) -> Tensor + +Out-of-place version of :meth:`torch.Tensor.scatter_` +""", +) + +add_docstr( + torch.scatter_add, + r""" +scatter_add(input, dim, index, src) -> Tensor + +Out-of-place version of :meth:`torch.Tensor.scatter_add_` +""", +) + +add_docstr( + torch.scatter_reduce, + r""" +scatter_reduce(input, dim, index, src, reduce, *, include_self=True) -> Tensor + +Out-of-place version of :meth:`torch.Tensor.scatter_reduce_` +""", +) + +add_docstr( + torch.segment_reduce, + r""" +segment_reduce(data: Tensor, reduce: str, *, lengths: Tensor | None = None, indices: Tensor | None = None, offsets: Tensor | None = None, axis: _int = 0, unsafe: _bool = False, initial: Number | _complex | None = None) -> Tensor # noqa: B950 + +Perform a segment reduction operation on the input tensor along the specified axis. + +Args: + data (Tensor): The input tensor on which the segment reduction operation will be performed. + reduce (str): The type of reduction operation. Supported values are ``sum``, ``mean``, ``max``, ``min``, ``prod``. + +Keyword args: + lengths (Tensor, optional): Length of each segment. Default: ``None``. + offsets (Tensor, optional): Offset of each segment. Default: ``None``. + axis (int, optional): The axis perform reduction. Default: ``0``. + unsafe (bool, optional): Skip validation If `True`. Default: ``False``. + initial (Number, optional): The initial value for the reduction operation. Default: ``None``. + +Example:: + + >>> data = torch.tensor([[1, 2, 3, 4],[5, 6, 7, 8],[9, 10, 11, 12]], dtype=torch.float32, device='cuda') + >>> lengths = torch.tensor([2, 1], device='cuda') + >>> torch.segment_reduce(data, 'max', lengths=lengths) + tensor([[ 5., 6., 7., 8.], + [ 9., 10., 11., 12.]], device='cuda:0') +""", +) + +add_docstr( + torch.select, + r""" +select(input, dim, index) -> Tensor + +Slices the :attr:`input` tensor along the selected dimension at the given index. +This function returns a view of the original tensor with the given dimension removed. + +.. note:: If :attr:`input` is a sparse tensor and returning a view of + the tensor is not possible, a RuntimeError exception is + raised. In this is the case, consider using + :func:`torch.select_copy` function. + +Args: + {input} + dim (int): the dimension to slice + index (int): the index to select with + +.. note:: + + :meth:`select` is equivalent to slicing. For example, + ``tensor.select(0, index)`` is equivalent to ``tensor[index]`` and + ``tensor.select(2, index)`` is equivalent to ``tensor[:,:,index]``. +""".format(**common_args), +) + +add_docstr( + torch.select_scatter, + r""" +select_scatter(input, src, dim, index) -> Tensor + +Embeds the values of the :attr:`src` tensor into :attr:`input` at the given index. +This function returns a tensor with fresh storage; it does not create a view. + + +Args: + {input} + src (Tensor): The tensor to embed into :attr:`input` + dim (int): the dimension to insert the slice into. + index (int): the index to select with + +.. note:: + + :attr:`src` must be of the proper size in order to be embedded + into :attr:`input`. Specifically, it should have the same shape as + ``torch.select(input, dim, index)`` + +Example:: + + >>> a = torch.zeros(2, 2) + >>> b = torch.ones(2) + >>> a.select_scatter(b, 0, 0) + tensor([[1., 1.], + [0., 0.]]) +""".format(**common_args), +) + +add_docstr( + torch.slice_scatter, + r""" +slice_scatter(input, src, dim=0, start=None, end=None, step=1) -> Tensor + +Embeds the values of the :attr:`src` tensor into :attr:`input` at the given +dimension. +This function returns a tensor with fresh storage; it does not create a view. + + +Args: + {input} + src (Tensor): The tensor to embed into :attr:`input` + dim (int): the dimension to insert the slice into + start (Optional[int]): the start index of where to insert the slice + end (Optional[int]): the end index of where to insert the slice + step (int): the how many elements to skip in + +Example:: + + >>> a = torch.zeros(8, 8) + >>> b = torch.ones(2, 8) + >>> a.slice_scatter(b, start=6) + tensor([[0., 0., 0., 0., 0., 0., 0., 0.], + [0., 0., 0., 0., 0., 0., 0., 0.], + [0., 0., 0., 0., 0., 0., 0., 0.], + [0., 0., 0., 0., 0., 0., 0., 0.], + [0., 0., 0., 0., 0., 0., 0., 0.], + [0., 0., 0., 0., 0., 0., 0., 0.], + [1., 1., 1., 1., 1., 1., 1., 1.], + [1., 1., 1., 1., 1., 1., 1., 1.]]) + + >>> b = torch.ones(8, 2) + >>> a.slice_scatter(b, dim=1, start=2, end=6, step=2) + tensor([[0., 0., 1., 0., 1., 0., 0., 0.], + [0., 0., 1., 0., 1., 0., 0., 0.], + [0., 0., 1., 0., 1., 0., 0., 0.], + [0., 0., 1., 0., 1., 0., 0., 0.], + [0., 0., 1., 0., 1., 0., 0., 0.], + [0., 0., 1., 0., 1., 0., 0., 0.], + [0., 0., 1., 0., 1., 0., 0., 0.], + [0., 0., 1., 0., 1., 0., 0., 0.]]) +""".format(**common_args), +) + +add_docstr( + torch.set_flush_denormal, + r""" +set_flush_denormal(mode) -> bool + +Disables denormal floating numbers on CPU. + +Returns ``True`` if your system supports flushing denormal numbers and it +successfully configures flush denormal mode. :meth:`~torch.set_flush_denormal` +is supported on x86 architectures supporting SSE3 and AArch64 architecture. + +Args: + mode (bool): Controls whether to enable flush denormal mode or not + +Example:: + + >>> torch.set_flush_denormal(True) + True + >>> torch.tensor([1e-323], dtype=torch.float64) + tensor([ 0.], dtype=torch.float64) + >>> torch.set_flush_denormal(False) + True + >>> torch.tensor([1e-323], dtype=torch.float64) + tensor(9.88131e-324 * + [ 1.0000], dtype=torch.float64) +""", +) + +add_docstr( + torch.set_num_threads, + r""" +set_num_threads(int) + +Sets the number of threads used for intraop parallelism on CPU. + +.. warning:: + To ensure that the correct number of threads is used, set_num_threads + must be called before running eager, JIT or autograd code. +""", +) + +add_docstr( + torch.set_num_interop_threads, + r""" +set_num_interop_threads(int) + +Sets the number of threads used for interop parallelism +(e.g. in JIT interpreter) on CPU. + +.. warning:: + Can only be called once and before any inter-op parallel work + is started (e.g. JIT execution). +""", +) + +add_docstr( + torch.sigmoid, + r""" +sigmoid(input, *, out=None) -> Tensor + +Alias for :func:`torch.special.expit`. +""", +) + +add_docstr( + torch.logit, + r""" +logit(input, eps=None, *, out=None) -> Tensor + +Alias for :func:`torch.special.logit`. +""", +) + +add_docstr( + torch.sign, + r""" +sign(input, *, out=None) -> Tensor + +Returns a new tensor with the signs of the elements of :attr:`input`. + +.. math:: + \text{out}_{i} = \operatorname{sgn}(\text{input}_{i}) +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.tensor([0.7, -1.2, 0., 2.3]) + >>> a + tensor([ 0.7000, -1.2000, 0.0000, 2.3000]) + >>> torch.sign(a) + tensor([ 1., -1., 0., 1.]) +""".format(**common_args), +) + +add_docstr( + torch.signbit, + r""" +signbit(input, *, out=None) -> Tensor + +Tests if each element of :attr:`input` has its sign bit set or not. + +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.tensor([0.7, -1.2, 0., 2.3]) + >>> torch.signbit(a) + tensor([ False, True, False, False]) + >>> a = torch.tensor([-0.0, 0.0]) + >>> torch.signbit(a) + tensor([ True, False]) + +.. note:: + signbit handles signed zeros, so negative zero (-0) returns True. + +""".format(**common_args), +) + +add_docstr( + torch.sgn, + r""" +sgn(input, *, out=None) -> Tensor + +This function is an extension of torch.sign() to complex tensors. +It computes a new tensor whose elements have +the same angles as the corresponding elements of :attr:`input` and +absolute values (i.e. magnitudes) of one for complex tensors and +is equivalent to torch.sign() for non-complex tensors. + +.. math:: + \text{out}_{i} = \begin{cases} + 0 & |\text{{input}}_i| == 0 \\ + \frac{{\text{{input}}_i}}{|{\text{{input}}_i}|} & \text{otherwise} + \end{cases} + +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> t = torch.tensor([3+4j, 7-24j, 0, 1+2j]) + >>> t.sgn() + tensor([0.6000+0.8000j, 0.2800-0.9600j, 0.0000+0.0000j, 0.4472+0.8944j]) +""".format(**common_args), +) + +add_docstr( + torch.sin, + r""" +sin(input, *, out=None) -> Tensor + +Returns a new tensor with the sine of the elements in the :attr:`input` tensor, +where each value in this input tensor is in radians. + +.. math:: + \text{out}_{i} = \sin(\text{input}_{i}) +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-0.5461, 0.1347, -2.7266, -0.2746]) + >>> torch.sin(a) + tensor([-0.5194, 0.1343, -0.4032, -0.2711]) +""".format(**common_args), +) + +add_docstr( + torch.sinc, + r""" +sinc(input, *, out=None) -> Tensor + +Alias for :func:`torch.special.sinc`. +""", +) + +add_docstr( + torch.sinh, + r""" +sinh(input, *, out=None) -> Tensor + +Returns a new tensor with the hyperbolic sine of the elements of +:attr:`input`. + +.. math:: + \text{out}_{i} = \sinh(\text{input}_{i}) +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.5380, -0.8632, -0.1265, 0.9399]) + >>> torch.sinh(a) + tensor([ 0.5644, -0.9744, -0.1268, 1.0845]) + +.. note:: + When :attr:`input` is on the CPU, the implementation of torch.sinh may use + the Sleef library, which rounds very large results to infinity or negative + infinity. See `here `_ for details. +""".format(**common_args), +) + +add_docstr( + torch.sort, + r""" +sort(input, dim=-1, descending=False, *, stable=False, out=None) -> (Tensor, LongTensor) + +Sorts the elements of the :attr:`input` tensor along a given dimension +in ascending order by value. + +If :attr:`dim` is not given, the last dimension of the `input` is chosen. + +If :attr:`descending` is ``True`` then the elements are sorted in descending +order by value. + +If :attr:`stable` is ``True`` then the sorting routine becomes stable, preserving +the order of equivalent elements. + +A namedtuple of (values, indices) is returned, where the `values` are the +sorted values and `indices` are the indices of the elements in the original +`input` tensor. + +Args: + {input} + dim (int, optional): the dimension to sort along + descending (bool, optional): controls the sorting order (ascending or descending) + +Keyword args: + stable (bool, optional): makes the sorting routine stable, which guarantees that the order + of equivalent elements is preserved. + out (tuple, optional): the output tuple of (`Tensor`, `LongTensor`) that can + be optionally given to be used as output buffers + +Example:: + + >>> x = torch.randn(3, 4) + >>> sorted, indices = torch.sort(x) + >>> sorted + tensor([[-0.2162, 0.0608, 0.6719, 2.3332], + [-0.5793, 0.0061, 0.6058, 0.9497], + [-0.5071, 0.3343, 0.9553, 1.0960]]) + >>> indices + tensor([[ 1, 0, 2, 3], + [ 3, 1, 0, 2], + [ 0, 3, 1, 2]]) + + >>> sorted, indices = torch.sort(x, 0) + >>> sorted + tensor([[-0.5071, -0.2162, 0.6719, -0.5793], + [ 0.0608, 0.0061, 0.9497, 0.3343], + [ 0.6058, 0.9553, 1.0960, 2.3332]]) + >>> indices + tensor([[ 2, 0, 0, 1], + [ 0, 1, 1, 2], + [ 1, 2, 2, 0]]) + >>> x = torch.tensor([0, 1] * 9) + >>> x.sort() + torch.return_types.sort( + values=tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1]), + indices=tensor([ 2, 16, 4, 6, 14, 8, 0, 10, 12, 9, 17, 15, 13, 11, 7, 5, 3, 1])) + >>> x.sort(stable=True) + torch.return_types.sort( + values=tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1]), + indices=tensor([ 0, 2, 4, 6, 8, 10, 12, 14, 16, 1, 3, 5, 7, 9, 11, 13, 15, 17])) +""".format(**common_args), +) + +add_docstr( + torch.argsort, + r""" +argsort(input, dim=-1, descending=False, *, stable=False) -> Tensor + +Returns the indices that sort a tensor along a given dimension in ascending +order by value. + +This is the second value returned by :meth:`torch.sort`. See its documentation +for the exact semantics of this method. + +If :attr:`stable` is ``True`` then the sorting routine becomes stable, preserving +the order of equivalent elements. If ``False``, the relative order of values +which compare equal is not guaranteed. ``True`` is slower. + +Args: + {input} + dim (int, optional): the dimension to sort along + descending (bool, optional): controls the sorting order (ascending or descending) + +Keyword args: + stable (bool, optional): controls the relative order of equivalent elements + +Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.0785, 1.5267, -0.8521, 0.4065], + [ 0.1598, 0.0788, -0.0745, -1.2700], + [ 1.2208, 1.0722, -0.7064, 1.2564], + [ 0.0669, -0.2318, -0.8229, -0.9280]]) + + + >>> torch.argsort(a, dim=1) + tensor([[2, 0, 3, 1], + [3, 2, 1, 0], + [2, 1, 0, 3], + [3, 2, 1, 0]]) +""".format(**common_args), +) + +add_docstr( + torch.msort, + r""" +msort(input: Tensor, *, out: Optional[Tensor]) -> Tensor + +Sorts the elements of the :attr:`input` tensor along its first dimension +in ascending order by value. + +.. note:: `torch.msort(t)` is equivalent to `torch.sort(t, dim=0)[0]`. + See also :func:`torch.sort`. + +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> t = torch.randn(3, 4) + >>> t + tensor([[-0.1321, 0.4370, -1.2631, -1.1289], + [-2.0527, -1.1250, 0.2275, 0.3077], + [-0.0881, -0.1259, -0.5495, 1.0284]]) + >>> torch.msort(t) + tensor([[-2.0527, -1.1250, -1.2631, -1.1289], + [-0.1321, -0.1259, -0.5495, 0.3077], + [-0.0881, 0.4370, 0.2275, 1.0284]]) +""".format(**common_args), +) + +add_docstr( + torch.sparse_compressed_tensor, + r"""sparse_compressed_tensor(compressed_indices, plain_indices, values, size=None, """ + r"""*, dtype=None, layout=None, device=None, pin_memory=False, requires_grad=False, check_invariants=None) -> Tensor + +Constructs a :ref:`sparse tensor in Compressed Sparse format - CSR, +CSC, BSR, or BSC - ` with specified values at +the given :attr:`compressed_indices` and :attr:`plain_indices`. Sparse +matrix multiplication operations in Compressed Sparse format are +typically faster than that for sparse tensors in COO format. Make you +have a look at :ref:`the note on the data type of the indices +`. + +{sparse_factory_device_note} + +Args: + compressed_indices (array_like): (B+1)-dimensional array of size + ``(*batchsize, compressed_dim_size + 1)``. The last element of + each batch is the number of non-zero elements or blocks. This + tensor encodes the index in ``values`` and ``plain_indices`` + depending on where the given compressed dimension (row or + column) starts. Each successive number in the tensor + subtracted by the number before it denotes the number of + elements or blocks in a given compressed dimension. + plain_indices (array_like): Plain dimension (column or row) + coordinates of each element or block in values. (B+1)-dimensional + tensor with the same length as values. + + values (array_list): Initial values for the tensor. Can be a list, + tuple, NumPy ``ndarray``, scalar, and other types. that + represents a (1+K)-dimensional (for CSR and CSC layouts) or + (1+2+K)-dimensional tensor (for BSR and BSC layouts) where + ``K`` is the number of dense dimensions. + size (list, tuple, :class:`torch.Size`, optional): Size of the + sparse tensor: ``(*batchsize, nrows * blocksize[0], ncols * + blocksize[1], *densesize)`` where ``blocksize[0] == + blocksize[1] == 1`` for CSR and CSC formats. If not provided, + the size will be inferred as the minimum size big enough to + hold all non-zero elements or blocks. + +Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of + returned tensor. Default: if None, infers data type from + :attr:`values`. + layout (:class:`torch.layout`, required): the desired layout of + returned tensor: :attr:`torch.sparse_csr`, + :attr:`torch.sparse_csc`, :attr:`torch.sparse_bsr`, or + :attr:`torch.sparse_bsc`. + device (:class:`torch.device`, optional): the desired device of + returned tensor. Default: if None, uses the current device + for the default tensor type (see + :func:`torch.set_default_device`). :attr:`device` will be + the CPU for CPU tensor types and the current CUDA device for + CUDA tensor types. + {pin_memory} + {requires_grad} + {check_invariants} + +Example:: + + >>> compressed_indices = [0, 2, 4] + >>> plain_indices = [0, 1, 0, 1] + >>> values = [1, 2, 3, 4] + >>> torch.sparse_compressed_tensor(torch.tensor(compressed_indices, dtype=torch.int64), + ... torch.tensor(plain_indices, dtype=torch.int64), + ... torch.tensor(values), dtype=torch.double, layout=torch.sparse_csr) + tensor(crow_indices=tensor([0, 2, 4]), + col_indices=tensor([0, 1, 0, 1]), + values=tensor([1., 2., 3., 4.]), size=(2, 2), nnz=4, + dtype=torch.float64, layout=torch.sparse_csr) +""".format(**factory_common_args), +) + +add_docstr( + torch.sparse_csr_tensor, + r"""sparse_csr_tensor(crow_indices, col_indices, values, size=None, """ + r"""*, dtype=None, device=None, pin_memory=False, requires_grad=False, check_invariants=None) -> Tensor + +Constructs a :ref:`sparse tensor in CSR (Compressed Sparse Row) ` with specified +values at the given :attr:`crow_indices` and :attr:`col_indices`. Sparse matrix multiplication operations +in CSR format are typically faster than that for sparse tensors in COO format. Make you have a look +at :ref:`the note on the data type of the indices `. + +{sparse_factory_device_note} + +Args: + crow_indices (array_like): (B+1)-dimensional array of size + ``(*batchsize, nrows + 1)``. The last element of each batch + is the number of non-zeros. This tensor encodes the index in + values and col_indices depending on where the given row + starts. Each successive number in the tensor subtracted by the + number before it denotes the number of elements in a given + row. + col_indices (array_like): Column coordinates of each element in + values. (B+1)-dimensional tensor with the same length + as values. + values (array_list): Initial values for the tensor. Can be a list, + tuple, NumPy ``ndarray``, scalar, and other types that + represents a (1+K)-dimensional tensor where ``K`` is the number + of dense dimensions. + size (list, tuple, :class:`torch.Size`, optional): Size of the + sparse tensor: ``(*batchsize, nrows, ncols, *densesize)``. If + not provided, the size will be inferred as the minimum size + big enough to hold all non-zero elements. + +Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of + returned tensor. Default: if None, infers data type from + :attr:`values`. + device (:class:`torch.device`, optional): the desired device of + returned tensor. Default: if None, uses the current device + for the default tensor type (see + :func:`torch.set_default_device`). :attr:`device` will be + the CPU for CPU tensor types and the current CUDA device for + CUDA tensor types. + {pin_memory} + {requires_grad} + {check_invariants} + +Example:: + + >>> crow_indices = [0, 2, 4] + >>> col_indices = [0, 1, 0, 1] + >>> values = [1, 2, 3, 4] + >>> torch.sparse_csr_tensor(torch.tensor(crow_indices, dtype=torch.int64), + ... torch.tensor(col_indices, dtype=torch.int64), + ... torch.tensor(values), dtype=torch.double) + tensor(crow_indices=tensor([0, 2, 4]), + col_indices=tensor([0, 1, 0, 1]), + values=tensor([1., 2., 3., 4.]), size=(2, 2), nnz=4, + dtype=torch.float64, layout=torch.sparse_csr) +""".format(**factory_common_args), +) + +add_docstr( + torch.sparse_csc_tensor, + r"""sparse_csc_tensor(ccol_indices, row_indices, values, size=None, """ + r"""*, dtype=None, device=None, pin_memory=False, requires_grad=False, check_invariants=None) -> Tensor + +Constructs a :ref:`sparse tensor in CSC (Compressed Sparse Column) +` with specified values at the given +:attr:`ccol_indices` and :attr:`row_indices`. Sparse matrix +multiplication operations in CSC format are typically faster than that +for sparse tensors in COO format. Make you have a look at :ref:`the +note on the data type of the indices `. + +{sparse_factory_device_note} + +Args: + ccol_indices (array_like): (B+1)-dimensional array of size + ``(*batchsize, ncols + 1)``. The last element of each batch + is the number of non-zeros. This tensor encodes the index in + values and row_indices depending on where the given column + starts. Each successive number in the tensor subtracted by the + number before it denotes the number of elements in a given + column. + row_indices (array_like): Row coordinates of each element in + values. (B+1)-dimensional tensor with the same length as + values. + values (array_list): Initial values for the tensor. Can be a list, + tuple, NumPy ``ndarray``, scalar, and other types that + represents a (1+K)-dimensional tensor where ``K`` is the number + of dense dimensions. + size (list, tuple, :class:`torch.Size`, optional): Size of the + sparse tensor: ``(*batchsize, nrows, ncols, *densesize)``. If + not provided, the size will be inferred as the minimum size + big enough to hold all non-zero elements. + +Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of + returned tensor. Default: if None, infers data type from + :attr:`values`. + device (:class:`torch.device`, optional): the desired device of + returned tensor. Default: if None, uses the current device + for the default tensor type (see + :func:`torch.set_default_device`). :attr:`device` will be + the CPU for CPU tensor types and the current CUDA device for + CUDA tensor types. + {pin_memory} + {requires_grad} + {check_invariants} + +Example:: + + >>> ccol_indices = [0, 2, 4] + >>> row_indices = [0, 1, 0, 1] + >>> values = [1, 2, 3, 4] + >>> torch.sparse_csc_tensor(torch.tensor(ccol_indices, dtype=torch.int64), + ... torch.tensor(row_indices, dtype=torch.int64), + ... torch.tensor(values), dtype=torch.double) + tensor(ccol_indices=tensor([0, 2, 4]), + row_indices=tensor([0, 1, 0, 1]), + values=tensor([1., 2., 3., 4.]), size=(2, 2), nnz=4, + dtype=torch.float64, layout=torch.sparse_csc) +""".format(**factory_common_args), +) + +add_docstr( + torch.sparse_bsr_tensor, + r"""sparse_bsr_tensor(crow_indices, col_indices, values, size=None, """ + r"""*, dtype=None, device=None, pin_memory=False, requires_grad=False, check_invariants=None) -> Tensor + +Constructs a :ref:`sparse tensor in BSR (Block Compressed Sparse Row)) +` with specified 2-dimensional blocks at the given +:attr:`crow_indices` and :attr:`col_indices`. Sparse matrix +multiplication operations in BSR format are typically faster than that +for sparse tensors in COO format. Make you have a look at :ref:`the +note on the data type of the indices `. + +{sparse_factory_device_note} + +Args: + crow_indices (array_like): (B+1)-dimensional array of size + ``(*batchsize, nrowblocks + 1)``. The last element of each + batch is the number of non-zeros. This tensor encodes the + block index in values and col_indices depending on where the + given row block starts. Each successive number in the tensor + subtracted by the number before it denotes the number of + blocks in a given row. + col_indices (array_like): Column block coordinates of each block + in values. (B+1)-dimensional tensor with the same length as + values. + values (array_list): Initial values for the tensor. Can be a list, + tuple, NumPy ``ndarray``, scalar, and other types that + represents a (1 + 2 + K)-dimensional tensor where ``K`` is the + number of dense dimensions. + size (list, tuple, :class:`torch.Size`, optional): Size of the + sparse tensor: ``(*batchsize, nrows * blocksize[0], ncols * + blocksize[1], *densesize)`` where ``blocksize == + values.shape[1:3]``. If not provided, the size will be + inferred as the minimum size big enough to hold all non-zero + blocks. + +Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of + returned tensor. Default: if None, infers data type from + :attr:`values`. + device (:class:`torch.device`, optional): the desired device of + returned tensor. Default: if None, uses the current device + for the default tensor type (see + :func:`torch.set_default_device`). :attr:`device` will be + the CPU for CPU tensor types and the current CUDA device for + CUDA tensor types. + {pin_memory} + {requires_grad} + {check_invariants} + +Example:: + + >>> crow_indices = [0, 1, 2] + >>> col_indices = [0, 1] + >>> values = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]] + >>> torch.sparse_bsr_tensor(torch.tensor(crow_indices, dtype=torch.int64), + ... torch.tensor(col_indices, dtype=torch.int64), + ... torch.tensor(values), dtype=torch.double) + tensor(crow_indices=tensor([0, 1, 2]), + col_indices=tensor([0, 1]), + values=tensor([[[1., 2.], + [3., 4.]], + [[5., 6.], + [7., 8.]]]), size=(2, 2), nnz=2, dtype=torch.float64, + layout=torch.sparse_bsr) +""".format(**factory_common_args), +) + +add_docstr( + torch.sparse_bsc_tensor, + r"""sparse_bsc_tensor(ccol_indices, row_indices, values, size=None, """ + r"""*, dtype=None, device=None, pin_memory=False, requires_grad=False, check_invariants=None) -> Tensor + +Constructs a :ref:`sparse tensor in BSC (Block Compressed Sparse +Column)) ` with specified 2-dimensional blocks at the +given :attr:`ccol_indices` and :attr:`row_indices`. Sparse matrix +multiplication operations in BSC format are typically faster than that +for sparse tensors in COO format. Make you have a look at :ref:`the +note on the data type of the indices `. + +{sparse_factory_device_note} + +Args: + ccol_indices (array_like): (B+1)-dimensional array of size + ``(*batchsize, ncolblocks + 1)``. The last element of each + batch is the number of non-zeros. This tensor encodes the + index in values and row_indices depending on where the given + column starts. Each successive number in the tensor subtracted + by the number before it denotes the number of elements in a + given column. + row_indices (array_like): Row block coordinates of each block in + values. (B+1)-dimensional tensor with the same length + as values. + values (array_list): Initial blocks for the tensor. Can be a list, + tuple, NumPy ``ndarray``, and other types that + represents a (1 + 2 + K)-dimensional tensor where ``K`` is the + number of dense dimensions. + size (list, tuple, :class:`torch.Size`, optional): Size of the + sparse tensor: ``(*batchsize, nrows * blocksize[0], ncols * + blocksize[1], *densesize)`` If not provided, the size will be + inferred as the minimum size big enough to hold all non-zero + blocks. + +Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of + returned tensor. Default: if None, infers data type from + :attr:`values`. + device (:class:`torch.device`, optional): the desired device of + returned tensor. Default: if None, uses the current device + for the default tensor type (see + :func:`torch.set_default_device`). :attr:`device` will be + the CPU for CPU tensor types and the current CUDA device for + CUDA tensor types. + {pin_memory} + {requires_grad} + {check_invariants} + +Example:: + + >>> ccol_indices = [0, 1, 2] + >>> row_indices = [0, 1] + >>> values = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]] + >>> torch.sparse_bsc_tensor(torch.tensor(ccol_indices, dtype=torch.int64), + ... torch.tensor(row_indices, dtype=torch.int64), + ... torch.tensor(values), dtype=torch.double) + tensor(ccol_indices=tensor([0, 1, 2]), + row_indices=tensor([0, 1]), + values=tensor([[[1., 2.], + [3., 4.]], + [[5., 6.], + [7., 8.]]]), size=(2, 2), nnz=2, dtype=torch.float64, + layout=torch.sparse_bsc) +""".format(**factory_common_args), +) + +add_docstr( + torch.sparse_coo_tensor, + r"""sparse_coo_tensor(indices, values, size=None, """ + r"""*, dtype=None, device=None, pin_memory=False, requires_grad=False, check_invariants=None, is_coalesced=None) -> Tensor + +Constructs a :ref:`sparse tensor in COO(rdinate) format +` with specified values at the given +:attr:`indices`. + +.. note:: + + This function returns an :ref:`uncoalesced tensor + ` when :attr:`is_coalesced` is + unspecified or ``None``. + +{sparse_factory_device_note} + +Args: + indices (array_like): Initial data for the tensor. Can be a list, tuple, + NumPy ``ndarray``, scalar, and other types. Will be cast to a :class:`torch.LongTensor` + internally. The indices are the coordinates of the non-zero values in the matrix, and thus + should be two-dimensional where the first dimension is the number of tensor dimensions and + the second dimension is the number of non-zero values. + values (array_like): Initial values for the tensor. Can be a list, tuple, + NumPy ``ndarray``, scalar, and other types. + size (list, tuple, or :class:`torch.Size`, optional): Size of the sparse tensor. If not + provided the size will be inferred as the minimum size big enough to hold all non-zero + elements. + +Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if None, infers data type from :attr:`values`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if None, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + {pin_memory} + {requires_grad} + {check_invariants} + is_coalesced (bool, optional): When``True``, the caller is + responsible for providing tensor indices that correspond to a + coalesced tensor. If the :attr:`check_invariants` flag is + False, no error will be raised if the prerequisites are not + met and this will lead to silently incorrect results. To force + coalescion please use :meth:`coalesce` on the resulting + Tensor. + Default: None: except for trivial cases (e.g. nnz < 2) the + resulting Tensor has is_coalesced set to ``False```. + +Example:: + + >>> i = torch.tensor([[0, 1, 1], + ... [2, 0, 2]]) + >>> v = torch.tensor([3, 4, 5], dtype=torch.float32) + >>> torch.sparse_coo_tensor(i, v, [2, 4]) + tensor(indices=tensor([[0, 1, 1], + [2, 0, 2]]), + values=tensor([3., 4., 5.]), + size=(2, 4), nnz=3, layout=torch.sparse_coo) + + >>> torch.sparse_coo_tensor(i, v) # Shape inference + tensor(indices=tensor([[0, 1, 1], + [2, 0, 2]]), + values=tensor([3., 4., 5.]), + size=(2, 3), nnz=3, layout=torch.sparse_coo) + + >>> torch.sparse_coo_tensor(i, v, [2, 4], + ... dtype=torch.float64, + ... device=torch.device('cuda:0')) + tensor(indices=tensor([[0, 1, 1], + [2, 0, 2]]), + values=tensor([3., 4., 5.]), + device='cuda:0', size=(2, 4), nnz=3, dtype=torch.float64, + layout=torch.sparse_coo) + + # Create an empty sparse tensor with the following invariants: + # 1. sparse_dim + dense_dim = len(SparseTensor.shape) + # 2. SparseTensor._indices().shape = (sparse_dim, nnz) + # 3. SparseTensor._values().shape = (nnz, SparseTensor.shape[sparse_dim:]) + # + # For instance, to create an empty sparse tensor with nnz = 0, dense_dim = 0 and + # sparse_dim = 1 (hence indices is a 2D tensor of shape = (1, 0)) + >>> S = torch.sparse_coo_tensor(torch.empty([1, 0]), [], [1]) + tensor(indices=tensor([], size=(1, 0)), + values=tensor([], size=(0,)), + size=(1,), nnz=0, layout=torch.sparse_coo) + + # and to create an empty sparse tensor with nnz = 0, dense_dim = 1 and + # sparse_dim = 1 + >>> S = torch.sparse_coo_tensor(torch.empty([1, 0]), torch.empty([0, 2]), [1, 2]) + tensor(indices=tensor([], size=(1, 0)), + values=tensor([], size=(0, 2)), + size=(1, 2), nnz=0, layout=torch.sparse_coo) + +.. _torch.sparse: https://pytorch.org/docs/stable/sparse.html +""".format(**factory_common_args), +) + +add_docstr( + torch.sqrt, + r""" +sqrt(input, *, out=None) -> Tensor + +Returns a new tensor with the square-root of the elements of :attr:`input`. + +.. math:: + \text{out}_{i} = \sqrt{\text{input}_{i}} +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-2.0755, 1.0226, 0.0831, 0.4806]) + >>> torch.sqrt(a) + tensor([ nan, 1.0112, 0.2883, 0.6933]) +""".format(**common_args), +) + +add_docstr( + torch.square, + r""" +square(input: Tensor, *, out: Optional[Tensor]) -> Tensor + +Returns a new tensor with the square of the elements of :attr:`input`. + +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-2.0755, 1.0226, 0.0831, 0.4806]) + >>> torch.square(a) + tensor([ 4.3077, 1.0457, 0.0069, 0.2310]) +""".format(**common_args), +) + +add_docstr( + torch.squeeze, + r""" +squeeze(input: Tensor, dim: Optional[Union[int, List[int]]]) -> Tensor + +Returns a tensor with all specified dimensions of :attr:`input` of size `1` removed. + +For example, if `input` is of shape: +:math:`(A \times 1 \times B \times C \times 1 \times D)` then the `input.squeeze()` +will be of shape: :math:`(A \times B \times C \times D)`. + +When :attr:`dim` is given, a squeeze operation is done only in the given +dimension(s). If `input` is of shape: :math:`(A \times 1 \times B)`, +``squeeze(input, 0)`` leaves the tensor unchanged, but ``squeeze(input, 1)`` +will squeeze the tensor to the shape :math:`(A \times B)`. + +.. note:: The returned tensor shares the storage with the input tensor, + so changing the contents of one will change the contents of the other. + +.. warning:: If the tensor has a batch dimension of size 1, then `squeeze(input)` + will also remove the batch dimension, which can lead to unexpected + errors. Consider specifying only the dims you wish to be squeezed. + +Args: + {input} + dim (int or tuple of ints, optional): if given, the input will be squeezed + only in the specified dimensions. + + .. versionchanged:: 2.0 + :attr:`dim` now accepts tuples of dimensions. + +Example:: + + >>> x = torch.zeros(2, 1, 2, 1, 2) + >>> x.size() + torch.Size([2, 1, 2, 1, 2]) + >>> y = torch.squeeze(x) + >>> y.size() + torch.Size([2, 2, 2]) + >>> y = torch.squeeze(x, 0) + >>> y.size() + torch.Size([2, 1, 2, 1, 2]) + >>> y = torch.squeeze(x, 1) + >>> y.size() + torch.Size([2, 2, 1, 2]) + >>> y = torch.squeeze(x, (1, 2, 3)) + torch.Size([2, 2, 2]) +""".format(**common_args), +) + +add_docstr( + torch.std, + r""" +std(input, dim=None, *, correction=1, keepdim=False, out=None) -> Tensor + +Calculates the standard deviation over the dimensions specified by :attr:`dim`. +:attr:`dim` can be a single dimension, list of dimensions, or ``None`` to +reduce over all dimensions. + +The standard deviation (:math:`\sigma`) is calculated as + +.. math:: \sigma = \sqrt{\frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2} + +where :math:`x` is the sample set of elements, :math:`\bar{x}` is the +sample mean, :math:`N` is the number of samples and :math:`\delta N` is +the :attr:`correction`. +""" + + r""" + +{keepdim_details} + +Args: + {input} + {opt_dim_all_reduce} + +Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + {opt_keepdim} + {out} + +Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.std(a, dim=1, keepdim=True) + tensor([[1.0311], + [0.7477], + [1.2204], + [0.9087]]) + +.. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + +""".format(**multi_dim_common), +) + +add_docstr( + torch.std_mean, + r""" +std_mean(input, dim=None, *, correction=1, keepdim=False, out=None) -> (Tensor, Tensor) + +Calculates the standard deviation and mean over the dimensions specified by +:attr:`dim`. :attr:`dim` can be a single dimension, list of dimensions, or +``None`` to reduce over all dimensions. + +The standard deviation (:math:`\sigma`) is calculated as + +.. math:: \sigma = \sqrt{\frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2} + +where :math:`x` is the sample set of elements, :math:`\bar{x}` is the +sample mean, :math:`N` is the number of samples and :math:`\delta N` is +the :attr:`correction`. + +""" + + r""" + +{keepdim_details} + +Args: + {input} + {opt_dim_all_reduce} + +Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + {opt_keepdim} + {out} + +Returns: + A tuple (std, mean) containing the standard deviation and mean. + +Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.std_mean(a, dim=0, keepdim=True) + (tensor([[1.2620, 1.0028, 1.0957, 0.6038]]), + tensor([[ 0.0645, 0.4485, 0.8707, -0.0665]])) + +.. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + +""".format(**multi_dim_common), +) + +add_docstr( + torch.sub, + r""" +sub(input, other, *, alpha=1, out=None) -> Tensor + +Subtracts :attr:`other`, scaled by :attr:`alpha`, from :attr:`input`. + +.. math:: + \text{{out}}_i = \text{{input}}_i - \text{{alpha}} \times \text{{other}}_i +""" + + r""" + +Supports :ref:`broadcasting to a common shape `, +:ref:`type promotion `, and integer, float, and complex inputs. + +Args: + {input} + other (Tensor or Number): the tensor or number to subtract from :attr:`input`. + +Keyword args: + alpha (Number): the multiplier for :attr:`other`. + {out} + +Example:: + + >>> a = torch.tensor((1, 2)) + >>> b = torch.tensor((0, 1)) + >>> torch.sub(a, b, alpha=2) + tensor([1, 0]) +""".format(**common_args), +) + +add_docstr( + torch.subtract, + r""" +subtract(input, other, *, alpha=1, out=None) -> Tensor + +Alias for :func:`torch.sub`. +""", +) + +add_docstr( + torch.sum, + r""" +sum(input, *, dtype=None) -> Tensor + +Returns the sum of all elements in the :attr:`input` tensor. + +Args: + {input} + +Keyword args: + {dtype} + +.. note:: Use the `dtype` argument if you need the result in a specific tensor type. + Otherwise, the result type may be automatically promoted (e.g., from `torch.int32` to `torch.int64`). + +Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.1133, -0.9567, 0.2958]]) + >>> torch.sum(a) + tensor(-0.5475) + +.. function:: sum(input, dim, keepdim=False, *, dtype=None) -> Tensor + :noindex: + +Returns the sum of each row of the :attr:`input` tensor in the given +dimension :attr:`dim`. If :attr:`dim` is a list of dimensions, +reduce over all of them. + +{keepdim_details} + +Args: + {input} + {opt_dim_all_reduce} + {opt_keepdim} + +Keyword args: + {dtype} + +Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.0569, -0.2475, 0.0737, -0.3429], + [-0.2993, 0.9138, 0.9337, -1.6864], + [ 0.1132, 0.7892, -0.1003, 0.5688], + [ 0.3637, -0.9906, -0.4752, -1.5197]]) + >>> torch.sum(a, 1) + tensor([-0.4598, -0.1381, 1.3708, -2.6217]) + >>> b = torch.arange(4 * 5 * 6).view(4, 5, 6) + >>> torch.sum(b, (2, 1)) + tensor([ 435., 1335., 2235., 3135.]) +""".format(**multi_dim_common), +) + +add_docstr( + torch.nansum, + r""" +nansum(input, *, dtype=None) -> Tensor + +Returns the sum of all elements, treating Not a Numbers (NaNs) as zero. + +Args: + {input} + +Keyword args: + {dtype} + +Example:: + + >>> a = torch.tensor([1., 2., float('nan'), 4.]) + >>> torch.nansum(a) + tensor(7.) + +.. function:: nansum(input, dim, keepdim=False, *, dtype=None) -> Tensor + :noindex: + +Returns the sum of each row of the :attr:`input` tensor in the given +dimension :attr:`dim`, treating Not a Numbers (NaNs) as zero. +If :attr:`dim` is a list of dimensions, reduce over all of them. + +{keepdim_details} + +Args: + {input} + {opt_dim_all_reduce} + {opt_keepdim} + +Keyword args: + {dtype} + +Example:: + + >>> torch.nansum(torch.tensor([1., float("nan")])) + tensor(1.) + >>> a = torch.tensor([[1, 2], [3., float("nan")]]) + >>> torch.nansum(a) + tensor(6.) + >>> torch.nansum(a, dim=0) + tensor([4., 2.]) + >>> torch.nansum(a, dim=1) + tensor([3., 3.]) +""".format(**multi_dim_common), +) + +add_docstr( + torch.svd, + r""" +svd(input, some=True, compute_uv=True, *, out=None) -> (Tensor, Tensor, Tensor) + +Computes the singular value decomposition of either a matrix or batch of +matrices :attr:`input`. The singular value decomposition is represented as a +namedtuple `(U, S, V)`, such that :attr:`input` :math:`= U \text{diag}(S) V^{\text{H}}`. +where :math:`V^{\text{H}}` is the transpose of `V` for real inputs, +and the conjugate transpose of `V` for complex inputs. +If :attr:`input` is a batch of matrices, then `U`, `S`, and `V` are also +batched with the same batch dimensions as :attr:`input`. + +If :attr:`some` is `True` (default), the method returns the reduced singular +value decomposition. In this case, if the last two dimensions of :attr:`input` are +`m` and `n`, then the returned `U` and `V` matrices will contain only +`min(n, m)` orthonormal columns. + +If :attr:`compute_uv` is `False`, the returned `U` and `V` will be +zero-filled matrices of shape `(m, m)` and `(n, n)` +respectively, and the same device as :attr:`input`. The argument :attr:`some` +has no effect when :attr:`compute_uv` is `False`. + +Supports :attr:`input` of float, double, cfloat and cdouble data types. +The dtypes of `U` and `V` are the same as :attr:`input`'s. `S` will +always be real-valued, even if :attr:`input` is complex. + +.. warning:: + + :func:`torch.svd` is deprecated in favor of :func:`torch.linalg.svd` + and will be removed in a future PyTorch release. + + ``U, S, V = torch.svd(A, some=some, compute_uv=True)`` (default) should be replaced with + + .. code:: python + + U, S, Vh = torch.linalg.svd(A, full_matrices=not some) + V = Vh.mH + + ``_, S, _ = torch.svd(A, some=some, compute_uv=False)`` should be replaced with + + .. code:: python + + S = torch.linalg.svdvals(A) + +.. note:: Differences with :func:`torch.linalg.svd`: + + * :attr:`some` is the opposite of + :func:`torch.linalg.svd`'s :attr:`full_matrices`. Note that + default value for both is `True`, so the default behavior is + effectively the opposite. + * :func:`torch.svd` returns `V`, whereas :func:`torch.linalg.svd` returns + `Vh`, that is, :math:`V^{\text{H}}`. + * If :attr:`compute_uv` is `False`, :func:`torch.svd` returns zero-filled + tensors for `U` and `Vh`, whereas :func:`torch.linalg.svd` returns + empty tensors. + +.. note:: The singular values are returned in descending order. If :attr:`input` is a batch of matrices, + then the singular values of each matrix in the batch are returned in descending order. + +.. note:: The `S` tensor can only be used to compute gradients if :attr:`compute_uv` is `True`. + +.. note:: When :attr:`some` is `False`, the gradients on `U[..., :, min(m, n):]` + and `V[..., :, min(m, n):]` will be ignored in the backward pass, as those vectors + can be arbitrary bases of the corresponding subspaces. + +.. note:: The implementation of :func:`torch.linalg.svd` on CPU uses LAPACK's routine `?gesdd` + (a divide-and-conquer algorithm) instead of `?gesvd` for speed. Analogously, + on GPU, it uses cuSOLVER's routines `gesvdj` and `gesvdjBatched` on CUDA 10.1.243 + and later, and MAGMA's routine `gesdd` on earlier versions of CUDA. + +.. note:: The returned `U` will not be contiguous. The matrix (or batch of matrices) will + be represented as a column-major matrix (i.e. Fortran-contiguous). + +.. warning:: The gradients with respect to `U` and `V` will only be finite when the input does not + have zero nor repeated singular values. + +.. warning:: If the distance between any two singular values is close to zero, the gradients with respect to + `U` and `V` will be numerically unstable, as they depends on + :math:`\frac{1}{\min_{i \neq j} \sigma_i^2 - \sigma_j^2}`. The same happens when the matrix + has small singular values, as these gradients also depend on `S^{-1}`. + +.. warning:: For complex-valued :attr:`input` the singular value decomposition is not unique, + as `U` and `V` may be multiplied by an arbitrary phase factor :math:`e^{i \phi}` on every column. + The same happens when :attr:`input` has repeated singular values, where one may multiply + the columns of the spanning subspace in `U` and `V` by a rotation matrix + and `the resulting vectors will span the same subspace`_. + Different platforms, like NumPy, or inputs on different device types, + may produce different `U` and `V` tensors. + +Args: + input (Tensor): the input tensor of size `(*, m, n)` where `*` is zero or more + batch dimensions consisting of `(m, n)` matrices. + some (bool, optional): controls whether to compute the reduced or full decomposition, and + consequently, the shape of returned `U` and `V`. Default: `True`. + compute_uv (bool, optional): controls whether to compute `U` and `V`. Default: `True`. + +Keyword args: + out (tuple, optional): the output tuple of tensors + +Example:: + + >>> a = torch.randn(5, 3) + >>> a + tensor([[ 0.2364, -0.7752, 0.6372], + [ 1.7201, 0.7394, -0.0504], + [-0.3371, -1.0584, 0.5296], + [ 0.3550, -0.4022, 1.5569], + [ 0.2445, -0.0158, 1.1414]]) + >>> u, s, v = torch.svd(a) + >>> u + tensor([[ 0.4027, 0.0287, 0.5434], + [-0.1946, 0.8833, 0.3679], + [ 0.4296, -0.2890, 0.5261], + [ 0.6604, 0.2717, -0.2618], + [ 0.4234, 0.2481, -0.4733]]) + >>> s + tensor([2.3289, 2.0315, 0.7806]) + >>> v + tensor([[-0.0199, 0.8766, 0.4809], + [-0.5080, 0.4054, -0.7600], + [ 0.8611, 0.2594, -0.4373]]) + >>> torch.dist(a, torch.mm(torch.mm(u, torch.diag(s)), v.t())) + tensor(8.6531e-07) + >>> a_big = torch.randn(7, 5, 3) + >>> u, s, v = torch.svd(a_big) + >>> torch.dist(a_big, torch.matmul(torch.matmul(u, torch.diag_embed(s)), v.mT)) + tensor(2.6503e-06) + +.. _the resulting vectors will span the same subspace: + (https://en.wikipedia.org/wiki/Singular_value_decomposition#Singular_values,_singular_vectors,_and_their_relation_to_the_SVD) +""", +) + + +add_docstr( + torch.t, + r""" +t(input) -> Tensor + +Expects :attr:`input` to be <= 2-D tensor and transposes dimensions 0 +and 1. + +0-D and 1-D tensors are returned as is. When input is a 2-D tensor this +is equivalent to ``transpose(input, 0, 1)``. + +Args: + {input} + +Example:: + + >>> x = torch.randn(()) + >>> x + tensor(0.1995) + >>> torch.t(x) + tensor(0.1995) + >>> x = torch.randn(3) + >>> x + tensor([ 2.4320, -0.4608, 0.7702]) + >>> torch.t(x) + tensor([ 2.4320, -0.4608, 0.7702]) + >>> x = torch.randn(2, 3) + >>> x + tensor([[ 0.4875, 0.9158, -0.5872], + [ 0.3938, -0.6929, 0.6932]]) + >>> torch.t(x) + tensor([[ 0.4875, 0.3938], + [ 0.9158, -0.6929], + [-0.5872, 0.6932]]) + +See also :func:`torch.transpose`. +""".format(**common_args), +) + +add_docstr( + torch.flip, + r""" +flip(input, dims) -> Tensor + +Reverse the order of an n-D tensor along given axis in dims. + +.. note:: + `torch.flip` makes a copy of :attr:`input`'s data. This is different from NumPy's `np.flip`, + which returns a view in constant time. Since copying a tensor's data is more work than viewing that data, + `torch.flip` is expected to be slower than `np.flip`. + +Args: + {input} + dims (a list or tuple): axis to flip on + +Example:: + + >>> x = torch.arange(8).view(2, 2, 2) + >>> x + tensor([[[ 0, 1], + [ 2, 3]], + + [[ 4, 5], + [ 6, 7]]]) + >>> torch.flip(x, [0, 1]) + tensor([[[ 6, 7], + [ 4, 5]], + + [[ 2, 3], + [ 0, 1]]]) +""".format(**common_args), +) + +add_docstr( + torch.fliplr, + r""" +fliplr(input) -> Tensor + +Flip tensor in the left/right direction, returning a new tensor. + +Flip the entries in each row in the left/right direction. +Columns are preserved, but appear in a different order than before. + +Note: + Requires the tensor to be at least 2-D. + +.. note:: + `torch.fliplr` makes a copy of :attr:`input`'s data. This is different from NumPy's `np.fliplr`, + which returns a view in constant time. Since copying a tensor's data is more work than viewing that data, + `torch.fliplr` is expected to be slower than `np.fliplr`. + +Args: + input (Tensor): Must be at least 2-dimensional. + +Example:: + + >>> x = torch.arange(4).view(2, 2) + >>> x + tensor([[0, 1], + [2, 3]]) + >>> torch.fliplr(x) + tensor([[1, 0], + [3, 2]]) +""".format(**common_args), +) + +add_docstr( + torch.flipud, + r""" +flipud(input) -> Tensor + +Flip tensor in the up/down direction, returning a new tensor. + +Flip the entries in each column in the up/down direction. +Rows are preserved, but appear in a different order than before. + +Note: + Requires the tensor to be at least 1-D. + +.. note:: + `torch.flipud` makes a copy of :attr:`input`'s data. This is different from NumPy's `np.flipud`, + which returns a view in constant time. Since copying a tensor's data is more work than viewing that data, + `torch.flipud` is expected to be slower than `np.flipud`. + +Args: + input (Tensor): Must be at least 1-dimensional. + +Example:: + + >>> x = torch.arange(4).view(2, 2) + >>> x + tensor([[0, 1], + [2, 3]]) + >>> torch.flipud(x) + tensor([[2, 3], + [0, 1]]) +""".format(**common_args), +) + +add_docstr( + torch.roll, + r""" +roll(input, shifts, dims=None) -> Tensor + +Roll the tensor :attr:`input` along the given dimension(s). Elements that are +shifted beyond the last position are re-introduced at the first position. If +:attr:`dims` is `None`, the tensor will be flattened before rolling and then +restored to the original shape. + +Args: + {input} + shifts (int or tuple of ints): The number of places by which the elements + of the tensor are shifted. If shifts is a tuple, dims must be a tuple of + the same size, and each dimension will be rolled by the corresponding + value + dims (int or tuple of ints): Axis along which to roll + +Example:: + + >>> x = torch.tensor([1, 2, 3, 4, 5, 6, 7, 8]).view(4, 2) + >>> x + tensor([[1, 2], + [3, 4], + [5, 6], + [7, 8]]) + >>> torch.roll(x, 1) + tensor([[8, 1], + [2, 3], + [4, 5], + [6, 7]]) + >>> torch.roll(x, 1, 0) + tensor([[7, 8], + [1, 2], + [3, 4], + [5, 6]]) + >>> torch.roll(x, -1, 0) + tensor([[3, 4], + [5, 6], + [7, 8], + [1, 2]]) + >>> torch.roll(x, shifts=(2, 1), dims=(0, 1)) + tensor([[6, 5], + [8, 7], + [2, 1], + [4, 3]]) +""".format(**common_args), +) + +add_docstr( + torch.rot90, + r""" +rot90(input, k=1, dims=(0, 1)) -> Tensor + +Rotate an n-D tensor by 90 degrees in the plane specified by dims axis. +Rotation direction is from the first towards the second axis if k > 0, and from the second towards the first for k < 0. + +Args: + {input} + k (int): number of times to rotate. Default value is 1 + dims (a list or tuple): axis to rotate. Default value is [0, 1] + +Example:: + + >>> x = torch.arange(4).view(2, 2) + >>> x + tensor([[0, 1], + [2, 3]]) + >>> torch.rot90(x, 1, [0, 1]) + tensor([[1, 3], + [0, 2]]) + + >>> x = torch.arange(8).view(2, 2, 2) + >>> x + tensor([[[0, 1], + [2, 3]], + + [[4, 5], + [6, 7]]]) + >>> torch.rot90(x, 1, [1, 2]) + tensor([[[1, 3], + [0, 2]], + + [[5, 7], + [4, 6]]]) +""".format(**common_args), +) + +add_docstr( + torch.take, + r""" +take(input, index) -> Tensor + +Returns a new tensor with the elements of :attr:`input` at the given indices. +The input tensor is treated as if it were viewed as a 1-D tensor. The result +takes the same shape as the indices. + +Args: + {input} + index (LongTensor): the indices into tensor + +Example:: + + >>> src = torch.tensor([[4, 3, 5], + ... [6, 7, 8]]) + >>> torch.take(src, torch.tensor([0, 2, 5])) + tensor([ 4, 5, 8]) +""".format(**common_args), +) + +add_docstr( + torch.take_along_dim, + r""" +take_along_dim(input, indices, dim=None, *, out=None) -> Tensor + +Selects values from :attr:`input` at the 1-dimensional indices from :attr:`indices` along the given :attr:`dim`. + +If :attr:`dim` is None, the input array is treated as if it has been flattened to 1d. + +Functions that return indices along a dimension, like :func:`torch.argmax` and :func:`torch.argsort`, +are designed to work with this function. See the examples below. + +.. note:: + This function is similar to NumPy's `take_along_axis`. + See also :func:`torch.gather`. + +Args: + {input} + indices (LongTensor): the indices into :attr:`input`. Must have long dtype. + dim (int, optional): dimension to select along. Default: 0 + +Keyword args: + {out} + +Example:: + + >>> t = torch.tensor([[10, 30, 20], [60, 40, 50]]) + >>> max_idx = torch.argmax(t) + >>> torch.take_along_dim(t, max_idx) + tensor([60]) + >>> sorted_idx = torch.argsort(t, dim=1) + >>> torch.take_along_dim(t, sorted_idx, dim=1) + tensor([[10, 20, 30], + [40, 50, 60]]) +""".format(**common_args), +) + +add_docstr( + torch.tan, + r""" +tan(input, *, out=None) -> Tensor + +Returns a new tensor with the tangent of the elements in the :attr:`input` tensor, +where each value in this input tensor is in radians. + +.. math:: + \text{out}_{i} = \tan(\text{input}_{i}) +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-1.2027, -1.7687, 0.4412, -1.3856]) + >>> torch.tan(a) + tensor([-2.5930, 4.9859, 0.4722, -5.3366]) +""".format(**common_args), +) + +add_docstr( + torch.tanh, + r""" +tanh(input, *, out=None) -> Tensor + +Returns a new tensor with the hyperbolic tangent of the elements +of :attr:`input`. + +.. math:: + \text{out}_{i} = \tanh(\text{input}_{i}) +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.8986, -0.7279, 1.1745, 0.2611]) + >>> torch.tanh(a) + tensor([ 0.7156, -0.6218, 0.8257, 0.2553]) +""".format(**common_args), +) + +add_docstr( + # torch.softmax doc str. Point this to torch.nn.functional.softmax + torch.softmax, + r""" +softmax(input, dim, *, dtype=None) -> Tensor + +Alias for :func:`torch.nn.functional.softmax`. +""", +) + +add_docstr( + torch.topk, + r""" +topk(input, k, dim=None, largest=True, sorted=True, *, out=None) -> (Tensor, LongTensor) + +Returns the :attr:`k` largest elements of the given :attr:`input` tensor along +a given dimension. + +If :attr:`dim` is not given, the last dimension of the `input` is chosen. + +If :attr:`largest` is ``False`` then the `k` smallest elements are returned. + +A namedtuple of `(values, indices)` is returned with the `values` and +`indices` of the largest `k` elements of each row of the `input` tensor in the +given dimension `dim`. + +The boolean option :attr:`sorted` if ``True``, will make sure that the returned +`k` elements are themselves sorted + +.. note:: + When using `torch.topk`, the indices of tied elements are not guaranteed to be stable + and may vary across different invocations. + +Args: + {input} + k (int): the k in "top-k" + dim (int, optional): the dimension to sort along + largest (bool, optional): controls whether to return largest or + smallest elements + sorted (bool, optional): controls whether to return the elements + in sorted order + +Keyword args: + out (tuple, optional): the output tuple of (Tensor, LongTensor) that can be + optionally given to be used as output buffers + +Example:: + + >>> x = torch.arange(1., 6.) + >>> x + tensor([ 1., 2., 3., 4., 5.]) + >>> torch.topk(x, 3) + torch.return_types.topk(values=tensor([5., 4., 3.]), indices=tensor([4, 3, 2])) +""".format(**common_args), +) + +add_docstr( + torch.trace, + r""" +trace(input) -> Tensor + +Returns the sum of the elements of the diagonal of the input 2-D matrix. + +Example:: + + >>> x = torch.arange(1., 10.).view(3, 3) + >>> x + tensor([[ 1., 2., 3.], + [ 4., 5., 6.], + [ 7., 8., 9.]]) + >>> torch.trace(x) + tensor(15.) +""", +) + +add_docstr( + torch.transpose, + r""" +transpose(input, dim0, dim1) -> Tensor + +Returns a tensor that is a transposed version of :attr:`input`. +The given dimensions :attr:`dim0` and :attr:`dim1` are swapped. + +If :attr:`input` is a strided tensor then the resulting :attr:`out` +tensor shares its underlying storage with the :attr:`input` tensor, so +changing the content of one would change the content of the other. + +If :attr:`input` is a :ref:`sparse tensor ` then the +resulting :attr:`out` tensor *does not* share the underlying storage +with the :attr:`input` tensor. + +If :attr:`input` is a :ref:`sparse tensor ` with compressed +layout (SparseCSR, SparseBSR, SparseCSC or SparseBSC) the arguments +:attr:`dim0` and :attr:`dim1` must be both batch dimensions, or must +both be sparse dimensions. The batch dimensions of a sparse tensor are the +dimensions preceding the sparse dimensions. + +.. note:: + Transpositions which interchange the sparse dimensions of a `SparseCSR` + or `SparseCSC` layout tensor will result in the layout changing between + the two options. Transposition of the sparse dimensions of a ` SparseBSR` + or `SparseBSC` layout tensor will likewise generate a result with the + opposite layout. + + +Args: + {input} + dim0 (int): the first dimension to be transposed + dim1 (int): the second dimension to be transposed + +Example:: + + >>> x = torch.randn(2, 3) + >>> x + tensor([[ 1.0028, -0.9893, 0.5809], + [-0.1669, 0.7299, 0.4942]]) + >>> torch.transpose(x, 0, 1) + tensor([[ 1.0028, -0.1669], + [-0.9893, 0.7299], + [ 0.5809, 0.4942]]) + +See also :func:`torch.t`. +""".format(**common_args), +) + +add_docstr( + torch.triangular_solve, + r""" +triangular_solve(b, A, upper=True, transpose=False, unitriangular=False, *, out=None) -> (Tensor, Tensor) + +Solves a system of equations with a square upper or lower triangular invertible matrix :math:`A` +and multiple right-hand sides :math:`b`. + +In symbols, it solves :math:`AX = b` and assumes :math:`A` is square upper-triangular +(or lower-triangular if :attr:`upper`\ `= False`) and does not have zeros on the diagonal. + +`torch.triangular_solve(b, A)` can take in 2D inputs `b, A` or inputs that are +batches of 2D matrices. If the inputs are batches, then returns +batched outputs `X` + +If the diagonal of :attr:`A` contains zeros or elements that are very close to zero and +:attr:`unitriangular`\ `= False` (default) or if the input matrix is badly conditioned, +the result may contain `NaN` s. + +Supports input of float, double, cfloat and cdouble data types. + +.. warning:: + + :func:`torch.triangular_solve` is deprecated in favor of :func:`torch.linalg.solve_triangular` + and will be removed in a future PyTorch release. + :func:`torch.linalg.solve_triangular` has its arguments reversed and does not return a + copy of one of the inputs. + + ``X = torch.triangular_solve(B, A).solution`` should be replaced with + + .. code:: python + + X = torch.linalg.solve_triangular(A, B) + +Args: + b (Tensor): multiple right-hand sides of size :math:`(*, m, k)` where + :math:`*` is zero of more batch dimensions + A (Tensor): the input triangular coefficient matrix of size :math:`(*, m, m)` + where :math:`*` is zero or more batch dimensions + upper (bool, optional): whether :math:`A` is upper or lower triangular. Default: ``True``. + transpose (bool, optional): solves `op(A)X = b` where `op(A) = A^T` if this flag is ``True``, + and `op(A) = A` if it is ``False``. Default: ``False``. + unitriangular (bool, optional): whether :math:`A` is unit triangular. + If True, the diagonal elements of :math:`A` are assumed to be + 1 and not referenced from :math:`A`. Default: ``False``. + +Keyword args: + out ((Tensor, Tensor), optional): tuple of two tensors to write + the output to. Ignored if `None`. Default: `None`. + +Returns: + A namedtuple `(solution, cloned_coefficient)` where `cloned_coefficient` + is a clone of :math:`A` and `solution` is the solution :math:`X` to :math:`AX = b` + (or whatever variant of the system of equations, depending on the keyword arguments.) + +Examples:: + + >>> A = torch.randn(2, 2).triu() + >>> A + tensor([[ 1.1527, -1.0753], + [ 0.0000, 0.7986]]) + >>> b = torch.randn(2, 3) + >>> b + tensor([[-0.0210, 2.3513, -1.5492], + [ 1.5429, 0.7403, -1.0243]]) + >>> torch.triangular_solve(b, A) + torch.return_types.triangular_solve( + solution=tensor([[ 1.7841, 2.9046, -2.5405], + [ 1.9320, 0.9270, -1.2826]]), + cloned_coefficient=tensor([[ 1.1527, -1.0753], + [ 0.0000, 0.7986]])) +""", +) + +add_docstr( + torch.tril, + r""" +tril(input, diagonal=0, *, out=None) -> Tensor + +Returns the lower triangular part of the matrix (2-D tensor) or batch of matrices +:attr:`input`, the other elements of the result tensor :attr:`out` are set to 0. + +The lower triangular part of the matrix is defined as the elements on and +below the diagonal. + +The argument :attr:`diagonal` controls which diagonal to consider. If +:attr:`diagonal` = 0, all elements on and below the main diagonal are +retained. A positive value includes just as many diagonals above the main +diagonal, and similarly a negative value excludes just as many diagonals below +the main diagonal. The main diagonal are the set of indices +:math:`\lbrace (i, i) \rbrace` for :math:`i \in [0, \min\{d_{1}, d_{2}\} - 1]` where +:math:`d_{1}, d_{2}` are the dimensions of the matrix. +""" + + r""" +Args: + {input} + diagonal (int, optional): the diagonal to consider + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(3, 3) + >>> a + tensor([[-1.0813, -0.8619, 0.7105], + [ 0.0935, 0.1380, 2.2112], + [-0.3409, -0.9828, 0.0289]]) + >>> torch.tril(a) + tensor([[-1.0813, 0.0000, 0.0000], + [ 0.0935, 0.1380, 0.0000], + [-0.3409, -0.9828, 0.0289]]) + + >>> b = torch.randn(4, 6) + >>> b + tensor([[ 1.2219, 0.5653, -0.2521, -0.2345, 1.2544, 0.3461], + [ 0.4785, -0.4477, 0.6049, 0.6368, 0.8775, 0.7145], + [ 1.1502, 3.2716, -1.1243, -0.5413, 0.3615, 0.6864], + [-0.0614, -0.7344, -1.3164, -0.7648, -1.4024, 0.0978]]) + >>> torch.tril(b, diagonal=1) + tensor([[ 1.2219, 0.5653, 0.0000, 0.0000, 0.0000, 0.0000], + [ 0.4785, -0.4477, 0.6049, 0.0000, 0.0000, 0.0000], + [ 1.1502, 3.2716, -1.1243, -0.5413, 0.0000, 0.0000], + [-0.0614, -0.7344, -1.3164, -0.7648, -1.4024, 0.0000]]) + >>> torch.tril(b, diagonal=-1) + tensor([[ 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000], + [ 0.4785, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000], + [ 1.1502, 3.2716, 0.0000, 0.0000, 0.0000, 0.0000], + [-0.0614, -0.7344, -1.3164, 0.0000, 0.0000, 0.0000]]) +""".format(**common_args), +) + +# docstr is split in two parts to avoid format mis-captureing :math: braces '{}' +# as common args. +add_docstr( + torch.tril_indices, + r""" +tril_indices(row, col, offset=0, *, dtype=torch.long, device='cpu', layout=torch.strided) -> Tensor + +Returns the indices of the lower triangular part of a :attr:`row`-by- +:attr:`col` matrix in a 2-by-N Tensor, where the first row contains row +coordinates of all indices and the second row contains column coordinates. +Indices are ordered based on rows and then columns. + +The lower triangular part of the matrix is defined as the elements on and +below the diagonal. + +The argument :attr:`offset` controls which diagonal to consider. If +:attr:`offset` = 0, all elements on and below the main diagonal are +retained. A positive value includes just as many diagonals above the main +diagonal, and similarly a negative value excludes just as many diagonals below +the main diagonal. The main diagonal are the set of indices +:math:`\lbrace (i, i) \rbrace` for :math:`i \in [0, \min\{d_{1}, d_{2}\} - 1]` +where :math:`d_{1}, d_{2}` are the dimensions of the matrix. + +.. note:: + When running on CUDA, ``row * col`` must be less than :math:`2^{59}` to + prevent overflow during calculation. +""" + + r""" +Args: + row (``int``): number of rows in the 2-D matrix. + col (``int``): number of columns in the 2-D matrix. + offset (``int``): diagonal offset from the main diagonal. + Default: if not provided, 0. + +Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor, + only support ``torch.int``, ``torch.long``. Default: if ``None``, ``torch.long``. + {device} + layout (:class:`torch.layout`, optional): currently only support ``torch.strided``. + +Example:: + + >>> a = torch.tril_indices(3, 3) + >>> a + tensor([[0, 1, 1, 2, 2, 2], + [0, 0, 1, 0, 1, 2]]) + + >>> a = torch.tril_indices(4, 3, -1) + >>> a + tensor([[1, 2, 2, 3, 3, 3], + [0, 0, 1, 0, 1, 2]]) + + >>> a = torch.tril_indices(4, 3, 1) + >>> a + tensor([[0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3], + [0, 1, 0, 1, 2, 0, 1, 2, 0, 1, 2]]) +""".format(**factory_common_args), +) + +add_docstr( + torch.triu, + r""" +triu(input, diagonal=0, *, out=None) -> Tensor + +Returns the upper triangular part of a matrix (2-D tensor) or batch of matrices +:attr:`input`, the other elements of the result tensor :attr:`out` are set to 0. + +The upper triangular part of the matrix is defined as the elements on and +above the diagonal. + +The argument :attr:`diagonal` controls which diagonal to consider. If +:attr:`diagonal` = 0, all elements on and above the main diagonal are +retained. A positive value excludes just as many diagonals above the main +diagonal, and similarly a negative value includes just as many diagonals below +the main diagonal. The main diagonal are the set of indices +:math:`\lbrace (i, i) \rbrace` for :math:`i \in [0, \min\{d_{1}, d_{2}\} - 1]` where +:math:`d_{1}, d_{2}` are the dimensions of the matrix. +""" + + r""" +Args: + {input} + diagonal (int, optional): the diagonal to consider + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(3, 3) + >>> a + tensor([[ 0.2309, 0.5207, 2.0049], + [ 0.2072, -1.0680, 0.6602], + [ 0.3480, -0.5211, -0.4573]]) + >>> torch.triu(a) + tensor([[ 0.2309, 0.5207, 2.0049], + [ 0.0000, -1.0680, 0.6602], + [ 0.0000, 0.0000, -0.4573]]) + >>> torch.triu(a, diagonal=1) + tensor([[ 0.0000, 0.5207, 2.0049], + [ 0.0000, 0.0000, 0.6602], + [ 0.0000, 0.0000, 0.0000]]) + >>> torch.triu(a, diagonal=-1) + tensor([[ 0.2309, 0.5207, 2.0049], + [ 0.2072, -1.0680, 0.6602], + [ 0.0000, -0.5211, -0.4573]]) + + >>> b = torch.randn(4, 6) + >>> b + tensor([[ 0.5876, -0.0794, -1.8373, 0.6654, 0.2604, 1.5235], + [-0.2447, 0.9556, -1.2919, 1.3378, -0.1768, -1.0857], + [ 0.4333, 0.3146, 0.6576, -1.0432, 0.9348, -0.4410], + [-0.9888, 1.0679, -1.3337, -1.6556, 0.4798, 0.2830]]) + >>> torch.triu(b, diagonal=1) + tensor([[ 0.0000, -0.0794, -1.8373, 0.6654, 0.2604, 1.5235], + [ 0.0000, 0.0000, -1.2919, 1.3378, -0.1768, -1.0857], + [ 0.0000, 0.0000, 0.0000, -1.0432, 0.9348, -0.4410], + [ 0.0000, 0.0000, 0.0000, 0.0000, 0.4798, 0.2830]]) + >>> torch.triu(b, diagonal=-1) + tensor([[ 0.5876, -0.0794, -1.8373, 0.6654, 0.2604, 1.5235], + [-0.2447, 0.9556, -1.2919, 1.3378, -0.1768, -1.0857], + [ 0.0000, 0.3146, 0.6576, -1.0432, 0.9348, -0.4410], + [ 0.0000, 0.0000, -1.3337, -1.6556, 0.4798, 0.2830]]) +""".format(**common_args), +) + +# docstr is split in two parts to avoid format mis-capturing :math: braces '{}' +# as common args. +add_docstr( + torch.triu_indices, + r""" +triu_indices(row, col, offset=0, *, dtype=torch.long, device='cpu', layout=torch.strided) -> Tensor + +Returns the indices of the upper triangular part of a :attr:`row` by +:attr:`col` matrix in a 2-by-N Tensor, where the first row contains row +coordinates of all indices and the second row contains column coordinates. +Indices are ordered based on rows and then columns. + +The upper triangular part of the matrix is defined as the elements on and +above the diagonal. + +The argument :attr:`offset` controls which diagonal to consider. If +:attr:`offset` = 0, all elements on and above the main diagonal are +retained. A positive value excludes just as many diagonals above the main +diagonal, and similarly a negative value includes just as many diagonals below +the main diagonal. The main diagonal are the set of indices +:math:`\lbrace (i, i) \rbrace` for :math:`i \in [0, \min\{d_{1}, d_{2}\} - 1]` +where :math:`d_{1}, d_{2}` are the dimensions of the matrix. + +.. note:: + When running on CUDA, ``row * col`` must be less than :math:`2^{59}` to + prevent overflow during calculation. +""" + + r""" +Args: + row (``int``): number of rows in the 2-D matrix. + col (``int``): number of columns in the 2-D matrix. + offset (``int``): diagonal offset from the main diagonal. + Default: if not provided, 0. + +Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor, + only support ``torch.int``, ``torch.long``. Default: if ``None``, ``torch.long``. + {device} + layout (:class:`torch.layout`, optional): currently only support ``torch.strided``. + +Example:: + + >>> a = torch.triu_indices(3, 3) + >>> a + tensor([[0, 0, 0, 1, 1, 2], + [0, 1, 2, 1, 2, 2]]) + + >>> a = torch.triu_indices(4, 3, -1) + >>> a + tensor([[0, 0, 0, 1, 1, 1, 2, 2, 3], + [0, 1, 2, 0, 1, 2, 1, 2, 2]]) + + >>> a = torch.triu_indices(4, 3, 1) + >>> a + tensor([[0, 0, 1], + [1, 2, 2]]) +""".format(**factory_common_args), +) + +add_docstr( + torch.true_divide, + r""" +true_divide(dividend, divisor, *, out) -> Tensor + +Alias for :func:`torch.div` with ``rounding_mode=None``. +""", +) + +add_docstr( + torch.trunc, + r""" +trunc(input, *, out=None) -> Tensor + +Returns a new tensor with the truncated integer values of +the elements of :attr:`input`. + +For integer inputs, follows the array-api convention of returning a +copy of the input tensor. + +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 3.4742, 0.5466, -0.8008, -0.9079]) + >>> torch.trunc(a) + tensor([ 3., 0., -0., -0.]) +""".format(**common_args), +) + +add_docstr( + torch.fake_quantize_per_tensor_affine, + r""" +fake_quantize_per_tensor_affine(input, scale, zero_point, quant_min, quant_max) -> Tensor + +Returns a new tensor with the data in :attr:`input` fake quantized using :attr:`scale`, +:attr:`zero_point`, :attr:`quant_min` and :attr:`quant_max`. + +.. math:: + \text{output} = ( + min( + \text{quant\_max}, + max( + \text{quant\_min}, + \text{std::nearby\_int}(\text{input} / \text{scale}) + \text{zero\_point} + ) + ) - \text{zero\_point} + ) \times \text{scale} + +Args: + input (Tensor): the input value(s), ``torch.float32`` tensor + scale (double scalar or ``float32`` Tensor): quantization scale + zero_point (int64 scalar or ``int32`` Tensor): quantization zero_point + quant_min (int64): lower bound of the quantized domain + quant_max (int64): upper bound of the quantized domain + +Returns: + Tensor: A newly fake_quantized ``torch.float32`` tensor + +Example:: + + >>> x = torch.randn(4) + >>> x + tensor([ 0.0552, 0.9730, 0.3973, -1.0780]) + >>> torch.fake_quantize_per_tensor_affine(x, 0.1, 0, 0, 255) + tensor([0.1000, 1.0000, 0.4000, 0.0000]) + >>> torch.fake_quantize_per_tensor_affine(x, torch.tensor(0.1), torch.tensor(0), 0, 255) + tensor([0.1000, 1.0000, 0.4000, 0.0000]) +""", +) + +add_docstr( + torch.fake_quantize_per_channel_affine, + r""" +fake_quantize_per_channel_affine(input, scale, zero_point, axis, quant_min, quant_max) -> Tensor + +Returns a new tensor with the data in :attr:`input` fake quantized per channel using :attr:`scale`, +:attr:`zero_point`, :attr:`quant_min` and :attr:`quant_max`, across the channel specified by :attr:`axis`. + +.. math:: + \text{output} = ( + min( + \text{quant\_max}, + max( + \text{quant\_min}, + \text{std::nearby\_int}(\text{input} / \text{scale}) + \text{zero\_point} + ) + ) - \text{zero\_point} + ) \times \text{scale} + +Args: + input (Tensor): the input value(s), in ``torch.float32`` + scale (Tensor): quantization scale, per channel in ``torch.float32`` + zero_point (Tensor): quantization zero_point, per channel in ``torch.int32`` or ``torch.half`` or ``torch.float32`` + axis (int32): channel axis + quant_min (int64): lower bound of the quantized domain + quant_max (int64): upper bound of the quantized domain + +Returns: + Tensor: A newly fake_quantized per channel ``torch.float32`` tensor + +Example:: + + >>> x = torch.randn(2, 2, 2) + >>> x + tensor([[[-0.2525, -0.0466], + [ 0.3491, -0.2168]], + + [[-0.5906, 1.6258], + [ 0.6444, -0.0542]]]) + >>> scales = (torch.randn(2) + 1) * 0.05 + >>> scales + tensor([0.0475, 0.0486]) + >>> zero_points = torch.zeros(2).to(torch.int32) + >>> zero_points + tensor([0, 0]) + >>> torch.fake_quantize_per_channel_affine(x, scales, zero_points, 1, 0, 255) + tensor([[[0.0000, 0.0000], + [0.3405, 0.0000]], + + [[0.0000, 1.6134], + [0.6323, 0.0000]]]) +""", +) + +add_docstr( + torch.fix, + r""" +fix(input, *, out=None) -> Tensor + +Alias for :func:`torch.trunc` +""", +) + +add_docstr( + torch.unsqueeze, + r""" +unsqueeze(input, dim) -> Tensor + +Returns a new tensor with a dimension of size one inserted at the +specified position. + +The returned tensor shares the same underlying data with this tensor. + +A :attr:`dim` value within the range ``[-input.dim() - 1, input.dim() + 1)`` +can be used. Negative :attr:`dim` will correspond to :meth:`unsqueeze` +applied at :attr:`dim` = ``dim + input.dim() + 1``. + +Args: + {input} + dim (int): the index at which to insert the singleton dimension + +Example:: + + >>> x = torch.tensor([1, 2, 3, 4]) + >>> torch.unsqueeze(x, 0) + tensor([[ 1, 2, 3, 4]]) + >>> torch.unsqueeze(x, 1) + tensor([[ 1], + [ 2], + [ 3], + [ 4]]) +""".format(**common_args), +) + +add_docstr( + torch.var, + r""" +var(input, dim=None, *, correction=1, keepdim=False, out=None) -> Tensor + +Calculates the variance over the dimensions specified by :attr:`dim`. :attr:`dim` +can be a single dimension, list of dimensions, or ``None`` to reduce over all +dimensions. + +The variance (:math:`\sigma^2`) is calculated as + +.. math:: \sigma^2 = \frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2 + +where :math:`x` is the sample set of elements, :math:`\bar{x}` is the +sample mean, :math:`N` is the number of samples and :math:`\delta N` is +the :attr:`correction`. +""" + + r""" + +{keepdim_details} + +Args: + {input} + {opt_dim_all_reduce} + +Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + {opt_keepdim} + {out} + +Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.var(a, dim=1, keepdim=True) + tensor([[1.0631], + [0.5590], + [1.4893], + [0.8258]]) + +.. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + +""".format(**multi_dim_common), +) + +add_docstr( + torch.var_mean, + r""" +var_mean(input, dim=None, *, correction=1, keepdim=False, out=None) -> (Tensor, Tensor) + +Calculates the variance and mean over the dimensions specified by :attr:`dim`. +:attr:`dim` can be a single dimension, list of dimensions, or ``None`` to +reduce over all dimensions. + +The variance (:math:`\sigma^2`) is calculated as + +.. math:: \sigma^2 = \frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2 + +where :math:`x` is the sample set of elements, :math:`\bar{x}` is the +sample mean, :math:`N` is the number of samples and :math:`\delta N` is +the :attr:`correction`. +""" + + r""" + +{keepdim_details} + +Args: + {input} + {opt_dim_all_reduce} + +Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + {opt_keepdim} + {out} + +Returns: + A tuple (var, mean) containing the variance and mean. + +Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.var_mean(a, dim=0, keepdim=True) + (tensor([[1.5926, 1.0056, 1.2005, 0.3646]]), + tensor([[ 0.0645, 0.4485, 0.8707, -0.0665]])) + +.. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + +""".format(**multi_dim_common), +) + +add_docstr( + torch.zeros, + r""" +zeros(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + +Returns a tensor filled with the scalar value `0`, with the shape defined +by the variable argument :attr:`size`. + +Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + +Keyword args: + {out} + {dtype} + {layout} + {device} + {requires_grad} + +Example:: + + >>> torch.zeros(2, 3) + tensor([[ 0., 0., 0.], + [ 0., 0., 0.]]) + + >>> torch.zeros(5) + tensor([ 0., 0., 0., 0., 0.]) +""".format(**factory_common_args), +) + +add_docstr( + torch.zeros_like, + r""" +zeros_like(input, *, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + +Returns a tensor filled with the scalar value `0`, with the same size as +:attr:`input`. ``torch.zeros_like(input)`` is equivalent to +``torch.zeros(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``. + +.. warning:: + As of 0.4, this function does not support an :attr:`out` keyword. As an alternative, + the old ``torch.zeros_like(input, out=output)`` is equivalent to + ``torch.zeros(input.size(), out=output)``. + +Args: + {input} + +Keyword args: + {dtype} + {layout} + {device} + {requires_grad} + {memory_format} + +Example:: + + >>> input = torch.empty(2, 3) + >>> torch.zeros_like(input) + tensor([[ 0., 0., 0.], + [ 0., 0., 0.]]) +""".format(**factory_like_common_args), +) + +add_docstr( + torch.empty, + """ +empty(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False, \ +memory_format=torch.contiguous_format) -> Tensor + +Returns a tensor filled with uninitialized data. The shape of the tensor is +defined by the variable argument :attr:`size`. + +.. note:: + If :func:`torch.use_deterministic_algorithms()` and + :attr:`torch.utils.deterministic.fill_uninitialized_memory` are both set to + ``True``, the output tensor is initialized to prevent any possible + nondeterministic behavior from using the data as an input to an operation. + Floating point and complex tensors are filled with NaN, and integer tensors + are filled with the maximum value. + +Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + +Keyword args: + {out} + {dtype} + {layout} + {device} + {requires_grad} + {pin_memory} + {memory_format} + +Example:: + + >>> torch.empty((2,3), dtype=torch.int64) + tensor([[ 9.4064e+13, 2.8000e+01, 9.3493e+13], + [ 7.5751e+18, 7.1428e+18, 7.5955e+18]]) +""".format(**factory_common_args), +) + +add_docstr( + torch.empty_like, + r""" +empty_like(input, *, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + +Returns an uninitialized tensor with the same size as :attr:`input`. +``torch.empty_like(input)`` is equivalent to +``torch.empty(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``. + +.. note:: + If :func:`torch.use_deterministic_algorithms()` and + :attr:`torch.utils.deterministic.fill_uninitialized_memory` are both set to + ``True``, the output tensor is initialized to prevent any possible + nondeterministic behavior from using the data as an input to an operation. + Floating point and complex tensors are filled with NaN, and integer tensors + are filled with the maximum value. + + When ``torch.preserve_format`` is used: + If the input tensor is dense (i.e., non-overlapping strided), + its memory format (including strides) is retained. + Otherwise (e.g., a non-dense view like a stepped slice), + the output is converted to the dense format. + +Args: + {input} + +Keyword args: + {dtype} + {layout} + {device} + {requires_grad} + {memory_format} + +Example:: + + >>> a=torch.empty((2,3), dtype=torch.int32, device = 'cuda') + >>> torch.empty_like(a) + tensor([[0, 0, 0], + [0, 0, 0]], device='cuda:0', dtype=torch.int32) +""".format(**factory_like_common_args), +) + +add_docstr( + torch.empty_strided, + r""" +empty_strided(size, stride, *, dtype=None, layout=None, device=None, requires_grad=False, pin_memory=False) -> Tensor + +Creates a tensor with the specified :attr:`size` and :attr:`stride` and filled with undefined data. + +.. warning:: + If the constructed tensor is "overlapped" (with multiple indices referring to the same element + in memory) its behavior is undefined. + +.. note:: + If :func:`torch.use_deterministic_algorithms()` and + :attr:`torch.utils.deterministic.fill_uninitialized_memory` are both set to + ``True``, the output tensor is initialized to prevent any possible + nondeterministic behavior from using the data as an input to an operation. + Floating point and complex tensors are filled with NaN, and integer tensors + are filled with the maximum value. + +Args: + size (tuple of int): the shape of the output tensor + stride (tuple of int): the strides of the output tensor + +Keyword args: + {dtype} + {layout} + {device} + {requires_grad} + {pin_memory} + +Example:: + + >>> a = torch.empty_strided((2, 3), (1, 2)) + >>> a + tensor([[8.9683e-44, 4.4842e-44, 5.1239e+07], + [0.0000e+00, 0.0000e+00, 3.0705e-41]]) + >>> a.stride() + (1, 2) + >>> a.size() + torch.Size([2, 3]) +""".format(**factory_common_args), +) + +add_docstr( + torch.empty_permuted, + r""" +empty_permuted(size, physical_layout, *, dtype=None, layout=None, device=None, requires_grad=False, pin_memory=False) -> Tensor + +Creates an uninitialized, non-overlapping and dense tensor with the +specified :attr:`size`, with :attr:`physical_layout` specifying how the +dimensions are physically laid out in memory (each logical dimension is listed +from outermost to innermost). :attr:`physical_layout` is a generalization +of NCHW/NHWC notation: if each dimension is assigned a number according to +what order they occur in size (N=0, C=1, H=2, W=3), then NCHW is ``(0, 1, 2, 3)`` +while NHWC is ``(0, 2, 3, 1)``. Equivalently, the strides of the output +tensor ``t`` are such that ``t.stride(physical_layout[i]) == contiguous_strides[i]`` +(notably, this function is *not* equivalent to ``torch.empty(size).permute(physical_layout)``). + +Unlike :func:`torch.empty_strided`, this is guaranteed to produce a dense +tensor with no overlaps. If possible, prefer using this function over +:func:`torch.empty_strided` or manual use of :func:`torch.as_strided`. + +.. note:: + If :func:`torch.use_deterministic_algorithms()` and + :attr:`torch.utils.deterministic.fill_uninitialized_memory` are both set to + ``True``, the output tensor is initialized to prevent any possible + nondeterministic behavior from using the data as an input to an operation. + Floating point and complex tensors are filled with NaN, and integer tensors + are filled with the maximum value. + +Args: + size (tuple of int): the shape of the output tensor + physical_layout (tuple of int): the ordering of dimensions physically in memory + +Keyword args: + {dtype} + {layout} + {device} + {requires_grad} + {pin_memory} + +Examples: + + >>> torch.empty((2, 3, 5, 7)).stride() + (105, 35, 7, 1) + >>> torch.empty_permuted((2, 3, 5, 7), (0, 1, 2, 3)).stride() + (105, 35, 7, 1) + >>> torch.empty((2, 3, 5, 7), memory_format=torch.channels_last).stride() + (105, 1, 21, 3) + >>> torch.empty_permuted((2, 3, 5, 7), (0, 2, 3, 1)).stride() + (105, 1, 21, 3) + >>> torch.empty_permuted((2, 3, 5, 7), (0, 2, 3, 1)).dim_order() + (0, 2, 3, 1) +""".format(**factory_common_args), +) + +add_docstr( + torch.full, + r""" +full(size, fill_value, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + +Creates a tensor of size :attr:`size` filled with :attr:`fill_value`. The +tensor's dtype is inferred from :attr:`fill_value`. + +Args: + size (int...): a list, tuple, or :class:`torch.Size` of integers defining the + shape of the output tensor. + fill_value (Scalar): the value to fill the output tensor with. + +Keyword args: + {out} + {dtype} + {layout} + {device} + {requires_grad} + +Example:: + + >>> torch.full((2, 3), 3.141592) + tensor([[ 3.1416, 3.1416, 3.1416], + [ 3.1416, 3.1416, 3.1416]]) +""".format(**factory_common_args), +) + +add_docstr( + torch.full_like, + """ +full_like(input, fill_value, \\*, dtype=None, layout=torch.strided, device=None, requires_grad=False, \ +memory_format=torch.preserve_format) -> Tensor + +Returns a tensor with the same size as :attr:`input` filled with :attr:`fill_value`. +``torch.full_like(input, fill_value)`` is equivalent to +``torch.full(input.size(), fill_value, dtype=input.dtype, layout=input.layout, device=input.device)``. + +Args: + {input} + fill_value: the number to fill the output tensor with. + +Keyword args: + {dtype} + {layout} + {device} + {requires_grad} + {memory_format} + +Example:: + + >>> x = torch.ones(2, 3) + >>> torch.full_like(x, 3.141592) + tensor([[ 3.1416, 3.1416, 3.1416], + [ 3.1416, 3.1416, 3.1416]]) + >>> torch.full_like(x, 7) + tensor([[7., 7., 7.], + [7., 7., 7.]]) + >>> torch.full_like(x, 0.5, dtype=torch.int32) + tensor([[0, 0, 0], + [0, 0, 0]], dtype=torch.int32) + >>> y = torch.randn(3, 4, dtype=torch.float64) + >>> torch.full_like(y, -1.0) + tensor([[-1., -1., -1., -1.], + [-1., -1., -1., -1.], + [-1., -1., -1., -1.]], dtype=torch.float64) +""".format(**factory_like_common_args), +) + +add_docstr( + torch.det, + r""" +det(input) -> Tensor + +Alias for :func:`torch.linalg.det` +""", +) + +add_docstr( + torch.where, + r""" +where(condition, input, other, *, out=None) -> Tensor + +Return a tensor of elements selected from either :attr:`input` or :attr:`other`, depending on :attr:`condition`. + +The operation is defined as: + +.. math:: + \text{out}_i = \begin{cases} + \text{input}_i & \text{if } \text{condition}_i \\ + \text{other}_i & \text{otherwise} \\ + \end{cases} +""" + + r""" +.. note:: + The tensors :attr:`condition`, :attr:`input`, :attr:`other` must be :ref:`broadcastable `. + +Arguments: + condition (BoolTensor): When True (nonzero), yield input, otherwise yield other + input (Tensor or Scalar): value (if :attr:`input` is a scalar) or values selected at indices + where :attr:`condition` is ``True`` + other (Tensor or Scalar): value (if :attr:`other` is a scalar) or values selected at indices + where :attr:`condition` is ``False`` + +Keyword args: + {out} + +Returns: + Tensor: A tensor of shape equal to the broadcasted shape of :attr:`condition`, :attr:`input`, :attr:`other` + +Example:: + + >>> x = torch.randn(3, 2) + >>> y = torch.ones(3, 2) + >>> x + tensor([[-0.4620, 0.3139], + [ 0.3898, -0.7197], + [ 0.0478, -0.1657]]) + >>> torch.where(x > 0, 1.0, 0.0) + tensor([[0., 1.], + [1., 0.], + [1., 0.]]) + >>> torch.where(x > 0, x, y) + tensor([[ 1.0000, 0.3139], + [ 0.3898, 1.0000], + [ 0.0478, 1.0000]]) + >>> x = torch.randn(2, 2, dtype=torch.double) + >>> x + tensor([[ 1.0779, 0.0383], + [-0.8785, -1.1089]], dtype=torch.float64) + >>> torch.where(x > 0, x, 0.) + tensor([[1.0779, 0.0383], + [0.0000, 0.0000]], dtype=torch.float64) + +.. function:: where(condition) -> tuple of LongTensor + :noindex: + +``torch.where(condition)`` is identical to +``torch.nonzero(condition, as_tuple=True)``. + +.. note:: + See also :func:`torch.nonzero`. +""".format(**common_args), +) + +add_docstr( + torch.logdet, + r""" +logdet(input) -> Tensor + +Calculates log determinant of a square matrix or batches of square matrices. + +It returns ``-inf`` if the input has a determinant of zero, and ``NaN`` if it has +a negative determinant. + +.. note:: + Backward through :meth:`logdet` internally uses SVD results when :attr:`input` + is not invertible. In this case, double backward through :meth:`logdet` will + be unstable in when :attr:`input` doesn't have distinct singular values. See + :func:`torch.linalg.svd` for details. + +.. seealso:: + + :func:`torch.linalg.slogdet` computes the sign (resp. angle) and natural logarithm of the + absolute value of the determinant of real-valued (resp. complex) square matrices. + +Arguments: + input (Tensor): the input tensor of size ``(*, n, n)`` where ``*`` is zero or more + batch dimensions. + +Example:: + + >>> A = torch.randn(3, 3) + >>> torch.det(A) + tensor(0.2611) + >>> torch.logdet(A) + tensor(-1.3430) + >>> A + tensor([[[ 0.9254, -0.6213], + [-0.5787, 1.6843]], + + [[ 0.3242, -0.9665], + [ 0.4539, -0.0887]], + + [[ 1.1336, -0.4025], + [-0.7089, 0.9032]]]) + >>> A.det() + tensor([1.1990, 0.4099, 0.7386]) + >>> A.det().log() + tensor([ 0.1815, -0.8917, -0.3031]) +""", +) + +add_docstr( + torch.slogdet, + r""" +slogdet(input) -> (Tensor, Tensor) + +Alias for :func:`torch.linalg.slogdet` +""", +) + +add_docstr( + torch.pinverse, + r""" +pinverse(input, rcond=1e-15) -> Tensor + +Alias for :func:`torch.linalg.pinv` +""", +) + +add_docstr( + torch.hann_window, + """ +hann_window(window_length, periodic=True, *, dtype=None, \ +layout=torch.strided, device=None, requires_grad=False) -> Tensor +""" + + r""" +Hann window function. + +.. math:: + w[n] = \frac{1}{2}\ \left[1 - \cos \left( \frac{2 \pi n}{N - 1} \right)\right] = + \sin^2 \left( \frac{\pi n}{N - 1} \right), + +where :math:`N` is the full window size. + +The input :attr:`window_length` is a positive integer controlling the +returned window size. :attr:`periodic` flag determines whether the returned +window trims off the last duplicate value from the symmetric window and is +ready to be used as a periodic window with functions like +:meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in +above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have +``torch.hann_window(L, periodic=True)`` equal to +``torch.hann_window(L + 1, periodic=False)[:-1])``. + +.. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. +""" + + r""" +Arguments: + window_length (int): the size of returned window + periodic (bool, optional): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + +Keyword args: + {dtype} Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + {device} + {requires_grad} + +Returns: + Tensor: A 1-D tensor of size :math:`(\text{{window\_length}},)` containing the window + +""".format(**factory_common_args), +) + + +add_docstr( + torch.hamming_window, + """ +hamming_window(window_length, *, dtype=None, layout=None, device=None, pin_memory=False, \ +requires_grad=False) -> Tensor +""" + + r""" +Hamming window function. + +.. math:: + w[n] = \alpha - \beta\ \cos \left( \frac{2 \pi n}{N - 1} \right), + +where :math:`N` is the full window size. + +The input :attr:`window_length` is a positive integer controlling the +returned window size. :attr:`periodic` flag determines whether the returned +window trims off the last duplicate value from the symmetric window and is +ready to be used as a periodic window with functions like +:meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in +above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have +``torch.hamming_window(L, periodic=True)`` equal to +``torch.hamming_window(L + 1, periodic=False)[:-1])``. + +.. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. + +.. note:: + This is a generalized version of :meth:`torch.hann_window`. +""" + + r""" +Arguments: + window_length (int): the size of returned window + +Keyword args: + {dtype} Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + {device} + {pin_memory} + {requires_grad} + +Returns: + Tensor: A 1-D tensor of size :math:`(\text{{window\_length}},)` containing the window. + +.. function:: hamming_window(window_length, periodic, *, dtype=None, layout=None, device=None, \ + pin_memory=False, requires_grad=False) -> Tensor + :noindex: + +Hamming window function with periodic specified. + +Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + +Keyword args: + {dtype} Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + {device} + {pin_memory} + {requires_grad} + +Returns: + Tensor: A 1-D tensor of size :math:`(\text{{window\_length}},)` containing the window. + +.. function:: hamming_window(window_length, periodic, float alpha, *, dtype=None, layout=None, device=None, \ + pin_memory=False, requires_grad=False) -> Tensor + :noindex: + +Hamming window function with periodic and alpha specified. + +Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + alpha (float): The coefficient :math:`\alpha` in the equation above + +Keyword args: + {dtype} Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + {device} + {pin_memory} + {requires_grad} + +Returns: + Tensor: A 1-D tensor of size :math:`(\text{{window\_length}},)` containing the window. + +.. function:: hamming_window(window_length, periodic, float alpha, float beta, *, dtype=None, layout=None, \ + device=None, pin_memory=False, requires_grad=False) -> Tensor + :noindex: + +Hamming window function with periodic, alpha and beta specified. + +Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + alpha (float): The coefficient :math:`\alpha` in the equation above + beta (float): The coefficient :math:`\beta` in the equation above + +Keyword args: + {dtype} Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + {device} + {pin_memory} + {requires_grad} + +Returns: + Tensor: A 1-D tensor of size :math:`(\text{{window\_length}},)` containing the window. + +""".format(**factory_common_args), +) + + +add_docstr( + torch.bartlett_window, + """ +bartlett_window(window_length, periodic=True, *, dtype=None, \ +layout=torch.strided, device=None, requires_grad=False) -> Tensor +""" + + r""" +Bartlett window function. + +.. math:: + w[n] = 1 - \left| \frac{2n}{N-1} - 1 \right| = \begin{cases} + \frac{2n}{N - 1} & \text{if } 0 \leq n \leq \frac{N - 1}{2} \\ + 2 - \frac{2n}{N - 1} & \text{if } \frac{N - 1}{2} < n < N \\ + \end{cases}, + +where :math:`N` is the full window size. + +The input :attr:`window_length` is a positive integer controlling the +returned window size. :attr:`periodic` flag determines whether the returned +window trims off the last duplicate value from the symmetric window and is +ready to be used as a periodic window with functions like +:meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in +above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have +``torch.bartlett_window(L, periodic=True)`` equal to +``torch.bartlett_window(L + 1, periodic=False)[:-1])``. + +.. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. +""" + + r""" +Arguments: + window_length (int): the size of returned window + periodic (bool, optional): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + +Keyword args: + {dtype} Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + {device} + {requires_grad} + +Returns: + Tensor: A 1-D tensor of size :math:`(\text{{window\_length}},)` containing the window + +""".format(**factory_common_args), +) + + +add_docstr( + torch.blackman_window, + """ +blackman_window(window_length, periodic=True, *, dtype=None, \ +layout=torch.strided, device=None, requires_grad=False) -> Tensor +""" + + r""" +Blackman window function. + +.. math:: + w[n] = 0.42 - 0.5 \cos \left( \frac{2 \pi n}{N - 1} \right) + 0.08 \cos \left( \frac{4 \pi n}{N - 1} \right) + +where :math:`N` is the full window size. + +The input :attr:`window_length` is a positive integer controlling the +returned window size. :attr:`periodic` flag determines whether the returned +window trims off the last duplicate value from the symmetric window and is +ready to be used as a periodic window with functions like +:meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in +above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have +``torch.blackman_window(L, periodic=True)`` equal to +``torch.blackman_window(L + 1, periodic=False)[:-1]``. + +.. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. +""" + + r""" +Arguments: + window_length (int): the size of returned window + periodic (bool, optional): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + +Keyword args: + {dtype} Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + {device} + {requires_grad} + +Returns: + Tensor: A 1-D tensor of size :math:`(\text{{window\_length}},)` containing the window + +""".format(**factory_common_args), +) + + +add_docstr( + torch.kaiser_window, + """ +kaiser_window(window_length, periodic=True, beta=12.0, *, dtype=None, \ +layout=torch.strided, device=None, requires_grad=False) -> Tensor +""" + + r""" +Computes the Kaiser window with window length :attr:`window_length` and shape parameter :attr:`beta`. + +Let I_0 be the zeroth order modified Bessel function of the first kind (see :func:`torch.i0`) and +``N = L - 1`` if :attr:`periodic` is False and ``L`` if :attr:`periodic` is True, +where ``L`` is the :attr:`window_length`. This function computes: + +.. math:: + out_i = I_0 \left( \beta \sqrt{1 - \left( {\frac{i - N/2}{N/2}} \right) ^2 } \right) / I_0( \beta ) + +Calling ``torch.kaiser_window(L, B, periodic=True)`` is equivalent to calling +``torch.kaiser_window(L + 1, B, periodic=False)[:-1])``. +The :attr:`periodic` argument is intended as a helpful shorthand +to produce a periodic window as input to functions like :func:`torch.stft`. + +.. note:: + If :attr:`window_length` is one, then the returned window is a single element tensor containing a one. + +""" + + r""" +Args: + window_length (int): length of the window. + periodic (bool, optional): If True, returns a periodic window suitable for use in spectral analysis. + If False, returns a symmetric window suitable for use in filter design. + beta (float, optional): shape parameter for the window. + +Keyword args: + {dtype} + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + {device} + {requires_grad} + +""".format(**factory_common_args), +) + + +add_docstr( + torch.vander, + """ +vander(x, N=None, increasing=False) -> Tensor +""" + + r""" +Generates a Vandermonde matrix. + +The columns of the output matrix are elementwise powers of the input vector :math:`x^{{(N-1)}}, x^{{(N-2)}}, ..., x^0`. +If increasing is True, the order of the columns is reversed :math:`x^0, x^1, ..., x^{{(N-1)}}`. Such a +matrix with a geometric progression in each row is named for Alexandre-Theophile Vandermonde. + +Arguments: + x (Tensor): 1-D input tensor. + N (int, optional): Number of columns in the output. If N is not specified, + a square array is returned :math:`(N = len(x))`. + increasing (bool, optional): Order of the powers of the columns. If True, + the powers increase from left to right, if False (the default) they are reversed. + +Returns: + Tensor: Vandermonde matrix. If increasing is False, the first column is :math:`x^{{(N-1)}}`, + the second :math:`x^{{(N-2)}}` and so forth. If increasing is True, the columns + are :math:`x^0, x^1, ..., x^{{(N-1)}}`. + +Example:: + + >>> x = torch.tensor([1, 2, 3, 5]) + >>> torch.vander(x) + tensor([[ 1, 1, 1, 1], + [ 8, 4, 2, 1], + [ 27, 9, 3, 1], + [125, 25, 5, 1]]) + >>> torch.vander(x, N=3) + tensor([[ 1, 1, 1], + [ 4, 2, 1], + [ 9, 3, 1], + [25, 5, 1]]) + >>> torch.vander(x, N=3, increasing=True) + tensor([[ 1, 1, 1], + [ 1, 2, 4], + [ 1, 3, 9], + [ 1, 5, 25]]) + +""".format(**factory_common_args), +) + + +add_docstr( + torch.unbind, + r""" +unbind(input, dim=0) -> seq + +Removes a tensor dimension. + +Returns a tuple of all slices along a given dimension, already without it. + +Arguments: + input (Tensor): the tensor to unbind + dim (int): dimension to remove + +Example:: + + >>> torch.unbind(torch.tensor([[1, 2, 3], + >>> [4, 5, 6], + >>> [7, 8, 9]])) + (tensor([1, 2, 3]), tensor([4, 5, 6]), tensor([7, 8, 9])) +""", +) + + +add_docstr( + torch.combinations, + r""" +combinations(input: Tensor, r: int = 2, with_replacement: bool = False) -> seq + +Compute combinations of length :math:`r` of the given tensor. The behavior is similar to +python's `itertools.combinations` when `with_replacement` is set to `False`, and +`itertools.combinations_with_replacement` when `with_replacement` is set to `True`. + +Arguments: + input (Tensor): 1D vector. + r (int, optional): number of elements to combine + with_replacement (bool, optional): whether to allow duplication in combination + +Returns: + Tensor: A tensor equivalent to converting all the input tensors into lists, do + `itertools.combinations` or `itertools.combinations_with_replacement` on these + lists, and finally convert the resulting list into tensor. + +Example:: + + >>> a = [1, 2, 3] + >>> list(itertools.combinations(a, r=2)) + [(1, 2), (1, 3), (2, 3)] + >>> list(itertools.combinations(a, r=3)) + [(1, 2, 3)] + >>> list(itertools.combinations_with_replacement(a, r=2)) + [(1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)] + >>> tensor_a = torch.tensor(a) + >>> torch.combinations(tensor_a) + tensor([[1, 2], + [1, 3], + [2, 3]]) + >>> torch.combinations(tensor_a, r=3) + tensor([[1, 2, 3]]) + >>> torch.combinations(tensor_a, with_replacement=True) + tensor([[1, 1], + [1, 2], + [1, 3], + [2, 2], + [2, 3], + [3, 3]]) + +""", +) + +add_docstr( + torch.trapezoid, + r""" +trapezoid(y, x=None, *, dx=None, dim=-1) -> Tensor + +Computes the `trapezoidal rule `_ along +:attr:`dim`. By default the spacing between elements is assumed to be 1, but +:attr:`dx` can be used to specify a different constant spacing, and :attr:`x` can be +used to specify arbitrary spacing along :attr:`dim`. Only one of :attr:`x` or :attr:`dx` should be specified. + + +Assuming :attr:`y` is a one-dimensional tensor with elements :math:`{y_0, y_1, ..., y_n}`, +the default computation is + +.. math:: + \begin{aligned} + \sum_{i = 1}^{n} \frac{1}{2} (y_i + y_{i-1}) + \end{aligned} + +When :attr:`dx` is specified the computation becomes + +.. math:: + \begin{aligned} + \sum_{i = 1}^{n} \frac{\Delta x}{2} (y_i + y_{i-1}) + \end{aligned} + +effectively multiplying the result by :attr:`dx`. When :attr:`x` is specified, +assuming :attr:`x` is also a one-dimensional tensor with +elements :math:`{x_0, x_1, ..., x_n}`, the computation becomes + +.. math:: + \begin{aligned} + \sum_{i = 1}^{n} \frac{(x_i - x_{i-1})}{2} (y_i + y_{i-1}) + \end{aligned} + +When :attr:`x` and :attr:`y` have the same size, the computation is as described above and no broadcasting is needed. +The broadcasting behavior of this function is as follows when their sizes are different. For both :attr:`x` +and :attr:`y`, the function computes the difference between consecutive elements along +dimension :attr:`dim`. This effectively creates two tensors, `x_diff` and `y_diff`, that have +the same shape as the original tensors except their lengths along the dimension :attr:`dim` is reduced by 1. +After that, those two tensors are broadcast together to compute final output as part of the trapezoidal rule. +See the examples below for details. + +.. note:: + The trapezoidal rule is a technique for approximating the definite integral of a function + by averaging its left and right Riemann sums. The approximation becomes more accurate as + the resolution of the partition increases. + +Arguments: + y (Tensor): Values to use when computing the trapezoidal rule. + x (Tensor): If specified, defines spacing between values as specified above. + +Keyword arguments: + dx (float): constant spacing between values. If neither :attr:`x` or :attr:`dx` + are specified then this defaults to 1. Effectively multiplies the result by its value. + dim (int): The dimension along which to compute the trapezoidal rule. + The last (inner-most) dimension by default. + +Examples:: + + >>> # Computes the trapezoidal rule in 1D, spacing is implicitly 1 + >>> y = torch.tensor([1, 5, 10]) + >>> torch.trapezoid(y) + tensor(10.5) + + >>> # Computes the same trapezoidal rule directly to verify + >>> (1 + 10 + 10) / 2 + 10.5 + + >>> # Computes the trapezoidal rule in 1D with constant spacing of 2 + >>> # NOTE: the result is the same as before, but multiplied by 2 + >>> torch.trapezoid(y, dx=2) + 21.0 + + >>> # Computes the trapezoidal rule in 1D with arbitrary spacing + >>> x = torch.tensor([1, 3, 6]) + >>> torch.trapezoid(y, x) + 28.5 + + >>> # Computes the same trapezoidal rule directly to verify + >>> ((3 - 1) * (1 + 5) + (6 - 3) * (5 + 10)) / 2 + 28.5 + + >>> # Computes the trapezoidal rule for each row of a 3x3 matrix + >>> y = torch.arange(9).reshape(3, 3) + tensor([[0, 1, 2], + [3, 4, 5], + [6, 7, 8]]) + >>> torch.trapezoid(y) + tensor([ 2., 8., 14.]) + + >>> # Computes the trapezoidal rule for each column of the matrix + >>> torch.trapezoid(y, dim=0) + tensor([ 6., 8., 10.]) + + >>> # Computes the trapezoidal rule for each row of a 3x3 ones matrix + >>> # with the same arbitrary spacing + >>> y = torch.ones(3, 3) + >>> x = torch.tensor([1, 3, 6]) + >>> torch.trapezoid(y, x) + array([5., 5., 5.]) + + >>> # Computes the trapezoidal rule for each row of a 3x3 ones matrix + >>> # with different arbitrary spacing per row + >>> y = torch.ones(3, 3) + >>> x = torch.tensor([[1, 2, 3], [1, 3, 5], [1, 4, 7]]) + >>> torch.trapezoid(y, x) + array([2., 4., 6.]) +""", +) + +add_docstr( + torch.trapz, + r""" +trapz(y, x, *, dim=-1) -> Tensor + +Alias for :func:`torch.trapezoid`. +""", +) + +add_docstr( + torch.cumulative_trapezoid, + r""" +cumulative_trapezoid(y, x=None, *, dx=None, dim=-1) -> Tensor + +Cumulatively computes the `trapezoidal rule `_ +along :attr:`dim`. By default the spacing between elements is assumed to be 1, but +:attr:`dx` can be used to specify a different constant spacing, and :attr:`x` can be +used to specify arbitrary spacing along :attr:`dim`. + +For more details, please read :func:`torch.trapezoid`. The difference between :func:`torch.trapezoid` +and this function is that, :func:`torch.trapezoid` returns a value for each integration, +where as this function returns a cumulative value for every spacing within the integration. This +is analogous to how `.sum` returns a value and `.cumsum` returns a cumulative sum. + +Arguments: + y (Tensor): Values to use when computing the trapezoidal rule. + x (Tensor): If specified, defines spacing between values as specified above. + +Keyword arguments: + dx (float): constant spacing between values. If neither :attr:`x` or :attr:`dx` + are specified then this defaults to 1. Effectively multiplies the result by its value. + dim (int): The dimension along which to compute the trapezoidal rule. + The last (inner-most) dimension by default. + +Examples:: + + >>> # Cumulatively computes the trapezoidal rule in 1D, spacing is implicitly 1. + >>> y = torch.tensor([1, 5, 10]) + >>> torch.cumulative_trapezoid(y) + tensor([3., 10.5]) + + >>> # Computes the same trapezoidal rule directly up to each element to verify + >>> (1 + 5) / 2 + 3.0 + >>> (1 + 10 + 10) / 2 + 10.5 + + >>> # Cumulatively computes the trapezoidal rule in 1D with constant spacing of 2 + >>> # NOTE: the result is the same as before, but multiplied by 2 + >>> torch.cumulative_trapezoid(y, dx=2) + tensor([6., 21.]) + + >>> # Cumulatively computes the trapezoidal rule in 1D with arbitrary spacing + >>> x = torch.tensor([1, 3, 6]) + >>> torch.cumulative_trapezoid(y, x) + tensor([6., 28.5]) + + >>> # Computes the same trapezoidal rule directly up to each element to verify + >>> ((3 - 1) * (1 + 5)) / 2 + 6.0 + >>> ((3 - 1) * (1 + 5) + (6 - 3) * (5 + 10)) / 2 + 28.5 + + >>> # Cumulatively computes the trapezoidal rule for each row of a 3x3 matrix + >>> y = torch.arange(9).reshape(3, 3) + tensor([[0, 1, 2], + [3, 4, 5], + [6, 7, 8]]) + >>> torch.cumulative_trapezoid(y) + tensor([[ 0.5, 2.], + [ 3.5, 8.], + [ 6.5, 14.]]) + + >>> # Cumulatively computes the trapezoidal rule for each column of the matrix + >>> torch.cumulative_trapezoid(y, dim=0) + tensor([[ 1.5, 2.5, 3.5], + [ 6.0, 8.0, 10.0]]) + + >>> # Cumulatively computes the trapezoidal rule for each row of a 3x3 ones matrix + >>> # with the same arbitrary spacing + >>> y = torch.ones(3, 3) + >>> x = torch.tensor([1, 3, 6]) + >>> torch.cumulative_trapezoid(y, x) + tensor([[2., 5.], + [2., 5.], + [2., 5.]]) + + >>> # Cumulatively computes the trapezoidal rule for each row of a 3x3 ones matrix + >>> # with different arbitrary spacing per row + >>> y = torch.ones(3, 3) + >>> x = torch.tensor([[1, 2, 3], [1, 3, 5], [1, 4, 7]]) + >>> torch.cumulative_trapezoid(y, x) + tensor([[1., 2.], + [2., 4.], + [3., 6.]]) +""", +) + +add_docstr( + torch.repeat_interleave, + r""" +repeat_interleave(input, repeats, dim=None, *, output_size=None) -> Tensor + +Repeat elements of a tensor. + +.. warning:: + + This is different from :meth:`torch.Tensor.repeat` but similar to ``numpy.repeat``. + +Args: + {input} + repeats (Tensor or int): The number of repetitions for each element. + repeats is broadcasted to fit the shape of the given axis. + dim (int, optional): The dimension along which to repeat values. + By default, use the flattened input array, and return a flat output + array. + +Keyword args: + output_size (int, optional): Total output size for the given axis + ( e.g. sum of repeats). If given, it will avoid stream synchronization + needed to calculate output shape of the tensor. + +Returns: + Tensor: Repeated tensor which has the same shape as input, except along the given axis. + +Example:: + + >>> x = torch.tensor([1, 2, 3]) + >>> x.repeat_interleave(2) + tensor([1, 1, 2, 2, 3, 3]) + >>> y = torch.tensor([[1, 2], [3, 4]]) + >>> torch.repeat_interleave(y, 2) + tensor([1, 1, 2, 2, 3, 3, 4, 4]) + >>> torch.repeat_interleave(y, 3, dim=1) + tensor([[1, 1, 1, 2, 2, 2], + [3, 3, 3, 4, 4, 4]]) + >>> torch.repeat_interleave(y, torch.tensor([1, 2]), dim=0) + tensor([[1, 2], + [3, 4], + [3, 4]]) + >>> torch.repeat_interleave(y, torch.tensor([1, 2]), dim=0, output_size=3) + tensor([[1, 2], + [3, 4], + [3, 4]]) + +If the `repeats` is `tensor([n1, n2, n3, ...])`, then the output will be +`tensor([0, 0, ..., 1, 1, ..., 2, 2, ..., ...])` where `0` appears `n1` times, +`1` appears `n2` times, `2` appears `n3` times, etc. + +.. function:: repeat_interleave(repeats, *) -> Tensor + :noindex: + +Repeats 0 repeats[0] times, 1 repeats[1] times, 2 repeats[2] times, etc. + +Args: + repeats (Tensor): The number of repetitions for each element. + +Returns: + Tensor: Repeated tensor of size `sum(repeats)`. + +Example:: + + >>> torch.repeat_interleave(torch.tensor([1, 2, 3])) + tensor([0, 1, 1, 2, 2, 2]) + +""".format(**common_args), +) + +add_docstr( + torch.tile, + r""" +tile(input, dims) -> Tensor + +Constructs a tensor by repeating the elements of :attr:`input`. +The :attr:`dims` argument specifies the number of repetitions +in each dimension. + +If :attr:`dims` specifies fewer dimensions than :attr:`input` has, then +ones are prepended to :attr:`dims` until all dimensions are specified. +For example, if :attr:`input` has shape (8, 6, 4, 2) and :attr:`dims` +is (2, 2), then :attr:`dims` is treated as (1, 1, 2, 2). + +Analogously, if :attr:`input` has fewer dimensions than :attr:`dims` +specifies, then :attr:`input` is treated as if it were unsqueezed at +dimension zero until it has as many dimensions as :attr:`dims` specifies. +For example, if :attr:`input` has shape (4, 2) and :attr:`dims` +is (3, 3, 2, 2), then :attr:`input` is treated as if it had the +shape (1, 1, 4, 2). + +.. note:: + + This function is similar to NumPy's tile function. + +Args: + input (Tensor): the tensor whose elements to repeat. + dims (tuple): the number of repetitions per dimension. + +Example:: + + >>> x = torch.tensor([1, 2, 3]) + >>> x.tile((2,)) + tensor([1, 2, 3, 1, 2, 3]) + >>> y = torch.tensor([[1, 2], [3, 4]]) + >>> torch.tile(y, (2, 2)) + tensor([[1, 2, 1, 2], + [3, 4, 3, 4], + [1, 2, 1, 2], + [3, 4, 3, 4]]) +""", +) + +add_docstr( + torch.quantize_per_tensor, + r""" +quantize_per_tensor(input, scale, zero_point, dtype) -> Tensor + +Converts a float tensor to a quantized tensor with given scale and zero point. + +Arguments: + input (Tensor): float tensor or list of tensors to quantize + scale (float or Tensor): scale to apply in quantization formula + zero_point (int or Tensor): offset in integer value that maps to float zero + dtype (:class:`torch.dtype`): the desired data type of returned tensor. + Has to be one of the quantized dtypes: ``torch.quint8``, ``torch.qint8``, ``torch.qint32`` + +Returns: + Tensor: A newly quantized tensor or list of quantized tensors. + +Example:: + + >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), 0.1, 10, torch.quint8) + tensor([-1., 0., 1., 2.], size=(4,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.1, zero_point=10) + >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), 0.1, 10, torch.quint8).int_repr() + tensor([ 0, 10, 20, 30], dtype=torch.uint8) + >>> torch.quantize_per_tensor([torch.tensor([-1.0, 0.0]), torch.tensor([-2.0, 2.0])], + >>> torch.tensor([0.1, 0.2]), torch.tensor([10, 20]), torch.quint8) + (tensor([-1., 0.], size=(2,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.1, zero_point=10), + tensor([-2., 2.], size=(2,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.2, zero_point=20)) + >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), torch.tensor(0.1), torch.tensor(10), torch.quint8) + tensor([-1., 0., 1., 2.], size=(4,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.10, zero_point=10) +""", +) + +add_docstr( + torch.quantize_per_tensor_dynamic, + r""" +quantize_per_tensor_dynamic(input, dtype, reduce_range) -> Tensor + +Converts a float tensor to a quantized tensor with scale and zero_point calculated +dynamically based on the input. + +Arguments: + input (Tensor): float tensor or list of tensors to quantize + dtype (:class:`torch.dtype`): the desired data type of returned tensor. + Has to be one of the quantized dtypes: ``torch.quint8``, ``torch.qint8`` + reduce_range (bool): a flag to indicate whether to reduce the range of quantized + data by 1 bit, it's required to avoid instruction overflow for some hardwares + +Returns: + Tensor: A newly (dynamically) quantized tensor + +Example:: + + >>> t = torch.quantize_per_tensor_dynamic(torch.tensor([-1.0, 0.0, 1.0, 2.0]), torch.quint8, False) + >>> print(t) + tensor([-1., 0., 1., 2.], size=(4,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.011764705882352941, + zero_point=85) + >>> t.int_repr() + tensor([ 0, 85, 170, 255], dtype=torch.uint8) +""", +) + +add_docstr( + torch.quantize_per_channel, + r""" +quantize_per_channel(input, scales, zero_points, axis, dtype) -> Tensor + +Converts a float tensor to a per-channel quantized tensor with given scales and zero points. + +Arguments: + input (Tensor): float tensor to quantize + scales (Tensor): float 1D tensor of scales to use, size should match ``input.size(axis)`` + zero_points (int): integer 1D tensor of offset to use, size should match ``input.size(axis)`` + axis (int): dimension on which apply per-channel quantization + dtype (:class:`torch.dtype`): the desired data type of returned tensor. + Has to be one of the quantized dtypes: ``torch.quint8``, ``torch.qint8``, ``torch.qint32`` + +Returns: + Tensor: A newly quantized tensor + +Example:: + + >>> x = torch.tensor([[-1.0, 0.0], [1.0, 2.0]]) + >>> torch.quantize_per_channel(x, torch.tensor([0.1, 0.01]), torch.tensor([10, 0]), 0, torch.quint8) + tensor([[-1., 0.], + [ 1., 2.]], size=(2, 2), dtype=torch.quint8, + quantization_scheme=torch.per_channel_affine, + scale=tensor([0.1000, 0.0100], dtype=torch.float64), + zero_point=tensor([10, 0]), axis=0) + >>> torch.quantize_per_channel(x, torch.tensor([0.1, 0.01]), torch.tensor([10, 0]), 0, torch.quint8).int_repr() + tensor([[ 0, 10], + [100, 200]], dtype=torch.uint8) +""", +) + + +add_docstr( + torch.quantized_batch_norm, + r""" +quantized_batch_norm(input, weight=None, bias=None, mean, var, eps, output_scale, output_zero_point) -> Tensor + +Applies batch normalization on a 4D (NCHW) quantized tensor. + +.. math:: + + y = \frac{x - \mathrm{E}[x]}{\sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta + +Arguments: + input (Tensor): quantized tensor + weight (Tensor): float tensor that corresponds to the gamma, size C + bias (Tensor): float tensor that corresponds to the beta, size C + mean (Tensor): float mean value in batch normalization, size C + var (Tensor): float tensor for variance, size C + eps (float): a value added to the denominator for numerical stability. + output_scale (float): output quantized tensor scale + output_zero_point (int): output quantized tensor zero_point + +Returns: + Tensor: A quantized tensor with batch normalization applied. + +Example:: + + >>> qx = torch.quantize_per_tensor(torch.rand(2, 2, 2, 2), 1.5, 3, torch.quint8) + >>> torch.quantized_batch_norm(qx, torch.ones(2), torch.zeros(2), torch.rand(2), torch.rand(2), 0.00001, 0.2, 2) + tensor([[[[-0.2000, -0.2000], + [ 1.6000, -0.2000]], + + [[-0.4000, -0.4000], + [-0.4000, 0.6000]]], + + + [[[-0.2000, -0.2000], + [-0.2000, -0.2000]], + + [[ 0.6000, -0.4000], + [ 0.6000, -0.4000]]]], size=(2, 2, 2, 2), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.2, zero_point=2) +""", +) + + +add_docstr( + torch.quantized_max_pool1d, + r""" +quantized_max_pool1d(input, kernel_size, stride=[], padding=0, dilation=1, ceil_mode=False) -> Tensor + +Applies a 1D max pooling over an input quantized tensor composed of several input planes. + +Arguments: + input (Tensor): quantized tensor + kernel_size (list of int): the size of the sliding window + stride (``list of int``, optional): the stride of the sliding window + padding (``list of int``, optional): padding to be added on both sides, must be >= 0 and <= kernel_size / 2 + dilation (``list of int``, optional): The stride between elements within a sliding window, must be > 0. Default 1 + ceil_mode (bool, optional): If True, will use ceil instead of floor to compute the output shape. + Defaults to False. + + +Returns: + Tensor: A quantized tensor with max_pool1d applied. + +Example:: + + >>> qx = torch.quantize_per_tensor(torch.rand(2, 2), 1.5, 3, torch.quint8) + >>> torch.quantized_max_pool1d(qx, [2]) + tensor([[0.0000], + [1.5000]], size=(2, 1), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=1.5, zero_point=3) +""", +) + + +add_docstr( + torch.quantized_max_pool2d, + r""" +quantized_max_pool2d(input, kernel_size, stride=[], padding=0, dilation=1, ceil_mode=False) -> Tensor + +Applies a 2D max pooling over an input quantized tensor composed of several input planes. + +Arguments: + input (Tensor): quantized tensor + kernel_size (``list of int``): the size of the sliding window + stride (``list of int``, optional): the stride of the sliding window + padding (``list of int``, optional): padding to be added on both sides, must be >= 0 and <= kernel_size / 2 + dilation (``list of int``, optional): The stride between elements within a sliding window, must be > 0. Default 1 + ceil_mode (bool, optional): If True, will use ceil instead of floor to compute the output shape. + Defaults to False. + + +Returns: + Tensor: A quantized tensor with max_pool2d applied. + +Example:: + + >>> qx = torch.quantize_per_tensor(torch.rand(2, 2, 2, 2), 1.5, 3, torch.quint8) + >>> torch.quantized_max_pool2d(qx, [2,2]) + tensor([[[[1.5000]], + + [[1.5000]]], + + + [[[0.0000]], + + [[0.0000]]]], size=(2, 2, 1, 1), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=1.5, zero_point=3) +""", +) + + +add_docstr( + torch.Stream, + r""" +Stream(device, *, priority) -> Stream + +An in-order queue of executing the respective tasks asynchronously in first in first out (FIFO) order. +It can control or synchronize the execution of other Stream or block the current host thread to ensure +the correct task sequencing. It supports with statement as a context manager to ensure the operators +within the with block are running on the corresponding stream. + +See in-depth description of the CUDA behavior at :ref:`cuda-semantics` for details +on the exact semantic that applies to all devices. + +Arguments: + device (:class:`torch.device`, optional): the desired device for the Stream. + If not given, the current :ref:`accelerator` type will be used. + priority (int, optional): priority of the stream, should be 0 or negative, where negative + numbers indicate higher priority. By default, streams have priority 0. + +Returns: + Stream: An torch.Stream object. + +Example:: + + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA) + >>> with torch.Stream(device='cuda') as s_cuda: + >>> a = torch.randn(10, 5, device='cuda') + >>> b = torch.randn(5, 10, device='cuda') + >>> c = torch.mm(a, b) +""", +) + + +add_docstr( + torch.Stream.query, + r""" +Stream.query() -> bool + +Check if all the work submitted has been completed. + +Returns: + bool: A boolean indicating if all kernels in this stream are completed. + +Example:: + + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA) + >>> s_cuda = torch.Stream(device='cuda') + >>> s_cuda.query() + True +""", +) + + +add_docstr( + torch.Stream.record_event, + r""" +Stream.record_event(event) -> Event + +Record an event. En-queuing it into the Stream to allow further synchronization from the current point in the FIFO queue. + +Arguments: + event (:class:`torch.Event`, optional): event to record. If not given, a new one will be allocated. + +Returns: + Event: Recorded event. + +Example:: + + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA) + >>> s_cuda = torch.Stream(device='cuda') + >>> e_cuda = s_cuda.record_event() +""", +) + + +add_docstr( + torch.Stream.synchronize, + r""" +Stream.synchronize() -> None + +Wait for all the kernels in this stream to complete. + +Example:: + + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA) + >>> s_cuda = torch.Stream(device='cuda') + >>> s_cuda.synchronize() +""", +) + + +add_docstr( + torch.Stream.wait_event, + r""" +Stream.wait_event(event) -> None + +Make all future work submitted to the stream wait for an event. + +Arguments: + event (:class:`torch.Event`): an event to wait for. + +Example:: + + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA) + >>> s1_cuda = torch.Stream(device='cuda') + >>> s2_cuda = torch.Stream(device='cuda') + >>> e_cuda = s1_cuda.record_event() + >>> s2_cuda.wait_event(e_cuda) +""", +) + + +add_docstr( + torch.Stream.wait_stream, + r""" +Stream.wait_stream(stream) -> None + +Synchronize with another stream. All future work submitted to this stream will wait until all kernels +already submitted to the given stream are completed. + +Arguments: + stream (:class:`torch.Stream`): a stream to synchronize. + +Example:: + + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA) + >>> s1_cuda = torch.Stream(device='cuda') + >>> s2_cuda = torch.Stream(device='cuda') + >>> s2_cuda.wait_stream(s1_cuda) +""", +) + + +add_docstr( + torch.Event, + r""" +Event(device=None, *, enable_timing=False, blocking=False, interprocess=False) + +Query and record Stream status to identify or control dependencies across Stream and measure timing. + +Arguments: + device (:class:`torch.device`, optional): the desired device for the Event. + If not given, the current :ref:`accelerator` type will be used. + enable_timing (bool, optional): indicates if the event should measure time (default: ``False``) + blocking (bool, optional): if ``True``, :meth:`wait` will be blocking (default: ``False``) + interprocess (bool): if ``True``, the event can be shared between processes (default: ``False``) + +.. warning:: + + Both blocking and interprocess are not supported right now and are noops. + +Returns: + Event: An torch.Event object. + +Example:: + + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA) + >>> event = torch.Event() + >>> e_cuda = torch.Event(device='cuda') +""", +) + + +add_docstr( + torch.Event.elapsed_time, + r""" +Event.elapsed_time(end_event) -> float + +Returns the elapsed time in milliseconds between when this event and the :attr:`end_event` are +each recorded via :func:`torch.Stream.record_event`. + +Arguments: + end_event (:class:`torch.Event`): The ending event has been recorded. + +Returns: + float: Time between starting and ending event in milliseconds. + +Example:: + + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA) + >>> s_cuda = torch.Stream(device='cuda') + >>> e1_cuda = s_cuda.record_event() + >>> e2_cuda = s_cuda.record_event() + >>> ms = e1_cuda.elapsed_time(e2_cuda) +""", +) + + +add_docstr( + torch.Event.query, + r""" +Event.query() -> bool + +Check if the stream where this event was recorded already moved past the point where the event was recorded. +Always returns ``True`` if the Event was not recorded. + +Returns: + bool: A boolean indicating if all work currently captured by event has completed. + +Example:: + + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA) + >>> s_cuda = torch.Stream(device='cuda') + >>> e_cuda = s_cuda.record_event() + >>> e_cuda.query() + True +""", +) + + +add_docstr( + torch.Event.record, + r""" +Event.record(stream=None) -> None + +Record the event in a given stream. The stream's device must match the event's device. +This function is equivalent to ``stream.record_event(self)``. + +Arguments: + stream (:class:`torch.Stream`, optional): A stream to be recorded. + If not given, the current stream will be used. + +Example:: + + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA) + >>> e_cuda = torch.Event(device='cuda') + >>> e_cuda.record() +""", +) + + +add_docstr( + torch.Event.synchronize, + r""" +Event.synchronize() -> None + +Wait for the event to complete. This prevents the CPU thread from proceeding until the event completes. + +Example:: + + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA) + >>> s_cuda = torch.Stream(device='cuda') + >>> e_cuda = s_cuda.record_event() + >>> e_cuda.synchronize() +""", +) + + +add_docstr( + torch.Event.wait, + r""" +Event.wait(stream=None) -> None + +Make all future work submitted to the given stream wait for this event. + +Arguments: + stream (:class:`torch.Stream`, optional): A stream to synchronize. + If not given, the current stream will be used. + +Example:: + + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA) + >>> s1_cuda = torch.Stream(device='cuda') + >>> s2_cuda = torch.Stream(device='cuda') + >>> e_cuda = s1_cuda.record() + >>> e_cuda.wait(s2) +""", +) + + +add_docstr( + torch.Generator, + r""" +Generator(device='cpu') -> Generator + +Creates and returns a generator object that manages the state of the algorithm which +produces pseudo random numbers. Used as a keyword argument in many :ref:`inplace-random-sampling` +functions. + +Arguments: + device (:class:`torch.device`, optional): the desired device for the generator. + +Returns: + Generator: An torch.Generator object. + +Example:: + + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA) + >>> g_cpu = torch.Generator() + >>> g_cuda = torch.Generator(device='cuda') +""", +) + + +add_docstr( + torch.Generator.set_state, + r""" +Generator.set_state(new_state) -> void + +Sets the Generator state. + +Arguments: + new_state (torch.ByteTensor): The desired state. + +Example:: + + >>> g_cpu = torch.Generator() + >>> g_cpu_other = torch.Generator() + >>> g_cpu.set_state(g_cpu_other.get_state()) +""", +) + + +add_docstr( + torch.Generator.get_state, + r""" +Generator.get_state() -> Tensor + +Returns the Generator state as a ``torch.ByteTensor``. + +Returns: + Tensor: A ``torch.ByteTensor`` which contains all the necessary bits + to restore a Generator to a specific point in time. + +Example:: + + >>> g_cpu = torch.Generator() + >>> g_cpu.get_state() +""", +) + +add_docstr( + torch.Generator.graphsafe_set_state, + r""" +Generator.graphsafe_set_state(state) -> None + +Sets the state of the generator to the specified state in a manner that is safe for use in graph capture. +This method is crucial for ensuring that the generator's state can be captured in the CUDA graph. + +Arguments: + state (torch.Generator): A Generator point to the new state for the generator, typically obtained from `graphsafe_get_state`. + +Example: + >>> g_cuda = torch.Generator(device='cuda') + >>> g_cuda_other = torch.Generator(device='cuda') + >>> current_state = g_cuda_other.graphsafe_get_state() + >>> g_cuda.graphsafe_set_state(current_state) +""", +) + +add_docstr( + torch.Generator.graphsafe_get_state, + r""" +Generator.graphsafe_get_state() -> torch.Generator + +Retrieves the current state of the generator in a manner that is safe for graph capture. +This method is crucial for ensuring that the generator's state can be captured in the CUDA graph. + +Returns: + torch.Generator: A Generator point to the current state of the generator + +Example: + >>> g_cuda = torch.Generator(device='cuda') + >>> current_state = g_cuda.graphsafe_get_state() +""", +) + +add_docstr( + torch.Generator.clone_state, + r""" +Generator.clone_state() -> torch.Generator + +Clones the current state of the generator and returns a new generator pointing to this cloned state. +This method is beneficial for preserving a particular state of a generator to restore at a later point. + +Returns: + torch.Generator: A Generator pointing to the newly cloned state. + +Example: + >>> g_cuda = torch.Generator(device='cuda') + >>> cloned_state = g_cuda.clone_state() +""", +) + +add_docstr( + torch.Generator.manual_seed, + r""" +Generator.manual_seed(seed) -> Generator + +Sets the seed for generating random numbers. Returns a `torch.Generator` object. Any 32-bit integer is a valid seed. + +Arguments: + seed (int): The desired seed. Value must be within the inclusive range + `[-0x8000_0000_0000_0000, 0xffff_ffff_ffff_ffff]`. Otherwise, a RuntimeError + is raised. Negative inputs are remapped to positive values with the formula + `0xffff_ffff_ffff_ffff + seed`. + +Returns: + Generator: An torch.Generator object. + +Example:: + + >>> g_cpu = torch.Generator() + >>> g_cpu.manual_seed(2147483647) +""", +) + + +add_docstr( + torch.Generator.initial_seed, + r""" +Generator.initial_seed() -> int + +Returns the initial seed for generating random numbers. + +Example:: + + >>> g_cpu = torch.Generator() + >>> g_cpu.initial_seed() + 2147483647 +""", +) + + +add_docstr( + torch.Generator.seed, + r""" +Generator.seed() -> int + +Gets a non-deterministic random number from std::random_device or the current +time and uses it to seed a Generator. + +Example:: + + >>> g_cpu = torch.Generator() + >>> g_cpu.seed() + 1516516984916 +""", +) + + +add_docstr( + torch.Generator.device, + r""" +Generator.device -> device + +Gets the current device of the generator. + +Example:: + + >>> g_cpu = torch.Generator() + >>> g_cpu.device + device(type='cpu') +""", +) + +add_docstr( + torch._assert_async, + r""" +_assert_async(tensor) -> void + +Asynchronously assert that the contents of tensor are nonzero. For CPU tensors, +this is equivalent to ``assert tensor`` or ``assert tensor.is_nonzero()``; for +CUDA tensors, we DO NOT synchronize and you may only find out the assertion +failed at a later CUDA kernel launch. Asynchronous assertion can be helpful for +testing invariants in CUDA tensors without giving up performance. This function +is NOT intended to be used for regular error checking, as it will trash your CUDA +context if the assert fails (forcing you to restart your PyTorch process.) + +Args: + tensor (Tensor): a one element tensor to test to see if it is nonzero. Zero + elements (including False for boolean tensors) cause an assertion failure + to be raised. +""", +) + +add_docstr( + torch.searchsorted, + r""" +searchsorted(sorted_sequence, values, *, out_int32=False, right=False, side=None, out=None, sorter=None) -> Tensor + +Find the indices from the *innermost* dimension of :attr:`sorted_sequence` such that, if the +corresponding values in :attr:`values` were inserted before the indices, when sorted, the order +of the corresponding *innermost* dimension within :attr:`sorted_sequence` would be preserved. +Return a new tensor with the same size as :attr:`values`. More formally, +the returned index satisfies the following rules: + +.. list-table:: + :widths: 12 10 78 + :header-rows: 1 + + * - :attr:`sorted_sequence` + - :attr:`right` + - *returned index satisfies* + * - 1-D + - False + - ``sorted_sequence[i-1] < values[m][n]...[l][x] <= sorted_sequence[i]`` + * - 1-D + - True + - ``sorted_sequence[i-1] <= values[m][n]...[l][x] < sorted_sequence[i]`` + * - N-D + - False + - ``sorted_sequence[m][n]...[l][i-1] < values[m][n]...[l][x] <= sorted_sequence[m][n]...[l][i]`` + * - N-D + - True + - ``sorted_sequence[m][n]...[l][i-1] <= values[m][n]...[l][x] < sorted_sequence[m][n]...[l][i]`` + +Args: + sorted_sequence (Tensor): N-D or 1-D tensor, containing monotonically increasing sequence on the *innermost* + dimension unless :attr:`sorter` is provided, in which case the sequence does not + need to be sorted + values (Tensor or Scalar): N-D tensor or a Scalar containing the search value(s). + +Keyword args: + out_int32 (bool, optional): indicate the output data type. torch.int32 if True, torch.int64 otherwise. + Default value is False, i.e. default output data type is torch.int64. + right (bool, optional): if False, return the first suitable location that is found. If True, return the + last such index. If no suitable index found, return 0 for non-numerical value + (eg. nan, inf) or the size of *innermost* dimension within :attr:`sorted_sequence` + (one pass the last index of the *innermost* dimension). In other words, if False, + gets the lower bound index for each value in :attr:`values` on the corresponding + *innermost* dimension of the :attr:`sorted_sequence`. If True, gets the upper + bound index instead. Default value is False. :attr:`side` does the same and is + preferred. It will error if :attr:`side` is set to "left" while this is True. + side (str, optional): the same as :attr:`right` but preferred. "left" corresponds to False for :attr:`right` + and "right" corresponds to True for :attr:`right`. It will error if this is set to + "left" while :attr:`right` is True. Default value is None. + out (Tensor, optional): the output tensor, must be the same size as :attr:`values` if provided. + sorter (LongTensor, optional): if provided, a tensor matching the shape of the unsorted + :attr:`sorted_sequence` containing a sequence of indices that sort it in the + ascending order on the innermost dimension + + +Example:: + + >>> sorted_sequence = torch.tensor([[1, 3, 5, 7, 9], [2, 4, 6, 8, 10]]) + >>> sorted_sequence + tensor([[ 1, 3, 5, 7, 9], + [ 2, 4, 6, 8, 10]]) + >>> values = torch.tensor([[3, 6, 9], [3, 6, 9]]) + >>> values + tensor([[3, 6, 9], + [3, 6, 9]]) + >>> torch.searchsorted(sorted_sequence, values) + tensor([[1, 3, 4], + [1, 2, 4]]) + >>> torch.searchsorted(sorted_sequence, values, side='right') + tensor([[2, 3, 5], + [1, 3, 4]]) + + >>> sorted_sequence_1d = torch.tensor([1, 3, 5, 7, 9]) + >>> sorted_sequence_1d + tensor([1, 3, 5, 7, 9]) + >>> torch.searchsorted(sorted_sequence_1d, values) + tensor([[1, 3, 4], + [1, 3, 4]]) +""", +) + +add_docstr( + torch.bucketize, + r""" +bucketize(input, boundaries, *, out_int32=False, right=False, out=None) -> Tensor + +Returns the indices of the buckets to which each value in the :attr:`input` belongs, where the +boundaries of the buckets are set by :attr:`boundaries`. Return a new tensor with the same size +as :attr:`input`. If :attr:`right` is False (default), then the left boundary is open. Note that +this behavior is opposite the behavior of +`numpy.digitize `_. +More formally, the returned index satisfies the following rules: + +.. list-table:: + :widths: 15 85 + :header-rows: 1 + + * - :attr:`right` + - *returned index satisfies* + * - False + - ``boundaries[i-1] < input[m][n]...[l][x] <= boundaries[i]`` + * - True + - ``boundaries[i-1] <= input[m][n]...[l][x] < boundaries[i]`` + +Args: + input (Tensor or Scalar): N-D tensor or a Scalar containing the search value(s). + boundaries (Tensor): 1-D tensor, must contain a strictly increasing sequence, or the return value is undefined. + +Keyword args: + out_int32 (bool, optional): indicate the output data type. torch.int32 if True, torch.int64 otherwise. + Default value is False, i.e. default output data type is torch.int64. + right (bool, optional): determines the behavior for values in :attr:`boundaries`. See the table above. + out (Tensor, optional): the output tensor, must be the same size as :attr:`input` if provided. + + +Example:: + + >>> boundaries = torch.tensor([1, 3, 5, 7, 9]) + >>> boundaries + tensor([1, 3, 5, 7, 9]) + >>> v = torch.tensor([[3, 6, 9], [3, 6, 9]]) + >>> v + tensor([[3, 6, 9], + [3, 6, 9]]) + >>> torch.bucketize(v, boundaries) + tensor([[1, 3, 4], + [1, 3, 4]]) + >>> torch.bucketize(v, boundaries, right=True) + tensor([[2, 3, 5], + [2, 3, 5]]) +""", +) + +add_docstr( + torch.view_as_real_copy, + r""" +Performs the same operation as :func:`torch.view_as_real`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.view_as_complex_copy, + r""" +Performs the same operation as :func:`torch.view_as_complex`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.as_strided_copy, + r""" +Performs the same operation as :func:`torch.as_strided`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.diagonal_copy, + r""" +Performs the same operation as :func:`torch.diagonal`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.expand_copy, + r""" +Performs the same operation as :func:`torch.Tensor.expand`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.permute_copy, + r""" +Performs the same operation as :func:`torch.permute`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.select_copy, + r""" +Performs the same operation as :func:`torch.select`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.detach_copy, + r""" +Performs the same operation as :func:`torch.detach`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.slice_copy, + r""" +Performs the same operation as :func:`torch.slice`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.split_copy, + r""" +Performs the same operation as :func:`torch.split`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.split_with_sizes_copy, + r""" +Performs the same operation as :func:`torch.split_with_sizes`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.squeeze_copy, + r""" +Performs the same operation as :func:`torch.squeeze`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.t_copy, + r""" +Performs the same operation as :func:`torch.t`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.transpose_copy, + r""" +Performs the same operation as :func:`torch.transpose`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.unsqueeze_copy, + r""" +Performs the same operation as :func:`torch.unsqueeze`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.indices_copy, + r""" +Performs the same operation as :func:`torch.indices`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.values_copy, + r""" +Performs the same operation as :func:`torch.values`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.crow_indices_copy, + r""" +Performs the same operation as :func:`torch.crow_indices`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.col_indices_copy, + r""" +Performs the same operation as :func:`torch.col_indices`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.unbind_copy, + r""" +Performs the same operation as :func:`torch.unbind`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.view_copy, + r""" +Performs the same operation as :func:`torch.view`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.unfold_copy, + r""" +Performs the same operation as :func:`torch.unfold`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.alias_copy, + r""" +Performs the same operation as :func:`torch.alias`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +for unary_base_func_name in ( + "exp", + "sqrt", + "abs", + "acos", + "asin", + "atan", + "ceil", + "cos", + "cosh", + "erf", + "erfc", + "expm1", + "floor", + "log", + "log10", + "log1p", + "log2", + "neg", + "tan", + "tanh", + "sin", + "sinh", + "round", + "lgamma", + "frac", + "reciprocal", + "sigmoid", + "trunc", + "zero", +): + unary_foreach_func_name = f"_foreach_{unary_base_func_name}" + if hasattr(torch, unary_foreach_func_name): + add_docstr( + getattr(torch, unary_foreach_func_name), + rf""" +{unary_foreach_func_name}(self: List[Tensor]) -> List[Tensor] + +Apply :func:`torch.{unary_base_func_name}` to each Tensor of the input list. + """, + ) + unary_inplace_foreach_func_name = f"{unary_foreach_func_name}_" + if hasattr(torch, unary_inplace_foreach_func_name): + add_docstr( + getattr(torch, unary_inplace_foreach_func_name), + rf""" +{unary_inplace_foreach_func_name}(self: List[Tensor]) -> None + +Apply :func:`torch.{unary_base_func_name}` to each Tensor of the input list. + """, + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..70641a7c534d7d7bf6f786761532d9328322a008 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_utils.py @@ -0,0 +1,1117 @@ +# mypy: allow-untyped-defs +import copyreg +import functools +import importlib +import logging +import sys +import traceback +import warnings +from collections import defaultdict +from collections.abc import Callable +from types import ModuleType +from typing import Any, Generic, TYPE_CHECKING +from typing_extensions import deprecated, ParamSpec + +import torch + + +def _type(self, dtype=None, non_blocking=False, **kwargs): + """Returns the type if `dtype` is not provided, else casts this object to + the specified type. + + If this is already of the correct type, no copy is performed and the + original object is returned. + + Args: + dtype (type or string): The desired type + non_blocking (bool): If ``True``, and the source is in pinned memory + and destination is on the GPU or vice versa, the copy is performed + asynchronously with respect to the host. Otherwise, the argument + has no effect. + **kwargs: For compatibility, may contain the key ``async`` in place of + the ``non_blocking`` argument. The ``async`` arg is deprecated. + """ + non_blocking = _get_async_or_non_blocking("type", non_blocking, kwargs) + if dtype is None: + return self.__module__ + "." + self.__class__.__name__ + + if isinstance(dtype, str): + dtype = _import_dotted_name(dtype) + if dtype is type(self): + return self + if self.is_sparse: + if not dtype.is_sparse: + raise RuntimeError("Cannot cast sparse tensor to dense tensor") + new_module_name = dtype.__module__.replace(".sparse", "") + new_values_type_name = new_module_name + "." + dtype.__name__ + new_values = torch.Tensor._values(self).type(new_values_type_name, non_blocking) + new_indices_type_name = new_module_name + ".LongTensor" + new_indices = torch.Tensor._indices(self).type( + new_indices_type_name, non_blocking + ) + return dtype(new_indices, new_values, self.size()) + if dtype.is_sparse: + raise RuntimeError("Cannot cast dense tensor to sparse tensor") + return dtype(self.size()).copy_(self, non_blocking) + + +def _to(self, device, non_blocking=False): + """Returns a copy of this object in device memory. + + If this object is already on the correct device, then no copy is performed + and the original object is returned. + + Args: + device (int): The destination device. + non_blocking (bool): If ``True`` and the source is in pinned memory, + the copy will be asynchronous with respect to the host. Otherwise, + the argument has no effect. + """ + if self.device == device: + return self + + if device.type == "cpu": + pin_memory = non_blocking and self.device.type in ( + "cuda", + torch._C._get_privateuse1_backend_name(), + ) + untyped_storage = torch.empty( + self.nbytes(), dtype=torch.uint8, device=device, pin_memory=pin_memory + ).untyped_storage() + untyped_storage.copy_(self, non_blocking) + return untyped_storage + + device_module = getattr(torch, device.type, None) + assert device_module is not None, ( + f"{device.type.upper()} device module is not loaded" + ) + with device_module.device(device): + if self.is_sparse and hasattr(device_module, "sparse"): + new_type = getattr(device_module.sparse, self.__class__.__name__) + indices = getattr(torch.Tensor._indices(self), device.type)( + device, non_blocking + ) + values = getattr(torch.Tensor._values(self), device.type)( + device, non_blocking + ) + return new_type(indices, values, self.size()) + else: + assert not self.is_sparse, ( + f"sparse storage is not supported for {device.type.upper()} tensors" + ) + untyped_storage = torch.UntypedStorage(self.size(), device=device) + untyped_storage.copy_(self, non_blocking) + return untyped_storage + + +def _get_async_or_non_blocking(function_name, non_blocking, kwargs): + """Return the non-blocking flag given the function name and kwargs. + + Args: + function_name (str): the name of the function being used. + non_blocking (bool): the default value. + **kwargs (dict): the kwargs passed to the function. + """ + if not kwargs: + return non_blocking + if len(kwargs) != 1 or "async" not in kwargs: + message = "{}() got an unexpected keyword argument '{}'" + argument = list(kwargs.keys()).pop() + raise TypeError(message.format(function_name, argument)) + warnings.warn("'async' is deprecated; use 'non_blocking'", stacklevel=2) + return kwargs["async"] + + +def _get_restore_location(device): + """Return the map_location location. + + Used for rebuild functions where the tensor device is distinct from the storage + """ + + map_location = torch.serialization._serialization_tls.map_location + if map_location is None: + return device + else: + if isinstance(map_location, dict): + return map_location.get(device, device) + elif isinstance(map_location, (str, torch.device)): + return map_location + else: + assert callable(map_location) + raise RuntimeError( + "Callable map_location not supported with _rebuild_wrapper_subclass " + "or _rebuild_device_tensor_from_numpy" + ) + + +# Note [Don't serialize hooks] +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# Since time immemorial, we have serialized the backward hooks associated with +# variables. This kind of half-worked--Python can pickle global functions +# (but not closures!)--but there were problems. +# +# - It's fragile. If you serialize a backward hook into a saved +# model, and then you rename the function associated with the hook, +# now your saved model is broken and you can't load it anymore. +# +# - It's not actually used. The standard recommendation is to +# serialize the *state_dict* of a model, not the model itself +# (since this is more stable to code changes affecting the model +# serialization), and the state dict saves "data" only, thus +# stripping the backward hooks. In some cases, hooks are +# essential to the well-functioning of a model (e.g., DDP), +# but DDP already manages re-adding the hooks! +# +# - We didn't serialize them in many cases. Prior to #10220, we +# were dropping backward hooks in ForkingPickler. We "fixed" this +# to be convenient with other serialization sites, but lack of +# serializing backward hooks wasn't actually the root cause of +# the bug. +# +# With these cases in mind, we have decided that a better strategy +# is to just NOT serialize hooks at all. +# +# Since this is a BC-breaking change, we should warn when we previously +# serialized a hook, but no longer do so. This will be done by adding a special +# sentinel property to hooks will be used to suppress this warning. If a hook +# has the property _torch_serialize_ignore, we will not emit a warning if we +# attempt to serialize a Tensor with this hook attached to it. +# +# By the way, when _backward_hooks is skipped, we must give an EMPTY +# OrderedDict(), if you pass a None you'll run afoul #12219. + + +# TODO: Once we decide to break serialization FC, `storage` no longer needs to +# be a TypedStorage +def _rebuild_tensor(storage, storage_offset, size, stride): + # first construct a tensor with the correct dtype/device + t = torch.empty((0,), dtype=storage.dtype, device=storage._untyped_storage.device) + return t.set_(storage._untyped_storage, storage_offset, size, stride) + + +def get_tensor_metadata(tensor): + # Tensor's Metadata for serializing. + # Currently, this only returns a dict[string, bool] specifying whether + # `conj` or `neg` bit is set. + assert isinstance(tensor, torch.Tensor) + return torch._C._get_tensor_metadata(tensor) # type: ignore[attr-defined] + + +def set_tensor_metadata(tensor, metadata): + # See `get_tensor_metadata` above + assert isinstance(metadata, dict) + assert isinstance(tensor, torch.Tensor) + torch._C._set_tensor_metadata(tensor, metadata) # type: ignore[attr-defined] + + +def _restore_device_fake_mode(tensor): + if torch._guards.detect_fake_mode(None) is not None: + if tensor.untyped_storage()._fake_device is not None: + device = _get_restore_location(tensor.untyped_storage()._fake_device) + if not isinstance(device, torch.device): + device = torch.device(device) + tensor.fake_device = torch.device(device) + return tensor + + +def _rebuild_tensor_v2( + storage, + storage_offset, + size, + stride, + requires_grad, + backward_hooks, + metadata=None, +): + tensor = _rebuild_tensor(storage, storage_offset, size, stride) + tensor.requires_grad = requires_grad + if metadata: + set_tensor_metadata(tensor, metadata) + + # NB: This line exists only for backwards compatibility; the + # general expectation is that backward_hooks is an empty + # OrderedDict. See Note [Don't serialize hooks] + tensor._backward_hooks = backward_hooks + + tensor = _restore_device_fake_mode(tensor) + return tensor + + +def _rebuild_tensor_v3( + storage, + storage_offset, + size, + stride, + requires_grad, + backward_hooks, + dtype, + metadata=None, +): + t = torch.empty( + (0,), + dtype=dtype, + device=storage._untyped_storage.device, + requires_grad=requires_grad, + ) + t.set_(storage._untyped_storage, storage_offset, size, stride) + if metadata: + set_tensor_metadata(t, metadata) + t._backward_hooks = backward_hooks + t = _restore_device_fake_mode(t) + return t + + +_sparse_tensors_to_validate: list["torch.Tensor"] = [] + + +# In _legacy_load() in serialization.py we unpickle storages after the sparse +# tensors have been already unpickled. Those storages contain data necessary for +# validating sparse tensors: indices and values. That's why sparse tensors are +# first unpickled without any validation, and then this function is called just +# before _legacy_load() returns, so that all the sparse tensors can be validated +# in bulk. +# +# The same procedure must be followed by _load() in serialization.py because due +# to Pickler semantics, we have to use the same (non-validating) function for +# unpickling sparse tensors, regardless of the caller. +def _validate_loaded_sparse_tensors(): + if not torch.sparse.check_sparse_tensor_invariants().is_enabled(): + # Skip sparse tensor invariants validation for better + # performance. See check_sparse_tensor_invariants + # documentation for how to control sparse tensor invariants + # checking. + _sparse_tensors_to_validate.clear() + return + try: + # We disable pinning check (see check_pinning=False below) to + # avoid gh-153143. In fact, pinning check is unnecessary + # anywhy when loading sparse data from external sources. + for t in _sparse_tensors_to_validate: + if t.layout is torch.sparse_coo: + torch._validate_sparse_coo_tensor_args( + t._indices(), + t._values(), + t.size(), + t.is_coalesced(), + check_pinning=False, + ) + elif t.layout in { + torch.sparse_csr, + torch.sparse_csc, + torch.sparse_bsr, + torch.sparse_bsc, + }: + # TODO: Validation currently involves an expensive traversal + # on CPU, which may include a device transfer. + if t.layout in {torch.sparse_csr, torch.sparse_bsr}: + compressed_indices, plain_indices = ( + t.crow_indices(), + t.col_indices(), + ) + else: + compressed_indices, plain_indices = ( + t.ccol_indices(), + t.row_indices(), + ) + torch._validate_sparse_compressed_tensor_args( + compressed_indices, + plain_indices, + t.values(), + t.size(), + t.layout, + check_pinning=False, + ) + else: + raise NotImplementedError( + f"_validate_loaded_sparse_tensors for layout `{t.layout}`" + ) + + finally: + _sparse_tensors_to_validate.clear() + + +def _rebuild_sparse_tensor(layout, data): + """ + Rebuilds a sparse tensor from its sparse storage representation. + + Args: + layout (str): The sparse storage layout of the tensor. + data (tuple): The tensor's sparse storage representation. + """ + if layout == torch.sparse_coo: + if len(data) == 3: + # For BC: + indices, values, size = data + is_coalesced = None + else: + indices, values, size, is_coalesced = data + result = torch.sparse_coo_tensor( + indices, values, size, check_invariants=False, is_coalesced=is_coalesced + ) + _sparse_tensors_to_validate.append(result) + return result + + elif layout in { + torch.sparse_csr, + torch.sparse_csc, + torch.sparse_bsr, + torch.sparse_bsc, + }: + compressed_indices, plain_indices, values, size = data + result = torch.sparse_compressed_tensor( + compressed_indices, + plain_indices, + values, + size, + layout=layout, + check_invariants=False, + ) + _sparse_tensors_to_validate.append(result) + return result + + raise NotImplementedError(f"rebuilding sparse tensor for layout {layout}") + + +def _rebuild_nested_tensor(buffer, sizes, strides, storage_offsets): + return torch._nested_view_from_buffer(buffer, sizes, strides, storage_offsets) + + +def _rebuild_device_tensor_from_cpu_tensor(data, dtype, device, requires_grad): + device = _get_restore_location(device) + tensor = data.to(dtype=dtype, device=device) + tensor.requires_grad = requires_grad + return tensor + + +def _rebuild_device_tensor_from_numpy(data, dtype, device, requires_grad): + device = _get_restore_location(device) + tensor = torch.from_numpy(data).to(dtype=dtype, device=device) + tensor.requires_grad = requires_grad + return tensor + + +# Should not be used, only here to be able to load Tensors serialized with older versions of pytorch +_rebuild_xla_tensor = _rebuild_device_tensor_from_numpy + + +def _rebuild_meta_tensor_no_storage(dtype, size, stride, requires_grad): + return torch.empty_strided( + size, stride, dtype=dtype, device="meta", requires_grad=requires_grad + ) + + +def _rebuild_wrapper_subclass( + cls, + dtype, + size, + stride, + storage_offset, + layout, + device, + requires_grad, +): + device = _get_restore_location(device) + return torch.Tensor._make_wrapper_subclass( + cls, + size, + strides=stride, + dtype=dtype, + storage_offset=storage_offset, + layout=layout, + device=device, + requires_grad=requires_grad, + ) + + +# TODO: Once we decide to break serialization FC, `storage` no longer needs to +# be a TypedStorage +def _rebuild_qtensor( + storage, + storage_offset, + size, + stride, + quantizer_params, + requires_grad, + backward_hooks, +): + qscheme = quantizer_params[0] + if qscheme == torch.per_tensor_affine: + _, scale, zero_point = quantizer_params + tensor = torch._empty_affine_quantized( + size, + scale=scale, + zero_point=zero_point, + dtype=storage.dtype, + device=storage.device, + ) + elif qscheme in (torch.per_channel_affine, torch.per_channel_affine_float_qparams): + _, scales, zero_points, axis = quantizer_params + if type(scales) is list and type(zero_points) is list: + if qscheme == torch.per_channel_affine: + scales = torch.tensor(scales, dtype=torch.double, device=storage.device) + zero_points = torch.tensor( + zero_points, dtype=torch.long, device=storage.device + ) + else: + scales = torch.tensor(scales, dtype=torch.float, device=storage.device) + zero_points = torch.tensor( + zero_points, dtype=torch.float, device=storage.device + ) + tensor = torch._empty_per_channel_affine_quantized( + size, + scales=scales, + zero_points=zero_points, + axis=axis, + dtype=storage.dtype, + device=storage.device, + ) + else: + raise RuntimeError(f"Can't deserialize quantized tensor with qscheme {qscheme}") + tensor.set_(storage, storage_offset, size, stride) + tensor.requires_grad = requires_grad + # NB: This line exists only for backwards compatibility; the + # general expectation is that backward_hooks is an empty + # OrderedDict. See Note [Don't serialize hooks] + tensor._backward_hooks = backward_hooks + return tensor + + +def _rebuild_parameter(data, requires_grad, backward_hooks): + param = torch.nn.Parameter(data, requires_grad) + # NB: This line exists only for backwards compatibility; the + # general expectation is that backward_hooks is an empty + # OrderedDict. See Note [Don't serialize hooks] + param._backward_hooks = backward_hooks + + return param + + +def _rebuild_parameter_with_state(data, requires_grad, backward_hooks, state): + param = torch.nn.Parameter(data, requires_grad) + # NB: This line exists only for backwards compatibility; the + # general expectation is that backward_hooks is an empty + # OrderedDict. See Note [Don't serialize hooks] + param._backward_hooks = backward_hooks + + # Restore state on Parameter like python attr. + param = _set_obj_state(param, state) + return param + + +def _get_obj_state(obj): + # Get the state of the python subclass + # This loosely mimics the function on the object class but since Tensor do not inherit + # from it, we cannot call that function directly + # https://github.com/python/cpython/blob/c83919bd635f4433f1c6ae8504996a9fe3c215e5/Objects/typeobject.c#L4891 + # Note that starting with Python 3.11, this `__getstate__` is always defined and thus + # the else branch will never be taken. + getstate_fn = getattr(obj, "__getstate__", None) + if getstate_fn: + state = getstate_fn() + else: + slots_to_save = copyreg._slotnames(obj.__class__) # type: ignore[attr-defined] + if slots_to_save: + state = ( + obj.__dict__, + { + name: getattr(obj, name) + for name in slots_to_save + if hasattr(obj, name) + }, + ) + else: + state = obj.__dict__ + + return state + + +def _set_obj_state(obj, state): + if isinstance(state, tuple): + if not len(state) == 2: + raise RuntimeError(f"Invalid serialized state: {state}") + dict_state = state[0] + slots_state = state[1] + else: + dict_state = state + slots_state = None + + # Starting with Python 3.11, the __dict__ attribute is lazily created + # and is serialized as None when not needed. + if dict_state: + for k, v in dict_state.items(): + setattr(obj, k, v) + + if slots_state: + for k, v in slots_state.items(): + setattr(obj, k, v) + return obj + + +def _import_dotted_name(name): + components = name.split(".") + obj = __import__(components[0]) + for component in components[1:]: + obj = getattr(obj, component) + return obj + + +def _flatten_dense_tensors(tensors): + """Flatten dense tensors into a contiguous 1D buffer. Assume tensors are of + same dense type. + + Since inputs are dense, the resulting tensor will be a concatenated 1D + buffer. Element-wise operation on this buffer will be equivalent to + operating individually. + + Args: + tensors (Iterable[Tensor]): dense tensors to flatten. + + Returns: + A contiguous 1D buffer containing input tensors. + """ + return torch._C._nn.flatten_dense_tensors(tensors) + + +def _flatten_sparse_tensors(tensors): + """Flatten sparse tensors into two contiguous 1D buffers, one of indices and + one of values. Assume tensors are of same sparse type. + + Args: + tensors (Iterable[Tensor]): sparse tensors to flatten. + + Returns: + A tuple of two contiguous 1D buffers, one containing input tensors' + indices and the other containing the values. + """ + flat_indices = torch._C._nn.flatten_dense_tensors( + [torch.Tensor._indices(t) for t in tensors] + ) + flat_values = torch._C._nn.flatten_dense_tensors( + [torch.Tensor._values(t) for t in tensors] + ) + return flat_indices, flat_values + + +def _unflatten_dense_tensors(flat, tensors): + """View a flat buffer using the sizes of tensors. Assume that tensors are of + same dense type, and that flat is given by _flatten_dense_tensors. + + Args: + flat (Tensor): flattened dense tensors to unflatten. + tensors (Iterable[Tensor]): dense tensors whose sizes will be used to + unflatten flat. + + Returns: + Unflattened dense tensors with sizes same as tensors and values from + flat. + """ + return torch._C._nn.unflatten_dense_tensors(flat, tensors) + + +def _unflatten_sparse_tensors(flat, tensors): + """View flat buffer (containing indices and values) using the sizes of + tensors. Assume that tensors are of same sparse type, and that flat is given + by _flatten_sparse_tensors. + + Args: + flat (tuple(Tensor, Tensor)): flattened indices and values of sparse + tensors to unflatten. + tensors (Iterable[Tensor]): sparse tensors whose sizes will be used to + unflatten flat. + + Returns: + Unflattened sparse tensors with sizes same as tensors and values from + flat. + """ + flat_indices, flat_values = flat + indices = torch._C._nn.unflatten_dense_tensors( + flat_indices, [torch.Tensor._indices(t) for t in tensors] + ) + values = torch._C._nn.unflatten_dense_tensors( + flat_values, [torch.Tensor._values(t) for t in tensors] + ) + outputs = [] + for t, i, v in zip(tensors, indices, values): + outputs.append(t.new(i, v, t.size())) + return tuple(outputs) + + +def _reorder_tensors_as(tensors, ordered_tensors): + """Assume that tensors are of same order as ordered_tensors within their + types, e.g., from _take_tensors. Reorder them to be of same order as + ordered_tensors. + + Args: + tensors (Iterable[Tensor]): tensors to be reordered. They should be of + the same order as ordered_tensors within their own types. + ordered_tensors (Iterable[Tensor]): tensors whose order will be the + reference. + + Returns: + Ordered tuple of tensors with contents from tensors and order of + ordered_tensors. + """ + type_dict = defaultdict(list) + for tensor in tensors: + type_dict[tensor.type()].append(tensor) + type_dict_ = {t: iter(coll) for t, coll in type_dict.items()} + return tuple(next(type_dict_[tensor.type()]) for tensor in ordered_tensors) + + +def _take_tensors(tensors, size_limit): + """Group tensors into chunks. This generator yields a chunk at each time, + each containing tensors of same type up to certain byte limit in total size. + + Args: + tensors (Sequence): A sequence of tensors to be separated into chunks. + size_limit (int): The limit of each chunk in bytes. + + Yields: + Blocks of tensors of same type and within size_limit. The yielded + tensors are only ordered as the original sequence within its types. + """ + buf_dict: defaultdict[str, list] = defaultdict(lambda: [[], 0]) + for tensor in tensors: + t = tensor.type() + if tensor.is_sparse: + indices = torch.Tensor._indices(tensor) + values = torch.Tensor._values(tensor) + size = ( + indices.numel() * indices.element_size() + + values.numel() * values.element_size() + ) + else: + size = tensor.numel() * tensor.element_size() + buf_and_size = buf_dict[t] + if buf_and_size[1] + size > size_limit and buf_and_size[1] > 0: + yield buf_and_size[0] + buf_and_size = buf_dict[t] = [[], 0] + buf_and_size[0].append(tensor) # pyrefly: ignore [missing-attribute] + buf_and_size[1] += size # pyrefly: ignore [unsupported-operation] + for buf, _ in buf_dict.values(): + if len(buf) > 0: + yield buf + + +# annotation decorator to get annotations in a way that is compatible +# with both Python 2 and 3 +def annotate(ret, **kwargs): + def dec(fun): + fun.__annotations__ = dict(kwargs) + fun.__annotations__["return"] = ret + return fun + + return dec + + +def render_call(fn, args, kwargs): + str_fn = torch.overrides.resolve_name(fn) + if str_fn is None: + str_fn = str(fn) + + str_args: list[str] = [] + with torch._tensor_str.printoptions(threshold=0, edgeitems=0): + str_args.extend(repr(a) for a in args) + str_args.extend(f"{k}={repr(v)}" for k, v in kwargs.items()) + r = f"{str_fn}({', '.join(str_args)})" + return r + + +# NOTE [ Python Traceback Reference Cycle Problem ] +# +# When using sys.exc_info(), it is important to **not** store the exc_info[2], +# which is the traceback, because otherwise you will run into the traceback +# reference cycle problem, i.e., the traceback holding reference to the frame, +# and the frame (which holds reference to all the object in its temporary scope) +# holding reference the traceback. + + +class KeyErrorMessage(str): + r"""str subclass that returns itself in repr""" + + __slots__ = () + + def __repr__(self): + return self + + +class ExceptionWrapper: + r"""Wraps an exception plus traceback to communicate across threads""" + + def __init__(self, exc_info=None, where="in background"): + # It is important that we don't store exc_info, see + # NOTE [ Python Traceback Reference Cycle Problem ] + if exc_info is None: + exc_info = sys.exc_info() + self.exc_type = exc_info[0] + # pyrefly: ignore [not-iterable] + self.exc_msg = "".join(traceback.format_exception(*exc_info)) + self.where = where + + def reraise(self): + r"""Reraises the wrapped exception in the current thread""" + # Format a message such as: "Caught ValueError in DataLoader worker + # process 2. Original Traceback:", followed by the traceback. + msg = f"Caught {self.exc_type.__name__} {self.where}.\nOriginal {self.exc_msg}" # pyrefly: ignore [missing-attribute] + if self.exc_type is KeyError: + # KeyError calls repr() on its argument (usually a dict key). This + # makes stack traces unreadable. It will not be changed in Python + # (https://bugs.python.org/issue2651), so we work around it. + msg = KeyErrorMessage(msg) + elif getattr(self.exc_type, "message", None): + # Some exceptions have first argument as non-str but explicitly + # have message field + # pyrefly: ignore [not-callable] + raise self.exc_type( + # pyrefly: ignore [unexpected-keyword] + message=msg + ) + try: + exception = self.exc_type(msg) # pyrefly: ignore [not-callable] + except Exception: + # If the exception takes multiple arguments or otherwise can't + # be constructed, don't try to instantiate since we don't know how to + raise RuntimeError(msg) from None + raise exception + + +def _get_available_device_type(): + if torch.cuda.is_available(): + return "cuda" + if torch.backends.mps.is_available(): + return "mps" + if hasattr(torch, "xpu") and torch.xpu.is_available(): # type: ignore[attr-defined] + return "xpu" + if hasattr(torch, "mtia") and torch.mtia.is_available(): + return "mtia" + custom_backend_name = torch._C._get_privateuse1_backend_name() + custom_device_mod = getattr(torch, custom_backend_name, None) + if custom_device_mod and custom_device_mod.is_available(): + return custom_backend_name + # add more available device types here + return None + + +def _get_device_attr(get_member): + device_type = _get_available_device_type() + if device_type and device_type.lower() == "cuda": + return get_member(torch.cuda) + if device_type and device_type.lower() == "mps": + return get_member(torch.mps) + if device_type and device_type.lower() == "xpu": + return get_member(torch.xpu) # type: ignore[attr-defined] + if device_type and device_type.lower() == "mtia": + return get_member(torch.mtia) + if device_type == torch._C._get_privateuse1_backend_name(): + return get_member(getattr(torch, device_type)) + # add more available device types here + return None + + +def _get_current_device_index(): + # current device index + return _get_device_attr(lambda m: m.current_device()) + + +def _get_all_device_indices(): + # all device index + return _get_device_attr(lambda m: list(range(m.device_count()))) + + +def _get_devices_properties(device_ids): + # all device properties + return [_get_device_attr(lambda m: m.get_device_properties(i)) for i in device_ids] + + +def get_current_device_index() -> int: + r"""Checks if there are CUDA devices available and + returns the device index of the current default CUDA device. + Returns -1 in case there are no CUDA devices available. + Arguments: ``None`` + """ + if torch.cuda.device_count() > 0: + return torch.cuda.current_device() + return -1 + + +def _get_device_index( + device: Any, + optional: bool = False, + allow_cpu: bool = False, +) -> int: + r"""Gets the device index from :attr:`device`, which can be a torch.device + object, a Python integer, or ``None``. + + If :attr:`device` is a torch.device object, returns the device index if it + has index. Note that for a device without a specified index, + i.e., ``torch.device('xxx')``, this will return the current default + device of that type if :attr:`optional` is ``True``. If :attr:`allow_cpu` is ``True``, + CPU devices will be accepted and ``-1`` will be returned in this case. + + If :attr:`device` is a Python integer, it is returned as is. + + If :attr:`device` is ``None``, this will return the current default + device of the supported runtime platform if :attr:`optional` is ``True``. + i.e., the current default CUDA device will be returned if CUDA runtime is supported. + """ + if isinstance(device, str): + device = torch.device(device) + device_idx: int | None = None + if isinstance(device, torch.device): + if not allow_cpu and device.type == "cpu": + raise ValueError(f"Expected a non cpu device, but got: {device}") + device_idx = -1 if device.type == "cpu" else device.index + if isinstance(device, int): + device_idx = device + if device_idx is None: + if optional: + # The eager API _get_current_device_index uses `lambda` functions which are + # not supported in JIT and hence not scriptable. The JIT equivalent API to get + # the current device index is `get_current_device_index()` which can + # be scripted. We use is_scripting to check the mode we are in and call the + # appropriate API. + if torch.jit.is_scripting(): + device_idx = get_current_device_index() + else: + device_idx = _get_current_device_index() + else: + raise ValueError( + f"Expected a torch.device with a specified index or an integer, but got:{device}" + ) + return device_idx + + +def _handle_complex(tensor): + """ + Returns a real view of a tensor if complex dtype else just the tensor + need to check if a UninitializedParameter because otherwise checking is_complex is an error for a LazyModule + """ + return ( + torch.view_as_real(tensor) + if not isinstance(tensor, torch.nn.UninitializedParameter) + and tensor.is_complex() + else tensor + ) + + +def _element_size(dtype): + """ + Returns the element size for a dtype, in bytes + """ + if not isinstance(dtype, torch.dtype): + raise RuntimeError(f"expected torch.dtype, but got {type(dtype)}") + + if dtype.is_complex: + return torch.finfo(dtype).bits >> 2 + elif dtype.is_floating_point: + return torch.finfo(dtype).bits >> 3 + elif dtype == torch.bool: + # NOTE: torch.bool is not supported in torch.iinfo() + return 1 + else: + return torch.iinfo(dtype).bits >> 3 + + +class _ClassPropertyDescriptor: + def __init__(self, fget, fset=None): + self.fget = fget + + def __get__(self, instance, owner=None): + if owner is None: + owner = type(instance) + return self.fget.__get__(instance, owner)() + + +def classproperty(func): + if not isinstance(func, (classmethod, staticmethod)): + func = classmethod(func) + return _ClassPropertyDescriptor(func) + + +if TYPE_CHECKING: + # TorchScript does not support `@deprecated` + # This is a workaround to avoid breaking TorchScript + @deprecated( + "`torch._utils.is_compiling` is deprecated. Use `torch.compiler.is_compiling` instead.", + category=FutureWarning, + ) + def is_compiling() -> bool: + return torch.compiler.is_compiling() + +else: + + def is_compiling() -> bool: + """ + Indicates whether we are tracing/compiling with torch.compile() or torch.export(). + """ + warnings.warn( # use `warnings.warn` instead of `@deprecated` + "`torch._utils.is_compiling` is deprecated. Use `torch.compiler.is_compiling` instead.", + # FutureWarning, # TorchScript does not support Warning type + stacklevel=2, + ) + return torch.compiler.is_compiling() + + +def _functionalize_sync(t): + # This code lives in python instead of C++ since conditioning on a certain python subclass + # is much more of a pain in C++. + from torch._subclasses.functional_tensor import FunctionalTensor + + if isinstance(t, FunctionalTensor): + # If a FunctionalTensorMode is active while syncing, we don't want it to intercept any ops that get called + # when we sync our inner tensor. + # Why? + # (1) If there are input mutations in the graph, then they will be re-applied during + # AOTAutograd when we call _sync() from inside of our functionalization kernels. + # (2) _sync() causes us to regenerate our updated the tensor from the updated base, + # which dispatches to a bunch of view ops + # (3) The input to these view ops is our inner FunctionalTensorWrapper + # (since the sync was called from C++), not the python FunctionalTensor + # (4) if a python FunctionalTensorMode is active, it will complain when it intercepts + # the view op, since it will see an input that is a C++ FunctionalTensorWrapper + # (aka a normal torch.Tensor) instead of a python `FunctionalTensor). + maybe_functional_mode = torch._C._unset_dispatch_mode( + torch._C._TorchDispatchModeKey.FUNCTIONAL + ) + try: + torch._functionalize_sync(t.elem) # type: ignore[attr-defined] + finally: + if maybe_functional_mode is not None: + torch._C._set_dispatch_mode(maybe_functional_mode) + else: + torch._functionalize_sync(t) # type: ignore[attr-defined] + + +@functools.lru_cache(2) +def _get_device_module(device_type: str): + device_module = getattr(torch, device_type, None) + if device_module is None: + raise RuntimeError( + f"Device '{device_type}' does not have a corresponding module registered as 'torch.{device_type}'." + ) + return device_module + + +def _dummy_type(name: str) -> type: + def get_err_fn(is_init: bool): + def err_fn(obj, *args, **kwargs): + if is_init: + class_name = obj.__class__.__name__ + else: + class_name = obj.__name__ + raise RuntimeError(f"Tried to instantiate dummy base class {class_name}") + + return err_fn + + return type( + name, (object,), {"__init__": get_err_fn(True), "__new__": get_err_fn(False)} + ) + + +class _LazySeedTracker: + # Since seeding is memory-less, only track the latest seed. + # Note: `manual_seed_all` followed by `manual_seed` overwrites + # the seed on current device. We track the order of **latest** + # calls between these two API. + def __init__(self): + self.manual_seed_all_cb = None + self.manual_seed_cb = None + self.call_order = [] + + def queue_seed_all(self, cb, traceback): + self.manual_seed_all_cb = (cb, traceback) # pyrefly: ignore [bad-assignment] + # update seed_all to be latest + self.call_order = [self.manual_seed_cb, self.manual_seed_all_cb] + + def queue_seed(self, cb, traceback): + self.manual_seed_cb = (cb, traceback) # pyrefly: ignore [bad-assignment] + # update seed to be latest + self.call_order = [self.manual_seed_all_cb, self.manual_seed_cb] + + def get_calls(self) -> list: + return self.call_order + + +logger = logging.getLogger(__name__) +P = ParamSpec("P") + + +class CallbackRegistry(Generic[P]): + def __init__(self, name: str): + self.name = name + self.callback_list: list[Callable[P, None]] = [] + + def add_callback(self, cb: Callable[P, None]) -> None: + self.callback_list.append(cb) + + def fire_callbacks(self, *args: P.args, **kwargs: P.kwargs) -> None: + for cb in self.callback_list: + try: + cb(*args, **kwargs) + except Exception: + logger.exception( + "Exception in callback for %s registered with gpu trace", self.name + ) + + +def try_import(module_name: str) -> ModuleType | None: + # Implementation based on + # https://docs.python.org/3/library/importlib.html#checking-if-a-module-can-be-imported + if (module := sys.modules.get(module_name, None)) is not None: + return module + + if (spec := importlib.util.find_spec(module_name)) is not None: + module = importlib.util.module_from_spec(spec) + sys.modules[module_name] = module + + # https://docs.python.org/3/library/importlib.html#importlib.machinery.ModuleSpec.loader + # "The finder should always set this attribute" + assert spec.loader is not None, "The loader attribute should always be set" + spec.loader.exec_module(module) + return module + + return None + + +# IMPORT_MAPPING and NAME_MAPPING are adapted from https://github.com/python/cpython/blob/main/Lib/_compat_pickle.py +# for use in the weights_only Unpickler. + +IMPORT_MAPPING = { + "__builtin__": "builtins", + "copy_reg": "copyreg", + "Queue": "queue", + "repr": "reprlib", + "_abcoll": "collections.abc", + # Non-mutual mappings. + "UserDict": "collections", + "UserList": "collections", + "UserString": "collections", + "whichdb": "dbm", + "StringIO": "io", + "cStringIO": "io", +} + + +# This contains rename rules that are easy to handle. We ignore the more +# complex stuff (e.g. mapping the names in the urllib and types modules). +# These rules should be run before import names are fixed. +NAME_MAPPING = { + ("__builtin__", "xrange"): ("builtins", "range"), + ("__builtin__", "reduce"): ("functools", "reduce"), + ("__builtin__", "intern"): ("sys", "intern"), + ("__builtin__", "unichr"): ("builtins", "chr"), + ("__builtin__", "unicode"): ("builtins", "str"), + ("__builtin__", "long"): ("builtins", "int"), + ("itertools", "izip"): ("builtins", "zip"), + ("itertools", "imap"): ("builtins", "map"), + ("itertools", "ifilter"): ("builtins", "filter"), + ("itertools", "ifilterfalse"): ("itertools", "filterfalse"), + ("itertools", "izip_longest"): ("itertools", "zip_longest"), + ("UserDict", "IterableUserDict"): ("collections", "UserDict"), + ("UserList", "UserList"): ("collections", "UserList"), + ("UserString", "UserString"): ("collections", "UserString"), + # Non-mutual mappings. + ("__builtin__", "basestring"): ("builtins", "str"), + ("exceptions", "StandardError"): ("builtins", "Exception"), + ("UserDict", "UserDict"): ("collections", "UserDict"), +} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_utils_internal.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_utils_internal.py new file mode 100644 index 0000000000000000000000000000000000000000..6f95511b5ce80cff8c735126d6428fc88bf2c5f2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_utils_internal.py @@ -0,0 +1,378 @@ +# mypy: allow-untyped-defs +import functools +import logging +import os +import sys +import tempfile +import typing_extensions +from collections.abc import Callable +from typing import Any, TypeVar +from typing_extensions import ParamSpec + +import torch +from torch._strobelight.compile_time_profiler import StrobelightCompileTimeProfiler + + +_T = TypeVar("_T") +_P = ParamSpec("_P") + +log = logging.getLogger(__name__) + +if os.environ.get("TORCH_COMPILE_STROBELIGHT", False): + import shutil + + if not shutil.which("strobeclient"): + log.info( + "TORCH_COMPILE_STROBELIGHT is true, but seems like you are not on a FB machine." + ) + else: + log.info("Strobelight profiler is enabled via environment variable") + StrobelightCompileTimeProfiler.enable() + +# this arbitrary-looking assortment of functionality is provided here +# to have a central place for overridable behavior. The motivating +# use is the FB build environment, where this source file is replaced +# by an equivalent. + +if os.path.basename(os.path.dirname(__file__)) == "shared": + torch_parent = os.path.dirname(os.path.dirname(os.path.dirname(__file__))) +else: + torch_parent = os.path.dirname(os.path.dirname(__file__)) + + +def get_file_path(*path_components: str) -> str: + return os.path.join(torch_parent, *path_components) + + +def get_file_path_2(*path_components: str) -> str: + return os.path.join(*path_components) + + +def get_writable_path(path: str) -> str: + if os.access(path, os.W_OK): + return path + return tempfile.mkdtemp(suffix=os.path.basename(path)) + + +def prepare_multiprocessing_environment(path: str) -> None: + pass + + +def resolve_library_path(path: str) -> str: + return os.path.realpath(path) + + +def throw_abstract_impl_not_imported_error(opname, module, context): + if module in sys.modules: + raise NotImplementedError( + f"{opname}: We could not find the fake impl for this operator. " + ) + else: + raise NotImplementedError( + f"{opname}: We could not find the fake impl for this operator. " + f"The operator specified that you may need to import the '{module}' " + f"Python module to load the fake impl. {context}" + ) + + +# NB! This treats "skip" kwarg specially!! +def compile_time_strobelight_meta( + phase_name: str, +) -> Callable[[Callable[_P, _T]], Callable[_P, _T]]: + def compile_time_strobelight_meta_inner( + function: Callable[_P, _T], + ) -> Callable[_P, _T]: + @functools.wraps(function) + def wrapper_function(*args: _P.args, **kwargs: _P.kwargs) -> _T: + if "skip" in kwargs and isinstance( + # pyrefly: ignore [unsupported-operation] + skip := kwargs["skip"], + int, + ): + kwargs["skip"] = skip + 1 + + # This is not needed but we have it here to avoid having profile_compile_time + # in stack traces when profiling is not enabled. + if not StrobelightCompileTimeProfiler.enabled: + return function(*args, **kwargs) + + return StrobelightCompileTimeProfiler.profile_compile_time( + function, phase_name, *args, **kwargs + ) + + return wrapper_function + + return compile_time_strobelight_meta_inner + + +# Meta only, see +# https://www.internalfb.com/intern/wiki/ML_Workflow_Observability/User_Guides/Adding_instrumentation_to_your_code/ +# +# This will cause an event to get logged to Scuba via the signposts API. You +# can view samples on the API at https://fburl.com/scuba/workflow_signpost/zh9wmpqs +# we log to subsystem "torch", and the category and name you provide here. +# Each of the arguments translate into a Scuba column. We're still figuring +# out local conventions in PyTorch, but category should be something like +# "dynamo" or "inductor", and name should be a specific string describing what +# kind of event happened. +# +# Killswitch is at +# https://www.internalfb.com/intern/justknobs/?name=pytorch%2Fsignpost#event +def signpost_event(category: str, name: str, parameters: dict[str, Any]): + log.info("%s %s: %r", category, name, parameters) + + +def add_mlhub_insight(category: str, insight: str, insight_description: str): + pass + + +def log_compilation_event(metrics): + log.info("%s", metrics) + + +def upload_graph(graph): + pass + + +def set_pytorch_distributed_envs_from_justknobs(): + pass + + +def log_export_usage(**kwargs): + pass + + +def log_draft_export_usage(**kwargs): + pass + + +def log_trace_structured_event(*args, **kwargs) -> None: + pass + + +def log_cache_bypass(*args, **kwargs) -> None: + pass + + +def log_torchscript_usage(api: str, **kwargs): + _ = api + return + + +def check_if_torch_exportable(): + return False + + +def export_training_ir_rollout_check() -> bool: + return True + + +def full_aoti_runtime_assert() -> bool: + return True + + +def log_torch_jit_trace_exportability( + api: str, + type_of_export: str, + export_outcome: str, + result: str, +): + _, _, _, _ = api, type_of_export, export_outcome, result + return + + +DISABLE_JUSTKNOBS = True + + +def justknobs_check(name: str, default: bool = True) -> bool: + """ + This function can be used to killswitch functionality in FB prod, + where you can toggle this value to False in JK without having to + do a code push. In OSS, we always have everything turned on all + the time, because downstream users can simply choose to not update + PyTorch. (If more fine-grained enable/disable is needed, we could + potentially have a map we lookup name in to toggle behavior. But + the point is that it's all tied to source code in OSS, since there's + no live server to query.) + + This is the bare minimum functionality I needed to do some killswitches. + We have a more detailed plan at + https://docs.google.com/document/d/1Ukerh9_42SeGh89J-tGtecpHBPwGlkQ043pddkKb3PU/edit + In particular, in some circumstances it may be necessary to read in + a knob once at process start, and then use it consistently for the + rest of the process. Future functionality will codify these patterns + into a better high level API. + + WARNING: Do NOT call this function at module import time, JK is not + fork safe and you will break anyone who forks the process and then + hits JK again. + """ + return default + + +def justknobs_getval_int(name: str) -> int: + """ + Read warning on justknobs_check + """ + return 0 + + +def is_fb_unit_test() -> bool: + return False + + +@functools.cache +def max_clock_rate(): + """ + unit: MHz + """ + if not torch.version.hip: + from triton.testing import nvsmi + + return nvsmi(["clocks.max.sm"])[0] + else: + # Manually set max-clock speeds on ROCm until equivalent nvmsi + # functionality in triton.testing or via pyamdsmi enablement. Required + # for test_snode_runtime unit tests. + gcn_arch = str(torch.cuda.get_device_properties(0).gcnArchName.split(":", 1)[0]) + if "gfx94" in gcn_arch: + return 1700 + elif "gfx90a" in gcn_arch: + return 1700 + elif "gfx908" in gcn_arch: + return 1502 + elif "gfx12" in gcn_arch: + return 1700 + elif "gfx11" in gcn_arch: + return 1700 + elif "gfx103" in gcn_arch: + return 1967 + elif "gfx101" in gcn_arch: + return 1144 + elif "gfx95" in gcn_arch: + return 1700 # TODO: placeholder, get actual value + else: + return 1100 + + +def get_mast_job_name_version() -> tuple[str, int] | None: + return None + + +TEST_MASTER_ADDR = "127.0.0.1" +TEST_MASTER_PORT = 29500 +# USE_GLOBAL_DEPS controls whether __init__.py tries to load +# libtorch_global_deps, see Note [Global dependencies] +USE_GLOBAL_DEPS = True +# USE_RTLD_GLOBAL_WITH_LIBTORCH controls whether __init__.py tries to load +# _C.so with RTLD_GLOBAL during the call to dlopen. +USE_RTLD_GLOBAL_WITH_LIBTORCH = False +# If an op was defined in C++ and extended from Python using the +# torch.library.register_fake, returns if we require that there be a +# m.set_python_module("mylib.ops") call from C++ that associates +# the C++ op with a python module. +REQUIRES_SET_PYTHON_MODULE = False + + +def maybe_upload_prof_stats_to_manifold(profile_path: str) -> str | None: + print("Uploading profile stats (fb-only otherwise no-op)") + return None + + +def log_chromium_event_internal( + event: dict[str, Any], + stack: list[str], + logger_uuid: str, + start_time_ns: int, +): + return None + + +def record_chromium_event_internal( + event: dict[str, Any], +): + return None + + +def profiler_allow_cudagraph_cupti_lazy_reinit_cuda12(): + return True + + +def deprecated(): + """ + When we deprecate a function that might still be in use, we make it internal + by adding a leading underscore. This decorator is used with a private function, + and creates a public alias without the leading underscore, but has a deprecation + warning. This tells users "THIS FUNCTION IS DEPRECATED, please use something else" + without breaking them, however, if they still really really want to use the + deprecated function without the warning, they can do so by using the internal + function name. + """ + + def decorator(func: Callable[_P, _T]) -> Callable[_P, _T]: + # Validate naming convention - single leading underscore, not dunder + if not (func.__name__.startswith("_")): + raise ValueError( + "@deprecate must decorate a function whose name " + "starts with a single leading underscore (e.g. '_foo') as the api should be considered internal for deprecation." + ) + + public_name = func.__name__[1:] # drop exactly one leading underscore + module = sys.modules[func.__module__] + + # Don't clobber an existing symbol accidentally. + if hasattr(module, public_name): + raise RuntimeError( + f"Cannot create alias '{public_name}' -> symbol already exists in {module.__name__}. \ + Please rename it or consult a pytorch developer on what to do" + ) + + warning_msg = f"{func.__name__[1:]} is DEPRECATED, please consider using an alternative API(s). " + + # public deprecated alias + alias = typing_extensions.deprecated( + # pyrefly: ignore [bad-argument-type] + warning_msg, + category=UserWarning, + stacklevel=1, + )(func) + + alias.__name__ = public_name + + # Adjust qualname if nested inside a class or another function + if "." in func.__qualname__: + alias.__qualname__ = func.__qualname__.rsplit(".", 1)[0] + "." + public_name + else: + alias.__qualname__ = public_name + + setattr(module, public_name, alias) + + return func + + return decorator + + +def get_default_numa_options(): + """ + When using elastic agent, if no numa options are provided, we will use these + as the default. + + For external use cases, we return None, i.e. no numa binding. If you would like + to use torch's automatic numa binding capabilities, you should provide + NumaOptions to your launch config directly or use the numa binding option + available in torchrun. + + Must return None or NumaOptions, but not specifying to avoid circular import. + """ + return None + + +def log_triton_builds(fail: str | None): + pass + + +def find_compile_subproc_binary() -> str | None: + """ + Allows overriding the binary used for subprocesses + """ + return None diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_vmap_internals.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_vmap_internals.py new file mode 100644 index 0000000000000000000000000000000000000000..861d4fd4b4153cd599cb8d5fcf7a82b09aa2289b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_vmap_internals.py @@ -0,0 +1,246 @@ +# mypy: allow-untyped-defs +import functools +from collections.abc import Callable +from typing import Any +from typing_extensions import deprecated + +import torch +from torch import Tensor +from torch.utils._pytree import _broadcast_to_and_flatten, tree_flatten, tree_unflatten + + +in_dims_t = int | tuple +out_dims_t = int | tuple[int, ...] + + +# Checks that all args-to-be-batched have the same batch dim size +def _validate_and_get_batch_size( + flat_in_dims: list[int | None], + flat_args: list, +) -> int: + batch_sizes = [ + arg.size(in_dim) + for in_dim, arg in zip(flat_in_dims, flat_args) + if in_dim is not None + ] + if batch_sizes and any(size != batch_sizes[0] for size in batch_sizes): + raise ValueError( + f"vmap: Expected all tensors to have the same size in the mapped " + f"dimension, got sizes {batch_sizes} for the mapped dimension" + ) + return batch_sizes[0] + + +def _num_outputs(batched_outputs: Tensor | tuple[Tensor, ...]) -> int: + if isinstance(batched_outputs, tuple): + return len(batched_outputs) + return 1 + + +# If value is a tuple, check it has length `num_elements`. +# If value is not a tuple, make a tuple with `value` repeated `num_elements` times +def _as_tuple( + value: Any, + num_elements: int, + error_message_lambda: Callable[[], str], +) -> tuple: + if not isinstance(value, tuple): + return (value,) * num_elements + if len(value) != num_elements: + raise ValueError(error_message_lambda()) + return value + + +# Creates BatchedTensors for every Tensor in arg that should be batched. +# Returns the (potentially) batched arguments and the batch_size. +def _create_batched_inputs( + in_dims: in_dims_t, + args: tuple, + vmap_level: int, + func: Callable, +) -> tuple[tuple, int]: + if not isinstance(in_dims, int) and not isinstance(in_dims, tuple): + raise ValueError( + f"vmap({_get_name(func)}, in_dims={in_dims}, ...)(): " + f"expected `in_dims` to be int or a (potentially nested) tuple " + f"matching the structure of inputs, got: {type(in_dims)}." + ) + if len(args) == 0: + raise ValueError( + f"vmap({_get_name(func)})(): got no inputs. Maybe you forgot to add " + f"inputs, or you are trying to vmap over a function with no inputs. " + f"The latter is unsupported." + ) + + flat_args, args_spec = tree_flatten(args) + flat_in_dims = _broadcast_to_and_flatten(in_dims, args_spec) + if flat_in_dims is None: + raise ValueError( + f"vmap({_get_name(func)}, in_dims={in_dims}, ...)(): " + f"in_dims is not compatible with the structure of `inputs`. " + f"in_dims has structure {tree_flatten(in_dims)[1]} but inputs " + f"has structure {args_spec}." + ) + + for arg, in_dim in zip(flat_args, flat_in_dims): + if not isinstance(in_dim, int) and in_dim is not None: + raise ValueError( + f"vmap({_get_name(func)}, in_dims={in_dims}, ...)(): " + f"Got in_dim={in_dim} for an input but in_dim must be either " + f"an integer dimension or None." + ) + if isinstance(in_dim, int) and not isinstance(arg, Tensor): + raise ValueError( + f"vmap({_get_name(func)}, in_dims={in_dims}, ...)(): " + f"Got in_dim={in_dim} for an input but the input is of type " + f"{type(arg)}. We cannot vmap over non-Tensor arguments, " + f"please use None as the respective in_dim" + ) + if in_dim is not None and (in_dim < 0 or in_dim >= arg.dim()): + raise ValueError( + f"vmap({_get_name(func)}, in_dims={in_dims}, ...)(): " + f"Got in_dim={in_dim} for some input, but that input is a Tensor " + f"of dimensionality {arg.dim()} so expected in_dim to satisfy " + f"0 <= in_dim < {arg.dim()}." + ) + + batch_size = _validate_and_get_batch_size(flat_in_dims, flat_args) + # See NOTE [Ignored _remove_batch_dim, _add_batch_dim] + batched_inputs = [ + arg if in_dim is None else torch._add_batch_dim(arg, in_dim, vmap_level) + for in_dim, arg in zip(flat_in_dims, flat_args) + ] + return tree_unflatten(batched_inputs, args_spec), batch_size + + +# Undos the batching (and any batch dimensions) associated with the `vmap_level`. +def _unwrap_batched( + batched_outputs: Tensor | tuple[Tensor, ...], + out_dims: out_dims_t, + vmap_level: int, + batch_size: int, + func: Callable, + allow_none_pass_through: bool = False, +) -> tuple: + num_outputs = _num_outputs(batched_outputs) + out_dims_as_tuple = _as_tuple( + out_dims, + num_outputs, + lambda: f"vmap({_get_name(func)}, ..., out_dims={out_dims}): `out_dims` must " + f"have one dim per output (got {num_outputs} outputs) of {_get_name(func)}.", + ) + + # NOTE [Ignored _remove_batch_dim, _add_batch_dim] + # There is something wrong with our type bindings for functions that begin + # with '_', see #40397. + if isinstance(batched_outputs, Tensor): + out_dim = out_dims_as_tuple[0] + return torch._remove_batch_dim(batched_outputs, vmap_level, batch_size, out_dim) # type: ignore[return-value] + if allow_none_pass_through: + return tuple( + ( + torch._remove_batch_dim(out, vmap_level, batch_size, out_dim) + if out is not None + else None + ) + for out, out_dim in zip(batched_outputs, out_dims_as_tuple) + ) + else: + return tuple( + torch._remove_batch_dim(out, vmap_level, batch_size, out_dim) + for out, out_dim in zip(batched_outputs, out_dims_as_tuple) + ) + + +# Checks that `fn` returned one or more Tensors and nothing else. +# NB: A python function that return multiple arguments returns a single tuple, +# so we are effectively checking that `outputs` is a single Tensor or a tuple of +# Tensors. +def _validate_outputs(outputs: Any, func: Callable) -> None: + if isinstance(outputs, Tensor): + return + if not isinstance(outputs, tuple): + raise ValueError( + f"vmap({_get_name(func)}, ...): `{_get_name(func)}` must only return " + f"Tensors, got type {type(outputs)} as the return." + ) + for idx, output in enumerate(outputs): + if isinstance(output, Tensor): + continue + raise ValueError( + f"vmap({_get_name(func)}, ...): `{_get_name(func)}` must only return " + f"Tensors, got type {type(output)} for return {idx}." + ) + + +def _check_out_dims_is_int_or_int_tuple(out_dims: out_dims_t, func: Callable) -> None: + if isinstance(out_dims, int): + return + if not isinstance(out_dims, tuple) or not all( + isinstance(out_dim, int) for out_dim in out_dims + ): + raise ValueError( + f"vmap({_get_name(func)}, ..., out_dims={out_dims}): `out_dims` must be " + f"an int or a tuple of int representing where in the outputs the " + f"vmapped dimension should appear." + ) + + +def _get_name(func: Callable): + if hasattr(func, "__name__"): + return func.__name__ + + # Not all callables have __name__, in fact, only static functions/methods do. + # A callable created via functools.partial or an nn.Module, to name some + # examples, don't have a __name__. + return repr(func) + + +# vmap(func)(inputs) wraps all Tensor inputs to be batched in BatchedTensors, +# sends those into func, and then unwraps the output BatchedTensors. Operations +# on BatchedTensors perform the batched operations that the user is asking for. +@deprecated( + "Please use `torch.vmap` instead of `torch._vmap_internals.vmap`.", + category=FutureWarning, +) +def vmap(func: Callable, in_dims: in_dims_t = 0, out_dims: out_dims_t = 0) -> Callable: + """ + Please use torch.vmap instead of this API. + """ + return _vmap(func, in_dims, out_dims) + + +# A version of vmap but without the initial "experimental prototype" warning +def _vmap( + func: Callable, + in_dims: in_dims_t = 0, + out_dims: out_dims_t = 0, + allow_none_pass_through: bool = False, +) -> Callable: + # The `allow_none_pass_through` argument is a temporary workaround may be removed. + # Currently it enables us to wrap the call in `autograd.grad` to the autograd engine, + # which may return None if any of the inputs are unused. See the issue discussing this: + # https://github.com/pytorch/functorch/issues/159. + @functools.wraps(func) + def wrapped(*args): + _check_out_dims_is_int_or_int_tuple(out_dims, func) + vmap_level = torch._C._vmapmode_increment_nesting() + try: + batched_inputs, batch_size = _create_batched_inputs( + in_dims, args, vmap_level, func + ) + batched_outputs = func(*batched_inputs) + if not allow_none_pass_through: + _validate_outputs(batched_outputs, func) + return _unwrap_batched( + batched_outputs, + out_dims, + vmap_level, + batch_size, + func, + allow_none_pass_through=allow_none_pass_through, + ) + finally: + torch._C._vmapmode_decrement_nesting() + + return wrapped diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_weights_only_unpickler.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_weights_only_unpickler.py new file mode 100644 index 0000000000000000000000000000000000000000..722c8081dfb51bf7a1242f8096a8c2fe009532b9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_weights_only_unpickler.py @@ -0,0 +1,588 @@ +# mypy: allow-untyped-defs +# Unpickler restricted to loading only state dicts +# Restrict constructing types to a list defined in _get_allowed_globals() +# Restrict BUILD operation to `Tensor`, `Parameter` and `OrderedDict` types only +# Restrict APPEND/APPENDS to `list` +# In `GLOBALS` operation do not do class lookup by name, but rather rely on dictionary +# defined by `_get_allowed_globals()` method, that contains: +# - torch types (Storage, dtypes, Tensor, `torch.Size`), +# - `torch._utils._rebuild` functions. +# - `torch.nn.Parameter` +# - `collections.Counter` +# - `collections.OrderedDict` +# Additionally, users can use an allowlist for adding classes they have deemed as safe using +# `_add_safe_globals()` (`torch.serialization.add_safe_globals`) +# `_clear_safe_globals()` (`torch.serialization.clear_safe_globals`) +# `_get_safe_globals()` (`torch.serialization.get_safe_globals`) + +# Based of https://github.com/python/cpython/blob/main/Lib/pickle.py +# Expected to be useful for loading PyTorch model weights +# For example: +# data = urllib.request.urlopen('https://download.pytorch.org/models/resnet50-0676ba61.pth').read() +# buf = io.BytesIO(data) +# weights = torch.load(buf, weights_only = True) + +import functools as _functools +import warnings + +from _codecs import encode +from collections import Counter, OrderedDict +from collections.abc import Callable +from pickle import ( + APPEND, + APPENDS, + BINFLOAT, + BINGET, + BININT, + BININT1, + BININT2, + BINPERSID, + BINPUT, + BINUNICODE, + BUILD, + bytes_types, + decode_long, + EMPTY_DICT, + EMPTY_LIST, + EMPTY_SET, + EMPTY_TUPLE, + GLOBAL, + LONG1, + LONG_BINGET, + LONG_BINPUT, + MARK, + NEWFALSE, + NEWOBJ, + NEWTRUE, + NONE, + PROTO, + REDUCE, + SETITEM, + SETITEMS, + SHORT_BINSTRING, + STOP, + TUPLE, + TUPLE1, + TUPLE2, + TUPLE3, + UnpicklingError, +) +from struct import unpack +from sys import maxsize +from typing import Any + +import torch +from torch._utils import _sparse_tensors_to_validate, IMPORT_MAPPING, NAME_MAPPING + + +# modules in this list are never allowed, even if the user attempts to allowlist +# functions/classes from them +_blocklisted_modules = [ + "sys", + "os", + "posix", + "nt", +] + +_marked_safe_globals_set: set[Callable | tuple[Callable, str]] = set() + + +def _add_safe_globals(safe_globals: list[Callable | tuple[Callable, str]]): + global _marked_safe_globals_set + _marked_safe_globals_set = _marked_safe_globals_set.union(set(safe_globals)) + + +def _get_safe_globals() -> list[Callable | tuple[Callable, str]]: + global _marked_safe_globals_set + return list(_marked_safe_globals_set) + + +def _clear_safe_globals(): + global _marked_safe_globals_set + _marked_safe_globals_set = set() + + +def _remove_safe_globals( + globals_to_remove: list[Callable | tuple[Callable, str]], +): + global _marked_safe_globals_set + _marked_safe_globals_set = _marked_safe_globals_set - set(globals_to_remove) + + +class _safe_globals: + def __init__(self, safe_globals: list[Callable | tuple[Callable, str]]): + self.safe_globals = safe_globals + + def __enter__(self): + _add_safe_globals(self.safe_globals) + + def __exit__(self, type, value, tb): + _remove_safe_globals(self.safe_globals) + + +# Separate from _get_allowed_globals because of the lru_cache on _get_allowed_globals +# For example if user had a script like +# torch.load(file_a) +# torch.serialization._add_safe_globals([torch.foo]) +# torch.load(file_b) +# the dynamic additions to safe_globals would not be picked up by +# _get_allowed_globals due to the lru_cache +def _get_user_allowed_globals(): + rc: dict[str, Any] = {} + for f in _marked_safe_globals_set: + if isinstance(f, tuple): + if len(f) != 2: + raise ValueError( + f"Expected tuple of length 2 (global, str of callable full path), but got tuple of length: {len(f)}" + ) + if type(f[1]) is not str: + raise TypeError( + f"Expected second item in tuple to be str of callable full path, but got: {type(f[1])}" + ) + f, name = f + rc[name] = f + else: + module, name = f.__module__, f.__qualname__ + rc[f"{module}.{name}"] = f + return rc + + +def _tensor_rebuild_functions(): + return { + torch._utils._rebuild_parameter, + torch._utils._rebuild_parameter_with_state, + torch._utils._rebuild_qtensor, + torch._utils._rebuild_tensor, + torch._utils._rebuild_tensor_v2, + torch._utils._rebuild_tensor_v3, + torch._utils._rebuild_sparse_tensor, + torch._utils._rebuild_meta_tensor_no_storage, + torch._utils._rebuild_nested_tensor, + torch._utils._rebuild_wrapper_subclass, + # Allowlisting this, but not allowlisting the numpy functions by default + # Reasoning is that we don't have control over the numpy functions, but + # this utility is provided by pytorch + torch._utils._rebuild_device_tensor_from_numpy, + # In 2.6, we should no longer have a dependency on numpy and the above + # _rebuild_device_tensor_from_numpy function. + torch._utils._rebuild_device_tensor_from_cpu_tensor, + } + + +# Unpickling machinery +@_functools.lru_cache(maxsize=1) +def _get_allowed_globals(): + rc: dict[str, Any] = { + "collections.OrderedDict": OrderedDict, + "collections.Counter": Counter, + "torch.nn.parameter.Parameter": torch.nn.Parameter, + "torch.serialization._get_layout": torch.serialization._get_layout, + "torch.Size": torch.Size, + "torch.Tensor": torch.Tensor, + "torch.device": torch.device, + "_codecs.encode": encode, # for bytes + "builtins.bytearray": bytearray, # for bytearray + "builtins.set": set, # for set + "builtins.complex": complex, # for complex + } + + # dtype + for t in torch.storage._dtype_to_storage_type_map(): + rc[str(t)] = t + for t in torch.storage._new_dtypes(): + rc[str(t)] = t + for t in [getattr(torch, f"uint{x}") for x in range(1, 8)]: + rc[str(t)] = t + for t in [getattr(torch, f"int{x}") for x in range(1, 8)]: + rc[str(t)] = t + + # Tensor classes + for tt in torch._tensor_classes: + rc[f"{tt.__module__}.{tt.__name__}"] = tt + # Storage classes + for ts in torch._storage_classes: + if ts not in (torch.storage.TypedStorage, torch.storage.UntypedStorage): + # Wrap legacy storage types in a dummy class + rc[f"{ts.__module__}.{ts.__name__}"] = torch.serialization.StorageType( + ts.__name__ + ) + else: + rc[f"{ts.__module__}.{ts.__name__}"] = ts + # Quantization specific + for qt in [ + torch.per_tensor_affine, + torch.per_tensor_symmetric, + torch.per_channel_affine, + torch.per_channel_symmetric, + torch.per_channel_affine_float_qparams, + ]: + rc[str(qt)] = qt + # Rebuild functions + for f in _tensor_rebuild_functions(): + rc[f"torch._utils.{f.__name__}"] = f + + # Handles Tensor Subclasses, Tensor's with attributes. + # NOTE: It calls into above rebuild functions for regular Tensor types. + rc["torch._tensor._rebuild_from_type_v2"] = torch._tensor._rebuild_from_type_v2 + return rc + + +def _read_global_instruction(readline: Callable) -> tuple[str, str]: + module = readline()[:-1].decode("utf-8") + name = readline()[:-1].decode("utf-8") + # Patch since torch.save default protocol is 2 + # users will be running this code in python > 3 + if (module, name) in NAME_MAPPING: + module, name = NAME_MAPPING[(module, name)] + elif module in IMPORT_MAPPING: + module = IMPORT_MAPPING[module] + return module, name + + +def get_globals_in_pkl(file) -> set[str]: + globals_in_checkpoint = set() + read = file.read + readline = file.readline + op_to_bytes_to_read = { + NEWOBJ[0]: 0, + REDUCE[0]: 0, + BUILD[0]: 0, + APPEND[0]: 0, + APPENDS[0]: 0, + SETITEM[0]: 0, + SETITEMS[0]: 0, + MARK[0]: 0, + TUPLE[0]: 0, + TUPLE1[0]: 0, + TUPLE2[0]: 0, + TUPLE3[0]: 0, + NONE[0]: 0, + NEWFALSE[0]: 0, + NEWTRUE[0]: 0, + EMPTY_TUPLE[0]: 0, + EMPTY_LIST[0]: 0, + EMPTY_DICT[0]: 0, + EMPTY_SET[0]: 0, + BINPERSID[0]: 0, + BININT[0]: 4, + BININT1[0]: 1, + BININT2[0]: 2, + BINFLOAT[0]: 8, + BINGET[0]: 1, + LONG_BINGET[0]: 4, + BINPUT[0]: 1, + LONG_BINPUT[0]: 4, + } + while True: + key = read(1) + if not key: + raise EOFError + assert isinstance(key, bytes_types) + if key[0] == GLOBAL[0]: + module, name = _read_global_instruction(readline) + globals_in_checkpoint.add(f"{module}.{name}") + elif key[0] in op_to_bytes_to_read: + bytes_to_read = op_to_bytes_to_read[key[0]] + if bytes_to_read: + read(bytes_to_read) + # ops where bytes to read depends on the data + elif key[0] == BINUNICODE[0]: + strlen = unpack(" maxsize: + raise UnpicklingError("String is too long") + read(strlen) + elif key[0] in {SHORT_BINSTRING[0], LONG1[0]}: + strlen = read(1)[0] + read(strlen) + # first and last op + elif key[0] == PROTO[0]: + read(1)[0] + elif key[0] == STOP[0]: + return globals_in_checkpoint + else: + raise UnpicklingError(f"Unsupported operand {key[0]}") + + +class Unpickler: + def __init__(self, file, *, encoding: str = "bytes"): + self.encoding = encoding + self.readline = file.readline + self.read = file.read + self.memo: dict[int, Any] = {} + self.proto: int = -1 + + def load(self): + """Read a pickled object representation from the open file. + + Return the reconstituted object hierarchy specified in the file. + """ + self.metastack = [] + self.stack: list[Any] = [] + self.append = self.stack.append + read = self.read + while True: + key = read(1) + if not key: + raise EOFError + assert isinstance(key, bytes_types) + # Risky operators + if key[0] == GLOBAL[0]: + module, name = _read_global_instruction(self.readline) + full_path = f"{module}.{name}" + if module in _blocklisted_modules: + raise UnpicklingError( + f"Trying to load unsupported GLOBAL {full_path} whose module {module} is blocked." + ) + if full_path in _get_allowed_globals(): + self.append(_get_allowed_globals()[full_path]) + elif full_path in _get_user_allowed_globals(): + self.append(_get_user_allowed_globals()[full_path]) + elif full_path in ( + [ + "torch.nested._internal.nested_tensor.NestedTensor", + "torch.nested._internal.nested_tensor._rebuild_njt", + "torch._dynamo.decorators._DimRange", + ] + ): + raise UnpicklingError( + "``torch.nested`` and ``torch._dynamo`` must be imported to load nested jagged tensors (NJTs)" + ) + elif full_path in ( + [ + "torch.distributed.device_mesh.DeviceMesh", + "torch.distributed.tensor._dtensor_spec.DTensorSpec", + "torch.distributed.tensor._dtensor_spec.TensorMeta", + "torch.distributed.tensor.DTensor", + "torch.distributed.tensor.placement_types.Partial", + "torch.distributed.tensor.placement_types.Replicate", + "torch.distributed.tensor.placement_types.Shard", + ] + ): + raise UnpicklingError( + "``torch.distributed.tensor`` must be imported to load DTensors" + ) + else: + builtins_name = "builtins" + if ( + builtins_name in full_path + and builtins_name == full_path[: len(builtins_name)] + ): + full_path = full_path[len(builtins_name) :] + full_path = ( + full_path[1:] + if len(full_path) > 0 and full_path[0] == "." + else builtins_name + full_path + ) + raise UnpicklingError( + f"Unsupported global: GLOBAL {full_path} was not an allowed global by default. " + f"Please use `torch.serialization.add_safe_globals([{full_path}])` or the " + f"`torch.serialization.safe_globals([{full_path}])` context manager to allowlist this global " + "if you trust this class/function." + ) + elif key[0] == NEWOBJ[0]: + args = self.stack.pop() + cls = self.stack.pop() + if cls is torch.nn.Parameter: + self.append(torch.nn.Parameter(*args)) + elif ( + cls in _get_user_allowed_globals().values() + or cls in _get_allowed_globals().values() + ): + result = cls.__new__(cls, *args) + if cls in torch._tensor_classes and "sparse" in cls.__module__: + _sparse_tensors_to_validate.append(result) + self.append(result) + else: + raise UnpicklingError( + "Can only create new object for nn.Parameter or classes allowlisted " + f"via `add_safe_globals` but got {cls}" + ) + elif key[0] == REDUCE[0]: + args = self.stack.pop() + func = self.stack[-1] + if ( + func not in _get_allowed_globals().values() + and func not in _get_user_allowed_globals().values() + ): + error_msg = ( + f"Trying to call reduce for unrecognized function {func}" + ) + if hasattr(func, "__self__"): + error_msg += f" which belongs to {func.__self__}" + raise UnpicklingError(error_msg) + result = func(*args) + if func in torch._tensor_classes and "sparse" in func.__module__: + _sparse_tensors_to_validate.append(result) + self.stack[-1] = result + elif key[0] == BUILD[0]: + state = self.stack.pop() + inst = self.stack[-1] + if type(inst) is torch.Tensor: + # Legacy unpickling + # pyrefly: ignore [not-iterable] + inst.set_(*state) + elif type(inst) is torch.nn.Parameter: + inst.__setstate__(state) + elif type(inst) is OrderedDict: + inst.__dict__.update(state) + elif ( + type(inst) in _get_user_allowed_globals().values() + or type(inst) in _get_allowed_globals().values() + ): + if hasattr(inst, "__setstate__"): + inst.__setstate__(state) + else: + # mimics load_build in pickle + # https://github.com/python/cpython/blob/f0c6fccd08904787a39269367f09f263d496114c/Lib/pickle.py#L1854-L1867 + slotstate = None + if isinstance(state, tuple) and len(state) == 2: + state, slotstate = state + if state: + inst.__dict__.update(state) + if slotstate: + for k, v in slotstate.items(): + setattr(inst, k, v) + else: + raise UnpicklingError( + "Can only build Tensor, Parameter, OrderedDict or types allowlisted " + f"via `add_safe_globals`, but got {type(inst)}" + ) + # Stack manipulation + elif key[0] == APPEND[0]: + item = self.stack.pop() + list_obj = self.stack[-1] + if type(list_obj) is not list: + raise UnpicklingError( + f"Can only append to lists, but got {type(list_obj)}" + ) + list_obj.append(item) + elif key[0] == APPENDS[0]: + items = self.pop_mark() + list_obj = self.stack[-1] + if type(list_obj) is not list: + raise UnpicklingError( + f"Can only extend lists, but got {type(list_obj)}" + ) + list_obj.extend(items) + elif key[0] == SETITEM[0]: + (v, k) = (self.stack.pop(), self.stack.pop()) + self._check_set_item_target("SETITEM") + self.stack[-1][k] = v + elif key[0] == SETITEMS[0]: + items = self.pop_mark() + self._check_set_item_target("SETITEMS") + for i in range(0, len(items), 2): + self.stack[-1][items[i]] = items[i + 1] + elif key[0] == MARK[0]: + self.metastack.append(self.stack) + self.stack = [] + self.append = self.stack.append + elif key[0] == TUPLE[0]: + items = self.pop_mark() + self.append(tuple(items)) + elif key[0] == TUPLE1[0]: + self.stack[-1] = (self.stack[-1],) + elif key[0] == TUPLE2[0]: + self.stack[-2:] = [(self.stack[-2], self.stack[-1])] + elif key[0] == TUPLE3[0]: + self.stack[-3:] = [(self.stack[-3], self.stack[-2], self.stack[-1])] + # Basic types construction + elif key[0] == NONE[0]: + self.append(None) + elif key[0] == NEWFALSE[0]: + self.append(False) + elif key[0] == NEWTRUE[0]: + self.append(True) + elif key[0] == EMPTY_TUPLE[0]: + self.append(()) + elif key[0] == EMPTY_LIST[0]: + self.append([]) + elif key[0] == EMPTY_DICT[0]: + self.append({}) + elif key[0] == EMPTY_SET[0]: + self.append(set()) + elif key[0] == BININT[0]: + self.append(unpack("d", self.read(8))[0]) + elif key[0] == BINUNICODE[0]: + strlen = unpack(" maxsize: + raise UnpicklingError("String is too long") + strval = str(read(strlen), "utf-8", "surrogatepass") + self.append(strval) + elif key[0] == SHORT_BINSTRING[0]: + strlen = read(1)[0] + strdata = read(strlen) + if self.encoding != "bytes": + strdata = strdata.decode(self.encoding, "strict") + self.append(strdata) + elif key[0] == BINPERSID[0]: + pid = self.stack.pop() + # Only allow persistent load of storage + if type(pid) is not tuple and type(pid) is not int: + raise UnpicklingError( + f"persistent_load id must be tuple or int, but got {type(pid)}" + ) + if ( + type(pid) is tuple + and len(pid) > 0 + and torch.serialization._maybe_decode_ascii(pid[0]) != "storage" + ): + raise UnpicklingError( + f"Only persistent_load of storage is allowed, but got {type(pid[0])}" + ) + self.append(self.persistent_load(pid)) + elif key[0] in [BINGET[0], LONG_BINGET[0]]: + idx = (read(1) if key[0] == BINGET[0] else unpack(" List of Tensors + + Broadcasts the given tensors according to :ref:`broadcasting-semantics`. + + Args: + *tensors: any number of tensors of the same type + + .. warning:: + + More than one element of a broadcasted tensor may refer to a single + memory location. As a result, in-place operations (especially ones that + are vectorized) may result in incorrect behavior. If you need to write + to the tensors, please clone them first. + + Example:: + + >>> x = torch.arange(3).view(1, 3) + >>> y = torch.arange(2).view(2, 1) + >>> a, b = torch.broadcast_tensors(x, y) + >>> a.size() + torch.Size([2, 3]) + >>> a + tensor([[0, 1, 2], + [0, 1, 2]]) + """ + # This wrapper exists to support variadic args. + if has_torch_function(tensors): + return handle_torch_function(broadcast_tensors, tensors, *tensors) + return _VF.broadcast_tensors(tensors) # type: ignore[attr-defined] + + +def broadcast_shapes(*shapes): + r"""broadcast_shapes(*shapes) -> Size + + Similar to :func:`broadcast_tensors` but for shapes. + + This is equivalent to + ``torch.broadcast_tensors(*map(torch.empty, shapes))[0].shape`` + but avoids the need create to intermediate tensors. This is useful for + broadcasting tensors of common batch shape but different rightmost shape, + e.g. to broadcast mean vectors with covariance matrices. + + Example:: + + >>> torch.broadcast_shapes((2,), (3, 1), (1, 1, 1)) + torch.Size([1, 3, 2]) + + Args: + \*shapes (torch.Size): Shapes of tensors. + + Returns: + shape (torch.Size): A shape compatible with all input shapes. + + Raises: + RuntimeError: If shapes are incompatible. + """ + # This wrapper exists to support variadic args. + # TODO Move this to C++ once the jit has better support for torch.Size. + if not torch.jit.is_tracing(): + result = torch._refs._broadcast_shapes(*shapes) + if result is None: + return torch.Size([]) + return torch.Size(result) + else: + # with implementation above, torch.jit.trace hardcodes the sizes which makes subsequent replays fail + with torch.no_grad(): + scalar = torch.zeros((), device="cpu") + tensors = [scalar.expand(shape) for shape in shapes] + tensors = broadcast_tensors(*tensors) + return tensors[0].shape + + +def split( + tensor: Tensor, + split_size_or_sections: int | list[int], + dim: int = 0, +) -> tuple[Tensor, ...]: + r"""Splits the tensor into chunks. Each chunk is a view of the original tensor. + + If :attr:`split_size_or_sections` is an integer type, then :attr:`tensor` will + be split into equally sized chunks (if possible). Last chunk will be smaller if + the tensor size along the given dimension :attr:`dim` is not divisible by + :attr:`split_size`. + + If :attr:`split_size_or_sections` is a list, then :attr:`tensor` will be split + into ``len(split_size_or_sections)`` chunks with sizes in :attr:`dim` according + to :attr:`split_size_or_sections`. + + Args: + tensor (Tensor): tensor to split. + split_size_or_sections (int) or (list(int)): size of a single chunk or + list of sizes for each chunk + dim (int): dimension along which to split the tensor. + + Example:: + + >>> a = torch.arange(10).reshape(5, 2) + >>> a + tensor([[0, 1], + [2, 3], + [4, 5], + [6, 7], + [8, 9]]) + >>> torch.split(a, 2) + (tensor([[0, 1], + [2, 3]]), + tensor([[4, 5], + [6, 7]]), + tensor([[8, 9]])) + >>> torch.split(a, [1, 4]) + (tensor([[0, 1]]), + tensor([[2, 3], + [4, 5], + [6, 7], + [8, 9]])) + """ + if has_torch_function_unary(tensor): + return handle_torch_function( + split, (tensor,), tensor, split_size_or_sections, dim=dim + ) + # Overwriting reason: + # This dispatches to two ATen functions depending on the type of + # split_size_or_sections. The branching code is in _tensor.py, which we + # call here. + return tensor.split(split_size_or_sections, dim) + + +def einsum(*args: Any) -> Tensor: + r"""einsum(equation, *operands) -> Tensor + + Sums the product of the elements of the input :attr:`operands` along dimensions specified using a notation + based on the Einstein summation convention. + + Einsum allows computing many common multi-dimensional linear algebraic array operations by representing them + in a short-hand format based on the Einstein summation convention, given by :attr:`equation`. The details of + this format are described below, but the general idea is to label every dimension of the input :attr:`operands` + with some subscript and define which subscripts are part of the output. The output is then computed by summing + the product of the elements of the :attr:`operands` along the dimensions whose subscripts are not part of the + output. For example, matrix multiplication can be computed using einsum as `torch.einsum("ij,jk->ik", A, B)`. + Here, j is the summation subscript and i and k the output subscripts (see section below for more details on why). + + Equation: + + The :attr:`equation` string specifies the subscripts (letters in `[a-zA-Z]`) for each dimension of + the input :attr:`operands` in the same order as the dimensions, separating subscripts for each operand by a + comma (','), e.g. `'ij,jk'` specify subscripts for two 2D operands. The dimensions labeled with the same subscript + must be broadcastable, that is, their size must either match or be `1`. The exception is if a subscript is + repeated for the same input operand, in which case the dimensions labeled with this subscript for this operand + must match in size and the operand will be replaced by its diagonal along these dimensions. The subscripts that + appear exactly once in the :attr:`equation` will be part of the output, sorted in increasing alphabetical order. + The output is computed by multiplying the input :attr:`operands` element-wise, with their dimensions aligned based + on the subscripts, and then summing out the dimensions whose subscripts are not part of the output. + + Optionally, the output subscripts can be explicitly defined by adding an arrow ('->') at the end of the equation + followed by the subscripts for the output. For instance, the following equation computes the transpose of a + matrix multiplication: 'ij,jk->ki'. The output subscripts must appear at least once for some input operand and + at most once for the output. + + Ellipsis ('...') can be used in place of subscripts to broadcast the dimensions covered by the ellipsis. + Each input operand may contain at most one ellipsis which will cover the dimensions not covered by subscripts, + e.g. for an input operand with 5 dimensions, the ellipsis in the equation `'ab...c'` cover the third and fourth + dimensions. The ellipsis does not need to cover the same number of dimensions across the :attr:`operands` but the + 'shape' of the ellipsis (the size of the dimensions covered by them) must broadcast together. If the output is not + explicitly defined with the arrow ('->') notation, the ellipsis will come first in the output (left-most dimensions), + before the subscript labels that appear exactly once for the input operands. e.g. the following equation implements + batch matrix multiplication `'...ij,...jk'`. + + A few final notes: the equation may contain whitespaces between the different elements (subscripts, ellipsis, + arrow and comma) but something like `'. . .'` is not valid. An empty string `''` is valid for scalar operands. + + .. note:: + + ``torch.einsum`` handles ellipsis ('...') differently from NumPy in that it allows dimensions + covered by the ellipsis to be summed over, that is, ellipsis are not required to be part of the output. + + .. note:: + + Please install opt-einsum (https://optimized-einsum.readthedocs.io/en/stable/) in order to enroll into a more + performant einsum. You can install when installing torch like so: `pip install torch[opt-einsum]` or by itself + with `pip install opt-einsum`. + + If opt-einsum is available, this function will automatically speed up computation and/or consume less memory + by optimizing contraction order through our opt_einsum backend :mod:`torch.backends.opt_einsum` (The _ vs - is + confusing, I know). This optimization occurs when there are at least three inputs, since the order does not matter + otherwise. Note that finding `the` optimal path is an NP-hard problem, thus, opt-einsum relies on different + heuristics to achieve near-optimal results. If opt-einsum is not available, the default order is to contract + from left to right. + + To bypass this default behavior, add the following to disable opt_einsum and skip path calculation: + ``torch.backends.opt_einsum.enabled = False`` + + To specify which strategy you'd like for opt_einsum to compute the contraction path, add the following line: + ``torch.backends.opt_einsum.strategy = 'auto'``. The default strategy is 'auto', and we also support 'greedy' and + 'optimal'. Disclaimer that the runtime of 'optimal' is factorial in the number of inputs! See more details in + the opt_einsum documentation (https://optimized-einsum.readthedocs.io/en/stable/path_finding.html). + + .. note:: + + As of PyTorch 1.10 :func:`torch.einsum` also supports the sublist format (see examples below). In this format, + subscripts for each operand are specified by sublists, list of integers in the range [0, 52). These sublists + follow their operands, and an extra sublist can appear at the end of the input to specify the output's + subscripts., e.g. `torch.einsum(op1, sublist1, op2, sublist2, ..., [subslist_out])`. Python's `Ellipsis` object + may be provided in a sublist to enable broadcasting as described in the Equation section above. + + Args: + equation (str): The subscripts for the Einstein summation. + operands (List[Tensor]): The tensors to compute the Einstein summation of. + + Examples:: + + >>> # xdoctest: +IGNORE_WANT("non-deterministic") + >>> # trace + >>> torch.einsum('ii', torch.randn(4, 4)) + tensor(-1.2104) + + >>> # xdoctest: +IGNORE_WANT("non-deterministic") + >>> # diagonal + >>> torch.einsum('ii->i', torch.randn(4, 4)) + tensor([-0.1034, 0.7952, -0.2433, 0.4545]) + + >>> # xdoctest: +IGNORE_WANT("non-deterministic") + >>> # outer product + >>> x = torch.randn(5) + >>> y = torch.randn(4) + >>> torch.einsum('i,j->ij', x, y) + tensor([[ 0.1156, -0.2897, -0.3918, 0.4963], + [-0.3744, 0.9381, 1.2685, -1.6070], + [ 0.7208, -1.8058, -2.4419, 3.0936], + [ 0.1713, -0.4291, -0.5802, 0.7350], + [ 0.5704, -1.4290, -1.9323, 2.4480]]) + + >>> # xdoctest: +IGNORE_WANT("non-deterministic") + >>> # batch matrix multiplication + >>> As = torch.randn(3, 2, 5) + >>> Bs = torch.randn(3, 5, 4) + >>> torch.einsum('bij,bjk->bik', As, Bs) + tensor([[[-1.0564, -1.5904, 3.2023, 3.1271], + [-1.6706, -0.8097, -0.8025, -2.1183]], + + [[ 4.2239, 0.3107, -0.5756, -0.2354], + [-1.4558, -0.3460, 1.5087, -0.8530]], + + [[ 2.8153, 1.8787, -4.3839, -1.2112], + [ 0.3728, -2.1131, 0.0921, 0.8305]]]) + + >>> # xdoctest: +IGNORE_WANT("non-deterministic") + >>> # with sublist format and ellipsis + >>> torch.einsum(As, [..., 0, 1], Bs, [..., 1, 2], [..., 0, 2]) + tensor([[[-1.0564, -1.5904, 3.2023, 3.1271], + [-1.6706, -0.8097, -0.8025, -2.1183]], + + [[ 4.2239, 0.3107, -0.5756, -0.2354], + [-1.4558, -0.3460, 1.5087, -0.8530]], + + [[ 2.8153, 1.8787, -4.3839, -1.2112], + [ 0.3728, -2.1131, 0.0921, 0.8305]]]) + + >>> # batch permute + >>> A = torch.randn(2, 3, 4, 5) + >>> torch.einsum('...ij->...ji', A).shape + torch.Size([2, 3, 5, 4]) + + >>> # equivalent to torch.nn.functional.bilinear + >>> A = torch.randn(3, 5, 4) + >>> l = torch.randn(2, 5) + >>> r = torch.randn(2, 4) + >>> torch.einsum('bn,anm,bm->ba', l, A, r) + tensor([[-0.3430, -5.2405, 0.4494], + [ 0.3311, 5.5201, -3.0356]]) + """ + import torch.backends.opt_einsum as opt_einsum + + # This wrapper exists to support variadic args. + if len(args) < 2: + raise ValueError( + "einsum(): must specify the equation string and at least one operand, " + "or at least one operand and its subscripts list" + ) + + equation = None + operands = None + + if isinstance(args[0], torch.Tensor): + # Convert the subscript list format which is an interleaving of operand and its subscripts + # list with an optional output subscripts list at the end (see documentation for more details on this) + # to the equation string format by creating the equation string from the subscripts list and grouping the + # input operands into a tensorlist (List[Tensor]). + def parse_subscript(n: int) -> str: + if n == Ellipsis: + return "..." + if n >= 0 and n < 26: + return chr(ord("A") + n) + if n >= 26 and n < 52: + return chr(ord("a") + n - 26) + raise ValueError( + "einsum(): subscript in subscript list is not within the valid range [0, 52)" + ) + + # Parse subscripts for input operands + equation = ",".join("".join(parse_subscript(s) for s in l) for l in args[1::2]) + + # Parse optional output subscripts (provided when the number of arguments is odd) + if len(args) % 2 == 1: + equation += "->" + "".join(parse_subscript(s) for s in args[-1]) + operands = args[:-1:2] + else: + operands = args[::2] + else: + equation = args[0] + operands = args[1:] + + if has_torch_function(operands): + return handle_torch_function(einsum, operands, equation, *operands) + + if len(operands) == 1 and isinstance(operands[0], (list, tuple)): + # the old interface of passing the operands as one list argument + _operands = operands[0] + # recurse in case operands contains value that has torch function + # in the original implementation this line is omitted + return einsum(equation, *_operands) + + if len(operands) <= 2 or not opt_einsum.enabled: + # the path for contracting 0 or 1 time(s) is already optimized + # or the user has disabled using opt_einsum + return _VF.einsum(equation, operands) # type: ignore[attr-defined] + + path = None + if opt_einsum.is_available(): + _opt_einsum = opt_einsum.get_opt_einsum() + tupled_path = _opt_einsum.contract_path( + equation, *operands, optimize=opt_einsum.strategy + )[0] + # flatten path for dispatching to C++ + path = [*itertools.chain.from_iterable(tupled_path)] + return _VF.einsum(equation, operands, path=path) # type: ignore[attr-defined] + + +# This wrapper exists to support variadic args. +if TYPE_CHECKING: + # The JIT doesn't understand Union, so only add type annotation for mypy + def meshgrid( + *tensors: Tensor | list[Tensor], indexing: str | None = None + ) -> tuple[Tensor, ...]: + return _meshgrid(*tensors, indexing=indexing) + +else: + + def meshgrid(*tensors, indexing: str | None = None) -> tuple[Tensor, ...]: + r"""Creates grids of coordinates specified by the 1D inputs in `attr`:tensors. + + This is helpful when you want to visualize data over some + range of inputs. See below for a plotting example. + + Given :math:`N` 1D tensors :math:`T_0 \ldots T_{N-1}` as + inputs with corresponding sizes :math:`S_0 \ldots S_{N-1}`, + this creates :math:`N` N-dimensional tensors :math:`G_0 \ldots + G_{N-1}`, each with shape :math:`(S_0, ..., S_{N-1})` where + the output :math:`G_i` is constructed by expanding :math:`T_i` + to the result shape. + + .. note:: + 0D inputs are treated equivalently to 1D inputs of a + single element. + + .. warning:: + `torch.meshgrid(*tensors)` currently has the same behavior + as calling `numpy.meshgrid(*arrays, indexing='ij')`. + + In the future `torch.meshgrid` will transition to + `indexing='xy'` as the default. + + https://github.com/pytorch/pytorch/issues/50276 tracks + this issue with the goal of migrating to NumPy's behavior. + + .. seealso:: + + :func:`torch.cartesian_prod` has the same effect but it + collects the data in a tensor of vectors. + + Args: + tensors (list of Tensor): list of scalars or 1 dimensional tensors. Scalars will be + treated as tensors of size :math:`(1,)` automatically + + indexing: (str, optional): the indexing mode, either "xy" + or "ij", defaults to "ij". See warning for future changes. + + If "xy" is selected, the first dimension corresponds + to the cardinality of the second input and the second + dimension corresponds to the cardinality of the first + input. + + If "ij" is selected, the dimensions are in the same + order as the cardinality of the inputs. + + Returns: + seq (sequence of Tensors): If the input has :math:`N` + tensors of size :math:`S_0 \ldots S_{N-1}``, then the + output will also have :math:`N` tensors, where each tensor + is of shape :math:`(S_0, ..., S_{N-1})`. + + Example:: + + >>> x = torch.tensor([1, 2, 3]) + >>> y = torch.tensor([4, 5, 6]) + + Observe the element-wise pairings across the grid, (1, 4), + (1, 5), ..., (3, 6). This is the same thing as the + cartesian product. + >>> grid_x, grid_y = torch.meshgrid(x, y, indexing='ij') + >>> grid_x + tensor([[1, 1, 1], + [2, 2, 2], + [3, 3, 3]]) + >>> grid_y + tensor([[4, 5, 6], + [4, 5, 6], + [4, 5, 6]]) + + This correspondence can be seen when these grids are + stacked properly. + >>> torch.equal(torch.cat(tuple(torch.dstack([grid_x, grid_y]))), + ... torch.cartesian_prod(x, y)) + True + + `torch.meshgrid` is commonly used to produce a grid for + plotting. + >>> # xdoctest: +REQUIRES(module:matplotlib) + >>> # xdoctest: +REQUIRES(env:DOCTEST_SHOW) + >>> import matplotlib.pyplot as plt + >>> xs = torch.linspace(-5, 5, steps=100) + >>> ys = torch.linspace(-5, 5, steps=100) + >>> x, y = torch.meshgrid(xs, ys, indexing='xy') + >>> z = torch.sin(torch.sqrt(x * x + y * y)) + >>> ax = plt.axes(projection='3d') + >>> ax.plot_surface(x.numpy(), y.numpy(), z.numpy()) + >>> plt.show() + + .. image:: ../_static/img/meshgrid.png + :width: 512 + + """ + return _meshgrid(*tensors, indexing=indexing) + + +def _meshgrid(*tensors, indexing: str | None): + if has_torch_function(tensors): + return handle_torch_function(meshgrid, tensors, *tensors, indexing=indexing) + if len(tensors) == 1 and isinstance(tensors[0], (list, tuple)): + # the old interface of passing the operands as one list argument + tensors = tensors[0] # type: ignore[assignment] + + # Continue allowing call of old method that takes no indexing + # kwarg for forward compatibility reasons. + # + # Remove this two weeks after landing. + kwargs = {} if indexing is None else {"indexing": indexing} + return _VF.meshgrid(tensors, **kwargs) # type: ignore[attr-defined] + + +def stft( + input: Tensor, + n_fft: int, + hop_length: int | None = None, + win_length: int | None = None, + window: Tensor | None = None, + center: bool = True, + pad_mode: str = "reflect", + normalized: bool = False, + onesided: bool | None = None, + return_complex: bool | None = None, + align_to_window: bool | None = None, +) -> Tensor: + r"""Short-time Fourier transform (STFT). + + .. warning:: + From version 1.8.0, :attr:`return_complex` must always be given + explicitly for real inputs and `return_complex=False` has been + deprecated. Strongly prefer `return_complex=True` as in a future + pytorch release, this function will only return complex tensors. + + Note that :func:`torch.view_as_real` can be used to recover a real + tensor with an extra last dimension for real and imaginary components. + + .. warning:: + From version 2.1, a warning will be provided if a :attr:`window` is + not specified. In a future release, this attribute will be required. + Not providing a window currently defaults to using a rectangular window, + which may result in undesirable artifacts. Consider using tapered windows, + such as :func:`torch.hann_window`. + + The STFT computes the Fourier transform of short overlapping windows of the + input. This giving frequency components of the signal as they change over + time. The interface of this function is modeled after (but *not* a drop-in + replacement for) librosa_ stft function. + + .. _librosa: https://librosa.org/doc/latest/generated/librosa.stft.html + + Ignoring the optional batch dimension, this method computes the following + expression: + + .. math:: + X[\omega, m] = \sum_{k = 0}^{\text{win\_length-1}}% + \text{window}[k]\ \text{input}[m \times \text{hop\_length} + k]\ % + \exp\left(- j \frac{2 \pi \cdot \omega k}{\text{n\_fft}}\right), + + where :math:`m` is the index of the sliding window, and :math:`\omega` is + the frequency :math:`0 \leq \omega < \text{n\_fft}` for ``onesided=False``, + or :math:`0 \leq \omega < \lfloor \text{n\_fft} / 2 \rfloor + 1` for ``onesided=True``. + + * :attr:`input` must be either a 1-D time sequence or a 2-D batch of time + sequences. + + * If :attr:`hop_length` is ``None`` (default), it is treated as equal to + ``floor(n_fft / 4)``. + + * If :attr:`win_length` is ``None`` (default), it is treated as equal to + :attr:`n_fft`. + + * :attr:`window` can be a 1-D tensor of size :attr:`win_length`, e.g., from + :meth:`torch.hann_window`. If :attr:`window` is ``None`` (default), it is + treated as if having :math:`1` everywhere in the window. If + :math:`\text{win\_length} < \text{n\_fft}`, :attr:`window` will be padded on + both sides to length :attr:`n_fft` before being applied. + + * If :attr:`center` is ``True`` (default), :attr:`input` will be padded on + both sides so that the :math:`t`-th frame is centered at time + :math:`t \times \text{hop\_length}`. Otherwise, the :math:`t`-th frame + begins at time :math:`t \times \text{hop\_length}`. + + * :attr:`pad_mode` determines the padding method used on :attr:`input` when + :attr:`center` is ``True``. See :meth:`torch.nn.functional.pad` for + all available options. Default is ``"reflect"``. + + * If :attr:`onesided` is ``True`` (default for real input), only values for + :math:`\omega` in :math:`\left[0, 1, 2, \dots, \left\lfloor + \frac{\text{n\_fft}}{2} \right\rfloor + 1\right]` are returned because + the real-to-complex Fourier transform satisfies the conjugate symmetry, + i.e., :math:`X[m, \omega] = X[m, \text{n\_fft} - \omega]^*`. + Note if the input or window tensors are complex, then :attr:`onesided` + output is not possible. + + * If :attr:`normalized` is ``True`` (default is ``False``), the function + returns the normalized STFT results, i.e., multiplied by :math:`(\text{frame\_length})^{-0.5}`. + + * If :attr:`return_complex` is ``True`` (default if input is complex), the + return is a ``input.dim() + 1`` dimensional complex tensor. If ``False``, + the output is a ``input.dim() + 2`` dimensional real tensor where the last + dimension represents the real and imaginary components. + + Returns either a complex tensor of size :math:`(* \times N \times T)` if + :attr:`return_complex` is true, or a real tensor of size :math:`(* \times N + \times T \times 2)`. Where :math:`*` is the optional batch size of + :attr:`input`, :math:`N` is the number of frequencies where STFT is applied + and :math:`T` is the total number of frames used. + + .. warning:: + This function changed signature at version 0.4.1. Calling with the + previous signature may cause error or return incorrect result. + + Args: + input (Tensor): the input tensor of shape `(B?, L)` where `B?` is an optional + batch dimension + n_fft (int): size of Fourier transform + hop_length (int, optional): the distance between neighboring sliding window + frames. Default: ``None`` (treated as equal to ``floor(n_fft / 4)``) + win_length (int, optional): the size of window frame and STFT filter. + Default: ``None`` (treated as equal to :attr:`n_fft`) + window (Tensor, optional): the optional window function. + Shape must be 1d and `<= n_fft` + Default: ``None`` (treated as window of all :math:`1` s) + center (bool, optional): whether to pad :attr:`input` on both sides so + that the :math:`t`-th frame is centered at time :math:`t \times \text{hop\_length}`. + Default: ``True`` + pad_mode (str, optional): controls the padding method used when + :attr:`center` is ``True``. Default: ``"reflect"`` + normalized (bool, optional): controls whether to return the normalized STFT results + Default: ``False`` + onesided (bool, optional): controls whether to return half of results to + avoid redundancy for real inputs. + Default: ``True`` for real :attr:`input` and :attr:`window`, ``False`` otherwise. + return_complex (bool, optional): whether to return a complex tensor, or + a real tensor with an extra last dimension for the real and + imaginary components. + + .. versionchanged:: 2.0 + ``return_complex`` is now a required argument for real inputs, + as the default is being transitioned to ``True``. + + .. deprecated:: 2.0 + ``return_complex=False`` is deprecated, instead use ``return_complex=True`` + Note that calling :func:`torch.view_as_real` on the output will + recover the deprecated output format. + + Returns: + Tensor: A tensor containing the STFT result with shape `(B?, N, T, C?)` where + - `B?` is an optional batch dimension from the input. + - `N` is the number of frequency samples, `(n_fft // 2) + 1` for + `onesided=True`, or otherwise `n_fft`. + - `T` is the number of frames, `1 + L // hop_length` + for `center=True`, or `1 + (L - n_fft) // hop_length` otherwise. + - `C?` is an optional length-2 dimension of real and imaginary + components, present when `return_complex=False`. + + """ + if has_torch_function_unary(input): + return handle_torch_function( + stft, + (input,), + input, + n_fft, + hop_length=hop_length, + win_length=win_length, + window=window, + center=center, + pad_mode=pad_mode, + normalized=normalized, + onesided=onesided, + return_complex=return_complex, + align_to_window=align_to_window, + ) + if center and align_to_window is not None: + raise RuntimeError( + "stft align_to_window should only be set when center = false" + ) + # NOTE: Do not edit. This code will be removed once the forward-compatibility + # period is over for PR #73432 + if center: + signal_dim = input.dim() + extended_shape = [1] * (3 - signal_dim) + list(input.size()) + pad = int(n_fft // 2) + input = F.pad(input.view(extended_shape), [pad, pad], pad_mode) + input = input.view(input.shape[-signal_dim:]) + return _VF.stft( # type: ignore[attr-defined] + input, + n_fft, + hop_length, + win_length, + window, + normalized, + onesided, + return_complex, + align_to_window, + ) + + +istft = _add_docstr( + torch.istft, + "istft(input, n_fft, hop_length=None, win_length=None, window=None, center=True, " + "normalized=False, onesided=None, length=None, return_complex=False) -> Tensor:\n" + r""" +Inverse short time Fourier Transform. This is expected to be the inverse of :func:`~torch.stft`. + +.. warning:: + From version 2.1, a warning will be provided if a :attr:`window` is + not specified. In a future release, this attribute will be required. + Please provide the same window used in the stft call. + +It has the same parameters (+ additional optional parameter of :attr:`length`) and it should return the +least squares estimation of the original signal. The algorithm will check using the NOLA condition ( +nonzero overlap). + +Important consideration in the parameters :attr:`window` and :attr:`center` so that the envelope +created by the summation of all the windows is never zero at certain point in time. Specifically, +:math:`\sum_{t=-\infty}^{\infty} |w|^2[n-t\times hop\_length] \cancel{=} 0`. + +Since :func:`~torch.stft` discards elements at the end of the signal if they do not fit in a frame, +``istft`` may return a shorter signal than the original signal (can occur if :attr:`center` is False +since the signal isn't padded). If `length` is given in the arguments and is longer than expected, +``istft`` will pad zeros to the end of the returned signal. + +If :attr:`center` is ``True``, then there will be padding e.g. ``'constant'``, ``'reflect'``, etc. +Left padding can be trimmed off exactly because they can be calculated but right padding cannot be +calculated without additional information. + +Example: Suppose the last window is: +``[17, 18, 0, 0, 0]`` vs ``[18, 0, 0, 0, 0]`` + +The :attr:`n_fft`, :attr:`hop_length`, :attr:`win_length` are all the same which prevents the calculation +of right padding. These additional values could be zeros or a reflection of the signal so providing +:attr:`length` could be useful. If :attr:`length` is ``None`` then padding will be aggressively removed +(some loss of signal). + +[1] D. W. Griffin and J. S. Lim, "Signal estimation from modified short-time Fourier transform," +IEEE Trans. ASSP, vol.32, no.2, pp.236-243, Apr. 1984. + +Args: + input (Tensor): The input tensor. Expected to be in the format of :func:`~torch.stft`, + output. That is a complex tensor of shape `(B?, N, T)` where + + - `B?` is an optional batch dimension + - `N` is the number of frequency samples, `(n_fft // 2) + 1` + for onesided input, or otherwise `n_fft`. + - `T` is the number of frames, `1 + length // hop_length` for centered stft, + or `1 + (length - n_fft) // hop_length` otherwise. + + .. versionchanged:: 2.0 + Real datatype inputs are no longer supported. Input must now have a + complex datatype, as returned by ``stft(..., return_complex=True)``. + n_fft (int): Size of Fourier transform + hop_length (Optional[int]): The distance between neighboring sliding window frames. + (Default: ``n_fft // 4``) + win_length (Optional[int]): The size of window frame and STFT filter. (Default: ``n_fft``) + window (Optional[torch.Tensor]): The optional window function. + Shape must be 1d and `<= n_fft` + (Default: ``torch.ones(win_length)``) + center (bool): Whether :attr:`input` was padded on both sides so that the :math:`t`-th frame is + centered at time :math:`t \times \text{hop\_length}`. + (Default: ``True``) + normalized (bool): Whether the STFT was normalized. (Default: ``False``) + onesided (Optional[bool]): Whether the STFT was onesided. + (Default: ``True`` if `n_fft != fft_size` in the input size) + length (Optional[int]): The amount to trim the signal by (i.e. the + original signal length). Defaults to `(T - 1) * hop_length` for + centered stft, or `n_fft + (T - 1) * hop_length` otherwise, where `T` + is the number of input frames. + return_complex (Optional[bool]): + Whether the output should be complex, or if the input should be + assumed to derive from a real signal and window. + Note that this is incompatible with ``onesided=True``. + (Default: ``False``) + +Returns: + Tensor: Least squares estimation of the original signal of shape `(B?, length)` where + `B?` is an optional batch dimension from the input tensor. +""", +) + + +if TYPE_CHECKING: + # These _impl functions return a variable number of tensors as output with + # __torch_function__; tuple unpacking is done already rather than being + # done by the caller of the _impl function + _unique_impl_out = Any +else: + _unique_impl_out = tuple[Tensor, Tensor, Tensor] + + +def _unique_impl( + input: Tensor, + sorted: bool = True, + return_inverse: bool = False, + return_counts: bool = False, + dim: int | None = None, +) -> _unique_impl_out: + r"""unique(input, sorted=True, return_inverse=False, return_counts=False, dim=None) -> tuple[Tensor, Tensor, Tensor] + + Returns the unique elements of the input tensor. + + .. note:: This function is different from :func:`torch.unique_consecutive` in the sense that + this function also eliminates non-consecutive duplicate values. + + .. note:: Currently in the CUDA implementation and the CPU implementation, + `torch.unique` always sort the tensor at the beginning regardless of the `sort` argument. + Sorting could be slow, so if your input tensor is already sorted, it is recommended to use + :func:`torch.unique_consecutive` which avoids the sorting. + + Args: + input (Tensor): the input tensor + sorted (bool): Whether to sort the unique elements in ascending order + before returning as output. + return_inverse (bool): Whether to also return the indices for where + elements in the original input ended up in the returned unique list. + return_counts (bool): Whether to also return the counts for each unique + element. + dim (int, optional): the dimension to operate upon. If ``None``, the + unique of the flattened input is returned. Otherwise, each of the + tensors indexed by the given dimension is treated as one of the + elements to apply the unique operation upon. See examples for more + details. Default: ``None`` + + Returns: + (Tensor, Tensor (optional), Tensor (optional)): A tensor or a tuple of tensors containing + + - **output** (*Tensor*): the output list of unique scalar elements. + - **inverse_indices** (*Tensor*): (optional) if + :attr:`return_inverse` is True, there will be an additional + returned tensor (same shape as input) representing the indices + for where elements in the original input map to in the output; + otherwise, this function will only return a single tensor. + - **counts** (*Tensor*): (optional) if + :attr:`return_counts` is True, there will be an additional + returned tensor (same shape as output or output.size(dim), + if dim was specified) representing the number of occurrences + for each unique value or tensor. + + Example:: + + >>> output = torch.unique(torch.tensor([1, 3, 2, 3], dtype=torch.long)) + >>> output + tensor([1, 2, 3]) + + >>> output, inverse_indices = torch.unique( + ... torch.tensor([1, 3, 2, 3], dtype=torch.long), sorted=True, return_inverse=True) + >>> output + tensor([1, 2, 3]) + >>> inverse_indices + tensor([0, 2, 1, 2]) + + >>> output, inverse_indices = torch.unique( + ... torch.tensor([[1, 3], [2, 3]], dtype=torch.long), sorted=True, return_inverse=True) + >>> output + tensor([1, 2, 3]) + >>> inverse_indices + tensor([[0, 2], + [1, 2]]) + + >>> a = torch.tensor([ + ... [ + ... [1, 1, 0, 0], + ... [1, 1, 0, 0], + ... [0, 0, 1, 1], + ... ], + ... [ + ... [0, 0, 1, 1], + ... [0, 0, 1, 1], + ... [1, 1, 1, 1], + ... ], + ... [ + ... [1, 1, 0, 0], + ... [1, 1, 0, 0], + ... [0, 0, 1, 1], + ... ], + ... ]) + + >>> # If we call `torch.unique(a, dim=0)`, each of the tensors `a[idx, :, :]` + >>> # will be compared. We can see that `a[0, :, :]` and `a[2, :, :]` match + >>> # each other, so one of them will be removed. + >>> (a[0, :, :] == a[2, :, :]).all() + tensor(True) + >>> a_unique_dim0 = torch.unique(a, dim=0) + >>> a_unique_dim0 + tensor([[[0, 0, 1, 1], + [0, 0, 1, 1], + [1, 1, 1, 1]], + [[1, 1, 0, 0], + [1, 1, 0, 0], + [0, 0, 1, 1]]]) + + >>> # Notice which sub-tensors from `a` match with the sub-tensors from + >>> # `a_unique_dim0`: + >>> (a_unique_dim0[0, :, :] == a[1, :, :]).all() + tensor(True) + >>> (a_unique_dim0[1, :, :] == a[0, :, :]).all() + tensor(True) + + >>> # For `torch.unique(a, dim=1)`, each of the tensors `a[:, idx, :]` are + >>> # compared. `a[:, 0, :]` and `a[:, 1, :]` match each other, so one of + >>> # them will be removed. + >>> (a[:, 0, :] == a[:, 1, :]).all() + tensor(True) + >>> torch.unique(a, dim=1) + tensor([[[0, 0, 1, 1], + [1, 1, 0, 0]], + [[1, 1, 1, 1], + [0, 0, 1, 1]], + [[0, 0, 1, 1], + [1, 1, 0, 0]]]) + + >>> # For `torch.unique(a, dim=2)`, the tensors `a[:, :, idx]` are compared. + >>> # `a[:, :, 0]` and `a[:, :, 1]` match each other. Also, `a[:, :, 2]` and + >>> # `a[:, :, 3]` match each other as well. So in this case, two of the + >>> # sub-tensors will be removed. + >>> (a[:, :, 0] == a[:, :, 1]).all() + tensor(True) + >>> (a[:, :, 2] == a[:, :, 3]).all() + tensor(True) + >>> torch.unique(a, dim=2) + tensor([[[0, 1], + [0, 1], + [1, 0]], + [[1, 0], + [1, 0], + [1, 1]], + [[0, 1], + [0, 1], + [1, 0]]]) + """ + if has_torch_function_unary(input): + return handle_torch_function( + unique, + (input,), + input, + sorted=sorted, + return_inverse=return_inverse, + return_counts=return_counts, + dim=dim, + ) + + if dim is not None: + output, inverse_indices, counts = _VF.unique_dim( + input, + dim, + sorted=sorted, + return_inverse=return_inverse, + return_counts=return_counts, + ) + else: + output, inverse_indices, counts = torch._unique2( + input, + sorted=sorted, + return_inverse=return_inverse, + return_counts=return_counts, + ) + return output, inverse_indices, counts + + +def _unique_consecutive_impl( + input: Tensor, + return_inverse: bool = False, + return_counts: bool = False, + dim: int | None = None, +) -> _unique_impl_out: + r"""Eliminates all but the first element from every consecutive group of equivalent elements. + + .. note:: This function is different from :func:`torch.unique` in the sense that this function + only eliminates consecutive duplicate values. This semantics is similar to `std::unique` + in C++. + + Args: + input (Tensor): the input tensor + return_inverse (bool): Whether to also return the indices for where + elements in the original input ended up in the returned unique list. + return_counts (bool): Whether to also return the counts for each unique + element. + dim (int): the dimension to apply unique. If ``None``, the unique of the + flattened input is returned. default: ``None`` + + Returns: + (Tensor, Tensor (optional), Tensor (optional)): A tensor or a tuple of tensors containing + + - **output** (*Tensor*): the output list of unique scalar elements. + - **inverse_indices** (*Tensor*): (optional) if + :attr:`return_inverse` is True, there will be an additional + returned tensor (same shape as input) representing the indices + for where elements in the original input map to in the output; + otherwise, this function will only return a single tensor. + - **counts** (*Tensor*): (optional) if + :attr:`return_counts` is True, there will be an additional + returned tensor (same shape as output or output.size(dim), + if dim was specified) representing the number of occurrences + for each unique value or tensor. + + Example:: + + >>> x = torch.tensor([1, 1, 2, 2, 3, 1, 1, 2]) + >>> output = torch.unique_consecutive(x) + >>> output + tensor([1, 2, 3, 1, 2]) + + >>> output, inverse_indices = torch.unique_consecutive(x, return_inverse=True) + >>> output + tensor([1, 2, 3, 1, 2]) + >>> inverse_indices + tensor([0, 0, 1, 1, 2, 3, 3, 4]) + + >>> output, counts = torch.unique_consecutive(x, return_counts=True) + >>> output + tensor([1, 2, 3, 1, 2]) + >>> counts + tensor([2, 2, 1, 2, 1]) + """ + if has_torch_function_unary(input): + return handle_torch_function( + unique_consecutive, + (input,), + input, + return_inverse=return_inverse, + return_counts=return_counts, + dim=dim, + ) + output, inverse_indices, counts = _VF.unique_consecutive( # type: ignore[attr-defined] + input, return_inverse=return_inverse, return_counts=return_counts, dim=dim + ) + return output, inverse_indices, counts + + +def _return_counts( + input, + sorted=True, + return_inverse=False, + return_counts=False, + dim=None, +): + # type: (Tensor, bool, bool, bool, Optional[int]) -> tuple[Tensor, Tensor] + + if has_torch_function_unary(input): + return _unique_impl(input, sorted, return_inverse, return_counts, dim) + + output, _, counts = _unique_impl(input, sorted, return_inverse, return_counts, dim) + return output, counts + + +def _return_output( + input, + sorted=True, + return_inverse=False, + return_counts=False, + dim=None, +): + # type: (Tensor, bool, bool, bool, Optional[int]) -> Tensor + + if has_torch_function_unary(input): + return _unique_impl(input, sorted, return_inverse, return_counts, dim) + + output, _, _ = _unique_impl(input, sorted, return_inverse, return_counts, dim) + return output + + +def _return_inverse( + input, + sorted=True, + return_inverse=False, + return_counts=False, + dim=None, +): + # type: (Tensor, bool, bool, bool, Optional[int]) -> tuple[Tensor, Tensor] + + if has_torch_function_unary(input): + return _unique_impl(input, sorted, return_inverse, return_counts, dim) + + output, inverse_indices, _ = _unique_impl( + input, sorted, return_inverse, return_counts, dim + ) + return output, inverse_indices + + +_return_inverse_false = boolean_dispatch( + arg_name="return_counts", + arg_index=3, + default=False, + if_true=_return_counts, + if_false=_return_output, + module_name=__name__, + func_name="unique", +) + +_return_inverse_true = boolean_dispatch( + arg_name="return_counts", + arg_index=3, + default=False, + if_true=_unique_impl, + if_false=_return_inverse, + module_name=__name__, + func_name="unique", +) + +# The return type of unique depends on `return_inverse`, and `return_counts` so in order to +# resolve the output type in TorchScript we need to statically know the value of both parameters + +unique = boolean_dispatch( + arg_name="return_inverse", + arg_index=2, + default=False, + if_true=_return_inverse_true, + if_false=_return_inverse_false, + module_name=__name__, + func_name="unique", +) +unique.__doc__ = _unique_impl.__doc__ + + +def _consecutive_return_counts( + input, + return_inverse=False, + return_counts=False, + dim=None, +): + # type: (Tensor, bool, bool, Optional[int]) -> tuple[Tensor, Tensor] + + if has_torch_function_unary(input): + return _unique_consecutive_impl(input, return_inverse, return_counts, dim) + + output, _, counts = _unique_consecutive_impl( + input, return_inverse, return_counts, dim + ) + return output, counts + + +def _consecutive_return_output( + input, + return_inverse=False, + return_counts=False, + dim=None, +): + # type: (Tensor, bool, bool, Optional[int]) -> Tensor + + if has_torch_function_unary(input): + return _unique_consecutive_impl(input, return_inverse, return_counts, dim) + + output, _, _ = _unique_consecutive_impl(input, return_inverse, return_counts, dim) + return output + + +def _consecutive_return_inverse( + input, + return_inverse=False, + return_counts=False, + dim=None, +): + # type: (Tensor, bool, bool, Optional[int]) -> tuple[Tensor, Tensor] + + if has_torch_function_unary(input): + return _unique_consecutive_impl(input, return_inverse, return_counts, dim) + + output, inverse_indices, _ = _unique_consecutive_impl( + input, return_inverse, return_counts, dim + ) + return output, inverse_indices + + +_consecutive_return_inverse_false = boolean_dispatch( + arg_name="return_counts", + arg_index=1, + default=False, + if_true=_consecutive_return_counts, + if_false=_consecutive_return_output, + module_name=__name__, + func_name="unique_consecutive", +) + +_consecutive_return_inverse_true = boolean_dispatch( + arg_name="return_counts", + arg_index=1, + default=False, + if_true=_unique_consecutive_impl, + if_false=_consecutive_return_inverse, + module_name=__name__, + func_name="unique_consecutive", +) + +# The return type of unique depends on `return_inverse`, and `return_counts` so in order to +# resolve the output type in TorchScript we need to statically know the value of both parameters + +unique_consecutive = boolean_dispatch( + arg_name="return_inverse", + arg_index=2, + default=False, + if_true=_consecutive_return_inverse_true, + if_false=_consecutive_return_inverse_false, + module_name=__name__, + func_name="unique_consecutive", +) +unique_consecutive.__doc__ = _unique_consecutive_impl.__doc__ + +if TYPE_CHECKING: + pass + # There's no good way to use this type annotation without breaking JIT + # overloads. So leave untyped for mypy for now. +else: + + @overload + def tensordot( + a, + b, + dims: int = 2, + out: torch.Tensor | None = None, + ): + pass + + @overload + def tensordot( # noqa: F811 + a, + b, + dims: tuple[list[int], list[int]], + out: torch.Tensor | None = None, + ): + pass + + @overload + def tensordot( # noqa: F811 + a, + b, + dims: list[list[int]], + out: torch.Tensor | None = None, + ): + pass + + @overload + def tensordot( # noqa: F811 + a, + b, + dims: torch.Tensor, + out: torch.Tensor | None = None, + ): + pass + + +def tensordot( # noqa: F811 + a, + b, + dims=2, + out: torch.Tensor | None = None, +): + r"""Returns a contraction of a and b over multiple dimensions. + + :attr:`tensordot` implements a generalized matrix product. + + Args: + a (Tensor): Left tensor to contract + b (Tensor): Right tensor to contract + dims (int or Tuple[List[int], List[int]] or List[List[int]] containing two lists or Tensor): number of dimensions to + contract or explicit lists of dimensions for :attr:`a` and + :attr:`b` respectively + + When called with a non-negative integer argument :attr:`dims` = :math:`d`, and + the number of dimensions of :attr:`a` and :attr:`b` is :math:`m` and :math:`n`, + respectively, :func:`~torch.tensordot` computes + + .. math:: + r_{i_0,...,i_{m-d}, i_d,...,i_n} + = \sum_{k_0,...,k_{d-1}} a_{i_0,...,i_{m-d},k_0,...,k_{d-1}} \times b_{k_0,...,k_{d-1}, i_d,...,i_n}. + + When called with :attr:`dims` of the list form, the given dimensions will be contracted + in place of the last :math:`d` of :attr:`a` and the first :math:`d` of :math:`b`. The sizes + in these dimensions must match, but :func:`~torch.tensordot` will deal with broadcasted + dimensions. + + Examples:: + + >>> a = torch.arange(60.).reshape(3, 4, 5) + >>> b = torch.arange(24.).reshape(4, 3, 2) + >>> torch.tensordot(a, b, dims=([1, 0], [0, 1])) + tensor([[4400., 4730.], + [4532., 4874.], + [4664., 5018.], + [4796., 5162.], + [4928., 5306.]]) + + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA) + >>> a = torch.randn(3, 4, 5, device='cuda') + >>> b = torch.randn(4, 5, 6, device='cuda') + >>> c = torch.tensordot(a, b, dims=2).cpu() + tensor([[ 8.3504, -2.5436, 6.2922, 2.7556, -1.0732, 3.2741], + [ 3.3161, 0.0704, 5.0187, -0.4079, -4.3126, 4.8744], + [ 0.8223, 3.9445, 3.2168, -0.2400, 3.4117, 1.7780]]) + + >>> a = torch.randn(3, 5, 4, 6) + >>> b = torch.randn(6, 4, 5, 3) + >>> torch.tensordot(a, b, dims=([2, 1, 3], [1, 2, 0])) + tensor([[ 7.7193, -2.4867, -10.3204], + [ 1.5513, -14.4737, -6.5113], + [ -0.2850, 4.2573, -3.5997]]) + """ + if has_torch_function_variadic(a, b): + return handle_torch_function(tensordot, (a, b), a, b, dims=dims, out=out) + + if not isinstance(dims, (tuple, list, torch.Tensor, int, torch.SymInt)): + raise RuntimeError( + "tensordot expects dims to be int or " + + "tuple[list[int], list[int]] or " + + "list[list[int]] containing two lists, but got " + + f"dims={dims}" + ) + + dims_a: list[int] = [] + dims_b: list[int] = [] + + if isinstance(dims, (tuple, list)): + dims_a, dims_b = dims + + if isinstance(dims, torch.Tensor): + num_elements = dims.numel() + if num_elements > 1: + assert dims.size()[0] == 2 + dims_a = torch.jit.annotate(list[int], dims[0].tolist()) + dims_b = torch.jit.annotate(list[int], dims[1].tolist()) + else: + dims_val = int(dims.item()) + if dims_val < 0: + raise RuntimeError(f"tensordot expects dims >= 0, but got dims={dims}") + dims_a = list(range(-dims_val, 0)) + dims_b = list(range(dims_val)) + + if isinstance(dims, (int, torch.SymInt)): + if dims < 0: + raise RuntimeError(f"tensordot expects dims >= 0, but got dims={dims}") + if dims > min(a.dim(), b.dim()): + raise RuntimeError( + f"tensordot expects dims < ndim_a or ndim_b, but got dims={dims}" + ) + dims_a = list(range(-dims, 0)) + dims_b = list(range(dims)) + + if out is None: + return _VF.tensordot(a, b, dims_a, dims_b) # type: ignore[attr-defined] + else: + return _VF.tensordot(a, b, dims_a, dims_b, out=out) # type: ignore[attr-defined] + + +def cartesian_prod(*tensors: Tensor) -> Tensor: + """Do cartesian product of the given sequence of tensors. The behavior is similar to + python's `itertools.product`. + + Args: + *tensors: any number of 1 dimensional tensors. + + Returns: + Tensor: A tensor equivalent to converting all the input tensors into lists, + do `itertools.product` on these lists, and finally convert the resulting list + into tensor. + + Example:: + + >>> import itertools + >>> a = [1, 2, 3] + >>> b = [4, 5] + >>> list(itertools.product(a, b)) + [(1, 4), (1, 5), (2, 4), (2, 5), (3, 4), (3, 5)] + >>> tensor_a = torch.tensor(a) + >>> tensor_b = torch.tensor(b) + >>> torch.cartesian_prod(tensor_a, tensor_b) + tensor([[1, 4], + [1, 5], + [2, 4], + [2, 5], + [3, 4], + [3, 5]]) + """ + # This wrapper exists to support variadic args. + if has_torch_function(tensors): + return handle_torch_function(cartesian_prod, tensors, *tensors) + return _VF.cartesian_prod(tensors) # type: ignore[attr-defined] + + +def block_diag(*tensors): + """Create a block diagonal matrix from provided tensors. + + Args: + *tensors: One or more tensors with 0, 1, or 2 dimensions. + + Returns: + Tensor: A 2 dimensional tensor with all the input tensors arranged in + order such that their upper left and lower right corners are + diagonally adjacent. All other elements are set to 0. + + Example:: + + >>> import torch + >>> A = torch.tensor([[0, 1], [1, 0]]) + >>> B = torch.tensor([[3, 4, 5], [6, 7, 8]]) + >>> C = torch.tensor(7) + >>> D = torch.tensor([1, 2, 3]) + >>> E = torch.tensor([[4], [5], [6]]) + >>> torch.block_diag(A, B, C, D, E) + tensor([[0, 1, 0, 0, 0, 0, 0, 0, 0, 0], + [1, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 3, 4, 5, 0, 0, 0, 0, 0], + [0, 0, 6, 7, 8, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 7, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 1, 2, 3, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 4], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 5], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 6]]) + """ + # This wrapper exists to support variadic args. + if has_torch_function(tensors): + return handle_torch_function(block_diag, tensors, *tensors) + return torch._C._VariableFunctions.block_diag(tensors) # type: ignore[attr-defined] + + +def cdist(x1, x2, p=2.0, compute_mode="use_mm_for_euclid_dist_if_necessary"): + # type: (Tensor, Tensor, float, str) -> (Tensor) + r"""Computes batched the p-norm distance between each pair of the two collections of row vectors. + + Args: + x1 (Tensor): input tensor where the last two dimensions represent the points and the feature dimension respectively. + The shape can be :math:`D_1 \times D_2 \times \cdots \times D_n \times P \times M`, + where :math:`P` is the number of points and :math:`M` is the feature dimension. + x2 (Tensor): input tensor where the last two dimensions also represent the points and the feature dimension respectively. + The shape can be :math:`D_1' \times D_2' \times \cdots \times D_m' \times R \times M`, + where :math:`R` is the number of points and :math:`M` is the feature dimension, + which should match the feature dimension of `x1`. + p: p value for the p-norm distance to calculate between each vector pair + :math:`\in [0, \infty]`. + compute_mode: + 'use_mm_for_euclid_dist_if_necessary' - will use matrix multiplication approach to calculate + euclidean distance (p = 2) if P > 25 or R > 25 + 'use_mm_for_euclid_dist' - will always use matrix multiplication approach to calculate + euclidean distance (p = 2) + 'donot_use_mm_for_euclid_dist' - will never use matrix multiplication approach to calculate + euclidean distance (p = 2) + Default: use_mm_for_euclid_dist_if_necessary. + + If x1 has shape :math:`B \times P \times M` and x2 has shape :math:`B \times R \times M` then the + output will have shape :math:`B \times P \times R`. + + This function is equivalent to `scipy.spatial.distance.cdist(input,'minkowski', p=p)` + if :math:`p \in (0, \infty)`. When :math:`p = 0` it is equivalent to + `scipy.spatial.distance.cdist(input, 'hamming') * M`. When :math:`p = \infty`, the closest + scipy function is `scipy.spatial.distance.cdist(xn, lambda x, y: np.abs(x - y).max())`. + + Example: + + >>> a = torch.tensor([[0.9041, 0.0196], [-0.3108, -2.4423], [-0.4821, 1.059]]) + >>> a + tensor([[ 0.9041, 0.0196], + [-0.3108, -2.4423], + [-0.4821, 1.0590]]) + >>> b = torch.tensor([[-2.1763, -0.4713], [-0.6986, 1.3702]]) + >>> b + tensor([[-2.1763, -0.4713], + [-0.6986, 1.3702]]) + >>> torch.cdist(a, b, p=2) + tensor([[3.1193, 2.0959], + [2.7138, 3.8322], + [2.2830, 0.3791]]) + """ + if has_torch_function_variadic(x1, x2): + return handle_torch_function( + cdist, (x1, x2), x1, x2, p=p, compute_mode=compute_mode + ) + if compute_mode == "use_mm_for_euclid_dist_if_necessary": + return _VF.cdist(x1, x2, p, None) # type: ignore[attr-defined] + elif compute_mode == "use_mm_for_euclid_dist": + return _VF.cdist(x1, x2, p, 1) # type: ignore[attr-defined] + elif compute_mode == "donot_use_mm_for_euclid_dist": + return _VF.cdist(x1, x2, p, 2) # type: ignore[attr-defined] + else: + raise ValueError(f"{compute_mode} is not a valid value for compute_mode") + + +def atleast_1d(*tensors): + r""" + Returns a 1-dimensional view of each input tensor with zero dimensions. + Input tensors with one or more dimensions are returned as-is. + + Args: + input (Tensor or sequence of Tensors): tensor(s) to be converted to at least 1-dimensional. + + Returns: + output (Tensor or tuple of Tensors) + + Example:: + + >>> x = torch.arange(2) + >>> x + tensor([0, 1]) + >>> torch.atleast_1d(x) + tensor([0, 1]) + >>> x = torch.tensor(1.) + >>> x + tensor(1.) + >>> torch.atleast_1d(x) + tensor([1.]) + >>> x = torch.tensor(0.5) + >>> y = torch.tensor(1.) + >>> torch.atleast_1d((x, y)) + (tensor([0.5000]), tensor([1.])) + >>> torch.atleast_1d() + () + """ + # This wrapper exists to support variadic args. + if has_torch_function(tensors): + return handle_torch_function(atleast_1d, tensors, *tensors) + if len(tensors) == 1: + tensors = tensors[0] + return _VF.atleast_1d(tensors) # type: ignore[attr-defined] + + +def atleast_2d(*tensors): + r""" + Returns a 2-dimensional view of each input tensor with zero dimensions. + Input tensors with two or more dimensions are returned as-is. + + Args: + input (Tensor or sequence of Tensors): tensor(s) to be converted to at least 2-dimensional. + + Returns: + output (Tensor or tuple of Tensors) + + Example:: + + >>> x = torch.tensor(1.) + >>> x + tensor(1.) + >>> torch.atleast_2d(x) + tensor([[1.]]) + >>> x = torch.arange(4).view(2, 2) + >>> x + tensor([[0, 1], + [2, 3]]) + >>> torch.atleast_2d(x) + tensor([[0, 1], + [2, 3]]) + >>> x = torch.tensor(0.5) + >>> y = torch.tensor(1.) + >>> torch.atleast_2d((x, y)) + (tensor([[0.5000]]), tensor([[1.]])) + >>> torch.atleast_2d() + () + """ + # This wrapper exists to support variadic args. + if has_torch_function(tensors): + return handle_torch_function(atleast_2d, tensors, *tensors) + if len(tensors) == 1: + tensors = tensors[0] + return _VF.atleast_2d(tensors) # type: ignore[attr-defined] + + +def atleast_3d(*tensors): + r""" + Returns a 3-dimensional view of each input tensor with zero dimensions. + Input tensors with three or more dimensions are returned as-is. + + Args: + input (Tensor or sequence of Tensors): tensor(s) to be converted to at least 3-dimensional. + + Returns: + output (Tensor or tuple of Tensors) + + Example: + + >>> x = torch.tensor(0.5) + >>> x + tensor(0.5000) + >>> torch.atleast_3d(x) + tensor([[[0.5000]]]) + >>> y = torch.arange(4).view(2, 2) + >>> y + tensor([[0, 1], + [2, 3]]) + >>> torch.atleast_3d(y) + tensor([[[0], + [1]], + + [[2], + [3]]]) + >>> x = torch.tensor(1).view(1, 1, 1) + >>> x + tensor([[[1]]]) + >>> torch.atleast_3d(x) + tensor([[[1]]]) + >>> x = torch.tensor(0.5) + >>> y = torch.tensor(1.0) + >>> torch.atleast_3d((x, y)) + (tensor([[[0.5000]]]), tensor([[[1.]]])) + >>> torch.atleast_3d() + () + """ + # This wrapper exists to support variadic args. + if has_torch_function(tensors): + return handle_torch_function(atleast_3d, tensors, *tensors) + if len(tensors) == 1: + tensors = tensors[0] + return _VF.atleast_3d(tensors) # type: ignore[attr-defined] + + +if TYPE_CHECKING: + pass + # There's no good way to use this type annotation; cannot rename norm() to + # _norm_impl() in a way that doesn't break JIT overloads. So leave untyped + # for mypy for now. + # def norm(input: Tensor, + # p: Optional[Union[str, Number]] = "fro", + # dim: Optional[Union[int, List[int]]] = None, + # keepdim: bool = False, + # out: Optional[Tensor] = None, + # dtype: _dtype = None) -> Tensor: + # return _norm_impl(input, p, dim, keepdim, out, dtype) +else: + # TODO: type dim as BroadcastingList when + # https://github.com/pytorch/pytorch/issues/33782 is fixed + @overload + def norm( + input, + p="fro", + dim=None, + keepdim=False, + out=None, + dtype=None, + ): + # type: (Tensor, str, Optional[List[int]], bool, Optional[Tensor], Optional[int]) -> Tensor + pass + + @overload + def norm( # noqa: F811 + input, + p="fro", + dim=None, + keepdim=False, + out=None, + dtype=None, + ): + # type: (Tensor, Optional[number], Optional[List[int]], bool, Optional[Tensor], Optional[int]) -> Tensor + pass + + @overload + def norm( # noqa: F811 + input, + p="fro", + dim=None, + keepdim=False, + out=None, + dtype=None, + ): + # type: (Tensor, Optional[number], Optional[int], bool, Optional[Tensor], Optional[int]) -> Tensor + pass + + @overload + def norm( # noqa: F811 + input, + p="fro", + dim=None, + keepdim=False, + out=None, + dtype=None, + ): + # type: (Tensor, str, Optional[int], bool, Optional[Tensor], Optional[int]) -> Tensor + pass + + +def norm( # noqa: F811 + input, + p: float | str | None = "fro", + dim=None, + keepdim=False, + out=None, + dtype=None, +): + r"""Returns the matrix norm or vector norm of a given tensor. + + .. warning:: + + torch.norm is deprecated and may be removed in a future PyTorch release. + Its documentation and behavior may be incorrect, and it is no longer + actively maintained. + + Use :func:`torch.linalg.vector_norm` when computing vector norms and + :func:`torch.linalg.matrix_norm` when computing matrix norms. + For a function with a similar behavior as this one see :func:`torch.linalg.norm`. + Note, however, the signature for these functions is slightly different than the + signature for ``torch.norm``. + + Args: + input (Tensor): The input tensor. Its data type must be either a floating + point or complex type. For complex inputs, the norm is calculated using the + absolute value of each element. If the input is complex and neither + :attr:`dtype` nor :attr:`out` is specified, the result's data type will + be the corresponding floating point type (e.g. float if :attr:`input` is + complexfloat). + + p (int, float, inf, -inf, 'fro', 'nuc', optional): the order of norm. Default: ``'fro'`` + The following norms can be calculated: + + ====== ============== ========================== + ord matrix norm vector norm + ====== ============== ========================== + 'fro' Frobenius norm -- + 'nuc' nuclear norm -- + Number -- sum(abs(x)**ord)**(1./ord) + ====== ============== ========================== + + The vector norm can be calculated across any number of dimensions. + The corresponding dimensions of :attr:`input` are flattened into + one dimension, and the norm is calculated on the flattened + dimension. + + Frobenius norm produces the same result as ``p=2`` in all cases + except when :attr:`dim` is a list of three or more dims, in which + case Frobenius norm throws an error. + + Nuclear norm can only be calculated across exactly two dimensions. + + dim (int, tuple of ints, list of ints, optional): + Specifies which dimension or dimensions of :attr:`input` to + calculate the norm across. If :attr:`dim` is ``None``, the norm will + be calculated across all dimensions of :attr:`input`. If the norm + type indicated by :attr:`p` does not support the specified number of + dimensions, an error will occur. + keepdim (bool, optional): whether the output tensors have :attr:`dim` + retained or not. Ignored if :attr:`dim` = ``None`` and + :attr:`out` = ``None``. Default: ``False`` + out (Tensor, optional): the output tensor. Ignored if + :attr:`dim` = ``None`` and :attr:`out` = ``None``. + dtype (:class:`torch.dtype`, optional): the desired data type of + returned tensor. If specified, the input tensor is casted to + :attr:`dtype` while performing the operation. Default: None. + + .. note:: + Even though ``p='fro'`` supports any number of dimensions, the true + mathematical definition of Frobenius norm only applies to tensors with + exactly two dimensions. :func:`torch.linalg.matrix_norm` with ``ord='fro'`` + aligns with the mathematical definition, since it can only be applied across + exactly two dimensions. + + Example:: + + >>> import torch + >>> a = torch.arange(9, dtype= torch.float) - 4 + >>> b = a.reshape((3, 3)) + >>> torch.norm(a) + tensor(7.7460) + >>> torch.norm(b) + tensor(7.7460) + >>> torch.norm(a, float('inf')) + tensor(4.) + >>> torch.norm(b, float('inf')) + tensor(4.) + >>> c = torch.tensor([[ 1, 2, 3], [-1, 1, 4]] , dtype=torch.float) + >>> torch.norm(c, dim=0) + tensor([1.4142, 2.2361, 5.0000]) + >>> torch.norm(c, dim=1) + tensor([3.7417, 4.2426]) + >>> torch.norm(c, p=1, dim=1) + tensor([6., 6.]) + >>> d = torch.arange(8, dtype=torch.float).reshape(2, 2, 2) + >>> torch.norm(d, dim=(1, 2)) + tensor([ 3.7417, 11.2250]) + >>> torch.norm(d[0, :, :]), torch.norm(d[1, :, :]) + (tensor(3.7417), tensor(11.2250)) + """ + + if has_torch_function_unary(input): + return handle_torch_function( + norm, (input,), input, p=p, dim=dim, keepdim=keepdim, out=out, dtype=dtype + ) + + # NB. All the repeated code and weird python is to please TorchScript. + # For a more compact implementation see the relevant function in `_refs/__init__.py` + + # We don't do this for MPS or sparse tensors + if input.layout == torch.strided and input.device.type in ( + "cpu", + "cuda", + "xpu", + "meta", + torch.utils.backend_registration._privateuse1_backend_name, + ): + if dim is not None: + if isinstance(dim, (int, torch.SymInt)): + _dim = [dim] + else: + _dim = dim + else: + _dim = None # type: ignore[assignment] + + if isinstance(p, str): + if p == "fro" and ( + dim is None + or isinstance(dim, (int, torch.SymInt)) + or len(dim) <= 2 # pyrefly: ignore # bad-argument-type + ): + if out is None: + return torch.linalg.vector_norm( + input, 2, _dim, keepdim, dtype=dtype + ) + else: + return torch.linalg.vector_norm( + input, 2, _dim, keepdim, dtype=dtype, out=out + ) + + # Here we either call the nuclear norm, or we call matrix_norm with some arguments + # that will throw an error + if _dim is None: + _dim = list(range(input.ndim)) + if out is None: + return torch.linalg.matrix_norm(input, p, _dim, keepdim, dtype=dtype) + else: + return torch.linalg.matrix_norm( + input, p, _dim, keepdim, dtype=dtype, out=out + ) + else: + # NB. p should be Union[str, number], not Optional! + _p = 2.0 if p is None else p + if out is None: + return torch.linalg.vector_norm(input, _p, _dim, keepdim, dtype=dtype) + else: + return torch.linalg.vector_norm( + input, _p, _dim, keepdim, dtype=dtype, out=out + ) + + ndim = input.dim() + + # catch default case + if dim is None and out is None and dtype is None and p is not None: + if isinstance(p, str): + if p == "fro": + return _VF.frobenius_norm(input, dim=(), keepdim=keepdim) + if not isinstance(p, str): + _dim = list(range(ndim)) + return _VF.norm(input, p, dim=_dim, keepdim=keepdim) # type: ignore[attr-defined] + + # TODO: when https://github.com/pytorch/pytorch/issues/33782 is fixed + # remove the overloads where dim is an int and replace with BroadcastingList1 + # and remove next four lines, replace _dim with dim + if dim is not None: + if isinstance(dim, (int, torch.SymInt)): + _dim = [dim] + else: + _dim = dim + else: + _dim = None # type: ignore[assignment] + + if isinstance(p, str): + if p == "fro": + if dtype is not None: + raise ValueError("dtype argument is not supported in frobenius norm") + + if _dim is None: + _dim = list(range(ndim)) + if out is None: + return _VF.frobenius_norm(input, _dim, keepdim=keepdim) # type: ignore[arg-type] + else: + return _VF.frobenius_norm(input, _dim, keepdim=keepdim, out=out) # type: ignore[arg-type] + elif p == "nuc": + if dtype is not None: + raise ValueError("dtype argument is not supported in nuclear norm") + if _dim is None: + if out is None: + return _VF.nuclear_norm(input, keepdim=keepdim) # type: ignore[arg-type] + else: + return _VF.nuclear_norm(input, keepdim=keepdim, out=out) # type: ignore[arg-type] + else: + if out is None: + return _VF.nuclear_norm(input, _dim, keepdim=keepdim) # type: ignore[arg-type] + else: + return _VF.nuclear_norm(input, _dim, keepdim=keepdim, out=out) # type: ignore[arg-type] + raise RuntimeError(f"only valid string values are 'fro' and 'nuc', found {p}") + else: + if _dim is None: + _dim = list(range(ndim)) + + if out is None: + if dtype is None: + return _VF.norm(input, p, _dim, keepdim=keepdim) # type: ignore[attr-defined] + else: + return _VF.norm(input, p, _dim, keepdim=keepdim, dtype=dtype) # type: ignore[attr-defined] + else: + if dtype is None: + return _VF.norm(input, p, _dim, keepdim=keepdim, out=out) # type: ignore[attr-defined] + else: + return _VF.norm(input, p, _dim, keepdim=keepdim, dtype=dtype, out=out) # type: ignore[attr-defined] + + +def unravel_index( + indices: Tensor, + shape: int | Sequence[int] | torch.Size, +) -> tuple[Tensor, ...]: + r"""Converts a tensor of flat indices into a tuple of coordinate tensors that + index into an arbitrary tensor of the specified shape. + + Args: + indices (Tensor): An integer tensor containing indices into the + flattened version of an arbitrary tensor of shape :attr:`shape`. + All elements must be in the range ``[0, prod(shape) - 1]``. + + shape (int, sequence of ints, or torch.Size): The shape of the arbitrary + tensor. All elements must be non-negative. + + Returns: + tuple of Tensors: Each ``i``-th tensor in the output corresponds with + dimension ``i`` of :attr:`shape`. Each tensor has the same shape as + ``indices`` and contains one index into dimension ``i`` for each of the + flat indices given by ``indices``. + + Example:: + + >>> import torch + >>> torch.unravel_index(torch.tensor(4), (3, 2)) + (tensor(2), + tensor(0)) + + >>> torch.unravel_index(torch.tensor([4, 1]), (3, 2)) + (tensor([2, 0]), + tensor([0, 1])) + + >>> torch.unravel_index(torch.tensor([0, 1, 2, 3, 4, 5]), (3, 2)) + (tensor([0, 0, 1, 1, 2, 2]), + tensor([0, 1, 0, 1, 0, 1])) + + >>> torch.unravel_index(torch.tensor([1234, 5678]), (10, 10, 10, 10)) + (tensor([1, 5]), + tensor([2, 6]), + tensor([3, 7]), + tensor([4, 8])) + + >>> torch.unravel_index(torch.tensor([[1234], [5678]]), (10, 10, 10, 10)) + (tensor([[1], [5]]), + tensor([[2], [6]]), + tensor([[3], [7]]), + tensor([[4], [8]])) + + >>> torch.unravel_index(torch.tensor([[1234], [5678]]), (100, 100)) + (tensor([[12], [56]]), + tensor([[34], [78]])) + """ + if has_torch_function_unary(indices): + return handle_torch_function(unravel_index, (indices,), indices, shape=shape) + res_tensor = _unravel_index(indices, shape) + return res_tensor.unbind(-1) + + +def _unravel_index(indices: Tensor, shape: int | Sequence[int]) -> Tensor: + torch._check_type( + not indices.is_complex() + and not indices.is_floating_point() + and indices.dtype != torch.bool, + lambda: f"expected 'indices' to be integer dtype, but got {indices.dtype}", + ) + + torch._check_type( + isinstance(shape, (int, torch.SymInt, Sequence)), + lambda: f"expected 'shape' to be int or sequence of ints, but got {type(shape)}", + ) + + if isinstance(shape, (int, torch.SymInt)): + shape = torch.Size([shape]) # pyrefly: ignore [bad-argument-type] + else: + for dim in shape: + torch._check_type( + isinstance(dim, (int, torch.SymInt)), + lambda: f"expected 'shape' sequence to only contain ints, but got {type(dim)}", + ) + shape = torch.Size(shape) + + torch._check_value( + all(dim >= 0 for dim in shape), + lambda: f"'shape' cannot have negative values, but got {tuple(shape)}", + ) + + coefs = list( + reversed( + list( + itertools.accumulate( + reversed(shape[1:] + torch.Size([1])), func=operator.mul + ) + ) + ) + ) + return indices.unsqueeze(-1).floor_divide( + torch.tensor(coefs, device=indices.device, dtype=torch.int64) + ) % torch.tensor(shape, device=indices.device, dtype=torch.int64) + + +def chain_matmul(*matrices, out=None): + r"""Returns the matrix product of the :math:`N` 2-D tensors. This product is efficiently computed + using the matrix chain order algorithm which selects the order in which incurs the lowest cost in terms + of arithmetic operations (`[CLRS]`_). Note that since this is a function to compute the product, :math:`N` + needs to be greater than or equal to 2; if equal to 2 then a trivial matrix-matrix product is returned. + If :math:`N` is 1, then this is a no-op - the original matrix is returned as is. + + .. warning:: + + :func:`torch.chain_matmul` is deprecated and will be removed in a future PyTorch release. + Use :func:`torch.linalg.multi_dot` instead, which accepts a list of two or more tensors + rather than multiple arguments. + + Args: + matrices (Tensors...): a sequence of 2 or more 2-D tensors whose product is to be determined. + out (Tensor, optional): the output tensor. Ignored if :attr:`out` = ``None``. + + Returns: + Tensor: if the :math:`i^{th}` tensor was of dimensions :math:`p_{i} \times p_{i + 1}`, then the product + would be of dimensions :math:`p_{1} \times p_{N + 1}`. + + Example:: + + >>> # xdoctest: +SKIP + >>> # xdoctest: +IGNORE_WANT("non-deterministic") + >>> a = torch.randn(3, 4) + >>> b = torch.randn(4, 5) + >>> c = torch.randn(5, 6) + >>> d = torch.randn(6, 7) + >>> # will raise a deprecation warning + >>> torch.chain_matmul(a, b, c, d) + tensor([[ -2.3375, -3.9790, -4.1119, -6.6577, 9.5609, -11.5095, -3.2614], + [ 21.4038, 3.3378, -8.4982, -5.2457, -10.2561, -2.4684, 2.7163], + [ -0.9647, -5.8917, -2.3213, -5.2284, 12.8615, -12.2816, -2.5095]]) + + .. _`[CLRS]`: https://mitpress.mit.edu/books/introduction-algorithms-third-edition + """ + # This wrapper exists to support variadic args. + if has_torch_function(matrices): + return handle_torch_function(chain_matmul, matrices, *matrices) + + if out is None: + return _VF.chain_matmul(matrices) # type: ignore[attr-defined] + else: + return _VF.chain_matmul(matrices, out=out) # type: ignore[attr-defined] + + +def _lu_impl(A, pivot=True, get_infos=False, out=None): + # type: (Tensor, bool, bool, Any) -> tuple[Tensor, Tensor, Tensor] + r"""Computes the LU factorization of a matrix or batches of matrices + :attr:`A`. Returns a tuple containing the LU factorization and + pivots of :attr:`A`. Pivoting is done if :attr:`pivot` is set to + ``True``. + + .. warning:: + + :func:`torch.lu` is deprecated in favor of :func:`torch.linalg.lu_factor` + and :func:`torch.linalg.lu_factor_ex`. :func:`torch.lu` will be removed in a + future PyTorch release. + ``LU, pivots, info = torch.lu(A, compute_pivots)`` should be replaced with + + .. code:: python + + LU, pivots = torch.linalg.lu_factor(A, compute_pivots) + + ``LU, pivots, info = torch.lu(A, compute_pivots, get_infos=True)`` should be replaced with + + .. code:: python + + LU, pivots, info = torch.linalg.lu_factor_ex(A, compute_pivots) + + .. note:: + * The returned permutation matrix for every matrix in the batch is + represented by a 1-indexed vector of size ``min(A.shape[-2], A.shape[-1])``. + ``pivots[i] == j`` represents that in the ``i``-th step of the algorithm, + the ``i``-th row was permuted with the ``j-1``-th row. + * LU factorization with :attr:`pivot` = ``False`` is not available + for CPU, and attempting to do so will throw an error. However, + LU factorization with :attr:`pivot` = ``False`` is available for + CUDA. + * This function does not check if the factorization was successful + or not if :attr:`get_infos` is ``True`` since the status of the + factorization is present in the third element of the return tuple. + * In the case of batches of square matrices with size less or equal + to 32 on a CUDA device, the LU factorization is repeated for + singular matrices due to the bug in the MAGMA library + (see magma issue 13). + * ``L``, ``U``, and ``P`` can be derived using :func:`torch.lu_unpack`. + + .. warning:: + The gradients of this function will only be finite when :attr:`A` is full rank. + This is because the LU decomposition is just differentiable at full rank matrices. + Furthermore, if :attr:`A` is close to not being full rank, + the gradient will be numerically unstable as it depends on the computation of :math:`L^{-1}` and :math:`U^{-1}`. + + Args: + A (Tensor): the tensor to factor of size :math:`(*, m, n)` + pivot (bool, optional): Whether to compute the LU decomposition with partial pivoting, or the regular LU + decomposition. :attr:`pivot`\ `= False` not supported on CPU. Default: `True`. + get_infos (bool, optional): if set to ``True``, returns an info IntTensor. + Default: ``False`` + out (tuple, optional): optional output tuple. If :attr:`get_infos` is ``True``, + then the elements in the tuple are Tensor, IntTensor, + and IntTensor. If :attr:`get_infos` is ``False``, then the + elements in the tuple are Tensor, IntTensor. Default: ``None`` + + Returns: + (Tensor, IntTensor, IntTensor (optional)): A tuple of tensors containing + + - **factorization** (*Tensor*): the factorization of size :math:`(*, m, n)` + + - **pivots** (*IntTensor*): the pivots of size :math:`(*, \text{min}(m, n))`. + ``pivots`` stores all the intermediate transpositions of rows. + The final permutation ``perm`` could be reconstructed by + applying ``swap(perm[i], perm[pivots[i] - 1])`` for ``i = 0, ..., pivots.size(-1) - 1``, + where ``perm`` is initially the identity permutation of :math:`m` elements + (essentially this is what :func:`torch.lu_unpack` is doing). + + - **infos** (*IntTensor*, *optional*): if :attr:`get_infos` is ``True``, this is a tensor of + size :math:`(*)` where non-zero values indicate whether factorization for the matrix or + each minibatch has succeeded or failed + + Example:: + + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_LAPACK) + >>> # xdoctest: +IGNORE_WANT("non-deterministic") + >>> A = torch.randn(2, 3, 3) + >>> A_LU, pivots = torch.lu(A) + >>> A_LU + tensor([[[ 1.3506, 2.5558, -0.0816], + [ 0.1684, 1.1551, 0.1940], + [ 0.1193, 0.6189, -0.5497]], + + [[ 0.4526, 1.2526, -0.3285], + [-0.7988, 0.7175, -0.9701], + [ 0.2634, -0.9255, -0.3459]]]) + >>> pivots + tensor([[ 3, 3, 3], + [ 3, 3, 3]], dtype=torch.int32) + >>> A_LU, pivots, info = torch.lu(A, get_infos=True) + >>> if info.nonzero().size(0) == 0: + ... print('LU factorization succeeded for all samples!') + LU factorization succeeded for all samples! + """ + # If get_infos is True, then we don't need to check for errors and vice versa + return torch._lu_with_info(A, pivot=pivot, check_errors=(not get_infos)) + + +if TYPE_CHECKING: + _ListOrSeq = Sequence[Tensor] +else: + _ListOrSeq = list[Tensor] + + +def _check_list_size(out_len: int, get_infos: bool, out: _ListOrSeq) -> None: + get_infos_int = 1 if get_infos else 0 + if out_len - get_infos_int != 2: + raise TypeError( + f"expected tuple of {2 + int(get_infos)} elements but got {out_len}" + ) + if not isinstance(out, (tuple, list)): + raise TypeError( + f"argument 'out' must be tuple of Tensors, not {type(out).__name__}" + ) + + +def _lu_with_infos(A, pivot=True, get_infos=False, out=None): + # type: (Tensor, bool, bool, Optional[tuple[Tensor, Tensor, Tensor]]) -> tuple[Tensor, Tensor, Tensor] + if has_torch_function_unary(A): + return handle_torch_function( + lu, (A,), A, pivot=pivot, get_infos=get_infos, out=out + ) + result = _lu_impl(A, pivot, get_infos, out) + if out is not None: + _check_list_size(len(out), get_infos, out) + for i in range(len(out)): + out[i].resize_as_(result[i]).copy_(result[i]) + return out + else: + return result # A_LU, pivots, infos + + +def _lu_no_infos(A, pivot=True, get_infos=False, out=None): + # type: (Tensor, bool, bool, Optional[tuple[Tensor, Tensor]]) -> tuple[Tensor, Tensor] + # need to check for torch_function here so that we exit if + if has_torch_function_unary(A): + return handle_torch_function( + lu, (A,), A, pivot=pivot, get_infos=get_infos, out=out + ) + result = _lu_impl(A, pivot, get_infos, out) + if out is not None: + _check_list_size(len(out), get_infos, out) + for i in range(len(out)): + out[i].resize_as_(result[i]).copy_(result[i]) + return out + else: + return result[0], result[1] # A_LU, pivots + + +# The return type of lu depends on `get_infos`, so in order to resolve the output type +# of lu in TorchScript we need to statically know the value of `get_infos` +lu = boolean_dispatch( + arg_name="get_infos", + arg_index=2, + default=False, + if_true=_lu_with_infos, + if_false=_lu_no_infos, + module_name=__name__, + func_name="lu", +) +lu.__doc__ = _lu_impl.__doc__ + + +def align_tensors(*tensors): + raise RuntimeError("`align_tensors` not yet implemented.") diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/hub.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/hub.py new file mode 100644 index 0000000000000000000000000000000000000000..4344855d0060fe52b8dffa9c8b2efcdf41b3854c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/hub.py @@ -0,0 +1,884 @@ +# mypy: allow-untyped-defs +import contextlib +import errno +import hashlib +import json +import os +import re +import shutil +import sys +import tempfile +import uuid +import warnings +import zipfile +from pathlib import Path +from typing import Any +from typing_extensions import deprecated +from urllib.error import HTTPError, URLError +from urllib.parse import urlparse # noqa: F401 +from urllib.request import Request, urlopen + +import torch +from torch.serialization import MAP_LOCATION + + +class _Faketqdm: # type: ignore[no-redef] + def __init__(self, total=None, disable=False, unit=None, *args, **kwargs): + self.total = total + self.disable = disable + self.n = 0 + # Ignore all extra *args and **kwargs lest you want to reinvent tqdm + + def update(self, n): + if self.disable: + return + + self.n += n + if self.total is None: + sys.stderr.write(f"\r{self.n:.1f} bytes") + else: + sys.stderr.write(f"\r{100 * self.n / float(self.total):.1f}%") + sys.stderr.flush() + + # Don't bother implementing; use real tqdm if you want + def set_description(self, *args, **kwargs): + pass + + def write(self, s): + sys.stderr.write(f"{s}\n") + + def close(self): + self.disable = True + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + if self.disable: + return + + sys.stderr.write("\n") + + +try: + from tqdm import tqdm # If tqdm is installed use it, otherwise use the fake wrapper +except ImportError: + tqdm = _Faketqdm + +__all__ = [ + "download_url_to_file", + "get_dir", + "help", + "list", + "load", + "load_state_dict_from_url", + "set_dir", +] + +# matches bfd8deac from resnet18-bfd8deac.pth +HASH_REGEX = re.compile(r"-([a-f0-9]*)\.") + +_TRUSTED_REPO_OWNERS = ( + "facebookresearch", + "facebookincubator", + "pytorch", + "fairinternal", +) +ENV_GITHUB_TOKEN = "GITHUB_TOKEN" +ENV_TORCH_HOME = "TORCH_HOME" +ENV_XDG_CACHE_HOME = "XDG_CACHE_HOME" +DEFAULT_CACHE_DIR = "~/.cache" +VAR_DEPENDENCY = "dependencies" +MODULE_HUBCONF = "hubconf.py" +READ_DATA_CHUNK = 128 * 1024 +_hub_dir: str | None = None + + +@contextlib.contextmanager +def _add_to_sys_path(path): + sys.path.insert(0, path) + try: + yield + finally: + sys.path.remove(path) + + +# Copied from tools/shared/module_loader to be included in torch package +def _import_module(name, path): + import importlib.util + from importlib.abc import Loader + + spec = importlib.util.spec_from_file_location(name, path) + assert spec is not None + module = importlib.util.module_from_spec(spec) + assert isinstance(spec.loader, Loader) + spec.loader.exec_module(module) + return module + + +def _remove_if_exists(path): + if os.path.exists(path): + if os.path.isfile(path): + os.remove(path) + else: + shutil.rmtree(path) + + +def _git_archive_link(repo_owner, repo_name, ref): + # See https://docs.github.com/en/rest/reference/repos#download-a-repository-archive-zip + return f"https://github.com/{repo_owner}/{repo_name}/zipball/{ref}" + + +def _load_attr_from_module(module, func_name): + # Check if callable is defined in the module + if func_name not in dir(module): + return None + return getattr(module, func_name) + + +def _get_torch_home(): + torch_home = os.path.expanduser( + os.getenv( + ENV_TORCH_HOME, + os.path.join(os.getenv(ENV_XDG_CACHE_HOME, DEFAULT_CACHE_DIR), "torch"), + ) + ) + return torch_home + + +def _parse_repo_info(github): + if ":" in github: + repo_info, ref = github.split(":") + else: + repo_info, ref = github, None + repo_owner, repo_name = repo_info.split("/") + + if ref is None: + # The ref wasn't specified by the user, so we need to figure out the + # default branch: main or master. Our assumption is that if main exists + # then it's the default branch, otherwise it's master. + try: + with urlopen(f"https://github.com/{repo_owner}/{repo_name}/tree/main/"): + ref = "main" + except HTTPError as e: + if e.code == 404: + ref = "master" + else: + raise + except URLError as e: + # No internet connection, need to check for cache as last resort + for possible_ref in ("main", "master"): + if os.path.exists( + f"{get_dir()}/{repo_owner}_{repo_name}_{possible_ref}" + ): + ref = possible_ref + break + if ref is None: + raise RuntimeError( + "It looks like there is no internet connection and the " + f"repo could not be found in the cache ({get_dir()})" + ) from e + return repo_owner, repo_name, ref + + +def _read_url(url): + with urlopen(url) as r: + return r.read().decode(r.headers.get_content_charset("utf-8")) + + +def _validate_not_a_forked_repo(repo_owner, repo_name, ref): + # Use urlopen to avoid depending on local git. + headers = {"Accept": "application/vnd.github.v3+json"} + token = os.environ.get(ENV_GITHUB_TOKEN) + if token is not None: + headers["Authorization"] = f"token {token}" + for url_prefix in ( + f"https://api.github.com/repos/{repo_owner}/{repo_name}/branches", + f"https://api.github.com/repos/{repo_owner}/{repo_name}/tags", + ): + page = 0 + while True: + page += 1 + url = f"{url_prefix}?per_page=100&page={page}" + try: + response = json.loads(_read_url(Request(url, headers=headers))) + except HTTPError: + # Retry without token in case it had insufficient permissions. + del headers["Authorization"] + response = json.loads(_read_url(Request(url, headers=headers))) + # Empty response means no more data to process + if not response: + break + for br in response: + if br["name"] == ref or br["commit"]["sha"].startswith(ref): + return + + raise ValueError( + f"Cannot find {ref} in https://github.com/{repo_owner}/{repo_name}. " + "If it's a commit from a forked repo, please call hub.load() with forked repo directly." + ) + + +def _get_cache_or_reload( + github, + force_reload, + trust_repo, + calling_fn, + verbose=True, + skip_validation=False, +): + # Setup hub_dir to save downloaded files + hub_dir = get_dir() + os.makedirs(hub_dir, exist_ok=True) + # Parse github repo information + repo_owner, repo_name, ref = _parse_repo_info(github) + # Github allows branch name with slash '/', + # this causes confusion with path on both Linux and Windows. + # Backslash is not allowed in Github branch name so no need to + # to worry about it. + normalized_br = ref.replace("/", "_") + # Github renames folder repo-v1.x.x to repo-1.x.x + # We don't know the repo name before downloading the zip file + # and inspect name from it. + # To check if cached repo exists, we need to normalize folder names. + owner_name_branch = "_".join([repo_owner, repo_name, normalized_br]) + repo_dir = os.path.join(hub_dir, owner_name_branch) + # Check that the repo is in the trusted list + _check_repo_is_trusted( + repo_owner, + repo_name, + owner_name_branch, + trust_repo=trust_repo, + calling_fn=calling_fn, + ) + + use_cache = (not force_reload) and os.path.exists(repo_dir) + + if use_cache: + if verbose: + sys.stderr.write(f"Using cache found in {repo_dir}\n") + else: + # Validate the tag/branch is from the original repo instead of a forked repo + if not skip_validation: + _validate_not_a_forked_repo(repo_owner, repo_name, ref) + + cached_file = os.path.join(hub_dir, normalized_br + ".zip") + _remove_if_exists(cached_file) + + try: + url = _git_archive_link(repo_owner, repo_name, ref) + sys.stdout.write(f'Downloading: "{url}" to {cached_file}\n') + download_url_to_file(url, cached_file, progress=False) + except HTTPError as err: + if err.code == 300: + # Getting a 300 Multiple Choices error likely means that the ref is both a tag and a branch + # in the repo. This can be disambiguated by explicitly using refs/heads/ or refs/tags + # See https://git-scm.com/book/en/v2/Git-Internals-Git-References + # Here, we do the same as git: we throw a warning, and assume the user wanted the branch + warnings.warn( + f"The ref {ref} is ambiguous. Perhaps it is both a tag and a branch in the repo? " + "Torchhub will now assume that it's a branch. " + "You can disambiguate tags and branches by explicitly passing refs/heads/branch_name or " + "refs/tags/tag_name as the ref. That might require using skip_validation=True.", + stacklevel=2, + ) + disambiguated_branch_ref = f"refs/heads/{ref}" + url = _git_archive_link( + repo_owner, repo_name, ref=disambiguated_branch_ref + ) + download_url_to_file(url, cached_file, progress=False) + else: + raise + + with zipfile.ZipFile(cached_file) as cached_zipfile: + extraced_repo_name = cached_zipfile.infolist()[0].filename + extracted_repo = os.path.join(hub_dir, extraced_repo_name) + _remove_if_exists(extracted_repo) + # Unzip the code and rename the base folder + cached_zipfile.extractall(hub_dir) + + _remove_if_exists(cached_file) + _remove_if_exists(repo_dir) + shutil.move(extracted_repo, repo_dir) # rename the repo + + return repo_dir + + +def _check_repo_is_trusted( + repo_owner, + repo_name, + owner_name_branch, + trust_repo, + calling_fn="load", +): + hub_dir = get_dir() + filepath = os.path.join(hub_dir, "trusted_list") + + if not os.path.exists(filepath): + Path(filepath).touch() + with open(filepath) as file: + trusted_repos = tuple(line.strip() for line in file) + + # To minimize friction of introducing the new trust_repo mechanism, we consider that + # if a repo was already downloaded by torchhub, then it is already trusted (even if it's not in the allowlist) + trusted_repos_legacy = next(os.walk(hub_dir))[1] + + owner_name = "_".join([repo_owner, repo_name]) + is_trusted = ( + owner_name in trusted_repos + or owner_name_branch in trusted_repos_legacy + or repo_owner in _TRUSTED_REPO_OWNERS + ) + + # TODO: Remove `None` option in 2.0 and change the default to "check" + if trust_repo is None: + if not is_trusted: + warnings.warn( + "You are about to download and run code from an untrusted repository. In a future release, this won't " + f"be allowed. To add the repository to your trusted list, change the command to {calling_fn}(..., " + "trust_repo=False) and a command prompt will appear asking for an explicit confirmation of trust, " + f"or {calling_fn}(..., trust_repo=True), which will assume that the prompt is to be answered with " + f"'yes'. You can also use {calling_fn}(..., trust_repo='check') which will only prompt for " + f"confirmation if the repo is not already trusted. This will eventually be the default behaviour", + stacklevel=2, + ) + return + + if (trust_repo is False) or (trust_repo == "check" and not is_trusted): + response = input( + f"The repository {owner_name} does not belong to the list of trusted repositories and as such cannot be downloaded. " + "Do you trust this repository and wish to add it to the trusted list of repositories (y/N)?" + ) + if response.lower() in ("y", "yes"): + if is_trusted: + print("The repository is already trusted.") + elif response.lower() in ("n", "no", ""): + raise Exception("Untrusted repository.") # noqa: TRY002 + else: + raise ValueError(f"Unrecognized response {response}.") + + # At this point we're sure that the user trusts the repo (or wants to trust it) + if not is_trusted: + with open(filepath, "a") as file: + file.write(owner_name + "\n") + + +def _check_module_exists(name): + import importlib.util + + return importlib.util.find_spec(name) is not None + + +def _check_dependencies(m): + dependencies = _load_attr_from_module(m, VAR_DEPENDENCY) + + if dependencies is not None: + missing_deps = [pkg for pkg in dependencies if not _check_module_exists(pkg)] + if missing_deps: + raise RuntimeError(f"Missing dependencies: {', '.join(missing_deps)}") + + +def _load_entry_from_hubconf(m, model): + if not isinstance(model, str): + raise ValueError("Invalid input: model should be a string of function name") + + # Note that if a missing dependency is imported at top level of hubconf, it will + # throw before this function. It's a chicken and egg situation where we have to + # load hubconf to know what're the dependencies, but to import hubconf it requires + # a missing package. This is fine, Python will throw proper error message for users. + _check_dependencies(m) + + func = _load_attr_from_module(m, model) + + if func is None or not callable(func): + raise RuntimeError(f"Cannot find callable {model} in hubconf") + + return func + + +def get_dir() -> str: + r""" + Get the Torch Hub cache directory used for storing downloaded models & weights. + + If :func:`~torch.hub.set_dir` is not called, default path is ``$TORCH_HOME/hub`` where + environment variable ``$TORCH_HOME`` defaults to ``$XDG_CACHE_HOME/torch``. + ``$XDG_CACHE_HOME`` follows the X Design Group specification of the Linux + filesystem layout, with a default value ``~/.cache`` if the environment + variable is not set. + """ + # Issue warning to move data if old env is set + if os.getenv("TORCH_HUB"): + warnings.warn( + "TORCH_HUB is deprecated, please use env TORCH_HOME instead", stacklevel=2 + ) + + if _hub_dir is not None: + return _hub_dir + return os.path.join(_get_torch_home(), "hub") + + +def set_dir(d: str | os.PathLike) -> None: + r""" + Optionally set the Torch Hub directory used to save downloaded models & weights. + + Args: + d (str): path to a local folder to save downloaded models & weights. + """ + global _hub_dir + _hub_dir = os.path.expanduser(d) + + +def list( + github, + force_reload=False, + skip_validation=False, + trust_repo=None, + verbose=True, +): + r""" + List all callable entrypoints available in the repo specified by ``github``. + + Args: + github (str): a string with format "repo_owner/repo_name[:ref]" with an optional + ref (tag or branch). If ``ref`` is not specified, the default branch is assumed to be ``main`` if + it exists, and otherwise ``master``. + Example: 'pytorch/vision:0.10' + force_reload (bool, optional): whether to discard the existing cache and force a fresh download. + Default is ``False``. + skip_validation (bool, optional): if ``False``, torchhub will check that the branch or commit + specified by the ``github`` argument properly belongs to the repo owner. This will make + requests to the GitHub API; you can specify a non-default GitHub token by setting the + ``GITHUB_TOKEN`` environment variable. Default is ``False``. + trust_repo (bool, str or None): ``"check"``, ``True``, ``False`` or ``None``. + This parameter was introduced in v1.12 and helps ensuring that users + only run code from repos that they trust. + + - If ``False``, a prompt will ask the user whether the repo should + be trusted. + - If ``True``, the repo will be added to the trusted list and loaded + without requiring explicit confirmation. + - If ``"check"``, the repo will be checked against the list of + trusted repos in the cache. If it is not present in that list, the + behaviour will fall back onto the ``trust_repo=False`` option. + - If ``None``: this will raise a warning, inviting the user to set + ``trust_repo`` to either ``False``, ``True`` or ``"check"``. This + is only present for backward compatibility and will be removed in + v2.0. + + Default is ``None`` and will eventually change to ``"check"`` in v2.0. + verbose (bool, optional): If ``False``, mute messages about hitting + local caches. Note that the message about first download cannot be + muted. Default is ``True``. + + Returns: + list: The available callables entrypoint + + Example: + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_HUB) + >>> entrypoints = torch.hub.list("pytorch/vision", force_reload=True) + """ + repo_dir = _get_cache_or_reload( + github, + force_reload, + trust_repo, + "list", + verbose=verbose, + skip_validation=skip_validation, + ) + + with _add_to_sys_path(repo_dir): + hubconf_path = os.path.join(repo_dir, MODULE_HUBCONF) + hub_module = _import_module(MODULE_HUBCONF, hubconf_path) + + # We take functions starts with '_' as internal helper functions + entrypoints = [ + f + for f in dir(hub_module) + if callable(getattr(hub_module, f)) and not f.startswith("_") + ] + + return entrypoints + + +def help(github, model, force_reload=False, skip_validation=False, trust_repo=None): + r""" + Show the docstring of entrypoint ``model``. + + Args: + github (str): a string with format with an optional + ref (a tag or a branch). If ``ref`` is not specified, the default branch is assumed + to be ``main`` if it exists, and otherwise ``master``. + Example: 'pytorch/vision:0.10' + model (str): a string of entrypoint name defined in repo's ``hubconf.py`` + force_reload (bool, optional): whether to discard the existing cache and force a fresh download. + Default is ``False``. + skip_validation (bool, optional): if ``False``, torchhub will check that the ref + specified by the ``github`` argument properly belongs to the repo owner. This will make + requests to the GitHub API; you can specify a non-default GitHub token by setting the + ``GITHUB_TOKEN`` environment variable. Default is ``False``. + trust_repo (bool, str or None): ``"check"``, ``True``, ``False`` or ``None``. + This parameter was introduced in v1.12 and helps ensuring that users + only run code from repos that they trust. + + - If ``False``, a prompt will ask the user whether the repo should + be trusted. + - If ``True``, the repo will be added to the trusted list and loaded + without requiring explicit confirmation. + - If ``"check"``, the repo will be checked against the list of + trusted repos in the cache. If it is not present in that list, the + behaviour will fall back onto the ``trust_repo=False`` option. + - If ``None``: this will raise a warning, inviting the user to set + ``trust_repo`` to either ``False``, ``True`` or ``"check"``. This + is only present for backward compatibility and will be removed in + v2.0. + + Default is ``None`` and will eventually change to ``"check"`` in v2.0. + Example: + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_HUB) + >>> print(torch.hub.help("pytorch/vision", "resnet18", force_reload=True)) + """ + repo_dir = _get_cache_or_reload( + github, + force_reload, + trust_repo, + "help", + verbose=True, + skip_validation=skip_validation, + ) + + with _add_to_sys_path(repo_dir): + hubconf_path = os.path.join(repo_dir, MODULE_HUBCONF) + hub_module = _import_module(MODULE_HUBCONF, hubconf_path) + + entry = _load_entry_from_hubconf(hub_module, model) + + return entry.__doc__ + + +def load( + repo_or_dir, + model, + *args, + source="github", + trust_repo=None, + force_reload=False, + verbose=True, + skip_validation=False, + **kwargs, +): + r""" + Load a model from a github repo or a local directory. + + Note: Loading a model is the typical use case, but this can also be used to + for loading other objects such as tokenizers, loss functions, etc. + + If ``source`` is 'github', ``repo_or_dir`` is expected to be + of the form ``repo_owner/repo_name[:ref]`` with an optional + ref (a tag or a branch). + + If ``source`` is 'local', ``repo_or_dir`` is expected to be a + path to a local directory. + + Args: + repo_or_dir (str): If ``source`` is 'github', + this should correspond to a github repo with format ``repo_owner/repo_name[:ref]`` with + an optional ref (tag or branch), for example 'pytorch/vision:0.10'. If ``ref`` is not specified, + the default branch is assumed to be ``main`` if it exists, and otherwise ``master``. + If ``source`` is 'local' then it should be a path to a local directory. + model (str): the name of a callable (entrypoint) defined in the + repo/dir's ``hubconf.py``. + *args (optional): the corresponding args for callable ``model``. + source (str, optional): 'github' or 'local'. Specifies how + ``repo_or_dir`` is to be interpreted. Default is 'github'. + trust_repo (bool, str or None): ``"check"``, ``True``, ``False`` or ``None``. + This parameter was introduced in v1.12 and helps ensuring that users + only run code from repos that they trust. + + - If ``False``, a prompt will ask the user whether the repo should + be trusted. + - If ``True``, the repo will be added to the trusted list and loaded + without requiring explicit confirmation. + - If ``"check"``, the repo will be checked against the list of + trusted repos in the cache. If it is not present in that list, the + behaviour will fall back onto the ``trust_repo=False`` option. + - If ``None``: this will raise a warning, inviting the user to set + ``trust_repo`` to either ``False``, ``True`` or ``"check"``. This + is only present for backward compatibility and will be removed in + v2.0. + + Default is ``None`` and will eventually change to ``"check"`` in v2.0. + force_reload (bool, optional): whether to force a fresh download of + the github repo unconditionally. Does not have any effect if + ``source = 'local'``. Default is ``False``. + verbose (bool, optional): If ``False``, mute messages about hitting + local caches. Note that the message about first download cannot be + muted. Does not have any effect if ``source = 'local'``. + Default is ``True``. + skip_validation (bool, optional): if ``False``, torchhub will check that the branch or commit + specified by the ``github`` argument properly belongs to the repo owner. This will make + requests to the GitHub API; you can specify a non-default GitHub token by setting the + ``GITHUB_TOKEN`` environment variable. Default is ``False``. + **kwargs (optional): the corresponding kwargs for callable ``model``. + + Returns: + The output of the ``model`` callable when called with the given + ``*args`` and ``**kwargs``. + + Example: + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_HUB) + >>> # from a github repo + >>> repo = "pytorch/vision" + >>> model = torch.hub.load( + ... repo, "resnet50", weights="ResNet50_Weights.IMAGENET1K_V1" + ... ) + >>> # from a local directory + >>> path = "/some/local/path/pytorch/vision" + >>> # xdoctest: +SKIP + >>> model = torch.hub.load(path, "resnet50", weights="ResNet50_Weights.DEFAULT") + """ + source = source.lower() + + if source not in ("github", "local"): + raise ValueError( + f'Unknown source: "{source}". Allowed values: "github" | "local".' + ) + + if source == "github": + repo_or_dir = _get_cache_or_reload( + repo_or_dir, + force_reload, + trust_repo, + "load", + verbose=verbose, + skip_validation=skip_validation, + ) + + model = _load_local(repo_or_dir, model, *args, **kwargs) + return model + + +def _load_local(hubconf_dir, model, *args, **kwargs): + r""" + Load a model from a local directory with a ``hubconf.py``. + + Args: + hubconf_dir (str): path to a local directory that contains a + ``hubconf.py``. + model (str): name of an entrypoint defined in the directory's + ``hubconf.py``. + *args (optional): the corresponding args for callable ``model``. + **kwargs (optional): the corresponding kwargs for callable ``model``. + + Returns: + a single model with corresponding pretrained weights. + + Example: + >>> # xdoctest: +SKIP("stub local path") + >>> path = "/some/local/path/pytorch/vision" + >>> model = _load_local( + ... path, + ... "resnet50", + ... weights="ResNet50_Weights.IMAGENET1K_V1", + ... ) + """ + with _add_to_sys_path(hubconf_dir): + hubconf_path = os.path.join(hubconf_dir, MODULE_HUBCONF) + hub_module = _import_module(MODULE_HUBCONF, hubconf_path) + + entry = _load_entry_from_hubconf(hub_module, model) + model = entry(*args, **kwargs) + + return model + + +def download_url_to_file( + url: str, + dst: str, + hash_prefix: str | None = None, + progress: bool = True, +) -> None: + r"""Download object at the given URL to a local path. + + Args: + url (str): URL of the object to download + dst (str): Full path where object will be saved, e.g. ``/tmp/temporary_file`` + hash_prefix (str, optional): If not None, the SHA256 downloaded file should start with ``hash_prefix``. + Default: None + progress (bool, optional): whether or not to display a progress bar to stderr + Default: True + + Example: + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_HUB) + >>> # xdoctest: +REQUIRES(POSIX) + >>> torch.hub.download_url_to_file( + ... "https://s3.amazonaws.com/pytorch/models/resnet18-5c106cde.pth", + ... "/tmp/temporary_file", + ... ) + + """ + # We deliberately save it in a temp file and move it after + # download is complete. This prevents a local working checkpoint + # being overridden by a broken download. + # We deliberately do not use NamedTemporaryFile to avoid restrictive + # file permissions being applied to the downloaded file. + dst = os.path.expanduser(dst) + for _ in range(tempfile.TMP_MAX): + tmp_dst = dst + "." + uuid.uuid4().hex + ".partial" + try: + f = open(tmp_dst, "w+b") # noqa: SIM115 + except FileExistsError: + continue + break + else: + raise FileExistsError(errno.EEXIST, "No usable temporary file name found") + req = Request(url, headers={"User-Agent": "torch.hub"}) + try: + with urlopen(req) as u: + meta = u.info() + if hasattr(meta, "getheaders"): + content_length = meta.getheaders("Content-Length") + else: + content_length = meta.get_all("Content-Length") + file_size = None + if content_length is not None and len(content_length) > 0: + file_size = int(content_length[0]) + + sha256 = hashlib.sha256() if hash_prefix is not None else None + with tqdm( + total=file_size, + disable=not progress, + unit="B", + unit_scale=True, + unit_divisor=1024, + ) as pbar: + while True: + buffer = u.read(READ_DATA_CHUNK) + if len(buffer) == 0: + break + f.write(buffer) + if sha256 is not None: + sha256.update(buffer) + pbar.update(len(buffer)) + + f.close() + if sha256 is not None and hash_prefix is not None: + digest = sha256.hexdigest() + if digest[: len(hash_prefix)] != hash_prefix: + raise RuntimeError( + f'invalid hash value (expected "{hash_prefix}", got "{digest}")' + ) + shutil.move(f.name, dst) + finally: + f.close() + if os.path.exists(f.name): + os.remove(f.name) + + +# Hub used to support automatically extracts from zipfile manually compressed by users. +# The legacy zip format expects only one file from torch.save() < 1.6 in the zip. +# We should remove this support since zipfile is now default zipfile format for torch.save(). +def _is_legacy_zip_format(filename: str) -> bool: + if zipfile.is_zipfile(filename): + with zipfile.ZipFile(filename) as zf: + infolist = zf.infolist() + return len(infolist) == 1 and not infolist[0].is_dir() + return False + + +@deprecated( + "Falling back to the old format < 1.6. This support will be " + "deprecated in favor of default zipfile format introduced in 1.6. " + "Please redo torch.save() to save it in the new zipfile format.", + category=FutureWarning, +) +def _legacy_zip_load( + filename: str, + model_dir: str, + map_location: MAP_LOCATION, + weights_only: bool, +) -> dict[str, Any]: + # Note: extractall() defaults to overwrite file if exists. No need to clean up beforehand. + # We deliberately don't handle tarfile here since our legacy serialization format was in tar. + # E.g. resnet18-5c106cde.pth which is widely used. + with zipfile.ZipFile(filename) as f: + members = f.infolist() + if len(members) != 1: + raise RuntimeError("Only one file(not dir) is allowed in the zipfile") + f.extractall(model_dir) + extraced_name = members[0].filename + extracted_file = os.path.join(model_dir, extraced_name) + return torch.load( + extracted_file, map_location=map_location, weights_only=weights_only + ) + + +def load_state_dict_from_url( + url: str, + model_dir: str | None = None, + map_location: MAP_LOCATION = None, + progress: bool = True, + check_hash: bool = False, + file_name: str | None = None, + weights_only: bool = False, +) -> dict[str, Any]: + r"""Loads the Torch serialized object at the given URL. + + If downloaded file is a zip file, it will be automatically + decompressed. + + If the object is already present in `model_dir`, it's deserialized and + returned. + The default value of ``model_dir`` is ``/checkpoints`` where + ``hub_dir`` is the directory returned by :func:`~torch.hub.get_dir`. + + Args: + url (str): URL of the object to download + model_dir (str, optional): directory in which to save the object + map_location (optional): a function or a dict specifying how to remap storage locations (see torch.load) + progress (bool, optional): whether or not to display a progress bar to stderr. + Default: True + check_hash(bool, optional): If True, the filename part of the URL should follow the naming convention + ``filename-.ext`` where ```` is the first eight or more + digits of the SHA256 hash of the contents of the file. The hash is used to + ensure unique names and to verify the contents of the file. + Default: False + file_name (str, optional): name for the downloaded file. Filename from ``url`` will be used if not set. + weights_only(bool, optional): If True, only weights will be loaded and no complex pickled objects. + Recommended for untrusted sources. See :func:`~torch.load` for more details. + + Example: + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_HUB) + >>> state_dict = torch.hub.load_state_dict_from_url( + ... "https://s3.amazonaws.com/pytorch/models/resnet18-5c106cde.pth" + ... ) + + """ + # Issue warning to move data if old env is set + if os.getenv("TORCH_MODEL_ZOO"): + warnings.warn( + "TORCH_MODEL_ZOO is deprecated, please use env TORCH_HOME instead", + stacklevel=2, + ) + + if model_dir is None: + hub_dir = get_dir() + model_dir = os.path.join(hub_dir, "checkpoints") + + os.makedirs(model_dir, exist_ok=True) + + parts = urlparse(url) + filename = os.path.basename(parts.path) + if file_name is not None: + filename = file_name + cached_file = os.path.join(model_dir, filename) + if not os.path.exists(cached_file): + sys.stdout.write(f'Downloading: "{url}" to {cached_file}\n') + hash_prefix = None + if check_hash: + r = HASH_REGEX.search(filename) # r is Optional[Match[str]] + hash_prefix = r.group(1) if r else None + download_url_to_file(url, cached_file, hash_prefix, progress=progress) + + if _is_legacy_zip_format(cached_file): + return _legacy_zip_load(cached_file, model_dir, map_location, weights_only) + return torch.load(cached_file, map_location=map_location, weights_only=weights_only) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/library.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/library.py new file mode 100644 index 0000000000000000000000000000000000000000..5305d647bc6136888b0bb476e7d4026579428a2e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/library.py @@ -0,0 +1,1736 @@ +# mypy: allow-untyped-defs +import contextlib +import functools +import inspect +import re +import sys +import traceback +import weakref +from collections.abc import Callable, Sequence +from typing import Any, overload, TYPE_CHECKING, TypeVar, Union +from typing_extensions import deprecated, ParamSpec + +import torch +import torch._library as _library +from torch._library.custom_ops import ( + _cast, + _maybe_get_opdef, + custom_op, + CustomOpDef, + device_types_t, +) +from torch._library.effects import EffectType +from torch._library.infer_schema import infer_schema # noqa: F401 +from torch._library.triton import triton_op, wrap_triton +from torch._ops import OpOverload +from torch.types import _dtype + + +__all__ = [ + "Library", + "impl", + "define", + "fallthrough_kernel", + "impl_abstract", + "register_autocast", + "register_fake", + "register_torch_dispatch", + "register_vmap", + "get_ctx", + "get_kernel", + "custom_op", + "triton_op", + "wrap_triton", + "infer_schema", +] + +_T = TypeVar("_T") +_P = ParamSpec("_P") + +# Set containing the combination of (namespace, operator, DispatchKey) for which a new kernel has been registered +# The keys in the set are of the form `namespace + "/" + op_name + "/" + dispatch_key`. +# This set is maintained to ensure that two libraries don't try to override the exact same functionality to avoid +# libraries calling into kernels not intended to be called. +_impls: set[str] = set() +_defs: set[str] = set() + +# prim is reserved by TorchScript interpreter +_reserved_namespaces = ["prim"] + + +def fallthrough_kernel(): + """ + A dummy function to pass to ``Library.impl`` in order to register a fallthrough. + """ + raise NotImplementedError("fallthrough_kernel() should never be called.") + + +class Library: + """ + A class to create libraries that can be used to register new operators or + override operators in existing libraries from Python. + A user can optionally pass in a dispatch keyname if they only want to register + kernels corresponding to only one specific dispatch key. + + To create a library to override operators in an existing library (with name ns), set the kind to "IMPL". + To create a new library (with name ns) to register new operators, set the kind to "DEF". + To create a fragment of a possibly existing library to register operators (and bypass + the limitation that there is only one library for a given namespace), set the kind to + "FRAGMENT". + + Args: + ns: library name + kind: "DEF", "IMPL", "FRAGMENT" + dispatch_key: PyTorch dispatch key (default: "") + """ + + def __init__(self, ns, kind, dispatch_key=""): + from torch.fx.operator_schemas import _SCHEMA_TO_SIGNATURE_CACHE + + if kind not in ("IMPL", "DEF", "FRAGMENT"): + raise ValueError("Unsupported kind: ", kind) + + if ns in _reserved_namespaces and (kind == "DEF" or kind == "FRAGMENT"): + raise ValueError( + ns, + " is a reserved namespace. Please try creating a library with another name.", + ) + + frame = traceback.extract_stack(limit=2)[0] + filename, lineno = frame.filename, frame.lineno + self.m: Any | None = torch._C._dispatch_library( + kind, ns, dispatch_key, filename, lineno + ) + self.ns = ns + self._op_defs: set[str] = set() + self._op_impls: set[str] = set() + self._registration_handles: list[torch._library.utils.RegistrationHandle] = [] + self.kind = kind + self.dispatch_key = dispatch_key + # Use a finalizer to setup the "destructor" instead of __del__. + # Python __del__ can lead to weird things (globals and locals may already + # be gone when __del__ actually gets called!). finalizers help the + # situation because it lets us capture references and keeps them alive + weakref.finalize( + self, + _del_library, + _impls, + self._op_impls, + _defs, + self._op_defs, + self._registration_handles, + self.m, + _SCHEMA_TO_SIGNATURE_CACHE, + ) + + def __repr__(self): + return f"Library(kind={self.kind}, ns={self.ns}, dispatch_key={self.dispatch_key})>" + + def define(self, schema, alias_analysis="", *, tags=()): + r"""Defines a new operator and its semantics in the ns namespace. + + Args: + schema: function schema to define a new operator. + alias_analysis (optional): Indicates if the aliasing properties of the operator arguments can be + inferred from the schema (default behavior) or not ("CONSERVATIVE"). + tags (Tag | Sequence[Tag]): one or more torch.Tag to apply to this + operator. Tagging an operator changes the operator's behavior + under various PyTorch subsystems; please read the docs for the + torch.Tag carefully before applying it. + + Returns: + name of the operator as inferred from the schema. + + Example:: + + >>> my_lib = Library("mylib", "DEF") + >>> my_lib.define("sum(Tensor self) -> Tensor") + """ + + # This is added because we also want to disallow PURE_FUNCTION alias analysis which is a valid + # AliasAnalysis type in C++ + if alias_analysis not in ["", "FROM_SCHEMA", "CONSERVATIVE"]: + raise RuntimeError(f"Invalid alias_analysis type {alias_analysis}") + assert self.m is not None + if isinstance(tags, torch.Tag): + tags = (tags,) + + name = schema.split("(")[0] + packet_name = name.split(".")[0] if "." in name else name + has_preexisting_packet = hasattr(torch.ops, self.ns) and hasattr( + getattr(torch.ops, self.ns), packet_name + ) + + result = self.m.define(schema, alias_analysis, tuple(tags)) + name = schema.split("(")[0] + qualname = self.ns + "::" + name + + # If the OpOverloadPacket exists already, then this means we're adding a + # new OpOverload for it. Refresh the packet to include the new OpOverload. + if has_preexisting_packet: + ns = getattr(torch.ops, self.ns) + packet = getattr(ns, packet_name) + torch._ops._refresh_packet(packet) + + self._op_defs.add(qualname) + _defs.add(qualname) + return result + + def _register_fake(self, op_name, fn, _stacklevel=1, *, allow_override=False): + r"""Registers the fake impl for an operator defined in the library.""" + + source = torch._library.utils.get_source(_stacklevel + 1) + frame = sys._getframe(_stacklevel) + caller_module = inspect.getmodule(frame) + # Can be none if you call register_fake from somewhere there isn't a module + # (e.g. __main__) + caller_module_name = None if caller_module is None else caller_module.__name__ + + # TODO(rzou): We're gonna need to stage this change with torchvision, + # since torchvision is github first. + if caller_module_name is not None and caller_module_name.startswith( + "torchvision." + ): + caller_module_name = None + + qualname = f"{self.ns}::{op_name}" + entry = torch._library.simple_registry.singleton.find(qualname) + if caller_module_name is not None: + func_to_register = _check_pystubs_once(fn, qualname, caller_module_name) + else: + func_to_register = fn + + handle = entry.fake_impl.register( + func_to_register, source, lib=self, allow_override=allow_override + ) + self._registration_handles.append(handle) + + def _register_torch_dispatch_rule(self, op_name, torch_dispatch_class, fn): + r"""Registers a torch_dispatch rule for the given operator and torch_dispatch_class. + + This allows for open registration to specify the behavior between the operator + and the torch_dispatch_class without needing to modify the torch_dispatch_class + or the operator directly. + + The torch_dispatch_class is either a Tensor subclass with `__torch_dispatch__` or a + TorchDispatchMode. + + If it is a Tensor subclass, we expect fn to have the following signature: + (cls, func: OpOverload, types: Tuple[type, ...], args, kwargs) -> Any + + If it is a TorchDispatchMode, we expect fn to have the following signature: + (mode, func: OpOverload, types: Tuple[type, ...], args, kwargs) -> Any + """ + + qualname = f"{self.ns}::{op_name}" + entry = torch._library.simple_registry.singleton.find(qualname) + handle = entry.torch_dispatch_rules.register(torch_dispatch_class, fn) + self._registration_handles.append(handle) + + def _impl_with_aoti_compile(self, op_name, dispatch_key=""): + r"""Register the operator to use the AOTI-compiled implementation. + + Args: + op_name: operator name (along with the overload) or OpOverload object. + dispatch_key: dispatch key that the input function should be registered for. By default, it uses + the dispatch key that the library was created with. + + Example:: + + >>> my_lib = Library("aten", "IMPL") + >>> my_lib._impl_with_aoti_compile("div.Tensor", "CPU") + """ + + if dispatch_key == "": + dispatch_key = self.dispatch_key + # pyrefly: ignore [bad-argument-type] + assert torch.DispatchKeySet(dispatch_key).has(torch._C.DispatchKey.Dense) + + if isinstance(op_name, str): + name = op_name + elif isinstance(op_name, OpOverload): + name = op_name._schema.name + overload_name = op_name._schema.overload_name + if overload_name != "": + name = name + "." + overload_name + else: + raise RuntimeError( + "_impl_with_aoti_compile should be passed either a name or an OpOverload object " + "as the first argument" + ) + + key = self.ns + "/" + name.split("::")[-1] + "/" + dispatch_key + if key in _impls: + # TODO: in future, add more info about where the existing function is registered (this info is + # today already returned by the C++ warning when _impl_with_aoti_compile is called but we error out before that) + raise RuntimeError( + "This is not allowed since there's already a kernel registered from python overriding {}" + "'s behavior for {} dispatch key and {} namespace.".format( + name.split("::")[-1], dispatch_key, self.ns + ) + ) + + assert self.m is not None + impl_fn: Callable = self.m.impl_with_aoti_compile + impl_fn(self.ns, name.split("::")[-1], dispatch_key) + + _impls.add(key) + self._op_impls.add(key) + + def impl( + self, op_name, fn, dispatch_key="", *, with_keyset=False, allow_override=False + ): + r"""Registers the function implementation for an operator defined in the library. + + Args: + op_name: operator name (along with the overload) or OpOverload object. + fn: function that's the operator implementation for the input dispatch key or :func:`~fallthrough_kernel` + to register a fallthrough. + dispatch_key: dispatch key that the input function should be registered for. By default, it uses + the dispatch key that the library was created with. + with_keyset: flag controlling if the current dispatcher call keyset should be passed as the first argument + to :attr:`fn` when calling. This should be used to create the appropriate keyset for redispatch calls. + allow_override: Flag controlling if we want to override an + existing registered kernel implementation. This is by + default off, and will error you're trying to register a + kernel to a dispatch key with a kernel already + registered. + + Example:: + + >>> my_lib = Library("aten", "IMPL") + >>> def div_cpu(self, other): + >>> return self * (1 / other) + >>> my_lib.impl("div.Tensor", div_cpu, "CPU") + """ + + if not callable(fn): + raise TypeError( + f"Input function is required to be a callable but found type {type(fn)}" + ) + if dispatch_key == "": + dispatch_key = self.dispatch_key + + if isinstance(op_name, str): + name = op_name + elif isinstance(op_name, OpOverload): + name = op_name._schema.name + overload_name = op_name._schema.overload_name + if overload_name != "": + name = name + "." + overload_name + else: + raise RuntimeError( + "impl should be passed either a name or an OpOverload object as the first argument" + ) + + key = self.ns + "/" + name.split("::")[-1] + "/" + dispatch_key + if (not allow_override) and key in _impls: + # TODO: in future, add more info about where the existing function is registered (this info is + # today already returned by the C++ warning when impl is called but we error out before that) + raise RuntimeError( + "This is not allowed since there's already a kernel registered from python overriding {}" + "'s behavior for {} dispatch key and {} namespace.".format( + name.split("::")[-1], dispatch_key, self.ns + ) + ) + + if dispatch_key == "Meta": + dispatcher_op_name = name + if "::" not in dispatcher_op_name: + dispatcher_op_name = f"{self.ns}::{dispatcher_op_name}" + + # Internally, we shouldn't be registering meta kernels for any operators that + # have CompositeImplicitAutograd kernels. + # Instead, we should be letting those decompositions run, and writing meta kernels + # only for the base operators. + if torch._C._dispatch_has_kernel_for_dispatch_key( + dispatcher_op_name, "CompositeImplicitAutograd" + ): + raise RuntimeError( + f"We should not register a meta kernel directly to the operator '{name}'," + " because it has a CompositeImplicitAutograd kernel in core." + " Instead we should let the operator decompose, and ensure that we have meta kernels" + " for the base ops that it decomposes into." + ) + + assert self.m is not None + self.m.impl( + name, + dispatch_key if dispatch_key != "" else "CompositeImplicitAutograd", + fn, + with_keyset, + ) + + _impls.add(key) + self._op_impls.add(key) + + def fallback(self, fn, dispatch_key="", *, with_keyset=False): + r"""Registers the function implementation as the fallback for the given key. + + This function only works for a library with global namespace ("_"). + + Args: + fn: function used as fallback for the given dispatch key or :func:`~fallthrough_kernel` + to register a fallthrough. + dispatch_key: dispatch key that the input function should be registered for. By default, it uses + the dispatch key that the library was created with. + with_keyset: flag controlling if the current dispatcher call keyset should be passed as the first argument + to :attr:`fn` when calling. This should be used to create the appropriate keyset for redispatch calls. + + Example:: + + >>> my_lib = Library("_", "IMPL") + >>> def fallback_kernel(op, *args, **kwargs): + >>> # Handle all autocast ops generically + >>> # ... + >>> my_lib.fallback(fallback_kernel, "Autocast") + """ + + if dispatch_key == "": + dispatch_key = self.dispatch_key + + if self.ns != "_": + raise RuntimeError( + f"""Fallback can only be registered using library fragment on the global namespace "_" but it is {self.ns}""" + ) + + assert dispatch_key != "" + assert self.m is not None + + self.m.fallback(dispatch_key, fn, with_keyset) + + def _register_effectful_op(self, op_name: str, effect: EffectType | None): + """ + Registers an effect to an operator. This is used to register an op that + has side effects that is not capturable by the schema. + + Args: + op_name: operator name (along with the overload) or OpOverload object. + effect: The effect of the op. + """ + from torch._higher_order_ops.effects import ( + _register_effectful_op as hoo_register_effect, + ) + + handle = hoo_register_effect(op_name, effect) + self._registration_handles.append(handle) + + def _destroy(self): + if self.m is not None: + self.m.reset() + self.m = None + for handle in self._registration_handles: + handle.destroy() + self._registration_handles.clear() + global _impls + _impls -= self._op_impls + for name in self._op_defs: + # Delete the cached torch.ops.ns.foo if it was registered. + # Otherwise, accessing it leads to a segfault. + # It's possible that we only registered an overload in this Library + # and another library owns an alive overload. + # That's OK - the next time torch.ops.ns.foo gets called, it'll be + # recomputed to point at the right collection of overloads. + ns, name_with_overload = name.split("::") + name = name_with_overload.split(".")[0] + if not hasattr(torch.ops, ns): + continue + namespace = getattr(torch.ops, ns) + if not hasattr(namespace, name): + continue + delattr(namespace, name) + namespace._dir.remove(name) + + +def _del_library( + captured_impls, + op_impls, + captured_defs, + op_defs, + registration_handles, + m, + schema_to_signature_cache, +): + for op_def in op_defs: + name = op_def + overload_name = "" + if "." in op_def: + name, overload_name = op_def.split(".") + if ( + name, + overload_name, + ) in schema_to_signature_cache: + del schema_to_signature_cache[(name, overload_name)] + + captured_impls -= op_impls + captured_defs -= op_defs + for handle in registration_handles: + handle.destroy() + + if m is not None: + m.reset() + + +@contextlib.contextmanager +def _scoped_library(*args, **kwargs): + try: + lib = Library(*args, **kwargs) + yield lib + finally: + lib._destroy() + + +_keep_alive: list[Library] = [] + + +NAMELESS_SCHEMA = re.compile(r"\(.*\) -> .*") + + +@functools.singledispatch +def define(qualname, schema, *, lib=None, tags=()): + r"""Defines a new operator. + + In PyTorch, defining an op (short for "operator") is a two step-process: + - we need to define the op (by providing an operator name and schema) + - we need to implement behavior for how the operator interacts with + various PyTorch subsystems, like CPU/CUDA Tensors, Autograd, etc. + + This entrypoint defines the custom operator (the first step) + you must then perform the second step by calling various + ``impl_*`` APIs, like :func:`torch.library.impl` or + :func:`torch.library.register_fake`. + + Args: + qualname (str): The qualified name for the operator. Should be + a string that looks like "namespace::name", e.g. "aten::sin". + Operators in PyTorch need a namespace to + avoid name collisions; a given operator may only be created once. + If you are writing a Python library, we recommend the namespace to + be the name of your top-level module. + schema (str): The schema of the operator. E.g. "(Tensor x) -> Tensor" + for an op that accepts one Tensor and returns one Tensor. It does + not contain the operator name (that is passed in ``qualname``). + lib (Optional[Library]): If provided, the lifetime of this operator + will be tied to the lifetime of the Library object. + tags (Tag | Sequence[Tag]): one or more torch.Tag to apply to this + operator. Tagging an operator changes the operator's behavior + under various PyTorch subsystems; please read the docs for the + torch.Tag carefully before applying it. + + Example:: + >>> import torch + >>> import numpy as np + >>> + >>> # Define the operator + >>> torch.library.define("mylib::sin", "(Tensor x) -> Tensor") + >>> + >>> # Add implementations for the operator + >>> @torch.library.impl("mylib::sin", "cpu") + >>> def f(x): + >>> return torch.from_numpy(np.sin(x.numpy())) + >>> + >>> # Call the new operator from torch.ops. + >>> x = torch.randn(3) + >>> y = torch.ops.mylib.sin(x) + >>> assert torch.allclose(y, x.sin()) + + """ + if not isinstance(qualname, str): + raise ValueError( + f"define(qualname, schema): expected qualname " + f"to be instance of str, got {type(qualname)}" + ) + namespace, name = torch._library.utils.parse_namespace(qualname) + if lib is None: + lib = Library(namespace, "FRAGMENT") + _keep_alive.append(lib) + if not NAMELESS_SCHEMA.fullmatch(schema): + raise ValueError( + f"define(qualname, schema, ...): expected schema " + f'to look like e.g. "(Tensor x) -> Tensor" but ' + f'got "{schema}"' + ) + lib.define(name + schema, alias_analysis="", tags=tags) + + +@define.register +def _(lib: Library, schema, alias_analysis=""): + """The old torch.library.define. + We're keeping this around for BC reasons + """ + + def wrap(f): + name = lib.define(schema, alias_analysis) + lib.impl(name, f) + return f + + return wrap + + +@overload +def impl( + qualname: str, + types: str | Sequence[str], + func: None = None, + *, + lib: Library | None = None, +) -> Callable[[Callable[..., object]], None]: ... + + +@overload +def impl( + qualname: str, + types: str | Sequence[str], + func: Callable[..., object], + *, + lib: Library | None = None, +) -> None: ... + + +# Deprecated BC API +@overload +def impl( + lib: Library, + name: str, + dispatch_key: str = "", +) -> Callable[[Callable[_P, _T]], Callable[_P, _T]]: ... + + +@functools.singledispatch +def impl( + qualname: str, + types: str | Sequence[str], + func: Callable[_P, _T] | None = None, + *, + lib: Library | None = None, +) -> object: + """Register an implementation for a device type for this operator. + + You may pass "default" for ``types`` to register this implementation as the + default implementation for ALL device types. + Please only use this if the implementation truly supports all device types; + for example, this is true if it is a composition of built-in PyTorch operators. + + This API may be used as a decorator. You can use nested decorators + with this API provided they return a function and are placed inside + this API (see Example 2). + + Some valid types are: "cpu", "cuda", "xla", "mps", "ipu", "xpu". + + Args: + qualname (str): Should be a string that looks like "namespace::operator_name". + types (str | Sequence[str]): The device types to register an impl to. + lib (Optional[Library]): If provided, the lifetime of this registration + will be tied to the lifetime of the Library object. + + Examples: + >>> import torch + >>> import numpy as np + >>> # Example 1: Register function. + >>> # Define the operator + >>> torch.library.define("mylib::mysin", "(Tensor x) -> Tensor") + >>> + >>> # Add implementations for the cpu device + >>> @torch.library.impl("mylib::mysin", "cpu") + >>> def f(x): + >>> return torch.from_numpy(np.sin(x.numpy())) + >>> + >>> x = torch.randn(3) + >>> y = torch.ops.mylib.mysin(x) + >>> assert torch.allclose(y, x.sin()) + >>> + >>> # Example 2: Register function with decorator. + >>> def custom_decorator(func): + >>> def wrapper(*args, **kwargs): + >>> return func(*args, **kwargs) + 1 + >>> return wrapper + >>> + >>> # Define the operator + >>> torch.library.define("mylib::sin_plus_one", "(Tensor x) -> Tensor") + >>> + >>> # Add implementations for the operator + >>> @torch.library.impl("mylib::sin_plus_one", "cpu") + >>> @custom_decorator + >>> def f(x): + >>> return torch.from_numpy(np.sin(x.numpy())) + >>> + >>> # Call the new operator from torch.ops. + >>> x = torch.randn(3) + >>> + >>> y1 = torch.ops.mylib.sin_plus_one(x) + >>> y2 = torch.sin(x) + 1 + >>> assert torch.allclose(y1, y2) + """ + + return _impl(qualname, types, func, lib=lib, disable_dynamo=False) + + +if not TYPE_CHECKING: + + @impl.register + def _( + lib: Library, name: str, dispatch_key: str = "" + ) -> Callable[[Callable[_P, _T]], Callable[_P, _T]]: + """Legacy torch.library.impl API. Kept around for BC""" + + def wrap(f: Callable[_P, _T]) -> Callable[_P, _T]: + lib.impl(name, f, dispatch_key) + return f + + return wrap + + +@overload +def _impl( + qualname: str, + types: str | Sequence[str], + func: None = None, + *, + lib: Library | None = None, + disable_dynamo: bool = False, +) -> Callable[[Callable[..., object]], None]: ... + + +@overload +def _impl( + qualname: str, + types: str | Sequence[str], + func: Callable[..., object], + *, + lib: Library | None = None, + disable_dynamo: bool = False, +) -> None: ... + + +def _impl( + qualname: str, + types: str | Sequence[str], + func: Callable[..., object] | None = None, + *, + lib: Library | None = None, + disable_dynamo: bool = False, +) -> Callable[[Callable[..., object]], None] | None: + # See impl() + if isinstance(types, str): + types = (types,) + keys = set({}) + for typ in types: + is_dispatch_key = torch._C._parse_dispatch_key(typ) + if is_dispatch_key: + # We also support passing a DispatchKey to impl. Please prefer using + # the higher-level torch.library APIs and only pass DispatchKey to + # torch.library.impl with caution (or even better, don't use this + # option and file an issue on GitHub for what you need). + # We don't advertise this to users because + # it is very easy to shoot yourself in the foot. + keys.add(typ) + else: + keys.add(_device_type_to_key(typ)) + + def register_(func: Callable[..., object]) -> None: + namespace, _ = torch._library.utils.parse_namespace(qualname) + + if lib is None: + use_lib = Library(namespace, "FRAGMENT") + _keep_alive.append(use_lib) + else: + use_lib = lib + if disable_dynamo: + + @torch._disable_dynamo + def func_no_dynamo(*args, **kwargs): + return func(*args, **kwargs) + + for key in keys: + use_lib.impl(qualname, func_no_dynamo, key) + else: + for key in keys: + use_lib.impl(qualname, func, key) + + if func is None: + return register_ + else: + register_(func) + return None + + +def _device_type_to_key(device_type: str) -> str: + if device_type == "default": + # This is technically not correct, because although all device_type + # DispatchKeys are included in CompositeExplicitAutograd, + # not everything in CompositeExplicitAutograd is associated with a + # device_type. I don't really care that much about the difference. + return "CompositeExplicitAutograd" + return torch._C._dispatch_key_for_device(device_type) + + +@deprecated( + "`torch.library.impl_abstract` was renamed to `torch.library.register_fake`. Please use that " + "instead; we will remove `torch.library.impl_abstract` in a future version of PyTorch.", + category=FutureWarning, +) +def impl_abstract(qualname, func=None, *, lib=None, _stacklevel=1): + r"""This API was renamed to :func:`torch.library.register_fake` in PyTorch 2.4. + Please use that instead. + """ + if func is not None: + _stacklevel = _stacklevel + 1 + return register_fake(qualname, func, lib=lib, _stacklevel=_stacklevel) + + +_op_identifier = Union[ + str, "torch._ops.OpOverload", "torch._library.custom_ops.CustomOpDef" +] + + +def register_kernel( + op: _op_identifier, + device_types: device_types_t, + func: Callable | None = None, + /, + *, + lib: Library | None = None, +): + """Register an implementation for a device type for this operator. + + Some valid device_types are: "cpu", "cuda", "xla", "mps", "ipu", "xpu". + This API may be used as a decorator. + + Args: + op (str | OpOverload): The operator to register an impl to. + device_types (None | str | Sequence[str]): The device_types to register an impl to. + If None, we will register to all device types -- please only use + this option if your implementation is truly device-type-agnostic. + func (Callable): The function to register as the implementation for + the given device types. + lib (Optional[Library]): If provided, the lifetime of this registration + + Examples:: + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA) + >>> import torch + >>> from torch import Tensor + >>> from torch.library import custom_op + >>> import numpy as np + >>> + >>> # Create a custom op that works on cpu + >>> @custom_op("mylib::numpy_sin", mutates_args=(), device_types="cpu") + >>> def numpy_sin(x: Tensor) -> Tensor: + >>> x_np = x.numpy() + >>> y_np = np.sin(x_np) + >>> return torch.from_numpy(y_np) + >>> + >>> # Add implementations for the cuda device + >>> @torch.library.register_kernel("mylib::numpy_sin", "cuda") + >>> def _(x): + >>> x_np = x.cpu().numpy() + >>> y_np = np.sin(x_np) + >>> return torch.from_numpy(y_np).to(device=x.device) + >>> + >>> x_cpu = torch.randn(3) + >>> x_cuda = x_cpu.cuda() + >>> assert torch.allclose(numpy_sin(x_cpu), x_cpu.sin()) + >>> assert torch.allclose(numpy_sin(x_cuda), x_cuda.sin()) + + """ + + if not isinstance( + op, (str, torch._ops.OpOverload, torch._library.custom_ops.CustomOpDef) + ): + raise ValueError( + f"register_kernel({op}): got unexpected type for op: {type(op)}" + ) + if isinstance(op, torch._ops.OpOverload): + op = op._name + opdef = _maybe_get_opdef(op) + if opdef is not None: + return opdef.register_kernel(device_types, func) + assert isinstance(op, str) + if device_types is None: + device_types = "CompositeExplicitAutograd" + + return _impl(op, device_types, func, lib=lib, disable_dynamo=True) + + +def register_autocast( + op: _op_identifier, + device_type: str, + cast_inputs: _dtype, + /, + *, + lib: Library | None = None, +): + r"""Register an autocast dispatch rule for this custom op. + + Valid `device_type` include: "cpu" and "cuda". + + Args: + op (str | OpOverload): The operator to register an autocast dispatch rule to. + device_type(str): Device type to use. 'cuda' or 'cpu'. + The type is the same as the `type` attribute of a :class:`torch.device`. + Thus, you may obtain the device type of a tensor using `Tensor.device.type`. + cast_inputs (:class:`torch.dtype`): When custom op runs in an autocast-enabled region, + casts incoming floating-point Tensors to the target dtype (non-floating-point Tensors + are not affected), then executes custom op with autocast disabled. + lib (Optional[Library]): If provided, the lifetime of this registration + + Examples:: + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA) + >>> import torch + >>> from torch import Tensor + >>> from torch.library import custom_op + >>> + >>> # Create a custom op that works on cuda + >>> @torch.library.custom_op("mylib::my_sin", mutates_args=()) + >>> def my_sin(x: Tensor) -> Tensor: + >>> return torch.sin(x) + >>> + >>> # Register autocast dispatch rule for the cuda device + >>> torch.library.register_autocast("mylib::my_sin", "cuda", torch.float16) + >>> + >>> x = torch.randn(3, dtype=torch.float32, device="cuda") + >>> with torch.autocast("cuda", dtype=torch.float16): + >>> y = torch.ops.mylib.my_sin(x) + >>> assert y.dtype == torch.float16 + + """ + if not isinstance( + op, (str, torch._ops.OpOverload, torch._library.custom_ops.CustomOpDef) + ): + raise ValueError( + f"register_autocast({op}): got unexpected type for op: {type(op)}" + ) + if device_type not in ["cpu", "cuda"]: + raise ValueError(f"Unknown device type: {device_type}") + + if isinstance(op, torch._ops.OpOverload): + op = op._name + opdef = _maybe_get_opdef(op) + if opdef is not None: + return opdef.register_autocast(device_type, cast_inputs) + + assert isinstance(op, str) + qualname = op + _op = torch._library.utils.lookup_op(qualname) + + namespace, opname = torch._library.utils.parse_namespace(qualname) + if lib is None: + lib = Library(namespace, "FRAGMENT") + _keep_alive.append(lib) + + def _maybe_override_py_impl(op: torch._ops.OpOverload, dispatch_key): + def inner(kernel): + if op.has_kernel_for_dispatch_key(dispatch_key): + op.py_kernels.pop(dispatch_key) + return op.py_impl(dispatch_key)(kernel) + + return inner + + @_maybe_override_py_impl(_op, torch._C.DispatchKey.AutocastCPU) + @_maybe_override_py_impl(_op, torch._C.DispatchKey.AutocastCUDA) + def _autocast_py_impl(*args, **kwargs): + assert len(kwargs) == 0, "Custom ops do not support kwargs yet." + autocast_keyset = torch._C.DispatchKeySet( + torch._C.DispatchKey.AutocastCPU + ) | torch._C.DispatchKeySet(torch._C.DispatchKey.AutocastCUDA) + with torch._C._ExcludeDispatchKeyGuard(autocast_keyset): + return _op(*_cast(args, device_type, cast_inputs)) + + def kernel(_, *args, **kwargs): + assert len(kwargs) == 0, "Custom ops do not support kwargs yet." + return _autocast_py_impl(*args, **kwargs) + + if device_type == "cuda": + return lib.impl(opname, kernel, "AutocastCUDA", with_keyset=True) + else: + # device_type is "cpu" + return lib.impl(opname, kernel, "AutocastCPU", with_keyset=True) + + +def register_fake( + op: _op_identifier, + func: Callable | None = None, + /, + *, + lib: Library | None = None, + _stacklevel: int = 1, + allow_override: bool = False, +): + r"""Register a FakeTensor implementation ("fake impl") for this operator. + + Also sometimes known as a "meta kernel", "abstract impl". + + An "FakeTensor implementation" specifies the behavior of this operator on + Tensors that carry no data ("FakeTensor"). Given some input Tensors with + certain properties (sizes/strides/storage_offset/device), it specifies + what the properties of the output Tensors are. + + The FakeTensor implementation has the same signature as the operator. + It is run for both FakeTensors and meta tensors. To write a FakeTensor + implementation, assume that all Tensor inputs to the operator are + regular CPU/CUDA/Meta tensors, but they do not have storage, and + you are trying to return regular CPU/CUDA/Meta tensor(s) as output. + The FakeTensor implementation must consist of only PyTorch operations + (and may not directly access the storage or data of any input or + intermediate Tensors). + + This API may be used as a decorator (see examples). + + For a detailed guide on custom ops, please see + https://pytorch.org/tutorials/advanced/custom_ops_landing_page.html + + Args: + op_name: Operator name (along with the overload) or OpOverload object. + func: Fake tensor implementation. + lib (Optional[Library]): Library to register the fake tensor to. + allow_override: Flag controlling if we want to override an + existing registered fake impl. This is by default off, + and will error you're trying to register a fake impl to + an operator that already has a fake impl. This also only + applies if the custom operator was not created via + torch.library.custom_op, as overriding and existing fake + impl is already allowed. + + Examples: + >>> import torch + >>> import numpy as np + >>> from torch import Tensor + >>> + >>> # Example 1: an operator without data-dependent output shape + >>> @torch.library.custom_op("mylib::custom_linear", mutates_args=()) + >>> def custom_linear(x: Tensor, weight: Tensor, bias: Tensor) -> Tensor: + >>> raise NotImplementedError("Implementation goes here") + >>> + >>> @torch.library.register_fake("mylib::custom_linear") + >>> def _(x, weight, bias): + >>> assert x.dim() == 2 + >>> assert weight.dim() == 2 + >>> assert bias.dim() == 1 + >>> assert x.shape[1] == weight.shape[1] + >>> assert weight.shape[0] == bias.shape[0] + >>> assert x.device == weight.device + >>> + >>> return (x @ weight.t()) + bias + >>> + >>> with torch._subclasses.fake_tensor.FakeTensorMode(): + >>> x = torch.randn(2, 3) + >>> w = torch.randn(3, 3) + >>> b = torch.randn(3) + >>> y = torch.ops.mylib.custom_linear(x, w, b) + >>> + >>> assert y.shape == (2, 3) + >>> + >>> # Example 2: an operator with data-dependent output shape + >>> @torch.library.custom_op("mylib::custom_nonzero", mutates_args=()) + >>> def custom_nonzero(x: Tensor) -> Tensor: + >>> x_np = x.numpy(force=True) + >>> res = np.stack(np.nonzero(x_np), axis=1) + >>> return torch.tensor(res, device=x.device) + >>> + >>> @torch.library.register_fake("mylib::custom_nonzero") + >>> def _(x): + >>> # Number of nonzero-elements is data-dependent. + >>> # Since we cannot peek at the data in an fake impl, + >>> # we use the ctx object to construct a new symint that + >>> # represents the data-dependent size. + >>> ctx = torch.library.get_ctx() + >>> nnz = ctx.new_dynamic_size() + >>> shape = [nnz, x.dim()] + >>> result = x.new_empty(shape, dtype=torch.int64) + >>> return result + >>> + >>> from torch.fx.experimental.proxy_tensor import make_fx + >>> + >>> x = torch.tensor([0, 1, 2, 3, 4, 0]) + >>> trace = make_fx(torch.ops.mylib.custom_nonzero, tracing_mode="symbolic")(x) + >>> trace.print_readable() + >>> + >>> assert torch.allclose(trace(x), torch.ops.mylib.custom_nonzero(x)) + + """ + if not isinstance( + op, (str, torch._ops.OpOverload, torch._library.custom_ops.CustomOpDef) + ): + raise ValueError(f"register_fake({op}): got unexpected type for op: {type(op)}") + if isinstance(op, torch._ops.OpOverload): + op = op._name + opdef = _maybe_get_opdef(op) + if opdef is not None: + if func is None: + return opdef.register_fake + else: + return opdef.register_fake(func) + assert isinstance(op, str) + + stacklevel = _stacklevel + + def register(func): + namespace, op_name = torch._library.utils.parse_namespace(op) + if lib is None: + use_lib = Library(namespace, "FRAGMENT") + _keep_alive.append(use_lib) + else: + use_lib = lib + use_lib._register_fake( + op_name, func, _stacklevel=stacklevel + 1, allow_override=allow_override + ) + return func + + if func is None: + return register + else: + stacklevel += 1 + return register(func) + + +def _register_effectful_op( + op: _op_identifier, + effect: EffectType | None, + *, + lib: Library | None = None, +) -> None: + r""" + To specify that an operator has side-effects, we must register an effect + type for the operator. This will prevent graph passes in torch.compile from + reordering operations with the same effect type. + + Args: + op_name: Operator name (along with the overload) or OpOverload object. + effect: Effect type to register. None means the operator is not effectful. + """ + if not isinstance( + op, (str, torch._ops.OpOverload, torch._library.custom_ops.CustomOpDef) + ): + raise ValueError( + f"register_effectful_op({op}): got unexpected type for op: {type(op)}" + ) + + if isinstance(op, torch._ops.OpOverload): + op = op._name + opdef = _maybe_get_opdef(op) + if opdef is not None: + opdef.register_effect(effect) + assert isinstance(op, str) + + namespace, _ = torch._library.utils.parse_namespace(op) + if lib is None: + use_lib = Library(namespace, "FRAGMENT") + _keep_alive.append(use_lib) + else: + use_lib = lib + use_lib._register_effectful_op(op, effect) + + +def register_autograd( + op: _op_identifier, + backward: Callable, + /, + *, + setup_context: Callable | None = None, + lib=None, +) -> None: + r"""Register a backward formula for this custom op. + + In order for an operator to work with autograd, you need to register + a backward formula: + 1. You must tell us how to compute gradients during the backward pass + by providing us a "backward" function. + 2. If you need any values from the forward to compute gradients, you can + use `setup_context` to save values for backward. + + ``backward`` runs during the backward pass. It accepts ``(ctx, *grads)``: + - ``grads`` is one or more gradients. The number of gradients matches + the number of outputs of the operator. + The ``ctx`` object is `the same ctx object `_ used by + :class:`torch.autograd.Function`. The semantics of ``backward_fn`` are the + same as :meth:`torch.autograd.Function.backward`. + + ``setup_context(ctx, inputs, output)`` runs during the forward pass. + Please save quantities needed for backward onto the ``ctx`` object via + either :meth:`torch.autograd.function.FunctionCtx.save_for_backward` + or assigning them as attributes of ``ctx``. If your custom op has + kwarg-only arguments, we expect the signature of ``setup_context`` + to be ``setup_context(ctx, inputs, keyword_only_inputs, output)``. + + Both ``setup_context_fn`` and ``backward_fn`` must be traceable. That is, + they may not directly access :meth:`torch.Tensor.data_ptr` and they must + not depend on or mutate global state. If you need a non-traceable backward, + you can make it a separate custom_op that you call inside ``backward_fn``. + + If you need different autograd behavior on different devices, then we + recommend creating two different custom operators, one for each device + that needs different behavior, and switching between them at runtime. + + Examples: + >>> import torch + >>> import numpy as np + >>> from torch import Tensor + >>> + >>> @torch.library.custom_op("mylib::numpy_sin", mutates_args=()) + >>> def numpy_sin(x: Tensor) -> Tensor: + >>> x_np = x.cpu().numpy() + >>> y_np = np.sin(x_np) + >>> return torch.from_numpy(y_np).to(device=x.device) + >>> + >>> def setup_context(ctx, inputs, output) -> Tensor: + >>> x, = inputs + >>> ctx.save_for_backward(x) + >>> + >>> def backward(ctx, grad): + >>> x, = ctx.saved_tensors + >>> return grad * x.cos() + >>> + >>> torch.library.register_autograd( + ... "mylib::numpy_sin", backward, setup_context=setup_context + ... ) + >>> + >>> x = torch.randn(3, requires_grad=True) + >>> y = numpy_sin(x) + >>> (grad_x,) = torch.autograd.grad(y, x, torch.ones_like(y)) + >>> assert torch.allclose(grad_x, x.cos()) + >>> + >>> # Example with a keyword-only arg + >>> @torch.library.custom_op("mylib::numpy_mul", mutates_args=()) + >>> def numpy_mul(x: Tensor, *, val: float) -> Tensor: + >>> x_np = x.cpu().numpy() + >>> y_np = x_np * val + >>> return torch.from_numpy(y_np).to(device=x.device) + >>> + >>> def setup_context(ctx, inputs, keyword_only_inputs, output) -> Tensor: + >>> ctx.val = keyword_only_inputs["val"] + >>> + >>> def backward(ctx, grad): + >>> return grad * ctx.val + >>> + >>> torch.library.register_autograd( + ... "mylib::numpy_mul", backward, setup_context=setup_context + ... ) + >>> + >>> x = torch.randn(3, requires_grad=True) + >>> y = numpy_mul(x, val=3.14) + >>> (grad_x,) = torch.autograd.grad(y, x, torch.ones_like(y)) + >>> assert torch.allclose(grad_x, torch.full_like(x, 3.14)) + + """ + if not isinstance( + op, (str, torch._ops.OpOverload, torch._library.custom_ops.CustomOpDef) + ): + raise ValueError( + f"register_autograd({op}): got unexpected type for op: {type(op)}" + ) + if isinstance(op, torch._ops.OpOverload): + op = op._name + opdef = _maybe_get_opdef(op) + if opdef is not None: + opdef.register_autograd(backward, setup_context=setup_context) + return + + assert isinstance(op, str) + qualname = op + op = torch._library.utils.lookup_op(qualname) + schema = op._schema + if not _library.utils.is_functional_schema(schema): + raise RuntimeError( + f"Cannot register autograd formula for non-functional operator " + f"{op} with schema {schema}. Please create " + f"a functional operator and register an autograd formula for that." + ) + if _library.utils.has_kwarg_only_tensors(schema): + raise NotImplementedError( + f"register_autograd with kwarg-only Tensor args. In the original " + f"definition of the op, please make your tensors not kwarg-only. " + f"Got: {schema}" + ) + + info = _library.autograd.Info(backward, setup_context) + autograd_kernel = _library.autograd.make_autograd_impl(op, info) + namespace, opname = torch._library.utils.parse_namespace(qualname) + if lib is None: + lib = Library(namespace, "FRAGMENT") + _keep_alive.append(lib) + lib.impl(opname, autograd_kernel, "Autograd", with_keyset=True) + + +def register_torch_dispatch( + op: _op_identifier, + torch_dispatch_class: Any, + func: Callable | None = None, + /, + *, + lib: Library | None = None, +): + r"""Registers a torch_dispatch rule for the given operator and ``torch_dispatch_class``. + + This allows for open registration to specify the behavior between the operator + and the ``torch_dispatch_class`` without needing to modify the ``torch_dispatch_class`` + or the operator directly. + + The ``torch_dispatch_class`` is either a Tensor subclass with ``__torch_dispatch__`` or a + TorchDispatchMode. + + If it is a Tensor subclass, we expect ``func`` to have the following signature: + ``(cls, func: OpOverload, types: Tuple[type, ...], args, kwargs) -> Any`` + + If it is a TorchDispatchMode, we expect ``func`` to have the following signature: + ``(mode, func: OpOverload, types: Tuple[type, ...], args, kwargs) -> Any`` + + ``args`` and ``kwargs`` will have been normalized the same way they are + in ``__torch_dispatch__`` (see :ref:`torch-dispatch-calling-convention`). + + Examples: + + >>> import torch + >>> + >>> @torch.library.custom_op("mylib::foo", mutates_args={}) + >>> def foo(x: torch.Tensor) -> torch.Tensor: + >>> return x.clone() + >>> + >>> class MyMode(torch.utils._python_dispatch.TorchDispatchMode): + >>> def __torch_dispatch__(self, func, types, args=(), kwargs=None): + >>> return func(*args, **kwargs) + >>> + >>> @torch.library.register_torch_dispatch("mylib::foo", MyMode) + >>> def _(mode, func, types, args, kwargs): + >>> x, = args + >>> return x + 1 + >>> + >>> x = torch.randn(3) + >>> y = foo(x) + >>> assert torch.allclose(y, x) + >>> + >>> with MyMode(): + >>> y = foo(x) + >>> assert torch.allclose(y, x + 1) + + """ + if not isinstance( + op, (str, torch._ops.OpOverload, torch._library.custom_ops.CustomOpDef) + ): + raise ValueError( + f"register_torch_dispatch({op}): got unexpected type for op: {type(op)}" + ) + if isinstance(op, torch._ops.OpOverload): + op = op._name + opdef = _maybe_get_opdef(op) + if opdef is not None: + return opdef.register_torch_dispatch(torch_dispatch_class, func) + assert isinstance(op, str) + + def register(func): + namespace, op_name = torch._library.utils.parse_namespace(op) + if lib is None: + use_lib = Library(namespace, "FRAGMENT") + _keep_alive.append(use_lib) + else: + use_lib = lib + use_lib._register_torch_dispatch_rule(op_name, torch_dispatch_class, func) + return func + + if func is None: + return register + else: + return register(func) + + +def register_vmap( + op: _op_identifier, + func: Callable | None = None, + /, + *, + lib=None, +): + r"""Register a vmap implementation to support :func:`torch.vmap` for this custom op. + + This API may be used as a decorator (see examples). + + In order for an operator to work with :func:`torch.vmap`, you may need to register a + vmap implementation in the following signature: + + ``vmap_func(info, in_dims: Tuple[Optional[int]], *args, **kwargs)``, + + where ``*args`` and ``**kwargs`` are the arguments and kwargs for ``op``. + We do not support kwarg-only Tensor args. + + It specifies how do we compute the batched version of ``op`` given inputs with an additional + dimension (specified by ``in_dims``). + + For each arg in ``args``, ``in_dims`` has a corresponding ``Optional[int]``. It is ``None`` + if the arg is not a Tensor or if the arg is not being vmapped over, otherwise, it is an integer + specifying what dimension of the Tensor is being vmapped over. + + ``info`` is a collection of additional metadata that may be helpful: + ``info.batch_size`` specifies the size of the dimension being vmapped over, while + ``info.randomness`` is the ``randomness`` option that was passed to :func:`torch.vmap`. + + The return of the function ``func`` is a tuple of ``(output, out_dims)``. Similar to ``in_dims``, + ``out_dims`` should be of the same structure as ``output`` and contain one ``out_dim`` + per output that specifies if the output has the vmapped dimension and what index it is in. + + Examples: + >>> import torch + >>> import numpy as np + >>> from torch import Tensor + >>> from typing import Tuple + >>> + >>> def to_numpy(tensor): + >>> return tensor.cpu().numpy() + >>> + >>> lib = torch.library.Library("mylib", "FRAGMENT") + >>> @torch.library.custom_op("mylib::numpy_cube", mutates_args=()) + >>> def numpy_cube(x: Tensor) -> Tuple[Tensor, Tensor]: + >>> x_np = to_numpy(x) + >>> dx = torch.tensor(3 * x_np ** 2, device=x.device) + >>> return torch.tensor(x_np ** 3, device=x.device), dx + >>> + >>> def numpy_cube_vmap(info, in_dims, x): + >>> result = numpy_cube(x) + >>> return result, (in_dims[0], in_dims[0]) + >>> + >>> torch.library.register_vmap(numpy_cube, numpy_cube_vmap) + >>> + >>> x = torch.randn(3) + >>> torch.vmap(numpy_cube)(x) + >>> + >>> @torch.library.custom_op("mylib::numpy_mul", mutates_args=()) + >>> def numpy_mul(x: Tensor, y: Tensor) -> Tensor: + >>> return torch.tensor(to_numpy(x) * to_numpy(y), device=x.device) + >>> + >>> @torch.library.register_vmap("mylib::numpy_mul") + >>> def numpy_mul_vmap(info, in_dims, x, y): + >>> x_bdim, y_bdim = in_dims + >>> x = x.movedim(x_bdim, -1) if x_bdim is not None else x.unsqueeze(-1) + >>> y = y.movedim(y_bdim, -1) if y_bdim is not None else y.unsqueeze(-1) + >>> result = x * y + >>> result = result.movedim(-1, 0) + >>> return result, 0 + >>> + >>> + >>> x = torch.randn(3) + >>> y = torch.randn(3) + >>> torch.vmap(numpy_mul)(x, y) + + .. note:: + The vmap function should aim to preserve the semantics of the entire custom operator. + That is, ``grad(vmap(op))`` should be replaceable with a ``grad(map(op))``. + + If your custom operator has any custom behavior in the backward pass, please + keep this in mind. + + """ + if not isinstance( + op, (str, torch._ops.OpOverload, torch._library.custom_ops.CustomOpDef) + ): + raise ValueError(f"register_vmap({op}): got unexpected type for op: {type(op)}") + if isinstance(op, torch._ops.OpOverload): + op = op._name + opdef = _maybe_get_opdef(op) + if opdef is not None: + return opdef.register_vmap(func) + assert isinstance(op, str) + qualname = op + op = torch._library.utils.lookup_op(qualname) + schema = op._schema + if _library.utils.has_kwarg_only_tensors(schema): + raise NotImplementedError( + f"register_vmap with kwarg-only Tensor args. In the original " + f"definition of the op, please make your tensors not kwarg-only. " + f"Got: {schema}" + ) + + def register(func): + nonlocal op, lib + + namespace, opname = torch._library.utils.parse_namespace(qualname) + if lib is None: + lib = Library(namespace, "FRAGMENT") + _keep_alive.append(lib) + + from torch._functorch.autograd_function import custom_function_call_vmap_helper + from torch._functorch.pyfunctorch import retrieve_current_functorch_interpreter + + def wrapped_func(keyset, *args, **kwargs): + interpreter = retrieve_current_functorch_interpreter() + return custom_function_call_vmap_helper( + interpreter, func, op, *args, **kwargs + ) + + lib.impl(opname, wrapped_func, "FuncTorchBatched", with_keyset=True) + + if func is None: + return register + else: + return register(func) + + +# If the op was defined in C++, then we want to make sure there was an +# m.set_python_module(module, ...) call and that the module is the +# same as the module that called torch.library.register_fake. +def _check_pystubs_once(func, qualname, actual_module_name): + checked = False + + def inner(*args, **kwargs): + nonlocal checked + if checked: + return func(*args, **kwargs) + + op = torch._library.utils.lookup_op(qualname) + if op._defined_in_python: + checked = True + return func(*args, **kwargs) + + maybe_pystub = torch._C._dispatch_pystub( + op._schema.name, op._schema.overload_name + ) + if maybe_pystub is None: + if torch._library.utils.requires_set_python_module(): + namespace = op.namespace + cpp_filename = op._handle.debug() + raise RuntimeError( + f"Operator '{qualname}' was defined in C++ and has a Python " + f"fake impl. In this situation, we require there to also be a " + f'companion C++ `m.set_python_module("{actual_module_name}")` ' + f"call, but we could not find one. Please add that to " + f"to the top of the C++ TORCH_LIBRARY({namespace}, ...) block the " + f"operator was registered in ({cpp_filename})" + ) + else: + pystub_module = maybe_pystub[0] + if actual_module_name != pystub_module: + cpp_filename = op._handle.debug() + raise RuntimeError( + f"Operator '{qualname}' specified that its python fake impl " + f"is in the Python module '{pystub_module}' but it was actually found " + f"in '{actual_module_name}'. Please either move the fake impl " + f"or correct the m.set_python_module call ({cpp_filename})" + ) + checked = True + return func(*args, **kwargs) + + return inner + + +# NOTE [ctx inside the fake implementation] +# If a user has an operator with data-dependent output shape, then when writing +# a fake implementation they must query the current ctx and use methods on the +# ctx to construct a new unbacked symint. +# +# This is done via us setting the global_ctx_getter function every time a fake +# implementation is invoked. +def get_ctx() -> "torch._library.fake_impl.FakeImplCtx": + """get_ctx() returns the current AbstractImplCtx object. + + Calling ``get_ctx()`` is only valid inside of an fake impl + (see :func:`torch.library.register_fake` for more usage details. + """ + return torch._library.fake_impl.global_ctx_getter() + + +def get_kernel( + op: _op_identifier, dispatch_key: str | torch.DispatchKey +) -> torch._C._SafeKernelFunction: + """Returns the computed kernel for a given operator and dispatch key. + + This function retrieves the kernel that would be executed for a given + operator and dispatch key combination. The returned SafeKernelFunction + can be used to call the kernel in a boxed fashion. The intended use + case for this function is to retrieve the original kernel for a given + dispatch key and then register another kernel to the same dispatch key + that calls into the original kernel for certain cases. + + Args: + op: Operator name (along with the overload) or OpOverload object + Can be a string (e.g., "aten::add.Tensor"), an OpOverload, or a CustomOpDef. + dispatch_key (str | torch.DispatchKey): The dispatch key to get the kernel for. + Can be a string (e.g., "CPU", "CUDA") or a DispatchKey enum value. + + Returns: + torch._C._SafeKernelFunction: A safe kernel function that can be used to + call the kernel. + + Raises: + RuntimeError: If the operator does not exist. + + Example: + >>> # Get the CPU kernel for torch.add + >>> kernel = torch.library.get_kernel("aten::add.Tensor", "CPU") + >>> + >>> # You can also use DispatchKey enum + >>> kernel = torch.library.get_kernel("aten::add.Tensor", torch.DispatchKey.CPU) + >>> + >>> # Or use an OpOverload directly + >>> kernel = torch.library.get_kernel(torch.ops.aten.add.Tensor, "CPU") + >>> + >>> # Example: Using get_kernel in a custom op with conditional dispatch + >>> # Get the original kernel for torch.sin + >>> original_sin_kernel = torch.library.get_kernel("aten::sin", "CPU") + >>> + >>> # If input has negative values, use original sin, otherwise return zeros + >>> def conditional_sin_impl(dispatch_keys, x): + >>> if (x < 0).any(): + >>> return original_sin_kernel.call_boxed(dispatch_keys, x) + >>> else: + >>> return torch.zeros_like(x) + >>> + >>> lib = torch.library.Library("aten", "IMPL") + >>> # with_keyset=True so the first argument to the impl is the current DispatchKeySet + >>> which needs to be the first argument to ``kernel.call_boxed`` + >>> lib.impl("sin", conditional_sin_impl, "CPU", with_keyset=True) + >>> + >>> # Test the conditional behavior + >>> x_positive = torch.tensor([1.0, 2.0]) + >>> x_mixed = torch.tensor([-1.0, 2.0]) + >>> torch.sin(x_positive) + tensor([0., 0.]) + >>> torch.sin(x_mixed) + tensor([-0.8415, 0.9093]) + """ + if not isinstance(op, (str, torch._ops.OpOverload)): + raise ValueError(f"get_kernel({op}): got unexpected type for op: {type(op)}") + + if isinstance(op, torch._ops.OpOverload): + op = op._name + + if isinstance(dispatch_key, str): + try: + dispatch_key = torch._C.DispatchKey.__members__[dispatch_key] + except KeyError: + raise ValueError(f"Invalid dispatch key: {dispatch_key}") from None + + return torch._C._dispatch_get_computed_kernel_for_dispatch_key(op, dispatch_key) + + +_OPCHECK_DEFAULT_UTILS = ( + "test_schema", + "test_autograd_registration", + "test_faketensor", + "test_aot_dispatch_dynamic", +) + + +def opcheck( + op: torch._ops.OpOverload | torch._ops.OpOverloadPacket | CustomOpDef, + args: tuple[Any, ...], + kwargs: dict[str, Any] | None = None, + *, + test_utils: str | Sequence[str] = _OPCHECK_DEFAULT_UTILS, + raise_exception: bool = True, + atol=None, + rtol=None, +) -> dict[str, str]: + """Given an operator and some sample arguments, tests if the operator is + registered correctly. + + That is, when you use the torch.library/TORCH_LIBRARY APIs to create a + custom op, you specified metadata (e.g. mutability info) about the custom op + and these APIs require that the functions you pass them satisfy certain + properties (e.g. no data pointer access in the fake/meta/abstract kernel) + ``opcheck`` tests these metadata and properties. + + Concretely, we test the following: + + - test_schema: If the schema matches the implementation of + the operator. For example: if the schema specifies a Tensor is mutated, + then we check the implementation mutates the Tensor. If the schema + specifies that we return a new Tensor, then we check that the + implementation returns a new Tensor (instead of an existing one or + a view of an existing one). + - test_autograd_registration: If the operator supports training + (autograd): we check that its autograd formula is registered via + torch.library.register_autograd or a manual registration to one + or more DispatchKey::Autograd keys. Any other DispatchKey-based + registrations may lead to undefined behavior. + - test_faketensor: If the operator has a FakeTensor kernel + (and if it is correct). The FakeTensor kernel is necessary ( + but not sufficient) for the operator to work with PyTorch compilation + APIs (torch.compile/export/FX). We check that a FakeTensor kernel + (also sometimes known as a meta kernel) was registered for the + operator and that it is correct. This test takes the result of + running the operator on real tensors and the result of running + the operator on FakeTensors and checks that they have the same + Tensor metadata (sizes/strides/dtype/device/etc). + - test_aot_dispatch_dynamic: If the operator has correct behavior + with PyTorch compilation APIs (torch.compile/export/FX). + This checks that the outputs (and gradients, if applicable) are the + same under eager-mode PyTorch and torch.compile. + This test is a superset of ``test_faketensor`` and is an e2e test; + other things it tests are that the operator supports + functionalization and that the backward pass (if it exists) also + supports FakeTensor and functionalization. + + For best results, please call ``opcheck`` multiple times with a + representative set of inputs. If your operator supports + autograd, please use ``opcheck`` with inputs with ``requires_grad = True``; + if your operator supports multiple devices (e.g. CPU and CUDA), please + use ``opcheck`` with inputs on all supported devices. + + Args: + op: The operator. Must either be a function decorated with + :func:`torch.library.custom_op` or an OpOverload/OpOverloadPacket + found in torch.ops.* (e.g. torch.ops.aten.sin, torch.ops.mylib.foo) + args: The args to the operator + kwargs: The kwargs to the operator + test_utils: Tests that we should run. Default: all of them. + Example: ("test_schema", "test_faketensor") + raise_exception: If we should raise an exception on the first + error. If False, we will return a dict with information + on if each test passed or not. + rtol (Optional[float]): Relative tolerance for floating point comparisons. + If specified ``atol`` must also be specified. + If omitted, default values based on the ``dtype`` are selected + (see the table in :func:`torch.testing.assert_close`). + atol (Optional[float]): Absolute tolerance for floating point comparisons. + If specified ``rtol`` must also be specified. + If omitted, default values based on the ``dtype`` are selected + (see the table in :func:`torch.testing.assert_close`). + + .. warning:: + + opcheck and :func:`torch.autograd.gradcheck` test different things; + opcheck tests if your usage of torch.library APIs is correct while + :func:`torch.autograd.gradcheck` tests if your autograd formula is + mathematically correct. Use both to test custom ops that support + gradient computation. + + Example: + + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA) + >>> @torch.library.custom_op("mylib::numpy_mul", mutates_args=()) + >>> def numpy_mul(x: Tensor, y: float) -> Tensor: + >>> x_np = x.numpy(force=True) + >>> z_np = x_np * y + >>> return torch.from_numpy(z_np).to(x.device) + >>> + >>> @numpy_mul.register_fake + >>> def _(x, y): + >>> return torch.empty_like(x) + >>> + >>> def setup_context(ctx, inputs, output): + >>> y, = inputs + >>> ctx.y = y + >>> + >>> def backward(ctx, grad): + >>> return grad * ctx.y, None + >>> + >>> numpy_mul.register_autograd(backward, setup_context=setup_context) + >>> + >>> sample_inputs = [ + >>> (torch.randn(3), 3.14), + >>> (torch.randn(2, 3, device='cuda'), 2.718), + >>> (torch.randn(1, 10, requires_grad=True), 1.234), + >>> (torch.randn(64, 64, device='cuda', requires_grad=True), 90.18), + >>> ] + >>> + >>> for args in sample_inputs: + >>> torch.library.opcheck(numpy_mul, args) + + """ + import torch.testing._internal.optests as optests + + return optests.opcheck( + op, + args, + kwargs, + test_utils=test_utils, + raise_exception=raise_exception, + rtol=rtol, + atol=atol, + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/overrides.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/overrides.py new file mode 100644 index 0000000000000000000000000000000000000000..b1193bab3d6dc4b74ab80329d62a0f234dfa1ea1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/overrides.py @@ -0,0 +1,2134 @@ +""" +Python implementation of ``__torch_function__`` + +While most of the torch API and handling for ``__torch_function__`` happens +at the C++ level, some of the torch API is written in Python so we need +python-level handling for ``__torch_function__`` overrides as well. The main +developer-facing functionality in this file are handle_torch_function and +has_torch_function. See torch/functional.py and test/test_overrides.py +for usage examples. + +Note +---- +heavily inspired by NumPy's ``__array_function__`` (see: +https://github.com/pytorch/pytorch/issues/24015 and +https://www.numpy.org/neps/nep-0018-array-function-protocol.html +) + +If changing this file in a way that can affect ``__torch_function__`` overhead, +please report the benchmarks in ``benchmarks/overrides_benchmark``. See the +instructions in the ``README.md`` in that directory. +""" + +import __future__ # noqa: F404 + +import collections +import contextlib +import functools +import sys +import types +import warnings +from collections.abc import Callable, Iterable +from functools import wraps +from typing import Any, TypeVar +from typing_extensions import ParamSpec + +import torch +from torch._C import ( + _add_docstr, + _get_function_stack_at, + _has_torch_function, + _has_torch_function_unary, + _has_torch_function_variadic, + _is_torch_function_mode_enabled, + _len_torch_function_stack, + _pop_torch_function_stack, + _push_on_torch_function_stack, +) + + +__all__ = [ + "get_ignored_functions", + "get_overridable_functions", + "get_testing_overrides", + "handle_torch_function", + "has_torch_function", + "resolve_name", + "is_tensor_like", + "is_tensor_method_or_property", + "wrap_torch_function", + "enable_reentrant_dispatch", +] + +_P = ParamSpec("_P") +_R = TypeVar("_R") + + +def _disable_user_warnings( + func: Callable[_P, _R], + regex: str = ".*is deprecated, please use.*", + module: str = "torch", +) -> Callable[_P, _R]: + """ + Decorator that temporarily disables ``UserWarning``s for the given ``module`` if the warning message matches the + given ``regex`` pattern. + + Arguments + --------- + func : function + Function to disable the warnings for. + regex : str + A regex pattern compilable by ``re.compile``. This is used to match the ``UserWarning`` message. + module : str + The python module to which the filtering should be restricted. + + Returns + ------- + function + The wrapped function. + """ + + @wraps(func) + def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> _R: + with warnings.catch_warnings(): + warnings.filterwarnings( + "ignore", category=UserWarning, message=regex, module=module + ) + return func(*args, **kwargs) + + return wrapper + + +@functools.cache +@_disable_user_warnings +def get_ignored_functions() -> set[Callable]: + """ + Return public functions that cannot be overridden by ``__torch_function__``. + + Returns + ------- + set[Callable] + A tuple of functions that are publicly available in the torch API but cannot + be overridden with ``__torch_function__``. Mostly this is because none of the + arguments of these functions are tensors or tensor-likes. + + Examples + -------- + >>> torch.Tensor.as_subclass in torch.overrides.get_ignored_functions() + True + >>> torch.add in torch.overrides.get_ignored_functions() + False + """ + Tensor = torch.Tensor + functions = { + torch.typename, + torch.is_tensor, + torch.is_storage, + torch.set_default_tensor_type, + torch.set_default_device, + torch.get_default_device, + torch.set_rng_state, + torch.get_rng_state, + torch.manual_seed, + torch.initial_seed, + torch.seed, + torch.save, + torch.load, + torch.set_printoptions, + torch.fork, + torch.get_default_dtype, + torch.get_num_interop_threads, + torch.get_num_threads, + torch.init_num_threads, + torch.import_ir_module, + torch.import_ir_module_from_buffer, + torch.is_anomaly_enabled, + torch.is_anomaly_check_nan_enabled, + torch.is_grad_enabled, + torch.merge_type_from_type_comment, + torch.parse_ir, + torch.parse_schema, + torch.parse_type_comment, + torch.set_anomaly_enabled, + torch.set_flush_denormal, + torch.set_num_interop_threads, + torch.set_num_threads, + torch.wait, + torch.as_tensor, + torch.from_numpy, + torch.tensor, + torch.default_generator, + torch.has_cuda, + torch.has_cudnn, + torch.has_lapack, + torch.device, + torch.dtype, + torch.finfo, + torch.has_mkl, + torch.has_mps, + torch.has_mkldnn, + torch.has_openmp, + torch.iinfo, + torch.memory_format, + torch.qscheme, + torch.set_grad_enabled, + torch.no_grad, + torch.enable_grad, + torch.inference_mode, + torch.is_inference_mode_enabled, + torch.layout, + torch.align_tensors, + torch.arange, + torch.as_strided, + torch.bartlett_window, + torch.blackman_window, + torch.broadcast_shapes, + torch.can_cast, + torch.compile, + torch.cudnn_affine_grid_generator, + torch.cudnn_batch_norm, + torch.cudnn_convolution, + torch.cudnn_convolution_transpose, + torch.cudnn_convolution_relu, + torch.cudnn_convolution_add_relu, + torch.cudnn_grid_sampler, + torch.cudnn_is_acceptable, + torch.empty, + torch.empty_permuted, + torch.empty_strided, + torch.empty_quantized, + torch.export.export, + torch.export.load, + torch.export.register_dataclass, + torch.export.save, + torch.eye, + torch.fft.fftfreq, + torch.fft.rfftfreq, + torch.from_file, + torch.full, + torch.fill, + torch.hamming_window, + torch.hann_window, + torch.kaiser_window, + torch.linspace, + torch.logspace, + torch.mkldnn_adaptive_avg_pool2d, + torch.mkldnn_convolution, + torch.mkldnn_max_pool2d, + torch.mkldnn_max_pool3d, + torch.mkldnn_linear_backward_weights, + torch.mkldnn_rnn_layer, + torch.normal, + torch.ones, + torch.promote_types, + torch.rand, + torch.rand_like, + torch.randn, + torch.randn_like, + torch.randint, + torch.randint_like, + torch.randperm, + torch.range, + torch.result_type, + torch.scalar_tensor, + torch.sparse_coo_tensor, + torch.sparse_compressed_tensor, + torch.sparse_csr_tensor, + torch.sparse_csc_tensor, + torch.sparse_bsr_tensor, + torch.sparse_bsc_tensor, + torch.sym_constrain_range, + torch.sym_constrain_range_for_size, + torch.sym_fresh_size, + torch.tril_indices, + torch.triu_indices, + torch.vander, + torch.zeros, + torch._jit_internal.boolean_dispatch, + torch.nn.functional.assert_int_or_pair, + torch.nn.functional.upsample, + torch.nn.functional.upsample_bilinear, + torch.nn.functional.upsample_nearest, + torch.nn.functional.has_torch_function, + torch.nn.functional.has_torch_function_unary, + torch.nn.functional.has_torch_function_variadic, + torch.nn.functional.handle_torch_function, + torch.nn.functional.grouped_mm, + torch.nn.functional.scaled_grouped_mm, + torch.nn.functional.scaled_mm, + torch.nn.functional.sigmoid, + torch.nn.functional.hardsigmoid, + torch.nn.functional.tanh, + torch.nn.functional._canonical_mask, + torch.nn.functional._none_or_dtype, + # Doesn't actually take or return tensor arguments + torch.nn.init.calculate_gain, + # These are deprecated; don't test them + torch.nn.init.uniform, + torch.nn.init.normal, + torch.nn.init.constant, + torch.nn.init.eye, + torch.nn.init.dirac, + torch.nn.init.xavier_uniform, + torch.nn.init.xavier_normal, + torch.nn.init.kaiming_uniform, + torch.nn.init.kaiming_normal, + torch.nn.init.orthogonal, + torch.nn.init.sparse, + torch.nested.to_padded_tensor, + has_torch_function, + handle_torch_function, + torch.set_autocast_enabled, + torch.is_autocast_enabled, + torch.set_autocast_dtype, + torch.get_autocast_dtype, + torch.clear_autocast_cache, + torch.set_autocast_cpu_enabled, + torch.is_autocast_cpu_enabled, + torch.set_autocast_xla_enabled, + torch.is_autocast_xla_enabled, + torch.set_autocast_ipu_enabled, + torch.is_autocast_ipu_enabled, + torch.set_autocast_cpu_dtype, + torch.get_autocast_cpu_dtype, + torch.set_autocast_ipu_dtype, + torch.get_autocast_ipu_dtype, + torch.get_autocast_gpu_dtype, + torch.set_autocast_gpu_dtype, + torch.get_autocast_xla_dtype, + torch.set_autocast_xla_dtype, + torch.autocast_increment_nesting, + torch.autocast_decrement_nesting, + torch.is_autocast_cache_enabled, + torch.set_autocast_cache_enabled, + torch.nn.functional.hardswish, + torch.is_vulkan_available, + torch.are_deterministic_algorithms_enabled, + torch.use_deterministic_algorithms, + torch.is_deterministic_algorithms_warn_only_enabled, + torch.set_deterministic_debug_mode, + torch.get_device_module, + torch.get_deterministic_debug_mode, + torch.set_float32_matmul_precision, + torch.get_float32_matmul_precision, + torch.unify_type_list, + torch.is_warn_always_enabled, + torch.set_warn_always, + torch.vitals_enabled, + torch.set_vital, + torch.read_vitals, + torch.vmap, + torch.cond, + torch.frombuffer, + torch.asarray, + torch._functional_sym_constrain_range, + torch._make_dep_token, + Tensor.__delitem__, + Tensor.__dir__, + Tensor.__getattribute__, + Tensor.__init__, + Tensor.__iter__, + Tensor.__init_subclass__, + Tensor.__delattr__, + Tensor.__setattr__, + Tensor.__torch_function__, + Tensor.__torch_dispatch__, + Tensor.__new__, + Tensor.__class__, + Tensor.__subclasshook__, + Tensor.__hash__, + Tensor.as_subclass, + Tensor.eig, + Tensor.lstsq, + Tensor.reinforce, + Tensor.new, + Tensor.new_tensor, + Tensor.new_empty, + Tensor.new_empty_strided, + Tensor.new_zeros, + Tensor.new_ones, + Tensor.new_full, + Tensor._make_subclass, + Tensor.solve, + Tensor.symeig, + Tensor.stride, + Tensor.unflatten, + Tensor.to_sparse_coo, + Tensor.to_sparse_csr, + Tensor.to_sparse_csc, + Tensor.to_sparse_bsr, + Tensor.to_sparse_bsc, + Tensor._to_sparse, + Tensor._to_sparse_csr, + Tensor._to_sparse_csc, + Tensor._to_sparse_bsr, + Tensor._to_sparse_bsc, + Tensor._typed_storage, + Tensor._reduce_ex_internal, + Tensor._fix_weakref, + Tensor._view_func, + Tensor._view_func_unsafe, + Tensor._rev_view_func_unsafe, + Tensor._dtensor__new__, + Tensor._make_wrapper_subclass, + Tensor._python_dispatch.__get__, + Tensor._has_symbolic_sizes_strides.__get__, + Tensor._conj, + Tensor._conj_physical, + Tensor._lazy_clone, + Tensor._neg_view, + Tensor._is_zerotensor, + Tensor._is_all_true, + Tensor._is_any_true, + Tensor._addmm_activation, + Tensor.to_padded_tensor, + Tensor._use_count, + } + + if sys.version_info >= (3, 14): + functions.add(Tensor.__annotate__) + + return functions + + +@functools.cache +def get_default_nowrap_functions() -> set[Callable]: + """ + Return public functions that do not wrap in a subclass when invoked by + the default ``Tensor.__torch_function__`` that preserves subclasses. Typically, + these functions represent field accesses (i.e., retrieving a Tensor that + is stored somewhere on the Tensor) as opposed to computation. Users of + these functions expect object identity to be preserved over multiple accesses + (e.g., ``a.grad is a.grad``) which cannot be upheld if we're wrapping on + the fly every time (furthermore, the tensor stored here might already be + the subclass, in which case wrapping really ought not to happen). + + Not ALL property accessors have this property; for example ``Tensor.T`` actually + just creates a new transposed tensor on the fly, and so we SHOULD interpose on + these calls (you need to check the implementation of the function to see if + this is the case or not). Additionally, if a property accessor doesn't return a Tensor, + it doesn't have to be on this list (though it is harmless if it is). + """ + Tensor = torch.Tensor + return { + Tensor._base.__get__, + Tensor.grad.__get__, + Tensor._grad.__get__, + } + + +@functools.cache +@_disable_user_warnings +def get_testing_overrides() -> dict[Callable, Callable]: + """Return a dict containing dummy overrides for all overridable functions + + Returns + ------- + Dict[Callable, Callable] + A dictionary that maps overridable functions in the PyTorch API to + lambda functions that have the same signature as the real function + and unconditionally return -1. These lambda functions are useful + for testing API coverage for a type that defines ``__torch_function__``. + + Examples + -------- + >>> import inspect + >>> my_add = torch.overrides.get_testing_overrides()[torch.add] + >>> inspect.signature(my_add) + + """ + # Every function in the PyTorchAPI that can be overridden needs an entry + # in this dict. + # + # Optimally we would use inspect to get the function signature and define + # the lambda function procedurally but that is blocked by generating + # function signatures for native kernels that can be consumed by inspect. + # See Issue #28233. + Tensor = torch.Tensor + ret: dict[Callable, Callable] = { + torch.abs: lambda input, out=None: -1, + torch.absolute: lambda input, out=None: -1, + torch.adaptive_avg_pool1d: lambda input, output_size: -1, + torch.adaptive_max_pool1d: lambda inputs, output_size: -1, + torch.acos: lambda input, out=None: -1, + torch.adjoint: lambda input: -1, + torch.arccos: lambda input, out=None: -1, + torch.acosh: lambda input, out=None: -1, + torch.arccosh: lambda input, out=None: -1, + torch.add: lambda input, other, out=None: -1, + torch.addbmm: lambda input, batch1, batch2, alpha=1, beta=1, out=None: -1, + torch.addcdiv: lambda input, tensor1, tensor2, value=1, out=None: -1, + torch.addcmul: lambda input, tensor1, tensor2, value=1, out=None: -1, + torch.addmm: lambda input, mat1, mat2, beta=1, alpha=1, out=None: -1, + torch.addmv: lambda input, mat, vec, beta=1, alpha=1, out=None: -1, + torch.addr: lambda input, vec1, vec2, beta=1, alpha=1, out=None: -1, + torch.affine_grid_generator: lambda theta, size, align_corners: -1, + torch.all: lambda input, dim=None: -1, + torch.allclose: lambda input, other, trol=1e-05, atol=1e-08, equal_nan=False: -1, + torch.alpha_dropout: lambda input, p, train, inplace=False: -1, + torch.amax: lambda input, dim=None: -1, + torch.amin: lambda input, dim=None: -1, + torch.aminmax: lambda input, dim=None, keepdim=False, out=None: -1, + torch.angle: lambda input, out=None: -1, + torch.any: lambda input, dim=None, keepdim=False, out=None: -1, + torch.argmax: lambda input: -1, + torch.argmin: lambda input: -1, + torch.argsort: lambda input, dim=None: -1, + torch.asin: lambda input, out=None: -1, + torch._assert_async: lambda input, msg: -1, + torch.arcsin: lambda input, out=None: -1, + torch.asinh: lambda input, out=None: -1, + torch.arcsinh: lambda input, out=None: -1, + torch.atan: lambda input, out=None: -1, + torch.arctan: lambda input, out=None: -1, + torch.atan2: lambda input, other, out=None: -1, + torch.arctan2: lambda input, other, out=None: -1, + torch.atanh: lambda input, out=None: -1, + torch.arctanh: lambda input, out=None: -1, + torch.atleast_1d: lambda *tensors: -1, + torch.atleast_2d: lambda *tensors: -1, + torch.atleast_3d: lambda *tensors: -1, + torch.avg_pool1d: lambda input, kernel_size, stride=None, padding=0, ceil_mode=False, count_include_pad=True: -1, + torch.baddbmm: lambda input, batch1, batch2, alpha=1, beta=1, out=None: -1, + torch.batch_norm: lambda input, weight, bias, running_mean, running_var, training, momentum, eps, cudnn_enabled: -1, + torch.batch_norm_backward_elemt: lambda grad_out, input, mean, invstd, weight, sum_dy, sum_dy_xmu, count_tensor: -1, + torch.batch_norm_backward_reduce: lambda grad_out, input, mean, invstd, weight, input_g, weight_g, bias_g: -1, + torch.batch_norm_elemt: lambda input, weight, bias, mean, invstd, eps: -1, + torch.batch_norm_gather_stats: lambda input, mean, invstd, running_mean, running_var, momentum, eps, count: -1, + torch.batch_norm_gather_stats_with_counts: lambda input, mean, invstd, running_mean, running_var, momentum, eps, count: -1, + torch.batch_norm_stats: lambda input, eps: -1, + torch.batch_norm_update_stats: lambda input, running_mean, running_var, momentum: -1, + torch.bernoulli: lambda input, generator=None, out=None: -1, + torch.bilinear: lambda input1, input2, weight, bias: -1, + torch.binary_cross_entropy_with_logits: ( + lambda input, target, weight=None, size_average=None, reduce=None, reduction="mean", pos_weight=None: -1 + ), + torch.bincount: lambda input, weights=None, minlength=0: -1, + torch.binomial: lambda count, prob, generator=None: -1, + torch.bitwise_and: lambda input, other, out=None: -1, + torch.bitwise_not: lambda input, out=None: -1, + torch.bitwise_or: lambda input, other, out=None: -1, + torch.bitwise_xor: lambda input, other, out=None: -1, + torch.bitwise_left_shift: lambda input, other, out=None: -1, + torch.bitwise_right_shift: lambda input, other, out=None: -1, + torch.block_diag: lambda *tensors: -1, + torch.bmm: lambda input, mat2, out_dtype=None, out=None: -1, + torch.broadcast_tensors: lambda *tensors: -1, + torch.broadcast_to: lambda self, size: -1, + torch.bucketize: lambda input, boundaries, out_int32=False, right=False, out=None: -1, + torch.cartesian_prod: lambda *tensors: -1, + torch.cat: lambda tensors, dim=0, out=None: -1, + torch.concat: lambda tensors, dim=0, out=None: -1, # alias for torch.cat + torch.concatenate: lambda tensors, dim=0, out=None: -1, # alias for torch.concatenate + torch.cdist: lambda x1, x2, p=2.0, compute_mode="use_mm_for_euclid_dist_if_necessary": -1, + torch.ceil: lambda input, out=None: -1, + torch.celu: lambda input, alpha=1.0, inplace=False: -1, + torch.chain_matmul: lambda *matrices, out=None: -1, + torch.channel_shuffle: lambda input, groups: -1, + torch.cholesky: lambda input, upper=False, out=None: -1, + torch.linalg.cholesky: lambda input, out=None: -1, + torch.linalg.cholesky_ex: lambda input, check_errors=False, out=None: -1, + torch.cholesky_inverse: lambda input, upper=False, out=None: -1, + torch.cholesky_solve: lambda input1, input2, upper=False, out=None: -1, + torch.choose_qparams_optimized: lambda input, numel, n_bins, ratio, bit_width: -1, + torch.chunk: lambda input, chunks, dim=0: -1, + torch.clamp: lambda input, min=None, max=None, out=None: -1, + torch.clip: lambda input, min=None, max=None, out=None: -1, + torch.clamp_min: lambda input, min, out=None: -1, + torch.clamp_max: lambda input, max, out=None: -1, + torch.column_stack: lambda tensors, out=None: -1, + torch.cov: lambda input, correction=1, fweights=None, aweights=None: -1, + torch.clone: lambda input: -1, + torch.combinations: lambda input, r=2, with_replacement=False: -1, + torch.complex: lambda real, imag: -1, + torch.copysign: lambda input, other, out=None: -1, + torch.polar: lambda abs, ang: -1, + torch.linalg.cond: lambda input, ord=None: -1, + torch.conj: lambda input, out=None: -1, + torch.conj_physical: lambda input, out=None: -1, + torch.resolve_conj: lambda input, out=None: -1, + torch.resolve_neg: lambda input, out=None: -1, + torch.constant_pad_nd: lambda input, pad, value=0: -1, + torch.conv1d: lambda input, weight, bias=None, stride=1, padding=0, dilation=1, groups=1: -1, + torch.conv2d: lambda input, weight, bias=None, stride=1, padding=0, dilation=1, groups=1: -1, + torch.conv3d: lambda input, weight, bias=None, stride=1, padding=0, dilation=1, groups=1: -1, + torch.convolution: lambda input, weight, bias, stride, padding, dilation, transposed, output_adding, groups: -1, + torch.conv_tbc: lambda input, weight, bias, pad=0: -1, + torch.conv_transpose1d: lambda input, weight, bias=None, stride=1, padding=0, output_padding=0, groups=1, dilation=1: -1, + torch.conv_transpose2d: lambda input, weight, bias=None, stride=1, padding=0, output_padding=0, groups=1, dilation=1: -1, + torch.conv_transpose3d: lambda input, weight, bias=None, stride=1, padding=0, output_padding=0, groups=1, dilation=1: -1, + torch.corrcoef: lambda input: -1, + torch.cos: lambda input, out=None: -1, + torch.cosine_embedding_loss: lambda input1, input2, target, margin=0, size_average=None, reduce=None, reduction="mean": -1, + torch.cosh: lambda input, out=None: -1, + torch.cosine_similarity: lambda x1, x2, dim=1, eps=1e-8: -1, + torch.count_nonzero: lambda input: -1, + torch.cross: lambda input, other, dim=None, out=None: -1, + torch.linalg.cross: lambda input, other, dim=-1, out=None: -1, + torch.ctc_loss: ( + lambda log_probs, targets, input_lengths, target_lengths, blank=0, reduction="mean", zero_infinity=False: -1 + ), + torch.cummax: lambda input, dim, out=None: -1, + torch.cummin: lambda input, dim, out=None: -1, + torch.cumprod: lambda input, dim, out=None, dtype=None: -1, + torch.cumsum: lambda input, dim, out=None, dtype=None: -1, + torch.cumulative_trapezoid: lambda y, x=None, dim=-1: -1, + torch.logcumsumexp: lambda input, dim, out=None: -1, + torch.deg2rad: lambda input, out=None: -1, + torch.dequantize: lambda input: -1, + torch.det: lambda input: -1, + torch.linalg.det: lambda input: -1, # alias for torch.det # type: ignore[attr-defined] + torch.detach: lambda input: -1, + torch.diag: lambda input, diagonal=0, out=None: -1, + torch.diag_embed: lambda input, diagonal=0, out=None: -1, + torch.diagflat: lambda input, offset=0: -1, + torch.diff: lambda input, n=1, dim=-1, prepend=None, append=None, out=None: -1, + torch.diagonal: lambda input, offset=0, dim1=0, dim2=1: -1, + torch.linalg.diagonal: lambda input, offset=0, dim1=-2, dim2=-1: -1, + torch.diagonal_scatter: lambda input, src, offset=0, dim1=0, dim2=1: -1, + torch.as_strided_scatter: lambda self, src, size, stride, storage_offset=None: -1, + torch.digamma: lambda input, out=None: -1, + torch.dist: lambda input, other, p=2: -1, + torch.div: lambda input, other, rounding_mode=None, out=None: -1, + torch.divide: lambda input, other, rounding_mode=None, out=None: -1, + torch.dot: lambda input, other, out=None: -1, + torch.dropout: lambda input, p, train, inplace=False: -1, + torch.dsmm: lambda input, mat2, out_dtype=None: -1, + torch.hsmm: lambda mat1, mat2: -1, + torch.dsplit: lambda input, indices_or_sections: -1, + torch.dstack: lambda tensors, out=None: -1, + torch.linalg.eig: lambda input, out=None: -1, + torch.linalg.eigvals: lambda input, out=None: -1, + torch.linalg.eigh: lambda input, UPLO="L", out=None: -1, + torch.linalg.eigvalsh: lambda input, UPLO="L", out=None: -1, + torch.einsum: lambda equation, *operands: -1, + torch.embedding: ( + lambda input, weight, padding_idx=None, max_norm=None, norm_type=2.0, scale_grad_by_freq=False, sparse=False: -1 # noqa: B950 + ), + torch.embedding_bag: ( + lambda input, weight, offsets, max_norm=None, norm_type=2, scale_grad_by_freq=False, mode="mean", sparse=False, per_sample_weights=None, padding_idx=None: -1 # noqa: B950 + ), + torch.empty_like: lambda input, dtype=None, layout=None, device=None, requires_grad=False: -1, + torch.eq: lambda input, other, out=None: -1, + torch.equal: lambda input, other: -1, + torch.erf: lambda input, out=None: -1, + torch.erfc: lambda input, out=None: -1, + torch.erfinv: lambda input, out=None: -1, + torch.exp: lambda input, out=None: -1, + torch.exp2: lambda input, out=None: -1, + torch.expm1: lambda input, out=None: -1, + torch.fake_quantize_per_channel_affine: lambda input, scale, zero_point, axis, quant_min, quant_max: -1, + torch.fake_quantize_per_tensor_affine: lambda input, scale, zero_point, quant_min, quant_max: -1, + torch.fused_moving_avg_obs_fake_quant: ( + lambda x, observer_on, fake_quant_on, averaging_const, running_min, running_max, scale, zero_point, quant_min, quant_max, ch_axis, per_row_fake_quant=False, symmetric_quant=False: -1 # noqa: B950 + ), + torch.fbgemm_linear_fp16_weight: lambda input, packed_weight, bias, output: -1, + torch.fbgemm_linear_fp16_weight_fp32_activation: lambda input, packed_weight, bias, output: -1, + torch.fbgemm_linear_int8_weight: lambda input, weight, packed, col_offsets, weight_scale, weight_zero_point, bias: -1, # noqa: B950 + torch.fbgemm_linear_int8_weight_fp32_activation: ( + lambda input, weight, packed, col_offsets, weight_scale, weight_zero_point, bias: -1 + ), + torch.fbgemm_linear_quantize_weight: lambda input: -1, + torch.fbgemm_pack_gemm_matrix_fp16: lambda input: -1, + torch.fbgemm_pack_quantized_matrix: lambda input, a, b: -1, + torch.feature_alpha_dropout: lambda input, p, train: -1, + torch.feature_dropout: lambda input, p, train: -1, + torch.fft.ifft: lambda input, n=None, dim=-1, norm=None: -1, + torch.fft.rfft: lambda input, n=None, dim=-1, norm=None: -1, + torch.fft.irfft: lambda input, n=None, dim=-1, norm=None: -1, + torch.fft.hfft: lambda input, n=None, dim=-1, norm=None: -1, + torch.fft.ihfft: lambda input, n=None, dim=-1, norm=None: -1, + torch.fft.hfft2: lambda input, s=None, dim=(-2, -1), norm=None: -1, + torch.fft.ihfft2: lambda input, s=None, dim=(-2, -1), norm=None: -1, + torch.fft.hfftn: lambda input, s=None, dim=-1, norm=None: -1, + torch.fft.ihfftn: lambda input, s=None, dim=-1, norm=None: -1, + torch.fft.fftn: lambda input, s=None, dim=None, norm=None: -1, + torch.fft.ifftn: lambda input, s=None, dim=None, norm=None: -1, + torch.fft.rfftn: lambda input, s=None, dim=None, norm=None: -1, + torch.fft.irfftn: lambda input, s=None, dim=None, norm=None: -1, + torch.fft.fft2: lambda input, s=None, dim=(-2, -1), norm=None: -1, + torch.fft.ifft2: lambda input, s=None, dim=(-2, -1), norm=None: -1, + torch.fft.rfft2: lambda input, s=None, dim=(-2, -1), norm=None: -1, + torch.fft.irfft2: lambda input, s=None, dim=(-2, -1), norm=None: -1, + torch.fft.fftshift: lambda input, dim=None: -1, + torch.fft.ifftshift: lambda input, dim=None: -1, + torch.fft.fft: lambda input, n=None, dim=-1, norm=None: -1, + torch.fix: lambda input, out=None: -1, + torch.flatten: lambda input, start_dim=0, end_dim=-1: -1, + torch.flip: lambda input, dims: -1, + torch.fliplr: lambda input: -1, + torch.flipud: lambda input: -1, + torch.frobenius_norm: lambda input, dim=None, keepdim=False, out=None: -1, + torch.floor: lambda input, out=None: -1, + torch.floor_divide: lambda input, other: -1, + torch.float_power: lambda input, exponent, out=None: -1, + torch.fmod: lambda input, other, out=None: -1, + torch.frac: lambda input, out=None: -1, + torch.frexp: lambda input, out=None: -1, + torch.full_like: lambda input, fill_value, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False: -1, # noqa: B950 + torch._functional_assert_async: lambda input, msg, dep_token: -1, + torch.lu_unpack: lambda LU_data, LU_pivots, unpack_data=True, unpack_pivots=True: -1, + torch.gather: lambda input, dim, index, out=None, sparse_grad=False: -1, + torch.gcd: lambda input, other, out=None: -1, + torch.ge: lambda input, other, out=None: -1, + torch.get_device: lambda input: -1, + torch.greater_equal: lambda input, other, out=None: -1, + torch.geqrf: lambda input, out=None: -1, + torch.i0: lambda input, out=None: -1, + torch.inner: lambda input, other, out=None: -1, + torch.outer: lambda input, vec2, out=None: -1, + torch.ger: lambda input, vec2, out=None: -1, # alias for torch.outer + torch.gradient: lambda input, spacing=None, dim=None, edge_order=1: -1, + torch.grid_sampler: lambda input, grid, interpolation_mode, padding_mode, align_corners: -1, + torch.grid_sampler_2d: lambda input, grid, interpolation_mode, padding_mode, align_corners: -1, + torch.grid_sampler_3d: lambda input, grid, interpolation_mode, padding_mode, align_corners: -1, + torch.group_norm: lambda input, num_groups, weight=None, bias=None, eps=1e-05, cudnn_enabled=True: -1, + torch.gru: lambda input, hx, params, has_biases, num_layers, dropout, train, bidirectional, batch_first: -1, + torch.gru_cell: lambda input, hx, w_ih, w_hh, b_ih=None, b_hh=None: -1, + torch.gt: lambda input, other, out=None: -1, + torch.greater: lambda input, other, out=None: -1, + torch.hardshrink: lambda input, lambd=0.5: -1, + torch.hash_tensor: lambda input, dim=None, keepdim=False, mode=0, out=None: -1, + torch.heaviside: lambda input, values, out=None: -1, + torch.hinge_embedding_loss: lambda input, target, margin=1.0, size_average=None, reduce=None, reduction="mean": -1, # noqa: B950 + torch.histc: lambda input, bins=100, min=0, max=0, out=None: -1, + torch.histogram: lambda input, bins=100, min=None, max=None, weight=None, density=False, out=None: -1, + torch.histogramdd: lambda input, bins, range=None, weight=None, density=False: -1, + torch.linalg.householder_product: lambda input, tau: -1, + torch.hspmm: lambda mat1, mat2, out=None: -1, + torch.hsplit: lambda input, indices_or_sections: -1, + torch.hstack: lambda tensors, out=None: -1, + torch.hypot: lambda input, other, out=None: -1, + torch.igamma: lambda input, other, out=None: -1, + torch.igammac: lambda input, other, out=None: -1, + torch.imag: lambda input, out=None: -1, + torch.index_add: lambda input, dim, index, source: -1, + torch.index_copy: lambda input, dim, index, source: -1, + torch.index_put: lambda input, indices, values, accumulate=False: -1, + torch.index_select: lambda input, dim, index, out=None: -1, + torch.index_fill: lambda input, dim, index, value: -1, + torch.index_reduce: lambda input, dim, index, source, reduce, include_input=True: -1, + torch.isfinite: lambda tensor: -1, + torch.isin: lambda e, te, assume_unique=False, invert=False: -1, + torch.isinf: lambda tensor: -1, + torch.isreal: lambda tensor: -1, + torch.isposinf: lambda input, out=None: -1, + torch.isneginf: lambda input, out=None: -1, + torch.instance_norm: ( + lambda input, running_mean, running_var, weight, bias, use_input_stats, momentum, eps, cudnn_enabled: -1 + ), + torch.int_repr: lambda input: -1, + torch.inverse: lambda input, out=None: -1, + torch.linalg.inv: lambda input, out=None: -1, + torch.linalg.inv_ex: lambda input, check_errors=False, out=None: -1, + torch.is_complex: lambda input: -1, + torch.is_conj: lambda input: -1, + torch.is_neg: lambda input: -1, + torch.is_distributed: lambda input: -1, + torch.is_inference: lambda input: -1, + torch.is_floating_point: lambda input: -1, + torch.is_nonzero: lambda input: -1, + torch.is_same_size: lambda input, other: -1, + torch.is_signed: lambda input: -1, + torch.isclose: lambda input, other, rtol=1e-05, atol=1e-08, equal_nan=False: -1, + torch.isnan: lambda input: -1, + torch.istft: ( + lambda input, n_fft, hop_length=None, win_length=None, window=None, center=True, normalized=False, onesided=None, length=None, return_complex=False: -1 # noqa: B950 + ), + torch.kl_div: lambda input, target, size_average=None, reduce=None, reduction="mean", log_target=False: -1, + torch.kron: lambda input, other: -1, + torch.kthvalue: lambda input, k, dim=None, keepdim=False, out=None: -1, + torch.linalg.ldl_factor_ex: lambda input, hermitian=False, check_errors=False, out=None: -1, + torch.linalg.ldl_factor: lambda input, hermitian=False, out=None: -1, + torch.linalg.ldl_solve: lambda LD, pivots, B, hermitian=False, out=None: -1, + torch.layer_norm: lambda input, normalized_shape, weight=None, bias=None, esp=1e-05, cudnn_enabled=True: -1, + torch.lcm: lambda input, other, out=None: -1, + torch.ldexp: lambda input, other, out=None: -1, + torch.le: lambda input, other, out=None: -1, + torch.less_equal: lambda input, other, out=None: -1, + torch.lerp: lambda input, end, weight, out=None: -1, + torch.lgamma: lambda input, out=None: -1, + torch.lobpcg: lambda input, k=None, B=None, X=None, n=None, iK=None, niter=None, tol=None, largest=None, method=None, tracker=None, ortho_iparams=None, ortho_fparams=None, ortho_bparams=None: -1, # noqa: B950 + torch.log: lambda input, out=None: -1, + torch.log_softmax: lambda input, dim, dtype=None: -1, + torch.log10: lambda input, out=None: -1, + torch.log1p: lambda input, out=None: -1, + torch.log2: lambda input, out=None: -1, + torch.logaddexp: lambda input, other, out=None: -1, + torch.logaddexp2: lambda input, other, out=None: -1, + torch.logdet: lambda input: -1, + torch.xlogy: lambda x, y, out=None: -1, + torch.logical_and: lambda input, other, out=None: -1, + torch.logical_not: lambda input, out=None: -1, + torch.logical_or: lambda input, other, out=None: -1, + torch.logical_xor: lambda input, other, out=None: -1, + torch.logit: lambda input, eps=None: -1, + torch.logsumexp: lambda input, names, keepdim=False, out=None: -1, + torch.lstm: lambda data, batch_sizes, hx, params, has_biases, num_layers, dropout, train, bidirectional: -1, + torch.lstm_cell: lambda input, hx, w_ih, w_hh, b_ih=None, b_hh=None: -1, + torch.lt: lambda input, other, out=None: -1, + torch.less: lambda input, other, out=None: -1, + torch.lu: lambda A, pivot=True, get_infos=False, out=None: -1, + torch.lu_solve: lambda b, LU_data, LU_pivots, out=None: -1, + torch.margin_ranking_loss: lambda input1, input2, target, margin=0, size_average=None, reduce=None, reduction="mean": -1, # type: ignore[attr-defined] # noqa: B950 + torch.masked_fill: lambda input, mask, value: -1, + torch.masked_scatter: lambda input, mask, source: -1, + torch.masked_select: lambda input, mask, out=None: -1, + torch.matmul: lambda input, other, out=None: -1, + torch.linalg.lu: lambda input, pivot=True, out=None: -1, + torch.linalg.lu_factor: lambda input, pivot=True, out=None: -1, + torch.linalg.lu_factor_ex: lambda input, pivot=True, check_errors=False, out=None: -1, + torch.linalg.lu_solve: lambda LU, pivots, B, left=True, adjoint=False, out=None: -1, + torch.linalg.matmul: lambda input, other, out=None: -1, # alias for torch.matmul + torch.matrix_power: lambda input, n: -1, + torch.linalg.matrix_power: lambda input, n, out=None: -1, + torch.linalg.matrix_rank: lambda input, tol=None, hermitian=False: -1, + torch.linalg.multi_dot: lambda tensors, out=None: -1, + torch.matrix_exp: lambda input: -1, + torch.linalg.matrix_exp: lambda input: -1, + torch.max: lambda input, out=None: -1, + torch.maximum: lambda input, other, out=None: -1, + torch.fmax: lambda input, other, out=None: -1, + torch.max_pool1d: lambda input, kernel_size, stride=None, padding=0, dilation=1, ceil_mode=False: -1, + torch.max_pool2d: lambda input, kernel_size, stride=None, padding=0, dilation=1, ceil_mode=False: -1, + torch.max_pool3d: lambda input, kernel_size, stride=None, padding=0, dilation=1, ceil_mode=False: -1, + torch.max_pool1d_with_indices: ( + lambda input, kernel_size, stride=None, padding=0, dilation=1, return_indices=False, ceil_mode=False: -1 + ), + torch.mean: lambda input, dim=None: -1, + torch.nanmean: lambda input, dim=None, keepdim=False, dtype=None, out=None: -1, + torch.median: lambda input, dim=None: -1, + torch.nanmedian: lambda input, dim=None: -1, + torch.meshgrid: lambda *tensors, **kwargs: -1, + torch.min: lambda input, out=None: -1, + torch.minimum: lambda input, other, out=None: -1, + torch.fmin: lambda input, other, out=None: -1, + torch.miopen_batch_norm: ( + lambda input, weight, bias, running_mean, running_var, training, exponential_average_factor, epsilon: -1 + ), + torch.miopen_convolution: lambda input, weight, bias, padding, stride, dilation, groups, benchmark, deterministic: -1, # noqa: B950 + torch.miopen_convolution_add_relu: lambda input, weight, z, alpha, bias, stride, padding, dilation, groups: -1, + torch.miopen_convolution_relu: lambda input, weight, bias, stride, padding, dilation, groups: -1, + torch.miopen_convolution_transpose: ( + lambda input, weight, bias, padding, output_padding, stride, dilation, groups, benchmark, deterministic: -1 + ), + torch.miopen_depthwise_convolution: ( + lambda input, weight, bias, padding, stride, dilation, groups, benchmark, deterministic: -1 + ), + torch.miopen_rnn: ( + lambda input, weight, weight_stride0, hx, cx, mode, hidden_size, num_layers, batch_first, dropout, train, bidirectional, batch_sizes, dropout_state: -1 # noqa: B950 + ), + torch.mm: lambda input, mat2, out_dtype=None, out=None: -1, + torch.mode: lambda input, dim=-1, keepdim=False, out=None: -1, + torch.movedim: lambda input, source, destination: -1, + torch.moveaxis: lambda input, source, destination: -1, + torch.msort: lambda input, descending=False, out=None: -1, + torch.mul: lambda input, other, out=None: -1, + torch.multiply: lambda input, other, out=None: -1, + torch.multinomial: lambda input, num_samples, replacement=False, out=None: -1, + torch.mv: lambda input, vec, out=None: -1, + torch.mvlgamma: lambda input, p: -1, + torch.narrow: lambda input, dim, start, length: -1, + torch.nan_to_num: lambda input, nan=0.0, posinf=None, neginf=None, out=None: -1, + torch.native_batch_norm: lambda input, weight, bias, running_mean, running_var, training, momentum, eps: -1, + torch._native_batch_norm_legit: lambda input, weight, bias, training, momentum, eps: -1, + torch.native_dropout: lambda input, p, train: -1, + torch.native_layer_norm: lambda input, normalized_shape, weight=None, bias=None, eps=1e-05: -1, + torch._fused_rms_norm: lambda input, normalized_shape, weight=None, eps=1e-05: -1, + torch.native_group_norm: lambda input, weight, bias, N, C, HxW, group, eps: -1, + torch.native_norm: lambda input, p=2, dim=None, keepdim=False, dtype=None: -1, + torch.native_channel_shuffle: lambda input, groups: -1, + torch.ne: lambda input, other, out=None: -1, + torch.not_equal: lambda input, other, out=None: -1, + torch.neg: lambda input, out=None: -1, + torch.negative: lambda input, out=None: -1, + torch.nextafter: lambda input, other, out=None: -1, + torch.nn.functional.adaptive_avg_pool2d: lambda input, output_size: -1, + torch.nn.functional.adaptive_avg_pool3d: lambda input, output_size: -1, + torch.nn.functional.adaptive_max_pool1d: lambda input, output_size, return_indices=False: -1, + torch.nn.functional.adaptive_max_pool1d_with_indices: lambda input, output_size, return_indices=False: -1, + torch.nn.functional.adaptive_max_pool2d: lambda input, output_size, return_indices=False: -1, + torch.nn.functional.adaptive_max_pool2d_with_indices: lambda input, output_size, return_indices=False: -1, + torch.nn.functional.adaptive_max_pool3d: lambda input, output_size, return_indices=False: -1, + torch.nn.functional.adaptive_max_pool3d_with_indices: lambda input, output_size, return_indices=False: -1, + torch.nn.functional.affine_grid: lambda theta, size, align_corners=None: -1, + torch.nn.functional.alpha_dropout: lambda input, p=0.5, training=False, inplace=False: -1, + torch.nn.functional.avg_pool2d: ( + lambda input, kernel_size, stride=None, padding=0, ceil_mode=False, count_include_pad=True, divisor_override=None: -1 # noqa: B950 + ), + torch.nn.functional.avg_pool3d: ( + lambda input, kernel_size, stride=None, padding=0, ceil_mode=False, count_include_pad=True, divisor_override=None: -1 # noqa: B950 + ), + torch.nn.functional.batch_norm: ( + lambda input, running_mean, running_var, weight=None, bias=None, training=False, momentum=0.1, eps=1e-05: -1 + ), + torch.nn.functional.bilinear: lambda input1, input2, weight, bias=None: -1, + torch.nn.functional.binary_cross_entropy: ( + lambda input, target, weight=None, size_average=None, reduce=None, reduction="mean": -1 + ), + torch.nn.functional.binary_cross_entropy_with_logits: ( + lambda input, target, weight=None, size_average=None, reduce=None, reduction="mean", pos_weight=None: -1 + ), + torch.nn.functional.celu: lambda input, alpha=1.0, inplace=False: -1, + torch.nn.functional.cosine_embedding_loss: ( + lambda input1, input2, target, margin=0, size_average=None, reduce=None, reduction="mean": -1 + ), + torch.nn.functional.cross_entropy: ( + lambda input, target, weight=None, size_average=None, ignore_index=-100, reduce=None, reduction="mean", label_smoothing=0.0: -1 # noqa: B950 + ), + torch.nn.functional.ctc_loss: ( + lambda log_probs, targets, input_lengths, target_lengths, blank=0, reduction="mean", zero_infinity=False: -1 + ), + torch.nn.functional.dropout: lambda input, p=0.5, training=True, inplace=False: -1, + torch.nn.functional.dropout1d: lambda input, p=0.5, training=True, inplace=False: -1, + torch.nn.functional.dropout2d: lambda input, p=0.5, training=True, inplace=False: -1, + torch.nn.functional.dropout3d: lambda input, p=0.5, training=True, inplace=False: -1, + torch.nn.functional.elu: lambda input, alpha=1.0, inplace=False: -1, + torch.nn.functional.embedding: ( + lambda input, weight, padding_idx=None, max_norm=None, norm_type=2.0, scale_grad_by_freq=False, sparse=False: -1 # noqa: B950 + ), + torch.nn.functional.embedding_bag: ( + lambda input, weight, offsets=None, max_norm=None, norm_type=2, scale_grad_by_freq=False, mode="mean", sparse=False, per_sample_weights=None, include_last_offset=False, padding_idx=None: -1 # noqa: B950 + ), + torch.nn.functional.feature_alpha_dropout: lambda input, p=0.5, training=False, inplace=False: -1, + torch.nn.functional.fold: lambda input, output_size, kernel_size, dilation=1, padding=0, stride=1: -1, + torch.nn.functional.fractional_max_pool2d: ( + lambda input, kernel_size, output_size=None, output_ratio=None, return_indices=False, _random_samples=None: -1 # noqa: B950 + ), + torch.nn.functional.fractional_max_pool2d_with_indices: ( + lambda input, kernel_size, output_size=None, output_ratio=None, return_indices=False, _random_samples=None: -1 # noqa: B950 + ), + torch.nn.functional.fractional_max_pool3d: ( + lambda input, kernel_size, output_size=None, output_ratio=None, return_indices=False, _random_samples=None: -1 # noqa: B950 + ), + torch.nn.functional.fractional_max_pool3d_with_indices: ( + lambda input, kernel_size, output_size=None, output_ratio=None, return_indices=False, _random_samples=None: -1 # noqa: B950 + ), + torch.nn.functional.gaussian_nll_loss: lambda input, target, var, full=False, eps=1e-06, reduction="mean": -1, + torch.nn.functional.gelu: lambda input, approximate="none": -1, + torch.nn.functional.glu: lambda input, dim=-1: -1, + torch.nn.functional.grid_sample: lambda input, grid, mode="bilinear", padding_mode="zeros", align_corners=None: -1, # noqa: B950 + torch.nn.functional.group_norm: lambda input, num_groups, weight=None, bias=None, eps=1e-05: -1, + torch.nn.functional.gumbel_softmax: lambda logits, tau=1, hard=False, eps=1e-10, dim=-1: -1, + torch.nn.functional.hardshrink: lambda input, lambd=0.5: -1, + torch.nn.functional.hardtanh: lambda input, min_val=-1.0, max_val=1.0, inplace=False: -1, + torch.nn.functional.hinge_embedding_loss: ( + lambda input, target, margin=1.0, size_average=None, reduce=None, reduction="mean": -1 + ), + torch.nn.functional.instance_norm: ( + lambda input, running_mean=None, running_var=None, weight=None, bias=None, use_input_stats=True, momentum=0.1, eps=1e-05: -1 # noqa: B950 + ), + torch.nn.functional.interpolate: ( + lambda input, size=None, scale_factor=None, mode="nearest", align_corners=None, recompute_scale_factor=None, antialias=False: -1 # noqa: B950 + ), + torch.nn.functional.kl_div: lambda input, target, size_average=None, reduce=None, reduction="mean", log_target=False: -1, # noqa: B950 + torch.nn.functional.l1_loss: lambda input, target, size_average=None, reduce=None, reduction="mean", weight=None: -1, + torch.nn.functional.layer_norm: lambda input, normalized_shape, weight=None, bias=None, eps=1e-05: -1, + torch.nn.functional.leaky_relu: lambda input, negative_slope=0.01, inplace=False: -1, + torch.nn.functional.linear: lambda input, weight, bias=None: -1, + torch.nn.functional.local_response_norm: lambda input, size, alpha=0.0001, beta=0.75, k=1.0: -1, + torch.nn.functional.log_softmax: lambda input, dim=None, _stacklevel=3, dtype=None: -1, + torch.nn.functional.logsigmoid: lambda input: -1, + torch.nn.functional.lp_pool1d: lambda input, norm_type, kernel_size, stride=None, ceil_mode=False: -1, + torch.nn.functional.lp_pool2d: lambda input, norm_type, kernel_size, stride=None, ceil_mode=False: -1, + torch.nn.functional.lp_pool3d: lambda input, norm_type, kernel_size, stride=None, ceil_mode=False: -1, + torch.nn.functional.margin_ranking_loss: ( + lambda input1, input2, target, margin=0, size_average=None, reduce=None, reduction="mean": -1 + ), + torch.nn.functional.max_pool1d: ( + lambda input, kernel_size, stride=None, padding=0, dilation=1, ceil_mode=False, return_indices=False: -1 + ), + torch.nn.functional.max_pool1d_with_indices: ( + lambda input, kernel_size, stride=None, padding=0, dilation=1, return_indices=False, ceil_mode=False: -1 + ), + torch.nn.functional.max_pool2d: ( + lambda input, kernel_size, stride=None, padding=0, dilation=1, ceil_mode=False, return_indices=False: -1 + ), + torch.nn.functional.max_pool2d_with_indices: ( + lambda input, kernel_size, stride=None, padding=0, dilation=1, return_indices=False, ceil_mode=False: -1 + ), + torch.nn.functional.max_pool3d: ( + lambda input, kernel_size, stride=None, padding=0, dilation=1, return_indices=False, ceil_mode=False: -1 + ), + torch.nn.functional.max_pool3d_with_indices: ( + lambda input, kernel_size, stride=None, padding=0, dilation=1, return_indices=False, ceil_mode=False: -1 + ), + torch.nn.functional.max_unpool1d: lambda input, indices, kernel_size, stride=None, padding=0, output_size=None: -1, # noqa: B950 + torch.nn.functional.max_unpool2d: lambda input, indices, kernel_size, stride=None, padding=0, output_size=None: -1, # noqa: B950 + torch.nn.functional.max_unpool3d: lambda input, indices, kernel_size, stride=None, padding=0, output_size=None: -1, # noqa: B950 + torch.nn.functional.mse_loss: lambda input, target, size_average=None, reduce=None, reduction="mean", weight=None: -1, + torch.nn.functional.multi_head_attention_forward: ( + lambda query, key, value, embed_dim_to_check, num_heads, in_proj_weight, in_proj_bias, bias_k, bias_v, add_zero_attn, dropout_p, out_proj_weight, out_proj_bias, training=True, key_padding_mask=None, need_weights=True, attn_mask=None, use_separate_proj_weight=False, q_proj_weight=None, k_proj_weight=None, v_proj_weight=None, static_k=None, static_v=None, average_attn_weights=None, is_causal=False: -1 # noqa: B950 + ), + torch.nn.functional.multi_margin_loss: ( + lambda input, target, p=1, margin=1.0, weight=None, size_average=None, reduce=None, reduction="mean": -1 + ), + torch.nn.functional.multilabel_margin_loss: ( + lambda input, target, size_average=None, reduce=None, reduction="mean": -1 + ), + torch.nn.functional.multilabel_soft_margin_loss: ( + lambda input, target, weight=None, size_average=None, reduce=None, reduction="mean": -1 + ), + torch.nn.functional.nll_loss: ( + lambda input, target, weight=None, size_average=None, ignore_index=-100, reduce=None, reduction="mean": -1 + ), + torch.nn.functional.normalize: lambda input, p=2, dim=1, eps=1e-12, out=None: -1, + torch.nn.functional.one_hot: lambda tensor, num_classes=-1: -1, + torch.nn.functional.pad: lambda input, pad, mode="constant", value=0: -1, + torch.nn.functional.pairwise_distance: lambda x1, x2, p=2.0, eps=1e-06, keepdim=False: -1, + torch.nn.functional.poisson_nll_loss: ( + lambda input, target, log_input=True, full=False, size_average=None, eps=1e-08, reduce=None, reduction="mean": -1 # noqa: B950 + ), + torch.nn.functional.prelu: lambda input, weight: -1, + torch.nn.functional.relu: lambda input, inplace=False: -1, + torch.nn.functional.relu6: lambda input, inplace=False: -1, + torch.nn.functional.rms_norm: lambda input, normalized_shape, weight=None, eps=1e-6: -1, + torch.nn.functional.rrelu: lambda input, lower=0.125, upper=0.3333333333333333, training=False, inplace=False: -1, # noqa: B950 + torch.nn.functional.selu: lambda input, inplace=False: -1, + torch.nn.functional.silu: lambda input, inplace=False: -1, + torch.nn.functional.mish: lambda input, inplace=False: -1, + torch.nn.functional.scaled_dot_product_attention: lambda query, key, value, attn_mask=None, dropout_p=0.0: -1, + torch.nn.functional.smooth_l1_loss: lambda input, target, size_average=None, reduce=None, reduction="mean", beta=1.0: -1, # noqa: B950 + torch.nn.functional.huber_loss: lambda input, target, reduction="mean", delta=1.0, weight=None: -1, + torch.nn.functional.soft_margin_loss: lambda input, target, size_average=None, reduce=None, reduction="mean": -1, # noqa: B950 + torch.nn.functional.softmax: lambda input, dim=None, _stacklevel=3, dtype=None: -1, + torch.nn.functional.softmin: lambda input, dim=None, _stacklevel=3, dtype=None: -1, + torch.nn.functional.softplus: lambda input, beta=1, threshold=20: -1, + torch.nn.functional.softshrink: lambda input, lambd=0.5: -1, + torch.nn.functional.softsign: lambda input: -1, + torch.nn.functional.tanhshrink: lambda input: -1, + torch.nn.functional.threshold: lambda input, threshold, value, inplace=False: -1, + torch.nn.functional.triplet_margin_loss: ( + lambda anchor, positive, negative, margin=1.0, p=2, eps=1e-06, swap=False, size_average=None, reduce=None, reduction="mean": -1 # noqa: B950 + ), + torch.nn.functional.triplet_margin_with_distance_loss: ( + lambda anchor, positive, negative, *, distance_function=None, margin=1.0, swap=False, reduction="mean": -1 + ), + torch.nn.functional.unfold: lambda input, kernel_size, dilation=1, padding=0, stride=1: -1, + torch.nn.init.uniform_: lambda tensor, a=0.0, b=1.0, generator=None: -1, + torch.nn.init.normal_: lambda tensor, mean=0.0, std=1.0, generator=None: -1, + torch.nn.init.constant_: lambda tensor, val: -1, + torch.nn.init.kaiming_uniform_: lambda tensor, a=0, mode="fan_in", nonlinearity="leaky_relu", generator=None: -1, # noqa: B950 + torch.nonzero: lambda input, as_tuple=False: -1, + torch.nonzero_static: lambda input, *, size, fill_value=-1: -1, + torch.argwhere: lambda input: -1, + torch.norm: lambda input, p="fro", dim=None, keepdim=False, out=None, dtype=None: -1, + torch.linalg.norm: lambda input, ord=None, dim=None, keepdim=False, out=None, dtype=None: -1, + torch.linalg.vector_norm: lambda input, ord=2, dim=None, keepdim=False, out=None, dtype=None: -1, + torch.linalg.matrix_norm: lambda input, ord="fro", dim=( + -2, + -1, + ), keepdim=False, out=None, dtype=None: -1, + torch.norm_except_dim: lambda v, pow=2, dim=0: -1, + torch.nuclear_norm: lambda input, p="fro", dim=None, keepdim=False, out=None, dtype=None: -1, + torch.numel: lambda input: -1, + torch.orgqr: lambda input, tau: -1, + torch.ormqr: lambda input, input2, input3, left=True, transpose=False: -1, + torch.pairwise_distance: lambda x1, x2, p=2.0, eps=1e-06, keepdim=False: -1, + torch.permute: lambda self, dim: -1, + torch.pca_lowrank: lambda input, q=None, center=True, niter=2: -1, + torch.pdist: lambda input, p=2: -1, + torch.pinverse: lambda input, rcond=1e-15: -1, + torch.linalg.pinv: lambda input, rcond=1e-15, hermitian=False: -1, + torch.pixel_shuffle: lambda input, upscale_factor: -1, + torch.pixel_unshuffle: lambda input, downscale_factor: -1, + torch.poisson: lambda input, generator=None: -1, + torch.poisson_nll_loss: lambda input, target, log_input, full, eps, reduction: -1, + torch.polygamma: lambda input, n, out=None: -1, + torch.positive: lambda input, out=None: -1, + torch.prelu: lambda input, weight: -1, + torch.ones_like: lambda input, dtype=None, layout=None, device=None, requires_grad=False: -1, + torch.pow: lambda input, exponent, out=None: -1, + torch.prod: lambda input, dtype=None: -1, + torch.put: lambda input, index, source, accumulate=False: -1, + torch.q_per_channel_axis: lambda input: -1, + torch.q_per_channel_scales: lambda input: -1, + torch.q_per_channel_zero_points: lambda input: -1, + torch.q_scale: lambda input: -1, + torch.q_zero_point: lambda input: -1, + torch.qr: lambda input, some=True, out=None: -1, + torch.linalg.qr: lambda input, mode="reduced", out=None: -1, + torch.quantile: lambda input, q, dim=None, keepdim=False, interpolation="linear", out=None: -1, + torch.nanquantile: lambda input, q, dim=None, keepdim=False, interpolation="linear", out=None: -1, + torch.quantize_per_channel: lambda input, scales, zero_points, axis, dtype: -1, + torch.quantize_per_tensor: lambda input, scale, zero_point, dtype: -1, + torch.quantize_per_tensor_dynamic: lambda input, dtype, reduce_range: -1, + torch.quantized_batch_norm: lambda input, weight, bias, mean, var, eps, output_scale, output_zero_point: -1, + torch.quantized_gru_cell: ( + lambda input, hx, w_ih, w_hh, b_ih, b_hh, packed_ih, packed_hh, col_offsets_ih, col_offsets_hh, scale_ih, scale_hh, zero_point_ih, zero_point_hh: -1 # noqa: B950 + ), + torch.quantized_lstm_cell: ( + lambda input, hx, w_ih, w_hh, b_ih, b_hh, packed_ih, packed_hh, col_offsets_ih, col_offsets_hh, scale_ih, scale_hh, zero_point_ih, zero_point_hh: -1 # noqa: B950 + ), + torch.quantized_max_pool1d: ( + lambda input, kernel_size, stride=(), padding=(0,), dilation=( + 1, + ), ceil_mode=False: -1 + ), + torch.quantized_max_pool2d: ( + lambda input, kernel_size, stride=(), padding=(0, 0), dilation=( + 1, + 1, + ), ceil_mode=False: -1 + ), + torch.quantized_max_pool3d: ( + lambda input, kernel_size, stride=(), padding=(0, 0, 0), dilation=( + 1, + 1, + 1, + ), ceil_mode=False: -1 + ), + torch.quantized_rnn_relu_cell: ( + lambda input, hx, w_ih, w_hh, b_ih, b_hh, packed_ih, packed_hh, col_offsets_ih, col_offsets_hh, scale_ih, scale_hh, zero_point_ih, zero_point_hh: -1 # noqa: B950 + ), + torch.quantized_rnn_tanh_cell: ( + lambda input, hx, w_ih, w_hh, b_ih, b_hh, packed_ih, packed_hh, col_offsets_ih, col_offsets_hh, scale_ih, scale_hh, zero_point_ih, zero_point_hh: -1 # noqa: B950 + ), + torch.rad2deg: lambda input, out=None: -1, + torch.ravel: lambda input: -1, + torch.real: lambda input, out=None: -1, + torch.vdot: lambda input, other, out=None: -1, + torch.linalg.vecdot: lambda input, other, dim=-1, out=None: -1, + torch.view_as_real: lambda input: -1, + torch.view_as_complex: lambda input: -1, + torch.reciprocal: lambda input, out=None: -1, + torch.relu: lambda input, inplace=False: -1, + torch.remainder: lambda input, other, out=None: -1, + torch.renorm: lambda input, p, dim, maxnorm, out=None: -1, + torch.repeat_interleave: lambda input, dim=None: -1, + torch.reshape: lambda input, shape: -1, + torch.rms_norm: lambda input, normalized_shape, weight=None, eps=1e-6: -1, + torch.rnn_relu: lambda input, hx, params, has_biases, num_layers, dropout, train, bidirectional, batch_first: -1, # noqa: B950 + torch.rnn_relu_cell: lambda input, hx, w_ih, w_hh, b_ih=None, b_hh=None: -1, + torch.rnn_tanh: lambda input, hx, params, has_biases, num_layers, dropout, train, bidirectional, batch_first: -1, # noqa: B950 + torch.rnn_tanh_cell: lambda input, hx, w_ih, w_hh, b_ih=None, b_hh=None: -1, + torch.roll: lambda input, shifts, dims=None: -1, + torch.rot90: lambda input, k=1, dims=(0, 1): -1, + torch.round: lambda input, out=None: -1, + torch.row_stack: lambda tensors, out=None: -1, # alias for torch.vstack + torch._rowwise_prune: (lambda weight, mask, compressed_indices_dtype: -1), + torch.rrelu: lambda input, lower=1.0 / 8, upper=1.0 / 3, training=False, inplace=False: -1, + torch.rsqrt: lambda input, out=None: -1, + torch.rsub: lambda input, other, alpha=1: -1, + torch.saddmm: lambda input, mat1, mat2, beta=1, alpha=1, out=None: -1, + torch.scatter: lambda input, dim, index, src: -1, + torch.scatter_add: lambda input, dim, index, src: -1, + torch.scatter_reduce: lambda input, dim, index, src, reduce, include_self=True: -1, + torch.searchsorted: lambda sorted_sequence, input, out_int32=False, right=False, out=None: -1, + torch._segment_reduce: lambda data, reduce="max", lengths=None, indices=None, offsets=None, axis=0, unsafe=False: -1, # noqa: B950 + torch.select: lambda input, dim, index: -1, + torch.select_scatter: lambda input, src, dim, index: -1, + torch.slice_inverse: lambda input, src, dim=0, start=None, end=None, step=1: -1, + torch.slice_scatter: lambda input, src, dim=0, start=None, end=None, step=1: -1, + torch.selu: lambda input, inplace=False: -1, + torch.sigmoid: lambda input, out=None: -1, + torch.sign: lambda input, out=None: -1, + torch.signbit: lambda input, out=None: -1, + torch.sgn: lambda input, out=None: -1, + torch.sin: lambda input, out=None: -1, + torch.sinc: lambda input, out=None: -1, + torch.sinh: lambda input, out=None: -1, + torch.slogdet: lambda input: -1, + torch.linalg.slogdet: lambda input: -1, + torch.smm: lambda input, mat2, out_dtype=None: -1, + torch.spmm: lambda input, mat2, out_dtype=None: -1, + torch.softmax: lambda input, dim, dtype=None: -1, + torch.linalg.solve: lambda A, B, left=True, out=None: -1, + torch.linalg.solve_ex: lambda A, B, left=True, check_errors=False, out=None: -1, + torch.sort: lambda input, dim=-1, descending=False, *, stable=False, out=None: -1, + torch.split: lambda tensor, split_size_or_sections, dim=0: -1, + torch.split_with_sizes: lambda tensor, split_size_or_sections, dim=0: -1, + torch.sqrt: lambda input, out=None: -1, + torch.square: lambda input, out=None: -1, + torch.squeeze: lambda input, dim=None, out=None: -1, + torch.sspaddmm: lambda input, mat1, mat2, beta=1, alpha=1, out=None: -1, + torch.stack: lambda tensors, dim=0, out=None: -1, + torch.std: lambda input, dim=None: -1, + torch.std_mean: lambda input, dim=None: -1, + torch.stft: ( + lambda input, n_fft, hop_length=None, win_length=None, window=None, center=True, pad_mode="reflect", normalized=False, onesided=True, return_complex=None, align_to_window=None: -1 # noqa: B950 + ), + torch.sub: lambda input, other, out=None: -1, + torch.subtract: lambda input, other, out=None: -1, + torch.sum: lambda input, dim=None: -1, + torch.sym_float: lambda input: -1, + torch.sym_int: lambda input: -1, + torch.sym_max: lambda a, b: -1, + torch.sym_min: lambda a, b: -1, + torch.sym_not: lambda input: -1, + torch.sym_ite: lambda a, b, c: -1, + torch.sym_sum: lambda args: -1, + torch._sym_sqrt: lambda input: -1, + torch._sym_cos: lambda input: -1, + torch._sym_cosh: lambda input: -1, + torch._sym_sin: lambda input: -1, + torch._sym_sinh: lambda input: -1, + torch._sym_tan: lambda input: -1, + torch._sym_tanh: lambda input: -1, + torch._sym_asin: lambda input: -1, + torch._sym_acos: lambda input: -1, + torch._sym_atan: lambda input: -1, + torch.nansum: lambda input, dim=None: -1, + torch.svd: lambda input, some=True, compute_uv=True, out=None: -1, + torch.svd_lowrank: lambda input, q=6, niter=2, M=None: -1, + torch.linalg.svd: lambda input, full_matrices=True, out=None: -1, + torch.linalg.svdvals: lambda input, out=None: -1, + torch.swapaxes: lambda input, dim0, dim1: -1, + torch.swapdims: lambda input, axis0, axis1: -1, + torch.special.airy_ai: lambda input: -1, + torch.special.bessel_j0: lambda input: -1, + torch.special.bessel_j1: lambda input: -1, + torch.special.bessel_y0: lambda input: -1, + torch.special.bessel_y1: lambda input: -1, + torch.special.chebyshev_polynomial_t: lambda input, n, out=None: -1, + torch.special.chebyshev_polynomial_u: lambda input, n, out=None: -1, + torch.special.chebyshev_polynomial_v: lambda input, n, out=None: -1, + torch.special.chebyshev_polynomial_w: lambda input, n, out=None: -1, + torch.special.digamma: lambda input: -1, + torch.special.entr: lambda input: -1, + torch.special.erf: lambda input: -1, + torch.special.erfc: lambda input: -1, + torch.special.erfcx: lambda input: -1, + torch.special.erfinv: lambda input: -1, + torch.special.exp2: lambda input: -1, + torch.special.expit: lambda input: -1, + torch.special.expm1: lambda input: -1, + torch.special.gammainc: lambda input, other, out=None: -1, + torch.special.gammaincc: lambda input, other, out=None: -1, + torch.special.gammaln: lambda input: -1, + torch.special.hermite_polynomial_h: lambda input, n, out=None: -1, + torch.special.hermite_polynomial_he: lambda input, n, out=None: -1, + torch.special.i0: lambda input: -1, + torch.special.i0e: lambda input: -1, + torch.special.i1: lambda input: -1, + torch.special.i1e: lambda input: -1, + torch.special.laguerre_polynomial_l: lambda input, n, out=None: -1, + torch.special.legendre_polynomial_p: lambda input, n, out=None: -1, + torch.special.log1p: lambda input: -1, + torch.special.log_ndtr: lambda input: -1, + torch.special.log_softmax: lambda input, dim, dtype=None: -1, + torch.special.logit: lambda input: -1, + torch.special.logsumexp: lambda input, dim, keepdim=False, out=None: -1, + torch.special.modified_bessel_i0: lambda input: -1, + torch.special.modified_bessel_i1: lambda input: -1, + torch.special.modified_bessel_k0: lambda input: -1, + torch.special.modified_bessel_k1: lambda input: -1, + torch.special.multigammaln: lambda input, p: -1, + torch.special.ndtr: lambda input: -1, + torch.special.ndtri: lambda input: -1, + torch.special.polygamma: lambda input, n, out=None: -1, + torch.special.psi: lambda input: -1, + torch.special.round: lambda input: -1, + torch.special.scaled_modified_bessel_k0: lambda input: -1, + torch.special.scaled_modified_bessel_k1: lambda input: -1, + torch.special.shifted_chebyshev_polynomial_t: lambda input, n, out=None: -1, + torch.special.shifted_chebyshev_polynomial_u: lambda input, n, out=None: -1, + torch.special.shifted_chebyshev_polynomial_v: lambda input, n, out=None: -1, + torch.special.shifted_chebyshev_polynomial_w: lambda input, n, out=None: -1, + torch.special.sinc: lambda input: -1, + torch.special.softmax: lambda input, dim, dtype=None: -1, + torch.special.spherical_bessel_j0: lambda input: -1, + torch.special.xlog1py: lambda input, other, out=None: -1, + torch.special.xlogy: lambda input, other, out=None: -1, + torch.special.zeta: lambda self, other, out=None: -1, + torch.t: lambda input: -1, + torch.take: lambda input, index: -1, + torch.take_along_dim: lambda input, indices, dim=None, out=None: -1, + torch.tan: lambda input, out=None: -1, + torch.tanh: lambda input, out=None: -1, + torch.linalg.tensorinv: lambda a, ind=2: -1, + torch.linalg.tensorsolve: lambda a, b, dims=None: -1, + torch.tensordot: lambda a, b, dims=2, out=None: -1, + torch.tensor_split: lambda input, indices_or_sections, dim=0: -1, + torch.threshold: lambda input, threshold, value, inplace=False: -1, + torch.tile: lambda input, dims: -1, + torch.topk: lambda input, k, dim=-1, descending=False, out=None: -1, + torch.trace: lambda input: -1, + torch.transpose: lambda input, dim0, dim1: -1, + torch.trapz: lambda y, x=None, dim=-1: -1, + torch.trapezoid: lambda y, x=None, dim=-1: -1, + torch.triangular_solve: lambda input, A, upper=True, transpose=False, unitriangular=False: -1, + torch.linalg.solve_triangular: lambda input, B, upper, left=True, unitriangular=False: -1, + torch.tril: lambda input, diagonal=0, out=None: -1, + torch.triplet_margin_loss: ( + lambda anchor, positive, negative, margin=1.0, p=2, eps=1e-06, swap=False, size_average=None, reduce=None, reduction="mean": -1 # noqa: B950 + ), + torch.triu: lambda input, diagonal=0, out=None: -1, + torch.true_divide: lambda input, other: -1, + torch.trunc: lambda input, out=None: -1, + torch.unbind: lambda input, dim=0: -1, + torch.unflatten: lambda input, dim, sizes, names: -1, + torch.unique: lambda input, sorted=True, return_inverse=False, return_counts=False, dim=None: -1, + torch.unique_consecutive: lambda input, return_inverse=False, return_counts=False, dim=None: -1, + torch.unravel_index: lambda indices, shape: -1, + torch.unsafe_chunk: lambda input, chunks, dim=0: -1, + torch.unsafe_split: lambda tensor, split_size_or_sections, dim=0: -1, + torch.unsafe_split_with_sizes: lambda tensor, split_size_or_sections, dim=0: -1, + torch.unsqueeze: lambda input, dim, out=None: -1, + torch.linalg.vander: lambda x, N=None: -1, + torch.var: lambda input, dim=None: -1, + torch.var_mean: lambda input, dim=None: -1, + torch.vsplit: lambda input, indices_or_sections: -1, + torch.vstack: lambda tensors, out=None: -1, + torch.where: lambda condition, x=None, y=None: -1, + torch._wrapped_linear_prepack: lambda weight, weight_scale, weight_zero_point, bias : -1, + torch._wrapped_quantized_linear_prepacked: ( + lambda input, input_scale, input_zero_point, prepacked, out_scale, out_zero_point, out_channel : -1 # noqa: B950 + ), + torch.zeros_like: lambda input, dtype=None, layout=None, device=None, requires_grad=False: -1, + torch._fw_primal_copy: lambda self, level: -1, + torch._make_dual_copy: lambda primal, tangent, level: -1, + torch.view_as_real_copy: lambda self: -1, + torch.view_as_complex_copy: lambda self: -1, + torch._conj_copy: lambda self: -1, + torch._neg_view_copy: lambda self: -1, + torch.as_strided_copy: lambda self, size, stride, storage_offset=None: -1, + torch._sparse_broadcast_to_copy: lambda self, size: -1, + torch.diagonal_copy: lambda self, offset=0, dim1=0, dim2=1: -1, + torch.expand_copy: lambda self, size, *, implicit=False: -1, + torch.narrow_copy: lambda self, dim, start, length: -1, + torch.permute_copy: lambda self, dims: -1, + torch._reshape_alias_copy: lambda self, size, stride: -1, + torch.select_copy: lambda self, dim, index: -1, + torch.detach_copy: lambda self: -1, + torch.slice_copy: lambda self, dim=0, start=None, end=None, step=1: -1, + torch.split_copy: lambda self, split_size, dim=0: -1, + torch.split_with_sizes_copy: lambda self, split_sizes, dim=0: -1, + torch.squeeze_copy: lambda self, dim: -1, + torch.t_copy: lambda self: -1, + torch.transpose_copy: lambda self, dim0, dim1: -1, + torch.unsqueeze_copy: lambda self, dim: -1, + torch._indices_copy: lambda self: -1, + torch._values_copy: lambda self: -1, + torch.indices_copy: lambda self: -1, + torch.values_copy: lambda self: -1, + torch.crow_indices_copy: lambda self: -1, + torch.col_indices_copy: lambda self: -1, + torch.ccol_indices_copy: lambda self: -1, + torch.row_indices_copy: lambda self: -1, + torch.unbind_copy: lambda self, dim=0: -1, + torch.view_copy: lambda self, dtype: -1, + torch.unfold_copy: lambda self, dimension, size, step: -1, + torch.alias_copy: lambda self: -1, + Tensor.__floordiv__: lambda self, other: -1, + Tensor.__rfloordiv__: lambda self, other: -1, + Tensor.__ifloordiv__: lambda self, other: -1, + Tensor.__truediv__: lambda self, other: -1, + Tensor.__rtruediv__: lambda self, other: -1, + Tensor.__itruediv__: lambda self, other: -1, + Tensor.__lshift__: lambda self, other: -1, + Tensor.__rlshift__: lambda self, other: -1, + Tensor.__ilshift__: lambda self, other: -1, + Tensor.__rshift__: lambda self, other: -1, + Tensor.__rrshift__: lambda self, other: -1, + Tensor.__irshift__: lambda self, other: -1, + Tensor.__and__: lambda self, other: -1, + Tensor.__or__: lambda self, other: -1, + Tensor.__xor__: lambda self, other: -1, + Tensor.__float__: lambda self: -1, + Tensor.__complex__: lambda self: -1, + Tensor.__array__: lambda self, dtype: -1, + Tensor.__bool__: lambda self: -1, + Tensor.__contains__: lambda self, other: -1, + Tensor.__neg__: lambda self: -1, + Tensor.__invert__: lambda self: -1, + Tensor.__mod__: lambda self, other: -1, + Tensor.__rmod__: lambda self, other: -1, + Tensor.__imod__: lambda self, other: -1, + Tensor.__array_wrap__: lambda self, array: -1, + Tensor.__getitem__: lambda self, idx: -1, + Tensor.__deepcopy__: lambda self, memo: -1, + Tensor.__int__: lambda self: -1, + Tensor.__long__: lambda self: -1, + Tensor.__index__: lambda self: -1, + Tensor.__len__: lambda self: -1, + Tensor.__format__: lambda self, format_spec: -1, + Tensor.__reduce_ex__: lambda self, proto: -1, + Tensor.__reversed__: lambda self: -1, + Tensor.__repr__: lambda self, *, tensor_contents=None: -1, + Tensor.__setitem__: lambda self, k, v: -1, + Tensor.__setstate__: lambda self, d: -1, + Tensor.T.__get__: lambda self: -1, + Tensor.H.__get__: lambda self: -1, + Tensor.mT.__get__: lambda self: -1, + Tensor.mH.__get__: lambda self: -1, + Tensor._backward_hooks.__get__: lambda self: -1, + Tensor._post_accumulate_grad_hooks.__get__: lambda self: -1, + Tensor._base.__get__: lambda self: -1, + Tensor._cdata.__get__: lambda self: -1, + Tensor.grad.__get__: lambda self: -1, + Tensor._grad.__get__: lambda self: -1, + Tensor._grad_fn.__get__: lambda self: -1, + Tensor.grad_fn.__get__: lambda self: -1, + Tensor.grad_dtype.__get__: lambda self: -1, + Tensor._version.__get__: lambda self: -1, + Tensor._autocast_to_reduced_precision: lambda self, cuda_enabled, cpu_enabled, cuda_dtype, cpu_dtype: -1, + Tensor._autocast_to_full_precision: lambda self, cuda_enabled, cpu_enabled: -1, + Tensor._clear_non_serializable_cached_data: lambda self: -1, + Tensor.data.__get__: lambda self: -1, + Tensor.device.__get__: lambda self: -1, + Tensor.dtype.__get__: lambda self: -1, + Tensor.is_cuda.__get__: lambda self: -1, + Tensor.is_cpu.__get__: lambda self: -1, + Tensor.is_xla.__get__: lambda self: -1, + Tensor.is_xpu.__get__: lambda self: -1, + Tensor.is_ipu.__get__: lambda self: -1, + Tensor.is_leaf.__get__: lambda self: -1, + Tensor.retains_grad.__get__: lambda self: -1, + Tensor.is_meta.__get__: lambda self: -1, + Tensor.is_mps.__get__: lambda self: -1, + Tensor.is_mtia.__get__: lambda self: -1, + Tensor.is_nested.__get__: lambda self: -1, + Tensor.is_maia.__get__: lambda self: -1, + Tensor.is_mkldnn.__get__: lambda self: -1, + Tensor.is_quantized.__get__: lambda self: -1, + Tensor.is_sparse.__get__: lambda self: -1, + Tensor.is_sparse_csr.__get__: lambda self: -1, + Tensor.is_vulkan.__get__: lambda self: -1, + Tensor.itemsize.__get__: lambda self: -1, + Tensor.layout.__get__: lambda self: -1, + Tensor.name.__get__: lambda self: -1, + Tensor.names.__get__: lambda self: -1, + Tensor.nbytes.__get__: lambda self: -1, + Tensor.ndim.__get__: lambda self: -1, + Tensor.output_nr.__get__: lambda self: -1, + Tensor.requires_grad.__get__: lambda self: -1, + Tensor.shape.__get__: lambda self: -1, + Tensor.volatile.__get__: lambda self: -1, + Tensor.real.__get__: lambda self: -1, + Tensor.imag.__get__: lambda self: -1, + Tensor.__cuda_array_interface__.__get__: lambda self: -1, + Tensor.type: lambda self, dtype=None, non_blocking=False, **kwargs: -1, + Tensor._dimI: lambda self: -1, + Tensor._dimV: lambda self: -1, + Tensor._indices: lambda self: -1, + Tensor._is_view: lambda self: -1, + Tensor._nnz: lambda self: -1, + Tensor.crow_indices: lambda self: -1, + Tensor.col_indices: lambda self: -1, + Tensor.ccol_indices: lambda self: -1, + Tensor.row_indices: lambda self: -1, + Tensor._update_names: lambda self, names, inplace: -1, + Tensor._values: lambda self: -1, + Tensor.adjoint: lambda self: -1, + Tensor.align_as: lambda self, other: -1, + Tensor.align_to: lambda self, order, ellipsis_idx: -1, + Tensor.apply_: lambda self, callable: -1, + Tensor.as_strided: lambda self, size, stride: -1, + Tensor.as_strided_: lambda self, size, stride: -1, + Tensor.backward: lambda self, gradient=None, retain_graph=None, create_graph=False, inputs=None: -1, + Tensor.bfloat16: lambda self, memory_format=torch.preserve_format: -1, + Tensor.bool: lambda self, memory_format=torch.preserve_format: -1, + Tensor.byte: lambda self, memory_format=torch.preserve_format: -1, + Tensor.char: lambda self, memory_format=torch.preserve_format: -1, + Tensor.cauchy_: lambda self, median=0, sigma=1, *, generator=None: -1, + Tensor.coalesce: lambda self: -1, + Tensor._coalesced_: lambda self, coalesced: -1, + Tensor.contiguous: lambda self, memory_format=torch.contiguous_format: -1, + Tensor.copy_: lambda self, src, non_blocking=False: -1, + Tensor.cpu: lambda self, memory_format=torch.preserve_format: -1, + Tensor.cuda: lambda self, memory_format=torch.preserve_format: -1, + Tensor.mtia: lambda self, memory_format=torch.preserve_format: -1, + Tensor.xpu: lambda self, memory_format=torch.preserve_format: -1, + Tensor.ipu: lambda self, memory_format=torch.preserve_format: -1, + Tensor.data_ptr: lambda self: -1, + Tensor.dense_dim: lambda self: -1, + Tensor.diagonal_scatter: lambda self, src, offset=0, dim1=0, dim2=1: -1, + Tensor.dim: lambda self: -1, + Tensor.dim_order: lambda self, ambiguity_check=False: -1, + Tensor.double: lambda self, memory_format=torch.preserve_format: -1, + Tensor.cdouble: lambda self, memory_format=torch.preserve_format: -1, + Tensor.element_size: lambda self: -1, + Tensor.expand: lambda self, size: -1, + Tensor.expand_as: lambda self, other: -1, + Tensor.exponential_: lambda self, lambd=1, *, generator=None: -1, + Tensor.fill_: lambda self, value: -1, + Tensor.fill_diagonal_: lambda self, value: -1, + Tensor.float: lambda self, memory_format=torch.preserve_format: -1, + Tensor.cfloat: lambda self, memory_format=torch.preserve_format: -1, + Tensor.geometric_: lambda self, p, *, generator=None: -1, + Tensor.get_device: lambda self: -1, + Tensor.half: lambda self, memory_format=torch.preserve_format: -1, + Tensor.chalf: lambda self, memory_format=torch.preserve_format: -1, + Tensor.has_names: lambda self: -1, + Tensor.indices: lambda self: -1, + Tensor.int: lambda self, memory_format=torch.preserve_format: -1, + Tensor.is_coalesced: lambda self: -1, + Tensor.is_contiguous: lambda self: -1, + Tensor.is_inference: lambda self: -1, + Tensor.is_pinned: lambda self: -1, + Tensor.is_set_to: lambda self, tensor: -1, + Tensor.is_shared: lambda self: -1, + Tensor.item: lambda self: -1, + Tensor.log_normal_: lambda self, mean=1, std=2, *, generator=None: -1, + Tensor.log_softmax: lambda self, dim: -1, + Tensor.long: lambda self, memory_format=torch.preserve_format: -1, + Tensor.map_: lambda self, tensor, callable: -1, + Tensor.map2_: lambda self, x, y, callable: -1, + Tensor.mm: lambda self, mat2, out_dtype=None: -1, + Tensor.module_load: lambda self, other, assign=False: -1, + Tensor.narrow_copy: lambda self, dimension, start, length: -1, + Tensor.ndimension: lambda self: -1, + Tensor.nelement: lambda self: -1, + Tensor._nested_tensor_size: lambda self: -1, + Tensor._nested_tensor_storage_offsets: lambda self: -1, + Tensor._nested_tensor_strides: lambda self: -1, + Tensor.normal_: lambda self: -1, + Tensor.numpy: lambda self: -1, + Tensor.permute: lambda self, dim: -1, + Tensor.pin_memory: lambda self: -1, + Tensor.put_: lambda self, indices, tensor, accumulate=False: -1, + Tensor.qscheme: lambda self: -1, + Tensor.random_: lambda self, from_=0, to=None, *, generator=None: -1, + Tensor.record_stream: lambda self, stream: -1, + Tensor.refine_names: lambda self, names: -1, + Tensor.register_hook: lambda self, hook: -1, + Tensor.register_post_accumulate_grad_hook: lambda self, hook: -1, + Tensor.rename: lambda self, name: -1, + Tensor.repeat: lambda self, *size: -1, + Tensor.requires_grad_: lambda self, requires_grad=True: -1, + Tensor.reshape_as: lambda self, other: -1, + Tensor.resize: lambda self, *size: -1, + Tensor.resize_: lambda self, size: -1, + Tensor.resize_as: lambda self, other: -1, + Tensor.resize_as_sparse_: lambda self, other: -1, + Tensor.retain_grad: lambda self: -1, + Tensor.set_: lambda self, source=None, storage_offset=0, size=None, stride=None: -1, + Tensor.select_scatter: lambda self, src, dim, index: -1, + Tensor.share_memory_: lambda self: -1, + Tensor.short: lambda self, memory_format=torch.preserve_format: -1, + Tensor.size: lambda self: -1, + Tensor.slice_scatter: lambda self, src, dim=0, start=None, end=None, step=1: -1, + Tensor.sparse_dim: lambda self: -1, + Tensor.sparse_mask: lambda self, mask: -1, + Tensor._sparse_mask_projection: lambda self, mask, accumulate_matches=False: -1, + Tensor.sparse_resize_: lambda self, size1, size2, dense_dim: -1, + Tensor.sparse_resize_and_clear_: lambda self, size1, size2, dense_dim: -1, + Tensor.sspaddmm: lambda self, mat1, mat2, beta=1, alpha=1, out=None: -1, + Tensor.storage: lambda self: -1, + Tensor.untyped_storage: lambda self: -1, + Tensor.storage_offset: lambda self: -1, + Tensor.storage_type: lambda self: -1, + Tensor.sum_to_size: lambda self, size: -1, + Tensor.tile: lambda self, *reps: -1, + Tensor.to: lambda self, dtype, non_blocking=False, copy=False, memory_format=torch.preserve_format: -1, + Tensor.to_dense: lambda self, dtype=None, *, masked_grad=None: -1, + Tensor._to_dense: lambda self, dtype=None, masked_grad=None: -1, + Tensor.to_sparse: lambda self: -1, + Tensor.tolist: lambda self: -1, + Tensor.to_mkldnn: lambda self: -1, + Tensor.type_as: lambda self, other: -1, + Tensor.unfold: lambda self, dimension, size, step: -1, + Tensor.uniform_: lambda self, from_=0, to=1: -1, + Tensor.values: lambda self: -1, + Tensor.view: lambda self, shape: -1, + Tensor.view_as: lambda self, other: -1, + Tensor.zero_: lambda self: -1, + Tensor.__dlpack__: lambda self, stream=None, max_version=None, dl_device=None, copy=None: -1, + Tensor.__dlpack_device__: lambda self: -1, + Tensor.index: lambda self, a, b: -1, + torch.linalg.lstsq: lambda self, b, cond=None, driver=None: -1, + } # fmt: skip + + privateuse1_backend_name = ( + torch.utils.backend_registration._privateuse1_backend_name + ) + if hasattr(Tensor, privateuse1_backend_name): + ret[getattr(Tensor, privateuse1_backend_name)] = ( + lambda self, device=None, non_blocking=False, **kwargs: -1 + ) + ret[getattr(Tensor, f"is_{privateuse1_backend_name}").__get__] = lambda self: -1 + + ret2 = {} + ignored = get_ignored_functions() + + for k, v in ret.items(): + # Generate methods like __add__ and add_ by default from add + names = [ + k.__name__, # Default method + k.__name__ + "_", # Inplace variant + "__" + k.__name__ + "__", # Dunder method + "__i" + k.__name__ + "__", # Inplace dunder method + "__r" + k.__name__ + "__", # Reverse dunder method + ] + + if k.__name__.startswith("bitwise_"): + # bitwise_ have dunder methods of the form ____ + # And so on. + subname = k.__name__[len("bitwise_") :] + names.extend( + ["__" + subname + "__", "__i" + subname + "__", "__r" + subname + "__"] + ) + + for name in names: + func = getattr(Tensor, name, None) + if callable(func) and func not in ret and func not in ignored: + ret2[func] = v + + ret.update(ret2) + return ret + + +def wrap_torch_function(dispatcher: Callable): + """Wraps a given function with ``__torch_function__`` -related functionality. + + Parameters + ---------- + dispatcher: Callable + A callable that returns an iterable of Tensor-likes passed into the function. + + Note + ---- + This decorator may reduce the performance of your code. Generally, it's enough to express + your code as a series of functions that, themselves, support __torch_function__. If you + find yourself in the rare situation where this is not the case, e.g. if you're wrapping a + low-level library and you also need it to work for Tensor-likes, then this function is available. + + Examples + -------- + >>> def dispatcher(a): # Must have the same signature as func + ... return (a,) + >>> @torch.overrides.wrap_torch_function(dispatcher) + >>> def func(a): # This will make func dispatchable by __torch_function__ + ... return a + 0 + """ + + def inner(func): + @functools.wraps(func) + def wrapped(*args, **kwargs): + relevant_args = dispatcher(*args, **kwargs) + if has_torch_function(relevant_args): + return handle_torch_function(wrapped, relevant_args, *args, **kwargs) + + return func(*args, **kwargs) + + return wrapped + + return inner + + +def _get_overloaded_args( + relevant_args: Iterable[Any], + get_type_fn: Callable[[Any], type] | None = None, +) -> list[Any]: + """Returns a list of arguments on which to call __torch_function__. + + Checks arguments in relevant_args for __torch_function__ implementations, + storing references to the arguments and their types in overloaded_args and + overloaded_types in order of calling precedence. Only distinct types are + considered. If a type is a subclass of another type it will have higher + precedence, otherwise the precedence order is the same as the order of + arguments in relevant_args, that is, from left-to-right in the argument list. + + The precedence-determining algorithm implemented in this function is + described in `NEP-0018`_. + + See torch::append_overloaded_arg for the equivalent function in the C++ + implementation. + + Parameters + ---------- + relevant_args : iterable of array-like + Iterable of array-like arguments to check for __torch_function__ + methods. + + get_type_fn : callable, optional + Function to call on each argument in relevant_args to get its type. + + Returns + ------- + overloaded_args : list + Arguments from relevant_args on which to call __torch_function__ + methods, in the order in which they should be called. + + .. _NEP-0018: + https://numpy.org/neps/nep-0018-array-function-protocol.html + """ + if get_type_fn is None: + get_type_fn = type + + # If torch function is not enabled, there are no overloaded types + if not torch._C._is_torch_function_enabled(): + return [] + # Runtime is O(num_arguments * num_unique_types) + overloaded_types: set[type] = set() + overloaded_args: list[Any] = [] + for arg in relevant_args: + arg_type = get_type_fn(arg) + # We only collect arguments if they have a unique type, which ensures + # reasonable performance even with a long list of possibly overloaded + # arguments. + # + # NB: Important to exclude _disabled_torch_function_impl, otherwise + # https://github.com/pytorch/pytorch/issues/64687 + if ( + arg_type not in overloaded_types + and hasattr(arg_type, "__torch_function__") + and arg_type.__torch_function__ + is not torch._C._disabled_torch_function_impl + ): + # Create lists explicitly for the first type (usually the only one + # done) to avoid setting up the iterator for overloaded_args. + if overloaded_types: + overloaded_types.add(arg_type) + # By default, insert argument at the end, but if it is + # subclass of another argument, insert it before that argument. + # This ensures "subclasses before superclasses". + index = len(overloaded_args) + for i, old_arg in enumerate(overloaded_args): + if issubclass(arg_type, get_type_fn(old_arg)): + index = i + break + overloaded_args.insert(index, arg) + else: + overloaded_types = {arg_type} + overloaded_args = [arg] + return overloaded_args + + +def handle_torch_function( + public_api: Callable, + relevant_args: Iterable[Any], + *args, + **kwargs, +) -> Any: + """Implement a function with checks for ``__torch_function__`` overrides. + + See torch::autograd::handle_torch_function for the equivalent of this + function in the C++ implementation. + + Arguments + --------- + public_api : function + Function exposed by the public torch API originally called like + ``public_api(*args, **kwargs)`` on which arguments are now being + checked. + relevant_args : iterable + Iterable of arguments to check for __torch_function__ methods. + args : tuple + Arbitrary positional arguments originally passed into ``public_api``. + kwargs : tuple + Arbitrary keyword arguments originally passed into ``public_api``. + + Returns + ------- + object + Result from calling ``implementation`` or an ``__torch_function__`` + method, as appropriate. + + Raises + ------ + TypeError : if no implementation is found. + + Example + ------- + >>> def func(a): + ... if has_torch_function_unary(a): + ... return handle_torch_function(func, (a,), a) + ... return a + 0 + """ + # Check for __torch_function__ methods. + overloaded_args = _get_overloaded_args(relevant_args) + # overloaded_args already have unique types. + types = tuple(map(type, overloaded_args)) + + # Check for __torch_function__ mode. + if _is_torch_function_mode_enabled(): + # if we're here, the mode must be set to a TorchFunctionStackMode + # this unsets it and calls directly into TorchFunctionStackMode's torch function + with _pop_mode_temporarily() as mode: + result = mode.__torch_function__(public_api, types, args, kwargs) + if result is not NotImplemented: + return result + + # Call overrides + for overloaded_arg in overloaded_args: + # This call needs to become a classmethod call in the future. + # See https://github.com/pytorch/pytorch/issues/63767 + torch_func_method = overloaded_arg.__torch_function__ + if ( + hasattr(torch_func_method, "__self__") + and torch_func_method.__self__ is overloaded_arg + and torch_func_method is not torch._C._disabled_torch_function_impl + ): + warnings.warn( + "Defining your `__torch_function__ as a plain method is deprecated and " + "will be an error in future, please define it as a classmethod.", + DeprecationWarning, + stacklevel=2, + ) + + # Use `public_api` instead of `implementation` so __torch_function__ + # implementations can do equality/identity comparisons. + result = torch_func_method(public_api, types, args, kwargs) + + if result is not NotImplemented: + return result + + func_name = f"{public_api.__module__}.{public_api.__name__}" + msg = ( + f"no implementation found for '{func_name}' on types that implement " + f"__torch_function__: {[type(arg) for arg in overloaded_args]}" + ) + if _is_torch_function_mode_enabled(): + msg += f" nor in mode {_get_current_function_mode()}" + raise TypeError(msg) + + +has_torch_function = _add_docstr( + _has_torch_function, + r"""Check for __torch_function__ implementations in the elements of an iterable + or if a __torch_function__ mode is enabled. Considers exact ``Tensor`` s + and ``Parameter`` s non-dispatchable. Use this to guard a call to + :func:`handle_torch_function`; don't use it to test if something + is Tensor-like, use :func:`is_tensor_like` instead. + Arguments + --------- + relevant_args : iterable + Iterable or arguments to check for __torch_function__ methods. + Returns + ------- + bool + True if any of the elements of relevant_args have __torch_function__ + implementations, False otherwise. + See Also + ________ + torch.is_tensor_like + Checks if something is a Tensor-like, including an exact ``Tensor``. + """, +) + +has_torch_function_unary = _add_docstr( + _has_torch_function_unary, + r"""Special case of `has_torch_function` for single inputs. + Instead of: + `has_torch_function((t,))` + call: + `has_torch_function_unary(t)` + which skips unnecessary packing and unpacking work. + """, +) + +has_torch_function_variadic = _add_docstr( + _has_torch_function_variadic, + r"""Special case of `has_torch_function` that skips tuple creation. + + This uses the METH_FASTCALL protocol introduced in Python 3.7 + + Instead of: + `has_torch_function((a, b))` + call: + `has_torch_function_variadic(a, b)` + which skips unnecessary packing and unpacking work. + """, +) + + +@functools.cache +def _get_overridable_functions() -> tuple[ + dict[Any, list[Callable]], dict[Callable, str] +]: + overridable_funcs = collections.defaultdict(list) + index = {} + tested_namespaces = [ + ("torch", torch, torch.__all__), + ("torch.functional", torch.functional, torch.functional.__all__), + ("torch.nn.functional", torch.nn.functional, dir(torch.nn.functional)), + ("torch.nn.init", torch.nn.init, dir(torch.nn.init)), + ("torch.Tensor", torch.Tensor, dir(torch.Tensor)), + ("torch.linalg", torch.linalg, dir(torch.linalg)), + ("torch.fft", torch.fft, dir(torch.fft)), + ("torch.special", torch.special, dir(torch.special)), + ] + for namespace_str, namespace, ns_funcs in tested_namespaces: + for func_name in ns_funcs: + ignore = False + # ignore private functions or functions that are deleted in torch.__init__ + if namespace is not torch.Tensor: + if func_name.startswith("__"): + continue + elif func_name.startswith("_"): + ignore = True + elif func_name.endswith("_"): + ignore = True + elif not func_name[0].islower(): + ignore = True + elif func_name == "unique_dim": + continue + else: + func = getattr(namespace, func_name) + if getattr(object, func_name, None) == func: + continue + if func_name == "__weakref__": + continue + func = getattr(namespace, func_name) + if namespace is torch.Tensor and getattr(object, func_name, None) == func: + continue + # ignore re-exported modules + if isinstance(func, types.ModuleType): + continue + # ignore __future__ imports + if isinstance(func, __future__._Feature): + continue + + if not callable(func) and hasattr(func, "__get__"): + index[func.__get__] = f"{namespace_str}.{func_name}.__get__" + index[func.__set__] = f"{namespace_str}.{func_name}.__set__" + if ignore: + continue + if func.__get__ in get_ignored_functions(): + msg = ( + "{}.{} is in the tuple returned by torch._overrides.get_ignored_functions " + "but still has an explicit override" + ) + assert func.__get__ not in get_testing_overrides(), msg.format( + namespace, func.__name__ + ) + continue + else: + overridable_funcs[func].append(func.__get__) + continue + + if not callable(func): + continue + + index[func] = f"{namespace_str}.{func_name}" + + if ignore: + continue + + # cannot be overridden by __torch_function__ + if func in get_ignored_functions(): + msg = ( + "{}.{} is in the tuple returned by torch._overrides.get_ignored_functions " + "but still has an explicit override" + ) + assert func not in get_testing_overrides(), msg.format( + namespace, func.__name__ + ) + continue + overridable_funcs[namespace].append(func) + return overridable_funcs, index + + +@_disable_user_warnings +def get_overridable_functions() -> dict[Any, list[Callable]]: + """List functions that are overridable via __torch_function__ + + Returns + ------- + Dict[Any, List[Callable]] + A dictionary that maps namespaces that contain overridable functions + to functions in that namespace that can be overridden. + """ + return _get_overridable_functions()[0] + + +@_disable_user_warnings +def resolve_name(f): + """Get a human readable string name for a function passed to + __torch_function__ + + Arguments + --------- + f : Callable + Function to resolve the name of. + + Returns + ------- + str + Name of the function; if eval'ed it should give back the input + function. + """ + if isinstance(f, (torch._ops.OpOverload, torch._ops.OpOverloadPacket)): + return str(f) + return _get_overridable_functions()[1].get(f) + + +@functools.cache +def _get_tensor_methods() -> set[Callable]: + """Returns a set of the overridable methods on ``torch.Tensor``""" + overridable_funcs = get_overridable_functions() + methods = set(overridable_funcs[torch.Tensor]) + return methods + + +@_disable_user_warnings +def is_tensor_method_or_property(func: Callable) -> bool: + """ + Returns True if the function passed in is a handler for a + method or property belonging to ``torch.Tensor``, as passed + into ``__torch_function__``. + + .. note:: + For properties, their ``__get__`` method must be passed in. + + This may be needed, in particular, for the following reasons: + + 1. Methods/properties sometimes don't contain a `__module__` slot. + 2. They require that the first passed-in argument is an instance + of ``torch.Tensor``. + + Examples + -------- + >>> is_tensor_method_or_property(torch.Tensor.add) + True + >>> is_tensor_method_or_property(torch.add) + False + """ + return func in _get_tensor_methods() or func.__name__ == "__get__" + + +def is_tensor_like(inp): + """ + Returns ``True`` if the passed-in input is a Tensor-like. + + Currently, this occurs whenever there's a ``__torch_function__`` + attribute on the type of the input. + + Examples + -------- + A subclass of tensor is generally a Tensor-like. + + >>> class SubTensor(torch.Tensor): ... + >>> is_tensor_like(SubTensor([0])) + True + + Built-in or user types aren't usually Tensor-like. + + >>> is_tensor_like(6) + False + >>> is_tensor_like(None) + False + >>> class NotATensor: ... + >>> is_tensor_like(NotATensor()) + False + + But, they can be made Tensor-like by implementing __torch_function__. + + >>> class TensorLike: + ... @classmethod + ... def __torch_function__(cls, func, types, args, kwargs): + ... return -1 + >>> is_tensor_like(TensorLike()) + True + """ + return type(inp) is torch.Tensor or hasattr(inp, "__torch_function__") + + +class TorchFunctionMode: + """ + A ``TorchFunctionMode`` allows you to override the meaning of all + ``__torch_function__`` overridable functions within a dynamic scope, + without having to actually create a tensor subclass or manually + monkey-patch functions in the PyTorch API. Some common situations + where you should use a mode: + + * You want to override the meaning of factory functions, or other + functions that do not otherwise take a tensor as an argument + (these cannot be overridden with tensor subclasses). + + * You want to override the behavior of all functions without needing + to wrap your inputs in tensor subclasses; e.g., if you are just + interested in logging intermediate computations. + + * You want to control the order of execution of various tensor + subclasses explicitly, rather than implicitly via the return of + ``NotImplemented``. + + Independent subclasses of :class:`TorchFunctionMode` are compositional: + modes can be pushed onto a stack using ``with MyMode():``. + When you call functions in the PyTorch API inside your + ``__torch_function__`` implementation, by default, they will forward on to + the next mode on the mode stack. If you want recursively call back into + your current ``__torch_function__`` implementation, either explicitly + invoke ``self.__torch_function__(...)``, or use the context manager + ``enable_torch_function_mode(self, replace=self.inner)`` to make PyTorch + API self-referential (beware of infinite loops, in this case!) + """ + + inner: "TorchFunctionMode" + + # Force metaclass to generate constructor at the base of the hierarchy + def __init__(self) -> None: + pass + + def __torch_function__(self, func, types, args=(), kwargs=None): + raise NotImplementedError + + def __enter__(self): + _push_mode(self) + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + _pop_mode() + + @classmethod + def push(cls, *args, **kwargs): + warnings.warn( + "`Mode.push()` is no longer necessary and can be replaced with just `with Mode()`", + stacklevel=2, + ) + instance = cls(*args, **kwargs) + return instance + + +def _get_current_function_mode(): + stack_len = _len_torch_function_stack() + return _get_function_stack_at(stack_len - 1) if stack_len > 0 else None + + +def _get_current_function_mode_stack(): + stack_len = _len_torch_function_stack() + return [_get_function_stack_at(i) for i in range(stack_len)] + + +def _push_mode(mode): + _push_on_torch_function_stack(mode) + + +def _pop_mode(): + old = _pop_torch_function_stack() + return old + + +@contextlib.contextmanager +def _pop_mode_temporarily(): + old = _pop_mode() + try: + yield old + finally: + _push_mode(old) + + +class BaseTorchFunctionMode(TorchFunctionMode): + def __torch_function__(self, func, types, args=(), kwargs=None): + if kwargs is None: + kwargs = {} + return func(*args, **kwargs) + + +@contextlib.contextmanager +def _enable_torch_function(): + old_state = torch._C._get_torch_function_state() + try: + torch._C._set_torch_function_state(torch._C._TorchFunctionState.ENABLED) + yield + finally: + torch._C._set_torch_function_state(old_state) + + +@contextlib.contextmanager +def enable_reentrant_dispatch(): + # NB: this can't simply be + # `enable_reentrant_dispatch = torch._C._RestorePythonTLSSnapshot` + # because: + # 1. torch._C._RestorePythonTLSSnapshot is unavailable when this file + # initially gets imported. Probably an import order thing. + # 2. enable_reentrant_dispatch is technically public API; assigning + # it the object would change the __module__ to look private. + with torch._C._RestorePythonTLSSnapshot(): + try: + yield + finally: + pass diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/py.typed b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/quasirandom.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/quasirandom.py new file mode 100644 index 0000000000000000000000000000000000000000..f9e6619cab180da41e0d7ec5968cdfd20da9097c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/quasirandom.py @@ -0,0 +1,216 @@ +# mypy: allow-untyped-defs + +import torch + + +class SobolEngine: + r""" + The :class:`torch.quasirandom.SobolEngine` is an engine for generating + (scrambled) Sobol sequences. Sobol sequences are an example of low + discrepancy quasi-random sequences. + + This implementation of an engine for Sobol sequences is capable of + sampling sequences up to a maximum dimension of 21201. It uses direction + numbers from https://web.maths.unsw.edu.au/~fkuo/sobol/ obtained using the + search criterion D(6) up to the dimension 21201. This is the recommended + choice by the authors. + + References: + - Art B. Owen. Scrambling Sobol and Niederreiter-Xing points. + Journal of Complexity, 14(4):466-489, December 1998. + + - I. M. Sobol. The distribution of points in a cube and the accurate + evaluation of integrals. + Zh. Vychisl. Mat. i Mat. Phys., 7:784-802, 1967. + + Args: + dimension (Int): The dimensionality of the sequence to be drawn + scramble (bool, optional): Setting this to ``True`` will produce + scrambled Sobol sequences. Scrambling is + capable of producing better Sobol + sequences. Default: ``False``. + seed (Int, optional): This is the seed for the scrambling. The seed + of the random number generator is set to this, + if specified. Otherwise, it uses a random seed. + Default: ``None`` + + Examples:: + + >>> # xdoctest: +SKIP("unseeded random state") + >>> soboleng = torch.quasirandom.SobolEngine(dimension=5) + >>> soboleng.draw(3) + tensor([[0.0000, 0.0000, 0.0000, 0.0000, 0.0000], + [0.5000, 0.5000, 0.5000, 0.5000, 0.5000], + [0.7500, 0.2500, 0.2500, 0.2500, 0.7500]]) + """ + + MAXBIT = 30 + MAXDIM = 21201 + + def __init__(self, dimension, scramble=False, seed=None): + if dimension > self.MAXDIM or dimension < 1: + raise ValueError( + "Supported range of dimensionality " + f"for SobolEngine is [1, {self.MAXDIM}]" + ) + + self.seed = seed + self.scramble = scramble + self.dimension = dimension + + cpu = torch.device("cpu") + + self.sobolstate = torch.zeros( + dimension, self.MAXBIT, device=cpu, dtype=torch.long + ) + torch._sobol_engine_initialize_state_(self.sobolstate, self.dimension) + + if not self.scramble: + self.shift = torch.zeros(self.dimension, device=cpu, dtype=torch.long) + else: + self._scramble() + + self.quasi = self.shift.clone(memory_format=torch.contiguous_format) + self._first_point = (self.quasi / 2**self.MAXBIT).reshape(1, -1) + self.num_generated = 0 + + def draw( + self, + n: int = 1, + out: torch.Tensor | None = None, + dtype: torch.dtype | None = None, + ) -> torch.Tensor: + r""" + Function to draw a sequence of :attr:`n` points from a Sobol sequence. + Note that the samples are dependent on the previous samples. The size + of the result is :math:`(n, dimension)`. + + Args: + n (Int, optional): The length of sequence of points to draw. + Default: 1 + out (Tensor, optional): The output tensor + dtype (:class:`torch.dtype`, optional): the desired data type of the + returned tensor. + Default: ``None`` + """ + if dtype is None: + dtype = torch.get_default_dtype() + + if self.num_generated == 0: + if n == 1: + result = self._first_point.to(dtype) + else: + result, self.quasi = torch._sobol_engine_draw( + self.quasi, + n - 1, + self.sobolstate, + self.dimension, + self.num_generated, + dtype=dtype, + ) + result = torch.cat((self._first_point.to(dtype), result), dim=-2) + else: + result, self.quasi = torch._sobol_engine_draw( + self.quasi, + n, + self.sobolstate, + self.dimension, + self.num_generated - 1, + dtype=dtype, + ) + + self.num_generated += n + + if out is not None: + out.resize_as_(result).copy_(result) + return out + + return result + + def draw_base2( + self, + m: int, + out: torch.Tensor | None = None, + dtype: torch.dtype | None = None, + ) -> torch.Tensor: + r""" + Function to draw a sequence of :attr:`2**m` points from a Sobol sequence. + Note that the samples are dependent on the previous samples. The size + of the result is :math:`(2**m, dimension)`. + + Args: + m (Int): The (base2) exponent of the number of points to draw. + out (Tensor, optional): The output tensor + dtype (:class:`torch.dtype`, optional): the desired data type of the + returned tensor. + Default: ``None`` + """ + n = 2**m + total_n = self.num_generated + n + if not (total_n & (total_n - 1) == 0): + raise ValueError( + "The balance properties of Sobol' points require " + f"n to be a power of 2. {self.num_generated} points have been " + f"previously generated, then: n={self.num_generated}+2**{m}={total_n}. " + "If you still want to do this, please use " + "'SobolEngine.draw()' instead." + ) + return self.draw(n=n, out=out, dtype=dtype) + + def reset(self): + r""" + Function to reset the ``SobolEngine`` to base state. + """ + self.quasi.copy_(self.shift) + self.num_generated = 0 + return self + + def fast_forward(self, n): + r""" + Function to fast-forward the state of the ``SobolEngine`` by + :attr:`n` steps. This is equivalent to drawing :attr:`n` samples + without using the samples. + + Args: + n (Int): The number of steps to fast-forward by. + """ + if self.num_generated == 0: + torch._sobol_engine_ff_( + self.quasi, n - 1, self.sobolstate, self.dimension, self.num_generated + ) + else: + torch._sobol_engine_ff_( + self.quasi, n, self.sobolstate, self.dimension, self.num_generated - 1 + ) + self.num_generated += n + return self + + def _scramble(self): + g: torch.Generator | None = None + if self.seed is not None: + g = torch.Generator() + g.manual_seed(self.seed) + + cpu = torch.device("cpu") + + # Generate shift vector + shift_ints = torch.randint( + 2, (self.dimension, self.MAXBIT), device=cpu, generator=g + ) + self.shift = torch.mv( + shift_ints, torch.pow(2, torch.arange(0, self.MAXBIT, device=cpu)) + ) + + # Generate lower triangular matrices (stacked across dimensions) + ltm_dims = (self.dimension, self.MAXBIT, self.MAXBIT) + ltm = torch.randint(2, ltm_dims, device=cpu, generator=g).tril() + + torch._sobol_engine_scramble_(self.sobolstate, ltm, self.dimension) + + def __repr__(self): + fmt_string = [f"dimension={self.dimension}"] + if self.scramble: + fmt_string += ["scramble=True"] + if self.seed is not None: + fmt_string += [f"seed={self.seed}"] + return self.__class__.__name__ + "(" + ", ".join(fmt_string) + ")" diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/random.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/random.py new file mode 100644 index 0000000000000000000000000000000000000000..e36f635c0df1310703f8240a184715de6640e1d0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/random.py @@ -0,0 +1,207 @@ +# mypy: allow-untyped-defs +import contextlib +import warnings +from collections.abc import Generator + +import torch +from torch._C import default_generator + + +def set_rng_state(new_state: torch.Tensor) -> None: + r"""Sets the random number generator state. + + .. note:: This function only works for CPU. For CUDA, please use + :func:`torch.manual_seed`, which works for both CPU and CUDA. + + Args: + new_state (torch.ByteTensor): The desired state + """ + default_generator.set_state(new_state) + + +def get_rng_state() -> torch.Tensor: + r"""Returns the random number generator state as a `torch.ByteTensor`. + + .. note:: The returned state is for the default generator on CPU only. + + See also: :func:`torch.random.fork_rng`. + """ + return default_generator.get_state() + + +def manual_seed(seed) -> torch._C.Generator: + r"""Sets the seed for generating random numbers on all devices. Returns a + `torch.Generator` object. + + Args: + seed (int): The desired seed. Value must be within the inclusive range + `[-0x8000_0000_0000_0000, 0xffff_ffff_ffff_ffff]`. Otherwise, a RuntimeError + is raised. Negative inputs are remapped to positive values with the formula + `0xffff_ffff_ffff_ffff + seed`. + """ + return _manual_seed_impl(seed) + + +def _manual_seed_impl(seed) -> torch._C.Generator: + seed = int(seed) + import torch.cuda + + if not torch.cuda._is_in_bad_fork(): + torch.cuda.manual_seed_all(seed) + + import torch.mps + + if not torch.mps._is_in_bad_fork(): + torch.mps.manual_seed(seed) + + import torch.xpu + + if not torch.xpu._is_in_bad_fork(): + torch.xpu.manual_seed_all(seed) + + _seed_custom_device(seed) + + return default_generator.manual_seed(seed) + + +def seed() -> int: + r"""Sets the seed for generating random numbers to a non-deterministic + random number on all devices. Returns a 64 bit number used to seed the RNG. + """ + seed = default_generator.seed() + import torch.cuda + + if not torch.cuda._is_in_bad_fork(): + torch.cuda.manual_seed_all(seed) + + import torch.mps + + if not torch.mps._is_in_bad_fork(): + torch.mps.manual_seed(seed) + + import torch.xpu + + if not torch.xpu._is_in_bad_fork(): + torch.xpu.manual_seed_all(seed) + + _seed_custom_device(seed) + + return seed + + +def _seed_custom_device(seed) -> None: + r"""Sets the seed to generate random numbers for custom device. + + Args: + seed (int): The desired seed. + + See [Note: support the custom device with privateuse1] + """ + seed = int(seed) + custom_backend_name = torch._C._get_privateuse1_backend_name() + if hasattr(torch, custom_backend_name): + custom_device_mod = getattr(torch, custom_backend_name) + _bad_fork_name = "_is_in_bad_fork" + _seed_all_name = "manual_seed_all" + if hasattr(custom_device_mod, _bad_fork_name) and hasattr( + custom_device_mod, _seed_all_name + ): + if not getattr(custom_device_mod, _bad_fork_name)(): + getattr(custom_device_mod, _seed_all_name)(seed) + else: + message = f"Set seed for `{custom_backend_name}` device does not take effect, please add API's " + message += f"`{_bad_fork_name}` and `{_seed_all_name}` to `{custom_backend_name}` device module." + warnings.warn(message, UserWarning, stacklevel=3) + + +def initial_seed() -> int: + r"""Returns the initial seed for generating random numbers as a + Python `long`. + + .. note:: The returned seed is for the default generator on CPU only. + """ + return default_generator.initial_seed() + + +_fork_rng_warned_already = False + + +@contextlib.contextmanager +def fork_rng( + devices=None, + enabled=True, + _caller="fork_rng", + _devices_kw="devices", + device_type="cuda", +) -> Generator: + """ + Forks the RNG, so that when you return, the RNG is reset + to the state that it was previously in. + + Args: + devices (iterable of Device IDs): devices for which to fork + the RNG. CPU RNG state is always forked. By default, :meth:`fork_rng` operates + on all devices, but will emit a warning if your machine has a lot + of devices, since this function will run very slowly in that case. + If you explicitly specify devices, this warning will be suppressed + enabled (bool): if ``False``, the RNG is not forked. This is a convenience + argument for easily disabling the context manager without having + to delete it and unindent your Python code under it. + device_type (str): device type str, default is `cuda`. As for supported device, + see details in :ref:`accelerator` + """ + + if device_type == "meta": + yield + return + + device_type = torch.device(device_type).type + device_mod = getattr(torch, device_type, None) + if device_mod is None: + raise RuntimeError( + f"torch has no module of `{device_type}`, you should register " + + "a module by `torch._register_device_module`." + ) + global _fork_rng_warned_already + + # Internal arguments: + # _caller: the function which called fork_rng, which the user used + # _devices_kw: the devices keyword of _caller + + if not enabled: + yield + return + + if devices is None: + num_devices = device_mod.device_count() + if num_devices > 1 and not _fork_rng_warned_already: + message = ( + f"{device_type.upper()} reports that you have {num_devices} available devices, and " + f"you have used {_caller} without explicitly specifying which devices are being used. " + f"For safety, we initialize *every* {device_type.upper()} device by default, which can " + f"be quite slow if you have a lot of {device_type.upper()}s. If you know that you are only" + f" making use of a few {device_type.upper()} devices, set the environment variable " + f"{device_type.upper()}_VISIBLE_DEVICES or the '{_devices_kw}' keyword argument of {_caller} " + "with the set of devices you are actually using. For example, if you are using CPU only, " + "set device.upper()_VISIBLE_DEVICES= or devices=[]; if you are using device 0 only, " + f"set {device_type.upper()}_VISIBLE_DEVICES=0 or devices=[0]. To initialize all devices " + f"and suppress this warning, set the '{_devices_kw}' keyword argument to " + f"`range(torch.{device_type}.device_count())`." + ) + warnings.warn(message, stacklevel=2) + _fork_rng_warned_already = True + devices = list(range(num_devices)) + else: + # Protect against user passing us a generator; we need to traverse this + # multiple times but a generator will be exhausted upon first traversal + devices = list(devices) + + cpu_rng_state = torch.get_rng_state() + device_rng_states = [device_mod.get_rng_state(device) for device in devices] + + try: + yield + finally: + torch.set_rng_state(cpu_rng_state) + for device, device_rng_state in zip(devices, device_rng_states): + device_mod.set_rng_state(device_rng_state, device) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/return_types.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/return_types.py new file mode 100644 index 0000000000000000000000000000000000000000..d456742be4b88ebdca9f3696a415014a500cdd33 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/return_types.py @@ -0,0 +1,51 @@ +import inspect + +import torch +from torch.utils._pytree import register_pytree_node, SequenceKey + + +__all__ = ["pytree_register_structseq", "all_return_types"] + +all_return_types = [] + +# error: Module has no attribute "_return_types" +return_types = torch._C._return_types # type: ignore[attr-defined] + + +def pytree_register_structseq(cls): + def structseq_flatten(structseq): + return list(structseq), None + + def structseq_flatten_with_keys(structseq): + values, context = structseq_flatten(structseq) + return [(SequenceKey(i), v) for i, v in enumerate(values)], context + + def structseq_unflatten(values, context): + return cls(values) + + register_pytree_node( + cls, + structseq_flatten, + structseq_unflatten, + flatten_with_keys_fn=structseq_flatten_with_keys, + ) + + +for name in dir(return_types): + if name.startswith("__"): + continue + + _attr = getattr(return_types, name) + globals()[name] = _attr + + if not name.startswith("_"): + __all__.append(name) + all_return_types.append(_attr) + + # Today everything in torch.return_types is a structseq, aka a "namedtuple"-like + # thing defined by the Python C-API. We're going to need to modify this when that + # is no longer the case. + # NB: I don't know how to check that something is a "structseq" so we do a fuzzy + # check for tuple + if inspect.isclass(_attr) and issubclass(_attr, tuple): + pytree_register_structseq(_attr) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/return_types.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/return_types.pyi new file mode 100644 index 0000000000000000000000000000000000000000..e8dce0869e225ea2a50200240469d220ed296e34 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/return_types.pyi @@ -0,0 +1,605 @@ +# @generated by tools/pyi/gen_pyi.py from torch/_C/return_types.pyi.in +# mypy: allow-untyped-defs + +from typing import Final, NoReturn +from typing_extensions import Self + +from torch import SymInt, Tensor +from torch.types import ( # noqa: F401 + _bool, + _device, + _dtype, + _float, + _int, + _layout, + _qscheme, + _size, + Number, +) + +__all__ = [ + "pytree_register_structseq", + "all_return_types", + "_fake_quantize_per_tensor_affine_cachemask_tensor_qparams", + "_fused_moving_avg_obs_fq_helper", + "_linalg_det", + "_linalg_eigh", + "_linalg_slogdet", + "_linalg_solve_ex", + "_linalg_svd", + "_lu_with_info", + "_scaled_dot_product_cudnn_attention", + "_scaled_dot_product_efficient_attention", + "_scaled_dot_product_flash_attention", + "_scaled_dot_product_flash_attention_for_cpu", + "_unpack_dual", + "aminmax", + "cummax", + "cummin", + "frexp", + "geqrf", + "histogram", + "histogramdd", + "kthvalue", + "lu_unpack", + "max", + "median", + "min", + "mode", + "nanmedian", + "qr", + "slogdet", + "sort", + "svd", + "topk", + "triangular_solve", +] + +def pytree_register_structseq(cls: type) -> None: ... + +class _fake_quantize_per_tensor_affine_cachemask_tensor_qparams(tuple[Tensor, Tensor]): # fmt: skip + @property + def output(self) -> Tensor: ... + @property + def mask(self) -> Tensor: ... + def __new__( + cls, + sequence: tuple[Tensor, Tensor], + ) -> Self: # fmt: skip + ... + n_fields: Final[_int] = 2 + n_sequence_fields: Final[_int] = 2 + n_unnamed_fields: Final[_int] = 0 + def __init_subclass__(cls) -> NoReturn: ... # prohibit subclassing + +class _fused_moving_avg_obs_fq_helper(tuple[Tensor, Tensor]): # fmt: skip + @property + def output(self) -> Tensor: ... + @property + def mask(self) -> Tensor: ... + def __new__( + cls, + sequence: tuple[Tensor, Tensor], + ) -> Self: # fmt: skip + ... + n_fields: Final[_int] = 2 + n_sequence_fields: Final[_int] = 2 + n_unnamed_fields: Final[_int] = 0 + def __init_subclass__(cls) -> NoReturn: ... # prohibit subclassing + +class _linalg_det(tuple[Tensor, Tensor, Tensor]): # fmt: skip + @property + def result(self) -> Tensor: ... + @property + def LU(self) -> Tensor: ... + @property + def pivots(self) -> Tensor: ... + def __new__( + cls, + sequence: tuple[Tensor, Tensor, Tensor], + ) -> Self: # fmt: skip + ... + n_fields: Final[_int] = 3 + n_sequence_fields: Final[_int] = 3 + n_unnamed_fields: Final[_int] = 0 + def __init_subclass__(cls) -> NoReturn: ... # prohibit subclassing + +class _linalg_eigh(tuple[Tensor, Tensor]): # fmt: skip + @property + def eigenvalues(self) -> Tensor: ... + @property + def eigenvectors(self) -> Tensor: ... + def __new__( + cls, + sequence: tuple[Tensor, Tensor], + ) -> Self: # fmt: skip + ... + n_fields: Final[_int] = 2 + n_sequence_fields: Final[_int] = 2 + n_unnamed_fields: Final[_int] = 0 + def __init_subclass__(cls) -> NoReturn: ... # prohibit subclassing + +class _linalg_slogdet(tuple[Tensor, Tensor, Tensor, Tensor]): # fmt: skip + @property + def sign(self) -> Tensor: ... + @property + def logabsdet(self) -> Tensor: ... + @property + def LU(self) -> Tensor: ... + @property + def pivots(self) -> Tensor: ... + def __new__( + cls, + sequence: tuple[Tensor, Tensor, Tensor, Tensor], + ) -> Self: # fmt: skip + ... + n_fields: Final[_int] = 4 + n_sequence_fields: Final[_int] = 4 + n_unnamed_fields: Final[_int] = 0 + def __init_subclass__(cls) -> NoReturn: ... # prohibit subclassing + +class _linalg_solve_ex(tuple[Tensor, Tensor, Tensor, Tensor]): # fmt: skip + @property + def result(self) -> Tensor: ... + @property + def LU(self) -> Tensor: ... + @property + def pivots(self) -> Tensor: ... + @property + def info(self) -> Tensor: ... + def __new__( + cls, + sequence: tuple[Tensor, Tensor, Tensor, Tensor], + ) -> Self: # fmt: skip + ... + n_fields: Final[_int] = 4 + n_sequence_fields: Final[_int] = 4 + n_unnamed_fields: Final[_int] = 0 + def __init_subclass__(cls) -> NoReturn: ... # prohibit subclassing + +class _linalg_svd(tuple[Tensor, Tensor, Tensor]): # fmt: skip + @property + def U(self) -> Tensor: ... + @property + def S(self) -> Tensor: ... + @property + def Vh(self) -> Tensor: ... + def __new__( + cls, + sequence: tuple[Tensor, Tensor, Tensor], + ) -> Self: # fmt: skip + ... + n_fields: Final[_int] = 3 + n_sequence_fields: Final[_int] = 3 + n_unnamed_fields: Final[_int] = 0 + def __init_subclass__(cls) -> NoReturn: ... # prohibit subclassing + +class _lu_with_info(tuple[Tensor, Tensor, Tensor]): # fmt: skip + @property + def LU(self) -> Tensor: ... + @property + def pivots(self) -> Tensor: ... + @property + def info(self) -> Tensor: ... + def __new__( + cls, + sequence: tuple[Tensor, Tensor, Tensor], + ) -> Self: # fmt: skip + ... + n_fields: Final[_int] = 3 + n_sequence_fields: Final[_int] = 3 + n_unnamed_fields: Final[_int] = 0 + def __init_subclass__(cls) -> NoReturn: ... # prohibit subclassing + +class _scaled_dot_product_cudnn_attention(tuple[Tensor, Tensor, Tensor, Tensor, _int | SymInt, _int | SymInt, Tensor, Tensor, Tensor]): # fmt: skip + @property + def output(self) -> Tensor: ... + @property + def logsumexp(self) -> Tensor: ... + @property + def cum_seq_q(self) -> Tensor: ... + @property + def cum_seq_k(self) -> Tensor: ... + @property + def max_q(self) -> _int | SymInt: ... + @property + def max_k(self) -> _int | SymInt: ... + @property + def philox_seed(self) -> Tensor: ... + @property + def philox_offset(self) -> Tensor: ... + @property + def debug_attn_mask(self) -> Tensor: ... + def __new__( + cls, + sequence: tuple[Tensor, Tensor, Tensor, Tensor, _int | SymInt, _int | SymInt, Tensor, Tensor, Tensor], + ) -> Self: # fmt: skip + ... + n_fields: Final[_int] = 9 + n_sequence_fields: Final[_int] = 9 + n_unnamed_fields: Final[_int] = 0 + def __init_subclass__(cls) -> NoReturn: ... # prohibit subclassing + +class _scaled_dot_product_efficient_attention(tuple[Tensor, Tensor, Tensor, Tensor]): # fmt: skip + @property + def output(self) -> Tensor: ... + @property + def log_sumexp(self) -> Tensor: ... + @property + def philox_seed(self) -> Tensor: ... + @property + def philox_offset(self) -> Tensor: ... + def __new__( + cls, + sequence: tuple[Tensor, Tensor, Tensor, Tensor], + ) -> Self: # fmt: skip + ... + n_fields: Final[_int] = 4 + n_sequence_fields: Final[_int] = 4 + n_unnamed_fields: Final[_int] = 0 + def __init_subclass__(cls) -> NoReturn: ... # prohibit subclassing + +class _scaled_dot_product_flash_attention(tuple[Tensor, Tensor, Tensor, Tensor, _int | SymInt, _int | SymInt, Tensor, Tensor, Tensor]): # fmt: skip + @property + def output(self) -> Tensor: ... + @property + def logsumexp(self) -> Tensor: ... + @property + def cum_seq_q(self) -> Tensor: ... + @property + def cum_seq_k(self) -> Tensor: ... + @property + def max_q(self) -> _int | SymInt: ... + @property + def max_k(self) -> _int | SymInt: ... + @property + def rng_state(self) -> Tensor: ... + @property + def unused(self) -> Tensor: ... + @property + def debug_attn_mask(self) -> Tensor: ... + def __new__( + cls, + sequence: tuple[Tensor, Tensor, Tensor, Tensor, _int | SymInt, _int | SymInt, Tensor, Tensor, Tensor], + ) -> Self: # fmt: skip + ... + n_fields: Final[_int] = 9 + n_sequence_fields: Final[_int] = 9 + n_unnamed_fields: Final[_int] = 0 + def __init_subclass__(cls) -> NoReturn: ... # prohibit subclassing + +class _scaled_dot_product_flash_attention_for_cpu(tuple[Tensor, Tensor]): # fmt: skip + @property + def output(self) -> Tensor: ... + @property + def logsumexp(self) -> Tensor: ... + def __new__( + cls, + sequence: tuple[Tensor, Tensor], + ) -> Self: # fmt: skip + ... + n_fields: Final[_int] = 2 + n_sequence_fields: Final[_int] = 2 + n_unnamed_fields: Final[_int] = 0 + def __init_subclass__(cls) -> NoReturn: ... # prohibit subclassing + +class _unpack_dual(tuple[Tensor, Tensor]): # fmt: skip + @property + def primal(self) -> Tensor: ... + @property + def tangent(self) -> Tensor: ... + def __new__( + cls, + sequence: tuple[Tensor, Tensor], + ) -> Self: # fmt: skip + ... + n_fields: Final[_int] = 2 + n_sequence_fields: Final[_int] = 2 + n_unnamed_fields: Final[_int] = 0 + def __init_subclass__(cls) -> NoReturn: ... # prohibit subclassing + +class aminmax(tuple[Tensor, Tensor]): # fmt: skip + @property + def min(self) -> Tensor: ... + @property + def max(self) -> Tensor: ... + def __new__( + cls, + sequence: tuple[Tensor, Tensor], + ) -> Self: # fmt: skip + ... + n_fields: Final[_int] = 2 + n_sequence_fields: Final[_int] = 2 + n_unnamed_fields: Final[_int] = 0 + def __init_subclass__(cls) -> NoReturn: ... # prohibit subclassing + +class cummax(tuple[Tensor, Tensor]): # fmt: skip + @property + def values(self) -> Tensor: ... + @property + def indices(self) -> Tensor: ... + def __new__( + cls, + sequence: tuple[Tensor, Tensor], + ) -> Self: # fmt: skip + ... + n_fields: Final[_int] = 2 + n_sequence_fields: Final[_int] = 2 + n_unnamed_fields: Final[_int] = 0 + def __init_subclass__(cls) -> NoReturn: ... # prohibit subclassing + +class cummin(tuple[Tensor, Tensor]): # fmt: skip + @property + def values(self) -> Tensor: ... + @property + def indices(self) -> Tensor: ... + def __new__( + cls, + sequence: tuple[Tensor, Tensor], + ) -> Self: # fmt: skip + ... + n_fields: Final[_int] = 2 + n_sequence_fields: Final[_int] = 2 + n_unnamed_fields: Final[_int] = 0 + def __init_subclass__(cls) -> NoReturn: ... # prohibit subclassing + +class frexp(tuple[Tensor, Tensor]): # fmt: skip + @property + def mantissa(self) -> Tensor: ... + @property + def exponent(self) -> Tensor: ... + def __new__( + cls, + sequence: tuple[Tensor, Tensor], + ) -> Self: # fmt: skip + ... + n_fields: Final[_int] = 2 + n_sequence_fields: Final[_int] = 2 + n_unnamed_fields: Final[_int] = 0 + def __init_subclass__(cls) -> NoReturn: ... # prohibit subclassing + +class geqrf(tuple[Tensor, Tensor]): # fmt: skip + @property + def a(self) -> Tensor: ... + @property + def tau(self) -> Tensor: ... + def __new__( + cls, + sequence: tuple[Tensor, Tensor], + ) -> Self: # fmt: skip + ... + n_fields: Final[_int] = 2 + n_sequence_fields: Final[_int] = 2 + n_unnamed_fields: Final[_int] = 0 + def __init_subclass__(cls) -> NoReturn: ... # prohibit subclassing + +class histogram(tuple[Tensor, Tensor]): # fmt: skip + @property + def hist(self) -> Tensor: ... + @property + def bin_edges(self) -> Tensor: ... + def __new__( + cls, + sequence: tuple[Tensor, Tensor], + ) -> Self: # fmt: skip + ... + n_fields: Final[_int] = 2 + n_sequence_fields: Final[_int] = 2 + n_unnamed_fields: Final[_int] = 0 + def __init_subclass__(cls) -> NoReturn: ... # prohibit subclassing + +class histogramdd(tuple[Tensor, tuple[Tensor, ...]]): # fmt: skip + @property + def hist(self) -> Tensor: ... + @property + def bin_edges(self) -> tuple[Tensor, ...]: ... + def __new__( + cls, + sequence: tuple[Tensor, tuple[Tensor, ...]], + ) -> Self: # fmt: skip + ... + n_fields: Final[_int] = 2 + n_sequence_fields: Final[_int] = 2 + n_unnamed_fields: Final[_int] = 0 + def __init_subclass__(cls) -> NoReturn: ... # prohibit subclassing + +class kthvalue(tuple[Tensor, Tensor]): # fmt: skip + @property + def values(self) -> Tensor: ... + @property + def indices(self) -> Tensor: ... + def __new__( + cls, + sequence: tuple[Tensor, Tensor], + ) -> Self: # fmt: skip + ... + n_fields: Final[_int] = 2 + n_sequence_fields: Final[_int] = 2 + n_unnamed_fields: Final[_int] = 0 + def __init_subclass__(cls) -> NoReturn: ... # prohibit subclassing + +class lu_unpack(tuple[Tensor, Tensor, Tensor]): # fmt: skip + @property + def P(self) -> Tensor: ... + @property + def L(self) -> Tensor: ... + @property + def U(self) -> Tensor: ... + def __new__( + cls, + sequence: tuple[Tensor, Tensor, Tensor], + ) -> Self: # fmt: skip + ... + n_fields: Final[_int] = 3 + n_sequence_fields: Final[_int] = 3 + n_unnamed_fields: Final[_int] = 0 + def __init_subclass__(cls) -> NoReturn: ... # prohibit subclassing + +class max(tuple[Tensor, Tensor]): # fmt: skip + @property + def values(self) -> Tensor: ... + @property + def indices(self) -> Tensor: ... + def __new__( + cls, + sequence: tuple[Tensor, Tensor], + ) -> Self: # fmt: skip + ... + n_fields: Final[_int] = 2 + n_sequence_fields: Final[_int] = 2 + n_unnamed_fields: Final[_int] = 0 + def __init_subclass__(cls) -> NoReturn: ... # prohibit subclassing + +class median(tuple[Tensor, Tensor]): # fmt: skip + @property + def values(self) -> Tensor: ... + @property + def indices(self) -> Tensor: ... + def __new__( + cls, + sequence: tuple[Tensor, Tensor], + ) -> Self: # fmt: skip + ... + n_fields: Final[_int] = 2 + n_sequence_fields: Final[_int] = 2 + n_unnamed_fields: Final[_int] = 0 + def __init_subclass__(cls) -> NoReturn: ... # prohibit subclassing + +class min(tuple[Tensor, Tensor]): # fmt: skip + @property + def values(self) -> Tensor: ... + @property + def indices(self) -> Tensor: ... + def __new__( + cls, + sequence: tuple[Tensor, Tensor], + ) -> Self: # fmt: skip + ... + n_fields: Final[_int] = 2 + n_sequence_fields: Final[_int] = 2 + n_unnamed_fields: Final[_int] = 0 + def __init_subclass__(cls) -> NoReturn: ... # prohibit subclassing + +class mode(tuple[Tensor, Tensor]): # fmt: skip + @property + def values(self) -> Tensor: ... + @property + def indices(self) -> Tensor: ... + def __new__( + cls, + sequence: tuple[Tensor, Tensor], + ) -> Self: # fmt: skip + ... + n_fields: Final[_int] = 2 + n_sequence_fields: Final[_int] = 2 + n_unnamed_fields: Final[_int] = 0 + def __init_subclass__(cls) -> NoReturn: ... # prohibit subclassing + +class nanmedian(tuple[Tensor, Tensor]): # fmt: skip + @property + def values(self) -> Tensor: ... + @property + def indices(self) -> Tensor: ... + def __new__( + cls, + sequence: tuple[Tensor, Tensor], + ) -> Self: # fmt: skip + ... + n_fields: Final[_int] = 2 + n_sequence_fields: Final[_int] = 2 + n_unnamed_fields: Final[_int] = 0 + def __init_subclass__(cls) -> NoReturn: ... # prohibit subclassing + +class qr(tuple[Tensor, Tensor]): # fmt: skip + @property + def Q(self) -> Tensor: ... + @property + def R(self) -> Tensor: ... + def __new__( + cls, + sequence: tuple[Tensor, Tensor], + ) -> Self: # fmt: skip + ... + n_fields: Final[_int] = 2 + n_sequence_fields: Final[_int] = 2 + n_unnamed_fields: Final[_int] = 0 + def __init_subclass__(cls) -> NoReturn: ... # prohibit subclassing + +class slogdet(tuple[Tensor, Tensor]): # fmt: skip + @property + def sign(self) -> Tensor: ... + @property + def logabsdet(self) -> Tensor: ... + def __new__( + cls, + sequence: tuple[Tensor, Tensor], + ) -> Self: # fmt: skip + ... + n_fields: Final[_int] = 2 + n_sequence_fields: Final[_int] = 2 + n_unnamed_fields: Final[_int] = 0 + def __init_subclass__(cls) -> NoReturn: ... # prohibit subclassing + +class sort(tuple[Tensor, Tensor]): # fmt: skip + @property + def values(self) -> Tensor: ... + @property + def indices(self) -> Tensor: ... + def __new__( + cls, + sequence: tuple[Tensor, Tensor], + ) -> Self: # fmt: skip + ... + n_fields: Final[_int] = 2 + n_sequence_fields: Final[_int] = 2 + n_unnamed_fields: Final[_int] = 0 + def __init_subclass__(cls) -> NoReturn: ... # prohibit subclassing + +class svd(tuple[Tensor, Tensor, Tensor]): # fmt: skip + @property + def U(self) -> Tensor: ... + @property + def S(self) -> Tensor: ... + @property + def V(self) -> Tensor: ... + def __new__( + cls, + sequence: tuple[Tensor, Tensor, Tensor], + ) -> Self: # fmt: skip + ... + n_fields: Final[_int] = 3 + n_sequence_fields: Final[_int] = 3 + n_unnamed_fields: Final[_int] = 0 + def __init_subclass__(cls) -> NoReturn: ... # prohibit subclassing + +class topk(tuple[Tensor, Tensor]): # fmt: skip + @property + def values(self) -> Tensor: ... + @property + def indices(self) -> Tensor: ... + def __new__( + cls, + sequence: tuple[Tensor, Tensor], + ) -> Self: # fmt: skip + ... + n_fields: Final[_int] = 2 + n_sequence_fields: Final[_int] = 2 + n_unnamed_fields: Final[_int] = 0 + def __init_subclass__(cls) -> NoReturn: ... # prohibit subclassing + +class triangular_solve(tuple[Tensor, Tensor]): # fmt: skip + @property + def solution(self) -> Tensor: ... + @property + def cloned_coefficient(self) -> Tensor: ... + def __new__( + cls, + sequence: tuple[Tensor, Tensor], + ) -> Self: # fmt: skip + ... + n_fields: Final[_int] = 2 + n_sequence_fields: Final[_int] = 2 + n_unnamed_fields: Final[_int] = 0 + def __init_subclass__(cls) -> NoReturn: ... # prohibit subclassing + +all_return_types: list[type] = ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/serialization.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/serialization.py new file mode 100644 index 0000000000000000000000000000000000000000..1a6acc8010634ec9f2fcfc1d24f34f2dbe31b8c9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/serialization.py @@ -0,0 +1,2154 @@ +# mypy: allow-untyped-defs +import copyreg +import difflib +import functools +import io +import os +import pickle +import re +import shutil +import struct +import sys +import tarfile +import tempfile +import threading +import warnings +from collections.abc import Callable +from contextlib import closing, contextmanager +from enum import Enum +from typing import Any, cast, Generic, IO, TypeAlias, TypeVar +from typing_extensions import TypeIs + +import torch +import torch._weights_only_unpickler as _weights_only_unpickler +from torch._sources import get_source_lines_and_file +from torch._utils import _import_dotted_name +from torch.storage import _get_dtype_from_pickle_storage_type +from torch.types import FileLike, Storage + + +__all__ = [ + "SourceChangeWarning", + "mkdtemp", + "register_package", + "check_module_version_greater_or_equal", + "validate_cuda_device", + "validate_hpu_device", + "location_tag", + "default_restore_location", + "normalize_storage_type", + "storage_to_tensor_type", + "save", + "load", + "StorageType", + "LoadEndianness", + "get_crc32_options", + "set_crc32_options", + "get_default_load_endianness", + "set_default_load_endianness", + "get_default_mmap_options", + "set_default_mmap_options", + "clear_safe_globals", + "get_safe_globals", + "add_safe_globals", + "safe_globals", + "get_unsafe_globals_in_checkpoint", + "skip_data", +] + +DEFAULT_PROTOCOL = 2 + +LONG_SIZE = struct.Struct("=l").size +INT_SIZE = struct.Struct("=i").size +SHORT_SIZE = struct.Struct("=h").size + +MAGIC_NUMBER = 0x1950A86A20F9469CFC6C +PROTOCOL_VERSION = 1001 +STORAGE_KEY_SEPARATOR = "," + +MAP_LOCATION: TypeAlias = ( + Callable[[Storage, str], Storage] | torch.device | str | dict[str, str] | None +) +STORAGE: TypeAlias = Storage | torch.storage.TypedStorage | torch.UntypedStorage + +IS_WINDOWS = sys.platform == "win32" + +UNSAFE_MESSAGE = ( + "In PyTorch 2.6, we changed the default value of the `weights_only` argument in `torch.load` " + "from `False` to `True`. Re-running `torch.load` with `weights_only` set to `False` will likely succeed, " + "but it can result in arbitrary code execution. Do it only if you got the file from a " + "trusted source." +) + +if not IS_WINDOWS: + from mmap import MAP_PRIVATE, MAP_SHARED +else: + MAP_SHARED, MAP_PRIVATE = None, None # type: ignore[assignment] + + +def _default_to_weights_only(pickle_module): + is_fbcode = not hasattr(torch.version, "git_version") + return pickle_module is None and not is_fbcode + + +# _serialization_tls is used to store thread local state specific to serialization +# that needs to be propagated to other files, in particular we use this for +# (1) map_location (needed for wrapper subclasses/third party devices to torch._utils) +# (2) skip_data (needed for torch.Tensor.__reduce_ex__ for skip_data ctx) +# (3) materialize_fake_tensors (needed for torch.Tensor.__reduce_ex__ for skip_data ctx) +class _SerializationLocal(threading.local): + def __init__(self): + super().__init__() + self.map_location: MAP_LOCATION | None = None + self.skip_data: bool = False + self.materialize_fake_tensors: bool = False + + +_serialization_tls = _SerializationLocal() + + +class SourceChangeWarning(Warning): + pass + + +@contextmanager +def mkdtemp(): + path = tempfile.mkdtemp() + try: + yield path + finally: + shutil.rmtree(path) + + +_package_registry: list[ + tuple[ + int, + Callable[[STORAGE], str | None], + Callable[[STORAGE, str], STORAGE | None], + ] +] = [] + + +class LoadEndianness(Enum): + NATIVE = 1 + LITTLE = 2 + BIG = 3 + + +def get_default_load_endianness() -> LoadEndianness | None: + """ + Get fallback byte order for loading files + + If byteorder mark is not present in saved checkpoint, + this byte order is used as fallback. + By default, it's "native" byte order. + + Returns: + default_load_endian: Optional[LoadEndianness] + """ + from torch.utils.serialization import config + + return config.load.endianness + + +def set_default_load_endianness(endianness): + """ + Set fallback byte order for loading files + + If byteorder mark is not present in saved checkpoint, + this byte order is used as fallback. + By default, it's "native" byte order. + + Args: + endianness: the new fallback byte order + """ + if not isinstance(endianness, LoadEndianness) and endianness is not None: + raise TypeError("Invalid argument type in function set_default_load_endianness") + from torch.utils.serialization import config + + config.load.endianness = endianness + + +def get_crc32_options() -> bool: + """ + Get whether :func:`torch.save` computes and writes crc32 for each record. + + Defaults to ``True``. + """ + from torch.utils.serialization import config + + return config.save.compute_crc32 + + +def set_crc32_options(compute_crc32: bool): + """ + Set whether :func:`torch.save` computes and writes crc32 for each record. + + .. note:: + Setting this to ``False`` may make unzipping of the ``torch.save`` output + fail or warn due to corrupted CRC32. However ``torch.load`` will be + able to load the file. + + Args: + compute_crc32 (bool): set crc32 computation flag + """ + from torch.utils.serialization import config + + config.save.compute_crc32 = compute_crc32 + + +def get_default_mmap_options() -> int | None: + """ + Get default mmap options for :func:`torch.load` with ``mmap=True``. + + Defaults to ``mmap.MAP_PRIVATE``. + + + Returns: + default_mmap_options: int + """ + from torch.utils.serialization import config + + return config.load.mmap_flags + + +def _get_storage_alignment() -> int: + """ + Gets alignment for storages in torch.save files/ + + Defaults to 64. + + Returns: + storage_alginment: int + """ + from torch.utils.serialization import config + + return config.save.storage_alignment + + +class set_default_mmap_options: + """ + Context manager or function to set default mmap options for :func:`torch.load` with ``mmap=True`` to flags. + + For now, only either ``mmap.MAP_PRIVATE`` or ``mmap.MAP_SHARED`` are supported. + Please open an issue if you need any other option to be added here. + + .. note:: + This feature is currently not supported for Windows. + + Args: + flags: ``mmap.MAP_PRIVATE`` or ``mmap.MAP_SHARED`` + """ + + def __init__(self, flags: int) -> None: + if IS_WINDOWS: + raise RuntimeError( + "Changing the default mmap options is currently not supported for Windows" + ) + if flags != MAP_PRIVATE and flags != MAP_SHARED: + raise ValueError( + "Invalid argument in function set_default_mmap_options, " + f"expected mmap.MAP_PRIVATE or mmap.MAP_SHARED, but got {flags}" + ) + # global config + from torch.utils.serialization import config + + self.prev = config.load.mmap_flags + config.load.mmap_flags = flags + + def __enter__(self) -> None: + pass + + def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None: + from torch.utils.serialization import config + + config.load.mmap_flags = self.prev + + +def clear_safe_globals() -> None: + """ + Clears the list of globals that are safe for ``weights_only`` load. + """ + _weights_only_unpickler._clear_safe_globals() + + +def get_safe_globals() -> list[Callable | tuple[Callable, str]]: + """ + Returns the list of user-added globals that are safe for ``weights_only`` load. + """ + return _weights_only_unpickler._get_safe_globals() + + +def add_safe_globals(safe_globals: list[Callable | tuple[Callable, str]]) -> None: + """ + Marks the given globals as safe for ``weights_only`` load. For example, functions + added to this list can be called during unpickling, classes could be instantiated + and have state set. + + Each item in the list can either be a function/class or a tuple of the form + (function/class, string) where string is the full path of the function/class. + + Within the serialized format, each function is identified with its full + path as ``{__module__}.{__qualname__}``. When calling this API, you can provide this + full path that should match the one in the checkpoint otherwise the default + ``{fn.__module__}.{fn.__qualname__}`` will be used. + + Args: + safe_globals (List[Union[Callable, Tuple[Callable, str]]]): list of globals to mark as safe + + Example: + >>> # xdoctest: +SKIP("Can't torch.save(t, ...) as doctest thinks MyTensor is defined on torch.serialization") + >>> import tempfile + >>> class MyTensor(torch.Tensor): + ... pass + >>> t = MyTensor(torch.randn(2, 3)) + >>> with tempfile.NamedTemporaryFile() as f: + ... torch.save(t, f.name) + # Running `torch.load(f.name, weights_only=True)` will fail with + # Unsupported global: GLOBAL __main__.MyTensor was not an allowed global by default. + # Check the code and make sure MyTensor is safe to be used when loaded from an arbitrary checkpoint. + ... torch.serialization.add_safe_globals([MyTensor]) + ... torch.load(f.name, weights_only=True) + # MyTensor([[-0.5024, -1.8152, -0.5455], + # [-0.8234, 2.0500, -0.3657]]) + """ + _weights_only_unpickler._add_safe_globals(safe_globals) + + +class safe_globals(_weights_only_unpickler._safe_globals): + r"""Context-manager that adds certain globals as safe for ``weights_only`` load. + + Args: + safe_globals: List of globals for weights_only load. + + Example: + >>> # xdoctest: +SKIP("Can't torch.save(t, ...) as doctest thinks MyTensor is defined on torch.serialization") + >>> import tempfile + >>> class MyTensor(torch.Tensor): + ... pass + >>> t = MyTensor(torch.randn(2, 3)) + >>> with tempfile.NamedTemporaryFile() as f: + ... torch.save(t, f.name) + # Running `torch.load(f.name, weights_only=True)` will fail with + # Unsupported global: GLOBAL __main__.MyTensor was not an allowed global by default. + # Check the code and make sure MyTensor is safe to be used when loaded from an arbitrary checkpoint. + ... with torch.serialization.safe_globals([MyTensor]): + ... torch.load(f.name, weights_only=True) + # MyTensor([[-0.5024, -1.8152, -0.5455], + # [-0.8234, 2.0500, -0.3657]]) + >>> assert torch.serialization.get_safe_globals() == [] + """ + + +def get_unsafe_globals_in_checkpoint(f: FileLike) -> list[str]: + """Returns a list of strings of functions/classes in a ``torch.save`` object that are not safe for ``weights_only``. + + For a given function or class ``f``, the corresponding string will be of the form + ``{f.__module__}.{f.__name__}``. + + This function will return any GLOBALs in the checkpoint that are not in the set marked safe + for ``weights_only`` (either via :func:`add_safe_globals` or :class:`safe_globals` context or + allowlisted by ``torch`` by default). + + .. note:: + This function will statically disassemble the pickle file in the checkpoint. + The implication is any classes dynamically pushed onto the stack during unpickling + will not be included in the output. + + Args: + f: File-like object or string containing the checkpoint object saved via ``torch.save`` + + Returns: + A list of strings of pickle GLOBALs in the checkpoint that are not allowlisted for ``weights_only``. + """ + default_safe_globals_strings = set( + _weights_only_unpickler._get_allowed_globals().keys() + ) + user_safe_global_strings = set( + _weights_only_unpickler._get_user_allowed_globals().keys() + ) + safe_global_strings = default_safe_globals_strings.union(user_safe_global_strings) + + with _open_file_like(f, "rb") as opened_file: + if not _is_zipfile(opened_file): + raise ValueError("Expected input to be a checkpoint returned by torch.save") + with _open_zipfile_reader(opened_file) as zip_file: + if _is_torchscript_zip(zip_file): + raise ValueError( + "Expected input to be a checkpoint returned by torch.save but got a torchscript checkpoint" + ) + data_file = io.BytesIO(zip_file.get_record("data.pkl")) + all_globals = _weights_only_unpickler.get_globals_in_pkl(data_file) + return list(all_globals.difference(safe_global_strings)) + + +class skip_data: + """ + Context-manager that skips writing/reading storage bytes for ``torch.save`` / ``torch.load`` calls. + + For the save path, storages will still be saved, but the space that their bytes would usually be written to + will be empty space. The storage bytes can then be populated in a separate pass. + + For the load path, tensors will be loaded per the checkpoint but their storages will not be populated with data. + + .. warning:: + The ``skip_data`` context manager is an early prototype and is subject to change. + + Args: + materialize_fake_tensors: Whether to materialize FakeTensors during save. This is a no-op for the load path. + + Example: + >>> # xdoctest: +SKIP("NamedTemporaryFile on Windows") + >>> import tempfile + >>> t = torch.randn(2, 3) + >>> with tempfile.NamedTemporaryFile() as f: + ... with torch.serialization.skip_data(): + ... torch.save(t, f.name) + ... torch.load(f.name, weights_only=True) + tensor([[0., 0., 0.], + [0., 0., 0.]]) + """ + + def __init__(self, materialize_fake_tensors: bool = False): + self.materialize_fake_tensors = materialize_fake_tensors + + def __enter__(self): + global _serialization_tls + self._old_skip_data = _serialization_tls.skip_data + self._old_materialize_fake_tensors = _serialization_tls.materialize_fake_tensors + _serialization_tls.skip_data = True + _serialization_tls.materialize_fake_tensors = self.materialize_fake_tensors + + def __exit__(self, type, value, tb): + global _serialization_tls + _serialization_tls.skip_data = self._old_skip_data + _serialization_tls.materialize_fake_tensors = self._old_materialize_fake_tensors + + +def _is_zipfile(f) -> bool: + # This is a stricter implementation than zipfile.is_zipfile(). + # zipfile.is_zipfile() is True if the magic number appears anywhere in the + # binary. Since we expect the files here to be generated by torch.save or + # torch.jit.save, it's safe to only check the start bytes and avoid + # collisions and assume the zip has only 1 file. + # See bugs.python.org/issue28494. + + start = f.tell() + # Read the first few bytes and match against the ZIP file signature + local_header_magic_number = b"PK\x03\x04" + read_bytes = f.read(len(local_header_magic_number)) + f.seek(start) + return read_bytes == local_header_magic_number + + +def register_package( + priority: int, + tagger: Callable[[STORAGE], str | None], + deserializer: Callable[[STORAGE, str], STORAGE | None], +): + """ + Registers callables for tagging and deserializing storage objects with an associated priority. + Tagging associates a device with a storage object at save time while deserializing moves a + storage object to an appropriate device at load time. :attr:`tagger` and :attr:`deserializer` + are run in the order given by their :attr:`priority` until a tagger/deserializer returns a + value that is not `None`. + + To override the deserialization behavior for a device in the global registry, one can register a + tagger with a higher priority than the existing tagger. + + This function can also be used to register a tagger and deserializer for new devices. + + Args: + priority: Indicates the priority associated with the tagger and deserializer, where a lower + value indicates higher priority. + tagger: Callable that takes in a storage object and returns its tagged device as a string + or None. + deserializer: Callable that takes in storage object and a device string and returns a storage + object on the appropriate device or None. + + Returns: + `None` + + Example: + >>> def ipu_tag(obj): + >>> if obj.device.type == 'ipu': + >>> return 'ipu' + >>> def ipu_deserialize(obj, location): + >>> if location.startswith('ipu'): + >>> ipu = getattr(torch, "ipu", None) + >>> assert ipu is not None, "IPU device module is not loaded" + >>> assert torch.ipu.is_available(), "ipu is not available" + >>> return obj.ipu(location) + >>> torch.serialization.register_package(11, ipu_tag, ipu_deserialize) + """ + queue_elem = (priority, tagger, deserializer) + _package_registry.append(queue_elem) + _package_registry.sort() + + +def check_module_version_greater_or_equal( + module, + req_version_tuple, + error_if_malformed=True, +): + """ + Check if a module's version satisfies requirements + + Usually, a module's version string will be like 'x.y.z', which would be represented + as a tuple (x, y, z), but sometimes it could be an unexpected format. If the version + string does not match the given tuple's format up to the length of the tuple, then + error and exit or emit a warning. + + Args: + module: the module to check the version of + req_version_tuple: tuple (usually of ints) representing the required version + error_if_malformed: whether we should exit if module version string is malformed + + Returns: + requirement_is_met: bool + """ + try: + version_strs = module.__version__.split(".") + # Cast module version fields to match the types of the required version + module_version = tuple( + type(req_field)(version_strs[idx]) + for idx, req_field in enumerate(req_version_tuple) + ) + requirement_is_met = module_version >= req_version_tuple + + except Exception as e: + message = ( + f"'{module.__name__}' module version string is malformed '{module.__version__}' and cannot be compared" + f" with tuple {str(req_version_tuple)}" + ) + if error_if_malformed: + raise RuntimeError(message) from e + else: + warnings.warn( + message + ", but continuing assuming that requirement is met", + stacklevel=2, + ) + requirement_is_met = True + + return requirement_is_met + + +def _cpu_tag(obj): + if obj.device.type == "cpu": + return "cpu" + + +def _mps_tag(obj): + if obj.device.type == "mps": + return "mps" + + +def _meta_tag(obj): + if obj.device.type == "meta": + return "meta" + + +def _backend_tag(backend_name, obj): + if backend_name == "privateuse1": + backend_name = torch._C._get_privateuse1_backend_name() + if obj.device.type == backend_name: + if obj.device.index is None: + return backend_name + else: + return backend_name + ":" + str(obj.device.index) + + +def _cpu_deserialize(obj, location): + if location == "cpu": + return obj + + +def _mps_deserialize(obj, location): + if location.startswith("mps"): + return obj.mps() + + +def _meta_deserialize(obj, location): + if location == "meta": + return torch.UntypedStorage(obj.nbytes(), device="meta") + + +def _validate_device(location, backend_name): + """ + Check whether the device index of specified backend is valid + + In case of privateuse1 backend, your must first register a device_module for + privateuse1 using torch._register_device_module. Implement the following + methods in device_module like cuda: device_module._utils._get_device_index(location, True), + device_module.device_count(). + + Args: + location: string of device + backend_name: the backend name or the name of privateuse1, which can be renamed + + Returns: + device_index: int + """ + if not hasattr(torch, backend_name): + raise RuntimeError( + f"The {backend_name.upper()} device module is not registered. " + "If you are running on a CPU-only machine, " + "please use torch.load with map_location=torch.device('cpu') " + "to map your storages to the CPU." + ) + device_module = getattr(torch, backend_name) + if hasattr(device_module, "_utils") and hasattr( + device_module._utils, "_get_device_index" + ): + device_index = device_module._utils._get_device_index(location, True) + device = torch.device(backend_name, device_index) + else: + device = torch.device(location) + device_index = device.index if device.index else 0 + if hasattr(device_module, "is_available") and not device_module.is_available(): + raise RuntimeError( + f"Attempting to deserialize object on a {backend_name.upper()} " + f"device but torch.{backend_name}.is_available() is False. " + "If you are running on a CPU-only machine, " + "please use torch.load with map_location=torch.device('cpu') " + "to map your storages to the CPU." + ) + if hasattr(device_module, "device_count"): + device_count = device_module.device_count() + if device_index >= device_count: + raise RuntimeError( + f"Attempting to deserialize object on {backend_name.upper()} device " + f"{device_index} but torch.{backend_name}.device_count() is {device_count}. " + "Please use torch.load with map_location to map your storages " + "to an existing device." + ) + return device + + +def validate_cuda_device(location): + return _validate_device(location, "cuda").index + + +def validate_hpu_device(location): + return _validate_device(location, "hpu").index + + +def _deserialize(backend_name, obj, location): + if backend_name == "privateuse1": + backend_name = torch._C._get_privateuse1_backend_name() + if location.startswith(backend_name): + device = _validate_device(location, backend_name) + return obj.to(device=device) + + +register_package(10, _cpu_tag, _cpu_deserialize) +register_package( + 20, + functools.partial(_backend_tag, "cuda"), + functools.partial(_deserialize, "cuda"), +) +register_package(21, _mps_tag, _mps_deserialize) +register_package(22, _meta_tag, _meta_deserialize) +register_package( + 23, + functools.partial(_backend_tag, "privateuse1"), + functools.partial(_deserialize, "privateuse1"), +) +register_package( + 24, + functools.partial(_backend_tag, "hpu"), + functools.partial(_deserialize, "hpu"), +) +register_package( + 25, + functools.partial(_backend_tag, "xpu"), + functools.partial(_deserialize, "xpu"), +) +register_package( + 26, + functools.partial(_backend_tag, "mtia"), + functools.partial(_deserialize, "mtia"), +) + + +def location_tag( + storage: Storage | torch.storage.TypedStorage | torch.UntypedStorage, +): + for _, tagger, _ in _package_registry: + location = tagger(storage) + if location: + return location + raise RuntimeError( + "don't know how to determine data location of " + torch.typename(storage) + ) + + +def default_restore_location(storage, location): + """ + Restores `storage` using a deserializer function registered for the `location`. + + This function looks in the registry for deserializer functions that match the `location`. + If found, it attempts to use them, in priority order, to restore `storage` until one + returns a not `None` result. If no deserializer can be found in the registry, or all found fail + to bear a result, it raises a `RuntimeError`. + + Args: + storage (STORAGE): the storage object to restore + location (str): the location tag associated with the storage object + + Returns: + storage: Optional[STORAGE] + + Raises: + RuntimeError: If no deserializer matching `location` is found in the registry or if + all matching ones return `None`. + """ + for _, _, fn in _package_registry: + result = fn(storage, location) + if result is not None: + return result + raise RuntimeError( + "don't know how to restore data location of " + + torch.typename(storage) + + " (tagged with " + + location + + ")" + ) + + +def normalize_storage_type(storage_type): + return getattr(torch, storage_type.__name__) + + +def storage_to_tensor_type(storage): + storage_type = type(storage) + module = _import_dotted_name(storage_type.__module__) + return getattr(module, storage_type.__name__.replace("Storage", "Tensor")) + + +def _is_path(name_or_buffer: object) -> TypeIs[str | os.PathLike]: + return isinstance(name_or_buffer, (str, os.PathLike)) + + +T = TypeVar("T") + + +class _opener(Generic[T]): + def __init__(self, file_like: T) -> None: + self.file_like: T = file_like + + def __enter__(self): + return self.file_like + + def __exit__(self, *args): + pass + + +class _open_file(_opener[IO[bytes]]): + def __init__(self, name: str | os.PathLike[str], mode: str) -> None: + super().__init__(open(name, mode)) # noqa: SIM115 + + def __exit__(self, *args): + self.file_like.close() + + +class _open_buffer_reader(_opener[IO[bytes]]): + def __init__(self, buffer: IO[bytes]) -> None: + super().__init__(buffer) + _check_seekable(buffer) + + +class _open_buffer_writer(_opener[IO[bytes]]): + def __exit__(self, *args): + self.file_like.flush() + + +def _open_file_like(name_or_buffer: FileLike, mode: str) -> _opener[IO[bytes]]: + if _is_path(name_or_buffer): + return _open_file(name_or_buffer, mode) + else: + if "w" in mode: + return _open_buffer_writer(name_or_buffer) + elif "r" in mode: + return _open_buffer_reader(name_or_buffer) + else: + raise RuntimeError(f"Expected 'r' or 'w' in mode but got {mode}") + + +class _open_zipfile_reader(_opener[torch._C.PyTorchFileReader]): + def __init__(self, name_or_buffer: str | IO[bytes]) -> None: + super().__init__(torch._C.PyTorchFileReader(name_or_buffer)) + + +class _open_zipfile_writer_file(_opener[torch._C.PyTorchFileWriter]): + def __init__(self, name: str) -> None: + self.file_stream = None + self.name = name + try: + self.name.encode("ascii") + except UnicodeEncodeError: + # PyTorchFileWriter only supports ascii filename. + # For filenames with non-ascii characters, we rely on Python + # for writing out the file. + # pyrefly: ignore [bad-assignment] + self.file_stream = io.FileIO(self.name, mode="w") + super().__init__( + torch._C.PyTorchFileWriter( # pyrefly: ignore # no-matching-overload + self.file_stream, get_crc32_options(), _get_storage_alignment() + ) + ) + else: + super().__init__( + torch._C.PyTorchFileWriter( + self.name, get_crc32_options(), _get_storage_alignment() + ) + ) + + def __exit__(self, *args) -> None: + self.file_like.write_end_of_file() + if self.file_stream is not None: + self.file_stream.close() + + +class _open_zipfile_writer_buffer(_opener[torch._C.PyTorchFileWriter]): + def __init__(self, buffer: IO[bytes]) -> None: + if not callable(getattr(buffer, "write", None)): + msg = f"Buffer of {str(type(buffer)).strip('<>')} has no callable attribute 'write'" + if not hasattr(buffer, "write"): + raise AttributeError(msg) + raise TypeError(msg) + self.buffer = buffer + super().__init__( + torch._C.PyTorchFileWriter( + buffer, get_crc32_options(), _get_storage_alignment() + ) + ) + + def __exit__(self, *args) -> None: + self.file_like.write_end_of_file() + self.buffer.flush() + + +def _open_zipfile_writer(name_or_buffer: str | IO[bytes]) -> _opener: + container: type[_opener] + if _is_path(name_or_buffer): + container = _open_zipfile_writer_file + else: + container = _open_zipfile_writer_buffer + return container(name_or_buffer) # type: ignore[arg-type] + + +def _is_compressed_file(f) -> bool: + compress_modules = ["gzip"] + try: + return f.__module__ in compress_modules + except AttributeError: + return False + + +def _should_read_directly(f): + """ + Checks if f is a file that should be read directly. It should be read + directly if it is backed by a real file (has a fileno) and is not a + a compressed file (e.g. gzip) + """ + if _is_compressed_file(f): + return False + try: + return f.fileno() >= 0 + except io.UnsupportedOperation: + return False + except AttributeError: + return False + + +def _check_seekable(f) -> bool: + def raise_err_msg(patterns, e): + for p in patterns: + if p in str(e): + msg = ( + str(e) + + ". You can only torch.load from a file that is seekable." + + " Please pre-load the data into a buffer like io.BytesIO and" + + " try to load from it instead." + ) + raise type(e)(msg) + raise e + + try: + f.seek(f.tell()) + return True + except (io.UnsupportedOperation, AttributeError) as e: + raise_err_msg(["seek", "tell"], e) + return False + + +def _check_dill_version(pickle_module) -> None: + """Checks if using dill as the pickle module, and if so, checks if it is the correct version. + If dill version is lower than 0.3.1, a ValueError is raised. + + Args: + pickle_module: module used for pickling metadata and objects + + """ + if pickle_module is not None and pickle_module.__name__ == "dill": + required_dill_version = (0, 3, 1) + if not check_module_version_greater_or_equal( + pickle_module, required_dill_version, False + ): + raise ValueError( + ( + "'torch' supports dill >= {}, but you have dill {}." + " Please upgrade dill or switch to 'pickle'" + ).format( + ".".join([str(num) for num in required_dill_version]), + pickle_module.__version__, + ) + ) + + +def _check_save_filelike(f): + if not _is_path(f) and not hasattr(f, "write"): + raise AttributeError( + "expected 'f' to be string, path, or a file-like object with " + "a 'write' attribute" + ) + + +def save( + obj: object, + f: FileLike, + pickle_module: Any = pickle, + pickle_protocol: int = DEFAULT_PROTOCOL, + _use_new_zipfile_serialization: bool = True, + _disable_byteorder_record: bool = False, +) -> None: + # Reference: https://github.com/pytorch/pytorch/issues/54354 + # The first line of this docstring overrides the one Sphinx generates for the + # documentation. We need it so that Sphinx doesn't leak `pickle`s path from + # the build environment (e.g. `>> # xdoctest: +SKIP("makes cwd dirty") + >>> # Save to file + >>> x = torch.tensor([0, 1, 2, 3, 4]) + >>> torch.save(x, "tensor.pt") + >>> # Save to io.BytesIO buffer + >>> buffer = io.BytesIO() + >>> torch.save(x, buffer) + """ + torch._C._log_api_usage_once("torch.save") + _check_dill_version(pickle_module) + _check_save_filelike(f) + + if isinstance(f, (str, os.PathLike)): + f = os.fspath(f) + + if _use_new_zipfile_serialization: + with _open_zipfile_writer(f) as opened_zipfile: + _save( + obj, + opened_zipfile, + pickle_module, + pickle_protocol, + _disable_byteorder_record, + ) + return + else: + global _serialization_tls + if _serialization_tls.skip_data: + raise RuntimeError( + "Cannot use skip_data=True with _use_new_zipfile_serialization=False" + ) + with _open_file_like(f, "wb") as opened_file: + _legacy_save(obj, opened_file, pickle_module, pickle_protocol) + + +def _legacy_save(obj, f, pickle_module, pickle_protocol) -> None: + import torch.nn as nn + + serialized_container_types = {} + serialized_storages: dict[str, tuple[torch.UntypedStorage, torch.dtype]] = {} + + # Since loading storages that view the same data with different dtypes is + # not supported, we need to keep track of the dtype associated with each + # storage data_ptr and throw an error if the dtype is ever different. + # TODO: This feature could be added in the future + storage_dtypes: dict[int, torch.dtype] = {} + + def persistent_id(obj: Any) -> tuple | None: + # FIXME: the docs say that persistent_id should only return a string + # but torch store returns tuples. This works only in the binary protocol + # see + # https://docs.python.org/2/library/pickle.html#pickling-and-unpickling-external-objects + # https://github.com/python/cpython/blob/master/Lib/pickle.py#L527-L537 + if isinstance(obj, type) and issubclass(obj, nn.Module): + if obj in serialized_container_types: + return None + serialized_container_types[obj] = True + source_file = source = None + try: + source_lines, _, source_file = get_source_lines_and_file(obj) + source = "".join(source_lines) + except ( + Exception + ): # saving the source is optional, so we can ignore any errors + warnings.warn( + "Couldn't retrieve source code for container of " + "type " + obj.__name__ + ". It won't be checked " + "for correctness upon loading.", + stacklevel=2, + ) + return ("module", obj, source_file, source) + + if isinstance(obj, torch.storage.TypedStorage) or torch.is_storage(obj): + storage: torch.UntypedStorage + + if isinstance(obj, torch.storage.TypedStorage): + # TODO: Once we decide to break serialization FC, this case + # can be deleted + storage = obj._untyped_storage + storage_dtype = obj.dtype + storage_type_str = obj._pickle_storage_type() + storage_type = getattr(torch, storage_type_str) + dtype = obj.dtype + storage_numel = obj._size() + + elif isinstance(obj, torch.UntypedStorage): + storage = obj + storage_dtype = torch.uint8 + storage_type = normalize_storage_type(type(obj)) + dtype = torch.uint8 + storage_numel = storage.nbytes() + else: + raise TypeError(f"type not recognized: {type(obj)}") + + # If storage is allocated, ensure that any other saved storages + # pointing to the same data all have the same dtype. If storage is + # not allocated, don't perform this check + if storage.data_ptr() != 0: + if storage.data_ptr() in storage_dtypes: + if storage_dtype != storage_dtypes[storage.data_ptr()]: + raise RuntimeError( + "Cannot save multiple tensors or storages that " + "view the same data as different types" + ) + else: + storage_dtypes[storage.data_ptr()] = storage_dtype + + view_metadata: tuple[str, int, int] | None + + # Offset is always 0, but we keep it for backwards compatibility + # with the old serialization format (which supported storage views) + offset = 0 + storage_key = str(storage._cdata) + location = location_tag(storage) + + # TODO: There's an issue here with FC. It might be impossible to + # solve, but it's worth noting. Imagine we save a list `[storage, + # tensor]`, where `tensor.storage()` is the same as `storage`, and + # `tensor.element_size() > 1`. Let's say that `tensor.dtype == + # torch.float`. The storage will be serialized with element size + # of 1, since we're choosing to serialize the first occurrence of + # a duplicate storage. Since this legacy serialization format saves + # the numel of the storage, rather than nbytes directly, we'll be + # effectively saving nbytes in this case. We'll be able to load it + # and the tensor back up with no problems in _this_ and future + # versions of pytorch, but in older versions, here's the problem: + # the storage will be loaded up as a UntypedStorage, and then the + # FloatTensor will loaded and the UntypedStorage will be assigned to + # it. Since the storage dtype does not match the tensor dtype, this + # will cause an error. If we reverse the list, like `[tensor, + # storage]`, then we will save the `tensor.storage()` as a faked + # `FloatStorage`, and the saved size will be the correct + # dtype-specific numel count that old versions expect. `tensor` + # will be able to load up properly in old versions, pointing to + # a FloatStorage. However, `storage` is still being translated to + # a UntypedStorage, and it will try to resolve to the same + # FloatStorage that `tensor` contains. This will also cause an + # error. It doesn't seem like there's any way around this. + # Probably, we just cannot maintain FC for the legacy format if the + # saved list contains both a tensor and a storage that point to the + # same data. We should still be able to maintain FC for lists of + # just tensors, as long as all views share the same dtype as the + # tensor they are viewing. + + if storage_key not in serialized_storages: + serialized_storages[storage_key] = (storage, dtype) + is_view = storage._cdata != storage._cdata + if is_view: + view_metadata = (str(storage._cdata), offset, storage.nbytes()) + else: + view_metadata = None + + res = ( + "storage", + storage_type, + storage_key, + location, + storage_numel, + view_metadata, + ) + return res + return None + + sys_info = { + "protocol_version": PROTOCOL_VERSION, + "little_endian": sys.byteorder == "little", + "type_sizes": { + "short": SHORT_SIZE, + "int": INT_SIZE, + "long": LONG_SIZE, + }, + } + + pickle_module.dump(MAGIC_NUMBER, f, protocol=pickle_protocol) + pickle_module.dump(PROTOCOL_VERSION, f, protocol=pickle_protocol) + pickle_module.dump(sys_info, f, protocol=pickle_protocol) + + class PyTorchLegacyPickler(pickle_module.Pickler): + def persistent_id(self, obj): + return persistent_id(obj) # noqa: F821 + + pickler = PyTorchLegacyPickler(f, protocol=pickle_protocol) + pickler.dump(obj) + + # The class def keeps the persistent_id closure alive, leaking memory. + del persistent_id + + serialized_storage_keys = sorted(serialized_storages.keys()) + pickle_module.dump(serialized_storage_keys, f, protocol=pickle_protocol) + f.flush() + for key in serialized_storage_keys: + storage, dtype = serialized_storages[key] + storage._write_file( + f, _should_read_directly(f), True, torch._utils._element_size(dtype) + ) + + +def _save( + obj, + zip_file, + pickle_module, + pickle_protocol, + _disable_byteorder_record, +): + serialized_storages: dict[str, torch.storage.UntypedStorage] = {} + id_map: dict[int, str] = {} + + # Since loading storages that view the same data with different dtypes is + # not supported, we need to keep track of the dtype associated with each + # storage data_ptr and throw an error if the dtype is ever different. + # TODO: This feature could be added in the future + storage_dtypes: dict[int, torch.dtype] = {} + + def persistent_id(obj): + # FIXME: the docs say that persistent_id should only return a string + # but torch store returns tuples. This works only in the binary protocol + # see + # https://docs.python.org/2/library/pickle.html#pickling-and-unpickling-external-objects + # https://github.com/python/cpython/blob/master/Lib/pickle.py#L527-L537 + if isinstance(obj, torch.storage.TypedStorage) or torch.is_storage(obj): + if isinstance(obj, torch.storage.TypedStorage): + # TODO: Once we decide to break serialization FC, this case + # can be deleted + storage = obj._untyped_storage + storage_dtype = obj.dtype + storage_type_str = obj._pickle_storage_type() + storage_type = getattr(torch, storage_type_str) + storage_numel = obj._size() + + else: + storage = obj + storage_dtype = torch.uint8 + storage_type = normalize_storage_type(type(obj)) + storage_numel = storage.nbytes() + + # If storage is allocated, ensure that any other saved storages + # pointing to the same data all have the same dtype. If storage is + # not allocated, don't perform this check + if str(storage.device) != "meta" and storage.data_ptr() != 0: + if storage.data_ptr() in storage_dtypes: + if storage_dtype != storage_dtypes[storage.data_ptr()]: + raise RuntimeError( + "Cannot save multiple tensors or storages that " + "view the same data as different types" + ) + else: + storage_dtypes[storage.data_ptr()] = storage_dtype + + storage_key = id_map.setdefault(storage._cdata, str(len(id_map))) + if hasattr(obj, "_fake_device") and obj._fake_device is not None: + location = str(obj._fake_device) + else: + location = location_tag(storage) + serialized_storages[storage_key] = storage + + return ("storage", storage_type, storage_key, location, storage_numel) + + return None + + # Write the pickle data for `obj` + data_buf = io.BytesIO() + + class PyTorchPickler(pickle_module.Pickler): # type: ignore[name-defined] + def persistent_id(self, obj): + return persistent_id(obj) # noqa: F821 + + pickler = PyTorchPickler(data_buf, protocol=pickle_protocol) + pickler.dump(obj) + + # The class def keeps the persistent_id closure alive, leaking memory. + del persistent_id + + data_value = data_buf.getvalue() + zip_file.write_record("data.pkl", data_value, len(data_value)) + # .format_version is used to track + # 1. version 1 represents the order of storages being changed from + # lexicographical based on keys to numerically ordered based on keys + # 2. version 2 represents including storage_alignment as a record + # within the zipfile + zip_file.write_record(".format_version", "1", len("1")) + storage_alignment = str(_get_storage_alignment()) + zip_file.write_record( + ".storage_alignment", storage_alignment, len(storage_alignment) + ) + + # Write byte order marker + if not _disable_byteorder_record: + if sys.byteorder not in ["little", "big"]: + raise ValueError("Unknown endianness type: " + sys.byteorder) + + zip_file.write_record("byteorder", sys.byteorder, len(sys.byteorder)) + + # Write each tensor to a file named tensor/the_tensor_key in the zip archive + for key in serialized_storages: + name = f"data/{key}" + storage = serialized_storages[key] + num_bytes = storage.nbytes() + global _serialization_tls + if _serialization_tls.skip_data: + zip_file.write_record_metadata(name, num_bytes) + else: + # given that we copy things around anyway, we might use storage.cpu() + # this means to that to get tensors serialized, you need to implement + # .cpu() on the underlying Storage + if storage.device.type != "cpu": + from torch.utils.serialization import config + + if ( + config.save.use_pinned_memory_for_d2h + and ( + acc := torch.accelerator.current_accelerator( + check_available=True + ) + ) + is not None + and acc.type == storage.device.type + ): + new_storage = torch.empty( + num_bytes, dtype=torch.uint8, device="cpu", pin_memory=True + ).untyped_storage() + new_storage.copy_(storage) + torch.accelerator.current_stream(storage.device.index).synchronize() + storage = new_storage + else: + storage = storage.cpu() + # Now that it is on the CPU we can directly copy it into the zip file + zip_file.write_record(name, storage, num_bytes) + + +def load( + f: FileLike, + map_location: MAP_LOCATION = None, + pickle_module: Any = None, + *, + weights_only: bool | None = None, + mmap: bool | None = None, + **pickle_load_args: Any, +) -> Any: + # Reference: https://github.com/pytorch/pytorch/issues/54354 + # The first line of this docstring overrides the one Sphinx generates for the + # documentation. We need it so that Sphinx doesn't leak `pickle`s path from + # the build environment (e.g. `>> # xdoctest: +SKIP("undefined filepaths") + >>> torch.load("tensors.pt", weights_only=True) + # Load all tensors onto the CPU + >>> torch.load( + ... "tensors.pt", + ... map_location=torch.device("cpu"), + ... weights_only=True, + ... ) + # Load all tensors onto the CPU, using a function + >>> torch.load( + ... "tensors.pt", + ... map_location=lambda storage, loc: storage, + ... weights_only=True, + ... ) + # Load all tensors onto GPU 1 + >>> torch.load( + ... "tensors.pt", + ... map_location=lambda storage, loc: storage.cuda(1), # type: ignore[attr-defined] + ... weights_only=True, + ... ) # type: ignore[attr-defined] + # Map tensors from GPU 1 to GPU 0 + >>> torch.load( + ... "tensors.pt", + ... map_location={"cuda:1": "cuda:0"}, + ... weights_only=True, + ... ) + # Load tensor from io.BytesIO object + # Loading from a buffer setting weights_only=False, warning this can be unsafe + >>> with open("tensor.pt", "rb") as f: + ... buffer = io.BytesIO(f.read()) + >>> torch.load(buffer, weights_only=False) + # Load a module with 'ascii' encoding for unpickling + # Loading from a module setting weights_only=False, warning this can be unsafe + >>> torch.load("module.pt", encoding="ascii", weights_only=False) + """ + torch._C._log_api_usage_once("torch.load") + DOCS_MESSAGE = ( + "\n\nCheck the documentation of torch.load to learn more about types accepted by default with " + "weights_only https://pytorch.org/docs/stable/generated/torch.load.html." + ) + + def _get_wo_message(message: str) -> str: + unsafe_global_pattern = r"GLOBAL (\S+) was not an allowed global by default." + has_unsafe_global = re.search(unsafe_global_pattern, message) is not None + blocklist_pattern = r"whose module (\S+) is blocked" + has_blocklist = re.search(blocklist_pattern, message) is not None + import_pattern = r"(\S+) must be (\S+) to load" + has_import = re.search(import_pattern, message) is not None + if has_unsafe_global: + updated_message = ( + "Weights only load failed. This file can still be loaded, to do so you have two options, " + "\033[1mdo those steps only if you trust the source of the checkpoint\033[0m. " + f"\n\t(1) {UNSAFE_MESSAGE}\n\t(2) Alternatively, to load with `weights_only=True` please check " + "the recommended steps in the following error message.\n\tWeightsUnpickler error: " + + message + ) + else: + if has_import: + return f"Weights only load failed. {message}\n {UNSAFE_MESSAGE}\n" + else: + updated_message = f"Weights only load failed. {UNSAFE_MESSAGE}\n" + if not has_blocklist: + updated_message += ( + "Please file an issue with the following so that we can make " + "`weights_only=True` compatible with your use case: WeightsUnpickler error: " + ) + updated_message += "\n\n" + message + return updated_message + DOCS_MESSAGE + + weights_only_not_set = weights_only is None + + if weights_only_not_set: + weights_only = _default_to_weights_only(pickle_module) + + true_values = ["1", "y", "yes", "true"] + # Add ability to force safe only or non-safe weight loads via environment variables + force_weights_only_load = ( + os.getenv("TORCH_FORCE_WEIGHTS_ONLY_LOAD", "0") in true_values + ) + force_no_weights_only_load = ( + os.getenv("TORCH_FORCE_NO_WEIGHTS_ONLY_LOAD", "0") in true_values + ) + + if force_weights_only_load and force_no_weights_only_load: + raise RuntimeError( + "Only one of `TORCH_FORCE_WEIGHTS_ONLY_LOAD` or `TORCH_FORCE_NO_WEIGHTS_ONLY_LOAD` " + "should be set, but both were set." + ) + elif force_weights_only_load: + weights_only = True + elif force_no_weights_only_load: + # TORCH_FORCE_NO_WEIGHTS_ONLY_LOAD can only override if callsite did not explicitly set weights_only + if weights_only_not_set: + warnings.warn( + "Environment variable TORCH_FORCE_NO_WEIGHTS_ONLY_LOAD detected, since the" + "`weights_only` argument was not explicitly passed to `torch.load`, forcing weights_only=False.", + UserWarning, + stacklevel=2, + ) + weights_only = False + + if weights_only: + if pickle_module is not None: + raise RuntimeError( + "Can not safely load weights when explicit pickle_module is specified" + ) + else: + if pickle_module is None: + pickle_module = pickle + + # make flipping default BC-compatible + if mmap is None: + from torch.utils.serialization import config + + mmap = config.load.mmap + + _check_dill_version(pickle_module) + + if "encoding" not in pickle_load_args: + pickle_load_args["encoding"] = "utf-8" + + with _open_file_like(f, "rb") as opened_file: + if _is_zipfile(opened_file): + # The zipfile reader is going to advance the current file position. + # If we want to actually tail call to torch.jit.load, we need to + # reset back to the original position. + orig_position = opened_file.tell() + overall_storage = None + with _open_zipfile_reader(opened_file) as opened_zipfile: + if _is_torchscript_zip(opened_zipfile): + warnings.warn( + "'torch.load' received a zip file that looks like a TorchScript archive" + " dispatching to 'torch.jit.load' (call 'torch.jit.load' directly to" + " silence this warning)", + UserWarning, + stacklevel=2, + ) + if weights_only: + raise RuntimeError( + "Cannot use ``weights_only=True`` with TorchScript archives passed to " + "``torch.load``. " + UNSAFE_MESSAGE + ) + opened_file.seek(orig_position) + return torch.jit.load(opened_file, map_location=map_location) + if mmap: + if not _is_path(f): + raise ValueError( + "f must be a file path in order to use the mmap argument" + ) + size = os.path.getsize(f) + if not IS_WINDOWS: + shared = get_default_mmap_options() == MAP_SHARED + else: + shared = False + overall_storage = torch.UntypedStorage.from_file( + os.fspath(f), + shared, + size, + ) + if weights_only: + try: + return _load( + opened_zipfile, + map_location, + _weights_only_unpickler, + overall_storage=overall_storage, + **pickle_load_args, + ) + except pickle.UnpicklingError as e: + raise pickle.UnpicklingError(_get_wo_message(str(e))) from None + return _load( + opened_zipfile, + map_location, + pickle_module, + overall_storage=overall_storage, + **pickle_load_args, + ) + if mmap: + f_name = "" if not isinstance(f, str) else f"{f}, " + raise RuntimeError( + "mmap can only be used with files saved with " + f"`torch.save({f_name}_use_new_zipfile_serialization=True), " + "please torch.save your checkpoint with this option in order to use mmap." + ) + if weights_only: + try: + return _legacy_load( + opened_file, + map_location, + _weights_only_unpickler, + **pickle_load_args, + ) + except pickle.UnpicklingError as e: + raise pickle.UnpicklingError(_get_wo_message(str(e))) from None + return _legacy_load( + opened_file, map_location, pickle_module, **pickle_load_args + ) + + +# Register pickling support for layout instances such as +# torch.sparse_coo, etc +def _get_layout(name): + """Get layout extension object from its string representation.""" + cache = _get_layout.cache # type: ignore[attr-defined] + if not cache: + for v in torch.__dict__.values(): + if isinstance(v, torch.layout): + cache[str(v)] = v + return cache[name] + + +# There are yet not good way to type annotate function attributes https://github.com/python/mypy/issues/2087 +_get_layout.cache = {} # type: ignore[attr-defined] +copyreg.pickle(torch.layout, lambda obj: (_get_layout, (str(obj),))) + + +def _legacy_load(f, map_location, pickle_module, **pickle_load_args): + deserialized_objects: dict[int, Any] = {} + + restore_location = _get_restore_location(map_location) + + class UnpicklerWrapper(pickle_module.Unpickler): # type: ignore[name-defined] + def find_class(self, mod_name, name): + if type(name) is str and "Storage" in name: + try: + return StorageType(name) + except KeyError: + pass + return super().find_class(mod_name, name) + + def _check_container_source(container_type, source_file, original_source): + try: + current_source = "".join(get_source_lines_and_file(container_type)[0]) + except Exception: # saving the source is optional, so we can ignore any errors + warnings.warn( + "Couldn't retrieve source code for container of " + "type " + container_type.__name__ + ". It won't be checked " + "for correctness upon loading.", + stacklevel=2, + ) + return + if original_source != current_source: + if container_type.dump_patches: + file_name = container_type.__name__ + ".patch" + diff = difflib.unified_diff( + current_source.split("\n"), + original_source.split("\n"), + source_file, + source_file, + lineterm="", + ) + lines = "\n".join(diff) + try: + with open(file_name, "a+") as f: + file_size = f.seek(0, 2) + f.seek(0) + if file_size == 0: + f.write(lines) + elif file_size != len(lines) or f.read() != lines: + raise OSError + msg = ( + "Saved a reverse patch to " + file_name + ". " + "Run `patch -p0 < " + file_name + "` to revert your " + "changes." + ) + except OSError: + msg = ( + "Tried to save a patch, but couldn't create a " + "writable file " + file_name + ". Make sure it " + "doesn't exist and your working directory is " + "writable." + ) + else: + msg = ( + "you can retrieve the original source code by " + "accessing the object's source attribute or set " + "`torch.nn.Module.dump_patches = True` and use the " + "patch tool to revert the changes." + ) + msg = f"source code of class '{torch.typename(container_type)}' has changed. {msg}" + warnings.warn(msg, SourceChangeWarning, stacklevel=2) + + def legacy_load(f): + deserialized_objects: dict[int, Any] = {} + + def persistent_load(saved_id): + if isinstance(saved_id, tuple): + # Ignore containers that don't have any sources saved + if all(saved_id[1:]): + _check_container_source(*saved_id) + return saved_id[0] + return deserialized_objects[int(saved_id)] + + with ( + closing( + tarfile.open(fileobj=f, mode="r:", format=tarfile.PAX_FORMAT) + ) as tar, + mkdtemp() as tmpdir, + ): + if pickle_module is _weights_only_unpickler: + raise RuntimeError( + "Cannot use ``weights_only=True`` with files saved in the " + "legacy .tar format. " + UNSAFE_MESSAGE + ) + tar.extract("storages", path=tmpdir) + with open(os.path.join(tmpdir, "storages"), "rb", 0) as f: + num_storages = pickle_module.load(f, **pickle_load_args) + for _ in range(num_storages): + args = pickle_module.load(f, **pickle_load_args) + key, location, storage_type = args + dtype = storage_type._dtype + obj = cast(Storage, torch.UntypedStorage)._new_with_file( + f, torch._utils._element_size(dtype) + ) + obj = restore_location(obj, location) + # TODO: Once we decide to break serialization FC, we can + # stop wrapping with TypedStorage + deserialized_objects[key] = torch.storage.TypedStorage( + wrap_storage=obj, dtype=dtype, _internal=True + ) + + storage_views = pickle_module.load(f, **pickle_load_args) + for target_cdata, root_cdata, offset, numel in storage_views: + root = deserialized_objects[root_cdata] + element_size = torch._utils._element_size(root.dtype) + offset_bytes = offset * element_size + # TODO: Once we decide to break serialization FC, we can + # stop wrapping with TypedStorage + deserialized_objects[target_cdata] = torch.storage.TypedStorage( + wrap_storage=root._untyped_storage[ + offset_bytes : offset_bytes + numel * element_size + ], + dtype=root.dtype, + _internal=True, + ) + + tar.extract("tensors", path=tmpdir) + with open(os.path.join(tmpdir, "tensors"), "rb", 0) as f: + num_tensors = pickle_module.load(f, **pickle_load_args) + for _ in range(num_tensors): + args = pickle_module.load(f, **pickle_load_args) + key, storage_id, _original_tensor_type = args + storage = deserialized_objects[storage_id] + (ndim,) = struct.unpack(" str: + # When using encoding='bytes' in Py3, some **internal** keys stored as + # strings in Py2 are loaded as bytes. This function decodes them with + # ascii encoding, one that Py3 uses by default. + # + # NOTE: This should only be used on internal keys (e.g., `typename` and + # `location` in `persistent_load` below! + if isinstance(bytes_str, bytes): + return bytes_str.decode("ascii") + return bytes_str + + +def _get_restore_location(map_location): + if map_location is None: + restore_location = default_restore_location + elif isinstance(map_location, dict): + + def restore_location(storage, location): + location = map_location.get(location, location) + return default_restore_location(storage, location) + + elif isinstance(map_location, (str, bytes)): + + def restore_location(storage, location): + return default_restore_location(storage, map_location) + + elif isinstance(map_location, torch.device): + + def restore_location(storage, location): + return default_restore_location(storage, str(map_location)) + + else: + + def restore_location(storage, location): + result = map_location(storage, location) + if result is None: + result = default_restore_location(storage, location) + return result + + return restore_location + + +class StorageType: + def __init__(self, name): + self._dtype = _get_dtype_from_pickle_storage_type(name) + + @property + def dtype(self): + return self._dtype + + def __str__(self): + return f"StorageType(dtype={self.dtype})" + + +def _load( + zip_file, + map_location, + pickle_module, + pickle_file="data.pkl", + overall_storage=None, + **pickle_load_args, +): + restore_location = _get_restore_location(map_location) + + loaded_storages = {} + + can_calculate_storage_offsets = False + if zip_file.has_record(".format_version"): + version = zip_file.get_record(".format_version") + can_calculate_storage_offsets = version >= b"1" + + # check if byteswapping is needed + byteordername = "byteorder" + byteorderdata = None + if zip_file.has_record(byteordername): + byteorderdata = zip_file.get_record(byteordername) + if byteorderdata not in [b"little", b"big"]: + raise ValueError("Unknown endianness type: " + byteorderdata.decode()) + elif ( + get_default_load_endianness() == LoadEndianness.LITTLE + or get_default_load_endianness() is None + ): + byteorderdata = b"little" + elif get_default_load_endianness() == LoadEndianness.BIG: + byteorderdata = b"big" + elif get_default_load_endianness() == LoadEndianness.NATIVE: + pass + else: + raise ValueError("Invalid load endianness type") + + storage_alignment = 64 + if zip_file.has_record(".storage_alignment"): + storage_alignment = int(zip_file.get_record(".storage_alignment")) + + if ( + not zip_file.has_record(byteordername) + and get_default_load_endianness() is None + and sys.byteorder == "big" + ): + # Default behaviour was changed + # See https://github.com/pytorch/pytorch/issues/101688 + warnings.warn( + "The default load endianness for checkpoints without a byteorder mark " + "on big endian machines was changed from 'native' to 'little' endian, " + "to avoid this behavior please use " + "torch.serialization.set_default_load_endianness to set " + "the desired default load endianness", + UserWarning, + stacklevel=2, + ) + + from torch.utils.serialization import config + + calculate_storage_offsets = config.load.calculate_storage_offsets + run_debug_asserts = os.environ.get("TORCH_SERIALIZATION_DEBUG", "0") == "1" + current_offset = None + # constants from miniz.h/miniz.c + data_descripter_size64 = 24 + data_descripter_size32 = 16 + mz_uint32_max = 0xFFFFFFFF + offsets: dict[str, int] = dict() + + def _get_offset(key, name, numel): + """ + Return the offset of the storage associated with key with record name `name` and size numel. + It is expected that the zipfile header of this storage starts at current_offset. + + WARNING: This function relies on the behavior of the zipwriter in miniz.c. In particular, + the behavior of `mz_zip_writer_add_mem_ex_v2`. The behavior of this function must be kept + in sync with that of miniz! + + After reading a storage of size numel that starts at storage_offset + if it is the first time that storage was read, update nonlocal variable + current_offset to the start of the next zipfile header by incrementing + it by numel and the data descriptor size. + """ + nonlocal current_offset, offsets + if name in offsets: + storage_offset = offsets[name] + return storage_offset + + if current_offset is None: + assert key == "0" + current_offset = zip_file.get_record_offset(name) + local_header_offset = zip_file.get_record_header_offset(name) + storage_offset = current_offset + else: + storage_offset = zip_file.get_record_offset_no_read( + current_offset, name, numel, storage_alignment + ) + local_header_offset = current_offset + + # This is only actually needed for storages that have typed_storage._data_ptr() == 0 + # after being read. Otherwise persistent_load would never "re-call" load_tensor + # for a given key. + offsets[name] = storage_offset + + # Increment current_offset to offset where next zipfile header starts + current_offset = storage_offset + numel + # add size of data descriptor after payload + if numel > 0: + if local_header_offset >= mz_uint32_max or numel >= mz_uint32_max: + current_offset += data_descripter_size64 + else: + current_offset += data_descripter_size32 + + return storage_offset + + def load_tensor(dtype, numel, key, location): + name = f"data/{key}" + if torch._guards.detect_fake_mode(None) is not None: + nbytes = numel * torch._utils._element_size(dtype) + storage = torch.UntypedStorage(nbytes, device="meta") + if can_calculate_storage_offsets: + storage._checkpoint_offset = _get_offset(key, name, numel) + else: + storage._checkpoint_offset = zip_file.get_record_offset(name) + elif _serialization_tls.skip_data: + nbytes = numel * torch._utils._element_size(dtype) + storage = torch.UntypedStorage(nbytes) + elif overall_storage is not None: + if can_calculate_storage_offsets and calculate_storage_offsets: + storage_offset = _get_offset(key, name, numel) + if run_debug_asserts: + if storage_offset != zip_file.get_record_offset(name): + raise RuntimeError( + "This is a debug assert that was run as the `TORCH_SERIALIZATION_DEBUG` environment " + f"variable was set: Incorrect offset for {name}, got {storage_offset} expected " + f"{zip_file.get_record_offset(name)}" + ) + else: + storage_offset = zip_file.get_record_offset(name) + storage = overall_storage[storage_offset : storage_offset + numel] + else: + if can_calculate_storage_offsets and run_debug_asserts: + # This is debug code that we use to test the validity of + # torch.utils.serialization.config.load.calculate_storage_offsets throughout CI + storage_offset = _get_offset(key, name, numel) + if storage_offset != zip_file.get_record_offset(name): + raise RuntimeError( + "This is a debug assert that was run as the `TORCH_SERIALIZATION_DEBUG` environment " + f"variable was set: Incorrect offset for {name}, got {storage_offset} expected " + f"{zip_file.get_record_offset(name)}" + ) + storage = ( + zip_file.get_storage_from_record(name, numel, torch.UntypedStorage) + ._typed_storage() + ._untyped_storage + ) + # swap here if byteswapping is needed + if byteorderdata is not None: + if byteorderdata.decode() != sys.byteorder: + storage.byteswap(dtype) + + # TODO: Once we decide to break serialization FC, we can + # stop wrapping with TypedStorage + + if torch._guards.detect_fake_mode(None) is None: + wrap_storage = restore_location(storage, location) + else: + storage._fake_device = location + wrap_storage = storage + + typed_storage = torch.storage.TypedStorage( + wrap_storage=wrap_storage, + dtype=dtype, + _internal=True, + ) + + if typed_storage._data_ptr() != 0: + loaded_storages[key] = typed_storage + + return typed_storage + + def persistent_load(saved_id): + assert isinstance(saved_id, tuple) + typename = _maybe_decode_ascii(saved_id[0]) + data = saved_id[1:] + + assert typename == "storage", ( + f"Unknown typename for persistent_load, expected 'storage' but got '{typename}'" + ) + storage_type, key, location, numel = data + if storage_type is torch.UntypedStorage: + dtype = torch.uint8 + else: + dtype = storage_type.dtype + + if key in loaded_storages: + typed_storage = loaded_storages[key] + else: + nbytes = numel * torch._utils._element_size(dtype) + typed_storage = load_tensor( + dtype, nbytes, key, _maybe_decode_ascii(location) + ) + + return typed_storage + + load_module_mapping: dict[str, str] = { + # See https://github.com/pytorch/pytorch/pull/51633 + "torch.tensor": "torch._tensor" + } + + # Need to subclass Unpickler instead of directly monkey-patching the find_class method + # because it's marked readonly in pickle. + # The type: ignore is because mypy can't statically determine the type of this class. + class UnpicklerWrapper(pickle_module.Unpickler): # type: ignore[name-defined] + # from https://stackoverflow.com/questions/13398462/unpickling-python-objects-with-a-changed-module-path/13405732 + # Lets us override the imports that pickle uses when unpickling an object. + # This is useful for maintaining BC if we change a module path that tensor instantiation relies on. + def find_class(self, mod_name, name): + if type(name) is str and "Storage" in name: + try: + return StorageType(name) + except KeyError: + pass + mod_name = load_module_mapping.get(mod_name, mod_name) + return super().find_class(mod_name, name) + + # Load the data (which may in turn use `persistent_load` to load tensors) + data_file = io.BytesIO(zip_file.get_record(pickle_file)) + + unpickler = UnpicklerWrapper(data_file, **pickle_load_args) + unpickler.persistent_load = persistent_load + # Needed for tensors where storage device and rebuild tensor device are + # not connected (wrapper subclasses and tensors rebuilt using numpy) + global _serialization_tls + _serialization_tls.map_location = map_location + result = unpickler.load() + _serialization_tls.map_location = None + + torch._utils._validate_loaded_sparse_tensors() + torch._C._log_api_usage_metadata( + "torch.load.metadata", {"serialization_id": zip_file.serialization_id()} + ) + return result + + +def _is_torchscript_zip(zip_file): + return "constants.pkl" in zip_file.get_all_records() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/storage.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/storage.py new file mode 100644 index 0000000000000000000000000000000000000000..29847d958523ddee2db004e4d6d02b0d2487fcb8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/storage.py @@ -0,0 +1,1549 @@ +# mypy: allow-untyped-defs + +from __future__ import annotations + +import collections +import copy +import functools +import io +import threading +import warnings +from typing import Any, cast, TYPE_CHECKING, TypeVar +from typing_extensions import Self + +import torch +from torch._utils import _to, _type +from torch.types import _bool, _int, Storage + + +if TYPE_CHECKING: + from torch._prims_common import DeviceLikeType + + +__all__ = ["TypedStorage", "UntypedStorage"] + + +try: + import numpy as np + + HAS_NUMPY = True +except ModuleNotFoundError: + HAS_NUMPY = False + np = None # type: ignore[assignment] + + +_share_memory_lock = threading.Lock() +_share_memory_map: dict[int, threading.RLock] = {} + +T = TypeVar("T", bound="_StorageBase | TypedStorage") + + +class _StorageBase: + _cdata: Any + is_sparse: _bool = False + is_sparse_csr: _bool = False + device: torch.device + # Used when + # (1) stashing FakeTensor device onto storage in torch.serialization.skip_data + # (2) stashing device onto storage to propagate to FakeTensor when torch.load under FakeTensorMode + _fake_device: torch.device | None = None + # Used when loading with FakeTensorMode to give information about offset of storage in torch.saved-file + _checkpoint_offset: int | None = None + + def __init__(self, *args, **kwargs): + pass + + def __len__(self) -> _int: + raise NotImplementedError + + def __getitem__(self, idx): + raise NotImplementedError + + def __setitem__(self, *args, **kwargs): + raise NotImplementedError + + def copy_(self, source: T, non_blocking: _bool | None = None) -> T: + raise NotImplementedError + + def new(self) -> _StorageBase | TypedStorage: + raise NotImplementedError + + def nbytes(self) -> _int: + raise NotImplementedError + + def size(self) -> _int: + return self.nbytes() + + def type( + self, dtype: str | None = None, non_blocking: _bool = False + ) -> _StorageBase | TypedStorage: + return _type(self, dtype, non_blocking) + + def cuda(self, device=None, non_blocking=False) -> _StorageBase | TypedStorage: + """Returns a copy of this object in CUDA memory. + + If this object is already in CUDA memory and on the correct device, then + no copy is performed and the original object is returned. + + Args: + device (int): The destination GPU id. Defaults to the current device. + non_blocking (bool): If ``True`` and the source is in pinned memory, + the copy will be asynchronous with respect to the host. Otherwise, + the argument has no effect. + """ + device2 = torch.device("cuda", device) if device else torch.device("cuda") + return self.to(device=device2, non_blocking=non_blocking) + + def hpu(self, device=None, non_blocking=False) -> _StorageBase | TypedStorage: + """Returns a copy of this object in HPU memory. + + If this object is already in HPU memory and on the correct device, then + no copy is performed and the original object is returned. + + Args: + device (int): The destination HPU id. Defaults to the current device. + non_blocking (bool): If ``True`` and the source is in pinned memory, + the copy will be asynchronous with respect to the host. Otherwise, + the argument has no effect. + """ + device2 = torch.device("hpu", device) if device else torch.device("hpu") + return self.to(device=device2, non_blocking=non_blocking) + + def element_size(self) -> _int: + raise NotImplementedError + + def get_device(self) -> _int: + return self.device.index + + def data_ptr(self) -> _int: + raise NotImplementedError + + def resizable(self) -> _bool: + raise NotImplementedError + + # Defined in torch/csrc/generic/StorageSharing.cpp + def _share_filename_cpu_(self, *args, **kwargs): + raise NotImplementedError + + def _share_fd_cpu_(self, *args, **kwargs): + raise NotImplementedError + + @classmethod + def _new_using_filename_cpu(cls, size: _int) -> Self: + raise NotImplementedError + + @classmethod + def _new_using_fd_cpu(cls, size: _int) -> Self: + raise NotImplementedError + + @classmethod + def from_buffer(cls, *args, **kwargs) -> Self: + raise NotImplementedError + + @classmethod + def _new_shared_filename_cpu( + cls, + manager, + obj, + size, + *, + device=None, + dtype=None, + ) -> Self: + raise NotImplementedError + + @classmethod + def _release_ipc_counter(cls, *args, device=None, **kwargs): + return cls._release_ipc_counter_cuda(*args, **kwargs) + + @classmethod + def _release_ipc_counter_cuda(cls, *args, **kwargs) -> Self: + raise NotImplementedError + + @classmethod + def _new_with_weak_ptr(cls, *args, **kwargs) -> Self: + raise NotImplementedError + + def _shared_decref(self) -> _StorageBase | TypedStorage: + raise NotImplementedError + + def _write_file(self, *args, **kwargs): + raise NotImplementedError + + def resize_(self, size: _int): + raise NotImplementedError + + def _weak_ref(self, *args, **kwargs) -> _StorageBase | TypedStorage: + raise NotImplementedError + + def _set_from_file(self, *args, **kwargs): + raise NotImplementedError + + def _set_cdata(self, *args, **kwargs): + raise NotImplementedError + + def _share_cuda_(self, *args, **kwargs): + raise NotImplementedError + + def is_shared(self) -> _bool: + raise NotImplementedError + + @classmethod + def _new_shared_cuda(cls, *args, **kwargs) -> Self: + raise NotImplementedError + + def _shared_incref(self, *args, **kwargs): + raise NotImplementedError + + @classmethod + def _free_weak_ref(cls, *args, **kwargs): + raise NotImplementedError + + @property + def is_cuda(self): + raise NotImplementedError + + @property + def is_hpu(self): + raise NotImplementedError + + @classmethod + def from_file(cls, filename, shared, nbytes) -> _StorageBase | TypedStorage: + raise NotImplementedError + + @classmethod + def _expired(cls, *args, **kwargs) -> _StorageBase | TypedStorage: + raise NotImplementedError + + def _byteswap(self, *args, **kwargs): + raise NotImplementedError + + def _get_filename(self, *args, **kwargs) -> str | None: + raise NotImplementedError + + def __repr__(self): + info_str = f"[{torch.typename(self)}(device={self.device}) of size {len(self)}]" + if self.device.type == "meta": + return "...\n" + info_str + data_str = " " + "\n ".join(str(self[i]) for i in range(self.size())) + return data_str + "\n" + info_str + + def __iter__(self): + return iter(self[i] for i in range(self.size())) + + def __copy__(self): + return self.clone() + + def __deepcopy__(self, memo): + memo = memo.setdefault("torch", {}) + if self._cdata in memo: + return memo[self._cdata] + new_storage = self.clone() + memo[self._cdata] = new_storage + return new_storage + + def __reduce__(self): + b = io.BytesIO() + torch.save(self, b, _use_new_zipfile_serialization=False) + return (_load_from_bytes, (b.getvalue(),)) + + def __sizeof__(self): + return super().__sizeof__() + self.size() + + def clone(self): + """Return a copy of this storage.""" + return type(self)(self.nbytes(), device=self.device).copy_(self) + + def tolist(self): + """Return a list containing the elements of this storage.""" + return list(self) + + def cpu(self): + """Return a CPU copy of this storage if it's not already on the CPU.""" + if self.device.type != "cpu": + return torch.UntypedStorage(self.size()).copy_(self, False) + return self + + def mps(self): + """Return a MPS copy of this storage if it's not already on the MPS.""" + if self.device.type != "mps": + return torch.UntypedStorage(self.size(), device="mps").copy_(self, False) + return self + + def _to(self, dtype): + if not isinstance(dtype, torch.dtype): + raise TypeError(f"Argument 'dtype' must be torch.dtype, not {type(dtype)}") + storage = ( + torch.tensor([], dtype=torch.uint8, device=self.device) + .set_(cast(Storage, self)) + .to(dtype) + ._typed_storage() + ) + if storage.data_ptr() == self.data_ptr(): + storage = storage.clone() + return storage + + def to(self, *, device: DeviceLikeType, non_blocking: _bool = False): + if not isinstance(device, torch.device): + device = torch.device(device) + return _to(self, device, non_blocking) + + def double(self): + """Casts this storage to double type.""" + return self._to(torch.double) + + def float(self): + """Casts this storage to float type.""" + return self._to(torch.float) + + def half(self): + """Casts this storage to half type.""" + return self._to(torch.half) + + def long(self): + """Casts this storage to long type.""" + return self._to(torch.long) + + def int(self): + """Casts this storage to int type.""" + return self._to(torch.int) + + def short(self): + """Casts this storage to short type.""" + return self._to(torch.short) + + def char(self): + """Casts this storage to char type.""" + return self._to(torch.int8) + + def byte(self): + """Casts this storage to byte type.""" + return self._to(torch.uint8) + + def bool(self): + """Casts this storage to bool type.""" + return self._to(torch.bool) + + def bfloat16(self): + """Casts this storage to bfloat16 type.""" + return self._to(torch.bfloat16) + + def complex_double(self): + """Casts this storage to complex double type.""" + return self._to(torch.cdouble) + + def complex_float(self): + """Casts this storage to complex float type.""" + return self._to(torch.cfloat) + + def float8_e5m2(self): + """Casts this storage to float8_e5m2 type""" + return self._to(torch.float8_e5m2) + + def float8_e4m3fn(self): + """Casts this storage to float8_e4m3fn type""" + return self._to(torch.float8_e4m3fn) + + def float8_e5m2fnuz(self): + """Casts this storage to float8_e5m2fnuz type""" + return self._to(torch.float8_e5m2fnuz) + + def float8_e4m3fnuz(self): + """Casts this storage to float8_e4m3fnuz type""" + return self._to(torch.float8_e4m3fnuz) + + def is_pinned(self, device: str | torch.device = "cuda"): + r"""Determine whether the CPU storage is already pinned on device. + + Args: + device (str or torch.device): The device to pin memory on (default: ``'cuda'``). + This argument is discouraged and subject to deprecated. + + Returns: + A boolean variable. + """ + return ( + torch.tensor([], dtype=torch.uint8, device=self.device) + .set_(cast(Storage, self)) + .is_pinned(device) + ) + + def pin_memory(self, device: str | torch.device = "cuda"): + r"""Copy the CPU storage to pinned memory, if it's not already pinned. + + Args: + device (str or torch.device): The device to pin memory on (default: ``'cuda'``). + This argument is discouraged and subject to deprecated. + + Returns: + A pinned CPU storage. + """ + if self.device.type != "cpu": + raise TypeError(f"cannot pin '{self.type()}' only CPU memory can be pinned") + + pinned_tensor = ( + torch.tensor([], dtype=torch.uint8, device=self.device) + .set_(cast(Storage, self)) + .pin_memory(device) + ) + return pinned_tensor.untyped_storage() + + def share_memory_(self): + """See :meth:`torch.UntypedStorage.share_memory_`""" + from torch.multiprocessing import get_sharing_strategy + + if self.device.type in ["cuda", torch._C._get_privateuse1_backend_name()]: + pass # CUDA or PrivateUse1 doesn't use POSIX shared memory + elif get_sharing_strategy() == "file_system": + self._share_filename_cpu_() + else: + self._share_fd_cpu_() + return self + + @classmethod + def _new_shared(cls, size, *, device="cpu"): + """Create a new storage in shared memory with the same data type.""" + from torch.multiprocessing import get_sharing_strategy + + device = torch.device(device) + if device.type in ["cuda", torch._C._get_privateuse1_backend_name(), "hpu"]: + return cls(size, device=device) + elif get_sharing_strategy() == "file_system": + return cls._new_using_filename_cpu(size) + else: + return cls._new_using_fd_cpu(size) + + def untyped(self): + return self + + def byteswap(self, dtype): + """Swap bytes in underlying data.""" + elem_size = torch._utils._element_size(dtype) + # for complex types, don't swap first and second numbers + if dtype.is_complex: + elem_size = max(int(elem_size / 2), 1) + self._byteswap(elem_size) + + +def _share_memory_lock_protected(fn): + @functools.wraps(fn) + def wrapper(self, *args, **kwargs): + to_free = None + to_wait = None + with _share_memory_lock: + key = self._cdata + if key in _share_memory_map: + to_wait = _share_memory_map[key] + else: + _share_memory_map[key] = threading.RLock() + _share_memory_map[key].acquire() + to_free = key + + # If we're already in the process of sharing the storage, wait + # for it to be done. + if to_wait is not None: + with to_wait: + pass + + try: + return fn(self, *args, **kwargs) + finally: + # If we acquired the storage lock here and we're done working on it + # we can now release it and free the entry. + if to_free is not None: + # Ensure that the cdata from the storage didn't change and only + # the data_ptr did. + assert self._cdata == to_free + with _share_memory_lock: + _share_memory_map[to_free].release() + del _share_memory_map[to_free] + + return wrapper + + +class UntypedStorage(torch._C.StorageBase, _StorageBase): + def __getitem__(self, *args, **kwargs): + if self.device.type == "meta": + raise NotImplementedError("Not available for 'meta' device type") + return super().__getitem__(*args, **kwargs) + + @property + def is_cuda(self): + return self.device.type == "cuda" + + @property + def is_hpu(self): + return self.device.type == "hpu" + + @property + def filename(self) -> str | None: + """Returns the file name associated with this storage. + + The file name will be a string if the storage is on CPU and was created via + :meth:`~torch.from_file()` with ``shared`` as ``True``. This attribute is ``None`` otherwise. + """ + return self._get_filename() + + @_share_memory_lock_protected + def share_memory_(self, *args, **kwargs): + """ + Moves the storage to shared memory. + + This is a no-op for storages already in shared memory and for CUDA + storages, which do not need to be moved for sharing across processes. + Storages in shared memory cannot be resized. + + Note that to mitigate issues like `this `_ + it is thread safe to call this function from multiple threads on the same object. + It is NOT thread safe though to call any other function on self without proper + synchronization. Please see :doc:`/notes/multiprocessing` for more details. + + .. note:: + When all references to a storage in shared memory are deleted, the associated shared memory + object will also be deleted. PyTorch has a special cleanup process to ensure that this happens + even if the current process exits unexpectedly. + + It is worth noting the difference between :meth:`share_memory_` and :meth:`from_file` with ``shared = True`` + + #. ``share_memory_`` uses `shm_open(3) `_ to create a + POSIX shared memory object while :meth:`from_file` uses + `open(2) `_ to open the filename passed by the user. + #. Both use an `mmap(2) call `_ with ``MAP_SHARED`` + to map the file/object into the current virtual address space + #. ``share_memory_`` will call ``shm_unlink(3)`` on the object after mapping it to make sure the shared memory + object is freed when no process has the object open. ``torch.from_file(shared=True)`` does not unlink the + file. This file is persistent and will remain until it is deleted by the user. + + Returns: + ``self`` + """ + return super().share_memory_(*args, **kwargs) + + @_share_memory_lock_protected + def _share_fd_cpu_(self, *args, **kwargs): + return super()._share_fd_cpu_(*args, **kwargs) + + @_share_memory_lock_protected + def _share_filename_cpu_(self, *args, **kwargs): + return super()._share_filename_cpu_(*args, **kwargs) + + +def _load_from_bytes(b): + return torch.load(io.BytesIO(b), weights_only=False) + + +@functools.cache +def _new_dtypes(): + # These are dtypes serialized as UntypedStorage unlike those in + # _dtype_to_storage_type_map + return { + torch.float8_e5m2, + torch.float8_e4m3fn, + torch.float8_e5m2fnuz, + torch.float8_e4m3fnuz, + torch.float8_e8m0fnu, + torch.float4_e2m1fn_x2, + torch.bits8, + torch.bits16, + torch.bits1x8, + torch.bits2x4, + torch.bits4x2, + torch.complex32, + torch.uint16, + torch.uint32, + torch.uint64, + } + + +@functools.cache +def _dtype_to_storage_type_map(): + # NOTE: We should no longer add dtypes to this map. This map + # is only used for BC/FC with older PyTorch versions. Going forward, + # new dtypes of TypedStorage should not translate to a legacy + # Storage class. Instead, new dtypes of TypedStorage should + # be serialized as an UntypedStorage paired with a torch.dtype + return { + torch.double: "DoubleStorage", + torch.float: "FloatStorage", + torch.half: "HalfStorage", + torch.long: "LongStorage", + torch.int: "IntStorage", + torch.int16: "ShortStorage", + torch.int8: "CharStorage", + torch.uint8: "ByteStorage", + torch.bool: "BoolStorage", + torch.bfloat16: "BFloat16Storage", + torch.cdouble: "ComplexDoubleStorage", + torch.cfloat: "ComplexFloatStorage", + torch.qint8: "QInt8Storage", + torch.qint32: "QInt32Storage", + torch.quint8: "QUInt8Storage", + torch.quint4x2: "QUInt4x2Storage", + torch.quint2x4: "QUInt2x4Storage", + } + + +@functools.cache +def _storage_type_to_dtype_map(): + dtype_map = {val: key for key, val in _dtype_to_storage_type_map().items()} + return dtype_map + + +def _get_storage_from_sequence(sequence, dtype, device): + if dtype in [ + torch.quint8, + torch.quint4x2, + torch.quint2x4, + torch.qint32, + torch.qint8, + ]: + interpret_dtypes = { + torch.quint8: torch.uint8, + torch.quint4x2: torch.uint8, + torch.quint2x4: torch.uint8, + torch.qint32: torch.int32, + torch.qint8: torch.int8, + } + tmp_tensor = torch.tensor( + sequence, dtype=interpret_dtypes[dtype], device=device + ) + + else: + tmp_tensor = torch.tensor(sequence, dtype=dtype, device=device) + + return tmp_tensor._typed_storage()._untyped_storage + + +def _isint(x): + if HAS_NUMPY: + return isinstance(x, (int, np.integer)) # pyrefly: ignore [missing-attribute] + else: + return isinstance(x, int) + + +_always_warn_typed_storage_removal = False + + +def _get_always_warn_typed_storage_removal(): + return _always_warn_typed_storage_removal + + +def _set_always_warn_typed_storage_removal(always_warn): + global _always_warn_typed_storage_removal + assert isinstance(always_warn, bool) + _always_warn_typed_storage_removal = always_warn + + +def _warn_typed_storage_removal(stacklevel=2): + global _always_warn_typed_storage_removal + + def is_first_time(): + if not hasattr(_warn_typed_storage_removal, "has_warned"): + return True + else: + return not _warn_typed_storage_removal.__dict__["has_warned"] + + if _get_always_warn_typed_storage_removal() or is_first_time(): + message = ( + "TypedStorage is deprecated. It will be removed in the future and " + "UntypedStorage will be the only storage class. This should only matter " + "to you if you are using storages directly. To access UntypedStorage " + "directly, use tensor.untyped_storage() instead of tensor.storage()" + ) + warnings.warn(message, UserWarning, stacklevel=stacklevel + 1) + _warn_typed_storage_removal.__dict__["has_warned"] = True + + +def _reset_warn_typed_storage_removal(): + _warn_typed_storage_removal.__dict__["has_warned"] = False + + +def _get_device_from_module(module: str): + last_part = module.rsplit(".", 1)[-1] + if last_part in ["cuda", torch._C._get_privateuse1_backend_name(), "hpu"]: + return last_part + else: + return "cpu" + + +class TypedStorage: + is_sparse: _bool = False + # Used when stashing FakeTensor device onto storage in torch.save(metadata_only=True) + _fake_device: torch.device | None = None + + dtype: torch.dtype + + @property + def _dtype(self): + return self.dtype + + @property + def filename(self) -> str | None: + """Returns the file name associated with this storage if the storage was memory mapped from a file. + or ``None`` if the storage was not created by memory mapping a file.""" + return self._untyped_storage.filename + + def fill_(self, value): + _warn_typed_storage_removal() + self._setitem(slice(0, self._size()), value) + return self + + def __new__( + cls, + *args, + wrap_storage=None, + dtype=None, + device=None, + _internal=False, + ): + if not _internal: + _warn_typed_storage_removal() + + if cls == torch.storage._LegacyStorage: + raise RuntimeError( + "Only child classes of _LegacyStorage can be instantiated" + ) + + if cls == TypedStorage: + return super().__new__(cls) + + else: + arg_error_msg = ( + f"{cls}.__new__ received an invalid combination " + f"of arguments. Expected one of:\n" + " * no arguments\n" + " * (int size)\n" + " * (Sequence data)\n" + " * (*, UntypedStorage wrap_storage)" + ) + + if device is not None: + raise RuntimeError( + arg_error_msg + "\nKeyword argument 'device' cannot be specified" + ) + + if dtype is not None: + raise RuntimeError( + arg_error_msg + "\nKeyword argument 'dtype' cannot be specified" + ) + + if wrap_storage is None: + if len(args) > 1: + raise RuntimeError( + arg_error_msg + "\nToo many positional arguments" + ) + + if ( + len(args) == 1 + and not _isint(args[0]) + and not isinstance(args[0], collections.abc.Sequence) + ): + raise TypeError( + arg_error_msg + + f"\nArgument type not recognized: {type(args[0])}" + ) + + return TypedStorage( + *args, + dtype=cls._dtype, + device=_get_device_from_module(cls.__module__), + _internal=True, + ) + + else: + if len(args) != 0: + raise RuntimeError( + arg_error_msg + + "\nNo positional arguments should be given when using " + "'wrap_storage'" + ) + + if not isinstance(wrap_storage, torch.UntypedStorage): + raise TypeError( + arg_error_msg + + f"\nArgument 'wrap_storage' must be UntypedStorage, but got {type(wrap_storage)}" + ) + + cls_device = _get_device_from_module(cls.__module__) + + if wrap_storage.device.type != cls_device: + raise RuntimeError( + arg_error_msg + + f"\nDevice of 'wrap_storage' must be {cls_device}" + f", but got {wrap_storage.device.type}" + ) + + return TypedStorage( + *args, + wrap_storage=wrap_storage, + dtype=cls.dtype, + _internal=True, + ) + + def __init__( + self, + *args, + device=None, + dtype=None, + wrap_storage=None, + _internal=False, + ): + if not _internal: + _warn_typed_storage_removal() + arg_error_msg = ( + "TypedStorage.__init__ received an invalid combination " + "of arguments. Expected one of:\n" + " * (*, torch.device device, torch.dtype dtype)\n" + " * (int size, *, torch.device device, torch.dtype dtype)\n" + " * (Sequence data, *, torch.device device, torch.dtype dtype)\n" + " * (*, UntypedStorage wrap_storage, torch.dtype dtype)" + ) + + if wrap_storage is not None: + if len(args) != 0: + raise RuntimeError( + arg_error_msg + + "\nNo positional arguments should be given when using " + "'wrap_storage'" + ) + + if dtype is None: + raise RuntimeError( + arg_error_msg + "\nArgument 'dtype' must be specified" + ) + + if not isinstance(dtype, torch.dtype): + raise TypeError( + arg_error_msg + + f"\nArgument 'dtype' must be torch.dtype, not {type(dtype)}" + ) + + if device is not None: + raise RuntimeError( + arg_error_msg + + "\nArgument 'device' should not be specified when 'wrap_storage' is given" + ) + + self.dtype = dtype + + if not isinstance(wrap_storage, torch.UntypedStorage): + raise TypeError( + arg_error_msg + + f"\nArgument 'wrap_storage' must be UntypedStorage, but got {type(wrap_storage)}" + ) + + self._untyped_storage = wrap_storage + + else: + self.dtype = torch.get_default_dtype() if dtype is None else dtype + device = torch.device("cpu" if device is None else device) + + if self.dtype in [ + torch.quint8, + torch.quint4x2, + torch.quint2x4, + torch.qint32, + torch.qint8, + ]: + if device.type == "cuda": + raise RuntimeError( + "Cannot create CUDA storage with quantized dtype" + ) + + if len(args) == 0: + self._untyped_storage = torch.UntypedStorage(device=device) + + elif len(args) == 1: + if _isint(args[0]): + self._untyped_storage = torch.UntypedStorage( + int(args[0]) * self._element_size(), device=device + ) + elif isinstance(args[0], collections.abc.Sequence): + self._untyped_storage = _get_storage_from_sequence( + args[0], self.dtype, device + ) + else: + raise TypeError( + arg_error_msg + + f"\nArgument type not recognized: {type(args[0])}" + ) + + else: + raise RuntimeError(arg_error_msg + "\nToo many positional arguments") + + @property + def is_cuda(self): + _warn_typed_storage_removal() + return self._untyped_storage.device.type == "cuda" + + @property + def is_hpu(self): + _warn_typed_storage_removal() + return self._untyped_storage.device.type == "hpu" + + def untyped(self): + """Return the internal :class:`torch.UntypedStorage`.""" + _warn_typed_storage_removal() + return self._untyped_storage + + def _new_wrapped_storage(self, untyped_storage) -> Self: + assert type(untyped_storage) is torch.UntypedStorage + + if type(self) is TypedStorage: + return cast( + Self, + TypedStorage( + wrap_storage=untyped_storage, dtype=self.dtype, _internal=True + ), + ) + else: + return type(self)(wrap_storage=untyped_storage) + + def __len__(self): + _warn_typed_storage_removal() + return self._size() + + def _maybe_wrap_index(self, idx, is_stop=False): + if idx is None: + if is_stop: + return self._size() + else: + return 0 + + else: + if type(idx) is not int: + raise TypeError(f"can't index a {type(self)} with {type(idx)}") + if is_stop: + if (idx > self._size()) or (idx < -self._size()): + raise IndexError( + f"index {idx} out of range for storage of size {self.size()}" + ) + if idx > 0: + return idx + else: + return idx % self._size() + else: + if (idx >= self._size()) or (idx < -self._size()): + raise IndexError( + f"index {idx} out of range for storage of size {self.size()}" + ) + return idx % self._size() + + def __setitem__(self, idx, value): + _warn_typed_storage_removal() + return self._setitem(idx, value) + + def _setitem(self, idx, value): + if not isinstance(idx, (int, slice)): + raise RuntimeError(f"can't index a {type(self)} with {type(idx)}") + if torch.is_storage(value): + raise RuntimeError(f"cannot set item with value type {type(value)}") + if self.dtype in [ + torch.quint8, + torch.quint4x2, + torch.quint2x4, + torch.qint32, + torch.qint8, + ]: + interpret_dtypes = { + torch.quint8: torch.uint8, + torch.quint4x2: torch.uint8, + torch.quint2x4: torch.uint8, + torch.qint32: torch.int32, + torch.qint8: torch.int8, + } + tmp_dtype = interpret_dtypes[self.dtype] + tmp_tensor = torch.tensor( + [], dtype=tmp_dtype, device=self._untyped_storage.device + ) + tmp_tensor.set_( + TypedStorage( + wrap_storage=self._untyped_storage, dtype=tmp_dtype, _internal=True + ) + ) + else: + tmp_tensor = torch.tensor( + [], dtype=self.dtype, device=self._untyped_storage.device + ).set_(self) + + tmp_tensor[idx] = value + + def __getitem__(self, idx): + _warn_typed_storage_removal() + return self._getitem(idx) + + def _getitem(self, idx): + if self._untyped_storage.device.type == "meta": + raise NotImplementedError("Not available for 'meta' device type") + + # NOTE: Before TypedStorage existed, indexing with a slice used to be + # possible for Storage objects. However, it would return + # a storage view, which would be a hassle to implement in TypedStorage, + # so it was disabled + if isinstance(idx, slice): + raise RuntimeError( + "slices are only supported in UntypedStorage.__getitem__" + ) + elif not isinstance(idx, int): + raise RuntimeError(f"can't index a {type(self)} with {type(idx)}") + + if self.dtype in [ + torch.quint8, + torch.quint4x2, + torch.quint2x4, + torch.qint32, + torch.qint8, + ]: + interpret_dtypes = { + torch.quint8: torch.uint8, + torch.quint4x2: torch.uint8, + torch.quint2x4: torch.uint8, + torch.qint32: torch.int32, + torch.qint8: torch.int8, + } + return TypedStorage( + wrap_storage=self._untyped_storage, + dtype=interpret_dtypes[self.dtype], + _internal=True, + )._getitem(idx) + + idx_wrapped = self._maybe_wrap_index(idx) + from torch._subclasses.fake_tensor import unset_fake_temporarily + + with unset_fake_temporarily(): + tmp_tensor = torch.tensor( + [], dtype=self.dtype, device=self._untyped_storage.device + ).set_(self) + return tmp_tensor[idx_wrapped].item() + + def copy_(self, source: T, non_blocking: bool | None = None): + _warn_typed_storage_removal() + if isinstance(source, TypedStorage): + self._untyped_storage.copy_(source._untyped_storage, non_blocking) + else: + self._untyped_storage.copy_(source, non_blocking) + return self + + def nbytes(self): + _warn_typed_storage_removal() + return self._nbytes() + + # For internal use only, to avoid deprecation warning + def _nbytes(self): + return self._untyped_storage.nbytes() + + def type( + self, + dtype: str | None = None, + non_blocking: bool = False, + ) -> _StorageBase | TypedStorage | str: + _warn_typed_storage_removal() + if dtype is None: + legacy_class = self._get_legacy_storage_class() + + if legacy_class is not None: + return legacy_class.__module__ + "." + legacy_class.__name__ + + return ".".join([self.__module__, type(self).__name__]) + + else: + return self._untyped_storage.type(dtype, non_blocking) + + def cuda(self, device=None, non_blocking=False) -> Self: + _warn_typed_storage_removal() + if self.dtype in [ + torch.quint8, + torch.quint4x2, + torch.quint2x4, + torch.qint32, + torch.qint8, + ]: + raise RuntimeError("Cannot create CUDA storage with quantized dtype") + cuda_storage = self._untyped_storage.cuda(device, non_blocking) + return self._new_wrapped_storage(cuda_storage) + + def hpu(self, device=None, non_blocking=False) -> Self: + _warn_typed_storage_removal() + if self.dtype in [ + torch.quint8, + torch.quint4x2, + torch.quint2x4, + torch.qint32, + torch.qint8, + ]: + raise RuntimeError("Cannot create HPU storage with quantized dtype") + hpu_storage = self._untyped_storage.hpu(device, non_blocking) + return self._new_wrapped_storage(hpu_storage) + + def to(self, *, device: DeviceLikeType, non_blocking: bool = False) -> Self: + _warn_typed_storage_removal() + if not isinstance(device, torch.device): + device = torch.device(device) + if self.dtype in [ + torch.quint8, + torch.quint4x2, + torch.quint2x4, + torch.qint32, + torch.qint8, + ]: + raise RuntimeError( + f"Cannot create {device.type.upper()} storage with quantized dtype" + ) + to_storage = self._untyped_storage.to(device=device, non_blocking=non_blocking) + return self._new_wrapped_storage(to_storage) + + def element_size(self): + _warn_typed_storage_removal() + return self._element_size() + + # For internal use only, to avoid deprecation warning + def _element_size(self): + return torch._utils._element_size(self.dtype) + + def get_device(self) -> _int: + _warn_typed_storage_removal() + return self._untyped_storage.get_device() + + def __str__(self): + _warn_typed_storage_removal() + info_str = ( + f"[{torch.typename(self)}(dtype={self.dtype}, " + f"device={self.device}) of size {len(self)}]" + ) + if self.device.type == "meta": + return "...\n" + info_str + else: + data_str = " " + "\n ".join(str(self[i]) for i in range(self.size())) + return data_str + "\n" + info_str + + def __repr__(self): + _warn_typed_storage_removal() + return str(self) + + def __iter__(self): + _warn_typed_storage_removal() + return iter(self[i] for i in range(self.size())) + + def __copy__(self): + _warn_typed_storage_removal() + return self._new_wrapped_storage(copy.copy(self._untyped_storage)) + + def __deepcopy__(self, memo): + _warn_typed_storage_removal() + return self._deepcopy(memo) + + # For internal use only, to avoid deprecation warning + def _deepcopy(self, memo): + return self._new_wrapped_storage(copy.deepcopy(self._untyped_storage, memo)) + + def __sizeof__(self): + _warn_typed_storage_removal() + return super().__sizeof__() + self.nbytes() + + def clone(self): + """Return a copy of this storage.""" + _warn_typed_storage_removal() + return self._new_wrapped_storage(self._untyped_storage.clone()) + + def tolist(self): + """Return a list containing the elements of this storage.""" + _warn_typed_storage_removal() + return list(self) + + def cpu(self): + """Return a CPU copy of this storage if it's not already on the CPU.""" + _warn_typed_storage_removal() + return self._new_wrapped_storage(self._untyped_storage.cpu()) + + def is_pinned(self, device: str | torch.device = "cuda"): + r"""Determine whether the CPU TypedStorage is already pinned on device. + + Args: + device (str or torch.device): The device to pin memory on (default: ``'cuda'``). + This argument is discouraged and subject to deprecated. + + Returns: + A boolean variable. + """ + _warn_typed_storage_removal() + return self._untyped_storage.is_pinned(device) + + def pin_memory(self, device: str | torch.device = "cuda"): + r"""Copy the CPU TypedStorage to pinned memory, if it's not already pinned. + + Args: + device (str or torch.device): The device to pin memory on (default: ``'cuda'``). + This argument is discouraged and subject to deprecated. + + Returns: + A pinned CPU storage. + """ + _warn_typed_storage_removal() + return self._new_wrapped_storage( + self._untyped_storage.pin_memory(device=device) + ) + + def share_memory_(self): + """See :meth:`torch.UntypedStorage.share_memory_`""" + _warn_typed_storage_removal() + return self._share_memory_() + + # For internal use only, to avoid deprecation warning + def _share_memory_(self): + self._untyped_storage.share_memory_() + return self + + def _new_shared(self, size, *, device=None): + """Create a new storage in shared memory with the same data type.""" + if device is None: + device = "cpu" + device = torch.device(device) + untyped_storage = torch.UntypedStorage._new_shared( + size * self._element_size(), device=device + ) + return TypedStorage( + wrap_storage=untyped_storage, dtype=self.dtype, _internal=True + ) + + @property + def _cdata(self): + return self._untyped_storage._cdata + + @property + def device(self): + _warn_typed_storage_removal() + return self._untyped_storage.device + + def size(self): + _warn_typed_storage_removal() + return self._size() + + # For internal use only, to avoid deprecation warning + def _size(self): + # NB: don't indirect through __len__, as that requires + # an int to be returned + return self._untyped_storage.nbytes() // self._element_size() + + def pickle_storage_type(self): + _warn_typed_storage_removal() + return self._pickle_storage_type() + + # For internal use only, to avoid deprecation warning + def _pickle_storage_type(self): + try: + return _dtype_to_storage_type_map()[self.dtype] + except KeyError as e: + raise KeyError(f"dtype {self.dtype} is not recognized") from e + + def __reduce__(self): + b = io.BytesIO() + torch.save(self, b, _use_new_zipfile_serialization=False) + return (_load_from_bytes, (b.getvalue(),)) + + def data_ptr(self): + _warn_typed_storage_removal() + return self._data_ptr() + + # For internal use only, to avoid deprecation warning + def _data_ptr(self): + return self._untyped_storage.data_ptr() + + def resizable(self): + _warn_typed_storage_removal() + return self._untyped_storage.resizable() + + def resize_(self, size): + _warn_typed_storage_removal() + self._resize_(size) + + # For internal use only, to avoid deprecation warning + def _resize_(self, size): + self._untyped_storage.resize_(size * self._element_size()) + + @classmethod + def _free_weak_ref(cls, *args, **kwargs): + return UntypedStorage._free_weak_ref(*args, **kwargs) + + def _weak_ref(self, *args, **kwargs): + return self._untyped_storage._weak_ref(*args, **kwargs) + + @classmethod + def from_buffer(cls, *args, **kwargs): + _warn_typed_storage_removal() + return cls._from_buffer(*args, **kwargs) + + @classmethod + def _from_buffer(cls, *args, dtype=None, device=None, **kwargs): + if cls == TypedStorage: + dtype = torch.get_default_dtype() if dtype is None else dtype + device = torch.device("cpu" if device is None else device) + if device.type != "cpu": + raise RuntimeError( + f"TypedStorage.from_buffer: Not available for device {device.type}" + ) + untyped_storage: torch.UntypedStorage = torch.UntypedStorage.from_buffer( + *args, dtype=dtype, **kwargs + ) + + else: + if dtype is not None or len(args) == 5: + raise RuntimeError( + "from_buffer: 'dtype' can only be specified in " + "UntypedStorage.from_buffer and TypedStorage.from_buffer" + ) + if device is not None: + raise RuntimeError( + "from_buffer: 'device' can only be specified in " + "UntypedStorage.from_buffer and TypedStorage.from_buffer" + ) + + dtype = cls._dtype + untyped_storage = torch.UntypedStorage.from_buffer( + *args, dtype=dtype, **kwargs + ) + + return TypedStorage(wrap_storage=untyped_storage, dtype=dtype, _internal=True) + + def _to(self, dtype): + if not isinstance(dtype, torch.dtype): + raise TypeError(f"Argument 'dtype' must be torch.dtype, not {type(dtype)}") + storage = ( + torch.tensor([], dtype=self.dtype, device=self.device) + .set_(self) + .to(dtype) + ._typed_storage() + ) + if storage.data_ptr() == self.data_ptr(): + storage = storage.clone() + return storage + + def double(self): + """Casts this storage to double type.""" + _warn_typed_storage_removal() + return self._to(torch.double) + + def float(self): + """Casts this storage to float type.""" + _warn_typed_storage_removal() + return self._to(torch.float) + + def half(self): + """Casts this storage to half type.""" + _warn_typed_storage_removal() + return self._to(torch.half) + + def long(self): + """Casts this storage to long type.""" + _warn_typed_storage_removal() + return self._to(torch.long) + + def int(self): + """Casts this storage to int type.""" + _warn_typed_storage_removal() + return self._to(torch.int) + + def short(self): + """Casts this storage to short type.""" + _warn_typed_storage_removal() + return self._to(torch.short) + + def char(self): + """Casts this storage to char type.""" + _warn_typed_storage_removal() + return self._to(torch.int8) + + def byte(self): + """Casts this storage to byte type.""" + _warn_typed_storage_removal() + return self._to(torch.uint8) + + def bool(self): + """Casts this storage to bool type.""" + _warn_typed_storage_removal() + return self._to(torch.bool) + + def bfloat16(self): + """Casts this storage to bfloat16 type.""" + _warn_typed_storage_removal() + return self._to(torch.bfloat16) + + def complex_double(self): + """Casts this storage to complex double type.""" + _warn_typed_storage_removal() + return self._to(torch.cdouble) + + def complex_float(self): + """Casts this storage to complex float type.""" + _warn_typed_storage_removal() + return self._to(torch.cfloat) + + def float8_e5m2(self): + """Casts this storage to float8_e5m2 type""" + _warn_typed_storage_removal() + return self._to(torch.float8_e5m2) + + def float8_e4m3fn(self): + """Casts this storage to float8_e4m3fn type""" + _warn_typed_storage_removal() + return self._to(torch.float8_e4m3fn) + + def float8_e5m2fnuz(self): + """Casts this storage to float8_e5m2fnuz type""" + _warn_typed_storage_removal() + return self._to(torch.float8_e5m2fnuz) + + def float8_e4m3fnuz(self): + """Casts this storage to float8_e4m3fnuz type""" + _warn_typed_storage_removal() + return self._to(torch.float8_e4m3fnuz) + + @classmethod + def from_file(cls, filename, shared, size): + """from_file(filename, shared=False, size=0) -> Storage + + Creates a CPU storage backed by a memory-mapped file. + + If ``shared`` is ``True``, then memory is shared between all processes. + All changes are written to the file. If ``shared`` is ``False``, then the changes on + the storage do not affect the file. + + ``size`` is the number of elements in the storage. If ``shared`` is ``False``, + then the file must contain at least ``size * sizeof(Type)`` bytes + (``Type`` is the type of storage). If ``shared`` is ``True`` the file will be created if needed. + + Args: + filename (str): file name to map + shared (bool): whether to share memory (whether ``MAP_SHARED`` or ``MAP_PRIVATE`` is passed to the + underlying `mmap(2) call `_) + size (int): number of elements in the storage + """ + _warn_typed_storage_removal() + if cls == TypedStorage: + raise RuntimeError("from_file can only be called on derived classes") + untyped_storage = UntypedStorage.from_file( + filename, shared, size * torch._utils._element_size(cls.dtype) + ) + storage = cls(wrap_storage=untyped_storage) + return storage + + @classmethod + def _expired(cls, *args, **kwargs): + return UntypedStorage._expired(*args, **kwargs) + + def _write_file(self, *args, **kwargs): + return self._untyped_storage._write_file(*args, **kwargs) + + def _set_from_file(self, *args, **kwargs): + return self._untyped_storage._set_from_file(*args, **kwargs) + + def _set_cdata(self, *args, **kwargs): + return self._untyped_storage._set_cdata(*args, **kwargs) + + def _share_cuda_(self, *args, **kwargs): + return self._untyped_storage._share_cuda_(*args, **kwargs) + + def is_shared(self): + _warn_typed_storage_removal() + return self._is_shared() + + # For internal use only, to avoid deprecation warning + def _is_shared(self): + return self._untyped_storage.is_shared() + + @classmethod + def _new_shared_cuda(cls, *args, **kwargs): + return torch.UntypedStorage._new_shared_cuda(*args, **kwargs) + + def _share_filename_cpu_(self, *args, **kwargs): + ( + manager_handle, + storage_handle, + size, + ) = self._untyped_storage._share_filename_cpu_(*args, **kwargs) + return manager_handle, storage_handle, size // self._element_size() + + def _shared_decref(self): + self._untyped_storage._shared_decref() + return self + + @classmethod + def _release_ipc_counter(cls, *args, device=None, **kwargs): + return torch.UntypedStorage._release_ipc_counter_cuda(*args, **kwargs) + + def _shared_incref(self, *args, **kwargs): + return self._untyped_storage._shared_incref(*args, **kwargs) + + def _share_fd_cpu_(self, *args, **kwargs): + fd, size = self._untyped_storage._share_fd_cpu_(*args, **kwargs) + return fd, size // self._element_size() + + def _get_legacy_storage_class(self): + if self.dtype not in _dtype_to_storage_type_map(): + return None + + storage_name = _dtype_to_storage_type_map()[self.dtype] + + if self.device.type not in [ + "cpu", + "cuda", + "hpu", + torch._C._get_privateuse1_backend_name(), + ]: + return None + + module = ( + torch if self.device.type == "cpu" else getattr(torch, self.device.type) + ) + + try: + return getattr(module, storage_name) + except AttributeError: + return None + + +TypedStorage.type.__doc__ = _type.__doc__ +TypedStorage.cuda.__doc__ = _StorageBase.cuda.__doc__ +TypedStorage.hpu.__doc__ = _StorageBase.hpu.__doc__ +TypedStorage.to.__doc__ = _to.__doc__ + + +class _LegacyStorageMeta(type): + dtype: torch.dtype + + def __instancecheck__(cls, instance): + if type(instance) is TypedStorage: + cls_device = _get_device_from_module(cls.__module__) + return (cls_device == instance.device.type) and ( + cls.dtype == instance.dtype + ) + return False + + +class _LegacyStorage(TypedStorage, metaclass=_LegacyStorageMeta): + @classmethod + def _new_shared(cls, size): # type: ignore[override] + """Create a new storage in shared memory with the same data type.""" + untyped_storage = torch.UntypedStorage._new_shared(size * cls()._element_size()) + return cls(wrap_storage=untyped_storage) + + @classmethod + def _release_ipc_counter(cls, *args, **kwargs): + return torch.UntypedStorage._release_ipc_counter_cuda(*args, **kwargs) + + @classmethod + def _new_shared_filename(cls, manager, obj, size): + bytes_size = size * torch._utils._element_size(cls.dtype) + return cls( + wrap_storage=torch.UntypedStorage._new_shared_filename_cpu( + manager, obj, bytes_size + ) + ) + + +def _get_dtype_from_pickle_storage_type(pickle_storage_type: str): + try: + return _storage_type_to_dtype_map()[pickle_storage_type] + except KeyError as e: + raise KeyError( + f'pickle storage type "{pickle_storage_type}" is not recognized' + ) from e diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/torch_version.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/torch_version.py new file mode 100644 index 0000000000000000000000000000000000000000..0496a1b564feefe4a52280e2d7f268516f256a70 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/torch_version.py @@ -0,0 +1,66 @@ +from collections.abc import Iterable +from typing import Any + +from torch._vendor.packaging.version import InvalidVersion, Version +from torch.version import __version__ as internal_version + + +__all__ = ["TorchVersion"] + + +class TorchVersion(str): + """A string with magic powers to compare to both Version and iterables! + Prior to 1.10.0 torch.__version__ was stored as a str and so many did + comparisons against torch.__version__ as if it were a str. In order to not + break them we have TorchVersion which masquerades as a str while also + having the ability to compare against both packaging.version.Version as + well as tuples of values, eg. (1, 2, 1) + Examples: + Comparing a TorchVersion object to a Version object + TorchVersion('1.10.0a') > Version('1.10.0a') + Comparing a TorchVersion object to a Tuple object + TorchVersion('1.10.0a') > (1, 2) # 1.2 + TorchVersion('1.10.0a') > (1, 2, 1) # 1.2.1 + Comparing a TorchVersion object against a string + TorchVersion('1.10.0a') > '1.2' + TorchVersion('1.10.0a') > '1.2.1' + """ + + __slots__ = () + + # fully qualified type names here to appease mypy + def _convert_to_version(self, inp: Any) -> Any: + if isinstance(inp, Version): + return inp + elif isinstance(inp, str): + return Version(inp) + elif isinstance(inp, Iterable): + # Ideally this should work for most cases by attempting to group + # the version tuple, assuming the tuple looks (MAJOR, MINOR, ?PATCH) + # Examples: + # * (1) -> Version("1") + # * (1, 20) -> Version("1.20") + # * (1, 20, 1) -> Version("1.20.1") + return Version(".".join(str(item) for item in inp)) + else: + raise InvalidVersion(inp) + + def _cmp_wrapper(self, cmp: Any, method: str) -> bool: + try: + return getattr(Version(self), method)(self._convert_to_version(cmp)) + except BaseException as e: + if not isinstance(e, InvalidVersion): + raise + # Fall back to regular string comparison if dealing with an invalid + # version like 'parrot' + return getattr(super(), method)(cmp) + + +for cmp_method in ["__gt__", "__lt__", "__eq__", "__ge__", "__le__"]: + setattr( + TorchVersion, + cmp_method, + lambda x, y, method=cmp_method: x._cmp_wrapper(y, method), + ) + +__version__ = TorchVersion(internal_version) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/types.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/types.py new file mode 100644 index 0000000000000000000000000000000000000000..9ed69a859b1ee46781ea11f4000082316939bdbd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/types.py @@ -0,0 +1,130 @@ +# In some cases, these basic types are shadowed by corresponding +# top-level values. The underscore variants let us refer to these +# types. See https://github.com/python/mypy/issues/4146 for why these +# workarounds is necessary +import os +from builtins import ( # noqa: F401 + bool as _bool, + bytes as _bytes, + complex as _complex, + float as _float, + int as _int, + str as _str, +) +from collections.abc import Sequence +from typing import Any, IO, TYPE_CHECKING, TypeAlias, Union +from typing_extensions import Self + +# `as` imports have better static analysis support than assignment `ExposedType: TypeAlias = HiddenType` +from torch import ( # noqa: F401 + device as _device, + DispatchKey, + dtype as _dtype, + layout as _layout, + qscheme as _qscheme, + Size, + SymBool, + SymFloat, + SymInt, + Tensor, +) + + +if TYPE_CHECKING: + from torch.autograd.graph import GradientEdge + + +__all__ = ["Number", "Device", "FileLike", "Storage"] + +# Convenience aliases for common composite types that we need +# to talk about in PyTorch +_TensorOrTensors: TypeAlias = Tensor | Sequence[Tensor] # noqa: PYI047 +_TensorOrTensorsOrGradEdge: TypeAlias = Union[ # noqa: PYI047 + Tensor, + Sequence[Tensor], + "GradientEdge", + Sequence["GradientEdge"], +] + +_size: TypeAlias = Size | list[int] | tuple[int, ...] # noqa: PYI042,PYI047 +_symsize: TypeAlias = Size | Sequence[int | SymInt] # noqa: PYI042,PYI047 +_dispatchkey: TypeAlias = str | DispatchKey # noqa: PYI042,PYI047 + +# int or SymInt +IntLikeType: TypeAlias = int | SymInt +# float or SymFloat +FloatLikeType: TypeAlias = float | SymFloat +# bool or SymBool +BoolLikeType: TypeAlias = bool | SymBool + +py_sym_types = (SymInt, SymFloat, SymBool) # left un-annotated intentionally +PySymType: TypeAlias = SymInt | SymFloat | SymBool + +# Meta-type for "numeric" things; matches our docs +Number: TypeAlias = int | float | bool +# tuple for isinstance(x, Number) checks. +# FIXME: refactor once python 3.9 support is dropped. +_Number = (int, float, bool) + +FileLike: TypeAlias = str | os.PathLike[str] | IO[bytes] + +# Meta-type for "device-like" things. Not to be confused with 'device' (a +# literal device object). This nomenclature is consistent with PythonArgParser. +# None means use the default device (typically CPU) +Device: TypeAlias = _device | str | int | None + + +# Storage protocol implemented by ${Type}StorageBase classes +class Storage: + _cdata: int + device: _device + dtype: _dtype + _torch_load_uninitialized: bool + + def __deepcopy__(self, memo: dict[int, Any]) -> Self: + raise NotImplementedError + + def _new_shared(self, size: int) -> Self: + raise NotImplementedError + + def _write_file( + self, + f: Any, + is_real_file: bool, + save_size: bool, + element_size: int, + ) -> None: + raise NotImplementedError + + def element_size(self) -> int: + raise NotImplementedError + + def is_shared(self) -> bool: + raise NotImplementedError + + def share_memory_(self) -> Self: + raise NotImplementedError + + def nbytes(self) -> int: + raise NotImplementedError + + def cpu(self) -> Self: + raise NotImplementedError + + def data_ptr(self) -> int: + raise NotImplementedError + + def from_file( + self, + filename: str, + shared: bool = False, + nbytes: int = 0, + ) -> Self: + raise NotImplementedError + + def _new_with_file( + self, + f: Any, + element_size: int, + ) -> Self: + raise NotImplementedError diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/version.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/version.py new file mode 100644 index 0000000000000000000000000000000000000000..6b121072264a57cbc8ac632e67e8685aaa1b03dc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/version.py @@ -0,0 +1,10 @@ +from typing import Optional + +__all__ = ['__version__', 'debug', 'cuda', 'git_version', 'hip', 'rocm', 'xpu'] +__version__ = '2.10.0+cu128' +debug = False +cuda: Optional[str] = '12.8' +git_version = '449b1768410104d3ed79d3bcfe4ba1d65c7f22c0' +hip: Optional[str] = None +rocm: Optional[str] = None +xpu: Optional[str] = None